Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(mcp): poll the transcript for 2 s to prove parentClaudeSessionId
Jack Rudenko51104c769b58
diff --git a/ai-docs/architecture/mcp-channel.md b/ai-docs/architecture/mcp-channel.mdindex 36ae2c0b..2ee24cc6 100644--- a/ai-docs/architecture/mcp-channel.md+++ b/ai-docs/architecture/mcp-channel.md@@ -204,14 +204,17 @@ inert. `launcherPid` is recorded exactly when that branch ran. No `ps`, no treeenvironment's `CLAUDE_CODE_SESSION_ID` goes stale on `/clear`, on a resume, and whenever twowindows share a conversation, so it is never stored as such. Claude Code puts the callingtool-use id in the request `_meta["claudecode/toolUseId"]` (the dispatcher passes it as-`ctx.toolUseId`), and the tool_use block is on disk in the caller's transcript before the tool-runs. For at most two candidates — the env id (only when `CLAUDE_CODE_CHILD_SESSION` is empty)+`ctx.toolUseId`), and the tool_use block lands in the caller's transcript — but ASYNCHRONOUSLY:+in a live Claude Code 2.1.290 session (2026-10-06, 10 ms poller) the `create_session` record+reached disk 377 ms after its own timestamp, after the tool had already started. For at most two candidates — the env id (only when `CLAUDE_CODE_CHILD_SESSION` is empty)and the `sessionId` of the host's live record `<configDir>/sessions/<hostPid>.json` (only whenits `pid` matches) — the proof finds the candidate's project directory (fast path: the hostrecord's `cwd` with every non-alphanumeric character replaced by `-`; else one listing of`projects/`, cached per candidate), then searches the last 256 KB of `<C>.jsonl` and up to 32-subagent transcripts modified in the last 10 minutes for the quoted id. No hit → wait 250 ms-once, look again, then absent. A tool-use id is unique and lives only in the transcript of the+subagent transcripts modified in the last 10 minutes for the quoted id. No hit → look again+every 100 ms (`PROOF_POLL_INTERVAL_MS`) until 2000 ms (`PROOF_DEADLINE_MS`) have passed, then+absent; a hit returns at once, so a call whose record is already on disk waits for nothing. The+single 250 ms retry this replaced lost that race in 2 of 3 calls in one session. A tool-use id is unique and lives only in the transcript of theconversation that issued it, so a hit is proof and every failure degrades to "absent". It is`await`ed with `fs/promises` before `createSession`, so the server keeps pumping live sessionswhile it looks. `meta.json` (`SessionInfo.parentClaudeSessionId`) carries the same key with thediff --git a/packages/cli/src/channel/parent-proof.contract.test.ts b/packages/cli/src/channel/parent-proof.contract.test.tsindex e94c6985..81346f45 100644--- a/packages/cli/src/channel/parent-proof.contract.test.ts+++ b/packages/cli/src/channel/parent-proof.contract.test.ts@@ -3,8 +3,8 @@* Black-box contract tests for channel/parent-proof.ts (design §3.5, §8.1 tests 9-10;* amendments 1 and 5). Written from the specification only.*- * Every proof runs over a synthetic Claude config dir in a temp directory. The retry wait is- * injected (`sleep`), so no test waits 250 ms for real. INFERRED: a `ProofCandidate` carries+ * Every proof runs over a synthetic Claude config dir in a temp directory. The poll wait is+ * injected (`sleep`), so no test waits for real. INFERRED: a `ProofCandidate` carries* `{ sessionId, cwd? }` — the only place the host record's `cwd` can reach the proof, since* `proveCallingConversation` takes no host-record argument. Built in `candidate()` only.*/@@ -24,7 +24,8 @@ import {import {CLAUDE_ID_RE,MAX_SUBAGENT_FILES,- PROOF_RETRY_DELAY_MS,+ PROOF_DEADLINE_MS,+ PROOF_POLL_INTERVAL_MS,SUBAGENT_WINDOW_MS,TOOL_USE_ID_META_KEY,TRANSCRIPT_TAIL_BYTES,@@ -102,13 +103,14 @@ describe("REQ-4 constants named by the contract carry the spec's values", () =>expect(TOOL_USE_ID_META_KEY).toBe("claudecode/toolUseId");});- test("tail, subagent window, subagent cap and retry delay match §3.5", () => {+ test("tail, subagent window, subagent cap and proof polling match §3.5", () => {expect({tail: TRANSCRIPT_TAIL_BYTES,window: SUBAGENT_WINDOW_MS,cap: MAX_SUBAGENT_FILES,- retry: PROOF_RETRY_DELAY_MS,- }).toEqual({ tail: 256 * 1024, window: 10 * 60 * 1000, cap: 32, retry: 250 });+ poll: PROOF_POLL_INTERVAL_MS,+ deadline: PROOF_DEADLINE_MS,+ }).toEqual({ tail: 256 * 1024, window: 10 * 60 * 1000, cap: 32, poll: 100, deadline: 2000 });});test.each([@@ -328,7 +330,7 @@ describe("REQ-1/REQ-2/REQ-4 proveCallingConversation (§8.1 test 10)", () => {expect(parent).toBe(E);});- test("returns undefined after exactly one 250 ms wait when no transcript holds the id", async () => {+ test("returns undefined after polling every 100 ms for 2000 ms when no transcript holds the id", async () => {const E = claudeId("env");writeMainTranscript("P", E, fillerLine(1));@@ -340,10 +342,10 @@ describe("REQ-1/REQ-2/REQ-4 proveCallingConversation (§8.1 test 10)", () => {});expect(parent).toBeUndefined();- expect(sleeps).toEqual([250]);+ expect(sleeps).toEqual(Array(20).fill(100));});- test("finds an id appended to the transcript during the retry wait", async () => {+ test("finds an id appended to the transcript during the first poll wait", async () => {const E = claudeId("env");const T = toolUseId();const path = writeMainTranscript("P", E, fillerLine(1));@@ -360,7 +362,7 @@ describe("REQ-1/REQ-2/REQ-4 proveCallingConversation (§8.1 test 10)", () => {});expect(parent).toBe(E);- expect(sleeps).toEqual([250]);+ expect(sleeps).toEqual([100]);});test("ignores an id that occurs only before the last 256 KB of the main transcript", async () => {diff --git a/packages/cli/src/channel/parent-proof.test.ts b/packages/cli/src/channel/parent-proof.test.tsindex ce352bd5..10077627 100644--- a/packages/cli/src/channel/parent-proof.test.ts+++ b/packages/cli/src/channel/parent-proof.test.ts@@ -11,7 +11,13 @@import { describe, expect, test } from "bun:test";import { join } from "node:path";-import { type ProjectDirCache, type ProofFs, proveCallingConversation } from "./parent-proof.js";+import {+ PROOF_DEADLINE_MS,+ PROOF_POLL_INTERVAL_MS,+ type ProjectDirCache,+ type ProofFs,+ proveCallingConversation,+} from "./parent-proof.js";const CONFIG = "/cfg";const PROJECTS = join(CONFIG, "projects");@@ -137,3 +143,94 @@ describe("parent proof project-directory cache", () => {expect([...cache.values()]).toEqual([join(PROJECTS, "-new")]);});});++/**+ * Claude Code appends the tool_use record asynchronously. Measured in a live+ * 2.1.290 session, the `create_session` record reached disk 377 ms after its+ * own timestamp, after a single 250 ms retry had already given up.+ */+describe("parent proof waits for a late transcript append", () => {+ test("a tool-use id that reaches disk 400 ms late is proven", async () => {+ const path = join(PROJECTS, "-p", `${SESSION}.jsonl`);+ const nodes = new Map<string, Node>([[path, { kind: "file", content: "", mtimeMs: 0 }]]);+ let clock = 0;+ const parent = await proveCallingConversation({+ toolUseId: TOOL_USE,+ candidates: [{ sessionId: SESSION }],+ configDir: CONFIG,+ fs: memoryFs(nodes),+ cache: new Map(),+ now: () => clock,+ sleep: async (ms) => {+ clock += ms;+ if (clock >= 400) nodes.set(path, transcript());+ },+ });+ expect(parent).toBe(SESSION);+ });++ test("a hit on the first look sleeps not at all", async () => {+ const sleeps: number[] = [];+ const nodes = new Map<string, Node>([[join(PROJECTS, "-p", `${SESSION}.jsonl`), transcript()]]);+ const parent = await proveCallingConversation({+ toolUseId: TOOL_USE,+ candidates: [{ sessionId: SESSION }],+ configDir: CONFIG,+ fs: memoryFs(nodes),+ cache: new Map(),+ now: () => 0,+ sleep: async (ms) => {+ sleeps.push(ms);+ },+ });+ expect(parent).toBe(SESSION);+ expect(sleeps).toEqual([]);+ });++ test("an id that never arrives is unproven after the deadline, even on a frozen clock", async () => {+ const sleeps: number[] = [];+ const nodes = new Map<string, Node>([+ [join(PROJECTS, "-p", `${SESSION}.jsonl`), { kind: "file", content: "", mtimeMs: 0 }],+ ]);+ const parent = await proveCallingConversation({+ toolUseId: TOOL_USE,+ candidates: [{ sessionId: SESSION }],+ configDir: CONFIG,+ fs: memoryFs(nodes),+ cache: new Map(),+ now: () => 0,+ sleep: async (ms) => {+ sleeps.push(ms);+ },+ });+ expect(parent).toBeUndefined();+ expect(sleeps.every((ms) => ms === PROOF_POLL_INTERVAL_MS)).toBe(true);+ expect(sleeps.reduce((a, b) => a + b, 0)).toBe(PROOF_DEADLINE_MS);+ });++ test("time spent looking counts toward the deadline", async () => {+ const sleeps: number[] = [];+ let clock = 0;+ const nodes = new Map<string, Node>([+ [join(PROJECTS, "-p", `${SESSION}.jsonl`), { kind: "file", content: "", mtimeMs: 0 }],+ ]);+ const parent = await proveCallingConversation({+ toolUseId: TOOL_USE,+ candidates: [{ sessionId: SESSION }],+ configDir: CONFIG,+ fs: memoryFs(nodes),+ cache: new Map(),+ // Every clock read costs 500 ms of wall time: a slow disk.+ now: () => {+ clock += 500;+ return clock;+ },+ sleep: async (ms) => {+ sleeps.push(ms);+ clock += ms;+ },+ });+ expect(parent).toBeUndefined();+ expect(sleeps.length).toBeLessThan(PROOF_DEADLINE_MS / PROOF_POLL_INTERVAL_MS);+ });+});diff --git a/packages/cli/src/channel/parent-proof.ts b/packages/cli/src/channel/parent-proof.tsindex fba49f13..25fad340 100644--- a/packages/cli/src/channel/parent-proof.ts+++ b/packages/cli/src/channel/parent-proof.ts@@ -39,8 +39,15 @@ export const SUBAGENT_WINDOW_MS = 10 * 60_000;/** At most this many subagent transcripts are searched, newest first. */export const MAX_SUBAGENT_FILES = 32;-/** The single wait before the second look: the transcript append may be in flight. */-export const PROOF_RETRY_DELAY_MS = 250;+/**+ * Wait between looks while the transcript append may still be in flight.+ * Claude Code writes the tool_use record asynchronously: in a live 2.1.290+ * session it reached disk 377 ms after its own timestamp.+ */+export const PROOF_POLL_INTERVAL_MS = 100;++/** Total time the proof keeps looking before it answers "not proven". */+export const PROOF_DEADLINE_MS = 2000;// ─── hostPid ─────────────────────────────────────────────────────────────────@@ -353,11 +360,11 @@ export interface ProveCallingConversationOptions {candidates: readonly (ProofCandidate | string)[];/** Claude Code's config directory (`claudeConfigDir(env)`). */configDir: string;- /** Clock for the subagent recency window. Default `Date.now`. */+ /** Clock for the subagent recency window and the deadline. Default `Date.now`. */now?: () => number;/** Injected filesystem. Default `node:fs/promises`. */fs?: ProofFs;- /** The single 250 ms wait. Default a real timer. */+ /** The wait between looks. Default a real timer. */sleep?: (ms: number) => Promise<void>;/** Project directories the listing found. Default: one cache for the server's life. */cache?: ProjectDirCache;@@ -371,8 +378,12 @@ export interface ProveCallingConversationOptions {* For each candidate: find its project directory (fast path from `cwd`, else* one listing), then search the last 256 KB of `<C>.jsonl`, then up to 32* subagent transcripts modified in the last 10 minutes, newest first, for the- * exact quoted substring `"<toolUseId>"`. The first hit decides. With no hit,- * wait 250 ms once and look again; then `undefined`.+ * exact quoted substring `"<toolUseId>"`. The first hit decides and returns at+ * once, so a call whose record is already on disk waits for nothing. With no+ * hit, look again every `PROOF_POLL_INTERVAL_MS` until `PROOF_DEADLINE_MS`+ * has passed, then `undefined`. Elapsed time is the larger of the clock's+ * advance and the total slept, so the loop ends even under a clock that never+ * moves.*/export async function proveCallingConversation(opts: ProveCallingConversationOptions@@ -398,10 +409,17 @@ export async function proveCallingConversation(};try {- const first = await look();- if (first !== undefined) return first;- await sleep(PROOF_RETRY_DELAY_MS);- return await look();+ const startedAt = now();+ let slept = 0;+ for (;;) {+ const found = await look();+ if (found !== undefined) return found;+ const remaining = PROOF_DEADLINE_MS - Math.max(now() - startedAt, slept);+ if (remaining <= 0) return undefined;+ const wait = Math.min(PROOF_POLL_INTERVAL_MS, remaining);+ await sleep(wait);+ slept += wait;+ }} catch {// Every failure is "not proven".return undefined;diff --git a/packages/cli/src/mcp-server.ts b/packages/cli/src/mcp-server.tsindex 7cd197f6..29cb68bf 100644--- a/packages/cli/src/mcp-server.ts+++ b/packages/cli/src/mcp-server.ts@@ -1798,7 +1798,7 @@ function defineTools(});// Which conversation called, PROVEN from its transcript or left absent.- // Asynchronous throughout (fs/promises, one 250 ms timer at most), so+ // Asynchronous throughout (fs/promises, 100 ms polls for 2 s at most), so// this process keeps pumping every live session while it looks.const parentClaudeSessionId = await proveParentForCall({toolUseId: ctx.toolUseId,