Skip to content

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

docs(team): describe team slots as panes in team-lifecycle and capture

Jack Rudenkod4a4eb3975ea
diff --git a/ai-docs/architecture/team-capture.md b/ai-docs/architecture/team-capture.md
index 520499c8..a24bf62e 100644
--- a/ai-docs/architecture/team-capture.md
+++ b/ai-docs/architecture/team-capture.md
@@ -1,9 +1,14 @@
-> Why exit 0 proves nothing under `claude -p`, and the stream-json recovery that fixed it.
+> Why exit 0 proves nothing under `claude -p`, why `require_pattern` exists, and how a team slot's answer is now read from the transcript.
>
> Extracted from `CLAUDE.md` (v7.64.0). Indexed in [`README.md`](./README.md).
# The `team` success oracle — why exit 0 proves nothing
+Team slots are no longer print-mode children: each is an interactive Claude Code in a headless
+magmux pane, and its answer comes from the transcript ([`pane-session.md`](pane-session.md)). The
+print-mode measurement below is kept because it is why `require_pattern` exists, and why the answer
+is every assistant message of the turn rather than the last one.
+
`claude -p` in text output mode emits **ONLY the final assistant message**. Any turn the child takes AFTER writing its answer replaces that answer on the captured surface. Isolated proof, no claudish anywhere in the path:
```
@@ -22,44 +27,31 @@ Measured on claudish's `team`, deterministic 2/2 on the first attempt:
Both surviving texts referred to "the review and vote above" — a review that is not on disk. The originally reported incident (236 B from `glm-5.2`) is the same shape. **It is not model-specific and not a claudish bug**: a madbench eval reproduced it on `claude-haiku-4-5` through plain Claude Code, no claudish in the path, 3 consecutive runs. It is a property of the print-mode capture surface.
-The existing classifier could not see it because the epilogue passes every test it ran: exit code 0, no `[API Error: ...]` marker, non-whitespace output. `DEFAULT_MIN_OUTPUT_BYTES` is 0 (opt-in, off).
+The classifier of the time could not see it because the epilogue passes every test it ran: exit code 0, no `[API Error: ...]` marker, non-whitespace output. `DEFAULT_MIN_OUTPUT_BYTES` is 0 (opt-in, off).
**A byte threshold is the wrong instrument, and this is the design point.** An earlier default of 200 produced a 2/2 false-positive rate against real short answers (measured 141 B and 96 B replies, both valid). Length is a guess. A caller that MANDATED an output shape, by contrast, knows what a complete answer looks like — so `require_pattern` is a precise oracle where length is not.
Detection, then:
-- `FailureReason` gains `shape_mismatch`; `classifyRunOutput` gains optional `requirePattern` and `fullOutput`.
-- `runModels` gains `requirePattern` and validates the regex **BEFORE reading the manifest and before spawning anything** — a bad regex discovered later would either waste the whole run or, worse, silently enforce nothing.
+- `FailureReason` has `shape_mismatch`; `classifyRunOutput` takes the caller's `requirePattern`.
+- `startModels` validates the regex **BEFORE reading the manifest and before spawning anything** — a bad regex discovered later would either waste the whole run or, worse, silently enforce nothing.
- The MCP `team` tool exposes `require_pattern` and `min_output_bytes`. The reporter of the original bug had no way to opt in, which is why the option existing internally was not enough.
Two ordering decisions worth keeping:
-1. **The shape check runs LAST**, after the api_error / background-ceiling / empty checks. A run that hit one of those would fail the shape check too, and reporting "no `vote` block" for what is really an API error sends the caller after the wrong problem.
-2. **The pattern is matched against the FULL response, not `stdoutTail`**, because that tail is capped at `STDOUT_TAIL_LIMIT` (4000 B) — a contract whose marker sits near the START of a long answer would otherwise silently never match. Mutation-tested: changing `fullOutput ?? stdoutTail` to `stdoutTail` fails the suite.
-
-## Recovery — the answer is no longer lost (v7.50.0+)
-
-Detection turned a silent wrong verdict into a loud failure, but the generated answer was still gone: the caller re-ran and paid again. Children now spawn with `--output-format stream-json` and `team-stream-capture.ts` concatenates **every** assistant text block, so a post-answer turn costs nothing.
-
-Deterministic A/B, one real captured stream replayed through `runModels` twice:
+1. **The shape check runs LAST**, after `api_error`, `prompt_not_read`, `refused`, the whitespace-only `empty_output` and `min_output_bytes`. A turn that hit one of those would fail the shape check too, and reporting "no `vote` block" for what is really an API error sends the caller after the wrong problem.
+2. **The pattern is matched against the WHOLE answer**, never a bounded tail — a contract whose marker sits near the START of a long answer would otherwise silently never match. `new RegExp(pattern)`, no flags.
-| capture | `response-NN.md` | bytes | verdict |
-|---|---|---|---|
-| `print` (pre-7.50) | `OMEGA_MARKER` | 13 | EMPTY · `shape_mismatch` |
-| `stream-json` (default) | `ALPHA_MARKER` + `OMEGA_MARKER` | 27 | COMPLETED |
+## The answer is every assistant message of the turn, from the transcript
-**Concatenate-everything was chosen over "keep the last substantial message"** because "substantial" is a byte threshold, and `DEFAULT_MIN_OUTPUT_BYTES` is 0 precisely because a 200-byte default recorded two correct short answers (141 B, 96 B) as EMPTY. Intermediate "let me read that file" chatter now lands in the response file; that cost is visible and bounded, whereas a wrong "substantial" verdict discards the answer again silently. `response-NN.md` stays prose either way, so the judge phase and every downstream reader are unaffected.
+Detection turned a silent wrong verdict into a loud failure, but the generated answer was still gone: the caller re-ran and paid again. v7.50.0 recovered it by switching team children to `--output-format stream-json` and concatenating every assistant text block. The pane driver keeps that rule and drops the stream: a slot's answer is **every assistant text block of the turn, in order, joined with a blank line, read from Claude Code's own transcript** — scoped to the turn by the offset claudish recorded before delivering the prompt, and excluding API-error entries. A post-answer turn (a background agent's notification, a Stop-hook re-wake) is part of the same turn and costs nothing.
-Four things that are load-bearing:
+**Concatenate-everything was chosen over "keep the last substantial message"** because "substantial" is a byte threshold, and `DEFAULT_MIN_OUTPUT_BYTES` is 0 precisely because a 200-byte default recorded two correct short answers (141 B, 96 B) as EMPTY. Intermediate "let me read that file" chatter would land in the response file; that cost is visible and bounded, whereas a wrong "substantial" verdict discards the answer again silently.
-- **Argv order.** Children get `--verbose --quiet --output-format stream-json`, and `--verbose` MUST precede `--quiet`. claudish consumes `--verbose` as its own verbosity flag *and* forwards a copy to `claude`, which hard-errors on `--print --output-format stream-json` without it (`cli.ts` ~line 645). Reversed, every child narrates itself onto stderr. Verified live end-to-end: real claudish + `[email protected]` produced stream-json on stdout with exactly one stderr line.
-- **`byteCount` and `stdoutTail` are fed the RECOVERED prose, not the raw JSON.** Every consumer — the empty check, `minOutputBytes`, the `[API Error:` match, the reported `outputSize` — is asking about the answer, and raw JSON inflates all of them (an empty answer wrapped in events is still kilobytes). `classifyRunOutput` never learns the wire format changed.
-- **Unrecognised JSON is passed through, not dropped.** Only a line that is valid JSON *and* carries a `type` in {system, assistant, user, result} is treated as an event. The rule is per-line and never latches: sniffing the format once from the first line would let a single unexpected banner silently disable recovery for a whole run and quietly restore the original bug. Worst case is raw JSON in a response file — ugly, and visibly so.
-- **Passthrough is byte-EXACT; only recovered messages get a synthesised trailing newline.** Not cosmetic: `team-timeout-repro.test.ts` pins a child that writes exactly 65536 bytes with no trailing newline to `outputSize === 65536`, and an added newline made it 65537. Two separators exist for the same reason — a blank line belongs *between messages*, while raw lines are a byte stream that already carries its own newline, and using the message separator for them inserted a blank line between every pair of prose lines.
-- **The `is_error` result event is kept.** A terminal `result` normally just repeats the final assistant message, but on a failed turn it carries the error prose print mode would have put on stdout — which is what `API_ERROR_RE` matches. Dropping it would have silently disabled `api_error` detection.
+One piece of chatter is now cut deliberately, because it is not about the task: when the prompt is delivered as a task file (anything but one plain line), the answer starts AFTER the Read result that returned the last unread line of that file. Narration before the task was read never reaches `response-<slot>.md` or `require_pattern`; its size is reported as `preambleBytes`. A slot whose task file was not fully read is FAILED `prompt_not_read` instead of being judged on an answer to a task it never saw.
-`shape_mismatch` now means something different and says so: under recovery every assistant message was captured, so a missing marker means the model never produced the shape. The old "your answer was discarded" explanation survives only for `captureMode: "print"`. Escape hatch: `CLAUDISH_TEAM_CAPTURE=print` or `TeamRunOptions.captureMode`, kept for diagnosing a capture problem by comparing the two.
+`response-<slot>.md` stays prose, written once, byte-exact, so the judge phase and every downstream reader are unaffected. `shape_mismatch` therefore means one thing: every assistant message of the turn was read, and the model did not produce the shape. The old "your answer was discarded" explanation, the `captureMode: "print"` escape hatch and `CLAUDISH_TEAM_CAPTURE` were removed with print mode.
-Fixture: `test-fixtures/stream-json/haiku-post-answer-turn.jsonl`, a real capture whose `.result` is `OMEGA_MARKER` alone while the stream carries both messages. That one file is the whole bug and the whole fix.
+`max_tokens` is no longer an ending a slot sees as such: Claude Code 2.1.290 auto-continues a `max_tokens` stop on its own and finally writes a synthetic `max_output_tokens` API error, which is FAILED `api_error`. A COMPLETED turn whose recorded `stop_reason` is `max_tokens` carries the note "the answer may be truncated" in its anomalies.
-Unrelated but adjacent: `teamCommand` is exported from `team-cli.ts` and imported nowhere, so `claudish team run` is dead code that silently falls through to catalog search. The `team` surface is **MCP-only**.
+The CLI shares all of this: `claudish team …` and `--team --mode json` call `runModels`, the same code the MCP tool runs. CLI `--grid` is the exception; it still runs print-mode children in a visible magmux for a human to watch.
diff --git a/ai-docs/architecture/team-lifecycle.md b/ai-docs/architecture/team-lifecycle.md
index 2899ca84..e86e8dcb 100644
--- a/ai-docs/architecture/team-lifecycle.md
+++ b/ai-docs/architecture/team-lifecycle.md
@@ -1,8 +1,9 @@
# Team lifecycle — why nothing kills a slot
`team` spawns N Claude Code sessions and collects their answers. This file
-records why it has no deadline, why `run` does not block, and who is allowed to
-terminate a slot.
+records why it has no deadline, why `run` returns early, and who is allowed to
+terminate a slot. Every slot is an interactive Claude Code in its own headless
+magmux pane; the driver and its settle rule are in [`pane-session.md`](pane-session.md).
## The measurement that removed the deadline
@@ -37,53 +38,72 @@ threshold. Slot `02` missed surviving by 0.6 seconds.
## Why a stall detector was never needed
Claude Code bounds its own tool calls. The `Bash` tool has a timeout (default
-120 s, maximum 600 s), and Claude Code emits
-`Background tasks still running after 600s; terminating`, which
-`team-orchestrator.ts` already parses as `BG_CEILING_RE`.
+120 s, maximum 600 s). A tool call inside the child cannot hang forever, so a
+claudish-side tool-stall detector guarded a condition the harness prevents.
-A tool call inside the child cannot hang forever. A claudish-side tool-stall
-detector guarded a condition the harness prevents.
+Print mode also ended its own run with `Background tasks still running after
+600s; terminating`, which team once parsed as `BG_CEILING_RE`. An interactive
+pane has no such ceiling, and the pattern went with print mode. A background
+SHELL is not awaited at all: the turn settles at Claude Code's own
+`turn_duration`, the slot reports `background_shell_open: <command>` in its
+`detail`, and the reap ends the shell (`pane-session.md`, D23). Background
+AGENTS are awaited, with no bound.
## What replaced it
-**Nothing terminates a slot on a timer.** `TeamRunOptions.timeout`,
-`graceExtension`, `maxGraceSeconds` and `stallSeconds` are gone, along with the
-watcher, `timeoutModel`, and the token-file progress read.
-
-**Silence is reported, not judged.** Each child's raw stdout and stderr writes
-stamp a timestamp — a listener separate from the answer capture, because those
-ask different questions. Capture asks "is this an answer?" and says no to a
-`tool_progress` heartbeat; liveness asks "is anything alive?" and the same frame
-says yes. `teamSlotIdleSeconds()` publishes the result, and `mode: "status"`
-returns it as `idle_seconds_by_slot`.
-
-Frames keep arriving during a long tool call — Claude Code emits `tool_progress`
-heartbeats every 30 s — which is exactly why this signal stays honest where the
-token-flow timestamp did not.
-
-**The liveness maps describe RUNNING slots only.** `idle_seconds_by_slot`,
+**Nothing terminates a slot on a timer once its prompt is accepted.**
+`TeamRunOptions.timeout`, `graceExtension`, `maxGraceSeconds` and `stallSeconds`
+are gone, along with the watcher, `timeoutModel`, and the token-file progress
+read. The only bounds left are the pane's boot (90 s) and the admission of the
+prompt (30 s), before any work exists (D10).
+
+**Silence is reported, not judged.** A slot's `last_activity_at` is its last
+screen change or transcript append, and `idle_seconds` counts from it — a signal
+separate from the answer, because the two ask different questions. The answer
+asks "what did the model say?"; liveness asks "is anything alive?". `mode:
+"status"` returns it as `idle_seconds_by_slot`, and every `run.slots` row and
+`team(mode:"list")` row carries it as `idle_seconds`.
+
+The screen keeps changing during a long tool call — Claude Code rewrites its
+working row (`✶ Simmering… (3s · ↓ 154 tokens)`) and the Bash timer every second
+— which is exactly why this signal stays honest where the token-flow timestamp
+did not.
+
+**The liveness maps describe live slots only.** `idle_seconds_by_slot`,
`activity_by_slot` and `live_output_bytes_by_slot` skip any slot whose `state` is
-not `RUNNING`; an exited slot's outcome is its `state`. The run stays registered
+terminal; a finished slot's outcome is its `state`. The run stays registered
until its LAST slot settles, so before 2026-09-12 an exited slot kept answering:
activity frozen at `waiting_for_input`, idle counting up from its exit. Measured in
a real status payload: `completedAt + idle_seconds` landed on the poll time for
both finished slots (idle 57 s and 571 s), while the third slot was still working.
A caller read `waiting_for_input` as a slot that needed an answer, which `team`
-has no way to send. A slot now never reports `waiting_for_input` at all:
-between its `result` and its exit it reads `finishing` (see below).
+has no way to send.
+
+**A slot never waits for input.** Between the model's last message and Claude
+Code's end-of-turn record its activity reads `finishing` (typically while Stop
+hooks run). A slot that stops on a question or a permission dialog it cannot
+answer is FAILED `blocked` at once, with the question in its `detail` (D19):
+team has no answering verb, so a blocked slot could never finish, and `judge`,
+`run-and-judge` and the CLI would wait for it forever. When a `finishing` slot's
+screen has been static with no Stop-hook row for 3 × 32 s, its activity reads
+`finishing: turn_end_record_missing` and the status note tells the caller to
+cancel it; nothing cancels it for them.
**The caller decides, and `cancel` is how it acts.** `cancelTeamRun` is the only
-thing that kills a slot. It kills the process GROUP: `claudish` is a launcher
-that runs the real CLI under Bun, which runs `claude`, so signalling the direct
-child reaches only the launcher and leaves the tree billing and holding the
-response pipe open.
+thing that ends a working slot. The slot is CANCELLED when the call returns; the
+pane's reap finishes in the background: `close_pane {force:true}`, magmux through
+its handle, then SIGTERM and SIGKILL on the pane's process GROUP after an
+identity check. The group matters: `claudish` runs the real CLI under Bun, which
+runs `claude`, with a Bash-tool grandchild below that, so signalling one process
+leaves the rest billing. `team(mode:"cancel")` stops one slot (`slot`) or the
+whole run and answers per slot `{state, changed}`.
## `outputSize` is not a progress signal, and callers read it as one
-`outputSize` is written exactly once per slot, in `finish()`, so a RUNNING slot
-carries the `0` it was initialised with for its whole life. This is correct — the
-field means "size of the final answer" and there is no final answer yet — and it
-is also the single most misread number the tool emits.
+`outputSize` is written exactly once per slot, when it turns terminal, so a
+RUNNING slot carries the `0` it was initialised with for its whole life. This is
+correct — the field means "size of the final answer" and there is no final answer
+yet — and it is also the single most misread number the tool emits.
Measured 2026-09-08, session `dev-feature-advisor-any-model-20260909-0001`: an
orchestrator polling a four-slot review panel saw
@@ -103,23 +123,22 @@ Nothing in the payload contradicted the misreading. The `note` explained
COMPLETED slot and omitted it from the RUNNING one — the one place a reader could
have been warned instead skipped the case.
-**The fix publishes the number that was already being counted.**
-`ModelRuntime.getByteCount()` has always tracked answer bytes as they arrive, in
-the same unit `outputSize` ends up holding (recovered prose, not raw
-stream-json). `teamSlotLiveBytes()` exports it and `mode: "status"` returns it as
-`live_output_bytes_by_slot`. A running slot now has a true volume number beside
-its true liveness numbers.
+**The fix publishes the number that was already being counted.** The pane's
+snapshot carries `liveAnswerBytes`, the current turn's assistant text so far, in
+the same unit `outputSize` ends up holding (answer prose). `mode: "status"`
+returns it as `live_output_bytes_by_slot`. A running slot now has a true volume
+number beside its true liveness numbers.
**`outputSize` itself was deliberately not changed.** Making it report live bytes
while RUNNING would have made the misleading number true, at the cost of the one
distinction a caller actually needs: `formatTeamResult` and `classifyRunOutput`
-both read `outputSize` as final-answer size, and an EMPTY slot is defined by that
-field being small. Overload it and `0` no longer separates "still working" from
-"exited having produced nothing". One name, one meaning.
+both read the final answer's size, and an EMPTY slot is defined by it being
+small. Overload it and `0` no longer separates "still working" from "finished
+having produced nothing". One name, one meaning.
**The note is keyed on RUNNING, not on liveness.** The previous note appeared only
-when `teamSlotIdleSeconds()` returned non-null, i.e. only for runs this server
-spawned. A run whose server restarted under it still shows RUNNING slots from
+when the liveness maps were non-null, i.e. only for runs this server spawned. A
+run whose server restarted under it still shows RUNNING slots from
`status.json`, with all three liveness maps null — which is precisely a reader
about to misjudge an `outputSize` of 0, and now the one who most needs telling.
The not-live wording names no liveness field, because naming a null field sends
@@ -131,7 +150,7 @@ assertion is the ordering one: `outputSize` must appear in the note BEFORE
survives gutting the warning, because the remedy clause mentions the field too;
the ordering check does not.
-## Why `run` does not block
+## Why `run` does not wait for answers
A team slot is a full Claude Code session and can legitimately work for a long
time. Holding a tool call open for that duration makes the run's length the MCP
@@ -140,14 +159,37 @@ and a real `team` run died at exactly 1800 s for that reason. The keepalive
(`notifications/progress`, the only notification measured to reset that timer)
was built to defeat it.
-`startModels` returns as soon as the children exist, handing back a `TeamHandle`
-with the team session id and a model-to-slot map. The run continues in the
-background; the caller polls `mode: "status"`. This removes the reason the 1800 s
-ceiling ever mattered rather than working around it.
+`startModels` returns once every slot has **left STARTING** (D9): its prompt was
+accepted (RUNNING), or it failed boot or admission. It hands back a `TeamHandle`
+with the `run_id`, the team session id and a model-to-slot map. The run continues
+in the background; the caller polls `mode: "status"` (read `run.slots`) or
+`mode: "list"`. This removes the reason the 1800 s ceiling ever mattered rather
+than working around it.
+
+**It does block through boot and admission, and only through them.** The bound
+is boot 90 s + admission 30 s = 120 s, before any work exists, so nothing can be
+lost to it; with the fake child a slot reaches RUNNING in 1.2–1.9 s. Returning any
+earlier breaks a real consumer: the dev plugin's team gate polls until no slot is
+RUNNING, so a slot still STARTING on its first poll would end the gate with zero
+ballots. Boot and admission failures are therefore in the `run` answer itself.
+Slots spawn 300 ms apart so N REPLs do not write `~/.claude.json` in the same
+instant.
`runModels` remains as the blocking form, for `run-and-judge` — a pipeline
cannot judge answers that do not exist yet.
+### The run registry, by `run_id`
+
+Runs this process started are kept in memory keyed by `run_id`
+(`<team_session_id>-<base36 start ms>-<6 hex>`), with an index of the newest run
+per path. A path holds at most one ACTIVE run; `run` on an ACTIVE path is refused.
+A SETTLED run (every slot terminal) stays listable and capturable for 30 minutes,
+at most 20 of them, oldest evicted first. `status`, `cancel` and `capture` take an
+optional `run_id`, which addresses THAT run while it is retained even after a newer
+run reused the path; without one they address the newest run at `path`. After
+eviction, or after a server restart, `status` still answers from `status.json`
+(the newest run at the path only), with every liveness map null.
+
### The run's record in the sessions directory, ended exactly once
Returning early has a cost: the run's completion reaches the caller only through
@@ -159,9 +201,10 @@ directory the magus `claudish` plugin monitor already watches:
- `<sessionsDir>/team-<8 hex>/spawn.json` — `kind: "team"`, `teamPath`, `slots`,
`hostPid`, `mcpPid` (and `launcherPid`, `parentClaudeSessionId` when they
- apply), written by `SessionManager.recordTeamRun` BEFORE `startModels`; a throw
- fails the call with nothing started. The `run` result carries the id as
- `monitor_record`.
+ apply), written by `SessionManager.recordTeamRun` BEFORE `startModels` and after
+ every pre-spawn refusal (`claude_flags`, an undeliverable prompt, magmux, an
+ ACTIVE path, the pane limit); a throw fails the call with nothing started. The
+ `run` result carries the id as `monitor_record`.
- `<sessionsDir>/team-<8 hex>/meta.json` — `{kind:"team", status, startedAt,
completedAt, elapsedSeconds, slots, ok, failed, cancelled}` plus
`reason: "start-failed"` when the run never started; written atomically by
@@ -170,40 +213,59 @@ directory the magus `claudish` plugin monitor already watches:
**The end is wired INTO `startModels`, not after it.** `TeamRunOptions.onSettled`
is called from `done`'s `finally`, after the settled `status.txt` render, inside
-its own `try`. Read inside `startModels`, it exists before the first child does,
+its own `try`. Read inside `startModels`, it exists before the first pane does,
so a run that settles at once and a slow one take the same path. A settle hung
on `handle.done.then(…)` in the handler would depend on code that runs after
`startModels` returns, and would never be installed when `startModels` throws.
-
-**A throw inside the spawn loop kills what it already spawned.** The ticker, the
-registry entry and `done` are all built after the loop, so a synchronous
-`spawn()` error or a failed `status.json` write for slot N used to leave slots
-1..N-1 running and billing, unreachable, with the SIGINT handler still installed.
-The loop's `catch` stops every spawned slot's process group with
-`terminateChildTree` — SIGTERM, then SIGKILL after `TERMINATE_GRACE_MS`, as
-`cancel_session` does — and waits for that before it removes the SIGINT handler
-and rethrows. SIGTERM alone left a slot that traps it running and billing under
-a record that already said `start-failed`. The handler's `catch` then writes
-`failed`, `reason: start-failed` with counts from `status.json`
-(`summarise(readTeamStatus(path))`), and rethrows the ORIGINAL error. `spawnChild`
-is the seam a test uses to make one spawn throw, `terminateGraceMs` the one that
-shortens the grace period (`team-start-failure.test.ts`).
+`team-run-mcp.contract.test.ts` measures the end against the settle: `meta.json`'s
+`completedAt` is within 1 s of the last slot's `completedAt`.
+
+**A throw inside the spawn loop stops what it already started.** The ticker, the
+registry entry and `done` are all built after the loop, so a failed `status.json`
+write for slot N used to leave slots 1..N-1 running and billing, unreachable. The
+loop's `catch` now calls `cancel()` on every pane already started and awaits each
+`reaped()`: `close_pane {force:true}`, magmux through its handle, then SIGTERM and
+SIGKILL on the verified pane group — the reap's own escalation, so a slot that
+traps SIGTERM cannot keep running under a record that already says
+`start-failed` (measured: magmux's forced close sent the trapping fake SIGHUP and
+killed it before the group backstop was needed). Those cancels are not the
+caller's, so they reach neither `status.json` nor any frame: the started slots stay
+STARTING there and count as failed. Only then does the ORIGINAL error escape. A
+slot's own `startPaneSession` throw is NOT such a throw: it is that slot's FAILED
+`pane_lost`, and its siblings run on. There is no claudish SIGINT handler to remove
+any more; the pane registry's shutdown hooks cover every consumer. The handler's
+`catch` then writes `failed`, `reason: start-failed` with counts from `status.json`
+(`summarise(readTeamStatus(path))`), and rethrows the original error. The tests
+inject the fault by making `status.json` read-only once the first pane record
+exists (`team-start-failure.test.ts`, `team-orchestrator-settle.contract.test.ts`).
**The record ends exactly once because the two paths cannot both run.**
-`onSettled` is called only from `done`, and `done` is built after the spawn loop;
-when the loop throws, `startModels` rejects without ever building it, however
-fast the spawned slots exit. When the loop completes, nothing after it throws, so
+`onSettled` is called only from `done`, and `done` is built LAST — after the spawn
+loop and after the D9 `ready` await, which never rejects (`ready` resolves on any
+exit from STARTING, terminal included) — immediately before the `return`. When the
+loop throws, `startModels` rejects without ever building it, however fast the
+started slots end. When the loop completes, nothing after it throws, so
`startModels` resolves and the handler's `catch` never runs. And `finishTeamRun`
keeps its first outcome, so a second call could not overwrite it anyway.
-`team-run-settles-once.test.ts` pins all three on the real code.
-
-`summarise` counts `COMPLETED` as ok, a `cancelled` reason as cancelled, and every
-other state — `PENDING` and `RUNNING` included — as failed; the verdict is
-`completed` when any slot is ok (the channel frame's rule), `cancelled` when all
-were cancelled. Only `run` writes a record: `run-and-judge` returns its verdict in
-the call, and `judge`/`status`/`cancel` start no work. `loadDiskRecord` returns
-null for a `kind: "team"` directory, so session tools answer a `team-*` id as
-unknown and `list_sessions` (in-memory only) never lists one.
+`team-run-settles-once.test.ts` pins all three on the real code. "Settled" means
+every slot is terminal, not every pane reaped: `done` awaits each slot's
+`terminal`, and the reap finishes up to ≈ 12 s later without delaying the record.
+
+`summarise` counts `COMPLETED` as ok, a terminal slot whose `error.reason` is
+`cancelled` as cancelled (every CANCELLED row carries it), and every other state —
+the non-terminal STARTING, RUNNING, AWAITING_INPUT and AWAITING_PERMISSION
+included — as failed; the verdict is `completed` when any slot is ok (the channel
+frame's rule), `cancelled` when all were cancelled. Only `run` writes a record:
+`run-and-judge` returns its verdict in the call, and `judge`/`status`/`list`/
+`capture`/`cancel` start no work. `loadDiskRecord` returns null for a
+`kind: "team"` directory, so session tools answer a `team-*` id as unknown and
+`list_sessions` (in-memory only) never lists one.
+
+**Shutdown ends the record too.** Stdin EOF, SIGINT, SIGTERM and SIGHUP run
+`shutdownAllTeamRuns()` before the pane reap: every live slot is cancelled, each
+run's `done` resolves on those transitions, and every record ends `cancelled`.
+After a SIGKILL no record ends; the pane watchers still remove every process, and
+the monitor reports the run from the writer's death.
### Blinding is unaffected
@@ -212,62 +274,29 @@ manifest is shuffled so the judge CHILDREN, which read `response-<id>.md` withou
a manifest, cannot attribute answers. The orchestrating caller has always seen
the mapping — `status.txt` prints model names beside slot ids.
-## One parser, two consumers
-
-`team` drove `createAssistantTextCapture()` directly and hand-rolled everything
-around it. The channel wrapped that SAME capture in `StreamJsonReducer` and added
-what team lacked: a state machine that tells thinking from tool execution, and
-`sawResult` — the child's own terminal `result` frame, a real completion oracle
-where exit 0 is not (`claude -p` exits 0 on API errors too).
-
-Two implementations of one job existed because `team-orchestrator.ts` dates from
-2026-03-20 and `stream-json-reducer.ts` from 2026-08-22. `team` now feeds the
-reducer, and `StreamJsonReducer` is the only production consumer of the capture.
-`feed()` and `end()` return exactly what `capture.write()`/`capture.end()`
-returned, so `byteCount`, `stdoutTail` and `classifyRunOutput` were unaffected by
-the swap.
-
-### The one behaviour that had to be made explicit
-
-The two parsers disagreed on a line that is valid JSON but is NOT stream-json
-vocabulary — a bare array, a stray object:
-
-| Line | capture | reducer (before) |
-|---|---|---|
-| not JSON (`[API Error: …]`) | passthrough | passthrough |
-| recognised frame | recover prose | recover prose |
-| JSON, unrecognised | **passthrough** | **dropped** |
-
-Both behaviours are correct for their own consumer. A channel session's stdout is
-pure stream-json, so a stray JSON object is machine noise and keeping it would
-pollute the answer. A team slot's `response-<id>.md` is the only place a reader
-ever sees what the child printed, and this project has already lost real answers
-to a parser deciding something was not worth keeping (`team-capture.md`).
-
-So it is an option — `keepUnrecognizedJson`, default false, and `team` passes
-true — rather than one rule imposed on both. Note the asymmetry it resolves: an
-UNPARSEABLE line was always kept ("it is the only place a reader would ever see
-it"), so dropping *valid* JSON was the stricter rule, not the looser one.
-
-This was caught by the `--print-argv` test, whose fake child prints a JSON array
-to stdout: under the reducer's default the argv never reached the response file
-and the slot was classified EMPTY.
-
-### Team must settle the reducer itself
-
-A `result` frame ends a turn, and the reducer asks its owner whether stdin stays
-open (`onResult` returns `TurnEnd`). `team` closes stdin at spawn, so it always
-answers `"stdin-closed"` and the slot moves to `finishing`, which only a terminal
-state may follow. Before `finishing` existed, every `result` moved the reducer to
-`waiting_for_input`, on the premise that stdin was still open — a premise that
-never held for a slot — and until 2026-09-12 nothing settled the reducer after
-that: it stayed in `waiting_for_input` after the child had exited.
-
-`finish()` now settles it to the outcome it just recorded (COMPLETED → `completed`,
-EMPTY or FAILED → `failed`, a cancelled slot → `cancelled`, TIMEOUT → `timeout`)
-and only then disposes it. The dispose moved out of `finalizeCapture` because a
-disposed reducer ignores `settle()`, and `finish()` runs later, off the output
-stream's "close".
+## One driver, two owners
+
+`team` and the channel once had two implementations of one job: team drove a
+stream-json capture and hand-rolled everything around it, while the channel
+wrapped the same capture in a reducer with a state machine. Both went with print
+mode. Both owners now drive the same `PaneSession` (`pane/`), which owns the
+MECHANISM — boot, delivery, the transcript turn oracle, settle, the reap — and asks
+its owner for POLICY at exactly two points:
+
+- `decide(turn)` when a turn settles. Team's answer writes `response-<slot>.md`
+ (byte-exact, once) and returns `classifyRunOutput` with the caller's
+ `require_pattern` and `min_output_bytes` (`team-capture.md`); the channel's
+ classifies a one-shot turn with no floor and no pattern, or continues an
+ interactive one.
+- `onBlocked(block)` when a turn stops on a question or a dialog. Team fails the
+ slot `blocked`; the channel waits for `send_input`.
+
+So nothing team-specific leaks into the pane module, and nothing pane-specific into
+the policy. Two details that used to need explicit rules now follow from the
+transcript: there is no "valid JSON but not stream-json" line to keep or drop (the
+`keepUnrecognizedJson` option is gone with the reducer), and there is no reducer for
+team to settle after its child exits — a slot is terminal at its verdict, before its
+pane is reaped.
## Spawn plumbing: what was shared, and what was deliberately not
@@ -279,25 +308,25 @@ evaluated and rejected. Reading what `createSession` actually does shows why:
- It calls `classifyRunOutput` with `minOutputBytes: 0` and NO `requirePattern`.
Team's shape contract is the one signal that catches a voter which never voted,
so team's policy would have to be pushed down into the session manager.
-- `requirePattern` is matched against the FULL response, not the bounded tail, so
- the session manager would also need team's re-read-from-disk step.
+- `requirePattern` is matched against the FULL answer, not a bounded tail, so the
+ session manager would also need team's whole-answer handling.
- `session-manager.ts` already imports `classifyRunOutput` FROM
`team-orchestrator.ts`. Adding team's options would complete the inversion: a
channel session manager that knows what a blind-vote panel is.
The addressability was also worth less than it looked. `team` already answers the
-same questions through `mode:"status"` and `mode:"cancel"`, so the session id
-would have added convenience, not capability — at the price of that inversion,
-plus a shared `maxSessions` cap and a second copy of every answer on disk.
-
-What IS genuinely shared is the mechanism, and that was extracted:
-
-- **`stdio-decode.ts`.** A `data` chunk ends at the pipe's read boundary, which
- can fall mid-codepoint. The channel decoded through a `StringDecoder` all
- along; team read with `chunk.toString()`, which replaces the dangling bytes
- with U+FFFD — permanently mangling any CJK character or emoji straddling a
- boundary in `response-<id>.md`, and mis-sizing `outputSize`. Both now share
- one decoder helper, one per pipe.
+same questions through `mode:"status"`, `mode:"capture"` and `mode:"cancel"`, so
+the session id would have added convenience, not capability — at the price of that
+inversion, plus a shared `maxSessions` cap and a second copy of every answer on
+disk.
+
+What IS genuinely shared is the mechanism, and that was extracted — first as
+shared helpers, now as one driver:
+
+- **`pane/`**, the whole child lifecycle (above). It replaced `stdio-decode.ts`,
+ the shared pipe decoder that had fixed team's `chunk.toString()` mangling CJK
+ and emoji split across a read boundary; a transcript record is a whole line of
+ JSON, so that hazard no longer exists.
- **The upstream-error log.** `captureUpstreamError` is opt-in on
`UPSTREAM_ERROR_LOG_ENV`, which team never set — so it was a guaranteed no-op
for every team child, and the provider response body that separates a
@@ -305,16 +334,15 @@ What IS genuinely shared is the mechanism, and that was extracted:
been classified. Team now sets it per slot (the records carry no slot id, so a
shared path would interleave models), and `ModelError.upstreamErrorLogPath`
names the file only when one was actually written.
-- **The stream-json parser**, covered above.
-What remains team's own is what legitimately differs: a one-shot `--stdin` argv
-against the channel's bidirectional `--input-format stream-json` (which exists so
-`send_input` works), team's directory layout, its anonymised slot ids, and its
-status file. Those are not duplication; they are two different jobs.
+What remains team's own is what legitimately differs: its policy, its directory
+layout (`input.md`, `response-<slot>.md`, `status.json`, `errors/<slot>.log`,
+`stats/<slot>.json`), its anonymised slot ids and its run registry. Those are not
+duplication; they are two different jobs.
-`SessionCreateOptions` did gain `sessionId`, `sessionDir`, `tokenFile` and
-`keepUnrecognizedJson` while this was being evaluated. They are additive, tested,
-and make the adoption route available later if the trade above ever changes.
+`SessionCreateOptions` did gain `sessionId`, `sessionDir` and `tokenFile` while
+this was being evaluated. They are additive, tested, and make the adoption route
+available later if the trade above ever changes.
## Coverage removed with the mechanism
@@ -323,3 +351,7 @@ Deleting the reaper deleted the tests that drove it: `team-timeout-termination`
Two of those covered behaviour reachable only through the kill path — an answer
flushed during shutdown being recovered, and nothing being written after the run
returns. Equivalent coverage belongs against the agent-initiated cancel path.
+`team-cancel.test.ts` now covers that path on real panes (synchronous and
+idempotent, one slot, the whole run), and every pane test asserts that no process
+or file outlives the run. A cancelled slot's partial answer reaches
+`response-<slot>.md` through its terminal transition; no test pins that yet.