From 3cf8b2ac22d707af56f68095e2858dba14f20ad1 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Mon, 5 Oct 2026 23:40:58 +0800 Subject: [PATCH 1/2] fix: strip cache_control from prefix-affinity identity hashing (#2188) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude Code stamps a cache_control breakpoint on its last message + last assistant message and moves them as the conversation grows. The prefix-affinity identity chain hashed those bytes via stableStringify, so a --resume/--fork replay of an earlier history diverged from the parent's stored chain exactly at the breakpoint position and findResumeParent returned null deterministically — every Claude Code resume/fork lost all compression inheritance (#1486/#1834/#1850). Add canonicalForHash: sorted-key JSON with every cache_control field dropped, used by both chainHashes and perItemHashes. The identity chain is now invariant to breakpoint placement while still requiring actual content to match byte-for-byte. Behavior change (one-time): pre-upgrade chains persisted in prefix-affinity.json were hashed WITH cache_control, so they no longer match new-format incoming hashes and fork fresh once; each session converges after its next live request re-notes its chain (self-healing, no persistence-format change). --- src/prefix-affinity.ts | 32 ++++++++++++++++++-- tests/prefix-affinity.test.ts | 57 +++++++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+), 2 deletions(-) diff --git a/src/prefix-affinity.ts b/src/prefix-affinity.ts index c7f6e3a608..36b148d15d 100644 --- a/src/prefix-affinity.ts +++ b/src/prefix-affinity.ts @@ -149,6 +149,34 @@ function sortKeys(value: unknown): unknown { return value; } +/** Canonical form for IDENTITY hashing (#2188): sorted-key JSON with every + * `cache_control` field dropped. Claude Code stamps a `cache_control` + * breakpoint on its last message + last assistant message and MOVES them as + * the conversation grows, so a --resume/--fork replay of an earlier history + * differs from the parent's final live request ONLY by where those hints sit. + * They are transport-layer cache hints, not conversation content — hashing + * them made EVERY resume/fork miss findResumeParent (the shared prefix was no + * longer byte-stable across a breakpoint shift). Stripping them makes the + * identity chain invariant to breakpoint placement while still requiring the + * actual content to match byte-for-byte. */ +function canonicalForHash(value: unknown): string { + return JSON.stringify(canonicalize(value)); +} + +function canonicalize(value: unknown): unknown { + if (Array.isArray(value)) return value.map(canonicalize); + if (value && typeof value === "object") { + const record = value as Record; + const out: Record = {}; + for (const key of Object.keys(record).sort()) { + if (key === "cache_control") continue; // #2188: transport-layer hint, not content + out[key] = canonicalize(record[key]); + } + return out; + } + return value; +} + function sha256(text: string): string { return createHash("sha256").update(text, "utf8").digest("hex"); } @@ -163,7 +191,7 @@ function chainHashes(messages: unknown[]): string[] { let prev = ""; let bytes = 0; for (const message of messages) { - const canonical = stableStringify(message); + const canonical = canonicalForHash(message); bytes += canonical.length; prev = sha256(`${prev}\u0000${canonical}`); hashes.push(prev); @@ -176,7 +204,7 @@ function chainHashes(messages: unknown[]): string[] { * cannot match across a truncation), these support lineage lookups: fork-LCP * from index 0, and truncated-run detection strictly inside a stored chain. */ function perItemHashes(messages: unknown[]): string[] { - return messages.map((m) => sha256(stableStringify(m))); + return messages.map((m) => sha256(canonicalForHash(m))); } /** Length of the longest common prefix of two per-item hash arrays. */ diff --git a/tests/prefix-affinity.test.ts b/tests/prefix-affinity.test.ts index 230ef45659..1716b77bd8 100644 --- a/tests/prefix-affinity.test.ts +++ b/tests/prefix-affinity.test.ts @@ -271,6 +271,63 @@ test("prefix-affinity: equal-depth replay under a different id is NOT a resume ( assert.equal(r.findResumeParent(transcript, "sess-two"), null, "a byte-exact replay at the SAME depth under another id is a duplicate conversation, not a resume — linking it would adopt foreign blocks"); }); +test("prefix-affinity: identity hash is invariant to cache_control placement (#2188)", () => { + const r = new PrefixAffinityResolver(); + const base = [ + { role: "user", content: [{ type: "text", text: "hello there friend" }] }, + { role: "assistant", content: [{ type: "text", text: "hi, how can I help" }] }, + ]; + const stamped = (where: number) => base.map((m, i) => ({ + ...m, + content: m.content.map((b, j) => (i === where && j === 0 ? { ...b, cache_control: { type: "ephemeral" } } : { ...b })), + })); + const f1 = r.chainFingerprint(stamped(1))!; + const f2 = r.chainFingerprint(stamped(0))!; + assert.equal(f1.tailHash, f2.tailHash, "moving a cache_control breakpoint must not change the identity chain"); + assert.deepEqual(f1.itemHashes, f2.itemHashes, "per-item hashes must ignore cache_control too"); +}); + +test("prefix-affinity: resume-fork survives a cache_control breakpoint shift (#2188)", () => { + const r = new PrefixAffinityResolver(); + const mk = (role: "user" | "assistant", text: string, cc?: boolean) => ({ + role, + content: [{ type: "text", text, ...(cc ? { cache_control: { type: "ephemeral" } } : {}) }], + }); + // Parent's final LIVE request: 10 messages; Claude Code stamps cache_control + // on its trailing pair (last assistant message + last message). + const parentLive = [ + mk("user", "parent turn 0 substance"), + mk("assistant", "parent reply 1"), + mk("user", "parent turn 2 substance"), + mk("assistant", "parent reply 3"), + mk("user", "parent turn 4 substance"), + mk("assistant", "parent reply 5"), + mk("user", "parent turn 6 substance"), + mk("assistant", "parent reply 7"), + mk("assistant", "parent reply 8", true), + mk("user", "parent turn 9 live prompt", true), + ]; + const fp = r.chainFingerprint(parentLive)!; + r.note("sess-parent", fp.depth, fp.tailHash, fp.itemHashes, true); + // Resume/fork replay of the SAME ten messages, but the breakpoints have + // moved past them (they are mid-history now, so they no longer carry + // cache_control); two fresh messages extend the tail, new breakpoint on it. + const stripCc = (m: ReturnType) => ({ + ...m, + content: m.content.map((b) => { const c = { ...b }; delete c.cache_control; return c; }), + }); + const childReplay = [ + ...parentLive.map(stripCc), + mk("assistant", "child reply after resume"), + mk("user", "child question after resume", true), + ]; + assert.deepEqual( + r.findResumeParent(childReplay, "sess-child"), + { sessionId: "sess-parent", sharedDepth: 10 }, + "a resume/fork differing from the parent ONLY by cache_control placement must still inherit", + ); +}); + test("prefix-affinity: anonymous resolution never adopts an identified chain (#1486 #309)", () => { const r = new PrefixAffinityResolver(); const transcript = Array.from({ length: 10 }, (_, i) => user(`cross identity turn ${i} with substance`)); From 61ed9766ad7731d331cd11713a3b878b39263739 Mon Sep 17 00:00:00 2001 From: ework-daemon Date: Mon, 5 Oct 2026 23:56:42 +0800 Subject: [PATCH 2/2] docs: drop duplicated comment line above MAX_TRACKED_SESSIONS (review nit, #2191) --- src/prefix-affinity.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/prefix-affinity.ts b/src/prefix-affinity.ts index 36b148d15d..7fe9e2673e 100644 --- a/src/prefix-affinity.ts +++ b/src/prefix-affinity.ts @@ -49,7 +49,6 @@ import { createHash } from "node:crypto"; * usable conversation signal. Below it the request keeps the #286 400. */ const MIN_CANONICAL_BYTES = 24; -/** Upper bound on tracked chains (LRU-evicted, global — content is the /** Upper bound on tracked chains (LRU-evicted, global — content is the * only key, so there are no per-credential buckets). Chains are PERMANENT * (#1724): the product promise is month- to year-level single sessions, so