From 20ebd2e62786e669e1d263d0f14f7c8e0d76efc0 Mon Sep 17 00:00:00 2001 From: ci-check Date: Mon, 26 Oct 2026 03:32:38 +0800 Subject: [PATCH 1/2] fix: split header-less claude code subagents onto their own session lane (#4352) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude Code builds that stamp no agent-id headers (VS Code extension) send subagent model requests under the parent session id. Their short, unrelated histories ride the parent session and destroy its fold substrate: fold-reconcile sees covered ids missing, confirms epoch destruction, and the model's compress calls die as substrate-destruction with refs recorded DEAD. The #975 two-signal gate cannot see these subagents: VS Code builds share the parent's first system block verbatim, so the main-prefix negative check fails even when the agent-id headers are present. Route claude anthropic-wire traffic (x-claude-code-session-id source, evidence allowlist in the lane-decisions registry) through the continuity-aware order resolver when the #975 gate misses: a continuing main conversation keeps the raw id on order+content evidence; a history-disjoint ride forks onto its own |sub: lane (own lock chain, own compression state); a byte-drifted system on continuing history still keeps the raw id (#1106). Gated by the existing subagentSplit knob (no new config surface); side calls and empty-system requests stay verbatim. Re-applies the fix from unmerged PR #4409 (closed by a stale-ticket bot that misattributed the closure to #4337, which does not touch this path) onto current master. Closes #4769 (re-report of #4352). Tests: tests/issue4352-claude-anthropic-subagent-split.test.ts — both gate directions plus the live VS Code field shape captured in the issue comment. Docs: CONFIGURATION.md/.zh-CN.md subagentSplit rows describe both paths. --- CONFIGURATION.md | 2 +- CONFIGURATION.zh-CN.md | 2 +- src/config.ts | 12 +- src/host-profiles.ts | 22 +- src/server/handle.ts | 34 +- src/server/lane-decisions.ts | 10 +- src/session-id.ts | 54 ++- ...52-claude-anthropic-subagent-split.test.ts | 339 ++++++++++++++++++ 8 files changed, 439 insertions(+), 36 deletions(-) create mode 100644 tests/issue4352-claude-anthropic-subagent-split.test.ts diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 9e69ee04f7..68e79022ca 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -742,7 +742,7 @@ Top-level keys that control how the proxy listens and behaves globally. - **Type:** `boolean` - **Default:** `true` - **Status:** ACTIVE -- **Description:** Claude Code background-subagent session splitting (#970): anthropic-wire requests carrying the `x-claude-code-agent-id` + `x-claude-code-parent-agent-id` pair get their own `\|sub:` session — own lock chain and compression state — instead of queueing behind the main session's lock. Disabled by `BILI_SUBAGENT_SPLIT=0`. +- **Description:** Claude Code subagent session splitting (#970/#4352), two mechanisms both gated by this switch. (1) anthropic-wire requests carrying the `x-claude-code-agent-id` + `x-claude-code-parent-agent-id` pair get their own `\|sub:` session — own lock chain and compression state — instead of queueing behind the main session's lock. (2) Header-less claude code traffic (the VS Code extension build, whose subagents carry no agent-id headers and share the parent's first system block, so the pair gate misses — #4352) is routed through the continuity-aware order resolver: a continuing main conversation keeps the raw key on order+content evidence, while a history-disjoint subagent ride forks onto its own `\|sub:` lane so it stops destroying the parent's fold substrate. Set `BILI_SUBAGENT_SPLIT=0` to disable BOTH mechanisms. ### `forkAdoption` diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 5b1947722a..17e51f0089 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -742,7 +742,7 @@ - **类型:** `boolean` - **默认值:** `true` - **状态:** ACTIVE -- **说明:** Claude Code 后台子代理会话拆分(#970):携带 `x-claude-code-agent-id` + `x-claude-code-parent-agent-id` 对的 anthropic-wire 请求获得自己的 `\|sub:` 会话 —— 独立的锁链与压缩状态 —— 而不是排在主会话锁后面。`BILI_SUBAGENT_SPLIT=0` 关闭。 +- **说明:** Claude Code subagent 会话拆分(#970/#4352),两套机制都由本开关控制。(1) 携带 `x-claude-code-agent-id` + `x-claude-code-parent-agent-id` 对的 anthropic-wire 请求获得自己的 `\|sub:` 会话 —— 独立的锁链与压缩状态 —— 而不是排在主会话锁后面。(2) 无头 claude code 流量(VS Code 扩展构建:其 subagent 不带 agent-id 头、且与父会话逐字共享第一个 system block,因此双信号门必然不命中,#4352)改走顺序优先会话解析器 —— 历史连续的主会话按顺序+内容证据留在原 key,历史不相交的 subagent 借道则分叉到自己的 `\|sub:` 车道,不再摧毁父会话的折叠基底。设 `BILI_SUBAGENT_SPLIT=0` 同时关闭两套机制。 ### `forkAdoption` diff --git a/src/config.ts b/src/config.ts index 7f394feb3f..02cd6dda0c 100644 --- a/src/config.ts +++ b/src/config.ts @@ -877,10 +877,14 @@ export type ProxyOptions = { * omitted). Opt out for local debugging with env BILI_LOG_MASK_HOSTS=0 * or `maskHosts: false` (#897); credential masking stays on either way. */ maskHosts?: boolean; - /** Split Claude Code subagent requests (parent+agent header pair) into - * their own session id so they don't queue on the main session's lock - * (#970, default on). Opt out with env BILI_SUBAGENT_SPLIT=0 or - * `subagentSplit: false` in the config file (env wins). */ + /** Split Claude Code subagent requests into their own session id so they + * don't queue on the main session's lock (#970, default on). Two + * mechanisms, both gated by this switch: the agent-id header pair split, + * and header-less claude code traffic (VS Code build subagents, #4352) + * routed through the continuity-aware order resolver so a history- + * disjoint ride forks onto its own |sub lane while continuing main + * conversations keep the raw key. Opt out with env BILI_SUBAGENT_SPLIT=0 + * or `subagentSplit: false` in the config file (env wins). */ subagentSplit?: boolean; /** Opt-in fork block-adoption (#629, default off). ANONYMOUS clients * (prefix-affinity) that fork their history inherit the parent's diff --git a/src/host-profiles.ts b/src/host-profiles.ts index 9312b83593..c5e2d9ee99 100644 --- a/src/host-profiles.ts +++ b/src/host-profiles.ts @@ -58,6 +58,16 @@ export interface HostProfile { * share the main session id there). #3482 site 4. */ readonly instructionsFingerprintKeyed: boolean; + /** + * Declared: this client shares one conversation id across personas + * (main agent + subagents), so its ANTHROPIC-wire traffic rides the + * continuity-aware order resolver (personaConversationOrder) for persona + * separation (#4352): a continuing main conversation keeps the raw key on + * order+content evidence, a history-disjoint subagent ride forks onto its + * own |sub: lane. Anthropic wire only — the responses wire expresses + * the same intent via instructionsFingerprintKeyed (#970/#2250). + */ + readonly personaOrderKeyed: boolean; /** * Declared: this host compacts histories CLIENT-SIDE and resends the * compacted form (dsh native compaction, #2432) — the four prepares run @@ -68,7 +78,7 @@ export interface HostProfile { } const PROFILES: Record = { - dsh: { identity: "dsh", toolsHostScopedByDefault: true, wantsBillingBlock: true, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, compactsClientSide: true }, + dsh: { identity: "dsh", toolsHostScopedByDefault: true, wantsBillingBlock: true, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, personaOrderKeyed: false, compactsClientSide: true }, // #4344: zcode reaches the ACP tools ONLY through its MCP bridge // (mcp__bili__* names), and bridge delivery is environmental — zcode's // agent modes gate MCP tools, and the degraded shim path serves an EMPTY @@ -79,16 +89,16 @@ const PROFILES: Record = { // and the surface goes silent instead of advertising a tool the model // cannot call (the #4344 shape: nudges armed at 21-29% usage, 0 // compressions — #3177's "unknown tool" discipline, applied to zcode). - zcode: { identity: "zcode", toolsHostScopedByDefault: true, wantsBillingBlock: false, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, compactsClientSide: false }, - pi: { identity: "pi", toolsHostScopedByDefault: false, wantsBillingBlock: false, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, compactsClientSide: false }, - omp: { identity: "omp", toolsHostScopedByDefault: false, wantsBillingBlock: false, stampsBodyPromptCacheKey: true, coworkTransportPossible: true, instructionsFingerprintKeyed: false, compactsClientSide: false }, - opencode: { identity: "opencode", toolsHostScopedByDefault: false, wantsBillingBlock: false, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, compactsClientSide: false }, + zcode: { identity: "zcode", toolsHostScopedByDefault: true, wantsBillingBlock: false, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, personaOrderKeyed: false, compactsClientSide: false }, + pi: { identity: "pi", toolsHostScopedByDefault: false, wantsBillingBlock: false, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, personaOrderKeyed: false, compactsClientSide: false }, + omp: { identity: "omp", toolsHostScopedByDefault: false, wantsBillingBlock: false, stampsBodyPromptCacheKey: true, coworkTransportPossible: true, instructionsFingerprintKeyed: false, personaOrderKeyed: false, compactsClientSide: false }, + opencode: { identity: "opencode", toolsHostScopedByDefault: false, wantsBillingBlock: false, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, personaOrderKeyed: false, compactsClientSide: false }, }; /** No declared defaults at all — unknown agents and header-less proxy-lane * clients resolve here (lane-decisions re-identifies them by name or wire * signals). Exported because the wire-client table spreads it. */ -export const ANONYMOUS: HostProfile = { identity: "", toolsHostScopedByDefault: false, wantsBillingBlock: false, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, compactsClientSide: false }; +export const ANONYMOUS: HostProfile = { identity: "", toolsHostScopedByDefault: false, wantsBillingBlock: false, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, personaOrderKeyed: false, compactsClientSide: false }; /** Resolve the declared profile for a plugin agent header value. Trimmed * exact match — the historical shape of every pluginAgent comparison. diff --git a/src/server/handle.ts b/src/server/handle.ts index 1ec676fcd4..996c602195 100644 --- a/src/server/handle.ts +++ b/src/server/handle.ts @@ -32,7 +32,7 @@ import { enterSessionContext, log as loggerLog } from "../logger.js"; import { codexCompactGatePre, codexCompactMode, hasCompactionTrigger, isCodexHost, replaceBiliCompactionItems } from "../codex-compact.js"; import { emitPreflightError } from "../stream-error.js"; import { agentProviderRecipes } from "../agent-providers.js"; -import { affinityToken, conversationHeaderSource, claudeSubagentAgentId, claudeSubagentSplit, clientConversationHeader, codexTurnIdentity, dshPersonaFingerprintApplies, instructionsFingerprintApplies, openaiSystemTextForPersona, preferPromptCacheKeyIdentity } from "../session-id.js"; +import { affinityToken, claudeAnthropicPersonaOrderApplies, conversationHeaderSource, claudeSubagentAgentId, claudeSubagentSplit, clientConversationHeader, codexTurnIdentity, dshPersonaFingerprintApplies, instructionsFingerprintApplies, openaiSystemTextForPersona, preferPromptCacheKeyIdentity } from "../session-id.js"; import { personaConversationOrder } from "../session-resolve.js"; import { prefixAffinity, describeResumeMiss, type AnonymousAffinity } from "../prefix-affinity.js"; import { buildAnonymousProvenance, type AnonymousProvenance } from "../anon-provenance.js"; @@ -1085,15 +1085,29 @@ async function handleRequest( // semantics): ride the verbatim id — never route // empty-tag traffic through the order resolver // (codex turn-1 shape keys by its session header). - ? (anthropicIdentity?.value ?? anthropicSignal) - : personaConversationOrder( - anthropicIdentity?.value ?? anthropicSignal, - (parsed as AnthropicRequestBody).messages, - personaSystemText, - pluginReportedModel(req.headers), - )) - : anthropicIdentity?.value ?? anthropicSignal) - : protocol === "openai" + ? (anthropicIdentity?.value ?? anthropicSignal) + : personaConversationOrder( + anthropicIdentity?.value ?? anthropicSignal, + (parsed as AnthropicRequestBody).messages, + personaSystemText, + pluginReportedModel(req.headers), + )) + : claudeAnthropicPersonaOrderApplies(req.headers) && opts.subagentSplit !== false + && !sideRequestLike && personaSystemText !== "" + // #4352: header-less claude code subagents (VS Code + // build) ride the raw parent id; route them through the + // continuity-aware order resolver so a history-disjoint + // ride forks onto its own |sub: lane while a + // continuing main conversation keeps the raw key on + // order+content evidence (#2944). + ? personaConversationOrder( + anthropicIdentity?.value ?? anthropicSignal, + (parsed as AnthropicRequestBody).messages, + personaSystemText, + pluginReportedModel(req.headers), + ) + : anthropicIdentity?.value ?? anthropicSignal) + : protocol === "openai" ? (dshPersona && !sideRequestLike && personaSystemText !== "" ? personaConversationOrder( openaiIdentity?.value ?? openaiSignal, diff --git a/src/server/lane-decisions.ts b/src/server/lane-decisions.ts index 1c480ad193..9964645955 100644 --- a/src/server/lane-decisions.ts +++ b/src/server/lane-decisions.ts @@ -114,10 +114,12 @@ const WIRE_CLIENTS: readonly WireClientEntry[] = [ matches: (s) => !s.headerNames.has("x-bili-plugin") && (s.headerNames.has("x-codex-turn-metadata") || s.codexUserAgent), }, { - // claude over Responses (#970): subagents SHARE the main agent's - // session id (the anthropic path splits them via claudeSubagentSplit; - // a claude client on the Responses wire only has this fingerprint). - profile: { ...ANONYMOUS, identity: "claude-responses", instructionsFingerprintKeyed: true }, + // claude code (#970/#4352): subagents SHARE the main agent's session + // id on every wire. The responses wire separates them via the + // instructions fingerprint (instructionsFingerprintKeyed); the + // anthropic wire via the order resolver (personaOrderKeyed) when the + // two-signal header gate (claudeSubagentAgentId) misses. + profile: { ...ANONYMOUS, identity: "claude-responses", instructionsFingerprintKeyed: true, personaOrderKeyed: true }, matches: (s) => s.conversationSourceName === "x-claude-code-session-id", }, ]; diff --git a/src/session-id.ts b/src/session-id.ts index 66e214e955..f691eafabf 100644 --- a/src/session-id.ts +++ b/src/session-id.ts @@ -102,9 +102,11 @@ export function conversationHeaderSource(headers: Record): boolean { - // Detection only — the client-identity DECISION (who keys by - // instructions) lives in the lane-decisions wire-client registry - // (#3482 site 4): the header-name literals are registry data, not - // scattered comparisons. Signals are name-free observations here. +/** Name-free wire observations for the lane-decisions client registry + * (#3482): present header names, the resolved conversation-source header, + * and the codex user-agent fact. Shared by every predicate below so the + * signal extraction stays single-sourced. */ +function wireClientSignals(headers: Record): { headerNames: Set; conversationSourceName: string | undefined; codexUserAgent: boolean } { const headerNames = new Set(); for (const [name, value] of Object.entries(headers ?? {})) { const first = Array.isArray(value) ? value[0] : value; if (typeof first === "string" && first.trim().length > 0) headerNames.add(name); } - return resolveWireClientProfile({ + return { headerNames, conversationSourceName: conversationHeaderSource(headers)?.name, codexUserAgent: isCodexClient(headers), - }).instructionsFingerprintKeyed; + }; +} + +export function instructionsFingerprintApplies(headers: Record): boolean { + // Detection only — the client-identity DECISION (who keys by + // instructions) lives in the lane-decisions wire-client registry + // (#3482 site 4): the header-name literals are registry data, not + // scattered comparisons. Signals are name-free observations here. + return resolveWireClientProfile(wireClientSignals(headers)).instructionsFingerprintKeyed; +} + +/** #4352: whether THIS request's claude-code-over-Anthropic traffic should + * ride the continuity-aware order resolver (personaConversationOrder) for + * persona separation when the #970 two-signal header gate + * (claudeSubagentAgentId) misses. + * + * Evidence (v0.1.204 field report, #4352): Claude Code stamps ONE session id + * on every model request of a session INCLUDING Task-tool subagents, and the + * VS Code extension build's subagent requests carry no agent-id headers at + * all — so claudeSubagentAgentId misses and those subagents ride the raw + * parent id, where their disjoint short histories accumulate fold-reconcile + * drop events until epoch confirmation fires substrate-destruction and the + * parent's refs go permanently DEAD (compress rejected for the rest of the + * session). Routing such traffic through the order resolver separates exactly + * those disjoint rides onto |sub: lanes while a continuing main + * conversation keeps the raw key on order+content evidence (#2944) — the same + * mechanism the dsh lane uses (#1916). + * + * Detection only — the client-identity DECISION lives in the lane-decisions + * wire-client registry (#3482 site 4), same shape as + * instructionsFingerprintApplies above. */ +export function claudeAnthropicPersonaOrderApplies(headers: Record): boolean { + return resolveWireClientProfile(wireClientSignals(headers)).personaOrderKeyed; } /** #1916/#1307/#1314: whether the persona fingerprint (session id + system diff --git a/tests/issue4352-claude-anthropic-subagent-split.test.ts b/tests/issue4352-claude-anthropic-subagent-split.test.ts new file mode 100644 index 0000000000..4e28808a1a --- /dev/null +++ b/tests/issue4352-claude-anthropic-subagent-split.test.ts @@ -0,0 +1,339 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import { createHash, randomUUID } from "node:crypto"; +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _resetSessionsForTest, _sessionsSizeForTest, peekSession } from "../src/session.ts"; +import { claudeAnthropicPersonaOrderApplies } from "../src/session-id.ts"; +import { resetSessionOrderForTest, resolveSessionOrder } from "../src/session-resolve.ts"; +import type { ProxyOptions } from "../src/config.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; + +// #4352: claude code builds that stamp NO agent-id headers (VS Code extension +// subagents) ride the parent session id. Their traffic must fork onto its own +// |sub lane instead of destroying the parent's fold substrate. + +// Every test mints its OWN session id: the order-resolver skeleton state is +// persisted per raw id (#3397) and re-hydrated on each server boot, so a fixed +// id shared across tests would let one test's system-drift anchor migration +// (#2241) leak into the next test's resolution. + +// System-block shapes captured from live Claude Code traffic (same corpus as +// tests/claude-subagent-split.test.ts). +const MAIN_SYSTEM = ["You are Claude Code, Anthropic's official CLI for Claude. You are an interactive agent..."]; +const SUB_AGENT_SYSTEM = ["x-anthropic-billing-header: cc_version=...", "You are a Claude agent, built on Anthropic's...", "You are a file search specialist for..."]; +const OTHER_SUB_SYSTEM = ["x-anthropic-billing-header: cc_version=...", "You are a Claude agent, built on Anthropic's...", "This session is a background job. The..."]; + +const tag = (blocks: string[]): string => blocks.join("\n\n"); +const forkKey = (conv: string, systemText: string): string => + `${conv}|sub:${createHash("sha256").update(systemText, "utf8").digest("hex").slice(0, 16)}`; + +type Msg = { role: string; content: string }; +/** n alternating user/assistant turns with distinct per-prefix content. */ +function history(prefix: string, turns: number): Msg[] { + const out: Msg[] = []; + for (let i = 1; i <= turns; i++) { + out.push({ role: "user", content: `${prefix}-user-${i}` }); + out.push({ role: "assistant", content: `${prefix}-assistant-${i}` }); + } + return out; +} + +function sse(type: string, data: Record): string { + return `event: ${type}\ndata: ${JSON.stringify(data)}\n\n`; +} + +/** Minimal valid Anthropic /v1/messages SSE stream: one text block "ok". */ +function anthropicStream(): string { + return ( + sse("message_start", { message: { id: "msg_1", type: "message", role: "assistant", model: "claude-test", content: [], stop_reason: null, usage: { input_tokens: 10, output_tokens: 1 } } }) + + sse("content_block_start", { index: 0, content_block: { type: "text", text: "" } }) + + sse("content_block_delta", { index: 0, delta: { type: "text_delta", text: "ok" } }) + + sse("content_block_stop", { index: 0 }) + + sse("message_delta", { delta: { stop_reason: "end_turn" }, usage: { output_tokens: 2 } }) + + sse("message_stop", {}) + ); +} + +function startMockUpstream(): http.Server { + const server = http.createServer((_req, res) => { + res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" }); + res.write(anthropicStream()); + res.end(); + }); + server.listen(0, "127.0.0.1"); + return server; +} + +function listen(server: http.Server): Promise { + if (server.listening) return Promise.resolve(); + return once(server, "listening").then(() => undefined); +} + +function close(server: http.Server): Promise { + return new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve()))); +} + +async function startHarness(upstream: http.Server, over: Partial = {}): Promise<{ proxy: http.Server; post: (headers: Record, body?: Record) => Promise<{ status: number; text: string }> }> { + const upstreamPort = (upstream.address() as { port: number }).port; + const opts: ProxyOptions = { + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upstreamPort}`]: { models: { "claude-test": { context: 1_000_000 } } } } as ProxyOptions["routes"], + modelContextLimit: 1_000_000, + kernelConfig: defaultConfig(1_000_000), + compress: { injectTool: false, 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: [] }, + ...over, + }; + const proxy = await startServer(opts); + await listen(proxy); + const proxyPort = (proxy.address() as { port: number }).port; + const url = `http://127.0.0.1:${proxyPort}/bili/http://127.0.0.1:${upstreamPort}/v1/messages`; + const post = async (headers: Record, body?: Record) => { + const res = await fetch(url, { + method: "POST", + headers: { "content-type": "application/json", ...headers }, + body: JSON.stringify(body ?? { model: "claude-test", stream: true, max_tokens: 1024, messages: [{ role: "user", content: "hi" }] }), + duplex: "half", + } as RequestInit); + const text = await res.text(); + return { status: res.status, text }; + }; + return { proxy, post }; +} + +function freshState(): void { + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + _resetSessionsForTest(); + resetSessionOrderForTest(); +} + +const ccHeadersFor = (id: string) => ({ "x-claude-code-session-id": id }); +const sysBlocks = (system: string[]) => system.map((t) => ({ type: "text", text: t })); +const mainBody = (hist: Msg[], system: string[] = MAIN_SYSTEM): Record => + ({ model: "claude-test", stream: true, max_tokens: 1024, system: sysBlocks(system), messages: hist }); + +test("claudeAnthropicPersonaOrderApplies: allowlist is the claude-code conversation source only", () => { + const id = randomUUID(); + assert.equal(claudeAnthropicPersonaOrderApplies({ "x-claude-code-session-id": id }), true); + assert.equal(claudeAnthropicPersonaOrderApplies({ "x-acp-session": id }), false, "plain anthropic clients keep verbatim identity (#1106)"); + assert.equal(claudeAnthropicPersonaOrderApplies({ "x-bili-plugin": "dsh", "x-bili-plugin-conversation": id }), false, "dsh keeps its own persona mechanism (#1916)"); + assert.equal(claudeAnthropicPersonaOrderApplies({}), false); +}); + +test("#4352 resolver rows: disjoint ride forks; continuing main and compaction keep the raw key", () => { + const SESSION = randomUUID(); + const MAIN_TAG = tag(MAIN_SYSTEM); + const SUB_TAG = tag(SUB_AGENT_SYSTEM); + const OTHER_TAG = tag(OTHER_SUB_SYSTEM); + + resetSessionOrderForTest(); + const claim = resolveSessionOrder(SESSION, history("main", 4), MAIN_TAG); + assert.equal(claim.key, SESSION, "first sight claims the raw id"); + assert.equal(claim.action, "claim"); + + const ride = resolveSessionOrder(SESSION, history("sub", 2), SUB_TAG); + assert.equal(ride.key, forkKey(SESSION, SUB_TAG), "history-disjoint ride under a different system forks onto its own lane"); + assert.equal(ride.action, "derived-persona"); + + const ride2 = resolveSessionOrder(SESSION, history("sub", 3), SUB_TAG); + assert.equal(ride2.key, forkKey(SESSION, SUB_TAG), "successive passes of the same persona stay on ONE lane (ref continuity)"); + + const other = resolveSessionOrder(SESSION, history("other", 2), OTHER_TAG); + assert.notEqual(other.key, ride.key, "a different subagent system gets its own lane"); + + const drifted = resolveSessionOrder(SESSION, history("main", 5), MAIN_TAG + "\n[additional context loaded]"); + assert.equal(drifted.key, SESSION, "byte-drifted system on a verbatim-continuing history keeps the raw key (#1106)"); + assert.equal(drifted.action, "reanchor"); + + resetSessionOrderForTest(); + resolveSessionOrder(SESSION, history("main", 4), MAIN_TAG); + // Native /compact shape: the head collapses into a summary, the living tail + // stays verbatim, same system — must stay on the raw key. + const compacted = [ + { role: "user", content: "" }, + ...history("main", 4).slice(-4), + ]; + const compactRes = resolveSessionOrder(SESSION, compacted, MAIN_TAG); + assert.equal(compactRes.key, SESSION, "head-rewritten /compact replay keeps the raw key"); +}); + +test("#4352 field shape: VS Code build shares the parent's first system block; the fork still fires", () => { + // Live transcripts from Claude Code VS Code extension 2.1.307 (issue + // comment): the parent and ALL subagents send the SAME first system block + // verbatim — only the second block differs. The #975 main-prefix heuristic + // therefore cannot separate these subagents (their first block starts with + // "You are Claude Code"); separation must come from order+tag alone. + const SESSION = randomUUID(); + const SHARED = "You are Claude Code, Anthropic's official CLI for Claude, running within the Claude Agent SDK."; + const PARENT_TAG = [SHARED, "You are an interactive agent... (parent-specific second block)"].join("\n\n"); + const SUB_TAG = [SHARED, "You are an agent for Claude Code, ... (subagent second block)"].join("\n\n"); + + resetSessionOrderForTest(); + resolveSessionOrder(SESSION, history("main", 4), PARENT_TAG); + const ride = resolveSessionOrder(SESSION, history("sub", 2), SUB_TAG); + assert.equal(ride.key, forkKey(SESSION, SUB_TAG), "a shared first system block does not block the fork (order+tag decide)"); + assert.equal(ride.action, "derived-persona"); + const back = resolveSessionOrder(SESSION, history("main", 5), PARENT_TAG); + assert.equal(back.key, SESSION, "the parent returns to the raw key after the subagent burst"); +}); + +test("#4352 split: header-less subagent rides its own lane; the parent session is untouched", async () => { + freshState(); + const SESSION = randomUUID(); + const ccHeaders = ccHeadersFor(SESSION); + const upstream = startMockUpstream(); + await listen(upstream); + const { proxy, post } = await startHarness(upstream); + try { + for (let t = 1; t <= 3; t++) { + const r = await post(ccHeaders, mainBody(history("main", t))); + assert.equal(r.status, 200, `parent turn ${t}: ${r.text}`); + } + const parentBefore = peekSession(SESSION); + assert.ok(parentBefore, "parent session exists"); + assert.equal(parentBefore.stats.requests, 3); + + const sub1 = await post(ccHeaders, mainBody(history("sub", 2), SUB_AGENT_SYSTEM)); + assert.equal(sub1.status, 200, `subagent pass 1: ${sub1.text}`); + const subKey = forkKey(SESSION, tag(SUB_AGENT_SYSTEM)); + const subSession = peekSession(subKey); + assert.ok(subSession, "header-less subagent must fork onto its own |sub: lane"); + assert.notEqual(subSession, parentBefore, "forked lane is a separate session object (own lock chain / compression state)"); + assert.equal(peekSession(SESSION), parentBefore, "parent session object is the same instance"); + assert.equal(parentBefore.stats.requests, 3, "subagent turns must not accumulate on the parent"); + + const sub2 = await post(ccHeaders, mainBody(history("sub", 3), SUB_AGENT_SYSTEM)); + assert.equal(sub2.status, 200, `subagent pass 2: ${sub2.text}`); + assert.equal(peekSession(subKey)!.stats.requests, 2, "successive passes share ONE forked session"); + assert.equal(parentBefore.stats.requests, 3, "parent still untouched after pass 2"); + + const main4 = await post(ccHeaders, mainBody(history("main", 4))); + assert.equal(main4.status, 200, `parent turn 4: ${main4.text}`); + assert.equal(parentBefore.stats.requests, 4, "the parent continues accumulating on the raw key after the burst"); + } finally { + await close(proxy); + await close(upstream); + } +}); + +test("#4352 negative: a main turn with a byte-drifted system keeps the raw key (#1106)", async () => { + freshState(); + const SESSION = randomUUID(); + const ccHeaders = ccHeadersFor(SESSION); + const upstream = startMockUpstream(); + await listen(upstream); + const { proxy, post } = await startHarness(upstream); + try { + for (let t = 1; t <= 3; t++) { + const r = await post(ccHeaders, mainBody(history("main", t))); + assert.equal(r.status, 200, `parent turn ${t}: ${r.text}`); + } + const drifted = [...MAIN_SYSTEM, "[additional context loaded]"]; + const r = await post(ccHeaders, mainBody(history("main", 4), drifted)); + assert.equal(r.status, 200, `drifted-system continuation: ${r.text}`); + assert.equal(peekSession(SESSION)!.stats.requests, 4, "continuation must stay on the raw key"); + assert.equal(peekSession(forkKey(SESSION, tag(drifted))), undefined, "no |sub lane is minted for a continuing conversation"); + } finally { + await close(proxy); + await close(upstream); + } +}); + +test("#4352 negative: non-claude anthropic clients stay verbatim (#1106)", async () => { + freshState(); + const OTHER_SESSION = randomUUID(); + const upstream = startMockUpstream(); + await listen(upstream); + const { proxy, post } = await startHarness(upstream); + try { + const headers = { "x-acp-session": OTHER_SESSION }; + // Two disjoint main-shaped conversations under the same id must behave + // EXACTLY as before the fix: verbatim identity, one session. + for (let t = 1; t <= 2; t++) { + const r = await post(headers, mainBody(history("alpha", t))); + assert.equal(r.status, 200, `alpha turn ${t}: ${r.text}`); + } + for (let t = 1; t <= 2; t++) { + const r = await post(headers, mainBody(history("beta", t), OTHER_SUB_SYSTEM)); + assert.equal(r.status, 200, `beta turn ${t}: ${r.text}`); + } + assert.equal(peekSession(OTHER_SESSION)!.stats.requests, 4, "all four requests accumulate on the one verbatim session"); + assert.equal(peekSession(forkKey(OTHER_SESSION, tag(OTHER_SUB_SYSTEM))), undefined, "no fork lane is minted for non-claude clients"); + } finally { + await close(proxy); + await close(upstream); + } +}); + +test("#4352 opt-out: subagentSplit:false disables the header-less fallback too", async () => { + freshState(); + const SESSION = randomUUID(); + const ccHeaders = ccHeadersFor(SESSION); + const upstream = startMockUpstream(); + await listen(upstream); + const { proxy, post } = await startHarness(upstream, { subagentSplit: false }); + try { + for (let t = 1; t <= 3; t++) { + const r = await post(ccHeaders, mainBody(history("main", t))); + assert.equal(r.status, 200, `parent turn ${t}: ${r.text}`); + } + const sub = await post(ccHeaders, mainBody(history("sub", 2), SUB_AGENT_SYSTEM)); + assert.equal(sub.status, 200, `subagent with split off: ${sub.text}`); + assert.equal(peekSession(SESSION)!.stats.requests, 4, "with the split off, the subagent rides the raw key (pre-fix behavior)"); + assert.equal(peekSession(forkKey(SESSION, tag(SUB_AGENT_SYSTEM))), undefined, "with the split off, no fork lane is minted"); + } finally { + await close(proxy); + await close(upstream); + } +}); + +test("#4352 exemptions: side calls and empty-system requests stay verbatim", async () => { + freshState(); + const SESSION = randomUUID(); + const ccHeaders = ccHeadersFor(SESSION); + const upstream = startMockUpstream(); + await listen(upstream); + const { proxy, post } = await startHarness(upstream); + try { + for (let t = 1; t <= 2; t++) { + const r = await post(ccHeaders, mainBody(history("main", t))); + assert.equal(r.status, 200, `parent turn ${t}: ${r.text}`); + } + // Tool-less request with a small output budget = the #388 side-request + // shape: it rides the main session key verbatim by contract. Side calls + // never increment stats.requests (the passthrough lane skips the + // counter), so only the two parent turns + the empty-system request + // count here. + const side = await post(ccHeaders, { model: "claude-test", stream: true, max_tokens: 100, system: sysBlocks(MAIN_SYSTEM), messages: [{ role: "user", content: "summarize in one word" }] }); + assert.equal(side.status, 200, `side call: ${side.text}`); + assert.equal(peekSession(SESSION)!.stats.requests, 2, "side call rides the raw key but does not bump the request counter"); + // Empty system is non-anchoring (kernel anchor semantics): verbatim. + const bare = await post(ccHeaders, { model: "claude-test", stream: true, max_tokens: 1024, messages: history("sub", 2) }); + assert.equal(bare.status, 200, `empty-system request: ${bare.text}`); + assert.equal(peekSession(SESSION)!.stats.requests, 3, "both exempt shapes land on the raw key; side calls are uncounted"); + assert.equal(_sessionsSizeForTest(), 1, "no fork lane is minted for exempt shapes"); + } finally { + await close(proxy); + await close(upstream); + } +}); From 5c6d37f1bf5e44899179eba8cf5d8800b85acaf7 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Tue, 27 Oct 2026 23:53:03 +0800 Subject: [PATCH 2/2] test(side-lane): pin the #4352 anthropic persona gate's sideRequestLike veto (#2170) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The header-less claude-code persona fork landed in src/server/handle.ts's anthropic ladder with a fresh !sideRequestLike conjunct. Per the #2170 lane-guard discipline a lane-symbol edit in handle.ts must land with a dedicated lane-suite pin. Row (K) is that pin, contrast-shaped: the same claude-code persona traffic with sideRequestLike=true (tiny tool-less budget, no agent header) stays verbatim on the raw key — counted nowhere, no persisted |sub ghost — while the full-budget shape rides the order resolver and forks its own |sub: lane. --- tests/side-lane-invariants.test.ts | 50 ++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/tests/side-lane-invariants.test.ts b/tests/side-lane-invariants.test.ts index 1755e36f7a..aabcb12f03 100644 --- a/tests/side-lane-invariants.test.ts +++ b/tests/side-lane-invariants.test.ts @@ -366,3 +366,53 @@ test("(I) revival (#3402): the absorb tool name is bili-owned again", () => { test("(J) post-#3400: acp_read_original_image is bili-owned for #1897 demotion", () => { assert.ok(BILI_TOOL_NAMES.has(READ_ORIGINAL_IMAGE_TOOL_NAME), "acp_read_original_image is in the bili-owned set"); }); + +// (#4352): the header-less claude-code persona gate landed in src/server/handle.ts's +// anthropic ladder with a fresh `!sideRequestLike` conjunct — a lane-symbol edit +// in handle.ts must land with a dedicated lane-suite pin (#2170 discipline). This +// row is that pin, contrast-shaped: the SAME claude-code persona traffic, with +// sideRequestLike=true (tiny tool-less budget, no agent header) stays verbatim on +// the raw key and observation-transparent, while sideRequestLike=false (full +// budget) rides the order resolver and forks its own |sub: lane. +test("(K) #4352 anthropic persona gate is side-vetoed: side shape stays verbatim, full-budget shape forks", async () => { + const h = await harness(); + try { + const conv = "cc4352"; + const ccSend = async (system: string, msgs: unknown[], maxTokens: number) => { + const r = await fetch(`${h.origin}/bili/${h.upstreamUrl}/v1/messages`, { + method: "POST", + headers: { "content-type": "application/json", "x-claude-code-session-id": conv }, + body: JSON.stringify({ model: "claude-test", stream: false, max_tokens: maxTokens, system, messages: msgs }), + }); + assert.equal(r.status, 200, await r.text()); + }; + // main turn anchors the raw key (claude-code main persona) + await ccSend("You are Claude Code, Anthropic's official CLI for Claude. You are an interactive agent.", [mainMsg(0)], 256); + const session = resolveConversation(conv).session!; + assert.equal(session.stats.requests, 1, "main turn counted once on the parent"); + const sessions = listSessions().length; + + // side shape: same raw id, SUB persona system, tool-less tiny budget (<= + // the #388 heuristic, no agent header) → the new anthropic gate is + // vetoed by !sideRequestLike: verbatim raw key, counted nowhere, and + // NO persisted |sub ghost for it. + const hits = h.forwarded.length; + await ccSend("You are a file search specialist for the parent session.", [{ role: "user", content: "summarize" }], 100); + assert.equal(h.forwarded.length, hits + 1, "the side call reaches the upstream"); + assert.equal(resolveConversation(conv).session!.stats.requests, 1, "side call never counts on the parent"); + assert.equal(listSessions().length, sessions, "side call must not fork a |sub lane"); + + // full-budget shape: the SAME sub persona system + disjoint history → the + // resolver DOES engage (proof the verbatim above is the sideRequestLike + // conjunct, not a dead gate): a |sub: lane appears, parent untouched. + await ccSend("You are a file search specialist for the parent session.", [ + { role: "user", content: "sub-user-1" }, + { role: "assistant", content: "sub-assistant-1" }, + { role: "user", content: "sub-user-2" }, + ], 1024); + assert.equal(listSessions().length, sessions + 1, "full-budget sub persona forks its own |sub lane"); + assert.equal(resolveConversation(conv).session!.stats.requests, 1, "the fork lane counts nowhere on the parent"); + } finally { + await h.close(); + } +});