Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(mcp)!: run team slots as interactive panes in headless magmux
Jack Rudenko7a22c8447009
diff --git a/packages/cli/src/channel/session-manager.ts b/packages/cli/src/channel/session-manager.tsindex 4451e07a..9f22044a 100644--- a/packages/cli/src/channel/session-manager.ts+++ b/packages/cli/src/channel/session-manager.ts@@ -46,12 +46,7 @@ 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,- classifyRunOutput,- meaningfulStderr,-} from "../team-orchestrator.js";+import { STDOUT_TAIL_LIMIT, type TeamRunOutcome } from "../team-orchestrator.js";import { readTokenStatsAt } from "../team-stats.js";import { sessionsDirFrom } from "./home-dir.js";import { hostPidFrom } from "./parent-proof.js";@@ -343,6 +338,57 @@ function writeJsonAtomic(path: string, value: unknown): void {/** 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();+}++/** "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;+}+const TERMINAL_STATUSES: readonly SessionStatus[] = ["completed", "failed", "cancelled", "timeout"];/** Every `SessionStatus`, for validating one read back off disk. */@@ -2315,13 +2361,7 @@ export class SessionManager {};}- const reason = classifyRunOutput({- outputSize: entry.proseBytes,- stdoutTail: entry.proseTail,- stderr: entry.stderr,- minOutputBytes: 0,- captureMode: "stream-json",- });+ const reason = classifyStreamJsonProse(entry.proseBytes, entry.proseTail, entry.stderr);if (reason) {return { state: "failed", content: withStderr(`${reason.reason}: ${reason.detail}`) };}diff --git a/packages/cli/src/channel/test-helpers/fake-dropout-child.ts b/packages/cli/src/channel/test-helpers/fake-dropout-child.tsdeleted file mode 100644index b69a9bf1..00000000--- a/packages/cli/src/channel/test-helpers/fake-dropout-child.ts+++ /dev/null@@ -1,28 +0,0 @@-#!/usr/bin/env bun-/**- * Fake claudish child for the MCP team shape-contract test.- *- * The real flags (`--model`, `-y`, `--stdin`, `--quiet`) are intentionally- * ignored. The child drains stdin, then reproduces the measured 250-byte final- * message from a run whose real answer was displaced by a background-task turn.- */--export {};--const DROPOUT_EPILOGUE =- 'The background agent finished: it counted **99** `.ts` files under `packages/cli/src/` containing "timeout" (case-insensitive; 77 for strict-lowercase). ' +- "That was step 1's parallel task — the review and vote above are complete and unaffected by it.";--async function main() {- for await (const chunk of process.stdin) {- void chunk;- }-- process.stdout.write(`${DROPOUT_EPILOGUE}\n`);- process.exit(0);-}--main().catch((err) => {- process.stderr.write(`${String(err)}\n`);- process.exit(1);-});diff --git a/packages/cli/src/channel/test-helpers/fake-streamjson-child.ts b/packages/cli/src/channel/test-helpers/fake-streamjson-child.tsdeleted file mode 100644index ed06ac40..00000000--- a/packages/cli/src/channel/test-helpers/fake-streamjson-child.ts+++ /dev/null@@ -1,154 +0,0 @@-#!/usr/bin/env bun-/**- * Fake claudish child for the team stream-json recovery regression.- *- * It models the real post-answer-turn capture: a substantial answer, a tool- * round trip, a short background-task epilogue, and a terminal result whose- * `.result` contains only that epilogue. Without `--output-format stream-json`- * it behaves like `claude -p` and prints only the terminal result text.- */--export {};--const LONG_ANSWER = [- "# Independent review",- "",- "The implementation preserves the complete answer even when a late background task creates another assistant turn.",- "The recovered response still carries the caller's required vote contract and remains suitable for judging.",- "",- "```vote",- "RESPONSE: 01",- "VERDICT: APPROVE",- "CONFIDENCE: 9",- "SUMMARY: The answer-survival behavior is correct and covered by a process-level regression.",- "KEY_ISSUES: None",- "```",- "",- "This paragraph makes the answer deliberately substantial, so losing it cannot be confused with a harmless formatting change.",-].join("\n");--const BACKGROUND_EPILOGUE =- "The background task has now finished; its bookkeeping note does not change the vote above.";--const THINKING_DETAIL =- "I am checking the implementation and keeping private reasoning out of the final answer. ".repeat(- 120- );-const TOOL_INPUT_DETAIL =- "Inspect the repository without changing it, then report only the relevant evidence. ".repeat(60);-const TOOL_RESULT_DETAIL =- "Inspection completed successfully; the requested evidence was collected. ".repeat(60);--function buildStreamJson(): string {- const events = [- {- type: "system",- subtype: "thinking_tokens",- estimated_tokens: 12,- estimated_tokens_delta: 12,- session_id: "fake-stream-json-session",- },- {- type: "assistant",- message: {- role: "assistant",- content: [{ type: "thinking", thinking: THINKING_DETAIL }],- },- session_id: "fake-stream-json-session",- },- {- type: "assistant",- message: {- role: "assistant",- content: [{ type: "text", text: LONG_ANSWER }],- },- session_id: "fake-stream-json-session",- },- {- type: "assistant",- message: {- role: "assistant",- content: [- {- type: "tool_use",- id: "toolu_fake_stream_json",- name: "Bash",- input: { command: "true", description: TOOL_INPUT_DETAIL },- },- ],- },- session_id: "fake-stream-json-session",- },- {- type: "user",- message: {- role: "user",- content: [- {- type: "tool_result",- tool_use_id: "toolu_fake_stream_json",- content: TOOL_RESULT_DETAIL,- is_error: false,- },- ],- },- session_id: "fake-stream-json-session",- },- {- type: "system",- subtype: "thinking_tokens",- estimated_tokens: 4,- estimated_tokens_delta: 4,- session_id: "fake-stream-json-session",- },- {- type: "assistant",- message: {- role: "assistant",- content: [- {- type: "thinking",- thinking: "The background task finished, so I should acknowledge it briefly.",- },- ],- },- session_id: "fake-stream-json-session",- },- {- type: "assistant",- message: {- role: "assistant",- content: [{ type: "text", text: BACKGROUND_EPILOGUE }],- },- session_id: "fake-stream-json-session",- },- {- type: "result",- subtype: "success",- is_error: false,- num_turns: 2,- result: BACKGROUND_EPILOGUE,- session_id: "fake-stream-json-session",- },- ];-- return `${events.map((event) => JSON.stringify(event)).join("\n")}\n`;-}--async function main() {- for await (const chunk of process.stdin) {- void chunk;- }-- const args = process.argv.slice(2);- const outputFormatAt = args.indexOf("--output-format");- const streamJsonRequested = outputFormatAt !== -1 && args[outputFormatAt + 1] === "stream-json";-- process.stdout.write(streamJsonRequested ? buildStreamJson() : `${BACKGROUND_EPILOGUE}\n`);- process.exit(0);-}--main().catch((err) => {- process.stderr.write(`${String(err)}\n`);- process.exit(1);-});diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex 232fadbf..0ef1d283 100644--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -669,12 +669,27 @@ async function runCli() {const sessionPath = join(process.cwd(), `.claudish-team-${Date.now()}`);if (mode === "json") {- // JSON mode: run models without grid, collect JSON output to stdout- const { setupSession, runModels } = await import("./team-orchestrator.js");+ // JSON mode: every model runs as an interactive pane in a headless magmux (the+ // same runModels as the MCP `team` tool); each answer is read from its+ // transcript, so no child output flag is passed. Ctrl-C reaps every pane.+ const { installPaneShutdownHooks } = await import("./pane/index.js");+ const { preflightTeamRun, setupSession, runModels } = await import(+ "./team-orchestrator.js"+ );+ installPaneShutdownHooks({ exitAfter: true });+ try {+ await preflightTeamRun({+ path: sessionPath,+ slots: cliConfig.team.length,+ input: prompt,+ });+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ console.error(`Error: ${msg}`);+ process.exit(msg.startsWith("invalid_args") ? 2 : 1);+ }setupSession(sessionPath, cliConfig.team, prompt);- const status = await runModels(sessionPath, {- claudeFlags: ["--json"],- });+ const status = await runModels(sessionPath);// Build JSON result with model responses includedconst result: Record<string, unknown> = { ...status, responses: {} };diff --git a/packages/cli/src/mcp-server.ts b/packages/cli/src/mcp-server.tsindex c7d3eaa9..9905144a 100644--- a/packages/cli/src/mcp-server.ts+++ b/packages/cli/src/mcp-server.ts@@ -43,6 +43,15 @@ import {groupRecommendedModels,normalizePricingDisplay,} from "./model-loader.js";+import {+ ContractErrorException,+ type FailureReason,+ SLOT_STATES,+ type SlotState,+ TERMINAL_STATES,+ type TeamRunRow,+ contractMeta,+} from "./pane/index.js";import { findAvailablePort } from "./port-manager.js";import { ensureEndpointsRegistered } from "./providers/endpoint-registration.js";import { compareByReleaseDateDesc } from "./providers/model-ordering.js";@@ -56,20 +65,25 @@ import { route } from "./providers/routing-rules.js";import { createProxyServer } from "./proxy-server.js";import { sanitizeForReport } from "./redact.js";import {+ type ModelStatus,type TeamRunOutcome,+ type TeamStatus,cancelTeamRun,+ captureTeamSlot,getStatus,+ isSupersededRun,judgeResponses,+ listTeamRuns,+ preflightTeamRun,readTeamInputFile,readTeamStatus,- runModels,setupSession,shutdownAllTeamRuns,startModels,summarise,- teamSlotActivity,- teamSlotIdleSeconds,- teamSlotLiveBytes,+ teamLiveMaps,+ teamRunRow,+ teamRunRowFromDisk,validateSessionPath,} from "./team-orchestrator.js";import type { ProxyServer } from "./types.js";@@ -386,20 +400,37 @@ function orderingKey(model: any): { releaseDate?: string; id?: string } {* The action a caller should take for each failure class. Deterministic strings* so the agent branches on a known value instead of parsing prose.*/-const NEXT_STEP: Record<string, string> = {- nonzero_exit: "read the evidence log, then retry or drop the model",+export const NEXT_STEP: Record<FailureReason, string> = {cancelled:"you stopped this slot; nothing is wrong with it. Re-run it if you still want its vote",timeout: "grid mode only — magmux ended the pane. The orchestrator has no deadline",+ boot_timeout:+ "the child never reached its prompt and its screen kept changing — read the evidence " ++ "screen; usually a slow catalog fetch or MCP server start",+ boot_blocked:+ "a screen claudish does not know stopped boot — its text is in `what`; answer it once " ++ "interactively in that directory",+ first_run_dialog:+ "run claude (or claudish --model X) once interactively in that directory and answer the " ++ "dialog named in `what`; claudish never accepts it for you",+ agent_rejected: "fix the agent name; the available agents are listed in `what`",+ prompt_not_accepted: "the REPL never took the prompt — read the evidence screen; retry",+ prompt_not_read:+ "the child never read all of its task file — check that its agent or tool flags allow " ++ "Read and that the model can call tools; `what` says which lines were read",+ child_exited: "read the evidence screen, then retry or drop the model",+ pane_lost: "magmux died — check `magmux --version` ≥ 0.14.0 and retry",+ blocked:+ "the child asked a question team cannot answer — make the prompt self-contained or use " ++ "create_session",api_error: "retry once, or route via a different provider (or@<model>)",- background_task_ceiling:- "set CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS=0 for children, or forbid background work in the prompt",+ refused: "the model refused — rephrase or drop the model",empty_output: "retry once; if it repeats, drop the model",shape_mismatch:- "the response does not carry the shape you required. Every assistant message the " +- "child emitted was captured, so nothing was lost in transit — the model did not " +- "produce it. Re-prompt with the required format restated; do NOT count this slot " +- "as a vote",+ "the answer (assistant text after the task was read) did not match. Every assistant " ++ "message of the turn was read from the transcript, so nothing was lost in transit — " ++ "the model did not produce it. Re-prompt with the required format restated; do NOT " ++ "count this slot as a vote",};/** `18864` → `18.4KB`. */@@ -475,21 +506,26 @@ export function buildChildClaudeFlags(agent: unknown, claudeFlags: unknown): str/*** The prose that stops a caller reading `outputSize` as progress.*- * A slot's `outputSize` is written once, when it finishes, so a RUNNING slot+ * A slot's `outputSize` is written once, when it finishes, so a working slot* always reports 0. Real orchestrators have read that 0 next to a 20-minute-old* `startedAt` and concluded the slot produced nothing; one then had to reason its* way back out in front of the user. The note leads with that, because a caller* skimming a JSON blob reads the first clause and stops.*- * Returned only while something is still RUNNING — on a settled run the states- * are final, `outputSize` means exactly what it says, and this would be noise.+ * Returned only while some slot is not terminal — on a settled run the states are+ * final, `outputSize` means exactly what it says, and this would be noise.*/-export function teamStatusNote(opts: { anyRunning: boolean; live: boolean }): string | undefined {- if (!opts.anyRunning) return undefined;+export function teamStatusNote(opts: {+ anyActive: boolean;+ live: boolean;+ /** slots whose turn sits in `finishing` with no end-of-turn record (R3-M4) */+ endRecordMissing?: string[];+}): string | undefined {+ if (!opts.anyActive) return undefined;const trap ="outputSize is the size of the FINAL answer and is written once, when a slot " +- "finishes. Every RUNNING slot therefore reports 0 however much work it has done: " +- "it is NOT a progress signal, and 0 there does not mean the slot produced nothing.";+ "finishes. Every slot still working therefore reports 0 however much work it has " ++ "done: it is NOT a progress signal, and 0 there does not mean the slot produced nothing.";// No live handles means this server did not spawn the run, or was restarted// under it. Promising fields that are null would send the reader after// evidence that is not there.@@ -500,62 +536,95 @@ export function teamStatusNote(opts: { anyRunning: boolean; live: boolean }): st"whatever was last written to status.json.");}+ const missing = opts.endRecordMissing ?? [];+ const missingNote = missing.length+ ? ` Slot(s) ${missing.join(", ")}: the model's message ended long ago with a static ` ++ "screen and no Stop hook running, but Claude Code never wrote its end-of-turn record " ++ "(turn_end_record_missing). Nothing ends such a slot on a timer — cancel it if it " ++ "stays this way."+ : "";return (- `${trap} Judge a running slot on three fields read TOGETHER: ` ++ `${trap} Judge a working slot on three fields read TOGETHER: ` +"live_output_bytes_by_slot (answer bytes so far, the number outputSize will become), " +- "idle_seconds_by_slot (seconds of silence) and activity_by_slot (what it is doing). " +- "Silence in tool_executing is a build or test suite running, and is not a failure " +- 'signal. Nothing cancels on your behalf — use mode:"cancel" if you decide to.'+ "idle_seconds_by_slot (seconds of silence) and activity_by_slot (what it is doing: a " ++ 'tool name, "thinking", "background" or "finishing"). Silence while a tool runs is a ' ++ "build or test suite, and is not a failure signal. Nothing cancels on your behalf — " ++ `use mode:"cancel" if you decide to.${missingNote}`);}+/** A persisted state outside the closed set reads FAILED (terminal), as §8 B says. */+function slotStateOf(m: ModelStatus): string {+ return (SLOT_STATES as readonly string[]).includes(m.state) ? m.state : "FAILED";+}+/**- * Assemble the `status` response. Pure and exported so the contract above can be- * tested without spawning a run: every liveness input is a parameter.+ * Assemble the `status` response: the legacy path-based payload, the contract's+ * `contract_version`/`capabilities`, and `run` (§8 B). Pure and exported so the payload+ * can be tested without spawning a run: every liveness input is a parameter.*/export function buildTeamStatusPayload(opts: {- status: import("./team-orchestrator.js").TeamStatus;+ status: TeamStatus;sessionPath: string;idle: Record<string, number> | null;activity: Record<string, string> | null;liveBytes: Record<string, number> | null;+ run: TeamRunRow;+ endRecordMissing?: string[];}): Record<string, unknown> {const { status, sessionPath, idle, activity, liveBytes } = opts;- const anyRunning = Object.values(status.models).some((m) => m.state === "RUNNING");- // Keyed on RUNNING, not on liveness. A run this server never spawned can still- // show RUNNING slots from a stale status.json, and that is precisely a reader- // who is about to misjudge an `outputSize` of 0.- const note = teamStatusNote({ anyRunning, live: idle !== null });+ // Keyed on the states, not on liveness. A run this server never spawned can still+ // show working slots from a stale status.json, and that is precisely a reader who+ // is about to misjudge an `outputSize` of 0.+ const anyActive = Object.values(status.models).some(+ (m) => !TERMINAL_STATES.includes(slotStateOf(m) as SlotState)+ );+ const note = teamStatusNote({+ anyActive,+ live: idle !== null,+ endRecordMissing: opts.endRecordMissing,+ });return {...status,- // Bytes of answer produced SO FAR, per still-running slot. `outputSize` cannot- // answer this — see teamSlotLiveBytes.+ // Bytes of answer produced SO FAR, per slot still working. `outputSize` cannot+ // answer this.live_output_bytes_by_slot: liveBytes,idle_seconds_by_slot: idle,- // What each slot is DOING, which is what makes the idle number readable.- // Silence in `tool_executing` is a build; the same silence in `running` is a- // stalled answer.+ // What each slot is DOING, which is what makes the idle number readable. Silence+ // while a tool runs is a build; the same silence in "thinking" is a stalled answer.activity_by_slot: activity,...(note ? { note } : {}),- // The rendered result card, once there is a result to render. This is the- // summary `run` used to return before it stopped waiting; a settled `status`- // is now where it belongs, since that is the call that knows the outcome.- ...(anyRunning ? {} : { summary: formatTeamResult(status, sessionPath) }),+ // The rendered result card, once there is a result to render.+ ...(anyActive ? {} : { summary: formatTeamResult(status, sessionPath) }),+ ...contractMeta(),+ run: opts.run,};}-export function formatTeamResult(- status: import("./team-orchestrator.js").TeamStatus,- sessionPath: string-): string {- const entries = Object.entries(status.models).sort(([a], [b]) => a.localeCompare(b));- // EMPTY belongs with the failures: the process exited 0 but produced no usable- // answer. Filing it under "succeeded" is what forced callers to infer failure- // from outputSize by hand.- const failed = entries.filter(- ([, m]) => m.state === "FAILED" || m.state === "TIMEOUT" || m.state === "EMPTY"+/** One failed slot on the result card: reason, what happened, next step, evidence. */+function failureLines(id: string, m: ModelStatus): string[] {+ const reason = m.error?.reason;+ const out = [` ${id} ${slotStateOf(m)} reason=${reason ?? "unknown"}`];+ // A blocked slot's detail is the question it stopped on.+ if (m.error?.detail)+ out.push(` ${reason === "blocked" ? "question" : "what"}: ${m.error.detail}`);+ out.push(` next: ${(reason && NEXT_STEP[reason]) || "read the evidence log"}`);+ out.push(+ m.error?.errorLogPath+ ? ` evidence: ${m.error.errorLogPath}`+ : " evidence: NONE CAPTURED — orchestrator bug, report via report_error");+ return out;+}++export function formatTeamResult(status: TeamStatus, sessionPath: string): string {+ const entries = Object.entries(status.models).sort(([a], [b]) => a.localeCompare(b));+ // Everything that is not COMPLETED belongs with the failures: EMPTY (the turn settled+ // but its answer is unusable), CANCELLED (the caller stopped it), FAILED and TIMEOUT.+ // Filing EMPTY under "succeeded" is what forced callers to infer failure from+ // outputSize by hand.const succeeded = entries.filter(([, m]) => m.state === "COMPLETED");+ const failed = entries.filter(([, m]) => m.state !== "COMPLETED");const lines: string[] = [];lines.push(`<<<TEAM_RESULT path="${sessionPath}">>>`);@@ -568,30 +637,21 @@ export function formatTeamResult(lines.push("succeeded:");for (const [id, m] of succeeded) {lines.push(` ${id} ${fmtSize(m.outputSize)} response-${id}.md`);+ // R3-M5: an open background shell (or a truncated turn) is worth a line.+ for (const a of m.anomalies ?? []) lines.push(` note: ${a}`);}}if (failed.length > 0) {lines.push("failures:");- for (const [id, m] of failed) {- const reason = m.error?.reason ?? "unknown";- const next = NEXT_STEP[reason] ?? "read the evidence log";- lines.push(` ${id} ${m.state} reason=${reason}`);- if (m.error?.detail) lines.push(` what: ${m.error.detail}`);- lines.push(` next: ${next}`);- if (m.error?.errorLogPath) {- lines.push(` evidence: ${m.error.errorLogPath}`);- } else {- lines.push(" evidence: NONE CAPTURED — orchestrator bug, report via report_error");- }- }+ for (const [id, m] of failed) lines.push(...failureLines(id, m));lines.push("actions:");- lines.push(" full stderr/stdout for one failure → Read the evidence path above");+ lines.push(" final screen and answer for one failure → Read the evidence path above");lines.push(- ` machine-readable status → team(mode="status", path="${sessionPath}")`+ ` machine-readable status → team(mode="status", path="${sessionPath}")`);lines.push(- ` report a provider bug → report_error(session_path="${sessionPath}")`+ ` report a provider bug → report_error(session_path="${sessionPath}")`);}@@ -599,6 +659,115 @@ export function formatTeamResult(return lines.join("\n");}+// ─── team: the mod-contract verbs (§8 A–D) ───────────────────────────────────++type ToolAnswer = { content: Array<{ type: "text"; text: string }>; isError?: boolean };++function contractAnswer(value: unknown): ToolAnswer {+ return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };+}++/** Every §8 verb answers its errors as the `ContractError` JSON with `isError: true`. */+function contractErrorAnswer(e: unknown): ToolAnswer {+ const err =+ e instanceof ContractErrorException+ ? e+ : new ContractErrorException("invalid_args", e instanceof Error ? e.message : String(e));+ return {+ content: [{ type: "text", text: JSON.stringify(err.toContractError()) }],+ isError: true,+ };+}++function contractPath(raw: unknown, mode: string): string {+ if (typeof raw !== "string" || !raw)+ throw new ContractErrorException("invalid_args", `'path' is required for mode '${mode}'`);+ try {+ return validateSessionPath(raw);+ } catch (e) {+ throw new ContractErrorException("invalid_args", e instanceof Error ? e.message : String(e));+ }+}++function optionalString(raw: unknown, name: string): string | undefined {+ if (raw === undefined || raw === null) return undefined;+ if (typeof raw !== "string" || !raw)+ throw new ContractErrorException("invalid_args", `'${name}' must be a non-empty string`);+ return raw;+}++/**+ * `team(mode="status")` (§8 B): the legacy payload of the newest run at `path` plus+ * `contract_version`, `capabilities` and `run`. Given a `run_id` that a newer run at the+ * same path superseded, only `run` and the contract keys: `status.json` there now+ * belongs to the newer run.+ */+export function teamStatusAnswer(path: string, runId?: string): Record<string, unknown> {+ let row: TeamRunRow | null = null;+ if (runId) {+ row = teamRunRow(path, runId);+ if (!row)+ throw new ContractErrorException(+ "unknown_run",+ `no team run with run_id ${runId} at ${path} is retained by this server`+ );+ if (isSupersededRun(runId)) return { ...contractMeta(), run: row };+ } else {+ row = teamRunRow(path);+ }+ let status: TeamStatus;+ try {+ status = getStatus(path);+ } catch {+ if (row) return { ...contractMeta(), run: row };+ throw new ContractErrorException(+ "unknown_run",+ `no team run at ${path}: no status.json there and no run held by this server`+ );+ }+ const live = teamLiveMaps(path, runId);+ return buildTeamStatusPayload({+ status,+ sessionPath: path,+ idle: live?.idle ?? null,+ activity: live?.activity ?? null,+ liveBytes: live?.liveBytes ?? null,+ run: row ?? teamRunRowFromDisk(path, status),+ endRecordMissing: live?.endRecordMissing,+ });+}++/** `list` / `status` / `cancel` / `capture`: memory reads, JSON answers, ContractError errors. */+export async function teamContractVerb(+ mode: "list" | "status" | "cancel" | "capture",+ args: Record<string, unknown>+): Promise<ToolAnswer> {+ try {+ if (mode === "list") return contractAnswer(listTeamRuns());+ const path = contractPath(args.path, mode);+ const runId = optionalString(args.run_id, "run_id");+ const slot = optionalString(args.slot, "slot");+ switch (mode) {+ case "status":+ return contractAnswer(teamStatusAnswer(path, runId));+ case "cancel":+ return contractAnswer(await cancelTeamRun(path, slot, runId));+ case "capture": {+ if (slot === undefined)+ throw new ContractErrorException("invalid_args", "'slot' is required for mode 'capture'");+ 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(+ captureTeamSlot(path, slot, since as number | undefined, args.spans === true, runId)+ );+ }+ }+ } catch (e) {+ return contractErrorAnswer(e);+ }+}+/*** `report_error` sends data OFF this machine, so it gets the full treatment:* credentials AND the personal details that identify the user.@@ -1223,43 +1392,66 @@ function defineTools(tools.push({name: "team",description:- "Run AI models on a task with anonymized outputs and optional blind judging. " +- "Modes: 'run' (START the models and return a slot map immediately — it does NOT " +- "wait), 'status' (per-slot state, plus live answer bytes, seconds of silence and " +- "current activity per slot), " +- "'cancel' (stop one slot or the whole run), 'judge' (blind-vote on existing " +- "outputs), 'run-and-judge' (the blocking pipeline). " +- "NO SLOT IS EVER KILLED ON A TIMER. A team slot is a full Claude Code session and " +- "may work for a long time; a slot inside a build or test suite emits nothing for " +- "minutes and is working, not stuck. Poll 'status', judge the silence against the " +- "task you set, and use 'cancel' if you decide a slot is wedged. " +- "JUDGING A RUNNING SLOT: read live_output_bytes_by_slot, idle_seconds_by_slot and " +- "activity_by_slot. Do NOT use 'outputSize' — it is the size of the final answer, " +- "written only when a slot finishes, so it is 0 for every running slot no matter how " +- "much that slot has produced.",+ "Run AI models on a task with anonymized outputs and optional blind judging. Every " ++ "slot is an interactive Claude Code session in its own headless magmux pane. " ++ "Modes: 'run' (START the models and return once each has taken its prompt — it does " ++ "NOT wait for answers), 'status' (per-slot state; read `run.slots`), 'list' (every " ++ "run this server holds), 'capture' (one slot's screen), 'cancel' (stop one slot or " ++ "the whole run), 'judge' (blind-vote on existing outputs), 'run-and-judge' (the " ++ "blocking pipeline). Poll 'status' (read run.slots) or 'list'. " ++ "NO SLOT IS EVER KILLED ON A TIMER once its prompt is accepted. A team slot is a full " ++ "Claude Code session and may work for a long time; a slot inside a build or test " ++ "suite emits nothing for minutes and is working, not stuck. Judge the silence " ++ "against the task you set, and use 'cancel' if you decide a slot is wedged. A slot " ++ "that stops on a question it cannot answer is FAILED 'blocked' (team has no way to " ++ "answer it). JUDGING A WORKING SLOT: read live_output_bytes_by_slot, " ++ "idle_seconds_by_slot and activity_by_slot (or each row's idle_seconds and " ++ "activity). Do NOT use 'outputSize' — it is the size of the final answer, written " ++ "only when a slot finishes, so it is 0 for every working slot no matter how much " ++ "that slot has produced.",inputSchema: {type: "object",properties: {mode: {type: "string",- enum: ["run", "judge", "run-and-judge", "status", "cancel"],+ enum: ["run", "judge", "run-and-judge", "status", "cancel", "list", "capture"],description:- "Operation mode. 'run' STARTS the models and returns immediately with a " +- "slot map — it does not wait. Poll 'status' for progress (read it from " +- "live_output_bytes_by_slot and activity_by_slot, never from outputSize, " +- "which stays 0 until a slot finishes), then 'judge' once the slots have " +- "finished. 'run-and-judge' is the blocking pipeline and holds the call open " +- "for the whole run. 'cancel' stops one slot or the whole run.",+ "Operation mode. 'run' STARTS the models and returns once every slot has taken " ++ "its prompt (or failed to) — it does not wait for answers. Poll 'status' (read " ++ "`run.slots`) or 'list' for progress, then 'judge' once the slots have " ++ "finished. 'capture' returns one slot's screen. 'run-and-judge' is the blocking " ++ "pipeline and holds the call open for the whole run. 'cancel' stops one slot or " ++ "the whole run.",},slot: {type: "string",description:- "For 'cancel': the anonymised slot id to stop (e.g. '02'), from the slot map " +- "'run' returned. Omit to cancel every slot in the run.",+ "For 'cancel' and 'capture': the anonymised slot id (e.g. '02') from the slot " ++ "map 'run' returned. 'capture' requires it; for 'cancel', omit it to stop every " ++ "slot in the run.",},path: {type: "string",- description: "Session directory path (must be within current working directory)",+ description:+ "Session directory path (must be within current working directory). Required " ++ "by every mode except 'list'.",+ },+ run_id: {+ type: "string",+ description:+ "For 'status', 'cancel' and 'capture': the run_id a 'run' answer returned. It " ++ "addresses THAT run while this server retains it, even after a newer run reused " ++ "the path. Omit it to address the newest run at 'path'.",+ },+ since_seq: {+ type: "number",+ description:+ "For 'capture': the `seq` of the screen you already hold. When it is still " ++ "current the answer is `{unchanged:true}`; any other value returns the full screen.",+ },+ spans: {+ type: "boolean",+ description: "For 'capture': also return the colour/attribute spans of each line.",},models: {type: "array",@@ -1271,8 +1463,8 @@ function defineTools("'opus'/'sonnet'/'haiku'/'claude-*' select a specific one. They run on the " +"user's Claude subscription through the native passthrough (no API key, no " +"translation), and — unlike a Task agent — they are covered by require_pattern, " +- "so a native reviewer that never produced the required shape is reported FAILED " +- "instead of silently succeeding.",+ "so a native reviewer that never produced the required shape is reported " ++ "EMPTY 'shape_mismatch' instead of silently succeeding.",},judges: {type: "array",@@ -1299,18 +1491,17 @@ function defineTools(require_pattern: {type: "string",description:- "Regex the response MUST match, or the slot is reported FAILED (state EMPTY, " +- "reason 'shape_mismatch') instead of succeeded. Strongly recommended whenever " +- "your prompt mandates an output shape — e.g. '```vote' for a voting panel. " +- "Exit code 0 is not a success oracle: it is 0 on API errors and on a child " +- "that simply never followed the format. Answers are no longer LOST to print " +- "mode (every assistant message is captured), so a mismatch now means the model " +- "did not produce the shape, not that the shape was discarded.",+ "Regex (no flags) the slot's answer MUST match, or the slot is reported EMPTY " ++ "with reason 'shape_mismatch' instead of succeeded. The answer is the turn's " ++ "assistant text, read from the transcript; for a prompt delivered as a file it " ++ "starts after the child read that file, so `^` anchors to the answer's start. " ++ "Strongly recommended whenever your prompt mandates an output shape — e.g. " ++ "'```vote' for a voting panel.",},min_output_bytes: {type: "number",description:- "Report a slot FAILED if it produced fewer than this many bytes (default 0 = " ++ "Report a slot EMPTY if its answer is shorter than this many bytes (default 0 = " +"off). A blunter instrument than require_pattern — short answers can be " +"legitimate — so prefer require_pattern when you know the expected shape.",},@@ -1321,21 +1512,23 @@ function defineTools("Each child is a full Claude Code session, so this loads that agent's system " +"prompt and tool allowlist — the same specialisation a Task agent gets, but " +"inside the team run, where require_pattern still applies. Applies to EVERY " +- "model in the run (native and external alike); there is no per-model form.",+ "model in the run (native and external alike); there is no per-model form. An " ++ "unknown agent fails the slot 'agent_rejected', listing the available agents.",},claude_flags: {type: "string",description:"Any other Claude Code flags, space-separated (e.g. '--effort high " +- "--permission-mode plan'). Unrecognised flags pass straight through to the " +- "child Claude Code, so anything Claude Code accepts works here. Prefer the " +- "dedicated 'agent' parameter for the subagent; an --agent given here is " +- "ignored when 'agent' is also set. NOTE: split on whitespace, so a flag " +- 'VALUE containing spaces (e.g. --append-system-prompt "two words") cannot ' +- "be expressed here.",+ "--permission-mode plan'): flags and their values only, never positional text. " ++ "One value per flag (write '--allowedTools Read,Bash'). Flags that would break " ++ "the interactive pane (-p, --output-format, --resume, …) and print-mode-only " ++ "flags (--max-turns, --max-budget-usd, …) are refused. Prefer the dedicated " ++ "'agent' parameter for the subagent; an --agent given here is ignored when " ++ "'agent' is also set. NOTE: split on whitespace, so a flag VALUE containing " ++ 'spaces (e.g. --append-system-prompt "two words") cannot be expressed here.',},},- required: ["mode", "path"],+ required: ["mode"],},group: "agentic",// The tool the whole keepalive exists for: a real run was aborted at exactly@@ -1343,19 +1536,24 @@ function defineTools(// failure happened in a session with channels unregistered, so gating the// keepalive behind the channel group would reproduce the bug exactly.//- // Still needed even though `run` no longer blocks: `run-and-judge` is the- // pipeline mode and holds the call open for the whole run, which is exactly- // the shape that hit the ceiling. `run` returning early does not remove the- // exposure, it just stops the common path from carrying it.+ // Still needed even though `run` no longer blocks on answers: `run-and-judge` is+ // the pipeline mode and holds the call open for the whole run, and `run` itself+ // waits up to boot + admission (≤ 120 s) for every slot to take its prompt.//// The background run keeps calling `ctx.reportProgress` after `run` has// returned. That is safe by contract — see ToolCallContext: a no-op once the// heartbeat is stopped, and it never throws.heartbeat: true,handler: async (args, ctx) => {+ const mode = args.mode as string;+ if (mode === "list" || mode === "status" || mode === "cancel" || mode === "capture") {+ return teamContractVerb(mode, args);+ }try {- const mode = args.mode as string;- const path = args.path as string;+ if (mode !== "run" && mode !== "judge" && mode !== "run-and-judge")+ throw new Error(`Unknown mode: ${mode}`);+ const path = args.path;+ if (typeof path !== "string" || !path) throw new Error(`'path' is required for '${mode}'`);const models = args.models as string[] | undefined;const judges = args.judges as string[] | undefined;// `input_file` is the preferred form: a team prompt is usually a long@@ -1373,11 +1571,9 @@ function defineTools(const input = inputFile !== undefined ? readTeamInputFile(inputFile) : inlineInput;const requirePattern = args.require_pattern as string | undefined;const minOutputBytes = args.min_output_bytes as number | undefined;- const childFlags = buildChildClaudeFlags(args.agent, args.claude_flags);- // Reject an unknown agent BEFORE spawning N children. `team` spawns with- // --stdin so Claude Code would catch it, but centrally is where the two- // spawn sites stay consistent — see agent-availability.ts.- await assertAgentAvailable(args.agent as string | undefined, process.cwd());+ const childFlags = buildChildClaudeFlags(args.agent, args.claude_flags) ?? [];+ // No agent probe here: the interactive child refuses an unknown --agent itself,+ // before any model request, and that slot is FAILED agent_rejected (D11).const resolved = validateSessionPath(path);@@ -1414,16 +1610,31 @@ function defineTools(},};+ /** The prompt the slots will get: `input`, else an input.md already in the dir. */+ const promptText = (): string | undefined => {+ if (input !== undefined) return input;+ const existing = join(resolved, "input.md");+ return existsSync(existing) ? readFileSync(existing, "utf-8") : undefined;+ };+switch (mode) {case "run": {if (!models?.length) throw new Error("'models' is required for 'run' mode");+ // Every refusal BEFORE anything is written: a refused run leaves no+ // session directory, no record and no pane (§4.1).+ await preflightTeamRun({+ path: resolved,+ slots: models.length,+ claudeFlags: childFlags,+ input: promptText(),+ });setupSession(resolved, models, input);// The run's record in the sessions directory, for observers outside// this process (the magus claudish plugin monitor): the run's own// status.json lives wherever the caller pointed `path`, and its only// completion push is a channel frame Claude Code drops without- // `--channels`. Written BEFORE any child exists; a throw here fails+ // `--channels`. Written BEFORE any pane exists; a throw here fails// the call with nothing started.const parentClaudeSessionId = await proveParentForCall({toolUseId: ctx.toolUseId,@@ -1437,15 +1648,14 @@ function defineTools(const settleRecord = (outcome: TeamRunOutcome): void =>sessionManager.finishTeamRun(monitorRecord, outcome);- // Returns once the children EXIST, not once they finish. A team slot- // is a full Claude Code session and can legitimately work for a long- // time; holding the tool call open for that made the run's duration- // the client's problem, and the deadline that existed to bound it- // killed working slots. Poll `mode: "status"` instead.+ // Returns once every slot has LEFT STARTING (D9): its prompt was+ // accepted, or it failed to boot or to take it. Never once the answers+ // exist: a team slot can legitimately work for a long time, and holding+ // the call open for that made the run's duration the client's problem.//// The record's end is passed IN as `onSettled`, so it exists before- // the first child and fires however fast the run settles. If- // `startModels` throws, it has already killed whatever it spawned;+ // the first pane and fires however fast the run settles. If+ // `startModels` throws, it has already reaped whatever it started;// the record ends `failed`, `reason: start-failed`, and the ORIGINAL// error reaches the caller (`finishTeamRun` never throws).let handle: Awaited<ReturnType<typeof startModels>>;@@ -1465,6 +1675,8 @@ function defineTools(});throw err;}+ const run = teamRunRow(resolved, handle.runId);+ const p = handle.sessionPath;return {content: [{@@ -1472,18 +1684,23 @@ function defineTools(text: JSON.stringify({started: true,+ run_id: handle.runId,team_session_id: handle.teamSessionId,- session_path: handle.sessionPath,+ session_path: p,monitor_record: monitorRecord,slots: handle.slots,+ run,next: {- status: `team(mode:"status", path:"${handle.sessionPath}")`,- cancel: `team(mode:"cancel", path:"${handle.sessionPath}", slot:"<id>")`,- judge: `team(mode:"judge", path:"${handle.sessionPath}") once every slot has finished`,+ status: `team(mode:"status", path:"${p}", run_id:"${handle.runId}") — read run.slots`,+ list: `team(mode:"list")`,+ capture: `team(mode:"capture", path:"${p}", slot:"<id>")`,+ cancel: `team(mode:"cancel", path:"${p}", slot:"<id>")`,+ judge: `team(mode:"judge", path:"${p}") once every slot has finished`,},note:- "Nothing terminates a slot on a timer. `status` reports how many " +- "seconds each slot has been silent; a slot inside a long build is " ++ "Every slot has taken its prompt or failed to. Nothing terminates a " ++ "working slot on a timer: `status` reports each slot's state, " ++ "activity and seconds of silence; a slot inside a long build is " +"quiet and working. You decide whether to cancel.",},null,@@ -1493,67 +1710,28 @@ function defineTools(],};}- case "cancel": {- const slot = args.slot as string | undefined;- const teamSessionId = resolved.split("/").filter(Boolean).pop() ?? "team";- const result = await cancelTeamRun(teamSessionId, slot);- if (!result.found) {- return {- content: [- {- type: "text" as const,- text: JSON.stringify({- cancelled: [],- note:- "No live run for that path. It already settled (read `status`), or " +- "it was started by a different process — this server can only stop " +- "children it spawned.",- }),- },- ],- };- }- return {- content: [- {- type: "text" as const,- text: JSON.stringify({ cancelled: result.cancelled }, null, 2),- },- ],- };- }case "judge": {const verdict = await judgeResponses(resolved, { judges, claudeFlags: childFlags });return { content: [{ type: "text" as const, text: JSON.stringify(verdict, null, 2) }] };}case "run-and-judge": {if (!models?.length) throw new Error("'models' is required for 'run-and-judge' mode");+ await preflightTeamRun({+ path: resolved,+ slots: models.length,+ claudeFlags: childFlags,+ input: promptText(),+ });setupSession(resolved, models, input);- await runModels(resolved, runOpts);+ const handle = await startModels(resolved, runOpts);+ await handle.done;+ const run = teamRunRow(resolved, handle.runId);const verdict = await judgeResponses(resolved, { judges, claudeFlags: childFlags });- return { content: [{ type: "text" as const, text: JSON.stringify(verdict, null, 2) }] };- }- case "status": {- const status = getStatus(resolved);- const teamSessionId = resolved.split("/").filter(Boolean).pop() ?? "team";- // All three liveness reads are null once the run has settled or if it- // was never spawned here — the states in `status` are then whatever- // status.json last recorded, and there is no child left to ask.return {content: [{type: "text" as const,- text: JSON.stringify(- buildTeamStatusPayload({- status,- sessionPath: resolved,- idle: teamSlotIdleSeconds(teamSessionId),- activity: teamSlotActivity(teamSessionId),- liveBytes: teamSlotLiveBytes(teamSessionId),- }),- null,- 2- ),+ text: JSON.stringify({ ...verdict, run_id: handle.runId, run }, null, 2),},],};diff --git a/packages/cli/src/pane/test-helpers/fake-interactive-child.ts b/packages/cli/src/pane/test-helpers/fake-interactive-child.tsindex d3ed21b5..13c83447 100644--- a/packages/cli/src/pane/test-helpers/fake-interactive-child.ts+++ b/packages/cli/src/pane/test-helpers/fake-interactive-child.ts@@ -886,8 +886,13 @@ function dumpClaudeMode(): void {async function boot(): Promise<void> {if (asClaude) dumpClaudeMode();+ // `{session}` in the path is replaced by this child's --session-id, so several slots of+ // one run can each leave a probe.if (env.FAKE_PROBE_FILE && scenario === "env_probe")- writeFileSync(env.FAKE_PROBE_FILE, JSON.stringify({ env: { ...env }, cwd, argv }, null, 1));+ writeFileSync(+ env.FAKE_PROBE_FILE.replace("{session}", sessionId),+ JSON.stringify({ env: { ...env }, cwd, argv }, null, 1)+ );if (agent?.startsWith("zzz")) {process.stdout.write(`--agent '${agent}' not found. Available agents: claude, claude-code-guide, Explore, general-purpose, Plan, statusline-setup\r\n`diff --git a/packages/cli/src/team-cancel.test.ts b/packages/cli/src/team-cancel.test.tsindex 72e789cf..d1437875 100644--- a/packages/cli/src/team-cancel.test.ts+++ b/packages/cli/src/team-cancel.test.ts@@ -1,7 +1,11 @@+/**+ * Cancelling a team run on panes (contract C): the transition is synchronous, the reap is+ * asynchronous, a second call returns `changed:false`, and nothing of a cancelled pane+ * survives — no process, socket, record or launcher dir in the test's sockRoot.+ */+import { afterEach, beforeEach, describe, expect, it } from "bun:test";-import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";-import { tmpdir } from "node:os";-import { join } from "node:path";+import { ContractErrorException } from "./pane/index.js";import {type TeamHandle,type TeamStatus,@@ -9,167 +13,183 @@ import {getStatus,setupSession,startModels,- teamSlotIdleSeconds,- teamSlotLiveBytes,+ teamLiveMaps,+ teamRunRow,} from "./team-orchestrator.js";--const delay = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));-const spawnPlanner = async () => ({ pinned: new Map<string, string>() });--let tempRoot: string;-let fakeDir: string;-let fakeClaudish: string;-let originalClaudishBin: string | undefined;+import {+ MAGMUX,+ NO_MAGMUX_MESSAGE,+ type PaneTestEnv,+ finishPaneTest,+ makePaneTestEnv,+ paneRunOptions,+ teamDirOf,+ waitUntil,+} from "./test-helpers/team-pane.js";++if (!MAGMUX) console.warn(NO_MAGMUX_MESSAGE);++const HANG = "@@HANG@@ Wait until the caller cancels this run.";+const T = 30_000;++let t: PaneTestEnv;let handles: TeamHandle[];-function makeSession(prefix: string, models: string[]): string {- const sessionPath = mkdtempSync(join(tempRoot, prefix));- setupSession(sessionPath, models, "Wait until the caller cancels this run.");+function makeSession(name: string, models: string[]): string {+ const sessionPath = teamDirOf(t, name);+ setupSession(sessionPath, models, HANG);return sessionPath;}async function startSlowTeam(sessionPath: string): Promise<TeamHandle> {- const handle = await startModels(sessionPath, {- captureMode: "stream-json",- spawnPlanner,- });+ const handle = await startModels(sessionPath, paneRunOptions(t));handles.push(handle);return handle;}-async function waitForSlotToStop(- sessionPath: string,- slotId: string,- limitMs = 1_500-): Promise<TeamStatus> {- const deadline = Date.now() + limitMs;- let status = getStatus(sessionPath);-- while (status.models[slotId]?.state === "RUNNING" && Date.now() < deadline) {- await delay(10);- status = getStatus(sessionPath);- }-- if (status.models[slotId]?.state === "RUNNING") {- throw new Error(- `slot ${slotId} did not stop within ${limitMs}ms; status=${JSON.stringify(status)}`- );- }- return status;+async function waitForSlotToStop(sessionPath: string, slotId: string): Promise<TeamStatus> {+ await waitUntil(+ () => getStatus(sessionPath).models[slotId]?.state === "CANCELLED",+ `slot ${slotId} CANCELLED in status.json`,+ 3_000+ );+ return getStatus(sessionPath);}beforeEach(() => {- tempRoot = mkdtempSync(join(tmpdir(), "team-cancel-test-"));- fakeDir = mkdtempSync(join(tmpdir(), "fake-claudish-cancel-"));- fakeClaudish = join(fakeDir, "claudish");- originalClaudishBin = process.env.CLAUDISH_BIN;+ t = makePaneTestEnv();handles = [];-- writeFileSync(- fakeClaudish,- `#!/bin/sh-cat > /dev/null-sleep 2-printf '%s\n' '{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"uncancelled child completed"}]},"session_id":"fake-cancel-session"}'-exit 0-`,- "utf-8"- );- chmodSync(fakeClaudish, 0o755);- process.env.CLAUDISH_BIN = fakeClaudish;});afterEach(async () => {for (const handle of handles) {- await cancelTeamRun(handle.teamSessionId);+ await cancelTeamRun(handle.sessionPath, undefined, handle.runId).catch(() => undefined);await handle.done;}-- if (originalClaudishBin === undefined) {- delete process.env.CLAUDISH_BIN;- } else {- process.env.CLAUDISH_BIN = originalClaudishBin;- }- rmSync(tempRoot, { recursive: true, force: true });- rmSync(fakeDir, { recursive: true, force: true });+ const report = await finishPaneTest(t);+ expect(report).toEqual({ processes: [], files: [] });});-describe("team run cancellation", () => {- it("reports live bytes for a zero-output slot and removes them on settle", async () => {- const sessionPath = makeSession("live-bytes-", ["slow-model"]);- const handle = await startSlowTeam(sessionPath);- const slotId = handle.slots["slow-model"];-- const liveBytes = teamSlotLiveBytes(handle.teamSessionId);- expect(liveBytes).not.toBeNull();- expect(liveBytes).toHaveProperty(slotId, 0);- expect(typeof liveBytes?.[slotId]).toBe("number");- expect(Object.keys(liveBytes ?? {})).toEqual(- Object.keys(teamSlotIdleSeconds(handle.teamSessionId) ?? {})- );-- await cancelTeamRun(handle.teamSessionId);- await handle.done;- expect(teamSlotLiveBytes(handle.teamSessionId)).toBeNull();- });-- it("returns a live handle before children finish and removes liveness on settle", async () => {- const sessionPath = makeSession("live-", ["slow-model"]);- const handle = await startSlowTeam(sessionPath);- const slotId = handle.slots["slow-model"];-- expect(slotId).toMatch(/^\d{2,}$/);- expect(getStatus(sessionPath).models[slotId]?.state).toBe("RUNNING");- const idle = teamSlotIdleSeconds(handle.teamSessionId);- expect(idle).not.toBeNull();- expect(typeof idle?.[slotId]).toBe("number");-- const cancelled = await cancelTeamRun(handle.teamSessionId);- expect(cancelled).toEqual({ found: true, cancelled: [slotId] });- await handle.done;- expect(teamSlotIdleSeconds(handle.teamSessionId)).toBeNull();- });+describe.skipIf(!MAGMUX)("team run cancellation", () => {+ it(+ "reports live bytes for a zero-output slot, and none once the run settled",+ async () => {+ const sessionPath = makeSession("live-bytes", ["contract-fake-model"]);+ const handle = await startSlowTeam(sessionPath);+ const slotId = handle.slots["contract-fake-model"] as string;++ const live = teamLiveMaps(sessionPath);+ expect(live).not.toBeNull();+ expect(live?.liveBytes).toHaveProperty(slotId, 0);+ expect(Object.keys(live?.liveBytes ?? {})).toEqual(Object.keys(live?.idle ?? {}));+ expect(live?.activity[slotId]).toBe("thinking");++ await cancelTeamRun(sessionPath);+ await handle.done;+ expect(teamLiveMaps(sessionPath)).toEqual({+ idle: {},+ activity: {},+ liveBytes: {},+ endRecordMissing: [],+ });+ },+ T+ );- it("cancels one slot while leaving the other slot running", async () => {- const sessionPath = makeSession("one-slot-", ["slow-a", "slow-b"]);- const handle = await startSlowTeam(sessionPath);- const cancelledSlot = handle.slots["slow-a"];- const survivingSlot = handle.slots["slow-b"];+ it(+ "returns once the prompt is accepted; cancel is synchronous and idempotent",+ async () => {+ const sessionPath = makeSession("live", ["contract-fake-model"]);+ const handle = await startSlowTeam(sessionPath);+ const slotId = handle.slots["contract-fake-model"] as string;++ expect(slotId).toMatch(/^\d{2,}$/);+ expect(getStatus(sessionPath).models[slotId]?.state).toBe("RUNNING");+ expect(teamRunRow(sessionPath)?.slots[0]?.state).toBe("RUNNING");++ const cancelled = await cancelTeamRun(sessionPath);+ expect(cancelled).toEqual({+ run_id: handle.runId,+ path: sessionPath,+ results: [{ slot: slotId, state: "CANCELLED", changed: true }],+ });+ // The state is CANCELLED when cancel returns, before the reap finished.+ expect(teamRunRow(sessionPath)?.slots[0]?.state).toBe("CANCELLED");+ const again = await cancelTeamRun(sessionPath, undefined, handle.runId);+ expect(again.results).toEqual([{ slot: slotId, state: "CANCELLED", changed: false }]);+ await handle.done;+ },+ T+ );- const result = await cancelTeamRun(handle.teamSessionId, cancelledSlot);- expect(result).toEqual({ found: true, cancelled: [cancelledSlot] });+ it(+ "cancels one slot while leaving the other slot running",+ async () => {+ const sessionPath = makeSession("one-slot", ["contract-fake-a", "contract-fake-b"]);+ const handle = await startSlowTeam(sessionPath);+ const cancelledSlot = handle.slots["contract-fake-a"] as string;+ const survivingSlot = handle.slots["contract-fake-b"] as string;++ const result = await cancelTeamRun(sessionPath, cancelledSlot);+ expect(result.results).toEqual([{ slot: cancelledSlot, state: "CANCELLED", changed: true }]);++ const status = await waitForSlotToStop(sessionPath, cancelledSlot);+ expect(status.models[cancelledSlot]?.error?.reason).toBe("cancelled");+ expect(status.models[survivingSlot]?.state).toBe("RUNNING");+ expect(typeof teamLiveMaps(sessionPath)?.idle[survivingSlot]).toBe("number");+ expect(teamRunRow(sessionPath)?.state).toBe("ACTIVE");++ await cancelTeamRun(sessionPath, survivingSlot);+ await handle.done;+ },+ T+ );- const status = await waitForSlotToStop(sessionPath, cancelledSlot);- expect(status.models[cancelledSlot]?.state).not.toBe("RUNNING");- expect(status.models[cancelledSlot]?.error?.reason).toBe("cancelled");- expect(status.models[survivingSlot]?.state).toBe("RUNNING");- expect(typeof teamSlotIdleSeconds(handle.teamSessionId)?.[survivingSlot]).toBe("number");+ it(+ "cancels every slot when no slot id is supplied; the run settles all-failed",+ async () => {+ const sessionPath = makeSession("all-slots", ["contract-fake-a", "contract-fake-b"]);+ const handle = await startSlowTeam(sessionPath);+ const expectedSlots = Object.values(handle.slots).sort();++ const result = await cancelTeamRun(sessionPath);+ expect(result.results.map((r) => r.slot)).toEqual(expectedSlots);+ expect(result.results.every((r) => r.changed && r.state === "CANCELLED")).toBe(true);++ const settled = await handle.done;+ for (const slotId of expectedSlots) {+ expect(settled.models[slotId]?.state).toBe("CANCELLED");+ expect(settled.models[slotId]?.error?.reason).toBe("cancelled");+ }+ const row = teamRunRow(sessionPath);+ expect(row?.state).toBe("SETTLED");+ expect(row?.outcome).toBe("all-failed");+ expect(row?.slots.every((s) => s.reason === "cancelled" && s.idle_seconds === null)).toBe(+ true+ );+ },+ T+ );- await cancelTeamRun(handle.teamSessionId, survivingSlot);- await handle.done;- });+ it("answers an unknown run and an unknown slot as contract errors", async () => {+ const unknown = await cancelTeamRun(teamDirOf(t, "never-started")).catch((e: unknown) => e);+ expect(unknown).toBeInstanceOf(ContractErrorException);+ expect((unknown as ContractErrorException).code).toBe("unknown_run");- it("cancels every slot when no slot id is supplied", async () => {- const sessionPath = makeSession("all-slots-", ["slow-a", "slow-b"]);- const handle = await startSlowTeam(sessionPath);- const expectedSlots = Object.values(handle.slots).sort();-- const result = await cancelTeamRun(handle.teamSessionId);- expect(result.found).toBe(true);- expect(result.cancelled.sort()).toEqual(expectedSlots);-- const settled = await handle.done;- expect(Object.values(settled.models).every((model) => model.state !== "RUNNING")).toBe(true);- for (const slotId of expectedSlots) {- expect(settled.models[slotId]?.error?.reason).toBe("cancelled");- }- expect(teamSlotIdleSeconds(handle.teamSessionId)).toBeNull();+ const byId = await cancelTeamRun(undefined, undefined, "nope-0-000000").catch((e) => e);+ expect((byId as ContractErrorException).code).toBe("unknown_run");});- it("reports an unknown run without claiming any cancellation", async () => {- await expect(cancelTeamRun("unknown-team-session")).resolves.toEqual({- found: false,- cancelled: [],- });- });+ it(+ "answers an unknown slot of a known run as unknown_slot",+ async () => {+ const sessionPath = makeSession("bad-slot", ["contract-fake-model"]);+ const handle = await startSlowTeam(sessionPath);+ const err = await cancelTeamRun(sessionPath, "99").catch((e: unknown) => e);+ expect((err as ContractErrorException).code).toBe("unknown_slot");+ await cancelTeamRun(sessionPath, undefined, handle.runId);+ await handle.done;+ },+ T+ );});diff --git a/packages/cli/src/team-cli.ts b/packages/cli/src/team-cli.tsindex 8e9e4b1b..74303447 100644--- a/packages/cli/src/team-cli.ts+++ b/packages/cli/src/team-cli.ts@@ -1,14 +1,42 @@import { readFileSync } from "node:fs";import { join } from "node:path";+import { installPaneShutdownHooks } from "./pane/index.js";import {+ type TeamRunOptions,type TeamStatus,getStatus,judgeResponses,+ preflightTeamRun,runModels,setupSession,validateSessionPath,} from "./team-orchestrator.js";+/**+ * `claudish team run|run-and-judge` (json mode) runs every slot as an interactive pane,+ * like the MCP `team` tool (they share `runModels`). The refusals come first, before+ * the session directory is written: a bad flag exits 2, a missing magmux or a full pane+ * limit exits 1. Ctrl-C (and SIGTERM / SIGHUP) reaps every pane in ≤ 3 s, then exits+ * 128 + the signal number — 130 for Ctrl-C.+ */+async function runPaneTeam(+ sessionPath: string,+ models: string[],+ input: string | undefined,+ opts: TeamRunOptions+): Promise<TeamStatus> {+ installPaneShutdownHooks({ exitAfter: true });+ try {+ await preflightTeamRun({ path: sessionPath, slots: models.length, input });+ } catch (err) {+ const msg = err instanceof Error ? err.message : String(err);+ console.error(`Error: ${msg}`);+ process.exit(msg.startsWith("invalid_args") ? 2 : 1);+ }+ setupSession(sessionPath, models, input);+ return runModels(sessionPath, opts);+}+// ─── Arg Parsing Helpers ─────────────────────────────────────────────────────function getFlag(args: string[], flag: string): string | undefined {@@ -57,6 +85,8 @@ Options (run / run-and-judge):--input <text> Task prompt (or create input.md in --path beforehand)--timeout <secs> Grid modes only: magmux's own per-pane timeout (default: 300).json mode has no deadline — nothing kills a working model.+ json mode runs each model as an interactive pane in a headless+ magmux (>= 0.14.0; darwin and linux).--grid Show all models in a magmux grid with live output + status barOptions (judge / run-and-judge):@@ -143,8 +173,7 @@ export async function teamCommand(args: string[]): Promise<void> {process.exit(1);}if (effectiveMode === "json") {- setupSession(sessionPath, models, input);- const runStatus = await runModels(sessionPath, {+ const runStatus = await runPaneTeam(sessionPath, models, input, {onStatusChange: (id, s) => {process.stderr.write(`[team] ${id}: ${s.state}\n`);},@@ -172,8 +201,7 @@ export async function teamCommand(args: string[]): Promise<void> {console.error("Error: --models is required");process.exit(1);}- setupSession(sessionPath, models, input);- const status = await runModels(sessionPath, {+ const status = await runPaneTeam(sessionPath, models, input, {onStatusChange: (id, s) => {process.stderr.write(`[team] ${id}: ${s.state}\n`);},diff --git a/packages/cli/src/team-grid.ts b/packages/cli/src/team-grid.tsindex 71e78100..27e0248f 100644--- a/packages/cli/src/team-grid.ts+++ b/packages/cli/src/team-grid.ts@@ -280,6 +280,10 @@ function buildTeamStatus(startedAt,completedAt: null,outputSize: 0,+ model: manifest.models[anonId]?.model,+ spawnModel: null,+ provider: null,+ pane: null,};continue;}@@ -303,6 +307,10 @@ function buildTeamStatus(startedAt: result.startedAt ?? startedAt,completedAt: result.completedAt ?? new Date().toISOString(),outputSize: result.response?.length ?? 0,+ model: manifest.models[anonId]?.model,+ spawnModel: null,+ provider: null,+ pane: null,};}diff --git a/packages/cli/src/team-heartbeat-survival.test.ts b/packages/cli/src/team-heartbeat-survival.test.tsindex 832de263..c05619e3 100644--- a/packages/cli/src/team-heartbeat-survival.test.ts+++ b/packages/cli/src/team-heartbeat-survival.test.ts@@ -1,88 +1,97 @@-import { describe, expect, it } from "bun:test";-import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";-import { tmpdir } from "node:os";+/**+ * NO SLOT IS EVER KILLED ON A TIMER once its prompt is accepted (D10,+ * team-lifecycle.md). A slot inside a long silent tool call, and a slot whose Stop hook+ * runs for a long time after its answer, both settle on Claude Code's own end-of-turn+ * record with their answer intact — and report what they are doing meanwhile.+ */++import { afterEach, beforeEach, describe, expect, it } from "bun:test";+import { readFileSync } from "node:fs";import { join } from "node:path";-import { runModels, setupSession } from "./team-orchestrator.js";+import { runModels, setupSession, startModels, teamLiveMaps } from "./team-orchestrator.js";+import {+ MAGMUX,+ NO_MAGMUX_MESSAGE,+ type PaneTestEnv,+ finishPaneTest,+ makePaneTestEnv,+ paneRunOptions,+ teamDirOf,+ waitUntil,+} from "./test-helpers/team-pane.js";++if (!MAGMUX) console.warn(NO_MAGMUX_MESSAGE);-const ANSWER = "The long-running tool call finished and the answer survived intact.";+let t: PaneTestEnv;-describe("team slot heartbeat survival", () => {- it("keeps a working slot alive through a scaled-down silent tool-call interval", async () => {- const sessionPath = mkdtempSync(join(tmpdir(), "team-heartbeat-survival-"));- const fakeDir = mkdtempSync(join(tmpdir(), "fake-claudish-heartbeat-"));- const fakeClaudish = join(fakeDir, "claudish");- const originalClaudishBin = process.env.CLAUDISH_BIN;+beforeEach(() => {+ t = makePaneTestEnv();+});++afterEach(async () => {+ const report = await finishPaneTest(t);+ expect(report).toEqual({ processes: [], files: [] });+});- const heartbeatOne = JSON.stringify({- type: "tool_progress",- tool_use_id: "toolu_fake_long_call",- tool_name: "Bash",- elapsed_time_seconds: 0.025,- heartbeat: true,- session_id: "fake-heartbeat-session",- });- const heartbeatTwo = JSON.stringify({- type: "tool_progress",- tool_use_id: "toolu_fake_long_call",- tool_name: "Bash",- elapsed_time_seconds: 0.05,- heartbeat: true,- session_id: "fake-heartbeat-session",- });- const assistantMessage = JSON.stringify({- type: "assistant",- message: {- role: "assistant",- content: [{ type: "text", text: ANSWER }],- },- session_id: "fake-heartbeat-session",- });+describe.skipIf(!MAGMUX)("team slot heartbeat survival", () => {+ it("keeps a slot alive through a silent tool call and reports activity Bash", async () => {+ const sessionPath = teamDirOf(t);+ setupSession(sessionPath, ["fake-tool_slow"], "Run the long tool call.");- writeFileSync(- fakeClaudish,- `#!/bin/sh-cat > /dev/null-printf '%s\n' '${heartbeatOne}'-sleep 0.025-printf '%s\n' '${heartbeatTwo}'-# Scaled-down analogue of the old 90-second apparent-silence window.-sleep 0.250-printf '%s\n' '${assistantMessage}'-exit 0-`,- "utf-8"+ const startedAt = Date.now();+ const handle = await startModels(+ sessionPath,+ paneRunOptions(t, {}, { FAKE_GAP_MS_TOOL: "3000" }));- chmodSync(fakeClaudish, 0o755);+ const slotId = handle.slots["fake-tool_slow"] as string;+ const seen = new Set<string>();+ let maxIdle = 0;+ const watch = setInterval(() => {+ const live = teamLiveMaps(sessionPath);+ if (live?.activity[slotId]) seen.add(live.activity[slotId] as string);+ maxIdle = Math.max(maxIdle, live?.idle[slotId] ?? 0);+ }, 100);+ const status = await handle.done;+ clearInterval(watch);+ const elapsedMs = Date.now() - startedAt;+ const model = status.models[slotId];+ const response = readFileSync(join(sessionPath, `response-${slotId}.md`), "utf-8");- try {- process.env.CLAUDISH_BIN = fakeClaudish;- setupSession(sessionPath, ["heartbeat-model"], "Run the long tool call.");+ expect(elapsedMs).toBeGreaterThanOrEqual(3000);+ expect(seen.has("Bash")).toBe(true);+ expect(maxIdle).toBeGreaterThanOrEqual(1);+ expect(model?.state).toBe("COMPLETED");+ expect(model?.error).toBeUndefined();+ expect(response).toStartWith("ANSWER fake-tool_slow ");+ expect(response.split("ANSWER")).toHaveLength(2);+ }, 30_000);- const startedAt = Date.now();- const status = await runModels(sessionPath, {- captureMode: "stream-json",- minOutputBytes: 0,- spawnPlanner: async () => ({ pinned: new Map<string, string>() }),- });- const elapsedMs = Date.now() - startedAt;- const [slotId, model] = Object.entries(status.models)[0];- const response = readFileSync(join(sessionPath, `response-${slotId}.md`), "utf-8");+ it("waits out a slow Stop hook after the answer, reading finishing meanwhile", async () => {+ const sessionPath = teamDirOf(t);+ setupSession(sessionPath, ["fake-slow_stop_hook"], "Answer, then let the hook run.");++ const handle = await startModels(+ sessionPath,+ paneRunOptions(t, {}, { FAKE_GAP_MS_HOOK: "3000" })+ );+ const slotId = handle.slots["fake-slow_stop_hook"] as string;+ await waitUntil(+ () => teamLiveMaps(sessionPath)?.activity[slotId] === "finishing",+ "activity finishing",+ 5_000+ );+ const status = await handle.done;++ expect(status.models[slotId]?.state).toBe("COMPLETED");+ expect(readFileSync(join(sessionPath, `response-${slotId}.md`), "utf-8")).toStartWith(+ "ANSWER fake-slow_stop_hook "+ );+ }, 30_000);- expect(elapsedMs).toBeGreaterThanOrEqual(200);- expect(model.state).toBe("COMPLETED");- expect(model.state).not.toBe("TIMEOUT");- expect(model.exitCode).toBe(0);- expect(model.error).toBeUndefined();- expect(response).toContain(ANSWER);- expect(response.split(ANSWER)).toHaveLength(2);- } finally {- if (originalClaudishBin === undefined) {- delete process.env.CLAUDISH_BIN;- } else {- process.env.CLAUDISH_BIN = originalClaudishBin;- }- rmSync(sessionPath, { recursive: true, force: true });- rmSync(fakeDir, { recursive: true, force: true });- }- });+ it("runModels resolves with the settled status of a quick slot", async () => {+ const sessionPath = teamDirOf(t);+ setupSession(sessionPath, ["fake-answer"], "Reply with exactly PEAR");+ const status = await runModels(sessionPath, paneRunOptions(t));+ expect(Object.values(status.models).map((m) => m.state)).toEqual(["COMPLETED"]);+ }, 30_000);});diff --git a/packages/cli/src/team-liveness-exited-slot.test.ts b/packages/cli/src/team-liveness-exited-slot.test.tsindex 1ef6a95c..ac3707b0 100644--- a/packages/cli/src/team-liveness-exited-slot.test.ts+++ b/packages/cli/src/team-liveness-exited-slot.test.ts@@ -1,171 +1,94 @@+/**+ * A terminal slot carries no liveness: its row has `idle_seconds:null` and+ * `activity:null`, and it is absent from the `*_by_slot` maps, while a sibling still+ * works. Never `waiting_for_input`: a team slot cannot wait for input.+ */++// REGRESSION: team status reported exited slots as `waiting_for_input` with a growing idle clock — Fixed in /dev:fix session dev-fix-20260912-213141-f1fb0c1c+import { afterEach, beforeEach, describe, expect, it } from "bun:test";-import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";-import { tmpdir } from "node:os";-import { join } from "node:path";import {type TeamHandle,- type TeamStatus,cancelTeamRun,getStatus,setupSession,startModels,- teamSlotActivity,- teamSlotIdleSeconds,- teamSlotLiveBytes,+ teamLiveMaps,+ teamRunRow,} from "./team-orchestrator.js";--// REGRESSION: team status reported exited slots as `waiting_for_input` with a growing idle clock — Fixed in /dev:fix session dev-fix-20260912-213141-f1fb0c1c--const delay = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));-const spawnPlanner = async () => ({ pinned: new Map<string, string>() });--let tempRoot: string;-let fakeDir: string;-let fakeClaudish: string;-let slowReleasePath: string;-let originalClaudishBin: string | undefined;+import {+ MAGMUX,+ NO_MAGMUX_MESSAGE,+ type PaneTestEnv,+ finishPaneTest,+ makePaneTestEnv,+ paneRunOptions,+ teamDirOf,+ waitUntil,+} from "./test-helpers/team-pane.js";++if (!MAGMUX) console.warn(NO_MAGMUX_MESSAGE);++let t: PaneTestEnv;let handles: TeamHandle[];-async function waitForSlotToStop(- sessionPath: string,- slotId: string,- limitMs = 3_000-): Promise<TeamStatus> {- const deadline = Date.now() + limitMs;- let status = getStatus(sessionPath);-- while (status.models[slotId]?.state === "RUNNING" && Date.now() < deadline) {- await delay(10);- status = getStatus(sessionPath);- }-- if (status.models[slotId]?.state === "RUNNING") {- throw new Error(- `slot ${slotId} did not stop within ${limitMs}ms; status=${JSON.stringify(status)}`- );- }- return status;-}-beforeEach(() => {- tempRoot = mkdtempSync(join(tmpdir(), "team-liveness-exited-slot-test-"));- fakeDir = mkdtempSync(join(tmpdir(), "fake-claudish-liveness-"));- fakeClaudish = join(fakeDir, "claudish");- slowReleasePath = join(tempRoot, "release-slow");- originalClaudishBin = process.env.CLAUDISH_BIN;+ t = makePaneTestEnv();handles = [];-- const fixturePath = join(- import.meta.dir,- "test-fixtures/stream-json/haiku-post-answer-turn.jsonl"- );- writeFileSync(- fakeClaudish,- `#!/bin/sh-model=""-while [ "$#" -gt 0 ]; do- case "$1" in- --model)- model="$2"- shift 2- ;;- --model=*)- model="\${1#--model=}"- shift- ;;- *)- shift- ;;- esac-done-cat > /dev/null-case "$model" in- fast-model)- cat "${fixturePath}"- ;;- slow-model)- attempts=0- while [ ! -f "${slowReleasePath}" ] && [ "$attempts" -lt 400 ]; do- sleep 0.05- attempts=$((attempts + 1))- done- cat "${fixturePath}"- ;;- *)- printf 'unexpected model: %s\n' "$model" >&2- exit 2- ;;-esac-exit 0-`,- "utf-8"- );- chmodSync(fakeClaudish, 0o755);- process.env.CLAUDISH_BIN = fakeClaudish;});afterEach(async () => {- writeFileSync(slowReleasePath, "", "utf-8");- for (const handle of handles) {- await cancelTeamRun(handle.teamSessionId);- await handle.done;+ for (const h of handles) {+ await cancelTeamRun(h.sessionPath, undefined, h.runId).catch(() => undefined);+ await h.done;}-- if (originalClaudishBin === undefined) {- delete process.env.CLAUDISH_BIN;- } else {- process.env.CLAUDISH_BIN = originalClaudishBin;- }- rmSync(tempRoot, { recursive: true, force: true });- rmSync(fakeDir, { recursive: true, force: true });+ const report = await finishPaneTest(t);+ expect(report).toEqual({ processes: [], files: [] });});-describe("team slot liveness", () => {- it("omits an exited slot while another slot is still running", async () => {- const sessionPath = mkdtempSync(join(tempRoot, "exited-slot-"));- setupSession(sessionPath, ["fast-model", "slow-model"], "Keep the slow slot alive.");- const handle = await startModels(sessionPath, {- captureMode: "stream-json",- spawnPlanner,- });+describe.skipIf(!MAGMUX)("team slot liveness", () => {+ it("omits a terminal slot's liveness while another slot is still running", async () => {+ const sessionPath = teamDirOf(t);+ // fake-answer answers at once; the marker-mode slot hangs on @@HANG@@.+ setupSession(+ sessionPath,+ ["fake-answer", "contract-fake-model"],+ "@@HANG@@ keep the slow slot alive"+ );+ const handle = await startModels(sessionPath, paneRunOptions(t));handles.push(handle);- const fastSlot = handle.slots["fast-model"];- const slowSlot = handle.slots["slow-model"];- const status = await waitForSlotToStop(sessionPath, fastSlot);- if (status.models[slowSlot]?.state !== "RUNNING") {- throw new Error(- `slow slot was not RUNNING when fast slot exited; status=${JSON.stringify(status)}`- );- }+ const fastSlot = handle.slots["fake-answer"] as string;+ const slowSlot = handle.slots["contract-fake-model"] as string;+ await waitUntil(+ () => getStatus(sessionPath).models[fastSlot]?.state === "COMPLETED",+ "the fast slot to complete"+ );+ expect(getStatus(sessionPath).models[slowSlot]?.state).toBe("RUNNING");- await delay(1_100);- const laterStatus = getStatus(sessionPath);- if (laterStatus.models[slowSlot]?.state !== "RUNNING") {- throw new Error(- `slow slot was not RUNNING after idle-clock window; status=${JSON.stringify(laterStatus)}`- );- }+ await Bun.sleep(1_100);+ expect(getStatus(sessionPath).models[slowSlot]?.state).toBe("RUNNING");- const activity = teamSlotActivity(handle.teamSessionId);- const idleSeconds = teamSlotIdleSeconds(handle.teamSessionId);- const liveBytes = teamSlotLiveBytes(handle.teamSessionId);- if (activity === null || idleSeconds === null || liveBytes === null) {- throw new Error(- "live slot telemetry unexpectedly disappeared while the slow slot was RUNNING"- );- }+ const live = teamLiveMaps(sessionPath);+ if (live === null) throw new Error("live slot telemetry disappeared while a slot works");+ const { activity, idle, liveBytes } = live;expect(activity).not.toHaveProperty(fastSlot);- expect(idleSeconds).not.toHaveProperty(fastSlot);+ expect(idle).not.toHaveProperty(fastSlot);expect(liveBytes).not.toHaveProperty(fastSlot);expect(activity).toHaveProperty(slowSlot);- expect(idleSeconds).toHaveProperty(slowSlot);+ expect(idle).toHaveProperty(slowSlot);expect(liveBytes).toHaveProperty(slowSlot);- expect(Object.keys(idleSeconds)).toEqual(Object.keys(activity));+ expect(Object.keys(idle)).toEqual(Object.keys(activity));expect(Object.keys(liveBytes)).toEqual(Object.keys(activity));expect(Object.values(activity)).not.toContain("waiting_for_input");- writeFileSync(slowReleasePath, "", "utf-8");- });+ const rows = teamRunRow(sessionPath)?.slots ?? [];+ const fast = rows.find((r) => r.slot === fastSlot);+ const slow = rows.find((r) => r.slot === slowSlot);+ expect(fast).toMatchObject({ state: "COMPLETED", idle_seconds: null, activity: null });+ expect(slow?.state).toBe("RUNNING");+ expect(slow?.idle_seconds).toBeGreaterThanOrEqual(1);+ expect(slow?.activity).toBe("thinking");+ }, 30_000);});diff --git a/packages/cli/src/team-mcp-shape-contract.e2e.test.ts b/packages/cli/src/team-mcp-shape-contract.e2e.test.tsindex e94dad4d..77d4fff1 100644--- a/packages/cli/src/team-mcp-shape-contract.e2e.test.ts+++ b/packages/cli/src/team-mcp-shape-contract.e2e.test.ts@@ -9,11 +9,11 @@* precisely the quiet failure this feature exists to remove. This test closes* that gap by driving a real `claudish --mcp` server over real stdio JSON-RPC.*- * The measured failure is subtle: `claude -p` prints only the final assistant- * message. If a child answers and then takes one more turn when a background- * task completes, its real answer is replaced by a short epilogue. The process- * still exits 0 with plausible prose and no API error, so only the caller's- * required output shape distinguishes that dropout from success.+ * Every slot is an interactive pane (the fake interactive child, via CLAUDISH_BIN, in+ * a real headless magmux). The answer `require_pattern` is matched against is the+ * turn's assistant text read from the transcript. A model that answers without the+ * shape is EMPTY `shape_mismatch`; the same model with no pattern is COMPLETED; a+ * pattern contained in the answer passes.*/import { describe, expect, it } from "bun:test";@@ -21,11 +21,18 @@ import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { dirname, join, resolve } from "node:path";import { fileURLToPath } from "node:url";+import {+ MAGMUX,+ NO_MAGMUX_MESSAGE,+ makePaneTestEnv,+ waitNoOrphans,+} from "./pane/test-helpers/hermetic-env.js";++if (!MAGMUX) console.warn(NO_MAGMUX_MESSAGE);const SRC_DIR = dirname(fileURLToPath(import.meta.url));const REPO_ROOT = resolve(SRC_DIR, "../../..");const SERVER_ENTRY = join(SRC_DIR, "index.ts");-const FAKE_CHILD = join(SRC_DIR, "channel", "test-helpers", "fake-dropout-child.ts");const REQUEST_TIMEOUT_MS = 30_000;interface JsonRpcResponse {@@ -110,30 +117,34 @@ function parseToolJson<T>(result: ToolCallResult, context: string): T {}}-describe("MCP team shape contract", () => {+describe.skipIf(!MAGMUX)("MCP team shape contract", () => {it("exposes and enforces require_pattern without misclassifying the healthy child",async () => {const tempRoot = mkdtempSync(join(REPO_ROOT, ".tmp-mcp-shape-"));+ const paneEnv = makePaneTestEnv();const requiredShapeSession = join(tempRoot, "required-shape");const controlSession = join(tempRoot, "control");+ const containedSession = join(tempRoot, "contained");const configPath = join(tempRoot, "config.json");let server: ChildProcessWithoutNullStreams | undefined;let serverClosed: Promise<void> | undefined;try {- mkdirSync(requiredShapeSession);- mkdirSync(controlSession);- writeFileSync(join(requiredShapeSession, "input.md"), "Review the implementation.\n");- writeFileSync(join(controlSession, "input.md"), "Review the implementation.\n");+ for (const dir of [requiredShapeSession, controlSession, containedSession]) {+ mkdirSync(dir);+ // Two lines: delivered as a task file, so the answer starts after the Read.+ writeFileSync(join(dir, "input.md"), "Review the implementation.\n");+ }writeFileSync(configPath, "{}\n");server = spawn(process.execPath, ["run", SERVER_ENTRY, "--mcp"], {cwd: REPO_ROOT,stdio: ["pipe", "pipe", "pipe"],env: {- ...process.env,- CLAUDISH_BIN: FAKE_CHILD,+ // Hermetic: HOME, CLAUDE_CONFIG_DIR, the pane root and CLAUDISH_BIN (the fake)+ // come from makePaneTestEnv; nothing is inherited from this shell.+ ...paneEnv.env,CLAUDISH_CONFIG: configPath,CLAUDISH_DISABLE_OP: "1",CLAUDISH_MCP_TOOLS: "all",@@ -286,7 +297,7 @@ describe("MCP team shape contract", () => {if (!models || typeof models !== "object") {throw new Error(`${label} status has no models object`);}- if (Object.values(models).every((model) => model.state !== "RUNNING")) {+ if ((lastStatus as { run?: { state?: string } }).run?.state === "SETTLED") {return lastStatus;}@@ -300,55 +311,63 @@ describe("MCP team shape contract", () => {);};- const mismatchResult = (await request("tools/call", {- name: "team",- arguments: {- mode: "run",- path: requiredShapeSession,- models: ["fake-dropout"],- require_pattern: "```vote",- },- })) as ToolCallResult;- expect(mismatchResult.isError).not.toBe(true);- const mismatchStart = parseToolJson<TeamStartPayload>(mismatchResult, "shape-required run");- expect(mismatchStart.started).toBe(true);- expect(mismatchStart.team_session_id).toBe("required-shape");- expect(mismatchStart.session_path).toBe(requiredShapeSession);- expect(mismatchStart.slots).toHaveProperty("fake-dropout");- const mismatchSlot = mismatchStart.slots?.["fake-dropout"];- expect(typeof mismatchSlot).toBe("string");-- const mismatchStatus = await pollSettledStatus(requiredShapeSession, "shape-required run");- const mismatchedModel = mismatchStatus.models?.[String(mismatchSlot)];- expect(mismatchedModel).toBeDefined();- expect(mismatchedModel?.state).toBe("EMPTY");- expect(mismatchedModel?.error?.reason).toBe("shape_mismatch");-- // This control is load-bearing: the same exit-0 child must succeed when- // no shape is required, proving the first failure was not a broken fake.- const controlResult = (await request("tools/call", {- name: "team",- arguments: {- mode: "run",- path: controlSession,- models: ["fake-dropout"],- },- })) as ToolCallResult;- expect(controlResult.isError).not.toBe(true);- const controlStart = parseToolJson<TeamStartPayload>(controlResult, "control run");- expect(controlStart.started).toBe(true);- expect(controlStart.slots).toHaveProperty("fake-dropout");- const controlSlot = controlStart.slots?.["fake-dropout"];- expect(typeof controlSlot).toBe("string");-- const controlStatus = await pollSettledStatus(controlSession, "control run");- const controlModel = controlStatus.models?.[String(controlSlot)];- expect(controlModel).toBeDefined();- expect(controlModel?.state).toBe("COMPLETED");- expect(controlModel?.error).toBeUndefined();+ const runAndSettle = async (+ sessionPath: string,+ model: string,+ label: string,+ requirePattern?: string+ ) => {+ const result = (await request("tools/call", {+ name: "team",+ arguments: {+ mode: "run",+ path: sessionPath,+ models: [model],+ ...(requirePattern === undefined ? {} : { require_pattern: requirePattern }),+ },+ })) as ToolCallResult;+ expect(result.isError).not.toBe(true);+ const start = parseToolJson<TeamStartPayload>(result, label);+ expect(start.started).toBe(true);+ expect(start.session_path).toBe(sessionPath);+ expect(start.slots).toHaveProperty(model);+ const slot = start.slots?.[model];+ expect(typeof slot).toBe("string");+ const status = await pollSettledStatus(sessionPath, label);+ return status.models?.[String(slot)];+ };++ // Negative control on the transcript answer: the fake answers prose with no vote.+ const mismatched = await runAndSettle(+ requiredShapeSession,+ "fake-no_shape",+ "shape-required run",+ "```vote"+ );+ expect(mismatched).toBeDefined();+ expect(mismatched?.state).toBe("EMPTY");+ expect(mismatched?.error?.reason).toBe("shape_mismatch");++ // This control is load-bearing: the same child must succeed when no shape is+ // required, proving the first failure was not a broken fake.+ const control = await runAndSettle(controlSession, "fake-no_shape", "control run");+ expect(control?.state).toBe("COMPLETED");+ expect(control?.error).toBeUndefined();++ // A pattern contained in the answer passes.+ const contained = await runAndSettle(+ containedSession,+ "fake-answer",+ "contained-pattern run",+ "ANSWER fake-answer [0-9a-f]{8}"+ );+ expect(contained?.state).toBe("COMPLETED");} finally {if (server && serverClosed) await terminateServer(server, serverClosed);rmSync(tempRoot, { recursive: true, force: true });+ const report = await waitNoOrphans({ sockRoot: paneEnv.sockRoot });+ paneEnv.cleanup();+ expect(report).toEqual({ processes: [], files: [] });}},{ timeout: 120_000 }diff --git a/packages/cli/src/team-multibyte-answer.test.ts b/packages/cli/src/team-multibyte-answer.test.tsindex b40cbb84..2a81d10f 100644--- a/packages/cli/src/team-multibyte-answer.test.ts+++ b/packages/cli/src/team-multibyte-answer.test.ts@@ -1,84 +1,52 @@-import { describe, expect, it } from "bun:test";-import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";-import { tmpdir } from "node:os";+/**+ * A CJK + emoji answer reaches `response-<id>.md` byte-exact, and `outputSize` counts its+ * UTF-8 bytes. The answer is read from the transcript (JSON lines), so no pipe chunk+ * boundary can split a code point any more; this pins the end-to-end bytes.+ */++import { afterEach, beforeEach, describe, expect, it } from "bun:test";+import { createHash } from "node:crypto";+import { readFileSync } from "node:fs";import { join } from "node:path";import { runModels, setupSession } from "./team-orchestrator.js";--const ANSWER = "answer 🚀 日本語 end";--describe("team multibyte answer capture", () => {- it("preserves UTF-8 split across separate child stdout chunks", async () => {- const sessionPath = mkdtempSync(join(tmpdir(), "team-multibyte-answer-"));- const fakeDir = mkdtempSync(join(tmpdir(), "fake-claudish-multibyte-"));- const fakeClaudish = join(fakeDir, "claudish");- const originalClaudishBin = process.env.CLAUDISH_BIN;- const originalCaptureMode = process.env.CLAUDISH_TEAM_CAPTURE;-- writeFileSync(- fakeClaudish,- `#!/usr/bin/env bun-for await (const chunk of process.stdin) {- void chunk;-}--const answer = ${JSON.stringify(ANSWER)};-const line = JSON.stringify({- type: "assistant",- message: {- role: "assistant",- content: [{ type: "text", text: answer }],- },-}) + "\\n";-const bytes = Buffer.from(line, "utf8");-const emojiAt = bytes.indexOf(Buffer.from("🚀", "utf8"));-if (emojiAt === -1) {- throw new Error("emoji missing from fake stream-json frame");-}--const splitAt = emojiAt + 2;-const writeStdout = (chunk) => new Promise((resolve, reject) => {- process.stdout.write(chunk, (error) => error ? reject(error) : resolve());+import {+ MAGMUX,+ NO_MAGMUX_MESSAGE,+ type PaneTestEnv,+ finishPaneTest,+ makePaneTestEnv,+ paneRunOptions,+ teamDirOf,+} from "./test-helpers/team-pane.js";++if (!MAGMUX) console.warn(NO_MAGMUX_MESSAGE);++let t: PaneTestEnv;++beforeEach(() => {+ t = makePaneTestEnv();});-await writeStdout(bytes.subarray(0, splitAt));-await Bun.sleep(50);-await writeStdout(bytes.subarray(splitAt));-`,- "utf-8"- );- chmodSync(fakeClaudish, 0o755);-- try {- process.env.CLAUDISH_BIN = fakeClaudish;- delete process.env.CLAUDISH_TEAM_CAPTURE;- setupSession(sessionPath, ["multibyte-model"], "Return the answer.");-- const status = await runModels(sessionPath, {- captureMode: "stream-json",- spawnPlanner: async () => ({ pinned: new Map<string, string>() }),- });- const [slotId, model] = Object.entries(status.models)[0];- const response = readFileSync(join(sessionPath, `response-${slotId}.md`), "utf-8");+afterEach(async () => {+ const report = await finishPaneTest(t);+ expect(report).toEqual({ processes: [], files: [] });+});- expect(model.state).toBe("COMPLETED");- expect(response).toContain("🚀");- expect(response).toContain("日本語");- expect(response).not.toContain("�");- expect(response).toBe(`${ANSWER}\n`);- expect(model.outputSize).toBe(Buffer.byteLength(`${ANSWER}\n`, "utf8"));- } finally {- if (originalClaudishBin === undefined) {- delete process.env.CLAUDISH_BIN;- } else {- process.env.CLAUDISH_BIN = originalClaudishBin;- }- if (originalCaptureMode === undefined) {- delete process.env.CLAUDISH_TEAM_CAPTURE;- } else {- process.env.CLAUDISH_TEAM_CAPTURE = originalCaptureMode;- }- rmSync(sessionPath, { recursive: true, force: true });- rmSync(fakeDir, { recursive: true, force: true });- }- });+describe.skipIf(!MAGMUX)("team multibyte answer capture", () => {+ it("writes a CJK and emoji answer byte-exact", async () => {+ const prompt = "Return the answer.";+ const sessionPath = teamDirOf(t);+ setupSession(sessionPath, ["fake-multibyte"], prompt);++ const status = await runModels(sessionPath, paneRunOptions(t));+ const [slotId, model] = Object.entries(status.models)[0] ?? [];+ const response = readFileSync(join(sessionPath, `response-${slotId}.md`), "utf-8");+ const sha8 = createHash("sha1").update(prompt).digest("hex").slice(0, 8);+ const expected = `答え 🍐 ANSWER fake-multibyte ${sha8} — 東京 ✓`;++ expect(model?.state).toBe("COMPLETED");+ expect(response).not.toContain("�");+ expect(response).toBe(expected);+ expect(model?.outputSize).toBe(Buffer.byteLength(expected, "utf8"));+ }, 30_000);});diff --git a/packages/cli/src/team-orchestrator-settle.contract.test.ts b/packages/cli/src/team-orchestrator-settle.contract.test.tsindex 35dfc067..2a81dd13 100644--- a/packages/cli/src/team-orchestrator-settle.contract.test.ts+++ b/packages/cli/src/team-orchestrator-settle.contract.test.ts@@ -5,33 +5,59 @@** - `TeamRunOptions.onSettled` is called exactly once, after the settled `status.txt`* render, for a run that settles at once; a throwing consumer cannot fail the run.- * - A throw inside the spawn loop SIGTERMs every child already spawned, removes the SIGINT- * handler, rethrows the ORIGINAL error, and never calls `onSettled`.+ * - A throw inside the spawn loop stops every pane already started, rethrows the+ * ORIGINAL error, and never calls `onSettled`.* - A throw before the loop (unreadable manifest.json) spawns nothing and never settles.*- * Children are the contract fake, injected through `TeamRunOptions.spawnChild` (documented).+ * Ported to panes (architecture §20.2): every slot is the pane fake (marker mode) in a real+ * headless magmux, reached through `TeamRunOptions.parentEnv` (CLAUDISH_BIN) instead of the+ * deleted `spawnChild` seam. Only the adapters and the fake changed; an assertion that no+ * longer holds is replaced and cites its reason.+ ** INFERRED (adapters in test-helpers/contract-adapters.ts): `setupSession(path, models, input)`,- * `startModels(path, opts)` resolving to a handle with `done`, the spawnChild call shape, and- * the file names `manifest.json` and `status.txt` in the team directory (both named in §3.3).+ * `startModels(path, opts)` resolving to a handle with `done`, and the file names+ * `manifest.json` and `status.txt` in the team directory (both named in §3.3).*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { existsSync, writeFileSync } from "node:fs";+import { chmodSync, existsSync, readdirSync, writeFileSync } from "node:fs";import { join } from "node:path";+import { orphanReport } from "./pane/test-helpers/hermetic-env.js";import { readTeamStatus, summarise } from "./team-orchestrator.js";-import { setupTeamSession, spawnSeam, startModels } from "./test-helpers/contract-adapters.js";+import { setupTeamSession, startModels } from "./test-helpers/contract-adapters.js";import { type TempLayout, makeTempLayout, waitFor } from "./test-helpers/contract-records.js";+import {+ MAGMUX,+ NO_MAGMUX_MESSAGE,+ type PaneTestEnv,+ finishPaneTest,+ makePaneTestEnv,+ paneRunOptions,+} from "./test-helpers/team-pane.js";++if (!MAGMUX) console.warn(NO_MAGMUX_MESSAGE);const T_TEST = 30_000;const MODELS = ["contract-fake-a", "contract-fake-b"];let layout: TempLayout;+let panes: PaneTestEnv;let teamDir: string;beforeEach(() => {layout = makeTempLayout("settle");+ panes = makePaneTestEnv();teamDir = join(layout.root, "team");});-afterEach(() => layout.cleanup());+afterEach(async () => {+ try {+ chmodSync(join(teamDir, "status.json"), 0o644);+ } catch {+ // no status.json in this test+ }+ const report = await finishPaneTest(panes);+ layout.cleanup();+ expect(report).toEqual({ processes: [], files: [] });+});async function settledWithin<T>(p: Promise<T>, ms: number, what: string): Promise<T> {let timer: ReturnType<typeof setTimeout> | undefined;@@ -45,137 +71,145 @@ async function settledWithin<T>(p: Promise<T>, ms: number, what: string): Promis}}-describe("REQ-21 onSettled: called once, after the settled render, for a run that settles at once", () => {- test(- "every slot answers and exits at once: onSettled runs exactly once with a completed status",- async () => {- await setupTeamSession(teamDir, MODELS, "answer once and exit");- const seam = spawnSeam({});- const calls: Array<{ status: unknown; statusTxtExisted: boolean }> = [];-- const handle = await startModels(teamDir, {- spawnChild: seam.spawnChild,- onSettled: (status: unknown) =>- calls.push({ status, statusTxtExisted: existsSync(join(teamDir, "status.txt")) }),- });- await settledWithin(handle.done, 15_000, "the team run");- await Bun.sleep(200);-- expect(seam.calls()).toBe(MODELS.length);- expect(calls).toHaveLength(1);- expect(calls[0]?.statusTxtExisted).toBe(true);- expect(summarise(calls[0]?.status as never)).toEqual({- status: "completed",- slots: 2,- ok: 2,- failed: 0,- cancelled: 0,- });- },- T_TEST- );-- test(- "a consumer that throws inside onSettled cannot fail the run",- async () => {- await setupTeamSession(teamDir, MODELS, "answer once and exit");- const seam = spawnSeam({});- let called = 0;-- const handle = await startModels(teamDir, {- spawnChild: seam.spawnChild,- onSettled: () => {- called += 1;- throw new Error("contract: a broken consumer");- },- });- let rejected: unknown;- await settledWithin(handle.done, 15_000, "the team run").catch((err) => {- rejected = err;- });-- expect(rejected).toBeUndefined();- expect(called).toBe(1);- },- T_TEST- );-});+/** Every slot that got a pane has its pane id in status.json. */+function panesStarted(): number {+ return Object.values(readTeamStatus(teamDir).models).filter((m) => Boolean(m.pane)).length;+}-describe("REQ-22 a throw inside the spawn loop leaves nothing running (amendment 4)", () => {- test(- "slot 2's spawn throws: the original error is rethrown, slot 1 gets SIGTERM, SIGINT handler removed, onSettled never called",- async () => {- await setupTeamSession(teamDir, MODELS, "@@HANG@@ stay alive until signalled");- const injected = new Error("contract: spawn of slot 2 failed");- const marker = (n: number) => join(layout.root, `sigterm-slot-${n}`);- const seam = spawnSeam({ throwOn: 2, error: injected, markerFor: marker, hang: true });- const sigintBefore = process.listenerCount("SIGINT");- let settledCalls = 0;-- const thrown = await startModels(teamDir, {- spawnChild: seam.spawnChild,- onSettled: () => {- settledCalls += 1;- },- }).then(- () => undefined,- (err: unknown) => err- );- const slot1 = seam.children[0];- await waitFor(- () => slot1 !== undefined && (slot1.exitCode !== null || slot1.signalCode !== null),- {- what: "slot 1 to exit",- timeoutMs: 5_000,- }- );- await Bun.sleep(300);- // The SIGTERM can arrive before the fake child has installed its handler (the loop throws- // within milliseconds of the first spawn); the default action then ends it by SIGTERM with- // no marker. Either is proof of SIGTERM; a SIGKILL or a clean exit is not.- const sigtermProof = slot1?.signalCode === "SIGTERM" || existsSync(marker(1));-- expect(sigtermProof).toBe(true);- expect(thrown).toBe(injected);- expect(seam.calls()).toBe(2);- expect(process.listenerCount("SIGINT")).toBe(sigintBefore);- expect(settledCalls).toBe(0);- expect(summarise(readTeamStatus(teamDir))).toEqual({- status: "failed",- slots: 2,- ok: 0,- failed: 2,- cancelled: 0,- });- },- T_TEST- );-- test(- "a throw before the loop (unreadable manifest.json): rejects, spawns nothing, never settles",- async () => {- await setupTeamSession(teamDir, MODELS, "answer once and exit");- writeFileSync(join(teamDir, "manifest.json"), "{ this is not json");- const seam = spawnSeam({});- const sigintBefore = process.listenerCount("SIGINT");- let settledCalls = 0;-- const thrown = await startModels(teamDir, {- spawnChild: seam.spawnChild,- onSettled: () => {- settledCalls += 1;- },- }).then(- () => undefined,- (err: unknown) => err- );- await Bun.sleep(300);-- expect(thrown).toBeInstanceOf(Error);- expect(seam.calls()).toBe(0);- expect(settledCalls).toBe(0);- expect(process.listenerCount("SIGINT")).toBe(sigintBefore);- },- T_TEST- );-});+describe.skipIf(!MAGMUX)(+ "REQ-21 onSettled: called once, after the settled render, for a run that settles at once",+ () => {+ test(+ "every slot answers at once: onSettled runs exactly once with a completed status",+ async () => {+ await setupTeamSession(teamDir, MODELS, "answer once and exit");+ const calls: Array<{ status: unknown; statusTxtExisted: boolean }> = [];++ const handle = await startModels(teamDir, {+ ...paneRunOptions(panes),+ onSettled: (status: unknown) =>+ calls.push({ status, statusTxtExisted: existsSync(join(teamDir, "status.txt")) }),+ });+ await settledWithin(handle.done, 15_000, "the team run");+ await Bun.sleep(200);++ // was: the spawn seam was called once per model+ expect(panesStarted()).toBe(MODELS.length);+ expect(calls).toHaveLength(1);+ expect(calls[0]?.statusTxtExisted).toBe(true);+ expect(summarise(calls[0]?.status as never)).toEqual({+ status: "completed",+ slots: 2,+ ok: 2,+ failed: 0,+ cancelled: 0,+ });+ },+ T_TEST+ );++ test(+ "a consumer that throws inside onSettled cannot fail the run",+ async () => {+ await setupTeamSession(teamDir, MODELS, "answer once and exit");+ let called = 0;++ const handle = await startModels(teamDir, {+ ...paneRunOptions(panes),+ onSettled: () => {+ called += 1;+ throw new Error("contract: a broken consumer");+ },+ });+ let rejected: unknown;+ await settledWithin(handle.done, 15_000, "the team run").catch((err) => {+ rejected = err;+ });++ expect(rejected).toBeUndefined();+ expect(called).toBe(1);+ },+ T_TEST+ );+ }+);++describe.skipIf(!MAGMUX)(+ "REQ-22 a throw inside the spawn loop leaves nothing running (amendment 4)",+ () => {+ test(+ "slot 2's status.json write throws: the original error is rethrown, slot 1's pane is reaped first, onSettled never called",+ async () => {+ await setupTeamSession(teamDir, MODELS, "@@HANG@@ stay alive until signalled");+ let settledCalls = 0;++ const run = startModels(teamDir, {+ ...paneRunOptions(panes),+ onSettled: () => {+ settledCalls += 1;+ },+ }).then(+ () => undefined,+ (err: unknown) => err+ );+ // The fault (§20.2, replacing the spawn seam's throw): once slot 1's pane exists — its+ // pane record is written before anything is spawned — status.json turns read-only,+ // inside the 300 ms boot stagger, so slot 2's STARTING write throws EACCES. (The file,+ // not the directory: an overwrite in place needs write permission on the file.)+ await waitFor(+ () => {+ const recs = join(panes.sockRoot, "panes");+ return existsSync(recs) && readdirSync(recs).length > 0;+ },+ { what: "slot 1's pane record", timeoutMs: 5_000, intervalMs: 5 }+ );+ chmodSync(join(teamDir, "status.json"), 0o444);+ const thrown = await run;++ // was: slot 1 got SIGTERM. Now: every started pane is reaped (no process, socket or+ // record) before the rejection.+ expect(orphanReport({ sockRoot: panes.sockRoot })).toEqual({ processes: [], files: [] });+ expect((thrown as NodeJS.ErrnoException).code).toBe("EACCES");+ expect(String((thrown as Error).message)).toContain("status.json");+ // deleted: "removes the SIGINT handler" — there is no per-run handler any more (§2.11)+ expect(settledCalls).toBe(0);+ expect(summarise(readTeamStatus(teamDir))).toEqual({+ status: "failed",+ slots: 2,+ ok: 0,+ failed: 2,+ cancelled: 0,+ });+ },+ T_TEST+ );++ test(+ "a throw before the loop (unreadable manifest.json): rejects, spawns nothing, never settles",+ async () => {+ await setupTeamSession(teamDir, MODELS, "answer once and exit");+ writeFileSync(join(teamDir, "manifest.json"), "{ this is not json");+ const sigintBefore = process.listenerCount("SIGINT");+ let settledCalls = 0;++ const thrown = await startModels(teamDir, {+ ...paneRunOptions(panes),+ onSettled: () => {+ settledCalls += 1;+ },+ }).then(+ () => undefined,+ (err: unknown) => err+ );+ await Bun.sleep(300);++ expect(thrown).toBeInstanceOf(Error);+ // was: the spawn seam was never called+ expect(existsSync(join(panes.sockRoot, "panes"))).toBe(false);+ expect(settledCalls).toBe(0);+ expect(process.listenerCount("SIGINT")).toBe(sigintBefore);+ },+ T_TEST+ );+ }+);diff --git a/packages/cli/src/team-orchestrator.test.ts b/packages/cli/src/team-orchestrator.test.tsindex 01cc7141..aca3b011 100644--- a/packages/cli/src/team-orchestrator.test.ts+++ b/packages/cli/src/team-orchestrator.test.ts@@ -7,17 +7,25 @@* - architecture.md: public API signatures, manifest.json schema,* status.json schema, security (path validation), revision #5 (zero-padded IDs)*- * Most runModels and judgeResponses behavior lives in integration tests; this- * file keeps one hermetic fake-child run to pin the manifest identity contract.+ * Most runModels and judgeResponses behavior lives in integration tests; this file+ * keeps hermetic pane runs (the fake interactive child in a real headless magmux) to+ * pin the manifest identity, the pane argv and the per-slot environment.*/import { afterEach, beforeEach, describe, expect, it, mock } from "bun:test";import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";-import { dirname, join, resolve } from "node:path";-import { fileURLToPath } from "node:url";+import { join, resolve } from "node:path";import { UPSTREAM_ERROR_LOG_ENV } from "./handlers/shared/upstream-error-capture.js";import type { ModelStatus, TeamManifest, TeamStatus, VoteResult } from "./team-orchestrator.js";+import {+ MAGMUX,+ type PaneTestEnv,+ finishPaneTest,+ makePaneTestEnv,+ paneRunOptions,+ teamDirOf,+} from "./test-helpers/team-pane.js";// ─── Dynamic imports (resolved at runtime so the module doesn't need to exist// until the tests actually run) ──────────────────────────────────────────@@ -38,60 +46,24 @@ function readJson<T>(filePath: string): T {return JSON.parse(readFileSync(filePath, "utf-8")) as T;}-/** Run a callback with `claudish` resolved to one of the real-process helpers. */-async function withFakeClaudish<T>(- helperName: string,- callback: (helperPath: string) => Promise<T>-): Promise<T> {- const originalPath = process.env.PATH;- const originalClaudishBin = process.env.CLAUDISH_BIN;- const originalCaptureMode = process.env.CLAUDISH_TEAM_CAPTURE;- const originalUpstreamErrorLog = process.env[UPSTREAM_ERROR_LOG_ENV];- const shimDir = mkdtempSync(join(tmpdir(), "team-orchestrator-shim-"));- const helperPath = join(- dirname(fileURLToPath(import.meta.url)),- "channel",- "test-helpers",- helperName- );-- writeFileSync(join(shimDir, "claudish"), `#!/bin/sh\nexec bun run "${helperPath}" "$@"\n`, {- mode: 0o755,- });-- try {- // CLAUDISH_BIN outranks PATH, and a capture env override would make the- // default-mode assertion depend on the developer's shell.- delete process.env.CLAUDISH_BIN;- delete process.env.CLAUDISH_TEAM_CAPTURE;- delete process.env[UPSTREAM_ERROR_LOG_ENV];- process.env.PATH = `${shimDir}:${originalPath ?? ""}`;- return await callback(helperPath);- } finally {- process.env.PATH = originalPath;- if (originalClaudishBin === undefined) {- delete process.env.CLAUDISH_BIN;- } else {- process.env.CLAUDISH_BIN = originalClaudishBin;- }- if (originalCaptureMode === undefined) {- delete process.env.CLAUDISH_TEAM_CAPTURE;- } else {- process.env.CLAUDISH_TEAM_CAPTURE = originalCaptureMode;- }- if (originalUpstreamErrorLog === undefined) {- delete process.env[UPSTREAM_ERROR_LOG_ENV];- } else {- process.env[UPSTREAM_ERROR_LOG_ENV] = originalUpstreamErrorLog;- }- rmSync(shimDir, { recursive: true, force: true });- }-}-// ─── Test state ───────────────────────────────────────────────────────────────let tempDir: string;+/** The hermetic pane env of the current pane test (set by `usePaneHooks`). */+let t: PaneTestEnv;++/** Per-test pane env, and the no-orphan check after every pane test. */+function usePaneHooks(): void {+ beforeEach(() => {+ t = makePaneTestEnv();+ });+ afterEach(async () => {+ const report = await finishPaneTest(t);+ expect(report).toEqual({ processes: [], files: [] });+ });+}+beforeEach(() => {tempDir = makeTempDir();});@@ -245,7 +217,7 @@ describe("team-orchestrator", () => {// ── FR6: status.json ──────────────────────────────────────────────────────describe("setupSession — status.json", () => {- it("TEST-08: all models start with PENDING state in status.json", async () => {+ it("TEST-08: all models start STARTING in status.json (the closed set has no PENDING)", async () => {const { setupSession } = await getOrchestrator();const models = ["model-a", "model-b", "model-c"];@@ -253,7 +225,7 @@ describe("team-orchestrator", () => {const status = readJson<TeamStatus>(join(tempDir, "status.json"));const states = Object.values(status.models).map((m) => m.state);- expect(states.every((s) => s === "PENDING")).toBe(true);+ expect(states.every((s) => s === "STARTING")).toBe(true);});it("TEST-09: status.json model count matches input models array length", async () => {@@ -303,6 +275,31 @@ describe("team-orchestrator", () => {// ── FR8: input validation — empty models ──────────────────────────────────+ // Moved from the deleted team-timeout-repro.test.ts (its bug #3).+ describe("setupSession — session directory overwrite protection", () => {+ it("rejects an existing session directory", async () => {+ const { setupSession } = await getOrchestrator();+ setupSession(tempDir, ["model-a"], "First run input");+ expect(() => setupSession(tempDir, ["model-b"], "Second run input")).toThrow(+ /Session already exists/+ );+ });++ it("preserves the session artifacts when a re-run is rejected", async () => {+ const { setupSession } = await getOrchestrator();+ setupSession(tempDir, ["model-a"], "First run input");+ const originalManifest = readFileSync(join(tempDir, "manifest.json"), "utf-8");+ const originalInput = readFileSync(join(tempDir, "input.md"), "utf-8");+ const originalStatus = readFileSync(join(tempDir, "status.json"), "utf-8");++ expect(() => setupSession(tempDir, ["model-b"], "DIFFERENT input")).toThrow();++ expect(readFileSync(join(tempDir, "manifest.json"), "utf-8")).toBe(originalManifest);+ expect(readFileSync(join(tempDir, "input.md"), "utf-8")).toBe(originalInput);+ expect(readFileSync(join(tempDir, "status.json"), "utf-8")).toBe(originalStatus);+ });+ });+describe("setupSession — input validation", () => {it("TEST-13: throws for an empty models array", async () => {const { setupSession } = await getOrchestrator();@@ -429,7 +426,7 @@ describe("team-orchestrator", () => {// ── FR6: getStatus ────────────────────────────────────────────────────────describe("getStatus", () => {- it("TEST-16: returns parsed status.json with PENDING state after setupSession", async () => {+ it("TEST-16: returns parsed status.json with STARTING state after setupSession", async () => {const { setupSession, getStatus } = await getOrchestrator();setupSession(tempDir, ["model-a", "model-b"], "task");@@ -440,7 +437,7 @@ describe("team-orchestrator", () => {expect(typeof status.models).toBe("object");const states = Object.values(status.models).map((m: ModelStatus) => m.state);- expect(states.every((s) => s === "PENDING")).toBe(true);+ expect(states.every((s) => s === "STARTING")).toBe(true);});it("TEST-17: getStatus throws when status.json does not exist", async () => {@@ -451,185 +448,222 @@ describe("team-orchestrator", () => {});});- describe("runModels — pinned spawn identity", () => {- it("keeps manifest identity and uses the default stream-json argv contract", async () => {+ describe.skipIf(!MAGMUX)("runModels on panes — spawn identity and argv", () => {+ usePaneHooks();++ it("keeps manifest identity and launches an interactive child with the pane argv", async () => {const { runModels, setupSession } = await getOrchestrator();const spawnPlanner = mock(async () => ({- pinned: new Map([["vendor/model", "or@vendor/model"]]),+ pinned: new Map([["vendor/model", "fake-env_probe"]]),}));+ const probe = join(t.tmp, "probe-{session}.json");+ const sessionPath = teamDirOf(t);+ setupSession(sessionPath, ["vendor/model"], "Analyze this input");- await withFakeClaudish("fake-claudish.ts", async () => {- setupSession(tempDir, ["vendor/model"], "Analyze this input");- const status = await runModels(tempDir, {- claudeFlags: ["--print-argv"],- spawnPlanner,- });- expect(Object.values(status.models)[0].state).toBe("COMPLETED");- expect(spawnPlanner).toHaveBeenCalledWith(["vendor/model"]);-- const manifest = readJson<TeamManifest>(join(tempDir, "manifest.json"));- const [anonId, entry] = Object.entries(manifest.models)[0];- expect(entry.model).toBe("vendor/model");-- const argv = JSON.parse(- readFileSync(join(tempDir, `response-${anonId}.md`), "utf-8").trim()- ) as string[];- const modelFlag = argv.indexOf("--model");- expect(argv[modelFlag + 1]).toBe("or@vendor/model");- const outputFormatFlag = argv.indexOf("--output-format");- expect(argv.slice(outputFormatFlag, outputFormatFlag + 2)).toEqual([- "--output-format",- "stream-json",- ]);-- const verboseFlag = argv.indexOf("--verbose");- const quietFlag = argv.indexOf("--quiet");- expect(verboseFlag).toBeGreaterThanOrEqual(0);- expect(quietFlag).toBeGreaterThanOrEqual(0);- // Mutation guard: claudish consumes --verbose for itself and also- // forwards a copy to claude, which rejects print + stream-json without- // it. --quiet must come later so only claudish's own narration stays off.- expect(verboseFlag).toBeLessThan(quietFlag);-- // The manifest identity is re-used by the judge round; the pinned argv- // must never replace it with the provider wire spec.- const reread = readJson<TeamManifest>(join(tempDir, "manifest.json"));- expect(reread.models[anonId].model).toBe("vendor/model");+ const status = await runModels(sessionPath, {+ ...paneRunOptions(t, {}, { FAKE_PROBE_FILE: probe }),+ spawnPlanner,});- });-- it("omits stream-json-only flags when captureMode is print", async () => {+ const [anonId, slot] = Object.entries(status.models)[0] ?? [];+ expect(slot?.state).toBe("COMPLETED");+ expect(spawnPlanner).toHaveBeenCalledWith(["vendor/model"]);+ expect(slot?.model).toBe("vendor/model");+ expect(slot?.spawnModel).toBe("fake-env_probe");++ const { argv } = readJson<{ argv: string[] }>(+ probe.replace("{session}", slot?.sessionUuid as string)+ );+ // -i --model <spawnModel> -y --quiet --session-id <uuid> --add-dir <turn dir>+ expect(argv.slice(0, 6)).toEqual([+ "-i",+ "--model",+ "fake-env_probe",+ "-y",+ "--quiet",+ "--session-id",+ ]);+ expect(argv[6]).toBe(slot?.sessionUuid as string);+ expect(argv[7]).toBe("--add-dir");+ for (const banned of ["-p", "--print", "--stdin", "--output-format", "--verbose", "--json"])+ expect(argv).not.toContain(banned);++ // The manifest identity is re-used by the judge round; the pinned argv must never+ // replace it with the provider wire spec.+ const reread = readJson<TeamManifest>(join(sessionPath, "manifest.json"));+ expect(reread.models[anonId as string]?.model).toBe("vendor/model");+ }, 30_000);++ it("gives every model slot its own upstream-error log and token file", async () => {const { runModels, setupSession } = await getOrchestrator();- const spawnPlanner = mock(async () => ({ pinned: new Map<string, string>() }));-- await withFakeClaudish("fake-claudish.ts", async () => {- setupSession(tempDir, ["vendor/model"], "Analyze this input");- const status = await runModels(tempDir, {- captureMode: "print",- claudeFlags: ["--print-argv"],- spawnPlanner,- });-- const [anonId, modelStatus] = Object.entries(status.models)[0];- expect(modelStatus.state).toBe("COMPLETED");- const argv = JSON.parse(- readFileSync(join(tempDir, `response-${anonId}.md`), "utf-8").trim()- ) as string[];-- expect(argv).toContain("--quiet");- expect(argv).not.toContain("--output-format");- expect(argv).not.toContain("--verbose");- });- });+ const probe = join(t.tmp, "probe-{session}.json");+ const sessionPath = teamDirOf(t);+ setupSession(sessionPath, ["fake-env_probe-1", "fake-env_probe-2"], "Analyze this input");- it("gives every model slot its own upstream-error log path", async () => {- const { runModels, setupSession } = await getOrchestrator();- const spawnPlanner = mock(async () => ({ pinned: new Map<string, string>() }));-- await withFakeClaudish("fake-claudish.ts", async () => {- setupSession(tempDir, ["vendor/model-a", "vendor/model-b"], "Analyze this input");- const status = await runModels(tempDir, {- claudeFlags: ["--print-env", UPSTREAM_ERROR_LOG_ENV],- spawnPlanner,- });-- const manifest = readJson<TeamManifest>(join(tempDir, "manifest.json"));- const paths = Object.keys(manifest.models).map((anonId) => {- expect(status.models[anonId].state).toBe("COMPLETED");- const childEnv = JSON.parse(- readFileSync(join(tempDir, `response-${anonId}.md`), "utf-8").trim()- ) as Record<string, string | null>;- const path = childEnv[UPSTREAM_ERROR_LOG_ENV];-- expect(path).toBe(join(tempDir, "errors", `${anonId}-upstream.jsonl`));- expect(dirname(path!)).toBe(join(tempDir, "errors"));- expect(path).toContain(anonId);- return path;- });-- expect(new Set(paths).size).toBe(paths.length);+ const status = await runModels(+ sessionPath,+ paneRunOptions(t, {}, { FAKE_PROBE_FILE: probe })+ );++ const paths = Object.entries(status.models).map(([anonId, m]) => {+ expect(m.state).toBe("COMPLETED");+ const { env } = readJson<{ env: Record<string, string> }>(+ probe.replace("{session}", m.sessionUuid as string)+ );+ const path = env[UPSTREAM_ERROR_LOG_ENV];+ expect(path).toBe(join(sessionPath, "errors", `${anonId}-upstream.jsonl`));+ expect(env.CLAUDISH_TOKEN_FILE).toBe(join(sessionPath, "stats", `${anonId}.json`));+ return path;});- });+ expect(new Set(paths).size).toBe(paths.length);+ }, 30_000);it("omits upstreamErrorLogPath from a recorded error when the child wrote no file", async () => {const { runModels, setupSession } = await getOrchestrator();- const spawnPlanner = mock(async () => ({ pinned: new Map<string, string>() }));-- await withFakeClaudish("fake-claudish.ts", async () => {- setupSession(tempDir, ["vendor/failing-model"], "Analyze this input");- await runModels(tempDir, {- claudeFlags: ["--fail"],- spawnPlanner,- });-- const recorded = readJson<TeamStatus>(join(tempDir, "status.json"));- const [anonId, modelStatus] = Object.entries(recorded.models)[0];- expect(modelStatus.state).toBe("FAILED");- expect(modelStatus.error).toBeDefined();- expect(modelStatus.error).not.toHaveProperty("upstreamErrorLogPath");- expect(existsSync(join(tempDir, "errors", `${anonId}-upstream.jsonl`))).toBe(false);- });- });+ const sessionPath = teamDirOf(t);+ setupSession(sessionPath, ["fake-exit_mid_turn"], "Analyze this input");+ await runModels(sessionPath, paneRunOptions(t));++ const recorded = readJson<TeamStatus>(join(sessionPath, "status.json"));+ const [anonId, modelStatus] = Object.entries(recorded.models)[0] ?? [];+ expect(modelStatus?.state).toBe("FAILED");+ expect(modelStatus?.error?.reason).toBe("child_exited");+ expect(modelStatus?.error).not.toHaveProperty("upstreamErrorLogPath");+ expect(existsSync(join(sessionPath, "errors", `${anonId}-upstream.jsonl`))).toBe(false);+ expect(existsSync(join(sessionPath, "errors", `${anonId}.log`))).toBe(true);+ }, 30_000);});- describe("runModels — stream-json answer recovery", () => {- it("keeps the voted answer that print mode loses to a later epilogue", async () => {+ describe.skipIf(!MAGMUX)("startModels on panes — team policy", () => {+ usePaneHooks();+ const TWO_LINES = "Review the change below.\nReply starting with VERDICT:.";++ it("returns once every slot left STARTING (D9)", async () => {+ const { startModels, setupSession, getStatus } = await getOrchestrator();+ const sessionPath = teamDirOf(t);+ setupSession(sessionPath, ["contract-fake-a", "contract-fake-b"], "@@HANG@@ hold");+ const handle = await startModels(sessionPath, paneRunOptions(t));+ const states = Object.values(getStatus(sessionPath).models).map((m) => m.state);+ expect(states).toEqual(["RUNNING", "RUNNING"]);+ const { cancelTeamRun } = await getOrchestrator();+ await cancelTeamRun(sessionPath);+ await handle.done;+ }, 30_000);++ it("fails a slot that stops on a question team cannot answer: FAILED blocked (D19)", async () => {+ const { runModels, setupSession } = await getOrchestrator();+ const sessionPath = teamDirOf(t);+ setupSession(sessionPath, ["fake-ask_user"], "Pick a fruit.");+ const status = await runModels(sessionPath, paneRunOptions(t));+ const [id, m] = Object.entries(status.models)[0] ?? [];+ expect(m?.state).toBe("FAILED");+ expect(m?.error?.reason).toBe("blocked");+ expect(m?.error?.detail.length).toBeGreaterThan(0);+ // The answer so far is kept for inspection.+ expect(existsSync(join(sessionPath, `response-${id}.md`))).toBe(true);+ }, 30_000);++ it("matches ^VERDICT: on the answer that starts after the task file was read (§2.13)", async () => {const { runModels, setupSession } = await getOrchestrator();- const spawnPlanner = mock(async () => ({ pinned: new Map<string, string>() }));- const input = "Review the implementation and return the required fenced vote block.";+ const sessionPath = teamDirOf(t);+ setupSession(sessionPath, ["fake-narrate_then_read"], TWO_LINES);+ const status = await runModels(+ sessionPath,+ paneRunOptions(t, { requirePattern: "^VERDICT:" })+ );+ const [id, m] = Object.entries(status.models)[0] ?? [];+ expect(m?.state).toBe("COMPLETED");+ // The narration before the Read never reaches response-<id>.md.+ expect(readFileSync(join(sessionPath, `response-${id}.md`), "utf-8")).toBe("VERDICT: ok");+ }, 30_000);- await withFakeClaudish("fake-streamjson-child.ts", async (fakeChild) => {- const rawProc = Bun.spawn(- [process.execPath, "run", fakeChild, "--output-format", "stream-json"],- { stdin: "ignore", stdout: "pipe", stderr: "pipe" }- );- const [rawStream, rawStderr, rawExitCode] = await Promise.all([- new Response(rawProc.stdout).text(),- new Response(rawProc.stderr).text(),- rawProc.exited,- ]);- expect(rawExitCode).toBe(0);- expect(rawStderr).toBe("");-- const recoveredDir = join(tempDir, "recovered");- setupSession(recoveredDir, ["vendor/model"], input);- const recoveredStatus = await runModels(recoveredDir, {- requirePattern: "```vote",- spawnPlanner,- });-- const [recoveredId, recoveredModel] = Object.entries(recoveredStatus.models)[0];- const recoveredOutput = readFileSync(- join(recoveredDir, `response-${recoveredId}.md`),- "utf-8"- );- expect(recoveredOutput).toContain("```vote");- expect(recoveredOutput).toContain("The background task has now finished");- expect(recoveredModel.state).toBe("COMPLETED");-- const recoveredFileSize = Buffer.byteLength(recoveredOutput);- const rawStreamSize = Buffer.byteLength(rawStream);- expect(recoveredModel.outputSize).toBe(recoveredFileSize);- expect(rawStreamSize).toBeGreaterThan(recoveredModel.outputSize * 8);-- const printDir = join(tempDir, "print");- setupSession(printDir, ["vendor/model"], input);- const printStatus = await runModels(printDir, {- captureMode: "print",- requirePattern: "```vote",- spawnPlanner,- });-- const [printId, printModel] = Object.entries(printStatus.models)[0];- const printOutput = readFileSync(join(printDir, `response-${printId}.md`), "utf-8");- expect(printOutput).toContain("The background task has now finished");- expect(printOutput).not.toContain("```vote");- expect(printModel.state).toBe("EMPTY");- expect(printModel.error?.reason).toBe("shape_mismatch");- });+ it("fails a slot that never read its task file: FAILED prompt_not_read", async () => {+ const { runModels, setupSession } = await getOrchestrator();+ const sessionPath = teamDirOf(t);+ setupSession(sessionPath, ["fake-no_read"], TWO_LINES);+ const status = await runModels(sessionPath, paneRunOptions(t));+ const m = Object.values(status.models)[0];+ expect(m?.state).toBe("FAILED");+ expect(m?.error?.reason).toBe("prompt_not_read");+ expect(m?.error?.detail).toContain("never read");+ }, 30_000);++ it("fails a slot whose child refuses --agent: FAILED agent_rejected (D11)", async () => {+ const { runModels, setupSession } = await getOrchestrator();+ const sessionPath = teamDirOf(t);+ setupSession(sessionPath, ["fake-answer"], "Reply with exactly PEAR");+ const status = await runModels(+ sessionPath,+ paneRunOptions(t, { claudeFlags: ["--agent", "zzz-missing"] })+ );+ const m = Object.values(status.models)[0];+ expect(m?.state).toBe("FAILED");+ expect(m?.error?.reason).toBe("agent_rejected");+ }, 30_000);++ it("names an open background shell in the slot's anomalies (R3-M5)", async () => {+ const { runModels, setupSession } = await getOrchestrator();+ const sessionPath = teamDirOf(t);+ setupSession(sessionPath, ["fake-bg_server"], "Start the dev server.");+ const status = await runModels(sessionPath, paneRunOptions(t));+ const m = Object.values(status.models)[0];+ expect(m?.state).toBe("COMPLETED");+ expect(m?.anomalies?.some((a) => a.startsWith("background_shell_open: "))).toBe(true);+ }, 30_000);++ it("refuses reserved claude_flags before anything is written or spawned", async () => {+ const { startModels, setupSession } = await getOrchestrator();+ const sessionPath = teamDirOf(t);+ setupSession(sessionPath, ["fake-answer"], "Reply with exactly PEAR");+ await expect(+ startModels(sessionPath, paneRunOptions(t, { claudeFlags: ["--max-budget-usd", "5"] }))+ ).rejects.toThrow(/^invalid_args: .*--max-budget-usd/);+ await expect(+ startModels(+ sessionPath,+ paneRunOptions(t, { claudeFlags: ["--allowedTools", "Read", "Bash"] })+ )+ ).rejects.toThrow(/^invalid_args: .*positional/);+ expect(existsSync(join(t.sockRoot, "panes"))).toBe(false);+ });++ it("refuses a non-plain prompt when the flags remove Read (§2.3 rule 4)", async () => {+ const { startModels, setupSession } = await getOrchestrator();+ const sessionPath = teamDirOf(t);+ setupSession(sessionPath, ["fake-answer"], TWO_LINES);+ await expect(+ startModels(sessionPath, paneRunOptions(t, { claudeFlags: ["--disallowedTools", "Read"] }))+ ).rejects.toThrow(/^invalid_args: .*Read tool is unavailable/);});});+ describe.skipIf(!MAGMUX)("runModels on panes — the whole turn is the answer", () => {+ usePaneHooks();++ it("keeps the voted answer AND the message a re-wake added after it", async () => {+ // Print mode kept only the final assistant message, so a late message replaced the+ // vote. A pane turn settles on Claude Code's own turn_duration, after the re-wake,+ // and its answer is every assistant text block of the turn.+ const { runModels, setupSession } = await getOrchestrator();+ const sessionPath = teamDirOf(t);+ setupSession(sessionPath, ["fake-rewake"], "Review and vote.");+ const status = await runModels(sessionPath, {+ ...paneRunOptions(+ t,+ { requirePattern: "^ANSWER fake-rewake " },+ { FAKE_GAP_MS_REWAKE: "1000" }+ ),+ paneTimings: { replStableMs: 200, secondaryQuietMs: 4_000 },+ });++ const [id, model] = Object.entries(status.models)[0] ?? [];+ const response = readFileSync(join(sessionPath, `response-${id}.md`), "utf-8");+ expect(model?.state).toBe("COMPLETED");+ expect(response).toStartWith("ANSWER fake-rewake ");+ expect(response).toEndWith("\n\nLATE second message");+ expect(model?.outputSize).toBe(Buffer.byteLength(response));+ }, 30_000);+ });+describe("runModels — requirePattern validation", () => {it("rejects an invalid pattern before reading manifest.json", async () => {const { runModels } = await getOrchestrator();diff --git a/packages/cli/src/team-orchestrator.ts b/packages/cli/src/team-orchestrator.tsindex 02ac60b9..dd2b4111 100644--- a/packages/cli/src/team-orchestrator.ts+++ b/packages/cli/src/team-orchestrator.ts@@ -1,28 +1,61 @@-import { type ChildProcess, spawn } from "node:child_process";-import {- createWriteStream,- existsSync,- mkdirSync,- readFileSync,- readdirSync,- writeFileSync,-} from "node:fs";+import { randomBytes, randomUUID } from "node:crypto";+import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";import { basename, join, resolve } from "node:path";import { type SpawnPlan, prehydrateCredentialsForSpawn } from "./auth/credentials/prehydrate.js";-import { StreamJsonReducer } from "./channel/stream-json-reducer.js";import { ENV } from "./config.js";import { UPSTREAM_ERROR_LOG_ENV } from "./handlers/shared/upstream-error-capture.js";import {- KILL_PROCESS_GROUP,- TERMINATE_GRACE_MS,- signalProcessTree,- terminateChildTree,-} from "./process-tree.js";+ type Accounting,+ type CaptureResult,+ type CaptureUnchanged,+ ContractErrorException,+ type FailureReason,+ type FinalVerdict,+ MAX_LIVE_PANES,+ type PaneBlock,+ type PaneSession,+ type PaneSessionOptions,+ type PaneSnapshot,+ SLOT_STATES,+ type SettledTurn,+ type SlotRow,+ type SlotState,+ TERMINAL_STATES,+ type TeamCancelResult,+ type TeamListResult,+ type TeamRunRow,+ assertMagmuxAvailable,+ checkChildFlags,+ contractMeta,+ deliveryRefusal,+ flagsRemoveRead,+ isTerminalState,+ livePaneCount,+ mergeAccounting,+ readTokenFileCached,+ releasePaneReservations,+ reservePanes,+ resolveProvider,+ sockRootFor,+ startPaneSession,+ toSlotRow,+} from "./pane/index.js";import { redactSecrets } from "./redact.js";-import { resolveClaudishSpawn } from "./spawn-claudish.js";-import { decodeChunk, newStdioDecoder } from "./stdio-decode.js";+import { projectsDir, transcriptPathFor } from "./session/session-discovery.js";import { renderTeamStatsCompact, statsDir, tokenFileFor, writeStatusFile } from "./team-stats.js";+/*+ * Every team slot is an INTERACTIVE Claude Code session launched through claudish, in its+ * own headless magmux pane, driven by `PaneSession` (pane/). The transcript decides when a+ * turn settled and what its answer is; this file owns the TEAM policy on top of it:+ * `require_pattern` / `min_output_bytes` (`classifyRunOutput`), a slot that stops on a+ * question it cannot answer is FAILED `blocked` (D19), and the run registry the polling+ * verbs read. Rationale: ai-docs/architecture/team-lifecycle.md and team-capture.md.+ *+ * No claudish timer ends a slot after its prompt was accepted (D10). The only bounds are+ * the pane's boot (90 s) and the admission of the prompt (30 s), before any work exists.+ */+// ─── Types ───────────────────────────────────────────────────────────────────export interface TeamManifest {@@ -31,68 +64,19 @@ export interface TeamManifest {shuffleOrder: string[];}-/**- * Why a run is being reported as unusable.- *- * Exit code alone is a bad success oracle here: `claude -p` exits 0 on API- * errors and on background-task termination just as it does on real success.- * Classifying the failure means the caller never has to infer it from byte counts.- */-export type FailureReason =- | "nonzero_exit"- /**- * The caller stopped this slot through `team(mode:"cancel")`. NOT a defect —- * the only failure reason here that reflects a decision rather than a fault.- */- | "cancelled"- /**- * Only `team-grid.ts` produces this now, mapping magmux's pane states. The- * orchestrator has no deadline and never terminates a slot itself — see- * ai-docs/architecture/team-lifecycle.md.- */- | "timeout"- | "api_error"- | "background_task_ceiling"- | "empty_output"- | "shape_mismatch";--/**- * How a child's answer is read off its stdout. See TeamRunOptions.captureMode.- */-export type TeamCaptureMode = "stream-json" | "print";--/** Escape hatch, so `"print"` is reachable without editing a call site. */-export const TEAM_CAPTURE_ENV_VAR = "CLAUDISH_TEAM_CAPTURE";--/**- * Resolve the capture mode: explicit option wins, then the env var, then- * recovery-on by default.- *- * Only the exact string `"print"` opts out. Garbage resolves to the default- * rather than throwing — a typo in an env var must not fail a whole team run,- * and the safe direction is the one that keeps more of the answer.- */-export function resolveCaptureMode(- explicit: TeamCaptureMode | undefined,- env: NodeJS.ProcessEnv = process.env-): TeamCaptureMode {- if (explicit) return explicit;- return env[TEAM_CAPTURE_ENV_VAR]?.trim().toLowerCase() === "print" ? "print" : "stream-json";-}-export interface ModelError {/** Model ID that failed (anonymized id used in the report). */model: string;- /** The command that was run. */+ /** The command the slot ran (the pane child's claudish argv, for the reader). */command: string;- /** Failure classification. */+ /** Failure classification (the contract's closed set, pane/contract.ts). */reason: FailureReason;/** One-line human-readable explanation of `reason`. */detail: string;- /** Tail of the captured stderr, if any. */- stderrSnippet?: string;- /** Tail of the captured stdout — the failure signal often lands here, not on stderr. */- stdoutSnippet?: string;+ /** Redacted head and tail of the pane's final screen. */+ screenSnippet?: string;+ /** Redacted head and tail of the answer the slot produced. */+ answerSnippet?: string;/** Path to the full error log file. */errorLogPath: string;/**@@ -104,77 +88,81 @@ export interface ModelError {* file means the child never had an upstream failure to record.*/upstreamErrorLogPath?: string;- /** Working directory the child ran in. */+ /** The team session directory. */workDir: string;}/**- * EMPTY = the child exited 0 but its stdout is not a usable answer (an API- * error, a truncated preamble, or fewer than `minOutputBytes`). Distinct from- * FAILED so callers can tell "the process broke" from "the process lied".+ * One slot in `status.json`. `state` is the contract's closed nine-value set. The fields+ * after `error` are written by every pane run; they are optional in the TYPE because a+ * `status.json` written by a pre-contract claudish lacks them, and `getStatus` returns+ * whatever is on disk.*/-export type ModelState = "PENDING" | "RUNNING" | "COMPLETED" | "FAILED" | "TIMEOUT" | "EMPTY";-export interface ModelStatus {- state: ModelState;+ state: SlotState;+ /** From the pane's exit event; null when claudish ended the pane (verdict, cancel). */exitCode: number | null;startedAt: string | null;completedAt: string | null;+ /** FINAL answer bytes, written once, when the slot turns terminal (team-lifecycle.md). */outputSize: number;- /** Populated on FAILED/TIMEOUT/EMPTY with details for the failure report. */+ /** Populated on FAILED / EMPTY / CANCELLED with details for the failure report. */error?: ModelError;+ model?: string;+ spawnModel?: string | null;+ provider?: string | null;+ sessionUuid?: string;+ transcriptPath?: string;+ pane?: string | null;+ captureSource?: "transcript" | "screen" | "none" | null;+ turnSource?: "transcript" | "screen";+ stopReason?: string | null;+ tokensIn?: number | null;+ tokensOut?: number | null;+ costUsd?: number | null;+ toolCalls?: number;+ turnsCompleted?: number;+ lastActivityAt?: string | null;+ /** The child's Claude Code version from its boot banner (R3-M4). */+ claudeCodeVersion?: string | null;+ /** Facts worth a reader's attention that are not failures (R3-M5, truncation). */+ anomalies?: string[];}export interface TeamStatus {startedAt: string;+ /** The run that wrote this file (CA-13); absent in a pre-contract file. */+ runId?: string;+ kind?: "run" | "judge";models: Record<string, ModelStatus>;}export interface TeamRunOptions {- claudeFlags?: string[]; // extra flags passed to child claudish+ claudeFlags?: string[]; // extra flags passed to child claudish (checked by checkChildFlags)onStatusChange?: (id: string, status: ModelStatus) => void;/**- * Opt-in stub threshold: below this many stdout bytes an exit-0 run is- * recorded EMPTY. Default 0 (off) — see DEFAULT_MIN_OUTPUT_BYTES for why.- * Whitespace-only output is caught regardless of this setting.+ * Opt-in stub threshold: below this many answer bytes a settled slot is recorded+ * EMPTY. Default 0 (off) — see DEFAULT_MIN_OUTPUT_BYTES for why. Whitespace-only+ * output is caught regardless of this setting.*/minOutputBytes?: number;/**- * Opt-in SHAPE contract: a JS regex source string the response must match, or- * the run is recorded EMPTY with reason `shape_mismatch`.- *- * This is the only signal that catches a child which answered correctly and- * then took one more turn. `claude -p` prints ONLY the final assistant- * message, so any post-answer turn (a background Task completing, a- * notification arriving) silently replaces the answer with an epilogue —- * exit 0, no API error, real non-whitespace prose. Measured: two models- * turned 7,743 and 4,737 output tokens into 250 B and 396 B of "the review- * above stands", and both were reported `succeeded`.+ * Opt-in SHAPE contract: a JS regex source string the answer must match, or the slot+ * is recorded EMPTY with reason `shape_mismatch`.*- * Byte counts cannot separate that from a legitimately short answer (a+ * Byte counts cannot separate a broken answer from a legitimately short one (a* measured 96 B reply is valid — see DEFAULT_MIN_OUTPUT_BYTES). A caller that* mandated an output shape, however, KNOWS what a complete answer looks like:- * `team`'s prompts require a fenced ```vote block, so "```vote" is a precise- * oracle where length is a guess.+ * `team`'s prompts require a fenced ```vote block, so "```vote" is a precise oracle+ * where length is a guess.*- * Matched against the FULL response, not the bounded tail.+ * Matched with `new RegExp(pattern)` (no flags) against the FULL answer: every+ * assistant text block of the turn, joined with "\n\n", exactly as written to+ * `response-<id>.md`. For a prompt delivered as a file the answer starts with the+ * first text block AFTER the task file was fully read, so `^VERDICT:` matches an+ * answer that begins with its verdict even when the model narrated before reading.*/requirePattern?: string;- /**- * How a child's answer is captured off its stdout. Default `"stream-json"`.- *- * - `"stream-json"` — children run under `--output-format stream-json` and- * the orchestrator concatenates every assistant text block. A child that- * answers and then takes one more turn keeps its answer.- * - `"print"` — the pre-v7.50 raw pipe: whatever `claude -p` prints, which is- * ONLY the final assistant message. Kept as an escape hatch for diagnosing- * a capture problem by comparing the two, and reachable without a code- * change via `CLAUDISH_TEAM_CAPTURE=print`.- *- * `requirePattern` is worth keeping ON under `"stream-json"`: recovery fixes- * answers that were LOST, not answers the model never shaped correctly.- */- captureMode?: TeamCaptureMode;/*** Called on a timer with a rendered, colourless progress block, and once more* when the run settles. Used to push live status somewhere a human can see it@@ -206,42 +194,48 @@ export interface TeamRunOptions {/** Spawn-plan factory seam for hermetic call-site tests. */spawnPlanner?: (models: (string | undefined)[]) => Promise<SpawnPlan>;/**- * Child-process spawn seam for hermetic tests (default `node:child_process`- * `spawn`). Lets a test make one slot's spawn throw synchronously.- */- spawnChild?: typeof spawn;- /**- * Pause between SIGTERM and SIGKILL when the spawn loop throws and the slots- * already spawned are stopped. Default `TERMINATE_GRACE_MS`. A test seam.- */- terminateGraceMs?: number;- /**- * Called exactly once, when the run SETTLES: after the last slot finished and- * the settled `status.txt` render, from inside `done`'s `finally`. Receives+ * Called exactly once, when the run SETTLES: after the last slot turned terminal+ * and the settled `status.txt` render, from inside `done`'s `finally`. Receives* the final status.*- * Read inside `startModels`, so the hook exists before the first child is+ * Read inside `startModels`, so the hook exists before the first pane is* spawned and does not depend on anything the caller does after* `startModels` returns — a run that settles at once takes the same path as a* slow one. A throwing consumer cannot fail the run. NOT called when* `startModels` itself throws: no run started, and the caller settles that.*/onSettled?: (status: TeamStatus) => void;+ /**+ * The environment every pane of this run is built from (X-M9). Default+ * `process.env`. The transcript path is derived with `projectsDir(parentEnv)`.+ */+ parentEnv?: Record<string, string | undefined>;+ /** "judge" for the judging/ sub-run of `judgeResponses`; default "run". */+ kind?: "run" | "judge";+ /** @internal test-only pane timing seams (X-M7); production never passes them */+ paneTimings?: PaneSessionOptions["timings"];+ /** @internal test-only boot bound; production uses the pane's 90 s */+ bootTimeoutMs?: number;}/**- * A running team, handed back the moment its children exist.+ * A running team, handed back once every slot has LEFT STARTING (D9): its prompt was+ * accepted, or it failed to boot or to take the prompt.** This is what makes a team run addressable without blocking on it. The caller- * gets the ids it needs to ask questions later, and asks them through- * `getStatus(sessionPath)` — which reports each slot's state, bytes and tokens —- * rather than by holding a tool call open for the length of the run.+ * gets the ids it needs to ask questions later, and asks them through the polling+ * verbs (`teamRunRow`, `listTeamRuns`, `captureTeamSlot`, `getStatus`) rather than by+ * holding a tool call open for the length of the run.*/export interface TeamHandle {/**- * Stable id for the whole run: the session directory's basename. Already the- * id used for this run's channel frames, so a caller correlating frames to a- * run needs no second identifier.+ * Unique per start (CA-13): `<team_session_id>-<base36 start ms>-<6 hex>`. Distinct+ * even when a later run reuses `sessionPath`.+ */+ runId: string;+ /**+ * The session directory's basename. Already the id used for this run's channel+ * frames, so a caller correlating frames to a run needs no second identifier.*/teamSessionId: string;/** Absolute session directory. `getStatus` and `judgeResponses` both take it. */@@ -255,210 +249,464 @@ export interface TeamHandle {*/slots: Record<string, string>;/**- * Settles when every slot has finished. Nothing needs to await it — the run+ * Settles when every slot is terminal. Nothing needs to await it — the run* completes and writes its files either way — and a caller that only polls- * `getStatus` can ignore it entirely.+ * can ignore it entirely.*/done: Promise<TeamStatus>;}-/** What the registry needs to answer questions about a run still in flight. */+export interface TeamJudgeOptions {+ judges?: string[]; // models to use as judges (default: same models as runners)+ claudeFlags?: string[];+ /** The environment the judge panes are built from; default `process.env`. */+ parentEnv?: Record<string, string | undefined>;+ /** @internal test-only pane timing seams */+ paneTimings?: PaneSessionOptions["timings"];+}++export interface VoteResult {+ judgeId: string;+ responseId: string;+ verdict: "APPROVE" | "REJECT" | "ABSTAIN";+ confidence: number;+ summary: string;+ keyIssues: string[];+}++export interface TeamVerdict {+ responses: Record<+ string,+ {+ approvals: number;+ rejections: number;+ abstentions: number;+ score: number; // approvals / (approvals + rejections)+ }+ >;+ ranking: string[]; // response IDs sorted by score descending+ votes: VoteResult[];+}++// ─── Run registry (architecture §3.2) ─────────────────────────────────────────++interface SlotEntry {+ id: string;+ model: string;+ spawnModel: string | null;+ tokenFile: string;+ /** null = the pane never spawned (its row is FAILED `pane_lost`, `pane: null`) */+ session: PaneSession | null;+ /** refreshed on the 2 s tick and on every read */+ acct: Accounting;+ /** what `response-<id>.md` holds once it was written (decide, onBlocked or terminal) */+ answer: string | null;+ stopReason: string | null;+}+interface LiveTeamRun {- sessionPath: string;- processes: Map<string, ChildProcess>;- idleMsFor: (slotId: string) => number | null;- activityFor: (slotId: string) => string | null;- liveBytesFor: (slotId: string) => number | null;- /**- * Whether the slot is still RUNNING. The run stays registered until its LAST- * slot settles, so without this an exited slot kept reporting its frozen- * activity and an idle clock that grew for as long as its siblings worked.- */- isRunning: (slotId: string) => boolean;- /** Marked before the signal, so the exit handler can tell stopped from crashed. */- cancelledSlots: Set<string>;+ runId: string;+ /** resolved absolute session dir (was the basename: "judging" collided, F6) */+ path: string;+ kind: "run" | "judge";+ startedAt: string;+ finishedAt: string | null;+ /** the in-memory object `updateModelStatus` serialises to status.json */+ status: TeamStatus;+ slots: Map<string, SlotEntry>;}/**- * Team runs currently in flight, keyed by `teamSessionId`.- *- * This exists because `startModels` returns before its children do. Once the- * run outlives the call that started it, something has to let a later call- * reach back into it — to read how long a slot has been quiet, and to stop one.- *- * Entries are removed when the run settles, so a completed run answers from- * `status.json` on disk rather than from memory, and the map cannot grow without- * bound in a long-lived MCP server.+ * Runs this process started, keyed by run_id (CA-13). An ACTIVE run stays until it+ * settles; a SETTLED run stays listable and capturable for SETTLED_RUN_RETENTION_MS,+ * at most MAX_SETTLED_RUNS of them (oldest evicted first). After eviction `status` still+ * answers from `status.json` (newest run at a path only).*/-const liveTeamRuns = new Map<string, LiveTeamRun>();+const teamRuns = new Map<string, LiveTeamRun>();+/** resolved path → run_id of the newest run started there */+const newestRunByPath = new Map<string, string>();+export const SETTLED_RUN_RETENTION_MS = 30 * 60_000; // same as channel TERMINAL_RETENTION_MS+export const MAX_SETTLED_RUNS = 20;+/** Slots of one run spawn this far apart, so N REPLs do not write ~/.claude.json at once (X-L8). */+export const BOOT_STAGGER_MS = 300;++function slotTerminal(e: SlotEntry): boolean {+ if (!e.session) return true;+ return isTerminalState(e.session.snapshot().state);+}++function runSettled(run: LiveTeamRun): boolean {+ return [...run.slots.values()].every((e) => slotTerminal(e));+}++/** Set `finishedAt` the moment the last slot turned terminal. */+function markIfSettled(run: LiveTeamRun): void {+ if (run.finishedAt === null && runSettled(run)) run.finishedAt = new Date().toISOString();+}++function evictRun(run: LiveTeamRun): void {+ teamRuns.delete(run.runId);+ if (newestRunByPath.get(run.path) === run.runId) newestRunByPath.delete(run.path);+}++/** Apply the retention policy. Called on every registry read and on every new run. */+function pruneRuns(now: number = Date.now()): void {+ const settled = [...teamRuns.values()]+ .filter((r) => {+ markIfSettled(r);+ return r.finishedAt !== null;+ })+ .sort((a, b) => Date.parse(a.finishedAt as string) - Date.parse(b.finishedAt as string));+ const keep: LiveTeamRun[] = [];+ for (const r of settled) {+ if (now - Date.parse(r.finishedAt as string) > SETTLED_RUN_RETENTION_MS) evictRun(r);+ else keep.push(r);+ }+ while (keep.length > MAX_SETTLED_RUNS) evictRun(keep.shift() as LiveTeamRun);+}++/** The run a verb addresses: `run_id` while retained, else the newest run at `path`. */+function addressRun(path: string | undefined, runId?: string): LiveTeamRun | null {+ pruneRuns();+ if (runId) {+ const run = teamRuns.get(runId) ?? null;+ if (run && path !== undefined && resolve(path) !== run.path) return null;+ return run;+ }+ if (path === undefined) return null;+ const id = newestRunByPath.get(resolve(path));+ return id ? (teamRuns.get(id) ?? null) : null;+}++/** The newest run at `path` when it is still ACTIVE. */+export function activeRunAt(path: string): { runId: string } | null {+ const run = addressRun(path);+ return run && !runSettled(run) ? { runId: run.runId } : null;+}/**- * Seconds each still-running slot has been silent, or null if the run is not- * live (never started here, or already settled — read `status.json` instead).- *- * INFORMATION ONLY. Nothing in claudish terminates a slot for being quiet. A- * child inside `go test ./...` writes nothing for minutes and is working; only- * the caller that set the task knows whether that is expected. Read this, then- * call `cancelTeamRun` or do not.+ * At most one ACTIVE run per path (§3.2). Thrown as `run`'s usual text error, never as+ * a ContractError: `run` is not a verb of the mod contract.*/-export function teamSlotIdleSeconds(teamSessionId: string): Record<string, number> | null {- const run = liveTeamRuns.get(teamSessionId);- if (!run) return null;- const out: Record<string, number> = {};- for (const slotId of run.processes.keys()) {- if (!run.isRunning(slotId)) continue;- const idle = run.idleMsFor(slotId);- if (idle !== null) out[slotId] = Math.round(idle / 1000);- }- return out;+function assertNoActiveRun(path: string): void {+ const active = activeRunAt(path);+ if (active)+ throw new Error(+ `invalid_args: a team run is already ACTIVE at ${path} (run_id ${active.runId}); cancel it or wait for it`+ );+}++function emptyAccounting(provider: string | null): Accounting {+ return { tokensIn: null, tokensOut: null, costUsd: null, toolCalls: 0, provider };+}++function refreshAccounting(e: SlotEntry, snap: PaneSnapshot): Accounting {+ e.acct = mergeAccounting(snap, readTokenFileCached(e.tokenFile), {+ model: e.model,+ spawnModel: e.spawnModel,+ });+ return e.acct;+}++/** The R3-M4 / R3-M5 anomalies a team reader must see beside the state. */+function notableAnomalies(snap: PaneSnapshot): string[] {+ return snap.anomalies.filter(+ (a) =>+ a.startsWith("background_shell_open") ||+ a.startsWith("turn_end_record_missing") ||+ a.startsWith("prompt_not_read")+ );+}++function neverSpawnedRow(e: SlotEntry, m: ModelStatus | undefined): SlotRow {+ return {+ slot: e.id,+ model: e.model,+ provider: e.acct.provider,+ state: m?.state ?? "FAILED",+ reason: m?.error?.reason ?? "pane_lost",+ tokens_in: null,+ tokens_out: null,+ cost_usd: null,+ tool_calls: 0,+ turns_completed: 0,+ last_activity_at: null,+ idle_seconds: null,+ activity: null,+ pane: null,+ };+}++function liveSlotRow(run: LiveTeamRun, e: SlotEntry): SlotRow {+ if (!e.session) return neverSpawnedRow(e, run.status.models[e.id]);+ const snap = e.session.snapshot();+ return toSlotRow(+ { slot: e.id, model: e.model, spawnModel: e.spawnModel },+ snap,+ refreshAccounting(e, snap)+ );+}++/** "ok" | "partial" | "all-failed" — the result card's words; CANCELLED counts as failed. */+function outcomeOf(states: SlotState[]): "ok" | "partial" | "all-failed" {+ const ok = states.filter((s) => s === "COMPLETED").length;+ if (ok === states.length) return "ok";+ return ok === 0 ? "all-failed" : "partial";+}++function runRow(run: LiveTeamRun): TeamRunRow {+ markIfSettled(run);+ const slots = [...run.slots.values()]+ .sort((a, b) => a.id.localeCompare(b.id))+ .map((e) => liveSlotRow(run, e));+ const settled = slots.every((s) => isTerminalState(s.state));+ return {+ run_id: run.runId,+ path: run.path,+ kind: run.kind,+ started_at: run.startedAt,+ finished_at: settled ? run.finishedAt : null,+ state: settled ? "SETTLED" : "ACTIVE",+ outcome: settled ? outcomeOf(slots.map((s) => s.state)) : null,+ slots,+ };+}++/** `run` from memory: the addressed run while retained, else null. */+export function teamRunRow(path: string | undefined, runId?: string): TeamRunRow | null {+ const run = addressRun(path, runId);+ return run ? runRow(run) : null;+}++/** True when `runId` is retained but a newer run now owns its path's status.json. */+export function isSupersededRun(runId: string): boolean {+ const run = teamRuns.get(runId);+ return !!run && newestRunByPath.get(run.path) !== runId;+}++/** A persisted state outside the closed set (e.g. `PENDING`) reads FAILED with reason null. */+function closedState(s: unknown): { state: SlotState; known: boolean } {+ return (SLOT_STATES as readonly unknown[]).includes(s)+ ? { state: s as SlotState, known: true }+ : { state: "FAILED", known: false };}/**- * What each still-running slot is doing, from the stream-json reducer:- * `starting`, `running`, `tool_executing` or `finishing` (its `result` arrived- * and it is exiting). A slot never reports `waiting_for_input`: its stdin is- * closed at spawn, so nothing can wait for input. Null for a run that is not- * live; a slot is absent once it has exited (its outcome is `state` in- * `status.json`), and under `"print"` capture, which emits no frames to read.- *- * The companion to `teamSlotIdleSeconds`, and the reason that number is safe to- * publish without a verdict attached. Ninety seconds of silence in- * `tool_executing` is a build running; the same ninety seconds in `running` is- * a model that stopped mid-answer. The old reaper could not tell those apart —- * it had no state at all — and killed the first kind.+ * `run` built from `status.json`, for a run this server does not hold (§8 B): rows have+ * `idle_seconds:null` and `activity:null`, and `state` is whatever was last written.*/-export function teamSlotActivity(teamSessionId: string): Record<string, string> | null {- const run = liveTeamRuns.get(teamSessionId);- if (!run) return null;- const out: Record<string, string> = {};- for (const slotId of run.processes.keys()) {- if (!run.isRunning(slotId)) continue;- const activity = run.activityFor(slotId);- if (activity !== null) out[slotId] = activity;+export function teamRunRowFromDisk(path: string, status: TeamStatus): TeamRunRow {+ const manifest = readManifestOrNull(path);+ const slots: SlotRow[] = Object.entries(status.models ?? {})+ .sort(([a], [b]) => a.localeCompare(b))+ .map(([id, m]) => {+ const { state, known } = closedState(m?.state);+ const terminal = isTerminalState(state);+ return {+ slot: id,+ model: m?.model ?? manifest?.models[id]?.model ?? "unknown",+ provider: m?.provider ?? null,+ state,+ reason: !known || !terminal || state === "COMPLETED" ? null : (m?.error?.reason ?? null),+ tokens_in: m?.tokensIn ?? null,+ tokens_out: m?.tokensOut ?? null,+ cost_usd: m?.costUsd ?? null,+ tool_calls: m?.toolCalls ?? 0,+ turns_completed: m?.turnsCompleted ?? 0,+ last_activity_at: m?.lastActivityAt ?? null,+ idle_seconds: null,+ activity: null,+ pane: m?.pane ?? null,+ };+ });+ const settled = slots.length > 0 && slots.every((s) => isTerminalState(s.state));+ const completions = Object.values(status.models ?? {})+ .map((m) => (m?.completedAt ? Date.parse(m.completedAt) : Number.NaN))+ .filter(Number.isFinite);+ return {+ run_id: status.runId ?? basename(path),+ path,+ kind: status.kind ?? (basename(path) === "judging" ? "judge" : "run"),+ started_at: status.startedAt,+ finished_at:+ settled && completions.length ? new Date(Math.max(...completions)).toISOString() : null,+ state: settled ? "SETTLED" : "ACTIVE",+ outcome: settled ? outcomeOf(slots.map((s) => s.state)) : null,+ slots,+ };+}++function readManifestOrNull(path: string): TeamManifest | null {+ try {+ return JSON.parse(readFileSync(join(path, "manifest.json"), "utf-8")) as TeamManifest;+ } catch {+ return null;}- return out;+}++/** Contract A: every retained run, ACTIVE first, then SETTLED by `finished_at` desc. */+export function listTeamRuns(): TeamListResult {+ pruneRuns();+ const rows = [...teamRuns.values()].map(runRow);+ const active = rows+ .filter((r) => r.state === "ACTIVE")+ .sort((a, b) => b.started_at.localeCompare(a.started_at));+ const settled = rows+ .filter((r) => r.state === "SETTLED")+ .sort((a, b) => (b.finished_at ?? "").localeCompare(a.finished_at ?? ""));+ return { ...contractMeta(), runs: [...active, ...settled] };+}++function unknownRun(path: string | undefined, runId?: string): ContractErrorException {+ return new ContractErrorException(+ "unknown_run",+ runId+ ? `no team run with run_id ${runId} is retained by this server`+ : `no team run at ${path} is held by this server`+ );}/**- * Bytes of ANSWER each still-running slot has produced so far, or null for a run- * that is not live here.- *- * The field `outputSize` is not this. `outputSize` is written once, in `finish()`,- * so it reads 0 for the whole life of a RUNNING slot however much that slot has- * written — and a caller that reads it as progress concludes a working slot- * produced nothing. That misreading is the reason this exists.+ * Stop one slot, or every slot in a run, on the caller's instruction (contract C).*- * Same unit as `outputSize`, deliberately: both count recovered answer prose, so- * this number grows into the one the slot finishes with. It lags by at most one- * unterminated line, which the stream-json reducer holds back until its newline- * arrives (see `ModelRuntime.flushPartial`).+ * The ONLY thing that ends a working team slot. The orchestrator used to do it on a+ * timer and got it wrong — three productive slots died in session team-20260827-0015+ * because silence during a long tool call was read as death. The decision belongs to+ * whoever set the task and can tell a slow build from a hang.*- * Volume, not liveness. Read it with `teamSlotIdleSeconds` and `teamSlotActivity`:- * a slot can legitimately sit at 0 B for minutes while a build runs.+ * Synchronous transition, asynchronous reap: the state is CANCELLED when this returns;+ * the pane close and the process-group reap finish in the background.*/-export function teamSlotLiveBytes(teamSessionId: string): Record<string, number> | null {- const run = liveTeamRuns.get(teamSessionId);- if (!run) return null;- const out: Record<string, number> = {};- for (const slotId of run.processes.keys()) {- if (!run.isRunning(slotId)) continue;- const bytes = run.liveBytesFor(slotId);- if (bytes !== null) out[slotId] = bytes;+export async function cancelTeamRun(+ path: string | undefined,+ slot?: string,+ runId?: string+): Promise<TeamCancelResult> {+ const run = addressRun(path, runId);+ if (!run) throw unknownRun(path, runId);+ const entries = [...run.slots.values()].sort((a, b) => a.id.localeCompare(b.id));+ const targets = slot === undefined ? entries : entries.filter((e) => e.id === slot);+ if (slot !== undefined && targets.length === 0)+ throw new ContractErrorException(+ "unknown_slot",+ `run ${run.runId} has no slot ${JSON.stringify(slot)}`+ );+ const results = targets.map((e) => {+ if (!e.session)+ return { slot: e.id, state: run.status.models[e.id]?.state ?? "FAILED", changed: false };+ const r = e.session.cancel();+ return { slot: e.id, state: r.state, changed: r.changed };+ });+ return { run_id: run.runId, path: run.path, results };+}++/** The screen of a slot whose pane never spawned (§8 D, amended r2). */+function neverSpawnedCapture(): CaptureResult {+ return {+ seq: 0,+ cols: 160,+ rows: 50,+ cursor: { x: 0, y: 0 },+ lines: Array.from({ length: 50 }, () => ""),+ final: true,+ };+}++/** Contract D, memory only. Throws `ContractErrorException`. */+export function captureTeamSlot(+ path: string | undefined,+ slot: string,+ sinceSeq?: number,+ spans?: boolean,+ runId?: string+): CaptureResult | CaptureUnchanged {+ const run = addressRun(path, runId);+ if (!run) throw unknownRun(path, runId);+ const e = run.slots.get(slot);+ if (!e)+ throw new ContractErrorException(+ "unknown_slot",+ `run ${run.runId} has no slot ${JSON.stringify(slot)}`+ );+ if (!e.session) {+ const c = neverSpawnedCapture();+ return sinceSeq === 0 ? { unchanged: true, seq: 0, final: true } : c;}- return out;+ return e.session.capture(sinceSeq, { spans: spans === true });}/**- * Terminate one slot, or every slot in a run, on the caller's instruction.- *- * The ONLY thing that kills a team slot. The orchestrator used to do it on a- * timer and got it wrong — three productive slots died in session- * team-20260827-0015 because silence during a long tool call was read as death.- * The decision now belongs to whoever set the task and can tell a slow build- * from a hang.- *- * Kills the process GROUP, not the pid: `claudish` is a launcher that runs the- * real CLI under Bun, which runs `claude`. Signalling the direct child reaches- * only the launcher and leaves the tree alive, still billing and still holding- * the response pipe open.+ * Per-slot maps the legacy `status` payload carries beside `run` (§4.1), derived from+ * the live rows: idle seconds and activity of every non-terminal slot, and the answer+ * bytes each has produced so far. Null for a run this server does not hold.*/-export async function cancelTeamRun(- teamSessionId: string,- slotId?: string-): Promise<{ found: boolean; cancelled: string[] }> {- const run = liveTeamRuns.get(teamSessionId);- if (!run) return { found: false, cancelled: [] };-- const targets = slotId ? (run.processes.has(slotId) ? [slotId] : []) : [...run.processes.keys()];-- const cancelled: string[] = [];- for (const id of targets) {- const proc = run.processes.get(id);- if (!proc) continue;- // Marked BEFORE the signal. The exit handler can fire as soon as the process- // dies, and a mark set afterwards would lose the race and file a deliberate- // stop as a crash.- run.cancelledSlots.add(id);- await terminateChildTree(proc);- cancelled.push(id);+export function teamLiveMaps(+ path: string | undefined,+ runId?: string+): {+ idle: Record<string, number>;+ activity: Record<string, string>;+ liveBytes: Record<string, number>;+ endRecordMissing: string[];+} | null {+ const run = addressRun(path, runId);+ if (!run) return null;+ const idle: Record<string, number> = {};+ const activity: Record<string, string> = {};+ const liveBytes: Record<string, number> = {};+ const endRecordMissing: string[] = [];+ for (const e of run.slots.values()) {+ if (!e.session) continue;+ const snap = e.session.snapshot();+ if (isTerminalState(snap.state)) continue;+ const row = toSlotRow({ slot: e.id, model: e.model, spawnModel: e.spawnModel }, snap, e.acct);+ if (row.idle_seconds !== null) idle[e.id] = row.idle_seconds;+ liveBytes[e.id] = snap.liveAnswerBytes;+ const missing = snap.anomalies.includes("turn_end_record_missing");+ if (missing) endRecordMissing.push(e.id);+ if (row.activity !== null)+ activity[e.id] = missing ? `${row.activity}: turn_end_record_missing` : row.activity;}- return { found: true, cancelled };+ return { idle, activity, liveBytes, endRecordMissing };}/**- * Terminate every live team run. Process shutdown only.- *- * Needed because `startModels` returns before its children do: a run now- * outlives the call that started it, so nothing else would reach these children- * when the host process is asked to stop. Without this they survive their parent- * and keep billing — the same orphaning `cancelTeamRun` guards against, one- * level up.- *- * The per-run SIGINT handler covers Ctrl+C. This covers SIGTERM, which that- * handler does not see.+ * Settle every live team run CANCELLED. Process shutdown only: the records end+ * `cancelled` because each run's `done` resolves on these transitions; the pane registry's+ * `reapAllPanes` does the killing.*/export async function shutdownAllTeamRuns(): Promise<void> {- await Promise.all([...liveTeamRuns.keys()].map((id) => cancelTeamRun(id).catch(() => undefined)));+ const pending: Promise<unknown>[] = [];+ for (const run of teamRuns.values()) {+ for (const e of run.slots.values()) {+ if (!e.session) continue;+ e.session.cancel();+ pending.push(e.session.terminal.catch(() => undefined));+ }+ }+ await Promise.all(pending);}-export interface TeamJudgeOptions {- judges?: string[]; // models to use as judges (default: same models as runners)- claudeFlags?: string[];+/** @internal tests: forget every retained run. */+export function resetTeamRegistryForTests(): void {+ teamRuns.clear();+ newestRunByPath.clear();}-export interface VoteResult {- judgeId: string;- responseId: string;- verdict: "APPROVE" | "REJECT" | "ABSTAIN";- confidence: number;- summary: string;- keyIssues: string[];-}--export interface TeamVerdict {- responses: Record<- string,- {- approvals: number;- rejections: number;- abstentions: number;- score: number; // approvals / (approvals + rejections)- }- >;- ranking: string[]; // response IDs sorted by score descending- votes: VoteResult[];+/** @internal tests: apply the retention policy as of `now` (the 30-minute rule). */+export function pruneTeamRunsForTests(now: number): void {+ pruneRuns(now);}// ─── Output Classification ────────────────────────────────────────────────────/**- * How many trailing stdout bytes we retain per child for diagnosis. Bounded so a- * 30 KB answer isn't buffered twice; exported-by-const so `classifyRunOutput`- * knows when the tail it was handed is the complete output.+ * How many trailing answer bytes the channel's stream-json path retains for diagnosis+ * (both owners use it until the channel moves onto panes).*/export const STDOUT_TAIL_LIMIT = 4000;-/** Budget for the stdout snippet recorded in `status.json`. */+/** Budget for the answer / screen snippets recorded in `status.json`. */const SNIPPET_LIMIT = 2000;/** Bytes of the snippet budget spent on the START of the text. */@@ -485,16 +733,6 @@ export function snippetHeadAndTail(text: string): string {return `${head}\n\n… [${omitted} bytes omitted] …\n\n${tail}`;}-/** 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. When it fires, the turn is- * terminated, whatever text was already emitted is flushed, and the exit code- * is 0 — so the run looks successful while carrying only a partial answer.- */-const BG_CEILING_RE = /Background tasks still running after (\d+)s; terminating/i;-/*** Stub threshold, OFF by default.*@@ -511,189 +749,142 @@ const BG_CEILING_RE = /Background tasks still running after (\d+)s; terminating/*/export const DEFAULT_MIN_OUTPUT_BYTES = 0;-/* Process-tree termination lives in ./process-tree.ts — shared with the channel- session manager, which had the identical orphaning bug in `cancel_session`. */+/** Added to `detail` (or the COMPLETED slot's anomalies) when the turn ended on max_tokens. */+export const TRUNCATION_NOTE =+ "the turn ended on stop_reason max_tokens, so the answer may be truncated";/**- * Decide whether an exit-0 run actually produced an answer.- * Returns null when the output looks usable.+ * Decide whether a settled turn produced a usable answer. Returns null when it did.+ *+ * Precedence: `api_error` (FAILED) → `prompt_not_read` (FAILED) → `refused` (EMPTY) →+ * whitespace-only `empty_output` → `min_output_bytes` → `shape_mismatch` LAST (all+ * EMPTY). The structural failures come first because they give better detail, and a+ * turn that hit one of them would fail the shape contract too — reporting "no ```vote+ * block" for what is really an API error would send the caller after the wrong problem.*/-export function classifyRunOutput(opts: {- outputSize: number;- stdoutTail: string;- stderr: string;- minOutputBytes: number;+export function classifyRunOutput(input: {+ /** The full answer: text blocks joined with "\n\n", as written to response-<id>.md. */+ answer: string;+ apiError: { status: number | null; text: string } | null;+ stopReason?: string | null;+ /** `complete === false` → prompt_not_read */+ promptRead?: SettledTurn["delivery"];+ minOutputBytes?: number;/** Caller's shape contract (regex source). See TeamRunOptions.requirePattern. */requirePattern?: string;- /**- * The complete stdout, when the caller could read it back off disk.- *- * `stdoutTail` holds only the LAST STDOUT_TAIL_LIMIT bytes, so matching a- * pattern against it would silently fail for any contract whose marker sits- * near the START of a long answer. Falls back to the tail when absent, which- * is exact whenever the tail IS the whole output.- */- fullOutput?: string;- /**- * How the answer was captured. Only changes the `shape_mismatch` EXPLANATION,- * never the verdict: under `"print"` a missing marker is most likely an- * answer that was discarded, while under `"stream-json"` every assistant- * message was kept, so the model genuinely did not produce one. Pointing the- * caller at the wrong one of those costs a wasted investigation.- */- captureMode?: TeamCaptureMode;-}): { reason: FailureReason; detail: string } | null {- const {- outputSize,- stdoutTail,- stderr,- minOutputBytes,- requirePattern,- fullOutput,- captureMode = "print",- } = opts;-- const apiError = API_ERROR_RE.exec(stdoutTail);+}): { state: "FAILED" | "EMPTY"; reason: FailureReason; detail: string } | null {+ const v = classifyAnswer(input);+ if (v && input.stopReason === "max_tokens") v.detail = `${v.detail} (${TRUNCATION_NOTE})`;+ return v;+}++type Verdict = { state: "FAILED" | "EMPTY"; reason: FailureReason; detail: string };++/** The turn's own failure signals: an API error, an unread task file, a refusal. */+function classifyTurnSignals(input: Parameters<typeof classifyRunOutput>[0]): Verdict | null {+ const { apiError, stopReason, promptRead } = input;if (apiError) {+ const status = apiError.status === null ? "" : ` (status ${apiError.status})`;return {+ state: "FAILED",reason: "api_error",- detail: `Child exited 0 but stdout carries an API error: ${apiError[1]?.trim() || "unknown"}`,+ detail: `The turn ended in an API error${status}: ${apiError.text.slice(0, 300) || "unknown"}`,};}-- const bgCeiling = BG_CEILING_RE.exec(stderr);- if (bgCeiling) {+ if (promptRead?.complete === false) {+ const read = promptRead.linesRead ?? 0;return {- reason: "background_task_ceiling",+ state: "FAILED",+ reason: "prompt_not_read",detail:- `Claude Code terminated the turn after ${bgCeiling[1]}s waiting on background tasks, ` +- "flushing only partial output. Set CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS=0 in the child " +- "environment to wait indefinitely, or tell the model not to spawn background work.",+ read === 0+ ? "the task file was never read, so the answer cannot be about the task"+ : `the child's Read calls returned ${read} of ${promptRead.linesTotal ?? "?"} lines of the task file`,};}+ if (stopReason === "refusal") {+ return {+ state: "EMPTY",+ reason: "refused",+ detail: "The model refused (stop_reason refusal).",+ };+ }+ return null;+}- // Nothing but whitespace is never a real answer, at any threshold. This is- // what actually catches the observed 1-byte "\n" run.- //- // Guarded on outputSize: `stdoutTail` holds only the LAST STDOUT_TAIL_LIMIT- // bytes, so a large answer that happens to end in padding would otherwise be- // misread as empty. Only trust the tail when it IS the whole output.- const tailIsWholeOutput = outputSize <= STDOUT_TAIL_LIMIT;- if (outputSize === 0 || (tailIsWholeOutput && stdoutTail.trim().length === 0)) {+/** The caller's shape contract, matched against the full answer (no flags). */+function classifyShape(answer: string, requirePattern: string | undefined): Verdict | null {+ if (!requirePattern) return null;+ let re: RegExp | null = null;+ try {+ re = new RegExp(requirePattern);+ } catch {+ // An unusable pattern must never fail a run that may be perfectly good.+ // startModels validates up front so the caller hears about it before any+ // model is spawned; this branch only guards a direct call.+ return null;+ }+ if (re.test(answer)) return null;+ return {+ state: "EMPTY",+ reason: "shape_mismatch",+ detail:+ `The answer (${Buffer.byteLength(answer, "utf8")} B of assistant text after the task was ` ++ `read) does not match the required pattern /${requirePattern}/. Every assistant message ` ++ "of the turn was read from the transcript, so nothing was lost: the model did not " ++ "produce the shape. Re-prompt it, or relax the contract.",+ };+}++function classifyAnswer(input: Parameters<typeof classifyRunOutput>[0]): Verdict | null {+ const signal = classifyTurnSignals(input);+ if (signal) return signal;+ const { answer } = input;+ const minOutputBytes = input.minOutputBytes ?? DEFAULT_MIN_OUTPUT_BYTES;+ const outputSize = Buffer.byteLength(answer, "utf8");++ // Nothing but whitespace is never a real answer, at any threshold.+ if (answer.trim().length === 0) {return {+ state: "EMPTY",reason: "empty_output",- detail: `Child exited 0 but produced no non-whitespace output (${outputSize} B).`,+ detail: `The turn settled with no non-whitespace answer (${outputSize} B).`,};}// Opt-in stub threshold. Off by default — see DEFAULT_MIN_OUTPUT_BYTES.if (minOutputBytes > 0 && outputSize < minOutputBytes) {return {+ state: "EMPTY",reason: "empty_output",- detail:- `Child exited 0 but produced only ${outputSize} B of stdout ` +- `(caller required at least ${minOutputBytes} B).`,+ detail: `The answer is only ${outputSize} B (caller required at least ${minOutputBytes} B).`,};}- // Shape contract, checked LAST: the structural failures above are cheaper and- // give better detail, and a run that hit one of them would fail this too —- // reporting "no ```vote block" for what is really an API error would send the- // caller after the wrong problem.- if (requirePattern) {- const haystack = fullOutput ?? stdoutTail;- let re: RegExp | null = null;- try {- re = new RegExp(requirePattern);- } catch {- // An unusable pattern must never fail a run that may be perfectly good.- // runModels validates up front so the caller hears about it before any- // model is spawned; this branch only guards a direct call.- re = null;- }- if (re && !re.test(haystack)) {- const cause =- captureMode === "stream-json"- ? "Every assistant message this child produced was captured and concatenated, " +- "so this is not the print-mode dropout: the model genuinely never emitted the " +- "required shape. Re-prompt it, or relax the contract."- : "This is the signature of a child that answered and then took one more turn: " +- "`claude -p` prints only the FINAL assistant message, so a background task " +- "completing (or any late notification) replaces the real answer with an " +- "epilogue about it. The answer was generated, it just was not the last thing " +- "said — re-run with the default stream-json capture to keep it.";- return {- reason: "shape_mismatch",- detail:- `Child exited 0 with ${outputSize} B, but the response does not match the ` +- `required pattern /${requirePattern}/. ${cause}`,- };- }- }-- return null;+ return classifyShape(answer, input.requirePattern);}/**- * stderr lines that every healthy child emits, and which say nothing about the- * run's outcome.- *- * `unrecognized_model` is Claude Code telling itself it does not know the model- * name claudish routed — which is the NORMAL case for a proxied model and is- * emitted by runs that exit 0 with a perfect answer. In session- * team-20260815-115227 all four successful models produced an ~80 B- * `errors/NN.log` containing nothing else, so the run looked like it had four- * errors it did not have, and a reader scanning for real failures had to open- * each one to find out.- *- * Deliberately anchored on Claude Code's own `[claude-code:...]` tag rather than- * on the model name, so it cannot accidentally swallow a provider's message.- */-const BENIGN_STDERR_PATTERNS: readonly RegExp[] = [/^\s*\[claude-code:unrecognized_model\]/];--/**- * The part of stderr that is worth persisting — everything that is not known- * boilerplate. Empty means "nothing happened worth a log file".- *- * NOTE this filters only what decides whether to WRITE a success-path log. A- * genuine failure still persists the RAW stderr through `persistErrorLog`,- * because in that case even the boilerplate is context for whoever is reading.- */-export 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();-}--/**- * Write the full diagnostic log for a run.+ * Write the full diagnostic log for a slot that did not complete.** Always called on failure, so `errorLogPath` in the status report is never a- * dangling reference — including for timeouts, whose stderr used to be dropped.+ * dangling reference.*- * Credentials are stripped BEFORE the bytes hit disk. Provider stderr routinely- * echoes key material, and the team result card now names this path for the agent- * to read — so an unredacted log is a credential handed straight into an agent's- * context. Redacting at write time is the only point that covers every reader- * (the agent, a human, `report_error`, a future consumer).+ * Credentials are stripped BEFORE the bytes hit disk. A screen or an answer can echo+ * key material, and the team result card names this path for the agent to read — so an+ * unredacted log is a credential handed straight into an agent's context. Redacting at+ * write time is the only point that covers every reader (the agent, a human,+ * `report_error`, a future consumer).*/function persistErrorLog(errorLogPath: string,header: string,- stderr: string,- stdoutTail: string+ sections: Array<[title: string, body: string]>): void {const parts = [`=== ${redactSecrets(header)} ===`, ""];- parts.push("--- stderr ---", stderr.trim() ? redactSecrets(stderr) : "(empty)", "");- parts.push(- "--- stdout (tail) ---",- stdoutTail.trim() ? redactSecrets(stdoutTail) : "(empty)",- ""- );+ for (const [title, body] of sections) {+ parts.push(`--- ${title} ---`, body.trim() ? redactSecrets(body) : "(empty)", "");+ }try {writeFileSync(errorLogPath, parts.join("\n"), "utf-8");} catch {@@ -823,18 +1014,20 @@ export function setupSession(sessionPath: string, models: string[], input?: striwriteFileSync(join(sessionPath, "manifest.json"), JSON.stringify(manifest, null, 2), "utf-8");- // Initialize status.json with all models in PENDING state+ // Initialize status.json with every model STARTING: the closed set has no "not yet+ // started" state, and a slot leaves STARTING within the boot + admission bounds.const status: TeamStatus = {startedAt: now,models: Object.fromEntries(Object.keys(manifest.models).map((id) => [id,{- state: "PENDING" as const,+ state: "STARTING" as const,exitCode: null,startedAt: null,completedAt: null,outputSize: 0,+ model: manifest.models[id]?.model,},])),@@ -863,694 +1056,421 @@ function assertValidRequirePattern(pattern: string | undefined): void {}/**- * Read the response back only when a shape contract needs the whole text —- * otherwise this is pure cost on the happy path. Callers invoke this from- * `finish`, which runs on the outputStream's "close", so the file is complete.- *- * Returns undefined when the read is unnecessary OR fails; the caller then- * falls back to the tail, and a contract checked against less text can only- * produce a false FAILURE, never a false success, with the detail string- * naming the pattern either way.+ * The pre-spawn refusals of a team run, in the order the MCP `run` handler applies them+ * BEFORE `setupSession` writes anything (§4.1): the caller's flags (D18), a prompt that+ * cannot be delivered with those flags (§2.3 rule 4), magmux present (≥ 0.14.0), no+ * ACTIVE run at the path, and room under the per-user pane limit. Each throws an Error+ * whose message starts with its code (`invalid_args:`, `magmux_unavailable:`,+ * `pane_limit:`). `startModels` repeats them, so the CLI gets the same checks.*/-function readFullOutputIfNeeded(opts: {- crashed: boolean;- requirePattern: string | undefined;- outputSize: number;- outputPath: string;-}): string | undefined {- const { crashed, requirePattern, outputSize, outputPath } = opts;- if (crashed || !requirePattern || outputSize <= STDOUT_TAIL_LIMIT) return undefined;- try {- return readFileSync(outputPath, "utf-8");- } catch {- return undefined;+export async function preflightTeamRun(opts: {+ path: string;+ slots: number;+ claudeFlags?: string[];+ input?: string;+ parentEnv?: Record<string, string | undefined>;+}): Promise<void> {+ const flags = opts.claudeFlags ?? [];+ const check = checkChildFlags(flags);+ if (!check.ok) throw new Error(`invalid_args: ${check.message}`);+ if (opts.input !== undefined) {+ const refusal = deliveryRefusal(opts.input, !flagsRemoveRead(flags));+ if (refusal) throw new Error(`invalid_args: ${refusal}`);}+ await assertMagmuxAvailable();+ assertNoActiveRun(resolve(opts.path));+ const root = sockRootFor(opts.parentEnv ?? process.env);+ const live = livePaneCount(root);+ if (live + opts.slots > MAX_LIVE_PANES)+ throw new Error(+ `pane_limit: ${live} live panes for this user, ${opts.slots} more would exceed ${MAX_LIVE_PANES}`+ );}+function mintRunId(path: string, startMs: number): string {+ return `${basename(path)}-${startMs.toString(36)}-${randomBytes(3).toString("hex")}`;+}++const CANCELLED_DETAIL =+ 'Stopped on the caller\'s instruction via team(mode:"cancel"). ' ++ "Whatever the child had written up to that point is in its response file.";+/**- * Spawn every model in parallel and RETURN, without waiting for any of them.- *- * Resolves once the children exist: credentials are prehydrated (one 1Password- * handshake for the whole run, not one per model) and every process is running.- * The run itself continues in the background, and `handle.done` settles when the- * last slot finishes.+ * Start every model as an interactive pane and RETURN once each has left STARTING+ * (D9): its prompt was accepted, or it failed to boot or to take the prompt. Bounded+ * by the boot (90 s) and admission (30 s) limits, about 12–20 s typical.** Why this is the primitive rather than a blocking call. A team slot is a full* Claude Code session and can legitimately work for a very long time; the* previous blocking shape forced a deadline on it, and enforcing that deadline* killed three productive slots in session team-20260827-0015. Nothing here- * imposes a deadline any more. The caller polls `getStatus`, reads how long each- * slot has been quiet, and decides for itself whether to keep waiting.+ * imposes a deadline after a prompt is accepted. The caller polls, reads how long+ * each slot has been quiet and what it is doing, and decides for itself whether to+ * keep waiting.*- * Each model reads input.md and writes response-{ID}.md.+ * Each slot receives input.md (typed when it is one plain line, else as a task file it+ * is told to Read) and its answer is written to response-{ID}.md.*/export async function startModels(sessionPath: string,opts: TeamRunOptions = {}): Promise<TeamHandle> {assertValidRequirePattern(opts.requirePattern);-- const manifest: TeamManifest = JSON.parse(- readFileSync(join(sessionPath, "manifest.json"), "utf-8")- );- const statusPath = join(sessionPath, "status.json");-- const inputPath = join(sessionPath, "input.md");- const inputContent = readFileSync(inputPath, "utf-8");+ const claudeFlags = opts.claudeFlags ?? [];+ const flagCheck = checkChildFlags(claudeFlags);+ if (!flagCheck.ok) throw new Error(`invalid_args: ${flagCheck.message}`);++ const path = resolve(sessionPath);+ const manifest: TeamManifest = JSON.parse(readFileSync(join(path, "manifest.json"), "utf-8"));+ const statusPath = join(path, "status.json");+ const inputContent = readFileSync(join(path, "input.md"), "utf-8");+ const readAvailable = !flagsRemoveRead(claudeFlags);+ const refusal = deliveryRefusal(inputContent, readAvailable);+ if (refusal) throw new Error(`invalid_args: ${refusal}`);+ assertNoActiveRun(path);+ const parentEnv = opts.parentEnv ?? process.env;+ const kind = opts.kind ?? "run";// Resolve every model's credential AND its route HERE, before the spawn loop- // below fires N children at once. Each child would otherwise open its own- // 1Password SDK client, and the desktop app authorizes exactly one of them and- // denies the rest ("Denied authorization for SDK client") — silently losing- // whichever models depend on 1Password rather than a shell env var. Resolving- // in the parent write-throughs the keys into process.env, which the children- // inherit, and the returned plan pins each bare name to an explicit- // "provider@model" spec so the child never re-walks the chain (which is how a- // hydrated child still reached 1Password). See auth/credentials/prehydrate.ts- // for the measured repro.+ // below starts N children. Each child would otherwise open its own 1Password SDK+ // client, and the desktop app authorizes exactly one of them and denies the rest+ // ("Denied authorization for SDK client") — silently losing whichever models+ // depend on 1Password rather than a shell env var. Resolving in the parent+ // write-throughs the keys into process.env, which the pane snapshot carries to the+ // children, and the returned plan pins each bare name to an explicit+ // "provider@model" spec so the child never re-walks the chain. See+ // auth/credentials/prehydrate.ts for the measured repro.const spawnPlan = await (opts.spawnPlanner ?? prehydrateCredentialsForSpawn)(Object.values(manifest.models).map((m) => m.model));+ await assertMagmuxAvailable();// In-memory status cache to eliminate read-modify-write racesconst statusCache: TeamStatus = JSON.parse(readFileSync(statusPath, "utf-8"));+ const startMs = Date.now();+ const runId = mintRunId(path, startMs);+ statusCache.runId = runId;+ statusCache.kind = kind;- function updateModelStatus(id: string, update: Partial<ModelStatus>): void {- statusCache.models[id] = { ...statusCache.models[id], ...update };+ /**+ * Set while the spawn loop is being unwound (§6.1 step 7): the cancels it issues are+ * not the caller's, so nothing they do reaches status.json — the started slots stay+ * STARTING there and `summarise` counts them as failed.+ */+ let aborting = false;++ function patchModelStatus(id: string, update: Partial<ModelStatus>): void {+ statusCache.models[id] = { ...statusCache.models[id], ...update } as ModelStatus;+ }+ function flushStatus(): void {writeFileSync(statusPath, JSON.stringify(statusCache, null, 2), "utf-8");}+ function updateModelStatus(id: string, update: Partial<ModelStatus>): void {+ if (aborting) return;+ patchModelStatus(id, update);+ flushStatus();+ }+ function notifyStatus(id: string): void {+ try {+ opts.onStatusChange?.(id, statusCache.models[id] as ModelStatus);+ } catch {+ // A status consumer must never be able to fail the run.+ }+ }const minOutputBytes = opts.minOutputBytes ?? DEFAULT_MIN_OUTPUT_BYTES;const requirePattern = opts.requirePattern;- const captureMode = resolveCaptureMode(opts.captureMode);- /**- * Re-judge a timed-out model once its stdout pipe has closed and the response- * file is therefore final.- *- * A TIMEOUT is a statement about the CLOCK, not about the output. Those are- * separate facts and the run reported only the first: a model killed at the- * deadline was recorded `outputSize: 0` forever, even when a complete answer- * landed microseconds later. Anything downstream that trusted the run's own- * summary — the judging phase, a human, an orchestrating agent — discarded- * real work.- *- * If the child did produce a usable answer, record it as COMPLETED and say- * plainly that it arrived past the deadline. The file is on disk either way;- * this only decides whether the run ADMITS to having it.- */- function reconcileTimedOutOutput(- id: string,- finalBytes: number,- stdoutTail: string,- stderr: string- ): void {- const current = statusCache.models[id];- if (!current || current.state !== "TIMEOUT") return;- if (finalBytes <= current.outputSize) return; // nothing new arrived-- const degraded = classifyRunOutput({- outputSize: finalBytes,- stdoutTail,- stderr,- minOutputBytes,- });+ // Each child writes its token/cost stats here (one file per model).+ mkdirSync(statsDir(path), { recursive: true });++ const entries = new Map<string, SlotEntry>();+ let run: LiveTeamRun | null = null;+ const errorLogPathOf = (id: string) => join(path, "errors", `${id}.log`);+ const upstreamLogOf = (id: string) => join(path, "errors", `${id}-upstream.jsonl`);+ const commandOf = (e: SlotEntry) =>+ ["claudish", "-i", "--model", e.spawnModel ?? e.model, "-y", "--quiet", ...claudeFlags].join(+ " "+ );- if (degraded) {- // More bytes, but still not an answer (an API error, a preamble). Keep- // TIMEOUT and just correct the byte count so the report is not a lie.- updateModelStatus(id, { outputSize: finalBytes });- return;- }+ /** `response-<id>.md` in one write, byte-exact; remembered so it is written once. */+ function writeResponse(e: SlotEntry, text: string): string {+ writeFileSync(join(path, `response-${e.id}.md`), text, "utf-8");+ e.answer = text;+ return text;+ }- updateModelStatus(id, {- state: "COMPLETED",- outputSize: finalBytes,- completedAt: new Date().toISOString(),- error: undefined,+ /** Team policy for a settled turn (D8): the verdict, after the response file exists. */+ function teamDecide(e: SlotEntry, turn: SettledTurn): FinalVerdict {+ e.stopReason = turn.stopReason;+ writeResponse(e, turn.answer);+ const v = classifyRunOutput({+ answer: turn.answer,+ apiError: turn.apiError,+ stopReason: turn.stopReason,+ promptRead: turn.delivery,+ minOutputBytes,+ requirePattern,});- const note =- `Recovered after the deadline: the child flushed ${finalBytes} B while shutting down, ` +- "so its answer is complete and is being counted. The run still exceeded its timeout.";- const rt = runtimes.get(id);- if (rt) persistErrorLog(rt.errorLogPath, `RECOVERED: ${note}`, stderr, stdoutTail);- opts.onStatusChange?.(id, statusCache.models[id]);+ // R3-M5: an open background shell goes into the slot's detail, not only the anomalies.+ const shells = (e.session?.snapshot().anomalies ?? []).filter((a) =>+ a.startsWith("background_shell_open")+ );+ if (!v) {+ const notes = [...shells, ...(turn.stopReason === "max_tokens" ? [TRUNCATION_NOTE] : [])];+ return notes.length+ ? { state: "COMPLETED", detail: notes.join(" · ") }+ : { state: "COMPLETED" };+ }+ return { state: v.state, reason: v.reason, detail: [v.detail, ...shells].join(" · ") };}- // Each child writes its token/cost stats here (one file per model).- mkdirSync(statsDir(sessionPath), { recursive: true });-- const processes: Map<string, ChildProcess> = new Map();-- /**- * Per-model diagnostic handles, readable from OUTSIDE the spawn closure.- * A caller asking "what is slot 03 doing?" cannot reach into the closure, so- * everything it needs to answer that is published here.- */- interface ModelRuntime {- command: string;- errorLogPath: string;- getStderr: () => string;- getStdoutTail: () => string;- getByteCount: () => number;- /**- * Milliseconds since this child last wrote ANYTHING on either pipe.- *- * Reported, never acted on. This is the signal the deleted reaper lacked: it- * read `stats/<id>.json`, which only advances when tokens flow, so a slot- * inside a 90s `go test` looked dead and was killed. Raw pipe writes keep- * arriving throughout — Claude Code emits `tool_progress` heartbeats every- * 30s inside a long tool call — so this number distinguishes quiet-and-- * working from wedged, which a token timestamp cannot.- *- * The caller reads it and decides. `cancelTeamRun` is how it acts.- */- getIdleMs: () => number;- /**- * What this slot is doing right now, from the shared stream-json reducer:- * `starting`, `running`, `tool_executing`, `finishing`, a terminal state, or- * null under `"print"` capture, which produces no frames to read.- *- * This is the other half of the idle number. 90 seconds of silence means- * one thing in `tool_executing` (a build is running) and quite another in- * `running` (the model has stopped mid-answer), and a caller deciding- * whether to cancel needs both.- */- getActivity: () => string | null;- /**- * Drain any partially-received line into the byte count, tail, and response- * file. A no-op under `"print"` capture, which counts raw bytes as they- * arrive.- *- * Required by the TIMEOUT path. The stream-json capture holds an unterminated- * line back until its newline arrives, so a child that wrote a partial line- * and then hung would be reported as 0 B — destroying the one diagnostic the- * timeout handler exists to provide. Deliberately does NOT close the write- * stream: that would fire `finish()` while the status is still RUNNING and- * race the run to COMPLETED.- */- flushPartial: () => void;+ /** D19: team has no answering verb, so a slot blocked on a question can never finish. */+ function teamOnBlocked(e: SlotEntry, b: PaneBlock): FinalVerdict {+ const index = (e.session?.snapshot().turnsCompleted ?? 0) + 1;+ writeResponse(e, e.session?.turnAnswer(index) ?? "");+ return { state: "FAILED", reason: "blocked", detail: b.text };}- const runtimes: Map<string, ModelRuntime> = new Map();- /**- * Slots the caller asked to stop, recorded BEFORE the signal goes out.- *- * The exit handler cannot otherwise tell a deliberate stop from a crash — both- * arrive as a non-zero exit — and filing a cancellation as `nonzero_exit`- * would put a fault in the permanent record for a decision the caller made.- */- const cancelledSlots = new Set<string>();-- // SIGINT handler: kill all child processes on Ctrl+C.- //- // This is now LOAD-BEARING rather than a convenience. Children are spawned- // detached, so they are no longer in the terminal's foreground process group- // and Ctrl+C does not reach them on its own. Signal each group directly.- //- // Synchronous by necessity — `process.exit` runs immediately after, so there- // is no opportunity to await a SIGKILL escalation. SIGTERM to the group is- // enough here because the launcher now forwards it (see bin/claudish.cjs).- const sigintHandler = () => {- for (const [, proc] of processes) {- signalProcessTree(proc, "SIGTERM");- }- process.exit(1);- };- process.on("SIGINT", sigintHandler);+ function accountingFields(a: Accounting): Partial<ModelStatus> {+ return {+ provider: a.provider,+ tokensIn: a.tokensIn,+ tokensOut: a.tokensOut,+ costUsd: a.costUsd,+ toolCalls: a.toolCalls,+ };+ }- const completionPromises: Promise<void>[] = [];+ function liveFields(e: SlotEntry, snap: PaneSnapshot): Partial<ModelStatus> {+ return {+ state: snap.state,+ pane: snap.paneId || null,+ captureSource: snap.captureSource,+ turnSource: snap.turnSource,+ lastActivityAt: snap.lastActivityAt,+ turnsCompleted: snap.turnsCompleted,+ claudeCodeVersion: snap.claudeCodeVersion,+ anomalies: notableAnomalies(snap),+ ...accountingFields(refreshAccounting(e, snap)),+ };+ }- // The spawn loop has its own catch because NOTHING after it exists yet when- // it throws: the ticker, the registry entry and `done` are all built below.- // A synchronous `spawn()` error or a failed `status.json` write for slot N- // would otherwise leave slots 1..N-1 running and billing with no `done`, no- // registry entry to cancel them through, and the SIGINT handler installed.- try {- for (const [anonId, entry] of Object.entries(manifest.models)) {- const outputPath = join(sessionPath, `response-${anonId}.md`);- const errorLogPath = join(sessionPath, "errors", `${anonId}.log`);- const upstreamErrorLogPath = join(sessionPath, "errors", `${anonId}-upstream.jsonl`);-- // Spawn with the parent-resolved explicit spec when there is one, so the- // child skips routing entirely and finds its key in the inherited env.- // ABSENT from the map is not an error — it means "spawn it bare", which is- // exactly the pre-pinning behaviour. The manifest keeps `entry.model` (the- // user's string) as the run's identity; only argv changes.- const spawnModel = spawnPlan.pinned.get(entry.model) ?? entry.model;+ /** The fields a slot gets once, when it turns terminal (and its error log on failure). */+ function terminalFields(e: SlotEntry, snap: PaneSnapshot): Partial<ModelStatus> {+ const index = Math.max(1, snap.turnsCompleted);+ const answer = e.answer ?? writeResponse(e, e.session?.turnAnswer(index) ?? "");+ const anomalies = [+ ...notableAnomalies(snap),+ ...(snap.state === "COMPLETED" && e.stopReason === "max_tokens" ? [TRUNCATION_NOTE] : []),+ ];+ const base: Partial<ModelStatus> = {+ completedAt: snap.endedAt ?? new Date().toISOString(),+ exitCode: snap.exitCode,+ outputSize: Buffer.byteLength(answer, "utf8"),+ stopReason: e.stopReason,+ anomalies,+ };+ if (snap.state === "COMPLETED") return { ...base, error: undefined };+ return { ...base, error: slotError(e, snap, answer) };+ }- // CRITICAL FIX: do NOT use -p flag (-p means --profile in claudish)- // --stdin triggers non-interactive single-shot mode- //- // ORDER IS LOAD-BEARING when recovery is on. claudish consumes --verbose as- // its OWN log-verbosity flag (it sets quiet=false) and separately forwards a- // copy to the child `claude`, which hard-errors on- // `--print --output-format stream-json` without it. Putting --verbose BEFORE- // --quiet gets the forward while letting --quiet win claudish's own- // verbosity — reversed, every child would narrate itself onto stderr.- // `--output-format stream-json` is an unknown flag to claudish and passes- // through to `claude` with its value.- const args = [- "--model",- spawnModel,- "-y",- "--stdin",- ...(captureMode === "stream-json"- ? ["--verbose", "--quiet", "--output-format", "stream-json"]- : ["--quiet"]),- ...(opts.claudeFlags ?? []),- ];-- updateModelStatus(anonId, {- state: "RUNNING",- startedAt: new Date().toISOString(),- });+ /** The `ModelError` of a slot that did not complete; writes its error log first. */+ function slotError(e: SlotEntry, snap: PaneSnapshot, answer: string): ModelError {+ const reason: FailureReason =+ snap.reason ?? (snap.state === "CANCELLED" ? "cancelled" : "child_exited");+ const detail = reason === "cancelled" ? CANCELLED_DETAIL : (snap.detail ?? reason);+ const errorLogPath = errorLogPathOf(e.id);+ persistErrorLog(errorLogPath, `${snap.state}: ${reason}: ${detail}`, [+ ["final screen", snap.screenTail],+ [+ "exit code",+ snap.exitCode === null ? "(none: claudish ended the pane)" : String(snap.exitCode),+ ],+ ["anomalies", snap.anomalies.join("\n")],+ ["answer (tail)", answer.slice(-STDOUT_TAIL_LIMIT)],+ ]);+ const upstream = upstreamLogOf(e.id);+ return {+ model: e.id,+ command: commandOf(e),+ reason,+ detail,+ screenSnippet: snap.screenTail+ ? snippetHeadAndTail(redactSecrets(snap.screenTail))+ : undefined,+ answerSnippet: answer ? snippetHeadAndTail(redactSecrets(answer)) : undefined,+ errorLogPath,+ // Only when the child actually wrote one. Naming a file that does not exist+ // sends a reader after evidence that was never captured.+ upstreamErrorLogPath: existsSync(upstream) ? upstream : undefined,+ workDir: path,+ };+ }- // See session-manager: resolved so a harness can spawn the tree under test- // instead of the installed binary. Unset in production → plain "claudish".- const teamSpawnTarget = resolveClaudishSpawn();- const proc = (opts.spawnChild ?? spawn)(- teamSpawnTarget.command,- [...teamSpawnTarget.prefixArgs, ...args],- {- stdio: ["pipe", "pipe", "pipe"],- shell: false,- // Each child leads its OWN process group, so we can signal the whole- // subtree with `process.kill(-pid)`.- //- // `claudish` is a tree, not a process: the bin is a Node launcher that- // runs the real CLI under Bun, which spawns `claude`, which spawns its- // own tools and MCP servers. Signalling the direct child alone reaches- // only the launcher — measured 2026-08-15, both SIGTERM and SIGKILL to- // the pid left the Bun process alive and still holding the write end of- // the pipe feeding `response-<id>.md`, which is how a run declared- // TIMEOUT with 0 B gained a complete 40,699 B answer six minutes later.- // Only the group kill was clean.- //- // Trade-off: a detached child no longer receives the terminal's Ctrl+C- // (that goes to the foreground group, which the child has just left), so- // the SIGINT handler below MUST kill the groups explicitly. It also means- // an orchestrator that dies without running its handlers leaves children- // behind — the same exposure as before this change, not a new one.- detached: KILL_PROCESS_GROUP,- env: {- ...process.env,- // Point this child's token tracker at a path WE choose, so its- // tokens/cost can be attributed back to this model. Without this the- // child writes to tokens-<its-own-port>.json and nothing links the two.- [ENV.CLAUDISH_TOKEN_FILE]: tokenFileFor(sessionPath, anonId),- // Un-no-op `captureUpstreamError` (handlers/composed-handler.ts), which- // is opt-in on this env var and was therefore a guaranteed no-op for- // every team child. Its own comment says what that costs: `log()` only- // persists under `--debug`, so the upstream body that separates a- // retryable rate limit from a hard quota wall is gone the moment it has- // been classified — and a run that already failed cannot be re-run with- // a flag. The channel has set this all along; team never did.- //- // Per SLOT, unconditionally: the records carry no slot id, so one shared- // path would interleave every model in the run into an unattributable- // file.- [UPSTREAM_ERROR_LOG_ENV]: upstreamErrorLogPath,- },- }- );- // Tracked the moment it exists, so a throw later in this iteration still- // reaches it through the loop's catch below.- processes.set(anonId, proc);-- /**- * When this child last wrote on either pipe.- *- * A SEPARATE listener from the capture below, deliberately. Capture asks- * "is this an answer?" and answers no for a `tool_progress` heartbeat or a- * thinking frame; liveness asks "is anything alive down there?" and those- * same frames answer yes. Conflating the two questions is precisely how the- * old reaper concluded that a compiling child was dead.- */- let lastOutputAt = Date.now();- const stampLiveness = (): void => {- lastOutputAt = Date.now();- };+ /** `onTransition`: every wire-state change, synchronously, before any frame. */+ function onSlotTransition(e: SlotEntry, snap: PaneSnapshot): void {+ if (aborting) return;+ const update = liveFields(e, snap);+ if (isTerminalState(snap.state)) Object.assign(update, terminalFields(e, snap));+ updateModelStatus(e.id, update);+ notifyStatus(e.id);+ if (run) markIfSettled(run);+ }- /**- * One decoder per pipe, never shared.- *- * A `data` chunk ends at the pipe's read boundary, which lands mid-codepoint- * often enough to matter: `chunk.toString()` replaces the dangling bytes- * with U+FFFD, so any CJK character or emoji straddling a boundary was- * permanently mangled in `response-<id>.md` and mis-sized in `outputSize`.- * The channel has decoded this way all along; team did not.- */- const stdoutDecoder = newStdioDecoder();- const stderrDecoder = newStdioDecoder();- proc.stdout?.on("data", stampLiveness);- proc.stderr?.on("data", stampLiveness);-- // Count bytes flowing through stdout for accurate outputSize tracking- let byteCount = 0;- // Bounded tail of stdout. Claude Code writes "[API Error: ...]" to stdout- // and still exits 0, so the failure signal is often here rather than on- // stderr. Bounded so a 30 KB answer doesn't get buffered twice.- let stdoutTail = "";-- const outputStream = createWriteStream(outputPath);-- /** See ModelRuntime.flushPartial. Reassigned below when recovery is on. */- let flushPartial: () => void = () => {};-- /**- * The stream-json supervisor for this slot, or null under `"print"`.- *- * `team` used to drive `createAssistantTextCapture()` directly and hand-roll- * everything around it. The channel wraps that SAME capture in- * `StreamJsonReducer` and adds what team was missing: a state machine that- * knows the difference between thinking and running a tool, and `sawResult`- * — the child's own terminal `result` frame, which is a real completion- * oracle where exit 0 is not (`claude -p` exits 0 on API errors too).- *- * Two implementations of one job existed because this file predates the- * reducer by four months. There is now one parser; this is the caller that- * moved onto it.- */- let reducer: StreamJsonReducer | null = null;-- if (captureMode === "print") {- // Legacy path: whatever `claude -p` printed, byte for byte.- proc.stdout?.on("data", (chunk: Buffer) => {- byteCount += chunk.length;- stdoutTail = (stdoutTail + decodeChunk(stdoutDecoder, chunk)).slice(-STDOUT_TAIL_LIMIT);- });- // Stream stdout to disk via pipe — no memory buffering- proc.stdout?.pipe(outputStream);- } else {- // Recovery path. The child's stdout is a stream-json event log, so the- // ANSWER has to be extracted from it rather than piped through.- //- // byteCount and stdoutTail are deliberately fed the RECOVERED prose, not- // the raw JSON. Every downstream consumer — the empty check, the- // minOutputBytes threshold, the [API Error:] match, the reported- // outputSize — is asking about the answer, and raw JSON bytes would- // inflate all of them (an empty answer wrapped in events is still- // kilobytes). Feeding recovered prose keeps `classifyRunOutput`- // completely unaware that the wire format changed.- const slotReducer = new StreamJsonReducer({- sessionId: anonId,- // 0 disables the reducer's stall watchdog. That watchdog ANNOUNCES- // silence; team publishes the number through `teamSlotIdleSeconds` and- // leaves the verdict to the caller, so a second opinion on the same- // question would only be noise. It also means no timer is armed here.- stallSeconds: 0,- // Preserve anything not positively recognised. `response-<id>.md` is the- // only place a reader sees what this child printed, and discarding a- // real answer is the failure this file has already been burned by —- // see ai-docs/architecture/team-capture.md.- keepUnrecognizedJson: true,- // State changes are read on demand via `getActivity`, not pushed. Team- // already has its own status file and progress ticker; routing reducer- // transitions into a second notification path would duplicate it.- callback: () => {},- // stdin is written and ended right after spawn (below), so a `result`- // is always the end of the slot's work: `finishing` until it exits,- // never `waiting_for_input`.- onResult: () => "stdin-closed",- });- reducer = slotReducer;-- const absorb = (text: string): void => {- if (text.length === 0) return;- byteCount += Buffer.byteLength(text);- stdoutTail = (stdoutTail + text).slice(-STDOUT_TAIL_LIMIT);- outputStream.write(text);- };-- // `feed` returns exactly what `capture.write` returned — the recovered- // prose for this chunk — so every downstream consumer of `byteCount` and- // `stdoutTail` is unaffected by the swap.- proc.stdout?.on("data", (chunk: Buffer) =>- absorb(slotReducer.feed(decodeChunk(stdoutDecoder, chunk)))- );-- // `end()` is idempotent, so a caller draining early does not disturb the- // normal finalisation below.- flushPartial = () => absorb(slotReducer.end());-- // The write stream is ours to close now that nothing pipes into it, and- // `finish()` hangs off its "close". Both events are wired because "end"- // does not fire on a destroyed stream (a killed child), and a run that- // never resolves is worse than one that resolves empty.- let captureFinalized = false;- const finalizeCapture = (): void => {- if (captureFinalized) return;- captureFinalized = true;- absorb(slotReducer.end());- // NOT disposed here: `finish()` decides the slot's outcome later, off- // outputStream "close", and a disposed reducer ignores `settle()`. It- // settles and disposes the reducer there, once.- outputStream.end();- };- proc.stdout?.on("end", finalizeCapture);- proc.stdout?.on("close", finalizeCapture);- }+ /** A slot whose pane never spawned: FAILED `pane_lost` with the message; siblings continue. */+ function failNeverSpawned(e: SlotEntry, err: unknown): void {+ const msg = err instanceof Error ? err.message : String(err);+ const errorLogPath = errorLogPathOf(e.id);+ writeResponse(e, "");+ persistErrorLog(errorLogPath, `FAILED: pane_lost: ${msg}`, [["start", msg]]);+ updateModelStatus(e.id, {+ state: "FAILED",+ completedAt: new Date().toISOString(),+ outputSize: 0,+ pane: null,+ error: {+ model: e.id,+ command: commandOf(e),+ reason: "pane_lost",+ detail: `the pane never started: ${msg}`,+ errorLogPath,+ workDir: path,+ },+ });+ notifyStatus(e.id);+ }- // Collect stderr for error logging- let stderr = "";- proc.stderr?.on("data", (chunk: Buffer) => {- stderr += decodeChunk(stderrDecoder, chunk);- });+ const cwd = process.cwd();+ const projects = projectsDir(parentEnv);- const command = `claudish ${args.join(" ")}`;- runtimes.set(anonId, {- command,- errorLogPath,- getStderr: () => stderr,- getStdoutTail: () => stdoutTail,- getByteCount: () => byteCount,- // The raw-pipe stamp, not `reducer.idleMs`. The reducer's clock advances- // per complete LINE, so a child writing one long line slowly would look- // quiet; this one sees every byte, on both pipes. Broadest definition of- // "still alive", which is the question being asked.- getIdleMs: () => Math.max(0, Date.now() - lastOutputAt),- getActivity: () => reducer?.state ?? null,- flushPartial: () => flushPartial(),+ async function startSlot(e: SlotEntry, uuid: string, transcriptPath: string): Promise<void> {+ let session: PaneSession;+ try {+ session = await startPaneSession({+ kind: "t",+ label: e.id,+ callerFlags: claudeFlags,+ spawnModel: e.spawnModel ?? e.model,+ cwd,+ sessionUuid: uuid,+ transcriptPath,+ slotEnv: {+ // Point this child's token tracker at a path WE choose, so its tokens/cost+ // can be attributed back to this model.+ [ENV.CLAUDISH_TOKEN_FILE]: e.tokenFile,+ // Per SLOT, unconditionally: the records carry no slot id, so one shared+ // path would interleave every model in the run into an unattributable file.+ [UPSTREAM_ERROR_LOG_ENV]: upstreamLogOf(e.id),+ },+ shape: "one-shot",+ initialPrompt: inputContent,+ readAvailable,+ decide: (turn) => teamDecide(e, turn),+ onBlocked: (b) => teamOnBlocked(e, b),+ onTransition: (t) => onSlotTransition(e, t.snap),+ parentEnv,+ ...(opts.bootTimeoutMs !== undefined ? { bootTimeoutMs: opts.bootTimeoutMs } : {}),+ ...(opts.paneTimings ? { timings: opts.paneTimings } : {}),});+ } catch (err) {+ failNeverSpawned(e, err);+ return;+ }+ e.session = session;+ updateModelStatus(e.id, { pane: session.paneId });+ }- // Pipe input to stdin. A slot cancelled (or a child that exits) before it- // drains stdin closes the pipe under a pending write, and Node surfaces- // that as an `error` event on the stream — unhandled, it is an uncaught- // exception in the orchestrator, not the child. EPIPE here means only- // "the reader went away", which the exit/close handlers already report;- // anything else is still worth a log line.- proc.stdin?.on("error", (err: NodeJS.ErrnoException) => {- if (err?.code === "EPIPE") return;- stderr += `[claudish] stdin error for slot ${anonId}: ${err?.message ?? String(err)}\n`;- });- proc.stdin?.write(inputContent);- proc.stdin?.end();-- const completionPromise = new Promise<void>((resolve) => {- let exitCode: number | null = null;- let resolved = false;-- /**- * Settle the reducer to the outcome just recorded, then release it.- *- * Without the settle the reducer stays wherever the stream left it — a- * `result` frame parks it in `finishing` — so an exited slot read as- * still exiting rather than done. Runs only once `state` is final, which is why- * the dispose lives here and not in `finalizeCapture`. No-op under- * `"print"`, which has no reducer.- */- const settleReducer = (): void => {- if (!reducer) return;- const state = statusCache.models[anonId]?.state;- const failed = state === "FAILED" || state === "EMPTY";- reducer.settle(- failed && cancelledSlots.has(anonId)- ? "cancelled"- : state === "COMPLETED"- ? "completed"- : state === "TIMEOUT"- ? "timeout"- : "failed"- );- reducer.dispose();- };-- const finish = () => {- if (resolved) return;- // The timeout handler may have fired between proc "exit" and- // outputStream "close". Don't clobber TIMEOUT — but do RECONCILE.- //- // Reaching here means the stdout pipe has closed, so `response-<id>.md`- // is final and `byteCount` is its true size. A child killed at the- // deadline can still have flushed a complete answer in the window- // between the signal and the pipe closing, and the old code threw that- // away: it recorded whatever byte count existed at KILL time (0 B for a- // `--quiet` child, which emits only at the end) and never looked again.- // The judging phase then scored a real answer as an empty submission.- if (statusCache.models[anonId].state === "TIMEOUT") {- resolved = true;- reconcileTimedOutOutput(anonId, byteCount, stdoutTail, stderr);- // After the reconcile, which can upgrade TIMEOUT to COMPLETED.- settleReducer();- resolve();- return;- }- resolved = true;-- const outputSize = byteCount;-- // A non-zero exit is an outright failure. A zero exit still has to earn- // it: `claude -p` exits 0 on API errors and on background-task- // termination, so exit code alone would file both as success.- const crashed = exitCode !== 0;- const fullOutput = readFullOutputIfNeeded({- crashed,- requirePattern,- outputSize,- outputPath,- });- const degraded = crashed- ? null- : classifyRunOutput({- outputSize,- stdoutTail,- stderr,- minOutputBytes,- requirePattern,- fullOutput,- captureMode,- });-- const failed = crashed || degraded !== null;- const state: ModelState = crashed ? "FAILED" : degraded ? "EMPTY" : "COMPLETED";-- if (failed) {- // A slot the caller stopped exited non-zero, but it did not crash and- // saying so would be a lie in the permanent record. `cancelled` is the- // one failure reason that is not a defect: the caller looked at the- // evidence and decided. Nothing else in claudish can produce it.- const wasCancelled = cancelledSlots.has(anonId);- const reason: FailureReason = wasCancelled- ? "cancelled"- : crashed- ? "nonzero_exit"- : degraded!.reason;- const detail = wasCancelled- ? 'Stopped on the caller\'s instruction via team(mode:"cancel"). ' +- "Whatever the child had written up to that point is in its response file."- : crashed- ? `Child exited with code ${exitCode}.`- : degraded!.detail;-- persistErrorLog(errorLogPath, `${state}: ${detail}`, stderr, stdoutTail);-- updateModelStatus(anonId, {- state,- exitCode: exitCode ?? 1,- completedAt: new Date().toISOString(),- outputSize,- error: {- model: anonId,- command,- reason,- detail,- // Redacted: these land in status.json on disk and are read back- // by anything inspecting the run.- stderrSnippet: stderr ? redactSecrets(stderr).slice(-2000) : undefined,- stdoutSnippet: stdoutTail- ? snippetHeadAndTail(redactSecrets(stdoutTail))- : undefined,- errorLogPath,- // Only when the child actually wrote one. Naming a file that does- // not exist sends a reader after evidence that was never captured.- upstreamErrorLogPath: existsSync(upstreamErrorLogPath)- ? upstreamErrorLogPath- : undefined,- workDir: sessionPath,- },- });- } else {- updateModelStatus(anonId, {- state,- exitCode: exitCode ?? 0,- completedAt: new Date().toISOString(),- outputSize,- error: undefined,- });- }-- // Before the caller's callback, so a throwing consumer cannot skip the- // dispose and leak the reducer's tool-batch timer.- settleReducer();- opts.onStatusChange?.(anonId, statusCache.models[anonId]);- resolve();- };-- // "close" always fires after the stream ends or errors — single resolution point- outputStream.on("close", finish);-- proc.on("exit", (code) => {- const timedOut = statusCache.models[anonId]?.state === "TIMEOUT";-- // On TIMEOUT this handler must NOT settle the promise. "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 and made the later- // "close" a no-op, which is how a complete answer was reported as 0 B- // and judged as an empty submission. Let "close" drive finish(), which- // re-measures. `runModels` bounds the wait, so a pipe that never closes- // degrades to a stale read rather than a hang.- //- // Still guard the error log: persistErrorLog has just written the- // TIMEOUT diagnostics there and a raw stderr dump would erase them.- // Only write a log when there is something worth reading. Every healthy- // child emits Claude Code's `unrecognized_model` line — normal for a- // proxied model — and writing it produced an `errors/NN.log` for runs- // that had no error at all, which is exactly the noise that hides a real- // one. `finish()` still writes the full log on any genuine failure.- if (!timedOut && meaningfulStderr(stderr)) {- // Redacted like every other persistence point — provider stderr can- // echo key material and this file is read by agents.- writeFileSync(errorLogPath, redactSecrets(stderr), "utf-8");- }-- exitCode = code;- // If the stream already closed before exit fired, finish immediately- if (outputStream.destroyed) {- finish();- }- // Otherwise wait for outputStream "close" to call finish()- });+ const slotIds = Object.keys(manifest.models);+ reservePanes(slotIds.length, sockRootFor(parentEnv));+ // Each startSlot call consumes exactly one reservation, whether its pane starts or not.+ let reservationsLeft = slotIds.length;+ const starts: Promise<void>[] = [];++ // The spawn loop has its own catch because NOTHING after it exists yet when it+ // throws: the ticker, the registry entry and `done` are all built below. A failed+ // status.json write for slot N would otherwise leave slots 1..N-1 running and billing+ // with no `done` and no registry entry to cancel them through. A slot's own+ // startPaneSession throw is NOT such a throw: it is that slot's FAILED pane_lost.+ try {+ let i = 0;+ for (const [id, entry] of Object.entries(manifest.models)) {+ if (i++ > 0) await new Promise((r) => setTimeout(r, BOOT_STAGGER_MS));+ // Spawn with the parent-resolved explicit spec when there is one, so the child+ // skips routing entirely and finds its key in the inherited env. ABSENT from the+ // map means "spawn it bare". The manifest keeps `entry.model` (the user's string)+ // as the run's identity; only argv changes.+ const spawnModel = spawnPlan.pinned.get(entry.model) ?? entry.model;+ const tokenFile = tokenFileFor(path, id);+ const provider = resolveProvider({ model: entry.model, spawnModel, tokenFile: null });+ const e: SlotEntry = {+ id,+ model: entry.model,+ spawnModel,+ tokenFile,+ session: null,+ acct: emptyAccounting(provider),+ answer: null,+ stopReason: null,+ };+ entries.set(id, e);+ const uuid = randomUUID();+ // Team children run in the server's cwd, as before; the launcher `cd`s there.+ const transcriptPath = transcriptPathFor(cwd, uuid, projects);+ updateModelStatus(id, {+ state: "STARTING",+ startedAt: new Date().toISOString(),+ completedAt: null,+ exitCode: null,+ outputSize: 0,+ model: entry.model,+ spawnModel,+ provider,+ sessionUuid: uuid,+ transcriptPath,+ pane: null,+ captureSource: null,+ turnSource: "transcript",+ stopReason: null,+ tokensIn: null,+ tokensOut: null,+ costUsd: null,+ toolCalls: 0,+ turnsCompleted: 0,+ lastActivityAt: null,});-- completionPromises.push(completionPromise);+ const start = startSlot(e, uuid, transcriptPath);+ // Observed by the Promise.all below; until then a rejection must not count as+ // unhandled while the loop is still staggering.+ start.catch(() => undefined);+ starts.push(start);+ reservationsLeft--;}+ await Promise.all(starts);} catch (err) {- // Nothing reported as failed to start may keep running or billing: stop- // every slot already spawned, by process group — SIGTERM, then SIGKILL- // after the grace period, as `cancel_session` does — and only then let- // the error out, so the caller's `start-failed` record is true when it- // is written. A slot that traps SIGTERM would otherwise run on. The SIGINT- // handler stays installed while we wait. `onSettled` is NOT called — no run- // started; the caller records the failure.- const graceMs = opts.terminateGraceMs ?? TERMINATE_GRACE_MS;- await Promise.all([...processes.values()].map((proc) => terminateChildTree(proc, graceMs)));- process.off("SIGINT", sigintHandler);+ // Nothing reported as failed to start may keep running or billing: stop every pane+ // already started (§2.10: close_pane, magmux, then SIGTERM and SIGKILL on the+ // verified group) and only then let the ORIGINAL error out, so the caller's+ // `start-failed` record is true when it is written. `onSettled` is NOT called — no+ // run started; the caller records the failure.+ aborting = true;+ await Promise.allSettled(starts);+ const started = [...entries.values()]+ .map((e) => e.session)+ .filter((s): s is PaneSession => s !== null);+ for (const s of started) s.cancel();+ await Promise.all(started.map((s) => s.reaped().catch(() => undefined)));+ releasePaneReservations(reservationsLeft);throw err;}// ── Live progress ─────────────────────────────────────────────────────────- // Children in --quiet print mode emit nothing until they finish, so without a- // poll there is no signal at all between "started" and "done".- //// Two different cadences, deliberately:- // · status.txt — rewritten every poll. It is a file; frequency is free.- // · onProgress — only when the run's state actually CHANGES, plus a slow- // heartbeat. Each frame renders as its own new line in the- // client, so a fixed short tick would bury the transcript- // in near-identical rows (a 15-min run at 5s = ~180 lines).- const runStartedMs = Date.now();+ // · status.json / status.txt — rewritten every poll. Files; frequency is free.+ // · onProgress — only when the run's state actually CHANGES, plus a slow+ // heartbeat. Each frame renders as its own new line in the+ // client, so a fixed short tick would bury the transcript in+ // near-identical rows (a 15-min run at 5s = ~180 lines).const POLL_MS = 2000;const heartbeatMs = (opts.heartbeatSeconds ?? 60) * 1000;@@ -1558,15 +1478,9 @@ export async function startModels(let lastEmitMs = 0;/**- * What "changed" means for emission purposes.- *- * EXCLUDES elapsed time — otherwise every poll differs and the dedupe never- * suppresses anything.- *- * EXCLUDES raw token counts too. Tokens tick continuously while a model- * streams, so keying on them re-creates the spam this dedupe exists to stop.- * Token totals still ride along on whatever frame does get emitted, and the- * heartbeat guarantees they refresh on a quiet run.+ * What "changed" means for emission purposes. EXCLUDES elapsed time and raw token+ * counts: both tick continuously, and keying on them re-creates the spam this dedupe+ * exists to stop. Token totals still ride along on whatever frame does get emitted.*/const stateSignature = (): string =>Object.entries(statusCache.models)@@ -1575,8 +1489,8 @@ export async function startModels(.join("|");const emitProgress = (phase: "running" | "settled" = "running"): void => {- const elapsedSeconds = (Date.now() - runStartedMs) / 1000;- writeStatusFile(sessionPath, manifest, statusCache, { elapsedSeconds });+ const elapsedSeconds = (Date.now() - startMs) / 1000;+ writeStatusFile(path, manifest, statusCache, { elapsedSeconds });if (!opts.onProgress) return;const signature = stateSignature();@@ -1591,7 +1505,7 @@ export async function startModels(try {const models = Object.values(statusCache.models);opts.onProgress({- rendered: renderTeamStatsCompact(sessionPath, manifest, statusCache, { elapsedSeconds }),+ rendered: renderTeamStatsCompact(path, manifest, statusCache, { elapsedSeconds }),phase,allFailed: models.length > 0 && models.every((m) => m.state !== "COMPLETED"),});@@ -1600,43 +1514,72 @@ export async function startModels(}};+ /** Fresh accounting for disk readers (§3.1): every non-terminal slot, one write. */+ const refreshLiveSlots = (): void => {+ let dirty = false;+ for (const e of entries.values()) {+ if (!e.session) continue;+ const snap = e.session.snapshot();+ if (isTerminalState(snap.state)) continue;+ patchModelStatus(e.id, liveFields(e, snap));+ dirty = true;+ }+ if (dirty) {+ try {+ flushStatus();+ } catch {+ // the next tick retries; a state change writes on its own+ }+ }+ };++ // The registry entry exists from here, before the D9 `ready` await, so a run is+ // listable and cancellable once all of its panes exist (§3.2, §20.3).+ run = {+ runId,+ path,+ kind,+ startedAt: new Date(startMs).toISOString(),+ finishedAt: null,+ status: statusCache,+ slots: entries,+ };+ teamRuns.set(runId, run);+ newestRunByPath.set(path, runId);+ pruneRuns();+ markIfSettled(run);+emitProgress(); // one immediately, so status.txt exists from the start- const progressHandle = setInterval(() => emitProgress("running"), POLL_MS);+ const progressHandle = setInterval(() => {+ refreshLiveSlots();+ emitProgress("running");+ }, POLL_MS);// Don't hold the event loop open on the ticker alone.progressHandle.unref?.();- // Settlement runs in the background. Nothing awaits it here — that is the- // whole point of this function — but it must still tear down the ticker, emit- // the terminal frame, and release the SIGINT handler, or a caller that never- // reads `done` leaks all three.- const teamSessionId = basename(sessionPath);-- // Registered BEFORE `done` is built, so a caller that cancels immediately- // finds the run rather than racing its own start.- liveTeamRuns.set(teamSessionId, {- sessionPath,- processes,- idleMsFor: (slotId) => runtimes.get(slotId)?.getIdleMs() ?? null,- activityFor: (slotId) => runtimes.get(slotId)?.getActivity() ?? null,- liveBytesFor: (slotId) => runtimes.get(slotId)?.getByteCount() ?? null,- isRunning: (slotId) => statusCache.models[slotId]?.state === "RUNNING",- cancelledSlots,- });+ // D9: return once every slot has left STARTING. `ready` never rejects: it resolves on+ // any exit from STARTING, terminal included.+ await Promise.all([...entries.values()].map((e) => e.session?.ready ?? Promise.resolve()));+ const liveRun = run;+ // Built last, immediately before the return, and nothing after it can throw: the+ // record's one end (`onSettled`) can therefore never race the handler's start-failed+ // `catch` (§20.3 item 1).const done = (async (): Promise<TeamStatus> => {+ // The caller resumes from `await startModels(...)` before this body runs on, even+ // for a run whose every slot already ended.+ await new Promise((r) => setImmediate(r));try {- await Promise.all(completionPromises);+ await Promise.all([...entries.values()].map((e) => e.session?.terminal ?? Promise.resolve()));} finally {clearInterval(progressHandle);- // Terminal frame. Without this a status-tracking consumer never sees the- // run close — every frame would read "running", including the last one.+ markIfSettled(liveRun);+ if (liveRun.finishedAt === null) liveRun.finishedAt = new Date().toISOString();+ // Terminal frame. Without this a status-tracking consumer never sees the run+ // close — every frame would read "running", including the last one.emitProgress("settled");- process.off("SIGINT", sigintHandler);- // A settled run answers from status.json, not from memory. Dropping the- // entry is also what stops this map growing for the life of the server.- liveTeamRuns.delete(teamSessionId);- // The caller's settle hook, exactly once, after the settled render. Its- // own try, the `onProgress` convention: a consumer can never fail the run.+ // The caller's settle hook, exactly once, after the settled render. Its own try,+ // the `onProgress` convention: a consumer can never fail the run.try {opts.onSettled?.(statusCache);} catch {@@ -1645,19 +1588,17 @@ export async function startModels(}return statusCache;})();-- // A caller that only polls `getStatus` never touches `done`. Without this an- // unobserved rejection would take down the MCP server, which hosts every- // other session too.+ // A caller that only polls never touches `done`. Without this an unobserved rejection+ // would take down the MCP server, which hosts every other session too.done.catch(() => {});return {- teamSessionId,- sessionPath,- // Display model → anonymised slot. The manifest is shuffled for blind- // JUDGING, which protects the judge children reading response-<id>.md- // without a manifest. It was never hidden from the orchestrating caller —- // status.txt has printed model names beside slot ids all along.+ runId,+ teamSessionId: basename(path),+ sessionPath: path,+ // Display model → anonymised slot. The manifest is shuffled for blind JUDGING,+ // which protects the judge children reading response-<id>.md without a manifest.+ // It was never hidden from the orchestrating caller.slots: Object.fromEntries(Object.entries(manifest.models).map(([anonId, entry]) => [entry.model, anonId])),@@ -1666,7 +1607,7 @@ export async function startModels(}/**- * Spawn every model and wait for all of them.+ * Start every model and wait for all of them.** The blocking form of `startModels`, kept for the pipeline modes that are* inherently sequential: `run-and-judge` cannot judge answers that do not exist@@ -1718,7 +1659,15 @@ export async function judgeResponses(mkdirSync(judgePath, { recursive: true });setupSession(judgePath, judgeModels, judgePrompt);- await runModels(judgePath, { claudeFlags: opts.claudeFlags });+ // The judge prompt (rubric + every response) is not a plain line, so it reaches each+ // judge as a task file it Reads; an incomplete read is FAILED prompt_not_read, never a+ // verdict on part of the input.+ await runModels(judgePath, {+ claudeFlags: opts.claudeFlags,+ kind: "judge",+ ...(opts.parentEnv ? { parentEnv: opts.parentEnv } : {}),+ ...(opts.paneTimings ? { paneTimings: opts.paneTimings } : {}),+ });// Parse votes from judge outputsconst votes = parseJudgeVotes(judgePath, Object.keys(responses));@@ -1780,10 +1729,11 @@ export interface TeamRunOutcome {* partway still yields counts.** - `COMPLETED` → ok.- * - `FAILED` / `EMPTY` / `TIMEOUT` whose `error.reason` is `cancelled` →- * cancelled; with any other reason → failed.- * - `PENDING` / `RUNNING` → failed. A settled run has none; in a run that- * failed to start they are the slots never started and the slots just killed.+ * - a terminal row whose `error.reason` is `cancelled` → cancelled (a CANCELLED row+ * always carries it); with any other reason → failed.+ * - every non-terminal row (STARTING, RUNNING, AWAITING_*) → failed. A settled run has+ * none; in a run that failed to start they are the slots never started and the slots+ * just stopped. The magus monitor's heartbeat applies the same rule.** `slots` is the number of entries. `status` is `completed` when at least one* slot is ok (the channel frame's rule), `cancelled` when every slot was@@ -1796,11 +1746,7 @@ export function summarise(status: TeamStatus): TeamRunOutcome {let cancelled = 0;for (const model of models) {if (model?.state === "COMPLETED") ok++;- else if (- model?.error?.reason === "cancelled" &&- model.state !== "PENDING" &&- model.state !== "RUNNING"- ) {+ else if (model?.error?.reason === "cancelled" && TERMINAL_STATES.includes(model.state)) {cancelled++;} else failed++;}diff --git a/packages/cli/src/team-output-classification.test.ts b/packages/cli/src/team-output-classification.test.tsindex eda1c3ca..18507d81 100644--- a/packages/cli/src/team-output-classification.test.ts+++ b/packages/cli/src/team-output-classification.test.ts@@ -1,185 +1,186 @@import { describe, expect, it } from "bun:test";+import type { SettledTurn } from "./pane/index.js";import {DEFAULT_MIN_OUTPUT_BYTES,- STDOUT_TAIL_LIMIT,+ TRUNCATION_NOTE,classifyRunOutput,} from "./team-orchestrator.js";-const CLEAN_LARGE_OUTPUT = "A".repeat(STDOUT_TAIL_LIMIT);+/*+ * `classifyRunOutput` decides a settled pane turn. Its inputs are the turn's ANSWER (the+ * assistant text read from the transcript — for a file-delivered prompt, only the text+ * after the task file was read), the transcript's API-error entry, the stop_reason and+ * the read coverage of the task file. Precedence: api_error (FAILED) → prompt_not_read+ * (FAILED) → refused (EMPTY) → empty_output → min_output_bytes → shape_mismatch LAST.+ */++const CLEAN_LARGE_OUTPUT = "A".repeat(4000);++function delivery(over: Partial<SettledTurn["delivery"]> = {}): SettledTurn["delivery"] {+ return {+ mode: "file",+ linesTotal: 40,+ linesRead: 40,+ complete: true,+ preambleBytes: 0,+ ...over,+ };+}describe("classifyRunOutput", () => {- it("classifies an API error printed to stdout", () => {+ it("classifies a turn that ended in an API error entry as FAILED api_error", () => {const result = classifyRunOutput({- outputSize: 98,- stdoutTail:- "[API Error: server_is_overloaded Our servers are currently overloaded. Please try again later.]",- stderr: "",- minOutputBytes: DEFAULT_MIN_OUTPUT_BYTES,+ answer: "",+ apiError: {+ status: 529,+ text: "API Error: 529 Our servers are currently overloaded. Please try again later.",+ },});+ expect(result?.state).toBe("FAILED");expect(result?.reason).toBe("api_error");- expect(result?.detail).toContain(- "server_is_overloaded Our servers are currently overloaded. Please try again later."- );- });-- it("classifies Claude Code's background-task wait ceiling", () => {- const result = classifyRunOutput({- outputSize: 195,- stdoutTail: "A short preamble that is not a complete model response.",- stderr:- "Background tasks still running after 600s; terminating. " +- "Set CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS=0 to wait indefinitely.",- minOutputBytes: DEFAULT_MIN_OUTPUT_BYTES,- });-- expect(result?.reason).toBe("background_task_ceiling");- expect(result?.detail).toContain("CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS");+ expect(result?.detail).toContain("status 529");+ expect(result?.detail).toContain("Our servers are currently overloaded");});it("classifies output below the configured minimum as empty", () => {const shortOutput = "A".repeat(300);- const result = classifyRunOutput({- outputSize: 300,- stdoutTail: shortOutput,- stderr: "",- minOutputBytes: 500,- });+ const result = classifyRunOutput({ answer: shortOutput, apiError: null, minOutputBytes: 500 });+ expect(result?.state).toBe("EMPTY");expect(result?.reason).toBe("empty_output");- expect(result?.detail).toContain("caller required at least 500 B");+ expect(result?.detail).toContain("at least 500 B");expect(classifyRunOutput({- outputSize: 300,- stdoutTail: shortOutput,- stderr: "",+ answer: shortOutput,+ apiError: null,minOutputBytes: DEFAULT_MIN_OUTPUT_BYTES,})).toBeNull();});it.each([- {- outputSize: 141,- stdoutTail:- "Observability provides visibility into complex system behaviors, enabling rapid diagnosis and resolution of issues before they impact users.",- },- {- outputSize: 96,- stdoutTail:- "Observability matters because it turns opaque failures into diagnosable signals you can act on.",- },- ])(- "accepts the measured $outputSize B regression answer at default",- ({ outputSize, stdoutTail }) => {- expect(- classifyRunOutput({- outputSize,- stdoutTail,- stderr: "",- minOutputBytes: DEFAULT_MIN_OUTPUT_BYTES,- })- ).toBeNull();- }- );+ "Observability provides visibility into complex system behaviors, enabling rapid diagnosis and resolution of issues before they impact users.",+ "Observability matters because it turns opaque failures into diagnosable signals you can act on.",+ ])("accepts a measured short regression answer at default (%#)", (answer) => {+ expect(classifyRunOutput({ answer, apiError: null })).toBeNull();+ });it.each([- { name: "a newline", outputSize: 1, stdoutTail: "\n" },- {- name: "mixed spaces, newline, and tab",- outputSize: Buffer.byteLength(" \n\t "),- stdoutTail: " \n\t ",- },- { name: "zero bytes", outputSize: 0, stdoutTail: "" },- ])("classifies $name as empty at default", ({ outputSize, stdoutTail }) => {- const result = classifyRunOutput({- outputSize,- stdoutTail,- stderr: "",- minOutputBytes: DEFAULT_MIN_OUTPUT_BYTES,- });+ { name: "a newline", answer: "\n" },+ { name: "mixed spaces, newline, and tab", answer: " \n\t " },+ { name: "zero bytes", answer: "" },+ ])("classifies $name as empty at default", ({ answer }) => {+ const result = classifyRunOutput({ answer, apiError: null });+ expect(result?.state).toBe("EMPTY");expect(result?.reason).toBe("empty_output");});it("accepts large clean output", () => {- expect(- classifyRunOutput({- outputSize: Buffer.byteLength(CLEAN_LARGE_OUTPUT),- stdoutTail: CLEAN_LARGE_OUTPUT,- stderr: "",- minOutputBytes: DEFAULT_MIN_OUTPUT_BYTES,- })- ).toBeNull();+ expect(classifyRunOutput({ answer: CLEAN_LARGE_OUTPUT, apiError: null })).toBeNull();});- it("does not treat a large answer with a whitespace-only retained tail as empty", () => {- expect(- classifyRunOutput({- outputSize: 30_000,- stdoutTail: " \n ",- stderr: "",- minOutputBytes: DEFAULT_MIN_OUTPUT_BYTES,- })- ).toBeNull();+ it("measures min_output_bytes in UTF-8 bytes of the answer", () => {+ const answer = "答え".repeat(10); // 60 bytes, 20 chars+ expect(classifyRunOutput({ answer, apiError: null, minOutputBytes: 60 })).toBeNull();+ expect(classifyRunOutput({ answer, apiError: null, minOutputBytes: 61 })?.reason).toBe(+ "empty_output"+ );});- it("classifies whitespace-only output at the retained-tail boundary as empty", () => {+ it("gives an API error precedence over empty output", () => {const result = classifyRunOutput({- outputSize: STDOUT_TAIL_LIMIT,- stdoutTail: " ".repeat(STDOUT_TAIL_LIMIT),- stderr: "",- minOutputBytes: DEFAULT_MIN_OUTPUT_BYTES,+ answer: "",+ apiError: { status: null, text: "request failed" },+ minOutputBytes: 500,});- expect(result?.reason).toBe("empty_output");+ expect(result?.reason).toBe("api_error");});- it("gives an API error precedence over empty output", () => {- const apiError = "[API Error: request failed]";+ it("classifies a refusal as EMPTY refused", () => {const result = classifyRunOutput({- outputSize: Buffer.byteLength(apiError),- stdoutTail: apiError,- stderr: "",- minOutputBytes: 500,+ answer: "I can't help with that.",+ apiError: null,+ stopReason: "refusal",});- expect(result?.reason).toBe("api_error");+ expect(result).toEqual({+ state: "EMPTY",+ reason: "refused",+ detail: expect.stringContaining("refusal"),+ });});- it("gives the background-task ceiling precedence over whitespace-only output", () => {+ it("adds the truncation note to whatever results from a max_tokens turn", () => {const result = classifyRunOutput({- outputSize: 1,- stdoutTail: "\n",- stderr: "Background tasks still running after 600s; terminating.",- minOutputBytes: DEFAULT_MIN_OUTPUT_BYTES,+ answer: "",+ apiError: null,+ stopReason: "max_tokens",});- expect(result?.reason).toBe("background_task_ceiling");+ expect(result?.reason).toBe("empty_output");+ expect(result?.detail).toContain(TRUNCATION_NOTE);+ expect(+ classifyRunOutput({ answer: "complete", apiError: null, stopReason: "max_tokens" })+ ).toBeNull();});+});- it.each([- {- name: "API error in stdout",- stdoutTail: `${CLEAN_LARGE_OUTPUT}[API Error: rate limit exceeded]`,- stderr: "",- reason: "api_error",- },- {- name: "background-task ceiling in stderr",- stdoutTail: CLEAN_LARGE_OUTPUT,- stderr: "Background tasks still running after 600s; terminating.",- reason: "background_task_ceiling",- },- ])("detects $name even when outputSize is large", ({ stdoutTail, stderr, reason }) => {+describe("classifyRunOutput — prompt_not_read", () => {+ it("fails a turn whose task file was never read", () => {const result = classifyRunOutput({- outputSize: 10_000,- stdoutTail,- stderr,- minOutputBytes: DEFAULT_MIN_OUTPUT_BYTES,+ answer: "VERDICT: ok",+ apiError: null,+ promptRead: delivery({ linesRead: 0, complete: false }),});- expect(result?.reason).toBe(reason);+ expect(result?.state).toBe("FAILED");+ expect(result?.reason).toBe("prompt_not_read");+ expect(result?.detail).toContain("never read");+ });++ it("names the lines a partial read returned", () => {+ const result = classifyRunOutput({+ answer: "VERDICT: ok",+ apiError: null,+ promptRead: delivery({ linesTotal: 3400, linesRead: 2000, complete: false }),+ });++ expect(result?.reason).toBe("prompt_not_read");+ expect(result?.detail).toContain("2000 of 3400");+ });++ it("comes after api_error and before refused and the shape contract", () => {+ const unread = delivery({ linesRead: 0, complete: false });+ expect(+ classifyRunOutput({+ answer: "",+ apiError: { status: 500, text: "boom" },+ promptRead: unread,+ })?.reason+ ).toBe("api_error");+ expect(+ classifyRunOutput({+ answer: "no",+ apiError: null,+ stopReason: "refusal",+ promptRead: unread,+ requirePattern: "VERDICT",+ })?.reason+ ).toBe("prompt_not_read");+ });++ it("does not apply to a typed prompt (complete is null) or a fully read file", () => {+ expect(+ classifyRunOutput({+ answer: "ok",+ apiError: null,+ promptRead: delivery({ mode: "typed", linesTotal: null, linesRead: null, complete: null }),+ })+ ).toBeNull();+ expect(classifyRunOutput({ answer: "ok", apiError: null, promptRead: delivery() })).toBeNull();});});@@ -187,8 +188,8 @@ describe("classifyRunOutput — requirePattern", () => {const requirePattern = "```vote";// These are the three real epilogues that replaced complete answers in the- // measured dropout runs. Their byte counts are deliberately derived from the- // captured text so the fixtures cannot drift away from what is classified.+ // measured print-mode dropout runs. A pane turn keeps every assistant message, but+ // an answer that IS only an epilogue still has no vote, and must still be refused.const dropoutFixtures = [{name: "repro4 response-01 from [email protected]",@@ -211,18 +212,12 @@ describe("classifyRunOutput — requirePattern", () => {];it.each(dropoutFixtures)("classifies $name as a shape mismatch", ({ text }) => {- const outputSize = Buffer.byteLength(text);- const result = classifyRunOutput({- outputSize,- stdoutTail: text,- stderr: "",- minOutputBytes: DEFAULT_MIN_OUTPUT_BYTES,- requirePattern,- });+ const result = classifyRunOutput({ answer: text, apiError: null, requirePattern });+ expect(result?.state).toBe("EMPTY");expect(result?.reason).toBe("shape_mismatch");expect(result?.detail).toContain(requirePattern);- expect(result?.detail).toContain(`${outputSize} B`);+ expect(result?.detail).toContain(`${Buffer.byteLength(text)} B`);});it("accepts output that contains the required shape", () => {@@ -234,103 +229,61 @@ describe("classifyRunOutput — requirePattern", () => {"```",].join("\n");- expect(- classifyRunOutput({- outputSize: Buffer.byteLength(text),- stdoutTail: text,- stderr: "",- minOutputBytes: DEFAULT_MIN_OUTPUT_BYTES,- requirePattern,- })- ).toBeNull();+ expect(classifyRunOutput({ answer: text, apiError: null, requirePattern })).toBeNull();});it("leaves shape validation off when requirePattern is omitted", () => {- const text = dropoutFixtures[0].text;+ expect(classifyRunOutput({ answer: dropoutFixtures[0].text, apiError: null })).toBeNull();+ });- expect(- classifyRunOutput({- outputSize: Buffer.byteLength(text),- stdoutTail: text,- stderr: "",- minOutputBytes: DEFAULT_MIN_OUTPUT_BYTES,- })- ).toBeNull();+ it("matches the FULL answer: a marker at the start of a long answer is found", () => {+ const text = `Review complete.\n${requirePattern}\n${"A".repeat(40_000)}`;+ expect(classifyRunOutput({ answer: text, apiError: null, requirePattern })).toBeNull();});- it("matches the complete output when the required marker is outside the bounded tail", () => {- // The answer contract can appear near the start of a multi-KB response. The- // retained tail alone recreates the exact false failure fullOutput prevents.- const text = `Review complete.\n${requirePattern}\n${"A".repeat(STDOUT_TAIL_LIMIT + 100)}`;- const stdoutTail = text.slice(-STDOUT_TAIL_LIMIT);- const opts = {- outputSize: Buffer.byteLength(text),- stdoutTail,- stderr: "",- minOutputBytes: DEFAULT_MIN_OUTPUT_BYTES,- requirePattern,- };-- expect(stdoutTail).not.toContain(requirePattern);- expect(classifyRunOutput({ ...opts, fullOutput: text })).toBeNull();- expect(classifyRunOutput(opts)?.reason).toBe("shape_mismatch");+ it("anchors ^ to the start of the whole answer, with no flags (no m)", () => {+ const answer = "VERDICT: PASS\n\nThe change is sound.";+ expect(classifyRunOutput({ answer, apiError: null, requirePattern: "^VERDICT:" })).toBeNull();++ // A verdict on a later line does not satisfy ^: the pattern has no `m` flag.+ const later = "I read the file.\n\nVERDICT: PASS";+ expect(+ classifyRunOutput({ answer: later, apiError: null, requirePattern: "^VERDICT:" })?.reason+ ).toBe("shape_mismatch");+ // $ anchors to the end of the whole answer.+ expect(classifyRunOutput({ answer, apiError: null, requirePattern: "sound\\.$" })).toBeNull();});it.each([{- name: "an API error in stdout",+ name: "an API error",expectedReason: "api_error",- opts: {- outputSize: Buffer.byteLength("[API Error: server_is_overloaded ...]"),- stdoutTail: "[API Error: server_is_overloaded ...]",- stderr: "",- minOutputBytes: DEFAULT_MIN_OUTPUT_BYTES,- },+ input: { answer: "", apiError: { status: 529, text: "overloaded" } },},{- name: "the background-task ceiling in stderr",- expectedReason: "background_task_ceiling",- opts: {- outputSize: Buffer.byteLength("A real response was started."),- stdoutTail: "A real response was started.",- stderr: "Background tasks still running after 600s; terminating",- minOutputBytes: DEFAULT_MIN_OUTPUT_BYTES,- },+ name: "a refusal",+ expectedReason: "refused",+ input: { answer: "No.", apiError: null, stopReason: "refusal" },},{name: "zero-byte output",expectedReason: "empty_output",- opts: {- outputSize: 0,- stdoutTail: "",- stderr: "",- minOutputBytes: DEFAULT_MIN_OUTPUT_BYTES,- },+ input: { answer: "", apiError: null },},{name: "whitespace-only output",expectedReason: "empty_output",- opts: {- outputSize: Buffer.byteLength("\n"),- stdoutTail: "\n",- stderr: "",- minOutputBytes: DEFAULT_MIN_OUTPUT_BYTES,- },+ input: { answer: "\n", apiError: null },},{name: "output below the caller's minimum",expectedReason: "empty_output",- opts: {- outputSize: Buffer.byteLength("A short but non-empty response."),- stdoutTail: "A short but non-empty response.",- stderr: "",- minOutputBytes: 500,- },+ input: { answer: "A short but non-empty response.", apiError: null, minOutputBytes: 500 },},- ])("gives $name precedence over shape validation", ({ expectedReason, opts }) => {- const result = classifyRunOutput({ ...opts, requirePattern });+ ])("gives $name precedence over shape validation", ({ expectedReason, input }) => {+ const result = classifyRunOutput({ ...input, requirePattern });- expect(result?.reason).toBe(expectedReason);+ expect(result?.reason).toBe(expectedReason as never);expect(result?.reason).not.toBe("shape_mismatch");});@@ -339,41 +292,8 @@ describe("classifyRunOutput — requirePattern", () => {let result: ReturnType<typeof classifyRunOutput> | undefined;expect(() => {- result = classifyRunOutput({- outputSize: Buffer.byteLength(text),- stdoutTail: text,- stderr: "",- minOutputBytes: DEFAULT_MIN_OUTPUT_BYTES,- requirePattern: "(",- });+ result = classifyRunOutput({ answer: text, apiError: null, requirePattern: "(" });}).not.toThrow();expect(result).toBeNull();});-- it.each([- {- outputSize: 141,- stdoutTail:- "Observability provides visibility into complex system behaviors, enabling rapid diagnosis and resolution of issues before they impact users.",- },- {- outputSize: 96,- stdoutTail:- "Observability matters because it turns opaque failures into diagnosable signals you can act on.",- },- ])(- "still accepts the measured $outputSize B answer when requirePattern is omitted",- ({ outputSize, stdoutTail }) => {- // These real short answers exposed the old minimum-size false positive.- // The opt-in shape contract must not recreate that failure by default.- expect(- classifyRunOutput({- outputSize,- stdoutTail,- stderr: "",- minOutputBytes: DEFAULT_MIN_OUTPUT_BYTES,- })- ).toBeNull();- }- );});diff --git a/packages/cli/src/team-result-card.test.ts b/packages/cli/src/team-result-card.test.tsindex 369dd007..2d72965f 100644--- a/packages/cli/src/team-result-card.test.ts+++ b/packages/cli/src/team-result-card.test.ts@@ -1,12 +1,9 @@import { describe, expect, it } from "bun:test";-import { formatTeamResult } from "./mcp-server.js";-import type {- FailureReason,- ModelError,- ModelState,- ModelStatus,- TeamStatus,-} from "./team-orchestrator.js";+import { NEXT_STEP, formatTeamResult } from "./mcp-server.js";+import { FAILURE_REASONS, type FailureReason, type SlotState } from "./pane/index.js";+import type { ModelError, ModelStatus, TeamStatus } from "./team-orchestrator.js";++type ModelState = SlotState;const SESSION_PATH = "/tmp/team-result-card";const STARTED_AT = "2026-07-30T00:00:00.000Z";@@ -18,26 +15,29 @@ function modelStatus(id?: string;outputSize?: number;reason?: FailureReason;- stderrSnippet?: string;- stdoutSnippet?: string;+ screenSnippet?: string;+ answerSnippet?: string;withError?: boolean;+ detail?: string;+ anomalies?: string[];} = {}): ModelStatus {const id = options.id ?? "01";const isCompleted = state === "COMPLETED";- const isFailure = state === "FAILED" || state === "TIMEOUT" || state === "EMPTY";+ const isFailure =+ state === "FAILED" || state === "TIMEOUT" || state === "EMPTY" || state === "CANCELLED";const withError = options.withError ?? isFailure;let error: ModelError | undefined;if (withError) {- const reason = options.reason ?? "nonzero_exit";+ const reason = options.reason ?? "child_exited";error = {model: id,command: `claudish --model test-${id}`,reason,- detail: `diagnostic detail for ${reason}`,- stderrSnippet: options.stderrSnippet,- stdoutSnippet: options.stdoutSnippet,+ detail: options.detail ?? `diagnostic detail for ${reason}`,+ screenSnippet: options.screenSnippet,+ answerSnippet: options.answerSnippet,errorLogPath: `${SESSION_PATH}/errors/${id}.log`,workDir: `${SESSION_PATH}/work/${id}`,};@@ -50,6 +50,7 @@ function modelStatus(completedAt: COMPLETED_AT,outputSize: options.outputSize ?? (isCompleted ? 1024 : 0),error,+ ...(options.anomalies ? { anomalies: options.anomalies } : {}),};}@@ -61,30 +62,30 @@ function status(models: Record<string, ModelStatus>): TeamStatus {}function sixModelStatus(snippetLength: number): TeamStatus {- const stderrSnippet = "E".repeat(snippetLength);- const stdoutSnippet = "O".repeat(snippetLength);+ const screenSnippet = "E".repeat(snippetLength);+ const answerSnippet = "O".repeat(snippetLength);return status({"01": modelStatus("COMPLETED", { id: "01", outputSize: 1200 }),"02": modelStatus("FAILED", {id: "02",- reason: "nonzero_exit",- stderrSnippet,- stdoutSnippet,+ reason: "child_exited",+ screenSnippet,+ answerSnippet,}),"03": modelStatus("COMPLETED", { id: "03", outputSize: 2300 }),"04": modelStatus("TIMEOUT", {id: "04",reason: "timeout",- stderrSnippet,- stdoutSnippet,+ screenSnippet,+ answerSnippet,}),"05": modelStatus("COMPLETED", { id: "05", outputSize: 3400 }),"06": modelStatus("EMPTY", {id: "06",reason: "empty_output",- stderrSnippet,- stdoutSnippet,+ screenSnippet,+ answerSnippet,}),});}@@ -95,24 +96,24 @@ function occurrences(text: string, marker: string): number {describe("formatTeamResult", () => {it("never emits stderr or stdout snippets", () => {- const stderrMarker = "UNIQUE-STDERR-MARKER-7F3A";- const stdoutMarker = "UNIQUE-STDOUT-MARKER-91BC";+ const screenMarker = "UNIQUE-SCREEN-MARKER-7F3A";+ const answerMarker = "UNIQUE-ANSWER-MARKER-91BC";const output = formatTeamResult(status({"01": modelStatus("FAILED", {id: "01",- reason: "nonzero_exit",- stderrSnippet: `before ${stderrMarker} after`,- stdoutSnippet: `before ${stdoutMarker} after`,+ reason: "child_exited",+ screenSnippet: `before ${screenMarker} after`,+ answerSnippet: `before ${answerMarker} after`,}),}),SESSION_PATH);- expect(occurrences(output, stderrMarker)).toBe(0);- expect(occurrences(output, stdoutMarker)).toBe(0);- expect(output).not.toContain("stderrSnippet");- expect(output).not.toContain("stdoutSnippet");+ expect(occurrences(output, screenMarker)).toBe(0);+ expect(occurrences(output, answerMarker)).toBe(0);+ expect(output).not.toContain("screenSnippet");+ expect(output).not.toContain("answerSnippet");});it("stays under 2,500 bytes for six models and three capped failures", () => {@@ -141,55 +142,97 @@ describe("formatTeamResult", () => {expect(output.endsWith("<<<END_TEAM_RESULT>>>")).toBe(true);});- it("counts EMPTY, FAILED, and TIMEOUT as failures", () => {+ it("counts EMPTY, FAILED, TIMEOUT and CANCELLED as failures", () => {const output = formatTeamResult(status({"01": modelStatus("COMPLETED", { id: "01" }),- "02": modelStatus("FAILED", { id: "02", reason: "nonzero_exit" }),+ "02": modelStatus("FAILED", { id: "02", reason: "child_exited" }),"03": modelStatus("TIMEOUT", { id: "03", reason: "timeout" }),"04": modelStatus("EMPTY", { id: "04", reason: "empty_output" }),+ "05": modelStatus("CANCELLED", { id: "05", reason: "cancelled" }),}),SESSION_PATH);const failures = output.split("failures:\n")[1]?.split("\nactions:")[0] ?? "";- expect(output).toContain("status: partial — 1/4 succeeded");+ expect(output).toContain("status: partial — 1/5 succeeded");expect(failures).toContain("02 FAILED");expect(failures).toContain("03 TIMEOUT");expect(failures).toContain("04 EMPTY");+ expect(failures).toContain("05 CANCELLED reason=cancelled");+ });++ it.each([...FAILURE_REASONS])(+ "includes reason, next step, and evidence for %s",+ (reason: FailureReason) => {+ const state: ModelState =+ reason === "timeout"+ ? "TIMEOUT"+ : reason === "cancelled"+ ? "CANCELLED"+ : ["shape_mismatch", "empty_output", "refused"].includes(reason)+ ? "EMPTY"+ : "FAILED";+ const output = formatTeamResult(+ status({ "01": modelStatus(state, { id: "01", reason }) }),+ SESSION_PATH+ );++ expect(output).toContain(`reason=${reason}`);+ expect(output).toContain(`next: ${NEXT_STEP[reason]}`);+ expect(output).toContain(`evidence: ${SESSION_PATH}/errors/01.log`);++ if (reason === "api_error") {+ expect(output).toContain("or@");+ }+ }+ );++ it("has a deterministic next step for every reason in the closed set", () => {+ for (const reason of FAILURE_REASONS) expect(NEXT_STEP[reason]?.length).toBeGreaterThan(10);+ expect(Object.keys(NEXT_STEP).sort()).toEqual([...FAILURE_REASONS].sort());});- it.each([- "nonzero_exit",- "timeout",- "api_error",- "background_task_ceiling",- "empty_output",- "shape_mismatch",- ] as const)("includes reason, next step, and evidence for %s", (reason) => {+ it("lists a blocked slot with the question it stopped on", () => {const output = formatTeamResult(status({- "01": modelStatus(- reason === "timeout" ? "TIMEOUT" : reason === "shape_mismatch" ? "EMPTY" : "FAILED",- {- id: "01",- reason,- }- ),+ "01": modelStatus("FAILED", {+ id: "01",+ reason: "blocked",+ detail: "Which database should the migration target?",+ }),}),SESSION_PATH);- expect(output).toContain(`reason=${reason}`);- expect(output).toMatch(/^\s+next:\s+\S.+$/m);- expect(output).toContain(`evidence: ${SESSION_PATH}/errors/01.log`);+ expect(output).toContain("01 FAILED reason=blocked");+ expect(output).toContain("question: Which database should the migration target?");+ expect(output).toContain("make the prompt self-contained or use create_session");+ });- if (reason === "background_task_ceiling") {- expect(output).toContain("CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS");- }- if (reason === "api_error") {- expect(output).toContain("or@");- }+ it("names an open background shell under a succeeded slot (R3-M5)", () => {+ const output = formatTeamResult(+ status({+ "01": modelStatus("COMPLETED", {+ id: "01",+ anomalies: ["background_shell_open: npm run dev"],+ }),+ }),+ SESSION_PATH+ );++ expect(output).toContain("status: ok — 1/1 succeeded");+ expect(output).toContain("note: background_shell_open: npm run dev");+ });++ it("reads a pre-contract state outside the closed set as FAILED", () => {+ const legacy = {+ ...modelStatus("FAILED", { id: "01" }),+ state: "PENDING",+ } as unknown as ModelStatus;+ const output = formatTeamResult(status({ "01": legacy }), SESSION_PATH);++ expect(output).toContain("01 FAILED");});it("warns that a shape-mismatch answer was not produced and must not become a vote", () => {@@ -250,7 +293,7 @@ describe("formatTeamResult", () => {it("distinguishes all-failed from partial runs", () => {const allFailed = formatTeamResult(status({- "01": modelStatus("FAILED", { id: "01", reason: "nonzero_exit" }),+ "01": modelStatus("FAILED", { id: "01", reason: "child_exited" }),"02": modelStatus("EMPTY", { id: "02", reason: "empty_output" }),}),SESSION_PATH@@ -270,9 +313,9 @@ describe("formatTeamResult", () => {it("sorts model ids regardless of fixture insertion order", () => {const output = formatTeamResult(status({- "03": modelStatus("FAILED", { id: "03", reason: "nonzero_exit" }),- "01": modelStatus("FAILED", { id: "01", reason: "nonzero_exit" }),- "02": modelStatus("FAILED", { id: "02", reason: "nonzero_exit" }),+ "03": modelStatus("FAILED", { id: "03", reason: "child_exited" }),+ "01": modelStatus("FAILED", { id: "01", reason: "child_exited" }),+ "02": modelStatus("FAILED", { id: "02", reason: "child_exited" }),}),SESSION_PATH);diff --git a/packages/cli/src/team-run-mcp.contract.test.ts b/packages/cli/src/team-run-mcp.contract.test.tsindex c0088026..a30f78f6 100644--- a/packages/cli/src/team-run-mcp.contract.test.ts+++ b/packages/cli/src/team-run-mcp.contract.test.ts@@ -3,8 +3,10 @@* Black-box contract tests for the team-run record through the real `team` MCP tool* (design §3.3 "Team record", §3.2 item 3; §8.1 tests 7, 15, 16b, 18, 19).*- * A real claudish MCP server over stdio, every slot the stream-json fake via CLAUDISH_BIN.- * The team directory is inside the server's cwd, in case path validation requires it.+ * 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+ * 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.** INFERRED (adapter `teamCall` in test-helpers/contract-mcp.ts): the `team` tool takes* `mode`, a path, `models` and an input; key names are read from the tool's own inputSchema.@@ -14,7 +16,16 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";import { existsSync, readFileSync } from "node:fs";import { join } from "node:path";-import { McpServer, findField, serverEnv, teamCall } from "./test-helpers/contract-mcp.js";+import {+ MAGMUX_AVAILABLE,+ McpServer,+ NO_MAGMUX_MESSAGE,+ PANE_FAKE_CHILD,+ findField,+ paneOrphans,+ serverEnv,+ teamCall,+} from "./test-helpers/contract-mcp.js";import {TEAM_RECORD_ID_PATTERN,type TempLayout,@@ -33,14 +44,21 @@ let layout: TempLayout;let server: McpServer;let teamDir: string;+if (!MAGMUX_AVAILABLE) console.warn(NO_MAGMUX_MESSAGE);+beforeEach(async () => {layout = makeTempLayout("teammcp");teamDir = join(layout.cwd, "team-run");- server = await McpServer.start({ env: serverEnv(layout), cwd: layout.cwd });+ server = await McpServer.start({+ env: serverEnv(layout, { CLAUDISH_BIN: PANE_FAKE_CHILD }),+ cwd: layout.cwd,+ });});afterEach(async () => {await server.close();+ const report = await paneOrphans(layout);layout.cleanup();+ expect(report).toEqual({ processes: [], files: [] });});async function run(input: string): Promise<string> {@@ -51,105 +69,117 @@ async function run(input: string): Promise<string> {return record as string;}-describe("REQ-17 team(mode:'run') writes a kind:team record and returns its id", () => {- test(- "the result carries monitor_record, and that record's spawn.json is valid and names the run",- async () => {- const record = await run("answer once and exit");- const text = readFileSync(join(layout.sessionsDir, record, "spawn.json"), "utf8");-- expect(record).toMatch(TEAM_RECORD_ID_PATTERN);- expect(spawnRecordViolations(text, record)).toEqual([]);- expect(JSON.parse(text)).toMatchObject({- schema: 1,- kind: "team",- sessionId: record,- teamPath: teamDir,- slots: MODELS.length,- hostPid: process.pid,- mcpPid: server.pid,- });- expect(teamRecordDirs(layout.sessionsDir)).toEqual([record]);- },- T_TEST- );-});--describe("REQ-18/REQ-21 the record of a run that settles at once ends exactly once", () => {- test(- "meta.json is written within 1 s of the run call returning, completed, with every slot ok",- async () => {- const record = await run("answer once and exit");- const returnedAt = Date.now();-- const meta = await waitFor(() => readJson(join(layout.sessionsDir, record, "meta.json")), {- what: "the team record's meta.json",- timeoutMs: 1_000,- });-- expect(Date.now() - returnedAt).toBeLessThanOrEqual(1_000);- expect(meta).toEqual({- kind: "team",- status: "completed",- startedAt: expect.any(String),- completedAt: expect.any(String),- elapsedSeconds: expect.any(Number),- slots: 2,- ok: 2,- failed: 0,- cancelled: 0,- });- expect(entries(join(layout.sessionsDir, record))).toEqual(["meta.json", "spawn.json"]);- },- T_TEST- );-});--describe("REQ-23 only mode 'run' writes a record, and nothing goes under .hosts", () => {- test(- "status and cancel on an existing run add no record; no .hosts directory appears",- async () => {- const record = await run("answer once and exit");- await waitFor(() => readJson(join(layout.sessionsDir, record, "meta.json")), {- what: "the run to settle",- timeoutMs: 10_000,- });-- await teamCall(server, "status", { path: teamDir });- await teamCall(server, "cancel", { path: teamDir });-- expect(teamRecordDirs(layout.sessionsDir)).toEqual([record]);- expect(existsSync(join(layout.sessionsDir, ".hosts"))).toBe(false);- },- T_TEST- );-});--describe("REQ-24 a team slot reads finishing, never waiting_for_input, between its result and its exit", () => {- function activities(json: unknown): string[] {- const bySlot = findField(json, "activity_by_slot");- if (!bySlot || typeof bySlot !== "object") return [];- return Object.values(bySlot as Record<string, unknown>).map(String);+describe.skipIf(!MAGMUX_AVAILABLE)(+ "REQ-17 team(mode:'run') writes a kind:team record and returns its id",+ () => {+ test(+ "the result carries monitor_record, and that record's spawn.json is valid and names the run",+ async () => {+ const record = await run("answer once and exit");+ const text = readFileSync(join(layout.sessionsDir, record, "spawn.json"), "utf8");++ expect(record).toMatch(TEAM_RECORD_ID_PATTERN);+ expect(spawnRecordViolations(text, record)).toEqual([]);+ expect(JSON.parse(text)).toMatchObject({+ schema: 1,+ kind: "team",+ sessionId: record,+ teamPath: teamDir,+ slots: MODELS.length,+ hostPid: process.pid,+ mcpPid: server.pid,+ });+ expect(teamRecordDirs(layout.sessionsDir)).toEqual([record]);+ },+ T_TEST+ );}-- test(- "slots that answer and then linger before exiting report finishing",- async () => {- const record = await run("answer, then linger before exiting @@LINGER@@");- const seen = new Set<string>();-- await waitFor(- async () => {- const status = await teamCall(server, "status", { path: teamDir });- for (const a of activities(status.json)) seen.add(a);- return readJson(join(layout.sessionsDir, record, "meta.json"));- },- { what: "the run to settle", timeoutMs: 15_000, intervalMs: 100 }- );-- expect(seen.has("finishing")).toBe(true);- expect(seen.has("waiting_for_input")).toBe(false);- },- T_TEST- );-});+);++describe.skipIf(!MAGMUX_AVAILABLE)(+ "REQ-18/REQ-21 the record of a run that settles at once ends exactly once",+ () => {+ test(+ "meta.json is written within 1 s of the run call returning, completed, with every slot ok",+ async () => {+ const record = await run("answer once and exit");+ const returnedAt = Date.now();++ const meta = await waitFor(() => readJson(join(layout.sessionsDir, record, "meta.json")), {+ what: "the team record's meta.json",+ timeoutMs: 1_000,+ });++ expect(Date.now() - returnedAt).toBeLessThanOrEqual(1_000);+ expect(meta).toEqual({+ kind: "team",+ status: "completed",+ startedAt: expect.any(String),+ completedAt: expect.any(String),+ elapsedSeconds: expect.any(Number),+ slots: 2,+ ok: 2,+ failed: 0,+ cancelled: 0,+ });+ expect(entries(join(layout.sessionsDir, record))).toEqual(["meta.json", "spawn.json"]);+ },+ T_TEST+ );+ }+);++describe.skipIf(!MAGMUX_AVAILABLE)(+ "REQ-23 only mode 'run' writes a record, and nothing goes under .hosts",+ () => {+ test(+ "status and cancel on an existing run add no record; no .hosts directory appears",+ async () => {+ const record = await run("answer once and exit");+ await waitFor(() => readJson(join(layout.sessionsDir, record, "meta.json")), {+ what: "the run to settle",+ timeoutMs: 10_000,+ });++ await teamCall(server, "status", { path: teamDir });+ await teamCall(server, "cancel", { path: teamDir });++ expect(teamRecordDirs(layout.sessionsDir)).toEqual([record]);+ expect(existsSync(join(layout.sessionsDir, ".hosts"))).toBe(false);+ },+ T_TEST+ );+ }+);++describe.skipIf(!MAGMUX_AVAILABLE)(+ "REQ-24 a team slot reads finishing, never waiting_for_input, between its result and its exit",+ () => {+ function activities(json: unknown): string[] {+ const bySlot = findField(json, "activity_by_slot");+ if (!bySlot || typeof bySlot !== "object") return [];+ return Object.values(bySlot as Record<string, unknown>).map(String);+ }++ test(+ "slots that answer and then linger before exiting report finishing",+ async () => {+ const record = await run("answer, then linger before exiting @@LINGER@@");+ const seen = new Set<string>();++ await waitFor(+ async () => {+ const status = await teamCall(server, "status", { path: teamDir });+ for (const a of activities(status.json)) seen.add(a);+ return readJson(join(layout.sessionsDir, record, "meta.json"));+ },+ { what: "the run to settle", timeoutMs: 15_000, intervalMs: 100 }+ );++ expect(seen.has("finishing")).toBe(true);+ expect(seen.has("waiting_for_input")).toBe(false);+ },+ T_TEST+ );+ }+);diff --git a/packages/cli/src/team-run-settles-once.test.ts b/packages/cli/src/team-run-settles-once.test.tsindex 48c3cb64..18b5f2d1 100644--- a/packages/cli/src/team-run-settles-once.test.ts+++ b/packages/cli/src/team-run-settles-once.test.ts@@ -8,131 +8,143 @@* overwrites the real outcome. These tests reproduce that scenario on the real* `startModels` and `SessionManager.finishTeamRun`:*- * 1. a failed start never calls `onSettled`, however fast its spawned slot- * exits — `done` is built after the spawn loop, so a throwing loop never+ * 1. a failed start never calls `onSettled`, however fast its started slot+ * answers — `done` is built after the spawn loop, so a throwing loop never* builds it;* 2. a run that settles at once calls `onSettled` exactly once, and only after* `startModels` has returned — so the handler's `catch` cannot run for it;* 3. a second `finishTeamRun` for one record never replaces the first.+ *+ * Ported to panes (architecture §20.2): the print-mode `/bin/sh` fake is the pane fake+ * in a real headless magmux, and the spawn throw is a failed status.json write after slot+ * 1's pane started. All three properties are kept.*/import { afterEach, beforeEach, describe, expect, it } from "bun:test";-import { type ChildProcess, spawn } from "node:child_process";import {chmodSync,+ existsSync,mkdirSync,mkdtempSync,readFileSync,+ readdirSync,rmSync,statSync,- writeFileSync,} from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { SessionManager } from "./channel/session-manager.js";-import { type TeamStatus, getStatus, setupSession, startModels } from "./team-orchestrator.js";+import { waitNoOrphans } from "./pane/test-helpers/hermetic-env.js";+import { type TeamStatus, setupSession, startModels } from "./team-orchestrator.js";+import {+ MAGMUX,+ NO_MAGMUX_MESSAGE,+ type PaneTestEnv,+ finishPaneTest,+ makePaneTestEnv,+ paneRunOptions,+ waitUntil,+} from "./test-helpers/team-pane.js";-const spawnPlanner = async () => ({ pinned: new Map<string, string>() });-const delay = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));+if (!MAGMUX) console.warn(NO_MAGMUX_MESSAGE);-/**- * Until the one spawned slot's end is recorded in `status.json`. The slot whose- * spawn threw stays `RUNNING` there: it was marked before the throw.- */-async function waitForSpawnedSlotEnd(sessionPath: string, limitMs = 5_000): Promise<void> {- const deadline = Date.now() + limitMs;- const ended = () =>- Object.values(getStatus(sessionPath).models).some((m) => Boolean(m.completedAt));- while (!ended()) {- if (Date.now() > deadline) throw new Error(`the spawned slot never ended: ${sessionPath}`);- await delay(10);- }-}+const delay = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));let tempRoot: string;-let originalClaudishBin: string | undefined;+let panes: PaneTestEnv;beforeEach(() => {tempRoot = mkdtempSync(join(tmpdir(), "team-run-settles-once-test-"));- originalClaudishBin = process.env.CLAUDISH_BIN;- // A slot that answers and exits at once.- const fake = join(tempRoot, "claudish");- writeFileSync(- fake,- "#!/bin/sh\ncat > /dev/null\necho 'PONG answer from the fake slot'\nexit 0\n"- );- chmodSync(fake, 0o755);- process.env.CLAUDISH_BIN = fake;+ panes = makePaneTestEnv();});-afterEach(() => {- if (originalClaudishBin === undefined) delete process.env.CLAUDISH_BIN;- else process.env.CLAUDISH_BIN = originalClaudishBin;+afterEach(async () => {+ for (const dir of readdirSync(tempRoot)) {+ try {+ chmodSync(join(tempRoot, dir, "status.json"), 0o644);+ } catch {+ // not a team dir+ }+ }rmSync(tempRoot, { recursive: true, force: true });+ const report = await finishPaneTest(panes);+ expect(report).toEqual({ processes: [], files: [] });});describe("team run record settles once", () => {- it("never calls onSettled for a failed start whose spawned slot exits at once", async () => {- const sessionPath = join(tempRoot, "fast-then-throw");- setupSession(sessionPath, ["model-a", "model-b"], "ping");-- let first: ChildProcess | undefined;- let calls = 0;- const spawnChild = ((command: string, args: string[], options: object) => {- calls++;- if (calls === 1) {- first = spawn(command, args, options);- return first;- }- throw new Error("spawn EMFILE");- }) as unknown as typeof spawn;-- let settledCalls = 0;- const error = await startModels(sessionPath, {- captureMode: "print",- spawnPlanner,- spawnChild,- onSettled: () => {- settledCalls++;- },- }).catch((err: unknown) => err);-- expect((error as Error).message).toBe("spawn EMFILE");- expect(first).toBeDefined();- // The first slot's exit and close handlers have run and recorded its end- // — the path that settles a started run — and a stray settle has had time.- await waitForSpawnedSlotEnd(sessionPath);- await delay(300);- expect(settledCalls).toBe(0);- });+ it.skipIf(!MAGMUX)(+ "never calls onSettled for a failed start whose started slot answers at once",+ async () => {+ const sessionPath = join(tempRoot, "fast-then-throw");+ // fake-answer answers the moment its prompt is accepted.+ setupSession(sessionPath, ["fake-answer", "model-b"], "ping");++ let settledCalls = 0;+ const run = startModels(sessionPath, {+ ...paneRunOptions(panes),+ onSettled: () => {+ settledCalls++;+ },+ }).catch((err: unknown) => err);+ // The fault: slot 1's pane record exists, so status.json turns read-only and slot+ // 2's STARTING write throws (was: slot 2's spawn threw EMFILE).+ await waitUntil(+ () => {+ const recs = join(panes.sockRoot, "panes");+ return existsSync(recs) && readdirSync(recs).length > 0;+ },+ "slot 1's pane record",+ 5_000,+ 5+ );+ chmodSync(join(sessionPath, "status.json"), 0o444);+ const error = await run;++ expect((error as NodeJS.ErrnoException).code).toBe("EACCES");+ // The started slot is gone — the path that would settle a started run — and a stray+ // settle has had time.+ expect(await waitNoOrphans({ sockRoot: panes.sockRoot }, 5_000)).toEqual({+ processes: [],+ files: [],+ });+ await delay(300);+ expect(settledCalls).toBe(0);+ },+ 30_000+ );- it("calls onSettled exactly once, after startModels returned, for a run that settles at once", async () => {- const sessionPath = join(tempRoot, "fast");- setupSession(sessionPath, ["model-a", "model-b"], "ping");-- const order: string[] = [];- const settled: TeamStatus[] = [];- const handle = await startModels(sessionPath, {- captureMode: "print",- spawnPlanner,- minOutputBytes: 1,- onSettled: (status) => {- order.push("settled");- settled.push(status);- },- });- order.push("returned");-- await handle.done;- await delay(100);- expect(order).toEqual(["returned", "settled"]);- expect(settled).toHaveLength(1);- // Settled: every slot has an outcome. Which one is not the point here.- for (const model of Object.values(settled[0].models)) {- expect(["PENDING", "RUNNING"]).not.toContain(model.state);- }- });+ it.skipIf(!MAGMUX)(+ "calls onSettled exactly once, after startModels returned, for a run that settles at once",+ async () => {+ const sessionPath = join(tempRoot, "fast");+ setupSession(sessionPath, ["model-a", "model-b"], "ping");++ const order: string[] = [];+ const settled: TeamStatus[] = [];+ const handle = await startModels(sessionPath, {+ ...paneRunOptions(panes),+ minOutputBytes: 1,+ onSettled: (status) => {+ order.push("settled");+ settled.push(status);+ },+ });+ order.push("returned");++ await handle.done;+ await delay(100);+ expect(order).toEqual(["returned", "settled"]);+ expect(settled).toHaveLength(1);+ // Settled: every slot has an outcome. Which one is not the point here.+ for (const model of Object.values(settled[0]?.models ?? {})) {+ expect(["STARTING", "RUNNING", "AWAITING_INPUT", "AWAITING_PERMISSION"]).not.toContain(+ model.state+ );+ }+ },+ 30_000+ );it("keeps the first finishTeamRun outcome when a second call arrives", async () => {const manager = new SessionManager({ hostPid: 1, sessionsDir: join(tempRoot, "sessions") });diff --git a/packages/cli/src/team-run-summary.contract.test.ts b/packages/cli/src/team-run-summary.contract.test.tsindex 9d874ec7..bd081ec9 100644--- a/packages/cli/src/team-run-summary.contract.test.ts+++ b/packages/cli/src/team-run-summary.contract.test.ts@@ -74,6 +74,22 @@ describe("REQ-19 summarise counts every ModelState as the table says", () => {expect(outcome).toEqual({ status: "failed", slots: 2, ok: 0, failed: 2, cancelled: 0 });});++ // Added for the pane migration (§20.2): the closed nine-value set.+ test("CANCELLED with error.reason 'cancelled' counts as cancelled (RB6)", () => {+ const outcome = summarise(status([cancelledSlot("CANCELLED"), { state: S.COMPLETED }]));++ expect(outcome).toEqual({ status: "completed", slots: 2, ok: 1, failed: 0, cancelled: 1 });+ });++ test.each(["AWAITING_INPUT", "AWAITING_PERMISSION"])(+ "%s counts as failed, like every non-terminal state",+ (state) => {+ const outcome = summarise(status([{ state }, cancelledSlot(state)]));++ expect(outcome).toEqual({ status: "failed", slots: 2, ok: 0, failed: 2, cancelled: 0 });+ }+ );});describe("REQ-19 summarise derives the run's status", () => {diff --git a/packages/cli/src/team-start-failure.test.ts b/packages/cli/src/team-start-failure.test.tsindex 028f2f48..86524429 100644--- a/packages/cli/src/team-start-failure.test.ts+++ b/packages/cli/src/team-start-failure.test.ts@@ -1,106 +1,94 @@/*** A team run that fails to START: the spawn loop throws after some slots- * exist. Every slot already spawned must be STOPPED before the error reaches- * the caller — SIGTERM, then SIGKILL after the grace period — so nothing the+ * exist. Every pane already started must be STOPPED before the error reaches+ * the caller — SIGTERM, then SIGKILL on the verified pane group — so nothing the* `team(mode:"run")` handler records as `failed reason=start-failed` keeps* running and billing. A slot that ignores SIGTERM is the case that matters.+ *+ * Ported to panes (architecture §20.2): the EventEmitter child is the pane fake's+ * `ignore_term` scenario in a real headless magmux (it traps SIGTERM and SIGHUP and dies+ * only on SIGKILL), and the spawn throw is a failed status.json write after slot 1's pane+ * started.*/import { afterEach, beforeEach, describe, expect, it } from "bun:test";-import type { ChildProcess, spawn } from "node:child_process";-import { EventEmitter } from "node:events";-import { mkdtempSync, rmSync } from "node:fs";-import { tmpdir } from "node:os";+import { chmodSync, existsSync, readFileSync } from "node:fs";import { join } from "node:path";-import { PassThrough } from "node:stream";-import { getStatus, setupSession, startModels } from "./team-orchestrator.js";+import { readProcessTable } from "./pane/process-identity.js";+import { orphanReport } from "./pane/test-helpers/hermetic-env.js";+import { setupSession, startModels } from "./team-orchestrator.js";+import {+ MAGMUX,+ NO_MAGMUX_MESSAGE,+ type PaneTestEnv,+ finishPaneTest,+ makePaneTestEnv,+ paneRunOptions,+ teamDirOf,+ waitUntil,+} from "./test-helpers/team-pane.js";-const spawnPlanner = async () => ({ pinned: new Map<string, string>() });-const delay = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));+if (!MAGMUX) console.warn(NO_MAGMUX_MESSAGE);-/**- * Until the one spawned slot's end is recorded in `status.json`. The slot whose- * spawn threw stays `RUNNING` there: it was marked before the throw.- */-async function waitForSpawnedSlotEnd(sessionPath: string, limitMs = 5_000): Promise<void> {- const deadline = Date.now() + limitMs;- const ended = () =>- Object.values(getStatus(sessionPath).models).some((m) => Boolean(m.completedAt));- while (!ended()) {- if (Date.now() > deadline) throw new Error(`the spawned slot never ended: ${sessionPath}`);- await delay(10);- }-}--/**- * A child that ignores SIGTERM and dies only on SIGKILL. No pid, so- * `signalProcessTree` never addresses a real process group; `killed` stays- * false so every signal reaches `kill`, as the group kill would in production.- */-class StubbornChild extends EventEmitter {- readonly pid = undefined;- readonly killed = false;- exitCode: number | null = null;- signalCode: NodeJS.Signals | null = null;- readonly stdin = new PassThrough();- readonly stdout = new PassThrough();- readonly stderr = new PassThrough();- readonly signals: string[] = [];-- kill(signal: NodeJS.Signals = "SIGTERM"): boolean {- this.signals.push(signal);- if (signal === "SIGKILL" && this.signalCode === null) {- this.signalCode = "SIGKILL";- this.stdout.end();- this.stderr.end();- this.emit("exit", null, "SIGKILL");- }- return true;- }-}--let tempRoot: string;+let panes: PaneTestEnv;+let sessionPath: string;beforeEach(() => {- tempRoot = mkdtempSync(join(tmpdir(), "team-start-failure-test-"));+ panes = makePaneTestEnv();+ sessionPath = teamDirOf(panes, "stubborn");});-afterEach(() => {- rmSync(tempRoot, { recursive: true, force: true });+afterEach(async () => {+ try {+ chmodSync(join(sessionPath, "status.json"), 0o644);+ } catch {+ // not created+ }+ const report = await finishPaneTest(panes);+ expect(report).toEqual({ processes: [], files: [] });});-describe("team spawn-loop failure", () => {- it("escalates to SIGKILL for a spawned slot that ignores SIGTERM, before rethrowing", async () => {- const sessionPath = join(tempRoot, "stubborn");- setupSession(sessionPath, ["model-a", "model-b"], "ping");-- const stubborn = new StubbornChild();- let calls = 0;- const spawnChild = (() => {- calls++;- if (calls === 1) return stubborn as unknown as ChildProcess;- throw new Error("spawn EAGAIN");- }) as unknown as typeof spawn;+describe.skipIf(!MAGMUX)("team spawn-loop failure", () => {+ it("escalates to SIGKILL for a started pane that ignores SIGTERM, before rethrowing", async () => {+ // Eight slots stagger in over ~2 s, which leaves time for slot 1's child to boot and+ // install its SIGTERM trap before the fault.+ const models = ["fake-ignore_term", ...Array.from({ length: 7 }, (_, i) => `model-${i + 2}`)];+ setupSession(sessionPath, models, "@@HANG@@ hold");+ const marker = join(panes.tmp, "sigterm-marker");let settledCalls = 0;- const error = await startModels(sessionPath, {- captureMode: "print",- spawnPlanner,- spawnChild,- terminateGraceMs: 50,+ const run = startModels(sessionPath, {+ ...paneRunOptions(panes, {}, { CONTRACT_FAKE_SIGTERM_MARKER: marker }),onSettled: () => {settledCalls++;},}).catch((err: unknown) => err);+ await waitUntil(+ () =>+ readProcessTable().some(+ (r) =>+ r.command.includes("--model fake-ignore_term") && r.command.includes(panes.sockRoot)+ ),+ "slot 1's stubborn child",+ 5_000+ );+ await Bun.sleep(600); // its module loads and boot() installs the trap+ // The next slot's STARTING write now throws.+ chmodSync(join(sessionPath, "status.json"), 0o444);+ const error = await run;expect(error).toBeInstanceOf(Error);- expect((error as Error).message).toBe("spawn EAGAIN");- // Stopped BEFORE the error reached us, not after.- expect(stubborn.signals).toEqual(["SIGTERM", "SIGKILL"]);- expect(stubborn.signalCode).toBe("SIGKILL");- // Its close handler records the kill; let it land before the directory goes.- await waitForSpawnedSlotEnd(sessionPath);+ expect((error as NodeJS.ErrnoException).code).toBe("EACCES");+ // Stopped BEFORE the error reached us, not after: nothing of any started pane is left.+ expect(orphanReport({ sockRoot: panes.sockRoot })).toEqual({ processes: [], files: [] });+ // A polite signal came first (the trap recorded it and survived it), and the child is+ // gone anyway: only SIGKILL could have ended it. Measured: magmux's forced close_pane+ // sends the pane SIGHUP and then kills it itself, before the reap's own SIGTERM →+ // SIGKILL group backstop is needed, so the marker shows SIGHUP (SIGTERM when the+ // backstop runs).+ expect(existsSync(marker)).toBe(true);+ expect(readFileSync(marker, "utf8")).toMatch(/^SIG(HUP|TERM)$/m);expect(settledCalls).toBe(0);- });+ }, 30_000);});diff --git a/packages/cli/src/team-stats.ts b/packages/cli/src/team-stats.tsindex 16484484..095c72f2 100644--- a/packages/cli/src/team-stats.ts+++ b/packages/cli/src/team-stats.ts@@ -12,6 +12,8 @@import { existsSync, readFileSync, writeFileSync } from "node:fs";import { join } from "node:path";+// contract.ts directly, not the pane facade: pane/accounting.ts imports this file.+import { isTerminalState } from "./pane/contract.js";import type { ModelStatus, TeamManifest, TeamStatus } from "./team-orchestrator.js";/** Subset of the token file (`token-tracker.ts` writeFile) that we surface. */@@ -110,8 +112,14 @@ function fmtState(state: ModelStatus["state"]): string {return "TIME";case "EMPTY":return "EMPT";- case "PENDING":- return "wait";+ case "STARTING":+ return "boot";+ case "AWAITING_INPUT":+ return "ask ";+ case "AWAITING_PERMISSION":+ return "perm";+ case "CANCELLED":+ return "CANC";default:return "? ";}@@ -160,7 +168,7 @@ export function renderTeamStats(const stats = readTokenStats(sessionPath, id);if (m.state === "COMPLETED") done++;- else if (m.state === "RUNNING" || m.state === "PENDING") running++;+ else if (!isTerminalState(m.state)) running++;else failed++;const inTok = stats?.input_tokens ?? 0;@@ -236,7 +244,7 @@ export function renderTeamStatsCompact(const stats = readTokenStats(sessionPath, id);if (m.state === "COMPLETED") done++;- else if (m.state === "RUNNING" || m.state === "PENDING") running++;+ else if (!isTerminalState(m.state)) running++;else failed++;totalTokens += stats?.total_tokens ?? 0;diff --git a/packages/cli/src/team-status-payload.test.ts b/packages/cli/src/team-status-payload.test.tsindex b4153fbf..e7cbdb35 100644--- a/packages/cli/src/team-status-payload.test.ts+++ b/packages/cli/src/team-status-payload.test.ts@@ -1,6 +1,9 @@import { describe, expect, test } from "bun:test";import { buildTeamStatusPayload, teamStatusNote } from "./mcp-server.js";-import type { ModelStatus, TeamStatus } from "./team-orchestrator.js";+import { CAPABILITIES, type TeamRunRow } from "./pane/index.js";+import { type ModelStatus, type TeamStatus, teamRunRowFromDisk } from "./team-orchestrator.js";++const PATH = "/tmp/team-status-payload-test";function slot(state: ModelStatus["state"], outputSize: number): ModelStatus {return {@@ -12,14 +15,18 @@ function slot(state: ModelStatus["state"], outputSize: number): ModelStatus {};}+function runOf(status: TeamStatus): TeamRunRow {+ return teamRunRowFromDisk(PATH, status);+}+describe("teamStatusNote", () => {test("omits the note for settled runs regardless of liveness", () => {- expect(teamStatusNote({ anyRunning: false, live: false })).toBeUndefined();- expect(teamStatusNote({ anyRunning: false, live: true })).toBeUndefined();+ expect(teamStatusNote({ anyActive: false, live: false })).toBeUndefined();+ expect(teamStatusNote({ anyActive: false, live: true })).toBeUndefined();});- test("names outputSize and all three live fields for running live slots", () => {- const note = teamStatusNote({ anyRunning: true, live: true });+ test("names outputSize and all three live fields for working live slots", () => {+ const note = teamStatusNote({ anyActive: true, live: true });expect(typeof note).toBe("string");expect(note).toContain("outputSize");@@ -29,7 +36,7 @@ describe("teamStatusNote", () => {});test("puts the outputSize trap before the live-field remedy", () => {- const note = teamStatusNote({ anyRunning: true, live: true }) ?? "";+ const note = teamStatusNote({ anyActive: true, live: true }) ?? "";const trapIndex = note.indexOf("outputSize");const remedyIndex = note.indexOf("live_output_bytes_by_slot");@@ -40,13 +47,24 @@ describe("teamStatusNote", () => {});test("warns about outputSize without naming unavailable live fields", () => {- const note = teamStatusNote({ anyRunning: true, live: false });+ const note = teamStatusNote({ anyActive: true, live: false });expect(note).toContain("outputSize");expect(note).not.toContain("live_output_bytes_by_slot");expect(note).not.toContain("idle_seconds_by_slot");expect(note).not.toContain("activity_by_slot");});++ test("tells the caller to cancel a slot whose end-of-turn record is missing (R3-M4)", () => {+ const note = teamStatusNote({ anyActive: true, live: true, endRecordMissing: ["02"] }) ?? "";++ expect(note).toContain("02");+ expect(note).toContain("turn_end_record_missing");+ expect(note).toContain("cancel");+ expect(teamStatusNote({ anyActive: true, live: true }) ?? "").not.toContain(+ "turn_end_record_missing"+ );+ });});describe("buildTeamStatusPayload", () => {@@ -57,10 +75,11 @@ describe("buildTeamStatusPayload", () => {};const payload = buildTeamStatusPayload({status,- sessionPath: "/tmp/team-status-payload-test",+ sessionPath: PATH,idle: { "01": 2 },- activity: { "01": "running" },+ activity: { "01": "Bash" },liveBytes: { "01": 18342 },+ run: runOf(status),});expect(payload.live_output_bytes_by_slot).toEqual({ "01": 18342 });@@ -71,21 +90,42 @@ describe("buildTeamStatusPayload", () => {expect(payload).not.toHaveProperty("summary");});- test("includes a summary and no note when every slot is completed", () => {+ test("keys the note on any non-terminal slot, not only RUNNING", () => {+ for (const state of ["STARTING", "AWAITING_INPUT", "AWAITING_PERMISSION"] as const) {+ const status: TeamStatus = {+ startedAt: "2026-09-09T00:00:00.000Z",+ models: { "01": slot(state, 0), "02": slot("COMPLETED", 10) },+ };+ const payload = buildTeamStatusPayload({+ status,+ sessionPath: PATH,+ idle: {},+ activity: {},+ liveBytes: {},+ run: runOf(status),+ });+ expect(payload).toHaveProperty("note");+ expect(payload).not.toHaveProperty("summary");+ }+ });++ test("includes a summary and no note when every slot is terminal", () => {const status: TeamStatus = {startedAt: "2026-09-09T00:00:00.000Z",- models: { "01": slot("COMPLETED", 18342), "02": slot("COMPLETED", 31112) },+ models: { "01": slot("COMPLETED", 18342), "02": slot("CANCELLED", 0) },};const payload = buildTeamStatusPayload({status,- sessionPath: "/tmp/team-status-payload-test",+ sessionPath: PATH,idle: null,activity: null,liveBytes: null,+ run: runOf(status),});expect(payload).toHaveProperty("summary");expect(typeof payload.summary).toBe("string");+ expect(payload.summary).toContain("status: partial — 1/2 succeeded");expect(payload).not.toHaveProperty("note");});@@ -96,10 +136,11 @@ describe("buildTeamStatusPayload", () => {};const payload = buildTeamStatusPayload({status,- sessionPath: "/tmp/team-status-payload-test",+ sessionPath: PATH,idle: null,activity: null,liveBytes: null,+ run: runOf(status),});expect(payload).toHaveProperty("note");@@ -108,4 +149,70 @@ describe("buildTeamStatusPayload", () => {expect(payload.idle_seconds_by_slot).toBeNull();expect(payload.activity_by_slot).toBeNull();});++ test("adds contract_version, capabilities and the run row (CA-12, §8 B)", () => {+ const status: TeamStatus = {+ startedAt: "2026-09-09T00:00:00.000Z",+ runId: "team-x-abc-123456",+ models: { "01": slot("COMPLETED", 5) },+ };+ const payload = buildTeamStatusPayload({+ status,+ sessionPath: PATH,+ idle: null,+ activity: null,+ liveBytes: null,+ run: runOf(status),+ });++ expect(payload.contract_version).toBe(1);+ expect(payload.capabilities).toEqual([...CAPABILITIES]);+ const run = payload.run as TeamRunRow;+ expect(run.run_id).toBe("team-x-abc-123456");+ expect(run.state).toBe("SETTLED");+ expect(run.outcome).toBe("ok");+ expect(run.slots.map((s) => [s.slot, s.state, s.idle_seconds, s.activity])).toEqual([+ ["01", "COMPLETED", null, null],+ ]);+ });+});++describe("teamRunRowFromDisk", () => {+ test("reads a pre-contract state outside the closed set as FAILED with reason null", () => {+ const status = {+ startedAt: "2026-09-09T00:00:00.000Z",+ models: { "01": { ...slot("COMPLETED", 0), state: "PENDING" } },+ } as unknown as TeamStatus;+ const run = runOf(status);++ expect(run.slots[0]?.state).toBe("FAILED");+ expect(run.slots[0]?.reason).toBeNull();+ });++ test("reports a CANCELLED row's reason and an ACTIVE run with outcome null", () => {+ const status: TeamStatus = {+ startedAt: "2026-09-09T00:00:00.000Z",+ models: {+ "01": {+ ...slot("CANCELLED", 0),+ error: {+ model: "01",+ command: "claudish",+ reason: "cancelled",+ detail: "stopped",+ errorLogPath: `${PATH}/errors/01.log`,+ workDir: PATH,+ },+ },+ "02": slot("RUNNING", 0),+ },+ };+ const run = runOf(status);++ expect(run.state).toBe("ACTIVE");+ expect(run.outcome).toBeNull();+ expect(run.finished_at).toBeNull();+ expect(run.slots[0]?.reason).toBe("cancelled");+ expect(run.slots[1]?.reason).toBeNull();+ });});diff --git a/packages/cli/src/team-stderr-noise.test.ts b/packages/cli/src/team-stderr-noise.test.tsdeleted file mode 100644index 94dd7cc1..00000000--- a/packages/cli/src/team-stderr-noise.test.ts+++ /dev/null@@ -1,38 +0,0 @@-import { describe, expect, it } from "bun:test";-import { meaningfulStderr } from "./team-orchestrator.js";--const BENIGN_LINE =- '[claude-code:unrecognized_model] {"model":"[email protected]","query_source":"sdk"}';--describe("meaningfulStderr", () => {- it("returns empty output for empty and whitespace-only stderr", () => {- expect(meaningfulStderr("")).toBe("");- expect(meaningfulStderr(" \n\t ")).toBe("");- });-- it("strips the real Claude Code unrecognized-model line", () => {- expect(meaningfulStderr(BENIGN_LINE)).toBe("");- });-- it("strips the benign line when it has leading whitespace", () => {- expect(meaningfulStderr(` ${BENIGN_LINE}`)).toBe("");- });-- it("preserves a real provider error verbatim", () => {- const providerError = "Provider error: upstream request timed out";-- expect(meaningfulStderr(providerError)).toBe(providerError);- });-- it("keeps only the real error from mixed stderr", () => {- const providerError = "Provider error: upstream request timed out";-- expect(meaningfulStderr(`${BENIGN_LINE}\n${providerError}`)).toBe(providerError);- });-- it("does not strip prose that merely mentions unrecognized_model", () => {- const providerError = "Provider reported unrecognized_model while handling the request";-- expect(meaningfulStderr(providerError)).toBe(providerError);- });-});diff --git a/packages/cli/src/team-stream-capture.test.ts b/packages/cli/src/team-stream-capture.test.tsindex 7adfd99d..ca5b04fc 100644--- a/packages/cli/src/team-stream-capture.test.ts+++ b/packages/cli/src/team-stream-capture.test.ts@@ -1,7 +1,6 @@import { describe, expect, it } from "bun:test";import { readFileSync } from "node:fs";import { join } from "node:path";-import { TEAM_CAPTURE_ENV_VAR, resolveCaptureMode } from "./team-orchestrator.js";import { createAssistantTextCapture } from "./team-stream-capture.js";interface FixtureEvent {@@ -211,36 +210,3 @@ describe("createAssistantTextCapture — protocol frames are not prose", () => {expect(out).toContain("something-we-have-never-seen");});});--describe("resolveCaptureMode", () => {- it("lets an explicit mode win over the environment", () => {- expect(resolveCaptureMode("stream-json", { [TEAM_CAPTURE_ENV_VAR]: "print" })).toBe(- "stream-json"- );- expect(resolveCaptureMode("print", { [TEAM_CAPTURE_ENV_VAR]: "stream-json" })).toBe("print");- });-- it.each(["print", " PRINT ", "\tPrInT\n"])(- "resolves the case-insensitive environment value %j to print",- (value) => {- expect(resolveCaptureMode(undefined, { [TEAM_CAPTURE_ENV_VAR]: value })).toBe("print");- }- );-- it.each([undefined, "", " ", "stream-json", "typo"])(- "defaults the unset or invalid environment value %j to stream-json",- (value) => {- const env = value === undefined ? {} : { [TEAM_CAPTURE_ENV_VAR]: value };-- expect(resolveCaptureMode(undefined, env)).toBe("stream-json");- }- );-- it("does not throw for garbage in the environment", () => {- const resolveGarbage = () =>- resolveCaptureMode(undefined, { [TEAM_CAPTURE_ENV_VAR]: "definitely-not-a-mode" });-- expect(resolveGarbage).not.toThrow();- expect(resolveGarbage()).toBe("stream-json");- });-});diff --git a/packages/cli/src/team-timeout-repro.test.ts b/packages/cli/src/team-timeout-repro.test.tsdeleted file mode 100644index bb8b3c89..00000000--- a/packages/cli/src/team-timeout-repro.test.ts+++ /dev/null@@ -1,249 +0,0 @@-/**- * Reproduction test for Bug #1: TIMEOUT reported despite successful completion- *- * The race condition: when the timeout handler fires, it checks `!proc.killed`- * to decide which processes to mark as TIMEOUT. But Node.js's `proc.killed` is- * only `true` when the PARENT sent a signal via `.kill()`. A process that exited- * naturally has `proc.killed === false`, so the timeout handler incorrectly- * marks already-completed processes as TIMEOUT.- *- * Strategy: We create a tiny shell script "fake-claudish" that outputs a response- * and exits in ~100ms. We set the team timeout to 1 second. The process finishes- * well within the timeout, but if there's a race between the exit handler and- * the timeout handler (or if the timeout fires after completion but before- * cleanup), the bug manifests.- *- * To force the race: we set a very tight timeout so the completion and timeout- * fire in close succession.- */--import { afterEach, beforeEach, describe, expect, it } from "bun:test";-import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { type ModelState, type ModelStatus, runModels, setupSession } from "./team-orchestrator.js";--// Retries are enabled here because these tests spawn short-lived real subprocesses-// that can lose races under load. They are deliberately not used on expensive-// real-Claude-Code/real-model tests, where a retry costs minutes and starves neighbouring tests.--// ─── Helpers ────────────────────────────────────────────────────────────────--let tempDir: string;-let fakeClaudishDir: string;--function expectModelState(model: string, status: ModelStatus, expected: ModelState): void {- if (status.state !== expected) {- throw new Error(- `${model}: expected state ${expected}, received ${status.state}; ` +- `error.reason=${status.error?.reason ?? "<none>"}; ` +- `error.detail=${status.error?.detail ?? "<none>"}`- );- }- expect(status.state).toBe(expected);-}--function makeFakeClaudish(delayMs = 50): string {- // Create a fake claudish that:- // 1. Reads stdin (the input prompt)- // 2. Waits a bit (simulating model thinking)- // 3. Writes a response to stdout- // 4. Exits 0- const dir = mkdtempSync(join(tmpdir(), "fake-claudish-"));- const script = join(dir, "claudish");- writeFileSync(- script,- `#!/bin/bash-# Read stdin (discard)-cat > /dev/null-# Simulate model thinking-sleep ${(delayMs / 1000).toFixed(3)}-# Write response-echo "This is a complete model response with analysis and recommendations."-echo "The model has finished its work successfully."-exit 0-`,- "utf-8"- );- chmodSync(script, 0o755);- return dir;-}--beforeEach(() => {- tempDir = mkdtempSync(join(tmpdir(), "team-timeout-repro-"));- fakeClaudishDir = makeFakeClaudish(50); // 50ms delay-});--afterEach(() => {- for (const dir of [tempDir, fakeClaudishDir]) {- if (dir && existsSync(dir)) {- rmSync(dir, { recursive: true, force: true });- }- }-});--// ─── Tests ──────────────────────────────────────────────────────────────────--describe("Bug #1: TIMEOUT despite successful completion", () => {- it(- "REPRO: process that completes before timeout should be COMPLETED, not TIMEOUT",- async () => {- // Setup session with 2 "models"- setupSession(tempDir, ["fast-model-a", "fast-model-b"], "Say hello");-- // Run with a generous 5s timeout — processes complete in ~50ms- // Prepend fake claudish to PATH so it's found instead of real one- const originalPath = process.env.PATH;- const originalClaudishBin = process.env.CLAUDISH_BIN;- // CLAUDISH_BIN outranks PATH in resolveClaudishSpawn, so leaving it set would defeat the fake shim.- delete process.env.CLAUDISH_BIN;- process.env.PATH = `${fakeClaudishDir}:${originalPath}`;-- try {- const status = await runModels(tempDir, { minOutputBytes: 0 });-- // Both models should be COMPLETED since they finish well before the 5s timeout- for (const [modelId, model] of Object.entries(status.models)) {- expectModelState(modelId, model, "COMPLETED");- expect(model.exitCode).toBe(0);- expect(model.outputSize).toBeGreaterThan(0);- }- } finally {- process.env.PATH = originalPath;- if (originalClaudishBin === undefined) {- delete process.env.CLAUDISH_BIN;- } else {- process.env.CLAUDISH_BIN = originalClaudishBin;- }- }- },- { retry: 2 }- );-- it(- "REPRO: process that completes just before timeout fires should be COMPLETED",- async () => {- // This is the tighter race: process completes in ~200ms, timeout at 1s- // On a fast machine this should never timeout, but the bug is in how- // the timeout handler checks proc.killed- if (fakeClaudishDir) {- rmSync(fakeClaudishDir, { recursive: true, force: true });- }- fakeClaudishDir = makeFakeClaudish(200); // 200ms delay-- setupSession(tempDir, ["model-a"], "Say hello");-- const originalPath = process.env.PATH;- const originalClaudishBin = process.env.CLAUDISH_BIN;- // CLAUDISH_BIN outranks PATH in resolveClaudishSpawn, so leaving it set would defeat the fake shim.- delete process.env.CLAUDISH_BIN;- process.env.PATH = `${fakeClaudishDir}:${originalPath}`;-- try {- const status = await runModels(tempDir, { minOutputBytes: 0 });-- const model = Object.values(status.models)[0];- expectModelState("model-a", model, "COMPLETED");- expect(model.exitCode).toBe(0);- } finally {- process.env.PATH = originalPath;- if (originalClaudishBin === undefined) {- delete process.env.CLAUDISH_BIN;- } else {- process.env.CLAUDISH_BIN = originalClaudishBin;- }- }- },- { retry: 2 }- );-- it(- "REPRO: Bug #2 — byte counter tracks stdout accurately independent of filesystem",- async () => {- // The original bug: statSync reads file size before stream flush completes,- // reporting fewer bytes than actually written. With small output (~80 bytes),- // flush completes before finish() runs, so statSync would also pass.- //- // Fix: use a LARGE output (64KB, well above Node's 16KB highWaterMark) so- // the pipe buffer can't flush instantly. The byte counter must track data- // events on stdout, not the filesystem state.-- // Create a fake claudish that writes exactly 65536 bytes (64KB)- const largeFakeDir = mkdtempSync(join(tmpdir(), "fake-claudish-large-"));- const script = join(largeFakeDir, "claudish");- writeFileSync(- script,- `#!/bin/bash-cat > /dev/null-# Generate exactly 65536 bytes (64KB) — exceeds default highWaterMark-dd if=/dev/zero bs=1024 count=64 2>/dev/null | tr '\\0' 'A'-exit 0-`,- "utf-8"- );- chmodSync(script, 0o755);-- setupSession(tempDir, ["model-a"], "Say hello");-- const originalPath = process.env.PATH;- const originalClaudishBin = process.env.CLAUDISH_BIN;- // CLAUDISH_BIN outranks PATH in resolveClaudishSpawn, so leaving it set would defeat the fake shim.- delete process.env.CLAUDISH_BIN;- process.env.PATH = `${largeFakeDir}:${originalPath}`;-- try {- const status = await runModels(tempDir, {});-- const model = Object.values(status.models)[0];- expectModelState("model-a", model, "COMPLETED");- // The byte counter must report exactly 65536 bytes — the known amount- // written to stdout. A statSync-based approach would under-report this- // when the write stream hasn't flushed yet.- expect(model.outputSize).toBe(65536);- } finally {- process.env.PATH = originalPath;- if (originalClaudishBin === undefined) {- delete process.env.CLAUDISH_BIN;- } else {- process.env.CLAUDISH_BIN = originalClaudishBin;- }- rmSync(largeFakeDir, { recursive: true, force: true });- }- },- { retry: 2 }- );-});--describe("Bug #3: Session directory overwrite protection", () => {- it("REPRO: setupSession rejects existing session directory", () => {- // First setup succeeds- setupSession(tempDir, ["model-a"], "First run input");-- // Second setup on same dir should throw — manifest.json already exists- expect(() => setupSession(tempDir, ["model-b"], "Second run input")).toThrow(- /Session already exists/- );- });-- it("REPRO: session artifacts are preserved when re-run is rejected", () => {- setupSession(tempDir, ["model-a"], "First run input");-- // Capture original file contents that setupSession actually writes- const originalManifest = readFileSync(join(tempDir, "manifest.json"), "utf-8");- const originalInput = readFileSync(join(tempDir, "input.md"), "utf-8");- const originalStatus = readFileSync(join(tempDir, "status.json"), "utf-8");-- // Re-run attempt should fail- expect(() => setupSession(tempDir, ["model-b"], "DIFFERENT input")).toThrow();-- // All session artifacts must be byte-for-byte unchanged- expect(readFileSync(join(tempDir, "manifest.json"), "utf-8")).toBe(originalManifest);- expect(readFileSync(join(tempDir, "input.md"), "utf-8")).toBe(originalInput);- expect(readFileSync(join(tempDir, "status.json"), "utf-8")).toBe(originalStatus);- });-- it("REPRO: fresh directory works fine", () => {- // First call on a fresh dir should not throw- expect(() => setupSession(tempDir, ["model-a", "model-b"], "Task")).not.toThrow();- });-});diff --git a/packages/cli/src/test-helpers/contract-adapters.ts b/packages/cli/src/test-helpers/contract-adapters.tsindex 9612e88f..90e2d3ac 100644--- a/packages/cli/src/test-helpers/contract-adapters.ts+++ b/packages/cli/src/test-helpers/contract-adapters.ts@@ -9,17 +9,18 @@* documented), `recordTeamRun({ teamPath, slots, parentClaudeSessionId })` and* `finishTeamRun(record, outcome)` (documented by name and argument).* - team-orchestrator: `setupSession` (named, signature not given), `startModels(path, opts)`- * (named), `ModelState` member values, and the `spawnChild` seam's call shape.+ * (named), and the slot state values (`modelStates`). Team slots are panes now; their+ * suites drive the pane fake through `TeamRunOptions.parentEnv` (CLAUDISH_BIN), not a+ * spawn seam.** Every test asserts the SPEC; only these functions bend to the implementation. If a contract* test fails with "ADAPTER:", fix this file, not the test.*/-import { type ChildProcess, spawn as nodeSpawn } from "node:child_process";import * as sessionManagerModule from "../channel/session-manager.js";import * as reducerModule from "../channel/stream-json-reducer.js";import type { TurnEnd } from "../channel/stream-json-reducer.js";+import type { SlotState } from "../pane/index.js";import * as orchestrator from "../team-orchestrator.js";-import { FAKE_CHILD } from "./contract-mcp.js";type AnyRecord = Record<string, unknown>;type Fn = (...args: unknown[]) => unknown;@@ -240,20 +241,22 @@ export function newSessionManager(// team-orchestrator internals// -------------------------------------------------------------------------------------------/** `ModelState` member values; falls back to the member names when it is a type only. */+/**+ * The slot state values the record suites name. `status.json` now carries the contract's+ * closed `SlotState` set, which has no PENDING: a not-yet-started slot is STARTING+ * (`setupSession` writes it), and `summarise` counts it as failed either way (§20.2).+ */export function modelStates(): Record<"COMPLETED" | "FAILED" | "EMPTY" | "TIMEOUT" | "PENDING" | "RUNNING",- string+ SlotState> {- const ms = (orchestrator as unknown as AnyRecord).ModelState as AnyRecord | undefined;- const pick = (k: string) => (ms && typeof ms[k] === "string" ? (ms[k] as string) : k);return {- COMPLETED: pick("COMPLETED"),- FAILED: pick("FAILED"),- EMPTY: pick("EMPTY"),- TIMEOUT: pick("TIMEOUT"),- PENDING: pick("PENDING"),- RUNNING: pick("RUNNING"),+ COMPLETED: "COMPLETED",+ FAILED: "FAILED",+ EMPTY: "EMPTY",+ TIMEOUT: "TIMEOUT",+ PENDING: "STARTING",+ RUNNING: "RUNNING",};}@@ -279,53 +282,3 @@ export async function startModels(dir: string, opts: AnyRecord): Promise<TeamHanthrow new Error("ADAPTER: team-orchestrator does not export startModels");return (await fn(dir, opts)) as TeamHandleLike;}--export interface SpawnSeam {- spawnChild: (...args: unknown[]) => ChildProcess;- calls(): number;- children: ChildProcess[];-}--/**- * A `TeamRunOptions.spawnChild` seam. INFERRED call shape: node's `spawn(command, args, options)`;- * an object-shaped single argument `{ command, args, options }` is also accepted. Whatever the- * orchestrator asks to run, the contract fake runs instead, with the orchestrator's own options- * (stdio, detached, cwd) passed through so its process-group signalling still applies.- *- * `throwOn`: the 1-based call that throws synchronously, like a failed `spawn()`.- * `hang`: every child stays alive until signalled, whatever input it gets.- * `markerFor(n)`: file the n-th child writes when it receives SIGTERM.- */-export function spawnSeam(opts: {- throwOn?: number;- error?: Error;- markerFor?: (n: number) => string;- hang?: boolean;-}): SpawnSeam {- let n = 0;- const children: ChildProcess[] = [];- const spawnChild = (...args: unknown[]): ChildProcess => {- n += 1;- if (opts.throwOn === n) throw opts.error ?? new Error("contract: injected spawn failure");- const [a, b, c] = args;- let options: AnyRecord | undefined;- if (a && typeof a === "object" && !Array.isArray(a))- options = ((a as AnyRecord).options as AnyRecord | undefined) ?? undefined;- else options = (Array.isArray(b) ? c : b) as AnyRecord | undefined;- const baseEnv =- (options?.env as Record<string, string> | undefined) ??- (process.env as Record<string, string>);- const env: Record<string, string> = { ...baseEnv };- if (opts.markerFor) env.CONTRACT_FAKE_SIGTERM_MARKER = opts.markerFor(n);- // The task text reaches a team slot by a route the contract does not name (argument, file or- // stdin), so a slot that must stay alive is told so through its environment instead.- if (opts.hang) env.CONTRACT_FAKE_HANG = "1";- const child = nodeSpawn(process.execPath, [FAKE_CHILD], {- ...(options ?? {}),- env,- } as Parameters<typeof nodeSpawn>[2]);- children.push(child);- return child;- };- return { spawnChild, calls: () => n, children };-}diff --git a/packages/cli/src/test-helpers/contract-mcp.ts b/packages/cli/src/test-helpers/contract-mcp.tsindex 53b1c0ba..222a152a 100644--- a/packages/cli/src/test-helpers/contract-mcp.ts+++ b/packages/cli/src/test-helpers/contract-mcp.ts@@ -8,19 +8,58 @@* "tool adapters" section at the bottom, is the exact argument and result field names of the* claudish tools. Each adapter is marked INFERRED; fix a mismatch there, once.*/-import { chmodSync } from "node:fs";+import { randomBytes } from "node:crypto";+import { chmodSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";+import { findMagmuxBinaryOrNull } from "../launcher/magmux-binary.js";+import {+ type OrphanReport,+ killLeftovers,+ waitNoOrphans,+} from "../pane/test-helpers/hermetic-env.js";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). */+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";export const FAKE_MODEL = "contract-fake-model";+/** Suites that start panes skip with this message when magmux is absent (testing.md). */+export const MAGMUX_AVAILABLE = findMagmuxBinaryOrNull() !== null;+export const NO_MAGMUX_MESSAGE = "magmux not installed — not checked";++/**+ * A short pane root per layout (`/tmp/cpt-<8 hex>`, so socket paths stay < 100 bytes),+ * passed to the server as CLAUDISH_PANE_ROOT: its sweep, its pane limit and the+ * no-orphan check stay inside the test (§20.4).+ */+const paneRoots = new Map<string, string>();+export function paneRootOf(layout: TempLayout): string {+ let root = paneRoots.get(layout.root);+ if (!root) {+ root = `/tmp/cpt-${randomBytes(4).toString("hex")}`;+ paneRoots.set(layout.root, root);+ }+ return root;+}++/** Wait until nothing of the layout's panes remains, then remove the pane root. */+export async function paneOrphans(layout: TempLayout, ms = 10_000): Promise<OrphanReport> {+ const sockRoot = paneRootOf(layout);+ const report = await waitNoOrphans({ sockRoot }, ms);+ killLeftovers({ sockRoot });+ rmSync(sockRoot, { recursive: true, force: true });+ paneRoots.delete(layout.root);+ return report;+}+/*** A server environment built from scratch, so nothing leaks in from the shell that runs the* tests (for example a CLAUDE_CODE_SESSION_ID set because the tests run inside Claude Code).@@ -39,6 +78,17 @@ export function serverEnv(CLAUDISH_BIN: FAKE_CHILD,CLAUDE_CONFIG_DIR: layout.configDir,NO_COLOR: "1",+ // The hermetic keys of makePaneTestEnv: a pane child built from this env reads no+ // real config, keychain or 1Password, and its pane root is the test's own.+ ZDOTDIR: layout.home,+ SHELL: "/bin/zsh",+ USER: process.env.USER ?? "test",+ LANG: "en_US.UTF-8",+ CLAUDISH_DISABLE_KEYCHAIN: "1",+ CLAUDISH_DISABLE_OP: "1",+ CLAUDISH_DISABLE_CATALOG_WARM: "1",+ CLAUDISH_NO_PREDEFINED_ENDPOINTS: "1",+ CLAUDISH_PANE_ROOT: paneRootOf(layout),};for (const [key, value] of Object.entries(extra)) {if (value === undefined) delete env[key];diff --git a/packages/cli/src/test-helpers/team-pane.ts b/packages/cli/src/test-helpers/team-pane.tsnew file mode 100644index 00000000..992ef5a0--- /dev/null+++ b/packages/cli/src/test-helpers/team-pane.ts@@ -0,0 +1,65 @@+/**+ * Shared set-up for team tests that start real panes (architecture §12.1). Test-only.+ *+ * Every pane is the fake interactive child (`CLAUDISH_BIN`) inside a real headless+ * magmux, built from a hermetic environment passed as `parentEnv` (X-M9) — the test+ * process's own `process.env` is never mutated. `sockRoot` is per test, so the+ * no-orphan check and the startup sweep stay inside it.+ */++import { join } from "node:path";+import {+ MAGMUX,+ NO_MAGMUX_MESSAGE,+ type OrphanReport,+ type PaneTestEnv,+ killLeftovers,+ makePaneTestEnv,+ waitNoOrphans,+} from "../pane/test-helpers/hermetic-env.js";+import type { TeamRunOptions } from "../team-orchestrator.js";++export { MAGMUX, NO_MAGMUX_MESSAGE, makePaneTestEnv, type PaneTestEnv };++/** No credential resolution: every model spawns bare. */+export const spawnPlanner = async () => ({ pinned: new Map<string, string>() });++/** Orchestrator options for a hermetic pane run. */+export function paneRunOptions(+ t: PaneTestEnv,+ extra: TeamRunOptions = {},+ env: Record<string, string> = {}+): TeamRunOptions {+ return {+ parentEnv: { ...t.env, ...env },+ spawnPlanner,+ paneTimings: { replStableMs: 200 },+ ...extra,+ };+}++/** A team session directory inside the test's temp dir. */+export function teamDirOf(t: PaneTestEnv, name = "team"): string {+ return join(t.tmp, name);+}++/** Wait for every process and file of this test's panes to be gone, then clean up. */+export async function finishPaneTest(t: PaneTestEnv, ms = 10_000): Promise<OrphanReport> {+ const report = await waitNoOrphans({ sockRoot: t.sockRoot }, ms);+ killLeftovers({ sockRoot: t.sockRoot });+ t.cleanup();+ return report;+}++export async function waitUntil(+ pred: () => boolean,+ what: string,+ ms = 10_000,+ intervalMs = 25+): Promise<void> {+ const end = Date.now() + ms;+ while (!pred()) {+ if (Date.now() > end) throw new Error(`timed out waiting for ${what}`);+ await Bun.sleep(intervalMs);+ }+}