Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

test(channel): add blind contract tests for the session records

Jack Rudenkocf4f78359065
diff --git a/packages/cli/src/channel/host-pid.contract.test.ts b/packages/cli/src/channel/host-pid.contract.test.ts
new file mode 100644
index 00000000..e6f1b424
--- /dev/null
+++ b/packages/cli/src/channel/host-pid.contract.test.ts
@@ -0,0 +1,174 @@
+// packages/cli/src/channel/host-pid.contract.test.ts
+/**
+ * Black-box contract tests for `hostPid`, `launcherPid` and `mcpPid` in spawn.json, against
+ * real entry points (design §3.5 "hostPid, computed once at startup"; §8.1 tests 9a, 9b).
+ * The unit cases of hostPidFrom live in parent-proof.contract.test.ts.
+ *
+ * The test process stands in for Claude Code. Three topologies:
+ * 9b test → `bun src/index.ts --mcp` (the compiled-binary branch)
+ * pair test → a launcher stand-in → `bun src/index.ts --mcp` (the launcher branch, no build)
+ * 9a test → `node bin/claudish.cjs --mcp` → bun dist (the npm install, for real)
+ *
+ * INFERRED: the npm launcher is `<package>/bin/claudish.cjs` and runs `<package>/dist/index.js`
+ * after `bun run build` (design §3.5 names `bin/claudish.cjs:112-114` and `dist/index.js`).
+ * 9a builds once when dist/index.js is missing, so it never silently skips.
+ */
+import { afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import {
+ McpServer,
+ PACKAGE_DIR,
+ SERVER_ENTRY,
+ createSession,
+ serverEnv,
+} from "../test-helpers/contract-mcp.js";
+import {
+ type TempLayout,
+ makeTempLayout,
+ pidAlive,
+ ppidOf,
+ spawnRecordViolations,
+} from "../test-helpers/contract-records.js";
+
+const T_TEST = 60_000;
+
+let layout: TempLayout;
+const servers: McpServer[] = [];
+
+beforeEach(() => {
+ layout = makeTempLayout("hostpid");
+});
+afterEach(async () => {
+ for (const s of servers.splice(0)) await s.close();
+ layout.cleanup();
+});
+
+async function spawnRecordVia(
+ command: string[] | undefined,
+ extraEnv: Record<string, string | undefined> = {}
+) {
+ const server = await McpServer.start({
+ env: serverEnv(layout, extraEnv),
+ cwd: layout.cwd,
+ command,
+ });
+ servers.push(server);
+ const { sessionId, result } = await createSession(server, {
+ prompt: "@@HANG@@ keep the writer busy",
+ });
+ expect(result.isError).toBe(false);
+ const text = readFileSync(join(layout.sessionsDir, sessionId as string, "spawn.json"), "utf8");
+ expect(spawnRecordViolations(text, sessionId as string)).toEqual([]);
+ return { server, rec: JSON.parse(text) as Record<string, unknown> };
+}
+
+describe("REQ-3 the compiled-binary branch (9b): claudish started directly by its host", () => {
+ test(
+ "hostPid is the test process, mcpPid is the spawned server, and there is no launcherPid",
+ async () => {
+ const { server, rec } = await spawnRecordVia(undefined);
+
+ expect({ hostPid: rec.hostPid, mcpPid: rec.mcpPid }).toEqual({
+ hostPid: process.pid,
+ mcpPid: server.pid,
+ });
+ expect("launcherPid" in rec).toBe(false);
+ },
+ T_TEST
+ );
+
+ test(
+ "a launcher pair leaked from an outer launcher is inert: same result as with no pair",
+ async () => {
+ const { server, rec } = await spawnRecordVia(undefined, {
+ // An OUTER launcher's pair: its pid is not this server's parent (the test process), so
+ // CLAUDISH_LAUNCHER_PID != ppid and the pair must be ignored (contract 3.5, hostPidFrom).
+ CLAUDISH_LAUNCHER_PID: String(process.ppid),
+ CLAUDISH_LAUNCHER_PPID: "1",
+ });
+
+ expect({ hostPid: rec.hostPid, mcpPid: rec.mcpPid }).toEqual({
+ hostPid: process.pid,
+ mcpPid: server.pid,
+ });
+ expect("launcherPid" in rec).toBe(false);
+ },
+ T_TEST
+ );
+});
+
+describe("REQ-3 the launcher branch: a launcher that passes its own pid pair", () => {
+ test(
+ "hostPid is the launcher's parent, launcherPid is the launcher, mcpPid is its child",
+ async () => {
+ const launcher = join(layout.root, "launcher-stand-in.ts");
+ writeFileSync(
+ launcher,
+ [
+ `const child = Bun.spawn([process.execPath, ${JSON.stringify(SERVER_ENTRY)}, "--mcp"], {`,
+ ` stdin: "inherit", stdout: "inherit", stderr: "inherit",`,
+ " env: { ...process.env, CLAUDISH_LAUNCHER_PID: String(process.pid), CLAUDISH_LAUNCHER_PPID: String(process.ppid) },",
+ "});",
+ `process.on("SIGTERM", () => { child.kill("SIGTERM"); });`,
+ "process.exitCode = await child.exited;",
+ "",
+ ].join("\n")
+ );
+
+ const { server, rec } = await spawnRecordVia([process.execPath, launcher]);
+ const mcpPid = rec.mcpPid as number;
+
+ expect({ hostPid: rec.hostPid, launcherPid: rec.launcherPid }).toEqual({
+ hostPid: process.pid,
+ launcherPid: server.pid,
+ });
+ expect(mcpPid).not.toBe(process.pid);
+ expect(mcpPid).not.toBe(server.pid);
+ expect(pidAlive(mcpPid)).toBe(true);
+ expect(ppidOf(mcpPid)).toBe(server.pid);
+ },
+ T_TEST
+ );
+});
+
+describe("REQ-3 the installed npm path for real (9a)", () => {
+ const launcherScript = join(PACKAGE_DIR, "bin", "claudish.cjs");
+ const distEntry = join(PACKAGE_DIR, "dist", "index.js");
+
+ beforeAll(() => {
+ if (!existsSync(distEntry)) {
+ const build = Bun.spawnSync(["bun", "run", "build"], {
+ cwd: PACKAGE_DIR,
+ stdout: "pipe",
+ stderr: "pipe",
+ });
+ if (build.exitCode !== 0)
+ throw new Error(
+ `9a needs a build and \`bun run build\` failed:\n${build.stderr.toString()}`
+ );
+ }
+ }, 180_000);
+
+ test(
+ "node bin/claudish.cjs --mcp: hostPid is the test process, launcherPid the node launcher, mcpPid the bun grandchild",
+ async () => {
+ const node = Bun.which("node");
+ if (!node) throw new Error("9a needs `node` on PATH");
+ if (!existsSync(launcherScript))
+ throw new Error(`9a: missing the npm launcher at ${launcherScript}`);
+
+ const { server, rec } = await spawnRecordVia([node as string, launcherScript, "--mcp"]);
+ const mcpPid = rec.mcpPid as number;
+
+ expect({ hostPid: rec.hostPid, launcherPid: rec.launcherPid }).toEqual({
+ hostPid: process.pid,
+ launcherPid: server.pid,
+ });
+ expect(mcpPid).not.toBe(process.pid);
+ expect(mcpPid).not.toBe(server.pid);
+ expect(ppidOf(mcpPid)).toBe(server.pid);
+ },
+ T_TEST
+ );
+});
diff --git a/packages/cli/src/channel/parent-proof.contract.test.ts b/packages/cli/src/channel/parent-proof.contract.test.ts
new file mode 100644
index 00000000..e94c6985
--- /dev/null
+++ b/packages/cli/src/channel/parent-proof.contract.test.ts
@@ -0,0 +1,558 @@
+// packages/cli/src/channel/parent-proof.contract.test.ts
+/**
+ * Black-box contract tests for channel/parent-proof.ts (design §3.5, §8.1 tests 9-10;
+ * amendments 1 and 5). Written from the specification only.
+ *
+ * Every proof runs over a synthetic Claude config dir in a temp directory. The retry wait is
+ * injected (`sleep`), so no test waits 250 ms for real. INFERRED: a `ProofCandidate` carries
+ * `{ sessionId, cwd? }` — the only place the host record's `cwd` can reach the proof, since
+ * `proveCallingConversation` takes no host-record argument. Built in `candidate()` only.
+ */
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { appendFileSync, mkdirSync, rmSync, utimesSync, writeFileSync } from "node:fs";
+import * as fsp from "node:fs/promises";
+import { homedir } from "node:os";
+import { join } from "node:path";
+import {
+ type TempLayout,
+ claudeId,
+ fillerLine,
+ makeTempLayout,
+ sanitisedProjectName,
+ transcriptLineWithToolUse,
+} from "../test-helpers/contract-records.js";
+import {
+ CLAUDE_ID_RE,
+ MAX_SUBAGENT_FILES,
+ PROOF_RETRY_DELAY_MS,
+ SUBAGENT_WINDOW_MS,
+ TOOL_USE_ID_META_KEY,
+ TRANSCRIPT_TAIL_BYTES,
+ claudeConfigDir,
+ hostPidFrom,
+ parentSessionIdFrom,
+ projectDirNameFor,
+ proveCallingConversation,
+ readHostSessionRecord,
+} from "./parent-proof.js";
+import type { ProofCandidate, ProofFs } from "./parent-proof.js";
+
+// INFERRED candidate shape (see header).
+function candidate(sessionId: string, cwd?: string): ProofCandidate {
+ return (cwd === undefined ? { sessionId } : { sessionId, cwd }) as unknown as ProofCandidate;
+}
+
+let layout: TempLayout;
+let sleeps: number[];
+const recordSleep = async (ms: number): Promise<void> => {
+ sleeps.push(ms);
+};
+
+beforeEach(() => {
+ layout = makeTempLayout("proof");
+ sleeps = [];
+});
+afterEach(() => layout.cleanup());
+
+const projectsDir = () => join(layout.configDir, "projects");
+
+function writeMainTranscript(project: string, sessionId: string, content: string): string {
+ const dir = join(projectsDir(), project);
+ mkdirSync(dir, { recursive: true });
+ const path = join(dir, `${sessionId}.jsonl`);
+ writeFileSync(path, content);
+ return path;
+}
+
+function writeSubagentTranscript(
+ project: string,
+ parent: string,
+ name: string,
+ content: string,
+ mtimeMs?: number
+): string {
+ const dir = join(projectsDir(), project, parent, "subagents");
+ mkdirSync(dir, { recursive: true });
+ const path = join(dir, name);
+ writeFileSync(path, content);
+ if (mtimeMs !== undefined) utimesSync(path, mtimeMs / 1000, mtimeMs / 1000);
+ return path;
+}
+
+/** Wrap every node:fs/promises function so the test can see what the proof touched. */
+function countingFs(): { fs: ProofFs; calls: Array<{ method: string; path: string }> } {
+ const calls: Array<{ method: string; path: string }> = [];
+ const wrapped: Record<string, unknown> = {};
+ for (const [name, value] of Object.entries(fsp)) {
+ wrapped[name] =
+ typeof value === "function"
+ ? (...args: unknown[]) => {
+ calls.push({ method: name, path: String(args[0]) });
+ return (value as (...a: unknown[]) => unknown).apply(fsp, args);
+ }
+ : value;
+ }
+ return { fs: wrapped as unknown as ProofFs, calls };
+}
+
+const toolUseId = () => `toolu_contract_${crypto.randomUUID().replaceAll("-", "")}`;
+
+describe("REQ-4 constants named by the contract carry the spec's values", () => {
+ test("TOOL_USE_ID_META_KEY is the _meta key the dispatcher reads", () => {
+ expect(TOOL_USE_ID_META_KEY).toBe("claudecode/toolUseId");
+ });
+
+ test("tail, subagent window, subagent cap and retry delay match §3.5", () => {
+ expect({
+ tail: TRANSCRIPT_TAIL_BYTES,
+ window: SUBAGENT_WINDOW_MS,
+ cap: MAX_SUBAGENT_FILES,
+ retry: PROOF_RETRY_DELAY_MS,
+ }).toEqual({ tail: 256 * 1024, window: 10 * 60 * 1000, cap: 32, retry: 250 });
+ });
+
+ test.each([
+ ["8 allowed chars", "abcd_-12", true],
+ ["128 chars", "a".repeat(128), true],
+ ["7 chars", "abcdefg", false],
+ ["129 chars", "a".repeat(129), false],
+ ["a space", "abcd efgh", false],
+ ["a dot", "abcd.efgh", false],
+ ["a slash", "abcd/efgh", false],
+ ])("CLAUDE_ID_RE with %s → %p", (_label, id, ok) => {
+ expect(CLAUDE_ID_RE.test(id)).toBe(ok);
+ });
+});
+
+describe("REQ-3 hostPidFrom(env, ppid) picks the launcher branch only on an exact pair (§8.1 test 9)", () => {
+ test("a matching launcher pair → hostPid is the launcher's parent, launcherPid is ppid", () => {
+ expect(
+ hostPidFrom({ CLAUDISH_LAUNCHER_PID: "5000", CLAUDISH_LAUNCHER_PPID: "4000" }, 5000)
+ ).toEqual({
+ hostPid: 4000,
+ launcherPid: 5000,
+ });
+ });
+
+ test.each([
+ [
+ "a pair whose CLAUDISH_LAUNCHER_PID is not ppid (leaked from an outer launcher)",
+ { CLAUDISH_LAUNCHER_PID: "5001", CLAUDISH_LAUNCHER_PPID: "4000" },
+ ],
+ ["no pair", {}],
+ ["only CLAUDISH_LAUNCHER_PID", { CLAUDISH_LAUNCHER_PID: "5000" }],
+ ["a non-integer PPID", { CLAUDISH_LAUNCHER_PID: "5000", CLAUDISH_LAUNCHER_PPID: "abc" }],
+ ["a fractional PPID", { CLAUDISH_LAUNCHER_PID: "5000", CLAUDISH_LAUNCHER_PPID: "12.5" }],
+ ["a zero PPID", { CLAUDISH_LAUNCHER_PID: "5000", CLAUDISH_LAUNCHER_PPID: "0" }],
+ ["a negative PPID", { CLAUDISH_LAUNCHER_PID: "5000", CLAUDISH_LAUNCHER_PPID: "-3" }],
+ ["an empty PPID", { CLAUDISH_LAUNCHER_PID: "5000", CLAUDISH_LAUNCHER_PPID: "" }],
+ ])("%s → { hostPid: ppid } with no launcherPid", (_label, env) => {
+ const result = hostPidFrom(env as Record<string, string>, 5000) as {
+ hostPid: number;
+ launcherPid?: number;
+ };
+
+ expect(result.hostPid).toBe(5000);
+ expect(result.launcherPid).toBeUndefined();
+ });
+});
+
+describe("REQ-4 parentSessionIdFrom(env): the env candidate (§3.5 step 2)", () => {
+ const good = "0f9e8d7c-1111-4222-8333-444455556666";
+
+ test.each([
+ ["a valid CLAUDE_CODE_SESSION_ID", { CLAUDE_CODE_SESSION_ID: good }, good],
+ [
+ "a valid id with an empty CLAUDE_CODE_CHILD_SESSION",
+ { CLAUDE_CODE_SESSION_ID: good, CLAUDE_CODE_CHILD_SESSION: "" },
+ good,
+ ],
+ [
+ "CLAUDE_CODE_CHILD_SESSION=1 (not started by Claude Code directly)",
+ { CLAUDE_CODE_SESSION_ID: good, CLAUDE_CODE_CHILD_SESSION: "1" },
+ undefined,
+ ],
+ ["no CLAUDE_CODE_SESSION_ID", {}, undefined],
+ ["an empty id", { CLAUDE_CODE_SESSION_ID: "" }, undefined],
+ ["a 7-char id", { CLAUDE_CODE_SESSION_ID: "abcdefg" }, undefined],
+ ["a 129-char id", { CLAUDE_CODE_SESSION_ID: "a".repeat(129) }, undefined],
+ ["an id with a space", { CLAUDE_CODE_SESSION_ID: "abcd efgh" }, undefined],
+ ])("%s → %p", (_label, env, expected) => {
+ expect(parentSessionIdFrom(env as Record<string, string>) ?? undefined).toBe(expected);
+ });
+});
+
+describe("REQ-4 readHostSessionRecord: the host's live session record (§3.5 step 2)", () => {
+ const hostPid = 424242;
+ const R = "host-record-session-0001";
+
+ function writeHostRecord(pid: number, body: string): void {
+ mkdirSync(join(layout.configDir, "sessions"), { recursive: true });
+ writeFileSync(join(layout.configDir, "sessions", `${pid}.json`), body);
+ }
+
+ test("a record whose pid equals hostPid and whose sessionId is valid is used, with its cwd", async () => {
+ writeHostRecord(
+ hostPid,
+ JSON.stringify({ pid: hostPid, sessionId: R, cwd: join(layout.root, "project") })
+ );
+
+ const record = await readHostSessionRecord({ configDir: layout.configDir, hostPid });
+
+ expect(record).toMatchObject({ sessionId: R, cwd: join(layout.root, "project") });
+ });
+
+ test.each([
+ ["its pid is not hostPid", () => JSON.stringify({ pid: hostPid + 1, sessionId: R })],
+ ["it is not valid JSON (a write in progress)", () => `{"pid": ${hostPid}, "sessionId": "${R}"`],
+ [
+ "its sessionId does not match the id pattern",
+ () => JSON.stringify({ pid: hostPid, sessionId: "short" }),
+ ],
+ ["it has no sessionId", () => JSON.stringify({ pid: hostPid })],
+ ])("returns nothing when %s", async (_label, body) => {
+ writeHostRecord(hostPid, body());
+
+ const record = await readHostSessionRecord({ configDir: layout.configDir, hostPid });
+
+ expect(record ?? undefined).toBeUndefined();
+ });
+
+ test("returns nothing when no record exists for hostPid", async () => {
+ const record = await readHostSessionRecord({ configDir: layout.configDir, hostPid });
+
+ expect(record ?? undefined).toBeUndefined();
+ });
+});
+
+describe("REQ-6 claudeConfigDir follows CLAUDE_CONFIG_DIR, then HOME, then the OS home (amendment 1)", () => {
+ function withEnv<T>(
+ vars: Record<string, string | undefined>,
+ fn: (env: Record<string, string | undefined>) => T
+ ): T {
+ const saved: Record<string, string | undefined> = {};
+ for (const k of Object.keys(vars)) saved[k] = process.env[k];
+ for (const [k, v] of Object.entries(vars)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+ try {
+ // INFERRED: claudeConfigDir(env?) — pass the env and set process.env, so either shape works.
+ return fn({ ...process.env });
+ } finally {
+ for (const [k, v] of Object.entries(saved)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+ }
+ }
+ const call = (env: Record<string, string | undefined>) =>
+ (claudeConfigDir as unknown as (e?: unknown) => string)(env);
+
+ test("CLAUDE_CONFIG_DIR wins when set", () => {
+ expect(withEnv({ CLAUDE_CONFIG_DIR: layout.configDir, HOME: layout.home }, call)).toBe(
+ layout.configDir
+ );
+ });
+
+ test("without CLAUDE_CONFIG_DIR it is $HOME/.claude", () => {
+ expect(withEnv({ CLAUDE_CONFIG_DIR: undefined, HOME: layout.home }, call)).toBe(
+ join(layout.home, ".claude")
+ );
+ });
+
+ test("with HOME empty it is the OS home directory's .claude", () => {
+ expect(withEnv({ CLAUDE_CONFIG_DIR: undefined, HOME: "" }, call)).toBe(
+ join(homedir(), ".claude")
+ );
+ });
+});
+
+describe("REQ-4 projectDirNameFor: every character outside [A-Za-z0-9] becomes '-'", () => {
+ test.each([
+ ["/Users/someone/.claude/worktrees/x", "-Users-someone--claude-worktrees-x"],
+ ["/srv/my_app v2.1", "-srv-my-app-v2-1"],
+ ])("%s → %s", (cwd, expected) => {
+ expect(projectDirNameFor(cwd)).toBe(expected);
+ });
+});
+
+describe("REQ-1/REQ-2/REQ-4 proveCallingConversation (§8.1 test 10)", () => {
+ test("returns the candidate whose main transcript holds the quoted tool-use id", async () => {
+ const E = claudeId("env");
+ const T = toolUseId();
+ writeMainTranscript("P", E, fillerLine(1) + transcriptLineWithToolUse(T) + fillerLine(2));
+
+ const parent = await proveCallingConversation({
+ toolUseId: T,
+ candidates: [candidate(E)],
+ configDir: layout.configDir,
+ sleep: recordSleep,
+ });
+
+ expect(parent).toBe(E);
+ expect(sleeps).toEqual([]);
+ });
+
+ test("returns the second candidate when the id is only in one of its fresh subagent transcripts", async () => {
+ const E = claudeId("env");
+ const R = claudeId("host");
+ const T = toolUseId();
+ writeMainTranscript("P", E, fillerLine(1));
+ writeMainTranscript("Q", R, fillerLine(2));
+ writeSubagentTranscript("Q", R, "a.jsonl", transcriptLineWithToolUse(T));
+
+ const parent = await proveCallingConversation({
+ toolUseId: T,
+ candidates: [candidate(E), candidate(R)],
+ configDir: layout.configDir,
+ sleep: recordSleep,
+ });
+
+ expect(parent).toBe(R);
+ });
+
+ test("skips a candidate with no transcript anywhere and proves the other", async () => {
+ const ghost = claudeId("ghost");
+ const E = claudeId("env");
+ const T = toolUseId();
+ writeMainTranscript("P", E, transcriptLineWithToolUse(T));
+
+ const parent = await proveCallingConversation({
+ toolUseId: T,
+ candidates: [candidate(ghost), candidate(E)],
+ configDir: layout.configDir,
+ sleep: recordSleep,
+ });
+
+ expect(parent).toBe(E);
+ });
+
+ test("returns undefined after exactly one 250 ms wait when no transcript holds the id", async () => {
+ const E = claudeId("env");
+ writeMainTranscript("P", E, fillerLine(1));
+
+ const parent = await proveCallingConversation({
+ toolUseId: toolUseId(),
+ candidates: [candidate(E)],
+ configDir: layout.configDir,
+ sleep: recordSleep,
+ });
+
+ expect(parent).toBeUndefined();
+ expect(sleeps).toEqual([250]);
+ });
+
+ test("finds an id appended to the transcript during the retry wait", async () => {
+ const E = claudeId("env");
+ const T = toolUseId();
+ const path = writeMainTranscript("P", E, fillerLine(1));
+ const appendDuringWait = async (ms: number) => {
+ sleeps.push(ms);
+ appendFileSync(path, transcriptLineWithToolUse(T));
+ };
+
+ const parent = await proveCallingConversation({
+ toolUseId: T,
+ candidates: [candidate(E)],
+ configDir: layout.configDir,
+ sleep: appendDuringWait,
+ });
+
+ expect(parent).toBe(E);
+ expect(sleeps).toEqual([250]);
+ });
+
+ test("ignores an id that occurs only before the last 256 KB of the main transcript", async () => {
+ const E = claudeId("env");
+ const T = toolUseId();
+ let padding = "";
+ for (let i = 0; padding.length < 300 * 1024; i++) padding += fillerLine(i);
+ writeMainTranscript("P", E, transcriptLineWithToolUse(T) + padding);
+
+ const parent = await proveCallingConversation({
+ toolUseId: T,
+ candidates: [candidate(E)],
+ configDir: layout.configDir,
+ sleep: recordSleep,
+ });
+
+ expect(parent).toBeUndefined();
+ });
+
+ test("finds an id that sits inside the last 256 KB of a transcript larger than 256 KB", async () => {
+ const E = claudeId("env");
+ const T = toolUseId();
+ let head = "";
+ for (let i = 0; head.length < 300 * 1024; i++) head += fillerLine(i);
+ let tail = "";
+ for (let i = 0; tail.length < 200 * 1024; i++) tail += fillerLine(i);
+ writeMainTranscript("P", E, head + transcriptLineWithToolUse(T) + tail);
+
+ const parent = await proveCallingConversation({
+ toolUseId: T,
+ candidates: [candidate(E)],
+ configDir: layout.configDir,
+ sleep: recordSleep,
+ });
+
+ expect(parent).toBe(E);
+ });
+
+ test("matches the quoted id exactly, not as a prefix of a longer id", async () => {
+ const E = claudeId("env");
+ const T = toolUseId();
+ writeMainTranscript("P", E, transcriptLineWithToolUse(`${T}extra`));
+
+ const parent = await proveCallingConversation({
+ toolUseId: T,
+ candidates: [candidate(E)],
+ configDir: layout.configDir,
+ sleep: recordSleep,
+ });
+
+ expect(parent).toBeUndefined();
+ });
+
+ test.each([
+ ["a 7-char id", "toolu_1"],
+ ["an id with a space", "toolu has space"],
+ ["an id with a quote", 'toolu_"quoted"'],
+ ["a 129-char id", `t${"a".repeat(128)}`],
+ ["an empty id", ""],
+ ["no id at all", undefined],
+ ])("%s → undefined, and no file is touched", async (_label, badId) => {
+ const E = claudeId("env");
+ writeMainTranscript("P", E, transcriptLineWithToolUse(String(badId)));
+ const { fs, calls } = countingFs();
+
+ const parent = await proveCallingConversation({
+ toolUseId: badId as string,
+ candidates: [candidate(E)],
+ configDir: layout.configDir,
+ fs,
+ sleep: recordSleep,
+ });
+
+ expect(parent).toBeUndefined();
+ expect(calls).toEqual([]);
+ });
+
+ test("ignores a subagent transcript last modified more than 10 minutes ago", async () => {
+ const R = claudeId("host");
+ const T = toolUseId();
+ writeMainTranscript("Q", R, fillerLine(1));
+ writeSubagentTranscript(
+ "Q",
+ R,
+ "old.jsonl",
+ transcriptLineWithToolUse(T),
+ Date.now() - 11 * 60 * 1000
+ );
+
+ const parent = await proveCallingConversation({
+ toolUseId: T,
+ candidates: [candidate(R)],
+ configDir: layout.configDir,
+ sleep: recordSleep,
+ });
+
+ expect(parent).toBeUndefined();
+ });
+
+ test.each([
+ [32, "found"],
+ [33, "not found"],
+ ])(
+ "with %i fresh subagent files and the id only in the oldest, it is %s (newest first, at most 32)",
+ async (count, outcome) => {
+ const R = claudeId("host");
+ const T = toolUseId();
+ writeMainTranscript("Q", R, fillerLine(1));
+ const now = Date.now();
+ for (let i = 0; i < count; i++) {
+ const isOldest = i === 0;
+ writeSubagentTranscript(
+ "Q",
+ R,
+ `s${String(i).padStart(2, "0")}.jsonl`,
+ isOldest ? transcriptLineWithToolUse(T) : fillerLine(i),
+ now - 5 * 60 * 1000 + i * 1000
+ );
+ }
+
+ const parent = await proveCallingConversation({
+ toolUseId: T,
+ candidates: [candidate(R)],
+ configDir: layout.configDir,
+ sleep: recordSleep,
+ });
+
+ expect(parent).toBe(outcome === "found" ? R : undefined);
+ }
+ );
+
+ test("fast path: a candidate with a cwd is found under the sanitised-cwd directory with no listing of projects/", async () => {
+ const R = claudeId("host");
+ const T = toolUseId();
+ const cwd = join(layout.root, "work tree", ".claude", "wt_1");
+ writeMainTranscript(sanitisedProjectName(cwd), R, transcriptLineWithToolUse(T));
+ writeMainTranscript("unrelated-project", claudeId("other"), fillerLine(1));
+ const { fs, calls } = countingFs();
+
+ const parent = await proveCallingConversation({
+ toolUseId: T,
+ candidates: [candidate(R, cwd)],
+ configDir: layout.configDir,
+ fs,
+ sleep: recordSleep,
+ });
+
+ expect(parent).toBe(R);
+ const listings = calls.filter(
+ (c) =>
+ (c.method === "readdir" || c.method === "opendir") &&
+ c.path.replace(/\/+$/, "") === projectsDir()
+ );
+ expect(listings).toEqual([]);
+ });
+
+ test("a cwd that maps to no directory falls back to listing projects/ and still finds the transcript", async () => {
+ const R = claudeId("host");
+ const T = toolUseId();
+ writeMainTranscript("renamed-by-a-future-claude-code", R, transcriptLineWithToolUse(T));
+
+ const parent = await proveCallingConversation({
+ toolUseId: T,
+ candidates: [candidate(R, join(layout.root, "no", "such", "project"))],
+ configDir: layout.configDir,
+ sleep: recordSleep,
+ });
+
+ expect(parent).toBe(R);
+ });
+
+ test("REQ-5 an unproven call caches no project directory: the next call finds the transcript where it now lives", async () => {
+ const C = claudeId("moving");
+ const stale = writeMainTranscript("P-stale", C, fillerLine(1));
+
+ const first = await proveCallingConversation({
+ toolUseId: toolUseId(),
+ candidates: [candidate(C)],
+ configDir: layout.configDir,
+ sleep: recordSleep,
+ });
+ rmSync(stale);
+ const T = toolUseId();
+ writeMainTranscript("Q-current", C, transcriptLineWithToolUse(T));
+ const second = await proveCallingConversation({
+ toolUseId: T,
+ candidates: [candidate(C)],
+ configDir: layout.configDir,
+ sleep: recordSleep,
+ });
+
+ expect(first).toBeUndefined();
+ expect(second).toBe(C);
+ });
+});
diff --git a/packages/cli/src/channel/session-state-records.contract.test.ts b/packages/cli/src/channel/session-state-records.contract.test.ts
new file mode 100644
index 00000000..13eed75e
--- /dev/null
+++ b/packages/cli/src/channel/session-state-records.contract.test.ts
@@ -0,0 +1,314 @@
+// packages/cli/src/channel/session-state-records.contract.test.ts
+/**
+ * Black-box contract tests for the state model as it reaches disk: `finishing`, and the wait
+ * log `waits.jsonl` (design §3.2, §3.3 "waits.jsonl"; §8.1 tests 1-4).
+ *
+ * Each test starts a real claudish MCP server (`bun src/index.ts --mcp`) over stdio with a
+ * temp CLAUDISH_SESSIONS_DIR, HOME and CLAUDE_CONFIG_DIR, and CLAUDISH_BIN pointing at the
+ * stream-json fake in test-helpers/contract-fake-child.ts. No model, no network.
+ *
+ * The records on disk are the primary evidence: `waits.jsonl` gains an `open` line on every
+ * transition into waiting_for_input, so its absence proves a session never waited.
+ * INFERRED: get_diagnostics reports the live state in a `status` field (adapter in contract-mcp.ts).
+ */
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync } from "node:fs";
+import { join } from "node:path";
+import {
+ McpServer,
+ createSession,
+ sendInput,
+ serverEnv,
+ sessionStatus,
+ sessionTool,
+} from "../test-helpers/contract-mcp.js";
+import {
+ type TempLayout,
+ makeTempLayout,
+ readJson,
+ readWaitLines,
+ waitFor,
+ waitPairingViolations,
+} from "../test-helpers/contract-records.js";
+
+const T_TEST = 30_000;
+
+let layout: TempLayout;
+let server: McpServer;
+
+beforeEach(async () => {
+ layout = makeTempLayout("state");
+ server = await McpServer.start({ env: serverEnv(layout), cwd: layout.cwd });
+});
+afterEach(async () => {
+ await server.close();
+ layout.cleanup();
+});
+
+const dirOf = (id: string) => join(layout.sessionsDir, id);
+
+async function terminalMeta(id: string, timeoutMs = 10_000): Promise<Record<string, unknown>> {
+ return waitFor(
+ () => {
+ const meta = readJson(join(dirOf(id), "meta.json"));
+ return meta && ["completed", "failed", "timeout", "cancelled"].includes(String(meta.status))
+ ? meta
+ : undefined;
+ },
+ { what: `a terminal meta.json for ${id}`, timeoutMs }
+ );
+}
+
+async function created(args: Parameters<typeof createSession>[1]): Promise<string> {
+ const { sessionId, result } = await createSession(server, args);
+ expect(result.isError).toBe(false);
+ expect(typeof sessionId).toBe("string");
+ return sessionId as string;
+}
+
+describe("REQ-9 a one-shot session ends through finishing and never waits", () => {
+ test(
+ "a prompted session completes and leaves no waits.jsonl",
+ async () => {
+ const id = await created({ prompt: "say hello" });
+
+ const meta = await terminalMeta(id);
+
+ expect(meta.status).toBe("completed");
+ expect(existsSync(join(dirOf(id), "waits.jsonl"))).toBe(false);
+ },
+ T_TEST
+ );
+
+ test(
+ "a prompted session with a tool call completes and leaves no waits.jsonl",
+ async () => {
+ const id = await created({ prompt: "use a tool @@TOOL@@" });
+
+ const meta = await terminalMeta(id);
+
+ expect(meta.status).toBe("completed");
+ expect(existsSync(join(dirOf(id), "waits.jsonl"))).toBe(false);
+ },
+ T_TEST
+ );
+
+ test(
+ "between its final result and the child's exit the session reads finishing, then completed",
+ async () => {
+ const id = await created({ prompt: "answer, then take a while to exit @@LINGER@@" });
+ const seen: string[] = [];
+
+ await waitFor(
+ async () => {
+ const s = await sessionStatus(server, id);
+ if (s && seen[seen.length - 1] !== s) seen.push(s);
+ return s === "completed" ? s : undefined;
+ },
+ { what: "the session to complete", timeoutMs: 10_000, intervalMs: 50 }
+ );
+
+ expect(seen).toContain("finishing");
+ expect(seen).not.toContain("waiting_for_input");
+ expect(seen.indexOf("finishing")).toBeLessThan(seen.indexOf("completed"));
+ expect(existsSync(join(dirOf(id), "waits.jsonl"))).toBe(false);
+ },
+ T_TEST
+ );
+
+ test(
+ "REQ-13 a finishing session refuses send_input and still completes without waiting",
+ async () => {
+ const id = await created({ prompt: "answer, then linger @@LINGER@@" });
+ await waitFor(async () => (await sessionStatus(server, id)) === "finishing", {
+ what: "the finishing state",
+ timeoutMs: 10_000,
+ intervalMs: 20,
+ });
+
+ const refused = await sendInput(server, id, "too late");
+ const meta = await terminalMeta(id);
+
+ expect(refused.isError || /false|closed|not accept|cannot|refus/i.test(refused.text)).toBe(
+ true
+ );
+ expect(meta.status).toBe("completed");
+ expect(existsSync(join(dirOf(id), "waits.jsonl"))).toBe(false);
+ },
+ T_TEST
+ );
+
+ test(
+ "REQ-12 frames after the final result do not reopen the session; diagnostics name the refused state",
+ async () => {
+ const id = await created({ prompt: "answer, then misbehave @@LATE@@" });
+
+ const meta = await terminalMeta(id);
+ const diagnostics = await sessionTool(server, "get_diagnostics", id);
+
+ expect(meta.status).toBe("completed");
+ expect(existsSync(join(dirOf(id), "waits.jsonl"))).toBe(false);
+ // INFERRED: the recorded anomaly names the state the frame arrived in.
+ expect(diagnostics.text).toContain("finishing");
+ },
+ T_TEST
+ );
+});
+
+describe("REQ-11/REQ-14 a promptless session waits from creation, and every wait is logged", () => {
+ test(
+ "it is waiting_for_input once created, with one open line (turns 0), and the child's init does not end the wait",
+ async () => {
+ const id = await created({});
+
+ const status = await sessionStatus(server, id);
+ // The fake child emits system:init as soon as it starts; give it ample time to arrive.
+ await Bun.sleep(1_000);
+ const lines = readWaitLines(dirOf(id));
+ const statusAfterInit = await sessionStatus(server, id);
+
+ expect(status).toBe("waiting_for_input");
+ expect(statusAfterInit).toBe("waiting_for_input");
+ expect(lines).toHaveLength(1);
+ expect(lines?.[0]).toEqual({ wait: "open", since: expect.any(String), turns: 0 });
+ },
+ T_TEST
+ );
+
+ test(
+ "send_input closes the wait to running; the next result opens a new wait with turns already counted",
+ async () => {
+ const id = await created({});
+
+ expect((await sendInput(server, id, "first question")).isError).toBe(false);
+ const afterFirstTurn = await waitFor(
+ () => (readWaitLines(dirOf(id))?.length === 3 ? readWaitLines(dirOf(id)) : undefined),
+ {
+ what: "open, closed, open",
+ }
+ );
+ expect(await sessionStatus(server, id)).toBe("waiting_for_input");
+ expect((await sendInput(server, id, "second question")).isError).toBe(false);
+ const afterSecondInput = await waitFor(
+ () => {
+ const l = readWaitLines(dirOf(id));
+ return l && l.length >= 4 ? l : undefined;
+ },
+ { what: "the second closed line" }
+ );
+
+ expect(afterFirstTurn.map((l) => l.wait)).toEqual(["open", "closed", "open"]);
+ expect(afterFirstTurn[0].turns).toBe(0);
+ expect(afterFirstTurn[1]).toEqual({
+ wait: "closed",
+ since: afterFirstTurn[0].since,
+ at: expect.any(String),
+ to: "running",
+ });
+ expect(afterFirstTurn[2].turns).toBe(1);
+ expect(afterSecondInput[3]).toEqual({
+ wait: "closed",
+ since: afterFirstTurn[2].since,
+ at: expect.any(String),
+ to: "running",
+ });
+ expect(waitPairingViolations(afterSecondInput, true)).toEqual([]);
+ },
+ T_TEST
+ );
+
+ test(
+ "a wait that opens and closes within milliseconds still leaves both lines",
+ async () => {
+ const id = await created({});
+ await sendInput(server, id, "immediately");
+
+ const lines = await waitFor(
+ () => {
+ const l = readWaitLines(dirOf(id));
+ return l && l.length >= 2 ? l : undefined;
+ },
+ { what: "both lines of the short wait" }
+ );
+
+ expect(lines.slice(0, 2).map((l) => [l.wait, l.to])).toEqual([
+ ["open", undefined],
+ ["closed", "running"],
+ ]);
+ expect(lines[1].since).toBe(lines[0].since);
+ },
+ T_TEST
+ );
+});
+
+describe("REQ-14 no wait is left open beside a meta.json", () => {
+ test(
+ "cancel_session closes the open wait (to: cancelled) before meta.json exists",
+ async () => {
+ const id = await created({});
+ await waitFor(() => readWaitLines(dirOf(id))?.length === 1, { what: "the open line" });
+
+ await sessionTool(server, "cancel_session", id);
+ const meta = await terminalMeta(id);
+ const lines = readWaitLines(dirOf(id)) ?? [];
+
+ expect(meta.status).toBe("cancelled");
+ expect(lines.map((l) => l.wait)).toEqual(["open", "closed"]);
+ expect(lines[1].to).toBe("cancelled");
+ expect(waitPairingViolations(lines, false)).toEqual([]);
+ },
+ T_TEST
+ );
+
+ test(
+ "a session timeout closes the open wait (to: timeout)",
+ async () => {
+ const id = await created({ timeout_seconds: 1 });
+
+ const meta = await terminalMeta(id, 15_000);
+ const lines = readWaitLines(dirOf(id)) ?? [];
+
+ expect(meta.status).toBe("timeout");
+ expect(lines.map((l) => l.wait)).toEqual(["open", "closed"]);
+ expect(lines[1].to).toBe("timeout");
+ expect(waitPairingViolations(lines, false)).toEqual([]);
+ },
+ T_TEST
+ );
+
+ test(
+ "the moment meta.json first parses, the wait log is already closed",
+ async () => {
+ const id = await created({});
+ await waitFor(() => readWaitLines(dirOf(id))?.length === 1, { what: "the open line" });
+ const cancelling = sessionTool(server, "cancel_session", id).catch(() => undefined);
+
+ const linesWhenMetaAppeared = await waitFor(
+ () =>
+ readJson(join(dirOf(id), "meta.json")) ? (readWaitLines(dirOf(id)) ?? []) : undefined,
+ { what: "meta.json", timeoutMs: 10_000, intervalMs: 2 }
+ );
+ await cancelling;
+
+ expect(waitPairingViolations(linesWhenMetaAppeared, false)).toEqual([]);
+ },
+ T_TEST
+ );
+
+ test(
+ "a prompted session cancelled mid-turn never waited, so it has no waits.jsonl",
+ async () => {
+ const id = await created({ prompt: "never answer @@HANG@@" });
+ await waitFor(async () => (await sessionStatus(server, id)) === "running", {
+ what: "running",
+ });
+
+ await sessionTool(server, "cancel_session", id);
+ const meta = await terminalMeta(id);
+
+ expect(meta.status).toBe("cancelled");
+ expect(existsSync(join(dirOf(id), "waits.jsonl"))).toBe(false);
+ },
+ T_TEST
+ );
+});
diff --git a/packages/cli/src/channel/spawn-record.contract.test.ts b/packages/cli/src/channel/spawn-record.contract.test.ts
new file mode 100644
index 00000000..d5a8cffc
--- /dev/null
+++ b/packages/cli/src/channel/spawn-record.contract.test.ts
@@ -0,0 +1,511 @@
+// packages/cli/src/channel/spawn-record.contract.test.ts
+/**
+ * Black-box contract tests for the start-time record `spawn.json` and the proven parent
+ * conversation, end to end through a real claudish MCP server over stdio
+ * (design §3.3 "spawn.json", §3.4, §3.5; §8.1 tests 10b, 11-14b, 19; amendments 1 and 2).
+ *
+ * The test process stands in for Claude Code: it spawns `bun src/index.ts --mcp`, so the
+ * correct `hostPid` is `process.pid` and the host's live session record lives at
+ * `<CLAUDE_CONFIG_DIR>/sessions/<process.pid>.json`. The tool-use id travels in
+ * `params._meta["claudecode/toolUseId"]`, exactly as Claude Code sends it.
+ *
+ * INFERRED (adapters in test-helpers/contract-mcp.ts): create_session returns the id as
+ * `session_id`. The server exposes no `get_session` MCP tool, so a session read back from disk
+ * is observed through the public `SessionManager.getSession(id)` (documented to fall back to
+ * `<sessionsDir>/<id>/meta.json`), via test-helpers/contract-adapters.ts.
+ */
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { newSessionManager } from "../test-helpers/contract-adapters.js";
+import {
+ FAKE_MODEL,
+ McpServer,
+ createSession,
+ serverEnv,
+ sessionTool,
+} from "../test-helpers/contract-mcp.js";
+import {
+ type TempLayout,
+ claudeId,
+ entries,
+ fillerLine,
+ makeTempLayout,
+ readJson,
+ sanitisedProjectName,
+ spawnRecordViolations,
+ transcriptLineWithToolUse,
+ waitFor,
+} from "../test-helpers/contract-records.js";
+
+const T_TEST = 30_000;
+
+let layout: TempLayout;
+const servers: McpServer[] = [];
+
+beforeEach(() => {
+ layout = makeTempLayout("spawn");
+});
+afterEach(async () => {
+ for (const s of servers.splice(0)) await s.close();
+ layout.cleanup();
+});
+
+async function startServer(extraEnv: Record<string, string | undefined> = {}): Promise<McpServer> {
+ const server = await McpServer.start({ env: serverEnv(layout, extraEnv), cwd: layout.cwd });
+ servers.push(server);
+ return server;
+}
+
+const toolUseId = () => `toolu_contract_${crypto.randomUUID().replaceAll("-", "")}`;
+
+function writeTranscript(
+ configDir: string,
+ project: string,
+ sessionId: string,
+ content: string
+): string {
+ const dir = join(configDir, "projects", project);
+ mkdirSync(dir, { recursive: true });
+ const path = join(dir, `${sessionId}.jsonl`);
+ writeFileSync(path, content);
+ return path;
+}
+
+function writeHostRecord(configDir: string, record: Record<string, unknown>): void {
+ mkdirSync(join(configDir, "sessions"), { recursive: true });
+ writeFileSync(join(configDir, "sessions", `${process.pid}.json`), JSON.stringify(record));
+}
+
+function spawnRecord(sessionsDir: string, id: string): Record<string, unknown> {
+ return JSON.parse(readFileSync(join(sessionsDir, id, "spawn.json"), "utf8")) as Record<
+ string,
+ unknown
+ >;
+}
+
+async function terminalMeta(sessionsDir: string, id: string): Promise<Record<string, unknown>> {
+ return waitFor(
+ () => {
+ const meta = readJson(join(sessionsDir, id, "meta.json"));
+ return meta && ["completed", "failed", "timeout", "cancelled"].includes(String(meta.status))
+ ? meta
+ : undefined;
+ },
+ { what: `a terminal meta.json for ${id}`, timeoutMs: 10_000 }
+ );
+}
+
+async function createdId(
+ server: McpServer,
+ args: Parameters<typeof createSession>[1],
+ tuid?: string
+): Promise<string> {
+ const { sessionId, result } = await createSession(server, args, tuid);
+ expect(result.isError).toBe(false);
+ expect(typeof sessionId).toBe("string");
+ return sessionId as string;
+}
+
+describe("REQ-7 spawn.json: the start-time record of a session", () => {
+ test(
+ "exists when create_session returns, satisfies every schema rule, and names this host and this server",
+ async () => {
+ const server = await startServer();
+
+ const id = await createdId(server, { prompt: "hello" });
+ const dir = join(layout.sessionsDir, id);
+ const text = readFileSync(join(dir, "spawn.json"), "utf8");
+ const rec = JSON.parse(text) as Record<string, unknown>;
+
+ expect(spawnRecordViolations(text, id)).toEqual([]);
+ expect(rec).toMatchObject({
+ schema: 1,
+ kind: "session",
+ sessionId: id,
+ model: FAKE_MODEL,
+ timeoutSeconds: 600,
+ });
+ expect({ hostPid: rec.hostPid, mcpPid: rec.mcpPid }).toEqual({
+ hostPid: process.pid,
+ mcpPid: server.pid,
+ });
+ expect("launcherPid" in rec).toBe(false);
+ expect("parentClaudeSessionId" in rec).toBe(false);
+ expect(existsSync(join(dir, "spawn.json.tmp"))).toBe(false);
+ },
+ T_TEST
+ );
+
+ test(
+ "is never removed or rewritten: after the session ends it is byte-identical, beside meta.json",
+ async () => {
+ const server = await startServer();
+ const id = await createdId(server, { prompt: "hello" });
+ const before = readFileSync(join(layout.sessionsDir, id, "spawn.json"), "utf8");
+
+ await terminalMeta(layout.sessionsDir, id);
+
+ expect(readFileSync(join(layout.sessionsDir, id, "spawn.json"), "utf8")).toBe(before);
+ expect(entries(join(layout.sessionsDir, id)).filter((n) => n.endsWith(".tmp"))).toEqual([]);
+ },
+ T_TEST
+ );
+
+ test(
+ "REQ-23 nothing is written under <sessionsDir>/.hosts/",
+ async () => {
+ const server = await startServer();
+ const id = await createdId(server, { prompt: "hello" });
+
+ await terminalMeta(layout.sessionsDir, id);
+
+ expect(existsSync(join(layout.sessionsDir, ".hosts"))).toBe(false);
+ },
+ T_TEST
+ );
+
+ test(
+ "REQ-6 without CLAUDISH_SESSIONS_DIR the record is written under $HOME/.claudish/sessions",
+ async () => {
+ const server = await startServer({ CLAUDISH_SESSIONS_DIR: undefined });
+
+ const id = await createdId(server, { prompt: "hello" });
+ const homeSessions = join(layout.home, ".claudish", "sessions");
+
+ expect(
+ spawnRecordViolations(readFileSync(join(homeSessions, id, "spawn.json"), "utf8"), id)
+ ).toEqual([]);
+ expect(entries(layout.sessionsDir)).toEqual([]);
+ },
+ T_TEST
+ );
+});
+
+describe("REQ-8 timeoutSeconds is the effective timeout, an integer in 1..3600 (amendment 2)", () => {
+ test(
+ "a request above 3600 seconds is recorded as 3600",
+ async () => {
+ const server = await startServer();
+
+ const id = await createdId(server, { prompt: "hello", timeout_seconds: 99_999 });
+
+ expect(spawnRecord(layout.sessionsDir, id).timeoutSeconds).toBe(3600);
+ },
+ T_TEST
+ );
+
+ test.each([
+ [0, 1],
+ [-5, 1],
+ [1.4, 1],
+ [2.6, 3],
+ [3600.4, 3600],
+ ])(
+ "timeout_seconds %p is either refused by the tool or recorded as %p",
+ async (requested, effective) => {
+ const server = await startServer();
+
+ const { sessionId, result } = await createSession(server, {
+ prompt: "hello",
+ timeout_seconds: requested,
+ });
+
+ if (result.isError) {
+ expect(
+ entries(layout.sessionsDir).filter((d) =>
+ existsSync(join(layout.sessionsDir, d, "spawn.json"))
+ )
+ ).toEqual([]);
+ } else {
+ expect(spawnRecord(layout.sessionsDir, sessionId as string).timeoutSeconds).toBe(effective);
+ }
+ },
+ T_TEST
+ );
+});
+
+describe("REQ-1 the parent conversation is recorded when proven", () => {
+ test(
+ "env candidate: the tool-use id in E's transcript → spawn.json and meta.json carry parentClaudeSessionId E",
+ async () => {
+ const E = claudeId("env");
+ const T = toolUseId();
+ writeTranscript(layout.configDir, "P", E, fillerLine(1) + transcriptLineWithToolUse(T));
+ const server = await startServer({ CLAUDE_CODE_SESSION_ID: E });
+
+ const id = await createdId(server, { prompt: "hello" }, T);
+ const spawn = spawnRecord(layout.sessionsDir, id);
+ const meta = await terminalMeta(layout.sessionsDir, id);
+
+ expect(spawn.parentClaudeSessionId).toBe(E);
+ expect(spawn.hostPid).toBe(process.pid);
+ expect(meta.parentClaudeSessionId).toBe(E);
+ },
+ T_TEST
+ );
+
+ test(
+ "host-record candidate: with no env id, the host's live record (pid = hostPid) and its cwd lead to R",
+ async () => {
+ const R = claudeId("host");
+ const T = toolUseId();
+ const cwd = join(layout.root, "the project");
+ writeHostRecord(layout.configDir, { pid: process.pid, sessionId: R, cwd });
+ writeTranscript(layout.configDir, sanitisedProjectName(cwd), R, transcriptLineWithToolUse(T));
+ const server = await startServer({ CLAUDE_CODE_SESSION_ID: undefined });
+
+ const id = await createdId(server, { prompt: "hello" }, T);
+
+ expect(spawnRecord(layout.sessionsDir, id).parentClaudeSessionId).toBe(R);
+ expect((await terminalMeta(layout.sessionsDir, id)).parentClaudeSessionId).toBe(R);
+ },
+ T_TEST
+ );
+
+ test(
+ "REQ-6 without CLAUDE_CONFIG_DIR the proof reads $HOME/.claude",
+ async () => {
+ const E = claudeId("env");
+ const T = toolUseId();
+ writeTranscript(join(layout.home, ".claude"), "P", E, transcriptLineWithToolUse(T));
+ const server = await startServer({ CLAUDE_CONFIG_DIR: undefined, CLAUDE_CODE_SESSION_ID: E });
+
+ const id = await createdId(server, { prompt: "hello" }, T);
+
+ expect(spawnRecord(layout.sessionsDir, id).parentClaudeSessionId).toBe(E);
+ },
+ T_TEST
+ );
+
+ test(
+ "the server stays responsive while a proof waits: list_sessions sent later returns first, and the late-written id is still proven",
+ async () => {
+ const E = claudeId("env");
+ const T = toolUseId();
+ const transcript = writeTranscript(layout.configDir, "P", E, fillerLine(1));
+ const server = await startServer({ CLAUDE_CODE_SESSION_ID: E });
+ const order: string[] = [];
+
+ const creating = createSession(server, { prompt: "hello" }, T).then((r) => {
+ order.push("create_session");
+ return r;
+ });
+ await Bun.sleep(50);
+ const listing = server.callTool("list_sessions", {}).then((r) => {
+ order.push("list_sessions");
+ return r;
+ });
+ await Bun.sleep(100);
+ appendFileSync(transcript, transcriptLineWithToolUse(T));
+ const [{ sessionId }] = await Promise.all([creating, listing]);
+
+ expect(order).toEqual(["list_sessions", "create_session"]);
+ expect(spawnRecord(layout.sessionsDir, sessionId as string).parentClaudeSessionId).toBe(E);
+ },
+ T_TEST
+ );
+});
+
+describe("REQ-2 the parent field is absent, never wrong, when nothing is proven", () => {
+ async function expectNoParentAnywhere(
+ server: McpServer,
+ tuid: string | undefined
+ ): Promise<void> {
+ const id = await createdId(server, { prompt: "hello" }, tuid);
+ const spawn = spawnRecord(layout.sessionsDir, id);
+ const meta = await terminalMeta(layout.sessionsDir, id);
+ expect("parentClaudeSessionId" in spawn).toBe(false);
+ expect("parentClaudeSessionId" in meta).toBe(false);
+ }
+
+ test(
+ "the tool-use id is in no transcript",
+ async () => {
+ const E = claudeId("env");
+ writeTranscript(layout.configDir, "P", E, fillerLine(1));
+ const server = await startServer({ CLAUDE_CODE_SESSION_ID: E });
+
+ await expectNoParentAnywhere(server, toolUseId());
+ },
+ T_TEST
+ );
+
+ test(
+ "the call carries no _meta tool-use id",
+ async () => {
+ const E = claudeId("env");
+ writeTranscript(layout.configDir, "P", E, transcriptLineWithToolUse(toolUseId()));
+ const server = await startServer({ CLAUDE_CODE_SESSION_ID: E });
+
+ await expectNoParentAnywhere(server, undefined);
+ },
+ T_TEST
+ );
+
+ test(
+ "the _meta tool-use id is malformed, even though the transcript holds it",
+ async () => {
+ const E = claudeId("env");
+ const bad = "bad id!";
+ writeTranscript(layout.configDir, "P", E, transcriptLineWithToolUse(bad));
+ const server = await startServer({ CLAUDE_CODE_SESSION_ID: E });
+
+ await expectNoParentAnywhere(server, bad);
+ },
+ T_TEST
+ );
+
+ test(
+ "the env id is ignored under CLAUDE_CODE_CHILD_SESSION, even though its transcript holds the id",
+ async () => {
+ const E = claudeId("env");
+ const T = toolUseId();
+ writeTranscript(layout.configDir, "P", E, transcriptLineWithToolUse(T));
+ const server = await startServer({
+ CLAUDE_CODE_SESSION_ID: E,
+ CLAUDE_CODE_CHILD_SESSION: "1",
+ });
+
+ await expectNoParentAnywhere(server, T);
+ },
+ T_TEST
+ );
+
+ test(
+ "a host record whose pid is not hostPid is ignored, even though its transcript holds the id",
+ async () => {
+ const R = claudeId("host");
+ const T = toolUseId();
+ const cwd = join(layout.root, "proj");
+ writeHostRecord(layout.configDir, { pid: process.pid + 1, sessionId: R, cwd });
+ writeTranscript(layout.configDir, sanitisedProjectName(cwd), R, transcriptLineWithToolUse(T));
+ const server = await startServer({ CLAUDE_CODE_SESSION_ID: undefined });
+
+ await expectNoParentAnywhere(server, T);
+ },
+ T_TEST
+ );
+});
+
+describe("REQ-15 a session read back from disk carries parentClaudeSessionId only when meta.json has a real one", () => {
+ function writeDiskSession(id: string, parent: string | undefined): void {
+ const dir = join(layout.sessionsDir, id);
+ mkdirSync(dir, { recursive: true });
+ const meta: Record<string, unknown> = {
+ sessionId: id,
+ model: FAKE_MODEL,
+ status: "completed",
+ pid: 999_999,
+ startedAt: "2026-10-02T10:00:00.000Z",
+ completedAt: "2026-10-02T10:01:00.000Z",
+ exitCode: 0,
+ turnsCompleted: 1,
+ tokensUsed: 2,
+ toolCallCount: 0,
+ idleSeconds: 0,
+ costUsd: 0,
+ terminalReason: "completed",
+ claudeSessionId: "3a4b5c6d-0000-4000-8000-000000000001",
+ };
+ if (parent !== undefined) meta.parentClaudeSessionId = parent;
+ writeFileSync(join(dir, "meta.json"), JSON.stringify(meta, null, 2));
+ }
+
+ test.each([
+ ["a valid id", "parent-conversation-0001", "parent-conversation-0001"],
+ ["an empty string", "", undefined],
+ ["no key", undefined, undefined],
+ ])(
+ "meta.json with %s → SessionManager.getSession reports %p",
+ async (_label, stored, expected) => {
+ writeDiskSession("c0ffee01", stored);
+ const sm = newSessionManager(process.pid, { sessionsDir: layout.sessionsDir });
+
+ const r = sm.getSession("c0ffee01");
+ await sm.dispose();
+
+ expect(r.error).toBeUndefined();
+ expect(r.info?.sessionId).toBe("c0ffee01");
+ expect(r.info?.parentClaudeSessionId).toBe(expected);
+ },
+ T_TEST
+ );
+});
+
+describe("REQ-16 a team record id is answered exactly like an id that never existed", () => {
+ const TEAM_ID = "team-0a1b2c3d";
+ const NEVER = "f00dfeed";
+
+ function writeTeamRecord(): string {
+ const dir = join(layout.sessionsDir, TEAM_ID);
+ mkdirSync(dir, { recursive: true });
+ const spawn = {
+ schema: 1,
+ kind: "team",
+ sessionId: TEAM_ID,
+ hostPid: process.pid,
+ mcpPid: 999_998,
+ startedAt: "2026-10-02T10:00:00.000Z",
+ teamPath: join(layout.root, "team-run"),
+ slots: 2,
+ };
+ writeFileSync(join(dir, "spawn.json"), JSON.stringify(spawn, null, 2));
+ const meta = JSON.stringify(
+ {
+ kind: "team",
+ status: "completed",
+ startedAt: spawn.startedAt,
+ completedAt: "2026-10-02T10:05:00.000Z",
+ elapsedSeconds: 300,
+ slots: 2,
+ ok: 2,
+ failed: 0,
+ cancelled: 0,
+ },
+ null,
+ 2
+ );
+ writeFileSync(join(dir, "meta.json"), meta);
+ return meta;
+ }
+
+ test(
+ "SessionManager.getSession on a team-* id gives the never-existed answer, never a model: unknown record",
+ async () => {
+ const metaBefore = writeTeamRecord();
+ const sm = newSessionManager(process.pid, { sessionsDir: layout.sessionsDir });
+
+ const forTeam = sm.getSession(TEAM_ID);
+ const forNever = sm.getSession(NEVER);
+ await sm.dispose();
+
+ expect(forNever.info).toBeUndefined();
+ expect({ info: forTeam.info, error: forTeam.error?.replaceAll(TEAM_ID, "<ID>") }).toEqual({
+ info: undefined,
+ error: forNever.error?.replaceAll(NEVER, "<ID>"),
+ });
+ expect(readFileSync(join(layout.sessionsDir, TEAM_ID, "meta.json"), "utf8")).toBe(metaBefore);
+ },
+ T_TEST
+ );
+
+ test.each(["get_output", "get_diagnostics", "cancel_session"])(
+ "%s on a team-* id gives the never-existed answer, never a model: unknown record",
+ async (tool) => {
+ const metaBefore = writeTeamRecord();
+ const server = await startServer();
+
+ const forTeam = await sessionTool(server, tool, TEAM_ID);
+ const forNever = await sessionTool(server, tool, NEVER);
+
+ expect({ isError: forTeam.isError, text: forTeam.text.replaceAll(TEAM_ID, "<ID>") }).toEqual({
+ isError: forNever.isError,
+ text: forNever.text.replaceAll(NEVER, "<ID>"),
+ });
+ expect(forTeam.text).not.toMatch(/"model"\s*:\s*"unknown"/);
+ expect(readFileSync(join(layout.sessionsDir, TEAM_ID, "meta.json"), "utf8")).toBe(metaBefore);
+ },
+ T_TEST
+ );
+});
diff --git a/packages/cli/src/channel/stream-json-reducer.contract.test.ts b/packages/cli/src/channel/stream-json-reducer.contract.test.ts
new file mode 100644
index 00000000..75862741
--- /dev/null
+++ b/packages/cli/src/channel/stream-json-reducer.contract.test.ts
@@ -0,0 +1,248 @@
+// packages/cli/src/channel/stream-json-reducer.contract.test.ts
+/**
+ * Black-box contract tests for the claudish state model (design §3.2; §8.1 tests 1, 3, 5).
+ * Written from the specification only.
+ *
+ * Documented surface: `TurnEnd = "stdin-open" | "stdin-closed"`, the required
+ * `onResult: (summary) => TurnEnd`, `awaitInput()`, `beginTurn()`. Everything else about
+ * driving the reducer (constructor option for state changes, the line-ingest method, the state
+ * getter, `settle`, where refused transitions are recorded) is INFERRED and lives in
+ * test-helpers/contract-adapters.ts.
+ *
+ * Frames are the public Claude Code stream-json shapes.
+ */
+import { afterEach, describe, expect, test } from "bun:test";
+import { disposeReducerProbes, makeReducerProbe } from "../test-helpers/contract-adapters.js";
+import type { TurnEnd } from "./stream-json-reducer.js";
+
+afterEach(() => disposeReducerProbes());
+
+const CHILD = "7d1c0b6a-2222-4333-8444-555566667777";
+
+const init = {
+ type: "system",
+ subtype: "init",
+ session_id: CHILD,
+ model: "contract-fake",
+ tools: [],
+};
+const assistantText = (n: number) => ({
+ type: "assistant",
+ message: {
+ id: `msg_${n}`,
+ type: "message",
+ role: "assistant",
+ content: [{ type: "text", text: `reply ${n}` }],
+ stop_reason: "end_turn",
+ },
+ session_id: CHILD,
+});
+const assistantToolUse = (n: number) => ({
+ type: "assistant",
+ message: {
+ id: `msg_tool_${n}`,
+ type: "message",
+ role: "assistant",
+ content: [{ type: "tool_use", id: `toolu_${n}`, name: "Read", input: {} }],
+ stop_reason: "tool_use",
+ },
+ session_id: CHILD,
+});
+const userToolResult = (n: number) => ({
+ type: "user",
+ message: {
+ role: "user",
+ content: [{ type: "tool_result", tool_use_id: `toolu_${n}`, content: "ok" }],
+ },
+ session_id: CHILD,
+});
+const result = (turns: number) => ({
+ type: "result",
+ subtype: "success",
+ is_error: false,
+ num_turns: turns,
+ result: "done",
+ session_id: CHILD,
+ total_cost_usd: 0,
+ duration_ms: 1,
+ usage: { input_tokens: 1, output_tokens: 1 },
+});
+
+describe("REQ-10 TurnEnd is exactly the two documented values", () => {
+ test("both literals are assignable to TurnEnd", () => {
+ const values: TurnEnd[] = ["stdin-open", "stdin-closed"];
+
+ expect(values).toEqual(["stdin-open", "stdin-closed"]);
+ });
+});
+
+describe("REQ-9/REQ-10 the owner's TurnEnd decides the state after a result frame", () => {
+ test("stdin-closed: a one-shot turn goes running → finishing and never names waiting_for_input", () => {
+ const probe = makeReducerProbe("stdin-closed");
+
+ probe.feed(init);
+ probe.feed(assistantText(1));
+ probe.feed(result(1));
+
+ expect(probe.snapshots).toEqual(["starting", "running", "running", "finishing"]);
+ expect(probe.mentioned.has("waiting_for_input")).toBe(false);
+ });
+
+ test("stdin-open: an interactive turn goes running → waiting_for_input, not finishing", () => {
+ const probe = makeReducerProbe("stdin-open");
+
+ probe.feed(init);
+ probe.feed(assistantText(1));
+ probe.feed(result(1));
+
+ expect(probe.state()).toBe("waiting_for_input");
+ expect(probe.mentioned.has("finishing")).toBe(false);
+ });
+
+ test("onResult runs before the transition: during the call the state is still running", () => {
+ const probe = makeReducerProbe("stdin-closed");
+
+ probe.feed(init);
+ probe.feed(assistantText(1));
+ probe.feed(result(1));
+
+ expect(probe.stateAtOnResult).toEqual(["running"]);
+ });
+
+ test("starting → finishing is legal: a result before any init frame", () => {
+ const probe = makeReducerProbe("stdin-closed");
+
+ probe.feed(result(1));
+
+ expect(probe.state()).toBe("finishing");
+ });
+
+ test("tool_executing → finishing is legal: a result while a tool is executing", () => {
+ const probe = makeReducerProbe("stdin-closed");
+ probe.feed(init);
+ probe.feed(assistantToolUse(1));
+ expect(probe.state()).toBe("tool_executing");
+
+ probe.feed(result(1));
+
+ expect(probe.state()).toBe("finishing");
+ });
+});
+
+describe("REQ-12/REQ-13 finishing accepts only terminal successors", () => {
+ function finishingProbe() {
+ const probe = makeReducerProbe("stdin-closed");
+ probe.feed(init);
+ probe.feed(assistantText(1));
+ probe.feed(result(1));
+ expect(probe.state()).toBe("finishing");
+ return probe;
+ }
+
+ test.each([
+ ["an assistant text frame", assistantText(2)],
+ ["a user tool_result frame", userToolResult(2)],
+ ["an assistant tool_use frame", assistantToolUse(2)],
+ ])(
+ "%s after the final result is refused: the state stays finishing and an anomaly is recorded",
+ (_label, frame) => {
+ const probe = finishingProbe();
+ const anomaliesBefore = probe.anomalyCount();
+
+ probe.feed(frame);
+
+ expect(probe.state()).toBe("finishing");
+ expect(probe.anomalyCount()).toBeGreaterThan(anomaliesBefore);
+ }
+ );
+
+ test("a system:init frame in finishing does not move the state", () => {
+ const probe = finishingProbe();
+
+ probe.feed(init);
+
+ expect(probe.state()).toBe("finishing");
+ });
+
+ test.each(["completed", "failed", "timeout", "cancelled"])(
+ "finishing → %s is legal",
+ (terminal) => {
+ const probe = finishingProbe();
+
+ probe.settle(terminal);
+
+ expect(probe.state()).toBe(terminal);
+ }
+ );
+});
+
+describe("REQ-11 a promptless session waits from creation (awaitInput, init, beginTurn)", () => {
+ test("awaitInput moves starting → waiting_for_input", () => {
+ const probe = makeReducerProbe("stdin-open");
+
+ probe.awaitInput();
+
+ expect(probe.state()).toBe("waiting_for_input");
+ });
+
+ test("a system:init frame while waiting_for_input records the child but does not transition", () => {
+ const probe = makeReducerProbe("stdin-open");
+ probe.awaitInput();
+ const callsBefore = probe.stateChangeCalls();
+
+ probe.feed(init);
+
+ expect(probe.state()).toBe("waiting_for_input");
+ expect(probe.stateChangeCalls()).toBe(callsBefore);
+ });
+
+ test("beginTurn moves waiting_for_input → running", () => {
+ const probe = makeReducerProbe("stdin-open");
+ probe.awaitInput();
+ probe.feed(init);
+
+ probe.beginTurn();
+
+ expect(probe.state()).toBe("running");
+ });
+
+ test("a full interactive cycle: wait, turn, wait again, turn again", () => {
+ const probe = makeReducerProbe("stdin-open");
+
+ probe.awaitInput();
+ probe.feed(init);
+ probe.beginTurn();
+ probe.feed(assistantText(1));
+ probe.feed(result(1));
+ probe.beginTurn();
+
+ expect(probe.snapshots).toEqual([
+ "starting",
+ "waiting_for_input",
+ "waiting_for_input",
+ "running",
+ "running",
+ "waiting_for_input",
+ "running",
+ ]);
+ });
+
+ test("init from starting still moves to running (behaviour unchanged for everyone else)", () => {
+ const probe = makeReducerProbe("stdin-closed");
+
+ probe.feed(init);
+
+ expect(probe.state()).toBe("running");
+ });
+
+ test("beginTurn while running transitions nothing", () => {
+ const probe = makeReducerProbe("stdin-closed");
+ probe.feed(init);
+ const callsBefore = probe.stateChangeCalls();
+
+ probe.beginTurn();
+
+ expect(probe.state()).toBe("running");
+ expect(probe.stateChangeCalls()).toBe(callsBefore);
+ });
+});
diff --git a/packages/cli/src/channel/team-run-record.contract.test.ts b/packages/cli/src/channel/team-run-record.contract.test.ts
new file mode 100644
index 00000000..73d52c63
--- /dev/null
+++ b/packages/cli/src/channel/team-run-record.contract.test.ts
@@ -0,0 +1,232 @@
+// packages/cli/src/channel/team-run-record.contract.test.ts
+/**
+ * Black-box contract tests for the team-run record and its exactly-once end
+ * (design §3.3 "Team record", `finishTeamRun`; §8.1 tests 15, 17b; amendment 4).
+ *
+ * Drives `SessionManager.recordTeamRun({ teamPath, slots, parentClaudeSessionId })` and
+ * `finishTeamRun(record, outcome)` directly, with the documented test override `hostPid`.
+ * Outcomes are built with `summarise` (documented), exactly as the `team` handler builds them.
+ * INFERRED (adapter): the class is `SessionManager`, constructed with `{ hostPid }`, and it
+ * reads CLAUDISH_SESSIONS_DIR at construction or later.
+ */
+import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
+import { chmodSync, existsSync, mkdirSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+import { summarise } from "../team-orchestrator.js";
+import {
+ type SessionManagerHandle,
+ modelStates,
+ newSessionManager,
+} from "../test-helpers/contract-adapters.js";
+import {
+ TEAM_RECORD_ID_PATTERN,
+ type TempLayout,
+ entries,
+ makeTempLayout,
+ spawnRecordViolations,
+ teamRecordDirs,
+} from "../test-helpers/contract-records.js";
+
+const HOST_PID = 424_242;
+const S = modelStates();
+
+let layout: TempLayout;
+let savedSessionsDir: string | undefined;
+let handle: SessionManagerHandle;
+let teamPath: string;
+
+beforeEach(() => {
+ layout = makeTempLayout("teamrec");
+ savedSessionsDir = process.env.CLAUDISH_SESSIONS_DIR;
+ process.env.CLAUDISH_SESSIONS_DIR = layout.sessionsDir;
+ handle = newSessionManager(HOST_PID);
+ teamPath = join(layout.root, "team-run-dir");
+ mkdirSync(teamPath, { recursive: true });
+});
+afterEach(async () => {
+ await handle.dispose();
+ if (savedSessionsDir === undefined) delete process.env.CLAUDISH_SESSIONS_DIR;
+ else process.env.CLAUDISH_SESSIONS_DIR = savedSessionsDir;
+ for (const dir of teamRecordDirs(layout.sessionsDir))
+ chmodSync(join(layout.sessionsDir, dir), 0o755);
+ layout.cleanup();
+});
+
+const outcomeOf = (states: string[]) =>
+ summarise({
+ models: Object.fromEntries(states.map((state, i) => [`m${i}`, { state }])),
+ } as never);
+
+/** The one team record directory; asserts there is exactly one. */
+function onlyRecordDir(): string {
+ const dirs = teamRecordDirs(layout.sessionsDir);
+ expect(dirs).toHaveLength(1);
+ return join(layout.sessionsDir, dirs[0] as string);
+}
+
+function readMeta(dir: string): Record<string, unknown> {
+ return JSON.parse(readFileSync(join(dir, "meta.json"), "utf8")) as Record<string, unknown>;
+}
+
+/** Stub both stderr routes, so a line is counted once whichever one the implementation uses. */
+function captureStderr() {
+ const lines: string[] = [];
+ const write = spyOn(process.stderr, "write").mockImplementation(((chunk: unknown) => {
+ lines.push(String(chunk));
+ return true;
+ }) as typeof process.stderr.write);
+ const error = spyOn(console, "error").mockImplementation((...args: unknown[]) => {
+ lines.push(args.map(String).join(" "));
+ });
+ return {
+ lines,
+ restore() {
+ write.mockRestore();
+ error.mockRestore();
+ },
+ };
+}
+
+describe("REQ-17 recordTeamRun writes the team's spawn.json", () => {
+ test("a team-<8 hex> directory holding only a valid kind:team spawn.json", async () => {
+ const record = await handle.recordTeamRun({
+ teamPath,
+ slots: 3,
+ parentClaudeSessionId: "parent-conversation-0001",
+ });
+ const dir = onlyRecordDir();
+ const id = dir.slice(layout.sessionsDir.length + 1);
+ const text = readFileSync(join(dir, "spawn.json"), "utf8");
+
+ expect(id).toMatch(TEAM_RECORD_ID_PATTERN);
+ expect(typeof record === "string" ? record : id).toBe(id);
+ expect(spawnRecordViolations(text, id)).toEqual([]);
+ expect(JSON.parse(text)).toEqual({
+ schema: 1,
+ kind: "team",
+ sessionId: id,
+ parentClaudeSessionId: "parent-conversation-0001",
+ hostPid: HOST_PID,
+ mcpPid: process.pid,
+ startedAt: expect.any(String),
+ teamPath,
+ slots: 3,
+ });
+ expect(entries(dir)).toEqual(["spawn.json"]);
+ });
+
+ test.each([
+ ["no parent", undefined],
+ ["an empty parent", ""],
+ ])("with %s, spawn.json has no parentClaudeSessionId key", async (_label, parent) => {
+ await handle.recordTeamRun({ teamPath, slots: 2, parentClaudeSessionId: parent });
+
+ const rec = JSON.parse(readFileSync(join(onlyRecordDir(), "spawn.json"), "utf8")) as Record<
+ string,
+ unknown
+ >;
+
+ expect("parentClaudeSessionId" in rec).toBe(false);
+ });
+
+ test("two runs get two distinct record ids", async () => {
+ await handle.recordTeamRun({ teamPath, slots: 1 });
+ await handle.recordTeamRun({ teamPath, slots: 1 });
+
+ const dirs = teamRecordDirs(layout.sessionsDir);
+
+ expect(new Set(dirs).size).toBe(2);
+ });
+});
+
+describe("REQ-18 finishTeamRun ends the record exactly once", () => {
+ test("writes meta.json with the outcome's counts, kind team and the run's timing", async () => {
+ const record = await handle.recordTeamRun({ teamPath, slots: 3 });
+ const dir = onlyRecordDir();
+
+ await handle.finishTeamRun(record, outcomeOf([S.COMPLETED, S.COMPLETED, S.RUNNING]));
+ const meta = readMeta(dir);
+
+ expect(meta).toEqual({
+ kind: "team",
+ status: "completed",
+ startedAt: expect.any(String),
+ completedAt: expect.any(String),
+ elapsedSeconds: expect.any(Number),
+ slots: 3,
+ ok: 2,
+ failed: 1,
+ cancelled: 0,
+ });
+ expect(Date.parse(meta.completedAt as string)).toBeGreaterThanOrEqual(
+ Date.parse(meta.startedAt as string)
+ );
+ expect(Number.isInteger(meta.elapsedSeconds) && (meta.elapsedSeconds as number) >= 0).toBe(
+ true
+ );
+ expect(entries(dir)).toEqual(["meta.json", "spawn.json"]);
+ });
+
+ test("a start failure is recorded as failed with reason start-failed (amendment 4)", async () => {
+ const record = await handle.recordTeamRun({ teamPath, slots: 2 });
+ const dir = onlyRecordDir();
+
+ await handle.finishTeamRun(record, {
+ ...outcomeOf([S.RUNNING, S.PENDING]),
+ status: "failed",
+ reason: "start-failed",
+ });
+
+ expect(readMeta(dir)).toMatchObject({
+ kind: "team",
+ status: "failed",
+ reason: "start-failed",
+ slots: 2,
+ ok: 0,
+ failed: 2,
+ cancelled: 0,
+ });
+ });
+
+ test("a second call is a no-op that keeps the first content and writes one stderr line", async () => {
+ const record = await handle.recordTeamRun({ teamPath, slots: 2 });
+ const dir = onlyRecordDir();
+ await handle.finishTeamRun(record, outcomeOf([S.COMPLETED, S.COMPLETED]));
+ const first = readFileSync(join(dir, "meta.json"), "utf8");
+
+ const stderr = captureStderr();
+ try {
+ await handle.finishTeamRun(record, {
+ ...outcomeOf([S.RUNNING, S.RUNNING]),
+ status: "failed",
+ reason: "start-failed",
+ });
+ } finally {
+ stderr.restore();
+ }
+
+ expect(readFileSync(join(dir, "meta.json"), "utf8")).toBe(first);
+ expect(stderr.lines.join("").trimEnd().split("\n")).toHaveLength(1);
+ expect(entries(dir)).toEqual(["meta.json", "spawn.json"]);
+ });
+
+ test("a failed write never throws: the record directory is read-only", async () => {
+ const record = await handle.recordTeamRun({ teamPath, slots: 1 });
+ const dir = onlyRecordDir();
+ chmodSync(dir, 0o555);
+
+ const stderr = captureStderr();
+ let thrown: unknown;
+ try {
+ await handle.finishTeamRun(record, outcomeOf([S.COMPLETED]));
+ } catch (err) {
+ thrown = err;
+ } finally {
+ stderr.restore();
+ }
+
+ expect(thrown).toBeUndefined();
+ expect(existsSync(join(dir, "meta.json"))).toBe(false);
+ expect(stderr.lines.length).toBeGreaterThan(0);
+ });
+});
diff --git a/packages/cli/src/team-orchestrator-settle.contract.test.ts b/packages/cli/src/team-orchestrator-settle.contract.test.ts
new file mode 100644
index 00000000..35dfc067
--- /dev/null
+++ b/packages/cli/src/team-orchestrator-settle.contract.test.ts
@@ -0,0 +1,181 @@
+// packages/cli/src/team-orchestrator-settle.contract.test.ts
+/**
+ * Black-box contract tests for how a team run settles (design §3.3 "startModels changes";
+ * §8.1 tests 16b and 17; amendment 4).
+ *
+ * - `TeamRunOptions.onSettled` is called exactly once, after the settled `status.txt`
+ * render, for a run that settles at once; a throwing consumer cannot fail the run.
+ * - A throw inside the spawn loop SIGTERMs every child already spawned, removes the SIGINT
+ * handler, rethrows the ORIGINAL error, and never calls `onSettled`.
+ * - A throw before the loop (unreadable manifest.json) spawns nothing and never settles.
+ *
+ * Children are the contract fake, injected through `TeamRunOptions.spawnChild` (documented).
+ * INFERRED (adapters in test-helpers/contract-adapters.ts): `setupSession(path, models, input)`,
+ * `startModels(path, opts)` resolving to a handle with `done`, the spawnChild call shape, and
+ * the file names `manifest.json` and `status.txt` in the team directory (both named in §3.3).
+ */
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { readTeamStatus, summarise } from "./team-orchestrator.js";
+import { setupTeamSession, spawnSeam, startModels } from "./test-helpers/contract-adapters.js";
+import { type TempLayout, makeTempLayout, waitFor } from "./test-helpers/contract-records.js";
+
+const T_TEST = 30_000;
+const MODELS = ["contract-fake-a", "contract-fake-b"];
+
+let layout: TempLayout;
+let teamDir: string;
+
+beforeEach(() => {
+ layout = makeTempLayout("settle");
+ teamDir = join(layout.root, "team");
+});
+afterEach(() => layout.cleanup());
+
+async function settledWithin<T>(p: Promise<T>, ms: number, what: string): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const deadline = new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Error(`${what} did not settle within ${ms} ms`)), ms);
+ });
+ try {
+ return await Promise.race([p, deadline]);
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+describe("REQ-21 onSettled: called once, after the settled render, for a run that settles at once", () => {
+ test(
+ "every slot answers and exits at once: onSettled runs exactly once with a completed status",
+ async () => {
+ await setupTeamSession(teamDir, MODELS, "answer once and exit");
+ const seam = spawnSeam({});
+ const calls: Array<{ status: unknown; statusTxtExisted: boolean }> = [];
+
+ const handle = await startModels(teamDir, {
+ spawnChild: seam.spawnChild,
+ onSettled: (status: unknown) =>
+ calls.push({ status, statusTxtExisted: existsSync(join(teamDir, "status.txt")) }),
+ });
+ await settledWithin(handle.done, 15_000, "the team run");
+ await Bun.sleep(200);
+
+ expect(seam.calls()).toBe(MODELS.length);
+ expect(calls).toHaveLength(1);
+ expect(calls[0]?.statusTxtExisted).toBe(true);
+ expect(summarise(calls[0]?.status as never)).toEqual({
+ status: "completed",
+ slots: 2,
+ ok: 2,
+ failed: 0,
+ cancelled: 0,
+ });
+ },
+ T_TEST
+ );
+
+ test(
+ "a consumer that throws inside onSettled cannot fail the run",
+ async () => {
+ await setupTeamSession(teamDir, MODELS, "answer once and exit");
+ const seam = spawnSeam({});
+ let called = 0;
+
+ const handle = await startModels(teamDir, {
+ spawnChild: seam.spawnChild,
+ onSettled: () => {
+ called += 1;
+ throw new Error("contract: a broken consumer");
+ },
+ });
+ let rejected: unknown;
+ await settledWithin(handle.done, 15_000, "the team run").catch((err) => {
+ rejected = err;
+ });
+
+ expect(rejected).toBeUndefined();
+ expect(called).toBe(1);
+ },
+ T_TEST
+ );
+});
+
+describe("REQ-22 a throw inside the spawn loop leaves nothing running (amendment 4)", () => {
+ test(
+ "slot 2's spawn throws: the original error is rethrown, slot 1 gets SIGTERM, SIGINT handler removed, onSettled never called",
+ async () => {
+ await setupTeamSession(teamDir, MODELS, "@@HANG@@ stay alive until signalled");
+ const injected = new Error("contract: spawn of slot 2 failed");
+ const marker = (n: number) => join(layout.root, `sigterm-slot-${n}`);
+ const seam = spawnSeam({ throwOn: 2, error: injected, markerFor: marker, hang: true });
+ const sigintBefore = process.listenerCount("SIGINT");
+ let settledCalls = 0;
+
+ const thrown = await startModels(teamDir, {
+ spawnChild: seam.spawnChild,
+ onSettled: () => {
+ settledCalls += 1;
+ },
+ }).then(
+ () => undefined,
+ (err: unknown) => err
+ );
+ const slot1 = seam.children[0];
+ await waitFor(
+ () => slot1 !== undefined && (slot1.exitCode !== null || slot1.signalCode !== null),
+ {
+ what: "slot 1 to exit",
+ timeoutMs: 5_000,
+ }
+ );
+ await Bun.sleep(300);
+ // The SIGTERM can arrive before the fake child has installed its handler (the loop throws
+ // within milliseconds of the first spawn); the default action then ends it by SIGTERM with
+ // no marker. Either is proof of SIGTERM; a SIGKILL or a clean exit is not.
+ const sigtermProof = slot1?.signalCode === "SIGTERM" || existsSync(marker(1));
+
+ expect(sigtermProof).toBe(true);
+ expect(thrown).toBe(injected);
+ expect(seam.calls()).toBe(2);
+ expect(process.listenerCount("SIGINT")).toBe(sigintBefore);
+ expect(settledCalls).toBe(0);
+ expect(summarise(readTeamStatus(teamDir))).toEqual({
+ status: "failed",
+ slots: 2,
+ ok: 0,
+ failed: 2,
+ cancelled: 0,
+ });
+ },
+ T_TEST
+ );
+
+ test(
+ "a throw before the loop (unreadable manifest.json): rejects, spawns nothing, never settles",
+ async () => {
+ await setupTeamSession(teamDir, MODELS, "answer once and exit");
+ writeFileSync(join(teamDir, "manifest.json"), "{ this is not json");
+ const seam = spawnSeam({});
+ const sigintBefore = process.listenerCount("SIGINT");
+ let settledCalls = 0;
+
+ const thrown = await startModels(teamDir, {
+ spawnChild: seam.spawnChild,
+ onSettled: () => {
+ settledCalls += 1;
+ },
+ }).then(
+ () => undefined,
+ (err: unknown) => err
+ );
+ await Bun.sleep(300);
+
+ expect(thrown).toBeInstanceOf(Error);
+ expect(seam.calls()).toBe(0);
+ expect(settledCalls).toBe(0);
+ expect(process.listenerCount("SIGINT")).toBe(sigintBefore);
+ },
+ T_TEST
+ );
+});
diff --git a/packages/cli/src/team-run-mcp.contract.test.ts b/packages/cli/src/team-run-mcp.contract.test.ts
new file mode 100644
index 00000000..c0088026
--- /dev/null
+++ b/packages/cli/src/team-run-mcp.contract.test.ts
@@ -0,0 +1,155 @@
+// packages/cli/src/team-run-mcp.contract.test.ts
+/**
+ * Black-box contract tests for the team-run record through the real `team` MCP tool
+ * (design §3.3 "Team record", §3.2 item 3; §8.1 tests 7, 15, 16b, 18, 19).
+ *
+ * A real claudish MCP server over stdio, every slot the stream-json fake via CLAUDISH_BIN.
+ * The team directory is inside the server's cwd, in case path validation requires it.
+ *
+ * INFERRED (adapter `teamCall` in test-helpers/contract-mcp.ts): the `team` tool takes
+ * `mode`, a path, `models` and an input; key names are read from the tool's own inputSchema.
+ * `team(mode:"status")` reports per-slot activity under an `activity_by_slot` key (named in
+ * design §5.6). `run-and-judge` and `judge` are not exercised: they need a judge model.
+ */
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+import { McpServer, findField, serverEnv, teamCall } from "./test-helpers/contract-mcp.js";
+import {
+ TEAM_RECORD_ID_PATTERN,
+ type TempLayout,
+ entries,
+ makeTempLayout,
+ readJson,
+ spawnRecordViolations,
+ teamRecordDirs,
+ waitFor,
+} from "./test-helpers/contract-records.js";
+
+const T_TEST = 30_000;
+const MODELS = ["contract-fake-a", "contract-fake-b"];
+
+let layout: TempLayout;
+let server: McpServer;
+let teamDir: string;
+
+beforeEach(async () => {
+ layout = makeTempLayout("teammcp");
+ teamDir = join(layout.cwd, "team-run");
+ server = await McpServer.start({ env: serverEnv(layout), cwd: layout.cwd });
+});
+afterEach(async () => {
+ await server.close();
+ layout.cleanup();
+});
+
+async function run(input: string): Promise<string> {
+ const r = await teamCall(server, "run", { path: teamDir, models: MODELS, input });
+ expect(r.isError).toBe(false);
+ const record = findField(r.json, "monitor_record");
+ expect(typeof record).toBe("string");
+ return record as string;
+}
+
+describe("REQ-17 team(mode:'run') writes a kind:team record and returns its id", () => {
+ test(
+ "the result carries monitor_record, and that record's spawn.json is valid and names the run",
+ async () => {
+ const record = await run("answer once and exit");
+ const text = readFileSync(join(layout.sessionsDir, record, "spawn.json"), "utf8");
+
+ expect(record).toMatch(TEAM_RECORD_ID_PATTERN);
+ expect(spawnRecordViolations(text, record)).toEqual([]);
+ expect(JSON.parse(text)).toMatchObject({
+ schema: 1,
+ kind: "team",
+ sessionId: record,
+ teamPath: teamDir,
+ slots: MODELS.length,
+ hostPid: process.pid,
+ mcpPid: server.pid,
+ });
+ expect(teamRecordDirs(layout.sessionsDir)).toEqual([record]);
+ },
+ T_TEST
+ );
+});
+
+describe("REQ-18/REQ-21 the record of a run that settles at once ends exactly once", () => {
+ test(
+ "meta.json is written within 1 s of the run call returning, completed, with every slot ok",
+ async () => {
+ const record = await run("answer once and exit");
+ const returnedAt = Date.now();
+
+ const meta = await waitFor(() => readJson(join(layout.sessionsDir, record, "meta.json")), {
+ what: "the team record's meta.json",
+ timeoutMs: 1_000,
+ });
+
+ expect(Date.now() - returnedAt).toBeLessThanOrEqual(1_000);
+ expect(meta).toEqual({
+ kind: "team",
+ status: "completed",
+ startedAt: expect.any(String),
+ completedAt: expect.any(String),
+ elapsedSeconds: expect.any(Number),
+ slots: 2,
+ ok: 2,
+ failed: 0,
+ cancelled: 0,
+ });
+ expect(entries(join(layout.sessionsDir, record))).toEqual(["meta.json", "spawn.json"]);
+ },
+ T_TEST
+ );
+});
+
+describe("REQ-23 only mode 'run' writes a record, and nothing goes under .hosts", () => {
+ test(
+ "status and cancel on an existing run add no record; no .hosts directory appears",
+ async () => {
+ const record = await run("answer once and exit");
+ await waitFor(() => readJson(join(layout.sessionsDir, record, "meta.json")), {
+ what: "the run to settle",
+ timeoutMs: 10_000,
+ });
+
+ await teamCall(server, "status", { path: teamDir });
+ await teamCall(server, "cancel", { path: teamDir });
+
+ expect(teamRecordDirs(layout.sessionsDir)).toEqual([record]);
+ expect(existsSync(join(layout.sessionsDir, ".hosts"))).toBe(false);
+ },
+ T_TEST
+ );
+});
+
+describe("REQ-24 a team slot reads finishing, never waiting_for_input, between its result and its exit", () => {
+ function activities(json: unknown): string[] {
+ const bySlot = findField(json, "activity_by_slot");
+ if (!bySlot || typeof bySlot !== "object") return [];
+ return Object.values(bySlot as Record<string, unknown>).map(String);
+ }
+
+ test(
+ "slots that answer and then linger before exiting report finishing",
+ async () => {
+ const record = await run("answer, then linger before exiting @@LINGER@@");
+ const seen = new Set<string>();
+
+ await waitFor(
+ async () => {
+ const status = await teamCall(server, "status", { path: teamDir });
+ for (const a of activities(status.json)) seen.add(a);
+ return readJson(join(layout.sessionsDir, record, "meta.json"));
+ },
+ { what: "the run to settle", timeoutMs: 15_000, intervalMs: 100 }
+ );
+
+ expect(seen.has("finishing")).toBe(true);
+ expect(seen.has("waiting_for_input")).toBe(false);
+ },
+ T_TEST
+ );
+});
diff --git a/packages/cli/src/team-run-summary.contract.test.ts b/packages/cli/src/team-run-summary.contract.test.ts
new file mode 100644
index 00000000..9d874ec7
--- /dev/null
+++ b/packages/cli/src/team-run-summary.contract.test.ts
@@ -0,0 +1,159 @@
+// packages/cli/src/team-run-summary.contract.test.ts
+/**
+ * Black-box contract tests for `summarise` and `readTeamStatus` (design §3.3 "Team record";
+ * §8.1 test 16). Written from the specification only.
+ *
+ * `summarise(status)` counts over `Object.values(status.models)` by `state`:
+ * COMPLETED → ok; FAILED/EMPTY/TIMEOUT with error.reason "cancelled" → cancelled;
+ * FAILED/EMPTY/TIMEOUT otherwise → failed; PENDING/RUNNING → failed.
+ * status = "completed" when ok ≥ 1; "cancelled" when cancelled === slots; else "failed".
+ * A `reason` key is present only for start-failed, which summarise never produces.
+ *
+ * INFERRED: a TeamStatus needs only `models` for summarise; `ModelState` values come from the
+ * module when it is a runtime enum (adapter `modelStates()`).
+ */
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { readTeamStatus, summarise } from "./team-orchestrator.js";
+import { modelStates } from "./test-helpers/contract-adapters.js";
+import { type TempLayout, makeTempLayout } from "./test-helpers/contract-records.js";
+
+type TeamStatusArg = Parameters<typeof summarise>[0];
+const S = modelStates();
+
+interface Slot {
+ state: string;
+ reason?: string;
+}
+
+function status(slots: Slot[]): TeamStatusArg {
+ const models: Record<string, unknown> = {};
+ slots.forEach((slot, i) => {
+ models[`model-${i}`] =
+ slot.reason === undefined
+ ? { state: slot.state }
+ : { state: slot.state, error: { reason: slot.reason, message: slot.reason } };
+ });
+ return { models } as unknown as TeamStatusArg;
+}
+
+const cancelledSlot = (state: string): Slot => ({ state, reason: "cancelled" });
+const failedSlot = (state: string, reason = "exit-1"): Slot => ({ state, reason });
+
+describe("REQ-19 summarise counts every ModelState as the table says", () => {
+ test("one slot in each of the six states: COMPLETED is ok, the five others are failed", () => {
+ const outcome = summarise(
+ status([
+ { state: S.COMPLETED },
+ failedSlot(S.FAILED),
+ failedSlot(S.EMPTY),
+ failedSlot(S.TIMEOUT),
+ { state: S.PENDING },
+ { state: S.RUNNING },
+ ])
+ );
+
+ expect(outcome).toEqual({ status: "completed", slots: 6, ok: 1, failed: 5, cancelled: 0 });
+ });
+
+ test.each([S.FAILED, S.EMPTY, S.TIMEOUT])(
+ "%s with error.reason 'cancelled' counts as cancelled",
+ (state) => {
+ const outcome = summarise(status([cancelledSlot(state), { state: S.COMPLETED }]));
+
+ expect(outcome).toEqual({ status: "completed", slots: 2, ok: 1, failed: 0, cancelled: 1 });
+ }
+ );
+
+ test.each([S.PENDING, S.RUNNING])(
+ "%s counts as failed (a slot never started, or just killed)",
+ (state) => {
+ const outcome = summarise(status([{ state }, { state }]));
+
+ expect(outcome).toEqual({ status: "failed", slots: 2, ok: 0, failed: 2, cancelled: 0 });
+ }
+ );
+});
+
+describe("REQ-19 summarise derives the run's status", () => {
+ test("every slot completed → completed", () => {
+ expect(
+ summarise(status([{ state: S.COMPLETED }, { state: S.COMPLETED }, { state: S.COMPLETED }]))
+ ).toEqual({
+ status: "completed",
+ slots: 3,
+ ok: 3,
+ failed: 0,
+ cancelled: 0,
+ });
+ });
+
+ test("every slot cancelled → cancelled", () => {
+ expect(
+ summarise(status([cancelledSlot(S.FAILED), cancelledSlot(S.TIMEOUT), cancelledSlot(S.EMPTY)]))
+ ).toEqual({
+ status: "cancelled",
+ slots: 3,
+ ok: 0,
+ failed: 0,
+ cancelled: 3,
+ });
+ });
+
+ test("none completed, some failed, some cancelled → failed", () => {
+ expect(summarise(status([failedSlot(S.FAILED), cancelledSlot(S.FAILED)]))).toEqual({
+ status: "failed",
+ slots: 2,
+ ok: 0,
+ failed: 1,
+ cancelled: 1,
+ });
+ });
+
+ test("one completed among failures and cancellations → completed", () => {
+ expect(
+ summarise(status([{ state: S.COMPLETED }, failedSlot(S.TIMEOUT), cancelledSlot(S.FAILED)]))
+ ).toEqual({
+ status: "completed",
+ slots: 3,
+ ok: 1,
+ failed: 1,
+ cancelled: 1,
+ });
+ });
+
+ test("its result never carries a reason key", () => {
+ const outcome = summarise(status([failedSlot(S.FAILED)])) as unknown as Record<string, unknown>;
+
+ expect(outcome.reason).toBeUndefined();
+ });
+});
+
+describe("REQ-20 readTeamStatus reads <path>/status.json and degrades to an empty models map", () => {
+ let layout: TempLayout;
+ beforeEach(() => {
+ layout = makeTempLayout("teamstatus");
+ });
+ afterEach(() => layout.cleanup());
+
+ test("a readable status.json → its models", () => {
+ const models = { "model-a": { state: S.COMPLETED }, "model-b": { state: S.RUNNING } };
+ writeFileSync(join(layout.root, "status.json"), JSON.stringify({ models }));
+
+ expect(readTeamStatus(layout.root).models as unknown).toEqual(models);
+ });
+
+ test("no status.json → an empty models map, and summarise yields zero slots", () => {
+ const read = readTeamStatus(layout.root);
+
+ expect(read.models).toEqual({});
+ expect(summarise(read)).toMatchObject({ slots: 0, ok: 0, failed: 0, cancelled: 0 });
+ });
+
+ test("a torn status.json (rewritten in place, read mid-write) → an empty models map, not a throw", () => {
+ writeFileSync(join(layout.root, "status.json"), '{"models": {"model-a": {"state": "COMP');
+
+ expect(readTeamStatus(layout.root).models).toEqual({});
+ });
+});
diff --git a/packages/cli/src/test-helpers/contract-adapters.ts b/packages/cli/src/test-helpers/contract-adapters.ts
new file mode 100644
index 00000000..9612e88f
--- /dev/null
+++ b/packages/cli/src/test-helpers/contract-adapters.ts
@@ -0,0 +1,331 @@
+// packages/cli/src/test-helpers/contract-adapters.ts
+/**
+ * INFERRED glue, in one place. The contract names these symbols but not their exact shapes:
+ *
+ * - StreamJsonReducer: its constructor options beyond `onResult`, the method that ingests a
+ * stream-json line, the state getter, `settle`, and where refused transitions are recorded.
+ * Documented: `onResult: (summary) => TurnEnd` (required), `awaitInput()`, `beginTurn()`.
+ * - SessionManager: the class name and constructor (`SessionManagerOptions.hostPid` is
+ * documented), `recordTeamRun({ teamPath, slots, parentClaudeSessionId })` and
+ * `finishTeamRun(record, outcome)` (documented by name and argument).
+ * - team-orchestrator: `setupSession` (named, signature not given), `startModels(path, opts)`
+ * (named), `ModelState` member values, and the `spawnChild` seam's call shape.
+ *
+ * Every test asserts the SPEC; only these functions bend to the implementation. If a contract
+ * test fails with "ADAPTER:", fix this file, not the test.
+ */
+import { type ChildProcess, spawn as nodeSpawn } from "node:child_process";
+import * as sessionManagerModule from "../channel/session-manager.js";
+import * as reducerModule from "../channel/stream-json-reducer.js";
+import type { TurnEnd } from "../channel/stream-json-reducer.js";
+import * as orchestrator from "../team-orchestrator.js";
+import { FAKE_CHILD } from "./contract-mcp.js";
+
+type AnyRecord = Record<string, unknown>;
+type Fn = (...args: unknown[]) => unknown;
+
+export const KNOWN_STATES = [
+ "starting",
+ "running",
+ "tool_executing",
+ "waiting_for_input",
+ "finishing",
+ "completed",
+ "failed",
+ "timeout",
+ "cancelled",
+] as const;
+
+function method(obj: unknown, names: string[], what: string): Fn {
+ const o = obj as AnyRecord;
+ for (const name of names) {
+ if (typeof o?.[name] === "function") return (o[name] as Fn).bind(o);
+ }
+ throw new Error(
+ `ADAPTER: ${what}: none of ${names.join(", ")} exists — fix test-helpers/contract-adapters.ts`
+ );
+}
+
+// ------------------------------------------------------------------------------------------
+// StreamJsonReducer
+// ------------------------------------------------------------------------------------------
+
+export interface ReducerProbe {
+ reducer: AnyRecord;
+ /** Ingest one stream-json frame (serialised as one newline-terminated line). */
+ feed(frame: unknown): void;
+ state(): string;
+ /** The state after every step this probe drove (construction, feed, beginTurn, awaitInput, settle). */
+ snapshots: string[];
+ /** Every known state named in any argument of any state-change callback. */
+ mentioned: Set<string>;
+ stateChangeCalls(): number;
+ /** The reducer's state at the moment each onResult call ran. */
+ stateAtOnResult: string[];
+ anomalyCount(): number;
+ beginTurn(): void;
+ awaitInput(): void;
+ settle(state: string): void;
+ dispose(): void;
+}
+
+/** Reducers built by makeReducerProbe; a test file disposes them in afterEach so no stall timer outlives its test. */
+const liveReducers: AnyRecord[] = [];
+
+export function disposeReducerProbes(): void {
+ for (const r of liveReducers.splice(0)) {
+ if (typeof r.dispose === "function") (r.dispose as Fn).call(r);
+ }
+}
+
+function collectStates(value: unknown, into: Set<string>, depth = 0): void {
+ if (typeof value === "string") {
+ if ((KNOWN_STATES as readonly string[]).includes(value)) into.add(value);
+ return;
+ }
+ if (value && typeof value === "object" && depth < 2) {
+ for (const v of Object.values(value as AnyRecord)) collectStates(v, into, depth + 1);
+ }
+}
+
+export function makeReducerProbe(turnEnd: TurnEnd): ReducerProbe {
+ const Reducer = (reducerModule as unknown as AnyRecord).StreamJsonReducer as new (
+ opts: AnyRecord
+ ) => AnyRecord;
+ if (typeof Reducer !== "function")
+ throw new Error("ADAPTER: StreamJsonReducer is not exported as a class");
+
+ const mentioned = new Set<string>();
+ const stateAtOnResult: string[] = [];
+ const snapshots: string[] = [];
+ let calls = 0;
+
+ const readState = (): string => {
+ const r = reducer as AnyRecord;
+ for (const key of ["state", "status", "currentState"]) {
+ if (typeof r[key] === "string") return r[key] as string;
+ }
+ for (const key of ["getState", "getStatus", "currentState"]) {
+ if (typeof r[key] === "function") return String((r[key] as Fn).call(r));
+ }
+ throw new Error("ADAPTER: no state getter on StreamJsonReducer");
+ };
+
+ const onStateChange = (...args: unknown[]) => {
+ calls += 1;
+ for (const a of args) collectStates(a, mentioned);
+ };
+
+ // StreamJsonReducerOptions (exported interface): `sessionId` and `callback: ReducerCallback`
+ // are required alongside `onResult`. `callback(sessionId, event)` reports each state change.
+ const reducer: AnyRecord = new Reducer({
+ sessionId: "contract-reducer",
+ callback: onStateChange,
+ onResult: (_summary: unknown): TurnEnd => {
+ stateAtOnResult.push(readState());
+ return turnEnd;
+ },
+ });
+ liveReducers.push(reducer);
+
+ const snap = () => snapshots.push(readState());
+ snap();
+
+ const feedFn = method(
+ reducer,
+ ["handleLine", "processLine", "pushLine", "ingestLine", "push", "feed", "write", "ingest"],
+ "reducer line ingestion"
+ );
+
+ return {
+ reducer,
+ feed(frame) {
+ feedFn(`${JSON.stringify(frame)}\n`);
+ snap();
+ },
+ state: readState,
+ snapshots,
+ mentioned,
+ stateChangeCalls: () => calls,
+ stateAtOnResult,
+ anomalyCount() {
+ const r = reducer as AnyRecord;
+ const candidates: unknown[] = [
+ r.anomalies,
+ typeof r.getAnomalies === "function" ? (r.getAnomalies as Fn).call(r) : undefined,
+ (r.diagnostics as AnyRecord | undefined)?.anomalies,
+ typeof r.getDiagnostics === "function"
+ ? ((r.getDiagnostics as Fn).call(r) as AnyRecord | undefined)?.anomalies
+ : undefined,
+ ];
+ const list = candidates.find((c) => Array.isArray(c)) as unknown[] | undefined;
+ if (!list) throw new Error("ADAPTER: cannot find the reducer's recorded anomalies");
+ return list.length;
+ },
+ beginTurn() {
+ method(reducer, ["beginTurn"], "beginTurn")();
+ snap();
+ },
+ awaitInput() {
+ method(reducer, ["awaitInput"], "awaitInput")();
+ snap();
+ },
+ settle(state) {
+ method(reducer, ["settle"], "settle")(state);
+ snap();
+ },
+ dispose() {
+ method(reducer, ["dispose"], "dispose")();
+ },
+ };
+}
+
+// ------------------------------------------------------------------------------------------
+// SessionManager (team record API)
+// ------------------------------------------------------------------------------------------
+
+export interface SessionManagerHandle {
+ sm: AnyRecord;
+ recordTeamRun(args: { teamPath: string; slots: number; parentClaudeSessionId?: string }): unknown;
+ finishTeamRun(record: unknown, outcome: unknown): unknown;
+ /**
+ * `SessionManager.getSession(id): SessionInfo` (public; its doc comment says it falls back to
+ * `<sessionsDir>/<id>/meta.json` for a session not in memory). Returns `{ info }` or `{ error }`
+ * so an unknown-id answer can be compared, whether it throws or returns.
+ */
+ getSession(id: string): { info?: AnyRecord; error?: string };
+ dispose(): Promise<void>;
+}
+
+/**
+ * Construct with the documented test override `hostPid`. `sessionsDir` is the documented
+ * `SessionManagerOptions.sessionsDir`; without it the manager reads CLAUDISH_SESSIONS_DIR.
+ */
+export function newSessionManager(
+ hostPid: number,
+ opts: { sessionsDir?: string } = {}
+): SessionManagerHandle {
+ const Ctor = (sessionManagerModule as unknown as AnyRecord).SessionManager as new (
+ opts: AnyRecord
+ ) => AnyRecord;
+ if (typeof Ctor !== "function")
+ throw new Error("ADAPTER: SessionManager is not exported as a class");
+ const sm = new Ctor(
+ opts.sessionsDir === undefined ? { hostPid } : { hostPid, sessionsDir: opts.sessionsDir }
+ );
+ return {
+ sm,
+ getSession(id) {
+ try {
+ return { info: method(sm, ["getSession"], "getSession")(id) as AnyRecord };
+ } catch (err) {
+ return { error: err instanceof Error ? err.message : String(err) };
+ }
+ },
+ recordTeamRun: (args) => method(sm, ["recordTeamRun"], "recordTeamRun")(args),
+ finishTeamRun: (record, outcome) =>
+ method(sm, ["finishTeamRun"], "finishTeamRun")(record, outcome),
+ async dispose() {
+ for (const name of ["shutdown", "dispose", "close", "stop"]) {
+ if (typeof sm[name] === "function") {
+ await (sm[name] as Fn).call(sm);
+ return;
+ }
+ }
+ },
+ };
+}
+
+// ------------------------------------------------------------------------------------------
+// team-orchestrator internals
+// ------------------------------------------------------------------------------------------
+
+/** `ModelState` member values; falls back to the member names when it is a type only. */
+export function modelStates(): Record<
+ "COMPLETED" | "FAILED" | "EMPTY" | "TIMEOUT" | "PENDING" | "RUNNING",
+ string
+> {
+ const ms = (orchestrator as unknown as AnyRecord).ModelState as AnyRecord | undefined;
+ const pick = (k: string) => (ms && typeof ms[k] === "string" ? (ms[k] as string) : k);
+ return {
+ COMPLETED: pick("COMPLETED"),
+ FAILED: pick("FAILED"),
+ EMPTY: pick("EMPTY"),
+ TIMEOUT: pick("TIMEOUT"),
+ PENDING: pick("PENDING"),
+ RUNNING: pick("RUNNING"),
+ };
+}
+
+/** INFERRED signature: `setupSession(sessionPath, models, input)` writes manifest.json and status.json. */
+export async function setupTeamSession(
+ dir: string,
+ models: string[],
+ input: string
+): Promise<void> {
+ const fn = (orchestrator as unknown as AnyRecord).setupSession as Fn | undefined;
+ if (typeof fn !== "function")
+ throw new Error("ADAPTER: team-orchestrator does not export setupSession");
+ await fn(dir, models, input);
+}
+
+export interface TeamHandleLike {
+ done: Promise<unknown>;
+}
+
+export async function startModels(dir: string, opts: AnyRecord): Promise<TeamHandleLike> {
+ const fn = (orchestrator as unknown as AnyRecord).startModels as Fn | undefined;
+ if (typeof fn !== "function")
+ throw new Error("ADAPTER: team-orchestrator does not export startModels");
+ return (await fn(dir, opts)) as TeamHandleLike;
+}
+
+export interface SpawnSeam {
+ spawnChild: (...args: unknown[]) => ChildProcess;
+ calls(): number;
+ children: ChildProcess[];
+}
+
+/**
+ * A `TeamRunOptions.spawnChild` seam. INFERRED call shape: node's `spawn(command, args, options)`;
+ * an object-shaped single argument `{ command, args, options }` is also accepted. Whatever the
+ * orchestrator asks to run, the contract fake runs instead, with the orchestrator's own options
+ * (stdio, detached, cwd) passed through so its process-group signalling still applies.
+ *
+ * `throwOn`: the 1-based call that throws synchronously, like a failed `spawn()`.
+ * `hang`: every child stays alive until signalled, whatever input it gets.
+ * `markerFor(n)`: file the n-th child writes when it receives SIGTERM.
+ */
+export function spawnSeam(opts: {
+ throwOn?: number;
+ error?: Error;
+ markerFor?: (n: number) => string;
+ hang?: boolean;
+}): SpawnSeam {
+ let n = 0;
+ const children: ChildProcess[] = [];
+ const spawnChild = (...args: unknown[]): ChildProcess => {
+ n += 1;
+ if (opts.throwOn === n) throw opts.error ?? new Error("contract: injected spawn failure");
+ const [a, b, c] = args;
+ let options: AnyRecord | undefined;
+ if (a && typeof a === "object" && !Array.isArray(a))
+ options = ((a as AnyRecord).options as AnyRecord | undefined) ?? undefined;
+ else options = (Array.isArray(b) ? c : b) as AnyRecord | undefined;
+ const baseEnv =
+ (options?.env as Record<string, string> | undefined) ??
+ (process.env as Record<string, string>);
+ const env: Record<string, string> = { ...baseEnv };
+ if (opts.markerFor) env.CONTRACT_FAKE_SIGTERM_MARKER = opts.markerFor(n);
+ // The task text reaches a team slot by a route the contract does not name (argument, file or
+ // stdin), so a slot that must stay alive is told so through its environment instead.
+ if (opts.hang) env.CONTRACT_FAKE_HANG = "1";
+ const child = nodeSpawn(process.execPath, [FAKE_CHILD], {
+ ...(options ?? {}),
+ env,
+ } as Parameters<typeof nodeSpawn>[2]);
+ children.push(child);
+ return child;
+ };
+ return { spawnChild, calls: () => n, children };
+}
diff --git a/packages/cli/src/test-helpers/contract-fake-child.ts b/packages/cli/src/test-helpers/contract-fake-child.ts
new file mode 100755
index 00000000..df882374
--- /dev/null
+++ b/packages/cli/src/test-helpers/contract-fake-child.ts
@@ -0,0 +1,201 @@
+#!/usr/bin/env bun
+// packages/cli/src/test-helpers/contract-fake-child.ts
+/**
+ * A stream-json stand-in for the claudish child, used by the *.contract.test.ts files through
+ * CLAUDISH_BIN (sessions, team slots) or a TeamRunOptions.spawnChild seam. Written from the
+ * public stream-json shape only; it never calls a model or the network.
+ *
+ * It emits `system:init` at start, then answers input. Behaviour is chosen by markers anywhere
+ * in the input it receives, so one executable serves every test:
+ *
+ * (no marker) each stream-json `user` line gets one assistant message and one success result;
+ * non-JSON input is answered once, at end of input
+ * @@TOOL@@ the answer runs one tool first: assistant tool_use, user tool_result, then text
+ * @@HANG@@ never answer and ignore end of input; live until signalled
+ * @@LINGER@@ after input ends, stay alive LINGER_MS before exiting 0 (holds `finishing` open)
+ * @@LATE@@ after input ends, emit assistant, user and tool_use frames, then exit 0
+ *
+ * Markers are also read from argv. Optional env: CONTRACT_FAKE_SIGTERM_MARKER, a file written
+ * when SIGTERM arrives; CONTRACT_FAKE_HANG=1, behave as @@HANG@@ whatever the input.
+ */
+import { randomUUID } from "node:crypto";
+import { writeFileSync } from "node:fs";
+
+const LINGER_MS = 1_500;
+const LATE_GAP_MS = 150;
+const SAFETY_MS = Number(process.env.CONTRACT_FAKE_MAX_MS ?? 20_000);
+
+const argv = process.argv.slice(2);
+const sidAt = argv.indexOf("--session-id");
+const childSessionId = sidAt >= 0 && argv[sidAt + 1] ? argv[sidAt + 1] : randomUUID();
+
+let hang = process.env.CONTRACT_FAKE_HANG === "1";
+let linger = false;
+let late = false;
+let turns = 0;
+let sawJsonTurn = false;
+let pendingText = "";
+
+process.stdout.on("error", () => process.exit(0));
+process.on("SIGTERM", () => {
+ const marker = process.env.CONTRACT_FAKE_SIGTERM_MARKER;
+ if (marker) {
+ try {
+ writeFileSync(marker, String(process.pid));
+ } catch {
+ // the marker is evidence only
+ }
+ }
+ process.exit(143);
+});
+// Never outlive a broken test by more than SAFETY_MS. Not unref'd: it also keeps @@HANG@@ alive.
+setTimeout(() => process.exit(3), SAFETY_MS);
+
+function emit(frame: unknown): void {
+ process.stdout.write(`${JSON.stringify(frame)}\n`);
+}
+
+function assistantText(id: string, text: string): unknown {
+ return {
+ type: "assistant",
+ message: {
+ id,
+ type: "message",
+ role: "assistant",
+ model: "contract-fake",
+ content: [{ type: "text", text }],
+ stop_reason: "end_turn",
+ usage: { input_tokens: 1, output_tokens: 1 },
+ },
+ session_id: childSessionId,
+ };
+}
+
+function assistantToolUse(id: string, toolUseId: string): unknown {
+ return {
+ type: "assistant",
+ message: {
+ id,
+ type: "message",
+ role: "assistant",
+ model: "contract-fake",
+ content: [
+ {
+ type: "tool_use",
+ id: toolUseId,
+ name: "Read",
+ input: { file_path: "contract-fake.txt" },
+ },
+ ],
+ stop_reason: "tool_use",
+ usage: { input_tokens: 1, output_tokens: 1 },
+ },
+ session_id: childSessionId,
+ };
+}
+
+function userToolResult(toolUseId: string): unknown {
+ return {
+ type: "user",
+ message: {
+ role: "user",
+ content: [{ type: "tool_result", tool_use_id: toolUseId, content: "ok" }],
+ },
+ session_id: childSessionId,
+ };
+}
+
+function answer(withTool: boolean): void {
+ turns += 1;
+ if (withTool) {
+ const toolUseId = `toolu_contractfake_${turns}`;
+ emit(assistantToolUse(`msg_contractfake_${turns}_tool`, toolUseId));
+ emit(userToolResult(toolUseId));
+ }
+ emit(assistantText(`msg_contractfake_${turns}`, `contract reply ${turns}`));
+ emit({
+ type: "result",
+ subtype: "success",
+ is_error: false,
+ duration_ms: 1,
+ duration_api_ms: 1,
+ num_turns: turns,
+ result: `contract reply ${turns}`,
+ session_id: childSessionId,
+ total_cost_usd: 0,
+ usage: { input_tokens: 1, output_tokens: 1 },
+ });
+}
+
+function noteMarkers(text: string): void {
+ if (text.includes("@@HANG@@")) hang = true;
+ if (text.includes("@@LINGER@@")) linger = true;
+ if (text.includes("@@LATE@@")) late = true;
+}
+
+function onLine(raw: string): void {
+ const text = raw.trim();
+ if (!text) return;
+ noteMarkers(text);
+ let isUserFrame = false;
+ try {
+ const frame = JSON.parse(text) as { type?: unknown };
+ isUserFrame = Boolean(frame) && typeof frame === "object" && frame.type === "user";
+ } catch {
+ isUserFrame = false;
+ }
+ if (!isUserFrame) {
+ pendingText += `${text}\n`;
+ return;
+ }
+ sawJsonTurn = true;
+ if (hang) return;
+ answer(text.includes("@@TOOL@@"));
+}
+
+async function onEnd(): Promise<void> {
+ if (hang) return; // live until signalled or the safety timer fires
+ if (!sawJsonTurn && pendingText.trim() !== "") answer(pendingText.includes("@@TOOL@@"));
+ if (late) {
+ await Bun.sleep(LATE_GAP_MS);
+ emit(assistantText(`msg_contractfake_late_${turns}`, "a frame after the final result"));
+ emit(userToolResult(`toolu_contractfake_late_${turns}`));
+ emit(
+ assistantToolUse(`msg_contractfake_late_tool_${turns}`, `toolu_contractfake_late_${turns}`)
+ );
+ await Bun.sleep(LATE_GAP_MS);
+ }
+ if (linger) await Bun.sleep(LINGER_MS);
+ process.exit(0);
+}
+
+noteMarkers(argv.join(" "));
+
+emit({
+ type: "system",
+ subtype: "init",
+ session_id: childSessionId,
+ model: "contract-fake",
+ cwd: process.cwd(),
+ tools: [],
+ mcp_servers: [],
+ permissionMode: "default",
+ apiKeySource: "none",
+});
+
+let buffer = "";
+process.stdin.setEncoding("utf8");
+process.stdin.on("data", (chunk: string | Buffer) => {
+ buffer += chunk.toString();
+ for (let at = buffer.indexOf("\n"); at >= 0; at = buffer.indexOf("\n")) {
+ onLine(buffer.slice(0, at));
+ buffer = buffer.slice(at + 1);
+ }
+});
+process.stdin.on("end", () => {
+ if (buffer) {
+ onLine(buffer);
+ buffer = "";
+ }
+ void onEnd();
+});
diff --git a/packages/cli/src/test-helpers/contract-mcp.ts b/packages/cli/src/test-helpers/contract-mcp.ts
new file mode 100644
index 00000000..53b1c0ba
--- /dev/null
+++ b/packages/cli/src/test-helpers/contract-mcp.ts
@@ -0,0 +1,360 @@
+// packages/cli/src/test-helpers/contract-mcp.ts
+/**
+ * Drives a real claudish MCP server over stdio (newline-delimited JSON-RPC, the MCP stdio
+ * transport) for the *.contract.test.ts files. The test process stands in for Claude Code:
+ * it is the server's parent, so a correct `hostPid` equals `process.pid` (design §8.1 9b).
+ *
+ * The protocol is public. What is NOT in the contract, and is therefore isolated in the
+ * "tool adapters" section at the bottom, is the exact argument and result field names of the
+ * claudish tools. Each adapter is marked INFERRED; fix a mismatch there, once.
+ */
+import { chmodSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import type { TempLayout } from "./contract-records.js";
+
+export const SRC_DIR = join(import.meta.dir, "..");
+export const PACKAGE_DIR = join(SRC_DIR, "..");
+export const SERVER_ENTRY = join(SRC_DIR, "index.ts");
+export const FAKE_CHILD = join(import.meta.dir, "contract-fake-child.ts");
+/** Design §3.5 step 1: the dispatcher reads `extra._meta?.["claudecode/toolUseId"]`. */
+export const TOOL_USE_ID_META_KEY_FROM_SPEC = "claudecode/toolUseId";
+export const FAKE_MODEL = "contract-fake-model";
+
+/**
+ * A server environment built from scratch, so nothing leaks in from the shell that runs the
+ * tests (for example a CLAUDE_CODE_SESSION_ID set because the tests run inside Claude Code).
+ * `undefined` in `extra` deletes a key.
+ */
+export function serverEnv(
+ layout: TempLayout,
+ extra: Record<string, string | undefined> = {}
+): Record<string, string> {
+ chmodSync(FAKE_CHILD, 0o755);
+ const env: Record<string, string> = {
+ PATH: process.env.PATH ?? "",
+ HOME: layout.home,
+ TMPDIR: tmpdir(),
+ CLAUDISH_SESSIONS_DIR: layout.sessionsDir,
+ CLAUDISH_BIN: FAKE_CHILD,
+ CLAUDE_CONFIG_DIR: layout.configDir,
+ NO_COLOR: "1",
+ };
+ for (const [key, value] of Object.entries(extra)) {
+ if (value === undefined) delete env[key];
+ else env[key] = value;
+ }
+ return env;
+}
+
+export interface ToolResult {
+ isError: boolean;
+ text: string;
+ json: Record<string, unknown> | undefined;
+ raw: unknown;
+}
+
+interface Pending {
+ resolve: (msg: Record<string, unknown>) => void;
+ reject: (err: Error) => void;
+}
+
+export interface ToolInfo {
+ name: string;
+ inputSchema?: { properties?: Record<string, unknown>; required?: string[] };
+}
+
+export class McpServer {
+ readonly proc: ReturnType<typeof Bun.spawn>;
+ readonly pid: number;
+ stderrText = "";
+ readonly notifications: Record<string, unknown>[] = [];
+ private nextId = 1;
+ private readonly pending = new Map<number, Pending>();
+ private tools: ToolInfo[] | undefined;
+ private exited = false;
+
+ private constructor(command: string[], env: Record<string, string>, cwd: string) {
+ this.proc = Bun.spawn(command, { cwd, env, stdin: "pipe", stdout: "pipe", stderr: "pipe" });
+ this.pid = this.proc.pid;
+ void this.pumpStdout();
+ void this.pumpStderr();
+ void this.proc.exited.then(() => {
+ this.exited = true;
+ for (const p of this.pending.values()) {
+ p.reject(new Error(`MCP server exited; stderr tail:\n${this.stderrText.slice(-3000)}`));
+ }
+ this.pending.clear();
+ });
+ }
+
+ /** Start `bun <src>/index.ts --mcp` (the compiled-binary branch, §8.1 9b) unless `command` is given. */
+ static async start(opts: {
+ env: Record<string, string>;
+ cwd: string;
+ command?: string[];
+ }): Promise<McpServer> {
+ const server = new McpServer(
+ opts.command ?? [process.execPath, SERVER_ENTRY, "--mcp"],
+ opts.env,
+ opts.cwd
+ );
+ await server.request("initialize", {
+ protocolVersion: "2025-06-18",
+ capabilities: {},
+ clientInfo: { name: "claudish-contract-tests", version: "0.0.0" },
+ });
+ server.notify("notifications/initialized", {});
+ return server;
+ }
+
+ private async pumpStdout(): Promise<void> {
+ const stdout = this.proc.stdout as ReadableStream<Uint8Array>;
+ const reader = stdout.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+ for (let at = buffer.indexOf("\n"); at >= 0; at = buffer.indexOf("\n")) {
+ const line = buffer.slice(0, at).trim();
+ buffer = buffer.slice(at + 1);
+ if (line) this.onMessage(line);
+ }
+ }
+ }
+
+ private async pumpStderr(): Promise<void> {
+ const stderr = this.proc.stderr as ReadableStream<Uint8Array>;
+ const reader = stderr.getReader();
+ const decoder = new TextDecoder();
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ this.stderrText = (this.stderrText + decoder.decode(value, { stream: true })).slice(-50_000);
+ }
+ }
+
+ private onMessage(line: string): void {
+ let msg: Record<string, unknown>;
+ try {
+ msg = JSON.parse(line) as Record<string, unknown>;
+ } catch {
+ return; // not protocol traffic
+ }
+ const id = msg.id;
+ if (typeof id === "number" && ("result" in msg || "error" in msg) && this.pending.has(id)) {
+ const p = this.pending.get(id) as Pending;
+ this.pending.delete(id);
+ p.resolve(msg);
+ return;
+ }
+ if ("method" in msg && id !== undefined) {
+ // A server-to-client request (ping, roots/list, ...): answer with an empty result.
+ this.write({ jsonrpc: "2.0", id, result: {} });
+ return;
+ }
+ this.notifications.push(msg);
+ }
+
+ private write(msg: unknown): void {
+ const sink = this.proc.stdin as { write(s: string): unknown; flush?(): unknown };
+ sink.write(`${JSON.stringify(msg)}\n`);
+ sink.flush?.();
+ }
+
+ notify(method: string, params: unknown): void {
+ this.write({ jsonrpc: "2.0", method, params });
+ }
+
+ request(method: string, params: unknown, timeoutMs = 20_000): Promise<Record<string, unknown>> {
+ if (this.exited)
+ return Promise.reject(
+ new Error(`MCP server already exited; stderr:\n${this.stderrText.slice(-3000)}`)
+ );
+ const id = this.nextId++;
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.pending.delete(id);
+ reject(
+ new Error(
+ `MCP ${method} timed out after ${timeoutMs} ms; stderr tail:\n${this.stderrText.slice(-3000)}`
+ )
+ );
+ }, timeoutMs);
+ this.pending.set(id, {
+ resolve: (msg) => {
+ clearTimeout(timer);
+ resolve(msg);
+ },
+ reject: (err) => {
+ clearTimeout(timer);
+ reject(err);
+ },
+ });
+ this.write({ jsonrpc: "2.0", id, method, params });
+ });
+ }
+
+ async listTools(): Promise<ToolInfo[]> {
+ if (!this.tools) {
+ const msg = await this.request("tools/list", {});
+ this.tools = ((msg.result as { tools?: ToolInfo[] } | undefined)?.tools ?? []) as ToolInfo[];
+ }
+ return this.tools;
+ }
+
+ async callTool(
+ name: string,
+ args: Record<string, unknown>,
+ meta?: Record<string, unknown>
+ ): Promise<ToolResult> {
+ const params: Record<string, unknown> = { name, arguments: args };
+ if (meta) params._meta = meta;
+ const msg = await this.request("tools/call", params);
+ if (msg.error) {
+ const text = String(
+ (msg.error as { message?: unknown }).message ?? JSON.stringify(msg.error)
+ );
+ return { isError: true, text, json: undefined, raw: msg };
+ }
+ const result = (msg.result ?? {}) as {
+ content?: Array<{ type?: string; text?: string }>;
+ isError?: boolean;
+ };
+ const text = (result.content ?? [])
+ .map((c) => (typeof c.text === "string" ? c.text : ""))
+ .join("\n");
+ let json: Record<string, unknown> | undefined;
+ try {
+ const parsed: unknown = JSON.parse(text);
+ json = parsed && typeof parsed === "object" ? (parsed as Record<string, unknown>) : undefined;
+ } catch {
+ json = undefined;
+ }
+ return { isError: Boolean(result.isError), text, json, raw: msg };
+ }
+
+ async close(): Promise<void> {
+ if (!this.exited) {
+ try {
+ (this.proc.stdin as { end?(): unknown }).end?.();
+ } catch {
+ // already closed
+ }
+ const ended = await Promise.race([
+ this.proc.exited.then(() => true),
+ Bun.sleep(3_000).then(() => false),
+ ]);
+ if (!ended) {
+ this.proc.kill("SIGKILL");
+ await this.proc.exited;
+ }
+ }
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// Tool adapters. INFERRED: argument and result field names of the claudish tools are not in the
+// contract. Tool NAMES (create_session, send_input, get_session, get_output, get_diagnostics,
+// cancel_session, list_sessions, team) and `timeout_seconds`, `session_id`, `monitor_record`
+// come from the design text. Where a name could vary, the adapter reads the tool's own
+// inputSchema from tools/list instead of guessing.
+// ---------------------------------------------------------------------------------------------
+
+async function pickArgKey(server: McpServer, tool: string, preferred: string[]): Promise<string> {
+ const info = (await server.listTools()).find((t) => t.name === tool);
+ const props = Object.keys(info?.inputSchema?.properties ?? {});
+ return preferred.find((k) => props.includes(k)) ?? (preferred[0] as string);
+}
+
+/** Find a string field anywhere in a JSON value, depth-first, by key. */
+export function findField(value: unknown, key: string, depth = 0): unknown {
+ if (!value || typeof value !== "object" || depth > 6) return undefined;
+ const obj = value as Record<string, unknown>;
+ if (key in obj) return obj[key];
+ for (const child of Object.values(obj)) {
+ const hit = findField(child, key, depth + 1);
+ if (hit !== undefined) return hit;
+ }
+ return undefined;
+}
+
+export interface CreateArgs {
+ model?: string;
+ prompt?: string;
+ timeout_seconds?: number;
+}
+
+export async function createSession(
+ server: McpServer,
+ args: CreateArgs,
+ toolUseId?: string
+): Promise<{ sessionId: string | undefined; result: ToolResult }> {
+ const callArgs: Record<string, unknown> = { model: args.model ?? FAKE_MODEL };
+ if (args.prompt !== undefined) callArgs.prompt = args.prompt;
+ if (args.timeout_seconds !== undefined) callArgs.timeout_seconds = args.timeout_seconds;
+ const meta =
+ toolUseId === undefined ? undefined : { [TOOL_USE_ID_META_KEY_FROM_SPEC]: toolUseId };
+ const result = await server.callTool("create_session", callArgs, meta);
+ const fromJson = findField(result.json, "session_id") ?? findField(result.json, "sessionId");
+ const fromText = /"?session_?[iI]d"?\s*[:=]\s*"?([A-Za-z0-9][A-Za-z0-9._-]*)/.exec(
+ result.text
+ )?.[1];
+ const sessionId = typeof fromJson === "string" ? fromJson : fromText;
+ return { sessionId, result };
+}
+
+export async function sendInput(
+ server: McpServer,
+ sessionId: string,
+ text: string
+): Promise<ToolResult> {
+ const key = await pickArgKey(server, "send_input", [
+ "input",
+ "message",
+ "text",
+ "content",
+ "prompt",
+ ]);
+ return server.callTool("send_input", { session_id: sessionId, [key]: text });
+}
+
+export function sessionTool(
+ server: McpServer,
+ tool: string,
+ sessionId: string
+): Promise<ToolResult> {
+ return server.callTool(tool, { session_id: sessionId });
+}
+
+/**
+ * The session's status as `get_diagnostics` reports it, or undefined. The server exposes no
+ * `get_session` tool (tools/list); `get_diagnostics` is the documented per-id tool, and its
+ * result carries `status` for a live session and for one read back from disk.
+ */
+export async function sessionStatus(
+ server: McpServer,
+ sessionId: string
+): Promise<string | undefined> {
+ const r = await sessionTool(server, "get_diagnostics", sessionId);
+ const status = findField(r.json, "status");
+ if (typeof status === "string") return status;
+ return /"status"\s*:\s*"([a-z_]+)"/.exec(r.text)?.[1];
+}
+
+export async function teamCall(
+ server: McpServer,
+ mode: string,
+ args: { path: string; models?: string[]; input?: string }
+): Promise<ToolResult> {
+ const pathKey = await pickArgKey(server, "team", ["path", "session_path", "sessionPath"]);
+ const call: Record<string, unknown> = { mode, [pathKey]: args.path };
+ if (args.models) call.models = args.models;
+ if (args.input !== undefined) {
+ const inputKey = await pickArgKey(server, "team", ["input", "prompt", "task"]);
+ call[inputKey] = args.input;
+ }
+ return server.callTool("team", call);
+}
diff --git a/packages/cli/src/test-helpers/contract-records.ts b/packages/cli/src/test-helpers/contract-records.ts
new file mode 100644
index 00000000..8f875487
--- /dev/null
+++ b/packages/cli/src/test-helpers/contract-records.ts
@@ -0,0 +1,268 @@
+// packages/cli/src/test-helpers/contract-records.ts
+/**
+ * Shared helpers for the *.contract.test.ts files (session records, design §3.2-§3.5).
+ *
+ * Written blind from the specification and the public contract. Nothing here knows how
+ * claudish implements the records; every rule below is quoted from the design so a failing
+ * assertion names the rule it broke.
+ */
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ realpathSync,
+ rmSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { isAbsolute, join } from "node:path";
+
+/** §3.5: tool-use ids, env ids and host-record ids. */
+export const CLAUDE_ID_PATTERN = /^[A-Za-z0-9_-]{8,128}$/;
+/** §3.3 rule 2. */
+export const SESSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
+/** §3.3: a team record id is "team-" + 8 hex. */
+export const TEAM_RECORD_ID_PATTERN = /^team-[0-9a-f]{8}$/;
+/** Terminal session states (spec "Facts"; design §5.6). */
+export const SESSION_TERMINAL_STATES = ["completed", "failed", "timeout", "cancelled"] as const;
+
+export interface TempLayout {
+ root: string;
+ sessionsDir: string;
+ home: string;
+ configDir: string;
+ cwd: string;
+ cleanup(): void;
+}
+
+/** One isolated tree per test. realpath so macOS /var vs /private/var never decides a comparison. */
+export function makeTempLayout(label: string): TempLayout {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), `claudish-contract-${label}-`)));
+ const layout = {
+ root,
+ sessionsDir: join(root, "sessions"),
+ home: join(root, "home"),
+ configDir: join(root, "claude-config"),
+ cwd: join(root, "cwd"),
+ };
+ for (const dir of [layout.sessionsDir, layout.home, layout.configDir, layout.cwd]) {
+ mkdirSync(dir, { recursive: true });
+ }
+ return { ...layout, cleanup: () => rmSync(root, { recursive: true, force: true }) };
+}
+
+/** Poll until `probe` yields a value that is not undefined/null/false. Never a guessed sleep. */
+export async function waitFor<T>(
+ probe: () => T | undefined | null | false | Promise<T | undefined | null | false>,
+ opts: { what: string; timeoutMs?: number; intervalMs?: number }
+): Promise<T> {
+ const timeoutMs = opts.timeoutMs ?? 5_000;
+ const deadline = Date.now() + timeoutMs;
+ for (;;) {
+ const value = await probe();
+ if (value !== undefined && value !== null && value !== false) return value as T;
+ if (Date.now() > deadline)
+ throw new Error(`timed out after ${timeoutMs} ms waiting for ${opts.what}`);
+ await Bun.sleep(opts.intervalMs ?? 25);
+ }
+}
+
+/** Parse a JSON file; undefined when missing or not (yet) whole. A session meta.json is not atomic (§3.1). */
+export function readJson(path: string): Record<string, unknown> | undefined {
+ try {
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
+ return parsed && typeof parsed === "object" ? (parsed as Record<string, unknown>) : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+export interface WaitLine {
+ wait: "open" | "closed";
+ since: string;
+ turns?: number;
+ at?: string;
+ to?: string;
+}
+
+/**
+ * Read `<dir>/waits.jsonl` (§3.3). Returns undefined when the file does not exist.
+ * Only newline-terminated lines are returned; a complete line that does not parse is a defect,
+ * so it throws instead of being skipped.
+ */
+export function readWaitLines(sessionDir: string): WaitLine[] | undefined {
+ const path = join(sessionDir, "waits.jsonl");
+ if (!existsSync(path)) return undefined;
+ const text = readFileSync(path, "utf8");
+ const complete = text.endsWith("\n") ? text : text.slice(0, text.lastIndexOf("\n") + 1);
+ return complete
+ .split("\n")
+ .filter((line) => line.trim() !== "")
+ .map((line) => {
+ try {
+ return JSON.parse(line) as WaitLine;
+ } catch {
+ throw new Error(`waits.jsonl holds a complete line that is not JSON: ${line}`);
+ }
+ });
+}
+
+/**
+ * §3.3: every open line is followed by exactly one closed line repeating its `since`;
+ * lines alternate open/closed, starting with open. Returns the violations, [] when sound.
+ * `allowTrailingOpen` admits a final open line (a wait still in progress).
+ */
+export function waitPairingViolations(lines: WaitLine[], allowTrailingOpen: boolean): string[] {
+ const violations: string[] = [];
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ const expected = i % 2 === 0 ? "open" : "closed";
+ if (line.wait !== expected)
+ violations.push(`line ${i + 1} is "${line.wait}", expected "${expected}"`);
+ if (typeof line.since !== "string" || Number.isNaN(Date.parse(line.since))) {
+ violations.push(`line ${i + 1} has no ISO "since"`);
+ }
+ if (line.wait === "open" && !(Number.isInteger(line.turns) && (line.turns as number) >= 0)) {
+ violations.push(`open line ${i + 1} has no integer "turns"`);
+ }
+ if (line.wait === "closed") {
+ const open = lines[i - 1];
+ if (open && open.since !== line.since)
+ violations.push(`closed line ${i + 1} does not repeat its open line's "since"`);
+ if (typeof line.at !== "string" || Number.isNaN(Date.parse(line.at)))
+ violations.push(`closed line ${i + 1} has no ISO "at"`);
+ else if (Date.parse(line.at) < Date.parse(line.since))
+ violations.push(`closed line ${i + 1} closes before it opened`);
+ if (typeof line.to !== "string" || line.to === "waiting_for_input")
+ violations.push(`closed line ${i + 1} has a bad "to"`);
+ }
+ if (Buffer.byteLength(JSON.stringify(line)) >= 200)
+ violations.push(`line ${i + 1} is not < 200 bytes`);
+ }
+ if (!allowTrailingOpen && lines.length % 2 === 1) violations.push("the last wait is still open");
+ return violations;
+}
+
+const isPositiveInt = (x: unknown): x is number =>
+ typeof x === "number" && Number.isInteger(x) && x > 0;
+
+/**
+ * §3.3 `spawn.json` schema rules 1-4, plus "sessionId equals the record's directory name",
+ * the kind-specific key sets, and the on-disk format `JSON.stringify(record, null, 2)`.
+ * Returns the violated rules; [] means the record is valid.
+ */
+export function spawnRecordViolations(text: string, dirName: string): string[] {
+ let rec: Record<string, unknown>;
+ try {
+ rec = JSON.parse(text) as Record<string, unknown>;
+ } catch {
+ return ["spawn.json is not valid JSON"];
+ }
+ const v: string[] = [];
+ if (text.trimEnd() !== JSON.stringify(rec, null, 2))
+ v.push("format: not JSON.stringify(record, null, 2), one key per line");
+ // Rule 1
+ if (rec.schema !== 1) v.push(`rule 1: schema is ${JSON.stringify(rec.schema)}, not 1`);
+ if (rec.kind !== "session" && rec.kind !== "team")
+ v.push(`rule 1: kind is ${JSON.stringify(rec.kind)}`);
+ // Rule 2
+ if (typeof rec.sessionId !== "string" || !SESSION_ID_PATTERN.test(rec.sessionId))
+ v.push("rule 2: sessionId pattern");
+ if (rec.sessionId !== dirName)
+ v.push(`sessionId ${JSON.stringify(rec.sessionId)} is not the directory name ${dirName}`);
+ if (typeof rec.startedAt !== "string" || Number.isNaN(Date.parse(rec.startedAt)))
+ v.push("rule 2: startedAt is not a date");
+ if (!isPositiveInt(rec.hostPid)) v.push("rule 2: hostPid is not a positive integer");
+ if (!isPositiveInt(rec.mcpPid)) v.push("rule 2: mcpPid is not a positive integer");
+ if ("launcherPid" in rec) {
+ if (!isPositiveInt(rec.launcherPid))
+ v.push("rule 2: launcherPid present but not a positive integer");
+ if (rec.launcherPid === rec.hostPid || rec.launcherPid === rec.mcpPid)
+ v.push("rule 2: launcherPid equals hostPid or mcpPid");
+ }
+ // Rule 3
+ if ("parentClaudeSessionId" in rec) {
+ const p = rec.parentClaudeSessionId;
+ if (typeof p !== "string" || !CLAUDE_ID_PATTERN.test(p))
+ v.push('rule 3: parentClaudeSessionId present but invalid (never null, never "")');
+ }
+ // Rule 4
+ if (rec.kind === "session") {
+ const t = rec.timeoutSeconds;
+ if (!(typeof t === "number" && Number.isInteger(t) && t >= 1 && t <= 3600))
+ v.push(`rule 4: timeoutSeconds ${JSON.stringify(t)} not an integer in 1..3600`);
+ if ("model" in rec && typeof rec.model !== "string") v.push("rule 4: model is not a string");
+ if ("claudeSessionId" in rec && typeof rec.claudeSessionId !== "string")
+ v.push("rule 4: claudeSessionId is not a string");
+ for (const k of ["teamPath", "slots"])
+ if (k in rec) v.push(`kind session carries team-only key ${k}`);
+ }
+ if (rec.kind === "team") {
+ if (typeof rec.teamPath !== "string" || !isAbsolute(rec.teamPath))
+ v.push("rule 4: teamPath is not an absolute path string");
+ if (!isPositiveInt(rec.slots)) v.push("rule 4: slots is not a positive integer");
+ for (const k of ["model", "timeoutSeconds", "claudeSessionId"])
+ if (k in rec) v.push(`kind team carries session-only key ${k}`);
+ }
+ return v;
+}
+
+/** Names in a directory, sorted; [] when it does not exist. */
+export function entries(dir: string): string[] {
+ try {
+ return readdirSync(dir).sort();
+ } catch {
+ return [];
+ }
+}
+
+/** Record directories named team-* under a sessions dir. */
+export function teamRecordDirs(sessionsDir: string): string[] {
+ return entries(sessionsDir).filter((name) => name.startsWith("team-"));
+}
+
+/** Liveness by signal 0; EPERM still means the pid exists. */
+export function pidAlive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (err) {
+ return (err as NodeJS.ErrnoException).code === "EPERM";
+ }
+}
+
+/** The parent pid of `pid` from the process table, or undefined. */
+export function ppidOf(pid: number): number | undefined {
+ const out = Bun.spawnSync(["ps", "-o", "ppid=", "-p", String(pid)]);
+ const n = Number.parseInt(out.stdout.toString().trim(), 10);
+ return Number.isFinite(n) ? n : undefined;
+}
+
+/** §3.5 fast path: the project directory name is the cwd with every char outside [A-Za-z0-9] replaced by "-". */
+export function sanitisedProjectName(cwd: string): string {
+ return cwd.replace(/[^A-Za-z0-9]/g, "-");
+}
+
+/** One transcript line in which the tool-use id appears quoted, the way a tool_use block carries it. */
+export function transcriptLineWithToolUse(toolUseId: string): string {
+ return `${JSON.stringify({
+ type: "assistant",
+ message: {
+ role: "assistant",
+ content: [
+ { type: "tool_use", id: toolUseId, name: "mcp__claudish__create_session", input: {} },
+ ],
+ },
+ })}\n`;
+}
+
+/** A transcript line that mentions nothing interesting, for padding. */
+export function fillerLine(n: number): string {
+ return `${JSON.stringify({ type: "user", message: { role: "user", content: `filler ${n} ${"x".repeat(200)}` } })}\n`;
+}
+
+/** A fresh valid Claude-style id with a readable prefix. */
+export function claudeId(prefix: string): string {
+ return `${prefix}-${crypto.randomUUID()}`;
+}