Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(mcp): drive session hooks for create_session and team panes
Jack Rudenkob29cad80d6d2
diff --git a/packages/cli/src/mcp-session/session-manager.ts b/packages/cli/src/mcp-session/session-manager.tsindex 618221e6..c5e13845 100644--- a/packages/cli/src/mcp-session/session-manager.ts+++ b/packages/cli/src/mcp-session/session-manager.ts@@ -14,6 +14,12 @@// non-terminal state and queued (D17). `timeout_seconds` is the caller's own deadline// and the only post-acceptance timer (D10).//+// Session hooks (hook-system §2.3, §7.3, §7.4): every child gets an owner-created+// inbox (`hook-inbox.jsonl` in its session dir) and `CLAUDISH_HOOK_INBOX` /+// `CLAUDISH_HOOK_SESSION`. When this process's hook engine has a session hook, the pane+// gets a binding and each settled turn's answer is RECORDED into the output at once+// (`recordAnswer`), before its verdict, so no terminal path can lose it.+//// The 10.4.0 session records are kept, byte for byte where the magus monitor reads// them (§20.1): `spawn.json` before any pane, `waits.jsonl` from the pane's transition// hook, `meta.json` through `toMetaRecord` with every 10.4.0 key, `events.jsonl` with@@ -31,6 +37,7 @@ import {readFileSync,readSync,renameSync,+ rmSync,statSync,writeFileSync,} from "node:fs";@@ -38,6 +45,17 @@ import { join, resolve, sep } from "node:path";import { ENV } from "../config.js";import { UPSTREAM_ERROR_LOG_ENV } from "../handlers/shared/upstream-error-capture.js";+import type { HookEngine } from "../hooks/engine.js";+import { loadHooksOnce } from "../hooks/index.js";+import { createHookInbox } from "../hooks/injection/inbox.js";+import { HOOK_INBOX_ENV } from "../hooks/injection/sinks.js";+import { HOOK_SESSION_ENV } from "../hooks/request-stage.js";+import {+ type SessionHookBinding,+ createSessionHookBinding,+ reportOwnerWithoutHooks,+ sessionHooksNeedBinding,+} from "../hooks/session/binding.js";import {type Accounting,type CaptureResult,@@ -61,6 +79,7 @@ import {type SettledTurn,type SlotState,assertMagmuxAvailable,+ chainAnswerOf,checkChildFlags,clampPaneSize,deliveryRefusal,@@ -137,6 +156,8 @@ export interface SessionDiagnostics {costUsd: number | null;toolCalls: number;pendingInputs: number;+ /** Queued hook injections (hook-system §4.7 rule 11); 0 when not live. */+ pendingHookInputs: number;/** Whether claudish holds a live socket to the pane's magmux right now. */connected: boolean;/** The last non-empty rows of the child's screen, redacted (a PTY has no separate stderr). */@@ -230,6 +251,8 @@ interface SessionEntry {* is appended.*/answeredTurns: Map<number, string>;+ /** The owner-created hook inbox; null when it could not be created. */+ inboxPath: string | null;waitLogPath: string;waitLogBytes: number;/** The `since` of the wait that is open now, or null. */@@ -304,7 +327,8 @@ const UPSTREAM_ERROR_TAIL_BYTES = 64 * 1024;const SPAWN_RECORD_SCHEMA = 1;/** RUNNING activities that are not a tool name (§8 B). */-const NON_TOOL_ACTIVITY = new Set(["thinking", "background", "finishing"]);+// "hook": a settled turn held while session hooks run (§7.3); not a tool+const NON_TOOL_ACTIVITY = new Set(["thinking", "background", "finishing", "hook"]);/** `meta.json` `status` for each terminal state (§20.1): EMPTY is a failure to the monitor. */const META_STATUS: Record<SlotState, string> = {@@ -661,6 +685,11 @@ export class SessionManager {private readonly teamRunStarts = new Map<string, string>();/** Team run records whose end is on disk. The first `finishTeamRun` write to succeed wins. */private readonly settledTeamRuns = new Set<string>();+ /** The hook engine pane bindings are built from; loaded before the first pane spawn. */+ private hookEnginePromise: Promise<HookEngine | null> | null = null;+ private readonly hookEngineSource: () => Promise<HookEngine | null>;+ private readonly bindingOverride: SessionManagerOptions["hookBinding"];+ private readonly magmuxBinary: string | undefined;constructor(options?: SessionManagerOptions) {// Computed once: the Claude Code process that launched this MCP server@@ -679,6 +708,15 @@ export class SessionManager {this.sessionsDir = options?.sessionsDir ?? sessionsDirFrom(process.env);this.parentEnv = options?.parentEnv ?? process.env;this.paneTimings = options?.paneTimings;+ this.hookEngineSource = options?.hookEngine ?? (() => loadHooksOnce());+ this.bindingOverride = options?.hookBinding;+ this.magmuxBinary = options?.magmuxBinary;+ }++ /** The process's hook engine (§2.2), awaited before the first pane spawn. Never rejects. */+ private hookEngine(): Promise<HookEngine | null> {+ if (!this.hookEnginePromise) this.hookEnginePromise = this.hookEngineSource().catch(() => null);+ return this.hookEnginePromise;}/** The Claude Code process that launched this MCP server (`spawn.json` `hostPid`). */@@ -856,7 +894,7 @@ export class SessionManager {counted = false;};try {- await assertMagmuxAvailable();+ await assertMagmuxAvailable(this.magmuxBinary);reservePanes(1, sockRootFor(parentEnv));let entry: SessionEntry;try {@@ -957,6 +995,7 @@ export class SessionManager {eventRing: [],proseBytes: 0,answeredTurns: new Map(),+ inboxPath: null,waitLogPath: join(sessionDir, "waits.jsonl"),waitLogBytes: 0,waitSince: null,@@ -976,6 +1015,9 @@ export class SessionManager {p: { flags: string[]; readAvailable: boolean; parentEnv: Record<string, string | undefined> }): Promise<void> {const info = entry.info;+ const engine = await this.hookEngine();+ entry.inboxPath = createHookInbox(entry.sessionDir);+ const binding = this.bindingFor(entry, engine);// L2: a size asked for before this point is the pane's launch sizeconst launch = entry.requestedSize;const paneOpts: PaneSessionOptions = {@@ -993,6 +1035,10 @@ export class SessionManager {// Per session, unconditionally: the records carry no session id, so a shared// path would interleave concurrent sessions into one unattributable file.[UPSTREAM_ERROR_LOG_ENV]: entry.upstreamErrorLogPath,+ // Every child, unconditionally (§2.3 step 1): a child may load hooks this+ // process did not, so it must never lack a sink, and ctx.session must be set.+ ...(entry.inboxPath ? { [HOOK_INBOX_ENV]: entry.inboxPath } : {}),+ [HOOK_SESSION_ENV]: JSON.stringify({ kind: "channel", id: info.sessionId, role: null }),},shape: info.shape,...(opts.prompt ? { initialPrompt: opts.prompt } : {}),@@ -1005,20 +1051,69 @@ export class SessionManager {onTransition: (t) => this.onPaneTransition(entry, t),parentEnv: p.parentEnv,...(this.paneTimings ? { timings: this.paneTimings } : {}),+ ...(this.magmuxBinary ? { magmuxBinary: this.magmuxBinary } : {}),+ ...(binding+ ? {+ hooks: binding,+ onTurnRecorded: (turn: SettledTurn) =>+ this.recordAnswer(entry, turn.index, turn.answer),+ }+ : {}),};try {entry.session = await startPaneSession(paneOpts);} catch (err) {+ this.removeInbox(entry);this.failNeverSpawned(entry, err);throw err;}+ const session = entry.session;// a size asked for while the pane started (after its environment was built): apply it// now; the pane's own worker answers any later resizeconst asked = entry.requestedSize;entry.requestedSize = null;if (asked && (asked.cols !== launch?.cols || asked.rows !== launch?.rows))- entry.session.resize(asked.cols, asked.rows).catch(() => undefined);- if (!entry.ended) this.applySnapshot(entry, entry.session.snapshot());+ session.resize(asked.cols, asked.rows).catch(() => undefined);+ // At reap: an owner without a binding checks the inbox once, then the file goes.+ void session.reaped().then(() => {+ if (!binding && entry.inboxPath)+ reportOwnerWithoutHooks(entry.inboxPath, engine, {+ model: info.model,+ sessionId: info.claudeSessionId,+ });+ // with a binding, what no settle took is journaled before the file goes+ binding?.sweepInbox?.();+ this.removeInbox(entry);+ });+ if (!entry.ended) this.applySnapshot(entry, session.snapshot());+ }++ /** The pane's hook binding: a test's, or the real one when this engine has session hooks. */+ private bindingFor(entry: SessionEntry, engine: HookEngine | null): SessionHookBinding | null {+ const info = entry.info;+ const session = {+ kind: "channel" as const,+ role: null,+ id: info.sessionId,+ claudeSessionId: info.claudeSessionId,+ model: info.model,+ cwd: entry.cwd,+ shape: info.shape,+ injection: "available" as const,+ };+ if (this.bindingOverride)+ return this.bindingOverride({ session, inboxPath: entry.inboxPath, engine });+ if (!engine || !sessionHooksNeedBinding(engine)) return null;+ return createSessionHookBinding(engine, session, entry.inboxPath);+ }++ private removeInbox(entry: SessionEntry): void {+ if (!entry.inboxPath) return;+ try {+ rmSync(entry.inboxPath, { force: true });+ } catch {+ // the session dir keeps it; nothing reads it after the reap+ }}/** A session whose pane never started: FAILED `pane_lost`, its records ended. */@@ -1044,11 +1139,13 @@ export class SessionManager {// The pane's shape at the settle, not entry.info's copy: a send_input whose own step// settles the turn has converted the session before sendInput could update the copy.if (turn.shape === "one-shot") {+ // A hook-extended turn chain is classified as one answer, with the CHAIN HEAD's+ // prompt-read result (§4.7 rule 9). Without hooks both equal the turn's own.const v = classifyRunOutput({- answer: turn.answer,+ answer: chainAnswerOf(turn),apiError: turn.apiError,stopReason: turn.stopReason,- promptRead: turn.delivery,+ promptRead: turn.chainDelivery,minOutputBytes: 0,});if (v) return { state: v.state, reason: v.reason, detail: v.detail };@@ -1061,8 +1158,9 @@ export class SessionManager {return { state: "FAILED", reason: "api_error", detail: v?.detail ?? "API error" };}// An interactive turn whose task file was not fully read continues; the anomaly is- // in the session's event log (r2, X-M4).- if (turn.delivery.complete === false) {+ // in the session's event log (r2, X-M4). An unread HOOK turn is the pane's+ // hook_injection_not_read, never the caller-facing prompt_not_read (L-2).+ if (!turn.hookCaused && turn.delivery.complete === false) {this.appendEvent(entry, {type: "anomaly",key: "prompt_not_read",@@ -1292,6 +1390,8 @@ export class SessionManager {costUsd: info.costUsd,toolCalls: info.toolCalls,pendingInputs: info.pendingInputs,+ pendingHookInputs:+ entry.session && !entry.ended ? entry.session.snapshot().pendingHookInputs : 0,pane: info.pane,captureSource: info.captureSource,turnSource: info.turnSource,@@ -1607,6 +1707,7 @@ export class SessionManager {costUsd: info.costUsd,toolCalls: info.toolCalls,pendingInputs: 0,+ pendingHookInputs: 0,connected: false,screenTail: redactSecrets(screen?.text ?? "").trimEnd(),pane: info.pane,@@ -1667,6 +1768,16 @@ export class SessionManager {entry.info.elapsedSeconds = elapsedSecondsBetween(entry.info.startedAt, Date.now());}+ /**+ * `onTurnRecorded` (binding present): the answer reaches the output when the turn is+ * RECORDED, before its verdict and before any hold. A second record of the same index+ * (a re-wake) appends only the text past what was already written, once, as its own+ * paragraph (§7.4) — the same extension rule `appendAnswer` applies to a re-settle (D23).+ */+ private recordAnswer(entry: SessionEntry, index: number, answer: string): void {+ this.appendAnswer(entry, index, answer);+ }+/** A settled turn's answer → scrollback, `output.log` and `outputBytes`. Once per turn. */private appendAnswer(entry: SessionEntry, index: number, answer: string): void {const prior = entry.answeredTurns.get(index);diff --git a/packages/cli/src/mcp-session/types.ts b/packages/cli/src/mcp-session/types.tsindex 873cabc7..1efd9b32 100644--- a/packages/cli/src/mcp-session/types.ts+++ b/packages/cli/src/mcp-session/types.ts@@ -1,5 +1,8 @@// ─── MCP Session Types ───────────────────────────────────────────────────────+import type { HookEngine } from "../hooks/engine.js";+import type { SessionInfo as HookSessionInfo } from "../hooks/public.js";+import type { SessionHookBinding } from "../hooks/session/binding.js";import type { FailureReason, PaneSessionOptions, SlotState, SlotStep } from "../pane/index.js";/**@@ -189,4 +192,20 @@ export interface SessionManagerOptions {parentEnv?: Record<string, string | undefined>;/** @internal test-only pane timing seams (X-M7); production never passes them. */paneTimings?: PaneSessionOptions["timings"];+ /**+ * The hook engine pane bindings are built from. Default: the process engine+ * (`loadHooksOnce()`), awaited before the first pane spawn. Tests pass their own.+ */+ hookEngine?: () => Promise<HookEngine | null>;+ /** @internal test seam: the magmux binary every pane is spawned with (H-6) */+ magmuxBinary?: string;+ /**+ * @internal test seam (§11.5): the binding for one session, instead of the real one.+ * Return null for no binding.+ */+ hookBinding?: (ctx: {+ session: HookSessionInfo;+ inboxPath: string | null;+ engine: HookEngine | null;+ }) => SessionHookBinding | null;}diff --git a/packages/cli/src/pane/pane-hooks.integration.test.ts b/packages/cli/src/pane/pane-hooks.integration.test.tsnew file mode 100644index 00000000..fde03f4f--- /dev/null+++ b/packages/cli/src/pane/pane-hooks.integration.test.ts@@ -0,0 +1,1790 @@+/**+ * The settle hold, `SETTLING` and the turn chain (hook-system architecture §7.3, §7.4,+ * §11.5 H-1 … H-34), against REAL magmux and the fake interactive child in scripted+ * mode (`fake-scripted`, `FAKE_SCRIPT`, `FAKE_KEYLOG`).+ *+ * The binding is a test double whose `settle()` returns a promise the test resolves,+ * except where a row says "real binding" (H-21, H-21b, H-24, the cap and the+ * sessionStart rows), which run `createSessionHookBinding` over a real engine. The+ * owner is the real channel `SessionManager` (observed through get_output,+ * get_diagnostics, its frames and events.jsonl) or the real team orchestrator+ * (response-<slot>.md and the slot's status row). Every test ends with the+ * no-orphan check.+ */++import { afterAll, describe, expect, test } from "bun:test";+import { randomUUID } from "node:crypto";+import { chmodSync, existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { SessionManager } from "../channel/session-manager.js";+import type { ChannelEvent, SessionManagerOptions } from "../channel/types.js";+import { HookEngine } from "../hooks/engine.js";+import type { JournalEntry } from "../hooks/journal.js";+import type { HookDefinition } from "../hooks/public.js";+import { HookRegistry, type UserHookInput } from "../hooks/registry.js";+import {+ type HoldResult,+ type HoldTurnInfo,+ type SessionHookBinding,+ createSessionHookBinding,+} from "../hooks/session/binding.js";+import {+ type TeamHandle,+ type TeamRunOptions,+ cancelTeamRun,+ getStatus,+ setupSession,+ startModels,+} from "../team-orchestrator.js";+import type { CaptureResult, SlotState } from "./contract.js";+import { type PaneSession, type PaneSessionOptions, startPaneSession } from "./pane-session.js";+import {+ MAGMUX,+ NO_MAGMUX_MESSAGE,+ type PaneTestEnv,+ killLeftovers,+ makePaneTestEnv,+ newSessionUuid,+ waitNoOrphans,+} from "./test-helpers/hermetic-env.js";+import type { PaneSnapshot, SettledTurn } from "./types.js";++const T = 60_000;++/* ───────────────────────────── the test double binding ───────────────────────────── */++interface SettleCall {+ turn: HoldTurnInfo;+ signal: AbortSignal;+ resolve(r: HoldResult): void;+ reject(e: unknown): void;+}++function controlled(o: { idle?: boolean; bound?: number } = {}) {+ const calls: SettleCall[] = [];+ const dropped: Array<{ text: string; reason: string }> = [];+ const abandoned: Array<{ text: string; reason: string }> = [];+ const binding: SessionHookBinding = {+ hasIdleWork: () => o.idle ?? true,+ settle: (turn, signal) =>+ new Promise<HoldResult>((resolve, reject) => calls.push({ turn, signal, resolve, reject })),+ holdBoundMs: () => o.bound ?? 30_000,+ fireStart() {},+ fireBlocked() {},+ fireEnd() {},+ noteDropped: (item, reason) => void dropped.push({ text: item.text, reason }),+ abandon: (r, reason) => {+ for (const i of r.injections) abandoned.push({ text: i.text, reason });+ },+ };+ return { binding, calls, dropped, abandoned };+}++const inject = (text: string): HoldResult => ({+ injections: [{ text, hookIds: ["hook:t/x"], source: "sessionIdle" }],+});+const nothing: HoldResult = { injections: [] };++/* ───────────────────────────── engines for the real binding ───────────────────────────── */++function engineOf(...defs: Array<Omit<HookDefinition, "apiVersion">>) {+ const journal: JournalEntry[] = [];+ const users: UserHookInput[] = defs.map((d, i) => ({+ id: `hook:t/${d.id}`,+ module: "/hooks/t.ts",+ moduleIndex: 0,+ exportIndex: i,+ def: { apiVersion: 1, ...d } as HookDefinition,+ }));+ const engine = new HookEngine({+ registry: new HookRegistry([], users, undefined),+ config: {},+ hostMode: "mcp",+ journalSink: (e) => journal.push(e),+ warn: () => {},+ drainTelemetryOutbox: false,+ });+ return { engine, journal };+}++const after = <T>(ms: number, v: T) => new Promise<T>((r) => setTimeout(() => r(v), ms));++/* ───────────────────────────── helpers ───────────────────────────── */++interface TurnScript {+ say?: string;+ partial?: string;+ ask?: string;+ noWitness?: boolean;+ exitOnSubmit?: number;+ noRead?: boolean;+ apiError?: string;+ delayMs?: number;+ rewake?: {+ delayMs: number;+ say: string;+ workingMs?: number;+ quietMs?: number;+ gateFile?: string;+ clearWithRecords?: boolean;+ };+ exitAfter?: number;+ exitDelayMs?: number;+}++const openEnvs = new Set<PaneTestEnv>();+afterAll(() => {+ for (const t of openEnvs) {+ killLeftovers({ sockRoot: t.sockRoot });+ t.cleanup();+ }+});++function env(script: TurnScript[], extra: Record<string, string> = {}): PaneTestEnv {+ const t = makePaneTestEnv({+ FAKE_SCRIPT: JSON.stringify(script),+ CONTRACT_FAKE_MAX_MS: "60000",+ ...extra,+ });+ t.env.FAKE_KEYLOG = join(t.tmp, "keylog.txt");+ openEnvs.add(t);+ return t;+}++function keylog(t: PaneTestEnv): string[] {+ const p = t.env.FAKE_KEYLOG as string;+ return existsSync(p) ? readFileSync(p, "utf8").split("\n").filter(Boolean) : [];+}++/** Occurrences of a whole line in the output. */+function lineCount(output: string, line: string): number {+ return output.split("\n").filter((l) => l === line).length;+}++async function until(pred: () => boolean, what: string, ms = 20_000): Promise<void> {+ const end = Date.now() + ms;+ while (!pred()) {+ if (Date.now() > end) throw new Error(`timed out waiting for ${what}`);+ await Bun.sleep(25);+ }+}++const TERMINAL: SlotState[] = ["COMPLETED", "FAILED", "CANCELLED", "TIMEOUT", "EMPTY"];++interface Chan {+ t: PaneTestEnv;+ manager: SessionManager;+ id: string;+ frames: ChannelEvent[];+ info(): ReturnType<SessionManager["getSession"]>;+ output(): string;+ anomalies(): readonly string[];+ terminal(ms?: number): Promise<ReturnType<SessionManager["getSession"]>>;+}++async function channel(o: {+ script: TurnScript[];+ /** null = an interactive (promptless) session; the test sends turn 1 */+ prompt?: string | null;+ binding?: SessionHookBinding | SessionManagerOptions["hookBinding"];+ engine?: HookEngine;+ timeoutSeconds?: number;+ timings?: PaneSessionOptions["timings"];+ magmuxBinary?: string;+ extraEnv?: Record<string, string>;+}): Promise<Chan> {+ const t = env(o.script, o.extraEnv);+ const frames: ChannelEvent[] = [];+ const b = o.binding;+ const manager = new SessionManager({+ maxSessions: 20,+ sessionsDir: join(t.tmp, "sessions"),+ hostPid: 1,+ parentEnv: t.env,+ paneTimings: { replStableMs: 200, corroborationMs: 200, ...o.timings },+ hookEngine: async () => o.engine ?? null,+ ...(b ? { hookBinding: typeof b === "function" ? b : () => b } : {}),+ ...(o.magmuxBinary ? { magmuxBinary: o.magmuxBinary } : {}),+ onStateChange: (_id, ev) => void frames.push(ev),+ });+ const prompt = o.prompt === undefined ? "Reply with the first answer." : o.prompt;+ const id = await manager.createSession({+ model: "fake-scripted",+ cwd: t.cwd,+ ...(prompt ? { prompt } : {}),+ ...(o.timeoutSeconds ? { timeoutSeconds: o.timeoutSeconds } : {}),+ });+ return {+ t,+ manager,+ id,+ frames,+ info: () => manager.getSession(id),+ output: () => manager.getOutput(id).output,+ anomalies: () => manager.getDiagnostics(id).anomalies,+ async terminal(ms = 30_000) {+ await until(() => TERMINAL.includes(manager.getSession(id).state), "a terminal state", ms);+ return manager.getSession(id);+ },+ };+}++/** Cancel whatever is live, wait for the reap, and prove nothing is left. */+async function done(c: Chan): Promise<void> {+ await c.manager.shutdownAll();+ const left = await waitNoOrphans({ sockRoot: c.t.sockRoot }, 10_000);+ killLeftovers({ sockRoot: c.t.sockRoot });+ openEnvs.delete(c.t);+ c.t.cleanup();+ expect(left).toEqual({ processes: [], files: [] });+}++function eventsOf(c: Chan): Array<Record<string, unknown>> {+ const p = join(c.manager.getDiagnostics(c.id).sessionDir, "events.jsonl");+ return readFileSync(p, "utf8")+ .split("\n")+ .filter(Boolean)+ .map((l) => JSON.parse(l));+}++/** The pane's magmux pid, from its record. */+function magmuxPidOf(c: Chan): number {+ const pane = c.info().pane as string;+ const rec = JSON.parse(readFileSync(join(c.t.sockRoot, "panes", `${pane}.json`), "utf8"));+ return rec.magmuxPid as number;+}++function pidAlive(pid: number): boolean {+ try {+ process.kill(pid, 0);+ return true;+ } catch {+ return false;+ }+}++/* ───────────────────────────── team ───────────────────────────── */++interface Team {+ t: PaneTestEnv;+ handle: TeamHandle;+ slot: string;+ response(): string;+ state(): SlotState | undefined;+}++async function team(o: {+ script: TurnScript[];+ binding: SessionHookBinding;+ input?: string;+ extra?: TeamRunOptions;+ timings?: PaneSessionOptions["timings"];+}): Promise<Team> {+ const t = env(o.script);+ const path = join(t.tmp, "team");+ setupSession(path, ["fake-scripted"], o.input ?? "Reply with the first answer.");+ const handle = await startModels(path, {+ parentEnv: t.env,+ spawnPlanner: async () => ({ pinned: new Map<string, string>() }),+ paneTimings: { replStableMs: 200, corroborationMs: 200, ...o.timings },+ hookEngine: async () => null,+ hookBinding: () => o.binding,+ ...o.extra,+ });+ const slot = handle.slots["fake-scripted"] as string;+ return {+ t,+ handle,+ slot,+ response: () => {+ const p = join(path, `response-${slot}.md`);+ return existsSync(p) ? readFileSync(p, "utf8") : "";+ },+ state: () => getStatus(path).models[slot]?.state as SlotState | undefined,+ };+}++async function teamDone(x: Team): Promise<void> {+ await cancelTeamRun(x.handle.sessionPath, undefined, x.handle.runId).catch(() => undefined);+ await x.handle.done;+ const left = await waitNoOrphans({ sockRoot: x.t.sockRoot }, 10_000);+ killLeftovers({ sockRoot: x.t.sockRoot });+ openEnvs.delete(x.t);+ x.t.cleanup();+ expect(left).toEqual({ processes: [], files: [] });+}++/* ───────────────────────────── tests ───────────────────────────── */++describe.skipIf(!MAGMUX)(`the settle hold (§11.5) ${MAGMUX ? "" : NO_MAGMUX_MESSAGE}`, () => {+ describe.concurrent("the latch and the terminal paths of a hold (channel, one-shot)", () => {+ test(+ "H-1 latch: settle() once over ≥ 4 ticks; A1 already in get_output; RUNNING, activity hook, phase SETTLING",+ async () => {+ const ctl = controlled();+ const c = await channel({ script: [{ say: "ANS-ONE" }], binding: ctl.binding });+ try {+ await until(() => ctl.calls.length === 1, "settle()");+ await Bun.sleep(1_200); // ≥ 4 ticker ticks of 250 ms+ expect(ctl.calls.length).toBe(1);+ expect(ctl.calls[0]?.turn).toMatchObject({+ index: 1,+ answer: "ANS-ONE",+ hookCaused: false,+ });+ const info = c.info();+ expect(info.turnsCompleted).toBe(1);+ expect(info.state).toBe("RUNNING");+ expect(info.activity).toBe("hook");+ expect(lineCount(c.output(), "ANS-ONE")).toBe(1);+ const diag = c.manager.getDiagnostics(c.id);+ expect(diag.phase).toBe("SETTLING");+ expect(diag.anomalies.some((a) => a.startsWith("illegal_transition"))).toBe(false);+ expect(c.frames.map((f) => f.type)).not.toContain("waiting_for_input");+ // the frame for RUNNING is "running", never a tool frame named "hook"+ expect(c.frames.some((f) => f.type === "tool_executing")).toBe(false);+ } finally {+ await done(c);+ }+ },+ T+ );++ test(+ "H-2 timeout during the hold: TIMEOUT, A1 once; a late injection changes nothing",+ async () => {+ const ctl = controlled();+ const c = await channel({+ script: [{ say: "ANS-ONE" }, { say: "ANS-NEVER" }],+ binding: ctl.binding,+ timeoutSeconds: 5,+ });+ try {+ await until(() => ctl.calls.length === 1, "settle()");+ const end = await c.terminal(15_000);+ expect(end.state).toBe("TIMEOUT");+ expect(ctl.calls[0]?.signal.aborted).toBe(true);+ expect(ctl.calls[0]?.signal.reason).toBe("terminal");+ ctl.calls[0]?.resolve(inject("HOOK-LATE"));+ await Bun.sleep(600);+ expect(c.info().state).toBe("TIMEOUT");+ expect(keylog(c.t)).not.toContain("HOOK-LATE");+ expect(lineCount(c.output(), "ANS-ONE")).toBe(1);+ } finally {+ await done(c);+ }+ },+ T+ );++ test(+ "H-3 cancel during the hold: CANCELLED, A1 once; a late resolution is ignored",+ async () => {+ const ctl = controlled();+ const c = await channel({ script: [{ say: "ANS-ONE" }], binding: ctl.binding });+ try {+ await until(() => ctl.calls.length === 1, "settle()");+ c.manager.cancelSession(c.id);+ expect(c.info().state).toBe("CANCELLED");+ ctl.calls[0]?.resolve(inject("HOOK-LATE"));+ await Bun.sleep(500);+ expect(c.info().state).toBe("CANCELLED");+ expect(keylog(c.t)).not.toContain("HOOK-LATE");+ expect(lineCount(c.output(), "ANS-ONE")).toBe(1);+ } finally {+ await done(c);+ }+ },+ T+ );++ test(+ "H-4 the child exits 0 during the hold (one-shot): COMPLETED on A1 with the exit note, never child_exited",+ async () => {+ const ctl = controlled();+ const c = await channel({+ script: [{ say: "ANS-ONE", exitAfter: 0, exitDelayMs: 2_000 }],+ binding: ctl.binding,+ });+ try {+ await until(() => ctl.calls.length === 1, "settle()");+ const end = await c.terminal();+ expect(end.state).toBe("COMPLETED");+ expect(end.reason).toBeNull();+ expect(end.detail ?? "").toContain("pane child exited 0");+ expect(ctl.calls[0]?.signal.aborted).toBe(true);+ expect(ctl.calls[0]?.signal.reason).toBe("exit");+ expect(lineCount(c.output(), "ANS-ONE")).toBe(1);+ } finally {+ await done(c);+ }+ },+ T+ );++ test(+ "H-6 a fatal magmux stderr line during the hold: FAILED pane_lost; A1 once (published at record)",+ async () => {+ const ctl = controlled();+ const probe = makePaneTestEnv();+ const wrapper = join(probe.tmp, "magmux-wrapper.sh");+ const trigger = join(probe.tmp, "fatal-now");+ writeFileSync(+ wrapper,+ `#!/bin/bash+REAL=${JSON.stringify(MAGMUX)}+if [ "$1" = "--version" ]; then exec "$REAL" --version; fi+"$REAL" "$@" &+child=$!+trap 'kill -TERM $child 2>/dev/null; wait $child; exit 143' TERM+while kill -0 $child 2>/dev/null; do+ if [ -f "$H6_TRIGGER" ]; then rm -f "$H6_TRIGGER"; echo "magmux: socket lost (test)" >&2; fi+ sleep 0.05+done+wait $child+`+ );+ chmodSync(wrapper, 0o755);+ const c = await channel({+ script: [{ say: "ANS-ONE" }],+ binding: ctl.binding,+ magmuxBinary: wrapper,+ extraEnv: { H6_TRIGGER: trigger },+ });+ try {+ await until(() => ctl.calls.length === 1, "settle()");+ writeFileSync(trigger, "1");+ const end = await c.terminal();+ expect(end.state).toBe("FAILED");+ expect(end.reason).toBe("pane_lost");+ expect(end.detail ?? "").toContain("magmux: socket lost");+ expect(lineCount(c.output(), "ANS-ONE")).toBe(1);+ } finally {+ await done(c);+ probe.cleanup();+ }+ },+ T+ );++ test(+ "H-7 timeout while a chain turn runs: TIMEOUT; get_output holds A1 then A2-part, each once",+ async () => {+ const ctl = controlled();+ const c = await channel({+ script: [{ say: "ANS-ONE" }, { partial: "ANS-TWO-PART" }],+ binding: ctl.binding,+ timeoutSeconds: 6,+ });+ try {+ await until(() => ctl.calls.length === 1, "settle()");+ ctl.calls[0]?.resolve(inject("HOOK-PING"));+ const end = await c.terminal(15_000);+ expect(end.state).toBe("TIMEOUT");+ const out = c.output();+ expect(lineCount(out, "ANS-ONE")).toBe(1);+ expect(lineCount(out, "ANS-TWO-PART")).toBe(1);+ expect(out.indexOf("ANS-ONE")).toBeLessThan(out.indexOf("ANS-TWO-PART"));+ expect(keylog(c.t)).toContain("HOOK-PING");+ } finally {+ await done(c);+ }+ },+ T+ );++ test(+ "H-8 timeout in the second hold: TIMEOUT; A1 and A2 each once, in order",+ async () => {+ const ctl = controlled();+ const c = await channel({+ script: [{ say: "ANS-ONE" }, { say: "ANS-TWO" }],+ binding: ctl.binding,+ timeoutSeconds: 6,+ });+ try {+ await until(() => ctl.calls.length === 1, "settle() 1");+ ctl.calls[0]?.resolve(inject("HOOK-PING"));+ await until(() => ctl.calls.length === 2, "settle() 2");+ const end = await c.terminal(15_000);+ expect(end.state).toBe("TIMEOUT");+ const out = c.output();+ expect(lineCount(out, "ANS-ONE")).toBe(1);+ expect(lineCount(out, "ANS-TWO")).toBe(1);+ expect(out.indexOf("ANS-ONE")).toBeLessThan(out.indexOf("ANS-TWO"));+ expect(ctl.calls[1]?.turn).toMatchObject({ index: 2, hookCaused: true });+ } finally {+ await done(c);+ }+ },+ T+ );+ });++ describe.concurrent("team slots: chains, verdicts, terminal paths", () => {+ test(+ "H-9 team cancelled while chain turn 3 runs: response is A1\\n\\nA2\\n\\nA3-part, outputSize its byte length",+ async () => {+ const ctl = controlled();+ const x = await team({+ script: [{ say: "ANS-ONE" }, { say: "ANS-TWO" }, { partial: "ANS-3-PART" }],+ binding: ctl.binding,+ });+ try {+ await until(() => ctl.calls.length === 1, "settle() 1");+ ctl.calls[0]?.resolve(inject("HOOK-ONE"));+ await until(() => ctl.calls.length === 2, "settle() 2");+ ctl.calls[1]?.resolve(inject("HOOK-TWO"));+ const transcript = getStatus(x.handle.sessionPath).models[x.slot]+ ?.transcriptPath as string;+ await until(+ () => existsSync(transcript) && readFileSync(transcript, "utf8").includes("ANS-3-PART"),+ "the partial answer of turn 3"+ );+ await Bun.sleep(600); // let the follower read it+ await cancelTeamRun(x.handle.sessionPath, undefined, x.handle.runId);+ await until(() => x.state() === "CANCELLED", "CANCELLED");+ const want = "ANS-ONE\n\nANS-TWO\n\nANS-3-PART";+ expect(x.response()).toBe(want);+ expect(getStatus(x.handle.sessionPath).models[x.slot]?.outputSize).toBe(+ Buffer.byteLength(want, "utf8")+ );+ } finally {+ await teamDone(x);+ }+ },+ T+ );++ test(+ "H-10 team cancelled in the second hold: response is A1\\n\\nA2",+ async () => {+ const ctl = controlled();+ const x = await team({+ script: [{ say: "ANS-ONE" }, { say: "ANS-TWO" }],+ binding: ctl.binding,+ });+ try {+ await until(() => ctl.calls.length === 1, "settle() 1");+ ctl.calls[0]?.resolve(inject("HOOK-ONE"));+ await until(() => ctl.calls.length === 2, "settle() 2");+ // the chain so far is already on disk at record, before any verdict+ expect(x.response()).toBe("ANS-ONE\n\nANS-TWO");+ await cancelTeamRun(x.handle.sessionPath, undefined, x.handle.runId);+ await until(() => x.state() === "CANCELLED", "CANCELLED");+ expect(x.response()).toBe("ANS-ONE\n\nANS-TWO");+ } finally {+ await teamDone(x);+ }+ },+ T+ );++ for (const [pattern, state] of [+ ["^VOTE", "COMPLETED"],+ ["^NOPE", "EMPTY"],+ ] as const) {+ test(+ `H-11 require_pattern ${pattern} on a chain: one verdict, response A1\\n\\nA2, ${state}`,+ async () => {+ const ctl = controlled();+ const x = await team({+ script: [{ say: "thinking about it" }, { say: "VOTE: yes" }],+ binding: ctl.binding,+ extra: { requirePattern: pattern },+ });+ try {+ await until(() => ctl.calls.length === 1, "settle() 1");+ ctl.calls[0]?.resolve(inject("HOOK-PING"));+ await until(() => ctl.calls.length === 2, "settle() 2");+ ctl.calls[1]?.resolve(nothing);+ const status = await x.handle.done;+ expect(x.response()).toBe("thinking about it\n\nVOTE: yes");+ expect(status.models[x.slot]?.state).toBe(state);+ if (state === "EMPTY")+ expect(status.models[x.slot]?.error?.reason).toBe("shape_mismatch");+ } finally {+ await teamDone(x);+ }+ },+ T+ );+ }++ test(+ "H-12 team blocked mid-chain: FAILED blocked; response is A1\\n\\nB2",+ async () => {+ const ctl = controlled();+ const x = await team({+ script: [{ say: "ANS-ONE" }, { ask: "ANS-B2" }],+ binding: ctl.binding,+ });+ try {+ await until(() => ctl.calls.length === 1, "settle() 1");+ ctl.calls[0]?.resolve(inject("HOOK-PING"));+ const status = await x.handle.done;+ expect(status.models[x.slot]?.state).toBe("FAILED");+ expect(status.models[x.slot]?.error?.reason).toBe("blocked");+ expect(x.response()).toBe("ANS-ONE\n\nANS-B2");+ } finally {+ await teamDone(x);+ }+ },+ T+ );++ test(+ "H-14 team: an injected turn never accepted → slot COMPLETED, response A1, nothing left RUNNING",+ async () => {+ const ctl = controlled();+ const x = await team({+ script: [{ say: "ANS-ONE" }, { noWitness: true }],+ binding: ctl.binding,+ timings: { admitTimeoutMs: 1_500 },+ });+ try {+ await until(() => ctl.calls.length === 1, "settle() 1");+ ctl.calls[0]?.resolve(inject("HOOK-PING"));+ const status = await x.handle.done;+ expect(status.models[x.slot]?.state).toBe("COMPLETED");+ expect(x.response()).toBe("ANS-ONE");+ expect(ctl.dropped).toEqual([{ text: "HOOK-PING", reason: "send_not_accepted" }]);+ for (const m of Object.values(getStatus(x.handle.sessionPath).models))+ expect(["RUNNING", "AWAITING_INPUT"]).not.toContain(m.state);+ } finally {+ await teamDone(x);+ }+ },+ T+ );++ test(+ "H-32 team variant: the child exits 0 during an injected admission → slot COMPLETED, response A1",+ async () => {+ const ctl = controlled();+ const x = await team({+ script: [{ say: "ANS-ONE" }, { exitOnSubmit: 0 }],+ binding: ctl.binding,+ });+ try {+ await until(() => ctl.calls.length === 1, "settle() 1");+ ctl.calls[0]?.resolve(inject("HOOK-PING"));+ const status = await x.handle.done;+ expect(status.models[x.slot]?.state).toBe("COMPLETED");+ expect(x.response()).toBe("ANS-ONE");+ } finally {+ await teamDone(x);+ }+ },+ T+ );+ });++ describe.concurrent("injected turns never accepted, and caller input during a hold", () => {+ test(+ "H-13 one-shot: no witness → hook_injection_dropped:send_not_accepted, COMPLETED on A1, never AWAITING_INPUT",+ async () => {+ const ctl = controlled();+ const c = await channel({+ script: [{ say: "ANS-ONE" }, { noWitness: true }],+ binding: ctl.binding,+ timings: { admitTimeoutMs: 1_500 },+ });+ try {+ await until(() => ctl.calls.length === 1, "settle()");+ ctl.calls[0]?.resolve(inject("HOOK-PING"));+ const end = await c.terminal();+ expect(end.state).toBe("COMPLETED");+ expect(c.anomalies()).toContain("hook_injection_dropped:send_not_accepted");+ expect(c.frames.map((f) => f.type)).not.toContain("waiting_for_input");+ expect(lineCount(c.output(), "ANS-ONE")).toBe(1);+ expect(ctl.dropped).toEqual([{ text: "HOOK-PING", reason: "send_not_accepted" }]);+ } finally {+ await done(c);+ }+ },+ T+ );++ test(+ "H-15 interactive: no witness → AWAITING_INPUT (today's admit_abandoned), the anomaly, A1 once",+ async () => {+ const ctl = controlled();+ const c = await channel({+ script: [{ say: "ANS-ONE" }, { noWitness: true }],+ binding: ctl.binding,+ prompt: null,+ timings: { admitTimeoutMs: 1_500 },+ });+ try {+ await until(() => c.info().state === "AWAITING_INPUT", "boot");+ c.manager.sendInput(c.id, "Reply with the first answer.");+ await until(() => ctl.calls.length === 1, "settle()");+ ctl.calls[0]?.resolve(inject("HOOK-PING"));+ await until(+ () => c.anomalies().includes("hook_injection_dropped:send_not_accepted"),+ "the anomaly"+ );+ await until(() => c.info().state === "AWAITING_INPUT", "AWAITING_INPUT");+ expect(lineCount(c.output(), "ANS-ONE")).toBe(1);+ } finally {+ await done(c);+ }+ },+ T+ );++ test(+ "H-16 send_input during a hold: the hold ends in that step (caller), CALLER runs, a late HOOK never",+ async () => {+ const ctl = controlled();+ const c = await channel({+ script: [{ say: "ANS-ONE" }, { say: "ANS-CALLER" }],+ binding: ctl.binding,+ });+ try {+ await until(() => ctl.calls.length === 1, "settle()");+ const r = c.manager.sendInput(c.id, "CALLER");+ // admitted in this very step, so nothing is left queued (as for any send whose own+ // step settles a turn, session-manager.test G-row); see the P6 deviation note+ expect(r).toEqual({ success: true, queued: 0 });+ expect(ctl.calls[0]?.signal.aborted).toBe(true);+ expect(ctl.calls[0]?.signal.reason).toBe("caller");+ expect(c.manager.getDiagnostics(c.id).phase).toBe("ADMITTING");+ ctl.calls[0]?.resolve(inject("HOOK"));+ await until(() => c.info().turnsCompleted === 2, "turn 2");+ await until(() => ctl.calls.length === 2, "the second hold");+ ctl.calls[1]?.resolve(nothing);+ await until(() => c.info().state === "AWAITING_INPUT", "AWAITING_INPUT");+ expect(keylog(c.t)).toContain("CALLER");+ expect(keylog(c.t)).not.toContain("HOOK");+ expect(c.info().shape).toBe("interactive");+ expect(lineCount(c.output(), "ANS-ONE")).toBe(1);+ expect(lineCount(c.output(), "ANS-CALLER")).toBe(1);+ } finally {+ await done(c);+ }+ },+ T+ );++ test(+ "H-17 a hold that never resolves (bound 30 s) does not delay the caller: CALLER admitted at once, no watchdog",+ async () => {+ const ctl = controlled({ bound: 30_000 });+ const c = await channel({+ script: [{ say: "ANS-ONE" }, { say: "ANS-CALLER" }],+ binding: ctl.binding,+ });+ try {+ await until(() => ctl.calls.length === 1, "settle()");+ const t0 = Date.now();+ c.manager.sendInput(c.id, "CALLER");+ await until(() => keylog(c.t).includes("CALLER"), "CALLER typed", 2_000);+ expect(Date.now() - t0).toBeLessThan(1_500);+ expect(c.anomalies()).not.toContain("hook_hold_watchdog");+ expect(TERMINAL).not.toContain(c.info().state);+ } finally {+ await done(c);+ }+ },+ T+ );+ });++ describe.concurrent("the chain head's prompt-read result", () => {+ const filePrompt = "Line one of the task.\nLine two of the task.";++ test(+ "H-18 head delivered as a file and not read: FAILED prompt_not_read; get_output holds A1 and A2",+ async () => {+ const ctl = controlled();+ const c = await channel({+ script: [{ noRead: true, say: "ANS-ONE" }, { say: "ANS-TWO" }],+ binding: ctl.binding,+ prompt: filePrompt,+ });+ try {+ await until(() => ctl.calls.length === 1, "settle() 1");+ ctl.calls[0]?.resolve(inject("HOOK-PING"));+ await until(() => ctl.calls.length === 2, "settle() 2");+ ctl.calls[1]?.resolve(nothing);+ const end = await c.terminal();+ expect(end.state).toBe("FAILED");+ expect(end.reason).toBe("prompt_not_read");+ expect(lineCount(c.output(), "ANS-ONE")).toBe(1);+ expect(lineCount(c.output(), "ANS-TWO")).toBe(1);+ } finally {+ await done(c);+ }+ },+ T+ );++ test(+ "H-19 head read in full: COMPLETED",+ async () => {+ const ctl = controlled();+ const c = await channel({+ script: [{ say: "ANS-ONE" }, { say: "ANS-TWO" }],+ binding: ctl.binding,+ prompt: filePrompt,+ });+ try {+ await until(() => ctl.calls.length === 1, "settle() 1");+ ctl.calls[0]?.resolve(inject("HOOK-PING"));+ await until(() => ctl.calls.length === 2, "settle() 2");+ ctl.calls[1]?.resolve(nothing);+ const end = await c.terminal();+ expect(end.state).toBe("COMPLETED");+ // no wait opened between chain turns+ expect(c.frames.map((f) => f.type)).not.toContain("waiting_for_input");+ const waits = join(c.manager.getDiagnostics(c.id).sessionDir, "waits.jsonl");+ expect(existsSync(waits) ? readFileSync(waits, "utf8") : "").toBe("");+ } finally {+ await done(c);+ }+ },+ T+ );++ test(+ "H-20 a hook turn delivered as a file and not read: COMPLETED; anomaly hook_injection_not_read",+ async () => {+ const ctl = controlled();+ const c = await channel({+ script: [{ say: "ANS-ONE" }, { noRead: true, say: "ANS-TWO" }],+ binding: ctl.binding,+ });+ try {+ await until(() => ctl.calls.length === 1, "settle() 1");+ ctl.calls[0]?.resolve(inject("A hook turn\nthat goes as a file."));+ await until(() => ctl.calls.length === 2, "settle() 2");+ ctl.calls[1]?.resolve(nothing);+ const end = await c.terminal();+ expect(end.state).toBe("COMPLETED");+ expect(c.anomalies()).toContain("hook_injection_not_read");+ expect(c.anomalies()).not.toContain("prompt_not_read");+ } finally {+ await done(c);+ }+ },+ T+ );+ });++ describe.concurrent("sessionStart and the hold bound (real binding)", () => {+ test(+ "H-21 a sessionStart injection still running at the first settle holds it: turn 2 runs LATE; one verdict",+ async () => {+ const { engine } = engineOf({+ id: "late",+ on: { sessionStart: () => after(2_000, [{ type: "injectUserTurn", text: "LATE" }]) },+ });+ const c = await channel({ script: [{ say: "ANS-ONE" }, { say: "ANS-TWO" }], engine });+ try {+ const end = await c.terminal();+ expect(end.state).toBe("COMPLETED");+ expect(end.turnsCompleted).toBe(2);+ expect(keylog(c.t)).toContain("LATE");+ expect(lineCount(c.output(), "ANS-ONE")).toBe(1);+ expect(lineCount(c.output(), "ANS-TWO")).toBe(1);+ } finally {+ await done(c);+ }+ },+ T+ );++ test(+ "H-21 control: the hook returns after its timeout → COMPLETED after turn 1, journal timeout, no turn 2",+ async () => {+ const { engine, journal } = engineOf({+ id: "late",+ timeoutMs: 800,+ on: { sessionStart: () => after(2_000, [{ type: "injectUserTurn", text: "LATE" }]) },+ });+ const c = await channel({ script: [{ say: "ANS-ONE" }, { say: "ANS-TWO" }], engine });+ try {+ const end = await c.terminal();+ expect(end.state).toBe("COMPLETED");+ expect(end.turnsCompleted).toBe(1);+ expect(keylog(c.t)).not.toContain("LATE");+ expect(journal.some((j) => j.hookId === "hook:t/late" && j.decision === "timeout")).toBe(+ true+ );+ } finally {+ await done(c);+ }+ },+ T+ );++ for (const [delay, late] of [+ [2_500, true],+ [4_500, false],+ ] as const) {+ test(+ `H-21b sessionStart (timeout 4 s) returns at ${delay} ms, inbox bound 200 ms: no watchdog; ${late ? "turn 2 runs LATE" : "COMPLETED after turn 1"}`,+ async () => {+ const { engine, journal } = engineOf({+ id: "late",+ timeoutMs: 4_000,+ on: { sessionStart: () => after(delay, [{ type: "injectUserTurn", text: "LATE" }]) },+ });+ const t0 = Date.now();+ const c = await channel({+ script: [{ say: "ANS-ONE" }, { say: "ANS-TWO" }],+ engine,+ binding: ({ session, inboxPath }) =>+ createSessionHookBinding(engine, session, inboxPath, { inboxBoundMs: 200 }),+ });+ try {+ const end = await c.terminal();+ expect(end.state).toBe("COMPLETED");+ expect(c.anomalies()).not.toContain("hook_hold_watchdog");+ if (late) {+ expect(end.turnsCompleted).toBe(2);+ expect(keylog(c.t)).toContain("LATE");+ expect(lineCount(c.output(), "ANS-TWO")).toBe(1);+ } else {+ expect(end.turnsCompleted).toBe(1);+ expect(keylog(c.t)).not.toContain("LATE");+ expect(journal.some((j) => j.decision === "timeout")).toBe(true);+ expect(Date.now() - t0).toBeGreaterThanOrEqual(3_500);+ }+ expect(lineCount(c.output(), "ANS-ONE")).toBe(1);+ } finally {+ await done(c);+ }+ },+ T+ );+ }++ test(+ "a sessionStart injection that returns before turn 1 settles is delivered after turn 1 (callerSeq survives)",+ async () => {+ const { engine } = engineOf({+ id: "start",+ on: { sessionStart: () => [{ type: "injectUserTurn", text: "EARLY" }] },+ });+ const c = await channel({+ script: [{ say: "ANS-ONE", delayMs: 600 }, { say: "ANS-TWO" }],+ engine,+ });+ try {+ const end = await c.terminal();+ expect(end.state).toBe("COMPLETED");+ expect(end.turnsCompleted).toBe(2);+ const typed = keylog(c.t);+ expect(typed.indexOf("EARLY")).toBeGreaterThan(0); // after the initial prompt+ } finally {+ await done(c);+ }+ },+ T+ );++ test(+ "cap: an idle hook that always injects gets 3 hook-caused turns, then dropped capped; one verdict",+ async () => {+ let n = 0;+ const { engine } = engineOf({+ id: "more",+ on: { sessionIdle: () => [{ type: "injectUserTurn", text: `MORE-${++n}` }] },+ });+ const c = await channel({+ script: [+ { say: "ANS-1" },+ { say: "ANS-2" },+ { say: "ANS-3" },+ { say: "ANS-4" },+ { say: "ANS-5" },+ ],+ engine,+ });+ try {+ const end = await c.terminal();+ expect(end.state).toBe("COMPLETED");+ expect(end.turnsCompleted).toBe(4);+ expect(keylog(c.t).filter((l) => l.startsWith("MORE-"))).toEqual([+ "MORE-1",+ "MORE-2",+ "MORE-3",+ ]);+ expect(c.anomalies()).toContain("hook_injection_dropped:capped");+ expect(c.frames.map((f) => f.type)).not.toContain("waiting_for_input");+ } finally {+ await done(c);+ }+ },+ T+ );++ test(+ "a hook item queued during a QUESTION waits, and no Esc is ever sent for it",+ async () => {+ const { engine } = engineOf({+ id: "start",+ on: { sessionStart: () => after(800, [{ type: "injectUserTurn", text: "WAITING" }]) },+ });+ const c = await channel({ script: [{ ask: "" }], engine });+ try {+ await until(() => c.manager.getDiagnostics(c.id).phase === "QUESTION", "QUESTION");+ await until(+ () => c.manager.getDiagnostics(c.id).pendingHookInputs === 1,+ "the queued hook item"+ );+ await Bun.sleep(1_200);+ expect(c.manager.getDiagnostics(c.id).phase).toBe("QUESTION");+ expect(keylog(c.t)).not.toContain("<ESC>");+ expect(keylog(c.t)).not.toContain("WAITING");+ expect(c.manager.getDiagnostics(c.id).pendingInputs).toBe(0);+ } finally {+ await done(c);+ }+ },+ T+ );+ });++ describe.concurrent("errors, the watchdog, re-wake", () => {+ test(+ "H-22 settle() rejects: concluded with no injection; hook_hold_error; COMPLETED; A1 once",+ async () => {+ const ctl = controlled();+ const c = await channel({ script: [{ say: "ANS-ONE" }], binding: ctl.binding });+ try {+ await until(() => ctl.calls.length === 1, "settle()");+ ctl.calls[0]?.reject(new Error("binding broke"));+ const end = await c.terminal();+ expect(end.state).toBe("COMPLETED");+ expect(c.anomalies()).toContain("hook_hold_error");+ expect(lineCount(c.output(), "ANS-ONE")).toBe(1);+ } finally {+ await done(c);+ }+ },+ T+ );++ test(+ "H-23 settle() hangs, bound 300 ms: concluded at ~300 ms; hook_hold_watchdog; a later resolve changes nothing",+ async () => {+ const ctl = controlled({ bound: 300 });+ const c = await channel({+ script: [{ say: "ANS-ONE" }, { say: "ANS-X" }],+ binding: ctl.binding,+ });+ try {+ await until(() => ctl.calls.length === 1, "settle()");+ const t0 = Date.now();+ const end = await c.terminal();+ expect(Date.now() - t0).toBeLessThan(1_000);+ expect(end.state).toBe("COMPLETED");+ expect(c.anomalies()).toContain("hook_hold_watchdog");+ expect(ctl.calls[0]?.signal.reason).toBe("watchdog");+ ctl.calls[0]?.resolve(inject("HOOK-LATE"));+ await Bun.sleep(500);+ expect(keylog(c.t)).not.toContain("HOOK-LATE");+ expect(lineCount(c.output(), "ANS-ONE")).toBe(1);+ } finally {+ await done(c);+ }+ },+ T+ );++ test(+ "H-24 re-wake during a hold (real binding): S dropped, the drained proxy P is delivered next; A1 and A1b once",+ async () => {+ let idleCalls = 0;+ let firstSignal: AbortSignal | null = null;+ const { engine } = engineOf({+ id: "idle",+ on: {+ sessionIdle: (ctx) => {+ idleCalls++;+ if (idleCalls === 1) {+ firstSignal = ctx.signal;+ return new Promise((r) =>+ ctx.signal.addEventListener("abort", () =>+ r([{ type: "injectUserTurn", text: "S" }])+ )+ );+ }+ return [];+ },+ },+ });+ const c = await channel({+ script: [+ { say: "ANS-ONE", rewake: { delayMs: 1_500, say: "ANS-ONE-B" } },+ { say: "ANS-P" },+ ],+ engine,+ prompt: null,+ });+ try {+ await until(() => c.info().state === "AWAITING_INPUT", "boot");+ const inboxPath = join(c.manager.getDiagnostics(c.id).sessionDir, "hook-inbox.jsonl");+ writeFileSync(+ inboxPath,+ [+ { v: 1, kind: "stop", req: "r1" },+ { v: 1, kind: "inject", req: "r1", hookId: "hook:c/p", text: "INJECTED-P", at: "x" },+ { v: 1, kind: "end", req: "r1" },+ ]+ .map((l) => `${JSON.stringify(l)}\n`)+ .join("")+ );+ c.manager.sendInput(c.id, "Reply with the first answer.");+ await until(+ () => keylog(c.t).includes("INJECTED-P"),+ "P delivered as the next turn",+ 25_000+ );+ expect((firstSignal as AbortSignal | null)?.reason).toBe("rewake");+ await until(+ () => c.info().turnsCompleted === 2 && c.info().state === "AWAITING_INPUT",+ "turn 2"+ );+ expect(keylog(c.t)).not.toContain("S");+ const out = c.output();+ expect(lineCount(out, "ANS-ONE")).toBe(1);+ expect(lineCount(out, "ANS-ONE-B")).toBe(1);+ expect(lineCount(out, "ANS-P")).toBe(1);+ } finally {+ await done(c);+ }+ },+ T+ );+ });++ describe.concurrent("the exit paths of a hold (M-1)", () => {+ for (const code of [0, 1]) {+ test(+ `H-5 interactive, the child exits ${code} during the hold: ${code === 0 ? "COMPLETED through exit_clean" : "FAILED child_exited"}; A1 once`,+ async () => {+ const ctl = controlled();+ const c = await channel({+ script: [{ say: "ANS-ONE", exitAfter: code, exitDelayMs: 2_000 }],+ binding: ctl.binding,+ prompt: null,+ });+ try {+ await until(() => c.info().state === "AWAITING_INPUT", "boot");+ c.manager.sendInput(c.id, "Reply with the first answer.");+ await until(() => ctl.calls.length === 1, "settle()");+ const end = await c.terminal();+ if (code === 0) {+ expect(end.state).toBe("COMPLETED");+ } else {+ expect(end.state).toBe("FAILED");+ expect(end.reason).toBe("child_exited");+ }+ expect(lineCount(c.output(), "ANS-ONE")).toBe(1);+ } finally {+ await done(c);+ }+ },+ T+ );+ }++ test(+ "H-29 magmux killed during the hold (one-shot): COMPLETED on A1, detail 'magmux exited', signal reason exit",+ async () => {+ const ctl = controlled();+ const c = await channel({ script: [{ say: "ANS-ONE" }], binding: ctl.binding });+ try {+ await until(() => ctl.calls.length === 1, "settle()");+ process.kill(magmuxPidOf(c), "SIGKILL");+ const end = await c.terminal();+ expect(end.state).toBe("COMPLETED");+ expect(end.detail ?? "").toContain("magmux exited");+ expect(ctl.calls[0]?.signal.reason).toBe("exit");+ expect(lineCount(c.output(), "ANS-ONE")).toBe(1);+ } finally {+ await done(c);+ }+ },+ T+ );++ test(+ "H-30 magmux killed during the hold (interactive): FAILED pane_lost with today's 'magmux exited' detail; A1 once",+ async () => {+ const ctl = controlled();+ const c = await channel({+ script: [{ say: "ANS-ONE" }],+ binding: ctl.binding,+ prompt: null,+ });+ try {+ await until(() => c.info().state === "AWAITING_INPUT", "boot");+ c.manager.sendInput(c.id, "Reply with the first answer.");+ await until(() => ctl.calls.length === 1, "settle()");+ process.kill(magmuxPidOf(c), "SIGKILL");+ const end = await c.terminal();+ expect(end.state).toBe("FAILED");+ expect(end.reason).toBe("pane_lost");+ expect(end.detail ?? "").toContain("magmux exited");+ expect(lineCount(c.output(), "ANS-ONE")).toBe(1);+ } finally {+ await done(c);+ }+ },+ T+ );++ test(+ "H-31 the hold ends inside the exit-capture window: dropped pane_exited, nothing typed, COMPLETED with the exit note",+ async () => {+ const ctl = controlled();+ const c = await channel({+ script: [{ say: "ANS-ONE", exitAfter: 0, exitDelayMs: 2_000 }],+ binding: ctl.binding,+ timings: { exitCaptureDelayMs: 500 },+ });+ try {+ await until(() => ctl.calls.length === 1, "settle()");+ const pid = c.info().panePid as number;+ await until(() => !pidAlive(pid), "the child's exit", 10_000);+ await Bun.sleep(100);+ ctl.calls[0]?.resolve(inject("HOOK-X"));+ const end = await c.terminal();+ expect(end.state).toBe("COMPLETED");+ expect(end.detail ?? "").toContain("pane child exited 0");+ expect(c.anomalies()).toContain("hook_injection_dropped:pane_exited");+ expect(keylog(c.t)).not.toContain("HOOK-X");+ expect(lineCount(c.output(), "ANS-ONE")).toBe(1);+ } finally {+ await done(c);+ }+ },+ T+ );++ test(+ "H-32 one-shot: the child exits 0 during an injected admission → send_not_accepted; COMPLETED on A1 with the exit note",+ async () => {+ const ctl = controlled();+ const c = await channel({+ script: [{ say: "ANS-ONE" }, { exitOnSubmit: 0 }],+ binding: ctl.binding,+ });+ try {+ await until(() => ctl.calls.length === 1, "settle()");+ ctl.calls[0]?.resolve(inject("HOOK-PING"));+ const end = await c.terminal();+ expect(end.state).toBe("COMPLETED");+ expect(end.detail ?? "").toContain("pane child exited 0");+ expect(c.anomalies()).toContain("hook_injection_dropped:send_not_accepted");+ expect(lineCount(c.output(), "ANS-ONE")).toBe(1);+ } finally {+ await done(c);+ }+ },+ T+ );++ for (const code of [0, 1]) {+ test(+ `H-33 interactive: the child exits ${code} during an injected admission → the anomaly; ${code === 0 ? "COMPLETED (exit_clean)" : "FAILED child_exited"}`,+ async () => {+ const ctl = controlled();+ const c = await channel({+ script: [{ say: "ANS-ONE" }, { exitOnSubmit: code }],+ binding: ctl.binding,+ prompt: null,+ });+ try {+ await until(() => c.info().state === "AWAITING_INPUT", "boot");+ c.manager.sendInput(c.id, "Reply with the first answer.");+ await until(() => ctl.calls.length === 1, "settle()");+ ctl.calls[0]?.resolve(inject("HOOK-PING"));+ const end = await c.terminal();+ expect(c.anomalies()).toContain("hook_injection_dropped:send_not_accepted");+ if (code === 0) expect(end.state).toBe("COMPLETED");+ else {+ expect(end.state).toBe("FAILED");+ expect(end.reason).toBe("child_exited");+ }+ expect(lineCount(c.output(), "ANS-ONE")).toBe(1);+ } finally {+ await done(c);+ }+ },+ T+ );+ }++ test(+ "H-34 interactive: an unread hook-turn file is hook_injection_not_read, never prompt_not_read",+ async () => {+ const ctl = controlled();+ const c = await channel({+ script: [{ say: "ANS-ONE" }, { noRead: true, say: "ANS-TWO" }],+ binding: ctl.binding,+ prompt: null,+ });+ try {+ await until(() => c.info().state === "AWAITING_INPUT", "boot");+ c.manager.sendInput(c.id, "Reply with the first answer.");+ await until(() => ctl.calls.length === 1, "settle() 1");+ ctl.calls[0]?.resolve(inject("A hook turn\nthat goes as a file."));+ await until(() => ctl.calls.length === 2, "settle() 2");+ ctl.calls[1]?.resolve(nothing);+ await until(+ () => c.info().state === "AWAITING_INPUT" && c.info().turnsCompleted === 2,+ "idle"+ );+ await Bun.sleep(400);+ expect(c.anomalies()).toContain("hook_injection_not_read");+ const keys = eventsOf(c)+ .filter((e) => e.type === "anomaly")+ .map((e) => e.key);+ expect(keys).not.toContain("prompt_not_read");+ expect(c.frames.some((f) => f.extraMeta?.prompt_not_read === "true")).toBe(false);+ } finally {+ await done(c);+ }+ },+ T+ );++ test(+ "H-34 control: a caller send_input delivered as a file and not read → prompt_not_read as today",+ async () => {+ const c = await channel({+ script: [{ say: "ANS-ONE" }, { noRead: true, say: "ANS-TWO" }],+ prompt: null,+ });+ try {+ await until(() => c.info().state === "AWAITING_INPUT", "boot");+ c.manager.sendInput(c.id, "Reply with the first answer.");+ await until(+ () => c.info().turnsCompleted === 1 && c.info().state === "AWAITING_INPUT",+ "turn 1"+ );+ c.manager.sendInput(c.id, "A caller turn\nthat goes as a file.");+ await until(+ () => c.info().turnsCompleted === 2 && c.info().state === "AWAITING_INPUT",+ "turn 2"+ );+ await Bun.sleep(400);+ const keys = eventsOf(c)+ .filter((e) => e.type === "anomaly")+ .map((e) => e.key);+ expect(keys).toContain("prompt_not_read");+ } finally {+ await done(c);+ }+ },+ T+ );+ });++ /* ───────────────────────── PaneSession directly (snapshot, no-hold, no binding) ───────────────────────── */++ describe.concurrent(+ "PaneSession: the snapshot during a hold, the no-hold paths, no binding",+ () => {+ interface Direct {+ s: PaneSession;+ t: PaneTestEnv;+ uuid: string;+ transitions: Array<[SlotState, SlotState]>;+ recorded: SettledTurn[];+ decided: SettledTurn[];+ }++ async function direct(o: {+ script: TurnScript[];+ hooks?: SessionHookBinding;+ }): Promise<Direct> {+ const t = env(o.script);+ const uuid = newSessionUuid();+ const transitions: Array<[SlotState, SlotState]> = [];+ const recorded: SettledTurn[] = [];+ const decided: SettledTurn[] = [];+ const s = await startPaneSession({+ kind: "t",+ label: "01",+ callerFlags: [],+ spawnModel: "fake-scripted",+ cwd: t.cwd,+ sessionUuid: uuid,+ transcriptPath: t.transcriptPathFor(uuid),+ slotEnv: {},+ shape: "one-shot",+ initialPrompt: "Reply with the first answer.",+ readAvailable: true,+ parentEnv: t.env,+ sockRoot: t.sockRoot,+ decide: (turn) => {+ decided.push(turn);+ return { state: "COMPLETED" };+ },+ onBlocked: () => ({ state: "FAILED", reason: "blocked" }),+ onTransition: (x) => void transitions.push([x.from, x.to]),+ onTurnRecorded: (turn) => void recorded.push(turn),+ timings: { replStableMs: 200, corroborationMs: 200 },+ ...(o.hooks ? { hooks: o.hooks } : {}),+ });+ return { s, t, uuid, transitions, recorded, decided };+ }++ async function directDone(d: Direct): Promise<PaneSnapshot> {+ d.s.cancel();+ await d.s.reaped();+ const left = await waitNoOrphans({ sockRoot: d.t.sockRoot, ids: [d.uuid] });+ killLeftovers({ sockRoot: d.t.sockRoot, ids: [d.uuid] });+ openEnvs.delete(d.t);+ d.t.cleanup();+ expect(left).toEqual({ processes: [], files: [] });+ return d.s.snapshot();+ }++ test(+ "H-25 snapshot during a hold: state RUNNING, activity hook, phase SETTLING, turnEndRecordMissing false",+ async () => {+ const ctl = controlled();+ const d = await direct({ script: [{ say: "ANS-ONE" }], hooks: ctl.binding });+ try {+ await until(() => ctl.calls.length === 1, "settle()");+ const snap = d.s.snapshot();+ expect(snap.state).toBe("RUNNING");+ expect(snap.activity).toBe("hook");+ expect(snap.phase).toBe("SETTLING");+ expect(snap.turnEndRecordMissing).toBe(false);+ expect(snap.pendingHookInputs).toBe(0);+ // published at record, before any transition; not yet decided+ expect(d.recorded.map((r) => r.answer)).toEqual(["ANS-ONE"]);+ expect(d.decided).toEqual([]);+ expect(d.s.chainText()).toBe("ANS-ONE");+ } finally {+ await directDone(d);+ }+ },+ T+ );++ test(+ "H-26 hasIdleWork false: SETTLING never entered, settle() never called, the verdict in the settling step",+ async () => {+ const ctl = controlled({ idle: false });+ const d = await direct({ script: [{ say: "ANS-ONE" }], hooks: ctl.binding });+ try {+ await d.s.terminal;+ expect(ctl.calls).toEqual([]);+ expect(d.transitions).toEqual([+ ["STARTING", "RUNNING"],+ ["RUNNING", "COMPLETED"],+ ]);+ expect(d.recorded).toHaveLength(1);+ expect(d.decided).toHaveLength(1);+ expect(d.s.snapshot().anomalies.some((a) => a.startsWith("illegal_transition"))).toBe(+ false+ );+ } finally {+ await directDone(d);+ }+ },+ T+ );++ test(+ "H-27 end record and exit in the same tick: no hold, settle() never called, COMPLETED with the exit note",+ async () => {+ const ctl = controlled();+ const d = await direct({+ script: [{ say: "ANS-ONE", exitAfter: 0, exitDelayMs: 0 }],+ hooks: ctl.binding,+ });+ try {+ const snap = await d.s.terminal;+ expect(ctl.calls).toEqual([]);+ expect(snap.state).toBe("COMPLETED");+ expect(snap.detail ?? "").toContain("pane child exited 0");+ expect(d.decided.map((t) => t.answer)).toEqual(["ANS-ONE"]);+ } finally {+ await directDone(d);+ }+ },+ T+ );++ test(+ "H-28 binding absent: today's events — no record callback, no SETTLING, chain fields at their no-hook values",+ async () => {+ const d = await direct({ script: [{ say: "ANS-ONE" }] });+ try {+ const snap = await d.s.terminal;+ expect(snap.state).toBe("COMPLETED");+ expect(d.recorded).toEqual([]);+ expect(d.transitions).toEqual([+ ["STARTING", "RUNNING"],+ ["RUNNING", "COMPLETED"],+ ]);+ const turn = d.decided[0] as SettledTurn;+ expect(turn.chainAnswers).toEqual([]);+ expect(turn.chainDelivery).toEqual(turn.delivery);+ expect(turn.hookTurns).toBe(0);+ expect(turn.hookCaused).toBe(false);+ expect(snap.pendingHookInputs).toBe(0);+ } finally {+ await directDone(d);+ }+ },+ T+ );+ }+ );++ describe.concurrent("the hold's result is applied only on current evidence", () => {+ const screenShows = (c: Chan, text: string) =>+ (c.manager.captureSession(c.id) as CaptureResult).lines.some((l) => l.includes(text));+ /** The fake starts its re-wake when this file exists: after the test saw the hold. */+ const gateFile = () => join(tmpdir(), `claudish-rewake-gate-${randomUUID()}`);++ test(+ "a re-wake whose working row shows before its records: the injection is never typed; its result is abandoned rewake",+ async () => {+ const ctl = controlled();+ const gate = gateFile();+ const c = await channel({+ script: [+ {+ say: "ANS-ONE",+ rewake: { gateFile: gate, delayMs: 100, workingMs: 2_500, say: "ANS-ONE-B" },+ },+ { say: "ANS-NEVER" },+ ],+ binding: ctl.binding,+ });+ try {+ await until(() => ctl.calls.length === 1, "the hold");+ writeFileSync(gate, "");+ // The screen shows the re-woken turn working; the transcript has nothing of it yet.+ await until(() => screenShows(c, "Simmering"), "the re-wake's working row");+ ctl.calls[0]?.resolve(inject("HOOK-LATE"));+ await until(+ () => ctl.calls.length === 2 || keylog(c.t).includes("HOOK-LATE"),+ "the re-settle, or the injection typed over the running turn"+ );+ expect(keylog(c.t)).not.toContain("HOOK-LATE");+ expect(ctl.abandoned).toEqual([{ text: "HOOK-LATE", reason: "rewake" }]);+ expect(ctl.calls[1]?.turn.index).toBe(1);+ expect(ctl.calls[1]?.turn.answer).toContain("ANS-ONE-B");+ ctl.calls[1]?.resolve(nothing);+ const end = await c.terminal();+ expect(end.state).toBe("COMPLETED");+ const out = c.output();+ expect(lineCount(out, "ANS-ONE")).toBe(1);+ expect(lineCount(out, "ANS-ONE-B")).toBe(1);+ } finally {+ rmSync(gate, { force: true });+ await done(c);+ }+ },+ T+ );++ test(+ "a re-wake already in the transcript, with no frame since: the result arrives, the injection is never typed",+ async () => {+ const ctl = controlled();+ const gate = gateFile();+ const c = await channel({+ script: [+ {+ say: "ANS-ONE",+ rewake: { gateFile: gate, delayMs: 100, quietMs: 3_000, say: "ANS-ONE-B" },+ },+ { say: "ANS-NEVER" },+ ],+ binding: ctl.binding,+ });+ try {+ await until(() => ctl.calls.length === 1, "the hold");+ writeFileSync(gate, "");+ const transcript = c.t.transcriptPathFor(c.info().claudeSessionId as string);+ // Resolve the instant the re-wake's records are on disk: the pane's last poll+ // (frame-debounced, or the 1 s backstop) is older than them.+ const end = Date.now() + 20_000;+ while (!readFileSync(transcript, "utf8").includes("ANS-ONE-B")) {+ if (Date.now() > end) throw new Error("timed out waiting for the re-wake's records");+ await Bun.sleep(2);+ }+ ctl.calls[0]?.resolve(inject("HOOK-LATE"));+ await until(+ () => ctl.calls.length === 2 || keylog(c.t).includes("HOOK-LATE"),+ "the re-settle, or the injection typed over the running turn"+ );+ expect(keylog(c.t)).not.toContain("HOOK-LATE");+ // Either the result came back (abandoned rewake), or, rarely, the pane's own+ // backstop poll saw the records first and ended the hold before it arrived.+ if ((ctl.calls[0]?.signal.reason as string | undefined) !== "rewake")+ expect(ctl.abandoned).toEqual([{ text: "HOOK-LATE", reason: "rewake" }]);+ ctl.calls[1]?.resolve(nothing);+ expect((await c.terminal()).state).toBe("COMPLETED");+ expect(lineCount(c.output(), "ANS-ONE-B")).toBe(1);+ } finally {+ rmSync(gate, { force: true });+ await done(c);+ }+ },+ T+ );++ test(+ "a result that waited for a working row: a re-wake written as the row clears ends the hold; the injection is never typed",+ async () => {+ const ctl = controlled();+ const gate = gateFile();+ const c = await channel({+ script: [+ {+ say: "ANS-ONE",+ rewake: {+ gateFile: gate,+ delayMs: 100,+ workingMs: 1_500,+ clearWithRecords: true,+ quietMs: 3_000,+ say: "ANS-ONE-B",+ },+ },+ { say: "ANS-NEVER" },+ ],+ binding: ctl.binding,+ // A frame polls only 3 s after the last poll, so the frame that clears the row,+ // 1.5 s after the result's own read, comes with a view that predates the records.+ timings: { pollDebounceMs: 3_000, pollBackstopMs: 6_000 },+ });+ try {+ await until(() => ctl.calls.length === 1, "the hold");+ writeFileSync(gate, "");+ // The result arrives while the screen shows work, so it waits for the screen.+ await until(() => screenShows(c, "Simmering"), "the working row");+ ctl.calls[0]?.resolve(inject("HOOK-LATE"));+ // The row then clears in the same instant the re-wake's records land: only a+ // read made at admission sees them.+ await until(+ () => ctl.calls.length === 2 || keylog(c.t).includes("HOOK-LATE"),+ "the re-settle, or the injection typed over the running turn"+ );+ expect(keylog(c.t)).not.toContain("HOOK-LATE");+ expect(ctl.abandoned).toEqual([{ text: "HOOK-LATE", reason: "rewake" }]);+ ctl.calls[1]?.resolve(nothing);+ expect((await c.terminal()).state).toBe("COMPLETED");+ expect(lineCount(c.output(), "ANS-ONE-B")).toBe(1);+ } finally {+ rmSync(gate, { force: true });+ await done(c);+ }+ },+ T+ );+ });++ describe.concurrent("hook text never reaches the command path", () => {+ test(+ "an injection that starts with a slash is dropped delivery_unavailable and never typed",+ async () => {+ const ctl = controlled();+ const c = await channel({+ script: [{ say: "ANS-ONE" }, { say: "ANS-NEVER" }],+ binding: ctl.binding,+ prompt: null,+ });+ try {+ await until(() => c.info().state === "AWAITING_INPUT", "boot");+ c.manager.sendInput(c.id, "Reply with the first answer.");+ await until(() => ctl.calls.length === 1, "the hold");+ // the double skips the action rules a real binding applies+ ctl.calls[0]?.resolve(inject("/model opus"));+ await until(+ () => c.info().state === "AWAITING_INPUT" && c.info().turnsCompleted === 1,+ "idle after the dropped injection"+ );+ await Bun.sleep(300);+ expect(keylog(c.t)).toEqual(["Reply with the first answer."]);+ expect(ctl.dropped).toEqual([{ text: "/model opus", reason: "delivery_unavailable" }]);+ } finally {+ await done(c);+ }+ },+ T+ );+ });++ describe.concurrent("an interactive turn a hook follows gets its own verdict", () => {+ test(+ "turn 1 ends in an API error: FAILED api_error before any injection; the injection is dropped session_ended",+ async () => {+ const ctl = controlled();+ const c = await channel({+ script: [{ apiError: "API Error: 500 upstream failed" }, { say: "ANS-NEVER" }],+ binding: ctl.binding,+ prompt: null,+ });+ try {+ await until(() => c.info().state === "AWAITING_INPUT", "boot");+ c.manager.sendInput(c.id, "Reply with the first answer.");+ await until(() => ctl.calls.length === 1, "the hold");+ ctl.calls[0]?.resolve(inject("HOOK-AFTER-ERROR"));+ await until(+ () => TERMINAL.includes(c.info().state) || keylog(c.t).includes("HOOK-AFTER-ERROR"),+ "the verdict, or the injection typed"+ );+ expect(keylog(c.t)).not.toContain("HOOK-AFTER-ERROR");+ const end = await c.terminal();+ expect(end.state).toBe("FAILED");+ expect(end.reason).toBe("api_error");+ expect(ctl.dropped).toEqual([{ text: "HOOK-AFTER-ERROR", reason: "session_ended" }]);+ } finally {+ await done(c);+ }+ },+ T+ );++ test(+ "turn 1's task file was not read: prompt_not_read is recorded, then the injection is the next turn",+ async () => {+ const ctl = controlled();+ const c = await channel({+ script: [{ noRead: true, say: "ANS-ONE" }, { say: "ANS-TWO" }],+ binding: ctl.binding,+ prompt: null,+ });+ try {+ await until(() => c.info().state === "AWAITING_INPUT", "boot");+ c.manager.sendInput(c.id, "A caller turn\nthat goes as a file.");+ await until(() => ctl.calls.length === 1, "the hold");+ ctl.calls[0]?.resolve(inject("HOOK-NEXT"));+ await until(() => ctl.calls.length === 2, "the injected turn's hold");+ ctl.calls[1]?.resolve(nothing);+ await until(+ () => c.info().state === "AWAITING_INPUT" && c.info().turnsCompleted === 2,+ "idle"+ );+ expect(keylog(c.t)).toContain("HOOK-NEXT");+ const notRead = eventsOf(c).filter(+ (e) => e.type === "anomaly" && e.key === "prompt_not_read"+ );+ expect(notRead.map((e) => e.turn)).toEqual([1]);+ } finally {+ await done(c);+ }+ },+ T+ );+ });+});diff --git a/packages/cli/src/pane/test-helpers/fake-interactive-child.ts b/packages/cli/src/pane/test-helpers/fake-interactive-child.tsindex 9bf37b49..04e8bcb1 100755--- a/packages/cli/src/pane/test-helpers/fake-interactive-child.ts+++ b/packages/cli/src/pane/test-helpers/fake-interactive-child.ts@@ -19,12 +19,27 @@* - "claude" mode (`--fake-as-claude` first, via a CLAUDE_PATH wrapper): the REAL claudish* launches it as Claude Code; it dumps argv, env, cwd and the `--settings` content to* `FAKE_CLAUDE_DUMP`, then emulates the REPL in marker mode.+ * - proxied "claude" mode (`FAKE_CLAUDE_PROXY=1`, hook-system §11.2): each delivered+ * prompt is POSTed as a streaming `/v1/messages` to `ANTHROPIC_BASE_URL` (the real+ * child claudish's proxy) with `metadata.user_id` carrying the `--session-id`; the+ * SSE that comes back is folded, and the RECEIVED text is written as the assistant+ * record, then `turn_duration`. Whatever the proxy did, rewriting included, is in+ * the transcript. `FAKE_CLAUDE_SIDE=<text>` also fires one side request on turn 1+ * that is NOT awaited (a background subagent's stream) before the turn ends.** A file-delivered prompt (the fixed template) is read back exactly as Read returns it* (numbered lines, `toolUseResult.file`), reconstructed (split markers joined), and* answered `ANSWER <model> <sha1(reconstructed)[0..8]>`, so a test can compare the hash* with sha1 of the caller's prompt and see any loss. A typed line hashes the line.*+ * Scripted mode (`--model fake-scripted`, hook-system §11.5): `FAKE_SCRIPT` is a JSON array+ * with one entry per submitted turn (see `TurnScript`), so a test fixes each turn's answer,+ * a partial answer that never ends, a dialog, a missing witness, an unread task file, a+ * re-wake after the answer, or an exit. `FAKE_KEYLOG` names a file that receives every+ * submitted line and every Esc, so a test can prove what was (never) typed.+ * `FAKE_INITIAL_PROMPT` is a prompt given on the command line: its user record is written+ * before the REPL is first drawn (scripted mode).+ ** Gaps come from `FAKE_GAP_MS_<NAME>` so scenarios keep their ORDER at a fraction of real* time. `CONTRACT_FAKE_MAX_MS` (default 20 s) is a safety exit so a broken test never* leaves a REPL behind. `CONTRACT_FAKE_SIGTERM_MARKER` is written on SIGTERM or SIGHUP.@@ -535,6 +550,74 @@ function finishedRow(): string {return "✻ Cogitated for 1s";}+/* ───────────────────────────── scripted turns ───────────────────────────── */++/** One turn of `FAKE_SCRIPT` (scenario `scripted`). Every field is optional. */+interface TurnScript {+ /** the exact answer text (default: `ANSWER <model> <sha8>`) */+ say?: string;+ /** stream this text with no ending stop_reason and no end record, then hang */+ partial?: string;+ /** write this text (if non-empty), then open an AskUserQuestion and wait for Esc */+ ask?: string;+ /** never write the user record: the turn is never accepted */+ noWitness?: boolean;+ /** exit with this code as soon as the line is submitted (before any witness) */+ exitOnSubmit?: number;+ /** a file-delivered prompt is not read at all */+ noRead?: boolean;+ /** the turn ends with this API error record instead of an answer */+ apiError?: string;+ /** wait this long before the answer */+ delayMs?: number;+ /**+ * after the answer and its end record: a background notification, then a continuation.+ * `workingMs`: the working row shows this long BEFORE any record of the re-wake is+ * written (the screen leads the transcript). `quietMs`: the re-wake's records are+ * written and the screen is not redrawn for this long, so a reader sees them only by+ * polling the transcript. `gateFile`: the re-wake waits for this file to exist before+ * its `delayMs`, so a test starts it at a point it chose (a hold it observed).+ * `clearWithRecords` (with `workingMs`): the cleared row is drawn in the same instant+ * the records are written, so the frame that shows an idle screen is the first sign of+ * the re-wake, and only a transcript read made after it sees the records.+ */+ rewake?: {+ delayMs: number;+ say: string;+ workingMs?: number;+ quietMs?: number;+ gateFile?: string;+ clearWithRecords?: boolean;+ };+ /** after the answer: exit with this code, `exitDelayMs` (default 20) later */+ exitAfter?: number;+ exitDelayMs?: number;+}++const SCRIPT: TurnScript[] = (() => {+ try {+ const v = JSON.parse(env.FAKE_SCRIPT ?? "[]");+ return Array.isArray(v) ? (v as TurnScript[]) : [];+ } catch {+ return [];+ }+})();++function scriptOf(n: number): TurnScript {+ return SCRIPT[n - 1] ?? {};+}++/** Every submitted line and every Esc, one per line, for "never typed" assertions. */+function keylog(entry: string): void {+ const f = env.FAKE_KEYLOG;+ if (!f) return;+ try {+ appendFileSync(f, `${entry}\n`);+ } catch {+ // diagnostics only+ }+}+/* ───────────────────────────── turns ───────────────────────────── */const TEMPLATE_RE = /^Your task is in the file `([^`]+)`\./;@@ -613,6 +696,7 @@ function deliveredOf(line: string): Delivered {if (!m) return { content: line, file: null };const file = m[1] as string;if (scenario === "no_read") return { content: "", file };+ if (scenario === "scripted" && scriptOf(turn).noRead) return { content: "", file };const content = readTurnFile(file, line, {narrate: scenario === "narrate_then_read",partial: scenario === "partial_read",@@ -643,7 +727,63 @@ function effectiveScenario(content: string): string {return scenario;}+/* ───────────────────────────── proxied "claude" mode ───────────────────────────── */++const PROXIED = asClaude && env.FAKE_CLAUDE_PROXY === "1";++/** One streaming /v1/messages to the child claudish's proxy; the folded text of the reply. */+async function proxiedAnswer(content: string): Promise<string> {+ const base = (env.ANTHROPIC_BASE_URL ?? "").replace(/\/$/, "");+ const res = await fetch(`${base}/v1/messages`, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ "x-api-key": env.ANTHROPIC_API_KEY ?? "placeholder",+ "anthropic-version": "2023-06-01",+ },+ body: JSON.stringify({+ model: model,+ max_tokens: 1024,+ stream: true,+ messages: [{ role: "user", content }],+ metadata: { user_id: JSON.stringify({ session_id: sessionId }) },+ }),+ });+ const raw = await res.text();+ if (!res.ok) return `PROXY ERROR ${res.status}: ${raw.slice(0, 200)}`;+ let text = "";+ for (const event of raw.split(/\r?\n\r?\n/)) {+ for (const line of event.split(/\r?\n/)) {+ if (!line.startsWith("data:")) continue;+ try {+ const d = JSON.parse(line.slice(5).trim()) as {+ type?: string;+ delta?: { type?: string; text?: string };+ };+ if (d.type === "content_block_delta" && d.delta?.type === "text_delta")+ text += d.delta.text ?? "";+ } catch {+ // [DONE] or a keepalive+ }+ }+ }+ return text;+}++let sideFired = false;+async function answerTurn(content: string): Promise<void> {+ if (PROXIED) {+ if (env.FAKE_CLAUDE_SIDE && !sideFired) {+ sideFired = true;+ void proxiedAnswer(env.FAKE_CLAUDE_SIDE).catch(() => "");+ }+ const text = await proxiedAnswer(content).catch((e) => `PROXY FAILED ${String(e)}`);+ rec.text(text);+ rec.td();+ showHistory(`⏺ ${text}`, finishedRow());+ return;+ }rec.text(answerFor(content));rec.td();showHistory(`⏺ ${answerFor(content)}`, finishedRow());@@ -655,6 +795,60 @@ function waitEsc(): Promise<void> {});}+/** A settled turn woken by a background notification, then continued (`TurnScript.rewake`). */+async function rewakeAfter(rw: NonNullable<TurnScript["rewake"]>): Promise<void> {+ if (rw.gateFile) while (!existsSync(rw.gateFile)) await sleep(20);+ await sleep(rw.delayMs);+ if (rw.workingMs) {+ S.working = "✶ Simmering… (thinking)";+ render();+ await sleep(rw.workingMs);+ S.working = null;+ }+ emit(T.bgNotify);+ rec.text(rw.say);+ rec.td();+ if (rw.clearWithRecords) render();+ if (rw.quietMs) await sleep(rw.quietMs);+ showHistory(`⏺ ${rw.say}`, finishedRow());+}++/** One scripted turn (`FAKE_SCRIPT`): the transcript and screen of a real REPL turn. */+async function runScripted(sc: TurnScript, d: Delivered): Promise<void> {+ const c = d.content;+ if (sc.delayMs) await sleep(sc.delayMs);+ if (sc.partial !== undefined) {+ rec.text(sc.partial, null);+ S.history.push(`⏺ ${sc.partial}`);+ S.working = "✶ Simmering… (thinking)";+ render();+ await new Promise(() => {});+ return;+ }+ if (sc.ask !== undefined) {+ if (sc.ask) {+ rec.text(sc.ask, "tool_use");+ S.history.push(`⏺ ${sc.ask}`);+ }+ return askUser("ask_user", c);+ }+ if (sc.apiError !== undefined) {+ rec.apiError(sc.apiError);+ rec.td();+ showHistory(`⏺ ${sc.apiError}`, finishedRow());+ return;+ }+ const text = sc.say ?? answerFor(c);+ rec.text(text);+ rec.td();+ showHistory(`⏺ ${text}`, finishedRow());+ if (sc.rewake) await rewakeAfter(sc.rewake);+ if (sc.exitAfter !== undefined) {+ await sleep(sc.exitDelayMs ?? 20);+ return quit(sc.exitAfter);+ }+}+async function runScenario(name: string, d: Delivered): Promise<void> {const c = d.content;switch (name) {@@ -992,7 +1186,7 @@ async function localCommandTurn(name: string, args: string): Promise<void> {showHistory(` ⎿ ${stdout.replace(/\x1b\[[0-9;]*m/g, "")}`);}-async function submit(line: string): Promise<void> {+async function submit(line: string, opts: { argv?: boolean } = {}): Promise<void> {turn++;busy = true;try {@@ -1006,6 +1200,27 @@ async function submit(line: string): Promise<void> {].includes(scenario))return await screenOnlyTurn(line);+ if (scenario === "scripted") {+ const sc = scriptOf(turn);+ if (sc.exitOnSubmit !== undefined) {+ await sleep(30);+ return await quit(sc.exitOnSubmit);+ }+ if (sc.noWitness) {+ S.history.push(`❯ ${line.split("\n")[0]}`);+ return;+ }+ // A command-line prompt is written at once, before the REPL is drawn.+ if (!opts.argv) await sleep(gap("WITNESS", 50));+ rec.user(line);+ S.history.push(`❯ ${line.split("\n")[0]}`);+ S.working = "✶ Simmering… (thinking)";+ render();+ await sleep(gap("THINK", 50));+ const d = deliveredOf(line);+ S.working = null;+ return await runScripted(sc, d);+ }if (scenario === "slow_prompt_hook") {S.working = "✶ Blanching… (running UserPromptSubmit hook · 2s)";render();@@ -1051,6 +1266,8 @@ function onEnter(): void {const text = S.box;if (!text.trim() || S.vim) return;if (ignoredEnters++ < ignoredEnterLimit || scenario === "never_submit_transcript_off") return;+ // only a line Enter submits is logged: an ignored Enter submitted nothing+ keylog(text);if (scenario === "menu_eats_enter" && !menuEaten) {menuEaten = true; // the first Enter only closes a menu (phase-2 keylog: Esc/Enter on menus)S.menu = null;@@ -1090,6 +1307,7 @@ function acceptText(text: string): void {}function onEsc(): void {+ keylog("<ESC>");if (swallowUntilEsc) {swallowUntilEsc = false;S.full = null;@@ -1325,6 +1543,10 @@ async function boot(): Promise<void> {mkdirSync(dirname(transcript), { recursive: true });writeFileSync(transcript, "");}+ // `claude "<prompt>"`: Claude Code may write the prompt's record before the REPL+ // is drawn (hook-system §7.5: the interactive driver's first turn opens at offset 0).+ const initial = env.FAKE_INITIAL_PROMPT;+ if (initial) void submit(initial, { argv: true });process.stdout.write("\x1b[?1049h\x1b[?2004h");S.booted = true;S.ghost = scenario === "idle_suggestion";diff --git a/packages/cli/src/team-orchestrator.ts b/packages/cli/src/team-orchestrator.tsindex e813108d..30b4b749 100644--- a/packages/cli/src/team-orchestrator.ts+++ b/packages/cli/src/team-orchestrator.ts@@ -6,6 +6,7 @@ import {readFileSync,readdirSync,realpathSync,+ rmSync,statSync,writeFileSync,} from "node:fs";@@ -13,6 +14,18 @@ import { basename, dirname, join, resolve, sep } from "node:path";import { type SpawnPlan, prehydrateCredentialsForSpawn } from "./auth/credentials/prehydrate.js";import { ENV } from "./config.js";import { UPSTREAM_ERROR_LOG_ENV } from "./handlers/shared/upstream-error-capture.js";+import type { HookEngine } from "./hooks/engine.js";+import { loadHooksOnce } from "./hooks/index.js";+import { createHookInbox } from "./hooks/injection/inbox.js";+import { HOOK_INBOX_ENV } from "./hooks/injection/sinks.js";+import type { SessionInfo as HookSessionInfo } from "./hooks/public.js";+import { HOOK_SESSION_ENV } from "./hooks/request-stage.js";+import {+ type SessionHookBinding,+ createSessionHookBinding,+ reportOwnerWithoutHooks,+ sessionHooksNeedBinding,+} from "./hooks/session/binding.js";import {type Accounting,type CaptureResult,@@ -37,6 +50,7 @@ import {type TeamResizeResult,type TeamRunRow,assertMagmuxAvailable,+ chainAnswerOf,checkChildFlags,contractMeta,deliveryRefusal,@@ -230,6 +244,17 @@ export interface TeamRunOptions {paneTimings?: PaneSessionOptions["timings"];/** @internal test-only boot bound; production uses the pane's 90 s */bootTimeoutMs?: number;+ /**+ * The hook engine slot bindings are built from. Default: the process engine+ * (`loadHooksOnce()`), awaited before the spawn loop. Tests pass their own.+ */+ hookEngine?: () => Promise<HookEngine | null>;+ /** @internal test seam (§11.5): the binding for one slot, instead of the real one */+ hookBinding?: (ctx: {+ session: HookSessionInfo;+ inboxPath: string | null;+ engine: HookEngine | null;+ }) => SessionHookBinding | null;}/**@@ -316,6 +341,10 @@ interface SlotEntry {/** what `response-<id>.md` holds once it was written (decide, onBlocked or terminal) */answer: string | null;stopReason: string | null;+ /** the slot's session-hook binding (§7.4); null = today's index formulas */+ binding?: SessionHookBinding | null;+ /** the owner-created hook inbox; removed at reap */+ inboxPath?: string | null;}interface LiveTeamRun {@@ -855,6 +884,11 @@ export const TRUNCATION_NOTE =export function classifyRunOutput(input: {/** The full answer: text blocks joined with "\n\n", as written to response-<id>.md. */answer: string;+ /**+ * A hook-extended turn chain's answers, one per turn (§7.4): `requirePattern` passes+ * when it matches the joined `answer` OR any single element. Absent = the answer only.+ */+ chainAnswers?: string[];apiError: { status: number | null; text: string } | null;stopReason?: string | null;/** `complete === false` → prompt_not_read */@@ -902,8 +936,16 @@ function classifyTurnSignals(input: Parameters<typeof classifyRunOutput>[0]): Vereturn null;}-/** The caller's shape contract, matched against the full answer (no flags). */-function classifyShape(answer: string, requirePattern: string | undefined): Verdict | null {+/**+ * The caller's shape contract, matched against the full answer (no flags), or against any+ * single turn of a hook-extended chain, so a `^`-anchored pattern still matches a turn+ * that begins with it (§7.4).+ */+function classifyShape(+ answer: string,+ requirePattern: string | undefined,+ chainAnswers?: ReadonlyArray<string>+): Verdict | null {if (!requirePattern) return null;let re: RegExp | null = null;try {@@ -915,6 +957,7 @@ function classifyShape(answer: string, requirePattern: string | undefined): Verdreturn null;}if (re.test(answer)) return null;+ for (const turn of chainAnswers ?? []) if (re.test(turn)) return null;return {state: "EMPTY",reason: "shape_mismatch",@@ -951,7 +994,7 @@ function classifyAnswer(input: Parameters<typeof classifyRunOutput>[0]): Verdict};}- return classifyShape(answer, input.requirePattern);+ return classifyShape(answer, input.requirePattern, input.chainAnswers);}/**@@ -1274,6 +1317,8 @@ async function startModelsIn(assertNoActiveRun(path);const parentEnv = opts.parentEnv ?? process.env;const kind = opts.kind ?? "run";+ // The hook engine slot bindings are built from (§2.2), loaded before any spawn.+ const hookEngine = await (opts.hookEngine ?? (() => loadHooksOnce()))().catch(() => null);// Resolve every model's credential AND its route HERE, before the spawn loop// below starts N children. Each child would otherwise open its own 1Password SDK@@ -1353,15 +1398,38 @@ async function startModelsIn(return text;}+ /**+ * `onTurnRecorded` (binding present): the response file holds the chain so far, so no+ * terminal path can lose a settled turn. Not final: `e.answer` stays unset (§7.4).+ */+ function writeChainSoFar(e: SlotEntry): void {+ if (e.answer !== null || !e.session) return;+ try {+ writeFileSync(join(path, `response-${e.id}.md`), e.session.chainText(), "utf-8");+ } catch (err) {+ persistErrorLog(errorLogPathOf(e.id), `response file not written: ${String(err)}`, []);+ }+ }++ /** The answer of a slot that ended without a verdict: the chain with a binding (§7.4). */+ function unsettledAnswer(e: SlotEntry, index: number): string {+ if (e.binding && e.session) return e.session.chainText();+ return e.session?.turnAnswer(index) ?? "";+ }+/** 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);+ // A hook-extended chain is the slot's answer: every turn joined, classified with the+ // chain head's prompt-read result. Without hooks both are the turn's own (§7.4).+ const answer = chainAnswerOf(turn);+ writeResponse(e, answer);const v = classifyRunOutput({- answer: turn.answer,+ answer,+ chainAnswers: [...turn.chainAnswers, turn.answer],apiError: turn.apiError,stopReason: turn.stopReason,- promptRead: turn.delivery,+ promptRead: turn.chainDelivery,minOutputBytes,requirePattern,});@@ -1381,7 +1449,7 @@ async function startModelsIn(/** 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) ?? "");+ if (e.answer === null) writeResponse(e, unsettledAnswer(e, index));return { state: "FAILED", reason: "blocked", detail: b.text };}@@ -1412,7 +1480,7 @@ async function startModelsIn(/** 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 answer = e.answer ?? writeResponse(e, unsettledAnswer(e, index));const anomalies = [...notableAnomalies(snap),...(snap.state === "COMPLETED" && e.stopReason === "max_tokens" ? [TRUNCATION_NOTE] : []),@@ -1497,8 +1565,29 @@ async function startModelsIn(const cwd = process.cwd();const projects = projectsDir(parentEnv);+ /** The slot's hook binding: a test's, or the real one when the engine has session hooks. */+ function bindingFor(e: SlotEntry, uuid: string): SessionHookBinding | null {+ const session: HookSessionInfo = {+ kind: "team",+ role: kind === "judge" ? "judge" : "slot",+ id: `${runId}:${e.id}`,+ claudeSessionId: uuid,+ model: e.model,+ cwd,+ shape: "one-shot",+ injection: "available",+ };+ if (opts.hookBinding)+ return opts.hookBinding({ session, inboxPath: e.inboxPath ?? null, engine: hookEngine });+ if (!hookEngine || !sessionHooksNeedBinding(hookEngine)) return null;+ return createSessionHookBinding(hookEngine, session, e.inboxPath ?? null);+ }+async function startSlot(e: SlotEntry, uuid: string, transcriptPath: string): Promise<void> {let session: PaneSession;+ e.inboxPath = createHookInbox(join(path, "work"), `${e.id}.hook-inbox.jsonl`);+ const binding = bindingFor(e, uuid);+ e.binding = binding;try {session = await startPaneSession({kind: "t",@@ -1515,6 +1604,13 @@ async function startModelsIn(// 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),+ // Every slot and judge, unconditionally (§2.3 step 1).+ ...(e.inboxPath ? { [HOOK_INBOX_ENV]: e.inboxPath } : {}),+ [HOOK_SESSION_ENV]: JSON.stringify({+ kind: "team",+ id: `${runId}:${e.id}`,+ role: kind === "judge" ? "judge" : "slot",+ }),},shape: "one-shot",initialPrompt: inputContent,@@ -1525,15 +1621,34 @@ async function startModelsIn(parentEnv,...(opts.bootTimeoutMs !== undefined ? { bootTimeoutMs: opts.bootTimeoutMs } : {}),...(opts.paneTimings ? { timings: opts.paneTimings } : {}),+ ...(binding ? { hooks: binding, onTurnRecorded: () => writeChainSoFar(e) } : {}),});} catch (err) {+ removeInbox(e);failNeverSpawned(e, err);return;}e.session = session;+ // At reap: an owner without a binding checks the inbox once, then the file goes.+ void session.reaped().then(() => {+ if (!binding && e.inboxPath)+ reportOwnerWithoutHooks(e.inboxPath, hookEngine, { model: e.model, sessionId: uuid });+ // with a binding, what no settle took is journaled before the file goes+ binding?.sweepInbox?.();+ removeInbox(e);+ });updateModelStatus(e.id, { pane: session.paneId });}+ function removeInbox(e: SlotEntry): void {+ if (!e.inboxPath) return;+ try {+ rmSync(e.inboxPath, { force: true });+ } catch {+ // nothing reads it after the reap+ }+ }+const slotIds = Object.keys(manifest.models);reservePanes(slotIds.length, sockRootFor(parentEnv));// Each startSlot call consumes exactly one reservation, whether its pane starts or not.