diff --git a/src/fold-reconcile.ts b/src/fold-reconcile.ts index aca38a6913..2475a0c657 100644 --- a/src/fold-reconcile.ts +++ b/src/fold-reconcile.ts @@ -199,6 +199,10 @@ const METADATA_TRUNC_NOTED = "foldTruncationNoted"; * resent wire is a prefix-cut of the pre-rewind wire). Same benign class as * head truncation; a distinct key so the log can name which end moved. */ const METADATA_TAIL_TRUNC_NOTED = "foldTailTruncationNoted"; +/** #5715: one-per-episode info latch for the surviving-direct-ID-majority + * partial-loss verdict (cleared with the rest of the drift state on recovery, + * like the #3641/#3724 benign latches). */ +const METADATA_MAJORITY_LOSS_NOTED = "foldMajorityLossNoted"; /** #3641: the wire order frozen at the moment the drift episode began — the * baseline against which truncation-vs-replacement is decided. */ const METADATA_EPISODE_ORDER = "foldEpisodeOrder"; @@ -338,6 +342,7 @@ function resetFoldDriftState(session: Session): void { delete md[METADATA_SHAPE_NOTED]; delete md[METADATA_TRUNC_NOTED]; delete md[METADATA_TAIL_TRUNC_NOTED]; + delete md[METADATA_MAJORITY_LOSS_NOTED]; delete md[METADATA_EPISODE_ORDER]; // #5142: the expected-rebase RECORD itself (METADATA_EXPECTED_REBASE) is // id-level truth and survives episodes on purpose; only its one-shot log @@ -1697,8 +1702,11 @@ export function reconcileFoldCoverage(session: Session, msgs: CoreMessage[], opt const blocks = (session.state?.blocks ?? []) as BlockLike[]; // Active coverage first (the anchor cap's survivor order, #2334), then the // retained view-deactivated lineage re-fed into the claim ladder (#4050); - // see recoveryCandidateIds for what is excluded and why. - const covered = coveredIdsOf(blocks); + // see recoveryCandidateIds for what is excluded and why. activeCovered keeps + // the active-only caliber intact (a separate object, never mutated) so the + // #5715 surviving-majority test below can run on live substrate alone. + const activeCovered = coveredIdsOf(blocks); + const covered = new Set(activeCovered); for (const id of recoveryCandidateIds(blocks)) covered.add(id); if (covered.size === 0) { resetFoldDriftState(session); @@ -2166,6 +2174,39 @@ export function reconcileFoldCoverage(session: Session, msgs: CoreMessage[], opt && plan.nearDupResidual.length === 0 && classCarryingResidual.every((id) => absentSet.has(id)) && tailTruncated; + // #5715: a strict majority of hard-covered ids still PRESENT VERBATIM on + // the wire is the opposite of wholesale replacement — the fold substrate + // is alive. The verdict classifier above only sees claims==0 + unmatched>0 + // and never counts the surviving direct matches, so a handful of interior + // edits/deletions (neither a head cut nor a tail rewind) read as total + // drift and, after FOLD_DRIFT_ESCALATE_PASSES, falsely latch epoch-confirm + // and pause compression on a healthy session. We deliberately do NOT relax + // totalDrift itself: the #3641 drift streak + frozen witness are what keep + // a genuine mid-history edit reading as honest loss (zombie accrual) + // rather than sanctioned truncation (#4050/#2695). The surviving majority + // only voids the TERMINAL verdict (below). The base is ACTIVE coverage only + // (the coveredIdsOf caliber), NOT the full `covered`: the #4050 view- + // deactivated lineage re-fed via recoveryCandidateIds is recoverable-but- + // gone, and its legitimate post-rewind/post-drift absence must never be able + // to dilute a healthy active majority below the bar (#5715 field report). + // Denominators match the per-block coverage (separators / expected rebases / + // reasoning cores excluded); the bar is >= MIN_RESYNC_RUN and > half. + // Genuine wholesale replacement has ~0 directly-present ACTIVE covered ids, + // so this can never mask a real collapse. + let coveredHard = 0; + let presentHard = 0; + for (const id of activeCovered) { + if (isResponsesTurnSeparatorId(id) || expected[id] !== undefined || anchors[id]?.c === "reasoning") continue; + coveredHard++; + if (byId.has(id)) presentHard++; + } + const hardDirectMajority = presentHard >= MIN_RESYNC_RUN && 2 * presentHard > coveredHard; + // #5715: a strict direct-ID majority proves the fold substrate is alive on + // the wire — any pending epoch-confirm latch is stale (the histories + // realigned) and clears immediately, whether or not this pass still carries + // residual loss (a partial restore keeps totalDrift true, so the normal + // !totalDrift reset below would never fire for it). + if (hardDirectMajority && epochConfirmPending(session)) resetFoldDriftState(session); const totalDrift = plan.claims.size === 0 && realUnmatched.length > 0 && !reasoningOnlyDrop && !markerChurnExplained && !shapeExplained && !truncationExplained && !tailTruncationExplained; // Classify before reaping: the epoch-confirm gate promises to retain the @@ -2362,7 +2403,11 @@ export function reconcileFoldCoverage(session: Session, msgs: CoreMessage[], opt } session.metadata[METADATA_DRIFT_STREAK] = streak; if (prevStreak === 0) session.metadata[METADATA_DRIFT_SINCE] = Date.now(); - if (streak >= FOLD_DRIFT_ESCALATE_PASSES && nonReasoningUnmatched >= FOLD_DRIFT_ESCALATE_MIN_UNMATCHED + // #5715: a strict direct-ID majority means the fold substrate is alive + // on the wire — this is partial loss, not wholesale replacement, so the + // terminal epoch-confirm verdict (and its compression pause) must not + // fire even though the #2193 streak above has accrued. + if (!hardDirectMajority && streak >= FOLD_DRIFT_ESCALATE_PASSES && nonReasoningUnmatched >= FOLD_DRIFT_ESCALATE_MIN_UNMATCHED && session.metadata[METADATA_DRIFT_ESCALATED] !== true) { session.metadata[METADATA_DRIFT_ESCALATED] = true; // #2709: take a ledger action at the destruction point (not just log) — attribute @@ -2417,6 +2462,21 @@ export function reconcileFoldCoverage(session: Session, msgs: CoreMessage[], opt opts.log("info", `${tag}[fold-reconcile] ${realUnmatched.length} covered id(s) missing with no anchor match${expectedNote}, but this pass stripped ${opts.markerStripped} raw marker artifact(s) — covered ids minted from marker-laden bytes churn once the strip engine cleans the resent history; benign on stateless resend (content still on the wire, re-folds re-cover), tolerated (#2815/#2789)`); } + } else if (hardDirectMajority && nonReasoningUnmatched >= FOLD_DRIFT_ESCALATE_MIN_UNMATCHED + && !shapeExplained && !truncationExplained && !tailTruncationExplained) { + // #5715: a surviving direct-ID majority AT THE MASS BAR is PARTIAL + // loss, not the "fold silently lost" the generic warn below names — + // report it once per episode at info level (acceptance, not repair). + // Sub-mass-bar single edits keep the honest per-pass warn below. The + // #3641 verdict above already kept this from latching epoch-confirm. + // Already-explained episodes (shape churn / head / tail truncation) + // own their own one-per-episode note — reporting them here too would + // print a second line mislabeling a head/tail cut as "interior" + // loss, so they fall through to the original per-pass warn. + if (session.metadata[METADATA_MAJORITY_LOSS_NOTED] !== true) { + session.metadata[METADATA_MAJORITY_LOSS_NOTED] = true; + opts.log("info", `${tag}[fold-reconcile] ${realUnmatched.length} covered id(s) missing but ${presentHard}/${coveredHard} hard-covered id(s) still ride verbatim on the wire — partial interior loss, fold substrate healthy, no epoch confirmation (#5715)`); + } } else if (session.metadata[METADATA_DRIFT_ESCALATED] !== true) { // #2297: once the episode escalated, the single error line IS the // report — repeating this warn per pass contradicts the #2193 diff --git a/tests/fold-anchor-doctrine.test.ts b/tests/fold-anchor-doctrine.test.ts index 50392e4eec..ffbd7f8b52 100644 --- a/tests/fold-anchor-doctrine.test.ts +++ b/tests/fold-anchor-doctrine.test.ts @@ -292,3 +292,188 @@ describe("honesty gates survive the doctrine (no wholesale silencing)", () => { assert.notEqual(session.metadata[METADATA_DRIFT_ESCALATED], true, "single-cell churn never mass-escalates"); }); }); + +describe("#5715 partial interior loss with a surviving direct-ID majority is NOT total drift", () => { + // 30-turn history, every turn folded in. The host drops TEN INTERIOR turns + // (neither a head cut nor a tail rewind) while the other TWENTY ride + // verbatim on the wire. The #3641 verdict classifier only saw + // claims==0 + unmatched>0 and never counted the twenty surviving DIRECT + // matches, so three such passes latched epoch-confirm and paused + // compression on a healthy session (#5715 field: 1162/1171 direct-present, + // ten interior missing). A strict direct-ID majority is the opposite of + // wholesale replacement and must not read as substrate destruction. + function interiorLossFixture(): { old: CoreMessage[]; covered: string[]; wire: CoreMessage[] } { + const old: CoreMessage[] = []; + for (let i = 0; i < 30; i++) { + old.push(msg(`t${i}`, i % 2 ? "user" : "assistant", + `history turn ${i} with distinctive vocabulary marker word ${i} for shingle coverage`)); + } + const covered = old.map((m) => m.id as string); + const removed = new Set([4, 6, 8, 10, 12, 14, 16, 18, 20, 22]); // ten INTERIOR turns + const wire = old.filter((_, i) => !removed.has(i)); + return { old, covered, wire }; + } + + test("ten interior turns dropped, twenty verbatim: no escalation, no epoch-confirm latch", () => { + const { old, covered, wire } = interiorLossFixture(); + const session = fakeSession(covered, old, "dsh"); + for (let pass = 0; pass < 4; pass++) reconcileFoldCoverage(session, wire, repair()); + assert.notEqual(session.metadata[METADATA_DRIFT_ESCALATED], true, + "a surviving strict direct-ID majority is not substrate destruction"); + assert.equal(epochConfirmPending(session), false, + "partial interior loss must not ask for an epoch confirmation"); + const blocks = (session.state as { blocks: Array<{ blockId?: string }> }).blocks; + assert.ok(blocks.some((b) => b.blockId === "blk-1"), "the snapshot block is retained, not reaped"); + }); + + test("the same interior-loss shape is tolerated in proxy mode too (lane-agnostic)", () => { + const { old, covered, wire } = interiorLossFixture(); + const session = fakeSession(covered, old); // no pluginAgent -> proxy mode + for (let pass = 0; pass < 4; pass++) reconcileFoldCoverage(session, wire, repair()); + assert.equal(epochConfirmPending(session), false, + "direct-ID majority continuity is identity evidence on every lane, not just DSH"); + }); + + test("an already-pending stale latch clears once the healthy majority is back", () => { + const { old, covered } = interiorLossFixture(); + const session = fakeSession(covered, old, "dsh"); + // A persisted pending latch whose drift streak was already cleared + // (#5715 second site: prevStreak===0 must not strand the pause). + session.metadata["foldEpochConfirmPending"] = true; + assert.equal(epochConfirmPending(session), true, "precondition: the latch is pending"); + // the original history is back on the wire wholesale -> a clean realigned pass + reconcileFoldCoverage(session, old, repair()); + assert.equal(epochConfirmPending(session), false, + "strong direct continuity on an already-pending session recovers compression"); + }); + + test("an explained head cut keeps its own note — the majority note stays silent", () => { + // 30 fully-covered turns; the host drops the OLDEST ten (a head cut — + // truncationExplained territory, #2695) while twenty ride verbatim, + // which is ALSO a strict direct-ID majority. The #2695 note owns this + // episode: the #5715 majority note must not fire a second line + // mislabeling the head cut as "interior" loss. + const old: CoreMessage[] = []; + for (let i = 0; i < 30; i++) { + old.push(msg(`t${i}`, i % 2 ? "user" : "assistant", + `history turn ${i} with distinctive vocabulary marker word ${i} for shingle coverage`)); + } + const session = fakeSession(old.map((m) => m.id as string), old); + reconcileFoldCoverage(session, old, repair()); // warm pass: coverage established + const logs: string[] = []; + for (let pass = 0; pass < 4; pass++) reconcileFoldCoverage(session, old.slice(10), repair((l, m) => logs.push(`${l}: ${m}`))); + assert.ok(logs.some((line) => line.startsWith("info") && /truncat/i.test(line)), + "the #2695 truncation note still names the head cut"); + assert.ok(!logs.some((line) => line.includes("partial interior loss")), + "an already-explained episode is not double-reported as interior loss"); + }); + + test("genuine wholesale replacement STILL escalates (the gate did not weaken detection)", () => { + const { old, covered } = interiorLossFixture(); + const session = fakeSession(covered, old, "dsh"); + const foreign: CoreMessage[] = []; + for (let i = 0; i < 14; i++) foreign.push(msg(`x${i}`, i % 2 ? "user" : "assistant", + `unrelated fresh content ${i} about a brand new topic entirely`)); + for (let pass = 0; pass < 4; pass++) reconcileFoldCoverage(session, foreign, repair()); + assert.equal(session.metadata[METADATA_DRIFT_ESCALATED], true, "detection intact: the collapse is still flagged"); + assert.equal(epochConfirmPending(session), true, "wholesale replacement still asks for an epoch confirmation"); + }); + + // #5715 field report (independent 0.1.213/Linux-DSH confirmation): the + // surviving-majority base must be ACTIVE coverage alone. A successful + // rewind deactivates an old fold (#4050 lineage) whose ids legitimately + // leave the wire; counting those absent inactive recovery candidates in + // the denominator dilutes a healthy active direct-ID majority below the + // bar and re-latches epoch-confirm on a live session. + test("absent inactive recovery candidates cannot dilute a healthy active majority", () => { + const active: CoreMessage[] = []; + for (let i = 0; i < 20; i++) { + active.push(msg(`a${i}`, i % 2 ? "user" : "assistant", + `live turn ${i} alpha distinctive vocabulary ${i} shingle coverage body`)); + } + const rewound: CoreMessage[] = []; + for (let i = 0; i < 30; i++) { + rewound.push(msg(`r${i}`, i % 2 ? "user" : "assistant", + `retired rewound turn ${i} beta distinctive vocabulary ${i} long deactivated`)); + } + const anchors: Record = {}; + for (const m of [...active, ...rewound]) anchors[m.id as string] = anchorOf(m); + const droppedActive = new Set([3, 14]); // two INTERIOR live turns lost + const wire = [...active.filter((_, i) => !droppedActive.has(i)), + ...Array.from({ length: 6 }, (_, i) => msg(`n${i}`, i % 2 ? "user" : "assistant", `fresh turn ${i} gamma vocabulary ${i}`))]; + // Order backbone sandwiches the deactivated block between two LIVE halves + // so its absence is interior, not a head/tail truncation run. + const order = [...active.slice(0, 10).map((m) => m.id as string), + ...rewound.map((m) => m.id as string), + ...active.slice(10).map((m) => m.id as string)]; + const session = { + id: "s-doctrine", + metadata: { foldAnchors: anchors, foldAnchorOrder: order, pluginAgent: "dsh" }, + state: { + blocks: [ + { active: true, blockId: "blk-live", effectiveMessageIds: active.map((m) => m.id as string), directMessageIds: active.map((m) => m.id as string) }, + { active: false, blockId: "blk-rewound", effectiveMessageIds: rewound.map((m) => m.id as string), directMessageIds: rewound.map((m) => m.id as string) }, + ], + messageRefs: { byRaw: {}, byRef: {} }, + }, + } as unknown as Session; + for (let pass = 0; pass < 4; pass++) reconcileFoldCoverage(session, wire, repair()); + assert.ok((session.metadata["foldDriftStreak"] as number ?? 0) >= 3, + "precondition: drift WAS detected (total-loss verdict held, no explainer) — the gate, not an explainer, decides"); + assert.equal(epochConfirmPending(session), false, + "absent inactive recovery candidates must not mask a healthy active direct-ID majority"); + assert.notEqual(session.metadata[METADATA_DRIFT_ESCALATED], true, + "partial active loss plus legitimate rewind residuals is not substrate destruction"); + }); + + // #5715 field report negative control: a "surviving majority" made ONLY of + // reasoning cores must never satisfy the bar — reasoning is excluded from + // both numerator and denominator, so a genuine HARD (text/tool) loss still + // escalates even when many thinking cores ride verbatim on the wire. + test("reasoning-only survivors do not mask a hard (text) loss", () => { + const text: CoreMessage[] = []; + for (let i = 0; i < 20; i++) { + text.push(msg(`t${i}`, i % 2 ? "user" : "assistant", + `hard turn ${i} delta distinctive vocabulary ${i} shingle body here`)); + } + const reasoning: CoreMessage[] = []; + for (let i = 0; i < 20; i++) { + reasoning.push(msg(`q${i}`, "assistant", `thinking core ${i} epsilon vocabulary ${i}`, { contentType: "reasoning" })); + } + const anchors: Record = {}; + for (const m of [...text, ...reasoning]) anchors[m.id as string] = anchorOf(m); + const droppedText = new Set([1, 3, 5, 7, 9, 11, 13, 15, 17, 19]); // ten INTERIOR hard turns lost + const wire = [...text.filter((_, i) => !droppedText.has(i)), ...reasoning]; + const session = { + id: "s-doctrine", + metadata: { foldAnchors: anchors, foldAnchorOrder: [...text, ...reasoning].map((m) => m.id as string), pluginAgent: "dsh" }, + state: { + blocks: [{ active: true, blockId: "blk-1", effectiveMessageIds: [...text, ...reasoning].map((m) => m.id as string), directMessageIds: [...text, ...reasoning].map((m) => m.id as string) }], + messageRefs: { byRaw: {}, byRef: {} }, + }, + } as unknown as Session; + for (let pass = 0; pass < 4; pass++) reconcileFoldCoverage(session, wire, repair()); + assert.equal(epochConfirmPending(session), true, + "twenty surviving reasoning cores are not a surviving HARD majority — the text loss still escalates"); + assert.equal(session.metadata[METADATA_DRIFT_ESCALATED], true, + "excluding reasoning from the majority base keeps detection honest"); + }); + + // #5715 tie-breaker: exactly HALF the active hard ids present is NOT a clear + // surviving majority (strict > half required). A repeated exactly-half loss + // is itself a strong anomaly — under-detecting a real 50% collapse is worse + // than one confirmable epoch prompt, so the bar stays strict at the boundary. + test("exactly half present is not a clear majority (strict boundary)", () => { + const old: CoreMessage[] = []; + for (let i = 0; i < 20; i++) { + old.push(msg(`t${i}`, i % 2 ? "user" : "assistant", + `half turn ${i} zeta distinctive vocabulary ${i} shingle coverage`)); + } + const session = fakeSession(old.map((m) => m.id as string), old, "dsh"); + const removed = new Set([1, 3, 5, 7, 9, 11, 13, 15, 17, 19]); // exactly ten of twenty + const wire = old.filter((_, i) => !removed.has(i)); + for (let pass = 0; pass < 4; pass++) reconcileFoldCoverage(session, wire, repair()); + assert.equal(epochConfirmPending(session), true, + "ten-of-twenty present is not a strict majority — the terminal verdict may still fire"); + }); +});