Skip to content

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

fix(mcp): read parentClaudeSessionId from the host session record

Jack Rudenkof4952d145e69
diff --git a/ai-docs/architecture/mcp-channel.md b/ai-docs/architecture/mcp-channel.md
index 5d97b26f..3013aca0 100644
--- a/ai-docs/architecture/mcp-channel.md
+++ b/ai-docs/architecture/mcp-channel.md
@@ -46,7 +46,7 @@ argument becomes `--agent <name>`; an unknown name is refused by the child itsel
`agent_rejected`), so claudish runs no agent probe of its own.
**A session is created in this order**: the flag check, `assertMagmuxAvailable` (magmux ≥ 0.14.0,
-else `Error: magmux_unavailable: …`), credential pre-hydration, the parent proof, a pane
+else `Error: magmux_unavailable: …`), credential pre-hydration, the parent session read, a pane
reservation (`Error: pane_limit: …` past 48 live panes per user), `prompt.md`, `spawn.json`, then the
pane. `create_session` returns `{session_id, state}` once the pane exists, without waiting for boot.
A pane that fails to start leaves a FAILED `pane_lost` session with its `meta.json`, and the call
@@ -170,7 +170,7 @@ every runtime file (`output.log`, `events.jsonl`, `tokens.json`, `waits.jsonl`,
"schema": 1, // versions spawn.json only
"kind": "session", // "session" | "team"
"sessionId": "1a2b3c4d",
- "parentClaudeSessionId": "<uuid>", // OPTIONAL — present only when proven
+ "parentClaudeSessionId": "<uuid>", // OPTIONAL — absent when no well-formed id could be read
"hostPid": 12345, // the Claude Code process that launched this server
"launcherPid": 12398, // OPTIONAL — present only on the npm launcher path
"mcpPid": 12399, // this process: the one that writes meta.json
@@ -187,7 +187,7 @@ sessions directory and reports progress to the Claude Code window that started a
`mcpPid` is also the pane record's owner, and the watchers make the monitor's liveness inference
sound: when the writer dies, its panes die with it.
-**`hostPid` is structural, computed once at startup** (`hostPidFrom`, `channel/parent-proof.ts`).
+**`hostPid` is structural, computed once at startup** (`hostPidFrom`, `channel/parent-session.ts`).
A compiled binary or `bun src/index.ts` is the direct child of Claude Code, so `hostPid` is
`process.ppid`. An npm/bun global install runs Claude Code → `node bin/claudish.cjs` → `bun
dist/index.js`, so the launcher puts `CLAUDISH_LAUNCHER_PID` (itself) and
@@ -197,25 +197,36 @@ inert. `launcherPid` is recorded exactly when that branch ran. No `ps`, no tree
environment strips the pair and `CLAUDE_CODE_SESSION_ID`, so a claudish MCP server nested inside a
pane cannot inherit the host's identity either.
-**`parentClaudeSessionId` is proven per call, or absent** (`proveCallingConversation`). The
-environment's `CLAUDE_CODE_SESSION_ID` goes stale on `/clear`, on a resume, and whenever two
-windows share a conversation, so it is never stored as such. Claude Code puts the calling
-tool-use id in the request `_meta["claudecode/toolUseId"]` (the dispatcher passes it as
-`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 when
-its `pid` matches) — the proof finds the candidate's project directory (fast path: the host
-record'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 → 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 the
-conversation 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 sessions
-while it looks. `meta.json` carries the same key with the same value exactly when `spawn.json`
-does.
+**`parentClaudeSessionId` is the host session record's id, read once per call**
+(`parentSessionForCall`, `channel/parent-session.ts`). At `create_session` and
+`team(mode:"run")` time claudish reads `<configDir>/sessions/<hostPid>.json` (`configDir` is
+`CLAUDE_CONFIG_DIR`, else `$HOME/.claude`) and records its `sessionId` when the file parses,
+its `pid` equals `hostPid` and the id is well formed. Only when no record can be read does it
+fall back to `CLAUDE_CODE_SESSION_ID` (ignored under `CLAUDE_CODE_CHILD_SESSION`); with
+neither, the key is absent. One file read: no transcript search, no polling, no delay.
+`meta.json` carries the same key with the same value exactly when `spawn.json` does.
+
+Why the host record, measured on Claude Code 2.1.290 in live interactive sessions
+(`madbench --manual`, 2026-10-06):
+
+- The host record carries the window's LIVE conversation, `{"pid":…,"sessionId":…,"cwd":…}`:
+ its `sessionId` went `6f9e3d06…` → `d5b9974e…` after `/clear` and back to `6f9e3d06…`
+ after `/resume`. The MCP server's `CLAUDE_CODE_SESSION_ID` equals it at server start and
+ goes stale after the first `/clear`, which is why the env id is only the fallback.
+- The transcript cannot attribute the call. Claude Code writes a call's `tool_use` record
+ only AFTER the MCP tool call returns. With a 10 ms poller: record timestamp `00:41:39.899`,
+ claudish gave up a 2 s transcript poll and spawned at `00:41:41.909`, the record reached
+ disk at `00:41:42.052`; an earlier call, `34.785` / spawn `35.040` / on disk `35.162`. The
+ previous mechanism searched the calling conversation's transcript for the `_meta`
+ tool-use id, polling up to 2 s; it could never find the call it was proving, so every
+ `create_session` came out unattributed and 2 s slower. It is deleted, and claudish no
+ longer reads `_meta["claudecode/toolUseId"]`.
+ `spawn-record.contract.test.ts` "regression: the transcript does not hold the call while
+ the tool runs" replays that order and fails against the transcript search.
+
+Accepted race: a `/clear` typed in the very moment a call runs may attribute that run to the
+new conversation. It is never attributed to another window — the record is keyed by this
+server's own `hostPid`.
### `meta.json` — the final record, and `events.jsonl`'s assistant lines
diff --git a/docs/usage/mcp-server.md b/docs/usage/mcp-server.md
index 4a543baa..f63a2764 100644
--- a/docs/usage/mcp-server.md
+++ b/docs/usage/mcp-server.md
@@ -394,7 +394,7 @@ contract.
| File | Written | Contents |
|------|---------|----------|
-| `spawn.json` | once, before the session's pane starts; atomic | `schema`, `kind: "session"`, `sessionId`, `hostPid` (the Claude Code process running this MCP server), `mcpPid`, `startedAt`, `model`, `timeoutSeconds`, `claudeSessionId`; `launcherPid` when claudish runs through the npm launcher; `parentClaudeSessionId` only when claudish proved which Claude Code conversation made the call |
+| `spawn.json` | once, before the session's pane starts; atomic | `schema`, `kind: "session"`, `sessionId`, `hostPid` (the Claude Code process running this MCP server), `mcpPid`, `startedAt`, `model`, `timeoutSeconds`, `claudeSessionId`; `launcherPid` when claudish runs through the npm launcher; `parentClaudeSessionId`, the Claude Code conversation live in the calling window when the call ran (read from Claude Code's session record for `hostPid`, else from `CLAUDE_CODE_SESSION_ID`; absent when neither has an id) |
| `waits.jsonl` | one line each time the session starts and stops waiting for `send_input` | `{"wait":"open","since":…,"turns":…}` then `{"wait":"closed","since":…,"at":…,"to":…}`. Written by interactive sessions, and by any session stopped on a question or permission dialog; append-only, so a wait that opened and closed between two reads still shows. Stops at 1 MB |
| `meta.json` | once, when the session ends, before its pane is closed | the final record: `status`, `terminalReason`, `exitCode`, `turnsCompleted`, `toolCallCount`, `costUsd` (null for native Claude models), plus `state`, `detail`, `tokensIn`, `tokensOut`, and `parentClaudeSessionId` exactly when `spawn.json` has it |
| `events.jsonl` | while the session runs | claudish's own records: state changes, tools, anomalies, and one `{"type":"assistant","message":{"id":…}}` line per model reply. Capped at 4 MB |
diff --git a/packages/cli/bin/claudish.cjs b/packages/cli/bin/claudish.cjs
index d4212b6b..e804fcf5 100755
--- a/packages/cli/bin/claudish.cjs
+++ b/packages/cli/bin/claudish.cjs
@@ -114,7 +114,7 @@ Learn more: https://bun.sh`);
// The pid pair tells the Bun child who launched it: this launcher, and the
// launcher's own parent (Claude Code, for an MCP server). The child
// believes the pair only when CLAUDISH_LAUNCHER_PID is its real parent
- // (channel/parent-proof.ts `hostPidFrom`), so a value leaked into a
+ // (channel/parent-session.ts `hostPidFrom`), so a value leaked into a
// nested claudish is inert.
env: {
...process.env,
diff --git a/packages/cli/src/channel/home-dir.test.ts b/packages/cli/src/channel/home-dir.test.ts
index 2b4c91ea..a6749860 100644
--- a/packages/cli/src/channel/home-dir.test.ts
+++ b/packages/cli/src/channel/home-dir.test.ts
@@ -11,8 +11,8 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { join } from "node:path";
-import { sessionsDirFrom, userHomeFrom } from "./home-dir.js";
-import { claudeConfigDir } from "./parent-proof.js";
+import { projectDirNameFor, sessionsDirFrom, userHomeFrom } from "./home-dir.js";
+import { claudeConfigDir } from "./parent-session.js";
import { SessionManager } from "./session-manager.js";
const SANDBOX_HOME = "/sandbox/home-dir-test";
@@ -69,7 +69,7 @@ describe("claudish follows a runtime HOME", () => {
}
});
- test("the parent proof reads Claude Code's config under $HOME", () => {
+ test("the host session record is read from Claude Code's config under $HOME", () => {
expect(claudeConfigDir({ HOME: SANDBOX_HOME })).toBe(join(SANDBOX_HOME, ".claude"));
});
@@ -77,3 +77,12 @@ describe("claudish follows a runtime HOME", () => {
expect(claudeConfigDir({ HOME: SANDBOX_HOME, CLAUDE_CONFIG_DIR: "/cfg" })).toBe("/cfg");
});
});
+
+describe("REQ-4 projectDirNameFor: every character outside [A-Za-z0-9] becomes '-'", () => {
+ test.each([
+ ["/Users/someone/.claude/worktrees/x", "-Users-someone--claude-worktrees-x"],
+ ["/srv/my_app v2.1", "-srv-my-app-v2-1"],
+ ])("%s → %s", (cwd, expected) => {
+ expect(projectDirNameFor(cwd)).toBe(expected);
+ });
+});
diff --git a/packages/cli/src/channel/home-dir.ts b/packages/cli/src/channel/home-dir.ts
index 8a4e8b37..b730601b 100644
--- a/packages/cli/src/channel/home-dir.ts
+++ b/packages/cli/src/channel/home-dir.ts
@@ -1,6 +1,6 @@
// ─── Where the sessions directory and Claude Code's config live ──────────────
//
-// ONE rule, shared with the magus `claudish` plugin monitor
+// The sessions directory: ONE rule, shared with the magus `claudish` plugin monitor
// (`plugins/claudish/scripts/session-monitor.ts` `sessionsDirFrom`), which
// polls the directory this process writes. If the two resolve it differently,
// every run is written where the monitor is not looking and nothing errors.
@@ -31,3 +31,32 @@ export function sessionsDirFrom(env: Env, homedirFn: () => string = homedir): st
if (explicit && explicit.length > 0) return explicit;
return join(userHomeFrom(env, homedirFn), ".claudish", "sessions");
}
+
+// ─── Claude Code's project directory name for a cwd ──────────────────────────
+
+/** Claude Code keeps a project directory name to this many slug characters. */
+export const PROJECT_DIR_SLUG_MAX = 200;
+
+/** Claude Code's 32-bit string hash (`(h << 5) - h + charCode`, per UTF-16 unit). */
+function claudeCodeStringHash(s: string): number {
+ let h = 0;
+ for (let i = 0; i < s.length; i++) h = ((h << 5) - h + s.charCodeAt(i)) | 0;
+ return h;
+}
+
+/**
+ * Claude Code's project directory name for a cwd: every character outside
+ * `[A-Za-z0-9]` becomes `-` (so `/.claude/` becomes `--claude-`). A slug longer than
+ * 200 characters is cut to 200 and suffixed `-<base36 |hash(cwd)|>`, the hash taken
+ * over the WHOLE path, not the slug. Read from Claude Code 2.1.291's own bundle
+ * (`k(e)=e.replace(/[^a-zA-Z0-9]/g,"-")`, `eI(e)` truncates at `Rle=200` and appends
+ * `Le(e)=Math.abs(hash(e)).toString(36)`) and MEASURED: a live 2.1.291 run in a
+ * 259-character cwd wrote `<200 slug chars>-g32rlu`, which this function reproduces.
+ * The one rule: `slugForPath` (session/session-discovery.ts) and every transcript path
+ * claudish derives go through it.
+ */
+export function projectDirNameFor(cwd: string): string {
+ const slug = cwd.replace(/[^A-Za-z0-9]/g, "-");
+ if (slug.length <= PROJECT_DIR_SLUG_MAX) return slug;
+ return `${slug.slice(0, PROJECT_DIR_SLUG_MAX)}-${Math.abs(claudeCodeStringHash(cwd)).toString(36)}`;
+}
diff --git a/packages/cli/src/channel/host-pid.contract.test.ts b/packages/cli/src/channel/host-pid.contract.test.ts
index 5d1092b2..39673bec 100644
--- a/packages/cli/src/channel/host-pid.contract.test.ts
+++ b/packages/cli/src/channel/host-pid.contract.test.ts
@@ -2,7 +2,7 @@
/**
* Black-box contract tests for `hostPid`, `launcherPid` and `mcpPid` in spawn.json, against
* real entry points (design §3.5 "hostPid, computed once at startup"; §8.1 tests 9a, 9b).
- * The unit cases of hostPidFrom live in parent-proof.contract.test.ts.
+ * The unit cases of hostPidFrom live in parent-session.contract.test.ts.
*
* The session is an interactive pane (the pane fake, marker mode, in a real headless magmux
* under the test's own CLAUDISH_PANE_ROOT; ported per architecture §20.2, every assertion
diff --git a/packages/cli/src/channel/parent-proof.contract.test.ts b/packages/cli/src/channel/parent-proof.contract.test.ts
deleted file mode 100644
index 81346f45..00000000
--- a/packages/cli/src/channel/parent-proof.contract.test.ts
+++ /dev/null
@@ -1,560 +0,0 @@
-// packages/cli/src/channel/parent-proof.contract.test.ts
-/**
- * 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 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.
- */
-import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { appendFileSync, mkdirSync, rmSync, utimesSync, writeFileSync } from "node:fs";
-import * as fsp from "node:fs/promises";
-import { homedir } from "node:os";
-import { join } from "node:path";
-import {
- type TempLayout,
- claudeId,
- fillerLine,
- makeTempLayout,
- sanitisedProjectName,
- transcriptLineWithToolUse,
-} from "../test-helpers/contract-records.js";
-import {
- CLAUDE_ID_RE,
- MAX_SUBAGENT_FILES,
- PROOF_DEADLINE_MS,
- PROOF_POLL_INTERVAL_MS,
- SUBAGENT_WINDOW_MS,
- TOOL_USE_ID_META_KEY,
- TRANSCRIPT_TAIL_BYTES,
- claudeConfigDir,
- hostPidFrom,
- parentSessionIdFrom,
- projectDirNameFor,
- proveCallingConversation,
- readHostSessionRecord,
-} from "./parent-proof.js";
-import type { ProofCandidate, ProofFs } from "./parent-proof.js";
-
-// INFERRED candidate shape (see header).
-function candidate(sessionId: string, cwd?: string): ProofCandidate {
- return (cwd === undefined ? { sessionId } : { sessionId, cwd }) as unknown as ProofCandidate;
-}
-
-let layout: TempLayout;
-let sleeps: number[];
-const recordSleep = async (ms: number): Promise<void> => {
- sleeps.push(ms);
-};
-
-beforeEach(() => {
- layout = makeTempLayout("proof");
- sleeps = [];
-});
-afterEach(() => layout.cleanup());
-
-const projectsDir = () => join(layout.configDir, "projects");
-
-function writeMainTranscript(project: string, sessionId: string, content: string): string {
- const dir = join(projectsDir(), project);
- mkdirSync(dir, { recursive: true });
- const path = join(dir, `${sessionId}.jsonl`);
- writeFileSync(path, content);
- return path;
-}
-
-function writeSubagentTranscript(
- project: string,
- parent: string,
- name: string,
- content: string,
- mtimeMs?: number
-): string {
- const dir = join(projectsDir(), project, parent, "subagents");
- mkdirSync(dir, { recursive: true });
- const path = join(dir, name);
- writeFileSync(path, content);
- if (mtimeMs !== undefined) utimesSync(path, mtimeMs / 1000, mtimeMs / 1000);
- return path;
-}
-
-/** Wrap every node:fs/promises function so the test can see what the proof touched. */
-function countingFs(): { fs: ProofFs; calls: Array<{ method: string; path: string }> } {
- const calls: Array<{ method: string; path: string }> = [];
- const wrapped: Record<string, unknown> = {};
- for (const [name, value] of Object.entries(fsp)) {
- wrapped[name] =
- typeof value === "function"
- ? (...args: unknown[]) => {
- calls.push({ method: name, path: String(args[0]) });
- return (value as (...a: unknown[]) => unknown).apply(fsp, args);
- }
- : value;
- }
- return { fs: wrapped as unknown as ProofFs, calls };
-}
-
-const toolUseId = () => `toolu_contract_${crypto.randomUUID().replaceAll("-", "")}`;
-
-describe("REQ-4 constants named by the contract carry the spec's values", () => {
- test("TOOL_USE_ID_META_KEY is the _meta key the dispatcher reads", () => {
- expect(TOOL_USE_ID_META_KEY).toBe("claudecode/toolUseId");
- });
-
- 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,
- 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([
- ["8 allowed chars", "abcd_-12", true],
- ["128 chars", "a".repeat(128), true],
- ["7 chars", "abcdefg", false],
- ["129 chars", "a".repeat(129), false],
- ["a space", "abcd efgh", false],
- ["a dot", "abcd.efgh", false],
- ["a slash", "abcd/efgh", false],
- ])("CLAUDE_ID_RE with %s → %p", (_label, id, ok) => {
- expect(CLAUDE_ID_RE.test(id)).toBe(ok);
- });
-});
-
-describe("REQ-3 hostPidFrom(env, ppid) picks the launcher branch only on an exact pair (§8.1 test 9)", () => {
- test("a matching launcher pair → hostPid is the launcher's parent, launcherPid is ppid", () => {
- expect(
- hostPidFrom({ CLAUDISH_LAUNCHER_PID: "5000", CLAUDISH_LAUNCHER_PPID: "4000" }, 5000)
- ).toEqual({
- hostPid: 4000,
- launcherPid: 5000,
- });
- });
-
- test.each([
- [
- "a pair whose CLAUDISH_LAUNCHER_PID is not ppid (leaked from an outer launcher)",
- { CLAUDISH_LAUNCHER_PID: "5001", CLAUDISH_LAUNCHER_PPID: "4000" },
- ],
- ["no pair", {}],
- ["only CLAUDISH_LAUNCHER_PID", { CLAUDISH_LAUNCHER_PID: "5000" }],
- ["a non-integer PPID", { CLAUDISH_LAUNCHER_PID: "5000", CLAUDISH_LAUNCHER_PPID: "abc" }],
- ["a fractional PPID", { CLAUDISH_LAUNCHER_PID: "5000", CLAUDISH_LAUNCHER_PPID: "12.5" }],
- ["a zero PPID", { CLAUDISH_LAUNCHER_PID: "5000", CLAUDISH_LAUNCHER_PPID: "0" }],
- ["a negative PPID", { CLAUDISH_LAUNCHER_PID: "5000", CLAUDISH_LAUNCHER_PPID: "-3" }],
- ["an empty PPID", { CLAUDISH_LAUNCHER_PID: "5000", CLAUDISH_LAUNCHER_PPID: "" }],
- ])("%s → { hostPid: ppid } with no launcherPid", (_label, env) => {
- const result = hostPidFrom(env as Record<string, string>, 5000) as {
- hostPid: number;
- launcherPid?: number;
- };
-
- expect(result.hostPid).toBe(5000);
- expect(result.launcherPid).toBeUndefined();
- });
-});
-
-describe("REQ-4 parentSessionIdFrom(env): the env candidate (§3.5 step 2)", () => {
- const good = "0f9e8d7c-1111-4222-8333-444455556666";
-
- test.each([
- ["a valid CLAUDE_CODE_SESSION_ID", { CLAUDE_CODE_SESSION_ID: good }, good],
- [
- "a valid id with an empty CLAUDE_CODE_CHILD_SESSION",
- { CLAUDE_CODE_SESSION_ID: good, CLAUDE_CODE_CHILD_SESSION: "" },
- good,
- ],
- [
- "CLAUDE_CODE_CHILD_SESSION=1 (not started by Claude Code directly)",
- { CLAUDE_CODE_SESSION_ID: good, CLAUDE_CODE_CHILD_SESSION: "1" },
- undefined,
- ],
- ["no CLAUDE_CODE_SESSION_ID", {}, undefined],
- ["an empty id", { CLAUDE_CODE_SESSION_ID: "" }, undefined],
- ["a 7-char id", { CLAUDE_CODE_SESSION_ID: "abcdefg" }, undefined],
- ["a 129-char id", { CLAUDE_CODE_SESSION_ID: "a".repeat(129) }, undefined],
- ["an id with a space", { CLAUDE_CODE_SESSION_ID: "abcd efgh" }, undefined],
- ])("%s → %p", (_label, env, expected) => {
- expect(parentSessionIdFrom(env as Record<string, string>) ?? undefined).toBe(expected);
- });
-});
-
-describe("REQ-4 readHostSessionRecord: the host's live session record (§3.5 step 2)", () => {
- const hostPid = 424242;
- const R = "host-record-session-0001";
-
- function writeHostRecord(pid: number, body: string): void {
- mkdirSync(join(layout.configDir, "sessions"), { recursive: true });
- writeFileSync(join(layout.configDir, "sessions", `${pid}.json`), body);
- }
-
- test("a record whose pid equals hostPid and whose sessionId is valid is used, with its cwd", async () => {
- writeHostRecord(
- hostPid,
- JSON.stringify({ pid: hostPid, sessionId: R, cwd: join(layout.root, "project") })
- );
-
- const record = await readHostSessionRecord({ configDir: layout.configDir, hostPid });
-
- expect(record).toMatchObject({ sessionId: R, cwd: join(layout.root, "project") });
- });
-
- test.each([
- ["its pid is not hostPid", () => JSON.stringify({ pid: hostPid + 1, sessionId: R })],
- ["it is not valid JSON (a write in progress)", () => `{"pid": ${hostPid}, "sessionId": "${R}"`],
- [
- "its sessionId does not match the id pattern",
- () => JSON.stringify({ pid: hostPid, sessionId: "short" }),
- ],
- ["it has no sessionId", () => JSON.stringify({ pid: hostPid })],
- ])("returns nothing when %s", async (_label, body) => {
- writeHostRecord(hostPid, body());
-
- const record = await readHostSessionRecord({ configDir: layout.configDir, hostPid });
-
- expect(record ?? undefined).toBeUndefined();
- });
-
- test("returns nothing when no record exists for hostPid", async () => {
- const record = await readHostSessionRecord({ configDir: layout.configDir, hostPid });
-
- expect(record ?? undefined).toBeUndefined();
- });
-});
-
-describe("REQ-6 claudeConfigDir follows CLAUDE_CONFIG_DIR, then HOME, then the OS home (amendment 1)", () => {
- function withEnv<T>(
- vars: Record<string, string | undefined>,
- fn: (env: Record<string, string | undefined>) => T
- ): T {
- const saved: Record<string, string | undefined> = {};
- for (const k of Object.keys(vars)) saved[k] = process.env[k];
- for (const [k, v] of Object.entries(vars)) {
- if (v === undefined) delete process.env[k];
- else process.env[k] = v;
- }
- try {
- // INFERRED: claudeConfigDir(env?) — pass the env and set process.env, so either shape works.
- return fn({ ...process.env });
- } finally {
- for (const [k, v] of Object.entries(saved)) {
- if (v === undefined) delete process.env[k];
- else process.env[k] = v;
- }
- }
- }
- const call = (env: Record<string, string | undefined>) =>
- (claudeConfigDir as unknown as (e?: unknown) => string)(env);
-
- test("CLAUDE_CONFIG_DIR wins when set", () => {
- expect(withEnv({ CLAUDE_CONFIG_DIR: layout.configDir, HOME: layout.home }, call)).toBe(
- layout.configDir
- );
- });
-
- test("without CLAUDE_CONFIG_DIR it is $HOME/.claude", () => {
- expect(withEnv({ CLAUDE_CONFIG_DIR: undefined, HOME: layout.home }, call)).toBe(
- join(layout.home, ".claude")
- );
- });
-
- test("with HOME empty it is the OS home directory's .claude", () => {
- expect(withEnv({ CLAUDE_CONFIG_DIR: undefined, HOME: "" }, call)).toBe(
- join(homedir(), ".claude")
- );
- });
-});
-
-describe("REQ-4 projectDirNameFor: every character outside [A-Za-z0-9] becomes '-'", () => {
- test.each([
- ["/Users/someone/.claude/worktrees/x", "-Users-someone--claude-worktrees-x"],
- ["/srv/my_app v2.1", "-srv-my-app-v2-1"],
- ])("%s → %s", (cwd, expected) => {
- expect(projectDirNameFor(cwd)).toBe(expected);
- });
-});
-
-describe("REQ-1/REQ-2/REQ-4 proveCallingConversation (§8.1 test 10)", () => {
- test("returns the candidate whose main transcript holds the quoted tool-use id", async () => {
- const E = claudeId("env");
- const T = toolUseId();
- writeMainTranscript("P", E, fillerLine(1) + transcriptLineWithToolUse(T) + fillerLine(2));
-
- const parent = await proveCallingConversation({
- toolUseId: T,
- candidates: [candidate(E)],
- configDir: layout.configDir,
- sleep: recordSleep,
- });
-
- expect(parent).toBe(E);
- expect(sleeps).toEqual([]);
- });
-
- test("returns the second candidate when the id is only in one of its fresh subagent transcripts", async () => {
- const E = claudeId("env");
- const R = claudeId("host");
- const T = toolUseId();
- writeMainTranscript("P", E, fillerLine(1));
- writeMainTranscript("Q", R, fillerLine(2));
- writeSubagentTranscript("Q", R, "a.jsonl", transcriptLineWithToolUse(T));
-
- const parent = await proveCallingConversation({
- toolUseId: T,
- candidates: [candidate(E), candidate(R)],
- configDir: layout.configDir,
- sleep: recordSleep,
- });
-
- expect(parent).toBe(R);
- });
-
- test("skips a candidate with no transcript anywhere and proves the other", async () => {
- const ghost = claudeId("ghost");
- const E = claudeId("env");
- const T = toolUseId();
- writeMainTranscript("P", E, transcriptLineWithToolUse(T));
-
- const parent = await proveCallingConversation({
- toolUseId: T,
- candidates: [candidate(ghost), candidate(E)],
- configDir: layout.configDir,
- sleep: recordSleep,
- });
-
- expect(parent).toBe(E);
- });
-
- 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));
-
- const parent = await proveCallingConversation({
- toolUseId: toolUseId(),
- candidates: [candidate(E)],
- configDir: layout.configDir,
- sleep: recordSleep,
- });
-
- expect(parent).toBeUndefined();
- expect(sleeps).toEqual(Array(20).fill(100));
- });
-
- 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));
- const appendDuringWait = async (ms: number) => {
- sleeps.push(ms);
- appendFileSync(path, transcriptLineWithToolUse(T));
- };
-
- const parent = await proveCallingConversation({
- toolUseId: T,
- candidates: [candidate(E)],
- configDir: layout.configDir,
- sleep: appendDuringWait,
- });
-
- expect(parent).toBe(E);
- expect(sleeps).toEqual([100]);
- });
-
- test("ignores an id that occurs only before the last 256 KB of the main transcript", async () => {
- const E = claudeId("env");
- const T = toolUseId();
- let padding = "";
- for (let i = 0; padding.length < 300 * 1024; i++) padding += fillerLine(i);
- writeMainTranscript("P", E, transcriptLineWithToolUse(T) + padding);
-
- const parent = await proveCallingConversation({
- toolUseId: T,
- candidates: [candidate(E)],
- configDir: layout.configDir,
- sleep: recordSleep,
- });
-
- expect(parent).toBeUndefined();
- });
-
- test("finds an id that sits inside the last 256 KB of a transcript larger than 256 KB", async () => {
- const E = claudeId("env");
- const T = toolUseId();
- let head = "";
- for (let i = 0; head.length < 300 * 1024; i++) head += fillerLine(i);
- let tail = "";
- for (let i = 0; tail.length < 200 * 1024; i++) tail += fillerLine(i);
- writeMainTranscript("P", E, head + transcriptLineWithToolUse(T) + tail);
-
- const parent = await proveCallingConversation({
- toolUseId: T,
- candidates: [candidate(E)],
- configDir: layout.configDir,
- sleep: recordSleep,
- });
-
- expect(parent).toBe(E);
- });
-
- test("matches the quoted id exactly, not as a prefix of a longer id", async () => {
- const E = claudeId("env");
- const T = toolUseId();
- writeMainTranscript("P", E, transcriptLineWithToolUse(`${T}extra`));
-
- const parent = await proveCallingConversation({
- toolUseId: T,
- candidates: [candidate(E)],
- configDir: layout.configDir,
- sleep: recordSleep,
- });
-
- expect(parent).toBeUndefined();
- });
-
- test.each([
- ["a 7-char id", "toolu_1"],
- ["an id with a space", "toolu has space"],
- ["an id with a quote", 'toolu_"quoted"'],
- ["a 129-char id", `t${"a".repeat(128)}`],
- ["an empty id", ""],
- ["no id at all", undefined],
- ])("%s → undefined, and no file is touched", async (_label, badId) => {
- const E = claudeId("env");
- writeMainTranscript("P", E, transcriptLineWithToolUse(String(badId)));
- const { fs, calls } = countingFs();
-
- const parent = await proveCallingConversation({
- toolUseId: badId as string,
- candidates: [candidate(E)],
- configDir: layout.configDir,
- fs,
- sleep: recordSleep,
- });
-
- expect(parent).toBeUndefined();
- expect(calls).toEqual([]);
- });
-
- test("ignores a subagent transcript last modified more than 10 minutes ago", async () => {
- const R = claudeId("host");
- const T = toolUseId();
- writeMainTranscript("Q", R, fillerLine(1));
- writeSubagentTranscript(
- "Q",
- R,
- "old.jsonl",
- transcriptLineWithToolUse(T),
- Date.now() - 11 * 60 * 1000
- );
-
- const parent = await proveCallingConversation({
- toolUseId: T,
- candidates: [candidate(R)],
- configDir: layout.configDir,
- sleep: recordSleep,
- });
-
- expect(parent).toBeUndefined();
- });
-
- test.each([
- [32, "found"],
- [33, "not found"],
- ])(
- "with %i fresh subagent files and the id only in the oldest, it is %s (newest first, at most 32)",
- async (count, outcome) => {
- const R = claudeId("host");
- const T = toolUseId();
- writeMainTranscript("Q", R, fillerLine(1));
- const now = Date.now();
- for (let i = 0; i < count; i++) {
- const isOldest = i === 0;
- writeSubagentTranscript(
- "Q",
- R,
- `s${String(i).padStart(2, "0")}.jsonl`,
- isOldest ? transcriptLineWithToolUse(T) : fillerLine(i),
- now - 5 * 60 * 1000 + i * 1000
- );
- }
-
- const parent = await proveCallingConversation({
- toolUseId: T,
- candidates: [candidate(R)],
- configDir: layout.configDir,
- sleep: recordSleep,
- });
-
- expect(parent).toBe(outcome === "found" ? R : undefined);
- }
- );
-
- test("fast path: a candidate with a cwd is found under the sanitised-cwd directory with no listing of projects/", async () => {
- const R = claudeId("host");
- const T = toolUseId();
- const cwd = join(layout.root, "work tree", ".claude", "wt_1");
- writeMainTranscript(sanitisedProjectName(cwd), R, transcriptLineWithToolUse(T));
- writeMainTranscript("unrelated-project", claudeId("other"), fillerLine(1));
- const { fs, calls } = countingFs();
-
- const parent = await proveCallingConversation({
- toolUseId: T,
- candidates: [candidate(R, cwd)],
- configDir: layout.configDir,
- fs,
- sleep: recordSleep,
- });
-
- expect(parent).toBe(R);
- const listings = calls.filter(
- (c) =>
- (c.method === "readdir" || c.method === "opendir") &&
- c.path.replace(/\/+$/, "") === projectsDir()
- );
- expect(listings).toEqual([]);
- });
-
- test("a cwd that maps to no directory falls back to listing projects/ and still finds the transcript", async () => {
- const R = claudeId("host");
- const T = toolUseId();
- writeMainTranscript("renamed-by-a-future-claude-code", R, transcriptLineWithToolUse(T));
-
- const parent = await proveCallingConversation({
- toolUseId: T,
- candidates: [candidate(R, join(layout.root, "no", "such", "project"))],
- configDir: layout.configDir,
- sleep: recordSleep,
- });
-
- expect(parent).toBe(R);
- });
-
- test("REQ-5 an unproven call caches no project directory: the next call finds the transcript where it now lives", async () => {
- const C = claudeId("moving");
- const stale = writeMainTranscript("P-stale", C, fillerLine(1));
-
- const first = await proveCallingConversation({
- toolUseId: toolUseId(),
- candidates: [candidate(C)],
- configDir: layout.configDir,
- sleep: recordSleep,
- });
- rmSync(stale);
- const T = toolUseId();
- writeMainTranscript("Q-current", C, transcriptLineWithToolUse(T));
- const second = await proveCallingConversation({
- toolUseId: T,
- candidates: [candidate(C)],
- configDir: layout.configDir,
- sleep: recordSleep,
- });
-
- expect(first).toBeUndefined();
- expect(second).toBe(C);
- });
-});
diff --git a/packages/cli/src/channel/parent-proof.test.ts b/packages/cli/src/channel/parent-proof.test.ts
deleted file mode 100644
index 10077627..00000000
--- a/packages/cli/src/channel/parent-proof.test.ts
+++ /dev/null
@@ -1,236 +0,0 @@
-/**
- * The parent proof's project-directory cache must never hold a wrong answer.
- *
- * A wrong entry lives for the MCP server's whole life: every later call for
- * that conversation searches the wrong place and `parentClaudeSessionId` stays
- * absent, even for transcripts that hold the tool-use id. Two ways in: a
- * DIRECTORY named `<id>.jsonl` (a bare `stat` is true for it), and a cached
- * directory that no longer holds the transcript.
- */
-
-import { describe, expect, test } from "bun:test";
-import { join } from "node:path";
-
-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");
-const SESSION = "11111111-2222-3333-4444-555555555555";
-const TOOL_USE = "toolu_01ABCDEFGHJKLMNP";
-
-type Node = { kind: "dir" } | { kind: "file"; content: string; mtimeMs: number };
-
-/** An in-memory filesystem: absolute path → node. Parents are implied by paths. */
-function memoryFs(nodes: Map<string, Node>): ProofFs {
- const get = (path: string): Node => {
- const node = nodes.get(path);
- if (node) return node;
- // A path that is a prefix of another is an implied directory.
- for (const key of nodes.keys()) if (key.startsWith(`${path}/`)) return { kind: "dir" };
- throw Object.assign(new Error(`ENOENT: ${path}`), { code: "ENOENT" });
- };
- return {
- readFile: async (path) => {
- const node = get(path);
- if (node.kind !== "file") throw new Error(`EISDIR: ${path}`);
- return node.content;
- },
- readdir: async (path) => {
- if (get(path).kind !== "dir") throw new Error(`ENOTDIR: ${path}`);
- const names = new Set<string>();
- for (const key of nodes.keys()) {
- if (key.startsWith(`${path}/`)) names.add(key.slice(path.length + 1).split("/")[0]);
- }
- return [...names].sort();
- },
- stat: async (path) => {
- const node = get(path);
- return {
- mtimeMs: node.kind === "file" ? node.mtimeMs : 0,
- size: node.kind === "file" ? Buffer.byteLength(node.content) : 0,
- isDirectory: () => node.kind === "dir",
- isFile: () => node.kind === "file",
- };
- },
- open: async (path) => {
- const node = get(path);
- if (node.kind !== "file") throw new Error(`EISDIR: ${path}`);
- const bytes = Buffer.from(node.content, "utf-8");
- return {
- read: async (buffer, offset, length, position) => {
- const n = bytes.copy(buffer, offset, position, position + length);
- return { bytesRead: n };
- },
- close: async () => {},
- };
- },
- };
-}
-
-const transcript = (): Node => ({
- kind: "file",
- content: `{"type":"assistant","message":{"content":[{"type":"tool_use","id":"${TOOL_USE}"}]}}\n`,
- mtimeMs: 0,
-});
-
-function prove(fs: ProofFs, cache: ProjectDirCache, cwd?: string): Promise<string | undefined> {
- return proveCallingConversation({
- toolUseId: TOOL_USE,
- candidates: [{ sessionId: SESSION, ...(cwd ? { cwd } : {}) }],
- configDir: CONFIG,
- fs,
- cache,
- sleep: async () => {},
- now: () => 0,
- });
-}
-
-describe("parent proof project-directory cache", () => {
- test("a directory named <id>.jsonl is not the transcript (listing path)", async () => {
- // `-a` lists before `-b`, so a bare existence check stops at the decoy.
- const nodes = new Map<string, Node>([
- [join(PROJECTS, "-a", `${SESSION}.jsonl`, "x"), { kind: "file", content: "", mtimeMs: 0 }],
- [join(PROJECTS, "-b", `${SESSION}.jsonl`), transcript()],
- ]);
- const cache: ProjectDirCache = new Map();
- expect(await prove(memoryFs(nodes), cache)).toBe(SESSION);
- expect([...cache.values()]).toEqual([join(PROJECTS, "-b")]);
- });
-
- test("a directory named <id>.jsonl on the fast path falls through to the listing", async () => {
- const cwd = "/work/repo";
- const nodes = new Map<string, Node>([
- [
- join(PROJECTS, "-work-repo", `${SESSION}.jsonl`, "x"),
- { kind: "file", content: "", mtimeMs: 0 },
- ],
- [join(PROJECTS, "-z", `${SESSION}.jsonl`), transcript()],
- ]);
- const cache: ProjectDirCache = new Map();
- expect(await prove(memoryFs(nodes), cache, cwd)).toBe(SESSION);
- });
-
- test("a fast-path hit is not cached", async () => {
- const cwd = "/work/repo";
- const nodes = new Map<string, Node>([
- [join(PROJECTS, "-work-repo", `${SESSION}.jsonl`), transcript()],
- ]);
- const cache: ProjectDirCache = new Map();
- expect(await prove(memoryFs(nodes), cache, cwd)).toBe(SESSION);
- expect(cache.size).toBe(0);
- });
-
- test("a cached directory that lost the transcript is resolved again", async () => {
- const nodes = new Map<string, Node>([
- [join(PROJECTS, "-old", `${SESSION}.jsonl`), transcript()],
- ]);
- const fs = memoryFs(nodes);
- const cache: ProjectDirCache = new Map();
- expect(await prove(fs, cache)).toBe(SESSION);
-
- // The conversation's transcript now lives in another project directory.
- nodes.delete(join(PROJECTS, "-old", `${SESSION}.jsonl`));
- nodes.set(join(PROJECTS, "-old", "other.jsonl"), { kind: "file", content: "", mtimeMs: 0 });
- nodes.set(join(PROJECTS, "-new", `${SESSION}.jsonl`), transcript());
-
- expect(await prove(fs, cache)).toBe(SESSION);
- 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.ts
deleted file mode 100644
index e7ef4d95..00000000
--- a/packages/cli/src/channel/parent-proof.ts
+++ /dev/null
@@ -1,491 +0,0 @@
-// ─── Host pid and the parent proof ───────────────────────────────────────────
-//
-// Two facts a session or team record carries so an observer outside this
-// process — the magus `claudish` plugin monitor — can tell which Claude Code
-// window started a run:
-//
-// * `hostPid`: the Claude Code process that launched this MCP server. A
-// structural fact, read once at startup from the process tree we were given
-// (our parent, or our launcher's parent). Never searched for.
-// * `parentClaudeSessionId`: the Claude Code CONVERSATION that issued the
-// tool call. Recorded only when PROVEN per call: the calling tool-use id is
-// found in that conversation's transcript. Otherwise absent — never the id
-// the server happened to start with, which goes stale on /clear, on a
-// resume, and whenever two windows share one conversation.
-//
-// Why a hit is proof: a tool-use id is unique and is written only into the
-// transcript of the conversation (or of a subagent of it) that issued the call.
-// Every source below is used to CONFIRM, and every failure — no `_meta`, an
-// unreadable record, a transcript layout a future Claude Code changed —
-// degrades to "absent", never to a wrong answer.
-
-import * as fsPromises from "node:fs/promises";
-import { join } from "node:path";
-
-import { userHomeFrom } from "./home-dir.js";
-
-/** What a Claude Code session id or tool-use id may look like. Also the path-safety gate. */
-export const CLAUDE_ID_RE = /^[A-Za-z0-9_-]{8,128}$/;
-
-/** `_meta` key Claude Code puts the calling tool-use id under. */
-export const TOOL_USE_ID_META_KEY = "claudecode/toolUseId";
-
-/** Bytes of a main transcript searched for the tool-use id, from its end. */
-export const TRANSCRIPT_TAIL_BYTES = 256 * 1024;
-
-/** Subagent transcripts are searched only when modified this recently. */
-export const SUBAGENT_WINDOW_MS = 10 * 60_000;
-
-/** At most this many subagent transcripts are searched, newest first. */
-export const MAX_SUBAGENT_FILES = 32;
-
-/**
- * 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 ─────────────────────────────────────────────────────────────────
-
-export interface HostPids {
- /** The Claude Code process that launched this MCP server. */
- hostPid: number;
- /**
- * The npm `node` launcher (`bin/claudish.cjs`) between Claude Code and this
- * process, when there is one. Present exactly when `hostPid` came from the
- * launcher branch, so every record says which branch produced it.
- */
- launcherPid?: number;
-}
-
-function positiveInt(value: string | undefined): number | undefined {
- if (value === undefined || !/^[1-9][0-9]*$/.test(value)) return undefined;
- const n = Number(value);
- return Number.isSafeInteger(n) ? n : undefined;
-}
-
-/**
- * The host pid, from the environment and our own parent pid. Pure.
- *
- * - npm / bun global install: Claude Code → `node` launcher → `bun` (us). The
- * launcher sets `CLAUDISH_LAUNCHER_PID` (itself) and `CLAUDISH_LAUNCHER_PPID`
- * (its parent). When `CLAUDISH_LAUNCHER_PID` is OUR parent, the host is the
- * launcher's parent.
- * - compiled binary, or `bun src/index.ts`: our parent is the host.
- *
- * The pair check makes a leaked pair inert: a nested claudish that inherits an
- * outer launcher's variables sees `CLAUDISH_LAUNCHER_PID` ≠ its own parent and
- * ignores them. No `ps`, no walk.
- */
-export function hostPidFrom(env: Record<string, string | undefined>, ppid: number): HostPids {
- const launcherPpid = positiveInt(env.CLAUDISH_LAUNCHER_PPID);
- if (
- env.CLAUDISH_LAUNCHER_PID === String(ppid) &&
- launcherPpid !== undefined &&
- launcherPpid !== ppid
- ) {
- return { hostPid: launcherPpid, launcherPid: ppid };
- }
- return { hostPid: ppid };
-}
-
-// ─── Candidates ──────────────────────────────────────────────────────────────
-
-/**
- * The conversation id this server was started with, when it can be a
- * candidate at all.
- *
- * `CLAUDE_CODE_SESSION_ID` when it is well formed and `CLAUDE_CODE_CHILD_SESSION`
- * is empty. Claude Code sets the latter for Bash-tool children and monitors and
- * strips it from the stdio MCP servers it launches, so its presence means this
- * server was not started by Claude Code directly. A candidate only: it is
- * believed when the proof finds the tool-use id in its transcript.
- */
-export function parentSessionIdFrom(env: Record<string, string | undefined>): string | undefined {
- const id = env.CLAUDE_CODE_SESSION_ID;
- if (id === undefined || !CLAUDE_ID_RE.test(id)) return undefined;
- if (env.CLAUDE_CODE_CHILD_SESSION) return undefined;
- return id;
-}
-
-/**
- * `CLAUDE_CONFIG_DIR`, else `<home>/.claude`, with `<home>` resolved by the
- * same `$HOME`-first rule as the sessions directory (home-dir.ts): Claude Code
- * follows `$HOME`, and Bun's `os.homedir()` does not.
- */
-export function claudeConfigDir(env: Record<string, string | undefined>): string {
- const fromEnv = env.CLAUDE_CONFIG_DIR;
- return fromEnv && fromEnv.length > 0 ? fromEnv : join(userHomeFrom(env), ".claude");
-}
-
-/** The subset of `node:fs/promises` the proof uses. Injectable for tests. */
-export interface ProofFs {
- readFile: (path: string, encoding: "utf-8") => Promise<string>;
- readdir: (path: string) => Promise<string[]>;
- stat: (
- path: string
- ) => Promise<{ mtimeMs: number; size: number; isDirectory(): boolean; isFile(): boolean }>;
- open: (
- path: string,
- flags: "r"
- ) => Promise<{
- read: (
- buffer: Uint8Array,
- offset: number,
- length: number,
- position: number
- ) => Promise<{ bytesRead: number }>;
- close: () => Promise<void>;
- }>;
-}
-
-const defaultFs: ProofFs = {
- readFile: (path, encoding) => fsPromises.readFile(path, encoding),
- readdir: (path) => fsPromises.readdir(path),
- stat: (path) => fsPromises.stat(path),
- open: (path, flags) => fsPromises.open(path, flags),
-};
-
-/** The host's live session record, as far as the proof trusts it. */
-export interface HostSessionRecord {
- sessionId: string;
- /** The host's working directory, when the record names one. Feeds the fast path. */
- cwd?: string;
-}
-
-/**
- * `<configDir>/sessions/<hostPid>.json`, the record Claude Code writes at
- * startup and rewrites on every session switch (so it is current after
- * `/clear`). Used only when it parses, its `pid === hostPid`, and its
- * `sessionId` is well formed; anything else is `undefined`. Never throws.
- */
-export async function readHostSessionRecord(opts: {
- configDir: string;
- hostPid: number;
- fs?: ProofFs;
-}): Promise<HostSessionRecord | undefined> {
- const fs = opts.fs ?? defaultFs;
- try {
- const raw = await fs.readFile(
- join(opts.configDir, "sessions", `${opts.hostPid}.json`),
- "utf-8"
- );
- const parsed: unknown = JSON.parse(raw);
- if (!parsed || typeof parsed !== "object") return undefined;
- const rec = parsed as { pid?: unknown; sessionId?: unknown; cwd?: unknown };
- if (rec.pid !== opts.hostPid) return undefined;
- if (typeof rec.sessionId !== "string" || !CLAUDE_ID_RE.test(rec.sessionId)) return undefined;
- return {
- sessionId: rec.sessionId,
- ...(typeof rec.cwd === "string" && rec.cwd.length > 0 ? { cwd: rec.cwd } : {}),
- };
- } catch {
- return undefined;
- }
-}
-
-/** One conversation the proof may confirm. */
-export interface ProofCandidate {
- sessionId: string;
- /** Working directory whose project directory is tried first (the fast path). */
- cwd?: string;
-}
-
-/**
- * The candidates for one call, deduplicated, at most two: the environment's
- * session id, then the host session record's. The host record's `cwd` is
- * attached to both, since it names the project the host runs in.
- */
-export async function gatherProofCandidates(opts: {
- env: Record<string, string | undefined>;
- hostPid: number;
- configDir: string;
- fs?: ProofFs;
-}): Promise<ProofCandidate[]> {
- const record = await readHostSessionRecord({
- configDir: opts.configDir,
- hostPid: opts.hostPid,
- fs: opts.fs,
- });
- const cwd = record?.cwd;
- const ids = [parentSessionIdFrom(opts.env), record?.sessionId].filter(
- (id): id is string => id !== undefined
- );
- return [...new Set(ids)].map((sessionId) => ({ sessionId, ...(cwd ? { cwd } : {}) }));
-}
-
-// ─── The proof ───────────────────────────────────────────────────────────────
-
-/** Claude Code keeps a project directory name to this many slug characters. */
-export const PROJECT_DIR_SLUG_MAX = 200;
-
-/** Claude Code's 32-bit string hash (`(h << 5) - h + charCode`, per UTF-16 unit). */
-function claudeCodeStringHash(s: string): number {
- let h = 0;
- for (let i = 0; i < s.length; i++) h = ((h << 5) - h + s.charCodeAt(i)) | 0;
- return h;
-}
-
-/**
- * Claude Code's project directory name for a cwd: every character outside
- * `[A-Za-z0-9]` becomes `-` (so `/.claude/` becomes `--claude-`). A slug longer than
- * 200 characters is cut to 200 and suffixed `-<base36 |hash(cwd)|>`, the hash taken
- * over the WHOLE path, not the slug. Read from Claude Code 2.1.291's own bundle
- * (`k(e)=e.replace(/[^a-zA-Z0-9]/g,"-")`, `eI(e)` truncates at `Rle=200` and appends
- * `Le(e)=Math.abs(hash(e)).toString(36)`) and MEASURED: a live 2.1.291 run in a
- * 259-character cwd wrote `<200 slug chars>-g32rlu`, which this function reproduces.
- * Used as the fast path of the proof (a future rule change degrades to the directory
- * listing) and, through `slugForPath`, for every transcript path claudish derives.
- */
-export function projectDirNameFor(cwd: string): string {
- const slug = cwd.replace(/[^A-Za-z0-9]/g, "-");
- if (slug.length <= PROJECT_DIR_SLUG_MAX) return slug;
- return `${slug.slice(0, PROJECT_DIR_SLUG_MAX)}-${Math.abs(claudeCodeStringHash(cwd)).toString(36)}`;
-}
-
-/**
- * `<configDir>\0<candidate>` → the project directory the LISTING found holding
- * `<candidate>.jsonl`, so the listing runs about once per candidate per server
- * life. The fast path is never cached (it is one `stat`), and an entry whose
- * transcript is gone is dropped and resolved again: a wrong entry would
- * otherwise answer every later call for the server's whole life.
- */
-export type ProjectDirCache = Map<string, string>;
-
-const serverProjectDirCache: ProjectDirCache = new Map();
-
-/** A regular file at `path`. A directory that happens to carry the name is not a transcript. */
-async function isTranscriptFile(fs: ProofFs, path: string): Promise<boolean> {
- try {
- return (await fs.stat(path)).isFile();
- } catch {
- return false;
- }
-}
-
-async function findProjectDir(
- fs: ProofFs,
- configDir: string,
- candidate: ProofCandidate,
- cache: ProjectDirCache
-): Promise<string | undefined> {
- const cacheKey = `${configDir}\0${candidate.sessionId}`;
- const projectsDir = join(configDir, "projects");
- const fileName = `${candidate.sessionId}.jsonl`;
-
- const cached = cache.get(cacheKey);
- if (cached !== undefined) {
- if (await isTranscriptFile(fs, join(cached, fileName))) return cached;
- cache.delete(cacheKey);
- }
-
- if (candidate.cwd) {
- const fast = join(projectsDir, projectDirNameFor(candidate.cwd));
- if (await isTranscriptFile(fs, join(fast, fileName))) return fast;
- }
-
- let names: string[];
- try {
- names = await fs.readdir(projectsDir);
- } catch {
- return undefined;
- }
- for (const name of names) {
- const dir = join(projectsDir, name);
- if (await isTranscriptFile(fs, join(dir, fileName))) {
- cache.set(cacheKey, dir);
- return dir;
- }
- }
- return undefined;
-}
-
-/** Whether the last `TRANSCRIPT_TAIL_BYTES` of `path` contain `needle`. */
-async function tailContains(fs: ProofFs, path: string, needle: Buffer): Promise<boolean> {
- let handle: Awaited<ReturnType<ProofFs["open"]>> | undefined;
- try {
- const { size } = await fs.stat(path);
- const length = Math.min(size, TRANSCRIPT_TAIL_BYTES);
- if (length < needle.length) return false;
- const buffer = Buffer.alloc(length);
- handle = await fs.open(path, "r");
- const { bytesRead } = await handle.read(buffer, 0, length, size - length);
- return buffer.subarray(0, bytesRead).includes(needle);
- } catch {
- return false;
- } finally {
- await handle?.close().catch(() => {});
- }
-}
-
-/** `<project>/<candidate>/subagents/*.jsonl` modified in the window, newest first, capped. */
-async function recentSubagentTranscripts(
- fs: ProofFs,
- projectDir: string,
- candidateId: string,
- nowMs: number
-): Promise<string[]> {
- const dir = join(projectDir, candidateId, "subagents");
- let names: string[];
- try {
- names = await fs.readdir(dir);
- } catch {
- return [];
- }
- const recent: { path: string; mtimeMs: number }[] = [];
- for (const name of names) {
- if (!name.endsWith(".jsonl")) continue;
- const path = join(dir, name);
- try {
- const { mtimeMs } = await fs.stat(path);
- if (nowMs - mtimeMs <= SUBAGENT_WINDOW_MS) recent.push({ path, mtimeMs });
- } catch {
- /* gone between readdir and stat */
- }
- }
- recent.sort((a, b) => b.mtimeMs - a.mtimeMs);
- return recent.slice(0, MAX_SUBAGENT_FILES).map((f) => f.path);
-}
-
-async function candidateHolds(
- fs: ProofFs,
- configDir: string,
- candidate: ProofCandidate,
- needle: Buffer,
- nowMs: number,
- cache: ProjectDirCache
-): Promise<boolean> {
- const projectDir = await findProjectDir(fs, configDir, candidate, cache);
- if (projectDir === undefined) return false;
- if (await tailContains(fs, join(projectDir, `${candidate.sessionId}.jsonl`), needle)) {
- return true;
- }
- for (const path of await recentSubagentTranscripts(fs, projectDir, candidate.sessionId, nowMs)) {
- if (await tailContains(fs, path, needle)) return true;
- }
- return false;
-}
-
-export interface ProveCallingConversationOptions {
- /** The calling tool-use id, from the request `_meta`. Anything malformed → `undefined`, no read. */
- toolUseId: unknown;
- /** At most two are used, after deduplication. A bare string is a candidate with no `cwd`. */
- candidates: readonly (ProofCandidate | string)[];
- /** Claude Code's config directory (`claudeConfigDir(env)`). */
- configDir: string;
- /** Clock for the subagent recency window and the deadline. Default `Date.now`. */
- now?: () => number;
- /** Injected filesystem. Default `node:fs/promises`. */
- fs?: ProofFs;
- /** 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;
-}
-
-/**
- * The conversation whose transcript holds the calling tool-use id, or
- * `undefined`. Asynchronous throughout, so the MCP process keeps pumping every
- * live session while one call proves. Never throws.
- *
- * 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 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
-): Promise<string | undefined> {
- const { toolUseId } = opts;
- if (typeof toolUseId !== "string" || !CLAUDE_ID_RE.test(toolUseId)) return undefined;
- const candidates = normaliseCandidates(opts.candidates);
- if (candidates.length === 0) return undefined;
-
- const fs = opts.fs ?? defaultFs;
- const now = opts.now ?? Date.now;
- const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
- const cache = opts.cache ?? serverProjectDirCache;
- const needle = Buffer.from(`"${toolUseId}"`, "utf-8");
-
- const look = async (): Promise<string | undefined> => {
- for (const candidate of candidates) {
- if (await candidateHolds(fs, opts.configDir, candidate, needle, now(), cache)) {
- return candidate.sessionId;
- }
- }
- return undefined;
- };
-
- try {
- 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;
- }
-}
-
-/**
- * Well-formed, deduplicated, at most two. The id becomes a path segment, and
- * the pattern is what keeps it one.
- */
-function normaliseCandidates(raw: readonly (ProofCandidate | string)[]): ProofCandidate[] {
- const out: ProofCandidate[] = [];
- for (const entry of raw) {
- const candidate = typeof entry === "string" ? { sessionId: entry } : entry;
- if (!CLAUDE_ID_RE.test(candidate.sessionId)) continue;
- if (out.some((c) => c.sessionId === candidate.sessionId)) continue;
- out.push(candidate);
- if (out.length === 2) break;
- }
- return out;
-}
-
-/**
- * The whole per-call proof as the MCP handlers run it: gather the candidates
- * for this host, then prove. `undefined` whenever nothing is proven.
- */
-export async function proveParentForCall(opts: {
- toolUseId: unknown;
- hostPid: number;
- env?: Record<string, string | undefined>;
- fs?: ProofFs;
-}): Promise<string | undefined> {
- if (typeof opts.toolUseId !== "string" || !CLAUDE_ID_RE.test(opts.toolUseId)) return undefined;
- const env = opts.env ?? process.env;
- const configDir = claudeConfigDir(env);
- try {
- const candidates = await gatherProofCandidates({
- env,
- hostPid: opts.hostPid,
- configDir,
- fs: opts.fs,
- });
- return await proveCallingConversation({
- toolUseId: opts.toolUseId,
- candidates,
- configDir,
- fs: opts.fs,
- });
- } catch {
- return undefined;
- }
-}
diff --git a/packages/cli/src/channel/parent-session.contract.test.ts b/packages/cli/src/channel/parent-session.contract.test.ts
new file mode 100644
index 00000000..5b26bce4
--- /dev/null
+++ b/packages/cli/src/channel/parent-session.contract.test.ts
@@ -0,0 +1,228 @@
+// packages/cli/src/channel/parent-session.contract.test.ts
+/**
+ * Contract tests for channel/parent-session.ts: `hostPid`, and the `parentClaudeSessionId` a
+ * call records.
+ *
+ * The parent contract, as measured on Claude Code 2.1.290: the host session record
+ * `<configDir>/sessions/<hostPid>.json` carries the window's LIVE conversation (it changes on
+ * `/clear` and back on `/resume`), while `CLAUDE_CODE_SESSION_ID` is the id the server started
+ * with. So: record present → its id; record missing → the env id; neither → absent; and each
+ * call reads the record at its own time. Every case runs over a synthetic Claude config dir in
+ * a temp directory.
+ */
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+import { type TempLayout, claudeId, makeTempLayout } from "../test-helpers/contract-records.js";
+import {
+ CLAUDE_ID_RE,
+ claudeConfigDir,
+ hostPidFrom,
+ parentSessionForCall,
+ parentSessionIdFrom,
+ readHostSessionRecord,
+} from "./parent-session.js";
+
+let layout: TempLayout;
+
+beforeEach(() => {
+ layout = makeTempLayout("parent");
+});
+afterEach(() => layout.cleanup());
+
+function writeHostRecord(pid: number, body: string): string {
+ mkdirSync(join(layout.configDir, "sessions"), { recursive: true });
+ const path = join(layout.configDir, "sessions", `${pid}.json`);
+ writeFileSync(path, body);
+ return path;
+}
+
+describe("CLAUDE_ID_RE is the id shape and the path-safety gate", () => {
+ test.each([
+ ["8 allowed chars", "abcd_-12", true],
+ ["128 chars", "a".repeat(128), true],
+ ["7 chars", "abcdefg", false],
+ ["129 chars", "a".repeat(129), false],
+ ["a space", "abcd efgh", false],
+ ["a dot", "abcd.efgh", false],
+ ["a slash", "abcd/efgh", false],
+ ])("CLAUDE_ID_RE with %s → %p", (_label, id, ok) => {
+ expect(CLAUDE_ID_RE.test(id)).toBe(ok);
+ });
+});
+
+describe("REQ-3 hostPidFrom(env, ppid) picks the launcher branch only on an exact pair (§8.1 test 9)", () => {
+ test("a matching launcher pair → hostPid is the launcher's parent, launcherPid is ppid", () => {
+ expect(
+ hostPidFrom({ CLAUDISH_LAUNCHER_PID: "5000", CLAUDISH_LAUNCHER_PPID: "4000" }, 5000)
+ ).toEqual({
+ hostPid: 4000,
+ launcherPid: 5000,
+ });
+ });
+
+ test.each([
+ [
+ "a pair whose CLAUDISH_LAUNCHER_PID is not ppid (leaked from an outer launcher)",
+ { CLAUDISH_LAUNCHER_PID: "5001", CLAUDISH_LAUNCHER_PPID: "4000" },
+ ],
+ ["no pair", {}],
+ ["only CLAUDISH_LAUNCHER_PID", { CLAUDISH_LAUNCHER_PID: "5000" }],
+ ["a non-integer PPID", { CLAUDISH_LAUNCHER_PID: "5000", CLAUDISH_LAUNCHER_PPID: "abc" }],
+ ["a fractional PPID", { CLAUDISH_LAUNCHER_PID: "5000", CLAUDISH_LAUNCHER_PPID: "12.5" }],
+ ["a zero PPID", { CLAUDISH_LAUNCHER_PID: "5000", CLAUDISH_LAUNCHER_PPID: "0" }],
+ ["a negative PPID", { CLAUDISH_LAUNCHER_PID: "5000", CLAUDISH_LAUNCHER_PPID: "-3" }],
+ ["an empty PPID", { CLAUDISH_LAUNCHER_PID: "5000", CLAUDISH_LAUNCHER_PPID: "" }],
+ ])("%s → { hostPid: ppid } with no launcherPid", (_label, env) => {
+ const result = hostPidFrom(env as Record<string, string>, 5000);
+
+ expect(result.hostPid).toBe(5000);
+ expect(result.launcherPid).toBeUndefined();
+ });
+});
+
+describe("parentSessionIdFrom(env): the environment's id, the fallback", () => {
+ const good = "0f9e8d7c-1111-4222-8333-444455556666";
+
+ test.each([
+ ["a valid CLAUDE_CODE_SESSION_ID", { CLAUDE_CODE_SESSION_ID: good }, good],
+ [
+ "a valid id with an empty CLAUDE_CODE_CHILD_SESSION",
+ { CLAUDE_CODE_SESSION_ID: good, CLAUDE_CODE_CHILD_SESSION: "" },
+ good,
+ ],
+ [
+ "CLAUDE_CODE_CHILD_SESSION=1 (not started by Claude Code directly)",
+ { CLAUDE_CODE_SESSION_ID: good, CLAUDE_CODE_CHILD_SESSION: "1" },
+ undefined,
+ ],
+ ["no CLAUDE_CODE_SESSION_ID", {}, undefined],
+ ["an empty id", { CLAUDE_CODE_SESSION_ID: "" }, undefined],
+ ["a 7-char id", { CLAUDE_CODE_SESSION_ID: "abcdefg" }, undefined],
+ ["a 129-char id", { CLAUDE_CODE_SESSION_ID: "a".repeat(129) }, undefined],
+ ["an id with a space", { CLAUDE_CODE_SESSION_ID: "abcd efgh" }, undefined],
+ ])("%s → %p", (_label, env, expected) => {
+ expect(parentSessionIdFrom(env as Record<string, string>)).toBe(expected);
+ });
+});
+
+describe("readHostSessionRecord: the host's live session record", () => {
+ const hostPid = 424242;
+ const R = "host-record-session-0001";
+
+ test("a record whose pid equals hostPid and whose sessionId is valid is used", async () => {
+ writeHostRecord(
+ hostPid,
+ JSON.stringify({ pid: hostPid, sessionId: R, cwd: join(layout.root, "project") })
+ );
+
+ const record = await readHostSessionRecord({ configDir: layout.configDir, hostPid });
+
+ expect(record).toEqual({ sessionId: R });
+ });
+
+ test.each([
+ ["its pid is not hostPid", () => JSON.stringify({ pid: hostPid + 1, sessionId: R })],
+ ["it is not valid JSON (a write in progress)", () => `{"pid": ${hostPid}, "sessionId": "${R}"`],
+ [
+ "its sessionId does not match the id pattern",
+ () => JSON.stringify({ pid: hostPid, sessionId: "short" }),
+ ],
+ ["it has no sessionId", () => JSON.stringify({ pid: hostPid })],
+ ])("returns nothing when %s", async (_label, body) => {
+ writeHostRecord(hostPid, body());
+
+ const record = await readHostSessionRecord({ configDir: layout.configDir, hostPid });
+
+ expect(record).toBeUndefined();
+ });
+
+ test("returns nothing when no record exists for hostPid", async () => {
+ const record = await readHostSessionRecord({ configDir: layout.configDir, hostPid });
+
+ expect(record).toBeUndefined();
+ });
+});
+
+describe("REQ-6 claudeConfigDir follows CLAUDE_CONFIG_DIR, then HOME, then the OS home (amendment 1)", () => {
+ test("CLAUDE_CONFIG_DIR wins when set", () => {
+ expect(claudeConfigDir({ CLAUDE_CONFIG_DIR: layout.configDir, HOME: layout.home })).toBe(
+ layout.configDir
+ );
+ });
+
+ test("without CLAUDE_CONFIG_DIR it is $HOME/.claude", () => {
+ expect(claudeConfigDir({ HOME: layout.home })).toBe(join(layout.home, ".claude"));
+ });
+
+ test("with HOME empty it is the OS home directory's .claude", () => {
+ expect(claudeConfigDir({ HOME: "" })).toBe(join(homedir(), ".claude"));
+ });
+});
+
+describe("REQ-1/REQ-2 parentSessionForCall: the host record first, the env id second, else absent", () => {
+ const hostPid = 515151;
+ const env = (extra: Record<string, string> = {}) => ({
+ CLAUDE_CONFIG_DIR: layout.configDir,
+ ...extra,
+ });
+
+ test("record present → its id, even when the env carries a different (stale) id", async () => {
+ const R = claudeId("host");
+ const E = claudeId("env");
+ writeHostRecord(hostPid, JSON.stringify({ pid: hostPid, sessionId: R }));
+
+ expect(await parentSessionForCall({ hostPid, env: env({ CLAUDE_CODE_SESSION_ID: E }) })).toBe(
+ R
+ );
+ });
+
+ test("record missing → the env id", async () => {
+ const E = claudeId("env");
+
+ expect(await parentSessionForCall({ hostPid, env: env({ CLAUDE_CODE_SESSION_ID: E }) })).toBe(
+ E
+ );
+ });
+
+ test("record unusable (pid is not hostPid) → the env id", async () => {
+ const E = claudeId("env");
+ writeHostRecord(hostPid, JSON.stringify({ pid: hostPid + 1, sessionId: claudeId("other") }));
+
+ expect(await parentSessionForCall({ hostPid, env: env({ CLAUDE_CODE_SESSION_ID: E }) })).toBe(
+ E
+ );
+ });
+
+ test.each([
+ ["no record and no env id", {}],
+ ["no record and a malformed env id", { CLAUDE_CODE_SESSION_ID: "bad id!" }],
+ [
+ "no record and an env id under CLAUDE_CODE_CHILD_SESSION",
+ {
+ CLAUDE_CODE_SESSION_ID: "0f9e8d7c-1111-4222-8333-444455556666",
+ CLAUDE_CODE_CHILD_SESSION: "1",
+ },
+ ],
+ ])("%s → undefined", async (_label, extra) => {
+ expect(await parentSessionForCall({ hostPid, env: env(extra) })).toBeUndefined();
+ });
+
+ test("the record's id changes between two calls (/clear) → each call gets the id current at its time", async () => {
+ const before = claudeId("before-clear");
+ const after = claudeId("after-clear");
+ const E = claudeId("env-start");
+ const callEnv = env({ CLAUDE_CODE_SESSION_ID: E });
+ writeHostRecord(hostPid, JSON.stringify({ pid: hostPid, sessionId: before }));
+ const first = await parentSessionForCall({ hostPid, env: callEnv });
+
+ writeHostRecord(hostPid, JSON.stringify({ pid: hostPid, sessionId: after }));
+ const second = await parentSessionForCall({ hostPid, env: callEnv });
+
+ rmSync(join(layout.configDir, "sessions", `${hostPid}.json`));
+ const third = await parentSessionForCall({ hostPid, env: callEnv });
+
+ expect([first, second, third]).toEqual([before, after, E]);
+ });
+});
diff --git a/packages/cli/src/channel/parent-session.ts b/packages/cli/src/channel/parent-session.ts
new file mode 100644
index 00000000..bb30688e
--- /dev/null
+++ b/packages/cli/src/channel/parent-session.ts
@@ -0,0 +1,150 @@
+// ─── Host pid and the parent conversation ────────────────────────────────────
+//
+// Two facts a session or team record carries so an observer outside this
+// process — the magus `claudish` plugin monitor — can tell which Claude Code
+// window started a run:
+//
+// * `hostPid`: the Claude Code process that launched this MCP server. A
+// structural fact, read once at startup from the process tree we were given
+// (our parent, or our launcher's parent). Never searched for.
+// * `parentClaudeSessionId`: the Claude Code CONVERSATION live in that window
+// when the tool call ran. Read once per call from the host's session record
+// `<configDir>/sessions/<hostPid>.json`, which Claude Code rewrites on every
+// session switch (`/clear`, `/resume`). Only when no record can be read does
+// it fall back to `CLAUDE_CODE_SESSION_ID`, the id the server was started
+// with, which goes stale on the first `/clear`.
+//
+// Why not prove it from the transcript: Claude Code (measured on 2.1.290)
+// appends the call's `tool_use` record only AFTER the MCP tool call returns, so
+// no search made while the tool runs can find the call it is attributing.
+//
+// Accepted race: a `/clear` typed in the very moment a call runs may attribute
+// that run to the new conversation. It is always a conversation of the same
+// window — the record is keyed by this server's own host pid.
+
+import { readFile } from "node:fs/promises";
+import { join } from "node:path";
+
+import { userHomeFrom } from "./home-dir.js";
+
+/** What a Claude Code session id may look like. Also the path-safety gate. */
+export const CLAUDE_ID_RE = /^[A-Za-z0-9_-]{8,128}$/;
+
+// ─── hostPid ─────────────────────────────────────────────────────────────────
+
+export interface HostPids {
+ /** The Claude Code process that launched this MCP server. */
+ hostPid: number;
+ /**
+ * The npm `node` launcher (`bin/claudish.cjs`) between Claude Code and this
+ * process, when there is one. Present exactly when `hostPid` came from the
+ * launcher branch, so every record says which branch produced it.
+ */
+ launcherPid?: number;
+}
+
+function positiveInt(value: string | undefined): number | undefined {
+ if (value === undefined || !/^[1-9][0-9]*$/.test(value)) return undefined;
+ const n = Number(value);
+ return Number.isSafeInteger(n) ? n : undefined;
+}
+
+/**
+ * The host pid, from the environment and our own parent pid. Pure.
+ *
+ * - npm / bun global install: Claude Code → `node` launcher → `bun` (us). The
+ * launcher sets `CLAUDISH_LAUNCHER_PID` (itself) and `CLAUDISH_LAUNCHER_PPID`
+ * (its parent). When `CLAUDISH_LAUNCHER_PID` is OUR parent, the host is the
+ * launcher's parent.
+ * - compiled binary, or `bun src/index.ts`: our parent is the host.
+ *
+ * The pair check makes a leaked pair inert: a nested claudish that inherits an
+ * outer launcher's variables sees `CLAUDISH_LAUNCHER_PID` ≠ its own parent and
+ * ignores them. No `ps`, no walk.
+ */
+export function hostPidFrom(env: Record<string, string | undefined>, ppid: number): HostPids {
+ const launcherPpid = positiveInt(env.CLAUDISH_LAUNCHER_PPID);
+ if (
+ env.CLAUDISH_LAUNCHER_PID === String(ppid) &&
+ launcherPpid !== undefined &&
+ launcherPpid !== ppid
+ ) {
+ return { hostPid: launcherPpid, launcherPid: ppid };
+ }
+ return { hostPid: ppid };
+}
+
+// ─── parentClaudeSessionId ───────────────────────────────────────────────────
+
+/**
+ * The conversation id this server was started with, when it is usable at all.
+ *
+ * `CLAUDE_CODE_SESSION_ID` when it is well formed and `CLAUDE_CODE_CHILD_SESSION`
+ * is empty. Claude Code sets the latter for Bash-tool children and monitors and
+ * strips it from the stdio MCP servers it launches, so its presence means this
+ * server was not started by Claude Code directly. The fallback only: it is
+ * current until the first `/clear` and stale after it.
+ */
+export function parentSessionIdFrom(env: Record<string, string | undefined>): string | undefined {
+ const id = env.CLAUDE_CODE_SESSION_ID;
+ if (id === undefined || !CLAUDE_ID_RE.test(id)) return undefined;
+ if (env.CLAUDE_CODE_CHILD_SESSION) return undefined;
+ return id;
+}
+
+/**
+ * `CLAUDE_CONFIG_DIR`, else `<home>/.claude`, with `<home>` resolved by the
+ * same `$HOME`-first rule as the sessions directory (home-dir.ts): Claude Code
+ * follows `$HOME`, and Bun's `os.homedir()` does not.
+ */
+export function claudeConfigDir(env: Record<string, string | undefined>): string {
+ const fromEnv = env.CLAUDE_CONFIG_DIR;
+ return fromEnv && fromEnv.length > 0 ? fromEnv : join(userHomeFrom(env), ".claude");
+}
+
+/** The host's live session record, as far as claudish trusts it. */
+export interface HostSessionRecord {
+ sessionId: string;
+}
+
+/**
+ * `<configDir>/sessions/<hostPid>.json`, the record Claude Code writes at
+ * startup and rewrites on every session switch, so its `sessionId` is the
+ * window's live conversation (`/clear` moves it to the new id, `/resume` back).
+ * Used only when it parses, its `pid === hostPid`, and its `sessionId` is well
+ * formed; anything else is `undefined`. Never throws.
+ */
+export async function readHostSessionRecord(opts: {
+ configDir: string;
+ hostPid: number;
+}): Promise<HostSessionRecord | undefined> {
+ try {
+ const raw = await readFile(join(opts.configDir, "sessions", `${opts.hostPid}.json`), "utf-8");
+ const parsed: unknown = JSON.parse(raw);
+ if (!parsed || typeof parsed !== "object") return undefined;
+ const rec = parsed as { pid?: unknown; sessionId?: unknown };
+ if (rec.pid !== opts.hostPid) return undefined;
+ if (typeof rec.sessionId !== "string" || !CLAUDE_ID_RE.test(rec.sessionId)) return undefined;
+ return { sessionId: rec.sessionId };
+ } catch {
+ return undefined;
+ }
+}
+
+/**
+ * The `parentClaudeSessionId` for one `create_session` or `team(mode:"run")`
+ * call, read once at call time: the host session record's `sessionId`, else
+ * the environment's id, else `undefined` (the field is then omitted). One file
+ * read, no search, no wait. Never throws.
+ */
+export async function parentSessionForCall(opts: {
+ hostPid: number;
+ env?: Record<string, string | undefined>;
+}): Promise<string | undefined> {
+ const env = opts.env ?? process.env;
+ const record = await readHostSessionRecord({
+ configDir: claudeConfigDir(env),
+ hostPid: opts.hostPid,
+ });
+ return record?.sessionId ?? parentSessionIdFrom(env);
+}
diff --git a/packages/cli/src/channel/session-manager.ts b/packages/cli/src/channel/session-manager.ts
index 0c8f8d7a..6f76239c 100644
--- a/packages/cli/src/channel/session-manager.ts
+++ b/packages/cli/src/channel/session-manager.ts
@@ -73,7 +73,7 @@ import { projectsDir, transcriptPathFor } from "../session/session-discovery.js"
import { TRUNCATION_NOTE, type TeamRunOutcome, classifyRunOutput } from "../team-orchestrator.js";
import { readTokenStatsAt } from "../team-stats.js";
import { sessionsDirFrom } from "./home-dir.js";
-import { hostPidFrom } from "./parent-proof.js";
+import { hostPidFrom } from "./parent-session.js";
import { ScrollbackBuffer } from "./scrollback-buffer.js";
import type {
ChannelEvent,
@@ -653,7 +653,7 @@ export class SessionManager {
constructor(options?: SessionManagerOptions) {
// Computed once: the Claude Code process that launched this MCP server
- // does not change for the life of the process. See parent-proof.ts.
+ // does not change for the life of the process. See parent-session.ts.
const host =
options?.hostPid !== undefined
? { hostPid: options.hostPid }
@@ -927,7 +927,7 @@ export class SessionManager {
pendingInputs: opts.prompt ? 1 : 0,
claudeSessionId,
transcriptPath: transcriptPathFor(cwd, claudeSessionId, projectsDir(parentEnv)),
- // Present only when proven, so `meta.json` carries the key exactly when
+ // Present only when there is one, so `meta.json` carries the key exactly when
// `spawn.json` does, with the same value.
...optionalParent(opts.parentClaudeSessionId),
captureSource: null,
diff --git a/packages/cli/src/channel/spawn-record.contract.test.ts b/packages/cli/src/channel/spawn-record.contract.test.ts
index 3d96c96d..8f43ed41 100644
--- a/packages/cli/src/channel/spawn-record.contract.test.ts
+++ b/packages/cli/src/channel/spawn-record.contract.test.ts
@@ -1,6 +1,6 @@
// packages/cli/src/channel/spawn-record.contract.test.ts
/**
- * Black-box contract tests for the start-time record `spawn.json` and the proven parent
+ * Black-box contract tests for the start-time record `spawn.json` and its parent
* conversation, end to end through a real claudish MCP server over stdio
* (design §3.3 "spawn.json", §3.4, §3.5; §8.1 tests 10b, 11-14b, 19; amendments 1 and 2).
*
@@ -10,8 +10,10 @@
*
* The test process stands in for Claude Code: it spawns `bun src/index.ts --mcp`, so the
* correct `hostPid` is `process.pid` and the host's live session record lives at
- * `<CLAUDE_CONFIG_DIR>/sessions/<process.pid>.json`. The tool-use id travels in
- * `params._meta["claudecode/toolUseId"]`, exactly as Claude Code sends it.
+ * `<CLAUDE_CONFIG_DIR>/sessions/<process.pid>.json`. The regression case also sends the
+ * tool-use id in `params._meta["claudecode/toolUseId"]` and writes the transcript's
+ * `tool_use` record only after the call returns, the order Claude Code 2.1.290 was measured
+ * to use; claudish reads neither.
*
* INFERRED (adapters in test-helpers/contract-mcp.ts): create_session returns the id as
* `session_id`. The server exposes no `get_session` MCP tool, so a session read back from disk
@@ -241,171 +243,160 @@ describe.skipIf(!MAGMUX_AVAILABLE)(
}
);
-describe.skipIf(!MAGMUX_AVAILABLE)("REQ-1 the parent conversation is recorded when proven", () => {
- test(
- "env candidate: the tool-use id in E's transcript → spawn.json and meta.json carry parentClaudeSessionId E",
- async () => {
- const E = claudeId("env");
- const T = toolUseId();
- writeTranscript(layout.configDir, "P", E, fillerLine(1) + transcriptLineWithToolUse(T));
- const server = await startServer({ CLAUDE_CODE_SESSION_ID: E });
+describe.skipIf(!MAGMUX_AVAILABLE)(
+ "REQ-1 the parent conversation is the host session record's, read at call time",
+ () => {
+ test(
+ "host record present: spawn.json and meta.json carry its id, not the stale env id",
+ async () => {
+ const R = claudeId("host");
+ const E = claudeId("env-stale");
+ writeHostRecord(layout.configDir, { pid: process.pid, sessionId: R });
+ const server = await startServer({ CLAUDE_CODE_SESSION_ID: E });
- const id = await createdId(server, { prompt: "hello" }, T);
- const spawn = spawnRecord(layout.sessionsDir, id);
- const meta = await terminalMeta(layout.sessionsDir, id);
+ const id = await createdId(server, { prompt: "hello" });
+ const spawn = spawnRecord(layout.sessionsDir, id);
+ const meta = await terminalMeta(layout.sessionsDir, id);
- expect(spawn.parentClaudeSessionId).toBe(E);
- expect(spawn.hostPid).toBe(process.pid);
- expect(meta.parentClaudeSessionId).toBe(E);
- },
- T_TEST
- );
+ expect(spawn.parentClaudeSessionId).toBe(R);
+ expect(spawn.hostPid).toBe(process.pid);
+ expect(meta.parentClaudeSessionId).toBe(R);
+ },
+ T_TEST
+ );
- test(
- "host-record candidate: with no env id, the host's live record (pid = hostPid) and its cwd lead to R",
- async () => {
- const R = claudeId("host");
- const T = toolUseId();
- const cwd = join(layout.root, "the project");
- writeHostRecord(layout.configDir, { pid: process.pid, sessionId: R, cwd });
- writeTranscript(layout.configDir, sanitisedProjectName(cwd), R, transcriptLineWithToolUse(T));
- const server = await startServer({ CLAUDE_CODE_SESSION_ID: undefined });
+ test(
+ "no host record: the env id E is recorded",
+ async () => {
+ const E = claudeId("env");
+ const server = await startServer({ CLAUDE_CODE_SESSION_ID: E });
- const id = await createdId(server, { prompt: "hello" }, T);
+ const id = await createdId(server, { prompt: "hello" });
- expect(spawnRecord(layout.sessionsDir, id).parentClaudeSessionId).toBe(R);
- expect((await terminalMeta(layout.sessionsDir, id)).parentClaudeSessionId).toBe(R);
- },
- T_TEST
- );
+ expect(spawnRecord(layout.sessionsDir, id).parentClaudeSessionId).toBe(E);
+ expect((await terminalMeta(layout.sessionsDir, id)).parentClaudeSessionId).toBe(E);
+ },
+ T_TEST
+ );
- test(
- "REQ-6 without CLAUDE_CONFIG_DIR the proof reads $HOME/.claude",
- async () => {
- const E = claudeId("env");
- const T = toolUseId();
- writeTranscript(join(layout.home, ".claude"), "P", E, transcriptLineWithToolUse(T));
- const server = await startServer({ CLAUDE_CONFIG_DIR: undefined, CLAUDE_CODE_SESSION_ID: E });
+ test(
+ "REQ-6 without CLAUDE_CONFIG_DIR the host record is read from $HOME/.claude",
+ async () => {
+ const R = claudeId("host");
+ writeHostRecord(join(layout.home, ".claude"), { pid: process.pid, sessionId: R });
+ const server = await startServer({ CLAUDE_CONFIG_DIR: undefined });
- const id = await createdId(server, { prompt: "hello" }, T);
+ const id = await createdId(server, { prompt: "hello" });
- expect(spawnRecord(layout.sessionsDir, id).parentClaudeSessionId).toBe(E);
- },
- T_TEST
- );
-
- test(
- "the server stays responsive while a proof waits: list_sessions sent later returns first, and the late-written id is still proven",
- async () => {
- const E = claudeId("env");
- const T = toolUseId();
- const transcript = writeTranscript(layout.configDir, "P", E, fillerLine(1));
- const server = await startServer({ CLAUDE_CODE_SESSION_ID: E });
- const order: string[] = [];
-
- const creating = createSession(server, { prompt: "hello" }, T).then((r) => {
- order.push("create_session");
- return r;
- });
- await Bun.sleep(50);
- const listing = server.callTool("list_sessions", {}).then((r) => {
- order.push("list_sessions");
- return r;
- });
- await Bun.sleep(100);
- appendFileSync(transcript, transcriptLineWithToolUse(T));
- const [{ sessionId }] = await Promise.all([creating, listing]);
+ expect(spawnRecord(layout.sessionsDir, id).parentClaudeSessionId).toBe(R);
+ },
+ T_TEST
+ );
- expect(order).toEqual(["list_sessions", "create_session"]);
- expect(spawnRecord(layout.sessionsDir, sessionId as string).parentClaudeSessionId).toBe(E);
- },
- T_TEST
- );
-});
+ test(
+ "the record's id changes between two calls (/clear): each session gets the id current at its call",
+ async () => {
+ const before = claudeId("before-clear");
+ const after = claudeId("after-clear");
+ writeHostRecord(layout.configDir, { pid: process.pid, sessionId: before });
+ const server = await startServer({ CLAUDE_CODE_SESSION_ID: before });
+
+ const first = await createdId(server, { prompt: "hello" });
+ writeHostRecord(layout.configDir, { pid: process.pid, sessionId: after });
+ const second = await createdId(server, { prompt: "hello" });
+
+ expect([
+ spawnRecord(layout.sessionsDir, first).parentClaudeSessionId,
+ spawnRecord(layout.sessionsDir, second).parentClaudeSessionId,
+ ]).toEqual([before, after]);
+ },
+ T_TEST
+ );
+ }
+);
describe.skipIf(!MAGMUX_AVAILABLE)(
- "REQ-2 the parent field is absent, never wrong, when nothing is proven",
+ "regression: the transcript does not hold the call while the tool runs",
() => {
- async function expectNoParentAnywhere(
- server: McpServer,
- tuid: string | undefined
- ): Promise<void> {
- const id = await createdId(server, { prompt: "hello" }, tuid);
- const spawn = spawnRecord(layout.sessionsDir, id);
- const meta = await terminalMeta(layout.sessionsDir, id);
- expect("parentClaudeSessionId" in spawn).toBe(false);
- expect("parentClaudeSessionId" in meta).toBe(false);
- }
-
test(
- "the tool-use id is in no transcript",
+ "Claude Code 2.1.290 writes the tool_use record only after the call returns, yet the parent is recorded",
async () => {
- const E = claudeId("env");
- writeTranscript(layout.configDir, "P", E, fillerLine(1));
+ const R = claudeId("host");
+ const E = claudeId("env-stale");
+ const T = toolUseId();
+ const cwd = join(layout.root, "project");
+ writeHostRecord(layout.configDir, { pid: process.pid, sessionId: R, cwd });
+ const transcript = writeTranscript(
+ layout.configDir,
+ sanitisedProjectName(cwd),
+ R,
+ fillerLine(1)
+ );
const server = await startServer({ CLAUDE_CODE_SESSION_ID: E });
- await expectNoParentAnywhere(server, toolUseId());
+ const id = await createdId(server, { prompt: "hello" }, T);
+ // Measured order: the record reaches disk ~140 ms after the call returned.
+ appendFileSync(transcript, transcriptLineWithToolUse(T));
+
+ expect(spawnRecord(layout.sessionsDir, id).parentClaudeSessionId).toBe(R);
+ expect((await terminalMeta(layout.sessionsDir, id)).parentClaudeSessionId).toBe(R);
},
T_TEST
);
+ }
+);
+
+describe.skipIf(!MAGMUX_AVAILABLE)(
+ "REQ-2 the parent field is absent when neither source has a well-formed id",
+ () => {
+ async function expectNoParentAnywhere(server: McpServer): Promise<void> {
+ const id = await createdId(server, { prompt: "hello" });
+ const spawn = spawnRecord(layout.sessionsDir, id);
+ const meta = await terminalMeta(layout.sessionsDir, id);
+ expect("parentClaudeSessionId" in spawn).toBe(false);
+ expect("parentClaudeSessionId" in meta).toBe(false);
+ }
test(
- "the call carries no _meta tool-use id",
+ "no host record and no env id",
async () => {
- const E = claudeId("env");
- writeTranscript(layout.configDir, "P", E, transcriptLineWithToolUse(toolUseId()));
- const server = await startServer({ CLAUDE_CODE_SESSION_ID: E });
+ const server = await startServer({ CLAUDE_CODE_SESSION_ID: undefined });
- await expectNoParentAnywhere(server, undefined);
+ await expectNoParentAnywhere(server);
},
T_TEST
);
test(
- "the _meta tool-use id is malformed, even though the transcript holds it",
+ "no host record and a malformed env id",
async () => {
- const E = claudeId("env");
- const bad = "bad id!";
- writeTranscript(layout.configDir, "P", E, transcriptLineWithToolUse(bad));
- const server = await startServer({ CLAUDE_CODE_SESSION_ID: E });
+ const server = await startServer({ CLAUDE_CODE_SESSION_ID: "bad id!" });
- await expectNoParentAnywhere(server, bad);
+ await expectNoParentAnywhere(server);
},
T_TEST
);
test(
- "the env id is ignored under CLAUDE_CODE_CHILD_SESSION, even though its transcript holds the id",
+ "no host record, and the env id is ignored under CLAUDE_CODE_CHILD_SESSION",
async () => {
- const E = claudeId("env");
- const T = toolUseId();
- writeTranscript(layout.configDir, "P", E, transcriptLineWithToolUse(T));
const server = await startServer({
- CLAUDE_CODE_SESSION_ID: E,
+ CLAUDE_CODE_SESSION_ID: claudeId("env"),
CLAUDE_CODE_CHILD_SESSION: "1",
});
- await expectNoParentAnywhere(server, T);
+ await expectNoParentAnywhere(server);
},
T_TEST
);
test(
- "a host record whose pid is not hostPid is ignored, even though its transcript holds the id",
+ "a host record whose pid is not hostPid is ignored, and there is no env id",
async () => {
- const R = claudeId("host");
- const T = toolUseId();
- const cwd = join(layout.root, "proj");
- writeHostRecord(layout.configDir, { pid: process.pid + 1, sessionId: R, cwd });
- writeTranscript(
- layout.configDir,
- sanitisedProjectName(cwd),
- R,
- transcriptLineWithToolUse(T)
- );
+ writeHostRecord(layout.configDir, { pid: process.pid + 1, sessionId: claudeId("host") });
const server = await startServer({ CLAUDE_CODE_SESSION_ID: undefined });
- await expectNoParentAnywhere(server, T);
+ await expectNoParentAnywhere(server);
},
T_TEST
);
diff --git a/packages/cli/src/channel/types.ts b/packages/cli/src/channel/types.ts
index 5aaeb6bc..5444cc71 100644
--- a/packages/cli/src/channel/types.ts
+++ b/packages/cli/src/channel/types.ts
@@ -99,8 +99,10 @@ export interface SessionInfo {
*/
transcriptPath: string;
/**
- * The Claude Code conversation that called create_session, PROVEN at call time
- * (channel/parent-proof.ts). Absent when not proven — never a guess.
+ * The Claude Code conversation live in the calling window when
+ * create_session ran: the host session record's `sessionId`, else
+ * `CLAUDE_CODE_SESSION_ID` (channel/parent-session.ts). Absent when neither
+ * is a well-formed id.
*/
parentClaudeSessionId?: string;
captureSource: "transcript" | "screen" | "none" | null;
@@ -148,9 +150,9 @@ export interface SessionCreateOptions {
/** Where the child's token tracker writes. Defaults to `<sessionDir>/tokens.json`. */
tokenFile?: string;
/**
- * The calling conversation, when the caller PROVED it (see
- * `proveCallingConversation`). Recorded verbatim in `spawn.json` and
- * `SessionInfo`; absent means not proven. Never pass an unproven id.
+ * The calling conversation, as `parentSessionForCall` read it at call time.
+ * Recorded verbatim in `spawn.json` and `SessionInfo`; absent means no id
+ * could be read.
*/
parentClaudeSessionId?: string;
/**
@@ -192,7 +194,7 @@ export interface SessionManagerOptions {
terminalRetentionMs?: number;
/**
* Test override for the host pid recorded in `spawn.json`. Default:
- * `hostPidFrom(process.env, process.ppid)` (channel/parent-proof.ts). An
+ * `hostPidFrom(process.env, process.ppid)` (channel/parent-session.ts). An
* override records no `launcherPid`.
*/
hostPid?: number;
diff --git a/packages/cli/src/mcp-server.ts b/packages/cli/src/mcp-server.ts
index 302633c0..4f7cf27b 100644
--- a/packages/cli/src/mcp-server.ts
+++ b/packages/cli/src/mcp-server.ts
@@ -23,7 +23,7 @@ import { searchCatalogModels } from "./adapters/model-catalog.js";
import { prehydrateCredentialsForSpawn } from "./auth/credentials/prehydrate.js";
import { installWireTap, watchNotificationResult, wrapStateChange } from "./channel/diagnostics.js";
import { SessionManager } from "./channel/index.js";
-import { TOOL_USE_ID_META_KEY, proveParentForCall } from "./channel/parent-proof.js";
+import { parentSessionForCall } from "./channel/parent-session.js";
import type { ChannelEventType } from "./channel/types.js";
import { isSubscriptionProvider } from "./handlers/shared/remote-provider-types.js";
import {
@@ -171,13 +171,6 @@ interface ToolCallContext {
* heartbeat has been stopped. Never throws.
*/
reportProgress: (message?: string) => void;
- /**
- * The calling tool-use id, from the request `_meta["claudecode/toolUseId"]`
- * Claude Code attaches to every MCP tool call. Undefined when the client sent
- * none. Untrusted input: `proveCallingConversation` validates it before any
- * use, and it is only ever used to PROVE which conversation called.
- */
- toolUseId?: string;
}
interface ToolDefinition {
@@ -1662,8 +1655,7 @@ function defineTools(
// completion push is a channel frame Claude Code drops without
// `--channels`. Written BEFORE any pane exists; a throw here fails
// the call with nothing started.
- const parentClaudeSessionId = await proveParentForCall({
- toolUseId: ctx.toolUseId,
+ const parentClaudeSessionId = await parentSessionForCall({
hostPid: sessionManager.hostPid,
});
const monitorRecord = sessionManager.recordTeamRun({
@@ -1981,7 +1973,7 @@ function defineTools(
required: ["model"],
},
group: "channel",
- handler: async (args, ctx) => {
+ handler: async (args) => {
try {
const claudishFlags = buildChildClaudeFlags(args.agent, args.claude_flags) ?? [];
// Refusals first, before any credential work: reserved or positional flags, then
@@ -2011,11 +2003,9 @@ function defineTools(
pin: workDir === undefined || resolve(workDir) === process.cwd(),
});
- // Which conversation called, PROVEN from its transcript or left absent.
- // 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,
+ // The conversation live in the calling window, from the host's session
+ // record: one read at call time, no wait. See channel/parent-session.ts.
+ const parentClaudeSessionId = await parentSessionForCall({
hostPid: sessionManager.hostPid,
});
@@ -2504,10 +2494,8 @@ async function main() {
extra.sendNotification({ method: "notifications/progress", params: frame }),
})
: NOOP_HEARTBEAT;
- const rawToolUseId = extra._meta?.[TOOL_USE_ID_META_KEY];
const ctx: ToolCallContext = {
reportProgress: (message) => heartbeat.tick(message),
- ...(typeof rawToolUseId === "string" ? { toolUseId: rawToolUseId } : {}),
};
try {
diff --git a/packages/cli/src/pane/test-helpers/fake-interactive-child.ts b/packages/cli/src/pane/test-helpers/fake-interactive-child.ts
index 61818d51..fc7820a9 100755
--- a/packages/cli/src/pane/test-helpers/fake-interactive-child.ts
+++ b/packages/cli/src/pane/test-helpers/fake-interactive-child.ts
@@ -34,7 +34,7 @@ import { spawn } from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
import { appendFileSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
-import { projectDirNameFor } from "../../channel/parent-proof.js";
+import { projectDirNameFor } from "../../channel/home-dir.js";
/* ───────────────────────────── argv and env ───────────────────────────── */
diff --git a/packages/cli/src/pane/test-helpers/hermetic-env.ts b/packages/cli/src/pane/test-helpers/hermetic-env.ts
index 35a6d65c..cda84fde 100644
--- a/packages/cli/src/pane/test-helpers/hermetic-env.ts
+++ b/packages/cli/src/pane/test-helpers/hermetic-env.ts
@@ -25,7 +25,7 @@ import {
} from "node:fs";
import { homedir, tmpdir } from "node:os";
import { join } from "node:path";
-import { projectDirNameFor } from "../../channel/parent-proof.js";
+import { projectDirNameFor } from "../../channel/home-dir.js";
import { findMagmuxBinaryOrNull } from "../../launcher/magmux-binary.js";
import { readProcessTable } from "../process-identity.js";
diff --git a/packages/cli/src/session-events/index.ts b/packages/cli/src/session-events/index.ts
index 2986a450..3838f8f1 100644
--- a/packages/cli/src/session-events/index.ts
+++ b/packages/cli/src/session-events/index.ts
@@ -14,7 +14,7 @@
import { existsSync, readFileSync, readdirSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
-import { projectDirNameFor } from "../channel/parent-proof.js";
+import { projectDirNameFor } from "../channel/home-dir.js";
import { log } from "../logger.js";
import { translateLine } from "./event-translator.js";
import { initialState, reduceEvent } from "./session-state.js";
diff --git a/packages/cli/src/session/session-discovery.test.ts b/packages/cli/src/session/session-discovery.test.ts
index ee8502fb..4863834a 100644
--- a/packages/cli/src/session/session-discovery.test.ts
+++ b/packages/cli/src/session/session-discovery.test.ts
@@ -2,7 +2,7 @@ import { afterAll, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { projectDirNameFor } from "../channel/parent-proof.js";
+import { projectDirNameFor } from "../channel/home-dir.js";
import {
ACTIVE_WINDOW_MS,
type SessionRow,
@@ -100,7 +100,7 @@ describe("session discovery pure helpers", () => {
);
});
- test("slugForPath is the parent proof's projectDirNameFor, so the two cannot drift", () => {
+ test("slugForPath is home-dir's projectDirNameFor, so the two cannot drift", () => {
for (const p of ["/a/b_c.d", "/x y/@z", "/Users/x/.claude/worktrees/y"]) {
expect(slugForPath(p)).toBe(projectDirNameFor(p));
}
diff --git a/packages/cli/src/session/session-discovery.ts b/packages/cli/src/session/session-discovery.ts
index 90459888..3f271b48 100644
--- a/packages/cli/src/session/session-discovery.ts
+++ b/packages/cli/src/session/session-discovery.ts
@@ -22,14 +22,15 @@
import { execFile, execFileSync } from "node:child_process";
import { closeSync, openSync, readSync, readdirSync, realpathSync, statSync } from "node:fs";
import { basename, join } from "node:path";
-import { claudeConfigDir, projectDirNameFor } from "../channel/parent-proof.js";
+import { projectDirNameFor } from "../channel/home-dir.js";
+import { claudeConfigDir } from "../channel/parent-session.js";
/** Head bytes scanned for the `entrypoint` marker. See `isAgentSession`. */
const ENTRYPOINT_BYTES = 8192;
/**
* Where Claude Code keeps transcripts: `<config dir>/projects`, the config dir being
- * `CLAUDE_CONFIG_DIR`, else `$HOME/.claude` (`claudeConfigDir`, `channel/parent-proof.ts`).
+ * `CLAUDE_CONFIG_DIR`, else `$HOME/.claude` (`claudeConfigDir`, `channel/parent-session.ts`).
*
* Resolved at CALL time from the environment it is given. It used to be a module
* constant built from `os.homedir()`, which is wrong twice: it ignored a
@@ -50,10 +51,10 @@ export function projectsDir(env: Record<string, string | undefined> = process.en
* created `…-fresh-cwd-v1`: the `_` is replaced too. This used to replace only `/` and
* `.`, so a cwd with `_`, a space or `@` produced a transcript path that did not exist.
*
- * ONE rule: this is `projectDirNameFor` (`channel/parent-proof.ts`), the function the
- * parent-conversation proof searches with, so the path claudish derives for a child's
- * transcript and the directory the proof looks in cannot drift apart. Callers pass a
- * realpath (`transcriptPathFor` resolves one; git hands out real paths).
+ * ONE rule: this is `projectDirNameFor` (`channel/home-dir.ts`), which also cuts a slug
+ * over 200 characters and appends Claude Code's hash. `session-events`' `slugFromCwd`
+ * calls the same function, so no two transcript paths claudish derives can drift apart.
+ * Callers pass a realpath (`transcriptPathFor` resolves one; git hands out real paths).
*
* The mapping is deliberately NOT inverted anywhere in this file. It is lossy — a `-`
* in the slug could have been any non-alphanumeric character — so un-slugging a path
diff --git a/packages/cli/src/team-run-mcp.contract.test.ts b/packages/cli/src/team-run-mcp.contract.test.ts
index 97a58337..b8ea09bf 100644
--- a/packages/cli/src/team-run-mcp.contract.test.ts
+++ b/packages/cli/src/team-run-mcp.contract.test.ts
@@ -14,7 +14,7 @@
* design §5.6). `run-and-judge` and `judge` are not exercised: they need a judge model.
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { existsSync, readFileSync } from "node:fs";
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import {
MAGMUX_AVAILABLE,
@@ -28,6 +28,7 @@ import {
import {
TEAM_RECORD_ID_PATTERN,
type TempLayout,
+ claudeId,
entries,
makeTempLayout,
readJson,
@@ -92,6 +93,25 @@ describe.skipIf(!MAGMUX_AVAILABLE)(
},
T_TEST
);
+
+ test(
+ "the record carries the host session record's id, read when the run call arrives",
+ async () => {
+ const R = claudeId("host");
+ mkdirSync(join(layout.configDir, "sessions"), { recursive: true });
+ writeFileSync(
+ join(layout.configDir, "sessions", `${process.pid}.json`),
+ JSON.stringify({ pid: process.pid, sessionId: R })
+ );
+
+ const record = await run("answer once and exit");
+
+ expect(readJson(join(layout.sessionsDir, record, "spawn.json"))).toMatchObject({
+ parentClaudeSessionId: R,
+ });
+ },
+ T_TEST
+ );
}
);
diff --git a/packages/cli/src/test-helpers/contract-mcp.ts b/packages/cli/src/test-helpers/contract-mcp.ts
index fb9f4ce5..59254d8c 100644
--- a/packages/cli/src/test-helpers/contract-mcp.ts
+++ b/packages/cli/src/test-helpers/contract-mcp.ts
@@ -28,8 +28,8 @@ export const SERVER_ENTRY = join(SRC_DIR, "index.ts");
* server's default CLAUDISH_BIN.
*/
export const PANE_FAKE_CHILD = join(SRC_DIR, "pane", "test-helpers", "fake-interactive-child.ts");
-/** Design §3.5 step 1: the dispatcher reads `extra._meta?.["claudecode/toolUseId"]`. */
-export const TOOL_USE_ID_META_KEY_FROM_SPEC = "claudecode/toolUseId";
+/** The `_meta` key Claude Code sends the calling tool-use id under. claudish does not read it. */
+export const CLAUDE_CODE_TOOL_USE_META_KEY = "claudecode/toolUseId";
export const FAKE_MODEL = "contract-fake-model";
/** Suites that start panes skip with this message when magmux is absent (testing.md). */
@@ -350,8 +350,7 @@ export async function createSession(
const callArgs: Record<string, unknown> = { model: args.model ?? FAKE_MODEL };
if (args.prompt !== undefined) callArgs.prompt = args.prompt;
if (args.timeout_seconds !== undefined) callArgs.timeout_seconds = args.timeout_seconds;
- const meta =
- toolUseId === undefined ? undefined : { [TOOL_USE_ID_META_KEY_FROM_SPEC]: toolUseId };
+ const meta = toolUseId === undefined ? undefined : { [CLAUDE_CODE_TOOL_USE_META_KEY]: toolUseId };
const result = await server.callTool("create_session", callArgs, meta);
const fromJson = findField(result.json, "session_id") ?? findField(result.json, "sessionId");
const fromText = /"?session_?[iI]d"?\s*[:=]\s*"?([A-Za-z0-9][A-Za-z0-9._-]*)/.exec(
diff --git a/packages/cli/src/test-helpers/contract-records.ts b/packages/cli/src/test-helpers/contract-records.ts
index 8f875487..27f21373 100644
--- a/packages/cli/src/test-helpers/contract-records.ts
+++ b/packages/cli/src/test-helpers/contract-records.ts
@@ -239,7 +239,7 @@ export function ppidOf(pid: number): number | undefined {
return Number.isFinite(n) ? n : undefined;
}
-/** §3.5 fast path: the project directory name is the cwd with every char outside [A-Za-z0-9] replaced by "-". */
+/** Claude Code's project directory name for a cwd: every char outside [A-Za-z0-9] replaced by "-". */
export function sanitisedProjectName(cwd: string): string {
return cwd.replace(/[^A-Za-z0-9]/g, "-");
}