From 20446637019809efcbffa95a0474fc133e07db4b Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 13 Oct 2026 00:14:43 +0800 Subject: [PATCH 1/6] persona fp: neutralize tool prompts before fingerprinting (#2917) The dsh host renders the plugin manifest's tool descriptions into the main system message, so the persona fingerprint keyed on strings bili itself controls. Two ambient events forked the main lane off the raw key (zero-fold ghost session, folds unreachable, preflight unfold dies): - a bili upgrade that rewords a tool description (kernel 540f44028, compress 55473->55496 chars; #2917 restart race: old prompt claimed, new prompt forked |sub:, 14MB unfold 502'd in preflight) - a user installing a plugin mid-session (new tool lines) Tool prompts are ambient configuration, not conversation identity (owner rule 2026-10-12): neutralizeToolPrompts drops every system line containing a request-declared tool description before fingerprinting, anchor storage, and the #2601 model-drift line-diff. Line granularity so the tool-name remnant disappears (a plugin install must MATCH, not migrate). Wrapped renders fail containment and stay conservative. A real persona edit (AGENTS.md) and the review persona still fork; #2601 absorption now survives a simultaneous tool rewrite. AGENTS.md 2.11 records the principle. --- AGENTS.md | 1 + src/persona-anchor.ts | 58 ++++++- src/server/handle.ts | 4 + ...sue2917-tool-prompt-neutralization.test.ts | 152 ++++++++++++++++++ 4 files changed, 209 insertions(+), 6 deletions(-) create mode 100644 tests/issue2917-tool-prompt-neutralization.test.ts diff --git a/AGENTS.md b/AGENTS.md index a2fc3109b4..31693977ec 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -48,6 +48,7 @@ The full file-by-file map lives in [reference/architecture.md](reference/archite 9. **Hosts that reuse ONE session id across personas get id + system-hash session keys ("hash 不一样自动分裂")** — when a plugin host stamps the SAME conversation id on every model request of a session INCLUDING auxiliary personas (dsh auto-review `classifyRisk()`: fixed REVIEW_POLICY system + a fresh flattened blob before every tool call — #1916/#1307/#1314), those auxiliary requests must be keyed by `subagentNamespace(id, systemText)` so the persona forks onto its own `|sub:` session instead of overwriting the main session's baseline/snapshots. The FIRST system seen under the id keeps the raw key (kernel anchor), so main turns never fork; an empty system is non-anchoring (verbatim); SIDE REQUESTS never claim the anchor either — dsh's title-gen sidecar fires at session start before/concurrent with the first main turn, and claiming it would fork the whole main conversation onto `|sub:` while every host-stamped ACP management call (compress/decompress/acp_status) routes into the ghost's empty session and fails forever (#2156/#2160; the `sideRequestLike` gate in `src/server.ts` mirrors the #388 passthrough predicate). This is an EVIDENCE-PERMITLIST (`dshPersonaFingerprintApplies` in `src/session-id.ts`), the same discipline as the instructions fingerprint (#1104/#1107): do NOT enable it wholesale — for everyone else system drift mid-id means "same conversation, evolved", and forking resets compression for no defending bug (#1106). A future host found reusing session ids across personas gets added to that predicate WITH traffic evidence (shape + stability proof: the host's main system must be session-stable, e.g. dsh composes it once per session and puts volatile time-context in a USER message). The fork must record itself under its suffixed id (`personaForked` → `recordPluginSession`) so the single-valued conversations map keeps the raw key owned by the main session (#970 discipline). Tests: `tests/dsh-persona-fingerprint.test.ts`. 10. **Thinking-family blocks are signature-verified — NEVER rewrite them (#1960)** — Anthropic `thinking`/`redacted_thinking` blocks and Gemini `thoughtSignature` parts are verified byte-for-byte when the latest assistant message is replayed ("thinking blocks ... cannot be modified"). The bytes the proxy forwards become the client's persisted history, and the bytes the loop accumulates become the re-request rebuild — BOTH must stay verbatim. Any transformation (tag/marker stripping, dedup, trimming, re-laying-out block order, dropping empty segments) desynchronizes text from signature and bricks the session: first on the in-turn re-request, then on every subsequent request via the client's echo. #1882 put a prose filter on the thinking channel and it was exactly this bug. Treat ANY future change touching thinking-family payloads as high-risk: it needs loop-level byte-equality tests (re-request body AND client-visible stream) on both signed wires, not just adapter-level ones. The prose filters (#206/#1881) are for the TEXT channel only. +11. **工具提示词是环境配置,不参与会话身份 (tool prompts are ambient config, ignored by session identity — owner rule, 2026-10-12, #2917)** — the dsh host renders the plugin manifest's tool descriptions INTO the main system message, so the persona fingerprint would otherwise key on strings bili itself controls: an upgrade that rewords a tool description (kernel 540f44028, compress 55473→55496 chars — #2917: restart race claimed the raw key with the OLD prompt, the NEW prompt forked `|sub:` with zero folds and a 14MB unfold died in preflight) or a user installing a plugin mid-session (new tool lines) would BOTH fork the main lane off its compression state. Rule: `neutralizeToolPrompts` (src/persona-anchor.ts) drops every system line containing a request-declared tool description BEFORE fingerprinting, anchor storage, and #2601 model-drift line-diff — tool-prompt churn is invisible to session identity by construction. Line granularity (not substring) so the tool-name remnant disappears too; wrapped/reformatted renders fail the containment and stay conservative; a system that empties out entirely passes through un-anchored. A REAL persona edit (AGENTS.md) still forks — tool prompts must be ignored, not the whole system. Tests: `tests/issue2917-tool-prompt-neutralization.test.ts`. ### Install-Lane & Update-Ownership Contract (#1196) diff --git a/src/persona-anchor.ts b/src/persona-anchor.ts index 005d82fd75..8954d307f4 100644 --- a/src/persona-anchor.ts +++ b/src/persona-anchor.ts @@ -48,6 +48,44 @@ import { prefixAffinity } from "./prefix-affinity.js"; const anchors = new Map(); +/** #2917: request-declared tool descriptions — anthropic + * {name,description}, openai chat {type:"function",function:{description}}, + * Responses {type:"function",name,description}. Short strings (<16 + * chars) are skipped: removing a tiny fragment is noise, not signal. */ +function toolDescriptions(tools: unknown): string[] { + if (!Array.isArray(tools)) return []; + const out: string[] = []; + for (const t of tools) { + if (t === null || typeof t !== "object") continue; + const o = t as Record; + const fn = o.function as Record | undefined; + const desc = + typeof o.description === "string" ? o.description : typeof fn?.description === "string" ? fn.description : undefined; + if (desc !== undefined && desc.trim().length >= 16) out.push(desc); + } + return out; +} + +/** #2917: tool prompts are ambient configuration, not conversation + * identity. bili's own upgrades rewrite tool descriptions (kernel 540f44028 + * reworded the compress tool mid-#2917-session, 55473→55496 chars) and + * plugin installs add tools mid-session; neither event may fork the main + * lane off the raw key. Every line of the system text that contains a + * request-declared tool description is DROPPED before fingerprinting and + * anchor storage — the dsh host renders the manifest's description strings + * into whole system lines ("- compress: "), so line-granular + * removal also erases the tool-name remnant a pure substring cut would + * leave behind (a plugin install would otherwise show up as an extra + * remnant line and drift the fingerprint). A wrapped or reformatted render + * spans lines and simply fails to match — conservative, the fragment stays + * in the hash. */ +export function neutralizeToolPrompts(systemText: string, tools: unknown): string { + const descs = toolDescriptions(tools); + if (descs.length === 0) return systemText; + const kept = systemText.split("\n").filter((line) => !descs.some((d) => line.includes(d))); + return kept.join("\n"); +} + function personaFingerprint(systemText: string): string { return createHash("sha256").update(systemText, "utf8").digest("hex").slice(0, 16); } @@ -110,12 +148,19 @@ export function resolvePersonaKey( systemText: string, messages: unknown[], model?: string, + tools?: unknown, ): PersonaKeyResolution { if (!systemText) return { key: rawId, action: "passthrough" }; - const fp = personaFingerprint(systemText); + // #2917: strip the request's own tool descriptions before any identity + // comparison — anchor, fp, and modelDriftAbsorbed all see the neutralized + // text, so a tool-description rewrite (upgrade) or a new tool (plugin + // install) cannot change the fingerprint. + const text = neutralizeToolPrompts(systemText, tools); + if (!text.trim()) return { key: rawId, action: "passthrough" }; + const fp = personaFingerprint(text); const anchored = anchors.get(rawId); if (anchored === undefined) { - anchors.set(rawId, { fp, system: systemText, model }); + anchors.set(rawId, { fp, system: text, model }); return { key: rawId, action: "claim" }; } if (anchored.fp === fp) { @@ -131,11 +176,11 @@ export function resolvePersonaKey( return { key: rawId, action: "match" }; } if (prefixAffinity.chainContinues(messages, rawId)) { - anchors.set(rawId, { fp, system: systemText, model }); + anchors.set(rawId, { fp, system: text, model }); return { key: rawId, action: "migrate" }; } - if (modelDriftAbsorbed(anchored, systemText, model)) { - anchors.set(rawId, { fp, system: systemText, model }); + if (modelDriftAbsorbed(anchored, text, model)) { + anchors.set(rawId, { fp, system: text, model }); return { key: rawId, action: "migrate-model" }; } return { key: `${rawId}|sub:${fp}`, action: "fork" }; @@ -157,10 +202,11 @@ export function personaNamespace( messages: unknown, log: (level: "info" | "warn" | "error", message: string) => void, model?: string, + tools?: unknown, ): string { const list = Array.isArray(messages) ? messages : []; const text = typeof systemText === "string" && systemText.trim().length > 0 ? systemText : ""; - const res = resolvePersonaKey(rawId, text, list, model); + const res = resolvePersonaKey(rawId, text, list, model, tools); if (res.action === "migrate") { log("info", `[persona] persona text changed mid-conversation but the history continues ${rawId}'s chain — anchor migrated, compression state stays on the raw key (#2241/#2250)`); } else if (res.action === "migrate-model") { diff --git a/src/server/handle.ts b/src/server/handle.ts index 271299d1aa..7a6fa27955 100644 --- a/src/server/handle.ts +++ b/src/server/handle.ts @@ -822,6 +822,7 @@ async function handleRequest( (parsed as AnthropicRequestBody).messages, log, pluginReportedModel(req.headers), + (parsed as AnthropicRequestBody).tools, ) : anthropicIdentity?.value ?? anthropicSignal) : protocol === "openai" @@ -832,6 +833,7 @@ async function handleRequest( (parsed as OpenAIRequestBody).messages, log, pluginReportedModel(req.headers), + (parsed as OpenAIRequestBody).tools, ) : openaiIdentity?.value ?? openaiSignal) : codexTurn @@ -854,6 +856,7 @@ async function handleRequest( (parsed as ResponsesRequestBody).input, log, pluginReportedModel(req.headers), + (parsed as ResponsesRequestBody).tools, ) : opts.stableSystemAnchor && pluginAgentHeader(req.headers) === undefined // #1085: with anchoring on (plain-proxy mode only — see the @@ -891,6 +894,7 @@ async function handleRequest( (parsed as ResponsesRequestBody).input, log, pluginReportedModel(req.headers), + (parsed as ResponsesRequestBody).tools, ) : (responsesIdentity?.value ?? conversationSignalResponses(parsed as ResponsesRequestBody, convHeader))) : (responsesIdentity?.value ?? conversationSignalResponses(parsed as ResponsesRequestBody, convHeader)); diff --git a/tests/issue2917-tool-prompt-neutralization.test.ts b/tests/issue2917-tool-prompt-neutralization.test.ts new file mode 100644 index 0000000000..39c772e2d0 --- /dev/null +++ b/tests/issue2917-tool-prompt-neutralization.test.ts @@ -0,0 +1,152 @@ +// #2917: tool prompts are ambient configuration, not conversation +// identity. The dsh host renders the plugin manifest's tool descriptions +// INTO the main system message; bili's own upgrades rewrite those strings +// (kernel 540f44028 reworded the compress tool, 55473→55496 chars — only +// the tool line changed) and users install plugins mid-session (new tool +// lines appear). Neither event may fork the main lane off the raw key: +// the persona fingerprint hashes the system text with every +// request-declared tool description REMOVED. A real persona edit +// (AGENTS.md) and the review persona still fork; #2601 model-drift +// absorption keeps working and now survives a simultaneous tool rewrite. +import test from "node:test"; +import assert from "node:assert/strict"; +import path from "node:path"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { createHash } from "node:crypto"; + +// Hermetic state dirs BEFORE importing the server modules (#2601 idiom). +const testRoot = mkdtempSync(path.join(tmpdir(), "bc-2917-toolprompt-")); +for (const key of ["XDG_STATE_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_CONFIG_HOME"]) process.env[key] = testRoot; + +const { prefixAffinity } = await import("../src/prefix-affinity.ts"); +const { resolvePersonaKey, personaAnchorOf, neutralizeToolPrompts, resetPersonaAnchorsForTest } = await import( + "../src/persona-anchor.ts" +); + +test.after(() => rmSync(testRoot, { recursive: true, force: true })); + +// The #2917 shape: a long persona text with the manifest's tool +// descriptions rendered in (the real system is ~55K chars / 1175 lines; +// only the tool line changes across the upgrade). +const DESC_V1 = "Compress the conversation history into a summary. Target the exchange graph, no JSON structure required."; +const DESC_V2 = + "Compress the conversation history into a summary. Target the exchange graph, preserving every open question, no JSON structure required."; +const DESC_SEARCH = "Search the workspace for a symbol or free-text query and return the ranked matches with line numbers."; + +const systemWith = (...toolLines: string[]): string => + `You are DeepSeek Harness, the main coding agent.\nModel: GLM-4.6.\n` + + toolLines.map((d) => `- ${d}`).join("\n") + + `\nWorkspace: /tmp.\nAnswer in the user's language.`; + +const SYSTEM_V1 = systemWith(`compress: ${DESC_V1}`); +const SYSTEM_V2 = systemWith(`compress: ${DESC_V2}`); +const SYSTEM_PLUGIN = systemWith(`compress: ${DESC_V2}`, `search: ${DESC_SEARCH}`); + +const TOOLS_V1 = [{ name: "compress", description: DESC_V1 }]; +const TOOLS_V2 = [{ name: "compress", description: DESC_V2 }]; +const TOOLS_PLUGIN = [...TOOLS_V2, { name: "search", description: DESC_SEARCH }]; + +const NEUTRALIZED = `You are DeepSeek Harness, the main coding agent.\nModel: GLM-4.6.\nWorkspace: /tmp.\nAnswer in the user's language.`; +const fpOf = (s: string): string => createHash("sha256").update(s, "utf8").digest("hex").slice(0, 16); +const forkKey = (conv: string, system: string): string => `${conv}|sub:${fpOf(system)}`; + +const msgs = (n: number, tag: string): { role: string; content: string }[] => + Array.from({ length: n }, (_, i): { role: string; content: string } => ({ + role: i % 2 === 0 ? "user" : "assistant", + content: `${tag}-${i + 1}-` + "z".repeat(120), + })); + +function seed(conv: string, chain: { role: string; content: string }[]): void { + resetPersonaAnchorsForTest(); + prefixAffinity.forget(conv); + const fp = prefixAffinity.chainFingerprint(chain); + assert.ok(fp, "chain fingerprint exists"); + prefixAffinity.note(conv, fp.depth, fp.tailHash, fp.itemHashes, true); +} + +test("neutralizeToolPrompts: removes descriptions from all three wire shapes", () => { + // anthropic / responses flat shape + assert.equal(neutralizeToolPrompts(SYSTEM_V1, TOOLS_V1), NEUTRALIZED); + // openai chat nested shape + const nested = [{ type: "function", function: { name: "compress", description: DESC_V1 } }]; + assert.equal(neutralizeToolPrompts(SYSTEM_V1, nested), NEUTRALIZED); + // multiple tools, dedup, non-objects and short strings ignored + const noisy = [null, 7, "x", { description: "short" }, TOOLS_V1[0], TOOLS_V1[0]]; + assert.equal(neutralizeToolPrompts(SYSTEM_V1, noisy), NEUTRALIZED); + // absent description stays conservative (fragment remains) + assert.equal(neutralizeToolPrompts(SYSTEM_V1, undefined), SYSTEM_V1); +}); + +test("#2917 replay: bili upgrade rewrites the compress description mid-conversation — anchor MATCHES, no fork", () => { + const conv = "2917-upgrade"; + const chainA = msgs(6, "a"); + seed(conv, chainA); + // restart: first arrival claims with the OLD rendered prompt + OLD tools + assert.deepEqual(resolvePersonaKey(conv, SYSTEM_V1, chainA, "glm-4.6", TOOLS_V1), { key: conv, action: "claim" }); + // 0.35s later the NEW system text arrives with the NEW tools declaration + assert.deepEqual(resolvePersonaKey(conv, SYSTEM_V2, chainA, "glm-4.6", TOOLS_V2), { key: conv, action: "match" }); + assert.equal(personaAnchorOf(conv), fpOf(NEUTRALIZED), "fp is the neutralized text"); +}); + +test("plugin install adds a tool mid-conversation — anchor MATCHES, no fork", () => { + const conv = "2917-plugin"; + const chainA = msgs(6, "p"); + seed(conv, chainA); + assert.deepEqual(resolvePersonaKey(conv, SYSTEM_V2, chainA, "glm-4.6", TOOLS_V2), { key: conv, action: "claim" }); + // user installs a plugin: a new tool line appears in the system text + // AND a new declaration rides the tools array. + assert.deepEqual(resolvePersonaKey(conv, SYSTEM_PLUGIN, chainA, "glm-4.6", TOOLS_PLUGIN), { key: conv, action: "match" }); + // and the old build (no search tool) still matches after that + assert.deepEqual(resolvePersonaKey(conv, SYSTEM_V2, chainA, "glm-4.6", TOOLS_V2), { key: conv, action: "match" }); +}); + +test("a REAL persona edit still forks (tool neutralization must not swallow persona drift)", () => { + const conv = "2917-persona-edit"; + const chainA = msgs(6, "e"); + seed(conv, chainA); + assert.deepEqual(resolvePersonaKey(conv, SYSTEM_V2, chainA, "glm-4.6", TOOLS_V2), { key: conv, action: "claim" }); + // AGENTS.md edit rewrites a persona line AND the history is fresh (new + // task reusing the id) — the designed fork must survive. + const edited = SYSTEM_V2.replace("Answer in the user's language.", "Always answer in Chinese."); + const fresh = msgs(2, "fresh-e"); + assert.deepEqual(resolvePersonaKey(conv, edited, fresh, "glm-4.6", TOOLS_V2), { + key: forkKey(conv, neutralizeToolPrompts(edited, TOOLS_V2)), + action: "fork", + }); +}); + +test("review persona (different system, no shared tool text) still forks", () => { + const conv = "2917-review"; + const chainA = msgs(6, "r"); + seed(conv, chainA); + assert.deepEqual(resolvePersonaKey(conv, SYSTEM_V2, chainA, "glm-4.6", TOOLS_V2), { key: conv, action: "claim" }); + const reviewSystem = "You are the final authorization reviewer for exactly one pending tool call.\nAnswer with one word."; + const reviewBlob = msgs(1, "review-blob"); + assert.deepEqual(resolvePersonaKey(conv, reviewSystem, reviewBlob, "glm-4.6", TOOLS_V2), { + key: forkKey(conv, reviewSystem), + action: "fork", + }); +}); + +test("#2601 model-switch absorption survives a simultaneous tool-description rewrite", () => { + const conv = "2917-model-and-tool"; + const chainA = msgs(6, "m"); + seed(conv, chainA); + const sysA = systemWith(`compress: ${DESC_V1}`).replace("GLM-4.6", "GLM-4.6"); + assert.deepEqual(resolvePersonaKey(conv, sysA, chainA, "glm-4.6", TOOLS_V1), { key: conv, action: "claim" }); + // model line change + tool description change in the same window, with + // a discontinued chain (the #2601 residual conjunction): neutralization + // makes the tool line IDENTICAL on both sides, so the line-diff is + // confined to the model identity lines → absorbed. + const sysB = systemWith(`compress: ${DESC_V2}`).replace("GLM-4.6", "GLM-5.3"); + const fresh = msgs(2, "fresh-m"); + assert.deepEqual(resolvePersonaKey(conv, sysB, fresh, "glm-5.3", TOOLS_V2), { key: conv, action: "migrate-model" }); +}); + +test("a system text that is ONLY tool prompts passes through un-anchored", () => { + assert.deepEqual(resolvePersonaKey("2917-passthrough", `- ${DESC_V1}`, [], undefined, TOOLS_V1), { + key: "2917-passthrough", + action: "passthrough", + }); +}); From 32cf42d0c07170b3cea085df828f321756adf40b Mon Sep 17 00:00:00 2001 From: ework-agent Date: Tue, 13 Oct 2026 00:36:59 +0800 Subject: [PATCH 2/6] test(#2917): pin the openai-lane persona tools wiring end-to-end MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The four handle.ts call sites pass parsed.tools as an OPTIONAL positional arg into personaNamespace() — dropping it compiles clean and every unit test stays green, silently disabling the neutralization for that lane. This e2e drives real requests through startServer on the dsh/openai lane with a DISCONTINUOUS history between claim and rewrite, so only the MATCH rung can keep the raw key (the migrate rung cannot rescue broken wiring). Negative control: a real persona edit in the same shape still forks. Fixture note: each request carries a host action tool alongside the ACP tool — a bili-tools-only declaration is demoted via #1897 (leaked-tools side passthrough) before persona resolution runs. --- ...sue2917-tool-prompt-neutralization.test.ts | 160 ++++++++++++++++++ 1 file changed, 160 insertions(+) diff --git a/tests/issue2917-tool-prompt-neutralization.test.ts b/tests/issue2917-tool-prompt-neutralization.test.ts index 39c772e2d0..5f7aa081f5 100644 --- a/tests/issue2917-tool-prompt-neutralization.test.ts +++ b/tests/issue2917-tool-prompt-neutralization.test.ts @@ -11,9 +11,12 @@ import test from "node:test"; import assert from "node:assert/strict"; import path from "node:path"; +import http from "node:http"; +import { once } from "node:events"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { createHash } from "node:crypto"; +import type { ProxyOptions } from "../src/config.ts"; // Hermetic state dirs BEFORE importing the server modules (#2601 idiom). const testRoot = mkdtempSync(path.join(tmpdir(), "bc-2917-toolprompt-")); @@ -150,3 +153,160 @@ test("a system text that is ONLY tool prompts passes through un-anchored", () => action: "passthrough", }); }); + +// --------------------------------------------------------------------------- +// Server-level wiring (review addition): handle.ts passes `tools` into +// personaNamespace as an OPTIONAL positional arg — dropping it compiles +// clean and the unit tests above stay green. Pin the openai lane (dsh's +// wire) end-to-end on a DISCONTINUOUS history so only the MATCH rung can +// keep the raw key; a real persona edit in the same shape must still fork +// (negative control, so the match cannot pass trivially). +// --------------------------------------------------------------------------- + +const WIRE_MODEL = "claude-sonnet-4-5"; +const WIRE_CONV = "2917-wire-openai"; + +async function startWireRig(): Promise<{ url: string; close: () => Promise }> { + const { startServer } = await import("../src/server.ts"); + const { defaultConfig } = await import("acp-kernel"); + const { SessionStore, _setStoreForTest } = await import("../src/persist.ts"); + const { _setForTest: setRegistryForTest } = await import("../src/registry.ts"); + const { _resetPluginStateForTest } = await import("../src/plugin.ts"); + const { _resetSessionsForTest } = await import("../src/session.ts"); + + const upstream = http.createServer((req, res) => { + let b = ""; + req.on("data", (c: Buffer) => (b += c.toString("utf8"))); + req.on("end", () => { + 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(); + 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), + 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"); + const proxyPort = (proxy.address() as { port: number }).port; + return { + url: `http://127.0.0.1:${proxyPort}/bili/http://127.0.0.1:${upstreamPort}/v1/chat/completions`, + close: async () => { + proxy.close(); + await once(proxy, "close"); + upstream.close(); + await once(upstream, "close"); + }, + }; +} + +test("e2e openai lane wiring: rewrite rides body.tools → MATCH on raw key; persona edit in the same shape still forks", async () => { + const { getSession, peekSession } = await import("../src/session.ts"); + resetPersonaAnchorsForTest(); + prefixAffinity.forget(WIRE_CONV); + + const rig = await startWireRig(); + try { + const headers: Record = { + "content-type": "application/json", + "x-bili-plugin": "dsh", + "x-bili-plugin-conversation": WIRE_CONV, + }; + const oiTool = (name: string, description: string) => ({ + type: "function", + function: { name, description, parameters: { type: "object", properties: {} } }, + }); + // A bili ACP tool alone demotes the request via #1897 (leaked-tools + // side passthrough) before persona resolution runs — real dsh main + // turns always carry host action tools alongside the ACP tools. + const HOST_TOOL = oiTool("bash", "Run a shell command in the workspace"); + + // Claim with the v1 render + v1 tools declaration. + const r1 = await fetch(rig.url, { + method: "POST", + headers, + body: JSON.stringify({ + model: WIRE_MODEL, + max_tokens: 64_000, + tools: [HOST_TOOL, oiTool("compress", DESC_V1)], + messages: [{ role: "system", content: SYSTEM_V1 }, ...msgs(6, "w")], + }), + }); + assert.equal(r1.status, 200); + await r1.text(); + assert.equal(getSession(WIRE_CONV)?.stats.requests, 1, "claim lands on the raw key"); + + // Upgrade shape: v2 render + v2 declaration with a DISCONTINUOUS + // (fresh) history — isolates the MATCH rung. If handle.ts dropped + // `tools`, the fingerprints differ and no other rung rescues the key. + const r2 = await fetch(rig.url, { + method: "POST", + headers, + body: JSON.stringify({ + model: WIRE_MODEL, + max_tokens: 64_000, + tools: [HOST_TOOL, oiTool("compress", DESC_V2)], + messages: [{ role: "system", content: SYSTEM_V2 }, ...msgs(2, "w-fresh")], + }), + }); + assert.equal(r2.status, 200); + await r2.text(); + assert.equal(getSession(WIRE_CONV)?.stats.requests, 2, "rewritten description matched the raw key end-to-end"); + assert.equal(peekSession(forkKey(WIRE_CONV, SYSTEM_V2)), undefined, "no ghost under the un-neutralized fp"); + assert.equal(peekSession(forkKey(WIRE_CONV, NEUTRALIZED)), undefined, "no ghost under the neutralized fp either"); + + // Negative control: a REAL persona edit (non-tool line) in the same + // shape must still fork — proves the match above is not trivial. + const edited = SYSTEM_V2.replace("Answer in the user's language.", "Always answer in Chinese."); + const r3 = await fetch(rig.url, { + method: "POST", + headers, + body: JSON.stringify({ + model: WIRE_MODEL, + max_tokens: 64_000, + tools: [HOST_TOOL, oiTool("compress", DESC_V2)], + messages: [{ role: "system", content: edited }, ...msgs(2, "w-edit")], + }), + }); + assert.equal(r3.status, 200); + await r3.text(); + assert.ok( + peekSession(forkKey(WIRE_CONV, neutralizeToolPrompts(edited, [HOST_TOOL, oiTool("compress", DESC_V2)]))), + "persona edit forks onto its own namespace", + ); + assert.equal(getSession(WIRE_CONV)?.stats.requests, 2, "persona edit did not touch the raw session"); + } finally { + await rig.close(); + } +}); From 36505d40fe0e78df2f21035aacea6416f055810b Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Tue, 13 Oct 2026 00:42:32 +0800 Subject: [PATCH 3/6] order-primary session resolution: order+id claim, shape guard rails (#2944) src/session-resolve.ts implements the #2944 rule ALONGSIDE persona-anchor.ts (no deletion, no server switch-over): a client-minted unambiguous id plus an intact order skeleton (content-blind per-position kind sequence) claims the same session - 50% mid-conversation content churn cannot fork the main lane. Shallow traffic (no assistant turns) is always derived (|sub:aux, #1916 race dead); head truncation re-anchors; deep strangers park at |sub:task. tests/issue2944-session-resolve.test.ts pins BOTH implementations with the same corpus: the old fp ladder is characterized FIRST (charting pins), the new resolver runs the same inputs, designed divergences documented per row. Special proofs: P1 50% churn same order+length -> same session; P2 review blob never claims raw; P3 truncated head -> raw + re-anchor; P5 deep main-shaped stranger -> derived-task. AGENTS.md Key Design Decision #12. --- AGENTS.md | 2 + src/session-resolve.ts | 139 ++++++++++++++++++ tests/issue2944-session-resolve.test.ts | 178 ++++++++++++++++++++++++ 3 files changed, 319 insertions(+) create mode 100644 src/session-resolve.ts create mode 100644 tests/issue2944-session-resolve.test.ts diff --git a/AGENTS.md b/AGENTS.md index 31693977ec..1a800804ac 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,6 +50,8 @@ The full file-by-file map lives in [reference/architecture.md](reference/archite 10. **Thinking-family blocks are signature-verified — NEVER rewrite them (#1960)** — Anthropic `thinking`/`redacted_thinking` blocks and Gemini `thoughtSignature` parts are verified byte-for-byte when the latest assistant message is replayed ("thinking blocks ... cannot be modified"). The bytes the proxy forwards become the client's persisted history, and the bytes the loop accumulates become the re-request rebuild — BOTH must stay verbatim. Any transformation (tag/marker stripping, dedup, trimming, re-laying-out block order, dropping empty segments) desynchronizes text from signature and bricks the session: first on the in-turn re-request, then on every subsequent request via the client's echo. #1882 put a prose filter on the thinking channel and it was exactly this bug. Treat ANY future change touching thinking-family payloads as high-risk: it needs loop-level byte-equality tests (re-request body AND client-visible stream) on both signed wires, not just adapter-level ones. The prose filters (#206/#1881) are for the TEXT channel only. 11. **工具提示词是环境配置,不参与会话身份 (tool prompts are ambient config, ignored by session identity — owner rule, 2026-10-12, #2917)** — the dsh host renders the plugin manifest's tool descriptions INTO the main system message, so the persona fingerprint would otherwise key on strings bili itself controls: an upgrade that rewords a tool description (kernel 540f44028, compress 55473→55496 chars — #2917: restart race claimed the raw key with the OLD prompt, the NEW prompt forked `|sub:` with zero folds and a 14MB unfold died in preflight) or a user installing a plugin mid-session (new tool lines) would BOTH fork the main lane off its compression state. Rule: `neutralizeToolPrompts` (src/persona-anchor.ts) drops every system line containing a request-declared tool description BEFORE fingerprinting, anchor storage, and #2601 model-drift line-diff — tool-prompt churn is invisible to session identity by construction. Line granularity (not substring) so the tool-name remnant disappears too; wrapped/reformatted renders fail the containment and stay conservative; a system that empties out entirely passes through un-anchored. A REAL persona edit (AGENTS.md) still forks — tool prompts must be ignored, not the whole system. Tests: `tests/issue2917-tool-prompt-neutralization.test.ts`. +12. **顺序+自铸 id 即可认领会话,hash 只是护栏 (order+id claim, hash as guard — owner rule, 2026-10-12, #2944)** — the session-identity layer must not key on representation: #2847/#2821/#2917 were all "content representation churn → ghost fork (`|sub:` with zero folds) → giant unfold → doomed 502". Rule ①: a client-minted, UNAMBIGUOUS conversation id plus an intact ORDER SKELETON (per-position message-kind sequence: role + tool shape, content-blind) claims the same session — 绝对没有错误, even if 50% of mid-conversation content changed. Rule ②: shallow traffic (no assistant turns — dsh auto-review blob) NEVER claims the raw key; it is always derived (`|sub:aux`), which kills the #1916 restart race without reading a byte of system text. Rule ③: head truncation (native compaction) keeps the raw key and re-anchors (tail window aligns or the id is simply trusted); a deep main-shaped history sharing nothing with the recorded skeleton parks at `|sub:task` — the only hash-shaped guard rails, and they are SHAPE rails, not content rails. System text is not read anywhere in the claim decision. Implementation lives in `src/session-resolve.ts` ALONGSIDE `src/persona-anchor.ts` (the old fp ladder) — the old file is NOT deleted and the server switch-over happens only after the differential corpus in `tests/issue2944-session-resolve.test.ts` (same inputs through both implementations; behavior-compatible rows share one expectation, designed divergences old→new documented per row) stays green. 压缩锚点默认顺序位置,hash 只是参考 — the lower layer (#2939 order-centric reconcile) already carries the same principle. + ### Install-Lane & Update-Ownership Contract (#1196) Every bili presence on a machine follows ONE contract — decide changes against it, not ad hoc: diff --git a/src/session-resolve.ts b/src/session-resolve.ts new file mode 100644 index 0000000000..dc6bc84705 --- /dev/null +++ b/src/session-resolve.ts @@ -0,0 +1,139 @@ +// #2944: order-primary session resolution — the general rule that retires +// the persona-fp ladder (owner rule, 2026-10-12): +// +// 1. 顺序 + sessionid(客户端自生成、无歧义)就可以认领为同一个会话, +// 绝对没有错误 —— 内容一个字不看。 +// 2. 压缩锚点默认顺序位置,hash 只是参考(下层 #2939 order-centric +// reconcile 已经是这个形状)。 +// 3. hash 用来防止压缩导致的漂移、subagents 复用主会话带来的漂移 +// —— 防错认护栏,不参与认领决策。本层唯一的护栏是消息形状: +// 浅 blob(无 assistant 轮)= 辅助 persona,派生 key。 +// 4. 不打膏药:一条通用规则,协议无关,不逐客户端特判。 +// +// This module is the NEW implementation, implemented ALONGSIDE +// src/persona-anchor.ts (the old ladder) — the old file is NOT deleted and +// the server is NOT switched over yet (see #2944 rollout). Both +// implementations are pinned by the same input/output corpus in +// tests/issue2944-session-resolve.test.ts: behavior-compatible rows share +// one expectation; designed divergences are marked old→new per row. +// +// The claim evidence is the ORDER SKELETON — the per-position message KIND +// sequence (role + tool shape), with content completely ignored. A 50% +// mid-conversation content rewrite that keeps order and length is the SAME +// session (#2917/#2821/#2847 family: representation churn must never fork +// the main lane off its folds). The id must be client-minted and +// unambiguous (never reused across conversations) — that is the caller's +// provenance contract; ids that fail it stay on the anonymous ladder +// (prefix-affinity), which is untouched. + +/** Message-kind classification for the order skeleton. Content-blind by + * construction: only role and block shape participate. */ +export function orderKindOf(msg: unknown): string { + if (msg === null || typeof msg !== "object") return "opaque"; + const m = msg as Record; + const role = typeof m.role === "string" ? m.role : "?"; + // Tool turns are their own skeleton cell: a tool_use/tool_call and its + // tool_result keep distinct kinds so alternating tool exchanges align + // as tool cells, not prose cells. + const content = m.content; + if (Array.isArray(content)) { + const types = content + .map((b) => (b !== null && typeof b === "object" && typeof (b as Record).type === "string" ? ((b as Record).type as string) : "")) + .filter((s: string) => s.length > 0) + .join(","); + if (types.length > 0) return `${role}:${types}`; + } + if (typeof m.tool_calls === "object" && m.tool_calls !== null) return `${role}:tool_calls`; + if (typeof m.tool_call_id === "string") return `${role}:tool_result`; + return role; +} + +export function orderKindsOf(history: unknown): string[] { + const list = Array.isArray(history) ? history : []; + return list.map(orderKindOf); +} + +function mainShaped(kinds: string[]): boolean { + // A main conversation has assistant turns and at least a few cells; + // an aux persona (dsh auto-review: one flattened user blob) has + // neither. This is the ONLY aux/persona discriminator — no system + // text, no content hash. + if (kinds.length < 3) return false; + return kinds.some((k) => k.startsWith("assistant")); +} + +const AUX_MIN_TAIL = 8; + +function tailAligns(kinds: string[], recorded: string[]): boolean { + const window = Math.min(AUX_MIN_TAIL, kinds.length, recorded.length); + if (window === 0) return false; + for (let i = 1; i <= window; i++) { + if (kinds[kinds.length - i] !== recorded[recorded.length - i]) return false; + } + return true; +} + +export type SessionOrderResolution = { + key: string; + action: "claim" | "continue" | "reanchor" | "derived-aux" | "derived-task"; + /** Human-readable reason for the derived/reanchor branches (log surface). */ + reason?: string; +}; + +/** In-memory order skeletons, same lifetime as the old anchors map. */ +const skeletons = new Map(); + +/** #2944 order-primary resolution. `rawId` MUST be a client-minted, + * unambiguous conversation id (caller's provenance contract). */ +export function resolveSessionOrder(rawId: string, history: unknown): SessionOrderResolution { + const kinds = orderKindsOf(history); + const recorded = skeletons.get(rawId); + if (recorded === undefined) { + // First sight under the id. A main-shaped history claims the raw + // key; anything else (shallow blob with no assistant turns) is an + // aux persona and NEVER claims — the #1916 review-steals-raw race + // dies here without reading a byte of system text. + if (!mainShaped(kinds)) { + return { key: `${rawId}|sub:aux`, action: "derived-aux", reason: "shallow history with no assistant turns" }; + } + skeletons.set(rawId, kinds); + return { key: rawId, action: "claim" }; + } + if (!mainShaped(kinds)) { + // Aux traffic under an already-claimed id — always derived. + return { key: `${rawId}|sub:aux`, action: "derived-aux", reason: "aux persona reuse of the main id" }; + } + if (kinds.length >= recorded.length) { + const aligns = recorded.every((k, i) => kinds[i] === k); + if (aligns) { + skeletons.set(rawId, kinds); + return { key: rawId, action: "continue" }; + } + if (tailAligns(kinds, recorded)) { + // Same length or grown, prefix diverged, tail aligned: the host + // rewrote the head (native compaction summary / re-anchored + // event log). Trust the id, re-anchor the skeleton. + skeletons.set(rawId, kinds); + return { key: rawId, action: "reanchor", reason: "order tail aligned, head rewritten" }; + } + // Deep main-shaped history sharing nothing with the recorded + // skeleton on an unambiguous id: the guard rail (owner rule 3) — + // derived, never the raw key, until the skeleton is re-established. + return { key: `${rawId}|sub:task`, action: "derived-task", reason: "no order alignment with the recorded skeleton" }; + } + // Shorter than recorded: head truncation (dsh native compaction). The + // tail is the living end of the conversation — tail alignment keeps the + // raw key and re-anchors; even without it the id is unambiguous, so the + // conversation stays raw and the skeleton follows the host's truth. + skeletons.set(rawId, kinds); + return { key: rawId, action: "reanchor", reason: tailAligns(kinds, recorded) ? "truncated head, tail aligned" : "truncated head, id trusted" }; +} + +/** Diagnostic/test surface: the recorded skeleton for an id. */ +export function sessionOrderSkeletonOf(rawId: string): string[] | undefined { + return skeletons.get(rawId); +} + +export function resetSessionOrderForTest(): void { + skeletons.clear(); +} diff --git a/tests/issue2944-session-resolve.test.ts b/tests/issue2944-session-resolve.test.ts new file mode 100644 index 0000000000..63a024bd2b --- /dev/null +++ b/tests/issue2944-session-resolve.test.ts @@ -0,0 +1,178 @@ +// #2944: order-primary session resolution — differential pin. +// +// The SAME scenario corpus runs through BOTH implementations: +// OLD: src/persona-anchor.ts (the fp ladder — behavior pinned FIRST as +// the 瞄点; these assertions must pass against the current file +// untouched) +// NEW: src/session-resolve.ts (order+id claim; content-blind skeleton) +// Rows where the two agree share one expectation; designed divergences +// are marked old→new with the #2944 principle that justifies them. +// +// Special proofs (特殊代码证明) required by the owner: +// P1 50% mid-conversation content churn, same order + same length → +// SAME session (new: continue raw; old: match raw via fp-equal). +// P2 shallow review blob under a claimed id → NEVER claims raw +// (old: fork |sub:fp; new: derived-aux |sub:aux — #1916 race dead). +// P3 head truncation (native compaction) under same id → raw + +// re-anchor (old: match raw via fp-equal rescue; new: reanchor). +// P4 system/tool prompt drift + same chain → raw (old: migrate #2241 / +// #2942 match; new: continue — system text is not read at all). +// P5 deep main-shaped history sharing nothing with the recorded +// skeleton → derived, not raw (guard rail). + +import test from "node:test"; +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +// Hermetic dirs BEFORE imports (same idiom as issue2601 suite). +const XDG = mkdtempSync(join(tmpdir(), "issue2944-")); +process.env.XDG_DATA_HOME = join(XDG, "data"); +process.env.XDG_STATE_HOME = join(XDG, "state"); +process.env.BILI_PERSIST = "0"; +process.env.NODE_ENV = "test"; + +const { prefixAffinity } = await import("../src/prefix-affinity.ts"); +const { resetPersonaAnchorsForTest, resolvePersonaKey } = await import("../src/persona-anchor.ts"); +import { resolveSessionOrder, resetSessionOrderForTest, orderKindsOf } from "../src/session-resolve.ts"; + +const sha = (s: string) => createHash("sha256").update(s).digest("hex").slice(0, 16); + +type Msg = { role: string; content: string }; + +/** Alternating user/assistant turns, ~120 chars each. */ +function msgs(n: number, tag = "m"): Msg[] { + const out: Msg[] = []; + for (let i = 0; i < n; i++) { + const role = i % 2 === 0 ? "user" : "assistant"; + out.push({ role, content: `${tag} #${i} — ${tag} message body with enough prose to be a realistic cell ${"x".repeat(80)}` }); + } + return out; +} + +/** Rewrites the content of every even-indexed message (50% churn) while + * keeping roles, order and length identical. */ +function churn50(list: Msg[]): Msg[] { + return list.map((m, i) => (i % 2 === 0 ? { ...m, content: `REWRITTEN ${i}: completely different words, same slot ${"y".repeat(80)}` } : m)); +} + +// Shared system inputs (the new resolver never reads them — they exist for +// the OLD run to keep the corpus identical). +const BASE_SYSTEM = "You are dsh, a desktop shell agent. " + "ambient config line. ".repeat(40); +const DRIFTED_SYSTEM = BASE_SYSTEM.replace("ambient config line.", "ambient config line (v2 with more words)."); +const REVIEW_SYSTEM = "You are an automated reviewer. Output only XML verdict tags."; +const conv = "session-2944"; + +function seedChain(conv: string, chain: Msg[]) { + resetPersonaAnchorsForTest(); + prefixAffinity.forget(conv); + const fp = prefixAffinity.chainFingerprint(chain); + if (fp) prefixAffinity.note(conv, fp.depth, fp.tailHash, fp.itemHashes, true); +} + +// --------------------------------------------------------------------------- +// OLD resolver: run the corpus against persona-anchor, seeded per scenario +// so each characterization expectation is exactly the current ladder's. +test("old ladder: characterization pins (瞄点)", async (t) => { + // S1: first sight claims raw. + seedChain(conv, msgs(6, "seed")); + assert.equal(resolvePersonaKey(conv, BASE_SYSTEM, msgs(6, "seed")).key, conv); + + // S2: fp equal → match raw. + assert.equal(resolvePersonaKey(conv, BASE_SYSTEM, msgs(10, "seed")).key, conv); + + // S3: fp drift + chain continues → migrate raw (anchor moves). + assert.equal(resolvePersonaKey(conv, DRIFTED_SYSTEM, msgs(10, "seed")).key, conv); + + // S4: fp equal → match raw even though 50% of contents churned. + assert.equal(resolvePersonaKey(conv, DRIFTED_SYSTEM, churn50(msgs(10, "seed"))).key, conv); + + // S5: fp equal → match raw for truncated history. + assert.equal(resolvePersonaKey(conv, DRIFTED_SYSTEM, msgs(6, "seed").slice(3)).key, conv); + + // S6: review blob → fork |sub:. + const blob = msgs(1, "review-blob").map((m) => ({ ...m, role: "user" })); + assert.equal(resolvePersonaKey(conv, REVIEW_SYSTEM, blob).key, `${conv}|sub:${sha(REVIEW_SYSTEM)}`); +}); + +// --------------------------------------------------------------------------- +// NEW resolver: same inputs, order+id semantics. +test("new resolver: same corpus, order+id semantics", async (t) => { + resetSessionOrderForTest(); + + // S1: first sight, main-shaped → claim raw. + assert.equal(resolveSessionOrder(conv, msgs(6, "seed")).key, conv); + + // S2: growth → continue raw. + assert.equal(resolveSessionOrder(conv, msgs(10, "seed")).key, conv); + + // S3: system drift invisible (input IDENTICAL to S2) → continue raw. + const s3 = resolveSessionOrder(conv, msgs(10, "seed")); + assert.equal(s3.key, conv); + assert.equal(s3.action, "continue"); + + // S4 (P1): 50% content churn, same kinds → SAME session. + const s4 = resolveSessionOrder(conv, churn50(msgs(10, "seed"))); + assert.equal(s4.key, conv); + assert.equal(s4.action, "continue"); + + // S5 (P3): truncated head, tail aligns → raw + reanchor. + const s5 = resolveSessionOrder(conv, msgs(6, "seed").slice(3)); + assert.equal(s5.key, conv); + assert.equal(s5.action, "reanchor"); + + // S6 (P2): shallow blob under claimed id → derived-aux. + const blob = msgs(1, "review-blob").map((m) => ({ ...m, role: "user" })); + const s6 = resolveSessionOrder(conv, blob); + assert.equal(s6.key, `${conv}|sub:aux`); + assert.equal(s6.action, "derived-aux"); +}); + +// --------------------------------------------------------------------------- +// P5 guard rail: deep main-shaped history sharing NOTHING with the recorded +// skeleton under the same id → derived-task, never raw. +test("P5: deep main-shaped stranger → derived-task", () => { + resetSessionOrderForTest(); + resolveSessionOrder(conv, msgs(8, "seed")); + // Different parity shape AND different length growth mismatch: build a + // history whose kind sequence diverges from position 1 and never + // re-aligns in the tail window. + const stranger: Msg[] = []; + const roles = ["user", "user", "user", "assistant", "user", "assistant", "user", "assistant", "assistant"]; + roles.forEach((r, i) => stranger.push({ role: r, content: `stranger ${i} ${"z".repeat(60)}` })); + const res = resolveSessionOrder(conv, stranger); + assert.equal(res.key, `${conv}|sub:task`); + assert.equal(res.action, "derived-task"); +}); + +// Aux traffic FIRST (before any main claim) must never claim raw. +test("shallow-first: aux blob on virgin id → derived-aux, raw unclaimed", () => { + resetSessionOrderForTest(); + const blob = msgs(1, "x").map((m) => ({ ...m, role: "user" })); + const res = resolveSessionOrder("session-virgin", blob); + assert.equal(res.action, "derived-aux"); + assert.equal(res.key, "session-virgin|sub:aux"); + // And the main conversation arriving afterwards still claims raw. + const main = resolveSessionOrder("session-virgin", msgs(6, "main")); + assert.equal(main.action, "claim"); + assert.equal(main.key, "session-virgin"); +}); + +// Skeleton is content-blind by construction: kinds of a churned history are +// identical to the original. +test("orderKindsOf ignores content, keeps role/tool shape", () => { + const a = msgs(6, "seed"); + const b = churn50(a); + assert.deepEqual(orderKindsOf(a), orderKindsOf(b)); + const toolTurn = { role: "assistant", content: [{ type: "tool_use", id: "t1", name: "bash", input: {} }] }; + const toolRes = { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "ok" }] }; + assert.equal(orderKindOf2(toolTurn), "assistant:tool_use"); + assert.equal(orderKindOf2(toolRes), "user:tool_result"); +}); + +function orderKindOf2(m: unknown): string { + // re-exported below; use import to avoid duplication + return orderKindsOf([m])[0]; +} From 2479a8a32eaea964e0d593f79911cc05da796607 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Tue, 13 Oct 2026 01:01:36 +0800 Subject: [PATCH 4/6] test(#2944): exercise session-resolve's exported surface through the corpus MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The unused-exports gate failed on orderKindOf / SessionOrderResolution / sessionOrderSkeletonOf — all three exist for the test + switch-over diagnostic surface, so make the corpus consume them instead of waiving: direct orderKindOf assertions (incl. the OpenAI tool_calls/tool_call_id wire shape) replace the local shim, skeleton bookkeeping is pinned after continue/reanchor/claim, and a resolution result carries the exported type. No source change. --- tests/issue2944-session-resolve.test.ts | 28 +++++++++++++++---------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/tests/issue2944-session-resolve.test.ts b/tests/issue2944-session-resolve.test.ts index 63a024bd2b..aa3f8b5ffc 100644 --- a/tests/issue2944-session-resolve.test.ts +++ b/tests/issue2944-session-resolve.test.ts @@ -36,7 +36,7 @@ process.env.NODE_ENV = "test"; const { prefixAffinity } = await import("../src/prefix-affinity.ts"); const { resetPersonaAnchorsForTest, resolvePersonaKey } = await import("../src/persona-anchor.ts"); -import { resolveSessionOrder, resetSessionOrderForTest, orderKindsOf } from "../src/session-resolve.ts"; +import { resolveSessionOrder, resetSessionOrderForTest, orderKindsOf, orderKindOf, sessionOrderSkeletonOf, type SessionOrderResolution } from "../src/session-resolve.ts"; const sha = (s: string) => createHash("sha256").update(s).digest("hex").slice(0, 16); @@ -113,15 +113,19 @@ test("new resolver: same corpus, order+id semantics", async (t) => { assert.equal(s3.key, conv); assert.equal(s3.action, "continue"); - // S4 (P1): 50% content churn, same kinds → SAME session. + // S4 (P1): 50% content churn, same kinds → SAME session. The recorded + // skeleton is content-blind too: the churn leaves it byte-identical. const s4 = resolveSessionOrder(conv, churn50(msgs(10, "seed"))); assert.equal(s4.key, conv); assert.equal(s4.action, "continue"); + assert.deepEqual(sessionOrderSkeletonOf(conv), orderKindsOf(msgs(10, "seed"))); - // S5 (P3): truncated head, tail aligns → raw + reanchor. - const s5 = resolveSessionOrder(conv, msgs(6, "seed").slice(3)); + // S5 (P3): truncated head, tail aligns → raw + reanchor; the skeleton + // follows the host's truth (re-anchored to the truncated kinds). + const s5: SessionOrderResolution = resolveSessionOrder(conv, msgs(6, "seed").slice(3)); assert.equal(s5.key, conv); assert.equal(s5.action, "reanchor"); + assert.deepEqual(sessionOrderSkeletonOf(conv), orderKindsOf(msgs(6, "seed").slice(3))); // S6 (P2): shallow blob under claimed id → derived-aux. const blob = msgs(1, "review-blob").map((m) => ({ ...m, role: "user" })); @@ -154,10 +158,14 @@ test("shallow-first: aux blob on virgin id → derived-aux, raw unclaimed", () = const res = resolveSessionOrder("session-virgin", blob); assert.equal(res.action, "derived-aux"); assert.equal(res.key, "session-virgin|sub:aux"); + // The blob records NOTHING under the raw id — only a main-shaped + // history may establish the skeleton. + assert.equal(sessionOrderSkeletonOf("session-virgin"), undefined); // And the main conversation arriving afterwards still claims raw. const main = resolveSessionOrder("session-virgin", msgs(6, "main")); assert.equal(main.action, "claim"); assert.equal(main.key, "session-virgin"); + assert.deepEqual(sessionOrderSkeletonOf("session-virgin"), orderKindsOf(msgs(6, "main"))); }); // Skeleton is content-blind by construction: kinds of a churned history are @@ -168,11 +176,9 @@ test("orderKindsOf ignores content, keeps role/tool shape", () => { assert.deepEqual(orderKindsOf(a), orderKindsOf(b)); const toolTurn = { role: "assistant", content: [{ type: "tool_use", id: "t1", name: "bash", input: {} }] }; const toolRes = { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "ok" }] }; - assert.equal(orderKindOf2(toolTurn), "assistant:tool_use"); - assert.equal(orderKindOf2(toolRes), "user:tool_result"); + assert.equal(orderKindOf(toolTurn), "assistant:tool_use"); + assert.equal(orderKindOf(toolRes), "user:tool_result"); + // OpenAI wire shape: tool_calls on the assistant, tool_call_id on the reply. + assert.equal(orderKindOf({ role: "assistant", content: "", tool_calls: [{ id: "c1", function: { name: "bash" } }] }), "assistant:tool_calls"); + assert.equal(orderKindOf({ role: "tool", content: "ok", tool_call_id: "c1" }), "tool:tool_result"); }); - -function orderKindOf2(m: unknown): string { - // re-exported below; use import to avoid duplication - return orderKindsOf([m])[0]; -} From cc304247bff8a2c09dd2dd3d11014090203aac9a Mon Sep 17 00:00:00 2001 From: ework-agent Date: Tue, 13 Oct 2026 01:13:37 +0800 Subject: [PATCH 5/6] docs(#2944): add session-resolve.ts + persona-anchor.ts to the module map --- reference/architecture.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/reference/architecture.md b/reference/architecture.md index 33fe32a5ce..09d881707d 100644 --- a/reference/architecture.md +++ b/reference/architecture.md @@ -99,6 +99,8 @@ billion-context/ │ ├── registry-snapshot.json # Bundled full models.dev snapshot (offline floor) │ ├── session.ts # Session model + in-memory store (bounded, MAX_SESSIONS) │ ├── session-id.ts # Session identity: client value verbatim + persona fork fingerprint +│ ├── persona-anchor.ts # Persona fp ladder (old identity layer, retiring per #2944) + tool-prompt neutralization (#2917) +│ ├── session-resolve.ts # Order+id session resolution (new identity layer, #2944; alongside until switch-over) │ ├── session-gc.ts # Session-file GC, opt-in (sessions.gc.* / BILI_SESSION_GC*) (#1082) │ ├── persist.ts # On-disk session persistence (kernel StateStore) │ ├── persist-eperm.ts # EPERM/EACCES write-failure alert layer (#362) @@ -204,7 +206,7 @@ When navigating this codebase, these are the load-bearing entry points: - **Knobs** — every behavior knob resolves through `src/knobs.ts` (env > config file > default, #2030). Never add a new `process.env` read in a leaf module — see AGENTS.md "Environment Variable Discipline". - **Update path** — `src/update.ts` is deliberately self-contained and conservative; it installs via tarball extraction (not `npm install`) to avoid lifecycle-script surprises on user machines. It is load-bearing infrastructure: changes require a no-op validation release first (§5). - **Agent plugins** — `src/agent/*.ts` are thin host-specific adapters; shared logic lives in `src/agent/shared.ts`. Each host has a `-native.ts` bootstrap gate variant. -- **Persistence** — `src/persist.ts` wraps the acp-kernel `StateStore`; `src/session.ts` holds the in-memory session pool. Session identity rules: `src/session-id.ts`. +- **Persistence** — `src/persist.ts` wraps the acp-kernel `StateStore`; `src/session.ts` holds the in-memory session pool. Session identity rules: `src/session-id.ts`; persona-fp ladder `src/persona-anchor.ts` and its order+id successor `src/session-resolve.ts` (#2944, switch-over pending). - **会话派生缓存** — `Session.transient` 持有插件工具视图与诊断请求副本;随会话淘汰释放,也纳入会话对象图的字节计量。它不写入持久化记录或上游协议;诊断截段独立复制 UTF-16 内容,避免保留完整请求底层字符串(#2920)。 - **Wire fidelity** — `src/stream-*.ts` files handle per-protocol streaming transformation. The invariant: never alter upstream protocol shape beyond intended injection (§7.3). - **E2E regression** — `tests/e2e/` contains real-client suites (codex, opencode, pi, dsh) plus hermetic lanes (registry, advisory-rollback, release-canary, opencode WS, image billing); each carries its own skip gate — read the test header for the exact env var. From ce42938a38283de9720844a9a8869fcdae48f85d Mon Sep 17 00:00:00 2001 From: ework-agent Date: Tue, 13 Oct 2026 01:13:37 +0800 Subject: [PATCH 6/6] =?UTF-8?q?docs(#2944):=20#2939=20is=20still=20an=20op?= =?UTF-8?q?en=20PR=20=E2=80=94=20say=20so=20instead=20of=20'already=20land?= =?UTF-8?q?ed'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 2 +- src/session-resolve.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1a800804ac..38e0b3e9bf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,7 +50,7 @@ The full file-by-file map lives in [reference/architecture.md](reference/archite 10. **Thinking-family blocks are signature-verified — NEVER rewrite them (#1960)** — Anthropic `thinking`/`redacted_thinking` blocks and Gemini `thoughtSignature` parts are verified byte-for-byte when the latest assistant message is replayed ("thinking blocks ... cannot be modified"). The bytes the proxy forwards become the client's persisted history, and the bytes the loop accumulates become the re-request rebuild — BOTH must stay verbatim. Any transformation (tag/marker stripping, dedup, trimming, re-laying-out block order, dropping empty segments) desynchronizes text from signature and bricks the session: first on the in-turn re-request, then on every subsequent request via the client's echo. #1882 put a prose filter on the thinking channel and it was exactly this bug. Treat ANY future change touching thinking-family payloads as high-risk: it needs loop-level byte-equality tests (re-request body AND client-visible stream) on both signed wires, not just adapter-level ones. The prose filters (#206/#1881) are for the TEXT channel only. 11. **工具提示词是环境配置,不参与会话身份 (tool prompts are ambient config, ignored by session identity — owner rule, 2026-10-12, #2917)** — the dsh host renders the plugin manifest's tool descriptions INTO the main system message, so the persona fingerprint would otherwise key on strings bili itself controls: an upgrade that rewords a tool description (kernel 540f44028, compress 55473→55496 chars — #2917: restart race claimed the raw key with the OLD prompt, the NEW prompt forked `|sub:` with zero folds and a 14MB unfold died in preflight) or a user installing a plugin mid-session (new tool lines) would BOTH fork the main lane off its compression state. Rule: `neutralizeToolPrompts` (src/persona-anchor.ts) drops every system line containing a request-declared tool description BEFORE fingerprinting, anchor storage, and #2601 model-drift line-diff — tool-prompt churn is invisible to session identity by construction. Line granularity (not substring) so the tool-name remnant disappears too; wrapped/reformatted renders fail the containment and stay conservative; a system that empties out entirely passes through un-anchored. A REAL persona edit (AGENTS.md) still forks — tool prompts must be ignored, not the whole system. Tests: `tests/issue2917-tool-prompt-neutralization.test.ts`. -12. **顺序+自铸 id 即可认领会话,hash 只是护栏 (order+id claim, hash as guard — owner rule, 2026-10-12, #2944)** — the session-identity layer must not key on representation: #2847/#2821/#2917 were all "content representation churn → ghost fork (`|sub:` with zero folds) → giant unfold → doomed 502". Rule ①: a client-minted, UNAMBIGUOUS conversation id plus an intact ORDER SKELETON (per-position message-kind sequence: role + tool shape, content-blind) claims the same session — 绝对没有错误, even if 50% of mid-conversation content changed. Rule ②: shallow traffic (no assistant turns — dsh auto-review blob) NEVER claims the raw key; it is always derived (`|sub:aux`), which kills the #1916 restart race without reading a byte of system text. Rule ③: head truncation (native compaction) keeps the raw key and re-anchors (tail window aligns or the id is simply trusted); a deep main-shaped history sharing nothing with the recorded skeleton parks at `|sub:task` — the only hash-shaped guard rails, and they are SHAPE rails, not content rails. System text is not read anywhere in the claim decision. Implementation lives in `src/session-resolve.ts` ALONGSIDE `src/persona-anchor.ts` (the old fp ladder) — the old file is NOT deleted and the server switch-over happens only after the differential corpus in `tests/issue2944-session-resolve.test.ts` (same inputs through both implementations; behavior-compatible rows share one expectation, designed divergences old→new documented per row) stays green. 压缩锚点默认顺序位置,hash 只是参考 — the lower layer (#2939 order-centric reconcile) already carries the same principle. +12. **顺序+自铸 id 即可认领会话,hash 只是护栏 (order+id claim, hash as guard — owner rule, 2026-10-12, #2944)** — the session-identity layer must not key on representation: #2847/#2821/#2917 were all "content representation churn → ghost fork (`|sub:` with zero folds) → giant unfold → doomed 502". Rule ①: a client-minted, UNAMBIGUOUS conversation id plus an intact ORDER SKELETON (per-position message-kind sequence: role + tool shape, content-blind) claims the same session — 绝对没有错误, even if 50% of mid-conversation content changed. Rule ②: shallow traffic (no assistant turns — dsh auto-review blob) NEVER claims the raw key; it is always derived (`|sub:aux`), which kills the #1916 restart race without reading a byte of system text. Rule ③: head truncation (native compaction) keeps the raw key and re-anchors (tail window aligns or the id is simply trusted); a deep main-shaped history sharing nothing with the recorded skeleton parks at `|sub:task` — the only hash-shaped guard rails, and they are SHAPE rails, not content rails. System text is not read anywhere in the claim decision. Implementation lives in `src/session-resolve.ts` ALONGSIDE `src/persona-anchor.ts` (the old fp ladder) — the old file is NOT deleted and the server switch-over happens only after the differential corpus in `tests/issue2944-session-resolve.test.ts` (same inputs through both implementations; behavior-compatible rows share one expectation, designed divergences old→new documented per row) stays green. 压缩锚点默认顺序位置,hash 只是参考 — the lower layer rides #2939 (order-centric reconcile) — verify its merge state before the switch-over. ### Install-Lane & Update-Ownership Contract (#1196) diff --git a/src/session-resolve.ts b/src/session-resolve.ts index dc6bc84705..270e47653b 100644 --- a/src/session-resolve.ts +++ b/src/session-resolve.ts @@ -4,7 +4,7 @@ // 1. 顺序 + sessionid(客户端自生成、无歧义)就可以认领为同一个会话, // 绝对没有错误 —— 内容一个字不看。 // 2. 压缩锚点默认顺序位置,hash 只是参考(下层 #2939 order-centric -// reconcile 已经是这个形状)。 +// reconcile 同向;PR 未合并——切换前核对其合并状态)。 // 3. hash 用来防止压缩导致的漂移、subagents 复用主会话带来的漂移 // —— 防错认护栏,不参与认领决策。本层唯一的护栏是消息形状: // 浅 blob(无 assistant 轮)= 辅助 persona,派生 key。