Skip to content

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

feat(mcp)!: run create_session as an interactive pane in headless magmux

Jack Rudenko352e1ee15350
diff --git a/packages/cli/src/agent-availability.test.ts b/packages/cli/src/agent-availability.test.ts
deleted file mode 100644
index e226d432..00000000
--- a/packages/cli/src/agent-availability.test.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-import { describe, expect, test } from "bun:test";
-import {
- assertAgentAvailable,
- clearAgentCache,
- discoverAvailableAgents,
- parseAvailableAgents,
- seedAgentCacheForTest,
-} from "./agent-availability.js";
-
-describe("parseAvailableAgents", () => {
- test("extracts the agent list from Claude Code's rejection message", () => {
- // Real message shape, measured 2026-08-22.
- const msg =
- "--agent 'zzz-bogus' not found. Available agents: claude, code-analysis:detective, " +
- "dev:architect, dev:reviewer, Explore, general-purpose";
- expect(parseAvailableAgents(msg)).toEqual([
- "claude",
- "code-analysis:detective",
- "dev:architect",
- "dev:reviewer",
- "Explore",
- "general-purpose",
- ]);
- });
-
- test("returns null when the agent list is absent", () => {
- expect(parseAvailableAgents("some unrelated output")).toBeNull();
- expect(parseAvailableAgents("")).toBeNull();
- });
-
- test("returns null rather than an empty agent list", () => {
- // An empty list must not be cached as "no agents exist", which would reject
- // every name. Null means "could not determine" and fails open.
- expect(parseAvailableAgents("Available agents: ")).toBeNull();
- });
-});
-
-describe("assertAgentAvailable — with a known agent list", () => {
- const CWD = "/seeded/project";
-
- test("accepts a name that is on the agent list", async () => {
- clearAgentCache();
- seedAgentCacheForTest(CWD, ["dev:reviewer", "dev:architect", "general-purpose"]);
- await assertAgentAvailable("dev:reviewer", CWD);
- });
-
- test("REJECTS a typo, naming the valid agents", async () => {
- // The behaviour this module exists for. Claude Code silently ignores an
- // unknown --agent under --input-format stream-json and runs the DEFAULT
- // agent, so a typo would otherwise produce a plausible answer from the
- // wrong agent with nothing saying so.
- clearAgentCache();
- seedAgentCacheForTest(CWD, ["dev:reviewer", "dev:architect"]);
- await expect(assertAgentAvailable("dev:reviwer", CWD)).rejects.toThrow(
- /Unknown agent 'dev:reviwer'/
- );
- await expect(assertAgentAvailable("dev:reviwer", CWD)).rejects.toThrow(/dev:architect/);
- });
-
- test("is case- and whitespace-exact — no silent coercion", async () => {
- // Claude Code matches the name exactly; accepting "DEV:REVIEWER" here would
- // pass validation and then be ignored downstream, recreating the trap.
- clearAgentCache();
- seedAgentCacheForTest(CWD, ["dev:reviewer"]);
- await expect(assertAgentAvailable("DEV:REVIEWER", CWD)).rejects.toThrow(/Unknown agent/);
- await expect(assertAgentAvailable(" dev:reviewer ", CWD)).rejects.toThrow(/Unknown agent/);
- });
-
- test("agent lists are isolated per cwd", async () => {
- // Measured: this repo resolves 24 agents, /tmp resolves 5. A global cache
- // would reject an agent that is valid in the directory the child runs in.
- clearAgentCache();
- seedAgentCacheForTest("/project/a", ["dev:reviewer"]);
- seedAgentCacheForTest("/project/b", ["general-purpose"]);
- await assertAgentAvailable("dev:reviewer", "/project/a");
- await expect(assertAgentAvailable("dev:reviewer", "/project/b")).rejects.toThrow(
- /Unknown agent/
- );
- });
-
- test("a seeded agent list is served from cache, not re-probed", async () => {
- // The seeded cwd does not exist, so a probe would fail open and accept
- // anything. Rejection proves the cached agent list was used.
- clearAgentCache();
- seedAgentCacheForTest("/nonexistent-cached-dir", ["only-this-one"]);
- await expect(assertAgentAvailable("something-else", "/nonexistent-cached-dir")).rejects.toThrow(
- /Unknown agent/
- );
- expect((await discoverAvailableAgents("/nonexistent-cached-dir"))?.has("only-this-one")).toBe(
- true
- );
- });
-});
-
-describe("assertAgentAvailable — degenerate inputs", () => {
- test("no agent named is a no-op and never probes", async () => {
- clearAgentCache();
- await assertAgentAvailable(undefined, "/nonexistent-dir-for-test");
- await assertAgentAvailable("", "/nonexistent-dir-for-test");
- });
-
- test("fails OPEN when the agent list cannot be determined", async () => {
- // Spawning in a directory that does not exist makes the probe error.
- // Blocking every session because a probe broke would be worse than the trap
- // this guards, so an undeterminable agent list must not throw.
- clearAgentCache();
- await assertAgentAvailable("whatever-agent", "/nonexistent-dir-for-test-xyz");
- });
-});
diff --git a/packages/cli/src/agent-availability.ts b/packages/cli/src/agent-availability.ts
deleted file mode 100644
index 34673334..00000000
--- a/packages/cli/src/agent-availability.ts
+++ /dev/null
@@ -1,150 +0,0 @@
-import { spawn } from "node:child_process";
-
-/**
- * Is a `--agent` name real?
- *
- * WHY THIS EXISTS. Claude Code validates `--agent` and fails loudly with the list
- * of valid names — but NOT under `--input-format stream-json`, where an unknown
- * name is silently ignored and the session runs the DEFAULT agent instead.
- * Measured 2026-08-22, one variable between the two runs:
- *
- * claude … --output-format stream-json --input-format stream-json --agent zzz-bogus
- * → exit 0, nothing on stderr, default agent silently used
- * claude … --output-format stream-json --agent zzz-bogus
- * → exit 1, "--agent 'zzz-bogus' not found. Available agents: …"
- *
- * The channel transport (`create_session`) spawns with `--input-format stream-json`,
- * so a typo there — `agent: "dev:reviwer"` — produces a plausible answer from the
- * wrong agent with nothing anywhere saying so. That is a failure that reports itself
- * as a success, which is the exact defect class the `require_pattern` work exists to
- * kill. `team` is unaffected (it spawns `--stdin`), but validating centrally covers
- * both and keeps them from drifting.
- */
-
-/** A name no real agent can hold, used to make Claude Code print its agent list. */
-const PROBE_AGENT = "__claudish_agent_probe__";
-
-/** How long a discovered agent list stays fresh. Plugins can be installed mid-session. */
-const TTL_MS = 5 * 60_000;
-
-interface Entry {
- agents: Set<string>;
- at: number;
-}
-
-/**
- * Keyed by cwd — NOT global. The agent list is resolved relative to the working
- * directory: measured from this repo it is 24 names including every plugin agent,
- * and from /tmp it is 5. Caching globally would reject valid agents for one
- * directory because another had a narrower agent list.
- */
-const cache = new Map<string, Entry>();
-
-/** Extract the agent list from Claude Code's rejection message. Null if absent. */
-export function parseAvailableAgents(output: string): string[] | null {
- const m = /Available agents:\s*(.+)/.exec(output);
- if (!m) return null;
- const names = m[1]
- .split(",")
- .map((s) => s.trim())
- .filter(Boolean);
- return names.length > 0 ? names : null;
-}
-
-/** Run the probe. Resolves to null when the agent list cannot be determined. */
-async function probe(cwd: string): Promise<Set<string> | null> {
- return new Promise((resolveP) => {
- let out = "";
- let settled = false;
- const done = (v: Set<string> | null) => {
- if (!settled) {
- settled = true;
- resolveP(v);
- }
- };
- try {
- // `-p` with a bogus agent fails on ARGUMENT validation before any model
- // work — measured at ~0.5s, no API call, no tokens.
- const child = spawn("claude", ["--agent", PROBE_AGENT, "-p"], {
- cwd,
- stdio: ["pipe", "pipe", "pipe"],
- shell: false,
- });
- const timer = setTimeout(() => {
- child.kill("SIGKILL");
- done(null);
- }, 15_000);
- child.stdout.on("data", (d) => {
- out += d;
- });
- child.stderr.on("data", (d) => {
- out += d;
- });
- child.on("error", () => {
- clearTimeout(timer);
- done(null);
- });
- child.on("close", () => {
- clearTimeout(timer);
- const names = parseAvailableAgents(out);
- done(names ? new Set(names) : null);
- });
- // MUST end stdin: `-p` reads it, and an unclosed pipe hangs forever.
- child.stdin.end("probe\n");
- } catch {
- done(null);
- }
- });
-}
-
-/** The agent list for `cwd`, or null when it cannot be determined. Cached per cwd. */
-export async function discoverAvailableAgents(cwd: string): Promise<Set<string> | null> {
- const hit = cache.get(cwd);
- if (hit && Date.now() - hit.at < TTL_MS) return hit.agents;
- const agents = await probe(cwd);
- if (agents) cache.set(cwd, { agents, at: Date.now() });
- return agents;
-}
-
-/** Test seam — drop cached agent lists. */
-export function clearAgentCache(): void {
- cache.clear();
-}
-
-/**
- * Test seam — supply the agent list for `cwd` instead of probing.
- *
- * Exists because the accept/reject behaviour is the whole point of this module
- * and cannot otherwise be tested without spawning a real `claude`: a suite that
- * only covers "no agent named" and "agent list undeterminable" would stay green if
- * this file became a no-op. Seeding the cache is deliberately used rather than
- * mocking the module — a Bun `mock.module` on shared infrastructure bleeds into
- * sibling test files.
- */
-export function seedAgentCacheForTest(cwd: string, agents: string[]): void {
- cache.set(cwd, { agents: new Set(agents), at: Date.now() });
-}
-
-/**
- * Throw if `agent` is not a real agent in `cwd`.
- *
- * FAILS OPEN when the agent list cannot be determined (claude not on PATH, probe
- * timed out, output shape changed). Blocking every session because a probe broke
- * would be a worse failure than the one this guards, and it mirrors the contract
- * `prehydrateCredentialsForSpawn` already documents: a resolution step is an
- * optimisation of WHERE something is checked, not a gate on whether the spawn
- * proceeds.
- */
-export async function assertAgentAvailable(agent: string | undefined, cwd: string): Promise<void> {
- if (!agent) return;
- const available = await discoverAvailableAgents(cwd);
- if (!available) return; // fail open — see above
- if (available.has(agent)) return;
- const known = [...available].sort().join(", ");
- throw new Error(
- `Unknown agent '${agent}'. Available agents: ${known}. ` +
- "Claude Code silently ignores an unknown --agent under the channel transport " +
- "(--input-format stream-json) and runs the DEFAULT agent instead, so this is " +
- "rejected here rather than producing a plausible answer from the wrong agent."
- );
-}
diff --git a/packages/cli/src/channel/channel-wire-format.test.ts b/packages/cli/src/channel/channel-wire-format.test.ts
index 2787f203..a25f7ae6 100644
--- a/packages/cli/src/channel/channel-wire-format.test.ts
+++ b/packages/cli/src/channel/channel-wire-format.test.ts
@@ -2,18 +2,20 @@
* Channel notification wire-format regression tests.
*
* These tests pin the exact JSON-RPC contract that the MCP server emits over
- * stdio for channel notifications. They run without any API key by using the
- * fake-claudish PATH shim — fake-claudish produces deterministic stdout that
- * drives SignalWatcher state transitions, which in turn fire onStateChange
- * callbacks, which invoke server.notification(), which serialize JSON-RPC
- * frames to stdout.
+ * stdio for channel notifications. They run without any API key: the server's
+ * CLAUDISH_BIN is the pane fake (pane/test-helpers/fake-interactive-child.ts),
+ * which a real headless magmux runs as an interactive child; its transcript
+ * drives the pane session's state machine, whose transitions fire
+ * onStateChange callbacks, which invoke server.notification(), which serialize
+ * JSON-RPC frames to stdout. The server env is hermetic (contract-mcp.ts
+ * `serverEnv`) with its own pane root, and every test proves no pane is left.
*
* Why a dedicated test file:
* - The OPENROUTER_API_KEY-gated lifecycle test in e2e-channel.test.ts
* does similar checks but is skipped when the key is absent, so CI never
- * runs it. These tests run unconditionally.
+ * runs it. These tests run unconditionally (wherever magmux is installed).
* - We use raw JSON-RPC over child process pipes (not the MCP Client SDK)
- * so we can assert the literal frame bytes — that's the wire contract.
+ * so we can assert the literal frame objects — that's the wire contract.
*
* What's pinned:
* 1. The notification method name: "notifications/claude/channel"
@@ -26,306 +28,248 @@
* If a future refactor changes any of these, these tests will fail loudly.
*/
-import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+import { afterEach, describe, expect, test } from "bun:test";
import { type ChildProcess, spawn } from "node:child_process";
-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
-import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
+import {
+ FAKE_MODEL,
+ MAGMUX_AVAILABLE,
+ McpServer,
+ NO_MAGMUX_MESSAGE,
+ type ToolResult,
+ paneOrphans,
+ serverEnv,
+} from "../test-helpers/contract-mcp.js";
+import { type TempLayout, makeTempLayout, waitFor } from "../test-helpers/contract-records.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const SERVER_ENTRY = join(__dirname, "../index.ts");
-const FAKE_CLAUDISH_TS = join(__dirname, "test-helpers", "fake-claudish.ts");
-
-// ─── PATH shim setup ────────────────────────────────────────────────────────
-
-let shimDir: string;
-let sessionsDir: string;
-const ORIGINAL_PATH = process.env.PATH ?? "";
-const ORIGINAL_CLAUDISH_BIN = process.env.CLAUDISH_BIN;
-
-beforeAll(() => {
- shimDir = mkdtempSync(join(tmpdir(), "claudish-shim-wireformat-"));
- sessionsDir = mkdtempSync(join(tmpdir(), "claudish-sessions-wireformat-"));
- const shimPath = join(shimDir, "claudish");
- writeFileSync(shimPath, `#!/bin/sh\nexec bun run "${FAKE_CLAUDISH_TS}" "$@"\n`, { mode: 0o755 });
- // CLAUDISH_BIN outranks PATH in resolveClaudishSpawn, so leaving it set would defeat the fake shim.
- delete process.env.CLAUDISH_BIN;
- process.env.PATH = `${shimDir}:${ORIGINAL_PATH}`;
-});
-afterAll(() => {
- process.env.PATH = ORIGINAL_PATH;
- if (ORIGINAL_CLAUDISH_BIN === undefined) {
- delete process.env.CLAUDISH_BIN;
- } else {
- process.env.CLAUDISH_BIN = ORIGINAL_CLAUDISH_BIN;
- }
- if (shimDir) {
- try {
- rmSync(shimDir, { recursive: true, force: true });
- rmSync(sessionsDir, { recursive: true, force: true });
- } catch {}
- }
-});
+const TERMINAL_EVENTS = ["completed", "failed", "cancelled", "timeout"];
// ─── Helper: drive an MCP server session and capture frames ─────────────────
+interface ChannelFrame {
+ method: string;
+ params: { content: string; meta: Record<string, string> };
+ jsonrpc: string;
+}
+
interface CapturedFrames {
- notifications: Array<{
- method: string;
- params: { content: string; meta: Record<string, string> };
- jsonrpc: string;
- }>;
- responses: Array<{ id: number; result?: unknown; error?: unknown; jsonrpc: string }>;
- rawStdoutLines: string[];
- stderr: string;
+ notifications: ChannelFrame[];
+ createResult: ToolResult;
+}
+
+const layouts: TempLayout[] = [];
+
+afterEach(async () => {
+ // Every pane this file started is gone: no process, socket, record or launcher dir.
+ for (const layout of layouts.splice(0)) {
+ const report = await paneOrphans(layout);
+ layout.cleanup();
+ expect(report).toEqual({ processes: [], files: [] });
+ }
+});
+
+function channelFrames(server: McpServer): ChannelFrame[] {
+ return server.notifications.filter(
+ (n) => n.method === "notifications/claude/channel"
+ ) as unknown as ChannelFrame[];
}
+/**
+ * Start a server, create one session, collect its channel frames until `until` holds
+ * (default: a terminal event), then close the server (stdin EOF shuts it down).
+ */
async function captureSessionFrames(opts: {
- shimArgs?: string[]; // extra args passed to fake-claudish via spawn
+ model?: string;
+ prompt?: string;
+ until?: (frames: ChannelFrame[]) => boolean;
timeoutMs?: number;
}): Promise<CapturedFrames> {
- const proc: ChildProcess = spawn("bun", ["run", SERVER_ENTRY, "--mcp"], {
- stdio: ["pipe", "pipe", "pipe"],
- env: {
- ...process.env,
- CLAUDISH_MCP_TOOLS: "all",
- CLAUDISH_SESSIONS_DIR: sessionsDir,
- },
- });
-
- const captured: CapturedFrames = {
- notifications: [],
- responses: [],
- rawStdoutLines: [],
- stderr: "",
- };
-
- let stdoutBuf = "";
- let resolveDone: () => void;
- const done = new Promise<void>((r) => {
- resolveDone = r;
- });
-
- proc.stdout!.on("data", (chunk: Buffer) => {
- stdoutBuf += chunk.toString("utf-8");
- let nl: number;
- // biome-ignore lint/suspicious/noAssignInExpressions: canonical line-buffer drain idiom
- while ((nl = stdoutBuf.indexOf("\n")) !== -1) {
- const line = stdoutBuf.slice(0, nl);
- stdoutBuf = stdoutBuf.slice(nl + 1);
- if (!line.trim()) continue;
- captured.rawStdoutLines.push(line);
- try {
- const msg = JSON.parse(line);
- if (msg.method === "notifications/claude/channel") {
- captured.notifications.push(msg);
- // Resolve once we see a terminal event
- const evt = msg.params?.meta?.event;
- if (evt === "completed" || evt === "failed" || evt === "cancelled") {
- resolveDone();
- }
- } else if (msg.id !== undefined) {
- captured.responses.push(msg);
- }
- } catch {
- // not JSON, ignore
- }
- }
- });
-
- proc.stderr!.on("data", (chunk: Buffer) => {
- captured.stderr += chunk.toString("utf-8");
- });
-
- function send(rpc: object) {
- proc.stdin!.write(`${JSON.stringify(rpc)}\n`);
+ const layout = makeTempLayout("wireformat");
+ layouts.push(layout);
+ const server = await McpServer.start({ env: serverEnv(layout), cwd: layout.cwd });
+ try {
+ const createResult = await server.callTool("create_session", {
+ model: opts.model ?? FAKE_MODEL,
+ prompt: opts.prompt ?? "Reply with a short answer.",
+ timeout_seconds: 60,
+ });
+ expect(createResult.isError).toBe(false);
+ const until =
+ opts.until ??
+ ((frames: ChannelFrame[]) =>
+ frames.some((f) => TERMINAL_EVENTS.includes(f.params?.meta?.event)));
+ await waitFor(() => until(channelFrames(server)), {
+ what: "the expected channel frames",
+ timeoutMs: opts.timeoutMs ?? 20_000,
+ });
+ // Brief grace period to capture any final frames
+ await Bun.sleep(200);
+ return { notifications: [...channelFrames(server)], createResult };
+ } finally {
+ await server.close();
}
-
- // Initialize
- send({
- jsonrpc: "2.0",
- id: 1,
- method: "initialize",
- params: {
- protocolVersion: "2024-11-05",
- clientInfo: { name: "wire-format-test", version: "1.0.0" },
- capabilities: { experimental: { "claude/channel": {} } },
- },
- });
-
- await new Promise((r) => setTimeout(r, 300));
- send({ jsonrpc: "2.0", method: "notifications/initialized" });
- await new Promise((r) => setTimeout(r, 100));
-
- // create_session — fake-claudish ignores --model so any value works.
- // We pass an extra prompt-style arg via claudish_flags so fake-claudish
- // gets the --lines flag and produces deterministic output.
- send({
- jsonrpc: "2.0",
- id: 2,
- method: "tools/call",
- params: {
- name: "create_session",
- arguments: {
- model: "fake-model",
- prompt: "ignored",
- timeout_seconds: 10,
- claudish_flags: opts.shimArgs ?? ["--lines", "3"],
- },
- },
- });
-
- // Wait for terminal event or timeout
- const timeoutMs = opts.timeoutMs ?? 15_000;
- await Promise.race([done, new Promise<void>((r) => setTimeout(r, timeoutMs))]);
-
- // Brief grace period to capture any final frames
- await new Promise((r) => setTimeout(r, 200));
-
- proc.kill("SIGTERM");
- await new Promise<void>((r) => proc.on("exit", () => r()));
-
- return captured;
}
// ─── Tests ──────────────────────────────────────────────────────────────────
-describe("Channel notification wire format", () => {
- test("emits well-formed notifications/claude/channel JSON-RPC frames", async () => {
- const captured = await captureSessionFrames({ shimArgs: ["--lines", "3"] });
-
- // At least one notification should arrive (running + completed expected)
- expect(captured.notifications.length).toBeGreaterThan(0);
-
- for (const n of captured.notifications) {
- // Method name is exactly the contracted string
- expect(n.method).toBe("notifications/claude/channel");
-
- // JSON-RPC framing
- expect(n.jsonrpc).toBe("2.0");
-
- // params shape
- expect(n.params).toBeDefined();
- expect(typeof n.params.content).toBe("string");
- expect(n.params.meta).toBeDefined();
-
- // Required meta keys (current Claudish vocabulary)
- expect(n.params.meta.session_id).toMatch(/^[0-9a-f]{8}$/);
- expect(typeof n.params.meta.event).toBe("string");
- expect(n.params.meta.model).toBe("fake-model");
-
- // elapsed_seconds is serialized as a string (not a number) —
- // this is intentional per the MCP server's bridge: see mcp-server.ts
- // where it calls String(event.elapsedSeconds).
- expect(typeof n.params.meta.elapsed_seconds).toBe("string");
- expect(n.params.meta.elapsed_seconds).toMatch(/^\d+$/);
-
- // SEP-1686 forward-compat fields (additive — see mcp-server.ts bridge
- // and ai-docs/sessions/.../sep-1686-migration-schema.md)
- // task_id mirrors session_id (will become the only field after migration)
- expect(n.params.meta.task_id).toBe(n.params.meta.session_id);
- // status carries the SEP-1686 5-value TaskStatus enum
- expect(["working", "input_required", "completed", "failed", "cancelled"]).toContain(
- n.params.meta.status
- );
- // ISO 8601 timestamps
- expect(n.params.meta.created_at).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/);
- expect(n.params.meta.last_updated_at).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/);
- }
- }, 20_000);
-
- test("SEP-1686 status mapping: 9-value event collapses to 5-value status correctly", async () => {
- const captured = await captureSessionFrames({ shimArgs: ["--lines", "3"] });
- expect(captured.notifications.length).toBeGreaterThan(0);
-
- // Build (event, status) pairs and validate every observed pair against
- // the expected mapping defined in mcp-server.ts:EVENT_TO_TASK_STATUS.
- const expectedMapping: Record<string, string> = {
- starting: "working",
- running: "working",
- tool_executing: "working",
- waiting_for_input: "input_required",
- finishing: "working",
- completed: "completed",
- failed: "failed",
- cancelled: "cancelled",
- timeout: "failed",
- };
-
- for (const n of captured.notifications) {
- const event = n.params.meta.event as string;
- const status = n.params.meta.status as string;
- const expected = expectedMapping[event];
- if (expected !== undefined) {
- expect(status).toBe(expected);
- } else {
- // Unknown event types fall through to "working" per
- // mapEventToTaskStatus's default. If a NEW event type ever leaks
- // through without an entry in EVENT_TO_TASK_STATUS, this catches it.
- expect(status).toBe("working");
+describe.skipIf(!MAGMUX_AVAILABLE)(
+ `Channel notification wire format${MAGMUX_AVAILABLE ? "" : ` (${NO_MAGMUX_MESSAGE})`}`,
+ () => {
+ test("emits well-formed notifications/claude/channel JSON-RPC frames", async () => {
+ const captured = await captureSessionFrames({});
+
+ // At least one notification should arrive (running + completed expected)
+ expect(captured.notifications.length).toBeGreaterThan(0);
+
+ for (const n of captured.notifications) {
+ // Method name is exactly the contracted string
+ expect(n.method).toBe("notifications/claude/channel");
+
+ // JSON-RPC framing
+ expect(n.jsonrpc).toBe("2.0");
+
+ // params shape
+ expect(n.params).toBeDefined();
+ expect(typeof n.params.content).toBe("string");
+ expect(n.params.meta).toBeDefined();
+
+ // Required meta keys (current Claudish vocabulary)
+ expect(n.params.meta.session_id).toMatch(/^[0-9a-f]{8}$/);
+ expect(typeof n.params.meta.event).toBe("string");
+ expect(n.params.meta.model).toBe(FAKE_MODEL);
+
+ // elapsed_seconds is serialized as a string (not a number) —
+ // this is intentional per the MCP server's bridge: see mcp-server.ts
+ // where it calls String(event.elapsedSeconds).
+ expect(typeof n.params.meta.elapsed_seconds).toBe("string");
+ expect(n.params.meta.elapsed_seconds).toMatch(/^\d+$/);
+
+ // SEP-1686 forward-compat fields (additive — see mcp-server.ts bridge
+ // and ai-docs/sessions/.../sep-1686-migration-schema.md)
+ // task_id mirrors session_id (will become the only field after migration)
+ expect(n.params.meta.task_id).toBe(n.params.meta.session_id);
+ // status carries the SEP-1686 5-value TaskStatus enum
+ expect(["working", "input_required", "completed", "failed", "cancelled"]).toContain(
+ n.params.meta.status
+ );
+ // ISO 8601 timestamps
+ expect(n.params.meta.created_at).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/);
+ expect(n.params.meta.last_updated_at).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/);
}
- }
- }, 20_000);
-
- test("all notifications for one session share the same created_at timestamp", async () => {
- const captured = await captureSessionFrames({ shimArgs: ["--lines", "5"] });
- expect(captured.notifications.length).toBeGreaterThan(0);
-
- // created_at is the session start time; all events from one session
- // must report the same value. last_updated_at varies per event.
- const createdAts = new Set(captured.notifications.map((n) => n.params.meta.created_at));
- expect(createdAts.size).toBe(1);
-
- // last_updated_at should differ across at least some events (they fire
- // at different moments). With --lines 5 there's typically running +
- // completed, so at least 2 distinct timestamps.
- const lastUpdates = new Set(captured.notifications.map((n) => n.params.meta.last_updated_at));
- expect(lastUpdates.size).toBeGreaterThan(0);
- }, 20_000);
-
- test("all notifications for one session share the same session_id", async () => {
- const captured = await captureSessionFrames({ shimArgs: ["--lines", "5"] });
- expect(captured.notifications.length).toBeGreaterThan(0);
-
- const ids = new Set(captured.notifications.map((n) => n.params.meta.session_id));
- expect(ids.size).toBe(1);
- }, 20_000);
-
- test("session lifecycle ends with a terminal event (completed/failed/cancelled)", async () => {
- const captured = await captureSessionFrames({ shimArgs: ["--lines", "2"] });
- expect(captured.notifications.length).toBeGreaterThan(0);
-
- const events = captured.notifications.map((n) => n.params.meta.event);
- const lastEvent = events[events.length - 1];
- expect(["completed", "failed", "cancelled"]).toContain(lastEvent);
- }, 20_000);
-
- test("create_session response payload contains session_id matching notifications", async () => {
- const captured = await captureSessionFrames({ shimArgs: ["--lines", "3"] });
-
- const callResponse = captured.responses.find((r) => r.id === 2);
- expect(callResponse).toBeDefined();
-
- const content = (callResponse!.result as { content: Array<{ text: string }> }).content;
- const parsed = JSON.parse(content[0].text) as { session_id: string };
- expect(parsed.session_id).toMatch(/^[0-9a-f]{8}$/);
-
- // session_id from create_session response must equal the one in
- // notifications — they describe the same session.
- const notifSid = captured.notifications[0].params.meta.session_id;
- expect(parsed.session_id).toBe(notifSid);
- }, 20_000);
-});
+ }, 40_000);
+
+ test("SEP-1686 status mapping: 9-value event collapses to 5-value status correctly", async () => {
+ const captured = await captureSessionFrames({});
+ expect(captured.notifications.length).toBeGreaterThan(0);
+
+ // Build (event, status) pairs and validate every observed pair against
+ // the expected mapping defined in mcp-server.ts:EVENT_TO_TASK_STATUS.
+ // RB1: `finishing` is no longer a channel event; `awaiting_permission` is (F5).
+ const expectedMapping: Record<string, string> = {
+ starting: "working",
+ running: "working",
+ tool_executing: "working",
+ waiting_for_input: "input_required",
+ awaiting_permission: "input_required",
+ completed: "completed",
+ failed: "failed",
+ cancelled: "cancelled",
+ timeout: "failed",
+ };
+
+ for (const n of captured.notifications) {
+ const event = n.params.meta.event as string;
+ const status = n.params.meta.status as string;
+ const expected = expectedMapping[event];
+ if (expected !== undefined) {
+ expect(status).toBe(expected);
+ } else {
+ // Unknown event types fall through to "working" per
+ // mapEventToTaskStatus's default. If a NEW event type ever leaks
+ // through without an entry in EVENT_TO_TASK_STATUS, this catches it.
+ expect(status).toBe("working");
+ }
+ }
+ }, 40_000);
+
+ test("a permission dialog emits awaiting_permission with status input_required", async () => {
+ const captured = await captureSessionFrames({
+ model: "fake-permission",
+ prompt: "Edit the file.",
+ until: (frames) => frames.some((f) => f.params?.meta?.event === "awaiting_permission"),
+ });
+ const frame = captured.notifications.find(
+ (n) => n.params.meta.event === "awaiting_permission"
+ );
+ expect(frame).toBeDefined();
+ expect(frame?.params.meta.status).toBe("input_required");
+ expect(frame?.params.meta.model).toBe("fake-permission");
+ expect(typeof frame?.params.content).toBe("string");
+ }, 40_000);
+
+ test("all notifications for one session share the same created_at timestamp", async () => {
+ const captured = await captureSessionFrames({});
+ expect(captured.notifications.length).toBeGreaterThan(0);
+
+ // created_at is the session start time; all events from one session
+ // must report the same value. last_updated_at varies per event.
+ const createdAts = new Set(captured.notifications.map((n) => n.params.meta.created_at));
+ expect(createdAts.size).toBe(1);
+
+ // last_updated_at should differ across at least some events (they fire
+ // at different moments). Typically running + completed, so at least
+ // 2 distinct timestamps.
+ const lastUpdates = new Set(captured.notifications.map((n) => n.params.meta.last_updated_at));
+ expect(lastUpdates.size).toBeGreaterThan(0);
+ }, 40_000);
+
+ test("all notifications for one session share the same session_id", async () => {
+ const captured = await captureSessionFrames({});
+ expect(captured.notifications.length).toBeGreaterThan(0);
+
+ const ids = new Set(captured.notifications.map((n) => n.params.meta.session_id));
+ expect(ids.size).toBe(1);
+ }, 40_000);
+
+ test("session lifecycle ends with a terminal event (completed/failed/cancelled)", async () => {
+ const captured = await captureSessionFrames({});
+ expect(captured.notifications.length).toBeGreaterThan(0);
+
+ const events = captured.notifications.map((n) => n.params.meta.event);
+ const lastEvent = events[events.length - 1];
+ expect(["completed", "failed", "cancelled"]).toContain(lastEvent);
+ }, 40_000);
+
+ test("create_session response payload contains session_id matching notifications", async () => {
+ const captured = await captureSessionFrames({});
+
+ const parsed = captured.createResult.json as { session_id: string };
+ expect(parsed.session_id).toMatch(/^[0-9a-f]{8}$/);
+
+ // session_id from create_session response must equal the one in
+ // notifications — they describe the same session.
+ const notifSid = captured.notifications[0]?.params.meta.session_id;
+ expect(parsed.session_id).toBe(notifSid);
+ }, 40_000);
+ }
+);
describe("MCP capability declaration", () => {
- test("initialize response declares experimental.claude/channel capability", async () => {
+ async function initializeCapabilities(
+ toolMode: string
+ ): Promise<{ experimental?: Record<string, unknown> }> {
+ const layout = makeTempLayout("wirecaps");
+ layouts.push(layout);
// Drive only the initialize handshake — no session needed.
- const proc: ChildProcess = spawn("bun", ["run", SERVER_ENTRY, "--mcp"], {
+ const proc: ChildProcess = spawn(process.execPath, [SERVER_ENTRY, "--mcp"], {
stdio: ["pipe", "pipe", "pipe"],
- env: { ...process.env, CLAUDISH_MCP_TOOLS: "all" },
+ env: serverEnv(layout, { CLAUDISH_MCP_TOOLS: toolMode }),
+ cwd: layout.cwd,
});
let stdoutBuf = "";
@@ -337,7 +281,7 @@ describe("MCP capability declaration", () => {
resolveInit = r;
});
- proc.stdout!.on("data", (chunk: Buffer) => {
+ proc.stdout?.on("data", (chunk: Buffer) => {
stdoutBuf += chunk.toString("utf-8");
let nl: number;
// biome-ignore lint/suspicious/noAssignInExpressions: canonical line-buffer drain idiom
@@ -355,7 +299,7 @@ describe("MCP capability declaration", () => {
}
});
- proc.stdin!.write(
+ proc.stdin?.write(
`${JSON.stringify({
jsonrpc: "2.0",
id: 1,
@@ -369,11 +313,20 @@ describe("MCP capability declaration", () => {
);
await Promise.race([initDone, new Promise((r) => setTimeout(r, 10_000))]);
+ const exited = new Promise<void>((r) => proc.on("exit", () => r()));
proc.kill("SIGTERM");
- await new Promise<void>((r) => proc.on("exit", () => r()));
+ await exited;
expect(initResponse).not.toBeNull();
- const caps = initResponse!.result.capabilities;
+ return (
+ initResponse as unknown as {
+ result: { capabilities: { experimental?: Record<string, unknown> } };
+ }
+ ).result.capabilities;
+ }
+
+ test("initialize response declares experimental.claude/channel capability", async () => {
+ const caps = await initializeCapabilities("all");
expect(caps.experimental).toBeDefined();
expect(caps.experimental).toHaveProperty("claude/channel");
}, 15_000);
@@ -381,57 +334,7 @@ describe("MCP capability declaration", () => {
test("experimental capability is omitted when channel tools are disabled", async () => {
// With CLAUDISH_MCP_TOOLS=low-level, channel tools are gated off and
// the experimental.claude/channel capability should NOT be declared.
- const proc: ChildProcess = spawn("bun", ["run", SERVER_ENTRY, "--mcp"], {
- stdio: ["pipe", "pipe", "pipe"],
- env: { ...process.env, CLAUDISH_MCP_TOOLS: "low-level" },
- });
-
- let stdoutBuf = "";
- let initResponse: {
- result: { capabilities: { experimental?: Record<string, unknown> } };
- } | null = null;
- let resolveInit: () => void;
- const initDone = new Promise<void>((r) => {
- resolveInit = r;
- });
-
- proc.stdout!.on("data", (chunk: Buffer) => {
- stdoutBuf += chunk.toString("utf-8");
- let nl: number;
- // biome-ignore lint/suspicious/noAssignInExpressions: canonical line-buffer drain idiom
- while ((nl = stdoutBuf.indexOf("\n")) !== -1) {
- const line = stdoutBuf.slice(0, nl);
- stdoutBuf = stdoutBuf.slice(nl + 1);
- if (!line.trim()) continue;
- try {
- const msg = JSON.parse(line);
- if (msg.id === 1) {
- initResponse = msg;
- resolveInit();
- }
- } catch {}
- }
- });
-
- proc.stdin!.write(
- `${JSON.stringify({
- jsonrpc: "2.0",
- id: 1,
- method: "initialize",
- params: {
- protocolVersion: "2024-11-05",
- clientInfo: { name: "cap-test", version: "1.0.0" },
- capabilities: {},
- },
- })}\n`
- );
-
- await Promise.race([initDone, new Promise((r) => setTimeout(r, 10_000))]);
- proc.kill("SIGTERM");
- await new Promise<void>((r) => proc.on("exit", () => r()));
-
- expect(initResponse).not.toBeNull();
- const caps = initResponse!.result.capabilities;
+ const caps = await initializeCapabilities("low-level");
// Either experimental is absent entirely, or it doesn't have claude/channel
const hasChannel = !!caps.experimental && "claude/channel" in caps.experimental;
expect(hasChannel).toBe(false);
diff --git a/packages/cli/src/channel/e2e-channel.test.ts b/packages/cli/src/channel/e2e-channel.test.ts
index b03aa15e..7e340d2a 100644
--- a/packages/cli/src/channel/e2e-channel.test.ts
+++ b/packages/cli/src/channel/e2e-channel.test.ts
@@ -86,6 +86,7 @@ describe("Group 1: MCP Protocol — channel capability", () => {
const names = result.tools.map((t) => t.name).sort();
expect(names).toEqual([
"cancel_session",
+ "capture_session",
"compare_models",
"create_session",
"get_diagnostics",
@@ -115,6 +116,8 @@ describe("Group 1: MCP Protocol — channel capability", () => {
});
const parsed = JSON.parse((result.content as any)[0].text);
expect(parsed.sessions).toEqual([]);
+ // CA-12: the answer says which contract it speaks.
+ expect(parsed.contract_version).toBe(1);
});
test("send_input returns false for non-existent session", async () => {
@@ -124,6 +127,7 @@ describe("Group 1: MCP Protocol — channel capability", () => {
});
const parsed = JSON.parse((result.content as any)[0].text);
expect(parsed.success).toBe(false);
+ expect(parsed.reason).toBe("unknown_session");
});
test("get_output errors for non-existent session", async () => {
@@ -131,13 +135,25 @@ describe("Group 1: MCP Protocol — channel capability", () => {
expect(result.isError).toBe(true);
});
- test("cancel_session returns false for non-existent session", async () => {
+ test("cancel_session answers unknown_session for a non-existent session", async () => {
+ // A §8 verb: errors are a JSON ContractError with isError (was `{success:false}`).
const result = await client.callTool({
name: "cancel_session",
arguments: { session_id: "bad" },
});
- const parsed = JSON.parse((result.content as any)[0].text);
- expect(parsed.success).toBe(false);
+ expect(result.isError).toBe(true);
+ const parsed = JSON.parse((result.content as Array<{ text: string }>)[0]?.text ?? "");
+ expect(parsed.error.code).toBe("unknown_session");
+ });
+
+ test("capture_session answers unknown_session for a non-existent session", async () => {
+ const result = await client.callTool({
+ name: "capture_session",
+ arguments: { session_id: "bad" },
+ });
+ expect(result.isError).toBe(true);
+ const parsed = JSON.parse((result.content as Array<{ text: string }>)[0]?.text ?? "");
+ expect(parsed.error.code).toBe("unknown_session");
});
test("unknown tool returns isError", async () => {
@@ -169,7 +185,7 @@ describe("Group 1: MCP Protocol — channel capability", () => {
// Poll until the session reaches a terminal state. Use a wall-clock
// budget so scheduler contention cannot turn a slow session into a
// misleading empty-output failure.
- const terminalStatuses = new Set(["completed", "failed", "timeout"]);
+ const terminalStatuses = new Set(["COMPLETED", "FAILED", "TIMEOUT", "EMPTY"]);
const pollStartedAt = Date.now();
const pollBudgetMs = 120_000;
let lastObservedStatus = "not found";
@@ -182,9 +198,9 @@ describe("Group 1: MCP Protocol — channel capability", () => {
arguments: { include_completed: true },
});
const sessions = JSON.parse((list.content as any)[0].text).sessions;
- const s = sessions.find((x: any) => x.sessionId === sid);
- lastObservedStatus = s?.status ?? "not found";
- if (s && terminalStatuses.has(s.status)) {
+ const s = sessions.find((x: any) => x.session_id === sid);
+ lastObservedStatus = s?.state ?? "not found";
+ if (s && terminalStatuses.has(s.state)) {
reachedTerminal = true;
break;
}
@@ -257,11 +273,12 @@ describe("Group 1b: MCP Protocol — channel-only tools", () => {
} catch {}
});
- test("lists only the 6 channel tools when CLAUDISH_MCP_TOOLS=channel", async () => {
+ test("lists only the 7 channel tools when CLAUDISH_MCP_TOOLS=channel", async () => {
const result = await client.listTools();
const names = result.tools.map((t) => t.name).sort();
expect(names).toEqual([
"cancel_session",
+ "capture_session",
"create_session",
"get_diagnostics",
"get_output",
diff --git a/packages/cli/src/channel/event-task-status.test.ts b/packages/cli/src/channel/event-task-status.test.ts
index c6c6dca9..2608555d 100644
--- a/packages/cli/src/channel/event-task-status.test.ts
+++ b/packages/cli/src/channel/event-task-status.test.ts
@@ -18,7 +18,6 @@ const EXPECTED = {
tool_executing: "working",
waiting_for_input: "input_required",
awaiting_permission: "input_required",
- finishing: "working",
completed: "completed",
failed: "failed",
cancelled: "cancelled",
@@ -36,6 +35,10 @@ describe("EVENT_TO_TASK_STATUS", () => {
expect(mapEventToTaskStatus("awaiting_permission")).toBe("input_required");
});
+ test("finishing is no longer a channel event (RB1): it falls through like any unknown word", () => {
+ expect((CHANNEL_EVENT_TYPES as readonly string[]).includes("finishing")).toBe(false);
+ });
+
test("the list and the table name the same events", () => {
const listed: string[] = [...CHANNEL_EVENT_TYPES].sort();
expect(listed).toEqual(Object.keys(EXPECTED).sort());
diff --git a/packages/cli/src/channel/host-pid.contract.test.ts b/packages/cli/src/channel/host-pid.contract.test.ts
index e6f1b424..5d1092b2 100644
--- a/packages/cli/src/channel/host-pid.contract.test.ts
+++ b/packages/cli/src/channel/host-pid.contract.test.ts
@@ -4,6 +4,10 @@
* 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 session is an interactive pane (the pane fake, marker mode, in a real headless magmux
+ * under the test's own CLAUDISH_PANE_ROOT; ported per architecture §20.2, every assertion
+ * kept). After each test no pane process or file may remain.
+ *
* 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)
@@ -17,10 +21,13 @@ import { afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:te
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import {
+ MAGMUX_AVAILABLE,
McpServer,
+ NO_MAGMUX_MESSAGE,
PACKAGE_DIR,
SERVER_ENTRY,
createSession,
+ paneOrphans,
serverEnv,
} from "../test-helpers/contract-mcp.js";
import {
@@ -36,13 +43,17 @@ const T_TEST = 60_000;
let layout: TempLayout;
const servers: McpServer[] = [];
+if (!MAGMUX_AVAILABLE) console.warn(NO_MAGMUX_MESSAGE);
+
beforeEach(() => {
layout = makeTempLayout("hostpid");
});
afterEach(async () => {
for (const s of servers.splice(0)) await s.close();
+ const report = await paneOrphans(layout);
layout.cleanup();
-});
+ expect(report).toEqual({ processes: [], files: [] });
+}, 40_000);
async function spawnRecordVia(
command: string[] | undefined,
@@ -63,76 +74,82 @@ async function spawnRecordVia(
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.skipIf(!MAGMUX_AVAILABLE)(
+ "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.skipIf(!MAGMUX_AVAILABLE)(
+ "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")
+ );
-describe("REQ-3 the installed npm path for real (9a)", () => {
+ 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.skipIf(!MAGMUX_AVAILABLE)("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");
diff --git a/packages/cli/src/channel/index.ts b/packages/cli/src/channel/index.ts
index 907adb37..3b1568c4 100644
--- a/packages/cli/src/channel/index.ts
+++ b/packages/cli/src/channel/index.ts
@@ -1,20 +1,22 @@
export { ScrollbackBuffer } from "./scrollback-buffer.js";
-export { StreamJsonReducer } from "./stream-json-reducer.js";
-export type { ResultSummary, StreamJsonReducerOptions } from "./stream-json-reducer.js";
export {
- assertNoReservedFlags,
- buildChannelSpawnArgs,
SessionManager,
- userFrame,
+ channelEventFor,
+ normaliseTimeoutSeconds,
+ sessionRowOf,
+ toMetaRecord,
} from "./session-manager.js";
-export type { DiagnosticEvent, SessionDiagnostics } from "./session-manager.js";
export type {
- SessionStatus,
+ DiagnosticEvent,
+ SendInputResult,
+ SessionDiagnostics,
+ SessionOutput,
+} from "./session-manager.js";
+export { CHANNEL_EVENT_TYPES } from "./types.js";
+export type {
SessionInfo,
SessionCreateOptions,
SessionManagerOptions,
ChannelEvent,
ChannelEventType,
- ReducerEvent,
- ReducerCallback,
} from "./types.js";
diff --git a/packages/cli/src/channel/session-create-options.test.ts b/packages/cli/src/channel/session-create-options.test.ts
index 3140ab60..a75e8c37 100644
--- a/packages/cli/src/channel/session-create-options.test.ts
+++ b/packages/cli/src/channel/session-create-options.test.ts
@@ -1,39 +1,32 @@
/**
* Process-level coverage for SessionCreateOptions passthroughs.
*
- * The shared fake child exposes selected spawn environment values without a
- * model or API key. Every manager writes into a per-test temporary root, and
- * afterEach shuts down any child that is still live.
+ * Every session is the fake interactive child in a real headless magmux pane, built from
+ * a hermetic `parentEnv`. Its `env_probe` scenario writes the environment the pane child
+ * actually received to FAKE_PROBE_FILE, so `tokenFile` and the upstream-error log are
+ * checked where the child reads them. Every manager writes into a per-test temporary
+ * root; afterEach settles every session and proves no pane is left.
*/
-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test";
-import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { dirname, join } from "node:path";
-import { fileURLToPath } from "node:url";
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, readFileSync } from "node:fs";
+import { join } from "node:path";
import { ENV } from "../config.js";
+import { UPSTREAM_ERROR_LOG_ENV } from "../handlers/shared/upstream-error-capture.js";
+import {
+ MAGMUX,
+ NO_MAGMUX_MESSAGE,
+ type PaneTestEnv,
+ killLeftovers,
+ makePaneTestEnv,
+ waitNoOrphans,
+} from "../pane/test-helpers/hermetic-env.js";
import { SessionManager } from "./session-manager.js";
-import type { SessionStatus } from "./types.js";
-const FAKE_CLAUDISH_TS = join(
- dirname(fileURLToPath(import.meta.url)),
- "test-helpers",
- "fake-claudish.ts"
-);
-const TERMINAL_STATUSES: readonly SessionStatus[] = ["completed", "failed", "cancelled", "timeout"];
-
-const originalClaudishBin = process.env.CLAUDISH_BIN;
-let sessionsDir: string;
-let managers: SessionManager[];
+const T_PANE = 30_000;
-function makeManager(): SessionManager {
- const manager = new SessionManager({ sessionsDir, stallSeconds: 0 });
- managers.push(manager);
- return manager;
-}
-
-function waitUntil(predicate: () => boolean, timeoutMs = 5000): Promise<void> {
+function waitUntil(predicate: () => boolean, timeoutMs = 10_000): Promise<void> {
return new Promise((resolve, reject) => {
const deadline = Date.now() + timeoutMs;
const check = () => {
@@ -45,139 +38,145 @@ function waitUntil(predicate: () => boolean, timeoutMs = 5000): Promise<void> {
});
}
-async function waitForTerminal(manager: SessionManager, sessionId: string): Promise<void> {
- await waitUntil(() => TERMINAL_STATUSES.includes(manager.getSession(sessionId).status));
-}
-
-function readOutputJson(manager: SessionManager, sessionId: string): Record<string, string | null> {
- return JSON.parse(manager.getOutput(sessionId).output.trim()) as Record<string, string | null>;
-}
-
-beforeAll(() => {
- process.env.CLAUDISH_BIN = FAKE_CLAUDISH_TS;
-});
-
-afterAll(() => {
- if (originalClaudishBin === undefined) delete process.env.CLAUDISH_BIN;
- else process.env.CLAUDISH_BIN = originalClaudishBin;
-});
-
-beforeEach(() => {
- sessionsDir = mkdtempSync(join(tmpdir(), "session-create-options-"));
- managers = [];
-});
-
-afterEach(async () => {
- await Promise.all(managers.map((manager) => manager.shutdownAll()));
- rmSync(sessionsDir, { recursive: true, force: true });
-});
-
-describe("SessionCreateOptions passthroughs", () => {
- test("uses a caller-supplied sessionId verbatim", () => {
- const manager = makeManager();
- const sessionId = manager.createSession({
- model: "test-model",
- sessionId: "slot-07",
- claudishFlags: ["--sleep", "60"],
+describe.skipIf(!MAGMUX)(
+ `SessionCreateOptions passthroughs (${MAGMUX ? "magmux" : NO_MAGMUX_MESSAGE})`,
+ () => {
+ let t: PaneTestEnv;
+ let sessionsDir: string;
+ let probe: string;
+ let managers: SessionManager[];
+
+ beforeEach(() => {
+ t = makePaneTestEnv();
+ sessionsDir = join(t.tmp, "sessions");
+ probe = join(t.tmp, "probe-{session}.json");
+ managers = [];
});
- expect(sessionId).toBe("slot-07");
- expect(manager.getSession(sessionId).sessionId).toBe("slot-07");
- });
-
- test("rejects reuse of a live caller-supplied sessionId", () => {
- const manager = makeManager();
- const sessionId = "live-slot";
- manager.createSession({
- model: "first-model",
- sessionId,
- claudishFlags: ["--sleep", "60"],
- });
- const originalPid = manager.getSession(sessionId).pid;
-
- expect(() =>
- manager.createSession({
- model: "replacement-model",
- sessionId,
- claudishFlags: ["--sleep", "60"],
- })
- ).toThrow(`Session id already in use: ${sessionId}`);
- expect(manager.getSession(sessionId).model).toBe("first-model");
- expect(manager.getSession(sessionId).pid).toBe(originalPid);
- });
-
- test("writes artifacts to sessionDir instead of the manager sessionsDir", () => {
- const manager = makeManager();
- const sessionId = "custom-artifacts";
- const sessionDir = join(sessionsDir, "elsewhere", "slot-artifacts");
- const prompt = "keep this artifact in the requested directory";
-
- manager.createSession({
- model: "test-model",
- sessionId,
- sessionDir,
- prompt,
- claudishFlags: ["--sleep", "60"],
- });
-
- expect(readFileSync(join(sessionDir, "prompt.md"), "utf8")).toBe(prompt);
- expect(manager.getDiagnostics(sessionId).sessionDir).toBe(sessionDir);
- expect(existsSync(join(sessionsDir, sessionId))).toBe(false);
- });
-
- test("points the child token tracker at tokenFile", async () => {
- const manager = makeManager();
- const tokenFile = join(sessionsDir, "accounting", "slot-03.json");
- const sessionId = manager.createSession({
- model: "test-model",
- tokenFile,
- claudishFlags: ["--print-env", ENV.CLAUDISH_TOKEN_FILE],
+ afterEach(async () => {
+ for (const m of managers) await m.shutdownAll();
+ const report = await waitNoOrphans({ sockRoot: t.sockRoot }, 10_000);
+ killLeftovers({ sockRoot: t.sockRoot });
+ t.cleanup();
+ expect(report).toEqual({ processes: [], files: [] });
});
- await waitForTerminal(manager, sessionId);
-
- expect(readOutputJson(manager, sessionId)[ENV.CLAUDISH_TOKEN_FILE]).toBe(tokenFile);
- });
-
- test("passes keepUnrecognizedJson to the session reducer", async () => {
- const manager = makeManager();
- const sessionId = manager.createSession({
- model: "test-model",
- keepUnrecognizedJson: true,
- claudishFlags: ["--print-argv"],
- });
-
- await waitForTerminal(manager, sessionId);
-
- const [rawArgv] = manager.getOutput(sessionId).output.split("\n");
- const argv = JSON.parse(rawArgv) as string[];
- expect(argv).toContain("--print-argv");
- });
-
- test("omitting all four options preserves the random id and artifact, token, and reducer defaults", async () => {
- const manager = makeManager();
- const envSessionId = manager.createSession({
- model: "test-model",
- claudishFlags: ["--print-env", ENV.CLAUDISH_TOKEN_FILE],
- });
+ function makeManager(): SessionManager {
+ const manager = new SessionManager({
+ sessionsDir,
+ hostPid: 1,
+ parentEnv: { ...t.env, FAKE_PROBE_FILE: probe },
+ paneTimings: { replStableMs: 200 },
+ });
+ managers.push(manager);
+ return manager;
+ }
+
+ /** The environment the pane child received, from its env_probe file. */
+ async function childEnv(
+ manager: SessionManager,
+ sessionId: string
+ ): Promise<Record<string, string>> {
+ const path = probe.replace("{session}", manager.getSession(sessionId).claudeSessionId);
+ await waitUntil(() => existsSync(path));
+ return (JSON.parse(readFileSync(path, "utf-8")) as { env: Record<string, string> }).env;
+ }
+
+ test(
+ "uses a caller-supplied sessionId verbatim",
+ async () => {
+ const manager = makeManager();
+ const sessionId = await manager.createSession({
+ model: "fake-answer",
+ cwd: t.cwd,
+ sessionId: "slot-07",
+ });
+ expect(sessionId).toBe("slot-07");
+ expect(manager.getSession(sessionId).sessionId).toBe("slot-07");
+ expect(manager.getSession(sessionId).pane).toContain("slot07");
+ },
+ T_PANE
+ );
- await waitForTerminal(manager, envSessionId);
+ test(
+ "rejects reuse of a live caller-supplied sessionId",
+ async () => {
+ const manager = makeManager();
+ const sessionId = "live-slot";
+ await manager.createSession({ model: "first-model", cwd: t.cwd, sessionId });
+ const originalPane = manager.getSession(sessionId).pane;
+
+ await expect(
+ manager.createSession({ model: "replacement-model", cwd: t.cwd, sessionId })
+ ).rejects.toThrow(`Session id already in use: ${sessionId}`);
+ expect(manager.getSession(sessionId).model).toBe("first-model");
+ expect(manager.getSession(sessionId).pane).toBe(originalPane);
+ },
+ T_PANE
+ );
- const defaultSessionDir = join(sessionsDir, envSessionId);
- expect(envSessionId).toMatch(/^[0-9a-f]{8}$/);
- expect(manager.getDiagnostics(envSessionId).sessionDir).toBe(defaultSessionDir);
- expect(existsSync(defaultSessionDir)).toBe(true);
- expect(readOutputJson(manager, envSessionId)[ENV.CLAUDISH_TOKEN_FILE]).toBe(
- join(defaultSessionDir, "tokens.json")
+ test(
+ "writes artifacts to sessionDir instead of the manager sessionsDir",
+ async () => {
+ const manager = makeManager();
+ const sessionId = "custom-artifacts";
+ const sessionDir = join(t.tmp, "elsewhere", "slot-artifacts");
+ const prompt = "keep this artifact in the requested directory";
+
+ await manager.createSession({
+ model: "contract-fake-model",
+ cwd: t.cwd,
+ sessionId,
+ sessionDir,
+ prompt: `${prompt} @@HANG@@`,
+ });
+
+ expect(readFileSync(join(sessionDir, "prompt.md"), "utf8")).toBe(`${prompt} @@HANG@@`);
+ expect(existsSync(join(sessionDir, "spawn.json"))).toBe(true);
+ expect(manager.getDiagnostics(sessionId).sessionDir).toBe(sessionDir);
+ expect(existsSync(join(sessionsDir, sessionId))).toBe(false);
+ },
+ T_PANE
);
- const reducerSessionId = manager.createSession({
- model: "test-model",
- claudishFlags: ["--print-argv"],
- });
- await waitForTerminal(manager, reducerSessionId);
+ test(
+ "points the child token tracker at tokenFile and the upstream-error log into sessionDir",
+ async () => {
+ const manager = makeManager();
+ const tokenFile = join(t.tmp, "accounting", "slot-03.json");
+ const sessionDir = join(t.tmp, "elsewhere", "slot-03");
+ const sessionId = await manager.createSession({
+ model: "fake-env_probe",
+ cwd: t.cwd,
+ sessionDir,
+ tokenFile,
+ });
+
+ const env = await childEnv(manager, sessionId);
+ expect(env[ENV.CLAUDISH_TOKEN_FILE]).toBe(tokenFile);
+ expect(env[UPSTREAM_ERROR_LOG_ENV]).toBe(join(sessionDir, "upstream-errors.jsonl"));
+ expect(manager.getDiagnostics(sessionId).upstreamErrorLogPath).toBe(
+ join(sessionDir, "upstream-errors.jsonl")
+ );
+ },
+ T_PANE
+ );
- // Valid JSON outside the stream-json vocabulary remains hidden by default.
- expect(manager.getOutput(reducerSessionId).output).not.toContain("--print-argv");
- });
-});
+ test(
+ "omitting the options keeps the random id and the artifact and token defaults",
+ async () => {
+ const manager = makeManager();
+ const sessionId = await manager.createSession({ model: "fake-env_probe", cwd: t.cwd });
+
+ const defaultSessionDir = join(sessionsDir, sessionId);
+ expect(sessionId).toMatch(/^[0-9a-f]{8}$/);
+ expect(manager.getDiagnostics(sessionId).sessionDir).toBe(defaultSessionDir);
+ expect(existsSync(defaultSessionDir)).toBe(true);
+ const env = await childEnv(manager, sessionId);
+ expect(env[ENV.CLAUDISH_TOKEN_FILE]).toBe(join(defaultSessionDir, "tokens.json"));
+ expect(env[UPSTREAM_ERROR_LOG_ENV]).toBe(join(defaultSessionDir, "upstream-errors.jsonl"));
+ },
+ T_PANE
+ );
+ }
+);
diff --git a/packages/cli/src/channel/session-manager.test.ts b/packages/cli/src/channel/session-manager.test.ts
index c63e0ba8..4b888508 100644
--- a/packages/cli/src/channel/session-manager.test.ts
+++ b/packages/cli/src/channel/session-manager.test.ts
@@ -1,13 +1,16 @@
/**
- * Unit and process-level regression tests for the bidirectional stream-json
- * channel transport.
+ * Unit and process-level regression tests for the channel's interactive pane transport
+ * (architecture §7, §12.4).
*
- * SessionManager spawns the stream-json-speaking fake through the CLAUDISH_BIN
- * seam. Every manager gets an explicit temporary sessionsDir, so this file
- * never resolves either the installed claudish binary or ~/.claudish/sessions.
+ * Process-level tests drive `SessionManager` directly: every session is the fake
+ * interactive child (`CLAUDISH_BIN`, pane/test-helpers/fake-interactive-child.ts) inside a
+ * real headless magmux, built from a hermetic environment passed as `parentEnv` — this
+ * file never mutates `process.env`, never resolves the installed claudish and never
+ * touches ~/.claudish/sessions. After each such test every pane is gone (no process,
+ * socket, record or launcher dir under the test's sockRoot).
*/
-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test";
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { type ChildProcess, spawn } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
@@ -15,45 +18,31 @@ import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { mapEventToTaskStatus } from "../mcp-server.js";
+import { ContractErrorException, type SlotState, checkChildFlags } from "../pane/index.js";
+import {
+ MAGMUX,
+ NO_MAGMUX_MESSAGE,
+ type PaneTestEnv,
+ killLeftovers,
+ makePaneTestEnv,
+ waitNoOrphans,
+} from "../pane/test-helpers/hermetic-env.js";
+import { projectsDir, transcriptPathFor } from "../session/session-discovery.js";
import {
SessionManager,
- assertNoReservedFlags,
- buildChannelSpawnArgs,
- userFrame,
+ channelEventFor,
+ normaliseTimeoutSeconds,
+ sessionRowOf,
+ toMetaRecord,
} from "./session-manager.js";
-import {
- CAPTURED_ASSISTANT_PROSE,
- CAPTURED_DELTA_LINE,
- capturedAssistantFrame,
-} from "./test-helpers/captured-stream-json.js";
-import type { ChannelEvent, SessionManagerOptions, SessionStatus } from "./types.js";
-
-const __filename = fileURLToPath(import.meta.url);
-const __dirname = dirname(__filename);
-const FAKE_CLAUDISH_TS = join(__dirname, "test-helpers", "fake-channel-stream-json.ts");
-const SIGNAL_CHILD_TS = join(__dirname, "test-helpers", "stats-buffer-signal-child.ts");
-const TERMINAL_STATUSES: readonly SessionStatus[] = ["completed", "failed", "cancelled", "timeout"];
-// Must match KILL_GRACE_MS in session-manager.ts:210; post-SIGTERM waits must exceed it.
-const KILL_GRACE_MS = 5000;
-const POST_SIGTERM_WAIT_MS = KILL_GRACE_MS + 2000;
-const TIMEOUT_REGRESSION_TEST_MS = POST_SIGTERM_WAIT_MS * 2 + 1000;
-
-const ORIGINAL_CLAUDISH_BIN = process.env.CLAUDISH_BIN;
-let sessionsDir: string;
-let managers: SessionManager[] = [];
-
-beforeAll(() => {
- sessionsDir = mkdtempSync(join(tmpdir(), "claudish-channel-sessions-"));
- process.env.CLAUDISH_BIN = FAKE_CLAUDISH_TS;
-});
+import type { ChannelEvent, SessionInfo, SessionManagerOptions } from "./types.js";
-afterAll(() => {
- if (ORIGINAL_CLAUDISH_BIN === undefined) delete process.env.CLAUDISH_BIN;
- else process.env.CLAUDISH_BIN = ORIGINAL_CLAUDISH_BIN;
- rmSync(sessionsDir, { recursive: true, force: true });
-});
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const SIGNAL_CHILD_TS = join(__dirname, "test-helpers", "stats-buffer-signal-child.ts");
+const TERMINAL_EVENTS = ["completed", "failed", "cancelled", "timeout"];
+const T_PANE = 30_000;
-function waitUntil(predicate: () => boolean, timeoutMs = 5000, intervalMs = 25): Promise<void> {
+function waitUntil(predicate: () => boolean, timeoutMs = 10_000, intervalMs = 25): Promise<void> {
return new Promise((resolve, reject) => {
const deadline = Date.now() + timeoutMs;
const check = () => {
@@ -65,428 +54,338 @@ function waitUntil(predicate: () => boolean, timeoutMs = 5000, intervalMs = 25):
});
}
-function makeManager(opts?: SessionManagerOptions): SessionManager {
- const manager = new SessionManager({
- maxSessions: 20,
- sessionsDir,
- stallSeconds: 0,
- ...opts,
- });
- managers.push(manager);
- return manager;
-}
-
-function quickSession(
- manager: SessionManager,
- extraFlags: string[] = [],
- prompt = "hello"
-): string {
- return manager.createSession({
- model: "test-model",
- prompt,
- claudishFlags: extraFlags,
- });
-}
-
-async function waitForStatus(
- manager: SessionManager,
- sessionId: string,
- statuses: readonly SessionStatus[],
- timeoutMs = 5000
-): Promise<void> {
- await waitUntil(() => statuses.includes(manager.getSession(sessionId).status), timeoutMs);
-}
-
-async function waitForCompleted(manager: SessionManager, sessionId: string): Promise<void> {
- await waitForStatus(manager, sessionId, ["completed"]);
+function captureError(fn: () => unknown): unknown {
+ try {
+ fn();
+ } catch (e) {
+ return e;
+ }
+ return undefined;
}
-async function waitForMeta(sessionId: string, timeoutMs = 5000): Promise<string> {
- const metaPath = join(sessionsDir, sessionId, "meta.json");
- await waitUntil(() => existsSync(metaPath), timeoutMs);
- return metaPath;
+/** A SessionInfo with every field set, for the pure record and row tests. */
+function sampleInfo(over: Partial<SessionInfo> = {}): SessionInfo {
+ return {
+ sessionId: "abcd1234",
+ model: "glm-5",
+ spawnModel: "gc@glm-5",
+ provider: "GLM Coding",
+ state: "EMPTY",
+ shape: "one-shot",
+ pane: "c1-x-sabcd1234-aaaaaa",
+ panePid: 4242,
+ startedAt: "2026-10-06T00:00:00.000Z",
+ completedAt: "2026-10-06T00:00:10.000Z",
+ exitCode: null,
+ turnsCompleted: 1,
+ tokensIn: 1000,
+ tokensOut: 50,
+ costUsd: 0.01,
+ toolCalls: 3,
+ lastActivityAt: "2026-10-06T00:00:09.000Z",
+ elapsedSeconds: 10,
+ idleSeconds: null,
+ activity: null,
+ reason: "shape_mismatch",
+ detail: "no match",
+ pendingInputs: 0,
+ claudeSessionId: "11111111-2222-3333-4444-555555555555",
+ transcriptPath: "/nonexistent/projects/x/11111111-2222-3333-4444-555555555555.jsonl",
+ captureSource: "transcript",
+ turnSource: "transcript",
+ timeoutSeconds: 600,
+ ...over,
+ };
}
-beforeEach(() => {
- managers = [];
-});
+// ─── pure ────────────────────────────────────────────────────────────────────
-afterEach(async () => {
- // Cancel only live sessions. Calling shutdownAll on a process that already
- // exited waits for an exit event that has already happened.
- for (const manager of managers) {
- for (const session of manager.listSessions(false)) {
- manager.cancelSession(session.sessionId);
+describe("exported channel seams (pure)", () => {
+ test("timeout projects to SEP-1686 failed instead of falling through to working", () => {
+ expect(mapEventToTaskStatus("timeout")).toBe("failed");
+ expect(mapEventToTaskStatus("timeout")).not.toBe("working");
+ expect(mapEventToTaskStatus("genuinely_unknown_event")).toBe("working");
+ for (const [event, status] of [
+ ["completed", "completed"],
+ ["failed", "failed"],
+ ["cancelled", "cancelled"],
+ ["awaiting_permission", "input_required"],
+ ] as const) {
+ expect(mapEventToTaskStatus(event)).toBe(status);
}
- }
- await new Promise((resolve) => setTimeout(resolve, 75));
-});
-
-describe("SessionManager", () => {
- let manager: SessionManager;
-
- beforeEach(() => {
- manager = makeManager();
});
- test("createSession returns unique session IDs", () => {
- const id1 = manager.createSession({ model: "test-model", claudishFlags: ["--sleep", "3"] });
- const id2 = manager.createSession({ model: "test-model", claudishFlags: ["--sleep", "3"] });
- expect(id1).not.toBe(id2);
- expect(id1.length).toBeGreaterThan(0);
- expect(id2.length).toBeGreaterThan(0);
+ test("channelEventFor maps every SlotState (§3.4)", () => {
+ const cases: Array<[SlotState, string | null, string, string | null]> = [
+ ["STARTING", null, "starting", null],
+ ["RUNNING", "thinking", "running", null],
+ ["RUNNING", "finishing", "running", null],
+ ["RUNNING", "background", "running", null],
+ ["RUNNING", null, "running", null],
+ ["RUNNING", "Bash", "tool_executing", "Bash"],
+ ["AWAITING_INPUT", null, "waiting_for_input", null],
+ ["AWAITING_INPUT", "AskUserQuestion", "waiting_for_input", null],
+ ["AWAITING_PERMISSION", "Edit", "awaiting_permission", null],
+ ["COMPLETED", null, "completed", null],
+ ["FAILED", null, "failed", null],
+ ["EMPTY", null, "failed", null],
+ ["CANCELLED", null, "cancelled", null],
+ ["TIMEOUT", null, "timeout", null],
+ ];
+ for (const [state, activity, event, tool] of cases) {
+ expect(channelEventFor({ state, activity }), `${state}/${activity}`).toEqual({
+ event: event as ReturnType<typeof channelEventFor>["event"],
+ tool,
+ });
+ }
});
- test("getSession returns correct model/status/sessionId fields", () => {
- const id = manager.createSession({ model: "test-model", claudishFlags: ["--sleep", "3"] });
- const info = manager.getSession(id);
- expect(info.sessionId).toBe(id);
- expect(info.model).toBe("test-model");
- // Promptless: it waits for its first send_input from the moment it exists.
- expect(info.status).toBe("waiting_for_input");
- expect(info.pid).not.toBeNull();
- expect(typeof info.startedAt).toBe("string");
- expect(info.completedAt).toBeNull();
- expect(info.exitCode).toBeNull();
+ test("normaliseTimeoutSeconds clamps to an integer in 1..3600", () => {
+ expect(normaliseTimeoutSeconds(90.5)).toBe(91);
+ expect(normaliseTimeoutSeconds(0)).toBe(1);
+ expect(normaliseTimeoutSeconds(7200)).toBe(3600);
+ expect(normaliseTimeoutSeconds(undefined)).toBe(600);
+ });
+
+ test("toMetaRecord keeps every 10.4.0 key under its 10.4.0 name, plus the pane keys", () => {
+ const meta = toMetaRecord(sampleInfo({ parentClaudeSessionId: "parent-1" }), "/work");
+ for (const key of [
+ "sessionId",
+ "model",
+ "spawnModel",
+ "status",
+ "pid",
+ "startedAt",
+ "completedAt",
+ "exitCode",
+ "turnsCompleted",
+ "tokensUsed",
+ "elapsedSeconds",
+ "idleSeconds",
+ "costUsd",
+ "toolCallCount",
+ "terminalReason",
+ "claudeSessionId",
+ "parentClaudeSessionId",
+ "transcriptPath",
+ ])
+ expect(meta, key).toHaveProperty(key);
+ // EMPTY is a failure to the monitor; the SlotState rides beside it.
+ expect(meta.status).toBe("failed");
+ expect(meta.state).toBe("EMPTY");
+ expect(meta.terminalReason).toBe("shape_mismatch");
+ expect(meta.toolCallCount).toBe(3);
+ expect(meta.tokensUsed).toBe(1050);
+ expect(meta.pid).toBe(4242);
+ expect(meta.cwd).toBe("/work");
+ // one name per fact
+ for (const dup of ["toolCalls", "reason", "panePid"]) expect(meta).not.toHaveProperty(dup);
+ // not proven → absent, never an empty value
+ expect(toMetaRecord(sampleInfo(), "/w")).not.toHaveProperty("parentClaudeSessionId");
+ for (const [state, status] of [
+ ["COMPLETED", "completed"],
+ ["FAILED", "failed"],
+ ["CANCELLED", "cancelled"],
+ ["TIMEOUT", "timeout"],
+ ] as const)
+ expect(toMetaRecord(sampleInfo({ state }), "/w").status).toBe(status);
+ });
+
+ test("sessionRowOf yields exactly the SessionRow keys; terminal rows drop idle and activity", () => {
+ const row = sessionRowOf(sampleInfo({ idleSeconds: 5, activity: "Bash" }));
+ expect(Object.keys(row).sort()).toEqual(
+ [
+ "slot",
+ "model",
+ "provider",
+ "state",
+ "reason",
+ "tokens_in",
+ "tokens_out",
+ "cost_usd",
+ "tool_calls",
+ "turns_completed",
+ "last_activity_at",
+ "idle_seconds",
+ "activity",
+ "pane",
+ "session_id",
+ "started_at",
+ "completed_at",
+ "elapsed_seconds",
+ ].sort()
+ );
+ expect(row.slot).toBe(row.session_id);
+ expect(row.idle_seconds).toBeNull();
+ expect(row.activity).toBeNull();
+ expect(row.reason).toBe("shape_mismatch");
+ const live = sessionRowOf(
+ sampleInfo({ state: "RUNNING", reason: null, idleSeconds: 5, activity: "Bash" })
+ );
+ expect(live.idle_seconds).toBe(5);
+ expect(live.activity).toBe("Bash");
+ expect(sessionRowOf(sampleInfo({ state: "COMPLETED", reason: null })).reason).toBeNull();
+ });
+
+ test("G4: transport-owned, print-only and positional flags are refused before anything starts", async () => {
+ const root = mkdtempSync(join(tmpdir(), "claudish-g4-"));
+ try {
+ const manager = new SessionManager({ sessionsDir: join(root, "s"), hostPid: 1 });
+ for (const flags of [
+ ["-p"],
+ ["--print"],
+ ["--output-format", "json"],
+ ["--output-format=json"],
+ ["--input-format", "stream-json"],
+ ["--session-id", "x"],
+ ["--stdin"],
+ ["--max-turns", "3"],
+ ["--max-budget-usd", "1"],
+ ["--allowedTools", "Read", "Bash"],
+ ]) {
+ await expect(
+ manager.createSession({ model: "m", claudishFlags: flags }),
+ JSON.stringify(flags)
+ ).rejects.toThrow(/^invalid_args: /);
+ }
+ // a refused session leaves no record
+ expect(existsSync(join(root, "s"))).toBe(false);
+ expect(checkChildFlags(["--effort", "high", "--agent", "dev:reviewer"]).ok).toBe(true);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
});
+});
- test("spawnModel changes argv while SessionInfo keeps the requested model", async () => {
- const id = manager.createSession({
- model: "glm-5",
- spawnModel: "gc@glm-5",
- prompt: "report argv",
- claudishFlags: ["--print-argv"],
- });
-
- await waitForCompleted(manager, id);
+// ─── disk reader (pure) ────────────────────────────────────────────────────
- const argv = JSON.parse(manager.getOutput(id).output.trim()) as string[];
- const modelFlag = argv.indexOf("--model");
- expect(argv[modelFlag + 1]).toBe("gc@glm-5");
- expect(argv).not.toContain("--stdin");
- expect(manager.getSession(id).model).toBe("glm-5");
- });
+describe("SessionManager disk reader", () => {
+ let root: string;
+ let sessionsDir: string;
+ let manager: SessionManager;
- test("spawn argv falls back to the requested model when spawnModel is absent", async () => {
- const id = manager.createSession({
- model: "glm-5",
- prompt: "report argv",
- claudishFlags: ["--print-argv"],
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), "claudish-disk-reader-"));
+ sessionsDir = join(root, "sessions");
+ mkdirSync(sessionsDir, { recursive: true });
+ manager = new SessionManager({
+ sessionsDir,
+ hostPid: 1,
+ parentEnv: { HOME: join(root, "home"), CLAUDE_CONFIG_DIR: join(root, "home", ".claude") },
});
-
- await waitForCompleted(manager, id);
-
- const argv = JSON.parse(manager.getOutput(id).output.trim()) as string[];
- const modelFlag = argv.indexOf("--model");
- expect(argv[modelFlag + 1]).toBe("glm-5");
- expect(argv).toContain("stream-json");
- expect(manager.getSession(id).model).toBe("glm-5");
});
+ afterEach(() => rmSync(root, { recursive: true, force: true }));
- test("getSession throws for non-existent session", () => {
+ test("unknown ids: the readers throw not found, the mutators answer unknown_session", () => {
expect(() => manager.getSession("nonexistent")).toThrow("not found");
- });
-
- test("listSessions includes active session", () => {
- const id = manager.createSession({ model: "test-model", claudishFlags: ["--sleep", "3"] });
- expect(manager.listSessions(false).some((session) => session.sessionId === id)).toBe(true);
- });
-
- test("listSessions excludes completed sessions when includeCompleted=false", async () => {
- const id = quickSession(manager);
- await waitForCompleted(manager, id);
- expect(manager.listSessions(false).some((session) => session.sessionId === id)).toBe(false);
- });
-
- test("listSessions includes completed sessions when includeCompleted=true", async () => {
- const id = quickSession(manager);
- await waitForCompleted(manager, id);
- expect(manager.listSessions(true).some((session) => session.sessionId === id)).toBe(true);
- });
-
- test("maxSessions limit: 3rd session throws when limit is 2", () => {
- const limited = makeManager({ maxSessions: 2 });
- limited.createSession({ model: "m", claudishFlags: ["--sleep", "3"] });
- limited.createSession({ model: "m", claudishFlags: ["--sleep", "3"] });
- expect(() => limited.createSession({ model: "m", claudishFlags: ["--sleep", "3"] })).toThrow(
- /Max sessions/
- );
- });
-
- test("cancelSession: status becomes 'cancelled'", async () => {
- const id = manager.createSession({
- model: "test-model",
- claudishFlags: ["--sleep", "60"],
- });
- await waitUntil(() => manager.getSession(id).pid !== null);
-
- expect(manager.cancelSession(id)).toBe(true);
- expect(manager.getSession(id).status).toBe("cancelled");
- });
-
- test("cancelSession returns false for completed session", async () => {
- const id = quickSession(manager);
- await waitForCompleted(manager, id);
- expect(manager.cancelSession(id)).toBe(false);
- });
-
- test("sendInput returns false for non-existent session", () => {
- expect(manager.sendInput("does-not-exist", "hello")).toBe(false);
- });
-
- test("sendInput returns false for completed session", async () => {
- const id = quickSession(manager);
- await waitForCompleted(manager, id);
- expect(manager.sendInput(id, "some input")).toBe(false);
- });
-
- test("getOutput returns output from process stdout", async () => {
- const id = quickSession(manager, [], "hello world");
- await waitForCompleted(manager, id);
-
- const output = manager.getOutput(id);
- expect(output.sessionId).toBe(id);
- expect(output.status).toBe("completed");
- expect(output.output).toContain(CAPTURED_ASSISTANT_PROSE);
- expect(output.output).not.toContain('"type":"assistant"');
- });
-
- test("getOutput with tail_lines returns only the last N lines", async () => {
- const id = quickSession(manager, ["--messages", "5"]);
- await waitForCompleted(manager, id);
-
- const full = manager.getOutput(id);
- const tail = manager.getOutput(id, 2);
- const fullLines = full.output.split("\n");
- expect(tail.output).toBe(fullLines.slice(-2).join("\n"));
- expect(tail.output.split("\n")).toHaveLength(2);
- expect(tail.totalLines).toBe(full.totalLines);
- expect(tail.output).not.toBe(full.output);
- });
-
- test("getOutput throws for non-existent session", () => {
expect(() => manager.getOutput("bad-id")).toThrow("not found");
- });
-
- test("timeout kills long-running process and terminates it", async () => {
- const id = manager.createSession({
- model: "test-model",
- timeoutSeconds: 1,
- claudishFlags: ["--sleep", "60"],
+ expect(manager.sendInput("does-not-exist", "hello")).toEqual({
+ success: false,
+ reason: "unknown_session",
+ state: null,
});
-
- const metaPath = await waitForMeta(id, 4000);
- const info = manager.getSession(id);
- const meta = JSON.parse(readFileSync(metaPath, "utf-8")) as { status: string };
- expect(info.completedAt).not.toBeNull();
- expect(info.status).toBe("timeout");
- expect(meta.status).toBe("timeout");
- }, 10_000);
-
- test("onStateChange callback fires with session_id and event", async () => {
- const events: Array<{ sessionId: string; event: ChannelEvent }> = [];
- const callbackManager = makeManager({
- onStateChange: (sessionId, event) => events.push({ sessionId, event }),
- });
- const id = quickSession(callbackManager, [], "trigger events");
-
- await waitForCompleted(callbackManager, id);
-
- // A one-shot session's turn end is `finishing`: claudish closed stdin, so
- // nothing waits for input. It never passes through `waiting_for_input`.
- expect(events.map(({ event }) => event.type)).toEqual(["running", "finishing", "completed"]);
- for (const observed of events) {
- expect(observed.sessionId).toBe(id);
- expect(observed.event.model).toBe("test-model");
- }
+ const err = captureError(() => manager.cancelSession("ghost-session"));
+ expect(err).toBeInstanceOf(ContractErrorException);
+ expect((err as ContractErrorException).code).toBe("unknown_session");
+ const cap = captureError(() => manager.captureSession("ghost-session"));
+ expect((cap as ContractErrorException).code).toBe("unknown_session");
});
- test("meta.json is written to the configured sessions directory after completion", async () => {
- const id = quickSession(manager);
- const metaPath = await waitForMeta(id);
- const meta = JSON.parse(readFileSync(metaPath, "utf-8")) as Record<string, unknown>;
-
- expect(meta.sessionId).toBe(id);
- expect(meta.model).toBe("test-model");
- expect(meta.status).toBe("completed");
- expect(meta.turnsCompleted).toBe(1);
- expect(typeof meta.startedAt).toBe("string");
- expect(typeof meta.completedAt).toBe("string");
- });
-
- test("createSession stores session in listSessions immediately", () => {
- const id = manager.createSession({
- model: "test-model",
- claudishFlags: ["--sleep", "3"],
+ test("a 10.4.0-generation meta.json (status, no state) reads into the closed set", () => {
+ const write = (id: string, meta: Record<string, unknown>) => {
+ mkdirSync(join(sessionsDir, id), { recursive: true });
+ writeFileSync(join(sessionsDir, id, "meta.json"), JSON.stringify(meta));
+ };
+ const base = {
+ model: "m",
+ startedAt: "2026-10-01T00:00:00.000Z",
+ completedAt: "2026-10-01T00:01:00.000Z",
+ turnsCompleted: 2,
+ toolCallCount: 3,
+ costUsd: 0.5,
+ tokensUsed: 100,
+ exitCode: 143,
+ terminalReason: "user_cancelled",
+ };
+ write("old-cancelled", { ...base, sessionId: "old-cancelled", status: "cancelled" });
+ write("old-completed", { ...base, sessionId: "old-completed", status: "completed" });
+ write("old-timeout", { ...base, sessionId: "old-timeout", status: "timeout" });
+ write("old-finishing", { ...base, sessionId: "old-finishing", status: "finishing" });
+
+ const cancelled = manager.getSession("old-cancelled");
+ expect(cancelled.state).toBe("CANCELLED");
+ expect(cancelled.reason).toBe("cancelled");
+ expect(cancelled.toolCalls).toBe(3);
+ expect(cancelled.costUsd).toBe(0.5);
+ expect(cancelled.turnsCompleted).toBe(2);
+ expect(cancelled.exitCode).toBe(143);
+ expect(cancelled.elapsedSeconds).toBe(60);
+ expect(cancelled.panePid).toBeNull();
+ expect(manager.getSession("old-completed")).toMatchObject({ state: "COMPLETED", reason: null });
+ expect(manager.getSession("old-timeout")).toMatchObject({
+ state: "TIMEOUT",
+ reason: "timeout",
});
- expect(manager.listSessions(true).some((session) => session.sessionId === id)).toBe(true);
- });
-
- test("cancelled session appears in listSessions with includeCompleted=true", async () => {
- const id = manager.createSession({
- model: "test-model",
- claudishFlags: ["--sleep", "3"],
+ // a non-terminal pre-contract value is FAILED with reason null (§8 B)
+ expect(manager.getSession("old-finishing")).toMatchObject({ state: "FAILED", reason: null });
+ expect(manager.getDiagnostics("old-cancelled")).toMatchObject({
+ state: "CANCELLED",
+ event: "cancelled",
+ phase: null,
+ connected: false,
});
- await waitUntil(() => manager.getSession(id).pid !== null);
- manager.cancelSession(id);
-
- const found = manager.listSessions(true).find((session) => session.sessionId === id);
- expect(found?.status).toBe("cancelled");
- });
-
- test("getOutput totalLines reflects number of lines produced", async () => {
- const id = quickSession(manager, ["--messages", "5"]);
- await waitForCompleted(manager, id);
- expect(manager.getOutput(id).totalLines).toBeGreaterThanOrEqual(5);
- });
-
- test("cancelSession returns false for non-existent session", () => {
- expect(manager.cancelSession("ghost-session")).toBe(false);
});
- test(
- "G1/G2: timeout stays timeout in memory, meta, and on the wire",
- async () => {
- const events: ChannelEvent[] = [];
- const timeoutManager = makeManager({
- onStateChange: (_sessionId, event) => events.push(event),
- });
- const id = timeoutManager.createSession({
- model: "test-model",
- timeoutSeconds: 1,
- claudishFlags: ["--result-then-hang", "--trap-term-exit-zero"],
- });
-
- // Promptless, so it waits for its first input from creation.
- await waitForStatus(timeoutManager, id, ["waiting_for_input"]);
- expect(timeoutManager.sendInput(id, "interactive turn")).toBe(true);
- await waitForStatus(timeoutManager, id, ["waiting_for_input"]);
-
- // If the SIGTERM trap loses its race, SIGKILL follows only after the full
- // grace, then exit, pipe drain, and writeArtifacts must finish. Keep these
- // polling budgets above KILL_GRACE_MS or load makes this a fast-path-only test.
- await waitForStatus(timeoutManager, id, ["timeout"], POST_SIGTERM_WAIT_MS);
- const metaPath = await waitForMeta(id, POST_SIGTERM_WAIT_MS);
- const info = timeoutManager.getSession(id);
- const meta = JSON.parse(readFileSync(metaPath, "utf-8")) as {
- status: string;
- exitCode: number | null;
- };
- const terminalWireEvents = events
- .map((event) => event.type)
- .filter((type) => TERMINAL_STATUSES.includes(type as SessionStatus));
-
- // Same test, deliberately: memory, persistent data, and the wire must all
- // report the honest terminal reason. SEP-1686 projects timeout to failed.
- expect(info.status).toBe("timeout");
- expect(meta.status).toBe("timeout");
- expect(info.exitCode).toBe(0);
- expect(meta.exitCode).toBe(0);
- expect(terminalWireEvents).toEqual(["timeout"]);
- expect(events.some((event) => event.type === "timeout")).toBe(true);
- },
- TIMEOUT_REGRESSION_TEST_MS
- );
-
- test("G7: a promptless session reaches a usable state and accepts later input", async () => {
- const id = manager.createSession({ model: "test-model", timeoutSeconds: 5 });
-
- // Waiting for input from creation: nothing happens until send_input.
- await waitForStatus(manager, id, ["waiting_for_input"], 2000);
- expect(manager.sendInput(id, "first interactive turn")).toBe(true);
- await waitUntil(
- () =>
- manager.getSession(id).status === "waiting_for_input" &&
- manager.getOutput(id).output.includes(CAPTURED_ASSISTANT_PROSE),
- 2000
- );
-
- expect(existsSync(join(sessionsDir, id, "prompt.md"))).toBe(false);
- expect(manager.getSession(id).status).toBe("waiting_for_input");
- expect(manager.cancelSession(id)).toBe(true);
- });
-
- test("G6: delta firehose is not stored and cannot evict assistant prose", () => {
- const boundedManager = makeManager({ scrollbackCapacity: 2000 });
- const id = boundedManager.createSession({
- model: "test-model",
- claudishFlags: ["--sleep", "60"],
+ test("a pane-generation meta.json round-trips through toMetaRecord; a stale transcript path is re-derived", () => {
+ const cwd = join(root, "work dir_1");
+ mkdirSync(cwd, { recursive: true });
+ const info = sampleInfo({
+ sessionId: "pane-gen",
+ shape: "interactive",
+ parentClaudeSessionId: "parent-9",
});
- const internal = boundedManager as unknown as {
- sessions: Map<string, { process: ChildProcess }>;
- };
- const stdout = internal.sessions.get(id)?.process.stdout;
- if (!stdout) throw new Error("spawned test child has no stdout pipe");
-
- for (let i = 0; i < 3; i++) {
- stdout.emit("data", Buffer.from(`${JSON.stringify(capturedAssistantFrame())}\n`));
- }
- stdout.emit("data", Buffer.from(`${CAPTURED_DELTA_LINE}\n`.repeat(3000)));
-
- const output = boundedManager.getOutput(id);
- expect(output.output).toContain(CAPTURED_ASSISTANT_PROSE);
- expect(output.output).not.toContain('"type":"stream_event"');
- expect(output.totalLines).toBeLessThan(20);
- });
+ mkdirSync(join(sessionsDir, "pane-gen"), { recursive: true });
+ writeFileSync(
+ join(sessionsDir, "pane-gen", "meta.json"),
+ JSON.stringify(toMetaRecord(info, cwd))
+ );
+ writeFileSync(join(sessionsDir, "pane-gen", "screen.txt"), "❯ final screen\n");
- test("D1: a new manager recovers a finished session from disk", async () => {
- const id = quickSession(manager, [], "DELTA");
- await waitForCompleted(manager, id);
- await waitForMeta(id);
-
- const liveInfo = manager.getSession(id);
- const liveOutput = manager.getOutput(id);
- const recovered = makeManager();
-
- const info = recovered.getSession(id);
- const output = recovered.getOutput(id);
- const diagnostics = recovered.getDiagnostics(id);
-
- expect(info).toMatchObject({
- sessionId: id,
- model: liveInfo.model,
- status: "completed",
- turnsCompleted: liveInfo.turnsCompleted,
- exitCode: liveInfo.exitCode,
- });
- expect(output).toMatchObject({
- sessionId: id,
- status: "completed",
- turnsCompleted: liveOutput.turnsCompleted,
- tokensUsed: liveOutput.tokensUsed,
- });
- // ScrollbackBuffer is chunk-boundary sensitive: live can retain a phantom
- // trailing line that a one-append disk replay correctly cannot reproduce.
- expect(output.output.trimEnd()).toBe(liveOutput.output.trimEnd());
- expect(diagnostics).toMatchObject({
- sessionId: id,
- status: "completed",
- model: liveInfo.model,
- turnsCompleted: liveInfo.turnsCompleted,
+ const read = manager.getSession("pane-gen");
+ expect(read).toMatchObject({
+ sessionId: "pane-gen",
+ model: "glm-5",
+ spawnModel: "gc@glm-5",
+ provider: "GLM Coding",
+ state: "EMPTY",
+ reason: "shape_mismatch",
+ detail: "no match",
+ shape: "interactive",
+ pane: info.pane,
+ panePid: null,
+ tokensIn: 1000,
+ tokensOut: 50,
+ costUsd: 0.01,
+ toolCalls: 3,
+ turnsCompleted: 1,
+ timeoutSeconds: 600,
+ parentClaudeSessionId: "parent-9",
+ idleSeconds: null,
});
- expect(diagnostics.outputBytes).toBeGreaterThan(0);
- expect(diagnostics.eventsTotal).toBeGreaterThan(0);
- expect(diagnostics.recentEvents.every((event) => event.at === "")).toBe(true);
- });
-
- test("D2: a disk-recovered session is structurally read-only", async () => {
- const id = quickSession(manager);
- await waitForCompleted(manager, id);
- await waitForMeta(id);
-
- const recovered = makeManager();
- expect(recovered.getSession(id).pid).toBeNull();
- expect(recovered.sendInput(id, "hello")).toBe(false);
- expect(recovered.cancelSession(id)).toBe(false);
+ expect(read.transcriptPath).toBe(
+ transcriptPathFor(
+ cwd,
+ info.claudeSessionId,
+ projectsDir({ HOME: join(root, "home"), CLAUDE_CONFIG_DIR: join(root, "home", ".claude") })
+ )
+ );
+ expect(manager.getDiagnostics("pane-gen").screenTail).toBe("❯ final screen");
});
test("D3: hostile session ids are rejected before disk lookup", () => {
- const root = join(sessionsDir, "hostile-root");
const outside = join(root, "outside");
mkdirSync(join(outside, "victim"), { recursive: true });
writeFileSync(join(outside, "victim", "meta.json"), JSON.stringify({ model: "LEAKED" }));
- const hostileManager = makeManager({ sessionsDir: join(root, "sessions") });
-
for (const id of [
"../outside/victim",
"..%2Foutside",
@@ -501,7 +400,7 @@ describe("SessionManager", () => {
".hidden",
"x".repeat(200),
]) {
- expect(() => hostileManager.getSession(id), JSON.stringify(id)).toThrow("not found");
+ expect(() => manager.getSession(id), JSON.stringify(id)).toThrow("not found");
}
});
@@ -516,6 +415,7 @@ describe("SessionManager", () => {
sessionId: 42,
model: null,
status: "banana",
+ state: "BANANA",
tokensUsed: "lots",
pid: 1,
startedAt: [],
@@ -524,7 +424,6 @@ describe("SessionManager", () => {
],
["notjson", "[1,2,3]"],
];
-
for (const [id, meta] of cases) {
const dir = join(sessionsDir, id);
mkdirSync(dir, { recursive: true });
@@ -535,15 +434,17 @@ describe("SessionManager", () => {
const output = manager.getOutput(id);
const diagnostics = manager.getDiagnostics(id);
expect(info.sessionId).toBe(id);
- expect(info.pid).toBeNull();
- expect(typeof info.tokensUsed).toBe("number");
+ expect(info.panePid).toBeNull();
+ expect(info.state).toBe("FAILED");
+ expect(typeof info.toolCalls).toBe("number");
expect(Number.isFinite(info.elapsedSeconds)).toBe(true);
expect(typeof output.output).toBe("string");
- expect(typeof diagnostics.stderrTail).toBe("string");
+ expect(typeof diagnostics.screenTail).toBe("string");
if (id !== "wrongtypes") {
expect(diagnostics.anomalies.length, id).toBeGreaterThan(0);
}
}
+ expect(manager.getOutput("halfwritten").output).toContain("partial answer");
});
test("D5: disk diagnostics stay bounded for a 4 MB event log", () => {
@@ -559,16 +460,10 @@ describe("SessionManager", () => {
startedAt: new Date().toISOString(),
})
);
-
const frames: string[] = [];
let eventBytes = 0;
for (let i = 0; eventBytes < 4 * 1024 * 1024; i++) {
- const frame = `${JSON.stringify({
- type: "assistant",
- subtype: null,
- i,
- pad: "x".repeat(2000),
- })}\n`;
+ const frame = `${JSON.stringify({ type: "state", i, pad: "x".repeat(2000) })}\n`;
frames.push(frame);
eventBytes += Buffer.byteLength(frame);
}
@@ -582,69 +477,367 @@ describe("SessionManager", () => {
});
});
-describe("exported channel transport seams", () => {
- test("timeout projects to SEP-1686 failed instead of falling through to working", () => {
- expect(mapEventToTaskStatus("timeout")).toBe("failed");
- expect(mapEventToTaskStatus("timeout")).not.toBe("working");
- expect(mapEventToTaskStatus("genuinely_unknown_event")).toBe("working");
+// ─── panes ────────────────────────────────────────────────────────────────
- for (const [event, status] of [
- ["completed", "completed"],
- ["failed", "failed"],
- ["cancelled", "cancelled"],
- ] as const) {
- expect(mapEventToTaskStatus(event)).toBe(status);
+describe.skipIf(!MAGMUX)(
+ `SessionManager on panes (${MAGMUX ? "magmux" : NO_MAGMUX_MESSAGE})`,
+ () => {
+ let t: PaneTestEnv;
+ let sessionsDir: string;
+ let managers: SessionManager[];
+
+ beforeEach(() => {
+ t = makePaneTestEnv();
+ sessionsDir = join(t.tmp, "sessions");
+ managers = [];
+ });
+
+ afterEach(async () => {
+ for (const m of managers) await m.shutdownAll();
+ const report = await waitNoOrphans({ sockRoot: t.sockRoot }, 10_000);
+ killLeftovers({ sockRoot: t.sockRoot });
+ t.cleanup();
+ expect(report).toEqual({ processes: [], files: [] });
+ });
+
+ function makeManager(opts: SessionManagerOptions = {}): SessionManager {
+ const manager = new SessionManager({
+ maxSessions: 20,
+ sessionsDir,
+ hostPid: 1,
+ parentEnv: t.env,
+ paneTimings: { replStableMs: 200 },
+ ...opts,
+ });
+ managers.push(manager);
+ return manager;
}
- });
- test("G4: every transport-owned flag is rejected loudly", () => {
- for (const flag of [
- "-p",
- "--print",
- "--output-format",
- "--input-format",
- "--session-id",
- "--verbose",
- "--output-format=json",
- ]) {
- expect(() => assertNoReservedFlags([flag])).toThrow(/channel transport/);
+ function create(
+ manager: SessionManager,
+ opts: { model?: string; prompt?: string; timeoutSeconds?: number; spawnModel?: string } = {}
+ ): Promise<string> {
+ return manager.createSession({ model: "fake-answer", cwd: t.cwd, ...opts });
}
- expect(() =>
- assertNoReservedFlags(["--effort", "high", "--agent", "dev:reviewer"])
- ).not.toThrow();
- });
+ async function waitForState(
+ manager: SessionManager,
+ id: string,
+ states: readonly SlotState[],
+ timeoutMs = 15_000
+ ): Promise<void> {
+ await waitUntil(() => states.includes(manager.getSession(id).state), timeoutMs);
+ }
- test("G5: spawn argv keeps verbose before quiet and leaves -p valueless", () => {
- const args = buildChannelSpawnArgs({
- model: "provider@model",
- claudeSessionId: "captured-session-id",
- claudishFlags: ["--effort", "high"],
- });
- const verboseAt = args.indexOf("--verbose");
- const quietAt = args.indexOf("--quiet");
- const printAt = args.indexOf("-p");
-
- expect(verboseAt).toBeGreaterThan(-1);
- expect(quietAt).toBeGreaterThan(verboseAt);
- expect(printAt).toBeGreaterThan(-1);
- expect(args[printAt + 1]?.startsWith("-")).toBe(true);
- expect(args).not.toContain("--stdin");
- });
+ const waitForMeta = (id: string, timeoutMs = 15_000) =>
+ waitUntil(() => existsSync(join(sessionsDir, id, "meta.json")), timeoutMs).then(() =>
+ JSON.parse(readFileSync(join(sessionsDir, id, "meta.json"), "utf-8"))
+ );
+
+ test(
+ "createSession returns unique ids; a promptless session is STARTING, then AWAITING_INPUT once booted",
+ async () => {
+ const manager = makeManager();
+ const id1 = await create(manager);
+ const id2 = await create(manager);
+ expect(id1).not.toBe(id2);
+ const info = manager.getSession(id1);
+ expect(info.sessionId).toBe(id1);
+ expect(info.model).toBe("fake-answer");
+ expect(info.shape).toBe("interactive");
+ expect(typeof info.startedAt).toBe("string");
+ expect(info.completedAt).toBeNull();
+ expect(info.exitCode).toBeNull();
+ expect(info.pane).not.toBeNull();
+ expect(["STARTING", "AWAITING_INPUT"]).toContain(info.state);
+ await waitForState(manager, id1, ["AWAITING_INPUT"]);
+ expect(manager.getSession(id1).panePid).not.toBeNull();
+ expect(manager.listSessions(false).map((s) => s.sessionId)).toEqual(
+ expect.arrayContaining([id1, id2])
+ );
+ },
+ T_PANE
+ );
- test("userFrame encodes one newline-delimited user turn", () => {
- const encoded = userFrame("hello\nworld");
- expect(encoded.endsWith("\n")).toBe(true);
- expect(encoded.split("\n")).toHaveLength(2);
- expect(JSON.parse(encoded)).toEqual({
- type: "user",
- message: {
- role: "user",
- content: [{ type: "text", text: "hello\nworld" }],
+ test(
+ "spawnModel changes argv while SessionInfo keeps the requested model; the argv is interactive",
+ async () => {
+ const probe = join(t.tmp, "probe-{session}.json");
+ const manager = makeManager({ parentEnv: { ...t.env, FAKE_PROBE_FILE: probe } });
+ const pinned = await create(manager, { model: "glm-5", spawnModel: "fake-env_probe" });
+ const bare = await create(manager, { model: "fake-env_probe" });
+ const argvOf = (id: string) => {
+ const path = probe.replace("{session}", manager.getSession(id).claudeSessionId);
+ return waitUntil(() => existsSync(path)).then(
+ () => (JSON.parse(readFileSync(path, "utf-8")) as { argv: string[] }).argv
+ );
+ };
+ const a = await argvOf(pinned);
+ expect(a[a.indexOf("--model") + 1]).toBe("fake-env_probe");
+ expect(a[0]).toBe("-i");
+ for (const banned of ["-p", "--print", "--stdin", "--output-format", "--input-format"])
+ expect(a).not.toContain(banned);
+ expect(manager.getSession(pinned).model).toBe("glm-5");
+ expect(manager.getSession(pinned).spawnModel).toBe("fake-env_probe");
+ const b = await argvOf(bare);
+ expect(b[b.indexOf("--model") + 1]).toBe("fake-env_probe");
+ expect(manager.getSession(bare).spawnModel).toBeNull();
},
- });
- });
-});
+ T_PANE
+ );
+
+ test(
+ "listSessions excludes a completed session unless includeCompleted; meta.json is written at completion",
+ async () => {
+ const manager = makeManager();
+ const id = await create(manager, { prompt: "hello" });
+ await waitForState(manager, id, ["COMPLETED"]);
+ expect(manager.listSessions(false).some((s) => s.sessionId === id)).toBe(false);
+ expect(manager.listSessions(true).some((s) => s.sessionId === id)).toBe(true);
+ const meta = await waitForMeta(id);
+ expect(meta.sessionId).toBe(id);
+ expect(meta.model).toBe("fake-answer");
+ expect(meta.status).toBe("completed");
+ expect(meta.state).toBe("COMPLETED");
+ expect(meta.turnsCompleted).toBe(1);
+ expect(meta.terminalReason).toBeNull();
+ expect(typeof meta.startedAt).toBe("string");
+ expect(typeof meta.completedAt).toBe("string");
+ },
+ T_PANE
+ );
+
+ test(
+ "maxSessions limit: the 3rd session throws when the limit is 2",
+ async () => {
+ const limited = makeManager({ maxSessions: 2 });
+ await create(limited);
+ await create(limited);
+ await expect(create(limited)).rejects.toThrow(/Max sessions/);
+ },
+ T_PANE
+ );
+
+ test(
+ "cancelSession: CANCELLED at once, idempotent, and listed with includeCompleted",
+ async () => {
+ const manager = makeManager();
+ const id = await create(manager);
+ await waitUntil(() => manager.getSession(id).panePid !== null);
+ expect(manager.cancelSession(id)).toEqual({
+ session_id: id,
+ state: "CANCELLED",
+ changed: true,
+ });
+ expect(manager.getSession(id).state).toBe("CANCELLED");
+ expect(manager.cancelSession(id)).toEqual({
+ session_id: id,
+ state: "CANCELLED",
+ changed: false,
+ });
+ const found = manager.listSessions(true).find((s) => s.sessionId === id);
+ expect(found?.state).toBe("CANCELLED");
+ expect(found?.reason).toBe("cancelled");
+ },
+ T_PANE
+ );
+
+ test(
+ "a finished one-shot session refuses send_input and cancel changes nothing",
+ async () => {
+ const manager = makeManager();
+ const id = await create(manager, { prompt: "hello" });
+ await waitForState(manager, id, ["COMPLETED"]);
+ expect(manager.sendInput(id, "some input")).toEqual({
+ success: false,
+ reason: "terminal",
+ state: "COMPLETED",
+ });
+ expect(manager.cancelSession(id).changed).toBe(false);
+ },
+ T_PANE
+ );
+
+ test(
+ "getOutput returns the answer prose, never raw records; tail_lines returns the last N",
+ async () => {
+ const manager = makeManager();
+ const one = await create(manager, { prompt: "hello world" });
+ await waitForState(manager, one, ["COMPLETED"]);
+ const output = manager.getOutput(one);
+ expect(output.sessionId).toBe(one);
+ expect(output.state).toBe("COMPLETED");
+ expect(output.output).toMatch(/^ANSWER fake-answer [0-9a-f]{8}/);
+ expect(output.output).not.toContain('"type":"assistant"');
+
+ const id = await create(manager);
+ for (const [i, text] of ["first", "second", "third"].entries()) {
+ await waitForState(manager, id, ["AWAITING_INPUT"]);
+ expect(manager.sendInput(id, text).success).toBe(true);
+ await waitUntil(
+ () =>
+ manager.getSession(id).turnsCompleted === i + 1 &&
+ manager.getSession(id).state === "AWAITING_INPUT",
+ 15_000
+ );
+ }
+ const full = manager.getOutput(id);
+ const tail = manager.getOutput(id, 2);
+ const fullLines = full.output.split("\n");
+ expect(full.output.match(/ANSWER fake-answer/g)).toHaveLength(3);
+ expect(tail.output).toBe(fullLines.slice(-2).join("\n"));
+ expect(tail.totalLines).toBe(full.totalLines);
+ expect(tail.output).not.toBe(full.output);
+ expect(full.totalLines).toBeGreaterThanOrEqual(3);
+ },
+ T_PANE
+ );
+
+ test(
+ "10.4.0 edit: a one-shot session's frames are exactly running → completed",
+ async () => {
+ const events: Array<{ sessionId: string; event: ChannelEvent }> = [];
+ const manager = makeManager({
+ onStateChange: (sessionId, event) => events.push({ sessionId, event }),
+ });
+ const id = await create(manager, { prompt: "trigger events" });
+ await waitForState(manager, id, ["COMPLETED"]);
+ expect(events.map(({ event }) => event.type)).toEqual(["running", "completed"]);
+ for (const observed of events) {
+ expect(observed.sessionId).toBe(id);
+ expect(observed.event.model).toBe("fake-answer");
+ }
+ },
+ T_PANE
+ );
+
+ test(
+ "10.4.0 edit: a promptless session's first frame is waiting_for_input, after boot",
+ async () => {
+ const events: string[] = [];
+ const manager = makeManager({ onStateChange: (_sid, e) => events.push(e.type) });
+ const id = await create(manager);
+ expect(events).not.toContain("waiting_for_input");
+ await waitForState(manager, id, ["AWAITING_INPUT"]);
+ await waitUntil(() => events.length > 0);
+ expect(events[0]).toBe("waiting_for_input");
+ expect(events).not.toContain("starting");
+ },
+ T_PANE
+ );
+
+ test(
+ "G1/G2: a timeout stays TIMEOUT in memory, meta and on the wire, with a send queued while RUNNING",
+ async () => {
+ const events: ChannelEvent[] = [];
+ const manager = makeManager({ onStateChange: (_sid, event) => events.push(event) });
+ const id = await create(manager, {
+ model: "contract-fake-model",
+ prompt: "work forever @@HANG@@",
+ timeoutSeconds: 6,
+ });
+ await waitForState(manager, id, ["RUNNING"]);
+ const queued = manager.sendInput(id, "later");
+ expect(queued.success).toBe(true);
+ expect(queued.success && queued.queued).toBeGreaterThanOrEqual(1);
+ expect(manager.getSession(id).state).toBe("RUNNING");
+
+ await waitForState(manager, id, ["TIMEOUT"], 15_000);
+ const meta = await waitForMeta(id);
+ const info = manager.getSession(id);
+ const terminalWireEvents = events
+ .map((e) => e.type)
+ .filter((x) => TERMINAL_EVENTS.includes(x));
+
+ expect(info.state).toBe("TIMEOUT");
+ expect(info.reason).toBe("timeout");
+ expect(meta.status).toBe("timeout");
+ expect(meta.state).toBe("TIMEOUT");
+ expect(meta.terminalReason).toBe("timeout");
+ // RB4: claudish ended the pane, so there is no child exit code.
+ expect(info.exitCode).toBeNull();
+ expect(meta.exitCode).toBeNull();
+ expect(terminalWireEvents).toEqual(["timeout"]);
+ },
+ T_PANE
+ );
+
+ test(
+ "G7: a promptless session takes a send while STARTING (queued) and answers it",
+ async () => {
+ const manager = makeManager();
+ const id = await create(manager, { timeoutSeconds: 30 });
+ expect(manager.getSession(id).state).toBe("STARTING");
+ const r = manager.sendInput(id, "first interactive turn");
+ expect(r).toEqual({ success: true, queued: 1 });
+ await waitUntil(
+ () =>
+ manager.getSession(id).state === "AWAITING_INPUT" &&
+ manager.getOutput(id).output.includes("ANSWER fake-answer"),
+ 15_000
+ );
+ expect(existsSync(join(sessionsDir, id, "prompt.md"))).toBe(false);
+ expect(manager.getSession(id).turnsCompleted).toBe(1);
+ expect(manager.cancelSession(id).changed).toBe(true);
+ },
+ T_PANE
+ );
+
+ test(
+ "D1/D2: a new manager recovers a finished session from disk, read-only",
+ async () => {
+ const manager = makeManager();
+ const id = await create(manager, { prompt: "DELTA" });
+ await waitForState(manager, id, ["COMPLETED"]);
+ await waitForMeta(id);
+
+ const liveInfo = manager.getSession(id);
+ const liveOutput = manager.getOutput(id);
+ const recovered = makeManager();
+
+ const info = recovered.getSession(id);
+ const output = recovered.getOutput(id);
+ const diagnostics = recovered.getDiagnostics(id);
+ expect(info).toMatchObject({
+ sessionId: id,
+ model: liveInfo.model,
+ state: "COMPLETED",
+ turnsCompleted: liveInfo.turnsCompleted,
+ exitCode: liveInfo.exitCode,
+ tokensIn: liveInfo.tokensIn,
+ tokensOut: liveInfo.tokensOut,
+ claudeSessionId: liveInfo.claudeSessionId,
+ transcriptPath: liveInfo.transcriptPath,
+ });
+ expect(output).toMatchObject({ sessionId: id, state: "COMPLETED", turnsCompleted: 1 });
+ expect(output.output.trimEnd()).toBe(liveOutput.output.trimEnd());
+ expect(diagnostics).toMatchObject({
+ sessionId: id,
+ state: "COMPLETED",
+ event: "completed",
+ });
+ expect(diagnostics.outputBytes).toBeGreaterThan(0);
+ expect(diagnostics.eventsTotal).toBeGreaterThan(0);
+ // every record claudish writes carries its own `at`
+ expect(diagnostics.recentEvents.every((e) => /^\d{4}-\d\d-\d\dT/.test(e.at))).toBe(true);
+ expect(diagnostics.screenTail.length).toBeGreaterThan(0);
+
+ // D2: structurally read-only
+ expect(info.panePid).toBeNull();
+ expect(recovered.sendInput(id, "hello")).toMatchObject({
+ success: false,
+ reason: "unknown_session",
+ });
+ expect(
+ (captureError(() => recovered.cancelSession(id)) as ContractErrorException).code
+ ).toBe("unknown_session");
+ },
+ T_PANE
+ );
+ }
+);
+
+// ─── signal exit codes ───────────────────────────────────────────────────
interface ExitObservation {
code: number | null;
diff --git a/packages/cli/src/channel/session-manager.ts b/packages/cli/src/channel/session-manager.ts
index 9f22044a..a01a5117 100644
--- a/packages/cli/src/channel/session-manager.ts
+++ b/packages/cli/src/channel/session-manager.ts
@@ -1,33 +1,31 @@
// ─── SessionManager ──────────────────────────────────────────────────────────
//
-// Lifecycle owner for channel sessions. Each session is one `claudish` child
-// spawned over plain pipes, driven by BIDIRECTIONAL stream-json:
+// Lifecycle owner for channel sessions. Each session is one INTERACTIVE Claude Code,
+// launched through claudish (`claudish -i --model X -y --quiet --session-id <uuid>
+// --add-dir <turnDir> [caller flags]`) inside its own headless magmux pane and driven
+// over the pane's socket (packages/cli/src/pane/, architecture §2). There is no `-p`,
+// no `--stdin` and no stream-json: the child's own transcript is the turn oracle, and
+// the pane session's phase table is the clock of every state record this file writes.
//
-// parent ──{"type":"user",…}──▶ proc.stdin ─inherit─▶ claude's fd 0
-// parent ◀── NDJSON frames ──── proc.stdout ◀─inherit─ claude's fd 1
+// The policy stays here (D8): a one-shot session's verdict is `classifyRunOutput` with
+// no byte floor and no pattern; an interactive session continues after each turn and
+// fails only on an API-error turn (D20); a question or a permission dialog waits for
+// `send_input` (D19 is team's rule, not ours). `send_input` is accepted in every
+// non-terminal state and queued (D17). `timeout_seconds` is the caller's own deadline
+// and the only post-acceptance timer (D10).
//
-// There is no relay code in between. `claudish` is spawned WITHOUT `--stdin`, so
-// nothing in it consumes fd 0, and it spawns `claude` with `stdio: "inherit"` —
-// which means the pipe this file creates lands directly on the grandchild.
-// Verified end to end on 2026-08-22 against claude 2.1.239 (see
-// ai-docs/sessions/dev-feature-stream-json-*/probes/probe-argv.ts).
-//
-// What that buys, in order of how badly it was needed:
-// * progress that is real — the child declares its state instead of us
-// regex-matching TUI glyphs it never prints (see stream-json-reducer.ts)
-// * `send_input` that works — it has never worked before; the bytes used to
-// land in an already-satisfied stdin drain
-// * a terminal state that has to be earned — `result.terminal_reason` plus
-// `classifyRunOutput`, instead of "exit code 0 means success"
-// * real tokens and cost — `CLAUDISH_TOKEN_FILE` points the child's own token
-// tracker at this session's directory
-
-import { type ChildProcess, spawn } from "node:child_process";
+// The 10.4.0 session records are kept, byte for byte where the magus monitor reads
+// them (§20.1): `spawn.json` before any pane, `waits.jsonl` from the pane's transition
+// hook, `meta.json` through `toMetaRecord` with every 10.4.0 key, `events.jsonl` with
+// one `assistant` line per main-chain message id.
+
import { randomUUID } from "node:crypto";
import {
+ type WriteStream,
appendFileSync,
closeSync,
createWriteStream,
+ existsSync,
mkdirSync,
openSync,
readFileSync,
@@ -37,91 +35,125 @@ import {
writeFileSync,
} from "node:fs";
import { join, resolve, sep } from "node:path";
-import { StringDecoder } from "node:string_decoder";
import { ENV } from "../config.js";
import { UPSTREAM_ERROR_LOG_ENV } from "../handlers/shared/upstream-error-capture.js";
-import { KILL_PROCESS_GROUP, signalProcessTree, terminateChildTree } from "../process-tree.js";
+import {
+ type Accounting,
+ type CaptureResult,
+ type CaptureUnchanged,
+ ContractErrorException,
+ FAILURE_REASONS,
+ type FailureReason,
+ type FinalVerdict,
+ type PaneBlock,
+ type PaneSession,
+ type PaneSessionOptions,
+ type PaneSnapshot,
+ SLOT_STATES,
+ type SessionCancelResult,
+ type SessionRow,
+ type SettledTurn,
+ type SlotState,
+ assertMagmuxAvailable,
+ checkChildFlags,
+ deliveryRefusal,
+ flagsRemoveRead,
+ isTerminalState,
+ mergeAccounting,
+ readTokenFileCached,
+ releasePaneReservations,
+ reservePanes,
+ resolveProvider,
+ sockRootFor,
+ startPaneSession,
+} from "../pane/index.js";
import { redactSecrets } from "../redact.js";
-import { transcriptPathFor } from "../session/session-discovery.js";
-import { resolveClaudishSpawn } from "../spawn-claudish.js";
-import { decodeChunk } from "../stdio-decode.js";
-import { STDOUT_TAIL_LIMIT, type TeamRunOutcome } from "../team-orchestrator.js";
+import { projectsDir, transcriptPathFor } from "../session/session-discovery.js";
+import { TRUNCATION_NOTE, type TeamRunOutcome, classifyRunOutput } from "../team-orchestrator.js";
import { readTokenStatsAt } from "../team-stats.js";
import { sessionsDirFrom } from "./home-dir.js";
import { hostPidFrom } from "./parent-proof.js";
import { ScrollbackBuffer } from "./scrollback-buffer.js";
-import {
- type ResultSummary,
- StreamJsonReducer,
- type TurnEnd,
- labelForLine,
-} from "./stream-json-reducer.js";
import type {
ChannelEvent,
+ ChannelEventType,
SessionCreateOptions,
SessionInfo,
SessionManagerOptions,
- SessionStatus,
} from "./types.js";
-/** One semantic frame, as `get_diagnostics` returns it. */
+/** One record of the session's own event log, as `get_diagnostics` returns it. */
export interface DiagnosticEvent {
/**
- * When the frame was observed, ISO-8601 — or `""` for a frame recovered from
- * `events.jsonl` after the session left memory.
- *
- * The log stores the frame verbatim and nothing else, so the observation time
- * is genuinely not on disk. Empty rather than back-filled from the file's
- * mtime or the session's `completedAt`: both would be a fabricated timestamp
- * indistinguishable from a measured one, and every frame would carry the same
- * one. A consumer can tell the two cases apart by testing for "".
+ * When the record was written, ISO-8601 — or `""` for a record recovered from
+ * `events.jsonl` after the session left memory whose line carries no `at`.
+ * Empty rather than back-filled from the file's mtime: a fabricated timestamp is
+ * indistinguishable from a measured one.
*/
at: string;
- /** `type[:subtype]` from the frame, or null for a line that carried no type. */
+ /** The record's `type` (`state`, `tool`, `anomaly`, `assistant`), or null. */
label: string | null;
- /** The frame, redacted and truncated to `EVENT_PREVIEW_CHARS`. */
+ /** The record, redacted and truncated to `EVENT_PREVIEW_CHARS`. */
preview: string;
- /** True when `preview` is a prefix rather than the whole frame. */
+ /** True when `preview` is a prefix rather than the whole record. */
truncated: boolean;
}
/** What `get_diagnostics` returns. Every field is reachable without a filesystem read. */
export interface SessionDiagnostics {
sessionId: string;
- status: SessionStatus;
+ state: SlotState;
+ /** The current channel event (10.4.0's `status` key, RB7). */
+ event: ChannelEventType;
+ reason: FailureReason | null;
+ detail: string | null;
/** The model as the caller asked for it. */
model: string;
/** The pinned `provider@model` the child was spawned with, or null. */
spawnModel: string | null;
+ provider: string | null;
+ shape: "one-shot" | "interactive";
+ /** The pane's internal phase; null when the session is not live. */
+ phase: string | null;
exitCode: number | null;
- terminalReason: string | null;
- /**
- * Seconds since the child last emitted a frame; null when the session is not
- * live. Reported so the caller can tell working-but-quiet from wedged.
- * Nothing in claudish acts on it.
- */
+ /** Seconds since the last screen change or transcript append; null when not live. */
idleSeconds: number | null;
elapsedSeconds: number;
- /** The session's own timeout, for reading `elapsedSeconds` against. */
+ /** The session's own timeout, for reading `elapsedSeconds` against (0 when unknown). */
timeoutSeconds: number;
- /** Bytes of recovered assistant PROSE. Zero on a session that produced no answer. */
+ /** Bytes of answer prose in `get_output`. Zero on a session that produced no answer. */
outputBytes: number;
turnsCompleted: number;
- tokensUsed: number;
- costUsd: number;
- toolCallCount: number;
- /** Redacted, bounded stderr. See `stderrForDiagnostics` for which rule produced it. */
- stderrTail: string;
- /** True when benign boilerplate was dropped (success path only). */
- stderrFiltered: boolean;
- /** True when the in-memory stderr buffer dropped a middle section. */
- stderrTruncated: boolean;
- /** Illegal transitions and unparseable lines the reducer recorded. */
+ tokensIn: number | null;
+ tokensOut: number | null;
+ costUsd: number | null;
+ toolCalls: number;
+ pendingInputs: number;
+ /** Whether claudish holds a live socket to the pane's magmux right now. */
+ connected: boolean;
+ /** The last non-empty rows of the child's screen, redacted (a PTY has no separate stderr). */
+ screenTail: string;
+ pane: string | null;
+ sockPath: string | null;
+ /** The head of magmux's own stderr, redacted. */
+ magmuxStderr: string;
+ captureSource: SessionInfo["captureSource"];
+ turnSource: SessionInfo["turnSource"];
+ /** Bytes of assistant text before a file-delivered turn's task file was read. */
+ preambleBytes: number;
+ readCoverage: {
+ linesTotal: number;
+ linesReturned: number;
+ complete: boolean;
+ reads: number;
+ } | null;
+ claudeCodeVersion: string | null;
+ /** Deduplicated anomaly keys with counts (`illegal_transition:…`, `socket_reconnected ×2`, …). */
anomalies: readonly string[];
- /** The tail of the semantic-frame ring, oldest → newest. */
+ /** The tail of the session's own event records, oldest → newest. */
recentEvents: readonly DiagnosticEvent[];
- /** How many frames the ring holds (it caps at `EVENT_RING_SIZE`). */
+ /** How many records the ring holds (it caps at `EVENT_RING_SIZE`). */
eventsTotal: number;
/** Raw JSONL records from the child proxy's upstream-error capture, newest last. */
upstreamErrors: readonly string[];
@@ -132,110 +164,72 @@ export interface SessionDiagnostics {
upstreamErrorLogPath: string;
}
+/** What `get_output` returns. */
+export interface SessionOutput {
+ sessionId: string;
+ state: SlotState;
+ output: string;
+ totalLines: number;
+ turnsCompleted: number;
+ tokensIn: number | null;
+ tokensOut: number | null;
+ elapsedSeconds: number;
+ /** Seconds since the last activity. Null when not live. */
+ idleSeconds: number | null;
+}
+
+/** What `send_input` returns (§4.2). */
+export type SendInputResult =
+ | { success: true; queued: number }
+ | {
+ success: false;
+ reason: "terminal" | "unknown_session" | "delivery_unavailable" | "unsupported_command";
+ state: SlotState | null;
+ };
+
interface SessionEntry {
info: SessionInfo;
- process: ChildProcess;
- /** Recovered assistant PROSE, one line per entry. What `get_output` returns. */
+ /** null before the pane started, and for a session whose pane never started */
+ session: PaneSession | null;
+ /** Answer prose, one line per entry. What `get_output` returns. */
scrollback: ScrollbackBuffer;
- reducer: StreamJsonReducer;
- timeoutHandle: ReturnType<typeof setTimeout> | null;
- killHandle: ReturnType<typeof setTimeout> | null;
- /** Bounds how long finalisation waits for the stdio pipes after `exit`. */
- drainHandle: ReturnType<typeof setTimeout> | null;
- /** Removes a terminal session from the map once its retention window is up. */
- evictHandle: ReturnType<typeof setTimeout> | null;
- /**
- * Head + tail of the child's stderr, bounded (see `boundStderr`).
- *
- * A chatty child used to grow this string without limit for the entire life
- * of the MCP server, and the sessions holding it were never evicted.
- */
- stderr: string;
- /** True once `stderr` has been truncated, so the record says so. */
- stderrTruncated: boolean;
- /** Statefully decodes stdout/stderr so a multi-byte char may span chunks. */
- stdoutDecoder: StringDecoder;
- stderrDecoder: StringDecoder;
- outputLogStream: ReturnType<typeof createWriteStream> | null;
+ outputLogStream: WriteStream | null;
sessionDir: string;
+ cwd: string;
+ tokenFile: string;
eventLogPath: string;
/** Bytes already written to `events.jsonl`; the log stops at EVENT_LOG_LIMIT. */
eventLogBytes: number;
- /**
- * `<sessionDir>/upstream-errors.jsonl` — where the child proxy's own
- * `captureUpstreamError` writes non-ok upstream bodies. See `createSession`.
- */
upstreamErrorLogPath: string;
- /**
- * The last `EVENT_RING_SIZE` semantic frames, redacted and truncated.
- *
- * `events.jsonl` holds all of them, but it is capped at 4 MB and lives on
- * disk, and the whole point of Phase 3 is that a diagnosis must not require
- * reading the filesystem by hand. This is the in-API tail.
- */
+ /** The last `EVENT_RING_SIZE` event records, redacted and truncated. */
eventRing: DiagnosticEvent[];
- /** The directory the child was spawned in, before any realpath resolution. */
- cwd: string;
- /**
- * The `cwd + uuid` the current `info.transcriptPath` was derived from.
- *
- * `transcriptPathFor` does a `realpathSync`, and the refresh runs on every
- * `list_sessions` / `get_output` / `get_session`; this makes the syscall
- * happen only when one of its two inputs actually changed.
- */
- transcriptKey: string;
- /** The caller's timeout for this session, in seconds. Reported by getDiagnostics. */
- timeoutSeconds: number;
- /** Bytes and tail of recovered prose — the inputs `classifyRunOutput` measures. */
+ /** Bytes of answer prose appended (the `outputBytes` metric). */
proseBytes: number;
- proseTail: string;
- /**
- * Exit facts, recorded on `exit` and consumed by `finalize`.
- *
- * These are two different moments: `exit` fires BEFORE the stdout pipe
- * closes, so the verdict cannot be reached here. See `finalize`.
- */
- pendingExit: { code: number | null; signal: string | null; at: string } | null;
- openPipes: number;
- /** Finalisation runs exactly once, from whichever path gets there first. */
- finalized: boolean;
- /**
- * Close stdin on the first terminal `result`.
- *
- * True when `create_session` supplied a prompt (one-shot intent), false once
- * `send_input` is called (the caller has taken over). Without this a session
- * would never end on its own: stdin stays open by design, so the child sits
- * idle after answering until the hard timeout fires and the run is reported
- * as a failure it did not have.
- */
- autoCloseOnResult: boolean;
- stdinClosed: boolean;
- /** `<sessionDir>/waits.jsonl`. See `appendWait`. */
+ /** Turn indexes whose answer reached the scrollback. */
+ answeredTurns: Set<number>;
waitLogPath: string;
- /** Bytes already appended to `waits.jsonl`; the log stops at WAIT_LOG_LIMIT. */
waitLogBytes: number;
- /**
- * The `since` of the wait that is open now, or null. Kept so the `closed`
- * line repeats its `open` line's key exactly.
- */
+ /** The `since` of the wait that is open now, or null. */
waitSince: string | null;
+ /** The terminal transition was handled (records written). */
+ ended: boolean;
+ evictHandle: ReturnType<typeof setTimeout> | null;
+ /** The last channel event emitted; STARTING is the initial state, never a frame. */
+ lastEvent: ChannelEventType;
+ lastFrameTool: string | null;
+ lastFrameToolCount: number;
+ lastToolFrameAt: number;
+ lastLoggedTool: string | null;
+ assistantIdsLogged: number;
+ anomaliesLogged: Set<string>;
+ sendRejectedSeen: number;
+ /** Optional frame meta for the next frame (`prompt_not_read`, `send_rejected`). */
+ pendingMeta: Record<string, string>;
+ /** The question or permission text of the current block, for the frame content. */
+ blockText: string | null;
}
const DEFAULT_MAX_SESSIONS = 20;
-
-/**
- * How long to wait, after a child is confirmed dead, for its stdout pipe to
- * close so the session's recorded output is final.
- *
- * Bounded: the pipe can only stay open while some descendant still holds the
- * write end, and after a group SIGKILL that should be nobody. This exists so a
- * pathological case degrades into a slightly-stale read rather than a hang.
- *
- * Previously imported from `team-orchestrator`, which pointed the channel at
- * `team` for a constant that only the channel still uses — `team` no longer
- * terminates children, so it no longer drains them either.
- */
-const DRAIN_TIMEOUT_MS = 10_000;
const DEFAULT_SCROLLBACK = 2000;
const DEFAULT_TIMEOUT = 600;
const MAX_TIMEOUT = 3600;
@@ -256,36 +250,19 @@ export function normaliseTimeoutSeconds(raw: unknown): number {
if (typeof n !== "number" || !Number.isFinite(n)) return DEFAULT_TIMEOUT;
return Math.min(MAX_TIMEOUT, Math.max(1, Math.round(n)));
}
-const KILL_GRACE_MS = 5000;
/**
* How long a terminal session stays readable before it is dropped from the map.
- *
- * `maxSessions` bounds only ACTIVE sessions, so without this a long-lived MCP
- * server accumulates every finished session forever — each holding a 2 000-line
- * scrollback, a reducer and a stderr buffer. Long enough that an agent which
- * polls, gets `completed`, and then calls `get_output`/`get_diagnostics` always
- * finds the session; the artifacts on disk outlive it either way.
+ * Long enough that an agent which polls, sees `completed`, and then calls
+ * `get_output`/`get_diagnostics`/`capture_session` always finds the session; the
+ * artifacts on disk outlive it either way.
*/
const TERMINAL_RETENTION_MS = 30 * 60_000;
/** Hard ceiling on retained terminal sessions, whatever the retention window says. */
const MAX_TERMINAL_SESSIONS = 50;
-/**
- * Cap on the in-memory stderr buffer: this many bytes of HEAD plus the same of TAIL.
- *
- * Both ends, not just a tail: the diagnostic that motivated all of this — the
- * 81-byte `[claude-code:unrecognized_model]` line — is emitted at STARTUP, so a
- * pure tail buffer is exactly the shape that would have lost it, while the
- * death rattle that explains a late failure only exists at the end.
- */
-const STDERR_SIDE_LIMIT = 32 * 1024;
-
-/**
- * Cap on `events.jsonl`. ~1.3 MB is a long real session (measured), so this is
- * roughly 3× the worst observed case and still bounded on a pathological stream.
- */
+/** Cap on `events.jsonl`. */
const EVENT_LOG_LIMIT = 4 * 1024 * 1024;
/**
@@ -295,28 +272,14 @@ const EVENT_LOG_LIMIT = 4 * 1024 * 1024;
*/
const WAIT_LOG_LIMIT = 1024 * 1024;
-/**
- * How many semantic frames `get_diagnostics` can hand back, and how much of each.
- *
- * Bounded on both axes because this ring is held per session for the whole
- * retention window: 200 × 800 chars is ~160 KB at worst, ~8 MB across the
- * 50-session ceiling, and a single `tool_result` frame can be megabytes on its
- * own. A prefix is enough to identify a frame; `events.jsonl` has the whole of
- * it and `get_diagnostics` names that path.
- */
+/** How many event records `get_diagnostics` can hand back, and how much of each. */
const EVENT_RING_SIZE = 200;
const EVENT_PREVIEW_CHARS = 800;
/** Default number of ring events returned when the caller names no limit. */
const DEFAULT_EVENT_LIMIT = 40;
-/**
- * Bytes of `upstream-errors.jsonl` read back for diagnostics.
- *
- * Each record is bounded at ~2 KB by `MAX_CAPTURED_BODY_BYTES`, so this is the
- * last ~30 upstream failures — far more than any diagnosis needs, and a hard
- * bound on a file the child appends to on every failed request.
- */
+/** Bytes of `upstream-errors.jsonl` read back for diagnostics. */
const UPSTREAM_ERROR_TAIL_BYTES = 64 * 1024;
/**
@@ -325,6 +288,130 @@ const UPSTREAM_ERROR_TAIL_BYTES = 64 * 1024;
*/
const SPAWN_RECORD_SCHEMA = 1;
+/** RUNNING activities that are not a tool name (§8 B). */
+const NON_TOOL_ACTIVITY = new Set(["thinking", "background", "finishing"]);
+
+/** `meta.json` `status` for each terminal state (§20.1): EMPTY is a failure to the monitor. */
+const META_STATUS: Record<SlotState, string> = {
+ STARTING: "starting",
+ RUNNING: "running",
+ AWAITING_INPUT: "waiting_for_input",
+ AWAITING_PERMISSION: "awaiting_permission",
+ COMPLETED: "completed",
+ FAILED: "failed",
+ EMPTY: "failed",
+ CANCELLED: "cancelled",
+ TIMEOUT: "timeout",
+};
+
+/** A 10.4.0 `meta.json` `status` read back as a `SlotState` (the first-generation reader). */
+const STATE_OF_10_4_STATUS: Record<string, SlotState> = {
+ completed: "COMPLETED",
+ failed: "FAILED",
+ cancelled: "CANCELLED",
+ timeout: "TIMEOUT",
+};
+
+/**
+ * The channel event for a session state (architecture §3.4). Pure; the wire, the
+ * wait log's `to` and `get_diagnostics.event` all read it.
+ */
+export function channelEventFor(snap: { state: SlotState; activity: string | null }): {
+ event: ChannelEventType;
+ tool: string | null;
+} {
+ switch (snap.state) {
+ case "STARTING":
+ return { event: "starting", tool: null };
+ case "RUNNING": {
+ const a = snap.activity;
+ return a && !NON_TOOL_ACTIVITY.has(a)
+ ? { event: "tool_executing", tool: a }
+ : { event: "running", tool: null };
+ }
+ case "AWAITING_INPUT":
+ return { event: "waiting_for_input", tool: null };
+ case "AWAITING_PERMISSION":
+ return { event: "awaiting_permission", tool: null };
+ case "COMPLETED":
+ return { event: "completed", tool: null };
+ case "CANCELLED":
+ return { event: "cancelled", tool: null };
+ case "TIMEOUT":
+ return { event: "timeout", tool: null };
+ default:
+ return { event: "failed", tool: null };
+ }
+}
+
+/** One `list_sessions` row (§8 B): exactly the SlotRow keys plus the four session keys. */
+export function sessionRowOf(info: SessionInfo): SessionRow {
+ const terminal = isTerminalState(info.state);
+ return {
+ slot: info.sessionId,
+ model: info.model,
+ provider: info.provider,
+ state: info.state,
+ reason: info.state === "COMPLETED" || !terminal ? null : info.reason,
+ tokens_in: info.tokensIn,
+ tokens_out: info.tokensOut,
+ cost_usd: info.costUsd,
+ tool_calls: info.toolCalls,
+ turns_completed: info.turnsCompleted,
+ last_activity_at: info.lastActivityAt,
+ idle_seconds: terminal ? null : info.idleSeconds,
+ activity: terminal ? null : info.activity,
+ pane: info.pane,
+ session_id: info.sessionId,
+ started_at: info.startedAt,
+ completed_at: info.completedAt,
+ elapsed_seconds: info.elapsedSeconds,
+ };
+}
+
+/**
+ * The `meta.json` record (§20.1). Every 10.4.0 key under its 10.4.0 name and meaning —
+ * the magus monitor reads `status` (an unknown value reads as `failed`),
+ * `terminalReason`, `elapsedSeconds`, `turnsCompleted`, `toolCallCount`, `costUsd` and
+ * `exitCode` — plus additive keys. A `SessionInfo` key that would repeat a pinned key
+ * (`toolCalls`, `reason`, `panePid`) is written only under the pinned name.
+ */
+export function toMetaRecord(info: SessionInfo, cwd: string): Record<string, unknown> {
+ return {
+ sessionId: info.sessionId,
+ model: info.model,
+ spawnModel: info.spawnModel,
+ status: META_STATUS[info.state],
+ pid: info.panePid,
+ startedAt: info.startedAt,
+ completedAt: info.completedAt,
+ exitCode: info.exitCode,
+ turnsCompleted: info.turnsCompleted,
+ tokensUsed: (info.tokensIn ?? 0) + (info.tokensOut ?? 0),
+ elapsedSeconds: info.elapsedSeconds,
+ idleSeconds: info.idleSeconds,
+ costUsd: info.costUsd,
+ toolCallCount: info.toolCalls,
+ terminalReason: info.reason,
+ claudeSessionId: info.claudeSessionId,
+ ...(info.parentClaudeSessionId ? { parentClaudeSessionId: info.parentClaudeSessionId } : {}),
+ transcriptPath: info.transcriptPath,
+ // additive (pane generation)
+ state: info.state,
+ detail: info.detail,
+ tokensIn: info.tokensIn,
+ tokensOut: info.tokensOut,
+ lastActivityAt: info.lastActivityAt,
+ shape: info.shape,
+ pane: info.pane,
+ provider: info.provider,
+ captureSource: info.captureSource,
+ turnSource: info.turnSource,
+ timeoutSeconds: info.timeoutSeconds,
+ cwd,
+ };
+}
+
/**
* Write JSON so a reader never sees half of it: `<path>.tmp`, then rename over
* `<path>`. Throws on failure; callers that must not throw catch it themselves.
@@ -335,161 +422,58 @@ function writeJsonAtomic(path: string, value: unknown): void {
renameSync(tmp, path);
}
-/** Marker `recordStderr` leaves where it dropped the middle of the buffer. */
-const STDERR_TRUNCATION_MARKER = "[claudish] … stderr truncated to";
-
-/*
- * The stream-json child's output checks. Team moved onto interactive panes, whose
- * transcript replaces both, and took `classifyRunOutput`'s print-mode branch and
- * `meaningfulStderr` with it; this channel path keeps private copies until it moves onto
- * panes too, when these go with the pipe readers.
- */
-
-/** Claude Code prints API failures into its stdout and still exits 0. */
-const API_ERROR_RE = /\[API Error:\s*([^\]]{0,300})\]/i;
-/** Claude Code's print-mode background-task ceiling: partial output, exit 0. */
-const BG_CEILING_RE = /Background tasks still running after (\d+)s; terminating/i;
-/** stderr lines every healthy child emits (`unrecognized_model` is normal for a proxied model). */
-const BENIGN_STDERR_PATTERNS: readonly RegExp[] = [/^\s*\[claude-code:unrecognized_model\]/];
-
-/** The part of stderr worth persisting — everything that is not known boilerplate. */
-function meaningfulStderr(stderr: string): string {
- if (!stderr) return "";
- return stderr
- .split("\n")
- .filter((line) => line.trim().length > 0)
- .filter((line) => !BENIGN_STDERR_PATTERNS.some((re) => re.test(line)))
- .join("\n")
- .trim();
+/** The count of one anomaly key in a snapshot's `anomalies` (`key` or `key ×n`). */
+function anomalyCount(anomalies: readonly string[], key: string): number {
+ for (const a of anomalies) {
+ if (a === key) return 1;
+ if (a.startsWith(`${key} ×`)) return Number(a.slice(key.length + 2)) || 1;
+ }
+ return 0;
}
-/** "Exit 0 with nothing to show for it": an API error, the bg ceiling, or no prose. */
-function classifyStreamJsonProse(
- outputSize: number,
- proseTail: string,
- stderr: string
-): { reason: string; detail: string } | null {
- const apiError = API_ERROR_RE.exec(proseTail);
- if (apiError)
- return {
- reason: "api_error",
- detail: `Child exited 0 but stdout carries an API error: ${apiError[1]?.trim() || "unknown"}`,
- };
- const bg = BG_CEILING_RE.exec(stderr);
- if (bg)
- return {
- reason: "background_task_ceiling",
- detail: `Claude Code terminated the turn after ${bg[1]}s waiting on background tasks, flushing only partial output.`,
- };
- if (outputSize === 0 || (outputSize <= STDOUT_TAIL_LIMIT && proseTail.trim().length === 0))
- return {
- reason: "empty_output",
- detail: `Child exited 0 but produced no non-whitespace output (${outputSize} B).`,
- };
- return null;
+/** An anomaly entry without its `×n` count suffix. */
+function anomalyKey(a: string): string {
+ const at = a.lastIndexOf(" ×");
+ return at > 0 ? a.slice(0, at) : a;
}
-const TERMINAL_STATUSES: readonly SessionStatus[] = ["completed", "failed", "cancelled", "timeout"];
-
-/** Every `SessionStatus`, for validating one read back off disk. */
-const KNOWN_STATUSES: readonly SessionStatus[] = [
- "starting",
- "running",
- "tool_executing",
- "waiting_for_input",
- "finishing",
- "completed",
- "failed",
- "cancelled",
- "timeout",
-];
-
// ─── Disk fallback ───────────────────────────────────────────────────────────
//
// Sessions live in a Map, and two things legitimately remove them from it: the
-// 30-minute / 50-session retention policy, and the MCP server restarting. Before
-// this, either one made a finished session unreachable — `getOutput`,
-// `getSession` and `getDiagnostics` all threw `Session <id> not found` — while
-// its entire record sat complete under `<sessionsDir>/<id>/`. Measured on a real
-// session (probes/probe-gaps.ts §G-B): `meta.json` on disk with
-// `status=cancelled tokens=37076`, alongside `output.log`, `stderr.log`,
-// `events.jsonl`, `tokens.json` and `prompt.md` — and a fresh manager throwing.
-//
-// That is the same defect this whole feature exists to remove: the answer on
-// disk while the API says there is nothing. Worse here, because the point of the
-// diagnostics is that a failure which ALREADY HAPPENED can be explained without
-// re-running it — and a restart is exactly what tends to follow a crash.
-//
-// So the three READERS fall back to disk. The two MUTATORS never do; see
-// `liveEntry`.
+// 30-minute / 50-session retention policy, and the MCP server restarting. The three
+// READERS (`getSession`, `getOutput`, `getDiagnostics`) fall back to the session's
+// directory; the MUTATORS never do (`liveEntry`). The reader reads both generations of
+// `meta.json`: 10.4.0's (`status`, no `state`) and the pane one (`state` beside it).
/**
- * What a session id may contain, given that it is about to become a path
- * segment.
- *
- * `createSession` mints `randomUUID().slice(0, 8)` — 8 lowercase hex — but these
- * readers take the id from an MCP caller, so on the read path it is untrusted
- * input heading for `join(sessionsDir, id)` and an `open`. The allowlist admits
- * no `/`, no `\`, no NUL and no leading dot, which is what makes `..`,
- * `../../etc/passwd` and an absolute path unrepresentable rather than merely
- * unlikely. Wider than 8 hex on purpose: an id minted by an older or future
- * build must still resolve.
+ * What a session id may contain, given that it is about to become a path segment.
+ * No `/`, no `\`, no NUL and no leading dot, which makes `..`, `../../etc/passwd` and an
+ * absolute path unrepresentable rather than merely unlikely.
*/
const SESSION_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
-/**
- * Refuse to parse a `meta.json` larger than this.
- *
- * It is a serialised `SessionInfo` — well under 1 KB — so anything at this size
- * is not the file we wrote, and `JSON.parse` of an arbitrarily large string is
- * not something the error path should be doing.
- */
+/** Refuse to parse a `meta.json` larger than this; it is not the file we wrote. */
const META_READ_LIMIT = 1024 * 1024;
-/**
- * Bytes of `output.log` read back, before the same 2 000-line scrollback bound
- * the live path applies.
- *
- * The live `getOutput` answers from a `ScrollbackBuffer` that holds at most
- * `scrollbackCapacity` lines (~200 KB by default), so this is the byte window
- * that comfortably contains that many lines of prose. The recovered text is then
- * pushed through a real `ScrollbackBuffer` so the two paths cannot disagree
- * about ANSI stripping, line splitting or `tailLines`.
- */
+/** Bytes of `output.log` read back, before the same scrollback bound the live path applies. */
const OUTPUT_TAIL_BYTES = 256 * 1024;
-/**
- * Bytes of `stderr.log` read back.
- *
- * `recordStderr` bounds what it writes at `STDERR_SIDE_LIMIT` per end (64 KB
- * plus a marker), so this window reads a file THIS manager wrote in full —
- * head included. That matters: the 81-byte `[claude-code:unrecognized_model]`
- * line which motivated the diagnostics is emitted at STARTUP, and a window that
- * only reached the tail is precisely the shape that would lose it.
- */
-const STDERR_READ_BYTES = 256 * 1024;
-
-/**
- * Bytes of `events.jsonl` read back.
- *
- * That file is capped at `EVENT_LOG_LIMIT` (4 MB) and a single `tool_result`
- * frame can be megabytes on its own, so it is read as a bounded TAIL and never
- * whole: a 4 MB event log must not become a 4 MB read, let alone a 4 MB MCP
- * response. At the 200-frame ceiling this window still averages 2.6 KB a frame.
- * `eventLogPath` is returned so the full record stays one `cat` away.
- */
+/** Bytes of `events.jsonl` read back: a bounded TAIL, never the whole file. */
const EVENT_TAIL_BYTES = 512 * 1024;
+/** Bytes of `screen.txt` read back. */
+const SCREEN_READ_BYTES = 64 * 1024;
+
/**
- * `terminalReason` for a session whose directory exists but whose `meta.json`
- * does not, or will not parse.
- *
- * `meta.json` is written by `writeArtifacts`, at the very end of `finalize`, so
- * its absence means the process died before reaching a verdict — SIGKILL, a
- * panic, a full disk, or a write caught half-way. Distinctive enough to grep.
+ * The detail of a session whose directory exists but whose `meta.json` does not, or
+ * will not parse: the process died before reaching a verdict (SIGKILL, a panic, a full
+ * disk). Distinctive enough to grep.
*/
const NO_TERMINAL_RECORD = "claudish_no_terminal_record";
+/** How every annotation of OUR OWN in `output.log` begins (kept out of `outputBytes`). */
+const CLAUDISH_NOTE_PREFIX = "[claudish] ";
+
/** A session reconstructed from `<sessionsDir>/<id>/`. There is no process behind it. */
interface DiskRecord {
info: SessionInfo;
@@ -499,154 +483,8 @@ interface DiskRecord {
}
/**
- * The argv a channel child is spawned with.
- *
- * ORDER IS LOAD-BEARING, in two independent ways.
- *
- * 1. `--verbose` BEFORE `--quiet`. claudish consumes `--verbose`/`-v` as its OWN
- * log-verbosity flag (cli.ts:344, it sets quiet=false) and SEPARATELY forwards
- * a copy to the child `claude` (cli.ts:674), which hard-errors on
- * `--print --output-format stream-json` without it. Putting `--verbose` first
- * gets the forward while letting `--quiet` win claudish's own verbosity.
- * Reversed, every child narrates itself onto stderr. Same rule, same reason,
- * as team-orchestrator.ts:818-825.
- *
- * 2. `-p` must be followed by another FLAG. Unknown flags pass through to
- * `claude` with their value, and the value rule is "the next token, if it does
- * not start with `-`" (cli.ts:647). `-p` takes no value, so a non-flag after
- * it would be swallowed. It also must be present at all: without it and
- * without `--stdin`, cli.ts:667 sees no positional prompt and launches the
- * interactive picker.
- *
- * `--session-id <uuid>` is last of the base args on purpose: it consumes exactly
- * one token, so whatever the caller appends afterwards is parsed fresh.
- */
-export function buildChannelSpawnArgs(opts: {
- model: string;
- claudeSessionId: string;
- claudishFlags?: readonly string[];
-}): string[] {
- return [
- "--model",
- opts.model,
- "-y",
- "--verbose",
- "--quiet",
- "-p",
- "--output-format",
- "stream-json",
- "--input-format",
- "stream-json",
- "--include-partial-messages",
- "--include-hook-events",
- "--replay-user-messages",
- "--session-id",
- opts.claudeSessionId,
- ...(opts.claudishFlags ?? []),
- ];
-}
-
-/**
- * Every other SPELLING claudish's own parser accepts for a flag the transport
- * sets. Sourced from `cli.ts`'s arg loop, not guessed:
- *
- * `--model` / `-m` cli.ts:263
- * `--auto-approve` / `-y` cli.ts:310
- * `--quiet` / `-q` cli.ts:338
- * `--verbose` / `-v` cli.ts:340
- *
- * `-v` is the one that mattered. The guard was built to stop a caller's
- * `--verbose` landing after our `--quiet` and flipping claudish's own log
- * verbosity (every child then narrates onto stderr) — and `-v` walked straight
- * past it into exactly that regression. `-p` is `claude`'s short `--print`; it
- * is not a claudish flag, so it is listed the other way round.
- */
-const RESERVED_FLAG_ALIASES: Record<string, readonly string[]> = {
- "--model": ["-m"],
- "-y": ["--auto-approve"],
- "--quiet": ["-q"],
- "--verbose": ["-v"],
- "-p": ["--print"],
-};
-
-/**
- * Flags the transport does not pass but cannot survive.
- *
- * `--stdin` makes claudish consume fd 0 and wait for EOF, while this manager
- * holds stdin open waiting for a `result` — a circular wait that ends only at
- * the timeout.
- */
-const TRANSPORT_BREAKING_FLAGS: readonly string[] = ["--stdin"];
-
-/**
- * Flags the transport owns. A caller-supplied duplicate is REJECTED, not merged.
- *
- * DERIVED from `buildChannelSpawnArgs` rather than hand-listed, because the
- * hand-listed version drifted the moment it existed: it had `--verbose` but not
- * `-v`, and no `--model` at all, so the two most consequential collisions were
- * both accepted. Anything added to the spawn argv is now reserved automatically.
- *
- * `create_session`'s `claude_flags` are appended verbatim after the base args,
- * and the shared builder that produces them dedupes `--agent` against itself and
- * nothing else — it knows nothing about any one spawn site's base args. Claude
- * Code's precedence for a duplicate is UNMEASURED.
- *
- * Deliberately local rather than in the shared builder: the reserved set is a
- * property of THIS transport (team reserves fewer), and a shared denylist would
- * be wrong for both.
- */
-const RESERVED_CHILD_FLAGS: readonly string[] = (() => {
- const reserved = new Set<string>(TRANSPORT_BREAKING_FLAGS);
- for (const token of buildChannelSpawnArgs({ model: "MODEL", claudeSessionId: "SESSION-ID" })) {
- if (!token.startsWith("-")) continue;
- reserved.add(token);
- for (const alias of RESERVED_FLAG_ALIASES[token] ?? []) reserved.add(alias);
- }
- return [...reserved];
-})();
-
-/**
- * Reject caller flags that collide with the transport's own.
- *
- * Loud on purpose. Silently appending the duplicate is the failure mode this
- * codebase keeps paying for — the effect shows up three layers away as garbled
- * output or a dropped answer, with nothing pointing back at the flag.
- *
- * The match is EXACT-TOKEN, never a prefix. `--print-argv`, `--model-opus`,
- * `--model-sonnet`, `--agents` (custom agent DEFINITIONS, unrelated to
- * `--agent`) are all real flags that a `startsWith` guard would eat. The
- * neighbouring `buildChildClaudeFlags` shipped both halves of that mistake at
- * once — too narrow on `--agent=value`, too wide on `--agents`.
- */
-export function assertNoReservedFlags(flags: readonly string[] | undefined): void {
- if (!flags?.length) return;
- for (const flag of flags) {
- // Tolerate `--flag=value`; the collision is on the flag, not the spelling.
- // Long form only — `-v=x` is not a spelling claudish's parser accepts.
- const name =
- flag.startsWith("--") && flag.includes("=") ? flag.slice(0, flag.indexOf("=")) : flag;
- if (RESERVED_CHILD_FLAGS.includes(name)) {
- throw new Error(
- `flag "${name}" is set by the channel transport and cannot be overridden. ` +
- "Channel sessions run the child over bidirectional stream-json; " +
- `${RESERVED_CHILD_FLAGS.join(", ")} are all part of that wire contract.`
- );
- }
- }
-}
-
-/* `decodeChunk` moved to ../stdio-decode.ts — `team` supervises a claudish child
- over a pipe too, and was reading its children with `chunk.toString()`. */
-
-/**
- * The last `maxBytes` of a file, as text, plus whether the read began mid-file.
- *
- * A positioned tail read, never a whole-file read: every caller reads a log
- * whose size is not ours to bound — `upstream-errors.jsonl` is written by the
- * CHILD on every failed request, and `events.jsonl` is capped at 4 MB.
- *
- * Returns null for a file that does not exist, which is the ordinary case for
- * all of them. Never throws: this is the error path.
+ * The last `maxBytes` of a file, as text, plus whether the read began mid-file. A
+ * positioned tail read, never a whole-file read. Null for an absent file. Never throws.
*/
function readTailText(path: string, maxBytes: number): { text: string; truncated: boolean } | null {
let fd: number | null = null;
@@ -660,7 +498,6 @@ function readTailText(path: string, maxBytes: number): { text: string; truncated
readSync(fd, buf, 0, length, start);
return { text: buf.toString("utf-8"), truncated: start > 0 };
} catch {
- // Absent, unreadable, or racing a write. Diagnostics are never load-bearing.
return null;
} finally {
if (fd !== null) {
@@ -673,17 +510,11 @@ function readTailText(path: string, maxBytes: number): { text: string; truncated
}
}
-/**
- * The last `maxBytes` of a JSONL file, split into whole lines.
- *
- * A first partial line is dropped rather than returned mangled. `[]` for a file
- * that does not exist.
- */
+/** The last `maxBytes` of a JSONL file, split into whole lines; a first partial line is dropped. */
function readTailLines(path: string, maxBytes: number): string[] {
const tail = readTailText(path, maxBytes);
if (!tail) return [];
const lines = tail.text.split("\n");
- // A read that began mid-file almost certainly began mid-line.
if (tail.truncated) lines.shift();
return lines.filter((line) => line.trim().length > 0);
}
@@ -697,14 +528,7 @@ function fileSize(path: string): number {
}
}
-/**
- * Parse a small JSON object off disk, or null.
- *
- * Every failure mode of the file is a null: absent, too large to be the file we
- * wrote, unreadable, invalid JSON, or valid JSON that is not an object. A
- * `meta.json` caught half-written by a SIGKILL is the case this exists for, and
- * it must degrade to a partial record rather than take the reader down.
- */
+/** Parse a small JSON object off disk, or null for every failure mode of the file. */
function readJsonObject(path: string, maxBytes: number): Record<string, unknown> | null {
try {
if (fileSize(path) > maxBytes) return null;
@@ -728,86 +552,54 @@ const optionalParent = (id: string | null | undefined): { parentClaudeSessionId?
const metaNumber = (v: unknown): number | null =>
typeof v === "number" && Number.isFinite(v) ? v : null;
-/** A `status` field that must name a real `SessionStatus`, or null. */
-const metaStatus = (v: unknown): SessionStatus | null =>
- typeof v === "string" && (KNOWN_STATUSES as readonly string[]).includes(v)
- ? (v as SessionStatus)
+const metaReason = (v: unknown): FailureReason | null =>
+ typeof v === "string" && (FAILURE_REASONS as readonly string[]).includes(v)
+ ? (v as FailureReason)
: null;
-/**
- * How every annotation `recordNote` writes into `output.log` begins.
- *
- * Coupled to the three `recordNote` call sites by convention, not by
- * construction — they format the string themselves. Only `diskProseBytes` reads
- * it, and only to keep our own explanations out of a metric that measures what
- * the CHILD produced; a note that stopped matching costs a slightly generous
- * byte count, nothing else.
- */
-const CLAUDISH_NOTE_PREFIX = "[claudish] ";
+/** The record's `type`, or null — the label of one `events.jsonl` line. */
+function labelForLine(line: string): string | null {
+ try {
+ const v = JSON.parse(line) as { type?: unknown; subtype?: unknown };
+ if (typeof v?.type !== "string") return null;
+ return typeof v.subtype === "string" ? `${v.type}:${v.subtype}` : v.type;
+ } catch {
+ return null;
+ }
+}
-/**
- * A tail window with its first, partial line removed.
- *
- * A read that began mid-file began mid-line. The exception is a window with no
- * newline at all: that is one enormous line, and dropping it would return
- * nothing at all rather than the end of the answer.
- */
+/** A tail window with its first, partial line removed (unless it is one enormous line). */
function dropLeadingFragment(tail: { text: string; truncated: boolean }): string {
if (!tail.truncated) return tail.text;
const firstBreak = tail.text.indexOf("\n");
return firstBreak === -1 ? tail.text : tail.text.slice(firstBreak + 1);
}
-/**
- * Tokens, cost and tool calls straight from a recovered session's `tokens.json`.
- *
- * The proxy's own file, and the fallback for the case `meta.json` cannot cover:
- * a run killed before `writeArtifacts` never got a `meta.json`, but the CHILD
- * wrote this one as it went, so every token it spent is still recorded. Same
- * authority as the live `refreshAccounting` — the proxy, never the child's own
- * `result.total_cost_usd`, which prices every model at Anthropic's rates.
- */
+/** Tokens, cost and tool calls from a recovered session's `tokens.json` (the proxy's own file). */
function diskAccounting(sessionDir: string): {
- tokensUsed: number;
- costUsd: number;
- toolCallCount: number;
+ tokensIn: number | null;
+ tokensOut: number | null;
+ costUsd: number | null;
+ toolCalls: number;
} {
const stats = readTokenStatsAt(join(sessionDir, "tokens.json"));
return {
- tokensUsed:
- (stats?.total_tokens ?? 0) || (stats?.input_tokens ?? 0) + (stats?.output_tokens ?? 0),
- costUsd: stats?.total_cost ?? 0,
- toolCallCount: Array.isArray(stats?.tool_calls)
+ tokensIn: stats?.billed_input_tokens ?? null,
+ tokensOut: stats?.output_tokens ?? null,
+ costUsd: typeof stats?.total_cost === "number" ? stats.total_cost : null,
+ toolCalls: Array.isArray(stats?.tool_calls)
? stats.tool_calls.reduce((sum, t) => sum + (typeof t.count === "number" ? t.count : 0), 0)
: 0,
};
}
-/**
- * Whole seconds between an ISO start and an epoch-ms end, never negative and
- * never `NaN` — an unparseable timestamp in a half-written `meta.json` degrades
- * to 0 rather than putting `null` on the wire.
- */
+/** Whole seconds between an ISO start and an epoch-ms end, never negative and never NaN. */
function elapsedSecondsBetween(startedAt: string, endedAtMs: number): number {
const seconds = Math.round((endedAtMs - Date.parse(startedAt)) / 1000);
return Number.isFinite(seconds) ? Math.max(0, seconds) : 0;
}
-/**
- * `outputBytes` for a recovered session: prose only, not the whole log.
- *
- * `outputBytes` exists to answer "did this session actually say anything?", and
- * the file it would naively be measured from also holds the `[claudish] …`
- * notes `finalize` writes to EXPLAIN a failure. Counting those makes a session
- * that answered with nothing report ~200 bytes — the diagnostic falsifying the
- * exact metric it exists to explain, which is a mistake `recordNote` already
- * documents having made once on the live path.
- *
- * So the notes are subtracted, whenever the whole log was read. When it was not
- * (a log past `OUTPUT_TAIL_BYTES`) the file size is returned instead: at that
- * size the notes are rounding error, and "did it answer at all" is already
- * settled. The subtraction is line-accurate to within newline accounting.
- */
+/** `outputBytes` for a recovered session: prose only, without our own `[claudish] …` notes. */
function diskProseBytes(
tail: { text: string; truncated: boolean } | null,
fileBytes: number
@@ -820,12 +612,23 @@ function diskProseBytes(
return Buffer.byteLength(prose, "utf-8");
}
-/** One turn, in the shape `--input-format stream-json` accepts. Measured, not guessed. */
-export function userFrame(text: string): string {
- return `${JSON.stringify({
- type: "user",
- message: { role: "user", content: [{ type: "text", text }] },
- })}\n`;
+/** The screen of a session whose pane never spawned (§8 D, amended r2). */
+function blankFinalCapture(): CaptureResult {
+ return {
+ seq: 0,
+ cols: 160,
+ rows: 50,
+ cursor: { x: 0, y: 0 },
+ lines: Array.from({ length: 50 }, () => ""),
+ final: true,
+ };
+}
+
+function unknownSession(sessionId: string): ContractErrorException {
+ return new ContractErrorException(
+ "unknown_session",
+ `no session ${JSON.stringify(sessionId)} is held by this server`
+ );
}
export class SessionManager {
@@ -833,10 +636,14 @@ export class SessionManager {
private maxSessions: number;
private scrollbackCapacity: number;
private sessionsDir: string;
- private stallSeconds: number | undefined;
private terminalRetentionMs: number;
private onStateChange?: (sessionId: string, event: ChannelEvent) => void;
- private sigintHandler: (() => void) | null = null;
+ private readonly parentEnv: Record<string, string | undefined>;
+ private readonly paneTimings: SessionManagerOptions["paneTimings"];
+ /** createSession calls past their checks whose entry is not in the map yet. */
+ private starting = 0;
+ /** Pane starts in flight; `shutdownAll` waits for them so no pane starts unsettled. */
+ private readonly pendingStarts = new Set<Promise<void>>();
private readonly _hostPid: number;
private readonly _launcherPid: number | undefined;
/** Team run record id → its `startedAt`, until `finishTeamRun` writes its end. */
@@ -859,8 +666,9 @@ export class SessionManager {
// `$HOME` before `os.homedir()`, by the rule the plugin monitor shares —
// see home-dir.ts. Diverging here makes every run invisible to it.
this.sessionsDir = options?.sessionsDir ?? sessionsDirFrom(process.env);
- this.stallSeconds = options?.stallSeconds;
this.onStateChange = options?.onStateChange;
+ this.parentEnv = options?.parentEnv ?? process.env;
+ this.paneTimings = options?.paneTimings;
}
/** The Claude Code process that launched this MCP server (`spawn.json` `hostPid`). */
@@ -968,7 +776,7 @@ export class SessionManager {
* one key per line.
*
* Deliberately NOT wrapped in a `try`: a run that cannot be recorded must not
- * run unrecorded, so a failure here fails the tool call before any child
+ * run unrecorded, so a failure here fails the tool call before any pane
* exists. `hostPid`, `launcherPid` (only when the launcher branch produced
* `hostPid`) and `mcpPid` — this process, the one that writes `meta.json` —
* are filled in here; the caller supplies the rest.
@@ -1002,39 +810,82 @@ export class SessionManager {
writeJsonAtomic(join(dir, "spawn.json"), body);
}
- /** Create and start a new session. Returns the session ID. */
- createSession(opts: SessionCreateOptions): string {
- if (this.activeSessions >= this.maxSessions) {
+ /**
+ * Create a session and start its pane. Resolves with the session id once the pane
+ * exists (no boot wait): the session is STARTING then.
+ *
+ * Order (§4.2, §20.1): the checks; the magmux check; the pane reservation (a refused
+ * session leaves no record); `prompt.md`; `spawn.json` (a failure releases the
+ * reservation and fails the call); then the pane. A pane that fails to start leaves a
+ * FAILED `pane_lost` session with a `meta.json`, and the call throws.
+ */
+ async createSession(opts: SessionCreateOptions): Promise<string> {
+ if (this.activeSessions + this.starting >= this.maxSessions) {
throw new Error(`Max sessions (${this.maxSessions}) reached`);
}
- assertNoReservedFlags(opts.claudishFlags);
-
- // A caller-supplied id must not be able to adopt or overwrite a live
- // session: `sessions.set` would replace the entry and orphan the running
- // child, which then bills on with nothing tracking it.
+ // A caller-supplied id must not be able to adopt or overwrite a live session.
if (opts.sessionId !== undefined && this.sessions.has(opts.sessionId)) {
throw new Error(`Session id already in use: ${opts.sessionId}`);
}
+ const flags = opts.claudishFlags ?? [];
+ const flagCheck = checkChildFlags(flags);
+ if (!flagCheck.ok) throw new Error(`invalid_args: ${flagCheck.message}`);
+ const readAvailable = !flagsRemoveRead(flags);
+ if (opts.prompt) {
+ const refusal = deliveryRefusal(opts.prompt, readAvailable);
+ if (refusal) throw new Error(`invalid_args: ${refusal}`);
+ }
+ const parentEnv = opts.parentEnv ?? this.parentEnv;
+
+ // Counted from here, so concurrent creates cannot overshoot maxSessions while they
+ // await the magmux check; from `sessions.set` on, the entry itself counts.
+ this.starting++;
+ let counted = true;
+ const uncount = () => {
+ if (counted) this.starting--;
+ counted = false;
+ };
+ try {
+ await assertMagmuxAvailable();
+ reservePanes(1, sockRootFor(parentEnv));
+ let entry: SessionEntry;
+ try {
+ entry = this.recordSession(opts);
+ } catch (err) {
+ releasePaneReservations(1);
+ throw err;
+ }
+ this.sessions.set(entry.info.sessionId, entry);
+ uncount();
+ const started = this.startPane(entry, opts, { flags, readAvailable, parentEnv });
+ const tracked = started.catch(() => undefined);
+ this.pendingStarts.add(tracked);
+ try {
+ await started;
+ } finally {
+ this.pendingStarts.delete(tracked);
+ }
+ return entry.info.sessionId;
+ } finally {
+ uncount();
+ }
+ }
+
+ /** `prompt.md`, `spawn.json` and the in-memory entry (STARTING). Throws before any pane. */
+ private recordSession(opts: SessionCreateOptions): SessionEntry {
const sessionId = opts.sessionId ?? randomUUID().slice(0, 8);
- // Minted here rather than discovered later: it is the child's transcript
- // filename under ~/.claude/projects/<slug>/, so knowing it BEFORE spawn
- // removes the cwd+mtime guessing a post-hoc search would need.
+ // Minted here: it is the child's transcript basename, known BEFORE the pane starts.
const claudeSessionId = randomUUID();
- // Normalised once, here, so `spawn.json` and the timer agree on one value
- // the plugin monitor accepts (an integer in 1..MAX_TIMEOUT).
+ // Normalised once, here, so `spawn.json`, `SessionInfo` and the pane's timer agree
+ // on one value the plugin monitor accepts (an integer in 1..MAX_TIMEOUT).
const timeout = normaliseTimeoutSeconds(opts.timeoutSeconds);
const startedAt = new Date().toISOString();
-
const sessionDir = opts.sessionDir ?? join(this.sessionsDir, sessionId);
mkdirSync(sessionDir, { recursive: true });
- if (opts.prompt) {
- writeFileSync(join(sessionDir, "prompt.md"), opts.prompt, "utf-8");
- }
+ if (opts.prompt) writeFileSync(join(sessionDir, "prompt.md"), opts.prompt, "utf-8");
- // The start-time record, BEFORE spawn and before every runtime file, so a
- // session never runs unrecorded and an observer of the sessions directory
- // can attribute it from its first moment (`hostPid`, and the calling
- // conversation when the caller proved it). Throws rather than continue.
+ // The start-time record, BEFORE the pane and before every runtime file, so a
+ // session never runs unrecorded. Throws rather than continue.
this.writeSpawnRecord(sessionDir, {
kind: "session",
sessionId,
@@ -1045,576 +896,616 @@ export class SessionManager {
claudeSessionId,
});
- // `spawnModel` is the parent-resolved explicit "provider@model" spec when
- // routing was pinned; absent means spawn the caller's string. `info.model`
- // below deliberately keeps `opts.model` — the pin is argv-only.
- const args = buildChannelSpawnArgs({
- model: opts.spawnModel ?? opts.model,
- claudeSessionId,
- claudishFlags: opts.claudishFlags,
- });
-
- const tokenFile = opts.tokenFile ?? join(sessionDir, "tokens.json");
- const eventLogPath = join(sessionDir, "events.jsonl");
- const upstreamErrorLogPath = join(sessionDir, "upstream-errors.jsonl");
const cwd = opts.cwd ?? process.cwd();
-
- // Resolved rather than hardcoded so a test harness can point child spawns at
- // the tree under test — without it the suite exercises whatever claudish is
- // INSTALLED. Unset in production, where the result is exactly "claudish".
- const spawnTarget = resolveClaudishSpawn();
- const proc = spawn(spawnTarget.command, [...spawnTarget.prefixArgs, ...args], {
- cwd,
- stdio: ["pipe", "pipe", "pipe"],
- shell: false,
- // Own process group, so cancel/timeout can signal the whole subtree.
- // `claudish` is a launcher → Bun CLI → `claude` → tools chain, and
- // signalling the pid we hold reaches only the launcher; the rest is
- // orphaned and keeps running (and billing). See process-tree.ts for the
- // measurement. This is what made `cancel_session`'s documented
- // "SIGTERM, then SIGKILL after 5 seconds" not actually stop the work.
- detached: KILL_PROCESS_GROUP,
- env: {
- ...process.env,
- // Point this child's token tracker at a path WE own. claudish IS the
- // proxy, so it sees every request and response: tokens, cost and tool
- // counts come from here rather than from parsing anything the child
- // prints. Without this line the child wrote to tokens-<its-own-port>.json
- // and nothing linked the two — which is why `tokensUsed` was hardcoded 0.
- [ENV.CLAUDISH_TOKEN_FILE]: tokenFile,
- // Un-no-op `captureUpstreamError` (handlers/composed-handler.ts).
- //
- // That capture is opt-in and this env var was never set for a channel
- // child, so it was a guaranteed no-op for every session here. Its own
- // comment says what that costs: `log()` only persists under `--debug`,
- // so the upstream body that distinguishes a retryable rate limit from a
- // hard quota wall is gone the moment it has been classified — and a
- // failure that already happened cannot be re-run with a flag. On the
- // two 900-second silent successes this is very likely the file that
- // would have ended the investigation.
- //
- // Set UNCONDITIONALLY, overriding any inherited value: the records carry
- // no session id, so a shared path interleaves up to 20 concurrent
- // sessions into one unattributable file — and `get_diagnostics`
- // publishes this exact path as the session's own.
- [UPSTREAM_ERROR_LOG_ENV]: upstreamErrorLogPath,
- },
- });
-
- const scrollback = new ScrollbackBuffer(this.scrollbackCapacity);
- const outputLogStream = createWriteStream(join(sessionDir, "output.log"));
-
- const entry: SessionEntry = {
+ const parentEnv = opts.parentEnv ?? this.parentEnv;
+ const spawnModel = opts.spawnModel ?? null;
+ const tokenFile = opts.tokenFile ?? join(sessionDir, "tokens.json");
+ return {
info: {
sessionId,
model: opts.model,
- spawnModel: opts.spawnModel ?? null,
- status: "starting",
- pid: proc.pid ?? null,
+ spawnModel,
+ provider: resolveProvider({ model: opts.model, spawnModel, tokenFile: null }),
+ state: "STARTING",
+ shape: opts.prompt ? "one-shot" : "interactive",
+ pane: null,
+ panePid: null,
startedAt,
- // Refreshed from the reducer at every read point, like elapsedSeconds.
- idleSeconds: 0,
completedAt: null,
exitCode: null,
turnsCompleted: 0,
- tokensUsed: 0,
+ tokensIn: null,
+ tokensOut: null,
+ costUsd: null,
+ toolCalls: 0,
+ lastActivityAt: null,
elapsedSeconds: 0,
- costUsd: 0,
- toolCallCount: 0,
- terminalReason: null,
+ idleSeconds: null,
+ activity: null,
+ reason: null,
+ detail: null,
+ pendingInputs: opts.prompt ? 1 : 0,
claudeSessionId,
+ transcriptPath: transcriptPathFor(cwd, claudeSessionId, projectsDir(parentEnv)),
// Present only when proven, so `meta.json` carries the key exactly when
// `spawn.json` does, with the same value.
...optionalParent(opts.parentClaudeSessionId),
- // Derived from the spawn cwd now, and re-derived from the child's own
- // `system:init.cwd` if that turns out to differ. See refreshTranscriptPath.
- transcriptPath: transcriptPathFor(cwd, claudeSessionId),
+ captureSource: null,
+ turnSource: "transcript",
+ timeoutSeconds: timeout,
},
- process: proc,
- scrollback,
- // Assigned immediately below; the reducer's callback needs `entry`.
- reducer: undefined as unknown as StreamJsonReducer,
- timeoutHandle: null,
- killHandle: null,
- drainHandle: null,
- evictHandle: null,
- stderr: "",
- stderrTruncated: false,
- stdoutDecoder: new StringDecoder("utf8"),
- stderrDecoder: new StringDecoder("utf8"),
- outputLogStream,
+ session: null,
+ scrollback: new ScrollbackBuffer(this.scrollbackCapacity),
+ outputLogStream: createWriteStream(join(sessionDir, "output.log")),
sessionDir,
- eventLogPath,
+ cwd,
+ tokenFile,
+ eventLogPath: join(sessionDir, "events.jsonl"),
eventLogBytes: 0,
- upstreamErrorLogPath,
+ upstreamErrorLogPath: join(sessionDir, "upstream-errors.jsonl"),
eventRing: [],
- cwd,
- transcriptKey: `${cwd} ${claudeSessionId}`,
- timeoutSeconds: timeout,
proseBytes: 0,
- proseTail: "",
- pendingExit: null,
- // stdout + stderr. Decremented on each pipe's `close`; finalisation waits
- // for zero (bounded) rather than trusting `exit`.
- openPipes: (proc.stdout ? 1 : 0) + (proc.stderr ? 1 : 0),
- finalized: false,
- autoCloseOnResult: Boolean(opts.prompt),
- stdinClosed: false,
+ answeredTurns: new Set(),
waitLogPath: join(sessionDir, "waits.jsonl"),
waitLogBytes: 0,
waitSince: null,
+ ended: false,
+ evictHandle: null,
+ lastEvent: "starting",
+ lastFrameTool: null,
+ lastFrameToolCount: 0,
+ lastToolFrameAt: 0,
+ lastLoggedTool: null,
+ assistantIdsLogged: 0,
+ anomaliesLogged: new Set(),
+ sendRejectedSeen: 0,
+ pendingMeta: {},
+ blockText: null,
};
+ }
- entry.reducer = new StreamJsonReducer({
- sessionId,
- stallSeconds: this.stallSeconds,
- keepUnrecognizedJson: opts.keepUnrecognizedJson,
- callback: (sid, data) => {
- const current = this.sessions.get(sid);
- if (!current) return;
-
- // One value, for the record and the wire alike. These used to diverge:
- // the timeout recorded `"timeout"` and emitted `"failed"`, because
- // EVENT_TO_TASK_STATUS had no `"timeout"` key and fell through to
- // `?? "working"` — reporting a dead session as alive. That key exists
- // now, so `ChannelEventType === SessionStatus` and the override is gone.
- current.info.status = data.newState;
- current.info.elapsedSeconds = this.getElapsed(current.info.startedAt);
-
- // Before the notification, so the wait line is on disk by the time
- // anyone hears of the transition.
- this.recordWaitTransition(current, data);
-
- this.onStateChange?.(sid, {
- type: data.newState,
- model: current.info.model,
- content: data.content ?? "",
- elapsedSeconds: current.info.elapsedSeconds,
- createdAt: current.info.startedAt,
- extraMeta: {
- ...(data.toolName ? { tool: data.toolName } : {}),
- ...(data.toolCount ? { tool_count: String(data.toolCount) } : {}),
- ...(data.stalled ? { stalled: "true" } : {}),
- },
- });
+ /** Start the entry's pane. A throw ends the record FAILED `pane_lost` and is rethrown. */
+ private async startPane(
+ entry: SessionEntry,
+ opts: SessionCreateOptions,
+ p: { flags: string[]; readAvailable: boolean; parentEnv: Record<string, string | undefined> }
+ ): Promise<void> {
+ const info = entry.info;
+ const paneOpts: PaneSessionOptions = {
+ kind: "s",
+ label: info.sessionId,
+ callerFlags: p.flags,
+ spawnModel: info.spawnModel ?? info.model,
+ cwd: entry.cwd,
+ sessionUuid: info.claudeSessionId,
+ transcriptPath: info.transcriptPath,
+ slotEnv: {
+ // The child's token tracker writes to a path WE own: tokens, cost and tool
+ // counts come from the proxy, never from anything the child prints.
+ [ENV.CLAUDISH_TOKEN_FILE]: entry.tokenFile,
+ // Per session, unconditionally: the records carry no session id, so a shared
+ // path would interleave concurrent sessions into one unattributable file.
+ [UPSTREAM_ERROR_LOG_ENV]: entry.upstreamErrorLogPath,
},
- onResult: (summary) => this.handleResult(sessionId, summary),
- onSemanticLine: (line, label) => this.recordEvent(entry, line, label),
- });
+ shape: info.shape,
+ ...(opts.prompt ? { initialPrompt: opts.prompt } : {}),
+ readAvailable: p.readAvailable,
+ decide: (turn) => this.decide(entry, turn),
+ onBlocked: (b) => this.onBlocked(entry, b),
+ timeoutMs: info.timeoutSeconds * 1000,
+ onChange: (snap) => this.onPaneChange(entry, snap),
+ onTransition: (t) => this.onPaneTransition(entry, t),
+ parentEnv: p.parentEnv,
+ ...(this.paneTimings ? { timings: this.paneTimings } : {}),
+ };
+ try {
+ entry.session = await startPaneSession(paneOpts);
+ } catch (err) {
+ this.failNeverSpawned(entry, err);
+ throw err;
+ }
+ if (!entry.ended) this.applySnapshot(entry, entry.session.snapshot());
+ }
- this.sessions.set(sessionId, entry);
-
- // stdout → reducer → prose → scrollback + output.log.
- //
- // The RAW NDJSON deliberately does not reach either: `get_output` returns
- // prose (that is a wire-compatibility requirement), and the delta frames
- // would evict all 2 000 scrollback lines within seconds. The structured
- // record lives in events.jsonl.
- //
- // Decoded through a StringDecoder, NOT `chunk.toString()`: a `data` chunk
- // ends wherever the pipe's read boundary fell, which can be mid-codepoint.
- // `toString` turns those dangling bytes into U+FFFD before the reducer's
- // line reassembly ever sees them, so any CJK character or emoji straddling
- // a read boundary was permanently mangled in the answer an agent reads.
- // The decoder holds the partial sequence until the rest of it arrives.
- proc.stdout?.on("data", (chunk: Buffer | string) => {
- const prose = entry.reducer.feed(decodeChunk(entry.stdoutDecoder, chunk));
- if (!prose) return;
- this.recordProse(entry, prose);
- });
+ /** A session whose pane never started: FAILED `pane_lost`, its records ended. */
+ private failNeverSpawned(entry: SessionEntry, err: unknown): void {
+ const msg = err instanceof Error ? err.message : String(err);
+ const at = new Date().toISOString();
+ const info = entry.info;
+ info.state = "FAILED";
+ info.reason = "pane_lost";
+ info.detail = `the pane never started: ${msg}`;
+ info.completedAt = at;
+ info.pendingInputs = 0;
+ info.elapsedSeconds = elapsedSecondsBetween(info.startedAt, Date.parse(at));
+ this.appendEvent(entry, { type: "state", from: "STARTING", to: "FAILED", at });
+ this.endRecords(entry, null);
+ this.emitFrame(entry, { state: "FAILED", activity: null, toolCalls: 0 });
+ }
- proc.stderr?.on("data", (chunk: Buffer | string) => {
- this.recordStderr(entry, decodeChunk(entry.stderrDecoder, chunk));
- });
+ // ─── Pane policy (D8) ──────────────────────────────────────────────────
+
+ /** The verdict of a settled turn: one-shot → classified; interactive → continue (D20). */
+ private decide(entry: SessionEntry, turn: SettledTurn): FinalVerdict | "continue" {
+ this.appendAnswer(entry, turn.index, turn.answer);
+ if (entry.info.shape === "one-shot") {
+ const v = classifyRunOutput({
+ answer: turn.answer,
+ apiError: turn.apiError,
+ stopReason: turn.stopReason,
+ promptRead: turn.delivery,
+ minOutputBytes: 0,
+ });
+ if (v) return { state: v.state, reason: v.reason, detail: v.detail };
+ return turn.stopReason === "max_tokens"
+ ? { state: "COMPLETED", detail: TRUNCATION_NOTE }
+ : { state: "COMPLETED" };
+ }
+ if (turn.apiError) {
+ const v = classifyRunOutput({ answer: turn.answer, apiError: turn.apiError });
+ return { state: "FAILED", reason: "api_error", detail: v?.detail ?? "API error" };
+ }
+ // An interactive turn whose task file was not fully read continues; the caller is
+ // told on the next frame (r2, X-M4).
+ if (turn.delivery.complete === false) {
+ entry.pendingMeta.prompt_not_read = "true";
+ this.appendEvent(entry, {
+ type: "anomaly",
+ key: "prompt_not_read",
+ turn: turn.index,
+ linesRead: turn.delivery.linesRead,
+ linesTotal: turn.delivery.linesTotal,
+ at: new Date().toISOString(),
+ });
+ }
+ return "continue";
+ }
- // `close` on each pipe is what finalisation actually waits for — see
- // `finalize`. Registered before the exit handler so the ordering is
- // explicit: whichever fires last does the work.
- proc.stdout?.on("close", () => this.onPipeClosed(sessionId));
- proc.stderr?.on("close", () => this.onPipeClosed(sessionId));
-
- // Without this, the first write to a child that has already exited raises an
- // unhandled 'error' on the stream and takes the whole MCP server with it —
- // and stdin now stays open across the session's entire life, so the window
- // is no longer a single write at startup.
- proc.stdin?.on("error", () => {
- entry.stdinClosed = true;
- });
+ /** A question or a permission dialog waits for `send_input` (the channel can answer). */
+ private onBlocked(entry: SessionEntry, b: PaneBlock): "wait" {
+ entry.blockText = b.text;
+ return "wait";
+ }
- // The prompt is the opening frame, not a positional argument. stdin stays
- // OPEN: that is what makes `send_input` real, and closing it here is what
- // used to make a promptless session hang until the timeout.
- this.openFirstTurn(entry, opts.prompt);
-
- proc.on("exit", (code, signal) => this.handleExit(sessionId, code, signal));
-
- // A spawn that never happened. This used to settle the reducer and stop —
- // leaking the output.log fd and both timers, and (because `exit` does not
- // follow a spawn `error`) writing no meta.json at all, so a session that
- // failed to start left NO on-disk record. Route it through the same
- // finalisation as every other ending.
- proc.on("error", (err) => {
- const current = this.sessions.get(sessionId);
- if (!current) return;
- current.pendingExit = { code: null, signal: null, at: new Date().toISOString() };
- current.info.completedAt = current.pendingExit.at;
- current.reducer.settle("failed", { content: `Spawn error: ${err.message}` });
- this.recordNote(current, `\n[claudish] spawn error: ${err.message}\n`);
- // Nothing to drain: the pipes of a process that never ran are already done.
- this.finalize(sessionId);
- });
+ // ─── Pane callbacks ────────────────────────────────────────────────────
- entry.timeoutHandle = setTimeout(() => {
- // `proc.killed` only means "a signal was SENT", so it is not a liveness
- // test — a child that ignored SIGTERM reads as killed while still
- // running. The exit/signal codes are the ones that mean "it is gone".
- if (proc.exitCode !== null || proc.signalCode !== null) return;
- signalProcessTree(proc, "SIGTERM");
- entry.killHandle = setTimeout(() => {
- try {
- signalProcessTree(proc, "SIGKILL");
- } catch {
- // Process may already be gone
- }
- }, KILL_GRACE_MS);
- entry.killHandle.unref?.();
-
- entry.info.completedAt = new Date().toISOString();
- // `"timeout"` in the record AND on the wire. It used to be laundered into
- // `"failed"` because EVENT_TO_TASK_STATUS could not project it; now it can
- // (→ `failed`, SEP-1686's nearest member), so a consumer watching only the
- // channel can finally tell "ran out of time" from "errored".
- entry.reducer.settle("timeout", { content: `Timeout after ${timeout}s` });
- }, timeout * 1000);
- entry.timeoutHandle.unref?.();
-
- this.setupSigint();
-
- return sessionId;
+ /** `onTransition`: every wire-state change, synchronously, before any frame. */
+ private onPaneTransition(
+ entry: SessionEntry,
+ t: { from: SlotState; to: SlotState; at: string; snap: PaneSnapshot }
+ ): void {
+ if (entry.ended) return;
+ const { snap } = t;
+ this.applySnapshot(entry, snap);
+ // Before the frame, so the wait line is on disk by the time anyone hears of it.
+ this.recordWaitTransition(entry, t.from, t.to, t.at, snap);
+ this.appendEvent(entry, { type: "state", from: t.from, to: t.to, at: t.at });
+ this.logPaneFacts(entry, snap);
+ if (!isWaiting(t.to)) entry.blockText = null;
+ if (isTerminalState(t.to)) this.onTerminal(entry, snap);
+ this.emitFrame(entry, snap);
}
- /**
- * Send a turn to a running session.
- *
- * Writes a stream-json `user` frame — the same shape `create_session`'s prompt
- * takes. Under the old `--stdin` topology this wrote raw text into a drain the
- * child had already finished reading, so it silently did nothing; this is the
- * first version that reaches the model.
- */
- sendInput(sessionId: string, text: string): boolean {
- const entry = this.liveEntry(sessionId);
- if (!entry) return false;
- if (TERMINAL_STATUSES.includes(entry.info.status)) return false;
- if (entry.stdinClosed) return false;
+ /** `onChange` (coalesced): activity and accounting changes within a state. */
+ private onPaneChange(entry: SessionEntry, snap: PaneSnapshot): void {
+ if (entry.ended) return;
+ this.applySnapshot(entry, snap);
+ this.logPaneFacts(entry, snap);
+ this.emitFrame(entry, snap);
+ }
- // The caller is driving now, so stop deciding when the session is finished.
- entry.autoCloseOnResult = false;
- return this.writeFrame(entry, text);
+ /** The terminal transition: answer, records and eviction, before the reap starts. */
+ private onTerminal(entry: SessionEntry, snap: PaneSnapshot): void {
+ const session = entry.session;
+ // A turn that ended without a settle (cancel, timeout, child exit) still shows the
+ // answer it had produced.
+ const index = snap.turnsCompleted + 1;
+ if (session && !entry.answeredTurns.has(index)) {
+ const partial = session.turnAnswer(index);
+ if (partial) this.appendAnswer(entry, index, partial);
+ }
+ if (snap.state !== "COMPLETED") {
+ const why = snap.reason ?? snap.state.toLowerCase();
+ this.recordNote(
+ entry,
+ `\n[claudish] ${snap.state} ${why}${snap.detail ? `: ${snap.detail}` : ""}\n`
+ );
+ }
+ const screen = session ? (session.capture() as CaptureResult).lines : null;
+ this.endRecords(entry, screen);
}
- /**
- * Get a session's recovered prose.
- *
- * Falls back to `<sessionsDir>/<id>/output.log` for a session that has left
- * the map — evicted, or lost to a restart. See the "Disk fallback" note above.
+ /** Close `output.log`, write `screen.txt` and `meta.json`, schedule eviction. Once. */
+ private endRecords(entry: SessionEntry, screenLines: string[] | null): void {
+ if (entry.ended) return;
+ entry.ended = true;
+ entry.outputLogStream?.end();
+ entry.outputLogStream = null;
+ if (screenLines) {
+ try {
+ const text = screenLines.join("\n").replace(/\s+$/, "");
+ writeFileSync(join(entry.sessionDir, "screen.txt"), `${redactSecrets(text)}\n`, "utf-8");
+ } catch {
+ /* diagnostics are never load-bearing */
+ }
+ }
+ // A wait can only be open here when the session ended in a step that also left the
+ // waiting state; recordWaitTransition closed it. Belt and braces for the never-
+ // spawned path, which has no transition.
+ if (entry.waitSince !== null) {
+ this.appendWait(entry, {
+ wait: "closed",
+ since: entry.waitSince,
+ at: entry.info.completedAt ?? new Date().toISOString(),
+ to: channelEventFor(entry.info).event,
+ });
+ entry.waitSince = null;
+ }
+ try {
+ writeFileSync(
+ join(entry.sessionDir, "meta.json"),
+ JSON.stringify(toMetaRecord(entry.info, entry.cwd), null, 2),
+ "utf-8"
+ );
+ } catch (err) {
+ process.stderr.write(
+ `[claudish] session ${entry.info.sessionId}: could not write meta.json: ` +
+ `${err instanceof Error ? err.message : String(err)}\n`
+ );
+ }
+ this.scheduleEviction(entry);
+ }
+
+ /** Copy a pane snapshot (and the proxy's token file) into the session's info. */
+ private applySnapshot(entry: SessionEntry, snap: PaneSnapshot): void {
+ const info = entry.info;
+ const acct: Accounting = mergeAccounting(snap, readTokenFileCached(entry.tokenFile), {
+ model: info.model,
+ spawnModel: info.spawnModel,
+ });
+ info.state = snap.state;
+ info.shape = snap.shape;
+ info.pane = snap.paneId || null;
+ info.panePid = snap.panePid;
+ info.completedAt = snap.endedAt;
+ info.exitCode = snap.exitCode;
+ info.turnsCompleted = snap.turnsCompleted;
+ info.tokensIn = acct.tokensIn;
+ info.tokensOut = acct.tokensOut;
+ info.costUsd = acct.costUsd;
+ info.toolCalls = acct.toolCalls;
+ info.provider = acct.provider ?? info.provider;
+ info.lastActivityAt = snap.lastActivityAt;
+ info.idleSeconds = snap.idleSeconds;
+ info.activity = snap.activity;
+ info.reason = snap.reason;
+ info.detail = snap.detail;
+ info.pendingInputs = snap.pendingInputs;
+ info.captureSource = snap.captureSource;
+ info.turnSource = snap.turnSource;
+ info.elapsedSeconds = elapsedSecondsBetween(
+ info.startedAt,
+ snap.endedAt ? Date.parse(snap.endedAt) : Date.now()
+ );
+ }
+
+ /** `events.jsonl`: new assistant message ids, tool changes, new anomalies. */
+ private logPaneFacts(entry: SessionEntry, snap: PaneSnapshot): void {
+ const at = new Date().toISOString();
+ const ids = entry.session?.assistantMessageIds() ?? [];
+ for (; entry.assistantIdsLogged < ids.length; entry.assistantIdsLogged++) {
+ this.appendEvent(entry, {
+ type: "assistant",
+ message: { id: ids[entry.assistantIdsLogged] },
+ at,
+ });
+ }
+ const { tool } = channelEventFor(snap);
+ if (tool && tool !== entry.lastLoggedTool)
+ this.appendEvent(entry, { type: "tool", name: tool, at });
+ entry.lastLoggedTool = tool;
+ for (const a of snap.anomalies) {
+ const key = anomalyKey(a);
+ if (entry.anomaliesLogged.has(key)) continue;
+ entry.anomaliesLogged.add(key);
+ this.appendEvent(entry, { type: "anomaly", key, at });
+ }
+ const rejected = anomalyCount(snap.anomalies, "send_not_accepted");
+ if (rejected > entry.sendRejectedSeen) {
+ entry.sendRejectedSeen = rejected;
+ entry.pendingMeta.send_rejected = "true";
+ }
+ }
+
+ /**
+ * One channel frame when the derived event changes, plus a coalesced `tool_executing`
+ * repeat (≤ 1 frame/s) when the tool or the tool count changes.
*/
- getOutput(
- sessionId: string,
- tailLines?: number
- ): {
- sessionId: string;
- status: SessionStatus;
- output: string;
- totalLines: number;
- turnsCompleted: number;
- tokensUsed: number;
- elapsedSeconds: number;
- /** Seconds since the child last emitted a frame. Null when not live. */
- idleSeconds: number | null;
- } {
- const entry = this.sessions.get(sessionId);
- if (!entry) return this.diskOutput(this.requireDiskRecord(sessionId), tailLines);
+ private emitFrame(
+ entry: SessionEntry,
+ snap: Pick<PaneSnapshot, "state" | "activity" | "toolCalls">
+ ): void {
+ const { event, tool } = channelEventFor(snap);
+ const now = Date.now();
+ const changed = event !== entry.lastEvent;
+ const toolRepeat =
+ !changed &&
+ event === "tool_executing" &&
+ (tool !== entry.lastFrameTool || snap.toolCalls !== entry.lastFrameToolCount) &&
+ now - entry.lastToolFrameAt >= 1000;
+ if (!changed && !toolRepeat) return;
+ entry.lastEvent = event;
+ if (event === "tool_executing") {
+ entry.lastFrameTool = tool;
+ entry.lastFrameToolCount = snap.toolCalls;
+ entry.lastToolFrameAt = now;
+ }
+ const extraMeta: Record<string, string> = {
+ ...(tool ? { tool, tool_count: String(snap.toolCalls) } : {}),
+ ...(snap.activity ? { activity: snap.activity } : {}),
+ ...entry.pendingMeta,
+ };
+ entry.pendingMeta = {};
+ try {
+ this.onStateChange?.(entry.info.sessionId, {
+ type: event,
+ model: entry.info.model,
+ content: this.frameContent(entry, event, tool),
+ elapsedSeconds: entry.info.elapsedSeconds,
+ createdAt: entry.info.startedAt,
+ extraMeta,
+ });
+ } catch {
+ // a notification consumer must never break the session
+ }
+ }
- entry.info.elapsedSeconds = this.getElapsed(entry.info.startedAt);
- entry.info.idleSeconds = entry.reducer ? Math.round(entry.reducer.idleMs / 1000) : null;
- this.refreshAccounting(entry);
+ private frameContent(entry: SessionEntry, event: ChannelEventType, tool: string | null): string {
+ const info = entry.info;
+ switch (event) {
+ case "running":
+ return "The turn is running.";
+ case "tool_executing":
+ return `Using ${tool}.`;
+ case "waiting_for_input":
+ return entry.blockText
+ ? `The model asked a question; send_input declines it and becomes the next prompt.\n${entry.blockText}`
+ : "The turn finished; waiting for send_input.";
+ case "awaiting_permission":
+ return `A permission dialog is open for ${info.activity ?? "a tool"}; send_input declines it and becomes the next prompt.${entry.blockText ? `\n${entry.blockText}` : ""}`;
+ case "completed":
+ return `Session completed (${info.turnsCompleted} turn(s)). Call get_output for the answer.`;
+ case "cancelled":
+ return "Session cancelled.";
+ case "timeout":
+ return `Timeout after ${info.timeoutSeconds}s; the pane was closed.`;
+ case "failed":
+ return `${info.state} ${info.reason ?? ""}${info.detail ? `: ${info.detail}` : ""}`.trim();
+ default:
+ return "";
+ }
+ }
- const lines = entry.scrollback.getLines(tailLines);
+ // ─── Public verbs ──────────────────────────────────────────────────────
+
+ /**
+ * Send a turn (D17): accepted in every non-terminal state and queued until the session
+ * is idle; during a question or a permission dialog the dialog is declined with Esc and
+ * the text becomes the next prompt. Any accepted send converts a one-shot session to
+ * interactive. A disk-recovered or unknown session answers `unknown_session`.
+ */
+ sendInput(sessionId: string, text: string): SendInputResult {
+ const entry = this.liveEntry(sessionId);
+ if (!entry) return { success: false, reason: "unknown_session", state: null };
+ if (!entry.session) return { success: false, reason: "terminal", state: entry.info.state };
+ const r = entry.session.send(text);
+ if (!r.ok) return { success: false, reason: r.reason, state: entry.session.snapshot().state };
+ entry.info.shape = "interactive";
+ this.applySnapshot(entry, entry.session.snapshot());
+ return { success: true, queued: r.queued };
+ }
+
+ /** Answer prose. Falls back to `<sessionsDir>/<id>/output.log` for a session not in memory. */
+ getOutput(sessionId: string, tailLines?: number): SessionOutput {
+ const entry = this.sessions.get(sessionId);
+ if (!entry) return this.diskOutput(this.requireDiskRecord(sessionId), tailLines);
+ this.refresh(entry);
+ const info = entry.info;
return {
sessionId,
- status: entry.info.status,
- output: lines.join("\n"),
+ state: info.state,
+ output: entry.scrollback.getLines(tailLines).join("\n"),
totalLines: entry.scrollback.totalLines,
- turnsCompleted: entry.info.turnsCompleted,
- tokensUsed: entry.info.tokensUsed,
- elapsedSeconds: entry.info.elapsedSeconds,
- idleSeconds: entry.info.idleSeconds,
+ turnsCompleted: info.turnsCompleted,
+ tokensIn: info.tokensIn,
+ tokensOut: info.tokensOut,
+ elapsedSeconds: info.elapsedSeconds,
+ idleSeconds: isTerminalState(info.state) ? null : info.idleSeconds,
};
}
/**
- * Everything a post-mortem needs, from the API rather than the filesystem.
- *
- * This method is the whole point of Phase 3. The two 15-minute silent
- * successes produced exactly one diagnostic between them — an 81-byte
- * `[claude-code:unrecognized_model]` line in `stderr.log` — and NO MCP tool
- * returned it. Diagnosing them meant reading `~/.claudish/sessions/<id>/` by
- * hand, which an agent consuming the MCP interface has no reason to know
- * exists. A failure that has already happened cannot be re-run with `--debug`,
- * so everything here is captured unconditionally, during the run.
+ * Everything a post-mortem needs, from the API rather than the filesystem. Falls back
+ * to the session directory for a session not in memory — the restart case is the one
+ * this exists for.
*/
getDiagnostics(sessionId: string, eventLimit = DEFAULT_EVENT_LIMIT): SessionDiagnostics {
const limit = Math.max(0, Math.min(Math.trunc(eventLimit) || 0, EVENT_RING_SIZE));
-
const entry = this.sessions.get(sessionId);
- // The restart case is the one this method exists for: a crash is followed by
- // a restart, and the crash is what you wanted explained.
if (!entry) return this.diskDiagnostics(this.requireDiskRecord(sessionId), limit);
-
- this.refreshAccounting(entry);
- entry.info.elapsedSeconds = this.getElapsed(entry.info.startedAt);
- entry.info.idleSeconds = entry.reducer ? Math.round(entry.reducer.idleMs / 1000) : null;
-
+ this.refresh(entry);
+ const info = entry.info;
return {
sessionId,
- status: entry.info.status,
- // The resolved chain, both halves. `model` is what the caller asked for
- // and is never rewritten; `spawnModel` is the pinned `provider@model` the
- // child was actually spawned with. Which provider served the request was
- // invisible from every tool before this, and it is the first thing a
- // routing failure needs.
- model: entry.info.model,
- spawnModel: entry.info.spawnModel,
- exitCode: entry.info.exitCode,
- terminalReason: entry.info.terminalReason,
- elapsedSeconds: entry.info.elapsedSeconds,
- // Silence, reported not judged. A long `Bash` emits nothing and is
- // working; only the caller knows if that is expected for the task it set.
- idleSeconds: entry.info.idleSeconds,
- timeoutSeconds: entry.timeoutSeconds,
- /** Recovered assistant PROSE, not raw stream bytes — see `recordProse`. */
+ state: info.state,
+ event: channelEventFor(info).event,
+ reason: isTerminalState(info.state) && info.state !== "COMPLETED" ? info.reason : null,
+ detail: info.detail,
+ // The resolved chain, both halves: what the caller asked for, and the pinned
+ // `provider@model` the child was actually spawned with.
+ model: info.model,
+ spawnModel: info.spawnModel,
+ provider: info.provider,
+ shape: info.shape,
+ exitCode: info.exitCode,
+ // Silence, reported not judged.
+ idleSeconds: isTerminalState(info.state) ? null : info.idleSeconds,
+ elapsedSeconds: info.elapsedSeconds,
+ timeoutSeconds: info.timeoutSeconds,
outputBytes: entry.proseBytes,
- turnsCompleted: entry.info.turnsCompleted,
- tokensUsed: entry.info.tokensUsed,
- costUsd: entry.info.costUsd,
- toolCallCount: entry.info.toolCallCount,
- ...this.stderrForDiagnostics(entry),
- anomalies: entry.reducer.anomalies,
+ turnsCompleted: info.turnsCompleted,
+ tokensIn: info.tokensIn,
+ tokensOut: info.tokensOut,
+ costUsd: info.costUsd,
+ toolCalls: info.toolCalls,
+ pendingInputs: info.pendingInputs,
+ pane: info.pane,
+ captureSource: info.captureSource,
+ turnSource: info.turnSource,
+ ...this.paneFacts(entry),
recentEvents: limit === 0 ? [] : entry.eventRing.slice(-limit),
eventsTotal: entry.eventRing.length,
upstreamErrors: readTailLines(entry.upstreamErrorLogPath, UPSTREAM_ERROR_TAIL_BYTES),
- claudeSessionId: entry.info.claudeSessionId,
- transcriptPath: entry.info.transcriptPath,
+ claudeSessionId: info.claudeSessionId,
+ transcriptPath: info.transcriptPath,
sessionDir: entry.sessionDir,
eventLogPath: entry.eventLogPath,
upstreamErrorLogPath: entry.upstreamErrorLogPath,
};
}
- /**
- * The stderr an agent should see, and an honest flag saying which rule made it.
- *
- * `meaningfulStderr` deliberately DROPS `[claude-code:unrecognized_model]` as
- * benign boilerplate — normal for any proxied model, and noise on a healthy
- * run. But that single line was the ENTIRE content of the incident this tool
- * exists to explain, so filtering a failure would return an empty string for
- * the one case that motivated the work.
- *
- * team already draws this distinction and states it at
- * `team-orchestrator.ts:447-455`: the filter decides whether to write a
- * SUCCESS-path log, while a genuine failure persists the RAW stderr, because
- * there the boilerplate IS the context. Same rule here — filtered only for a
- * clean `completed`, raw for everything else.
- *
- * Redacted either way. `entry.stderr` is the unredacted in-memory buffer (only
- * the on-disk `stderr.log` was redacted before), so returning it verbatim
- * would hand provider key material straight into an agent's context.
- */
- private stderrForDiagnostics(entry: SessionEntry): {
- stderrTail: string;
- stderrFiltered: boolean;
- stderrTruncated: boolean;
- } {
- const filtered = entry.info.status === "completed";
- const source = filtered ? meaningfulStderr(entry.stderr) : entry.stderr;
+ /** The `get_diagnostics` fields only a pane can answer; their "no pane" values otherwise. */
+ private paneFacts(
+ entry: SessionEntry
+ ): Pick<
+ SessionDiagnostics,
+ | "phase"
+ | "connected"
+ | "screenTail"
+ | "sockPath"
+ | "magmuxStderr"
+ | "preambleBytes"
+ | "readCoverage"
+ | "claudeCodeVersion"
+ | "anomalies"
+ > {
+ const session = entry.session;
+ if (!session)
+ return {
+ phase: null,
+ connected: false,
+ screenTail: "",
+ sockPath: null,
+ magmuxStderr: "",
+ preambleBytes: 0,
+ readCoverage: null,
+ claudeCodeVersion: null,
+ anomalies: entry.info.detail ? [entry.info.detail] : [],
+ };
+ const snap = session.snapshot();
+ const pane = session.diagnostics();
return {
- stderrTail: redactSecrets(source).slice(-STDOUT_TAIL_LIMIT),
- stderrFiltered: filtered,
- stderrTruncated: entry.stderrTruncated,
+ phase: snap.phase,
+ connected: snap.connected,
+ screenTail: redactSecrets(snap.screenTail),
+ sockPath: session.sockPath,
+ magmuxStderr: redactSecrets(pane.magmuxStderr),
+ preambleBytes: pane.preambleBytes,
+ readCoverage: pane.readCoverage,
+ claudeCodeVersion: snap.claudeCodeVersion,
+ anomalies: snap.anomalies,
};
}
- /** Cancel a session. */
- cancelSession(sessionId: string): boolean {
+ /**
+ * Stop a session (§8 C): synchronous transition, asynchronous reap. Idempotent: a
+ * second call returns the same state with `changed:false`. Throws
+ * `ContractErrorException("unknown_session")` for a session this server does not hold.
+ */
+ cancelSession(sessionId: string): SessionCancelResult {
const entry = this.liveEntry(sessionId);
- if (!entry) return false;
- if (TERMINAL_STATUSES.includes(entry.info.status)) return false;
-
- if (entry.timeoutHandle) clearTimeout(entry.timeoutHandle);
- if (entry.killHandle) clearTimeout(entry.killHandle);
-
- entry.info.completedAt = new Date().toISOString();
- entry.reducer.settle("cancelled", { content: "Session cancelled" });
-
- // `killed` is "a signal was sent", not "it is gone" — see the timeout path.
- if (entry.process.exitCode === null && entry.process.signalCode === null) {
- signalProcessTree(entry.process, "SIGTERM");
- entry.killHandle = setTimeout(() => {
- try {
- signalProcessTree(entry.process, "SIGKILL");
- } catch {
- // Process may already be gone
- }
- }, KILL_GRACE_MS);
- entry.killHandle.unref?.();
- }
+ if (!entry) throw unknownSession(sessionId);
+ if (!entry.session) return { session_id: sessionId, state: entry.info.state, changed: false };
+ const r = entry.session.cancel();
+ return { session_id: sessionId, state: r.state, changed: r.changed };
+ }
- return true;
+ /**
+ * The session's screen (§8 D): a memory read. `CaptureUnchanged` when `sinceSeq`
+ * equals the current seq. A session whose pane never started answers a blank final
+ * screen. Throws `ContractErrorException("unknown_session")` once it is not retained.
+ */
+ captureSession(
+ sessionId: string,
+ sinceSeq?: number,
+ spans?: boolean
+ ): CaptureResult | CaptureUnchanged {
+ const entry = this.liveEntry(sessionId);
+ if (!entry) throw unknownSession(sessionId);
+ if (!entry.session)
+ return sinceSeq === 0 ? { unchanged: true, seq: 0, final: true } : blankFinalCapture();
+ return entry.session.capture(sinceSeq, { spans: spans === true });
}
/**
- * List sessions. IN-MEMORY ONLY — deliberately, and this one was measured.
- *
- * The three id-addressed readers fall back to `<sessionsDir>/<id>/`, so the
- * obvious symmetry would be for this to enumerate that directory. It does not,
- * for two reasons found by measuring the real one (9 946 session directories
- * on this machine; nothing prunes them, so it only grows):
- *
- * 1. COST. Session ids carry no ordering, so "the newest N" requires a `stat`
- * of every entry: 40 ms warm, 144 ms cold, synchronously, on the same
- * thread that pumps every live session's stdout — per call, on a tool an
- * agent POLLS.
- * 2. A BOUNDED scan does not fix that, it makes the answer wrong. `readdir`
- * order on APFS is uncorrelated with recency: the last 2 000 of those 9 946
- * dirents contained 9 of the 50 genuinely-newest sessions. A capped
- * enumeration would present an arbitrary 18 % sample as "the session list",
- * and a caller cannot tell a sampled-out session from one that never
- * existed. Returning a list that is honestly "what this process is holding"
- * beats returning a lottery.
- *
- * Nothing is lost that matters: recovery is id-addressed and O(1) — one open
- * of a known path — and the id is always in the caller's hand, because both
- * `create_session` and every channel notification carry it. Discovery by
- * browsing is a directory listing, not a diagnostic.
+ * Sessions this process holds. IN-MEMORY ONLY, deliberately: session ids carry no
+ * ordering, and the sessions directory only grows (≈ 10 000 entries measured), so a
+ * directory scan is either slow or a sample. Recovery is id-addressed and O(1).
*/
listSessions(includeCompleted = false): SessionInfo[] {
const sessions: SessionInfo[] = [];
for (const entry of this.sessions.values()) {
- const isTerminal = TERMINAL_STATUSES.includes(entry.info.status);
- if (!includeCompleted && isTerminal) continue;
- if (!isTerminal) {
- entry.info.elapsedSeconds = this.getElapsed(entry.info.startedAt);
- entry.info.idleSeconds = entry.reducer ? Math.round(entry.reducer.idleMs / 1000) : null;
- this.refreshAccounting(entry);
- }
+ this.refresh(entry);
+ if (!includeCompleted && isTerminalState(entry.info.state)) continue;
sessions.push({ ...entry.info });
}
return sessions;
}
- /**
- * Get a single session's info.
- *
- * Falls back to `<sessionsDir>/<id>/meta.json` for a session that has left the
- * map. See the "Disk fallback" note above.
- */
+ /** `list_sessions` rows (§8 B). */
+ listSessionRows(includeCompleted = false): SessionRow[] {
+ return this.listSessions(includeCompleted).map(sessionRowOf);
+ }
+
+ /** A single session's info; falls back to `<sessionsDir>/<id>/meta.json`. */
getSession(sessionId: string): SessionInfo {
const entry = this.sessions.get(sessionId);
if (!entry) return this.requireDiskRecord(sessionId).info;
- entry.info.elapsedSeconds = this.getElapsed(entry.info.startedAt);
- entry.info.idleSeconds = entry.reducer ? Math.round(entry.reducer.idleMs / 1000) : null;
- this.refreshAccounting(entry);
+ this.refresh(entry);
return { ...entry.info };
}
/**
- * Shut down all active sessions.
- *
- * Two things here were wrong in a way that orphaned billed work.
- *
- * 1. Liveness was `!proc.killed`. `signalProcessTree` sets `killed` the moment
- * a signal is SENT, so a child that ignored SIGTERM — the only kind that
- * needs escalating — read as already dead and was skipped entirely.
- * 2. The old code then cleared `entry.killHandle`, which is the pending
- * SIGKILL a `cancelSession` five seconds earlier had scheduled. Cancelling
- * the only escalation and skipping the kill left the detached process
- * GROUP running: it keeps working, keeps billing, and nothing is left
- * holding a handle to it.
- *
- * `terminateChildTree` is the escalation that replaces both: SIGTERM to the
- * group, wait, SIGKILL to the group, wait. The pending `killHandle` is only
- * cleared once that has actually run.
+ * Settle every live session CANCELLED (process shutdown): each closes its open wait
+ * (`to:"cancelled"`) and writes its `meta.json` on that transition, before this
+ * resolves. The pane registry's `reapAllPanes` does the killing; a test that wants the
+ * panes gone awaits its own no-orphan check.
*/
async shutdownAll(): Promise<void> {
- const promises: Promise<void>[] = [];
- for (const [sessionId, entry] of this.sessions) {
- // Every session's timers, whether or not its process is still alive.
- // Before this there were ZERO dispose() call sites and every session
- // leaked its timers for the life of the server.
- if (entry.timeoutHandle) clearTimeout(entry.timeoutHandle);
- entry.timeoutHandle = null;
- if (entry.drainHandle) clearTimeout(entry.drainHandle);
- entry.drainHandle = null;
- if (entry.evictHandle) clearTimeout(entry.evictHandle);
- entry.evictHandle = null;
-
- const alive = entry.process.exitCode === null && entry.process.signalCode === null;
- if (alive) {
- // Record the verdict BEFORE disposing, or the exit that follows finds a
- // disposed reducer, settles nothing, and writes a meta.json still
- // claiming the session was running.
- entry.info.completedAt ??= new Date().toISOString();
- entry.reducer.settle("cancelled", { content: "Server shut down" });
- promises.push(
- terminateChildTree(entry.process, KILL_GRACE_MS).then(() => {
- if (entry.killHandle) clearTimeout(entry.killHandle);
- entry.killHandle = null;
- // Writes meta.json and disposes. Idempotent: the child's own exit
- // may have raced us here.
- this.finalize(sessionId);
- })
- );
- continue;
- }
-
- if (entry.killHandle) {
- clearTimeout(entry.killHandle);
- entry.killHandle = null;
- }
- entry.reducer.dispose();
+ // A pane still starting would otherwise be skipped here and run on unsettled.
+ await Promise.all([...this.pendingStarts]);
+ const pending: Promise<unknown>[] = [];
+ for (const entry of this.sessions.values()) {
+ const session = entry.session;
+ if (!session) continue;
+ if (!isTerminalState(session.snapshot().state)) session.cancel();
+ pending.push(session.terminal.catch(() => undefined));
}
- await Promise.all(promises);
- this.cleanupSigint();
+ await Promise.all(pending);
}
// ─── Internal: the read-only disk fallback ───────────────────────────────
/**
- * The LIVE entry for a session, or undefined. Never consults the disk.
- *
- * This exists to make the read-only boundary a STRUCTURAL fact rather than an
- * incidental one. `sendInput` and `cancelSession` go through here and the
- * three readers do not, so "a disk-recovered session can never be driven" is
- * enforced by which accessor a method calls — visible at the call site, and
- * impossible to lose by someone later "unifying the lookup".
- *
- * A recovered record describes a process that is GONE. `sendInput` on it would
- * have no stdin to write to, and `cancelSession` no pid to signal — worse than
- * no-ops, they would have to invent a liveness that is not there. Both keep
- * returning `false`, which is exactly what they already returned for an
- * unknown id, so the contract does not change.
+ * The LIVE entry for a session, or undefined. Never consults the disk: a recovered
+ * record describes a process that is GONE, so `sendInput`, `cancelSession` and
+ * `captureSession` go through here and the three readers do not.
*/
private liveEntry(sessionId: string): SessionEntry | undefined {
return this.sessions.get(sessionId);
}
- /**
- * A disk record for `sessionId`, or the same `not found` the callers used to
- * throw unconditionally.
- *
- * The error is unchanged on purpose: a genuinely unknown id must still look
- * unknown, and only an id whose directory exists gets an answer.
- */
+ /** A disk record for `sessionId`, or the same `not found` an unknown id always got. */
private requireDiskRecord(sessionId: string): DiskRecord {
const record = this.loadDiskRecord(sessionId);
if (!record) throw new Error(`Session ${sessionId} not found`);
@@ -1622,14 +1513,8 @@ export class SessionManager {
}
/**
- * `<sessionsDir>/<id>`, or null when the id is not something we will join onto
- * a path.
- *
- * Two independent gates, because this is the one place untrusted input reaches
- * the filesystem. `SESSION_ID_RE` is the allowlist; the containment check
- * afterwards is the same belt-and-braces `validateSessionPath`
- * (team-orchestrator.ts) applies — it does not trust the regex to be the last
- * word on what `resolve` will do with a string.
+ * `<sessionsDir>/<id>`, or null when the id is not something we will join onto a
+ * path: the allowlist, then a containment check.
*/
private diskSessionDir(sessionId: string): string | null {
if (!SESSION_ID_RE.test(sessionId)) return null;
@@ -1641,12 +1526,8 @@ export class SessionManager {
}
/**
- * Rebuild a `SessionInfo` from `<sessionsDir>/<id>/`.
- *
- * Every field is validated, never coerced: a `meta.json` truncated mid-write
- * by the SIGKILL that ended the session is the case this is FOR, so a missing
- * or wrong-typed field falls back to a documented default and the record comes
- * back `partial`. Nothing here throws.
+ * Rebuild a `SessionInfo` from `<sessionsDir>/<id>/`, reading both `meta.json`
+ * generations. Every field is validated, never coerced; nothing here throws.
*/
private loadDiskRecord(sessionId: string): DiskRecord | null {
const sessionDir = this.diskSessionDir(sessionId);
@@ -1658,15 +1539,12 @@ export class SessionManager {
if (!stat.isDirectory()) return null;
dirMtimeMs = stat.mtimeMs;
} catch {
- // No directory: this id was never a session here. Same answer as before.
return null;
}
- // A team run's record lives in the same directory (`team-<8 hex>/`, written
- // for the plugin monitor) and its id passes SESSION_ID_RE, but it is not a
- // session: read as one it would come back a confident `model: "unknown"`
- // record. `spawn.json` exists from creation, so it is checked first; an
- // id-addressed tool then answers a team id exactly like an unknown id.
+ // A team run's record lives in the same directory (`team-<8 hex>/`) and its id
+ // passes SESSION_ID_RE, but it is not a session; an id-addressed tool answers a
+ // team id exactly like an unknown id.
const spawnRecord = readJsonObject(join(sessionDir, "spawn.json"), META_READ_LIMIT);
if (spawnRecord?.kind === "team") return null;
const meta = readJsonObject(join(sessionDir, "meta.json"), META_READ_LIMIT);
@@ -1674,176 +1552,117 @@ export class SessionManager {
const partial = meta === null;
const measured = diskAccounting(sessionDir);
- const startedAt = metaString(meta?.startedAt) ?? new Date(dirMtimeMs).toISOString();
- const completedAt = metaString(meta?.completedAt);
-
+ const transcriptPath = this.diskTranscriptPath(
+ meta,
+ metaString(meta?.claudeSessionId) ?? metaString(spawnRecord?.claudeSessionId) ?? ""
+ );
return {
sessionDir,
partial,
- info: {
- // The id we were ASKED for, never the one in the file: the directory
- // name is what addresses this record, and a mismatched `sessionId` in a
- // hand-edited meta.json must not be able to rename someone else's run.
- sessionId,
- model: metaString(meta?.model) ?? "unknown",
- spawnModel: metaString(meta?.spawnModel),
- status: metaStatus(meta?.status) ?? "failed",
- // A record restored from disk has no live reducer, so there is no
- // "since the last frame" to report. Null says unknown, not zero —
- // zero would read as "spoke just now" for a session that ended days ago.
- idleSeconds: null,
- // NEVER the pid from the file. It belonged to a process that is gone,
- // and pids are reused — a stale one names some unrelated live process,
- // which is a genuinely dangerous thing to hand back from a tool whose
- // neighbours send signals. Null says what is true: no process.
- pid: null,
- startedAt,
- completedAt,
- exitCode: metaNumber(meta?.exitCode),
- turnsCompleted: metaNumber(meta?.turnsCompleted) ?? 0,
- tokensUsed: metaNumber(meta?.tokensUsed) || measured.tokensUsed,
- // Wall time as it ENDED, not as it looks now. A live session reports
- // `now - startedAt`; doing that here would make a run that finished last
- // week report a week of elapsed time. `completedAt` when the session
- // reached a verdict, the directory's own mtime — the last write anything
- // made into it — when it did not.
- elapsedSeconds: elapsedSecondsBetween(
- startedAt,
- completedAt ? Date.parse(completedAt) : dirMtimeMs
- ),
- costUsd: metaNumber(meta?.costUsd) || measured.costUsd,
- toolCallCount: metaNumber(meta?.toolCallCount) || measured.toolCallCount,
- // A directory with no readable `meta.json` means the process died before
- // `writeArtifacts`, so there is no verdict to report — `failed` above
- // plus this marker say "ended without a record", not "ended in error".
- terminalReason: metaString(meta?.terminalReason) ?? (partial ? NO_TERMINAL_RECORD : null),
- claudeSessionId: metaString(meta?.claudeSessionId),
- // Absent unless the file carries a non-empty value: `""` is "not proven".
- ...optionalParent(metaString(meta?.parentClaudeSessionId)),
- transcriptPath: metaString(meta?.transcriptPath),
- },
+ info: diskInfo({ sessionId, meta, spawnRecord, measured, dirMtimeMs, transcriptPath }),
};
}
/**
- * `getOutput` for a recovered session, from `output.log`.
- *
- * Replayed through a real `ScrollbackBuffer` at the manager's own capacity
- * rather than split by hand, so the disk path cannot drift from the live one
- * on ANSI stripping, line splitting or `tailLines` — they are the same code.
- *
- * `totalLines` is the count within the recovered window, which is a LOWER
- * BOUND when the log exceeded `OUTPUT_TAIL_BYTES`. The live counter is "lines
- * ever written" and recovering that would mean reading a whole unbounded file
- * to produce one integer.
- *
- * One difference from the live path is not recoverable and is not a bug here.
- * `ScrollbackBuffer` is CHUNK-BOUNDARY SENSITIVE: `append("x\n")` records one
- * line, while `append("x")` then `append("\n")` records two — the second an
- * empty one. Live, the boundaries are wherever the reducer happened to emit
- * prose, so a one-line answer typically ends up with a phantom trailing empty
- * line and `output` gains a trailing "\n". Replaying the file in one append
- * does not reproduce that, because the boundaries were pipe read positions and
- * nothing records them. Measured: live `"turn1:DELTA\n"` / totalLines 2,
- * recovered `"turn1:DELTA"` / totalLines 1 — same answer, and the recovered
- * one is the cleaner of the two.
+ * The recorded transcript path, re-derived from `claudeSessionId` + the recorded cwd
+ * when the stored one does not exist (F1 window, §3.3). A 10.4.0 record carries no
+ * cwd, so its stored path is returned as is.
*/
- private diskOutput(
- record: DiskRecord,
- tailLines?: number
- ): {
- sessionId: string;
- status: SessionStatus;
- output: string;
- totalLines: number;
- turnsCompleted: number;
- tokensUsed: number;
- elapsedSeconds: number;
- idleSeconds: number | null;
- } {
+ private diskTranscriptPath(meta: Record<string, unknown> | null, uuid: string): string {
+ const stored = metaString(meta?.transcriptPath) ?? "";
+ const cwd = metaString(meta?.cwd);
+ if (stored && existsSync(stored)) return stored;
+ if (cwd && uuid) return transcriptPathFor(cwd, uuid, projectsDir(this.parentEnv));
+ return stored;
+ }
+
+ /** `getOutput` for a recovered session, replayed through a real `ScrollbackBuffer`. */
+ private diskOutput(record: DiskRecord, tailLines?: number): SessionOutput {
const tail = readTailText(join(record.sessionDir, "output.log"), OUTPUT_TAIL_BYTES);
const buffer = new ScrollbackBuffer(this.scrollbackCapacity);
if (tail?.text) buffer.append(dropLeadingFragment(tail));
-
- const lines = buffer.getLines(tailLines);
+ const info = record.info;
return {
- sessionId: record.info.sessionId,
- status: record.info.status,
- output: lines.join("\n"),
+ sessionId: info.sessionId,
+ state: info.state,
+ output: buffer.getLines(tailLines).join("\n"),
totalLines: buffer.totalLines,
- turnsCompleted: record.info.turnsCompleted,
- tokensUsed: record.info.tokensUsed,
- elapsedSeconds: record.info.elapsedSeconds,
- // Read from disk: the process is gone, so "since the last frame" is not a
- // question this record can answer. Null, never 0.
+ turnsCompleted: info.turnsCompleted,
+ tokensIn: info.tokensIn,
+ tokensOut: info.tokensOut,
+ elapsedSeconds: info.elapsedSeconds,
idleSeconds: null,
};
}
/**
- * `getDiagnostics` for a recovered session, from the four logs in its
- * directory.
- *
- * Three fields cannot be recovered and say so rather than guessing:
- *
- * `timeoutSeconds` — 0. The caller's timeout is not part of `SessionInfo`
- * and so was never written; `elapsedSeconds` still stands on its own.
- * `anomalies` — the reducer's tally of illegal transitions and
- * unparseable lines was running state and died with the process, so it
- * cannot be recovered. The one anomaly that CAN be observed from disk is
- * reported: a record with no readable `meta.json`. Reporting nothing at
- * all would let a reconstructed record pass for a complete one, which is
- * the more expensive mistake. `events.jsonl` still holds every frame the
- * reducer was judging.
- * `at` on each event — "". See `DiagnosticEvent`.
+ * `getDiagnostics` for a recovered session. What died with the process says so rather
+ * than guessing: no phase, no live connection, `at:""` on an event line without one,
+ * and the one anomaly that CAN be observed from disk — a record with no `meta.json`.
*/
private diskDiagnostics(record: DiskRecord, limit: number): SessionDiagnostics {
const { sessionDir, info } = record;
const eventLogPath = join(sessionDir, "events.jsonl");
const upstreamErrorLogPath = join(sessionDir, "upstream-errors.jsonl");
const outputLogPath = join(sessionDir, "output.log");
-
const events = readTailLines(eventLogPath, EVENT_TAIL_BYTES);
const outputTail = readTailText(outputLogPath, OUTPUT_TAIL_BYTES);
-
+ const screen = readTailText(join(sessionDir, "screen.txt"), SCREEN_READ_BYTES);
return {
sessionId: info.sessionId,
- status: info.status,
+ state: info.state,
+ event: channelEventFor(info).event,
+ reason: info.reason,
+ detail: info.detail,
model: info.model,
spawnModel: info.spawnModel,
+ provider: info.provider,
+ shape: info.shape,
+ phase: null,
exitCode: info.exitCode,
- terminalReason: info.terminalReason,
- elapsedSeconds: info.elapsedSeconds,
- // Recovered from disk — no live process to be idle. Null, never 0.
idleSeconds: null,
- timeoutSeconds: 0,
+ elapsedSeconds: info.elapsedSeconds,
+ timeoutSeconds: info.timeoutSeconds,
outputBytes: diskProseBytes(outputTail, fileSize(outputLogPath)),
turnsCompleted: info.turnsCompleted,
- tokensUsed: info.tokensUsed,
+ tokensIn: info.tokensIn,
+ tokensOut: info.tokensOut,
costUsd: info.costUsd,
- toolCallCount: info.toolCallCount,
- ...this.diskStderrForDiagnostics(record),
+ toolCalls: info.toolCalls,
+ pendingInputs: 0,
+ connected: false,
+ screenTail: redactSecrets(screen?.text ?? "").trimEnd(),
+ pane: info.pane,
+ sockPath: null,
+ magmuxStderr: "",
+ captureSource: info.captureSource,
+ turnSource: info.turnSource,
+ preambleBytes: 0,
+ readCoverage: null,
+ claudeCodeVersion: null,
anomalies: record.partial
? [
`no readable meta.json in ${sessionDir} — this record was reconstructed from ` +
- "the remaining artifacts, so status, exit code and timings are unknown. The " +
+ "the remaining artifacts, so state, exit code and timings are unknown. The " +
"session's process died before it could write a verdict.",
]
: [],
- // Bounded twice over: `limit` caps at EVENT_RING_SIZE the same as the live
- // path, and each preview at EVENT_PREVIEW_CHARS. A 4 MB event log cannot
- // become a 4 MB response, and did not even become a 4 MB read.
recentEvents:
limit === 0
? []
: events.slice(-limit).map((line) => {
- // Redacted on the READ path too. `events.jsonl` was redacted when
- // written, but a log from an older build was not, and this is
- // about to enter an agent's context either way.
+ // Redacted on the READ path too: a log from an older build was not.
const redacted = redactSecrets(line);
const truncated = redacted.length > EVENT_PREVIEW_CHARS;
+ let at = "";
+ try {
+ const parsed = JSON.parse(line) as { at?: unknown };
+ if (typeof parsed?.at === "string") at = parsed.at;
+ } catch {
+ /* not ours */
+ }
return {
- at: "",
+ at,
label: labelForLine(line),
preview: truncated ? redacted.slice(0, EVENT_PREVIEW_CHARS) : redacted,
truncated,
@@ -1851,62 +1670,36 @@ export class SessionManager {
}),
eventsTotal: events.length,
upstreamErrors: readTailLines(upstreamErrorLogPath, UPSTREAM_ERROR_TAIL_BYTES),
- claudeSessionId: info.claudeSessionId,
- transcriptPath: info.transcriptPath,
+ claudeSessionId: info.claudeSessionId || null,
+ transcriptPath: info.transcriptPath || null,
sessionDir,
eventLogPath,
upstreamErrorLogPath,
};
}
- /**
- * The disk twin of `stderrForDiagnostics`, and the same rule: filtered only
- * for a clean `completed`, raw for everything else, redacted either way.
- *
- * `STDERR_READ_BYTES` exceeds what `recordStderr` will ever write, so a
- * `stderr.log` this manager produced is read WHOLE — head included. The head
- * is the half that matters: `[claude-code:unrecognized_model]` is a startup
- * line, and it was the entire content of the incident these diagnostics exist
- * to explain.
- */
- private diskStderrForDiagnostics(record: DiskRecord): {
- stderrTail: string;
- stderrFiltered: boolean;
- stderrTruncated: boolean;
- } {
- const tail = readTailText(join(record.sessionDir, "stderr.log"), STDERR_READ_BYTES);
- const raw = tail?.text ?? "";
- const filtered = record.info.status === "completed";
- const source = filtered ? meaningfulStderr(raw) : raw;
- return {
- stderrTail: redactSecrets(source).slice(-STDOUT_TAIL_LIMIT),
- stderrFiltered: filtered,
- // Either end can have lost bytes: the in-memory buffer may have dropped
- // its middle before the file was written (the marker says so), or our own
- // window may not have reached the start of the file.
- stderrTruncated: (tail?.truncated ?? false) || raw.includes(STDERR_TRUNCATION_MARKER),
- };
- }
-
// ─── Internal ────────────────────────────────────────────────────────
- /** Append recovered prose to the scrollback, the tail, and output.log. */
- private recordProse(entry: SessionEntry, prose: string): void {
- entry.proseBytes += Buffer.byteLength(prose, "utf-8");
- entry.proseTail = (entry.proseTail + prose).slice(-STDOUT_TAIL_LIMIT);
- this.appendToOutput(entry, prose);
+ /** Refresh a live entry's info from its pane (a memory read plus a cached token file). */
+ private refresh(entry: SessionEntry): void {
+ if (entry.session && !entry.ended) this.applySnapshot(entry, entry.session.snapshot());
+ else if (!isTerminalState(entry.info.state))
+ entry.info.elapsedSeconds = elapsedSecondsBetween(entry.info.startedAt, Date.now());
+ }
+
+ /** A settled turn's answer → scrollback, `output.log` and `outputBytes`. Once per turn. */
+ private appendAnswer(entry: SessionEntry, index: number, answer: string): void {
+ if (entry.answeredTurns.has(index)) return;
+ entry.answeredTurns.add(index);
+ if (!answer) return;
+ const text = answer.endsWith("\n") ? answer : `${answer}\n`;
+ entry.proseBytes += Buffer.byteLength(answer, "utf-8");
+ this.appendToOutput(entry, text);
}
/**
- * Append a `[claudish] …` annotation of OUR OWN to the output.
- *
- * Deliberately not `recordProse`: `proseBytes` and `proseTail` are the measured
- * facts about what the CHILD produced. `classifyRunOutput` reads them to decide
- * whether a run had anything to show for itself, and `get_diagnostics` reports
- * `outputBytes` so a reader can see that a "completed" session answered with
- * nothing. Counting our own explanation of a failure as model output makes a
- * 0-byte session report 312 bytes — the diagnostic quietly falsifying the
- * metric it exists to explain. Measured; this is not hypothetical.
+ * Append a `[claudish] …` annotation of OUR OWN to the output. Not counted in
+ * `outputBytes`: that metric is what the CHILD produced.
*/
private recordNote(entry: SessionEntry, note: string): void {
this.appendToOutput(entry, note);
@@ -1917,60 +1710,23 @@ export class SessionManager {
entry.outputLogStream?.write(text);
}
- private writeFrame(entry: SessionEntry, text: string): boolean {
- if (entry.stdinClosed) return false;
- try {
- entry.process.stdin?.write(userFrame(text));
- // A turn is now outstanding, so the PREVIOUS turn's `result` stops
- // counting as evidence that this session finished. See beginTurn().
- entry.reducer.beginTurn();
- return true;
- } catch {
- entry.stdinClosed = true;
- return false;
- }
- }
-
- /**
- * One semantic frame: into the in-memory ring AND onto `events.jsonl`.
- *
- * Redacted ONCE, here, and the same redacted string is used for both — these
- * frames carry `user` turns and `tool_result` blocks (`.env` contents, command
- * output, provider errors that echo key material), and both destinations are
- * handed to an agent by `get_diagnostics`. Same rule and same reason as team's
- * error log (team-orchestrator.ts:1070).
- */
- private recordEvent(entry: SessionEntry, line: string, label: string | null): void {
+ /** One event record: into the in-memory ring AND onto `events.jsonl`, redacted once. */
+ private appendEvent(entry: SessionEntry, record: Record<string, unknown>): void {
+ const line = JSON.stringify(record);
const redacted = redactSecrets(line);
const truncated = redacted.length > EVENT_PREVIEW_CHARS;
-
- // The ring is filled even after `events.jsonl` has hit its cap: the last
- // frames before a session died are exactly the ones a post-mortem wants,
- // and a capped FILE must not also blind the API.
entry.eventRing.push({
- at: new Date().toISOString(),
- label,
+ at: typeof record.at === "string" ? record.at : new Date().toISOString(),
+ label: typeof record.type === "string" ? record.type : null,
preview: truncated ? redacted.slice(0, EVENT_PREVIEW_CHARS) : redacted,
truncated,
});
if (entry.eventRing.length > EVENT_RING_SIZE) entry.eventRing.shift();
-
- this.appendEventLog(entry, redacted);
- }
-
- /**
- * Append one already-redacted frame to `events.jsonl`.
- *
- * Bounded because a long interactive session or one large tool result would
- * otherwise grow the file without limit.
- */
- private appendEventLog(entry: SessionEntry, redactedLine: string): void {
if (entry.eventLogBytes >= EVENT_LOG_LIMIT) return;
- const payload = `${redactedLine}\n`;
+ const payload = `${redacted}\n`;
entry.eventLogBytes += Buffer.byteLength(payload, "utf-8");
const capped = entry.eventLogBytes >= EVENT_LOG_LIMIT;
try {
- // Best-effort: a full disk must not take the session down with it.
appendFileSync(
entry.eventLogPath,
capped
@@ -1983,130 +1739,47 @@ export class SessionManager {
}
/**
- * Accumulate the child's stderr, keeping the HEAD and the TAIL.
- *
- * Unbounded before: `entry.stderr += chunk` for the whole life of a session
- * that was itself never evicted. Keeping both ends rather than a tail is
- * deliberate — startup diagnostics (`[claude-code:unrecognized_model]`) are
- * at the head and the failure that killed a long run is at the end.
- */
- private recordStderr(entry: SessionEntry, chunk: string): void {
- if (!chunk) return;
- const combined = entry.stderr + chunk;
- if (combined.length <= STDERR_SIDE_LIMIT * 2) {
- entry.stderr = combined;
- return;
- }
- entry.stderrTruncated = true;
- entry.stderr =
- combined.slice(0, STDERR_SIDE_LIMIT) +
- `\n${STDERR_TRUNCATION_MARKER} ${STDERR_SIDE_LIMIT} bytes per end …\n` +
- combined.slice(-STDERR_SIDE_LIMIT);
- }
-
- /**
- * A turn ended; answer the reducer's question "does stdin stay open?".
- *
- * Called BEFORE the reducer changes state, so the answer decides it:
- *
- * - one-shot (`autoCloseOnResult`): close stdin now and answer
- * `"stdin-closed"`. The session moves to `finishing` and the child exits 0
- * on its own (measured — see §3.2 of the channel design).
- * - stdin already closed (the child broke the pipe, or exit raced us):
- * `"stdin-closed"` too — nothing can send it input any more.
- * - otherwise `"stdin-open"`: an interactive session now waits for
- * `send_input` in `waiting_for_input`.
- *
- * The bookkeeping runs first in every case, so a wait opened by this turn end
- * logs the turn count that includes it.
- */
- private handleResult(sessionId: string, summary: ResultSummary): TurnEnd {
- const entry = this.sessions.get(sessionId);
- // No entry means no stdin held open for anyone, so nothing can wait.
- if (!entry) return "stdin-closed";
-
- entry.info.turnsCompleted = summary.numTurns || entry.info.turnsCompleted;
- entry.info.terminalReason = summary.terminalReason;
-
- if (entry.stdinClosed) return "stdin-closed";
- if (!entry.autoCloseOnResult) return "stdin-open";
- entry.stdinClosed = true;
- try {
- entry.process.stdin?.end();
- } catch {
- /* the child may already be gone */
- }
- return "stdin-closed";
- }
-
- /**
- * Hand the child its opening turn, or record that the session waits for one.
- *
- * A promptless session waits for its first `send_input` from the moment it
- * exists, and says so (`starting → waiting_for_input`). Called after
- * `sessions.set`, so the reducer callback finds the entry and the wait is
- * logged.
- */
- private openFirstTurn(entry: SessionEntry, prompt: string | undefined): void {
- if (prompt) {
- this.writeFrame(entry, prompt);
- return;
- }
- entry.reducer.awaitInput();
- }
-
- /**
- * The wait log's two hooks: one `open` line on every transition INTO
- * `waiting_for_input`, one `closed` line on every transition OUT of it,
- * including into a terminal state.
- *
- * Runs in the same callback that changes the state, so a wait cannot happen
- * unrecorded while this process lives. `settle()` goes through `transition()`,
- * so cancel and timeout close an open wait, and `finalize` settles before
- * `writeArtifacts` — no `meta.json` ever sits beside an unclosed wait written
- * by a live process. Self-transitions never reach the callback unless
- * `repeat`, and no `repeat` caller targets `waiting_for_input`.
+ * The wait log's two hooks (§20.1): one `open` line when the wire state enters
+ * AWAITING_INPUT or AWAITING_PERMISSION, one `closed` line when it leaves both. Driven
+ * by the pane's `onTransition`, which reports the NET change of one step, so a turn
+ * that settles with a send queued (RUNNING → IDLE → ADMITTING) opens no wait. The
+ * phase table has no wait-to-wait edge, so `to` is never `waiting_for_input`.
*/
private recordWaitTransition(
entry: SessionEntry,
- data: { previousState: SessionStatus; newState: SessionStatus; timestamp: string }
+ from: SlotState,
+ to: SlotState,
+ at: string,
+ snap: PaneSnapshot
): void {
- const wasWaiting = data.previousState === "waiting_for_input";
- const isWaiting = data.newState === "waiting_for_input";
- if (!wasWaiting && isWaiting) {
- entry.waitSince = data.timestamp;
- this.appendWait(entry, {
- wait: "open",
- since: data.timestamp,
- turns: entry.info.turnsCompleted,
- });
+ const was = isWaiting(from);
+ const is = isWaiting(to);
+ if (!was && is) {
+ entry.waitSince = at;
+ this.appendWait(entry, { wait: "open", since: at, turns: snap.turnsCompleted });
return;
}
- if (wasWaiting && !isWaiting) {
+ if (was && !is) {
this.appendWait(entry, {
wait: "closed",
- since: entry.waitSince ?? data.timestamp,
- at: data.timestamp,
- to: data.newState,
+ since: entry.waitSince ?? at,
+ at,
+ to: channelEventFor(snap).event,
});
entry.waitSince = null;
}
}
/**
- * Append one line to `waits.jsonl`.
- *
- * Durable on purpose: a wait can open and close between two reads of any
- * observer, and an append-only line survives that where a marker file that
- * exists only during the wait would not. One `appendFileSync` of under 200
- * bytes per line. A write failure is reported on stderr and changes nothing
- * else — only that line is lost. The log stops at WAIT_LOG_LIMIT.
+ * Append one line to `waits.jsonl`. Durable on purpose: a wait can open and close
+ * between two reads of any observer. One `appendFileSync` of under 200 bytes per line;
+ * a write failure loses only that line. The log stops at WAIT_LOG_LIMIT.
*/
private appendWait(
entry: SessionEntry,
line:
| { wait: "open"; since: string; turns: number }
- | { wait: "closed"; since: string; at: string; to: SessionStatus }
+ | { wait: "closed"; since: string; at: string; to: ChannelEventType }
): void {
if (entry.waitLogBytes >= WAIT_LOG_LIMIT) return;
const payload = `${JSON.stringify(line)}\n`;
@@ -2121,170 +1794,7 @@ export class SessionManager {
}
}
- /**
- * The child is gone. Record the FACTS; do not reach a verdict here.
- *
- * `exit` fires BEFORE the stdout pipe closes, and the terminal `result` frame
- * is by construction the LAST line the child writes — so it is precisely the
- * frame still in flight at this moment. Classifying here read `sawResult ===
- * false` on a session that had answered perfectly well and filed it as
- * "exited 0 without ever emitting a terminal `result` frame": a complete,
- * billed run reported as a failure, nondeterministically.
- *
- * `team` already paid for this exact lesson and encoded the fix — see the
- * comment above its own exit handler (team-orchestrator.ts ~1050): "exit
- * fires BEFORE the stdout pipe closes, and an answer flushed during shutdown
- * is still in flight at this moment — resolving here marked the run finished
- * with the byte count from KILL time … which is how a complete answer was
- * reported as 0 B". Same discipline here: `close` on the stdio pipes drives
- * finalisation, bounded by the same `DRAIN_TIMEOUT_MS` so a pipe some
- * descendant still holds degrades into a slightly-late verdict, not a hang.
- */
- private handleExit(sessionId: string, code: number | null, signal: string | null): void {
- const entry = this.sessions.get(sessionId);
- if (!entry || entry.pendingExit) return;
-
- entry.pendingExit = { code, signal, at: new Date().toISOString() };
- entry.stdinClosed = true;
-
- if (entry.timeoutHandle) clearTimeout(entry.timeoutHandle);
- entry.timeoutHandle = null;
- if (entry.killHandle) clearTimeout(entry.killHandle);
- entry.killHandle = null;
-
- if (entry.openPipes <= 0) {
- this.finalize(sessionId);
- return;
- }
- entry.drainHandle = setTimeout(() => this.finalize(sessionId), DRAIN_TIMEOUT_MS);
- entry.drainHandle.unref?.();
- }
-
- /** One stdio pipe reached EOF. Finalise once both have, and the child is gone. */
- private onPipeClosed(sessionId: string): void {
- const entry = this.sessions.get(sessionId);
- if (!entry) return;
- entry.openPipes--;
- if (entry.openPipes > 0) return;
- // A pipe can close before `exit` fires; the verdict still needs the code.
- if (!entry.pendingExit) return;
- this.finalize(sessionId);
- }
-
- /**
- * Reach the verdict, write the artifacts, release the session's resources.
- *
- * Runs exactly once, from whichever of the three paths gets here first: both
- * pipes drained after `exit`, the bounded drain timer, or a spawn `error`.
- */
- private finalize(sessionId: string): void {
- const entry = this.sessions.get(sessionId);
- if (!entry || entry.finalized) return;
- entry.finalized = true;
-
- this.clearTimers(entry);
-
- const { code, signal, at } = entry.pendingExit ?? {
- code: null,
- signal: null,
- at: new Date().toISOString(),
- };
- entry.info.exitCode = code;
- entry.info.completedAt = at;
- entry.info.elapsedSeconds = this.getElapsed(entry.info.startedAt);
- entry.info.idleSeconds = entry.reducer ? Math.round(entry.reducer.idleMs / 1000) : null;
- entry.stdinClosed = true;
-
- this.flushDecoders(entry);
-
- // A timeout or a cancel has ALREADY decided how this session ended. The exit
- // that follows is a consequence of that decision, not a new verdict — and
- // letting it be one is exactly what turned a killed session into a
- // "completed" one. Report the exit; do not re-judge on it.
- const priorVerdict = TERMINAL_STATUSES.includes(entry.info.status) ? entry.info.status : null;
- const verdict = this.classifyExit(entry, code, signal);
-
- if (priorVerdict) {
- this.recordNote(
- entry,
- `\n[claudish] child exited (code=${code ?? "null"}, signal=${signal ?? "none"}) ` +
- `after the session was already recorded as ${priorVerdict}.\n`
- );
- } else if (verdict.state === "failed") {
- // The explanation goes into the SCROLLBACK, which is the field
- // `get_output` returns. A failed session whose only diagnostic sat in a
- // file nobody could reach is the exact shape of the bug this replaces.
- this.recordNote(entry, `\n[claudish] ${verdict.content}\n`);
- }
- // Absorbing terminal states mean this cannot upgrade a timeout or a cancel
- // that already ran — which is precisely what manufactured the false success.
- entry.reducer.settle(verdict.state, { content: verdict.content });
-
- this.writeArtifacts(entry);
-
- entry.reducer.dispose();
- this.scheduleEviction(entry);
- this.cleanupSigint();
- }
-
- /** Stop every timer a session owns. Safe to call more than once. */
- private clearTimers(entry: SessionEntry): void {
- if (entry.drainHandle) clearTimeout(entry.drainHandle);
- entry.drainHandle = null;
- if (entry.timeoutHandle) clearTimeout(entry.timeoutHandle);
- entry.timeoutHandle = null;
- if (entry.killHandle) clearTimeout(entry.killHandle);
- entry.killHandle = null;
- }
-
- /**
- * Flush whatever the stateful decoders and the reducer are still holding.
- *
- * A chunk that ended mid-codepoint leaves those bytes inside the decoder, and
- * a child killed mid-frame leaves an incomplete line inside the reducer. Both
- * are real answer text.
- */
- private flushDecoders(entry: SessionEntry): void {
- const decodedTail = entry.stdoutDecoder.end();
- if (decodedTail) {
- const prose = entry.reducer.feed(decodedTail);
- if (prose) this.recordProse(entry, prose);
- }
- this.recordStderr(entry, entry.stderrDecoder.end());
-
- const tail = entry.reducer.end();
- if (tail) this.recordProse(entry, tail);
- }
-
- /** Close output.log and write the two post-mortem files. */
- private writeArtifacts(entry: SessionEntry): void {
- entry.outputLogStream?.end();
- entry.outputLogStream = null;
-
- if (entry.stderr) {
- // Redacted before the bytes hit disk: provider stderr routinely echoes
- // key material and `get_diagnostics` hands this file's tail to an agent.
- writeFileSync(join(entry.sessionDir, "stderr.log"), redactSecrets(entry.stderr), "utf-8");
- }
-
- this.refreshAccounting(entry);
- entry.info.claudeSessionId = entry.reducer.claudeSessionId ?? entry.info.claudeSessionId;
- writeFileSync(
- join(entry.sessionDir, "meta.json"),
- JSON.stringify(entry.info, null, 2),
- "utf-8"
- );
- }
-
- /**
- * Drop a terminal session from the map after its retention window.
- *
- * `maxSessions` only counts ACTIVE sessions, so nothing used to remove a
- * finished one — there was not a single `sessions.delete` in this file, and a
- * long-lived MCP server grew a scrollback, a reducer and a stderr buffer per
- * session forever. The on-disk artifacts under `sessionDir` are unaffected;
- * this only bounds memory.
- */
+ /** Drop a terminal session from the map after its retention window (memory only). */
private scheduleEviction(entry: SessionEntry): void {
if (entry.evictHandle) return;
entry.evictHandle = setTimeout(() => {
@@ -2297,11 +1807,8 @@ export class SessionManager {
/** Enforce the hard ceiling, oldest terminal session first. */
private evictOldestTerminal(): void {
- const terminal = [...this.sessions.values()].filter(
- (candidate) => candidate.finalized && TERMINAL_STATUSES.includes(candidate.info.status)
- );
+ const terminal = [...this.sessions.values()].filter((c) => c.ended);
if (terminal.length <= MAX_TERMINAL_SESSIONS) return;
-
terminal.sort((a, b) => (a.info.completedAt ?? "").localeCompare(b.info.completedAt ?? ""));
for (const victim of terminal.slice(0, terminal.length - MAX_TERMINAL_SESSIONS)) {
if (victim.evictHandle) clearTimeout(victim.evictHandle);
@@ -2309,144 +1816,104 @@ export class SessionManager {
}
}
- /**
- * Decide how the session ended. Exit 0 has to EARN `completed`.
- *
- * Three independent witnesses, in order of authority:
- * 1. the exit code / signal
- * 2. the child's own `result` frame — `is_error`, `api_error_status`,
- * `terminal_reason`; and its ABSENCE, which means the child died before
- * finishing a turn no matter what it exited with
- * 3. `classifyRunOutput`, the same "exit 0 with nothing to show for it"
- * test `team` applies (empty output, API error text, background-task
- * ceiling)
- */
- private classifyExit(
- entry: SessionEntry,
- code: number | null,
- signal: string | null
- ): { state: "completed" | "failed"; content: string } {
- const stderrNote = meaningfulStderr(entry.stderr) || entry.stderr.trim();
- const withStderr = (text: string): string =>
- stderrNote ? `${text} stderr: ${stderrNote.slice(-500)}` : text;
-
- if (signal) {
- return { state: "failed", content: withStderr(`Child terminated by ${signal}.`) };
- }
- if (code !== 0) {
- return {
- state: "failed",
- content: withStderr(`Child exited with code ${code ?? "unknown"}.`),
- };
- }
-
- if (!entry.reducer.sawResult) {
- return {
- state: "failed",
- content: withStderr(
- "Child exited 0 without ever emitting a terminal `result` frame — it died " +
- "before finishing a turn. This is the signature of a startup failure " +
- "(unroutable model, missing credential) rather than a completed run."
- ),
- };
- }
- if (entry.reducer.resultIsError || entry.reducer.apiErrorStatus !== null) {
- const status = entry.reducer.apiErrorStatus;
- return {
- state: "failed",
- content: withStderr(
- `Child reported an error turn (terminal_reason=${entry.reducer.terminalReason ?? "unknown"}` +
- `${status !== null ? `, api_error_status=${status}` : ""}).`
- ),
- };
- }
-
- const reason = classifyStreamJsonProse(entry.proseBytes, entry.proseTail, entry.stderr);
- if (reason) {
- return { state: "failed", content: withStderr(`${reason.reason}: ${reason.detail}`) };
- }
-
- return { state: "completed", content: "" };
- }
-
- /**
- * Refresh tokens / cost / tool counts from the proxy's own token file.
- *
- * The proxy is the authority here, not the child. `result.total_cost_usd`
- * prices every model at Anthropic's rates, so for a proxied model it is
- * fiction and for a subscription provider it invents spend that will never be
- * billed. The child's `result.usage` is a sound fallback for TOKENS only —
- * used when the token file does not exist yet, or when the run died before its
- * first response.
- */
- private refreshAccounting(entry: SessionEntry): void {
- const stats = readTokenStatsAt(join(entry.sessionDir, "tokens.json"));
-
- const fileTokens =
- (stats?.total_tokens ?? 0) || (stats?.input_tokens ?? 0) + (stats?.output_tokens ?? 0);
- entry.info.tokensUsed = fileTokens || entry.reducer.tokens;
- entry.info.costUsd = stats?.total_cost ?? 0;
-
- const fileToolCalls = Array.isArray(stats?.tool_calls)
- ? stats.tool_calls.reduce((sum, t) => sum + (typeof t.count === "number" ? t.count : 0), 0)
- : 0;
- entry.info.toolCallCount = fileToolCalls || entry.reducer.toolUseCount;
-
- if (entry.reducer.turns > 0) entry.info.turnsCompleted = entry.reducer.turns;
- entry.info.terminalReason = entry.reducer.terminalReason ?? entry.info.terminalReason;
- entry.info.claudeSessionId = entry.reducer.claudeSessionId ?? entry.info.claudeSessionId;
- this.refreshTranscriptPath(entry);
- }
-
- /**
- * Re-derive the transcript path when the child reports a cwd we did not spawn
- * with, and only then.
- *
- * `system:init.cwd` is the child's own answer and outranks ours: claudish may
- * resolve, normalise or be handed a `work_dir` that is not the directory
- * `claude` ends up in, and the transcript lands under the one `claude` used.
- * Guarded on a CHANGE because `transcriptPathFor` does a `realpathSync`, and
- * this runs on every `list_sessions` / `get_output` / `get_session` call.
- */
- private refreshTranscriptPath(entry: SessionEntry): void {
- const uuid = entry.info.claudeSessionId;
- if (!uuid) {
- entry.info.transcriptPath = null;
- return;
- }
- const cwd = entry.reducer.cwd ?? entry.cwd;
- const key = `${cwd}\0${uuid}`;
- if (key === entry.transcriptKey) return;
- entry.transcriptKey = key;
- entry.info.transcriptPath = transcriptPathFor(cwd, uuid);
- }
-
private get activeSessions(): number {
let count = 0;
- for (const entry of this.sessions.values()) {
- if (!TERMINAL_STATUSES.includes(entry.info.status)) count++;
- }
+ for (const entry of this.sessions.values()) if (!entry.ended) count++;
return count;
}
+}
- private getElapsed(startedAt: string): number {
- return Math.round((Date.now() - new Date(startedAt).getTime()) / 1000);
- }
+function isWaiting(s: SlotState): boolean {
+ return s === "AWAITING_INPUT" || s === "AWAITING_PERMISSION";
+}
- private setupSigint(): void {
- if (this.sigintHandler) return;
- this.sigintHandler = () => {
- this.shutdownAll().catch(() => {});
- process.exit(1);
- };
- process.on("SIGINT", this.sigintHandler);
+/**
+ * The state and reason of a disk record, from either `meta.json` generation: the pane
+ * generation's `state` (a closed-set value) and `terminalReason` (a `FailureReason`), or
+ * 10.4.0's `status`. A non-terminal or unknown value — and a missing record — reads
+ * FAILED with reason null (§8 B).
+ */
+function diskState(meta: Record<string, unknown> | null): {
+ state: SlotState;
+ reason: FailureReason | null;
+} {
+ const raw = meta?.state;
+ if (typeof raw === "string" && (SLOT_STATES as readonly string[]).includes(raw)) {
+ const state = raw as SlotState;
+ if (!isTerminalState(state)) return { state: "FAILED", reason: null };
+ return { state, reason: state === "COMPLETED" ? null : metaReason(meta?.terminalReason) };
}
+ // 10.4.0: its terminalReason was Claude Code's text, not a FailureReason, so only the
+ // two reasons a state implies are known.
+ const status = typeof meta?.status === "string" ? STATE_OF_10_4_STATUS[meta.status] : undefined;
+ const state = status ?? "FAILED";
+ if (state === "CANCELLED") return { state, reason: "cancelled" };
+ if (state === "TIMEOUT") return { state, reason: "timeout" };
+ return { state, reason: null };
+}
- private cleanupSigint(): void {
- if (this.activeSessions > 0) return;
- if (this.sigintHandler) {
- process.off("SIGINT", this.sigintHandler);
- this.sigintHandler = null;
- }
- }
+/**
+ * A `SessionInfo` from a session directory's files. Every field is validated, never
+ * coerced: a `meta.json` truncated mid-write by a SIGKILL is the case this is FOR.
+ */
+function diskInfo(d: {
+ sessionId: string;
+ meta: Record<string, unknown> | null;
+ spawnRecord: Record<string, unknown> | null;
+ measured: ReturnType<typeof diskAccounting>;
+ dirMtimeMs: number;
+ transcriptPath: string;
+}): SessionInfo {
+ const { meta, spawnRecord, measured } = d;
+ const startedAt =
+ metaString(meta?.startedAt) ??
+ metaString(spawnRecord?.startedAt) ??
+ new Date(d.dirMtimeMs).toISOString();
+ const completedAt = metaString(meta?.completedAt);
+ const { state, reason } = diskState(meta);
+ return {
+ // The id we were ASKED for, never the one in the file.
+ sessionId: d.sessionId,
+ model: metaString(meta?.model) ?? metaString(spawnRecord?.model) ?? "unknown",
+ spawnModel: metaString(meta?.spawnModel),
+ provider: metaString(meta?.provider),
+ state,
+ shape: meta?.shape === "interactive" ? "interactive" : "one-shot",
+ pane: metaString(meta?.pane),
+ // NEVER the pid from the file: it belonged to a process that is gone, and pids are
+ // reused.
+ panePid: null,
+ startedAt,
+ completedAt,
+ exitCode: metaNumber(meta?.exitCode),
+ turnsCompleted: metaNumber(meta?.turnsCompleted) ?? 0,
+ tokensIn: metaNumber(meta?.tokensIn) ?? measured.tokensIn,
+ tokensOut: metaNumber(meta?.tokensOut) ?? measured.tokensOut,
+ costUsd: metaNumber(meta?.costUsd) ?? measured.costUsd,
+ toolCalls: metaNumber(meta?.toolCallCount) ?? measured.toolCalls,
+ lastActivityAt: metaString(meta?.lastActivityAt),
+ // Wall time as it ENDED, not as it looks now.
+ elapsedSeconds: elapsedSecondsBetween(
+ startedAt,
+ completedAt ? Date.parse(completedAt) : d.dirMtimeMs
+ ),
+ // Read from disk: no live process to be idle. Null, never 0.
+ idleSeconds: null,
+ activity: null,
+ reason,
+ detail: meta === null ? NO_TERMINAL_RECORD : metaString(meta.detail),
+ pendingInputs: 0,
+ claudeSessionId:
+ metaString(meta?.claudeSessionId) ?? metaString(spawnRecord?.claudeSessionId) ?? "",
+ ...optionalParent(metaString(meta?.parentClaudeSessionId)),
+ transcriptPath: d.transcriptPath,
+ captureSource: diskCaptureSource(meta?.captureSource),
+ turnSource: meta?.turnSource === "screen" ? "screen" : "transcript",
+ timeoutSeconds:
+ metaNumber(meta?.timeoutSeconds) ?? metaNumber(spawnRecord?.timeoutSeconds) ?? 0,
+ };
+}
+
+function diskCaptureSource(v: unknown): SessionInfo["captureSource"] {
+ return v === "transcript" || v === "screen" || v === "none" ? v : null;
}
diff --git a/packages/cli/src/channel/session-state-records.contract.test.ts b/packages/cli/src/channel/session-state-records.contract.test.ts
index 13eed75e..cbcb5845 100644
--- a/packages/cli/src/channel/session-state-records.contract.test.ts
+++ b/packages/cli/src/channel/session-state-records.contract.test.ts
@@ -1,22 +1,31 @@
// 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).
+ * Black-box contract tests for the state model as it reaches disk: 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.
+ * temp CLAUDISH_SESSIONS_DIR, HOME and CLAUDE_CONFIG_DIR. Every session is an interactive
+ * pane: the pane fake (marker mode) via CLAUDISH_BIN, in a real headless magmux under the
+ * test's own CLAUDISH_PANE_ROOT. No model, no network. Ported per architecture §20.2: only
+ * the adapters and the fake changed; the three cases about 10.4.0's `finishing` state are
+ * replaced (RB1, D17, D23), and the promptless cases wait for boot first (RB2). After each
+ * test no pane process or file may remain.
*
* 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).
+ * transition into a wait, so its absence proves a session never waited.
+ * INFERRED: get_diagnostics reports the live channel event in an `event` field (adapter
+ * `sessionStatus` in contract-mcp.ts, RB7).
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { existsSync } from "node:fs";
import { join } from "node:path";
import {
+ MAGMUX_AVAILABLE,
McpServer,
+ NO_MAGMUX_MESSAGE,
createSession,
+ paneOrphans,
+ paneRootOf,
sendInput,
serverEnv,
sessionStatus,
@@ -24,6 +33,7 @@ import {
} from "../test-helpers/contract-mcp.js";
import {
type TempLayout,
+ entries,
makeTempLayout,
readJson,
readWaitLines,
@@ -32,22 +42,28 @@ import {
} from "../test-helpers/contract-records.js";
const T_TEST = 30_000;
+/** Boot (≈ 2 s with the fake) plus the answer, with room for a loaded machine. */
+const BOOT_MS = 15_000;
let layout: TempLayout;
let server: McpServer;
+if (!MAGMUX_AVAILABLE) console.warn(NO_MAGMUX_MESSAGE);
+
beforeEach(async () => {
layout = makeTempLayout("state");
server = await McpServer.start({ env: serverEnv(layout), cwd: layout.cwd });
});
afterEach(async () => {
await server.close();
+ const report = await paneOrphans(layout);
layout.cleanup();
-});
+ expect(report).toEqual({ processes: [], files: [] });
+}, 40_000);
const dirOf = (id: string) => join(layout.sessionsDir, id);
-async function terminalMeta(id: string, timeoutMs = 10_000): Promise<Record<string, unknown>> {
+async function terminalMeta(id: string, timeoutMs = BOOT_MS): Promise<Record<string, unknown>> {
return waitFor(
() => {
const meta = readJson(join(dirOf(id), "meta.json"));
@@ -66,187 +82,246 @@ async function created(args: Parameters<typeof createSession>[1]): Promise<strin
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" }
- );
+/** RB2: a promptless session waits once boot is ready (STARTING before). */
+async function bootedPromptless(): Promise<string> {
+ const id = await created({});
+ await waitFor(() => readWaitLines(dirOf(id))?.length === 1, {
+ what: "the first open line (boot ready)",
+ timeoutMs: BOOT_MS,
+ intervalMs: 2,
+ });
+ return id;
+}
- 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
- );
-});
+/** The session's `list_sessions` row. */
+async function rowOf(id: string): Promise<Record<string, unknown> | undefined> {
+ const r = await server.callTool("list_sessions", { include_completed: true });
+ const rows = (r.json?.sessions ?? []) as Array<Record<string, unknown>>;
+ return rows.find((row) => row.session_id === id);
+}
-describe("REQ-14 no wait is left open beside a meta.json", () => {
+describe.skipIf(!MAGMUX_AVAILABLE)(
+ "REQ-9 a one-shot session ends at its verdict 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
+ );
+
+ // Replaced (RB1): 10.4.0's "between its final result and the child's exit the session reads
+ // finishing, then completed". A pane session decides a one-shot verdict at settle, so the
+ // exiting interval does not exist; the end-of-turn wait is `activity:"finishing"` on RUNNING.
+ test(
+ "RB1 a one-shot session goes running → completed with no wait, and meta.json is written before its pane is reaped",
+ async () => {
+ const id = await created({
+ prompt: "answer, then take a while to end the turn @@LINGER@@",
+ });
+ const seen: string[] = [];
+ const panes = join(paneRootOf(layout), "panes");
+ let paneRecordsAtMeta = -1;
+
+ await waitFor(
+ async () => {
+ if (paneRecordsAtMeta < 0 && readJson(join(dirOf(id), "meta.json")))
+ paneRecordsAtMeta = entries(panes).length;
+ 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: BOOT_MS, intervalMs: 5 }
+ );
+ await waitFor(
+ () => {
+ if (paneRecordsAtMeta < 0 && readJson(join(dirOf(id), "meta.json")))
+ paneRecordsAtMeta = entries(panes).length;
+ return paneRecordsAtMeta >= 0;
+ },
+ { what: "meta.json", intervalMs: 2 }
+ );
+
+ expect(seen).toContain("running");
+ expect(seen[seen.length - 1]).toBe("completed");
+ expect(seen).not.toContain("finishing");
+ expect(seen).not.toContain("waiting_for_input");
+ expect(paneRecordsAtMeta).toBe(1);
+ expect(existsSync(join(dirOf(id), "waits.jsonl"))).toBe(false);
+ },
+ T_TEST
+ );
+
+ // Replaced (D17): 10.4.0's "a finishing session refuses send_input and still completes without
+ // waiting". send_input is accepted in every non-terminal state; only a terminal one refuses.
+ test(
+ "D17 a send after a one-shot's verdict is refused terminal; a send while its activity is finishing is queued, converts it, and is answered as turn 2",
+ async () => {
+ const done = await created({ prompt: "say hello" });
+ await terminalMeta(done);
+ const refused = await sendInput(server, done, "too late");
+ expect(refused.json).toMatchObject({ success: false, reason: "terminal" });
+
+ const id = await created({ prompt: "answer, then linger @@LINGER@@" });
+ await waitFor(async () => (await rowOf(id))?.activity === "finishing", {
+ what: "activity finishing",
+ timeoutMs: BOOT_MS,
+ intervalMs: 20,
+ });
+ const accepted = await sendInput(server, id, "second question");
+ expect(accepted.json).toMatchObject({ success: true });
+
+ const row = await waitFor(
+ async () => {
+ const r = await rowOf(id);
+ return r?.turns_completed === 2 && r.state === "AWAITING_INPUT" ? r : undefined;
+ },
+ { what: "turn 2 answered", timeoutMs: BOOT_MS }
+ );
+ const output = await sessionTool(server, "get_output", id);
+ const lines = readWaitLines(dirOf(id)) ?? [];
+
+ expect(row.state).toBe("AWAITING_INPUT");
+ expect((String(output.json?.output).match(/ANSWER /g) ?? []).length).toBe(2);
+ // The send was queued behind turn 1, so no wait opened between the turns (net of the pump).
+ expect(lines.map((l) => [l.wait, l.turns])).toEqual([["open", 2]]);
+ await sessionTool(server, "cancel_session", id);
+ },
+ T_TEST
+ );
+
+ // Replaced (D23, §2.8): 10.4.0's "frames after the final result do not reopen the session;
+ // diagnostics name the refused state". A re-wake is part of the same turn, not a late frame.
+ test(
+ "D23 a re-wake after the answer stays in the same turn, opens no wait, and turnsCompleted is 1",
+ async () => {
+ const id = await created({ prompt: "answer, then wake again @@LATE@@" });
+
+ const meta = await terminalMeta(id);
+ const output = await sessionTool(server, "get_output", id);
+
+ expect(meta.status).toBe("completed");
+ expect(meta.turnsCompleted).toBe(1);
+ expect(String(output.json?.output)).toContain("LATE second message");
+ expect(existsSync(join(dirOf(id), "waits.jsonl"))).toBe(false);
+ },
+ T_TEST
+ );
+ }
+);
+
+describe.skipIf(!MAGMUX_AVAILABLE)(
+ "REQ-11/REQ-14 a promptless session waits once boot is ready, and every wait is logged",
+ () => {
+ test(
+ "RB2 it is waiting_for_input once boot is ready, with one open line (turns 0), and the child's own activity does not end the wait",
+ async () => {
+ const id = await bootedPromptless();
+
+ const status = await sessionStatus(server, id);
+ await Bun.sleep(1_000);
+ const lines = readWaitLines(dirOf(id));
+ const statusLater = await sessionStatus(server, id);
+
+ expect(status).toBe("waiting_for_input");
+ expect(statusLater).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 bootedPromptless();
+
+ 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", timeoutMs: BOOT_MS }
+ );
+ 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", timeoutMs: BOOT_MS }
+ );
+
+ 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
+ );
+
+ // RB2: a send during boot is queued and becomes the first prompt, so no wait opens; the
+ // shortest real wait starts at boot-ready, so the send follows the open line at once.
+ test(
+ "a wait that opens and closes within milliseconds still leaves both lines",
+ async () => {
+ const id = await bootedPromptless();
+ 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", timeoutMs: BOOT_MS }
+ );
+
+ 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.skipIf(!MAGMUX_AVAILABLE)("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" });
+ const id = await bootedPromptless();
await sessionTool(server, "cancel_session", id);
const meta = await terminalMeta(id);
@@ -260,12 +335,13 @@ describe("REQ-14 no wait is left open beside a meta.json", () => {
T_TEST
);
+ // RB2: a timeout that expires during boot opens no wait; 5 s lets the session boot and wait.
test(
"a session timeout closes the open wait (to: timeout)",
async () => {
- const id = await created({ timeout_seconds: 1 });
+ const id = await created({ timeout_seconds: 5 });
- const meta = await terminalMeta(id, 15_000);
+ const meta = await terminalMeta(id, 20_000);
const lines = readWaitLines(dirOf(id)) ?? [];
expect(meta.status).toBe("timeout");
@@ -279,8 +355,7 @@ describe("REQ-14 no wait is left open beside a meta.json", () => {
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 id = await bootedPromptless();
const cancelling = sessionTool(server, "cancel_session", id).catch(() => undefined);
const linesWhenMetaAppeared = await waitFor(
@@ -301,6 +376,7 @@ describe("REQ-14 no wait is left open beside a meta.json", () => {
const id = await created({ prompt: "never answer @@HANG@@" });
await waitFor(async () => (await sessionStatus(server, id)) === "running", {
what: "running",
+ timeoutMs: BOOT_MS,
});
await sessionTool(server, "cancel_session", id);
diff --git a/packages/cli/src/channel/session-timeout.test.ts b/packages/cli/src/channel/session-timeout.test.ts
index f39bbe8a..504c8a55 100644
--- a/packages/cli/src/channel/session-timeout.test.ts
+++ b/packages/cli/src/channel/session-timeout.test.ts
@@ -1,6 +1,6 @@
/**
* `timeout_seconds` is normalised ONCE, in `createSession`, before it reaches
- * `spawn.json` or the timer.
+ * `spawn.json`, `SessionInfo` or the pane's timer.
*
* The tool schema accepted any number, and the writer persisted
* `Math.min(value, 3600)` unvalidated: 90.5, 0 and -5 went to disk as-is, and a
@@ -8,73 +8,84 @@
* magus plugin monitor requires an integer in 1..3600 and drops any other
* record, so the whole run went unreported — and 0 or a negative value also
* timed the session out at once.
+ *
+ * Each session is a promptless pane session on the fake interactive child, so nothing
+ * but its own timeout ends it; a value of 1 expires it during boot (§20.3 item 4), which
+ * is the caller's explicit deadline.
*/
-import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test";
-import { mkdtempSync, readFileSync, rmSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { dirname, join } from "node:path";
-import { fileURLToPath } from "node:url";
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import {
+ MAGMUX,
+ NO_MAGMUX_MESSAGE,
+ type PaneTestEnv,
+ killLeftovers,
+ makePaneTestEnv,
+ waitNoOrphans,
+} from "../pane/test-helpers/hermetic-env.js";
import { SessionManager } from "./session-manager.js";
-const FAKE_CLAUDISH_TS = join(
- dirname(fileURLToPath(import.meta.url)),
- "test-helpers",
- "fake-channel-stream-json.ts"
-);
-
-const originalClaudishBin = process.env.CLAUDISH_BIN;
-let sessionsDir: string;
-let manager: SessionManager;
-
-beforeAll(() => {
- process.env.CLAUDISH_BIN = FAKE_CLAUDISH_TS;
-});
-
-afterAll(() => {
- if (originalClaudishBin === undefined) delete process.env.CLAUDISH_BIN;
- else process.env.CLAUDISH_BIN = originalClaudishBin;
-});
+describe.skipIf(!MAGMUX)(
+ `createSession timeout normalisation (${MAGMUX ? "magmux" : NO_MAGMUX_MESSAGE})`,
+ () => {
+ let t: PaneTestEnv;
+ let sessionsDir: string;
+ let manager: SessionManager;
-beforeEach(() => {
- sessionsDir = mkdtempSync(join(tmpdir(), "claudish-session-timeout-"));
- manager = new SessionManager({ hostPid: 1, sessionsDir, stallSeconds: 0 });
-});
+ // One environment for the table: every case starts a pane and cancels it at once.
+ beforeAll(() => {
+ t = makePaneTestEnv();
+ sessionsDir = join(t.tmp, "sessions");
+ manager = new SessionManager({
+ hostPid: 1,
+ sessionsDir,
+ parentEnv: t.env,
+ paneTimings: { replStableMs: 200 },
+ });
+ });
-afterEach(async () => {
- await manager.shutdownAll();
- rmSync(sessionsDir, { recursive: true, force: true });
-});
+ afterAll(async () => {
+ await manager.shutdownAll();
+ const report = await waitNoOrphans({ sockRoot: t.sockRoot }, 15_000);
+ killLeftovers({ sockRoot: t.sockRoot });
+ t.cleanup();
+ expect(report).toEqual({ processes: [], files: [] });
+ });
-function spawnRecordTimeout(raw: unknown): unknown {
- const sessionId = manager.createSession({
- model: "fake-model",
- // A promptless session waits for input, so nothing ends it during the test.
- timeoutSeconds: raw as number | undefined,
- });
- const spawn = JSON.parse(readFileSync(join(sessionsDir, sessionId, "spawn.json"), "utf-8"));
- return spawn.timeoutSeconds;
-}
+ async function spawnRecordTimeout(raw: unknown): Promise<unknown> {
+ const sessionId = await manager.createSession({
+ model: "fake-answer",
+ cwd: t.cwd,
+ timeoutSeconds: raw as number | undefined,
+ });
+ const spawn = JSON.parse(readFileSync(join(sessionsDir, sessionId, "spawn.json"), "utf-8"));
+ // the record and the timer cannot disagree: SessionInfo carries the same value
+ expect(manager.getSession(sessionId).timeoutSeconds).toBe(spawn.timeoutSeconds);
+ manager.cancelSession(sessionId);
+ return spawn.timeoutSeconds;
+ }
-describe("createSession timeout normalisation", () => {
- const cases: [unknown, number][] = [
- [90.5, 91],
- [90.4, 90],
- [0, 1],
- [-5, 1],
- [0.2, 1],
- [7200, 3600],
- [Number.NaN, 600],
- [Number.POSITIVE_INFINITY, 600],
- ["600", 600],
- [null, 600],
- [undefined, 600],
- ];
+ const cases: [unknown, number][] = [
+ [90.5, 91],
+ [90.4, 90],
+ [0, 1],
+ [-5, 1],
+ [0.2, 1],
+ [7200, 3600],
+ [Number.NaN, 600],
+ [Number.POSITIVE_INFINITY, 600],
+ ["600", 600],
+ [null, 600],
+ [undefined, 600],
+ ];
- for (const [raw, expected] of cases) {
- test(`${String(raw)} → ${expected}`, () => {
- expect(spawnRecordTimeout(raw)).toBe(expected);
- });
+ for (const [raw, expected] of cases) {
+ test(`${String(raw)} → ${expected}`, async () => {
+ expect(await spawnRecordTimeout(raw)).toBe(expected);
+ }, 30_000);
+ }
}
-});
+);
diff --git a/packages/cli/src/channel/spawn-record.contract.test.ts b/packages/cli/src/channel/spawn-record.contract.test.ts
index d5a8cffc..3d96c96d 100644
--- a/packages/cli/src/channel/spawn-record.contract.test.ts
+++ b/packages/cli/src/channel/spawn-record.contract.test.ts
@@ -4,6 +4,10 @@
* 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).
*
+ * Every session is an interactive pane: the pane fake (marker mode) via CLAUDISH_BIN, in a
+ * real headless magmux under the test's own CLAUDISH_PANE_ROOT (ported per architecture
+ * §20.2; every assertion kept). After each test no pane process or file may remain.
+ *
* 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
@@ -20,8 +24,11 @@ import { join } from "node:path";
import { newSessionManager } from "../test-helpers/contract-adapters.js";
import {
FAKE_MODEL,
+ MAGMUX_AVAILABLE,
McpServer,
+ NO_MAGMUX_MESSAGE,
createSession,
+ paneOrphans,
serverEnv,
sessionTool,
} from "../test-helpers/contract-mcp.js";
@@ -43,13 +50,17 @@ const T_TEST = 30_000;
let layout: TempLayout;
const servers: McpServer[] = [];
+if (!MAGMUX_AVAILABLE) console.warn(NO_MAGMUX_MESSAGE);
+
beforeEach(() => {
layout = makeTempLayout("spawn");
});
afterEach(async () => {
for (const s of servers.splice(0)) await s.close();
+ const report = await paneOrphans(layout);
layout.cleanup();
-});
+ expect(report).toEqual({ processes: [], files: [] });
+}, 40_000);
async function startServer(extraEnv: Record<string, string | undefined> = {}): Promise<McpServer> {
const server = await McpServer.start({ env: serverEnv(layout, extraEnv), cwd: layout.cwd });
@@ -107,7 +118,7 @@ async function createdId(
return sessionId as string;
}
-describe("REQ-7 spawn.json: the start-time record of a session", () => {
+describe.skipIf(!MAGMUX_AVAILABLE)("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 () => {
@@ -182,50 +193,55 @@ describe("REQ-7 spawn.json: the start-time record of a session", () => {
);
});
-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();
+describe.skipIf(!MAGMUX_AVAILABLE)(
+ "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 });
+ 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,
- });
+ expect(spawnRecord(layout.sessionsDir, id).timeoutSeconds).toBe(3600);
+ },
+ T_TEST
+ );
- 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
- );
-});
+ 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", () => {
+describe.skipIf(!MAGMUX_AVAILABLE)("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 () => {
@@ -307,86 +323,94 @@ describe("REQ-1 the parent conversation is recorded when proven", () => {
);
});
-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
- );
+describe.skipIf(!MAGMUX_AVAILABLE)(
+ "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 _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 });
+ 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, bad);
- },
- T_TEST
- );
+ await expectNoParentAnywhere(server, undefined);
+ },
+ 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",
- });
+ 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, T);
- },
- T_TEST
- );
+ await expectNoParentAnywhere(server, bad);
+ },
+ 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 });
+ 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
+ );
- 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 {
diff --git a/packages/cli/src/channel/stream-json-reducer-unrecognized-json.test.ts b/packages/cli/src/channel/stream-json-reducer-unrecognized-json.test.ts
deleted file mode 100644
index de8eb63a..00000000
--- a/packages/cli/src/channel/stream-json-reducer-unrecognized-json.test.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { describe, expect, test } from "bun:test";
-
-import { StreamJsonReducer } from "./stream-json-reducer.js";
-
-const UNRECOGNIZED_JSON = '["--model","x","-y"]';
-const API_ERROR = "[API Error: overloaded]";
-const ASSISTANT_TEXT = "Recovered assistant answer";
-const ASSISTANT_FRAME = JSON.stringify({
- type: "assistant",
- message: {
- role: "assistant",
- content: [{ type: "text", text: ASSISTANT_TEXT }],
- },
-});
-
-function feedLine(line: string, keepUnrecognizedJson?: true): string {
- const reducer = new StreamJsonReducer({
- sessionId: "unrecognized-json-test",
- stallSeconds: 0,
- callback: () => {},
- onResult: () => "stdin-closed",
- ...(keepUnrecognizedJson === true ? { keepUnrecognizedJson } : {}),
- });
-
- try {
- return reducer.feed(`${line}\n`);
- } finally {
- reducer.dispose();
- }
-}
-
-describe.each([
- { setting: "the default", keepUnrecognizedJson: undefined, unrecognizedJson: "" },
- {
- setting: "keepUnrecognizedJson enabled",
- keepUnrecognizedJson: true,
- unrecognizedJson: `${UNRECOGNIZED_JSON}\n`,
- },
-] as const)("StreamJsonReducer with $setting", ({ keepUnrecognizedJson, unrecognizedJson }) => {
- test("handles valid JSON outside the stream-json vocabulary", () => {
- expect(feedLine(UNRECOGNIZED_JSON, keepUnrecognizedJson)).toBe(unrecognizedJson);
- });
-
- test("always passes through non-JSON output verbatim", () => {
- expect(feedLine(API_ERROR, keepUnrecognizedJson)).toBe(`${API_ERROR}\n`);
- });
-
- test("always recovers prose from a recognized assistant frame", () => {
- expect(feedLine(ASSISTANT_FRAME, keepUnrecognizedJson)).toBe(ASSISTANT_TEXT);
- });
-});
diff --git a/packages/cli/src/channel/stream-json-reducer.contract.test.ts b/packages/cli/src/channel/stream-json-reducer.contract.test.ts
deleted file mode 100644
index 75862741..00000000
--- a/packages/cli/src/channel/stream-json-reducer.contract.test.ts
+++ /dev/null
@@ -1,248 +0,0 @@
-// 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/stream-json-reducer.test.ts b/packages/cli/src/channel/stream-json-reducer.test.ts
deleted file mode 100644
index 8169e1f8..00000000
--- a/packages/cli/src/channel/stream-json-reducer.test.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-import { describe, expect, test } from "bun:test";
-
-import { ScrollbackBuffer } from "./scrollback-buffer.js";
-import {
- type ResultSummary,
- StreamJsonReducer,
- type StreamJsonReducerOptions,
-} from "./stream-json-reducer.js";
-import {
- CAPTURED_ASSISTANT_FRAME,
- CAPTURED_ASSISTANT_PROSE,
- CAPTURED_DELTA_LINE,
- CAPTURED_RATE_LIMIT_LINE,
- CAPTURED_STATUS_LINE,
- capturedSuccessResult,
-} from "./test-helpers/captured-stream-json.js";
-import type { ReducerEvent } from "./types.js";
-
-function line(frame: Record<string, unknown>): string {
- return `${JSON.stringify(frame)}\n`;
-}
-
-describe("StreamJsonReducer", () => {
- test("captured semantic frames drive state, prose, result accounting, and diagnostics", () => {
- const events: ReducerEvent[] = [];
- const semanticLines: string[] = [];
- let summary: ResultSummary | undefined;
- const options: StreamJsonReducerOptions = {
- sessionId: "reducer-test",
- stallSeconds: 0,
- callback: (_sessionId, event) => events.push(event),
- onSemanticLine: (semanticLine) => semanticLines.push(semanticLine),
- // The captured stream is a one-shot run: its owner closes stdin at the
- // result, so the turn end moves to `finishing`, never `waiting_for_input`.
- onResult: (result) => {
- summary = result;
- return "stdin-closed";
- },
- };
- const reducer = new StreamJsonReducer(options);
-
- let prose = "";
- prose += reducer.feed(`${CAPTURED_STATUS_LINE}\n`);
- prose += reducer.feed(line(CAPTURED_ASSISTANT_FRAME));
- prose += reducer.feed(`${CAPTURED_RATE_LIMIT_LINE}\n`);
- prose += reducer.feed(line(capturedSuccessResult(CAPTURED_ASSISTANT_PROSE)));
- prose += reducer.end();
-
- expect(events.map((event) => event.newState)).toEqual(["running", "finishing"]);
- expect(prose).toBe(`${CAPTURED_ASSISTANT_PROSE}\n`);
- expect(reducer.state).toBe("finishing");
- expect(reducer.sawResult).toBe(true);
- expect(reducer.turns).toBe(1);
- expect(reducer.tokens).toBeGreaterThan(0);
- expect(summary?.terminalReason).toBe("completed");
- expect(semanticLines).toHaveLength(4);
- expect(semanticLines).toContain(CAPTURED_RATE_LIMIT_LINE);
- reducer.dispose();
- });
-
- test("G6: delta firehose never evicts real assistant prose from scrollback", () => {
- const scrollback = new ScrollbackBuffer(2000);
- const reducer = new StreamJsonReducer({
- sessionId: "delta-regression",
- stallSeconds: 0,
- callback: () => {},
- onResult: () => "stdin-closed",
- });
- const appendRecovered = (chunk: string): void => {
- const recovered = reducer.feed(chunk);
- if (recovered) scrollback.append(recovered);
- };
-
- // This assistant frame and the delta frame both come from the captured
- // bidirectional probe. Assistant prose arrives first, exactly as it would
- // be vulnerable to eviction during a long generation.
- for (let index = 0; index < 5; index++) {
- appendRecovered(line(CAPTURED_ASSISTANT_FRAME));
- }
- for (let index = 0; index < 3000; index++) {
- appendRecovered(`${CAPTURED_DELTA_LINE}\n`);
- }
- const tail = reducer.end();
- if (tail) scrollback.append(tail);
-
- const stored = scrollback.getLines().join("\n");
- expect(stored).toContain(CAPTURED_ASSISTANT_PROSE);
- expect(stored).not.toContain('"type":"stream_event"');
- expect(scrollback.totalLines).toBeLessThan(100);
- reducer.dispose();
- });
-});
diff --git a/packages/cli/src/channel/stream-json-reducer.ts b/packages/cli/src/channel/stream-json-reducer.ts
deleted file mode 100644
index 77ac2b1e..00000000
--- a/packages/cli/src/channel/stream-json-reducer.ts
+++ /dev/null
@@ -1,759 +0,0 @@
-/**
- * StreamJsonReducer — turns a child's `--output-format stream-json` NDJSON into
- * channel state, prose, and accounting.
- *
- * ## What it replaces, and why
- *
- * `SignalWatcher` inferred state by regex-matching Claude Code's INTERACTIVE TUI
- * glyphs (`⏺ Read`, spinner text) against the output of a child running in PRINT
- * mode, which emits none of them. Every pattern was therefore dead from the day
- * it shipped: `feed()` never matched, the machine never left `starting`, and the
- * only transition that ever fired was the one driven by process exit. Two real
- * sessions ran 15 minutes, made 93 tool calls and generated 68 k output tokens,
- * and were recorded as `turnsCompleted: 0, tokensUsed: 0, status: "completed"`
- * with a 0-byte output log.
- *
- * The fix is not a better regex. The child can be asked to *declare* its state,
- * and 2.1.239 does: `--output-format stream-json` emits one JSON object per line
- * for every message, tool call, hook and turn boundary, and `result` carries
- * `terminal_reason` / `is_error` / `api_error_status` / `num_turns` / `usage`.
- * Transitions become facts instead of guesses.
- *
- * ## Three rules that are load-bearing
- *
- * 1. **Deltas are consumed and discarded.** With `--include-partial-messages` a
- * long session emits 20–60 k `stream_event` frames (~230 B each, 5–14 MB).
- * Storing them would evict all 2 000 lines of `ScrollbackBuffer` within
- * seconds and leave a ring full of three-character text fragments. They exist
- * here to prove the child is alive — nothing more.
- *
- * 2. **Per-line degradation, never latching.** Only a line that is BOTH valid
- * JSON AND carries a recognised `type` is treated as an event. Anything else
- * goes to the answer verbatim. This is not defensive padding: a real run of
- * `claude 2.1.239` put `Client.listTools() called but server does not
- * advertise tools capability - returning empty list` on stdout, mid-stream.
- * Sniffing the format once from the first line would have been cheaper and
- * would have silently disabled recovery for the whole run.
- *
- * 3. **Terminal states are absorbing.** The 900-second silent success was
- * manufactured by a guard that blocked only `cancelled`, so a process exit
- * could *upgrade* a `failed` the timeout handler had already decided. The
- * transition table below makes every terminal state absorbing, and an attempt
- * to leave one is recorded rather than obeyed.
- */
-
-import {
- type AssistantTextCapture,
- STREAM_JSON_EVENT_TYPES,
- createAssistantTextCapture,
-} from "../team-stream-capture.js";
-import type { ReducerCallback, ReducerEvent, SessionStatus } from "./types.js";
-
-/**
- * Frame types that exist only to prove liveness.
- *
- * They are counted, they reset the stall watchdog, and then they are dropped —
- * never fed to the answer capture, never written to the event log. `stream_event`
- * is the partial-message delta firehose (rule 1 above).
- */
-const DELTA_FRAME_TYPES = new Set(["stream_event"]);
-
-/**
- * Which lines reach the answer capture.
- *
- * `STREAM_JSON_EVENT_TYPES` is the capture's own vocabulary, imported rather
- * than duplicated: a frame it does not recognise it passes through VERBATIM, so
- * handing it `rate_limit_event` (or any type Claude Code adds next) would dump
- * raw protocol JSON into the answer an agent reads. Measured — that is exactly
- * what happened to `rate_limit_event` before this gate existed.
- *
- * Non-JSON lines still go through, which is the point of the degradation rule:
- * the worst case must be an ugly answer, never a lost one.
- */
-function reachesAnswer(
- parsedType: string | null,
- isJson: boolean,
- keepUnrecognizedJson: boolean
-): boolean {
- if (!isJson) return true;
- if (parsedType !== null && STREAM_JSON_EVENT_TYPES.has(parsedType)) return true;
- // JSON that is not stream-json vocabulary. A channel session's stdout is pure
- // stream-json, so for the channel this is machine noise and dropping it keeps
- // the answer clean. `team` needs the opposite — see keepUnrecognizedJson.
- return keepUnrecognizedJson;
-}
-
-const TERMINAL_STATES: readonly SessionStatus[] = ["completed", "failed", "cancelled", "timeout"];
-
-/**
- * Which states may follow which. Absent from a row ⇒ illegal.
- *
- * The four terminal states have EMPTY rows, which is the whole point: once a
- * supervisor (timeout, cancel, exit classification) has decided how a session
- * ended, nothing may revise it.
- */
-const LEGAL_TRANSITIONS: Record<SessionStatus, readonly SessionStatus[]> = {
- starting: ["running", "tool_executing", "waiting_for_input", "finishing", ...TERMINAL_STATES],
- running: ["tool_executing", "waiting_for_input", "finishing", ...TERMINAL_STATES],
- tool_executing: ["running", "waiting_for_input", "finishing", ...TERMINAL_STATES],
- waiting_for_input: ["running", "tool_executing", ...TERMINAL_STATES],
- // The final turn ended and stdin is closed: only the exit verdict may follow.
- // A frame arriving here is outside the stream-json contract, so it is refused
- // and recorded as an anomaly rather than moving the session backwards.
- finishing: [...TERMINAL_STATES],
- completed: [],
- failed: [],
- cancelled: [],
- // Absorbing, like every other terminal state. `"timeout"` reaches the wire
- // now that EVENT_TO_TASK_STATUS knows how to project it; it used to be
- // laundered into `"failed"` here and re-attached to the record separately.
- timeout: [],
-};
-
-/** Debounce window for batching rapid tool_use frames into one notification. */
-const TOOL_BATCH_MS = 500;
-
-/**
- * Default stream silence before a stall notice, in seconds.
- *
- * Only `starting` and `running` are watched. `tool_executing` is deliberately
- * exempt: a 10-minute `Bash` produces no frames at all and is not stalled, it is
- * working. `waiting_for_input` is exempt for the same reason — silence there is
- * the contract. `finishing` is exempt too: the child is exiting, and the session
- * timeout bounds it.
- */
-const DEFAULT_STALL_SECONDS = 120;
-
-/** How often the stall watchdog looks at the clock. Bounded so tests stay quick. */
-const STALL_TICK_CEILING_MS = 15_000;
-
-/** Bounded per-session record of illegal transitions and unparseable lines. */
-const MAX_ANOMALIES = 50;
-
-/** What the child reported on its terminal `result` frame. */
-export interface ResultSummary {
- /** `subtype`, e.g. "success" / "error_max_turns". */
- subtype: string | null;
- isError: boolean;
- /** `terminal_reason`, e.g. "completed". Null when the field is absent. */
- terminalReason: string | null;
- /** `api_error_status` — a number when the turn died on an upstream status. */
- apiErrorStatus: number | null;
- stopReason: string | null;
- numTurns: number;
- inputTokens: number;
- outputTokens: number;
- permissionDenials: number;
-}
-
-/**
- * The owner's answer, at a turn end, to "does stdin stay open?".
- *
- * - `"stdin-open"` → the session waits for `send_input`: `waiting_for_input`.
- * - `"stdin-closed"` → that was the final turn and the child is exiting:
- * `finishing`, then a terminal state.
- *
- * The reducer cannot see stdin, so it asks. Deciding it here instead is what
- * used to put every one-shot session through a false `waiting_for_input`.
- */
-export type TurnEnd = "stdin-open" | "stdin-closed";
-
-export interface StreamJsonReducerOptions {
- sessionId: string;
- callback: ReducerCallback;
- /** Seconds of stream silence before a stall notice. 0 disables the watchdog. */
- stallSeconds?: number;
- /**
- * Keep JSON lines that are not stream-json vocabulary, instead of dropping
- * them. Default false.
- *
- * The two consumers want opposite things and both are right. A CHANNEL
- * session's stdout is pure stream-json, so a stray JSON object is machine
- * noise and keeping it would pollute the answer. A TEAM slot's response file
- * is the only place a reader ever sees what the child printed, and this
- * project has already lost real answers to a parser that decided something
- * was not worth keeping (see ai-docs/architecture/team-capture.md) — so team
- * preserves anything it does not positively recognise.
- *
- * Note the asymmetry this fixes: an UNPARSEABLE line is kept either way
- * ("keep it, verbatim — it is the only place a reader would ever see it"),
- * so dropping *valid* JSON was the stricter of the two rules, not the looser.
- */
- keepUnrecognizedJson?: boolean;
- /**
- * Fired once per terminal `result` frame, BEFORE the state changes, and its
- * answer decides the state the turn end moves to (see `TurnEnd`).
- * SessionManager closes stdin on a one-shot session's first `result` and
- * answers `"stdin-closed"`, which is what lets the session reach `completed`
- * instead of idling until the timeout; `team` closes stdin at spawn and always
- * answers `"stdin-closed"`.
- *
- * Required, so the compiler names every construction site: a default would
- * silently pick one of the two states for a caller that never decided.
- */
- onResult: (summary: ResultSummary) => TurnEnd;
- /**
- * Every line except the delta firehose, verbatim. Persisted to `events.jsonl`
- * so a post-mortem has the structured record the prose cannot carry.
- *
- * `label` is the frame's `type` (with `:subtype` when it carries one), or null
- * for a line that did not parse as a typed JSON frame. Passed along rather
- * than re-derived by the consumer, which would mean a second `JSON.parse` of
- * every frame purely to name it.
- */
- onSemanticLine?: (line: string, label: string | null) => void;
- /** Recovered assistant prose, streamed as it is decoded. */
- onProse?: (text: string) => void;
-}
-
-/** Shape of the frames we read. Everything is optional — the wire is not ours. */
-interface Frame {
- type?: unknown;
- subtype?: unknown;
- session_id?: unknown;
- cwd?: unknown;
- status?: unknown;
- hook_name?: unknown;
- is_error?: unknown;
- terminal_reason?: unknown;
- api_error_status?: unknown;
- stop_reason?: unknown;
- num_turns?: unknown;
- usage?: { input_tokens?: unknown; output_tokens?: unknown };
- permission_denials?: unknown;
- message?: { content?: unknown };
-}
-
-const asString = (v: unknown): string | null => (typeof v === "string" && v.length > 0 ? v : null);
-const asNumber = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) ? v : 0);
-
-/** `"system:init"`, `"result"`, or null for a line that carried no `type`. */
-function labelFor(type: string | null, subtype: string | null): string | null {
- if (type === null) return null;
- return subtype === null ? type : `${type}:${subtype}`;
-}
-
-/**
- * The same label, for a line read back off `events.jsonl` rather than off the
- * wire.
- *
- * Exported so the disk-recovery path in `SessionManager` cannot invent a second
- * spelling of a label a live session already has a spelling for — two formats
- * for the same frame would make a post-mortem's events unmatchable against a
- * live one's. It re-parses, which the live path must never do: there the frame
- * is already in hand and `labelFor` takes it directly.
- */
-export function labelForLine(line: string): string | null {
- try {
- const parsed: unknown = JSON.parse(line);
- if (!parsed || typeof parsed !== "object") return null;
- const frame = parsed as Frame;
- return labelFor(asString(frame.type), asString(frame.subtype));
- } catch {
- // Not JSON — the same case the reducer records as an unparseable line.
- return null;
- }
-}
-
-export class StreamJsonReducer {
- private _state: SessionStatus = "starting";
- private disposed = false;
-
- /** Incomplete trailing line held until its newline arrives. */
- private pending = "";
- private readonly capture: AssistantTextCapture = createAssistantTextCapture();
-
- private toolBatchTimer: ReturnType<typeof setTimeout> | null = null;
- private toolBatchCount = 0;
- /** How many tools the IMMEDIATE notification already reported, so the batched one adds news. */
- private toolBatchAnnounced = 0;
- private toolBatchName: string | null = null;
-
- private stallTimer: ReturnType<typeof setInterval> | null = null;
- private readonly stallMs: number;
- private lastFrameAt = Date.now();
- /** True while a stall notice is outstanding, so it is announced once per episode. */
- private stallAnnounced = false;
-
- // ─── Accounting, all sourced from the child's own frames ───────────────────
- private _claudeSessionId: string | null = null;
- private _cwd: string | null = null;
- private _turns = 0;
- private _inputTokens = 0;
- private _outputTokens = 0;
- private _toolUseCount = 0;
- private _terminalReason: string | null = null;
- private _apiErrorStatus: number | null = null;
- private _resultIsError = false;
- private _resultSeen = false;
- private readonly _anomalies: string[] = [];
-
- constructor(private readonly opts: StreamJsonReducerOptions) {
- const seconds = opts.stallSeconds ?? DEFAULT_STALL_SECONDS;
- this.stallMs = seconds > 0 ? seconds * 1000 : 0;
- if (this.stallMs > 0) {
- const tick = Math.min(this.stallMs, STALL_TICK_CEILING_MS);
- this.stallTimer = setInterval(() => this.checkStall(), tick);
- // A watchdog must never be the reason a process stays alive.
- this.stallTimer.unref?.();
- }
- }
-
- get state(): SessionStatus {
- return this._state;
- }
- get claudeSessionId(): string | null {
- return this._claudeSessionId;
- }
- /** The child's own report of its working directory, from `system:init`. */
- get cwd(): string | null {
- return this._cwd;
- }
- get turns(): number {
- return this._turns;
- }
- get tokens(): number {
- return this._inputTokens + this._outputTokens;
- }
- get toolUseCount(): number {
- return this._toolUseCount;
- }
- /**
- * Milliseconds since the child last put ANYTHING on stdout.
- *
- * Reported, never acted on. Silence is not a verdict: a child inside a long
- * `Bash` emits no frames and is working, not wedged, which is why
- * `tool_executing` is exempt from the stall notice. The agent asking "when did
- * session X last say something?" has context this class does not, so it gets
- * the number and makes the call — including the call to `cancel_session`.
- *
- * This is the signal `team` used to lack. It polled `stats/<id>.json`, which
- * only advances when tokens flow, so a slot compiling for 90s looked dead and
- * was killed. Frames arrive throughout — Claude Code emits `tool_progress`
- * heartbeats every 30s inside a long tool call — so this number stays honest
- * where a token-flow timestamp does not.
- */
- get idleMs(): number {
- return Math.max(0, Date.now() - this.lastFrameAt);
- }
- get terminalReason(): string | null {
- return this._terminalReason;
- }
- get apiErrorStatus(): number | null {
- return this._apiErrorStatus;
- }
- /** True once a `result` frame arrived. Exit 0 without one has not earned `completed`. */
- get sawResult(): boolean {
- return this._resultSeen;
- }
- get resultIsError(): boolean {
- return this._resultIsError;
- }
- /** Illegal transitions and unparseable lines, bounded. Diagnostics only. */
- get anomalies(): readonly string[] {
- return this._anomalies;
- }
-
- // ─── Input ─────────────────────────────────────────────────────────────────
-
- /** Feed a raw stdout chunk. Returns the assistant prose recovered from it. */
- feed(chunk: string): string {
- if (this.disposed) return "";
-
- this.pending += chunk;
- let prose = "";
- let newlineAt = this.pending.indexOf("\n");
- while (newlineAt !== -1) {
- const line = this.pending.slice(0, newlineAt);
- this.pending = this.pending.slice(newlineAt + 1);
- prose += this.consumeLine(line, true);
- newlineAt = this.pending.indexOf("\n");
- }
- return prose;
- }
-
- /**
- * Flush the trailing partial line and close the answer capture.
- *
- * A child killed mid-frame leaves an incomplete line; it is passed to the same
- * per-line rule, which will fail to parse it and keep it verbatim rather than
- * dropping it.
- */
- end(): string {
- if (this.disposed) return "";
- let prose = "";
- if (this.pending.length > 0) {
- prose += this.consumeLine(this.pending, false);
- this.pending = "";
- }
- const tail = this.capture.end();
- if (tail) {
- prose += tail;
- this.opts.onProse?.(tail);
- }
- return prose;
- }
-
- /**
- * A new turn has just been handed to the child. Clears the PREVIOUS turn's
- * terminal witness.
- *
- * Without this, `sawResult` is session-global and latches true forever: turn
- * 1 answers successfully, `send_input` starts turn 2, the child dies mid-turn
- * and exits 0 — and `classifyExit` finds turn 1's `result` sitting there and
- * calls the run completed. That is the original bug in a new costume, a
- * session reporting success on evidence that does not belong to it, so the
- * witness has to be scoped to the turn that is actually outstanding.
- *
- * `_turns`, the token counters and `_terminalReason` are deliberately NOT
- * reset — they are cumulative session accounting and the last observed
- * reason, not completion evidence.
- *
- * A session that was `waiting_for_input` is no longer waiting once a turn is
- * handed over, so this moves it to `running` — the only transition it makes.
- * From any other state it only resets the flags above.
- */
- beginTurn(): void {
- if (this.disposed) return;
- this._resultSeen = false;
- this._resultIsError = false;
- this._apiErrorStatus = null;
- // A turn was just sent, so the stream is legitimately busy again.
- this.lastFrameAt = Date.now();
- this.stallAnnounced = false;
- if (this._state === "waiting_for_input") {
- this.transition("running", { content: "input received" });
- }
- }
-
- /**
- * A promptless session waits for its first `send_input` from the moment it
- * exists: `starting → waiting_for_input`. A no-op from any other state.
- *
- * Without it such a session read `starting`, then `running` on the child's
- * `system:init`, while nothing would happen until the caller sent input.
- */
- awaitInput(): void {
- if (this.disposed || this._state !== "starting") return;
- this.transition("waiting_for_input", { content: "waiting for the first input" });
- }
-
- /**
- * Move to a terminal state, or to any state a supervisor decides.
- *
- * This is the ONLY way `completed` / `failed` / `cancelled` / `timeout` is
- * reached, and the transition table makes those absorbing — a later caller
- * cannot revise a verdict that has already been recorded.
- */
- settle(state: SessionStatus, opts?: { content?: string }): void {
- if (this.disposed) return;
- this.resetToolBatch();
- this.transition(state, { content: opts?.content });
- }
-
- /** Stop every timer. Called once, from SessionManager's exit/shutdown paths. */
- dispose(): void {
- if (this.disposed) return;
- this.disposed = true;
- this.resetToolBatch();
- if (this.stallTimer) {
- clearInterval(this.stallTimer);
- this.stallTimer = null;
- }
- }
-
- // ─── Internal ──────────────────────────────────────────────────────────────
-
- /**
- * One line of the child's stdout.
- *
- * Order matters: the delta check comes first so the firehose costs one
- * `JSON.parse` and nothing else, and the answer capture is only ever handed
- * lines that could plausibly carry prose.
- */
- private consumeLine(line: string, terminated: boolean): string {
- if (line.trim().length === 0) return "";
-
- this.lastFrameAt = Date.now();
- if (this.stallAnnounced) {
- this.stallAnnounced = false;
- }
-
- let frame: Frame | null = null;
- try {
- const parsed: unknown = JSON.parse(line);
- if (parsed && typeof parsed === "object") frame = parsed as Frame;
- } catch {
- // Not JSON. Rule 2: keep it, verbatim, in the answer — it is the only
- // place a reader would ever see it.
- this.note(`unparseable line: ${line.slice(0, 120)}`);
- }
-
- const type = frame ? asString(frame.type) : null;
-
- // Liveness only. Never stored, never shown, never logged.
- if (type !== null && DELTA_FRAME_TYPES.has(type)) return "";
-
- this.opts.onSemanticLine?.(line, labelFor(type, frame ? asString(frame.subtype) : null));
-
- if (frame && type !== null) this.applyFrame(frame, type);
-
- if (!reachesAnswer(type, frame !== null, this.opts.keepUnrecognizedJson ?? false)) return "";
-
- // The answer capture owns prose recovery; hand it the line exactly as it
- // arrived, newline included, so `outputBytes` agrees with what the child
- // actually wrote.
- const prose = this.capture.write(terminated ? `${line}\n` : line);
- if (prose) this.opts.onProse?.(prose);
- return prose;
- }
-
- private applyFrame(frame: Frame, type: string): void {
- switch (type) {
- case "system":
- this.applySystemFrame(frame);
- return;
-
- case "assistant": {
- const tools = this.toolUseNames(frame);
- if (tools.length > 0) {
- // Every BLOCK, not one per frame. Parallel tool calls are Claude
- // Code's default shape, so counting frames under-reported exactly the
- // metric ("93 tool calls") the silent-success incident was measured by.
- this._toolUseCount += tools.length;
- this.batchToolUse(tools[0], tools.length);
- } else if (this._state === "starting" || this._state === "finishing") {
- // From `finishing` the transition table refuses this and records the
- // anomaly: a frame after the final `result`, with stdin closed, is
- // outside the stream-json contract and must not revive the session.
- this.transition("running", { content: "assistant turn started" });
- }
- return;
- }
-
- case "user":
- // A `tool_result` closes a tool round trip; a replayed user message
- // (`--replay-user-messages`) is the child acking our input. Either way
- // the model is the thing that runs next. From `finishing` the table
- // refuses it and records the anomaly, as for `assistant` above.
- if (
- this._state === "tool_executing" ||
- this._state === "waiting_for_input" ||
- this._state === "finishing"
- ) {
- this.transition("running");
- } else if (this._state === "starting") {
- this.transition("running");
- }
- return;
-
- case "result":
- this.applyResultFrame(frame);
- return;
-
- default:
- // `rate_limit_event` and anything a future Claude Code adds. Recorded on
- // disk by the caller, ignored for state — an unknown frame must never
- // move a state machine.
- return;
- }
- }
-
- private applySystemFrame(frame: Frame): void {
- const subtype = asString(frame.subtype);
-
- if (subtype === "init") {
- this._claudeSessionId = asString(frame.session_id);
- this._cwd = asString(frame.cwd);
- // A promptless session announces itself with `init` while it still waits
- // for its first input; that is not a turn starting, so the wait stands.
- if (this._state === "waiting_for_input") return;
- this.transition("running", { content: "session initialised" });
- return;
- }
-
- // `{"status":"requesting"}` — the child's own first-party liveness signal,
- // emitted at the top of every request. Enough on its own to leave `starting`
- // when partial messages are off.
- if (subtype === "status" && this._state === "starting") {
- this.transition("running", { content: `status: ${asString(frame.status) ?? "requesting"}` });
- return;
- }
-
- // `--include-hook-events` reports the lifecycle of hooks the USER has
- // configured (measured: only `SessionStart` and `Stop` fired, because those
- // are the only two in ~/.claude/settings.json). It does NOT synthesise
- // PreToolUse/PostToolUse, so it is a diagnostic signal, not a state source.
- }
-
- private applyResultFrame(frame: Frame): void {
- const subtype = asString(frame.subtype);
- this._resultSeen = true;
- // `subtype` carries `error_max_turns` / `error_during_execution` — turns
- // that ended badly but do not always set `is_error`. Reading only
- // `is_error` let those through as clean completions.
- this._resultIsError = frame.is_error === true || (subtype?.startsWith("error") ?? false);
- this._terminalReason = asString(frame.terminal_reason);
- this._apiErrorStatus =
- typeof frame.api_error_status === "number" ? frame.api_error_status : null;
- this._turns = asNumber(frame.num_turns) || this._turns;
- this._inputTokens = asNumber(frame.usage?.input_tokens) || this._inputTokens;
- this._outputTokens = asNumber(frame.usage?.output_tokens) || this._outputTokens;
-
- const summary: ResultSummary = {
- subtype,
- isError: this._resultIsError,
- terminalReason: this._terminalReason,
- apiErrorStatus: this._apiErrorStatus,
- stopReason: asString(frame.stop_reason),
- numTurns: this._turns,
- inputTokens: this._inputTokens,
- outputTokens: this._outputTokens,
- permissionDenials: Array.isArray(frame.permission_denials)
- ? frame.permission_denials.length
- : 0,
- };
-
- // The owner decides FIRST whether stdin stays open, and the state follows
- // its answer. A turn boundary with stdin still open IS `waiting_for_input`;
- // one where the owner just closed stdin is `finishing`, and the child walks
- // to a terminal state on its own. Transitioning before asking is what put
- // every one-shot session through a `waiting_for_input` nothing waited in.
- const turnEnd = this.opts.onResult(summary);
- const content = summary.isError
- ? `turn ended with an error (${summary.terminalReason ?? summary.subtype ?? "unknown"})`
- : `turn ${summary.numTurns} complete`;
- this.transition(turnEnd === "stdin-closed" ? "finishing" : "waiting_for_input", { content });
- }
-
- /** Every `tool_use` block in an assistant message, in order. */
- private toolUseNames(frame: Frame): string[] {
- const content = frame.message?.content;
- if (!Array.isArray(content)) return [];
- const names: string[] = [];
- for (const raw of content) {
- const block = raw as { type?: unknown; name?: unknown };
- if (block?.type === "tool_use") names.push(asString(block.name) ?? "unknown");
- }
- return names;
- }
-
- /**
- * Announce the first tool immediately, then one aggregated notification per
- * burst. A batch of eight parallel Reads is one useful line, not eight.
- */
- private batchToolUse(toolName: string, count = 1): void {
- this.toolBatchCount += count;
- this.toolBatchName = toolName;
-
- if (this._state !== "tool_executing") {
- this.transition("tool_executing", { toolName, toolCount: count });
- this.toolBatchAnnounced = count;
- }
-
- if (this.toolBatchTimer) clearTimeout(this.toolBatchTimer);
- this.toolBatchTimer = setTimeout(() => {
- this.toolBatchTimer = null;
- // The batch is only ever a NOTIFICATION about the state we are still in.
- // `transition` already cancels a pending batch on any move away from
- // `tool_executing`, and this second check covers the ordering where the
- // timer was already in the macrotask queue when that move happened:
- // firing then would have dragged a `running` (final text being generated)
- // or a `waiting_for_input` session back to `tool_executing` with no tool
- // running at all.
- if (
- !this.disposed &&
- this._state === "tool_executing" &&
- this.toolBatchCount > 1 &&
- this.toolBatchCount > this.toolBatchAnnounced
- ) {
- this.transition("tool_executing", {
- toolName: this.toolBatchName ?? undefined,
- toolCount: this.toolBatchCount,
- repeat: true,
- });
- }
- this.toolBatchCount = 0;
- this.toolBatchAnnounced = 0;
- this.toolBatchName = null;
- }, TOOL_BATCH_MS);
- this.toolBatchTimer.unref?.();
- }
-
- /**
- * Report — never terminate — a stream that has gone quiet where it should not
- * be quiet.
- *
- * This is the 900-second case made visible. Terminating is the session
- * timeout's job; this only ensures the agent is not staring at a state that
- * has not changed in ten minutes with no way to tell working from wedged.
- */
- private checkStall(): void {
- if (this.disposed || this.stallAnnounced) return;
- if (this._state !== "starting" && this._state !== "running") return;
- const idleMs = Date.now() - this.lastFrameAt;
- if (idleMs < this.stallMs) return;
-
- this.stallAnnounced = true;
- this.transition(this._state, {
- repeat: true,
- content: `no output from the child for ${Math.round(idleMs / 1000)}s`,
- stalled: true,
- });
- }
-
- private transition(newState: SessionStatus, extra?: Partial<ReducerEvent>): void {
- const prev = this._state;
-
- if (prev === newState) {
- // Self-transitions are only ever notifications (batched tools, stall
- // notices). Everything else would be wire spam.
- if (!extra?.repeat) return;
- } else if (!LEGAL_TRANSITIONS[prev].includes(newState)) {
- // Loud, but not fatal: this runs inside a stdout data handler on the MCP
- // server's event loop, and throwing here would take down every other
- // session with it. Recording + refusing is what kills the original bug —
- // an exit must never upgrade a verdict a supervisor already reached.
- this.note(
- `illegal transition ${prev} → ${newState}${TERMINAL_STATES.includes(prev) ? " (terminal state is absorbing)" : ""}`
- );
- return;
- }
-
- // Leaving `tool_executing` invalidates any batch still being accumulated.
- // Without this the debounce timer outlives the state it describes: a
- // `user` frame carrying the tool_result moves the session to `running`,
- // the model starts its final text, and 450 ms later the stale timer yanks
- // it back to `tool_executing` — a state change the child never reported.
- if (newState !== "tool_executing") this.resetToolBatch();
-
- this._state = newState;
-
- this.opts.callback(this.opts.sessionId, {
- previousState: prev,
- newState,
- timestamp: new Date().toISOString(),
- ...extra,
- });
- }
-
- /** Record an anomaly. Bounded — a pathological stream must not become a leak. */
- private note(text: string): void {
- if (this._anomalies.length >= MAX_ANOMALIES) return;
- this._anomalies.push(text);
- if (process.env.CLAUDISH_CHANNEL_TRACE === "1") {
- process.stderr.write(`[channel-trace] reducer sid=${this.opts.sessionId} ${text}\n`);
- }
- }
-
- /** Drop the pending tool batch: its timer, its count, and its name. */
- private resetToolBatch(): void {
- if (this.toolBatchTimer) {
- clearTimeout(this.toolBatchTimer);
- this.toolBatchTimer = null;
- }
- this.toolBatchCount = 0;
- this.toolBatchAnnounced = 0;
- this.toolBatchName = null;
- }
-}
diff --git a/packages/cli/src/channel/test-helpers/captured-stream-json.ts b/packages/cli/src/channel/test-helpers/captured-stream-json.ts
deleted file mode 100644
index ec99a2d9..00000000
--- a/packages/cli/src/channel/test-helpers/captured-stream-json.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-import { readFileSync } from "node:fs";
-import { resolve } from "node:path";
-
-/**
- * Test fixtures sourced from the real Claude Code 2.1.239 probe captures.
- *
- * The probe deliberately saved only the first 700/900 bytes of each distinct
- * frame (see the probe scripts beside the samples). Short frames are replayed
- * byte-for-byte. The captured assistant frame is complete through its message,
- * session id, uuid, and timestamp; only the cut-off `request...` suffix is
- * removed before closing the outer object so it is valid NDJSON again.
- */
-
-// TRACKED, deliberately. These captures previously lived in
-// `ai-docs/sessions/dev-arch-.../probes`, which `.gitignore:56` excludes — so the
-// tests passed on the machine that recorded them and FAILED in CI, which clones
-// fresh and has no session directory. CLAUDE.md names this exact trap ("three
-// write-ups already died this way"); this was the fourth. A test fixture is
-// something meant to outlive the session, so it belongs next to the test.
-const PROBE_DIR = resolve(import.meta.dir, "captures");
-
-export const BIDIRECTIONAL_CAPTURE_PATH = resolve(PROBE_DIR, "samples-bidirectional.txt");
-export const TOOL_TURN_CAPTURE_PATH = resolve(PROBE_DIR, "samples-tool-turn.txt");
-
-const bidirectionalLines = readFileSync(BIDIRECTIONAL_CAPTURE_PATH, "utf-8")
- .split("\n")
- .filter((line) => line.trim().length > 0);
-const toolTurnLines = readFileSync(TOOL_TURN_CAPTURE_PATH, "utf-8")
- .split("\n")
- .filter((line) => line.trim().length > 0);
-
-function requiredLine(lines: readonly string[], marker: string): string {
- const line = lines.find((candidate) => candidate.includes(marker));
- if (!line) throw new Error(`Captured stream-json fixture is missing ${marker}`);
- return line;
-}
-
-/** A complete real `system:status` frame, replayed byte-for-byte. */
-export const CAPTURED_STATUS_LINE = requiredLine(bidirectionalLines, '"subtype":"status"');
-
-/** A complete real partial-message delta, replayed byte-for-byte. */
-export const CAPTURED_DELTA_LINE = requiredLine(bidirectionalLines, '"type":"content_block_delta"');
-
-/** A complete real rate-limit frame, replayed byte-for-byte. */
-export const CAPTURED_RATE_LIMIT_LINE = requiredLine(
- bidirectionalLines,
- '"type":"rate_limit_event"'
-);
-
-/**
- * The real ALPHA assistant frame with only the probe's truncated suffix
- * removed. The assistant message itself is untouched.
- */
-export const CAPTURED_ASSISTANT_FRAME = (() => {
- const prefix = requiredLine(bidirectionalLines, '"type":"assistant"');
- const truncationAt = prefix.lastIndexOf(',"reques');
- if (truncationAt === -1) {
- throw new Error("Captured assistant fixture no longer has the expected probe truncation");
- }
- return JSON.parse(`${prefix.slice(0, truncationAt)}}`) as Record<string, unknown>;
-})();
-
-/** Exact prose carried by the captured assistant frame (`ALPHA`). */
-export const CAPTURED_ASSISTANT_PROSE = (() => {
- const message = CAPTURED_ASSISTANT_FRAME.message as {
- content?: Array<{ type?: unknown; text?: unknown }>;
- };
- const text = message.content?.find((block) => block.type === "text")?.text;
- if (typeof text !== "string") throw new Error("Captured assistant fixture has no text block");
- return text;
-})();
-
-/**
- * A minimal projection of the real captured terminal result.
- *
- * The result sample is cut at 900 bytes inside its usage detail. These fields
- * all occur before that cut and are extracted from the capture rather than
- * invented. `type: result` is the discriminator the probe used to select the
- * sample (its property occurs after the cut in Claude Code's serialized order).
- */
-export function capturedSuccessResult(result: string, numTurns = 1): Record<string, unknown> {
- const prefix = requiredLine(toolTurnLines, '"is_error":false');
- const parsedBoolean = /"is_error":(true|false)/.exec(prefix)?.[1] === "true";
- const stopReason = /"stop_reason":"([^"]+)"/.exec(prefix)?.[1] ?? null;
- const sessionId = /"session_id":"([^"]+)"/.exec(prefix)?.[1] ?? null;
- const inputTokens = Number(/"input_tokens":(\d+)/.exec(prefix)?.[1] ?? 0);
- const outputTokens = Number(/"output_tokens":(\d+)/.exec(prefix)?.[1] ?? 0);
-
- return {
- type: "result",
- subtype: "success",
- is_error: parsedBoolean,
- num_turns: numTurns,
- stop_reason: stopReason,
- session_id: sessionId,
- usage: { input_tokens: inputTokens, output_tokens: outputTokens },
- terminal_reason: "completed",
- api_error_status: null,
- result,
- };
-}
-
-/** Clone the captured assistant frame, optionally replacing only its text. */
-export function capturedAssistantFrame(text = CAPTURED_ASSISTANT_PROSE): Record<string, unknown> {
- const frame = structuredClone(CAPTURED_ASSISTANT_FRAME) as {
- message: { content: Array<{ type?: unknown; text?: unknown }> };
- };
- const block = frame.message.content.find((candidate) => candidate.type === "text");
- if (!block) throw new Error("Captured assistant fixture has no text block");
- block.text = text;
- return frame as Record<string, unknown>;
-}
diff --git a/packages/cli/src/channel/test-helpers/captures/samples-bidirectional.txt b/packages/cli/src/channel/test-helpers/captures/samples-bidirectional.txt
deleted file mode 100644
index 62554066..00000000
--- a/packages/cli/src/channel/test-helpers/captures/samples-bidirectional.txt
+++ /dev/null
@@ -1,27 +0,0 @@
-{"type":"system","subtype":"hook_started","hook_id":"06073859-363f-4efa-adf2-5787c46d68c3","hook_name":"SessionStart:startup","hook_event":"SessionStart","uuid":"60e2ce20-c214-4e01-8b9d-43fec675ed7a","session_id":"0f0e9618-b6df-406b-a63b-79e5ef75b4a9"}
-
-{"type":"system","subtype":"hook_response","hook_id":"06073859-363f-4efa-adf2-5787c46d68c3","hook_name":"SessionStart:startup","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"38b0f12e-5898-4b37-bd2f-89d3de40bac7","session_id":"0f0e9618-b6df-406b-a63b-79e5ef75b4a9"}
-
-{"type":"system","subtype":"init","cwd":"/private/tmp/cc-streamin-probe","session_id":"0f0e9618-b6df-406b-a63b-79e5ef75b4a9","tools":["Task","Bash","CronCreate","CronDelete","CronList","DesignSync","Edit","EnterWorktree","ExitWorktree","ListAgents","ListMcpResourcesTool","Monitor","NotebookEdit","PushNotification","Read","ReadMcpResourceDirTool","ReadMcpResourceTool","RemoteTrigger","ReportFindings","ScheduleWakeup","SendMessage","Skill","TaskOutput","TaskStop","ToolSearch","WebFetch","WebSearch","Workflow","Write","mcp__claude_ai_Canva__comment-on-design","mcp__claude_ai_Canva__copy-design","mcp__claude_ai_Canva__create-brand-template-draft","mcp__claude_ai_Canva__create-design-from-brand-t
-
-{"type":"system","subtype":"status","status":"requesting","uuid":"57005839-8b40-43c9-a880-8b4125975700","session_id":"0f0e9618-b6df-406b-a63b-79e5ef75b4a9"}
-
-{"type":"user","message":{"role":"user","content":[{"type":"text","text":"Say exactly: ALPHA"}]},"session_id":"0f0e9618-b6df-406b-a63b-79e5ef75b4a9","parent_tool_use_id":null,"uuid":"080f7f2e-5478-4537-908f-e651cbec5df9","timestamp":"2026-08-22T01:54:52.855Z","isReplay":true}
-
-{"type":"stream_event","event":{"type":"message_start","message":{"model":"claude-opus-5","id":"msg_011CeGxHf8FUzRgeCXbDy5ix","type":"message","role":"assistant","content":[],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":18550,"cache_read_input_tokens":15933,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":18550},"output_tokens":3,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null}},"session_id":"0f0e9618-b6df-406b-a63b-79e5ef75b4a9","parent_tool_use_id":null,"uuid":"2a9d6b20-856d-4c2c-9a5e-d08dee8d1eb4","ttft_ms":1039}
-
-{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}},"session_id":"0f0e9618-b6df-406b-a63b-79e5ef75b4a9","parent_tool_use_id":null,"uuid":"aee20a75-3311-4c64-87ea-a6aea667dfe8"}
-
-{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ALP"}},"session_id":"0f0e9618-b6df-406b-a63b-79e5ef75b4a9","parent_tool_use_id":null,"uuid":"6b8cdc3a-e11e-4a83-8184-636da5d0a5c6"}
-
-{"type":"assistant","message":{"model":"claude-opus-5","id":"msg_011CeGxHf8FUzRgeCXbDy5ix","type":"message","role":"assistant","content":[{"type":"text","text":"ALPHA"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":18550,"cache_read_input_tokens":15933,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":18550},"output_tokens":3,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"0f0e9618-b6df-406b-a63b-79e5ef75b4a9","uuid":"6b874723-9a52-4439-99d0-2102484f9bd3","timestamp":"2026-08-22T01:54:54.545Z","reques
-
-{"type":"stream_event","event":{"type":"content_block_stop","index":0},"session_id":"0f0e9618-b6df-406b-a63b-79e5ef75b4a9","parent_tool_use_id":null,"uuid":"33aac61a-0bdc-4a5b-a179-298c8d665f04"}
-
-{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null,"stop_details":null},"usage":{"input_tokens":2,"cache_creation_input_tokens":18550,"cache_read_input_tokens":15933,"output_tokens":7,"output_tokens_details":{"thinking_tokens":0},"iterations":[{"input_tokens":2,"output_tokens":7,"cache_read_input_tokens":15933,"cache_creation_input_tokens":18550,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":18550},"type":"message"}]},"context_management":{"applied_edits":[]}},"session_id":"0f0e9618-b6df-406b-a63b-79e5ef75b4a9","parent_tool_use_id":null,"uuid":"58489f38-bbe8-4134-8ab3-17cf136baedf"}
-
-{"type":"stream_event","event":{"type":"message_stop"},"session_id":"0f0e9618-b6df-406b-a63b-79e5ef75b4a9","parent_tool_use_id":null,"uuid":"078f0f83-d7d3-4b3a-aa4d-a820b356e46f"}
-
-{"type":"rate_limit_event","rate_limit_info":{"status":"allowed","resetsAt":1787372400,"rateLimitType":"five_hour","overageStatus":"allowed","overageResetsAt":1788220800,"isUsingOverage":false},"uuid":"a833f48d-e85b-41ca-bf17-f91dba355a1d","session_id":"0f0e9618-b6df-406b-a63b-79e5ef75b4a9"}
-
-{"is_error":false,"duration_api_ms":1639,"num_turns":1,"stop_reason":"end_turn","session_id":"0f0e9618-b6df-406b-a63b-79e5ef75b4a9","total_cost_usd":0.1936515,"usage":{"input_tokens":2,"cache_creation_input_tokens":18550,"cache_read_input_tokens":15933,"output_tokens":7,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":18550,"ephemeral_5m_input_tokens":0},"inference_geo":"not_available","iterations":[{"input_tokens":2,"output_tokens":7,"cache_read_input_tokens":15933,"cache_creation_input_tokens":18550,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemera
\ No newline at end of file
diff --git a/packages/cli/src/channel/test-helpers/captures/samples-tool-turn.txt b/packages/cli/src/channel/test-helpers/captures/samples-tool-turn.txt
deleted file mode 100644
index c0cd30d3..00000000
--- a/packages/cli/src/channel/test-helpers/captures/samples-tool-turn.txt
+++ /dev/null
@@ -1,15 +0,0 @@
-{"type":"system","subtype":"hook_started","hook_id":"f59b809a-3909-47bf-a3fb-f24fb7cd4a1c","hook_name":"SessionStart:startup","hook_event":"SessionStart","uuid":"9354f3c6-5d4f-4447-b325-03937235ecd6","session_id":"e1c2c275-4fbf-40c3-b261-48c985c43320"}
-
-{"type":"system","subtype":"hook_response","hook_id":"f59b809a-3909-47bf-a3fb-f24fb7cd4a1c","hook_name":"SessionStart:startup","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"063de96f-cf07-446f-a430-7cd6e822e42d","session_id":"e1c2c275-4fbf-40c3-b261-48c985c43320"}
-
-{"type":"system","subtype":"init","cwd":"/private/tmp/cc-tool-probe","session_id":"e1c2c275-4fbf-40c3-b261-48c985c43320","tools":["Task","Bash","CronCreate","CronDelete","CronList","DesignSync","Edit","EnterWorktree","ExitWorktree","ListAgents","ListMcpResourcesTool","Monitor","NotebookEdit","PushNotification","Read","ReadMcpResourceDirTool","ReadMcpResourceTool","RemoteTrigger","ReportFindings","ScheduleWakeup","SendMessage","Skill","TaskOutput","TaskStop","ToolSearch","WebFetch","WebSearch","Workflow","Write","mcp__claude_ai_Gmail__apply_sensitive_message_label","mcp__claude_ai_Gmail__apply_sensitive_thread_label","mcp__claude_ai_Gmail__create_draft","mcp__claude_ai_Gmail__create_label","mcp__claude_ai_Gmail__delete_label","mcp__claude_ai_Gmail__forward","mcp__claude_ai_Gmail__get_message","mcp__claude_ai_Gmail__get_thread","mcp__claude_ai_Gmail__label_message","mcp__claude_ai_Gmail__l
-
-{"type":"system","subtype":"status","status":"requesting","uuid":"a84d4698-9407-4c3d-b104-b919f8dbefe4","session_id":"e1c2c275-4fbf-40c3-b261-48c985c43320"}
-
-{"type":"system","subtype":"status","status":"requesting","uuid":"efbfc86b-7177-4fa0-8276-1de6d42e1bfe","session_id":"e1c2c275-4fbf-40c3-b261-48c985c43320"}
-
-{"type":"system","subtype":"hook_started","hook_id":"4b215889-8992-4423-a83e-a885d80c5c32","hook_name":"Stop","hook_event":"Stop","uuid":"f713261a-cb18-4632-90ed-02b27c0d3590","session_id":"e1c2c275-4fbf-40c3-b261-48c985c43320"}
-
-{"type":"system","subtype":"hook_response","hook_id":"4b215889-8992-4423-a83e-a885d80c5c32","hook_name":"Stop","hook_event":"Stop","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"1f73e5ea-45b8-4d58-869f-2f0bea76a940","session_id":"e1c2c275-4fbf-40c3-b261-48c985c43320"}
-
-{"is_error":false,"duration_api_ms":2905,"num_turns":2,"stop_reason":"end_turn","session_id":"e1c2c275-4fbf-40c3-b261-48c985c43320","total_cost_usd":0.254413,"usage":{"input_tokens":4,"cache_creation_input_tokens":22716,"cache_read_input_tokens":49766,"output_tokens":94,"output_tokens_details":{"thinking_tokens":0},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":22716,"ephemeral_5m_input_tokens":0},"inference_geo":"not_available","iterations":[{"input_tokens":2,"output_tokens":15,"cache_read_input_tokens":33833,"cache_creation_input_tokens":4816,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":4816},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-opus-5[1m]":{"inputTokens":4,"outputTokens":94,"cacheReadInputTokens":49766,"cacheCreationInputTokens":22716,"webS
\ No newline at end of file
diff --git a/packages/cli/src/channel/test-helpers/fake-channel-stream-json.ts b/packages/cli/src/channel/test-helpers/fake-channel-stream-json.ts
deleted file mode 100644
index 338f6bb7..00000000
--- a/packages/cli/src/channel/test-helpers/fake-channel-stream-json.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-#!/usr/bin/env bun
-/**
- * Captured-frame stream-json stand-in used by session-manager.test.ts.
- *
- * It announces a real status frame at startup, reads newline-delimited user
- * frames for as long as stdin remains open, emits captured assistant prose plus
- * a terminal result for each turn, and exits only after stdin closes.
- */
-
-import {
- CAPTURED_ASSISTANT_PROSE,
- CAPTURED_STATUS_LINE,
- capturedAssistantFrame,
- capturedSuccessResult,
-} from "./captured-stream-json.js";
-
-const args = process.argv.slice(2);
-
-function getFlag(name: string): string | null {
- const index = args.indexOf(name);
- return index === -1 ? null : (args[index + 1] ?? null);
-}
-
-function hasFlag(name: string): boolean {
- return args.includes(name);
-}
-
-function writeFrame(frame: Record<string, unknown>): void {
- process.stdout.write(`${JSON.stringify(frame)}\n`);
-}
-
-function assertUserFrame(inputLine: string): void {
- const input = JSON.parse(inputLine) as {
- type?: unknown;
- message?: { role?: unknown; content?: Array<{ type?: unknown; text?: unknown }> };
- };
- if (
- input.type !== "user" ||
- input.message?.role !== "user" ||
- input.message.content?.[0]?.type !== "text" ||
- typeof input.message.content[0].text !== "string"
- ) {
- throw new Error(`invalid user frame: ${inputLine}`);
- }
-}
-
-function emitTurn(turns: number, printArgv: boolean, messageCount: number): void {
- const prose = printArgv ? JSON.stringify(args) : CAPTURED_ASSISTANT_PROSE;
- const count = printArgv ? 1 : Math.max(1, messageCount);
- for (let index = 0; index < count; index++) {
- writeFrame(capturedAssistantFrame(prose));
- }
- writeFrame(capturedSuccessResult(prose, turns));
-}
-
-async function main(): Promise<void> {
- process.stdout.write(`${CAPTURED_STATUS_LINE}\n`);
-
- if (hasFlag("--trap-term-exit-zero")) {
- process.on("SIGTERM", () => process.exit(0));
- }
-
- if (hasFlag("--fail")) process.exit(1);
-
- const sleepValue = getFlag("--sleep");
- if (sleepValue !== null) {
- await new Promise((resolve) => setTimeout(resolve, Number.parseFloat(sleepValue) * 1000));
- process.exit(0);
- }
-
- const messageCount = Number.parseInt(getFlag("--messages") ?? "1", 10);
- const printArgv = hasFlag("--print-argv");
- let pending = "";
- let turns = 0;
-
- process.stdin.setEncoding("utf-8");
- process.stdin.on("data", (chunk: string) => {
- pending += chunk;
- let newlineAt = pending.indexOf("\n");
- while (newlineAt !== -1) {
- const inputLine = pending.slice(0, newlineAt);
- pending = pending.slice(newlineAt + 1);
- newlineAt = pending.indexOf("\n");
- if (!inputLine.trim()) continue;
-
- assertUserFrame(inputLine);
- emitTurn(++turns, printArgv, messageCount);
- // Stdin deliberately remains open after the result in interactive mode.
- }
- });
-
- process.stdin.on("end", () => {
- setTimeout(() => process.exit(0), 20);
- });
-}
-
-main().catch((error) => {
- process.stderr.write(`${String(error)}\n`);
- process.exit(1);
-});
diff --git a/packages/cli/src/channel/test-helpers/fake-claudish.ts b/packages/cli/src/channel/test-helpers/fake-claudish.ts
deleted file mode 100644
index ca351c4b..00000000
--- a/packages/cli/src/channel/test-helpers/fake-claudish.ts
+++ /dev/null
@@ -1,239 +0,0 @@
-#!/usr/bin/env bun
-/**
- * Stream-json claudish stand-in used by:
- * - packages/cli/src/channel/session-manager.test.ts
- * - packages/cli/src/team-orchestrator.test.ts (--print-argv pins the exact spawn contract,
- * including flag order)
- * - focused spawn-environment tests (--print-env reports one selected variable)
- * A flag unused by one consumer may be load-bearing for the other; running only the channel
- * suite will not catch its removal.
- */
-
-const args = process.argv.slice(2);
-
-function getFlag(name: string): string | null {
- const index = args.indexOf(name);
- return index === -1 ? null : (args[index + 1] ?? null);
-}
-
-function hasFlag(name: string): boolean {
- return args.includes(name);
-}
-
-function write(frame: Record<string, unknown>): void {
- process.stdout.write(`${JSON.stringify(frame)}\n`);
-}
-
-function sleep(ms: number): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, ms));
-}
-
-const sessionId = getFlag("--session-id") ?? "fake-0000-1111-2222-333333333333";
-
-async function runTurn(turn: number, inputLine: string): Promise<void> {
- const input = JSON.parse(inputLine) as {
- type?: unknown;
- message?: { role?: unknown; content?: Array<{ type?: unknown; text?: unknown }> };
- };
- if (
- input.type !== "user" ||
- input.message?.role !== "user" ||
- input.message.content?.[0]?.type !== "text" ||
- typeof input.message.content[0].text !== "string"
- ) {
- throw new Error(`invalid user frame: ${inputLine}`);
- }
-
- if (turn === 1) {
- write({
- type: "system",
- subtype: "hook_started",
- hook_name: "SessionStart:startup",
- hook_event: "SessionStart",
- session_id: sessionId,
- });
- write({
- type: "system",
- subtype: "hook_response",
- hook_name: "SessionStart:startup",
- exit_code: 0,
- outcome: "success",
- session_id: sessionId,
- });
- write({
- type: "system",
- subtype: "init",
- cwd: process.cwd(),
- session_id: sessionId,
- tools: ["Bash", "Read"],
- });
- }
-
- write({ type: "system", subtype: "status", status: "requesting", session_id: sessionId });
- write({ type: "user", message: input.message, session_id: sessionId, isReplay: true });
- await sleep(20);
- write({
- type: "stream_event",
- event: { type: "message_start", message: { model: "fake", usage: {} } },
- session_id: sessionId,
- ttft_ms: 12,
- });
-
- const lineCount = Number.parseInt(getFlag("--lines") ?? "0", 10);
- if (lineCount > 0) {
- for (let line = 1; line <= lineCount; line++) {
- write({
- type: "assistant",
- message: {
- model: "fake",
- role: "assistant",
- content: [{ type: "text", text: `line ${line}` }],
- },
- session_id: sessionId,
- });
- }
- } else {
- for (const fragment of ["Hel", "lo ", "from ", "the ", "fake ", "child"]) {
- write({
- type: "stream_event",
- event: {
- type: "content_block_delta",
- index: 0,
- delta: { type: "text_delta", text: fragment },
- },
- session_id: sessionId,
- });
- }
- write({
- type: "assistant",
- message: {
- model: "fake",
- role: "assistant",
- content: [{ type: "text", text: `Hello from the fake child (turn ${turn})` }],
- },
- session_id: sessionId,
- });
- write({
- type: "assistant",
- message: {
- model: "fake",
- role: "assistant",
- content: [{ type: "tool_use", id: "t1", name: "Bash", input: { command: "true" } }],
- },
- session_id: sessionId,
- });
- await sleep(20);
- process.stdout.write(
- "Client.listTools() called but server does not advertise tools capability - returning empty list\n"
- );
- write({
- type: "user",
- message: {
- role: "user",
- content: [{ type: "tool_result", tool_use_id: "t1", content: "ok" }],
- },
- session_id: sessionId,
- });
- write({
- type: "assistant",
- message: {
- model: "fake",
- role: "assistant",
- content: [{ type: "text", text: "ANSWER-MARKER done." }],
- },
- session_id: sessionId,
- });
- write({
- type: "rate_limit_event",
- rate_limit_info: { status: "allowed" },
- session_id: sessionId,
- });
- }
-
- write({
- type: "result",
- subtype: "success",
- is_error: false,
- num_turns: turn,
- stop_reason: "end_turn",
- session_id: sessionId,
- total_cost_usd: 0.42,
- usage: { input_tokens: 1234, output_tokens: 56 },
- permission_denials: [],
- terminal_reason: "completed",
- api_error_status: null,
- result: lineCount > 0 ? `line ${lineCount}` : "ANSWER-MARKER done.",
- duration_ms: 200,
- });
-}
-
-async function main(): Promise<void> {
- // --print-argv: expose the exact spawn contract to parent-process tests
- if (hasFlag("--print-argv")) {
- process.stdout.write(`${JSON.stringify(args)}\n`);
- process.exit(0);
- }
-
- // --print-env <NAME>: expose one selected child env value as ordinary
- // stream-json prose. Existing modes stay byte-for-byte unchanged, while
- // both channel and team supervisors can inspect the actual spawn env.
- const envName = getFlag("--print-env");
- if (envName !== null) {
- const answer = JSON.stringify({ [envName]: process.env[envName] ?? null });
- write({
- type: "assistant",
- message: {
- model: "fake",
- role: "assistant",
- content: [{ type: "text", text: answer }],
- },
- session_id: sessionId,
- });
- write({
- type: "result",
- subtype: "success",
- is_error: false,
- num_turns: 1,
- stop_reason: "end_turn",
- session_id: sessionId,
- terminal_reason: "completed",
- api_error_status: null,
- usage: { input_tokens: 0, output_tokens: 0 },
- permission_denials: [],
- result: answer,
- });
- process.exit(0);
- }
-
- if (hasFlag("--fail")) process.exit(1);
-
- const sleepSeconds = getFlag("--sleep");
- if (sleepSeconds !== null) {
- await sleep(Number.parseFloat(sleepSeconds) * 1000);
- process.exit(0);
- }
-
- let pending = "";
- let turns = 0;
- let turnQueue = Promise.resolve();
- process.stdin.setEncoding("utf-8");
- process.stdin.on("data", (chunk: string) => {
- pending += chunk;
- let newlineAt = pending.indexOf("\n");
- while (newlineAt !== -1) {
- const line = pending.slice(0, newlineAt);
- pending = pending.slice(newlineAt + 1);
- newlineAt = pending.indexOf("\n");
- if (!line.trim()) continue;
- turnQueue = turnQueue.then(() => runTurn(++turns, line));
- }
- });
- process.stdin.on("end", () => {
- void turnQueue.finally(() => setTimeout(() => process.exit(0), 20));
- });
-}
-
-main().catch((error) => {
- process.stderr.write(`${String(error)}\n`);
- process.exit(1);
-});
diff --git a/packages/cli/src/channel/types.ts b/packages/cli/src/channel/types.ts
index 105d0282..5aaeb6bc 100644
--- a/packages/cli/src/channel/types.ts
+++ b/packages/cli/src/channel/types.ts
@@ -1,26 +1,18 @@
// ─── Channel Mode Types ──────────────────────────────────────────────────────
-export type SessionStatus =
- | "starting"
- | "running"
- | "tool_executing"
- | "waiting_for_input"
- /**
- * The session's FINAL turn ended and claudish closed the child's stdin; the
- * child has not exited yet. Non-terminal, and nothing waits for input: only
- * a terminal state follows. Distinct from `waiting_for_input`, which holds
- * only while stdin stays open and the session waits for `send_input`.
- */
- | "finishing"
- | "completed"
- | "failed"
- | "cancelled"
- | "timeout";
+import type { FailureReason, PaneSessionOptions, SlotState } from "../pane/index.js";
/**
* Every value the channel wire's `event` field may carry, as a runtime list so a
* test can walk it (`event-task-status.test.ts` checks each one against
* `EVENT_TO_TASK_STATUS`). `ChannelEventType` is derived from it.
+ *
+ * It is its own union, derived from the session's `SlotState` by `channelEventFor`
+ * (session-manager.ts): the stream-json `SessionStatus` it once mirrored is gone with
+ * that transport. 10.4.0's `finishing` is not here (architecture §20.3 item 5, RB1): a
+ * pane session decides a one-shot verdict at settle, so the "exiting" interval it named
+ * does not exist; the wait for Claude Code's end-of-turn record is `activity:"finishing"`
+ * on a RUNNING row.
*/
export const CHANNEL_EVENT_TYPES = [
"starting",
@@ -29,7 +21,6 @@ export const CHANNEL_EVENT_TYPES = [
"waiting_for_input",
/** A tool call waits on Claude Code's permission dialog; answered with `send_input`. */
"awaiting_permission",
- "finishing",
"completed",
"failed",
"cancelled",
@@ -37,104 +28,85 @@ export const CHANNEL_EVENT_TYPES = [
] as const;
/**
- * The values the channel wire's `event` field may carry: every `SessionStatus`, plus
- * `awaiting_permission`, which a session reports on the wire while a permission
- * dialog is open (the interactive pane transport; `SessionStatus` is retired with the
- * stream-json transport).
+ * The values the channel wire's `event` field may carry.
*
- * The record and the wire did not always agree. This alias was `Exclude<SessionStatus, "timeout">`,
- * because `EVENT_TO_TASK_STATUS` (mcp-server.ts) maps the event enum onto
- * SEP-1686's 5-value `TaskStatus` and had **no `"timeout"` key**: it fell
- * through to `?? "working"`, so emitting `"timeout"` reported a dead session as
- * still working. The timeout path therefore recorded `"timeout"` and emitted
- * `"failed"`, and a consumer watching only the wire could not tell a session
- * that ran out of time from one that errored.
- *
- * `["timeout", "failed"]` now exists in that map — SEP-1686 has no `timeout`
- * member and `failed` is its only honest projection — so the divergence is gone
- * and `ReducerEvent` no longer carries a `sessionStatus` override.
+ * `EVENT_TO_TASK_STATUS` (mcp-server.ts) maps each onto SEP-1686's 5-value
+ * `TaskStatus`; it is a `Record` over this type, so an event without a projection is a
+ * compile error. `timeout` has its own key (→ `failed`): before it existed the timeout
+ * path fell through to `?? "working"` and reported a dead session as still working.
*/
export type ChannelEventType = (typeof CHANNEL_EVENT_TYPES)[number];
-// Compile-time: the list holds every SessionStatus (a status missing from it would
-// be emitted on the wire without a SEP-1686 projection test).
-type _MissingStatus = Exclude<SessionStatus, ChannelEventType>;
-const _everyStatusIsAnEvent: [_MissingStatus] extends [never] ? true : never = true;
-void _everyStatusIsAnEvent;
-
+/**
+ * One channel session, in memory (architecture §3.3). Persisted as `meta.json` through
+ * `toMetaRecord`, which keeps every 10.4.0 key under its 10.4.0 name (the magus monitor
+ * reads them) and adds the pane keys.
+ */
export interface SessionInfo {
sessionId: string;
+ /** The model as the caller asked for it; the display identity, never rewritten. */
model: string;
/**
- * The explicit `provider@model` spec the child was actually SPAWNED with, when
- * the parent pinned one (see `prehydrateCredentialsForSpawn`). Null means the
- * child was handed `model` verbatim and did its own routing.
- *
- * `model` is the display identity an agent correlates on and is never
- * rewritten, so without this field the resolved half of the chain is invisible
- * — and "which provider actually served this?" is the first question a routing
- * failure raises.
+ * The explicit `provider@model` spec the child was actually SPAWNED with, when the
+ * parent pinned one (see `prehydrateCredentialsForSpawn`). Null means the child was
+ * handed `model` verbatim and did its own routing.
*/
spawnModel: string | null;
- status: SessionStatus;
- pid: number | null;
+ /** Display name of the claudish provider serving it; null until known. */
+ provider: string | null;
+ state: SlotState;
+ /** "one-shot" when created with a prompt; a send_input converts it to "interactive". */
+ shape: "one-shot" | "interactive";
+ /** Informational pane id; null when no pane was ever spawned. */
+ pane: string | null;
+ panePid: number | null;
startedAt: string;
completedAt: string | null;
+ /** The child's own exit code; null when claudish ended the pane (verdict, cancel, timeout). */
exitCode: number | null;
- /** `result.num_turns` from the child's terminal frame. 0 until one arrives. */
+ /** Prompts whose turn settled (a re-wake adds none). */
turnsCompleted: number;
- /** Total tokens, PROXY-measured where possible. See SessionManager.refreshAccounting. */
- tokensUsed: number;
+ /** From the transcript or the proxy's token file; null = no source yet. */
+ tokensIn: number | null;
+ tokensOut: number | null;
+ /** Real spend from the proxy's token file; null = unknown (always null for native routes). */
+ costUsd: number | null;
+ toolCalls: number;
+ /** ISO 8601: last screen change or transcript append. */
+ lastActivityAt: string | null;
elapsedSeconds: number;
/**
- * Seconds since the child last put anything on stdout. Null for a session
- * with no live reducer (already finalised, or restored from disk).
- *
- * INFORMATION, not a verdict. Nothing in claudish terminates a session for
- * being idle. A child inside a long `Bash` is silent and working; only the
- * caller knows whether that is expected for the task it set. Read this, decide,
- * and call `cancel_session` if the answer is no.
+ * Seconds since `lastActivityAt`; null in terminal states and for a record read from
+ * disk. INFORMATION, not a verdict: nothing in claudish ends a session for being idle.
*/
idleSeconds: number | null;
+ /** RUNNING: tool name, "thinking", "background" or "finishing"; a blocked tool; else null. */
+ activity: string | null;
+ /** Set on FAILED / EMPTY / CANCELLED / TIMEOUT; null otherwise (incl. COMPLETED). */
+ reason: FailureReason | null;
+ detail: string | null;
+ /** send_input texts queued behind the current turn. */
+ pendingInputs: number;
/**
- * Real spend in USD, from the proxy's own token file.
- *
- * Deliberately NOT `result.total_cost_usd`: the child prices every model at
- * Anthropic's rates, so for a proxied model that figure is fiction — and for a
- * subscription provider it invents spend that will never be billed.
+ * The child Claude Code's own session uuid — minted here and passed as `--session-id`.
+ * It is the transcript's basename.
*/
- costUsd: number;
- /** Tool invocations the proxy counted, falling back to `tool_use` blocks seen on the stream. */
- toolCallCount: number;
- /** `result.terminal_reason` verbatim. Null when no terminal frame ever arrived. */
- terminalReason: string | null;
+ claudeSessionId: string;
/**
- * The child `claude`'s own session uuid — minted here and passed as
- * `--session-id`, then confirmed from its `system:init` frame. This is the
- * transcript filename under `~/.claude/projects/<slug>/`, so a diagnostic
- * consumer can find the full record without guessing by mtime.
+ * Absolute path of the child's JSONL transcript: `<config dir>/projects/<slug of the
+ * REALPATH of cwd>/<claudeSessionId>.jsonl`. The realpath is load-bearing (macOS `/tmp`
+ * is a symlink), and it is the turn oracle the pane session reads.
*/
- claudeSessionId: string | null;
+ transcriptPath: string;
/**
- * The Claude Code conversation that called create_session, PROVEN at call
- * time: the calling tool-use id was found in that conversation's transcript
- * (channel/parent-proof.ts). Absent when not proven — never a guess, never
- * the id the MCP server happened to start with.
+ * The Claude Code conversation that called create_session, PROVEN at call time
+ * (channel/parent-proof.ts). Absent when not proven — never a guess.
*/
parentClaudeSessionId?: string;
- /**
- * Absolute path to the child's authoritative JSONL transcript, or null before
- * `claudeSessionId` is known.
- *
- * Not a guess: the uuid is minted here and passed as `--session-id`, and the
- * directory is `~/.claude/projects/<slug of the REALPATH of cwd>`. The realpath
- * is the load-bearing half — on macOS `/tmp` is a symlink to `/private/tmp` and
- * a git worktree can be reached through one too, so the slug of the path we
- * SPAWNED with names a directory that does not exist. That is literally how the
- * incident's two transcripts were "missing": they were under the session's
- * `work_dir`, in a project directory nobody looked in.
- */
- transcriptPath: string | null;
+ captureSource: "transcript" | "screen" | "none" | null;
+ turnSource: "transcript" | "screen";
+ /** normaliseTimeoutSeconds(): an integer in 1..3600 (0 for a record read from disk without it). */
+ timeoutSeconds: number;
}
export interface SessionCreateOptions {
@@ -154,63 +126,43 @@ export interface SessionCreateOptions {
/**
* The first turn. Its presence also selects the session's SHAPE:
*
- * - given → one-shot. Sent as the opening `user` frame; stdin is closed as
- * soon as the child reports a terminal `result`, so the session passes
- * through `finishing` and ends at `completed` instead of idling to the
- * timeout. It never enters `waiting_for_input`.
- * - absent → interactive. Stdin stays open indefinitely. The session is in
- * `waiting_for_input` from creation until the first `send_input`, and again
- * after every turn the child finishes.
+ * - given → one-shot. Delivered once the REPL is ready; the session's verdict is
+ * decided when that turn settles, and it ends at COMPLETED, EMPTY or FAILED.
+ * - absent → interactive. The session waits in AWAITING_INPUT once boot is ready
+ * (STARTING before), and again after every turn.
*
- * A `send_input` call converts a one-shot session to interactive — the caller
- * has taken over driving it, so we stop deciding when it is finished.
+ * A `send_input` call converts a one-shot session to interactive — the caller has
+ * taken over driving it, so we stop deciding when it is finished.
*/
prompt?: string;
timeoutSeconds?: number;
claudishFlags?: string[];
cwd?: string;
/**
- * Use this id instead of minting a random one. Must be unique among live
- * sessions; a collision throws rather than silently adopting the existing
- * session.
- *
- * `team` needs it: its slots are anonymised ids ("01".."05") that address
- * everything else about the run — `response-<id>.md`, `stats/<id>.json`, the
- * manifest, the status file. A random session id would mean two names for one
- * slot and a mapping table to keep in step.
+ * Use this id instead of minting a random one. Must be unique among live sessions;
+ * a collision throws rather than silently adopting the existing session.
*/
sessionId?: string;
- /**
- * Where this session's artifacts go. Defaults to `<sessionsDir>/<sessionId>`.
- *
- * `team` points every slot at a directory inside the TEAM run, so one run's
- * evidence stays in one place rather than scattering across
- * `~/.claudish/sessions` under ids nothing links back.
- */
+ /** Where this session's artifacts go. Defaults to `<sessionsDir>/<sessionId>`. */
sessionDir?: string;
- /**
- * Where the child's token tracker writes. Defaults to `<sessionDir>/tokens.json`.
- *
- * `team` points it at `stats/<slot>.json`, which is what `renderTeamStatsCompact`
- * and the status file already read.
- */
+ /** Where the child's token tracker writes. Defaults to `<sessionDir>/tokens.json`. */
tokenFile?: string;
- /**
- * Keep JSON lines that are not stream-json vocabulary. Default false.
- * See `StreamJsonReducerOptions.keepUnrecognizedJson` for why the two
- * consumers differ.
- */
- keepUnrecognizedJson?: boolean;
/**
* The calling conversation, when the caller PROVED it (see
* `proveCallingConversation`). Recorded verbatim in `spawn.json` and
* `SessionInfo`; absent means not proven. Never pass an unproven id.
*/
parentClaudeSessionId?: string;
+ /**
+ * The environment the pane child is built from (X-M9). Defaults to the manager's
+ * `parentEnv`, then `process.env`. Tests pass a hermetic one instead of mutating
+ * `process.env`.
+ */
+ parentEnv?: Record<string, string | undefined>;
}
export interface ChannelEvent {
- type: string;
+ type: ChannelEventType;
model: string;
content: string;
elapsedSeconds: number;
@@ -223,56 +175,19 @@ export interface ChannelEvent {
extraMeta?: Record<string, string>;
}
-/**
- * One state change out of the stream-json reducer. Its states are `SessionStatus`:
- * print mode has no permission dialog, so the reducer never emits
- * `awaiting_permission`.
- */
-export interface ReducerEvent {
- previousState: SessionStatus;
- newState: SessionStatus;
- content?: string;
- toolName?: string;
- toolCount?: number;
- /**
- * Emit even when `newState === previousState`.
- *
- * Two callers need it: the batched-tool notification (a second
- * `tool_executing` carrying a count) and the stall notice (a `running` that
- * says the stream has gone quiet). Without it those are swallowed by the
- * no-op guard, which exists so ordinary repeated frames do not spam the wire.
- */
- repeat?: boolean;
- /**
- * The stream has gone quiet in a state that should be producing frames.
- * Surfaced on the wire as `meta.stalled` so a consumer can tell "still
- * thinking" from "wedged" without parsing the content string.
- */
- stalled?: boolean;
- timestamp: string;
-}
-
-export type ReducerCallback = (sessionId: string, event: ReducerEvent) => void;
-
export interface SessionManagerOptions {
maxSessions?: number;
scrollbackCapacity?: number;
onStateChange?: (sessionId: string, event: ChannelEvent) => void;
/** Artifact root override. Defaults to CLAUDISH_SESSIONS_DIR, then ~/.claudish/sessions. */
sessionsDir?: string;
- /**
- * Seconds of total stream silence, in a state that should be producing
- * frames, before the session reports itself stalled. 0 disables the watchdog.
- */
- stallSeconds?: number;
/**
* How long a TERMINAL session stays in the manager's map before it is
* evicted. Defaults to 30 minutes.
*
* `maxSessions` bounds only active sessions, so without eviction a long-lived
- * MCP server retains every finished session — and its scrollback, reducer and
- * stderr buffer — for the life of the process. The on-disk artifacts are
- * unaffected by eviction.
+ * MCP server retains every finished session for the life of the process. The
+ * on-disk artifacts are unaffected by eviction.
*/
terminalRetentionMs?: number;
/**
@@ -281,4 +196,8 @@ export interface SessionManagerOptions {
* override records no `launcherPid`.
*/
hostPid?: number;
+ /** The environment pane children are built from (X-M9). Defaults to `process.env`. */
+ parentEnv?: Record<string, string | undefined>;
+ /** @internal test-only pane timing seams (X-M7); production never passes them. */
+ paneTimings?: PaneSessionOptions["timings"];
}
diff --git a/packages/cli/src/mcp-e2e/runner.ts b/packages/cli/src/mcp-e2e/runner.ts
index 63b18360..7299b7bd 100644
--- a/packages/cli/src/mcp-e2e/runner.ts
+++ b/packages/cli/src/mcp-e2e/runner.ts
@@ -15,10 +15,9 @@
* changed. That is not paranoia — the repo's existing e2e tests write that file
* directly and have destroyed a real user's 1Password configuration twice.
*/
-import { createHash } from "node:crypto";
+import { createHash, randomBytes } from "node:crypto";
import {
appendFileSync,
- chmodSync,
existsSync,
mkdirSync,
readFileSync,
@@ -99,34 +98,27 @@ function md5(path: string): string {
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
/**
- * A `claudish` shim on PATH that runs THIS repo's source.
+ * The pane child every `create_session` / `team` slot of the server under test runs.
*
- * The MCP server spawns its children as `spawn("claudish", …)`
- * (`channel/session-manager.ts`, `team-orchestrator.ts`) — by NAME, resolved
- * through PATH, with no seam. So while the harness starts the SERVER from
- * `packages/cli/src/index.ts`, every child it spawned was the globally INSTALLED
- * claudish. Arms asserted on dev spans from the parent while the actual model
- * run resolved credentials with whatever version happened to be installed.
- *
- * That is how a deleted code path came back to life: installed 7.34.0 still
- * contained the `op account get` probe removed from this tree, and it fired on
- * every child spawn.
- *
- * Prepending this shim makes parent AND child the same code. Mirrors the
- * fake-claudish PATH shim `session-manager.test.ts` already uses, so it is the
- * repo's existing idiom rather than a new mechanism.
+ * Children are interactive Claude Code panes now: whatever they print goes to their
+ * pane's terminal, never to the server's stderr, so the spans this harness asserts on
+ * are the PARENT's (credential prehydration happens there). The child is therefore the
+ * hermetic pane fake (`pane/test-helpers/fake-interactive-child.ts`), passed as
+ * `CLAUDISH_BIN`: no installed claudish is ever spawned (the 7.34.0 incident, see
+ * `spawn-claudish.ts`), and a `create_session` arm costs no model turn.
*/
-function writeClaudishShim(): string {
- const binDir = join(RUN_DIR, "bin");
- mkdirSync(binDir, { recursive: true });
- const shim = join(binDir, "claudish");
- writeFileSync(
- shim,
- `#!/bin/sh\nexec "${process.execPath}" run "${SERVER_ENTRY}" "$@"\n`,
- "utf-8"
- );
- chmodSync(shim, 0o755);
- return binDir;
+const PANE_FAKE_CHILD = resolve(
+ REPO_ROOT,
+ "packages/cli/src/pane/test-helpers/fake-interactive-child.ts"
+);
+
+/**
+ * A short pane root per replica (`/tmp/cpt-<8 hex>`, so socket paths stay < 100
+ * bytes): the server's startup sweep, its pane limit and its records stay inside it,
+ * never the user's `/tmp/claudish-mux-<uid>`.
+ */
+function newPaneRoot(): string {
+ return `/tmp/cpt-${randomBytes(4).toString("hex")}`;
}
// ── session log collection ───────────────────────────────────────────────────
@@ -157,7 +149,7 @@ function collectSessionLogs(sinceMs: number): SessionLog[] {
} catch {
meta = null;
}
- out.push({ sessionId: id, meta, stderr: read("stderr.log"), output: read("output.log") });
+ out.push({ sessionId: id, meta, screen: read("screen.txt"), output: read("output.log") });
}
} catch {
// no sessions dir yet — fine
@@ -208,11 +200,11 @@ async function runScenario(sc: Scenario, gapBeforeSeconds: number): Promise<Verd
const configPath = join(armDir, "config.json");
writeFileSync(configPath, JSON.stringify(config, null, 2), "utf-8");
- const shimDir = writeClaudishShim();
const replicas = sc.concurrency ?? 1;
const observations: Observation[] = [];
const runReplica = async (replica: number): Promise<Observation> => {
+ const paneRoot = newPaneRoot();
const env = buildArmEnv({
parent: process.env,
keepKeys: sc.keepKeys,
@@ -220,9 +212,9 @@ async function runScenario(sc: Scenario, gapBeforeSeconds: number): Promise<Verd
...sc.env,
// Isolation: the child reads THIS file, never ~/.claudish/config.json.
CLAUDISH_CONFIG: configPath,
- // Applied AFTER sc.env so an arm that narrows PATH (op-no-op-binary
- // hides the `op` binary) still resolves `claudish` to this tree.
- PATH: `${shimDir}:${sc.env?.PATH ?? process.env.PATH ?? ""}`,
+ // Applied AFTER sc.env so an arm cannot point children anywhere else.
+ CLAUDISH_BIN: PANE_FAKE_CHILD,
+ CLAUDISH_PANE_ROOT: paneRoot,
// Observability: flips the trace into live-print so op spans stream out.
CLAUDISH_STARTUP_TRACE: "1",
CLAUDISH_OP_LOCK_TRACE: "1",
@@ -247,6 +239,8 @@ async function runScenario(sc: Scenario, gapBeforeSeconds: number): Promise<Verd
logFile: join(armDir, `stream${suffix}.log`),
verbose,
});
+ // The server reaped its panes on shutdown; its watchers handle a server that died.
+ rmSync(paneRoot, { recursive: true, force: true });
writeFileSync(join(armDir, `stderr${suffix}.log`), res.stderr, "utf-8");
writeFileSync(
diff --git a/packages/cli/src/mcp-e2e/scenarios.ts b/packages/cli/src/mcp-e2e/scenarios.ts
index f498c7fb..3bcb44e7 100644
--- a/packages/cli/src/mcp-e2e/scenarios.ts
+++ b/packages/cli/src/mcp-e2e/scenarios.ts
@@ -90,9 +90,11 @@ export const SCENARIOS: Scenario[] = [
}
const createSessionText = observation.toolText.create_session;
- if (!/\{"session_id":"[0-9a-f]{8}","status":"starting"\}/.test(createSessionText ?? "")) {
+ if (
+ !/"session_id":\s*"[0-9a-f]{8}",\s*"state":\s*"STARTING"/.test(createSessionText ?? "")
+ ) {
failures.push(
- `expected create_session tool text containing an 8-hex session_id with status starting, observed: ${createSessionText ? JSON.stringify(createSessionText) : "none"}`
+ `expected create_session tool text containing an 8-hex session_id with state STARTING, observed: ${createSessionText ? JSON.stringify(createSessionText) : "none"}`
);
}
if (observation.timedOut) {
diff --git a/packages/cli/src/mcp-e2e/types.ts b/packages/cli/src/mcp-e2e/types.ts
index 4de58d74..f97dacf3 100644
--- a/packages/cli/src/mcp-e2e/types.ts
+++ b/packages/cli/src/mcp-e2e/types.ts
@@ -79,7 +79,8 @@ export interface Observation {
export interface SessionLog {
sessionId: string;
meta: Record<string, unknown> | null;
- stderr: string;
+ /** `screen.txt`: the pane's final screen (a pane has no separate stderr). */
+ screen: string;
output: string;
}
diff --git a/packages/cli/src/mcp-server.ts b/packages/cli/src/mcp-server.ts
index 9905144a..fb1a884e 100644
--- a/packages/cli/src/mcp-server.ts
+++ b/packages/cli/src/mcp-server.ts
@@ -20,7 +20,6 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
import { config } from "dotenv";
import { searchCatalogModels } from "./adapters/model-catalog.js";
-import { assertAgentAvailable } from "./agent-availability.js";
import { prehydrateCredentialsForSpawn } from "./auth/credentials/prehydrate.js";
import { installWireTap, watchNotificationResult, wrapStateChange } from "./channel/diagnostics.js";
import { SessionManager } from "./channel/index.js";
@@ -50,7 +49,11 @@ import {
type SlotState,
TERMINAL_STATES,
type TeamRunRow,
+ assertMagmuxAvailable,
+ checkChildFlags,
contractMeta,
+ installPaneShutdownHooks,
+ sweepOrphanPanes,
} from "./pane/index.js";
import { findAvailablePort } from "./port-manager.js";
import { ensureEndpointsRegistered } from "./providers/endpoint-registration.js";
@@ -117,31 +120,32 @@ const INSTRUCTIONS = `Claudish MCP server provides access to external AI models
## Channel Mode — External Model Sessions
-When channel mode is active, you receive <channel source="claudish" ...> notifications about running external model sessions.
+When channel mode is active, you receive <channel source="claudish" ...> notifications about running external model sessions. Each session is an interactive Claude Code running the model in its own headless terminal pane.
### Events
-- session_started: A session began producing output. Note the session_id for future calls.
-- tool_executing: The model is using a tool (Read, Write, Bash, etc.). May include tool_count for batched events.
-- input_required: The session finished a turn and waits for send_input. Only interactive sessions do this (no prompt, or after a send_input). Call send_input with the session_id and your answer.
-- finishing: The session's last turn ended and claudish closed its input; it is exiting. Nothing to do; completed follows.
+- running: The session's turn is running (its prompt was accepted). Note the session_id for future calls.
+- tool_executing: The model is using a tool (Read, Write, Bash, etc.). Carries tool and tool_count.
+- input_required (event waiting_for_input): The session waits for send_input: an interactive session between turns, or a session stopped on a question (meta activity "AskUserQuestion"). A send declines a question and becomes the next prompt.
+- input_required (event awaiting_permission): A permission or plan-approval dialog is open. A send declines it and becomes the next prompt.
- completed: The session finished successfully. Call get_output to retrieve the full output.
-- failed: The session exited with an error. Call get_diagnostics for the cause.
-- timeout: The session hit its timeout_seconds and was killed. Call get_diagnostics to see how far it got.
+- failed: The session failed (boot, prompt not accepted or not read, child exited, API error, pane lost). Call get_diagnostics for the cause.
+- timeout: The session hit its timeout_seconds; the pane was closed. Call get_diagnostics to see how far it got.
- cancelled: The session was cancelled via cancel_session.
### Workflow
-1. Call create_session with a model and prompt to start an async session.
+1. Call create_session with a model and prompt to start an async session (state STARTING while Claude Code boots).
2. Watch for <channel> notifications — they arrive automatically.
-3. On input_required (interactive sessions only: no prompt, or after a send_input): call send_input with the answer.
+3. send_input may be called at any time; it is queued until the session is idle. On input_required, call send_input with the answer.
4. On completed: call get_output to get the full response.
5. On failed or timeout — or on a completed session whose output is empty or
- surprising — call get_diagnostics. It returns the child's stderr, the upstream
- error bodies, the recent event frames, the resolved model chain and the paths
- to the full records. It needs no re-run and no debug flag.
-6. Use list_sessions to see all active/completed sessions.
-7. Use cancel_session to stop a running session.
+ surprising — call get_diagnostics. It returns the child's final screen, the
+ upstream error bodies, the recent state records, the resolved model chain and the
+ paths to the full records. It needs no re-run and no debug flag.
+6. Use list_sessions to see sessions: each row has state, activity, idle_seconds and accounting.
+7. Use capture_session to read a session's current terminal screen.
+8. Use cancel_session to stop a running session.
The session_id in the channel tag's meta attributes is the key for all tool calls.`;
@@ -1908,7 +1912,11 @@ function defineTools(
tools.push({
name: "create_session",
description:
- "Create a new claudish proxy session for an external model. Spawns an async session that produces channel notifications as it runs.",
+ "Create a new claudish proxy session for an external model: an interactive Claude Code running " +
+ "it in its own headless magmux pane. Returns at once with state STARTING; the session produces " +
+ "channel notifications as it runs. With a prompt it is one-shot (it ends when that turn " +
+ "settles); without one it is interactive and waits for send_input. Needs magmux >= 0.14.0 " +
+ "(darwin and linux).",
inputSchema: {
type: "object",
properties: {
@@ -1937,9 +1945,10 @@ function defineTools(
claude_flags: {
type: "string",
description:
- "Any other Claude Code / claudish flags, space-separated. Unrecognised flags " +
- "pass through to the child Claude Code. NOTE: split on whitespace, so a flag " +
- "VALUE containing spaces cannot be expressed here.",
+ "Any other Claude Code / claudish flags and their values, space-separated — no " +
+ "positional text. Unrecognised flags pass through to the child Claude Code. " +
+ "Flags the pane owns or that only work in print mode are refused. NOTE: split on " +
+ "whitespace, so a flag VALUE containing spaces cannot be expressed here.",
},
work_dir: {
type: "string",
@@ -1951,7 +1960,13 @@ function defineTools(
group: "channel",
handler: async (args, ctx) => {
try {
- const claudishFlags = buildChildClaudeFlags(args.agent, args.claude_flags);
+ const claudishFlags = buildChildClaudeFlags(args.agent, args.claude_flags) ?? [];
+ // Refusals first, before any credential work: reserved or positional flags, then
+ // a missing magmux (its message starts with the code word). An unknown --agent is
+ // refused by the child itself, before any model request (D11).
+ const flagCheck = checkChildFlags(claudishFlags);
+ if (!flagCheck.ok) throw new Error(`invalid_args: ${flagCheck.message}`);
+ await assertMagmuxAvailable();
// Resolve the model's credential AND its route in THIS process before
// spawning the child. Several create_session calls in flight at once
@@ -1968,9 +1983,6 @@ function defineTools(
// an option — it is process-global and races concurrent calls.
const requestedModel = args.model as string;
const workDir = args.work_dir as string | undefined;
- // The agent list is cwd-dependent, so validate against the directory this
- // session will actually run in, not the parent's.
- await assertAgentAvailable(args.agent as string | undefined, workDir ?? process.cwd());
const plan = await prehydrateCredentialsForSpawn([requestedModel], {
pin: workDir === undefined || resolve(workDir) === process.cwd(),
@@ -1984,7 +1996,9 @@ function defineTools(
hostPid: sessionManager.hostPid,
});
- const sessionId = sessionManager.createSession({
+ // Reserves the pane, writes prompt.md and spawn.json, then starts the pane; no
+ // boot wait.
+ const sessionId = await sessionManager.createSession({
model: requestedModel,
spawnModel: plan.pinned.get(requestedModel),
prompt: args.prompt as string | undefined,
@@ -1998,12 +2012,21 @@ function defineTools(
content: [
{
type: "text" as const,
- text: JSON.stringify({ session_id: sessionId, status: "starting" }),
+ text: JSON.stringify({
+ session_id: sessionId,
+ state: sessionManager.getSession(sessionId).state,
+ }),
},
],
};
} catch (error) {
const errMsg = error instanceof Error ? error.message : String(error);
+ // A missing magmux or a full pane limit is the environment, not the provider:
+ // `Error: <code>: …` with the code first (§4.3), and no report_error hint.
+ const code = (error as { code?: unknown } | null)?.code;
+ if (code === "magmux_unavailable" || code === "pane_limit") {
+ return { content: [{ type: "text" as const, text: `Error: ${errMsg}` }], isError: true };
+ }
return {
content: [
{
@@ -2023,7 +2046,11 @@ function defineTools(
tools.push({
name: "send_input",
description:
- "Send input text to an active session's stdin. Use when a session is in 'waiting_for_input' state.",
+ "Send a prompt to a session. Accepted in every non-terminal state and queued until the " +
+ "session is idle: STARTING and RUNNING queue it; AWAITING_INPUT delivers it at once; during " +
+ "a question or a permission dialog the dialog is declined (Esc) and the text becomes the next " +
+ "prompt. Any accepted send makes a one-shot session interactive. Returns {success, queued} or " +
+ "{success:false, reason, state}.",
inputSchema: {
type: "object",
properties: {
@@ -2034,9 +2061,9 @@ function defineTools(
},
group: "channel",
handler: async (args) => {
- const success = sessionManager.sendInput(args.session_id as string, args.text as string);
+ const result = sessionManager.sendInput(args.session_id as string, args.text as string);
return {
- content: [{ type: "text" as const, text: JSON.stringify({ success }) }],
+ content: [{ type: "text" as const, text: JSON.stringify(result) }],
};
},
});
@@ -2044,7 +2071,8 @@ function defineTools(
tools.push({
name: "get_output",
description:
- "Get output from a session's scrollback buffer. Call after 'completed' notification to get full response.",
+ "Get a session's answer prose (each settled turn's assistant text, from its transcript). " +
+ "Call after the 'completed' notification to get the full response.",
inputSchema: {
type: "object",
properties: {
@@ -2083,7 +2111,9 @@ function defineTools(
tools.push({
name: "cancel_session",
description:
- "Cancel a running session. Sends SIGTERM, then SIGKILL after 5 seconds if still running.",
+ "Cancel a session. Returns once its state is CANCELLED ({session_id, state, changed}); the " +
+ "pane close and process-group reap finish in the background. Idempotent: a second call " +
+ "returns the same state with changed:false. Errors are a JSON ContractError.",
inputSchema: {
type: "object",
properties: {
@@ -2093,21 +2123,25 @@ function defineTools(
},
group: "channel",
handler: async (args) => {
- const success = sessionManager.cancelSession(args.session_id as string);
- return {
- content: [{ type: "text" as const, text: JSON.stringify({ success }) }],
- };
+ try {
+ const sessionId = optionalString(args.session_id, "session_id");
+ if (sessionId === undefined)
+ throw new ContractErrorException("invalid_args", "'session_id' is required");
+ return contractAnswer(sessionManager.cancelSession(sessionId));
+ } catch (e) {
+ return contractErrorAnswer(e);
+ }
},
});
tools.push({
name: "list_sessions",
description:
- "List all active channel sessions. Optionally include completed sessions. " +
- "Each session reports `idleSeconds`: how long since the child last emitted " +
- "anything. Nothing kills a session for being idle — a child inside a long " +
- "Bash call is silent and working — so this is yours to judge against the " +
- "task you set, and `cancel_session` is yours to call if the answer is no.",
+ "List channel sessions: {contract_version, capabilities, sessions}. Optionally include " +
+ "finished ones. Each row reports `state`, `activity` and `idle_seconds`: how long since " +
+ "the session's screen or transcript last changed. Nothing kills a session for being " +
+ "idle — a child inside a long Bash call is silent and working — so this is yours to " +
+ "judge against the task you set, and `cancel_session` is yours to call if the answer is no.",
inputSchema: {
type: "object",
properties: {
@@ -2119,10 +2153,14 @@ function defineTools(
},
group: "channel",
handler: async (args) => {
- const sessions = sessionManager.listSessions(args.include_completed as boolean | undefined);
- return {
- content: [{ type: "text" as const, text: JSON.stringify({ sessions }) }],
- };
+ try {
+ return contractAnswer({
+ ...contractMeta(),
+ sessions: sessionManager.listSessionRows(args.include_completed === true),
+ });
+ } catch (e) {
+ return contractErrorAnswer(e);
+ }
},
});
@@ -2141,13 +2179,13 @@ function defineTools(
tools.push({
name: "get_diagnostics",
description:
- "Explain what a channel session actually did — stderr, upstream error bodies, the " +
- "recent event frames, the resolved model chain, accounting, and the paths to the " +
- "full records. Call this FIRST whenever a session fails, times out, or completes " +
- "with empty or surprising output; it needs no re-run and no debug flag. " +
- "`idleSeconds` reports how long since the child last emitted a frame, and is " +
- "null once the session is no longer live. It is information, never a verdict: " +
- "claudish does not terminate a session for silence.",
+ "Explain what a channel session actually did — its final screen, upstream error bodies, " +
+ "the recent state records, anomalies, the resolved model chain, accounting, and the paths " +
+ "to the full records (transcript included). Call this FIRST whenever a session fails, times " +
+ "out, or completes with empty or surprising output; it needs no re-run and no debug flag. " +
+ "`idleSeconds` reports how long since the screen or transcript last changed, and is null " +
+ "once the session is no longer live. It is information, never a verdict: claudish does " +
+ "not terminate a session for silence.",
inputSchema: {
type: "object",
properties: {
@@ -2155,7 +2193,7 @@ function defineTools(
event_limit: {
type: "number",
description:
- "How many of the most recent semantic frames to include (default: 40, max: 200). " +
+ "How many of the most recent state records to include (default: 40, max: 200). " +
"0 omits them; `event_log_path` always has the full record.",
},
},
@@ -2185,6 +2223,46 @@ function defineTools(
},
});
+ tools.push({
+ name: "capture_session",
+ description:
+ "Read a session's current terminal screen (160×50): {seq, cols, rows, cursor, lines, final, " +
+ "spans?}. A memory read, meant for polling about once per second. Pass the last `seq` as " +
+ "since_seq to get {unchanged:true, seq, final} while nothing changed. `final:true` is the " +
+ "last screen of a closed pane. Errors are a JSON ContractError.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ session_id: { type: "string", description: "Session ID from create_session" },
+ since_seq: {
+ type: "number",
+ description: "The seq of your previous capture; an equal seq answers {unchanged:true}",
+ },
+ spans: {
+ type: "boolean",
+ description: "Include per-row colour and attribute runs (default: false)",
+ },
+ },
+ required: ["session_id"],
+ },
+ group: "channel",
+ handler: async (args) => {
+ try {
+ const sessionId = optionalString(args.session_id, "session_id");
+ if (sessionId === undefined)
+ throw new ContractErrorException("invalid_args", "'session_id' is required");
+ const since = args.since_seq;
+ if (since !== undefined && (typeof since !== "number" || !Number.isInteger(since)))
+ throw new ContractErrorException("invalid_args", "'since_seq' must be an integer");
+ return contractAnswer(
+ sessionManager.captureSession(sessionId, since as number | undefined, args.spans === true)
+ );
+ } catch (e) {
+ return contractErrorAnswer(e);
+ }
+ },
+ });
+
return tools;
}
@@ -2220,19 +2298,14 @@ const TASK_STATUS_BY_EVENT: Record<ChannelEventType, TaskStatus> = {
// session on. It had no key, so it fell through to "working": a SEP-1686
// consumer polled a session that was waiting on it as if it were busy.
awaiting_permission: "input_required",
- // Explicit although the fall-through below gives the same value: a missing
- // key is how the timeout projection hid (see the `timeout` entry). The final
- // turn ended and the child is exiting; nothing is asked of the caller.
- finishing: "working",
completed: "completed",
failed: "failed",
cancelled: "cancelled",
// The key whose ABSENCE forced the channel wire to lie. `mapEventToTaskStatus`
// falls through to `?? "working"`, so a session killed by its own timeout was
// reported to a SEP-1686 consumer as still working — which is why the timeout
- // path emitted `"failed"` on the wire while `SessionInfo.status` said
- // `"timeout"`. With this key present `ChannelEventType` is the full
- // `SessionStatus` and the timeout emits its own event; SEP-1686 has no
+ // path once emitted `"failed"` on the wire while the record said `"timeout"`.
+ // With this key present the timeout emits its own event; SEP-1686 has no
// `timeout` member, and `failed` is the only honest projection of it.
timeout: "failed",
};
@@ -2434,15 +2507,27 @@ async function main() {
const transport = new StdioServerTransport();
installWireTap();
await server.connect(transport);
+ installMcpShutdown(sessionManager);
+ // The startup sweep: panes whose owner died (and whose watcher died too) are reaped
+ // after an identity check. Asynchronous; a failure costs nothing but the sweep.
+ void sweepOrphanPanes().catch(() => undefined);
+}
- // Cleanup on shutdown. Both subsystems spawn children that outlive the call
- // that started them — channel sessions always did, and team runs do now that
- // `run` returns before its models finish — so both must be reached here or
- // their process trees survive this one and keep billing.
- process.on("SIGTERM", () => {
- sessionManager.shutdownAll().catch(() => {});
- shutdownAllTeamRuns().catch(() => {});
- });
+/**
+ * Shutdown (D15 layer 3, §20.3 item 8): stdin EOF, transport close, SIGINT, SIGTERM and
+ * SIGHUP settle every team run and channel session CANCELLED — so their records end
+ * (`meta.json`, the closing wait line) — then reap every pane in parallel and exit.
+ * Installed before any pane exists, so `startPaneSession`'s own default hooks never
+ * replace these options. A SIGKILL of this process ends no record; the per-pane
+ * watchers still remove the panes.
+ */
+function installMcpShutdown(sessionManager: SessionManager): void {
+ const before = async (): Promise<void> => {
+ await Promise.allSettled([shutdownAllTeamRuns(), sessionManager.shutdownAll()]);
+ };
+ // The stdio transport closes when stdin does, so stdin's `end`/`close` is the
+ // transport-close hook too.
+ installPaneShutdownHooks({ stdin: true, before });
}
// ─── Entry Point ─────────────────────────────────────────────────────────────
diff --git a/packages/cli/src/pane/test-helpers/fake-interactive-child.ts b/packages/cli/src/pane/test-helpers/fake-interactive-child.ts
old mode 100644
new mode 100755
diff --git a/packages/cli/src/stdio-decode.test.ts b/packages/cli/src/stdio-decode.test.ts
deleted file mode 100644
index 0de58323..00000000
--- a/packages/cli/src/stdio-decode.test.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { describe, expect, test } from "bun:test";
-
-import { decodeChunk, newStdioDecoder } from "./stdio-decode.js";
-
-const MULTIBYTE_CASES = [
- { label: "three-byte CJK", character: "界", splitAt: 1 },
- { label: "four-byte emoji", character: "🧭", splitAt: 2 },
-];
-
-function splitUtf8(character: string, splitAt: number): [Buffer, Buffer] {
- const bytes = Buffer.from(character, "utf8");
- return [bytes.subarray(0, splitAt), bytes.subarray(splitAt)];
-}
-
-describe.each(MULTIBYTE_CASES)("decodeChunk — $label", ({ character, splitAt }) => {
- test("reassembles a codepoint split across Buffer chunks", () => {
- const decoder = newStdioDecoder();
- const [first, second] = splitUtf8(character, splitAt);
-
- expect(decodeChunk(decoder, first)).toBe("");
- expect(decodeChunk(decoder, second)).toBe(character);
- });
-
- test("negative control: Buffer.toString permanently inserts replacement characters", () => {
- const [first, second] = splitUtf8(character, splitAt);
- const decodedWithoutState = first.toString("utf8") + second.toString("utf8");
-
- expect(decodedWithoutState).toContain("\uFFFD");
- expect(decodedWithoutState).not.toBe(character);
- });
-});
-
-test("decodeChunk passes string chunks through unchanged", () => {
- expect(decodeChunk(newStdioDecoder(), "emitted test string 🧭")).toBe("emitted test string 🧭");
-});
-
-test("separate decoders keep interleaved partial sequences independent", () => {
- const cjkDecoder = newStdioDecoder();
- const emojiDecoder = newStdioDecoder();
- const [cjkFirst, cjkSecond] = splitUtf8("界", 1);
- const [emojiFirst, emojiSecond] = splitUtf8("🧭", 2);
-
- expect(decodeChunk(cjkDecoder, cjkFirst)).toBe("");
- expect(decodeChunk(emojiDecoder, emojiFirst)).toBe("");
- expect(decodeChunk(emojiDecoder, emojiSecond)).toBe("🧭");
- expect(decodeChunk(cjkDecoder, cjkSecond)).toBe("界");
-});
diff --git a/packages/cli/src/stdio-decode.ts b/packages/cli/src/stdio-decode.ts
deleted file mode 100644
index 33c9175c..00000000
--- a/packages/cli/src/stdio-decode.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { StringDecoder } from "node:string_decoder";
-
-/**
- * Decode one stdio chunk, holding any partial multi-byte sequence for the next.
- *
- * A `data` chunk ends at the pipe's read boundary, which lands mid-codepoint
- * often enough to matter on any non-ASCII answer. `StringDecoder` keeps the
- * dangling bytes; `Buffer.toString` replaces them with U+FFFD — permanently, in
- * the answer a reader ends up with.
- *
- * Strings are passed through because a test can `emit("data", "…")` directly,
- * and `StringDecoder.write` only accepts a Buffer.
- *
- * Lives here rather than in either consumer because both supervise a `claudish`
- * child over a pipe and both need it. The channel had it; `team` did not, and
- * read its children with `chunk.toString()` — so a CJK character or emoji
- * straddling a read boundary was mangled in `response-<id>.md` and counted
- * wrong in `outputSize`.
- */
-export function decodeChunk(decoder: StringDecoder, chunk: Buffer | string): string {
- return typeof chunk === "string" ? chunk : decoder.write(chunk);
-}
-
-/** A decoder per pipe. Never share one between stdout and stderr. */
-export function newStdioDecoder(): StringDecoder {
- return new StringDecoder("utf8");
-}
diff --git a/packages/cli/src/team-orchestrator.ts b/packages/cli/src/team-orchestrator.ts
index dd2b4111..ce94a792 100644
--- a/packages/cli/src/team-orchestrator.ts
+++ b/packages/cli/src/team-orchestrator.ts
@@ -700,10 +700,7 @@ export function pruneTeamRunsForTests(now: number): void {
// ─── Output Classification ────────────────────────────────────────────────────
-/**
- * How many trailing answer bytes the channel's stream-json path retains for diagnosis
- * (both owners use it until the channel moves onto panes).
- */
+/** How many trailing answer bytes a failed slot's error log keeps. */
export const STDOUT_TAIL_LIMIT = 4000;
/** Budget for the answer / screen snippets recorded in `status.json`. */
diff --git a/packages/cli/src/team-run-mcp.contract.test.ts b/packages/cli/src/team-run-mcp.contract.test.ts
index a30f78f6..6c1687d2 100644
--- a/packages/cli/src/team-run-mcp.contract.test.ts
+++ b/packages/cli/src/team-run-mcp.contract.test.ts
@@ -4,7 +4,7 @@
* (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 an interactive pane: the pane fake
- * (marker mode) via CLAUDISH_BIN, in a real headless magmux under the test's own
+ * (marker mode; serverEnv's default CLAUDISH_BIN), in a real headless magmux under the test's own
* CLAUDISH_PANE_ROOT (ported per architecture §20.2; every assertion kept). The team
* directory is inside the server's cwd, in case path validation requires it.
*
@@ -20,7 +20,6 @@ import {
MAGMUX_AVAILABLE,
McpServer,
NO_MAGMUX_MESSAGE,
- PANE_FAKE_CHILD,
findField,
paneOrphans,
serverEnv,
@@ -50,7 +49,7 @@ beforeEach(async () => {
layout = makeTempLayout("teammcp");
teamDir = join(layout.cwd, "team-run");
server = await McpServer.start({
- env: serverEnv(layout, { CLAUDISH_BIN: PANE_FAKE_CHILD }),
+ env: serverEnv(layout),
cwd: layout.cwd,
});
});
diff --git a/packages/cli/src/team-stream-capture.test.ts b/packages/cli/src/team-stream-capture.test.ts
deleted file mode 100644
index ca5b04fc..00000000
--- a/packages/cli/src/team-stream-capture.test.ts
+++ /dev/null
@@ -1,212 +0,0 @@
-import { describe, expect, it } from "bun:test";
-import { readFileSync } from "node:fs";
-import { join } from "node:path";
-import { createAssistantTextCapture } from "./team-stream-capture.js";
-
-interface FixtureEvent {
- type?: unknown;
- is_error?: unknown;
- result?: unknown;
- message?: unknown;
- [key: string]: unknown;
-}
-
-const FIXTURE_PATH = join(
- import.meta.dir,
- "test-fixtures",
- "stream-json",
- "haiku-post-answer-turn.jsonl"
-);
-const FIXTURE = readFileSync(FIXTURE_PATH, "utf-8");
-const FIXTURE_EVENTS = FIXTURE.trimEnd()
- .split("\n")
- .map((line) => JSON.parse(line) as FixtureEvent);
-
-function recover(input: string, sliceSize?: number): string {
- const capture = createAssistantTextCapture();
- let output = "";
-
- if (sliceSize === undefined) {
- output += capture.write(input);
- } else {
- for (let offset = 0; offset < input.length; offset += sliceSize) {
- output += capture.write(input.slice(offset, offset + sliceSize));
- }
- }
-
- return output + capture.end();
-}
-
-function getFixtureResultEvent(): FixtureEvent {
- const event = FIXTURE_EVENTS.find((candidate) => candidate.type === "result");
- if (!event) throw new Error("fixture is missing its result event");
- return event;
-}
-
-function getFixtureAssistantTextEvent(): FixtureEvent {
- const event = FIXTURE_EVENTS.find((candidate) => {
- if (candidate.type !== "assistant") return false;
- const message = candidate.message;
- if (!message || typeof message !== "object" || Array.isArray(message)) return false;
- const content = (message as { content?: unknown }).content;
- if (!Array.isArray(content)) return false;
- return content.some(
- (block) =>
- block !== null &&
- typeof block === "object" &&
- !Array.isArray(block) &&
- (block as { type?: unknown }).type === "text" &&
- (block as { text?: unknown }).text === "ALPHA_MARKER"
- );
- });
- if (!event) throw new Error("fixture is missing its first assistant text event");
- return event;
-}
-
-describe("createAssistantTextCapture", () => {
- it("recovers the full answer instead of only the print-mode result", () => {
- const recovered = recover(FIXTURE);
- const resultEvent = getFixtureResultEvent();
-
- expect(recovered).toBe("ALPHA_MARKER\n\nOMEGA_MARKER\n");
- expect(recovered).toContain("ALPHA_MARKER");
- expect(recovered).toContain("OMEGA_MARKER");
- expect(typeof resultEvent.result).toBe("string");
- expect(recovered.trimEnd()).not.toBe(resultEvent.result);
- });
-
- it.each([1, 7, 13, 5000])("is independent of chunk boundaries at %i-byte slices", (sliceSize) => {
- const whole = recover(FIXTURE);
- const sliced = recover(FIXTURE, sliceSize);
-
- expect(sliced).toBe(whole);
- expect(sliced).toBe("ALPHA_MARKER\n\nOMEGA_MARKER\n");
- });
-
- it("drops thinking, tool_use input, and tool_result content", () => {
- const recovered = recover(FIXTURE);
-
- expect(FIXTURE).toContain("This is a straightforward request");
- expect(FIXTURE).toContain("Echo hi to stdout");
- expect(FIXTURE).toContain('"content":"hi"');
- expect(recovered).not.toContain("This is a straightforward request");
- expect(recovered).not.toContain("Echo hi to stdout");
- expect(recovered.split("\n")).not.toContain("hi");
- });
-
- it("passes plain prose lines through byte for byte", () => {
- const prose = "first plain prose line\nsecond plain prose line";
-
- expect(recover(`${prose}\n`)).toBe(`${prose}\n`);
- expect(recover(prose)).toBe(prose);
- });
-
- it.each(['["--model","x"]', '{"type":"telemetry","payload":"future-event"}'])(
- "passes unrecognised JSON through verbatim: %s",
- (line) => {
- expect(recover(line)).toBe(line);
- }
- );
-
- it("newline-terminates assistant-only streams but not passthrough-only streams", () => {
- const assistantOnly = JSON.stringify(getFixtureAssistantTextEvent());
- const passthroughOnly = "plain prose without a trailing newline";
-
- // Recovered messages stay newline-terminated, but passthrough outputSize must
- // match the child's byte count: minOutputBytes and the empty check both consume it.
- expect(recover(assistantOnly)).toBe("ALPHA_MARKER\n");
- expect(recover(passthroughOnly)).toBe(passthroughOnly);
- });
-
- it("drops a successful result event but preserves an API error result", () => {
- const fixtureResult = getFixtureResultEvent();
- const successfulResult = { ...fixtureResult, is_error: false };
- const apiError = "[API Error: overloaded]";
- const failedResult = { ...fixtureResult, is_error: true, result: apiError };
-
- expect(recover(JSON.stringify(successfulResult))).toBe("");
-
- // classifyRunOutput matches /\[API Error:/ against recovered stdout. Dropping
- // this failed result would silently disable api_error detection.
- expect(recover(JSON.stringify(failedResult))).toBe(`${apiError}\n`);
- });
-
- it("does not duplicate an API error already present in recovered prose", () => {
- const apiError = "[API Error: overloaded]";
- const fixtureAssistant = getFixtureAssistantTextEvent();
- const fixtureMessage = fixtureAssistant.message;
- if (!fixtureMessage || typeof fixtureMessage !== "object" || Array.isArray(fixtureMessage)) {
- throw new Error("fixture assistant event has no message object");
- }
-
- const assistantWithError = {
- ...fixtureAssistant,
- message: {
- ...fixtureMessage,
- content: [{ type: "text", text: apiError }],
- },
- };
- const failedResult = {
- ...getFixtureResultEvent(),
- is_error: true,
- result: apiError,
- };
- const recovered = recover(
- `${JSON.stringify(assistantWithError)}\n${JSON.stringify(failedResult)}\n`
- );
-
- expect(recovered).toBe(`${apiError}\n`);
- expect(recovered.match(/\[API Error:/g)).toHaveLength(1);
- });
-
- it("parses a final event without a trailing newline and terminates its output", () => {
- const assistantEvent = getFixtureAssistantTextEvent();
-
- expect(recover(JSON.stringify(assistantEvent))).toBe("ALPHA_MARKER\n");
- });
-
- it("ends an empty stream without introducing a newline", () => {
- const capture = createAssistantTextCapture();
-
- expect(capture.end()).toBe("");
- });
-});
-
-describe("createAssistantTextCapture — protocol frames are not prose", () => {
- // REGRESSION: `rate_limit_event` was absent from STREAM_JSON_EVENT_TYPES, so it
- // fell to the passthrough branch and was written into the captured answer.
- // Measured 2026-08-22: a two-byte reply was recorded as 191 B, which corrupts
- // outputSize and silently defeats min_output_bytes.
- const rateLimitFrame =
- '{"type":"rate_limit_event","rate_limit_info":{"status":"allowed",' +
- '"isUsingOverage":false},"uuid":"5c30f135","session_id":"7ffb7032"}\n';
-
- const assistantFrame = (text: string) =>
- `${JSON.stringify({ type: "assistant", message: { content: [{ type: "text", text }] } })}\n`;
-
- it("drops rate_limit_event instead of emitting it as text", () => {
- const cap = createAssistantTextCapture();
- let out = cap.write(assistantFrame("OK"));
- out += cap.write(rateLimitFrame);
- out += cap.end();
- // Exact value, not trimmed: the capture terminates the answer with a newline,
- // and asserting the real string keeps that pinned too.
- expect(out).toBe("OK\n");
- expect(out).not.toContain("rate_limit_event");
- });
-
- it("a rate_limit_event alone captures nothing", () => {
- const cap = createAssistantTextCapture();
- const out = cap.write(rateLimitFrame) + cap.end();
- expect(out).toBe("");
- });
-
- it("still passes genuinely unknown JSON through, as the degradation note promises", () => {
- // The passthrough branch exists for output that is not our protocol at all.
- // Fixing rate_limit_event must not turn it into a silent dropper.
- const cap = createAssistantTextCapture();
- const line = '{"type":"something-we-have-never-seen","x":1}\n';
- const out = cap.write(line) + cap.end();
- expect(out).toContain("something-we-have-never-seen");
- });
-});
diff --git a/packages/cli/src/team-stream-capture.ts b/packages/cli/src/team-stream-capture.ts
deleted file mode 100644
index 39526f89..00000000
--- a/packages/cli/src/team-stream-capture.ts
+++ /dev/null
@@ -1,277 +0,0 @@
-/**
- * Recovers a child's FULL answer from a `--output-format stream-json` stream.
- *
- * ## Why this exists
- *
- * `claude -p` prints ONLY the final assistant message. A child that answers and
- * then takes one more turn — a background `Task` completing, any late
- * notification prompting an acknowledgement — has its real answer REPLACED on
- * stdout by that epilogue. Measured on a real `team` run: 7,743 output tokens
- * generated, 250 bytes captured, exit 0, reported "succeeded".
- *
- * The data survives upstream. Captured live from `claude -p --output-format
- * stream-json --verbose` against the minimal repro prompt ("say ALPHA, run a
- * bash command, say OMEGA"):
- *
- * assistant → thinking
- * assistant → text "ALPHA_MARKER" <- the answer
- * assistant → tool_use (Bash)
- * user → tool_result
- * assistant → thinking
- * assistant → text "OMEGA_MARKER" <- the epilogue
- * result → .result = "OMEGA_MARKER" <- what print mode prints
- *
- * So the loss is purely a choice of output format, and recovery is a matter of
- * reading the events print mode discards.
- *
- * ## What it keeps, and why all of it
- *
- * Every `text` block from every `assistant` event, concatenated in order. The
- * alternative — keep only the last SUBSTANTIAL message — needs a definition of
- * "substantial", i.e. a byte threshold, which is the exact instrument this
- * codebase already established does not work: `DEFAULT_MIN_OUTPUT_BYTES` is 0
- * because a 200-byte default recorded two correct short answers (141 B, 96 B)
- * as EMPTY. Concatenation has a real cost — intermediate "let me read that
- * file" chatter lands in the response file — but it is bounded and legible,
- * whereas a wrong "substantial" verdict silently discards the answer again.
- *
- * `thinking` blocks are dropped: reasoning is not the answer. `tool_use` and
- * `tool_result` are dropped: they are the child's work, not its report.
- *
- * ## Degradation is the safety property
- *
- * Only a line that is BOTH valid JSON AND carries a recognised stream-json
- * `type` is treated as an event. Everything else — plain prose, a JSON shape
- * from some other protocol, a future event vocabulary we do not know — is
- * passed through VERBATIM.
- *
- * The rule is per-line and never latches, deliberately. Sniffing the format
- * once from the first line is cheaper but fails catastrophically in one
- * direction: a single unexpected banner ahead of the stream would silently
- * disable recovery for the whole run and quietly restore the original bug.
- * Under the per-line rule the worst case is raw JSON in a response file — ugly,
- * and visibly so — instead of a lost answer.
- */
-
-/** Bounded window of recovered prose kept for the `is_error` containment test. */
-const DEDUPE_TAIL_LIMIT = 4096;
-
-/**
- * The `type` values a stream-json event can carry, captured live from
- * `claude -p --output-format stream-json --verbose`. A JSON line whose type is
- * absent or outside this set is not our protocol and is passed through rather
- * than dropped — see the degradation note in the module header.
- */
-export const STREAM_JSON_EVENT_TYPES: ReadonlySet<string> = new Set([
- "system",
- "assistant",
- "user",
- "result",
- // Real protocol event, and its ABSENCE here was a bug: an unrecognised type
- // falls to `passthrough()` (line ~183), so every `rate_limit_event` frame was
- // emitted into the captured answer as prose. Measured 2026-08-22 — a two-byte
- // reply ("OK") was recorded as 191 B of "OK\n{\"type\":\"rate_limit_event\"…}",
- // which corrupts `outputSize` and silently defeats `min_output_bytes`.
- // Enumerated from real `--output-format stream-json` output; the full observed
- // vocabulary is system / assistant / rate_limit_event / result (+ user).
- "rate_limit_event",
-]);
-
-/*
- * TWO CONSUMERS READ THIS SET WITH DIFFERENT MEANINGS — check both before editing.
- *
- * - HERE (`write()` below): membership means "this is our protocol, handle it
- * structurally". A member that is not `assistant` yields no text, i.e. it is
- * DROPPED. A non-member is passed through VERBATIM.
- * - `channel/stream-json-reducer.ts` `reachesAnswer()`: membership means the
- * opposite direction — "safe to HAND to the capture". A non-member is
- * withheld from it.
- *
- * So adding a type here drops it in the team path and forwards it in the channel
- * path, and both are only correct because the two work together. `rate_limit_event`
- * is the worked example: the channel gate already withheld it (its comment records
- * the same measurement), which is why the channel path was accidentally fine while
- * the team path stayed broken — a fix in one consumer left the shared source wrong.
- */
-
-export interface AssistantTextCapture {
- /**
- * Feed raw child stdout. Returns the recovered prose produced by this chunk
- * (often ""), so the caller can stream it straight to disk without ever
- * holding the whole answer in memory.
- */
- write(chunk: string): string;
- /** Flush any trailing partial line. Returns the final recovered prose. */
- end(): string;
-}
-
-interface AssistantContentBlock {
- type?: unknown;
- text?: unknown;
-}
-
-/**
- * Pull the text blocks out of one parsed stream-json event.
- *
- * Returns [] for every event type that is not assistant text, which is most of
- * them (`system`, `user`, `result`) — the caller decides what to do with those.
- */
-function extractAssistantText(event: Record<string, unknown>): string[] {
- if (event.type !== "assistant") return [];
-
- const message = event.message as { content?: unknown } | undefined;
- const content = message?.content;
-
- // Defensive: the observed shape is an array of blocks, but a bare string is a
- // plausible variant and costs one branch to survive.
- if (typeof content === "string") {
- return content.length > 0 ? [content] : [];
- }
- if (!Array.isArray(content)) return [];
-
- const out: string[] = [];
- for (const raw of content) {
- const block = raw as AssistantContentBlock;
- if (block?.type !== "text") continue;
- if (typeof block.text !== "string" || block.text.length === 0) continue;
- out.push(block.text);
- }
- return out;
-}
-
-export function createAssistantTextCapture(): AssistantTextCapture {
- /** Incomplete trailing line held until its newline arrives. */
- let pending = "";
- let emittedAny = false;
- /** Whether the last emitted byte was a newline — drives separator width. */
- let endsWithNewline = false;
- /** Bounded tail of what we have emitted, for the is_error containment test. */
- let dedupeTail = "";
-
- /**
- * Whether the last thing emitted was a recovered MESSAGE or a passthrough
- * LINE. Only messages get a synthesised trailing newline — see `end()`.
- */
- let lastWasMessage = false;
-
- const record = (text: string, kind: "message" | "raw"): void => {
- emittedAny = true;
- lastWasMessage = kind === "message";
- endsWithNewline = text.endsWith("\n");
- dedupeTail = (dedupeTail + text).slice(-DEDUPE_TAIL_LIMIT);
- };
-
- /**
- * Separator before an assistant MESSAGE: always a blank line between two
- * messages, so a concatenated response reads as prose rather than a run-on.
- */
- const messageSeparator = (): string => {
- if (!emittedAny) return "";
- return endsWithNewline ? "\n" : "\n\n";
- };
-
- /**
- * Separator before a passthrough LINE: only enough to start it at column 0.
- *
- * Raw lines are a byte stream, not messages — they already carry their own
- * newline. Using the message separator here would insert a blank line between
- * every pair of prose lines, which would break the header's verbatim
- * guarantee for exactly the degraded case that guarantee exists to protect.
- */
- const rawSeparator = (): string => {
- if (!emittedAny || endsWithNewline) return "";
- return "\n";
- };
-
- const consumeLine = (line: string, terminated: boolean): string => {
- if (line.trim().length === 0) return "";
-
- /**
- * Emit a line we do not own, byte for byte — INCLUDING whether it ended in
- * a newline. A synthesised one would make `outputSize` disagree with what
- * the child actually wrote, and that byte counter is load-bearing: it is
- * what `minOutputBytes` and the empty check measure.
- */
- const passthrough = (): string => {
- const out = `${rawSeparator()}${line}${terminated ? "\n" : ""}`;
- record(out, "raw");
- return out;
- };
-
- let event: Record<string, unknown>;
- try {
- event = JSON.parse(line) as Record<string, unknown>;
- } catch {
- return passthrough(); // plain prose — the pre-recovery output shape
- }
-
- if (typeof event.type !== "string" || !STREAM_JSON_EVENT_TYPES.has(event.type)) {
- return passthrough(); // JSON, but not an event vocabulary we recognise
- }
-
- const texts = extractAssistantText(event);
- if (texts.length > 0) {
- let out = "";
- for (const text of texts) {
- // `messageSeparator()` reads state that `record()` writes, so each block
- // must be recorded before the next one computes its separator.
- const piece = `${messageSeparator()}${text}`;
- out += piece;
- record(piece, "message");
- }
- return out;
- }
-
- // The terminal `result` event normally just repeats the final assistant
- // message — appending it would duplicate the epilogue we already have. But
- // on a FAILED turn it carries the error prose that print mode would have
- // put on stdout, and `classifyRunOutput` matches `[API Error: ...]` against
- // exactly that text. Keeping it here is what preserves api_error detection
- // once the raw pipe is gone.
- if (event.type === "result" && event.is_error === true) {
- const result = typeof event.result === "string" ? event.result : "";
- if (result.trim().length > 0 && !dedupeTail.includes(result)) {
- const out = `${messageSeparator()}${result}`;
- record(out, "message");
- return out;
- }
- }
-
- return "";
- };
-
- return {
- write(chunk: string): string {
- pending += chunk;
- let out = "";
-
- // Split on newlines, keeping the last (possibly incomplete) fragment. A
- // JSON event can be split across chunk boundaries at any byte, so the
- // remainder must survive until its newline arrives.
- let newlineAt = pending.indexOf("\n");
- while (newlineAt !== -1) {
- const line = pending.slice(0, newlineAt);
- pending = pending.slice(newlineAt + 1);
- out += consumeLine(line, true);
- newlineAt = pending.indexOf("\n");
- }
-
- return out;
- },
-
- end(): string {
- // A final event with no trailing newline is still a complete event.
- let out = pending.length > 0 ? consumeLine(pending, false) : "";
- pending = "";
-
- // Keep a RECOVERED response newline-terminated. Never do this after a
- // passthrough line: that path's whole promise is byte-exactness, and the
- // raw pipe it replaces added nothing of its own.
- if (emittedAny && !endsWithNewline && lastWasMessage) {
- out += "\n";
- endsWithNewline = true;
- }
- return out;
- },
- };
-}
diff --git a/packages/cli/src/test-fixtures/stream-json/README.md b/packages/cli/src/test-fixtures/stream-json/README.md
deleted file mode 100644
index 22dab535..00000000
--- a/packages/cli/src/test-fixtures/stream-json/README.md
+++ /dev/null
@@ -1,26 +0,0 @@
-# stream-json fixtures
-
-Captured from real `claude -p --output-format stream-json --verbose` runs. These
-pin the wire shape that `team-stream-capture.ts` reads.
-
-## `haiku-post-answer-turn.jsonl`
-
-The minimal reproduction of the print-mode dropout, captured 2026-08-15 on
-`claude-haiku-4-5`. Prompt:
-
-> Say exactly ALPHA_MARKER on its own line. Then run the bash command: echo hi.
-> Then say exactly OMEGA_MARKER on its own line.
-
-The stream carries **both** assistant text blocks (`ALPHA_MARKER`, then a
-`tool_use`/`tool_result` pair, then `OMEGA_MARKER`), while the terminal `result`
-event's `.result` field holds `OMEGA_MARKER` alone — and `.result` is exactly
-what `claude -p` prints. That single file is the whole bug and the whole fix:
-the answer survives upstream, and only the capture format discarded it.
-
-**Trimmed, not synthesised.** Every retained line is byte-identical to the
-capture. Three event kinds were dropped because they carry local environment
-detail with no bearing on parsing: the `init` event (mcp servers, plugins,
-skills, memory paths, socket path) and the `hook_started` / `hook_response`
-events (which echo the capturing session's own directives). The `system`
-(`thinking_tokens`), `assistant`, `user`, and `result` events remain, so the
-fixture still exercises every branch the parser has.
diff --git a/packages/cli/src/test-fixtures/stream-json/haiku-post-answer-turn.jsonl b/packages/cli/src/test-fixtures/stream-json/haiku-post-answer-turn.jsonl
deleted file mode 100644
index 8efbbdc6..00000000
--- a/packages/cli/src/test-fixtures/stream-json/haiku-post-answer-turn.jsonl
+++ /dev/null
@@ -1,15 +0,0 @@
-{"type":"system","subtype":"thinking_tokens","estimated_tokens":7,"estimated_tokens_delta":7,"uuid":"af1899ec-1f5e-49c7-a9fd-0e166209d2bb","session_id":"77eba8a3-3ec9-43d5-83bd-f9c6772ee8a7"}
-{"type":"system","subtype":"thinking_tokens","estimated_tokens":13,"estimated_tokens_delta":6,"uuid":"f1d6ea3b-bdbb-47de-8ade-2bd3b7c3b319","session_id":"77eba8a3-3ec9-43d5-83bd-f9c6772ee8a7"}
-{"type":"system","subtype":"thinking_tokens","estimated_tokens":55,"estimated_tokens_delta":42,"uuid":"37719872-ba12-4e43-8b1c-7cd0b28e3927","session_id":"77eba8a3-3ec9-43d5-83bd-f9c6772ee8a7"}
-{"type":"system","subtype":"thinking_tokens","estimated_tokens":117,"estimated_tokens_delta":62,"uuid":"cc6120b3-05ff-4ac0-8a54-51e4d9f13ad1","session_id":"77eba8a3-3ec9-43d5-83bd-f9c6772ee8a7"}
-{"type":"assistant","message":{"model":"claude-haiku-4-5-20251001","id":"msg_011Ce3tprG5GqzswPc5VTRJU","type":"message","role":"assistant","content":[{"type":"thinking","thinking":"The user is asking me to:\n1. Say exactly ALPHA_MARKER on its own line\n2. Run the bash command: echo hi\n3. Say exactly OMEGA_MARKER on its own line\n\nThis is a straightforward request. Let me do exactly what they ask.","signature":"Es4DCpMBCBAYAipAiEuDyxIzjPxVd32Ycd6P/ApBSjRBjpjUZGohVCYTvX/FDiD4lLSjVGz40qkdgOVNi8BEtw5lAygiXc3+b/AVfTIZY2xhdWRlLWhhaWt1LTQtNS0yMDI1MTAwMTgAQgh0aGlua2luZ1okYjE0NTIyNTgtYzRmZC00OWU1LWFjNzktZDJlNWJjNDU2ODU4EgyLoWYTRa1tBpp1uKoaDFJJcRdEMNz/sDp1aSIw7cRCv5+MCXVh/AiIz2oi1r67Q0+zOTkQRGl5QnlsdfkrH9BWsHQD3jPIs85yuhf+KucB0GJjezff17OrxV2lgssmZibu8ylTp+JBjhnXsVRRvD/DjPn5WE2MuxEaDuSpf5w6wFeOe61nPTpN1dWFIbig9h5vmL3zKdStqRGHhs0/0cNu2iXwlJj+pATMkoAiCjQalMAthHOccgGIhXJFe1hDwB2MsP0bAkdzfC1ZmBZvJhX5RH7/DAg1Oe+12RuXWS5SWyfrbdiRnTtRcmSLc2URDGSn51xhHD4OV06Jiiw7dIoRaRT8co3nSWRGu4tR/7G0R2ZJnzWoiQQdgezNuoX5M4LqzA8CYS5F6z6MGfR60wQA2AgsfJKAGAE="}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":9,"cache_creation_input_tokens":65260,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":65260,"ephemeral_1h_input_tokens":0},"output_tokens":7,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"77eba8a3-3ec9-43d5-83bd-f9c6772ee8a7","uuid":"6e1dbe29-5a1e-40cb-a7b5-630c3a3cb37b","timestamp":"2026-08-15T04:21:47.429Z","request_id":"req_011Ce3tpqb9JiC4B4KFcnwv3"}
-{"type":"assistant","message":{"model":"claude-haiku-4-5-20251001","id":"msg_011Ce3tprG5GqzswPc5VTRJU","type":"message","role":"assistant","content":[{"type":"text","text":"ALPHA_MARKER"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":9,"cache_creation_input_tokens":65260,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":65260,"ephemeral_1h_input_tokens":0},"output_tokens":7,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"77eba8a3-3ec9-43d5-83bd-f9c6772ee8a7","uuid":"c0d1d00d-be3f-409a-b9a4-bdd1a28bfe55","timestamp":"2026-08-15T04:21:47.764Z","request_id":"req_011Ce3tpqb9JiC4B4KFcnwv3"}
-{"type":"assistant","message":{"model":"claude-haiku-4-5-20251001","id":"msg_011Ce3tprG5GqzswPc5VTRJU","type":"message","role":"assistant","content":[{"type":"tool_use","id":"toolu_016cZneypL5zTZc51vgpw6nh","name":"Bash","input":{"command":"echo hi","description":"Echo hi to stdout"},"caller":{"type":"direct"}}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":9,"cache_creation_input_tokens":65260,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":65260,"ephemeral_1h_input_tokens":0},"output_tokens":7,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"77eba8a3-3ec9-43d5-83bd-f9c6772ee8a7","uuid":"75c9263c-b882-4ca0-a3d7-a20d0e907b22","timestamp":"2026-08-15T04:21:47.778Z","request_id":"req_011Ce3tpqb9JiC4B4KFcnwv3"}
-{"type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_016cZneypL5zTZc51vgpw6nh","type":"tool_result","content":"hi","is_error":false}]},"parent_tool_use_id":null,"session_id":"77eba8a3-3ec9-43d5-83bd-f9c6772ee8a7","uuid":"206966e0-3c6e-48ea-b13d-c78e2b4445ad","timestamp":"2026-08-15T04:21:48.569Z","tool_use_result":{"stdout":"hi","stderr":"","interrupted":false,"isImage":false,"noOutputExpected":false}}
-{"type":"system","subtype":"thinking_tokens","estimated_tokens":1,"estimated_tokens_delta":1,"uuid":"84fea64a-9a72-498a-8465-696341ad1549","session_id":"77eba8a3-3ec9-43d5-83bd-f9c6772ee8a7"}
-{"type":"system","subtype":"thinking_tokens","estimated_tokens":19,"estimated_tokens_delta":18,"uuid":"00f0c891-80d5-4bdb-bbe7-8d0f3f07f65d","session_id":"77eba8a3-3ec9-43d5-83bd-f9c6772ee8a7"}
-{"type":"system","subtype":"thinking_tokens","estimated_tokens":21,"estimated_tokens_delta":2,"uuid":"9e0bbd6b-7fb6-4751-bc37-23f762c2c346","session_id":"77eba8a3-3ec9-43d5-83bd-f9c6772ee8a7"}
-{"type":"system","subtype":"thinking_tokens","estimated_tokens":84,"estimated_tokens_delta":63,"uuid":"1cb81a06-54c5-4c26-8641-b09724cf181c","session_id":"77eba8a3-3ec9-43d5-83bd-f9c6772ee8a7"}
-{"type":"assistant","message":{"model":"claude-haiku-4-5-20251001","id":"msg_011Ce3tq62oPph3X7LRYYyud","type":"message","role":"assistant","content":[{"type":"thinking","thinking":"Good, the bash command executed and returned \"hi\". Now I need to say OMEGA_MARKER.","signature":"EsgCCpMBCBAYAipA/xD//iJWNnzUo1X3Wi7hZL5H4TFADL8jb0sh3+z9oAqG23BXR5f3hK7Z46RqI4Hk5mVItzF6X1b0btg3uG9qBzIZY2xhdWRlLWhhaWt1LTQtNS0yMDI1MTAwMTgAQgh0aGlua2luZ1okYjE0NTIyNTgtYzRmZC00OWU1LWFjNzktZDJlNWJjNDU2ODU4EgxIEqTbGa9WfPjwXLUaDL2pchZlJ5ohJ/OQGiIwd4WQCmGX6Mk6F5G7Fcbin3vM8n2He3U9xu5D/5WMjYGwlPoc261NiPR3fp+VhhALKmJo/1ivLCVhMt068b/3wpBBa/yE07GC0ML9IlGJZ2VDA7/q6S4OCxnHJFbfO1N+ePWmf9Te7F5nFzLrKL8paUEl1VUw3f6jS6d0k5kFsbbscGc4Vry89IMGM1RnjeYd6GhCEBgB"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":8,"cache_creation_input_tokens":1229,"cache_read_input_tokens":65260,"cache_creation":{"ephemeral_5m_input_tokens":1229,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"77eba8a3-3ec9-43d5-83bd-f9c6772ee8a7","uuid":"6d02fa80-7352-470e-9ea4-5b7f1e80f452","timestamp":"2026-08-15T04:21:50.108Z","request_id":"req_011Ce3tq5Ns1FjFxjXke6Kpy"}
-{"type":"assistant","message":{"model":"claude-haiku-4-5-20251001","id":"msg_011Ce3tq62oPph3X7LRYYyud","type":"message","role":"assistant","content":[{"type":"text","text":"OMEGA_MARKER"}],"stop_reason":null,"stop_sequence":null,"stop_details":null,"usage":{"input_tokens":8,"cache_creation_input_tokens":1229,"cache_read_input_tokens":65260,"cache_creation":{"ephemeral_5m_input_tokens":1229,"ephemeral_1h_input_tokens":0},"output_tokens":1,"service_tier":"standard","inference_geo":"not_available"},"diagnostics":null,"context_management":null},"parent_tool_use_id":null,"session_id":"77eba8a3-3ec9-43d5-83bd-f9c6772ee8a7","uuid":"a0644bc0-7a2c-433f-afda-520e0b3a5949","timestamp":"2026-08-15T04:21:50.112Z","request_id":"req_011Ce3tq5Ns1FjFxjXke6Kpy"}
-{"is_error":false,"duration_api_ms":3510,"num_turns":2,"stop_reason":"end_turn","session_id":"77eba8a3-3ec9-43d5-83bd-f9c6772ee8a7","total_cost_usd":0.09058424999999999,"usage":{"input_tokens":17,"cache_creation_input_tokens":66489,"cache_read_input_tokens":65260,"output_tokens":186,"output_tokens_details":{"thinking_tokens":93},"server_tool_use":{"web_search_requests":0,"web_fetch_requests":0},"service_tier":"standard","cache_creation":{"ephemeral_1h_input_tokens":0,"ephemeral_5m_input_tokens":66489},"inference_geo":"not_available","iterations":[{"input_tokens":8,"output_tokens":38,"cache_read_input_tokens":65260,"cache_creation_input_tokens":1229,"cache_creation":{"ephemeral_5m_input_tokens":1229,"ephemeral_1h_input_tokens":0},"type":"message"}],"speed":"standard"},"modelUsage":{"claude-haiku-4-5-20251001":{"inputTokens":17,"outputTokens":186,"cacheReadInputTokens":65260,"cacheCreationInputTokens":66489,"webSearchRequests":0,"costUSD":0.09058424999999999,"contextWindow":200000,"maxOutputTokens":32000,"canonicalModel":"claude-haiku-4-5","provider":"firstParty"}},"permission_denials":[],"terminal_reason":"completed","fast_mode_state":"off","fast_mode_disabled_reason":"sdk_opt_in_required","subtype":"success","api_error_status":null,"result":"OMEGA_MARKER","ttft_ms":2455,"ttft_stream_ms":2080,"time_to_request_ms":560,"type":"result","duration_ms":5235,"uuid":"13beb785-0b57-4d60-a8ea-5fe7e343a3c3"}
diff --git a/packages/cli/src/test-helpers/contract-adapters.ts b/packages/cli/src/test-helpers/contract-adapters.ts
index 90e2d3ac..91c34af9 100644
--- a/packages/cli/src/test-helpers/contract-adapters.ts
+++ b/packages/cli/src/test-helpers/contract-adapters.ts
@@ -2,9 +2,6 @@
/**
* 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).
@@ -17,26 +14,12 @@
* test fails with "ADAPTER:", fix this file, not the test.
*/
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 type { SlotState } from "../pane/index.js";
import * as orchestrator from "../team-orchestrator.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) {
@@ -47,140 +30,6 @@ function method(obj: unknown, names: string[], what: string): Fn {
);
}
-// ------------------------------------------------------------------------------------------
-// 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)
// ------------------------------------------------------------------------------------------
diff --git a/packages/cli/src/test-helpers/contract-fake-child.ts b/packages/cli/src/test-helpers/contract-fake-child.ts
deleted file mode 100755
index df882374..00000000
--- a/packages/cli/src/test-helpers/contract-fake-child.ts
+++ /dev/null
@@ -1,201 +0,0 @@
-#!/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
index 222a152a..fb9f4ce5 100644
--- a/packages/cli/src/test-helpers/contract-mcp.ts
+++ b/packages/cli/src/test-helpers/contract-mcp.ts
@@ -23,9 +23,10 @@ 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");
-/** The stream-json child the channel suites still run (until the channel moves onto panes). */
-export const FAKE_CHILD = join(import.meta.dir, "contract-fake-child.ts");
-/** The pane fake: the team suites pass it explicitly as CLAUDISH_BIN (marker mode). */
+/**
+ * The child every contract suite runs: the pane fake (marker mode with FAKE_MODEL), the
+ * server's default CLAUDISH_BIN.
+ */
export const PANE_FAKE_CHILD = join(SRC_DIR, "pane", "test-helpers", "fake-interactive-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";
@@ -69,13 +70,13 @@ export function serverEnv(
layout: TempLayout,
extra: Record<string, string | undefined> = {}
): Record<string, string> {
- chmodSync(FAKE_CHILD, 0o755);
+ chmodSync(PANE_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,
+ CLAUDISH_BIN: PANE_FAKE_CHILD,
CLAUDE_CONFIG_DIR: layout.configDir,
NO_COLOR: "1",
// The hermetic keys of makePaneTestEnv: a pane child built from this env reads no
@@ -286,7 +287,11 @@ export class McpServer {
return { isError: Boolean(result.isError), text, json, raw: msg };
}
- async close(): Promise<void> {
+ /**
+ * Close the server's stdin, which shuts it down (records ended, panes reaped, exit 0).
+ * SIGKILL only if it has not exited within `graceMs`; the pane watchers clean up then.
+ */
+ async close(graceMs = 15_000): Promise<void> {
if (!this.exited) {
try {
(this.proc.stdin as { end?(): unknown }).end?.();
@@ -295,7 +300,7 @@ export class McpServer {
}
const ended = await Promise.race([
this.proc.exited.then(() => true),
- Bun.sleep(3_000).then(() => false),
+ Bun.sleep(graceMs).then(() => false),
]);
if (!ended) {
this.proc.kill("SIGKILL");
@@ -382,16 +387,17 @@ export function sessionTool(
/**
* 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.
+ * result carries the channel `event` (10.4.0's `status` key, RB7) 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];
+ const event = findField(r.json, "event");
+ if (typeof event === "string") return event;
+ return /"event"\s*:\s*"([a-z_]+)"/.exec(r.text)?.[1];
}
export async function teamCall(
diff --git a/scripts/no-retired-terms.test.ts b/scripts/no-retired-terms.test.ts
index 15315992..f81c1993 100644
--- a/scripts/no-retired-terms.test.ts
+++ b/scripts/no-retired-terms.test.ts
@@ -17,8 +17,9 @@ function filesUnder(dir: string): string[] {
}
test("packages and scripts contain no retired terminology", () => {
- // Mutation target: agent-availability.ts:24. Restoring its previous wording
- // is a representative one-line rename revert and must be reported as file:line.
+ // Mutation target: packages/cli/src/model-selector.ts:336. Restoring its previous
+ // wording ("roster") is a representative one-line rename revert and must be
+ // reported as file:line.
const findings: string[] = [];
for (const root of [join(repositoryRoot, "packages"), join(repositoryRoot, "scripts")]) {
for (const file of filesUnder(root)) {