diff --git a/.github/workflows/ci-e2e-dsh-native.yml b/.github/workflows/ci-e2e-dsh-native.yml index b12241c834..314956354f 100644 --- a/.github/workflows/ci-e2e-dsh-native.yml +++ b/.github/workflows/ci-e2e-dsh-native.yml @@ -25,7 +25,10 @@ jobs: # bundle API surface must not drift under this suite. Bump deliberately # after re-running the suite locally on the new version. - name: Install dsh CLI - run: npm i -g @deepseek-ai/dsh@0.1.5-rc.3 + # 0.2.0-rc.2: the persona lane needs `--session-id` (session adoption + # across runs — the #2241 model-switch shape). The base lane below was + # verified against this version too. + run: npm i -g @deepseek-ai/dsh@0.2.0-rc.2 - name: Print dsh version run: dsh --version @@ -39,7 +42,9 @@ jobs: - name: Run real-dsh native-lane compression E2E env: E2E_DSH_BIN: dsh - run: ACP_TEST_E2E_DSH_NATIVE=1 node --import tsx --test tests/e2e/e2e-native-dsh.test.ts + run: | + ACP_TEST_E2E_DSH_NATIVE=1 node --import tsx --test tests/e2e/e2e-native-dsh.test.ts + ACP_TEST_E2E_DSH_NATIVE=1 node --import tsx --test tests/e2e/e2e-native-dsh-persona.test.ts - name: Collect E2E artifacts if: failure() diff --git a/src/persona-anchor.ts b/src/persona-anchor.ts new file mode 100644 index 0000000000..dff5051517 --- /dev/null +++ b/src/persona-anchor.ts @@ -0,0 +1,104 @@ +// #2241: continuity-aware persona anchor for id-sharing dsh traffic. +// +// The original dsh persona fingerprint (db21309d, #1916/#1307/#1314) keyed +// dsh traffic by id + system-text hash with kernel subagentNamespace +// first-seen anchor semantics: the FIRST system seen under the id keeps the +// raw key, any different system forks onto `|sub:`. That was built +// on the assumption "dsh composes its main system once per session, so main +// turns never fork mid-conversation" — validated for the volatile +// time-context (which dsh puts in a USER message) but broken by `/model`: +// dsh rebuilds the main system per model, so every model switch forked the +// MAIN lane off the raw key. The host only ever stamps the bare id, so +// compression tool calls kept hitting the frozen husk on the raw key while +// the live conversation rode a `|sub:` session with zero compression state +// (#2241: 266,966 pendingT1 tokens, 0 folds, 38 minutes). +// +// This module keeps the review isolation intact but changes the fork +// TRIGGER from "system text changed" to "system text changed AND the +// incoming history does not continue the raw key's chain": +// +// - model switch (same conversation, new system) — the request replays +// the full history plus new turns, so it BYTE-EXACTLY CONTINUES the +// raw key's prefix-affinity chain (#1106/#1148 identity semantics: +// content is identity, system drift is evolution). The anchor +// MIGRATES to the new fingerprint and the conversation keeps its +// compression blocks, refs, and ledger on the raw key. +// - auto-review classifyRisk (fresh single-message blob under a fixed +// REVIEW_POLICY system) — its message list does not continue any +// tracked chain, so it still forks onto `|sub:` exactly as +// before, sharing ONE forked session across successive reviews. +// +// The fork id format `|sub:` is unchanged, so +// downstream consumers (the #2244 personaForkTarget routing, the #2170 +// designNamespaced canary) keep working. Empty system text stays +// non-anchoring (kernel semantics): system-less auxiliary calls keep riding +// the main session verbatim. +// +// Anchors are process memory, like the kernel anchor map they replace — no +// persistence contract changes. After a proxy restart the first arrival +// claims the raw anchor; if a review claims it, the next main turn's +// continuity check runs against the raw key's PERSISTED chain (#1724 +// permanent chains) and migrates the anchor back, so the restart race +// self-heals on the very next main turn. + +import { createHash } from "node:crypto"; +import { prefixAffinity } from "./prefix-affinity.js"; + +const anchors = new Map(); + +function personaFingerprint(systemText: string): string { + return createHash("sha256").update(systemText, "utf8").digest("hex").slice(0, 16); +} + +export type PersonaAnchorAction = "claim" | "match" | "migrate" | "fork" | "passthrough"; + +export interface PersonaKeyResolution { + key: string; + action: PersonaAnchorAction; +} + +/** + * Resolve the session key for a dsh persona-fingerprinted request. + * `messages` is the protocol's conversation message list (the same list + * prefix-affinity hashes — top-level system fields are not part of it). + */ +export function resolvePersonaKey(rawId: string, systemText: string, messages: unknown[]): PersonaKeyResolution { + if (!systemText) return { key: rawId, action: "passthrough" }; + const fp = personaFingerprint(systemText); + const anchored = anchors.get(rawId); + if (anchored === undefined) { + anchors.set(rawId, fp); + return { key: rawId, action: "claim" }; + } + if (anchored === fp) return { key: rawId, action: "match" }; + if (prefixAffinity.chainContinues(messages, rawId)) { + anchors.set(rawId, fp); + return { key: rawId, action: "migrate" }; + } + return { key: `${rawId}|sub:${fp}`, action: "fork" }; +} + +/** server.ts wrapper: resolves the key and surfaces anchor migrations in + * the log (forks stay silent — they are the designed review path). */ +export function dshPersonaNamespace( + rawId: string, + systemText: string, + messages: unknown, + log: (level: "info" | "warn" | "error", message: string) => void, +): string { + const list = Array.isArray(messages) ? messages : []; + const res = resolvePersonaKey(rawId, systemText, list); + if (res.action === "migrate") { + log("info", `[persona] system text changed mid-conversation but the history continues ${rawId}'s chain — anchor migrated, compression state stays on the raw key (#2241)`); + } + return res.key; +} + +/** Current anchor fingerprint for a raw id (test/diagnostic surface). */ +export function personaAnchorOf(rawId: string): string | undefined { + return anchors.get(rawId); +} + +export function resetPersonaAnchorsForTest(): void { + anchors.clear(); +} diff --git a/src/prefix-affinity.ts b/src/prefix-affinity.ts index 7fe9e2673e..66d7b95df0 100644 --- a/src/prefix-affinity.ts +++ b/src/prefix-affinity.ts @@ -407,6 +407,25 @@ export class PrefixAffinityResolver { return best ? { sessionId: best.sessionId, sharedDepth: best.sharedDepth } : null; } + /** #2241: does `messages` continue the tracked chain of `sessionId`? + * True when the session's stored chain is a byte-exact head-anchored + * prefix of the incoming list — the progressive hash at the stored + * depth equals the stored tail hash (equal depth = byte-exact replay, + * which also counts). The building block for the dsh persona anchor + * migration: a system-text change whose history continues the raw + * key's chain is the SAME conversation (model switch), not a new + * persona. Cryptographic equality of the whole prefix is the + * discriminator — no depth floor beyond chainHashes' MIN_CANONICAL_BYTES. */ + chainContinues(messages: unknown[], sessionId: string): boolean { + const entry = this.trackedChains.get(sessionId); + if (!entry) return false; + const msgs = normalizeAffinityMessages(messages); + if (!hasUserMessage(msgs)) return false; + const hashes = chainHashes(msgs); + if (hashes.length === 0 || msgs.length < entry.depth) return false; + return hashes[entry.depth - 1] === entry.tailHash; + } + /** Drop tracking for a removed session. */ forget(sessionId: string): void { this.trackedChains.delete(sessionId); diff --git a/src/server.ts b/src/server.ts index 5935c42fd3..dc1879cca8 100644 --- a/src/server.ts +++ b/src/server.ts @@ -110,6 +110,7 @@ import { rewriteResponsesJsonResponse } from "./stream-responses.js"; import { observeResponsesTerminalState } from "./stream-terminal.js"; import { emitPreflightError, emitStreamError } from "./stream-error.js"; import { affinityToken, claudeSubagentAgentId, claudeSubagentSplit, clientConversationHeader, codexTurnIdentity, conversationHeaderSource, dshPersonaFingerprintApplies, instructionsFingerprintApplies, openaiSystemTextForPersona, preferPromptCacheKeyIdentity, shouldStampRelayAffinityPck, type ConversationIdentity } from "./session-id.js"; +import { dshPersonaNamespace } from "./persona-anchor.js"; import { prefixAffinity, type AnonymousAffinity } from "./prefix-affinity.js"; import { maybeAdoptForkBlocks, maybeAdoptResume } from "./fork-adoption.js"; import { publicForkInputMatches } from "./plugin.js"; @@ -2269,11 +2270,26 @@ async function handle( (claudeSub !== undefined && opts.subagentSplit !== false ? claudeSubagentSplit(anthropicIdentity?.value ?? anthropicSignal, req.headers, systemTextsForSplit) : dshPersona && !sideRequestLike - ? subagentNamespace(anthropicIdentity?.value ?? anthropicSignal, personaSystemText) + // #2241: continuity-aware anchor — a system change whose + // history continues the raw key's prefix-affinity chain + // (model switch) MIGRATES the anchor instead of forking + // the main lane off the raw key; only history-discontinuous + // requests (review blobs) still fork onto `|sub:`. + ? dshPersonaNamespace( + anthropicIdentity?.value ?? anthropicSignal, + personaSystemText, + (parsed as AnthropicRequestBody).messages, + log, + ) : anthropicIdentity?.value ?? anthropicSignal) : protocol === "openai" ? (dshPersona && !sideRequestLike - ? subagentNamespace(openaiIdentity?.value ?? openaiSignal, personaSystemText) + ? dshPersonaNamespace( + openaiIdentity?.value ?? openaiSignal, + personaSystemText, + (parsed as OpenAIRequestBody).messages, + log, + ) : openaiIdentity?.value ?? openaiSignal) : codexTurn // Trusted Codex turn id enters the verbatim session chain diff --git a/tests/dsh-persona-continuity.test.ts b/tests/dsh-persona-continuity.test.ts new file mode 100644 index 0000000000..35002ba94f --- /dev/null +++ b/tests/dsh-persona-continuity.test.ts @@ -0,0 +1,273 @@ +// #2241: continuity-aware dsh persona anchor. The original fingerprint +// (db21309d) forked on ANY system-text change under the id — built on the +// assumption that dsh composes its main system once per session. `/model` +// breaks that assumption: dsh rebuilds the main system per model, so every +// model switch forked the MAIN lane off the raw key while the host kept +// stamping the bare id — compression then hit a frozen 7-message husk +// forever (#2241). The fix swaps the fork trigger for prefix-affinity +// semantics (#1106/#1148: content is identity): a system change whose +// history BYTE-EXACTLY CONTINUES the raw key's chain migrates the anchor +// (same conversation — compression state stays); a history-discontinuous +// request (auto-review blob) still forks onto `|sub:`. + +import test from "node:test"; +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import { createHash } from "node:crypto"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import type { ProxyOptions } from "../src/config.ts"; +import { prefixAffinity } from "../src/prefix-affinity.ts"; +import { personaAnchorOf, resolvePersonaKey, resetPersonaAnchorsForTest } from "../src/persona-anchor.ts"; +import { _rememberedForTest, _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"; + +// Hermetic state dirs (#7.2: no environmental luck). Without these, each rig +// hydrates the shared prefix-affinity snapshot left by the PREVIOUS run of +// this file — whose deeper dshc-* chains make chainContinues reject the +// shorter replay and fork instead of migrate, failing the second run while +// the first (and CI, fresh container) passes. +const testRoot = mkdtempSync(join(tmpdir(), "bili-dsh-cont-")); +test.after(() => rmSync(testRoot, { recursive: true, force: true })); +for (const key of ["XDG_STATE_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_CONFIG_HOME"]) process.env[key] = testRoot; + +const MODEL = "claude-sonnet-4-5"; +const SYSTEM_A = "You are DeepSeek Harness, the main coding agent.\nModel: GLM-A.\nWorkspace: /tmp."; +const SYSTEM_B = "You are DeepSeek Harness, the main coding agent.\nModel: GLM-B.\nWorkspace: /tmp."; +const REVIEW_SYSTEM = "You are the final authorization reviewer for exactly one pending tool call.\nAnswer with one word."; + +const forkKey = (conv: string, system: string): string => + `${conv}|sub:${createHash("sha256").update(system, "utf8").digest("hex").slice(0, 16)}`; + +const msgs = (n: number, tag = "main"): { 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(6000), + })); + +// --------------------------------------------------------------------------- +// Unit: the resolver state machine against a hand-noted affinity chain. +// --------------------------------------------------------------------------- +test("resolvePersonaKey: claim → match → migrate (continuing history) → fork (discontinuous)", () => { + resetPersonaAnchorsForTest(); + prefixAffinity.forget("unit-conv"); + const chain = msgs(6, "u"); + const fp0 = prefixAffinity.chainFingerprint(chain); + assert.ok(fp0, "chain fingerprint exists"); + prefixAffinity.note("unit-conv", fp0.depth, fp0.tailHash, fp0.itemHashes, true); + + const idA = createHash("sha256").update(SYSTEM_A, "utf8").digest("hex").slice(0, 16); + const idB = createHash("sha256").update(SYSTEM_B, "utf8").digest("hex").slice(0, 16); + + // first arrival claims + assert.deepEqual(resolvePersonaKey("unit-conv", SYSTEM_A, chain), { key: "unit-conv", action: "claim" }); + assert.equal(personaAnchorOf("unit-conv"), idA); + // same system keeps the raw key + assert.deepEqual(resolvePersonaKey("unit-conv", SYSTEM_A, chain), { key: "unit-conv", action: "match" }); + // empty system is non-anchoring passthrough (kernel semantics) + assert.deepEqual(resolvePersonaKey("unit-conv", "", chain), { key: "unit-conv", action: "passthrough" }); + assert.equal(personaAnchorOf("unit-conv"), idA, "passthrough does not touch the anchor"); + // model switch: same conversation, one new turn — history CONTINUES the + // chain → migrate, raw key, compression state stays (#2241) + const extended = [...chain, { role: "user", content: "u-new-" + "z".repeat(64) }]; + assert.deepEqual(resolvePersonaKey("unit-conv", SYSTEM_B, extended), { key: "unit-conv", action: "migrate" }); + assert.equal(personaAnchorOf("unit-conv"), idB, "anchor migrated to the new system fingerprint"); + // a review-shaped request (single fresh blob) does NOT continue the chain → fork + const reviewList = [{ role: "user", content: "Conversation transcript (flattened):\nuser: build it\nDecide: risky?" }]; + assert.deepEqual(resolvePersonaKey("unit-conv", REVIEW_SYSTEM, reviewList), { + key: forkKey("unit-conv", REVIEW_SYSTEM), + action: "fork", + }); + assert.equal(personaAnchorOf("unit-conv"), idB, "a fork never moves the raw anchor"); + // after migration the OLD system is now the stranger: a diverged tail + // under SYSTEM_A does not continue the migrated chain → fork (conservative) + const diverged = chain.map((m, i) => (i === chain.length - 1 ? { ...m, content: "rewritten-tail-" + "z".repeat(64) } : m)); + assert.equal(resolvePersonaKey("unit-conv", SYSTEM_A, diverged).action, "fork"); + // but a byte-exact replay at equal depth under the OLD system after the + // chain was re-noted at the longer depth is not a continuation either + // (the tracked chain moved past it) — replaying the SAME depth continues. + const reNoted = prefixAffinity.chainFingerprint(extended); + assert.ok(reNoted); + prefixAffinity.note("unit-conv", reNoted.depth, reNoted.tailHash, reNoted.itemHashes, true); + assert.equal(resolvePersonaKey("unit-conv", SYSTEM_A, extended).action, "migrate", "equal-depth byte-exact replay continues the chain"); +}); + +// --------------------------------------------------------------------------- +// e2e rigs (openai + anthropic lanes), mirroring dsh-persona-fingerprint. +// --------------------------------------------------------------------------- +type Rig = { proxyPort: number; upstreamPort: number; proxy: http.Server; upstream: http.Server }; + +async function startRig(): Promise { + 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(); + resetPersonaAnchorsForTest(); + const dir = mkdtempSync(join(testRoot, "run-")); + for (const key of ["XDG_STATE_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_CONFIG_HOME"]) process.env[key] = dir; + 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"); + return { proxyPort: (proxy.address() as { port: number }).port, upstreamPort, proxy, upstream }; +} + +async function closeRig(rig: Rig): Promise { + rig.proxy.close(); + await once(rig.proxy, "close"); + rig.upstream.close(); + await once(rig.upstream, "close"); +} + +test("e2e openai lane #2241: model switch keeps the raw key (anchor migration); review still forks; switch back migrates again", async () => { + const rig = await startRig(); + const CONV = "dshc-openai"; + 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": "dsh", "x-bili-plugin-conversation": CONV }; + const tools = [{ type: "function", function: { name: "bash", description: "run", parameters: { type: "object", properties: {} } } }]; + + // Model A main turn (12 messages) claims the raw key. + const r1 = await fetch(url, { + method: "POST", + headers, + body: JSON.stringify({ model: MODEL, max_tokens: 64_000, tools, messages: [{ role: "system", content: SYSTEM_A }, ...msgs(12)] }), + }); + await r1.text(); + const main = getSession(CONV); + assert.ok(main, "main session exists under the raw key"); + const refsA = Object.keys(main.state.messageRefs.byRaw).length; + assert.ok(refsA >= 12, "refs assigned to the main history"); + + // /model switch: SAME conversation replayed + one new turn, new system. + // Pre-fix behavior: fork onto `|sub:` (compression lost, #2241). + // Post-fix: history continues the raw chain → anchor migrates → raw key. + const switched = [...msgs(12), { role: "user", content: "after the switch-" + "z".repeat(64) }]; + const r2 = await fetch(url, { + method: "POST", + headers, + body: JSON.stringify({ model: MODEL, max_tokens: 64_000, tools, messages: [{ role: "system", content: SYSTEM_B }, ...switched] }), + }); + await r2.text(); + assert.equal(getSession(CONV).stats.requests, 2, "switched turn keeps riding the RAW key"); + assert.equal(peekSession(forkKey(CONV, SYSTEM_B)), undefined, "no `|sub:` session was minted for the main lane"); + assert.ok(Object.keys(getSession(CONV).state.messageRefs.byRaw).length > refsA, "refs keep accumulating on the same session (compression state preserved)"); + assert.ok((_rememberedForTest().get(CONV)?.processed.length ?? 0) >= 13, "remembered snapshot tracks the switched history"); + + // A review request under the SAME id still forks (isolation intact). + const r3 = await fetch(url, { + method: "POST", + headers, + body: JSON.stringify({ + model: MODEL, + max_tokens: 384_000, + messages: [ + { role: "system", content: REVIEW_SYSTEM }, + { role: "user", content: "Conversation transcript (flattened):\nuser: build it\nDecide: risky?" }, + ], + }), + }); + await r3.text(); + const fork = forkKey(CONV, REVIEW_SYSTEM); + const forkSession = peekSession(fork); + assert.ok(forkSession, "review request still forks onto its own session"); + assert.equal(forkSession.stats.requests, 1, "forked session served the review"); + assert.equal(getSession(CONV).stats.requests, 2, "main session untouched by the review"); + + // Switch BACK to model A (history continues) → migrate again, raw key. + const back = [...switched, { role: "user", content: "back on A-" + "z".repeat(64) }]; + const r4 = await fetch(url, { + method: "POST", + headers, + body: JSON.stringify({ model: MODEL, max_tokens: 64_000, tools, messages: [{ role: "system", content: SYSTEM_A }, ...back] }), + }); + await r4.text(); + assert.equal(getSession(CONV).stats.requests, 3, "switch-back turn also keeps the raw key"); + assert.equal(peekSession(forkKey(CONV, SYSTEM_A)), undefined, "no fork session for the main lane on switch-back either"); + + // A diverged replay under a THIRD system (tail rewritten, not a + // continuation) still forks — conservative by design. + const diverged = msgs(12).map((m, i) => (i === 11 ? { ...m, content: "rewritten-" + "z".repeat(64) } : m)); + const r5 = await fetch(url, { + method: "POST", + headers, + body: JSON.stringify({ model: MODEL, max_tokens: 64_000, tools, messages: [{ role: "system", content: SYSTEM_B }, ...diverged] }), + }); + await r5.text(); + assert.equal(getSession(CONV).stats.requests, 3, "diverged history did NOT ride the raw key"); + assert.ok(peekSession(forkKey(CONV, SYSTEM_B)), "diverged + system change forks (conservative)"); + } finally { + await closeRig(rig); + } +}); + +test("e2e anthropic lane #2241: the same anchor migration applies to dsh-over-anthropic", async () => { + const rig = await startRig(); + const CONV = "dshc-anthropic"; + try { + const url = `http://127.0.0.1:${rig.proxyPort}/bili/http://127.0.0.1:${rig.upstreamPort}/v1/messages`; + const headers: Record = { "content-type": "application/json", "x-bili-plugin": "dsh", "x-bili-plugin-conversation": CONV }; + const turn = (system: string, n: number, tag = "main") => ({ + model: MODEL, + max_tokens: 64_000, + system: [{ type: "text", text: system }], + messages: msgs(n, tag), + }); + const r1 = await fetch(url, { method: "POST", headers, body: JSON.stringify(turn(SYSTEM_A, 8)) }); + await r1.text(); + assert.ok(getSession(CONV), "main session exists under the raw key (anthropic)"); + + const r2 = await fetch(url, { method: "POST", headers, body: JSON.stringify(turn(SYSTEM_B, 9)) }); + await r2.text(); + assert.equal(getSession(CONV).stats.requests, 2, "model switch keeps the raw key on the anthropic lane"); + assert.equal(peekSession(forkKey(CONV, SYSTEM_B)), undefined, "no fork session minted"); + } finally { + await closeRig(rig); + } +}); diff --git a/tests/dsh-persona-fingerprint.test.ts b/tests/dsh-persona-fingerprint.test.ts index 3dbaa37490..54796c9623 100644 --- a/tests/dsh-persona-fingerprint.test.ts +++ b/tests/dsh-persona-fingerprint.test.ts @@ -20,6 +20,7 @@ import { defaultConfig } from "acp-kernel"; import { startServer } from "../src/server.ts"; import type { ProxyOptions } from "../src/config.ts"; import { dshPersonaFingerprintApplies, openaiSystemTextForPersona } from "../src/session-id.ts"; +import { resetPersonaAnchorsForTest } from "../src/persona-anchor.ts"; import { _rememberedForTest, _resetPluginStateForTest, resolveConversation } from "../src/plugin.ts"; import { SessionStore, _setStoreForTest } from "../src/persist.ts"; import { _setForTest as setRegistryForTest } from "../src/registry.ts"; @@ -90,6 +91,7 @@ async function startRig(): Promise { setRegistryForTest({}); _resetSessionsForTest(); _resetPluginStateForTest(); + resetPersonaAnchorsForTest(); const proxy = await startServer({ port: 0, host: "127.0.0.1", diff --git a/tests/e2e/e2e-native-dsh-persona.test.ts b/tests/e2e/e2e-native-dsh-persona.test.ts new file mode 100644 index 0000000000..4895b411cc --- /dev/null +++ b/tests/e2e/e2e-native-dsh-persona.test.ts @@ -0,0 +1,451 @@ +// E2E: REAL `dsh` — the #2241 regression family, on the native lane. +// +// A model switch mid-conversation must NOT fork the main lane off the raw +// conversation key (#2241): dsh rebuilds its main system per model, so the +// persona fingerprint (db21309d: "a different system forks onto |sub:") +// fired on EVERY /model switch — the main turn landed on a fresh `|sub:` +// session, compression refs renumbered from zero, and the folding state was +// lost for the rest of the session. The fix (PR #2247) keys persona forking +// on prefix-affinity CONTINUITY: a system change whose history byte-exactly +// continues the raw key's chain MIGRATES the anchor (same conversation); +// history-discontinuous requests still fork. +// +// Two scenarios, both with a real dsh headless client and zero tokens: +// +// A. model switch — turn 1 (model A) then the profile's default model is +// flipped and turn 2 continues the SAME dsh session (--session-id), so +// dsh recomposes its main system — the exact incident trigger. Accept: +// one stable conversation id, a real model switch on the wire, a +// continued history, and exactly ONE persisted bili session under the +// RAW key (no `|sub:` sibling, requests >= 2, refs accumulated). +// The title-generation side request dsh fires on turn 1 rides the same +// conversation id — it must stay a harmless side lane (never steals the +// raw key, never mints a persisted `|sub:` of its own). +// +// B. auto-review (blocked, see gatedB below) — with +// @deepseek-ai/dsh-experimental-auto-review enabled and a task that runs +// a bash tool call, dsh fires its reviewer request under the SAME +// conversation id: fixed REVIEW_POLICY system, one fresh +// flattened-transcript user message (history-discontinuous by design, +// #1916/#1307/#1314). Accept: the review request reaches the wire, the +// reviewer decision JSON round-trips, the tool actually executes, and — +// the regression pin — the review STILL forks onto its own `|sub:` +// session while the main lane keeps riding the raw key (refs never +// reset). An over-aggressive migration would collapse the review into +// the main session and fail this scenario. Until a headless surface to +// arm the Auto preset exists, that pin lives in +// tests/dsh-persona-continuity.test.ts (review e2e, both wires). +// +// Gated by ACP_TEST_E2E_DSH_NATIVE=1 (needs a real `dsh` >= 0.2.0-rc.2 with +// --session-id + `npm run build`; the profile loads dist/agent/dsh-native.js). +// Scenario A fails on pre-fix master with the `|sub:` fork — that is the +// regression it pins; scenario B pins the isolation the fix must preserve. + +import test from "node:test"; +import assert from "node:assert/strict"; +import { spawn, spawnSync } from "node:child_process"; +import fs from "node:fs"; +import http from "node:http"; +import path from "node:path"; +import os from "node:os"; + +const DSH_BIN = process.env.E2E_DSH_BIN ?? "dsh"; +const GATE = process.env.ACP_TEST_E2E_DSH_NATIVE === "1"; +const REPO_ROOT = path.join(import.meta.dirname, "..", ".."); +const TMO = 180_000; +const FAKE_PORT = 18931; + +function dshAvailable(): boolean { + const r = spawnSync(DSH_BIN, ["--version"], { timeout: 15_000 }); + return r.status === 0; +} + +function cleanEnv(): NodeJS.ProcessEnv { + const env: NodeJS.ProcessEnv = { ...process.env }; + for (const key of Object.keys(env)) { + if (key.startsWith("BILI") || key.startsWith("BILLION_CONTEXT") || key.startsWith("ACP_") || key.startsWith("DSH_") || key.startsWith("ZCODE")) delete env[key]; + } + for (const key of ["NODE_EXTRA_CA_CERTS", "NODE_OPTIONS", "NODE_TEST_CONTEXT", "HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy", "NO_PROXY", "no_proxy"]) delete env[key]; + return env; +} + +type FakeMessage = { role?: string; content?: unknown }; + +// Deterministic streaming-capable chat upstream with the scripted behaviors +// both scenarios need. Reply selection per request body: +// - REVIEW_POLICY system -> reviewer decision JSON (allow, low) +// - title-generator system -> a one-line title +// - a tool result in history -> final assistant text +// - the workspace task -> a bash tool_call (echo ZX7-back) +// - otherwise -> ok-N +// Every stamped request is recorded to a JSONL oracle (conversation id, +// model, message count, system head). +function startFakeUpstream(reqLog: string): Promise { + let n = 0; + const server = http.createServer((req, res) => { + if (req.method === "GET" && req.url?.endsWith("/models")) { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ object: "list", data: [ + { id: "fake-a", object: "model" }, + { id: "fake-b", object: "model" }, + ] })); + return; + } + if (req.method === "POST" && req.url?.endsWith("/chat/completions")) { + let raw = ""; + req.on("data", (c: Buffer) => { raw += c.toString("utf8"); }); + req.on("end", () => { + try { + const body = JSON.parse(raw) as { messages?: FakeMessage[]; model?: string; stream?: boolean }; + const messages = body.messages ?? []; + const sysMsg = messages.find((m) => m?.role === "system"); + const sysText = typeof sysMsg?.content === "string" ? sysMsg.content + : Array.isArray(sysMsg?.content) ? sysMsg.content.map((p) => (p as { text?: string })?.text ?? "").join("") + : ""; + const flat = (m: FakeMessage): string => typeof m.content === "string" ? m.content : JSON.stringify(m.content ?? ""); + fs.appendFileSync(reqLog, JSON.stringify({ + conv: req.headers["x-bili-plugin-conversation"] ?? null, + plugin: req.headers["x-bili-plugin"] ?? null, + model: body.model ?? null, + nmsgs: messages.length, + sysLen: sysText.length, + sysHead: sysText.slice(0, 80), + hasToolResult: messages.some((m) => m?.role === "tool"), + }) + "\n"); + + let content = `ok-${++n}`; + let toolCalls: { id: string; type: "function"; function: { name: string; arguments: string } }[] | undefined; + if (/^REVIEW_POLICY/.test(sysText)) { + content = `{"risk":"low","decision":"allow"}`; + } else if (/Create a concise title/i.test(sysText)) { + content = "Workspace Setup"; + } else if (messages.some((m) => m?.role === "tool")) { + content = "done: the output was ZX7-back"; + } else if (messages.some((m) => m?.role === "user" && /codeword|run the command/i.test(flat(m)))) { + toolCalls = [{ id: `call_${n}`, type: "function", function: { name: "bash", arguments: JSON.stringify({ command: "echo ZX7-back" }) } }]; + } + + const id = `chatcmpl-${n}`; + const model = body.model ?? "fake-a"; + const finish = toolCalls ? "tool_calls" : "stop"; + const usage = { prompt_tokens: 100, completion_tokens: 5, total_tokens: 105 }; + if (body.stream) { + res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive" }); + if (toolCalls) { + res.write(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", model, choices: [{ index: 0, delta: { tool_calls: toolCalls.map((tc, i) => ({ index: i, ...tc })) }, finish_reason: null }] })}\n\n`); + } else { + res.write(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", model, choices: [{ index: 0, delta: { role: "assistant" }, finish_reason: null }] })}\n\n`); + res.write(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", model, choices: [{ index: 0, delta: { content }, finish_reason: null }] })}\n\n`); + } + res.write(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", model, choices: [{ index: 0, delta: {}, finish_reason: finish }], usage })}\n\n`); + res.write("data: [DONE]\n\n"); + res.end(); + } else { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ + id, object: "chat.completion", model, + choices: [{ index: 0, message: { role: "assistant", content, ...(toolCalls ? { tool_calls: toolCalls } : {}) }, finish_reason: finish }], + usage, + })); + } + } catch (e) { + res.writeHead(500, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: { message: String(e) } })); + } + }); + return; + } + res.writeHead(404, { "content-type": "application/json" }); + res.end(JSON.stringify({ error: { message: "not found" } })); + }); + return new Promise((resolve) => server.listen(FAKE_PORT, "127.0.0.1", () => resolve(server))); +} + +interface Oracle { conv: string | null; plugin: string | null; model: string | null; nmsgs: number; sysLen: number; sysHead: string; hasToolResult: boolean } + +function readOracle(reqLog: string): Oracle[] { + if (!fs.existsSync(reqLog)) return []; + return fs.readFileSync(reqLog, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l) as Oracle); +} + +interface Rig { + env: NodeJS.ProcessEnv; + cwd: string; + reqLog: string; + outDir: string; + setDefaultModel: (model: string, withAutoReview: boolean) => void; + stopAndFlush: () => Promise; + persistedSessions: () => { state: string; data: string }; + cleanup: () => void; +} + +function buildRig(tag: string, withAutoReview: boolean): Rig { + const outDir = path.join(REPO_ROOT, "tmp", `e2e-dsh-persona-${tag}-${process.pid}`); + fs.mkdirSync(outDir, { recursive: true }); + const root = fs.mkdtempSync(path.join(os.tmpdir(), `e2e-dsh-persona-${tag}-`)); + const home = path.join(root, "home"); + const tmp = path.join(root, "tmp"); + const dshHome = path.join(root, "dsh"); + const xdg = { config: path.join(root, "config"), cache: path.join(root, "cache"), state: path.join(root, "state"), data: path.join(root, "data") }; + const cwd = path.join(root, "cwd"); + for (const d of [home, tmp, dshHome, cwd, ...Object.values(xdg)]) fs.mkdirSync(d, { recursive: true }); + const reqLog = path.join(outDir, "oracle.jsonl"); + + const profileDir = path.join(dshHome, "profiles", "headless"); + const pkgDir = path.join(profileDir, "node_modules", "billion-context"); + fs.mkdirSync(pkgDir, { recursive: true }); + fs.copyFileSync(path.join(REPO_ROOT, "package.json"), path.join(pkgDir, "package.json")); + fs.cpSync(path.join(REPO_ROOT, "dist"), path.join(pkgDir, "dist"), { recursive: true }); + fs.copyFileSync(path.join(REPO_ROOT, "dsh.bundle.patch.yml"), path.join(pkgDir, "dsh.bundle.patch.yml")); + const biliVersion = (JSON.parse(fs.readFileSync(path.join(REPO_ROOT, "package.json"), "utf8")) as { version: string }).version; + fs.writeFileSync(path.join(profileDir, "package.json"), JSON.stringify({ + name: `e2e-dsh-persona-${tag}`, + private: true, + dependencies: { "billion-context": biliVersion }, + dsh: { profile: { bundles: ["@deepseek-ai/dsh-base", "@deepseek-ai/dsh-headless", "billion-context"], patchReload: "startup" } }, + }, null, 2) + "\n"); + fs.writeFileSync(path.join(profileDir, "cordis.yml"), "[]\n"); + fs.writeFileSync(path.join(profileDir, "pnpm-workspace.yaml"), "packages:\n - .\nnodeLinker: hoisted\nautoInstallPeers: false\n"); + // Two models; flipping the default between turns makes dsh recompose its + // main system — the exact #2241 trigger. Model B also carries a different + // context window so the two system texts are guaranteed apart. + const patchYml = (model: string, autoReview: boolean): string => [ + "- id: llm-pi-ai", + " config:", + " providers:", + " fake:", + " displayName: Fake Upstream", + " apiKeyEnv: E2E_FAKE_KEY", + " api: openai-completions", + ` baseURL: http://127.0.0.1:${FAKE_PORT}/v1`, + " models:", + " - id: fake-a", + " name: Model Alpha", + " contextWindow: 60000", + " maxTokens: 4096", + " - id: fake-b", + " name: Model Beta", + " contextWindow: 32000", + " maxTokens: 4096", + "- id: agent-default-model", + " config:", + " provider: fake", + ` model: ${model}`, + ...(autoReview ? ["- id: auto-review"] : []), + "", + ].join("\n"); + fs.writeFileSync(path.join(profileDir, "cordis.patch.yml"), patchYml("fake-a", withAutoReview)); + fs.mkdirSync(path.join(xdg.config, "billion-context"), { recursive: true }); + fs.writeFileSync(path.join(xdg.config, "billion-context", "billion-context.json"), + JSON.stringify({ providers: {}, compress: { preserveRecentTokens: 0 } }, null, 2) + "\n"); + + const env: NodeJS.ProcessEnv = { + ...cleanEnv(), + HOME: home, + TMPDIR: tmp, + DSH_HOME: dshHome, + XDG_CONFIG_HOME: xdg.config, + XDG_CACHE_HOME: xdg.cache, + XDG_STATE_HOME: xdg.state, + XDG_DATA_HOME: xdg.data, + E2E_FAKE_KEY: "e2e-fake-key", + DSH_TELEMETRY_MODE: "DISABLED", + LANG: "C.UTF-8", + // #1158/#1187 coexistence: a dead proxy policy must not leak in; the + // loopback NO_PROXY keeps fixture traffic direct. + HTTP_PROXY: "http://127.0.0.1:1", + HTTPS_PROXY: "http://127.0.0.1:1", + NO_PROXY: "127.0.0.1,localhost", + }; + + const stopAndFlush = async (): Promise => { + const instancesDir = path.join(xdg.state, "billion-context", "instances"); + try { + for (const f of fs.readdirSync(instancesDir)) { + try { + const rec = JSON.parse(fs.readFileSync(path.join(instancesDir, f), "utf8")) as { pid?: number }; + if (typeof rec.pid === "number" && rec.pid > 0) { try { process.kill(rec.pid, "SIGTERM"); } catch { /* gone */ } } + } catch { /* unreadable record */ } + } + } catch { /* no instances dir */ } + await new Promise((r) => setTimeout(r, 1500)); + }; + + const readDir = (sessionsRoot: string): { id: string; requests: number | null; refs: number; blocks: number }[] => { + const found: { id: string; requests: number | null; refs: number; blocks: number }[] = []; + if (!fs.existsSync(sessionsRoot)) return found; + const walk = (d: string): void => { + for (const f of fs.readdirSync(d, { withFileTypes: true })) { + const p = path.join(d, f.name); + if (f.isDirectory()) walk(p); + else if (f.name.endsWith(".json")) { + try { + const j = JSON.parse(fs.readFileSync(p, "utf8")) as { payload?: { id?: string; stats?: { requests?: number }; state?: { messageRefs?: { byRaw?: Record }; blocks?: Record } } }; + const inner = j.payload; + if (!inner?.id) return; + found.push({ + id: String(inner.id), + requests: inner.stats?.requests ?? null, + refs: Object.keys(inner.state?.messageRefs?.byRaw ?? {}).length, + blocks: Object.keys(inner.state?.blocks ?? {}).length, + }); + } catch { /* skip unreadable */ } + } + } + }; + walk(sessionsRoot); + return found; + }; + + return { + env, cwd, reqLog, outDir, + setDefaultModel: (model, autoReview) => fs.writeFileSync(path.join(profileDir, "cordis.patch.yml"), patchYml(model, autoReview)), + stopAndFlush, + persistedSessions: () => ({ + state: JSON.stringify(readDir(path.join(xdg.state, "billion-context", "sessions"))), + data: JSON.stringify(readDir(path.join(xdg.data, "billion-context", "sessions"))), + }), + cleanup: () => { try { fs.rmSync(root, { recursive: true, force: true }); fs.rmSync(outDir, { recursive: true, force: true }); } catch { /* best-effort */ } }, + }; +} + +function dshRun(rig: Rig, args: string[], tag: string): Promise<{ code: number; out: string; err: string }> { + return new Promise((resolve) => { + const child = spawn(DSH_BIN, ["--profile", "headless", ...args], { cwd: rig.cwd, env: rig.env, stdio: ["ignore", "pipe", "pipe"] }); + let out = ""; + let err = ""; + child.stdout.on("data", (c) => { out += c.toString("utf8"); }); + child.stderr.on("data", (c) => { err += c.toString("utf8"); }); + const timer = setTimeout(() => { try { child.kill("SIGKILL"); } catch { /* noop */ } }, TMO); + child.on("close", (code) => { + clearTimeout(timer); + try { + fs.writeFileSync(path.join(rig.outDir, `persona-2241.${tag}.out`), out); + fs.writeFileSync(path.join(rig.outDir, `persona-2241.${tag}.err`), err); + } catch { /* artifacts best-effort */ } + resolve({ code: code ?? -1, out, err }); + }); + }); +} + +function sessionIdOf(out: string): string | undefined { + for (const line of out.split("\n")) { + if (!line.trim().startsWith("{")) continue; + try { + const ev = JSON.parse(line) as { type?: string; sessionId?: string }; + if (ev.type === "session" && typeof ev.sessionId === "string") return ev.sessionId; + } catch { /* skip partial */ } + } + return undefined; +} + +interface Session { id: string; requests: number | null; refs: number; blocks: number } + +function allSessions(rig: Rig): Session[] { + return [...JSON.parse(rig.persistedSessions().state) as Session[], ...JSON.parse(rig.persistedSessions().data) as Session[]]; +} + +const gated = { skip: (!GATE || !dshAvailable()) ? "set ACP_TEST_E2E_DSH_NATIVE=1 with a real dsh >= 0.2.0-rc.2" : false }; + +test("real dsh #2241 A: a mid-session model switch keeps the raw conversation key (no |sub: fork; title side lane harmless)", gated, async (t) => { + assert.ok(fs.existsSync(path.join(REPO_ROOT, "dist", "agent", "dsh-native.js")), "npm run build first — the profile loads dist/agent/dsh-native.js"); + const rig = buildRig("switch", false); + const fake = await startFakeUpstream(rig.reqLog); + t.after(() => { fake.close(); rig.cleanup(); }); + try { + // ---- turn 1: model A claims the raw key (title side request fires too) ---- + const r1 = await dshRun(rig, ["--json", "We are setting up a workspace. Remember the codeword ZX7. Then reply with exactly: setup done."], "A-t1"); + assert.equal(r1.code, 0, `turn 1 dsh exit (${r1.err.slice(-300)})`); + const sessionId = sessionIdOf(r1.out); + assert.ok(sessionId, "turn 1 --json events expose the dsh session id"); + + // ---- the model switch: same dsh session, recomposed main system ---- + rig.setDefaultModel("fake-b", false); + const r2 = await dshRun(rig, ["--session-id", sessionId, "--json", "What was the codeword? Answer with the word only."], "A-t2"); + assert.equal(r2.code, 0, `turn 2 dsh exit (${r2.err.slice(-300)})`); + + // ---- oracle: one conversation, a real model switch, history grew ---- + const oracle = readOracle(rig.reqLog); + const convs = new Set(oracle.map((o) => o.conv).filter(Boolean)); + assert.equal(convs.size, 1, "both turns stamped ONE conversation id"); + const conv = [...convs][0] as string; + const turn1 = oracle.filter((o) => o.model === "fake-a"); + const turn2 = oracle.filter((o) => o.model === "fake-b"); + assert.ok(turn1.length >= 1, "turn 1 rode model fake-a"); + assert.ok(turn2.length >= 1, "turn 2 rode model fake-b — the switch reached the wire"); + assert.ok(Math.max(...turn2.map((o) => o.nmsgs)) > Math.max(...turn1.map((o) => o.nmsgs)), "turn 2 continues the SAME history (more messages on the wire)"); + // The title side request rides the same conversation id and must stay + // harmless — never claims the raw key, never persists its own |sub:. + assert.ok(oracle.some((o) => /Create a concise title/i.test(o.sysHead)), "dsh fired its title-generation side request under the same conversation id"); + + // ---- acceptance: ONE session under the RAW key, no |sub: sibling ---- + await rig.stopAndFlush(); + const sessions = allSessions(rig).filter((s) => s.id === conv || s.id.startsWith(`${conv}|sub:`)); + const main = sessions.find((s) => s.id === conv); + const forks = sessions.filter((s) => s.id.startsWith(`${conv}|sub:`)); + assert.equal(forks.length, 0, `#2241: the model switch must NOT fork the main lane (found ${forks.map((f) => f.id).join(", ")})`); + assert.ok(main, "the raw conversation key persisted a session"); + assert.ok((main?.requests ?? 0) >= 2, `both turns rode the raw key (requests=${main?.requests})`); + assert.ok((main?.refs ?? 0) >= 4, `refs accumulated across the switch (refs=${main?.refs})`); + } finally { + // keep artifacts on failure for the CI upload step + if (t instanceof Error) { /* unreachable — t.after handles cleanup */ } + } +}); + +// Scenario B is written and kept ready, but real-client auto-review cannot +// arm in headless TODAY (verified against dsh 0.2.0-rc.2 sources): +// - the review gate is `permissionPresets.current(agent.session) !== "auto" +// -> pass through` (dsh-experimental-auto-review apply()); +// - a headless session carries NO preset: agents.create({meta:{cwd}}) only +// (dsh-headless run()), so the initial permission falls back to the +// permission plugin's inferred default (workspace-write); +// - the only Auto entry points are the web composer / "/permission auto" +// (README.zh.md: "通用设置与未来会话默认值不提供 Auto"), the registry's +// selectedDefault is deliberately not settable for Auto, and neither the +// plugin nor dsh-permission-presets reads any process.env override; +// - the profile settings.yaml legacy-import path does not settle within a +// one-shot run (the document is never consumed/renamed). +// Until dsh exposes a headless surface (or adopts an event log we can seed +// through supported means), the review FORK shape is pinned by the harness +// e2e in tests/dsh-persona-continuity.test.ts (review e2e, both wires). +// Flip this gate when that changes. +const gatedB = { + skip: (!GATE || !dshAvailable()) + ? "set ACP_TEST_E2E_DSH_NATIVE=1 with a real dsh >= 0.2.0-rc.2" + : process.env.ACP_TEST_E2E_DSH_AUTO_REVIEW === "1" + ? false + : "blocked: dsh 0.2.0-rc.2 exposes no headless surface to arm the Auto permission preset (web-UI /permission auto only) — set ACP_TEST_E2E_DSH_AUTO_REVIEW=1 to attempt anyway", +}; + +test("real dsh #2241 B: auto-review still forks onto |sub: while the main lane keeps the raw key", gatedB, async (t) => { + assert.ok(fs.existsSync(path.join(REPO_ROOT, "dist", "agent", "dsh-native.js")), "npm run build first — the profile loads dist/agent/dsh-native.js"); + const rig = buildRig("review", true); + const fake = await startFakeUpstream(rig.reqLog); + t.after(() => { fake.close(); rig.cleanup(); }); + + // ---- one task that runs a bash tool call -> auto-review fires ---- + const r1 = await dshRun(rig, ["--json", "Run the command: echo ZX7-back, then report its output."], "B-t1"); + assert.equal(r1.code, 0, `task dsh exit (${r1.err.slice(-300)})`); + + const oracle = readOracle(rig.reqLog); + const convs = new Set(oracle.map((o) => o.conv).filter(Boolean)); + assert.equal(convs.size, 1, "all requests stamped ONE conversation id"); + const conv = [...convs][0] as string; + const reviews = oracle.filter((o) => /^REVIEW_POLICY/.test(o.sysHead)); + assert.ok(reviews.length >= 1, `the auto-review reviewer request reached the wire (${reviews.length})`); + assert.equal(reviews[0]?.nmsgs, 1, "the review request carries ONE flattened-transcript user message (#1916 shape)"); + const mainTurns = oracle.filter((o) => !/^REVIEW_POLICY/.test(o.sysHead) && !/Create a concise title/i.test(o.sysHead) && o.nmsgs > 1); + assert.ok(mainTurns.length >= 2, `the main agent loop ran its rounds (rounds=${mainTurns.length})`); + assert.ok(oracle.some((o) => o.hasToolResult), "the tool result round-tripped (reviewer allowed the call)"); + + // ---- acceptance: review forked, main stayed raw ---- + await rig.stopAndFlush(); + const sessions = allSessions(rig).filter((s) => s.id === conv || s.id.startsWith(`${conv}|sub:`)); + const main = sessions.find((s) => s.id === conv); + const forks = sessions.filter((s) => s.id.startsWith(`${conv}|sub:`)); + assert.ok(main, "the main lane persisted under the RAW conversation key"); + assert.ok((main?.requests ?? 0) >= 2, `main rounds rode the raw key (requests=${main?.requests})`); + assert.ok((main?.refs ?? 0) >= 3, `main refs never reset (refs=${main?.refs})`); + assert.ok(forks.length >= 1, `the review request forked onto its own |sub: session — isolation preserved (forks=${JSON.stringify(forks.map((f) => f.id.slice(-12)))})`); +}); diff --git a/tests/side-lane-invariants.test.ts b/tests/side-lane-invariants.test.ts index 83de60cef6..0be535fcaa 100644 --- a/tests/side-lane-invariants.test.ts +++ b/tests/side-lane-invariants.test.ts @@ -197,7 +197,11 @@ test("(D) a design dsh persona fork (auto-review) does NOT trip the split canary // REVIEW_POLICY system, full-budget model turn (NOT a side request — // budget 300, no tools, no side agent) → keyed by design onto // `|sub:` (#1916/#1307/#1314) and rides the main pipeline there. - await h.dshSend(conv, [mainMsg(0), { role: "user", content: "REVIEW: tool call risk assessment" }], undefined, "REVIEW_POLICY: classify the risk of the proposed tool call. Answer SAFE or UNSAFE.", 300); + // #2241: the blob is the FLATTENED transcript as a single fresh user + // message — it does NOT byte-exactly continue the raw key's chain, so + // the continuity-aware anchor still forks it (a replay that DID + // continue the chain is the same conversation evolving, not a persona). + await h.dshSend(conv, [{ role: "user", content: "Conversation transcript (flattened):\nuser: main turn 0\nassistant: ok\nProposed tool call: bash rm -rf /tmp/x. Decide SAFE or UNSAFE." }], undefined, "REVIEW_POLICY: classify the risk of the proposed tool call. Answer SAFE or UNSAFE.", 300); const all = listSessions(); const kids = all.filter((s) => s.id.startsWith(conv + "|") || s.id.includes(conv + "|sub:")); assert.equal(kids.length, 1, `expected exactly one persona-fork child, got ${all.map((s) => s.id).join(", ")}`);