From d1c47bae2119f69557ae407e42cf7819eb0250b4 Mon Sep 17 00:00:00 2001 From: awork Date: Thu, 15 Oct 2026 16:43:25 +0800 Subject: [PATCH 1/3] kernel: share one unit-projection judgment between recommend and apply (#3236) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Eligibility and execution used two different definitions of "can this range fold": recommend screened turn-integrity over the GLOBAL compressible set while apply judged each SUBMITTED range alone, on a different array class, and widened boundaries within a capped window. A turn whose partners sat in other advertised units passed global screening yet made every submission throw "Range would split N turn(s)" — a permanent advertise/reject loop (billion-context#3236). - unit-projection.ts: projectUnit extracts applySingleRange's pre-block sequence verbatim (boundary widening -> carrier/coverage/media/ protected-tool carve -> protected-zone carve -> turn-integrity withdrawal -> emptiness); returns the projection or the ready-to-throw fatal error (zone/split). collectCoverage moves here. - applySingleRange delegates to projectUnit; errors/warnings stay byte-identical (existing suite passes untouched). - recommendNode re-screens every FINAL merged unit through projectUnit and demotes fatal units to gaps (no re-merge after filtering). - NodeEffects.applyView: judgment now runs on the EXACT array class applyCompression executes on; absent it, falls back to the pre-prune original (#2663) or the given view. - report.ts: buildStatusReport accepts config + originalMessages; the uncompressed view appends an additive warning flag to rows whose projection is fatal (flagged, never dropped); legacy output unchanged. - kernel/tests/issue3236-recommend-apply-consistency.test.ts: both divergence geometries (delayed results unreachable / reachable, double-burst interleave), healthy-turn non-over-screening, gate intactness on manual submit, and the acp_status flag surface. kernel 0.0.124 -> 0.0.125 --- kernel/package.json | 2 +- kernel/src/compress.ts | 394 ++------------- kernel/src/pipeline.ts | 5 + kernel/src/recommend.ts | 51 ++ kernel/src/report.ts | 76 ++- kernel/src/unit-projection.ts | 464 ++++++++++++++++++ ...ue3236-recommend-apply-consistency.test.ts | 418 ++++++++++++++++ package-lock.json | 2 +- 8 files changed, 1066 insertions(+), 346 deletions(-) create mode 100644 kernel/src/unit-projection.ts create mode 100644 kernel/tests/issue3236-recommend-apply-consistency.test.ts diff --git a/kernel/package.json b/kernel/package.json index de57e579e5..4e287cdef4 100644 --- a/kernel/package.json +++ b/kernel/package.json @@ -1,6 +1,6 @@ { "name": "acp-kernel", - "version": "0.0.124", + "version": "0.0.125", "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/compress.ts b/kernel/src/compress.ts index 4ee0df2367..18f29ca209 100644 --- a/kernel/src/compress.ts +++ b/kernel/src/compress.ts @@ -1,20 +1,14 @@ import { assignRefs, highestUsedIndex, indexToRef } from "./refs.js"; import { remintCoveredLiveIds } from "./instance-reid.js"; -import { prune, isSummaryMessageId } from "./prune.js"; +import { prune } from "./prune.js"; import { syncBlocks } from "./sync.js"; -import { - advanceSurvival, - activeBlocks, - blockById, - isLiveCheckpointCarrier, -} from "./state.js"; +import { advanceSurvival, activeBlocks, blockById } from "./state.js"; import { allocateBlockId, allocateRunId, createInitialState } from "./state.js"; import { countMessageTokens, defaultCountTokens } from "./tokenize.js"; import { validateConfig } from "./config.js"; import { BoundaryNotFoundError, resolveBoundaries, - blockVisibleInRange, parseBoundary, } from "./boundaries.js"; import type { ResolvedRange } from "./boundaries.js"; @@ -41,13 +35,12 @@ import { isMessageProtectedWithPairing, } from "./protected.js"; import { isToolMessage } from "./message-kind.js"; -import { adjustBoundariesForToolPairs } from "./tool-pairs.js"; -import { adjustBoundariesForReasoningPairs } from "./reasoning-pairs.js"; -import { computeIntegrityWithdrawals } from "./turn-integrity.js"; +import { projectUnit, collectCoverage } from "./unit-projection.js"; import { computeProtectedRefs, buildCompressibleRanges, mergeRangesToThreshold, + screenRecommendedUnits, } from "./recommend.js"; import { runPipeline, @@ -115,6 +108,13 @@ export interface ProcessTurnInput { /** Per-session CCR content store (pass result.contentStore back here). * Omit for pre-CCR sessions — an empty store is used. */ contentStore?: MessageContentStore; + /** #3236: the EXACT message array class applyCompression will run on for + * this lane. Hosts whose render view (`messages`) differs from the fold + * view (pruned separators, host-side compaction tails) pass the unpruned + * log here so recommendation screening and unit projection judge ranges on + * the same class execute will — advertised and applied can't diverge. + * Omit when `messages` already IS that class. */ + applyView?: CoreMessage[]; } export interface ApplyCompressionInput { @@ -769,7 +769,7 @@ export function createCore(ports: Ports = {}): CompressionCore { const initial: NodeIO = { messages: input.messages, state: input.state, - effects: {}, + effects: { applyView: input.applyView }, }; // Conversion (assign-refs) and rendering (render-refs) are separate // concerns. Refs are always assigned; renderTags only controls which @@ -1066,21 +1066,40 @@ const recommendNode: PipelineNode = { ctx.config, ctx.countTokens, ); + // #3236: screening must judge on the exact array class applyCompression + // runs on — the host's applyView when provided, else the pre-prune + // original (#2663 integritySource), else the view itself. + const screenArray = + io.effects.applyView ?? io.effects.originalMessages ?? io.messages; const contextRanges = buildCompressibleRanges( io.messages, io.state, ctx.config, protectedRefs, ctx.countTokens, - io.effects.originalMessages, + screenArray, ); const nothingToCompress = contextRanges.compressible.length === 0; - const recommendation: Recommendation = { - contextRanges, - recommendedRanges: mergeRangesToThreshold( + // #3236: re-screen each merged unit through the SAME judgment + // applySingleRange executes (unit-projection.ts). A unit that would be + // rejected wholesale (zone-only span, turn/pair split, nothing new to + // fold) is demoted to a gap instead of advertised — global screening + // alone passed turns whose partners sit in another advertised unit, so + // every submission of such a range threw (permanent advertise/reject + // loop in production). + const recommendedRanges = screenRecommendedUnits( + mergeRangesToThreshold( contextRanges.compressible, ctx.config.compress.minCompressRange, ), + screenArray, + io.state, + ctx.config, + computeProtectedRefs(screenArray, io.state, ctx.config, ctx.countTokens), + ); + const recommendation: Recommendation = { + contextRanges, + recommendedRanges, nothingToCompress, }; return { ...io, effects: { ...io.effects, recommendation } }; @@ -1253,218 +1272,27 @@ interface SingleRangeOutcome { function applySingleRange(input: SingleRangeInput): SingleRangeOutcome { const warnings: string[] = []; - const resolved = resolveBoundaries({ - startRef: input.spec.startRef, - endRef: input.spec.endRef, + // #3236: the pre-block sequence runs as ONE shared projection + // (unit-projection.ts) that the recommendation side screens with — same + // definition for advertise and execute; fatal errors are thrown verbatim. + const projection = projectUnit({ messages: input.messages, state: input.state, + config: input.config, + startRef: input.spec.startRef, + endRef: input.spec.endRef, + preExistingCoverage: input.preExistingCoverage, + protectedMessageIds: input.protectedMessageIds, + warnings, }); - - // Host checkpoint carriers (#335): a host that renders its own compression - // summaries marks each carrier with `summaryOfBlockId`. A plain message-ref - // range does not go through the block-distillation path, so folding a live - // carrier would silently drop the previous distillation from the visible - // context while the result reports nothing superseded. Keep carriers of - // still-active blocks visible; stale carriers (block already consumed, or - // unknown id) fold like ordinary messages. Block-ref boundaries deliberately - // distill across checkpoints and keep folding carriers. - const plainRange = resolved.boundaryKind !== "block"; - const liveCarrierIds = new Set(); - if (plainRange) { - // #2663: the selector screens with this same predicate — one definition, - // two call sites, so advertise/validate cannot drift apart again. - for (const message of input.messages) { - if (isLiveCheckpointCarrier(message, input.state)) { - liveCarrierIds.add(message.id); - } - } - } - const adjustedIds = applyPairBoundaryAdjustments(resolved, input.messages); - const skippedCarriers = adjustedIds.filter((id) => liveCarrierIds.has(id)); - if (skippedCarriers.length > 0) { - warnings.push( - `Excluded ${skippedCarriers.length} checkpoint message(s) ${skippedCarriers.join( - ", ", - )} from the compression range — they carry the visible summary of still-active block(s), which a plain message-ref range does not supersede. The checkpoints stay visible; to fold them, reference the block ids (bN..bM) instead.`, - ); - } - const rangeMessageIds = adjustedIds.filter( - (id) => !isSummaryMessageId(id) && !liveCarrierIds.has(id), - ); - - // Re-scan for nested blocks in the ADJUSTED range (tool-pair extension may - // have pulled in messages that are anchors of existing blocks). - if (rangeMessageIds.length > resolved.messageIds.length) { - const indexByMessageId = new Map(); - input.messages.forEach((m, i) => indexByMessageId.set(m.id, i)); - const adjustedStart = - rangeMessageIds.length > 0 - ? (indexByMessageId.get(rangeMessageIds[0]!) ?? resolved.startIndex) - : resolved.startIndex; - const adjustedEnd = - rangeMessageIds.length > 0 - ? (indexByMessageId.get(rangeMessageIds[rangeMessageIds.length - 1]!) ?? - resolved.endIndex) - : resolved.endIndex; - const nestedSeen = new Set(resolved.nestedBlockIds); - for (const block of activeBlocks(input.state)) { - if (nestedSeen.has(block.blockId)) continue; - if ( - blockVisibleInRange(block, indexByMessageId, adjustedStart, adjustedEnd) - ) { - nestedSeen.add(block.blockId); - resolved.nestedBlockIds.push(block.blockId); - } - } - } - - const isBlockBoundary = resolved.boundaryKind === "block"; - const targetTier = resolveTargetTier( - input.state, - resolved.nestedBlockIds, + if (projection.fatal) throw projection.fatal.error; + const { + filteredIds, + consumedBlockIds, + effectiveMessageIds, + outputTier, isBlockBoundary, - ); - const outputTier = isBlockBoundary - ? (Math.min(3, targetTier + 1) as CompressionTier) - : 1; - - const consumedBlockIds = resolved.nestedBlockIds.filter((id) => { - const block = blockById(input.state, id); - return block?.active && block.tier === targetTier; - }); - - const effectiveMessageIds = new Set(rangeMessageIds); - for (const consumedId of consumedBlockIds) { - const consumed = blockById(input.state, consumedId); - if (consumed) { - for (const id of consumed.effectiveMessageIds) - effectiveMessageIds.add(id); - } - } - - const directMessageIds = [...effectiveMessageIds].filter( - (id) => !input.preExistingCoverage.has(id), - ); - - let filteredIds = filterProtectedToolMessages( - directMessageIds, - input.messages, - input.config, - ); - - // filterProtectedToolMessages drops protected tool calls (and their paired - // results) from the compressible set. They must also leave effectiveMessageIds, - // otherwise the block would record them as covered and hide them from view. - // (Bug 39: protected tool messages folded into a block.) - if (filteredIds.length < directMessageIds.length) { - const kept = new Set(filteredIds); - for (const id of directMessageIds) { - if (!kept.has(id)) effectiveMessageIds.delete(id); - } - } - - const mediaExcluded = directMessageIds.filter((id) => { - const msg = input.messages.find((m) => m.id === id); - return !!msg && hasUnrecoverableMediaPayload(msg); - }); - if (mediaExcluded.length > 0) { - warnings.push( - `Excluded ${mediaExcluded.length} message(s) carrying unrecoverable media (remote URL / file references with no stored bytes) from compression range — folding would destroy them permanently (billion-context#1188/#2609). Inline images fold normally and stay restorable via decompress({ imageRef }).`, - ); - } - - // SOFT PROTECTION: the recent-N / last-user-message zone is advisory-only at - // compress time. Instead of failing the whole range when it brushes protected - // messages, exclude those messages and proceed with the rest (so the model - // isn't blocked when it picks a range that slightly overlaps the recent - // window). If excluding them empties the range entirely AND there are no - // consumed blocks to merge, we still fail — there is genuinely nothing to - // compress. `protectedMessageIds` holds REF ids (mNNNNN) from - // computeProtectedRefs; filteredIds holds RAW message ids, so convert via - // state.messageRefs.byRaw before testing membership. - const protectedRefs = input.protectedMessageIds; - const hitProtectedRaw = protectedRefs - ? filteredIds.filter((id) => { - const ref = input.state.messageRefs.byRaw[id]; - return ref !== undefined && protectedRefs.has(ref); - }) - : []; - if (hitProtectedRaw.length > 0) { - const protectedSet = new Set(hitProtectedRaw); - filteredIds = filteredIds.filter((id) => !protectedSet.has(id)); - // Remove protected messages from effective coverage too, so they are NOT - // hidden by the new block (they must stay fully visible). - for (const id of hitProtectedRaw) effectiveMessageIds.delete(id); - - const hitRefs = hitProtectedRaw - .map((id) => input.state.messageRefs.byRaw[id]) - .filter((v): v is string => typeof v === "string"); - - if (filteredIds.length === 0 && consumedBlockIds.length === 0) { - const recentN = input.config.preserveRecentMessages; - throw new Error( - `Range is entirely within the protected zone (the last ${recentN} messages and/or the most recent user message): ${hitRefs.join( - ", ", - )}. Adjust startId/endId to older messages.`, - ); - } - warnings.push( - `Excluded ${hitProtectedRaw.length} protected message(s) ${hitRefs.join( - ", ", - )} from compression range (recent/last-user zone) — they stay visible outside the new block; do not target them in another compress call.`, - ); - } - - // TURN-INTEGRITY GATE (#684): the protected carve above (and the protected - // tool filter before it) remove individual messages AFTER - // applyPairBoundaryAdjustments completed the range, which can split a turn. - // The DIRECTIONAL invariant that strict-echo providers enforce: an assistant - // tool-call message that survives the fold must keep its reasoning run - // (DeepSeek thinking mode: "reasoning_content ... must be passed back"). - // The reverse split — reasoning + text kept while the call and result fold — - // leaves a valid message stream and stays allowed (#564 depends on it), so - // only turns whose KEPT side carries a tool-call while the FOLDED side - // carries the reasoning are withdrawn, entirely (all members stay visible). - // The same carve can also strip a call and its result onto opposite sides of - // the fold. Either half alone is invalid — a visible call whose result folded - // is an unanswered tool_call_id, a visible result whose call folded answers - // nothing — so those pairs are withdrawn together, both halves staying - // visible. Whole pairs may still fold while the turn's reasoning and text - // stay visible (#564). - // - // Both invariants are re-checked to a fixed point inside - // computeIntegrityWithdrawals: withdrawing a pair for the result half can - // strand a turn whose reasoning still folds and whose call now stays visible. - // The recommendation side calls the same helper, so it never advertises a - // range this gate always empties. - { - const { - withdrawn: withdrawIds, - splitTurnCount, - splitPairCount, - } = computeIntegrityWithdrawals(input.messages, effectiveMessageIds); - if (withdrawIds.size > 0) { - for (const id of withdrawIds) effectiveMessageIds.delete(id); - const beforeWithdraw = filteredIds.length; - filteredIds = filteredIds.filter((id) => !withdrawIds.has(id)); - const splitDesc = [ - splitTurnCount > 0 ? `${splitTurnCount} turn(s)` : null, - splitPairCount > 0 - ? `${splitPairCount} tool call/result pair(s)` - : null, - ] - .filter((part): part is string => part !== null) - .join(" and "); - if (filteredIds.length === 0 && consumedBlockIds.length === 0) { - throw new Error( - `Range would split ${splitDesc} at the protected-zone boundary: a visible tool-call must keep its reasoning run and its results (strict providers reject a rebuilt request that lost either). Shrink the range to end before the turn starts, or wait until the whole turn ages out of the protected zone.`, - ); - } - warnings.push( - `Withdrawn ${beforeWithdraw - filteredIds.length} message(s) from compression range to keep ${splitDesc} intact (visible tool-call would lose its reasoning run or its results).`, - ); - } - } + } = projection; // Livelock guard (billion-context-pi#199): a message-ref range whose entire // content is already owned by active block(s) — its raw ids are all covered @@ -1554,53 +1382,6 @@ function applySingleRange(input: SingleRangeInput): SingleRangeOutcome { return { tokens: compressedTokens, warnings }; } -function applyPairBoundaryAdjustments( - resolved: { - startIndex: number; - endIndex: number; - messageIds: string[]; - boundaryKind: string; - }, - messages: CoreMessage[], -): string[] { - if (resolved.boundaryKind === "block") { - return resolved.messageIds; - } - // Compose tool-pair and reasoning-pair boundary adjustments to a fixpoint - // (≤2 passes). Reasoning may pull in a tool-call whose result tool-pairs - // then extends for; tool-pairs may pull in a tool-call whose preceding - // reasoning is then drawn in. Both only ever WIDEN the range. - let startIndex = resolved.startIndex; - let endIndex = resolved.endIndex; - for (let pass = 0; pass < 2; pass++) { - const reasoningAdjusted = adjustBoundariesForReasoningPairs( - startIndex, - endIndex, - messages, - ); - const toolAdjusted = adjustBoundariesForToolPairs( - reasoningAdjusted.startIndex, - reasoningAdjusted.endIndex, - messages, - ); - const changed = - toolAdjusted.startIndex !== startIndex || - toolAdjusted.endIndex !== endIndex; - startIndex = toolAdjusted.startIndex; - endIndex = toolAdjusted.endIndex; - if (!changed) break; - } - if (startIndex === resolved.startIndex && endIndex === resolved.endIndex) { - return resolved.messageIds; - } - const ids: string[] = []; - for (let i = startIndex; i <= endIndex; i++) { - const msg = messages[i]; - if (msg) ids.push(msg.id); - } - return ids; -} - function validateCompressionRange( input: SingleRangeInput, directMessageIds: string[], @@ -1642,77 +1423,6 @@ function validateSummaryLength( } } -function filterProtectedToolMessages( - directMessageIds: string[], - messages: CoreMessage[], - config: Config, -): string[] { - // Protected tool calls (and their results, paired by toolCallId) stay in - // visible context and are simply dropped from the compressible set. They are - // NOT folded into the summary — the summary reflects what the author wrote, - // nothing auto-appended. - const protectedCallIds = new Set(); - const removedIds = new Set(); - const latest = collectLatestProtected(messages, config); - for (const id of latest.callIds) protectedCallIds.add(id); - for (const msg of messages) { - if (isMessageProtected(msg, config) && msg.toolCallId) { - protectedCallIds.add(msg.toolCallId); - } - } - - for (const id of directMessageIds) { - const msg = messages.find((m) => m.id === id); - if (!msg) continue; - if ( - hasUnrecoverableMediaPayload(msg) || - isMessageProtected(msg, config) || - isMessageLatestProtected(msg, latest) - ) { - removedIds.add(id); - if (msg.toolCallId) protectedCallIds.add(msg.toolCallId); - } - } - - for (const id of directMessageIds) { - if (removedIds.has(id)) continue; - const msg = messages.find((m) => m.id === id); - if (!msg) continue; - if ( - msg.contentType === "tool-result" && - msg.toolCallId && - protectedCallIds.has(msg.toolCallId) - ) { - removedIds.add(id); - } - } - - return directMessageIds.filter((id) => !removedIds.has(id)); -} - -function resolveTargetTier( - state: CompressionState, - nestedBlockIds: string[], - isBlockBoundary: boolean, -): CompressionTier { - if (!isBlockBoundary) return 1; - if (nestedBlockIds.length === 0) return 1; - let minTier: CompressionTier = 3; - for (const id of nestedBlockIds) { - const block = blockById(state, id); - if (block && block.tier < minTier) minTier = block.tier; - } - return minTier; -} - -function collectCoverage(state: CompressionState): Set { - const coverage = new Set(); - for (const block of activeBlocks(state)) { - for (const id of block.effectiveMessageIds) coverage.add(id); - } - return coverage; -} - interface NudgeInput { tokenCount: number; config: Config; diff --git a/kernel/src/pipeline.ts b/kernel/src/pipeline.ts index 234343f3af..96d063f9d9 100644 --- a/kernel/src/pipeline.ts +++ b/kernel/src/pipeline.ts @@ -20,6 +20,11 @@ export interface NodeEffects { * same input class the apply side sees. Optional — custom pipelines without * a prune node simply don't set it and recommend falls back to its input. */ originalMessages?: CoreMessage[]; + /** #3236: the exact array class applyCompression runs on (host-passed, see + * ProcessTurnInput.applyView). Ranks above originalMessages for + * foldability judgment — on lanes whose processTurn input is itself a + * pruned/render view, even the pre-prune input is not the apply class. */ + applyView?: CoreMessage[]; readonly [key: string]: unknown; } diff --git a/kernel/src/recommend.ts b/kernel/src/recommend.ts index 4217015ecf..498aed5ae6 100644 --- a/kernel/src/recommend.ts +++ b/kernel/src/recommend.ts @@ -34,6 +34,8 @@ import { import { countMessageTokens } from "./tokenize.js"; import { computeIntegrityWithdrawals } from "./turn-integrity.js"; import { segmentGroups } from "./segment.js"; +import { projectUnit, collectCoverage } from "./unit-projection.js"; +import type { UnitProjection } from "./unit-projection.js"; // ─── Helpers ────────────────────────────────────────────────────────────────── @@ -529,3 +531,52 @@ export function mergeRangesToThreshold( } return result; } + +/** + * #3236: re-screen each merged recommended unit through the SAME judgment + * applySingleRange executes (projectUnit, unit-projection.ts). A unit that + * would be rejected wholesale — protected-zone-only span, turn/pair split, or + * nothing new to fold — is demoted to a gap instead of advertised. Without + * this, global integrity screening passes turns whose partners sit in ANOTHER + * advertised unit, and every submission of such a range throws "Range would + * split N turn(s)" — a permanent advertise/reject loop observed in production + * (billion-context#3236). No re-merge after filtering: re-merging could + * resurrect a doomed unit under different groupings and oscillate; a dropped + * unit simply stops being offered until the geometry changes. + */ +export function screenRecommendedUnits( + units: CompressibleRange[], + source: CoreMessage[], + state: CompressionState, + config: Config, + protectedRefs: Set, +): CompressibleRange[] { + if (units.length === 0) return units; + const coverage = collectCoverage(state); + return units.filter((unit) => { + let projection: UnitProjection | undefined; + try { + projection = projectUnit({ + messages: source, + state, + config, + startRef: unit.startRef, + endRef: unit.endRef, + preExistingCoverage: coverage, + protectedMessageIds: protectedRefs, + }); + } catch { + // Endpoints that cannot resolve on this array class (dead/consumed) + // must never be advertised. + return false; + } + if (!projection || projection.fatal !== null) return false; + if ( + projection.filteredIds.length === 0 && + projection.consumedBlockIds.length === 0 + ) { + return false; + } + return true; + }); +} diff --git a/kernel/src/report.ts b/kernel/src/report.ts index 01a4b5b330..05c5779e93 100644 --- a/kernel/src/report.ts +++ b/kernel/src/report.ts @@ -4,9 +4,13 @@ import { BLOCKED_REF, orderedRefPair, refForRaw } from "./refs.js"; import { countMessageTokens } from "./tokenize.js"; import { segmentGroups } from "./segment.js"; import { isLiveCheckpointCarrier } from "./state.js"; +import { computeProtectedRefs } from "./recommend.js"; +import { collectCoverage, projectUnit } from "./unit-projection.js"; +import type { UnitProjection } from "./unit-projection.js"; import type { CompressionBlock, CompressionState, + Config, CoreMessage, } from "./types.js"; @@ -171,6 +175,15 @@ export interface StatusReportOptions { sort?: "size" | "time" | "tool" | "age"; limit?: number; meta?: StatusReportMeta; + /** #3236: when both this and `originalMessages` are given, the + * uncompressed range rows are screened through the SAME projection + * applySingleRange executes and doomed rows get a ⚠ flag (diagnostic view — + * rows are flagged, never dropped). Omit both for legacy output. */ + config?: Config; + /** #3236: the exact array class applyCompression runs on (see + * ProcessTurnInput.applyView). Screening is skipped without it — projecting + * on the render view would judge a different array class than execute. */ + originalMessages?: CoreMessage[]; } export function buildStatusReport( @@ -210,7 +223,15 @@ export function buildStatusReport( if (view === "messages") { return renderMessageDrilldown(visible, toolFilter, sort, limit); } - return renderUncompressedRanges(visible, sort, limit); + return renderUncompressedRanges( + visible, + sort, + limit, + state, + countTokens, + options.config, + options.originalMessages, + ); } return renderOverview( @@ -333,6 +354,10 @@ function renderUncompressedRanges( visible: VisibleMessageInfo[], sort: string, limit: number, + state: CompressionState, + countTokens: (t: string) => number, + config?: Config, + original?: CoreMessage[], ): string { const lines: string[] = []; const totalTokens = visible.reduce((s, m) => s + m.tokens, 0); @@ -391,6 +416,52 @@ function renderUncompressedRanges( // ordering would mis-sort equal-size ranges. if (sort !== "time") merged.sort((a, b) => b.tokens - a.tokens || a.startIndex - b.startIndex); + // #3236: screen displayed rows through the SAME projection applySingleRange + // executes so a row that would be rejected wholesale carries a ⚠ flag. The + // diagnostic view flags rather than drops — it must keep showing what is + // visible even when it is not foldable as-is. Requires the exact array class + // apply runs on (`original`); without it projection would judge a different + // array class than execute, which is the #3236 bug itself. + let flagFor: ((r: Merged) => string | null) | null = null; + if (config && original) { + const coverage = collectCoverage(state); + const protectedRefs = computeProtectedRefs( + original, + state, + config, + countTokens, + ); + const splitDescOf = (p: UnitProjection): string => { + const parts: string[] = []; + if (p.splitTurnCount > 0) parts.push(`${p.splitTurnCount} turn(s)`); + if (p.splitPairCount > 0) + parts.push(`${p.splitPairCount} tool call/result pair(s)`); + return parts.join(" and ") || "turn structure"; + }; + flagFor = (r): string | null => { + let proj: UnitProjection; + try { + proj = projectUnit({ + messages: original!, + state, + config, + startRef: r.startRef, + endRef: r.endRef, + preExistingCoverage: coverage, + protectedMessageIds: protectedRefs, + }); + } catch { + return "\u26a0 not foldable: refs unresolvable"; + } + if (proj.fatal?.kind === "zone") + return "\u26a0 not foldable: protected zone only"; + if (proj.fatal?.kind === "split") + return `\u26a0 not foldable: would split ${splitDescOf(proj)}`; + if (proj.filteredIds.length === 0 && proj.consumedBlockIds.length === 0) + return "\u26a0 not foldable: nothing new to fold"; + return null; + }; + } lines.push(`Sorted by ${sort === "time" ? "time" : "size"}`); lines.push(""); for (const r of merged.slice(0, limit)) { @@ -400,8 +471,9 @@ function renderUncompressedRanges( r.count === 1 ? r.startRef : orderedRefPair(r.startRef, r.endRef).join("–"); + const flag = flagFor ? flagFor(r) : null; lines.push( - ` ${range} (${r.count} msgs, ${formatTokens(r.tokens)}${r.count > 1 ? ` (${Math.round(r.tokens / r.count)}/msg)` : ""}) ${dominantTool(r.toolTokens)}`, + ` ${range} (${r.count} msgs, ${formatTokens(r.tokens)}${r.count > 1 ? ` (${Math.round(r.tokens / r.count)}/msg)` : ""}) ${dominantTool(r.toolTokens)}${flag ? ` ${flag}` : ""}`, ); } if (merged.length > limit) { diff --git a/kernel/src/unit-projection.ts b/kernel/src/unit-projection.ts new file mode 100644 index 0000000000..4b67880f91 --- /dev/null +++ b/kernel/src/unit-projection.ts @@ -0,0 +1,464 @@ +import { activeBlocks, blockById, isLiveCheckpointCarrier } from "./state.js"; +import { resolveBoundaries, blockVisibleInRange } from "./boundaries.js"; +import { isSummaryMessageId } from "./prune.js"; +import { + collectLatestProtected, + hasUnrecoverableMediaPayload, + isMessageLatestProtected, + isMessageProtected, +} from "./protected.js"; +import { computeIntegrityWithdrawals } from "./turn-integrity.js"; +import { adjustBoundariesForReasoningPairs } from "./reasoning-pairs.js"; +import { adjustBoundariesForToolPairs } from "./tool-pairs.js"; +import type { + CompressionState, + CompressionTier, + Config, + CoreMessage, +} from "./types.js"; + +/** + * #3236: the ONE definition of "can this range fold" — the exact sequence + * applySingleRange runs before it creates a block: boundary resolution → + * checkpoint-carrier exclusion (#335/#2663) → pair-boundary widening + * (tool/reasoning pairs) → nested-block rescan → protected-tool/media/zone + * carves → turn-integrity withdrawal (#684) → empty check. + * + * Before this module existed the recommendation side re-implemented parts of + * that judgment with a DIFFERENT input scope: global integrity screening over + * ALL compressible messages at once (so a turn whose partners sit in another + * advertised unit passed screening), while apply judges each SUBMITTED range + * alone and throws when its carves split a turn or empty the fold. Production + * result: acp_status / nudge advertised ranges that every submission rejected + * with "Range would split N turn(s)" — a permanent advertise/reject loop. + * + * Now both sides run this one function on the same array class (the exact + * array applyCompression executes on — see ProcessTurnInput.applyView). Apply + * consumes the full projection and throws the carried Error verbatim; the + * recommendation side uses it as a screen and demotes doomed units to gaps; + * the acp_status uncompressed view flags rows whose projection is fatal. + * Swapping any single carve criterion (dead ref, live carrier, media, + * protected tools, zone, turn integrity) therefore changes advertise and + * execute together — the #2663 acceptance criterion. + */ +export interface UnitProjectionInput { + /** The EXACT message array class applyCompression will run on for this + * lane (the unpruned log when the render view differs from it). */ + messages: CoreMessage[]; + state: CompressionState; + config: Config; + startRef: string; + endRef: string; + /** Raw ids already covered by active blocks BEFORE this unit folds + * (apply computes one such set per call; recommend passes the current one). */ + preExistingCoverage: Set; + /** REF ids (mNNNNN) of the soft-protection zone, computed on `messages` — + * apply derives them from its own input array via computeProtectedRefs. */ + protectedMessageIds?: Set; + /** Warnings are pushed here in apply's original emission order so the + * apply-side refactor stays byte-identical. Omit for read-only screens. */ + warnings?: string[]; +} + +export interface UnitProjectionFatal { + kind: "zone" | "split"; + error: Error; +} + +export interface UnitProjection { + /** Non-null when applySingleRange would THROW for this unit (and which + * error, fully constructed). Null = the unit folds, possibly with warnings. */ + fatal: UnitProjectionFatal | null; + rangeMessageIds: string[]; + skippedCarrierIds: string[]; + nestedBlockIds: string[]; + consumedBlockIds: string[]; + effectiveMessageIds: Set; + directMessageIds: string[]; + filteredIds: string[]; + withdrawnIds: Set; + splitTurnCount: number; + splitPairCount: number; + targetTier: CompressionTier; + outputTier: CompressionTier; + isBlockBoundary: boolean; +} + +/** Read-only projection of one candidate range through the full apply + * sequence. Never mutates `state`; never creates blocks. Throws + * BoundaryNotFoundError when an endpoint ref cannot be resolved. */ +export function projectUnit(input: UnitProjectionInput): UnitProjection { + const warnings = input.warnings ?? []; + // Declared up front: every exit path (including the zone fatal below) + // assembles the result through finish(), which reads these bindings. + let withdrawnIds = new Set(); + let splitTurnCount = 0; + let splitPairCount = 0; + + const resolved = resolveBoundaries({ + startRef: input.startRef, + endRef: input.endRef, + messages: input.messages, + state: input.state, + }); + + // Host checkpoint carriers (#335): a host that renders its own compression + // summaries marks each carrier with `summaryOfBlockId`. A plain message-ref + // range does not go through the block-distillation path, so folding a live + // carrier would silently drop the previous distillation from the visible + // context while the result reports nothing superseded. Keep carriers of + // still-active blocks visible; stale carriers (block already consumed, or + // unknown id) fold like ordinary messages. Block-ref boundaries deliberately + // distill across checkpoints and keep folding carriers. + const plainRange = resolved.boundaryKind !== "block"; + const liveCarrierIds = new Set(); + if (plainRange) { + // #2663: the selector screens with this same predicate — one definition, + // two call sites, so advertise/validate cannot drift apart again. + for (const message of input.messages) { + if (isLiveCheckpointCarrier(message, input.state)) { + liveCarrierIds.add(message.id); + } + } + } + const adjustedIds = applyPairBoundaryAdjustments(resolved, input.messages); + const skippedCarrierIds = adjustedIds.filter((id) => liveCarrierIds.has(id)); + if (skippedCarrierIds.length > 0) { + warnings.push( + `Excluded ${skippedCarrierIds.length} checkpoint message(s) ${skippedCarrierIds.join( + ", ", + )} from the compression range — they carry the visible summary of still-active block(s), which a plain message-ref range does not supersede. The checkpoints stay visible; to fold them, reference the block ids (bN..bM) instead.`, + ); + } + const rangeMessageIds = adjustedIds.filter( + (id) => !isSummaryMessageId(id) && !liveCarrierIds.has(id), + ); + + // Re-scan for nested blocks in the ADJUSTED range (tool-pair extension may + // have pulled in messages that are anchors of existing blocks). + if (rangeMessageIds.length > resolved.messageIds.length) { + const indexByMessageId = new Map(); + input.messages.forEach((m, i) => indexByMessageId.set(m.id, i)); + const adjustedStart = + rangeMessageIds.length > 0 + ? (indexByMessageId.get(rangeMessageIds[0]!) ?? resolved.startIndex) + : resolved.startIndex; + const adjustedEnd = + rangeMessageIds.length > 0 + ? (indexByMessageId.get(rangeMessageIds[rangeMessageIds.length - 1]!) ?? + resolved.endIndex) + : resolved.endIndex; + const nestedSeen = new Set(resolved.nestedBlockIds); + for (const block of activeBlocks(input.state)) { + if (nestedSeen.has(block.blockId)) continue; + if ( + blockVisibleInRange(block, indexByMessageId, adjustedStart, adjustedEnd) + ) { + nestedSeen.add(block.blockId); + resolved.nestedBlockIds.push(block.blockId); + } + } + } + + const isBlockBoundary = resolved.boundaryKind === "block"; + const targetTier = resolveTargetTier( + input.state, + resolved.nestedBlockIds, + isBlockBoundary, + ); + const outputTier = isBlockBoundary + ? (Math.min(3, targetTier + 1) as CompressionTier) + : 1; + + const consumedBlockIds = resolved.nestedBlockIds.filter((id) => { + const block = blockById(input.state, id); + return block?.active && block.tier === targetTier; + }); + + const effectiveMessageIds = new Set(rangeMessageIds); + for (const consumedId of consumedBlockIds) { + const consumed = blockById(input.state, consumedId); + if (consumed) { + for (const id of consumed.effectiveMessageIds) + effectiveMessageIds.add(id); + } + } + + const directMessageIds = [...effectiveMessageIds].filter( + (id) => !input.preExistingCoverage.has(id), + ); + + let filteredIds = filterProtectedToolMessages( + directMessageIds, + input.messages, + input.config, + ); + + // filterProtectedToolMessages drops protected tool calls (and their paired + // results) from the compressible set. They must also leave effectiveMessageIds, + // otherwise the block would record them as covered and hide them from view. + // (Bug 39: protected tool messages folded into a block.) + if (filteredIds.length < directMessageIds.length) { + const kept = new Set(filteredIds); + for (const id of directMessageIds) { + if (!kept.has(id)) effectiveMessageIds.delete(id); + } + } + + const mediaExcluded = directMessageIds.filter((id) => { + const msg = input.messages.find((m) => m.id === id); + return !!msg && hasUnrecoverableMediaPayload(msg); + }); + if (mediaExcluded.length > 0) { + warnings.push( + `Excluded ${mediaExcluded.length} message(s) carrying unrecoverable media (remote URL / file references with no stored bytes) from compression range — folding would destroy them permanently (billion-context#1188/#2609). Inline images fold normally and stay restorable via decompress({ imageRef }).`, + ); + } + + // SOFT PROTECTION: the recent-N / last-user-message zone is advisory-only at + // compress time. Instead of failing the whole range when it brushes protected + // messages, exclude those messages and proceed with the rest (so the model + // isn't blocked when it picks a range that slightly overlaps the recent + // window). If excluding them empties the range entirely AND there are no + // consumed blocks to merge, we still fail — there is genuinely nothing to + // compress. `protectedMessageIds` holds REF ids (mNNNNN) from + // computeProtectedRefs; filteredIds holds RAW message ids, so convert via + // state.messageRefs.byRaw before testing membership. + const protectedRefs = input.protectedMessageIds; + const hitProtectedRaw = protectedRefs + ? filteredIds.filter((id) => { + const ref = input.state.messageRefs.byRaw[id]; + return ref !== undefined && protectedRefs.has(ref); + }) + : []; + if (hitProtectedRaw.length > 0) { + const protectedSet = new Set(hitProtectedRaw); + filteredIds = filteredIds.filter((id) => !protectedSet.has(id)); + // Remove protected messages from effective coverage too, so they are NOT + // hidden by the new block (they must stay fully visible). + for (const id of hitProtectedRaw) effectiveMessageIds.delete(id); + + const hitRefs = hitProtectedRaw + .map((id) => input.state.messageRefs.byRaw[id]) + .filter((v): v is string => typeof v === "string"); + + if (filteredIds.length === 0 && consumedBlockIds.length === 0) { + const recentN = input.config.preserveRecentMessages; + return finish({ + fatal: { + kind: "zone", + error: new Error( + `Range is entirely within the protected zone (the last ${recentN} messages and/or the most recent user message): ${hitRefs.join( + ", ", + )}. Adjust startId/endId to older messages.`, + ), + }, + }); + } + warnings.push( + `Excluded ${hitProtectedRaw.length} protected message(s) ${hitRefs.join( + ", ", + )} from compression range (recent/last-user zone) — they stay visible outside the new block; do not target them in another compress call.`, + ); + } + + // TURN-INTEGRITY GATE (#684): the protected carve above (and the protected + // tool filter before it) remove individual messages AFTER + // applyPairBoundaryAdjustments completed the range, which can split a turn. + // The DIRECTIONAL invariant that strict-echo providers enforce: an assistant + // tool-call message that survives the fold must keep its reasoning run + // (DeepSeek thinking mode: "reasoning_content ... must be passed back"). + // The reverse split — reasoning + text kept while the call and result fold — + // leaves a valid message stream and stays allowed (#564 depends on it), so + // only turns whose KEPT side carries a tool-call while the FOLDED side + // carries the reasoning are withdrawn, entirely (all members stay visible). + // The same carve can also strip a call and its result onto opposite sides of + // the fold. Either half alone is invalid — a visible call whose result folded + // is an unanswered tool_call_id, a visible result whose call folded answers + // nothing — so those pairs are withdrawn together, both halves staying + // visible. Whole pairs may still fold while the turn's reasoning and text + // stay visible (#564). + // + // Both invariants are re-checked to a fixed point inside + // computeIntegrityWithdrawals: withdrawing a pair for the result half can + // strand a turn whose reasoning still folds and whose call now stays visible. + { + const { + withdrawn: withdrawIds, + splitTurnCount: turns, + splitPairCount: pairs, + } = computeIntegrityWithdrawals(input.messages, effectiveMessageIds); + withdrawnIds = withdrawIds; + splitTurnCount = turns; + splitPairCount = pairs; + if (withdrawIds.size > 0) { + for (const id of withdrawIds) effectiveMessageIds.delete(id); + const beforeWithdraw = filteredIds.length; + filteredIds = filteredIds.filter((id) => !withdrawIds.has(id)); + const splitDesc = [ + splitTurnCount > 0 ? `${splitTurnCount} turn(s)` : null, + splitPairCount > 0 + ? `${splitPairCount} tool call/result pair(s)` + : null, + ] + .filter((part): part is string => part !== null) + .join(" and "); + if (filteredIds.length === 0 && consumedBlockIds.length === 0) { + return finish({ + fatal: { + kind: "split", + error: new Error( + `Range would split ${splitDesc} at the protected-zone boundary: a visible tool-call must keep its reasoning run and its results (strict providers reject a rebuilt request that lost either). Shrink the range to end before the turn starts, or wait until the whole turn ages out of the protected zone.`, + ), + }, + }); + } + warnings.push( + `Withdrawn ${beforeWithdraw - filteredIds.length} message(s) from compression range to keep ${splitDesc} intact (visible tool-call would lose its reasoning run or its results).`, + ); + } + } + + return finish({ fatal: null }); + + function finish( + partial: Pick, + ): UnitProjection { + return { + ...partial, + rangeMessageIds, + skippedCarrierIds, + nestedBlockIds: [...resolved.nestedBlockIds], + consumedBlockIds, + effectiveMessageIds, + directMessageIds, + filteredIds, + withdrawnIds, + splitTurnCount, + splitPairCount, + targetTier, + outputTier, + isBlockBoundary, + }; + } +} + +/** Union of the raw ids covered by all active blocks — the set apply treats + * as "already folded" before a new spec runs (one per applyCompression call). */ +export function collectCoverage(state: CompressionState): Set { + const coverage = new Set(); + for (const block of activeBlocks(state)) { + for (const id of block.effectiveMessageIds) coverage.add(id); + } + return coverage; +} + +function applyPairBoundaryAdjustments( + resolved: { + startIndex: number; + endIndex: number; + messageIds: string[]; + boundaryKind: string; + }, + messages: CoreMessage[], +): string[] { + if (resolved.boundaryKind === "block") { + return resolved.messageIds; + } + // Compose tool-pair and reasoning-pair boundary adjustments to a fixpoint + // (≤2 passes). Reasoning may pull in a tool-call whose result tool-pairs + // then extends for; tool-pairs may pull in a tool-call whose preceding + // reasoning is then drawn in. Both only ever WIDEN the range. + let startIndex = resolved.startIndex; + let endIndex = resolved.endIndex; + for (let pass = 0; pass < 2; pass++) { + const reasoningAdjusted = adjustBoundariesForReasoningPairs( + startIndex, + endIndex, + messages, + ); + const toolAdjusted = adjustBoundariesForToolPairs( + reasoningAdjusted.startIndex, + reasoningAdjusted.endIndex, + messages, + ); + const changed = + toolAdjusted.startIndex !== startIndex || + toolAdjusted.endIndex !== endIndex; + startIndex = toolAdjusted.startIndex; + endIndex = toolAdjusted.endIndex; + if (!changed) break; + } + if (startIndex === resolved.startIndex && endIndex === resolved.endIndex) { + return resolved.messageIds; + } + const ids: string[] = []; + for (let i = startIndex; i <= endIndex; i++) { + const msg = messages[i]; + if (msg) ids.push(msg.id); + } + return ids; +} + +function filterProtectedToolMessages( + directMessageIds: string[], + messages: CoreMessage[], + config: Config, +): string[] { + // Protected tool calls (and their results, paired by toolCallId) stay in + // visible context and are simply dropped from the compressible set. They are + // NOT folded into the summary — the summary reflects what the author wrote, + // nothing auto-appended. + const protectedCallIds = new Set(); + const removedIds = new Set(); + const latest = collectLatestProtected(messages, config); + for (const id of latest.callIds) protectedCallIds.add(id); + for (const msg of messages) { + if (isMessageProtected(msg, config) && msg.toolCallId) { + protectedCallIds.add(msg.toolCallId); + } + } + + for (const id of directMessageIds) { + const msg = messages.find((m) => m.id === id); + if (!msg) continue; + if ( + hasUnrecoverableMediaPayload(msg) || + isMessageProtected(msg, config) || + isMessageLatestProtected(msg, latest) + ) { + removedIds.add(id); + if (msg.toolCallId) protectedCallIds.add(msg.toolCallId); + } + } + + for (const id of directMessageIds) { + if (removedIds.has(id)) continue; + const msg = messages.find((m) => m.id === id); + if (!msg) continue; + if ( + msg.contentType === "tool-result" && + msg.toolCallId && + protectedCallIds.has(msg.toolCallId) + ) { + removedIds.add(id); + } + } + + return directMessageIds.filter((id) => !removedIds.has(id)); +} + +function resolveTargetTier( + state: CompressionState, + nestedBlockIds: string[], + isBlockBoundary: boolean, +): CompressionTier { + if (!isBlockBoundary) return 1; + if (nestedBlockIds.length === 0) return 1; + let minTier: CompressionTier = 3; + for (const id of nestedBlockIds) { + const block = blockById(state, id); + if (block && block.tier < minTier) minTier = block.tier; + } + return minTier; +} diff --git a/kernel/tests/issue3236-recommend-apply-consistency.test.ts b/kernel/tests/issue3236-recommend-apply-consistency.test.ts new file mode 100644 index 0000000000..8d88e8fac4 --- /dev/null +++ b/kernel/tests/issue3236-recommend-apply-consistency.test.ts @@ -0,0 +1,418 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createCore } from "../src/compress.js"; +import { createInitialState } from "../src/state.js"; +import { assignRefs } from "../src/refs.js"; +import { buildStatusReport } from "../src/report.js"; +import { defaultCountTokens } from "../src/tokenize.js"; +import type { Config, CoreMessage, CompressionState } from "../src/types.js"; + +// #3236: the eligibility side (recommend/nudge/acp_status) judged turn +// integrity over a different folded set than the execution side +// (per-submitted-range), so it advertised ranges the apply side rejected +// wholesale ("Range would split N turn(s)") in a permanent retry loop. Both +// sides now run the SAME projection (unit-projection.ts): every advertised +// range must apply cleanly, doomed ranges stop being advertised while the +// apply-side gate keeps rejecting them on manual submit, and healthy +// complete turns stay advertised. Geometries below mirror the field shapes +// (async tool results arriving far after their burst) that diverged on 0.1.196. + +function config(): Config { + return { + tiers: { enabled: false }, + nudge: { + maxContextLimitPct: 0.55, minContextLimitPct: 0.45, frequency: 5, iterationThreshold: 15, + force: "soft", growthRatio: 0.05, growthFloor: 6000, growthCap: 50000, + minGrowthFloor: 5000, minGrowthRatio: 0.45, emergencyThresholdPct: 0.98, + }, + promotionThreshold: 5, + truncate: { threshold: 1 }, + merge: { maxSummaryLength: 3000, minOldGenBlocks: 3 }, + compress: { minCompressRange: 5000, maxSummaryLength: 20000, minSummaryLength: 1 }, + protectedTools: [], + preserveRecentMessages: 0, + preserveRecentTokens: 0, + modelContextLimit: 100000, + }; +} + +function mk( + id: string, + role: CoreMessage["role"], + ct: CoreMessage["contentType"], + toolName?: string, + toolCallId?: string, + len = 1500, +): CoreMessage { + return { id, role, contentType: ct, toolName, toolCallId, text: "x".repeat(len) }; +} + +interface Scenario { + state: CompressionState; + all: CoreMessage[]; +} + +function buildHeadFold( + core: ReturnType, + cfg: Config, +): Scenario { + const state = createInitialState(); + const all: CoreMessage[] = [ + mk("U0", "user", "text", undefined, undefined, 3000), + mk("W1", "assistant", "text", undefined, undefined, 3000), + ]; + state.messageRefs = assignRefs(all, { + existing: state.messageRefs, + nextIndex: 1, + }).map; + const p1 = core.applyCompression({ + ranges: [{ startRef: "m00001", endRef: "m00002", summary: "earlier work" }], + messages: all, + state, + config: cfg, + }); + assert.equal(p1.result.errors.length, 0, p1.result.errors.join("; ")); + return { state: p1.state, all }; +} + +// Burst [R, C1..C5] with the FIRST result immediate, six filler turns, then +// the remaining four results arriving far beyond the apply side's pair-widen +// window (>20 slots, or cut off by the first non-match after a match). The +// old selector advertised the burst span itself; apply withdrew the whole +// turn and threw. +function buildDelayedResults( + core: ReturnType, + cfg: Config, + interleave: boolean, +): Scenario { + const { state, all } = buildHeadFold(core, cfg); + all.push( + mk("R", "assistant", "reasoning", undefined, undefined, 2000), + mk("C1", "assistant", "tool-call", "bash", "c1"), + mk("C2", "assistant", "tool-call", "read", "c2"), + mk("C3", "assistant", "tool-call", "bash", "c3"), + mk("C4", "assistant", "tool-call", "read", "c4"), + mk("C5", "assistant", "tool-call", "bash", "c5"), + mk("RS1", "tool", "tool-result", "read", "c1", 300), + ); + const late = [ + mk("RS2", "tool", "tool-result", "read", "c2", 300), + mk("RS3", "tool", "tool-result", "bash", "c3", 300), + mk("RS4", "tool", "tool-result", "read", "c4", 300), + mk("RS5", "tool", "tool-result", "bash", "c5", 300), + ]; + for (let f = 0; f < 6; f++) { + all.push(mk(`UF${f}`, "user", "text", undefined, undefined, 200)); + all.push(mk(`RF${f}`, "assistant", "reasoning", undefined, undefined, 300)); + all.push(mk(`CF${f}`, "assistant", "tool-call", "bash", `cf${f}`, 300)); + if (interleave && f === 2) all.push(late[0]!); + all.push(mk(`RSF${f}`, "tool", "tool-result", "bash", `cf${f}`, 300)); + if (interleave && f === 4) all.push(late[1]!); + } + if (interleave) all.push(late[2]!, late[3]!); + else all.push(...late); + state.messageRefs = assignRefs(all, { + existing: state.messageRefs, + nextIndex: 3, + }).map; + return { state, all }; +} + +// Two bursts interleaved (RA, CA1..CA3, RA_RS1, RB, CB1..CB3, RB_RS1) with +// each burst's late results appended after six filler turns. The old +// selector batched both bursts into ONE advertised range; apply reported +// "Range would split 2 turn(s) and 4 tool call/result pair(s)". +function buildTwoBursts( + core: ReturnType, + cfg: Config, +): Scenario { + const { state, all } = buildHeadFold(core, cfg); + all.push( + mk("RA", "assistant", "reasoning", undefined, undefined, 2000), + mk("CA1", "assistant", "tool-call", "bash", "a1"), + mk("CA2", "assistant", "tool-call", "read", "a2"), + mk("CA3", "assistant", "tool-call", "bash", "a3"), + mk("RA_RS1", "tool", "tool-result", "bash", "a1", 300), + mk("RB", "assistant", "reasoning", undefined, undefined, 2000), + mk("CB1", "assistant", "tool-call", "read", "b1"), + mk("CB2", "assistant", "tool-call", "bash", "b2"), + mk("CB3", "assistant", "tool-call", "read", "b3"), + mk("RB_RS1", "tool", "tool-result", "read", "b1", 300), + ); + for (let f = 0; f < 6; f++) { + all.push(mk(`UF${f}`, "user", "text", undefined, undefined, 200)); + all.push(mk(`RF${f}`, "assistant", "reasoning", undefined, undefined, 300)); + all.push(mk(`CF${f}`, "assistant", "tool-call", "bash", `cf${f}`, 300)); + all.push(mk(`RSF${f}`, "tool", "tool-result", "bash", `cf${f}`, 300)); + } + all.push( + mk("LA2", "tool", "tool-result", "read", "a2", 300), + mk("LA3", "tool", "tool-result", "bash", "a3", 300), + mk("LB2", "tool", "tool-result", "bash", "b2", 300), + mk("LB3", "tool", "tool-result", "read", "b3", 300), + ); + state.messageRefs = assignRefs(all, { + existing: state.messageRefs, + nextIndex: 3, + }).map; + return { state, all }; +} + +function refIndexMap(state: CompressionState, all: CoreMessage[]): Map { + const map = new Map(); + all.forEach((m, i) => { + const ref = state.messageRefs.byRaw[m.id]; + if (ref) map.set(ref, i); + }); + return map; +} + +// THE contract (#2638/#2663 lineage): every advertised range applies cleanly +// against the very state it was advertised from. +function assertAdvertisedApplyCleanly( + core: ReturnType, + cfg: Config, + state: CompressionState, + all: CoreMessage[], + label: string, +): void { + const processed = core.processTurn({ + messages: all, + state, + config: cfg, + tokenCount: 70000, + }); + const ranges = processed.nudge?.compressibleRanges ?? []; + assert.ok(ranges.length > 0, `${label}: fresh content must be advertised`); + for (const r of ranges) { + const applied = core.applyCompression({ + ranges: [{ startRef: r.startRef, endRef: r.endRef, summary: "steady-state fold" }], + messages: all, + state: structuredClone(state), + config: cfg, + }); + assert.equal( + applied.result.errors.length, + 0, + `${label}: advertised ${r.startRef}-${r.endRef} failed to apply: ${applied.result.errors.join("; ")}`, + ); + } +} + +test("#3236 A/A2: burst with delayed results — doomed units screened out; every advertised unit applies cleanly", () => { + const core = createCore(); + const cfg = config(); + for (const interleave of [false, true]) { + const label = interleave ? "A2" : "A"; + const { state, all } = buildDelayedResults(core, cfg, interleave); + const refIdx = refIndexMap(state, all); + + const processed = core.processTurn({ + messages: all, + state, + config: cfg, + tokenCount: 70000, + }); + const ranges = processed.nudge?.compressibleRanges ?? []; + assert.ok(ranges.length > 0, `${label}: content must still be advertised`); + + if (!interleave) { + // Scenario A: the delayed results sit far past the 20-slot widening + // window, so NO projection of a range spanning the burst can fold — + // such units must not be advertised. + const burstLo = refIdx.get(state.messageRefs.byRaw["R"]!)!; + const burstHi = refIdx.get(state.messageRefs.byRaw["RS1"]!)!; + for (const r of ranges) { + const s = refIdx.get(r.startRef); + const e = refIdx.get(r.endRef); + assert.notEqual(s, undefined, `${label}: start ${r.startRef} resolvable`); + assert.notEqual(e, undefined, `${label}: end ${r.endRef} resolvable`); + assert.ok( + !(s! <= burstHi && e! >= burstLo), + `${label}: advertised ${r.startRef}-${r.endRef} still spans the split burst`, + ); + } + } + for (const r of ranges) { + const applied = core.applyCompression({ + ranges: [{ startRef: r.startRef, endRef: r.endRef, summary: "steady-state fold" }], + messages: all, + state: structuredClone(state), + config: cfg, + }); + assert.equal( + applied.result.errors.length, + 0, + `${label}: advertised ${r.startRef}-${r.endRef} failed to apply: ${applied.result.errors.join("; ")}`, + ); + } + + // Manual submit of the raw burst span pins both behaviors: in A the gate + // still throws the wire-validity error (screening hides the unit, it does + // not bless it); in A2 the late results land inside the widening window, + // the span pulls them in and withdraws only the unreachable tail, so the + // same span legitimately folds. + const doomed = core.applyCompression({ + ranges: [{ + startRef: state.messageRefs.byRaw["R"]!, + endRef: state.messageRefs.byRaw["RS1"]!, + summary: "manual doomed span", + }], + messages: all, + state: structuredClone(state), + config: cfg, + }); + if (!interleave) { + assert.equal(doomed.result.blocksCreated, 0); + assert.match( + doomed.result.errors.join(" "), + /Range would split 1 turn\(s\) and 4 tool call\/result pair\(s\)/, + doomed.result.errors.join(" "), + ); + } else { + assert.equal( + doomed.result.errors.length, + 0, + `A2: self-healing span should fold, got: ${doomed.result.errors.join("; ")}`, + ); + assert.equal(doomed.result.blocksCreated, 1); + } + } +}); + +test("#3236 B: two interleaved bursts — advertised clean, gate intact on manual submit", () => { + const core = createCore(); + const cfg = config(); + const { state, all } = buildTwoBursts(core, cfg); + const refIdx = refIndexMap(state, all); + const burstLo = refIdx.get(state.messageRefs.byRaw["RA"]!)!; + const burstHi = refIdx.get(state.messageRefs.byRaw["RB_RS1"]!)!; + + const processed = core.processTurn({ + messages: all, + state, + config: cfg, + tokenCount: 70000, + }); + const ranges = processed.nudge?.compressibleRanges ?? []; + assert.ok(ranges.length > 0, "content must still be advertised"); + for (const r of ranges) { + const s = refIdx.get(r.startRef); + const e = refIdx.get(r.endRef); + assert.notEqual(s, undefined, `start ${r.startRef} resolvable`); + assert.notEqual(e, undefined, `end ${r.endRef} resolvable`); + assert.ok( + !(s! <= burstHi && e! >= burstLo), + `advertised ${r.startRef}-${r.endRef} still spans the split double burst`, + ); + const applied = core.applyCompression({ + ranges: [{ startRef: r.startRef, endRef: r.endRef, summary: "steady-state fold" }], + messages: all, + state: structuredClone(state), + config: cfg, + }); + assert.equal( + applied.result.errors.length, + 0, + `advertised ${r.startRef}-${r.endRef} failed to apply: ${applied.result.errors.join("; ")}`, + ); + } + + const doomed = core.applyCompression({ + ranges: [{ + startRef: state.messageRefs.byRaw["RA"]!, + endRef: state.messageRefs.byRaw["RB_RS1"]!, + summary: "manual doomed span", + }], + messages: all, + state: structuredClone(state), + config: cfg, + }); + assert.equal(doomed.result.blocksCreated, 0); + assert.match( + doomed.result.errors.join(" "), + /Range would split 2 turn\(s\) and 4 tool call\/result pair\(s\)/, + doomed.result.errors.join(" "), + ); +}); + +test("#3236: healthy complete turns remain advertised and apply cleanly (no over-screening)", () => { + const core = createCore(); + const cfg = config(); + const state = createInitialState(); + const all: CoreMessage[] = [ + mk("U", "user", "text", undefined, undefined, 1000), + mk("R", "assistant", "reasoning", undefined, undefined, 1000), + mk("C", "assistant", "tool-call", "bash", "c1"), + mk("RS", "tool", "tool-result", "bash", "c1", 3000), + ]; + state.messageRefs = assignRefs(all, { + existing: state.messageRefs, + nextIndex: 1, + }).map; + + assertAdvertisedApplyCleanly(core, cfg, state, all, "complete-turn"); + + const processed = core.processTurn({ + messages: all, + state, + config: cfg, + tokenCount: 70000, + }); + const ranges = processed.nudge?.compressibleRanges ?? []; + const refIdx = refIndexMap(state, all); + const turnLo = refIdx.get(state.messageRefs.byRaw["R"]!)!; + const turnHi = refIdx.get(state.messageRefs.byRaw["RS"]!)!; + assert.ok( + ranges.some((r) => { + const s = refIdx.get(r.startRef); + const e = refIdx.get(r.endRef); + return s !== undefined && e !== undefined && s <= turnLo && e >= turnHi; + }), + `the complete turn must still be advertised: ${JSON.stringify(ranges.map((r) => `${r.startRef}-${r.endRef}`))}`, + ); +}); + +test("#3236: acp_status uncompressed rows flag doomed spans but keep them visible", () => { + const core = createCore(); + const cfg = config(); + const { state, all } = buildTwoBursts(core, cfg); + + const report = buildStatusReport(state, all, defaultCountTokens, { + scope: "uncompressed", + view: "ranges", + config: cfg, + originalMessages: all, + }); + const lines = report.split("\n"); + const burstLine = lines.find( + (l) => + l.includes(state.messageRefs.byRaw["RA"]!) && + l.includes(state.messageRefs.byRaw["RB_RS1"]!), + ); + assert.ok(burstLine, "burst row must stay listed (flagged, not dropped)"); + assert.ok( + burstLine!.includes("\u26a0 not foldable"), + `burst row must carry the flag: ${burstLine}`, + ); + assert.ok( + burstLine!.includes("would split 2 turn(s)"), + `burst row must name the split: ${burstLine}`, + ); + + const fillerLine = lines.find( + (l) => + l.includes(state.messageRefs.byRaw["UF0"]!) && + l.includes(state.messageRefs.byRaw["RSF0"]!), + ); + assert.ok( + fillerLine !== undefined && !fillerLine.includes("\u26a0"), + `healthy complete-turn row must be unflagged: ${fillerLine}`, + ); + + // Legacy call (no config/originalMessages) keeps the byte-stable surface. + const legacy = buildStatusReport(state, all, defaultCountTokens, { + scope: "uncompressed", + }); + assert.ok(!legacy.includes("\u26a0"), "legacy output gains no flags"); +}); diff --git a/package-lock.json b/package-lock.json index b23392139b..452f9a2adf 100644 --- a/package-lock.json +++ b/package-lock.json @@ -48,7 +48,7 @@ }, "kernel": { "name": "acp-kernel", - "version": "0.0.124", + "version": "0.0.125", "dev": true, "license": "MIT", "devDependencies": { From f8b95a64d38f59c77f70c16633c3aaa5b7dbb59a Mon Sep 17 00:00:00 2001 From: awork Date: Thu, 15 Oct 2026 16:43:34 +0800 Subject: [PATCH 2/3] fix: judge nudge/status ranges on the apply-side array class (#3236) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Host lanes whose processTurn input is a render/processed view (plugin panel: mem.processed with synthetic separators, #2627; relay loop: processed messages) passed that view to the kernel, so even the pre- prune originalMessages fallback was not the class applyCompression executes on. Pass applyView everywhere it differs: - acp-status: AcpStatusCtx gains compressMessages (structural typing — both LoopCtx and RewriteCtx already carry it); liveCompressionRanges feeds it as applyView; handleAcpStatus passes config + original messages to buildStatusReport so the uncompressed view can flag un-foldable rows. - stream postCompressTail fallback + plugin panel status: applyView set from ctx.compressMessages / mem.original respectively. AGENTS.md: KDD bullet 12 records the shared unit-projection judgment. --- AGENTS.md | 1 + src/acp-status.ts | 11 +++++++++++ src/plugin.ts | 3 +++ src/stream.ts | 2 ++ 4 files changed, 17 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index d36f0a2346..46beba4e0c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,6 +50,7 @@ The full file-by-file map lives in [reference/architecture.md](reference/archite 10. **Thinking-family blocks are signature-verified — NEVER rewrite them (#1960)** — Anthropic `thinking`/`redacted_thinking` blocks and Gemini `thoughtSignature` parts are verified byte-for-byte when the latest assistant message is replayed ("thinking blocks ... cannot be modified"). The bytes the proxy forwards become the client's persisted history, and the bytes the loop accumulates become the re-request rebuild — BOTH must stay verbatim. Any transformation (tag/marker stripping, dedup, trimming, re-laying-out block order, dropping empty segments) desynchronizes text from signature and bricks the session: first on the in-turn re-request, then on every subsequent request via the client's echo. #1882 put a prose filter on the thinking channel and it was exactly this bug. Treat ANY future change touching thinking-family payloads as high-risk: it needs loop-level byte-equality tests (re-request body AND client-visible stream) on both signed wires, not just adapter-level ones. The prose filters (#206/#1881) are for the TEXT channel only. 11. **顺序为中心,hash 为辅助 (order-centric reconciliation — owner rule, 2026-10-12, #2821/#2915)** — fold-state reconciliation must treat ORDER as the primary carrier of message identity across resent histories: position claims verified spans (with per-cell fingerprint gates), content hashes and tool-call ids are auxiliary evidence, and NO single dimension's miss may cascade into total unfold. The identity dimensions survive different churn classes — order survives re-encoding AND id re-minting, content survives id churn, ids survive re-encoding — so the ladder is the union of their survival domains, and each rung fails soft: an id/fingerprint mismatch voids that CELL's claim only; the positional scans resync at the next run of same-index agreements (MIN_RESYNC_RUN consecutive matches, bounded gaps) and keep claiming verified spans behind the break. Genuinely changed cells (real edits, regenerations) stay honestly unmatched and re-enter the wire — "never fuzzy similarity" (mis-attribution is the most expensive failure, MESSAGE-IDENTITY.md) is unchanged: the hash stays a HARD per-cell gate, it just no longer holds a global veto over its neighbors. Escalation to "substrate destroyed" may only count gaps that survived resync AND the content passes (byTool/byTwin/byNorm/byTurn). #2821 was the canonical violation: a mid-session model switch re-minted every tool-call id on re-projection (content byte-identical), both positional flank scans died at their FIRST cell (changed preamble at the head, appended turn at the tail), 3289 covered ids went missing, three passes → destroyed verdict → total unfold → doomed-probe 502. #2396's detection-only twins are promoted to a claiming pass (Pass 1.5, k-th discipline + length guard) so id re-mints recover even without a stored positional copy — and after one churn pass the self-saved {ids, canon} copy upgrades recovery to the positional path. A Pass-0 gap cell (order break) is resolved by tiers, owner rule 2026-10-12: any exact channel that matches claims it; failing that, simhash corroboration (≤8 bits on the 64-bit word-shingle sketch — measured margins: re-wording ≈6-8 bits inside, negation flips ≈11 / word drops ≈13 / key reorders ≈21 outside) claims it; failing that, the ORDER BRACKET — same index strictly between VERIFIED claims on both flanks — asserts the SLOT (the owner-sanctioned delete+insert tradeoff: coverage rides the slot, the stale bytes do not); with zero corroboration and no fence the cell stays honest unmatched drift. Deletion is honest loss: the flanks absorb the shift, the deleted id never gets a bracket claim (its slot cell is consumed by the verified tail). Tests: `tests/issue2915-order-centric-reconcile.test.ts`. + 12. **资格判定与执行共用单一投影 (shared unit-projection judgment, #3236)** — whether a candidate range is foldable has exactly ONE definition: `projectUnit` in `kernel/src/unit-projection.ts` (applySingleRange's pre-block sequence extracted verbatim: boundary widening → carrier/coverage/media/protected-tool carve → protected-zone carve → turn-integrity withdrawal → emptiness), returning either a structured projection or the ready-to-throw fatal error (`zone`/`split`). The apply side throws it byte-identically; the recommend side re-screens every FINAL merged unit through it and demotes fatal units to gaps (no re-merge after filtering — anti-oscillation); the acp_status uncompressed view runs it per displayed row and appends an additive ⚠ flag (diagnostic surface: rows are flagged, never dropped). The judgment must run on the EXACT array class `applyCompression` executes on: hosts whose render view differs from their apply class pass it via `ProcessTurnInput.applyView` / `StatusReportOptions.originalMessages` (plugin lane = raw history per #2627; relay loop = `prepared.originalMessages`); absent it, judgment falls back to the pre-prune original (#2663) or the given view. The bug fixed: recommend judged turn-integrity over the GLOBAL compressible set while apply judged the PER-SUBMITTED-RANGE set — a turn whose partners sat in different advertised units passed global screening yet split per range, producing a permanent advertise→reject loop ("Range would split N turn(s)"). Tests: `kernel/tests/issue3236-recommend-apply-consistency.test.ts`. ### Install-Lane & Update-Ownership Contract (#1196) diff --git a/src/acp-status.ts b/src/acp-status.ts index ba24f55b7d..d8da280a54 100644 --- a/src/acp-status.ts +++ b/src/acp-status.ts @@ -31,6 +31,12 @@ interface AcpStatusCtx { config: Config; messages: CoreMessage[]; session: Session; + // #3236: the exact array class applyCompression runs on for this lane. + // Without it, processTurn's eligibility screening and the uncompressed + // view's foldability flags judge a different array class than execute. + // LoopCtx/RewriteCtx both carry it structurally; undefined when the lane + // has no split view (messages IS the apply class). + compressMessages?: CoreMessage[]; } // #3192: the submit gate rejects any range that still cites a ref recorded DEAD @@ -67,6 +73,7 @@ export function liveCompressionRanges(ctx: AcpStatusCtx): { nudge: NudgeDecision tokenCount: statusInputBaseline(ctx.session), renderTags: "none", contentStore: contentStoreOf(ctx.session), + applyView: ctx.compressMessages, }); if (!turn.nudge) return undefined; const minChars = ctx.config.compress.minCompressRange; @@ -159,6 +166,10 @@ export function handleAcpStatus(args: Record, ctx: AcpStatusCtx tool, sort, limit, + // #3236: screen uncompressed rows through the same projection apply + // executes — on the exact array class this lane applies on. + config: ccrLoopConfig(ctx.session, ctx.config), + originalMessages: ctx.compressMessages ?? ctx.messages, meta: { pack: ctx.session.meta.activePack ?? "default", host: `billion-context ${VERSION} (${BUILD_COMMIT})`, diff --git a/src/plugin.ts b/src/plugin.ts index 4f82de0268..244eea0812 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -1460,6 +1460,9 @@ export function handlePluginStatus(conversationId: string, res: import("node:htt tokenCount: statusInputBaseline(session), renderTags: "none", contentStore: contentStoreOf(session), + // #3236: screen advertised ranges on the apply class — the raw + // history, not this panel's processed view (#2627 split). + applyView: mem && mem.original.length > 0 ? mem.original : undefined, }).nudge; } } catch { diff --git a/src/stream.ts b/src/stream.ts index 19399f45d6..a7d48eceb2 100644 --- a/src/stream.ts +++ b/src/stream.ts @@ -518,6 +518,8 @@ function postCompressTail(ctx: RewriteCtx, cleanSuccess: boolean, submitted: Arr tokenCount: statusInputBaseline(ctx.session), renderTags: "none", contentStore: contentStoreOf(ctx.session), + // #3236: screen advertised tail ranges on the apply class. + applyView: ctx.compressMessages, }); nudge = turn.nudge; } catch { From b07444b20aac182435b96ae27cebad6084de9492 Mon Sep 17 00:00:00 2001 From: awork Date: Thu, 15 Oct 2026 21:00:04 +0800 Subject: [PATCH 3/3] =?UTF-8?q?kernel:=20bump=20acp-kernel=200.0.125=20->?= =?UTF-8?q?=200.0.126=20=E2=80=94=20master=20consumed=200.0.125=20via=2016?= =?UTF-8?q?4f5d9e4,=20which=20erased=20this=20PR's=20version=20delta=20in?= =?UTF-8?q?=20the=20clean=20auto-merge=20and=20tripped=20kernel-guard=20ru?= =?UTF-8?q?le=202=20(#3236)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- kernel/package.json | 2 +- package-lock.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/kernel/package.json b/kernel/package.json index 4e287cdef4..db30ddde37 100644 --- a/kernel/package.json +++ b/kernel/package.json @@ -1,6 +1,6 @@ { "name": "acp-kernel", - "version": "0.0.125", + "version": "0.0.126", "description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.", "license": "MIT", "author": "ranxianglei", diff --git a/package-lock.json b/package-lock.json index 452f9a2adf..df29a2a51a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -48,7 +48,7 @@ }, "kernel": { "name": "acp-kernel", - "version": "0.0.125", + "version": "0.0.126", "dev": true, "license": "MIT", "devDependencies": {