diff --git a/docs/configuration.ja.md b/docs/configuration.ja.md index 215a6ffc3e..e51b398df1 100644 --- a/docs/configuration.ja.md +++ b/docs/configuration.ja.md @@ -292,6 +292,8 @@ | `compress.streamSummary` | boolean | false (unset) | — | 事前チェックの要約を、最初の試行からストリーミング(SSE)コールとして実行することを強制する。エラー駆動の自己学習は、ストリーミングを強制するアップストリームを独自に処理する(非ストリーミング要約での 400 はワンショット SSE プローブをトリガーする、#2494)が、ゲートウェイタイムアウト(例: Cloudflare HTTP 524)では決してアームしない:bili とオリジンの間にそのようなゲートウェイがある場合にこれを設定するか、単に 1 回のプローブ往復をスキップするために設定する。 | | `compress.preserveRecentMessages` | number | 3 | — | 最新のメッセージは、折りたたみからソフト保護される。 | | `compress.preserveRecentTokens` | number | kernel ≈5000 | — | 最新のトークンはフォールドからソフト保護される。 | +| `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 | — | 1つの生成サマリーに対する文字数のハード上限。これを超える返信は全体として拒否される(切り詰めもリトライもされない)。外部サマライザーにはこの正確な上限が事前に通知される(#3635)。0 = 無制限。 | | `compress.minSummaryLength` | number | kernel 50 | — | 生成サマリーの文字数下限:単一範囲はこれに単独で達する必要がある。複数範囲のバッチは、その結合サマリーがこれに達した場合に合格する(#5894)。0 = 無効。外部サマライザーはサマリーごとの下限に引き続き従う(#3635)。 | diff --git a/docs/configuration.md b/docs/configuration.md index 6eaf046056..dbb43d9833 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -295,6 +295,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 | — | 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: a single range must meet it alone; a multi-range batch passes when its combined summaries reach it (#5894). 0 = disabled. External summarizers remain held to the per-summary floor (#3635). | @@ -1516,6 +1518,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.197) +- **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** → no-op success (#4521, landed on master after this PR branched): nothing folds, the receipt warns `folded nothing — it lies entirely inside the protected zone … do not resend this range` (a rejection would send retry loops back into the same 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.197) +- **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 a no-op success (#4521, landed on master after this PR branched) — nothing folds, the receipt warns `folded nothing … do not resend this range`. 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` - **Type:** `number` diff --git a/docs/configuration.zh-CN.md b/docs/configuration.zh-CN.md index 6209c06540..c0adb1996e 100644 --- a/docs/configuration.zh-CN.md +++ b/docs/configuration.zh-CN.md @@ -295,6 +295,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 | 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 | — | 生成摘要的字符下限:单段压缩按自身判定;批量压缩按合计判定——一段偷懒不再拖垮整批(#5894)。0 = 禁用。外部摘要模型仍受逐段下限约束(#3635)。 | @@ -1513,6 +1515,26 @@ ACP 原生 agent(当前为 `pi` 扩展)会在每个进程内向代理上报 - **状态:** ACTIVE - **说明:** 为最近消息保护预留的 token 预算。映射到内核字段 `preserveRecentTokens`。 +#### `preserveRecentTurns` + +- **类型:** `number` +- **默认值:** 关闭(`0` 或未设置) +- **状态:** ACTIVE(#4593,需要 `acp-kernel` ≥ 0.0.197) +- **说明:** 按轮保留。一轮 = 一条 user 消息 + 到下一条 user 消息为止的全部内容。最近 N 轮的全部消息与 `preserveRecentMessages`/`preserveRecentTokens`/最新 user 钉住一起并入软保护区——同一个并集,无内部优先级。一条轮往往横跨几十条工具调用/结果,按条数保留要么截在轮中间、要么过度保留,这正是本键存在的理由。提交压缩区间时的确定行为: + - **区间完全落在保护区内** → 空操作成功(#4521,在本 PR 分支后合入 master):不折叠任何消息,回执警告 `folded nothing — it lies entirely inside the protected zone … do not resend this range`(若拒绝会把重试循环送回同一保护区)。 + - **区间部分重叠** → 受保护部分被过滤掉(在第一条内部受保护消息处截断,保证摘要不会落在它所回答的问题之上,#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.197) +- **说明:** 硬保护所有 user 文本消息——会话中唯一不可再生的输入:工具结果可以重跑、摘要可以重写,但用户指令一旦被折进模型自写的摘要,就无法再逐字核对。保护是 HARD 排除,语义同 `protectedTools`:匹配的 ref 显示为 `BLOCKED`、永不出现在可压缩推荐里;提交的区间包含它们时会被过滤并留下可审计的回执警告(`Excluded N user message(s) … (protectUserMessages)`);整段全是这类消息的区间是空操作成功(#4521,在本 PR 分支后合入 master)——不折叠任何消息,回执警告 `folded nothing … do not resend this range`。刻意保守:宿主注入的 runtime-context user 消息也在保护范围内(误保护只损失压缩比,误折叠会丢指令)。摘要载体——文本以内核 SUMMARY_HEADER 开头的 user 消息——与工具结果(role `tool`)不匹配。与其他 compress 字段一样,global → provider → model 最深层生效。 +- **示例:** `{ "compress": { "protectUserMessages": true } }` + #### `minCompressRangeChars` - **类型:** `number` diff --git a/kernel/package-lock.json b/kernel/package-lock.json index 9437e48cf1..3e25df6ca0 100644 --- a/kernel/package-lock.json +++ b/kernel/package-lock.json @@ -1,12 +1,12 @@ { "name": "acp-kernel", - "version": "0.0.198", + "version": "0.0.199", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "acp-kernel", - "version": "0.0.198", + "version": "0.0.199", "license": "MIT", "devDependencies": { "@types/node": "^22.0.0", diff --git a/kernel/package.json b/kernel/package.json index a58d31360b..f65ce78fdd 100644 --- a/kernel/package.json +++ b/kernel/package.json @@ -1,6 +1,6 @@ { "name": "acp-kernel", - "version": "0.0.198", + "version": "0.0.199", "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 d180a05b24..597234105a 100644 --- a/kernel/src/compress.ts +++ b/kernel/src/compress.ts @@ -1266,7 +1266,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 68b0f0b935..1a1f2aa6cf 100644 --- a/kernel/src/config.ts +++ b/kernel/src/config.ts @@ -142,6 +142,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 27fd22fa3b..296ce9f5e2 100644 --- a/kernel/src/protected.ts +++ b/kernel/src/protected.ts @@ -314,6 +314,22 @@ 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; +} + /** #5109: the newest HUMAN user request — the Rule-3 protection anchor. * Backward scan skipping (a) bili's own summary carriers and covered ids * (same predicate as recommend's isSyntheticOrPruned, restated here to keep @@ -345,13 +361,20 @@ export function lastUserAnchor( 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 23a2ca2631..e82f12136a 100644 --- a/kernel/src/recommend.ts +++ b/kernel/src/recommend.ts @@ -33,6 +33,7 @@ import { isNeverPreserveRecent, lastUserAnchor, } 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"; @@ -70,10 +71,15 @@ 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). 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` @@ -155,6 +161,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..bf8c099321 --- /dev/null +++ b/kernel/src/turn-retention.ts @@ -0,0 +1,61 @@ +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 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 effective (floored) N (for error wording). */ + turns: number; +} + +export function computeTurnRetention( + messages: CoreMessage[], + state: CompressionState, + config: Pick, +): TurnRetention | 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++) { + 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 7e7b4f4699..0e4b648384 100644 --- a/kernel/src/types.ts +++ b/kernel/src/types.ts @@ -638,6 +638,30 @@ 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 + * (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; + * 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 + * 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 e375abbaa4..fcd57eb8af 100644 --- a/kernel/src/unit-projection.ts +++ b/kernel/src/unit-projection.ts @@ -11,15 +11,17 @@ import { } from "./boundaries.js"; import { isSummaryMessageId } from "./prune.js"; import { + collectAgedCompressCallIds, collectFailedCompressCallIds, collectLatestProtected, hasUnrecoverableMediaPayload, isMessageLatestProtected, isMessageProtected, - collectAgedCompressCallIds, + isUserTextMessage, lastUserAnchor, } from "./protected.js"; import type { LatestProtected } from "./protected.js"; +import { computeTurnRetention } from "./turn-retention.js"; import { buildIntegrityPre, computeIntegrityWithdrawals, @@ -265,6 +267,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 = msgById(id); return !!msg && hasUnrecoverableMediaPayload(msg); @@ -349,8 +372,26 @@ 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 ${retention.turns} 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; // #5789: an empty-after-exclusion span is NOT the protected-zone case — // every nested block was excluded by the recovery ladder because its // coverage strands a live conflict. Zone fatals are treated as no-op @@ -368,7 +409,7 @@ export function projectUnit(input: UnitProjectionInput): UnitProjection { error: excludedFatal ?? 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.`, ), @@ -386,7 +427,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.` + anchorNote + (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..2e6f73bd1e --- /dev/null +++ b/kernel/tests/issue4593-turn-retention.test.ts @@ -0,0 +1,317 @@ +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: 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 }), { + 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 a no-op (#4521) naming the protected 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, + }); + + // #4521 (landed on master after this PR branched): a range entirely inside + // the protected zone is a legal no-op, not a rejection — retry-loop fix. + // Nothing folds; the receipt warns "do not resend". The turn-zone + // attribution itself is still pinned by the crossing-range carve test above. + assert.equal(result.result.blocksCreated, 0); + assert.equal(result.result.errors.length, 0, JSON.stringify(result.result.errors)); + const warning = result.result.warnings.join("\n"); + assert.match(warning, /entirely inside the protected zone/i); +}); + +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 a no-op (#4521)", () => { + 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, + }); + + // #4521 (landed on master after this PR branched): a range of only protected + // user messages is a legal no-op, not a rejection — the carve receipt names + // the protectUserMessages cause, then nothing folds ("do not resend"). + assert.equal(result.result.blocksCreated, 0); + assert.equal(result.result.errors.length, 0, JSON.stringify(result.result.errors)); + const warning = result.result.warnings.join("\n"); + assert.match(warning, /Excluded 2 user message\(s\).*protectUserMessages/s); + assert.match(warning, /folded nothing/i); +}); + +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)); +}); diff --git a/package-lock.json b/package-lock.json index e0603e3124..09dd30aa7b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -50,7 +50,7 @@ }, "kernel": { "name": "acp-kernel", - "version": "0.0.198", + "version": "0.0.199", "dev": true, "license": "MIT", "devDependencies": { diff --git a/src/compress-settings.ts b/src/compress-settings.ts index 687f10f32d..4b6d09c958 100644 --- a/src/compress-settings.ts +++ b/src/compress-settings.ts @@ -83,6 +83,8 @@ export function mergeCompress( requireRecommendation: pick("requireRecommendation"), 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"), @@ -380,6 +382,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 e8c42325c5..bb6f90669e 100644 --- a/src/config.ts +++ b/src/config.ts @@ -344,6 +344,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.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.164). */ + 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 @@ -2553,7 +2567,7 @@ const COMPRESS_SETTING_FIELDS = new Set([ "modelContextLimit", "maxContextLimit", "emergencyThresholdPercent", "nudgeGrowthTokens", "minPressureBenefitTokens", "requireUsageSampleForPressure", "maxEstimateHoldRounds", "tierNudgeTokens", "nudgeModelDecided", "nudgeDecisionMaxTokens", "requireNudge", "requireRecommendation", - "preserveRecentMessages", "preserveRecentTokens", + "preserveRecentMessages", "preserveRecentTokens", "preserveRecentTurns", "protectUserMessages", "minCompressRange", "minCompressRangeChars", "outputHeadroomMaxPct", "tiers", "protectedLatestTools", "protectedTools", "neverPreserveRecentTools", "preserveRecentTools", @@ -3286,6 +3300,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 5f98e14d3f..7a39c6c8ba 100644 --- a/src/preflight.ts +++ b/src/preflight.ts @@ -1606,6 +1606,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); +}); diff --git a/website/config-reference/compress.yaml b/website/config-reference/compress.yaml index 700ac82737..076a1104ca 100644 --- a/website/config-reference/compress.yaml +++ b/website/config-reference/compress.yaml @@ -180,6 +180,28 @@ entries: desc_ja: "最新のトークンはフォールドからソフト保護される。" 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)。" + desc_ja: "直近 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)。" + desc_ja: "全 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 4b1172324e..6999880e81 100644 --- a/website/docs/index.html +++ b/website/docs/index.html @@ -197,6 +197,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): a single range must meet it on its own; a multi-range batch passes when its COMBINED summaries reach it — one lazy paragraph no longer sinks the whole batch (#5894). 0 disables the floor. External summarizers remain held to the per-summary floor (#3635). diff --git a/website/main.js b/website/main.js index 19461eee64..287f660aea 100644 --- a/website/main.js +++ b/website/main.js @@ -77,6 +77,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): a single range must meet it on its own; a multi-range batch passes when its COMBINED summaries reach it — one lazy paragraph no longer sinks the whole batch (#5894). 0 disables the floor. External summarizers remain held to the per-summary floor (#3635).", @@ -335,6 +337,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):单段压缩按自身判定;批量压缩按各段合计判定——一段偷懒不再拖垮整批(#5894)。0 禁用下限。外部摘要模型仍受逐段下限约束(#3635)。",