Skip to content

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

fix(pane): corroborate turn settle with the input gate, not the box

Jack Rudenkoaf427ddf81ba
diff --git a/packages/cli/src/pane/pane-session.ts b/packages/cli/src/pane/pane-session.ts
index 9f6eaa94..2aade0b3 100644
--- a/packages/cli/src/pane/pane-session.ts
+++ b/packages/cli/src/pane/pane-session.ts
@@ -104,8 +104,6 @@ import {
choiceDialog,
dialogText,
flatText,
- hasChoiceDialog,
- inputBox,
isWorking,
menuAbove,
nameBootScreen,
@@ -114,6 +112,7 @@ import {
screenText,
stopHookRunning,
transcriptSavingOff,
+ workingAboveBox,
} from "./screen-classifier.js";
import {
type MagmuxCapture,
@@ -125,8 +124,8 @@ import {
import { KNOWN_STATUSES, type RegistryRecord, SessionRegistry } from "./session-registry.js";
import {
CORROBORATION_MS,
+ type CorroborationFacts,
SECONDARY_QUIET_MS,
- type ScreenFacts,
type SettleDecision,
agentCountMismatch,
decideSettle,
@@ -196,6 +195,11 @@ const GATE_POLL_MS = 250;
const GATE_REPLY_MS = 1_000;
/** A gate reading older than this, or any reading while disconnected, is unknown. */
const GATE_STALE_MS = 1_000;
+/**
+ * The most gate corroboration may delay a transcript-closed turn (architecture-v2 §7.1,
+ * Jack's decision J2): after this much chat quiet it settles with `settle_gate_unconfirmed`.
+ */
+export const GATE_GRACE_MS = SECONDARY_QUIET_MS;
/**
* `list` showing pane 0 dead this long with no `exit` event: take the exit path anyway.
* The event stays the primary path (it carries `lastLine`); this is its backstop.
@@ -280,6 +284,8 @@ export interface PaneSessionOptions {
*/
resendAfterMs?: number;
corroborationMs?: number;
+ /** GATE_GRACE_MS */
+ gateGraceMs?: number;
bootStaticMs?: number;
/** @deprecated ignored: boot readiness is magmux's `input.ready` (see `REPL_STABLE_MS`) */
replStableMs?: number;
@@ -1965,17 +1971,26 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
}
}
- private screenFacts(): ScreenFacts | null {
+ /**
+ * Settle corroboration (architecture-v2 §7.1, R1.5.1): the gate's fresh reading, plus the
+ * working row and the quiet ABOVE the box located by the cursor. Null while disconnected.
+ * An unlocated box yields nulls, never a veto.
+ */
+ private corroborationFacts(): CorroborationFacts | null {
if (!this.client) return null;
- const box = inputBox(this.screen);
+ const g = this.gateNow();
return {
- boxEmpty: !!box && box.text === "",
- choiceDialog: hasChoiceDialog(this.screen),
- working: isWorking(this.screen),
- aboveBoxQuietMs: Date.now() - this.screen.aboveBoxChangedAt,
+ gate: g ? { ready: g.ready, dialog: g.dialog, reason: g.reason } : null,
+ working: workingAboveBox(this.screen),
+ aboveBoxQuietMs: this.aboveBoxQuietMs(),
};
}
+ /** ms since a row above the located box changed; null when this frame locates no box. */
+ private aboveBoxQuietMs(): number | null {
+ return locateBox(this.screen) ? Date.now() - this.screen.aboveBoxChangedAt : null;
+ }
+
/**
* A turn the gate accepted that the transcript has not witnessed: with the transcript off,
* or still absent or empty `DEGRADED_ENTRY_MS` after the acceptance, it settles from the
@@ -2027,22 +2042,24 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
}
if (this.detectBlocked(t)) return;
const now = Date.now();
+ const transcriptQuietMs = now - (view.lastAppendAt ?? this.startedAtMs);
const decision = decideSettle({
turn: t,
session: view.session,
- transcriptQuietMs: now - (view.lastAppendAt ?? this.startedAtMs),
+ transcriptQuietMs,
chatQuietMs: now - this.lastChatSeenAt,
- screen: this.screenFacts(),
+ facts: this.corroborationFacts(),
paneExited: false,
secondaryQuietMs: this.secondaryQuietMs,
corroborationMs: this.corroborationMs,
+ corroborationGraceMs: this.t("gateGraceMs", GATE_GRACE_MS),
});
if (decision.settled) {
this.settle(t, decision, null);
return;
}
this.activity = decision.activity;
- this.checkTurnEndMissing();
+ this.checkTurnEndMissing(t, transcriptQuietMs);
this.checkAgentCountMismatch(t);
}
@@ -2056,15 +2073,17 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
/**
* R3-M4: `finishing` with a static screen and no Stop-hook UI for N secondary windows.
* The condition is live (it clears the moment work resumes); the anomaly counts how often
- * it began.
+ * it began. A turn whose end record WAS written (turn_duration, or an interrupt) is not
+ * missing one: "the turn ended and the gate disagrees" is `settle_gate_unconfirmed`.
+ * Quiet is measured above the located box, else from the transcript (architecture-v2 §7.2).
*/
- private checkTurnEndMissing(): void {
- if (this.activity !== "finishing") {
+ private checkTurnEndMissing(t: TurnView, transcriptQuietMs: number): void {
+ if (this.activity !== "finishing" || t.turnDurationAfterLast || t.interruptAfterLast) {
this.turnEndMissing = false;
return;
}
if (!this.client) return;
- const quiet = Date.now() - this.screen.aboveBoxChangedAt;
+ const quiet = this.aboveBoxQuietMs() ?? transcriptQuietMs;
const missing =
quiet >= TURN_END_MISSING_FACTOR * this.secondaryQuietMs && !stopHookRunning(this.screen);
if (missing && !this.turnEndMissing) this.anomaly("turn_end_record_missing");
@@ -2232,12 +2251,16 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
return !!t && t.index === this.turnIndex && t.acceptedAt !== null;
}
- /** Degraded settle (§2.8): empty box, no dialog, not working, and an answer or error row gone quiet. */
+ /**
+ * Degraded settle (architecture-v2 §7.3): the gate ready (an empty box) and naming no
+ * dialog, no working row above the located box, and an answer or error row gone quiet.
+ * Quiet is above the located box, else the whole screen's (stricter: a ticking status line
+ * delays it), used only with no transcript witness.
+ */
private screenSettleReady(view: TranscriptView, answer: string, apiError: unknown): boolean {
- const box = inputBox(this.screen);
- if (!box || box.text !== "" || hasChoiceDialog(this.screen) || isWorking(this.screen))
- return false;
- const quiet = Date.now() - this.screen.aboveBoxChangedAt;
+ const g = this.gateNow();
+ if (!g || !g.ready || g.dialog !== null || workingAboveBox(this.screen) === true) return false;
+ const quiet = this.aboveBoxQuietMs() ?? Date.now() - this.screen.changedAt;
if (view.availability === "off" && quiet >= this.secondaryQuietMs) return true;
return (
(!!answer || !!apiError) && quiet >= 2 * this.t("screenSettleQuietMs", SCREEN_SETTLE_QUIET_MS)
@@ -2327,7 +2350,7 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {
session: view.session,
transcriptQuietMs: Number.MAX_SAFE_INTEGER,
chatQuietMs: Number.MAX_SAFE_INTEGER,
- screen: null,
+ facts: null,
paneExited: true,
secondaryQuietMs: this.secondaryQuietMs,
corroborationMs: 0,
diff --git a/packages/cli/src/pane/screen-classifier.ts b/packages/cli/src/pane/screen-classifier.ts
index 69783d9f..139b08c2 100644
--- a/packages/cli/src/pane/screen-classifier.ts
+++ b/packages/cli/src/pane/screen-classifier.ts
@@ -11,6 +11,7 @@
* unknown), never as `blocked` (R3-H1).
*/
+import { locateBox } from "./box-locate.js";
import type { SpanRun } from "./contract.js";
import { type ScreenState, boxTopRow, isBoxRule } from "./screen-model.js";
@@ -272,6 +273,15 @@ export function isWorking(s: ScreenState): boolean {
return region.some((l) => WORKING_ROW.test(l));
}
+/**
+ * `isWorking` over the rows above the box located by the cursor (architecture-v2 §7.5);
+ * null when no box is located, which settle corroboration reads as "no veto".
+ */
+export function workingAboveBox(s: ScreenState): boolean | null {
+ const box = locateBox(s);
+ return box ? s.lines.slice(0, box.top).some((l) => WORKING_ROW.test(l)) : null;
+}
+
/** A Stop hook is running: `· Processing… (running Stop hook · 2s …)`. */
export function stopHookRunning(s: ScreenState): boolean {
return s.lines.some((l) => /\(running Stop hook\b/.test(l));
diff --git a/packages/cli/src/pane/screen-model.ts b/packages/cli/src/pane/screen-model.ts
index bec3275a..594d3864 100644
--- a/packages/cli/src/pane/screen-model.ts
+++ b/packages/cli/src/pane/screen-model.ts
@@ -8,12 +8,16 @@
* or cols — for the pane's whole life.
*
* `aboveBoxChangedAt` moves only when a row ABOVE the input box's top rule changes, so a
- * status line ticking under the box never holds a settle quiet window open (M3). In
+ * status line ticking under the box never holds a settle quiet window open (M3). The box
+ * is the one `locateBox` finds from the cursor row (architecture-v2 §7.5); any change in a
+ * frame where no box is located counts as above it, and readers treat the quiet of a frame
+ * with no located box as unknown. In
* Claude Code 2.1.290 the working row (`· Processing… (running Stop hook · 2s …)`) sits
* above the box and is rewritten every second while anything runs, which is what keeps
* that window closed during a Stop hook (phase-2 capture s04).
*/
+import { locateBox } from "./box-locate.js";
import type { SpanRun } from "./contract.js";
export interface ScreenState {
@@ -108,9 +112,13 @@ function withSize(s: ScreenState, rows: number): { lines: string[]; spans: SpanR
return { lines, spans };
}
-function aboveBoxText(lines: readonly string[], cols: number): string {
- const top = boxTopRow(lines, cols);
- return (top >= 0 ? lines.slice(0, top) : lines).join("\n");
+/**
+ * The rows above the box located by the cursor (architecture-v2 §7.5), or null when the
+ * frame has no located box. No width test: the box is found from the cursor row.
+ */
+function aboveBoxText(s: ScreenState): string | null {
+ const box = locateBox(s);
+ return box ? s.lines.slice(0, box.top).join("\n") : null;
}
function finish(
@@ -128,14 +136,17 @@ function finish(
next.lines.some((l, i) => l !== prev.lines[i]) ||
next.spans.some((r, i) => !sameSpans(r, prev.spans[i]));
if (!visible) return prev;
- const aboveChanged =
- prev.seq === 0 || aboveBoxText(prev.lines, prev.cols) !== aboveBoxText(next.lines, next.cols);
- return {
+ const out: ScreenState = {
...next,
seq: prev.seq + 1,
changedAt: now,
- aboveBoxChangedAt: aboveChanged ? now : prev.aboveBoxChangedAt,
+ aboveBoxChangedAt: prev.aboveBoxChangedAt,
};
+ // conservative: a change while either frame has no located box counts as above the box
+ const before = prev.seq === 0 ? null : aboveBoxText(prev);
+ const after = aboveBoxText(out);
+ if (before === null || after === null || before !== after) out.aboveBoxChangedAt = now;
+ return out;
}
/** Apply one watch frame. A keyframe replaces every row; a delta replaces the rows it names. */
diff --git a/packages/cli/src/pane/settle-rule.test.ts b/packages/cli/src/pane/settle-rule.test.ts
index 99262748..162ff317 100644
--- a/packages/cli/src/pane/settle-rule.test.ts
+++ b/packages/cli/src/pane/settle-rule.test.ts
@@ -1,7 +1,8 @@
import { afterEach, describe, expect, test } from "bun:test";
import {
+ CORROBORATION_GRACE_MS,
SECONDARY_QUIET_MS,
- type ScreenFacts,
+ type CorroborationFacts,
type SettleInput,
agentCountMismatch,
decideSettle,
@@ -16,7 +17,7 @@ import {
} 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. */
+/** Turn views come from real transcripts replayed through the follower; only the corroboration facts are set by hand. */
const cleanups: Array<() => void> = [];
afterEach(() => {
@@ -39,20 +40,55 @@ function viewOf(
return r.views[r.views.length - 1]!;
}
-const IDLE_SCREEN: ScreenFacts = {
- boxEmpty: true,
- choiceDialog: false,
+const IDLE: CorroborationFacts = {
+ gate: { ready: true, dialog: null, reason: null },
working: false,
aboveBoxQuietMs: 0,
};
+const UNCONFIRMED: Array<{ name: string; facts: CorroborationFacts; why: string }> = [
+ {
+ name: "typed text",
+ facts: { ...IDLE, gate: { ready: false, dialog: null, reason: "box_not_empty" } },
+ why: "box_not_empty",
+ },
+ {
+ name: "a dialog",
+ facts: {
+ ...IDLE,
+ gate: { ready: false, dialog: "permission", reason: "dialog:permission" },
+ },
+ why: "dialog:permission",
+ },
+ {
+ name: "a working row",
+ facts: { ...IDLE, working: true },
+ why: "working",
+ },
+ {
+ name: "a not-ready gate",
+ facts: { ...IDLE, gate: { ready: false, dialog: null, reason: "starting" } },
+ why: "starting",
+ },
+ {
+ name: "a not-ready gate without a reason",
+ facts: { ...IDLE, gate: { ready: false, dialog: null, reason: null } },
+ why: "not_ready",
+ },
+ {
+ name: "an unknown or stale connected gate",
+ facts: { ...IDLE, gate: null },
+ why: "gate_unknown",
+ },
+];
+
function input(v: TranscriptView, over: Partial<SettleInput> = {}): SettleInput {
return {
turn: v.current,
session: v.session,
transcriptQuietMs: 1000,
chatQuietMs: 1000,
- screen: IDLE_SCREEN,
+ facts: IDLE,
paneExited: false,
...over,
};
@@ -61,7 +97,7 @@ function input(v: TranscriptView, over: Partial<SettleInput> = {}): SettleInput
const PEAR = "Reply with exactly PEAR and nothing else.";
describe("path P — turn_duration", () => {
- test("settles a hookless end_turn once the screen corroborates", () => {
+ test("settles a hookless end_turn once a clean gate corroborates (U7)", () => {
const v = viewOf("pear-hookless", PEAR);
expect(decideSettle(input(v))).toEqual({
settled: true,
@@ -88,23 +124,70 @@ describe("path P — turn_duration", () => {
});
});
- test("waits for the screen: typed text, a dialog, a working row, or a chat record < 500 ms old", () => {
+ for (const { name, facts, why } of UNCONFIRMED) {
+ test(`${name} delays P until the 32 s grace, then settles with ${why} (U7)`, () => {
+ const v = viewOf("pear-hookless", PEAR);
+ for (const chatQuietMs of [1000, CORROBORATION_GRACE_MS - 1]) {
+ expect(decideSettle(input(v, { facts, chatQuietMs, transcriptQuietMs: 1e9 })).settled).toBe(
+ false
+ );
+ }
+ for (const chatQuietMs of [CORROBORATION_GRACE_MS, CORROBORATION_GRACE_MS + 1]) {
+ expect(decideSettle(input(v, { facts, chatQuietMs }))).toEqual({
+ settled: true,
+ by: "turn_duration",
+ stopReason: "end_turn",
+ anomalies: [`settle_gate_unconfirmed:${why}`],
+ });
+ }
+ });
+ }
+
+ test("waits for a chat record to be 500 ms old even after the gate grace", () => {
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(
+ expect(decideSettle(input(v, { chatQuietMs: 100 })).settled).toBe(false);
+ expect(decideSettle(input(v, { chatQuietMs: 499, corroborationGraceMs: 0 })).settled).toBe(
false
);
- expect(decideSettle(input(v, { chatQuietMs: 100 })).settled).toBe(false);
+ expect(decideSettle(input(v, { chatQuietMs: 500 }))).toEqual({
+ settled: true,
+ by: "turn_duration",
+ stopReason: "end_turn",
+ anomalies: [],
+ });
+ });
+
+ test("working: null does not veto a clean gate (U7)", () => {
+ const v = viewOf("pear-hookless", PEAR);
+ expect(
+ decideSettle(input(v, { facts: { ...IDLE, working: null, aboveBoxQuietMs: null } }))
+ ).toEqual({
+ settled: true,
+ by: "turn_duration",
+ stopReason: "end_turn",
+ anomalies: [],
+ });
+ });
+
+ test("the default corroboration grace is 32 s (U7)", () => {
+ expect(CORROBORATION_GRACE_MS).toBe(32_000);
+ });
+
+ test("corroborationGraceMs overrides the default grace (U7)", () => {
+ const v = viewOf("pear-hookless", PEAR);
+ const over = { facts: { ...IDLE, gate: null }, corroborationGraceMs: 2000 };
+ expect(decideSettle(input(v, { ...over, chatQuietMs: 1999 })).settled).toBe(false);
+ expect(decideSettle(input(v, { ...over, chatQuietMs: 2000 }))).toEqual({
+ settled: true,
+ by: "turn_duration",
+ stopReason: "end_turn",
+ anomalies: ["settle_gate_unconfirmed:gate_unknown"],
+ });
});
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({
+ expect(decideSettle(input(v, { facts: null }))).toEqual({
settled: true,
by: "turn_duration",
stopReason: "end_turn",
@@ -127,9 +210,7 @@ describe("path P — turn_duration", () => {
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 } })
- )
+ decideSettle(input(mid, { transcriptQuietMs: 1e9, facts: { ...IDLE, aboveBoxQuietMs: 1e9 } }))
).toEqual({
settled: false,
activity: "thinking",
@@ -170,7 +251,7 @@ describe("agentCountMismatch", () => {
decideSettle({
...input(v, {
transcriptQuietMs: 1e9,
- screen: { ...IDLE_SCREEN, aboveBoxQuietMs: 1e9 },
+ facts: { ...IDLE, aboveBoxQuietMs: 1e9 },
}),
turn,
})
@@ -221,23 +302,40 @@ describe("Stop hooks hold the turn open (X-H2)", () => {
const v = viewOf(n, PEAR, { upTo: summary });
const long = {
transcriptQuietMs: 10 * SECONDARY_QUIET_MS,
- screen: { ...IDLE_SCREEN, aboveBoxQuietMs: 10 * SECONDARY_QUIET_MS },
+ facts: { ...IDLE, aboveBoxQuietMs: 10 * SECONDARY_QUIET_MS },
};
expect(decideSettle(input(v, long))).toEqual({ settled: false, activity: "finishing" });
});
+ test("the corroboration grace never settles a turn whose Stop hooks are unfinished", () => {
+ const v = viewOf(n, PEAR, { upTo: summary });
+ expect(v.current!.turnDurationAfterLast).toBeNull();
+ expect(v.current!.stopHookSummaryAfterLast).toBe(false);
+ for (const facts of [IDLE, ...UNCONFIRMED.map((c) => c.facts), null]) {
+ expect(
+ decideSettle(
+ input(v, {
+ transcriptQuietMs: 1e9,
+ chatQuietMs: 1e9,
+ facts: facts === null ? null : { ...facts, aboveBoxQuietMs: 1e9 },
+ })
+ )
+ ).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 },
+ facts: { ...IDLE, 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 },
+ facts: { ...IDLE, aboveBoxQuietMs: SECONDARY_QUIET_MS },
};
expect(decideSettle(input(v, ok))).toEqual({
settled: true,
@@ -246,7 +344,26 @@ describe("Stop hooks hold the turn open (X-H2)", () => {
anomalies: ["settled_without_turn_duration"],
});
// S waits for the reconnect
- expect(decideSettle(input(v, { ...ok, screen: null })).settled).toBe(false);
+ expect(decideSettle(input(v, { ...ok, facts: null })).settled).toBe(false);
+ });
+
+ test("path S uses transcriptQuietMs alone when aboveBoxQuietMs is null (U8)", () => {
+ const v = viewOf(n, PEAR, { upTo: summary + 1 });
+ expect(v.current!.turnDurationAfterLast).toBeNull();
+ expect(v.current!.stopHookSummaryAfterLast).toBe(true);
+ const facts = { ...IDLE, working: null, aboveBoxQuietMs: null };
+ expect(
+ decideSettle(input(v, { facts, transcriptQuietMs: SECONDARY_QUIET_MS - 1 })).settled
+ ).toBe(false);
+ expect(decideSettle(input(v, { facts, transcriptQuietMs: SECONDARY_QUIET_MS }))).toEqual({
+ settled: true,
+ by: "quiet",
+ stopReason: "end_turn",
+ anomalies: ["settled_without_turn_duration"],
+ });
+ expect(
+ decideSettle(input(v, { facts: null, transcriptQuietMs: SECONDARY_QUIET_MS })).settled
+ ).toBe(false);
});
test("the measured secondary window is 32 s", () => {
@@ -266,7 +383,7 @@ describe("path S in a session proven hook-less", () => {
expect(v.current!.turnDurationAfterLast).toBeNull();
const quiet = {
transcriptQuietMs: SECONDARY_QUIET_MS,
- screen: { ...IDLE_SCREEN, aboveBoxQuietMs: SECONDARY_QUIET_MS },
+ facts: { ...IDLE, aboveBoxQuietMs: SECONDARY_QUIET_MS },
};
expect(decideSettle(input(v, quiet))).toMatchObject({
settled: true,
@@ -366,10 +483,33 @@ describe("unsettled activity", () => {
witnessIndex(n, w)
);
const v = viewOf(n, w, { upTo: use + 1 });
- const quiet = { transcriptQuietMs: 1e9, screen: { ...IDLE_SCREEN, aboveBoxQuietMs: 1e9 } };
+ const quiet = { transcriptQuietMs: 1e9, facts: { ...IDLE, aboveBoxQuietMs: 1e9 } };
expect(decideSettle(input(v, quiet))).toEqual({ settled: false, activity: "Bash" });
});
+ test("a pending tool blocks path P regardless of the gate or elapsed grace (U7)", () => {
+ 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 pending = viewOf(n, w, { upTo: use + 1 });
+ const v = viewOf(n, w);
+ expect(pending.current!.pendingTool?.name).toBe("Bash");
+ expect(v.current!.turnDurationAfterLast).not.toBeNull();
+ expect(decideSettle(input(v))).toMatchObject({ settled: true, by: "turn_duration" });
+ const turn = { ...v.current!, pendingTool: pending.current!.pendingTool };
+ for (const facts of [IDLE, ...UNCONFIRMED.map((c) => c.facts), null]) {
+ expect(
+ decideSettle({
+ ...input(v, { facts, transcriptQuietMs: 1e9, chatQuietMs: 1e9 }),
+ turn,
+ })
+ ).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" });
@@ -382,7 +522,7 @@ describe("path X — pane exit", () => {
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({
+ expect(decideSettle(input(v, { paneExited: true, facts: null }))).toEqual({
settled: true,
by: "exit",
stopReason: "end_turn",
@@ -401,7 +541,7 @@ describe("path X — pane exit", () => {
witnessIndex(n, w)
);
const v = viewOf(n, w, { upTo: use + 1 });
- expect(decideSettle(input(v, { paneExited: true, screen: null })).settled).toBe(false);
+ expect(decideSettle(input(v, { paneExited: true, facts: null })).settled).toBe(false);
});
});
@@ -414,7 +554,7 @@ describe("refusal (redacted corpus)", () => {
});
cleanups.push(r.cleanup);
const v = r.views[0]!;
- const quiet = { transcriptQuietMs: 1e9, screen: { ...IDLE_SCREEN, aboveBoxQuietMs: 1e9 } };
+ const quiet = { transcriptQuietMs: 1e9, facts: { ...IDLE, aboveBoxQuietMs: 1e9 } };
expect(decideSettle(input(v, quiet))).toEqual({ settled: false, activity: "thinking" });
});
@@ -428,7 +568,7 @@ describe("refusal (redacted corpus)", () => {
};
const quiet = {
transcriptQuietMs: SECONDARY_QUIET_MS,
- screen: { ...IDLE_SCREEN, aboveBoxQuietMs: SECONDARY_QUIET_MS },
+ facts: { ...IDLE, aboveBoxQuietMs: SECONDARY_QUIET_MS },
};
expect(decideSettle({ ...input(v, quiet), turn })).toMatchObject({
settled: true,
@@ -459,12 +599,24 @@ describe("path L — a local command's stdout", () => {
anomalies: [],
});
expect(decideSettle(input(v, { chatQuietMs: 0 })).settled).toBe(false);
- expect(decideSettle(input(v, { screen: { ...IDLE_SCREEN, working: true } })).settled).toBe(
+ expect(decideSettle(input(v, { facts: { ...IDLE, working: true } })).settled).toBe(false);
+ expect(decideSettle(input(v, { facts: null, paneExited: true }))).toMatchObject({
+ settled: true,
+ by: "local_command",
+ });
+ });
+
+ test("a working row delays path L only until the corroboration grace", () => {
+ const v = compactView();
+ const facts = { ...IDLE, working: true };
+ expect(decideSettle(input(v, { facts, chatQuietMs: CORROBORATION_GRACE_MS - 1 })).settled).toBe(
false
);
- expect(decideSettle(input(v, { screen: null, paneExited: true }))).toMatchObject({
+ expect(decideSettle(input(v, { facts, chatQuietMs: CORROBORATION_GRACE_MS }))).toEqual({
settled: true,
by: "local_command",
+ stopReason: null,
+ anomalies: ["settle_gate_unconfirmed:working"],
});
});
});
diff --git a/packages/cli/src/pane/settle-rule.ts b/packages/cli/src/pane/settle-rule.ts
index fa0fdd53..41f0e078 100644
--- a/packages/cli/src/pane/settle-rule.ts
+++ b/packages/cli/src/pane/settle-rule.ts
@@ -21,6 +21,13 @@
*
* 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`.
+ *
+ * Corroboration (architecture-v2 §7.1, R1.5.1) reads magmux's input gate, not the box: an
+ * ending is clean when the gate is ready (which already means an EMPTY box), names no
+ * dialog, and no working row is drawn above the box located by the cursor. Corroboration
+ * can DELAY a transcript-proven ending, never veto it: after `corroborationGraceMs` of chat
+ * quiet the turn settles anyway, with `settle_gate_unconfirmed:<why>`. That window confirms
+ * an ending Claude Code already recorded, the same standing as S's window, so D10 holds.
*/
import type { SessionFacts, TurnView } from "./transcript-follower.js";
@@ -38,15 +45,23 @@ 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;
+/**
+ * The most corroboration may delay a transcript-proven ending (Jack's decision J2, R1.6):
+ * the secondary window, so a gate that cannot confirm idle costs at most what S costs.
+ */
+export const CORROBORATION_GRACE_MS = SECONDARY_QUIET_MS;
+
+/** What the gate and the screen say at a candidate ending (architecture-v2 §3.2, R1.5.1). */
+export interface CorroborationFacts {
+ /**
+ * magmux's published input gate; null when its last reading is stale. `ready` already
+ * means the box is empty: the published view refuses `box_not_empty` (R1.5.1).
+ */
+ gate: { ready: boolean; dialog: string | null; reason: string | null } | null;
+ /** a working row above the LOCATED box; null when the box is not located (never a veto) */
+ working: boolean | null;
+ /** ms since a row above the located box last changed; null when the box is not located */
+ aboveBoxQuietMs: number | null;
}
export interface SettleInput {
@@ -56,11 +71,13 @@ export interface SettleInput {
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;
+ /** null while the socket is disconnected: the in-memory screen and the gate are stale */
+ facts: CorroborationFacts | null;
paneExited: boolean;
secondaryQuietMs?: number;
corroborationMs?: number;
+ /** default CORROBORATION_GRACE_MS */
+ corroborationGraceMs?: number;
}
export type SettledBy = "turn_duration" | "interrupt" | "quiet" | "exit" | "local_command";
@@ -100,12 +117,28 @@ function activityOf(t: TurnView | null): string {
return "thinking";
}
+/**
+ * Why the gate does not confirm idle, or null when it does (R1.5.1). A stale gate reading
+ * is unknown; an unlocated box (`working: null`) is not a reason.
+ */
+function unconfirmedBy(f: CorroborationFacts): string | null {
+ const g = f.gate;
+ if (g === null) return "gate_unknown";
+ if (!g.ready || g.dialog !== null) return (g.reason ?? "not_ready").slice(0, 48);
+ if (f.working === true) return "working";
+ return null;
+}
+
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 };
+ if (!input.facts) return { ok: true, anomaly: "screen_unverified" };
+ const why = unconfirmedBy(input.facts);
+ if (why === null) return { ok: true };
+ // never a permanent veto: an ending the transcript proved settles after the grace
+ if (input.chatQuietMs >= (input.corroborationGraceMs ?? CORROBORATION_GRACE_MS))
+ return { ok: true, anomaly: `settle_gate_unconfirmed:${why}` };
+ return { ok: false };
}
type Path = SettleDecision | null; // null = this path does not apply / not yet
@@ -150,9 +183,12 @@ function pathPrimary(t: TurnView, input: SettleInput): Path {
/** 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
+ if (!input.facts) return null; // S waits for the reconnect
const window = input.secondaryQuietMs ?? SECONDARY_QUIET_MS;
- if (input.transcriptQuietMs < window || input.screen.aboveBoxQuietMs < window) return null;
+ if (input.transcriptQuietMs < window) return null;
+ // box not located: the transcript's quiet decides alone (S is already gated on Stop hooks)
+ const above = input.facts.aboveBoxQuietMs;
+ if (above !== null && above < window) return null;
const c = corroborated(input);
return c.ok
? settledAs("quiet", t.lastAssistant?.stopReason ?? null, c, ["settled_without_turn_duration"])