From 288f2e2a2cb4da2d5c3ac91a3c83deeb320c570b Mon Sep 17 00:00:00 2001 From: ci-check Date: Sun, 1 Nov 2026 10:51:59 +0800 Subject: [PATCH] fix: re-anchor fold coverage mutated by host tool-result pruners via byte-verified sentinel shape (#5395) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Host compression plugins (dsh desktop's tool-result-pruner) splice a versioned sentinel between preserved head and tail of long folded tool results. The middle deletion breaks every identity channel at once (norm/ twin equality, wordbag/simhash distance, positional fence); when the host also re-mints tool-call ids across projections (#2396 class) the covered id goes PERMANENTLY unmatched — re-reported every turn, riding unfolded and feeding #2438/#5223 escalation (reported: 614 ids x 156 turns/day). A: pruner-shape pass — LAST channel in planReconciliation. Claims only on positive evidence: resent bytes decompose as head + sentinel + tail with head/tail byte-matching the STORED original (unified index), non-empty deleted middle (overlap guard). No toolCallId equality gate (re-minting is exactly the permanent-drift condition). Steady state pays zero storage reads (marker substring scan first; rows pulled only when a sentinel is on the wire). Store unavailable -> honest unmatched. B: each verified claim lands one 'host-content-mutation' conflict-ledger event with its own advice tier — the second compressor becomes visible on banner/stats instead of staying log-only. Self-limiting: repair mode re-covers the pruned ids, next pass sees them present. Behavior change (intended, the bug fix): pruned covered ids were previously permanently unmatched (drift warn every turn forever); they now re-anchor in ONE pass and converge to clean resend. Additive FoldReconcileResult.byPrune field; additive ConflictKind member; no config surface, no kernel/, no wire shape change. Runs identically in plugin and proxy lanes. --- docs/message-identity.md | 37 ++++ src/conflict-watch.ts | 19 +- src/fold-decomposition-lookup.ts | 36 ++++ src/fold-reconcile.ts | 167 ++++++++++++++++- tests/fold-reconcile.test.ts | 2 +- tests/issue5395-pruner-shape.test.ts | 270 +++++++++++++++++++++++++++ 6 files changed, 518 insertions(+), 13 deletions(-) create mode 100644 tests/issue5395-pruner-shape.test.ts diff --git a/docs/message-identity.md b/docs/message-identity.md index 65c291dc61..1df0bbcdd7 100644 --- a/docs/message-identity.md +++ b/docs/message-identity.md @@ -276,6 +276,43 @@ migration, applies to old and new sessions alike, storage-independent (legacy JSON, shadow and full modes behave identically; bookkeeping rides session metadata). The kernel ledger's content-hash contract is untouched. +## The verified mutation class: host-pruner byte-checked re-anchor (#5395) + +The honesty boundary above rejects *fuzzy* content joins. One mutation +shape admits EXACT verification, and its absence was the costliest residual +class found in production: a host tool-result pruning plugin splices its +versioned sentinel between preserved head and tail of a long tool result +(`dsh-compaction-tool-result-pruner`, dsh desktop). The middle deletion +breaks every identity channel at once — norm/twin equality, wordbag/simhash +distance, positional fence — and when the host re-mints the tool-call id +across projections (#2396) the id channels starve too: the covered id goes +PERMANENTLY unmatched, re-reported every turn, feeding the #2438/#5223 +escalation (reported: 614 ids × 156 turns/day, ~571K tokens/day unfolded). + +The pruner-shape pass (`src/fold-reconcile.ts`; runs LAST in +`planReconciliation`, after every other claim pass) claims only on positive +evidence: the resent bytes must literally decompose as head + sentinel + +tail where head/tail are exact prefix/suffix of the message STORED in bili's +unified index, with a non-empty deleted middle (the overlap guard). Two +distinct originals cannot both decompose around the same sentinel into the +same resent bytes, so mis-attribution is structurally excluded — the +"verified class" the boundary above left open. Gates: role + content-class +agreement, strict length shrink against the anchor, k-th backbone order, one +candidate per old id; deliberately NO toolCallId equality (re-minting is +exactly the condition that makes the drift permanent). Store unavailable or +the original row GC'd → honest unmatched, never a guess. The sentinel table +is built-in code, not configuration: the strings are versioned by their host +plugin, so a new variant lands as a code change with traffic evidence. Each +verified claim lands one `host-content-mutation` conflict-ledger event +(self-limiting: repair mode re-covers the pruned ids, so the next pass sees +them present and the counter falls back to zero) — the second compressor +becomes visible on the banner/stats surfaces instead of staying log-only. +Steady state (no sentinel on the wire) pays zero storage reads. + +Proof: `tests/issue5395-pruner-shape.test.ts` (positive gate, every negative +gate per #3617, k-th discipline, cross-pass convergence, warn-mode parity, +degradation, zero-read contract). + ## The snapshot render engine: outbound identity moves server-side (#3756) #3641 classified verdicts when no channel verifies. #3756 removes the diff --git a/src/conflict-watch.ts b/src/conflict-watch.ts index 43006f9f3f..f2d4176eed 100644 --- a/src/conflict-watch.ts +++ b/src/conflict-watch.ts @@ -13,7 +13,7 @@ import { markDirty, type Session } from "./session.js"; import { isCodexClient } from "./codex-compact.js"; import { isDisplayOnlyConflictDetail, isSiblingConflictDetail } from "./thirdparty-scan.js"; -type ConflictKind = "third-party-plugin" | "unannounced-rewrite" | "orphan-reap" | "native-compaction" | "native-compaction-inferred" | "identity-orphan" | "id-churn-adoption"; +type ConflictKind = "third-party-plugin" | "unannounced-rewrite" | "orphan-reap" | "native-compaction" | "native-compaction-inferred" | "identity-orphan" | "id-churn-adoption" | "host-content-mutation"; export interface ConflictEvent { at: number; @@ -203,8 +203,14 @@ export function formatConflictSection(events: ConflictEvent[], now: number = Dat // landing was fully rebased onto (#2372/#2432) — handled, no ongoing risk. Gated to the // pure case so mixed ledgers keep their existing tier verbatim. const handledNativeOnly = meaningful.length > 0 && meaningful.every((e) => e.kind === "native-compaction"); + // #5395: byte-verified host-side MUTATION (a host tool-result pruner spliced + // its sentinel into folded content; bili re-anchored onto the pruned bytes). + // Own tier: it IS confirmed second-compressor evidence (the header says so), + // but unlike a native-compaction landing bili already REPAIRED it — the + // advice must name the mechanism and the switch, not command a hunt. + const hostMutationPresent = meaningful.some((e) => e.kind === "host-content-mutation"); const activeConfirmed = confirmed.some((e) => now - e.at <= CONFLICT_ACTIVE_WINDOW_MS); - lines.push(`COMPRESSION CONFLICTS — ${events.length} event(s) in this session (${active.length} active · ${historical.length} historical; active = within ${CONFLICT_ACTIVE_WINDOW_MS / 86_400_000} days). ${foreignConfirmed || nativePresent + lines.push(`COMPRESSION CONFLICTS — ${events.length} event(s) in this session (${active.length} active · ${historical.length} historical; active = within ${CONFLICT_ACTIVE_WINDOW_MS / 86_400_000} days). ${foreignConfirmed || nativePresent || hostMutationPresent ? "Two compressors on one conversation (bili + another compression plugin — third-party or bili's own sibling — or client native compaction) double-compress and corrupt message refs:" : "Diagnostic evidence that something outside bili touched this conversation — how strong that evidence is is tiered below:"}`); for (const e of events.slice(-10)) { @@ -247,6 +253,15 @@ export function formatConflictSection(events: ConflictEvent[], now: number = Dat advice = active.length > 0 ? "The events above are client-native compaction landings bili ALREADY rebased onto (#2372/#2432): each detected checkpoint rebuilt the fold base, so there is no ongoing double-compression risk and nothing to disable. If you did not expect these sessions to auto-compact, review the client's own auto-compaction setting; otherwise clear this ledger — Web UI conflict banner / session page, or POST /__bili/conflicts/clear?session=." : "All events above are client-native compaction landings older than 7 days (historical stock) that bili already rebased onto (#2372/#2432): handled at the time, no ongoing risk. Clear this ledger — Web UI conflict banner / session page, or POST /__bili/conflicts/clear?session=."; + } else if (hostMutationPresent) { + // #5395: already-repaired mutation — say so plainly (the conversation + // stayed coherent; bili re-anchored automatically) and name the switch + // that stops recurrence. Gated to ledgers carrying at least one such + // event; mixed ledgers keep their existing tier verbatim (first match + // wins, same as every branch above). + advice = active.length > 0 + ? "The events above are byte-verified host-side mutations: a host compression plugin (tool-result pruner) rewrote content bili had folded, and bili re-anchored its fold state onto the rewritten bytes automatically — the conversation stays coherent, but two compressors ARE touching this session. To stop the recurrence disable the host's tool-result pruning/compaction plugins (keep exactly one compressor per conversation); otherwise clear this ledger." + : "All events above are byte-verified host-side mutations older than 7 days (historical stock) that bili already re-anchored onto automatically: no ongoing corruption, but the host's tool-result pruning/compaction plugins were active alongside bili. If you did not expect them, disable them; otherwise clear this ledger."; } else if (orphanOnly) { // A headerless replay does not prove that the original client moved. // Older ledgers may contain tail-only matches; neither proves state loss. diff --git a/src/fold-decomposition-lookup.ts b/src/fold-decomposition-lookup.ts index 37cabe8a3c..9adc3df294 100644 --- a/src/fold-decomposition-lookup.ts +++ b/src/fold-decomposition-lookup.ts @@ -142,3 +142,39 @@ export function resolveStoredDecompositions( ordered.sort((a, b) => a.seq - b.seq); return ordered.map((o) => o.m); } + +/** #5395: stored originals for caller-chosen ids (pruner-shape byte + * verification) — unlike resolveStoredDecompositions' narrow #3301 backfill + * class, the caller decides WHICH ids to pull (its cheap marker pre-filter + * already ran). Same row discipline: latest seq per id wins; unparseable rows + * are auxiliary-evidence misses, not errors. undefined = index unavailable or + * no rows → the pruner-shape channel degrades to honest unmatched (absence is + * stable for folded-out history). */ +export function storedMessagesById(sessionId: string, msgIds: readonly string[]): Map | undefined { + let rows: StoredRow[] | null; + try { + rows = getStore().unifiedMessageRows(sessionId, msgIds); + } catch (err) { + loggerLog("warn", `[fold-reconcile] pruner-shape stored lookup failed: ${String(err)}`); + return undefined; + } + if (rows === null || rows.length === 0) return undefined; + const latestSeq = new Map(); + const out = new Map(); + for (const row of rows) { + let parsed: unknown; + try { + parsed = JSON.parse(row.content); + } catch { + continue; + } + if (typeof parsed !== "object" || parsed === null) continue; + const m = parsed as CoreMessage; + if (typeof m.id !== "string" || typeof m.role !== "string") continue; + const prev = latestSeq.get(row.msgId); + if (prev !== undefined && prev >= row.seq) continue; + latestSeq.set(row.msgId, row.seq); + out.set(m.id, m); + } + return out.size > 0 ? out : undefined; +} diff --git a/src/fold-reconcile.ts b/src/fold-reconcile.ts index 2475a0c657..cceb772dcb 100644 --- a/src/fold-reconcile.ts +++ b/src/fold-reconcile.ts @@ -140,6 +140,7 @@ import { reapDestroyedSubstrate, type Session } from "./session.js"; import { coveredRealHistoryIds, isResponsesTurnSeparatorId } from "./session.js"; import { dshNativeCompactionWitness, recordConflict } from "./conflict-watch.js"; import { dshCarrierRawMarkers, oneShotCarrierPaths } from "./durable-message-guards.js"; +import { storedMessagesById } from "./fold-decomposition-lookup.js"; import { log as loggerLog } from "./logger.js"; type FoldReconcileMode = "off" | "warn" | "repair"; @@ -262,6 +263,20 @@ const SIDE_REQUEST_MAX_MSGS = 10; * Exported for prefix-affinity's #2601 normalized tail fingerprint, which * must project the appended/placeholder-stripped replay as equal. */ export const USER_IMAGE_PLACEHOLDER = "(image omitted: model does not support images)"; +/** #5395: known host-side mutation sentinels — literal markers a host's + * compression plugin splices between preserved head and tail when pruning a + * long tool result (`dsh-compaction-tool-result-pruner`: thresholdChars=8192, + * headChars=4096, tailChars=1024 by default). Built-in table on purpose: the + * strings are VERSIONED by their host plugin, so a new variant lands as a code + * change with traffic evidence, not a config knob (config surface is + * owner-gated). */ +const PRUNE_MARKERS: readonly string[] = [ + "\n\n[... tool result middle pruned ...]\n\n", +]; +/** #5395: cap on stored-original rows pulled per pass for pruner-shape byte + * verification (the candidate pre-filter already bounds this to a handful; + * the cap is the hard ceiling for pathological drift episodes). */ +const PRUNE_VERIFY_MAX_IDS = 64; /** #5142: covered ids whose permanent absence is EXPECTED host behavior, * accounted out of drift so mega sessions stop paying the O(full-history) @@ -426,6 +441,11 @@ interface ReconciliationPlan { * Order-paired under wordbag + simhash corroboration, or k-th family * pairing for textless anchors; only fires on mass events (≥4 cells). */ byShape: number; + /** #5395: claims made by the pruner-shape pass — a host-side tool-result + * pruner mutated folded content (sentinel spliced between preserved + * head/tail); the resent bytes byte-verify against the STORED original, + * so identity is re-anchored on positive evidence. */ + byPrune: number; /** #2915: order breaks the positional scans resynced over (gaps claimed * as order-carried spans past a fingerprint break) — observability for * the order-centric doctrine, surfaced in the drift log line. */ @@ -482,6 +502,9 @@ export interface FoldReconcileResult { /** #3641: cells re-anchored by the shape-census pass (mass churn with * word evidence: protocol switch, image offload). */ byShape: number; + /** #5395: cells re-anchored onto host-pruned variants (byte-verified + * sentinel splice against the stored original). */ + byPrune: number; /** #2695: fold blocks reaped this pass (removed from state.blocks after * a majority-loss zombie streak). */ reaped: number; @@ -882,6 +905,39 @@ function recoveryCandidateIds(blocks: ReadonlyArray): Set { * stored positional fingerprint copy {ids, canon} (#2487's self-contained * storage shape, adopted); Pass 0 claims by position + canonical fingerprint * before the anchor passes run. */ +/** #5395: cheap superset gate shared by the caller-side storage pre-filter and + * the planner's claim loop — role and content-class agreement plus the length + * shrink. Deliberately NO toolCallId equality: hosts re-mint tool-call ids + * across provider projections (#2396), and that is exactly the condition + * under which the pruner drift goes PERMANENT (every exact channel starves) — + * the byte verification below is the identity proof and does not depend on + * the id surviving. */ +function pruneCandidateMatches(anchor: FoldAnchor, message: CoreMessage): boolean { + if (anchor.r !== undefined && anchor.r !== message.role) return false; + if (anchor.c !== undefined && message.contentType !== undefined && anchor.c !== message.contentType) return false; + return true; +} + +/** #5395: does `mutated` decompose as head + marker + tail where head/tail are + * exact prefix/suffix of `original` with a NON-EMPTY deleted middle? The + * length guard also excludes overlapping prefix/suffix matches (head+tail + * longer than the original would satisfy both suffix tests vacuously). Tries + * every marker occurrence — a double-pruned message repeats the sentinel. */ +function verifyPruneShape(original: string, mutated: string, marker: string): boolean { + let idx = mutated.indexOf(marker); + while (idx >= 0) { + const headLen = idx; + const tail = mutated.slice(idx + marker.length); + if (original.length >= headLen + tail.length + 1 + && original.startsWith(mutated.slice(0, headLen)) + && original.endsWith(tail)) { + return true; + } + idx = mutated.indexOf(marker, idx + marker.length); + } + return false; +} + export function planReconciliation( oldOrder: string[], anchors: Record, @@ -893,8 +949,12 @@ export function planReconciliation( * the missing computation so their permanent absence never triggers the * multi-channel alignment (the O(full-history) tax of #5139). */ expectedAbsent?: ReadonlySet, + /** #5395: stored originals for missing covered ids (unified index), keyed + * by covered id — byte-verification source for the pruner-shape pass. + * Absent → that pass is inert (honest unmatched). */ + storedById?: Map, ): ReconciliationPlan { - const plan: ReconciliationPlan = { claims: new Map(), byPos: 0, byTool: 0, byTwin: 0, bySim: 0, byOrder: 0, byNorm: 0, byTurn: 0, byImage: 0, unmatched: [], idRewriteSuspects: 0, newOrder: [], nextCanon: undefined, resyncs: 0, byShape: 0, absentEverywhere: [], nearDupResidual: [] }; + const plan: ReconciliationPlan = { claims: new Map(), byPos: 0, byTool: 0, byTwin: 0, bySim: 0, byOrder: 0, byNorm: 0, byTurn: 0, byImage: 0, unmatched: [], idRewriteSuspects: 0, newOrder: [], nextCanon: undefined, resyncs: 0, byShape: 0, byPrune: 0, absentEverywhere: [], nearDupResidual: [] }; // #2480: the positional copy is built on EVERY pass, so the first pass // after an upgrade establishes it and every later drift is // position-claimable. The fast path is reuse-by-ID (#2487): same id = @@ -1552,6 +1612,57 @@ export function planReconciliation( } } } + // #5395 — pruner-shape pass, LAST channel and strongest evidence: a host + // compression plugin (tool-result pruner) spliced a known sentinel between + // preserved head/tail of a folded tool result, so EVERY identity channel + // above starves on this shape by construction (the middle deletion breaks + // norm/twin equality, wordbag equality and simhash distance; the changed + // id sits in the churn region but no positional fence survives to verify + // it). Without this pass the covered id is PERMANENTLY unmatched — reported + // every turn forever, riding unfolded until #2438/#5223 escalation. Here + // the resent bytes byte-verify against the STORED original (verifyPruneShape), + // which no other channel can offer: two distinct originals cannot both + // decompose around the same sentinel into the same resent bytes. Runs after + // every other pass so it only fires when nothing else could claim; k-th + // discipline over missingMiddle (same iteration order as the exact passes); + // one candidate serves at most one old id. + if (storedById !== undefined && storedById.size > 0) { + const markerCands: Array<{ c: (typeof candidates)[number]; marker: string }> = []; + for (const c of candidates) { + if (claimedCandidates.has(c.id)) continue; + const text = c.message.text; + if (typeof text !== "string" || text.length === 0) continue; + for (const marker of PRUNE_MARKERS) { + if (text.includes(marker)) { markerCands.push({ c, marker }); break; } + } + } + if (markerCands.length > 0) { + for (const oldId of missingMiddle) { + if (plan.claims.has(oldId)) continue; + const anchor = anchors[oldId]; + if (anchor === undefined || anchor.b === undefined) continue; + const stored = storedById.get(oldId); + if (stored === undefined || typeof stored.text !== "string" || stored.text.length === 0) continue; + for (const { c, marker } of markerCands) { + if (claimedCandidates.has(c.id)) continue; + if (!pruneCandidateMatches(anchor, c.message)) continue; + const mutated = c.message.text ?? ""; + if (mutated.length >= anchor.b) continue; + if (!verifyPruneShape(stored.text, mutated, marker)) continue; + plan.claims.set(oldId, [c.id]); + claimedCandidates.add(c.id); + plan.byPrune++; + break; + } + } + if (plan.byPrune > 0) { + // plan.unmatched was frozen at the end of the exact passes; drop + // what this pass claimed so the census/suspect/churn accounting + // below sees the post-claim state. + plan.unmatched = plan.unmatched.filter((id) => !plan.claims.has(id)); + } + } + } // #3641 census of what STILL did not claim — the verdict classifier's // evidence: absentEverywhere (content truly off the wire → benign // truncation / sanctioned deletion) vs nearDupResidual (word evidence @@ -1697,7 +1808,7 @@ export function reconcileFoldCoverage(session: Session, msgs: CoreMessage[], opt const mode = opts.mode ?? resolveFoldReconcileMode(process.env); if (mode === "off") { resetFoldDriftState(session); - return { kind: "off", missing: 0, claims: 0, byPos: 0, byTool: 0, byTwin: 0, bySim: 0, byOrder: 0, byNorm: 0, byTurn: 0, byImage: 0, byShape: 0, reaped: 0, unmatched: 0, expectedRetired: 0 }; + return { kind: "off", missing: 0, claims: 0, byPos: 0, byTool: 0, byTwin: 0, bySim: 0, byOrder: 0, byNorm: 0, byTurn: 0, byImage: 0, byShape: 0, byPrune: 0, reaped: 0, unmatched: 0, expectedRetired: 0 }; } const blocks = (session.state?.blocks ?? []) as BlockLike[]; // Active coverage first (the anchor cap's survivor order, #2334), then the @@ -1710,7 +1821,7 @@ export function reconcileFoldCoverage(session: Session, msgs: CoreMessage[], opt for (const id of recoveryCandidateIds(blocks)) covered.add(id); if (covered.size === 0) { resetFoldDriftState(session); - return { kind: "noop", missing: 0, claims: 0, byPos: 0, byTool: 0, byTwin: 0, bySim: 0, byOrder: 0, byNorm: 0, byTurn: 0, byImage: 0, byShape: 0, reaped: 0, unmatched: 0, expectedRetired: 0 }; + return { kind: "noop", missing: 0, claims: 0, byPos: 0, byTool: 0, byTwin: 0, bySim: 0, byOrder: 0, byNorm: 0, byTurn: 0, byImage: 0, byShape: 0, byPrune: 0, reaped: 0, unmatched: 0, expectedRetired: 0 }; } // #2202: auxiliary side-requests (title-gen, WebSearch refinement — #1075) // share the conversation id but do not carry the conversation. Reconciling @@ -1723,9 +1834,9 @@ export function reconcileFoldCoverage(session: Session, msgs: CoreMessage[], opt // the episode state is left exactly as found (the resets above stay // reserved for true episode boundaries: reconcile off / no folds at all). if (msgs.length < SIDE_REQUEST_MAX_MSGS || (opts.inboundMessageCount !== undefined && opts.inboundMessageCount < SIDE_REQUEST_MAX_MSGS)) { - return { kind: "noop", missing: 0, claims: 0, byPos: 0, byTool: 0, byTwin: 0, bySim: 0, byOrder: 0, byNorm: 0, byTurn: 0, byImage: 0, byShape: 0, reaped: 0, unmatched: 0, expectedRetired: 0 }; + return { kind: "noop", missing: 0, claims: 0, byPos: 0, byTool: 0, byTwin: 0, bySim: 0, byOrder: 0, byNorm: 0, byTurn: 0, byImage: 0, byShape: 0, byPrune: 0, reaped: 0, unmatched: 0, expectedRetired: 0 }; } - if (!session.metadata) return { kind: "noop", missing: 0, claims: 0, byPos: 0, byTool: 0, byTwin: 0, bySim: 0, byOrder: 0, byNorm: 0, byTurn: 0, byImage: 0, byShape: 0, reaped: 0, unmatched: 0, expectedRetired: 0 }; + if (!session.metadata) return { kind: "noop", missing: 0, claims: 0, byPos: 0, byTool: 0, byTwin: 0, bySim: 0, byOrder: 0, byNorm: 0, byTurn: 0, byImage: 0, byShape: 0, byPrune: 0, reaped: 0, unmatched: 0, expectedRetired: 0 }; let anchors: Record = (session.metadata[METADATA_ANCHORS] as Record | undefined) ?? {}; @@ -1802,14 +1913,49 @@ export function reconcileFoldCoverage(session: Session, msgs: CoreMessage[], opt } let expectedSize = Object.keys(expected).length; - const plan = planReconciliation(oldOrder, anchors, msgs, covered, positions, new Set(Object.keys(expected))); + // #5395: locate host-pruner mutations BEFORE the plan runs. The substring + // scan is the only steady-state cost (one indexOf per marker per message); + // stored originals are pulled ONLY when a marker-bearing resend exists, and + // only for the missing covered ids it could have come from (superset gate + // pruneCandidateMatches + length shrink). No marker on the wire → zero + // storage reads, exactly as before this pass existed. + let pruneStored: Map | undefined; + if (opts.sessionId !== undefined) { + const markerMsgs: CoreMessage[] = []; + for (const m of msgs) { + if (m.id === undefined || covered.has(m.id) || typeof m.text !== "string") continue; + if (PRUNE_MARKERS.some((mk) => m.text!.includes(mk))) markerMsgs.push(m); + } + if (markerMsgs.length > 0) { + const needed: string[] = []; + for (const id of covered) { + if (byId.has(id)) continue; + const anchor = anchors[id]; + if (anchor === undefined || anchor.b === undefined) continue; + if (!markerMsgs.some((m) => pruneCandidateMatches(anchor, m) && (m.text?.length ?? 0) < anchor.b!)) continue; + needed.push(id); + if (needed.length >= PRUNE_VERIFY_MAX_IDS) break; + } + if (needed.length > 0) pruneStored = storedMessagesById(opts.sessionId, needed); + } + } + const plan = planReconciliation(oldOrder, anchors, msgs, covered, positions, new Set(Object.keys(expected)), pruneStored); if (plan.pass0Desync) { loggerLog("warn", `[fold-reconcile] Pass 0 disabled: stored positional copy desynced from order backbone (session=${session.id}, copyIds=${positions?.ids.length ?? -1}, backbone=${oldOrder.length})`); } if (process.env.FOLD_RECONCILE_DEBUG === "1") { const active = blocks.filter((b) => b.active).length; const sample = msgs.slice(0, 6).map((m) => `${m.role}/${m.contentType ?? "-"}/${m.id ?? "?"}`); - process.stderr.write(`[fold-reconcile-dbg] blocks=${blocks.length} active=${active} covered=${covered.size} oldOrder=${oldOrder.length} positions=${positions?.canon.length ?? -1} missing=${plan.unmatched.length + plan.claims.size} claims=${plan.claims.size} expected=${expectedSize} byPos=${plan.byPos} resyncs=${plan.resyncs} byTool=${plan.byTool} byTwin=${plan.byTwin} bySim=${plan.bySim} byOrder=${plan.byOrder} byNorm=${plan.byNorm} byTurn=${plan.byTurn} byImage=${plan.byImage} unmatched=${plan.unmatched.length} | msgs[0..5]=${sample.join(" | ")}\n`); + process.stderr.write(`[fold-reconcile-dbg] blocks=${blocks.length} active=${active} covered=${covered.size} oldOrder=${oldOrder.length} positions=${positions?.canon.length ?? -1} missing=${plan.unmatched.length + plan.claims.size} claims=${plan.claims.size} expected=${expectedSize} byPos=${plan.byPos} resyncs=${plan.resyncs} byTool=${plan.byTool} byTwin=${plan.byTwin} bySim=${plan.bySim} byOrder=${plan.byOrder} byNorm=${plan.byNorm} byTurn=${plan.byTurn} byImage=${plan.byImage} byPrune=${plan.byPrune} unmatched=${plan.unmatched.length} | msgs[0..5]=${sample.join(" | ")}\n`); + } + + // #5395 fix B: a byte-verified host-pruner mutation IS confirmed second- + // compressor evidence — land it in the conflict ledger so the double- + // compression banner/advice surfaces instead of staying a log-only drift. + // Self-limiting by construction: repair mode re-covers the pruned ids via + // the claims, so the NEXT pass sees them present and byPrune falls to zero. + if (plan.byPrune > 0) { + recordConflict(session, "host-content-mutation", `${plan.byPrune} covered tool-result id(s) re-anchored onto host-pruned variants — byte-verified sentinel splice: a host-side tool-result pruner mutated content bili had folded; disable the host pruner or accept coexistence (#5395)`); } // #5142 channels 2+3 — stored-byte evidence (drift passes only). @@ -2439,15 +2585,15 @@ export function reconcileFoldCoverage(session: Session, msgs: CoreMessage[], opt // so it reports like a plain resend (the drift-warn cascade below must not // fire for carrier retirement / offload rewrites). if (realUnmatched.length === 0 && plan.claims.size === 0) { - return { kind: "resend", missing: 0, claims: 0, byPos: 0, byTool: 0, byTwin: 0, bySim: 0, byOrder: 0, byNorm: 0, byTurn: 0, byImage: 0, byShape: 0, reaped: reapedCount, unmatched: 0, expectedRetired: expectedSize }; + return { kind: "resend", missing: 0, claims: 0, byPos: 0, byTool: 0, byTwin: 0, bySim: 0, byOrder: 0, byNorm: 0, byTurn: 0, byImage: 0, byShape: 0, byPrune: 0, reaped: reapedCount, unmatched: 0, expectedRetired: expectedSize }; } if (opts.log !== undefined) { if (plan.claims.size > 0 && mode === "repair") { opts.log(realUnmatched.length > 0 ? "warn" : "info", - `${tag}[fold-reconcile] resent history drifted: ${plan.claims.size + realUnmatched.length} covered id(s) missing${expectedNote} — reanchored ${plan.claims.size} (${plan.byPos} positional${plan.resyncs > 0 ? `, ${plan.resyncs} order break(s) resynced` : ""}, ${plan.byTool} by toolCallId${plan.byTwin > 0 ? `, ${plan.byTwin} by toolCallId twin` : ""}${plan.bySim > 0 ? `, ${plan.bySim} by simhash corroboration` : ""}${plan.byOrder > 0 ? `, ${plan.byOrder} by order bracket` : ""}, ${plan.byNorm} by normalized identity${plan.byTurn > 0 ? `, ${plan.byTurn} by assistant-turn key` : ""}${plan.byImage > 0 ? `, ${plan.byImage} by image-capability variant` : ""}${plan.byShape > 0 ? `, ${plan.byShape} by shape census` : ""}) onto churned bytes, ${realUnmatched.length} unmatched re-enter the wire unfolded${plan.idRewriteSuspects > 0 ? `; ${plan.idRewriteSuspects} suspected host-rewritten tool-call ids (identical content under a different toolCallId — #2396)` : ""} (#1921)${driftTok}`); + `${tag}[fold-reconcile] resent history drifted: ${plan.claims.size + realUnmatched.length} covered id(s) missing${expectedNote} — reanchored ${plan.claims.size} (${plan.byPos} positional${plan.resyncs > 0 ? `, ${plan.resyncs} order break(s) resynced` : ""}, ${plan.byTool} by toolCallId${plan.byTwin > 0 ? `, ${plan.byTwin} by toolCallId twin` : ""}${plan.bySim > 0 ? `, ${plan.bySim} by simhash corroboration` : ""}${plan.byOrder > 0 ? `, ${plan.byOrder} by order bracket` : ""}, ${plan.byNorm} by normalized identity${plan.byTurn > 0 ? `, ${plan.byTurn} by assistant-turn key` : ""}${plan.byImage > 0 ? `, ${plan.byImage} by image-capability variant` : ""}${plan.byShape > 0 ? `, ${plan.byShape} by shape census` : ""}${plan.byPrune > 0 ? `, ${plan.byPrune} by pruner-shape byte verification` : ""}) onto churned bytes, ${realUnmatched.length} unmatched re-enter the wire unfolded${plan.idRewriteSuspects > 0 ? `; ${plan.idRewriteSuspects} suspected host-rewritten tool-call ids (identical content under a different toolCallId — #2396)` : ""} (#1921)${driftTok}`); } else if (plan.claims.size > 0) { opts.log("warn", - `${tag}[fold-reconcile] resent history drifted: ${plan.claims.size + realUnmatched.length} covered id(s) missing${expectedNote}, ${plan.claims.size} matchable by anchor (${plan.byPos} positional${plan.resyncs > 0 ? `, ${plan.resyncs} resynced` : ""}, ${plan.byTool} toolCallId${plan.byTwin > 0 ? `, ${plan.byTwin} twin` : ""}${plan.bySim > 0 ? `, ${plan.bySim} simhash` : ""}${plan.byOrder > 0 ? `, ${plan.byOrder} order-bracket` : ""}, ${plan.byNorm} normalized${plan.byTurn > 0 ? `, ${plan.byTurn} turn key` : ""}${plan.byImage > 0 ? `, ${plan.byImage} image` : ""}) but reconcile=warn made no repair (#1921)${driftTok}`); + `${tag}[fold-reconcile] resent history drifted: ${plan.claims.size + realUnmatched.length} covered id(s) missing${expectedNote}, ${plan.claims.size} matchable by anchor (${plan.byPos} positional${plan.resyncs > 0 ? `, ${plan.resyncs} resynced` : ""}, ${plan.byTool} toolCallId${plan.byTwin > 0 ? `, ${plan.byTwin} twin` : ""}${plan.bySim > 0 ? `, ${plan.bySim} simhash` : ""}${plan.byOrder > 0 ? `, ${plan.byOrder} order-bracket` : ""}, ${plan.byNorm} normalized${plan.byTurn > 0 ? `, ${plan.byTurn} turn key` : ""}${plan.byImage > 0 ? `, ${plan.byImage} image` : ""}${plan.byPrune > 0 ? `, ${plan.byPrune} pruner-shape` : ""}) but reconcile=warn made no repair (#1921)${driftTok}`); } else if (reasoningOnlyDrop) { opts.log("info", `${tag}[fold-reconcile] ${realUnmatched.length} covered reasoning core(s) dropped by the host (cross-model replay discards structured thinking; every text/tool core intact) — fold substrate healthy, tolerated (#2193 follow-up)`); @@ -2501,6 +2647,7 @@ export function reconcileFoldCoverage(session: Session, msgs: CoreMessage[], opt byTurn: plan.byTurn, byImage: plan.byImage, byShape: plan.byShape, + byPrune: plan.byPrune, reaped: reapedCount, unmatched: realUnmatched.length, expectedRetired: expectedSize, diff --git a/tests/fold-reconcile.test.ts b/tests/fold-reconcile.test.ts index e8dfc6d303..67e59002b2 100644 --- a/tests/fold-reconcile.test.ts +++ b/tests/fold-reconcile.test.ts @@ -1070,7 +1070,7 @@ describe("reconcileFoldCoverage anchor cap boundary (#2334)", () => { const snapshot = JSON.stringify(session.metadata); resetNormalizedIdentityWork(); const second = reconcileFoldCoverage(session, msgs, opts); - assert.deepEqual(second, { kind: "resend", missing: 0, claims: 0, byPos: 0, byTool: 0, byTwin: 0, bySim: 0, byOrder: 0, byNorm: 0, byTurn: 0, byImage: 0, byShape: 0, reaped: 0, unmatched: 0, expectedRetired: 0 }); + assert.deepEqual(second, { kind: "resend", missing: 0, claims: 0, byPos: 0, byTool: 0, byTwin: 0, bySim: 0, byOrder: 0, byNorm: 0, byTurn: 0, byImage: 0, byShape: 0, byPrune: 0, reaped: 0, unmatched: 0, expectedRetired: 0 }); assert.equal(normalizedIdentityWorkCount(), 0, "the overflow tail must not be normalized+hashed and dropped AGAIN every pass (#2334)"); assert.equal(JSON.stringify(session.metadata), snapshot, "steady-state resend leaves metadata byte-stable"); diff --git a/tests/issue5395-pruner-shape.test.ts b/tests/issue5395-pruner-shape.test.ts new file mode 100644 index 0000000000..70b164d542 --- /dev/null +++ b/tests/issue5395-pruner-shape.test.ts @@ -0,0 +1,270 @@ +// #5395: host-side tool-result pruner mutates folded messages → covered ids go +// PERMANENTLY unmatched (re-reported every turn, feeding #2438/#5223 escalation). +// The dsh desktop tool-result-pruner splices its sentinel between preserved head +// and tail; bili's identity channels all starve on that shape (norm/twin equality, +// wordbag/simhash distance, positional fence). This suite pins the byte-verified +// pruner-shape re-anchor: positive gate, every negative gate (#3617 both-directions +// discipline), convergence (the bug was NON-convergence), ledger visibility, and +// the steady-state zero-storage-read contract. +import { test, describe } from "node:test"; +import assert from "node:assert/strict"; +import { + planReconciliation, + reconcileFoldCoverage, + normalizedIdentity, + normalizedIdentityNoToolCallId, + type FoldAnchor, + type ReconcileOptions, +} from "../src/fold-reconcile.ts"; +import type { CoreMessage } from "acp-kernel"; +import type { Session } from "../src/session.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { conflictEventsOf } from "../src/conflict-watch.js"; + +const MARKER = "\n\n[... tool result middle pruned ...]\n\n"; + +function msg(id: string, role: string, text: string, extra?: Partial): CoreMessage { + return { id, role, contentType: "text", text, ...extra } as CoreMessage; +} + +function anchorOf(m: CoreMessage): FoldAnchor { + const a: FoldAnchor = { n: normalizedIdentity(m), r: m.role, c: m.contentType, b: m.text?.length ?? 0 }; + if (m.toolCallId) { + a.t = m.toolCallId; + a.m = normalizedIdentityNoToolCallId(m); + } + return a; +} + +function bigText(seed: number, lines = 400): string { + return Array.from({ length: lines }, (_, i) => `line ${i} of tool output ${seed} with padding words`).join("\n"); +} + +/** The host pruner's transform: keep headChars + tailChars, splice the sentinel. */ +function pruned(original: string, headChars = 2000, tailChars = 500): string { + return original.slice(0, headChars) + MARKER + original.slice(-tailChars); +} + +describe("planReconciliation pruner-shape pass (#5395)", () => { + function setup() { + const u1 = msg("u1", "user", "run the big query please"); + const t1 = msg("t1", "tool_result", bigText(7), { toolCallId: "call_1", toolName: "query", contentType: "tool-result" }); + const u2 = msg("u2", "user", "thanks, summarize it"); + const anchors: Record = {}; + for (const m of [u1, t1, u2]) anchors[m.id!] = anchorOf(m); + return { u1, t1, u2, anchors, covered: new Set(["u1", "t1", "u2"]), oldOrder: ["u1", "t1", "u2"] }; + } + + test("stable toolCallId: recovered by the exact tool pass (pre-existing behavior, not stolen)", () => { + const s = setup(); + const p = msg("t1-pruned", "tool_result", pruned(s.t1.text!), { toolCallId: "call_1", toolName: "query", contentType: "tool-result" }); + const plan = planReconciliation(s.oldOrder, s.anchors, [s.u1, p, s.u2], s.covered, undefined, undefined, new Map([["t1", s.t1]])); + assert.deepEqual(plan.claims.get("t1"), ["t1-pruned"]); + assert.equal(plan.byTool, 1, "the exact channel claims first when the id survived"); + assert.equal(plan.byPrune, 0, "pruner-shape only fires when nothing else could claim"); + assert.equal(plan.unmatched.length, 0); + }); + + test("RE-MINTED toolCallId + pruned bytes: byte-verified re-anchor (positive gate — the #5395 regression)", () => { + const s = setup(); + // Host re-mints the tool-call id across projections (#2396 class) AND the + // pruner spliced its sentinel: every exact channel starves, only the byte + // verification against the stored original can claim. + const p = msg("t1-pruned", "tool_result", pruned(s.t1.text!), { toolCallId: "call_1_REMINTED", toolName: "query", contentType: "tool-result" }); + const plan = planReconciliation(s.oldOrder, s.anchors, [s.u1, p, s.u2], s.covered, undefined, undefined, new Map([["t1", s.t1]])); + assert.deepEqual(plan.claims.get("t1"), ["t1-pruned"]); + assert.equal(plan.byPrune, 1); + assert.equal(plan.byTool, 0); + assert.equal(plan.unmatched.length, 0); + }); + + test("marker text NOT byte-derived from the stored original stays unmatched (negative)", () => { + const s = setup(); + const foreignOriginal = bigText(999); + const p = msg("t1-fake", "tool_result", pruned(foreignOriginal), { toolCallId: "call_1_REMINTED", toolName: "query", contentType: "tool-result" }); + const plan = planReconciliation(s.oldOrder, s.anchors, [s.u1, p, s.u2], s.covered, undefined, undefined, new Map([["t1", s.t1]])); + assert.equal(plan.byPrune, 0, "byte verification must fail: head/tail do not match the stored original"); + assert.equal(plan.claims.size, 0); + assert.deepEqual(plan.unmatched, ["t1"]); + }); + + test("unpruned edit (no marker) stays unmatched — channel inert (negative)", () => { + const s = setup(); + const edited = msg("t1-edited", "tool_result", s.t1.text!.slice(0, 3000) + "\nUSER EDIT APPENDED\n" + s.t1.text!.slice(-3000), { toolCallId: "call_1_REMINTED", toolName: "query", contentType: "tool-result" }); + const plan = planReconciliation(s.oldOrder, s.anchors, [s.u1, edited, s.u2], s.covered, undefined, undefined, new Map([["t1", s.t1]])); + assert.equal(plan.byPrune, 0, "no sentinel → no claim, whatever the shape"); + assert.deepEqual(plan.unmatched, ["t1"]); + }); + + test("growth (longer than the anchored original) rejected (negative)", () => { + const s = setup(); + const grown = msg("t1-grown", "tool_result", s.t1.text! + MARKER + "appended tail", { toolCallId: "call_1_REMINTED", toolName: "query", contentType: "tool-result" }); + const plan = planReconciliation(s.oldOrder, s.anchors, [s.u1, grown, s.u2], s.covered, undefined, undefined, new Map([["t1", s.t1]])); + assert.equal(plan.byPrune, 0, "a pruned variant is always SHORTER than the anchored original"); + assert.deepEqual(plan.unmatched, ["t1"]); + }); + + test("role mismatch rejected even when bytes verify (negative)", () => { + const s = setup(); + // Same decomposition, wrong role: the candidate proves nothing about a + // tool_result anchor. + const p = msg("t1-wrongrole", "user", pruned(s.t1.text!), { contentType: "tool-result" }); + const plan = planReconciliation(s.oldOrder, s.anchors, [s.u1, p, s.u2], s.covered, undefined, undefined, new Map([["t1", s.t1]])); + assert.equal(plan.byPrune, 0); + assert.deepEqual(plan.unmatched, ["t1"]); + }); + + test("storedById absent: channel inert even with a valid marker shape (degradation)", () => { + const s = setup(); + const p = msg("t1-pruned", "tool_result", pruned(s.t1.text!), { toolCallId: "call_1_REMINTED", toolName: "query", contentType: "tool-result" }); + const plan = planReconciliation(s.oldOrder, s.anchors, [s.u1, p, s.u2], s.covered); + assert.equal(plan.byPrune, 0, "no stored original → honest unmatched, never a guess"); + assert.deepEqual(plan.unmatched, ["t1"]); + }); + + test("k-th pairing: two pruned tool results pair onto their OWN originals", () => { + const u1 = msg("u1", "user", "run both queries"); + const t1 = msg("t1", "tool_result", bigText(1), { toolCallId: "c_a", toolName: "q", contentType: "tool-result" }); + const t2 = msg("t2", "tool_result", bigText(2), { toolCallId: "c_b", toolName: "q", contentType: "tool-result" }); + const u2 = msg("u2", "user", "done"); + const anchors: Record = {}; + for (const m of [u1, t1, t2, u2]) anchors[m.id!] = anchorOf(m); + const covered = new Set(["u1", "t1", "t2", "u2"]); + const p1 = msg("t1-p", "tool_result", pruned(t1.text!), { toolCallId: "c_a'", toolName: "q", contentType: "tool-result" }); + const p2 = msg("t2-p", "tool_result", pruned(t2.text!), { toolCallId: "c_b'", toolName: "q", contentType: "tool-result" }); + const plan = planReconciliation(["u1", "t1", "t2", "u2"], anchors, [u1, p1, p2, u2], covered, undefined, undefined, new Map([["t1", t1], ["t2", t2]])); + assert.deepEqual(plan.claims.get("t1"), ["t1-p"], "no cross-pairing: each original verifies only against its own decomposition"); + assert.deepEqual(plan.claims.get("t2"), ["t2-p"]); + assert.equal(plan.byPrune, 2); + assert.equal(plan.unmatched.length, 0); + }); + + test("one candidate serves at most one old id (deterministic k-th, no double-claim)", () => { + // Two DISTINCT originals sharing head+tail around different middles + // decompose into the SAME pruned bytes under one cut — one candidate + // cannot cover both; the earlier backbone id wins, the later stays honest. + const sharedHead = "H".repeat(3000); + const sharedTail = "T".repeat(800); + const o1 = msg("o1", "tool_result", sharedHead + "MID-ONE-" + sharedTail, { toolCallId: "x1", contentType: "tool-result" }); + const o2 = msg("o2", "tool_result", sharedHead + "MID-TWO-" + sharedTail, { toolCallId: "x2", contentType: "tool-result" }); + const anchors: Record = {}; + anchors["o1"] = anchorOf(o1); + anchors["o2"] = anchorOf(o2); + const variant = pruned(o1.text!, 2500, 600); + const p = msg("p1", "tool_result", variant, { toolCallId: "x1'", contentType: "tool-result" }); + const plan = planReconciliation(["o1", "o2"], anchors, [p], new Set(["o1", "o2"]), undefined, undefined, new Map([["o1", o1], ["o2", o2]])); + assert.equal(plan.claims.size, 1); + assert.deepEqual(plan.claims.get("o1"), ["p1"], "backbone order decides; deterministic"); + assert.deepEqual(plan.unmatched, ["o2"]); + }); +}); + +describe("reconcileFoldCoverage integration (#5395)", () => { + type LogLine = { level: string; msg: string }; + interface RawRow { seq: number; msgId: string; content: string } + + /** Disabled real store (markDirty & friends stay safe) with unified rows shadowed in. */ + function storeWithRows(rows: RawRow[], calls?: number[]): SessionStore { + const base = new SessionStore({ enabled: false }); + return Object.create(base, { + unifiedMessageRows: { + value: (_id: string, ids: readonly string[]) => { + calls?.push(ids.length); + return rows.filter((r) => ids.includes(r.msgId)); + }, + }, + }) as SessionStore; + } + + const N_FILLER_BEFORE = 5; + function fixture() { + const t1 = msg("t1", "tool_result", bigText(7), { toolCallId: "call_1", toolName: "query", contentType: "tool-result" }); + const originals: CoreMessage[] = [ + ...Array.from({ length: N_FILLER_BEFORE }, (_, i) => msg(`f${i}`, "user", `filler turn ${i} padding words here`)), + t1, + ...Array.from({ length: N_FILLER_BEFORE }, (_, i) => msg(`g${i}`, "user", `trailing filler ${i} padding words`)), + ]; + const session: Session = { + id: "s-5395", + state: { blocks: [{ active: true, blockId: "blk-1", effectiveMessageIds: originals.map((m) => m.id!) }], messageRefs: { byRaw: {}, byRef: {} } }, + metadata: {}, + } as unknown as Session; + return { t1, originals, session }; + } + function makeOpts(logs?: LogLine[]): ReconcileOptions & { mode: "repair" | "warn" } { + return { + sessionId: "s-5395", + mode: "repair", + log: logs ? (level: string, m: string) => logs.push({ level, msg: m }) : undefined, + }; + } + /** Pass 2 wire: same history, t1 replaced by the host-pruned variant under a RE-MINTED id. */ + function prunedPass(originals: CoreMessage[], t1: CoreMessage): CoreMessage[] { + return originals.map((m, i) => i === N_FILLER_BEFORE + ? msg("t1-pruned", "tool_result", pruned(t1.text!), { toolCallId: "call_1_REMINTED", toolName: "query", contentType: "tool-result" }) + : m); + } + + test("repair mode: prune drift converges in ONE pass — rewrite + ledger event + log line", () => { + const { t1, originals, session } = fixture(); + const store = storeWithRows([{ seq: 1, msgId: "t1", content: JSON.stringify(t1) }]); + _setStoreForTest(store); + const logs: LogLine[] = []; + reconcileFoldCoverage(session, originals, makeOpts(logs)); + assert.equal(conflictEventsOf(session).length, 0, "clean seed pass records nothing"); + const r2 = reconcileFoldCoverage(session, prunedPass(originals, t1), makeOpts(logs)); + assert.equal(r2.kind, "reanchored"); + assert.equal(r2.byPrune, 1); + assert.equal(r2.unmatched, 0, "the permanent residual is gone"); + const eff = (session.state.blocks[0] as { effectiveMessageIds: string[] }).effectiveMessageIds; + assert.ok(eff.includes("t1-pruned"), "block rewritten onto the pruned id"); + assert.ok(!eff.includes("t1"), "old id retired from coverage"); + const events = conflictEventsOf(session).filter((e) => e.kind === "host-content-mutation"); + assert.equal(events.length, 1, "fix B: the double-compressor evidence lands in the ledger"); + assert.match(events[0].detail, /byte-verified sentinel splice/); + assert.ok(logs.some((l) => /by pruner-shape byte verification/.test(l.msg)), "drift line names the channel"); + }); + + test("second pass after re-anchor: clean resend, NO new ledger events (convergence — the bug was non-convergence)", () => { + const { t1, originals, session } = fixture(); + _setStoreForTest(storeWithRows([{ seq: 1, msgId: "t1", content: JSON.stringify(t1) }])); + const wire = prunedPass(originals, t1); + reconcileFoldCoverage(session, originals, makeOpts()); + reconcileFoldCoverage(session, wire, makeOpts()); + const before = conflictEventsOf(session).length; + const r3 = reconcileFoldCoverage(session, wire, makeOpts()); + assert.equal(r3.kind, "resend", "steady state after the one repair pass"); + assert.equal(r3.byPrune, 0); + assert.equal(conflictEventsOf(session).length, before, "self-limiting: no per-turn event spam"); + }); + + test("warn mode: counted but no repair; blocks untouched; ledger still lit", () => { + const { t1, originals, session } = fixture(); + _setStoreForTest(storeWithRows([{ seq: 1, msgId: "t1", content: JSON.stringify(t1) }])); + const before = JSON.stringify((session.state.blocks[0] as { effectiveMessageIds: string[] }).effectiveMessageIds); + reconcileFoldCoverage(session, originals, makeOpts()); + const r2 = reconcileFoldCoverage(session, prunedPass(originals, t1), { ...makeOpts(), mode: "warn" }); + assert.equal(r2.kind, "unmatched", "warn mode never repairs"); + assert.equal(r2.byPrune, 1, "evidence still counted"); + assert.equal(JSON.stringify((session.state.blocks[0] as { effectiveMessageIds: string[] }).effectiveMessageIds), before, "blocks untouched"); + assert.equal(conflictEventsOf(session).filter((e) => e.kind === "host-content-mutation").length, 1, "visibility does not depend on repair mode"); + }); + + test("store unavailable: graceful degradation to honest unmatched, no ledger event", () => { + const { t1, originals, session } = fixture(); + _setStoreForTest(new SessionStore({ enabled: false })); + reconcileFoldCoverage(session, originals, makeOpts()); + const r2 = reconcileFoldCoverage(session, prunedPass(originals, t1), makeOpts()); + assert.equal(r2.byPrune, 0, "no stored original → no guess"); + assert.equal(r2.unmatched, 1); + assert.equal(conflictEventsOf(session).length, 0, "unverified mutation is not confirmed evidence"); + }); + + test("no marker on the wire: zero storage reads (steady-state contract)", () => { + const { t1, originals, session } = fixture(); + const calls: number[] = []; + _setStoreForTest(storeWithRows([{ seq: 1, msgId: "t1", content: JSON.stringify(t1) }], calls)); + reconcileFoldCoverage(session, originals, makeOpts()); + assert.deepEqual(calls, [], "a marker-free pass never touches the index"); + }); +});