Skip to content

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

test(mcp): add the mod-contract and session-records e2e suites

Jack Rudenko9b8af03c5854
diff --git a/packages/cli/src/channel/session-records.contract.test.ts b/packages/cli/src/channel/session-records.contract.test.ts
new file mode 100644
index 00000000..fef757d9
--- /dev/null
+++ b/packages/cli/src/channel/session-records.contract.test.ts
@@ -0,0 +1,441 @@
+// packages/cli/src/channel/session-records.contract.test.ts
+/**
+ * The record half that the 10.4.0 suites assume and pane sessions must now produce
+ * (architecture §12.3, §20.1): `meta.json` keeps every 10.4.0 key with its 10.4.0 type,
+ * `events.jsonl` has exactly one `assistant` line per main-chain message id (the magus
+ * monitor's reply rule), a question or a permission dialog opens and closes one wait, a
+ * re-wake keeps its turn, a queued send opens no wait between turns, and a cancelled team
+ * slot's `status.json` row says why.
+ *
+ * A real claudish MCP server over stdio; every session is the pane fake in a real headless
+ * magmux under the test's own CLAUDISH_PANE_ROOT. After each test no pane process or file
+ * may remain.
+ */
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { FAILURE_REASONS } from "../pane/index.js";
+import {
+ MAGMUX_AVAILABLE,
+ McpServer,
+ NO_MAGMUX_MESSAGE,
+ createSession,
+ paneOrphans,
+ sendInput,
+ serverEnv,
+ sessionTool,
+ teamCall,
+} from "../test-helpers/contract-mcp.js";
+import {
+ type TempLayout,
+ makeTempLayout,
+ readJson,
+ readWaitLines,
+ waitFor,
+ waitPairingViolations,
+} from "../test-helpers/contract-records.js";
+import { toMetaRecord } from "./session-manager.js";
+import type { SessionInfo } from "./types.js";
+
+const T_TEST = 40_000;
+const BOOT_MS = 15_000;
+
+let layout: TempLayout;
+let server: McpServer;
+
+if (!MAGMUX_AVAILABLE) console.warn(NO_MAGMUX_MESSAGE);
+
+const dirOf = (id: string) => join(layout.sessionsDir, id);
+
+async function created(args: Parameters<typeof createSession>[1]): Promise<string> {
+ const { sessionId, result } = await createSession(server, args);
+ expect(result.isError).toBe(false);
+ expect(typeof sessionId).toBe("string");
+ return sessionId as string;
+}
+
+async function terminalMeta(id: string, timeoutMs = BOOT_MS): Promise<Record<string, unknown>> {
+ return waitFor(
+ () => {
+ const meta = readJson(join(dirOf(id), "meta.json"));
+ return meta && ["completed", "failed", "timeout", "cancelled"].includes(String(meta.status))
+ ? meta
+ : undefined;
+ },
+ { what: `a terminal meta.json for ${id}`, timeoutMs }
+ );
+}
+
+async function 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);
+}
+
+async function waitRow(
+ id: string,
+ pred: (row: Record<string, unknown>) => boolean,
+ what: string
+): Promise<Record<string, unknown>> {
+ return waitFor(
+ async () => {
+ const row = await rowOf(id);
+ return row && pred(row) ? row : undefined;
+ },
+ { what, timeoutMs: BOOT_MS, intervalMs: 50 }
+ );
+}
+
+const isInt = (x: unknown) => Number.isInteger(x);
+const isStr = (x: unknown) => typeof x === "string" && x.length > 0;
+const isIso = (x: unknown) => isStr(x) && !Number.isNaN(Date.parse(String(x)));
+const isNum = (x: unknown) => typeof x === "number";
+const nullOr = (ok: (y: unknown) => boolean) => (x: unknown) => x === null || ok(x);
+const any = () => true;
+
+/** The 10.4.0 `meta.json` keys and their types, as the magus monitor reads them. */
+const META_104: Record<string, (x: unknown) => boolean> = {
+ sessionId: isStr,
+ model: isStr,
+ spawnModel: nullOr(isStr),
+ status: (x) => ["completed", "failed", "cancelled", "timeout"].includes(String(x)),
+ pid: nullOr(isInt),
+ startedAt: isIso,
+ completedAt: isIso,
+ exitCode: nullOr(isInt),
+ turnsCompleted: isInt,
+ tokensUsed: isNum,
+ elapsedSeconds: isNum,
+ idleSeconds: any,
+ costUsd: nullOr(isNum),
+ toolCallCount: isInt,
+ terminalReason: nullOr((x) => (FAILURE_REASONS as readonly unknown[]).includes(x)),
+ claudeSessionId: isStr,
+ transcriptPath: isStr,
+};
+
+function meta104Violations(meta: Record<string, unknown>): string[] {
+ return Object.entries(META_104)
+ .filter(([key, ok]) => !(key in meta) || !ok(meta[key]))
+ .map(([key]) => `${key}=${JSON.stringify(meta[key])}`);
+}
+
+/** A copy of the monitor's reply rule: the distinct `message.id` of `type:"assistant"` lines. */
+function monitorReplies(eventsText: string): Set<string> {
+ const ids = new Set<string>();
+ for (const line of eventsText.split("\n")) {
+ if (!line.trim()) continue;
+ try {
+ const r = JSON.parse(line) as { type?: unknown; message?: { id?: unknown } };
+ if (r.type === "assistant" && typeof r.message?.id === "string") ids.add(r.message.id);
+ } catch {
+ /* the monitor skips a line it cannot parse */
+ }
+ }
+ return ids;
+}
+
+describe("EMPTY is a failure to the monitor (§20.1)", () => {
+ test("toMetaRecord writes status failed and the FailureReason for an EMPTY session", () => {
+ const info: SessionInfo = {
+ sessionId: "e0000001",
+ model: "m",
+ spawnModel: null,
+ provider: null,
+ state: "EMPTY",
+ shape: "one-shot",
+ pane: "p",
+ panePid: 4242,
+ startedAt: "2026-10-06T00:00:00.000Z",
+ completedAt: "2026-10-06T00:00:05.000Z",
+ exitCode: null,
+ turnsCompleted: 1,
+ tokensIn: 10,
+ tokensOut: 2,
+ costUsd: null,
+ toolCalls: 0,
+ lastActivityAt: null,
+ elapsedSeconds: 5,
+ idleSeconds: null,
+ activity: null,
+ reason: "empty_output",
+ detail: "no answer",
+ pendingInputs: 0,
+ claudeSessionId: "3a4b5c6d-0000-4000-8000-000000000001",
+ transcriptPath: "/x/y.jsonl",
+ captureSource: "transcript",
+ turnSource: "transcript",
+ timeoutSeconds: 600,
+ };
+ const meta = toMetaRecord(info, "/cwd");
+ expect(meta104Violations(meta)).toEqual([]);
+ expect(meta).toMatchObject({
+ status: "failed",
+ terminalReason: "empty_output",
+ state: "EMPTY",
+ pid: 4242,
+ tokensUsed: 12,
+ toolCallCount: 0,
+ });
+ expect("toolCalls" in meta || "reason" in meta || "panePid" in meta).toBe(false);
+ });
+});
+
+describe.skipIf(!MAGMUX_AVAILABLE)("live records", () => {
+ beforeEach(async () => {
+ layout = makeTempLayout("records");
+ 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);
+
+ describe("meta.json keeps the 10.4.0 keys with their 10.4.0 types in every terminal state", () => {
+ test(
+ "completed",
+ async () => {
+ const meta = await terminalMeta(await created({ prompt: "say hello" }));
+ expect(meta104Violations(meta)).toEqual([]);
+ expect(meta).toMatchObject({
+ status: "completed",
+ terminalReason: null,
+ turnsCompleted: 1,
+ });
+ },
+ T_TEST
+ );
+
+ test(
+ "failed: an API-error turn",
+ async () => {
+ const id = await created({ model: "fake-api_error", prompt: "say hello" });
+ const meta = await terminalMeta(id);
+ expect(meta104Violations(meta)).toEqual([]);
+ expect(meta).toMatchObject({ status: "failed", terminalReason: "api_error" });
+ },
+ T_TEST
+ );
+
+ test(
+ "failed: the child exited mid-turn, with its own exit code",
+ async () => {
+ const id = await created({ model: "fake-exit_mid_turn", prompt: "say hello" });
+ const meta = await terminalMeta(id);
+ expect(meta104Violations(meta)).toEqual([]);
+ expect(meta).toMatchObject({
+ status: "failed",
+ terminalReason: "child_exited",
+ exitCode: 3,
+ });
+ },
+ T_TEST
+ );
+
+ test(
+ "cancelled (claudish ended the pane: exitCode null)",
+ async () => {
+ const id = await created({ prompt: "never answer @@HANG@@" });
+ await waitRow(id, (r) => r.state === "RUNNING", "running");
+ await sessionTool(server, "cancel_session", id);
+ const meta = await terminalMeta(id);
+ expect(meta104Violations(meta)).toEqual([]);
+ expect(meta).toMatchObject({
+ status: "cancelled",
+ terminalReason: "cancelled",
+ exitCode: null,
+ });
+ },
+ T_TEST
+ );
+
+ test(
+ "timeout",
+ async () => {
+ const id = await created({ prompt: "never answer @@HANG@@", timeout_seconds: 4 });
+ const meta = await terminalMeta(id, 20_000);
+ expect(meta104Violations(meta)).toEqual([]);
+ expect(meta).toMatchObject({ status: "timeout", terminalReason: "timeout" });
+ },
+ T_TEST
+ );
+ });
+
+ test(
+ "events.jsonl has exactly one assistant line per distinct main-chain message id of the transcript",
+ async () => {
+ const id = await created({ prompt: "use a tool @@TOOL@@" });
+ await terminalMeta(id);
+ const diag = await sessionTool(server, "get_diagnostics", id);
+ const transcriptPath = String(diag.json?.transcriptPath);
+
+ const transcriptIds = new Set<string>();
+ for (const line of readFileSync(transcriptPath, "utf8").split("\n")) {
+ if (!line.trim()) continue;
+ const r = JSON.parse(line) as {
+ type?: string;
+ isSidechain?: boolean;
+ message?: { id?: string };
+ };
+ if (r.type === "assistant" && !r.isSidechain && r.message?.id)
+ transcriptIds.add(r.message.id);
+ }
+ const events = readFileSync(join(dirOf(id), "events.jsonl"), "utf8");
+ const assistantLines = events
+ .split("\n")
+ .filter((l) => l.trim())
+ .map((l) => JSON.parse(l) as { type?: string })
+ .filter((r) => r.type === "assistant");
+
+ expect(transcriptIds.size).toBeGreaterThanOrEqual(2); // the tool_use message and the answer
+ expect([...monitorReplies(events)].sort()).toEqual([...transcriptIds].sort());
+ expect(assistantLines).toHaveLength(transcriptIds.size);
+ },
+ T_TEST
+ );
+
+ test(
+ "RB3 a question in a channel session opens one wait; send_input declines it and closes it to running",
+ async () => {
+ const id = await created({ model: "fake-ask_user_send", prompt: "ask me something" });
+ const blocked = await waitRow(id, (r) => r.state === "AWAITING_INPUT", "the question");
+ expect(blocked.activity).toBe("AskUserQuestion");
+ const open = readWaitLines(dirOf(id)) ?? [];
+ expect(open).toEqual([{ wait: "open", since: expect.any(String), turns: 0 }]);
+
+ expect((await sendInput(server, id, "never mind, answer this")).json).toMatchObject({
+ success: true,
+ });
+ const lines = await waitFor(
+ () => {
+ const l = readWaitLines(dirOf(id));
+ return l && l.length >= 2 ? l : undefined;
+ },
+ { what: "the closed line", timeoutMs: BOOT_MS }
+ );
+
+ expect(lines[1]).toEqual({
+ wait: "closed",
+ since: lines[0].since,
+ at: expect.any(String),
+ to: "running",
+ });
+ expect(waitPairingViolations(lines, true)).toEqual([]);
+ await sessionTool(server, "cancel_session", id);
+ },
+ T_TEST
+ );
+
+ test(
+ "RB3 a permission dialog opens one wait (awaiting_permission); cancel closes it to cancelled",
+ async () => {
+ const id = await created({ model: "fake-permission", prompt: "edit something" });
+ await waitRow(id, (r) => r.state === "AWAITING_PERMISSION", "the permission dialog");
+ expect(readWaitLines(dirOf(id))).toEqual([
+ { wait: "open", since: expect.any(String), turns: 0 },
+ ]);
+
+ await sessionTool(server, "cancel_session", id);
+ await terminalMeta(id);
+ const lines = readWaitLines(dirOf(id)) ?? [];
+
+ expect(lines.map((l) => [l.wait, l.to])).toEqual([
+ ["open", undefined],
+ ["closed", "cancelled"],
+ ]);
+ expect(waitPairingViolations(lines, false)).toEqual([]);
+ },
+ T_TEST
+ );
+
+ test(
+ "D23 a re-wake after the answer closes no wait early and adds no turn",
+ async () => {
+ const id = await created({});
+ await waitFor(() => readWaitLines(dirOf(id))?.length === 1, {
+ what: "boot ready",
+ timeoutMs: BOOT_MS,
+ });
+ await sendInput(server, id, "answer, then wake again @@LATE@@");
+
+ const row = await waitRow(
+ id,
+ (r) => r.state === "AWAITING_INPUT" && r.turns_completed === 1,
+ "the re-woken turn to settle"
+ );
+ const lines = readWaitLines(dirOf(id)) ?? [];
+ const output = await sessionTool(server, "get_output", id);
+
+ expect(row.turns_completed).toBe(1);
+ expect(lines.map((l) => [l.wait, l.turns ?? l.to])).toEqual([
+ ["open", 0],
+ ["closed", "running"],
+ ["open", 1],
+ ]);
+ expect(String(output.json?.output)).toContain("LATE second message");
+ await sessionTool(server, "cancel_session", id);
+ },
+ T_TEST
+ );
+
+ test(
+ "a turn that settles with a send queued writes no wait line between the turns",
+ async () => {
+ const id = await created({});
+ await waitFor(() => readWaitLines(dirOf(id))?.length === 1, {
+ what: "boot ready",
+ timeoutMs: BOOT_MS,
+ });
+ await sendInput(server, id, "answer, then linger @@LINGER@@");
+ await waitRow(id, (r) => r.state === "RUNNING", "turn 1 running");
+ expect((await sendInput(server, id, "second question")).json).toMatchObject({
+ success: true,
+ });
+
+ await waitRow(
+ id,
+ (r) => r.state === "AWAITING_INPUT" && r.turns_completed === 2,
+ "turn 2 to settle"
+ );
+ const lines = readWaitLines(dirOf(id)) ?? [];
+
+ expect(lines.map((l) => [l.wait, l.turns ?? l.to])).toEqual([
+ ["open", 0],
+ ["closed", "running"],
+ ["open", 2],
+ ]);
+ await sessionTool(server, "cancel_session", id);
+ },
+ T_TEST
+ );
+
+ test(
+ "a cancelled team slot's status.json row carries error.reason cancelled",
+ async () => {
+ const teamDir = join(layout.cwd, "team-run");
+ const run = await teamCall(server, "run", {
+ path: teamDir,
+ models: ["contract-fake-a"],
+ input: "never answer @@HANG@@",
+ });
+ expect(run.isError).toBe(false);
+
+ const cancel = await server.callTool("team", { mode: "cancel", path: teamDir });
+ expect(cancel.isError).toBe(false);
+ const row = await waitFor(
+ () => {
+ const status = readJson(join(teamDir, "status.json"));
+ const models = (status?.models ?? {}) as Record<string, Record<string, unknown>>;
+ const slot = Object.values(models)[0];
+ return slot?.state === "CANCELLED" ? slot : undefined;
+ },
+ { what: "the CANCELLED row", timeoutMs: BOOT_MS }
+ );
+
+ expect((row.error as Record<string, unknown> | undefined)?.reason).toBe("cancelled");
+ },
+ T_TEST
+ );
+});
diff --git a/packages/cli/src/mcp-contract.e2e.test.ts b/packages/cli/src/mcp-contract.e2e.test.ts
new file mode 100644
index 00000000..377bc64d
--- /dev/null
+++ b/packages/cli/src/mcp-contract.e2e.test.ts
@@ -0,0 +1,366 @@
+/**
+ * The mod contract v1 (architecture §8, §12.3) through the REAL MCP server over JSON-RPC,
+ * every child the pane fake (marker mode) in a real headless magmux under the test's own
+ * CLAUDISH_PANE_ROOT.
+ *
+ * What is pinned: the EXACT key set of every §8 shape (`Object.keys(x).sort()` equality —
+ * a key added or dropped by accident fails here, a deliberate one is added here and to
+ * pane/contract.ts together), `contract_version: 1` and the exact `capabilities`, state
+ * values inside the closed set, cancel idempotency, `unchanged` captures while idle, and
+ * the JSON `ContractError` envelope (`isError: true`) on the error path of every §8 verb.
+ *
+ * The team directory is inside the server's cwd, so `validateSessionPath` accepts it.
+ */
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { join } from "node:path";
+import { CAPABILITIES, SLOT_STATES } from "./pane/contract.js";
+import {
+ 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 T_TEST = 60_000;
+
+type Json = Record<string, unknown>;
+
+const keys = (v: unknown): string[] => Object.keys(v as Json).sort();
+
+const SLOT_ROW_KEYS = [
+ "activity",
+ "cost_usd",
+ "idle_seconds",
+ "last_activity_at",
+ "model",
+ "pane",
+ "provider",
+ "reason",
+ "slot",
+ "state",
+ "tokens_in",
+ "tokens_out",
+ "tool_calls",
+ "turns_completed",
+].sort();
+const SESSION_ROW_KEYS = [
+ ...SLOT_ROW_KEYS,
+ "completed_at",
+ "elapsed_seconds",
+ "session_id",
+ "started_at",
+].sort();
+const TEAM_RUN_ROW_KEYS = [
+ "finished_at",
+ "kind",
+ "outcome",
+ "path",
+ "run_id",
+ "slots",
+ "started_at",
+ "state",
+].sort();
+const CAPTURE_KEYS = ["cols", "cursor", "final", "lines", "rows", "seq"].sort();
+const CAPTURE_SPANS_KEYS = [...CAPTURE_KEYS, "spans"].sort();
+const UNCHANGED_KEYS = ["final", "seq", "unchanged"];
+const TEAM_CANCEL_KEYS = ["path", "results", "run_id"];
+const TEAM_CANCEL_ENTRY_KEYS = ["changed", "slot", "state"];
+const SESSION_CANCEL_KEYS = ["changed", "session_id", "state"];
+
+let layout: TempLayout;
+let server: McpServer;
+
+if (!MAGMUX_AVAILABLE) console.warn(NO_MAGMUX_MESSAGE);
+
+beforeEach(async () => {
+ layout = makeTempLayout("mcpcontract");
+ server = await McpServer.start({
+ // the fake's safety exit must not end a @@HANG@@ slot mid-test
+ env: serverEnv(layout, { CONTRACT_FAKE_MAX_MS: "60000" }),
+ cwd: layout.cwd,
+ });
+});
+afterEach(async () => {
+ await server.close();
+ const report = await paneOrphans(layout);
+ layout.cleanup();
+ expect(report).toEqual({ processes: [], files: [] });
+});
+
+function ok(r: ToolResult): Json {
+ expect(r.isError).toBe(false);
+ expect(r.json).toBeDefined();
+ return r.json as Json;
+}
+
+function contractError(r: ToolResult, code: string): void {
+ expect(r.isError).toBe(true);
+ const body = JSON.parse(r.text) as Json;
+ expect(keys(body)).toEqual(["error"]);
+ expect(keys(body.error)).toEqual(["code", "message"]);
+ expect((body.error as Json).code).toBe(code);
+ expect(typeof (body.error as Json).message).toBe("string");
+}
+
+function expectContractMeta(body: Json): void {
+ expect(body.contract_version).toBe(1);
+ expect(body.capabilities).toEqual([...CAPABILITIES]);
+}
+
+function expectSlotRow(row: Json, extended: string[] = SLOT_ROW_KEYS): void {
+ expect(keys(row)).toEqual(extended);
+ expect(SLOT_STATES).toContain(row.state as never);
+}
+
+function expectRunRow(run: Json): void {
+ expect(keys(run)).toEqual(TEAM_RUN_ROW_KEYS);
+ expect(["ACTIVE", "SETTLED"]).toContain(run.state as string);
+ for (const s of run.slots as Json[]) expectSlotRow(s);
+}
+
+function team(args: Json): Promise<ToolResult> {
+ return server.callTool("team", args);
+}
+
+async function sessionRow(id: string): Promise<Json | undefined> {
+ const list = ok(await server.callTool("list_sessions", { include_completed: true }));
+ return (list.sessions as Json[]).find((s) => s.session_id === id);
+}
+
+describe.skipIf(!MAGMUX_AVAILABLE)("team verbs: exact shapes, idempotent cancel", () => {
+ test(
+ "list, status, capture and cancel of a live run answer exactly the §8 keys",
+ async () => {
+ const path = join(layout.cwd, "team-contract");
+ const started = ok(
+ await team({
+ mode: "run",
+ path,
+ models: ["contract-fake-a", "contract-fake-b"],
+ input: "stay busy @@HANG@@",
+ })
+ );
+ const runId = started.run_id as string;
+ expect(typeof runId).toBe("string");
+ expectRunRow(started.run as Json);
+
+ // A — list
+ const list = ok(await team({ mode: "list" }));
+ expect(keys(list)).toEqual(["capabilities", "contract_version", "runs"]);
+ expectContractMeta(list);
+ const listed = (list.runs as Json[]).find((r) => r.run_id === runId) as Json;
+ expect(listed).toBeDefined();
+ expectRunRow(listed);
+ expect(listed.state).toBe("ACTIVE");
+ expect((listed.slots as Json[]).map((s) => s.slot)).toEqual(["01", "02"]);
+
+ // B — status additions
+ const status = ok(await team({ mode: "status", path }));
+ expectContractMeta(status);
+ expectRunRow(status.run as Json);
+ expect((status.run as Json).run_id).toBe(runId);
+ const byRunId = ok(await team({ mode: "status", path, run_id: runId }));
+ expectContractMeta(byRunId);
+ expect((byRunId.run as Json).run_id).toBe(runId);
+
+ // D — capture, with and without spans
+ const cap = ok(await team({ mode: "capture", path, slot: "01" }));
+ expect(keys(cap)).toEqual(CAPTURE_KEYS);
+ expect(cap.cols).toBe(160);
+ expect(cap.rows).toBe(50);
+ expect((cap.lines as string[]).length).toBe(50);
+ expect(keys(cap.cursor)).toEqual(["x", "y"]);
+ const spans = ok(await team({ mode: "capture", path, slot: "01", spans: true }));
+ expect(keys(spans)).toEqual(CAPTURE_SPANS_KEYS);
+ expect((spans.spans as unknown[]).length).toBe(50);
+
+ // E — unknown slot on cancel, missing slot on capture
+ contractError(await team({ mode: "cancel", path, slot: "99" }), "unknown_slot");
+ contractError(await team({ mode: "capture", path, slot: "99" }), "unknown_slot");
+ contractError(await team({ mode: "capture", path }), "invalid_args");
+
+ // C — cancel one slot, then the run; each repeat is changed:false
+ const one = ok(await team({ mode: "cancel", path, slot: "01" }));
+ expect(keys(one)).toEqual(TEAM_CANCEL_KEYS);
+ expect(one.run_id).toBe(runId);
+ expect(one.results).toEqual([{ slot: "01", state: "CANCELLED", changed: true }]);
+ for (const e of one.results as Json[]) expect(keys(e)).toEqual(TEAM_CANCEL_ENTRY_KEYS);
+ const all = ok(await team({ mode: "cancel", path, run_id: runId }));
+ expect(keys(all)).toEqual(TEAM_CANCEL_KEYS);
+ expect(all.results).toEqual([
+ { slot: "01", state: "CANCELLED", changed: false },
+ { slot: "02", state: "CANCELLED", changed: true },
+ ]);
+ const again = ok(await team({ mode: "cancel", path }));
+ expect(again.results).toEqual([
+ { slot: "01", state: "CANCELLED", changed: false },
+ { slot: "02", state: "CANCELLED", changed: false },
+ ]);
+
+ // the settled run, then a closed pane's final screen
+ const settled = ok(await team({ mode: "status", path }));
+ expect((settled.run as Json).state).toBe("SETTLED");
+ expect((settled.run as Json).outcome).toBe("all-failed");
+ for (const s of (settled.run as Json).slots as Json[]) {
+ expect(s.reason).toBe("cancelled");
+ expect(s.idle_seconds).toBeNull();
+ expect(s.activity).toBeNull();
+ }
+ const final = await waitFor(
+ async () => {
+ const c = ok(await team({ mode: "capture", path, slot: "02" }));
+ return c.final === true ? c : undefined;
+ },
+ { what: "slot 02's final screen", timeoutMs: 15_000, intervalMs: 200 }
+ );
+ expect(keys(final)).toEqual(CAPTURE_KEYS);
+ const same = ok(
+ await team({ mode: "capture", path, slot: "02", since_seq: final.seq as number })
+ );
+ expect(keys(same)).toEqual(UNCHANGED_KEYS);
+ expect(same).toEqual({ unchanged: true, seq: final.seq, final: true });
+ },
+ T_TEST
+ );
+});
+
+describe.skipIf(!MAGMUX_AVAILABLE)("channel verbs: exact shapes, idempotent cancel", () => {
+ test(
+ "create_session, list_sessions, capture_session, send_input and cancel_session",
+ async () => {
+ const created = ok(await server.callTool("create_session", { model: "contract-fake-model" }));
+ expect(keys(created)).toEqual(["session_id", "state"]);
+ expect(created.state).toBe("STARTING");
+ const id = created.session_id as string;
+
+ await waitFor(async () => (await sessionRow(id))?.state === "AWAITING_INPUT", {
+ what: "the promptless session to be idle",
+ timeoutMs: 20_000,
+ intervalMs: 100,
+ });
+
+ // B — list_sessions
+ const list = ok(await server.callTool("list_sessions", {}));
+ expect(keys(list)).toEqual(["capabilities", "contract_version", "sessions"]);
+ expectContractMeta(list);
+ const row = (list.sessions as Json[]).find((s) => s.session_id === id) as Json;
+ expectSlotRow(row, SESSION_ROW_KEYS);
+ expect(row.slot).toBe(id);
+ expect(row.reason).toBeNull();
+ expect(row.activity).toBeNull();
+
+ // D — capture: wait for two equal seqs, then since_seq answers unchanged
+ const stable = await waitFor(
+ async () => {
+ const a = ok(await server.callTool("capture_session", { session_id: id }));
+ await Bun.sleep(400);
+ const b = ok(await server.callTool("capture_session", { session_id: id }));
+ return a.seq === b.seq && (b.seq as number) > 0 ? b : undefined;
+ },
+ { what: "an idle screen", timeoutMs: 15_000, intervalMs: 100 }
+ );
+ expect(keys(stable)).toEqual(CAPTURE_KEYS);
+ expect(stable.final).toBe(false);
+ const unchanged = ok(
+ await server.callTool("capture_session", { session_id: id, since_seq: stable.seq })
+ );
+ expect(keys(unchanged)).toEqual(UNCHANGED_KEYS);
+ expect(unchanged).toEqual({ unchanged: true, seq: stable.seq, final: false });
+ const lower = ok(
+ await server.callTool("capture_session", {
+ session_id: id,
+ since_seq: (stable.seq as number) - 1,
+ })
+ );
+ expect(keys(lower)).toEqual(CAPTURE_KEYS);
+ const spans = ok(await server.callTool("capture_session", { session_id: id, spans: true }));
+ expect(keys(spans)).toEqual(CAPTURE_SPANS_KEYS);
+
+ // send_input answer shape
+ const sent = ok(await server.callTool("send_input", { session_id: id, text: "hello" }));
+ expect(keys(sent)).toEqual(["queued", "success"]);
+ expect(sent.success).toBe(true);
+ expect(typeof sent.queued).toBe("number");
+
+ // C — cancel_session, twice
+ const first = ok(await server.callTool("cancel_session", { session_id: id }));
+ expect(keys(first)).toEqual(SESSION_CANCEL_KEYS);
+ expect(first).toEqual({ session_id: id, state: "CANCELLED", changed: true });
+ const second = ok(await server.callTool("cancel_session", { session_id: id }));
+ expect(second).toEqual({ session_id: id, state: "CANCELLED", changed: false });
+
+ const after = (await sessionRow(id)) as Json;
+ expectSlotRow(after, SESSION_ROW_KEYS);
+ expect(after.state).toBe("CANCELLED");
+ expect(after.reason).toBe("cancelled");
+ expect(after.idle_seconds).toBeNull();
+ expect(typeof after.completed_at).toBe("string");
+ const notListed = ok(await server.callTool("list_sessions", { include_completed: false }));
+ expect((notListed.sessions as Json[]).some((s) => s.session_id === id)).toBe(false);
+
+ // a refused send after the end names its reason and the state
+ const refused = ok(await server.callTool("send_input", { session_id: id, text: "late" }));
+ expect(refused).toEqual({ success: false, reason: "terminal", state: "CANCELLED" });
+ },
+ T_TEST
+ );
+});
+
+describe.skipIf(!MAGMUX_AVAILABLE)("every §8 verb answers its errors as a ContractError", () => {
+ test(
+ "team status/cancel/capture and the channel verbs",
+ async () => {
+ const nowhere = join(layout.cwd, "no-such-run");
+ const bogus = "team-00000000-zzzz-000000";
+
+ // team status: unknown path, unknown run_id, path outside the cwd, missing path
+ contractError(await team({ mode: "status", path: nowhere }), "unknown_run");
+ contractError(await team({ mode: "status", path: nowhere, run_id: bogus }), "unknown_run");
+ contractError(await team({ mode: "status", path: "/etc" }), "invalid_args");
+ contractError(await team({ mode: "status" }), "invalid_args");
+ contractError(await team({ mode: "status", path: nowhere, run_id: "" }), "invalid_args");
+
+ // team cancel / capture
+ contractError(await team({ mode: "cancel", path: nowhere }), "unknown_run");
+ contractError(await team({ mode: "cancel", path: nowhere, run_id: bogus }), "unknown_run");
+ contractError(
+ await team({ mode: "capture", path: nowhere, slot: "01", run_id: bogus }),
+ "unknown_run"
+ );
+ contractError(await team({ mode: "capture", path: nowhere, slot: "01" }), "unknown_run");
+ contractError(await team({ mode: "capture", path: nowhere }), "invalid_args");
+ contractError(
+ await team({ mode: "capture", path: nowhere, slot: "01", since_seq: "x" }),
+ "invalid_args"
+ );
+
+ // channel verbs
+ contractError(
+ await server.callTool("capture_session", { session_id: "deadbeef" }),
+ "unknown_session"
+ );
+ contractError(
+ await server.callTool("cancel_session", { session_id: "deadbeef" }),
+ "unknown_session"
+ );
+ contractError(
+ await server.callTool("capture_session", { session_id: "deadbeef", since_seq: "x" }),
+ "invalid_args"
+ );
+ contractError(await server.callTool("capture_session", {}), "invalid_args");
+ contractError(await server.callTool("cancel_session", {}), "invalid_args");
+
+ // list verbs have no error for valid input, and carry the contract keys
+ const teams = ok(await team({ mode: "list" }));
+ expectContractMeta(teams);
+ expect(teams.runs).toEqual([]);
+ const sessions = ok(await server.callTool("list_sessions", { include_completed: true }));
+ expectContractMeta(sessions);
+ expect(sessions.sessions).toEqual([]);
+ },
+ T_TEST
+ );
+});