diff --git a/PLUGIN.md b/PLUGIN.md index 4309f16d27..b89f05caa4 100644 --- a/PLUGIN.md +++ b/PLUGIN.md @@ -121,6 +121,7 @@ Context-level visibility for plugin UIs (status bars / slash commands): "outputTokens": 40021, "cachedTokens": 180000, "requests": 42, + "lastCompressAt": 1755300000123, "blocks": [{ "id": "b3", "tier": 1, "active": true }], "lastSeen": 1755300000000 } @@ -132,6 +133,8 @@ Forwarding a new model request replaces the previous observation with an estimat `contextTokensAt` is the observation time in Unix milliseconds (not the status read time), independently of the last usage timestamp. `contextGeneration` is an opaque change detector covering a unique observation id, context, revision, model and limit: successive observations remain distinct even at the same timestamp with identical token counts; repeated status reads do not create observations. Unavailable context has null tokens, timestamp and generation. Legacy persisted sessions without an independently attributed observation are unavailable until another request establishes one. `sessionId` and nullable `sessionRevision` identify the resolved session and its fork state. Pre-first-request/chain-only responses explicitly report unavailable context. Persisted sessions are loaded by the requested id before considering an explicitly requested `fallback=latest`. Errors: `400` missing `conversationId`, `404` unknown conversation. +`lastCompressAt` is the Unix-millisecond time of the last landed fold — a successful model-driven `compress` or a preflight overflow compress, both stamped when the fold lands — or `null` until the first fold in this process. The pi/omp plugin's compaction-takeover watchdog (#2110) reads it to release native auto-compaction after a bounded streak of cancelled passes without a NEWER fold; field ABSENCE (an older proxy that never had it) means `null` (new proxy, no folds yet) and selects the legacy unconditional-cancel behavior instead. + `compressibleRanges` is the live kernel recommendation as structured `{startRef, endRef, count, ...}` entries for `sessionRevision`, or `null` if it cannot be computed. An empty list means there is no recommended range. Read the exact conversation without `fallback=latest`, match the snapshot revision and ordered refs, and submit manual `compress` with `expectedRevision`; never parse the human panel or guess a fixed prefix. Hosts must exclude their retained first-user anchor from summaries: kernel pruning retains it even if a recommendation spans it. A concurrent mutation is rejected by the revision guard. ### 5. `POST /__bili/plugin/compact` diff --git a/src/agent/pi.ts b/src/agent/pi.ts index e57dad6a33..ec15bde7e9 100644 --- a/src/agent/pi.ts +++ b/src/agent/pi.ts @@ -326,6 +326,17 @@ function noProxyWarning(agent: string): string { const RETRY_INTERVAL_MS = 10000; +// #2110: takeover watchdog defaults — how many consecutive cancelled +// auto-compaction passes without a newer proxy fold (streak) or how much wall +// time (timeout) may elapse before bili releases compaction ownership back to +// the host's native pass. Hardcoded on purpose (config-surface discipline): +// the remedy for a broken proxy is fixing/updating it, not tuning plugin +// constants. The test seam is the factory opts below, not an env var. +const TAKEOVER_MAX_STALE_CANCELS = 8; +const TAKEOVER_TIMEOUT_MS = 600_000; + +type TakeoverEntry = { activeSince: number; staleCancels: number; knownFoldAt: number }; + type RegisterState = { sid?: string; toolsFor?: string; toolsReady?: boolean; pending?: Promise; retryAt?: number; identityAt?: string; carriedSids?: Set; retryIntervalMs: number; manifestPrime?: { base: string; tools: Promise } }; async function registerTools(pi: ExtensionAPI, ctx: Ctx, state: RegisterState, agent: string, awaitNativeOrigin = true): Promise { @@ -409,10 +420,13 @@ async function registerTools(pi: ExtensionAPI, ctx: Ctx, state: RegisterState, a } } -export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalMs?: number }): (pi: ExtensionAPI) => void { +export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalMs?: number; takeover?: { maxStaleCancels?: number; timeoutMs?: number } }): (pi: ExtensionAPI) => void { return function biliPlugin(pi: ExtensionAPI): void { const agent = agentName(agentOverride); const state: RegisterState = { retryIntervalMs: opts?.retryIntervalMs ?? RETRY_INTERVAL_MS }; + // #2110: per-conversation takeover watchdog state (see takeoverVerdict). + const takeoverLimits = { maxStaleCancels: opts?.takeover?.maxStaleCancels ?? TAKEOVER_MAX_STALE_CANCELS, timeoutMs: opts?.takeover?.timeoutMs ?? TAKEOVER_TIMEOUT_MS }; + const takeovers = new Map(); // #1217: -p single-shot fires round 1 before session_start's manifest // fetch can resolve, leaving the request unmarked → anonymous // proxy-mode session. Prime the fetch at load time: the launcher @@ -487,12 +501,19 @@ export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalM // content-hash identity, where avoiding double compression still // wins). Probe failure (proxy down/hung) means NO evidence → defer to // native compaction: a surviving native pass is safe (#395), a wrong - // cancel overflows the session. The handlers are async on purpose — - // pi's runner awaits session_before_compact handlers (verified in - // pi-coding-agent dist) before consulting .cancel/.compaction. - const ownsCompaction = async (ctx: Ctx | undefined, branchEntries?: unknown): Promise => { + // cancel overflows the session. #2110 adds the layer above ownership: + // owning compaction is necessary but not sufficient — the takeover must + // actually PRODUCE folds; when it doesn't (nudge-gate starvation, a + // preflight fold that never lands), the watchdog releases passes back + // to the host's native compaction after a bounded streak of + // evidence-less cancels (takeoverVerdict below). The handlers are + // async on purpose — pi's runner awaits session_before_compact + // handlers (verified in pi-coding-agent dist) before consulting + // .cancel/.compaction. + type OwnershipVerdict = { owned: boolean; proxyBase?: string; status?: Record }; + const ownsCompaction = async (ctx: Ctx | undefined, branchEntries?: unknown): Promise => { const proxyBase = proxyBaseForCtx(ctx, branchEntries); - if (proxyBase === undefined) return false; + if (proxyBase === undefined) return { owned: false }; const baseUrl = ctx?.model?.baseUrl; if (typeof baseUrl === "string" && baseUrl.length > 0 && !/^https?:\/\//i.test(baseUrl)) { // #1392: an opaque-scheme baseUrl (e.g. pi-claude-bridge's "claude-bridge") @@ -501,24 +522,89 @@ export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalM // evidence below (carriedSids / status probe) still decides, so unrouted traffic // never cancels and #1382 cannot recur for a newly-opted-in provider class. const provider = ctx?.model?.provider; - if (!(typeof provider === "string" && provider.length > 0 && nonHttpProvidersFromEnv().has(provider))) return false; + if (!(typeof provider === "string" && provider.length > 0 && nonHttpProvidersFromEnv().has(provider))) return { owned: false }; } const sid = ctx === undefined ? undefined : sessionIdOf(ctx); - if (sid === undefined || sid.length === 0) return true; - if (agent === "pi" ? state.carriedSids?.has(sid) === true : state.identityAt === sid) return true; + if (sid === undefined || sid.length === 0) return { owned: true }; + if (agent === "pi" ? state.carriedSids?.has(sid) === true : state.identityAt === sid) return { owned: true, proxyBase }; try { - return (await fetchStatus(proxyBase, sid)) !== undefined; + const status = await fetchStatus(proxyBase, sid); + return status === undefined ? { owned: false } : { owned: true, proxyBase, status }; } catch (err) { console.error(`bili-plugin(${agent}): compaction ownership probe failed (${err instanceof Error ? err.message : String(err)}) — leaving native compaction enabled`); + return { owned: false }; + } + }; + // #2110: the cancel is deterministic but bili's REPLACEMENT is not — when + // the nudge gates starve (slow-growth sessions: pendingT1 < threshold AND + // growth < floor on every pass) or a preflight fold never lands, cancelling + // every native pass leaves the session growing into overflow with zero + // compression ("Auto-compaction cancelled" spam until 348% of the effective + // window). Watch the takeover itself: every cancelled pass must be backed by + // evidence that a proxy fold actually landed since the previous one — + // /__bili/plugin/status lastCompressAt, stamped by BOTH model-driven compress + // and preflight folds (applyRanges). A streak of cancelled passes without a + // newer fold (or an unreachable/unknown status) means the takeover produces + // nothing: release the pass back to the host's native compaction instead. A + // surviving native pass is safe (#395 archives the blocks it makes + // unreachable), and the release self-heals both ways — after a native pass + // the context sits below the threshold so the hook stops firing, and if the + // proxy resumes folding the credit below re-arms the takeover immediately. + // A status WITHOUT the field (an older proxy) keeps the historical + // unconditional cancel: we cannot distinguish "old proxy folding fine" from + // "old proxy starving", and flipping that behavior mid-version would silently + // change mixed-version installs. + const takeoverVerdict = async (sid: string, verdict: OwnershipVerdict): Promise => { + // Evidence: reuse the status the remote-probe ownership check already + // fetched; local-evidence owners get one extra loopback read per event. + let status = verdict.status; + if (status === undefined && verdict.proxyBase !== undefined) { + try { + status = await fetchStatus(verdict.proxyBase, sid); + } catch { + status = undefined; + } + } + const now = Date.now(); + let entry = takeovers.get(sid); + if (status !== undefined && "lastCompressAt" in status) { + const foldAt = status.lastCompressAt; + if (typeof foldAt === "number" && (entry === undefined || foldAt > entry.knownFoldAt)) { + // A fold landed since we last saw one — the takeover is alive. + takeovers.set(sid, { activeSince: now, staleCancels: 0, knownFoldAt: foldAt }); + return false; + } + // null (no fold yet this process) or a repeat of the same fold: + // falls through to the stale counter below. + } else if (status !== undefined) { + return false; + } + if (entry === undefined) { + if (takeovers.size >= 64) { + const oldest = takeovers.keys().next().value; + if (oldest !== undefined) takeovers.delete(oldest); + } + entry = { activeSince: now, staleCancels: 0, knownFoldAt: Number.NEGATIVE_INFINITY }; + takeovers.set(sid, entry); + } + entry.staleCancels += 1; + if (entry.staleCancels < takeoverLimits.maxStaleCancels && now - entry.activeSince < takeoverLimits.timeoutMs) { return false; } + takeovers.delete(sid); + console.error(`bili-plugin(${agent}): takeover watchdog (#2110) — ${entry.staleCancels} consecutive cancelled auto-compaction passes without a newer proxy fold over ${Math.round((now - entry.activeSince) / 1000)}s; releasing this pass to the host's native compaction`); + return true; }; if (agent === "pi" || agent === "omp") { if (agent === "pi") { pi.on("session_before_compact", async (event, ctx) => { const ev = event as unknown as { reason?: unknown; branchEntries?: unknown }; if (ev.reason !== "threshold" && ev.reason !== "overflow") return undefined; - if (!(await ownsCompaction(ctx, ev.branchEntries))) return undefined; + const verdict = await ownsCompaction(ctx, ev.branchEntries); + if (!verdict.owned) return undefined; + const sid = ctx === undefined ? "" : sessionIdOf(ctx) ?? ""; + if (sid.length === 0) return { cancel: true }; + if (await takeoverVerdict(sid, verdict)) return undefined; return { cancel: true }; }); } else { @@ -531,8 +617,12 @@ export function createBiliPlugin(agentOverride?: string, opts?: { retryIntervalM }); pi.on("session_before_compact", async (event, ctx) => { if (!autoPending) return undefined; - if (!(await ownsCompaction(ctx))) return undefined; + const verdict = await ownsCompaction(ctx); + if (!verdict.owned) return undefined; autoPending = false; + const sid = ctx === undefined ? "" : sessionIdOf(ctx) ?? ""; + if (sid.length === 0) return { cancel: true }; + if (await takeoverVerdict(sid, verdict)) return undefined; return { cancel: true }; }); } diff --git a/src/plugin.ts b/src/plugin.ts index 84e6314c9c..3e2dd4bfda 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -1315,6 +1315,11 @@ export function handlePluginStatus(conversationId: string, res: import("node:htt outputTokens: session.stats.outputTokens, cachedTokens: session.stats.cachedTokens, requests: session.stats.requests, + // #2110: epoch ms of the last landed fold (model-driven compress OR + // preflight — both stamp it in applyRanges), null until the first fold + // in this process. The pi/omp plugin's takeover watchdog reads this to + // distinguish "owning compaction" from "compaction actually producing". + lastCompressAt: session.lastCompress?.at ?? null, blocks: session.state.blocks.map((b) => ({ id: b.blockId, tier: b.tier, active: b.active })), compressibleRanges: nudge?.compressibleRanges ?? null, panel, diff --git a/tests/issue2110-status-lastcompress.test.ts b/tests/issue2110-status-lastcompress.test.ts new file mode 100644 index 0000000000..f7d6df5907 --- /dev/null +++ b/tests/issue2110-status-lastcompress.test.ts @@ -0,0 +1,53 @@ +// #2110: the pi/omp plugin's takeover watchdog reads lastCompressAt from +// /__bili/plugin/status to tell "owning compaction" apart from "compaction +// actually producing". Pin the 200-path field contract: epoch ms of the last +// landed fold (model-driven compress OR preflight — both stamp it in +// applyRanges), null until the first fold in this process. An OLDER proxy +// omits the field entirely; the plugin treats absent (legacy unconditional +// cancel) differently from null (new proxy, no folds yet), so presence itself +// is part of the contract. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import http from "node:http"; +import { createCore, defaultConfig } from "acp-kernel"; +import { _resetSessionsForTest, getSession } from "../src/session.ts"; +import { handlePluginStatus, recordPluginSession } from "../src/plugin.ts"; + +function mockRes(): { res: http.ServerResponse; status: number; body: string } { + const out = { res: undefined as unknown as http.ServerResponse, status: 0, body: "" }; + const res = { + writeHead(code: number) { out.status = code; return res; }, + end(chunk?: unknown) { if (typeof chunk === "string") out.body = chunk; return res; }, + } as unknown as http.ServerResponse; + out.res = res; + return out; +} + +test("#2110: /__bili/plugin/status exposes lastCompressAt (null until the first fold)", () => { + _resetSessionsForTest(); + try { + const deps = { core: createCore(), config: defaultConfig(200000), log: (_l: string, _m: string) => {} }; + + const before = getSession("sess-wd-before", { protocol: "anthropic", label: "WD" }); + recordPluginSession("conv-wd-before", before.id); + const r0 = mockRes(); + handlePluginStatus("conv-wd-before", r0.res, deps, false); + assert.equal(r0.status, 200); + const j0 = JSON.parse(r0.body) as { ok: boolean; conversationId: string; lastCompressAt: number | null }; + assert.equal(j0.ok, true); + assert.equal(j0.conversationId, "conv-wd-before"); + assert.equal(j0.lastCompressAt, null, "no fold yet → null (field PRESENT, unlike an older proxy)"); + + const after = getSession("sess-wd-after", { protocol: "anthropic", label: "WD" }); + after.lastCompress = { at: 1_760_000_000_123, shrinkRatio: 0.42, foldPoint: "m00042", blocks: 3, tokensCompressed: 55_000 }; + recordPluginSession("conv-wd-after", after.id); + const r1 = mockRes(); + handlePluginStatus("conv-wd-after", r1.res, deps, false); + assert.equal(r1.status, 200); + const j1 = JSON.parse(r1.body) as { ok: boolean; lastCompressAt: number | null }; + assert.equal(j1.ok, true); + assert.equal(j1.lastCompressAt, 1_760_000_000_123, "fold landed → epoch ms passes through byte-exact"); + } finally { + _resetSessionsForTest(); + } +}); diff --git a/tests/plugin-agent.test.ts b/tests/plugin-agent.test.ts index 190ec54920..7b5b79f86c 100644 --- a/tests/plugin-agent.test.ts +++ b/tests/plugin-agent.test.ts @@ -62,6 +62,12 @@ type FakeProxy = { toolCalls: Array<{ conversationId: string; tool: string; args: unknown; nativeCaller?: boolean }>; registers: Array<{ conversationId: string; agent: string; identity: boolean; parentConversationId?: string }>; runtimeInfos: Array>; + /** Extra fields merged into the 200 /__bili/plugin/status body (tests mutate + * this between calls to simulate fold progress, #2110). */ + statusBody: Record; + /** Served /__bili/plugin/status request count — pins #2110's verdict + * reuse: exactly one loopback read per compaction event, not two. */ + statusCalls(): number; close(): Promise; }; @@ -69,6 +75,8 @@ async function startFakeProxy(opts: { failRegister?: number; statusOk?: boolean const toolCalls: FakeProxy["toolCalls"] = []; const registers: FakeProxy["registers"] = []; const runtimeInfos: FakeProxy["runtimeInfos"] = []; + const statusBody: Record = {}; + let statusCalls = 0; const server = http.createServer((req, res) => { const url = req.url ?? ""; if (url === "/__bili/plugin/manifest") { @@ -121,12 +129,13 @@ async function startFakeProxy(opts: { failRegister?: number; statusOk?: boolean return; } if (url.startsWith("/__bili/plugin/status")) { + statusCalls += 1; if (opts.statusOk === false) { res.writeHead(404, { "content-type": "application/json" }); res.end(JSON.stringify({ ok: false, error: "unknown plugin conversation" })); } else { res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: true, contextTokens: 1234 })); + res.end(JSON.stringify({ ok: true, contextTokens: 1234, ...statusBody })); } return; } @@ -136,7 +145,7 @@ async function startFakeProxy(opts: { failRegister?: number; statusOk?: boolean server.listen(0, "127.0.0.1"); await once(server, "listening"); const origin = `http://127.0.0.1:${(server.address() as { port: number }).port}`; - return { origin, toolCalls, registers, runtimeInfos, close: () => new Promise((resolve) => server.close(() => resolve())) }; + return { origin, toolCalls, registers, runtimeInfos, statusBody, statusCalls: () => statusCalls, close: () => new Promise((resolve) => server.close(() => resolve())) }; } test("shared manifest/tool/status against a fake proxy", async () => { @@ -486,6 +495,176 @@ test("#1382: compaction cancel requires evidence the proxy carries this conversa } }); +test("#2110: takeover watchdog releases auto compaction when no proxy fold lands", async () => { + // #2110: the cancel is deterministic but bili's replacement is not — when the + // nudge gates starve (slow-growth session: pendingT1 < threshold AND growth + // < floor on every pass) or a preflight fold never lands, cancelling every + // native pass leaves the session growing into overflow with zero compression + // (issue repro: "Auto-compaction cancelled" spam until 348% of the effective + // window). The watchdog requires fold evidence per cancelled pass — + // /__bili/plugin/status lastCompressAt, stamped by BOTH model-driven compress + // and preflight folds — and releases the pass back to the host's native + // compaction after a bounded streak without it. A surviving native pass is + // safe (#395 archives its blocks); the release self-heals both ways. + const stampLocalEvidence = async (proxy: FakeProxy, pi: FakePi, sid: string): Promise> => { + const ctx = fakeCtx(proxy, sid); + await pi.events.get("session_start")!({}, ctx); + await waitForTools(pi, 2); + const headers: Record = {}; + await pi.events.get("before_provider_headers")!({ headers }, ctx); + assert.equal(headers["x-bili-plugin-conversation"], sid, "local carriage evidence stamped"); + return ctx; + }; + + // (A) Stale fold timestamp: the first pass takes the fold as baseline, each + // further pass without a NEWER fold counts against the streak; at the limit + // the pass is released, and the next pass starts a FRESH streak (the proxy + // gets another chance once the native pass has run). + const stale = await startFakeProxy(); + try { + await withEnv({ BILLION_CONTEXT_PROXY: stale.origin }, async () => { + stale.statusBody.lastCompressAt = 1_000_000; + const pi = makeFakePi(); + createBiliPlugin("pi", { takeover: { maxStaleCancels: 3, timeoutMs: 60_000 } })(pi as never); + const ctx = await stampLocalEvidence(stale, pi, "sess-stale"); + const handler = pi.events.get("session_before_compact")!; + assert.deepEqual(await handler({ reason: "threshold" }, ctx), { cancel: true }, "fold seen → baseline, cancelled"); + assert.deepEqual(await handler({ reason: "threshold" }, ctx), { cancel: true }, "stale #1 → still cancelled"); + assert.deepEqual(await handler({ reason: "threshold" }, ctx), { cancel: true }, "stale #2 → still cancelled"); + assert.equal(await handler({ reason: "threshold" }, ctx), undefined, "stale #3 hits the streak limit → native compaction released"); + assert.deepEqual(await handler({ reason: "threshold" }, ctx), { cancel: true }, "post-release → fresh streak, proxy gets another chance"); + }); + } finally { + await stale.close(); + } + + // (B) Fold progress keeps the takeover armed indefinitely: a newer + // lastCompressAt on every pass resets the streak, so count or time can never + // release a healthy takeover. + const healthy = await startFakeProxy(); + try { + await withEnv({ BILLION_CONTEXT_PROXY: healthy.origin }, async () => { + const pi = makeFakePi(); + createBiliPlugin("pi", { takeover: { maxStaleCancels: 3, timeoutMs: 60_000 } })(pi as never); + const ctx = await stampLocalEvidence(healthy, pi, "sess-healthy"); + const handler = pi.events.get("session_before_compact")!; + for (let i = 0; i < 6; i++) { + healthy.statusBody.lastCompressAt = Date.now() + i; + assert.deepEqual(await handler({ reason: "threshold" }, ctx), { cancel: true }, `advancing fold ${i} keeps the takeover armed`); + } + }); + } finally { + await healthy.close(); + } + + // (C) Wall-clock timeout releases even below the streak limit: a takeover + // dead for long enough is dead, regardless of how few passes fired. + const slow = await startFakeProxy(); + try { + await withEnv({ BILLION_CONTEXT_PROXY: slow.origin }, async () => { + slow.statusBody.lastCompressAt = 1_000_000; + const pi = makeFakePi(); + // Wide margins on purpose: each pass is a loopback round-trip, so a + // tight window can elapse between passes on a loaded runner and flip + // the mid-window assertions (determinism rule #7.2). + createBiliPlugin("pi", { takeover: { maxStaleCancels: 100, timeoutMs: 500 } })(pi as never); + const ctx = await stampLocalEvidence(slow, pi, "sess-slow"); + const handler = pi.events.get("session_before_compact")!; + assert.deepEqual(await handler({ reason: "threshold" }, ctx), { cancel: true }, "baseline within the window"); + assert.deepEqual(await handler({ reason: "threshold" }, ctx), { cancel: true }, "stale #1 within the window"); + await sleep(600); + assert.equal(await handler({ reason: "threshold" }, ctx), undefined, "timeout elapsed → native compaction released"); + }); + } finally { + await slow.close(); + } + + // (D) Older proxy WITHOUT the field: the historical unconditional cancel + // stays — we cannot distinguish "old proxy folding fine" from "old proxy + // starving", so the release path activates only for proxies that advertise + // the field. + const old = await startFakeProxy(); + try { + await withEnv({ BILLION_CONTEXT_PROXY: old.origin }, async () => { + const pi = makeFakePi(); + createBiliPlugin("pi", { takeover: { maxStaleCancels: 2, timeoutMs: 60_000 } })(pi as never); + const ctx = await stampLocalEvidence(old, pi, "sess-old-proxy"); + const handler = pi.events.get("session_before_compact")!; + for (let i = 0; i < 5; i++) { + assert.deepEqual(await handler({ reason: "threshold" }, ctx), { cancel: true }, `field absent → legacy unconditional cancel (${i})`); + } + }); + } finally { + await old.close(); + } + + // (E) New proxy, NO fold yet this process (lastCompressAt: null): null is + // not fold evidence, so the streak runs from the first pass (no free + // baseline credit) and the limit releases. + const fresh = await startFakeProxy(); + try { + await withEnv({ BILLION_CONTEXT_PROXY: fresh.origin }, async () => { + fresh.statusBody.lastCompressAt = null; + const pi = makeFakePi(); + createBiliPlugin("pi", { takeover: { maxStaleCancels: 3, timeoutMs: 60_000 } })(pi as never); + const ctx = await stampLocalEvidence(fresh, pi, "sess-fresh"); + const handler = pi.events.get("session_before_compact")!; + assert.deepEqual(await handler({ reason: "threshold" }, ctx), { cancel: true }, "null fold #1 → cancelled"); + assert.deepEqual(await handler({ reason: "threshold" }, ctx), { cancel: true }, "null fold #2 → cancelled"); + assert.equal(await handler({ reason: "threshold" }, ctx), undefined, "null fold #3 hits the limit → released"); + }); + } finally { + await fresh.close(); + } + + // (F) Unknown-conversation status counts as missing evidence too (#1382(E)'s + // local-evidence case, sustained over time): a live-but-unaware proxy cannot + // produce folds either, so the same streak releases. + const unaware = await startFakeProxy({ statusOk: false }); + try { + await withEnv({ BILLION_CONTEXT_PROXY: unaware.origin }, async () => { + const pi = makeFakePi(); + createBiliPlugin("pi", { takeover: { maxStaleCancels: 3, timeoutMs: 60_000 } })(pi as never); + const ctx = await stampLocalEvidence(unaware, pi, "sess-unaware"); + const handler = pi.events.get("session_before_compact")!; + assert.deepEqual(await handler({ reason: "threshold" }, ctx), { cancel: true }, "unknown conversation #1 → cancelled"); + assert.deepEqual(await handler({ reason: "threshold" }, ctx), { cancel: true }, "unknown conversation #2 → cancelled"); + assert.equal(await handler({ reason: "threshold" }, ctx), undefined, "unknown conversation #3 hits the limit → released"); + }); + } finally { + await unaware.close(); + } + + // (G) omp parity + remote-probe ownership: the announced-auto path rides the + // same watchdog, and the status the ownership probe already fetched is + // reused (no second round-trip). + const ompProxy = await startFakeProxy(); + try { + await withEnv({ BILLION_CONTEXT_PROXY: ompProxy.origin }, async () => { + ompProxy.statusBody.lastCompressAt = 1_000_000; + const omp = makeFakePi(); + createBiliPlugin("omp", { takeover: { maxStaleCancels: 3, timeoutMs: 60_000 } })(omp as never); + const ctx: Record = { + sessionManager: { getSessionId: () => "sess-omp-watchdog" }, + model: { contextWindow: 1000000, baseUrl: "https://api.example.com/v1" }, + cwd: "/tmp", + }; + const handler = omp.events.get("session_before_compact")!; + const fire = async (): Promise => { + omp.events.get("auto_compaction_start")!({}, undefined); + return await handler({}, ctx); + }; + assert.deepEqual(await fire(), { cancel: true }, "omp: fold seen → baseline, cancelled"); + assert.deepEqual(await fire(), { cancel: true }, "omp: stale #1 → cancelled"); + assert.deepEqual(await fire(), { cancel: true }, "omp: stale #2 → cancelled"); + assert.equal(await fire(), undefined, "omp: stale #3 hits the limit → released"); + assert.equal(ompProxy.statusCalls(), 4, "ownership probe's status is reused by the verdict — one loopback read per event, not two"); + }); + } finally { + await ompProxy.close(); + } +}); + test("#1392: non-http(s) provider rides bili only when opted in AND carried", async () => { // #1383's stopgap vetoed ALL non-http(s) baseUrls (e.g. pi-claude-bridge's literal // "claude-bridge"), so a proxy's mere existence could never claim compaction for