import { spawn } from"node:child_process";importtype { ChildProcess } from"node:child_process";import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from"node:fs";import { tmpdir } from"node:os";import { join } from"node:path";/** * The fake HTTP endpoint the hook scripts are driven against. * * THE FAKE SERVER IS A CHILD PROCESS, NOT AN IN-PROCESS `createServer`. The * scripts under test are driven with `execFileSync`, which blocks this * process's event loop for its whole run — an in-process server would never * get to answer, and every case would fail on curl's own timeout rather than * on anything the script did. * * It answers 200 with the next response in the list (repeating the last one * forever) whatever the method or path, so the same helper serves the MCP * endpoint and the fake usage endpoint. A response made by `throttled(n)` is * answered as a 429 carrying `Retry-After: n` — the server's rate ceiling. * * These live in `scripts/__tests__`, which `turbo test` structurally cannot * see — `pnpm test:scripts` is the run. */const SOURCE = `import { createServer } from "node:http";import { appendFileSync, readFileSync, writeFileSync } from "node:fs";const [portFile, logFile, responsesFile] = process.argv.slice(2);const responses = JSON.parse(readFileSync(responsesFile, "utf8"));let n = 0;const server = createServer((req, res) => { const chunks = []; req.on("data", (chunk) => chunks.push(chunk)); req.on("end", () => { appendFileSync(logFile, JSON.stringify(Buffer.concat(chunks).toString("utf8")) + "\\n"); let body = responses[Math.min(n, responses.length - 1)]; n += 1; let status = 200; const headers = { "content-type": "application/json" }; const throttle = /^\\u0001429 (\\d+)\\u0001/.exec(body); if (throttle) { status = 429; headers["retry-after"] = throttle[1]; body = body.slice(throttle[0].length); } res.writeHead(status, headers); res.end(body); });});server.listen(0, "127.0.0.1", () => { writeFileSync(portFile, String(server.address().port));});`;exportfunction envelope(payload: Record<string, unknown>): string {return JSON.stringify({ jsonrpc: "2.0", id: 1, result: { content: [{ type: "text", text: JSON.stringify(payload) }] }, });}/** What the server answers when a tool refuses — e.g. a session that has * never logged a turn, which `resolveCaller` will not invent a row for. */exportfunction refusal(text: string): string {return JSON.stringify({ jsonrpc: "2.0", id: 1, result: { isError: true, content: [{ type: "text", text }] }, });}/** A 429 carrying `Retry-After: <seconds>`, the way the real server refuses a loop. */exportfunction throttled(retryAfterSeconds: number): string {return`\u0001429 ${retryAfterSeconds}\u0001` + JSON.stringify({ error: "too many MCP calls this hour — retry shortly", code: "rate_limited", retryAfterSeconds });}exportinterfaceFake { url: string;/** The server's scratch folder — removed by `killFakeServers`. */ dir: string; requests: () => number; bodies: () => string[];}const running: ChildProcess[] = [];/** Every server's scratch folder, removed with it: 157 were left in one Mac's * temp folder on 11 Oct 2026, one per server any suite ever started. */const folders: string[] = [];exportasyncfunction startFakeServer(responses: string[]): Promise<Fake> {const dir = mkdtempSync(join(tmpdir(), "cotton-fake-")); folders.push(dir);const scriptPath = join(dir, "server.mjs");const portFile = join(dir, "port");const logFile = join(dir, "requests.jsonl");const responsesFile = join(dir, "responses.json"); writeFileSync(scriptPath, SOURCE); writeFileSync(responsesFile, JSON.stringify(responses)); writeFileSync(logFile, "");const child = spawn(process.execPath, [scriptPath, portFile, logFile, responsesFile], { stdio: ["ignore", "ignore", "inherit"], }); running.push(child);let port = "";for (let attempt = 0; attempt < 400 && !port; attempt += 1) {awaitnewPromise((done) => setTimeout(done, 25));if (existsSync(portFile)) port = readFileSync(portFile, "utf8").trim(); }if (!port) thrownewError("the fake server never reported a port");const lines = (): string[] => readFileSync(logFile, "utf8") .split("\n") .filter((line) => line.length > 0);return { url: `http://127.0.0.1:${port}/v1/mcp`, dir, requests: () => lines().length, bodies: () => lines().map((line) => JSON.parse(line) as string), };}/** A port with nothing listening on it — the "server down" case. */exportasyncfunction deadFakeUrl(): Promise<string> {const fake = await startFakeServer(["{}"]); running.pop()?.kill("SIGKILL"); rmSync(fake.dir, { recursive: true, force: true }); folders.splice(folders.indexOf(fake.dir), 1);awaitnewPromise((done) => setTimeout(done, 100));return fake.url;}/** The scratch folders of the servers still running here — for the guard. */exportfunction fakeFolders(): string[] {return [...folders];}/** Stop every fake server this process started, and remove their folders. */exportfunction killFakeServers(): void {for (const child of running.splice(0)) child.kill("SIGKILL");for (const dir of folders.splice(0)) rmSync(dir, { recursive: true, force: true });}