Skip to content

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

test(mcp): add the fake interactive child and real-magmux pane suites

Jack Rudenko108d2695e881
diff --git a/packages/cli/src/pane/pane-child-real-claudish.integration.test.ts b/packages/cli/src/pane/pane-child-real-claudish.integration.test.ts
new file mode 100644
index 00000000..9a598f42
--- /dev/null
+++ b/packages/cli/src/pane/pane-child-real-claudish.integration.test.ts
@@ -0,0 +1,129 @@
+/**
+ * The REAL pane child claudish, hermetically (architecture §12.2, X-M6): the launcher
+ * execs this tree's `src/index.ts` (CLAUDISH_BIN), and that claudish launches the fake
+ * child in "claude" mode as Claude Code (CLAUDE_PATH), with a native model so no proxy
+ * request is ever made. The fake dumps the argv, env, cwd and `--settings` it was given.
+ */
+
+import { afterAll, describe, expect, test } from "bun:test";
+import { existsSync, readFileSync } from "node:fs";
+import { join } from "node:path";
+import { startPaneSession } from "./pane-session.js";
+import {
+ MAGMUX,
+ NO_MAGMUX_MESSAGE,
+ type PaneTestEnv,
+ killLeftovers,
+ makePaneTestEnv,
+ waitNoOrphans,
+ writeFakeClaudeWrapper,
+} from "./test-helpers/hermetic-env.js";
+
+const INDEX = join(import.meta.dir, "..", "index.ts");
+const envs: PaneTestEnv[] = [];
+afterAll(() => {
+ for (const t of envs) {
+ killLeftovers({ sockRoot: t.sockRoot });
+ t.cleanup();
+ }
+});
+
+async function run(callerFlags: string[] = []) {
+ const t = makePaneTestEnv();
+ envs.push(t);
+ const dump = join(t.tmp, "claude-dump.json");
+ const tokenFile = join(t.tmp, "tokens.json");
+ const env = {
+ ...t.env,
+ CLAUDISH_BIN: INDEX,
+ CLAUDE_PATH: writeFakeClaudeWrapper(t.tmp),
+ FAKE_CLAUDE_DUMP: dump,
+ PANE_TEST_CANARY: "kept",
+ CLAUDE_CODE_CHILD_SESSION: "1",
+ // an MCP server started by a wrapped claudish inherits a claudish-marked watchdog (D22)
+ CLAUDE_CODE_RETRY_WATCHDOG: "1",
+ CLAUDISH_SET_RETRY_WATCHDOG: "1",
+ CONTRACT_FAKE_MAX_MS: "60000",
+ };
+ const uuid = crypto.randomUUID();
+ const s = await startPaneSession({
+ kind: "s",
+ label: "real",
+ callerFlags,
+ spawnModel: "haiku",
+ cwd: t.cwd,
+ sessionUuid: uuid,
+ transcriptPath: t.transcriptPathFor(uuid),
+ slotEnv: { CLAUDISH_TOKEN_FILE: tokenFile },
+ shape: "one-shot",
+ initialPrompt: "Reply with exactly PEAR.",
+ readAvailable: true,
+ parentEnv: env,
+ sockRoot: t.sockRoot,
+ decide: (turn) =>
+ turn.answer ? { state: "COMPLETED" } : { state: "EMPTY", reason: "empty_output" },
+ onBlocked: () => "wait",
+ bootTimeoutMs: 45_000,
+ });
+ const snap = await Promise.race([
+ s.terminal,
+ Bun.sleep(60_000).then(() => {
+ throw new Error(`no terminal state: ${JSON.stringify(s.snapshot())}`);
+ }),
+ ]);
+ s.cancel();
+ await s.reaped();
+ const left = await waitNoOrphans({
+ sockRoot: t.sockRoot,
+ ids: [uuid],
+ pgids: [snap.panePid ?? 0],
+ });
+ return { t, snap, dump, tokenFile, left };
+}
+
+describe.skipIf(!MAGMUX)(
+ `the real pane child claudish (${MAGMUX ? "" : NO_MAGMUX_MESSAGE})`,
+ () => {
+ test("snapshot and cwd restored; overlay key; markers, child-session and watchdog stripped; answered", async () => {
+ const { t, snap, dump, tokenFile, left } = await run();
+ expect(snap.state).toBe("COMPLETED");
+ expect(left).toEqual({ processes: [], files: [] });
+ expect(existsSync(dump)).toBe(true);
+ const d = JSON.parse(readFileSync(dump, "utf8")) as {
+ argv: string[];
+ env: Record<string, string>;
+ cwd: string;
+ settings: Record<string, unknown> | string | null;
+ };
+ // child-env.ts re-applied the server's snapshot: the real SHELL (not the shim), the canary, the config dir
+ expect(d.env.SHELL).toBe("/bin/zsh");
+ expect(d.env.PANE_TEST_CANARY).toBe("kept");
+ expect(d.env.CLAUDE_CONFIG_DIR).toBe(t.configDir);
+ expect(d.cwd.endsWith("/cwd")).toBe(true);
+ for (const k of [
+ "CLAUDISH_PANE_CHILD",
+ "CLAUDISH_PANE_ENV",
+ "CLAUDISH_PANE_CWD",
+ "CLAUDE_CODE_CHILD_SESSION",
+ ])
+ expect(d.env[k]).toBeUndefined();
+ expect(d.env.CLAUDE_CODE_RETRY_WATCHDOG).toBeUndefined();
+ expect(typeof d.settings === "object" && d.settings !== null).toBe(true);
+ expect((d.settings as Record<string, unknown>).skipDangerousModePermissionPrompt).toBe(true);
+ expect(
+ JSON.stringify(d.settings).includes(tokenFile) || d.env.CLAUDISH_TOKEN_FILE === tokenFile
+ ).toBe(true);
+ expect(d.argv).toContain("--session-id");
+ expect(d.argv.some((a) => a === "-p" || a === "--print")).toBe(false);
+ }, 90_000);
+
+ test("a --team that slipped past the server walker: the child refuses with exit 64", async () => {
+ const { snap, left } = await run(["--team", "a,b"]);
+ expect(snap.state).toBe("FAILED");
+ expect(snap.reason).toBe("child_exited");
+ expect(snap.exitCode).toBe(64);
+ expect(snap.detail).toContain("pane child refused");
+ expect(left).toEqual({ processes: [], files: [] });
+ }, 90_000);
+ }
+);
diff --git a/packages/cli/src/pane/pane-live-claude.integration.test.ts b/packages/cli/src/pane/pane-live-claude.integration.test.ts
new file mode 100644
index 00000000..b3976ed0
--- /dev/null
+++ b/packages/cli/src/pane/pane-live-claude.integration.test.ts
@@ -0,0 +1,122 @@
+/**
+ * OPT-IN live tests: a real pane — this tree's claudish and the REAL Claude Code, native
+ * haiku — driven by PaneSession. Skipped unless the operator asks for them, because they
+ * spend money and need a login:
+ *
+ * CLAUDISH_PANE_LIVE=1 CLAUDE_CODE_OAUTH_TOKEN=<token> \
+ * bun test packages/cli/src/pane/pane-live-claude.integration.test.ts
+ *
+ * The config dir is hermetic (a temp CLAUDE_CONFIG_DIR is "Not logged in", so the token
+ * must come from the operator's env). The test never reads the keychain or ~/.claude.
+ */
+
+import { afterAll, describe, expect, test } from "bun:test";
+import { realpathSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { startPaneSession } from "./pane-session.js";
+import {
+ MAGMUX,
+ type PaneTestEnv,
+ killLeftovers,
+ makePaneTestEnv,
+ waitNoOrphans,
+} from "./test-helpers/hermetic-env.js";
+import type { SettledTurn } from "./types.js";
+
+const LIVE =
+ process.env.CLAUDISH_PANE_LIVE === "1" && !!process.env.CLAUDE_CODE_OAUTH_TOKEN && !!MAGMUX;
+const INDEX = join(import.meta.dir, "..", "index.ts");
+const envs: PaneTestEnv[] = [];
+afterAll(() => {
+ for (const t of envs) {
+ killLeftovers({ sockRoot: t.sockRoot });
+ t.cleanup();
+ }
+});
+
+async function live(
+ prompt: string,
+ shape: "one-shot" | "interactive" = "one-shot",
+ follow?: string
+) {
+ const t = makePaneTestEnv({
+ CLAUDISH_BIN: INDEX,
+ CLAUDE_CODE_OAUTH_TOKEN: process.env.CLAUDE_CODE_OAUTH_TOKEN as string,
+ });
+ envs.push(t);
+ writeFileSync(
+ join(t.configDir, ".claude.json"),
+ JSON.stringify({
+ hasCompletedOnboarding: true,
+ theme: "dark",
+ projects: { [realpathSync(t.cwd)]: { hasTrustDialogAccepted: true } },
+ })
+ );
+ const uuid = crypto.randomUUID();
+ const turns: SettledTurn[] = [];
+ const s = await startPaneSession({
+ kind: "s",
+ label: "live",
+ callerFlags: [],
+ spawnModel: "haiku",
+ cwd: t.cwd,
+ sessionUuid: uuid,
+ transcriptPath: t.transcriptPathFor(uuid),
+ slotEnv: { CLAUDISH_TOKEN_FILE: join(t.tmp, "tokens.json") },
+ shape,
+ initialPrompt: prompt,
+ readAvailable: true,
+ parentEnv: t.env,
+ sockRoot: t.sockRoot,
+ decide: (turn) => {
+ turns.push(turn);
+ if (shape === "interactive" && turns.length < 2) return "continue";
+ return turn.apiError
+ ? { state: "FAILED", reason: "api_error", detail: turn.apiError.text }
+ : { state: "COMPLETED" };
+ },
+ onBlocked: (b) => ({ state: "FAILED", reason: "blocked", detail: b.text }),
+ });
+ if (follow) {
+ await s.ready;
+ s.send(follow);
+ }
+ const snap = await s.terminal;
+ await s.reaped();
+ const left = await waitNoOrphans({
+ sockRoot: t.sockRoot,
+ ids: [uuid],
+ pgids: [snap.panePid ?? 0],
+ });
+ return { snap, turns, left };
+}
+
+describe.skipIf(!LIVE)(
+ "live: real claudish + real Claude Code in a pane (opt-in: CLAUDISH_PANE_LIVE=1)",
+ () => {
+ test("a typed one-shot prompt completes on turn_duration", async () => {
+ const r = await live("Reply with exactly PEAR and nothing else.");
+ expect(r.snap.state).toBe("COMPLETED");
+ expect(r.turns[0]?.answer).toContain("PEAR");
+ expect(r.turns[0]?.settledBy).toBe("turn_duration");
+ expect(r.left).toEqual({ processes: [], files: [] });
+ }, 180_000);
+
+ test("a multi-line prompt is delivered by file and fully read", async () => {
+ const r = await live(
+ "Reply with the word KIWI and nothing else.\nThis second line is part of the task."
+ );
+ expect(r.snap.state).toBe("COMPLETED");
+ expect(r.turns[0]?.delivery).toMatchObject({ mode: "file", complete: true });
+ expect(r.turns[0]?.answer).toContain("KIWI");
+ expect(r.left).toEqual({ processes: [], files: [] });
+ }, 180_000);
+
+ test("interactive: a queued second prompt is answered as turn 2", async () => {
+ const r = await live("Reply with exactly ONE.", "interactive", "Reply with exactly TWO.");
+ expect(r.snap.state).toBe("COMPLETED");
+ expect(r.turns.map((x) => x.answer.trim())).toEqual(["ONE", "TWO"]);
+ expect(r.snap.turnsCompleted).toBe(2);
+ }, 240_000);
+ }
+);
diff --git a/packages/cli/src/pane/pane-registry.test.ts b/packages/cli/src/pane/pane-registry.test.ts
new file mode 100644
index 00000000..f7d1d696
--- /dev/null
+++ b/packages/cli/src/pane/pane-registry.test.ts
@@ -0,0 +1,494 @@
+/**
+ * Process-wide pane safety against REAL magmux (architecture §2.11, §12.3): the parallel
+ * shutdown reap, the watcher's clean exit, the owner-SIGKILL gate with two panes (and the
+ * fd-hygiene measurement behind it), decoys that must never be signalled, the startup
+ * sweep, the cross-owner pane limit, and the R3-M1 spawn-failure reap.
+ */
+
+import { afterAll, describe, expect, test } from "bun:test";
+import { type ChildProcess, execFileSync, spawn } from "node:child_process";
+import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { waitForExit } from "../process-tree.js";
+import { assertMagmuxAvailable, ensureSockRoot, spawnPaneWatcher } from "./pane-launch.js";
+import {
+ MAX_LIVE_PANES,
+ PaneLimitError,
+ type PaneRecord,
+ livePaneCount,
+ ownerStartOfSelf,
+ readRecord,
+ reapAllPanes,
+ releasePaneReservations,
+ reservePanes,
+ sweepOrphanPanes,
+ writeRecord,
+} from "./pane-registry.js";
+import { startPaneSession } from "./pane-session.js";
+import { formatGroupFile, isPaneWatcherCommand, readProcessTable } from "./process-identity.js";
+import {
+ MAGMUX,
+ NO_MAGMUX_MESSAGE,
+ type PaneTestEnv,
+ killLeftovers,
+ makePaneTestEnv,
+ orphanReport,
+ waitNoOrphans,
+} from "./test-helpers/hermetic-env.js";
+
+const OWNER = join(import.meta.dir, "test-helpers", "pane-owner.ts");
+const envs: PaneTestEnv[] = [];
+const extraProcs: ChildProcess[] = [];
+
+afterAll(async () => {
+ for (const p of extraProcs) if (p.exitCode === null && p.signalCode === null) p.kill("SIGKILL");
+ for (const t of envs) {
+ killLeftovers({ sockRoot: t.sockRoot });
+ t.cleanup();
+ }
+});
+
+function env(): PaneTestEnv {
+ const t = makePaneTestEnv();
+ envs.push(t);
+ return t;
+}
+
+function alive(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+function deadPid(): number {
+ const p = Bun.spawnSync(["/usr/bin/true"]);
+ return p.pid;
+}
+
+async function hangSession(t: PaneTestEnv, label = "01") {
+ const uuid = crypto.randomUUID();
+ const s = await startPaneSession({
+ kind: "t",
+ label,
+ callerFlags: [],
+ spawnModel: "contract-fake-model",
+ cwd: t.cwd,
+ sessionUuid: uuid,
+ transcriptPath: t.transcriptPathFor(uuid),
+ slotEnv: {},
+ shape: "one-shot",
+ initialPrompt: "@@HANG@@",
+ readAvailable: true,
+ parentEnv: t.env,
+ sockRoot: t.sockRoot,
+ decide: () => ({ state: "COMPLETED" }),
+ onBlocked: () => "wait",
+ timings: { replStableMs: 200 },
+ });
+ await s.ready;
+ return { s, uuid };
+}
+
+interface OwnerInfo {
+ owner: number;
+ panes: Array<{ paneId: string; uuid: string; state: string; panePid: number }>;
+ records: PaneRecord[];
+}
+
+async function startOwner(
+ t: PaneTestEnv,
+ n: number
+): Promise<{ proc: ChildProcess; info: OwnerInfo }> {
+ const proc = spawn(process.execPath, [OWNER], {
+ env: {
+ ...t.env,
+ PANE_OWNER_SPEC: JSON.stringify({
+ n,
+ sockRoot: t.sockRoot,
+ cwd: t.cwd,
+ configDir: t.configDir,
+ env: t.env,
+ }),
+ },
+ stdio: ["ignore", "pipe", "inherit"],
+ });
+ extraProcs.push(proc);
+ const line = await new Promise<string>((resolve, reject) => {
+ let buf = "";
+ proc.stdout?.on("data", (d: Buffer) => {
+ buf += d.toString();
+ const nl = buf.indexOf("\n");
+ if (nl >= 0) resolve(buf.slice(0, nl));
+ });
+ proc.on("exit", (c) => reject(new Error(`owner exited ${c} before reporting`)));
+ });
+ return { proc, info: JSON.parse(line) as OwnerInfo };
+}
+
+/** lsof's unix-socket table for `pids`: pid → [{fd, addr, peer}]. */
+function unixFds(pids: number[]): Map<number, Array<{ fd: string; addr: string; peer: string }>> {
+ const out = new Map<number, Array<{ fd: string; addr: string; peer: string }>>();
+ let text = "";
+ try {
+ text = execFileSync("lsof", ["-a", "-U", "-p", pids.join(",")], { encoding: "utf8" });
+ } catch (e) {
+ text = String((e as { stdout?: string }).stdout ?? "");
+ }
+ for (const l of text.split("\n").slice(1)) {
+ const m = l.match(
+ /^\S+\s+(\d+)\s+\S+\s+(\S+)\s+unix\s+(0x[0-9a-f]+)\s+\S+\s+(?:->(0x[0-9a-f]+))?/
+ );
+ if (!m) continue;
+ const pid = Number(m[1]);
+ const arr = out.get(pid) ?? [];
+ arr.push({ fd: m[2] as string, addr: m[3] as string, peer: m[4] ?? "" });
+ out.set(pid, arr);
+ }
+ return out;
+}
+
+describe.skipIf(!MAGMUX)(`pane registry, real magmux (${MAGMUX ? "" : NO_MAGMUX_MESSAGE})`, () => {
+ test("reapAllPanes reaps five live panes in parallel within ≈ 3 s; nothing is left", async () => {
+ const t = env();
+ const sessions = await Promise.all(["1", "2", "3", "4", "5"].map((l) => hangSession(t, l)));
+ const pgids = sessions.map(({ s }) => s.snapshot().panePid ?? 0);
+ const t0 = Date.now();
+ await reapAllPanes("shutdown");
+ const took = Date.now() - t0;
+ expect(took).toBeLessThan(4500);
+ for (const { s } of sessions) expect(s.snapshot().state).toBe("CANCELLED");
+ const left = await waitNoOrphans({
+ sockRoot: t.sockRoot,
+ ids: sessions.map((x) => x.uuid),
+ pgids,
+ });
+ expect(left).toEqual({ processes: [], files: [] });
+ }, 30_000);
+
+ test("a clean reap ends the watcher: no claudish-pane-watcher <paneId> after reaped()", async () => {
+ const t = env();
+ const { s } = await hangSession(t);
+ const rec = readRecord(t.sockRoot, s.paneId) as PaneRecord;
+ expect(rec.watcherPid).toBeGreaterThan(0);
+ expect(alive(rec.watcherPid as number)).toBe(true);
+ s.cancel();
+ await s.reaped();
+ expect(readProcessTable().some((r) => isPaneWatcherCommand(r.command, s.paneId))).toBe(false);
+ expect(existsSync(s.sockPath)).toBe(false);
+ expect(readRecord(t.sockRoot, s.paneId)).toBeNull();
+ }, 30_000);
+
+ test("GATE: owner SIGKILL with two panes → both watchers remove group, magmux, socket, dirs, record (≤ 5 s); no watcher pipe leaked", async () => {
+ const t = env();
+ const { proc, info } = await startOwner(t, 2);
+ expect(info.panes).toHaveLength(2);
+ const watchers = info.records.map((r) => r.watcherPid as number);
+ const mags = info.records.map((r) => r.magmuxPid as number);
+ // fd hygiene: the owner holds each watcher's write end; neither magmux nor the sibling watcher may.
+ const fds = unixFds([info.owner, ...watchers, ...mags]);
+ const ownerEnds = new Map<number, string>(); // watcher pid → owner-side address of its stdin pair
+ for (const w of watchers) {
+ const w0 = fds.get(w)?.find((f) => f.fd.startsWith("0"));
+ expect(w0).toBeDefined();
+ ownerEnds.set(w, w0?.peer as string);
+ expect((fds.get(info.owner) ?? []).some((f) => f.addr === w0?.peer)).toBe(true);
+ }
+ for (const [w, end] of ownerEnds)
+ for (const other of [...watchers.filter((x) => x !== w), ...mags])
+ expect((fds.get(other) ?? []).some((f) => f.addr === end || f.peer === end)).toBe(false);
+ writeFileSync(join(t.tmp, "gate-lsof.json"), JSON.stringify({ info, fds: [...fds] }, null, 1));
+
+ const t0 = Date.now();
+ proc.kill("SIGKILL");
+ await waitForExit(proc, 2000);
+ const left = await waitNoOrphans(
+ {
+ sockRoot: t.sockRoot,
+ ids: info.panes.map((p) => p.uuid),
+ pgids: info.panes.map((p) => p.panePid),
+ },
+ 8000
+ );
+ const took = Date.now() - t0;
+ expect(left).toEqual({ processes: [], files: [] });
+ expect(took).toBeLessThan(5500);
+ for (const w of watchers) expect(alive(w)).toBe(false);
+ // evidence for the implementation log
+ process.stderr.write(
+ `[gate] owner SIGKILL → clean in ${took} ms; lsof: ${JSON.stringify([...fds])}\n`
+ );
+ }, 40_000);
+
+ test("decoy: the watcher never signals a pid that fails its identity check", async () => {
+ const t = env();
+ ensureSockRoot(t.sockRoot);
+ const decoy = spawn("sleep", ["60"], { detached: true, stdio: "ignore" });
+ extraProcs.push(decoy);
+ const ctl = join(t.sockRoot, "launch-DeCoY1");
+ const turn = join(t.sockRoot, "launch-DeCoY2");
+ mkdirSync(ctl, { mode: 0o700 });
+ mkdirSync(turn, { mode: 0o700 });
+ writeFileSync(join(ctl, "magmux.pid"), `${decoy.pid}\n`);
+ // the decoy's pid, but another start time: a reused pid
+ writeFileSync(
+ join(ctl, "group"),
+ formatGroupFile({
+ pgid: decoy.pid as number,
+ members: [{ pid: decoy.pid as number, lstart: "Thu Jan 1 00:00:00 2099" }],
+ })
+ );
+ const paneId = `c${deadPid()}-zz-tdecoy-abcdef`;
+ const w = spawnPaneWatcher({
+ paneId,
+ sessionUuid: crypto.randomUUID(),
+ ctlDir: ctl,
+ sockPath: join(t.sockRoot, `magmux-${paneId}.sock`),
+ recordPath: join(t.sockRoot, "panes", `${paneId}.json`),
+ turnDir: turn,
+ sockRoot: t.sockRoot,
+ });
+ w.stdin?.end(); // EOF without "done": the owner is gone
+ expect(await waitForExit(w, 8000)).toBe(true);
+ expect(alive(decoy.pid as number)).toBe(true);
+ expect(existsSync(ctl)).toBe(false); // nothing verified alive → files cleaned
+ decoy.kill("SIGKILL");
+ }, 20_000);
+
+ test("sweep: a dead-owner record is identity-validated; a decoy pid is kept, never signalled", async () => {
+ const t = env();
+ ensureSockRoot(t.sockRoot);
+ const decoy = spawn("sleep", ["60"], { detached: true, stdio: "ignore" });
+ extraProcs.push(decoy);
+ const ctl = join(t.sockRoot, "launch-SwEeP1");
+ mkdirSync(ctl, { mode: 0o700 });
+ writeFileSync(
+ join(ctl, "group"),
+ formatGroupFile({
+ pgid: decoy.pid as number,
+ members: [{ pid: decoy.pid as number, lstart: "Thu Jan 1 00:00:00 2099" }],
+ })
+ );
+ const paneId = `c${deadPid()}-zz-tsweep-abcdef`;
+ writeRecord(t.sockRoot, {
+ paneId,
+ ownerPid: deadPid(),
+ ownerStart: "Thu Jan 1 00:00:00 1970",
+ watcherPid: null,
+ magmuxPid: decoy.pid as number,
+ panePid: decoy.pid as number,
+ sessionUuid: crypto.randomUUID(),
+ sockPath: join(t.sockRoot, `magmux-${paneId}.sock`),
+ launcherDir: ctl,
+ turnDir: "",
+ createdAt: new Date().toISOString(),
+ });
+ const r = await sweepOrphanPanes(t.sockRoot);
+ expect(r.kept).toContain(paneId);
+ expect(alive(decoy.pid as number)).toBe(true);
+ expect(readRecord(t.sockRoot, paneId)).toBeNull();
+ decoy.kill("SIGKILL");
+ }, 20_000);
+
+ test("sweep: a record whose watcher is alive is skipped (the watcher is mid-job)", async () => {
+ const t = env();
+ ensureSockRoot(t.sockRoot);
+ const paneId = `c${deadPid()}-zz-tw-abcdef`;
+ const fakeWatcher = spawn(
+ "/bin/sh",
+ ["-c", "sleep 30; :", "claudish-pane-watcher", paneId, "x"],
+ { stdio: "ignore" }
+ );
+ extraProcs.push(fakeWatcher);
+ await Bun.sleep(100);
+ writeRecord(t.sockRoot, {
+ paneId,
+ ownerPid: deadPid(),
+ ownerStart: "x",
+ watcherPid: fakeWatcher.pid as number,
+ magmuxPid: null,
+ panePid: null,
+ sessionUuid: "u",
+ sockPath: join(t.sockRoot, `magmux-${paneId}.sock`),
+ launcherDir: join(t.sockRoot, "launch-nOnE12"),
+ turnDir: "",
+ createdAt: "",
+ });
+ const r = await sweepOrphanPanes(t.sockRoot);
+ expect(r.kept).toContain(paneId);
+ expect(readRecord(t.sockRoot, paneId)).not.toBeNull();
+ fakeWatcher.kill("SIGKILL");
+ rmSync(join(t.sockRoot, "panes", `${paneId}.json`), { force: true });
+ }, 20_000);
+
+ test("sweep: an orphaned real pane (owner AND watcher SIGKILLed) is verified, killed and cleaned", async () => {
+ const t = env();
+ const { proc, info } = await startOwner(t, 1);
+ const rec = info.records[0] as PaneRecord;
+ process.kill(rec.watcherPid as number, "SIGKILL");
+ await Bun.sleep(100);
+ proc.kill("SIGKILL");
+ await waitForExit(proc, 2000);
+ await Bun.sleep(300);
+ expect(alive(rec.magmuxPid as number)).toBe(true);
+ const r = await sweepOrphanPanes(t.sockRoot);
+ expect(r.reaped).toContain(rec.paneId);
+ const left = await waitNoOrphans({
+ sockRoot: t.sockRoot,
+ ids: [rec.sessionUuid],
+ pgids: [rec.panePid ?? 0],
+ });
+ expect(left).toEqual({ processes: [], files: [] });
+ }, 40_000);
+
+ test("sweep: recordless sockets — a refused one is unlinked; a live one is identity-checked and killed", async () => {
+ const t = env();
+ ensureSockRoot(t.sockRoot);
+ const stale = join(t.sockRoot, `magmux-c${deadPid()}-zz-tstale-abcdef.sock`);
+ writeFileSync(stale, "");
+ const id = `c${deadPid()}-zz-tlive-abcdef`;
+ const mag = spawn(
+ MAGMUX as string,
+ ["--headless", "--no-status", "--id", id, "--sock-dir", t.sockRoot, "-e", "sleep 60"],
+ {
+ env: { PATH: "/usr/bin:/bin", HOME: t.home, SHELL: "/bin/sh", COLUMNS: "80", LINES: "24" },
+ stdio: "ignore",
+ detached: true,
+ }
+ );
+ extraProcs.push(mag);
+ const sock = join(t.sockRoot, `magmux-${id}.sock`);
+ for (let i = 0; i < 100 && !existsSync(sock); i++) await Bun.sleep(50);
+ const r = await sweepOrphanPanes(t.sockRoot);
+ expect(r.cleaned.some((x) => x.includes("tstale"))).toBe(true);
+ expect(r.reaped).toContain(id);
+ expect(await waitForExit(mag, 3000)).toBe(true);
+ expect(existsSync(stale)).toBe(false);
+ expect(existsSync(sock)).toBe(false);
+ expect(orphanReport({ sockRoot: t.sockRoot }).processes).toEqual([]);
+ }, 20_000);
+
+ test("pane limit: counted across owners; reapFailed and dead-owner records never count", async () => {
+ const t = env();
+ const { proc, info } = await startOwner(t, 1);
+ expect(livePaneCount(t.sockRoot)).toBe(1); // the OTHER process's pane
+ const base: Omit<PaneRecord, "paneId"> = {
+ ownerPid: process.pid,
+ ownerStart: ownerStartOfSelf(),
+ watcherPid: null,
+ magmuxPid: null,
+ panePid: null,
+ sessionUuid: "u",
+ sockPath: "/nope",
+ launcherDir: "/nope",
+ turnDir: "",
+ createdAt: "",
+ };
+ writeRecord(t.sockRoot, { ...base, paneId: "c1-zz-tfailed-000000", reapFailed: true });
+ writeRecord(t.sockRoot, { ...base, paneId: "c1-zz-tdead-000000", ownerPid: deadPid() });
+ expect(livePaneCount(t.sockRoot)).toBe(1);
+ for (let i = 0; i < MAX_LIVE_PANES - 1; i++)
+ writeRecord(t.sockRoot, { ...base, paneId: `c1-zz-tfill${i}-000000` });
+ expect(livePaneCount(t.sockRoot)).toBe(MAX_LIVE_PANES);
+ expect(() => reservePanes(1, t.sockRoot)).toThrow(PaneLimitError);
+ for (let i = 0; i < MAX_LIVE_PANES - 1; i++)
+ rmSync(join(t.sockRoot, "panes", `c1-zz-tfill${i}-000000.json`));
+ reservePanes(2, t.sockRoot);
+ expect(livePaneCount(t.sockRoot)).toBe(3);
+ releasePaneReservations(2);
+ for (const n of ["c1-zz-tfailed-000000", "c1-zz-tdead-000000"])
+ rmSync(join(t.sockRoot, "panes", `${n}.json`));
+ proc.kill("SIGKILL");
+ const left = await waitNoOrphans({
+ sockRoot: t.sockRoot,
+ ids: info.panes.map((p) => p.uuid),
+ pgids: info.panes.map((p) => p.panePid),
+ });
+ expect(left).toEqual({ processes: [], files: [] });
+ }, 40_000);
+
+ test("R3-M1: a magmux spawn failure reaps at once — record and dirs gone, no watcher, livePaneCount 0", async () => {
+ const t = env();
+ const fake = join(t.tmp, "magmux-fake");
+ writeFileSync(fake, "#!/bin/sh\necho 'magmux 0.14.0 (fake)'\n");
+ chmodSync(fake, 0o755);
+ await assertMagmuxAvailable(fake); // passes the version gate …
+ rmSync(fake);
+ mkdirSync(fake); // … then the binary becomes unspawnable (EACCES on a directory)
+ const uuid = crypto.randomUUID();
+ let s: Awaited<ReturnType<typeof startPaneSession>> | null = null;
+ try {
+ s = await startPaneSession({
+ kind: "t",
+ label: "01",
+ callerFlags: [],
+ spawnModel: "fake-answer",
+ cwd: t.cwd,
+ sessionUuid: uuid,
+ transcriptPath: t.transcriptPathFor(uuid),
+ slotEnv: {},
+ shape: "one-shot",
+ initialPrompt: "x",
+ readAvailable: true,
+ parentEnv: t.env,
+ sockRoot: t.sockRoot,
+ magmuxBinary: fake,
+ decide: () => ({ state: "COMPLETED" }),
+ onBlocked: () => "wait",
+ });
+ } catch {
+ s = null; // a synchronous spawn throw is also a refusal before anything lives
+ }
+ if (s) {
+ const snap = await s.terminal;
+ expect(snap.state).toBe("FAILED");
+ expect(snap.reason).toBe("pane_lost");
+ expect(snap.detail).toContain("magmux spawn failed");
+ await s.reaped();
+ }
+ expect(livePaneCount(t.sockRoot)).toBe(0);
+ expect(
+ readProcessTable().some(
+ (r) => r.command.includes("claudish-pane-watcher") && r.command.includes(t.sockRoot)
+ )
+ ).toBe(false);
+ expect(orphanReport({ sockRoot: t.sockRoot, ids: [uuid] })).toEqual({
+ processes: [],
+ files: [],
+ });
+ }, 20_000);
+});
+
+describe("records", () => {
+ test("a record round-trips and is written 0600", () => {
+ const t = env();
+ ensureSockRoot(t.sockRoot);
+ const rec: PaneRecord = {
+ paneId: "c1-zz-trt-000000",
+ ownerPid: 1,
+ ownerStart: "Mon Oct 6 12:00:00 2026",
+ watcherPid: 2,
+ magmuxPid: null,
+ panePid: null,
+ sessionUuid: "u",
+ sockPath: "/s",
+ launcherDir: "/l",
+ turnDir: "/t",
+ createdAt: "now",
+ };
+ writeRecord(t.sockRoot, rec);
+ expect(readRecord(t.sockRoot, rec.paneId)).toEqual({ ...rec, reapFailed: false });
+ const mode =
+ Bun.file(join(t.sockRoot, "panes", `${rec.paneId}.json`)).size >= 0
+ ? execFileSync("stat", ["-f", "%Lp", join(t.sockRoot, "panes", `${rec.paneId}.json`)], {
+ encoding: "utf8",
+ }).trim()
+ : "";
+ if (process.platform === "darwin") expect(mode).toBe("600");
+ expect(
+ JSON.parse(readFileSync(join(t.sockRoot, "panes", `${rec.paneId}.json`), "utf8")).paneId
+ ).toBe(rec.paneId);
+ });
+});
diff --git a/packages/cli/src/pane/pane-session.integration.test.ts b/packages/cli/src/pane/pane-session.integration.test.ts
new file mode 100644
index 00000000..50023c9c
--- /dev/null
+++ b/packages/cli/src/pane/pane-session.integration.test.ts
@@ -0,0 +1,830 @@
+/**
+ * PaneSession against REAL magmux and the fake interactive child (architecture §12.3).
+ * Every test builds its own hermetic env and sockRoot and ends with the no-orphan check:
+ * no process whose argv carries the sockRoot or the session id, nothing left in the pane
+ * pgid, and no socket, record or launcher dir in the sockRoot.
+ */
+
+import { afterAll, describe, expect, test } from "bun:test";
+import { createHash } from "node:crypto";
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import type { SlotState } from "./contract.js";
+import {
+ type PaneBlock,
+ type PaneSession,
+ type PaneSessionOptions,
+ startPaneSession,
+} from "./pane-session.js";
+import {
+ MAGMUX,
+ NO_MAGMUX_MESSAGE,
+ type PaneTestEnv,
+ killLeftovers,
+ makePaneTestEnv,
+ newSessionUuid,
+ waitNoOrphans,
+} from "./test-helpers/hermetic-env.js";
+import type { FinalVerdict, PaneSnapshot, SettledTurn } from "./types.js";
+
+const sha8 = (s: string) => createHash("sha1").update(s).digest("hex").slice(0, 8);
+
+/** Runs not yet finished: a test that throws before `finish` is cleaned up at the end. */
+const open = new Set<Run>();
+afterAll(async () => {
+ for (const r of open) {
+ r.s.cancel();
+ await r.s.reaped();
+ killLeftovers({ sockRoot: r.t.sockRoot, ids: [r.uuid] });
+ r.t.cleanup();
+ }
+});
+
+interface Run {
+ s: PaneSession;
+ t: PaneTestEnv;
+ uuid: string;
+ transitions: Array<[SlotState, SlotState]>;
+ turns: SettledTurn[];
+ blocks: PaneBlock[];
+}
+
+/** team-like policy: verdict at the first settle; api error → FAILED; question → FAILED blocked */
+function teamDecide(turn: SettledTurn): FinalVerdict {
+ if (turn.apiError) return { state: "FAILED", reason: "api_error", detail: turn.apiError.text };
+ if (turn.delivery.complete === false) return { state: "FAILED", reason: "prompt_not_read" };
+ if (!turn.answer.trim()) return { state: "EMPTY", reason: "empty_output" };
+ return { state: "COMPLETED" };
+}
+
+async function start(
+ scenario: string,
+ over: Partial<PaneSessionOptions> & { env?: Record<string, string> } = {}
+): Promise<Run> {
+ const t = makePaneTestEnv(over.env ?? {});
+ const uuid = newSessionUuid();
+ const transitions: Array<[SlotState, SlotState]> = [];
+ const turns: SettledTurn[] = [];
+ const blocks: PaneBlock[] = [];
+ const { env: _e, decide, onBlocked, ...rest } = over;
+ const s = await startPaneSession({
+ kind: "t",
+ label: "01",
+ callerFlags: [],
+ spawnModel: scenario.startsWith("contract") ? scenario : `fake-${scenario}`,
+ cwd: t.cwd,
+ sessionUuid: uuid,
+ transcriptPath: t.transcriptPathFor(uuid),
+ slotEnv: {},
+ shape: "one-shot",
+ initialPrompt: "Reply with exactly PEAR.",
+ readAvailable: true,
+ parentEnv: t.env,
+ sockRoot: t.sockRoot,
+ decide: (turn) => {
+ turns.push(turn);
+ return decide ? decide(turn) : teamDecide(turn);
+ },
+ onBlocked: (b) => {
+ blocks.push(b);
+ return onBlocked ? onBlocked(b) : { state: "FAILED", reason: "blocked", detail: b.text };
+ },
+ onTransition: (x) => transitions.push([x.from, x.to]),
+ timings: {
+ replStableMs: 200,
+ bootStaticMs: 800,
+ corroborationMs: 200,
+ ...(rest.timings ?? {}),
+ },
+ ...rest,
+ });
+ const run = { s, t, uuid, transitions, turns, blocks };
+ open.add(run);
+ return run;
+}
+
+/** Run to terminal, then reap, and prove nothing is left. */
+async function finish(r: Run, ms = 20_000): Promise<PaneSnapshot> {
+ try {
+ const snap = await Promise.race([
+ r.s.terminal,
+ Bun.sleep(ms).then(() => {
+ throw new Error(`no terminal state in ${ms} ms: ${JSON.stringify(r.s.snapshot())}`);
+ }),
+ ]);
+ return snap;
+ } finally {
+ open.delete(r);
+ r.s.cancel();
+ await r.s.reaped();
+ const left = await waitNoOrphans({
+ sockRoot: r.t.sockRoot,
+ ids: [r.uuid],
+ pgids: [r.s.snapshot().panePid ?? 0],
+ });
+ killLeftovers({ sockRoot: r.t.sockRoot, ids: [r.uuid] });
+ r.t.cleanup();
+ expect(left).toEqual({ processes: [], files: [] });
+ }
+}
+
+async function until(
+ r: Run,
+ pred: (s: PaneSnapshot) => boolean,
+ ms = 15_000
+): Promise<PaneSnapshot> {
+ const end = Date.now() + ms;
+ for (;;) {
+ const s = r.s.snapshot();
+ if (pred(s)) return s;
+ if (Date.now() > end) throw new Error(`condition not met in ${ms} ms: ${JSON.stringify(s)}`);
+ await Bun.sleep(50);
+ }
+}
+
+const T = 40_000;
+
+describe.skipIf(!MAGMUX)(
+ `PaneSession, real magmux + fake child (${MAGMUX ? "" : NO_MAGMUX_MESSAGE})`,
+ () => {
+ describe.concurrent("happy path and delivery", () => {
+ test(
+ "answer: STARTING → RUNNING → COMPLETED on turn_duration, the typed line's hash, all reaped",
+ async () => {
+ const r = await start("answer");
+ await r.s.ready;
+ expect(r.s.snapshot().state).toBe("RUNNING");
+ const snap = await finish(r);
+ expect(snap.state).toBe("COMPLETED");
+ expect(r.transitions).toEqual([
+ ["STARTING", "RUNNING"],
+ ["RUNNING", "COMPLETED"],
+ ]);
+ expect(r.turns[0]?.answer).toBe(`ANSWER fake-answer ${sha8("Reply with exactly PEAR.")}`);
+ expect(r.turns[0]?.settledBy).toBe("turn_duration");
+ expect(r.turns[0]?.delivery.mode).toBe("typed");
+ expect(snap.turnsCompleted).toBe(1);
+ expect(snap.tokensIn).toBeGreaterThan(0);
+ expect(snap.claudeCodeVersion).toBe("2.1.290");
+ },
+ T
+ );
+
+ test(
+ "a multi-line prompt goes by file; Read coverage complete; the reconstructed hash equals the prompt's",
+ async () => {
+ const prompt = "First line.\n\tSecond line with a tab.\n! leading bang\nlast";
+ const r = await start("answer", { initialPrompt: prompt });
+ const snap = await finish(r);
+ expect(snap.state).toBe("COMPLETED");
+ const turn = r.turns[0] as SettledTurn;
+ expect(turn.delivery).toMatchObject({
+ mode: "file",
+ linesTotal: 4,
+ linesRead: 4,
+ complete: true,
+ });
+ expect(turn.answer).toBe(`ANSWER fake-answer ${sha8(prompt)}`);
+ expect(snap.toolCalls).toBe(1);
+ },
+ T
+ );
+
+ test(
+ "long_line: a 25,000-char line is split with ↩ and joined back losslessly",
+ async () => {
+ const prompt = `${"word ".repeat(5000)}\nend`;
+ const r = await start("long_line", { initialPrompt: prompt });
+ await finish(r);
+ expect(r.turns[0]?.answer).toBe(`ANSWER fake-long_line ${sha8(prompt)}`);
+ expect(r.turns[0]?.delivery.complete).toBe(true);
+ },
+ T
+ );
+
+ test(
+ "narrate_then_read: the answer starts after the Read result; ^VERDICT: matches; preamble counted",
+ async () => {
+ const r = await start("narrate_then_read", {
+ initialPrompt: "Review this.\nReply VERDICT: ok",
+ decide: (turn) =>
+ /^VERDICT:/.test(turn.answer)
+ ? { state: "COMPLETED" }
+ : { state: "EMPTY", reason: "shape_mismatch" },
+ });
+ const snap = await finish(r);
+ expect(snap.state).toBe("COMPLETED");
+ expect(r.turns[0]?.answer).toBe("VERDICT: ok");
+ expect(r.turns[0]?.delivery.preambleBytes).toBeGreaterThan(0);
+ },
+ T
+ );
+
+ test(
+ "partial_read / no_read: complete false → the team policy fails prompt_not_read",
+ async () => {
+ for (const sc of ["partial_read", "no_read"]) {
+ const r = await start(sc, { initialPrompt: "a\nb\nc\nd\ne\nf" });
+ const snap = await finish(r);
+ expect(snap.state).toBe("FAILED");
+ expect(snap.reason).toBe("prompt_not_read");
+ expect(r.turns[0]?.delivery.complete).toBe(false);
+ expect(r.turns[0]?.delivery.linesRead ?? 0).toBeLessThan(6);
+ }
+ },
+ T * 2
+ );
+
+ test(
+ "menu_eats_enter: the line still in the box at +resend → Enter again (resent_enter)",
+ async () => {
+ const r = await start("menu_eats_enter", { timings: { resendAfterMs: 800 } });
+ const snap = await finish(r);
+ expect(snap.state).toBe("COMPLETED");
+ expect(snap.anomalies).toContain("resent_enter");
+ },
+ T
+ );
+
+ test(
+ "immediate_write: a witness written at once is still found (offset taken before delivery)",
+ async () => {
+ const snap = await finish(await start("immediate_write"));
+ expect(snap.state).toBe("COMPLETED");
+ },
+ T
+ );
+ });
+
+ describe.concurrent("settle paths", () => {
+ test(
+ "quiet: path S after the secondary window, with the anomaly",
+ async () => {
+ const r = await start("quiet", { timings: { secondaryQuietMs: 1000 } });
+ const snap = await finish(r);
+ expect(snap.state).toBe("COMPLETED");
+ expect(r.turns[0]?.settledBy).toBe("quiet");
+ expect(snap.anomalies).toContain("settled_without_turn_duration");
+ },
+ T
+ );
+
+ test(
+ "quiet_no_summary: never settles (activity finishing); cancel → CANCELLED",
+ async () => {
+ const r = await start("quiet_no_summary", { timings: { secondaryQuietMs: 500 } });
+ await until(r, (s) => s.activity === "finishing");
+ await Bun.sleep(1500);
+ expect(r.s.snapshot().state).toBe("RUNNING");
+ expect(r.s.cancel()).toEqual({ changed: true, state: "CANCELLED" });
+ expect(r.s.cancel()).toEqual({ changed: false, state: "CANCELLED" });
+ const snap = await finish(r);
+ expect(snap.reason).toBe("cancelled");
+ expect(r.turns).toHaveLength(0);
+ },
+ T
+ );
+
+ test(
+ "hookless_quiet: turn 2 settles by S once turn 1 proved the session hook-less",
+ async () => {
+ const r = await start("hookless_quiet", {
+ shape: "interactive",
+ decide: () => "continue",
+ timings: { secondaryQuietMs: 800 },
+ });
+ await until(r, (s) => s.state === "AWAITING_INPUT" && s.turnsCompleted === 1);
+ r.s.send("second turn please");
+ await until(r, (s) => s.turnsCompleted === 2);
+ expect(r.turns.map((t) => t.settledBy)).toEqual(["turn_duration", "quiet"]);
+ await finish(r);
+ },
+ T
+ );
+
+ // The secondary window is chosen ABOVE the re-wake gap (2 × the corpus p99, §2.8), so the
+ // gap here is shorter than the window under test; a longer gap would open path S.
+ test(
+ "rewake: no settle before the late turn_duration; both texts in one answer",
+ async () => {
+ const r = await start("rewake", {
+ env: { FAKE_GAP_MS_REWAKE: "2000" },
+ timings: { secondaryQuietMs: 4000 },
+ });
+ const snap = await finish(r);
+ expect(snap.state).toBe("COMPLETED");
+ expect(r.turns).toHaveLength(1);
+ expect(r.turns[0]?.answer).toContain("LATE second message");
+ expect(r.turns[0]?.answer.startsWith("ANSWER")).toBe(true);
+ },
+ T
+ );
+
+ test(
+ "slow_stop_hook: nothing settles during the hook (3 × window); P after it",
+ async () => {
+ const r = await start("slow_stop_hook", {
+ env: { FAKE_GAP_MS_HOOK: "3000" },
+ timings: { secondaryQuietMs: 1000 },
+ });
+ await until(r, (s) => s.activity === "finishing");
+ const at = Date.now();
+ const snap = await finish(r);
+ expect(Date.now() - at).toBeGreaterThan(2000);
+ expect(snap.state).toBe("COMPLETED");
+ expect(r.turns[0]?.settledBy).toBe("turn_duration");
+ },
+ T
+ );
+
+ test(
+ "bg_rewake: waits for the background agent (activity background), then settles",
+ async () => {
+ const r = await start("bg_rewake", { env: { FAKE_GAP_MS_BG: "1500" } });
+ await until(r, (s) => s.activity === "background");
+ const snap = await finish(r);
+ expect(snap.state).toBe("COMPLETED");
+ expect(r.turns[0]?.answer).toContain("ANSWER");
+ },
+ T
+ );
+
+ test(
+ "bg_server: settles at turn_duration with background_shell_open; the reap ends the shell",
+ async () => {
+ const r = await start("bg_server");
+ const snap = await finish(r);
+ expect(snap.state).toBe("COMPLETED");
+ expect(
+ snap.anomalies.some((a) => a.startsWith("background_shell_open: fake-dev-server"))
+ ).toBe(true);
+ },
+ T
+ );
+
+ test(
+ "compaction keeps one answer; max_tokens ends in a max_output_tokens API error; null stop settles",
+ async () => {
+ const c = await start("compaction");
+ await finish(c);
+ expect(c.turns[0]?.answer).toContain("before compaction");
+ expect(c.turns[0]?.answer).toContain("ANSWER");
+ const m = await start("max_tokens");
+ const ms = await finish(m);
+ expect(ms.reason).toBe("api_error");
+ expect(m.turns[0]?.apiError?.category).toBe("max_output_tokens");
+ const n = await start("null_stop");
+ await finish(n);
+ expect(n.turns[0]?.stopReason).toBeNull();
+ },
+ T * 2
+ );
+
+ test(
+ "api_error → FAILED api_error; refusal continues to the fallback answer",
+ async () => {
+ const a = await start("api_error");
+ const as = await finish(a);
+ expect(as.reason).toBe("api_error");
+ expect(a.turns[0]?.apiError?.status).toBe(401);
+ const f = await start("refusal");
+ const fs = await finish(f);
+ expect(fs.state).toBe("COMPLETED");
+ expect(f.turns).toHaveLength(1);
+ },
+ T
+ );
+ });
+
+ describe.concurrent("blocked, interrupts and permission", () => {
+ test(
+ "ask_user (team): FAILED blocked with the question text, in one net transition",
+ async () => {
+ const r = await start("ask_user");
+ const snap = await finish(r);
+ expect(snap.state).toBe("FAILED");
+ expect(snap.reason).toBe("blocked");
+ expect(snap.detail).toBe("Which fruit do you prefer?");
+ expect(r.transitions).toEqual([
+ ["STARTING", "RUNNING"],
+ ["RUNNING", "FAILED"],
+ ]);
+ },
+ T
+ );
+
+ test(
+ "ask_user_send (channel): AWAITING_INPUT; a send presses Esc → path I settles; the text is turn 2",
+ async () => {
+ const r = await start("ask_user_send", {
+ shape: "interactive",
+ onBlocked: () => "wait",
+ decide: () => "continue",
+ });
+ const blocked = await until(
+ r,
+ (s) => s.state === "AWAITING_INPUT" && s.activity === "AskUserQuestion"
+ );
+ expect(blocked.phase).toBe("QUESTION");
+ expect(r.s.send("Pear, please")).toEqual({ ok: true, queued: 1 });
+ await until(r, (s) => s.turnsCompleted === 2);
+ expect(r.turns[0]?.stopReason).toBe("interrupted");
+ expect(r.turns[0]?.settledBy).toBe("interrupt");
+ expect(r.turns[1]?.answer).toBe(`ANSWER fake-ask_user_send ${sha8("Pear, please")}`);
+ await finish(r);
+ },
+ T
+ );
+
+ test(
+ "interrupt_td: the interrupt with a turn_duration settles once",
+ async () => {
+ const r = await start("interrupt_td", {
+ shape: "interactive",
+ onBlocked: () => "wait",
+ decide: () => "continue",
+ });
+ await until(r, (s) => s.phase === "QUESTION");
+ r.s.send("next");
+ await until(r, (s) => s.turnsCompleted === 2);
+ expect(r.turns).toHaveLength(2);
+ await finish(r);
+ },
+ T
+ );
+
+ test(
+ "permission: AWAITING_PERMISSION with the tool as activity; cancel ends it",
+ async () => {
+ const r = await start("permission", {
+ shape: "interactive",
+ onBlocked: () => "wait",
+ decide: () => "continue",
+ });
+ const s = await until(r, (x) => x.state === "AWAITING_PERMISSION");
+ expect(s.activity).toBe("Write");
+ expect(r.blocks[0]?.kind).toBe("permission");
+ r.s.cancel();
+ expect((await finish(r)).state).toBe("CANCELLED");
+ },
+ T
+ );
+
+ test(
+ "tool_slow_numbered: numbered prose over a running Bash is NOT a dialog (R3-H1)",
+ async () => {
+ const r = await start("tool_slow_numbered", { env: { FAKE_GAP_MS_TOOL: "2500" } });
+ const snap = await finish(r);
+ expect(snap.state).toBe("COMPLETED");
+ expect(r.blocks).toHaveLength(0);
+ },
+ T
+ );
+ });
+
+ describe.concurrent("exit paths", () => {
+ test(
+ "exit_mid_turn → FAILED child_exited with the code",
+ async () => {
+ const snap = await finish(await start("exit_mid_turn"));
+ expect(snap.reason).toBe("child_exited");
+ expect(snap.exitCode).toBe(3);
+ expect(snap.detail).toContain("code 3");
+ },
+ T
+ );
+
+ test(
+ "exit_after_settle / exit_before_td: the verdict comes from the turn, not child_exited",
+ async () => {
+ const a = await start("exit_after_settle");
+ expect((await finish(a)).state).toBe("COMPLETED");
+ const b = await start("exit_before_td");
+ expect((await finish(b)).state).toBe("COMPLETED");
+ expect(b.turns[0]?.settledBy).toBe("exit");
+ },
+ T
+ );
+
+ test(
+ "interactive_exit_after_settle: turn_continue then exit_clean → COMPLETED",
+ async () => {
+ const r = await start("interactive_exit_after_settle", {
+ shape: "interactive",
+ decide: () => "continue",
+ });
+ const snap = await finish(r);
+ expect(snap.state).toBe("COMPLETED");
+ expect(snap.turnsCompleted).toBe(1);
+ },
+ T
+ );
+
+ test(
+ "turn2_exit0: turn 2 accepted, exit 0 before answering → FAILED child_exited (C3)",
+ async () => {
+ const r = await start("turn2_exit0", { shape: "interactive", decide: () => "continue" });
+ await until(r, (s) => s.turnsCompleted === 1 && s.state === "AWAITING_INPUT");
+ r.s.send("turn two");
+ const snap = await finish(r);
+ expect(snap.reason).toBe("child_exited");
+ },
+ T
+ );
+
+ test(
+ "idle_exit: a promptless session's /exit → COMPLETED via exit_clean",
+ async () => {
+ const r = await start("answer", {
+ shape: "interactive",
+ initialPrompt: undefined,
+ decide: () => "continue",
+ });
+ await r.s.ready;
+ expect(r.s.snapshot().state).toBe("AWAITING_INPUT");
+ r.s.send("/exit");
+ expect((await finish(r)).state).toBe("COMPLETED");
+ },
+ T
+ );
+
+ test(
+ "an unknown --agent → FAILED agent_rejected with the child's own line",
+ async () => {
+ const r = await start("answer", { callerFlags: ["--agent", "zzz-not-real"] });
+ const snap = await finish(r);
+ expect(snap.reason).toBe("agent_rejected");
+ expect(snap.detail).toContain("--agent 'zzz-not-real' not found.");
+ },
+ T
+ );
+ });
+
+ describe.concurrent("boot and admission bounds", () => {
+ test(
+ "named dialog → first_run_dialog; unnamed choice → boot_blocked (text in detail)",
+ async () => {
+ const a = await start("dialog_trust");
+ const as = await finish(a);
+ expect(as.reason).toBe("first_run_dialog");
+ expect(as.detail).toContain("Is this a project you created or one you trust");
+ const b = await start("dialog_unknown");
+ expect((await finish(b)).reason).toBe("boot_blocked");
+ },
+ T
+ );
+
+ test(
+ "slow_boot with a 1 s boot bound → boot_timeout",
+ async () => {
+ const snap = await finish(await start("slow_boot", { bootTimeoutMs: 1000 }));
+ expect(snap.reason).toBe("boot_timeout");
+ },
+ T
+ );
+
+ test(
+ "ignore_input: the created prompt never accepted → FAILED prompt_not_accepted",
+ async () => {
+ const snap = await finish(
+ await start("ignore_input", { admitTimeoutMs: 2500, timings: { resendAfterMs: 1000 } })
+ );
+ expect(snap.reason).toBe("prompt_not_accepted");
+ },
+ T
+ );
+
+ test(
+ "promptless_first_send_ignored: AWAITING_INPUT → RUNNING → AWAITING_INPUT, never STARTING or FAILED",
+ async () => {
+ const r = await start("promptless_first_send_ignored", {
+ shape: "interactive",
+ initialPrompt: undefined,
+ decide: () => "continue",
+ admitTimeoutMs: 2000,
+ timings: { resendAfterMs: 800, degradedEntryMs: 800 },
+ });
+ await r.s.ready;
+ r.s.send("first, ignored");
+ await until(
+ r,
+ (s) => s.anomalies.includes("send_not_accepted") && s.state === "AWAITING_INPUT"
+ );
+ r.s.send("second, answered");
+ await until(r, (s) => s.turnsCompleted === 1);
+ await finish(r);
+ expect(r.transitions.slice(0, 3)).toEqual([
+ ["STARTING", "AWAITING_INPUT"],
+ ["AWAITING_INPUT", "RUNNING"],
+ ["RUNNING", "AWAITING_INPUT"],
+ ]);
+ expect(r.transitions.some(([, to]) => to === "STARTING" || to === "FAILED")).toBe(false);
+ },
+ T
+ );
+
+ test(
+ "timeoutMs → TIMEOUT (the caller's own deadline)",
+ async () => {
+ const r = await start("contract-fake-model", {
+ initialPrompt: "@@HANG@@",
+ timeoutMs: 3500,
+ });
+ expect((await finish(r)).state).toBe("TIMEOUT");
+ },
+ T
+ );
+ });
+
+ describe.concurrent("degraded mode", () => {
+ test(
+ "slow_prompt_hook: degraded entry, then the late witness reverts to the transcript",
+ async () => {
+ const r = await start("slow_prompt_hook", {
+ env: { FAKE_GAP_MS_PROMPT_HOOK: "5000" },
+ timings: { degradedEntryMs: 1500, resendAfterMs: 1500 },
+ });
+ const snap = await finish(r);
+ expect(snap.state).toBe("COMPLETED");
+ expect(snap.anomalies).toContain("degraded_mode");
+ expect(snap.anomalies).toContain("degraded_reverted");
+ expect(r.turns[0]?.captureSource).toBe("transcript");
+ },
+ T
+ );
+
+ test(
+ "no_transcript / missing_no_warning: settles from the screen, captureSource screen",
+ async () => {
+ for (const sc of ["no_transcript", "missing_no_warning"]) {
+ const r = await start(sc, {
+ timings: { degradedEntryMs: 800, screenSettleQuietMs: 300 },
+ });
+ const snap = await finish(r);
+ expect(snap.state).toBe("COMPLETED");
+ expect(r.turns[0]?.captureSource).toBe("screen");
+ expect(r.turns[0]?.answer).toContain("ANSWER");
+ expect(snap.turnSource).toBe("screen");
+ }
+ },
+ T * 2
+ );
+
+ test(
+ "screen_api_error: a degraded turn with an error row → FAILED api_error",
+ async () => {
+ const r = await start("screen_api_error", {
+ timings: { degradedEntryMs: 800, screenSettleQuietMs: 300 },
+ });
+ const snap = await finish(r);
+ expect(snap.reason).toBe("api_error");
+ },
+ T
+ );
+ });
+
+ describe.concurrent("screen, capture, transport", () => {
+ test(
+ "capture: seq 0 means no frame; since_seq unchanged; spans on request; final after terminal",
+ async () => {
+ const r = await start("answer");
+ await r.s.ready;
+ const c1 = r.s.capture(undefined, { spans: true });
+ expect("lines" in c1 && c1.lines.length === 50 && c1.cols === 160).toBe(true);
+ expect("spans" in c1 && Array.isArray(c1.spans)).toBe(true);
+ const same = r.s.capture((c1 as { seq: number }).seq);
+ expect(same).toMatchObject({ unchanged: true });
+ await r.s.terminal;
+ const fin = r.s.capture();
+ expect(fin.final).toBe(true);
+ await finish(r);
+ },
+ T
+ );
+
+ test(
+ "status_tick: a ticking status row under the box does not hold the settle; seq advances",
+ async () => {
+ const r = await start("status_tick", {
+ shape: "interactive",
+ decide: () => "continue",
+ initialPrompt: undefined,
+ });
+ await r.s.ready;
+ const s0 = r.s.capture().seq;
+ await Bun.sleep(2200);
+ expect(r.s.capture().seq).toBeGreaterThan(s0);
+ r.s.send("go");
+ await until(r, (s) => s.turnsCompleted === 1);
+ await finish(r);
+ },
+ T
+ );
+
+ test(
+ "idle_suggestion: faint ghost text reads as an empty box",
+ async () => {
+ expect((await finish(await start("idle_suggestion"))).state).toBe("COMPLETED");
+ },
+ T
+ );
+
+ test(
+ "subscriber drop: our socket closes while magmux lives → reconnect, no state change, seq continues",
+ async () => {
+ const r = await start("tool_slow", { env: { FAKE_GAP_MS_TOOL: "4000" } });
+ await until(r, (s) => s.activity === "Bash");
+ const seq = r.s.capture().seq;
+ (r.s as unknown as { client: { close(): void } }).client.close();
+ await until(r, (s) => s.anomalies.includes("socket_reconnected") && s.connected);
+ expect(r.s.snapshot().state).toBe("RUNNING");
+ const snap = await finish(r);
+ expect(snap.state).toBe("COMPLETED");
+ expect(r.s.capture().seq).toBeGreaterThanOrEqual(seq);
+ },
+ T
+ );
+
+ test(
+ "sends while RUNNING queue; the settle-then-admit step reports no AWAITING_INPUT (net onTransition)",
+ async () => {
+ const r = await start("tool_slow", {
+ shape: "interactive",
+ decide: () => "continue",
+ env: { FAKE_GAP_MS_TOOL: "1500" },
+ });
+ await until(r, (s) => s.activity === "Bash");
+ expect(r.s.send("queued one")).toEqual({ ok: true, queued: 1 });
+ expect(r.s.snapshot().pendingInputs).toBe(1);
+ await until(r, (s) => s.turnsCompleted === 2, 20_000);
+ const toAwaiting = r.transitions.filter(([, to]) => to === "AWAITING_INPUT");
+ expect(toAwaiting).toHaveLength(1); // only after turn 2
+ await finish(r);
+ },
+ T
+ );
+
+ test(
+ "send validation: /clear and /resume are unsupported; a terminal session refuses",
+ async () => {
+ const r = await start("answer");
+ expect(r.s.send("/clear")).toEqual({ ok: false, reason: "unsupported_command" });
+ await r.s.terminal;
+ expect(r.s.send("x")).toEqual({ ok: false, reason: "terminal" });
+ await finish(r);
+ },
+ T
+ );
+
+ test(
+ "env_probe: the pane's env and cwd — no terminal identity, no profile sourced, markers set",
+ async () => {
+ const probe = join("/tmp", `pane-probe-${process.pid}-${Date.now()}.json`);
+ const canary = join("/tmp", `pane-canary-${process.pid}-${Date.now()}`);
+ const r0 = makePaneTestEnv();
+ r0.cleanup();
+ const r = await start("env_probe", {
+ env: {
+ FAKE_PROBE_FILE: probe,
+ TMUX: "/tmp/tmux,1,0",
+ TERM_PROGRAM: "iTerm.app",
+ CLAUDE_CODE_SESSION_ID: "host",
+ },
+ });
+ mkdirSync(r.t.home, { recursive: true });
+ writeFileSync(
+ join(r.t.home, ".zprofile"),
+ `touch ${canary}\nexport CLAUDE_CONFIG_DIR=/nope\ncd /\n`
+ );
+ await finish(r);
+ const p = JSON.parse(readFileSync(probe, "utf8")) as {
+ env: Record<string, string>;
+ cwd: string;
+ };
+ expect(p.env.TMUX).toBeUndefined();
+ expect(p.env.TERM_PROGRAM).toBeUndefined();
+ expect(p.env.CLAUDE_CODE_SESSION_ID).toBeUndefined();
+ expect(p.env.CLAUDISH_PANE_CHILD).toBe("1");
+ expect(p.env.CLAUDISH_PANE_ENV).toBeDefined();
+ expect(JSON.parse(p.env.CLAUDISH_PANE_ENV as string).SHELL).toBe("/bin/zsh");
+ expect(p.env.SHELL.endsWith("/sh-shim")).toBe(true);
+ expect(p.env.CLAUDE_CONFIG_DIR).toBe(r.t.configDir);
+ expect(p.cwd.endsWith("/cwd")).toBe(true);
+ expect(existsSync(canary)).toBe(false);
+ },
+ T
+ );
+
+ test(
+ "five sessions at once: unique ids, all reaped",
+ async () => {
+ const runs = await Promise.all(["a", "b", "c", "d", "e"].map(() => start("answer")));
+ expect(new Set(runs.map((r) => r.s.paneId)).size).toBe(5);
+ const snaps = await Promise.all(runs.map((r) => finish(r)));
+ expect(snaps.every((s) => s.state === "COMPLETED")).toBe(true);
+ },
+ T
+ );
+ });
+ }
+);
diff --git a/packages/cli/src/pane/test-helpers/fake-interactive-child.ts b/packages/cli/src/pane/test-helpers/fake-interactive-child.ts
new file mode 100644
index 00000000..d3ed21b5
--- /dev/null
+++ b/packages/cli/src/pane/test-helpers/fake-interactive-child.ts
@@ -0,0 +1,932 @@
+#!/usr/bin/env bun
+/**
+ * The fake interactive child (architecture §12.2): a stand-in for "claudish → Claude Code"
+ * inside a real magmux pane. Test-only.
+ *
+ * It draws the REPL with lines COPIED from the phase-2 real screen fixtures, reads raw
+ * keystrokes with the key semantics measured from the real REPL's keylog (phase2-captures
+ * §3: `\r` submits, ctrl-j inserts a newline, Esc closes a menu / declines a dialog /
+ * interrupts, Enter on an `@` menu submits as typed), and writes its transcript to
+ * `<CLAUDE_CONFIG_DIR>/projects/<slug(realpath cwd)>/<uuid>.jsonl` by TEMPLATING records
+ * from the real transcript fixtures (ids, text and times substituted; never hand-written).
+ *
+ * Three ways to run it:
+ * - as claudish (`CLAUDISH_BIN=<this file>`): `-i --model fake-<scenario>[-<n>] -y --quiet
+ * --session-id <uuid> --add-dir <dir> [flags]`;
+ * - marker mode: any other `--model` (the contract suites pass `contract-fake-model`): the
+ * scenario comes from markers in the delivered prompt (`@@TOOL@@`, `@@HANG@@`,
+ * `@@LINGER@@`, `@@LATE@@`) or `CONTRACT_FAKE_HANG=1`;
+ * - "claude" mode (`--fake-as-claude` first, via a CLAUDE_PATH wrapper): the REAL claudish
+ * launches it as Claude Code; it dumps argv, env, cwd and the `--settings` content to
+ * `FAKE_CLAUDE_DUMP`, then emulates the REPL in marker mode.
+ *
+ * A file-delivered prompt (the fixed template) is read back exactly as Read returns it
+ * (numbered lines, `toolUseResult.file`), reconstructed (split markers joined), and
+ * answered `ANSWER <model> <sha1(reconstructed)[0..8]>`, so a test can compare the hash
+ * with sha1 of the caller's prompt and see any loss. A typed line hashes the line.
+ *
+ * Gaps come from `FAKE_GAP_MS_<NAME>` so scenarios keep their ORDER at a fraction of real
+ * time. `CONTRACT_FAKE_MAX_MS` (default 20 s) is a safety exit so a broken test never
+ * leaves a REPL behind. `CONTRACT_FAKE_SIGTERM_MARKER` is written on SIGTERM or SIGHUP.
+ */
+
+import { spawn } from "node:child_process";
+import { createHash, randomUUID } from "node:crypto";
+import { appendFileSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+
+/* ───────────────────────────── argv and env ───────────────────────────── */
+
+const rawArgv = process.argv.slice(2);
+const asClaude = rawArgv[0] === "--fake-as-claude";
+const argv = asClaude ? rawArgv.slice(1) : rawArgv;
+
+function flag(name: string): string | undefined {
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i] as string;
+ if (a === name) return argv[i + 1];
+ if (a.startsWith(`${name}=`)) return a.slice(name.length + 1);
+ }
+ return undefined;
+}
+
+const env = process.env;
+const model = flag("--model") ?? "fake-answer";
+const sessionId = flag("--session-id") ?? randomUUID();
+const agent = flag("--agent");
+const scenario = asClaude
+ ? (env.FAKE_SCENARIO ?? "marker")
+ : model.startsWith("fake-")
+ ? model.slice(5).replace(/-\d+$/, "")
+ : "marker";
+const COLS = Number(env.COLUMNS) || 160;
+const ROWS = Number(env.LINES) || 50;
+const cwd = (() => {
+ try {
+ return realpathSync(process.cwd());
+ } catch {
+ return process.cwd();
+ }
+})();
+
+function gap(name: string, dflt: number): number {
+ const v = Number(env[`FAKE_GAP_MS_${name}`]);
+ return Number.isFinite(v) && v >= 0 ? v : dflt;
+}
+
+const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
+
+/* ───────────────────────────── fixtures ───────────────────────────── */
+
+const FIX = join(import.meta.dir, "..", "test-fixtures");
+// biome-ignore lint/suspicious/noExplicitAny: raw JSON records copied from real captures
+type Rec = Record<string, any>;
+
+function lines(name: string): Rec[] {
+ return readFileSync(join(FIX, "transcripts", `${name}.jsonl`), "utf8")
+ .split("\n")
+ .filter(Boolean)
+ .map((l) => JSON.parse(l));
+}
+
+function screenLines(name: string): string[] {
+ return (
+ JSON.parse(readFileSync(join(FIX, "screens", `${name}.json`), "utf8")) as { lines: string[] }
+ ).lines;
+}
+
+const TOOLS = lines("tools-session");
+const T = {
+ user: TOOLS[4] as Rec,
+ text: TOOLS[28] as Rec,
+ td: TOOLS[29] as Rec,
+ tdPending: TOOLS[72] as Rec,
+ bashUse: TOOLS[19] as Rec,
+ bashResult: TOOLS[20] as Rec,
+ bgBashUse: TOOLS[45] as Rec,
+ bgBashResult: TOOLS[46] as Rec,
+ bgNotify: TOOLS[53] as Rec,
+ agentUse: TOOLS[61] as Rec,
+ agentResult: TOOLS[62] as Rec,
+ agentNotify: TOOLS[73] as Rec,
+ askUse: TOOLS[82] as Rec,
+ rejectResult: TOOLS[83] as Rec,
+ interruptTool: TOOLS[84] as Rec,
+ interruptPlain: TOOLS[98] as Rec,
+ readUse: TOOLS[132] as Rec,
+ readResult: TOOLS[133] as Rec,
+ compactBoundary: TOOLS[144] as Rec,
+ compactSummary: TOOLS[145] as Rec,
+ stopSummary: lines("stop-hook-matrix")[25] as Rec,
+ apiError: lines("api-error-hookless")[18] as Rec,
+ writeUse: lines("permission-write-esc")[19] as Rec,
+ command: lines("slash-and-reads")[4] as Rec,
+};
+const MAX_TOKENS_SLICE = lines("max-tokens-hookless").slice(18, 26);
+const REFUSAL_SLICE = lines("corpus-redacted/refusal-then-fallback").slice(30, 36);
+
+/* ───────────────────────────── transcript writer ───────────────────────────── */
+
+const configDir = env.CLAUDE_CONFIG_DIR || join(env.HOME ?? "/tmp", ".claude");
+const transcript = join(
+ configDir,
+ "projects",
+ cwd.replace(/[^a-zA-Z0-9]/g, "-"),
+ `${sessionId}.jsonl`
+);
+let parent: string | null = null;
+let msgCounter = 0;
+const writeTranscript = ![
+ "no_transcript",
+ "empty_transcript",
+ "missing_no_warning",
+ "screen_fast",
+ "screen_api_error",
+].includes(scenario);
+
+function newMsgId(): string {
+ return `msg_fake${process.pid}_${++msgCounter}_${randomUUID().slice(0, 8)}`;
+}
+
+function emit(template: Rec, patch: (r: Rec) => void = () => {}): Rec {
+ const r = structuredClone(template);
+ r.uuid = randomUUID();
+ if ("parentUuid" in r) r.parentUuid = parent;
+ r.timestamp = new Date().toISOString();
+ if ("sessionId" in r) r.sessionId = sessionId;
+ if ("session_id" in r) r.session_id = sessionId;
+ if ("cwd" in r) r.cwd = cwd;
+ patch(r);
+ if (writeTranscript) {
+ mkdirSync(dirname(transcript), { recursive: true });
+ appendFileSync(transcript, `${JSON.stringify(r)}\n`);
+ }
+ parent = r.uuid;
+ return r;
+}
+
+const rec = {
+ user(text: string) {
+ return emit(T.user, (r) => {
+ r.message.content = text;
+ r.promptId = randomUUID();
+ });
+ },
+ command(name: string, args: string) {
+ return emit(T.command, (r) => {
+ r.message.content = `<command-message>${name}</command-message>\n<command-name>/${name}</command-name>${args ? `\n<command-args>${args}</command-args>` : ""}`;
+ });
+ },
+ text(text: string, stop: string | null = "end_turn", id = newMsgId()) {
+ return emit(T.text, (r) => {
+ r.message.id = id;
+ r.message.content = [{ type: "text", text }];
+ r.message.stop_reason = stop;
+ });
+ },
+ toolUse(
+ name: string,
+ input: unknown,
+ opts: { id?: string; msgId?: string; template?: Rec } = {}
+ ) {
+ const id = opts.id ?? `toolu_fake${randomUUID().replace(/-/g, "").slice(0, 20)}`;
+ emit(opts.template ?? T.bashUse, (r) => {
+ r.message.id = opts.msgId ?? newMsgId();
+ r.message.content = [{ ...r.message.content[0], type: "tool_use", id, name, input }];
+ r.message.stop_reason = "tool_use";
+ });
+ return id;
+ },
+ toolResult(
+ id: string,
+ content: unknown,
+ tur: unknown,
+ opts: { isError?: boolean; template?: Rec } = {}
+ ) {
+ return emit(opts.template ?? T.bashResult, (r) => {
+ r.message.content = [
+ { tool_use_id: id, type: "tool_result", content, is_error: !!opts.isError },
+ ];
+ r.toolUseResult = tur;
+ r.sourceToolAssistantUUID = parent;
+ });
+ },
+ td(pending = 0) {
+ return emit(pending > 0 ? T.tdPending : T.td, (r) => {
+ if (pending > 0) r.pendingBackgroundAgentCount = pending;
+ else delete r.pendingBackgroundAgentCount;
+ });
+ },
+ stopSummary() {
+ return emit(T.stopSummary);
+ },
+ interrupt(forTool: boolean) {
+ return emit(forTool ? T.interruptTool : T.interruptPlain);
+ },
+ notify(template: Rec, oldId: string, newId: string) {
+ return emit(template, (r) => {
+ r.message.content = String(r.message.content).replaceAll(oldId, newId);
+ });
+ },
+ apiError(text: string) {
+ return emit(T.apiError, (r) => {
+ r.message.id = randomUUID();
+ r.message.content = [{ type: "text", text }];
+ });
+ },
+ /** Replay a real slice with fresh ids (message ids made unique, tool ids kept per slice). */
+ slice(records: Rec[]) {
+ const ids = new Map<string, string>();
+ for (const t of records) {
+ emit(t, (r) => {
+ const mid = r.message?.id;
+ if (typeof mid === "string" && r.type === "assistant") {
+ if (!ids.has(mid)) ids.set(mid, newMsgId());
+ r.message.id = ids.get(mid);
+ }
+ });
+ }
+ },
+};
+
+/* ───────────────────────────── screen ───────────────────────────── */
+
+const BANNER = screenLines("repl-boot-empty").slice(0, 4);
+const RULE = "─".repeat(COLS);
+const STATUS = [
+ " cwd • fake • $0.000 • N/A",
+ " ⏵⏵ bypass permissions on (shift+tab to cycle) · ← for agents",
+];
+const PLACEHOLDER = 'Try "how does <filepath> work?"'; // repl-boot-placeholder, attr 2 (faint)
+
+const S = {
+ booted: false,
+ box: "",
+ history: [] as string[],
+ working: null as string | null,
+ full: null as string[] | null, // a whole fixture screen (dialogs, panels)
+ menu: null as string | null,
+ statusTick: 0,
+ ghost: false,
+};
+
+function fit(l: string): string {
+ return Array.from(l).slice(0, COLS).join("");
+}
+
+function render(): void {
+ let out = "\x1b[H\x1b[2J";
+ const rows = S.full ? S.full.slice(0, ROWS) : replRows();
+ rows.forEach((l, y) => {
+ if (!l) return;
+ out += `\x1b[${y + 1};1H`;
+ if (l.startsWith("\u0000ghost")) out += `❯ \x1b[2m${PLACEHOLDER}\x1b[22m`;
+ else out += fit(l);
+ });
+ const boxRow = S.full ? ROWS - 1 : ROWS - 4;
+ out += `\x1b[${boxRow + 1};${3 + Array.from(S.box.split("\n").pop() ?? "").length}H`;
+ process.stdout.write(out);
+}
+
+function replRows(): string[] {
+ const out: string[] = Array.from({ length: ROWS }, () => "");
+ const boxLines = S.box.split("\n");
+ const top = ROWS - 4 - boxLines.length;
+ BANNER.forEach((l, i) => {
+ out[i] = i === 3 ? `${l.slice(0, 11)}${cwd}` : l;
+ });
+ out[top] = RULE;
+ boxLines.forEach((l, i) => {
+ out[top + 1 + i] = i === 0 ? `❯ ${l}` : ` ${l}`;
+ });
+ if (!S.box && S.ghost) out[top + 1] = "\u0000ghost";
+ out[ROWS - 3] = RULE;
+ out[ROWS - 2] = S.statusTick ? `${STATUS[0]} · ${S.statusTick}` : (STATUS[0] as string);
+ out[ROWS - 1] = STATUS[1] as string;
+ const above: string[] = [...S.history];
+ if (S.working) above.push(S.working);
+ if (S.menu) above.push("", S.menu);
+ const room = top - 4;
+ const shown = above.slice(-room);
+ shown.forEach((l, i) => {
+ out[4 + i] = l;
+ });
+ return out;
+}
+
+function showHistory(...rows: string[]): void {
+ S.history.push(...rows);
+ render();
+}
+
+function finishedRow(): string {
+ return "✻ Cogitated for 1s";
+}
+
+/* ───────────────────────────── turns ───────────────────────────── */
+
+const TEMPLATE_RE = /^Your task is in the file `([^`]+)`\./;
+let turn = 0;
+let busy = false;
+let pendingEsc: (() => void) | null = null;
+let swallowUntilEsc = false;
+let firstSubmitIgnored = false;
+let menuEaten = false;
+
+function sha8(s: string): string {
+ return createHash("sha1").update(s).digest("hex").slice(0, 8);
+}
+
+function answerFor(content: string): string {
+ if (scenario === "no_shape") return "Here is some prose without the expected shape.";
+ if (scenario === "multibyte") return `答え 🍐 ANSWER ${model} ${sha8(content)} — 東京 ✓`;
+ return `ANSWER ${model} ${sha8(content)}`;
+}
+
+interface Delivered {
+ content: string;
+ file: string | null;
+}
+
+/** Read the turn file the way Read does: numbered lines, `toolUseResult.file`, CR stripped. */
+function readTurnFile(
+ file: string,
+ line: string,
+ opts: { narrate?: boolean; partial?: boolean }
+): string {
+ const text = readFileSync(file, "utf8");
+ const all = text.split("\n").map((l) => (l.endsWith("\r") ? l.slice(0, -1) : l));
+ const take = opts.partial ? all.slice(0, Math.max(1, Math.ceil(all.length / 2))) : all;
+ const msgId = newMsgId();
+ if (opts.narrate) rec.text("I'll read the task file first.", "tool_use", msgId);
+ const id = rec.toolUse("Read", { file_path: file }, { msgId, template: T.readUse });
+ const content = take.map((l, i) => `${i + 1}\t${l}`).join("\n");
+ rec.toolResult(
+ id,
+ content,
+ {
+ type: "text",
+ file: {
+ filePath: file,
+ content: take.join("\n"),
+ numLines: take.length,
+ startLine: 1,
+ totalLines: all.length,
+ },
+ },
+ { template: T.readResult }
+ );
+ const marker = line.includes("ending in ⤶") ? "⤶" : line.includes("ending in ↩") ? "↩" : null;
+ let joined = take.join("\n");
+ if (marker) joined = joinSplit(joined, marker);
+ return joined;
+}
+
+function joinSplit(content: string, marker: string): string {
+ const out: string[] = [];
+ let acc = "";
+ for (const l of content.split("\n")) {
+ if (l.endsWith(marker)) acc += l.slice(0, -marker.length);
+ else {
+ out.push(acc + l);
+ acc = "";
+ }
+ }
+ if (acc) out.push(acc);
+ return out.join("\n");
+}
+
+function deliveredOf(line: string): Delivered {
+ const m = line.match(TEMPLATE_RE);
+ if (!m) return { content: line, file: null };
+ const file = m[1] as string;
+ if (scenario === "no_read") return { content: "", file };
+ const content = readTurnFile(file, line, {
+ narrate: scenario === "narrate_then_read",
+ partial: scenario === "partial_read",
+ });
+ return { content, file };
+}
+
+function markerScenario(content: string): string {
+ if (env.CONTRACT_FAKE_HANG === "1" || content.includes("@@HANG@@")) return "hang";
+ if (content.includes("@@TOOL@@")) return "tool";
+ if (content.includes("@@LINGER@@")) return "linger";
+ if (content.includes("@@LATE@@")) return "rewake";
+ return "answer";
+}
+
+/** Blocking scenarios block turn 1 only; the prompt sent after the decline is answered. */
+const FIRST_TURN_ONLY = new Set(["ask_user", "ask_user_send", "interrupt_td", "permission"]);
+
+function effectiveScenario(content: string): string {
+ if (scenario === "marker") return markerScenario(content);
+ if (turn > 1 && FIRST_TURN_ONLY.has(scenario)) return "answer";
+ return scenario;
+}
+
+async function answerTurn(content: string): Promise<void> {
+ rec.text(answerFor(content));
+ rec.td();
+ showHistory(`⏺ ${answerFor(content)}`, finishedRow());
+}
+
+function waitEsc(): Promise<void> {
+ return new Promise((r) => {
+ pendingEsc = r;
+ });
+}
+
+async function runScenario(name: string, d: Delivered): Promise<void> {
+ const c = d.content;
+ switch (name) {
+ case "hang":
+ S.working = "✶ Simmering… (thinking)";
+ render();
+ await new Promise(() => {});
+ return;
+ case "tool":
+ case "tool_slow":
+ case "tool_slow_numbered": {
+ const id = rec.toolUse("Bash", { command: "sleep 5", description: "Sleep for 5 seconds" });
+ if (name === "tool_slow_numbered") S.full = screenLines("numbered-prose-bash-running");
+ else showHistory("⏺ Sleeping for 5 seconds", " ⎿ $ sleep 5");
+ render();
+ await sleep(name === "tool" ? 100 : gap("TOOL", 5000));
+ S.full = null;
+ rec.toolResult(id, "", {
+ stdout: "",
+ stderr: "",
+ interrupted: false,
+ isImage: false,
+ noOutputExpected: true,
+ });
+ S.history.push(" Ran 1 shell command");
+ return answerTurn(c);
+ }
+ case "linger":
+ rec.text(answerFor(c));
+ showHistory(`⏺ ${answerFor(c)}`);
+ await sleep(gap("LINGER", Number(env.LINGER_MS) || 1500));
+ rec.stopSummary();
+ rec.td();
+ showHistory(finishedRow());
+ return;
+ case "quiet":
+ rec.text(answerFor(c));
+ rec.stopSummary();
+ showHistory(`⏺ ${answerFor(c)}`, finishedRow());
+ return;
+ case "quiet_no_summary":
+ rec.text(answerFor(c));
+ showHistory(`⏺ ${answerFor(c)}`, finishedRow());
+ return;
+ case "hookless_quiet":
+ rec.text(answerFor(c));
+ if (turn === 1) rec.td();
+ showHistory(`⏺ ${answerFor(c)}`, finishedRow());
+ return;
+ case "rewake":
+ rec.text(answerFor(c));
+ rec.stopSummary();
+ showHistory(`⏺ ${answerFor(c)}`, finishedRow());
+ await sleep(gap("REWAKE", 2000));
+ rec.text("LATE second message");
+ rec.td();
+ showHistory("⏺ LATE second message", finishedRow());
+ return;
+ case "slow_stop_hook":
+ rec.text(answerFor(c));
+ showHistory(`⏺ ${answerFor(c)}`);
+ await sleep(gap("HOOK", 3000));
+ rec.stopSummary();
+ rec.td();
+ showHistory(finishedRow());
+ return;
+ case "bg_rewake":
+ return bgRewake(c);
+ case "bg_server":
+ return bgServer(c);
+ case "ask_user":
+ case "ask_user_send":
+ case "interrupt_td":
+ return askUser(name, c);
+ case "permission":
+ return permission(c);
+ case "narrate_then_read":
+ rec.text("VERDICT: ok");
+ rec.td();
+ showHistory("⏺ VERDICT: ok", finishedRow());
+ return;
+ case "compaction":
+ rec.text("before compaction");
+ rec.slice([T.compactBoundary, T.compactSummary]);
+ rec.text(answerFor(c));
+ rec.td();
+ showHistory(`⏺ ${answerFor(c)}`, finishedRow());
+ return;
+ case "max_tokens":
+ rec.slice(MAX_TOKENS_SLICE);
+ rec.td();
+ showHistory(
+ "⏺ API Error: Claude's response exceeded the output token maximum.",
+ finishedRow()
+ );
+ return;
+ case "refusal":
+ rec.slice(REFUSAL_SLICE);
+ rec.text(answerFor(c));
+ rec.td();
+ showHistory(`⏺ ${answerFor(c)}`, finishedRow());
+ return;
+ case "null_stop":
+ rec.text(answerFor(c), null);
+ rec.td();
+ showHistory(`⏺ ${answerFor(c)}`, finishedRow());
+ return;
+ case "api_error":
+ rec.apiError("Please run /login · API Error: 401 OAuth access token is invalid.");
+ rec.td();
+ showHistory(
+ "⏺ Please run /login · API Error: 401 OAuth access token is invalid.",
+ finishedRow()
+ );
+ return;
+ case "exit_mid_turn":
+ await sleep(300);
+ return quit(3);
+ case "exit_after_settle":
+ case "interactive_exit_after_settle":
+ rec.text(answerFor(c));
+ rec.td();
+ showHistory(`⏺ ${answerFor(c)}`, finishedRow());
+ await sleep(20);
+ return quit(0);
+ case "exit_before_td":
+ rec.text(answerFor(c));
+ showHistory(`⏺ ${answerFor(c)}`);
+ await sleep(20);
+ return quit(0);
+ case "turn2_exit0":
+ if (turn >= 2) {
+ await sleep(200);
+ return quit(0);
+ }
+ return answerTurn(c);
+ default:
+ return answerTurn(c);
+ }
+}
+
+async function bgRewake(c: string): Promise<void> {
+ const agentId = `a${randomUUID().replace(/-/g, "").slice(0, 16)}`;
+ const oldId = String(T.agentResult.toolUseResult.agentId);
+ const id = rec.toolUse(
+ "Agent",
+ { description: "fruit", prompt: "Reply OK", subagent_type: "general-purpose" },
+ { template: T.agentUse }
+ );
+ rec.toolResult(
+ id,
+ T.agentResult.message.content[0].content,
+ { ...T.agentResult.toolUseResult, agentId },
+ { template: T.agentResult }
+ );
+ rec.text("LAUNCHED");
+ rec.td(1);
+ showHistory("⏺ LAUNCHED", "✻ Waiting for 1 background agent to finish");
+ await sleep(gap("BG", 1500));
+ rec.notify(T.agentNotify, oldId, agentId);
+ rec.text(answerFor(c));
+ rec.td();
+ showHistory(`⏺ Agent "fruit" finished · 1s`, `⏺ ${answerFor(c)}`, finishedRow());
+}
+
+async function bgServer(c: string): Promise<void> {
+ const id = rec.toolUse(
+ "Bash",
+ {
+ command: "fake-dev-server --port 0",
+ description: "Background server",
+ run_in_background: true,
+ },
+ { template: T.bgBashUse }
+ );
+ rec.toolResult(
+ id,
+ T.bgBashResult.message.content[0].content,
+ { ...T.bgBashResult.toolUseResult, backgroundTaskId: `b${process.pid}` },
+ { template: T.bgBashResult }
+ );
+ // a real process in the pane group, so the reap can be seen ending "the shell"
+ spawn("sleep", ["300"], { stdio: "ignore" }).unref();
+ return answerTurn(c);
+}
+
+async function askUser(name: string, _c: string): Promise<void> {
+ const id = rec.toolUse("AskUserQuestion", T.askUse.message.content[0].input, {
+ template: T.askUse,
+ });
+ S.full = screenLines("ask-user-question");
+ render();
+ await waitEsc();
+ S.full = null;
+ rec.toolResult(id, T.rejectResult.message.content[0].content, "User rejected tool use", {
+ isError: true,
+ template: T.rejectResult,
+ });
+ rec.interrupt(true);
+ if (name === "interrupt_td") rec.td();
+ showHistory(
+ "⏺ User declined to answer questions",
+ " ⎿ Interrupted · What should Claude do instead?"
+ );
+}
+
+async function permission(_c: string): Promise<void> {
+ const id = rec.toolUse(
+ "Write",
+ { file_path: join(cwd, "hello.txt"), content: "hi" },
+ { template: T.writeUse }
+ );
+ S.full = screenLines("permission-write");
+ render();
+ await waitEsc();
+ S.full = null;
+ rec.toolResult(id, T.rejectResult.message.content[0].content, "User rejected tool use", {
+ isError: true,
+ template: T.rejectResult,
+ });
+ rec.interrupt(true);
+ rec.td();
+ showHistory(" ⎿ User rejected write to hello.txt");
+}
+
+async function screenOnlyTurn(line: string): Promise<void> {
+ // degraded scenarios: no transcript evidence at all; the screen is the only witness
+ S.history.push(`❯ ${line}`);
+ if (scenario === "no_transcript") S.history.push(" ⎿ Transcript saving is off");
+ if (scenario !== "screen_fast") {
+ S.working = "✶ Simmering… (1s)";
+ render();
+ await sleep(gap("SCREEN", 600));
+ }
+ S.working = null;
+ if (scenario === "screen_api_error")
+ showHistory(
+ "⏺ Please run /login · API Error: 401 OAuth access token is invalid.",
+ finishedRow()
+ );
+ else showHistory(`⏺ ${answerFor(line)}`, finishedRow());
+}
+
+async function submit(line: string): Promise<void> {
+ turn++;
+ busy = true;
+ try {
+ if (
+ [
+ "no_transcript",
+ "empty_transcript",
+ "missing_no_warning",
+ "screen_fast",
+ "screen_api_error",
+ ].includes(scenario)
+ )
+ return await screenOnlyTurn(line);
+ if (scenario === "slow_prompt_hook") {
+ S.history.push(`❯ ${line}`);
+ S.working = "✶ Blanching… (running UserPromptSubmit hook · 2s)";
+ render();
+ await sleep(gap("PROMPT_HOOK", 12_000));
+ S.working = null;
+ rec.user(line);
+ } else {
+ if (scenario !== "immediate_write") await sleep(gap("WITNESS", 50));
+ const slash = line.match(/^\/([A-Za-z0-9][A-Za-z0-9:_-]*)\s*(.*)$/);
+ if (slash) rec.command(slash[1] as string, slash[2] ?? "");
+ else rec.user(line);
+ S.history.push(`❯ ${line.split("\n")[0]}`);
+ }
+ S.working = "✶ Simmering… (thinking)";
+ render();
+ await sleep(gap("THINK", 50));
+ const d = deliveredOf(line);
+ S.working = null;
+ await runScenario(effectiveScenario(d.content), d);
+ } finally {
+ S.working = null;
+ busy = false;
+ render();
+ }
+}
+
+/* ───────────────────────────── keys ───────────────────────────── */
+
+function onEnter(): void {
+ const text = S.box;
+ if (!text.trim()) return;
+ if (scenario === "menu_eats_enter" && !menuEaten) {
+ menuEaten = true; // the first Enter only closes a menu (phase-2 keylog: Esc/Enter on menus)
+ S.menu = null;
+ render();
+ return;
+ }
+ if (scenario === "ignore_input") return;
+ if (scenario === "promptless_first_send_ignored" && !firstSubmitIgnored) {
+ firstSubmitIgnored = true;
+ S.box = "";
+ render();
+ return;
+ }
+ S.box = "";
+ S.menu = null;
+ render();
+ const t = text.trim();
+ if (t === "/exit" || t === "/quit") return void quit(0);
+ if (t === "/cost") {
+ S.full = screenLines("usage-panel");
+ swallowUntilEsc = true;
+ render();
+ return;
+ }
+ if (busy) return; // a real REPL would queue it; the server never types while a turn runs
+ void submit(text);
+}
+
+function onEsc(): void {
+ if (swallowUntilEsc) {
+ swallowUntilEsc = false;
+ S.full = null;
+ render();
+ return;
+ }
+ if (S.menu) {
+ S.menu = null;
+ render();
+ return;
+ }
+ if (pendingEsc) {
+ const r = pendingEsc;
+ pendingEsc = null;
+ r();
+ }
+}
+
+function updateMenu(): void {
+ const b = S.box;
+ if (/^\/\S*$/.test(b))
+ S.menu = ` ❯ ${b.length > 1 ? b : "/add-dir"} Run a command`;
+ else if (/(^|\s)@\S*$/.test(b)) S.menu = " + notes.md";
+ else S.menu = null;
+}
+
+/** One plain key (not an escape sequence). */
+function onKey(ch: string): void {
+ if (ch === "\x1b") {
+ onEsc();
+ return;
+ }
+ if (swallowUntilEsc) return;
+ if (ch === "\r") {
+ onEnter();
+ return;
+ }
+ if (ch === "\n") S.box += "\n";
+ else if (ch === "\x7f" || ch === "\b") S.box = S.box.slice(0, -1);
+ else if (ch === "\x15") S.box = "";
+ else if (ch >= " ") S.box += ch;
+ updateMenu();
+}
+
+/** Consume a bracketed paste or a CSI/SS3 sequence at the head of `s`; null when none. */
+function consumeSequence(s: string): string | null {
+ if (s.startsWith("\x1b[200~")) {
+ const end = s.indexOf("\x1b[201~");
+ if (!swallowUntilEsc) S.box += end >= 0 ? s.slice(6, end) : s.slice(6);
+ return end >= 0 ? s.slice(end + 6) : "";
+ }
+ if (s.startsWith("\x1b[") || s.startsWith("\x1bO")) {
+ const m = s.slice(2).search(/[@-~]/);
+ return m >= 0 ? s.slice(m + 3) : "";
+ }
+ return null;
+}
+
+function onData(buf: Buffer): void {
+ let s = buf.toString("utf8");
+ while (s.length) {
+ const rest = consumeSequence(s);
+ if (rest !== null) {
+ s = rest;
+ continue;
+ }
+ onKey(s[0] as string);
+ s = s.slice(1);
+ }
+ render();
+}
+
+/* ───────────────────────────── lifecycle ───────────────────────────── */
+
+function restore(): void {
+ try {
+ process.stdout.write("\x1b[?2004l\x1b[?1049l");
+ } catch {
+ // pty gone
+ }
+}
+
+async function quit(code: number): Promise<void> {
+ restore();
+ await sleep(30);
+ process.exit(code);
+}
+
+function markSignal(sig: string): void {
+ const m = env.CONTRACT_FAKE_SIGTERM_MARKER;
+ if (m) {
+ try {
+ appendFileSync(m, `${sig}\n`);
+ } catch {
+ // ignore
+ }
+ }
+}
+
+function installSignals(): void {
+ const ignoreTerm = scenario === "ignore_term";
+ const ignoreHup = scenario === "ignore_hup" || ignoreTerm;
+ process.on("SIGTERM", () => {
+ markSignal("SIGTERM");
+ if (!ignoreTerm) process.exit(143);
+ });
+ process.on("SIGHUP", () => {
+ markSignal("SIGHUP");
+ if (!ignoreHup) process.exit(129);
+ });
+}
+
+function dumpClaudeMode(): void {
+ const out = env.FAKE_CLAUDE_DUMP;
+ if (!out) return;
+ const settingsArg = flag("--settings");
+ let settings: unknown = null;
+ if (settingsArg) {
+ try {
+ settings = JSON.parse(
+ settingsArg.trim().startsWith("{") ? settingsArg : readFileSync(settingsArg, "utf8")
+ );
+ } catch {
+ settings = settingsArg;
+ }
+ }
+ writeFileSync(out, JSON.stringify({ argv, env: { ...env }, cwd, settings }, null, 1));
+}
+
+async function boot(): Promise<void> {
+ if (asClaude) dumpClaudeMode();
+ if (env.FAKE_PROBE_FILE && scenario === "env_probe")
+ writeFileSync(env.FAKE_PROBE_FILE, JSON.stringify({ env: { ...env }, cwd, argv }, null, 1));
+ if (agent?.startsWith("zzz")) {
+ process.stdout.write(
+ `--agent '${agent}' not found. Available agents: claude, claude-code-guide, Explore, general-purpose, Plan, statusline-setup\r\n`
+ );
+ await sleep(50);
+ process.exit(1);
+ }
+ installSignals();
+ setTimeout(() => void quit(0), Number(env.CONTRACT_FAKE_MAX_MS) || 20_000).unref?.();
+ if (process.stdin.isTTY) process.stdin.setRawMode(true);
+ process.stdin.on("data", onData);
+ if (scenario === "orphan_grandchild") {
+ spawn("sleep", ["300"], { stdio: "ignore" }).unref();
+ setTimeout(() => process.exit(0), gap("ORPHAN", 3000));
+ }
+ if (scenario.startsWith("dialog_")) {
+ const name =
+ scenario === "dialog_unknown" ? "dialog-unnamed-mcp-server" : `dialog-${scenario.slice(7)}`;
+ S.full = screenLines(name);
+ render();
+ return;
+ }
+ if (scenario === "slow_boot") {
+ process.stdout.write("\x1b[H\x1b[2Jbooting the fake child…");
+ await sleep(gap("BOOT", 3000));
+ }
+ if (scenario === "empty_transcript") {
+ mkdirSync(dirname(transcript), { recursive: true });
+ writeFileSync(transcript, "");
+ }
+ process.stdout.write("\x1b[?1049h\x1b[?2004h");
+ S.booted = true;
+ S.ghost = scenario === "idle_suggestion";
+ render();
+ if (scenario === "status_tick")
+ setInterval(() => {
+ S.statusTick++;
+ render();
+ }, 1000);
+}
+
+void boot();
diff --git a/packages/cli/src/pane/test-helpers/pane-owner.ts b/packages/cli/src/pane/test-helpers/pane-owner.ts
new file mode 100644
index 00000000..f6c32261
--- /dev/null
+++ b/packages/cli/src/pane/test-helpers/pane-owner.ts
@@ -0,0 +1,65 @@
+#!/usr/bin/env bun
+/**
+ * A stand-alone pane OWNER for the registry tests (test-only): starts N pane sessions
+ * that hang (`@@HANG@@`), prints one JSON line describing them, then waits to be killed.
+ * The test SIGKILLs it to prove the watchers clean up with no help from the owner.
+ *
+ * Input: env PANE_OWNER_SPEC = JSON { n, sockRoot, cwd, configDir, env }.
+ */
+
+import { readFileSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+import { startPaneSession } from "../pane-session.js";
+
+const spec = JSON.parse(process.env.PANE_OWNER_SPEC ?? "{}") as {
+ n: number;
+ sockRoot: string;
+ cwd: string;
+ configDir: string;
+ env: Record<string, string>;
+};
+
+const sessions = await Promise.all(
+ Array.from({ length: spec.n }, async (_, i) => {
+ const uuid = crypto.randomUUID();
+ const s = await startPaneSession({
+ kind: "t",
+ label: `0${i + 1}`,
+ callerFlags: [],
+ spawnModel: "contract-fake-model",
+ cwd: spec.cwd,
+ sessionUuid: uuid,
+ transcriptPath: join(spec.configDir, "projects", "x", `${uuid}.jsonl`),
+ slotEnv: {},
+ shape: "one-shot",
+ initialPrompt: "@@HANG@@",
+ readAvailable: true,
+ parentEnv: { ...spec.env, CONTRACT_FAKE_MAX_MS: "120000" },
+ sockRoot: spec.sockRoot,
+ decide: () => ({ state: "COMPLETED" }),
+ onBlocked: () => "wait",
+ timings: { replStableMs: 200 },
+ });
+ await s.ready;
+ return { s, uuid };
+ })
+);
+
+// let the registry tick record each verified group (members with start times)
+await Bun.sleep(2500);
+const records = readdirSync(join(spec.sockRoot, "panes")).map((n) =>
+ JSON.parse(readFileSync(join(spec.sockRoot, "panes", n), "utf8"))
+);
+process.stdout.write(
+ `${JSON.stringify({
+ owner: process.pid,
+ panes: sessions.map(({ s, uuid }) => ({
+ paneId: s.paneId,
+ uuid,
+ state: s.snapshot().state,
+ panePid: s.snapshot().panePid,
+ })),
+ records,
+ })}\n`
+);
+await new Promise(() => {});