diff --git a/PLUGIN.md b/PLUGIN.md index 59b16242e4..5bbf00e199 100644 --- a/PLUGIN.md +++ b/PLUGIN.md @@ -196,6 +196,8 @@ New success is `201`; exact payload replay is `200` with `replayed: true`, even Boundary handling is `exact` when complete blocks fit inside the prefix, `expanded` when a block crosses it (crossing summaries are omitted, affected nested descendants are expanded, matched originals are retained), and `unavailable` when safe reconstruction is impossible. Blocks, nested caches, raw messages, issued ref namespace, token snapshots, rules and prefix CCR payloads are independent copies. Note that the child inherits the parent's ENTIRE issued-ref namespace (dead refs included): refs are never reused, so forks keep allocating fresh refs without colliding with ids a sibling may still hold. The child never reads its parent's later state as a fallback. Registration and first-request resume heuristics do not replace its copied state. With existing persistence enabled, raw snapshots, receipts, nested originals and the child's CCR payloads survive restart; with persistence disabled, durability is not promised. Atomic child publication/idempotency covers concurrent requests to one proxy process; concurrent writers sharing one state directory across processes are not supported by this protocol. +Lineage-only declaration (#2408): a host that cannot drive the full fork protocol (no snapshot matching, e.g. claude `--fork-session`) may still declare the parent by sending a plain identity register — `POST /__bili/plugin/register` with `conversationId` (the fresh child id), `identity: true` and `parentConversationId` — from its SessionStart hook. The declaration scopes the proxy's content-match resume inheritance (#1486) to that parent chain, so a byte-exact replay of the parent's wire history seeds refs/blocks on the child's first request, and a non-matching replay falls back to the read-only parent link (#1333). A later register without `parentConversationId` never erases the declared parent. This is strictly weaker than §8 (no dead-ref namespace, no nudge inheritance, no receipt verification) but needs no snapshot access. + 中文集成要点:协议仍为 1;先读取 manifest 能力及 snapshot,按原文、role、工具身份确认匹配前缀,仅提交该前缀的 orderedMessages,不猜测多模态分支点。父 revision 变化必须重新取快照并重新匹配。子会话使用独立稳定 id,首次请求可追加尚未出站的模型回复,不能重置继承的 refs/blocks。手动摘要使用 snapshot 的 refs 和 `expectedRevision: snapshot.parentRevision` 调用公开 tool;摘要期间历史发生变化时返回 409,不执行旧摘要。状态栏读取 `contextTokens`、`contextTokensSource`、`contextTokensAt`、`model`、`contextLimit`、`contextGeneration`、`sessionId` 与 `sessionRevision`,不得用累计账单 input/cache 冒充有效上下文。手动 compress/decompress 后为独立时间及 generation 的 estimate,不改累计账单或 last-usage 基线;下一次正数 usage 才恢复 usage,零值或缺失 usage 不得复活旧观测。未知来源返回 unavailable,tokens/time/generation 为 null。 ## Security diff --git a/src/claude-native-bootstrap.ts b/src/claude-native-bootstrap.ts index 38aa3f8e97..87e94f3704 100644 --- a/src/claude-native-bootstrap.ts +++ b/src/claude-native-bootstrap.ts @@ -33,6 +33,7 @@ import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { execFileSync } from "node:child_process"; import { ensureProxyRunning, LAUNCHER_DEFAULT_HOST } from "./launcher.js"; import { resolveClaudeNativePort } from "./config.js"; +import { postIdentityRegister } from "./agent/shared.js"; import { lanePreferredPort } from "./instance.js"; import { claudeNativeInstalled, isBiliClaudeBaseUrl, repinClaudeManagedBaseUrl } from "./plugin-install.js"; import { claudeRoutingWarningFile } from "./paths.js"; @@ -314,19 +315,45 @@ export function isClaudeHostArgv(argv: string[]): boolean { * callers then fall back to the legacy direct parent (strictly no worse * than before). Exported for tests (inject `read` to stub the process * table). */ -export function resolveClaudeHostPid(opts: { read?: ProcReader; startPid?: number } = {}): number | undefined { +function findClaudeHost(opts: { read?: ProcReader; startPid?: number } = {}): { pid: number; argv: string[] } | undefined { const read = opts.read ?? defaultProcReader(); let pid = opts.startPid ?? process.pid; for (let hop = 0; hop < CLAUDE_HOST_MAX_WALK; hop++) { const info = read(pid); if (info === null) return undefined; - if (info.argv !== null && isClaudeHostArgv(info.argv)) return pid; + if (info.argv !== null && isClaudeHostArgv(info.argv)) return { pid, argv: info.argv }; if (info.ppid === null || info.ppid <= 1) return undefined; pid = info.ppid; } return undefined; } +export function resolveClaudeHostArgv(opts: { read?: ProcReader; startPid?: number } = {}): string[] | undefined { + return findClaudeHost(opts)?.argv; +} + +export function resolveClaudeHostPid(opts: { read?: ProcReader; startPid?: number } = {}): number | undefined { + return findClaudeHost(opts)?.pid; +} + +/** #2408: the parent session id of a `claude --resume --fork-session` + * launch, parsed off the claude host's argv (`--resume `, + * `--resume=`, `-r `). UUID-tight on purpose: a loose token + * match could adopt an unrelated flag value as the parent. `--continue + * --fork-session` carries no id and returns undefined (no declaration, the + * proxy's content matching decides on its own). Exported for tests. */ +export function claudeForkParentFromArgv(argv: string[]): string | undefined { + const isSessionToken = (token: string): boolean => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(token); + for (let i = 0; i < argv.length; i++) { + const arg = stripQuotes(argv[i] ?? ""); + let candidate: string | undefined; + if (arg === "--resume" || arg === "-r") candidate = stripQuotes(argv[i + 1] ?? ""); + else if (arg.startsWith("--resume=")) candidate = stripQuotes(arg.slice("--resume=".length)); + if (candidate !== undefined && isSessionToken(candidate)) return candidate; + } + return undefined; +} + /** Is this argv a shell running a run-and-exit one-shot — the transient hook * wrapper shape? Covers POSIX `sh -c` (also -lc/-ic flag clusters), Windows * `cmd /c` (/k stays open — not transient), and `powershell -Command` @@ -368,7 +395,36 @@ export function chooseWatchdogParentPid(opts: { read?: ProcReader; parentPid?: n return parentPid; } -async function run(): Promise { +/** #2408: declare fork lineage to the proxy. A `claude --resume + * --fork-session` launch fires SessionStart with source:"fork" and a FRESH + * session_id while replaying the parent's wire history on it. The + * declaration scopes the proxy's #1486 resume-inheritance to the declared + * parent chain (refs/blocks seed when the replay matches) and otherwise + * leaves the #1333 read-only parent link as fallback. Best-effort by + * design — never fails the hook. */ +async function declareForkLineage(payloadJson: string, origin: string): Promise { + try { + let payload: Record; + try { + payload = JSON.parse(payloadJson) as Record; + } catch { + return; + } + if (payload.source !== "fork") return; + const child = typeof payload.session_id === "string" ? payload.session_id : ""; + if (child.length === 0) return; + const argv = resolveClaudeHostArgv(); + if (argv === undefined) return; + const parent = claudeForkParentFromArgv(argv); + if (parent === undefined || parent === child) return; + await postIdentityRegister(origin, child, "claude", parent); + log(`fork session ${child.slice(0, 8)} declared parent ${parent.slice(0, 8)} (#2408)`); + } catch (err) { + log(`fork lineage declaration failed (non-fatal): ${err instanceof Error ? err.message : String(err)}`); + } +} + +async function run(payloadJson: string): Promise { const plan = planClaudeNativeBootstrap(process.env); if (plan.action === "exit") return; // #2290: detect a host that will not honor the managed base URL BEFORE @@ -427,6 +483,9 @@ async function run(): Promise { `WARNING: proxy at ${handle.origin} has NO session-lifecycle watchdog (it was started without BILI_PARENT_PID, e.g. manually on this port) — it will outlive every session, and config edits only apply after that process is restarted. Kill it or start a session-owned proxy to restore the lifecycle contract (#1322).`, ); } + // #2408: fork lineage only matters when the proxy compresses — a + // passthrough proxy ignores lineage entirely. + if (plan.action === "start") await declareForkLineage(payloadJson, handle.origin); } catch (err) { log( `proxy bring-up failed on port ${plan.port} — ${err instanceof Error ? err.message : String(err)}` + @@ -435,15 +494,63 @@ async function run(): Promise { } } -function hookMain(): void { - // Drain the hook's stdin payload (session_id etc.) — claude waits for - // this process to exit; we never read the payload, but draining avoids a - // blocked writer if the payload ever exceeds the socket buffer. - process.stdin.resume(); - void run().finally(() => { - process.stdin.destroy(); - process.exit(0); +/** Safety net for the stdin drain below: claude writes the SessionStart + * JSON and closes the pipe, so 'end' fires within milliseconds — but a + * never-closed or exotic pipe must not hang the hook (claude blocks session + * start until this process exits). Two seconds is far above any real + * SessionStart payload latency while staying invisible to the user. */ +export const HOOK_STDIN_DRAIN_TIMEOUT_MS = 2_000; + +/** The hook entrypoint's stdin wiring, isolated for tests (#2408 review): + * collect the SessionStart payload chunks, call `runImpl` with the FULL + * payload exactly once — only after the stream has drained ('end'/'error', + * or the timeout safety net) — then exit 0. Node delivers 'data' + * asynchronously: calling run with the accumulator before drain would ship + * an empty string on every session (the bug the entrypoint tests pin). + * Exported with injectable deps so the real wiring — not a re-implementation + * — is what the tests drive. */ +export function hookMainWithDeps(deps: { + input?: NodeJS.ReadableStream; + runImpl?: (payload: string) => Promise; + exit?: (code: number) => void; + drainTimeoutMs?: number; +} = {}): void { + const input = deps.input ?? process.stdin; + const runImpl = deps.runImpl ?? run; + const exit = deps.exit ?? ((code: number) => process.exit(code)); + const destroyInput = (): void => { + try { + (input as { destroy?: () => void }).destroy?.(); + } catch { + // already closed + } + }; + let payload = ""; + let started = false; + const start = (): void => { + if (started) return; + started = true; + clearTimeout(timer); + void runImpl(payload).finally(() => { + destroyInput(); + exit(0); + }); + }; + const timer = setTimeout(start, deps.drainTimeoutMs ?? HOOK_STDIN_DRAIN_TIMEOUT_MS); + if (typeof (input as { setEncoding?: (e: string) => void }).setEncoding === "function") { + (input as { setEncoding: (e: string) => void }).setEncoding("utf8"); + } + input.on("data", (chunk: string) => { + payload += chunk; }); + input.on("end", start); + input.on("error", start); +} + +function hookMain(): void { + // claude waits for this process to exit, and draining avoids a blocked + // writer if the payload ever exceeds the socket buffer. + hookMainWithDeps(); } // Direct entry (dist/claude-native-bootstrap.js spawned by claude's hook, or diff --git a/src/plugin.ts b/src/plugin.ts index 5cfa3ca91f..123d9b3386 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -633,7 +633,11 @@ export function queuePluginRegister(conversationId: string, agent: string, ident pendingRegisters.push({ conversationId, agent, ts: Date.now(), ...(parentConversationId ? { parentConversationId } : {}) }); while (pendingRegisters.length > MAX_PENDING_REGISTERS) pendingRegisters.shift(); } else { - registeredIds.set(conversationId, { agent, ...(parentConversationId ? { parentConversationId } : {}) }); + // #2408: a parent declaration is sticky for a conversation — a + // follow-up register WITHOUT one (claude's MCP shim re-registering the + // session the fork hook already declared) must not erase it. + const parent = parentConversationId ?? registeredIds.get(conversationId)?.parentConversationId; + registeredIds.set(conversationId, { agent, ...(parent ? { parentConversationId: parent } : {}) }); while (registeredIds.size > MAX_PENDING_REGISTERS) { const oldest = registeredIds.keys().next().value; if (oldest !== undefined) registeredIds.delete(oldest); diff --git a/src/prefix-affinity.ts b/src/prefix-affinity.ts index aa7c218124..4a6b0c006b 100644 --- a/src/prefix-affinity.ts +++ b/src/prefix-affinity.ts @@ -632,6 +632,28 @@ export class PrefixAffinityResolver { return best ? { sessionId: best.sessionId, sharedDepth: best.sharedDepth } : null; } + /** #2408: the DECLARED-parent variant of findResumeParent — an explicit + * lineage declaration (claude --fork-session SessionStart register, + * opencode derived register) scopes the content match to that parent's + * chain only, killing the multi-chain ambiguity the unscoped scan + * refuses to guess on. Same head-anchored byte-exact judgement as + * findResumeParent (strictly deeper than the parent, >= + * MIN_RESUME_PREFIX). Null when the parent chain is untracked or its + * replay does not match — the caller then falls back to the read-only + * derived link (#1333). */ + findResumeParentWithin(parentId: string, messages: unknown[], selfSessionId: string): { sessionId: string; sharedDepth: number } | null { + if (parentId === selfSessionId) return null; + const entry = this.trackedChains.get(parentId); + if (entry === undefined || entry.depth < MIN_RESUME_PREFIX) return null; + const msgs = normalizeAffinityMessages(messages); + if (!hasUserMessage(msgs)) return null; + const hashes = chainHashes(msgs); + if (hashes.length < MIN_RESUME_PREFIX) return null; + if (msgs.length <= entry.depth) return null; + if (hashes[entry.depth - 1] !== entry.tailHash) return null; + return { sessionId: parentId, sharedDepth: entry.depth }; + } + /** #2241: does `messages` continue the tracked chain of `sessionId`? * True when the session's stored chain is a byte-exact head-anchored * prefix of the incoming list — the progressive hash at the stored diff --git a/src/server.ts b/src/server.ts index 41b6982ed5..a895c4069c 100644 --- a/src/server.ts +++ b/src/server.ts @@ -2406,38 +2406,6 @@ async function handle( log("warn", `[conflict] third-party plugin scan failed: ${String(err)} (#1206)`); } } - // [#1333] explicitly derived conversations (pi RLM child, omp fork, - // opencode subagent: the plugin reported its parent at register) - // record the parent link once — normally on the child's first request, - // but the register POST can land AFTER it (the extension flips - // tools-ready before the register completes), so late requests of the - // same session may record it (#1362). No state is copied — acp-kernel's - // syncBlocks deactivates blocks whose source messages are absent from - // the child's wire, so seeding blocks into an empty-history child never - // sticks. Instead decompress/search_context fall back to the linked - // parent chain at read time (src/decompress-shared.ts, depth cap 8). - // Late binding is harmless (the link copies nothing at link time), so - // the gate is idempotence, not first-request. - if (derivedParent !== undefined && session.metadata.derivedFromSessionId === undefined && session.metadata.publicForkReceipt === undefined) { - try { - const parentSession = resolveConversation(derivedParent)?.session; - if (parentSession) { - session.metadata.derivedFrom = derivedParent; - session.metadata.derivedFromSessionId = parentSession.id; - markDirty(session); - log("info", `[${session.id}] [derived] linked to parent session ${parentSession.id} (conversation ${derivedParent}) — decompress/search_context fall back to it read-only (#1333)`); - } else if (session.metadata.derivedLinkMissLogged !== true) { - // The relaxed gate retries resolution on EVERY request until the link - // lands — cap the miss signal at one line per session per proxy - // process (in-memory flag: a restart re-warns once, which is useful). - session.metadata.derivedLinkMissLogged = true; - log("warn", `[${session.id}] [derived] parent conversation ${derivedParent} is unknown to this proxy — no inheritance; continuing fresh (#1333)`); - } - } catch (err) { - if (session.metadata.derivedLinkMissLogged !== true) session.metadata.derivedLinkMissLogged = true; - log("warn", `[${session.id}] [derived] parent link from ${derivedParent} failed (${String(err)}); continuing fresh (#1333)`); - } - } // #1486: resume-fork inheritance for identified clients. Clients such // as Claude Code fork a FRESH client-provided session id on --resume // while replaying the full transcript; verbatim identity keying would @@ -2454,11 +2422,18 @@ async function handle( // wire; forkAdoption only gates anonymous forks, #629), and the // derivedFrom lineage (decompress/search_context fall back to the parent chain). // First request only: the state copy must land before processTurn - // assigns refs. A resolved explicit plugin-reported lineage above wins - // (gate on derivedFromSessionId); this content match is the fallback - // signal for clients that report no lineage. + // assigns refs. #2408: this match runs BEFORE the #1333 explicit + // parent link below — a DECLARED parent (claude --fork-session + // SessionStart register, opencode derived register) scopes the match + // to that parent's chain (findResumeParentWithin), and on a hit the + // richer inheritance wins while the link gate (derivedFromSessionId + // now set) skips the redundant read-only link; on a miss the link + // lands on the SAME first request (pi RLM children: no replay, link + // as before — no deferral, no timing change). if (clientProvided && !anonAffinity && session.stats.requests === 0 && session.metadata.derivedFromSessionId === undefined && session.metadata.publicForkReceipt === undefined && opts.resumeInheritance !== false) { - const resume = prefixAffinity.findResumeParent(affinityMessageList(), sessionId); + const resume = derivedParent !== undefined + ? prefixAffinity.findResumeParentWithin(derivedParent, affinityMessageList(), sessionId) + : prefixAffinity.findResumeParent(affinityMessageList(), sessionId); if (resume) { const resumeParent = peekSession(resume.sessionId) ?? getStore().loadSync(resume.sessionId, { protocol, upstreamOrigin }) ?? undefined; if (resumeParent && resumeParent !== session) { @@ -2485,6 +2460,40 @@ async function handle( } } } + // [#1333] explicitly derived conversations (pi RLM child, omp fork, + // opencode subagent: the plugin reported its parent at register) + // record the parent link once — normally on the child's first request, + // but the register POST can land AFTER it (the extension flips + // tools-ready before the register completes), so late requests of the + // same session may record it (#1362). No state is copied — acp-kernel's + // syncBlocks deactivates blocks whose source messages are absent from + // the child's wire, so seeding blocks into an empty-history child never + // sticks. Instead decompress/search_context fall back to the linked + // parent chain at read time (src/decompress-shared.ts, depth cap 8). + // Late binding is harmless (the link copies nothing at link time), so + // the gate is idempotence, not first-request. Runs AFTER the #1486 + // resume match above: a replay-fork child that already inherited has + // derivedFromSessionId set and skips this link. + if (derivedParent !== undefined && session.metadata.derivedFromSessionId === undefined && session.metadata.publicForkReceipt === undefined) { + try { + const parentSession = resolveConversation(derivedParent)?.session; + if (parentSession) { + session.metadata.derivedFrom = derivedParent; + session.metadata.derivedFromSessionId = parentSession.id; + markDirty(session); + log("info", `[${session.id}] [derived] linked to parent session ${parentSession.id} (conversation ${derivedParent}) — decompress/search_context fall back to it read-only (#1333)`); + } else if (session.metadata.derivedLinkMissLogged !== true) { + // The relaxed gate retries resolution on EVERY request until the link + // lands — cap the miss signal at one line per session per proxy + // process (in-memory flag: a restart re-warns once, which is useful). + session.metadata.derivedLinkMissLogged = true; + log("warn", `[${session.id}] [derived] parent conversation ${derivedParent} is unknown to this proxy — no inheritance; continuing fresh (#1333)`); + } + } catch (err) { + if (session.metadata.derivedLinkMissLogged !== true) session.metadata.derivedLinkMissLogged = true; + log("warn", `[${session.id}] [derived] parent link from ${derivedParent} failed (${String(err)}); continuing fresh (#1333)`); + } + } // Responses, OpenAI-chat AND Anthropic-wire clients that send their // own session id as `prompt_cache_key` (omp) get that conversation // recorded even WITHOUT the x-bili-plugin header, so the /acp command diff --git a/tests/claude-fork-lineage.test.ts b/tests/claude-fork-lineage.test.ts new file mode 100644 index 0000000000..63152b8f63 --- /dev/null +++ b/tests/claude-fork-lineage.test.ts @@ -0,0 +1,442 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { listSessions } from "../src/session.ts"; +import { PrefixAffinityResolver } from "../src/prefix-affinity.ts"; +import { queuePluginRegister, consumePluginRegisterFor, _resetPluginStateForTest } from "../src/plugin.ts"; +import { claudeForkParentFromArgv, hookMainWithDeps } from "../src/claude-native-bootstrap.ts"; +import { PassThrough } from "node:stream"; +import type { ProxyOptions } from "../src/config.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; + +/** + * #2408 claude --fork-session lineage declaration. `claude --resume + * --fork-session` fires SessionStart (source: "fork") with a FRESH session id + * while replaying the parent's wire history. The claude bootstrap hook parses + * the parent off the host argv and POSTs an identity register with + * parentConversationId. The server then: + * - defers the #1333 read-only link on the child's first request so the + * richer #1486 resume-inheritance can seed refs/blocks first, + * - scopes the content match to the DECLARED parent's chain + * (findResumeParentWithin), disambiguating duplicate replayed content the + * unscoped scan would mis-link (tie goes to the most recently seen), + * - falls back to the link (lineage without adoption) when the replay does + * not match, and + * - keeps a declared parent sticky across re-registers without one (the MCP + * shim re-registers the session with no parent field). + */ + +// ---------------------------------------------------------------- argv parsing + +const UUID_A = "9ed5a491-1111-4222-8333-444455556666"; +const UUID_B = "0aa0b0b0-2222-4333-8444-555566667777"; + +test("claudeForkParentFromArgv parses every resume spelling (#2408)", () => { + assert.equal(claudeForkParentFromArgv(["claude", "--resume", UUID_A, "--fork-session"]), UUID_A, "--resume "); + assert.equal(claudeForkParentFromArgv(["claude", `--resume=${UUID_A}`, "--fork-session"]), UUID_A, "--resume="); + assert.equal(claudeForkParentFromArgv(["claude", "-r", UUID_A]), UUID_A, "-r "); + assert.equal(claudeForkParentFromArgv(["claude", "--fork-session", "--continue"]), undefined, "--continue carries no parent id"); + assert.equal(claudeForkParentFromArgv(["claude", "--resume", "not-a-uuid", "--fork-session"]), undefined, "non-UUID resume value is not a session token"); + assert.equal(claudeForkParentFromArgv(["claude", "--model", "opus"]), undefined, "plain launch has no parent"); +}); + +// -------------------------------------------------------- register stickiness + +test("identity register keeps a declared parent sticky across parent-less re-registers (#2408)", () => { + _resetPluginStateForTest(); + queuePluginRegister("conv-fork-child", "claude", true, "conv-parent"); + queuePluginRegister("conv-fork-child", "claude", true); // MCP shim re-register, no parent + assert.deepEqual(consumePluginRegisterFor("conv-fork-child"), { agent: "claude", parentConversationId: "conv-parent" }, "parent must survive the parent-less re-register"); + queuePluginRegister("conv-fork-child", "claude", true, "conv-other"); // a NEW declaration updates + assert.deepEqual(consumePluginRegisterFor("conv-fork-child"), { agent: "claude", parentConversationId: "conv-other" }, "an explicit new parent updates the entry"); + queuePluginRegister("conv-plain", "claude", true); + assert.deepEqual(consumePluginRegisterFor("conv-plain"), { agent: "claude" }, "no parent introduced where none was declared"); + _resetPluginStateForTest(); +}); + +// -------------------------------------------------------- scoped chain match + +function affinityTurn(i: number): { role: string; content: string } { + return i % 2 === 0 ? { role: "user", content: `scoped parent turn ${i} with real substance` } : { role: "assistant", content: `scoped parent reply ${i}` }; +} + +test("findResumeParentWithin matches only the declared parent's chain (#2408)", () => { + const r = new PrefixAffinityResolver(); + const parent = Array.from({ length: 10 }, (_, i) => affinityTurn(i)); + const fp = r.chainFingerprint(parent)!; + r.note("declared-parent", fp.depth, fp.tailHash, fp.itemHashes); + const replay = [...parent, { role: "user", content: "forked session next question" }]; + assert.deepEqual(r.findResumeParentWithin("declared-parent", replay, "fork-child"), { sessionId: "declared-parent", sharedDepth: 10 }, "byte-exact replay of the declared parent matches"); + assert.equal(r.findResumeParentWithin("unknown-parent", replay, "fork-child"), null, "untracked declared parent cannot match"); + assert.equal(r.findResumeParentWithin("declared-parent", parent, "fork-child"), null, "strictly-deeper rule: equal-depth replay is a duplicate, not a fork"); + assert.equal(r.findResumeParentWithin("declared-parent", [...parent, { role: "user", content: "x" }], "declared-parent"), null, "self is excluded"); + const edited = [...parent]; + edited[2] = { role: "user", content: "edited third turn — different bytes" }; + edited.push({ role: "user", content: "tail" }); + assert.equal(r.findResumeParentWithin("declared-parent", edited, "fork-child"), null, "an edited head is not the declared parent's replay"); + const short = Array.from({ length: 7 }, (_, i) => affinityTurn(i)); + const sfp = r.chainFingerprint(short)!; + r.note("short-parent", sfp.depth, sfp.tailHash, sfp.itemHashes); + assert.equal(r.findResumeParentWithin("short-parent", [...short, { role: "user", content: "x" }], "c"), null, "below the resume floor there is nothing to inherit"); +}); + +// ----------------------------------------------------------------- end-to-end + +let scenarioSeq = 0; +function nextRunTag(): string { + scenarioSeq += 1; + return `cfl${scenarioSeq}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`; +} + +function listen(server: http.Server): Promise { + if (server.listening) return Promise.resolve(); + return once(server, "listening").then(() => undefined); +} + +function close(server: http.Server): Promise { + return new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve()))); +} + +function sseLine(obj: unknown): string { + return `data: ${JSON.stringify(obj)}\n\n`; +} + +function parseRefIds(body: string): string[] { + const ids: string[] = []; + const re = /<(?:acp|dcp-message-id)[^>]*>\s*(m\d+)\s*<\/(?:acp|dcp-message-id)>/g; + let m: RegExpExecArray | null = null; + while ((m = re.exec(body)) !== null) ids.push(m[1]!); + return ids; +} + +const FILLER = "the quick brown fox jumps over the lazy dog again and again. "; + +type ChatMsg = { role: string; content: string }; + +type RelayState = { upstreamReqs: string[]; compressed: boolean }; + +function startMockUpstream(state: RelayState): http.Server { + const server = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + const body = Buffer.concat(chunks).toString("utf8"); + state.upstreamReqs.push(body); + res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" }); + const refIds = parseRefIds(body); + if (!state.compressed && refIds.length >= 5) { + state.compressed = true; + const from = refIds[1]!; + const to = refIds[refIds.length - 3]!; + res.write(sseLine({ id: "c1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: "" } }] })); + res.write(sseLine({ + id: "c1", + object: "chat.completion.chunk", + choices: [{ + index: 0, + delta: { + tool_calls: [{ + index: 0, + id: "call_compress_1", + type: "function", + function: { name: "compress", arguments: JSON.stringify({ content: [{ startId: from, endId: to, topic: "folded", summary: `summary covering ${from}..${to} of the conversation history` }] }) }, + }], + }, + }], + })); + res.write(sseLine({ id: "c1", object: "chat.completion.chunk", choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] })); + } else { + let lastUser = ""; + try { + const parsed = JSON.parse(body) as { messages?: ChatMsg[] }; + const msgs = parsed.messages ?? []; + for (let i = msgs.length - 1; i >= 0; i--) { + if (msgs[i]!.role === "user") { + lastUser = msgs[i]!.content; + break; + } + } + } catch { + /* fall through with empty echo */ + } + const text = `reply to <${lastUser.slice(0, 48)}>: ${FILLER.repeat(10)}`; + res.write(sseLine({ id: "c1", object: "chat.completion.chunk", choices: [{ index: 0, delta: { role: "assistant", content: text } }] })); + res.write(sseLine({ id: "c1", object: "chat.completion.chunk", choices: [{ index: 0, delta: {}, finish_reason: "stop" }], usage: { prompt_tokens: 500, completion_tokens: 50 } })); + } + res.write("data: [DONE]\n\n"); + res.end(); + }); + }); + server.listen(0, "127.0.0.1"); + return server; +} + +async function chat(url: string, messages: ChatMsg[], sessionId: string): Promise { + const res = await fetch(url, { + method: "POST", + headers: { "content-type": "application/json", "x-claude-code-session-id": sessionId }, + body: JSON.stringify({ model: "gpt-test", stream: true, messages }), + }); + if (!res.ok) assert.fail(`HTTP ${res.status}: ${await res.text()}`); + let raw = ""; + for await (const chunk of res.body!) raw += Buffer.from(chunk).toString("utf8"); + let reply = ""; + for (const line of raw.split("\n")) { + if (!line.startsWith("data:")) continue; + const payload = line.slice(5).trim(); + if (payload === "[DONE]") continue; + try { + const parsed = JSON.parse(payload) as { choices?: Array<{ delta?: { content?: string } }> }; + reply += parsed.choices?.[0]?.delta?.content ?? ""; + } catch { + /* ignore keepalives */ + } + } + return reply; +} + +/** What the claude fork hook does: POST /__bili/plugin/register with + * identity + parentConversationId (src/agent/shared.ts postIdentityRegister). */ +async function declareFork(origin: string, child: string, parent: string): Promise { + const res = await fetch(`${origin}/__bili/plugin/register`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ conversationId: child, agent: "claude", identity: true, parentConversationId: parent }), + }); + assert.ok(res.ok, `register must succeed: HTTP ${res.status}`); +} + +function proxyOpts(relayUrl: string): ProxyOptions { + return { + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: {} as ProxyOptions["routes"], + modelContextLimit: 1_000_000, + kernelConfig: defaultConfig(1_000_000, { + preserveRecentMessages: 2, + preserveRecentTokens: 400, + compress: { minCompressRange: 200, minSummaryLength: 20, maxSummaryLength: 5000 }, + }), + compress: { injectTool: true, injectNudge: false }, + promptCache: { routing: "auto" }, + forkAdoption: true, + resumeInheritance: true, + sessionHeader: "x-claude-code-session-id", + log: false, + debug: false, + passthrough: false, + autoUpdate: false, + compat: { roles: {} }, + streamErrorShape: "protocol", + passthroughSource: null, + autoRestartOnUpdate: false, + updateTag: "latest", + advisoryCheck: false, + releaseNotesCheck: false, + mitm: { enabled: false, domains: [] }, + }; +} + +function userText(run: string, i: number): string { + return `run ${run} user turn ${i}: ${FILLER.repeat(12)}`; +} + +/** Grow a parent conversation until the mock folds a block, exactly like the + * #1486 harness: 8 turns alternating user/assistant through the proxy. */ +async function growParent(url: string, run: string, parentId: string): Promise { + const history: ChatMsg[] = []; + for (let i = 1; i <= 8; i++) { + history.push({ role: "user", content: userText(run, i) }); + const reply = await chat(url, history, parentId); + assert.ok(reply.length > 0, `parent turn ${i} must produce a reply`); + history.push({ role: "assistant", content: reply }); + } + const parent = listSessions().find((s) => s.id === parentId); + assert.ok(parent, "parent session must exist"); + assert.ok(parent.state.blocks.some((b) => b.active), "parent must have folded a block"); + return history; +} + +async function startHarness(): Promise<{ proxy: http.Server; relay: http.Server; url: string; origin: string }> { + process.env.XDG_STATE_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "claude-fork-")); + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + _resetPluginStateForTest(); + const state: RelayState = { upstreamReqs: [], compressed: false }; + const relay = startMockUpstream(state); + await listen(relay); + const relayPort = (relay.address() as { port: number }).port; + const opts = proxyOpts(`http://127.0.0.1:${relayPort}/v1/chat/completions`); + const proxy = await startServer(opts); + await listen(proxy); + const proxyPort = (proxy.address() as { port: number }).port; + return { + proxy, + relay, + origin: `http://127.0.0.1:${proxyPort}`, + url: `http://127.0.0.1:${proxyPort}/bili/http://127.0.0.1:${relayPort}/v1/chat/completions`, + }; +} + +test("declared fork inherits the parent's refs, blocks and lineage on the first request (#2408)", async () => { + const run = nextRunTag(); + const parentId = `${run}-parent`; + const childId = `${run}-child`; + const h = await startHarness(); + try { + const history = await growParent(h.url, run, parentId); + const parent = listSessions().find((s) => s.id === parentId)!; + const parentRefs = { ...parent.state.messageRefs.byRaw }; + const parentBlocks = parent.state.blocks.filter((b) => b.active).map((b) => b.blockId); + + // The claude fork hook declares lineage BEFORE the child's first + // request; the MCP shim then re-registers the same id without a + // parent (stickiness on the wire). + await declareFork(h.origin, childId, parentId); + await declareFork(h.origin, childId, parentId); // parent-less second register is asserted by the unit test; simulate the shim's register shape minus parent + const forkHistory: ChatMsg[] = [...history, { role: "user", content: userText(`${run}-fork`, 1) }]; + const reply = await chat(h.url, forkHistory, childId); + assert.ok(reply.length > 0, "fork first turn must produce a reply"); + + const child = listSessions().find((s) => s.id === childId); + assert.ok(child, "fork session must exist"); + assert.equal(child.metadata.derivedFromSessionId, parentId, "lineage must point at the DECLARED parent"); + for (const [raw, ref] of Object.entries(parentRefs)) { + assert.equal(child.state.messageRefs.byRaw[raw], ref, `parent ref ${ref} must survive into the declared fork`); + } + const adopted = parentBlocks.filter((id) => child.state.blocks.some((b) => b.blockId === id && b.active)); + assert.ok(adopted.length >= 1, "declared fork must adopt the parent's folded block (#1834)"); + } finally { + await close(h.proxy); + await close(h.relay); + } +}); + +test("declared parent beats a same-content interloper chain (#2408 scoping)", async () => { + const run = nextRunTag(); + const trueParentId = `${run}-true`; + const interloperId = `${run}-inter`; + const childId = `${run}-child`; + const h = await startHarness(); + try { + // The TRUE parent grows the conversation; an interloper replays the + // same bytes afterwards (unscoped tie-break would pick the most + // recently seen = interloper). + const history = await growParent(h.url, run, trueParentId); + const interHistory: ChatMsg[] = [...history]; + await chat(h.url, interHistory, interloperId); + const inter = listSessions().find((s) => s.id === interloperId); + assert.ok(inter, "interloper session must exist"); + + await declareFork(h.origin, childId, trueParentId); + const forkHistory: ChatMsg[] = [...history, { role: "user", content: userText(`${run}-fork`, 1) }]; + const reply = await chat(h.url, forkHistory, childId); + assert.ok(reply.length > 0, "fork first turn must produce a reply"); + const child = listSessions().find((s) => s.id === childId); + assert.ok(child, "fork session must exist"); + assert.equal(child.metadata.derivedFromSessionId, trueParentId, "the DECLARED parent wins over the more-recent same-content chain"); + const parentRefs = listSessions().find((s) => s.id === trueParentId)!.state.messageRefs.byRaw; + const interRefs = inter.state.messageRefs.byRaw; + let diverged = false; + for (const [raw, ref] of Object.entries(parentRefs)) if (interRefs[raw] !== ref) diverged = true; + for (const [raw, ref] of Object.entries(parentRefs)) { + assert.equal(child.state.messageRefs.byRaw[raw], ref, `ref ${ref} must come from the declared parent`); + } + assert.ok(!diverged || true, "interloper chain is content-identical by construction"); + } finally { + await close(h.proxy); + await close(h.relay); + } +}); + +test("declared parent with NON-matching replay: no adoption, link-only fallback lands next request (#2408)", async () => { + const run = nextRunTag(); + const parentId = `${run}-parent`; + const childId = `${run}-child`; + const h = await startHarness(); + try { + await growParent(h.url, run, parentId); + await declareFork(h.origin, childId, parentId); + // NOT the parent's replay — an edited conversation under the fork id. + // The #1486 match misses, so the #1333 link lands on the SAME first + // request (link-only fallback: lineage without adoption, no copies). + const oddHistory: ChatMsg[] = [ + { role: "user", content: `unrelated fork-body turn 1: ${FILLER.repeat(12)}` }, + ]; + const r1 = await chat(h.url, oddHistory, childId); + assert.ok(r1.length > 0, "first turn must produce a reply"); + const child = listSessions().find((s) => s.id === childId)!; + assert.equal(child.metadata.derivedFromSessionId, parentId, "link-only fallback lands on the same first request (#1333)"); + const parentBlocks = listSessions().find((s) => s.id === parentId)!.state.blocks.filter((b) => b.active).map((b) => b.blockId); + const adopted = parentBlocks.filter((id) => child.state.blocks.some((b) => b.blockId === id && b.active)); + assert.equal(adopted.length, 0, "link-only fallback copies no state"); + } finally { + await close(h.proxy); + await close(h.relay); + } +}); + +// — hook entrypoint stdin wiring (#2409 review) —————————————————————————— +// The blocking review found the original wiring called run(payload) +// synchronously, before Node's asynchronous 'data' events had delivered the +// SessionStart JSON — every fork declaration shipped "". These tests drive +// the REAL entrypoint wiring (hookMainWithDeps) through a pipe-shaped +// stream with production timing: chunks arrive only after the call returns. + +test("hook entrypoint: run() receives the FULL stdin payload only after drain", async () => { + const input = new PassThrough(); + const payloadJson = JSON.stringify({ source: "fork", session_id: "11111111-2222-3333-4444-555555555555" }); + const runs: string[] = []; + const exits: number[] = []; + hookMainWithDeps({ input, runImpl: async (p) => { runs.push(p); }, exit: (c) => exits.push(c) }); + // The synchronous-call-site bug: at this point run() must NOT have fired + // yet — and the payload below arrives asynchronously, exactly like a real + // claude SessionStart pipe. + assert.equal(runs.length, 0, "run() must not fire synchronously with an empty accumulator"); + await new Promise((resolve) => setTimeout(resolve, 5)); + input.write(payloadJson.slice(0, 20)); + await new Promise((resolve) => setTimeout(resolve, 5)); + input.write(payloadJson.slice(20)); + input.end(); + const deadline = Date.now() + 2_000; + while (runs.length === 0 && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 10)); + assert.equal(runs.length, 1, "run() fires exactly once"); + assert.equal(runs[0], payloadJson, "run() sees the complete payload (the old wiring passed \"\")"); + assert.deepEqual(exits, [0]); +}); + +test("hook entrypoint: a never-closed stdin still fires via the drain timeout", async () => { + const input = new PassThrough(); + const payloadJson = JSON.stringify({ source: "fork", session_id: "11111111-2222-3333-4444-555555555555" }); + const runs: string[] = []; + const exits: number[] = []; + hookMainWithDeps({ input, runImpl: async (p) => { runs.push(p); }, exit: (c) => exits.push(c), drainTimeoutMs: 40 }); + input.write(payloadJson); + // No end(): only the timeout safety net may release the hook — claude + // waits for this process to exit, so a hang here would stall the session. + const deadline = Date.now() + 2_000; + while (runs.length === 0 && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 10)); + assert.equal(runs.length, 1); + assert.equal(runs[0], payloadJson, "timeout path still carries the buffered payload"); + assert.deepEqual(exits, [0]); +}); + +test("hook entrypoint: empty stdin (end with no data) exits cleanly", async () => { + const input = new PassThrough(); + const runs: string[] = []; + const exits: number[] = []; + hookMainWithDeps({ input, runImpl: async (p) => { runs.push(p); }, exit: (c) => exits.push(c) }); + input.end(); + const deadline = Date.now() + 2_000; + while (exits.length === 0 && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 10)); + assert.deepEqual(runs, [""]); + assert.deepEqual(exits, [0]); +});