From 43dc94c5413c23817f73524075678e31a0a57893 Mon Sep 17 00:00:00 2001 From: ci-check Date: Sun, 25 Oct 2026 04:54:13 +0800 Subject: [PATCH 1/6] kernel: add preserveRecentTurns and protectUserMessages (#4593) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit kernel-change: per-turn retention window + hard protection for user messages requested in #4593 — the host side cannot express either: turn boundaries are positional (slide per user message, incompatible with permanent BLOCKED-ref identity decisions) and user-message hard exclusion needs to ride the shared isMessageProtected predicate so every consumer (refs, projection, report, absorb/ccr guards) stays in sync automatically. - turn-retention.ts: computeTurnRetention — visible user-message boundaries (consecutive users = one, summary carriers excluded), strict window starting AT the (N+1)-th-from-last boundary - recommend.ts: Rule 4 unions the retention suffix into the soft zone (partial overlap = existing #3953 carve + warning, full containment = zone fatal) - protected.ts: protectUserMessages hard-excludes user text messages (BLOCKED refs); compress.ts gate extended so the predicate actually runs - unit-projection.ts: warnings/fatal attribute causes (last-N-turns retention vs classic recent zone vs protectUserMessages) - config.ts: validateConfig checks; types.ts optional fields (defaultConfig untouched -> golden wire-contract stays stable) - version 0.0.151 -> 0.0.152 --- kernel/package.json | 2 +- kernel/src/compress.ts | 6 +- kernel/src/config.ts | 13 + kernel/src/protected.ts | 26 +- kernel/src/recommend.ts | 22 +- kernel/src/turn-retention.ts | 54 ++++ kernel/src/types.ts | 22 ++ kernel/src/unit-projection.ts | 49 ++- kernel/tests/issue4593-turn-retention.test.ts | 300 ++++++++++++++++++ 9 files changed, 486 insertions(+), 8 deletions(-) create mode 100644 kernel/src/turn-retention.ts create mode 100644 kernel/tests/issue4593-turn-retention.test.ts diff --git a/kernel/package.json b/kernel/package.json index e597d918ff..6af3a88f5a 100644 --- a/kernel/package.json +++ b/kernel/package.json @@ -1,6 +1,6 @@ { "name": "acp-kernel", - "version": "0.0.163", + "version": "0.0.164", "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 5a4fa2944c..ff998c6af6 100644 --- a/kernel/src/compress.ts +++ b/kernel/src/compress.ts @@ -997,7 +997,11 @@ const assignRefsNode: PipelineNode = { ctx.config.protectedTools.length > 0 || !!ctx.config.isToolProtected || !!ctx.config.isMessageProtected || - (ctx.config.protectedLatestTools?.length ?? 0) > 0; + (ctx.config.protectedLatestTools?.length ?? 0) > 0 || + // #4593: protectUserMessages alone must also run protectedFn — without + // this gate addition its isMessageProtected branch never executes and + // user messages get plain foldable refs. + ctx.config.protectUserMessages === true; const latest = hasProtection ? collectLatestProtected(io.messages, ctx.config) : undefined; diff --git a/kernel/src/config.ts b/kernel/src/config.ts index fb3409c30c..565991d53a 100644 --- a/kernel/src/config.ts +++ b/kernel/src/config.ts @@ -135,6 +135,19 @@ export function validateConfig(config: Config): string[] { ) { errors.push("preserveRecentTools must be a string array"); } + if ( + config.preserveRecentTurns !== undefined && + (!Number.isFinite(config.preserveRecentTurns) || + config.preserveRecentTurns < 0) + ) { + errors.push("preserveRecentTurns must be a finite number >= 0"); + } + if ( + config.protectUserMessages !== undefined && + typeof config.protectUserMessages !== "boolean" + ) { + errors.push("protectUserMessages must be a boolean"); + } if (config.absorb) { if (config.absorb.enabled && !config.absorb.toolName) { errors.push("absorb.toolName must be a non-empty string when enabled"); diff --git a/kernel/src/protected.ts b/kernel/src/protected.ts index f79f77a16e..1445b028b3 100644 --- a/kernel/src/protected.ts +++ b/kernel/src/protected.ts @@ -1,4 +1,5 @@ import type { Config, CoreMessage } from "./types.js"; +import { SUMMARY_HEADER } from "./prune.js"; /** Tools that are ALWAYS protected, regardless of user config. These are ACP's * own metadata tools whose records must remain in context: compress calls @@ -308,15 +309,38 @@ export function virtualToolPathOf( return config.messagePathOf?.(msg); } +/** True for a genuine user text message — role "user", plain text content, + * not a pasted summary carrier. #4593 protectUserMessages hard-protection + * rides on this: user instructions are the only non-regenerable input in a + * session (tool results can be re-run, summaries rewritten), so once one + * leaves the wire it can no longer be checked verbatim. Summary carriers + * are excluded so tier-merge of blocks that contain user messages stays + * possible; host-injected runtime-context user messages ARE protected on + * purpose (conservative default: over-protecting costs compression ratio, + * under-protecting loses an instruction). */ +export function isUserTextMessage(msg: CoreMessage): boolean { + if (msg.role !== "user") return false; + if (msg.contentType !== "text") return false; + if (msg.text?.startsWith(SUMMARY_HEADER)) return false; + return true; +} + export function isMessageProtected( msg: CoreMessage, - config: Pick, + config: Pick, failedToolCallIds?: ReadonlySet, ): boolean { // Host-declared message-level protection (#2419): applies to ANY content // type and outranks everything below — the host owns the decision. if (config.isMessageProtected?.(msg)) return true; + // #4593: user-text hard protection (protectUserMessages). Checked before + // the tool-path branches because its domain (role "user" text) never + // overlaps them. + if (config.protectUserMessages === true && isUserTextMessage(msg)) { + return true; + } + // #4289: a compress exchange that applied ZERO ranges is refuse, not // metadata — no block carries its arguments and decompress never consults // it. Exempt both halves from EVERY built-in source below (ALWAYS table, diff --git a/kernel/src/recommend.ts b/kernel/src/recommend.ts index 97095b97c3..a91b247b9a 100644 --- a/kernel/src/recommend.ts +++ b/kernel/src/recommend.ts @@ -32,6 +32,7 @@ import { isMessageProtectedWithPairing, isNeverPreserveRecent, } from "./protected.js"; +import { computeTurnRetention } from "./turn-retention.js"; import { countMessageTokens } from "./tokenize.js"; import { computeIntegrityWithdrawals } from "./turn-integrity.js"; import { evaluateRefold } from "./refold.js"; @@ -65,10 +66,14 @@ function isSyntheticOrPruned( * Compute the set of protected message refs (mNNNNN) that form the * "soft-protected zone" at the tail of the conversation. * - * Combines three rules: + * Combines four rules: * 1. Last N messages (`config.preserveRecentMessages`) * 2. Last N tokens expanding backward (`config.preserveRecentTokens`) * 3. Last visible user message (couples to Rule 1) + * 4. Per-turn retention (#4593): the last N user-initiated turns form a + * positional protected suffix (`config.preserveRecentTurns`; recomputed + * every turn — see turn-retention.ts). Ranges overlapping it are + * rejected by projectUnit, not truncated like Rules 1-3. * * Then closes the tool-pair gap (#2886): if either half of a (tool-call, * tool-result) pair is protected, both are. Without this, `neverPreserveRecentTools` @@ -152,6 +157,21 @@ export function computeProtectedRefs( } } + // Rule 4 (#4593): per-turn retention — the last N user-initiated turns form + // a positional protected suffix. Recomputed every turn (the window slides + // with each new user message), which is why it lives here rather than in + // the permanent BLOCKED-ref decision. Fewer than N+1 visible user messages + // ⇒ the whole conversation is retained (boundaryIndex 0). + { + const retention = computeTurnRetention(messages, state, config); + if (retention) { + for (let i = retention.boundaryIndex; i < messages.length; i++) { + const ref = state.messageRefs.byRaw[messages[i]!.id]; + if (ref && ref !== "BLOCKED") result.add(ref); + } + } + } + // #2886: close the tool-pair gap. neverPreserveRecentTools drops big-result // tools (read/bash/...) from `visible`, so a matching tool-result can never // enter the recent zone while its paired tool-call (unmatched name) can. diff --git a/kernel/src/turn-retention.ts b/kernel/src/turn-retention.ts new file mode 100644 index 0000000000..c9b6f1199d --- /dev/null +++ b/kernel/src/turn-retention.ts @@ -0,0 +1,54 @@ +import type { Config, CompressionState, CoreMessage } from "./types.js"; +import { coveredMessageIds } from "./state.js"; +import { SUMMARY_HEADER } from "./prune.js"; + +/** + * #4593: per-turn retention ("the last N turns stay verbatim"). + * + * A turn boundary is a VISIBLE user message: role "user", not a summary + * carrier, not already covered by an active block. Consecutive user messages + * (raw adjacency) count as ONE boundary — hosts batch runtime-context + * snapshots next to the instruction. The retention window is the suffix of + * the messages array starting AT the (N+1)-th-from-last boundary: + * the last N turns AND everything between them (tool calls/results, assistant + * replies) stay protected together — the window always STARTS on a user + * message (a clean turn boundary), never mid-turn. Fewer than N+1 boundaries + * ⇒ the whole conversation is inside the window (boundaryIndex 0). + * + * POSITIONAL by design: the window slides forward with every new user + * message, so it cannot ride the permanent BLOCKED-ref identity decision + * (an aged-out message would stay blocked forever, or force per-turn + * BLOCKED→numeric migration = prefix-cache churn). It recomputes every turn: + * computeProtectedRefs unions the refs into the soft-protection set, and + * projectUnit rejects submitted ranges that overlap it. + */ + +export interface TurnRetention { + /** Smallest messages-array index inside the retained suffix; everything at + * or after it is protected. 0 = the entire conversation is retained. */ + boundaryIndex: number; + /** The configured N (for error wording). */ + turns: number; +} + +export function computeTurnRetention( + messages: CoreMessage[], + state: CompressionState, + config: Pick, +): TurnRetention | null { + const turns = config.preserveRecentTurns; + if (turns === undefined || !Number.isFinite(turns) || turns < 1) return null; + const covered = coveredMessageIds(state); + const boundaries: number[] = []; + for (let i = 0; i < messages.length; i++) { + const m = messages[i]!; + if (m.role !== "user") continue; + if (m.text?.startsWith(SUMMARY_HEADER)) continue; + if (covered.has(m.id)) continue; + const prev = messages[i - 1]; + if (prev !== undefined && prev.role === "user") continue; + boundaries.push(i); + } + if (boundaries.length < turns + 1) return { boundaryIndex: 0, turns }; + return { boundaryIndex: boundaries[boundaries.length - turns]!, turns }; +} diff --git a/kernel/src/types.ts b/kernel/src/types.ts index 3ac5c6a348..ccb2d7f3bc 100644 --- a/kernel/src/types.ts +++ b/kernel/src/types.ts @@ -511,6 +511,28 @@ export interface Config { * `(neverPreserveRecentTools ?? built-in) minus preserveRecentTools`; * unset or empty = no subtraction (pure no-op). */ preserveRecentTools?: string[]; + /** #4593: per-turn retention — the last N user-initiated turns stay + * verbatim on the wire. A turn boundary is a visible user message (not a + * summary carrier, not already covered by an active block); consecutive + * user messages count as ONE boundary. Everything at or after the index + * right past the (N+1)-th-from-last boundary is protected; when fewer than + * N+1 boundaries exist the ENTIRE conversation is retained. Recomputed + * every turn (the window slides with each new user message), so it rides + * the soft-protection set rather than the permanent BLOCKED-ref decision + * — and a submitted range that overlaps it is REJECTED (it is explicit + * user intent, stronger than the advisory recent-zone truncation of + * #3953). `0`/unset = off. */ + preserveRecentTurns?: number; + /** #4593: hard-exclude every ordinary user text message from compression + * (BLOCKED ref, same semantics as protectedTools): user instructions are + * the only non-regenerable input — once folded they survive only as a + * model-written paraphrase in the summary, which the model later quotes + * as if it were the original. Summary carriers (SUMMARY_HEADER prefix) + * are exempt so tier distillation keeps working; tool results are never + * user-role in core space (they project to role "tool"), so nothing but + * genuine user text — including host-injected runtime-context snapshots, + * which are deliberately protected too — is affected. Unset/false = off. */ + protectUserMessages?: boolean; preserveRecentMessages: number; preserveRecentTokens: number; modelContextLimit: number; diff --git a/kernel/src/unit-projection.ts b/kernel/src/unit-projection.ts index 8b228d8220..7141ec9406 100644 --- a/kernel/src/unit-projection.ts +++ b/kernel/src/unit-projection.ts @@ -2,13 +2,15 @@ import { activeBlocks, blockById, isLiveCheckpointCarrier } from "./state.js"; import { resolveBoundaries, blockVisibleInRange } from "./boundaries.js"; import { isSummaryMessageId } from "./prune.js"; import { + collectAgedCompressCallIds, collectFailedCompressCallIds, collectLatestProtected, hasUnrecoverableMediaPayload, isMessageLatestProtected, isMessageProtected, - collectAgedCompressCallIds, + isUserTextMessage, } from "./protected.js"; +import { computeTurnRetention } from "./turn-retention.js"; import { computeIntegrityWithdrawals } from "./turn-integrity.js"; import { adjustBoundariesForReasoningPairs } from "./reasoning-pairs.js"; import { adjustBoundariesForToolPairs } from "./tool-pairs.js"; @@ -207,6 +209,27 @@ export function projectUnit(input: UnitProjectionInput): UnitProjection { } } + // #4593: the drop above is silent by design for protectedTools (longstanding + // behavior), but protectUserMessages removals MUST be auditable — user + // instructions are the non-regenerable input, so the receipt names exactly + // which refs were skipped and why. + if (input.config.protectUserMessages === true && filteredIds.length < directMessageIds.length) { + const kept = new Set(filteredIds); + const droppedUserRefs = directMessageIds + .filter((id) => !kept.has(id)) + .map((id) => input.messages.find((m) => m.id === id)) + .filter((m): m is CoreMessage => !!m && isUserTextMessage(m)) + .map((m) => input.state.messageRefs.byRaw[m.id]) + .filter((r): r is string => typeof r === "string"); + if (droppedUserRefs.length > 0) { + warnings.push( + `Excluded ${droppedUserRefs.length} user message(s) ${droppedUserRefs.join( + ", ", + )} from compression range (protectUserMessages) — they stay visible outside the new block; do not target them in another compress call.`, + ); + } + } + const mediaExcluded = directMessageIds.filter((id) => { const msg = input.messages.find((m) => m.id === id); return !!msg && hasUnrecoverableMediaPayload(msg); @@ -290,13 +313,31 @@ export function projectUnit(input: UnitProjectionInput): UnitProjection { .map((id) => input.state.messageRefs.byRaw[id]) .filter((v): v is string => typeof v === "string"); + // #4593: name every active retention regime so the receipt attributes + // skips to their cause. Turn-retention refs form a contiguous tail (the + // newest), so a count suffices to tell the two families apart. + const zoneParts = [ + `the last ${input.config.preserveRecentMessages} messages and/or the most recent user message`, + ]; + const retention = computeTurnRetention(input.messages, input.state, input.config); + let turnRetainedCount = 0; + if (retention) { + zoneParts.push(`the last ${input.config.preserveRecentTurns} turns`); + const retained = new Set(); + for (let i = retention.boundaryIndex; i < input.messages.length; i++) { + retained.add(input.messages[i]!.id); + } + turnRetainedCount = hitProtectedRaw.filter((id) => retained.has(id)).length; + } + const zoneDesc = + zoneParts.length > 1 ? `${zoneParts[0]} plus ${zoneParts[1]}` : zoneParts[0]; + 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( + `Range is entirely within the protected zone (${zoneDesc}): ${hitRefs.join( ", ", )}. Adjust startId/endId to older messages.`, ), @@ -306,7 +347,7 @@ export function projectUnit(input: UnitProjectionInput): UnitProjection { 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.` + + )} from compression range (${zoneDesc}${turnRetainedCount > 0 ? `, of which ${turnRetainedCount} in last-turns retention` : ""}) — they stay visible outside the new block; do not target them in another compress call.` + (truncatedAfter > 0 ? ` Range truncated at that boundary — ${truncatedAfter} later message(s) (including replies to the protected message) stay visible too, so no summary can land above the question it answers (#3953).` : ""), diff --git a/kernel/tests/issue4593-turn-retention.test.ts b/kernel/tests/issue4593-turn-retention.test.ts new file mode 100644 index 0000000000..edede94071 --- /dev/null +++ b/kernel/tests/issue4593-turn-retention.test.ts @@ -0,0 +1,300 @@ +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 { isMessageProtected } from "../src/protected.js"; +import { computeTurnRetention } from "../src/turn-retention.js"; +import { SUMMARY_HEADER } from "../src/prune.js"; +import type { Config, CoreMessage } from "../src/types.js"; + +function msg( + id: string, + text: string, + role: CoreMessage["role"] = "user", +): CoreMessage { + return { id, role, contentType: "text", text }; +} + +function config(overrides: Partial = {}): Config { + return { + tiers: { enabled: true, tier2Trigger: 5, tier3Trigger: 10 }, + 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 }, + compress: { minCompressRange: 0, maxSummaryLength: 0, minSummaryLength: 0 }, + protectedTools: [], + preserveRecentMessages: 0, + preserveRecentTokens: 0, + modelContextLimit: 100000, + ...overrides, + }; +} + +function seededState(messages: CoreMessage[]) { + const state = createInitialState(); + state.messageRefs = assignRefs(messages, { + existing: state.messageRefs, + nextIndex: 1, + }).map; + return state; +} + +// Five text turns: tNu/tNa pairs → refs m00001..m00010 (t1u..t5a). +const FIVE_TURNS: CoreMessage[] = [ + msg("t1u", "user instruction one"), + msg("t1a", "assistant reply one", "assistant"), + msg("t2u", "user instruction two"), + msg("t2a", "assistant reply two", "assistant"), + msg("t3u", "user instruction three"), + msg("t3a", "assistant reply three", "assistant"), + msg("t4u", "user instruction four"), + msg("t4a", "assistant reply four", "assistant"), + msg("t5u", "user instruction five"), + msg("t5a", "assistant reply five", "assistant"), +]; + +test("computeTurnRetention: off when unset / 0 / negative (#4593)", () => { + const state = createInitialState(); + assert.equal(computeTurnRetention(FIVE_TURNS, state, {}), null); + assert.equal(computeTurnRetention(FIVE_TURNS, state, { preserveRecentTurns: 0 }), null); + assert.equal(computeTurnRetention(FIVE_TURNS, state, { preserveRecentTurns: -1 }), null); +}); + +test("computeTurnRetention: the window starts AT the (N+1)-th-from-last user message (#4593)", () => { + const state = createInitialState(); + // Boundaries at idx 0,2,4,6,8. + assert.deepEqual(computeTurnRetention(FIVE_TURNS, state, { preserveRecentTurns: 1 }), { + boundaryIndex: 8, + turns: 1, + }); + assert.deepEqual(computeTurnRetention(FIVE_TURNS, state, { preserveRecentTurns: 2 }), { + boundaryIndex: 6, + turns: 2, + }); + assert.deepEqual(computeTurnRetention(FIVE_TURNS, state, { preserveRecentTurns: 4 }), { + boundaryIndex: 2, + turns: 4, + }); +}); + +test("computeTurnRetention: fewer than N+1 turns protects everything (#4593)", () => { + const state = createInitialState(); + assert.deepEqual(computeTurnRetention(FIVE_TURNS, state, { preserveRecentTurns: 6 }), { + boundaryIndex: 0, + turns: 6, + }); + assert.deepEqual(computeTurnRetention(FIVE_TURNS.slice(0, 4), state, { preserveRecentTurns: 5 }), { + boundaryIndex: 0, + turns: 5, + }); +}); + +test("computeTurnRetention: consecutive user messages count as ONE boundary (#4593)", () => { + const state = createInitialState(); + const batched = [ + msg("a", "runtime context snapshot"), + msg("b", "the instruction"), + msg("c", "reply", "assistant"), + ]; + // One boundary (idx 0); N=1 needs two → whole conversation retained. + assert.deepEqual(computeTurnRetention(batched, state, { preserveRecentTurns: 1 }), { + boundaryIndex: 0, + turns: 1, + }); + const batchedPlus = [...batched, msg("d", "next instruction"), msg("e", "reply two", "assistant")]; + // Boundaries [0, 3]; N=1 → window starts at idx 3. + assert.deepEqual(computeTurnRetention(batchedPlus, state, { preserveRecentTurns: 1 }), { + boundaryIndex: 3, + turns: 1, + }); +}); + +test("computeTurnRetention: summary carriers are not turn boundaries (#4593)", () => { + const state = createInitialState(); + const msgs = [ + msg("s", `${SUMMARY_HEADER}\nold folded content`), + msg("a", "real instruction"), + msg("b", "reply", "assistant"), + ]; + // Single real boundary (idx 1); N=1 → fewer than 2 → all retained. + assert.deepEqual(computeTurnRetention(msgs, state, { preserveRecentTurns: 1 }), { + boundaryIndex: 0, + turns: 1, + }); +}); + +test("#4593: folding older turns succeeds while the last N turns stay verbatim", () => { + const core = createCore(); + const messages = [...FIVE_TURNS]; + const state = seededState(messages); + const cfg = config({ preserveRecentTurns: 2 }); + + const result = core.applyCompression({ + ranges: [{ startRef: "m00001", endRef: "m00004", summary: "turns one and two", topic: "old" }], + messages, + state, + config: cfg, + }); + + assert.equal(result.result.errors.length, 0, JSON.stringify(result.result.errors)); + assert.equal(result.result.blocksCreated, 1); + const block = result.state.blocks[result.state.blocks.length - 1]!; + assert.deepEqual([...block.directMessageIds].sort(), ["t1a", "t1u", "t2a", "t2u"]); + for (const id of ["t3u", "t3a", "t4u", "t4a", "t5u", "t5a"]) { + assert.ok(!block.directMessageIds.includes(id), `${id} must stay verbatim`); + } +}); + +test("#4593: a range crossing the turn boundary truncates there with an auditable warning", () => { + const core = createCore(); + const messages = [...FIVE_TURNS]; + const state = seededState(messages); + const cfg = config({ preserveRecentTurns: 2 }); + + // m00003..m00008 = t2u..t4a; the retained suffix starts at t4u (m00007). + const result = core.applyCompression({ + ranges: [{ startRef: "m00003", endRef: "m00008", summary: "crossing the boundary", topic: "cross" }], + messages, + state, + config: cfg, + }); + + assert.equal(result.result.errors.length, 0, JSON.stringify(result.result.errors)); + assert.equal(result.result.blocksCreated, 1); + const block = result.state.blocks[result.state.blocks.length - 1]!; + assert.deepEqual([...block.directMessageIds].sort(), ["t2a", "t2u", "t3a", "t3u"]); + const warning = result.result.warnings.join("\n"); + assert.match(warning, /last 2 turns/); + assert.match(warning, /last-turns retention/); +}); + +test("#4593: a range entirely inside the retained turns is rejected naming the turn zone", () => { + const core = createCore(); + const messages = [...FIVE_TURNS]; + const state = seededState(messages); + const cfg = config({ preserveRecentTurns: 2 }); + + const result = core.applyCompression({ + ranges: [{ startRef: "m00007", endRef: "m00010", summary: "inside the zone", topic: "bad" }], + messages, + state, + config: cfg, + }); + + assert.equal(result.result.blocksCreated, 0); + assert.equal(result.result.errors.length, 1); + assert.match(result.result.errors[0]!, /entirely.*protected.*zone/i); + assert.match(result.result.errors[0]!, /last 2 turns/); +}); + +test("#4593: protectUserMessages hard-excludes user messages (BLOCKED refs + auditable carve)", () => { + const core = createCore(); + const messages = [...FIVE_TURNS]; + const cfg = config({ protectUserMessages: true }); + + // Ref assignment itself must render user messages BLOCKED. + const assigned = assignRefs(messages, { + existing: createInitialState().messageRefs, + nextIndex: 1, + isProtected: (m) => isMessageProtected(m, cfg), + }); + assert.equal(assigned.map.byRaw["t1u"], "BLOCKED"); + assert.equal(assigned.map.byRaw["t3u"], "BLOCKED"); + // BLOCKED refs consume no numbers: assistants take m00001..m00005. + assert.equal(assigned.map.byRaw["t1a"], "m00001"); + assert.equal(assigned.map.byRaw["t5a"], "m00005"); + + const state = seededState(messages); + const result = core.applyCompression({ + ranges: [{ startRef: "m00001", endRef: "m00006", summary: "folding around the instructions", topic: "mixed" }], + messages, + state, + config: cfg, + }); + + assert.equal(result.result.errors.length, 0, JSON.stringify(result.result.errors)); + assert.equal(result.result.blocksCreated, 1); + const block = result.state.blocks[result.state.blocks.length - 1]!; + assert.deepEqual([...block.directMessageIds].sort(), ["t1a", "t2a", "t3a"]); + const warning = result.result.warnings.join("\n"); + assert.match(warning, /protectUserMessages/); + assert.match(warning, /user message/); +}); + +test("#4593: a range containing only protected user messages is rejected", () => { + const core = createCore(); + const messages = [ + msg("u1", "instruction one"), + msg("u2", "instruction two"), + msg("a1", "reply", "assistant"), + ]; + const state = seededState(messages); + const cfg = config({ protectUserMessages: true }); + + const result = core.applyCompression({ + ranges: [{ startRef: "m00001", endRef: "m00002", summary: "users only", topic: "none" }], + messages, + state, + config: cfg, + }); + + assert.equal(result.result.blocksCreated, 0); + assert.equal(result.result.errors.length, 1); + assert.match(result.result.errors[0]!, /no compressible messages/); +}); + +test("#4593: preserveRecentTurns unions with preserveRecentMessages (one soft set)", () => { + const core = createCore(); + const messages = [...FIVE_TURNS]; + const state = seededState(messages); + // Last 2 messages (t5u/t5a) + last 4 turns (from t2u) → union starts at t2u. + const cfg = config({ preserveRecentMessages: 2, preserveRecentTurns: 4 }); + + const result = core.applyCompression({ + ranges: [{ startRef: "m00001", endRef: "m00003", summary: "up to the union edge", topic: "union" }], + messages, + state, + config: cfg, + }); + + assert.equal(result.result.errors.length, 0, JSON.stringify(result.result.errors)); + assert.equal(result.result.blocksCreated, 1); + const block = result.state.blocks[result.state.blocks.length - 1]!; + assert.deepEqual([...block.directMessageIds].sort(), ["t1a", "t1u"]); + const warning = result.result.warnings.join("\n"); + assert.match(warning, /last 4 turns/); +}); + +test("#4593: defaults are off — legacy behavior unchanged without the flags", () => { + const core = createCore(); + const messages = [...FIVE_TURNS]; + const state = seededState(messages); + const cfg = config(); + + const result = core.applyCompression({ + ranges: [{ startRef: "m00001", endRef: "m00004", summary: "legacy fold", topic: "legacy" }], + messages, + state, + config: cfg, + }); + + assert.equal(result.result.errors.length, 0, JSON.stringify(result.result.errors)); + assert.equal(result.result.blocksCreated, 1); + const block = result.state.blocks[result.state.blocks.length - 1]!; + assert.ok(block.directMessageIds.includes("t1u"), "old user messages fold normally by default"); + const flagged = result.result.warnings.filter((w) => /turns?|user message/i.test(w)); + assert.equal(flagged.length, 0, JSON.stringify(flagged)); +}); From 4277b74d0ab04da08cdbd04f9539e44986c07b56 Mon Sep 17 00:00:00 2001 From: ci-check Date: Sun, 25 Oct 2026 04:54:38 +0800 Subject: [PATCH 2/6] feat: expose compress.preserveRecentTurns / protectUserMessages (#4593) Config surface (owner-gated mapping, per-tier like siblings): - compress.preserveRecentTurns?: number (0/unset = off): last N turns (turn = user message -> next user message) join the soft-protected zone; submitted ranges crossing the boundary are carved with an auditable warning, fully-contained ranges are rejected - compress.protectUserMessages?: boolean (unset = false): every user text message hard-excluded (BLOCKED refs, never advertised), same semantics as protectedTools - parseCompressSettings: finite >= 0 number (explicit 0 = off) and strict boolean validation; COMPRESS_SETTING_FIELDS updated - mergeCompress/applyCompressSettings: per-field global -> provider -> model cascade with ?? (an explicit off at any tier wins) - preflight overflow relaxation deliberately does NOT touch preserveRecentTurns: folding user instructions defeats the feature, so unresolvable overflow fails loudly instead - CONFIGURATION.md en+zh: table rows + deterministic behavior spec (reject / filter+receipt / priority order) --- CONFIGURATION.md | 22 ++++++++++++++++++ CONFIGURATION.zh-CN.md | 22 ++++++++++++++++++ src/compress-settings.ts | 6 +++++ src/config.ts | 27 +++++++++++++++++++++- src/preflight.ts | 5 ++++ tests/compress-settings.test.ts | 41 +++++++++++++++++++++++++++++++++ 6 files changed, 122 insertions(+), 1 deletion(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 471913adc4..1b5376a3ed 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -266,6 +266,8 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `compress.streamSummary` | boolean | false (unset) | — | Force preflight summarization to run as a streaming (SSE) call from the first attempt. The error-driven self-learn handles stream-mandating upstreams on its own (any 400 on a non-streaming summary triggers a one-shot SSE probe, #2494) but NEVER arms on gateway timeouts (e.g. Cloudflare HTTP 524): set this where such a gateway sits between bili and the origin, or simply to skip the one probe round-trip. | | `compress.preserveRecentMessages` | number | 3 | — | The most recent messages stay soft-protected from folds. | | `compress.preserveRecentTokens` | number | kernel ≈5000 | — | The most recent tokens stay soft-protected from folds. | +| `compress.preserveRecentTurns` | number | off | acp-kernel ≥ 0.0.152 | All messages of the last N turns (turn = user message → next user message) join the soft-protected zone (#4593). | +| `compress.protectUserMessages` | boolean | off | acp-kernel ≥ 0.0.152 | Every user text message is hard-protected, never compressible (#4593). | | `compress.minCompressRangeChars` | number (deprecated alias: minCompressRange) | kernel ≈5000 | — | Smallest foldable range, in characters; shorter ranges never fold. | | `compress.maxSummaryLength` | number | kernel 20000 | — | Hard character cap on ONE generated summary; longer replies are rejected whole (no truncation, no retry). External summarizers are told this exact cap up front (#3635). 0 = unbounded. | | `compress.minSummaryLength` | number | kernel 50 | — | Character floor for generated summaries; shorter replies are rejected whole. 0 = disabled. External summarizers are held to the same floor (#3635). | @@ -1372,6 +1374,26 @@ For each request, the proxy resolves the settings by longest-URL-prefix match (t - **Status:** ACTIVE - **Description:** Token budget reserved for recent-message protection. Maps to the kernel field `preserveRecentTokens`. +#### `preserveRecentTurns` + +- **Type:** `number` +- **Default:** off (`0` or unset) +- **Status:** ACTIVE (#4593, requires `acp-kernel` ≥ 0.0.152) +- **Description:** Per-turn retention. A "turn" is one user message plus everything up to the next user message. All messages of the last N turns join the soft-protected zone alongside `preserveRecentMessages`/`preserveRecentTokens`/the latest-user pin — one union set, no internal priority. Message counts don't bound a turn (a single turn spans dozens of tool calls/results), which is why count-based retention alone either cuts mid-turn or over-retains. Deterministic behavior for a submitted compress range: + - **Range entirely inside the protected zone** → rejected with `Range is entirely within the protected zone (…)`. + - **Range partially overlapping** → the protected part is filtered out (truncated at the first interior protected message so no summary lands above the question it answers, #3953); the rest compresses normally, and the receipt carries an auditable warning listing exactly which refs were skipped and their cause (`…of which N in last-turns retention`). If the remainder falls below `minCompressRange`, the existing too-small rejection applies. + - Recommended ranges (`acp_status`) never cross the boundary — only hand-picked ranges hit the carve. + - Overflow relaxation (#330) zeroes `preserveRecentMessages`/`preserveRecentTokens` but deliberately NOT this knob: folding user instructions under pressure defeats the feature, so an unresolvable overflow fails loudly instead. +- **Example:** `{ "compress": { "preserveRecentTurns": 3 } }` + +#### `protectUserMessages` + +- **Type:** `boolean` +- **Default:** off (unset = `false`) +- **Status:** ACTIVE (#4593, requires `acp-kernel` ≥ 0.0.152) +- **Description:** Hard-protect every user text message — the only non-regenerable input in a session: tool results can be re-run, summaries rewritten, but once a user instruction is folded into a model-written summary it can no longer be checked verbatim. Protection is a HARD exclusion like `protectedTools`: matching refs render as `BLOCKED`, are never advertised as compressible, and a submitted range containing them has them carved out with an auditable receipt warning (`Excluded N user message(s) … (protectUserMessages)`); a range consisting solely of such messages is rejected. Conservative by design: host-injected runtime-context user messages are covered too (over-protection costs compression ratio; under-protection loses instructions). Kernel summary carriers (role `system`) and tool results (role `tool`) do NOT match. Deepest level wins across global → provider → model like the other compress fields. +- **Example:** `{ "compress": { "protectUserMessages": true } }` + #### `minCompressRangeChars` - **Type:** `number` diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 77c116c811..a6ce2d5769 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -266,6 +266,8 @@ | `compress.streamSummary` | boolean | false (unset) | — | 强制 preflight 摘要从首次尝试起就走流式(SSE)请求。要求流式的上游现在由错误驱动自学习自动处理(非流式摘要的任何 400 都会触发一次性 SSE 探测,#2494),但网关超时(如 Cloudflare HTTP 524)永远无法触发自学习:在此类网关位于 bili 与源站之间时设置此项,或用于省去一次探测往返。 | | `compress.preserveRecentMessages` | number | 3 | — | 最近的消息软保护、免于折叠。 | | `compress.preserveRecentTokens` | number | kernel ≈5000 | — | 最近的 token 软保护、免于折叠。 | +| `compress.preserveRecentTurns` | number | 关闭 | acp-kernel ≥ 0.0.152 | 最近 N 轮(轮 = 一条 user 消息到下一条 user 消息)的全部消息加入软保护区(#4593)。 | +| `compress.protectUserMessages` | boolean | 关闭 | acp-kernel ≥ 0.0.152 | 所有 user 文本消息硬保护、永不压缩(#4593)。 | | `compress.minCompressRangeChars` | number (deprecated alias: minCompressRange) | kernel ≈5000 | — | 可折叠片段的最小字符数;更短的永不折叠。 | | `compress.maxSummaryLength` | number | kernel 20000 | — | 单条生成摘要的硬字符上限;超长的回复被整段拒绝(不截断、不重试)。外部摘要模型会被提前告知这个确切上限(#3635)。0 = 不限制。 | | `compress.minSummaryLength` | number | kernel 50 | — | 生成摘要的字符下限;过短的回复被整段拒绝。0 = 禁用。外部摘要模型受同一下限约束(#3635)。 | @@ -1375,6 +1377,26 @@ ACP 原生 agent(当前为 `pi` 扩展)会在每个进程内向代理上报 - **状态:** ACTIVE - **说明:** 为最近消息保护预留的 token 预算。映射到内核字段 `preserveRecentTokens`。 +#### `preserveRecentTurns` + +- **类型:** `number` +- **默认值:** 关闭(`0` 或未设置) +- **状态:** ACTIVE(#4593,需要 `acp-kernel` ≥ 0.0.152) +- **说明:** 按轮保留。一轮 = 一条 user 消息 + 到下一条 user 消息为止的全部内容。最近 N 轮的全部消息与 `preserveRecentMessages`/`preserveRecentTokens`/最新 user 钉住一起并入软保护区——同一个并集,无内部优先级。一条轮往往横跨几十条工具调用/结果,按条数保留要么截在轮中间、要么过度保留,这正是本键存在的理由。提交压缩区间时的确定行为: + - **区间完全落在保护区内** → 拒绝,报错 `Range is entirely within the protected zone (…)`. + - **区间部分重叠** → 受保护部分被过滤掉(在第一条内部受保护消息处截断,保证摘要不会落在它所回答的问题之上,#3953),其余部分正常压缩;回执里带一条可审计警告,逐条列出被跳过的 ref 及原因(`…of which N in last-turns retention`)。若剩余不足 `minCompressRange`,走既有的 too-small 拒绝。 + - 推荐区间(`acp_status`)永不跨边界——只有手工挑选的区间才会触发过滤。 + - 溢出松弛(#330)会把 `preserveRecentMessages`/`preserveRecentTokens` 清零,但**有意不**清本键:压力下折叠用户指令等于让本功能失效,因此无法解决的溢出会响亮地失败而不是悄悄折掉指令。 +- **示例:** `{ "compress": { "preserveRecentTurns": 3 } }` + +#### `protectUserMessages` + +- **类型:** `boolean` +- **默认值:** 关闭(未设置 = `false`) +- **状态:** ACTIVE(#4593,需要 `acp-kernel` ≥ 0.0.152) +- **说明:** 硬保护所有 user 文本消息——会话中唯一不可再生的输入:工具结果可以重跑、摘要可以重写,但用户指令一旦被折进模型自写的摘要,就无法再逐字核对。保护是 HARD 排除,语义同 `protectedTools`:匹配的 ref 显示为 `BLOCKED`、永不出现在可压缩推荐里;提交的区间包含它们时会被过滤并留下可审计的回执警告(`Excluded N user message(s) … (protectUserMessages)`);整段全是这类消息的区间会被拒绝。刻意保守:宿主注入的 runtime-context user 消息也在保护范围内(误保护只损失压缩比,误折叠会丢指令)。内核摘要载体(role `system`)与工具结果(role `tool`)不匹配。与其他 compress 字段一样,global → provider → model 最深层生效。 +- **示例:** `{ "compress": { "protectUserMessages": true } }` + #### `minCompressRangeChars` - **类型:** `number` diff --git a/src/compress-settings.ts b/src/compress-settings.ts index 34e53ca3ed..1eb0c2adef 100644 --- a/src/compress-settings.ts +++ b/src/compress-settings.ts @@ -77,6 +77,8 @@ export function mergeCompress( nudgeDecisionMaxTokens: pick("nudgeDecisionMaxTokens"), preserveRecentMessages: pick("preserveRecentMessages"), preserveRecentTokens: pick("preserveRecentTokens"), + preserveRecentTurns: pick("preserveRecentTurns"), + protectUserMessages: pick("protectUserMessages"), minCompressRangeChars: rangeOf(model) ?? rangeOf(provider) ?? rangeOf(global), maxSummaryLength: pick("maxSummaryLength"), minSummaryLength: pick("minSummaryLength"), @@ -336,6 +338,10 @@ export function applyCompressSettings(base: Config, limit: number, s: CompressSe tiers, preserveRecentMessages: s.preserveRecentMessages ?? base.preserveRecentMessages, preserveRecentTokens: s.preserveRecentTokens ?? base.preserveRecentTokens, + // #4593: `??` (not `||`) — an explicit 0 / false at a deeper level is + // meaningful (off) and must override an enabled shallower level. + preserveRecentTurns: s.preserveRecentTurns ?? base.preserveRecentTurns, + protectUserMessages: s.protectUserMessages ?? base.protectUserMessages, compress: { ...base.compress, minCompressRange: s.minCompressRangeChars ?? s.minCompressRange ?? base.compress.minCompressRange, diff --git a/src/config.ts b/src/config.ts index 077ec0286b..c73fedbdd3 100644 --- a/src/config.ts +++ b/src/config.ts @@ -290,6 +290,20 @@ export type CompressSettings = { preserveRecentMessages?: number; /** Token budget reserved for recent messages (kernel `preserveRecentTokens`). */ preserveRecentTokens?: number; + /** #4593: per-turn retention. All messages of the last N turns (a turn = + * one user message plus everything up to the next user message) join + * the soft-protected zone: a submitted range is truncated/carved at the + * boundary with an auditable warning, and a range entirely inside it is + * rejected. 0 or unset = off. Deepest level wins across global → + * provider → model, like the other compress fields. Maps to kernel + * `preserveRecentTurns` (acp-kernel >= 0.0.152). */ + preserveRecentTurns?: number; + /** #4593: hard-protect every user text message (kernel + * `protectUserMessages`). User instructions are the only non-regenerable + * input in a session — once folded into a summary they can no longer be + * checked verbatim. Off unless explicitly enabled at some level. Maps to + * kernel `protectUserMessages` (acp-kernel >= 0.0.152). */ + protectUserMessages?: boolean; /** Minimum compressible range size, in CHARACTERS (not tokens); smaller * ranges are skipped. English/code averages ~4 chars per token, CJK * ~1-2 chars per token, so the same number is ~4× more permissive for @@ -2224,7 +2238,7 @@ const KNOWN_TOP_LEVEL_KEYS = new Set([ const COMPRESS_SETTING_FIELDS = new Set([ "modelContextLimit", "maxContextLimit", "emergencyThresholdPercent", "nudgeGrowthTokens", "minPressureBenefitTokens", "tierNudgeTokens", "nudgeModelDecided", "nudgeDecisionMaxTokens", - "preserveRecentMessages", "preserveRecentTokens", + "preserveRecentMessages", "preserveRecentTokens", "preserveRecentTurns", "protectUserMessages", "minCompressRange", "minCompressRangeChars", "outputHeadroomMaxPct", "tiers", "protectedLatestTools", "protectedTools", "neverPreserveRecentTools", "preserveRecentTools", @@ -2906,6 +2920,17 @@ export function parseCompressSettings(v: unknown): (CompressSettings & { injectT if (typeof v !== "number" || !Number.isFinite(v) || v < 0) ok = false; else (out as Record)[key] = v; } + // #4593: an explicit 0 is meaningful (off), so validate >= 0 instead of + // takeNumber's plain finite check (same class as minPressureBenefitTokens). + if ("preserveRecentTurns" in obj) { + const v = obj.preserveRecentTurns; + if (typeof v !== "number" || !Number.isFinite(v) || v < 0) ok = false; + else out.preserveRecentTurns = Math.floor(v); + } + if ("protectUserMessages" in obj) { + if (typeof obj.protectUserMessages !== "boolean") ok = false; + else out.protectUserMessages = obj.protectUserMessages; + } // #2228: the decision side-call budget must be positive — 0/negative would // starve the call, so validate stricter than takeNumber. if ("nudgeDecisionMaxTokens" in obj) { diff --git a/src/preflight.ts b/src/preflight.ts index 4c90bf5c26..eb6c757218 100644 --- a/src/preflight.ts +++ b/src/preflight.ts @@ -1432,6 +1432,11 @@ function readDeterministicProbeState(metadata: Record): Determi // the soft zone is a preference, not a constraint: relax it to zero so its // oldest content becomes foldable. The hard protectedTools exclusion is // computed independently of preserveRecent* and still applies. +// #4593 exception: preserveRecentTurns is deliberately NOT relaxed here. It is +// an explicit user decision that the last N turns (and their user +// instructions) must survive verbatim — folding them under overflow defeats +// the feature's purpose, so an unresolvable overflow fails loudly instead. +// protectUserMessages is a hard protection and never relaxes either. function relaxedConfig(config: Config): Config { return { ...config, preserveRecentMessages: 0, preserveRecentTokens: 0 }; } diff --git a/tests/compress-settings.test.ts b/tests/compress-settings.test.ts index 4940464dc0..010d680382 100644 --- a/tests/compress-settings.test.ts +++ b/tests/compress-settings.test.ts @@ -394,3 +394,44 @@ test("applyCompressSettings: maps tierNudgeTokens onto kernel nudge.tierGrowthTo assert.equal(absent.nudge.tierGrowthTokens, undefined); assert.equal(base.nudge.tierGrowthTokens, undefined, "base config not mutated"); }); + +test("mergeCompress: preserveRecentTurns / protectUserMessages cascade per field (#4593)", () => { + const merged = mergeCompress( + { preserveRecentTurns: 3, protectUserMessages: true }, + { preserveRecentTurns: 2 }, + { protectUserMessages: false }, + ); + assert.equal(merged.preserveRecentTurns, 2); + assert.equal(merged.protectUserMessages, false); + const absent = mergeCompress({}, {}, {}); + assert.equal(absent.preserveRecentTurns, undefined); + assert.equal(absent.protectUserMessages, undefined); +}); + +test("parseCompressSettings: preserveRecentTurns validates a finite >= 0 number, 0 = explicit off (#4593)", () => { + assert.equal(parseCompressSettings({ preserveRecentTurns: 3 })?.preserveRecentTurns, 3); + assert.equal(parseCompressSettings({ preserveRecentTurns: 0 })?.preserveRecentTurns, 0); + assert.equal(parseCompressSettings({ preserveRecentTurns: 3.7 })?.preserveRecentTurns, 3); + assert.equal(parseCompressSettings({ preserveRecentTurns: -1 }), undefined); + assert.equal(parseCompressSettings({ preserveRecentTurns: "3" }), undefined); + assert.equal(parseCompressSettings({ preserveRecentTurns: Number.NaN }), undefined); + assert.equal(parseCompressSettings({})?.preserveRecentTurns, undefined); +}); + +test("parseCompressSettings: protectUserMessages is a strict boolean (#4593)", () => { + assert.equal(parseCompressSettings({ protectUserMessages: true })?.protectUserMessages, true); + assert.equal(parseCompressSettings({ protectUserMessages: false })?.protectUserMessages, false); + assert.equal(parseCompressSettings({ protectUserMessages: "yes" }), undefined); + assert.equal(parseCompressSettings({ protectUserMessages: 1 }), undefined); + assert.equal(parseCompressSettings({})?.protectUserMessages, undefined); +}); + +test("applyCompressSettings: maps #4593 keys onto the kernel config; unset inherits base", () => { + const base = defaultConfig(200000); + const out = applyCompressSettings(base, 200000, { preserveRecentTurns: 4, protectUserMessages: true }); + assert.equal(out.preserveRecentTurns, 4); + assert.equal(out.protectUserMessages, true); + const inherited = applyCompressSettings(base, 200000, {}); + assert.equal(inherited.preserveRecentTurns, base.preserveRecentTurns); + assert.equal(inherited.protectUserMessages, base.protectUserMessages); +}); From 2244abeba6313ed8ad2846ecf3f8df9dfd8c1448 Mon Sep 17 00:00:00 2001 From: ci-check Date: Sun, 25 Oct 2026 06:28:55 +0800 Subject: [PATCH 3/6] fix(kernel): align #4593 comments with the implemented two-tier behavior; floor fractional preserveRecentTurns MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review fixes for the turn-retention feature (review of this PR): - types.ts / turn-retention.ts / recommend.ts: three comments still described the abandoned design (ANY overlap rejected). The implemented behavior is two-tier: partial overlap carves at the boundary with an auditable receipt, full containment rejects. Also corrected the window-start wording in types.ts (the boundary itself is included). - turn-retention.ts: floor fractional N. The host floors at parse time, but acp-kernel ships standalone — a direct-API fractional value would index boundaries[] fractionally and silently degrade to off. - unit-projection.ts: zone error wording uses the effective (floored) N. - tests: fractional-N case (1.9 -> window of 1 turn). --- kernel/src/recommend.ts | 5 +++-- kernel/src/turn-retention.ts | 15 +++++++++++---- kernel/src/types.ts | 14 ++++++++------ kernel/src/unit-projection.ts | 2 +- kernel/tests/issue4593-turn-retention.test.ts | 8 ++++++++ 5 files changed, 31 insertions(+), 13 deletions(-) diff --git a/kernel/src/recommend.ts b/kernel/src/recommend.ts index a91b247b9a..3ec2786bba 100644 --- a/kernel/src/recommend.ts +++ b/kernel/src/recommend.ts @@ -72,8 +72,9 @@ function isSyntheticOrPruned( * 3. Last visible user message (couples to Rule 1) * 4. Per-turn retention (#4593): the last N user-initiated turns form a * positional protected suffix (`config.preserveRecentTurns`; recomputed - * every turn — see turn-retention.ts). Ranges overlapping it are - * rejected by projectUnit, not truncated like Rules 1-3. + * every turn — see turn-retention.ts). A submitted range overlapping it + * is carved there with an auditable receipt (like Rules 1-3); a range + * entirely inside it is rejected by projectUnit. * * Then closes the tool-pair gap (#2886): if either half of a (tool-call, * tool-result) pair is protected, both are. Without this, `neverPreserveRecentTools` diff --git a/kernel/src/turn-retention.ts b/kernel/src/turn-retention.ts index c9b6f1199d..bf8c099321 100644 --- a/kernel/src/turn-retention.ts +++ b/kernel/src/turn-retention.ts @@ -20,14 +20,17 @@ import { SUMMARY_HEADER } from "./prune.js"; * (an aged-out message would stay blocked forever, or force per-turn * BLOCKED→numeric migration = prefix-cache churn). It recomputes every turn: * computeProtectedRefs unions the refs into the soft-protection set, and - * projectUnit rejects submitted ranges that overlap it. + * projectUnit enforces it in two tiers — a submitted range PARTIALLY + * overlapping the window is carved there (auditable receipt warning naming + * the turn zone), while a range ENTIRELY inside it is rejected (the range is + * explicit user intent aimed at protected content). */ export interface TurnRetention { /** Smallest messages-array index inside the retained suffix; everything at * or after it is protected. 0 = the entire conversation is retained. */ boundaryIndex: number; - /** The configured N (for error wording). */ + /** The effective (floored) N (for error wording). */ turns: number; } @@ -36,8 +39,12 @@ export function computeTurnRetention( state: CompressionState, config: Pick, ): TurnRetention | null { - const turns = config.preserveRecentTurns; - if (turns === undefined || !Number.isFinite(turns) || turns < 1) return null; + const raw = config.preserveRecentTurns; + if (raw === undefined || !Number.isFinite(raw) || raw < 1) return null; + // The host floors at parse time (src/config.ts); the kernel must be + // self-consistent for direct API users — a fractional N would otherwise + // index boundaries[] fractionally and silently degrade to off. + const turns = Math.floor(raw); const covered = coveredMessageIds(state); const boundaries: number[] = []; for (let i = 0; i < messages.length; i++) { diff --git a/kernel/src/types.ts b/kernel/src/types.ts index ccb2d7f3bc..a15d8b77ca 100644 --- a/kernel/src/types.ts +++ b/kernel/src/types.ts @@ -514,14 +514,16 @@ export interface Config { /** #4593: per-turn retention — the last N user-initiated turns stay * verbatim on the wire. A turn boundary is a visible user message (not a * summary carrier, not already covered by an active block); consecutive - * user messages count as ONE boundary. Everything at or after the index - * right past the (N+1)-th-from-last boundary is protected; when fewer than + * user messages count as ONE boundary. Everything at or after the + * (N+1)-th-from-last boundary (inclusive) is protected; when fewer than * N+1 boundaries exist the ENTIRE conversation is retained. Recomputed * every turn (the window slides with each new user message), so it rides - * the soft-protection set rather than the permanent BLOCKED-ref decision - * — and a submitted range that overlaps it is REJECTED (it is explicit - * user intent, stronger than the advisory recent-zone truncation of - * #3953). `0`/unset = off. */ + * the soft-protection set rather than the permanent BLOCKED-ref decision; + * projectUnit enforces it in two tiers — a submitted range PARTIALLY + * overlapping the window is carved at the boundary with an auditable + * receipt warning, a range ENTIRELY inside it is REJECTED (explicit user + * intent aimed at protected content). Fractional N floors (host parse and + * kernel agree). `0`/unset = off. */ preserveRecentTurns?: number; /** #4593: hard-exclude every ordinary user text message from compression * (BLOCKED ref, same semantics as protectedTools): user instructions are diff --git a/kernel/src/unit-projection.ts b/kernel/src/unit-projection.ts index 7141ec9406..d0a921e715 100644 --- a/kernel/src/unit-projection.ts +++ b/kernel/src/unit-projection.ts @@ -322,7 +322,7 @@ export function projectUnit(input: UnitProjectionInput): UnitProjection { const retention = computeTurnRetention(input.messages, input.state, input.config); let turnRetainedCount = 0; if (retention) { - zoneParts.push(`the last ${input.config.preserveRecentTurns} turns`); + zoneParts.push(`the last ${retention.turns} turns`); const retained = new Set(); for (let i = retention.boundaryIndex; i < input.messages.length; i++) { retained.add(input.messages[i]!.id); diff --git a/kernel/tests/issue4593-turn-retention.test.ts b/kernel/tests/issue4593-turn-retention.test.ts index edede94071..4c8fa834a3 100644 --- a/kernel/tests/issue4593-turn-retention.test.ts +++ b/kernel/tests/issue4593-turn-retention.test.ts @@ -90,6 +90,14 @@ test("computeTurnRetention: the window starts AT the (N+1)-th-from-last user mes }); }); +test("computeTurnRetention: fractional N floors like host parse (#4593)", () => { + const state = createInitialState(); + assert.deepEqual(computeTurnRetention(FIVE_TURNS, state, { preserveRecentTurns: 1.9 }), { + boundaryIndex: 8, + turns: 1, + }); +}); + test("computeTurnRetention: fewer than N+1 turns protects everything (#4593)", () => { const state = createInitialState(); assert.deepEqual(computeTurnRetention(FIVE_TURNS, state, { preserveRecentTurns: 6 }), { From 9df2264997039680ee2ccc991347ad5a71caf7a7 Mon Sep 17 00:00:00 2001 From: ci-check Date: Sun, 25 Oct 2026 06:35:00 +0800 Subject: [PATCH 4/6] docs: add #4593 config-reference seeds, regenerate derived docs, fix carrier-exclusion wording and kernel version refs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review fixes for the turn-retention feature (review of this PR): - The two new compress keys were added to COMPRESS_SETTING_FIELDS and to the generated index tables by hand, but their seeds were missing from website/config-reference/*.yaml — both the config-surface-guard and the docs-sync CI jobs fail on that. Add the seeds (cw.prturns / cw.pum) and regenerate all derived artifacts through tools/gen-config-docs.mjs. Regeneration also corrects the hand-edited table rows: the Env column is for BILI_* env vars (these keys have none), so it renders '—'. - Detail sections claimed summary carriers are role system; the actual exclusion is by SUMMARY_HEADER text prefix on user-role messages (tool results never match on role). Fix en+zh wording to match the code (kernel/src/protected.ts isUserTextMessage). - Kernel version refs 0.0.152 -> 0.0.164: the branch was rebased onto master, where acp-kernel is at 0.0.163, so this change ships as 0.0.164 (CI-enforced version discipline). --- CONFIGURATION.md | 10 +++++----- CONFIGURATION.zh-CN.md | 10 +++++----- src/config.ts | 4 ++-- website/config-reference/compress.yaml | 20 ++++++++++++++++++++ website/docs/index.html | 2 ++ website/main.js | 4 ++++ 6 files changed, 38 insertions(+), 12 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 1b5376a3ed..939a1e16b4 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -266,8 +266,8 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `compress.streamSummary` | boolean | false (unset) | — | Force preflight summarization to run as a streaming (SSE) call from the first attempt. The error-driven self-learn handles stream-mandating upstreams on its own (any 400 on a non-streaming summary triggers a one-shot SSE probe, #2494) but NEVER arms on gateway timeouts (e.g. Cloudflare HTTP 524): set this where such a gateway sits between bili and the origin, or simply to skip the one probe round-trip. | | `compress.preserveRecentMessages` | number | 3 | — | The most recent messages stay soft-protected from folds. | | `compress.preserveRecentTokens` | number | kernel ≈5000 | — | The most recent tokens stay soft-protected from folds. | -| `compress.preserveRecentTurns` | number | off | acp-kernel ≥ 0.0.152 | All messages of the last N turns (turn = user message → next user message) join the soft-protected zone (#4593). | -| `compress.protectUserMessages` | boolean | off | acp-kernel ≥ 0.0.152 | Every user text message is hard-protected, never compressible (#4593). | +| `compress.preserveRecentTurns` | number | off | — | All messages of the last N turns (turn = user message → next user message) join the soft-protected zone (#4593). | +| `compress.protectUserMessages` | boolean | off | — | Every user text message is hard-protected, never compressible (#4593). | | `compress.minCompressRangeChars` | number (deprecated alias: minCompressRange) | kernel ≈5000 | — | Smallest foldable range, in characters; shorter ranges never fold. | | `compress.maxSummaryLength` | number | kernel 20000 | — | Hard character cap on ONE generated summary; longer replies are rejected whole (no truncation, no retry). External summarizers are told this exact cap up front (#3635). 0 = unbounded. | | `compress.minSummaryLength` | number | kernel 50 | — | Character floor for generated summaries; shorter replies are rejected whole. 0 = disabled. External summarizers are held to the same floor (#3635). | @@ -1378,7 +1378,7 @@ For each request, the proxy resolves the settings by longest-URL-prefix match (t - **Type:** `number` - **Default:** off (`0` or unset) -- **Status:** ACTIVE (#4593, requires `acp-kernel` ≥ 0.0.152) +- **Status:** ACTIVE (#4593, requires `acp-kernel` ≥ 0.0.164) - **Description:** Per-turn retention. A "turn" is one user message plus everything up to the next user message. All messages of the last N turns join the soft-protected zone alongside `preserveRecentMessages`/`preserveRecentTokens`/the latest-user pin — one union set, no internal priority. Message counts don't bound a turn (a single turn spans dozens of tool calls/results), which is why count-based retention alone either cuts mid-turn or over-retains. Deterministic behavior for a submitted compress range: - **Range entirely inside the protected zone** → rejected with `Range is entirely within the protected zone (…)`. - **Range partially overlapping** → the protected part is filtered out (truncated at the first interior protected message so no summary lands above the question it answers, #3953); the rest compresses normally, and the receipt carries an auditable warning listing exactly which refs were skipped and their cause (`…of which N in last-turns retention`). If the remainder falls below `minCompressRange`, the existing too-small rejection applies. @@ -1390,8 +1390,8 @@ For each request, the proxy resolves the settings by longest-URL-prefix match (t - **Type:** `boolean` - **Default:** off (unset = `false`) -- **Status:** ACTIVE (#4593, requires `acp-kernel` ≥ 0.0.152) -- **Description:** Hard-protect every user text message — the only non-regenerable input in a session: tool results can be re-run, summaries rewritten, but once a user instruction is folded into a model-written summary it can no longer be checked verbatim. Protection is a HARD exclusion like `protectedTools`: matching refs render as `BLOCKED`, are never advertised as compressible, and a submitted range containing them has them carved out with an auditable receipt warning (`Excluded N user message(s) … (protectUserMessages)`); a range consisting solely of such messages is rejected. Conservative by design: host-injected runtime-context user messages are covered too (over-protection costs compression ratio; under-protection loses instructions). Kernel summary carriers (role `system`) and tool results (role `tool`) do NOT match. Deepest level wins across global → provider → model like the other compress fields. +- **Status:** ACTIVE (#4593, requires `acp-kernel` ≥ 0.0.164) +- **Description:** Hard-protect every user text message — the only non-regenerable input in a session: tool results can be re-run, summaries rewritten, but once a user instruction is folded into a model-written summary it can no longer be checked verbatim. Protection is a HARD exclusion like `protectedTools`: matching refs render as `BLOCKED`, are never advertised as compressible, and a submitted range containing them has them carved out with an auditable receipt warning (`Excluded N user message(s) … (protectUserMessages)`); a range consisting solely of such messages is rejected. Conservative by design: host-injected runtime-context user messages are covered too (over-protection costs compression ratio; under-protection loses instructions). Summary carriers — user-role messages whose text starts with the kernel's SUMMARY_HEADER — and tool results (role `tool`) do NOT match. Deepest level wins across global → provider → model like the other compress fields. - **Example:** `{ "compress": { "protectUserMessages": true } }` #### `minCompressRangeChars` diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index a6ce2d5769..be13f78362 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -266,8 +266,8 @@ | `compress.streamSummary` | boolean | false (unset) | — | 强制 preflight 摘要从首次尝试起就走流式(SSE)请求。要求流式的上游现在由错误驱动自学习自动处理(非流式摘要的任何 400 都会触发一次性 SSE 探测,#2494),但网关超时(如 Cloudflare HTTP 524)永远无法触发自学习:在此类网关位于 bili 与源站之间时设置此项,或用于省去一次探测往返。 | | `compress.preserveRecentMessages` | number | 3 | — | 最近的消息软保护、免于折叠。 | | `compress.preserveRecentTokens` | number | kernel ≈5000 | — | 最近的 token 软保护、免于折叠。 | -| `compress.preserveRecentTurns` | number | 关闭 | acp-kernel ≥ 0.0.152 | 最近 N 轮(轮 = 一条 user 消息到下一条 user 消息)的全部消息加入软保护区(#4593)。 | -| `compress.protectUserMessages` | boolean | 关闭 | acp-kernel ≥ 0.0.152 | 所有 user 文本消息硬保护、永不压缩(#4593)。 | +| `compress.preserveRecentTurns` | number | off | — | 最近 N 轮(轮 = 一条 user 消息到下一条 user 消息)的全部消息加入软保护区(#4593)。 | +| `compress.protectUserMessages` | boolean | off | — | 所有 user 文本消息硬保护、永不压缩(#4593)。 | | `compress.minCompressRangeChars` | number (deprecated alias: minCompressRange) | kernel ≈5000 | — | 可折叠片段的最小字符数;更短的永不折叠。 | | `compress.maxSummaryLength` | number | kernel 20000 | — | 单条生成摘要的硬字符上限;超长的回复被整段拒绝(不截断、不重试)。外部摘要模型会被提前告知这个确切上限(#3635)。0 = 不限制。 | | `compress.minSummaryLength` | number | kernel 50 | — | 生成摘要的字符下限;过短的回复被整段拒绝。0 = 禁用。外部摘要模型受同一下限约束(#3635)。 | @@ -1381,7 +1381,7 @@ ACP 原生 agent(当前为 `pi` 扩展)会在每个进程内向代理上报 - **类型:** `number` - **默认值:** 关闭(`0` 或未设置) -- **状态:** ACTIVE(#4593,需要 `acp-kernel` ≥ 0.0.152) +- **状态:** ACTIVE(#4593,需要 `acp-kernel` ≥ 0.0.164) - **说明:** 按轮保留。一轮 = 一条 user 消息 + 到下一条 user 消息为止的全部内容。最近 N 轮的全部消息与 `preserveRecentMessages`/`preserveRecentTokens`/最新 user 钉住一起并入软保护区——同一个并集,无内部优先级。一条轮往往横跨几十条工具调用/结果,按条数保留要么截在轮中间、要么过度保留,这正是本键存在的理由。提交压缩区间时的确定行为: - **区间完全落在保护区内** → 拒绝,报错 `Range is entirely within the protected zone (…)`. - **区间部分重叠** → 受保护部分被过滤掉(在第一条内部受保护消息处截断,保证摘要不会落在它所回答的问题之上,#3953),其余部分正常压缩;回执里带一条可审计警告,逐条列出被跳过的 ref 及原因(`…of which N in last-turns retention`)。若剩余不足 `minCompressRange`,走既有的 too-small 拒绝。 @@ -1393,8 +1393,8 @@ ACP 原生 agent(当前为 `pi` 扩展)会在每个进程内向代理上报 - **类型:** `boolean` - **默认值:** 关闭(未设置 = `false`) -- **状态:** ACTIVE(#4593,需要 `acp-kernel` ≥ 0.0.152) -- **说明:** 硬保护所有 user 文本消息——会话中唯一不可再生的输入:工具结果可以重跑、摘要可以重写,但用户指令一旦被折进模型自写的摘要,就无法再逐字核对。保护是 HARD 排除,语义同 `protectedTools`:匹配的 ref 显示为 `BLOCKED`、永不出现在可压缩推荐里;提交的区间包含它们时会被过滤并留下可审计的回执警告(`Excluded N user message(s) … (protectUserMessages)`);整段全是这类消息的区间会被拒绝。刻意保守:宿主注入的 runtime-context user 消息也在保护范围内(误保护只损失压缩比,误折叠会丢指令)。内核摘要载体(role `system`)与工具结果(role `tool`)不匹配。与其他 compress 字段一样,global → provider → model 最深层生效。 +- **状态:** ACTIVE(#4593,需要 `acp-kernel` ≥ 0.0.164) +- **说明:** 硬保护所有 user 文本消息——会话中唯一不可再生的输入:工具结果可以重跑、摘要可以重写,但用户指令一旦被折进模型自写的摘要,就无法再逐字核对。保护是 HARD 排除,语义同 `protectedTools`:匹配的 ref 显示为 `BLOCKED`、永不出现在可压缩推荐里;提交的区间包含它们时会被过滤并留下可审计的回执警告(`Excluded N user message(s) … (protectUserMessages)`);整段全是这类消息的区间会被拒绝。刻意保守:宿主注入的 runtime-context user 消息也在保护范围内(误保护只损失压缩比,误折叠会丢指令)。摘要载体——文本以内核 SUMMARY_HEADER 开头的 user 消息——与工具结果(role `tool`)不匹配。与其他 compress 字段一样,global → provider → model 最深层生效。 - **示例:** `{ "compress": { "protectUserMessages": true } }` #### `minCompressRangeChars` diff --git a/src/config.ts b/src/config.ts index c73fedbdd3..d2cea45fa6 100644 --- a/src/config.ts +++ b/src/config.ts @@ -296,13 +296,13 @@ export type CompressSettings = { * boundary with an auditable warning, and a range entirely inside it is * rejected. 0 or unset = off. Deepest level wins across global → * provider → model, like the other compress fields. Maps to kernel - * `preserveRecentTurns` (acp-kernel >= 0.0.152). */ + * `preserveRecentTurns` (acp-kernel >= 0.0.164). */ preserveRecentTurns?: number; /** #4593: hard-protect every user text message (kernel * `protectUserMessages`). User instructions are the only non-regenerable * input in a session — once folded into a summary they can no longer be * checked verbatim. Off unless explicitly enabled at some level. Maps to - * kernel `protectUserMessages` (acp-kernel >= 0.0.152). */ + * kernel `protectUserMessages` (acp-kernel >= 0.0.164). */ protectUserMessages?: boolean; /** Minimum compressible range size, in CHARACTERS (not tokens); smaller * ranges are skipped. English/code averages ~4 chars per token, CJK diff --git a/website/config-reference/compress.yaml b/website/config-reference/compress.yaml index 532cd5a055..5e35134db4 100644 --- a/website/config-reference/compress.yaml +++ b/website/config-reference/compress.yaml @@ -122,6 +122,26 @@ entries: desc_zh: "最近的 token 软保护、免于折叠。" site_en: "Kernel default ≈5000: the most recent tokens stay soft-protected from folds." site_zh: "内核默认约 5000:最近的 token 软保护、免于折叠。" + - key: compress.preserveRecentTurns + type: number + default: "off" + group: compress + id: cw.prturns + render: compress-row + desc_en: "All messages of the last N turns (turn = user message → next user message) join the soft-protected zone (#4593)." + desc_zh: "最近 N 轮(轮 = 一条 user 消息到下一条 user 消息)的全部消息加入软保护区(#4593)。" + site_en: "Opt-in per-turn retention (#4593): all messages of the last N turns stay verbatim on the wire. A submitted fold partially overlapping them is carved at the boundary with an auditable receipt warning; a fold entirely inside is rejected. Off unless set." + site_zh: "可选的按轮保留(#4593):最近 N 轮的全部消息逐字保留在线路上。提交的折叠若部分覆盖则在边界处裁出并附可审计回执警告;完全落在保护区内则拒绝。默认关闭。" + - key: compress.protectUserMessages + type: boolean + default: "off" + group: compress + id: cw.pum + render: compress-row + desc_en: "Every user text message is hard-protected, never compressible (#4593)." + desc_zh: "所有 user 文本消息硬保护、永不压缩(#4593)。" + site_en: "Opt-in hard protection for user instructions (#4593): every user text message renders as BLOCKED and is carved out of any submitted fold with an auditable receipt warning; summary carriers are exempt. Off unless set." + site_zh: "可选的用户指令硬保护(#4593):每条 user 文本消息渲染为 BLOCKED,任何提交的折叠都会将其裁出并附可审计回执警告;摘要载体除外。默认关闭。" - key: compress.minCompressRangeChars type: "number (deprecated alias: minCompressRange)" default: "kernel ≈5000" diff --git a/website/docs/index.html b/website/docs/index.html index f536028c6f..3f491c78f4 100644 --- a/website/docs/index.html +++ b/website/docs/index.html @@ -190,6 +190,8 @@

compress — every knob

streamSummarybooleanForce streaming (SSE) summarization from the first attempt — stream-mandating upstreams now self-heal via a one-shot SSE probe on any non-streaming 400 (#2494); kept as the escape hatch for gateways that time out long non-streaming calls (e.g. Cloudflare 524), which the self-learn cannot detect, or to skip the one probe round-trip. preserveRecentMessagesnumberKernel default 3 (tuned 5 → 3, #3058): the most recent messages stay soft-protected from folds. preserveRecentTokensnumberKernel default ≈5000: the most recent tokens stay soft-protected from folds. + preserveRecentTurnsnumberOpt-in per-turn retention (#4593): all messages of the last N turns stay verbatim on the wire. A submitted fold partially overlapping them is carved at the boundary with an auditable receipt warning; a fold entirely inside is rejected. Off unless set. + protectUserMessagesbooleanOpt-in hard protection for user instructions (#4593): every user text message renders as BLOCKED and is carved out of any submitted fold with an auditable receipt warning; summary carriers are exempt. Off unless set. minCompressRangeCharsnumber (deprecated alias: minCompressRange)Smallest foldable range, in characters (kernel default ≈5000) — shorter ranges never fold. maxSummaryLengthnumberHard cap, in characters, on one generated summary (kernel default 20000): longer replies are rejected whole by the kernel check or the external-summary executor. External summarizers receive this exact cap in their instructions (#3635); 0 disables the cap. minSummaryLengthnumberFloor, in characters, for generated summaries (kernel default 50): shorter replies are rejected whole; 0 disables the floor. External summarizers are held to the same floor (#3635). diff --git a/website/main.js b/website/main.js index de092ebcba..710f941850 100644 --- a/website/main.js +++ b/website/main.js @@ -73,6 +73,8 @@ "cw.ssm": "Force streaming (SSE) summarization from the first attempt — stream-mandating upstreams now self-heal via a one-shot SSE probe on any non-streaming 400 (#2494); kept as the escape hatch for gateways that time out long non-streaming calls (e.g. Cloudflare 524), which the self-learn cannot detect, or to skip the one probe round-trip.", "cw.prm": "Kernel default 3 (tuned 5 → 3, #3058): the most recent messages stay soft-protected from folds.", "cw.prt": "Kernel default ≈5000: the most recent tokens stay soft-protected from folds.", + "cw.prturns": "Opt-in per-turn retention (#4593): all messages of the last N turns stay verbatim on the wire. A submitted fold partially overlapping them is carved at the boundary with an auditable receipt warning; a fold entirely inside is rejected. Off unless set.", + "cw.pum": "Opt-in hard protection for user instructions (#4593): every user text message renders as BLOCKED and is carved out of any submitted fold with an auditable receipt warning; summary carriers are exempt. Off unless set.", "cw.mrc": "Smallest foldable range, in characters (kernel default ≈5000) — shorter ranges never fold.", "cw.msl": "Hard cap, in characters, on one generated summary (kernel default 20000): longer replies are rejected whole by the kernel check or the external-summary executor. External summarizers receive this exact cap in their instructions (#3635); 0 disables the cap.", "cw.mnl": "Floor, in characters, for generated summaries (kernel default 50): shorter replies are rejected whole; 0 disables the floor. External summarizers are held to the same floor (#3635).", @@ -318,6 +320,8 @@ "cw.ssm": "强制摘要从首次起走流式(SSE)——要求流式的上游现在通过任何非流式 400 上的一次性 SSE 探测自愈(#2494);保留作为会掐断长非流式调用的网关(如 Cloudflare 524)的逃生通道(自学习无法感知该场景),也可用于省去一次探测往返。", "cw.prm": "内核默认 3(5 → 3,#3058):最近消息软保护、免于折叠。", "cw.prt": "内核默认约 5000:最近的 token 软保护、免于折叠。", + "cw.prturns": "可选的按轮保留(#4593):最近 N 轮的全部消息逐字保留在线路上。提交的折叠若部分覆盖则在边界处裁出并附可审计回执警告;完全落在保护区内则拒绝。默认关闭。", + "cw.pum": "可选的用户指令硬保护(#4593):每条 user 文本消息渲染为 BLOCKED,任何提交的折叠都会将其裁出并附可审计回执警告;摘要载体除外。默认关闭。", "cw.mrc": "可折叠片段的最小字符数(内核默认约 5000),更短的永不折叠。", "cw.msl": "单条生成摘要的硬上限,单位为字符(内核默认 20000):超长的回复由内核检查或外部摘要执行器整段拒绝。外部摘要模型的指令中会写明这个确切上限(#3635);0 禁用上限。", "cw.mnl": "生成摘要的下限,单位为字符(内核默认 50):过短的回复被整段拒绝;0 禁下限。外部摘要模型受同一下限约束(#3635)。", From fa2fc54631f4d53bb09059e3ffb6fe0ac37da0ae Mon Sep 17 00:00:00 2001 From: ci-check Date: Sun, 25 Oct 2026 06:53:35 +0800 Subject: [PATCH 5/6] fix(kernel): sync kernel/package-lock.json version to 0.0.164 (lock-sync gate) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The rebase bumped kernel/package.json to 0.0.164 but the kernel's own lockfile (standalone acp-kernel identity, #2092) still recorded 0.0.163 — the lock-sync CI job diffs the regenerated kernel/package-lock.json and fails on that drift. (The original branch had the same latent drift from its 0.0.151 -> 0.0.152 bump.) --- 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 2a94d0e396..da011d94e1 100644 --- a/kernel/package-lock.json +++ b/kernel/package-lock.json @@ -1,12 +1,12 @@ { "name": "acp-kernel", - "version": "0.0.163", + "version": "0.0.164", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "acp-kernel", - "version": "0.0.163", + "version": "0.0.164", "license": "MIT", "devDependencies": { "@types/node": "^22.0.0", From e08e9fafea326002ed66670f9d3e49397d450243 Mon Sep 17 00:00:00 2001 From: ci-check Date: Sun, 25 Oct 2026 07:03:47 +0800 Subject: [PATCH 6/6] fix: sync root package-lock.json kernel link record to acp-kernel 0.0.164 (lock-sync gate) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up to the kernel/package-lock.json sync: the root lockfile also carries the file:-link's recorded version under packages."kernel", which the rebase bump to 0.0.164 left at 0.0.163 — the lock-sync job's root regen diffs exactly that line. --- package-lock.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package-lock.json b/package-lock.json index ad31ac56d5..3e4ceed45b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -50,7 +50,7 @@ }, "kernel": { "name": "acp-kernel", - "version": "0.0.163", + "version": "0.0.164", "dev": true, "license": "MIT", "devDependencies": {