Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(pane): report agent_count_mismatch when agent counts disagree
Jack Rudenkode9366b49a53
diff --git a/ai-docs/architecture/pane-session.md b/ai-docs/architecture/pane-session.mdindex 5f392f18..a1a0c594 100644--- a/ai-docs/architecture/pane-session.md+++ b/ai-docs/architecture/pane-session.md@@ -269,6 +269,16 @@ clears the moment activity leaves `finishing`, and only while it holds do `activrow's `activity` read `finishing: turn_end_record_missing`; the anomaly stays as history. A stickyread presented a slot the model had woken again as wedged. No timer ends the turn (D10).+**Counts that disagree.** While a turn is unsettled after a `turn_duration` and not waking, the+background agents claudish counts as pending (`agentsLaunched - agentsCompleted`) are compared with+Claude Code's own `pendingBackgroundAgentCount` (absent means 0). When they differ the anomaly+`agent_count_mismatch: claudish <counted> pending, Claude Code <reported>` is added once per onset of+a pair, and the CONDITION is live (`agentCountMismatch` on the snapshot): only while it holds does the+row's `activity` read `background: agent_count_mismatch`; it clears when the counts agree or the turn+settles, and the anomaly stays as history. It never settles or ends a turn: Claude Code's count is a+witness, never the decider (D23). Session 779a03f0 (2026-10-16) sat at claudish 2 pending, Claude+Code 0 until cancel, with nothing on the row to say why.+**Blocked.** A pending `AskUserQuestion` comes from the transcript. A permission or plan-approvaldialog also needs the screen: `hasChoiceDialog` is a CLOSED list (R3-H1) — a named header(`Do you want to proceed?`, `Do you want to create|make this edit to|overwrite|delete …?`,diff --git a/packages/cli/src/pane/accounting.test.ts b/packages/cli/src/pane/accounting.test.tsindex ac51417f..2bd12c2b 100644--- a/packages/cli/src/pane/accounting.test.ts+++ b/packages/cli/src/pane/accounting.test.ts@@ -53,6 +53,7 @@ function snap(over: Partial<PaneSnapshot> = {}): PaneSnapshot {claudeCodeVersion: null,shape: "one-shot",turnEndRecordMissing: false,+ agentCountMismatch: false,...over,};}@@ -243,6 +244,34 @@ describe("toSlotRow (§8 B)", () => {expect(resumed.activity).toBe("Bash");});+ // REGRESSION: one-shot session never settles when background-agent notifications arrive mid-turn as attachment/queued_command — Fixed in /dev:fix session dev-fix-20261016-224933-5e5cb5a4+ test("the row's activity carries agent_count_mismatch only while the live snapshot flag holds", () => {+ const acct = mergeAccounting(snap(), null);+ const id = { slot: "05", model: "m", spawnModel: null };+ const live = snap({ activity: "background", agentCountMismatch: true });+ const resumed = snap({+ activity: "Bash",+ agentCountMismatch: false,+ anomalies: ["agent_count_mismatch: claudish 2 pending, Claude Code 0"],+ });+ const settled = snap({+ state: "COMPLETED",+ phase: "COMPLETED",+ activity: null,+ agentCountMismatch: false,+ anomalies: resumed.anomalies,+ });+ expect([+ live.agentCountMismatch,+ resumed.agentCountMismatch,+ settled.agentCountMismatch,+ ]).toEqual([true, false, false]);+ // History alone cannot label a slot that resumed work or settled.+ expect(toSlotRow(id, resumed, acct).activity).toBe("Bash");+ expect(toSlotRow(id, settled, acct).activity).toBeNull();+ expect(toSlotRow(id, live, acct).activity).toBe("background: agent_count_mismatch");+ });+test("a pane that never spawned has pane null", () => {const row = toSlotRow({ slot: "04", model: "m", spawnModel: null },diff --git a/packages/cli/src/pane/pane-session.ts b/packages/cli/src/pane/pane-session.tsindex f75ef820..8b337d3a 100644--- a/packages/cli/src/pane/pane-session.ts+++ b/packages/cli/src/pane/pane-session.ts@@ -97,6 +97,7 @@ import {SECONDARY_QUIET_MS,type ScreenFacts,type SettleDecision,+ agentCountMismatch,decideSettle,} from "./settle-rule.js";import {@@ -344,6 +345,8 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {private claudeCodeVersion: string | null = null;private anomalies = new Map<string, number>();private turnEndMissing = false;+ /** the live agent_count_mismatch pair as `counted/reported`; null while counts agree */+ private agentMismatch: string | null = null;private readonly registry: SessionRegistry;private registryRec: RegistryRecord | null = null;private registryEverSeen = false;@@ -1247,6 +1250,7 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {}this.activity = decision.activity;this.checkTurnEndMissing();+ this.checkAgentCountMismatch(t);}private checkEscape(): void {@@ -1274,6 +1278,21 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {this.turnEndMissing = missing;}+ /**+ * claudish's pending background agents disagree with Claude Code's count at the turn's+ * end record. Live like turn_end_record_missing; the anomaly counts each onset of a pair.+ * It never settles or ends the turn: Claude Code's count is a witness (D23).+ */+ private checkAgentCountMismatch(t: TurnView): void {+ const m = agentCountMismatch(t);+ const key = m ? `${m.counted}/${m.reported}` : null;+ if (m && key !== this.agentMismatch)+ this.anomaly(+ `agent_count_mismatch: claudish ${m.counted} pending, Claude Code ${m.reported}`+ );+ this.agentMismatch = key;+ }+/** Blocked detection (H7): AskUserQuestion from the transcript; permission needs the dialog too. */private detectBlocked(t: TurnView): boolean {const pending = t.pendingTool;@@ -1352,6 +1371,7 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {private finishTurn(turn: SettledTurn, chatOffset: number | null, exitCode: number | null): void {this.turnEndMissing = false;+ this.agentMismatch = null;this.answers.set(turn.index, turn.answer);// owners ask for the current or the last settled turn: keep a few, not the session's allfor (const k of this.answers.keys()) if (k <= turn.index - KEPT_ANSWERS) this.answers.delete(k);@@ -1582,6 +1602,7 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {this.phase === "RUNNING" &&this.activity === "finishing" &&this.turnEndMissing,+ agentCountMismatch: !terminal && this.phase === "RUNNING" && this.agentMismatch !== null,};}diff --git a/packages/cli/src/pane/settle-rule.test.ts b/packages/cli/src/pane/settle-rule.test.tsindex 93c363f2..99262748 100644--- a/packages/cli/src/pane/settle-rule.test.ts+++ b/packages/cli/src/pane/settle-rule.test.ts@@ -3,6 +3,7 @@ import {SECONDARY_QUIET_MS,type ScreenFacts,type SettleInput,+ agentCountMismatch,decideSettle,} from "./settle-rule.js";import {@@ -142,6 +143,75 @@ describe("path P — turn_duration", () => {});});+describe("agentCountMismatch", () => {+ function completedView(): TranscriptView {+ const n = "corpus-redacted/background-agents-in-turn";+ const recs = transcriptRecords(n);+ const td = indexOf(n, (r) => r.type === "system" && r.subtype === "turn_duration");+ return viewOf(n, textOf(recs[0]!), { upTo: td + 1 });+ }++ // REGRESSION: one-shot session never settles when background-agent notifications arrive mid-turn as attachment/queued_command — Fixed in /dev:fix session dev-fix-20261016-224933-5e5cb5a4+ test("the fixed follower agrees with zero reported pending agents at the first turn_duration", () => {+ const v = completedView();+ expect([v.current!.agentsLaunched, v.current!.agentsCompleted]).toEqual([2, 2]);+ expect(v.current!.turnDurationAfterLast).toEqual({ pendingBackgroundAgentCount: null });+ expect(agentCountMismatch(v.current)).toBeNull();+ });++ // REGRESSION: one-shot session never settles when background-agent notifications arrive mid-turn as attachment/queued_command — Fixed in /dev:fix session dev-fix-20261016-224933-5e5cb5a4+ test("missed mid-turn completions report the counter mismatch without settling the turn", () => {+ const v = completedView();+ const turn = { ...v.current!, agentsCompleted: 0 };+ const before = structuredClone(turn);+ expect(agentCountMismatch(turn)).toEqual({ counted: 2, reported: 0 });+ expect(turn).toEqual(before);+ expect(+ decideSettle({+ ...input(v, {+ transcriptQuietMs: 1e9,+ screen: { ...IDLE_SCREEN, aboveBoxQuietMs: 1e9 },+ }),+ turn,+ })+ ).toEqual({ settled: false, activity: "background" });+ });++ // REGRESSION: one-shot session never settles when background-agent notifications arrive mid-turn as attachment/queued_command — Fixed in /dev:fix session dev-fix-20261016-224933-5e5cb5a4+ test("one counted background agent agrees with one reported at the Agent turn's first turn_duration", () => {+ const n = "tools-session";+ const w = transcriptRecords(n)+ .map(textOf)+ .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([v.current!.agentsLaunched, v.current!.agentsCompleted]).toEqual([1, 0]);+ expect(v.current!.turnDurationAfterLast).toEqual({ pendingBackgroundAgentCount: 1 });+ expect(agentCountMismatch(v.current)).toBeNull();+ });++ // REGRESSION: one-shot session never settles when background-agent notifications arrive mid-turn as attachment/queued_command — Fixed in /dev:fix session dev-fix-20261016-224933-5e5cb5a4+ test("a waking turn has no agent count mismatch even with stale end-of-turn counts", () => {+ const v = completedView();+ expect(+ agentCountMismatch({ ...v.current!, agentsCompleted: 0, wakingAfterLast: true })+ ).toBeNull();+ });++ // REGRESSION: one-shot session never settles when background-agent notifications arrive mid-turn as attachment/queued_command — Fixed in /dev:fix session dev-fix-20261016-224933-5e5cb5a4+ test("no turn_duration means no reported count to compare", () => {+ const v = completedView();+ expect(+ agentCountMismatch({ ...v.current!, agentsCompleted: 0, turnDurationAfterLast: null })+ ).toBeNull();+ });++ // REGRESSION: one-shot session never settles when background-agent notifications arrive mid-turn as attachment/queued_command — Fixed in /dev:fix session dev-fix-20261016-224933-5e5cb5a4+ test("a missing turn has no agent count mismatch", () => {+ expect(agentCountMismatch(null)).toBeNull();+ });+});+describe("Stop hooks hold the turn open (X-H2)", () => {const n = "stop-hook-matrix";const at = witnessIndex(n, PEAR);diff --git a/packages/cli/src/pane/settle-rule.ts b/packages/cli/src/pane/settle-rule.tsindex 7349f968..fa0fdd53 100644--- a/packages/cli/src/pane/settle-rule.ts+++ b/packages/cli/src/pane/settle-rule.ts@@ -159,6 +159,21 @@ function pathSecondary(t: TurnView, input: SettleInput): Path {: null;}+/**+ * claudish's pending background agents disagreeing with Claude Code's own count at the+ * turn's end record. Claude Code writes `pendingBackgroundAgentCount` only above 0, so+ * absent means 0. A witness, never a decider (D23): session 779a03f0 counted 2 pending+ * where Claude Code reported 0, and nothing said so.+ */+export function agentCountMismatch(+ t: TurnView | null+): { counted: number; reported: number } | null {+ if (!t || !t.turnDurationAfterLast || t.wakingAfterLast) return null;+ const counted = t.agentsLaunched - t.agentsCompleted;+ const reported = t.turnDurationAfterLast.pendingBackgroundAgentCount ?? 0;+ return counted === reported ? null : { counted, reported };+}+export function decideSettle(input: SettleInput): SettleDecision {const t = input.turn;const notYet: SettleDecision = { settled: false, activity: activityOf(t) };diff --git a/packages/cli/src/pane/slot-row.ts b/packages/cli/src/pane/slot-row.tsindex 77606a4b..2b1f3e5c 100644--- a/packages/cli/src/pane/slot-row.ts+++ b/packages/cli/src/pane/slot-row.ts@@ -45,7 +45,9 @@ export function toSlotRow(? null: snap.turnEndRecordMissing && snap.activity? `${snap.activity}: turn_end_record_missing`- : snap.activity,+ : snap.agentCountMismatch && snap.activity+ ? `${snap.activity}: agent_count_mismatch`+ : snap.activity,pane: snap.paneId || null,};}diff --git a/packages/cli/src/pane/types.ts b/packages/cli/src/pane/types.tsindex e22cec59..17418724 100644--- a/packages/cli/src/pane/types.ts+++ b/packages/cli/src/pane/types.ts@@ -72,4 +72,10 @@ export interface PaneSnapshot {* the same name stays in `anomalies` as history.*/turnEndRecordMissing: boolean;+ /**+ * LIVE: the unsettled turn's background agents pending by claudish's counters differ from+ * Claude Code's `pendingBackgroundAgentCount` at its end record. False once they agree or+ * the turn settles; the `agent_count_mismatch` anomaly stays in `anomalies` as history.+ */+ agentCountMismatch: boolean;}diff --git a/packages/cli/src/team-heartbeat-survival.test.ts b/packages/cli/src/team-heartbeat-survival.test.tsindex 0eb604e5..f7414458 100644--- a/packages/cli/src/team-heartbeat-survival.test.ts+++ b/packages/cli/src/team-heartbeat-survival.test.ts@@ -5,10 +5,12 @@* record with their answer intact — and report what they are doing meanwhile.*/-import { afterEach, beforeEach, describe, expect, it } from "bun:test";+import { afterEach, beforeEach, describe, expect, it, spyOn } from "bun:test";import { readFileSync } from "node:fs";import { join } from "node:path";+import * as pane from "./pane/index.js";import {+ resetTeamRegistryForTests,runModels,setupSession,startModels,@@ -39,6 +41,124 @@ afterEach(async () => {expect(report).toEqual({ processes: [], files: [] });});+describe("offline team slot anomaly projection", () => {+ // REGRESSION: one-shot session never settles when background-agent notifications arrive mid-turn as attachment/queued_command — Fixed in /dev:fix session dev-fix-20261016-224933-5e5cb5a4+ it("agent_count_mismatch shows in the row and map while live, and stays in status history after clearing", async () => {+ const sessionPath = teamDirOf(t);+ setupSession(sessionPath, ["haiku"], "Reply with exactly PEAR");+ const anomaly = "agent_count_mismatch: claudish 2 pending, Claude Code 0";+ let snap: pane.PaneSnapshot = {+ paneId: "c1-k0-t01-abcdef",+ phase: "RUNNING",+ state: "RUNNING",+ reason: null,+ detail: null,+ activity: "background",+ lastActivityAt: "2026-10-06T01:00:00.000Z",+ idleSeconds: 0,+ turnsCompleted: 0,+ tokensIn: 33324,+ tokensOut: 44,+ toolCalls: 2,+ liveAnswerBytes: 0,+ exitCode: null,+ captureSource: null,+ turnSource: "transcript",+ pendingInputs: 0,+ connected: true,+ startedAt: "2026-10-06T00:59:00.000Z",+ endedAt: null,+ transcriptPath: "/x.jsonl",+ panePid: null,+ screenTail: "",+ anomalies: [anomaly],+ claudeCodeVersion: null,+ shape: "one-shot",+ turnEndRecordMissing: false,+ agentCountMismatch: true,+ };+ let onTransition: pane.PaneSessionOptions["onTransition"];+ const terminal = Promise.withResolvers<void>();+ // Exercise the real team projection and anomaly filter, without starting a pane.+ const available = spyOn(pane, "assertMagmuxAvailable").mockResolvedValue({+ binary: "unused-offline",+ version: "unused-offline",+ });+ const reserve = spyOn(pane, "reservePanes").mockImplementation(() => {});+ const start = spyOn(pane, "startPaneSession").mockImplementation(async (opts) => {+ onTransition = opts.onTransition;+ return {+ paneId: snap.paneId,+ snapshot: () => snap,+ ready: Promise.resolve(),+ terminal: terminal.promise,+ turnAnswer: () => "PEAR",+ } as unknown as pane.PaneSession;+ });+ let handle: Awaited<ReturnType<typeof startModels>> | undefined;+ const update = (over: Partial<pane.PaneSnapshot>) => {+ snap = { ...snap, ...over };+ onTransition?.({ snap } as Parameters<NonNullable<typeof onTransition>>[0]);+ };+ try {+ handle = await startModels(sessionPath, paneRunOptions(t));+ const slotId = handle.slots.haiku!;+ const rowActivity = () =>+ teamRunRow(sessionPath)?.slots.find((s) => s.slot === slotId)?.activity ?? null;+ const anomalies = () =>+ JSON.parse(readFileSync(join(sessionPath, "status.json"), "utf8")).models[slotId].anomalies;+ update({});+ expect({+ flag: snap.agentCountMismatch,+ activity: teamLiveMaps(sessionPath)?.activity[slotId],+ rowActivity: rowActivity(),+ anomalies: anomalies(),+ }).toEqual({+ flag: true,+ activity: "background: agent_count_mismatch",+ rowActivity: "background: agent_count_mismatch",+ anomalies: [anomaly],+ });+ // The anomaly is history once the live condition clears, not an activity suffix.+ update({ activity: "Bash", agentCountMismatch: false });+ expect(snap.agentCountMismatch).toBe(false);+ expect(teamLiveMaps(sessionPath)?.activity[slotId]).toBe("Bash");+ expect(rowActivity()).toBe("Bash");+ expect(anomalies()).toEqual([anomaly]);+ expect(teamRunRow(sessionPath)?.state).toBe("ACTIVE");+ expect(snap.turnsCompleted).toBe(0);+ update({+ state: "COMPLETED",+ phase: "COMPLETED",+ activity: null,+ agentCountMismatch: false,+ turnsCompleted: 1,+ endedAt: new Date().toISOString(),+ });+ terminal.resolve();+ const status = await handle.done;+ expect(status.models[slotId]?.state).toBe("COMPLETED");+ expect(status.models[slotId]?.anomalies).toEqual([anomaly]);+ expect(rowActivity()).toBeNull();+ } finally {+ if (handle) {+ update({+ state: "COMPLETED",+ phase: "COMPLETED",+ activity: null,+ agentCountMismatch: false,+ });+ terminal.resolve();+ await handle.done;+ }+ start.mockRestore();+ reserve.mockRestore();+ available.mockRestore();+ resetTeamRegistryForTests();+ }+ });+});+describe.skipIf(!MAGMUX)("team slot heartbeat survival", () => {it("keeps a slot alive through a silent tool call and reports activity Bash", async () => {const sessionPath = teamDirOf(t);diff --git a/packages/cli/src/team-orchestrator.ts b/packages/cli/src/team-orchestrator.tsindex 6827cfc3..22e5fdf8 100644--- a/packages/cli/src/team-orchestrator.ts+++ b/packages/cli/src/team-orchestrator.ts@@ -427,6 +427,7 @@ function notableAnomalies(snap: PaneSnapshot): string[] {(a) =>a.startsWith("background_shell_open") ||a.startsWith("turn_end_record_missing") ||+ a.startsWith("agent_count_mismatch") ||a.startsWith("prompt_not_read"));}diff --git a/packages/cli/src/team-status-payload.test.ts b/packages/cli/src/team-status-payload.test.tsindex 640b6279..aaca7041 100644--- a/packages/cli/src/team-status-payload.test.ts+++ b/packages/cli/src/team-status-payload.test.ts@@ -3,7 +3,13 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { buildTeamStatusPayload, teamStatusNote } from "./mcp-server.js";-import { CAPABILITIES, type TeamRunRow } from "./pane/index.js";+import {+ CAPABILITIES,+ type PaneSnapshot,+ type TeamRunRow,+ mergeAccounting,+ toSlotRow,+} from "./pane/index.js";import { type ModelStatus, type TeamStatus, teamRunRowFromDisk } from "./team-orchestrator.js";const PATH = "/tmp/team-status-payload-test";@@ -132,6 +138,65 @@ describe("buildTeamStatusPayload", () => {expect(payload).not.toHaveProperty("summary");});+ // REGRESSION: one-shot session never settles when background-agent notifications arrive mid-turn as attachment/queued_command — Fixed in /dev:fix session dev-fix-20261016-224933-5e5cb5a4+ test("carries the live agent_count_mismatch activity and keeps its history after the condition clears", () => {+ const anomaly = "agent_count_mismatch: claudish 2 pending, Claude Code 0";+ const snap: PaneSnapshot = {+ paneId: "c1-k0-t01-abcdef",+ phase: "RUNNING",+ state: "RUNNING",+ reason: null,+ detail: null,+ activity: "background",+ lastActivityAt: "2026-10-06T01:00:00.000Z",+ idleSeconds: 0,+ turnsCompleted: 0,+ tokensIn: 33324,+ tokensOut: 44,+ toolCalls: 2,+ liveAnswerBytes: 0,+ exitCode: null,+ captureSource: null,+ turnSource: "transcript",+ pendingInputs: 0,+ connected: true,+ startedAt: "2026-10-06T00:59:00.000Z",+ endedAt: null,+ transcriptPath: "/x.jsonl",+ panePid: 1,+ screenTail: "",+ anomalies: [anomaly],+ claudeCodeVersion: null,+ shape: "one-shot",+ turnEndRecordMissing: false,+ agentCountMismatch: true,+ };+ const status: TeamStatus = {+ startedAt: snap.startedAt,+ models: { "01": { ...slot("RUNNING", 0), anomalies: snap.anomalies } },+ };+ const id = { slot: "01", model: "haiku", spawnModel: null };+ for (const current of [snap, { ...snap, activity: "Bash", agentCountMismatch: false }]) {+ const row = toSlotRow(id, current, mergeAccounting(current, null, id));+ const payload = buildTeamStatusPayload({+ status,+ sessionPath: PATH,+ idle: { "01": 0 },+ activity: { "01": row.activity! },+ liveBytes: { "01": 0 },+ run: { ...runOf(status), slots: [row] },+ });+ expect((payload.models as TeamStatus["models"])["01"]?.anomalies).toEqual([anomaly]);+ expect(payload.activity_by_slot).toEqual({+ "01": current.agentCountMismatch ? "background: agent_count_mismatch" : "Bash",+ });+ expect((payload.run as TeamRunRow).slots[0]?.activity).toBe(+ current.agentCountMismatch ? "background: agent_count_mismatch" : "Bash"+ );+ expect((payload.models as TeamStatus["models"])["01"]?.state).toBe("RUNNING");+ }+ });+test("keys the note on any non-terminal slot, not only RUNNING", () => {for (const state of ["STARTING", "AWAITING_INPUT", "AWAITING_PERMISSION"] as const) {const status: TeamStatus = {