From cd0812dd9325def20464874edb10182f3c9e16e2 Mon Sep 17 00:00:00 2001 From: ci-check Date: Thu, 19 Nov 2026 05:38:55 +0800 Subject: [PATCH 1/3] fix(server): integrity-aware anchor stripping for plugin folds (#5866) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After the first post-fold turn, hideConsumedCompressCalls stubs the re-sent compress call's summary to a 200-char prefix, but stripKernelSummaries only checked range-pair EXISTENCE (not whether the call still carries the full text), so it stripped the in-place anchor too — leaving zero full summary carriers on the wire. Option A (host-side, no kernel change): strip the anchor only when some matching re-sent call's summary is verbatim-equal to the anchor's body. A stubbed (or drifted) call keeps the anchor as the sole full carrier. buildCarrierIndex now tracks per-range summary texts in a single parse pass (ensureRangeSummaries); stripKernelSummaries compares the call's summary against extractAnchorBody(anchor.text) before stripping. Regression tests: tests/issue5866-anchor-integrity.test.ts pins the fresh-call (stripped) and stubbed-call (kept) directions, content-array form, empty-summary, trim normalization, mixed fresh+stub, absent-anchor, and proxy-mode (summary match does not apply) cases. Existing carrier-index tests updated to carry a matching summary field. Closes #5866 --- src/server.ts | 110 +++++++++++++++-------- tests/issue2042-carrier-index.test.ts | 8 +- tests/issue5866-anchor-integrity.test.ts | 99 ++++++++++++++++++++ 3 files changed, 178 insertions(+), 39 deletions(-) create mode 100644 tests/issue5866-anchor-integrity.test.ts diff --git a/src/server.ts b/src/server.ts index 3fb954b5ff..03ff3792eb 100644 --- a/src/server.ts +++ b/src/server.ts @@ -2764,42 +2764,65 @@ export function warnResponsesReasoningPairs( * block with recorded refs needs exact matching) and each call's args are * parsed at most ONCE, whereas the old per-block scan reparsed them for * every block. */ -function buildCarrierIndex(messages: BiliMessage[]): { callIds: Set; compressCalls: BiliMessage[]; ensureRangePairs: () => Map> } { - const callIds = new Set(); - const compressCalls: BiliMessage[] = []; - for (const m of messages) { - if (m.contentType !== "tool-call") continue; - if (m.toolCallId) callIds.add(m.toolCallId); - if (m.toolName === COMPRESS_TOOL_NAME) compressCalls.push(m); - } - let rangePairs: Map> | null = null; - const ensureRangePairs = (): Map> => { - if (!rangePairs) { - rangePairs = new Map>(); - for (const c of compressCalls) { - let parsed: unknown; - try { - parsed = JSON.parse(c.text ?? ""); - } catch { - continue; - } - const obj = parsed as { startId?: string; endId?: string; content?: unknown }; - const ranges: Array<{ startId?: string; endId?: string }> = Array.isArray(obj?.content) ? (obj.content as Array<{ startId?: string; endId?: string }>) : [obj]; - for (const r of ranges) { - if (typeof r?.startId !== "string" || !r.startId || typeof r?.endId !== "string" || !r.endId) continue; - let ends = rangePairs.get(r.startId); - if (!ends) { ends = new Set(); rangePairs.set(r.startId, ends); } - ends.add(r.endId); - } - } - } - return rangePairs; - }; - return { callIds, compressCalls, ensureRangePairs }; + function buildCarrierIndex(messages: BiliMessage[]): { callIds: Set; compressCalls: BiliMessage[]; ensureRangePairs: () => Map>; ensureRangeSummaries: () => Map>> } { + const callIds = new Set(); + const compressCalls: BiliMessage[] = []; + for (const m of messages) { + if (m.contentType !== "tool-call") continue; + if (m.toolCallId) callIds.add(m.toolCallId); + if (m.toolName === COMPRESS_TOOL_NAME) compressCalls.push(m); + } + let rangePairs: Map> | null = null; + let rangeSummaries: Map>> | null = null; + const ensureRangeData = (): void => { + if (rangePairs && rangeSummaries) return; + rangePairs = new Map>(); + rangeSummaries = new Map>>(); + for (const c of compressCalls) { + let parsed: unknown; + try { + parsed = JSON.parse(c.text ?? ""); + } catch { + continue; + } + const obj = parsed as { startId?: string; endId?: string; summary?: unknown; content?: unknown }; + const ranges: Array<{ startId?: string; endId?: string; summary?: unknown }> = Array.isArray(obj?.content) ? (obj.content as Array<{ startId?: string; endId?: string; summary?: unknown }>) : [obj]; + for (const r of ranges) { + if (typeof r?.startId !== "string" || !r.startId || typeof r?.endId !== "string" || !r.endId) continue; + let ends = rangePairs.get(r.startId); + if (!ends) { ends = new Set(); rangePairs.set(r.startId, ends); } + ends.add(r.endId); + const summary = typeof r.summary === "string" ? r.summary : ""; + let sumEnds = rangeSummaries.get(r.startId); + if (!sumEnds) { sumEnds = new Map>(); rangeSummaries.set(r.startId, sumEnds); } + let summaries = sumEnds.get(r.endId); + if (!summaries) { summaries = new Set(); sumEnds.set(r.endId, summaries); } + summaries.add(summary); + } + } + }; + const ensureRangePairs = (): Map> => { + ensureRangeData(); + return rangePairs!; + }; + const ensureRangeSummaries = (): Map>> => { + ensureRangeData(); + return rangeSummaries!; + }; + return { callIds, compressCalls, ensureRangePairs, ensureRangeSummaries }; + } + +// #5866: extract the body (everything after the first topic line) of a kernel +// summary anchor. The kernel renders anchors as `\n` (or just +// the topic line when the body is empty); a simplified anchor with no newline +// yields its whole text as the body. +function extractAnchorBody(text: string): string { + const idx = text.indexOf("\n"); + return idx === -1 ? text : text.slice(idx + 1); } export function stripKernelSummaries(messages: BiliMessage[], state: CompressionState): BiliMessage[] { - const { callIds, compressCalls, ensureRangePairs } = buildCarrierIndex(messages); + const { callIds, compressCalls, ensureRangePairs, ensureRangeSummaries } = buildCarrierIndex(messages); const carried = new Set(); for (const b of state.blocks) { if (!b.active || !b.compressCallId) continue; @@ -2815,9 +2838,26 @@ export function stripKernelSummaries(messages: BiliMessage[], state: Compression const present = isPluginFoldCallId(b.compressCallId) ? (!b.startRef || !b.endRef ? compressCalls.length > 0 : ensureRangePairs().get(b.startRef)?.has(b.endRef) ?? false) : callIds.has(b.compressCallId); - if (present) { - carried.add(`acp_summary_${b.blockId}`); + if (!present) continue; + // #5866 option A: integrity-aware anchor stripping for plugin folds. + // The re-sent compress call is only a full carrier while it still + // carries the FULL summary verbatim. After the first post-fold turn, + // hideConsumedCompressCalls stubs the call's summary to a 200-char + // prefix, so the call no longer carries the full text — the in-place + // anchor must then be the sole full carrier and MUST be kept. Strip + // only when some matching call's summary is verbatim-equal to the + // anchor's body; otherwise keep the anchor. + if (isPluginFoldCallId(b.compressCallId) && b.startRef && b.endRef) { + const anchorId = `acp_summary_${b.blockId}`; + const anchor = messages.find((m) => m.id === anchorId); + if (anchor) { + const anchorBody = extractAnchorBody(anchor.text ?? ""); + const callSummaries = ensureRangeSummaries().get(b.startRef)?.get(b.endRef); + const fullCarrier = callSummaries ? Array.from(callSummaries).some((s) => s.trim() === anchorBody) : false; + if (!fullCarrier) continue; + } } + carried.add(`acp_summary_${b.blockId}`); } return messages.filter((m) => !(m.id ?? "").startsWith("acp_summary_") || !carried.has(m.id)); } diff --git a/tests/issue2042-carrier-index.test.ts b/tests/issue2042-carrier-index.test.ts index 2ee1ea8175..5216405ff6 100644 --- a/tests/issue2042-carrier-index.test.ts +++ b/tests/issue2042-carrier-index.test.ts @@ -51,13 +51,13 @@ test("non-tool-call message carrying the same toolCallId does not count", () => }); test("plugin block: exact range match via flat args -> stripped", () => { - const messages = [summary("pb0"), toolCall("c1", "compress", '{"startId":"m1","endId":"m9"}'), tail(0)]; + const messages = [summary("pb0"), toolCall("c1", "compress", '{"startId":"m1","endId":"m9","summary":"summary"}'), tail(0)]; const out = stripKernelSummaries(messages, stateWith([{ blockId: "pb0", active: true, compressCallId: "plugin_1", startRef: "m1", endRef: "m9" }])); assert.deepEqual(ids(out), ["tc_c1", "u0"]); }); test("plugin block: exact range match via content array -> stripped", () => { - const messages = [summary("pb0"), toolCall("c1", "compress", '{"content":[{"startId":"m1","endId":"m9"}]}'), tail(0)]; + const messages = [summary("pb0"), toolCall("c1", "compress", '{"content":[{"startId":"m1","endId":"m9","summary":"summary"}]}'), tail(0)]; const out = stripKernelSummaries(messages, stateWith([{ blockId: "pb0", active: true, compressCallId: "plugin_1", startRef: "m1", endRef: "m9" }])); assert.deepEqual(ids(out), ["tc_c1", "u0"]); }); @@ -107,7 +107,7 @@ test("mixed branches: only blocks with carriers are stripped, order preserved", const messages = [ summary("p_hit"), summary("p_miss"), summary("pl_hit"), summary("pl_bad"), toolCall("proxy_call_p_hit", "bash"), - toolCall("c1", "compress", '{"content":[{"startId":"m1","endId":"m2"},{"startId":"m3","endId":"m4"}]}'), + toolCall("c1", "compress", '{"content":[{"startId":"m1","endId":"m2"},{"startId":"m3","endId":"m4","summary":"summary"}]}'), toolCall("c2", "compress", "{bad json"), tail(0), ]; @@ -124,7 +124,7 @@ test("mixed branches: only blocks with carriers are stripped, order preserved", test("one content array serving two plugin blocks parses the args exactly once", () => { const messages = [ summary("a0"), summary("a1"), - toolCall("c1", "compress", '{"content":[{"startId":"m1","endId":"m2"},{"startId":"m3","endId":"m4"}]}'), + toolCall("c1", "compress", '{"content":[{"startId":"m1","endId":"m2","summary":"summary"},{"startId":"m3","endId":"m4","summary":"summary"}]}'), tail(0), ]; const state = stateWith([ diff --git a/tests/issue5866-anchor-integrity.test.ts b/tests/issue5866-anchor-integrity.test.ts new file mode 100644 index 0000000000..bc51c70a2c --- /dev/null +++ b/tests/issue5866-anchor-integrity.test.ts @@ -0,0 +1,99 @@ +// #5866 regression: plugin-lane array-form folds end with ZERO full summaries +// on the wire after the first turn. The kernel's hideConsumedCompressCalls +// stubs the re-sent compress call's summary to a 200-char prefix, but the +// host's stripKernelSummaries only checked range-pair EXISTENCE (not whether +// the call still carries the full text), so it stripped the in-place anchor +// too — leaving zero full carriers. +// +// Option A (integrity-aware anchor stripping): strip the anchor only when some +// matching re-sent call's summary is verbatim-equal to the anchor's body. A +// stubbed (or drifted) call keeps the anchor as the sole full carrier. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createInitialState, type CompressionBlock, type CompressionState } from "acp-kernel"; +import type { BiliMessage } from "acp-kernel/wire"; +import { stripKernelSummaries } from "../src/server.ts"; + +function msg(partial: Partial & { id: string }): BiliMessage { + return { role: "user", contentType: "text", text: "x", ...partial } as BiliMessage; +} + +// A realistic anchor: topic line + body (the kernel's renderSummary format). +const anchor = (blockId: string, body: string): BiliMessage => + msg({ id: `acp_summary_${blockId}`, role: "system", text: `[Compressed conversation section]\n${body}` }); +const tail = (n: string | number): BiliMessage => msg({ id: `u${n}`, text: "tail" }); +const toolCall = (toolCallId: string, toolName: string, args?: string): BiliMessage => + msg({ id: `tc_${toolCallId}`, role: "assistant", contentType: "tool-call", toolCallId, toolName, ...(args !== undefined ? { text: args } : {}) }); + +function stateWith(blocks: Array>): CompressionState { + const s = createInitialState(); + s.blocks = blocks.map((b, i) => ({ blockId: `b${i}`, ...b }) as CompressionBlock); + return s; +} +const ids = (msgs: BiliMessage[]): string[] => msgs.map((m) => m.id); + +// The full summary body that the kernel rendered into the anchor. +const FULL_BODY = "This is the full summary of the compressed conversation section. It is longer than two hundred characters so that the stub prefix (first 200 chars) is strictly shorter than the body and therefore NOT verbatim-equal to it, which is exactly the condition that must keep the anchor as the sole full carrier."; +const STUB_BODY = FULL_BODY.slice(0, 199) + "\u2026"; // hideConsumedCompressCalls stub: 199-char prefix + ellipsis. + +test("fresh call: summary verbatim-equals anchor body -> anchor stripped", () => { + const messages = [anchor("pb0", FULL_BODY), toolCall("c1", "compress", JSON.stringify({ startId: "m1", endId: "m9", summary: FULL_BODY })), tail(0)]; + const out = stripKernelSummaries(messages, stateWith([{ blockId: "pb0", active: true, compressCallId: "plugin_1", startRef: "m1", endRef: "m9" }])); + assert.deepEqual(ids(out), ["tc_c1", "u0"]); +}); + +test("stubbed call: summary is 200-char prefix, NOT equal to anchor body -> anchor KEPT (the #5866 fix)", () => { + const messages = [anchor("pb0", FULL_BODY), toolCall("c1", "compress", JSON.stringify({ startId: "m1", endId: "m9", summary: STUB_BODY })), tail(0)]; + const out = stripKernelSummaries(messages, stateWith([{ blockId: "pb0", active: true, compressCallId: "plugin_1", startRef: "m1", endRef: "m9" }])); + // The anchor must survive: the stubbed call is not a full carrier. + assert.deepEqual(ids(out), ["acp_summary_pb0", "tc_c1", "u0"]); +}); + +test("stubbed call via content array: anchor KEPT", () => { + const messages = [anchor("pb0", FULL_BODY), toolCall("c1", "compress", JSON.stringify({ content: [{ startId: "m1", endId: "m9", summary: STUB_BODY }] })), tail(0)]; + const out = stripKernelSummaries(messages, stateWith([{ blockId: "pb0", active: true, compressCallId: "plugin_1", startRef: "m1", endRef: "m9" }])); + assert.deepEqual(ids(out), ["acp_summary_pb0", "tc_c1", "u0"]); +}); + +test("call with empty summary field: anchor KEPT", () => { + const messages = [anchor("pb0", FULL_BODY), toolCall("c1", "compress", JSON.stringify({ startId: "m1", endId: "m9" })), tail(0)]; + const out = stripKernelSummaries(messages, stateWith([{ blockId: "pb0", active: true, compressCallId: "plugin_1", startRef: "m1", endRef: "m9" }])); + assert.deepEqual(ids(out), ["acp_summary_pb0", "tc_c1", "u0"]); +}); + +test("call summary whitespace-padded but otherwise equal: anchor stripped (trim normalization)", () => { + const messages = [anchor("pb0", FULL_BODY), toolCall("c1", "compress", JSON.stringify({ startId: "m1", endId: "m9", summary: ` ${FULL_BODY} ` })), tail(0)]; + const out = stripKernelSummaries(messages, stateWith([{ blockId: "pb0", active: true, compressCallId: "plugin_1", startRef: "m1", endRef: "m9" }])); + assert.deepEqual(ids(out), ["tc_c1", "u0"]); +}); + +test("two blocks, one fresh + one stubbed: only the fresh anchor is stripped", () => { + const messages = [ + anchor("fresh", FULL_BODY), + anchor("stub", FULL_BODY), + toolCall("c1", "compress", JSON.stringify({ content: [{ startId: "m1", endId: "m2", summary: FULL_BODY }, { startId: "m3", endId: "m4", summary: STUB_BODY }] })), + tail(0), + ]; + const state = stateWith([ + { blockId: "fresh", active: true, compressCallId: "plugin_1", startRef: "m1", endRef: "m2" }, + { blockId: "stub", active: true, compressCallId: "plugin_2", startRef: "m3", endRef: "m4" }, + ]); + const out = stripKernelSummaries(messages, state); + // The fresh block's anchor is stripped (full carrier); the stubbed block's + // anchor is kept (no full carrier). + assert.deepEqual(ids(out), ["acp_summary_stub", "tc_c1", "u0"]); +}); + +test("anchor absent from messages (already stripped upstream): no crash, call still rides", () => { + const messages = [toolCall("c1", "compress", JSON.stringify({ startId: "m1", endId: "m9", summary: STUB_BODY })), tail(0)]; + const out = stripKernelSummaries(messages, stateWith([{ blockId: "pb0", active: true, compressCallId: "plugin_1", startRef: "m1", endRef: "m9" }])); + assert.deepEqual(ids(out), ["tc_c1", "u0"]); +}); + +test("proxy-mode block (non-plugin callId): summary match does NOT apply, id match governs", () => { + // Proxy-mode blocks use the plain toolCallId match; the integrity check is + // plugin-only. A proxy call with no summary field still strips its anchor. + const messages = [anchor("b0", FULL_BODY), toolCall("proxy_call_b0", "compress", JSON.stringify({ startId: "m1", endId: "m9" })), tail(0)]; + const out = stripKernelSummaries(messages, stateWith([{ blockId: "b0", active: true, compressCallId: "proxy_call_b0" }])); + assert.deepEqual(ids(out), ["tc_proxy_call_b0", "u0"]); +}); From 7c74ecaa56194677e223d6e6644624a860fd7fc1 Mon Sep 17 00:00:00 2001 From: Afloat Date: Thu, 19 Nov 2026 02:47:09 +0800 Subject: [PATCH 2/3] fix: validate Claude watchdog health payloads (cherry picked from commit 7e69d5b0c589d20396bd8ee5e6f8331dd387efab) --- src/claude-mcp-entry.ts | 4 +- tests/claude-watchdog-health-payload.test.ts | 173 +++++++++++++++++++ 2 files changed, 176 insertions(+), 1 deletion(-) create mode 100644 tests/claude-watchdog-health-payload.test.ts diff --git a/src/claude-mcp-entry.ts b/src/claude-mcp-entry.ts index 7472e02e84..b97fbdb103 100644 --- a/src/claude-mcp-entry.ts +++ b/src/claude-mcp-entry.ts @@ -106,7 +106,9 @@ export function _setClaudeHostPidForTest(pid: number | undefined): void { async function probeProxyHealth(origin: string): Promise { try { const res = await fetch(healthUrl(origin), { signal: AbortSignal.timeout(2000) }); - return res.ok; + if (!res.ok) return false; + const payload = await res.json() as { ok?: unknown } | null; + return payload?.ok === true; } catch { return false; } diff --git a/tests/claude-watchdog-health-payload.test.ts b/tests/claude-watchdog-health-payload.test.ts new file mode 100644 index 0000000000..f2843e6235 --- /dev/null +++ b/tests/claude-watchdog-health-payload.test.ts @@ -0,0 +1,173 @@ +import assert from "node:assert/strict"; +import { once } from "node:events"; +import fs from "node:fs"; +import http from "node:http"; +import os from "node:os"; +import path from "node:path"; +import { test, type TestContext } from "node:test"; +import { watchdogTick, type MutableWatchdogState, type WatchdogDeps } from "../src/claude-mcp-entry.ts"; +import { forwardTool } from "../src/mcp.ts"; +import { readClaudeManagedBaseUrl, repinClaudeManagedBaseUrl } from "../src/plugin-install.ts"; +import { rmrf } from "./tmp-rm.ts"; + +type HealthReply = { status: number; body: string; contentType?: string; stall?: "headers" | "body" }; +type Request = { listener: "old" | "replacement"; url: string; body?: Record }; + +async function fixture(t: TestContext, initialReply: HealthReply) { + let reply = initialReply; + const requests: Request[] = []; + const servers: http.Server[] = []; + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-claude-health-payload-")); + const env = { CLAUDE_CONFIG_DIR: dir }; + const previousPin = process.env.BILI_MCP_PROXY; + t.after(async () => { + if (previousPin === undefined) delete process.env.BILI_MCP_PROXY; + else process.env.BILI_MCP_PROXY = previousPin; + for (const server of servers) { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + } + rmrf(dir); + }); + + const listen = async (listener: "old" | "replacement"): Promise => { + const server = http.createServer(async (req, res) => { + let raw = ""; + for await (const chunk of req) raw += chunk; + const body = raw ? JSON.parse(raw) as Record : undefined; + requests.push({ listener, url: req.url ?? "", body }); + if (req.url === "/__bili/health" && listener === "old") { + if (reply.stall === "headers") return; + res.writeHead(reply.status, { "content-type": reply.contentType ?? "application/json" }); + if (reply.stall === "body") { + res.write(reply.body); + return; + } + res.end(reply.body); + return; + } + res.setHeader("content-type", "application/json"); + res.end(JSON.stringify(req.url === "/__bili/plugin/tool" + ? { ok: true, result: `ACP receipt from ${listener}`, outcome: "success" } + : { ok: true, version: "0.1.216" })); + }); + servers.push(server); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const address = server.address(); + assert.ok(address && typeof address === "object"); + return `http://127.0.0.1:${address.port}`; + }; + + const origin = await listen("old"); + const replacement = await listen("replacement"); + const settingsPath = path.join(dir, "settings.json"); + fs.writeFileSync(settingsPath, JSON.stringify({ + env: { ANTHROPIC_BASE_URL: `${origin}/bili/https://api.anthropic.com`, KEEP_SETTING: "unchanged" }, + permissions: { allow: ["Read"] }, + })); + process.env.BILI_MCP_PROXY = origin; + const state: MutableWatchdogState = { origin, failures: 0 }; + let ensureCalls = 0; + const deps: WatchdogDeps = { + ensure: async (opts) => { + ensureCalls += 1; + assert.equal(opts.port, 0); + assert.equal(opts.strictPort, false); + assert.equal(opts.lane, "claude"); + return { origin: replacement, port: Number(new URL(replacement).port), attached: true }; + }, + repin: (next) => repinClaudeManagedBaseUrl(next, env), + }; + const tick = () => watchdogTick(state, { port: 0, strict: false }, deps, () => {}); + const assertRouting = async (listener: "old" | "replacement") => { + const expected = listener === "replacement" ? replacement : origin; + assert.equal(state.origin, expected); + assert.equal(process.env.BILI_MCP_PROXY, expected); + assert.equal(readClaudeManagedBaseUrl(env), expected); + const settings = JSON.parse(fs.readFileSync(settingsPath, "utf8")); + assert.equal(settings.env.KEEP_SETTING, "unchanged"); + assert.deepEqual(settings.permissions, { allow: ["Read"] }); + const receipt = await forwardTool("acp_status", { detail: "preserved" }, 2_000, "health-payload-session"); + assert.equal(receipt.text, `ACP receipt from ${listener}`); + const posts = requests.filter((request) => request.url === "/__bili/plugin/tool"); + assert.equal(posts.length, 1); + assert.equal(posts[0].listener, listener); + assert.equal(posts[0].body?.conversationId, "health-payload-session"); + assert.deepEqual(posts[0].body?.args, { detail: "preserved" }); + }; + return { state, tick, assertRouting, ensureCalls: () => ensureCalls, setReply: (next: HealthReply) => { reply = next; } }; +} + +for (const [name, reply] of [ + ["HTML with status 200", { status: 200, body: "Development app", contentType: "text/html" }], + ["an explicit not-ok reply", { status: 200, body: '{"ok":false}' }], + ["a string ok flag", { status: 200, body: '{"ok":"true"}' }], + ["a numeric ok flag", { status: 200, body: '{"ok":1}' }], + ["a missing ok flag", { status: 200, body: '{"version":"other-service"}' }], + ["JSON null", { status: 200, body: "null" }], + ["a JSON primitive", { status: 200, body: "true" }], + ["malformed JSON", { status: 200, body: '{"ok":true' }], + ["an empty 204 reply", { status: 204, body: "" }], +] satisfies Array<[string, HealthReply]>) { + test(`Claude watchdog recovers after three health replies containing ${name}`, async (t) => { + const f = await fixture(t, reply); + await f.tick(); + assert.equal(f.state.failures, 1); + await f.tick(); + assert.equal(f.state.failures, 2); + assert.equal(f.ensureCalls(), 0); + await f.tick(); + assert.equal(f.ensureCalls(), 1); + assert.equal(f.state.failures, 0); + await f.assertRouting("replacement"); + await f.tick(); + assert.equal(f.ensureCalls(), 1, "the replacement's valid health response prevents another recovery"); + }); +} + +for (const contentType of ["application/json", "text/plain"]) { + test(`Claude watchdog accepts a valid health object served as ${contentType}`, async (t) => { + const f = await fixture(t, { status: 200, body: '{"ok":true,"version":"0.1.216"}', contentType }); + f.state.failures = 2; + await f.tick(); + assert.equal(f.state.failures, 0); + assert.equal(f.ensureCalls(), 0); + await f.assertRouting("old"); + }); +} + +test("Claude watchdog still rejects an HTTP error even with an ok payload", async (t) => { + const f = await fixture(t, { status: 503, body: '{"ok":true}' }); + for (let i = 0; i < 3; i++) await f.tick(); + assert.equal(f.ensureCalls(), 1); + await f.assertRouting("replacement"); +}); + +test("Claude watchdog requires consecutive invalid payloads after a healthy reset", async (t) => { + const f = await fixture(t, { status: 200, body: '{"ok":false}' }); + await f.tick(); + await f.tick(); + assert.equal(f.state.failures, 2); + f.setReply({ status: 200, body: '{"ok":true}' }); + await f.tick(); + assert.equal(f.state.failures, 0); + f.setReply({ status: 200, body: '{"ok":false}' }); + await f.tick(); + await f.tick(); + assert.equal(f.ensureCalls(), 0); + await f.tick(); + assert.equal(f.ensureCalls(), 1); + await f.assertRouting("replacement"); +}); + +for (const stall of ["headers", "body"] as const) { + test(`Claude watchdog bounds a stalled health ${stall} with its existing timeout`, { timeout: 10_000 }, async (t) => { + const f = await fixture(t, { status: 200, body: '{"ok":', stall }); + f.state.failures = 2; + await f.tick(); + assert.equal(f.ensureCalls(), 1, "an incomplete health reply cannot reset the failure counter"); + assert.equal(f.state.failures, 0); + await f.assertRouting("replacement"); + }); +} From db7c6157425e142f17133cc416a1409f0c07d715 Mon Sep 17 00:00:00 2001 From: ci-check Date: Thu, 19 Nov 2026 06:18:39 +0800 Subject: [PATCH 3/3] refactor: align buildCarrierIndex indentation to the repo 4-space standard Drive-by style fix found in review of #7231: the rewritten function carried a leading space on its declaration line and a 5-space body, off by one from the surrounding code. Whitespace only, no behavior change. --- src/server.ts | 94 +++++++++++++++++++++++++-------------------------- 1 file changed, 47 insertions(+), 47 deletions(-) diff --git a/src/server.ts b/src/server.ts index 03ff3792eb..39edc2c246 100644 --- a/src/server.ts +++ b/src/server.ts @@ -2764,53 +2764,53 @@ export function warnResponsesReasoningPairs( * block with recorded refs needs exact matching) and each call's args are * parsed at most ONCE, whereas the old per-block scan reparsed them for * every block. */ - function buildCarrierIndex(messages: BiliMessage[]): { callIds: Set; compressCalls: BiliMessage[]; ensureRangePairs: () => Map>; ensureRangeSummaries: () => Map>> } { - const callIds = new Set(); - const compressCalls: BiliMessage[] = []; - for (const m of messages) { - if (m.contentType !== "tool-call") continue; - if (m.toolCallId) callIds.add(m.toolCallId); - if (m.toolName === COMPRESS_TOOL_NAME) compressCalls.push(m); - } - let rangePairs: Map> | null = null; - let rangeSummaries: Map>> | null = null; - const ensureRangeData = (): void => { - if (rangePairs && rangeSummaries) return; - rangePairs = new Map>(); - rangeSummaries = new Map>>(); - for (const c of compressCalls) { - let parsed: unknown; - try { - parsed = JSON.parse(c.text ?? ""); - } catch { - continue; - } - const obj = parsed as { startId?: string; endId?: string; summary?: unknown; content?: unknown }; - const ranges: Array<{ startId?: string; endId?: string; summary?: unknown }> = Array.isArray(obj?.content) ? (obj.content as Array<{ startId?: string; endId?: string; summary?: unknown }>) : [obj]; - for (const r of ranges) { - if (typeof r?.startId !== "string" || !r.startId || typeof r?.endId !== "string" || !r.endId) continue; - let ends = rangePairs.get(r.startId); - if (!ends) { ends = new Set(); rangePairs.set(r.startId, ends); } - ends.add(r.endId); - const summary = typeof r.summary === "string" ? r.summary : ""; - let sumEnds = rangeSummaries.get(r.startId); - if (!sumEnds) { sumEnds = new Map>(); rangeSummaries.set(r.startId, sumEnds); } - let summaries = sumEnds.get(r.endId); - if (!summaries) { summaries = new Set(); sumEnds.set(r.endId, summaries); } - summaries.add(summary); - } - } - }; - const ensureRangePairs = (): Map> => { - ensureRangeData(); - return rangePairs!; - }; - const ensureRangeSummaries = (): Map>> => { - ensureRangeData(); - return rangeSummaries!; - }; - return { callIds, compressCalls, ensureRangePairs, ensureRangeSummaries }; - } +function buildCarrierIndex(messages: BiliMessage[]): { callIds: Set; compressCalls: BiliMessage[]; ensureRangePairs: () => Map>; ensureRangeSummaries: () => Map>> } { + const callIds = new Set(); + const compressCalls: BiliMessage[] = []; + for (const m of messages) { + if (m.contentType !== "tool-call") continue; + if (m.toolCallId) callIds.add(m.toolCallId); + if (m.toolName === COMPRESS_TOOL_NAME) compressCalls.push(m); + } + let rangePairs: Map> | null = null; + let rangeSummaries: Map>> | null = null; + const ensureRangeData = (): void => { + if (rangePairs && rangeSummaries) return; + rangePairs = new Map>(); + rangeSummaries = new Map>>(); + for (const c of compressCalls) { + let parsed: unknown; + try { + parsed = JSON.parse(c.text ?? ""); + } catch { + continue; + } + const obj = parsed as { startId?: string; endId?: string; summary?: unknown; content?: unknown }; + const ranges: Array<{ startId?: string; endId?: string; summary?: unknown }> = Array.isArray(obj?.content) ? (obj.content as Array<{ startId?: string; endId?: string; summary?: unknown }>) : [obj]; + for (const r of ranges) { + if (typeof r?.startId !== "string" || !r.startId || typeof r?.endId !== "string" || !r.endId) continue; + let ends = rangePairs.get(r.startId); + if (!ends) { ends = new Set(); rangePairs.set(r.startId, ends); } + ends.add(r.endId); + const summary = typeof r.summary === "string" ? r.summary : ""; + let sumEnds = rangeSummaries.get(r.startId); + if (!sumEnds) { sumEnds = new Map>(); rangeSummaries.set(r.startId, sumEnds); } + let summaries = sumEnds.get(r.endId); + if (!summaries) { summaries = new Set(); sumEnds.set(r.endId, summaries); } + summaries.add(summary); + } + } + }; + const ensureRangePairs = (): Map> => { + ensureRangeData(); + return rangePairs!; + }; + const ensureRangeSummaries = (): Map>> => { + ensureRangeData(); + return rangeSummaries!; + }; + return { callIds, compressCalls, ensureRangePairs, ensureRangeSummaries }; +} // #5866: extract the body (everything after the first topic line) of a kernel // summary anchor. The kernel renders anchors as `\n` (or just