Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
feat(mcp): log session-registry vs screen disagreements per pane
Jack Rudenko873f59de8dd5
diff --git a/packages/cli/src/channel/session-manager.ts b/packages/cli/src/channel/session-manager.tsindex 7e8c7e92..5cab980d 100644--- a/packages/cli/src/channel/session-manager.ts+++ b/packages/cli/src/channel/session-manager.ts@@ -138,6 +138,8 @@ export interface SessionDiagnostics {sockPath: string | null;/** The head of magmux's own stderr, redacted. */magmuxStderr: string;+ /** The child's Claude Code session-registry record as last read (telemetry); null when none. */+ registry: { status: string | null; waitingFor: string | null; version: string | null } | null;captureSource: SessionInfo["captureSource"];turnSource: SessionInfo["turnSource"];/** Bytes of assistant text before a file-delivered turn's task file was read. */@@ -1387,6 +1389,7 @@ export class SessionManager {| "screenTail"| "sockPath"| "magmuxStderr"+ | "registry"| "preambleBytes"| "readCoverage"| "claudeCodeVersion"@@ -1400,6 +1403,7 @@ export class SessionManager {screenTail: "",sockPath: null,magmuxStderr: "",+ registry: null,preambleBytes: 0,readCoverage: null,claudeCodeVersion: null,@@ -1413,6 +1417,7 @@ export class SessionManager {screenTail: redactSecrets(snap.screenTail),sockPath: session.sockPath,magmuxStderr: redactSecrets(pane.magmuxStderr),+ registry: pane.registry,preambleBytes: pane.preambleBytes,readCoverage: pane.readCoverage,claudeCodeVersion: snap.claudeCodeVersion,@@ -1638,6 +1643,7 @@ export class SessionManager {pane: info.pane,sockPath: null,magmuxStderr: "",+ registry: null,captureSource: info.captureSource,turnSource: info.turnSource,preambleBytes: 0,diff --git a/packages/cli/src/pane/pane-session.ts b/packages/cli/src/pane/pane-session.tsindex 9571ce75..bae45176 100644--- a/packages/cli/src/pane/pane-session.ts+++ b/packages/cli/src/pane/pane-session.ts@@ -20,6 +20,7 @@import type { ChildProcess } from "node:child_process";import { readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";import { join } from "node:path";+import { claudeConfigDir } from "../channel/parent-session.js";import { waitForExit } from "../process-tree.js";import { redactSecrets } from "../redact.js";import type { CaptureResult, CaptureUnchanged, FailureReason, SlotState } from "./contract.js";@@ -90,6 +91,7 @@ import {applyFrame,emptyScreen,} from "./screen-model.js";+import { KNOWN_STATUSES, type RegistryRecord, SessionRegistry } from "./session-registry.js";import {CORROBORATION_MS,SECONDARY_QUIET_MS,@@ -128,6 +130,12 @@ const WATCH_FPS = 4;const POLL_BACKSTOP_MS = 1_000;/** R3-M4: a `finishing` turn with a static screen for this many secondary windows. */const TURN_END_MISSING_FACTOR = 3;+/** The session registry is re-read at most this often (telemetry only). */+const REGISTRY_READ_MS = 250;+/** A registry/screen disagreement must hold this long before it is counted. */+const REGISTRY_DISAGREE_MS = 2_000;+/** No live registry record this long after boot was ready: `registry_record_missing`. */+const REGISTRY_MISSING_MS = 5_000;const MAX_ANOMALY_KEYS = 64;/** Settled answers kept for `turnAnswer` (owners read the current or the last one). */const KEPT_ANSWERS = 4;@@ -189,6 +197,8 @@ export type SendResult =export interface PaneDiagnostics {/** the head of magmux's own stderr (≤ 8 KB) */magmuxStderr: string;+ /** the child's session-registry record as last read (telemetry); null when none matched */+ registry: { status: string | null; waitingFor: string | null; version: string | null } | null;/** assistant text before a file-delivered turn's task file was read (X-H4) */preambleBytes: number;/** read coverage of the current turn's task file; null for a typed turn or no turn */@@ -318,6 +328,14 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {private claudeCodeVersion: string | null = null;private anomalies = new Map<string, number>();private turnEndMissing = false;+ private readonly registry: SessionRegistry;+ private registryRec: RegistryRecord | null = null;+ private registryEverSeen = false;+ private lastRegistryReadAt = 0;+ private bootReadyAtMs: number | null = null;+ /** registry/screen disagreements now holding, with when each began; counted once at onset */+ private disagreeSince = new Map<string, number>();+ private disagreeCounted = new Set<string>();private exitScrollback = "";private exitLastLine = "";@@ -367,6 +385,11 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {o.transcriptPath,join(o.transcriptPath.replace(/\.jsonl$/, ""), "subagents"));+ // the same environment the transcript path is derived from+ this.registry = new SessionRegistry({+ configDir: claudeConfigDir(o.parentEnv ?? process.env),+ sessionUuid: o.sessionUuid,+ });this.ready = new Promise((r) => {this.resolveReady = r;});@@ -723,9 +746,67 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {this.evalIdle(view);break;}+ this.checkRegistry();this.pump();}+ /**+ * Telemetry only (pane-session.md, "The session registry"): compare Claude Code's own+ * session record with what the screen says, and count each disagreement once at its onset.+ * No decision reads the registry.+ */+ private checkRegistry(): void {+ const now = Date.now();+ if (now - this.lastRegistryReadAt < REGISTRY_READ_MS) return;+ this.lastRegistryReadAt = now;+ const rec = this.registry.read();+ this.registryRec = rec;+ if (rec) this.registryEverSeen = true;+ if (+ !this.registryEverSeen &&+ this.bootReadyAtMs !== null &&+ now - this.bootReadyAtMs >= REGISTRY_MISSING_MS+ ) {+ this.disagree("registry_record_missing", true, now, 0);+ }+ const status = rec?.status ?? null;+ if (status !== null && !KNOWN_STATUSES.has(status))+ this.disagree(`registry_status_unknown:${status.slice(0, 32)}`, true, now, 0);+ if (!this.client) return; // a stale screen proves nothing+ const idle = status === "idle";+ const dialog = hasChoiceDialog(this.screen);+ this.disagree(+ "registry_idle_screen_booting",+ this.phase === "BOOTING" && idle && readBoot(this.screen).kind !== "repl",+ now+ );+ this.disagree(+ "registry_idle_screen_working",+ this.phase === "RUNNING" && idle && isWorking(this.screen),+ now+ );+ this.disagree("registry_waiting_no_dialog", status === "waiting" && !dialog, now);+ this.disagree(+ "screen_dialog_registry_not_waiting",+ dialog && (status === "idle" || status === "busy"),+ now+ );+ }++ private disagree(key: string, holds: boolean, now: number, forMs = REGISTRY_DISAGREE_MS): void {+ if (!holds) {+ this.disagreeSince.delete(key);+ this.disagreeCounted.delete(key);+ return;+ }+ const since = this.disagreeSince.get(key) ?? now;+ this.disagreeSince.set(key, since);+ if (now - since >= forMs && !this.disagreeCounted.has(key)) {+ this.disagreeCounted.add(key);+ this.anomaly(key);+ }+ }+/** While disconnected, the pane's liveness is `kill(panePid, 0)` every second (X-M12). */private checkLiveness(): void {if (this.client || !this.panePidValue || this.paneExited) return;@@ -777,6 +858,7 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {}private bootReady(): void {+ this.bootReadyAtMs = Date.now();if (this.queue.length === 0) {this.fire("boot_ready_idle");return;@@ -1503,8 +1585,12 @@ export class PaneSessionImpl implements PaneSession, RegisteredPane {diagnostics(): PaneDiagnostics {const cur = this.follower.view().current;+ const rec = this.registryRec;return {magmuxStderr: this.stderrHead,+ registry: rec+ ? { status: rec.status, waitingFor: rec.waitingFor, version: rec.version }+ : null,preambleBytes: cur?.preambleBytes ?? 0,readCoverage: cur?.delivery? {diff --git a/packages/cli/src/pane/session-registry.test.ts b/packages/cli/src/pane/session-registry.test.tsnew file mode 100644index 00000000..03ab8605--- /dev/null+++ b/packages/cli/src/pane/session-registry.test.ts@@ -0,0 +1,185 @@+import { afterEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { SessionRegistry, parseRegistryRecord } from "./session-registry.js";++// Real boot, idle and busy records from the acr2 registry.jsonl capture.+// Only cwd and messagingSocketPath are neutralized in these base fixtures.+const bootRecord = {+ pid: 20259,+ sessionId: "5b97c898-ab53-42be-b866-6389dd321a16",+ cwd: "/tmp/x",+ startedAt: 1791466216838,+ procStart: "Thu Oct 8 13:30:16 2026",+ version: "2.1.294",+ peerProtocol: 1,+ peerFeatures: ["notify_idle", "reply_across_default_dirs", "artifact_yield"],+ kind: "interactive",+ entrypoint: "cli",+ pidDomain: "darwin",+ messagingSocketPath: "/tmp/x.sock",+ name: "acr2-e6",+ nameSource: "derived",+ nameSince: 1791466216838,+};+const idleRecord = {+ ...bootRecord,+ status: "idle",+ updatedAt: 1791466216946,+ statusUpdatedAt: 1791466216946,+};+const busyRecord = {+ ...bootRecord,+ status: "busy",+ updatedAt: 1791466218682,+ statusUpdatedAt: 1791466218682,+};+const expectedIdle = {+ pid: 20259,+ sessionId: bootRecord.sessionId,+ status: "idle",+ statusUpdatedAt: 1791466216946,+ waitingFor: null,+ version: "2.1.294",+};++const tempDirs: string[] = [];+afterEach(() => {+ for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++function setup({ sessions = true, alive = true } = {}) {+ const configDir = mkdtempSync(join(tmpdir(), "session-registry-test-"));+ tempDirs.push(configDir);+ const dir = join(configDir, "sessions");+ if (sessions) mkdirSync(dir);+ let now = 10_000;+ const checkedPids: number[] = [];+ const registry = new SessionRegistry({+ configDir,+ sessionUuid: bootRecord.sessionId,+ now: () => now,+ isAlive: (pid) => {+ checkedPids.push(pid);+ return alive;+ },+ });+ return {+ registry,+ checkedPids,+ advance: (ms: number) => {+ now += ms;+ },+ write: (name: string, record: object, suffix = "") =>+ writeFileSync(join(dir, name), JSON.stringify(record) + suffix),+ remove: (name: string) => rmSync(join(dir, name)),+ };+}++describe("parseRegistryRecord", () => {+ test("maps fields from a real status record with absent waitingFor", () => {+ expect(parseRegistryRecord(JSON.stringify(idleRecord))).toEqual(expectedIdle);+ });++ test("returns null status before the first status update", () => {+ expect(parseRegistryRecord(JSON.stringify(bootRecord))).toEqual({+ ...expectedIdle,+ status: null,+ statusUpdatedAt: null,+ });+ });++ test("parses a torn write with an extra trailing brace", () => {+ expect(parseRegistryRecord(JSON.stringify(idleRecord) + "}\n")).toEqual(expectedIdle);+ });++ test("rejects garbage, non-objects and missing identity fields", () => {+ const { pid: _pid, ...withoutPid } = idleRecord;+ const { sessionId: _sessionId, ...withoutSessionId } = idleRecord;+ for (const raw of [+ "garbage",+ "null",+ "42",+ '"text"',+ "true",+ "[]",+ "{}",+ JSON.stringify(withoutPid),+ JSON.stringify(withoutSessionId),+ ]) {+ expect(parseRegistryRecord(raw)).toBeNull();+ }+ });+});++describe("SessionRegistry.read", () => {+ test("finds its session among foreign, torn and non-numeric files", () => {+ const s = setup();+ s.write("100.json", { ...idleRecord, pid: 100, sessionId: "foreign-session" });+ s.write("x.json", { ...idleRecord, pid: 101 });+ s.write("20259.json", idleRecord, "}");+ expect(s.registry.read()).toEqual(expectedIdle);+ expect(s.checkedPids).toEqual([20259]);+ });++ test("ignores a matching record in a non-numeric filename", () => {+ const s = setup();+ s.write("x.json", idleRecord);+ expect(s.registry.read()).toBeNull();+ expect(s.checkedPids).toEqual([]);+ });++ test("returns null for a foreign-only directory", () => {+ const s = setup();+ s.write("20259.json", { ...idleRecord, sessionId: "foreign-session" });+ expect(s.registry.read()).toBeNull();+ expect(s.checkedPids).toEqual([]);+ });++ test("returns null when the record pid is not alive", () => {+ const s = setup({ alive: false });+ s.write("20259.json", idleRecord);+ expect(s.registry.read()).toBeNull();+ expect(s.checkedPids).toEqual([20259]);+ });++ test("rejects a record whose pid differs from its filename", () => {+ const s = setup();+ s.write("20260.json", idleRecord);+ expect(s.registry.read()).toBeNull();+ expect(s.checkedPids).toEqual([]);+ });++ test("reads status changes from the cached pid before the next scan", () => {+ const s = setup();+ s.write("20259.json", idleRecord);+ expect(s.registry.read()).toEqual(expectedIdle);+ s.write("20259.json", busyRecord);+ expect(s.registry.read()).toEqual({+ ...expectedIdle,+ status: "busy",+ statusUpdatedAt: 1791466218682,+ });+ expect(s.checkedPids).toEqual([20259, 20259]);+ });++ test("waits for the scan interval after the cached file disappears", () => {+ const s = setup();+ s.write("20259.json", idleRecord);+ expect(s.registry.read()).toEqual(expectedIdle);+ s.remove("20259.json");+ expect(s.registry.read()).toBeNull();+ s.write("20260.json", { ...idleRecord, pid: 20260 });+ s.advance(999);+ expect(s.registry.read()).toBeNull();+ s.advance(1);+ expect(s.registry.read()).toEqual({ ...expectedIdle, pid: 20260 });+ expect(s.checkedPids).toEqual([20259, 20260]);+ });++ test("returns null without throwing when the sessions directory is missing", () => {+ const s = setup({ sessions: false });+ expect(() => expect(s.registry.read()).toBeNull()).not.toThrow();+ });+});diff --git a/packages/cli/src/pane/session-registry.ts b/packages/cli/src/pane/session-registry.tsnew file mode 100644index 00000000..256ae0ab--- /dev/null+++ b/packages/cli/src/pane/session-registry.ts@@ -0,0 +1,138 @@+/**+ * The pane child's own state from Claude Code's session registry (research+ * dev-research-cc-slot-signals, report §"What claudish reads from the screen").+ *+ * Every interactive Claude Code writes `<configDir>/sessions/<pid>.json` and rewrites it+ * on each state change: `status` is `idle`, `busy`, `waiting` (with `waitingFor`) or+ * `shell` (a background Bash still running after the turn), and the first record has no+ * `status` at all for 100–440 ms of boot. The record's `sessionId` is the `--session-id`+ * claudish mints, so a pane finds its record by that uuid (11/11 measured) and never by+ * a bare pid.+ *+ * The file is undocumented (`claude agents --json` is the documented reader, but a user's+ * `disableAgentView` makes it refuse, and it omits fields we read), so everything here is+ * defensive: a missing, unparseable, foreign or dead record is `null`, and callers fall+ * back to the screen. #96438: a torn write can leave a stray trailing `}`.+ */++import { readFileSync, readdirSync } from "node:fs";+import { join } from "node:path";++export interface RegistryRecord {+ pid: number;+ sessionId: string;+ /** null while the record has no status yet (boot) */+ status: string | null;+ /** Claude Code's wall clock, ms; null when absent */+ statusUpdatedAt: number | null;+ waitingFor: string | null;+ version: string | null;+}++/** Statuses whose meaning claudish relies on. Anything else is reported, never acted on. */+export const KNOWN_STATUSES: ReadonlySet<string> = new Set(["idle", "busy", "waiting", "shell"]);++/** Rescan the directory at most this often while the record is not found. */+const SCAN_INTERVAL_MS = 1_000;++/** Parse one record; tolerates the trailing-brace torn write of #96438. */+export function parseRegistryRecord(raw: string): RegistryRecord | null {+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ const trimmed = raw.trimEnd().replace(/\}+$/, "}");+ try {+ parsed = JSON.parse(trimmed);+ } catch {+ return null;+ }+ }+ if (!parsed || typeof parsed !== "object") return null;+ const r = parsed as Record<string, unknown>;+ if (typeof r.pid !== "number" || typeof r.sessionId !== "string") return null;+ return {+ pid: r.pid,+ sessionId: r.sessionId,+ status: typeof r.status === "string" ? r.status : null,+ statusUpdatedAt: typeof r.statusUpdatedAt === "number" ? r.statusUpdatedAt : null,+ waitingFor: typeof r.waitingFor === "string" ? r.waitingFor : null,+ version: typeof r.version === "string" ? r.version : null,+ };+}++function pidAlive(pid: number): boolean {+ try {+ process.kill(pid, 0);+ return true;+ } catch (e) {+ // EPERM: alive, owned by someone else — not our child, but not dead either+ return (e as NodeJS.ErrnoException).code === "EPERM";+ }+}++export interface SessionRegistryOptions {+ /** `claudeConfigDir(env)` of the child's environment */+ configDir: string;+ sessionUuid: string;+ /** @internal test seams */+ now?: () => number;+ isAlive?: (pid: number) => boolean;+}++/**+ * One pane's view of its record. `read()` is cheap once the record is found (one file+ * read); until then it scans `sessions/` at most once a second. Never throws.+ */+export class SessionRegistry {+ private pid: number | null = null;+ private lastScanAt = Number.NEGATIVE_INFINITY;+ private readonly dir: string;+ private readonly now: () => number;+ private readonly isAlive: (pid: number) => boolean;++ constructor(private readonly o: SessionRegistryOptions) {+ this.dir = join(o.configDir, "sessions");+ this.now = o.now ?? Date.now;+ this.isAlive = o.isAlive ?? pidAlive;+ }++ read(): RegistryRecord | null {+ if (this.pid !== null) {+ const rec = this.readPid(this.pid);+ if (rec) return rec;+ this.pid = null;+ }+ const now = this.now();+ if (now - this.lastScanAt < SCAN_INTERVAL_MS) return null;+ this.lastScanAt = now;+ let names: string[];+ try {+ names = readdirSync(this.dir);+ } catch {+ return null;+ }+ for (const name of names) {+ const m = /^(\d+)\.json$/.exec(name);+ if (!m) continue;+ const rec = this.readPid(Number(m[1]));+ if (rec) {+ this.pid = rec.pid;+ return rec;+ }+ }+ return null;+ }++ private readPid(pid: number): RegistryRecord | null {+ let raw: string;+ try {+ raw = readFileSync(join(this.dir, `${pid}.json`), "utf8");+ } catch {+ return null;+ }+ const rec = parseRegistryRecord(raw);+ if (!rec || rec.pid !== pid || rec.sessionId !== this.o.sessionUuid) return null;+ return this.isAlive(pid) ? rec : null;+ }+}