diff --git a/src/prefix-affinity.ts b/src/prefix-affinity.ts index 0a456f9bb9..e4aad652c7 100644 --- a/src/prefix-affinity.ts +++ b/src/prefix-affinity.ts @@ -45,6 +45,28 @@ const MAX_TRACKED_SESSIONS = 256; /** Chains unused for this long stop matching (sessions may outlive tracking). */ const TTL_MS = 7 * 24 * 60 * 60 * 1000; +/** Tail-window reattach window (#316 / PR-B): the incoming's LEADING items + * are searched for as a contiguous run at ANY offset inside each stored + * chain's per-item hashes (the incoming head is the retained suffix of the + * stored history, but a rolling-window client may retain any number of + * items, so the match offset must be free — not pinned to the stored tail). */ +const TAIL_WINDOW = 8; + +/** Minimum window size (items) for a tail-window reattach to be trusted. A + * 1-2 item window is too weak a signal (a single shared message is common); + * below this the request falls through to a new session as before. */ +const MIN_TAIL_MATCH = 3; + +/** Per tracked chain, store at most this many per-item hashes (the trailing + * ones). Bounds memory (256 chains × 128 × 64B ≈ 2MB) and keeps the tail + * window (8) comfortably available. Chains deeper than this lose their head, + * so fork-lineage prefix detection is best-effort for very long chains. */ +const MAX_STORED_ITEMS = 128; + +/** Minimum shared prefix (items) to record a "forked" lineage on a new + * session. UI/debug only — never used for matching. */ +const MIN_FORK_PREFIX = 3; + export interface AnonymousAffinity { /** Stable session id: "pfa-" + short hash of (tail, depth). */ sessionId: string; @@ -56,6 +78,16 @@ export interface AnonymousAffinity { incomingDepth: number; /** Chain hash of the incoming tail (log correlation). */ tailHash: string; + /** How the session was resolved: a full-prefix match, a tail-window + * reattach (truncated replay), or a brand-new session. */ + via: "prefix" | "tail-window" | "new"; + /** Per-item hashes of the incoming (trailing, capped at MAX_STORED_ITEMS) — + * passed to note() so the tracked chain can serve future tail-window + * reattach + fork-lineage lookups. */ + itemHashes: string[]; + /** Lineage for a NEW session: the discarded match candidates and why they + * were abandoned. Recorded for UI/debug only — NEVER used for matching. */ + lineage?: { parents: string[]; reason: "truncated" | "forked"; sharedPrefix?: number }; } interface ChainEntry { @@ -63,6 +95,9 @@ interface ChainEntry { depth: number; tailHash: string; lastSeen: number; + /** Per-item hashes (position-independent sha256 of each canonical + * message), trailing, capped at MAX_STORED_ITEMS. */ + itemHashes: string[]; } /** Deterministic JSON with recursively sorted object keys, so two replays @@ -104,6 +139,22 @@ function chainHashes(messages: unknown[]): string[] { return bytes >= MIN_CANONICAL_BYTES ? hashes : []; } +/** Position-INDEPENDENT per-item hashes: itemHashes[i] = sha256(canonical(msg_i)). + * Unlike the progressive chainHashes (which depend on the full prefix and so + * cannot match across a truncation), these let a window of the incoming head + * be compared against a window of a stored tail item-for-item. */ +function perItemHashes(messages: unknown[]): string[] { + return messages.map((m) => sha256(stableStringify(m))); +} + +/** Length of the longest common prefix of two per-item hash arrays. */ +function lcpLength(a: string[], b: string[]): number { + const n = Math.min(a.length, b.length); + let i = 0; + while (i < n && a[i] === b[i]) i++; + return i; +} + export class PrefixAffinityResolver { private trackedChains = new Map(); @@ -115,40 +166,110 @@ export class PrefixAffinityResolver { resolve(messages: unknown[]): AnonymousAffinity | null { const hashes = chainHashes(messages); if (hashes.length === 0 || !hasUserMessage(messages)) return null; - const tailHash = hashes[hashes.length - 1]!; + const incomingDepth = hashes.length; + const tailHash = hashes[incomingDepth - 1]!; + const incItemHashes = perItemHashes(messages); + const storedItemHashes = incItemHashes.slice(-MAX_STORED_ITEMS); const tracked = this.trackedChains; this.expire(tracked); + // 1. Full-depth prefix match (the original radix-style resolution). let best: ChainEntry | undefined; for (const entry of tracked.values()) { - if (entry.depth > hashes.length) continue; + if (entry.depth > incomingDepth) continue; if (hashes[entry.depth - 1] !== entry.tailHash) continue; if (!best || entry.depth > best.depth || (entry.depth === best.depth && entry.lastSeen > best.lastSeen)) best = entry; } - if (best) { return { sessionId: best.sessionId, matchedDepth: best.depth, storedDepth: best.depth, - incomingDepth: hashes.length, + incomingDepth, + tailHash, + via: "prefix", + itemHashes: storedItemHashes, + }; + } + + // 2. Tail-window reattach (#316 / PR-B): a client that dropped its + // oldest messages replays a retained suffix of the stored history + // (plus new appends), so the incoming's LEADING items must appear + // as a contiguous run somewhere inside the stored chain's item + // hashes — at any offset, not just the stored tail (a rolling-window + // client may retain more items than TAIL_WINDOW). + const w = Math.min(TAIL_WINDOW, incomingDepth); + const candidates: ChainEntry[] = []; + if (w >= MIN_TAIL_MATCH) { + for (const entry of tracked.values()) { + const stored = entry.itemHashes; + for (let j = 0; j + w <= stored.length; j++) { + let match = true; + for (let i = 0; i < w; i++) { + if (incItemHashes[i] !== stored[j + i]) { + match = false; + break; + } + } + if (match) { + candidates.push(entry); + break; + } + } + } + } + if (candidates.length === 1) { + const entry = candidates[0]!; + const w = Math.min(TAIL_WINDOW, incomingDepth, entry.depth); + return { + sessionId: entry.sessionId, + matchedDepth: w, + storedDepth: entry.depth, + incomingDepth, tailHash, + via: "tail-window", + itemHashes: storedItemHashes, }; } - // No stored chain is a prefix of the incoming history: this request - // starts a session, anchored deterministically on its current tail so - // an identical replay after a proxy restart reattaches the same id. - const sessionId = `pfa-${sha256(`${tailHash}\u0000${hashes.length}`).slice(0, 16)}`; - return { sessionId, matchedDepth: 0, storedDepth: 0, incomingDepth: hashes.length, tailHash }; + // 3. New session, anchored deterministically on its current tail so an + // identical replay after a proxy restart reattaches the same id. + // Record lineage (UI/debug only) for the discarded candidates. + let lineage: AnonymousAffinity["lineage"]; + if (candidates.length > 1) { + lineage = { parents: candidates.map((c) => c.sessionId), reason: "truncated" }; + } else { + let forkParent: ChainEntry | undefined; + let forkLcp = 0; + for (const entry of tracked.values()) { + if (entry.depth > MAX_STORED_ITEMS) continue; + const lcp = lcpLength(incItemHashes, entry.itemHashes); + if (lcp >= MIN_FORK_PREFIX && lcp > forkLcp) { + forkLcp = lcp; + forkParent = entry; + } + } + if (forkParent) lineage = { parents: [forkParent.sessionId], reason: "forked", sharedPrefix: forkLcp }; + } + const sessionId = `pfa-${sha256(`${tailHash}\u0000${incomingDepth}`).slice(0, 16)}`; + return { + sessionId, + matchedDepth: 0, + storedDepth: 0, + incomingDepth, + tailHash, + via: "new", + itemHashes: storedItemHashes, + ...(lineage ? { lineage } : {}), + }; } /** Record the chain of a session (on creation and after every anonymous * request — the incoming history is the truth, appends extend it). */ - note(sessionId: string, depth: number, tailHash: string): void { + note(sessionId: string, depth: number, tailHash: string, itemHashes: string[]): void { const tracked = this.trackedChains; tracked.delete(sessionId); - tracked.set(sessionId, { sessionId, depth, tailHash, lastSeen: Date.now() }); + tracked.set(sessionId, { sessionId, depth, tailHash, itemHashes, lastSeen: Date.now() }); while (tracked.size > MAX_TRACKED_SESSIONS) { const oldest = [...tracked.values()].sort((a, b) => a.lastSeen - b.lastSeen)[0]; if (!oldest) break; diff --git a/src/server.ts b/src/server.ts index 60d2eac1a2..2a46a760f3 100644 --- a/src/server.ts +++ b/src/server.ts @@ -900,12 +900,16 @@ async function handle( : { error: { type: "invalid_request_error", message: NO_IDENTITY_MESSAGE } })); return; } - if (anonAffinity.matchedDepth > 0) { + if (anonAffinity.via === "tail-window") { + log("info", `[prefix-affinity] anonymous ${protocol} request → session ${anonAffinity.sessionId} (tail-window reattach window=${anonAffinity.matchedDepth}/${anonAffinity.incomingDepth}, tail=${anonAffinity.tailHash.slice(0, 8)}; truncated replay reattached, kernel reconciles by message id)`); + loggerLog("info", `[prefix-affinity] session ${anonAffinity.sessionId} reattached via tail-window (window ${anonAffinity.matchedDepth}/${anonAffinity.incomingDepth}, tail=${anonAffinity.tailHash.slice(0, 8)})`); + } else if (anonAffinity.matchedDepth > 0) { log("info", `[prefix-affinity] anonymous ${protocol} request → session ${anonAffinity.sessionId} (prefix match depth=${anonAffinity.matchedDepth}/${anonAffinity.incomingDepth}, tail=${anonAffinity.tailHash.slice(0, 8)}; fork semantics: diverged histories split on their next request)`); loggerLog("info", `[prefix-affinity] session ${anonAffinity.sessionId} matched at depth ${anonAffinity.matchedDepth}/${anonAffinity.incomingDepth} (tail=${anonAffinity.tailHash.slice(0, 8)})`); } else { - log("info", `[prefix-affinity] new anonymous session ${anonAffinity.sessionId} (depth=${anonAffinity.incomingDepth}, tail=${anonAffinity.tailHash.slice(0, 8)})`); - loggerLog("info", `[prefix-affinity] new session ${anonAffinity.sessionId} at depth ${anonAffinity.incomingDepth} (tail=${anonAffinity.tailHash.slice(0, 8)})`); + const lineage = anonAffinity.lineage ? `; lineage=${anonAffinity.lineage.reason} of ${anonAffinity.lineage.parents.join(",")}` : ""; + log("info", `[prefix-affinity] new anonymous session ${anonAffinity.sessionId} (depth=${anonAffinity.incomingDepth}, tail=${anonAffinity.tailHash.slice(0, 8)}${lineage})`); + loggerLog("info", `[prefix-affinity] new session ${anonAffinity.sessionId} at depth ${anonAffinity.incomingDepth} (tail=${anonAffinity.tailHash.slice(0, 8)}${lineage})`); } } const sessionId = anonAffinity ? anonAffinity.sessionId : conversation; @@ -929,10 +933,12 @@ async function handle( : clientConversationHeader(req.headers); const session = getSession(sessionId, { protocol, upstreamOrigin, label: clientLabel ?? (anonAffinity ? "prefix-affinity" : undefined) }); if (anonAffinity) { - prefixAffinity.note(sessionId, anonAffinity.incomingDepth, anonAffinity.tailHash); + prefixAffinity.note(sessionId, anonAffinity.incomingDepth, anonAffinity.tailHash, anonAffinity.itemHashes); session.metadata.anonymousPrefixAffinity = { depth: anonAffinity.incomingDepth, tailHash: anonAffinity.tailHash, + via: anonAffinity.via, + ...(anonAffinity.lineage ? { lineage: anonAffinity.lineage } : {}), }; } // Launcher-mode binding (#162): prefer identity — claude code sends diff --git a/tests/prefix-affinity.test.ts b/tests/prefix-affinity.test.ts index 7680b55648..f51691b5b3 100644 --- a/tests/prefix-affinity.test.ts +++ b/tests/prefix-affinity.test.ts @@ -15,7 +15,7 @@ test("prefix-affinity: append-only continuation resolves to the same session", ( assert.ok(a); assert.equal(a.matchedDepth, 0); assert.match(a.sessionId, /^pfa-[0-9a-f]{16}$/); - r.note(a.sessionId, a.incomingDepth, a.tailHash); + r.note(a.sessionId, a.incomingDepth, a.tailHash, a.itemHashes); const b = r.resolve([user("hello there friend"), { role: "assistant", content: "hi" }, user("second question")]); assert.ok(b); @@ -27,7 +27,7 @@ test("prefix-affinity: append-only continuation resolves to the same session", ( test("prefix-affinity: different conversations with distinct roots stay separate", () => { const r = new PrefixAffinityResolver(); const a = r.resolve([user("project one setup question")]); - r.note(a!.sessionId, a!.incomingDepth, a!.tailHash); + r.note(a!.sessionId, a!.incomingDepth, a!.tailHash, a!.itemHashes); const b = r.resolve([user("totally different topic opener")]); assert.notEqual(b!.sessionId, a!.sessionId, "different content must not collide"); assert.equal(b!.matchedDepth, 0); @@ -37,12 +37,12 @@ test("prefix-affinity: shared opening, divergent continuation forks on the next const r = new PrefixAffinityResolver(); const shared = [user("same opening message with substance"), { role: "assistant", content: "ok" }]; const a = r.resolve(shared); - r.note(a!.sessionId, a!.incomingDepth, a!.tailHash); + r.note(a!.sessionId, a!.incomingDepth, a!.tailHash, a!.itemHashes); // Branch A extends first — it keeps the session. const aNext = r.resolve([...shared, user("branch A continuation")]); assert.equal(aNext!.sessionId, a!.sessionId); - r.note(aNext!.sessionId, aNext!.incomingDepth, aNext!.tailHash); + r.note(aNext!.sessionId, aNext!.incomingDepth, aNext!.tailHash, aNext!.itemHashes); // Branch B diverges: its history does not extend the stored chain (hash // at stored depth differs), so it starts its own session. @@ -54,7 +54,7 @@ test("prefix-affinity: shared opening, divergent continuation forks on the next test("prefix-affinity: identical replay after restart reattaches the same deterministic id", () => { const first = new PrefixAffinityResolver(); const a = first.resolve([user("persistent conversation anchor")]); - first.note(a!.sessionId, a!.incomingDepth, a!.tailHash); + first.note(a!.sessionId, a!.incomingDepth, a!.tailHash, a!.itemHashes); // Fresh process: no in-memory index, same first-turn content. const second = new PrefixAffinityResolver(); @@ -66,7 +66,7 @@ test("prefix-affinity: trimmed history no longer matches — safe new session", const r = new PrefixAffinityResolver(); const full = [user("first message with content"), { role: "assistant", content: "r1" }, user("second message")]; const a = r.resolve(full); - r.note(a!.sessionId, a!.incomingDepth, a!.tailHash); + r.note(a!.sessionId, a!.incomingDepth, a!.tailHash, a!.itemHashes); // Client-side microcompact drops the middle turn: the stored 3-deep chain // is NOT a prefix of the trimmed history (it is longer). @@ -80,7 +80,7 @@ test("prefix-affinity: no environmental partitioning — same content survives c const r = new PrefixAffinityResolver(); const history = [user("same words across rotating credentials")]; const a = r.resolve(history); - r.note(a!.sessionId, a!.incomingDepth, a!.tailHash); + r.note(a!.sessionId, a!.incomingDepth, a!.tailHash, a!.itemHashes); // #286 lesson: bearer rotation / relay switching / protocol translation // happen MID-CONVERSATION. There is no partition surface at all, so the // identical replay keeps resolving to the same session. @@ -106,7 +106,7 @@ test("prefix-affinity: system+user openai shape (shared system must not collide) const r = new PrefixAffinityResolver(); const sys = { role: "system", content: "You are ZCode, a shared IDE system prompt injected into every conversation." }; const a = r.resolve([sys, user("question about project A")]); - r.note(a!.sessionId, a!.incomingDepth, a!.tailHash); + r.note(a!.sessionId, a!.incomingDepth, a!.tailHash, a!.itemHashes); const b = r.resolve([sys, user("question about project B")]); assert.notEqual(b!.sessionId, a!.sessionId, "identical system prefix must not merge distinct conversations"); }); @@ -115,7 +115,7 @@ test("prefix-affinity: LRU cap bounds tracked sessions", () => { const r = new PrefixAffinityResolver(); for (let i = 0; i < 262; i++) { const a = r.resolve([user(`unique conversation number ${i} with filler content`)]); - r.note(a!.sessionId, a!.incomingDepth, a!.tailHash); + r.note(a!.sessionId, a!.incomingDepth, a!.tailHash, a!.itemHashes); } assert.equal(r.trackedSessionIds().length, 256); }); @@ -130,7 +130,7 @@ test("prefix-affinity: stableStringify sorts keys recursively", () => { test("prefix-affinity: key-order differences across replays still match", () => { const r = new PrefixAffinityResolver(); const a = r.resolve([{ role: "user", content: "key order robustness check", meta: { x: 1, y: 2 } }]); - r.note(a!.sessionId, a!.incomingDepth, a!.tailHash); + r.note(a!.sessionId, a!.incomingDepth, a!.tailHash, a!.itemHashes); const b = r.resolve([{ meta: { y: 2, x: 1 }, content: "key order robustness check", role: "user" }]); assert.equal(b!.sessionId, a!.sessionId, "same logical message in different key order must match"); }); diff --git a/tests/tail-window-reconcile.test.ts b/tests/tail-window-reconcile.test.ts new file mode 100644 index 0000000000..ae3099fa5c --- /dev/null +++ b/tests/tail-window-reconcile.test.ts @@ -0,0 +1,160 @@ +import assert from "node:assert"; +import test from "node:test"; + +process.env.NODE_ENV = "test"; + +import { PrefixAffinityResolver } from "../src/prefix-affinity.ts"; +import { createCore, createInitialState, defaultConfig } from "acp-kernel"; +import { anthropicToCore, type AnthropicRequestBody } from "acp-kernel/wire"; + +function user(text: string): Record { + return { role: "user", content: text }; +} + +// N distinct user messages (content long enough to clear MIN_CANONICAL_BYTES). +function chain(n: number, prefix = "msg"): Record[] { + const out: Record[] = []; + for (let i = 0; i < n; i++) out.push(user(`${prefix} ${i} with enough substance to hash`)); + return out; +} + +test("tail-window: truncated replay (drop oldest) reattaches the original session", () => { + const r = new PrefixAffinityResolver(); + const full = chain(10); + const a = r.resolve(full)!; + assert.equal(a.via, "new"); + r.note(a.sessionId, a.incomingDepth, a.tailHash, a.itemHashes); + + // Client keeps a fixed recent window: drops the 2 oldest, appends 1 new. + // Incoming head (first 8) == stored tail (last 8) → tail-window reattach. + const truncated = [...full.slice(2), user("a brand new tenth-plus turn here")]; + const b = r.resolve(truncated)!; + assert.equal(b.sessionId, a.sessionId, "truncated replay must reattach the original session"); + assert.equal(b.via, "tail-window"); + assert.equal(b.matchedDepth, 8, "window is capped at TAIL_WINDOW=8"); + assert.equal(b.storedDepth, 10); + assert.equal(b.incomingDepth, 9); +}); + +test("tail-window: rolling-window client retaining > TAIL_WINDOW items reattaches at any offset", () => { + // A dsh-style web client keeps a 20-30 item rolling window: the retained + // suffix is LONGER than TAIL_WINDOW, so the incoming head matches the + // stored chain in the middle, not at its tail. The any-offset substring + // search must still find it (tail-pinned matching would orphan it). + const r = new PrefixAffinityResolver(); + const full = chain(30); + const a = r.resolve(full)!; + assert.equal(a.via, "new"); + r.note(a.sessionId, a.incomingDepth, a.tailHash, a.itemHashes); + + // Sliding window: retains the last 20 (> TAIL_WINDOW=8), appends 1 new. + const slid = [...full.slice(10), user("a brand new turn after the window slid")]; + const b = r.resolve(slid)!; + assert.equal(b.sessionId, a.sessionId, "a >8-item rolling window must reattach the original session"); + assert.equal(b.via, "tail-window"); + assert.equal(b.matchedDepth, 8); + + // Deeper slides keep reattaching as the window keeps sliding. + r.note(b.sessionId, b.incomingDepth, b.tailHash, b.itemHashes); + const slid2 = [...full.slice(20), user("yet another turn after sliding again")]; + const c = r.resolve(slid2)!; + assert.equal(c.sessionId, a.sessionId, "a second slide must reattach the same session"); + assert.equal(c.via, "tail-window"); +}); + +test("tail-window: append-only continuation still resolves via prefix (regression)", () => { + const r = new PrefixAffinityResolver(); + const base = chain(4); + const a = r.resolve(base)!; + r.note(a.sessionId, a.incomingDepth, a.tailHash, a.itemHashes); + const b = r.resolve([...base, user("an appended continuation turn")])!; + assert.equal(b.sessionId, a.sessionId); + assert.equal(b.via, "prefix", "a true prefix extension must not be misread as a tail reattach"); + assert.equal(b.matchedDepth, 4); +}); + +test("tail-window: brand-new conversation resolves via new (regression)", () => { + const r = new PrefixAffinityResolver(); + const a = r.resolve(chain(3, "alpha"))!; + r.note(a.sessionId, a.incomingDepth, a.tailHash, a.itemHashes); + const b = r.resolve(chain(3, "beta"))!; + assert.equal(b.via, "new"); + assert.equal(b.matchedDepth, 0); + assert.notEqual(b.sessionId, a.sessionId); +}); + +test("fork lineage: divergent continuation records forked lineage (UI/debug only)", () => { + const r = new PrefixAffinityResolver(); + const shared = chain(4, "shared"); + const a = r.resolve(shared)!; + r.note(a.sessionId, a.incomingDepth, a.tailHash, a.itemHashes); + + // Replace the 4th item: shares a 3-item prefix, diverges at item 4. + const divergent = [...shared.slice(0, 3), user("a divergent fourth turn here")]; + const b = r.resolve(divergent)!; + assert.equal(b.via, "new", "a divergence must not steal the stored chain"); + assert.notEqual(b.sessionId, a.sessionId); + assert.equal(b.lineage?.reason, "forked"); + assert.deepEqual(b.lineage?.parents, [a.sessionId]); + assert.equal(b.lineage?.sharedPrefix, 3); +}); + +test("truncated lineage: ambiguous multi-candidate records truncated lineage", () => { + const r = new PrefixAffinityResolver(); + // Two tracked chains that share the same trailing 8 items but differ in + // their oldest items. A truncated replay whose head == that shared tail is + // ambiguous → new session with a "truncated" lineage naming both parents. + const tail = chain(8, "common-tail"); + const aFull = [...chain(2, "branch-a-head"), ...tail]; + const bFull = [...chain(2, "branch-b-head"), ...tail]; + const a = r.resolve(aFull)!; + r.note(a.sessionId, a.incomingDepth, a.tailHash, a.itemHashes); + const b = r.resolve(bFull)!; + r.note(b.sessionId, b.incomingDepth, b.tailHash, b.itemHashes); + + const incoming = [...tail, user("a fresh turn after truncation")]; + const c = r.resolve(incoming)!; + assert.equal(c.via, "new", "an ambiguous tail match must not guess a parent"); + assert.equal(c.lineage?.reason, "truncated"); + assert.ok(c.lineage?.parents.includes(a.sessionId)); + assert.ok(c.lineage?.parents.includes(b.sessionId)); +}); + +// Kernel reconcile anchor (#316 / PR-B): a truncated replay against +// block-bearing state must NOT throw, must deactivate the affected block +// gracefully (active → false), and must revive it (survivedCount++) when the +// full history returns. This is what makes tail-window reattach safe with zero +// kernel changes. +test("kernel reconcile: truncated replay deactivates blocks, full replay revives them (no throw)", () => { + const core = createCore(); + const config = defaultConfig(200000); + const state = createInitialState(); + const body: AnthropicRequestBody = { model: "claude-test", messages: [] }; + for (let i = 0; i < 40; i++) body.messages.push({ role: i % 2 === 0 ? "user" : "assistant", content: `message ${i} ${"y".repeat(500)}` }); + const { msgs } = anthropicToCore(body); + const turn = core.processTurn({ messages: msgs, state, config, tokenCount: 9999, renderTags: "text-only" }); + const res = core.applyCompression({ + ranges: [{ startRef: "m00001", endRef: "m00015", summary: "early history summary long enough to pass min length check".repeat(3) }], + state: turn.state, config, messages: turn.messages, + }); + let st = res.state; + const block = st.blocks[0]; + assert.ok(block, "a compression block should exist"); + assert.equal(block.active, true, "block starts active"); + const survivedBefore = block.survivedCount; + + // Truncated replay: drop the 10 oldest messages (which include the covered ones). + const truncated = core.processTurn({ messages: msgs.slice(10), state: st, config, tokenCount: 9999, renderTags: "text-only" }); + st = truncated.state; + const deactivated = st.blocks.find((b) => b.blockId === block.blockId); + assert.ok(deactivated, "block still present after truncation"); + assert.equal(deactivated.active, false, "block must deactivate gracefully when its messages are truncated away"); + + // Full replay: the messages return → the block revives. + const full = core.processTurn({ messages: msgs, state: st, config, tokenCount: 9999, renderTags: "text-only" }); + st = full.state; + const revived = st.blocks.find((b) => b.blockId === block.blockId); + assert.ok(revived, "block still present after full replay"); + assert.equal(revived.active, true, "block must revive when its messages return"); + assert.equal(revived.survivedCount, survivedBefore + 1, "survivedCount must increment on revival"); +});