From 041fa98e91d042f1c017ef7b17f70a6b7765188b Mon Sep 17 00:00:00 2001 From: ci-check Date: Sat, 7 Nov 2026 02:51:41 +0800 Subject: [PATCH 1/6] kernel: reject range folds that would merge blocks beyond the requested ref window (#5830) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A plain m-ref range carries one summary describing exactly [startRef..endRef], but projectUnit consumed any same-tier active block whose visible representation fell inside the RESOLVED span. After a folded historical ref snaps to its inheriting block's anchor (unbounded view-index jump), the span can sweep blocks whose coverage lies outside the window, silently replacing their summaries with one that does not cover their span (#5830). Hard gate in projectUnit (shared by apply/recommend/acp_status per #3236): a plain range consuming an active block with out-of-window coverage is fatal (kind 'window') — whole batch rejects atomically, zero commits, error names offenders + remedy. Unmappable coverage fails closed. Exempt: block-boundary distillation, no-op resubmits. report.ts flags the new kind for acp_status consistency. Regression: kernel/tests/issue5830-merge-window-guard.test.ts (repro verified red pre-fix + 3 controls). Kernel 0.0.182 -> 0.0.183. --- kernel/package.json | 2 +- kernel/src/report.ts | 2 + kernel/src/unit-projection.ts | 59 +++++- .../issue5830-merge-window-guard.test.ts | 174 ++++++++++++++++++ 4 files changed, 235 insertions(+), 2 deletions(-) create mode 100644 kernel/tests/issue5830-merge-window-guard.test.ts diff --git a/kernel/package.json b/kernel/package.json index ab632703e5..45eb3f8d39 100644 --- a/kernel/package.json +++ b/kernel/package.json @@ -1,6 +1,6 @@ { "name": "acp-kernel", - "version": "0.0.182", + "version": "0.0.183", "description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.", "license": "MIT", "author": "ranxianglei", diff --git a/kernel/src/report.ts b/kernel/src/report.ts index 29e10a2767..c6a034fafb 100644 --- a/kernel/src/report.ts +++ b/kernel/src/report.ts @@ -470,6 +470,8 @@ function renderUncompressedRanges( return "\u26a0 not foldable: protected zone only"; if (proj.fatal?.kind === "split") return `\u26a0 not foldable: would split ${splitDescOf(proj)}`; + if (proj.fatal?.kind === "window") + return "\u26a0 not foldable: would merge block(s) beyond the requested ref window"; if (proj.filteredIds.length === 0 && proj.consumedBlockIds.length === 0) return "\u26a0 not foldable: nothing new to fold"; return null; diff --git a/kernel/src/unit-projection.ts b/kernel/src/unit-projection.ts index e5b820e25d..d5e391260f 100644 --- a/kernel/src/unit-projection.ts +++ b/kernel/src/unit-projection.ts @@ -8,7 +8,9 @@ import { buildIndexByMessageId, resolveBoundaries, blockVisibleInRange, + parseBoundary, } from "./boundaries.js"; +import { indexToRef, refToIndex } from "./refs.js"; import { isSummaryMessageId } from "./prune.js"; import { collectFailedCompressCallIds, @@ -86,7 +88,7 @@ export interface UnitProjectionInput { } export interface UnitProjectionFatal { - kind: "zone" | "split"; + kind: "zone" | "split" | "window"; error: Error; } @@ -249,6 +251,61 @@ export function projectUnit(input: UnitProjectionInput): UnitProjection { } } + // #5830: the supplied summary describes exactly the requested ref window + // [startRef..endRef]. A plain message-ref range that would CONSUME an active + // block whose coverage extends outside that window replaces that block's + // wider-span summary with one that never saw part of it — silent + // active-summary coverage loss (incident: one tail-range summary left + // standing over a merged span back to the conversation start). Block- + // boundary merges (bN..bM) are exempt by contract — they exist to absorb + // the boundary blocks' coverage and the caller named the blocks. Pure + // resubmits (no new direct messages) are exempt too: they create no block, + // so there is no replacement to guard against (#4521 no-op class). + if (!isBlockBoundary && consumedBlockIds.length > 0 && filteredIds.length > 0) { + const startBoundary = parseBoundary(input.startRef); + const endBoundary = parseBoundary(input.endRef); + if (startBoundary?.kind === "message" && endBoundary?.kind === "message") { + const windowLo = Math.min(startBoundary.numericId, endBoundary.numericId); + const windowHi = Math.max(startBoundary.numericId, endBoundary.numericId); + const offenders: string[] = []; + for (const consumedId of consumedBlockIds) { + const block = blockById(input.state, consumedId); + if (!block || block.effectiveMessageIds.length === 0) continue; + let minNum: number | null = null; + let maxNum: number | null = null; + let outOfWindow = false; + for (const mid of block.effectiveMessageIds) { + const ref = input.state.messageRefs.byRaw[mid]; + const num = ref === undefined ? null : refToIndex(ref); + if (num === null) { + outOfWindow = true; // unmappable coverage: containment unprovable + break; + } + if (num < windowLo || num > windowHi) outOfWindow = true; + if (minNum === null || num < minNum) minNum = num; + if (maxNum === null || num > maxNum) maxNum = num; + } + if (outOfWindow) { + offenders.push( + minNum !== null && maxNum !== null + ? `${consumedId} [${indexToRef(minNum)}..${indexToRef(maxNum)}]` + : `${consumedId} [unmapped coverage]`, + ); + } + } + if (offenders.length > 0) { + return finish({ + fatal: { + kind: "window", + error: new Error( + `Range ${input.startRef}..${input.endRef} would merge ${offenders.join(", ")}, whose existing coverage extends beyond the requested ref window (${indexToRef(windowLo)}..${indexToRef(windowHi)}) — folding them would replace their summaries with one that does not cover their span. To merge them deliberately, reference the block ids directly (e.g. compress bN..bM); otherwise narrow the range so its endpoints bound the blocks' coverage.`, + ), + }, + }); + } + } + } + const mediaExcluded = directMessageIds.filter((id) => { const msg = msgById(id); return !!msg && hasUnrecoverableMediaPayload(msg); diff --git a/kernel/tests/issue5830-merge-window-guard.test.ts b/kernel/tests/issue5830-merge-window-guard.test.ts new file mode 100644 index 0000000000..bb9eb30a25 --- /dev/null +++ b/kernel/tests/issue5830-merge-window-guard.test.ts @@ -0,0 +1,174 @@ +import { describe, it } from "node:test"; +import assert from "node:assert/strict"; +import { createCore } from "../src/compress.js"; +import { + blockById, + coveredMessageIds, + createInitialState, +} from "../src/state.js"; +import { defaultConfig } from "../src/config.js"; +import { summaryMessageId } from "../src/prune.js"; +import type { CompressionState, CoreMessage } from "../src/types.js"; + +// #5830: a plain message-ref range must never merge an active block whose +// coverage extends beyond the requested ref window [startRef..endRef] — the +// supplied summary describes exactly that window, so such a merge replaces +// the block's wider-span summary with one that never saw part of it (the +// incident left b27 covering 1566 messages with only the last range's +// summary; prior blocks silently deactivated). +// +// Fixture = a reachable production sequence (full-resend host; the plugin +// lane judges on raw history per #3236's applyView): stage 1 builds two +// active blocks with OVERLAPPING coverage (a full-raw fold starting inside +// an existing T2's territory); stage 2 fires a range whose stale inherited +// startRef snaps to the T2's head anchor while its end is fresh, so the +// resolved span sweeps the overlapping T1 below the requested window. + +const LONG = + "Synthetic historical content, safe for public reproduction. ".repeat(150); +const sum = (label: string) => + `${label}: synthetic stage summary capturing the folded range. `.padEnd(72, "."); +const config = defaultConfig(255000, { + preserveRecentMessages: 0, + preserveRecentTokens: 0, +} as never); + +function mkMsg(id: string): CoreMessage { + return { id, role: "user", contentType: "text", text: LONG }; +} + +type Ranges = Parameters["applyCompression"]>[0]["ranges"]; + +function buildStage1() { + const core = createCore(); + const messages: CoreMessage[] = []; + const initial = createInitialState(); + for (let i = 1; i <= 14; i++) { + const id = `u${String(i).padStart(2, "0")}`; + messages.push(mkMsg(id)); + const ref = `m${String(i).padStart(5, "0")}`; + initial.messageRefs.byRaw[id] = ref; + initial.messageRefs.byRef[ref] = id; + } + let state: CompressionState = initial; + const fold = (ranges: Ranges) => { + const res = core.applyCompression({ messages, state, config, ranges }); + if (res.result.errors.length !== 0) { + throw new Error(`stage-1 fold failed: ${JSON.stringify(res.result.errors)}`); + } + state = res.state; + return res; + }; + fold([{ startRef: "m00001", endRef: "m00002", summary: sum("b1") }]); + fold([{ startRef: "m00003", endRef: "m00004", summary: sum("b2") }]); + fold([{ startRef: "b1", endRef: "b2", summary: sum("b3-distillation") }]); + const b3 = blockById(state, "b3"); + assert.equal(b3?.tier, 2, "distillation must produce a T2"); + assert.ok(b3?.active === true, "b3 must stay active"); + // Full-raw fold over the T2's territory: b3's anchor sits inside the span + // but b3 is T2 (target tier of a plain range is 1), so it survives — b4 + // ends up covering [u01..u12] and OVERLAPS b3's [u01..u04]. Both stay + // active: the stage-1 overlap product. + fold([{ startRef: "m00001", endRef: "m00012", summary: sum("b4-fullraw") }]); + const b4 = blockById(state, "b4"); + assert.equal(b4?.tier, 1, "plain fold must produce a T1"); + assert.ok( + b4?.active === true && b3.active === true, + "stage 1 must leave both blocks active with overlapping coverage", + ); + return { core, messages, state }; +} + +/** The pruned view a normal host sends after stage 1: the two rendered + * summaries at their head anchors, then the fresh uncovered tail. */ +function prunedView(messages: CoreMessage[]): CoreMessage[] { + return [ + { + id: summaryMessageId("b3"), + role: "system", + contentType: "text", + text: "[Compressed conversation section] S-b3", + }, + { + id: summaryMessageId("b4"), + role: "system", + contentType: "text", + text: "[Compressed conversation section] S-b4", + }, + messages[12]!, + messages[13]!, + ]; +} + +function lostCoverage(before: Set, state: CompressionState): string[] { + const after = coveredMessageIds(state); + return [...before].filter((id) => !after.has(id)); +} + +describe("#5830 plain-range merge window guard", () => { + it("stale-inherited start + fresh end: a sweep that swallows an out-of-window block is rejected atomically with zero commits", () => { + const { core, messages, state } = buildStage1(); + const before = coveredMessageIds(state); + const res = core.applyCompression({ + messages: prunedView(messages), + state, + config, + ranges: [{ startRef: "m00002", endRef: "m00014", summary: sum("tail-only") }], + }); + assert.equal(res.result.blocksCreated, 0, JSON.stringify(res.result)); + assert.equal(res.result.errors.length, 1, JSON.stringify(res.result.errors)); + assert.match( + res.result.errors[0]!, + /extends beyond the requested ref window/i, + ); + assert.match(res.result.errors[0]!, /b4/, "the offender block must be named"); + assert.deepEqual(lostCoverage(before, res.state), [], "no coverage may be lost"); + assert.ok(blockById(res.state, "b4")!.active, "b4 must stay active"); + assert.ok(blockById(res.state, "b3")!.active, "b3 must stay active"); + }); + + it("control: a plain-range merge whose window CONTAINS the consumed block's coverage still lands", () => { + const { core, messages, state } = buildStage1(); + const res = core.applyCompression({ + messages: prunedView(messages), + state, + config, + ranges: [{ startRef: "m00001", endRef: "m00014", summary: sum("legit-wide") }], + }); + assert.equal(res.result.errors.length, 0, JSON.stringify(res.result.errors)); + assert.equal(res.result.blocksCreated, 1, JSON.stringify(res.result)); + assert.equal( + blockById(res.state, "b4")!.active, + false, + "b4 [u01..u12] lies inside window [1..14] — legitimate absorption", + ); + }); + + it("control: a fully-covered resubmit changes nothing — no block, no coverage loss (pre-fix: refold-guidance error, NOT a silent merge)", () => { + const { core, messages, state } = buildStage1(); + const before = coveredMessageIds(state); + const res = core.applyCompression({ + messages: prunedView(messages), + state, + config, + ranges: [{ startRef: "m00002", endRef: "m00004", summary: sum("resubmit") }], + }); + assert.equal(res.result.blocksCreated, 0, JSON.stringify(res.result)); + assert.deepEqual(lostCoverage(before, res.state), []); + assert.ok( + blockById(res.state, "b4")!.active && blockById(res.state, "b3")!.active, + ); + }); + + it("control: block-boundary distillation across the same blocks is untouched by the gate", () => { + const { core, messages, state } = buildStage1(); + const res = core.applyCompression({ + messages: prunedView(messages), + state, + config, + ranges: [{ startRef: "b3", endRef: "b4", summary: sum("distill-mixed") }], + }); + assert.equal(res.result.errors.length, 0, JSON.stringify(res.result.errors)); + assert.equal(res.result.blocksCreated, 1, JSON.stringify(res.result)); + }); +}); From 3c4f8d5ea7eb3e9b44d226472f9dd08df03b7610 Mon Sep 17 00:00:00 2001 From: ci-check Date: Sat, 7 Nov 2026 03:06:47 +0800 Subject: [PATCH 2/6] =?UTF-8?q?ci:=20sync=20lockfiles=20to=20kernel=200.0.?= =?UTF-8?q?183=20=E2=80=94=20lock-sync=20regen=20after=20the=20version=20b?= =?UTF-8?q?ump=20(#5835)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- kernel/package-lock.json | 4 ++-- package-lock.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/kernel/package-lock.json b/kernel/package-lock.json index eddb848f06..d56ced4841 100644 --- a/kernel/package-lock.json +++ b/kernel/package-lock.json @@ -1,12 +1,12 @@ { "name": "acp-kernel", - "version": "0.0.182", + "version": "0.0.183", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "acp-kernel", - "version": "0.0.182", + "version": "0.0.183", "license": "MIT", "devDependencies": { "@types/node": "^22.0.0", diff --git a/package-lock.json b/package-lock.json index 9cb99d16c3..0d5c56cca3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -50,7 +50,7 @@ }, "kernel": { "name": "acp-kernel", - "version": "0.0.182", + "version": "0.0.183", "dev": true, "license": "MIT", "devDependencies": { From cd2a934ae8c4ab2ba8015c58748ff0a393fbebdb Mon Sep 17 00:00:00 2001 From: ci-check Date: Sat, 7 Nov 2026 03:49:06 +0800 Subject: [PATCH 3/6] =?UTF-8?q?kernel:=20refine=20merge-window=20guard=20?= =?UTF-8?q?=E2=80=94=20judge=20pair-widened=20spans=20when=20endpoints=20r?= =?UTF-8?q?esolve=20in=20place?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The literal-window containment check rejected legitimate folds whose span was extended by pair/reasoning boundary widening (#5531 stranded-pair recovery path): widened cells ride under the same summary by design, so when BOTH endpoints resolved in place (the requested message itself still occupies its slot), containment is now judged against the widened span computed over the range message refs. The #5830 producer stays fatal: an endpoint that resolved ELSEWHERE (stale inherited ref snapping to a distant inheriting-block anchor) holds the line at the requested window, as before. Unmappable coverage still fails closed either way. kernel 0.0.183 -> 0.0.184 (+ lockfile sync). --- kernel/package-lock.json | 4 ++-- kernel/package.json | 2 +- kernel/src/unit-projection.ts | 45 +++++++++++++++++++++++++++++++---- package-lock.json | 2 +- 4 files changed, 44 insertions(+), 9 deletions(-) diff --git a/kernel/package-lock.json b/kernel/package-lock.json index d56ced4841..4144191483 100644 --- a/kernel/package-lock.json +++ b/kernel/package-lock.json @@ -1,12 +1,12 @@ { "name": "acp-kernel", - "version": "0.0.183", + "version": "0.0.184", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "acp-kernel", - "version": "0.0.183", + "version": "0.0.184", "license": "MIT", "devDependencies": { "@types/node": "^22.0.0", diff --git a/kernel/package.json b/kernel/package.json index 45eb3f8d39..d26c24485f 100644 --- a/kernel/package.json +++ b/kernel/package.json @@ -1,6 +1,6 @@ { "name": "acp-kernel", - "version": "0.0.183", + "version": "0.0.184", "description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.", "license": "MIT", "author": "ranxianglei", diff --git a/kernel/src/unit-projection.ts b/kernel/src/unit-projection.ts index d5e391260f..e8ee00d24d 100644 --- a/kernel/src/unit-projection.ts +++ b/kernel/src/unit-projection.ts @@ -261,31 +261,64 @@ export function projectUnit(input: UnitProjectionInput): UnitProjection { // the boundary blocks' coverage and the caller named the blocks. Pure // resubmits (no new direct messages) are exempt too: they create no block, // so there is no replacement to guard against (#4521 no-op class). + // + // #5531: pair/reasoning boundary widening is the fold's OWN defined scope — + // the widened cells ride under the same summary by design, so when both + // endpoints resolved IN PLACE (the requested message itself still occupies + // its slot), containment is judged against the WIDENED span, not the + // literal window. What must stay fatal is the #5830 producer itself: an + // endpoint that RESOLVED ELSEWHERE (stale inherited ref snapping to a + // distant inheriting-block anchor) sweeps territory the summary never + // described regardless of widening — hold the line at the requested + // window then. Unmappable coverage fails closed either way (containment + // unprovable). if (!isBlockBoundary && consumedBlockIds.length > 0 && filteredIds.length > 0) { const startBoundary = parseBoundary(input.startRef); const endBoundary = parseBoundary(input.endRef); if (startBoundary?.kind === "message" && endBoundary?.kind === "message") { const windowLo = Math.min(startBoundary.numericId, endBoundary.numericId); const windowHi = Math.max(startBoundary.numericId, endBoundary.numericId); + const startRaw = input.state.messageRefs.byRef[startBoundary.raw]; + const endRaw = input.state.messageRefs.byRef[endBoundary.raw]; + const resolvedEndpointIds = [ + input.messages[resolved.startIndex]?.id, + input.messages[resolved.endIndex]?.id, + ]; + const resolutionInPlace = + startRaw !== undefined && + endRaw !== undefined && + resolvedEndpointIds.includes(startRaw) && + resolvedEndpointIds.includes(endRaw); + let spanLo = windowLo; + let spanHi = windowHi; + if (resolutionInPlace) { + for (const id of rangeMessageIds) { + const ref = input.state.messageRefs.byRaw[id]; + const num = ref === undefined ? null : refToIndex(ref); + if (num === null) continue; + if (num < spanLo) spanLo = num; + if (num > spanHi) spanHi = num; + } + } const offenders: string[] = []; for (const consumedId of consumedBlockIds) { const block = blockById(input.state, consumedId); if (!block || block.effectiveMessageIds.length === 0) continue; let minNum: number | null = null; let maxNum: number | null = null; - let outOfWindow = false; + let outOfSpan = false; for (const mid of block.effectiveMessageIds) { const ref = input.state.messageRefs.byRaw[mid]; const num = ref === undefined ? null : refToIndex(ref); if (num === null) { - outOfWindow = true; // unmappable coverage: containment unprovable + outOfSpan = true; // unmappable coverage: containment unprovable break; } - if (num < windowLo || num > windowHi) outOfWindow = true; + if (num < spanLo || num > spanHi) outOfSpan = true; if (minNum === null || num < minNum) minNum = num; if (maxNum === null || num > maxNum) maxNum = num; } - if (outOfWindow) { + if (outOfSpan) { offenders.push( minNum !== null && maxNum !== null ? `${consumedId} [${indexToRef(minNum)}..${indexToRef(maxNum)}]` @@ -298,7 +331,9 @@ export function projectUnit(input: UnitProjectionInput): UnitProjection { fatal: { kind: "window", error: new Error( - `Range ${input.startRef}..${input.endRef} would merge ${offenders.join(", ")}, whose existing coverage extends beyond the requested ref window (${indexToRef(windowLo)}..${indexToRef(windowHi)}) — folding them would replace their summaries with one that does not cover their span. To merge them deliberately, reference the block ids directly (e.g. compress bN..bM); otherwise narrow the range so its endpoints bound the blocks' coverage.`, + resolutionInPlace + ? `Range ${input.startRef}..${input.endRef} would merge ${offenders.join(", ")}, whose existing coverage lies outside the fold's span (${indexToRef(spanLo)}..${indexToRef(spanHi)}) — folding them would replace their summaries with one that does not cover their span. To merge them deliberately, reference the block ids directly (e.g. compress bN..bM); otherwise narrow the range.` + : `Range ${input.startRef}..${input.endRef} would merge ${offenders.join(", ")}, whose existing coverage extends beyond the requested ref window (${indexToRef(windowLo)}..${indexToRef(windowHi)}) — folding them would replace their summaries with one that does not cover their span. To merge them deliberately, reference the block ids directly (e.g. compress bN..bM); otherwise narrow the range so its endpoints bound the blocks' coverage.`, ), }, }); diff --git a/package-lock.json b/package-lock.json index 0d5c56cca3..df4e87298d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -50,7 +50,7 @@ }, "kernel": { "name": "acp-kernel", - "version": "0.0.183", + "version": "0.0.184", "dev": true, "license": "MIT", "devDependencies": { From 02ed9c926786dabe23ff038c6b004d36b4284056 Mon Sep 17 00:00:00 2001 From: ci-check Date: Sat, 7 Nov 2026 03:49:06 +0800 Subject: [PATCH 4/6] kernel: repair pi#199 fixture ledger + pin fail-closed unmapped-coverage rejection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The subtest-3 fixture numbered the pruned view fresh from nextIndex=1, which cannot model production: covered-but-pruned messages keep their original refs (ids are never re-minted), so their numbers sit inside the requested window even though the messages are gone. Seed an inherited ledger with the original numbering instead — the merge lands again. Add the companion negative pin (gate discipline #3617): the same shape with fresh numbering leaves b1's coverage unmappable in byRaw, so the fold must reject atomically with the [unmapped coverage] offender named. --- kernel/tests/regression-empty-rewrap.test.ts | 76 ++++++++++++++++++-- 1 file changed, 72 insertions(+), 4 deletions(-) diff --git a/kernel/tests/regression-empty-rewrap.test.ts b/kernel/tests/regression-empty-rewrap.test.ts index ff1a25dd82..55ee784f56 100644 --- a/kernel/tests/regression-empty-rewrap.test.ts +++ b/kernel/tests/regression-empty-rewrap.test.ts @@ -126,6 +126,25 @@ function withRefs( return state; } +// A production-shaped ledger: pruned messages KEEP their original refs (ids +// are never re-minted), so covered-but-pruned ids retain numbers with gaps +// relative to whatever remains visible. withRefs cannot express that gap. +function inheritedLedger( + specs: { + blockId: string; + effectiveMessageIds: string[]; + }[], + order: [string, number][], +): CompressionState { + const state = makeState(specs); + for (const [raw, n] of order) { + const ref = `m${String(n).padStart(5, "0")}`; + state.messageRefs.byRaw[raw] = ref; + state.messageRefs.byRef[ref] = raw; + } + return state; +} + test("#199: message-ref range that only re-wraps an active block is rejected, not fake-success", () => { const core = createCore(); const cfg = config(); @@ -205,14 +224,26 @@ test("#199: message-ref range that pulls in NEW messages plus a nested block is msg("raw-9", "x".repeat(6000)), ...loopedView().slice(3), ]; - const state = withRefs( - messages, - makeState([ + // b1's covered raw-2..raw-5 were pruned from the view but keep their + // original refs — inside the requested window m00001..m00009. + const state = inheritedLedger( + [ { blockId: "b1", effectiveMessageIds: ["raw-2", "raw-3", "raw-4", "raw-5"], }, - ]), + ], + [ + ["raw-1", 1], + ["tool-1", 2], + ["raw-2", 3], + ["raw-3", 4], + ["raw-4", 5], + ["raw-5", 6], + ["raw-9", 7], + ["raw-6", 8], + ["tool-2", 9], + ], ); const startRef = state.messageRefs.byRaw["raw-1"]!; const endRef = state.messageRefs.byRaw["tool-2"]!; @@ -230,3 +261,40 @@ test("#199: message-ref range that pulls in NEW messages plus a nested block is assert.deepEqual(newBlock.directMessageIds, ["raw-9"]); assert.deepEqual(newBlock.directBlockIds, ["b1"]); }); + +test("#5830 fail-closed: unmappable consumed-block coverage rejects instead of guessing containment", () => { + const core = createCore(); + const cfg = config(); + const messages = [ + ...loopedView().slice(0, 3), + msg("raw-9", "x".repeat(6000)), + ...loopedView().slice(3), + ]; + // Fresh nextIndex=1 numbering leaves b1's pruned covered ids out of byRaw + // entirely — containment is unprovable, so the fold must reject atomically + // (the positive direction is pinned by the inherited-ledger test above). + const state = withRefs( + messages, + makeState([ + { + blockId: "b1", + effectiveMessageIds: ["raw-2", "raw-3", "raw-4", "raw-5"], + }, + ]), + ); + const startRef = state.messageRefs.byRaw["raw-1"]!; + const endRef = state.messageRefs.byRaw["tool-2"]!; + + const applied = core.applyCompression({ + ranges: [{ startRef, endRef, summary: "S".repeat(80) }], + messages, + state, + config: cfg, + }); + + assert.equal(applied.result.blocksCreated, 0, "containment unprovable -> no merge"); + assert.equal(applied.result.errors.length, 1); + assert.match(applied.result.errors[0]!, /unmapped coverage/); + assert.equal(applied.state.blocks.length, 1, "atomic: nothing committed"); + assert.equal(applied.state.blocks[0]!.active, true, "b1 untouched"); +}); From ce6f877389a0d913fe43603b95ee9dd699cfc749 Mon Sep 17 00:00:00 2001 From: ci-check Date: Sat, 7 Nov 2026 04:23:51 +0800 Subject: [PATCH 5/6] kernel: judge merge-window containment over mappable coverage MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The fail-closed rule treated ANY unmappable coverage id as an offender. Turn separators (#2627) are synthetic outbound-only markers that legacy polluted views registered into block coverage WITHOUT a ref entry; a later plain-range fold consuming such a block was rejected although its real-history coverage sat entirely inside the window. Real history ids always keep their byRaw entry (ids are never re-minted; only applyCompactionArchive prunes at native-compaction boundaries), so an unmapped id carries no client-side content a replaced summary could lose — skip it. A block whose ENTIRE coverage is unmappable still fails closed (containment unprovable); the pi#199 negative pin holds. --- kernel/package-lock.json | 4 ++-- kernel/package.json | 2 +- kernel/src/unit-projection.ts | 29 ++++++++++++++--------------- package-lock.json | 2 +- 4 files changed, 18 insertions(+), 19 deletions(-) diff --git a/kernel/package-lock.json b/kernel/package-lock.json index 4144191483..367841bc5a 100644 --- a/kernel/package-lock.json +++ b/kernel/package-lock.json @@ -1,12 +1,12 @@ { "name": "acp-kernel", - "version": "0.0.184", + "version": "0.0.185", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "acp-kernel", - "version": "0.0.184", + "version": "0.0.185", "license": "MIT", "devDependencies": { "@types/node": "^22.0.0", diff --git a/kernel/package.json b/kernel/package.json index d26c24485f..ce8eecf8e6 100644 --- a/kernel/package.json +++ b/kernel/package.json @@ -1,6 +1,6 @@ { "name": "acp-kernel", - "version": "0.0.184", + "version": "0.0.185", "description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.", "license": "MIT", "author": "ranxianglei", diff --git a/kernel/src/unit-projection.ts b/kernel/src/unit-projection.ts index e8ee00d24d..cf865600a2 100644 --- a/kernel/src/unit-projection.ts +++ b/kernel/src/unit-projection.ts @@ -267,11 +267,15 @@ export function projectUnit(input: UnitProjectionInput): UnitProjection { // endpoints resolved IN PLACE (the requested message itself still occupies // its slot), containment is judged against the WIDENED span, not the // literal window. What must stay fatal is the #5830 producer itself: an - // endpoint that RESOLVED ELSEWHERE (stale inherited ref snapping to a - // distant inheriting-block anchor) sweeps territory the summary never - // described regardless of widening — hold the line at the requested - // window then. Unmappable coverage fails closed either way (containment - // unprovable). + // endpoint that RESOLVED ELSEWHERE (stale inherited ref snapping to a + // distant inheriting-block anchor) sweeps territory the summary never + // described regardless of widening — hold the line at the requested + // window then. Coverage ids carrying NO ref entry (synthetic outbound-only + // markers, e.g. #2627 turn separators that legacy polluted views registered + // into block coverage) describe no client-side real-history content, so a + // replaced summary cannot lose anything they stand for — they ride along. + // A block whose ENTIRE coverage is unmappable still fails closed + // (containment unprovable). if (!isBlockBoundary && consumedBlockIds.length > 0 && filteredIds.length > 0) { const startBoundary = parseBoundary(input.startRef); const endBoundary = parseBoundary(input.endRef); @@ -310,20 +314,15 @@ export function projectUnit(input: UnitProjectionInput): UnitProjection { for (const mid of block.effectiveMessageIds) { const ref = input.state.messageRefs.byRaw[mid]; const num = ref === undefined ? null : refToIndex(ref); - if (num === null) { - outOfSpan = true; // unmappable coverage: containment unprovable - break; - } + if (num === null) continue; if (num < spanLo || num > spanHi) outOfSpan = true; if (minNum === null || num < minNum) minNum = num; if (maxNum === null || num > maxNum) maxNum = num; } - if (outOfSpan) { - offenders.push( - minNum !== null && maxNum !== null - ? `${consumedId} [${indexToRef(minNum)}..${indexToRef(maxNum)}]` - : `${consumedId} [unmapped coverage]`, - ); + if (minNum === null || maxNum === null) { + offenders.push(`${consumedId} [unmapped coverage]`); + } else if (outOfSpan) { + offenders.push(`${consumedId} [${indexToRef(minNum)}..${indexToRef(maxNum)}]`); } } if (offenders.length > 0) { diff --git a/package-lock.json b/package-lock.json index df4e87298d..b86748e21c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -50,7 +50,7 @@ }, "kernel": { "name": "acp-kernel", - "version": "0.0.184", + "version": "0.0.185", "dev": true, "license": "MIT", "devDependencies": { From d4b2749d1d1d577c0e2aa6cb929e57c631e320dd Mon Sep 17 00:00:00 2001 From: ci-check Date: Sat, 7 Nov 2026 05:02:35 +0800 Subject: [PATCH 6/6] test: harden the #5152 receiver port handoff against a create/write race MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI shard flake on this PR (test ubuntu-22 s2, run 42288017742): 'receiver port must be a number, got 0'. The fixture published its port with appendFileSync — open(O_CREAT) and write are separate syscalls, so under runner load the parent's existsSync poll can observe the file while it is still empty, and Number('') === 0 trips the assertion. Reproduced locally by splitting the publication (probe: exact same failure text); kernel-only PR diff cannot touch this path. Two facets of the same race, both test-side only: - fixture publishes tmp + rename (atomic: existence now implies complete content) - startReceiver waits until the content parses to a valid port > 0 instead of trusting mere existence (keeps the 15s deadline and both failure modes) --- tests/fixtures/issue5152-beat-receiver.mjs | 9 +++++++-- tests/issue5152-owner-beat-survives-host-stall.test.ts | 10 ++++++++-- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/tests/fixtures/issue5152-beat-receiver.mjs b/tests/fixtures/issue5152-beat-receiver.mjs index 132fbe11aa..7176ffc7d9 100644 --- a/tests/fixtures/issue5152-beat-receiver.mjs +++ b/tests/fixtures/issue5152-beat-receiver.mjs @@ -3,7 +3,7 @@ // reaching it while the sender's own thread was pinned. An in-process receiver // would be pinned by the same block and the proof would be vacuous. import http from "node:http"; -import { appendFileSync } from "node:fs"; +import { appendFileSync, renameSync, writeFileSync } from "node:fs"; const out = process.argv[2]; if (!out) throw new Error("usage: issue5152-beat-receiver.mjs "); @@ -17,5 +17,10 @@ const server = http.createServer((req, res) => { }); }); server.listen(0, "127.0.0.1", () => { - appendFileSync(`${out}.port`, String(server.address().port)); + // Publish atomically (tmp + rename): the parent polls this file's + // existence, so a create-then-write gap lets it read an empty file and + // parse it as port 0. + const portFile = `${out}.port`; + writeFileSync(`${portFile}.tmp`, String(server.address().port)); + renameSync(`${portFile}.tmp`, portFile); }); diff --git a/tests/issue5152-owner-beat-survives-host-stall.test.ts b/tests/issue5152-owner-beat-survives-host-stall.test.ts index 671977001c..1851c3d85a 100644 --- a/tests/issue5152-owner-beat-survives-host-stall.test.ts +++ b/tests/issue5152-owner-beat-survives-host-stall.test.ts @@ -53,12 +53,18 @@ async function startReceiver(dir: string): Promise { const portFile = `${log}.port`; const child = spawn(process.execPath, [RECEIVER, log], { stdio: "ignore", detached: true }); child.unref(); + // Wait until the published port VALIDATES, not merely until the file + // exists: a partial/empty read must never be mistaken for a real port + // (Number("") === 0), even though the receiver now publishes tmp+rename. + let port = 0; const deadline = Date.now() + 15_000; - while (!existsSync(portFile) && Date.now() < deadline) { + while (!(Number.isInteger(port) && port > 0) && Date.now() < deadline) { + if (existsSync(portFile)) { + port = Number(readFileSync(portFile, "utf8").trim()); + } Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20); } assert.ok(existsSync(portFile), "receiver must publish its port"); - const port = Number(readFileSync(portFile, "utf8").trim()); assert.ok(Number.isInteger(port) && port > 0, `receiver port must be a number, got ${port}`); return { port,