From 1bc8aa7fd759e182cc10b1eb6e328a18d65887e3 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Thu, 24 Sep 2026 10:51:04 +0800 Subject: [PATCH 1/2] feat: conditionally protect acp_rule pairs by stream-derived rule liveness acp_rule moves out of ALWAYS_PROTECTED_TOOLS into collectRulePairProtection: a record pair stays protected iff its id survives an ordered walk of acp_rule tool-results (Recorded adds, Removed deletes, Cleared clears). All other acp_rule exchanges become ordinary foldable content. Fail-closed for malformed 'Recorded ' results. No-op safe without removal/clear events; zero byte change until a natural fold (billion-context#1177, owner-approved semantic change). --- src/absorb.ts | 11 +- src/ccr.ts | 14 +- src/compress.ts | 10 +- src/crush.ts | 5 +- src/index.ts | 3 + src/protected.ts | 117 ++++++++++++++- src/recommend.ts | 7 +- src/rules.ts | 9 +- src/types.ts | 8 +- tests/rule-pair-protection.test.ts | 220 +++++++++++++++++++++++++++++ tests/rules.test.ts | 7 +- 11 files changed, 390 insertions(+), 21 deletions(-) create mode 100644 tests/rule-pair-protection.test.ts diff --git a/src/absorb.ts b/src/absorb.ts index 92281d7..6b21e73 100644 --- a/src/absorb.ts +++ b/src/absorb.ts @@ -3,10 +3,13 @@ import { ACP_TOOL_NAMES, ABSORB_TOOL_NAME } from "./compress-tools.js"; import { isStoredPlaceholderText } from "./ccr.js"; import { collectLatestProtected, + collectRulePairProtection, isMessageLatestProtected, isMessageProtected, + isMessageRuleProtected, matchToolPattern, type LatestProtected, + type RulePairProtection, } from "./protected.js"; import type { AbsorbConfig, @@ -87,6 +90,7 @@ export function isAbsorbCandidate( msg: CoreMessage, config: Config, latest?: LatestProtected, + rule?: RulePairProtection, ): boolean { if (msg.contentType !== "tool-result" || !msg.toolCallId) return false; if (isStoredPlaceholderText(msg.text ?? "")) return false; @@ -94,6 +98,7 @@ export function isAbsorbCandidate( if (isAcpOrConfiguredTool(msg.toolName, cfg)) return false; if (isMessageProtected(msg, config)) return false; if (latest && isMessageLatestProtected(msg, latest)) return false; + if (rule && isMessageRuleProtected(msg, rule)) return false; for (const pattern of cfg.excludeTools) { if (msg.toolName && matchToolPattern(msg.toolName, pattern)) return false; } @@ -152,8 +157,9 @@ export function appendAbsorbPrompts( let promptedCount = 0; const latest = collectLatestProtected(messages, config); + const ruleProt = collectRulePairProtection(messages); const out = messages.map((msg) => { - if (!isAbsorbCandidate(msg, config, latest)) return msg; + if (!isAbsorbCandidate(msg, config, latest, ruleProt)) return msg; if (absorbedIds.has(msg.id)) return msg; const text = msg.text ?? ""; if (text.includes(ABSORB_PROMPT_MARKER)) return msg; @@ -305,7 +311,8 @@ export function applyAbsorb(input: AbsorbInput): AbsorbOutcome { isMessageLatestProtected( target, collectLatestProtected(input.messages, input.config), - ) + ) || + isMessageRuleProtected(target, collectRulePairProtection(input.messages)) ) { return { state: input.state, diff --git a/src/ccr.ts b/src/ccr.ts index 22c3502..aeb3db5 100644 --- a/src/ccr.ts +++ b/src/ccr.ts @@ -6,7 +6,12 @@ import type { } from "./types.js"; import { refForRaw, BLOCKED_REF } from "./refs.js"; import { ACP_TOOL_NAMES } from "./compress-tools.js"; -import { isMessageProtected, matchToolPattern } from "./protected.js"; +import { + collectRulePairProtection, + isMessageProtected, + isMessageRuleProtected, + matchToolPattern, +} from "./protected.js"; import { hasStoredRef, retrieveByRef, storeOriginal } from "./content-store.js"; import type { MessageContentStore, @@ -271,6 +276,7 @@ export function storeLargeResults( } } + const ruleProt = collectRulePairProtection(input.messages); const updated = input.messages.map((message) => { if (message.contentType !== "tool-result") return message; const text = message.text ?? ""; @@ -290,7 +296,11 @@ export function storeLargeResults( ) { return message; } - if (isMessageProtected(message, input.config)) return message; + if ( + isMessageProtected(message, input.config) || + isMessageRuleProtected(message, ruleProt) + ) + return message; const tokens = input.countTokens(text); if (tokens < cfg.minToolTokens) return message; const ref = refForRaw(input.state.messageRefs, message.id); diff --git a/src/compress.ts b/src/compress.ts index ebe383b..df0d0f7 100644 --- a/src/compress.ts +++ b/src/compress.ts @@ -26,9 +26,11 @@ import { createRenderRefsNode } from "./render-refs.js"; import type { RenderStrategy } from "./render-refs.js"; import { collectLatestProtected, + collectRulePairProtection, hasMediaPayload, isMessageLatestProtected, isMessageProtected, + isMessageRuleProtected, } from "./protected.js"; import { adjustBoundariesForToolPairs } from "./tool-pairs.js"; import { adjustBoundariesForReasoningPairs } from "./reasoning-pairs.js"; @@ -599,11 +601,15 @@ const assignRefsNode: PipelineNode = { const latest = hasProtection ? collectLatestProtected(io.messages, ctx.config) : undefined; + // Built-in conditional protection (no config gate): live acp_rule record + // pairs get a BLOCKED ref exactly like always-protected tools. + const ruleProt = collectRulePairProtection(io.messages); // Media payloads (image/file sidecars) ride outside msg.text; folding one // destroys it permanently (#1188), so media messages always get a BLOCKED // ref — never advertised, never folded — regardless of tool-protection config. const protectedFn = (m: CoreMessage) => hasMediaPayload(m) || + isMessageRuleProtected(m, ruleProt) || (hasProtection ? isMessageProtected(m, ctx.config) || (latest ? isMessageLatestProtected(m, latest) : false) @@ -1263,6 +1269,7 @@ function filterProtectedToolMessages( const removedIds = new Set(); const latest = collectLatestProtected(messages, config); for (const id of latest.callIds) protectedCallIds.add(id); + const ruleProt = collectRulePairProtection(messages); for (const msg of messages) { if (isMessageProtected(msg, config) && msg.toolCallId) { protectedCallIds.add(msg.toolCallId); @@ -1275,7 +1282,8 @@ function filterProtectedToolMessages( if ( hasMediaPayload(msg) || isMessageProtected(msg, config) || - isMessageLatestProtected(msg, latest) + isMessageLatestProtected(msg, latest) || + isMessageRuleProtected(msg, ruleProt) ) { removedIds.add(id); if (msg.toolCallId) protectedCallIds.add(msg.toolCallId); diff --git a/src/crush.ts b/src/crush.ts index 02e198e..3dfd589 100644 --- a/src/crush.ts +++ b/src/crush.ts @@ -60,7 +60,7 @@ import { isAbsorbCandidate, resolveAbsorbConfig, } from "./absorb.js"; -import { matchToolPattern } from "./protected.js"; +import { collectRulePairProtection, matchToolPattern } from "./protected.js"; import { defaultCountTokens, type TokenCountFn } from "./tokenize.js"; import type { AbsorbConfig, @@ -1798,8 +1798,9 @@ export function applyCrushToMessages( let distilledCount = 0; let changed = false; const out: CoreMessage[] = []; + const ruleProt = collectRulePairProtection(messages); for (const msg of messages) { - if (!isAbsorbCandidate(msg, config)) { + if (!isAbsorbCandidate(msg, config, undefined, ruleProt)) { out.push(msg); continue; } diff --git a/src/index.ts b/src/index.ts index efb4f39..137d8ea 100644 --- a/src/index.ts +++ b/src/index.ts @@ -346,11 +346,14 @@ export { } from "./search.js"; export { collectLatestProtected, + collectRulePairProtection, hasMediaPayload, isMessageLatestProtected, isMessageProtected, + isMessageRuleProtected, matchToolPattern, type LatestProtected, + type RulePairProtection, } from "./protected.js"; export { runPipeline, diff --git a/src/protected.ts b/src/protected.ts index 7d61e04..5439e85 100644 --- a/src/protected.ts +++ b/src/protected.ts @@ -1,13 +1,18 @@ import type { Config, CoreMessage } from "./types.js"; +import { RULE_TOOL_NAME } from "./rules.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 * carry the summaries that decompress/search rely on, and the system prompt - * treats past compress calls as load-bearing metadata. acp_rule calls record - * persistent user rules that are re-injected every turn — compressing them - * away would silently lose what the rules state. Letting any of these be - * compressed away breaks decompress and the "summary is historical" contract. */ -export const ALWAYS_PROTECTED_TOOLS = ["compress", "acp_rule"] as const; + * treats past compress calls as load-bearing metadata. Letting any of these + * be compressed away breaks decompress and the "summary is historical" + * contract. + * + * acp_rule pairs used to live here too; they moved to conditional protection + * (collectRulePairProtection below): a recorded rule's pair stays protected + * while the rule is still live, and once the host removes/clears the rule the + * pair becomes ordinary foldable content (billion-context#1177). */ +export const ALWAYS_PROTECTED_TOOLS = ["compress"] as const; /** Tool results that must NEVER participate in the soft-protected recent zone * (preserveRecentMessages / preserveRecentTokens / last user message). @@ -208,3 +213,105 @@ export function hasMediaPayload(msg: CoreMessage): boolean { function isObjWith(v: unknown, key: string, value: unknown): boolean { return typeof v === "object" && v !== null && (v as Record)[key] === value; } + +/** Result-text prefixes emitted by host acp_rule executors (billion-context's + * executeRule is the reference implementation): successful record / removal / + * full-clear. They form a closed partition of liveness events — no other + * executor outcome starts with them (listings start with a digit or "No", + * errors with lowercase words). */ +const RULE_RECORD_RESULT_RE = /^Recorded (rule\d+): /; +const RULE_REMOVE_RESULT_RE = /^Removed (rule\d+): /; +const RULE_CLEAR_RESULT_RE = /^Cleared \d+ rule\(s\)\./; + +export interface RulePairProtection { + /** toolCallIds whose still-live record pair (call AND result) stays protected. */ + callIds: Set; + /** Message ids of protected halves lacking a pairable toolCallId, plus + * fail-closed malformed record results. */ + msgIds: Set; +} + +/** + * Conditional protection for acp_rule pairs, derived from the visible message + * stream itself — no state dependency, because plugin-mode hosts fold in their + * own kernel copy, which never sees the server-side rules table, while the + * message stream is identical in both modes (billion-context#1177). + * + * Liveness walk over acp_rule tool-results in message order: `Recorded ruleN:` + * adds N, `Removed ruleN:` removes N, `Cleared k rule(s).` clears all. A + * record pair is protected iff its id survives the walk (ids are never + * re-issued, so final-set membership equals per-event liveness). Every other + * acp_rule exchange — removals, clears, listings, failures — is ordinary + * compressible content: they are event traces, not persistent reminders, and + * pinning them forever would recreate the accumulation problem the feature + * exists to fix. + * + * Fail-closed: a result starting `Recorded ` with an unparseable id keeps its + * pair protected (format drift must never silently fold a live rule). Without + * any removal/clear events the walk protects every record pair — behaviorally + * identical to the old unconditional name-based protection, so this change is + * a no-op until hosts actually delete rules. + */ +export function collectRulePairProtection( + messages: CoreMessage[], +): RulePairProtection { + const callNameById = new Map(); + for (const m of messages) { + if (m.contentType === "tool-call" && m.toolCallId && m.toolName) { + callNameById.set(m.toolCallId, m.toolName); + } + } + const isRuleResult = (m: CoreMessage): boolean => + m.contentType === "tool-result" && + (m.toolName === RULE_TOOL_NAME || + (m.toolCallId != null && + callNameById.get(m.toolCallId) === RULE_TOOL_NAME)); + + const live = new Set(); + const malformedMsgIds = new Set(); + const callIds = new Set(); + for (const m of messages) { + if (!isRuleResult(m)) continue; + const text = m.text ?? ""; + const removedId = RULE_REMOVE_RESULT_RE.exec(text)?.[1]; + if (removedId !== undefined) { + live.delete(removedId); + continue; + } + if (RULE_CLEAR_RESULT_RE.test(text)) { + live.clear(); + continue; + } + const recordedId = RULE_RECORD_RESULT_RE.exec(text)?.[1]; + if (recordedId !== undefined) { + live.add(recordedId); + } else if (text.startsWith("Recorded ")) { + malformedMsgIds.add(m.id); + if (m.toolCallId) callIds.add(m.toolCallId); + } + } + + const msgIds = new Set(malformedMsgIds); + for (const m of messages) { + if (!isRuleResult(m)) continue; + const recordedId = RULE_RECORD_RESULT_RE.exec(m.text ?? "")?.[1]; + if (recordedId === undefined || !live.has(recordedId)) continue; + if (m.toolCallId) callIds.add(m.toolCallId); + else msgIds.add(m.id); + } + return { callIds, msgIds }; +} + +/** True when msg is half of a still-live record pair per + * collectRulePairProtection (both halves share the pair's toolCallId), or a + * fail-closed malformed record result. */ +export function isMessageRuleProtected( + msg: CoreMessage, + protection: RulePairProtection, +): boolean { + if (msg.contentType !== "tool-call" && msg.contentType !== "tool-result") { + return false; + } + if (protection.msgIds.has(msg.id)) return true; + return msg.toolCallId != null && protection.callIds.has(msg.toolCallId); +} diff --git a/src/recommend.ts b/src/recommend.ts index 57a100b..b0deb4f 100644 --- a/src/recommend.ts +++ b/src/recommend.ts @@ -23,9 +23,11 @@ import type { CompressionState } from "./types.js"; import { collectLatestProtected, collectProtectedToolCallIds, + collectRulePairProtection, hasMediaPayload, isMessageLatestProtected, isMessageProtectedWithPairing, + isMessageRuleProtected, isNeverPreserveRecent, } from "./protected.js"; import { countMessageTokens } from "./tokenize.js"; @@ -177,6 +179,8 @@ export function buildCompressibleRanges( // matches tool-results). const latest = collectLatestProtected(messages, config); for (const id of latest.callIds) protectedCallIds.add(id); + // acp_rule record pairs: conditional protection derived from the stream. + const ruleProt = collectRulePairProtection(messages); // Segmentation is array adjacency, never ref arithmetic: surface-replacing // hosts leave holes in the ref map (compressed messages leave the array, refs @@ -209,7 +213,8 @@ export function buildCompressibleRanges( if ( isMessageProtectedWithPairing(msg, config, protectedCallIds) || - isMessageLatestProtected(msg, latest) + isMessageLatestProtected(msg, latest) || + isMessageRuleProtected(msg, ruleProt) ) { protectedMsgs.push({ ref, diff --git a/src/rules.ts b/src/rules.ts index 3581169..6afb910 100644 --- a/src/rules.ts +++ b/src/rules.ts @@ -3,9 +3,12 @@ import type { CompressionState, Config, RuleRecord } from "./types.js"; /** * Persistent rules ("acp_rule") — durable reminders recorded for future turns * (kernel #282, from billion-context-pi#433). The adapter injects - * formatRulesForPrompt(state) into the system prompt every turn, and acp_rule - * tool calls/results are hard-protected from compression - * (ALWAYS_PROTECTED_TOOLS), so a recorded rule survives context compaction. + * formatRulesForPrompt(state) into the system prompt every turn. A recorded + * rule's call/result pair stays protected from compression while the rule is + * live — protection is derived from the message stream itself + * (collectRulePairProtection in protected.ts), and once the host removes or + * clears the rule the pair becomes ordinary foldable content + * (billion-context#1177). * * State-mutating helpers: hosts hold live CompressionState objects (a session's * single state instance) and discard returned states — these helpers update diff --git a/src/types.ts b/src/types.ts index 4b577e6..7d6d1dc 100644 --- a/src/types.ts +++ b/src/types.ts @@ -150,8 +150,9 @@ export interface TerminalEscapeSignal { } /** A persistent reminder recorded via the acp_rule tool (see rules.ts). - * Injected into the system prompt every turn by the adapter and hard-protected - * from compression. Ids are never re-issued (see nextRuleId). */ + * Injected into the system prompt every turn by the adapter; its record pair + * stays protected from compression while the rule is live (collectRulePairProtection). + * Ids are never re-issued (see nextRuleId). */ export interface RuleRecord { id: string; text: string; @@ -159,7 +160,8 @@ export interface RuleRecord { /** Persistent-rule ("acp_rule") feature settings (see rules.ts). Absent or * enabled !== true = feature off — the adapter never injects the tool; kernel - * protection is unconditional but side-effect-free without acp_rule messages. + * pair-protection is stream-derived and side-effect-free without acp_rule + * messages (live record pairs protected, other exchanges foldable). * Deviates from kernel#282's original "no Config field" stance: hosts gate the * feature and carry their limit overrides through the resolved Config * (billion-context#750 reads config.rules.enabled + resolveRuleLimits). */ diff --git a/tests/rule-pair-protection.test.ts b/tests/rule-pair-protection.test.ts new file mode 100644 index 0000000..1b27f0e --- /dev/null +++ b/tests/rule-pair-protection.test.ts @@ -0,0 +1,220 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { + collectRulePairProtection, + isMessageRuleProtected, +} from "../src/protected.js"; +import { assignRefs, emptyRefMap } from "../src/refs.js"; +import { buildCompressibleRanges } from "../src/recommend.js"; +import { createInitialState } from "../src/state.js"; +import { defaultConfig } from "../src/config.js"; +import type { Config, CoreMessage } from "../src/types.js"; + +function textMsg(id: string, text: string): CoreMessage { + return { id, role: "user", contentType: "text", text }; +} + +function ruleCall(id: string, callId: string): CoreMessage { + return { + id, + role: "assistant", + contentType: "tool-call", + toolName: "acp_rule", + toolCallId: callId, + text: '{"rule":"always run tests before pushing"}', + }; +} + +// Realistic projection: results carry toolCallId but often no toolName. +function ruleResult(id: string, callId: string, text: string): CoreMessage { + return { + id, + role: "tool", + contentType: "tool-result", + toolCallId: callId, + text, + }; +} + +function cfg(overrides: Partial = {}): Config { + return defaultConfig(200000, { + compress: { minCompressRange: 0, maxSummaryLength: 0, minSummaryLength: 0 }, + preserveRecentMessages: 0, + preserveRecentTokens: 0, + ...overrides, + }); +} + +function rangesFor(messages: CoreMessage[], overrides?: Partial) { + const state = createInitialState(); + state.messageRefs = assignRefs(messages, { + existing: emptyRefMap(), + nextIndex: 1, + }).map; + return buildCompressibleRanges(messages, state, cfg(overrides)); +} + +function refNum(ref: string): number { + return Number(ref.replace(/^m/, "")); +} + +function compressibleRefSet(ranges: ReturnType): Set { + const out = new Set(); + for (const r of ranges.compressible) { + for (let n = refNum(r.startRef); n <= refNum(r.endRef); n++) out.add(n); + } + return out; +} + +test("live record pair stays protected", () => { + const c1 = ruleCall("c1", "rec-1"); + const r1 = ruleResult("r1", "rec-1", "Recorded rule1: keep cache warm"); + const prot = collectRulePairProtection([textMsg("u1", "hi"), c1, r1]); + assert.ok(prot.callIds.has("rec-1")); + assert.ok(isMessageRuleProtected(c1, prot)); + assert.ok(isMessageRuleProtected(r1, prot)); + assert.ok(!isMessageRuleProtected(textMsg("u1", "hi"), prot)); +}); + +test("removed rule pair becomes unprotected, delete trace too", () => { + const c1 = ruleCall("c1", "rec-1"); + const r1 = ruleResult("r1", "rec-1", "Recorded rule1: old model pin"); + const c2 = ruleCall("c2", "del-1"); + const r2 = ruleResult("r2", "del-1", "Removed rule1: old model pin"); + const prot = collectRulePairProtection([c1, r1, c2, r2]); + assert.equal(prot.callIds.size, 0); + assert.equal(prot.msgIds.size, 0); + for (const m of [c1, r1, c2, r2]) assert.ok(!isMessageRuleProtected(m, prot)); +}); + +test("clear wipes all record protection", () => { + const c1 = ruleCall("c1", "rec-1"); + const r1 = ruleResult("r1", "rec-1", "Recorded rule1: a"); + const c2 = ruleCall("c2", "rec-2"); + const r2 = ruleResult("r2", "rec-2", "Recorded rule2: b"); + const c3 = ruleCall("c3", "clr-1"); + const r3 = ruleResult("r3", "clr-1", "Cleared 2 rule(s)."); + const prot = collectRulePairProtection([c1, r1, c2, r2, c3, r3]); + assert.equal(prot.callIds.size, 0); + assert.ok(!isMessageRuleProtected(c1, prot)); + assert.ok(!isMessageRuleProtected(r2, prot)); +}); + +test("re-record after removal protects only the new id", () => { + const c1 = ruleCall("c1", "rec-1"); + const r1 = ruleResult("r1", "rec-1", "Recorded rule1: v1"); + const c2 = ruleCall("c2", "del-1"); + const r2 = ruleResult("r2", "del-1", "Removed rule1: v1"); + const c3 = ruleCall("c3", "rec-2"); + const r3 = ruleResult("r3", "rec-2", "Recorded rule2: v2"); + const prot = collectRulePairProtection([c1, r1, c2, r2, c3, r3]); + assert.deepEqual([...prot.callIds], ["rec-2"]); + assert.ok(!isMessageRuleProtected(r1, prot)); + assert.ok(isMessageRuleProtected(c3, prot)); + assert.ok(isMessageRuleProtected(r3, prot)); +}); + +test("malformed Recorded result fails closed on both halves", () => { + const c1 = ruleCall("c1", "rec-x"); + const r1 = ruleResult("r1", "rec-x", "Recorded ruleX: drifted format"); + const prot = collectRulePairProtection([c1, r1]); + assert.ok(isMessageRuleProtected(c1, prot)); + assert.ok(isMessageRuleProtected(r1, prot)); +}); + +test("listings and errors neither add nor remove liveness", () => { + const c1 = ruleCall("c1", "rec-1"); + const r1 = ruleResult("r1", "rec-1", "Recorded rule1: a"); + const c2 = ruleCall("c2", "lst-1"); + const r2 = ruleResult("c2r", "lst-1", "1. [rule1] a"); + const c3 = ruleCall("c3", "err-1"); + const r3 = ruleResult( + "r3", + "err-1", + 'no rule with id "rule9" — list current rules first (omit the text argument).', + ); + const prot = collectRulePairProtection([c1, r1, c2, r2, c3, r3]); + assert.deepEqual([...prot.callIds], ["rec-1"]); + assert.ok(!isMessageRuleProtected(r2, prot)); + assert.ok(!isMessageRuleProtected(r3, prot)); +}); + +test("result without toolName pairs via the call-side name", () => { + const c1 = ruleCall("c1", "rec-1"); + const r1 = ruleResult("r1", "rec-1", "Recorded rule1: a"); + assert.equal(r1.toolName, undefined); + const prot = collectRulePairProtection([c1, r1]); + assert.ok(prot.callIds.has("rec-1")); +}); + +test("result with explicit toolName also matches", () => { + const c1 = ruleCall("c1", "rec-1"); + const r1: CoreMessage = { + ...ruleResult("r1", "rec-1", "Recorded rule1: a"), + toolName: "acp_rule", + }; + const prot = collectRulePairProtection([c1, r1]); + assert.ok(prot.callIds.has("rec-1")); +}); + +test("no acp_rule messages at all yields empty protection", () => { + const prot = collectRulePairProtection([ + textMsg("u1", "hello"), + { + id: "b1", + role: "assistant", + contentType: "tool-call", + toolName: "bash", + toolCallId: "bc-1", + text: "ls", + }, + ]); + assert.equal(prot.callIds.size, 0); + assert.equal(prot.msgIds.size, 0); +}); + +test("gate: live pair excluded from compressible ranges, dead pair included", () => { + const messages: CoreMessage[] = [ + textMsg("u1", "work filler one"), + ruleCall("c1", "rec-1"), + ruleResult("r1", "rec-1", "Recorded rule1: keep cache warm"), + textMsg("u2", "work filler two"), + ruleCall("c2", "rec-2"), + ruleResult("r2", "rec-2", "Recorded rule2: old model pin"), + textMsg("u3", "work filler three"), + ruleCall("c3", "del-1"), + ruleResult("r3", "del-1", "Removed rule2: old model pin"), + textMsg("u4", "work filler four"), + ]; + const ranges = rangesFor(messages); + assert.equal(ranges.protected.length, 1); + assert.deepEqual(ranges.protected[0].tools, ["acp_rule"]); + assert.equal(ranges.protected[0].startRef, "m00002"); + assert.equal(ranges.protected[0].endRef, "m00003"); + const compressible = compressibleRefSet(ranges); + assert.ok(!compressible.has(2), "live call must not be compressible"); + assert.ok(!compressible.has(3), "live result must not be compressible"); + for (const n of [1, 4, 5, 6, 7, 8, 9, 10]) { + assert.ok( + compressible.has(n), + `ref m${String(n).padStart(5, "0")} compressible`, + ); + } +}); + +test("no-op safety: record-only history keeps every pair protected", () => { + const messages: CoreMessage[] = [ + textMsg("u1", "work filler one"), + ruleCall("c1", "rec-1"), + ruleResult("r1", "rec-1", "Recorded rule1: a"), + textMsg("u2", "work filler two"), + ruleCall("c2", "rec-2"), + ruleResult("r2", "rec-2", "Recorded rule2: b"), + textMsg("u3", "work filler three"), + ]; + const ranges = rangesFor(messages); + const compressible = compressibleRefSet(ranges); + for (const n of [2, 3, 5, 6]) assert.ok(!compressible.has(n)); + const protectedTools = ranges.protected.flatMap((r) => r.tools); + assert.ok(protectedTools.includes("acp_rule")); +}); diff --git a/tests/rules.test.ts b/tests/rules.test.ts index 75e020c..afb1e1e 100644 --- a/tests/rules.test.ts +++ b/tests/rules.test.ts @@ -67,9 +67,12 @@ function cfg(overrides: Partial = {}): Config { }); } -test("RULE_TOOL_NAME and ALWAYS_PROTECTED_TOOLS expose acp_rule", () => { +test("ALWAYS_PROTECTED_TOOLS keeps only compress; acp_rule is conditionally protected", () => { assert.equal(RULE_TOOL_NAME, "acp_rule"); - assert.ok((ALWAYS_PROTECTED_TOOLS as readonly string[]).includes("acp_rule")); + assert.ok((ALWAYS_PROTECTED_TOOLS as readonly string[]).includes("compress")); + assert.ok( + !(ALWAYS_PROTECTED_TOOLS as readonly string[]).includes("acp_rule"), + ); }); test("addRule mutates state in place and issues rule1 first", () => { From 2f1e50ae6654c3977fdef4f327e4039b03a10bdc Mon Sep 17 00:00:00 2001 From: ework-agent Date: Thu, 24 Sep 2026 11:18:06 +0800 Subject: [PATCH 2/2] test(rule-protection): pin CCR skip-store and absorb refusal guards (#378) --- tests/rule-pair-protection.test.ts | 86 +++++++++++++++++++++++++++++- 1 file changed, 85 insertions(+), 1 deletion(-) diff --git a/tests/rule-pair-protection.test.ts b/tests/rule-pair-protection.test.ts index 1b27f0e..fb99834 100644 --- a/tests/rule-pair-protection.test.ts +++ b/tests/rule-pair-protection.test.ts @@ -4,10 +4,17 @@ import { collectRulePairProtection, isMessageRuleProtected, } from "../src/protected.js"; -import { assignRefs, emptyRefMap } from "../src/refs.js"; +import { assignRefs, emptyRefMap, refForRaw } from "../src/refs.js"; import { buildCompressibleRanges } from "../src/recommend.js"; import { createInitialState } from "../src/state.js"; import { defaultConfig } from "../src/config.js"; +import { applyAbsorb } from "../src/absorb.js"; +import { + DEFAULT_CCR_CONFIG, + isStoredPlaceholderText, + storeLargeResults, +} from "../src/ccr.js"; +import { createContentStore } from "../src/content-store.js"; import type { Config, CoreMessage } from "../src/types.js"; function textMsg(id: string, text: string): CoreMessage { @@ -218,3 +225,80 @@ test("no-op safety: record-only history keeps every pair protected", () => { const protectedTools = ranges.protected.flatMap((r) => r.tools); assert.ok(protectedTools.includes("acp_rule")); }); + +const countTokens = (text: string) => Math.ceil(text.length / 4); + +function stateWithRefs(messages: CoreMessage[]) { + const state = createInitialState(); + state.messageRefs = assignRefs(messages, { + existing: emptyRefMap(), + nextIndex: 1, + }).map; + return state; +} + +test("CCR: live record result stays inline, dead pair is stored", () => { + const messages: CoreMessage[] = [ + ruleCall("c1", "rec-1"), + ruleResult("r1", "rec-1", "Recorded rule1: keep cache warm"), + ruleCall("c2", "rec-2"), + ruleResult("r2", "rec-2", "Recorded rule2: old model pin"), + ruleCall("c3", "del-1"), + ruleResult("r3", "del-1", "Removed rule2: old model pin"), + ]; + const config = cfg({ + ccr: { ...DEFAULT_CCR_CONFIG, enabled: true, minToolTokens: 1 }, + }); + const out = storeLargeResults({ + messages, + state: stateWithRefs(messages), + store: createContentStore(), + config, + countTokens, + }); + assert.equal(out.messages[1]?.text, "Recorded rule1: keep cache warm"); + assert.ok(isStoredPlaceholderText(out.messages[3]?.text ?? "")); + assert.ok(isStoredPlaceholderText(out.messages[5]?.text ?? "")); + assert.equal(out.storedCount, 2); +}); + +test("absorb: live record result refused, dead record result proceeds", () => { + const messages: CoreMessage[] = [ + textMsg("u1", "work filler one"), + ruleCall("c1", "rec-1"), + ruleResult("r1", "rec-1", "Recorded rule1: keep cache warm"), + ruleCall("c2", "rec-2"), + ruleResult("r2", "rec-2", "Recorded rule2: old model pin"), + ruleCall("c3", "del-1"), + ruleResult("r3", "del-1", "Removed rule2: old model pin"), + ]; + const state = stateWithRefs(messages); + const config = cfg({ + absorb: { + enabled: true, + toolName: "absorb", + minToolTokens: 0, + contextThresholdPct: 0, + excludeTools: [], + }, + }); + const live = applyAbsorb({ + ref: refForRaw(state.messageRefs, "r1")!, + summary: "rule recorded", + messages, + state, + config, + }); + assert.ok(!live.ok); + assert.match(live.resultText, /protected tool/); + const dead = applyAbsorb({ + ref: refForRaw(state.messageRefs, "r2")!, + summary: "old model pin rule, since removed", + messages, + state, + config, + }); + assert.ok(dead.ok, dead.resultText); + assert.equal(dead.state.absorbed!.length, 1); + assert.equal(dead.state.absorbed![0]!.resultMessageId, "r2"); +});