Skip to content

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

feat(mcp): add the pane transcript follower and settle rule

Jack Rudenko2132e5c17333
diff --git a/packages/cli/src/pane/settle-rule.test.ts b/packages/cli/src/pane/settle-rule.test.ts
new file mode 100644
index 00000000..926972aa
--- /dev/null
+++ b/packages/cli/src/pane/settle-rule.test.ts
@@ -0,0 +1,352 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import {
+ SECONDARY_QUIET_MS,
+ type ScreenFacts,
+ type SettleInput,
+ decideSettle,
+} from "./settle-rule.js";
+import {
+ type Rec,
+ indexOf,
+ replay,
+ textOf,
+ transcriptRecords,
+ witnessIndex,
+} from "./test-helpers/transcript-fixtures.js";
+import type { TranscriptView, Witness } from "./transcript-follower.js";
+
+/** Turn views come from real transcripts replayed through the follower; only the screen facts are set by hand. */
+
+const cleanups: Array<() => void> = [];
+afterEach(() => {
+ for (const c of cleanups.splice(0)) c();
+});
+
+const text = (t: string): Witness => ({ kind: "text", text: t });
+
+function viewOf(
+ name: string,
+ witnessText: string,
+ opts: { upTo?: number; nth?: number; earlier?: string[] } = {}
+): TranscriptView {
+ const turns = [...(opts.earlier ?? []), witnessText].map((w) => ({
+ at: witnessIndex(name, w),
+ witness: text(w),
+ }));
+ const r = replay(name, turns, { upTo: opts.upTo });
+ cleanups.push(r.cleanup);
+ return r.views[r.views.length - 1]!;
+}
+
+const IDLE_SCREEN: ScreenFacts = {
+ boxEmpty: true,
+ choiceDialog: false,
+ working: false,
+ aboveBoxQuietMs: 0,
+};
+
+function input(v: TranscriptView, over: Partial<SettleInput> = {}): SettleInput {
+ return {
+ turn: v.current,
+ session: v.session,
+ transcriptQuietMs: 1000,
+ chatQuietMs: 1000,
+ screen: IDLE_SCREEN,
+ paneExited: false,
+ ...over,
+ };
+}
+
+const PEAR = "Reply with exactly PEAR and nothing else.";
+
+describe("path P — turn_duration", () => {
+ test("settles a hookless end_turn once the screen corroborates", () => {
+ const v = viewOf("pear-hookless", PEAR);
+ expect(decideSettle(input(v))).toEqual({
+ settled: true,
+ by: "turn_duration",
+ stopReason: "end_turn",
+ anomalies: [],
+ });
+ });
+
+ test("waits for the screen: typed text, a dialog, a working row, or a chat record < 500 ms old", () => {
+ const v = viewOf("pear-hookless", PEAR);
+ expect(decideSettle(input(v, { screen: { ...IDLE_SCREEN, boxEmpty: false } })).settled).toBe(
+ false
+ );
+ expect(decideSettle(input(v, { screen: { ...IDLE_SCREEN, choiceDialog: true } })).settled).toBe(
+ false
+ );
+ expect(decideSettle(input(v, { screen: { ...IDLE_SCREEN, working: true } })).settled).toBe(
+ false
+ );
+ expect(decideSettle(input(v, { chatQuietMs: 100 })).settled).toBe(false);
+ });
+
+ test("while disconnected it settles on the transcript alone with screen_unverified (X-M12)", () => {
+ const v = viewOf("pear-hookless", PEAR);
+ expect(decideSettle(input(v, { screen: null }))).toEqual({
+ settled: true,
+ by: "turn_duration",
+ stopReason: "end_turn",
+ anomalies: ["screen_unverified"],
+ });
+ });
+
+ test("an API error settles through its turn_duration", () => {
+ const v = viewOf("api-error-stop-hook", PEAR);
+ expect(decideSettle(input(v))).toMatchObject({
+ settled: true,
+ by: "turn_duration",
+ stopReason: "stop_sequence",
+ });
+ });
+
+ test("a max_tokens turn settles only at its final API error, not at a continued max_tokens message", () => {
+ const n = "max-tokens-hookless";
+ const w = "Write a 400-word story about a pear, as plain text, no tools.";
+ const meta = indexOf(n, (r) => r.type === "user" && r.isMeta === true, witnessIndex(n, w));
+ const mid = viewOf(n, w, { upTo: meta + 1 });
+ expect(
+ decideSettle(
+ input(mid, { transcriptQuietMs: 1e9, screen: { ...IDLE_SCREEN, aboveBoxQuietMs: 1e9 } })
+ )
+ ).toEqual({
+ settled: false,
+ activity: "thinking",
+ });
+ const end = viewOf(n, w);
+ expect(decideSettle(input(end))).toMatchObject({
+ settled: true,
+ by: "turn_duration",
+ stopReason: "stop_sequence",
+ });
+ });
+});
+
+describe("Stop hooks hold the turn open (X-H2)", () => {
+ const n = "stop-hook-matrix";
+ const at = witnessIndex(n, PEAR);
+ const summary = indexOf(n, (r) => r.subtype === "stop_hook_summary", at);
+
+ test("a running Stop hook is 'finishing' and no quiet window, however long, settles it", () => {
+ const v = viewOf(n, PEAR, { upTo: summary });
+ const long = {
+ transcriptQuietMs: 10 * SECONDARY_QUIET_MS,
+ screen: { ...IDLE_SCREEN, aboveBoxQuietMs: 10 * SECONDARY_QUIET_MS },
+ };
+ expect(decideSettle(input(v, long))).toEqual({ settled: false, activity: "finishing" });
+ });
+
+ test("once the summary is written, path S may settle after the secondary quiet window", () => {
+ const v = viewOf(n, PEAR, { upTo: summary + 1 });
+ expect(v.current!.turnDurationAfterLast).toBeNull();
+ expect(v.current!.stopHookSummaryAfterLast).toBe(true);
+ const short = {
+ transcriptQuietMs: SECONDARY_QUIET_MS - 1,
+ screen: { ...IDLE_SCREEN, aboveBoxQuietMs: SECONDARY_QUIET_MS },
+ };
+ expect(decideSettle(input(v, short)).settled).toBe(false);
+ const ok = {
+ transcriptQuietMs: SECONDARY_QUIET_MS,
+ screen: { ...IDLE_SCREEN, aboveBoxQuietMs: SECONDARY_QUIET_MS },
+ };
+ expect(decideSettle(input(v, ok))).toEqual({
+ settled: true,
+ by: "quiet",
+ stopReason: "end_turn",
+ anomalies: ["settled_without_turn_duration"],
+ });
+ // S waits for the reconnect
+ expect(decideSettle(input(v, { ...ok, screen: null })).settled).toBe(false);
+ });
+
+ test("the measured secondary window is 32 s", () => {
+ expect(SECONDARY_QUIET_MS).toBe(32_000);
+ });
+});
+
+describe("path S in a session proven hook-less", () => {
+ test("turn 2 with no turn_duration settles after the quiet window because turn 1 proved there are no Stop hooks", () => {
+ const n = "tools-session";
+ const recs = transcriptRecords(n).map(textOf);
+ const t1 = recs.find((s) => s.startsWith("Run this exact command"))!;
+ const t2 = recs.find((s) => s.startsWith("First write, as plain text"))!;
+ const td2 = indexOf(n, (r) => r.subtype === "turn_duration", witnessIndex(n, t2));
+ const v = viewOf(n, t2, { earlier: [t1], upTo: td2 });
+ expect(v.session.provenHookless).toBe(true);
+ expect(v.current!.turnDurationAfterLast).toBeNull();
+ const quiet = {
+ transcriptQuietMs: SECONDARY_QUIET_MS,
+ screen: { ...IDLE_SCREEN, aboveBoxQuietMs: SECONDARY_QUIET_MS },
+ };
+ expect(decideSettle(input(v, quiet))).toMatchObject({
+ settled: true,
+ by: "quiet",
+ stopReason: "end_turn",
+ });
+ });
+});
+
+describe("path I — interrupts", () => {
+ const n = "stop-hook-matrix";
+ const all = transcriptRecords(n).map(textOf);
+ const ws = [
+ PEAR,
+ "Write a 400-word story about a pear, as plain text, no tools.",
+ "Run the command sleep 30 with the Bash tool, then reply DONE.",
+ "Write a 700-word story about a plum, as plain text, no tools.",
+ ];
+ const views = () => {
+ const r = replay(
+ n,
+ ws.map((w) => ({ at: all.findIndex((x) => x.trim() === w), witness: text(w) }))
+ );
+ cleanups.push(r.cleanup);
+ return r.views;
+ };
+
+ test("Esc during a running Bash settles 'interrupted' with no turn_duration and no Stop hook", () => {
+ const v = views()[2]!;
+ expect(decideSettle(input(v))).toEqual({
+ settled: true,
+ by: "interrupt",
+ stopReason: "interrupted",
+ anomalies: [],
+ });
+ });
+
+ test("a plain interrupt while streaming settles 'interrupted'", () => {
+ const v = views()[3]!;
+ expect(decideSettle(input(v))).toMatchObject({
+ settled: true,
+ by: "interrupt",
+ stopReason: "interrupted",
+ });
+ });
+
+ test("a declined dialog with interrupt + turn_duration settles once, by the interrupt", () => {
+ const p = "permission-write-esc";
+ const w =
+ "Create a file named hello.txt containing the word hi, using the Write tool. Do nothing else.";
+ const v = viewOf(p, w);
+ expect(decideSettle(input(v))).toMatchObject({
+ settled: true,
+ by: "interrupt",
+ stopReason: "interrupted",
+ });
+ });
+});
+
+describe("unsettled activity", () => {
+ const n = "tools-session";
+ const recs = transcriptRecords(n).map(textOf);
+
+ test("a background agent still pending at turn_duration reads 'background'", () => {
+ const w = recs.find((s) => s.startsWith("Use the Agent tool with run_in_background"))!;
+ const td = indexOf(n, (r) => r.subtype === "turn_duration", witnessIndex(n, w));
+ const v = viewOf(n, w, { upTo: td + 1 });
+ expect(decideSettle(input(v))).toEqual({ settled: false, activity: "background" });
+ });
+
+ test("a background Bash is NOT awaited: the turn settles at turn_duration with the shell open (D23)", () => {
+ const w = recs.find((s) => s.startsWith("Use the Bash tool with run_in_background"))!;
+ const td = indexOf(n, (r) => r.subtype === "turn_duration", witnessIndex(n, w));
+ const v = viewOf(n, w, { upTo: td + 1 });
+ expect(v.current!.backgroundShellsOpen).toEqual(["sleep 10; echo BGDONE"]);
+ expect(decideSettle(input(v))).toMatchObject({ settled: true, by: "turn_duration" });
+ });
+
+ test("a pending AskUserQuestion reads as its tool name", () => {
+ const w =
+ "Use the AskUserQuestion tool to ask me which fruit I prefer, with exactly two options: Apple and Pear. Do nothing else.";
+ const use = indexOf(
+ n,
+ (r) =>
+ r.type === "assistant" && r.message.content.some((b: Rec) => b.name === "AskUserQuestion"),
+ witnessIndex(n, w)
+ );
+ const v = viewOf(n, w, { upTo: use + 1 });
+ expect(decideSettle(input(v))).toEqual({ settled: false, activity: "AskUserQuestion" });
+ });
+
+ test("a running Bash reads 'Bash' and is never settled by quiet", () => {
+ const w = recs.find((s) => s.startsWith("Run this exact command"))!;
+ const use = indexOf(
+ n,
+ (r) => r.type === "assistant" && r.message.content.some((b: Rec) => b.name === "Bash"),
+ witnessIndex(n, w)
+ );
+ const v = viewOf(n, w, { upTo: use + 1 });
+ const quiet = { transcriptQuietMs: 1e9, screen: { ...IDLE_SCREEN, aboveBoxQuietMs: 1e9 } };
+ expect(decideSettle(input(v, quiet))).toEqual({ settled: false, activity: "Bash" });
+ });
+
+ test("before acceptance the activity is 'thinking'", () => {
+ const v = viewOf("pear-hookless", "a prompt never typed");
+ expect(decideSettle(input(v))).toEqual({ settled: false, activity: "thinking" });
+ });
+});
+
+describe("path X — pane exit", () => {
+ test("an end_turn answer with no turn_duration settles on exit (exit_before_td)", () => {
+ const n = "pear-hookless";
+ const td = indexOf(n, (r) => r.subtype === "turn_duration");
+ const v = viewOf(n, PEAR, { upTo: td });
+ expect(v.current!.turnDurationAfterLast).toBeNull();
+ expect(decideSettle(input(v, { paneExited: true, screen: null }))).toEqual({
+ settled: true,
+ by: "exit",
+ stopReason: "end_turn",
+ anomalies: [],
+ });
+ });
+
+ test("a tool_use message does not settle on exit", () => {
+ const n = "tools-session";
+ const w = transcriptRecords(n)
+ .map(textOf)
+ .find((s) => s.startsWith("Run this exact command"))!;
+ const use = indexOf(
+ n,
+ (r) => r.type === "assistant" && r.message.content.some((b: Rec) => b.name === "Bash"),
+ witnessIndex(n, w)
+ );
+ const v = viewOf(n, w, { upTo: use + 1 });
+ expect(decideSettle(input(v, { paneExited: true, screen: null })).settled).toBe(false);
+ });
+});
+
+describe("refusal (redacted corpus)", () => {
+ test("the companion record continues the turn, so the refusal itself never settles it", () => {
+ const n = "corpus-redacted/refusal-then-fallback";
+ const recs = transcriptRecords(n);
+ const r = replay(n, [{ at: 0, witness: text(textOf(recs[0]!)) }], {
+ upTo: indexOf(n, (x) => x.type === "user" && x.isMeta === true) + 1,
+ });
+ cleanups.push(r.cleanup);
+ const v = r.views[0]!;
+ const quiet = { transcriptQuietMs: 1e9, screen: { ...IDLE_SCREEN, aboveBoxQuietMs: 1e9 } };
+ expect(decideSettle(input(v, quiet))).toEqual({ settled: false, activity: "thinking" });
+ });
+
+ test("a refusal that does end a turn opens S's Stop-hook gate like an API error", () => {
+ const v = viewOf("stop-hook-matrix", PEAR, {
+ upTo: indexOf("stop-hook-matrix", (r) => r.subtype === "stop_hook_summary"),
+ });
+ const turn = {
+ ...v.current!,
+ lastAssistant: { ...v.current!.lastAssistant!, stopReason: "refusal" },
+ };
+ const quiet = {
+ transcriptQuietMs: SECONDARY_QUIET_MS,
+ screen: { ...IDLE_SCREEN, aboveBoxQuietMs: SECONDARY_QUIET_MS },
+ };
+ expect(decideSettle({ ...input(v, quiet), turn })).toMatchObject({
+ settled: true,
+ by: "quiet",
+ stopReason: "refusal",
+ });
+ });
+});
diff --git a/packages/cli/src/pane/settle-rule.ts b/packages/cli/src/pane/settle-rule.ts
new file mode 100644
index 00000000..aed97f55
--- /dev/null
+++ b/packages/cli/src/pane/settle-rule.ts
@@ -0,0 +1,166 @@
+/**
+ * The settle rule (architecture §2.8, D14), as one pure decision over the current
+ * turn's transcript facts and the screen.
+ *
+ * A turn is settled by Claude Code's OWN end-of-turn evidence, turn-scoped:
+ *
+ * P `turn_duration` after the last assistant message with no background agent
+ * pending. Claude Code writes it only after Stop hooks finish (captured: 30,077 ms
+ * after the answer with a `sleep 30` Stop hook), so P waits for hooks by construction.
+ * I `[Request interrupted by user…]` after the last assistant message. `turn_duration`
+ * is optional: a declined dialog writes one, Esc on a running Bash does not, a plain
+ * interrupt does not (all captured).
+ * S no `turn_duration`, no interrupt: an ending `stop_reason`, Stop hooks KNOWN to be
+ * finished, and full quiet for `secondaryQuietMs`. A running Stop hook can never
+ * satisfy S: until its summary is written there is none, and the screen's working
+ * row is rewritten every second while it runs.
+ * X only when the pane has exited: an ending `stop_reason` and nothing waking after it.
+ *
+ * Nothing here is a timer that ends work (D10): S's window only confirms an ending that
+ * has already happened, and an unsettled turn just reports its `activity`.
+ */
+
+import type { SessionFacts, TurnView } from "./transcript-follower.js";
+
+/**
+ * `max(15 000, 2 × p99)` of the `stop_hook_summary` → next main-chain assistant gap after
+ * an `end_turn`, over 3,001 local transcripts (1,944 cases, p99 15,832 ms → 31,664 ms),
+ * rounded up. Measured 2026-10-06; see phase2-captures.md §5.
+ */
+export const SECONDARY_QUIET_MS = 32_000;
+
+/** No further main-chain chat record for this long before a P/I/S settle is corroborated. */
+export const CORROBORATION_MS = 500;
+
+/** Stop reasons the harness itself continues; they never end a turn except through I. */
+const CONTINUING = new Set(["tool_use", "pause_turn"]);
+
+export interface ScreenFacts {
+ /** an input box is visible and its typed text is empty (placeholder cells excluded) */
+ boxEmpty: boolean;
+ /** hasChoiceDialog(screen) */
+ choiceDialog: boolean;
+ /** isWorking(screen) — a veto only */
+ working: boolean;
+ /** ms since a row above the input box last changed */
+ aboveBoxQuietMs: number;
+}
+
+export interface SettleInput {
+ turn: TurnView | null;
+ session: SessionFacts;
+ /** ms since the last append to the main transcript or any subagent file */
+ transcriptQuietMs: number;
+ /** ms since this turn's last main-chain chat record was READ (corroboration window) */
+ chatQuietMs: number;
+ /** null while the socket is disconnected: the in-memory screen is stale */
+ screen: ScreenFacts | null;
+ paneExited: boolean;
+ secondaryQuietMs?: number;
+ corroborationMs?: number;
+}
+
+export type SettledBy = "turn_duration" | "interrupt" | "quiet" | "exit";
+
+export type SettleDecision =
+ | { settled: true; by: SettledBy; stopReason: string | null; anomalies: string[] }
+ | { settled: false; activity: string };
+
+function agentsBalanced(t: TurnView): boolean {
+ return t.agentsLaunched === t.agentsCompleted;
+}
+
+function endingStop(t: TurnView): boolean {
+ const la = t.lastAssistant;
+ if (!la) return false;
+ return la.isApiError || !CONTINUING.has(la.stopReason ?? "");
+}
+
+/** Stop hooks are known to be finished (S's gate). */
+function stopHooksFinished(t: TurnView, s: SessionFacts): boolean {
+ const la = t.lastAssistant;
+ if (!la) return false;
+ // Stop hooks do not run after an API error (captured, s10) or a refusal (corpus).
+ return (
+ t.stopHookSummaryAfterLast || s.provenHookless || la.isApiError || la.stopReason === "refusal"
+ );
+}
+
+function activityOf(t: TurnView | null): string {
+ if (!t || !t.lastAssistant) return "thinking";
+ if (t.pendingTool) return t.pendingTool.name || "thinking";
+ if (t.wakingAfterLast) return "thinking";
+ const pending = t.turnDurationAfterLast?.pendingBackgroundAgentCount ?? 0;
+ if ((t.turnDurationAfterLast && pending > 0) || (t.turnDurationAfterLast && !agentsBalanced(t)))
+ return "background";
+ if (endingStop(t)) return "finishing";
+ return "thinking";
+}
+
+function corroborated(input: SettleInput): { ok: boolean; anomaly?: string } {
+ const quiet = input.corroborationMs ?? CORROBORATION_MS;
+ if (input.chatQuietMs < quiet) return { ok: false };
+ if (!input.screen) return { ok: true, anomaly: "screen_unverified" };
+ const s = input.screen;
+ return { ok: s.boxEmpty && !s.choiceDialog && !s.working };
+}
+
+type Path = SettleDecision | null; // null = this path does not apply / not yet
+
+function settledAs(
+ by: SettledBy,
+ stopReason: string | null,
+ c: { anomaly?: string },
+ extra: string[] = []
+): SettleDecision {
+ return {
+ settled: true,
+ by,
+ stopReason,
+ anomalies: [...(c.anomaly ? [c.anomaly] : []), ...extra],
+ };
+}
+
+/** I — interrupt (resolves the pending tool; turn_duration optional). */
+function pathInterrupt(input: SettleInput): Path {
+ const c = corroborated(input);
+ return c.ok ? settledAs("interrupt", "interrupted", c) : null;
+}
+
+/** P — turn_duration with no background agent pending. */
+function pathPrimary(t: TurnView, input: SettleInput): Path {
+ const td = t.turnDurationAfterLast;
+ if (!td) return null;
+ const pending = td.pendingBackgroundAgentCount ?? 0;
+ if (pending !== 0 || !agentsBalanced(t)) return null;
+ const c = corroborated(input);
+ return c.ok ? settledAs("turn_duration", t.lastAssistant?.stopReason ?? null, c) : null;
+}
+
+/** S — no turn_duration: Stop hooks known finished and full quiet for the secondary window. */
+function pathSecondary(t: TurnView, input: SettleInput): Path {
+ if (!endingStop(t) || !stopHooksFinished(t, input.session)) return null;
+ if (!input.screen) return null; // S waits for the reconnect
+ const window = input.secondaryQuietMs ?? SECONDARY_QUIET_MS;
+ if (input.transcriptQuietMs < window || input.screen.aboveBoxQuietMs < window) return null;
+ const c = corroborated(input);
+ return c.ok
+ ? settledAs("quiet", t.lastAssistant?.stopReason ?? null, c, ["settled_without_turn_duration"])
+ : null;
+}
+
+export function decideSettle(input: SettleInput): SettleDecision {
+ const t = input.turn;
+ const notYet: SettleDecision = { settled: false, activity: activityOf(t) };
+ // 1. accepted, with an assistant message after the witness; 2. nothing waking after it
+ if (!t || t.acceptedAt === null || !t.lastAssistant || t.wakingAfterLast) return notYet;
+ if (t.interruptAfterLast) return pathInterrupt(input) ?? notYet;
+ // 4. no pending tool, background agents balanced
+ if (t.pendingTool) return notYet;
+ if (t.turnDurationAfterLast) return pathPrimary(t, input) ?? notYet;
+ if (!agentsBalanced(t)) return notYet;
+ // X — exit (pane dead: no screen corroboration)
+ if (input.paneExited)
+ return endingStop(t) ? settledAs("exit", t.lastAssistant.stopReason, {}) : notYet;
+ return pathSecondary(t, input) ?? notYet;
+}
diff --git a/packages/cli/src/pane/test-helpers/transcript-fixtures.ts b/packages/cli/src/pane/test-helpers/transcript-fixtures.ts
new file mode 100644
index 00000000..2561c905
--- /dev/null
+++ b/packages/cli/src/pane/test-helpers/transcript-fixtures.ts
@@ -0,0 +1,106 @@
+/**
+ * Loaders for the phase-2 real-capture transcript fixtures, and a replay that feeds a
+ * real transcript to a TranscriptFollower the way a pane session sees it. Test-only.
+ */
+
+import { appendFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import {
+ TranscriptFollower,
+ type TranscriptView,
+ type TurnDelivery,
+ type Witness,
+} from "../transcript-follower.js";
+import { FIXTURES } from "./fixtures.js";
+
+/** A raw transcript record or content block (untyped JSON written by Claude Code). */
+// biome-ignore lint/suspicious/noExplicitAny: fixtures are raw JSON, read field by field in assertions
+export type Rec = Record<string, any>;
+
+export function transcriptLines(name: string): string[] {
+ return readFileSync(join(FIXTURES, "transcripts", `${name}.jsonl`), "utf8")
+ .split("\n")
+ .filter(Boolean);
+}
+
+export function transcriptRecords(name: string): Rec[] {
+ return transcriptLines(name).map((l) => JSON.parse(l));
+}
+
+/** Text of a user record (string content or text blocks). */
+export function textOf(r: Rec): string {
+ const c = r.message?.content;
+ if (typeof c === "string") return c;
+ return (c ?? [])
+ .filter((b: Rec) => b?.type === "text")
+ .map((b: Rec) => b.text)
+ .join("");
+}
+
+export interface ReplayTurn {
+ /** index of the record the turn's offset is marked BEFORE (normally the witness record) */
+ at: number;
+ witness: Witness;
+ delivery?: TurnDelivery | null;
+}
+
+/**
+ * Replays a real transcript into a temp file the way a pane session sees it: for each
+ * turn, every earlier line is appended and polled, the offset is marked (`size()`),
+ * the turn opened, and then the rest is appended. Returns the follower and the views
+ * taken right after each turn's lines were all applied.
+ */
+export function replay(
+ name: string,
+ turns: ReplayTurn[],
+ opts: { upTo?: number; subagents?: string; now?: () => number } = {}
+): { follower: TranscriptFollower; views: TranscriptView[]; dir: string; cleanup: () => void } {
+ const lines = transcriptLines(name);
+ const dir = mkdtempSync(join(tmpdir(), "pane-fixture-"));
+ const path = join(dir, "t.jsonl");
+ writeFileSync(path, "");
+ const follower = new TranscriptFollower(path, opts.subagents ?? join(dir, "none"), {
+ now: opts.now,
+ });
+ const views: TranscriptView[] = [];
+ const end = Math.min(opts.upTo ?? lines.length, lines.length);
+ let i = 0;
+ const sorted = [...turns].sort((a, b) => a.at - b.at);
+ for (let k = 0; k < sorted.length; k++) {
+ const t = sorted[k]!;
+ for (; i < t.at && i < end; i++) appendFileSync(path, `${lines[i]}\n`);
+ follower.poll();
+ follower.openTurn({
+ index: k + 1,
+ offset: follower.size(),
+ witness: t.witness,
+ delivery: t.delivery ?? null,
+ });
+ const stop = Math.min(sorted[k + 1]?.at ?? end, end);
+ for (; i < stop; i++) appendFileSync(path, `${lines[i]}\n`);
+ follower.poll();
+ views.push(follower.view());
+ }
+ if (sorted.length === 0) {
+ for (; i < end; i++) appendFileSync(path, `${lines[i]}\n`);
+ follower.poll();
+ }
+ return { follower, views, dir, cleanup: () => rmSync(dir, { recursive: true, force: true }) };
+}
+
+/** Index of the first record satisfying `pred` at or after `from`. */
+export function indexOf(name: string, pred: (r: Rec) => boolean, from = 0): number {
+ const recs = transcriptRecords(name);
+ for (let i = from; i < recs.length; i++) if (pred(recs[i]!)) return i;
+ return -1;
+}
+
+/** Index of the user record whose text equals `text` exactly (a witness). */
+export function witnessIndex(name: string, text: string, from = 0): number {
+ return indexOf(
+ name,
+ (r) => r.type === "user" && !r.isMeta && textOf(r).trim() === text.trim(),
+ from
+ );
+}
diff --git a/packages/cli/src/pane/transcript-follower.test.ts b/packages/cli/src/pane/transcript-follower.test.ts
new file mode 100644
index 00000000..e6a86064
--- /dev/null
+++ b/packages/cli/src/pane/transcript-follower.test.ts
@@ -0,0 +1,619 @@
+import { afterEach, describe, expect, test } from "bun:test";
+import { join } from "node:path";
+import { FIXTURES } from "./test-helpers/fixtures.js";
+import {
+ type Rec,
+ indexOf,
+ replay,
+ textOf,
+ transcriptRecords,
+ witnessIndex,
+} from "./test-helpers/transcript-fixtures.js";
+import type { TranscriptView, Witness } from "./transcript-follower.js";
+
+/** Every fixture is a real Claude Code 2.1.290 capture (phase2-captures.md) or a redacted corpus slice. */
+
+const cleanups: Array<() => void> = [];
+afterEach(() => {
+ for (const c of cleanups.splice(0)) c();
+});
+
+function run(
+ name: string,
+ turns: Array<{ at: number; witness: Witness; delivery?: { file: string; text: string } }>,
+ opts: { upTo?: number; subagents?: string } = {}
+) {
+ const r = replay(name, turns, opts);
+ cleanups.push(r.cleanup);
+ return r;
+}
+
+const text = (t: string): Witness => ({ kind: "text", text: t });
+const cur = (v: TranscriptView | undefined) => v!.current!;
+
+/** Generators of the files the captures read (phase2/s03-tools.ts, s11-readlimits.ts). */
+const BIG = `${Array.from({ length: 1800 }, (_, i) => `${i + 1} ${"lorem ipsum dolor sit amet ".repeat(4)}`).join("\n")}\n`;
+function longLine(n: number): string {
+ let s = "START";
+ let i = 0;
+ while (s.length < n) s += ` w${i++}`;
+ return `${s} END`;
+}
+
+describe("witness and turn scoping", () => {
+ const PEAR = "Reply with exactly PEAR and nothing else.";
+
+ test("a typed line is accepted by the user record carrying exactly that text", () => {
+ const at = witnessIndex("pear-hookless", PEAR);
+ const { views } = run("pear-hookless", [{ at, witness: text(PEAR) }]);
+ const t = cur(views[0]);
+ expect(t.acceptedAt).toBe(transcriptRecords("pear-hookless")[at]!.timestamp);
+ expect(t.assistantText).toEqual(["PEAR"]);
+ expect(t.lastAssistant?.stopReason).toBe("end_turn");
+ });
+
+ test("a different text is never accepted", () => {
+ const at = witnessIndex("pear-hookless", PEAR);
+ const { views } = run("pear-hookless", [{ at, witness: text("Reply with exactly PLUM") }]);
+ expect(cur(views[0]).acceptedAt).toBeNull();
+ expect(cur(views[0]).lastAssistant).toBeNull();
+ });
+
+ test("earlier evidence never satisfies a later turn (C3)", () => {
+ const n = "tools-session";
+ const t1 = witnessIndex(
+ n,
+ "Run this exact command with the Bash tool: sleep 12; echo LONGDONE — then reply with its output only."
+ );
+ const t2Text = transcriptRecords(n)
+ .map(textOf)
+ .find((s) => s.startsWith("First write, as plain text"))!;
+ const t2 = witnessIndex(n, t2Text);
+ // Turn 2 opened, but nothing after its offset has been written yet.
+ const { views } = run(
+ n,
+ [
+ { at: t1, witness: text(transcriptRecords(n).map(textOf)[t1]!) },
+ { at: t2, witness: text(t2Text) },
+ ],
+ { upTo: t2 }
+ );
+ expect(cur(views[0]).turnDurationAfterLast).not.toBeNull();
+ const t = cur(views[1]);
+ expect(t.index).toBe(2);
+ expect(t.acceptedAt).toBeNull();
+ expect(t.lastAssistant).toBeNull();
+ expect(t.turnDurationAfterLast).toBeNull();
+ });
+
+ test("a slash command is accepted by its <command-name> record", () => {
+ const n = "slash-and-reads";
+ const at = indexOf(
+ n,
+ (r) => r.type === "user" && textOf(r).includes("<command-name>/pear</command-name>")
+ );
+ const { views } = run(n, [{ at, witness: { kind: "command", name: "pear" } }], {
+ upTo: indexOf(n, (r) => r.subtype === "turn_duration", at) + 1,
+ });
+ const t = cur(views[0]);
+ expect(t.acceptedAt).not.toBeNull();
+ expect(t.assistantText).toEqual(["PEAR"]);
+ expect(t.turnDurationAfterLast).not.toBeNull();
+ });
+
+ test("a command witness for another name never matches", () => {
+ const n = "slash-and-reads";
+ const at = indexOf(
+ n,
+ (r) => r.type === "user" && textOf(r).includes("<command-name>/pear</command-name>")
+ );
+ const { views } = run(n, [{ at, witness: { kind: "command", name: "plum" } }], {
+ upTo: at + 12,
+ });
+ expect(cur(views[0]).acceptedAt).toBeNull();
+ });
+});
+
+describe("usage and tool calls", () => {
+ test("usage is taken once per message.id, not once per line", () => {
+ const n = "pear-hookless";
+ const recs = transcriptRecords(n);
+ const assistantLines = recs.filter((r) => r.type === "assistant");
+ expect(assistantLines.length).toBe(2); // thinking + text, one message
+ const u = assistantLines[0]!.message.usage;
+ const { views } = run(n, [
+ {
+ at: witnessIndex(n, "Reply with exactly PEAR and nothing else."),
+ witness: text("Reply with exactly PEAR and nothing else."),
+ },
+ ]);
+ expect(views[0]!.usage).toEqual({
+ tokensIn: u.input_tokens + u.cache_creation_input_tokens + u.cache_read_input_tokens,
+ tokensOut: u.output_tokens,
+ });
+ });
+
+ test("subagent files add their own messages and tool calls, deduplicated the same way", () => {
+ const n = "tools-session";
+ const main = run(n, []);
+ const without = main.follower.view();
+ const withSub = run(n, [], {
+ subagents: join(FIXTURES, "transcripts", "tools-session", "subagents"),
+ });
+ const v = withSub.follower.view();
+ expect(v.usage.tokensIn).toBeGreaterThan(without.usage.tokensIn);
+ expect(v.toolCalls).toBeGreaterThanOrEqual(without.toolCalls);
+ // unique tool_use ids of the main chain
+ const ids = new Set<string>();
+ for (const r of transcriptRecords(n))
+ if (r.type === "assistant" && !r.isSidechain)
+ for (const b of r.message.content) if (b.type === "tool_use") ids.add(b.id);
+ expect(without.toolCalls).toBe(ids.size);
+ });
+});
+
+describe("Stop hooks, provenHookless and turn_duration", () => {
+ test("hookless: end_turn → prompt_snapshot → turn_duration proves the session has no Stop hooks", () => {
+ const n = "pear-hookless";
+ const { views } = run(n, [
+ {
+ at: witnessIndex(n, "Reply with exactly PEAR and nothing else."),
+ witness: text("Reply with exactly PEAR and nothing else."),
+ },
+ ]);
+ expect(views[0]!.session).toEqual({ stopHooksSeen: false, provenHookless: true });
+ expect(cur(views[0]).stopHookSummaryAfterLast).toBe(false);
+ expect(cur(views[0]).turnDurationAfterLast).toEqual({ pendingBackgroundAgentCount: null });
+ });
+
+ test("with a Stop hook: stop_hook_summary then turn_duration; never provenHookless", () => {
+ const n = "stop-hook-matrix";
+ const at = witnessIndex(n, "Reply with exactly PEAR and nothing else.");
+ const summary = indexOf(n, (r) => r.subtype === "stop_hook_summary", at);
+ const before = run(n, [{ at, witness: text("Reply with exactly PEAR and nothing else.") }], {
+ upTo: summary,
+ });
+ expect(cur(before.views[0]).assistantText).toEqual(["PEAR"]);
+ expect(cur(before.views[0]).stopHookSummaryAfterLast).toBe(false);
+ expect(cur(before.views[0]).turnDurationAfterLast).toBeNull();
+ const after = run(n, [{ at, witness: text("Reply with exactly PEAR and nothing else.") }], {
+ upTo: summary + 2,
+ });
+ expect(cur(after.views[0]).stopHookSummaryAfterLast).toBe(true);
+ expect(cur(after.views[0]).turnDurationAfterLast).not.toBeNull();
+ expect(after.views[0]!.session).toEqual({ stopHooksSeen: true, provenHookless: false });
+ });
+
+ test("an API error is followed by turn_duration and no stop_hook_summary even with a Stop hook", () => {
+ const n = "api-error-stop-hook";
+ const { views } = run(n, [
+ {
+ at: witnessIndex(n, "Reply with exactly PEAR and nothing else."),
+ witness: text("Reply with exactly PEAR and nothing else."),
+ },
+ ]);
+ const t = cur(views[0]);
+ expect(t.lastAssistant).toMatchObject({ isApiError: true, stopReason: "stop_sequence" });
+ expect(t.apiError).toEqual({
+ status: 401,
+ category: "authentication_failed",
+ text: "Please run /login · API Error: 401 OAuth access token is invalid.",
+ });
+ expect(t.assistantText).toEqual([]);
+ expect(t.stopHookSummaryAfterLast).toBe(false);
+ expect(t.turnDurationAfterLast).not.toBeNull();
+ expect(views[0]!.session.provenHookless).toBe(false);
+ });
+});
+
+describe("interrupts (path I's evidence)", () => {
+ const n = "stop-hook-matrix";
+ const all = transcriptRecords(n).map(textOf);
+ const turns = [
+ "Reply with exactly PEAR and nothing else.",
+ "Write a 400-word story about a pear, as plain text, no tools.",
+ "Run the command sleep 30 with the Bash tool, then reply DONE.",
+ "Write a 700-word story about a plum, as plain text, no tools.",
+ ].map((t) => ({ at: all.findIndex((x) => x.trim() === t), witness: text(t) }));
+
+ test("Esc during a running Bash: tool form, pending tool resolved, no turn_duration", () => {
+ const { views } = run(n, turns);
+ const t = cur(views[2]);
+ expect(t.interruptAfterLast).toEqual({ forToolUse: true });
+ expect(t.pendingTool).toBeNull();
+ expect(t.turnDurationAfterLast).toBeNull();
+ expect(t.stopHookSummaryAfterLast).toBe(false);
+ });
+
+ test("Esc while streaming: plain form after an assistant record with stop_reason null", () => {
+ const { views } = run(n, turns);
+ const t = cur(views[3]);
+ expect(t.lastAssistant?.stopReason).toBeNull();
+ expect(t.interruptAfterLast).toEqual({ forToolUse: false });
+ expect(t.turnDurationAfterLast).toBeNull();
+ expect(t.assistantText.join("")).toStartWith("# The Plum Thief");
+ });
+
+ test("a declined dialog (permission) writes the interrupt AND turn_duration", () => {
+ const p = "permission-write-esc";
+ const w =
+ "Create a file named hello.txt containing the word hi, using the Write tool. Do nothing else.";
+ const { views } = run(p, [{ at: witnessIndex(p, w), witness: text(w) }]);
+ const t = cur(views[0]);
+ expect(t.interruptAfterLast).toEqual({ forToolUse: true });
+ expect(t.turnDurationAfterLast).not.toBeNull();
+ });
+});
+
+describe("blocked tools", () => {
+ test("a pending AskUserQuestion is visible until its rejection result lands", () => {
+ const n = "tools-session";
+ const w =
+ "Use the AskUserQuestion tool to ask me which fruit I prefer, with exactly two options: Apple and Pear. Do nothing else.";
+ const at = witnessIndex(n, w);
+ const use = indexOf(
+ n,
+ (r) =>
+ r.type === "assistant" && r.message.content.some((b: Rec) => b.name === "AskUserQuestion"),
+ at
+ );
+ const pending = run(n, [{ at, witness: text(w) }], { upTo: use + 1 });
+ expect(cur(pending.views[0]).pendingTool?.name).toBe("AskUserQuestion");
+ const done = run(n, [{ at, witness: text(w) }], { upTo: use + 6 });
+ const t = cur(done.views[0]);
+ expect(t.pendingTool).toBeNull();
+ expect(t.interruptAfterLast).toEqual({ forToolUse: true });
+ expect(t.turnDurationAfterLast).not.toBeNull();
+ });
+
+ test("a pending ExitPlanMode is visible until the plan is declined", () => {
+ const n = "plan-approval-esc";
+ const w =
+ "Make a one-step plan to create a file hello.txt containing hi, then call ExitPlanMode to present it. Keep it short.";
+ const at = witnessIndex(n, w);
+ const use = indexOf(
+ n,
+ (r) =>
+ r.type === "assistant" && r.message.content.some((b: Rec) => b.name === "ExitPlanMode"),
+ at
+ );
+ const { views } = run(n, [{ at, witness: text(w) }], { upTo: use + 1 });
+ expect(cur(views[0]).pendingTool?.name).toBe("ExitPlanMode");
+ });
+});
+
+describe("background work (D23)", () => {
+ const n = "tools-session";
+ const recs = transcriptRecords(n);
+ const find = (p: string) => recs.map(textOf).find((s) => s.startsWith(p))!;
+
+ test("a background Bash is listed open at the first turn_duration, then closed by its notification", () => {
+ const w = find("Use the Bash tool with run_in_background");
+ const at = witnessIndex(n, w);
+ const td = indexOf(n, (r) => r.subtype === "turn_duration", at);
+ const first = run(n, [{ at, witness: text(w) }], { upTo: td + 1 });
+ const t1 = cur(first.views[0]);
+ expect(t1.backgroundShellsOpen).toEqual(["sleep 10; echo BGDONE"]);
+ expect(t1.agentsLaunched).toBe(0);
+ expect(t1.turnDurationAfterLast).toEqual({ pendingBackgroundAgentCount: null });
+ const notif = indexOf(
+ n,
+ (r) => r.type === "user" && r.origin?.kind === "task-notification",
+ td
+ );
+ const woke = run(n, [{ at, witness: text(w) }], { upTo: notif + 1 });
+ expect(cur(woke.views[0]).wakingAfterLast).toBe(true);
+ expect(cur(woke.views[0]).backgroundShellsOpen).toEqual([]);
+ const td2 = indexOf(n, (r) => r.subtype === "turn_duration", notif);
+ const end = run(n, [{ at, witness: text(w) }], { upTo: td2 + 1 });
+ const t3 = cur(end.views[0]);
+ expect(t3.wakingAfterLast).toBe(false);
+ expect(t3.turnDurationAfterLast).not.toBeNull();
+ expect(t3.assistantText[0]).toBe("STARTED");
+ expect(t3.assistantText.length).toBe(2); // the re-wake stays in the same turn
+ });
+
+ test("a background agent is counted from toolUseResult.isAsync (its input had no run_in_background)", () => {
+ const w = find("Use the Agent tool with run_in_background");
+ const at = witnessIndex(n, w);
+ const use = recs.findIndex(
+ (r, i) =>
+ i > at && r.type === "assistant" && r.message.content.some((b: Rec) => b.name === "Agent")
+ );
+ expect(
+ recs[use]!.message.content.find((b: Rec) => b.name === "Agent").input.run_in_background
+ ).toBeUndefined();
+ const td = indexOf(n, (r) => r.subtype === "turn_duration", at);
+ const first = run(n, [{ at, witness: text(w) }], { upTo: td + 1 });
+ const t1 = cur(first.views[0]);
+ expect(t1.agentsLaunched).toBe(1);
+ expect(t1.agentsCompleted).toBe(0);
+ expect(t1.turnDurationAfterLast).toEqual({ pendingBackgroundAgentCount: 1 });
+ const td2 = indexOf(n, (r) => r.subtype === "turn_duration", td + 1);
+ const end = run(n, [{ at, witness: text(w) }], { upTo: td2 + 1 });
+ const t2 = cur(end.views[0]);
+ expect([t2.agentsLaunched, t2.agentsCompleted]).toEqual([1, 1]);
+ expect(t2.turnDurationAfterLast).toEqual({ pendingBackgroundAgentCount: null });
+ });
+});
+
+describe("Claude Code's own continuations wake the model", () => {
+ test("max_tokens: each isMeta 'Output token limit hit' record wakes; the turn ends in a max_output_tokens API error", () => {
+ const n = "max-tokens-hookless";
+ const w = "Write a 400-word story about a pear, as plain text, no tools.";
+ const at = witnessIndex(n, w);
+ const meta = indexOf(n, (r) => r.type === "user" && r.isMeta === true, at);
+ expect(textOf(transcriptRecords(n)[meta]!)).toStartWith("Output token limit hit.");
+ const mid = run(n, [{ at, witness: text(w) }], { upTo: meta + 1 });
+ expect(cur(mid.views[0]).lastAssistant?.stopReason).toBe("max_tokens");
+ expect(cur(mid.views[0]).wakingAfterLast).toBe(true);
+ const end = run(n, [{ at, witness: text(w) }]);
+ const t = cur(end.views[0]);
+ expect(t.wakingAfterLast).toBe(false);
+ expect(t.apiError?.category).toBe("max_output_tokens");
+ expect(t.turnDurationAfterLast).not.toBeNull();
+ });
+
+ test("refusal (redacted corpus): the companion isMeta record wakes; the model continues", () => {
+ const n = "corpus-redacted/refusal-then-fallback";
+ const recs = transcriptRecords(n);
+ const w = textOf(recs[0]!);
+ const refusal = recs.findIndex(
+ (r) => r.type === "assistant" && r.message.stop_reason === "refusal"
+ );
+ const companion = indexOf(n, (r) => r.type === "user" && r.isMeta === true, refusal);
+ const mid = run(n, [{ at: 0, witness: text(w) }], { upTo: companion + 1 });
+ expect(cur(mid.views[0]).lastAssistant?.stopReason).toBe("refusal");
+ expect(cur(mid.views[0]).wakingAfterLast).toBe(true);
+ const end = run(n, [{ at: 0, witness: text(w) }]);
+ expect(cur(end.views[0]).lastAssistant?.stopReason).not.toBe("refusal");
+ });
+});
+
+describe("compaction inside a turn (H12)", () => {
+ test("redacted corpus turn: text before and after the boundary stays in one answer", () => {
+ const n = "corpus-redacted/auto-compaction-in-turn";
+ const recs = transcriptRecords(n);
+ const w = textOf(recs[0]!);
+ const boundary = recs.findIndex((r) => r.subtype === "compact_boundary");
+ const { views } = run(n, [{ at: 0, witness: text(w) }]);
+ const t = cur(views[0]);
+ expect(t.compactions).toBe(1);
+ expect(t.turnDurationAfterLast).not.toBeNull();
+ const textsBefore = recs
+ .slice(0, boundary)
+ .flatMap((r) =>
+ r.type === "assistant" && !r.isSidechain
+ ? r.message.content.filter((b: Rec) => b.type === "text" && b.text)
+ : []
+ );
+ const textsAfter = recs
+ .slice(boundary)
+ .flatMap((r) =>
+ r.type === "assistant" && !r.isSidechain
+ ? r.message.content.filter((b: Rec) => b.type === "text" && b.text)
+ : []
+ );
+ expect(textsBefore.length).toBeGreaterThan(0);
+ expect(textsAfter.length).toBeGreaterThan(0);
+ expect(t.assistantText.length).toBe(textsBefore.length + textsAfter.length);
+ });
+
+ test("/compact is a command turn: accepted by <command-name>, no assistant message", () => {
+ const n = "tools-session";
+ const recs = transcriptRecords(n);
+ const witness = recs.findIndex(
+ (r) => r.type === "user" && textOf(r).includes("<command-name>/compact</command-name>")
+ );
+ // The offset is marked before delivery, so the boundary and summary written before the witness line belong to this turn.
+ const mark = recs.findIndex((r) => r.subtype === "compact_boundary") - 1;
+ const { views } = run(n, [{ at: mark, witness: { kind: "command", name: "compact" } }], {
+ upTo: witness + 2,
+ });
+ const t = cur(views[0]);
+ expect(t.acceptedAt).not.toBeNull();
+ expect(t.lastAssistant).toBeNull();
+ });
+});
+
+describe("read coverage of a file-delivered turn (X-H5, R3-M3)", () => {
+ test("the template turn: every line returned, CRs stripped, answer after the Read", () => {
+ const n = "tools-session";
+ const recs = transcriptRecords(n);
+ const w = recs.map(textOf).find((s) => s.startsWith("Your task is in the file"))!;
+ const file = w.match(/`([^`]+)`/)![1]!;
+ const body = `Reply with the word KIWI, then on a new line the number of lines in this file.\nSecond line.\r\nThird line with a tab:\there.\n${"x".repeat(50)}\n`;
+ const { views } = run(
+ n,
+ [{ at: witnessIndex(n, w), witness: text(w), delivery: { file, text: body } }],
+ {
+ upTo: indexOf(n, (r) => r.subtype === "turn_duration", witnessIndex(n, w)) + 1,
+ }
+ );
+ const t = cur(views[0]);
+ expect(t.delivery).toEqual({ file, lines: 5 });
+ expect(t.readCoverage).toMatchObject({ complete: true, reads: 1, linesReturned: 5 });
+ expect(t.readCoverage.completedAtOffset).not.toBeNull();
+ expect(t.assistantText).toEqual(["KIWI\n5"]);
+ expect(t.preambleBytes).toBe(0);
+ });
+
+ test("a token-capped read (lines 1-750 of 1801) is incomplete", () => {
+ const n = "slash-and-reads";
+ const w =
+ "Use the Read tool once on the file big.txt with no offset or limit, then reply with the single word READ.";
+ const file = "/private/tmp/cc2/s03b-tools/cwd/big.txt";
+ const { views } = run(n, [
+ { at: witnessIndex(n, w), witness: text(w), delivery: { file, text: BIG } },
+ ]);
+ const t = cur(views[0]);
+ expect(t.readCoverage).toMatchObject({
+ complete: false,
+ reads: 1,
+ linesReturned: 750,
+ completedAtOffset: null,
+ });
+ // never complete: the answer is the text after the last Read result
+ expect(t.assistantText).toEqual(["READ"]);
+ });
+
+ test("paging with offset:0 (numbered from 0) and an is_error first read still covers every line", () => {
+ const n = "read-limits";
+ const w =
+ "Read the whole file big.txt with the Read tool, paging with offset and limit until you have every line, then reply with the number of the last line.";
+ const file = "/private/tmp/cc2/s11-readlimits/cwd/big.txt";
+ const recs = transcriptRecords(n);
+ const at = witnessIndex(n, w);
+ const errors = recs
+ .slice(at)
+ .filter((r) => r.type === "user" && r.message?.content?.[0]?.is_error).length;
+ expect(errors).toBe(1);
+ const { views } = run(n, [{ at, witness: text(w), delivery: { file, text: BIG } }]);
+ const t = cur(views[0]);
+ expect(t.readCoverage).toMatchObject({ complete: true, reads: 5, linesReturned: 1801 });
+ // text written before coverage completed is preamble, not answer
+ const completedIdx = recs.findIndex(
+ (r, i) => i > at && r.type === "user" && r.toolUseResult?.file?.startLine === 1800
+ );
+ const preamble = recs
+ .slice(at, completedIdx)
+ .flatMap((r) =>
+ r.type === "assistant"
+ ? r.message.content
+ .filter((b: Rec) => b.type === "text" && b.text)
+ .map((b: Rec) => b.text)
+ : []
+ );
+ expect(t.preambleBytes).toBe(
+ preamble.reduce((s: number, x: string) => s + Buffer.byteLength(x), 0)
+ );
+ expect(t.assistantText.join("")).toContain("1801");
+ });
+
+ test("a returned line whose text differs from the file is not covered", () => {
+ const n = "read-limits";
+ const w =
+ "Read the whole file big.txt with the Read tool, paging with offset and limit until you have every line, then reply with the number of the last line.";
+ const file = "/private/tmp/cc2/s11-readlimits/cwd/big.txt";
+ const altered = BIG.replace("\n900 lorem", "\n900 LOREM");
+ const { views } = run(n, [
+ { at: witnessIndex(n, w), witness: text(w), delivery: { file, text: altered } },
+ ]);
+ const t = cur(views[0]);
+ expect(t.readCoverage.complete).toBe(false);
+ expect(t.readCoverage.linesReturned).toBe(1800);
+ });
+
+ test("lines of 40,000 and 90,005 characters come back whole and are covered", () => {
+ const n = "read-limits";
+ for (const [f, len] of [
+ ["line40k.txt", 40000],
+ ["line90k.txt", 90000],
+ ] as const) {
+ const w = `Use the Read tool once on the file ${f} with no offset or limit, then reply with the single word READ.`;
+ const file = `/private/tmp/cc2/s11-readlimits/cwd/${f}`;
+ const { views } = run(
+ n,
+ [
+ {
+ at: witnessIndex(n, w),
+ witness: text(w),
+ delivery: { file, text: `a\n${longLine(len)}\nz\n` },
+ },
+ ],
+ {
+ upTo: indexOf(n, (r) => r.subtype === "turn_duration", witnessIndex(n, w)) + 1,
+ }
+ );
+ expect(cur(views[0]).readCoverage).toMatchObject({ complete: true, reads: 1 });
+ }
+ });
+
+ test("a CRLF file is covered (Read strips the CRs)", () => {
+ const n = "slash-and-reads";
+ const w =
+ "Use the Read tool once on the file crlf.txt with no offset or limit, then reply with the single word READ.";
+ const { views } = run(
+ n,
+ [
+ {
+ at: witnessIndex(n, w),
+ witness: text(w),
+ delivery: {
+ file: "/private/tmp/cc2/s03b-tools/cwd/crlf.txt",
+ text: "alpha\r\nbeta\r\ngamma\r\n",
+ },
+ },
+ ],
+ {
+ upTo: indexOf(n, (r) => r.subtype === "turn_duration", witnessIndex(n, w)) + 1,
+ }
+ );
+ expect(cur(views[0]).readCoverage).toMatchObject({ complete: true, linesReturned: 4 });
+ });
+
+ test("a turn with no delivery reports complete coverage and no preamble", () => {
+ const n = "pear-hookless";
+ const w = "Reply with exactly PEAR and nothing else.";
+ const { views } = run(n, [{ at: witnessIndex(n, w), witness: text(w) }]);
+ expect(cur(views[0]).delivery).toBeNull();
+ expect(cur(views[0]).readCoverage.complete).toBe(true);
+ });
+});
+
+describe("tailing", () => {
+ test("availability: absent, empty (nothing after the offset), ok, off", async () => {
+ const { appendFileSync, mkdtempSync, rmSync, writeFileSync } = await import("node:fs");
+ const { tmpdir } = await import("node:os");
+ const { TranscriptFollower } = await import("./transcript-follower.js");
+ const dir = mkdtempSync(join(tmpdir(), "pane-avail-"));
+ cleanups.push(() => rmSync(dir, { recursive: true, force: true }));
+ const path = join(dir, "t.jsonl");
+ const f = new TranscriptFollower(path, join(dir, "subagents"));
+ expect(f.view().availability).toBe("absent");
+ writeFileSync(path, "");
+ f.poll();
+ f.openTurn({
+ index: 1,
+ offset: f.size(),
+ witness: text("Reply with exactly PEAR and nothing else."),
+ });
+ expect(f.view().availability).toBe("empty");
+ const lines = (await import("./test-helpers/transcript-fixtures.js")).transcriptLines(
+ "pear-hookless"
+ );
+ appendFileSync(path, `${lines.join("\n")}\n`);
+ f.poll();
+ expect(f.view().availability).toBe("ok");
+ f.markSavingOff();
+ expect(f.view().availability).toBe("off");
+ });
+
+ test("a record split across two appends is applied once, when complete", async () => {
+ const { appendFileSync, mkdtempSync, rmSync, writeFileSync } = await import("node:fs");
+ const { tmpdir } = await import("node:os");
+ const { TranscriptFollower } = await import("./transcript-follower.js");
+ const dir = mkdtempSync(join(tmpdir(), "pane-tail-"));
+ cleanups.push(() => rmSync(dir, { recursive: true, force: true }));
+ const path = join(dir, "t.jsonl");
+ writeFileSync(path, "");
+ const f = new TranscriptFollower(path, join(dir, "subagents"));
+ expect(f.view().availability).toBe("empty");
+ const w = "Reply with exactly PEAR and nothing else.";
+ f.openTurn({ index: 1, offset: f.size(), witness: text(w) });
+ const lines = (await import("./test-helpers/transcript-fixtures.js")).transcriptLines(
+ "pear-hookless"
+ );
+ const all = `${lines.join("\n")}\n`;
+ const cut = all.indexOf("\n", all.indexOf('"type":"assistant"')) - 20;
+ appendFileSync(path, all.slice(0, cut));
+ f.poll();
+ const partial = f.view().current!;
+ appendFileSync(path, all.slice(cut));
+ f.poll();
+ const whole = f.view().current!;
+ expect(partial.turnDurationAfterLast).toBeNull();
+ expect(whole.assistantText).toEqual(["PEAR"]);
+ expect(whole.turnDurationAfterLast).not.toBeNull();
+ });
+});
diff --git a/packages/cli/src/pane/transcript-follower.ts b/packages/cli/src/pane/transcript-follower.ts
new file mode 100644
index 00000000..a7b70376
--- /dev/null
+++ b/packages/cli/src/pane/transcript-follower.ts
@@ -0,0 +1,722 @@
+/**
+ * The turn-scoped transcript oracle (architecture §2.7, D3).
+ *
+ * Claude Code writes `<config>/projects/<slug(realpath cwd)>/<uuid>.jsonl` for the
+ * session claudish started with `--session-id <uuid>`, and subagents write
+ * `<uuid>/subagents/agent-<id>.jsonl`. The follower tails both, partial-line safe, and
+ * reduces the records into the facts the settle rule (`settle-rule.ts`) reads.
+ *
+ * Turns are segmented by claudish's OWN deliveries, never by user records: turn N owns
+ * every record whose byte offset is past N's offset (taken BEFORE delivery) and before
+ * N+1's offset, so evidence from an earlier turn can never satisfy a later one (C3, H12).
+ *
+ * Record shapes are pinned by the phase-2 captures of Claude Code 2.1.290
+ * (`ai-docs/reports/mcp-magmux-panes/phase2-captures.md`), notably:
+ * - the witness is a main-chain user record whose text equals the typed line
+ * (`origin.kind:"human"`), or a `<command-name>/x</command-name>` record;
+ * - between the last assistant record and `turn_duration` Claude Code writes
+ * `attachment/prompt_snapshot` and state records, so "directly followed" means "no
+ * `stop_hook_summary` in between";
+ * - a background agent is recognised by its RESULT (`toolUseResult.isAsync`), not by
+ * `run_in_background` in the input — haiku launched one with neither flag set;
+ * - an `isMeta` user record after the last assistant message is Claude Code waking the
+ * model itself (the `max_tokens` continuation "Output token limit hit…", the refusal
+ * companion), so the turn is not over;
+ * - Read returns `toolUseResult.file {content, startLine, numLines, totalLines}`;
+ * `offset:0` reports `startLine:0` for content that starts at file line 1, and CRs
+ * are stripped.
+ */
+
+import {
+ closeSync,
+ existsSync,
+ fstatSync,
+ openSync,
+ readSync,
+ readdirSync,
+ realpathSync,
+ statSync,
+} from "node:fs";
+import { join } from "node:path";
+
+export type Witness =
+ | { kind: "text"; text: string } // typed plain line or the file-reference instruction (exact)
+ | { kind: "command"; name: string }; // slash command: its <command-name> record
+
+export interface TurnDelivery {
+ /** absolute path of the turn file the child must Read */
+ file: string;
+ /** the exact bytes written to it */
+ text: string;
+}
+
+export interface ReadCoverage {
+ linesReturned: number;
+ complete: boolean;
+ reads: number;
+ completedAtOffset: number | null;
+}
+
+export interface TurnView {
+ index: number;
+ acceptedAt: string | null; // ISO of the witness record; null until accepted
+ acceptedOffset: number | null;
+ /** assistant text blocks after the witness, in order (excl. isApiErrorMessage); for a file-delivered
+ * turn only those after the Read result that completed coverage */
+ assistantText: string[];
+ lastAssistant: { messageId: string; stopReason: string | null; isApiError: boolean } | null;
+ turnDurationAfterLast: { pendingBackgroundAgentCount: number | null } | null;
+ stopHookSummaryAfterLast: boolean;
+ interruptAfterLast: { forToolUse: boolean } | null;
+ /** a main-chain user record that wakes the model (task notification, Stop-hook feedback, an isMeta
+ * continuation) arrived after the last assistant record, and no assistant record followed it yet */
+ wakingAfterLast: boolean;
+ pendingTool: { id: string; name: string } | null;
+ agentsLaunched: number;
+ agentsCompleted: number;
+ backgroundShellsOpen: string[];
+ apiError: { status: number | null; category: string | null; text: string } | null;
+ compactions: number;
+ delivery: { file: string; lines: number } | null;
+ readCoverage: ReadCoverage;
+ preambleBytes: number;
+ /** offset of the last main-chain chat record (user or assistant) of this turn */
+ lastChatOffset: number | null;
+}
+
+export interface SessionFacts {
+ stopHooksSeen: boolean;
+ provenHookless: boolean;
+}
+
+export interface TranscriptView {
+ availability: "ok" | "absent" | "empty" | "off";
+ current: TurnView | null;
+ settledTurns: number;
+ usage: { tokensIn: number; tokensOut: number };
+ toolCalls: number;
+ lastAppendAt: number | null;
+ session: SessionFacts;
+}
+
+/* ───────────────────────────── pure reducer ───────────────────────────── */
+
+interface ReadState {
+ delivery: TurnDelivery;
+ fileLines: string[];
+ required: number;
+ covered: Set<number>;
+ reads: number;
+ readIds: Set<string>;
+ completedAtOffset: number | null;
+ lastReadOffset: number | null;
+}
+
+interface TurnState {
+ index: number;
+ offset: number;
+ witness: Witness;
+ acceptedAt: string | null;
+ acceptedOffset: number | null;
+ texts: Array<{ offset: number; text: string }>;
+ lastAssistant: {
+ messageId: string;
+ stopReason: string | null;
+ isApiError: boolean;
+ offset: number;
+ } | null;
+ td: { pendingBackgroundAgentCount: number | null } | null;
+ stopHookAfterLast: boolean;
+ interrupt: { forToolUse: boolean } | null;
+ waking: boolean;
+ pending: Map<string, string>; // tool_use id → name
+ agents: Set<string>;
+ agentsDone: Set<string>;
+ shells: Map<string, string>; // backgroundTaskId → command
+ shellToolIds: Map<string, string>; // tool_use id → command (until its result names the task id)
+ apiError: TurnView["apiError"];
+ compactions: number;
+ read: ReadState | null;
+ lastChatOffset: number | null;
+}
+
+export interface FollowerState {
+ turns: TurnState[];
+ usage: Map<string, { in: number; out: number }>;
+ toolUseIds: Set<string>;
+ session: SessionFacts;
+ records: number;
+ resolvePath: (p: string) => string;
+}
+
+export function initialFollowerState(
+ resolvePath: (p: string) => string = safeRealpath
+): FollowerState {
+ return {
+ turns: [],
+ usage: new Map(),
+ toolUseIds: new Set(),
+ session: { stopHooksSeen: false, provenHookless: false },
+ records: 0,
+ resolvePath,
+ };
+}
+
+export function safeRealpath(p: string): string {
+ try {
+ return realpathSync(p);
+ } catch {
+ return p;
+ }
+}
+
+// Transcript records are untyped JSON written by Claude Code; every read below is guarded.
+// biome-ignore lint/suspicious/noExplicitAny: raw JSON records, narrowed field by field
+type Rec = Record<string, any>;
+
+function contentOf(r: Rec): unknown {
+ return r.message?.content;
+}
+
+/** Text of a user record: a string content, or its text blocks joined. */
+export function userText(r: Rec): string {
+ const c = contentOf(r);
+ if (typeof c === "string") return c;
+ if (!Array.isArray(c)) return "";
+ return c
+ .filter((b) => b?.type === "text" && typeof b.text === "string")
+ .map((b) => b.text)
+ .join("");
+}
+
+function hasToolResult(r: Rec): boolean {
+ const c = contentOf(r);
+ return Array.isArray(c) && c.some((b) => b?.type === "tool_result");
+}
+
+function isMainUser(r: Rec): boolean {
+ return r.type === "user" && !r.isSidechain;
+}
+
+function isTaskNotification(r: Rec): boolean {
+ return r.origin?.kind === "task-notification" || userText(r).includes("<task-notification>");
+}
+
+function taskIdOf(text: string): string | null {
+ const m = text.match(/<task-id>([^<]+)<\/task-id>/);
+ return m ? (m[1] ?? "").trim() : null;
+}
+
+function matchesWitness(r: Rec, w: Witness): boolean {
+ if (!isMainUser(r) || hasToolResult(r)) return false;
+ const text = userText(r);
+ if (w.kind === "text") return !r.isMeta && text.trim() === w.text.trim();
+ return text.includes(`<command-name>/${w.name}</command-name>`);
+}
+
+function recordUsage(state: FollowerState, r: Rec): void {
+ if (r.type !== "assistant") return;
+ const m = r.message;
+ const id = m?.id;
+ if (typeof id !== "string") return;
+ const u = m.usage ?? {};
+ const num = (x: unknown) => (typeof x === "number" && Number.isFinite(x) ? x : 0);
+ state.usage.set(id, {
+ in: num(u.input_tokens) + num(u.cache_creation_input_tokens) + num(u.cache_read_input_tokens),
+ out: num(u.output_tokens),
+ });
+ for (const b of m.content ?? [])
+ if (b?.type === "tool_use" && typeof b.id === "string") state.toolUseIds.add(b.id);
+}
+
+function turnFor(state: FollowerState, offset: number): TurnState | null {
+ for (let i = state.turns.length - 1; i >= 0; i--) {
+ const t = state.turns[i];
+ if (t && offset > t.offset) return t;
+ }
+ return null;
+}
+
+/** Strip a trailing CR: Read returns CRLF files with LF line ends (captured). */
+function stripCr(s: string): string {
+ return s.endsWith("\r") ? s.slice(0, -1) : s;
+}
+
+function newReadState(d: TurnDelivery): ReadState {
+ const fileLines = d.text.split("\n").map(stripCr);
+ // Read numbers the empty line after a final newline; coverage does not require it.
+ const required =
+ fileLines.length > 0 && fileLines[fileLines.length - 1] === ""
+ ? fileLines.length - 1
+ : fileLines.length;
+ return {
+ delivery: d,
+ fileLines,
+ required,
+ covered: new Set(),
+ reads: 0,
+ readIds: new Set(),
+ completedAtOffset: null,
+ lastReadOffset: null,
+ };
+}
+
+/** Lines a Read result returned, as [fileLineNumber, text] pairs. */
+function returnedLines(r: Rec, block: Rec): Array<[number, string]> {
+ const f = r.toolUseResult?.file;
+ if (f && typeof f.content === "string") return fileResultLines(f);
+ return renderedLines(blockText(block));
+}
+
+/** `toolUseResult.file`: `offset:0` reports `startLine:0` for content that starts at line 1. */
+function fileResultLines(f: Rec): Array<[number, string]> {
+ const start = Math.max(1, typeof f.startLine === "number" ? f.startLine : 1);
+ let lines = (f.content as string).split("\n").map(stripCr);
+ if (typeof f.numLines === "number") lines = lines.slice(0, f.numLines);
+ return lines.map((t: string, k: number) => [start + k, t]);
+}
+
+function blockText(block: Rec): string {
+ if (typeof block.content === "string") return block.content;
+ if (Array.isArray(block.content)) return block.content.map((c: Rec) => c?.text ?? "").join("");
+ return "";
+}
+
+/** Fallback: parse the numbered rendering `N\t<line>` (labels start at 0 for offset:0). */
+function renderedLines(text: string): Array<[number, string]> {
+ const out: Array<[number, string]> = [];
+ let shift = 0;
+ let first = true;
+ for (const line of text.split("\n")) {
+ const m = line.match(/^\s*(\d+)\t(.*)$/);
+ if (!m) continue;
+ const label = Number(m[1]);
+ if (first) {
+ shift = label === 0 ? 1 : 0;
+ first = false;
+ }
+ out.push([label + shift, stripCr(m[2] ?? "")]);
+ }
+ return out;
+}
+
+function applyReadUse(state: FollowerState, t: TurnState, block: Rec): void {
+ if (!t.read || block?.type !== "tool_use" || block.name !== "Read") return;
+ const fp = block.input?.file_path;
+ if (typeof fp !== "string") return;
+ if (state.resolvePath(fp) === state.resolvePath(t.read.delivery.file))
+ t.read.readIds.add(block.id);
+}
+
+function applyReadResult(t: TurnState, r: Rec, block: Rec, offset: number): void {
+ const rs = t.read;
+ if (!rs || block?.type !== "tool_result" || !rs.readIds.has(block.tool_use_id)) return;
+ rs.lastReadOffset = offset;
+ if (block.is_error) return;
+ rs.reads++;
+ for (const [n, text] of returnedLines(r, block)) {
+ if (n >= 1 && n <= rs.fileLines.length && rs.fileLines[n - 1] === text) rs.covered.add(n);
+ }
+ if (rs.completedAtOffset === null && isComplete(rs)) rs.completedAtOffset = offset;
+}
+
+function isComplete(rs: ReadState): boolean {
+ for (let n = 1; n <= rs.required; n++) if (!rs.covered.has(n)) return false;
+ return true;
+}
+
+function applyAssistant(state: FollowerState, t: TurnState, r: Rec, offset: number): void {
+ const m = r.message ?? {};
+ const isApiError = r.isApiErrorMessage === true;
+ t.lastAssistant = {
+ messageId: String(m.id ?? ""),
+ stopReason: m.stop_reason ?? null,
+ isApiError,
+ offset,
+ };
+ t.lastChatOffset = offset;
+ t.td = null;
+ t.stopHookAfterLast = false;
+ t.interrupt = null;
+ t.waking = false;
+ t.apiError = isApiError ? apiErrorOf(r) : null;
+ if (isApiError) return;
+ for (const b of m.content ?? []) applyAssistantBlock(state, t, b, offset);
+}
+
+function apiErrorOf(r: Rec): TurnView["apiError"] {
+ const text = (r.message?.content ?? [])
+ .filter((b: Rec) => b?.type === "text")
+ .map((b: Rec) => b.text)
+ .join("");
+ return {
+ status: typeof r.apiErrorStatus === "number" ? r.apiErrorStatus : null,
+ category: typeof r.error === "string" ? r.error : null,
+ text,
+ };
+}
+
+function applyAssistantBlock(state: FollowerState, t: TurnState, b: Rec, offset: number): void {
+ if (b?.type === "text" && typeof b.text === "string" && b.text.length > 0) {
+ t.texts.push({ offset, text: b.text });
+ return;
+ }
+ if (b?.type !== "tool_use" || typeof b.id !== "string") return;
+ t.pending.set(b.id, String(b.name ?? ""));
+ if (b.name === "Bash" && b.input?.run_in_background)
+ t.shellToolIds.set(b.id, String(b.input?.command ?? ""));
+ applyReadUse(state, t, b);
+}
+
+function applyToolResults(t: TurnState, r: Rec, blocks: Rec[], offset: number): void {
+ const tur = r.toolUseResult && typeof r.toolUseResult === "object" ? r.toolUseResult : null;
+ for (const b of blocks) {
+ if (b?.type !== "tool_result") continue;
+ t.pending.delete(b.tool_use_id);
+ // A background agent is recognised by its result, not by run_in_background in its input.
+ if (tur?.isAsync === true && typeof tur.agentId === "string") t.agents.add(tur.agentId);
+ if (typeof tur?.backgroundTaskId === "string")
+ t.shells.set(tur.backgroundTaskId, t.shellToolIds.get(b.tool_use_id) ?? "");
+ applyReadResult(t, r, b, offset);
+ }
+}
+
+function applyNotification(t: TurnState, text: string): void {
+ const id = taskIdOf(text);
+ if (!id) return;
+ if (t.agents.has(id)) t.agentsDone.add(id);
+ t.shells.delete(id);
+}
+
+function applyUser(t: TurnState, r: Rec, offset: number): void {
+ const c = contentOf(r);
+ if (Array.isArray(c) && c.some((b) => b?.type === "tool_result")) {
+ applyToolResults(t, r, c as Rec[], offset);
+ return;
+ }
+ if (r.isCompactSummary) {
+ t.compactions++;
+ return;
+ }
+ const text = userText(r);
+ if (text.startsWith("[Request interrupted by user")) {
+ t.interrupt = { forToolUse: text.includes("for tool use") };
+ t.pending.clear();
+ return;
+ }
+ if (isTaskNotification(r)) applyNotification(t, text);
+ if (t.lastAssistant && !t.interrupt) {
+ t.waking = true;
+ t.lastChatOffset = offset;
+ }
+}
+
+function acceptIfWitness(t: TurnState, r: Rec, offset: number): void {
+ if (!matchesWitness(r, t.witness)) return;
+ t.acceptedAt = typeof r.timestamp === "string" ? r.timestamp : new Date().toISOString();
+ t.acceptedOffset = offset;
+ t.lastChatOffset = offset;
+}
+
+/** Pure: fold one main-transcript record at byte `offset` into the state. */
+export function applyRecord(
+ state: FollowerState,
+ record: Record<string, unknown>,
+ offset: number
+): FollowerState {
+ const r = record as Rec;
+ state.records++;
+ recordUsage(state, r);
+ if (r.isSidechain) return state;
+ if (r.type === "system" && r.subtype === "stop_hook_summary") {
+ state.session.stopHooksSeen = true;
+ state.session.provenHookless = false;
+ }
+ const t = turnFor(state, offset);
+ if (!t) return state;
+
+ if (t.acceptedAt === null) {
+ acceptIfWitness(t, r, offset);
+ return state;
+ }
+
+ if (r.type === "assistant") applyAssistant(state, t, r, offset);
+ else if (r.type === "user") applyUser(t, r, offset);
+ else if (r.type === "system" && r.subtype === "stop_hook_summary") {
+ if (t.lastAssistant) t.stopHookAfterLast = true;
+ } else if (r.type === "system" && r.subtype === "turn_duration") applyTurnDuration(state, t, r);
+ // compact_boundary carries no turn fact; compactions are counted on the isCompactSummary record
+ return state;
+}
+
+function applyTurnDuration(state: FollowerState, t: TurnState, r: Rec): void {
+ const la = t.lastAssistant;
+ if (!la || t.waking) return;
+ const p = r.pendingBackgroundAgentCount;
+ t.td = { pendingBackgroundAgentCount: typeof p === "number" ? p : null };
+ // `end_turn` → `turn_duration` with no stop_hook_summary between proves the session has no
+ // Stop hooks (attachments and state records in between are normal: prompt_snapshot, mode, …).
+ const proves =
+ !t.stopHookAfterLast && !t.interrupt && la.stopReason === "end_turn" && !la.isApiError;
+ if (proves && !state.session.stopHooksSeen) state.session.provenHookless = true;
+}
+
+/** Fold one subagent record: usage, tool calls, and a Read of the turn file delegated to a subagent. */
+export function applySubagentRecord(
+ state: FollowerState,
+ record: Record<string, unknown>,
+ offsetKey: number
+): FollowerState {
+ const r = record as Rec;
+ recordUsage(state, r);
+ const t = state.turns[state.turns.length - 1];
+ if (!t?.read || t.acceptedAt === null) return state;
+ if (r.type === "assistant") for (const b of r.message?.content ?? []) applyReadUse(state, t, b);
+ if (r.type === "user" && Array.isArray(contentOf(r)))
+ for (const b of contentOf(r) as Rec[]) applyReadResult(t, r, b, offsetKey);
+ return state;
+}
+
+export function openTurnState(
+ state: FollowerState,
+ t: { index: number; offset: number; witness: Witness; delivery?: TurnDelivery | null }
+): FollowerState {
+ state.turns.push({
+ index: t.index,
+ offset: t.offset,
+ witness: t.witness,
+ acceptedAt: null,
+ acceptedOffset: null,
+ texts: [],
+ lastAssistant: null,
+ td: null,
+ stopHookAfterLast: false,
+ interrupt: null,
+ waking: false,
+ pending: new Map(),
+ agents: new Set(),
+ agentsDone: new Set(),
+ shells: new Map(),
+ shellToolIds: new Map(),
+ apiError: null,
+ compactions: 0,
+ read: t.delivery ? newReadState(t.delivery) : null,
+ lastChatOffset: null,
+ });
+ return state;
+}
+
+export function turnView(t: TurnState): TurnView {
+ const rs = t.read;
+ let texts = t.texts;
+ let preambleBytes = 0;
+ if (rs) {
+ const cut = rs.completedAtOffset ?? rs.lastReadOffset;
+ if (cut !== null) {
+ const before = texts.filter((x) => x.offset < cut);
+ preambleBytes = before.reduce((n, x) => n + Buffer.byteLength(x.text), 0);
+ texts = texts.filter((x) => x.offset > cut);
+ }
+ }
+ const pendingEntry = [...t.pending.entries()].pop();
+ return {
+ index: t.index,
+ acceptedAt: t.acceptedAt,
+ acceptedOffset: t.acceptedOffset,
+ assistantText: texts.map((x) => x.text),
+ lastAssistant: t.lastAssistant
+ ? {
+ messageId: t.lastAssistant.messageId,
+ stopReason: t.lastAssistant.stopReason,
+ isApiError: t.lastAssistant.isApiError,
+ }
+ : null,
+ turnDurationAfterLast: t.td,
+ stopHookSummaryAfterLast: t.stopHookAfterLast,
+ interruptAfterLast: t.interrupt,
+ wakingAfterLast: t.waking,
+ pendingTool: pendingEntry ? { id: pendingEntry[0], name: pendingEntry[1] } : null,
+ agentsLaunched: t.agents.size,
+ agentsCompleted: [...t.agents].filter((a) => t.agentsDone.has(a)).length,
+ backgroundShellsOpen: [...t.shells.values()],
+ apiError: t.apiError,
+ compactions: t.compactions,
+ delivery: rs ? { file: rs.delivery.file, lines: rs.fileLines.length } : null,
+ readCoverage: rs
+ ? {
+ linesReturned: rs.covered.size,
+ complete: isComplete(rs),
+ reads: rs.reads,
+ completedAtOffset: rs.completedAtOffset,
+ }
+ : { linesReturned: 0, complete: true, reads: 0, completedAtOffset: null },
+ preambleBytes,
+ lastChatOffset: t.lastChatOffset,
+ };
+}
+
+/* ───────────────────────────── file tailing ───────────────────────────── */
+
+class Tail {
+ offset = 0;
+ private buf = "";
+ constructor(readonly path: string) {}
+
+ /** Read appended bytes; return complete lines with the byte offset each starts at. */
+ read(): Array<{ offset: number; line: string }> {
+ let fd: number;
+ try {
+ fd = openSync(this.path, "r");
+ } catch {
+ return [];
+ }
+ try {
+ const size = fstatSync(fd).size;
+ const startOfBuf = this.offset - Buffer.byteLength(this.buf);
+ if (size <= this.offset) return [];
+ const chunk = Buffer.alloc(size - this.offset);
+ readSync(fd, chunk, 0, chunk.length, this.offset);
+ this.offset = size;
+ this.buf += chunk.toString("utf8");
+ const out: Array<{ offset: number; line: string }> = [];
+ let pos = startOfBuf;
+ let nl = this.buf.indexOf("\n");
+ while (nl >= 0) {
+ const line = this.buf.slice(0, nl);
+ out.push({ offset: pos, line });
+ pos += Buffer.byteLength(line) + 1;
+ this.buf = this.buf.slice(nl + 1);
+ nl = this.buf.indexOf("\n");
+ }
+ return out;
+ } finally {
+ closeSync(fd);
+ }
+ }
+}
+
+export class TranscriptFollower {
+ private state: FollowerState;
+ private main: Tail;
+ private subs = new Map<string, Tail>();
+ private lastAppend: number | null = null;
+ private settled = 0;
+ private savingOff = false;
+ private clock: () => number;
+
+ constructor(
+ readonly path: string,
+ readonly subagentsDir: string,
+ opts: { now?: () => number; resolvePath?: (p: string) => string } = {}
+ ) {
+ this.state = initialFollowerState(opts.resolvePath);
+ this.main = new Tail(path);
+ this.clock = opts.now ?? Date.now;
+ }
+
+ /** Read appended bytes of the main transcript and every subagent file. True when anything was new. */
+ poll(): boolean {
+ let any = false;
+ for (const { offset, line } of this.main.read()) {
+ any = true;
+ const rec = parse(line);
+ // Offsets are 1-based positions past the line start so a record AT the turn offset
+ // (written after the mark) is strictly greater than it.
+ if (rec) applyRecord(this.state, rec, offset + 1);
+ }
+ if (this.pollSubagents()) any = true;
+ if (any) this.lastAppend = this.clock();
+ return any;
+ }
+
+ private subagentFiles(): string[] {
+ if (!existsSync(this.subagentsDir)) return [];
+ try {
+ return readdirSync(this.subagentsDir).filter((f) => f.endsWith(".jsonl"));
+ } catch {
+ return [];
+ }
+ }
+
+ private pollSubagents(): boolean {
+ let any = false;
+ for (const f of this.subagentFiles()) {
+ let tail = this.subs.get(f);
+ if (!tail) {
+ tail = new Tail(join(this.subagentsDir, f));
+ this.subs.set(f, tail);
+ }
+ for (const { line } of tail.read()) {
+ any = true;
+ const rec = parse(line);
+ if (rec) applySubagentRecord(this.state, rec, this.main.offset + 1);
+ }
+ }
+ return any;
+ }
+
+ /** Current byte offset of the main transcript (after a poll). The turn boundary. */
+ size(): number {
+ return this.main.offset;
+ }
+
+ openTurn(t: {
+ index: number;
+ offset: number;
+ witness: Witness;
+ delivery?: TurnDelivery | null;
+ }): void {
+ openTurnState(this.state, t);
+ }
+
+ markSettled(): void {
+ this.settled++;
+ }
+
+ markSavingOff(): void {
+ this.savingOff = true;
+ }
+
+ view(): TranscriptView {
+ const t = this.state.turns[this.state.turns.length - 1] ?? null;
+ let tokensIn = 0;
+ let tokensOut = 0;
+ for (const u of this.state.usage.values()) {
+ tokensIn += u.in;
+ tokensOut += u.out;
+ }
+ let availability: TranscriptView["availability"];
+ if (this.savingOff) availability = "off";
+ else if (!existsSync(this.path)) availability = "absent";
+ else if (t && t.acceptedAt === null && fileSize(this.path) <= t.offset) availability = "empty";
+ else if (!t && fileSize(this.path) === 0) availability = "empty";
+ else availability = "ok";
+ return {
+ availability,
+ current: t ? turnView(t) : null,
+ settledTurns: this.settled,
+ usage: { tokensIn, tokensOut },
+ toolCalls: this.state.toolUseIds.size,
+ lastAppendAt: this.lastAppend,
+ session: { ...this.state.session },
+ };
+ }
+}
+
+function fileSize(p: string): number {
+ try {
+ return statSync(p).size;
+ } catch {
+ return 0;
+ }
+}
+
+function parse(line: string): Record<string, unknown> | null {
+ if (!line.trim()) return null;
+ try {
+ const v = JSON.parse(line);
+ return v && typeof v === "object" ? (v as Record<string, unknown>) : null;
+ } catch {
+ return null;
+ }
+}