From cc1e2408c822c66ca2852373b7e62e6afbb92ee7 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Sun, 8 Nov 2026 19:38:32 +0800 Subject: [PATCH 1/4] =?UTF-8?q?kernel:=20relocate-compress=20v2=20?= =?UTF-8?q?=E2=80=94=20summary=20text=20moves=20to=20the=20fold=20point,?= =?UTF-8?q?=20the=20pair=20stays=20in=20its=20slot=20with=20pointer=20args?= =?UTF-8?q?=20(#5470=20follow-up)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit v1 moved each still-visible compress call/result pair verbatim to its fold point. With the knob ON that leaves a mid-history wall of fully-shaped compress interactions, which weak-attention models (qwen3-27b) read as an invitation to keep compressing — observed as voluntary re-compress loops even while the ledger showed healthy headroom. v2 keeps exactly what the model needs at each spot: - the SUMMARY TEXT (args content) is re-emitted as a plain user text carrier at the fold point it describes ('[bili fold summary — block(s) bN …]'); - the pair KEEPS its chronological slot; the call core's args are replaced by a short pointer ('compression succeeded — summary relocated …; already folded — do not re-compress'), so it no longer reads as an open command; - the result core is forwarded verbatim (compression still 'succeeded'). View-only and deterministic as before; idempotent via carrier id (acp_reloc_) plus an args marker probe (survives host round-trips that strip synthetic ids). The call core rewrite is a shallow clone — input cores are never mutated. Boundary rule, ambiguity skips, #4732 tail fallback and the predicate-gated thinking clear are unchanged. kernel-change: fold-point relocation semantics v2 (owner-directed fix after live mis-behaviour analysis on a dev lane); kernel 0.0.187 → 0.0.188. --- kernel/package.json | 2 +- kernel/src/relocate-compress.ts | 169 ++++++++++++---- kernel/tests/relocate-compress.test.ts | 270 ++++++++++++++++--------- src/config.ts | 4 +- src/plugin-render.ts | 5 +- src/server/relay.ts | 10 +- src/web/i18n.ts | 8 +- 7 files changed, 312 insertions(+), 156 deletions(-) diff --git a/kernel/package.json b/kernel/package.json index 0749d68085..98de85b707 100644 --- a/kernel/package.json +++ b/kernel/package.json @@ -1,6 +1,6 @@ { "name": "acp-kernel", - "version": "0.0.187", + "version": "0.0.188", "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/relocate-compress.ts b/kernel/src/relocate-compress.ts index 47c8fa3231..bd0475fc5d 100644 --- a/kernel/src/relocate-compress.ts +++ b/kernel/src/relocate-compress.ts @@ -3,33 +3,52 @@ import { refNum } from "./hide-consumed.js"; import type { CompressionState, CoreMessage } from "./types.js"; /** Opt-in view transform (experimental, default OFF — see Config.compressAtFoldPoint): - * move each still-visible compress carrier pair from its ORIGINAL position to - * the fold point. + * relocate the SUMMARY TEXT of each still-visible compress carrier pair to the + * fold point, leaving the pair itself in its chronological slot with the call + * args replaced by a short pointer. * - * Why: the compress call/result pair is created at the TAIL of the live view at - * fold time and stays there (pi plugin mode persists it; the proxy loop re-rides - * ephemeral copies every round). For models with weak attention over long tails, - * a tool exchange sitting at the very end of resent history reads like a NEW - * command to execute — not as closed bookkeeping. Relocating the pair to sit - * directly after its own folded region ("[folded/summary region] – [compress - * pair] – [protected messages]") removes that ambiguity: the tail is clean, and - * the pair visibly belongs to the fold it documents. + * Semantics (v2, #5470 follow-up — replaces the verbatim-pair move): when the + * knob is on, for each compress call/result pair that still owns an active + * block: + * - a synthetic `user` text core carrying the call's summary text (the args + * `content`, or the raw args string when not JSON) is inserted directly + * after the pair's own folded region ("[folded region] – [summary carrier] – + * [protected messages]"); + * - the pair STAYS at its original (chronological) position — the tool + * exchange keeps reading as history, not as a fresh command — with the call + * core's args text replaced by a short pointer ("compression succeeded; + * summary relocated to its fold point above") so a weak-attention model + * cannot mistake the pair for an unfinished compression. The result core is + * forwarded verbatim. + * + * Why v2: with the v1 verbatim move, every historical pair stays visible + * mid-history as a fully-shaped compress interaction — for weak-attention + * models that gallery reads as an open invitation to keep compressing + * (observed: voluntary re-compress loops). v2 keeps exactly one recent + * interaction shape per fold (the pointer pair, which explicitly says + * "already folded") and renders the payloads the model actually needs to + * re-read (the summaries) as plain text at the place they describe. * * Invariants: * - VIEW-ONLY + deterministic f(history, state): nothing is persisted, refs are * untouched (assign-refs already ran; messageRefs is a persistent id→ref map), * so the layout is recomputed identically on every turn — byte-stable from the * second turn on, no incremental prefix-cache cost beyond the fold's own break. - * - Pair integrity: a pair moves only when BOTH cores are present, in order, - * adjacent, and unambiguous (exactly one tool-call core per active-block call - * id). Any anomaly → the pair stays where it is (the safe direction). - * - Boundary rule: insert before the first surviving core whose allocated ref is - * strictly greater than max(endRef) across the blocks this call created - * (multi-range batches → rightmost boundary); when none exists (fold reaches - * the window end, #4732 regime) append at the tail instead. + * The call core is rewritten via a shallow CLONE (input cores are never + * mutated — callers reuse them for persistence and round-2 rebuilds). + * - Idempotent: a call id whose carrier (`acp_reloc_`) is already + * present, or whose args already carry the relocation marker, is skipped — + * re-running the transform on its own output is a same-reference no-op. + * - Pair integrity: a call is rewritten only when BOTH cores are present, in + * order, adjacent, and unambiguous (exactly one tool-call core per active + * block's call id). Any anomaly → the pair stays verbatim (safe direction). + * - Boundary rule: insert the carrier before the first surviving core whose + * allocated ref is strictly greater than max(endRef) across the blocks this + * call created (multi-range batches → rightmost boundary); when none exists + * (fold reaches the window end, #4732 regime) append at the tail instead. * - Thinking clear (second opt-in, default off, predicate-gated): the run of - * contiguous `reasoning` cores immediately preceding a moved call may be - * dropped IF opts.reasoningDroppable accepts each one. Without a predicate + * contiguous `reasoning` cores immediately preceding the pair may be dropped + * IF opts.reasoningDroppable accepts each one. Without a predicate * NOTHING is dropped — signed-thinking / strict-echo awareness lives in the * host (it owns the wire signatures), and the conservative default here is * "never drop". */ @@ -37,7 +56,7 @@ export interface RelocateOptions { /** Same contract as Config.isCompressTool: host dialect names count as a * compress call. Unset = bare-name only. */ isCompressTool?: (toolName: string) => boolean; - /** Enable the #651-style reasoning drop around moved pairs. */ + /** Enable the #651-style reasoning drop around kept pairs. */ clearThinking?: boolean; /** Host predicate deciding which reasoning cores may be dropped (signed * thinking and strict-echo sessions must answer false). UNSET ⇒ no drop even @@ -49,16 +68,22 @@ export interface RelocateMove { callId: string; /** Index of the tool-call core in the input array. */ callIndex: number; - /** Survivor ordinal: emit before the k-th surviving (non-removed) input. - * k == total survivors ⇒ tail append (#4732 regime). */ + /** Index of the tool-result core in the input array (stays in place, verbatim). */ + resultIndex: number; + /** Survivor ordinal: emit the carrier before the k-th surviving (non-removed) + * input. k == total survivors ⇒ tail append (#4732 regime). */ insertAtOutput: number; /** Input indices of dropped reasoning cores (adjacent run before the call). */ droppedReasoningIndices: number[]; + /** Synthetic fold-point carrier carrying the relocated summary text. */ + carrier: CoreMessage; + /** Replacement args text for the call core (pointer JSON). */ + pointerText: string; } export interface RelocatePlan { moves: RelocateMove[]; - /** Input indices of ALL cores removed (pairs + dropped reasoning). */ + /** Input indices of ALL cores removed (dropped reasoning only — pairs stay). */ removedInputIndices: Set; changed: boolean; } @@ -66,6 +91,31 @@ export interface RelocatePlan { const bareIsCompressTool = (toolName: string | undefined): boolean => toolName === "compress"; +/** Marker embedded in the pointer args text; also the idempotency detector for + * hosts that round-trip a view whose carrier ids did not survive. */ +export const RELOCATED_POINTER_MARKER = + "[bili] compression succeeded — summary relocated"; + +const carrierIdFor = (callId: string): string => `acp_reloc_${callId}`; + +/** Pull the summary text out of a compress call's args. The plugin dialect + * rides JSON `{"content": "…"}`; anything else is used verbatim. Pure. */ +function summaryTextOf(callText: string | undefined): string { + if (!callText) return ""; + try { + const parsed: unknown = JSON.parse(callText); + if ( + typeof parsed === "object" && parsed !== null && + typeof (parsed as { content?: unknown }).content === "string" + ) { + return (parsed as { content: string }).content; + } + } catch { + // not JSON — raw args are the summary + } + return callText; +} + /** Compute the relocation plan for `messages` under `state`. Pure: same inputs * always yield the same plan (host-side determinism requirement). */ export function planRelocateCompressCarriers( @@ -79,12 +129,16 @@ export function planRelocateCompressCarriers( // 1. Which call ids still own an ACTIVE block whose boundaries are numeric // (legacy blocks lack start/endRef — they cannot get a boundary, skip). const endRefNumByCallId = new Map(); + const blockIdsByCallId = new Map(); for (const block of state.blocks) { if (!block.active || !block.compressCallId) continue; const n = refNum(block.endRef); if (n === null) continue; // legacyLiveByCallId-era or unresolved boundary const prev = endRefNumByCallId.get(block.compressCallId) ?? 0; if (n > prev) endRefNumByCallId.set(block.compressCallId, n); + const ids = blockIdsByCallId.get(block.compressCallId); + if (ids === undefined) blockIdsByCallId.set(block.compressCallId, [block.blockId]); + else ids.push(block.blockId); } if (endRefNumByCallId.size === 0) { return { moves: [], removedInputIndices: new Set(), changed: false }; @@ -95,6 +149,11 @@ export function planRelocateCompressCarriers( return ref === undefined || ref === BLOCKED_REF ? null : refNum(ref); }; + // Idempotency probes (view-only transform may be re-run on its own output + // by the relay round-2 mirror and the plugin-render mirror). + const presentCarrierIds = new Set(); + for (const m of messages) presentCarrierIds.add(m.id); + // 2. Locate candidate pairs (one pass; duplicates disqualify their call id). const callsByCallId = new Map(); for (let i = 0; i < messages.length; i++) { @@ -110,17 +169,33 @@ export function planRelocateCompressCarriers( const moves: RelocateMove[] = []; const removed = new Set(); for (const [callId, callIndices] of [...callsByCallId.entries()].sort((a, b) => a[0] < b[0] ? -1 : 1)) { - if (callIndices.length !== 1) continue; // ambiguous carrier: do not move + if (callIndices.length !== 1) continue; // ambiguous carrier: do not touch const j = callIndices[0]!; + // Already relocated in a previous pass of this view? Skip entirely. + if (presentCarrierIds.has(carrierIdFor(callId))) continue; + if ((messages[j]!.text ?? "").includes(RELOCATED_POINTER_MARKER)) continue; const resultIndex = j + 1; const r = messages[resultIndex]; if (!r || r.contentType !== "tool-result" || r.toolCallId !== callId) continue; - // Adjacent ordered pair confirmed. Record removals up front so later - // boundary scans never mistake another planned pair for a survivor. - removed.add(j); - removed.add(resultIndex); + // Adjacent ordered pair confirmed. + const blockIds = blockIdsByCallId.get(callId) ?? []; + const blockLabel = blockIds.length > 0 ? `block(s) ${blockIds.join(", ")}` : "fold"; + const summary = summaryTextOf(messages[j]!.text); + const carrier: CoreMessage = { + id: carrierIdFor(callId), + role: "user", + contentType: "text", + text: + `[bili fold summary — ${blockLabel}; relocated from compress call ${callId} ` + + `(the call/result exchange stays in its chronological slot below)]\n${summary}`, + }; + const pointerText = JSON.stringify({ + content: + `${RELOCATED_POINTER_MARKER} to its fold point above (${blockLabel}); ` + + `these ranges are already folded — do not re-compress them.`, + }); // 3. Optional thinking clear: contiguous reasoning run directly before the - // call, predicate-gated per core (predicate unset ⇒ drop nothing). + // pair, predicate-gated per core (predicate unset ⇒ drop nothing). const droppedReasoningIndices: number[] = []; if (opts.clearThinking && typeof opts.reasoningDroppable === "function") { for (let k = j - 1; k >= 0; k--) { @@ -132,16 +207,18 @@ export function planRelocateCompressCarriers( } } } - moves.push({ callId, callIndex: j, insertAtOutput: 0, droppedReasoningIndices }); + moves.push({ callId, callIndex: j, resultIndex, insertAtOutput: 0, droppedReasoningIndices, carrier, pointerText }); } if (moves.length === 0) { return { moves: [], removedInputIndices: new Set(), changed: false }; } // 4. Resolve each insertion point against the INPUT array, then convert to - // output space (output = input minus `removed`). A qualifying survivor is - // any non-removed core whose ref strictly exceeds this call's boundary — - // chronology of allocated refs equals ingest order (monotonic mint). + // output space (output = input minus `removed`). A qualifying survivor is + // any non-removed core whose ref strictly exceeds this call's boundary — + // chronology of allocated refs equals ingest order (monotonic mint). The + // kept pair cores themselves carry no refs (tool-call/result cores are not + // ref-minted), so they never qualify as boundaries. for (const move of moves) { const boundary = endRefNumByCallId.get(move.callId)!; let at = messages.length; // tail fallback (#4732 regime) @@ -166,15 +243,19 @@ export function planRelocateCompressCarriers( return { moves, removedInputIndices: removed, changed: true }; } -/** Apply the plan to `messages`, returning a NEW array when anything moved. +/** Apply the plan to `messages`, returning a NEW array when anything changed. * Fast path: no-op plans return the SAME array reference (byte-identical * guarantee for the default-off regime). * * Placement keys on the SURVIVOR ordinal, not the raw output length: a - * move "with insertAtOutput k" must appear right BEFORE the k-th surviving - * input. Emitted pairs grow the output array between survivors, so keying on - * out.length would skip slots whenever an earlier pair landed first (two - * calls folding different ranges may legally interleave). */ + * carrier "with insertAtOutput k" must appear right BEFORE the k-th surviving + * input. Emitted carriers grow the output array between survivors, so keying on + * out.length would skip slots whenever an earlier carrier landed first (two + * calls folding different ranges may legally interleave). + * + * The rewritten call core is a shallow CLONE of the input (view-only purity: + * callers reuse input cores for persistence and round-2 rebuilds); every other + * core is forwarded by reference. */ export function relocateCompressCarriers( messages: CoreMessage[], state: CompressionState, @@ -183,13 +264,15 @@ export function relocateCompressCarriers( const plan = planRelocateCompressCarriers(messages, state, opts); if (!plan.changed) return messages; const dueAt = new Map(); + const rewrite = new Map(); // input index → pointer args for (const move of plan.moves) { const list = dueAt.get(move.insertAtOutput); if (list === undefined) dueAt.set(move.insertAtOutput, [move]); else list.push(move); + rewrite.set(move.callIndex, move.pointerText); } // Per-slot order: earliest call slot first (deterministic tie-break when - // several pairs share one insertion point). + // several carriers share one insertion point). for (const list of dueAt.values()) { list.sort((a, b) => a.callIndex - b.callIndex); } @@ -198,15 +281,15 @@ export function relocateCompressCarriers( const due = dueAt.get(k); if (due === undefined) return; dueAt.delete(k); - for (const move of due) { - out.push(messages[move.callIndex]!, messages[move.callIndex + 1]!); - } + for (const move of due) out.push(move.carrier); }; let survivors = 0; for (let i = 0; i < messages.length; i++) { if (plan.removedInputIndices.has(i)) continue; flushDue(survivors); - out.push(messages[i]!); + const m = messages[i]!; + const pointer = rewrite.get(i); + out.push(pointer === undefined ? m : { ...m, text: pointer }); survivors++; } flushDue(survivors); // tail fallback (#4732 regime) diff --git a/kernel/tests/relocate-compress.test.ts b/kernel/tests/relocate-compress.test.ts index 392469884b..c95f9e4ae2 100644 --- a/kernel/tests/relocate-compress.test.ts +++ b/kernel/tests/relocate-compress.test.ts @@ -4,6 +4,7 @@ import { createInitialState } from "../src/state.js"; import { planRelocateCompressCarriers, relocateCompressCarriers, + RELOCATED_POINTER_MARKER, } from "../src/relocate-compress.js"; import type { CompressionBlock, @@ -72,6 +73,7 @@ function pair(callId: string) { } const ids = (ms: CoreMessage[]): string[] => ms.map((m) => m.id); +const carrierId = (callId: string): string => `acp_reloc_${callId}`; test("no active block with numeric endRef ⇒ same array reference (no-op fast path)", () => { const messages = [msg("a", "m00001", "text")]; @@ -101,10 +103,12 @@ test("inactive block is skipped even with numeric endRef", () => { assert.equal(relocateCompressCarriers(messages, state), messages); }); -test("basic move: pair lands before first surviving core whose ref exceeds endRef", () => { - // Fold covered m00001–m00002; protected survivors c (m00003), d (m00004). - const a = msg("a", "m00003", "user"); - const b = msg("b", "m00004", "assistant"); +test("basic relocate: summary carrier lands at the fold point, pair stays in its slot with pointer args", () => { + // Fold covered m00001–m00002; protected survivors a (m00003), b (m00004); the + // pair sits chronologically AFTER the survivors (the model compressed older + // history later on). + const a = msg("a", "m00003", "text"); + const b = msg("b", "m00004", "text"); const [c, r] = pair("call1"); const messages = [a, b, c, r]; const state = stateWith( @@ -112,63 +116,113 @@ test("basic move: pair lands before first surviving core whose ref exceeds endRe { a: "m00003", b: "m00004" }, ); const out = relocateCompressCarriers(messages, state); - // Survivors a (ref 3 > 2), so the pair must precede a — nothing before it. - assert.deepEqual(ids(out), ["call-call1", "res-call1", "a", "b"]); - // Original cores are moved by reference, never cloned. - assert.equal(out[0], c); - assert.equal(out[1], r); + // Carrier before the first survivor past the boundary (a, ref 3 > 2); the + // pair keeps its chronological slot at the end. + assert.deepEqual(ids(out), [carrierId("call1"), "a", "b", "call-call1", "res-call1"]); + // Survivors and the result core are forwarded by reference, never cloned. + assert.equal(out[1], a); + assert.equal(out[2], b); + assert.equal(out[4], r); + // The call core is a shallow CLONE carrying the pointer args. + assert.notEqual(out[3], c); + assert.ok(out[3]!.text!.includes(RELOCATED_POINTER_MARKER)); + assert.ok(out[3]!.text!.includes("b1")); + // The input core is not mutated. + assert.equal(c.text, "text-of-call-call1"); }); -test("pair already at its fold point keeps relative layout but still normalizes (moved-by-ref)", () => { - const a = msg("a", "m00005", "user"); - const b = msg("b", "m00006", "assistant"); +test("carrier text carries the summary; non-JSON args are used verbatim", () => { + const a = msg("a", "m00003", "text"); const [c, r] = pair("call1"); - const messages = [c, r, a, b]; // already before all survivors + c.text = "RAW-SUMMARY-BODY"; + const messages = [a, c, r]; const state = stateWith( - [{ blockId: "b1", compressCallId: "call1", startRef: "m00001", endRef: "m00004" }], - { a: "m00005", b: "m00006" }, + [{ blockId: "b1", compressCallId: "call1", startRef: "m00001", endRef: "m00002" }], + { a: "m00003" }, ); const out = relocateCompressCarriers(messages, state); - assert.deepEqual(ids(out), ["call-call1", "res-call1", "a", "b"]); + const carrier = out[0]!; + assert.equal(carrier.id, carrierId("call1")); + assert.equal(carrier.role, "user"); + assert.equal(carrier.contentType, "text"); + assert.ok(carrier.text!.startsWith(`[bili fold summary — block(s) b1; relocated from compress call call1`)); + assert.ok(carrier.text!.endsWith("\nRAW-SUMMARY-BODY")); }); -test("multi-range batch shares one call id ⇒ boundary is max(endRef)", () => { - const x = msg("x", "m00008", "user"); // inside later fold range - const y = msg("y", "m00011", "assistant"); // only survivor past both folds - const [c, r] = pair("callB"); - // Live views follow ingest (ref) order: x (8) precedes y (11). - const messages = [x, c, r, y]; +test("carrier text extracts .content from JSON args (plugin dialect)", () => { + const a = msg("a", "m00003", "text"); + const [c, r] = pair("call1"); + c.text = JSON.stringify({ content: "SUMMARY-TEXT", ranges: ["m00001-m00002"] }); + const messages = [a, c, r]; const state = stateWith( - [ - { blockId: "b1", compressCallId: "callB", startRef: "m00001", endRef: "m00005" }, - { blockId: "b2", compressCallId: "callB", startRef: "m00007", endRef: "m00010" }, - ], - { y: "m00011", x: "m00008" }, + [{ blockId: "b1", compressCallId: "call1", startRef: "m00001", endRef: "m00002" }], + { a: "m00003" }, ); - // Boundary = max(5,10)=10 ⇒ insert before y (11 > 10), after surviving x (8). const out = relocateCompressCarriers(messages, state); - assert.deepEqual(ids(out), ["x", "call-callB", "res-callB", "y"]); + const carrier = out[0]!; + assert.ok(carrier.text!.includes("SUMMARY-TEXT")); + assert.ok(!carrier.text!.includes("SUMMARY-TEXT\"")); // no JSON wrapper residue }); -test("fold reaches the window end (#4732 regime) ⇒ append at tail", () => { +test("pointer args are valid JSON embedding the marker and the block ids", () => { + const a = msg("a", "m00003", "text"); const [c, r] = pair("call1"); - const a = msg("a", "m00002", "user"); // only core; ref ≤ boundary const messages = [a, c, r]; const state = stateWith( [{ blockId: "b1", compressCallId: "call1", startRef: "m00001", endRef: "m00002" }], - { a: "m00002" }, + { a: "m00003" }, ); const out = relocateCompressCarriers(messages, state); - assert.deepEqual(ids(out), ["a", "call-call1", "res-call1"]); + const callOut = out.find((m) => m.id === "call-call1")!; + const parsed = JSON.parse(callOut.text!) as { content: string }; + assert.ok(parsed.content.startsWith(RELOCATED_POINTER_MARKER)); + assert.ok(parsed.content.includes("b1")); + assert.ok(parsed.content.includes("do not re-compress")); +}); + +test("already relocated call (marker in args, carrier present) ⇒ same array reference", () => { + // Hosts may round-trip a view: carrier ids survive AND the args keep the + // pointer. Both probes must independently make the plan a no-op. + const a = msg("a", "m00003", "text"); + const [c, r] = pair("call1"); + const once = relocateCompressCarriers([a, c, r], stateWith( + [{ blockId: "b1", compressCallId: "call1", startRef: "m00001", endRef: "m00002" }], + { a: "m00003" }, + )); + // Carrier present ⇒ skip. + assert.equal(relocateCompressCarriers(once, stateWith( + [{ blockId: "b1", compressCallId: "call1", startRef: "m00001", endRef: "m00002" }], + { a: "m00003" }, + )), once); + // Marker only (carrier id stripped by a host round-trip) ⇒ skip. + const markerOnly: CoreMessage[] = once.filter((m) => m.id !== carrierId("call1")); + assert.equal(relocateCompressCarriers(markerOnly, stateWith( + [{ blockId: "b1", compressCallId: "call1", startRef: "m00001", endRef: "m00002" }], + { a: "m00003" }, + )), markerOnly); }); -test("duplicate tool-call cores for one call id ⇒ ambiguous, do not move", () => { +test("idempotent: applying twice yields the identical array", () => { + const a = msg("a", "m00003", "text"); + const b = msg("b", "m00004", "text"); + const [c, r] = pair("call1"); + const messages = [a, b, c, r]; + const state = stateWith( + [{ blockId: "b1", compressCallId: "call1", startRef: "m00001", endRef: "m00002" }], + { a: "m00003", b: "m00004" }, + ); + const once = relocateCompressCarriers(messages, state); + const twice = relocateCompressCarriers(once, state); + assert.equal(twice, once); +}); + +test("duplicate tool-call cores for one call id ⇒ ambiguous, do not touch", () => { const [c1, r1] = pair("call1"); const c2 = msg("call-call1-again", null, "tool-call", { toolName: "compress", toolCallId: "call1", }); - const messages = [msg("a", "m00003", "user"), c1, r1, c2]; + const messages = [msg("a", "m00003", "text"), c1, r1, c2]; const state = stateWith( [{ blockId: "b1", compressCallId: "call1", startRef: "m00001", endRef: "m00002" }], { a: "m00003" }, @@ -183,7 +237,7 @@ test("non-adjacent result (foreign core between call and result) ⇒ skip", () = }); const result = msg("mr", null, "tool-result", { toolCallId: "call1" }); const foreign = msg("f", "m00003", "text"); - const messages = [msg("a", "m00004", "user"), call, foreign, result]; + const messages = [msg("a", "m00004", "text"), call, foreign, result]; const state = stateWith( [{ blockId: "b1", compressCallId: "call1", startRef: "m00001", endRef: "m00002" }], { a: "m00004", f: "m00003" }, @@ -197,7 +251,7 @@ test("result with mismatched toolCallId ⇒ not a pair, skip", () => { toolCallId: "call1", }); const result = msg("mr", null, "tool-result", { toolCallId: "other" }); - const messages = [msg("a", "m00003", "user"), call, result]; + const messages = [msg("a", "m00003", "text"), call, result]; const state = stateWith( [{ blockId: "b1", compressCallId: "call1", startRef: "m00001", endRef: "m00002" }], { a: "m00003" }, @@ -206,31 +260,64 @@ test("result with mismatched toolCallId ⇒ not a pair, skip", () => { }); test("BLOCKED_REF cores are not qualifying boundaries (durable-BLOCKED edge)", () => { - const protectedMsg = msg("prot", "BLOCKED", "user"); + const protectedMsg = msg("prot", "BLOCKED", "text"); const [c, r] = pair("call1"); const messages = [protectedMsg, c, r]; const state = stateWith( [{ blockId: "b1", compressCallId: "call1", startRef: "m00001", endRef: "m00002" }], { prot: "BLOCKED" }, ); - // Nothing qualifies beyond the boundary ⇒ tail append (position unchanged here). + // Nothing qualifies beyond the boundary ⇒ carrier appended at the tail; the + // pair stays in its slot untouched except the pointer rewrite. const out = relocateCompressCarriers(messages, state); - assert.deepEqual(ids(out), ["prot", "call-call1", "res-call1"]); + assert.deepEqual(ids(out), ["prot", "call-call1", "res-call1", carrierId("call1")]); assert.equal(out[0], protectedMsg); }); +test("multi-range batch shares one call id ⇒ boundary is max(endRef), pointer lists all blocks", () => { + const x = msg("x", "m00008", "text"); // inside later fold range + const y = msg("y", "m00011", "text"); // only survivor past both folds + const [c, r] = pair("callB"); + // Live views follow ingest (ref) order: x (8) precedes y (11). + const messages = [x, c, r, y]; + const state = stateWith( + [ + { blockId: "b1", compressCallId: "callB", startRef: "m00001", endRef: "m00005" }, + { blockId: "b2", compressCallId: "callB", startRef: "m00007", endRef: "m00010" }, + ], + { y: "m00011", x: "m00008" }, + ); + // Boundary = max(5,10)=10 ⇒ carrier before y (11 > 10), after x (8). + const out = relocateCompressCarriers(messages, state); + assert.deepEqual(ids(out), ["x", "call-callB", "res-callB", carrierId("callB"), "y"]); + const callOut = out.find((m) => m.id === "call-callB")!; + assert.ok(callOut.text!.includes("b1, b2")); +}); + +test("fold reaches the window end (#4732 regime) ⇒ carrier appended at tail", () => { + const [c, r] = pair("call1"); + const a = msg("a", "m00002", "text"); // only core; ref ≤ boundary + const messages = [a, c, r]; + const state = stateWith( + [{ blockId: "b1", compressCallId: "call1", startRef: "m00001", endRef: "m00002" }], + { a: "m00002" }, + ); + const out = relocateCompressCarriers(messages, state); + assert.deepEqual(ids(out), ["a", "call-call1", "res-call1", carrierId("call1")]); +}); + test("thinking clear: predicate unset ⇒ reasoning kept even with clearThinking set", () => { const think = msg("t1", "m00009", "reasoning"); const [c, r] = pair("call1"); - const a = msg("a", "m00010", "user"); + const a = msg("a", "m00010", "text"); const messages = [think, c, r, a]; const state = stateWith( [{ blockId: "b1", compressCallId: "call1", startRef: "m00001", endRef: "m00008" }], { a: "m00010" }, ); const out = relocateCompressCarriers(messages, state, { clearThinking: true }); - // Pair moves before a; thinking follows it (kept). - assert.deepEqual(ids(out), ["t1", "call-call1", "res-call1", "a"]); + // Pair stays in its slot; thinking kept; carrier before the first ref>8 (a). + assert.deepEqual(ids(out), ["t1", "call-call1", "res-call1", carrierId("call1"), "a"]); }); test("thinking clear: predicate-gated drop of the contiguous run before the call", () => { @@ -238,28 +325,30 @@ test("thinking clear: predicate-gated drop of the contiguous run before the call const drop1 = msg("d1", "m00007", "reasoning"); const drop2 = msg("d2", "m00008", "reasoning"); const [c, r] = pair("call1"); - const a = msg("a", "m00010", "user"); + const a = msg("a", "m00010", "text"); const messages = [keep1, drop1, drop2, c, r, a]; const state = stateWith( [{ blockId: "b1", compressCallId: "call1", startRef: "m00001", endRef: "m00005" }], { a: "m00010", k1: "m00006" }, ); // Predicate accepts d1/d2 but refuses k1 (e.g. signed) — scan continues PAST - // the refused core (documented behaviour). k1 survives with ref 6 > boundary - // 5, so the pair lands before it. + // the refused core (documented behaviour). Dropped cores never qualify as + // boundaries; first qualifying survivor is k1 (6 > 5). + // v2: the pair KEEPS its slot (after k1 in the input); only the carrier + // moves (before k1, the first qualifying survivor). const out = relocateCompressCarriers(messages, state, { clearThinking: true, reasoningDroppable: (m) => m.id !== "k1", }); - assert.deepEqual(ids(out), ["call-call1", "res-call1", "k1", "a"]); - assert.equal(out[2], keep1); + assert.deepEqual(ids(out), [carrierId("call1"), "k1", "call-call1", "res-call1", "a"]); + assert.equal(out[1], keep1); }); test("thinking clear: non-reasoning core stops the walk", () => { const textBefore = msg("t0", "m00006", "text"); const drop = msg("d1", "m00007", "reasoning"); const [c, r] = pair("call1"); - const a = msg("a", "m00010", "user"); + const a = msg("a", "m00010", "text"); const messages = [textBefore, drop, c, r, a]; const state = stateWith( [{ blockId: "b1", compressCallId: "call1", startRef: "m00001", endRef: "m00005" }], @@ -269,46 +358,17 @@ test("thinking clear: non-reasoning core stops the walk", () => { clearThinking: true, reasoningDroppable: () => true, }); - assert.deepEqual(ids(out), ["t0", "call-call1", "res-call1", "a"]); + assert.deepEqual(ids(out), ["t0", "call-call1", "res-call1", carrierId("call1"), "a"]); }); -test("clearThinking without a predicate is a no-op for drops (conservative default)", () => { - const drop = msg("d1", "m00007", "reasoning"); - const [c, r] = pair("call1"); - const a = msg("a", "m00010", "user"); - const messages = [drop, c, r, a]; - const state = stateWith( - [{ blockId: "b1", compressCallId: "call1", startRef: "m00001", endRef: "m00005" }], - { a: "m00010" }, - ); - const out = relocateCompressCarriers(messages, state, { clearThinking: true }); - assert.deepEqual(ids(out), ["d1", "call-call1", "res-call1", "a"]); -}); - -test("idempotent: applying twice yields the identical layout", () => { - const a = msg("a", "m00003", "user"); - const b = msg("b", "m00004", "assistant"); - const [c, r] = pair("call1"); - const messages = [a, b, c, r]; - const state = stateWith( - [{ blockId: "b1", compressCallId: "call1", startRef: "m00001", endRef: "m00002" }], - { a: "m00003", b: "m00004" }, - ); - const once = relocateCompressCarriers(messages, state); - const twice = relocateCompressCarriers(once, state); - assert.deepEqual(ids(twice), ids(once)); - for (let i = 0; i < once.length; i++) assert.equal(twice[i], once[i]); -}); - -test("interleaved calls: each pair lands at its own boundary regardless of slot order", () => { - // A folds m00001–m00005, B folds m00006–m00008; survivors p (m00001? no—p is - // pre-fold), q m00009... Construct post-fold reality: survivors only. - const s1 = msg("s1", "m00009", "user"); - const s2 = msg("s2", "m00010", "assistant"); - const s3 = msg("s3", "m00011", "user"); +test("interleaved calls: carriers land at their boundaries regardless of pair slot order", () => { + const s1 = msg("s1", "m00009", "text"); + const s2 = msg("s2", "m00010", "text"); + const s3 = msg("s3", "m00011", "text"); const [pa, ra] = pair("callA"); const [pb, rb] = pair("callB"); - // B's pair sits EARLIER than A's although A's boundary (5) is smaller. + // B's pair sits EARLIER than A's although A's boundary (5) is smaller; both + // pairs keep their slots, only carriers are emitted (k=0 for both). const messages = [s1, pb, rb, pa, ra, s2, s3]; const state = stateWith( [ @@ -317,23 +377,23 @@ test("interleaved calls: each pair lands at its own boundary regardless of slot ], { s1: "m00009", s2: "m00010", s3: "m00011" }, ); - // A: first survivor with ref>5 ⇒ s1 ⇒ k=0. B: same ⇒ k=0 too (both before s1); - // tie-break by original callIndex (pb earlier) ⇒ pb,rb then pa,ra. const out = relocateCompressCarriers(messages, state); assert.deepEqual(ids(out), [ + carrierId("callB"), + carrierId("callA"), + "s1", "call-callB", "res-callB", "call-callA", "res-callA", - "s1", "s2", "s3", ]); }); -test("two distinct boundaries place pairs at different survivor slots", () => { - const t1 = msg("t1", "m00003", "user"); // > 2 (A's boundary) but ≤ 8 (B's) - const s2 = msg("s2", "m00009", "assistant"); // > 8 +test("two distinct boundaries place carriers at different survivor slots", () => { + const t1 = msg("t1", "m00003", "text"); // > 2 (A's boundary) but ≤ 8 (B's) + const s2 = msg("s2", "m00009", "text"); // > 8 const [pa, ra] = pair("callA"); const [pb, rb] = pair("callB"); const messages = [t1, s2, pa, ra, pb, rb]; @@ -347,17 +407,19 @@ test("two distinct boundaries place pairs at different survivor slots", () => { const out = relocateCompressCarriers(messages, state); // A ⇒ before t1 (ref 3 > 2) ⇒ k=0; B ⇒ before s2 (first ref > 8) ⇒ k=1. assert.deepEqual(ids(out), [ + carrierId("callA"), + "t1", + carrierId("callB"), + "s2", "call-callA", "res-callA", - "t1", "call-callB", "res-callB", - "s2", ]); }); test("refs are untouched by relocation", () => { - const a = msg("a", "m00003", "user"); + const a = msg("a", "m00003", "text"); const [c, r] = pair("call1"); const messages = [a, c, r]; const state = stateWith( @@ -375,23 +437,23 @@ test("isCompressTool override honours dialect names", () => { toolCallId: "callX", }); const result = msg("mr", null, "tool-result", { toolCallId: "callX" }); - const a = msg("a", "m00003", "user"); + const a = msg("a", "m00003", "text"); const messages = [a, call, result]; const state = stateWith( [{ blockId: "bx", compressCallId: "callX", startRef: "m00001", endRef: "m00002" }], { a: "m00003" }, ); - // Bare-name matching alone would NOT move this pair. + // Bare-name matching alone would NOT relocate this pair. assert.equal(relocateCompressCarriers(messages, state), messages); // With the host dialect predicate it does. const out = relocateCompressCarriers(messages, state, { isCompressTool: (n) => n === "acp_compress", }); - assert.deepEqual(ids(out), ["mc", "mr", "a"]); + assert.deepEqual(ids(out), [carrierId("callX"), "a", "mc", "mr"]); }); -test("plan and apply agree on removed indices", () => { - const a = msg("a", "m00003", "user"); +test("plan and apply agree: no pair removals in v2, pointer+carrier well-formed", () => { + const a = msg("a", "m00003", "text"); const [c, r] = pair("call1"); const messages = [a, c, r]; const state = stateWith( @@ -400,7 +462,13 @@ test("plan and apply agree on removed indices", () => { ); const plan = planRelocateCompressCarriers(messages, state); assert.equal(plan.changed, true); - assert.deepEqual([...plan.removedInputIndices].sort((x, y) => x - y), [1, 2]); + // v2: the pair is NOT removed — only dropped reasoning ever lands here. + assert.deepEqual([...plan.removedInputIndices], []); assert.equal(plan.moves.length, 1); - assert.equal(plan.moves[0].insertAtOutput, 0); + const move = plan.moves[0]!; + assert.equal(move.callIndex, 1); + assert.equal(move.resultIndex, 2); + assert.equal(move.insertAtOutput, 0); // before a (ref 3 > 2) + assert.equal(move.carrier.id, carrierId("call1")); + assert.ok(move.pointerText.includes(RELOCATED_POINTER_MARKER)); }); diff --git a/src/config.ts b/src/config.ts index 82424f4587..b3a63447f8 100644 --- a/src/config.ts +++ b/src/config.ts @@ -663,7 +663,9 @@ export type CompressSettings = { * and state are untouched; identical layout is recomputed every turn. * Env BILI_COMPRESS_AT_FOLD_POINT wins over every level; * applyCompressSettings resolves it per request. Maps to kernel - * Config.compressAtFoldPoint (acp-kernel >= 0.0.177). */ + * Config.compressAtFoldPoint (acp-kernel >= 0.0.177; v2 semantics since + * 0.0.188 — summary text relocated to the fold point, pair kept in slot + * with pointer args). */ compressAtFoldPoint?: boolean; /** Second opt-in riding on compressAtFoldPoint (default OFF): also drop * the contiguous run of UNSIGNED reasoning cores immediately preceding a diff --git a/src/plugin-render.ts b/src/plugin-render.ts index 77f82386ed..cbc118043e 100644 --- a/src/plugin-render.ts +++ b/src/plugin-render.ts @@ -136,8 +136,9 @@ export async function handlePluginRender(req: http.IncomingMessage, res: http.Se // Fold-point carrier relocation mirror (switch A): with the knob on, move // still-visible compress pairs from their original slot to their fold point // — the same view-only transform the kernel node applies on processTurn, - // so the rendered prefix and steady turns agree. S4 has no per-request - // strictness context, so move-only (no thinking clear here). + // so the rendered prefix and steady turns agree (v2: summary text relocated + // to the fold point, pair kept in slot with pointer args). S4 has no + // per-request strictness context, so no thinking clear here. // KNOWN ASYMMETRY (v1, #5470 review): the knob is read from env + the // global `compress` file section only, while steady turns resolve through // the full cascade — a key set at a provider/model tier moves pairs on diff --git a/src/server/relay.ts b/src/server/relay.ts index 30d7dcf175..88d633c1cc 100644 --- a/src/server/relay.ts +++ b/src/server/relay.ts @@ -2262,10 +2262,12 @@ async function forwardCaptured( // against them drops the only cross-turn summary carrier and breaks the byte-prefix // at the fold anchor (post-fold cache floor reset to the stable head). const outBase = [...stripKernelSummaries(viewed as BiliMessage[], turn.state), ...(records as BiliMessage[])] as BiliMessage[]; - // Fold-point carrier relocation round-2 mirror (switch A): with the - // switch on, pairs sit at their fold point instead of being - // tail-appended onto the re-request. Idempotent when processTurn's - // node already moved them (view-only + deterministic transform). + // Fold-point summary relocation round-2 mirror (switch A): with + // the switch on, each still-visible compress pair keeps its + // chronological slot but its SUMMARY TEXT is re-emitted at its + // fold point (call args become a pointer — v2 semantics). + // Idempotent when processTurn's node already relocated them + // (view-only + deterministic transform). const out = loopConfig.compressAtFoldPoint ? relocateCompressCarriers(outBase as unknown as CoreMessage[], turn.state, { isCompressTool: loopConfig.isCompressTool, diff --git a/src/web/i18n.ts b/src/web/i18n.ts index 55596f5072..c0226c238f 100644 --- a/src/web/i18n.ts +++ b/src/web/i18n.ts @@ -578,8 +578,8 @@ export const MESSAGES: Record> = { "cfg.q_dsh_ctxtab_label": "DSH「上下文」标签页名称(dsh.contextTabLabel)——留空用内置名「上下文」,可改名避免与其他插件重名", "cfg.q_absorb": "工具结果即时蒸馏(absorb)——大工具结果到达时由模型即时蒸馏,原文隐藏到下一轮折叠前(默认关)", "cfg.q_absorb_hint": "默认只吸含图结果(#3422);mediaOnly: false 可恢复吸全文。子项(minToolTokens、contextThresholdPct、excludeTools)请在下方 JSON 编辑框写", - "cfg.q_cafp": "压缩折叠是否原位置替换(compressAtFoldPoint,默认关)——把折叠产生的 compress 调用对放到它自己的折叠点处替换,而不是留在历史尾部", - "cfg.q_cafp_hint": "针对 qwen3-27b 这类注意力机制有问题的小模型很有用:避免模型把历史尾部的工具交换误读成新命令;取消勾选 = 回到旧版布局(字节级一致)。可选的“清未签名思考”开关(clearThinking)只能走 env / JSON", + "cfg.q_cafp": "压缩摘要前置到折叠点(compressAtFoldPoint,默认关)——把每次压缩产生的摘要文本以纯文本形式放到它描述的折叠点处,原 compress 调用对留在原时间位置、参数替换成指针,不再是可执行的完整压缩命令", + "cfg.q_cafp_hint": "针对 qwen3-27b 这类注意力机制有问题的小模型很有用:避免历史中部一整墙“完整形状”的 compress 交互被误读成继续压缩的示范/新命令;取消勾选 = 回到旧版布局(字节级一致)。可选的“清未签名思考”开关(clearThinking)只能走 env / JSON", "cfg.q_require_nudge": "禁止未提示压缩(compress.requireNudge)——只在 bili 实际注入压缩提醒的同一轮允许模型调用 compress,其余一律拒绝并回错误回执(默认关)", "cfg.q_require_nudge_hint": "针对会自行乱压的模型(如 qwen 27b)。bili 自己的溢出兜底折叠不受影响;也可只对特定 provider/model 开启(JSON 编辑框)", "cfg.q_require_rec": "禁止越界压缩(compress.requireRecommendation)——只允许压缩 bili 当前推荐的范围,越界即拒(默认关)", @@ -1324,8 +1324,8 @@ export const MESSAGES: Record> = { "cfg.q_dsh_ctxtab_label": "Label of the DSH Context tab (dsh.contextTabLabel) — empty keeps the built-in name \"Context\"; rename to avoid clashing with another plugin's tab", "cfg.q_absorb": "Instant tool-result absorption (absorb) — large tool results are distilled by the model on arrival; originals hidden until the next fold round (default off)", "cfg.q_absorb_hint": "by default only image-bearing results are absorbed (#3422); set mediaOnly: false to absorb full text. Sub-fields (minToolTokens, contextThresholdPct, excludeTools) go in the JSON editor below", - "cfg.q_cafp": "Fold replacement in place (compressAtFoldPoint, default off) — the fold's compress call/result pair replaces the region at its own fold point instead of staying tail-adjacent", - "cfg.q_cafp_hint": "very useful for small models with attention issues such as qwen3-27b: stops them misreading the trailing tool exchange as a fresh command; uncheck = byte-identical legacy layout. The optional clear-thinking companion (clearThinking) stays env/JSON-only", + "cfg.q_cafp": "Summary text relocated to the fold point (compressAtFoldPoint, default off) — each fold's summary text is re-emitted as plain text at the fold point it describes, while the compress call/result pair keeps its chronological slot with its args replaced by a pointer (no longer a fully-shaped compress command)", + "cfg.q_cafp_hint": "very useful for small models with attention issues such as qwen3-27b: stops a mid-history wall of fully-shaped compress interactions from reading as an invitation to keep compressing; uncheck = byte-identical legacy layout. The optional clear-thinking companion (clearThinking) stays env/JSON-only", "cfg.q_require_nudge": "Forbid unprompted compression (compress.requireNudge) — compress may only be called in a round where a nudge was actually injected; anything else is refused with an error receipt (default off)", "cfg.q_require_nudge_hint": "for models that fold on their own (e.g. qwen 27b). bili's own overflow backstop folds are unaffected; can also be scoped per provider/model in the JSON editor", "cfg.q_require_rec": "Forbid out-of-bounds compression (compress.requireRecommendation) — only ranges bili currently recommends may be folded; anything else is refused (default off)", From ad242bf6c2fce5efb198fcfa8234e9c0f0d77817 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Sun, 8 Nov 2026 19:45:17 +0800 Subject: [PATCH 2/4] kernel: relocated fold summaries ride the #335 live-carrier protection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up to 2dd1f997c: the v2 fold-point carrier (plain user text carrying the relocated summary) had NO checkpoint protection — a plain message-ref compress range could fold it as if it were ordinary user text, re-distilling a summary whose source history is already folded away (#335's exact hazard). The carrier now carries summaryOfBlockId = the anchor block of the pair (first block; multi-block pairs virtually always get consumed together by the block-ref distillation that spans them). While the anchor is active: - recommend.ts screens the carrier as a protected gap — no advertised range bridges it; - unit-projection carves it out of any hand-rolled plain range (it stays visible, with the existing warning pointing at block refs); - once the anchor block is consumed by a block-ref distillation — which sees and absorbs the carrier text into the new summary — the carrier goes stale and folds like ordinary text: the RESULT remains compressible, the SUMMARY cannot be silently re-distilled as plain text. v1 (pair moved verbatim) had the same gap; nothing marked the moved pair. kernel-change: carrier protection hook-up (#335 predicate); 0.0.188 → 0.0.189. --- kernel/package.json | 2 +- kernel/src/relocate-compress.ts | 18 +++++++++++++++++- kernel/tests/relocate-compress.test.ts | 10 +++++++++- 3 files changed, 27 insertions(+), 3 deletions(-) diff --git a/kernel/package.json b/kernel/package.json index 98de85b707..3bd139db92 100644 --- a/kernel/package.json +++ b/kernel/package.json @@ -1,6 +1,6 @@ { "name": "acp-kernel", - "version": "0.0.188", + "version": "0.0.189", "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/relocate-compress.ts b/kernel/src/relocate-compress.ts index bd0475fc5d..827eb88919 100644 --- a/kernel/src/relocate-compress.ts +++ b/kernel/src/relocate-compress.ts @@ -75,7 +75,9 @@ export interface RelocateMove { insertAtOutput: number; /** Input indices of dropped reasoning cores (adjacent run before the call). */ droppedReasoningIndices: number[]; - /** Synthetic fold-point carrier carrying the relocated summary text. */ + /** Synthetic fold-point carrier carrying the relocated summary text. + * `summaryOfBlockId` anchors the #335 live-checkpoint-carrier protection + * (plain compress ranges cannot fold it; block-ref distillation can). */ carrier: CoreMessage; /** Replacement args text for the call core (pointer JSON). */ pointerText: string; @@ -185,6 +187,20 @@ export function planRelocateCompressCarriers( id: carrierIdFor(callId), role: "user", contentType: "text", + // #335 checkpoint-carrier protection: while the block(s) this summary + // describes are still active, a PLAIN message-ref compress range can + // neither be advertised across this carrier (recommend.ts screens with + // isLiveCheckpointCarrier) nor fold it (unit-projection carves it out + // and keeps it visible) — a relocated summary must not be re-distilled + // as if it were ordinary user text, because the history it summarizes + // is already folded away. Once the anchor block is consumed by a + // block-ref distillation (which sees and absorbs the carrier text), + // this turns stale and the carrier folds like ordinary text — that is + // the intended "the RESULT may be compressed later" path. Multi-block + // pairs anchor the FIRST block: an active anchor keeps the protection, + // and distillations that consume the anchor virtually always span the + // sibling blocks created by the same call. + summaryOfBlockId: blockIds[0], text: `[bili fold summary — ${blockLabel}; relocated from compress call ${callId} ` + `(the call/result exchange stays in its chronological slot below)]\n${summary}`, diff --git a/kernel/tests/relocate-compress.test.ts b/kernel/tests/relocate-compress.test.ts index c95f9e4ae2..56011a79d9 100644 --- a/kernel/tests/relocate-compress.test.ts +++ b/kernel/tests/relocate-compress.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { createInitialState } from "../src/state.js"; +import { createInitialState, isLiveCheckpointCarrier } from "../src/state.js"; import { planRelocateCompressCarriers, relocateCompressCarriers, @@ -147,6 +147,10 @@ test("carrier text carries the summary; non-JSON args are used verbatim", () => assert.equal(carrier.contentType, "text"); assert.ok(carrier.text!.startsWith(`[bili fold summary — block(s) b1; relocated from compress call call1`)); assert.ok(carrier.text!.endsWith("\nRAW-SUMMARY-BODY")); + // #335 protection: the carrier is a live checkpoint carrier while b1 is + // active — plain compress ranges can neither span nor fold it. + assert.equal(carrier.summaryOfBlockId, "b1"); + assert.equal(isLiveCheckpointCarrier(carrier, state), true); }); test("carrier text extracts .content from JSON args (plugin dialect)", () => { @@ -292,6 +296,10 @@ test("multi-range batch shares one call id ⇒ boundary is max(endRef), pointer assert.deepEqual(ids(out), ["x", "call-callB", "res-callB", carrierId("callB"), "y"]); const callOut = out.find((m) => m.id === "call-callB")!; assert.ok(callOut.text!.includes("b1, b2")); + // Multi-block pair anchors the FIRST block for the #335 carrier protection. + const carrier = out.find((m) => m.id === carrierId("callB"))!; + assert.equal(carrier.summaryOfBlockId, "b1"); + assert.equal(isLiveCheckpointCarrier(carrier, state), true); }); test("fold reaches the window end (#4732 regime) ⇒ carrier appended at tail", () => { From cec34d14ad564055caa83634031b81241997be98 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Sun, 8 Nov 2026 19:54:05 +0800 Subject: [PATCH 3/4] chore: sync package-lock acp-kernel to 0.0.189 (lock-sync) --- package-lock.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package-lock.json b/package-lock.json index e39addc404..9de2a4449e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -50,7 +50,7 @@ }, "kernel": { "name": "acp-kernel", - "version": "0.0.187", + "version": "0.0.189", "dev": true, "license": "MIT", "devDependencies": { From e316d3fea1bf58bf978853106c4cb63aa72f982a Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Sun, 8 Nov 2026 19:55:09 +0800 Subject: [PATCH 4/4] chore: sync kernel/package-lock.json version fields to 0.0.189 (lock-sync) --- kernel/package-lock.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/kernel/package-lock.json b/kernel/package-lock.json index 5c7694c5bd..69fdf92ab7 100644 --- a/kernel/package-lock.json +++ b/kernel/package-lock.json @@ -1,12 +1,12 @@ { "name": "acp-kernel", - "version": "0.0.187", + "version": "0.0.189", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "acp-kernel", - "version": "0.0.187", + "version": "0.0.189", "license": "MIT", "devDependencies": { "@types/node": "^22.0.0",