From 5c0e6bd9fddfa6342179c5081ff86cc6ea81e98d Mon Sep 17 00:00:00 2001 From: WSXYT Date: Sat, 17 Oct 2026 22:54:18 +0800 Subject: [PATCH 1/3] fix: preserve native Pi compress carrier identity (#3587) --- src/agent/pi.ts | 4 +- src/agent/shared.ts | 5 +- src/plugin.ts | 54 ++++++++-- src/server/prepare-responses.ts | 2 + tests/plugin-agent.test.ts | 6 +- tests/plugin-call-identity.test.ts | 165 +++++++++++++++++++++++++++++ 6 files changed, 222 insertions(+), 14 deletions(-) create mode 100644 tests/plugin-call-identity.test.ts diff --git a/src/agent/pi.ts b/src/agent/pi.ts index 2b3a56059f..545fa859ec 100644 --- a/src/agent/pi.ts +++ b/src/agent/pi.ts @@ -554,7 +554,7 @@ function manifestToTool(proxyBase: string, tool: ManifestTool, agent: string): T description: tool.description, parameters: tool.inputSchema, loadMode: "essential", - execute: async (_toolCallId, params, signal, _onUpdate, ctx) => { + execute: async (toolCallId, params, signal, _onUpdate, ctx) => { const conversationId = sessionIdOf(ctx) ?? "unknown"; try { // #2416: read the LIVE base — a native respawn after a proxy @@ -574,7 +574,7 @@ function manifestToTool(proxyBase: string, tool: ManifestTool, agent: string): T // rebinding (onRoutedOriginObserved) converges env back to the // observed routed origin. const base = proxyBaseForCtx(ctx) ?? proxyBase; - const output = await forwardTool(base, conversationId, tool.name, params, signal, conversationId !== "unknown"); + const output = await forwardTool(base, conversationId, tool.name, params, signal, conversationId !== "unknown", toolCallId); // #2204: a business failure (e.g. a refused export) must reach // the host as isError — rendering it as plain success text is // what hid the #2204 write failures from OMP. diff --git a/src/agent/shared.ts b/src/agent/shared.ts index 408dea25fd..54ab67c896 100644 --- a/src/agent/shared.ts +++ b/src/agent/shared.ts @@ -334,8 +334,9 @@ export async function reportRuntimeInfoOnChange(proxyBase: string | undefined, i * partial note in `text`. Absent on legacy envelopes without the fields. */ export type ForwardedToolResult = { text: string; failed: boolean; outcome?: ToolOutcomeKind; blocksCreated?: number }; -export async function forwardTool(proxyBase: string, conversationId: string, tool: string, args: unknown, signal?: AbortSignal, nativeCaller: boolean = false): Promise { - const body: { conversationId: string; tool: string; args: unknown; nativeCaller?: boolean } = { conversationId, tool, args: args ?? {} }; +export async function forwardTool(proxyBase: string, conversationId: string, tool: string, args: unknown, signal?: AbortSignal, nativeCaller: boolean = false, toolCallId?: string): Promise { + const body: { conversationId: string; tool: string; args: unknown; nativeCaller?: boolean; toolCallId?: string } = { conversationId, tool, args: args ?? {} }; + if (toolCallId !== undefined) body.toolCallId = toolCallId; // #2072: host-native agents (pi / dsh / opencode) stamp a per-call id minted // by the host's own session manager — declare it so a stale sibling witness // can neither redirect nor fail-closed the call (ladder rung 0, #2024/#2016). diff --git a/src/plugin.ts b/src/plugin.ts index 8b9fa0b10c..ce4ffbf6bd 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -126,15 +126,54 @@ const PLUGIN_REQUEST_AGENT_HEADER = "x-bili-plugin-agent"; const PLUGIN_PROTOCOL_VERSION = 1; -/** #1567: folds executed through POST /__bili/plugin/tool are minted this - * synthetic callId, which the client can never echo back — its own re-sent - * compress pair is the summary carrier for such blocks, so the kernel's - * in-place acp_summary anchor is redundant and must be stripped (#1567). */ +/** #1567: legacy callers without a native tool-call id get a synthetic id. + * Their resent compress pair is recognized by range as a summary carrier. */ const PLUGIN_FOLD_CALLID_PREFIX = "plugin_"; export function isPluginFoldCallId(callId: string | undefined): boolean { return typeof callId === "string" && callId.startsWith(PLUGIN_FOLD_CALLID_PREFIX); } +/** Reconnect legacy plugin blocks before the kernel mistakes their live carriers for orphans. */ +export function reconcilePluginFoldCallIds(session: Session, messages: CoreMessage[]): number { + const blocks = new Map(); + for (const block of session.state.blocks) { + if (!block.active || !block.startRef || !block.endRef) continue; + const key = JSON.stringify([block.startRef, block.endRef]); + const sameRange = blocks.get(key) ?? []; + sameRange.push(block); + blocks.set(key, sameRange); + } + const calls = new Map>(); + const results = new Map(messages.filter((m) => m.contentType === "tool-result" && m.toolCallId).map((m) => [m.toolCallId!, m.text ?? ""])); + for (const message of messages) { + if (message.contentType !== "tool-call" || message.toolName !== "compress" || !message.toolCallId) continue; + try { + const args = JSON.parse(message.text ?? "") as { content?: unknown; startId?: unknown; endId?: unknown }; + for (const range of Array.isArray(args?.content) ? args.content : [args]) { + if (!range || typeof range.startId !== "string" || typeof range.endId !== "string") continue; + const key = JSON.stringify([range.startId, range.endId]); + if (!blocks.has(key)) continue; + const ids = calls.get(key) ?? new Set(); + ids.add(message.toolCallId); + calls.set(key, ids); + } + } catch { /* Invalid historical arguments cannot establish ownership. */ } + } + let changed = 0; + for (const [key, sameRange] of blocks) { + const block = sameRange[0]!; + const ids = calls.get(key); + if (sameRange.length !== 1 || !isPluginFoldCallId(block.compressCallId) || ids?.size !== 1) continue; + const id = ids.values().next().value!; + const receipt = results.get(id); + if (!receipt?.startsWith("[Compressed ") || !receipt.split("\n").some((line) => line.startsWith(` · ${block.blockId} full summary `))) continue; + block.compressCallId = id; + changed++; + } + if (changed > 0) markDirty(session); + return changed; +} + const VERSION = (() => { try { const here = fileURLToPath(import.meta.url); @@ -1597,9 +1636,9 @@ export async function handlePluginTool( res: import("node:http").ServerResponse, deps: PluginToolDeps, ): Promise { - let parsed: { conversationId?: unknown; tool?: unknown; args?: unknown; expectedRevision?: unknown; nativeCaller?: unknown }; + let parsed: { conversationId?: unknown; tool?: unknown; args?: unknown; expectedRevision?: unknown; nativeCaller?: unknown; toolCallId?: unknown }; try { - parsed = JSON.parse(payload) as { conversationId?: unknown; tool?: unknown; args?: unknown; expectedRevision?: unknown; nativeCaller?: unknown }; + parsed = JSON.parse(payload) as { conversationId?: unknown; tool?: unknown; args?: unknown; expectedRevision?: unknown; nativeCaller?: unknown; toolCallId?: unknown }; if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("expected tool object"); } catch { res.writeHead(400, { "content-type": "application/json" }); @@ -1608,6 +1647,7 @@ export async function handlePluginTool( } const conversationId = typeof parsed.conversationId === "string" ? parsed.conversationId.trim() : ""; const tool = typeof parsed.tool === "string" ? parsed.tool : ""; + if (parsed.toolCallId !== undefined && (typeof parsed.toolCallId !== "string" || !parsed.toolCallId.trim() || parsed.toolCallId.length > 512)) return forkReply(res, 400, { ok: false, code: "INVALID_REQUEST", error: "toolCallId must be a non-empty string of at most 512 characters" }); if (parsed.expectedRevision !== undefined && (typeof parsed.expectedRevision !== "string" || !/^[a-f0-9]{64}$/.test(parsed.expectedRevision))) return forkReply(res, 400, { ok: false, code: "INVALID_REQUEST", error: "expectedRevision must be a snapshot revision" }); if (parsed.expectedRevision !== undefined && !conversationId) return forkReply(res, 400, { ok: false, code: "INVALID_REQUEST", error: "expectedRevision requires conversationId" }); // Explicit ids never yield to another session's outbound witness. A @@ -1761,7 +1801,7 @@ export async function handlePluginTool( // may still echo one — strip it before kernel arg parsing sees it (the // witness hash in tool-ring.ts strips the same key). delete args.conversation_id; - const callId = `${PLUGIN_FOLD_CALLID_PREFIX}${Date.now().toString(36)}`; + const callId = typeof parsed.toolCallId === "string" ? parsed.toolCallId : `${PLUGIN_FOLD_CALLID_PREFIX}${Date.now().toString(36)}`; acquireInFlight(session); let result: ProxyToolResult | undefined; let retrievalExport: RetrievalExport | undefined; diff --git a/src/server/prepare-responses.ts b/src/server/prepare-responses.ts index b8ec042f3e..54e807f228 100644 --- a/src/server/prepare-responses.ts +++ b/src/server/prepare-responses.ts @@ -29,6 +29,7 @@ import { isStrictReasoningEcho, modelIdOf, normalizeStrictEchoResponsesInput } f import { reconcileSystemAnchor } from "../system-anchor.js"; import { buildPromptForgeBody, buildTriggerForgeBody, carriesCodexLocalCompactionSummary, codexCompactGate, codexCompactGatePre, codexCompactMode, hasCompactionPrompt, hasCompactionTrigger, isCodexClient, mergeForgedSummaries, replaceBiliCompactionItems, stripBiliCompactionItems, CODEX_COMPACT_HEALTH_RATIO, CODEX_LOCAL_COMPACTION_MIN_MISSING } from "../codex-compact.js"; import type { ConversationIdentity } from "../session-id.js"; +import { reconcilePluginFoldCallIds } from "../plugin.js"; import { logRawStripCounts, markerArtifactCount, stripRawStage } from "../marker/engine.js"; import { imageRescaleMaxDim, keepResponseId as knobKeepResponseId, noCompressPrompt as knobNoCompressPrompt, noInjectTool as knobNoInjectTool, renderNone as knobRenderNone } from "../knobs.js"; import { applyImageRescaleItems } from "../image-rescale.js"; @@ -264,6 +265,7 @@ export async function prepareResponses( } } } + if (pluginMode && !isCompactionTrigger && !hasCompactionPrompt(parsed.input)) reconcilePluginFoldCallIds(session, msgs); // [#1921] re-anchor fold coverage onto churned-but-same messages // before the #1195 snapshot, so covered ids surviving a client // re-serialization stay covered (src/fold-reconcile.ts). diff --git a/tests/plugin-agent.test.ts b/tests/plugin-agent.test.ts index b8473e915c..c012d58a63 100644 --- a/tests/plugin-agent.test.ts +++ b/tests/plugin-agent.test.ts @@ -77,7 +77,7 @@ test("proxyBaseFromEnv accepts BILLION_CONTEXT_PROXY, detectProxyBase honors kil type FakeProxy = { origin: string; - toolCalls: Array<{ conversationId: string; tool: string; args: unknown; nativeCaller?: boolean }>; + toolCalls: Array<{ conversationId: string; tool: string; args: unknown; nativeCaller?: boolean; toolCallId?: string }>; registers: Array<{ conversationId: string; agent: string; identity: boolean; parentConversationId?: string }>; runtimeInfos: Array>; close(): Promise; @@ -752,7 +752,7 @@ test("pi extension registers manifest tools and stamps headers when proxied", as assert.equal(out.isError, undefined); // #2072: the pi host stamps its session-manager id as a confirmed // native caller — the captured wire body carries the flag. - assert.deepEqual(proxy.toolCalls, [{ conversationId: "sess-42", tool: "compress", args: { content: [] }, nativeCaller: true }]); + assert.deepEqual(proxy.toolCalls, [{ conversationId: "sess-42", tool: "compress", args: { content: [] }, nativeCaller: true, toolCallId: "call-1" }]); const errOut = await pi.tools[1]!.execute("call-2", {}, undefined, undefined, fakeCtx(proxy)); assert.match(errOut.content[0]!.text, /bili tool error:.*boom/); assert.equal(errOut.isError, true); @@ -814,7 +814,7 @@ test("#2416: registered tools track the respawned proxy origin — live re-read out = await pi.tools[0]!.execute("call-2", { content: [] }, undefined, undefined, ctx); assert.equal(out.isError, undefined, "the tool must reach the respawned proxy, not keep firing at the dead port"); assert.match(out.content[0]!.text, /\[Compressed/); - assert.deepEqual(newProxy.toolCalls, [{ conversationId: "sess-42", tool: "compress", args: { content: [] }, nativeCaller: true }]); + assert.deepEqual(newProxy.toolCalls, [{ conversationId: "sess-42", tool: "compress", args: { content: [] }, nativeCaller: true, toolCallId: "call-2" }]); assert.equal(oldProxy.toolCalls.length, 1, "nothing further may hit the dead origin"); } finally { if (prevEnv === undefined) delete process.env.BILLION_CONTEXT_PROXY; diff --git a/tests/plugin-call-identity.test.ts b/tests/plugin-call-identity.test.ts new file mode 100644 index 0000000000..7ea6970bf7 --- /dev/null +++ b/tests/plugin-call-identity.test.ts @@ -0,0 +1,165 @@ +import assert from "node:assert/strict"; +import http from "node:http"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { once } from "node:events"; +import test, { after } from "node:test"; +import type { ResponseInputItem } from "acp-kernel/wire"; +import type { ProxyOptions } from "../src/config.ts"; +import { rmrf } from "./tmp-rm.ts"; + +const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-call-identity-")); +for (const key of ["XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_CONFIG_HOME", "XDG_CACHE_HOME"]) process.env[key] = path.join(home, key); +process.env.BILI_CONFIG_FILE = path.join(home, "config.json"); +process.env.BILI_SESSIONS_DIR = path.join(home, "sessions"); +after(() => rmrf(home)); +const { defaultConfig } = await import("acp-kernel"); +const { startServer } = await import("../src/server.ts"); +const { SessionStore, _setStoreForTest } = await import("../src/persist.ts"); +const { _setForTest: setRegistryForTest } = await import("../src/registry.ts"); +const { _resetPluginStateForTest } = await import("../src/plugin.ts"); +const { listSessions, _resetSessionsForTest } = await import("../src/session.ts"); + +async function harness() { + const inputs: ResponseInputItem[][] = []; + const upstream = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + const body = JSON.parse(Buffer.concat(chunks).toString("utf8")) as { input?: ResponseInputItem[] }; + if (Array.isArray(body.input)) inputs.push(body.input); + res.writeHead(200, { "content-type": "text/event-stream" }); + res.end(`event: response.completed\ndata: ${JSON.stringify({ type: "response.completed", response: { id: "resp_identity", output: [], usage: { input_tokens: 1000, output_tokens: 1 } } })}\n\n`); + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const origin = `http://127.0.0.1:${(upstream.address() as { port: number }).port}`; + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + _resetSessionsForTest(); + _resetPluginStateForTest(); + const config = defaultConfig(200_000); + const opts: ProxyOptions = { + port: 0, host: "127.0.0.1", upstream: origin, + routes: { [origin]: { models: { "gpt-identity": { context: 200_000 } } } }, + modelContextLimit: 200_000, kernelConfig: config, + compress: { injectTool: true, injectNudge: false }, promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", log: false, debug: false, passthrough: false, + autoUpdate: false, autoRestartOnUpdate: false, updateTag: "latest", streamErrorShape: "protocol", + passthroughSource: null, advisoryCheck: false, releaseNotesCheck: false, + compat: { roles: {} }, mitm: { enabled: false, domains: [] }, + }; + const proxy = await startServer(opts); + await once(proxy, "listening"); + const base = `http://127.0.0.1:${(proxy.address() as { port: number }).port}`; + const cid = "identity-plugin"; + const history: ResponseInputItem[] = Array.from({ length: 20 }, (_, i) => ({ type: "message", role: i % 2 === 0 ? "user" : "assistant", content: `identity seed ${i} ${"x".repeat(2000)}` })); + const post = async () => { + const r = await fetch(`${base}/bili/${origin}/v1/responses`, { + method: "POST", headers: { "content-type": "application/json", "x-bili-plugin": "pi", "x-bili-plugin-conversation": cid }, + body: JSON.stringify({ model: "gpt-identity", stream: true, instructions: "Stable identity fixture.", input: history }), + }); + assert.equal(r.status, 200, await r.text()); + return inputs.at(-1)!; + }; + const tool = async (body: Record) => { + const r = await fetch(`${base}/__bili/plugin/tool`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ conversationId: cid, nativeCaller: true, tool: "compress", ...body }) }); + return { status: r.status, data: await r.json() as { ok?: boolean; result?: string } }; + }; + return { inputs, history, post, tool, session: () => listSessions()[0]!, close: async () => { + await new Promise((resolve, reject) => proxy.close(e => e ? reject(e) : resolve())); + await new Promise((resolve, reject) => upstream.close(e => e ? reject(e) : resolve())); + } }; +} + +function appendPair(history: ResponseInputItem[], id: string, args: unknown, result: string) { + history.push({ type: "function_call", name: "compress", call_id: id, arguments: JSON.stringify(args) }); + history.push({ type: "function_call_output", call_id: id, output: result }); +} + +const args = { content: [{ startId: "m00002", endId: "m00007", topic: "identity", summary: "The earlier fixture messages establish the completed setup. Preserve the retained tail and use the original block when full detail is needed." }] }; + +test("native plugin compress stores the host call identity, not an unrelated synthetic identity", async () => { + const h = await harness(); + try { + await h.post(); + const out = await h.tool({ toolCallId: "call_host_success", args }); + assert.equal(out.status, 200); + assert.ok(h.session().state.blocks.some(b => b.active), out.data.result); + assert.equal(h.session().state.blocks.at(-1)?.compressCallId, "call_host_success"); + } finally { await h.close(); } +}); + +test("two later failures must not evict an active successful plugin carrier or move the cached prefix", async () => { + const h = await harness(); + try { + await h.post(); + const out = await h.tool({ toolCallId: "call_host_success", args }); + assert.ok(h.session().state.blocks.some(b => b.active), out.data.result); + appendPair(h.history, "call_host_success", args, out.data.result!); + const before = await h.post(); + for (let i = 0; i < 2; i++) appendPair(h.history, `call_failed_${i}`, { content: [] }, "[Compression FAILED: external summary unavailable.]"); + const afterInput = await h.post(); + assert.ok(afterInput.some(item => item.type === "function_call" && item.call_id === "call_host_success"), "still-active success must not be an orphan"); + assert.deepEqual(afterInput.slice(0, before.length), before, "ordinary failed calls must append, not resurrect an early summary anchor or delete the old carrier"); + assert.equal(h.session().state.blocks.filter(b => b.active).length, 1); + } finally { await h.close(); } +}); + +test("legacy synthetic blocks bind only to a unique resent carrier before orphan pruning", async () => { + const h = await harness(); + try { + await h.post(); + const out = await h.tool({ args }); + const block = h.session().state.blocks.at(-1)!; + assert.match(block.compressCallId!, /^plugin_/); + appendPair(h.history, "call_legacy_success", args, out.data.result!); + const before = await h.post(); + assert.equal(h.session().state.blocks.at(-1)?.compressCallId, "call_legacy_success"); + for (let i = 0; i < 2; i++) appendPair(h.history, `call_failed_${i}`, { content: [] }, "[Compression FAILED: external summary unavailable.]"); + const afterInput = await h.post(); + assert.deepEqual(afterInput.slice(0, before.length), before); + } finally { await h.close(); } +}); + +test("ambiguous historical calls must not be guessed as a legacy block's owner", async () => { + const h = await harness(); + try { + await h.post(); + const out = await h.tool({ args }); + const oldId = h.session().state.blocks.at(-1)!.compressCallId; + appendPair(h.history, "call_candidate_1", args, out.data.result!); + appendPair(h.history, "call_candidate_2", args, "[Compression FAILED: retry.]"); + await h.post(); + assert.equal(h.session().state.blocks.at(-1)?.compressCallId, oldId); + } finally { await h.close(); } +}); + +test("matching ranges with a failed or foreign block receipt cannot establish legacy ownership", async () => { + const h = await harness(); + try { + await h.post(); + await h.tool({ args }); + const oldId = h.session().state.blocks.at(-1)!.compressCallId; + appendPair(h.history, "call_foreign_receipt", args, "[Compressed m00002..m00007]\n · b999 full summary 100ch"); + await h.post(); + assert.equal(h.session().state.blocks.at(-1)?.compressCallId, oldId); + } finally { await h.close(); } +}); + +test("missing host call identity keeps legacy compatibility; malformed identity rejects before mutation", async () => { + const h = await harness(); + try { + await h.post(); + for (const toolCallId of [null, 23, "", " ", "x".repeat(513)]) { + const out = await h.tool({ toolCallId, args }); + assert.equal(out.status, 400, `invalid id ${String(toolCallId).slice(0, 15)}`); + assert.equal(h.session().state.blocks.length, 0); + } + const out = await h.tool({ args }); + assert.equal(out.status, 200); + assert.match(h.session().state.blocks.at(-1)?.compressCallId ?? "", /^plugin_/); + } finally { await h.close(); } +}); From ce447b97553956e6cedd1ed78f936f641b981687 Mon Sep 17 00:00:00 2001 From: WSXYT Date: Sat, 17 Oct 2026 23:32:02 +0800 Subject: [PATCH 2/3] fix: recover legacy carrier ownership across failed retries --- src/plugin.ts | 13 +++++++------ tests/plugin-call-identity.test.ts | 20 ++++++++++++++++++-- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/src/plugin.ts b/src/plugin.ts index ce4ffbf6bd..8125aeda28 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -162,12 +162,13 @@ export function reconcilePluginFoldCallIds(session: Session, messages: CoreMessa let changed = 0; for (const [key, sameRange] of blocks) { const block = sameRange[0]!; - const ids = calls.get(key); - if (sameRange.length !== 1 || !isPluginFoldCallId(block.compressCallId) || ids?.size !== 1) continue; - const id = ids.values().next().value!; - const receipt = results.get(id); - if (!receipt?.startsWith("[Compressed ") || !receipt.split("\n").some((line) => line.startsWith(` · ${block.blockId} full summary `))) continue; - block.compressCallId = id; + if (sameRange.length !== 1 || !isPluginFoldCallId(block.compressCallId)) continue; + const ids = [...calls.get(key) ?? []].filter((id) => { + const receipt = results.get(id); + return receipt?.startsWith("[Compressed ") && receipt.split("\n").some((line) => line.startsWith(` · ${block.blockId} full summary `)); + }); + if (ids.length !== 1) continue; + block.compressCallId = ids[0]!; changed++; } if (changed > 0) markDirty(session); diff --git a/tests/plugin-call-identity.test.ts b/tests/plugin-call-identity.test.ts index 7ea6970bf7..5cf8bb01c2 100644 --- a/tests/plugin-call-identity.test.ts +++ b/tests/plugin-call-identity.test.ts @@ -124,14 +124,30 @@ test("legacy synthetic blocks bind only to a unique resent carrier before orphan } finally { await h.close(); } }); -test("ambiguous historical calls must not be guessed as a legacy block's owner", async () => { +test("failed retries of the same range do not obscure the legacy carrier's exact successful receipt", async () => { + const h = await harness(); + try { + await h.post(); + const out = await h.tool({ args }); + appendPair(h.history, "call_failed_before", args, "[Compression FAILED: retry.]"); + appendPair(h.history, "call_legacy_success", args, out.data.result!); + const before = await h.post(); + assert.equal(h.session().state.blocks.at(-1)?.compressCallId, "call_legacy_success"); + appendPair(h.history, "call_foreign_success", args, "[Compressed m00002..m00007]\n · b999 full summary 100ch"); + appendPair(h.history, "call_failed_after", args, "[Compression FAILED: retry.]"); + const afterInput = await h.post(); + assert.deepEqual(afterInput.slice(0, before.length), before, "failed retries must not delete the uniquely evidenced successful carrier"); + } finally { await h.close(); } +}); + +test("ambiguous successful receipts must not be guessed as a legacy block's owner", async () => { const h = await harness(); try { await h.post(); const out = await h.tool({ args }); const oldId = h.session().state.blocks.at(-1)!.compressCallId; appendPair(h.history, "call_candidate_1", args, out.data.result!); - appendPair(h.history, "call_candidate_2", args, "[Compression FAILED: retry.]"); + appendPair(h.history, "call_candidate_2", args, out.data.result!); await h.post(); assert.equal(h.session().state.blocks.at(-1)?.compressCallId, oldId); } finally { await h.close(); } From 9254bad7c8f93ad2e56295c571dadd6418ba9d34 Mon Sep 17 00:00:00 2001 From: WSXYT Date: Sun, 18 Oct 2026 13:54:02 +0800 Subject: [PATCH 3/3] test: distinguish active carriers from expired failed retries --- tests/plugin-call-identity.test.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/tests/plugin-call-identity.test.ts b/tests/plugin-call-identity.test.ts index 5cf8bb01c2..49262975ad 100644 --- a/tests/plugin-call-identity.test.ts +++ b/tests/plugin-call-identity.test.ts @@ -130,13 +130,18 @@ test("failed retries of the same range do not obscure the legacy carrier's exact await h.post(); const out = await h.tool({ args }); appendPair(h.history, "call_failed_before", args, "[Compression FAILED: retry.]"); + appendPair(h.history, "call_foreign_success", args, "[Compressed m00002..m00007]\n · b999 full summary 100ch"); appendPair(h.history, "call_legacy_success", args, out.data.result!); const before = await h.post(); assert.equal(h.session().state.blocks.at(-1)?.compressCallId, "call_legacy_success"); - appendPair(h.history, "call_foreign_success", args, "[Compressed m00002..m00007]\n · b999 full summary 100ch"); - appendPair(h.history, "call_failed_after", args, "[Compression FAILED: retry.]"); + for (let i = 0; i < 2; i++) appendPair(h.history, `call_failed_after_${i}`, args, "[Compression FAILED: retry.]"); const afterInput = await h.post(); - assert.deepEqual(afterInput.slice(0, before.length), before, "failed retries must not delete the uniquely evidenced successful carrier"); + const successfulPair = (input: ResponseInputItem[]) => input.filter(item => (item.type === "function_call" || item.type === "function_call_output") && item.call_id === "call_legacy_success"); + assert.equal(successfulPair(before).length, 2); + assert.deepEqual(successfulPair(afterInput), successfulPair(before), "the active carrier must survive even when older failed orphan pairs legitimately expire"); + const firstPair = before.findIndex(item => item.type === "function_call"); + assert.deepEqual(afterInput.slice(0, firstPair), before.slice(0, firstPair), "migration must not resurrect the early summary anchor"); + assert.equal(h.session().state.blocks.filter(block => block.active).length, 1); } finally { await h.close(); } });