From 9353f7a387f6e743d0d3134cfea1408a87381ace Mon Sep 17 00:00:00 2001 From: awork Date: Thu, 8 Oct 2026 23:17:51 +0800 Subject: [PATCH 1/6] kernel: add Config.isMessageProtected message-level protection hook (#2419) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Host-declared predicate hard-protects ANY message (every content type) from compression: BLOCKED ref in assignRefs (never advertised, never foldable-by-ref) and exclusion from effectiveMessageIds in applyCompression (stays fully visible, summary reflects only what was actually folded). Unset = byte-identical behavior (only tool exchanges and media payloads were protectable before). Needed because hosts can inject DURABLE STATE as ordinary conversation messages — dsh's skill catalog, which DSH fingerprint-gates and never resends while unchanged, so folding it loses skill visibility permanently (#2419). The existing protectedTools/isToolProtected surface is tool-exchange-only by design and cannot express this. Version bump 0.0.107 -> 0.0.108 (CI-enforced for kernel/src changes). Tests: kernel/tests/message-protection.test.ts (6 cases incl. upgrade path and entire-range veto). --- kernel/src/compress.ts | 1 + kernel/src/protected.ts | 6 +- kernel/src/types.ts | 15 ++ kernel/tests/message-protection.test.ts | 224 ++++++++++++++++++++++++ 4 files changed, 245 insertions(+), 1 deletion(-) create mode 100644 kernel/tests/message-protection.test.ts diff --git a/kernel/src/compress.ts b/kernel/src/compress.ts index c7875397ba..f55fea3fc5 100644 --- a/kernel/src/compress.ts +++ b/kernel/src/compress.ts @@ -896,6 +896,7 @@ const assignRefsNode: PipelineNode = { const hasProtection = ctx.config.protectedTools.length > 0 || !!ctx.config.isToolProtected || + !!ctx.config.isMessageProtected || (ctx.config.protectedLatestTools?.length ?? 0) > 0; const latest = hasProtection ? collectLatestProtected(io.messages, ctx.config) diff --git a/kernel/src/protected.ts b/kernel/src/protected.ts index c588440757..051ea841dc 100644 --- a/kernel/src/protected.ts +++ b/kernel/src/protected.ts @@ -182,8 +182,12 @@ export function matchToolMessagePattern( export function isMessageProtected( msg: CoreMessage, - config: Pick, + config: Pick, ): 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; + // tool-result carries the same toolName as its tool-call (the host projects // it), so checking toolName covers both sides of a tool exchange. if ( diff --git a/kernel/src/types.ts b/kernel/src/types.ts index f47f842c88..db64d74f22 100644 --- a/kernel/src/types.ts +++ b/kernel/src/types.ts @@ -388,6 +388,21 @@ export interface Config { compress: CompressValidationConfig; protectedTools: string[]; isToolProtected?: (toolName: string, toolInputText?: string) => boolean; + /** Host-declared message-level hard protection (billion-context#2419): + * when set, ANY message for which the predicate returns true is excluded + * from compression exactly like a protectedTools hit — BLOCKED ref in + * assignRefs (never advertised, never foldable-by-ref) AND dropped from + * effectiveMessageIds in applyCompression (stays fully visible; the + * summary reflects only what was actually folded). Applies to every + * content type; the tool-exchange checks below run additionally, not + * instead. Use for host-injected DURABLE STATE carried as ordinary + * conversation messages — e.g. dsh's skill catalog, which DSH + * fingerprint-gates (sha256 over name+description) and never resends + * while unchanged, so folding it loses skill visibility permanently. + * Unset = byte-identical behavior to before (only tool exchanges and + * media payloads are protectable). Must be pure and cheap: it runs once + * per message per turn. */ + isMessageProtected?: (msg: CoreMessage) => boolean; /** Tool-name patterns (glob suffix allowed) protected in their LATEST * instance only: the newest matching tool-call and its paired tool-result * are protected from compression; older instances remain compressible. For diff --git a/kernel/tests/message-protection.test.ts b/kernel/tests/message-protection.test.ts new file mode 100644 index 0000000000..ad039b2f66 --- /dev/null +++ b/kernel/tests/message-protection.test.ts @@ -0,0 +1,224 @@ +// #2419: host-declared message-level hard protection (Config.isMessageProtected). +// The dsh skill catalog rides as an ordinary user-role text message and DSH +// never resends it while its fingerprint is unchanged — folding it loses skill +// visibility permanently. These tests pin the generic mechanism: any message +// matching the host predicate is excluded from compression exactly like a +// protectedTools hit, for every content type, in both the assignRefs path +// (BLOCKED ref — never advertised) and the applyCompression path (excluded +// from effectiveMessageIds — stays visible). +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, BLOCKED_REF } from "../src/refs.js"; +import { defaultConfig } from "../src/config.js"; +import type { Config, CoreMessage } from "../src/types.js"; + +const CATALOG_MARKER = "\x3cavailable_skills\x3e"; + +function msg( + id: string, + text: string, + role: CoreMessage["role"] = "user", +): CoreMessage { + return { id, role, contentType: "text", text }; +} + +function setupRefs(messages: CoreMessage[]) { + const state = createInitialState(); + state.messageRefs = assignRefs(messages, { + existing: state.messageRefs, + nextIndex: 1, + }).map; + return state; +} + +const longText = "x".repeat(6000); +const catalogText = `\x3csystem-reminder\x3e ${CATALOG_MARKER} skill-a: does A; skill-b: does B \x3c/system-reminder\x3e`; +const validSummary = + "A meaningful summary that captures the key information of the compressed range including file paths and decisions."; + +function cfg(overrides: Partial = {}): Config { + return defaultConfig(200000, { + compress: { minCompressRange: 0, maxSummaryLength: 0, minSummaryLength: 0 }, + preserveRecentMessages: 0, + preserveRecentTokens: 0, + ...overrides, + }); +} + +const catalogGuard = (m: CoreMessage) => + m.contentType === "text" && m.text?.includes(CATALOG_MARKER) === true; + +test("isMessageProtected: predicate-protected user text message is excluded from the range", () => { + const core = createCore(); + const messages = [ + msg("a", longText), + msg("catalog", catalogText), + msg("d", longText), + ]; + const state = setupRefs(messages); + const config = cfg({ isMessageProtected: catalogGuard }); + + const result = core.applyCompression({ + ranges: [{ startRef: "m00001", endRef: "m00003", summary: validSummary }], + messages, + state, + config, + }); + + assert.equal(result.result.blocksCreated, 1); + assert.equal(result.result.errors.length, 0); + + const block = result.state.blocks[0]!; + assert.ok( + !block.directMessageIds.includes("catalog"), + "catalog must be excluded from the compressed set", + ); + assert.ok( + !block.effectiveMessageIds.includes("catalog"), + "catalog must be excluded from effective coverage (stays visible)", + ); + assert.ok(block.directMessageIds.includes("a"), "regular msg 'a' folded"); + assert.ok(block.directMessageIds.includes("d"), "regular msg 'd' folded"); + assert.equal( + block.summary, + validSummary, + "summary is exactly what the author wrote — no protected content appended", + ); +}); + +test("isMessageProtected: applies to every content type, not just user text", () => { + const core = createCore(); + const messages = [ + msg("a", longText), + msg("assistant-catalog", catalogText, "assistant"), + msg("d", longText), + ]; + const state = setupRefs(messages); + const config = cfg({ isMessageProtected: catalogGuard }); + + const result = core.applyCompression({ + ranges: [{ startRef: "m00001", endRef: "m00003", summary: validSummary }], + messages, + state, + config, + }); + + const block = result.state.blocks[0]!; + assert.ok( + !block.effectiveMessageIds.includes("assistant-catalog"), + "assistant-role message matching the predicate is protected too", + ); + assert.ok(block.effectiveMessageIds.includes("a"), "msg 'a' folded"); + assert.ok(block.effectiveMessageIds.includes("d"), "msg 'd' folded"); +}); + +test("isMessageProtected: without the predicate the same message folds normally", () => { + const core = createCore(); + const messages = [ + msg("a", longText), + msg("catalog", catalogText), + msg("d", longText), + ]; + const state = setupRefs(messages); + const config = cfg(); // no isMessageProtected + + const result = core.applyCompression({ + ranges: [{ startRef: "m00001", endRef: "m00003", summary: validSummary }], + messages, + state, + config, + }); + + const block = result.state.blocks[0]!; + assert.ok( + block.effectiveMessageIds.includes("catalog"), + "unset predicate = byte-identical behavior: catalog folds like any other message", + ); +}); + +test("isMessageProtected: predicate-protected message gets a BLOCKED ref via processTurn (never advertised)", () => { + const core = createCore(); + const messages = [ + msg("a", longText), + msg("catalog", catalogText), + msg("d", longText), + ]; + const state = createInitialState(); + const config = cfg({ isMessageProtected: catalogGuard }); + + const turn = core.processTurn({ + messages, + state, + config, + tokenCount: 1000, + }); + + assert.equal( + turn.state.messageRefs.byRaw["catalog"], + BLOCKED_REF, + "protected message must carry the BLOCKED ref (no mNNNNN allocated)", + ); + assert.notEqual( + turn.state.messageRefs.byRaw["a"], + BLOCKED_REF, + "unprotected message keeps a normal ref", + ); + assert.notEqual( + turn.state.messageRefs.byRaw["d"], + BLOCKED_REF, + "unprotected message keeps a normal ref", + ); +}); + +test("isMessageProtected: legacy refs assigned before protection still cannot be folded (upgrade path)", () => { + const core = createCore(); + const messages = [ + msg("a", longText), + msg("catalog", catalogText), + msg("d", longText), + ]; + // Simulates a session whose state predates the guard: refs were assigned + // with NO protection, so the catalog holds a live m-ref. + const state = setupRefs(messages); + assert.notEqual(state.messageRefs.byRaw["catalog"], BLOCKED_REF); + const config = cfg({ isMessageProtected: catalogGuard }); + + const result = core.applyCompression({ + ranges: [{ startRef: "m00001", endRef: "m00003", summary: validSummary }], + messages, + state, + config, + }); + + const block = result.state.blocks[0]!; + assert.ok( + !block.effectiveMessageIds.includes("catalog"), + "pre-existing ref does not make the message foldable once protected", + ); + assert.ok(block.effectiveMessageIds.includes("a"), "msg 'a' folded"); + assert.ok(block.effectiveMessageIds.includes("d"), "msg 'd' folded"); +}); + +test("isMessageProtected: range consisting solely of protected messages fails with a clear error", () => { + const core = createCore(); + const messages = [msg("catalog", catalogText)]; + const state = setupRefs(messages); + const config = cfg({ isMessageProtected: catalogGuard }); + + const result = core.applyCompression({ + ranges: [{ startRef: "m00001", endRef: "m00001", summary: validSummary }], + messages, + state, + config, + }); + + assert.equal(result.result.blocksCreated, 0, "nothing may be created"); + assert.equal(result.result.errors.length, 1); + assert.match( + result.result.errors[0]!, + /no compressible messages/, + "an entirely-protected range must fail loudly, not fake-compress", + ); +}); From c0584374cd72349e270c0047782741c61c946eb7 Mon Sep 17 00:00:00 2001 From: awork Date: Thu, 8 Oct 2026 23:17:51 +0800 Subject: [PATCH 2/6] =?UTF-8?q?feat:=20per-lane=20durable-message=20guards?= =?UTF-8?q?=20=E2=80=94=20dsh=20skill=20catalog=20survives=20ACP=20folds?= =?UTF-8?q?=20(#2419)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit src/durable-message-guards.ts: registry keyed by plugin-agent name; only dsh is registered (KDD #9 evidence-permitlist discipline — the predicate matches the marker on text messages, matched alone so wrapper wording changes cannot disarm it). server.ts: attaches the guard to reqConfig immediately before storeEffectiveConfig so this turn's processTurn AND the stamped effective config (read by /__bili/plugin/tool) carry it. Lanes absent from the registry are byte-identical. Behavior change (dsh lane only): the skill catalog message can no longer be folded away by ACP compression — it stays fully visible. Unregistered lanes fold it exactly as before (pinned by the control test). See #2419 for the full chain of evidence. --- src/durable-message-guards.ts | 41 ++++ src/server/handle.ts | 7 + tests/issue2419-dsh-skill-catalog.test.ts | 231 ++++++++++++++++++++++ 3 files changed, 279 insertions(+) create mode 100644 src/durable-message-guards.ts create mode 100644 tests/issue2419-dsh-skill-catalog.test.ts diff --git a/src/durable-message-guards.ts b/src/durable-message-guards.ts new file mode 100644 index 0000000000..cca3c79e7f --- /dev/null +++ b/src/durable-message-guards.ts @@ -0,0 +1,41 @@ +// #2419: durable-state message guards, declared per plugin lane. +// +// Some hosts inject DURABLE STATE as ordinary conversation messages and gate +// re-injection on a content fingerprint: dsh-tool-skill ships its skill +// catalog (\x3cavailable_skills\x3e) as a user-role system-reminder once per +// session and never resends it while the sha256(name+description) digest is +// unchanged. ACP compression treats every history message as consumable, so +// one fold of the catalog silently kills skill triggering forever (the host +// will not resend what it believes is already present). The kernel's +// protection surface was tool-exchange-only (protectedTools / isToolProtected), +// structurally unable to cover a plain text message — hence the generic +// Config.isMessageProtected hook (kernel 0.0.108) and this lane-scoped policy +// map. The mechanism lives in the kernel; the POLICY (which shapes, for which +// host) lives here, one entry per lane with traffic evidence. +// +// KDD #9 evidence-permitlist discipline applies: entries are added PER HOST +// with traffic evidence (shape + stability proof), never enabled wholesale — +// a message-shape guard applied to every lane would hard-pin arbitrary user +// prose into context for hosts whose state carriers have no such contract. + +import type { CoreMessage } from "acp-kernel"; + +export type DurableMessageGuard = (msg: CoreMessage) => boolean; + +/** dsh skill-catalog guard (#2419): matches the durable catalog message + * injected by dsh-tool-skill (a \x3csystem-reminder\x3e carrying the + * \x3cavailable_skills\x3e block; source: asar dsh-tool-skill/lib/index.js, + * createUserMessage({ source: { kind: "skill-catalog" } })). The marker is + * matched on its own rather than on the wrapper so a future wrapper change + * cannot silently disarm the guard; a false positive is benign (a matching + * message simply stays visible) and the marker is DSH-specific XML. */ +export function dshSkillCatalogGuard(msg: CoreMessage): boolean { + return msg.contentType === "text" && typeof msg.text === "string" && msg.text.includes("\x3cavailable_skills\x3e"); +} + +/** Lane → guard registry. Only lanes with traffic evidence of the + * durable-user-message carrier belong here (KDD #9). Keyed by the value of + * the x-bili-plugin header / session.metadata.pluginAgent binding. */ +export const durableMessageGuards: Record = { + dsh: dshSkillCatalogGuard, +}; diff --git a/src/server/handle.ts b/src/server/handle.ts index e3abafef6c..89f10eac9a 100644 --- a/src/server/handle.ts +++ b/src/server/handle.ts @@ -14,6 +14,7 @@ import { codexAlignedWindow } from "../codex-models.js"; import { MAX_REQUEST_BYTES } from "../fetch-util.js"; import { hostIdForLog, maskHeadersForLog, maskUrlForLog, maskUrlsInText } from "../log-mask.js"; import { buildIncomingImageIndex, foldAnchoredCutoff, pruneRetrieveImgExports } from "../image-restore.js"; +import { durableMessageGuards } from "../durable-message-guards.js"; import { biliToolsDeclaredOnWire, countBiliToolUses, evaluateSelfHealRound, nudgeSuppressed, pluginLaneDegraded, pluginLaneRestore } from "../session-self-heal.js"; import { compressBreakerArmed } from "../stream.js"; import { acquireInFlight, getSession, hasProcessedState, markDirty, peekSession, releaseInFlight, storeEffectiveConfig, tickPostRebuildAnchor, withSessionLock, type Session } from "../session.js"; @@ -1722,6 +1723,12 @@ export async function handle( // same instant as effectiveContextLimit above) so request-context-free // display paths (/__bili/plugin/status Nudge line, plugin tool API) // render from the values the kernel actually used this turn. + // #2419: per-lane durable-state message guard — attach BEFORE stamping + // so both this turn's processTurn(reqConfig) and the stamped effective + // config (read by /__bili/plugin/tool) carry it. Only lanes present in + // the registry are affected; an absent predicate is byte-identical. + const durableGuard = pluginAgent ? durableMessageGuards[pluginAgent] : undefined; + if (durableGuard !== undefined) reqConfig = { ...reqConfig, isMessageProtected: durableGuard }; storeEffectiveConfig(session, reqConfig); // acquireInFlight must precede the lock so evictOldest() cannot flush // this session between getSession and lock acquisition (inFlight===0 diff --git a/tests/issue2419-dsh-skill-catalog.test.ts b/tests/issue2419-dsh-skill-catalog.test.ts new file mode 100644 index 0000000000..9b4cab7285 --- /dev/null +++ b/tests/issue2419-dsh-skill-catalog.test.ts @@ -0,0 +1,231 @@ +// #2419: dsh's skill catalog is DURABLE STATE carried as an ordinary user +// message (dsh-tool-skill ships \x3cavailable_skills\x3e once per session and +// fingerprint-gates resends — sha256 over name+description; unchanged ⇒ never +// resent). The generic ACP fold treats every history message as consumable, +// so one compression killed skill visibility permanently. Fix: the kernel's +// host-declared Config.isMessageProtected hard-protection hook (kernel 0.0.108) +// plus the dsh-lane-scoped guard in src/durable-message-guards.ts. This test +// pins BOTH ends: the dsh lane keeps the catalog across a real fold executed +// through /__bili/plugin/tool, and an unregistered lane still folds it away +// (allowlist discipline — KDD #9: never enable wholesale). +import test from "node:test"; +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import type { ProxyOptions } from "../src/config.ts"; +import { dshSkillCatalogGuard, durableMessageGuards } from "../src/durable-message-guards.ts"; +import { resetPersonaAnchorsForTest } from "../src/persona-anchor.ts"; +import { _resetPluginStateForTest } from "../src/plugin.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { getSession, peekSession, _resetSessionsForTest } from "../src/session.ts"; + +process.env.NODE_ENV = "test"; +process.env.BILI_PERSIST = "0"; + +const MODEL = "gpt-test"; +const MAIN_SYSTEM = "You are DeepSeek Harness, the main coding agent."; +const CATALOG_MARKER = "\x3cavailable_skills\x3e"; +const CATALOG_MSG = `\x3csystem-reminder\x3e\nThe following skills are available in this workspace. Use the matching skill when its trigger words appear.\n${CATALOG_MARKER}\n- name: git-helper\n description: commit conventions and rebase safety\n- name: release-notes\n description: draft release notes from merged PRs\n\x3c/available_skills\x3e\n\x3c/system-reminder\x3e`; + +function filler(tag: string): string { + return `${tag}-` + "z".repeat(900); +} + +type Rig = { proxyPort: number; upstreamPort: number; proxy: http.Server; upstream: http.Server; bodies: string[] }; + +async function startRig(): Promise { + const bodies: string[] = []; + const upstream = http.createServer((req, res) => { + let b = ""; + req.on("data", (c: Buffer) => (b += c.toString("utf8"))); + req.on("end", () => { + bodies.push(b); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ + id: "chatcmpl-1", + object: "chat.completion", + choices: [{ index: 0, message: { role: "assistant", content: "ok" }, finish_reason: "stop" }], + usage: { prompt_tokens: 10, completion_tokens: 3, total_tokens: 13 }, + })); + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamPort = (upstream.address() as { port: number }).port; + + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + _resetSessionsForTest(); + _resetPluginStateForTest(); + resetPersonaAnchorsForTest(); + const proxy = await startServer({ + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upstreamPort}`]: {} }, + modelContextLimit: 200_000, + kernelConfig: defaultConfig(200_000, { + preserveRecentMessages: 3, + preserveRecentTokens: 0, + compress: { minCompressRange: 500, maxSummaryLength: 20_000, minSummaryLength: 50 }, + }), + compress: { injectTool: true, injectNudge: false }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: false, + debug: false, + passthrough: false, + autoUpdate: false, + compat: { roles: {} }, + streamErrorShape: "protocol", + passthroughSource: null, + autoRestartOnUpdate: false, + updateTag: "latest", + advisoryCheck: false, + releaseNotesCheck: false, + mitm: { enabled: false, domains: [] }, + } as ProxyOptions); + await once(proxy, "listening"); + return { proxyPort: (proxy.address() as { port: number }).port, upstreamPort, proxy, upstream, bodies }; +} + +async function closeRig(rig: Rig): Promise { + rig.proxy.close(); + await once(rig.proxy, "close"); + rig.upstream.close(); + await once(rig.upstream, "close"); +} + +/** Refs from NON-SYSTEM message content only: the injected system prompt + * carries literal ACP-tag EXAMPLES (e.g. \x3cacp …\x3em00001\x3c/acp\x3e) + * that a whole-body scan would mistake for live refs. */ +function parseRefIds(body: string): string[] { + let messages: Array<{ role?: string; content?: unknown }> = []; + try { + messages = (JSON.parse(body) as { messages?: Array<{ role?: string; content?: unknown }> }).messages ?? []; + } catch { + return []; + } + const text = messages + .filter((m) => m.role !== "system") + .map((m) => (typeof m.content === "string" ? m.content : JSON.stringify(m.content ?? ""))) + .join("\n"); + const ids: string[] = []; + const re = /<(?:acp|dcp-message-id)[^>]*>\s*(m\d+)\s*<\/(?:acp|dcp-message-id)>/g; + let m: RegExpExecArray | null; + while ((m = re.exec(text)) !== null) ids.push(m[1]!); + return ids; +} + +test("dshSkillCatalogGuard: matches the catalog marker on text messages only", () => { + const msg = (contentType: string, text: unknown) => ({ id: "id-1", createdAt: 0, contentType, text }) as never; + assert.equal(dshSkillCatalogGuard(msg("text", CATALOG_MSG)), true, "user text carrying the catalog matches"); + assert.equal(dshSkillCatalogGuard(msg("text", "plain prose without any catalog")), false); + assert.equal(dshSkillCatalogGuard(msg("tool-call", CATALOG_MARKER)), false, "non-text content types never match"); + assert.equal(dshSkillCatalogGuard(msg("text", undefined)), false, "missing text is safe"); + assert.deepEqual(Object.keys(durableMessageGuards), ["dsh"], "allowlist stays dsh-only (KDD #9 evidence-permitlist discipline)"); +}); + +/** Grow a dsh-lane conversation whose fold range POSITIONALLY covers the + * catalog message (it sits mid-history between two tagged fillers), execute + * a real compress through /__bili/plugin/tool, and return the next turn's + * upstream body. */ +async function runFoldScenario(agent: string, conv: string): Promise<{ postFoldBody: string; toolJson: Record }> { + const rig = await startRig(); + try { + const url = `http://127.0.0.1:${rig.proxyPort}/bili/http://127.0.0.1:${rig.upstreamPort}/v1/chat/completions`; + const headers: Record = { "content-type": "application/json", "x-bili-plugin": agent, "x-bili-plugin-conversation": conv }; + const post = (messages: Array<{ role: string; content: string }>) => + fetch(url, { method: "POST", headers, body: JSON.stringify({ model: MODEL, max_tokens: 64_000, messages: [{ role: "system", content: MAIN_SYSTEM }, ...messages] }) }); + + // Turn 1: two tagged fillers BEFORE the catalog… + const msgs: Array<{ role: string; content: string }> = []; + msgs.push({ role: "user", content: filler("F1") }); + await (await post(msgs)).text(); + msgs.push({ role: "assistant", content: filler("A1") }); + // …turn 2 drops the catalog mid-history… + msgs.push({ role: "user", content: CATALOG_MSG }); + await (await post(msgs)).text(); + msgs.push({ role: "assistant", content: filler("A2") }); + // …and turns 3–8 grow past it. + for (let i = 3; i <= 8; i++) { + msgs.push({ role: "user", content: filler(`F${i}`) }); + await (await post(msgs)).text(); + msgs.push({ role: "assistant", content: filler(`A${i}`) }); + } + + const refIds = parseRefIds(rig.bodies.at(-1)!); + assert.ok(refIds.length >= 10, `expected >= 10 tagged messages, got ${refIds.length}`); + // Fold from the FIRST tagged message (before the catalog) up to four + // back from the tail (clears preserveRecentMessages: 3): the range + // covers the catalog positionally — the old code folds it away. + const startId = refIds[0]!; + const endId = refIds[refIds.length - 4]!; + const toolRes = await fetch(`http://127.0.0.1:${rig.proxyPort}/__bili/plugin/tool`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + conversationId: conv, + tool: "compress", + args: { + topic: "issue2419 fold", + content: [{ startId, endId, topic: "issue2419 fold", summary: "issue2419 fold summary: filler turns F1..F8 were discussed and consumed; nothing else survived this range." }], + }, + }), + }); + const toolJson = (await toolRes.json()) as Record; + assert.ok(toolRes.status === 200 && toolJson.ok === true, `compress must succeed: HTTP ${toolRes.status} ${JSON.stringify(toolJson)}`); + + // Next turn: the rebuilt wire is the assertion surface. + msgs.push({ role: "user", content: filler("F9") }); + await (await post(msgs)).text(); + return { postFoldBody: rig.bodies.at(-1)!, toolJson }; + } finally { + await closeRig(rig); + } +} + +test("dsh lane (#2419): the skill catalog survives a fold that positionally covers it", async () => { + const { postFoldBody } = await runFoldScenario("dsh", "i2419-dsh"); + assert.ok(postFoldBody.includes("[Compressed conversation section]"), "the fold must have happened (protection may not veto the whole range)"); + assert.ok(postFoldBody.includes(CATALOG_MARKER), "the dsh skill catalog must survive the fold (hard-protected, stays fully visible)"); + // A1 (not F1): the kernel pins the session's FIRST user message on the + // wire even when a block covers it (kernel/src/prune.ts rebuildMessages, + // DESIGN.md §8.1 — strict providers reject user-less conversations), so + // F1 would survive any fold and cannot witness consumption. + assert.ok(!postFoldBody.includes("A1-"), "folded filler before the catalog must be gone (the fold really consumed its range)"); + assert.ok(!postFoldBody.includes("F5-"), "folded filler after the catalog must be gone"); +}); + +test("unregistered lane: without the guard the catalog folds away (pins lane scoping)", async () => { + const { postFoldBody } = await runFoldScenario("test-agent", "i2419-plain"); + assert.ok(postFoldBody.includes("[Compressed conversation section]"), "the fold must have happened"); + assert.ok(!postFoldBody.includes(CATALOG_MARKER), "an unregistered lane has no durable-state guard — the catalog is ordinary history and folds away"); +}); + +test("session-level: the dsh lane stamps the guard onto the effective config", async () => { + const rig = await startRig(); + try { + const url = `http://127.0.0.1:${rig.proxyPort}/bili/http://127.0.0.1:${rig.upstreamPort}/v1/chat/completions`; + const r = await fetch(url, { + method: "POST", + headers: { "content-type": "application/json", "x-bili-plugin": "dsh", "x-bili-plugin-conversation": "i2419-stamp" }, + body: JSON.stringify({ model: MODEL, max_tokens: 64_000, messages: [{ role: "system", content: MAIN_SYSTEM }, { role: "user", content: CATALOG_MSG }] }), + }); + assert.equal(r.status, 200); + await r.text(); + const s = peekSession("i2419-stamp"); + assert.ok(s, "dsh session exists"); + // The stamped effective config (read by /__bili/plugin/tool) carries the + // guard — proven indirectly: the catalog got a BLOCKED ref, i.e. it was + // recognized as protected AT ASSIGNMENT TIME on the very first turn. + const sFull = getSession("i2419-stamp"); + const catalogBlocked = Object.entries(sFull.state.messageRefs.byRaw).some(([, ref]) => ref === "BLOCKED"); + assert.ok(catalogBlocked, "the catalog message must carry a BLOCKED ref (never advertised, never foldable)"); + } finally { + await closeRig(rig); + } +}); From d728b6d84a8a7c4522dc379c090029fb674eede1 Mon Sep 17 00:00:00 2001 From: awork Date: Fri, 9 Oct 2026 00:06:52 +0800 Subject: [PATCH 3/6] fix: keep durable-message guard out of cloned/persisted session metadata (#2428) Storing the dsh guard FUNCTION in session.metadata.effectiveConfig broke fork/derived-child adoption: plugin.ts structuredClones that metadata and a function throws DataCloneError -> FORK_FAILED 503 (5 #2399 fork tests red on CI), and disk persistence cannot serialize a function either. Stamp the clone-safe config first, then attach the guard to the turn-local reqConfig so processTurn protects the message this turn; effectiveConfig() re-resolves the guard from the clone-safe pluginAgent lane id at read time, so /__bili/plugin/tool sees the same protection. Non-dsh lanes byte-identical. Also drop the unused DurableMessageGuard export (unused-exports gate). --- src/durable-message-guards.ts | 2 +- src/server/handle.ts | 12 +++++++----- src/session.ts | 13 +++++++++++-- 3 files changed, 19 insertions(+), 8 deletions(-) diff --git a/src/durable-message-guards.ts b/src/durable-message-guards.ts index cca3c79e7f..bd65bf79ed 100644 --- a/src/durable-message-guards.ts +++ b/src/durable-message-guards.ts @@ -20,7 +20,7 @@ import type { CoreMessage } from "acp-kernel"; -export type DurableMessageGuard = (msg: CoreMessage) => boolean; +type DurableMessageGuard = (msg: CoreMessage) => boolean; /** dsh skill-catalog guard (#2419): matches the durable catalog message * injected by dsh-tool-skill (a \x3csystem-reminder\x3e carrying the diff --git a/src/server/handle.ts b/src/server/handle.ts index 89f10eac9a..e107e0913a 100644 --- a/src/server/handle.ts +++ b/src/server/handle.ts @@ -1723,13 +1723,15 @@ export async function handle( // same instant as effectiveContextLimit above) so request-context-free // display paths (/__bili/plugin/status Nudge line, plugin tool API) // render from the values the kernel actually used this turn. - // #2419: per-lane durable-state message guard — attach BEFORE stamping - // so both this turn's processTurn(reqConfig) and the stamped effective - // config (read by /__bili/plugin/tool) carry it. Only lanes present in - // the registry are affected; an absent predicate is byte-identical. + // #2419: per-lane durable-state message guard (KDD#9 evidence-permitlist). + // Stamp the CLONE-SAFE config first — a function inside + // session.metadata.effectiveConfig would break fork-adoption structuredClone + // and disk persistence — then attach it to this turn's reqConfig so + // processTurn protects the message now. effectiveConfig() re-resolves the + // guard from the lane id at read time, so /__bili/plugin/tool sees it too. + storeEffectiveConfig(session, reqConfig); const durableGuard = pluginAgent ? durableMessageGuards[pluginAgent] : undefined; if (durableGuard !== undefined) reqConfig = { ...reqConfig, isMessageProtected: durableGuard }; - storeEffectiveConfig(session, reqConfig); // acquireInFlight must precede the lock so evictOldest() cannot flush // this session between getSession and lock acquisition (inFlight===0 // window). Released in the outer finally after forward completes. diff --git a/src/session.ts b/src/session.ts index f1840f53a5..d0d9dae10a 100644 --- a/src/session.ts +++ b/src/session.ts @@ -3,6 +3,7 @@ import { createHash } from "node:crypto"; import { log as loggerLog } from "./logger.js"; import { getStore } from "./persist.js"; import { maxSessions as knobMaxSessions } from "./knobs.js"; +import { durableMessageGuards } from "./durable-message-guards.js"; import type { WireProtocol } from "./util.js"; export type BlockView = { text: string; count: number }; @@ -425,8 +426,16 @@ export function storeEffectiveConfig(session: Session, config: Config): void { export function effectiveConfig(session: Session | undefined, fallback: Config): Config { const stored = session?.metadata["effectiveConfig"]; - if (stored && typeof stored === "object") return { ...fallback, ...(stored as Partial) }; - return fallback; + const base = stored && typeof stored === "object" ? { ...fallback, ...(stored as Partial) } : fallback; + // #2419 follow-up (CI regression): the per-lane durable-message guard is a + // FUNCTION and must never be persisted into session.metadata — fork-adoption + // structuredClones metadata.effectiveConfig (plugin.ts) and disk persistence + // cannot serialize a function. The lane id is already clone-safe here, so + // re-resolve the guard from it at read time; every consumer (plugin tool, + // nudge panel) then sees the same protection the wire path used this turn. + const lane = typeof session?.metadata["pluginAgent"] === "string" ? session.metadata["pluginAgent"] : undefined; + const guard = lane ? durableMessageGuards[lane] : undefined; + return guard && !base.isMessageProtected ? { ...base, isMessageProtected: guard } : base; } /** #2029: provenance-aware baseline for STATUS readers — acp_status nudge From 96d796c097f38875d3a4a40111854d3e752d4185 Mon Sep 17 00:00:00 2001 From: awork Date: Fri, 9 Oct 2026 09:46:08 +0800 Subject: [PATCH 4/6] fix: dsh lane durable guard also covers the workspace-instructions baseline (#2447) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #2447: dsh's @deepseek-ai/dsh-agent-instructions plugin carries the merged global+project AGENTS.md as a user-role system-reminder baseline (sections labelled 'Instructions from: '), re-emitted only when baselineIdentity (projectRoot + discovery/budget config, NOT file contents) changes — same durable-user-message contract as the #2419 skill catalog, second carrier missed by the original whitelist. Extend the dsh-lane predicate with dshWorkspaceInstructionsGuard (case-sensitive 'Instructions from:' inner marker; lowercase reconciliation variants stay consumable). No kernel change: the generic Config.isMessageProtected hook from #2419 already covers it. --- src/durable-message-guards.ts | 50 +++- ...sue2447-dsh-workspace-instructions.test.ts | 241 ++++++++++++++++++ 2 files changed, 278 insertions(+), 13 deletions(-) create mode 100644 tests/issue2447-dsh-workspace-instructions.test.ts diff --git a/src/durable-message-guards.ts b/src/durable-message-guards.ts index bd65bf79ed..13e20fcf71 100644 --- a/src/durable-message-guards.ts +++ b/src/durable-message-guards.ts @@ -1,17 +1,21 @@ -// #2419: durable-state message guards, declared per plugin lane. +// #2419/#2447: durable-state message guards, declared per plugin lane. // // Some hosts inject DURABLE STATE as ordinary conversation messages and gate -// re-injection on a content fingerprint: dsh-tool-skill ships its skill -// catalog (\x3cavailable_skills\x3e) as a user-role system-reminder once per -// session and never resends it while the sha256(name+description) digest is -// unchanged. ACP compression treats every history message as consumable, so -// one fold of the catalog silently kills skill triggering forever (the host -// will not resend what it believes is already present). The kernel's -// protection surface was tool-exchange-only (protectedTools / isToolProtected), -// structurally unable to cover a plain text message — hence the generic -// Config.isMessageProtected hook (kernel 0.0.108) and this lane-scoped policy -// map. The mechanism lives in the kernel; the POLICY (which shapes, for which -// host) lives here, one entry per lane with traffic evidence. +// re-injection on a content fingerprint: dsh ships two such carriers as +// user-role messages — dsh-tool-skill's skill catalog (\x3cavailable_skills\x3e, +// #2419; never resent while the sha256(name+description) digest is unchanged) +// and @deepseek-ai/dsh-agent-instructions' workspace-instructions baseline +// (#2447: global + project AGENTS.md merged into ONE message, re-emitted only +// when baselineIdentity — projectRoot + discovery/budget config, NOT file +// contents — changes). ACP compression treats every history message as +// consumable, so one fold of either carrier silently kills its guidance +// forever (the host will not resend what it believes is already present). The +// kernel's protection surface was tool-exchange-only (protectedTools / +// isToolProtected), structurally unable to cover a plain text message — hence +// the generic Config.isMessageProtected hook (kernel 0.0.108) and this +// lane-scoped policy map. The mechanism lives in the kernel; the POLICY +// (which shapes, for which host) lives here, one entry per lane with traffic +// evidence. // // KDD #9 evidence-permitlist discipline applies: entries are added PER HOST // with traffic evidence (shape + stability proof), never enabled wholesale — @@ -33,9 +37,29 @@ export function dshSkillCatalogGuard(msg: CoreMessage): boolean { return msg.contentType === "text" && typeof msg.text === "string" && msg.text.includes("\x3cavailable_skills\x3e"); } +/** dsh workspace-instructions guard (#2447): matches the durable AGENTS.md + * baseline message injected by @deepseek-ai/dsh-agent-instructions — global + * (~/.dsh/AGENTS.md) and project instructions merged into ONE user-role + * \x3csystem-reminder\x3e message whose sections are labelled + * `Instructions from: ` (source: lib/index.js sectionText + + * createUserMessage). The host re-emits the baseline only when + * baselineIdentity (projectRoot + discovery/budget config, NOT file contents) + * changes, so one fold of it silently kills hard constraints like "read X + * before any web access" forever. Same marker-over-wrapper rationale as + * dshSkillCatalogGuard: the per-file label is matched on its own so wrapper/ + * intro rewording cannot silently disarm the guard; a false positive is + * benign (a matching message simply stays visible). The match is + * case-sensitive on purpose — reconciliation change messages use lowercase + * variants ("Updated instructions from:") that remain ordinary consumable + * history. At most ~one such baseline lives per session (replacements are + * rare identity changes), so pinning every match is bounded. */ +export function dshWorkspaceInstructionsGuard(msg: CoreMessage): boolean { + return msg.contentType === "text" && typeof msg.text === "string" && msg.text.includes("Instructions from:"); +} + /** Lane → guard registry. Only lanes with traffic evidence of the * durable-user-message carrier belong here (KDD #9). Keyed by the value of * the x-bili-plugin header / session.metadata.pluginAgent binding. */ export const durableMessageGuards: Record = { - dsh: dshSkillCatalogGuard, + dsh: (msg) => dshSkillCatalogGuard(msg) || dshWorkspaceInstructionsGuard(msg), }; diff --git a/tests/issue2447-dsh-workspace-instructions.test.ts b/tests/issue2447-dsh-workspace-instructions.test.ts new file mode 100644 index 0000000000..668276339a --- /dev/null +++ b/tests/issue2447-dsh-workspace-instructions.test.ts @@ -0,0 +1,241 @@ +// #2447: dsh's workspace instructions (AGENTS.md) are DURABLE STATE carried +// as an ordinary user message — @deepseek-ai/dsh-agent-instructions merges the +// global (~/.dsh/AGENTS.md) and project instructions into ONE user-role +// \x3csystem-reminder\x3e baseline whose sections are labelled +// "Instructions from: ", and re-emits it only when baselineIdentity +// (projectRoot + discovery/budget config, NOT file contents) changes. The +// generic ACP fold treats every history message as consumable, so one +// compression killed hard constraints like "read X before any web access" +// permanently — same mechanism family as the #2419 skill catalog, second +// carrier missed by the #2428 whitelist. Fix: extend the dsh-lane durable +// guard in src/durable-message-guards.ts with dshWorkspaceInstructionsGuard. +// This test pins BOTH ends: the dsh lane keeps the baseline across a real fold +// executed through /__bili/plugin/tool, and an unregistered lane still folds +// it away (allowlist discipline — KDD #9: never enable wholesale). +import test from "node:test"; +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import type { ProxyOptions } from "../src/config.ts"; +import { dshWorkspaceInstructionsGuard, durableMessageGuards } from "../src/durable-message-guards.ts"; +import { resetPersonaAnchorsForTest } from "../src/persona-anchor.ts"; +import { _resetPluginStateForTest } from "../src/plugin.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { getSession, peekSession, _resetSessionsForTest } from "../src/session.ts"; + +process.env.NODE_ENV = "test"; +process.env.BILI_PERSIST = "0"; + +const MODEL = "gpt-test"; +const MAIN_SYSTEM = "You are DeepSeek Harness, the main coding agent."; +const RULE_MARKER = "$HOME/.agents/rules/web-access-rules/web-access-rules.md"; +const INSTR_MSG = `\x3csystem-reminder\x3e\nThe following workspace instructions may be relevant to your work. Use them as guidance when applicable. More specific instructions take precedence over broader ones. They do not override system, developer, or direct user instructions.\n\nInstructions from: ~/.dsh/AGENTS.md\n\n## \u89c4\u5219\n$HOME/.agents/rules/\n\u251c\u2500\u2500 web-access-rules/\n\u2502 \u251c\u2500\u2500 ${RULE_MARKER} # \u4efb\u4f55 web search/fetch \u524d\u5fc5\u8bfb\n\u251c\u2500\u2500 coding-rules.md # \u901a\u7528\u7f16\u7801\u89c4\u8303\n\nInstructions from: AGENTS.md\n\n# project rules\nalways run lint before committing\n\x3c/system-reminder\x3e`; +const CHANGE_MSG = `\x3csystem-reminder\x3e\nUpdated instructions from: AGENTS.md\n\n# project rules v2\nalways run lint AND typecheck before committing\n\x3c/system-reminder\x3e`; + +function filler(tag: string): string { + return `${tag}-` + "z".repeat(900); +} + +type Rig = { proxyPort: number; upstreamPort: number; proxy: http.Server; upstream: http.Server; bodies: string[] }; + +async function startRig(): Promise { + const bodies: string[] = []; + const upstream = http.createServer((req, res) => { + let b = ""; + req.on("data", (c: Buffer) => (b += c.toString("utf8"))); + req.on("end", () => { + bodies.push(b); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ + id: "chatcmpl-1", + object: "chat.completion", + choices: [{ index: 0, message: { role: "assistant", content: "ok" }, finish_reason: "stop" }], + usage: { prompt_tokens: 10, completion_tokens: 3, total_tokens: 13 }, + })); + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamPort = (upstream.address() as { port: number }).port; + + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + _resetSessionsForTest(); + _resetPluginStateForTest(); + resetPersonaAnchorsForTest(); + const proxy = await startServer({ + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upstreamPort}`]: {} }, + modelContextLimit: 200_000, + kernelConfig: defaultConfig(200_000, { + preserveRecentMessages: 3, + preserveRecentTokens: 0, + compress: { minCompressRange: 500, maxSummaryLength: 20_000, minSummaryLength: 50 }, + }), + compress: { injectTool: true, injectNudge: false }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: false, + debug: false, + passthrough: false, + autoUpdate: false, + compat: { roles: {} }, + streamErrorShape: "protocol", + passthroughSource: null, + autoRestartOnUpdate: false, + updateTag: "latest", + advisoryCheck: false, + releaseNotesCheck: false, + mitm: { enabled: false, domains: [] }, + } as ProxyOptions); + await once(proxy, "listening"); + return { proxyPort: (proxy.address() as { port: number }).port, upstreamPort, proxy, upstream, bodies }; +} + +async function closeRig(rig: Rig): Promise { + rig.proxy.close(); + await once(rig.proxy, "close"); + rig.upstream.close(); + await once(rig.upstream, "close"); +} + +/** Refs from NON-SYSTEM message content only: the injected system prompt + * carries literal ACP-tag EXAMPLES (e.g. \x3cacp …\x3em00001\x3c/acp\x3e) + * that a whole-body scan would mistake for live refs. */ +function parseRefIds(body: string): string[] { + let messages: Array<{ role?: string; content?: unknown }> = []; + try { + messages = (JSON.parse(body) as { messages?: Array<{ role?: string; content?: unknown }> }).messages ?? []; + } catch { + return []; + } + const text = messages + .filter((m) => m.role !== "system") + .map((m) => (typeof m.content === "string" ? m.content : JSON.stringify(m.content ?? ""))) + .join("\n"); + const ids: string[] = []; + const re = /<(?:acp|dcp-message-id)[^>]*>\s*(m\d+)\s*<\/(?:acp|dcp-message-id)>/g; + let m: RegExpExecArray | null; + while ((m = re.exec(text)) !== null) ids.push(m[1]!); + return ids; +} + +test("dshWorkspaceInstructionsGuard: matches the baseline label on text messages only", () => { + const msg = (contentType: string, text: unknown) => ({ id: "id-1", createdAt: 0, contentType, text }) as never; + assert.equal(dshWorkspaceInstructionsGuard(msg("text", INSTR_MSG)), true, "the merged global+project baseline matches"); + assert.equal(dshWorkspaceInstructionsGuard(msg("text", "plain prose about workspace setup")), false); + assert.equal(dshWorkspaceInstructionsGuard(msg("text", CHANGE_MSG)), false, "lowercase reconciliation variants stay consumable history"); + assert.equal(dshWorkspaceInstructionsGuard(msg("tool-call", "Instructions from: AGENTS.md")), false, "non-text content types never match"); + assert.equal(dshWorkspaceInstructionsGuard(msg("text", undefined)), false, "missing text is safe"); + const dshGuard = durableMessageGuards["dsh"]; + assert.ok(dshGuard, "dsh lane is registered"); + assert.equal(dshGuard!(msg("text", "\x3cavailable_skills\x3e…\x3c/available_skills\x3e")), true, "lane entry still covers the #2419 catalog shape"); + assert.deepEqual(Object.keys(durableMessageGuards), ["dsh"], "allowlist stays dsh-only (KDD #9 evidence-permitlist discipline)"); +}); + +/** Grow a dsh-lane conversation whose fold range POSITIONALLY covers the + * instructions baseline (it sits mid-history between two tagged fillers), + * execute a real compress through /__bili/plugin/tool, and return the next + * turn's upstream body. */ +async function runFoldScenario(agent: string, conv: string): Promise<{ postFoldBody: string; toolJson: Record }> { + const rig = await startRig(); + try { + const url = `http://127.0.0.1:${rig.proxyPort}/bili/http://127.0.0.1:${rig.upstreamPort}/v1/chat/completions`; + const headers: Record = { "content-type": "application/json", "x-bili-plugin": agent, "x-bili-plugin-conversation": conv }; + const post = (messages: Array<{ role: string; content: string }>) => + fetch(url, { method: "POST", headers, body: JSON.stringify({ model: MODEL, max_tokens: 64_000, messages: [{ role: "system", content: MAIN_SYSTEM }, ...messages] }) }); + + // Turn 1: two tagged fillers BEFORE the baseline… + const msgs: Array<{ role: string; content: string }> = []; + msgs.push({ role: "user", content: filler("F1") }); + await (await post(msgs)).text(); + msgs.push({ role: "assistant", content: filler("A1") }); + // …turn 2 drops the baseline mid-history… + msgs.push({ role: "user", content: INSTR_MSG }); + await (await post(msgs)).text(); + msgs.push({ role: "assistant", content: filler("A2") }); + // …and turns 3–8 grow past it. + for (let i = 3; i <= 8; i++) { + msgs.push({ role: "user", content: filler(`F${i}`) }); + await (await post(msgs)).text(); + msgs.push({ role: "assistant", content: filler(`A${i}`) }); + } + + const refIds = parseRefIds(rig.bodies.at(-1)!); + assert.ok(refIds.length >= 10, `expected >= 10 tagged messages, got ${refIds.length}`); + // Fold from the FIRST tagged message (before the baseline) up to four + // back from the tail (clears preserveRecentMessages: 3): the range + // covers the baseline positionally — the old code folds it away. + const startId = refIds[0]!; + const endId = refIds[refIds.length - 4]!; + const toolRes = await fetch(`http://127.0.0.1:${rig.proxyPort}/__bili/plugin/tool`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + conversationId: conv, + tool: "compress", + args: { + topic: "issue2447 fold", + content: [{ startId, endId, topic: "issue2447 fold", summary: "issue2447 fold summary: filler turns F1..F8 were discussed and consumed; nothing else survived this range." }], + }, + }), + }); + const toolJson = (await toolRes.json()) as Record; + assert.ok(toolRes.status === 200 && toolJson.ok === true, `compress must succeed: HTTP ${toolRes.status} ${JSON.stringify(toolJson)}`); + + // Next turn: the rebuilt wire is the assertion surface. + msgs.push({ role: "user", content: filler("F9") }); + await (await post(msgs)).text(); + return { postFoldBody: rig.bodies.at(-1)!, toolJson }; + } finally { + await closeRig(rig); + } +} + +test("dsh lane (#2447): the workspace-instructions baseline survives a fold that positionally covers it", async () => { + const { postFoldBody } = await runFoldScenario("dsh", "i2447-dsh"); + assert.ok(postFoldBody.includes("[Compressed conversation section]"), "the fold must have happened (protection may not veto the whole range)"); + assert.ok(postFoldBody.includes(RULE_MARKER), "the hard-constraint rule path must survive the fold (hard-protected, stays fully visible)"); + assert.ok(postFoldBody.includes("Instructions from: AGENTS.md"), "the project-level section must survive too (one message carries both)"); + // A1 (not F1): the kernel pins the session's FIRST user message on the + // wire even when a block covers it (kernel/src/prune.ts rebuildMessages, + // DESIGN.md §8.1 — strict providers reject user-less conversations), so + // F1 would survive any fold and cannot witness consumption. + assert.ok(!postFoldBody.includes("A1-"), "folded filler before the baseline must be gone (the fold really consumed its range)"); + assert.ok(!postFoldBody.includes("F5-"), "folded filler after the baseline must be gone"); +}); + +test("unregistered lane: without the guard the baseline folds away (pins lane scoping)", async () => { + const { postFoldBody } = await runFoldScenario("test-agent", "i2447-plain"); + assert.ok(postFoldBody.includes("[Compressed conversation section]"), "the fold must have happened"); + assert.ok(!postFoldBody.includes(RULE_MARKER), "an unregistered lane has no durable-state guard — the baseline is ordinary history and folds away"); +}); + +test("session-level: the dsh lane stamps the guard onto the effective config", async () => { + const rig = await startRig(); + try { + const url = `http://127.0.0.1:${rig.proxyPort}/bili/http://127.0.0.1:${rig.upstreamPort}/v1/chat/completions`; + const r = await fetch(url, { + method: "POST", + headers: { "content-type": "application/json", "x-bili-plugin": "dsh", "x-bili-plugin-conversation": "i2447-stamp" }, + body: JSON.stringify({ model: MODEL, max_tokens: 64_000, messages: [{ role: "system", content: MAIN_SYSTEM }, { role: "user", content: INSTR_MSG }] }), + }); + assert.equal(r.status, 200); + await r.text(); + const s = peekSession("i2447-stamp"); + assert.ok(s, "dsh session exists"); + // The stamped effective config (read by /__bili/plugin/tool) carries the + // guard — proven indirectly: the baseline got a BLOCKED ref, i.e. it was + // recognized as protected AT ASSIGNMENT TIME on the very first turn. + const sFull = getSession("i2447-stamp"); + const baselineBlocked = Object.entries(sFull.state.messageRefs.byRaw).some(([, ref]) => ref === "BLOCKED"); + assert.ok(baselineBlocked, "the baseline message must carry a BLOCKED ref (never advertised, never foldable)"); + } finally { + await closeRig(rig); + } +}); From 8d9a8c18a697e0c8eceb33aec27da98a4f2ca230 Mon Sep 17 00:00:00 2001 From: awork Date: Fri, 9 Oct 2026 09:49:38 +0800 Subject: [PATCH 5/6] kernel: bump acp-kernel to 0.0.110 after rebase onto master master independently reached 0.0.109 (d9ce7ad34); the isMessageProtected hook (#2419) is a kernel/src change and must land with its own version increment (CI kernel-guard version discipline). --- kernel/package.json | 2 +- package-lock.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/kernel/package.json b/kernel/package.json index 2317456b31..a759139819 100644 --- a/kernel/package.json +++ b/kernel/package.json @@ -1,6 +1,6 @@ { "name": "acp-kernel", - "version": "0.0.109", + "version": "0.0.110", "description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.", "license": "MIT", "author": "ranxianglei", diff --git a/package-lock.json b/package-lock.json index 04ad1c16f0..67ae4cdc7b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -48,7 +48,7 @@ }, "kernel": { "name": "acp-kernel", - "version": "0.0.109", + "version": "0.0.110", "dev": true, "license": "MIT", "devDependencies": { From b9569de3447f756d2bc06e4b1432e7eb8b2da1d4 Mon Sep 17 00:00:00 2001 From: awork Date: Fri, 9 Oct 2026 16:01:40 +0800 Subject: [PATCH 6/6] fix: dsh lane durable guard also covers the runtime-context snapshot (#2481) --- src/durable-message-guards.ts | 45 +++- tests/issue2481-dsh-runtime-context.test.ts | 253 ++++++++++++++++++++ 2 files changed, 289 insertions(+), 9 deletions(-) create mode 100644 tests/issue2481-dsh-runtime-context.test.ts diff --git a/src/durable-message-guards.ts b/src/durable-message-guards.ts index 13e20fcf71..1be3f3baeb 100644 --- a/src/durable-message-guards.ts +++ b/src/durable-message-guards.ts @@ -1,16 +1,22 @@ -// #2419/#2447: durable-state message guards, declared per plugin lane. +// #2419/#2447/#2481: durable-state message guards, declared per plugin lane. // // Some hosts inject DURABLE STATE as ordinary conversation messages and gate -// re-injection on a content fingerprint: dsh ships two such carriers as +// re-injection on a content fingerprint: dsh ships three such carriers as // user-role messages — dsh-tool-skill's skill catalog (\x3cavailable_skills\x3e, -// #2419; never resent while the sha256(name+description) digest is unchanged) -// and @deepseek-ai/dsh-agent-instructions' workspace-instructions baseline +// #2419; never resent while the sha256(name+description) digest is unchanged), +// @deepseek-ai/dsh-agent-instructions' workspace-instructions baseline // (#2447: global + project AGENTS.md merged into ONE message, re-emitted only // when baselineIdentity — projectRoot + discovery/budget config, NOT file -// contents — changes). ACP compression treats every history message as -// consumable, so one fold of either carrier silently kills its guidance -// forever (the host will not resend what it believes is already present). The -// kernel's protection surface was tool-exchange-only (protectedTools / +// contents — changes), and the agent-loop runtime-context snapshot (#2481: +// sandbox/approval policy state, self-declared "supersedes earlier +// runtime-context snapshots" — resent only when the runtime context CHANGES, +// not every turn). ACP compression treats every history message as consumable, +// so one fold of any carrier silently kills its guidance forever (the host +// will not resend what it believes is already present). The structured +// source.kind these hosts stamp internally never reaches the proxy wire +// (CoreMessage carries no metadata field), so the guards match stable text +// markers instead — the same criterion discipline as #2447. The kernel's +// protection surface was tool-exchange-only (protectedTools / // isToolProtected), structurally unable to cover a plain text message — hence // the generic Config.isMessageProtected hook (kernel 0.0.108) and this // lane-scoped policy map. The mechanism lives in the kernel; the POLICY @@ -57,9 +63,30 @@ export function dshWorkspaceInstructionsGuard(msg: CoreMessage): boolean { return msg.contentType === "text" && typeof msg.text === "string" && msg.text.includes("Instructions from:"); } +/** dsh runtime-context guard (#2481): matches the durable runtime-context + * snapshot injected by the dsh agent loop — sandbox/approval policy state + * carried as a user-role message containing "Current runtime context" + * (source: deepseek-ai/deepseek-harness MIT packages/core/agent-loop/src/ + * runtime-context.ts; the same text family bili already recognizes as an + * auto-injected notification in #2286's AUTO_INJECTED_NOTIFICATION_PREFIXES). + * Both variants match on purpose: the populated snapshot ("Current runtime + * context. This snapshot supersedes earlier runtime-context snapshots. …") + * AND the cleared form ("Current runtime context: none. Earlier + * runtime-context snapshots no longer apply.") — the cleared notice must + * stay visible too, because it is what invalidates the older snapshots this + * guard pins. The host re-emits only when the runtime context CHANGES (the + * per-turn time-context carrier deliberately stays foldable), so one fold of + * the latest snapshot silently drops the session's sandbox/approval semantics + * forever. Each snapshot is tiny (~100–400 chars); superseded ones keep + * pinning harmlessly because the newest carries the supersedes clause. */ +export function dshRuntimeContextGuard(msg: CoreMessage): boolean { + return msg.contentType === "text" && typeof msg.text === "string" && msg.text.includes("Current runtime context"); +} + /** Lane → guard registry. Only lanes with traffic evidence of the * durable-user-message carrier belong here (KDD #9). Keyed by the value of * the x-bili-plugin header / session.metadata.pluginAgent binding. */ export const durableMessageGuards: Record = { - dsh: (msg) => dshSkillCatalogGuard(msg) || dshWorkspaceInstructionsGuard(msg), + dsh: (msg) => + dshSkillCatalogGuard(msg) || dshWorkspaceInstructionsGuard(msg) || dshRuntimeContextGuard(msg), }; diff --git a/tests/issue2481-dsh-runtime-context.test.ts b/tests/issue2481-dsh-runtime-context.test.ts new file mode 100644 index 0000000000..42874d1719 --- /dev/null +++ b/tests/issue2481-dsh-runtime-context.test.ts @@ -0,0 +1,253 @@ +// #2481: dsh's runtime-context snapshot (sandbox/approval policy state) is +// DURABLE STATE carried as an ordinary user message — the dsh agent loop +// emits it once per session and re-emits only when the runtime context +// CHANGES ("This snapshot supersedes earlier runtime-context snapshots"), +// unlike the per-turn time-context carrier. The generic ACP fold treats every +// history message as consumable, so one compression dropped the session's +// sandbox/approval semantics permanently (the host will not resend what it +// believes is already present) — same mechanism family as the #2419 skill +// catalog and the #2447 workspace-instructions baseline, third carrier missed +// by the #2428 text-marker whitelist (its body carries neither +// "Instructions from:" nor \x3cavailable_skills\x3e). Fix: extend the dsh-lane +// durable guard in src/durable-message-guards.ts with dshRuntimeContextGuard. +// This test pins BOTH ends: the dsh lane keeps the snapshot across a real fold +// executed through /__bili/plugin/tool, and an unregistered lane still folds +// it away (allowlist discipline — KDD #9: never enable wholesale). +import test from "node:test"; +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import type { ProxyOptions } from "../src/config.ts"; +import { dshRuntimeContextGuard, durableMessageGuards } from "../src/durable-message-guards.ts"; +import { resetPersonaAnchorsForTest } from "../src/persona-anchor.ts"; +import { _resetPluginStateForTest } from "../src/plugin.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { getSession, peekSession, _resetSessionsForTest } from "../src/session.ts"; + +process.env.NODE_ENV = "test"; +process.env.BILI_PERSIST = "0"; + +const MODEL = "gpt-test"; +const MAIN_SYSTEM = "You are DeepSeek Harness, the main coding agent."; +// Verbatim from the #2481 report (session session-58f7d789, m00003): +const RT_MSG = `Current runtime context. This snapshot supersedes earlier runtime-context snapshots. + +Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations. + +Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set \`sandbox_permissions\`).`; +// Cleared variant from the same emitter (deepseek-harness +// packages/core/agent-loop/src/runtime-context.ts): +const RT_CLEARED_MSG = `Current runtime context: none. Earlier runtime-context snapshots no longer apply.`; + +function filler(tag: string): string { + return `${tag}-` + "z".repeat(900); +} + +type Rig = { proxyPort: number; upstreamPort: number; proxy: http.Server; upstream: http.Server; bodies: string[] }; + +async function startRig(): Promise { + const bodies: string[] = []; + const upstream = http.createServer((req, res) => { + let b = ""; + req.on("data", (c: Buffer) => (b += c.toString("utf8"))); + req.on("end", () => { + bodies.push(b); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ + id: "chatcmpl-1", + object: "chat.completion", + choices: [{ index: 0, message: { role: "assistant", content: "ok" }, finish_reason: "stop" }], + usage: { prompt_tokens: 10, completion_tokens: 3, total_tokens: 13 }, + })); + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamPort = (upstream.address() as { port: number }).port; + + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + _resetSessionsForTest(); + _resetPluginStateForTest(); + resetPersonaAnchorsForTest(); + const proxy = await startServer({ + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upstreamPort}`]: {} }, + modelContextLimit: 200_000, + kernelConfig: defaultConfig(200_000, { + preserveRecentMessages: 3, + preserveRecentTokens: 0, + compress: { minCompressRange: 500, maxSummaryLength: 20_000, minSummaryLength: 50 }, + }), + compress: { injectTool: true, injectNudge: false }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: false, + debug: false, + passthrough: false, + autoUpdate: false, + compat: { roles: {} }, + streamErrorShape: "protocol", + passthroughSource: null, + autoRestartOnUpdate: false, + updateTag: "latest", + advisoryCheck: false, + releaseNotesCheck: false, + mitm: { enabled: false, domains: [] }, + } as ProxyOptions); + await once(proxy, "listening"); + return { proxyPort: (proxy.address() as { port: number }).port, upstreamPort, proxy, upstream, bodies }; +} + +async function closeRig(rig: Rig): Promise { + rig.proxy.close(); + await once(rig.proxy, "close"); + rig.upstream.close(); + await once(rig.upstream, "close"); +} + +/** Refs from NON-SYSTEM message content only: the injected system prompt + * carries literal ACP-tag EXAMPLES (e.g. \x3cacp …\x3em00001\x3c/acp\x3e) + * that a whole-body scan would mistake for live refs. */ +function parseRefIds(body: string): string[] { + let messages: Array<{ role?: string; content?: unknown }> = []; + try { + messages = (JSON.parse(body) as { messages?: Array<{ role?: string; content?: unknown }> }).messages ?? []; + } catch { + return []; + } + const text = messages + .filter((m) => m.role !== "system") + .map((m) => (typeof m.content === "string" ? m.content : JSON.stringify(m.content ?? ""))) + .join("\n"); + const ids: string[] = []; + const re = /<(?:acp|dcp-message-id)[^>]*>\s*(m\d+)\s*<\/(?:acp|dcp-message-id)>/g; + let m: RegExpExecArray | null; + while ((m = re.exec(text)) !== null) ids.push(m[1]!); + return ids; +} + +test("dshRuntimeContextGuard: matches both snapshot variants on text messages only", () => { + const msg = (contentType: string, text: unknown) => ({ id: "id-1", createdAt: 0, contentType, text }) as never; + assert.equal(dshRuntimeContextGuard(msg("text", RT_MSG)), true, "the populated sandbox/approval snapshot matches"); + assert.equal(dshRuntimeContextGuard(msg("text", RT_CLEARED_MSG)), true, "the cleared form matches too (it invalidates the older pinned snapshots)"); + // Deliberately foldable neighbors stay consumable: + assert.equal(dshRuntimeContextGuard(msg("text", "Time sampled while preparing turn: Fri Oct 09 2026 15:20:00 CST")), false, "the per-turn time-context carrier stays foldable"); + assert.equal(dshRuntimeContextGuard(msg("text", "The approval policy changed from 'ask' to 'never' (changed by the user).")), false, "the approval-change DELTA is transient history (current state rides in the snapshot's approval:policy section)"); + assert.equal(dshRuntimeContextGuard(msg("text", "plain prose about the runtime environment")), false); + assert.equal(dshRuntimeContextGuard(msg("tool-call", RT_MSG)), false, "non-text content types never match"); + assert.equal(dshRuntimeContextGuard(msg("text", undefined)), false, "missing text is safe"); + const dshGuard = durableMessageGuards["dsh"]; + assert.ok(dshGuard, "dsh lane is registered"); + assert.equal(dshGuard!(msg("text", "\x3cavailable_skills\x3e…\x3c/available_skills\x3e")), true, "lane entry still covers the #2419 catalog shape"); + assert.equal(dshGuard!(msg("text", "Instructions from: AGENTS.md")), true, "lane entry still covers the #2447 baseline shape"); + assert.equal(dshGuard!(msg("text", RT_MSG)), true, "lane entry covers the #2481 snapshot shape"); + assert.deepEqual(Object.keys(durableMessageGuards), ["dsh"], "allowlist stays dsh-only (KDD #9 evidence-permitlist discipline)"); +}); + +/** Grow a dsh-lane conversation whose fold range POSITIONALLY covers the + * runtime-context snapshot (it sits mid-history between two tagged fillers), + * execute a real compress through /__bili/plugin/tool, and return the next + * turn's upstream body. */ +async function runFoldScenario(agent: string, conv: string): Promise<{ postFoldBody: string; toolJson: Record }> { + const rig = await startRig(); + try { + const url = `http://127.0.0.1:${rig.proxyPort}/bili/http://127.0.0.1:${rig.upstreamPort}/v1/chat/completions`; + const headers: Record = { "content-type": "application/json", "x-bili-plugin": agent, "x-bili-plugin-conversation": conv }; + const post = (messages: Array<{ role: string; content: string }>) => + fetch(url, { method: "POST", headers, body: JSON.stringify({ model: MODEL, max_tokens: 64_000, messages: [{ role: "system", content: MAIN_SYSTEM }, ...messages] }) }); + + // Turn 1: two tagged fillers BEFORE the snapshot… + const msgs: Array<{ role: string; content: string }> = []; + msgs.push({ role: "user", content: filler("F1") }); + await (await post(msgs)).text(); + msgs.push({ role: "assistant", content: filler("A1") }); + // …turn 2 drops the snapshot mid-history… + msgs.push({ role: "user", content: RT_MSG }); + await (await post(msgs)).text(); + msgs.push({ role: "assistant", content: filler("A2") }); + // …and turns 3–8 grow past it. + for (let i = 3; i <= 8; i++) { + msgs.push({ role: "user", content: filler(`F${i}`) }); + await (await post(msgs)).text(); + msgs.push({ role: "assistant", content: filler(`A${i}`) }); + } + + const refIds = parseRefIds(rig.bodies.at(-1)!); + assert.ok(refIds.length >= 10, `expected >= 10 tagged messages, got ${refIds.length}`); + // Fold from the FIRST tagged message (before the snapshot) up to four + // back from the tail (clears preserveRecentMessages: 3): the range + // covers the snapshot positionally — the old code folds it away. + const startId = refIds[0]!; + const endId = refIds[refIds.length - 4]!; + const toolRes = await fetch(`http://127.0.0.1:${rig.proxyPort}/__bili/plugin/tool`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + conversationId: conv, + tool: "compress", + args: { + topic: "issue2481 fold", + content: [{ startId, endId, topic: "issue2481 fold", summary: "issue2481 fold summary: filler turns F1..F8 were discussed and consumed; nothing else survived this range." }], + }, + }), + }); + const toolJson = (await toolRes.json()) as Record; + assert.ok(toolRes.status === 200 && toolJson.ok === true, `compress must succeed: HTTP ${toolRes.status} ${JSON.stringify(toolJson)}`); + + // Next turn: the rebuilt wire is the assertion surface. + msgs.push({ role: "user", content: filler("F9") }); + await (await post(msgs)).text(); + return { postFoldBody: rig.bodies.at(-1)!, toolJson }; + } finally { + await closeRig(rig); + } +} + +test("dsh lane (#2481): the runtime-context snapshot survives a fold that positionally covers it", async () => { + const { postFoldBody } = await runFoldScenario("dsh", "i2481-dsh"); + assert.ok(postFoldBody.includes("[Compressed conversation section]"), "the fold must have happened (protection may not veto the whole range)"); + assert.ok(postFoldBody.includes("danger-full-access"), "the sandbox policy must survive the fold (hard-protected, stays fully visible)"); + assert.ok(postFoldBody.includes("Approval prompts are disabled"), "the approval policy must survive too (one message carries both sections)"); + // A1 (not F1): the kernel pins the session's FIRST user message on the + // wire even when a block covers it (kernel/src/prune.ts rebuildMessages, + // DESIGN.md §8.1 — strict providers reject user-less conversations), so + // F1 would survive any fold and cannot witness consumption. + assert.ok(!postFoldBody.includes("A1-"), "folded filler before the snapshot must be gone (the fold really consumed its range)"); + assert.ok(!postFoldBody.includes("F5-"), "folded filler after the snapshot must be gone"); +}); + +test("unregistered lane: without the guard the snapshot folds away (pins lane scoping)", async () => { + const { postFoldBody } = await runFoldScenario("test-agent", "i2481-plain"); + assert.ok(postFoldBody.includes("[Compressed conversation section]"), "the fold must have happened"); + assert.ok(!postFoldBody.includes("danger-full-access"), "an unregistered lane has no durable-state guard — the snapshot is ordinary history and folds away"); +}); + +test("session-level: the dsh lane stamps the guard onto the effective config", async () => { + const rig = await startRig(); + try { + const url = `http://127.0.0.1:${rig.proxyPort}/bili/http://127.0.0.1:${rig.upstreamPort}/v1/chat/completions`; + const r = await fetch(url, { + method: "POST", + headers: { "content-type": "application/json", "x-bili-plugin": "dsh", "x-bili-plugin-conversation": "i2481-stamp" }, + body: JSON.stringify({ model: MODEL, max_tokens: 64_000, messages: [{ role: "system", content: MAIN_SYSTEM }, { role: "user", content: RT_MSG }] }), + }); + assert.equal(r.status, 200); + await r.text(); + const s = peekSession("i2481-stamp"); + assert.ok(s, "dsh session exists"); + // The stamped effective config (read by /__bili/plugin/tool) carries the + // guard — proven indirectly: the snapshot got a BLOCKED ref, i.e. it was + // recognized as protected AT ASSIGNMENT TIME on the very first turn. + const sFull = getSession("i2481-stamp"); + const blockedRefs = Object.entries(sFull.state.messageRefs.byRaw).filter(([, ref]) => ref === "BLOCKED").length; + assert.ok(blockedRefs >= 1, "the snapshot message must carry a BLOCKED ref (never advertised, never foldable)"); + } finally { + await closeRig(rig); + } +});