From 1783523b4c999a7d3b3d82c6fb07a7895ff93446 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 11:42:16 +0900 Subject: [PATCH 01/43] chore(release): open dev at 2.97.0 before releasing 2.96.0 (#8068) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- desktop/src-tauri/Cargo.lock | 2 +- desktop/src-tauri/Cargo.toml | 2 +- desktop/src-tauri/tauri.conf.json | 2 +- package.json | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock index 8f416f48dc5..0cc2f6deea2 100644 --- a/desktop/src-tauri/Cargo.lock +++ b/desktop/src-tauri/Cargo.lock @@ -2645,7 +2645,7 @@ dependencies = [ [[package]] name = "opencodex-desktop" -version = "2.96.0" +version = "2.97.0" dependencies = [ "base64 0.22.1", "dbus", diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index 385e89c5464..a0ecc4f7a0a 100644 --- a/desktop/src-tauri/Cargo.toml +++ b/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "opencodex-desktop" -version = "2.96.0" +version = "2.97.0" description = "OpenCodex desktop shell" authors = ["OpenCodex contributors"] license = "MIT" diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json index 38ac6967560..7a63a3e2b67 100644 --- a/desktop/src-tauri/tauri.conf.json +++ b/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "OpenCodex", - "version": "2.96.0", + "version": "2.97.0", "identifier": "com.opencodex.desktop", "build": { "frontendDist": "../ui", diff --git a/package.json b/package.json index 1c5ea6f0687..d763390a680 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@bitkyc08/opencodex", - "version": "2.96.0", + "version": "2.97.0", "description": "Universal provider proxy for OpenAI Codex & Claude Code — use any LLM with Codex CLI/App/SDK and Claude Code", "type": "module", "main": "./bin/package-main.mjs", From 6f1d3e65c5cf8290c7f4d10c7ad5b9b1f0bd8d71 Mon Sep 17 00:00:00 2001 From: JUN Date: Mon, 2 Nov 2026 15:08:43 +0900 Subject: [PATCH 02/43] fix(anthropic): show both 5-hour and weekly meters for Max and Team accounts (#8088) * fix(anthropic): keep inactive shared quota meters Treat is_active as the binding-meter marker for shared five-hour and weekly usage, including routing and cooldown recovery. When legacy five_hour is null, only an explicitly active finite session establishes a meter. Keep scoped model limits active-only. * test(anthropic): keep routing fixtures' weekly resets in the future --- .../src/content/docs/guides/claude-code.md | 8 ++- .../docs/reference/configuration/providers.md | 11 +-- .../quota/anthropic-usage-windows.ts | 16 ++++- structure/providers/anthropic-account-pool.md | 16 +++-- .../anthropic-active-limit-routing.test.ts | 72 +++++++++++++++++-- tests/fixtures/anthropic-usage-shapes.ts | 11 +++ .../provider-anthropic-usage-windows.test.ts | 62 +++++++++++++--- 7 files changed, 165 insertions(+), 31 deletions(-) diff --git a/docs-site/src/content/docs/guides/claude-code.md b/docs-site/src/content/docs/guides/claude-code.md index 46687ed3468..e9ef9a8e281 100644 --- a/docs-site/src/content/docs/guides/claude-code.md +++ b/docs-site/src/content/docs/guides/claude-code.md @@ -69,9 +69,11 @@ response headers on streaming, JSON and upstream-error responses, so compatible statusLine consumers can read the provider's quota observations. Missing observations are not filled with invented values. This relay does not change account selection or retry behavior. -Usage reads support Ultra (formerly Max 20x). Pro and Max 5x retain their five-hour and weekly meters. A null five-hour limit leaves that meter -absent and still allows weekly usage to display. Current `limits` counters take precedence -over legacy duplicates; only active model-specific weekly limits affect that model family. +Usage reads support Ultra (formerly Max 20x). Pro, Max 5x and Team retain their measured +five-hour and weekly meters whichever one is currently binding. An Ultra null five-hour limit +leaves that meter absent unless Anthropic marks a finite session meter active. Current `limits` +counters take precedence over legacy duplicates; shared usage can affect routing even when +inactive, while only active model-specific weekly limits affect that model family. The dashboard shows Pro, Max 5x, or Ultra beside Claude account quotas, using subscription metadata from the authenticated profile. Both `ultra` and `claude_max_20x` display as Ultra (the existing `ultra` and `max_20x` tier aliases are retained). Unfamiliar validated tiers retain their original name without diff --git a/docs-site/src/content/docs/reference/configuration/providers.md b/docs-site/src/content/docs/reference/configuration/providers.md index 16853705892..0c37bfc4a8a 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -1087,11 +1087,12 @@ eligible on the same account. Passive Fable evidence ages out after thirty minut known reset and is revalidated by one serving request at a time. Usage thresholds remain soft preferences with an all-drained fallback; these controls are not hard usage or billing caps. Active usage probes preserve absent family windows unless the response authoritatively enumerates limits. -Usage reads prefer the active `limits` rows over legacy quota buckets. An inactive -session or model window does not constrain admission, and a missing/null five-hour -bucket does not create a zero-percent five-hour bar. A model-scoped weekly limit -constrains only that model family while active; the all-model weekly limit applies -to every model. Legacy Pro/Max usage buckets remain supported. +Usage reads prefer recognized `limits` rows over legacy quota buckets. Pro, Max 5x and +Team retain measured five-hour and weekly meters whichever is currently binding. Shared +usage affects admission and cooldown recovery even when inactive. An explicitly null +five-hour bucket creates a meter only when Anthropic marks a finite session meter active. +A model-scoped weekly limit constrains only that model family while active; the all-model +weekly limit applies to every model. Legacy Pro/Max usage buckets remain supported. [Ultra replaces Max 20x](https://support.claude.com/en/articles/17728952-what-is-the-ultra-plan); upstream may still identify it as `claude_max_20x` (shown as `max_20x`). Ultra accounts diff --git a/src/providers/quota/anthropic-usage-windows.ts b/src/providers/quota/anthropic-usage-windows.ts index c423f1480d1..5fc10708dad 100644 --- a/src/providers/quota/anthropic-usage-windows.ts +++ b/src/providers/quota/anthropic-usage-windows.ts @@ -19,9 +19,11 @@ function scopedFamily(row: Record): "fable" | "opus" | "sonnet" } /** - * A limits entry supersedes its legacy duplicate even when inactive or unusable. - * Missing is_active preserves the older limits contract; an unknown flag is not active. - * Unknown kinds/families leave usable shared windows intact but cannot clear family refusals. + * Recognized rows supersede legacy duplicates even when skipped or malformed; duplicates + * and malformed shared measurements make family enumeration incomplete. Shared finite + * measurements apply regardless of the binding flag, though an unknown flag also makes + * enumeration incomplete. A null legacy five_hour requires an explicitly active session. + * Scoped rows retain active-only behavior; unknown kinds/families cannot clear refusals. */ export function anthropicUsageBuckets(body: Record): { buckets: AnthropicUsageBucket[]; familyEnumeration: boolean; @@ -37,6 +39,14 @@ export function anthropicUsageBuckets(body: Record): { if (!row || !window) { familyEnumeration = false; continue; } if (represented.has(window)) { familyEnumeration = false; continue; } represented.add(window); + if (window === "5h" || window === "weekly") { + const flag = row.is_active; + if (flag !== undefined && typeof flag !== "boolean") familyEnumeration = false; + if (toFiniteNumber(row.percent) === undefined) { familyEnumeration = false; continue; } + if (window === "5h" && body.five_hour === null && flag !== true) continue; + selected.set(window, { window, row, percentField: "percent" }); + continue; + } if (row.is_active === false) continue; if (row.is_active !== undefined && row.is_active !== true) { familyEnumeration = false; continue; } if (toFiniteNumber(row.percent) === undefined) familyEnumeration = false; diff --git a/structure/providers/anthropic-account-pool.md b/structure/providers/anthropic-account-pool.md index 896bcdf09af..abe49f2cd2a 100644 --- a/structure/providers/anthropic-account-pool.md +++ b/structure/providers/anthropic-account-pool.md @@ -54,8 +54,9 @@ confirmations/notifications through `gui/src/hooks/useProviderAccountPools.ts`; retain their existing alias/email labels. `gui/src/pages/providers-page-utils.ts` also strips Claude email metadata from the catalog/Add Provider account-status projection without mutating the source OAuth status; generic/custom account-status labels remain intact. The current quota section keeps -that label even if usage is unavailable. Pro and Max 5x keep their measured five-hour and -weekly windows; an explicitly absent/inactive session never fabricates a meter. +that label even if usage is unavailable. Pro, Max 5x and Team retain measured five-hour and +weekly windows regardless of which is binding. An explicitly null five-hour bucket permits +a session meter only when its finite measurement is explicitly active. `src/oauth/google-antigravity.ts` persists `loadCodeAssist`'s `paidTier.id`, falling back to `currentTier.id` (paid accounts report `free-tier` there), alongside the discovered project @@ -188,10 +189,13 @@ preserves, `null` deletes and an instance sets; an unset choice is never written `src/providers/claude-cli-usage.ts` display and the raw advisory projection in `src/providers/quota/anthropic-decision-windows.ts`. Recognized `limits` rows take precedence over their legacy buckets: `session`, `weekly_all`, and model-scoped -`weekly_scoped`. An inactive row suppresses its legacy duplicate; an absent/null -five-hour bucket contributes no measurement. Older rows without `is_active` retain -their original active semantics. Unknown flags are not active, and unknown kinds -or model families preserve usable shared windows without claiming a complete +`weekly_scoped`. Each recognized row is represented before any skip, so duplicates +and malformed shared measurements cannot revive legacy data and make family enumeration +incomplete. Shared finite measurements are used regardless of the binding `is_active` flag; +a non-boolean flag also makes enumeration incomplete. When legacy `five_hour` is explicitly +null, only a finite session marked active creates a five-hour meter. Inactive shared usage +is valid routing and cooldown recovery evidence. Scoped rows retain active-only semantics; +unknown kinds or model families preserve usable shared windows without claiming a complete family enumeration. An authoritative inactive family row can retire a previous passive family refusal; an incomplete enumeration cannot. Shared cooldown recovery still requires finite headroom for each rejected window, never an invented zero. diff --git a/tests/adapters/anthropic/anthropic-active-limit-routing.test.ts b/tests/adapters/anthropic/anthropic-active-limit-routing.test.ts index 79b80deda68..0a93965d8a7 100644 --- a/tests/adapters/anthropic/anthropic-active-limit-routing.test.ts +++ b/tests/adapters/anthropic/anthropic-active-limit-routing.test.ts @@ -6,8 +6,16 @@ import { getAccountSet, saveCredential } from "../../../src/oauth/store"; import { captureAnthropicCooldownRecovery, clearAnthropicAccountPoolState, getAnthropicAccountHealthSnapshot, pickAlternateAnthropicAccount, recordAnthropicAccount429, settleAnthropicCooldownRecovery } from "../../../src/oauth/anthropic-routing"; import { clearAccountQuotaCache, setCachedProviderAccountQuotaForTests } from "../../../src/providers/quota"; +import { anthropicFamilyRejected, observeAnthropicFamilyQuota } from "../../../src/oauth/anthropic-model-quota"; +import { probeAnthropicQuotaWithRecovery } from "../../../src/providers/quota/anthropic-cooldown-recovery"; +import { hasAnthropicFamilyEnumeration } from "../../../src/providers/quota/anthropic-family-headers"; +import { anthropicModelPercents } from "../../../src/oauth/anthropic-model-quota"; +import { providerQuotaWindows } from "../../../src/quota-pool/assemble"; import { probeAnthropicUsageQuota } from "../../../src/providers/claude-cli-usage"; -import { ultraUsage, weeklyReset } from "../../fixtures/anthropic-usage-shapes"; +import { ultraUsage } from "../../fixtures/anthropic-usage-shapes"; + +/** A weekly reset relative to now, so cached windows never expire mid-suite on a later date. */ +const futureWeeklyReset = () => new Date(Date.now() + 7 * 86_400_000).toISOString(); import { drainAndRemoveFixtureRoots } from "../../helpers/fixture-teardown"; import type { OcxConfig } from "../../../src/types"; @@ -47,8 +55,8 @@ async function parse(body: unknown) { for (const active of [false, true]) test(`real pool selection applies active=${active} Fable only to Fable`, async () => { const [a, b] = await seed(); const quota = await parse({ five_hour: null, seven_day_fable: { utilization: 100 }, limits: [ - { kind: "weekly_all", percent: 10, is_active: true, resets_at: weeklyReset }, - { kind: "weekly_scoped", percent: 100, is_active: active, resets_at: weeklyReset, + { kind: "weekly_all", percent: 10, is_active: true, resets_at: futureWeeklyReset() }, + { kind: "weekly_scoped", percent: 100, is_active: active, resets_at: futureWeeklyReset(), scope: { model: { display_name: "Fable" } } }, ] }); setCachedProviderAccountQuotaForTests("anthropic", a!, quota); @@ -65,7 +73,7 @@ test("null or explicitly inactive 5h does not fabricate evidence to clear an ear })); const claim = captureAnthropicCooldownRecovery(id!, now)!; expect(claim).not.toBeNull(); - for (const body of [ultraUsage, { ...ultraUsage, five_hour: { utilization: 0 }, limits: [ + for (const body of [ultraUsage, { ...ultraUsage, five_hour: null, limits: [ ...ultraUsage.limits, { kind: "session", is_active: false, percent: 0 }, ] }]) { const quota = await parse(body); @@ -74,3 +82,59 @@ test("null or explicitly inactive 5h does not fabricate evidence to clear an ear expect(getAnthropicAccountHealthSnapshot(id!)).not.toBeNull(); } }); + + +test("RR1 inactive exhausted weekly excludes all models", async () => { + const [a, b] = await seed(); + const quota = await parse({ limits: [{ kind: "weekly_all", percent: 100, is_active: false, resets_at: futureWeeklyReset() }] }); + for (const model of ["claude-sonnet-5-5", "claude-fable-5"]) expect(anthropicModelPercents(quota, model)).toContain(100); + expect(providerQuotaWindows(quota, "measured", Date.now()).find(row => row.id === "weekly")?.exhausted).toBe(true); + setCachedProviderAccountQuotaForTests("anthropic", a!, quota); + setCachedProviderAccountQuotaForTests("anthropic", b!, { weeklyPercent: 20, updatedAt: Date.now() }); + for (const model of ["claude-sonnet-5-5", "claude-fable-5"]) expect(pickAlternateAnthropicAccount(config, "outside-pool", Date.now(), null, model)).toBe(b!); +}); + +test("RR2 inactive weekly headroom settles pending weekly cooldown", async () => { + const [id] = await seed(); + const now = Date.now(); + recordAnthropicAccount429(config, id!, "3600", now, new Headers({ "anthropic-ratelimit-unified-7d-status": "rejected" })); + const claim = captureAnthropicCooldownRecovery(id!, now)!; + const quota = await parse({ limits: [{ kind: "weekly_all", is_active: false, percent: 55, resets_at: new Date(now + 3600000).toISOString() }] }); + expect(settleAnthropicCooldownRecovery(claim, quota)).toBe("cleared"); +}); + +test("G5 malformed shared data neither clears cooldown nor revives stale exhaustion", async () => { + const [id] = await seed(); + const now = Date.now(); + recordAnthropicAccount429(config, id!, "3600", now, new Headers({ "anthropic-ratelimit-unified-7d-status": "rejected" })); + const claim = captureAnthropicCooldownRecovery(id!, now)!; + for (const stale of [0, 100]) { + const quota = await parse({ five_hour: { utilization: 1 }, seven_day: { utilization: stale }, limits: [{ kind: "weekly_all", is_active: true, percent: "x" }] }); + expect(anthropicModelPercents(quota, "claude-fable-5")).toEqual([1]); + expect(settleAnthropicCooldownRecovery(claim, quota)).toBe("retained"); + } +}); + +async function familyRecovery(body: unknown, expectedEnumeration: boolean, retained: boolean) { + const [id] = await seed(); + const credentials = getAccountSet("anthropic")!.accounts.find(row => row.id === id)!.credential; + observeAnthropicFamilyQuota(id!, [{ label: "Fable", scope: "model", percent: 100, rejected: true }], Date.now()); + expect(anthropicFamilyRejected(id!, "claude-fable-5")).toBe(true); + const quota = await parse(body); + expect(hasAnthropicFamilyEnumeration(quota)).toBe(expectedEnumeration); + const result = await probeAnthropicQuotaWithRecovery(id!, credentials.access, async () => quota, () => true); + expect(result).not.toBeNull(); + expect(anthropicFamilyRejected(id!, "claude-fable-5")).toBe(retained); +} +const inactiveFable = { kind: "weekly_scoped", is_active: false, percent: 0, scope: { model: { display_name: "Fable" } } }; +test("R7 malformed inactive Ultra session retains passive Fable refusal", async () => { + await familyRecovery({ five_hour: null, seven_day: { utilization: 1 }, limits: [{ kind: "session", is_active: false, percent: "x" }, inactiveFable] }, false, true); +}); +for (const duplicate of [false, true]) test(`G6 incomplete shared enumeration retains family refusal duplicate=${duplicate}`, async () => { + const rows = duplicate ? [{ kind: "weekly_all", is_active: true, percent: 1 }, { kind: "weekly_all", is_active: true, percent: 2 }] + : [{ kind: "weekly_all", is_active: true, percent: "x" }]; + await familyRecovery({ five_hour: { utilization: 1 }, limits: [...rows, inactiveFable] }, false, true); +}); +test("G6 complete enumeration retires passive Fable refusal", async () => { + await familyRecovery({ limits: [{ kind: "weekly_all", is_active: true, percent: 1 }, inactiveFable] }, true, false); +}); diff --git a/tests/fixtures/anthropic-usage-shapes.ts b/tests/fixtures/anthropic-usage-shapes.ts index ed4bdca2fa4..520c222ef4d 100644 --- a/tests/fixtures/anthropic-usage-shapes.ts +++ b/tests/fixtures/anthropic-usage-shapes.ts @@ -29,3 +29,14 @@ export const noResetGrant = { weekly_resets_at: weeklyReset, cooldown_until: null, next_grant_id: null, event_props: { tier: "claude_max_20x", billing: "google_play" }, }; + +export const maxTeamInactiveWeeklyUsage = { + five_hour: { utilization: 0, resets_at: null }, seven_day: { utilization: 55, resets_at: weeklyReset }, + limits: [{ kind: "session", percent: 0, resets_at: null, is_active: true }, + { kind: "weekly_all", percent: 55, resets_at: weeklyReset, is_active: false }], +}; +export const maxTeamInactiveSessionUsage = { + five_hour: { utilization: 40, resets_at: weeklyReset }, seven_day: { utilization: 56, resets_at: weeklyReset }, + limits: [{ kind: "session", percent: 40, resets_at: weeklyReset, is_active: false }, + { kind: "weekly_all", percent: 56, resets_at: weeklyReset, is_active: true }], +}; diff --git a/tests/providers/provider-anthropic-usage-windows.test.ts b/tests/providers/provider-anthropic-usage-windows.test.ts index d83d2889354..610226a69e1 100644 --- a/tests/providers/provider-anthropic-usage-windows.test.ts +++ b/tests/providers/provider-anthropic-usage-windows.test.ts @@ -7,7 +7,7 @@ import { resolveAnthropicAccountIdentity } from "../../src/oauth/anthropic-ident import { providerQuotaWindows } from "../../src/quota-pool/assemble"; import { pooledWindows } from "../../src/quota-pool/pooled"; import { anthropicResetGrantBlocker, parseAnthropicResetGrantStatus } from "../../src/providers/anthropic-reset-grants"; -import { inactiveSessionUsage, legacyMax20xUsage, noResetGrant, ultraUsage, weeklyReset } from "../fixtures/anthropic-usage-shapes"; +import { inactiveSessionUsage, maxTeamInactiveWeeklyUsage, maxTeamInactiveSessionUsage, legacyMax20xUsage, noResetGrant, ultraUsage, weeklyReset } from "../fixtures/anthropic-usage-shapes"; const originalFetch = globalThis.fetch; const now = Date.parse("2026-10-31T14:00:00Z"); @@ -40,11 +40,11 @@ test("Ultra null 5h and inactive Fable publish only the weekly window", async () expect(providerQuotaWindows(quota!, "measured", now).map(row => row.id)).toEqual(["weekly"]); }); -test("inactive session evidence suppresses the legacy zero session bucket", async () => { +test("R3 inactive session retains the zero session meter", async () => { const quota = await parse(inactiveSessionUsage); - expect(quota?.fiveHourPercent).toBeUndefined(); + expect(quota?.fiveHourPercent).toBe(0); expect(quota?.fiveHourResetAt).toBeUndefined(); - expect(rawAnthropicUsageWindows(inactiveSessionUsage, now).map(row => row.window)).toEqual(["weekly"]); + expect(rawAnthropicUsageWindows(inactiveSessionUsage, now).map(row => row.window)).toEqual(["5h", "weekly"]); }); test("limits weekly_all works with missing five_hour and no legacy seven_day", async () => { @@ -86,12 +86,54 @@ test("unknown limit kinds/families do not discard shared usage or claim complete expect(hasAnthropicFamilyEnumeration(quota!)).toBe(false); }); -test("inactive or malformed authoritative limits never revive stale legacy exhaustion", async () => { - for (const is_active of [false, "unknown"]) { - const body = { seven_day: { utilization: 100 }, limits: [{ kind: "weekly_all", is_active, percent: 0 }] }; - expect((await parse(body))?.weeklyPercent).toBeUndefined(); - expect(rawAnthropicUsageWindows(body, now)).toEqual([]); - } +for (const flag of [false, "unknown"]) test(`R4 shared weekly flag ${flag} uses authoritative data`, async () => { + const body = { seven_day: { utilization: 100 }, limits: [{ kind: "weekly_all", is_active: flag, percent: 0 }] }; + const quota = await parse(body); + expect(quota?.weeklyPercent).toBe(0); + expect(rawAnthropicUsageWindows(body, now).map(row => row.percent)).toEqual([0]); + expect(hasAnthropicFamilyEnumeration(quota!)).toBe(flag === false); +}); + +test("R1 inactive weekly retains both shared projections", async () => { + const quota = await parse(maxTeamInactiveWeeklyUsage); + expect(quota).toMatchObject({ fiveHourPercent: 0, weeklyPercent: 55, weeklyResetAt: Date.parse(weeklyReset) }); + expect(rawAnthropicUsageWindows(maxTeamInactiveWeeklyUsage, now).map(row => row.window)).toEqual(["5h", "weekly"]); + expect(providerQuotaWindows(quota!, "measured", now).map(row => row.id)).toEqual(["5h", "weekly"]); +}); +test("R2 inactive session retains its measured usage", async () => { + const quota = await parse(maxTeamInactiveSessionUsage); + expect(quota).toMatchObject({ fiveHourPercent: 40, fiveHourResetAt: Date.parse(weeklyReset), weeklyPercent: 56 }); +}); +test("R5 Ultra null five_hour and missing session flag has no 5h meter", async () => { + const quota = await parse({ five_hour: null, limits: [{ kind: "session", percent: 7 }] }); + expect(quota?.fiveHourPercent).toBeUndefined(); +}); +for (const legacy of [undefined, { utilization: 99 }]) test(`R6 malformed inactive shared row clears enumeration legacy=${!!legacy}`, async () => { + const quota = await parse({ seven_day: legacy, limits: [{ kind: "session", is_active: true, percent: 1 }, { kind: "weekly_all", is_active: false, percent: "x" }] }); + expect(quota?.weeklyPercent).toBeUndefined(); + expect(hasAnthropicFamilyEnumeration(quota!)).toBe(false); +}); +test("G0 Ultra explicit active session establishes a 5h meter", async () => { + expect((await parse({ five_hour: null, limits: [{ kind: "session", is_active: true, percent: 7 }] }))?.fiveHourPercent).toBe(7); +}); +for (const flag of [false, "unknown"]) test(`G1 Ultra null session flag ${flag} has no meter`, async () => { + expect((await parse({ five_hour: null, limits: [{ kind: "session", is_active: flag, percent: 7 }] }))?.fiveHourPercent).toBeUndefined(); +}); +for (const percent of [undefined, "x"]) test(`G2 malformed active shared ${percent} suppresses legacy`, async () => { + const body = { five_hour: { utilization: 1 }, seven_day: { utilization: 100 }, limits: [{ kind: "weekly_all", is_active: true, percent }] }; + const quota = await parse(body); + expect(quota?.weeklyPercent).toBeUndefined(); + expect(rawAnthropicUsageWindows(body, now).map(row => row.window)).toEqual(["5h"]); + expect(hasAnthropicFamilyEnumeration(quota!)).toBe(false); +}); +for (const malformedFirst of [true, false]) test(`G3 duplicate shared first malformed=${malformedFirst}`, async () => { + const valid = { kind: "weekly_all", is_active: true, percent: 42 }; + const malformed = { kind: "weekly_all", is_active: true, percent: "x" }; + const body = { five_hour: { utilization: 1 }, seven_day: { utilization: 100 }, limits: malformedFirst ? [malformed, valid] : [valid, malformed] }; + const quota = await parse(body); + expect(quota?.weeklyPercent).toBe(malformedFirst ? undefined : 42); + expect(rawAnthropicUsageWindows(body, now).filter(row => row.window === "weekly").map(row => row.percent)).toEqual(malformedFirst ? [] : [42]); + expect(hasAnthropicFamilyEnumeration(quota!)).toBe(false); }); test("raw decision windows retain invalid reset evidence instead of display normalization", () => { From 52dd19fb78b10f660ae6ca6af75adca51dca21ec Mon Sep 17 00:00:00 2001 From: JUN Date: Mon, 2 Nov 2026 17:53:05 +0900 Subject: [PATCH 03/43] fix(codex): place round-robin conversations on accounts with quota headroom (#8092) * fix(codex): place round-robin conversations on accounts with quota headroom Round-robin rotated new Codex conversations by count alone, so a fresh conversation could bind to an account already at 95% and then move to a cold prompt cache when that account ran out. New placements now skip accounts at or over their effective autoSwitchThreshold while any eligible account is under it, using the hasCodexQuotaHeadroom score fill-first and the priority tier already use. When every account is over, rotation covers all of them as before. Bound conversations, failover alternates and the lineage first-placement hint keep their existing behaviour. Docs: document the Codex rule, and correct the Claude quota strategy description, which keeps the active account until it reaches autoSwitchThreshold before moving to the least-used account. * fix(codex): keep an operator's manual selection in round-robin placement Manual selection seeds the round-robin ring so the next placement lands on the chosen account. The headroom preference dropped an over-threshold selection from the candidates, which cleared that seed. Keep the scope's unspent manual selection in the list; once a dispatch on it succeeds the selection is spent and the headroom preference applies again. Docs: translated quotaWindow rows now say per-account weekly bars come from usage probes or observed response headers, matching English. * fix(codex): honor a manual selection on the Reserve ring too Manual selection seeds the shared ring and each independent quota-scope ring, but recorded the one-shot preference for the shared scope only, so the round-robin headroom preference dropped an over-threshold selection from the next Reserve placement. Record the one-shot per seeded scope and clear it with the seeds on release. Only the shared one-shot guards the shared active cursor; a successful dispatch in a scope spends that scope's one-shot. * test(codex): assert a shared success leaves the Reserve one-shot unspent * docs(codex): describe the per-scope one-shot lifecycle of a manual selection under round-robin --- .../261102_codex_rr_headroom/010_plan.md | 195 ++++++++++++++ .../src/content/docs/fr/guides/claude-code.md | 5 +- .../fr/reference/configuration/providers.md | 12 +- .../src/content/docs/guides/claude-code.md | 6 +- .../ja/reference/configuration/providers.md | 13 +- .../ko/reference/configuration/providers.md | 12 +- .../docs/reference/configuration/providers.md | 12 +- .../ru/reference/configuration/providers.md | 13 +- .../src/content/docs/tr/guides/claude-code.md | 6 +- .../tr/reference/configuration/providers.md | 12 +- .../reference/configuration/providers.md | 13 +- .../content/docs/zh-tw/guides/claude-code.md | 6 +- .../reference/configuration/providers.md | 12 +- scripts/test-layout/layout.json | 2 +- src/codex/routing/active-account.ts | 16 +- src/codex/routing/selection.ts | 41 ++- structure/INDEX.md | 2 + structure/manifest.json | 7 + .../providers/codex-round-robin-placement.md | 48 ++++ structure/providers/openai-accounts.md | 2 +- .../codex-round-robin-headroom.test.ts | 251 ++++++++++++++++++ tests/fixtures/test-layout-expected.json | 1 + 22 files changed, 618 insertions(+), 69 deletions(-) create mode 100644 devlog/_plan/261102_codex_rr_headroom/010_plan.md create mode 100644 structure/providers/codex-round-robin-placement.md create mode 100644 tests/codex-integration/codex-round-robin-headroom.test.ts diff --git a/devlog/_plan/261102_codex_rr_headroom/010_plan.md b/devlog/_plan/261102_codex_rr_headroom/010_plan.md new file mode 100644 index 00000000000..3acba0ef824 --- /dev/null +++ b/devlog/_plan/261102_codex_rr_headroom/010_plan.md @@ -0,0 +1,195 @@ +# 010 — Codex round-robin places new conversations on accounts with headroom + +Lane C of the multi-account parallel lanes. Branch `goat/lane-c-codex-rr-threshold`, PR target `dev`. + +## Problem + +`accountPoolStrategy: "round-robin"` rotates unbound (new) Codex conversations by counter only. +`pickUnboundStrategyAccount` (src/codex/routing/selection.ts) hands `listEligibleCodexAccountIds` +straight to `pickRoundRobinAccount` / `peekRoundRobinAccount`. A new conversation can therefore land +on an account already at 95%. The conversation binds there (thread affinity), and when the account +reaches 100% the binding is released and the conversation moves to another account with a cold +prompt cache. + +## Finding that changes the brief + +The brief says the Claude pool's round-robin already skips accounts over `autoSwitchThreshold` for new +sessions. On current `dev` it does not: `src/oauth/anthropic-routing.ts` `pickUnboundStrategyAccount` +filters only `anthropicModelExhausted` (model family at 100%), and the docs say Claude round-robin is +not usage-driven (docs-site providers-accounts.md, structure/providers/anthropic-account-thresholds.md). +The "prefer under threshold, fall back when none" rule lives in Claude's `pickLowestUsage` +("Thresholds are preferences, never eligibility"). This lane models the Codex rule on that idea and +leaves Claude routing code alone (out of lane scope). The PR body states this. + +## Design (diff level) + +src/codex/routing/selection.ts only. + +1. New private helper next to `hasCodexQuotaHeadroom`: + + ```ts + function roundRobinPlacementCandidates(config, eligible, now, selectionOptions): readonly string[] { + const withHeadroom = eligible.filter(id => hasCodexQuotaHeadroom(config, id, selectionOptions, now)); + return withHeadroom.length > 0 ? withHeadroom : eligible; + } + ``` + +2. `pickUnboundStrategyAccount`, round-robin branch: compute `eligible` as today, then + `const candidates = roundRobinPlacementCandidates(...)` and pass `candidates` to BOTH + `peekRoundRobinAccount` (commit=false, preview) and `pickRoundRobinAccount` (commit=true). Everything + after the pick (shared-active commit, `bindThreadAffinity`, `notePoolRotationSuccess`) is unchanged. + +Why this predicate: `hasCodexQuotaHeadroom` is the score server-side threshold evaluation already uses +for fill-first, reset-first, the priority-tier filter, pin drain and the bound-thread cache-safe +replacement: `computeCodexUsageScore` (hottest known 5h/weekly/30d window, credits cap at 99) against +`getEffectiveCodexAutoSwitchThreshold` (per-account override, use-remaining = 0, else global, default 80). +"At or over" = `usage >= threshold` is not headroom. Threshold 0 = always headroom (switching disabled). +Unknown usage (unprimed) = headroom, same as fill-first and the tier filter. + +Scope/pool interactions: +- Quota scopes (shared / reserve): `eligible` is already scope-filtered (cooldowns per scope) and the ring + is keyed per scope (`codexPoolKeyForScope`). Usage score is the account-level quota for every scope, as + for every other Codex usage decision (quota strategy, fill-first, tier filter). No scope-specific usage + store exists. +- Model detours: `strategySelectionOptionsForModelDetour` narrows `modelEligibleAccountIds` before + eligibility; the headroom filter only narrows that further and falls back to it. +- Priority tiers: `selectPriorityTier` already keeps a tier while any member has headroom; members without + headroom are in that tier only because a sibling has some. The new filter drops them for RR placement. +- Sticky limit: `pickRoundRobinFromState` keeps `activeKey` while it is in the passed list; a sticky + account that crossed the threshold is released and rotation continues over the headroom set. With all + over, the full list returns and sticky behaves as today. + +Not changed (deliberate): +- Bound conversations: RR never re-evaluates a live binding for quota (`reevaluateAffinityQuota` returns + null for non-quota strategies); a binding releases only on exhaustion/cooldown/failure/pause etc. This + change does not touch that path, and a test pins it. +- `pickAlternateCodexAccount` / `peekAlternateCodexAccount` (failover and transient detours): the request is + leaving a failing account, not being placed. Left as-is; preview/resolve agreement there is untouched. +- `listEligibleCodexAccountIds` itself (shared by fill-first/reset-first and failover paths). +- Claude/Anthropic routing. + +Placement after a released binding (account exhausted/cooled) goes through `pickUnboundStrategyAccount` +too, so that re-placement also prefers headroom — which is the cold move we want to land well. + +## Tests (new file tests/codex-integration/codex-round-robin-headroom.test.ts) + +Registered in scripts/test-layout/layout.json and tests/fixtures/test-layout-expected.json. +Three accounts a/b/c, global threshold 80, RR, stickyLimit 1 unless stated. + +1. New placements skip an account at 95% while b/c are at 10%: 6 unbound picks never return a, split 3/3. +2. Exactly at threshold (80) is skipped (>=). +3. All over threshold (90/95/85): unbound picks rotate across all three (old behaviour). +4. Per-account override above usage (a override 99, usage 95) keeps a in rotation. +5. Global threshold 0 keeps a at 95% in rotation. +6. Unknown usage counts as headroom: a=95, b/c unprimed -> never a. +7. Bound conversation stays: thread bound to a at 10%, a rises to 95% -> 20 resolves stay on a. +8. Preview agrees with resolve: previewCodexAccountForRequest(null) equals next resolve and is never a. +9. Reserve scope ring also skips a and does not advance the shared ring. +10. Sticky limit 2 over headroom set: b,b,c,c. + +Regression proof: run the new file against unchanged selection.ts before implementing; record failing tests. + +## Docs + +docs-site (English + fr, ja, ko, ru, tr, zh-cn, zh-tw where the row exists): +- reference/configuration/providers.md `anthropicAccountPool.strategy` and `quotaWindow` rows: exact rule in + "Audit round 1" B3 below. (All 8 locales.) +- guides/claude-code.md quota sentence (en, fr, tr, zh-tw carry it): same correction. +- Codex `autoSwitchThreshold` row ("normal round-robin selection does not use it"), `accountPoolStrategy` row + (round-robin clause) and the Codex strategy table `round-robin` row ("ignores usage thresholds"; en, fr, tr, + zh-tw): new rule — new placements skip accounts at/over their effective threshold while any eligible + account is under it; all over -> plain rotation; bound conversations never move for the threshold. +- getting-started/how-it-works.mdx if it states RR ignores usage (it does not today; check only). + +structure/providers/openai-accounts.md (owner of src/codex routing): add the RR placement rule to the +per-account auto-switch thresholds paragraph (where effective threshold is consumed). + +## Verification + +Focused: new file + codex-pool-rotation, codex-account-threshold-routing, codex-routing, codex-idle-window, +codex-priority-failback, codex-use-remaining-quota, codex-preserve-signed-in, codex-pool-request-owned-main, +codex-auth-context (baseline 502 pass / 1 skip / 0 fail on 6f1d3e65c). +Gates: bun run typecheck, bun run structure:check, bun run privacy:scan, test-layout tests, +bun scripts/test.ts --changed=dev --parallel=1. docs-site build (required, see B4). + +## Risks + +- Existing tests asserting RR rotation onto an over-threshold account would change colour: none found in the + baseline run; any that appears is examined as contract vs incidental. +- Unknown-as-headroom differs from Claude's pickLowestUsage (which filters only when a KNOWN account is under + threshold). Chosen for consistency with Codex fill-first/tier filter; an unprimed account is a better + placement than a known 95% one. + + +## Audit round 1 (Terra, FAIL) — dispositions + +B1 lineage first placement (routing.ts pickLineageServingAccount) — REBUTTED. The lineage pick is not a +round-robin placement: it runs for every strategy, before any strategy pick, and it places a child that has +no binding on the account its PARENT (or a compatible sibling) is being served from right now. The parent is +itself pinned there and, under cache affinity, stays until exhaustion/cooldown/failure; the child following +it keeps the family on one warm prefix, and the whole family moves together at the same release. Applying the +round-robin headroom filter here would split a family onto a cold account to save headroom, which is exactly +the trade the cache-affinity design (#4546) refuses, and it would change quota/fill-first/reset-first behaviour +the brief does not ask for. `lineageServingAccountId` already refuses a serving account that is not selectable, +has an unrecovered quota refusal, or is failover-tripped, so an exhausted parent does not attract children. +Kept unchanged; the docs and PR state that a child of a live conversation follows its parent's account. +(routing.ts is also at 1623/1626 of its file-size cap.) + +B2 docs scope — ACCEPTED. Codex round-robin claims to update: +- en providers.md: autoSwitchThreshold row (126), accountPoolStrategy row (128), strategy table round-robin row (1047). +- fr: rows 58, 60, strategy table 258. tr: rows 58, 60, strategy table 284. zh-tw: rows 54, 56, table 199. +- ja: rows 56, 58, strategy prose 236. ko: rows 56, 58, strategy prose 240. ru: rows 57, 59, prose 268. + zh-cn: rows 56, 58, prose 264. +Claude quota claims to update (all 8 locales): `anthropicAccountPool.strategy` row, and the `quotaWindow` row +sentence that says `quota` ranks eligible candidates directly for new-session assignment; guides/claude-code.md +quota sentence (en, fr, tr, zh-tw). + +B3 Claude wording — ACCEPTED. Accurate rule (anthropic-routing.ts resolveAnthropicAccountForSession): +with a new session and no manual/affinity hit, `quota` keeps a healthy active account while its known usage in +`quotaWindow` is below that account's effective `autoSwitchThreshold` (default 80); unknown usage also keeps it. +It picks the lowest known usage in `quotaWindow` when the active account reaches the threshold, or cannot be used +(paused, reauth, cooling, model-family exhausted, or under `weekly` its 5-hour bar is exhausted). With threshold +`0` a healthy active account is kept and lowest usage is used only when it cannot be used. 429 recovery ranks +replacements by `quotaWindow` directly. + +B4 docs build — ACCEPTED. Required locally: `cd docs-site && bun install --frozen-lockfile && bun run build`; +report honestly if it cannot run. + +Non-blocking notes folded: +- Tests added: sticky batch where the sticky account crosses the threshold mid-batch; re-entry after usage drops; + all-over fallback after a narrowed ring; released-binding re-placement (bound account goes to 100% -> next + placement avoids an over-threshold sibling); failover (pickAlternateCodexAccount) unchanged (may pick an + over-threshold account) as a boundary; model roster (modelEligibleAccountIds) narrowing; priority tier; + terminal short window (short-only 100% = no headroom); credits documented, not separately tested. +- Score wording qualified: hottest KNOWN long window (weekly/30d) refined by an unexpired short window; a + short-only observation is unknown except a terminal (100%) short window; spendable credits cap at 99 only + when credits-after-limit is enabled. +- Regression proof without stash: write the new test file first, run it against unchanged selection.ts, record + the failing tests, then implement. +- structure/: openai-accounts.md (per-account thresholds paragraph) is the owner touched; other src/codex + mapped docs checked for RR-ignores-threshold claims (none found besides openai-tiers' pin note, unaffected). + +## Audit round 2 (Terra, FAIL on one blocker) — dispositions + +R2-B1 Claude rule — ACCEPTED. Replacement rule used by the docs (supersedes the B3 wording above where they differ): +With the pool enabled, a new session without a manual or affinity hit keeps a healthy active account while its +known usage in `quotaWindow` is below that account's effective `autoSwitchThreshold` (default 80); unknown usage +also keeps it. When the active account reaches its threshold or cannot be used (paused, reauth, cooling, +model-family exhausted, or under `weekly` its 5-hour bar is exhausted), `quota` picks a replacement: among +candidates (5-hour-exhausted and model-exhausted ones dropped while others remain) it prefers accounts below their +own effective threshold whenever any account with known usage is below it, then takes the lowest usage in +`quotaWindow`; when every account is at or over its threshold it takes the lowest usage among all. Threshold 0 +keeps a healthy active account. 429 recovery under `quota` uses the same replacement picker. (anthropic-routing.ts +pickLowestUsage ~785-830, resolveAnthropicAccountForSession ~1048-1083.) Docs keep this compact: "keeps the active +account until it reaches autoSwitchThreshold (or cannot serve); then moves to the least-used account, preferring +accounts still under their own threshold". + +R2-N1 lineage — rationale CORRECTED, decision unchanged. The lineage pick precedes strategy selection and gives a +child with no binding the account its parent (or compatible sibling) is serving from now, for the warm family prefix. +Once placed, the child's binding is independent (a later parent move does not drag it). Kept as-is because it is a +strategy-agnostic cache-family hint, not a round-robin placement; documented as an exception ("a child of a live +conversation starts on its parent's account"), with a regression test: parent bound to an over-threshold account, an +under-threshold alternative exists -> the child still starts on the parent's account (boundary pin). + +R2-N2 idle-window — idle-window steering (codexPool.startIdleWindows) precedes round-robin and already requires +hasCodexQuotaHeadroom; docs say "round-robin placements", not "all new placements". diff --git a/docs-site/src/content/docs/fr/guides/claude-code.md b/docs-site/src/content/docs/fr/guides/claude-code.md index d26aaa1530f..3c68aea0926 100644 --- a/docs-site/src/content/docs/fr/guides/claude-code.md +++ b/docs-site/src/content/docs/fr/guides/claude-code.md @@ -15,8 +15,9 @@ ajouter un compte). Par défaut, chaque requête utilise uniquement le compte ** Un groupe de comptes Claude **expérimental et facultatif** (`anthropicAccountPool.enabled`) ajoute l'affinité de session et la sélection des nouvelles sessions basée sur l'usage entre ces comptes OAuth. Il ne contrôle **pas** le basculement sur 429 : dès que deux comptes utilisables sont enregistrés, une requête limitée bascule vers un autre compte que l'option soit activée ou non, et cela ne peut pas être désactivé. Pour les **nouvelles** sessions uniquement, `anthropicAccountPool.strategy` sélectionne un compte éligible : `quota` (par défaut) -choisit la plus faible utilisation connue dans la fenêtre configurée par `anthropicAccountPool.quotaWindow` -(`five-hour` par défaut, `weekly` ou `max-utilization`) lorsqu'elle dépasse `autoSwitchThreshold` ; `round-robin` +conserve le compte actif jusqu'à ce que son utilisation dans la fenêtre définie par +`anthropicAccountPool.quotaWindow` (`five-hour` par défaut, `weekly` ou `max-utilization`) atteigne +`autoSwitchThreshold` (80 par défaut), puis passe au compte le moins utilisé, en privilégiant les comptes encore sous leur propre seuil ; `round-robin` répartit les sessions uniformément (`stickyLimit`, `1` par défaut) ; `fill-first` utilise le compte actif jusqu'à un délai de récupération, une réauthentification ou le seuil, puis passe au suivant. Cette fonction est **désactivée par défaut** et reste expérimentale. diff --git a/docs-site/src/content/docs/fr/reference/configuration/providers.md b/docs-site/src/content/docs/fr/reference/configuration/providers.md index 6b7439f0b0c..c2ba9e8836a 100644 --- a/docs-site/src/content/docs/fr/reference/configuration/providers.md +++ b/docs-site/src/content/docs/fr/reference/configuration/providers.md @@ -55,9 +55,9 @@ Après une inscription ou une connexion OAuth dans l’interface, une boîte de | `activeCodexAccountId?` | `string` | — | Compte de pool sélectionné manuellement pour la prochaine demande. La sélection efface l'affinité des threads ; les demandes en cours conservent les informations d’identification capturées. | | `codexAccountPriorities?` | `Record` | — | Ordre de sélection par compte pour le pool Codex : identifiant de compte → entier de `-100` à `100`, **les valeurs élevées sont prioritaires**, une valeur absente équivaut à `0`. Cette limite porte sur le classement, et non sur l'admissibilité : la sélection retient, parmi les comptes déjà admissibles, le niveau prioritaire le plus élevé qui dispose encore d'une marge de quota, puis `accountPoolStrategy` choisit un compte dans ce niveau. Un niveau est ignoré uniquement lorsque chacun de ses membres atteint son propre seuil effectif non nul (valeur spécifique au compte ou seuil global), est en temporisation, est temporairement évité, est suspendu ou doit être réauthentifié ; un quota inconnu ne suffit jamais à considérer un niveau comme épuisé. L'ordre ne rend jamais admissible un compte qui ne l'est pas et ne réaffecte jamais une tâche déjà liée à un compte. Le compte principal `__main__` participe selon les mêmes règles ; la connexion Codex Desktop peut ainsi être configurée pour être utilisée en dernier. Sans entrée, le pool se comporte exactement comme auparavant. Un mappage mal formé est ignoré avec un avertissement dans la console : l'ordre est désactivé et la configuration n'est pas réparée. Ce champ est géré par `ocx account priority` et la page Codex Auth. | | `activeCodexAccountPinned?` | `string` | — | Identifiant du compte du dernier opérateur sélectionné manuellement. Lorsqu'il est défini, un niveau `codexAccountPriorities` supérieur ne peut pas le préempter jusqu'à ce que la broche soit libérée par drainage, exclusion, suppression ou un failover/promotion explicite. Un mouvement circulaire ordinaire à l’intérieur du niveau plafonné ne le libère pas. L'écriture d'une entrée `codexAccountPriorities` libère également le pin, donc un pin créé avant qu'un ordre n'existe ne peut pas surpasser un ensemble par la suite. `GET /api/codex-auth/active` indique à la fois si le compte effectif est épinglé (`pinned`) et le compte portant le plafond (`pinnedAccountId`). | -| `autoSwitchThreshold?` | `number` | `80` | Seuil d'utilisation pour la commutation proactive. `quota` peut réévaluer les requêtes non liées lors de leur prochaine requête. Les tâches liées conservent leur compte au-delà du seuil par défaut (`pool.cacheAffinity`) jusqu'à ce que ce compte soit épuisé ou ne puisse plus servir, et ne basculent alors que vers un compte dont l'utilisation est strictement inférieure et qui dispose d'une véritable marge de quota. Définissez `pool.cacheAffinity: false` pour réévaluer aussi les tâches liées à ce seuil. `fill-first` ne l'utilise que comme seuil d'évacuation pour l'affectation des requêtes non liées ; la sélection `round-robin` normale ne l'utilise pas. Le score retient la plus élevée des fenêtres de quota connues sur 5 heures, une semaine ou 30 jours. `0` désactive uniquement la commutation proactive fondée sur l'utilisation, pas l'affectation des requêtes non liées ni la récupération après incident. | +| `autoSwitchThreshold?` | `number` | `80` | Seuil d'utilisation pour la commutation proactive. `quota` peut réévaluer les requêtes non liées lors de leur prochaine requête. Les tâches liées conservent leur compte au-delà du seuil par défaut (`pool.cacheAffinity`) jusqu'à ce que ce compte soit épuisé ou ne puisse plus servir, et ne basculent alors que vers un compte dont l'utilisation est strictement inférieure et qui dispose d'une véritable marge de quota. Définissez `pool.cacheAffinity: false` pour réévaluer aussi les tâches liées à ce seuil. `fill-first` ne l'utilise que comme seuil d'évacuation pour l'affectation des requêtes non liées ; `round-robin` ne l'utilise que pour les nouvelles affectations non liées : tant qu'un compte admissible reste sous son seuil effectif, il ignore ceux qui l'atteignent ou le dépassent, sans jamais déplacer une tâche liée pour cette raison. Le score retient la plus élevée des fenêtres de quota connues sur 5 heures, une semaine ou 30 jours. `0` désactive uniquement la commutation proactive fondée sur l'utilisation, pas l'affectation des requêtes non liées ni la récupération après incident. | | `codexAccountAutoSwitchThresholds?` | `Record` | — | Seuils par compte remplaçant `autoSwitchThreshold` : identifiant → entier de `0` à `100`. Une entrée absente hérite du seuil global ; `0` désactive uniquement les déplacements fondés sur l’utilisation depuis ce compte. Le compte principal `__main__` est pris en charge. La carte du compte dans Codex Auth gère cette valeur. Activer la valeur spécifique au compte copie le seuil global actuel dans une valeur fixe. Cette valeur, y compris `0`, reste prioritaire après toute modification du seuil global. La désactiver envoie `threshold: null`, supprime l'entrée et rétablit l'héritage du seuil global actuel et de ses modifications futures. | -| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | Stratégie d'affectation des requêtes Codex nouvelles ou non liées. Une requête est non liée lorsqu'elle ne possède aucune affinité active, définie par l'identifiant de la tâche parente et la portée du quota ; une tâche existante visible peut perdre son lien après le redémarrage du proxy ou la réinitialisation de l'affinité. `quota` sélectionne le compte admissible le moins utilisé lorsqu'aucun compte actif n'existe, conserve un compte actif admissible sous `autoSwitchThreshold` et, une fois le seuil franchi, peut déplacer une requête non liée. Les tâches liées suivent `pool.cacheAffinity` (activé par défaut) : elles restent jusqu'à ce que le compte soit épuisé (utilisation connue à 100 %) ou ne puisse plus servir, et ne se relient alors qu'à un compte dont l'utilisation est strictement inférieure et qui dispose d'une véritable marge de quota. Définissez le drapeau à `false` pour relier de manière proactive une tâche liée à un compte admissible moins utilisé au seuil, toujours sous la même contrainte de destination. `round-robin` répartit équitablement les requêtes non liées ; `fill-first` continue de les attribuer au compte actif jusqu'à sa temporisation, son indisponibilité ou le seuil d'évacuation configuré. `reset-first`: Parmi les comptes sous le seuil, privilégier le prochain reset de 5 heures ou hebdomadaire. Les tâches liées suivent la politique d’affinité configurée. Les quotas de modèles indépendants suivent l’ordre de consommation. Les resets mensuels ne déterminent pas cet ordre. | +| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | Stratégie d'affectation des requêtes Codex nouvelles ou non liées. Une requête est non liée lorsqu'elle ne possède aucune affinité active, définie par l'identifiant de la tâche parente et la portée du quota ; une tâche existante visible peut perdre son lien après le redémarrage du proxy ou la réinitialisation de l'affinité. `quota` sélectionne le compte admissible le moins utilisé lorsqu'aucun compte actif n'existe, conserve un compte actif admissible sous `autoSwitchThreshold` et, une fois le seuil franchi, peut déplacer une requête non liée. Les tâches liées suivent `pool.cacheAffinity` (activé par défaut) : elles restent jusqu'à ce que le compte soit épuisé (utilisation connue à 100 %) ou ne puisse plus servir, et ne se relient alors qu'à un compte dont l'utilisation est strictement inférieure et qui dispose d'une véritable marge de quota. Définissez le drapeau à `false` pour relier de manière proactive une tâche liée à un compte admissible moins utilisé au seuil, toujours sous la même contrainte de destination. `round-robin` répartit équitablement les requêtes non liées entre les comptes admissibles sous leur `autoSwitchThreshold` effectif, ou entre tous les comptes admissibles s'ils ont tous atteint ou dépassé leur seuil ; `fill-first` continue de les attribuer au compte actif jusqu'à sa temporisation, son indisponibilité ou le seuil d'évacuation configuré. `reset-first`: Parmi les comptes sous le seuil, privilégier le prochain reset de 5 heures ou hebdomadaire. Les tâches liées suivent la politique d’affinité configurée. Les quotas de modèles indépendants suivent l’ordre de consommation. Les resets mensuels ne déterminent pas cet ordre. | | `pool.cacheAffinity?` | `boolean` | `true` | Ordre d'affinité de cache pour les threads Codex liés, indépendant de `pool.kernel`. Activé par défaut ; omettre la clé ou la définir à `true` conserve la liaison, et une valeur autre que `false` est lue comme activée. Une liaison active prime sur la marge de quota : `quota` ne déplace pas le thread simplement parce que l'utilisation a franchi `autoSwitchThreshold`, car déplacer une conversation liée jette le cache d'invites isolé par compte. Le thread quitte encore le compte s'il ne peut plus servir — suspendu, inutilisable, exclu du plan, identifiants invalides, génération remplacée, TTL expiré, refus de quota 429/402, ou réellement épuisé (utilisation connue à 100 %) — et seulement vers un compte dont l'utilisation est strictement inférieure et qui dispose d'une véritable marge de quota. Un compte dont l'utilisation est inconnue n'est jamais choisi comme destination d'une tâche liée. Si tous les comptes dépassent le seuil, la tâche liée reste, car aucune destination n'est meilleure. Définissez `false` pour rétablir la réaffectation au seuil, toujours sous la même contrainte de destination. L'affinité est un réordonnancement, pas un verrouillage. | | `accountPoolStickyLimit?` | `number` | `1` | Nombre d'affectations de tâches nouvelles ou non liées conservées sur une même sélection tournante avant de passer à la suivante ; le compteur avance lorsqu'une tâche est liée, et non après une réponse réussie en amont. Plage : 1–100. | | `upstreamFailoverThreshold?` | `number` | `3` | Nombre d'échecs transitoires consécutifs avant le basculement des futures nouvelles sessions. Réglez `0` pour désactiver ce mécanisme. Pour les requêtes Responses ordinaires et les envois compacts natifs, les échecs avérés d'accessibilité DNS/TCP avant connexion sont suivis au niveau du couple fournisseur-hôte : ils n'affectent jamais l'état ni la temporisation du compte, l'affinité de tâche ou de session, la sélection du compte actif ou le routage du pool, et ne sont jamais comptabilisés dans ce seuil. | @@ -255,7 +255,7 @@ et suspend uniquement ceux dont l'utilisation vient d'être confirmée à 100 % | Stratégie | Comportement | | --- | --- | | `quota` (par défaut) | S'il n'existe aucun compte actif, choisir le compte admissible le moins utilisé selon les fenêtres de 5 heures, d'une semaine et de 30 jours. Sinon, conserver un compte actif admissible sous `autoSwitchThreshold` ; une fois le seuil franchi, une requête non liée peut être déplacée vers un compte admissible moins utilisé. Les tâches liées conservent l'affinité de cache par défaut et restent jusqu'à ce que le compte soit épuisé (utilisation connue à 100 %) ou ne puisse plus servir (suspendu, inutilisable) ; un déplacement exige alors une véritable marge de quota et une utilisation strictement inférieure sur la destination. Définissez `pool.cacheAffinity: false` pour laisser la requête suivante d'une tâche liée bouger au seuil, toujours vers un compte admissible moins utilisé disposant d'une véritable marge de quota. `0` désactive cette réévaluation fondée sur l'utilisation, mais pas la récupération après incident. | -| `round-robin` | Répartit uniformément les requêtes non liées entre les comptes admissibles. La rotation repose sur un compteur et ignore les seuils, mais le filtre commun des niveaux de priorité évalue toujours la marge de chaque compte selon son seuil effectif (valeur spécifique au compte ou seuil global). `accountPoolStickyLimit` (1–100) compte les affectations effectuées avec une même sélection, et non les réponses réussies en amont. | +| `round-robin` | La rotation repose sur un compteur. Une nouvelle affectation ignore les comptes ayant atteint leur `autoSwitchThreshold` effectif (valeur du compte ou seuil global, évalué comme pour `quota`) tant qu'un compte admissible reste en dessous ; une utilisation inconnue ou un seuil de `0` compte comme inférieur. Si tous les comptes admissibles ont atteint leur seuil, la rotation les inclut tous. Une tâche liée conserve son compte au-delà du seuil et ne change que s'il ne peut plus servir (temporisation, refus de quota, basculement ou pause) ; l'enfant d'une conversation active commence sur le compte utilisé par son parent. Le filtre commun des niveaux de priorité évalue la marge de la même façon. Une sélection manuelle de l'opérateur prend le placement suivant dans chaque portée de quota, quelle que soit son utilisation ; une requête réussie sur ce compte dans cette portée consomme la sélection, puis les placements suivants y appliquent à nouveau le seuil. `accountPoolStickyLimit` (1–100) compte les affectations effectuées avec une même sélection, et non les réponses réussies en amont. | | `fill-first` | Attribue les requêtes non liées au compte actif jusqu'à sa temporisation, sa réauthentification ou le seuil d'évacuation effectif de ce compte (valeur spécifique au compte ou seuil global) ; une utilisation inconnue n'impose pas de changement. Les tâches liées et saines conservent leur affinité. | La rotation ne protège pas contre l’application des règles par les fournisseurs ; l'utilisation de plusieurs comptes peut enfreindre les conditions du fournisseur. @@ -269,9 +269,9 @@ rotation automatique peut déclencher des restrictions du fournisseur. | Clé | Type | Par défaut | Description | | --- | --- | --- | --- | | `anthropicAccountPool.enabled?` | `boolean` | `false` | Active l'affinité de session persistante et la sélection des nouvelles sessions basée sur l'usage. **Le basculement sur 429 n'est pas contrôlé ici** : il s'active dès que deux comptes utilisables sont enregistrés, comme pour tout autre fournisseur multi-identifiants, et ne peut pas être désactivé. | -| `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` | Pour les nouvelles sessions, lorsque le compte actif atteint ce seuil, choisir la plus faible utilisation connue et mise en cache dans la fenêtre configurée. `0` désactive la sélection selon le quota. | -| `anthropicAccountPool.strategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` | Stratégie des nouvelles sessions ; `quota` classe les comptes selon la fenêtre définie par `quotaWindow`, par défaut les barres sur 5 heures, et `fill-first` évalue son seuil d'évacuation dans cette même fenêtre. | -| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` | Barre d'utilisation signalée par le fournisseur, mise en cache et utilisée pour la sélection selon l'utilisation. `five-hour` conserve le comportement actuel. `weekly` utilise la barre hebdomadaire et ignore les comptes dont la barre sur 5 heures est épuisée tant qu'un autre compte admissible reste disponible, mais y revient si aucun autre ne reste. `max-utilization` utilise la valeur connue la plus élevée et peut donc employer la barre sur 5 heures avant que la barre hebdomadaire soit disponible ; si aucune n'est connue, le compte suit l'ordre des utilisations inconnues. Les utilisations connues précèdent les inconnues, mais si tous les comptes admissibles sont inconnus, la sélection en renvoie tout de même un dans leur ordre admissible. Après le départage documenté par la plus faible utilisation sur 5 heures, une égalité exacte conserve cet ordre. Une session saine avec affinité n'est pas rééquilibrée de manière proactive. Pour l'affectation des nouvelles sessions et la reprise du routage après un remplacement admissible à la suite d'un 429, `quota` classe directement les candidats admissibles avec cette fenêtre ; `fill-first` avance dans un ordre stable selon le seuil et les règles d'épuisement de cette fenêtre ; `round-robin` l'ignore. Le délai de récupération, les limites de basculement et l'éligibilité de réauthentification restent des états locaux distincts. Les barres hebdomadaires ne sont connues qu'après leur interrogation dans la page Fournisseurs du tableau de bord. | +| `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` | Pour les nouvelles sessions, lorsque le compte actif atteint ce seuil, choisir le compte dont l'utilisation connue en cache est la plus faible dans la fenêtre configurée, en privilégiant les comptes encore sous leur propre seuil ; le compte choisi n'a pas lui-même à atteindre ce seuil. `0` désactive uniquement la commutation proactive selon l'utilisation ; la sélection d'une nouvelle session et la reprise après un 429 admissible consultent toujours `quotaWindow`. | +| `anthropicAccountPool.strategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` | Stratégie des nouvelles sessions. `quota` conserve le compte actif jusqu'à ce que son utilisation dans `quotaWindow` atteigne son `autoSwitchThreshold` effectif (80 par défaut) ou qu'il ne puisse plus servir, puis choisit le compte le moins utilisé en privilégiant ceux sous leur propre seuil ; une utilisation inconnue conserve le compte actif. `round-robin` alterne les nouvelles sessions sans consulter les seuils d'utilisation. `fill-first` évalue son seuil d'évacuation dans `quotaWindow`. | +| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` | Barre d'utilisation signalée par le fournisseur, mise en cache et utilisée pour la sélection selon l'utilisation. `five-hour` conserve le comportement actuel. `weekly` utilise la barre hebdomadaire et ignore les comptes dont la barre sur 5 heures est épuisée tant qu'un autre compte admissible reste disponible, mais y revient si aucun autre ne reste. `max-utilization` utilise la valeur connue la plus élevée et peut donc employer la barre sur 5 heures avant que la barre hebdomadaire soit disponible ; si aucune n'est connue, le compte suit l'ordre des utilisations inconnues. Les utilisations connues précèdent les inconnues, mais si tous les comptes admissibles sont inconnus, la sélection en renvoie tout de même un dans leur ordre admissible. Après le départage documenté par la plus faible utilisation sur 5 heures, une égalité exacte conserve cet ordre. Une session saine avec affinité n'est pas rééquilibrée de manière proactive. Lorsque `quota` choisit un remplacement (nouvelle session dont le compte actif a atteint son seuil ou ne peut plus servir, ou reprise après un 429 admissible), il privilégie les candidats sous leur propre seuil et les classe avec cette fenêtre ; `fill-first` avance dans un ordre stable selon le seuil et les règles d'épuisement de cette fenêtre ; `round-robin` l'ignore. Le délai de récupération, les limites de basculement et l'éligibilité de réauthentification restent des états locaux distincts. Les barres hebdomadaires de chaque compte proviennent des sondages d'utilisation ou des en-têtes de réponse observés. | | `anthropicAccountPool.stickyLimit?` | `number` | `1` | Liaisons de nouvelle session réussies conservées sur une sélection à tour de rôle. Portée 1–100. | Seul un 429 confirmant le rejet d'un quota partagé de cinq heures ou hebdomadaire déclenche la temporisation et le basculement du compte. Une limitation temporaire suspend son admission en conservant l'affinité : au plus un bref nouvel essai sur le même compte et un détour vers un autre compte admissible par requête. Sans en-tête probant, un 429 permet un seul bref nouvel essai sur le même compte, sans refroidir le compte ni inventer Retry-After. Le comportement par défaut avec un seul compte reste identique. Un rejet propre à Fable laisse Sonnet admissible ; choix manuel et affinité vérifient aussi les quotas partagés et ceux de la famille demandée. Les observations passives de famille expirent après trente minutes ou à leur réinitialisation connue et sont revalidées par une seule requête à la fois. Les seuils restent des préférences souples avec le repli existant lorsque tous les candidats sont épuisés, sans plafond strict d'utilisation ou de facturation. L'affinité est locale au processus et de taille bornée. Les erreurs de renouvellement du jeton suivent les règles de réauthentification existantes. Un 403 confirmé lié à un abonnement ou à la facturation du compte permet un basculement avant la sortie, avec une temporisation selon `Retry-After` ou de dix minutes par défaut. Un refus d’autorisation ordinaire ne déclenche pas de basculement. Si tous les comptes admissibles sont en temporisation, les clients reçoivent un 429 accompagné de diff --git a/docs-site/src/content/docs/guides/claude-code.md b/docs-site/src/content/docs/guides/claude-code.md index e9ef9a8e281..169e401349c 100644 --- a/docs-site/src/content/docs/guides/claude-code.md +++ b/docs-site/src/content/docs/guides/claude-code.md @@ -88,9 +88,9 @@ session affinity and usage-aware new-session selection across those OAuth accoun to another account whether the pool is on or off, and the toggle does not switch that off; pause an account to keep it out of failover. For **new** sessions, -`anthropicAccountPool.strategy` selects among eligible accounts: `quota` (default) picks the -lowest known usage in the window set by `quotaWindow` (`five-hour` by default, or `weekly` / -`max-utilization`) when above `autoSwitchThreshold`; `round-robin` spreads evenly +`anthropicAccountPool.strategy` selects among eligible accounts: `quota` (default) keeps the active account until its usage in the window set by `quotaWindow` +(`five-hour` by default, or `weekly` / `max-utilization`) reaches `autoSwitchThreshold` +(default 80), then moves to the least-used account, preferring accounts still under their own threshold; `round-robin` spreads evenly (`stickyLimit`, default `1`); `fill-first` drains the active account until cooldown, reauthentication, or threshold, then advances. It is **off by default** and experimental. diff --git a/docs-site/src/content/docs/ja/reference/configuration/providers.md b/docs-site/src/content/docs/ja/reference/configuration/providers.md index 7ecffe3764a..3e9e5085980 100644 --- a/docs-site/src/content/docs/ja/reference/configuration/providers.md +++ b/docs-site/src/content/docs/ja/reference/configuration/providers.md @@ -53,9 +53,9 @@ GUI で登録または OAuth ログインが完了すると、Models ページ | `codexAccountPickerEnabled?` | `boolean` | map が空なら off | 有効な `codexAccountNamespaces` mapping から account-qualified Codex picker row を生成するかを制御します。`true` は mapping された行の表示を許可します。空でない map で省略した場合は後方互換性のため有効として扱われ、map が空なら off です。`false` は mapping を削除せず、明示的な `/` routing も無効にせずに、生成行を非表示にして picker の bare native 行を復元します。 | | `activeCodexAccountId?` | `string` | — |次のリクエスト用に手動で選択されたプール アカウント。選択するとスレッドのアフィニティがクリアされます。実行中のリクエストでは、取得された資格情報が保持されます。 | | `codexAccountPriorities?` | `Record` | — | Codex pool のアカウント別選択順。アカウント ID → `-100` から `100` の整数で、**大きいほど先に使われ**、未設定は `0` です。これは eligibility ではなく順序の境界です。選択は適格なアカウントを、まだ quota に余裕がある最上位 tier に絞り込み、その tier の中を `accountPoolStrategy` が選びます。tier が飛ばされるのは、そのメンバー全員が自身の 0 以外の実効しきい値(アカウント別上書き、未設定ならグローバル値)以上、cooldown 中、soft-avoid、一時停止、または再認証待ちのときだけで、usage 不明が tier を drain させることはありません。順序付けが不適格なアカウントを選択可能にすることはなく、すでにアカウントが結び付いた thread を再 bind することもありません。メインの `__main__` も同じ条件で参加するため、Codex Desktop ログインを最後に使わせられます。エントリが 1 つもなければ挙動は従来どおりです。map が不正な場合は警告を出して順序付けを無効にします(config の修復処理は走りません)。`ocx account priority` と Codex Auth ページで管理します。 | -| `autoSwitchThreshold?` | `number` | `80` | 使用量ベースのプロアクティブ切り替えしきい値。`quota` は未紐付けタスクの次のリクエストを再評価できます。紐付け済みタスクは既定(`pool.cacheAffinity`)ではしきい値を超えても同じアカウントを維持し、アカウントが使い切られるか処理できなくなったときだけ離れ、その場合も実際に quota 余裕があり usage がより低いアカウントへだけ移ります。`pool.cacheAffinity: false` にするとしきい値で紐付け済みタスクも再評価します。`fill-first` は未紐付け割り当ての使い切り基準としてのみ使用し、通常の `round-robin` 選択は使用しません。既知の 5 時間、週次、30 日 quota window の最大スコアを使います。`0` は使用量ベースの切り替えだけを無効にし、未紐付け割り当てや障害回復は無効にしません。 | +| `autoSwitchThreshold?` | `number` | `80` | 使用量ベースのプロアクティブ切り替えしきい値。`quota` は未紐付けタスクの次のリクエストを再評価できます。紐付け済みタスクは既定(`pool.cacheAffinity`)ではしきい値を超えても同じアカウントを維持し、アカウントが使い切られるか処理できなくなったときだけ離れ、その場合も実際に quota 余裕があり usage がより低いアカウントへだけ移ります。`pool.cacheAffinity: false` にするとしきい値で紐付け済みタスクも再評価します。`fill-first` は未紐付け割り当ての使い切り基準としてのみ使用し、`round-robin` は新規/未紐付けの割り当て時にのみ使用し、しきい値未満の適格アカウントがある間は実効しきい値以上のアカウントを除外し、この理由で紐付け済みタスクを移動しません。既知の 5 時間、週次、30 日 quota window の最大スコアを使います。`0` は使用量ベースの切り替えだけを無効にし、未紐付け割り当てや障害回復は無効にしません。 | | `codexAccountAutoSwitchThresholds?` | `Record` | — | `autoSwitchThreshold` のアカウント別上書き(アカウント ID → `0`〜`100` の整数)。未設定はグローバル値を継承し、`0` はそのアカウントからの使用量ベース切り替えだけを無効にします。メインの `__main__` も指定できます。Codex Auth の各アカウントカードで管理します。 上書きを有効にすると、現在のグローバルしきい値が固定のアカウント別値としてコピーされます。`0` を含む上書き値は、その後グローバル値が変更されても優先されます。無効にすると `threshold: null` を送信してエントリを削除し、現在のグローバルしきい値と今後の変更を継承する状態に戻ります。 | -| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | 新規/未紐付け Codex リクエストの割り当て戦略。live な `(parent thread id, quota scope)` affinity がなければ未紐付けで、プロキシ再起動や affinity リセット後は既存の表示タスクも未紐付けになり得ます。`quota` はアクティブアカウントがなければ既知 usage 最小の適格アカウントを選び、適格なアクティブアカウントが `autoSwitchThreshold` 未満なら維持します。しきい値到達後は未紐付けリクエストを移せます。紐付け済みタスクは既定ではアカウントが使い切られるか(既知 usage 100%)処理できなくなるまで維持され、離れるときは実際に quota 余裕があり usage がより低いアカウントへだけ移ります。フラグをオフにすると、しきい値で紐付け済みタスクの次のリクエストも実際に quota 余裕があり usage がより低い適格アカウントへ移せます。`round-robin` は未紐付けリクエストを均等分散し、`fill-first` は cooldown、使用不可、または drain threshold までアクティブアカウントへ割り当てます。 `reset-first`: 使用率のしきい値未満から、次の5時間枠または週次枠のリセットが最も近いアカウントを選びます。紐付け済みタスクは設定されたアフィニティ方針に従います。独立したモデル枠は使用率順です。 月次リセットはこの順序に使用しません。 | +| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | 新規/未紐付け Codex リクエストの割り当て戦略。live な `(parent thread id, quota scope)` affinity がなければ未紐付けで、プロキシ再起動や affinity リセット後は既存の表示タスクも未紐付けになり得ます。`quota` はアクティブアカウントがなければ既知 usage 最小の適格アカウントを選び、適格なアクティブアカウントが `autoSwitchThreshold` 未満なら維持します。しきい値到達後は未紐付けリクエストを移せます。紐付け済みタスクは既定ではアカウントが使い切られるか(既知 usage 100%)処理できなくなるまで維持され、離れるときは実際に quota 余裕があり usage がより低いアカウントへだけ移ります。フラグをオフにすると、しきい値で紐付け済みタスクの次のリクエストも実際に quota 余裕があり usage がより低い適格アカウントへ移せます。`round-robin` は実効 `autoSwitchThreshold` 未満の適格アカウントに未紐付けリクエストを均等分散し、全員がしきい値以上なら全適格アカウントに分散し、`fill-first` は cooldown、使用不可、または drain threshold までアクティブアカウントへ割り当てます。 `reset-first`: 使用率のしきい値未満から、次の5時間枠または週次枠のリセットが最も近いアカウントを選びます。紐付け済みタスクは設定されたアフィニティ方針に従います。独立したモデル枠は使用率順です。 月次リセットはこの順序に使用しません。 | | `pool.cacheAffinity?` | `boolean` | `true` | 紐付け済み Codex スレッド向けの cache-affinity 順序。`pool.kernel` とは独立で、既定はオンです。不正な値はオンとして読みます。live な紐付けが quota 余裕より優先され、`quota` は使用量が `autoSwitchThreshold` を超えたという理由だけではスレッドを移しません。一時停止、使用不可、または実際に使い切られたアカウント(既知 usage 100%)では離れますが、実際に quota 余裕があり usage がより低いアカウントへだけ移ります。`false` にするとしきい値での再紐付けに戻ります。affinity は固定ではなく並べ替えです。 | | `accountPoolStickyLimit?` | `number` | `1` | 1 回の round-robin 選択で次へ進む前に保持する新規/未紐付けタスク割り当て数。カウンターは上流の成功後ではなくタスクの紐付け時に増えます。範囲 1–100。`accountPoolStrategy` が `round-robin` のときのみ。 | | `upstreamFailoverThreshold?` | `number` | `3` |今後の新しいセッションがフェイルオーバーする前に一時的なエラーが連続して発生する。 `0` を無効に設定します。通常のResponses送信とネイティブcompact送信では、実証済みの接続前DNS/TCP到達不能障害はprovider-host単位で記録され、アカウントの健全性、アカウントのクールダウン、スレッド/セッションの親和性、アクティブアカウントの選択、Poolルーティングには影響せず、この閾値にもカウントされません。 | @@ -233,8 +233,7 @@ pause、cooldown、再認証、障害処理も独立して routing を消去ま 別の適格な Pool アカウントへリクエストを切り替えることがあります。これらの障害回復は `autoSwitchThreshold: 0` でも有効であり、`0` が無効にするのは使用量に基づく予防的な切り替えだけです。 -**割り当てとプロアクティブ切り替え戦略:** `quota`(既定)はアクティブアカウントがない場合に最小 usage の適格アカウントを選び、適格なアクティブアカウントが `autoSwitchThreshold` 未満なら維持します。`autoSwitchThreshold` 超過後は未紐付けリクエストを移せます。既定では cache affinity が quota 余裕より優先され、紐付け済みタスクはアカウントが使い切られるか(既知 usage 100%)処理できなくなるまで維持され、離れるときは実際に quota 余裕があり usage がより低いアカウントへだけ移ります。usage が不明なアカウントは紐付け済みタスクの移動先にはならず、すべてのアカウントがしきい値を超えていればそのまま残ります。フラグをオフにすると紐付け済みタスクの次のリクエストもしきい値で再紐付けできますが、その場合も実際に quota 余裕があり usage がより低いアカウントへだけ移ります。`round-robin` は -未紐付けリクエストを均等分散し、しきい値は通常の rotation を変えません。`accountPoolStickyLimit` +**割り当てとプロアクティブ切り替え戦略:** `quota`(既定)はアクティブアカウントがない場合に最小 usage の適格アカウントを選び、適格なアクティブアカウントが `autoSwitchThreshold` 未満なら維持します。`autoSwitchThreshold` 超過後は未紐付けリクエストを移せます。既定では cache affinity が quota 余裕より優先され、紐付け済みタスクはアカウントが使い切られるか(既知 usage 100%)処理できなくなるまで維持され、離れるときは実際に quota 余裕があり usage がより低いアカウントへだけ移ります。usage が不明なアカウントは紐付け済みタスクの移動先にはならず、すべてのアカウントがしきい値を超えていればそのまま残ります。フラグをオフにすると紐付け済みタスクの次のリクエストもしきい値で再紐付けできますが、その場合も実際に quota 余裕があり usage がより低いアカウントへだけ移ります。`round-robin`:rotationはカウンター方式です。新規割り当てでは実効 `autoSwitchThreshold`(アカウント別上書きまたはグローバル既定値、`quota` と同じスコア)未満の適格アカウントがある間、しきい値以上のアカウントを除外します。使用量不明またはしきい値 `0` は未満として扱い、全適格アカウントがしきい値以上なら全員で順番に回します。紐付け済みタスクはしきい値を超えても維持し、処理不能(cooldown、quota 拒否、failover、pause)の場合のみ移動します。live な会話の子は親が使用中のアカウントから始まります。共通の優先度階層フィルターも同じ方法で余裕を評価します。オペレーターの手動選択は、使用量にかかわらず各 quota スコープの次の配置を取ります。そのスコープでそのアカウントへのリクエストが成功すると選択は消費され、以後の配置では再びしきい値が適用されます。`accountPoolStickyLimit` (既定 `1`、1–100)は成功応答ではなく割り当て/紐付け数を数えます。`fill-first` は未紐付けリクエストを cooldown、再認証、またはそのアカウントの実効 drain threshold(アカウント別上書き、未設定ならグローバル値)までアクティブアカウントへ割り当て、正常な紐付け済みタスクは affinity を維持します。これらの戦略は provider enforcement を回避しません。 @@ -246,9 +245,9 @@ affinity を維持します。これらの戦略は provider enforcement を回 |キー |タイプ |デフォルト |説明 | | --- | --- | --- | --- | | `anthropicAccountPool.enabled?` | `boolean` | `false` | スティッキー セッション アフィニティと使用量に基づく新規セッション選択を有効にします。**429 フェイルオーバーはここでは制御しません**: 使用可能なアカウントが 2 つ以上あれば他の複数資格情報プロバイダーと同様に有効になり、無効にはできません。 | -| `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` |新しいセッションでは、アクティブなアカウントがこのしきい値に達すると、設定した期間で既知のキャッシュ使用量が最も低いアカウントを選択します。 `0` はクォータ選択を無効にします。 | -| `anthropicAccountPool.strategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` |新しいセッション戦略。`quota` は `quotaWindow` で指定した期間(既定は 5 時間足)でアカウントを順位付けし、`fill-first` も同じ期間で使い切りのしきい値を判定します。 | -| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` |使用量ベースのアカウント選択で使う、プロバイダー報告のキャッシュ済み使用率です。`five-hour` は従来の動作を維持します。`weekly` は週次使用量を使い、他に対象アカウントが残る間だけ 5 時間使用量が上限に達したアカウントを除外し、残らない場合はそれらへフォールバックします。`max-utilization` は判明している値のうち最も高いものを使うため、週次使用量が未取得でも 5 時間使用量を利用できます。どちらも不明なら unknown の順位付けに従います。既知の使用量は unknown より先ですが、対象がすべて unknown でも対象順の先頭を選択します。記載した 5 時間使用量による同点判定後も完全に同点なら、対象順を維持します。正常な affinity セッションを先回りして再配置することはありません。新規セッションの割り当てと、対象となる 429 代替後のルーティング復旧では、`quota` はこの期間で対象候補を直接順位付けし、`fill-first` はこの期間のしきい値と上限到達ルールを使って安定順に進み、`round-robin` はこの設定を無視します。クールダウン、フェイルオーバー上限、再認証の適格性は別のローカル状態です。アカウント別の週次使用量は、ダッシュボードのプロバイダーページで取得した後にのみ利用できます。 | +| `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` | 新規セッションでは、アクティブアカウントがこのしきい値に達すると、設定した期間の既知のキャッシュ済み使用量が最小のアカウントを選びます(自身のしきい値未満のアカウントを優先します)。選択先自体がしきい値以上である必要はありません。`0` は使用量ベースの先行切り替えのみを無効にし、新規セッションの選択と対象となる 429 後の復旧では引き続き `quotaWindow` を参照します。 | +| `anthropicAccountPool.strategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` | 新規セッション戦略。`quota` は `quotaWindow` の使用量が実効 `autoSwitchThreshold`(既定 80)に達するか処理不能になるまでアクティブアカウントを維持し、その後は自身のしきい値未満のアカウントを優先して最小使用量へ移ります。使用量不明なら維持します。`round-robin` は使用量のしきい値を参照せず新規セッションをローテーションします。`fill-first` は `quotaWindow` で使い切りしきい値を判定します。 | +| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` |使用量ベースのアカウント選択で使う、プロバイダー報告のキャッシュ済み使用率です。`five-hour` は従来の動作を維持します。`weekly` は週次使用量を使い、他に対象アカウントが残る間だけ 5 時間使用量が上限に達したアカウントを除外し、残らない場合はそれらへフォールバックします。`max-utilization` は判明している値のうち最も高いものを使うため、週次使用量が未取得でも 5 時間使用量を利用できます。どちらも不明なら unknown の順位付けに従います。既知の使用量は unknown より先ですが、対象がすべて unknown でも対象順の先頭を選択します。記載した 5 時間使用量による同点判定後も完全に同点なら、対象順を維持します。正常な affinity セッションを先回りして再配置することはありません。`quota` が代替を選ぶとき(アクティブアカウントがしきい値に達したか処理不能な新規セッション、または対象となる 429 後の復旧)、自身のしきい値未満の候補を優先し、この期間で順位付けし、`fill-first` はこの期間のしきい値と上限到達ルールを使って安定順に進み、`round-robin` はこの設定を無視します。クールダウン、フェイルオーバー上限、再認証の適格性は別のローカル状態です。アカウント別の週次使用量は、使用量プローブまたは観測したレスポンスヘッダーから取得します。 | | `anthropicAccountPool.stickyLimit?` | `number` | `1` |成功した新しいセッションのバインドは 1 つのラウンドロビン選択で保持されます。範囲は 1 ~ 100。 | 共有の5時間・週次クォータが拒否された429だけがアカウントのクールダウンと切り替えを行います。一時的な速度制限はアフィニティを維持して送信受付だけを停止し、リクエストごとに短い同一アカウント再試行1回と別の対象アカウントへの切り替え1回までです。根拠ヘッダーのない429は同一アカウントで1回だけ再試行し、アカウントを冷却せず、Retry-Afterも生成しません。既定の単一アカウント動作は変わりません。Fable専用の拒否はSonnetを制限しません。手動選択とアフィニティもリクエストモデルの共有・ファミリークォータを確認します。パッシブなファミリー情報は30分または既知のリセットで期限切れとなり、1つの送信リクエストで再確認します。使用量しきい値はソフトな優先設定で、全候補消耗時のフォールバックを維持します。使用量・課金のハード上限ではありません。アフィニティはプロセスローカルであり、サイズ制限があります。トークン更新の失敗は既存の再認証ルールに従います。確認済みの契約・アカウント請求の 403 は出力前に別アカウントへ切り替え、`Retry-After` または既定の10分間のクールダウンを記録します。一般的な権限拒否では切り替えません。すべての対象となるアカウントが冷却されている場合、クライアントは、既知の場合、認証エラーではなく、`Retry-After` を含む 429 を受け取ります。 diff --git a/docs-site/src/content/docs/ko/reference/configuration/providers.md b/docs-site/src/content/docs/ko/reference/configuration/providers.md index 6102a5442e6..4dfefc64d14 100644 --- a/docs-site/src/content/docs/ko/reference/configuration/providers.md +++ b/docs-site/src/content/docs/ko/reference/configuration/providers.md @@ -53,9 +53,9 @@ GUI에서 등록이나 OAuth 로그인을 마치면 Models 페이지로 이동 | `codexAccountPickerEnabled?` | `boolean` | map이 비어 있으면 꺼짐 | 유효한 `codexAccountNamespaces` 매핑에서 account-qualified Codex 선택기 행을 생성할지 제어합니다. `true`는 매핑된 행의 표시를 허용합니다. 비어 있지 않은 map에서 생략하면 이전 버전과의 호환성을 위해 활성화된 것으로 취급되며, map이 비어 있으면 꺼집니다. `false`는 매핑을 삭제하거나 명시적 `/` 라우팅을 비활성화하지 않은 채 생성 행을 숨기고 선택기에 bare native 행을 복원합니다. | | `activeCodexAccountId?` | `string` | — | 다음 요청에 수동으로 선택한 Pool 계정입니다. 선택하면 thread 결속이 해제되며, 진행 중인 요청은 캡처한 자격 증명을 유지합니다. | | `codexAccountPriorities?` | `Record` | — | Codex pool의 계정별 선택 순서. 계정 ID → `-100`부터 `100`까지의 정수이며 **값이 클수록 먼저** 쓰이고, 항목이 없으면 `0`입니다. 이는 eligibility 경계가 아니라 순서 경계입니다. 선택은 이미 적격한 계정들을 quota 여유가 남은 최상위 tier로 좁히고, 그 tier 안에서 `accountPoolStrategy`가 계정을 고릅니다. tier를 건너뛰는 경우는 그 구성원 전부가 자신의 0이 아닌 유효 임계값(계정별 재정의 또는 전역 기본값) 이상, cooldown, soft-avoid, 일시 중지 또는 재인증 대기일 때뿐이며, usage를 알 수 없다고 해서 tier가 소진되지는 않습니다. 순서는 부적격 계정을 선택 가능하게 만들지 않고, 이미 계정에 묶인 thread를 다시 bind하지도 않습니다. 메인 `__main__` 계정도 동일한 조건으로 참여하므로 Codex Desktop 로그인을 마지막에 쓰도록 둘 수 있습니다. 항목이 하나도 없으면 동작은 이전과 같습니다. map이 잘못된 경우 경고를 출력하고 순서 지정을 끕니다(config 복구는 하지 않습니다). `ocx account priority`와 Codex Auth 페이지에서 관리합니다. | -| `autoSwitchThreshold?` | `number` | `80` | 사용량 기반 선제 전환 임계값입니다. `quota`는 바인딩 없는 작업의 다음 요청을 재평가할 수 있습니다. 바인딩된 작업은 기본값(`pool.cacheAffinity`)에서 이 임계값을 넘어도 계정을 유지하며, 해당 계정이 소진되었거나 더 이상 처리할 수 없을 때에만 떠나고, 그때도 실제 quota 여유가 있고 usage가 더 낮은 계정으로만 옮깁니다. `pool.cacheAffinity: false`로 두면 임계값에서 바인딩된 작업도 재평가합니다. `fill-first`는 바인딩 없는 작업 배정의 소진 기준으로만 사용하며, 기본 `round-robin` 선택은 이 값을 사용하지 않습니다. 알려진 5시간, 주간, 30일 quota window 중 가장 높은 점수를 씁니다. `0`은 사용량 기반 전환만 끄며 바인딩 없는 작업 배정이나 실패 복구는 끄지 않습니다. | +| `autoSwitchThreshold?` | `number` | `80` | 사용량 기반 선제 전환 임계값입니다. `quota`는 바인딩 없는 작업의 다음 요청을 재평가할 수 있습니다. 바인딩된 작업은 기본값(`pool.cacheAffinity`)에서 이 임계값을 넘어도 계정을 유지하며, 해당 계정이 소진되었거나 더 이상 처리할 수 없을 때에만 떠나고, 그때도 실제 quota 여유가 있고 usage가 더 낮은 계정으로만 옮깁니다. `pool.cacheAffinity: false`로 두면 임계값에서 바인딩된 작업도 재평가합니다. `fill-first`는 바인딩 없는 작업 배정의 소진 기준으로만 사용하며, `round-robin`은 새/바인딩 없는 작업 배정에만 사용하며 임계값 미만인 적격 계정이 남아 있는 동안 유효 임계값 이상인 계정을 건너뛰고 이 때문에 바인딩된 작업을 옮기지 않습니다. 알려진 5시간, 주간, 30일 quota window 중 가장 높은 점수를 씁니다. `0`은 사용량 기반 전환만 끄며 바인딩 없는 작업 배정이나 실패 복구는 끄지 않습니다. | | `codexAccountAutoSwitchThresholds?` | `Record` | — | 계정별 `autoSwitchThreshold` 재정의입니다(계정 ID → `0`~`100` 정수). 항목이 없으면 전역 값을 상속하고, `0`은 해당 계정에서 시작하는 사용량 기반 전환만 끕니다. 메인 `__main__` 계정도 지원합니다. Codex Auth의 계정 카드에서 관리합니다. 재정의를 켜면 현재 전역 임계값을 고정된 계정별 값으로 복사합니다. `0`을 포함한 재정의 값은 이후 전역 값이 바뀌어도 우선합니다. 끄면 `threshold: null`을 보내 항목을 삭제하고 현재 전역 임계값과 향후 변경 사항을 상속하는 상태로 돌아갑니다. | -| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | 새 작업/바인딩 없는 Codex 요청의 계정 배정 전략입니다. `(parent thread id, quota scope)`의 live affinity가 없으면 바인딩 없는 요청이며, 프록시 재시작이나 affinity 초기화 뒤에는 기존에 보이던 작업도 바인딩이 없어질 수 있습니다. `quota`는 활성 계정이 없을 때 알려진 usage가 가장 낮은 적격 계정을 선택하고, 적격 활성 계정이 `autoSwitchThreshold` 미만이면 유지합니다. 임계값 도달 뒤에는 바인딩 없는 요청을 옮길 수 있습니다. 바인딩된 작업은 기본값에서 계정이 소진되었거나(알려진 usage 100%) 더 이상 처리할 수 없을 때까지 유지되며, 떠날 때는 실제 quota 여유가 있고 usage가 더 낮은 계정으로만 옮깁니다. 플래그를 끄면 임계값에서 바인딩된 작업의 다음 요청도 실제 quota 여유가 있고 usage가 더 낮은 적격 계정으로 옮길 수 있습니다. `round-robin`은 바인딩 없는 요청을 균등 분배하고, `fill-first`는 cooldown, 사용 불가 또는 drain threshold까지 활성 계정에 배정합니다. `reset-first`: 사용량 임계값 미만인 계정 중 다음 5시간·주간 초기화가 가장 가까운 계정을 고릅니다. 연결된 작업은 설정된 어피니티 정책을 따릅니다. 독립 모델 한도에는 사용량 순서를 적용합니다. 월간 초기화는 이 순서에 사용하지 않습니다. | +| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | 새 작업/바인딩 없는 Codex 요청의 계정 배정 전략입니다. `(parent thread id, quota scope)`의 live affinity가 없으면 바인딩 없는 요청이며, 프록시 재시작이나 affinity 초기화 뒤에는 기존에 보이던 작업도 바인딩이 없어질 수 있습니다. `quota`는 활성 계정이 없을 때 알려진 usage가 가장 낮은 적격 계정을 선택하고, 적격 활성 계정이 `autoSwitchThreshold` 미만이면 유지합니다. 임계값 도달 뒤에는 바인딩 없는 요청을 옮길 수 있습니다. 바인딩된 작업은 기본값에서 계정이 소진되었거나(알려진 usage 100%) 더 이상 처리할 수 없을 때까지 유지되며, 떠날 때는 실제 quota 여유가 있고 usage가 더 낮은 계정으로만 옮깁니다. 플래그를 끄면 임계값에서 바인딩된 작업의 다음 요청도 실제 quota 여유가 있고 usage가 더 낮은 적격 계정으로 옮길 수 있습니다. `round-robin`은 유효 `autoSwitchThreshold` 미만인 적격 계정에 바인딩 없는 요청을 균등 분배하고 모두 임계값 이상이면 모든 적격 계정에 분배하며, `fill-first`는 cooldown, 사용 불가 또는 drain threshold까지 활성 계정에 배정합니다. `reset-first`: 사용량 임계값 미만인 계정 중 다음 5시간·주간 초기화가 가장 가까운 계정을 고릅니다. 연결된 작업은 설정된 어피니티 정책을 따릅니다. 독립 모델 한도에는 사용량 순서를 적용합니다. 월간 초기화는 이 순서에 사용하지 않습니다. | | `pool.cacheAffinity?` | `boolean` | `true` | 바인딩된 Codex 스레드의 cache-affinity 순서입니다. `pool.kernel`과는 별개이며 기본값은 켜짐입니다. 잘못된 값은 켜진 것으로 읽습니다. live 바인딩이 quota 여유보다 우선하므로 `quota`는 사용량이 `autoSwitchThreshold`를 넘었다는 이유만으로 스레드를 옮기지 않습니다. 해당 계정이 일시 중지되었거나 사용할 수 없거나 실제로 소진된 경우(알려진 usage 100%)에는 떠나되, 실제 quota 여유가 있고 usage가 더 낮은 계정으로만 옮깁니다. `false`로 두면 임계값 재바인딩이 복원됩니다. affinity는 고정이 아니라 재정렬입니다. | | `accountPoolStickyLimit?` | `number` | `1` | 한 round-robin 선택이 다음으로 넘어가기 전에 유지하는 새 작업/바인딩 없는 작업 배정 수입니다. 카운터는 업스트림 성공 뒤가 아니라 작업을 바인딩할 때 증가합니다. 범위 1–100이며 `accountPoolStrategy`가 `round-robin`일 때만 적용됩니다. | | `upstreamFailoverThreshold?` | `number` | `3` | 연속된 일시적 실패가 이 횟수에 도달하면 이후 새 세션은 failover됩니다. `0`으로 두면 비활성화됩니다. 일반 Responses와 네이티브 compact 전송에서 입증된 연결 전 DNS/TCP 도달 불가 실패는 provider-host 범위로 기록되며 계정 상태, 계정 쿨다운, 스레드/세션 선호도, 활성 계정 선택 또는 Pool 라우팅에 영향을 주지 않고 이 임계값에도 집계되지 않습니다. | @@ -237,7 +237,7 @@ affinity 초기화 뒤의 기존 작업도 포함될 수 있습니다. 출력 **배정 및 선제 전환 전략:** `quota`(기본)는 활성 계정이 없을 때 최저 usage의 적격 계정을 선택하고, 적격 활성 계정이 `autoSwitchThreshold` 미만이면 유지합니다. 임계값 도달 뒤에는 바인딩 없는 요청을 옮길 수 있습니다. 기본값에서 cache affinity가 quota 여유보다 우선하며, 바인딩된 작업은 계정이 소진되었거나(알려진 usage 100%) 처리할 수 없을 때까지 유지되고, 떠날 때는 실제 quota 여유가 있고 usage가 더 낮은 계정으로만 옮깁니다. usage를 모르는 계정은 바인딩된 작업의 목적지가 되지 않으며, 모든 계정이 임계값 위이면 그대로 둡니다. 플래그를 끄면 바인딩된 작업의 다음 요청도 임계값에서 옮길 수 있지만, 그때도 실제 quota 여유가 있고 usage가 더 낮은 계정으로만 갑니다. -`round-robin`은 바인딩 없는 요청을 균등 분배하며 임계값은 기본 순환에 영향을 주지 않습니다. +`round-robin`은 카운터 기반으로 순환합니다. 새 배정은 유효 `autoSwitchThreshold`(계정별 재정의 또는 전역 기본값, `quota`와 같은 점수) 미만인 적격 계정이 있으면 임계값 이상인 계정을 건너뜁니다. 사용량을 모르거나 임계값이 `0`이면 미만으로 취급하고 모든 적격 계정이 임계값 이상이면 모두 순환합니다. 바인딩된 작업은 임계값을 넘어도 계정을 유지하며 처리할 수 없는 경우(cooldown, quota 거부, failover, pause)에만 이동합니다. live 대화의 자식은 부모가 사용하는 계정에서 시작합니다. 공통 우선순위 계층 필터도 같은 방식으로 여유를 평가합니다. 운영자의 수동 선택은 사용량과 관계없이 각 quota 범위의 다음 배정을 가져가며, 해당 범위에서 그 계정의 요청이 성공하면 선택이 소진되어 이후 배정에는 다시 임계값이 적용됩니다. `accountPoolStickyLimit`(기본 `1`, 1–100)은 성공 응답이 아니라 배정/바인딩 횟수를 셉니다. `fill-first`는 바인딩 없는 요청을 cooldown, 재인증 또는 해당 계정의 유효 drain threshold(계정별 재정의 또는 전역 기본값)까지 활성 계정에 배정하고, 정상적인 바인딩 작업은 affinity를 유지합니다. 이 전략들은 provider enforcement를 우회하지 않으며 @@ -250,9 +250,9 @@ affinity 초기화 뒤의 기존 작업도 포함될 수 있습니다. 출력 | 키 | 타입 | 기본값 | 설명 | | --- | --- | --- | --- | | `anthropicAccountPool.enabled?` | `boolean` | `false` | sticky 세션 결속과 사용량 기반 새 세션 선택을 켭니다. **429 failover는 여기서 제어되지 않습니다**: 쓸 수 있는 계정이 둘 이상이면 다른 다중 자격 증명 제공자와 똑같이 자동으로 켜지며, 끌 수 없습니다. | -| `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` | 새 세션에서는 활성 계정이 이 임계값에 도달하면 설정된 창의 알려진 캐시 사용량이 가장 낮은 계정을 고릅니다. `0`이면 quota 선택을 끕니다. | -| `anthropicAccountPool.strategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` | 새 세션 전략입니다. `quota`는 `quotaWindow`로 지정한 창(기본값은 5시간 막대)으로 계정 순위를 매기고, `fill-first`도 같은 창에서 소진 임계값을 판정합니다. | -| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` | 사용량 기반 계정 선택에 사용하는, 공급자가 보고한 캐시 사용률 막대입니다. `five-hour`는 기존 동작을 유지합니다. `weekly`는 주간 막대를 사용하며 다른 사용 가능한 계정이 남아 있을 때만 5시간 막대가 소진된 계정을 건너뛰고, 아무 계정도 남지 않으면 해당 계정으로 폴백합니다. `max-utilization`은 알려진 값 중 가장 높은 값을 사용하므로 주간 사용량을 알기 전에도 5시간 사용량을 쓸 수 있고, 둘 다 모르면 unknown 순서를 따릅니다. 알려진 사용량은 unknown보다 앞서지만, 사용 가능한 계정이 모두 unknown이어도 사용 가능한 순서의 계정을 선택합니다. 앞서 설명한 5시간 사용량 동점 판정 뒤에도 완전히 같으면 사용 가능한 순서를 유지합니다. 정상 affinity 세션을 선제적으로 재배치하지 않습니다. 새 세션 배정과 가능한 429 대체 이후 라우팅 복구에서 `quota`는 이 창으로 사용 가능한 후보의 순위를 직접 매기고, `fill-first`는 이 창의 임계값과 소진 규칙에 따라 안정 순서로 이동하며, `round-robin`은 이 설정을 무시합니다. 쿨다운, failover 한도, 재인증 가능 여부는 별도의 로컬 상태로 유지됩니다. 계정별 주간 막대는 대시보드의 프로바이더 페이지에서 조회한 뒤에만 알 수 있습니다. | +| `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` | 새 세션에서 활성 계정이 이 임계값에 도달하면 설정된 창의 알려진 캐시 사용량이 가장 낮은 계정을 선택하며, 자체 임계값 미만인 계정을 우선합니다. 선택된 계정 자체가 임계값 이상일 필요는 없습니다. `0`은 사용량 기반 선제 전환만 끄며 새 세션 선택과 적격 429 이후 복구는 여전히 `quotaWindow`를 참조합니다. | +| `anthropicAccountPool.strategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` | 새 세션 전략입니다. `quota`는 `quotaWindow` 사용량이 유효 `autoSwitchThreshold`(기본 80)에 도달하거나 처리할 수 없을 때까지 활성 계정을 유지한 뒤 자체 임계값 미만 계정을 우선하여 사용량이 가장 적은 계정으로 이동합니다. 사용량을 모르면 활성 계정을 유지합니다. `round-robin`은 사용량 임계값을 읽지 않고 새 세션을 순환합니다. `fill-first`는 `quotaWindow`에서 소진 임계값을 평가합니다. | +| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` | 사용량 기반 계정 선택에 사용하는, 공급자가 보고한 캐시 사용률 막대입니다. `five-hour`는 기존 동작을 유지합니다. `weekly`는 주간 막대를 사용하며 다른 사용 가능한 계정이 남아 있을 때만 5시간 막대가 소진된 계정을 건너뛰고, 아무 계정도 남지 않으면 해당 계정으로 폴백합니다. `max-utilization`은 알려진 값 중 가장 높은 값을 사용하므로 주간 사용량을 알기 전에도 5시간 사용량을 쓸 수 있고, 둘 다 모르면 unknown 순서를 따릅니다. 알려진 사용량은 unknown보다 앞서지만, 사용 가능한 계정이 모두 unknown이어도 사용 가능한 순서의 계정을 선택합니다. 앞서 설명한 5시간 사용량 동점 판정 뒤에도 완전히 같으면 사용 가능한 순서를 유지합니다. 정상 affinity 세션을 선제적으로 재배치하지 않습니다. `quota`가 대체 계정을 고를 때(활성 계정이 임계값에 도달했거나 처리할 수 없는 새 세션 또는 적격 429 이후 복구) 자체 임계값 미만 후보를 우선하고 이 창으로 순위를 매기며, `fill-first`는 이 창의 임계값과 소진 규칙에 따라 안정 순서로 이동하며, `round-robin`은 이 설정을 무시합니다. 쿨다운, failover 한도, 재인증 가능 여부는 별도의 로컬 상태로 유지됩니다. 계정별 주간 막대는 사용량 프로브나 관측된 응답 헤더에서 얻습니다. | | `anthropicAccountPool.stickyLimit?` | `number` | `1` | 성공한 새 세션 결속이 한 번의 라운드로빈 선택에 유지되는 횟수입니다. 범위는 1–100입니다. | 공유 5시간/주간 할당량의 거부가 확인된 429만 계정 쿨다운과 전환을 유발합니다. 일시적인 속도 제한은 affinity를 유지하며 해당 계정의 전송만 잠시 중지합니다. 요청마다 짧은 동일 계정 재시도 한 번과 적격한 다른 계정 전환 한 번까지만 허용됩니다. 근거 헤더가 없는 429는 동일 계정에서 한 번만 짧게 재시도하며 계정 상태를 냉각하지 않고 Retry-After를 만들어 붙이지 않습니다. 기본 단일 계정 동작은 유지됩니다. Fable 전용 거부는 Sonnet을 제한하지 않습니다. 수동 선택과 affinity도 요청 모델의 공유/계열 할당량을 확인합니다. 수동 조회가 아닌 응답 헤더의 계열 근거는 30분 또는 알려진 리셋 시각에 만료되며 요청 하나로 재확인합니다. 사용량 임계값은 소프트 선호이고 모든 후보가 소진되면 기존 폴백을 유지합니다. 사용량 또는 결제 하드 캡이 아닙니다. 결속은 프로세스 로컬이며 크기가 제한됩니다. 토큰 갱신 실패는 기존 재인증 규칙을 따릅니다. 확인된 구독 또는 계정 결제 403은 출력 전에 다른 계정으로 전환하며 `Retry-After` 또는 기본 10분 동안 냉각합니다. 일반 권한 거부는 전환하지 않습니다. 적격한 계정이 모두 쿨다운 중이면, 클라이언트는 인증 오류가 아니라 알려진 경우 `Retry-After`가 포함된 429를 받습니다. diff --git a/docs-site/src/content/docs/reference/configuration/providers.md b/docs-site/src/content/docs/reference/configuration/providers.md index 0c37bfc4a8a..082c0dd688f 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -123,9 +123,9 @@ separate. Full request URLs such as `/api/v1/responses` are not provider base UR | `activeCodexAccountPinned?` | `string` | — | Account id the operator last selected by hand. While set, a higher `codexAccountPriorities` tier cannot preempt it until the pin is released by drain, exclusion, deletion, or an explicit failover/promotion away. Ordinary round-robin movement inside the capped tier does not release it. Writing any `codexAccountPriorities` entry also releases the pin, so a pin made before an order existed cannot outrank one set afterward. `GET /api/codex-auth/active` reports both whether the effective account is pinned (`pinned`) and the account carrying the ceiling (`pinnedAccountId`). | | `codexPreserveSignedInAccount?` | `boolean` | `false` | Prefer other eligible Codex Pool identities before native main and ordinary entries matching its selected workspace and member email. Existing custom priorities are preserved inside each group. Healthy bindings and manual pins remain; exact account routes and Direct mode are unchanged. Fallback may consume signed-in quota under all existing guards. Use [account preserve-signed-in](/reference/cli/providers-accounts/#ocx-account-preserve-signed-in-openai-onoffstatus---apply-to-bound---json) for status or an explicit next-request binding transition. | | `codexAccountPriorityFailback?` | `boolean` | `false` | Opt-in return of ongoing Codex Pool tasks to a usable higher-priority account under the `quota` strategy. Requests trigger a background quota refresh at most once every five minutes, including failed refresh attempts. When recent quota observations show headroom, the next request may rebind even if its current account is below the threshold. This explicit preference can discard a warm prompt cache; it does not change default cache affinity. No requests means no polling. Manual pins, model access, cooldowns, pauses and reauthentication exclusions still apply; in-flight requests keep their captured account. Requires the current source account's effective threshold to be positive (an override of 0 disables it; a positive override works with global 0); exact account routes and Direct mode are unchanged. | -| `autoSwitchThreshold?` | `number` | `80` | Usage threshold for placing new/unbound work. `quota` can re-evaluate unbound tasks on their next request once usage crosses this threshold. Bound tasks keep their account past the threshold by default (`pool.cacheAffinity`); they leave only when that account is exhausted or otherwise cannot serve, and then only for an account with genuine quota headroom and strictly lower usage. Set `pool.cacheAffinity: false` to re-evaluate bound tasks at this threshold, still only onto such a destination. `fill-first` uses it only as the drain point for unbound assignment; normal `round-robin` selection does not use it. The score uses the hottest known 5h, weekly, or 30d quota window. `0` disables usage-based proactive switching only, not unbound assignment or failure recovery. | +| `autoSwitchThreshold?` | `number` | `80` | Usage threshold for placing new/unbound work. `quota` can re-evaluate unbound tasks on their next request once usage crosses this threshold. Bound tasks keep their account past the threshold by default (`pool.cacheAffinity`); they leave only when that account is exhausted or otherwise cannot serve, and then only for an account with genuine quota headroom and strictly lower usage. Set `pool.cacheAffinity: false` to re-evaluate bound tasks at this threshold, still only onto such a destination. `fill-first` uses it only as the drain point for unbound assignment; `round-robin` uses it only when placing new/unbound work: it skips accounts at or over their effective threshold while any eligible account is still under it, and never moves a bound task for it. The score uses the hottest known 5h, weekly, or 30d quota window. `0` disables usage-based proactive switching only, not unbound assignment or failure recovery. | | `codexAccountAutoSwitchThresholds?` | `Record` | — | Per-account overrides for `autoSwitchThreshold`: account id → integer from `0` to `100`. An absent entry inherits the global value; `0` disables usage-driven switching only when that account is the source. `quota` uses the current source account's effective threshold for bound-task re-evaluation and unbound switching. Fill-first drain and selection-order tier headroom are evaluated against each account's own effective threshold; main-account pins and subagent fallback also use the relevant account's effective threshold. Supports the main `__main__` account. A malformed map is ignored with a warning. Managed by each account card on the Codex Auth page; disabling an override removes its entry. Enabling the override copies the current global threshold into a fixed account value. The override, including `0`, takes precedence over later global changes. Disabling it sends `threshold: null`, removes the entry, and restores inheritance of the current global threshold and future global changes. | -| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | Assignment strategy for new/unbound Codex requests. A request is unbound when it has no live (parent thread id, quota scope) affinity; a visible existing task can become unbound after proxy restart or affinity reset. `quota` picks the lowest-usage eligible account when no active account exists, keeps an eligible active account below `autoSwitchThreshold`, and after the threshold may move an unbound request. Bound tasks follow `pool.cacheAffinity` (on by default): they stay until the account is exhausted (known usage at 100%) or otherwise cannot serve, and then may rebind only to an account with genuine quota headroom and strictly lower usage. Set the flag `false` to proactively rebind a bound task at the threshold, still only onto such a destination. `round-robin` distributes unbound requests evenly; `fill-first` keeps assigning unbound requests to the active account until cooldown, unavailability, or the configured drain threshold. `reset-first`: Prefer the nearest future 5-hour or weekly reset among accounts below the usage threshold. Bound tasks follow the configured affinity policy. Independent model quotas use quota ordering. Monthly resets do not determine this ordering. | +| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | Assignment strategy for new/unbound Codex requests. A request is unbound when it has no live (parent thread id, quota scope) affinity; a visible existing task can become unbound after proxy restart or affinity reset. `quota` picks the lowest-usage eligible account when no active account exists, keeps an eligible active account below `autoSwitchThreshold`, and after the threshold may move an unbound request. Bound tasks follow `pool.cacheAffinity` (on by default): they stay until the account is exhausted (known usage at 100%) or otherwise cannot serve, and then may rebind only to an account with genuine quota headroom and strictly lower usage. Set the flag `false` to proactively rebind a bound task at the threshold, still only onto such a destination. `round-robin` distributes unbound requests evenly across eligible accounts still under their effective `autoSwitchThreshold`, and across all eligible accounts when every one is at or over it; `fill-first` keeps assigning unbound requests to the active account until cooldown, unavailability, or the configured drain threshold. `reset-first`: Prefer the nearest future 5-hour or weekly reset among accounts below the usage threshold. Bound tasks follow the configured affinity policy. Independent model quotas use quota ordering. Monthly resets do not determine this ordering. | | `pool.cacheAffinity?` | `boolean` | `true` | Cache-affinity ordering for bound Codex threads, independent of `pool.kernel`. On by default; omitting the key or setting `true` keeps a bound task on its account until that account genuinely cannot serve. Only an explicit `false` restores threshold-based rebinding of bound tasks. A live binding outranks quota headroom: `quota` does not move the thread merely because usage crossed `autoSwitchThreshold`. The thread still leaves if that account cannot serve — paused, unusable, or genuinely exhausted (known usage at 100%) — and then only to an account with genuine quota headroom and strictly lower usage. Under either setting, an account with unknown usage is never chosen as a destination for a bound task, so when every account sits above the threshold the task stays put. Affinity is a reordering, not a pin. | | `pool.credentialGroups?` | `Array<{ id: string; credentials: string[]; note?: string }>` | `[]` | Accepted and validated, but not yet consumed by routing: declaring a group changes no routing decision until a consuming layer lands. Operator-declared quota domains: groups of credentials that demonstrably share one upstream usage limit. Members of one group count once toward available capacity, and a quota refusal inside a group is not answered by rotating to another member — the limit is the same, so the move would pay a cold prefix for zero new capacity. Declared groups speak only to quota; sharing a limit says nothing about prompt-cache compatibility, which is classified separately. Each member is written provider-qualified as `":"`, because a credential id means something only inside its provider; the provider segment accepts the usual aliases (`chatgpt:` and `codex:` both mean OpenAI). Group ids must be unique, `credentials` must be non-empty, and a credential may appear in at most one group — an ambiguous declaration is rejected on write and dropped with a warning on load rather than resolved by whichever group is listed first, since that would merge two unrelated quota domains. A malformed list costs only the grouping: `pool.kernel` and `pool.cacheAffinity` are preserved. Absent or empty means no declared grouping, so an unconfigured install behaves exactly as before. | | `accountPoolStickyLimit?` | `number` | `1` | New/unbound task assignments retained on one round-robin selection before advancing; the counter advances when a task is bound, not after an upstream success. Range 1–100. | @@ -1044,7 +1044,7 @@ and pauses only accounts freshly confirmed at 100%; unknown or failed refreshes | Strategy | Behaviour | | --- | --- | | `quota` (default) | If no active account exists, choose the lowest-usage eligible account across 5-hour, weekly, and 30-day windows. Otherwise retain an eligible active account below `autoSwitchThreshold`; after it crosses the threshold, an unbound request can move to a lower-usage eligible account. Bound tasks keep cache affinity by default and stay until the account is exhausted (known usage at 100%) or cannot serve (paused, unusable); a move then requires genuine quota headroom and strictly lower usage on the destination, so the task stays put when every account is over the threshold or the only cooler account has unknown usage. Set `pool.cacheAffinity: false` to let a bound task's next request move at the threshold, still only onto such a destination. `0` disables this usage-driven re-evaluation, not failure recovery. | -| `round-robin` | Evenly assign unbound requests across eligible accounts. Rotation is counter-based and ignores usage thresholds, but the shared priority-tier filter still evaluates each account's headroom using its effective threshold (account override or global default). `accountPoolStickyLimit` (1–100) counts assignments on one pick, not successful upstream responses. | +| `round-robin` | Evenly assign unbound requests across eligible accounts. Rotation is counter-based. A new placement skips accounts at or over their effective `autoSwitchThreshold` (account override or global default, scored like `quota`) while any eligible account is still under it; unknown usage and a threshold of `0` count as under. An operator's manual selection takes the next placement in each quota scope whatever its usage; a successful request on it in that scope spends the selection, and later placements there apply the threshold again. When every eligible account is at or over its threshold, rotation covers all of them. A bound task keeps its account past the threshold and moves only when that account cannot serve (cooldown, quota refusal, failover, pause), and a child of a live conversation starts on the account its parent is using. The shared priority-tier filter evaluates headroom the same way. `accountPoolStickyLimit` (1–100) counts assignments on one pick, not successful upstream responses. | | `fill-first` | Assign unbound requests to the active account until cooldown, reauthentication, or that account's effective drain threshold (account override or global default); unknown usage does not force a switch. Healthy bound tasks keep affinity. | Rotation does not protect against provider enforcement; multi-account use may violate provider terms. @@ -1061,9 +1061,9 @@ for the subscription and client conditions the pool is meant for. | --- | --- | --- | --- | | `anthropicAccountPool.enabled?` | `boolean` | `false` | Enable sticky session affinity and quota-ranked new-session selection. **429 failover is not gated here**: it activates whenever two or more usable accounts are stored, exactly like every other multi-credential provider, and cannot be switched off. | | `anthropicAccountPool.nativeMessages?` | `boolean` | `true` | Prefer native Claude Messages for eligible direct Anthropic routes when pooling is enabled. Explicit native rollout opt-outs still apply. `false` selects the legacy bridge for pooled requests; pool-off retains explicit rollout behavior. | -| `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` | For new sessions, when the active account reaches this threshold, choose the lowest known cached usage in the configured window; the account chosen does not itself have to be at or above the threshold. `0` disables **proactive** usage-based switching only — new-session selection and routing recovery after an eligible 429 still consult `quotaWindow`. | -| `anthropicAccountPool.strategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` | New-session strategy; `quota` ranks accounts by the window set by `quotaWindow`, and `fill-first` evaluates its drain threshold in that same window. | -| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` | The cached provider-reported utilization bar used for usage-aware account selection. `five-hour` keeps the original behavior. `weekly` scores the weekly bar and skips accounts whose 5-hour bar is exhausted while another eligible account remains, but falls back to exhausted candidates when none do. `max-utilization` scores the highest known bar, so it can use 5-hour usage before weekly usage is available; if neither is known, the account follows unknown-usage ordering. Known usage ranks before unknown usage under the opt-in `weekly` and `max-utilization` windows only; an omitted or explicit `five-hour` preserves the legacy ordering. If every eligible account is unknown, selection still returns one in eligible order. After the documented lower-5-hour tie-break, exact ties preserve eligible order. A healthy affinity-bound session is not proactively rebalanced. For new-session assignment and routing recovery after an eligible 429 replacement, `quota` ranks eligible candidates directly with this window; `fill-first` advances in stable order using this window's threshold and exhaustion rules; `round-robin` ignores it. Cooldown, failover limits, and reauthentication eligibility remain separate local state. Per-account weekly bars come from usage probes or observed response headers. | +| `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` | For new sessions, when the active account reaches this threshold, choose the lowest known cached usage in the configured window, preferring accounts still under their own threshold; the account chosen does not itself have to be at or above the threshold. `0` disables **proactive** usage-based switching only — new-session selection and routing recovery after an eligible 429 still consult `quotaWindow`. | +| `anthropicAccountPool.strategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` | New-session strategy. `quota` keeps the active account until its usage in `quotaWindow` reaches its effective `autoSwitchThreshold` (default 80) or it cannot serve, then moves to the least-used account, preferring accounts still under their own threshold; unknown usage keeps the active account. `round-robin` rotates new sessions without reading usage thresholds. `fill-first` evaluates its drain threshold in `quotaWindow`. | +| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` | The cached provider-reported utilization bar used for usage-aware account selection. `five-hour` keeps the original behavior. `weekly` scores the weekly bar and skips accounts whose 5-hour bar is exhausted while another eligible account remains, but falls back to exhausted candidates when none do. `max-utilization` scores the highest known bar, so it can use 5-hour usage before weekly usage is available; if neither is known, the account follows unknown-usage ordering. Known usage ranks before unknown usage under the opt-in `weekly` and `max-utilization` windows only; an omitted or explicit `five-hour` preserves the legacy ordering. If every eligible account is unknown, selection still returns one in eligible order. After the documented lower-5-hour tie-break, exact ties preserve eligible order. A healthy affinity-bound session is not proactively rebalanced. When `quota` picks a replacement (a new session whose active account reached its threshold or cannot serve, or recovery after an eligible 429), it prefers candidates under their own threshold and ranks them with this window; `fill-first` advances in stable order using this window's threshold and exhaustion rules; `round-robin` ignores it. Cooldown, failover limits, and reauthentication eligibility remain separate local state. Per-account weekly bars come from usage probes or observed response headers. | | `anthropicAccountPool.stickyLimit?` | `number` | `1` | Successful new-session binds retained on one round-robin selection. Range 1–100. | | `anthropicAccountPool.routes?` | `{name, match, accounts, fallback?}[]` | — | Ordered model routes for the enabled Anthropic OAuth pool. `match` is a full, case-sensitive model ID glob (`*` and `?`); first match wins. `accounts` contains stored account IDs, not aliases. Eligible accounts are limited to the route for initial selection and 429 retry. Without fallback, an empty route returns a local 401, or 429 with route-scoped `Retry-After` if all its declared accounts are cooling. With `fallback: true`, an all-cooling ordinary pool returns 429 with its earliest usable cooldown, even if a saved route account was removed; the client response never names the route; the proxy log uses `route:#` for the rule’s 1-based position. `fallback: true` widens only when no routed account is eligible; fill-first then uses ordinary pool order. No matching rule retains normal selection; disabling the pool makes saved routes inactive. Invalid rules fail validated writes and prevent routed dispatch until corrected. `null` clears routes through the settings API. | diff --git a/docs-site/src/content/docs/ru/reference/configuration/providers.md b/docs-site/src/content/docs/ru/reference/configuration/providers.md index 527f8f4761b..22a4986e82d 100644 --- a/docs-site/src/content/docs/ru/reference/configuration/providers.md +++ b/docs-site/src/content/docs/ru/reference/configuration/providers.md @@ -54,9 +54,9 @@ ocx models provider openrouter on | `codexAccountPickerEnabled?` | `boolean` | выкл. при пустой map | Управляет созданием account-qualified строк picker'а Codex из подходящих сопоставлений `codexAccountNamespaces`. `true` разрешает показывать сопоставленные строки. Если поле не задано при непустой map, функция считается включённой для обратной совместимости; при пустой map она выключена. `false` скрывает созданные строки и возвращает bare native-строки в picker, не удаляя сопоставления и не отключая точную маршрутизацию `/`. | | `activeCodexAccountId?` | `string` | — | Вручную выбранный аккаунт Pool для следующего запроса. Выбор очищает thread affinity; in-flight-запросы сохраняют уже захваченные credential'ы. | | `codexAccountPriorities?` | `Record` | — | Порядок выбора для каждого аккаунта пула Codex: id аккаунта → целое число от `-100` до `100`, **больше — используется раньше**, отсутствие означает `0`. Это граница порядка, а не пригодности: выбор сужает уже подходящие аккаунты до самого высокого уровня, у которого ещё есть запас квоты, а внутри этого уровня аккаунт выбирает `accountPoolStrategy`. Уровень пропускается, только когда все его аккаунты достигли собственного ненулевого эффективного порога (переопределение аккаунта или глобальное значение), находятся в cooldown, под soft-avoid, на паузе или требуют повторной аутентификации; неизвестный usage никогда не исчерпывает уровень. Порядок не делает выбираемым непригодный аккаунт и не перепривязывает поток, у которого аккаунт уже есть. Основной аккаунт `__main__` участвует на равных — именно так логин Codex Desktop можно оставить на самый конец. Без записей поведение остаётся прежним. Некорректная map игнорируется с предупреждением в консоли (порядок отключается, восстановление config не запускается). Управляется через `ocx account priority` и страницу Codex Auth. | -| `autoSwitchThreshold?` | `number` | `80` | Порог проактивного переключения по использованию. `quota` может повторно оценить следующий непривязанный запрос. Привязанная задача по умолчанию (`pool.cacheAffinity`) сохраняет аккаунт после порога, пока он не исчерпан и ещё может обслуживать запрос, и переносится только на аккаунт со строго меньшим usage и реальным запасом квоты. Установите `pool.cacheAffinity: false`, чтобы повторно оценивать привязанные задачи на этом пороге. `fill-first` использует его только как точку исчерпания для непривязанных назначений; обычный `round-robin` его не использует. Оценка берёт самое горячее из окон 5 часов, недели и 30 дней. `0` отключает только переключение по использованию, но не назначение непривязанных задач и не восстановление после сбоев. | +| `autoSwitchThreshold?` | `number` | `80` | Порог проактивного переключения по использованию. `quota` может повторно оценить следующий непривязанный запрос. Привязанная задача по умолчанию (`pool.cacheAffinity`) сохраняет аккаунт после порога, пока он не исчерпан и ещё может обслуживать запрос, и переносится только на аккаунт со строго меньшим usage и реальным запасом квоты. Установите `pool.cacheAffinity: false`, чтобы повторно оценивать привязанные задачи на этом пороге. `fill-first` использует его только как точку исчерпания для непривязанных назначений; `round-robin` применяет его только к новым назначениям: пока есть подходящий аккаунт ниже своего порога, аккаунты на пороге или выше пропускаются; привязанная задача из-за этого не переносится. Оценка берёт самое горячее из окон 5 часов, недели и 30 дней. `0` отключает только переключение по использованию, но не назначение непривязанных задач и не восстановление после сбоев. | | `codexAccountAutoSwitchThresholds?` | `Record` | — | Переопределения `autoSwitchThreshold` по аккаунтам: id → целое число `0`–`100`. Без записи наследуется глобальное значение; `0` отключает только переключения по использованию с этого аккаунта. Поддерживается основной аккаунт `__main__`. Управляется в карточке аккаунта на странице Codex Auth. Включение переопределения копирует текущий глобальный порог в фиксированное значение аккаунта. Переопределение, включая `0`, имеет приоритет и после изменения глобального порога. Отключение отправляет `threshold: null`, удаляет запись и восстанавливает наследование текущего глобального порога и его будущих изменений. | -| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | Стратегия назначения для новых/непривязанных запросов Codex. Запрос непривязан, если у него нет live affinity `(parent thread id, quota scope)`; видимая существующая задача может стать непривязанной после перезапуска прокси или сброса affinity. `quota` выбирает подходящий аккаунт с наименьшим известным usage, когда активного аккаунта нет, сохраняет подходящий активный аккаунт ниже `autoSwitchThreshold`, а после порога может перевести непривязанный запрос. Привязанные задачи следуют `pool.cacheAffinity` (по умолчанию включён): они остаются, пока аккаунт не исчерпан (известный usage 100%) или не может обслуживать запрос, и тогда переносятся только на аккаунт со строго меньшим usage и реальным запасом квоты. Установите флаг в `false`, чтобы на пороге проактивно перепривязать задачу к подходящему аккаунту с меньшим usage, всё равно только при той же проверке назначения. `round-robin` равномерно распределяет непривязанные запросы; `fill-first` назначает их активному аккаунту до cooldown, недоступности или порога исчерпания. `reset-first`: Среди аккаунтов ниже порога выбирается ближайший сброс 5-часовой или недельной квоты. Привязанные задачи следуют настроенной политике привязки. Независимые квоты моделей упорядочиваются по использованию. Месячный сброс не определяет этот порядок. | +| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | Стратегия назначения для новых/непривязанных запросов Codex. Запрос непривязан, если у него нет live affinity `(parent thread id, quota scope)`; видимая существующая задача может стать непривязанной после перезапуска прокси или сброса affinity. `quota` выбирает подходящий аккаунт с наименьшим известным usage, когда активного аккаунта нет, сохраняет подходящий активный аккаунт ниже `autoSwitchThreshold`, а после порога может перевести непривязанный запрос. Привязанные задачи следуют `pool.cacheAffinity` (по умолчанию включён): они остаются, пока аккаунт не исчерпан (известный usage 100%) или не может обслуживать запрос, и тогда переносятся только на аккаунт со строго меньшим usage и реальным запасом квоты. Установите флаг в `false`, чтобы на пороге проактивно перепривязать задачу к подходящему аккаунту с меньшим usage, всё равно только при той же проверке назначения. `round-robin` распределяет непривязанные запросы равномерно между подходящими аккаунтами ниже их эффективного `autoSwitchThreshold`, а если все достигли порога — между всеми подходящими; `fill-first` назначает их активному аккаунту до cooldown, недоступности или порога исчерпания. `reset-first`: Среди аккаунтов ниже порога выбирается ближайший сброс 5-часовой или недельной квоты. Привязанные задачи следуют настроенной политике привязки. Независимые квоты моделей упорядочиваются по использованию. Месячный сброс не определяет этот порядок. | | `pool.cacheAffinity?` | `boolean` | `true` | Порядок cache-affinity для привязанных потоков Codex, независимый от `pool.kernel`. По умолчанию включён; пропуск ключа или `true` сохраняет привязку, а любое значение кроме `false` читается как включённое. Живая привязка важнее запаса квоты: `quota` не переносит поток только потому, что usage пересёк `autoSwitchThreshold` — перенос живого разговора сбрасывает изолированный по аккаунту prompt cache. Поток всё равно уходит, если аккаунт не может обслуживать запрос — на паузе, непригоден, исключён планом, с недействительными credential'ами, со сменённой generation, с истёкшим TTL, при отказе квоты 429/402 или реально исчерпан (известный usage 100%) — и только на аккаунт со строго меньшим usage и реальным запасом квоты. Аккаунт с неизвестным usage никогда не выбирается как назначение для привязанной задачи. Если все аккаунты выше порога, привязанная задача остаётся: лучшего назначения нет. `false` возвращает перепривязку по порогу, всё равно только при той же проверке назначения. Affinity меняет порядок, а не закрепляет учётные данные. | | `accountPoolStickyLimit?` | `number` | `1` | Число назначений новых/непривязанных задач на одном выборе round-robin перед переходом дальше. Счётчик растёт при привязке задачи, а не после успеха upstream. Диапазон 1–100; только при `accountPoolStrategy` = `round-robin`. | | `upstreamFailoverThreshold?` | `number` | `3` | Сколько подряд transient failure допустить, прежде чем новые сессии начнут делать failover. `0` отключает эту логику. Для обычных Responses-запросов и нативных compact-отправок доказанные ошибки доступности DNS/TCP до соединения учитываются на уровне пары «провайдер, хост» и не влияют на здоровье аккаунта, кулдауны аккаунта, привязку потока/сессии, выбор активного аккаунта или маршрутизацию пула, а также не учитываются в этом пороге. | @@ -265,8 +265,7 @@ redirect'ов для обычных provider-request'ов реализована после чего запрос может перейти на другой подходящий аккаунт Pool. Эти переходы восстановления остаются активными при `autoSwitchThreshold: 0`; значение `0` отключает только проактивное переключение по использованию. -**Стратегии назначения и проактивного переключения:** `quota` выбирает подходящий аккаунт с наименьшим usage, когда активного аккаунта нет, сохраняет подходящий активный аккаунт ниже `autoSwitchThreshold`, а после порога может перевести непривязанный запрос. Привязанные задачи по умолчанию держат cache affinity и остаются, пока аккаунт не исчерпан (известный usage 100%) или не может обслуживать запрос; перенос тогда требует реального запаса квоты и строго меньшего usage на назначении. Установите `pool.cacheAffinity: false`, чтобы следующий запрос привязанной задачи мог уйти на пороге, всё равно только на подходящий аккаунт с меньшим usage и реальным запасом квоты. `round-robin` равномерно распределяет непривязанные запросы, а порог не -меняет обычную ротацию. `accountPoolStickyLimit` (по умолчанию `1`, 1–100) считает назначения/bind, +**Стратегии назначения и проактивного переключения:** `quota` выбирает подходящий аккаунт с наименьшим usage, когда активного аккаунта нет, сохраняет подходящий активный аккаунт ниже `autoSwitchThreshold`, а после порога может перевести непривязанный запрос. Привязанные задачи по умолчанию держат cache affinity и остаются, пока аккаунт не исчерпан (известный usage 100%) или не может обслуживать запрос; перенос тогда требует реального запаса квоты и строго меньшего usage на назначении. Установите `pool.cacheAffinity: false`, чтобы следующий запрос привязанной задачи мог уйти на пороге, всё равно только на подходящий аккаунт с меньшим usage и реальным запасом квоты. `round-robin`: Ротация основана на счётчике. Новые назначения пропускают аккаунты на эффективном `autoSwitchThreshold` или выше (значение аккаунта или глобальное, оценка как у `quota`), пока есть подходящий аккаунт ниже порога. Неизвестное usage и порог `0` считаются ниже; если все достигли порога, ротация охватывает всех. Привязанная задача сохраняет аккаунт после порога и переходит только если он не может обслуживать запрос (cooldown, отказ quota, failover, pause). Потомок активного диалога начинает на аккаунте родителя. Общий фильтр приоритетов оценивает запас так же. Ручной выбор оператора получает следующее назначение в каждой quota scope независимо от usage; успешный запрос на этом аккаунте в этой scope расходует выбор, и дальнейшие назначения там снова учитывают порог. `accountPoolStickyLimit` (по умолчанию `1`, 1–100) считает назначения/bind, а не успешные ответы. `fill-first` назначает непривязанные запросы активному аккаунту до cooldown, reauth или эффективного порога исчерпания этого аккаунта (переопределение аккаунта или глобальное значение); здоровые привязанные задачи сохраняют affinity. Эти стратегии не защищают от enforcement провайдера. @@ -282,9 +281,9 @@ reauth или эффективного порога исчерпания это | Ключ | Тип | По умолчанию | Описание | | --- | --- | --- | --- | | `anthropicAccountPool.enabled?` | `boolean` | `false` | Включить закрепление сессии и выбор новой сессии по использованию. **Переключение при 429 здесь не управляется**: оно работает, как только сохранено два и более пригодных аккаунта, как и у любого другого провайдера с несколькими учётными данными, и не отключается. | -| `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` | Для новых сессий выбирать аккаунт с наименьшим известным cached usage в настроенном окне, если активный аккаунт достиг порога. `0` отключает выбор по quota. | -| `anthropicAccountPool.strategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` | Стратегия для новых сессий; `quota` ранжирует аккаунты по окну, заданному в `quotaWindow` (по умолчанию это 5-hour bar'ы), а `fill-first` в этом же окне оценивает свой порог исчерпания. | -| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` | Кешированная полоса использования, сообщённая провайдером и применяемая при выборе по использованию. `five-hour` сохраняет прежнее поведение. `weekly` использует недельный bar и пропускает аккаунты с исчерпанным 5-hour bar, пока остаётся другой доступный аккаунт, но возвращается к ним, если других нет. `max-utilization` использует наибольшее известное значение, поэтому до появления недельных данных может использовать 5-hour usage; если неизвестны оба значения, аккаунт следует порядку unknown usage. Известное использование ранжируется раньше unknown, но если у всех доступных аккаунтов оно неизвестно, выбирается аккаунт в доступном порядке. После описанного сравнения по меньшему значению 5-hour usage полное равенство также сохраняет этот порядок. Здоровая сессия с affinity не перебалансируется заранее. При назначении новой сессии и восстановлении маршрутизации после допустимой замены при 429 `quota` напрямую ранжирует доступных кандидатов по этому окну, `fill-first` идёт в стабильном порядке с учётом порога и правил исчерпания этого окна, а `round-robin` игнорирует настройку. Cooldown, лимиты failover и допустимость повторной аутентификации остаются отдельным локальным состоянием. Недельные bar'ы аккаунтов известны только после опроса на странице Providers в dashboard. | +| `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` | Для новых сессий при достижении активным аккаунтом порога выбирается аккаунт с наименьшим известным cached usage в настроенном окне, с предпочтением аккаунтов ниже их собственного порога; выбранный аккаунт не обязан сам достигать порога. `0` отключает только проактивное переключение по использованию; выбор новой сессии и восстановление после допустимого 429 по-прежнему учитывают `quotaWindow`. | +| `anthropicAccountPool.strategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` | Стратегия новых сессий. `quota` сохраняет активный аккаунт, пока usage в `quotaWindow` не достигнет эффективного `autoSwitchThreshold` (по умолчанию 80) или аккаунт не перестанет обслуживать запросы, затем переходит к наименее используемому, предпочитая аккаунты ниже собственных порогов; неизвестное usage сохраняет активный аккаунт. `round-robin` чередует новые сессии без учёта порогов. `fill-first` оценивает порог исчерпания в `quotaWindow`. | +| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` | Кешированная полоса использования, сообщённая провайдером и применяемая при выборе по использованию. `five-hour` сохраняет прежнее поведение. `weekly` использует недельный bar и пропускает аккаунты с исчерпанным 5-hour bar, пока остаётся другой доступный аккаунт, но возвращается к ним, если других нет. `max-utilization` использует наибольшее известное значение, поэтому до появления недельных данных может использовать 5-hour usage; если неизвестны оба значения, аккаунт следует порядку unknown usage. Известное использование ранжируется раньше unknown, но если у всех доступных аккаунтов оно неизвестно, выбирается аккаунт в доступном порядке. После описанного сравнения по меньшему значению 5-hour usage полное равенство также сохраняет этот порядок. Здоровая сессия с affinity не перебалансируется заранее. Когда `quota` выбирает замену (новая сессия с активным аккаунтом на пороге или недоступным для обслуживания либо восстановление после допустимого 429), он предпочитает кандидатов ниже собственных порогов и ранжирует их по этому окну, `fill-first` идёт в стабильном порядке с учётом порога и правил исчерпания этого окна, а `round-robin` игнорирует настройку. Cooldown, лимиты failover и допустимость повторной аутентификации остаются отдельным локальным состоянием. Недельные bar'ы аккаунтов берутся из usage-проб или наблюдаемых заголовков ответов. | | `anthropicAccountPool.stickyLimit?` | `number` | `1` | Сколько успешных bind'ов новых сессий удерживать на одном выборе round-robin. Диапазон 1–100. | Только 429 с подтверждённым отказом общей пятичасовой или недельной квоты охлаждает аккаунт и допускает переключение. Временный лимит скорости приостанавливает допуск аккаунта, сохраняя affinity: на запрос разрешены один короткий повтор на том же аккаунте и один переход к другому подходящему аккаунту. Без доказательных заголовков 429 допускает только один короткий повтор на том же аккаунте, без cooldown и без выдуманного Retry-After. Поведение по умолчанию с одним аккаунтом не меняется. Отказ только для Fable не ограничивает Sonnet; ручной выбор и affinity также проверяют общую квоту и квоту запрошенного семейства. Пассивные данные семейства устаревают через тридцать минут или при известном сбросе и перепроверяются одним обслуживающим запросом за раз. Пороги остаются мягкими предпочтениями с прежним fallback при исчерпании всех кандидатов, без жёсткого лимита использования или оплаты. Affinity локальна для процесса и diff --git a/docs-site/src/content/docs/tr/guides/claude-code.md b/docs-site/src/content/docs/tr/guides/claude-code.md index fd92e204921..66b385d0809 100644 --- a/docs-site/src/content/docs/tr/guides/claude-code.md +++ b/docs-site/src/content/docs/tr/guides/claude-code.md @@ -18,9 +18,9 @@ fazla Claude hesabına giriş yapabilirsiniz. Varsayılan olarak her istek yaln (`anthropicAccountPool.enabled`), bu OAuth hesapları arasında yapışkan oturum bağlılığı ve kullanıma dayalı yeni oturum seçimi ekler. 429 yük devretmesini **kontrol etmez**: iki veya daha fazla kullanılabilir hesap saklandığında, hız sınırına takılan istek bu anahtar açık da kapalı da olsa başka bir hesaba geçer ve bu kapatılamaz. Yalnızca **yeni** oturumlar için `anthropicAccountPool.strategy` uygun hesaplar arasından -seçim yapar: `quota` (varsayılan), `autoSwitchThreshold` üzerinde olduğunda -`anthropicAccountPool.quotaWindow` ile yapılandırılan penceredeki bilinen en düşük kullanımı -seçer (`five-hour` varsayılandır; `weekly` ve `max-utilization` da kullanılabilir); `round-robin` eşit olarak dağıtır +seçim yapar: `quota` (varsayılan), etkin hesabı `anthropicAccountPool.quotaWindow` ile belirlenen penceredeki +kullanımı (`five-hour` varsayılandır; `weekly` ve `max-utilization` da kullanılabilir) +`autoSwitchThreshold` değerine (varsayılan 80) ulaşana kadar korur, sonra kendi eşiğinin altındaki hesapları tercih ederek en az kullanılan hesaba geçer; `round-robin` eşit olarak dağıtır (`stickyLimit`, varsayılan `1`); `fill-first`, bekleme süresi, yeniden kimlik doğrulama veya eşiğe kadar aktif hesabı tüketir, ardından ilerler. **Varsayılan olarak kapalıdır** ve deneyseldir. diff --git a/docs-site/src/content/docs/tr/reference/configuration/providers.md b/docs-site/src/content/docs/tr/reference/configuration/providers.md index 12f2004ed8b..1e155303344 100644 --- a/docs-site/src/content/docs/tr/reference/configuration/providers.md +++ b/docs-site/src/content/docs/tr/reference/configuration/providers.md @@ -55,9 +55,9 @@ Arayüzde kayıt veya OAuth girişi tamamlanınca Models sayfasını açan bir b | `activeCodexAccountId?` | `string` | — | Sonraki istek için manuel olarak seçilen Havuz hesabı. Seçim iş parçacığı bağlılığını temizler; devam eden istekler yakalanan kimlik bilgilerini korur. | | `codexAccountPriorities?` | `Record` | — | Codex havuzu için hesap başına seçim sırası: hesap kimliği → `-100` ile `100` arası tam sayı, **daha yüksek olan daha önce kullanılır**, yoksa `0` anlamına gelir. Bu bir öncelik sırası sınırıdır, bir uygunluk sınırı değildir: seçim, zaten uygun olan hesapları hala kota payı bulunan en yüksek katmana daraltır ve `accountPoolStrategy` daha sonra bu katman içinde seçim yapar. Bir katman, yalnızca her üye sıfırdan farklı kendi etkin eşiğine (hesaba özel değer veya genel varsayılan) ulaştığında, soğumada olduğunda, yumuşak kaçınıldığında, duraklatıldığında veya yeniden kimlik doğrulama gerektiğinde atlanır — bilinmeyen kota asla bir katmanı boşaltmaz. Sıralama asla uygun olmayan bir hesabı seçilebilir yapmaz ve zaten bir hesabı olan bir iş parçacığını asla yeniden bağlamaz. Ana `__main__` hesap eşit şartlarda katılır, bu sayede Codex Desktop girişi en son tükenecek şekilde ayarlanabilir. Hiçbir girdi olmadığında havuz tam olarak eskisi gibi davranır. Hatalı biçimlendirilmiş bir harita bir konsol uyarısıyla yok sayılır (sıralama kapalı, yapılandırma onarımı yok). `ocx account priority` ve Codex Auth sayfası tarafından yönetilir. | | `activeCodexAccountPinned?` | `string` | — | Operatörün en son elle seçtiği hesap kimliği. Ayarlandığı sürece, pin tükenme, hariç tutma, silme veya açık bir yük devretme/yükseltme ile serbest bırakılana kadar daha yüksek bir `codexAccountPriorities` katmanı onu öncelikleyemez. Sınırlı katman içindeki sıradan round-robin hareketi onu serbest bırakmaz. Herhangi bir `codexAccountPriorities` girdisi yazmak da pini serbest bırakır, böylece bir sıra var olmadan önce yapılan bir pin daha sonra ayarlanan bir pinin önüne geçemez. `GET /api/codex-auth/active`, hem geçerli hesabın sabitlenip sabitlenmediğini (`pinned`) hem de tavanı taşıyan hesabı (`pinnedAccountId`) bildirir. | -| `autoSwitchThreshold?` | `number` | `80` | Proaktif geçiş için kullanım eşiği. `quota`, bağımsız görevlerin bir sonraki isteğini yeniden değerlendirebilir. Bağlı görevler varsayılan olarak (`pool.cacheAffinity`) eşiğin ötesinde hesabını korur; hesap tükenene veya hizmet veremez hale gelene kadar kalır ve o zaman yalnızca kullanımı kesin olarak daha düşük ve gerçek kota payı olan bir hesaba geçer. `pool.cacheAffinity: false` ile bağlı görevler de bu eşikte yeniden değerlendirilir. `fill-first` bunu yalnızca bağımsız atama için tükenme noktası olarak kullanır; normal `round-robin` seçimi bunu kullanmaz. Puan, bilinen en sıcak 5 saatlik, haftalık veya 30 günlük kota penceresini kullanır. `0`, yalnızca kullanıma dayalı proaktif geçişi devre dışı bırakır, bağımsız atamayı veya arıza kurtarmayı devre dışı bırakmaz. | +| `autoSwitchThreshold?` | `number` | `80` | Proaktif geçiş için kullanım eşiği. `quota`, bağımsız görevlerin bir sonraki isteğini yeniden değerlendirebilir. Bağlı görevler varsayılan olarak (`pool.cacheAffinity`) eşiğin ötesinde hesabını korur; hesap tükenene veya hizmet veremez hale gelene kadar kalır ve o zaman yalnızca kullanımı kesin olarak daha düşük ve gerçek kota payı olan bir hesaba geçer. `pool.cacheAffinity: false` ile bağlı görevler de bu eşikte yeniden değerlendirilir. `fill-first` bunu yalnızca bağımsız atama için tükenme noktası olarak kullanır; `round-robin` bunu yalnızca yeni/bağımsız atamalarda kullanır: etkin eşiğinin altında uygun bir hesap kaldıkça eşiğine ulaşmış veya aşmış hesapları atlar ve bağlı bir görevi bu nedenle taşımaz. Puan, bilinen en sıcak 5 saatlik, haftalık veya 30 günlük kota penceresini kullanır. `0`, yalnızca kullanıma dayalı proaktif geçişi devre dışı bırakır, bağımsız atamayı veya arıza kurtarmayı devre dışı bırakmaz. | | `codexAccountAutoSwitchThresholds?` | `Record` | — | Hesap başına `autoSwitchThreshold` geçersiz kılmaları: hesap kimliği → `0`–`100` tam sayısı. Kayıt yoksa genel değer devralınır; `0` yalnızca bu hesaptan kullanıma dayalı geçişi kapatır. Ana `__main__` hesabı desteklenir. Codex Auth hesap kartından yönetilir. Hesaba özel değeri etkinleştirmek, mevcut genel eşiği sabit bir hesap değerine kopyalar. `0` dahil bu değer, genel eşik daha sonra değişse de önceliğini korur. Devre dışı bırakmak `threshold: null` gönderir, kaydı siler ve mevcut genel eşikle gelecekteki değişikliklerini devralmayı yeniden etkinleştirir. | -| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | Yeni/bağımsız Codex istekleri için atama stratejisi. Bir istek, canlı (üst iş parçacığı kimliği, kota kapsamı) bağlılığı olmadığında bağımsızdır; görünür mevcut bir görev, proxy yeniden başlatmasından veya bağlılık sıfırlamasından sonra bağımsız hale gelebilir. `quota`, aktif bir hesap olmadığında en düşük kullanımlı uygun hesabı seçer, `autoSwitchThreshold` altında uygun bir aktif hesabı tutar ve eşikten sonra bağımsız bir isteği taşıyabilir. Bağlı görevler `pool.cacheAffinity`'yi izler (varsayılan açık): hesap tükenene (bilinen kullanım %100) veya hizmet veremez hale gelene kadar kalır ve o zaman yalnızca kullanımı kesin olarak daha düşük ve gerçek kota payı olan bir hesaba geçer. Bayrağı `false` yapınca bağlı bir görev eşiğinde proaktif olarak daha düşük kullanımlı uygun bir hesaba yeniden bağlanabilir; hedef kısıtı yine geçerlidir. `round-robin`, bağımsız istekleri eşit olarak dağıtır; `fill-first`, soğuma, kullanılamama veya yapılandırılmış tükenme eşiğine kadar bağımsız istekleri aktif hesaba atamaya devam eder. `reset-first`: Eşiğin altındaki hesaplar arasından sonraki 5 saatlik veya haftalık sıfırlaması en yakın olanı seçer. Bağlı görevler yapılandırılmış bağlılık politikasını izler. Bağımsız model kotaları kullanıma göre sıralanır. Aylık sıfırlamalar bu sıralamayı belirlemez. | +| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | Yeni/bağımsız Codex istekleri için atama stratejisi. Bir istek, canlı (üst iş parçacığı kimliği, kota kapsamı) bağlılığı olmadığında bağımsızdır; görünür mevcut bir görev, proxy yeniden başlatmasından veya bağlılık sıfırlamasından sonra bağımsız hale gelebilir. `quota`, aktif bir hesap olmadığında en düşük kullanımlı uygun hesabı seçer, `autoSwitchThreshold` altında uygun bir aktif hesabı tutar ve eşikten sonra bağımsız bir isteği taşıyabilir. Bağlı görevler `pool.cacheAffinity`'yi izler (varsayılan açık): hesap tükenene (bilinen kullanım %100) veya hizmet veremez hale gelene kadar kalır ve o zaman yalnızca kullanımı kesin olarak daha düşük ve gerçek kota payı olan bir hesaba geçer. Bayrağı `false` yapınca bağlı bir görev eşiğinde proaktif olarak daha düşük kullanımlı uygun bir hesaba yeniden bağlanabilir; hedef kısıtı yine geçerlidir. `round-robin`, bağımsız istekleri etkin `autoSwitchThreshold` altında kalan uygun hesaplara eşit dağıtır; hepsi eşiğe ulaşmış veya aşmışsa tüm uygun hesaplara dağıtır; `fill-first`, soğuma, kullanılamama veya yapılandırılmış tükenme eşiğine kadar bağımsız istekleri aktif hesaba atamaya devam eder. `reset-first`: Eşiğin altındaki hesaplar arasından sonraki 5 saatlik veya haftalık sıfırlaması en yakın olanı seçer. Bağlı görevler yapılandırılmış bağlılık politikasını izler. Bağımsız model kotaları kullanıma göre sıralanır. Aylık sıfırlamalar bu sıralamayı belirlemez. | | `pool.cacheAffinity?` | `boolean` | `true` | Bağlı Codex iş parçacıkları için önbellek bağlılığı sıralaması; `pool.kernel`'dan bağımsızdır. Varsayılan olarak açıktır; anahtarı atlamak veya `true` vermek bağlamayı korur ve `false` dışındaki bir değer açık okunur. Canlı bağlama kota payından öndedir: `quota`, kullanımın `autoSwitchThreshold`'u geçmesi nedeniyle iş parçacığını taşımaz, çünkü canlı bir konuşmayı taşımak hesaba özel istem önbelleğini atar. Hesap duraklatılmış, kullanılamaz, plandan dışlanmış, kimlik bilgisi geçersiz, generation değişmiş, TTL dolmuş, 429/402 kota reddi almış veya gerçekten tükenmişse (bilinen kullanım %100) iş parçacığı yine ayrılır ve yalnızca kullanımı kesin olarak daha düşük ve gerçek kota payı olan bir hesaba geçer. Kullanımı bilinmeyen bir hesap bağlı bir görev için hedef olarak asla seçilmez. Tüm hesaplar eşiğin üzerindeyse bağlı görev yerinde kalır; daha iyi bir hedef yoktur. `false` eşiğe göre yeniden bağlamayı geri getirir; hedef kısıtı yine geçerlidir. Bağlılık bir sabitleme değil yeniden sıralamadır. | | `accountPoolStickyLimit?` | `number` | `1` | İlerlemeden önce bir round-robin seçiminde tutulan yeni/bağımsız görev atamaları; sayaç yukarı akış başarısından sonra değil, bir görev bağlandığında ilerler. Aralık 1–100. | | `upstreamFailoverThreshold?` | `number` | `3` | Gelecekteki yeni oturumların yük devretmesinden önceki ardışık geçici arızalar. Devre dışı bırakmak için `0` ayarlayın. Düzenli Responses ve yerel sıkıştırma gönderimleri için kanıtlanmış bağlantı öncesi DNS/TCP erişilebilirlik arızaları sağlayıcı-ana bilgisayar düzeyinde izlenir: hesap sağlığını, hesap soğuma sürelerini, iş parçacığı/oturum bağlılığını, aktif hesap seçimini veya Havuz yönlendirmesini asla etkilemez ve bu eşiğe asla sayılmaz. | @@ -281,7 +281,7 @@ kalır. | Strateji | Davranış | | --- | --- | | `quota` (varsayılan) | Aktif bir hesap yoksa 5 saatlik, haftalık ve 30 günlük pencerelerde en düşük kullanımlı uygun hesabı seçin. Aksi takdirde `autoSwitchThreshold` altında uygun bir aktif hesabı tutun; eşiği aştıktan sonra bağımsız bir istek daha düşük kullanımlı uygun bir hesaba geçebilir. Bağlı görevler varsayılan olarak önbellek bağlılığını korur ve hesap tükenene (bilinen kullanım %100) veya hizmet veremez hale gelene (duraklatılmış, kullanılamaz) kadar kalır; bir geçiş o zaman hedefte gerçek kota payı ve kesin olarak daha düşük kullanım ister. `pool.cacheAffinity: false` ile bağlı bir görevin bir sonraki isteği eşikte hareket edebilir, yine yalnızca gerçek kota payı olan daha düşük kullanımlı uygun bir hesaba. `0`, bu kullanım odaklı yeniden değerlendirmeyi devre dışı bırakır, arıza kurtarmayı devre dışı bırakmaz. | -| `round-robin` | Bağımsız istekleri uygun hesaplar arasında eşit olarak atayın. Dönüş sayaç tabanlıdır ve kullanım eşiklerini dikkate almaz; ancak ortak öncelik katmanı filtresi her hesabın kota payını kendi etkin eşiğine (hesaba özel değer veya genel varsayılan) göre değerlendirir. `accountPoolStickyLimit` (1–100), başarılı yukarı akış yanıtlarını değil, bir seçimdeki atamaları sayar. | +| `round-robin` | Dönüş sayaç tabanlıdır. Yeni atama, etkin `autoSwitchThreshold` altında uygun hesap kaldıkça eşiğe ulaşmış veya aşmış hesapları atlar (hesaba özel değer veya genel varsayılan; puanlama `quota` ile aynı). Bilinmeyen kullanım ve `0` eşiği eşik altı sayılır; tüm uygun hesaplar eşiğe ulaşmışsa dönüş hepsini kapsar. Bağlı görev eşiği aşınca hesabını korur ve yalnızca hesap hizmet veremediğinde (soğuma, kota reddi, yük devretme, duraklatma) taşınır. Canlı konuşmanın alt görevi ebeveyninin kullandığı hesapta başlar. Ortak öncelik katmanı filtresi kota payını aynı şekilde değerlendirir. Operatörün elle yaptığı seçim, kullanımından bağımsız olarak her kota kapsamındaki bir sonraki atamayı alır; o kapsamda bu hesaptaki başarılı bir istek seçimi tüketir ve oradaki sonraki atamalar eşiği yeniden uygular. `accountPoolStickyLimit` (1–100), başarılı yukarı akış yanıtlarını değil, bir seçimdeki atamaları sayar. | | `fill-first` | Bağımsız istekleri soğuma, yeniden kimlik doğrulama veya bu hesabın etkin tükenme eşiğine (hesaba özel değer veya genel varsayılan) kadar aktif hesaba atayın; bilinmeyen kullanım geçişe zorlamaz. Sağlıklı bağlı görevler bağlılığı korur. | Rotasyon, sağlayıcı yaptırımlarına karşı koruma sağlamaz; çoklu hesap kullanımı @@ -297,9 +297,9 @@ ve otomatik rotasyon sağlayıcı kısıtlamalarını tetikleyebilir. | Anahtar | Tip | Varsayılan | Açıklama | | --- | --- | --- | --- | | `anthropicAccountPool.enabled?` | `boolean` | `false` | Yapışkan oturum bağlılığını ve kullanıma dayalı yeni oturum seçimini etkinleştirir. **429 yük devretmesi buradan kontrol edilmez**: iki veya daha fazla kullanılabilir hesap saklandığında, diğer çok kimlikli sağlayıcılarda olduğu gibi devreye girer ve kapatılamaz. | -| `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` | Yeni oturumlarda etkin hesap bu eşiğe ulaştığında, yapılandırılan penceredeki bilinen en düşük önbelleğe alınmış kullanımı seçin. `0` kota seçimini devre dışı bırakır. | -| `anthropicAccountPool.strategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` | Yeni oturum stratejisi; `quota`, `quotaWindow` ile belirlenen pencereye (varsayılan 5 saatlik çubuklar) göre hesapları sıralar ve `fill-first` de tükenme eşiğini aynı pencerede değerlendirir. | -| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` | Kullanıma dayalı hesap seçiminde kullanılan, sağlayıcının bildirdiği önbelleğe alınmış kullanım çubuğu. `five-hour` mevcut davranışı korur. `weekly` haftalık çubuğu kullanır ve başka uygun hesap kaldığı sürece 5 saatlik çubuğu tükenmiş hesapları atlar; hiçbiri kalmazsa bu hesaplara geri döner. `max-utilization` bilinen en yüksek değeri kullanır; haftalık değer henüz yokken 5 saatlik değeri kullanabilir, ikisi de bilinmiyorsa hesap unknown kullanım sırasını izler. Bilinen kullanım unknown değerlerden önce gelir; tüm uygun hesaplar unknown olsa bile uygun sıradaki bir hesap seçilir. Belgelenen daha düşük 5 saatlik kullanım eşitlik bozmasından sonra tam eşitlikte de uygun sıra korunur. Sağlıklı affinity oturumları önceden yeniden dengelenmez. Yeni oturum ataması ve uygun bir 429 yedeğine geçildikten sonraki yönlendirme kurtarmasında `quota`, uygun adayları doğrudan bu pencereye göre sıralar; `fill-first`, bu pencerenin eşik ve tükenme kurallarıyla kararlı sırada ilerler; `round-robin` ayarı yok sayar. Cooldown, yük devretme sınırları ve yeniden kimlik doğrulama uygunluğu ayrı yerel durum olarak kalır. Hesap başına haftalık çubuklar ancak dashboard Sağlayıcılar sayfasında sorgulandıktan sonra bilinir. | +| `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` | Yeni oturumlarda etkin hesap bu eşiğe ulaştığında yapılandırılmış penceredeki bilinen önbellek kullanımı en düşük hesap seçilir ve kendi eşiğinin altındaki hesaplar tercih edilir; seçilen hesabın kendisinin eşiğe ulaşması gerekmez. `0` yalnızca kullanıma dayalı proaktif geçişi kapatır; yeni oturum seçimi ve uygun 429 sonrası yönlendirme kurtarması yine `quotaWindow` kullanır. | +| `anthropicAccountPool.strategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` | Yeni oturum stratejisi. `quota`, etkin hesabı `quotaWindow` kullanımının etkin `autoSwitchThreshold` değerine (varsayılan 80) ulaşmasına veya hesabın hizmet verememesine kadar korur; sonra kendi eşiğinin altındaki hesapları tercih ederek en az kullanılan hesaba geçer. Kullanım bilinmiyorsa etkin hesap korunur. `round-robin` kullanım eşiklerini okumadan yeni oturumları döndürür. `fill-first` tükenme eşiğini `quotaWindow` içinde değerlendirir. | +| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` | Kullanıma dayalı hesap seçiminde kullanılan, sağlayıcının bildirdiği önbelleğe alınmış kullanım çubuğu. `five-hour` mevcut davranışı korur. `weekly` haftalık çubuğu kullanır ve başka uygun hesap kaldığı sürece 5 saatlik çubuğu tükenmiş hesapları atlar; hiçbiri kalmazsa bu hesaplara geri döner. `max-utilization` bilinen en yüksek değeri kullanır; haftalık değer henüz yokken 5 saatlik değeri kullanabilir, ikisi de bilinmiyorsa hesap unknown kullanım sırasını izler. Bilinen kullanım unknown değerlerden önce gelir; tüm uygun hesaplar unknown olsa bile uygun sıradaki bir hesap seçilir. Belgelenen daha düşük 5 saatlik kullanım eşitlik bozmasından sonra tam eşitlikte de uygun sıra korunur. Sağlıklı affinity oturumları önceden yeniden dengelenmez. `quota` bir yedek seçtiğinde (etkin hesabı eşiğe ulaşmış veya hizmet veremeyen yeni oturum ya da uygun bir 429 sonrası kurtarma), kendi eşiğinin altındaki adayları tercih eder ve bu pencereye göre sıralar; `fill-first`, bu pencerenin eşik ve tükenme kurallarıyla kararlı sırada ilerler; `round-robin` ayarı yok sayar. Cooldown, yük devretme sınırları ve yeniden kimlik doğrulama uygunluğu ayrı yerel durum olarak kalır. Hesap başına haftalık çubuklar kullanım yoklamalarından veya gözlemlenen yanıt başlıklarından gelir. | | `anthropicAccountPool.stickyLimit?` | `number` | `1` | Bir round-robin seçiminde tutulan başarılı yeni oturum bağlamaları. Aralık 1–100. | Yalnızca ortak 5 saatlik veya haftalık kotanın reddini doğrulayan 429 hesabı soğutur ve değiştirir. Geçici hız sınırı bağlılığı koruyarak hesap kabulünü duraklatır; istek başına aynı hesapta bir kısa yeniden deneme ve uygun başka hesaba bir geçiş yapılabilir. Kanıt başlığı olmayan 429 yalnızca aynı hesapta bir kısa yeniden denemeye izin verir, hesabı soğutmaz ve Retry-After üretmez. Varsayılan tek hesap davranışı değişmez. Fable reddi Sonnet erişimini engellemez; elle seçim ve bağlılık da istenen modelin ortak ve aile kotalarını denetler. Pasif aile bilgisi otuz dakika veya bilinen sıfırlama anında eskir ve tek bir hizmet isteğiyle yeniden doğrulanır. Eşikler esnek tercihlerdir; tüm adaylar tükenince mevcut geri dönüş korunur. Bunlar katı kullanım veya faturalama tavanları değildir. Bağlılık işleme özeldir ve diff --git a/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md b/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md index bc201ce0b73..49c984a6a29 100644 --- a/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md +++ b/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md @@ -53,9 +53,9 @@ ocx models provider openrouter on | `codexAccountPickerEnabled?` | `boolean` | 映射为空时关闭 | 控制是否根据有效的 `codexAccountNamespaces` 映射生成账户限定的 Codex 选择器行。`true` 允许显示映射行。在非空映射中省略此字段时,为保持向后兼容会视为已启用;映射为空时则关闭。`false` 会隐藏生成行并恢复选择器中的裸原生行,但不会删除映射,也不会禁用精确的 `/` 路由。 | | `activeCodexAccountId?` | `string` | — | 为下一次请求手动选定的 Pool 账户。选择会清除线程亲和性;进行中的请求会保留捕获到的凭据。 | | `codexAccountPriorities?` | `Record` | — | Codex pool 各账号的选择顺序:账号 ID → `-100` 到 `100` 的整数,**数值越大越先使用**,未设置即为 `0`。这是顺序边界而非资格边界:选择会把已经合格的账号收窄到仍有 quota 余量的最高 tier,再由 `accountPoolStrategy` 在该 tier 内挑选。只有当某个 tier 的所有成员都达到各自非零的有效阈值(账号覆盖值,未设置则使用全局值)、处于 cooldown、被 soft-avoid、已暂停或需要重新认证时,该 tier 才会被跳过;usage 未知不会让 tier 耗尽。顺序不会让不合格的账号变得可选,也不会重新绑定已经绑定账号的 thread。主账号 `__main__` 同样参与排序,因此可以让 Codex Desktop 登录账号最后才被用到。没有任何条目时,行为与以往完全一致。映射格式非法时会打印警告并关闭排序(不会触发 config 修复)。可通过 `ocx account priority` 和 Codex Auth 页面管理。 | -| `autoSwitchThreshold?` | `number` | `80` | 基于用量的主动切换阈值。`quota` 可在下一次请求中重新评估未绑定任务。已绑定任务默认(`pool.cacheAffinity`)在越过阈值后仍保留账号,直到该账号耗尽或无法继续服务,并且只改绑到确有额度余量且 usage 严格更低的账号。将 `pool.cacheAffinity` 设为 `false` 才会在该阈值重新评估已绑定任务。`fill-first` 仅把它用作未绑定分配的耗尽点;正常 `round-robin` 不使用它。分数取已知 5 小时、周或 30 天 quota window 的最高值。`0` 只关闭基于用量的主动切换,不关闭未绑定任务分配或故障恢复。 | +| `autoSwitchThreshold?` | `number` | `80` | 基于用量的主动切换阈值。`quota` 可在下一次请求中重新评估未绑定任务。已绑定任务默认(`pool.cacheAffinity`)在越过阈值后仍保留账号,直到该账号耗尽或无法继续服务,并且只改绑到确有额度余量且 usage 严格更低的账号。将 `pool.cacheAffinity` 设为 `false` 才会在该阈值重新评估已绑定任务。`fill-first` 仅把它用作未绑定分配的耗尽点;`round-robin` 仅在新建/未绑定任务分配时使用它:只要仍有低于自身有效阈值的合格账号,就跳过达到或超过阈值的账号,且不会因此移动已绑定任务。分数取已知 5 小时、周或 30 天 quota window 的最高值。`0` 只关闭基于用量的主动切换,不关闭未绑定任务分配或故障恢复。 | | `codexAccountAutoSwitchThresholds?` | `Record` | — | 各账号对 `autoSwitchThreshold` 的覆盖:账号 ID → `0`–`100` 的整数。没有条目时继承全局值;`0` 只关闭从该账号发起的基于用量的切换。支持主账号 `__main__`。可在 Codex Auth 的账号卡片中管理。 启用覆盖时,会将当前全局阈值复制为固定的账号值。覆盖值(包括 `0`)在之后修改全局阈值时仍优先。禁用时发送 `threshold: null`,删除条目,并恢复继承当前全局阈值及其未来的更改。 | -| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | 新建/未绑定 Codex 请求的分配策略。没有 live `(parent thread id, quota scope)` affinity 的请求属于未绑定;代理重启或 affinity 重置后,已有可见任务也可能未绑定。`quota` 在没有活跃账号时选择已知 usage 最低的合格账号;活跃账号合格且低于 `autoSwitchThreshold` 时继续使用;达到阈值后,可把未绑定请求切换到 usage 更低的合格账号。已绑定任务默认会保留到账号耗尽(已知 usage 为 100%)或无法继续服务,改绑时只前往确有额度余量且 usage 严格更低的账号。关闭该标志后,也可在该阈值把已绑定任务的下一次请求改绑到确有额度余量且 usage 严格更低的账号。`round-robin` 均匀分配未绑定请求;`fill-first` 在 cooldown、不可用或耗尽阈值前持续分配给活跃账号。 `reset-first`: 在低于用量阈值的账号中,优先选择下次5小时或周额度重置最早的账号。已绑定任务遵循配置的亲和策略。独立模型额度按用量排序。 此排序不使用月额度重置时间。 | +| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | 新建/未绑定 Codex 请求的分配策略。没有 live `(parent thread id, quota scope)` affinity 的请求属于未绑定;代理重启或 affinity 重置后,已有可见任务也可能未绑定。`quota` 在没有活跃账号时选择已知 usage 最低的合格账号;活跃账号合格且低于 `autoSwitchThreshold` 时继续使用;达到阈值后,可把未绑定请求切换到 usage 更低的合格账号。已绑定任务默认会保留到账号耗尽(已知 usage 为 100%)或无法继续服务,改绑时只前往确有额度余量且 usage 严格更低的账号。关闭该标志后,也可在该阈值把已绑定任务的下一次请求改绑到确有额度余量且 usage 严格更低的账号。`round-robin` 在有效 `autoSwitchThreshold` 以下的合格账号间均匀分配未绑定请求,若全部达到或超过阈值则在所有合格账号间分配;`fill-first` 在 cooldown、不可用或耗尽阈值前持续分配给活跃账号。 `reset-first`: 在低于用量阈值的账号中,优先选择下次5小时或周额度重置最早的账号。已绑定任务遵循配置的亲和策略。独立模型额度按用量排序。 此排序不使用月额度重置时间。 | | `pool.cacheAffinity?` | `boolean` | `true` | 已绑定 Codex 线程的 cache-affinity 排序,独立于 `pool.kernel`。默认开启;省略该键或设为 `true` 即为开启,非法值视为开启。live 绑定优先于 quota 余量:`quota` 不会仅因用量越过 `autoSwitchThreshold` 就移动线程。账号暂停、不可用或真正耗尽(已知 usage 为 100%)时仍会离开,且只改绑到确有额度余量且 usage 严格更低的账号。用量未知的账号不会作为已绑定任务的改绑目标。设为 `false` 可恢复按阈值改绑。affinity 是重排而非钉死。 | | `accountPoolStickyLimit?` | `number` | `1` | 一次 round-robin 选择在推进前保留的新建/未绑定任务分配数。计数在任务绑定时增加,而不是在上游成功后增加。范围 1–100;仅当 `accountPoolStrategy` 为 `round-robin` 时生效。 | | `upstreamFailoverThreshold?` | `number` | `3` | 连续发生多少次瞬态故障后,后续新会话会切换到备用上游。设为 `0` 可禁用。对于常规 Responses 和原生 compact 发送,已证明的连接前 DNS/TCP 不可达故障按 provider-host 粒度记录,不影响账户健康、账户冷却、线程/会话亲和性、活动账户选择或 Pool 路由,也不会计入此阈值。 | @@ -261,8 +261,7 @@ routing。未绑定请求没有 live 账号绑定,也可能是代理重启或 并可将请求切换到另一个符合条件的 Pool 账户。即使 `autoSwitchThreshold: 0`, 这些故障恢复流程仍然有效;`0` 只会禁用基于用量的主动切换。 -**分配与主动切换策略:** `quota`(默认)在没有活跃账号时选择 usage 最低的合格账号;活跃账号合格且低于 `autoSwitchThreshold` 时继续使用;达到阈值后,可把未绑定请求切换到 usage 更低的合格账号。默认下 cache affinity 优先于 quota 余量,已绑定任务会保留到账号耗尽(已知 usage 为 100%)或无法继续服务,改绑时只前往确有额度余量且 usage 严格更低的账号。关闭该标志后,也可在该阈值把已绑定任务的下一次请求改绑到确有额度余量且 usage 严格更低的账号。`round-robin` 均匀分配未绑定请求,用量 -阈值不会改变正常轮换。`accountPoolStickyLimit`(默认 `1`,1–100)统计分配/绑定,而不是成功响应。 +**分配与主动切换策略:** `quota`(默认)在没有活跃账号时选择 usage 最低的合格账号;活跃账号合格且低于 `autoSwitchThreshold` 时继续使用;达到阈值后,可把未绑定请求切换到 usage 更低的合格账号。默认下 cache affinity 优先于 quota 余量,已绑定任务会保留到账号耗尽(已知 usage 为 100%)或无法继续服务,改绑时只前往确有额度余量且 usage 严格更低的账号。关闭该标志后,也可在该阈值把已绑定任务的下一次请求改绑到确有额度余量且 usage 严格更低的账号。`round-robin`:轮换基于计数器。新分配在仍有低于有效 `autoSwitchThreshold` 的合格账号时,跳过达到或超过阈值的账号(账号覆盖值或全局默认值,评分与 `quota` 相同);用量未知或阈值为 `0` 均视为低于阈值。所有合格账号均达到或超过阈值时,轮换涵盖全部账号。已绑定任务超过阈值仍保留账号,仅在账号无法服务(cooldown、配额拒绝、故障转移、暂停)时移动;活跃会话的子任务从父任务使用的账号开始。共用优先级层级筛选以相同方式评估余量。运营者的手动选择会在每个 quota 范围内获得下一次分配,无论其用量如何;该范围内对该账号的请求成功后,此选择即被消耗,之后在该范围内的分配重新应用阈值。`accountPoolStickyLimit`(默认 `1`,1–100)统计分配/绑定,而不是成功响应。 `fill-first` 在 cooldown、重新认证或耗尽阈值前把未绑定请求分配给活跃账号;健康的已绑定任务保持 affinity。这些策略不能规避 provider enforcement。 @@ -273,9 +272,9 @@ affinity。这些策略不能规避 provider enforcement。 | 键 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | | `anthropicAccountPool.enabled?` | `boolean` | `false` | 启用粘性会话亲和性与基于用量的新会话选择。**429 故障转移不由此开关控制**:只要存有两个及以上可用账号就会生效,与其他多凭据提供方一致,且无法关闭。 | -| `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` | 对于新会话,当活动账户达到此阈值时,选择配置窗口中已知缓存使用率最低的账户。`0` 会禁用配额选择。 | -| `anthropicAccountPool.strategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` | 新会话策略;`quota` 按 `quotaWindow` 指定的窗口(默认是 5 小时条形数据)对账户排序,`fill-first` 也在同一窗口中判定其耗尽阈值。 | -| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` | 基于用量选择账户时使用的、由提供商报告并缓存的用量条。`five-hour` 保持原有行为。`weekly` 使用每周用量条,并在仍有其他可用账户时跳过 5 小时用量已耗尽的账户;若没有其他账户,则回退使用这些账户。`max-utilization` 使用已知值中的最高值,因此每周用量尚不可用时仍可使用 5 小时用量;两者都未知时,账户遵循 unknown 用量排序。已知用量排在 unknown 之前,但如果所有可用账户都未知,仍会按可用顺序选择一个账户。在前述较低 5 小时用量的同分判定之后,完全相同时也保留可用顺序。不会主动重新平衡健康且已建立亲和性的会话。在新会话分配和符合条件的 429 替代后的路由恢复中,`quota` 直接按此窗口对可用候选账户排序;`fill-first` 按此窗口的阈值和耗尽规则以稳定顺序前进;`round-robin` 忽略此设置。冷却状态、故障转移上限和重新认证资格仍是独立的本地状态。各账户的每周用量只有在控制面板的提供商页面完成查询后才可用。 | +| `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` | 对于新会话,当活跃账号达到此阈值时,选择配置窗口中已知缓存用量最低的账号,并优先选择低于自身阈值的账号;所选账号本身不必达到阈值。`0` 只禁用基于用量的主动切换;新会话选择和符合条件的 429 后路由恢复仍会使用 `quotaWindow`。 | +| `anthropicAccountPool.strategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` | 新会话策略。`quota` 保留活跃账号,直到其 `quotaWindow` 用量达到有效 `autoSwitchThreshold`(默认 80)或无法服务,再转到用量最低的账号,优先选择低于自身阈值的账号;用量未知时保留活跃账号。`round-robin` 不读取用量阈值,轮换新会话。`fill-first` 在 `quotaWindow` 中评估耗尽阈值。 | +| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` | 基于用量选择账户时使用的、由提供商报告并缓存的用量条。`five-hour` 保持原有行为。`weekly` 使用每周用量条,并在仍有其他可用账户时跳过 5 小时用量已耗尽的账户;若没有其他账户,则回退使用这些账户。`max-utilization` 使用已知值中的最高值,因此每周用量尚不可用时仍可使用 5 小时用量;两者都未知时,账户遵循 unknown 用量排序。已知用量排在 unknown 之前,但如果所有可用账户都未知,仍会按可用顺序选择一个账户。在前述较低 5 小时用量的同分判定之后,完全相同时也保留可用顺序。不会主动重新平衡健康且已建立亲和性的会话。当 `quota` 选择替代账号时(活跃账号达到阈值或无法服务的新会话,或符合条件的 429 后恢复),优先选择低于自身阈值的候选账号并按此窗口排序;`fill-first` 按此窗口的阈值和耗尽规则以稳定顺序前进;`round-robin` 忽略此设置。冷却状态、故障转移上限和重新认证资格仍是独立的本地状态。各账户的每周用量来自用量探测或观察到的响应头。 | | `anthropicAccountPool.stickyLimit?` | `number` | `1` | 在一次轮询选择中保留的成功新会话绑定次数。范围 1–100。 | 只有共享5小时或每周额度明确拒绝的429才会冷却账户并切换。临时速率限制保留亲和性,只暂停该账户的请求准入;每个请求最多一次短暂的同账户重试和一次合格兄弟账户切换。没有依据响应头的429只允许一次同账户短暂重试,不冷却账户,也不生成Retry-After。默认单账户行为不变。Fable专属拒绝不限制Sonnet;手动选择和亲和性均检查请求模型的共享与家族额度。被动家族信息在30分钟或已知重置时到期,由一个服务请求串行重新验证。使用阈值仍是软偏好,全部候选耗尽时保留原有回退,不是用量或账单硬上限。亲和性是进程本地的,并且有大小上限。令牌刷新失败保留原有重新认证规则。明确的订阅或账户计费 403 可在输出前切换账户,并按 `Retry-After` 或默认十分钟冷却;普通权限拒绝不会切换。如果所有合格账户都在冷却,客户端会在已知时收到带 `Retry-After` 的 429,而不是身份验证错误。 diff --git a/docs-site/src/content/docs/zh-tw/guides/claude-code.md b/docs-site/src/content/docs/zh-tw/guides/claude-code.md index 5c921ee4a34..bba0718e4dd 100644 --- a/docs-site/src/content/docs/zh-tw/guides/claude-code.md +++ b/docs-site/src/content/docs/zh-tw/guides/claude-code.md @@ -14,9 +14,9 @@ Code 可以使用每一個已路由的供應商——包括 OAuth 登入、帳 **實驗性、opt-in** 的 Claude 帳號池(`anthropicAccountPool.enabled`)會在這些 OAuth 帳號之間加入 sticky session affinity 與依用量的新工作階段選擇。它**不**控制 429 容錯移轉:只要儲存了兩個以上可用帳號,被限流的請求無論此開關開或關都會切換到另一個帳號,且無法關閉。僅對**新**工作階段,`anthropicAccountPool.strategy` -會在合格帳號之間選擇:`quota`(預設)在用量高於 `autoSwitchThreshold` 時,依 -`anthropicAccountPool.quotaWindow` 所設定的視窗挑選已知用量最低者(`five-hour` 為預設,亦可選 -`weekly` 或 `max-utilization`); +會在合格帳號之間選擇:`quota`(預設)保留現用帳號,直到 `anthropicAccountPool.quotaWindow` 所設定視窗的用量 +(`five-hour` 為預設,亦可選 `weekly` 或 `max-utilization`)達到 `autoSwitchThreshold` +(預設 80),然後轉到用量最低的帳號,並優先選擇低於自身閾值的帳號; `round-robin` 平均分散(`stickyLimit`,預設 `1`);`fill-first` 一直使用作用中帳號直到冷卻、重新認證 或達到閾值,然後前進。它**預設關閉**,仍屬實驗性功能。 diff --git a/docs-site/src/content/docs/zh-tw/reference/configuration/providers.md b/docs-site/src/content/docs/zh-tw/reference/configuration/providers.md index 5a430f66c07..b3e75e1da34 100644 --- a/docs-site/src/content/docs/zh-tw/reference/configuration/providers.md +++ b/docs-site/src/content/docs/zh-tw/reference/configuration/providers.md @@ -51,9 +51,9 @@ ocx models provider openrouter on | `pausedCodexAccountIds?` | `string[]` | `[]` | 被排除於池選擇直到恢復的帳號,包含暫停時的 main `__main__` 帳號。 手動暫停或恢復會同步更新同一帳號、同一工作區的主登入與池內既有入口。 | | `codexAccountNamespaces?` | `Record` | — | 公開模型選擇器命名空間到已儲存 Codex 帳號目標。這會驗證並持久化映射,但不會自行新增 picker 列或變更路由。 | | `activeCodexAccountId?` | `string` | — | 為下一個請求手動選擇的池帳號。選擇清除執行緒親和性;進行中的請求保留擷取的憑證。 | -| `autoSwitchThreshold?` | `number` | `80` | 主動切換的用量閾值。`quota` 可在下一個請求時重新評估未綁定任務。綁定任務預設(`pool.cacheAffinity`)在越過閾值後仍會保留帳號,直到該帳號耗盡或無法繼續服務,並且只改綁到確有額度餘裕且用量嚴格更低的帳號。將 `pool.cacheAffinity` 設為 `false` 才會在此閾值重新評估綁定任務。`fill-first` 僅將其用作未綁定指派的排空點;一般 `round-robin` 選擇不使用它。分數使用最熱的已知 5h、週或 30d 配額視窗。`0` 僅停用基於用量的主動切換,而非未綁定指派或失敗復原。 | +| `autoSwitchThreshold?` | `number` | `80` | 主動切換的用量閾值。`quota` 可在下一個請求時重新評估未綁定任務。綁定任務預設(`pool.cacheAffinity`)在越過閾值後仍會保留帳號,直到該帳號耗盡或無法繼續服務,並且只改綁到確有額度餘裕且用量嚴格更低的帳號。將 `pool.cacheAffinity` 設為 `false` 才會在此閾值重新評估綁定任務。`fill-first` 僅將其用作未綁定指派的排空點;`round-robin` 僅在新/未綁定工作指派時使用它:只要仍有低於自身有效閾值的合格帳號,就略過達到或超過閾值的帳號,且不會因此移動已綁定任務。分數使用最熱的已知 5h、週或 30d 配額視窗。`0` 僅停用基於用量的主動切換,而非未綁定指派或失敗復原。 | | `codexAccountAutoSwitchThresholds?` | `Record` | — | 各帳號對 `autoSwitchThreshold` 的覆寫:帳號 ID → `0`–`100` 的整數。沒有項目時繼承全域值;`0` 只停用從該帳號發起的使用量主動切換。支援主帳號 `__main__`。可在 Codex Auth 的帳號卡片中管理。 啟用覆寫時,會將目前全域閾值複製為固定的帳號值。覆寫值(包括 `0`)在之後修改全域閾值時仍優先。停用時傳送 `threshold: null`,刪除項目,並恢復繼承目前全域閾值及其未來的變更。 | -| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | 新/未綁定 Codex 請求的指派策略。當請求沒有即時(父執行緒 id、配額 scope)親和性時即為未綁定;可見的既有任務在代理重啟或親和性重置後可變為未綁定。`quota` 在無現用帳號時選擇最低用量的合格帳號,將合格現用帳號保持在 `autoSwitchThreshold` 以下,且在閾值後可將未綁定請求移至較低用量的合格帳號。綁定任務預設會保留到帳號耗盡(已知用量 100%)或無法繼續服務,改綁時只前往確有額度餘裕且用量嚴格更低的帳號。關閉該設定後,也可在閾值將綁定任務的下一個請求改綁到確有額度餘裕且用量嚴格更低的帳號。`round-robin` 均勻分配未綁定請求;`fill-first` 持續將未綁定請求指派到現用帳號直到冷卻、不可用或設定的排空閾值。 `reset-first`: 在低於用量門檻的帳號中,優先選擇下次5小時或週額度重設最早的帳號。已綁定任務遵循設定的親和策略。獨立模型額度按用量排序。 此排序不使用月額度重設時間。 | +| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | 新/未綁定 Codex 請求的指派策略。當請求沒有即時(父執行緒 id、配額 scope)親和性時即為未綁定;可見的既有任務在代理重啟或親和性重置後可變為未綁定。`quota` 在無現用帳號時選擇最低用量的合格帳號,將合格現用帳號保持在 `autoSwitchThreshold` 以下,且在閾值後可將未綁定請求移至較低用量的合格帳號。綁定任務預設會保留到帳號耗盡(已知用量 100%)或無法繼續服務,改綁時只前往確有額度餘裕且用量嚴格更低的帳號。關閉該設定後,也可在閾值將綁定任務的下一個請求改綁到確有額度餘裕且用量嚴格更低的帳號。`round-robin` 在有效 `autoSwitchThreshold` 以下的合格帳號間均勻分配未綁定請求,若全部達到或超過閾值則在所有合格帳號間分配;`fill-first` 持續將未綁定請求指派到現用帳號直到冷卻、不可用或設定的排空閾值。 `reset-first`: 在低於用量門檻的帳號中,優先選擇下次5小時或週額度重設最早的帳號。已綁定任務遵循設定的親和策略。獨立模型額度按用量排序。 此排序不使用月額度重設時間。 | | `pool.cacheAffinity?` | `boolean` | `true` | 綁定 Codex 執行緒的 cache-affinity 排序,獨立於 `pool.kernel`。預設開啟;省略該鍵或設為 `true` 即為開啟,格式錯誤視為開啟。即時綁定優先於配額餘裕:`quota` 不會只因用量越過 `autoSwitchThreshold` 就移動執行緒。帳號暫停、無法使用或真正耗盡(已知用量 100%)時仍會離開,且只改綁到確有額度餘裕且用量嚴格更低的帳號。用量未知的帳號不會作為綁定任務的改綁目標。設為 `false` 可恢復依閾值重新綁定。親和性是重排而非釘死。 | | `accountPoolStickyLimit?` | `number` | `1` | 在前進一個 round-robin 選擇前保留的新/未綁定任務指派;計數器在任務綁定時前進,而非在上游成功後。範圍 1–100。 | | `upstreamFailoverThreshold?` | `number` | `3` | 未來新 session 容錯移轉前的連續暫時性失敗。設 `0` 停用。 | @@ -196,7 +196,7 @@ API-key 供應商可持有字面值金鑰或環境參考。OAuth 供應商使用 | 策略 | 行為 | | --- | --- | | `quota`(預設) | 若無現用帳號,跨 5 小時、週與 30 天視窗選擇最低用量的合格帳號。否則將合格現用帳號保持在 `autoSwitchThreshold` 以下;在超過閾值後,未綁定請求可移至較低用量的合格帳號。預設下 cache affinity 優先於配額餘裕,綁定任務會保留到帳號耗盡(已知用量 100%)或無法繼續服務,改綁時只前往確有額度餘裕且用量嚴格更低的帳號。關閉該設定後,也可在閾值將綁定任務的下一個請求改綁到確有額度餘裕且用量嚴格更低的帳號。`0` 停用此用量驅動的重新評估,而非失敗復原。 | -| `round-robin` | 在合格帳號間均勻指派未綁定請求。輪替本身以計數器為基礎,不使用用量閾值,但共用的優先順序層級篩選仍依各帳號自身的有效閾值(帳號覆寫值,未設定則使用全域值)檢查餘裕。`accountPoolStickyLimit`(1–100)計數一次選擇上的指派,而非成功的上游回應。 | +| `round-robin` | 輪替以計數器為基礎。新指派在仍有低於有效 `autoSwitchThreshold` 的合格帳號時,略過達到或超過閾值的帳號(帳號覆寫值或全域預設值,評分與 `quota` 相同);用量未知或閾值為 `0` 均視為低於閾值。所有合格帳號均達到或超過閾值時,輪替涵蓋全部帳號。已綁定任務超過閾值仍保留帳號,僅在帳號無法服務(冷卻、配額拒絕、容錯移轉、暫停)時移動;活躍對話的子任務從父任務使用的帳號開始。共用優先順序層級篩選以相同方式評估餘裕。操作者的手動選擇會在每個配額 scope 中取得下一次指派,不論其用量;該 scope 中對此帳號的請求成功後,此選擇即被消耗,之後在該 scope 的指派會再次套用閾值。 `accountPoolStickyLimit`(1–100)計數一次選擇上的指派,而非成功的上游回應。 | | `fill-first` | 將未綁定請求指派到現用帳號直到冷卻、重新認證或該帳號的有效排空閾值(帳號覆寫值,未設定則使用全域值);未知用量不強制切換。健康的綁定任務保留親和性。 | 輪換不保護免於供應商強制執行;多帳號使用可能違反供應商條款。 @@ -208,9 +208,9 @@ API-key 供應商可持有字面值金鑰或環境參考。OAuth 供應商使用 | Key | 型別 | 預設值 | 說明 | | --- | --- | --- | --- | | `anthropicAccountPool.enabled?` | `boolean` | `false` | 啟用 sticky 工作階段親和性與依用量的新工作階段選擇。**429 容錯移轉不由此開關控制**:只要儲存了兩個以上可用帳號就會生效,與其他多憑證供應商一致,且無法關閉。 | -| `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` | 對於新 session,當目前帳號達到此閾值時,選擇設定視窗中最低的已知快取用量。`0` 停用配額挑選。 | -| `anthropicAccountPool.strategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` | 新 session 策略;`quota` 依 `quotaWindow` 指定的視窗(預設為 5 小時列)為帳號排序,`fill-first` 也在同一視窗中判定其排空閾值。 | -| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` | 使用量型帳號選擇所採用、由供應商回報並快取的用量列。`five-hour` 保留原有行為。`weekly` 使用每週用量列,並在仍有其他可用帳號時略過 5 小時用量已用盡的帳號;若沒有其他帳號,則退回使用這些帳號。`max-utilization` 使用已知值中的最高值,因此每週用量尚未取得時仍可使用 5 小時用量;兩者都未知時,帳號遵循 unknown 用量排序。已知用量排在 unknown 之前,但若所有可用帳號都是 unknown,仍會依可用順序選出一個。完成前述較低 5 小時用量的同分判定後,完全相同時也保留可用順序。不會主動重新平衡健康且已有 affinity 的 session。在分配新 session 與符合條件的 429 替代後進行路由復原時,`quota` 直接依此視窗排序可用候選帳號;`fill-first` 依此視窗的門檻與用盡規則按穩定順序前進;`round-robin` 忽略此設定。冷卻狀態、容錯移轉上限與重新驗證資格仍是獨立的本機狀態。每個帳號的每週用量只有在 dashboard 的供應商頁面完成查詢後才可得知。 | +| `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` | 對於新 session,當現用帳號達到此閾值時,選擇設定視窗中已知快取用量最低的帳號,並優先選擇低於自身閾值的帳號;所選帳號本身不必達到閾值。`0` 僅停用基於用量的主動切換;新 session 選擇與符合條件的 429 後路由復原仍會使用 `quotaWindow`。 | +| `anthropicAccountPool.strategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` | 新 session 策略。`quota` 保留現用帳號,直到其 `quotaWindow` 用量達到有效 `autoSwitchThreshold`(預設 80)或無法服務,再轉到用量最低的帳號,優先選擇低於自身閾值的帳號;用量未知時保留現用帳號。`round-robin` 不讀取用量閾值,輪替新 session。`fill-first` 在 `quotaWindow` 中評估排空閾值。 | +| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` | 使用量型帳號選擇所採用、由供應商回報並快取的用量列。`five-hour` 保留原有行為。`weekly` 使用每週用量列,並在仍有其他可用帳號時略過 5 小時用量已用盡的帳號;若沒有其他帳號,則退回使用這些帳號。`max-utilization` 使用已知值中的最高值,因此每週用量尚未取得時仍可使用 5 小時用量;兩者都未知時,帳號遵循 unknown 用量排序。已知用量排在 unknown 之前,但若所有可用帳號都是 unknown,仍會依可用順序選出一個。完成前述較低 5 小時用量的同分判定後,完全相同時也保留可用順序。不會主動重新平衡健康且已有 affinity 的 session。當 `quota` 選擇替代帳號時(現用帳號達到閾值或無法服務的新 session,或符合條件的 429 後復原),優先選擇低於自身閾值的候選帳號並依此視窗排序;`fill-first` 依此視窗的門檻與用盡規則按穩定順序前進;`round-robin` 忽略此設定。冷卻狀態、容錯移轉上限與重新驗證資格仍是獨立的本機狀態。每個帳號的每週用量來自用量探測或觀察到的回應標頭。 | | `anthropicAccountPool.stickyLimit?` | `number` | `1` | 在一次 round-robin 選擇上保留的成功新 session 綁定。範圍 1–100。 | 只有共用5小時或每週額度明確拒絕的429才會冷卻帳號並切換。暫時速率限制保留親和性,只暫停該帳號的請求准入;每個請求最多一次短暫的同帳號重試及一次合格兄弟帳號切換。沒有依據回應標頭的429只允許一次同帳號短暫重試,不冷卻帳號,也不產生Retry-After。預設單帳號行為不變。Fable專屬拒絕不限制Sonnet;手動選擇和親和性均檢查請求模型的共用與家族額度。被動家族資訊在30分鐘或已知重設時到期,由一個服務請求依序重新驗證。用量門檻仍是軟偏好,全部候選耗盡時保留原有退回機制,不是用量或帳單硬上限。親和性為行程本地且有界。Token 更新失敗保留原有重新認證規則。已分類的訂閱或帳號計費 403 可在輸出前切換帳號,並按 `Retry-After` 或預設十分鐘冷卻;一般權限拒絕不切換。若所有合格帳號都在冷卻,客戶端收到附帶已知 `Retry-After` 的 429,而非認證錯誤。 diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index 79ff88d6093..ffdb46d1801 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -677,7 +677,7 @@ "codex-pool-refresh-backoff.test.ts": "codex-integration", "codex-pool-request-owned-main.test.ts": "codex-integration", "codex-pool-rotation.test.ts": "codex-integration", "codex-auth-release.test.ts": "codex-integration", - "codex-priority-failback.test.ts": "codex-integration", + "codex-priority-failback.test.ts": "codex-integration", "codex-round-robin-headroom.test.ts": "codex-integration", "codex-idle-window.test.ts": "codex-integration", "codex-prompt-adopt.test.ts": "codex-integration", "codex-prompt-base-variants.test.ts": "codex-integration", "codex-prompt-writes.test.ts": "codex-integration", "codex-prompt-scalar-scope.test.ts": "codex-integration", diff --git a/src/codex/routing/active-account.ts b/src/codex/routing/active-account.ts index 4a183244cf2..811bea390d5 100644 --- a/src/codex/routing/active-account.ts +++ b/src/codex/routing/active-account.ts @@ -35,10 +35,11 @@ export function resetCodexRoutingForManualSelection(accountId: string): void { clearThreadAccountMap(); // Manual selection is the operator source of truth — drop any automatic runtime cursor. runtimeActiveCodexAccountId = undefined; - // Record the pick as an unspent one-shot on the SHARED scope only. An independent scope - // gets no entry on purpose: every write site the guard protects is already skipped for - // independent scopes, so an entry there would be state nothing reads — and state nothing - // reads is what the next reader mistakes for a rule. + // Record the pick as an unspent one-shot on the shared scope and on each independent scope + // whose ring is seeded below. The cursor guard (`manualPreferenceBlocks`) still only acts on + // the shared scope: every write site it protects skips independent scopes. The independent + // entries have exactly one reader, round-robin placement, which keeps the selected account + // among its candidates until a dispatch in that scope spends the entry. // // Seeding happens ONLY here. A pool-driven promote must never create or move a preference, // or the pool would manufacture an operator intent nobody expressed. @@ -50,6 +51,7 @@ export function resetCodexRoutingForManualSelection(accountId: string): void { for (const scope of new Set(Object.values(NATIVE_MODEL_QUOTA_SCOPES))) { if (isIndependentCodexQuotaScope(scope)) { seedPoolRotationAccount(codexPoolKeyForScope(scope), accountId); + manualPreference.set(codexPoolKeyForScope(scope), accountId); } } // Quota avoidance is a preference, like the soft avoid dropped above, and an operator naming @@ -91,6 +93,7 @@ export function resetCodexRoutingForClearedSelection(): void { for (const scope of new Set(Object.values(NATIVE_MODEL_QUOTA_SCOPES))) { if (isIndependentCodexQuotaScope(scope)) { clearPoolRotationState(codexPoolKeyForScope(scope)); + manualPreference.delete(codexPoolKeyForScope(scope)); } } } @@ -143,6 +146,11 @@ export function manualPreferenceBlocks(poolKey: string, accountId: string): bool return preferred !== undefined && preferred !== accountId; } +/** The unspent operator selection for this pool scope, if any. Read-only. */ +export function unspentManualPreference(poolKey: string): string | undefined { + return manualPreference.get(poolKey); +} + export function getEffectiveActiveCodexAccountId(config: OcxConfig): string | undefined { return runtimeActiveCodexAccountId ?? config.activeCodexAccountId; } diff --git a/src/codex/routing/selection.ts b/src/codex/routing/selection.ts index 049ab1a5a9e..08db423769c 100644 --- a/src/codex/routing/selection.ts +++ b/src/codex/routing/selection.ts @@ -39,6 +39,7 @@ import { promoteActiveCodexAccount, rememberActiveCodexAccount, setActiveCodexAccount, + unspentManualPreference, } from "./active-account"; /** @@ -302,6 +303,38 @@ export function hasCodexQuotaHeadroom( return usage < threshold; } +/** + * Where round-robin may place a NEW conversation: the eligible accounts that still have headroom + * under their own threshold, or the whole eligible list when none does. + * + * Rotation by count alone put a fresh conversation on an account already at 95%. The conversation + * binds there, and when the account runs out it has to move to another account with a cold prompt + * cache. Preferring headroom at placement avoids that hop without touching anything already bound: + * live bindings never reach this function, and failover ({@link pickAlternateCodexAccount}) keeps + * plain ring order because leaving a failing account is not a placement. + * + * The score is {@link hasCodexQuotaHeadroom}, the one fill-first and the priority tier already use, + * so a threshold of 0 or unknown usage counts as headroom. It is a preference, never eligibility: + * when every account is at or over its threshold the ring sees the full list, exactly as before. + * + * An operator's unspent manual selection for this scope stays in the list whatever its usage. + * Manual selection seeds the ring so the next placement lands on the chosen account, and a + * preference must not overrule a person's explicit choice: dropping it here would clear that seed. + * Once a dispatch on it succeeds the selection is spent and the account is treated like any other. + */ +function roundRobinPlacementCandidates( + config: OcxConfig, + eligible: readonly string[], + now: number, + quotaScope?: CodexQuotaScope, + selectionOptions?: CodexAccountUsabilityOptions, +): readonly string[] { + const operatorChoice = unspentManualPreference(codexPoolKeyForScope(quotaScope)); + const withHeadroom = eligible.filter(id => + id === operatorChoice || hasCodexQuotaHeadroom(config, id, selectionOptions, now)); + return withHeadroom.length > 0 ? withHeadroom : eligible; +} + /** * Is a live binding held for its prompt cache? * @@ -475,7 +508,13 @@ export function pickUnboundStrategyAccount( let picked: string | null = null; if (strategy === "round-robin") { - const eligible = listEligibleCodexAccountIds(config, now, quotaScope, selectionOptions); + const eligible = roundRobinPlacementCandidates( + config, + listEligibleCodexAccountIds(config, now, quotaScope, selectionOptions), + now, + quotaScope, + selectionOptions, + ); const limit = stickyLimitForConfig(config); if (!commit) { return peekRoundRobinAccount(poolKey, eligible, limit); diff --git a/structure/INDEX.md b/structure/INDEX.md index 7983be15f9d..985ab19c7ec 100644 --- a/structure/INDEX.md +++ b/structure/INDEX.md @@ -99,6 +99,7 @@ Per-vendor contracts and the adapter authority that constructs them. | [`providers/openai-tiers.md`](providers/openai-tiers.md) | Pool/Direct account modes, API-key separation, and the public provider and quota contract. | | [`providers/pool-credit-renewal.md`](providers/pool-credit-renewal.md) | Independent credit-evidence renewal for opted-in exhausted Codex pool accounts. | | [`providers/openai-accounts.md`](providers/openai-accounts.md) | Migration and restore, wire identity, store concurrency, pool ordering and exclusions, quota observations, and account-bound retention. | +| [`providers/codex-round-robin-placement.md`](providers/codex-round-robin-placement.md) | Round-robin new-conversation placement preferring accounts under their effective auto-switch threshold, with all-over fallback and bound, failover and lineage boundaries. | | [`providers/openai-signed-in-preservation.md`](providers/openai-signed-in-preservation.md) | Opt-in effective priority bands that spend other pool accounts before the signed-in identity, its identity observation and management API. | | [`providers/cursor.md`](providers/cursor.md) | Cursor native exec, parameterized models, checkpoints, and active-context usage. | | [`providers/google.md`](providers/google.md) | Gemini thought-text, response parts, thought-signature replay, and adjacency repair. | @@ -289,6 +290,7 @@ A source area can be described by more than one doc, because these docs are orga | `src/codex/installation-id.ts` | [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | | `src/codex/provider-routing.ts` | [`codex-provider-routing.md`](codex-provider-routing.md) | | `src/codex/quota.ts` | [`quota-snapshots.md`](quota-snapshots.md) | +| `src/codex/routing/selection.ts` | [`providers/codex-round-robin-placement.md`](providers/codex-round-robin-placement.md) | | `src/codex/runtime.ts` | [`catalog-effort-clamp.md`](catalog-effort-clamp.md) | | `src/codex/shim.ts` | [`codex-cli-update.md`](codex-cli-update.md) | | `src/codex/signed-in-identity.ts` | [`providers/openai-signed-in-preservation.md`](providers/openai-signed-in-preservation.md) | diff --git a/structure/manifest.json b/structure/manifest.json index a3c8b3d3c2c..5c88ec2f184 100644 --- a/structure/manifest.json +++ b/structure/manifest.json @@ -721,6 +721,13 @@ "src/config.ts" ] }, + { + "path": "providers/codex-round-robin-placement.md", + "tier": 4, + "title": "Codex Round-Robin Placement", + "scope": "Round-robin new-conversation placement preferring accounts under their effective auto-switch threshold, with all-over fallback and bound, failover and lineage boundaries.", + "documents": ["src/codex/routing/selection.ts"] + }, { "path": "providers/openai-signed-in-preservation.md", "tier": 4, diff --git a/structure/providers/codex-round-robin-placement.md b/structure/providers/codex-round-robin-placement.md new file mode 100644 index 00000000000..228d1f38dff --- /dev/null +++ b/structure/providers/codex-round-robin-placement.md @@ -0,0 +1,48 @@ +# Codex Round-Robin Placement + +`accountPoolStrategy: "round-robin"` uses the effective per-account `autoSwitchThreshold` only when it +places a conversation that has no live binding. The threshold resolution itself is described under +[per-account auto-switch thresholds](openai-accounts.md#per-account-auto-switch-thresholds). + +## Placement prefers headroom + +`pickUnboundStrategyAccount` in `src/codex/routing/selection.ts` narrows the eligible list to accounts +that pass `hasCodexQuotaHeadroom` before it calls the ring, for the committed pick and the preview +peek alike, so `previewCodexAccountForRequest` names the account the next placement takes. When no +eligible account passes, the ring receives the full eligible list, so the threshold is a placement +preference and never eligibility. + +`hasCodexQuotaHeadroom` is the score fill-first, reset-first and the priority-tier filter already use: +`computeCodexUsageScore` (the hottest known weekly or 30-day window, refined by an unexpired short +window) against `getEffectiveCodexAutoSwitchThreshold`. Usage at or over the threshold has no +headroom; a threshold of 0 and unknown usage count as headroom. + +The narrowing runs after eligibility, so it composes with every existing pool boundary: quota-scope +cooldowns, the model-eligible roster of a model detour, the priority tier (a hot member of the top +tier is skipped rather than the tier descended), and plan, pause and credit exclusions. The ring and its +sticky count stay keyed per quota scope through `codexPoolKeyForScope`. A sticky account that crosses +the threshold drops out of the list the ring sees, which releases it for the next placement; it rejoins +rotation once its usage is back under the threshold. + +An operator's unspent manual selection for the scope stays in the list whatever its usage +(`unspentManualPreference` in `src/codex/routing/active-account.ts`). Manual selection seeds the shared +ring and each independent quota-scope ring, and records a one-shot for each of them, so the next +placement in every scope lands on the chosen account; dropping that account here would clear the seed +and let a preference overrule an explicit choice. A successful dispatch in a scope spends that scope's +one-shot, after which the account is narrowed like any other there. Only the shared one-shot guards the +shared active cursor (`manualPreferenceBlocks`). + +## What does not move + +Bound conversations never reach the narrowing. Round-robin reuses a live binding past the threshold +(`reevaluateAffinityQuota` in `src/codex/routing.ts` re-scores only `quota` and `reset-first`) and releases +it only on cooldown, quota refusal, failover, pause or another selectability guard; the re-placement that +follows goes through the same narrowing. Failover alternates (`pickAlternateCodexAccount` and its peek) +keep plain ring order, because leaving a failing account is not a placement. Idle-window steering and the +lineage first-placement hint run before the strategy: idle-window steering already requires headroom, +and a child of a live conversation starts on the account its parent is being served from. + +`tests/codex-integration/codex-round-robin-headroom.test.ts` covers placement, the at-threshold edge, +all-over fallback, per-account and zero thresholds, unknown usage, Reserve, sticky release and re-entry, +preview agreement, cooldown re-placement, the priority tier, and the bound, failover, model-roster and +lineage boundaries. diff --git a/structure/providers/openai-accounts.md b/structure/providers/openai-accounts.md index 44702333466..df79fd6543c 100644 --- a/structure/providers/openai-accounts.md +++ b/structure/providers/openai-accounts.md @@ -492,7 +492,7 @@ Upstream API-key usage follows the [physical-attempt account attribution contrac `codexAccountAutoSwitchThresholds` is persisted per-account routing metadata. Each 0..100 value overrides global `autoSwitchThreshold` for that source account; absence inherits global, and 0 disables only usage-driven switching from that account. Runtime resolves this effective value for unbound -selection, quota/reset-first bound-task re-evaluation, fill-first, priority-tier headroom, main-account +selection, quota/reset-first bound-task re-evaluation, fill-first, [round-robin placement](codex-round-robin-placement.md), priority-tier headroom, main-account pin reuse, previews and subagent quota fallback. Failure recovery remains separate. The stable `__main__` alias participates, deletion removes an added account's sidecar entry, and malformed maps degrade as a unit rather than invalidating config. Zero never disables main-account hard-lock, diff --git a/tests/codex-integration/codex-round-robin-headroom.test.ts b/tests/codex-integration/codex-round-robin-headroom.test.ts new file mode 100644 index 00000000000..5174d61b1c4 --- /dev/null +++ b/tests/codex-integration/codex-round-robin-headroom.test.ts @@ -0,0 +1,251 @@ +// Round-robin placement prefers accounts with quota headroom (Lane C). Reserve fixtures exercise +// routing state only; they do not authorize or dispatch Reserve. +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync } from "node:fs"; +import { join } from "node:path"; +import { clearPoolRotationState } from "../../src/codex/pool-rotation"; +import { + clearCodexUpstreamHealth, + clearThreadAccountMap, + pickAlternateCodexAccount, + previewCodexAccountForRequest, + recordCodexUpstreamOutcome, + resetCodexRoutingForManualSelection, + resolveCodexAccountForThread, + resolveCodexAccountForThreadDetailed, +} from "../../src/codex/routing"; +import { saveCodexAccountCredential } from "../../src/codex/account-store"; +import { clearAccountQuota, updateAccountQuota } from "../../src/codex/auth-api"; +import { setAccountQuotaFromParsed } from "../../src/codex/quota"; +import type { CodexThreadLineage } from "../../src/codex/lineage"; +import type { OcxConfig } from "../../src/types"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +const TEST_DIR = join(import.meta.dir, ".tmp-codex-round-robin-headroom-test"); +const NOW = 1_800_000_000_000; +let previousOpencodexHome: string | undefined; +let previousCodexHome: string | undefined; + +function makeConfig(overrides: Partial = {}): OcxConfig { + const ids = ["a", "b", "c"]; + for (const id of ids) { + saveCodexAccountCredential(id, { + accessToken: `access-${id}`, + refreshToken: `refresh-${id}`, + expiresAt: Date.now() + 5 * 60_000, + chatgptAccountId: `acct-${id}`, + }); + } + return { + providers: {}, + activeCodexAccountId: "a", + autoSwitchThreshold: 80, + accountPoolStrategy: "round-robin", + accountPoolStickyLimit: 1, + codexAccounts: ids.map(id => ({ id, email: `${id}@example.test`, isMain: false })), + ...overrides, + } as OcxConfig; +} + +function usage(a: number | undefined, b: number | undefined, c: number | undefined): void { + if (a !== undefined) updateAccountQuota("a", a); + if (b !== undefined) updateAccountQuota("b", b); + if (c !== undefined) updateAccountQuota("c", c); +} + +function newPlacements(config: OcxConfig, count: number, scope?: "shared" | "reserve"): Array { + return Array.from({ length: count }, (_, i) => resolveCodexAccountForThread(null, config, NOW + i, scope)); +} + +describe("round-robin new placement prefers accounts under their threshold", () => { + beforeEach(() => { + previousOpencodexHome = process.env.OPENCODEX_HOME; + previousCodexHome = process.env.CODEX_HOME; + if (existsSync(TEST_DIR)) removeTreeWithRetry(TEST_DIR); + mkdirSync(TEST_DIR, { recursive: true }); + process.env.OPENCODEX_HOME = TEST_DIR; + process.env.CODEX_HOME = TEST_DIR; + clearThreadAccountMap(); + clearCodexUpstreamHealth(); + clearAccountQuota(); + clearPoolRotationState(); + }); + + afterEach(() => { + clearAccountQuota(); + clearCodexUpstreamHealth(); + clearThreadAccountMap(); + clearPoolRotationState(); + if (previousOpencodexHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = previousOpencodexHome; + if (previousCodexHome === undefined) delete process.env.CODEX_HOME; + else process.env.CODEX_HOME = previousCodexHome; + if (existsSync(TEST_DIR)) removeTreeWithRetry(TEST_DIR); + }); + + test("new placements skip an account over the threshold while others are under it", () => { + const config = makeConfig(); + usage(95, 10, 10); + const picks = newPlacements(config, 6); + expect(picks).not.toContain("a"); + expect(picks.filter(id => id === "b")).toHaveLength(3); + expect(picks.filter(id => id === "c")).toHaveLength(3); + }); + + test("an account exactly at the threshold counts as over it", () => { + const config = makeConfig(); + usage(80, 10, 10); + expect(newPlacements(config, 6)).not.toContain("a"); + }); + + test("when every account is at or over the threshold, rotation covers all of them", () => { + const config = makeConfig(); + usage(90, 95, 85); + expect(new Set(newPlacements(config, 3))).toEqual(new Set(["a", "b", "c"])); + }); + + test("a per-account threshold above current usage keeps that account in rotation", () => { + const config = makeConfig({ codexAccountAutoSwitchThresholds: { a: 99 } }); + usage(95, 10, 10); + expect(new Set(newPlacements(config, 3))).toEqual(new Set(["a", "b", "c"])); + }); + + test("a threshold of 0 disables the preference", () => { + const config = makeConfig({ autoSwitchThreshold: 0 }); + usage(95, 10, 10); + expect(new Set(newPlacements(config, 3))).toEqual(new Set(["a", "b", "c"])); + }); + + test("unknown usage counts as headroom, so a known hot account is skipped", () => { + const config = makeConfig(); + usage(95, undefined, undefined); + expect(newPlacements(config, 4)).not.toContain("a"); + }); + + test("an account whose short window is full is not a placement target", () => { + const config = makeConfig(); + setAccountQuotaFromParsed("a", { shortPercent: 100, shortResetAt: NOW / 1000 + 3_600 }); + usage(undefined, 10, 10); + expect(newPlacements(config, 4)).not.toContain("a"); + }); + + test("a bound conversation keeps its account after that account crosses the threshold", () => { + const config = makeConfig(); + usage(10, 10, 10); + expect(resolveCodexAccountForThread("thread-bound", config, NOW)).toBe("a"); + usage(95, 10, 10); + for (let i = 1; i <= 20; i++) { + expect(resolveCodexAccountForThread("thread-bound", config, NOW + i)).toBe("a"); + } + }); + + test("preview names the same account the next placement takes", () => { + const config = makeConfig(); + usage(95, 10, 10); + for (let i = 0; i < 4; i++) { + const previewed = previewCodexAccountForRequest(null, config, NOW + i); + expect(previewed).not.toBe("a"); + expect(resolveCodexAccountForThread(null, config, NOW + i)).toBe(previewed); + } + }); + + test("the Reserve ring skips the hot account and leaves the shared ring where it was", () => { + const config = makeConfig(); + usage(95, 10, 10); + expect(newPlacements(config, 2, "reserve")).toEqual(["b", "c"]); + expect(resolveCodexAccountForThread(null, config, NOW + 10, "shared")).toBe("b"); + }); + + test("a sticky account that crosses the threshold mid-batch is released", () => { + const config = makeConfig({ accountPoolStickyLimit: 2 }); + usage(10, 10, 10); + expect(resolveCodexAccountForThread(null, config, NOW)).toBe("a"); + usage(95, 10, 10); + const picks = [1, 2, 3, 4].map(i => resolveCodexAccountForThread(null, config, NOW + i)); + expect(picks).toEqual(["b", "b", "c", "c"]); + }); + + test("an account rejoins rotation once its usage drops back under the threshold", () => { + const config = makeConfig(); + usage(95, 10, 10); + expect(newPlacements(config, 2)).not.toContain("a"); + usage(10, 10, 10); + expect(newPlacements(config, 3)).toContain("a"); + }); + + test("re-placing a conversation whose account went into cooldown avoids a hot sibling", () => { + const config = makeConfig(); + usage(10, 10, 10); + expect(resolveCodexAccountForThread("thread-moved", config, NOW)).toBe("a"); + usage(10, 10, 95); + recordCodexUpstreamOutcome(config, "a", 429, { + now: NOW + 1, + resetAt: Math.floor((NOW + 60 * 60_000) / 1_000), + }); + // The 429's own failover pick already advanced the ring to b, so plain rotation would hand + // the conversation to c next; c is over the threshold, so it goes to b instead. + expect(resolveCodexAccountForThread("thread-moved", config, NOW + 2)).toBe("b"); + }); + + test("failover keeps plain ring order: leaving a failing account is not a placement", () => { + const config = makeConfig(); + usage(10, 95, 10); + expect(pickAlternateCodexAccount(config, "a", NOW)).toBe("b"); + }); + + test("a model roster narrows the pool before the headroom preference", () => { + const config = makeConfig(); + usage(95, 10, 10); + const selectionOptions = { modelEligibleAccountIds: new Set(["a", "b"]) }; + for (let i = 0; i < 4; i++) { + const resolution = resolveCodexAccountForThreadDetailed(null, config, NOW + i, undefined, selectionOptions, "gpt-test"); + expect(resolution.accountId).toBe("b"); + } + }); + + test("within the top priority tier, a hot member is skipped instead of descending a tier", () => { + const config = makeConfig({ codexAccountPriorities: { a: 10, b: 10, c: 0 } }); + usage(95, 10, 10); + expect(newPlacements(config, 4)).toEqual(["b", "b", "b", "b"]); + }); + + test("an operator's manual selection takes its first placement even over the threshold", () => { + const config = makeConfig(); + usage(95, 10, 10); + resetCodexRoutingForManualSelection("a"); + expect(previewCodexAccountForRequest(null, config, NOW)).toBe("a"); + expect(resolveCodexAccountForThread(null, config, NOW)).toBe("a"); + // A successful dispatch spends the one-shot; after that the headroom preference applies again. + recordCodexUpstreamOutcome(config, "a", 200, { now: NOW + 1 }); + expect(newPlacements(config, 4)).not.toContain("a"); + }); + + test("a manual selection also takes the next Reserve placement until a Reserve dispatch spends it", () => { + const config = makeConfig(); + usage(95, 10, 10); + resetCodexRoutingForManualSelection("a"); + expect(previewCodexAccountForRequest(null, config, NOW, "reserve")).toBe("a"); + expect(resolveCodexAccountForThread(null, config, NOW, "reserve")).toBe("a"); + // A shared success spends only the shared one-shot; Reserve keeps its own until it is used there. + recordCodexUpstreamOutcome(config, "a", 200, { now: NOW + 1 }); + expect(newPlacements(config, 3, "reserve")).toContain("a"); + recordCodexUpstreamOutcome(config, "a", 200, { now: NOW + 2, modelId: "gpt-reserve" }); + expect(newPlacements(config, 4, "reserve")).not.toContain("a"); + }); + + test("a child of a live conversation still starts on its parent's account", () => { + const config = makeConfig(); + usage(10, 10, 10); + expect(resolveCodexAccountForThread("parent-key", config, NOW)).toBe("a"); + usage(95, 10, 10); + const lineage: CodexThreadLineage = { + conversationKey: "child-key", + rootSessionKey: "parent-key", + parentConversationKey: "parent-key", + siblingConversationKeys: [], + }; + const child = resolveCodexAccountForThreadDetailed("child-key", config, NOW + 1, undefined, undefined, undefined, lineage); + expect(child.accountId).toBe("a"); + }); +}); + diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 74bcb8a8604..59a85e01f92 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -678,6 +678,7 @@ "codex-pool-refresh-backoff.test.ts": "codex-integration", "codex-pool-request-owned-main.test.ts": "codex-integration", "codex-pool-rotation.test.ts": "codex-integration", "codex-priority-failback.test.ts": "codex-integration", "codex-idle-window.test.ts": "codex-integration", + "codex-round-robin-headroom.test.ts": "codex-integration", "codex-prompt-adopt.test.ts": "codex-integration", "codex-prompt-base-variants.test.ts": "codex-integration", "codex-prompt-journal.test.ts": "codex-integration", "codex-prompt-layers-read.test.ts": "codex-integration", "codex-prompt-layers-write.test.ts": "codex-integration", "codex-prompt-layers.test.ts": "codex-integration", From affd8403a21c933bd422a3a79df2bb40cf051c18 Mon Sep 17 00:00:00 2001 From: JUN Date: Mon, 2 Nov 2026 18:53:30 +0900 Subject: [PATCH 04/43] fix(codex): honest affinity labels and opt-in request-owned conversation affinity (#8080) (#8096) * fix(codex): honest affinity labels and opt-in request-owned conversation affinity (#8080) A Codex request carrying the caller's own ChatGPT bearer in Pool mode got no affinity key, so round-robin re-picked every turn and the request log still reported new_bind/healthy without any stored binding. - Affinity decisions are checked when selection returns: new_bind/rebound stay only if the key's entry names the selected account; otherwise the row reads unbound (request_owned / no_conversation / original reason) or cleared. - codexPool.requestOwnedAffinity (default off) gives request-owned traffic a process-local key scoped by an HMAC of the exact Authorization value and the conversation key. Final auth and both previews share one derivation; fixed accounts and Reserve get none; lineage is never recorded. - Keyed caller-owned main contexts carry the key and act as issuer __main__, so Pool<->main moves (incl. retry and compact alternates) scrub carried state. - Request-owned main pin logic moves byte-for-byte to request-owned-main-pin.ts. * fix(codex): scope conversation-state issuers per bearer and fix review findings (#8080) - Request-owned Pool and caller-owned main contexts carry a separate conversationStateKey (bearer-scoped HMAC), never passed to routing. Issuer records no longer borrow the stored-credential raw conversation key, and Pool<->main moves scrub carried state even with the opt-in off; the manual main pin path keeps the issuer key. - Caller-main fallbacks report what happened to main (detour/unbound), not the other account's decision. - Previews derive the key with each candidate model; recovery recomputes lineage from its own headers and ownership. * test(codex): drive real preview callbacks; document issuer retention (#8080) - Reserve and recovery preview regressions exercise the actual subagent fallback and encrypted-task recovery closures instead of source text. - Structure doc: manual selection keeps conversation-state issuers; stored credential traffic keeps its shared issuer namespace, unchanged. - Response-state store is cleared after the alternate-main test. * fix(codex): release a caller-owned main binding after its bearer is refused (#8080) With codexPool.requestOwnedAffinity on, a conversation bound to caller-owned main stayed there after the caller's bearer returned 429s, because main contexts bypass Pool outcome recording. Quota, credential and final transient refusals now release that caller-scoped binding (ordinary and model-detour entries) and carry the release reason to the next selection, without touching shared physical-main health, quota or cooldown. Covers regular, compact, streamed-terminal and WebSocket terminal paths. Docs: guide documents issuer-based scrubbing with the option on or off; the structure doc keeps only the present-tense persistence rule; the devlog unit is reduced to a present-tense record. * fix(codex): fence caller-main releases to selection-time bindings (#8080) - A delayed refusal releases only the binding entries captured when main was selected, so a newer binding from a later turn of the same conversation survives. - Only a caller-owned main carrying a request-owned key inspects a 5xx body, so unkeyed main requests are never delayed by the quota body reader. --- .../261102_request_owned_affinity/000_plan.md | 43 ++ .../010_research.md | 20 + .../content/docs/guides/codex-integration.md | 17 + scripts/test-layout/layout.json | 2 +- src/codex/auth-context.ts | 148 ++--- src/codex/request-owned-affinity.ts | 121 ++++ src/codex/request-owned-main-pin.ts | 86 +++ src/codex/routing/active-account.ts | 2 +- src/codex/routing/thread-affinity.ts | 16 +- src/config/schema/leaf-validators.ts | 1 + src/server/request-log.ts | 10 +- src/server/responses/account-change-state.ts | 15 +- src/server/responses/compact.ts | 14 +- src/server/responses/core-codex-account.ts | 16 +- src/server/responses/passthrough-delivery.ts | 14 + src/server/responses/request-prepare.ts | 15 +- src/types/config.ts | 2 + src/usage/log.ts | 4 +- structure/INDEX.md | 5 +- structure/manifest.json | 7 + .../providers/codex-request-owned-affinity.md | 74 +++ structure/providers/openai-tiers.md | 4 +- .../codex-main-rotation.test.ts | 4 +- .../codex-request-owned-affinity.test.ts | 579 ++++++++++++++++++ .../reserve-auth-context.test.ts | 18 + tests/fixtures/test-layout-expected.json | 3 +- .../compact-transient-alternate.test.ts | 102 +++ ...ponses-alternate-main-cancellation.test.ts | 158 +++++ ...responses-forward-incomplete-quota.test.ts | 16 + .../responses-preview-main-read-fence.test.ts | 99 +++ 30 files changed, 1473 insertions(+), 142 deletions(-) create mode 100644 devlog/_plan/261102_request_owned_affinity/000_plan.md create mode 100644 devlog/_plan/261102_request_owned_affinity/010_research.md create mode 100644 src/codex/request-owned-affinity.ts create mode 100644 src/codex/request-owned-main-pin.ts create mode 100644 structure/providers/codex-request-owned-affinity.md create mode 100644 tests/codex-integration/codex-request-owned-affinity.test.ts diff --git a/devlog/_plan/261102_request_owned_affinity/000_plan.md b/devlog/_plan/261102_request_owned_affinity/000_plan.md new file mode 100644 index 00000000000..63eea7a8d92 --- /dev/null +++ b/devlog/_plan/261102_request_owned_affinity/000_plan.md @@ -0,0 +1,43 @@ +# 261102 — Request-owned bearer conversation affinity (#8080) + +**Reader summary.** When Codex CLI signs in with ChatGPT and talks to a Pool-mode proxy, its own +bearer makes `main` one more round-robin candidate (#5019), but the request had no affinity key, so +every turn re-ran the strategy and a conversation hopped between main and the stored accounts. The +request log labelled each of those picks `new_bind/healthy` although nothing was stored. This unit +makes every affinity label describe what selection actually stored, and adds the opt-in +`codexPool.requestOwnedAffinity` (default off) that keeps one account per conversation for a +request-owned bearer. Research: `010_research.md`. Contract: `structure/providers/codex-request-owned-affinity.md`. + +## Scope + +- In: `src/codex/request-owned-affinity.ts` (key, label check, issuer helpers), + `src/codex/request-owned-main-pin.ts` (byte-for-byte move), wiring in `src/codex/auth-context.ts`, + request previews (`src/server/responses/request-prepare.ts`), issuer and retry/compact fallbacks, + request log and usage normalization, config field, manual-selection issuer retention. +- Out: affinity persistence (#8091), round-robin eligibility (#8092), Claude identity lanes. + +## Decisions + +1. Labels are checked when selection returns: `new_bind`/`rebound` stay only if the key's entry names + the selected account; otherwise `unbound` (`request_owned`, `no_conversation`, or the original + reason) or `cleared`. `unbound` is not a spend move reason. +2. The opt-in key is an HMAC under a process-random secret over the exact Authorization value and the + conversation key. Account-id claims are not used as principal. +3. Final auth and both previews (first and recovery, per candidate model) share one derivation; fixed + selectors and Reserve get no key; request-owned traffic never records lineage. +4. A separate bearer-scoped conversation-state key (never passed to routing) carries issuer records + for request-owned Pool and caller-owned main contexts, with or without the opt-in. +5. Manual account selection keeps issuer records while clearing routing bindings. +6. A refusal on a caller-owned main binding releases that binding without touching shared main health. + +## Acceptance + +Regression tests in `tests/codex-integration/codex-request-owned-affinity.test.ts`, +`tests/codex-integration/reserve-auth-context.test.ts`, `tests/responses/compact-transient-alternate.test.ts`, +`tests/responses/responses-alternate-main-cancellation.test.ts` and +`tests/responses/responses-preview-main-read-fence.test.ts` fail on the pre-change code and pass after it. + +## Outcome + +PR #8096. Plan audited over five rounds; implementation reviewed by a dedicated security review +and an independent code review before publication. diff --git a/devlog/_plan/261102_request_owned_affinity/010_research.md b/devlog/_plan/261102_request_owned_affinity/010_research.md new file mode 100644 index 00000000000..c03e9bb25b1 --- /dev/null +++ b/devlog/_plan/261102_request_owned_affinity/010_research.md @@ -0,0 +1,20 @@ +# 010 — Research (#8080) + +Source: Terra research task, 2026-11-02, read-only, at 6f1d3e65c. + +- Ownership flag: `codexRouteCredentialOwnership` (src/server/responses/core-auth.ts) marks a forwardable + caller bearer request-scoped. +- `poolStateEligible` (src/codex/auth-context.ts) rejects request-scoped credentials, so `affinityKey` and + lineage are undefined and `resolveCodexAccountForThreadDetailed` receives a null key. +- Since #5019/#5024 an unpinned caller bearer makes main an ordinary round-robin candidate; a stored + account selection materializes that stored credential. Intentional and documented in + structure/providers/openai-tiers.md. +- Round-robin commits its pick with a null key but binds only when `commitAffinity && threadId` + (src/codex/routing/selection.ts). With main + one stored account and sticky limit 1 the ring + alternates; with two stored accounts it cycles main, A, B. +- Every unbound success returns `affinityAfterRelease(null, undefined)` = `new_bind/healthy`. +- Log path: `noteCodexSelectionAffinity` (pool/main-pool only) → request log → `persistedAffinityFields` + → usage.jsonl via `KNOWN_AFFINITY_MOVES/REASONS` (src/usage/log.ts). No exhaustive Record over the + unions; GUI does not render these values. +- Options weighed: opt-in process-local namespace (chosen); always serve main (contradicts #5019); + raise sticky limit (shared counter, not affinity); omit label only (honest but uninformative). diff --git a/docs-site/src/content/docs/guides/codex-integration.md b/docs-site/src/content/docs/guides/codex-integration.md index ee6d1f4bb91..5e656662799 100644 --- a/docs-site/src/content/docs/guides/codex-integration.md +++ b/docs-site/src/content/docs/guides/codex-integration.md @@ -1314,6 +1314,23 @@ When an account leaves pool selection, the reason travels with the decision inst A main-account refresh that does not complete still answers `503` with `Retry-After`, because a retry may still succeed. The message now adds that a failure which persists means the main account needs reauthentication, rather than only asking for another attempt. +### Request-owned conversation affinity + +`codexPool.requestOwnedAffinity` is an optional boolean, defaulting to `false`. Set it to `true` +to keep a conversation carrying its own ChatGPT bearer on one eligible account within each quota +scope. Releases and model detours can still move it. The binding is process-local; restarting the +proxy or rotating the bearer starts a new binding. Session-less multi-generation subagent chains +may bind per thread. + +Affinity labels describe the binding when selection returns. `unbound` means no binding was stored; +`request_owned` means the caller-owned credential did not opt in, and `no_conversation` means no +conversation key was available. A later eligibility change can release a binding after selection. + +With or without the option, a request that carries its own bearer records which account served each +turn under a key scoped to that bearer. When a later turn is served by a different account, including +after you switch accounts manually, OpenCodex removes `previous_response_id` before sending and +rejects carried uploaded `file_id` references with HTTP 400, because the new account cannot read them. + ### Optional idle-window steering `codexPool.startIdleWindows` is an optional boolean and defaults to `false`. When enabled, a new diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index ffdb46d1801..80b5b0185ef 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -675,7 +675,7 @@ "codex-plugins-doctor.test.ts": "codex-integration", "codex-pool-plan-exclusion.test.ts": "codex-integration", "codex-pool-refresh-backoff.test.ts": "codex-integration", - "codex-pool-request-owned-main.test.ts": "codex-integration", + "codex-pool-request-owned-main.test.ts": "codex-integration", "codex-request-owned-affinity.test.ts": "codex-integration", "codex-pool-rotation.test.ts": "codex-integration", "codex-auth-release.test.ts": "codex-integration", "codex-priority-failback.test.ts": "codex-integration", "codex-round-robin-headroom.test.ts": "codex-integration", "codex-idle-window.test.ts": "codex-integration", diff --git a/src/codex/auth-context.ts b/src/codex/auth-context.ts index dd35923d2fa..7a17e2144ed 100644 --- a/src/codex/auth-context.ts +++ b/src/codex/auth-context.ts @@ -1,8 +1,10 @@ +import { requestOwnedAffinityKey, honestAffinityDecision, callerOwnedFallbackAffinityDecision, captureRequestOwnedAffinityBindings, type RequestOwnedBindingSnapshot } from "./request-owned-affinity"; +import { requestOwnedMainPinState, mainCreditsHoldResetAt, callerMatchesObservedMain } from "./request-owned-main-pin"; +export { requestOwnedMainPinState } from "./request-owned-main-pin"; import type { OcxRuntimeProviderConfig } from "./auth-context-provider"; export type { OcxRuntimeProviderConfig } from "./auth-context-provider"; export { stripCodexRuntimeProviderFields } from "./auth-context-provider"; import { bindPoolCreditPolicy, poolCreditHoldResetAt, poolContextCreditHoldResetAt, poolCreditRecoveryNeeded, poolContextCreditRecoveryNeeded, poolCreditRecoveryRetryAt } from "./pool-credit-policy"; -import { hasSpendableCodexCredits } from "./quota-types"; import { nextQuotaQueryDelay } from "./quota-query-backoff"; import { noteMainAccountActivity } from "./main-account-external-usage"; import { codexAccountPriorityFailbackEnabled } from "./account-priority"; @@ -40,9 +42,7 @@ import type { NativeMainStartupBlockReason } from "./native-profile-startup"; import { waitForMainAccountPolicyBinding } from "./main-account-policy-wait"; import { codexQuotaScopeForModel, - computeCodexUsageScore, getCodexQuotaHealthSnapshot, - isEffectiveCodexAccountPinned, releaseCodexQuotaProbeLease, releaseCodexQuotaScopeProbeLease, tryAcquireCodexQuotaProbeLease, @@ -74,8 +74,8 @@ import type { CodexCooldownSource, CodexQuotaScope } from "./routing"; import { maskAccountId } from "../lib/privacy"; import { formatErrorResponse, formatUsageLimitReachedResponse } from "../bridge"; import { nextCodexPoolRecoveryAt } from "./routing/pool-recovery"; -import { CODEX_UNKNOWN_USAGE_SCORE, getAccountQuota, getMainPolicyQuota, isValidWhamHistoryObservation, parseUsageQuota, parseMainPolicyUsageQuota, setAccountQuotaFromParsed } from "./quota"; -import { codexAccountUsesCreditsAfterLimit, codexUsageLimitResetAt } from "./account-credit-use"; +import { getAccountQuota, isValidWhamHistoryObservation, parseUsageQuota, parseMainPolicyUsageQuota, setAccountQuotaFromParsed } from "./quota"; +import { codexAccountUsesCreditsAfterLimit } from "./account-credit-use"; import type { CodexAccountMode, OcxConfig, OcxProviderConfig } from "../types"; import { FORWARD_HEADERS } from "../adapters/openai-responses"; import { isolateCodexPoolAccountHeaders } from "./forward-transport-headers"; @@ -85,7 +85,6 @@ import { resolveMainAccountHardLockThresholds, getMainAccountHardLockStatus, isMainAccountHardLockEnabled, - isMainAccountHardLocked, } from "./main-account-hard-lock"; import { captureMainAccountIdentityGeneration, @@ -102,67 +101,9 @@ import { CODEX_RESERVE_HELPER_UNSUPPORTED_MESSAGE, isCodexReserveHelperUnsupport import type { DataPlaneAdmission } from "../server/auth-cors"; import { getMainReserveAuthorization, isMainReserveAuthorizationLive, nativeUserIdClaims, type MainReserveAuthorization } from "./reserve-availability"; import { UpstreamRetryEvidenceError } from "../lib/upstream-retry"; -import { getEffectiveCodexAutoSwitchThreshold } from "./account-auto-switch"; import { CODEX_MAIN_DUPLICATE_ACTION, configuredCodexMainDuplicate } from "./collision-identity"; import { AgentAssertionUnsupportedError, authorizationCredential, hasAgentAssertionAuthorization } from "../lib/authorization-scheme"; -/** - * A request-owned bearer cannot inspect the physical main credential for its plan, but cached - * WHAM usage is still valid routing evidence for the same logical main account. Score it with - * the conservative unknown-plan rule: an unobserved governing window preserves the pin, while - * any known weekly/monthly/short value at the threshold releases it through the ordinary Pool - * path. This keeps the keyring boundary intact instead of reading auth.json just to classify a - * request that already brought its own credential (#3157). - */ -function requestOwnedMainPinHasQuotaHeadroom(config: OcxConfig): boolean { - const threshold = getEffectiveCodexAutoSwitchThreshold(config, MAIN_CODEX_ACCOUNT_ID); - if (threshold <= 0) return true; - const usage = computeCodexUsageScore(getAccountQuota(MAIN_CODEX_ACCOUNT_ID), undefined, Date.now(), codexAccountUsesCreditsAfterLimit(config, MAIN_CODEX_ACCOUNT_ID)); - return usage >= CODEX_UNKNOWN_USAGE_SCORE || usage < threshold; -} - -/** - * Whether a request carrying its OWN main credential still serves on main because the operator - * manually pinned it (#3166), split from the surrounding resolution so request preview can ask - * the identical question (#4850). - * - * Exported for exactly one reason: two copies of this fence is how #4850 happened. Final - * authentication honoured the ownership boundary while request preview, computing its fence from - * recovery and drain state alone, still handed pool eligibility the default liveness probe and - * opened the physical `auth.json` twice per spawn. A predicate one caller can forget is a - * predicate the other caller will eventually disagree with. - * - * Read-free by construction, which is what makes it usable on the fenced side. Every input is - * config, policy, or in-memory runtime state: the pin fields, the paused list, the cached quota - * score, the main policy quota the hard lock and the credits switch read, and `callerMatchesObservedMain`, which compares HMAC digests against the observed - * credential record in `main-account-cache.ts`. Nothing here opens a file. - * - * `candidate` is the pin before the hard-lock question, because the caller still owes the - * pending-binding check that only final authentication can fail closed on. - */ -export function requestOwnedMainPinState( - headers: Headers, - config: OcxConfig, - policy: CodexAuthPolicyConfig, - requestScopedMainCredential: boolean, - fixedAccountId: string | undefined, - quotaScope?: CodexQuotaScope, -): { candidate: boolean; preserve: boolean } { - const candidate = requestScopedMainCredential - && fixedAccountId === undefined - && config.activeCodexAccountPinned === MAIN_CODEX_ACCOUNT_ID - && isEffectiveCodexAccountPinned(config) - && !policy.pausedCodexAccountIds?.includes(MAIN_CODEX_ACCOUNT_ID) - && requestOwnedMainPinHasQuotaHeadroom(config); - return { - candidate, - preserve: candidate && !(callerMatchesObservedMain(headers) - && (isMainAccountHardLocked(policy) - || mainCreditsHoldResetAt(policy) !== undefined - || getCodexQuotaHealthSnapshot(MAIN_CODEX_ACCOUNT_ID, quotaScope)?.cooldownUntil)), - }; -} - /** * One conversation tree keys as ONE cohort (#4780). * @@ -247,12 +188,12 @@ export function requestOwnedMainCredentialIsLive(inputs: { } /** - * May this request own Pool affinity state at all? + * May this request use stored-credential Pool lineage? * - * Two credentials authenticate outside the Pool: an exact account selector (including the - * Reserve pin) and a request-owned main bearer, which exists for one request and must never - * fold into durable account state. Neither may read or write a binding, so neither may read - * or write LINEAGE either. + * Two credentials authenticate outside stored Pool state: an exact account selector (including + * Reserve) and a request-owned main bearer, which must never fold into durable account state. + * Neither may read or write a stored-credential binding or lineage. The optional request-owned + * affinity namespace is separate from this predicate. * * Exported so that a preview asks the question with the code that answers it, instead of a * restatement that can drift. It drifted once already: preview read a family relation from raw @@ -272,6 +213,15 @@ export function codexPoolStateEligible( ); } +/** Shared affinity derivation for final authentication and both request previews. */ +export function codexRequestAffinityKey(headers: Headers, config: OcxConfig, policy: CodexAuthPolicyConfig | undefined, options: CodexPoolStateEligibility = {}): string | undefined { + if (options.accountId !== undefined || requiresReserveAuthorization(policy, options.modelId, options.admission)) return undefined; + if (options.requestScopedMainCredential === true && hasCallerCodexBearer(headers)) { + return config.codexPool?.requestOwnedAffinity === true ? requestOwnedAffinityKey(headers) : undefined; + } + return codexPoolAffinityKey(headers); +} + /** * The lineage a PREVIEW is allowed to see: read-only, and only for a request that may hold Pool * state. Recording is left to the resolution that actually binds, so a preview can never leave a @@ -289,7 +239,7 @@ export function previewCodexPoolLineage( export type CodexAuthContext = | { - kind: "main"; accountId: null; reserveAuthorization?: MainReserveAuthorization; + kind: "main"; accountId: null; reserveAuthorization?: MainReserveAuthorization; affinityKey?: string; conversationStateKey?: string; affinityDecision?: CodexAffinityDecision; affinityBindingSnapshot?: RequestOwnedBindingSnapshot; /** Captured for the observed main credential actually selected for upstream. */ mainQuotaDispatch?: MainQuotaDispatch; } @@ -304,7 +254,7 @@ export type CodexAuthContext = /** Bypass Pool selection and suppress quota/transient failover for an exact selector. */ fixedAccount?: boolean; /** Pool binding key; the Desktop fallback is an opaque process-local HMAC. */ - affinityKey?: string; + affinityKey?: string; conversationStateKey?: string; /** * Set when this request was admitted through an active quota cooldown as * the account's single probe. Must be echoed into the upstream outcome so @@ -338,7 +288,7 @@ export type CodexAuthContext = chatgptAccountId: string; /** Bypass Pool selection and suppress quota/transient failover for an exact selector. */ fixedAccount?: boolean; - affinityKey?: string; // See `pool.affinityKey`. + affinityKey?: string; conversationStateKey?: string; // See `pool.affinityKey`. /** See `pool.probeLeaseId`. */ probeLeaseId?: string; quotaScope?: CodexQuotaScope; @@ -786,12 +736,6 @@ export function createCodexAuthDispatchGuard( }; } -function mainCreditsHoldResetAt(config: Pick): number | undefined { - if (codexAccountUsesCreditsAfterLimit(config, MAIN_CODEX_ACCOUNT_ID) - && hasSpendableCodexCredits(getMainPolicyQuota())) return undefined; - return codexUsageLimitResetAt(getMainPolicyQuota(), undefined, Date.now()); -} - function assertMainAccountPolicy( config: Pick | undefined, ): void { @@ -807,15 +751,6 @@ function assertMainAccountPolicy( noteMainAccountActivity(); } -/** No auth-file I/O: an unsigned claim alone never identifies a caller as stored main. */ -function callerMatchesObservedMain(headers: Headers): boolean { - const bearer = authorizationCredential(headers); - if (!bearer) return false; - const effectiveAccountId = headers.get("chatgpt-account-id") - ?? extractAccountId(undefined, bearer); - return matchesMainQuotaCredential(bearer, effectiveAccountId); -} - /** Constant-time digest comparison so bearer bytes never drive branch timing. */ function sameCredentialMaterial(a: string, b: string): boolean { return timingSafeEqual(createHash("sha256").update(a).digest(), createHash("sha256").update(b).digest()); @@ -1282,6 +1217,8 @@ async function resolveCodexAuthContextUnannotated( directSelectionAdmission.release(); } }; + const affinityKey = codexRequestAffinityKey(headers, config, policy, { accountId: fixedAccountId, modelId: options.modelId, admission: options.admission, requestScopedMainCredential }); + const conversationStateKey = affinityKey ?? (requestScopedMainCredential && fixedAccountId === undefined && !reserve ? requestOwnedAffinityKey(headers) : undefined); // Pool discovery excludes request-owned main credentials by design: they must never be folded // into stored-account entitlement, affinity, or persistence state. An effective manual main pin // is the one exception where that exclusion is selection evidence in the opposite direction. @@ -1294,7 +1231,7 @@ async function resolveCodexAuthContextUnannotated( options.isDirectCallerEntitledToCodexModel ?? isDirectCallerEntitledToCodexModel )(headers, options.modelId); if (callerEntitled && preserveRequestOwnedMainPin()) { - return { kind: "main", accountId: null }; + return { kind: "main", accountId: null, ...(mode === "pool" && conversationStateKey ? { conversationStateKey } : {}) }; } } // An explicit namespace binding is stronger than the provider's default mode. It must use the @@ -1309,19 +1246,24 @@ async function resolveCodexAuthContextUnannotated( } // A caller bearer can still accompany a request that selects a configured Pool account. Do not // let that request read, delete, or create a file-main affinity binding while deciding whether a - // stored account is available; only the stored credential selected below may own Pool state. - const affinityKey = poolStateEligible(fixedAccountId, requestScopedMainCredential) - ? codexPoolAffinityKey(headers) - : undefined; - // The thread's family relation, recorded under the same condition as the key itself. A - // first-placing child consults it; a request-owned or fixed credential never enters Pool - // state, so it never enters lineage either. - const lineage = affinityKey !== undefined + // stored account is available. Optional caller-owned bindings use a separate namespace; fixed + // selectors never own a binding. + // A first-placing child consults its thread's family relation. Fixed and request-owned + // credentials never enter stored Pool lineage, even when request-owned affinity is enabled. + const lineage = affinityKey !== undefined && poolStateEligible(fixedAccountId, requestScopedMainCredential) ? recordCodexThreadLineage(headers) : undefined; // Why this request is on this account, carried to the request log so a move reads as an event // instead of something inferred from account labels across lines (#4546). let affinityDecision: CodexAffinityDecision | undefined; + const resolveKeyedCallerMain = async (fallbackReason?: "cooldown" | "unusable"): Promise => { + const withheld = requestScopedMainCredential && config.codexPool?.requestOwnedAffinity !== true; + const decision = fallbackReason ? callerOwnedFallbackAffinityDecision(affinityDecision, affinityKey, quotaScope, options.modelId, withheld, fallbackReason) + : honestAffinityDecision(affinityDecision, affinityKey, MAIN_CODEX_ACCOUNT_ID, quotaScope, options.modelId, withheld); + const affinityBindingSnapshot = captureRequestOwnedAffinityBindings(affinityKey, quotaScope, options.modelId); + const context = await resolveCallerOwnedMainContext(); + return context.kind === "main" ? { ...context, ...(affinityBindingSnapshot ? { affinityBindingSnapshot } : {}), ...(affinityKey ? { affinityKey } : {}), ...(conversationStateKey ? { conversationStateKey } : {}), ...(decision ? { affinityDecision: decision } : {}) } : context; + }; // The half-open trial this request was granted, if it is the one allowed to test a held // account. Declared out here because the release paths below and the returned context are on // opposite sides of several throws (#4701). @@ -1470,17 +1412,17 @@ async function resolveCodexAuthContextUnannotated( throw new CodexRecoveryWithheldError(resolution.accountId, resolution.retryAt, resolution.detourAccountId); } const selected = resolution.status === "selected" ? resolution.accountId : null; - affinityDecision = resolution.affinity; + affinityDecision = selected ? honestAffinityDecision(resolution.affinity, affinityKey, selected, quotaScope, options.modelId, requestScopedMainCredential && config.codexPool?.requestOwnedAffinity !== true) : resolution.affinity; transientProbe = resolution.status === "selected" ? resolution.transientProbe : undefined; // Main now takes part in ordering when the request carries its own main bearer (#5019), so // selection can name it outright rather than only through the no-candidate fallback below. // Serve that selection from the credential the request arrived with: the read fence above // forbids this request from claiming, reading or reconciling the stored main profile, and a - // request-owned credential owns no Pool state, so there is nothing here to claim, prime or - // cool down. Hand back any trial first -- no Pool account is being sent to. + // request-owned credential owns no shared health state, so there is nothing here to claim, + // prime or cool down. Hand back any trial first -- no Pool account is being sent to. if (selected === MAIN_CODEX_ACCOUNT_ID && requestScopedMainCredential) { releaseTransientProbeGrant(); - const context = await resolveCallerOwnedMainContext(); + const context = await resolveKeyedCallerMain(); console.info("[codex] Pool selected caller-owned main credential."); return context; } @@ -1500,7 +1442,7 @@ async function resolveCodexAuthContextUnannotated( && !(callerMatchesObservedMain(headers) && policy.pausedCodexAccountIds?.includes(MAIN_CODEX_ACCOUNT_ID)) && options.excludeAccountId !== MAIN_CODEX_ACCOUNT_ID ) { - const context = await resolveCallerOwnedMainContext(); + const context = await resolveKeyedCallerMain("unusable"); console.info("[codex] Pool used caller-owned main credential: no selectable stored account."); return context; } @@ -1667,7 +1609,7 @@ async function resolveCodexAuthContextUnannotated( && !(callerMatchesObservedMain(headers) && policy.pausedCodexAccountIds?.includes(MAIN_CODEX_ACCOUNT_ID)) && options.excludeAccountId !== MAIN_CODEX_ACCOUNT_ID && !callerIsCooledPoolAccount(headers, config, accountId)) { - const context = await resolveCallerOwnedMainContext(); + const context = await resolveKeyedCallerMain("cooldown"); console.info("[codex] Pool used caller-owned main credential: stored account cooldown."); return context; } @@ -1727,6 +1669,7 @@ async function resolveCodexAuthContextUnannotated( chatgptAccountId: token.chatgptAccountId, ...(fixedAccountId !== undefined ? { fixedAccount: true } : {}), ...(affinityKey ? { affinityKey } : {}), + ...(conversationStateKey ? { conversationStateKey } : {}), ...(quotaScope ? { quotaScope } : {}), ...(probeLeaseId ? { probeLeaseId } : {}), ...(probeQuotaScope ? { probeQuotaScope } : {}), @@ -1750,6 +1693,7 @@ async function resolveCodexAuthContextUnannotated( chatgptAccountId: token.chatgptAccountId, ...(fixedAccountId !== undefined ? { fixedAccount: true } : {}), ...(affinityKey ? { affinityKey } : {}), + ...(conversationStateKey ? { conversationStateKey } : {}), ...(quotaScope ? { quotaScope } : {}), ...(probeLeaseId ? { probeLeaseId } : {}), ...(probeQuotaScope ? { probeQuotaScope } : {}), diff --git a/src/codex/request-owned-affinity.ts b/src/codex/request-owned-affinity.ts new file mode 100644 index 00000000000..514dc300c0b --- /dev/null +++ b/src/codex/request-owned-affinity.ts @@ -0,0 +1,121 @@ +/** + * Caller-owned affinity is scoped to the exact Authorization value and conversation key under a + * process-random HMAC key. It is process-local and must never be anchored or persisted, as required + * by the structure contract. Decisions describe the binding at selection time. + */ +import { createHmac, randomBytes } from "node:crypto"; +import { MAIN_CODEX_ACCOUNT_ID } from "./account-id"; +import { codexConversationIdentity } from "./lineage"; +import { getThreadAffinity, getModelDetourAffinity, deleteThreadAffinity, deleteModelDetourAffinity, notePendingReleaseReason, type CodexAffinityDecision, type CodexAffinityReason, type ThreadAffinityEntry } from "./routing/thread-affinity"; +import type { CodexQuotaScope } from "./routing/health-store"; +import { classifyCodexUpstreamOutcome } from "./routing/cooldown-math"; +import type { CodexAuthContext } from "./auth-context"; + +const key = randomBytes(32); +const prefix = "request-owned:v1:"; + +/** Derive the opaque key for this caller and conversation, if both exist. */ +export function requestOwnedAffinityKey(headers: Headers): string | undefined { + const authorization = headers.get("authorization"); + const conversation = codexConversationIdentity(headers)?.conversationKey; + if (!authorization || !conversation) return undefined; + return prefix + createHmac("sha256", key) + .update("opencodex-request-owned-affinity-v1\0").update(authorization).update("\0").update(conversation) + .digest("base64url"); +} + +/** Identify namespace keys that must remain process-local. */ +export function isRequestOwnedAffinityKey(value: string): boolean { + return value.startsWith(prefix); +} + +/** Report a bind only when the selection-time entry names the selected account. */ +export function honestAffinityDecision( + decision: CodexAffinityDecision | undefined, + affinityKey: string | undefined, + accountId: string, + quotaScope?: CodexQuotaScope, + modelId?: string, + requestOwnedKeyWithheld = false, +): CodexAffinityDecision | undefined { + if (!decision || (decision.move !== "new_bind" && decision.move !== "rebound")) return decision; + // This is a selection-time snapshot, immediately after the synchronous selector returns. + if (affinityKey && (getThreadAffinity(affinityKey, quotaScope)?.accountId === accountId + || getModelDetourAffinity(affinityKey, modelId, quotaScope)?.accountId === accountId)) return decision; + if (decision.move === "rebound") return { move: "cleared", reason: decision.reason }; + return { move: "unbound", reason: affinityKey ? decision.reason : requestOwnedKeyWithheld ? "request_owned" : "no_conversation" }; +} + +/** Identify the issuer for a Pool or keyed caller-main context. */ +export function conversationStateAccountId(ctx: { kind: "main" | "pool" | "main-pool"; accountId: string | null; affinityKey?: string; conversationStateKey?: string }): string | undefined { + return ctx.kind === "main" ? (ctx.affinityKey || ctx.conversationStateKey ? MAIN_CODEX_ACCOUNT_ID : undefined) : ctx.accountId ?? undefined; +} + +/** Describe the account actually serving a caller-owned fallback. */ +export function callerOwnedFallbackAffinityDecision( + decision: CodexAffinityDecision | undefined, affinityKey: string | undefined, quotaScope: CodexQuotaScope | undefined, + modelId: string | undefined, requestOwnedKeyWithheld: boolean, reason: "cooldown" | "unusable", +): CodexAffinityDecision { + const ordinary = affinityKey ? getThreadAffinity(affinityKey, quotaScope) : undefined; + const detour = affinityKey ? getModelDetourAffinity(affinityKey, modelId, quotaScope) : undefined; + if (ordinary?.accountId === MAIN_CODEX_ACCOUNT_ID || detour?.accountId === MAIN_CODEX_ACCOUNT_ID) + return honestAffinityDecision(decision ?? { move: "reused", reason: "healthy" }, affinityKey, MAIN_CODEX_ACCOUNT_ID, quotaScope, modelId, requestOwnedKeyWithheld)!; + if (ordinary || detour) return { move: "detour", reason }; + return { move: "unbound", reason: affinityKey ? decision?.reason ?? "healthy" : requestOwnedKeyWithheld ? "request_owned" : "no_conversation" }; +} + +/** Opaque process-local identity for the bindings present when main was selected. */ +export type RequestOwnedBindingSnapshot = object; +type EntryIdentity = { entry: ThreadAffinityEntry; accountId: string; generation: number; createdAt: number }; +const bindingSnapshots = new WeakMap(); + +function identity(entry: ThreadAffinityEntry | undefined): EntryIdentity | undefined { + return entry && { entry, accountId: entry.accountId, generation: entry.generation, createdAt: entry.createdAt }; +} +function matches(captured: EntryIdentity | undefined, current: ThreadAffinityEntry | undefined): boolean { + return !!captured && captured.entry === current && captured.accountId === current.accountId + && captured.generation === current.generation && captured.createdAt === current.createdAt; +} + +/** Capture the exact entries that a request is authorized to release after selection. */ +export function captureRequestOwnedAffinityBindings(key: string | undefined, scope?: CodexQuotaScope, modelId?: string): RequestOwnedBindingSnapshot | undefined { + if (!key || !isRequestOwnedAffinityKey(key)) return undefined; + const snapshot = {}; + bindingSnapshots.set(snapshot, { key, scope, modelId, ordinary: identity(getThreadAffinity(key, scope)), detour: identity(getModelDetourAffinity(key, modelId, scope)) }); + return snapshot; +} + +/** Whether a context carries a caller-owned routing key. */ +export function isKeyedRequestOwnedMain(ctx: CodexAuthContext): ctx is Extract & { affinityKey: string } { + return ctx.kind === "main" && !!ctx.affinityKey && isRequestOwnedAffinityKey(ctx.affinityKey); +} + +/** Release this caller’s scoped binding after its own main credential is refused. */ +export function releaseRequestOwnedMainOnOutcome(ctx: CodexAuthContext, outcome: number, _modelId?: string): void { + if (!isKeyedRequestOwnedMain(ctx) || !ctx.affinityBindingSnapshot) return; + const snapshot = bindingSnapshots.get(ctx.affinityBindingSnapshot); + if (!snapshot || snapshot.key !== ctx.affinityKey) return; + const outcomeClass = classifyCodexUpstreamOutcome(outcome); + const reason: CodexAffinityReason | undefined = outcomeClass === "quota" ? "quota_refusal" + : outcomeClass === "credential" ? "unusable" : outcomeClass === "transient" ? "transient" : undefined; + if (!reason) return; + const key = ctx.affinityKey; + const { scope, modelId: selectedModelId } = snapshot; + let released = false; + const ordinary = getThreadAffinity(key, scope); + const detour = getModelDetourAffinity(key, selectedModelId, scope); + const mainDetour = matches(snapshot.detour, detour) && detour?.accountId === MAIN_CODEX_ACCOUNT_ID; + // A caller-main fallback or model detour can leave an ordinary binding on a different + // account. Retire it too so the next placement reports the release rather than reuse. If + // main was itself bound and another turn has since rebound elsewhere, keep that newer entry. + const callerMainDetour = ctx.affinityDecision?.move === "detour"; + if (matches(snapshot.ordinary, ordinary) && (ordinary?.accountId === MAIN_CODEX_ACCOUNT_ID || mainDetour || callerMainDetour)) { + deleteThreadAffinity(key, scope); + released = true; + } + if (mainDetour) { + deleteModelDetourAffinity(key, selectedModelId, scope); + released = true; + } + if (released) notePendingReleaseReason(key, reason); +} diff --git a/src/codex/request-owned-main-pin.ts b/src/codex/request-owned-main-pin.ts new file mode 100644 index 00000000000..dd9917b264b --- /dev/null +++ b/src/codex/request-owned-main-pin.ts @@ -0,0 +1,86 @@ +import type { CodexAuthPolicyConfig } from "./auth-context"; +import type { OcxConfig } from "../types"; +import type { CodexQuotaScope } from "./routing"; +import { MAIN_CODEX_ACCOUNT_ID } from "./account-id"; +import { computeCodexUsageScore, getCodexQuotaHealthSnapshot, isEffectiveCodexAccountPinned } from "./routing"; +import { getEffectiveCodexAutoSwitchThreshold } from "./account-auto-switch"; +import { codexAccountUsesCreditsAfterLimit, codexUsageLimitResetAt } from "./account-credit-use"; +import { CODEX_UNKNOWN_USAGE_SCORE, getAccountQuota, getMainPolicyQuota } from "./quota"; +import { hasSpendableCodexCredits } from "./quota-types"; +import { isMainAccountHardLocked } from "./main-account-hard-lock"; +import { authorizationCredential } from "../lib/authorization-scheme"; +import { extractAccountId } from "../oauth/chatgpt"; +import { matchesMainQuotaCredential } from "./main-account-cache"; + +/** + * A request-owned bearer cannot inspect the physical main credential for its plan, but cached + * WHAM usage is still valid routing evidence for the same logical main account. Score it with + * the conservative unknown-plan rule: an unobserved governing window preserves the pin, while + * any known weekly/monthly/short value at the threshold releases it through the ordinary Pool + * path. This keeps the keyring boundary intact instead of reading auth.json just to classify a + * request that already brought its own credential (#3157). + */ +function requestOwnedMainPinHasQuotaHeadroom(config: OcxConfig): boolean { + const threshold = getEffectiveCodexAutoSwitchThreshold(config, MAIN_CODEX_ACCOUNT_ID); + if (threshold <= 0) return true; + const usage = computeCodexUsageScore(getAccountQuota(MAIN_CODEX_ACCOUNT_ID), undefined, Date.now(), codexAccountUsesCreditsAfterLimit(config, MAIN_CODEX_ACCOUNT_ID)); + return usage >= CODEX_UNKNOWN_USAGE_SCORE || usage < threshold; +} + +/** + * Whether a request carrying its OWN main credential still serves on main because the operator + * manually pinned it (#3166), split from the surrounding resolution so request preview can ask + * the identical question (#4850). + * + * Exported for exactly one reason: two copies of this fence is how #4850 happened. Final + * authentication honoured the ownership boundary while request preview, computing its fence from + * recovery and drain state alone, still handed pool eligibility the default liveness probe and + * opened the physical `auth.json` twice per spawn. A predicate one caller can forget is a + * predicate the other caller will eventually disagree with. + * + * Read-free by construction, which is what makes it usable on the fenced side. Every input is + * config, policy, or in-memory runtime state: the pin fields, the paused list, the cached quota + * score, the main policy quota the hard lock and the credits switch read, and `callerMatchesObservedMain`, which compares HMAC digests against the observed + * credential record in `main-account-cache.ts`. Nothing here opens a file. + * + * `candidate` is the pin before the hard-lock question, because the caller still owes the + * pending-binding check that only final authentication can fail closed on. + */ +export function requestOwnedMainPinState( + headers: Headers, + config: OcxConfig, + policy: CodexAuthPolicyConfig, + requestScopedMainCredential: boolean, + fixedAccountId: string | undefined, + quotaScope?: CodexQuotaScope, +): { candidate: boolean; preserve: boolean } { + const candidate = requestScopedMainCredential + && fixedAccountId === undefined + && config.activeCodexAccountPinned === MAIN_CODEX_ACCOUNT_ID + && isEffectiveCodexAccountPinned(config) + && !policy.pausedCodexAccountIds?.includes(MAIN_CODEX_ACCOUNT_ID) + && requestOwnedMainPinHasQuotaHeadroom(config); + return { + candidate, + preserve: candidate && !(callerMatchesObservedMain(headers) + && (isMainAccountHardLocked(policy) + || mainCreditsHoldResetAt(policy) !== undefined + || getCodexQuotaHealthSnapshot(MAIN_CODEX_ACCOUNT_ID, quotaScope)?.cooldownUntil)), + }; +} + +export function mainCreditsHoldResetAt(config: Pick): number | undefined { + if (codexAccountUsesCreditsAfterLimit(config, MAIN_CODEX_ACCOUNT_ID) + && hasSpendableCodexCredits(getMainPolicyQuota())) return undefined; + return codexUsageLimitResetAt(getMainPolicyQuota(), undefined, Date.now()); +} + + +/** No auth-file I/O: an unsigned claim alone never identifies a caller as stored main. */ +export function callerMatchesObservedMain(headers: Headers): boolean { + const bearer = authorizationCredential(headers); + if (!bearer) return false; + const effectiveAccountId = headers.get("chatgpt-account-id") + ?? extractAccountId(undefined, bearer); + return matchesMainQuotaCredential(bearer, effectiveAccountId); +} diff --git a/src/codex/routing/active-account.ts b/src/codex/routing/active-account.ts index 811bea390d5..7055199d491 100644 --- a/src/codex/routing/active-account.ts +++ b/src/codex/routing/active-account.ts @@ -32,7 +32,7 @@ let runtimeActiveCodexAccountId: string | undefined; /** Manual selection resets transient routing evidence without bypassing a real 429 cooldown. */ export function resetCodexRoutingForManualSelection(accountId: string): void { - clearThreadAccountMap(); + clearThreadAccountMap({ preserveConversationStateIssuers: true }); // Manual selection is the operator source of truth — drop any automatic runtime cursor. runtimeActiveCodexAccountId = undefined; // Record the pick as an unspent one-shot on the shared scope and on each independent scope diff --git a/src/codex/routing/thread-affinity.ts b/src/codex/routing/thread-affinity.ts index 1a44437177f..643d64fc5c4 100644 --- a/src/codex/routing/thread-affinity.ts +++ b/src/codex/routing/thread-affinity.ts @@ -86,7 +86,9 @@ export type CodexAffinityMove = /** There was no live binding; this request established one. */ | "new_bind" /** The binding was released without a replacement on this request. */ - | "cleared"; + | "cleared" + /** No binding was established for this selection. */ + | "unbound"; /** * Why. A move is the expensive event -- it discards the prompt-cache prefix warmed on the old @@ -95,6 +97,10 @@ export type CodexAffinityMove = */ export type CodexAffinityReason = | "healthy" + /** The request had no usable conversation key. */ + | "no_conversation" + /** A caller-owned credential did not opt into affinity. */ + | "request_owned" | "quota_headroom" | "quota_refusal" | "transient" @@ -202,7 +208,7 @@ type ConversationStateIssuerEntry = { }; const conversationStateIssuerMap = new Map(); -export function clearThreadAccountMap(): void { +export function clearThreadAccountMap(options: { preserveConversationStateIssuers?: boolean } = {}): void { threadAccountMap.clear(); threadAffinityEntryTotal = 0; // A refresh cooldown is per-account runtime state learned alongside these bindings. Leaving it @@ -213,7 +219,9 @@ export function clearThreadAccountMap(): void { // going away. A held account nobody may probe because of a lease issued against the previous // roster is a recovery that never starts. clearPoolRecoveryState(); - conversationStateIssuerMap.clear(); + // A manual account switch clears routing affinity, not the issuer of carried state. The next + // account needs that record to scrub or refuse account-bound continuation. + if (!options.preserveConversationStateIssuers) conversationStateIssuerMap.clear(); } export function clearConversationStateIssuerMap(): void { @@ -294,7 +302,7 @@ export function peekConversationStateIssuer( const pendingReleaseReasons = new Map(); const MAX_PENDING_RELEASE_REASONS = 4096; -function notePendingReleaseReason(threadId: string | null, reason: CodexAffinityReason): void { +export function notePendingReleaseReason(threadId: string | null, reason: CodexAffinityReason): void { if (threadId === null) return; if (!pendingReleaseReasons.has(threadId) && pendingReleaseReasons.size >= MAX_PENDING_RELEASE_REASONS) { const oldest = pendingReleaseReasons.keys().next(); diff --git a/src/config/schema/leaf-validators.ts b/src/config/schema/leaf-validators.ts index 3eacf076d56..5df3213e410 100644 --- a/src/config/schema/leaf-validators.ts +++ b/src/config/schema/leaf-validators.ts @@ -1045,6 +1045,7 @@ export const clientConnectionSchema = z.object({ export const codexPoolSchema = z.object({ excludedPlans: z.array(z.string().trim().min(1)).optional(), startIdleWindows: z.boolean().optional(), + requestOwnedAffinity: z.boolean().optional(), lowQuotaProtection: z.object({ enabled: z.boolean(), threshold: z.number().finite().min(1).max(100), diff --git a/src/server/request-log.ts b/src/server/request-log.ts index 925bd5f2c54..be3dde123cc 100644 --- a/src/server/request-log.ts +++ b/src/server/request-log.ts @@ -1235,13 +1235,13 @@ export function httpStatusForRequestLogTerminal( * `unresolved` rather than quietly inflating `settled`. */ export function requestSpendRecord( - logCtx: Pick, + logCtx: Pick, attempts: readonly PersistedUsageAttempt[] | undefined, ): PersistedRequestSpend | undefined { const rows = attempts ?? []; const budget = logCtx.executionBudget; const reasons = [...new Set( - (logCtx.affinityMoveReasons ?? (logCtx.affinityReason ? [logCtx.affinityReason] : [])) + (logCtx.affinityMoveReasons ?? (logCtx.affinity !== "unbound" && logCtx.affinityReason ? [logCtx.affinityReason] : [])) .filter(isKnownAffinityReason), )]; if (rows.length === 0 && !budget && reasons.length === 0) return undefined; @@ -1277,11 +1277,11 @@ export function noteAffinityMove( /** * Copy the selection's own affinity decision onto the request log. Both Pool-served kinds carry - * one: a stored Pool account and the main login rotating as `main-pool` (#4546, #7799). A move - * then reads as an event with its cause instead of something inferred from account labels. + * one: a stored Pool account and the main login rotating as `main-pool` (#4546, #7799). A keyed + * caller-owned main can also carry one. A move reads as an event with its cause. */ export function noteCodexSelectionAffinity(logCtx: RequestLogContext, authCtx: CodexAuthContext): void { - const decision = authCtx.kind === "pool" || authCtx.kind === "main-pool" ? authCtx.affinityDecision : undefined; + const decision = authCtx.affinityDecision; if (!decision) return; logCtx.affinity = decision.move; logCtx.affinityReason = decision.reason; diff --git a/src/server/responses/account-change-state.ts b/src/server/responses/account-change-state.ts index 95889b91db4..c76130dfb21 100644 --- a/src/server/responses/account-change-state.ts +++ b/src/server/responses/account-change-state.ts @@ -10,6 +10,7 @@ * The issuer association lives next to thread affinity in `src/codex/routing.ts`. */ +import { conversationStateAccountId } from "../../codex/request-owned-affinity"; import type { CodexAuthContext } from "../../codex/auth-context"; import { peekConversationStateIssuer, @@ -216,14 +217,20 @@ export function scrubUnportableConversationStateInPlace(body: unknown): boolean return changed; } +/** Preserve a Pool context's absent key instead of borrowing the raw request key. */ +export function compactAlternateAffinityKey(authCtx: CodexAuthContext, rawKey: () => string | undefined): string | undefined { + return authCtx.kind === "main" ? (authCtx.affinityKey ?? authCtx.conversationStateKey ?? rawKey()) : authCtx.affinityKey ?? authCtx.conversationStateKey; +} + export function conversationStateBindingFromAuth( authCtx: CodexAuthContext, fallbackAffinityKey?: string | null, ): { accountId: string; bindingKey: string } | null { - if (authCtx.kind !== "pool" && authCtx.kind !== "main-pool") return null; - const bindingKey = authCtx.affinityKey ?? fallbackAffinityKey ?? undefined; - if (!bindingKey || !authCtx.accountId) return null; - return { accountId: authCtx.accountId, bindingKey }; + const accountId = conversationStateAccountId(authCtx); + if (!accountId) return null; + const bindingKey = authCtx.affinityKey ?? authCtx.conversationStateKey ?? fallbackAffinityKey ?? undefined; + if (!bindingKey) return null; + return { accountId, bindingKey }; } export function rememberServingConversationStateIssuer( diff --git a/src/server/responses/compact.ts b/src/server/responses/compact.ts index 9484250829f..01f90d542be 100644 --- a/src/server/responses/compact.ts +++ b/src/server/responses/compact.ts @@ -1,3 +1,4 @@ +import { conversationStateAccountId, releaseRequestOwnedMainOnOutcome, isKeyedRequestOwnedMain } from "../../codex/request-owned-affinity"; import { CodexInstallationIdUnavailableError } from "../../codex/installation-id"; import { isolateCodexPoolClientMetadata } from "../../codex/forward-transport-headers"; import { captureAccountAutoPauseAttempt, wasAccountAutoPaused, wasPermanentAccountRefusal } from "../../oauth/account-auto-pause"; @@ -97,6 +98,7 @@ import { codexFailureWindowOutcomeMeta } from "../../codex/routing/failure-windo import { applyAccountChangeConversationStateScrub, conversationStateBindingFromAuth, + compactAlternateAffinityKey, accountChangeFileReferenceRefusal, rememberServingConversationStateIssuer, conversationCarriesUploadedFiles, @@ -1084,8 +1086,12 @@ export async function handleResponsesCompact( } = {}, ) => { // A gateway response is not evidence about any Codex account. - if (gatewayTransport || !usesCodexForwardPoolAuth(ctx, route.provider)) return; + if (gatewayTransport) return; if ((outcome === 401 || outcome === 403) && upstream && wasPermanentAccountRefusal(upstream)) return; + if (!usesCodexForwardPoolAuth(ctx, route.provider)) { + if (isKeyedRequestOwnedMain(ctx) && typeof outcome === "number" && (!upstream || !isNonReplayableResponse(upstream)) && isCanonicalOpenAiForwardProvider(route.provider)) releaseRequestOwnedMainOnOutcome(ctx, outcome, selectedModelId); + return; + } recordCodexUpstreamOutcome(config, ctx.accountId, outcome, { ...meta, ...codexFailureWindowOutcomeMeta(ctx), @@ -1428,9 +1434,7 @@ export async function handleResponsesCompact( const scrubCompactStateForAlternate = (alternateAuthCtx: CodexAuthContext): void => { const binding = conversationStateBindingFromAuth( alternateAuthCtx, - (authCtx.kind === "pool" || authCtx.kind === "main-pool") - ? authCtx.affinityKey - : codexPoolAffinityKey(req.headers), + compactAlternateAffinityKey(authCtx, () => codexPoolAffinityKey(req.headers)), ); if (!binding) return; for (const body of [raw, compactBody]) { @@ -1438,7 +1442,7 @@ export async function handleResponsesCompact( body, bindingKey: binding.bindingKey, servingAccountId: binding.accountId, - priorAccountId: authCtx.accountId, + priorAccountId: conversationStateAccountId(authCtx), logCtx, }); } diff --git a/src/server/responses/core-codex-account.ts b/src/server/responses/core-codex-account.ts index 3edcc235521..f48f5cf7b82 100644 --- a/src/server/responses/core-codex-account.ts +++ b/src/server/responses/core-codex-account.ts @@ -1,3 +1,4 @@ +import { conversationStateAccountId, releaseRequestOwnedMainOnOutcome, isKeyedRequestOwnedMain } from "../../codex/request-owned-affinity"; import { CodexInstallationIdUnavailableError } from "../../codex/installation-id"; import { captureAccountAutoPauseAttempt, wasPermanentAccountRefusal } from "../../oauth/account-auto-pause"; import type { OcxConfig, OcxProviderConfig, OcxParsedRequest } from "../../types"; @@ -912,9 +913,7 @@ export async function retryCodexPoolOnAlternateAccount( { const binding = conversationStateBindingFromAuth( retryAuthCtx, - firstAuthCtx.kind === "pool" || firstAuthCtx.kind === "main-pool" - ? firstAuthCtx.affinityKey - : undefined, + firstAuthCtx.affinityKey ?? firstAuthCtx.conversationStateKey, ); if (binding) { applyAccountChangeConversationStateScrub({ @@ -925,7 +924,7 @@ export async function retryCodexPoolOnAlternateAccount( && parsed._nativeReasoningRetention?.accountSwitch === true, bindingKey: binding.bindingKey, servingAccountId: binding.accountId, - priorAccountId: firstAuthCtx.accountId, + priorAccountId: conversationStateAccountId(firstAuthCtx), logCtx, }); } @@ -1164,7 +1163,14 @@ export function codexForwardTerminalOutcomeRecorder( modelId?: string, logCtx?: RequestLogContext, ): ((status: ResponsesTerminalStatus, httpStatusOverride?: number) => void) | undefined { - if (!usesCodexForwardPoolAuth(authCtx, provider)) return undefined; + if (!usesCodexForwardPoolAuth(authCtx, provider)) { + if (!isKeyedRequestOwnedMain(authCtx) || !isCanonicalOpenAiForwardProvider(provider)) return undefined; + return (status, httpStatusOverride) => { + const quota = [httpStatusOverride, logCtx?.terminalHttpStatus].find(value => value === 429 || value === 402); + const outcome = status === "completed" || (status === "incomplete" && quota === undefined) ? 200 : (quota ?? httpStatusOverride ?? logCtx?.terminalHttpStatus ?? 502); + releaseRequestOwnedMainOnOutcome(authCtx, outcome, modelId); + }; + } const windowMeta = codexFailureWindowOutcomeMeta(authCtx); return (status, httpStatusOverride) => { const quotaStatus = [httpStatusOverride, logCtx?.terminalHttpStatus] diff --git a/src/server/responses/passthrough-delivery.ts b/src/server/responses/passthrough-delivery.ts index 279d6ed03c7..8b7bba1ecc5 100644 --- a/src/server/responses/passthrough-delivery.ts +++ b/src/server/responses/passthrough-delivery.ts @@ -1,3 +1,4 @@ +import { releaseRequestOwnedMainOnOutcome, isKeyedRequestOwnedMain } from "../../codex/request-owned-affinity"; import { wasPermanentAccountRefusal } from "../../oauth/account-auto-pause"; import { hasResponseMediaType } from "../../lib/http-response-semantics"; import { isNativeControlResponse } from "./native-response-control"; @@ -34,6 +35,7 @@ import { codexDenialOutcomeMeta, isFixedCodexAccount, shouldDeferCodexResetDerivedCooldown, + shouldRetryCodexPoolAccountQuota, } from "./core-codex-account"; import { isMainQuotaDispatchLive, isMainQuotaDispatchWsClaimed } from "../../codex/main-account-cache"; import { MAIN_CODEX_ACCOUNT_ID } from "../../codex/account-id"; @@ -571,6 +573,18 @@ export async function deliverPassthroughResponse( }); } } else { + if (terminalBodyWillRecord) { + options.setTerminalOutcomeRecorder?.((status, httpStatusOverride) => { + terminalRecorder?.(status, httpStatusOverride); + options.onNativePassthroughTerminal?.(status); + }); + } + if (isKeyedRequestOwnedMain(admissionState.authCtx) && !terminalBodyWillRecord && !upstreamResponse.ok && !isNonReplayableResponse(upstreamResponse) + && !isReplayRefusalResponse(upstreamResponse) && !wasPermanentAccountRefusal(upstreamResponse) && isCanonicalOpenAiForwardProvider(route.provider)) { + const outcome = upstreamResponse.status >= 500 && await shouldRetryCodexPoolAccountQuota(upstreamResponse, options.abortSignal) + ? 429 : upstreamResponse.status; + releaseRequestOwnedMainOnOutcome(admissionState.authCtx, outcome, route.modelId); + } // The WS observer is the only plain-main publisher for a WebSocket exchange; // a prelude projection carries the prelude snapshot, not fresh evidence. // The dispatch claim is authoritative because downstream wrappers can replace the Response. diff --git a/src/server/responses/request-prepare.ts b/src/server/responses/request-prepare.ts index 8a7c561933a..065c3f66357 100644 --- a/src/server/responses/request-prepare.ts +++ b/src/server/responses/request-prepare.ts @@ -53,6 +53,7 @@ import { } from "./encrypted-payload"; import { codexPoolAffinityKey, + codexRequestAffinityKey, previewCodexPoolLineage, applyCodexAuthContextToProvider, releaseCodexAuthContextProbeLease, @@ -958,10 +959,10 @@ export async function prepareResponsesRequest( // // "The same" means both halves of the question the final resolution asks. The Authorization // it will be given, because the lineage scope is an HMAC of exactly that header; and its own - // Pool-state predicate, because a fixed account selector and a request-owned credential - // deliberately create no affinity at all -- previewing a family binding for one of those would - // hand model fallback an account this request can never authenticate as. Read-only: the record - // is written by the resolution that binds, never by a preview that may own no Pool state. + // Pool-state predicate: fixed selectors and request-owned credentials never use stored-credential + // lineage. An opt-in request-owned key has its own namespace; previewing a stored family binding + // would hand model fallback an account this request will not use. Preview is read-only: only + // eligible stored-credential resolutions record lineage. const poolLineage = previewCodexPoolLineage(previewAuthHeaders, options.codexAuthPolicy ?? config, { accountId: route.codexAccountId, modelId: route.modelId, @@ -1000,7 +1001,7 @@ export async function prepareResponsesRequest( }); const fallbackNow = Date.now(); subagentFallbackAccountPreview = (modelId, previewNow, modelEligibleAccountIds) => previewCodexAccountForRequest( - poolAffinityKey, + codexRequestAffinityKey(previewAuthHeaders, config, options.codexAuthPolicy ?? config, { accountId: route.codexAccountId, modelId, admission: options.admission, requestScopedMainCredential: previewRequestScopedMainCredential }) ?? null, config, previewNow, codexQuotaScopeForModel(modelId), @@ -1218,7 +1219,7 @@ export async function prepareResponsesRequest( // and then fail closed at final auth — the same class of stale-selection bug as // the quota scope, one layer over. subagentFallbackAccountPreview = (modelId, previewNow, modelEligibleAccountIds) => previewCodexAccountForRequest( - poolAffinityKey, + codexRequestAffinityKey(recoveryAuthHeaders, config, options.codexAuthPolicy ?? config, { accountId: route.codexAccountId, modelId, admission: options.admission, requestScopedMainCredential: recoveryRequestScopedMainCredential }) ?? null, config, previewNow, codexQuotaScopeForModel(modelId), @@ -1238,7 +1239,7 @@ export async function prepareResponsesRequest( }), }, modelId, - poolLineage, + previewCodexPoolLineage(recoveryAuthHeaders, options.codexAuthPolicy ?? config, { accountId: route.codexAccountId, modelId, admission: options.admission, requestScopedMainCredential: recoveryRequestScopedMainCredential }), ); const recoveryPreviewAccountId = subagentFallbackAccountPreview( parsed.modelId, diff --git a/src/types/config.ts b/src/types/config.ts index 10fcdcff171..1bc480ef5c4 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -1851,6 +1851,8 @@ export interface OcxWebSearchSidecarConfig { export interface OcxCodexPoolConfig { /** Start idle Codex windows when the pool is initialized. */ startIdleWindows?: boolean; + /** Enable process-local affinity for caller-owned credentials; defaults off. */ + requestOwnedAffinity?: boolean; /** * Plan keys ordinary rotation skips, matched case-insensitively against the plan stored on each * account. Absent or empty means no policy. diff --git a/src/usage/log.ts b/src/usage/log.ts index 51da4e7ee68..8a0f9ca5e1c 100644 --- a/src/usage/log.ts +++ b/src/usage/log.ts @@ -507,10 +507,10 @@ export function isKnownTerminalSource(value: unknown): value is NonNullable>([ - "reused", "held", "detour", "rebound", "new_bind", "cleared", + "reused", "held", "detour", "rebound", "new_bind", "cleared", "unbound", ]); const KNOWN_AFFINITY_REASONS = new Set>([ - "healthy", "quota_headroom", "quota_refusal", "transient", "transient_hold_expired", + "healthy", "no_conversation", "request_owned", "quota_headroom", "quota_refusal", "transient", "transient_hold_expired", "unusable", "paused", "plan_excluded", "credits_off", "cooldown", "quota_avoided", "generation", "expired", "model_lane", ]); diff --git a/structure/INDEX.md b/structure/INDEX.md index 985ab19c7ec..5e9f69f973e 100644 --- a/structure/INDEX.md +++ b/structure/INDEX.md @@ -70,6 +70,7 @@ The wire surfaces a client actually talks to. | [`data-planes/chat-reasoning-details.md`](data-planes/chat-reasoning-details.md) | The reasoning_details carrier that lets Chat Completions clients round-trip signed Anthropic thinking across tool steps (#7429). | | [`data-planes/protocol-paths.md`](data-planes/protocol-paths.md) | Shared protocol vocabulary, declared feature dispositions, the ingress-by-upstream baseline, plan/trace shapes, and protocol settings. | | [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | Per-account Pool wire installation identity, private secret, existence gates and fail-closed delivery. | +| [`providers/codex-request-owned-affinity.md`](providers/codex-request-owned-affinity.md) | Opt-in conversation affinity for a caller's own ChatGPT bearer in Pool mode, honest selection-time affinity labels, and the persistence exclusion contract. | | [`fallback-policy.md`](fallback-policy.md) | OCX-11 fallback off: what is a model or provider fallback (and what intra-pool rotation is not), scope precedence, the guarded hop sites, the fallback_refused and home_unreachable contracts, and the ocx.fallback/1 state. | | [`remote-workspace.md`](remote-workspace.md) | Opt-in workspace identity, executor grants, runtime adapters, management and dashboard integration. | | [`remote-link.md`](remote-link.md) | SSH machine-link building blocks: OpenSSH argument policy, ssh_config candidates, tunnel lifecycle reducer, the private link store, and standalone pairing-grant delivery. | @@ -260,7 +261,7 @@ A source area can be described by more than one doc, because these docs are orga | `src/codex/auth-api/account-preservation.ts` | [`providers/openai-signed-in-preservation.md`](providers/openai-signed-in-preservation.md) | | `src/codex/auth-api/pool-mode-gate.ts` | [`providers/pool-credit-renewal.md`](providers/pool-credit-renewal.md) | | `src/codex/auth-context-provider.ts` | [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | -| `src/codex/auth-context.ts` | [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | +| `src/codex/auth-context.ts` | [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md)
[`providers/codex-request-owned-affinity.md`](providers/codex-request-owned-affinity.md) | | `src/codex/catalog/effort.ts` | [`catalog-vendor-context.md`](catalog-vendor-context.md)
[`catalog-effort-clamp.md`](catalog-effort-clamp.md) | | `src/codex/catalog/model-hints.ts` | [`catalog-vendor-context.md`](catalog-vendor-context.md) | | `src/codex/catalog/ownership.ts` | [`catalog-routed-ownership.md`](catalog-routed-ownership.md) | @@ -290,6 +291,8 @@ A source area can be described by more than one doc, because these docs are orga | `src/codex/installation-id.ts` | [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | | `src/codex/provider-routing.ts` | [`codex-provider-routing.md`](codex-provider-routing.md) | | `src/codex/quota.ts` | [`quota-snapshots.md`](quota-snapshots.md) | +| `src/codex/request-owned-affinity.ts` | [`providers/codex-request-owned-affinity.md`](providers/codex-request-owned-affinity.md) | +| `src/codex/request-owned-main-pin.ts` | [`providers/codex-request-owned-affinity.md`](providers/codex-request-owned-affinity.md) | | `src/codex/routing/selection.ts` | [`providers/codex-round-robin-placement.md`](providers/codex-round-robin-placement.md) | | `src/codex/runtime.ts` | [`catalog-effort-clamp.md`](catalog-effort-clamp.md) | | `src/codex/shim.ts` | [`codex-cli-update.md`](codex-cli-update.md) | diff --git a/structure/manifest.json b/structure/manifest.json index 5c88ec2f184..494781fd41e 100644 --- a/structure/manifest.json +++ b/structure/manifest.json @@ -711,6 +711,13 @@ "scope": "Per-account Pool wire installation identity, private secret, existence gates and fail-closed delivery.", "documents": ["src/codex/installation-id.ts", "src/codex/auth-context.ts", "src/codex/auth-context-provider.ts", "src/codex/forward-transport-headers.ts", "src/adapters/openai-responses/transport.ts", "src/adapters/openai-responses/passthrough.ts", "src/server/ws-bridge.ts", "src/server/responses/codex-ws-request.ts", "src/server/responses/codex-ws-pool.ts", "src/server/responses/compact.ts", "src/server/responses/passthrough-build-error.ts", "src/server/context-history.ts", "src/server/search.ts", "src/server/images.ts", "src/server/live.ts", "src/server/audio-live.ts", "src/server/audio-dictation.ts", "src/server/index/serve-options.ts", "src/server/index/websocket-handler.ts", "src/server/index/live-sideband.ts", "src/server/claude-messages.ts", "src/codex/affinity-debug.ts"] }, + { + "path": "providers/codex-request-owned-affinity.md", + "tier": 3, + "title": "Codex Request-Owned Affinity", + "scope": "Opt-in conversation affinity for a caller's own ChatGPT bearer in Pool mode, honest selection-time affinity labels, and the persistence exclusion contract.", + "documents": ["src/codex/request-owned-affinity.ts", "src/codex/request-owned-main-pin.ts", "src/codex/auth-context.ts"] + }, { "path": "providers/openai-accounts.md", "tier": 4, diff --git a/structure/providers/codex-request-owned-affinity.md b/structure/providers/codex-request-owned-affinity.md new file mode 100644 index 00000000000..d9945fff821 --- /dev/null +++ b/structure/providers/codex-request-owned-affinity.md @@ -0,0 +1,74 @@ +# Codex Request-Owned Affinity + +A Codex request that carries the caller's own forwardable ChatGPT bearer in Pool mode is +request-owned (`codexRouteCredentialOwnership` in `src/server/responses/core-auth.ts`). Since #5019 that +bearer makes main an ordinary Pool candidate next to the stored accounts, while a stored-account pick is +served from that account's stored credential. This document owns how such a request may keep one account +per conversation, and how every affinity decision reports whether a binding was actually stored (#8080). + +## Ownership invariant + +By default a request-owned bearer owns no Pool affinity, lineage, persistence, entitlement cache, health +state or shared-active state: `codexRequestAffinityKey` in `src/codex/auth-context.ts` returns no key, so +every turn is placed by the strategy again. + +With `codexPool.requestOwnedAffinity: true` the request may own a process-local binding from the pair +(exact Authorization value, conversation key) to the account that served it. The key is +`request-owned:v1:` followed by an HMAC-SHA256 under a process-random secret +(`src/codex/request-owned-affinity.ts`), so: + +- two requests share a binding only when they present the byte-identical Authorization value and the same + conversation key; a stored-credential request's raw `app:` key cannot collide with it; +- a binding to `__main__` is always served from the presenting request's own bearer, so no caller is ever + served with another caller's credential; a binding to a stored account names an account ordinary + selection could already give this caller, and every reuse re-checks eligibility; +- a ChatGPT account-id claim is never the principal: it is header-suppliable and shared by workspace + members, so a rotated bearer simply starts a new binding; +- a restart makes every key unreproducible. + +Fixed account selectors and Reserve get no key in final auth or in either preview. Request-owned traffic +never records lineage; key derivation may read only the caller's own lineage scope, which that traffic +never writes, so session-less multi-generation subagent chains key per thread. + +The manual-pin exception for a request-owned bearer (`requestOwnedMainPinState`, #3166, #4850) lives in +`src/codex/request-owned-main-pin.ts`, read-free by construction and shared by final auth and both previews. + +## Labels + +`honestAffinityDecision` runs synchronously when selection returns. A `new_bind` or `rebound` decision +stays only when the ordinary or model-detour entry for the key names the selected account; otherwise +`new_bind` becomes `unbound` and `rebound` becomes `cleared`. The `unbound` reason is `request_owned` when +the key was withheld for a request-owned bearer, `no_conversation` when no key exists for another reason, +and the original reason when a key existed but nothing was stored. The label describes selection time, not +dispatch. `requestSpendRecord` does not count `unbound` as a move reason. A caller-main refusal +releases only the exact ordinary and model-detour entries captured at selection, so a delayed outcome +cannot delete a later binding. The snapshot is opaque and process-local; only an actual release records +a pending reason. + +## Caller-owned main and carried state + +Request-owned Pool contexts and caller-owned main contexts carry a process-local `conversationStateKey` +separate from the optional routing `affinityKey`. The issuer key is derived even when affinity is off +and on the manual-pin path; it is never passed to the routing selector. For conversation-state issuer +purposes a main context with either key is `__main__` (`conversationStateAccountId`). Pool to main and +main to Pool moves, including regular retry and compact alternate paths, scrub `previous_response_id` +when the issuer differs. This also applies with affinity off: those requests now record a bearer-scoped +issuer instead of leaving main untracked or using the stored-credential raw conversation key. Fixed +account selectors and Reserve do not receive a request-owned issuer key. Manual account selection +clears routing bindings while retaining issuer records, so the selected account can detect carried +state from the previous account: `clearThreadAccountMap({ preserveConversationStateIssuers: true })` +in `src/codex/routing/active-account.ts` retains issuers; a full reset clears both. Fixed-account and +other stored-credential traffic keeps the shared stored-credential issuer namespace; its `app:` key +is not caller-scoped by design and is unchanged by this feature. + +## Persistence contract + +Persistence of thread affinity must, for every key where `isRequestOwnedAffinityKey` is true: never register +an anchor for it, never serialize its thread rows (any scope, including model detours) or issuer rows, and +never adopt a restored row into it. The conversation-state key carries the same prefix, so the predicate +covers issuer records too. + +## Tests + +`tests/codex-integration/codex-request-owned-affinity.test.ts`, `tests/codex-integration/reserve-auth-context.test.ts`, +`tests/responses/compact-transient-alternate.test.ts`, `tests/responses/responses-alternate-main-cancellation.test.ts`. diff --git a/structure/providers/openai-tiers.md b/structure/providers/openai-tiers.md index 8f11ab67151..0eafaec4b20 100644 --- a/structure/providers/openai-tiers.md +++ b/structure/providers/openai-tiers.md @@ -561,7 +561,7 @@ A keyring-backed Codex request can carry its own forwardable ChatGPT bearer whil in Pool mode. When the effective manual pin is `__main__`, main is not paused, and its cached quota still has headroom, auth resolution validates the caller bearer's own gated-model roster and uses that request-owned credential before stored-Pool selection. The credential never enters Pool persistence, -affinity, entitlement cache, or health state, and this decision never reads the physical main credential. +entitlement cache, or health state, nor by default affinity ([request-owned affinity](codex-request-owned-affinity.md)); this never reads the physical main credential. If the caller lacks the requested model, a stored-account model detour may serve the request without clearing the healthy shared main pin. With quota-strategy cache affinity, the same detour preserves an ordinary added-account binding and shared selection beyond the proactive-switch threshold until genuine @@ -574,7 +574,7 @@ A forwardable request-owned bearer IS main's live credential for that request sent if selection named main — so `requestOwnedMainCredentialIsLive` answers the pool-liveness question yes, and main is compared against the stored accounts on the operator's own usage, priority and reset ordering. Selecting main then serves it from the caller's credential without claiming, -reading, reconciling or priming the stored profile, and without owning affinity or health state. +reading, reconciling or priming the stored profile, and without owning health state or (by default) affinity. A main that wins only through that bearer is also never recorded as the shared active account: the request resolves to main, while the persisted and runtime shared active account remain unchanged. Answering that question with the pin predicate instead scored main `main_credential_unavailable` on diff --git a/tests/codex-integration/codex-main-rotation.test.ts b/tests/codex-integration/codex-main-rotation.test.ts index 4c9c86665e3..0f5e59702cd 100644 --- a/tests/codex-integration/codex-main-rotation.test.ts +++ b/tests/codex-integration/codex-main-rotation.test.ts @@ -170,7 +170,7 @@ describe("main account rotation (Option A)", () => { identityKey: expect.stringMatching(/^[a-f0-9]{64}$/), identityGeneration: expect.any(Number), }, - affinityDecision: { move: "new_bind", reason: "healthy" }, + affinityDecision: { move: "unbound", reason: "no_conversation" }, }); expect(isCodexAuthContextUsable(ctx, config)).toBe(true); const headers = headersForCodexAuthContext(new Headers(), ctx); @@ -203,7 +203,7 @@ describe("main account rotation (Option A)", () => { identityKey: expect.stringMatching(/^[a-f0-9]{64}$/), identityGeneration: expect.any(Number), }, - affinityDecision: { move: "new_bind", reason: "healthy" }, + affinityDecision: { move: "unbound", reason: "no_conversation" }, }); expect(isCodexAccountInCooldown(MAIN_CODEX_ACCOUNT_ID)).toBe(false); expect(isAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID)).toBe(false); diff --git a/tests/codex-integration/codex-request-owned-affinity.test.ts b/tests/codex-integration/codex-request-owned-affinity.test.ts new file mode 100644 index 00000000000..dbc658d59aa --- /dev/null +++ b/tests/codex-integration/codex-request-owned-affinity.test.ts @@ -0,0 +1,579 @@ +import { describe, expect, test } from "bun:test"; +import { bindThreadAffinity, clearThreadAccountMap } from "../../src/codex/routing/thread-affinity"; +import { requestSpendRecord } from "../../src/server/request-log"; + +describe("request-owned affinity", () => { + test("namespaces bindings by exact bearer and conversation", async () => { + const { requestOwnedAffinityKey, isRequestOwnedAffinityKey } = await import("../../src/codex/request-owned-affinity"); + const a = new Headers({ authorization: "Bearer alpha", "session-id": "session", "thread-id": "thread" }); + const b = new Headers({ authorization: "Bearer beta", "session-id": "session", "thread-id": "thread" }); + const key = requestOwnedAffinityKey(a)!; + expect(isRequestOwnedAffinityKey(key)).toBe(true); + expect(key).toBe(requestOwnedAffinityKey(a)); + expect(key).not.toBe(requestOwnedAffinityKey(b)); + expect(key).not.toContain("alpha"); + expect(key).not.toContain("session"); + }); + test("selection labels claim a bind only when the chosen account is bound", async () => { + const { honestAffinityDecision } = await import("../../src/codex/request-owned-affinity"); + clearThreadAccountMap(); + const decision = { move: "new_bind", reason: "healthy" } as const; + expect(honestAffinityDecision(decision, undefined, "account", undefined, undefined, true)).toEqual({ move: "unbound", reason: "request_owned" }); + expect(honestAffinityDecision(decision, undefined, "account", undefined, undefined, false)).toEqual({ move: "unbound", reason: "no_conversation" }); + expect(honestAffinityDecision(decision, "key", "account")).toEqual({ move: "unbound", reason: "healthy" }); + bindThreadAffinity("key", "__main__", Date.now()); + expect(honestAffinityDecision(decision, "key", "__main__")).toEqual(decision); + clearThreadAccountMap(); + }); + test("unbound reasons do not become spend move reasons", () => { + expect(requestSpendRecord({ affinity: "unbound", affinityReason: "healthy" }, [])).toBeUndefined(); + expect(requestSpendRecord({ affinity: "unbound", affinityReason: "request_owned" }, [])).toBeUndefined(); + expect(requestSpendRecord({ affinity: "unbound", affinityReason: "request_owned", affinityMoveReasons: ["quota_refusal"] }, [])?.moveReasons).toEqual(["quota_refusal"]); + }); +}); + +test("opt-in main selection binds and reuses a caller-scoped key", async () => { + const { resolveCodexAuthContext, codexRequestAffinityKey, codexPoolAffinityKey } = await import("../../src/codex/auth-context"); + const { getThreadAffinity, clearThreadAccountMap } = await import("../../src/codex/routing/thread-affinity"); + const { conversationStateBindingFromAuth } = await import("../../src/server/responses/account-change-state"); + const { isRequestOwnedAffinityKey } = await import("../../src/codex/request-owned-affinity"); + const config = { providers: {}, codexAccounts: [], accountPoolStrategy: "round-robin", codexPool: { requestOwnedAffinity: true } } as import("../../src/types").OcxConfig; + const headers = new Headers({ authorization: "Bearer alpha", "session-id": "s", "thread-id": "t" }); + const options = { requestScopedMainCredential: true, primeCodexPoolQuotas: async () => {} }; + clearThreadAccountMap(); + const first = await resolveCodexAuthContext(headers, config, "pool", options); + const second = await resolveCodexAuthContext(headers, config, "pool", options); + expect(first.affinityDecision).toEqual({ move: "new_bind", reason: "healthy" }); + expect(second.affinityDecision).toEqual({ move: "reused", reason: "healthy" }); + expect(first.affinityKey).toBe(codexRequestAffinityKey(headers, config, config, options)); + expect(isRequestOwnedAffinityKey(first.affinityKey!)).toBe(true); + expect(first.affinityKey).not.toBe(codexPoolAffinityKey(headers)); + expect(getThreadAffinity(codexPoolAffinityKey(headers)!)).toBeUndefined(); + expect(conversationStateBindingFromAuth(first)).toEqual({ accountId: "__main__", bindingKey: first.affinityKey }); + clearThreadAccountMap(); +}); + +test("preview derivation excludes fixed selectors and preserves parent fallback", async () => { + const { codexRequestAffinityKey, codexPoolAffinityKey } = await import("../../src/codex/auth-context"); + const config = { providers: {}, codexPool: { requestOwnedAffinity: true } } as import("../../src/types").OcxConfig; + const headers = new Headers({ authorization: "Bearer alpha", "session-id": "s", "thread-id": "t" }); + const owned = { requestScopedMainCredential: true }; + expect(codexRequestAffinityKey(headers, config, config, { ...owned, accountId: "__main__" })).toBeUndefined(); + expect(codexRequestAffinityKey(headers, config, config, { ...owned, accountId: "pool" })).toBeUndefined(); + const reserveConfig = { ...config, codexDesktopAuthless: true }; + expect(codexRequestAffinityKey(headers, reserveConfig, reserveConfig, { ...owned, modelId: "gpt-reserve", admission: { source: "loopback" } })).toBeUndefined(); + expect(codexRequestAffinityKey(headers, config, config, {})).toBe(codexPoolAffinityKey(headers)); + expect(codexRequestAffinityKey(new Headers({ authorization: "Bearer alpha" }), config, config, owned)).toBeUndefined(); + const long = "x".repeat(513); + expect(codexRequestAffinityKey(new Headers({ authorization: "Bearer alpha", "session-id": long, "thread-id": "t" }), config, config, owned)).toBeUndefined(); + expect(codexRequestAffinityKey(new Headers({ authorization: "Bearer alpha", "session-id": long, "x-codex-parent-thread-id": "parent" }), config, config, owned)).toBeDefined(); +}); + +test("bound callers remain isolated and never record lineage", async () => { + const { resolveCodexAuthContext, codexPoolAffinityKey } = await import("../../src/codex/auth-context"); + const { codexLineageScopeKey, codexThreadLineageLookup, clearCodexThreadLineageForTests } = await import("../../src/codex/lineage"); + const { getThreadAffinity } = await import("../../src/codex/routing/thread-affinity"); + const config = { providers: {}, codexAccounts: [], accountPoolStrategy: "round-robin", codexPool: { requestOwnedAffinity: true } } as import("../../src/types").OcxConfig; + const a = new Headers({ authorization: "Bearer one", "session-id": "s", "thread-id": "t" }); + const b = new Headers({ authorization: "Bearer two", "session-id": "s", "thread-id": "t" }); + const options = { requestScopedMainCredential: true }; + clearThreadAccountMap(); clearCodexThreadLineageForTests(); + const first = await resolveCodexAuthContext(a, config, "pool", options); + const second = await resolveCodexAuthContext(a, config, "pool", options); + expect(first.affinityDecision?.move).toBe("new_bind"); + expect(second.affinityDecision?.move).toBe("reused"); + const other = await resolveCodexAuthContext(b, config, "pool", options); + expect(other.affinityDecision?.move).toBe("new_bind"); + expect(other.affinityKey).not.toBe(first.affinityKey); + expect((await resolveCodexAuthContext(a, config, "pool", options)).affinityDecision?.move).toBe("reused"); + expect(getThreadAffinity(codexPoolAffinityKey(a)!)).toBeUndefined(); + expect(codexThreadLineageLookup(codexPoolAffinityKey(a)!, codexLineageScopeKey(a))).toBeUndefined(); + clearThreadAccountMap(); clearCodexThreadLineageForTests(); +}); + +test("schema validates the default-off flag", async () => { + const { codexPoolSchema } = await import("../../src/config/schema/leaf-validators"); + expect(codexPoolSchema.safeParse({ requestOwnedAffinity: true }).success).toBe(true); + expect(codexPoolSchema.safeParse({ requestOwnedAffinity: "true" }).success).toBe(false); +}); + +test("usage log round trips the new affinity values", async () => { + const { mkdtempSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { removeTreeWithRetry } = await import("../helpers/remove-tree"); + const { addRequestLog, clearRequestLogsForTests } = await import("../../src/server/request-log"); + const { readUsageEntries, resetUsageReadCacheForTests } = await import("../../src/usage/log"); + const previous = process.env.OPENCODEX_HOME; + const home = mkdtempSync(join(tmpdir(), "ocx-affinity-")); + process.env.OPENCODEX_HOME = home; + clearRequestLogsForTests(); resetUsageReadCacheForTests(); + try { + for (const reason of ["request_owned", "no_conversation"] as const) addRequestLog({ + requestId: reason, timestamp: Date.now(), provider: "openai", model: "test", status: 200, + durationMs: 1, affinity: "unbound", affinityReason: reason, + }); + expect(readUsageEntries().map(row => [row.affinity, row.affinityReason])).toEqual([ + ["unbound", "request_owned"], ["unbound", "no_conversation"], + ]); + } finally { + clearRequestLogsForTests(); resetUsageReadCacheForTests(); + if (previous === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previous; + removeTreeWithRetry(home); + } +}); + +test("stored selection without a key labels the missing binding honestly", async () => { + const { mkdtempSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { removeTreeWithRetry } = await import("../helpers/remove-tree"); + const { saveCodexAccountCredential } = await import("../../src/codex/account-store"); + const { resolveCodexAuthContext } = await import("../../src/codex/auth-context"); + const home = mkdtempSync(join(tmpdir(), "ocx-owned-selection-")); + const oldHome = process.env.OPENCODEX_HOME; + const oldCodex = process.env.CODEX_HOME; + process.env.OPENCODEX_HOME = home; process.env.CODEX_HOME = home; + try { + saveCodexAccountCredential("a", { accessToken: "test-access", refreshToken: "test-refresh", expiresAt: Date.now() + 3600000, chatgptAccountId: "test-account" }); + const config = { providers: {}, codexAccounts: [{ id: "a", email: "a@example.test", isMain: false }], activeCodexAccountId: "a", pausedCodexAccountIds: ["__main__"] } as import("../../src/types").OcxConfig; + const options = { primeCodexPoolQuotas: async () => {} }; + clearThreadAccountMap(); + const noConversation = await resolveCodexAuthContext(new Headers(), config, "pool", options); + expect(noConversation.affinityDecision).toEqual({ move: "unbound", reason: "no_conversation" }); + const caller = new Headers({ authorization: "Bearer test", "session-id": "s", "thread-id": "t" }); + const off = await resolveCodexAuthContext(caller, config, "pool", { ...options, requestScopedMainCredential: true }); + expect(off.affinityDecision).toEqual({ move: "unbound", reason: "request_owned" }); + expect(off.affinityKey).toBeUndefined(); + const { codexPoolAffinityKey } = await import("../../src/codex/auth-context"); + const { rememberServingConversationStateIssuer, conversationStateBindingFromAuth } = await import("../../src/server/responses/account-change-state"); + const { peekConversationStateIssuer } = await import("../../src/codex/routing/thread-affinity"); + expect(off.conversationStateKey).toStartWith("request-owned:v1:"); + expect(off.conversationStateKey).not.toBe(codexPoolAffinityKey(caller)); + rememberServingConversationStateIssuer(off, codexPoolAffinityKey(caller)); + expect(peekConversationStateIssuer(off.conversationStateKey!)).toBe("a"); + expect(peekConversationStateIssuer(codexPoolAffinityKey(caller)!)).toBeUndefined(); + const stored = { kind: "pool", accountId: "other", generation: 0, writerGeneration: 0, accessToken: "test", chatgptAccountId: "test" } as const; + rememberServingConversationStateIssuer(stored, codexPoolAffinityKey(caller)); + expect(conversationStateBindingFromAuth(stored, codexPoolAffinityKey(caller))?.bindingKey).toBe(codexPoolAffinityKey(caller)); + expect(peekConversationStateIssuer(off.conversationStateKey!)).toBe("a"); + config.codexPool = { requestOwnedAffinity: true }; + const bound = await resolveCodexAuthContext(caller, config, "pool", { ...options, requestScopedMainCredential: true }); + const reused = await resolveCodexAuthContext(caller, config, "pool", { ...options, requestScopedMainCredential: true }); + expect(bound.affinityDecision?.move).toBe("new_bind"); + expect(reused.affinityDecision?.move).toBe("reused"); + const fixedPool = await resolveCodexAuthContext(caller, config, "pool", { ...options, requestScopedMainCredential: true, accountId: "a" }); + const fixedMain = await resolveCodexAuthContext(caller, config, "pool", { ...options, requestScopedMainCredential: true, accountId: "__main__" }); + expect(fixedPool.affinityKey).toBeUndefined(); + expect(fixedPool.conversationStateKey).toBeUndefined(); + expect(conversationStateBindingFromAuth(fixedPool, codexPoolAffinityKey(caller))?.bindingKey).toBe(codexPoolAffinityKey(caller)); + expect(fixedMain.affinityKey).toBeUndefined(); + expect(fixedMain.conversationStateKey).toBeUndefined(); + const { bindModelDetourAffinity, getThreadAffinity, getModelDetourAffinity } = await import("../../src/codex/routing/thread-affinity"); + const { honestAffinityDecision } = await import("../../src/codex/request-owned-affinity"); + bindModelDetourAffinity(bound.affinityKey!, "__main__", Date.now(), "detour-model"); + expect(getThreadAffinity(bound.affinityKey!)?.accountId).toBe("a"); + expect(getModelDetourAffinity(bound.affinityKey!, "detour-model")?.accountId).toBe("__main__"); + expect(honestAffinityDecision({ move: "new_bind", reason: "model_lane" }, bound.affinityKey, "__main__", undefined, "detour-model")).toEqual({ move: "new_bind", reason: "model_lane" }); + config.pausedCodexAccountIds = ["a"]; + const moved = await resolveCodexAuthContext(caller, config, "pool", { ...options, requestScopedMainCredential: true }); + expect(moved.kind).toBe("main"); + expect(moved.affinityDecision?.move).toBe("rebound"); + } finally { + clearThreadAccountMap(); + if (oldHome === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = oldHome; + if (oldCodex === undefined) delete process.env.CODEX_HOME; else process.env.CODEX_HOME = oldCodex; + removeTreeWithRetry(home); + } +}); + +test("keyed main issuer participates in account-change scrub and file refusal", async () => { + const { resolveCodexAuthContext } = await import("../../src/codex/auth-context"); + const { conversationStateBindingFromAuth, rememberServingConversationStateIssuer, applyAccountChangeConversationStateScrub, accountChangeFileReferenceRefusal } = await import("../../src/server/responses/account-change-state"); + const config = { providers: {}, codexAccounts: [], codexPool: { requestOwnedAffinity: true } } as import("../../src/types").OcxConfig; + const headers = new Headers({ authorization: "Bearer issuer", "session-id": "s", "thread-id": "t" }); + const options = { requestScopedMainCredential: true }; + clearThreadAccountMap(); + const first = await resolveCodexAuthContext(headers, config, "pool", options); + const second = await resolveCodexAuthContext(headers, config, "pool", options); + expect(first.affinityDecision?.move).toBe("new_bind"); + expect(second.affinityDecision?.move).toBe("reused"); + rememberServingConversationStateIssuer(second); + const binding = conversationStateBindingFromAuth(second)!; + const body = { previous_response_id: "opaque" }; + expect(applyAccountChangeConversationStateScrub({ body, bindingKey: binding.bindingKey, servingAccountId: "other" })).toBe(true); + expect(body).not.toHaveProperty("previous_response_id"); + expect(accountChangeFileReferenceRefusal({ body: { input: [{ file_id: "opaque" }] }, bindingKey: binding.bindingKey, servingAccountId: "other" })?.status).toBe(400); + clearThreadAccountMap(); +}); + +test("a namespaced binding remains independent across quota scopes", async () => { + const { resolveCodexAuthContext } = await import("../../src/codex/auth-context"); + const { getThreadAffinity } = await import("../../src/codex/routing/thread-affinity"); + const config = { providers: {}, codexAccounts: [], codexPool: { requestOwnedAffinity: true } } as import("../../src/types").OcxConfig; + const headers = new Headers({ authorization: "Bearer scopes", "session-id": "s", "thread-id": "t" }); + const options = { requestScopedMainCredential: true }; + clearThreadAccountMap(); + const first = await resolveCodexAuthContext(headers, config, "pool", options); + const second = await resolveCodexAuthContext(headers, config, "pool", options); + expect(first.affinityDecision?.move).toBe("new_bind"); + expect(second.affinityDecision?.move).toBe("reused"); + const shared = await resolveCodexAuthContext(headers, config, "pool", { ...options, modelId: "test-model" }); + expect(shared.affinityDecision?.move).toBe("new_bind"); + expect(getThreadAffinity(first.affinityKey!)?.accountId).toBe("__main__"); + expect(getThreadAffinity(first.affinityKey!, "shared")?.accountId).toBe("__main__"); + clearThreadAccountMap(); +}); + +test("substituted admission and injected main credentials use the ordinary key", async () => { + const { codexRouteCredentialOwnership } = await import("../../src/server/responses/core-auth"); + const { resolveCodexAuthContext, codexRequestAffinityKey, codexPoolAffinityKey } = await import("../../src/codex/auth-context"); + const { fakeChatGptJwt } = await import("../helpers/agent-task-recovery"); + const provider = { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", authMode: "forward" } as import("../../src/types").OcxProviderConfig; + const route = { provider, codexAccountMode: "pool" as const }; + const config = { providers: {}, codexAccounts: [], codexPool: { requestOwnedAffinity: true } } as import("../../src/types").OcxConfig; + const headers = new Headers({ authorization: `Bearer ${fakeChatGptJwt("test-account")}`, "session-id": "s", "thread-id": "t" }); + clearThreadAccountMap(); + const first = await resolveCodexAuthContext(headers, config, "pool", { requestScopedMainCredential: true }); + const second = await resolveCodexAuthContext(headers, config, "pool", { requestScopedMainCredential: true }); + expect(first.affinityDecision?.move).toBe("new_bind"); + expect(second.affinityDecision?.move).toBe("reused"); + const admission = { admission: { source: "bearer" } } as Parameters[3]; + const injected = { stripClaudeMainAuthForNoncanonicalForward: true, trustedClaudeMainAuth: { authorization: headers.get("authorization")! } } as Parameters[3]; + for (const options of [admission, injected]) { + const ownership = codexRouteCredentialOwnership(headers, config, route, options); + expect(ownership.requestScopedMainCredential).toBe(false); + expect(codexRequestAffinityKey(headers, config, config, ownership)).toBe(codexPoolAffinityKey(headers)); + } + clearThreadAccountMap(); +}); + +test("reusing a main binding never reads physical main auth", async () => { + const fs = await import("node:fs"); + const { spyOn } = await import("bun:test"); + const { resolveCodexAuthContext } = await import("../../src/codex/auth-context"); + const config = { providers: {}, codexAccounts: [], codexPool: { requestOwnedAffinity: true } } as import("../../src/types").OcxConfig; + const headers = new Headers({ authorization: "Bearer fenced", "session-id": "s", "thread-id": "t" }); + const options = { requestScopedMainCredential: true }; + clearThreadAccountMap(); + const first = await resolveCodexAuthContext(headers, config, "pool", options); + const second = await resolveCodexAuthContext(headers, config, "pool", options); + expect(first.affinityDecision?.move).toBe("new_bind"); + expect(second.affinityDecision?.move).toBe("reused"); + const original = fs.readFileSync as (...args: unknown[]) => unknown; + let mainReads = 0; + const spy = spyOn(fs, "readFileSync").mockImplementation(((...args: unknown[]) => { + if (typeof args[0] === "string" && args[0].endsWith("auth.json")) mainReads++; + return original(...args); + }) as typeof fs.readFileSync); + try { + expect((await resolveCodexAuthContext(headers, config, "pool", options)).affinityDecision?.move).toBe("reused"); + expect(mainReads).toBe(0); + } finally { spy.mockRestore(); clearThreadAccountMap(); } +}); + + +test("compact fixed-account Pool contexts never fall back to the raw key", async () => { + const { compactAlternateAffinityKey } = await import("../../src/server/responses/account-change-state"); + const pool = { kind: "pool", accountId: "a", fixedAccount: true, writerGeneration: 0, generation: 0, accessToken: "test", chatgptAccountId: "test" } as const; + let reads = 0; + const rawKey = () => { reads++; return "raw-key"; }; + expect(compactAlternateAffinityKey(pool, rawKey)).toBeUndefined(); + expect(compactAlternateAffinityKey({ kind: "main", accountId: null, affinityKey: "owned-key" }, rawKey)).toBe("owned-key"); + expect(reads).toBe(0); + expect(compactAlternateAffinityKey({ kind: "main", accountId: null }, rawKey)).toBe("raw-key"); + expect(reads).toBe(1); +}); + +test("six request-owned round-robin turns rotate when off and bind when on", async () => { + const { mkdtempSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { removeTreeWithRetry } = await import("../helpers/remove-tree"); + const { saveCodexAccountCredential } = await import("../../src/codex/account-store"); + const { resolveCodexAuthContext } = await import("../../src/codex/auth-context"); + const { clearPoolRotationState } = await import("../../src/codex/pool-rotation"); + const { clearCodexUpstreamHealth } = await import("../../src/codex/routing"); + const home = mkdtempSync(join(tmpdir(), "ocx-owned-rotation-")); + const oldHome = process.env.OPENCODEX_HOME, oldCodex = process.env.CODEX_HOME; + process.env.OPENCODEX_HOME = home; process.env.CODEX_HOME = home; + try { + for (const id of ["a", "b"]) saveCodexAccountCredential(id, { accessToken: `access-${id}`, refreshToken: `refresh-${id}`, expiresAt: Date.now() + 3600000, chatgptAccountId: `test-${id}` }); + const config = { providers: {}, codexAccounts: ["a", "b"].map(id => ({ id, email: `${id}@example.test`, isMain: false })), accountPoolStrategy: "round-robin", accountPoolStickyLimit: 1, autoSwitchThreshold: 0 } as import("../../src/types").OcxConfig; + const headers = new Headers({ authorization: "Bearer rotation", "session-id": "s", "thread-id": "t" }); + const options = { requestScopedMainCredential: true, primeCodexPoolQuotas: async () => {} }; + clearThreadAccountMap(); clearPoolRotationState(); clearCodexUpstreamHealth(); + const off = []; + for (let i = 0; i < 6; i++) off.push(await resolveCodexAuthContext(headers, config, "pool", options)); + expect(new Set(off.map(ctx => ctx.kind === "main" ? "__main__" : ctx.accountId)).size).toBe(3); + for (const ctx of off.filter(ctx => ctx.kind === "pool")) expect(ctx.affinityDecision).toEqual({ move: "unbound", reason: "request_owned" }); + clearThreadAccountMap(); clearPoolRotationState(); + config.codexPool = { requestOwnedAffinity: true }; + const on = []; + for (let i = 0; i < 6; i++) on.push(await resolveCodexAuthContext(headers, config, "pool", options)); + expect(new Set(on.map(ctx => ctx.kind === "main" ? "__main__" : ctx.accountId)).size).toBe(1); + expect(on.map(ctx => ctx.affinityDecision?.move)).toEqual(["new_bind", "reused", "reused", "reused", "reused", "reused"]); + // Model the first preview and a recovery reroute that changes credential ownership. + const { codexRequestAffinityKey } = await import("../../src/codex/auth-context"); + const { previewCodexAccountForRequest } = await import("../../src/codex/routing"); + const firstKey = codexRequestAffinityKey(headers, config, config, { requestScopedMainCredential: true })!; + const recoveryKey = codexRequestAffinityKey(headers, config, config, { requestScopedMainCredential: false })!; + expect(firstKey).not.toBe(recoveryKey); + const firstAccount = on[0]!.kind === "main" ? "__main__" : on[0]!.accountId!; + const otherAccount = firstAccount === "a" ? "b" : "a"; + bindThreadAffinity(recoveryKey, otherAccount, Date.now()); + expect(previewCodexAccountForRequest(firstKey, config, Date.now(), undefined, { requestOwnedMainCredential: true, isMainAccountTokenLive: () => true })).toBe(firstAccount); + expect(previewCodexAccountForRequest(recoveryKey, config, Date.now(), undefined, { isMainAccountTokenLive: () => false })).toBe(otherAccount); + const { resolveCodexAccountForThreadDetailed, codexQuotaScopeForModel } = await import("../../src/codex/routing"); + const { getThreadAffinity, getModelDetourAffinity } = await import("../../src/codex/routing/thread-affinity"); + const selection = { requestOwnedMainCredential: true, isMainAccountTokenLive: () => true }; + const shared = resolveCodexAccountForThreadDetailed(firstKey, config, Date.now(), "shared", selection); + expect(shared.status).toBe("selected"); + expect(shared.affinity?.move).toBe("new_bind"); + const scope = codexQuotaScopeForModel("gpt-reserve")!; + expect(scope).toBe("reserve"); + const reserve = resolveCodexAccountForThreadDetailed(firstKey, config, Date.now(), scope, selection); + expect(reserve.status).toBe("selected"); + expect(reserve.affinity?.move).toBe("new_bind"); + expect(getThreadAffinity(firstKey, scope)).toBeDefined(); + const ordinary = getThreadAffinity(firstKey, "shared")!.accountId; + const alternate = ordinary === "a" ? "b" : "a"; + const detour = resolveCodexAccountForThreadDetailed(firstKey, config, Date.now(), "shared", { ...selection, modelEligibleAccountIds: new Set([alternate]) }, "gpt-daybreak-blue-latest"); + expect(detour).toMatchObject({ status: "selected", accountId: alternate }); + expect(getModelDetourAffinity(firstKey, "gpt-daybreak-blue-latest", "shared")?.accountId).toBe(alternate); + expect(getThreadAffinity(firstKey, "shared")?.accountId).toBe(ordinary); + } finally { + clearThreadAccountMap(); clearPoolRotationState(); clearCodexUpstreamHealth(); + if (oldHome === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = oldHome; + if (oldCodex === undefined) delete process.env.CODEX_HOME; else process.env.CODEX_HOME = oldCodex; + removeTreeWithRetry(home); + } +}); + +test("pinned caller-main keeps the namespaced conversation-state issuer", async () => { + const { resolveCodexAuthContext } = await import("../../src/codex/auth-context"); + const { conversationStateBindingFromAuth, rememberServingConversationStateIssuer, applyAccountChangeConversationStateScrub, accountChangeFileReferenceRefusal } = await import("../../src/server/responses/account-change-state"); + const cfg = { providers: {}, codexAccounts: [], accountPoolStrategy: "round-robin", codexPool: { requestOwnedAffinity: true } } as import("../../src/types").OcxConfig; + const headers = new Headers({ authorization: "Bearer pinned", "session-id": "s", "thread-id": "t" }); + clearThreadAccountMap(); + const initial = await resolveCodexAuthContext(headers, cfg, "pool", { requestScopedMainCredential: true }); + const repeat = await resolveCodexAuthContext(headers, cfg, "pool", { requestScopedMainCredential: true }); + expect(initial.affinityDecision?.move).toBe("new_bind"); + expect(repeat.affinityDecision?.move).toBe("reused"); + const pool = { kind: "pool", accountId: "pool-x", writerGeneration: 0, generation: 0, accessToken: "test", chatgptAccountId: "test", affinityKey: initial.affinityKey } as const; + rememberServingConversationStateIssuer(pool); + cfg.activeCodexAccountId = "__main__"; cfg.activeCodexAccountPinned = "__main__"; + const pinned = await resolveCodexAuthContext(headers, cfg, "pool", { requestScopedMainCredential: true }); + expect(pinned.kind).toBe("main"); + expect(pinned.affinityKey).toBeUndefined(); + expect(pinned.conversationStateKey).toBe(initial.affinityKey); + const binding = conversationStateBindingFromAuth(pinned)!; + const body = { previous_response_id: "opaque" }; + expect(applyAccountChangeConversationStateScrub({ body, bindingKey: binding.bindingKey, servingAccountId: binding.accountId })).toBe(true); + expect(accountChangeFileReferenceRefusal({ body: { input: [{ file_id: "opaque" }] }, bindingKey: binding.bindingKey, servingAccountId: binding.accountId })?.status).toBe(400); + rememberServingConversationStateIssuer(pinned); + const reverse = { previous_response_id: "opaque" }; + expect(applyAccountChangeConversationStateScrub({ body: reverse, bindingKey: initial.affinityKey!, servingAccountId: "pool-x" })).toBe(true); + clearThreadAccountMap(); +}); + +test("caller-main issuer and fallback key use conversation state without routing affinity", async () => { + const { conversationStateAccountId } = await import("../../src/codex/request-owned-affinity"); + const { conversationStateBindingFromAuth, compactAlternateAffinityKey } = await import("../../src/server/responses/account-change-state"); + const main = { kind: "main", accountId: null, conversationStateKey: "owned-key" } as const; + expect(conversationStateAccountId(main)).toBe("__main__"); + expect(conversationStateBindingFromAuth(main, "raw")).toEqual({ accountId: "__main__", bindingKey: "owned-key" }); + expect(compactAlternateAffinityKey(main, () => "raw")).toBe("owned-key"); +}); + +test("fallback labels describe the caller-main detour", async () => { + const { callerOwnedFallbackAffinityDecision } = await import("../../src/codex/request-owned-affinity"); + clearThreadAccountMap(); + bindThreadAffinity("fallback-key", "__main__", Date.now()); + expect(callerOwnedFallbackAffinityDecision({ move: "reused", reason: "healthy" }, "fallback-key", undefined, undefined, false, "cooldown")).toEqual({ move: "reused", reason: "healthy" }); + expect(callerOwnedFallbackAffinityDecision({ move: "reused", reason: "healthy" }, undefined, undefined, undefined, true, "cooldown")).toEqual({ move: "unbound", reason: "request_owned" }); + clearThreadAccountMap(); +}); + +test("cooldown arriving after pool selection labels caller-main as a detour", async () => { + const { mkdtempSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { removeTreeWithRetry } = await import("../helpers/remove-tree"); + const { saveCodexAccountCredential } = await import("../../src/codex/account-store"); + const { resolveCodexAuthContext } = await import("../../src/codex/auth-context"); + const { recordCodexUpstreamOutcome, clearCodexUpstreamHealth } = await import("../../src/codex/routing"); + const { noteCodexSelectionAffinity } = await import("../../src/server/request-log"); + const home = mkdtempSync(join(tmpdir(), "ocx-owned-cooldown-")); + const oldHome = process.env.OPENCODEX_HOME, oldCodex = process.env.CODEX_HOME; + process.env.OPENCODEX_HOME = home; process.env.CODEX_HOME = home; + try { + saveCodexAccountCredential("a", { accessToken: "access-a", refreshToken: "refresh-a", expiresAt: Date.now() + 3600000, chatgptAccountId: "account-a" }); + const config = { providers: {}, codexAccounts: [{ id: "a", label: "a" }], activeCodexAccountId: "a", pausedCodexAccountIds: ["__main__"], autoSwitchThreshold: 0, codexPool: { requestOwnedAffinity: true } } as import("../../src/types").OcxConfig; + const headers = new Headers({ authorization: "Bearer distinct-caller", "chatgpt-account-id": "distinct-account", "session-id": "s", "thread-id": "t" }); + const options = { requestScopedMainCredential: true, primeCodexPoolQuotas: async () => {} }; + clearThreadAccountMap(); clearCodexUpstreamHealth(); + const first = await resolveCodexAuthContext(headers, config, "pool", options); + const second = await resolveCodexAuthContext(headers, config, "pool", options); + expect(first.affinityDecision?.move).toBe("new_bind"); expect(second.affinityDecision?.move).toBe("reused"); + const raced = await resolveCodexAuthContext(headers, config, "pool", { ...options, beginCodexAccountSelection: () => ({ mainProfileDraining: false, claimMainProfile: () => true, release: () => { + recordCodexUpstreamOutcome(config, "a", 429, { retryAfter: "600", fixedAccount: true }); + } }) }); + expect(raced.kind).toBe("main"); + expect(raced.affinityDecision).toEqual({ move: "detour", reason: "cooldown" }); + const log = { provider: "openai", model: "test" }; + noteCodexSelectionAffinity(log, raced); + expect(log).toMatchObject({ affinity: "detour", affinityReason: "cooldown" }); + } finally { + clearThreadAccountMap(); clearCodexUpstreamHealth(); + if (oldHome === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = oldHome; + if (oldCodex === undefined) delete process.env.CODEX_HOME; else process.env.CODEX_HOME = oldCodex; + removeTreeWithRetry(home); + } +}); + +test("manual selection clears affinity but retains carried-state issuers until a full reset", async () => { + const { resolveCodexAuthContext } = await import("../../src/codex/auth-context"); + const { rememberConversationStateIssuer, peekConversationStateIssuer, getThreadAffinity } = await import("../../src/codex/routing/thread-affinity"); + const { resetCodexRoutingForManualSelection, resetCodexRoutingForClearedSelection } = await import("../../src/codex/routing/active-account"); + const config = { providers: {}, codexAccounts: [], codexPool: { requestOwnedAffinity: true } } as import("../../src/types").OcxConfig; + const headers = new Headers({ authorization: "Bearer pin-reset", "session-id": "s", "thread-id": "t" }); + clearThreadAccountMap(); + try { + const first = await resolveCodexAuthContext(headers, config, "pool", { requestScopedMainCredential: true }); + const reused = await resolveCodexAuthContext(headers, config, "pool", { requestScopedMainCredential: true }); + expect(first.affinityDecision?.move).toBe("new_bind"); expect(reused.affinityDecision?.move).toBe("reused"); + const key = first.conversationStateKey!; + rememberConversationStateIssuer(key, "pool-a"); + rememberConversationStateIssuer("raw-key", "pool-b"); + expect(getThreadAffinity(key)).toBeDefined(); + resetCodexRoutingForManualSelection("__main__"); + expect(getThreadAffinity(key)).toBeUndefined(); + expect(peekConversationStateIssuer(key)).toBe("pool-a"); + expect(peekConversationStateIssuer("raw-key")).toBe("pool-b"); + clearThreadAccountMap(); + expect(peekConversationStateIssuer(key)).toBeUndefined(); + expect(peekConversationStateIssuer("raw-key")).toBeUndefined(); + } finally { clearThreadAccountMap(); resetCodexRoutingForClearedSelection(); } +}); + +test.each([[401, "unusable"], [403, "unusable"], [402, "quota_refusal"], [429, "quota_refusal"], [503, "transient"]] as const)( + "caller-owned main refusal %s releases namespaced bindings with %s", async (status, reason) => { + const { requestOwnedAffinityKey, releaseRequestOwnedMainOnOutcome, captureRequestOwnedAffinityBindings } = await import("../../src/codex/request-owned-affinity"); + const { bindModelDetourAffinity, getModelDetourAffinity, getThreadAffinity, peekPendingReleaseReason, affinityAfterRelease, rememberConversationStateIssuer, peekConversationStateIssuer } = await import("../../src/codex/routing/thread-affinity"); + const key = requestOwnedAffinityKey(new Headers({ authorization: "Bearer outcome-test", "session-id": "s", "thread-id": "t" }))!; + clearThreadAccountMap(); + bindThreadAffinity(key, "__main__", Date.now(), "shared"); + bindModelDetourAffinity(key, "__main__", Date.now(), "gpt-5.5", "shared"); + rememberConversationStateIssuer(key, "__main__"); + releaseRequestOwnedMainOnOutcome({ kind: "main", accountId: null, affinityKey: key, affinityBindingSnapshot: captureRequestOwnedAffinityBindings(key, "shared", "gpt-5.5") }, status, "gpt-5.5"); + expect(getThreadAffinity(key, "shared")).toBeUndefined(); + expect(getModelDetourAffinity(key, "gpt-5.5", "shared")).toBeUndefined(); + expect(peekPendingReleaseReason(key)).toBe(reason); + expect(peekConversationStateIssuer(key)).toBe("__main__"); + affinityAfterRelease(key, reason); + clearThreadAccountMap(); + }, +); + +test.each([200, 302, 400, 499])("non-refusal %s retains the caller-owned main binding", async status => { + const { requestOwnedAffinityKey, releaseRequestOwnedMainOnOutcome, captureRequestOwnedAffinityBindings } = await import("../../src/codex/request-owned-affinity"); + const { getThreadAffinity, peekPendingReleaseReason } = await import("../../src/codex/routing/thread-affinity"); + const key = requestOwnedAffinityKey(new Headers({ authorization: "Bearer no-refusal", "session-id": "s", "thread-id": "t" }))!; + clearThreadAccountMap(); bindThreadAffinity(key, "__main__", Date.now(), "shared"); + releaseRequestOwnedMainOnOutcome({ kind: "main", accountId: null, affinityKey: key, affinityBindingSnapshot: captureRequestOwnedAffinityBindings(key, "shared", "gpt-5.5") }, status, "gpt-5.5"); + expect(getThreadAffinity(key, "shared")?.accountId).toBe("__main__"); + expect(peekPendingReleaseReason(key)).toBeUndefined(); + clearThreadAccountMap(); +}); + +test("a failed caller-main model detour releases its ordinary and detour entries only", async () => { + const { mkdtempSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { removeTreeWithRetry } = await import("../helpers/remove-tree"); + const { saveCodexAccountCredential } = await import("../../src/codex/account-store"); + const { requestOwnedAffinityKey, releaseRequestOwnedMainOnOutcome, captureRequestOwnedAffinityBindings } = await import("../../src/codex/request-owned-affinity"); + const { bindModelDetourAffinity, getModelDetourAffinity, getThreadAffinity, peekPendingReleaseReason, affinityAfterRelease } = await import("../../src/codex/routing/thread-affinity"); + const home = mkdtempSync(join(tmpdir(), "ocx-detour-refusal-")); const previous = process.env.OPENCODEX_HOME; + process.env.OPENCODEX_HOME = home; + try { + saveCodexAccountCredential("a", { accessToken: "access-a", refreshToken: "refresh-a", expiresAt: Date.now() + 3600000, chatgptAccountId: "account-a" }); + const key = requestOwnedAffinityKey(new Headers({ authorization: "Bearer detour", "session-id": "s", "thread-id": "t" }))!; + clearThreadAccountMap(); + bindThreadAffinity(key, "a", Date.now(), "shared"); + bindModelDetourAffinity(key, "__main__", Date.now(), "gpt-5.5", "shared"); + const context = { kind: "main", accountId: null, affinityKey: key, affinityBindingSnapshot: captureRequestOwnedAffinityBindings(key, "shared", "gpt-5.5") } as const; + releaseRequestOwnedMainOnOutcome(context, 429, "gpt-5.5"); + expect(getThreadAffinity(key, "shared")).toBeUndefined(); + expect(getModelDetourAffinity(key, "gpt-5.5", "shared")).toBeUndefined(); + expect(peekPendingReleaseReason(key)).toBe("quota_refusal"); + affinityAfterRelease(key, "quota_refusal"); + bindThreadAffinity(key, "a", Date.now(), "shared"); + releaseRequestOwnedMainOnOutcome({ ...context, affinityDecision: { move: "reused", reason: "healthy" } }, 429, "gpt-5.5"); + expect(getThreadAffinity(key, "shared")?.accountId).toBe("a"); + expect(peekPendingReleaseReason(key)).toBeUndefined(); + releaseRequestOwnedMainOnOutcome({ ...context, affinityBindingSnapshot: captureRequestOwnedAffinityBindings(key, "shared", "gpt-5.5"), affinityDecision: { move: "detour", reason: "cooldown" } }, 429, "gpt-5.5"); + expect(getThreadAffinity(key, "shared")).toBeUndefined(); + expect(peekPendingReleaseReason(key)).toBe("quota_refusal"); + affinityAfterRelease(key, "quota_refusal"); + const sameTime = Date.now(); + bindThreadAffinity(key, "a", sameTime, "shared"); + bindModelDetourAffinity(key, "__main__", sameTime, "gpt-5.5", "shared"); + const older = { ...context, affinityBindingSnapshot: captureRequestOwnedAffinityBindings(key, "shared", "gpt-5.5") }; + bindThreadAffinity(key, "a", sameTime, "shared"); + bindModelDetourAffinity(key, "__main__", sameTime, "gpt-5.5", "shared"); + releaseRequestOwnedMainOnOutcome(older, 429, "gpt-5.5"); + expect(getThreadAffinity(key, "shared")?.accountId).toBe("a"); + expect(getModelDetourAffinity(key, "gpt-5.5", "shared")?.accountId).toBe("__main__"); + expect(peekPendingReleaseReason(key)).toBeUndefined(); + } finally { clearThreadAccountMap(); if (previous === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previous; removeTreeWithRetry(home); } +}); + +test("caller-main outcome cannot release a stored-credential raw binding", async () => { + const { releaseRequestOwnedMainOnOutcome } = await import("../../src/codex/request-owned-affinity"); + const { getThreadAffinity, peekPendingReleaseReason } = await import("../../src/codex/routing/thread-affinity"); + clearThreadAccountMap(); + bindThreadAffinity("app:stored-binding", "__main__", Date.now(), "shared"); + releaseRequestOwnedMainOnOutcome({ kind: "main", accountId: null, affinityKey: "app:stored-binding" }, 429, "gpt-5.5"); + expect(getThreadAffinity("app:stored-binding", "shared")?.accountId).toBe("__main__"); + expect(peekPendingReleaseReason("app:stored-binding")).toBeUndefined(); + clearThreadAccountMap(); +}); + +test.each(["pool", "main"] as const)("a delayed caller-main failure cannot retire a newer %s binding", async destination => { + const { mkdtempSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { removeTreeWithRetry } = await import("../helpers/remove-tree"); + const { saveCodexAccountCredential } = await import("../../src/codex/account-store"); + const { resolveCodexAuthContext } = await import("../../src/codex/auth-context"); + const { releaseRequestOwnedMainOnOutcome } = await import("../../src/codex/request-owned-affinity"); + const { getThreadAffinity, peekPendingReleaseReason } = await import("../../src/codex/routing/thread-affinity"); + const home = mkdtempSync(join(tmpdir(), "ocx-binding-race-")); + const oldHome = process.env.OPENCODEX_HOME, oldCodex = process.env.CODEX_HOME; + process.env.OPENCODEX_HOME = home; process.env.CODEX_HOME = home; + try { + saveCodexAccountCredential("a", { accessToken: "access-a", refreshToken: "refresh-a", expiresAt: Date.now() + 3600000, chatgptAccountId: "account-a" }); + const config = { providers: {}, codexAccounts: [{ id: "a", label: "a" }], pausedCodexAccountIds: ["a"], codexPool: { requestOwnedAffinity: true } } as import("../../src/types").OcxConfig; + const headers = new Headers({ authorization: "Bearer race-test", "session-id": "s", "thread-id": "t" }); + clearThreadAccountMap(); + const options = { requestScopedMainCredential: true, modelId: "gpt-5.5", primeCodexPoolQuotas: async () => {} }; + const first = await resolveCodexAuthContext(headers, config, "pool", options); + const reused = await resolveCodexAuthContext(headers, config, "pool", options); + expect(first.kind).toBe("main"); expect(first.affinityDecision?.move).toBe("new_bind"); expect(reused.affinityDecision?.move).toBe("reused"); + const key = first.affinityKey!; + const sameTime = getThreadAffinity(key, "shared")!.createdAt; + bindThreadAffinity(key, "a", sameTime, "shared"); + if (destination === "main") bindThreadAffinity(key, "__main__", sameTime, "shared"); + const stale = destination === "pool" ? { ...first, affinityDecision: { move: "detour", reason: "cooldown" } as const } : first; + releaseRequestOwnedMainOnOutcome(stale, 429, "gpt-5.5"); + expect(getThreadAffinity(key, "shared")?.accountId).toBe(destination === "pool" ? "a" : "__main__"); + expect(peekPendingReleaseReason(key)).toBeUndefined(); + } finally { + clearThreadAccountMap(); + if (oldHome === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = oldHome; + if (oldCodex === undefined) delete process.env.CODEX_HOME; else process.env.CODEX_HOME = oldCodex; + removeTreeWithRetry(home); + } +}); diff --git a/tests/codex-integration/reserve-auth-context.test.ts b/tests/codex-integration/reserve-auth-context.test.ts index c5ab020d0d8..82302391a85 100644 --- a/tests/codex-integration/reserve-auth-context.test.ts +++ b/tests/codex-integration/reserve-auth-context.test.ts @@ -168,6 +168,24 @@ afterEach(async () => { }); describe("Reserve owned auth admission", () => { + test("opt-in caller Reserve remains keyless even after ordinary affinity is bound", async () => { + const cfg = config(); + cfg.codexPool = { requestOwnedAffinity: true }; + const headers = caller(); + headers.set("session-id", "test-session"); + headers.set("thread-id", "test-thread"); + const options = { requestScopedMainCredential: true, primeCodexPoolQuotas: async () => {} }; + const first = await resolveCodexAuthContext(headers, cfg, "pool", options); + const second = await resolveCodexAuthContext(headers, cfg, "pool", options); + expect(first.affinityDecision?.move).toBe("new_bind"); + expect(second.affinityDecision?.move).toBe("reused"); + const reserve = await resolveCodexAuthContext(headers, cfg, "pool", { ...reserveOptions, ...options }); + expect(reserve.kind).toBe("main"); + expect(reserve.affinityKey).toBeUndefined(); + expect(reserve.affinityDecision).toBeUndefined(); + const { getThreadAffinity } = await import("../../src/codex/routing/thread-affinity"); + expect(getThreadAffinity(first.affinityKey!, "reserve")).toBeUndefined(); + }); test("unqualified Reserve pins stored main, requires capability WHAM, and carries private proof", async () => { const cfg = config(); const ctx = await resolveCodexAuthContext(new Headers(), cfg, "direct", reserveOptions); diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 59a85e01f92..053e11343bf 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -676,7 +676,8 @@ "codex-pin-drain-projection.test.ts": "codex-integration", "codex-plan.test.ts": "codex-integration", "codex-plugins-doctor.test.ts": "codex-integration", "codex-pool-plan-exclusion.test.ts": "codex-integration", "codex-pool-refresh-backoff.test.ts": "codex-integration", - "codex-pool-request-owned-main.test.ts": "codex-integration", "codex-pool-rotation.test.ts": "codex-integration", + "codex-pool-request-owned-main.test.ts": "codex-integration", + "codex-request-owned-affinity.test.ts": "codex-integration", "codex-pool-rotation.test.ts": "codex-integration", "codex-priority-failback.test.ts": "codex-integration", "codex-idle-window.test.ts": "codex-integration", "codex-round-robin-headroom.test.ts": "codex-integration", "codex-prompt-adopt.test.ts": "codex-integration", "codex-prompt-base-variants.test.ts": "codex-integration", diff --git a/tests/responses/compact-transient-alternate.test.ts b/tests/responses/compact-transient-alternate.test.ts index 4ec20a054ee..92112f605ed 100644 --- a/tests/responses/compact-transient-alternate.test.ts +++ b/tests/responses/compact-transient-alternate.test.ts @@ -301,3 +301,105 @@ describe("native compact moves a surviving transient 5xx to one alternate accoun expect(failures(WORK)).toBe(1); }); }); + +test.each([false, true])("caller-owned compact Pool-to-main retry scrubs continuation (affinity=%s)", async enabled => { + const { fakeChatGptJwt } = await import("../helpers/agent-task-recovery"); + const { rememberServingConversationStateIssuer } = await import("../../src/server/responses/account-change-state"); + const { peekConversationStateIssuer } = await import("../../src/codex/routing/thread-affinity"); + const bearer = fakeChatGptJwt("caller-test"); + const headers = new Headers({ authorization: `Bearer ${bearer}`, "content-type": "application/json", "session-id": "test-session", "thread-id": "test-thread" }); + const config = poolConfig({ codexAccounts: [{ id: WORK, label: WORK }], pausedCodexAccountIds: ["__main__"], codexPool: { requestOwnedAffinity: enabled } }); + const options = { requestScopedMainCredential: true, modelId: "gpt-5.5", primeCodexPoolQuotas: async () => {} }; + const first = await authContext.resolveCodexAuthContext(headers, config, "pool", options); + const second = await authContext.resolveCodexAuthContext(headers, config, "pool", options); + expect(first.affinityDecision?.move).toBe(enabled ? "new_bind" : "unbound"); + expect(second.affinityDecision?.move).toBe(enabled ? "reused" : "unbound"); + expect(first.kind).toBe("pool"); + rememberServingConversationStateIssuer(second); + const bodies: Record[] = []; + globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => { + sends.push(new Headers(init?.headers).get("authorization")); + bodies.push(JSON.parse(String(init?.body)) as Record); + if (sends.length === 1) config.pausedCodexAccountIds = []; + return sends.length === 1 ? overloadedOnce() : compacted(); + }) as typeof fetch; + const makeRequest = () => new Request("http://localhost/v1/responses/compact", { + method: "POST", headers, + body: JSON.stringify({ model: "gpt-5.5", previous_response_id: "opaque-previous", input: [{ role: "user", content: "continue" }] }), + }); + const response = await handleResponsesCompact(makeRequest(), config, { model: "", provider: "" }); + expect(sends.length).toBe(2); + expect(response.status).toBe(200); + expect(sends).toEqual(["Bearer work-access", `Bearer ${bearer}`]); + expect(bodies[1]?.previous_response_id).toBeUndefined(); + expect(peekConversationStateIssuer(first.conversationStateKey!)).toBe("__main__"); + config.pausedCodexAccountIds = ["__main__"]; + sends = []; bodies.length = 0; + globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => { + sends.push(new Headers(init?.headers).get("authorization")); + bodies.push(JSON.parse(String(init?.body)) as Record); + return compacted(); + }) as typeof fetch; + const next = await handleResponsesCompact(makeRequest(), config, { model: "", provider: "" }); + expect(next.status).toBe(200); + expect(sends).toEqual(["Bearer work-access"]); + expect(bodies[0]?.previous_response_id).toBeUndefined(); +}); + +test("caller-owned compact scrubs Pool to manually pinned main and back", async () => { + const { fakeChatGptJwt } = await import("../helpers/agent-task-recovery"); + const { rememberServingConversationStateIssuer } = await import("../../src/server/responses/account-change-state"); + const bearer = fakeChatGptJwt("pin-caller"); + const headers = new Headers({ authorization: `Bearer ${bearer}`, "content-type": "application/json", "session-id": "session", "thread-id": "thread" }); + const config = poolConfig({ codexAccounts: [{ id: WORK, label: WORK }], pausedCodexAccountIds: ["__main__"], codexPool: { requestOwnedAffinity: true } }); + const options = { requestScopedMainCredential: true, modelId: "gpt-5.5", primeCodexPoolQuotas: async () => {} }; + const first = await authContext.resolveCodexAuthContext(headers, config, "pool", options); + const second = await authContext.resolveCodexAuthContext(headers, config, "pool", options); + expect(first.affinityDecision?.move).toBe("new_bind"); expect(second.affinityDecision?.move).toBe("reused"); + expect(first.kind).toBe("pool"); rememberServingConversationStateIssuer(second); + const { resetCodexRoutingForManualSelection } = await import("../../src/codex/routing/active-account"); + resetCodexRoutingForManualSelection("__main__"); + config.activeCodexAccountId = "__main__"; config.activeCodexAccountPinned = "__main__"; config.pausedCodexAccountIds = []; + const bodies: Record[] = []; + globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => { + bodies.push(JSON.parse(String(init?.body)) as Record); + return compacted(); + }) as typeof fetch; + const request = (input: unknown = [{ role: "user", content: "continue" }]) => new Request("http://localhost/v1/responses/compact", { + method: "POST", headers, body: JSON.stringify({ model: "gpt-5.5", previous_response_id: "opaque", input }), + }); + const refusal = await handleResponsesCompact(request([{ role: "user", file_id: "opaque" }]), config, { model: "", provider: "" }); + expect(refusal.status).toBe(400); expect(bodies).toHaveLength(0); + const pinned = await handleResponsesCompact(request(), config, { model: "", provider: "" }); + expect(pinned.status).toBe(200); expect(bodies[0]?.previous_response_id).toBeUndefined(); + config.activeCodexAccountId = WORK; config.activeCodexAccountPinned = undefined; config.pausedCodexAccountIds = ["__main__"]; + const back = await handleResponsesCompact(request(), config, { model: "", provider: "" }); + expect(back.status).toBe(200); expect(bodies[1]?.previous_response_id).toBeUndefined(); +}); + +test("caller-owned compact main 429 releases only its conversation binding", async () => { + const { fakeChatGptJwt } = await import("../helpers/agent-task-recovery"); + const { getThreadAffinity } = await import("../../src/codex/routing/thread-affinity"); + const { getCodexQuotaHealthSnapshot } = await import("../../src/codex/routing"); + const bearer = fakeChatGptJwt("owned-compact-failure"); + const headers = new Headers({ authorization: `Bearer ${bearer}`, "content-type": "application/json", "session-id": "s", "thread-id": "t" }); + const config = poolConfig({ codexAccounts: [{ id: WORK, label: WORK }], pausedCodexAccountIds: [WORK], codexPool: { requestOwnedAffinity: true } }); + const options = { requestScopedMainCredential: true, modelId: "gpt-5.5", primeCodexPoolQuotas: async () => {} }; + const first = await authContext.resolveCodexAuthContext(headers, config, "pool", options); + const second = await authContext.resolveCodexAuthContext(headers, config, "pool", options); + expect(first.kind).toBe("main"); expect(first.affinityDecision?.move).toBe("new_bind"); + expect(second.affinityDecision?.move).toBe("reused"); + config.pausedCodexAccountIds = []; + let status = 200; + globalThis.fetch = (async () => status === 200 ? compacted() : Response.json({ error: { message: "quota exceeded" } }, { status: 429, headers: { "retry-after": "600" } })) as typeof fetch; + const makeRequest = () => new Request("http://localhost/v1/responses/compact", { method: "POST", headers, body: JSON.stringify({ model: "gpt-5.5", input: [{ role: "user", content: "continue" }] }) }); + expect((await handleResponsesCompact(makeRequest(), config, { model: "", provider: "" })).status).toBe(200); + expect(getThreadAffinity(first.affinityKey!, "shared")?.accountId).toBe("__main__"); + status = 429; + expect((await handleResponsesCompact(makeRequest(), config, { model: "", provider: "" })).status).toBe(429); + expect(getThreadAffinity(first.affinityKey!, "shared")).toBeUndefined(); + expect(getCodexQuotaHealthSnapshot("__main__", "shared")).toBeNull(); + const next = await authContext.resolveCodexAuthContext(headers, config, "pool", options); + expect(next.affinityDecision?.move).toBe("rebound"); + expect(next.affinityDecision?.reason).toBe("quota_refusal"); +}); diff --git a/tests/responses/responses-alternate-main-cancellation.test.ts b/tests/responses/responses-alternate-main-cancellation.test.ts index ca5fb4a13e9..a87f607cfde 100644 --- a/tests/responses/responses-alternate-main-cancellation.test.ts +++ b/tests/responses/responses-alternate-main-cancellation.test.ts @@ -251,3 +251,161 @@ for (const entry of ["retry helper", "messages ingress"] as const) { } }); } + +test.each([false, true])("caller-owned retry from Pool to main scrubs continuation (affinity=%s)", async enabled => { + const { rememberServingConversationStateIssuer, conversationStateBindingFromAuth, applyAccountChangeConversationStateScrub } = await import("../../src/server/responses/account-change-state"); + const { peekConversationStateIssuer } = await import("../../src/codex/routing/thread-affinity"); + const bearer = fakeChatGptJwt("fixture-caller", { exp: 4_000_000_000 }); + const headers = new Headers({ authorization: `Bearer ${bearer}`, "session-id": "session", "thread-id": "thread" }); + config.codexPool = { requestOwnedAffinity: enabled }; + config.pausedCodexAccountIds = [MAIN_CODEX_ACCOUNT_ID]; + const turn = tryAdmitTurn(); + expect(turn).not.toBeNull(); + const controller = new AbortController(); + try { + const authOptions = { modelId: "gpt-5.5", requestScopedMainCredential: true, primeCodexPoolQuotas: async () => {}, beginCodexAccountSelection: codexAccountSelectionForTurn(turn!) }; + const first = await resolveCodexAuthContext(headers, config, "pool", authOptions); + const reused = await resolveCodexAuthContext(headers, config, "pool", authOptions); + expect(first.affinityDecision?.move).toBe(enabled ? "new_bind" : "unbound"); + expect(reused.affinityDecision?.move).toBe(enabled ? "reused" : "unbound"); + expect(first.kind).toBe("pool"); + if (first.kind !== "pool") throw new Error("expected pool fixture"); + rememberServingConversationStateIssuer(first); + config.pausedCodexAccountIds = []; + let sentBody: Record | undefined; + globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => { + sentBody = JSON.parse(String(init?.body)) as Record; + return completedInference(); + }) as typeof fetch; + const parsed = parseRequest({ model: "gpt-5.5", previous_response_id: "opaque-previous", input: "hello", stream: false }); + const result = await retryCodexPoolOnAlternateAccount({ + callerAuthHeaders: headers, config, firstAuthCtx: first, firstResponse: quotaRefusal(), outcomeStatus: 429, + route: { providerName: "openai", modelId: "gpt-5.5", provider: config.providers.openai! }, + parsed, logCtx: { model: "", provider: "" }, + options: { abortSignal: controller.signal, translatorBudget: createTranslatorBudget(), turnAdmissionLease: turn! }, + upstream: controller, connectMs: 10_000, stream: false, httpOnly: true, + }); + expect(result.kind).toBe("retried"); + if (result.kind !== "retried") throw new Error("expected alternate retry"); + expect(result.authCtx.kind).toBe("main"); + expect(sentBody?.previous_response_id).toBeUndefined(); + rememberServingConversationStateIssuer(result.authCtx, first.conversationStateKey); + expect(peekConversationStateIssuer(first.conversationStateKey!)).toBe(MAIN_CODEX_ACCOUNT_ID); + config.pausedCodexAccountIds = [MAIN_CODEX_ACCOUNT_ID]; + clearCodexUpstreamHealth(); + const next = await resolveCodexAuthContext(headers, config, "pool", authOptions); + const binding = conversationStateBindingFromAuth(next)!; + const body = { previous_response_id: "opaque-main-response" }; + expect(applyAccountChangeConversationStateScrub({ body, bindingKey: binding.bindingKey, servingAccountId: binding.accountId })).toBe(true); + expect(body).not.toHaveProperty("previous_response_id"); + } finally { turn?.release(); } +}); + +test("regular Responses scrubs retained issuer on a manual main pin and on return to Pool", async () => { + const { rememberServingConversationStateIssuer } = await import("../../src/server/responses/account-change-state"); + const { forgetRuntimeActiveCodexAccount, resetCodexRoutingForManualSelection } = await import("../../src/codex/routing/active-account"); + const { handleResponses } = await import("../../src/server/responses"); + const { rememberResponseState, clearResponseStateForTests } = await import("../../src/responses/state"); + const bearer = fakeChatGptJwt("fixture-pin-caller", { exp: 4_000_000_000 }); + const headers = new Headers({ authorization: `Bearer ${bearer}`, "content-type": "application/json", "session-id": "session", "thread-id": "thread" }); + config.codexPool = { requestOwnedAffinity: true }; config.pausedCodexAccountIds = [MAIN_CODEX_ACCOUNT_ID]; + const turn = tryAdmitTurn(); + expect(turn).not.toBeNull(); + try { + const options = { requestScopedMainCredential: true, modelId: "gpt-5.5", primeCodexPoolQuotas: async () => {}, beginCodexAccountSelection: codexAccountSelectionForTurn(turn!) }; + const first = await resolveCodexAuthContext(headers, config, "pool", options); + const second = await resolveCodexAuthContext(headers, config, "pool", options); + expect(first.affinityDecision?.move).toBe("new_bind"); expect(second.affinityDecision?.move).toBe("reused"); + expect(first.kind).toBe("pool"); rememberServingConversationStateIssuer(second); + resetCodexRoutingForManualSelection(MAIN_CODEX_ACCOUNT_ID); + config.activeCodexAccountId = MAIN_CODEX_ACCOUNT_ID; config.activeCodexAccountPinned = MAIN_CODEX_ACCOUNT_ID; config.pausedCodexAccountIds = []; + const sent: Record[] = []; + globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => { sent.push(JSON.parse(String(init?.body)) as Record); return completedInference(); }) as typeof fetch; + clearResponseStateForTests(); + rememberResponseState({ model: "gpt-5.5", input: [{ role: "user", content: "earlier" }] }, { id: "opaque", status: "completed", output: [] }, undefined, { force: true }); + const request = (input: unknown = [{ role: "user", content: "hello" }]) => new Request("http://localhost/v1/responses", { method: "POST", headers, + body: JSON.stringify({ model: "gpt-5.5", previous_response_id: "opaque", input, stream: false }) }); + const refusal = await handleResponses(request([{ role: "user", file_id: "opaque" }]), config, { model: "", provider: "" }, { turnAdmissionLease: turn! }); + expect(refusal.status).toBe(400); expect(await refusal.text()).toContain("uploaded file"); expect(sent).toHaveLength(0); + const pinned = await handleResponses(request(), config, { model: "", provider: "" }, { turnAdmissionLease: turn! }); + const pinnedText = await pinned.text(); + if (pinned.status !== 200) throw new Error(`pinned status ${pinned.status}: ${pinnedText}`); + expect(sent[0]?.previous_response_id).toBeUndefined(); + forgetRuntimeActiveCodexAccount(); + config.activeCodexAccountId = POOL_ID; config.activeCodexAccountPinned = undefined; config.pausedCodexAccountIds = [MAIN_CODEX_ACCOUNT_ID]; + const back = await handleResponses(request(), config, { model: "", provider: "" }, { turnAdmissionLease: turn! }); + expect(back.status).toBe(200); await back.text(); expect(sent[1]?.previous_response_id).toBeUndefined(); + } finally { clearResponseStateForTests(); turn?.release(); } +}); + +test.each([429, 503])("caller-owned Responses main quota refusal %s releases only its conversation binding", async refusalStatus => { + const { handleResponses } = await import("../../src/server/responses"); + const { getThreadAffinity } = await import("../../src/codex/routing/thread-affinity"); + const { getCodexQuotaHealthSnapshot } = await import("../../src/codex/routing"); + const headers = new Headers({ authorization: `Bearer ${fakeChatGptJwt("owned-responses-failure")}`, "content-type": "application/json", "session-id": "s", "thread-id": "t" }); + config.codexPool = { requestOwnedAffinity: true }; config.pausedCodexAccountIds = [POOL_ID]; + config.accountPoolStrategy = "round-robin"; config.accountPoolStickyLimit = 1; + const turn = tryAdmitTurn(); expect(turn).not.toBeNull(); + try { + const options = { requestScopedMainCredential: true, modelId: "gpt-5.5", primeCodexPoolQuotas: async () => {}, beginCodexAccountSelection: codexAccountSelectionForTurn(turn!) }; + const first = await resolveCodexAuthContext(headers, config, "pool", options); + const second = await resolveCodexAuthContext(headers, config, "pool", options); + expect(first.kind).toBe("main"); expect(first.affinityDecision?.move).toBe("new_bind"); expect(second.affinityDecision?.move).toBe("reused"); + config.pausedCodexAccountIds = []; + let status = 200; + globalThis.fetch = (async () => status === 200 ? completedInference() : refusalStatus === 429 ? quotaRefusal() : Response.json({ error: { code: "usage_limit_reached", message: "usage limit reached" } }, { status: 503, headers: { "retry-after": "600" } })) as typeof fetch; + const makeRequest = () => new Request("http://localhost/v1/responses", { method: "POST", headers, body: JSON.stringify({ model: "gpt-5.5", input: "hello", stream: false }) }); + const success = await handleResponses(makeRequest(), config, { model: "", provider: "" }, { turnAdmissionLease: turn! }); + expect(success.status).toBe(200); await success.text(); + expect(getThreadAffinity(first.affinityKey!, "shared")?.accountId).toBe(MAIN_CODEX_ACCOUNT_ID); + status = 429; + const failure = await handleResponses(makeRequest(), config, { model: "", provider: "" }, { turnAdmissionLease: turn! }); + expect(failure.status).toBe(refusalStatus); await failure.text(); + expect(getThreadAffinity(first.affinityKey!, "shared")).toBeUndefined(); + expect(getCodexQuotaHealthSnapshot(MAIN_CODEX_ACCOUNT_ID, "shared")).toBeNull(); + const next = await resolveCodexAuthContext(headers, config, "pool", options); + expect(next.affinityDecision?.move).toBe("rebound"); expect(next.affinityDecision?.reason).toBe("quota_refusal"); + } finally { turn?.release(); } +}); + +test("websocket terminal recorder releases a caller-owned main binding on quota refusal", async () => { + const { handleResponses } = await import("../../src/server/responses"); + const { getThreadAffinity } = await import("../../src/codex/routing/thread-affinity"); + const headers = new Headers({ authorization: `Bearer ${fakeChatGptJwt("owned-ws-failure")}`, "content-type": "application/json", "session-id": "s", "thread-id": "t" }); + config.codexPool = { requestOwnedAffinity: true }; config.pausedCodexAccountIds = [POOL_ID]; + config.accountPoolStrategy = "round-robin"; config.accountPoolStickyLimit = 1; + const turn = tryAdmitTurn(); expect(turn).not.toBeNull(); + try { + const options = { requestScopedMainCredential: true, modelId: "gpt-5.5", primeCodexPoolQuotas: async () => {}, beginCodexAccountSelection: codexAccountSelectionForTurn(turn!) }; + const first = await resolveCodexAuthContext(headers, config, "pool", options); + const second = await resolveCodexAuthContext(headers, config, "pool", options); + expect(first.kind).toBe("main"); expect(first.affinityDecision?.move).toBe("new_bind"); expect(second.affinityDecision?.move).toBe("reused"); + config.pausedCodexAccountIds = []; + globalThis.fetch = (async () => completedInference()) as typeof fetch; + let record: ((status: "completed" | "failed" | "incomplete", httpStatusOverride?: number) => void) | undefined; + const req = new Request("http://localhost/v1/responses", { method: "POST", headers, body: JSON.stringify({ model: "gpt-5.5", input: "hello", stream: true }) }); + const response = await handleResponses(req, config, { model: "", provider: "" }, { turnAdmissionLease: turn!, inboundTransport: "websocket", recordTerminalOutcomes: false, setTerminalOutcomeRecorder: fn => { record = fn; } }); + expect(response.status).toBe(200); await response.text(); + expect(record).toBeDefined(); + record!("incomplete", 429); + expect(getThreadAffinity(first.affinityKey!, "shared")).toBeUndefined(); + } finally { turn?.release(); } +}); + +test("unkeyed caller-main 5xx does not inspect quota response body", async () => { + const { handleResponses } = await import("../../src/server/responses"); + const account = await import("../../src/server/responses/core-codex-account"); + const { spyOn } = await import("bun:test"); + const headers = new Headers({ authorization: `Bearer ${fakeChatGptJwt("unkeyed-inspection")}`, "content-type": "application/json" }); + config.pausedCodexAccountIds = [POOL_ID]; + const turn = tryAdmitTurn(); expect(turn).not.toBeNull(); + const quotaInspector = spyOn(account, "shouldRetryCodexPoolAccountQuota").mockResolvedValue(false); + try { + globalThis.fetch = (async () => Response.json({ error: { message: "server error" } }, { status: 503, headers: { "retry-after": "600" } })) as typeof fetch; + const req = new Request("http://localhost/v1/responses", { method: "POST", headers, body: JSON.stringify({ model: "gpt-5.5", input: "hello", stream: false }) }); + const response = await handleResponses(req, config, { model: "", provider: "" }, { turnAdmissionLease: turn! }); + expect(response.status).toBe(503); + expect(quotaInspector).not.toHaveBeenCalled(); + await response.text(); + } finally { quotaInspector.mockRestore(); turn?.release(); } +}); diff --git a/tests/responses/responses-forward-incomplete-quota.test.ts b/tests/responses/responses-forward-incomplete-quota.test.ts index ee79fd9c182..25ca110e060 100644 --- a/tests/responses/responses-forward-incomplete-quota.test.ts +++ b/tests/responses/responses-forward-incomplete-quota.test.ts @@ -340,3 +340,19 @@ describe("incomplete quota endpoint reporter wiring", () => { await exerciseSpawnReporter("native-sse"); }, { timeout: SERVER_BUDGET_MS }); }); + +test("caller-owned main streamed terminal releases only on a refusal", async () => { + const { requestOwnedAffinityKey, captureRequestOwnedAffinityBindings } = await import("../../src/codex/request-owned-affinity"); + const { bindThreadAffinity, getThreadAffinity, peekPendingReleaseReason, affinityAfterRelease } = await import("../../src/codex/routing/thread-affinity"); + const key = requestOwnedAffinityKey(new Headers({ authorization: "Bearer stream-test", "session-id": "s", "thread-id": "t" }))!; + clearThreadAccountMap(); bindThreadAffinity(key, "__main__", Date.now(), "shared"); + const ctx: CodexAuthContext = { kind: "main", accountId: null, affinityKey: key, affinityBindingSnapshot: captureRequestOwnedAffinityBindings(key, "shared", "gpt-test") }; + const record = codexForwardTerminalOutcomeRecorder(getDefaultConfig(), ctx, provider, "gpt-test", { model: "gpt-test", provider: "openai" }); + expect(record).toBeDefined(); + record!("completed"); + expect(getThreadAffinity(key, "shared")?.accountId).toBe("__main__"); + record!("incomplete", 429); + expect(getThreadAffinity(key, "shared")).toBeUndefined(); + expect(peekPendingReleaseReason(key)).toBe("quota_refusal"); + affinityAfterRelease(key, "quota_refusal"); clearThreadAccountMap(); +}); diff --git a/tests/responses/responses-preview-main-read-fence.test.ts b/tests/responses/responses-preview-main-read-fence.test.ts index bb3a95a7024..d59e01df5d6 100644 --- a/tests/responses/responses-preview-main-read-fence.test.ts +++ b/tests/responses/responses-preview-main-read-fence.test.ts @@ -626,3 +626,102 @@ describe("preview and final authentication agree on the native-main read fence", expect(upstreamAuth[0]).not.toBe("Bearer physical-main-token"); }); }); + +test("subagent preview evaluates affinity separately for Reserve candidates", async () => { + const routing = await import("../../src/codex/routing"); + const auth = await import("../../src/codex/auth-context"); + const { bindThreadAffinity } = await import("../../src/codex/routing/thread-affinity"); + const config = providerConfig({ codexDesktopAuthless: true, codexPool: { requestOwnedAffinity: true }, subagentModelFallback: ["gpt-reserve", "gpt-5.5"] }); + const headers = codexHeaders("caller-account", { "session-id": "preview-session", "thread-id": "preview-thread" }); + config.pausedCodexAccountIds = [MAIN_CODEX_ACCOUNT_ID]; + const authOptions = { requestScopedMainCredential: true, modelId: PREFERRED_MODEL, primeCodexPoolQuotas: async () => {} }; + const first = await auth.resolveCodexAuthContext(headers, config, "pool", authOptions); + const second = await auth.resolveCodexAuthContext(headers, config, "pool", authOptions); + expect(first.affinityDecision?.move).toBe("new_bind"); + expect(second.affinityDecision?.move).toBe("reused"); + const key = first.affinityKey!; + expect(key).toBe(auth.codexRequestAffinityKey(headers, config, config, { requestScopedMainCredential: true })); + config.pausedCodexAccountIds = []; + bindThreadAffinity(key, "pool-a", NOW, "reserve"); + noteSubagentModelFailure(PREFERRED_MODEL, "429", config, "pool-a", NOW); + noteSubagentModelFailure("gpt-reserve", "429", config, MAIN_CODEX_ACCOUNT_ID, NOW); + noteSubagentModelFailure("gpt-reserve", "429", config, "pool-a", NOW); + const observed: Array<{ model: string | undefined; key: string | null; account: string | null }> = []; + const original = routing.previewCodexAccountForRequest; + const spy = spyOn(routing, "previewCodexAccountForRequest").mockImplementation((thread, cfg, now, scope, opts, model, lineage) => { + const account = original(thread, cfg, now, scope, opts, model, lineage); + observed.push({ model, key: thread, account }); + return account; + }); + globalThis.fetch = (async () => completedCanonicalSse()) as typeof fetch; + try { + const logCtx: RequestLogContext = { model: "", provider: "" }; + const response = await postSpawn(config, { admission: { kind: "loopback", source: "loopback" } }, headers, readableInput(), PREFERRED_MODEL, logCtx); + expect(response.status).toBe(200); + expect(observed.some(row => row.model === "gpt-reserve" && row.key === null)).toBe(true); + expect(observed.some(row => row.model === "gpt-5.5" && row.key === key && row.account === "pool-a")).toBe(true); + expect((logCtx as unknown as Record).subagentModelFallbackTo).toBe("gpt-5.5"); + } finally { spy.mockRestore(); } +}); + +test("recovery preview reads the recovered ownership key and lineage", async () => { + const routing = await import("../../src/codex/routing"); + const auth = await import("../../src/codex/auth-context"); + const coreAuth = await import("../../src/server/responses/core-auth"); + const { recordCodexThreadLineage, clearCodexThreadLineageForTests } = await import("../../src/codex/lineage"); + const { bindThreadAffinity } = await import("../../src/codex/routing/thread-affinity"); + const config = providerConfig({ defaultProvider: "xai", agentTaskRecovery: { enabled: true }, codexPool: { requestOwnedAffinity: true }, subagentModelFallback: ["gpt-5.5"] }); + const headers = codexHeaders("caller-account", { "session-id": "recovery-session", "thread-id": "recovery-thread" }); + clearCodexThreadLineageForTests(); + config.pausedCodexAccountIds = [MAIN_CODEX_ACCOUNT_ID]; + const authOptions = { requestScopedMainCredential: true, modelId: "gpt-5.5", primeCodexPoolQuotas: async () => {} }; + const first = await auth.resolveCodexAuthContext(headers, config, "pool", authOptions); + const second = await auth.resolveCodexAuthContext(headers, config, "pool", authOptions); + expect(first.affinityDecision?.move).toBe("new_bind"); + expect(second.affinityDecision?.move).toBe("reused"); + const ownedKey = first.affinityKey!; + config.pausedCodexAccountIds = []; + const lineage = recordCodexThreadLineage(headers)!; + const rawKey = auth.codexPoolAffinityKey(headers)!; + bindThreadAffinity(rawKey, MAIN_CODEX_ACCOUNT_ID, NOW, "shared"); + noteSubagentModelFailure("gpt-5.5", "429", config, MAIN_CODEX_ACCOUNT_ID, NOW); + noteSubagentModelFailure("gpt-5.5", "429", config, "pool-a", NOW); + let recovered = false; + const observed: Array<{ key: string | null; model: string | undefined; lineage: unknown; account: string | null; recovered: boolean }> = []; + const originalPreview = routing.previewCodexAccountForRequest; + const preview = spyOn(routing, "previewCodexAccountForRequest").mockImplementation((key, cfg, now, scope, opts, model, hint) => { + const account = originalPreview(key, cfg, now, scope, opts, model, hint); + observed.push({ key, model, lineage: hint, account, recovered }); + return account; + }); + // The request-level harness cannot naturally reroute from a readable canonical candidate to a + // recovery-required provider: ciphertext restricts the first fallback pass to trusted routes. + // Switch the credential-domain result at the recovery boundary to exercise the real closure + // with the headers and ownership that a reroute would provide. + const originalDomainHeaders = coreAuth.codexRouteCredentialDomainHeaders; + const domainHeaders = spyOn(coreAuth, "codexRouteCredentialDomainHeaders").mockImplementation((...args) => recovered ? new Headers(headers) : originalDomainHeaders(...args)); + const originalOwnership = coreAuth.codexRouteCredentialOwnership; + const ownershipCalls: Array<{ recovered: boolean; hasAuth: boolean }> = []; + const ownership = spyOn(coreAuth, "codexRouteCredentialOwnership").mockImplementation((...args) => { ownershipCalls.push({ recovered, hasAuth: args[0].has("authorization") }); return { ...originalOwnership(...args), requestScopedMainCredential: recovered }; }); + globalThis.fetch = (async (input, init) => { + if (typeof init?.body === "string" && init.body.includes("capture_assignment")) { + recovered = true; + resetSubagentModelFallbackStateForTests(); + noteSubagentModelFailure("xai/grok-4.5", "429", config, null, NOW); + return new Response(recoverySse("Recovered assignment"), { headers: { "content-type": "text/event-stream" } }); + } + const url = new URL(input instanceof Request ? input.url : String(input)); + return url.hostname === "chatgpt.com" ? completedCanonicalSse() : completedResponses(FALLBACK_MODEL); + }) as typeof fetch; + try { + const logCtx: RequestLogContext = { model: "", provider: "" }; + const response = await postSpawn(config, {}, headers, encryptedInput(), "xai/grok-4.5", logCtx); + expect(response.status).toBe(200); + expect(recovered).toBe(true); + expect(observed.some(row => !row.recovered && row.key === rawKey && row.lineage !== undefined && row.account === MAIN_CODEX_ACCOUNT_ID)).toBe(true); + expect(ownershipCalls).toContainEqual({ recovered: true, hasAuth: true }); + expect(observed.filter(row => row.recovered).map(row => ({ model: row.model, owned: row.key === ownedKey, raw: row.key === rawKey, hasLineage: row.lineage !== undefined, account: row.account }))).toContainEqual({ model: "gpt-5.5", owned: true, raw: false, hasLineage: false, account: "pool-a" }); + expect((logCtx as unknown as Record).subagentModelFallbackTo).toBe("gpt-5.5"); + expect(lineage.conversationKey).toBe(rawKey); + } finally { preview.mockRestore(); ownership.mockRestore(); domainHeaders.mockRestore(); clearCodexThreadLineageForTests(); } +}); From b14a35afe9ee25e7f7ea2f550b7485c22e20ebd3 Mon Sep 17 00:00:00 2001 From: JUN Date: Mon, 2 Nov 2026 19:41:20 +0900 Subject: [PATCH 05/43] fix(claude): bind header-less Messages bridge turns to one Codex pool account (carry #8028) (#8094) * fix(claude): bind header-less Messages bridge turns to one Codex pool account The Messages bridge replays each Claude turn on an internal /v1/responses request. Without caller session-id and thread-id, codexPoolAffinityKey is undefined, so the Codex pool never binds the turn and round-robin with session pinning moves every turn to the next account. The bridge now resolves a private pool identity (caller session alias, else the metadata session, else x-claude-code-session-id; derived values are scoped to the admitted principal for remote callers) and passes it out of band as HandleResponsesOptions.claudeBridgePoolSession. Only Codex account-selection headers complete session-id and thread-id from it: credential-domain headers, both 401 refresh materializations, and the route-independent pool key in request prepare. Replay headers stay untouched, so request logs, reasoning replay, Go lanes, adapter fingerprints, Anthropic passthrough and non-Codex routes are unchanged. Spawn turns, declared parents, caller thread ids and complete caller pairs keep their behavior. Carries #8028. Co-authored-by: vibewriter-hand <337401476+vibewriter-hand@users.noreply.github.com> * test(claude): isolate lineage and prove parent-account inheritance in bridge pool dispatch * docs(pool): note Claude Code session binding for Codex pool strategies * fix(claude): scope bridge pool aliases per principal and keep the pool identity off the wire Remote callers' session_id/session-id aliases now pass through the same principal scoping as the metadata and Claude session header values before they name a Codex pool session; no principal means no identity. The completed session-id/thread-id are now given only to Codex account selection (final and alternate-account) and selection previews. First-send, 401 refresh and alternate-account retry headers are built from the uncompleted request headers, so the upstream wire is unchanged from dev. Co-authored-by: vibewriter-hand <337401476+vibewriter-hand@users.noreply.github.com> * fix(claude): key bridge pool identities with a process-local secret A complete caller-supplied session-id + thread-id pair reaches Codex selection unscoped, so a synthesized pool identity must not be computable by callers. Every identity the bridge names (caller alias, metadata session or Claude session header) is now an HMAC under a process-local key over its admission scope (loopback, or the remote principal), never the raw value or a public hash. The identity stays in the process: replay and upstream headers are built without it. Co-authored-by: vibewriter-hand <337401476+vibewriter-hand@users.noreply.github.com> * test(claude): observe the alternate-account pick's selection key in bridge pool failover * docs(structure): name the metadata-derived cache key as the bridge identity source --------- Co-authored-by: vibewriter-hand <337401476+vibewriter-hand@users.noreply.github.com> --- .../docs/reference/configuration/providers.md | 2 +- .../test-layout/layout-server-inbound.json | 4 +- src/server/claude-bridge-pool-session.ts | 59 ++++ src/server/claude-messages.ts | 5 + src/server/responses/core-auth.ts | 23 +- src/server/responses/core-codex-account.ts | 7 +- src/server/responses/core-options.ts | 2 + src/server/responses/request-prepare.ts | 3 +- structure/data-planes/inbound-compat.md | 17 ++ .../providers/codex-installation-identity.md | 2 + .../transports/response-turn-membership.md | 2 + .../claude-bridge-pool-dispatch.test.ts | 258 ++++++++++++++++++ .../claude-bridge-pool-session.test.ts | 83 ++++++ tests/fixtures/test-layout-expected.json | 1 + 14 files changed, 461 insertions(+), 7 deletions(-) create mode 100644 src/server/claude-bridge-pool-session.ts create mode 100644 tests/claude-integration/claude-bridge-pool-dispatch.test.ts create mode 100644 tests/claude-integration/claude-bridge-pool-session.test.ts diff --git a/docs-site/src/content/docs/reference/configuration/providers.md b/docs-site/src/content/docs/reference/configuration/providers.md index 082c0dd688f..7190882103a 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -125,7 +125,7 @@ separate. Full request URLs such as `/api/v1/responses` are not provider base UR | `codexAccountPriorityFailback?` | `boolean` | `false` | Opt-in return of ongoing Codex Pool tasks to a usable higher-priority account under the `quota` strategy. Requests trigger a background quota refresh at most once every five minutes, including failed refresh attempts. When recent quota observations show headroom, the next request may rebind even if its current account is below the threshold. This explicit preference can discard a warm prompt cache; it does not change default cache affinity. No requests means no polling. Manual pins, model access, cooldowns, pauses and reauthentication exclusions still apply; in-flight requests keep their captured account. Requires the current source account's effective threshold to be positive (an override of 0 disables it; a positive override works with global 0); exact account routes and Direct mode are unchanged. | | `autoSwitchThreshold?` | `number` | `80` | Usage threshold for placing new/unbound work. `quota` can re-evaluate unbound tasks on their next request once usage crosses this threshold. Bound tasks keep their account past the threshold by default (`pool.cacheAffinity`); they leave only when that account is exhausted or otherwise cannot serve, and then only for an account with genuine quota headroom and strictly lower usage. Set `pool.cacheAffinity: false` to re-evaluate bound tasks at this threshold, still only onto such a destination. `fill-first` uses it only as the drain point for unbound assignment; `round-robin` uses it only when placing new/unbound work: it skips accounts at or over their effective threshold while any eligible account is still under it, and never moves a bound task for it. The score uses the hottest known 5h, weekly, or 30d quota window. `0` disables usage-based proactive switching only, not unbound assignment or failure recovery. | | `codexAccountAutoSwitchThresholds?` | `Record` | — | Per-account overrides for `autoSwitchThreshold`: account id → integer from `0` to `100`. An absent entry inherits the global value; `0` disables usage-driven switching only when that account is the source. `quota` uses the current source account's effective threshold for bound-task re-evaluation and unbound switching. Fill-first drain and selection-order tier headroom are evaluated against each account's own effective threshold; main-account pins and subagent fallback also use the relevant account's effective threshold. Supports the main `__main__` account. A malformed map is ignored with a warning. Managed by each account card on the Codex Auth page; disabling an override removes its entry. Enabling the override copies the current global threshold into a fixed account value. The override, including `0`, takes precedence over later global changes. Disabling it sends `threshold: null`, removes the entry, and restores inheritance of the current global threshold and future global changes. | -| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | Assignment strategy for new/unbound Codex requests. A request is unbound when it has no live (parent thread id, quota scope) affinity; a visible existing task can become unbound after proxy restart or affinity reset. `quota` picks the lowest-usage eligible account when no active account exists, keeps an eligible active account below `autoSwitchThreshold`, and after the threshold may move an unbound request. Bound tasks follow `pool.cacheAffinity` (on by default): they stay until the account is exhausted (known usage at 100%) or otherwise cannot serve, and then may rebind only to an account with genuine quota headroom and strictly lower usage. Set the flag `false` to proactively rebind a bound task at the threshold, still only onto such a destination. `round-robin` distributes unbound requests evenly across eligible accounts still under their effective `autoSwitchThreshold`, and across all eligible accounts when every one is at or over it; `fill-first` keeps assigning unbound requests to the active account until cooldown, unavailability, or the configured drain threshold. `reset-first`: Prefer the nearest future 5-hour or weekly reset among accounts below the usage threshold. Bound tasks follow the configured affinity policy. Independent model quotas use quota ordering. Monthly resets do not determine this ordering. | +| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | Assignment strategy for new/unbound Codex requests. A request is unbound when it has no live (parent thread id, quota scope) affinity; a visible existing task can become unbound after proxy restart or affinity reset. `quota` picks the lowest-usage eligible account when no active account exists, keeps an eligible active account below `autoSwitchThreshold`, and after the threshold may move an unbound request. Bound tasks follow `pool.cacheAffinity` (on by default): they stay until the account is exhausted (known usage at 100%) or otherwise cannot serve, and then may rebind only to an account with genuine quota headroom and strictly lower usage. Set the flag `false` to proactively rebind a bound task at the threshold, still only onto such a destination. `round-robin` distributes unbound requests evenly across eligible accounts still under their effective `autoSwitchThreshold`, and across all eligible accounts when every one is at or over it; `fill-first` keeps assigning unbound requests to the active account until cooldown, unavailability, or the configured drain threshold. `reset-first`: Prefer the nearest future 5-hour or weekly reset among accounts below the usage threshold. Bound tasks follow the configured affinity policy. Independent model quotas use quota ordering. Monthly resets do not determine this ordering. Under every strategy, a Claude Code turn that reaches a Codex account route through `/v1/messages` is bound by its Claude session: a caller `session_id`/`session-id` alias if present, else the metadata session, else `x-claude-code-session-id`; the binding is keyed to the admitted credential (or to local loopback use) with a server-held secret, so callers cannot share, guess or reuse another credential's binding. The binding is used only to choose the account; the headers sent upstream are unchanged. Spawn turns and turns that already carry `x-codex-parent-thread-id`, `thread-id` or a complete session/thread pair keep their own identity. A bound session normally stays on one account; the affinity and failure-recovery rules above can still move it. | | `pool.cacheAffinity?` | `boolean` | `true` | Cache-affinity ordering for bound Codex threads, independent of `pool.kernel`. On by default; omitting the key or setting `true` keeps a bound task on its account until that account genuinely cannot serve. Only an explicit `false` restores threshold-based rebinding of bound tasks. A live binding outranks quota headroom: `quota` does not move the thread merely because usage crossed `autoSwitchThreshold`. The thread still leaves if that account cannot serve — paused, unusable, or genuinely exhausted (known usage at 100%) — and then only to an account with genuine quota headroom and strictly lower usage. Under either setting, an account with unknown usage is never chosen as a destination for a bound task, so when every account sits above the threshold the task stays put. Affinity is a reordering, not a pin. | | `pool.credentialGroups?` | `Array<{ id: string; credentials: string[]; note?: string }>` | `[]` | Accepted and validated, but not yet consumed by routing: declaring a group changes no routing decision until a consuming layer lands. Operator-declared quota domains: groups of credentials that demonstrably share one upstream usage limit. Members of one group count once toward available capacity, and a quota refusal inside a group is not answered by rotating to another member — the limit is the same, so the move would pay a cold prefix for zero new capacity. Declared groups speak only to quota; sharing a limit says nothing about prompt-cache compatibility, which is classified separately. Each member is written provider-qualified as `":"`, because a credential id means something only inside its provider; the provider segment accepts the usual aliases (`chatgpt:` and `codex:` both mean OpenAI). Group ids must be unique, `credentials` must be non-empty, and a credential may appear in at most one group — an ambiguous declaration is rejected on write and dropped with a warning on load rather than resolved by whichever group is listed first, since that would merge two unrelated quota domains. A malformed list costs only the grouping: `pool.kernel` and `pool.cacheAffinity` are preserved. Absent or empty means no declared grouping, so an unconfigured install behaves exactly as before. | | `accountPoolStickyLimit?` | `number` | `1` | New/unbound task assignments retained on one round-robin selection before advancing; the counter advances when a task is bound, not after an upstream success. Range 1–100. | diff --git a/scripts/test-layout/layout-server-inbound.json b/scripts/test-layout/layout-server-inbound.json index f38f6530ecd..41002edc674 100644 --- a/scripts/test-layout/layout-server-inbound.json +++ b/scripts/test-layout/layout-server-inbound.json @@ -1,5 +1,7 @@ { "config-concurrent-inbound-body.test.ts": "config", "inbound-body-admission.test.ts": "server", - "inbound-body-budget.test.ts": "server" + "inbound-body-budget.test.ts": "server", + "claude-bridge-pool-session.test.ts": "claude-integration", + "claude-bridge-pool-dispatch.test.ts": "claude-integration" } diff --git a/src/server/claude-bridge-pool-session.ts b/src/server/claude-bridge-pool-session.ts new file mode 100644 index 00000000000..6fb34e375c4 --- /dev/null +++ b/src/server/claude-bridge-pool-session.ts @@ -0,0 +1,59 @@ +/** Private pool identity for translated Claude turns; replay headers remain unchanged. */ +import { createHmac, randomBytes } from "node:crypto"; +import { codexPoolAffinityKey } from "../codex/auth-context"; +import { contextPrincipalIdOf, type DataPlaneAdmission } from "./auth-cors"; +import { safeCallerSessionId } from "./caller-session-identity"; +import { isThreadSpawnRequest } from "./effort-policy"; +import type { RouteResult } from "../router"; +import type { HandleResponsesOptions } from "./responses/core-options"; + +/** + * Process-local, like the lineage key: a synthesized identity never leaves the process (replay and + * upstream headers stay uncompleted), so no caller can name it, not even as a complete + * session-id + thread-id pair, which reaches the pool unscoped. + */ +const BRIDGE_POOL_KEY = randomBytes(32); + +export function resolveClaudeBridgePoolSession(args: { + ingress: Headers; replay: Headers; metadataSessionId?: string; admission?: DataPlaneAdmission; +}): string | undefined { + const { ingress, replay, metadataSessionId, admission } = args; + if (!admission || isThreadSpawnRequest(ingress) || isThreadSpawnRequest(replay)) return undefined; + if (ingress.has("x-codex-parent-thread-id") || ingress.has("thread-id")) return undefined; + if (codexPoolAffinityKey(replay) !== undefined) return undefined; + let value: string | undefined; + if (ingress.has("session_id") || ingress.has("session-id")) { + const first = ingress.get("session_id"); + const second = ingress.get("session-id"); + if (first && second && first !== second) return undefined; + value = safeCallerSessionId(first || second); + } else { + value = safeCallerSessionId(metadataSessionId ?? ingress.get("x-claude-code-session-id")); + } + if (!value) return undefined; + // Every identity this bridge names, caller aliases included, is bound to its admission scope: + // a shared or guessed value must never select another principal's conversation key. + let scope: unknown = "loopback"; + if (admission.kind !== "loopback") { + const principal = contextPrincipalIdOf(admission); + if (!principal) return undefined; + scope = ["principal", principal]; + } + return createHmac("sha256", BRIDGE_POOL_KEY) + .update(JSON.stringify(["opencodex-claude-bridge-pool-v1", scope, value])).digest("hex"); +} + +export function completeClaudeBridgePoolIdentity(headers: Headers, options: Pick): Headers { + const session = options.claudeBridgePoolSession; + if (!session || headers.get("x-codex-parent-thread-id") || headers.get("thread-id") + || codexPoolAffinityKey(headers) !== undefined) return headers; + const completed = new Headers(headers); + completed.set("session-id", session); + completed.set("thread-id", session); + return completed; +} + +export function applyClaudeBridgePoolSession(headers: Headers, route: Pick, + options: Pick): Headers { + return route.codexAccountMode !== undefined ? completeClaudeBridgePoolIdentity(headers, options) : headers; +} diff --git a/src/server/claude-messages.ts b/src/server/claude-messages.ts index 45170d2f755..344d15d8462 100644 --- a/src/server/claude-messages.ts +++ b/src/server/claude-messages.ts @@ -8,6 +8,7 @@ import { CodexInstallationIdUnavailableError } from "../codex/installation-id"; * unchanged. The Responses output (SSE or JSON) is converted back to Anthropic shape. */ import { FORWARD_HEADERS } from "../adapters/openai-responses"; +import { resolveClaudeBridgePoolSession } from "./claude-bridge-pool-session"; import { admissionModelDeniedResponse, AdmissionModelDeniedError, @@ -1176,6 +1177,9 @@ async function handleClaudeMessagesWithBudget( ?? normalizeLogConversationId(req.headers.get("x-opencode-session")) ?? metadataGoLane ?? getOrAllocateRequestSessionLane(req); + const claudeBridgePoolSession = resolveClaudeBridgePoolSession({ + ingress: req.headers, replay: headers, metadataSessionId: claudeNativeSessionId, admission: logIds?.admission, + }); let internalReq: Request; try { // The UTF-16 JSON string and the Request's UTF-8 body coexist until dispatch. @@ -1239,6 +1243,7 @@ async function handleClaudeMessagesWithBudget( ? { tools: anthropicBody.tools, messages: anthropicBody.messages, tool_choice: anthropicBody.tool_choice } : undefined, claudeGoAffinity: { sessionLane: claudeGoSessionLane }, claudeNativeSessionId, + ...(claudeBridgePoolSession ? { claudeBridgePoolSession } : {}), stripClaudeMainAuthForNoncanonicalForward: true, ...(trustedClaudeMainAuth ? { trustedClaudeMainAuth } : {}), // Claude's internal stored-main enrichment is not an original caller credential. diff --git a/src/server/responses/core-auth.ts b/src/server/responses/core-auth.ts index 6f3990d4cc7..d5ba2c19b99 100644 --- a/src/server/responses/core-auth.ts +++ b/src/server/responses/core-auth.ts @@ -1,3 +1,4 @@ +import { applyClaudeBridgePoolSession } from "../claude-bridge-pool-session"; import type { OcxProviderConfig, OcxConfig } from "../../types"; import { isCanonicalOpenAiForwardProvider } from "../../providers/openai-tiers"; import type { CodexAuthContext } from "../../codex/auth-context"; @@ -111,7 +112,7 @@ function validatedCallerDirectHeaders( return captureCallerDirectAuth(headers, config) ? headers : undefined; } -export function codexRouteCredentialDomainHeaders( +function codexRouteCredentialDomainHeadersFor( req: Request, route: RouteResult, options: HandleResponsesOptions, @@ -156,6 +157,20 @@ export function codexRouteCredentialDomainHeaders( } +/** + * Credential-domain headers for Codex account SELECTION (previews, recovery, final resolution). + * A Claude bridge pool identity is completed here only; upstream headers are always materialized + * from the uncompleted form, so the synthesized pair never reaches the wire. + */ +export function codexRouteCredentialDomainHeaders( + req: Request, route: RouteResult, options: HandleResponsesOptions, + credentialDomainWasRewritten: boolean, config: OcxConfig, +): Headers { + return applyClaudeBridgePoolSession( + codexRouteCredentialDomainHeadersFor(req, route, options, credentialDomainWasRewritten, config), route, options, + ); +} + /** * Does this route substitute OUR stored main credential, and does the caller own the credential * this request will authenticate with? @@ -210,7 +225,7 @@ export async function resolveResponsesCodexAuth( // routed credential with it either, because that would be a silent credential swap. if (hasAgentAssertionAuthorization(req.headers)) return { ok: false, response: agentAssertionUnsupportedResponse() }; try { - let authInputHeaders = codexRouteCredentialDomainHeaders( + let authInputHeaders = codexRouteCredentialDomainHeadersFor( req, route, options, @@ -270,7 +285,9 @@ export async function resolveResponsesCodexAuth( validateForwardAdmissionCredential(authInputHeaders, config); } if (route.codexAccountMode) { - authCtx = await resolveCodexAuthContext(authInputHeaders, config, route.codexAccountMode, { + // Only selection sees the Claude bridge pool identity; materialization below keeps the + // uncompleted headers, so the wire matches the original request. + authCtx = await resolveCodexAuthContext(applyClaudeBridgePoolSession(authInputHeaders, route, options), config, route.codexAccountMode, { admission: options.admission, codexAuthPolicy: options.codexAuthPolicy, accountId: route.codexAccountId, diff --git a/src/server/responses/core-codex-account.ts b/src/server/responses/core-codex-account.ts index f48f5cf7b82..736c2c1f1e7 100644 --- a/src/server/responses/core-codex-account.ts +++ b/src/server/responses/core-codex-account.ts @@ -27,6 +27,7 @@ import { formatErrorResponse } from "../../bridge"; import { readBoundedResponseBody } from "../../lib/bounded-body"; import { upstreamErrorMessageFromPayload, isRateLimitOrQuotaFailureMessage } from "../../lib/errors"; import { isNonReplayableResponse, isTransientUpstreamStatus, SendBudgetExhaustedError } from "../../lib/upstream-retry"; +import { applyClaudeBridgePoolSession } from "../claude-bridge-pool-session"; import { codexWsPreOutputRefusalHold, codexWsPreOutputRefusalOutcomeRecorded, @@ -490,6 +491,8 @@ export interface CodexPoolAccountRetryArgs { abortSignal?: AbortSignal; onCodexAuthContextResolved?: (ctx: CodexAuthContext) => void; deferCodexResetDerivedCooldown?: boolean; + /** Private Claude bridge pool identity; alternate selection completes it like the first pick. */ + claudeBridgePoolSession?: string; // Narrowed subset of HandleResponsesOptions: the retry rebuilds the adapter, so it // needs the inbound scope or the retry could land on a different wire than the // first attempt. @@ -767,7 +770,9 @@ export async function retryCodexPoolOnAlternateAccount( } try { retryAuthCtx ??= await resolveCodexAuthContext( - callerAuthHeaders, + // Alternate selection keeps the initial Claude bridge pool identity; the retry's upstream + // headers are still built from uncompleted callerAuthHeaders below. + applyClaudeBridgePoolSession(callerAuthHeaders, { codexAccountMode: "pool" }, options), config, "pool", { diff --git a/src/server/responses/core-options.ts b/src/server/responses/core-options.ts index 36473e8ed7b..049463cff9b 100644 --- a/src/server/responses/core-options.ts +++ b/src/server/responses/core-options.ts @@ -118,6 +118,8 @@ export interface HandleResponsesOptions { claudeGoAffinity?: { sessionLane?: string }; /** Validated Claude metadata identity; projected only into final canonical attempt headers. */ claudeNativeSessionId?: string; + /** Private Claude bridge pool identity (validated, principal-scoped when derived); completes session-id/thread-id only on Codex account-selection headers. */ + claudeBridgePoolSession?: string; /** Original live policy owner; separate from caller-specific routing/sidecar snapshots. */ codexAuthPolicy?: CodexAuthPolicyConfig; turnAdmissionLease?: AdmissionLease; diff --git a/src/server/responses/request-prepare.ts b/src/server/responses/request-prepare.ts index 065c3f66357..7985abb8b60 100644 --- a/src/server/responses/request-prepare.ts +++ b/src/server/responses/request-prepare.ts @@ -1,3 +1,4 @@ +import { completeClaudeBridgePoolIdentity } from "../claude-bridge-pool-session"; import type { HandleResponsesOptions, ResponsesRequestContext, ResponsesAdmissionState, ResponsesDispatchers } from "./core-options"; import type { PolicyRequestEvidence } from "../../routing/evaluator"; import type { RequestLogContext } from "../request-log"; @@ -952,7 +953,7 @@ export async function prepareResponsesRequest( let subagentFallbackModelEligibleAccountIdsForModel: SubagentModelEligibleAccountIds | undefined; let subagentQuotaFailureModel = parsed.modelId; const parentThreadId = req.headers.get("x-codex-parent-thread-id")?.trim() ?? null; - const poolAffinityKey = codexPoolAffinityKey(req.headers) ?? null; + const poolAffinityKey = codexPoolAffinityKey(completeClaudeBridgePoolIdentity(req.headers, options)) ?? null; // Preview has to see the same lineage resolve does. Without it, a child's first turn is // previewed as a cold pick and resolved onto the family account, and the subagent fallback // then decides model eligibility against an account the request will never use. diff --git a/structure/data-planes/inbound-compat.md b/structure/data-planes/inbound-compat.md index 00135946d9d..b00ba62b047 100644 --- a/structure/data-planes/inbound-compat.md +++ b/structure/data-planes/inbound-compat.md @@ -389,6 +389,23 @@ canonical Go transport, including combo selection and failover. No Go-only repla reaches non-Go destinations. Shared system cache keys never become conversation identity. The request-scoped fallback is stable across retries and distinct across client requests. +The Messages bridge carries a separate private Codex pool identity without changing replay headers. +It requires admission and excludes spawn markers, any ingress parent or thread header (even empty) +and a replay with a complete pool key. Explicit session_id then session-id aliases win; conflicting, +empty-only or invalid aliases block derivation. Otherwise the metadata session (the uuid form of the +metadata-derived prompt_cache_key), then the Claude session header, supplies the value; a system-derived +cohort key never does. Every value, aliases included, is HMAC-keyed with a process-local secret over its +admission scope (loopback, or the principal a remote caller must have), so no caller can name another +scope's pool key, not even as a complete pair. A caller-supplied complete pair stays unscoped. + +The identity is selection-only: session-id and thread-id are completed for Codex account selection +(final and alternate-account), selection previews, recovery and the route-independent pool key used +as state-binding fallback. Every upstream header set (first send, 401 refresh, alternate-account retry) +is built from the uncompleted headers, so the wire is unchanged and no synthesized pair or digest is +forwarded. Non-Codex routes, Anthropic passthrough, request logs, reasoning replay, Go lanes and adapter +fingerprints are unchanged. claude-bridge-pool-session.test.ts and claude-bridge-pool-dispatch.test.ts +cover the rules, the wire contract, 401 refresh and alternate-account failover. + Claude metadata also supplies a private native-session value. Only the final canonical ChatGPT attempt receives it, in copied forwarding headers; an explicit underscore session, hyphenated session or thread header suppresses synthesis. Refresh and alternate-account retries retain diff --git a/structure/providers/codex-installation-identity.md b/structure/providers/codex-installation-identity.md index 0e16b361d64..d16f82cf067 100644 --- a/structure/providers/codex-installation-identity.md +++ b/structure/providers/codex-installation-identity.md @@ -70,3 +70,5 @@ Authenticated live and frame contracts are covered by `tests/codex-integration/codex-installation-live-ws.test.ts`; compact empty-header and turn-size contracts are covered by `tests/responses/codex-installation-compact-empty.test.ts` and `tests/responses/codex-installation-turn-limit.test.ts`. + +The Claude bridge carries its private pool identity through Codex selection; see [Claude affinity](../data-planes/inbound-compat.md#claude-affinity-at-final-go-dispatch). diff --git a/structure/transports/response-turn-membership.md b/structure/transports/response-turn-membership.md index 894a20b21e6..67b27165ac0 100644 --- a/structure/transports/response-turn-membership.md +++ b/structure/transports/response-turn-membership.md @@ -36,3 +36,5 @@ retry and queued rebuilds through `src/server/responses/adapter-dispatch.ts` and `src/server/responses/request-transport.ts`; missing metadata keeps earlier tool delivery off. This structural mechanism does not alter supplier bodies, reasoning effort, retry policy, settlement or provider-opaque replay scope. + +The route-independent Claude bridge pool key agrees with final Codex selection; see [Claude affinity](../data-planes/inbound-compat.md#claude-affinity-at-final-go-dispatch). diff --git a/tests/claude-integration/claude-bridge-pool-dispatch.test.ts b/tests/claude-integration/claude-bridge-pool-dispatch.test.ts new file mode 100644 index 00000000000..5b900ee7fe9 --- /dev/null +++ b/tests/claude-integration/claude-bridge-pool-dispatch.test.ts @@ -0,0 +1,258 @@ +import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { MAIN_CODEX_ACCOUNT_ID } from "../../src/codex/main-account"; +import { clearMainAccountInfoCache } from "../../src/codex/auth-api"; +import { fakeChatGptJwt } from "../helpers/fake-chatgpt-jwt"; +import { clearCodexThreadLineageForTests, recordCodexThreadLineage, resolveCodexThreadLineage } from "../../src/codex/lineage"; +import { saveCodexAccountCredential } from "../../src/codex/account-store"; +import { clearThreadAccountMap, clearCodexUpstreamHealth } from "../../src/codex/routing"; +import { codexPoolAffinityKey } from "../../src/codex/auth-context"; +import * as authContext from "../../src/codex/auth-context"; +import { clearConversationStateIssuerMap, peekConversationStateIssuer } from "../../src/codex/routing/thread-affinity"; +import { clearAccountQuota, updateAccountQuota } from "../../src/codex/auth-api"; +import { handleClaudeMessages } from "../../src/server/claude-messages"; +import { resolveClaudeBridgePoolSession } from "../../src/server/claude-bridge-pool-session"; +import { tryAdmitTurn } from "../../src/server/lifecycle"; +import type { DataPlaneAdmission } from "../../src/server/auth-cors"; +import type { OcxConfig } from "../../src/types"; +import { installIsolatedCodexHome, type IsolatedCodexHome } from "../helpers/isolated-codex-home"; +import { acquireOwnedSpendHome } from "../helpers/owned-spend-home"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +const originalFetch = globalThis.fetch; +const local: DataPlaneAdmission = { kind: "loopback", source: "loopback" }; +const metadataUuid = "9745d86c-d579-494a-8d0e-f69a5214cf96"; +const principal = (id: string): DataPlaneAdmission => ({ kind: "configured", keyId: "fixture", source: "dedicated", contextPrincipalId: id }); +// What a caller could compute from public inputs; the keyed bridge identity must never equal it. +const publicDigest = (principalId: string, value: string) => new Bun.CryptoHasher("sha256") + .update(JSON.stringify(["opencodex-caller-session-v1", principalId, value])).digest("hex"); +// The bridge's own identity for these inputs (same process key), used to read its bookkeeping. +const bridgeIdentity = (admission: DataPlaneAdmission, ingress: Record = {}, metadataSessionId?: string) => + resolveClaudeBridgePoolSession({ ingress: new Headers(ingress), replay: new Headers(ingress), admission, metadataSessionId })!; +const poolKey = (identity: string) => codexPoolAffinityKey(new Headers({ "session-id": identity, "thread-id": identity }))!; +const account = (wire: Headers | undefined) => wire?.get("chatgpt-account-id"); +/** The pool identity is selection-only: no attempt may carry a synthesized pair upstream. */ +function expectNoSynthesizedPair(wire: Headers) { + expect(wire.has("session-id")).toBe(false); + expect(wire.has("thread-id")).toBe(false); + for (const name of ["session_id", "session-id", "thread-id"]) expect(wire.get(name) ?? "").not.toMatch(/^[0-9a-f]{64}$/); +} +let home: string, previous: string | undefined, isolated: IsolatedCodexHome, release: () => void; +let wires: Headers[]; +let cfg: OcxConfig; + +beforeEach(() => { + previous = process.env.OPENCODEX_HOME; + home = mkdtempSync(join(tmpdir(), "ocx-bridge-pool-")); + process.env.OPENCODEX_HOME = home; + isolated = installIsolatedCodexHome("ocx-bridge-codex-"); + release = acquireOwnedSpendHome(); + clearThreadAccountMap(); clearCodexUpstreamHealth(); clearAccountQuota(); clearCodexThreadLineageForTests(); clearConversationStateIssuerMap(); + for (const id of ["fixture-a", "fixture-b"]) { + saveCodexAccountCredential(id, { accessToken: `fixture-access-${id}`, refreshToken: `fixture-refresh-${id}`, expiresAt: Date.now() + 3_600_000, chatgptAccountId: `account-${id}` }); + updateAccountQuota(id, 10, 10); + } + cfg = { defaultProvider: "openai", activeCodexAccountId: "fixture-a", autoSwitchThreshold: 0, + accountPoolStrategy: "round-robin", accountPoolStickyLimit: 1, + codexAccounts: [{ id: "fixture-a", label: "a" }, { id: "fixture-b", label: "b" }], + providers: { openai: { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", authMode: "forward", codexAccountMode: "pool", upstreamWebsocket: false } }, + } as unknown as OcxConfig; + wires = []; + globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => { + wires.push(new Headers(init?.headers)); + return Response.json({ id: "resp_fixture", object: "response", status: "completed", output: [], usage: { input_tokens: 1, output_tokens: 0, total_tokens: 1 } }); + }) as typeof fetch; +}); +afterEach(() => { + globalThis.fetch = originalFetch; clearMainAccountInfoCache(); release(); isolated.restore(); + if (previous === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previous; + removeTreeWithRetry(home); clearThreadAccountMap(); clearCodexUpstreamHealth(); clearAccountQuota(); clearCodexThreadLineageForTests(); clearConversationStateIssuerMap(); +}); + +async function turn(session: string | undefined, admission: DataPlaneAdmission = local, headers: Record = {}, model = "openai/gpt-5.4") { + const lease = tryAdmitTurn(); + expect(lease).not.toBeNull(); + try { + const response = await handleClaudeMessages(new Request("http://localhost/v1/messages", { method: "POST", + headers: { "content-type": "application/json", ...headers }, + body: JSON.stringify({ model, max_tokens: 32, stream: false, ...(session ? { metadata: { user_id: session } } : {}), messages: [{ role: "user", content: "ping" }] }), + }), cfg, { model: "", provider: "" }, { requestId: "fixture", start: Date.now(), turnAdmissionLease: lease!, admission }); + await response.text(); + expect(response.status).toBe(200); + } finally { lease?.release(); } +} + +test("pool binds multiple turns and separates sessions while preserving the native session", async () => { + for (const session of ["user_test_account__session_conversation-native", "user_test_account__session_conversation-native", "user_test_account__session_other", "user_test_account__session_other"]) await turn(session); + expect(wires).toHaveLength(4); + expect(wires[0]!.get("chatgpt-account-id")).toBe(wires[1]!.get("chatgpt-account-id")); + expect(wires[2]!.get("chatgpt-account-id")).toBe(wires[3]!.get("chatgpt-account-id")); + expect(wires[0]!.get("chatgpt-account-id")).not.toBe(wires[2]!.get("chatgpt-account-id")); + expect(wires[0]!.get("session_id")).toBe(metadataUuid); + for (const wire of wires) expectNoSynthesizedPair(wire); +}); + +test("a synthesized identity with a recorded parent follows the parent's account", async () => { + const child = bridgeIdentity(local, {}, metadataUuid); + // A complete caller pair keeps dev behavior, so this binds the root to the first round-robin pick. + await turn(undefined, local, { "session-id": "fixture-root", "thread-id": "fixture-root" }); + const childHeaders = new Headers({ "session-id": child, "thread-id": child, "x-codex-parent-thread-id": "fixture-root" }); + recordCodexThreadLineage(childHeaders); + const rootPair = new Headers({ "session-id": child, "thread-id": child }); + expect(resolveCodexThreadLineage(rootPair)?.parentThreadId).toBe("fixture-root"); + await turn("user_test_account__session_conversation-native"); + await turn("user_test_account__session_conversation-native"); + // Control: an unrelated cold session lands on the other account, so the child's placement + // above came from the recorded parent rather than from a cold pick. + await turn("user_test_account__session_unrelated"); + const rootAccount = wires[0]!.get("chatgpt-account-id"); + expect(rootAccount).toBeTruthy(); + expect(wires[1]!.get("chatgpt-account-id")).toBe(rootAccount); + expect(wires[2]!.get("chatgpt-account-id")).toBe(rootAccount); + expect(wires[3]!.get("chatgpt-account-id")).not.toBe(rootAccount); + expect(resolveCodexThreadLineage(rootPair)?.parentThreadId).toBe("fixture-root"); +}); + +test("remote principals with identical metadata pin separately and keep the dev wire", async () => { + for (const id of ["a", "a", "b", "b", "a"]) await turn("user_test_account__session_conversation-native", principal(id)); + expect(account(wires[1])).toBe(account(wires[0])); + expect(account(wires[2])).not.toBe(account(wires[0])); + expect(account(wires[3])).toBe(account(wires[2])); + expect(account(wires[4])).toBe(account(wires[0])); + for (const wire of wires) { + expect(wire.get("session_id")).toBe(metadataUuid); + expectNoSynthesizedPair(wire); + } +}); + +test("remote principals sending the same session alias do not share a pool binding", async () => { + for (const id of ["a", "a", "b", "b", "a"]) await turn(undefined, principal(id), { session_id: "fixture-alias" }); + expect(account(wires[1])).toBe(account(wires[0])); + expect(account(wires[2])).not.toBe(account(wires[0])); + expect(account(wires[3])).toBe(account(wires[2])); + expect(account(wires[4])).toBe(account(wires[0])); + for (const wire of wires) { + expect(wire.get("session_id")).toBe("fixture-alias"); + expectNoSynthesizedPair(wire); + } +}); + +test("an alias equal to another principal's derived identity does not join that binding", async () => { + await turn("user_test_account__session_conversation-native", principal("b")); + const victim = bridgeIdentity(principal("b"), {}, metadataUuid); + await turn(undefined, principal("a"), { session_id: victim }); + await turn(undefined, principal("a"), { session_id: victim }); + expect(account(wires[1])).not.toBe(account(wires[0])); + expect(account(wires[2])).toBe(account(wires[1])); + expect(peekConversationStateIssuer(poolKey(victim))).toBe(account(wires[0])!.replace(/^account-/, "")); +}); + +test("a complete caller pair built from public inputs cannot address a synthesized identity", async () => { + await turn("user_test_account__session_conversation-native", principal("b")); + const victim = bridgeIdentity(principal("b"), {}, metadataUuid); + const victimAccount = account(wires[0])!.replace(/^account-/, ""); + // Raw metadata session and the publicly computable digest are what an attacker could know. + for (const guess of [metadataUuid, publicDigest("b", metadataUuid)]) { + expect(guess).not.toBe(victim); + expect(poolKey(guess)).not.toBe(poolKey(victim)); + await turn(undefined, principal("a"), { "session-id": guess, "thread-id": guess }); + } + expect(account(wires[1])).not.toBe(account(wires[0])); + expect(peekConversationStateIssuer(poolKey(victim))).toBe(victimAccount); +}); + +test("caller session-id aliases and complete pairs reach the wire exactly as sent", async () => { + await turn(undefined, local, { "session-id": "fixture-hyphen" }); + expect(wires[0]!.get("session-id")).toBe("fixture-hyphen"); + expect(wires[0]!.get("session_id")).toBe("fixture-hyphen"); + expect(wires[0]!.has("thread-id")).toBe(false); + await turn(undefined, principal("a"), { "session-id": "fixture-pair", "thread-id": "fixture-pair" }); + expect(wires[1]!.get("session-id")).toBe("fixture-pair"); + expect(wires[1]!.get("thread-id")).toBe("fixture-pair"); +}); + +test("spawn markers do not synthesize thread identity", async () => { + for (const marker of [{ "x-openai-subagent": "collab_spawn" }, { "x-codex-turn-metadata": '{"subagent_kind":"thread_spawn"}' }]) { + await turn("user_test_account__session_conversation-native", local, marker); + } + expect(wires).toHaveLength(2); + for (const wire of wires) expect(wire.has("thread-id")).toBe(false); +}); + +test("API-key Responses routes do not receive pool identity", async () => { + cfg.providers.other = { adapter: "openai-responses", authMode: "key", apiKey: "fixture-key", baseUrl: "https://example.invalid/v1", models: ["m"] }; + await turn("user_test_account__session_conversation-native", local, {}, "other/m"); + expect(wires[0]!.has("thread-id")).toBe(false); + expect(wires[0]!.has("session-id")).toBe(false); +}); + +for (const mode of ["stored", "main"] as const) for (const variant of ["local", "remote", "header"] as const) test(`${mode} pool 401 refresh keeps the dev wire for ${variant} identity on retry`, async () => { + cfg.codexAccounts = mode === "stored" ? [{ id: "fixture-a", label: "a" }] : []; + if (mode === "main") { + cfg.activeCodexAccountId = MAIN_CODEX_ACCOUNT_ID; + clearMainAccountInfoCache(); + const token = fakeChatGptJwt({ exp: Math.floor(Date.now() / 1000) + 86400, chatgpt_account_id: "fixture-main" }); + writeFileSync(join(isolated.path, "auth.json"), JSON.stringify({ tokens: { access_token: token, refresh_token: "fixture-main-grant", account_id: "fixture-main" } })); + } + let refreshes = 0; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(input instanceof Request ? input.url : String(input)); + if (url.hostname === "auth.openai.com") { + refreshes++; + return Response.json({ access_token: mode === "main" ? fakeChatGptJwt({ exp: Math.floor(Date.now() / 1000) + 86400, chatgpt_account_id: "fixture-main" }) : "fixture-refreshed-access", refresh_token: "fixture-refreshed-grant", expires_in: 3600 }); + } + if (!url.pathname.endsWith("/responses")) return Response.json({ rate_limit: { primary_window: { used_percent: 10 } } }); + wires.push(new Headers(init?.headers)); + return wires.length === 1 ? Response.json({ error: { message: "expired" } }, { status: 401 }) + : Response.json({ id: "resp_fixture", object: "response", status: "completed", output: [], usage: { input_tokens: 1, output_tokens: 0, total_tokens: 1 } }); + }) as typeof fetch; + const admission: DataPlaneAdmission = variant === "remote" ? { kind: "configured", keyId: "fixture", source: "dedicated", contextPrincipalId: "fixture-principal" } : local; + await turn(variant === "header" ? undefined : "user_test_account__session_conversation-native", admission, + variant === "header" ? { "x-claude-code-session-id": "fixture-header" } : {}); + expect(refreshes).toBe(1); + expect(wires).toHaveLength(2); + for (const name of ["session_id", "session-id", "thread-id"]) { + expect(wires[1]!.get(name)).toBe(wires[0]!.get(name)); + } + expect(wires[0]!.get("session_id")).toBe(variant === "header" ? null : metadataUuid); + for (const wire of wires) expectNoSynthesizedPair(wire); +}); + +for (const variant of ["local-metadata", "remote-alias"] as const) test(`alternate-account failover binds ${variant} under the initial selection key`, async () => { + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(input instanceof Request ? input.url : String(input)); + if (!url.pathname.endsWith("/responses")) return Response.json({ rate_limit: { primary_window: { used_percent: 10 } } }); + wires.push(new Headers(init?.headers)); + return wires.length === 1 ? Response.json({ error: { message: "rate limited" } }, { status: 429 }) + : Response.json({ id: "resp_fixture", object: "response", status: "completed", output: [], usage: { input_tokens: 1, output_tokens: 0, total_tokens: 1 } }); + }) as typeof fetch; + const send = () => variant === "local-metadata" + ? turn("user_test_account__session_conversation-native") + : turn(undefined, principal("fixture-principal"), { session_id: "fixture-alias" }); + // Observe the alternate pick itself: its selection headers must carry the initial pool key. + const alternatePickKeys: Array = []; + const resolveSpy = spyOn(authContext, "resolveCodexAuthContext"); + try { + await send(); + for (const call of resolveSpy.mock.calls) { + const [headers, , , options] = call as Parameters; + if (options?.excludeAccountId) alternatePickKeys.push(codexPoolAffinityKey(headers)); + } + } finally { resolveSpy.mockRestore(); } + expect(wires).toHaveLength(2); + const alternate = account(wires[1]); + expect(alternate).toBeTruthy(); + expect(alternate).not.toBe(account(wires[0])); + const identity = variant === "local-metadata" + ? bridgeIdentity(local, {}, metadataUuid) + : bridgeIdentity(principal("fixture-principal"), { session_id: "fixture-alias" }); + const key = poolKey(identity); + expect(alternatePickKeys).toEqual([key]); + // The alternate account's conversation-state issuer is recorded under the initial selection key. + expect(peekConversationStateIssuer(key)).toBe(alternate!.replace(/^account-/, "")); + await send(); + expect(account(wires[2])).toBe(alternate); + for (const wire of wires) expectNoSynthesizedPair(wire); +}); diff --git a/tests/claude-integration/claude-bridge-pool-session.test.ts b/tests/claude-integration/claude-bridge-pool-session.test.ts new file mode 100644 index 00000000000..532711467ec --- /dev/null +++ b/tests/claude-integration/claude-bridge-pool-session.test.ts @@ -0,0 +1,83 @@ +import { expect, test } from "bun:test"; +import { codexPoolAffinityKey } from "../../src/codex/auth-context"; +import { getDefaultConfig } from "../../src/config"; +import { routeConcreteModel } from "../../src/router"; +import { codexRouteCredentialDomainHeaders } from "../../src/server/responses/core-auth"; +import { applyClaudeBridgePoolSession, completeClaudeBridgePoolIdentity, resolveClaudeBridgePoolSession } from "../../src/server/claude-bridge-pool-session"; +import type { DataPlaneAdmission } from "../../src/server/auth-cors"; + +const local: DataPlaneAdmission = { kind: "loopback", source: "loopback" }; +const remote = (principal?: string): DataPlaneAdmission => ({ kind: "configured", keyId: "fixture", source: "bearer", contextPrincipalId: principal }); +const resolve = (headers: Record = {}, admission: DataPlaneAdmission | undefined = local, metadataSessionId?: string, replay = new Headers(headers)) => + resolveClaudeBridgePoolSession({ ingress: new Headers(headers), replay, admission, metadataSessionId }); + +test("admission, spawn and explicit lineage gate synthesis", () => { + expect(resolveClaudeBridgePoolSession({ ingress: new Headers({ session_id: "alias" }), replay: new Headers() })).toBeUndefined(); + expect(resolveClaudeBridgePoolSession({ ingress: new Headers(), replay: new Headers(), metadataSessionId: "metadata" })).toBeUndefined(); + for (const marker of [{ "x-openai-subagent": "collab_spawn" }, { "x-codex-turn-metadata": '{"subagent_kind":"thread_spawn"}' }]) { + expect(resolve(marker, local, "metadata")).toBeUndefined(); + expect(resolve({}, local, "metadata", new Headers(marker))).toBeUndefined(); + } + for (const name of ["thread-id", "x-codex-parent-thread-id"]) for (const value of ["", "parent"]) { + expect(resolve({ [name]: value }, local, "metadata")).toBeUndefined(); + } + expect(resolve({}, local, "metadata", new Headers({ "session-id": "existing", "thread-id": "existing" }))).toBeUndefined(); +}); + +test("aliases take precedence and conflicts or invalid values block derivation", () => { + // An alias names the same keyed identity a derived value of the same text would in that scope. + const alias = resolve({}, local, "alias"); + for (const headers of [{ session_id: "alias" }, { "session-id": "alias" }, { session_id: "alias", "session-id": "alias" }, { session_id: "", "session-id": "alias" }]) expect(resolve(headers, local, "metadata")).toBe(alias); + for (const headers of [{ session_id: "a", "session-id": "b" }, { session_id: "" }, { session_id: "bad value", "session-id": "valid" }, { session_id: "bad value" }]) expect(resolve(headers, local, "metadata")).toBeUndefined(); +}); + +test("derived metadata and header identities are keyed per admission scope", () => { + const loopback = resolve({}, local, "metadata"); + expect(loopback).toMatch(/^[0-9a-f]{64}$/); + expect(loopback).not.toBe("metadata"); + expect(resolve({}, local, "metadata")).toBe(loopback); + const a = resolve({}, remote("a"), "metadata"); + expect(a).toMatch(/^[0-9a-f]{64}$/); + expect(resolve({}, remote("a"), "metadata")).toBe(a); + expect(resolve({}, remote("b"), "metadata")).not.toBe(a); + expect(a).not.toBe(loopback); + expect(resolve({}, remote(), "metadata")).toBeUndefined(); + expect(resolve({ "x-claude-code-session-id": "header" })).toBe(resolve({}, local, "header")); + expect(resolve({ "x-claude-code-session-id": "header" }, remote("a"))).toMatch(/^[0-9a-f]{64}$/); + expect(resolve({ "x-claude-code-session-id": "bad value" })).toBeUndefined(); + expect(resolve({ "prompt_cache_key": "shared-system" })).toBeUndefined(); +}); + +test("caller aliases are keyed to their principal and never computable from public inputs", () => { + const publicDigest = (principal: string, value: string) => new Bun.CryptoHasher("sha256") + .update(JSON.stringify(["opencodex-caller-session-v1", principal, value])).digest("hex"); + for (const name of ["session_id", "session-id"]) { + const a = resolve({ [name]: "fixture-alias" }, remote("a"), "metadata"); + expect(a).toMatch(/^[0-9a-f]{64}$/); + expect(a).not.toBe(publicDigest("a", "fixture-alias")); + expect(resolve({ [name]: "fixture-alias" }, remote("a"), "metadata")).toBe(a); + expect(resolve({ [name]: "fixture-alias" }, remote("b"), "metadata")).not.toBe(a); + expect(resolve({ [name]: "fixture-alias" }, remote(), "metadata")).toBeUndefined(); + expect(resolve({ [name]: "fixture-alias" }, local, "metadata")).not.toBe("fixture-alias"); + } + // A caller that knows another principal's derived identity cannot reuse it as an alias. + const victim = resolve({}, remote("b"), "metadata")!; + expect(resolve({ session_id: victim }, remote("a"))).not.toBe(victim); +}); + +test("completion agrees with final credential-domain headers for both Codex routes", () => { + const config = getDefaultConfig(); + const route = routeConcreteModel(config, "openai/gpt-5.4")!; + const headers = new Headers(); + const options = { claudeBridgePoolSession: "conversation" }; + expect(applyClaudeBridgePoolSession(headers, { codexAccountMode: undefined }, options)).toBe(headers); + const complete = completeClaudeBridgePoolIdentity(headers, options); + const key = codexPoolAffinityKey(complete); + expect(key).toBeDefined(); + const req = new Request("http://localhost/v1/responses", { headers }); + for (const [mode, rewrite] of [["pool", false], ["direct", true]] as const) { + const codexRoute = { ...route, codexAccountMode: mode }; + expect(codexPoolAffinityKey(codexRouteCredentialDomainHeaders(req, codexRoute, options, rewrite, config))).toBe(key); + } + expect(completeClaudeBridgePoolIdentity(complete, options)).toBe(complete); +}); diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 053e11343bf..a839b41d9d3 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -508,6 +508,7 @@ "messages-native-decline-trace.test.ts": "claude-integration", "messages-native-oauth.test.ts": "claude-integration", "messages-native-opaque-state.test.ts": "claude-integration", "messages-surface-matrix.test.ts": "claude-integration", "claude-model-info.test.ts": "claude-integration", "claude-models-discovery.test.ts": "claude-integration", + "claude-bridge-pool-session.test.ts": "claude-integration", "claude-bridge-pool-dispatch.test.ts": "claude-integration", "claude-native-affinity.test.ts": "claude-integration", "claude-native-passthrough.test.ts": "claude-integration", "messages-shared-sse.test.ts": "claude-integration", "claude-native-rate-limit-headers.test.ts": "claude-integration", "claude-outbound.test.ts": "claude-integration", From 5cfd0ac11fe32b8f6d28bdf108cecc37d5092793 Mon Sep 17 00:00:00 2001 From: JUN Date: Mon, 2 Nov 2026 20:30:27 +0900 Subject: [PATCH 06/43] fix(codex): keep Codex pool session pins across proxy restarts (#8098) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * wip(codex): lease releasing hooks, owned affinity paths, lineage anchor observer, plan unit * wip(codex): durable affinity store module * wip(codex): harden affinity store (readability, release vs home retirement, scope exhaustiveness, gap tests) * wip(codex): wire durable affinity into thread affinity and account-change state; restart tests * docs(codex): durable pool affinity contract and restart wording * test(codex): restart matrix for durable pool affinity * test(codex): remaining restart matrix cases (compact turn-state case currently red) * fix(codex): keep row keys for persisted deletes, durable touches for unknown issuers, compact turn-state scrub * fix(codex): reconcile live affinity on new lease, bounded and pruned store, file refusal for moved unknown issuers, gateway compact tests * fix(codex): bounded flush under the size cap, scope-aware adoption, eager startup prune * fix(codex): touches before chunk prunes, full scope enumeration, prune after failed flush, passive-safe lease hooks * docs(codex): describe affinity pruning as attempted, with its exceptions * fix(codex): apply touches before every chunk prune * chore: trim trailing blank lines * fix(codex): address CodeRabbit review — unscoped adoption marker, relative test timestamps, acquired-hook and restart-eligibility docs * fix(compact): rescrub turn state on 401 replay and on caller-owned main alternates * fix(codex): keep request-owned keys out of the durable store; align with manual-switch issuer retention; memory wins after a lease gap; persist in unowned homes * fix(codex): replay lease-gap changes instead of rewriting the store; conditional restart wording; French grammar * fix(codex): fail closed after a lease gap instead of replaying; carry row keys across lease changes * fix(codex): keep carried row keys past a failed reopen; document the post-release limit * docs(structure): state that affinity rows store the local pool account id --- .../261102_codex_affinity_persist/010_plan.md | 145 +++ .../020_plan_revision.md | 151 +++ .../030_plan_revision.md | 98 ++ .../040_plan_revision.md | 94 ++ .../050_plan_revision.md | 79 ++ .../060_plan_revision.md | 68 ++ .../070_plan_revision.md | 44 + .../080_implementation_spec.md | 187 ++++ .../fr/reference/cli/providers-accounts.md | 5 +- .../fr/reference/configuration/providers.md | 5 +- .../ja/reference/cli/providers-accounts.md | 2 +- .../ja/reference/configuration/providers.md | 5 +- .../ko/reference/cli/providers-accounts.md | 2 +- .../ko/reference/configuration/providers.md | 5 +- .../docs/reference/cli/providers-accounts.md | 5 +- .../docs/reference/configuration/providers.md | 5 +- .../ru/reference/cli/providers-accounts.md | 2 +- .../ru/reference/configuration/providers.md | 5 +- .../tr/reference/cli/providers-accounts.md | 6 +- .../tr/reference/configuration/providers.md | 5 +- .../zh-cn/reference/cli/providers-accounts.md | 2 +- .../reference/configuration/providers.md | 4 +- .../zh-tw/reference/cli/providers-accounts.md | 2 +- .../reference/configuration/providers.md | 4 +- scripts/test-layout/layout.json | 6 +- src/codex/lineage.ts | 20 +- src/codex/request-owned-affinity-key.ts | 11 + src/codex/request-owned-affinity.ts | 9 +- src/codex/routing/thread-affinity-store.ts | 899 ++++++++++++++++++ src/codex/routing/thread-affinity.ts | 86 +- src/lib/config-ownership.ts | 4 + src/lib/spend-ledger-owner.ts | 38 +- src/server/responses/account-change-state.ts | 8 +- src/server/responses/compact.ts | 32 +- structure/INDEX.md | 4 + structure/manifest.json | 11 + structure/providers/codex-pool-affinity.md | 14 + .../providers/codex-request-owned-affinity.md | 4 +- structure/providers/openai-tiers.md | 4 +- structure/transports/responses-spend.md | 10 +- .../codex-affinity-lease-gap.test.ts | 99 ++ .../codex-affinity-request-owned.test.ts | 86 ++ .../codex-affinity-restart-matrix.test.ts | 226 +++++ .../codex-affinity-restart.test.ts | 234 +++++ .../codex-affinity-store.test.ts | 353 +++++++ .../codex-lineage-placement.test.ts | 19 + tests/fixtures/test-layout-expected.json | 3 +- .../helpers/codex-affinity-handler-worker.ts | 27 + .../codex-affinity-home-switch-worker.ts | 40 + tests/helpers/codex-affinity-matrix-worker.ts | 191 ++++ .../helpers/codex-affinity-restart-worker.ts | 46 + tests/lib/spend-ledger-owner.test.ts | 47 + ...ive-compaction-gateway-credentials.test.ts | 122 +++ .../native-compaction-gateway.test.ts | 13 + 54 files changed, 3519 insertions(+), 77 deletions(-) create mode 100644 devlog/_plan/261102_codex_affinity_persist/010_plan.md create mode 100644 devlog/_plan/261102_codex_affinity_persist/020_plan_revision.md create mode 100644 devlog/_plan/261102_codex_affinity_persist/030_plan_revision.md create mode 100644 devlog/_plan/261102_codex_affinity_persist/040_plan_revision.md create mode 100644 devlog/_plan/261102_codex_affinity_persist/050_plan_revision.md create mode 100644 devlog/_plan/261102_codex_affinity_persist/060_plan_revision.md create mode 100644 devlog/_plan/261102_codex_affinity_persist/070_plan_revision.md create mode 100644 devlog/_plan/261102_codex_affinity_persist/080_implementation_spec.md create mode 100644 src/codex/request-owned-affinity-key.ts create mode 100644 src/codex/routing/thread-affinity-store.ts create mode 100644 structure/providers/codex-pool-affinity.md create mode 100644 tests/codex-integration/codex-affinity-lease-gap.test.ts create mode 100644 tests/codex-integration/codex-affinity-request-owned.test.ts create mode 100644 tests/codex-integration/codex-affinity-restart-matrix.test.ts create mode 100644 tests/codex-integration/codex-affinity-restart.test.ts create mode 100644 tests/codex-integration/codex-affinity-store.test.ts create mode 100644 tests/helpers/codex-affinity-handler-worker.ts create mode 100644 tests/helpers/codex-affinity-home-switch-worker.ts create mode 100644 tests/helpers/codex-affinity-matrix-worker.ts create mode 100644 tests/helpers/codex-affinity-restart-worker.ts diff --git a/devlog/_plan/261102_codex_affinity_persist/010_plan.md b/devlog/_plan/261102_codex_affinity_persist/010_plan.md new file mode 100644 index 00000000000..3eef8172862 --- /dev/null +++ b/devlog/_plan/261102_codex_affinity_persist/010_plan.md @@ -0,0 +1,145 @@ +# 261102 Codex pool affinity persistence (Lane B) — 010 plan + +Status: P (plan) — awaiting Terra audit. + +## Problem + +Codex pool session pins live only in memory, so a proxy restart re-places every ongoing conversation. +Two process-local facts cause it, and both must change: + +1. `src/codex/routing/thread-affinity.ts` keeps `threadAccountMap` (conversation key -> scope -> binding) and + `conversationStateIssuerMap` (binding key -> account that minted carried encrypted state) in memory only. +2. The key those maps are indexed by is `codexConversationKeyFor()` in `src/codex/lineage.ts`: + `app:HMAC(CODEX_LINEAGE_KEY, family, thread)` where `CODEX_LINEAGE_KEY = randomBytes(32)` at module load. + After a restart the same conversation derives a different key, so a persisted map alone could never be + looked up again. (The lineage scope key `auth:HMAC(key, Authorization)` uses the same secret.) + +Under round-robin most conversations move after a restart: the prompt cache goes cold and carried encrypted +state minted by the old account can fail with `invalid_encrypted_content`. + +Reference implementation to mirror: `src/oauth/anthropic-session-affinity-store.ts` (#7813 / #7828) and its +structure section `structure/providers/anthropic-account-pool.md#durable-session-affinity`. + +## Design + +### A. Durable conversation-key secret — new `src/codex/affinity-key.ts` + +- `codexAffinityKey(): Buffer` returns a 32-byte secret cached per resolved `getConfigDir()` (re-resolved when the + home changes, as the Claude store's scope does). +- Path: `/codex-affinity-key`. Content: one line `v1:` (validated by regex). +- Hydration: `readBoundedRegularFileSync(path, 128)` (rejects symlinks/junctions/non-regular files and oversize). + Valid -> use. ENOENT -> `randomBytes(32)`, cache it, and persist asynchronously: + `trackBackgroundWork("codex-affinity-key-write", withConfigDirHardeningSettled(home, () => atomicWriteFileNoFollow(path, text, undefined, {}, { exclusive: true })))`. + If the exclusive publish loses a race (another process created it first), keep the in-memory key for this process + (its pins are lost at the next restart, same as today) — no overwrite. Invalid or unreadable -> identifier-free + `console.warn("[codex-affinity] key unavailable or invalid; affinity is process-local until it is replaced")`, generate + a fresh key and replace the file with a non-exclusive atomic write (a corrupt key must not disable persistence forever). +- The file is a secret: private mode via the atomic publisher (0600 on POSIX) and the config-dir Windows ACL barrier. + Never logged, never included in diagnostics. +- `src/codex/lineage.ts`: drop `CODEX_LINEAGE_KEY`; both HMACs call `codexAffinityKey()`. Update the LIFETIME doc block: + keys are now reproducible across restarts of one config home; lineage records themselves stay process-local. + Keep lineage a leaf: the new module imports only config/lib modules (no routing import, no cycle). +- `src/adapters/google-antigravity-wire.ts` comment that calls the key "process-random ... changes across a proxy restart": + reword only (the derivation there stays independent; it must survive loss of the key file too). No behavior change. + +### B. Durable pin + issuer snapshot — new `src/codex/routing/thread-affinity-store.ts` + +- File `/codex-affinity.json`, `{ version: 1, threads: [...], issuers: [...] }`. + - thread row: `{ keyDigest, scope, accountId, generation, createdAt, lastUsedAt }` + - issuer row: `{ keyDigest, accountId, lastUsedAt }` + - `keyDigest = sha256hex("opencodex/codex-affinity//v1\0" + key)`. Raw conversation keys, raw parent ids + (legacy keys) and binding keys never reach disk. Account ids are opaque pool ids (`isValidCodexAccountId` or `__main__`). + - Transient fields (`transientHoldSince`, `transientDetourAccountId`) and `lastReevalAt` are not persisted; restored + entries get `lastReevalAt = restore time`. +- Bounds: `MAX_FILE_BYTES = 1 MiB` on read; newest `CODEX_THREAD_AFFINITY_MAX_ENTRIES` (2048) rows per table on write and read; + rows idle longer than `CODEX_THREAD_AFFINITY_IDLE_TTL_MS` (24 h), future-dated rows, malformed rows are dropped. + Scope strings validated (`spark`/quota scopes, `legacy`, `model-detour::`, <= 512 bytes). +- Hydration is lazy per config home (first affinity read/write), synchronous and bounded, like the Claude store. + Restored rows are held in digest-keyed `restoredThreads` / `restoredIssuers` maps; they never enter + `threadAccountMap` until a request looks them up. +- Adoption: in `getThreadAffinityForScope(threadId, scope)` on a memory miss, and in `peekConversationStateIssuer`, + compute the digest, take the restored row, validate, and insert it into the in-memory map (removing it from the restored + map). Validation for thread rows = not expired AND `isThreadAffinityGenerationLive({accountId, generation})` (account record + exists, has a credential, not deleted, same credential generation; `__main__` must be generation 0). A failing row is + discarded and the request falls back to normal selection. Usability (paused, reauth, plan exclusion, quota, cooldown) is + NOT checked at restore: the existing resolve path already re-evaluates a bound account every request and releases it + with the usual reason. Issuer rows are restored after TTL validation only: an issuer for a deleted account still correctly + forces the account-change scrub. +- Writes: the snapshot is serialized from the live maps plus unadopted restored rows at flush time, so in-place mutations + elsewhere are captured. Structural changes (new bind, account change, delete, clear, per-account clear, hand-off, + prune/evict, issuer change) flush promptly; timestamp-only activity (bind of the same account, a binding read, an issuer + peek) schedules one coalesced flush after 1 s (unref'd timer). Reading a binding schedules the coalesced flush because + `src/codex/routing.ts` updates `lastUsedAt` in place after the read and that file is at its file-size cap. +- Publisher: `trackBackgroundWork("codex-affinity-write", withConfigDirHardeningSettled(home, () => atomicWriteFileNoFollow(path, json)))`, + revision counter re-flush exactly like `flushScope` in the Claude store, best-effort `registerOptionalShutdownHook("codex-affinity", ...)`, + identifier-free warnings (`[codex-affinity] snapshot persistence failed; using runtime affinity` / + `snapshot unavailable or invalid; using runtime affinity`). An observed config-home change retires the scope (memory + restored maps + pending timer), as in the Claude store. +- Exports: `flushCodexThreadAffinity()` (tests and shutdown), `resetCodexAffinityStoreMemoryForTests()`. + +### C. Minimal hooks in `src/codex/routing/thread-affinity.ts` + +- `getThreadAffinityForScope`: on miss, adopt from the store; on hit, schedule the coalesced touch flush. +- `bindThreadAffinityForScope`, `deleteThreadAffinityForScope`, `deleteThreadAffinitiesForAccount`, + `clearThreadAccountMapForAccount` (also purge restored rows for that account), `handOffThreadAffinityGeneration` (also + move restored rows fromGeneration -> toGeneration), prune/LRU paths, `rememberConversationStateIssuer`, + `peekConversationStateIssuer`, `clearConversationStateIssuerMap`, `clearThreadAccountMap` (also clears restored rows and + persists the empty snapshot, matching the Claude "explicit runtime selection clears bindings and persists the reset"). +- Update the doc comments that promise process-local lifetime (issuer map comment, `adoptLegacyAffinityForScope` comment). +- Keep edits to call sites; do not touch the affinity log label (Lane D) or `src/codex/routing/selection.ts` (Lane C). +- Core-path boundary: the store imports only `src/config/*` and `src/lib/*`; no `src/lab/` reachability. + +## Tests (new files; register each in `scripts/test-layout/layout.json` or its domain shard AND a `tests/fixtures/test-layout-expected*.json` shard) + +`tests/codex-integration/codex-affinity-restart.test.ts` (temp `OPENCODEX_HOME` per test, `removeTreeWithRetry` cleanup): + +1. Restart keeps the pin: build headers with `session-id`/`thread-id`, key = `codexPoolAffinityKey(headers)`, seed two pool + accounts, `bindThreadAffinity(key, B, now)`, `rememberConversationStateIssuer(key, B)`, flush, simulate restart + (reset in-memory affinity, store scope and key cache — NOT the files), recompute the key from the same headers: it is + identical, `getThreadAffinity(key)` returns B, `peekConversationStateIssuer(key)` returns B. Prefer one assertion through + the real resolver (`resolveCodexAccountForThread` or the existing public resolve used in `tests/codex-integration/codex-routing.test.ts`) + under round-robin, showing the restored binding wins over the strategy cursor. + MUST FAIL on old code (record output): the key differs after restart and the map is empty. +2. Dead pins fall back: account removed, credential generation bumped (re-login), and expired (>24 h) rows are dropped; + resolve returns a normal selection and the dropped row is gone from the next snapshot. +3. Privacy/bounds: the snapshot contains no raw session id, thread id or conversation key; key file is 0600 on POSIX; + oversized, malformed, future-dated and symlinked snapshots are ignored with an identifier-free warning (assert the + warning text contains no account id or key); more than 2048 rows keeps the newest. +4. `clearThreadAccountMap()` and `clearThreadAccountMapForAccount()` persist their removals (after restart the pin is gone). +5. Key file: reused across restart; a corrupt key file is replaced and a warning is emitted. + +Existing suites to rerun: `tests/codex-integration/codex-routing*.test.ts`, `codex-affinity-debug.test.ts`, +`codex-idle-window.test.ts`, `codex-account-selection-atomicity.test.ts`, `codex-auth-release.test.ts`, +`tests/responses/responses-account-change-scrub.test.ts`, `tests/responses/responses-4546-incident-regression.test.ts`, +lineage tests (`rg -l lineage tests`), `tests/lab/core-lab-boundary.test.ts`, `tests/test-layout.test.ts`, file-size ratchet test. + +## Docs + +- `structure/providers/openai-tiers.md`: lineage section (lines ~105-160) — key is a per-config-home durable secret; add a + "Durable Codex pool affinity" paragraph parallel to the Anthropic one (file names, row shape, bounds, validation, flush policy, + test names). Run `bun run structure:check`; add the new src files to the owning manifest entry if the check asks. +- `docs-site/src/content/docs/reference/cli/providers-accounts.md` (~line 848): replace "proxy restart or affinity eviction can + also leave a task unbound" with: bindings survive a proxy restart for 24 h idle; eviction, account removal or re-login leave a + task unbound. Apply the equivalent edit in every locale copy that carries the sentence (`rg -l` across docs-site locales) so no + locale contradicts English; follow `docs-site/AGENTS.md`. +- `docs-site/src/content/docs/reference/configuration/providers.md` `accountPoolStrategy` row (~line 128) says a task "can become unbound after proxy restart or affinity reset"; update it (and locale copies) the same way. + +Issue: https://github.com/lidge-jun/opencodex/issues/8091 + +## Verification + +`bun test `, `bun run typecheck`, `bun run structure:check`, `bun run privacy:scan`, +`bun scripts/test.ts --changed=dev --parallel=1`. Red-on-old proof: run test 1 against `origin/dev` sources (stash src changes) and record the failure. +`ci:full` label: yes — the change reaches on-disk files and docs the import graph cannot see. + +## Out of scope + +`src/codex/routing/selection.ts` (Lane C), `src/codex/auth-context.ts` and the affinity log label (Lane D), +`src/server/claude-*`, `src/server/caller-session-identity.ts` (Lane A). No change to selection policy. + +## Risks + +- Persisting the HMAC secret changes the documented "keys are unreproducible after restart" posture. The secret stays private + (same protection class as `admin-api-token`), and the snapshot holds only digests of keys derived from it. +- Two processes sharing one config home: exclusive create means the loser keeps a process-local key; acceptable and documented. +- Write amplification: at most one coalesced write per second while traffic flows, same as the Claude store. diff --git a/devlog/_plan/261102_codex_affinity_persist/020_plan_revision.md b/devlog/_plan/261102_codex_affinity_persist/020_plan_revision.md new file mode 100644 index 00000000000..cfb69bc1020 --- /dev/null +++ b/devlog/_plan/261102_codex_affinity_persist/020_plan_revision.md @@ -0,0 +1,151 @@ +# 261102 Codex pool affinity persistence — 020 plan revision (answers audit round 1 + coordinator note) + +Supersedes the Design, Tests and Verification sections of 010_plan.md. Problem statement, docs list and out-of-scope +boundaries in 010 stay. Issue: https://github.com/lidge-jun/opencodex/issues/8091 + +## Security posture (coordinator note; security-sensitive per MAINTAINERS.md) + +The existing conversation-key secret `CODEX_LINEAGE_KEY` in `src/codex/lineage.ts` STAYS process-local and unchanged. +Every consumer of the derived key `app:HMAC(CODEX_LINEAGE_KEY, anchor, anchor)` therefore reveals exactly what it reveals today: + +| Consumer of the ephemeral key | Where | Changes? | +|---|---|---| +| `threadAccountMap` / `conversationStateIssuerMap` keys, pending release reasons | `src/codex/routing/thread-affinity.ts` (memory) | no | +| `authCtx.affinityKey` passed as `threadId` to routing | `src/codex/auth-context.ts`, `src/server/responses/core-codex-account.ts`, `passthrough-*.ts`, `src/providers/openai-sidecar.ts` (memory) | no | +| `_cursorClientThreadId` (Cursor adapter conversation id, advisor state) | `src/server/responses/request-prepare.ts:417,563`, `src/adapters/cursor/request-builder.ts:385`, `src/advisor/state.ts` | no | +| lineage scope `auth:HMAC(key, Authorization)` and records | `src/codex/lineage.ts` (memory) | no | +| debug capture tags | `src/codex/affinity-debug.ts` (own process-local key, ADR-0089) | no | +| request log / usage ledger lanes | `src/server/request-log-conversation.ts` — uses its own digest of raw headers, not the affinity key | no | + +The ONLY new durable artifact is the snapshot. Its row keys are derived from a SEPARATE secret used for nothing else: +`rowKey = HMAC-SHA256(storeSecret, "opencodex/codex-affinity/conversation/v1\0" + anchor)` (hex), where `anchor` is the +cohort anchor already used by `codexConversationKeyFor(anchor, anchor)` (the session id, or the parent thread id for +session-less requests). Issuer rows use domain `.../issuer/v1`. The store secret never leaves the store module and the +snapshot file; it is not logged, not exposed by diagnostics or management APIs. What becomes linkable across restarts: +only that "the same anchor was bound to account X", and only to someone who can read both the private snapshot and the +private secret file (owner-only). Nothing written to logs gains cross-restart linkability. + +## Design + +### A. Store secret — inside `src/codex/routing/thread-affinity-store.ts` + +- File `/codex-affinity-key`, content `v1:\n`, read with `readBoundedRegularFileSync(path, 128)` + (rejects symlinks, junctions, non-regular files, oversize). +- States per config-home scope: `durable` (read valid file, or our exclusive create succeeded and re-read matches), + `pending` (generated, publish in flight), `disabled` (publish failed, lost the exclusive race, file unreadable). + **The snapshot is written only in state `durable`** (blocker 2): a process with an unpublished or losing key never touches + `codex-affinity.json`. Exclusive-race loser: re-read the winner's key; if valid, adopt it before any row key is derived + (rows are derived lazily at flush time from retained anchors — see B — so adoption is safe) and become `durable`; + otherwise `disabled`. +- ENOENT -> generate, exclusive publish via `withConfigDirHardeningSettled(home, () => atomicWriteFileNoFollow(path, text, undefined, {}, { exclusive: true }))` + inside `trackBackgroundWork`. A snapshot with no key file is ignored (cannot be verified) and replaced on the first durable flush. +- Present-but-invalid regular file -> identifier-free warning, replace with a fresh key (non-exclusive atomic write), drop any + existing snapshot (its rows are unverifiable). Unreadable/symlink/non-regular -> warning, `disabled`, never replaced blindly. +- Ownership: the key file and snapshot are recorded as owned config files (use the default non-exclusive path's ownership + recording, or call `recordOwnedConfigPath` after an exclusive publish) so uninstall/reset removes them. Implementer verifies + how `src/lib/config-ownership.ts` is consumed and states it in the PR. + +### B. Durable rows without changing the ephemeral key + +- `src/codex/lineage.ts` gains a one-slot observer: `setCodexConversationAnchorObserver(fn | undefined)`; `codexConversationKeyFor(familyId, threadId)` + calls `fn?.(key, familyId, threadId)` after deriving. No new imports in lineage.ts (stays a leaf). The store registers the + observer when `thread-affinity.ts` loads it. +- The store keeps, per config-home scope, a bounded `anchorByKey: Map` (same TTL/size as the binding map; + memory only — raw anchors already live in lineage records in memory). Row keys are computed from the anchor only when a + snapshot is serialized or a restored row is looked up. Keys with no recorded anchor (legacy raw-parent keys, test keys bound + directly) are memory-only, exactly as today. +- **Durability contract (blocker 1, narrowed and documented):** a pin survives restart when the request's key is derivable from + its headers alone: every request carrying `session-id` (all Codex CLI/App turns, roots and subagents), and session-less + requests whose anchor is their immediate parent. A session-less chain of depth >= 2 resolves through an in-memory lineage + record that a restart forgets, so it re-places after restart as it does today. Docs say so. Test both sides. + +### C. Snapshot store (`codex-affinity.json`) + +- `{ version: 1, threads: [{ rowKey, scope, accountId, fence, createdAt, lastUsedAt }], issuers: [{ rowKey, accountId, fence?, lastUsedAt }] }`. +- Fence (blocker 5): `fence = sha256hex("opencodex/codex-affinity/identity/v1\0" + record.quotaHistoryIdentity)`. `quotaHistoryIdentity` is a random + UUID minted on every new login/replacement and preserved across same-account token refresh (`src/codex/account-store.ts:264,493,554`), + i.e. the Codex twin of the Claude `loginFence`. Records without a valid `quotaHistoryIdentity` stay memory-only (Claude legacy rule). +- `__main__` pins are not persisted (no durable identity fence for the native login). `__main__` issuer rows and pool issuer rows + whose fence no longer matches restore as a foreign sentinel issuer (`"\u0000foreign"`), which never equals a serving account id + and therefore forces the account-change scrub instead of letting stale carried state reach a new account. +- Restore of a thread row: TTL ok, not future-dated, scope valid, account record has credential, not deleted, fence matches. On adoption + the entry takes the record's CURRENT generation (fence proves identity continuity; this also covers an offline `ocx account refresh`), + `lastReevalAt = now`, no transient fields. Otherwise discard -> normal selection. Usability (paused, reauth, cooldown, plan/model + exclusion, transient) is left to the existing resolver (`resolveCodexAccountForThread`, `src/codex/routing.ts:498`, reuse checks ~959-1021). +- Bounds (blocker 6): read cap and write cap both `MAX_FILE_BYTES = 2 MiB`; per table newest-first up to 2048 rows; on write, if the + serialized document exceeds the cap, drop oldest rows (detour scopes first, then by `lastUsedAt`, ties by rowKey) until it fits — + deterministic. Duplicate rowKey+scope on read: keep newest. Scope validation mirrors the real component rules: `legacy`, a known + `CodexQuotaScope`, or `model-detour::` where model passes the existing 512-byte component limit (no extra cap on the whole scope). +- Lazy adoption + reconciliation (blocker 3): restored rows live in `restoredThreads: Map>` and + `restoredIssuers: Map`. EVERY mutation for an ephemeral key K with a known anchor first reconciles the restored rows of + rowKey(K): bind (restored row for that scope dropped, live wins), delete scope, delete-for-account, issuer remember, and the getters + (adopt). Account-wide operations (`clearThreadAccountMapForAccount`, `handOffThreadAffinityGeneration` — fence unchanged so no row edit + needed) and `clearThreadAccountMap`/`clearConversationStateIssuerMap` act on restored rows too, even when the live map misses. TTL pruning and + LRU eviction count live + restored rows against the 2048 bound, detour-first as `pruneLruThreadAffinities` does. Adoption increments + `threadAffinityEntryTotal` and runs the existing prune. `getThreadAffinityScopes(threadId)` adopts all restored scopes for that key first. +- Flush policy: structural changes publish promptly; timestamp-only activity (same-account rebind, binding read, issuer peek) schedules one + coalesced flush after 1 s (unref'd), which captures the in-place `lastUsedAt` writes in `src/codex/routing.ts:911,942,985,1021` + (that file is at its size cap). Revision re-flush, `trackBackgroundWork("codex-affinity-write", withConfigDirHardeningSettled(...))`, + best-effort `registerOptionalShutdownHook("codex-affinity", ...)`. Clear racing a pending flush: the flush serializes at callback time + from current state under the active-scope check, and a clear bumps the revision so a re-flush follows. +- Config-home scope (blocker 4): scope = resolved `getConfigDir()`. On an observed change the old scope is retired (restored rows, anchor map, + timers, key state) and the live runtime affinity maps are cleared (mirrors the Claude store, whose rows ARE its runtime map), so home B + never inherits or persists home A's pins. Every deferred callback re-checks `scope.active && getConfigDir() === scope.home` INSIDE the + ACL-settled callback before writing (Claude `flushSync` pattern). Lineage records stay process-global but carry only ephemeral keys, + which home B cannot persist without its own anchor observation — implementer confirms no cross-home leak in the A->B->A test. +- Passive reads (blocker 7): when `isPassiveRead()` is true the store neither creates/replaces the key, nor hydrates, adopts, schedules, + or flushes; affinity behaves exactly as today for that call. +- Warnings are identifier-free: `[codex-affinity] snapshot persistence failed; using runtime affinity`, + `[codex-affinity] snapshot unavailable or invalid; using runtime affinity`, `[codex-affinity] key unavailable; affinity stays process-local`. + +### D. Hooks in `src/codex/routing/thread-affinity.ts` + +Call-site hooks only: the getters, bind/delete/clear paths, LRU/TTL prune, issuer remember/peek/clear, `getThreadAffinityScopes`. +Comment updates for the issuer map and legacy adoption lifetime notes. No change to the affinity log label (Lane D), `selection.ts` (Lane C), +`auth-context.ts` (Lane D), or `src/codex/routing.ts` (at cap). + +## Tests + +`tests/codex-integration/codex-affinity-restart.test.ts` (register in `scripts/test-layout/layout.json` next to line 709 and in +`tests/fixtures/test-layout-expected.json` next to line 697; run `tests/test-layout.test.ts` and `tests/test-layout-tooling.test.ts`). + +1. **Restart, two fresh subprocesses (red-on-old)**: a helper script (`tests/helpers/codex-affinity-restart-worker.ts`, registered if the + layout requires) run with `bun` twice against one temp `OPENCODEX_HOME`: process 1 seeds two pool accounts (round-robin), resolves a + session-bearing request through `resolveCodexAccountForThread` with the key from `codexPoolAffinityKey(headers)`, records the issuer, + then awaits the store flush if the export exists (dynamic import with catch, like `tests/adapters/anthropic/anthropic-affinity-restart.test.ts`) + and exits; process 2 advances the round-robin cursor so a fresh pick would choose the other account, resolves the same headers, and + prints the account and whether the account-change scrub fires for a body carrying `previous_response_id` when served by the other account. + Expect: same account; issuer known. Old code: different account / no issuer. Record the old-code failure from an isolated export of + `origin/dev` (`git archive origin/dev | tar -x -C ` + the test file + `bun install --frozen-lockfile` or a node_modules link); + no stash, no worktree. +2. Fallbacks: account removed; account re-logged (new `quotaHistoryIdentity`); legacy record without identity; expired row; future row -> + normal selection, row gone from the next snapshot. Usability cases (paused, needs reauth, cooldown, model exclusion, transient hold) assert + the existing resolver behavior after restore, case by case, not a blanket "deleted". +3. `__main__`: pin not persisted; issuer restores as foreign sentinel and forces scrub. +4. Session-less depth-1 survives; depth-2 session-less chain re-places (documented limitation). +5. Reconciliation before first lookup: bind, delete, delete-for-account, issuer remember, clear and clear-for-account on a key whose row + was restored but not adopted; pending flush racing clear. +6. Key states: reused across restart; exclusive race loser adopts the winner or stays disabled and never writes the snapshot; publish + failure leaves no snapshot; corrupt regular key replaced and old snapshot dropped; symlinked/unreadable key disabled, not replaced. + Key file and snapshot are 0600 on POSIX. +7. Privacy and bounds: snapshot contains no raw session/thread id, no ephemeral key; warnings contain no account id; two full tables with + worst-case UTF-8 detour scopes stay under the cap and re-read successfully; oversized/malformed/symlinked snapshot ignored. +8. Config home A -> B -> A with pending writes: no cross-home rows, no write after retirement. +9. Passive read: no files created, no pending work. +Drain tracked background work before temp-home cleanup. + +Existing suites to rerun: `rg -l` of the affinity entry points (the round-1 audit counted 38 files) plus +`tests/lab/core-lab-boundary.test.ts`, the file-size ratchet test, `tests/ci-workflows/test-home-guard.test.ts`, lineage tests. + +## Docs + +As in 010, plus: `structure/providers/openai-tiers.md` lineage section states the conversation key stays process-local and adds +"Durable Codex pool affinity" (secret, row derivation, fence, main rule, contract narrowing, bounds, flush, passive, home scope, tests); +`structure/providers/openai-accounts.md` only where it claims pins are process-local (do not touch the diagnostic tags or the idle-window +reservation map). Locale copies found per locale (fr, ko, zh-cn, and any others), not by English text. Build the docs site per docs-site/AGENTS.md. + +## Verification + +Focused new + affected tests, `bun run typecheck`, `bun run structure:check`, `bun run privacy:scan`, docs-site build, +`bun scripts/test.ts --changed=dev --parallel=1`, red-on-old recorded. Before the PR: a dedicated Terra security review (secret file +permissions/ACL, key scope, cross-restart linkability, snapshot contents, deletion on pool/config reset); its verdict goes in the PR description. diff --git a/devlog/_plan/261102_codex_affinity_persist/030_plan_revision.md b/devlog/_plan/261102_codex_affinity_persist/030_plan_revision.md new file mode 100644 index 00000000000..6be70fbd03d --- /dev/null +++ b/devlog/_plan/261102_codex_affinity_persist/030_plan_revision.md @@ -0,0 +1,98 @@ +# 261102 Codex pool affinity persistence — 030 plan revision (answers audit round 2) + +Amends 020_plan_revision.md; everything in 020 not changed here stands. Issue: https://github.com/lidge-jun/opencodex/issues/8091 + +## R2-B1 — fences captured at the credential event + +- `ThreadAffinityEntry` gains an optional `identityFence?: string` (sha256hex of `"opencodex/codex-affinity/identity/v1\0" + quotaHistoryIdentity`). + `bindThreadAffinityForScope` already reads the account record once to take `generation`; it takes the fence from that SAME + record read, so the fence always describes the credential the binding was made under. `handOffThreadAffinityGeneration` + keeps the fence (an owned refresh preserves `quotaHistoryIdentity`, account-store.ts:493,554). An entry without a fence + (legacy record, `__main__`) is memory-only. Serialization writes the captured fence; it never reads the current record. +- Issuers: `rememberConversationStateIssuer(bindingKey, accountId, now?, credentialGeneration?)`. The fence is captured only when + the record's current generation equals the dispatched `credentialGeneration` (one record read, under the same call); otherwise + the issuer row is written without a fence. `rememberServingConversationStateIssuer` in `src/server/responses/account-change-state.ts` + passes `authCtx.generation` for pool contexts (`CodexAuthContext` pool kind carries `generation`, auth-context.ts:300). Callers that + pass no generation (routing.ts, compact) produce fence-less rows. A re-login while a response is in flight therefore cannot + attach the new identity to state issued by the old credential. +- Restore: thread row adopted only if record live AND current `quotaHistoryIdentity` fence equals the stored fence; then it takes + the record's current generation. Issuer row: fence equal -> issuer = accountId; fence missing or different -> UNKNOWN issuer + (R2-B2). `__main__` issuer rows are not persisted at all (behaves exactly as today after restart). +- Orca/external rotation (account-store.ts:1157) preserves `quotaHistoryIdentity` only after verifying `chatgptAccountId` and + `sourceSubject` are unchanged, i.e. the same upstream account; restoring across it is correct. Tested. +- Tests: re-login between bind and flush (row restored? no -> dropped); re-login between dispatch and issuer completion (issuer row + has no fence -> unknown); owned refresh/handoff before flush (restored); Orca rotation (restored); delete + re-add same id (dropped). + +## R2-B2 — unknown issuer is not proof of an account change for files + +- `thread-affinity.ts` exports `CODEX_UNKNOWN_CONVERSATION_STATE_ISSUER` (a value no account id can equal; account ids match + `^[A-Za-z0-9._-]{1,64}$` or `__main__`). `peekConversationStateIssuer` may return it only for a restored row. +- `applyAccountChangeConversationStateScrub`: unknown counts as changed (conservative continuation scrub; one cold turn). +- `accountChangeFileReferenceRefusal`: unknown issuer is ignored; refusal only when a KNOWN issuer differs or `priorAccountId` + proves an in-request move. So persistence adds no file refusal that did not exist before. +- Tests: pool re-login (fence mismatch) + file reference -> scrub of continuation state, no 400; known pool move + file -> 400 as today; + unchanged pool account -> neither. + +## R2-B3 — home switching and observer ordering + +- The anchor observer first resolves the active scope (`current()`: retire the old scope and clear live affinity maps if the home + changed) and only then records the anchor in the new scope. So the first request under home B keeps its own anchor. +- Anchor cache: per scope, LRU, refreshed on every derivation, bound 4096 (2x the binding bound), same 24 h TTL. Session-bearing + requests re-derive on every request, so their anchors are always present. A key that reaches routing without being observed in + the current scope (recorded session-less lineage reused after an anchor eviction or after a home change, legacy keys, directly + bound test keys) is memory-only: it is neither written nor matched. This is part of the documented narrowed contract. +- Tests: first B request persists under B; A -> B -> A with pending writes, both direct derivation and recorded lineage; no B row + ever appears in A's snapshot or vice versa; anchor eviction then recorded-lineage lookup -> memory-only. + +## R2-B4 — cross-process serialization + +All durable writes happen inside `withConfigDirHardeningSettled(home, () => withConfigMutationLockSync(() => ..., home))` +(`src/config/mutation-lock.ts:104`: OS-backed SQLite `BEGIN IMMEDIATE`, `busy_timeout=0`, released on process exit). Under the lock: + +1. Key: re-read the key file. Valid -> adopt it if it differs from ours (rows are derived lazily from anchors, so adoption is safe; + restored rows hydrated under a different key are discarded). Missing -> write ours. Invalid regular file -> replace with ours + and treat the existing snapshot as empty. Unreadable/symlink/non-regular -> `disabled`, no write. No `exclusive` publish is used, + so atomic-write records ownership as it does for other config files (verify; otherwise call `recordOwnedConfigPath` and treat a + `false` result as a one-time identifier-free warning, persistence continues). +2. Snapshot: read the on-disk snapshot (bounded) and MERGE: for each (rowKey, scope) keep the newest `lastUsedAt` of disk vs ours, + then apply our pending tombstones recorded since our last successful publish: per-row deletes, per-account deletes + (`{accountId, at}`: drop disk rows of that account with `lastUsedAt <= at`) and full clears (`{at}`: drop disk rows with + `lastUsedAt <= at`). Trim to the bounds. Write atomically. Clear tombstones only after the write succeeds. +3. Lock busy -> nothing written, state stays dirty, retried by the next coalesced flush (1 s, unref'd). Repeated failure warns once, + identifier-free. + +Two proxies on one config home therefore never lose each other's newer rows and never publish under a key the other replaced. +Tests: two processes creating the key concurrently end with one key and both see it; concurrent invalid-key recovery; two writers +with disjoint rows -> union; writer A deletes a row writer B still has older -> stays deleted; lock held by another process -> retry. + +## R2-B5 — reset and removal semantics + +| Entry point | Effect on disk | +|---|---| +| `clearThreadAccountMap()` — config, provider, model, combo, agent-settings, logs-usage, oauth-account and shared management routes, server index (`rg -n clearThreadAccountMap src`) | full-clear tombstone; next publish writes a snapshot without those rows (issuers cleared too, as today) | +| `clearConversationStateIssuerMap()` | issuer table cleared on disk | +| `clearThreadAccountMapForAccount(id)` — account removal, auto-pause, plan exclusion, quota refusal, account-preservation | per-account tombstone for pins only; issuer history is preserved, as today (thread-affinity.ts:223) | +| account deletion without a clear | row fails the fence on restore and is discarded | +| uninstall (`removeOwnedConfigState`) | both files are owned config paths and are removed | + +Clears bump the revision and fence pending writes (the publish serializes current state at callback time under the scope check). +Tests: restart after each row of the table. + +## R2-B7 (partial) — passive + +Under `isPassiveRead()`: no hydration, adoption, scope switch, anchor recording, scheduling or flushing. Tests with a populated +snapshot, an already scheduled write, passive getters and observer calls, and existing live maps. + +## Security table corrections (non-blocking 1) + +- Add rows: compact (`src/server/responses/compact.ts:1684` uses the ephemeral key as an in-memory issuer binding key only), + previous-response replay (keyed by response ids and its own scope, not the affinity key — implementer confirms with file:line), + advisor ledger (`src/advisor/state.ts:213` derives its own hash from `_cursorClientThreadId`, which stays ephemeral -> unchanged). +- Correct the linkability claim: anyone who can read two snapshots of the same home can link identical row keys and the plaintext + pool account ids across restarts without the secret; the secret is needed only to test a candidate session id against a row. + Both files are owner-only (0600 / config-dir ACL). The key file is itself a new durable artifact. + +## Security review + +Dedicated Terra security review before the PR; per MAINTAINERS.md security-sensitive changes also need explicit maintainer security +review — the PR says so and requests it. diff --git a/devlog/_plan/261102_codex_affinity_persist/040_plan_revision.md b/devlog/_plan/261102_codex_affinity_persist/040_plan_revision.md new file mode 100644 index 00000000000..0c24d47275b --- /dev/null +++ b/devlog/_plan/261102_codex_affinity_persist/040_plan_revision.md @@ -0,0 +1,94 @@ +# 261102 Codex pool affinity persistence — 040 plan revision (answers audit round 3) + +Replaces the STORAGE design of 010/020/030 (JSON snapshot, key file, merge, tombstones, config mutation lock). Everything the +round-3 audit marked RESOLVED stays as written in 020/030: identity fences captured at bind/issuance (030 R2-B1), unknown issuer +handling (030 R2-B2), observer/home ordering and the narrowed contract (030 R2-B3, 020 B), passive rule (030), security table (030), +regression-test approach (020 Tests 1). Issue: https://github.com/lidge-jun/opencodex/issues/8091 + +## Why the storage changes + +Round 3 showed that a whole-file snapshot needs cross-process deletion evidence and a lock that config writes also use. A small +dedicated SQLite database gives both for free: every mutation is a row operation inside a transaction, a delete is a DELETE that +no other writer can undo by republishing its memory, and the database's own locking replaces the shared config lock. The Claude +store's properties are kept: config-home location, atomic commits, bounded rows, 24 h idle expiry, digested keys, identifier-free +warnings, private file mode and Windows ACL hardening. + +## Storage: `/codex-affinity.sqlite` (module `src/codex/routing/thread-affinity-store.ts`) + +- Opened lazily per config-home scope with `bun:sqlite`. Setup mirrors `configMutationDatabasePath` in `src/config/mutation-lock.ts:38`: + `assertNotRealHomeUnderTest`, dir 0700, `hardenSecretDir` on Windows (failure -> one identifier-free warning, persistence disabled for + the scope), file chmod 0600. `PRAGMA journal_mode=WAL; synchronous=NORMAL; busy_timeout=0`. Its own file: no interaction with + `config-mutation.sqlite`, so config and credential mutations are never blocked by this store (round-3 blocker 1). +- Ownership (round-3 blocker 3): before the first open, `recordOwnedConfigPath` for the db and its `-wal`, `-shm`, `-journal` sidecars; + every call's boolean is checked. If any returns false the store does NOT create the database (warn once, identifier-free; affinity + stays process-local for that scope). So any file this store creates is an owned path that uninstall (`removeOwnedConfigState`) removes. + Test: existing owned home -> paths recorded; manifest recording failure -> no database created. +- Schema v1 (`PRAGMA user_version = 1`; unknown version -> warn, disabled, file untouched): + - `meta(name TEXT PRIMARY KEY, value BLOB)` — row `secret`: 32 random bytes, created with `INSERT OR IGNORE` then read back, so + concurrent processes converge on one secret atomically. Replaces the key file; no corrupt-key recovery path exists. + - `threads(row_key TEXT, scope TEXT, account_id TEXT, fence TEXT, created_at INT, last_used_at INT, PRIMARY KEY(row_key, scope))` + - `issuers(row_key TEXT PRIMARY KEY, account_id TEXT, fence TEXT NULL, last_used_at INT)` + - `row_key` = HMAC-SHA256(secret, domain + anchor) hex as in 020; fence as in 030. +- Corrupt or unreadable database (open/pragma/query throws SQLITE_CORRUPT/NOTADB, symlink at the path, non-regular file): warn once, + persistence disabled for the scope, the file is left in place. + +## Writes: an ordered, coalesced in-process operation queue + +- Every mutation of the live maps enqueues an operation keyed so that the last operation per key wins: + - `bind(rowKey, scope, accountId, fence, createdAt, lastUsedAt)` -> `INSERT ... ON CONFLICT DO UPDATE` (a real placement decision). + - `touch(rowKey, scope, accountId, fence, lastUsedAt)` -> `UPDATE threads SET last_used_at = max(last_used_at, ?) WHERE row_key=? AND scope=? AND account_id=? AND fence=?`. + A touch can never create or revive a row: if another process deleted or rebound it, the touch is a no-op (round-3 blocker 2: + a stale in-memory pin in process B cannot undo A's clear). + - `deleteScope`, `deleteKey` (all scopes), `issuerSet` (upsert), `issuerTouch` (UPDATE-only, same rule), `issuerDelete`. + - `clearAccountPins(accountId)` -> `DELETE FROM threads WHERE account_id=?` (issuer history preserved, as today). + - `clearAll` -> `DELETE FROM threads; DELETE FROM issuers`; `clearIssuers` -> `DELETE FROM issuers`. + - A `clearAll` discards every queued operation before it; a `clearAccountPins` discards queued thread ops for that account. +- Flush: structural ops (bind, deletes, clears, issuerSet) schedule an immediate microtask-deferred flush; touches schedule a coalesced + flush after 1 s (unref'd timer). Read-time touches capture the in-place `lastUsedAt` writes in `src/codex/routing.ts` (at its size cap) + because the touch reads the entry's `lastUsedAt` at flush time. A flush runs the whole queue in ONE `BEGIN IMMEDIATE` transaction inside + `withConfigDirHardeningSettled(home, syncCallback)` with an in-callback `scope.active && getConfigDir() === scope.home` check, then prunes: + `DELETE` rows idle > 24 h or future-dated, and rows beyond the newest 2048 per table (ORDER BY last_used_at DESC, row_key, scope — + deterministic, detour scopes evicted first for threads, mirroring `pruneLruThreadAffinities`). +- Contention: SQLITE_BUSY -> nothing committed, queue kept, retry on the next coalesced flush; one identifier-free warning after repeated + failure. Queue bound: one entry per key (coalesced) plus per-account and full clears; if it exceeds 16384 entries (persistent failure), + drop queued touches first, then convert the remainder to `clearAll` + binds of current live rows — the failure direction loses pins + (today's behavior), never revives a deleted one. +- Same-row conflicts between processes resolve in commit order (SQLite serializes writers); equal timestamps need no tie rule. +- Best-effort shutdown flush via `registerOptionalShutdownHook("codex-affinity", ...)`; `trackBackgroundWork` around flushes; the db handle is + closed on scope retirement and in a test reset export. + +## Reads: lazy adoption straight from the database + +- No hydrated restored map. On a live-map miss for key K whose anchor is known in the current scope: + 1. If the queue holds a delete/clear covering rowKey(K) (or a pending `clearAll`), treat as absent. + 2. Otherwise `SELECT` the rows for rowKey(K) (WAL readers are not blocked by writers; a BUSY/error read is treated as absent). + 3. Validate each: TTL, not future-dated, scope rules (020), account record live with matching `quotaHistoryIdentity` fence (030). Valid -> + adopt into `threadAccountMap` with the record's current generation, count it in `threadAffinityEntryTotal`, run the existing LRU prune. + Invalid -> enqueue `deleteScope` for it. + 4. Remember per scope that rowKey(K) was consulted (bounded set, same TTL) so a second miss does not query again. +- Issuers: same on `peekConversationStateIssuer` miss; fence mismatch or null -> `CODEX_UNKNOWN_CONVERSATION_STATE_ISSUER` (030). +- Because writers go through the queue and reads check it first, a delete in this process can never be re-adopted from disk before it + is flushed, and a delete in another process is visible as soon as it commits. + +## Issuer fence capture (residual from round 3) + +`rememberServingConversationStateIssuer` passes `{ generation, chatgptAccountId }` from the pool auth context; the fence is captured only if the +record's current generation AND `credential.chatgptAccountId` both match (as `account-store.ts:382` does for dispatched credentials). + +## Tests (adds to/replaces 020+030 test list where storage-specific) + +- Two-process restart through `resolveCodexAccountForThread` (red-on-old from a `git archive origin/dev` export). +- Cross-process: A deletes/clears (row, account, issuer, full) and commits; B, holding the stale pin in memory, touches and flushes; a fresh + process restores nothing. B re-binds after A's clear (a real placement) -> row exists. Concurrent first open -> one secret. +- A process holding a write transaction on `codex-affinity.sqlite` does not block a real config mutation (`withConfigMutationLockSync`) or + a credential save. +- BUSY on flush -> retry succeeds later; queue overflow -> no deleted row revived. +- Ownership: paths recorded; recording failure -> no db created. Corrupt db / symlinked path / unknown user_version -> disabled, untouched. +- Bounds: >2048 rows per table keeps newest; idle and future rows pruned; worst-case UTF-8 detour scopes accepted. +- Everything else from 020/030 (fences, unknown issuer with files via responses and compact, priorAccountId retry, home A->B->A, passive, + privacy: no raw ids in db, warnings identifier-free, db 0600). + +## Docs + +structure/providers/openai-tiers.md "Durable Codex pool affinity" describes the SQLite store (file, schema, secret, fences, queue, touch +semantics, bounds, ownership, contract limits). Rest as in 010/030. diff --git a/devlog/_plan/261102_codex_affinity_persist/050_plan_revision.md b/devlog/_plan/261102_codex_affinity_persist/050_plan_revision.md new file mode 100644 index 00000000000..52e8b476845 --- /dev/null +++ b/devlog/_plan/261102_codex_affinity_persist/050_plan_revision.md @@ -0,0 +1,79 @@ +# 261102 Codex pool affinity persistence — 050 plan revision (answers audit round 4: single writer) + +Amends 040 (SQLite store). Items marked RESOLVED in rounds 3-4 stay: dedicated database separate from the config mutation lock, +fences captured at bind/issuance including `chatgptAccountId` (030/040), unknown issuer (030), observer/home ordering and narrowed +contract (020/030), passive rule, security table, deterministic pruning, regression-test approach. Issue: https://github.com/lidge-jun/opencodex/issues/8091 + +## Step back (loop-engineering, repeated reviewer FAIL) + +Rounds 2-4 failed on the same root: several processes writing one store and reconciling stale memory. Instead of more ordering +machinery, the store gets exactly ONE writer per config home, enforced by the operating system, and only the proxy server writes. + +## Arming: only the running proxy persists + +- `armCodexAffinityPersistence()` (store module) sets a process flag; the store opens nothing and writes nothing until armed. + `startServer` arms it synchronously (no await; preserves the Lab-activation window guard in `tests/lab/core-lab-boundary.test.ts`), + via an existing non-capped startup helper in `src/server/index/*` if one fits, otherwise the single line of headroom in + `src/server/index.ts` (cap 893, now 892). CLI processes, management passive reads and every test that does not arm behave + exactly as today: no files, no handles. This also removes Windows open-handle teardown risk from existing tests. +- Tests that exercise the store arm explicitly and close it in teardown via `resetCodexAffinityStoreForTests()` (flush + close + disarm). + +## Single writer: SQLite exclusive locking mode + +- Open sequence (all inside `withConfigDirHardeningSettled(home, sync)`, scope check inside the callback): `assertNotRealHomeUnderTest`, + ownership (below), dir 0700 + `hardenSecretDir` on Windows, `new Database(path, {create:true})`, chmod 0600, then + `PRAGMA busy_timeout=0`, `PRAGMA locking_mode=EXCLUSIVE`, `PRAGMA journal_mode=WAL` (exclusive mode uses no `-shm`), `BEGIN IMMEDIATE` + (acquires and, in exclusive mode, KEEPS the write lock until close), read `user_version`: 0 + empty -> create schema v1 and secret; + 1 -> continue; anything else -> ROLLBACK, close, disable (file untouched). COMMIT. Any failure -> rollback, close the handle, classify. +- Classification: SQLITE_BUSY/LOCKED at open = another process owns the store -> state `standby`; corrupt/NOTADB/symlink/non-regular/ + unknown version/ACL failure -> `disabled` for the scope (one identifier-free warning, file untouched). +- `standby`: affinity is process-local (today's behavior). The open is retried on a later affinity access at most every 2 s + (no timer). This covers a restart whose old process is still exiting. While in standby, mutations are recorded in the pending + log (below) bounded at 4096 key groups; on overflow the oldest key group (all ops for that rowKey) is dropped — the database then + keeps its pre-gap state for that key, which is the state persistence intends to restore and is fence-checked on adoption. +- The lock is released on close and on process exit (OS file lock), so a crash never wedges the next start. +- Two-process tests: B opening while A holds the store gets standby and never writes; A closes -> B's retry acquires; A crash + (kill) -> next process acquires. + +## In-process write log (answers round-4 blockers 1-3) + +- Ordered structural log: bind, deleteScope, deleteKey, deleteAccountPins, clearAll, clearIssuers, issuerSet, issuerDelete appended in + call order. No per-key coalescing of structural ops; `clearAll` may drop entries before it (they are dominated), nothing else is dropped + except the standby overflow rule above. +- Touch set (rowKey+scope -> latest, issuer rowKey -> latest), separate from the log. At flush, in ONE transaction: replay the log in + order, then apply touches as `UPDATE ... SET last_used_at = max(last_used_at, ?) WHERE row_key=? AND scope=? AND account_id=? AND fence=?`. + Bind-then-touch: the bind inserts, the touch updates it. Delete-then-touch: the touch matches nothing. A touch never inserts. +- With a single writer, commit order equals this process's call order, so stale cross-process writes cannot exist; validation-driven + deletes are unconditional because nothing else can have replaced the row. +- Flush failure while open (disk full, I/O): rollback, keep log and touches, retry on the next flush. After 3 consecutive failures: + close and unlink the database (an owned path) so no stale pins can be restored, disable for the process, warn once. If the unlink + fails too, warn; the next start only adopts rows that pass the fence and are then re-checked by the resolver. + +## Reads + +On a live-map miss with a known anchor and the store open: if the log holds a delete/clear covering rowKey(K) -> absent; else +`SELECT` (we hold the only connection, so no BUSY). Valid -> adopt (030 validation, current generation, entry count + LRU). Invalid -> +append `deleteScope`. A per-scope "consulted" set prevents re-querying the same rowKey; read errors are not cached and do not disable +unless classified corrupt. In standby, misses do not read. + +## Ownership (round-4 blocker 4) + +- Add `codex-affinity.sqlite`, `codex-affinity.sqlite-wal`, `codex-affinity.sqlite-journal` (and `-shm` defensively) to + `INITIAL_OWNED_PATHS` in `src/lib/config-ownership.ts`, next to the `config-mutation.sqlite*` entries. Every home created from now + on owns the files from creation, with no manifest update and no race. +- Existing homes: `recordOwnedConfigPath` for each path before first create; a `false` result -> do not create the database (warn once). + The residual race — another process holding an older cached manifest rewriting it — is a property of `recordOwnedConfigPath` shared by + every config writer today (`atomicWriteFileNoFollow` default path, `config-mutation.sqlite`, the Anthropic affinity file); fixing that + API is outside this lane and is noted in the PR as pre-existing. Tests: new home lists the paths; existing owned home records them; + recording failure creates nothing; `removeOwnedConfigState` removes the db and sidecars. + +## Handle lifetime + +Closed on: scope retirement (home change), `resetCodexAffinityStoreForTests`, the shutdown hook (flush then close), the failure path. +Windows test: arm, use, reset, `removeTreeWithRetry` succeeds. + +## Guards to extend/run + +`tests/ci-workflows/test-home-guard.test.ts` (the new writer refuses before any filesystem mutation when pointed at the real home), +`tests/lab/core-lab-boundary.test.ts` (new imports do not reach Lab; startServer window scan), config-ownership tests (INITIAL list), +file-size ratchet, test-layout guards, plus the 020/030/040 test list adjusted: cross-process cases become single-writer cases above. diff --git a/devlog/_plan/261102_codex_affinity_persist/060_plan_revision.md b/devlog/_plan/261102_codex_affinity_persist/060_plan_revision.md new file mode 100644 index 00000000000..2febd334108 --- /dev/null +++ b/devlog/_plan/261102_codex_affinity_persist/060_plan_revision.md @@ -0,0 +1,68 @@ +# 261102 Codex pool affinity persistence — 060 plan revision (answers audit round 5: reuse the existing single-writer lease) + +Amends 050. Items resolved in rounds 3-5 stay (dedicated database, fences captured at bind/issuance incl. chatgptAccountId, unknown +issuer, observer/home ordering and narrowed contract, passive rule, security table, ordered structural log + UPDATE-only touch set, +deterministic pruning, regression-test approach). 050's own lease (locking_mode=EXCLUSIVE), standby queue, overflow drop rule and +failure unlink are REMOVED. Issue: https://github.com/lidge-jun/opencodex/issues/8091 + +## The product already has one serving writer per state directory + +`src/lib/spend-ledger-owner.ts` holds a process-lifetime SQLite write transaction on `spend-ledger-owner.sqlite` (acquireSpendLedgerOwner:144). +`startServer` acquires it first (`src/server/index.ts:210` via `acquireSpendLedgerServerLifecycle`); a second server on the same home fails with +`SPEND_LEDGER_OWNER_BUSY` and does not serve; a restart child waits up to 5 s for the parent's release (restartHandoffWaitMs). Leases are +reference-counted per process; release hooks (`onSpendLedgerOwnerReleased`) run BEFORE the owner transaction is rolled back and closed +(leaseFor:200-213), i.e. while the lock is still held. `mintSpendLedgerStorage(fileName)` issues a storage token bound to the current owner +generation and `assertStorageOwned(token)` refuses it after any release/reacquire (lines 255-326). The affinity store uses exactly this. + +## Activation and writes + +- The store is active for a config home only while `mintSpendLedgerStorage("codex-affinity.sqlite")` succeeds (this process owns the lease for + the current home). Otherwise affinity is process-local, exactly as today: CLI processes, passive reads, tests that never start a server. + No separate arming call; no change to `src/server/index.ts`. +- Every open and every flush first calls `assertStorageOwned(token)`; NOT_HELD or a generation change retires the scope (close the handle, + drop log/touches, memory-only) and writes nothing. A newer owner generation mints a new token and a new scope. +- One `onSpendLedgerOwnerReleased` hook (registered once): synchronously flush the pending log and touches, set `meta.clean = 1` in the same + transaction, close the handle, retire the scope. It runs while the lease is still held, so no next owner can open the database before the + final state is committed. If that flush fails, `clean` stays 0 (below). Mutations after release are memory-only (the server has stopped serving). +- Open (lazy, first affinity access while owned), synchronous like `prepareOwnerPath`: `assertNotRealHomeUnderTest` FIRST (before ownership + initialization), `recordOwnedConfigPath` for the db and its `-journal`/`-wal`/`-shm` sidecars (every boolean checked; any false -> do not create, + warn once), create with `openSync(path, "wx", 0o600)` tolerant of EEXIST, `assertPrivateFile`-equivalent (regular, not a symlink, nlink 1, + owned by uid on POSIX), `hardenSecretPath(path, { required: true })` on Windows. Then `new Database(path)`, `PRAGMA busy_timeout = 0` (the lease + guarantees no other writer; any BUSY is an anomaly -> disable), default rollback journal (no journal-mode change, so nothing is modified + before the version check), `BEGIN IMMEDIATE`, read `user_version` and `sqlite_master`: empty v0 -> create schema v1 + `meta.secret` + `meta.clean=0`; + v1 -> read `meta.clean`; if 0 (previous owner crashed or failed its final flush) DELETE all thread and issuer rows (fail closed: pins + fall back to normal selection, never revive a release that was not committed); then set `meta.clean = 0` for this ownership; any other + version/shape -> ROLLBACK, close, disable, file untouched. COMMIT. Any failure: rollback, close, classify, identifier-free warning. +- Flushes are synchronous SQLite transactions scheduled from a microtask (structural) or a 1 s unref'd timer (touches); no async ACL + barrier is needed because no file is created after open (the transient `-journal` inherits the hardened directory, as for the owner db). +- Flush failure: rollback, keep the log, retry next flush. If the log exceeds 16384 entries or 3 consecutive flushes fail, the scope is + POISONED: the log is dropped, nothing more is written, and `clean` is never set to 1 — the next owner discards every row. No unlink, no + handoff race: the file stays under the lease until this process releases or dies. + +## Why the round-5 blockers are closed + +1. Standby replay: there is no standby. Only the lease holder writes, and a new holder can open only after the previous holder's release + hook committed (or it died, in which case `clean = 0` discards everything). Decisions are never replayed across ownerships. +2. Close-then-unlink: removed. Invalidation is `clean = 0` + DELETE at the next open, serialized by the lease. +3. Dropped deletions: no drop rule. Overflow poisons the scope, which fails closed at the next start. +4. Ownership race for existing homes: REBUTTED as pre-existing and out of lane, with mitigation. New homes own the four paths from creation + via `INITIAL_OWNED_PATHS` (no manifest update, no race). Existing homes use `recordOwnedConfigPath` before creation — the identical + mechanism `spend-ledger-owner.sqlite` (prepareOwnerPath:93), `config-mutation.sqlite` (mutation-lock.ts:62) and every default + `atomicWriteFileNoFollow` write rely on today. The stale-cache rewrite is a defect of that shared API; fixing it would change every + writer and is outside this lane's scope. The PR states it as a residual: if another process's stale manifest rewrite drops the entry, + uninstall can leave `codex-affinity.sqlite` (row digests + opaque pool ids, no tokens) behind. A follow-up issue will be filed for the API. + +## Tests (storage-specific; replaces 050's cross-process list) + +- Two-process restart through `resolveCodexAccountForThread` with real `startServer`-equivalent lease acquisition (or `acquireSpendLedgerOwner` + directly) — red-on-old from a `git archive origin/dev` export. +- Not owned -> no file created, no handle; owned -> created 0600 with ownership recorded; INITIAL list contains the four names. +- Release hook: pending structural op made just before release is committed and `clean = 1`; next owner restores it. +- Crash: kill an owner subprocess with pending/committed rows -> next owner finds `clean = 0` and restores nothing. +- Poison: injected flush failures / log overflow -> next owner restores nothing. +- Release + reacquire in one process (generation change): old token refused, new scope, no writes from the old one. +- Second server on the same home is refused by the existing lease (document; existing test covers BUSY) and never opens the affinity db. +- Unknown version / non-v1 schema -> untouched bytes, disabled; symlink or non-regular path -> disabled. +- Windows: start, use, stop (release hook closes), `removeTreeWithRetry` succeeds. +- Everything else from 020/030/040 (fences, unknown issuer via responses/compact/retry, home switch, passive, bounds, privacy). +- Guards: test-home guard (real home refused before ownership init), core-lab boundary, config-ownership tests, file-size ratchet, test layout. diff --git a/devlog/_plan/261102_codex_affinity_persist/070_plan_revision.md b/devlog/_plan/261102_codex_affinity_persist/070_plan_revision.md new file mode 100644 index 00000000000..cb9316439c9 --- /dev/null +++ b/devlog/_plan/261102_codex_affinity_persist/070_plan_revision.md @@ -0,0 +1,44 @@ +# 261102 Codex pool affinity persistence — 070 plan revision (answers audit round 6) + +Amends 060; everything else in 060 stands. Issue: https://github.com/lidge-jun/opencodex/issues/8091 + +## R6 blocker — final flush runs while ownership is still logically held + +`leaseFor` (src/lib/spend-ledger-owner.ts:200-213) decrements references and nulls `activeOwner` before running `releaseHooks`, so a hook +cannot pass `assertStorageOwned`. Change (minimal, in spend-ledger-owner.ts): + +- New `onSpendLedgerOwnerReleasing(hook: () => void): void` registry. In `release()`, when this is the FINAL reference + (`owner.references === 1`), set a module flag `releasing = true`, run the releasing hooks (each in try/catch), clear the flag, then + decrement, null `activeOwner`, run the existing `releaseHooks`, ROLLBACK and close as today. During releasing hooks the owner, its + generation and the physical lock are unchanged, so `assertStorageOwned(token)` passes for the current-generation token only. +- While `releasing` is true, `acquireSpendLedgerOwner` and `mintSpendLedgerStorage` throw NOT_HELD (no reentrant acquisition or new tokens + from inside a hook). Ordinary flushes after release fail `assertStorageOwned` exactly as before; stale tokens from an earlier generation + are refused as before. +- Optional neutral alias: export `mintStateDirectoryStorage`/`assertStateDirectoryStorageOwned` as thin aliases of the spend-named functions, + with a doc comment that the lease is the state directory's single-writer primitive. (Implementer may skip if maintainers' naming rules + object; behavior is identical.) +- The affinity store registers ONE releasing hook: sync flush of log + touches, `meta.clean = 1` in the same transaction, close, retire scope. + Hook failure -> rollback, `clean` stays 0, close, retire (fail closed). The existing `onSpendLedgerOwnerReleased` hook is used only to make + sure the scope is retired if the releasing hook did not run (defensive). +- Tests: pending structural op committed and restored across a real final release (two leases in one process: first release does not flush/close, + final does); stale-token refusal after release + reacquire; hook failure leaves `clean = 0` and the next owner restores nothing; acquire/mint + inside a releasing hook is refused; existing tests/lib/spend-ledger-owner.test.ts and tests/server/spend-ledger-owner-startup.test.ts still pass. + +## R6 residuals, accepted and specified + +- Stop failure keeps ownership until process exit; abrupt exit has no release hook -> `clean = 0` path (pins discarded). Documented. +- The final transaction is synchronous and bounded (at most the pending log, itself bounded at 16384 entries + touches); filesystem stalls + can still delay shutdown. Documented in structure. +- After final release, late async work is memory-only: the scope is retired, its token is invalid, nothing reopens under it and `clean` is never + touched again by that scope. +- Multiple servers in one process share the lease; the store stays live until the last reference releases. +- Test isolation (060 wording corrected): tests that start a server AND exercise affinity will create `codex-affinity.sqlite` in their isolated + home; the handle closes on the final server stop. Implementer runs every suite that starts a server and uses pool affinity + (`rg -l startServer tests` intersected with affinity entry points), checks teardown order, and adds a Windows-safe close in any helper that + resets state without stopping the server. +- Passive calls stay passive under a held lease: no open, adoption, scheduling or flush. Lazy open happens before any durable deletion that + must invalidate an unadopted row (a delete for a key with a known anchor opens the store first when owned). +- Ownership race for existing homes: residual stated in the PR; a follow-up issue for `recordOwnedConfigPath` is filed before the PR opens + and linked from it. +- Unsupported version/shape tests assert the application wrote nothing (no schema/meta change, no row change); they do not claim byte-for-byte + identity where SQLite's own hot-journal recovery may touch the file. diff --git a/devlog/_plan/261102_codex_affinity_persist/080_implementation_spec.md b/devlog/_plan/261102_codex_affinity_persist/080_implementation_spec.md new file mode 100644 index 00000000000..44f5913513a --- /dev/null +++ b/devlog/_plan/261102_codex_affinity_persist/080_implementation_spec.md @@ -0,0 +1,187 @@ +# 261102 Codex pool affinity persistence — 080 consolidated implementation spec + +Single source of truth for implementation. Consolidates 010-070 and the round-7 residuals; where they differ, this file wins. +Issue: https://github.com/lidge-jun/opencodex/issues/8091. Follow-up (ownership manifest race): https://github.com/lidge-jun/opencodex/issues/8093. +Security-sensitive (MAINTAINERS.md): a dedicated Terra security review runs before the PR and its verdict goes in the PR description. + +## 1. Problem + +Codex pool pins (`threadAccountMap`) and conversation-state issuers (`conversationStateIssuerMap`) in `src/codex/routing/thread-affinity.ts` +are in memory only, and the key they use is `codexConversationKeyFor()` in `src/codex/lineage.ts`, an HMAC under a per-process random secret. +A restart re-places every conversation (round-robin moves most of them: cold prompt cache) and loses the issuer that triggers the +account-change scrub (carried encrypted state can fail with `invalid_encrypted_content`). + +## 2. Contract + +- A pin survives a graceful proxy restart for up to 24 h idle when the request's cohort anchor is derivable from its headers: every request + with `session-id` (Codex CLI/App roots and subagents) and session-less requests anchored on their immediate parent. Deeper session-less + chains, keys first derived under another config home, legacy raw-parent keys and keys whose anchor was evicted are memory-only. +- Pins whose account is gone, re-logged (new `quotaHistoryIdentity`), legacy (no identity) or expired are dropped: normal selection. + Usability (pause, reauth, cooldown, plan/model exclusion, transient hold) stays with the existing resolver (`resolveCodexAccountForThread`, src/codex/routing.ts:498). +- `__main__` pins and `__main__` issuers are not persisted. +- A crash, a failed final flush, or a poisoned store makes the next owner discard every row (fail closed). +- Only the process holding the state directory's single-writer lease (`src/lib/spend-ledger-owner.ts`, acquired by `startServer`) persists. + A server in another process on the same home is refused by that lease; servers in the same process share it (reference-counted). + +## 3. Security posture + +- `CODEX_LINEAGE_KEY` and every value derived from it stay process-local and unchanged: pin/issuer map keys, `authCtx.affinityKey`, + `_cursorClientThreadId` (request-prepare.ts:417,563; cursor request-builder.ts:385; advisor state.ts:213 derives its own hash from it), + compact's issuer binding key (compact.ts:1684), lineage scope keys, affinity-debug tags (own key, ADR-0089). Request-log lanes use their + own digest of raw headers. Previous-response replay is keyed by response ids (implementer cites file:line in the PR). None changes. +- New durable artifact: `/codex-affinity.sqlite` (0600, Windows ACL via `hardenSecretPath`). It holds a 32-byte store secret + (`meta.secret`), rows keyed by `HMAC-SHA256(secret, "opencodex/codex-affinity/conversation/v1\0" + anchor)` (issuers: `.../issuer/v1`), + opaque pool account ids, identity fences `sha256("opencodex/codex-affinity/identity/v1\0" + quotaHistoryIdentity)`, scopes and timestamps. + No raw session/thread ids, no ephemeral keys, no tokens, no emails. Anyone who can read two copies of the file can link identical row keys + and pool ids across restarts; the secret is needed only to test a guessed anchor. Never logged; warnings are identifier-free. + +## 4. Modules and changes + +### 4.1 `src/codex/lineage.ts` +- Add `setCodexConversationAnchorObserver(fn?: (key: string, anchor: string) => void)`; `codexConversationKeyFor` calls it after deriving + (`anchor` = the family/thread value; for the cohort form both are the anchor). No new imports. Update the LIFETIME doc block: keys stay + process-local; the affinity store persists only digests under its own secret. + +### 4.2 `src/lib/spend-ledger-owner.ts` +- `onSpendLedgerOwnerReleasing(hook)`: in `release()`, after the per-lease `released` idempotence guard and the existing owner/refcount checks, + when this is the final reference (`owner.references === 1`): set `releasing = true`; run each releasing hook in its own try/catch; + clear `releasing` in `finally`; then continue exactly as today (decrement, null `activeOwner`, `boundLedgerHome = null`, release hooks, + ROLLBACK/close, throw on rollback/close failure). +- While `releasing`, `acquireSpendLedgerOwner` and `mintSpendLedgerStorage` throw `SPEND_LEDGER_OWNER_NOT_HELD`. +- Optional neutral aliases (`mintStateDirectoryStorage`, `assertStateDirectoryStorageOwned`) with a doc comment; behavior identical. +- Tests: throwing releasing hook does not block release; repeated release is a no-op; first of two leases does not run hooks; acquire/mint inside + a hook refused; existing `tests/lib/spend-ledger-owner.test.ts`, `tests/server/spend-ledger-owner-startup.test.ts` pass. + +### 4.3 `src/lib/config-ownership.ts` +- Add `codex-affinity.sqlite`, `-journal`, `-wal`, `-shm` to `INITIAL_OWNED_PATHS` next to the `config-mutation.sqlite*` entries. + +### 4.4 New `src/codex/routing/thread-affinity-store.ts` +Imports only `src/config/*`, `src/lib/*`, `bun:sqlite`, node builtins and the account-store reader (no routing value import cycle, no Lab). + +Scope = (config home, owner generation, storage token). Created lazily on the first affinity access when `mintSpendLedgerStorage("codex-affinity.sqlite")` +succeeds and `isPassiveRead()` is false. A home change or generation change retires the scope (close handle, drop log/touches/anchors/consulted set) +and clears the live affinity maps (as the Claude store drops its rows on home change). The anchor observer resolves the active scope FIRST, +then records `anchorByKey` (LRU, 4096, 24 h TTL, refreshed per derivation). Passive calls do nothing (no open, observe, adopt, schedule, flush). + +Open (synchronous; any failing step -> rollback/close, identifier-free warning, scope disabled for its lifetime. Earlier steps may already have +created the empty file or set its mode/ACL; for an unsupported version or shape the app makes no schema, metadata or row change, though SQLite's +own hot-journal recovery may still alter bytes): +1. `assertNotRealHomeUnderTest(home)` before anything else. +2. `recordOwnedConfigPath` for the db and its three sidecars (`-journal`, `-wal`, `-shm`); any `false` -> do not create. +3. `openSync(path, "wx", 0o600)` tolerating EEXIST; regular file, not a symlink, nlink 1, uid owner on POSIX; chmod 0600; `hardenSecretPath(path, {required:true})`; re-check. +4. `assertStorageOwned(token)`; `new Database(path)`; `PRAGMA busy_timeout = 0`; default rollback journal (no journal-mode change). +5. `BEGIN IMMEDIATE`; read `user_version` and `sqlite_master`. Empty v0 -> create schema v1, `meta.secret` (32 random bytes), `meta.clean = 0`. + v1 with the exact expected tables -> if `meta.clean != 1`, DELETE all thread and issuer rows; set `meta.clean = 0`. Anything else -> ROLLBACK, close, disable. + COMMIT. BUSY at any point is an anomaly under the lease -> disable. + +Schema v1: `meta(name TEXT PRIMARY KEY, value BLOB)`; `threads(row_key TEXT, scope TEXT, account_id TEXT, fence TEXT, created_at INTEGER, last_used_at INTEGER, PRIMARY KEY(row_key, scope))`; +`issuers(row_key TEXT PRIMARY KEY, account_id TEXT, fence TEXT, last_used_at INTEGER)` (fence nullable). + +Writes: +- Ordered structural log in call order: bind(rowKey, scope, accountId, fence, createdAt, lastUsedAt) = upsert; deleteScope; deleteKey; + deleteAccountPins(accountId) (pins only; issuers kept, as today); issuerSet (upsert); issuerDelete; clearIssuers; clearAll. Only `clearAll` + may drop earlier entries. Ops are logged only for keys with a known anchor in the scope (account-wide and clear ops always). +- Touch set (rows touched since the last flush) applied after the log in the same transaction. The timestamp is read from the LIVE in-memory entry + AT FLUSH TIME, never captured when the touch is scheduled: the getter schedules the touch before `src/codex/routing.ts` mutates the returned entry + (routing.ts:903-911), so a captured value would persist the old time and could expire an active pin. A touched row whose live entry is gone is skipped. Statement: + `UPDATE ... SET last_used_at = max(last_used_at, ?) WHERE row_key=? AND scope=? AND account_id=? AND fence=?` (issuers: `account_id` and `fence IS ?`). Never inserts. +- Structural ops schedule a microtask flush; touches (same-account rebind, binding read, issuer peek) a 1 s unref'd timer. A binding read schedules a + touch so the in-place `lastUsedAt` writes in `src/codex/routing.ts:911,942,985,1021` are captured (that file is at its size cap and is not edited). +- Flush = `assertStorageOwned(token)`, one `BEGIN IMMEDIATE` transaction: log, touches, prune (idle > 24 h or future-dated; newest 2048 per table ordered by + `last_used_at DESC, row_key, scope`, model-detour scopes evicted first). Failure -> ROLLBACK, keep log, retry next flush. 3 consecutive failures or log + > 16384 entries -> POISONED: drop log/touches, never write again, `clean` stays 0. +- Releasing hook (registered once via `onSpendLedgerOwnerReleasing`): if the scope is open and not poisoned, one transaction = log + touches + prune + + `meta.clean = 1`. Transaction failure -> ROLLBACK (clean stays 0). Then close; a close error after a successful COMMIT leaves `clean = 1` committed + (state is consistent: everything was committed) and is reported as an identifier-free warning. Retire the scope. `onSpendLedgerOwnerReleased` retires + any scope still open (defensive). Late async work after release is memory-only and never reopens under the old token. + +Reads (adoption): +- On a live-map miss for key K with a known anchor in an open scope: a pending delete/clear in the log covering rowKey(K) -> absent. Otherwise SELECT. + Thread row valid when: not idle > 24 h, not future-dated, scope valid (`legacy`, a known `CodexQuotaScope`, or `model-detour::` whose model + passes the existing 512-byte component rule), account record has a credential, not deleted, current `quotaHistoryIdentity` fence equals the stored fence. + Valid -> insert into `threadAccountMap` with the record's CURRENT generation, `lastReevalAt = now`, no transient fields, increment + `threadAffinityEntryTotal`, run the existing LRU prune. Invalid -> log deleteScope. +- Issuer row: idle > 24 h or future-dated -> absent and log issuerDelete (time passes after the last flush prune, and the live issuer map also + expires on peek, thread-affinity.ts:238,274). Otherwise fence equal -> issuer = account id; fence null or different -> `CODEX_UNKNOWN_CONVERSATION_STATE_ISSUER`. +- A bounded per-scope consulted set avoids re-querying; read errors are not cached. +- `getThreadAffinityScopes(K)` adopts all restored scopes for K first. + +### 4.5 `src/codex/routing/thread-affinity.ts` (call-site hooks only; not the affinity log label) +- `ThreadAffinityEntry.identityFence?: string`, captured in `bindThreadAffinityForScope` from the same record read that supplies `generation`; + kept by `handOffThreadAffinityGeneration`. Entries without a fence (legacy record, `__main__`) are memory-only. +- `rememberConversationStateIssuer(bindingKey, accountId, now?, credential?: { generation, chatgptAccountId })`: fence captured only when the record's current + generation AND `credential.chatgptAccountId` match; else the row is fence-less (restores as unknown). `__main__` not persisted. +- Export `CODEX_UNKNOWN_CONVERSATION_STATE_ISSUER` (a string no account id can equal). +- Hooks in: scoped getters (adopt on miss; touch on hit), `getThreadAffinityScopes`, bind/delete/delete-for-account, `clearThreadAccountMapForAccount`, + TTL/LRU prune, `handOffThreadAffinityGeneration`, issuer remember/peek/clear, `clearThreadAccountMap` (clearAll). +- Update the lifetime comments (issuer map, legacy adoption). + +### 4.6 `src/server/responses/account-change-state.ts` +- `rememberServingConversationStateIssuer` passes `{ generation, chatgptAccountId }` for pool contexts. +- `applyAccountChangeConversationStateScrub`: unknown issuer counts as changed. +- `accountChangeFileReferenceRefusal`: unknown issuer ignored; refuse only for a known different issuer or a `priorAccountId` move. + +### 4.7 Comment-only +`src/adapters/google-antigravity-wire.ts` comment about the process-random key: keep the meaning (the key still changes across restarts), adjust wording only if needed. + +## 5. Reset and removal + +| Entry point | Durable effect | +|---|---| +| `clearThreadAccountMap()` (config/provider/model/combo/agent-settings/logs-usage/oauth-account/shared management routes, server index) | clearAll | +| `clearConversationStateIssuerMap()` | clearIssuers | +| `clearThreadAccountMapForAccount(id)` (removal, auto-pause, plan exclusion, quota refusal, preservation) | deleteAccountPins (issuers kept) | +| account deleted/re-logged without a clear | fence fails on adoption -> row deleted | +| uninstall | owned paths removed (new homes always; existing homes subject to #8093) | + +## 6. Tests + +New file `tests/codex-integration/codex-affinity-restart.test.ts` (+ helper worker under `tests/helpers/` if needed); register in +`scripts/test-layout/layout.json` (near line 709) and `tests/fixtures/test-layout-expected.json` (near line 697). Lease tests may live in +`tests/lib/spend-ledger-owner.test.ts` if under its size cap, else a sibling file (registered). Cases: + +1. Red-on-old: two fresh `bun` subprocesses on one temp home, each acquiring the lease, seeding two pool accounts with round-robin, resolving a + session-bearing request via `resolveCodexAccountForThread` with `codexPoolAffinityKey(headers)`, recording the issuer, releasing. Process 2 advances + the cursor so a fresh pick chooses the other account. Expect same account and known issuer (scrub not triggered for the same account; triggered for + a different one). Old code (isolated `git archive origin/dev` export with the test + helper copied, only the optional store import caught) fails on + the assertion; record output. +2. Fallbacks: removed, re-logged, legacy, expired, future -> normal selection, row deleted. Usability cases asserted against the resolver one by one. +3. `__main__`: pin and issuer not persisted. +4. Session-less depth-1 survives; depth-2 re-places; anchor eviction -> memory-only. +5. Reconciliation before first lookup: bind/delete/delete-for-account/issuer set/clear/clear-for-account on a key with a restored, unadopted row. +6. Fence races: re-login between bind and release; re-login between dispatch and issuer completion; owned refresh/handoff; Orca rotation; delete + re-add. +7. Unknown issuer with file references via responses and compact; `priorAccountId` retry still refuses; known different issuer still refuses. +8. Lease: not owned -> no file; release flush commits pending op and `clean = 1`; two leases -> only final release flushes; crash (kill subprocess) -> next owner + restores nothing; poison (injected failures, overflow) -> next owner restores nothing; transaction failure in the releasing hook -> clean 0; close failure + after commit -> rows restored; release + reacquire -> old token refused. +9. Database shape: unknown version/shape -> app makes no schema, metadata or row change (SQLite hot-journal recovery may still alter bytes) and disables; symlink/non-regular -> disabled; file 0600; INITIAL list has the four names; + existing owned home records them; recording failure -> no db. +10. Bounds and privacy: > 2048 rows per table keeps newest; worst-case UTF-8 detour scope accepted; no raw ids/ephemeral keys in the db; warnings identifier-free. + Touch timing: resolver reuse (which mutates `lastUsedAt` after the getter) then release and restart persists the NEW timestamp; an issuer row that + expired or is future-dated at read time is treated as absent and deleted. +11. Home A -> B -> A, first B request, recorded lineage; passive calls with a populated db and a held lease. +12. Windows: start, use, stop, `removeTreeWithRetry` succeeds. + +Existing suites to run: every test file using the affinity entry points or `startServer` + pool affinity (the round-1 audit counted 38), lineage tests, +`tests/responses/responses-account-change-scrub.test.ts`, `tests/responses/responses-4546-incident-regression.test.ts`, owner tests, config-ownership tests, +`tests/lab/core-lab-boundary.test.ts`, `tests/ci-workflows/test-home-guard.test.ts` (new writer refused before ownership init), file-size ratchet, +`tests/test-layout.test.ts`, `tests/test-layout-tooling.test.ts`. + +## 7. Docs + +- `structure/providers/openai-tiers.md`: lineage section (key stays process-local) + new "Durable Codex pool affinity" subsection (contract, file, schema, + secret, fences, lease, clean flag, write log, touches, bounds, ownership residual #8093, tests). +- `structure/providers/openai-accounts.md`: only claims that pins are process-local (not the diagnostic tags or idle-window reservations). +- `structure/` owner of `src/lib/spend-ledger-owner.ts` (find via structure/manifest.json): document releasing hooks. +- docs-site: `reference/cli/providers-accounts.md` (~848) and `reference/configuration/providers.md` (`accountPoolStrategy` row) restart wording, in English + and every locale copy (search per locale); build the docs site per docs-site/AGENTS.md. + +## 8. Verification + +Focused tests above, `bun run typecheck`, `bun run structure:check`, `bun run privacy:scan`, docs-site build, `bun scripts/test.ts --changed=dev --parallel=1`, +red-on-old recorded. PR gets `ci:full` (subprocess tests, docs, on-disk contracts). + +## 9. Out of scope + +`src/codex/routing/selection.ts` (Lane C), `src/codex/auth-context.ts` and the affinity log label (Lane D), `src/server/claude-*` and +`src/server/caller-session-identity.ts` (Lane A), `src/codex/routing.ts` and `src/server/index.ts` (size caps), the ownership API fix (#8093). diff --git a/docs-site/src/content/docs/fr/reference/cli/providers-accounts.md b/docs-site/src/content/docs/fr/reference/cli/providers-accounts.md index acdc51645c5..b378545e45b 100644 --- a/docs-site/src/content/docs/fr/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/fr/reference/cli/providers-accounts.md @@ -229,9 +229,8 @@ cet état et quitte toujours 0. `--json` renvoie : `auto` efface la sélection manuelle pour que le pool place à nouveau le travail selon sa propre stratégie — sauf si un compte Codex porte littéralement l'id `auto`, qui l'emporte par correspondance exacte d'id ; `ocx account clear ` rétablit toujours la sélection automatique. Un compte Codex peut être désigné par l'alias défini avec `ocx account alias` au lieu de son id ; cela vaut aussi pour `priority`, `pause`, `resume`, `clear-cooldown`, `remove` et `alias`. Pour les comptes Codex, `auto`, `main` et `__main__` sont réservés sans distinction de casse et ne peuvent pas être attribués comme alias. Les noms affichés des comptes OAuth et des clés API conservent leurs règles existantes. Sélectionne un compte Codex, un compte OAuth ou une clé API existant. Pour `openai`, `main` sélectionne la -connexion Codex App. Une sélection en mode Codex Pool efface l'affinité locale du processus et s'applique à la requête suivante, -dont un provenant d'une tâche visible existante ; le redémarrage du proxy ou l'expulsion par affinité peuvent également laisser une tâche -non lié, tandis que les demandes en cours conservent leur compte capturé. Cela contrôle uniquement le routage du pool ; +connexion Codex App. Une sélection en mode Codex Pool efface l'affinité et s'applique à la requête suivante, +y compris si elle provient d'une tâche visible existante. Les liaisons des requêtes avec un identifiant de session (y compris les tours habituels de Codex CLI et App et les sous-agents), ou des requêtes sans session ancrées sur leur parent immédiat, peuvent survivre à un redémarrage normal du proxy jusqu’à 24 heures d’inactivité, si l’enregistrement final de l’affinité à l’arrêt réussit. Les chaînes sans session plus profondes et les liaisons à la connexion principale de Codex App restent en mémoire uniquement et sont réattribuées après le redémarrage ; une expulsion, la suppression du compte, une reconnexion, un plantage ou une réinitialisation de l’affinité peuvent laisser une tâche non liée, tandis que les demandes en cours conservent leur compte capturé. Cela contrôle uniquement le routage du pool ; Le mode direct continue d’utiliser les informations d’identification principales de l’appelant. Commutation proactive basée sur l'utilisation, 401/403 réauthentification, 429/retry-after temps de recharge, exclusion et pré-sortie 429/402 échec la récupération peut sélectionner ultérieurement un autre compte Pool éligible. Ces chemins de récupération restent actifs lorsque diff --git a/docs-site/src/content/docs/fr/reference/configuration/providers.md b/docs-site/src/content/docs/fr/reference/configuration/providers.md index c2ba9e8836a..c4bd73f020c 100644 --- a/docs-site/src/content/docs/fr/reference/configuration/providers.md +++ b/docs-site/src/content/docs/fr/reference/configuration/providers.md @@ -57,7 +57,7 @@ Après une inscription ou une connexion OAuth dans l’interface, une boîte de | `activeCodexAccountPinned?` | `string` | — | Identifiant du compte du dernier opérateur sélectionné manuellement. Lorsqu'il est défini, un niveau `codexAccountPriorities` supérieur ne peut pas le préempter jusqu'à ce que la broche soit libérée par drainage, exclusion, suppression ou un failover/promotion explicite. Un mouvement circulaire ordinaire à l’intérieur du niveau plafonné ne le libère pas. L'écriture d'une entrée `codexAccountPriorities` libère également le pin, donc un pin créé avant qu'un ordre n'existe ne peut pas surpasser un ensemble par la suite. `GET /api/codex-auth/active` indique à la fois si le compte effectif est épinglé (`pinned`) et le compte portant le plafond (`pinnedAccountId`). | | `autoSwitchThreshold?` | `number` | `80` | Seuil d'utilisation pour la commutation proactive. `quota` peut réévaluer les requêtes non liées lors de leur prochaine requête. Les tâches liées conservent leur compte au-delà du seuil par défaut (`pool.cacheAffinity`) jusqu'à ce que ce compte soit épuisé ou ne puisse plus servir, et ne basculent alors que vers un compte dont l'utilisation est strictement inférieure et qui dispose d'une véritable marge de quota. Définissez `pool.cacheAffinity: false` pour réévaluer aussi les tâches liées à ce seuil. `fill-first` ne l'utilise que comme seuil d'évacuation pour l'affectation des requêtes non liées ; `round-robin` ne l'utilise que pour les nouvelles affectations non liées : tant qu'un compte admissible reste sous son seuil effectif, il ignore ceux qui l'atteignent ou le dépassent, sans jamais déplacer une tâche liée pour cette raison. Le score retient la plus élevée des fenêtres de quota connues sur 5 heures, une semaine ou 30 jours. `0` désactive uniquement la commutation proactive fondée sur l'utilisation, pas l'affectation des requêtes non liées ni la récupération après incident. | | `codexAccountAutoSwitchThresholds?` | `Record` | — | Seuils par compte remplaçant `autoSwitchThreshold` : identifiant → entier de `0` à `100`. Une entrée absente hérite du seuil global ; `0` désactive uniquement les déplacements fondés sur l’utilisation depuis ce compte. Le compte principal `__main__` est pris en charge. La carte du compte dans Codex Auth gère cette valeur. Activer la valeur spécifique au compte copie le seuil global actuel dans une valeur fixe. Cette valeur, y compris `0`, reste prioritaire après toute modification du seuil global. La désactiver envoie `threshold: null`, supprime l'entrée et rétablit l'héritage du seuil global actuel et de ses modifications futures. | -| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | Stratégie d'affectation des requêtes Codex nouvelles ou non liées. Une requête est non liée lorsqu'elle ne possède aucune affinité active, définie par l'identifiant de la tâche parente et la portée du quota ; une tâche existante visible peut perdre son lien après le redémarrage du proxy ou la réinitialisation de l'affinité. `quota` sélectionne le compte admissible le moins utilisé lorsqu'aucun compte actif n'existe, conserve un compte actif admissible sous `autoSwitchThreshold` et, une fois le seuil franchi, peut déplacer une requête non liée. Les tâches liées suivent `pool.cacheAffinity` (activé par défaut) : elles restent jusqu'à ce que le compte soit épuisé (utilisation connue à 100 %) ou ne puisse plus servir, et ne se relient alors qu'à un compte dont l'utilisation est strictement inférieure et qui dispose d'une véritable marge de quota. Définissez le drapeau à `false` pour relier de manière proactive une tâche liée à un compte admissible moins utilisé au seuil, toujours sous la même contrainte de destination. `round-robin` répartit équitablement les requêtes non liées entre les comptes admissibles sous leur `autoSwitchThreshold` effectif, ou entre tous les comptes admissibles s'ils ont tous atteint ou dépassé leur seuil ; `fill-first` continue de les attribuer au compte actif jusqu'à sa temporisation, son indisponibilité ou le seuil d'évacuation configuré. `reset-first`: Parmi les comptes sous le seuil, privilégier le prochain reset de 5 heures ou hebdomadaire. Les tâches liées suivent la politique d’affinité configurée. Les quotas de modèles indépendants suivent l’ordre de consommation. Les resets mensuels ne déterminent pas cet ordre. | +| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | Stratégie d'affectation des requêtes Codex nouvelles ou non liées. Une requête est non liée lorsqu'elle ne possède aucune affinité active, définie par l'identifiant de la tâche parente et la portée du quota . Les liaisons des requêtes avec un identifiant de session (y compris les tours habituels de Codex CLI et App et les sous-agents), ou des requêtes sans session ancrées sur leur parent immédiat, peuvent survivre à un redémarrage normal du proxy jusqu’à 24 heures d’inactivité, si l’enregistrement final de l’affinité à l’arrêt réussit. Les chaînes sans session plus profondes et les liaisons à la connexion principale de Codex App restent en mémoire uniquement et sont réattribuées après le redémarrage ; une expulsion, la suppression du compte, une reconnexion, un plantage ou une réinitialisation de l’affinité peuvent laisser une tâche non liée. `quota` sélectionne le compte admissible le moins utilisé lorsqu'aucun compte actif n'existe, conserve un compte actif admissible sous `autoSwitchThreshold` et, une fois le seuil franchi, peut déplacer une requête non liée. Les tâches liées suivent `pool.cacheAffinity` (activé par défaut) : elles restent jusqu'à ce que le compte soit épuisé (utilisation connue à 100 %) ou ne puisse plus servir, et ne se relient alors qu'à un compte dont l'utilisation est strictement inférieure et qui dispose d'une véritable marge de quota. Définissez le drapeau à `false` pour relier de manière proactive une tâche liée à un compte admissible moins utilisé au seuil, toujours sous la même contrainte de destination. `round-robin` répartit équitablement les requêtes non liées entre les comptes admissibles sous leur `autoSwitchThreshold` effectif, ou entre tous les comptes admissibles s'ils ont tous atteint ou dépassé leur seuil ; `fill-first` continue de les attribuer au compte actif jusqu'à sa temporisation, son indisponibilité ou le seuil d'évacuation configuré. `reset-first`: Parmi les comptes sous le seuil, privilégier le prochain reset de 5 heures ou hebdomadaire. Les tâches liées suivent la politique d’affinité configurée. Les quotas de modèles indépendants suivent l’ordre de consommation. Les resets mensuels ne déterminent pas cet ordre. | | `pool.cacheAffinity?` | `boolean` | `true` | Ordre d'affinité de cache pour les threads Codex liés, indépendant de `pool.kernel`. Activé par défaut ; omettre la clé ou la définir à `true` conserve la liaison, et une valeur autre que `false` est lue comme activée. Une liaison active prime sur la marge de quota : `quota` ne déplace pas le thread simplement parce que l'utilisation a franchi `autoSwitchThreshold`, car déplacer une conversation liée jette le cache d'invites isolé par compte. Le thread quitte encore le compte s'il ne peut plus servir — suspendu, inutilisable, exclu du plan, identifiants invalides, génération remplacée, TTL expiré, refus de quota 429/402, ou réellement épuisé (utilisation connue à 100 %) — et seulement vers un compte dont l'utilisation est strictement inférieure et qui dispose d'une véritable marge de quota. Un compte dont l'utilisation est inconnue n'est jamais choisi comme destination d'une tâche liée. Si tous les comptes dépassent le seuil, la tâche liée reste, car aucune destination n'est meilleure. Définissez `false` pour rétablir la réaffectation au seuil, toujours sous la même contrainte de destination. L'affinité est un réordonnancement, pas un verrouillage. | | `accountPoolStickyLimit?` | `number` | `1` | Nombre d'affectations de tâches nouvelles ou non liées conservées sur une même sélection tournante avant de passer à la suivante ; le compteur avance lorsqu'une tâche est liée, et non après une réponse réussie en amont. Plage : 1–100. | | `upstreamFailoverThreshold?` | `number` | `3` | Nombre d'échecs transitoires consécutifs avant le basculement des futures nouvelles sessions. Réglez `0` pour désactiver ce mécanisme. Pour les requêtes Responses ordinaires et les envois compacts natifs, les échecs avérés d'accessibilité DNS/TCP avant connexion sont suivis au niveau du couple fournisseur-hôte : ils n'affectent jamais l'état ni la temporisation du compte, l'affinité de tâche ou de session, la sélection du compte actif ou le routage du pool, et ne sont jamais comptabilisés dans ce seuil. | @@ -235,8 +235,7 @@ Utilisez **Codex Auth** dans le tableau de bord pour ajouter des comptes au grou métadonnées non secrètes ; les jetons d'accès et d'actualisation utilisent le magasin d'identifiants renforcé. Le routage du pool distingue l'affectation des requêtes nouvelles ou non liées, la commutation proactive fondée sur l'utilisation et la récupération après incident. Une tâche liée conserve normalement son affinité. Par défaut (`pool.cacheAffinity`), cette réaffectation attend que le compte lié soit épuisé ou ne puisse plus servir, et seulement vers un compte dont l'utilisation est strictement inférieure et qui dispose d'une véritable marge de quota. Définissez `pool.cacheAffinity: false` pour laisser `quota` la relier dès la requête suivante une fois le seuil franchi, toujours sous la même contrainte de destination. Un refus de quota 429/402, une pause, une invalidation des identifiants ou l'expiration du TTL libèrent encore la liaison immédiatement ; une série d'échecs transitoires (5xx et autres échecs hors quota) sert la requête sur un autre compte sans supprimer la liaison active. -Une requête non liée ne possède aucune liaison active à un compte ; il peut s'agir d'une tâche existante visible après le redémarrage -du proxy ou la réinitialisation de l'affinité. Un 429 ou un 402 reçu avant le début de la diffusion déclenche une nouvelle tentative unique sur un +Une requête non liée ne possède aucune liaison active à un compte . Les liaisons des requêtes avec un identifiant de session (y compris les tours habituels de Codex CLI et App et les sous-agents), ou des requêtes sans session ancrées sur leur parent immédiat, peuvent survivre à un redémarrage normal du proxy jusqu’à 24 heures d’inactivité, si l’enregistrement final de l’affinité à l’arrêt réussit. Les chaînes sans session plus profondes et les liaisons à la connexion principale de Codex App restent en mémoire uniquement et sont réattribuées après le redémarrage ; une expulsion, la suppression du compte, une reconnexion, un plantage ou une réinitialisation de l’affinité peuvent laisser une tâche non liée. Un 429 ou un 402 reçu avant le début de la diffusion déclenche une nouvelle tentative unique sur un autre compte admissible au sein de la même requête, même lorsque la commutation proactive fondée sur l'utilisation est désactivée. Les changements de compte préservent et relisent le contexte de la conversation, mais la réutilisation du cache d'invites du fournisseur entre plusieurs comptes n'est pas garantie et le cache peut devoir être réchauffé. diff --git a/docs-site/src/content/docs/ja/reference/cli/providers-accounts.md b/docs-site/src/content/docs/ja/reference/cli/providers-accounts.md index b199c822ffc..0a939338274 100644 --- a/docs-site/src/content/docs/ja/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/ja/reference/cli/providers-accounts.md @@ -180,7 +180,7 @@ Codex クライアント連携を無効にしても、既存のネイティブ `auto` は手動の選択を解除し、プールが自身の戦略で再び配置するようにします — ただし id が `auto` の Codex アカウントが存在する場合は完全一致の id が優先され、`ocx account clear ` が常に自動選択を復元します。Codex アカウントは id の代わりに `ocx account alias` で付けたエイリアスでも指定でき、`priority`、`pause`、`resume`、`clear-cooldown`、`remove`、`alias` でも同様です。Codex アカウントでは `auto`、`main`、`__main__` は大文字・小文字を区別せず予約語として扱われるため、エイリアスとして設定できません。OAuth アカウントと API キーの表示名には従来のルールが適用されます。 既存の Codex アカウント、OAuth アカウント、または API key を選びます。`openai` で `main` は Codex App ログインを -選択します。Codex Pool の選択は process-local affinity を消去し、既存の表示タスクを含む次のリクエストから適用されます。プロキシ再起動や affinity eviction 後もタスクは未紐付けになり得ますが、処理中のリクエストは取得済みアカウントを維持します。この選択は Pool routing のみを制御し、Direct mode は caller-owned/native main credential を使い続けます。使用量ベースのプロアクティブ切り替え、401/403 再認証、429/retry-after cooldown、除外、出力前 429/402 の障害回復により、後で別の適格 Pool アカウントが選ばれる場合があります。これらの回復経路は使用量ベース切り替えが off でも有効です。アカウント変更後も OpenCodex は会話コンテキストを再生しますが、provider prompt cache は再ウォームアップが必要な場合があります。 +選択します。Codex Pool の選択は affinity を消去し、既存の表示タスクを含む次のリクエストから適用されます。セッションIDを持つリクエスト(通常の Codex CLI・App のターンやサブエージェントを含む)と、直近の親に紐付くセッションなしリクエストの紐付けは、シャットダウン時の最終的な affinity 保存が成功した場合、プロキシの正常な再起動後も最大24時間の非活動期間まで保持されることがあります。より深いセッションなしの連鎖と Codex App のメインログインへの紐付けはメモリ内にのみ残り、再起動後に再割り当てされます。eviction、アカウント削除、再ログイン、クラッシュ、affinity リセットではタスクが未紐付けになり得ますが、処理中のリクエストは取得済みアカウントを維持します。この選択は Pool routing のみを制御し、Direct mode は caller-owned/native main credential を使い続けます。使用量ベースのプロアクティブ切り替え、401/403 再認証、429/retry-after cooldown、除外、出力前 429/402 の障害回復により、後で別の適格 Pool アカウントが選ばれる場合があります。これらの回復経路は使用量ベース切り替えが off でも有効です。アカウント変更後も OpenCodex は会話コンテキストを再生しますが、provider prompt cache は再ウォームアップが必要な場合があります。 不明なプロバイダーや id は終了コード 1 です。`--json` は次を返します。 **401/403** では、そのアカウントへのプロセスローカルな affinity を解除し、再認証を要求します。 **429** では `Retry-After` を尊重してアカウントの cooldown を開始し、affinity を解除したうえで、 diff --git a/docs-site/src/content/docs/ja/reference/configuration/providers.md b/docs-site/src/content/docs/ja/reference/configuration/providers.md index 3e9e5085980..3459c6b2caf 100644 --- a/docs-site/src/content/docs/ja/reference/configuration/providers.md +++ b/docs-site/src/content/docs/ja/reference/configuration/providers.md @@ -55,7 +55,7 @@ GUI で登録または OAuth ログインが完了すると、Models ページ | `codexAccountPriorities?` | `Record` | — | Codex pool のアカウント別選択順。アカウント ID → `-100` から `100` の整数で、**大きいほど先に使われ**、未設定は `0` です。これは eligibility ではなく順序の境界です。選択は適格なアカウントを、まだ quota に余裕がある最上位 tier に絞り込み、その tier の中を `accountPoolStrategy` が選びます。tier が飛ばされるのは、そのメンバー全員が自身の 0 以外の実効しきい値(アカウント別上書き、未設定ならグローバル値)以上、cooldown 中、soft-avoid、一時停止、または再認証待ちのときだけで、usage 不明が tier を drain させることはありません。順序付けが不適格なアカウントを選択可能にすることはなく、すでにアカウントが結び付いた thread を再 bind することもありません。メインの `__main__` も同じ条件で参加するため、Codex Desktop ログインを最後に使わせられます。エントリが 1 つもなければ挙動は従来どおりです。map が不正な場合は警告を出して順序付けを無効にします(config の修復処理は走りません)。`ocx account priority` と Codex Auth ページで管理します。 | | `autoSwitchThreshold?` | `number` | `80` | 使用量ベースのプロアクティブ切り替えしきい値。`quota` は未紐付けタスクの次のリクエストを再評価できます。紐付け済みタスクは既定(`pool.cacheAffinity`)ではしきい値を超えても同じアカウントを維持し、アカウントが使い切られるか処理できなくなったときだけ離れ、その場合も実際に quota 余裕があり usage がより低いアカウントへだけ移ります。`pool.cacheAffinity: false` にするとしきい値で紐付け済みタスクも再評価します。`fill-first` は未紐付け割り当ての使い切り基準としてのみ使用し、`round-robin` は新規/未紐付けの割り当て時にのみ使用し、しきい値未満の適格アカウントがある間は実効しきい値以上のアカウントを除外し、この理由で紐付け済みタスクを移動しません。既知の 5 時間、週次、30 日 quota window の最大スコアを使います。`0` は使用量ベースの切り替えだけを無効にし、未紐付け割り当てや障害回復は無効にしません。 | | `codexAccountAutoSwitchThresholds?` | `Record` | — | `autoSwitchThreshold` のアカウント別上書き(アカウント ID → `0`〜`100` の整数)。未設定はグローバル値を継承し、`0` はそのアカウントからの使用量ベース切り替えだけを無効にします。メインの `__main__` も指定できます。Codex Auth の各アカウントカードで管理します。 上書きを有効にすると、現在のグローバルしきい値が固定のアカウント別値としてコピーされます。`0` を含む上書き値は、その後グローバル値が変更されても優先されます。無効にすると `threshold: null` を送信してエントリを削除し、現在のグローバルしきい値と今後の変更を継承する状態に戻ります。 | -| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | 新規/未紐付け Codex リクエストの割り当て戦略。live な `(parent thread id, quota scope)` affinity がなければ未紐付けで、プロキシ再起動や affinity リセット後は既存の表示タスクも未紐付けになり得ます。`quota` はアクティブアカウントがなければ既知 usage 最小の適格アカウントを選び、適格なアクティブアカウントが `autoSwitchThreshold` 未満なら維持します。しきい値到達後は未紐付けリクエストを移せます。紐付け済みタスクは既定ではアカウントが使い切られるか(既知 usage 100%)処理できなくなるまで維持され、離れるときは実際に quota 余裕があり usage がより低いアカウントへだけ移ります。フラグをオフにすると、しきい値で紐付け済みタスクの次のリクエストも実際に quota 余裕があり usage がより低い適格アカウントへ移せます。`round-robin` は実効 `autoSwitchThreshold` 未満の適格アカウントに未紐付けリクエストを均等分散し、全員がしきい値以上なら全適格アカウントに分散し、`fill-first` は cooldown、使用不可、または drain threshold までアクティブアカウントへ割り当てます。 `reset-first`: 使用率のしきい値未満から、次の5時間枠または週次枠のリセットが最も近いアカウントを選びます。紐付け済みタスクは設定されたアフィニティ方針に従います。独立したモデル枠は使用率順です。 月次リセットはこの順序に使用しません。 | +| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | 新規/未紐付け Codex リクエストの割り当て戦略。live な `(parent thread id, quota scope)` affinity がなければ未紐付けです。セッションIDを持つリクエスト(通常の Codex CLI・App のターンやサブエージェントを含む)と、直近の親に紐付くセッションなしリクエストの紐付けは、シャットダウン時の最終的な affinity 保存が成功した場合、プロキシの正常な再起動後も最大24時間の非活動期間まで保持されることがあります。より深いセッションなしの連鎖と Codex App のメインログインへの紐付けはメモリ内にのみ残り、再起動後に再割り当てされます。eviction、アカウント削除、再ログイン、クラッシュ、affinity リセットではタスクが未紐付けになり得ます。`quota` はアクティブアカウントがなければ既知 usage 最小の適格アカウントを選び、適格なアクティブアカウントが `autoSwitchThreshold` 未満なら維持します。しきい値到達後は未紐付けリクエストを移せます。紐付け済みタスクは既定ではアカウントが使い切られるか(既知 usage 100%)処理できなくなるまで維持され、離れるときは実際に quota 余裕があり usage がより低いアカウントへだけ移ります。フラグをオフにすると、しきい値で紐付け済みタスクの次のリクエストも実際に quota 余裕があり usage がより低い適格アカウントへ移せます。`round-robin` は実効 `autoSwitchThreshold` 未満の適格アカウントに未紐付けリクエストを均等分散し、全員がしきい値以上なら全適格アカウントに分散し、`fill-first` は cooldown、使用不可、または drain threshold までアクティブアカウントへ割り当てます。 `reset-first`: 使用率のしきい値未満から、次の5時間枠または週次枠のリセットが最も近いアカウントを選びます。紐付け済みタスクは設定されたアフィニティ方針に従います。独立したモデル枠は使用率順です。 月次リセットはこの順序に使用しません。 | | `pool.cacheAffinity?` | `boolean` | `true` | 紐付け済み Codex スレッド向けの cache-affinity 順序。`pool.kernel` とは独立で、既定はオンです。不正な値はオンとして読みます。live な紐付けが quota 余裕より優先され、`quota` は使用量が `autoSwitchThreshold` を超えたという理由だけではスレッドを移しません。一時停止、使用不可、または実際に使い切られたアカウント(既知 usage 100%)では離れますが、実際に quota 余裕があり usage がより低いアカウントへだけ移ります。`false` にするとしきい値での再紐付けに戻ります。affinity は固定ではなく並べ替えです。 | | `accountPoolStickyLimit?` | `number` | `1` | 1 回の round-robin 選択で次へ進む前に保持する新規/未紐付けタスク割り当て数。カウンターは上流の成功後ではなくタスクの紐付け時に増えます。範囲 1–100。`accountPoolStrategy` が `round-robin` のときのみ。 | | `upstreamFailoverThreshold?` | `number` | `3` |今後の新しいセッションがフェイルオーバーする前に一時的なエラーが連続して発生する。 `0` を無効に設定します。通常のResponses送信とネイティブcompact送信では、実証済みの接続前DNS/TCP到達不能障害はprovider-host単位で記録され、アカウントの健全性、アカウントのクールダウン、スレッド/セッションの親和性、アクティブアカウントの選択、Poolルーティングには影響せず、この閾値にもカウントされません。 | @@ -220,8 +220,7 @@ pool アカウントの追加と quota 更新はダッシュボードの **Codex 使い切られるか処理できなくなるまで再紐付けを延期し、離れるときは実際に quota 余裕があり usage が より低いアカウントへだけ移ります。フラグをオフにすると、`quota` はしきい値超過後の次のリクエストで 再紐付けできます。 -pause、cooldown、再認証、障害処理も独立して routing を消去または変更できます。未紐付けリクエストには -プロキシ再起動や affinity リセット後の既存タスクも含まれます。出力前の **429/402** は使用量ベースの +pause、cooldown、再認証、障害処理も独立して routing を消去または変更できます。未紐付けリクエストには有効なアカウントの紐付けがありません。セッションIDを持つリクエスト(通常の Codex CLI・App のターンやサブエージェントを含む)と、直近の親に紐付くセッションなしリクエストの紐付けは、シャットダウン時の最終的な affinity 保存が成功した場合、プロキシの正常な再起動後も最大24時間の非活動期間まで保持されることがあります。より深いセッションなしの連鎖と Codex App のメインログインへの紐付けはメモリ内にのみ残り、再起動後に再割り当てされます。eviction、アカウント削除、再ログイン、クラッシュ、affinity リセットではタスクが未紐付けになり得ます。出力前の **429/402** は使用量ベースの 切り替えがオフでも同じリクエストで適格な代替アカウントへ 1 回再試行できます。アカウント変更後も会話 コンテキストは保持・再生されますが、アカウント間の provider prompt cache 再利用は保証されません。 一時停止したアカウントと quota metadata は表示されたままですが、自動切り替え、再試行/failover 選択、cooldown 復旧プローブ、手動有効化の対象外です。 diff --git a/docs-site/src/content/docs/ko/reference/cli/providers-accounts.md b/docs-site/src/content/docs/ko/reference/cli/providers-accounts.md index 4355de7071b..8e77626c88f 100644 --- a/docs-site/src/content/docs/ko/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/ko/reference/cli/providers-accounts.md @@ -298,7 +298,7 @@ Codex JSON 행에는 등록된 `id`와 같은 `slotId`, 그리고 `native-main` `auto`는 수동 선택을 지워 풀이 다시 자체 전략으로 작업을 배치하게 합니다 — 단 id가 `auto`인 Codex 계정이 있으면 정확한 id 일치가 우선되며 `ocx account clear `는 항상 자동 선택을 복원합니다. Codex 계정은 id 대신 `ocx account alias`로 지정한 별칭으로도 가리킬 수 있으며, `priority`, `pause`, `resume`, `clear-cooldown`, `remove`, `alias`에서도 마찬가지입니다. Codex 계정에서 `auto`, `main`, `__main__`은 대소문자 구분 없이 예약어이므로 별칭으로 지정할 수 없습니다. OAuth 계정과 API 키의 표시 이름에는 기존 규칙이 그대로 적용됩니다. 기존 Codex 계정, OAuth 계정 또는 API key를 선택합니다. `openai`에서 `main`은 Codex App 로그인을 -선택합니다. Codex Pool 선택은 프로세스 로컬 affinity를 지우고 기존에 보이던 작업을 포함한 다음 요청부터 적용됩니다. 프록시 재시작이나 affinity eviction 뒤에도 작업이 바인딩 없는 상태가 될 수 있지만, 진행 중인 요청은 이미 확보한 계정을 유지합니다. 이 선택은 Pool 라우팅만 제어하며 Direct mode는 호출자 소유/native main credential을 계속 사용합니다. 사용량 기반 선제 전환, 401/403 재인증, 429/retry-after cooldown, 제외, 출력 전 429/402 실패 복구는 나중에 다른 적격 Pool 계정을 선택할 수 있습니다. 이러한 복구 경로는 사용량 기반 전환이 꺼져 있어도 동작합니다. 계정이 바뀌어도 OpenCodex는 대화 문맥을 재생하지만 프로바이더 측 prompt cache는 다시 예열해야 할 수 있습니다. +선택합니다. Codex Pool 선택은 affinity를 지우고 기존에 보이던 작업을 포함한 다음 요청부터 적용됩니다. 세션 ID가 있는 요청(일반적인 Codex CLI 및 App 턴과 서브에이전트 포함)이나 바로 위 부모에 연결된 세션 없는 요청의 바인딩은 종료 시 마지막 affinity 저장이 성공하면 프록시를 정상적으로 재시작해도 최대 24시간의 유휴 기간 동안 유지될 수 있습니다. 더 깊은 세션 없는 체인과 Codex App의 주 로그인에 대한 바인딩은 메모리에만 남으며 재시작 후 다시 배정됩니다. eviction, 계정 삭제, 재로그인, 충돌 또는 affinity 초기화로 작업이 바인딩 없는 상태가 될 수 있습니다. 진행 중인 요청은 이미 확보한 계정을 유지합니다. 이 선택은 Pool 라우팅만 제어하며 Direct mode는 호출자 소유/native main credential을 계속 사용합니다. 사용량 기반 선제 전환, 401/403 재인증, 429/retry-after cooldown, 제외, 출력 전 429/402 실패 복구는 나중에 다른 적격 Pool 계정을 선택할 수 있습니다. 이러한 복구 경로는 사용량 기반 전환이 꺼져 있어도 동작합니다. 계정이 바뀌어도 OpenCodex는 대화 문맥을 재생하지만 프로바이더 측 prompt cache는 다시 예열해야 할 수 있습니다. 알 수 없는 프로바이더나 id는 종료 코드 1입니다. `--json`은 다음을 반환합니다. **401/403**이 발생하면 해당 계정의 프로세스 로컬 affinity를 해제하고 재인증을 요구합니다. **429**에서는 `Retry-After`를 준수해 계정 cooldown을 시작하고 affinity를 해제한 뒤, diff --git a/docs-site/src/content/docs/ko/reference/configuration/providers.md b/docs-site/src/content/docs/ko/reference/configuration/providers.md index 4dfefc64d14..d59609c3db8 100644 --- a/docs-site/src/content/docs/ko/reference/configuration/providers.md +++ b/docs-site/src/content/docs/ko/reference/configuration/providers.md @@ -55,7 +55,7 @@ GUI에서 등록이나 OAuth 로그인을 마치면 Models 페이지로 이동 | `codexAccountPriorities?` | `Record` | — | Codex pool의 계정별 선택 순서. 계정 ID → `-100`부터 `100`까지의 정수이며 **값이 클수록 먼저** 쓰이고, 항목이 없으면 `0`입니다. 이는 eligibility 경계가 아니라 순서 경계입니다. 선택은 이미 적격한 계정들을 quota 여유가 남은 최상위 tier로 좁히고, 그 tier 안에서 `accountPoolStrategy`가 계정을 고릅니다. tier를 건너뛰는 경우는 그 구성원 전부가 자신의 0이 아닌 유효 임계값(계정별 재정의 또는 전역 기본값) 이상, cooldown, soft-avoid, 일시 중지 또는 재인증 대기일 때뿐이며, usage를 알 수 없다고 해서 tier가 소진되지는 않습니다. 순서는 부적격 계정을 선택 가능하게 만들지 않고, 이미 계정에 묶인 thread를 다시 bind하지도 않습니다. 메인 `__main__` 계정도 동일한 조건으로 참여하므로 Codex Desktop 로그인을 마지막에 쓰도록 둘 수 있습니다. 항목이 하나도 없으면 동작은 이전과 같습니다. map이 잘못된 경우 경고를 출력하고 순서 지정을 끕니다(config 복구는 하지 않습니다). `ocx account priority`와 Codex Auth 페이지에서 관리합니다. | | `autoSwitchThreshold?` | `number` | `80` | 사용량 기반 선제 전환 임계값입니다. `quota`는 바인딩 없는 작업의 다음 요청을 재평가할 수 있습니다. 바인딩된 작업은 기본값(`pool.cacheAffinity`)에서 이 임계값을 넘어도 계정을 유지하며, 해당 계정이 소진되었거나 더 이상 처리할 수 없을 때에만 떠나고, 그때도 실제 quota 여유가 있고 usage가 더 낮은 계정으로만 옮깁니다. `pool.cacheAffinity: false`로 두면 임계값에서 바인딩된 작업도 재평가합니다. `fill-first`는 바인딩 없는 작업 배정의 소진 기준으로만 사용하며, `round-robin`은 새/바인딩 없는 작업 배정에만 사용하며 임계값 미만인 적격 계정이 남아 있는 동안 유효 임계값 이상인 계정을 건너뛰고 이 때문에 바인딩된 작업을 옮기지 않습니다. 알려진 5시간, 주간, 30일 quota window 중 가장 높은 점수를 씁니다. `0`은 사용량 기반 전환만 끄며 바인딩 없는 작업 배정이나 실패 복구는 끄지 않습니다. | | `codexAccountAutoSwitchThresholds?` | `Record` | — | 계정별 `autoSwitchThreshold` 재정의입니다(계정 ID → `0`~`100` 정수). 항목이 없으면 전역 값을 상속하고, `0`은 해당 계정에서 시작하는 사용량 기반 전환만 끕니다. 메인 `__main__` 계정도 지원합니다. Codex Auth의 계정 카드에서 관리합니다. 재정의를 켜면 현재 전역 임계값을 고정된 계정별 값으로 복사합니다. `0`을 포함한 재정의 값은 이후 전역 값이 바뀌어도 우선합니다. 끄면 `threshold: null`을 보내 항목을 삭제하고 현재 전역 임계값과 향후 변경 사항을 상속하는 상태로 돌아갑니다. | -| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | 새 작업/바인딩 없는 Codex 요청의 계정 배정 전략입니다. `(parent thread id, quota scope)`의 live affinity가 없으면 바인딩 없는 요청이며, 프록시 재시작이나 affinity 초기화 뒤에는 기존에 보이던 작업도 바인딩이 없어질 수 있습니다. `quota`는 활성 계정이 없을 때 알려진 usage가 가장 낮은 적격 계정을 선택하고, 적격 활성 계정이 `autoSwitchThreshold` 미만이면 유지합니다. 임계값 도달 뒤에는 바인딩 없는 요청을 옮길 수 있습니다. 바인딩된 작업은 기본값에서 계정이 소진되었거나(알려진 usage 100%) 더 이상 처리할 수 없을 때까지 유지되며, 떠날 때는 실제 quota 여유가 있고 usage가 더 낮은 계정으로만 옮깁니다. 플래그를 끄면 임계값에서 바인딩된 작업의 다음 요청도 실제 quota 여유가 있고 usage가 더 낮은 적격 계정으로 옮길 수 있습니다. `round-robin`은 유효 `autoSwitchThreshold` 미만인 적격 계정에 바인딩 없는 요청을 균등 분배하고 모두 임계값 이상이면 모든 적격 계정에 분배하며, `fill-first`는 cooldown, 사용 불가 또는 drain threshold까지 활성 계정에 배정합니다. `reset-first`: 사용량 임계값 미만인 계정 중 다음 5시간·주간 초기화가 가장 가까운 계정을 고릅니다. 연결된 작업은 설정된 어피니티 정책을 따릅니다. 독립 모델 한도에는 사용량 순서를 적용합니다. 월간 초기화는 이 순서에 사용하지 않습니다. | +| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | 새 작업/바인딩 없는 Codex 요청의 계정 배정 전략입니다. `(parent thread id, quota scope)`의 live affinity가 없으면 바인딩 없는 요청입니다. 세션 ID가 있는 요청(일반적인 Codex CLI 및 App 턴과 서브에이전트 포함)이나 바로 위 부모에 연결된 세션 없는 요청의 바인딩은 종료 시 마지막 affinity 저장이 성공하면 프록시를 정상적으로 재시작해도 최대 24시간의 유휴 기간 동안 유지될 수 있습니다. 더 깊은 세션 없는 체인과 Codex App의 주 로그인에 대한 바인딩은 메모리에만 남으며 재시작 후 다시 배정됩니다. eviction, 계정 삭제, 재로그인, 충돌 또는 affinity 초기화로 작업이 바인딩 없는 상태가 될 수 있습니다. `quota`는 활성 계정이 없을 때 알려진 usage가 가장 낮은 적격 계정을 선택하고, 적격 활성 계정이 `autoSwitchThreshold` 미만이면 유지합니다. 임계값 도달 뒤에는 바인딩 없는 요청을 옮길 수 있습니다. 바인딩된 작업은 기본값에서 계정이 소진되었거나(알려진 usage 100%) 더 이상 처리할 수 없을 때까지 유지되며, 떠날 때는 실제 quota 여유가 있고 usage가 더 낮은 계정으로만 옮깁니다. 플래그를 끄면 임계값에서 바인딩된 작업의 다음 요청도 실제 quota 여유가 있고 usage가 더 낮은 적격 계정으로 옮길 수 있습니다. `round-robin`은 유효 `autoSwitchThreshold` 미만인 적격 계정에 바인딩 없는 요청을 균등 분배하고 모두 임계값 이상이면 모든 적격 계정에 분배하며, `fill-first`는 cooldown, 사용 불가 또는 drain threshold까지 활성 계정에 배정합니다. `reset-first`: 사용량 임계값 미만인 계정 중 다음 5시간·주간 초기화가 가장 가까운 계정을 고릅니다. 연결된 작업은 설정된 어피니티 정책을 따릅니다. 독립 모델 한도에는 사용량 순서를 적용합니다. 월간 초기화는 이 순서에 사용하지 않습니다. | | `pool.cacheAffinity?` | `boolean` | `true` | 바인딩된 Codex 스레드의 cache-affinity 순서입니다. `pool.kernel`과는 별개이며 기본값은 켜짐입니다. 잘못된 값은 켜진 것으로 읽습니다. live 바인딩이 quota 여유보다 우선하므로 `quota`는 사용량이 `autoSwitchThreshold`를 넘었다는 이유만으로 스레드를 옮기지 않습니다. 해당 계정이 일시 중지되었거나 사용할 수 없거나 실제로 소진된 경우(알려진 usage 100%)에는 떠나되, 실제 quota 여유가 있고 usage가 더 낮은 계정으로만 옮깁니다. `false`로 두면 임계값 재바인딩이 복원됩니다. affinity는 고정이 아니라 재정렬입니다. | | `accountPoolStickyLimit?` | `number` | `1` | 한 round-robin 선택이 다음으로 넘어가기 전에 유지하는 새 작업/바인딩 없는 작업 배정 수입니다. 카운터는 업스트림 성공 뒤가 아니라 작업을 바인딩할 때 증가합니다. 범위 1–100이며 `accountPoolStrategy`가 `round-robin`일 때만 적용됩니다. | | `upstreamFailoverThreshold?` | `number` | `3` | 연속된 일시적 실패가 이 횟수에 도달하면 이후 새 세션은 failover됩니다. `0`으로 두면 비활성화됩니다. 일반 Responses와 네이티브 compact 전송에서 입증된 연결 전 DNS/TCP 도달 불가 실패는 provider-host 범위로 기록되며 계정 상태, 계정 쿨다운, 스레드/세션 선호도, 활성 계정 선택 또는 Pool 라우팅에 영향을 주지 않고 이 임계값에도 집계되지 않습니다. | @@ -221,8 +221,7 @@ pool 계정 추가와 quota 갱신은 대시보드의 **Codex Auth** 페이지 구분됩니다. 바인딩된 작업은 보통 affinity를 유지합니다. 기본값(`pool.cacheAffinity`)에서는 바인딩된 계정이 소진되었거나 더 이상 처리할 수 없을 때까지 재바인딩을 미루고, 떠날 때는 실제 quota 여유가 있고 usage가 더 낮은 계정으로만 옮깁니다. 플래그를 끄면 `quota`가 사용량 임계값을 넘은 뒤 다음 요청에서 재바인딩할 수 있습니다. 일시 중지, cooldown, 재인증, 실패 처리도 -독립적으로 라우팅을 지우거나 바꿀 수 있습니다. 바인딩 없는 요청은 live 계정 바인딩이 없는 요청이며, 프록시 재시작이나 -affinity 초기화 뒤의 기존 작업도 포함될 수 있습니다. 출력 전 **429/402**는 사용량 기반 선제 +독립적으로 라우팅을 지우거나 바꿀 수 있습니다. 바인딩 없는 요청에는 live 계정 바인딩이 없습니다. 세션 ID가 있는 요청(일반적인 Codex CLI 및 App 턴과 서브에이전트 포함)이나 바로 위 부모에 연결된 세션 없는 요청의 바인딩은 종료 시 마지막 affinity 저장이 성공하면 프록시를 정상적으로 재시작해도 최대 24시간의 유휴 기간 동안 유지될 수 있습니다. 더 깊은 세션 없는 체인과 Codex App의 주 로그인에 대한 바인딩은 메모리에만 남으며 재시작 후 다시 배정됩니다. eviction, 계정 삭제, 재로그인, 충돌 또는 affinity 초기화로 작업이 바인딩 없는 상태가 될 수 있습니다. 출력 전 **429/402**는 사용량 기반 선제 전환이 꺼져 있어도 같은 요청에서 적격 대체 계정으로 한 번 재시도할 수 있습니다. 계정이 바뀌어도 대화 문맥은 보존·재생되지만 계정 간 프로바이더 측 prompt cache 재사용은 보장되지 않아 다시 예열해야 할 수 있습니다. diff --git a/docs-site/src/content/docs/reference/cli/providers-accounts.md b/docs-site/src/content/docs/reference/cli/providers-accounts.md index 3100c891189..092133e51de 100644 --- a/docs-site/src/content/docs/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/reference/cli/providers-accounts.md @@ -845,9 +845,8 @@ that state and still exits 0. `--json` returns: `auto` clears the manual selection so the pool places work by its own strategy again — unless a Codex account literally carries the id `auto`, which wins by exact-id precedence; `ocx account clear ` always restores automatic selection. Any Codex account can be named by the alias set with `ocx account alias` instead of its id; that holds for `priority`, `pause`, `resume`, `clear-cooldown`, `remove` and `alias` too. For Codex accounts, `auto`, `main` and `__main__` are reserved regardless of case and cannot be assigned as aliases. OAuth and API-key display names keep their existing rules. Selects an existing Codex account, OAuth account, or API key. For `openai`, `main` selects the Codex -App login. A Codex Pool selection clears process-local affinity and applies to the next request, -including one from an existing visible task; proxy restart or affinity eviction can also leave a task -unbound, while in-flight requests keep their captured account. This controls Pool routing only; +App login. A Codex Pool selection clears affinity and applies to the next request, +including one from an existing visible task. Bindings for requests with a session ID (including normal Codex CLI and App turns and subagents), or session-less requests anchored on their immediate parent, can survive a graceful proxy restart, for up to 24 hours idle, when the final affinity save at shutdown succeeds. Deeper session-less chains and bindings to the Codex App main login stay in memory only and are assigned again after restart; eviction, account removal, re-login, a crash, or an affinity reset can leave a task unbound, while in-flight requests keep their captured account. This controls Pool routing only; Direct mode keeps using the caller-owned/native main credential. Usage-based proactive switching, 401/403 reauthentication, 429/retry-after cooldowns, exclusion, and pre-output 429/402 failure recovery may later select another eligible Pool account. Those recovery paths remain active when diff --git a/docs-site/src/content/docs/reference/configuration/providers.md b/docs-site/src/content/docs/reference/configuration/providers.md index 7190882103a..7b739f5f860 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -125,7 +125,7 @@ separate. Full request URLs such as `/api/v1/responses` are not provider base UR | `codexAccountPriorityFailback?` | `boolean` | `false` | Opt-in return of ongoing Codex Pool tasks to a usable higher-priority account under the `quota` strategy. Requests trigger a background quota refresh at most once every five minutes, including failed refresh attempts. When recent quota observations show headroom, the next request may rebind even if its current account is below the threshold. This explicit preference can discard a warm prompt cache; it does not change default cache affinity. No requests means no polling. Manual pins, model access, cooldowns, pauses and reauthentication exclusions still apply; in-flight requests keep their captured account. Requires the current source account's effective threshold to be positive (an override of 0 disables it; a positive override works with global 0); exact account routes and Direct mode are unchanged. | | `autoSwitchThreshold?` | `number` | `80` | Usage threshold for placing new/unbound work. `quota` can re-evaluate unbound tasks on their next request once usage crosses this threshold. Bound tasks keep their account past the threshold by default (`pool.cacheAffinity`); they leave only when that account is exhausted or otherwise cannot serve, and then only for an account with genuine quota headroom and strictly lower usage. Set `pool.cacheAffinity: false` to re-evaluate bound tasks at this threshold, still only onto such a destination. `fill-first` uses it only as the drain point for unbound assignment; `round-robin` uses it only when placing new/unbound work: it skips accounts at or over their effective threshold while any eligible account is still under it, and never moves a bound task for it. The score uses the hottest known 5h, weekly, or 30d quota window. `0` disables usage-based proactive switching only, not unbound assignment or failure recovery. | | `codexAccountAutoSwitchThresholds?` | `Record` | — | Per-account overrides for `autoSwitchThreshold`: account id → integer from `0` to `100`. An absent entry inherits the global value; `0` disables usage-driven switching only when that account is the source. `quota` uses the current source account's effective threshold for bound-task re-evaluation and unbound switching. Fill-first drain and selection-order tier headroom are evaluated against each account's own effective threshold; main-account pins and subagent fallback also use the relevant account's effective threshold. Supports the main `__main__` account. A malformed map is ignored with a warning. Managed by each account card on the Codex Auth page; disabling an override removes its entry. Enabling the override copies the current global threshold into a fixed account value. The override, including `0`, takes precedence over later global changes. Disabling it sends `threshold: null`, removes the entry, and restores inheritance of the current global threshold and future global changes. | -| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | Assignment strategy for new/unbound Codex requests. A request is unbound when it has no live (parent thread id, quota scope) affinity; a visible existing task can become unbound after proxy restart or affinity reset. `quota` picks the lowest-usage eligible account when no active account exists, keeps an eligible active account below `autoSwitchThreshold`, and after the threshold may move an unbound request. Bound tasks follow `pool.cacheAffinity` (on by default): they stay until the account is exhausted (known usage at 100%) or otherwise cannot serve, and then may rebind only to an account with genuine quota headroom and strictly lower usage. Set the flag `false` to proactively rebind a bound task at the threshold, still only onto such a destination. `round-robin` distributes unbound requests evenly across eligible accounts still under their effective `autoSwitchThreshold`, and across all eligible accounts when every one is at or over it; `fill-first` keeps assigning unbound requests to the active account until cooldown, unavailability, or the configured drain threshold. `reset-first`: Prefer the nearest future 5-hour or weekly reset among accounts below the usage threshold. Bound tasks follow the configured affinity policy. Independent model quotas use quota ordering. Monthly resets do not determine this ordering. Under every strategy, a Claude Code turn that reaches a Codex account route through `/v1/messages` is bound by its Claude session: a caller `session_id`/`session-id` alias if present, else the metadata session, else `x-claude-code-session-id`; the binding is keyed to the admitted credential (or to local loopback use) with a server-held secret, so callers cannot share, guess or reuse another credential's binding. The binding is used only to choose the account; the headers sent upstream are unchanged. Spawn turns and turns that already carry `x-codex-parent-thread-id`, `thread-id` or a complete session/thread pair keep their own identity. A bound session normally stays on one account; the affinity and failure-recovery rules above can still move it. | +| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | Assignment strategy for new/unbound Codex requests. A request is unbound when it has no live (parent thread id, quota scope) affinity. Bindings for requests with a session ID (including normal Codex CLI and App turns and subagents), or session-less requests anchored on their immediate parent, can survive a graceful proxy restart, for up to 24 hours idle, when the final affinity save at shutdown succeeds. Deeper session-less chains and bindings to the Codex App main login stay in memory only and are assigned again after restart; eviction, account removal, re-login, a crash, or an affinity reset can leave a task unbound. `quota` picks the lowest-usage eligible account when no active account exists, keeps an eligible active account below `autoSwitchThreshold`, and after the threshold may move an unbound request. Bound tasks follow `pool.cacheAffinity` (on by default): they stay until the account is exhausted (known usage at 100%) or otherwise cannot serve, and then may rebind only to an account with genuine quota headroom and strictly lower usage. Set the flag `false` to proactively rebind a bound task at the threshold, still only onto such a destination. `round-robin` distributes unbound requests evenly across eligible accounts still under their effective `autoSwitchThreshold`, and across all eligible accounts when every one is at or over it; `fill-first` keeps assigning unbound requests to the active account until cooldown, unavailability, or the configured drain threshold. `reset-first`: Prefer the nearest future 5-hour or weekly reset among accounts below the usage threshold. Bound tasks follow the configured affinity policy. Independent model quotas use quota ordering. Monthly resets do not determine this ordering. Under every strategy, a Claude Code turn that reaches a Codex account route through `/v1/messages` is bound by its Claude session: a caller `session_id`/`session-id` alias if present, else the metadata session, else `x-claude-code-session-id`; the binding is keyed to the admitted credential (or to local loopback use) with a server-held secret, so callers cannot share, guess or reuse another credential's binding. The binding is used only to choose the account; the headers sent upstream are unchanged. Spawn turns and turns that already carry `x-codex-parent-thread-id`, `thread-id` or a complete session/thread pair keep their own identity. A bound session normally stays on one account; the affinity and failure-recovery rules above can still move it. | | `pool.cacheAffinity?` | `boolean` | `true` | Cache-affinity ordering for bound Codex threads, independent of `pool.kernel`. On by default; omitting the key or setting `true` keeps a bound task on its account until that account genuinely cannot serve. Only an explicit `false` restores threshold-based rebinding of bound tasks. A live binding outranks quota headroom: `quota` does not move the thread merely because usage crossed `autoSwitchThreshold`. The thread still leaves if that account cannot serve — paused, unusable, or genuinely exhausted (known usage at 100%) — and then only to an account with genuine quota headroom and strictly lower usage. Under either setting, an account with unknown usage is never chosen as a destination for a bound task, so when every account sits above the threshold the task stays put. Affinity is a reordering, not a pin. | | `pool.credentialGroups?` | `Array<{ id: string; credentials: string[]; note?: string }>` | `[]` | Accepted and validated, but not yet consumed by routing: declaring a group changes no routing decision until a consuming layer lands. Operator-declared quota domains: groups of credentials that demonstrably share one upstream usage limit. Members of one group count once toward available capacity, and a quota refusal inside a group is not answered by rotating to another member — the limit is the same, so the move would pay a cold prefix for zero new capacity. Declared groups speak only to quota; sharing a limit says nothing about prompt-cache compatibility, which is classified separately. Each member is written provider-qualified as `":"`, because a credential id means something only inside its provider; the provider segment accepts the usual aliases (`chatgpt:` and `codex:` both mean OpenAI). Group ids must be unique, `credentials` must be non-empty, and a credential may appear in at most one group — an ambiguous declaration is rejected on write and dropped with a warning on load rather than resolved by whichever group is listed first, since that would merge two unrelated quota domains. A malformed list costs only the grouping: `pool.kernel` and `pool.cacheAffinity` are preserved. Absent or empty means no declared grouping, so an unconfigured install behaves exactly as before. | | `accountPoolStickyLimit?` | `number` | `1` | New/unbound task assignments retained on one round-robin selection before advancing; the counter advances when a task is bound, not after an upstream success. Range 1–100. | @@ -1022,8 +1022,7 @@ Set `pool.cacheAffinity: false` to restore threshold rebinding of bound tasks, s a destination. Pause, cooldown, reauthentication, and quota refusals still release a live binding immediately. A transient-failure streak serves the request from another account while keeping the binding, and the task returns once that account serves again; after 10 minutes the binding is -released normally. An unbound request has no live account binding; this can include an existing visible -task after proxy restart or affinity reset. A pre-stream 429 or 402, or a 5xx response whose bounded +released normally. An unbound request has no live account binding. Bindings for requests with a session ID (including normal Codex CLI and App turns and subagents), or session-less requests anchored on their immediate parent, can survive a graceful proxy restart, for up to 24 hours idle, when the final affinity save at shutdown succeeds. Deeper session-less chains and bindings to the Codex App main login stay in memory only and are assigned again after restart; eviction, account removal, re-login, a crash, or an affinity reset can leave a task unbound. A pre-stream 429 or 402, or a 5xx response whose bounded body explicitly reports quota exhaustion, retries once on an eligible alternate account in the same request, even when usage-based proactive switching is off. The ordinary transient-5xx policy runs first, so a wrapped quota response may make up to three sends on the exhausted account before pool diff --git a/docs-site/src/content/docs/ru/reference/cli/providers-accounts.md b/docs-site/src/content/docs/ru/reference/cli/providers-accounts.md index 80861b69725..8adca4b9a4e 100644 --- a/docs-site/src/content/docs/ru/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/ru/reference/cli/providers-accounts.md @@ -211,7 +211,7 @@ credential'а, это состояние тоже печатается, но к `auto` снимает ручной выбор, и пул снова распределяет работу по своей стратегии — если только аккаунт Codex буквально не имеет id `auto`: точное совпадение id выигрывает, а `ocx account clear ` всегда восстанавливает автоматический выбор. Аккаунт Codex можно указать по псевдониму, заданному через `ocx account alias`, вместо id; это относится и к `priority`, `pause`, `resume`, `clear-cooldown`, `remove` и `alias`. Для аккаунтов Codex значения `auto`, `main` и `__main__` зарезервированы независимо от регистра и не могут назначаться как псевдонимы. Для отображаемых имён аккаунтов OAuth и API-ключей действуют прежние правила. Выбирает существующий аккаунт Codex, OAuth-аккаунт или API-ключ. Для `openai` значение `main` -выбирает вход Codex App. Выбор Codex Pool очищает process-local affinity и применяется к следующему запросу, включая запрос существующей видимой задачи; после перезапуска прокси или affinity eviction задача также может стать непривязанной, а выполняющиеся запросы сохраняют захваченный аккаунт. Это управляет только Pool routing; Direct mode продолжает использовать caller-owned/native main credential. Проактивное переключение по использованию, повторная аутентификация 401/403, cooldown 429/retry-after, исключение и восстановление после отказа 429/402 до вывода могут позже выбрать другой подходящий Pool-аккаунт. Эти пути восстановления остаются активными, когда переключение по использованию выключено. После смены аккаунта OpenCodex воспроизводит контекст разговора, но prompt cache провайдера может потребовать прогрева. Неизвестные провайдеры +выбирает вход Codex App. Выбор Codex Pool очищает affinity и применяется к следующему запросу, включая запрос существующей видимой задачи. Привязки запросов с идентификатором сессии (включая обычные ходы Codex CLI и App и субагентов) или запросов без сессии, опирающихся на непосредственного родителя, могут сохраниться после штатного перезапуска прокси при простое до 24 часов, если финальное сохранение affinity при завершении работы прошло успешно. Более глубокие цепочки без сессии и привязки к основному входу Codex App остаются только в памяти и назначаются заново после перезапуска; вытеснение, удаление аккаунта, повторный вход, сбой или сброс affinity могут оставить задачу без привязки, а выполняющиеся запросы сохраняют захваченный аккаунт. Это управляет только Pool routing; Direct mode продолжает использовать caller-owned/native main credential. Проактивное переключение по использованию, повторная аутентификация 401/403, cooldown 429/retry-after, исключение и восстановление после отказа 429/402 до вывода могут позже выбрать другой подходящий Pool-аккаунт. Эти пути восстановления остаются активными, когда переключение по использованию выключено. После смены аккаунта OpenCodex воспроизводит контекст разговора, но prompt cache провайдера может потребовать прогрева. Неизвестные провайдеры или id завершаются с кодом 1. `--json` возвращает: При **401/403** локальная для процесса привязка к аккаунту сбрасывается и требуется повторная аутентификация. При **429** учитывается `Retry-After`, для аккаунта запускается cooldown, привязка сбрасывается, diff --git a/docs-site/src/content/docs/ru/reference/configuration/providers.md b/docs-site/src/content/docs/ru/reference/configuration/providers.md index 22a4986e82d..4ffac816f4d 100644 --- a/docs-site/src/content/docs/ru/reference/configuration/providers.md +++ b/docs-site/src/content/docs/ru/reference/configuration/providers.md @@ -56,7 +56,7 @@ ocx models provider openrouter on | `codexAccountPriorities?` | `Record` | — | Порядок выбора для каждого аккаунта пула Codex: id аккаунта → целое число от `-100` до `100`, **больше — используется раньше**, отсутствие означает `0`. Это граница порядка, а не пригодности: выбор сужает уже подходящие аккаунты до самого высокого уровня, у которого ещё есть запас квоты, а внутри этого уровня аккаунт выбирает `accountPoolStrategy`. Уровень пропускается, только когда все его аккаунты достигли собственного ненулевого эффективного порога (переопределение аккаунта или глобальное значение), находятся в cooldown, под soft-avoid, на паузе или требуют повторной аутентификации; неизвестный usage никогда не исчерпывает уровень. Порядок не делает выбираемым непригодный аккаунт и не перепривязывает поток, у которого аккаунт уже есть. Основной аккаунт `__main__` участвует на равных — именно так логин Codex Desktop можно оставить на самый конец. Без записей поведение остаётся прежним. Некорректная map игнорируется с предупреждением в консоли (порядок отключается, восстановление config не запускается). Управляется через `ocx account priority` и страницу Codex Auth. | | `autoSwitchThreshold?` | `number` | `80` | Порог проактивного переключения по использованию. `quota` может повторно оценить следующий непривязанный запрос. Привязанная задача по умолчанию (`pool.cacheAffinity`) сохраняет аккаунт после порога, пока он не исчерпан и ещё может обслуживать запрос, и переносится только на аккаунт со строго меньшим usage и реальным запасом квоты. Установите `pool.cacheAffinity: false`, чтобы повторно оценивать привязанные задачи на этом пороге. `fill-first` использует его только как точку исчерпания для непривязанных назначений; `round-robin` применяет его только к новым назначениям: пока есть подходящий аккаунт ниже своего порога, аккаунты на пороге или выше пропускаются; привязанная задача из-за этого не переносится. Оценка берёт самое горячее из окон 5 часов, недели и 30 дней. `0` отключает только переключение по использованию, но не назначение непривязанных задач и не восстановление после сбоев. | | `codexAccountAutoSwitchThresholds?` | `Record` | — | Переопределения `autoSwitchThreshold` по аккаунтам: id → целое число `0`–`100`. Без записи наследуется глобальное значение; `0` отключает только переключения по использованию с этого аккаунта. Поддерживается основной аккаунт `__main__`. Управляется в карточке аккаунта на странице Codex Auth. Включение переопределения копирует текущий глобальный порог в фиксированное значение аккаунта. Переопределение, включая `0`, имеет приоритет и после изменения глобального порога. Отключение отправляет `threshold: null`, удаляет запись и восстанавливает наследование текущего глобального порога и его будущих изменений. | -| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | Стратегия назначения для новых/непривязанных запросов Codex. Запрос непривязан, если у него нет live affinity `(parent thread id, quota scope)`; видимая существующая задача может стать непривязанной после перезапуска прокси или сброса affinity. `quota` выбирает подходящий аккаунт с наименьшим известным usage, когда активного аккаунта нет, сохраняет подходящий активный аккаунт ниже `autoSwitchThreshold`, а после порога может перевести непривязанный запрос. Привязанные задачи следуют `pool.cacheAffinity` (по умолчанию включён): они остаются, пока аккаунт не исчерпан (известный usage 100%) или не может обслуживать запрос, и тогда переносятся только на аккаунт со строго меньшим usage и реальным запасом квоты. Установите флаг в `false`, чтобы на пороге проактивно перепривязать задачу к подходящему аккаунту с меньшим usage, всё равно только при той же проверке назначения. `round-robin` распределяет непривязанные запросы равномерно между подходящими аккаунтами ниже их эффективного `autoSwitchThreshold`, а если все достигли порога — между всеми подходящими; `fill-first` назначает их активному аккаунту до cooldown, недоступности или порога исчерпания. `reset-first`: Среди аккаунтов ниже порога выбирается ближайший сброс 5-часовой или недельной квоты. Привязанные задачи следуют настроенной политике привязки. Независимые квоты моделей упорядочиваются по использованию. Месячный сброс не определяет этот порядок. | +| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | Стратегия назначения для новых/непривязанных запросов Codex. Запрос непривязан, если у него нет live affinity `(parent thread id, quota scope)`. Привязки запросов с идентификатором сессии (включая обычные ходы Codex CLI и App и субагентов) или запросов без сессии, опирающихся на непосредственного родителя, могут сохраниться после штатного перезапуска прокси при простое до 24 часов, если финальное сохранение affinity при завершении работы прошло успешно. Более глубокие цепочки без сессии и привязки к основному входу Codex App остаются только в памяти и назначаются заново после перезапуска; вытеснение, удаление аккаунта, повторный вход, сбой или сброс affinity могут оставить задачу без привязки. `quota` выбирает подходящий аккаунт с наименьшим известным usage, когда активного аккаунта нет, сохраняет подходящий активный аккаунт ниже `autoSwitchThreshold`, а после порога может перевести непривязанный запрос. Привязанные задачи следуют `pool.cacheAffinity` (по умолчанию включён): они остаются, пока аккаунт не исчерпан (известный usage 100%) или не может обслуживать запрос, и тогда переносятся только на аккаунт со строго меньшим usage и реальным запасом квоты. Установите флаг в `false`, чтобы на пороге проактивно перепривязать задачу к подходящему аккаунту с меньшим usage, всё равно только при той же проверке назначения. `round-robin` распределяет непривязанные запросы равномерно между подходящими аккаунтами ниже их эффективного `autoSwitchThreshold`, а если все достигли порога — между всеми подходящими; `fill-first` назначает их активному аккаунту до cooldown, недоступности или порога исчерпания. `reset-first`: Среди аккаунтов ниже порога выбирается ближайший сброс 5-часовой или недельной квоты. Привязанные задачи следуют настроенной политике привязки. Независимые квоты моделей упорядочиваются по использованию. Месячный сброс не определяет этот порядок. | | `pool.cacheAffinity?` | `boolean` | `true` | Порядок cache-affinity для привязанных потоков Codex, независимый от `pool.kernel`. По умолчанию включён; пропуск ключа или `true` сохраняет привязку, а любое значение кроме `false` читается как включённое. Живая привязка важнее запаса квоты: `quota` не переносит поток только потому, что usage пересёк `autoSwitchThreshold` — перенос живого разговора сбрасывает изолированный по аккаунту prompt cache. Поток всё равно уходит, если аккаунт не может обслуживать запрос — на паузе, непригоден, исключён планом, с недействительными credential'ами, со сменённой generation, с истёкшим TTL, при отказе квоты 429/402 или реально исчерпан (известный usage 100%) — и только на аккаунт со строго меньшим usage и реальным запасом квоты. Аккаунт с неизвестным usage никогда не выбирается как назначение для привязанной задачи. Если все аккаунты выше порога, привязанная задача остаётся: лучшего назначения нет. `false` возвращает перепривязку по порогу, всё равно только при той же проверке назначения. Affinity меняет порядок, а не закрепляет учётные данные. | | `accountPoolStickyLimit?` | `number` | `1` | Число назначений новых/непривязанных задач на одном выборе round-robin перед переходом дальше. Счётчик растёт при привязке задачи, а не после успеха upstream. Диапазон 1–100; только при `accountPoolStrategy` = `round-robin`. | | `upstreamFailoverThreshold?` | `number` | `3` | Сколько подряд transient failure допустить, прежде чем новые сессии начнут делать failover. `0` отключает эту логику. Для обычных Responses-запросов и нативных compact-отправок доказанные ошибки доступности DNS/TCP до соединения учитываются на уровне пары «провайдер, хост» и не влияют на здоровье аккаунта, кулдауны аккаунта, привязку потока/сессии, выбор активного аккаунта или маршрутизацию пула, а также не учитываются в этом пороге. | @@ -249,8 +249,7 @@ redirect'ов для обычных provider-request'ов реализована защищённом хранилище учётных данных аккаунтов Codex. Pool routing разделяет назначение новых/непривязанных задач, проактивное переключение по использованию и восстановление после сбоев. Привязанная задача обычно сохраняет affinity. По умолчанию (`pool.cacheAffinity`) эта перепривязка ждёт, пока -привязанный аккаунт не будет исчерпан или не сможет обслуживать запрос, и тогда только на аккаунт со строго меньшим usage и реальным запасом квоты. Установите `pool.cacheAffinity: false`, чтобы `quota` перепривязывала задачу при следующем запросе после превышения порога, всё равно только при той же проверке назначения. Отказ квоты 429/402, пауза, инвалидация credential'ов и истечение TTL по-прежнему снимают привязку сразу; серия временных сбоев (5xx и другие не-квотные ошибки) обслуживает запрос на другом аккаунте, не удаляя живую привязку. Непривязанным может стать и существующая задача -после перезапуска прокси или сброса affinity. Отказ **429/402** до вывода допускает одну попытку +привязанный аккаунт не будет исчерпан или не сможет обслуживать запрос, и тогда только на аккаунт со строго меньшим usage и реальным запасом квоты. Установите `pool.cacheAffinity: false`, чтобы `quota` перепривязывала задачу при следующем запросе после превышения порога, всё равно только при той же проверке назначения. Отказ квоты 429/402, пауза, инвалидация credential'ов и истечение TTL по-прежнему снимают привязку сразу; серия временных сбоев (5xx и другие не-квотные ошибки) обслуживает запрос на другом аккаунте, не удаляя живую привязку. Привязки запросов с идентификатором сессии (включая обычные ходы Codex CLI и App и субагентов) или запросов без сессии, опирающихся на непосредственного родителя, могут сохраниться после штатного перезапуска прокси при простое до 24 часов, если финальное сохранение affinity при завершении работы прошло успешно. Более глубокие цепочки без сессии и привязки к основному входу Codex App остаются только в памяти и назначаются заново после перезапуска; вытеснение, удаление аккаунта, повторный вход, сбой или сброс affinity могут оставить задачу без привязки. Отказ **429/402** до вывода допускает одну попытку на подходящем альтернативном аккаунте даже при выключенном переключении по использованию. Контекст разговора сохраняется и воспроизводится, но prompt cache провайдера между аккаунтами может не переиспользоваться и потребовать прогрева. diff --git a/docs-site/src/content/docs/tr/reference/cli/providers-accounts.md b/docs-site/src/content/docs/tr/reference/cli/providers-accounts.md index eec9aabd8d2..f0cec9d17ac 100644 --- a/docs-site/src/content/docs/tr/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/tr/reference/cli/providers-accounts.md @@ -243,10 +243,8 @@ yine de 0 ile çıkar. `--json` şunu döndürür: `auto` elle yapılan seçimi temizler; havuz işi yeniden kendi stratejisiyle yerleştirir — ancak id'si `auto` olan bir Codex hesabı varsa tam id eşleşmesi kazanır ve `ocx account clear ` her zaman otomatik seçimi geri yükler. Bir Codex hesabı, id yerine `ocx account alias` ile verilen takma adla da belirtilebilir; bu `priority`, `pause`, `resume`, `clear-cooldown`, `remove` ve `alias` için de geçerlidir. Codex hesaplarında `auto`, `main` ve `__main__` büyük/küçük harf fark etmeksizin ayrılmış sözcüklerdir ve takma ad olarak atanamaz. OAuth hesaplarının ve API anahtarlarının görünen adları için mevcut kurallar geçerlidir. Mevcut bir Codex hesabını, OAuth hesabını veya API anahtarını seçer. `openai` -için `main` Codex App girişini seçer. Bir Codex Havuzu seçimi süreç içi yerel -bağlılığı temizler ve mevcut görünür bir görevden gelen istekler de dahil olmak -üzere bir sonraki isteğe uygulanır; proxy yeniden başlatması veya bağlılık -çıkarma işlemi de bir görevi bağımsız bırakabilirken devam eden istekler +için `main` Codex App girişini seçer. Bir Codex Havuzu seçimi bağlılığı temizler ve mevcut görünür bir görevden gelen istekler de dahil olmak +üzere bir sonraki isteğe uygulanır. Oturum kimliği taşıyan isteklerin (normal Codex CLI ve App turları ile alt ajanlar dahil) veya doğrudan üst öğesine bağlanan oturumsuz isteklerin bağları, kapatma sırasında son bağlılık kaydı başarılı olursa proxy düzgün yeniden başlatıldığında 24 saate kadar boşta kalma süresiyle korunabilir. Daha derin oturumsuz zincirler ve Codex App ana girişine ait bağlar yalnızca bellekte kalır ve yeniden başlatmadan sonra yeniden atanır; çıkarma, hesap silme, yeniden giriş, çökme veya bağlılık sıfırlaması bir görevi bağımsız bırakabilirken devam eden istekler yakaladıkları hesabı tutar. Bu yalnızca Havuz yönlendirmesini denetler; Direct modu arayana ait/yerel ana kimlik bilgisini kullanmaya devam eder. Kullanıma dayalı proaktif geçiş, 401/403 yeniden kimlik doğrulaması, 429/retry-after diff --git a/docs-site/src/content/docs/tr/reference/configuration/providers.md b/docs-site/src/content/docs/tr/reference/configuration/providers.md index 1e155303344..5c9a70f54a1 100644 --- a/docs-site/src/content/docs/tr/reference/configuration/providers.md +++ b/docs-site/src/content/docs/tr/reference/configuration/providers.md @@ -57,7 +57,7 @@ Arayüzde kayıt veya OAuth girişi tamamlanınca Models sayfasını açan bir b | `activeCodexAccountPinned?` | `string` | — | Operatörün en son elle seçtiği hesap kimliği. Ayarlandığı sürece, pin tükenme, hariç tutma, silme veya açık bir yük devretme/yükseltme ile serbest bırakılana kadar daha yüksek bir `codexAccountPriorities` katmanı onu öncelikleyemez. Sınırlı katman içindeki sıradan round-robin hareketi onu serbest bırakmaz. Herhangi bir `codexAccountPriorities` girdisi yazmak da pini serbest bırakır, böylece bir sıra var olmadan önce yapılan bir pin daha sonra ayarlanan bir pinin önüne geçemez. `GET /api/codex-auth/active`, hem geçerli hesabın sabitlenip sabitlenmediğini (`pinned`) hem de tavanı taşıyan hesabı (`pinnedAccountId`) bildirir. | | `autoSwitchThreshold?` | `number` | `80` | Proaktif geçiş için kullanım eşiği. `quota`, bağımsız görevlerin bir sonraki isteğini yeniden değerlendirebilir. Bağlı görevler varsayılan olarak (`pool.cacheAffinity`) eşiğin ötesinde hesabını korur; hesap tükenene veya hizmet veremez hale gelene kadar kalır ve o zaman yalnızca kullanımı kesin olarak daha düşük ve gerçek kota payı olan bir hesaba geçer. `pool.cacheAffinity: false` ile bağlı görevler de bu eşikte yeniden değerlendirilir. `fill-first` bunu yalnızca bağımsız atama için tükenme noktası olarak kullanır; `round-robin` bunu yalnızca yeni/bağımsız atamalarda kullanır: etkin eşiğinin altında uygun bir hesap kaldıkça eşiğine ulaşmış veya aşmış hesapları atlar ve bağlı bir görevi bu nedenle taşımaz. Puan, bilinen en sıcak 5 saatlik, haftalık veya 30 günlük kota penceresini kullanır. `0`, yalnızca kullanıma dayalı proaktif geçişi devre dışı bırakır, bağımsız atamayı veya arıza kurtarmayı devre dışı bırakmaz. | | `codexAccountAutoSwitchThresholds?` | `Record` | — | Hesap başına `autoSwitchThreshold` geçersiz kılmaları: hesap kimliği → `0`–`100` tam sayısı. Kayıt yoksa genel değer devralınır; `0` yalnızca bu hesaptan kullanıma dayalı geçişi kapatır. Ana `__main__` hesabı desteklenir. Codex Auth hesap kartından yönetilir. Hesaba özel değeri etkinleştirmek, mevcut genel eşiği sabit bir hesap değerine kopyalar. `0` dahil bu değer, genel eşik daha sonra değişse de önceliğini korur. Devre dışı bırakmak `threshold: null` gönderir, kaydı siler ve mevcut genel eşikle gelecekteki değişikliklerini devralmayı yeniden etkinleştirir. | -| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | Yeni/bağımsız Codex istekleri için atama stratejisi. Bir istek, canlı (üst iş parçacığı kimliği, kota kapsamı) bağlılığı olmadığında bağımsızdır; görünür mevcut bir görev, proxy yeniden başlatmasından veya bağlılık sıfırlamasından sonra bağımsız hale gelebilir. `quota`, aktif bir hesap olmadığında en düşük kullanımlı uygun hesabı seçer, `autoSwitchThreshold` altında uygun bir aktif hesabı tutar ve eşikten sonra bağımsız bir isteği taşıyabilir. Bağlı görevler `pool.cacheAffinity`'yi izler (varsayılan açık): hesap tükenene (bilinen kullanım %100) veya hizmet veremez hale gelene kadar kalır ve o zaman yalnızca kullanımı kesin olarak daha düşük ve gerçek kota payı olan bir hesaba geçer. Bayrağı `false` yapınca bağlı bir görev eşiğinde proaktif olarak daha düşük kullanımlı uygun bir hesaba yeniden bağlanabilir; hedef kısıtı yine geçerlidir. `round-robin`, bağımsız istekleri etkin `autoSwitchThreshold` altında kalan uygun hesaplara eşit dağıtır; hepsi eşiğe ulaşmış veya aşmışsa tüm uygun hesaplara dağıtır; `fill-first`, soğuma, kullanılamama veya yapılandırılmış tükenme eşiğine kadar bağımsız istekleri aktif hesaba atamaya devam eder. `reset-first`: Eşiğin altındaki hesaplar arasından sonraki 5 saatlik veya haftalık sıfırlaması en yakın olanı seçer. Bağlı görevler yapılandırılmış bağlılık politikasını izler. Bağımsız model kotaları kullanıma göre sıralanır. Aylık sıfırlamalar bu sıralamayı belirlemez. | +| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | Yeni/bağımsız Codex istekleri için atama stratejisi. Bir istek, canlı (üst iş parçacığı kimliği, kota kapsamı) bağlılığı olmadığında bağımsızdır. Oturum kimliği taşıyan isteklerin (normal Codex CLI ve App turları ile alt ajanlar dahil) veya doğrudan üst öğesine bağlanan oturumsuz isteklerin bağları, kapatma sırasında son bağlılık kaydı başarılı olursa proxy düzgün yeniden başlatıldığında 24 saate kadar boşta kalma süresiyle korunabilir. Daha derin oturumsuz zincirler ve Codex App ana girişine ait bağlar yalnızca bellekte kalır ve yeniden başlatmadan sonra yeniden atanır; çıkarma, hesap silme, yeniden giriş, çökme veya bağlılık sıfırlaması bir görevi bağımsız bırakabilir. `quota`, aktif bir hesap olmadığında en düşük kullanımlı uygun hesabı seçer, `autoSwitchThreshold` altında uygun bir aktif hesabı tutar ve eşikten sonra bağımsız bir isteği taşıyabilir. Bağlı görevler `pool.cacheAffinity`'yi izler (varsayılan açık): hesap tükenene (bilinen kullanım %100) veya hizmet veremez hale gelene kadar kalır ve o zaman yalnızca kullanımı kesin olarak daha düşük ve gerçek kota payı olan bir hesaba geçer. Bayrağı `false` yapınca bağlı bir görev eşiğinde proaktif olarak daha düşük kullanımlı uygun bir hesaba yeniden bağlanabilir; hedef kısıtı yine geçerlidir. `round-robin`, bağımsız istekleri etkin `autoSwitchThreshold` altında kalan uygun hesaplara eşit dağıtır; hepsi eşiğe ulaşmış veya aşmışsa tüm uygun hesaplara dağıtır; `fill-first`, soğuma, kullanılamama veya yapılandırılmış tükenme eşiğine kadar bağımsız istekleri aktif hesaba atamaya devam eder. `reset-first`: Eşiğin altındaki hesaplar arasından sonraki 5 saatlik veya haftalık sıfırlaması en yakın olanı seçer. Bağlı görevler yapılandırılmış bağlılık politikasını izler. Bağımsız model kotaları kullanıma göre sıralanır. Aylık sıfırlamalar bu sıralamayı belirlemez. | | `pool.cacheAffinity?` | `boolean` | `true` | Bağlı Codex iş parçacıkları için önbellek bağlılığı sıralaması; `pool.kernel`'dan bağımsızdır. Varsayılan olarak açıktır; anahtarı atlamak veya `true` vermek bağlamayı korur ve `false` dışındaki bir değer açık okunur. Canlı bağlama kota payından öndedir: `quota`, kullanımın `autoSwitchThreshold`'u geçmesi nedeniyle iş parçacığını taşımaz, çünkü canlı bir konuşmayı taşımak hesaba özel istem önbelleğini atar. Hesap duraklatılmış, kullanılamaz, plandan dışlanmış, kimlik bilgisi geçersiz, generation değişmiş, TTL dolmuş, 429/402 kota reddi almış veya gerçekten tükenmişse (bilinen kullanım %100) iş parçacığı yine ayrılır ve yalnızca kullanımı kesin olarak daha düşük ve gerçek kota payı olan bir hesaba geçer. Kullanımı bilinmeyen bir hesap bağlı bir görev için hedef olarak asla seçilmez. Tüm hesaplar eşiğin üzerindeyse bağlı görev yerinde kalır; daha iyi bir hedef yoktur. `false` eşiğe göre yeniden bağlamayı geri getirir; hedef kısıtı yine geçerlidir. Bağlılık bir sabitleme değil yeniden sıralamadır. | | `accountPoolStickyLimit?` | `number` | `1` | İlerlemeden önce bir round-robin seçiminde tutulan yeni/bağımsız görev atamaları; sayaç yukarı akış başarısından sonra değil, bir görev bağlandığında ilerler. Aralık 1–100. | | `upstreamFailoverThreshold?` | `number` | `3` | Gelecekteki yeni oturumların yük devretmesinden önceki ardışık geçici arızalar. Devre dışı bırakmak için `0` ayarlayın. Düzenli Responses ve yerel sıkıştırma gönderimleri için kanıtlanmış bağlantı öncesi DNS/TCP erişilebilirlik arızaları sağlayıcı-ana bilgisayar düzeyinde izlenir: hesap sağlığını, hesap soğuma sürelerini, iş parçacığı/oturum bağlılığını, aktif hesap seçimini veya Havuz yönlendirmesini asla etkilemez ve bu eşiğe asla sayılmaz. | @@ -253,8 +253,7 @@ yönlendirmesi yeni/bağımsız atamayı, kullanıma dayalı proaktif geçişi v kurtarmayı ayırır. Bağlı bir görev normalde bağlılığı korur. Varsayılan olarak (`pool.cacheAffinity`) bu yeniden bağlama, bağlı hesap tükenene veya hizmet veremez hale gelene kadar bekler ve o zaman yalnızca kullanımı kesin olarak daha düşük ve gerçek kota payı olan bir hesaba geçer. `pool.cacheAffinity: false` ile `quota`, kullanım eşiği aşıldıktan sonraki isteğinde onu yeniden bağlayabilir; hedef kısıtı yine geçerlidir. 429/402 kota reddi, duraklatma, kimlik bilgisi geçersizliği ve TTL dolması bağlamayı hemen serbest bırakır; geçici arıza serisi (5xx ve diğer kota dışı arızalar) isteği başka bir hesapta sunar ama canlı bağlamayı silmez. Bağımsız bir -isteğin canlı hesap bağlaması yoktur; bu, proxy yeniden başlatmasından veya -bağlılık sıfırlamasından sonra mevcut görünür bir görevi içerebilir. Akış öncesi +isteğin canlı hesap bağlaması yoktur. Oturum kimliği taşıyan isteklerin (normal Codex CLI ve App turları ile alt ajanlar dahil) veya doğrudan üst öğesine bağlanan oturumsuz isteklerin bağları, kapatma sırasında son bağlılık kaydı başarılı olursa proxy düzgün yeniden başlatıldığında 24 saate kadar boşta kalma süresiyle korunabilir. Daha derin oturumsuz zincirler ve Codex App ana girişine ait bağlar yalnızca bellekte kalır ve yeniden başlatmadan sonra yeniden atanır; çıkarma, hesap silme, yeniden giriş, çökme veya bağlılık sıfırlaması bir görevi bağımsız bırakabilir. Akış öncesi bir 429 veya 402, kullanıma dayalı proaktif geçiş kapalı olsa bile aynı istekte uygun alternatif bir hesapta bir kez yeniden dener. Hesap değişiklikleri görüşme bağlamını korur ve yeniden oynatır, ancak hesaplar arasında sağlayıcı tarafı diff --git a/docs-site/src/content/docs/zh-cn/reference/cli/providers-accounts.md b/docs-site/src/content/docs/zh-cn/reference/cli/providers-accounts.md index 6c7a259ad2c..1c3f0893a21 100644 --- a/docs-site/src/content/docs/zh-cn/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/zh-cn/reference/cli/providers-accounts.md @@ -200,7 +200,7 @@ OAuth 账号会显示为 `Account N`,而 plan/label 列会在 plan、屏蔽后 `auto` 会清除手动选择,让 Pool 重新按自身策略分配工作 — 但如果某个 Codex 账号的 id 恰为 `auto`,则精确 id 匹配优先;`ocx account clear ` 始终恢复自动选择。Codex 账号可以用 `ocx account alias` 设置的别名代替 id 来指定;`priority`、`pause`、`resume`、`clear-cooldown`、`remove` 和 `alias` 同样如此。对于 Codex 账号,`auto`、`main` 和 `__main__` 为保留字(不区分大小写),不能设为别名。OAuth 账号和 API 密钥的显示名称仍遵循原有规则。 选择已有的 Codex 账号、OAuth 账号或 API key。对 `openai` 而言,`main` 选择 Codex App 登录。 -Codex Pool 选择会清除进程本地 affinity,并从下一次请求开始生效,包括已有可见任务的请求;代理重启或 affinity eviction 后,任务也可能变为未绑定,但进行中的请求保留已捕获账号。此选择只控制 Pool routing;Direct mode 继续使用 caller-owned/native main credential。基于用量的主动切换、401/403 重新认证、429/retry-after cooldown、排除,以及输出前 429/402 故障恢复之后仍可能选择其他合格 Pool 账号。这些恢复路径在关闭基于用量的切换时仍然有效。账号变化后 OpenCodex 会重放对话上下文,但 provider prompt cache 可能需要重新预热。未知 provider 或 id 返回退出码 1。`--json` 返回: +Codex Pool 选择会清除 affinity,并从下一次请求开始生效,包括已有可见任务的请求;带会话 ID 的请求(包括常规 Codex CLI 和 App 轮次及子代理),或锚定到直接父任务的无会话请求,其绑定在关闭时最后一次 affinity 保存成功的情况下,代理正常重启后可保留,空闲时间最长为 24 小时。更深层的无会话链和 Codex App 主登录的绑定仅保存在内存中,重启后会重新分配;驱逐、账号删除、重新登录、崩溃或 affinity 重置仍可能使任务变为未绑定,但进行中的请求保留已捕获账号。此选择只控制 Pool routing;Direct mode 继续使用 caller-owned/native main credential。基于用量的主动切换、401/403 重新认证、429/retry-after cooldown、排除,以及输出前 429/402 故障恢复之后仍可能选择其他合格 Pool 账号。这些恢复路径在关闭基于用量的切换时仍然有效。账号变化后 OpenCodex 会重放对话上下文,但 provider prompt cache 可能需要重新预热。未知 provider 或 id 返回退出码 1。`--json` 返回: 遇到 **401/403** 时,App 登录会清除该账户的进程内 affinity 并要求重新认证。 遇到 **429** 时,它会遵循 `Retry-After`、启动账户 cooldown、清除 affinity, 并可将请求切换到另一个符合条件的 Pool 账户。即使 `autoSwitchThreshold: 0`, diff --git a/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md b/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md index 49c984a6a29..41890df5aa3 100644 --- a/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md +++ b/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md @@ -55,7 +55,7 @@ ocx models provider openrouter on | `codexAccountPriorities?` | `Record` | — | Codex pool 各账号的选择顺序:账号 ID → `-100` 到 `100` 的整数,**数值越大越先使用**,未设置即为 `0`。这是顺序边界而非资格边界:选择会把已经合格的账号收窄到仍有 quota 余量的最高 tier,再由 `accountPoolStrategy` 在该 tier 内挑选。只有当某个 tier 的所有成员都达到各自非零的有效阈值(账号覆盖值,未设置则使用全局值)、处于 cooldown、被 soft-avoid、已暂停或需要重新认证时,该 tier 才会被跳过;usage 未知不会让 tier 耗尽。顺序不会让不合格的账号变得可选,也不会重新绑定已经绑定账号的 thread。主账号 `__main__` 同样参与排序,因此可以让 Codex Desktop 登录账号最后才被用到。没有任何条目时,行为与以往完全一致。映射格式非法时会打印警告并关闭排序(不会触发 config 修复)。可通过 `ocx account priority` 和 Codex Auth 页面管理。 | | `autoSwitchThreshold?` | `number` | `80` | 基于用量的主动切换阈值。`quota` 可在下一次请求中重新评估未绑定任务。已绑定任务默认(`pool.cacheAffinity`)在越过阈值后仍保留账号,直到该账号耗尽或无法继续服务,并且只改绑到确有额度余量且 usage 严格更低的账号。将 `pool.cacheAffinity` 设为 `false` 才会在该阈值重新评估已绑定任务。`fill-first` 仅把它用作未绑定分配的耗尽点;`round-robin` 仅在新建/未绑定任务分配时使用它:只要仍有低于自身有效阈值的合格账号,就跳过达到或超过阈值的账号,且不会因此移动已绑定任务。分数取已知 5 小时、周或 30 天 quota window 的最高值。`0` 只关闭基于用量的主动切换,不关闭未绑定任务分配或故障恢复。 | | `codexAccountAutoSwitchThresholds?` | `Record` | — | 各账号对 `autoSwitchThreshold` 的覆盖:账号 ID → `0`–`100` 的整数。没有条目时继承全局值;`0` 只关闭从该账号发起的基于用量的切换。支持主账号 `__main__`。可在 Codex Auth 的账号卡片中管理。 启用覆盖时,会将当前全局阈值复制为固定的账号值。覆盖值(包括 `0`)在之后修改全局阈值时仍优先。禁用时发送 `threshold: null`,删除条目,并恢复继承当前全局阈值及其未来的更改。 | -| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | 新建/未绑定 Codex 请求的分配策略。没有 live `(parent thread id, quota scope)` affinity 的请求属于未绑定;代理重启或 affinity 重置后,已有可见任务也可能未绑定。`quota` 在没有活跃账号时选择已知 usage 最低的合格账号;活跃账号合格且低于 `autoSwitchThreshold` 时继续使用;达到阈值后,可把未绑定请求切换到 usage 更低的合格账号。已绑定任务默认会保留到账号耗尽(已知 usage 为 100%)或无法继续服务,改绑时只前往确有额度余量且 usage 严格更低的账号。关闭该标志后,也可在该阈值把已绑定任务的下一次请求改绑到确有额度余量且 usage 严格更低的账号。`round-robin` 在有效 `autoSwitchThreshold` 以下的合格账号间均匀分配未绑定请求,若全部达到或超过阈值则在所有合格账号间分配;`fill-first` 在 cooldown、不可用或耗尽阈值前持续分配给活跃账号。 `reset-first`: 在低于用量阈值的账号中,优先选择下次5小时或周额度重置最早的账号。已绑定任务遵循配置的亲和策略。独立模型额度按用量排序。 此排序不使用月额度重置时间。 | +| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | 新建/未绑定 Codex 请求的分配策略。没有 live `(parent thread id, quota scope)` affinity 的请求属于未绑定;带会话 ID 的请求(包括常规 Codex CLI 和 App 轮次及子代理),或锚定到直接父任务的无会话请求,其绑定在关闭时最后一次 affinity 保存成功的情况下,代理正常重启后可保留,空闲时间最长为 24 小时。更深层的无会话链和 Codex App 主登录的绑定仅保存在内存中,重启后会重新分配;驱逐、账号删除、重新登录、崩溃或 affinity 重置仍可能使任务变为未绑定。`quota` 在没有活跃账号时选择已知 usage 最低的合格账号;活跃账号合格且低于 `autoSwitchThreshold` 时继续使用;达到阈值后,可把未绑定请求切换到 usage 更低的合格账号。已绑定任务默认会保留到账号耗尽(已知 usage 为 100%)或无法继续服务,改绑时只前往确有额度余量且 usage 严格更低的账号。关闭该标志后,也可在该阈值把已绑定任务的下一次请求改绑到确有额度余量且 usage 严格更低的账号。`round-robin` 在有效 `autoSwitchThreshold` 以下的合格账号间均匀分配未绑定请求,若全部达到或超过阈值则在所有合格账号间分配;`fill-first` 在 cooldown、不可用或耗尽阈值前持续分配给活跃账号。 `reset-first`: 在低于用量阈值的账号中,优先选择下次5小时或周额度重置最早的账号。已绑定任务遵循配置的亲和策略。独立模型额度按用量排序。 此排序不使用月额度重置时间。 | | `pool.cacheAffinity?` | `boolean` | `true` | 已绑定 Codex 线程的 cache-affinity 排序,独立于 `pool.kernel`。默认开启;省略该键或设为 `true` 即为开启,非法值视为开启。live 绑定优先于 quota 余量:`quota` 不会仅因用量越过 `autoSwitchThreshold` 就移动线程。账号暂停、不可用或真正耗尽(已知 usage 为 100%)时仍会离开,且只改绑到确有额度余量且 usage 严格更低的账号。用量未知的账号不会作为已绑定任务的改绑目标。设为 `false` 可恢复按阈值改绑。affinity 是重排而非钉死。 | | `accountPoolStickyLimit?` | `number` | `1` | 一次 round-robin 选择在推进前保留的新建/未绑定任务分配数。计数在任务绑定时增加,而不是在上游成功后增加。范围 1–100;仅当 `accountPoolStrategy` 为 `round-robin` 时生效。 | | `upstreamFailoverThreshold?` | `number` | `3` | 连续发生多少次瞬态故障后,后续新会话会切换到备用上游。设为 `0` 可禁用。对于常规 Responses 和原生 compact 发送,已证明的连接前 DNS/TCP 不可达故障按 provider-host 粒度记录,不影响账户健康、账户冷却、线程/会话亲和性、活动账户选择或 Pool 路由,也不会计入此阈值。 | @@ -249,7 +249,7 @@ OpenCodex 不会依据网关名称或 URL 猜测可信度。如果同一网关 请在仪表盘 **Codex Auth** 页面添加 pool account 并刷新 quota。配置只保存非 secret account metadata;access/refresh token 存放在加固的 Codex account credential store 中。Pool routing 分为新建/未绑定任务分配、基于用量的主动切换和故障恢复。已绑定任务通常保持 affinity。默认(`pool.cacheAffinity`)下,该重新绑定会等到绑定账号耗尽或无法继续服务,并且只改绑到确有额度余量且 usage 严格更低的账号;所有账号都高于阈值时,已绑定任务留在原账号。关闭该标志后,`quota` 可在超过阈值后的下一次请求中重新绑定,但仍只改绑到确有额度余量且 usage 严格更低的账号。暂停、cooldown、重新认证和故障处理也能独立清除或改变 -routing。未绑定请求没有 live 账号绑定,也可能是代理重启或 affinity 重置后的已有任务。输出前的 +routing。未绑定请求没有 live 账号绑定。带会话 ID 的请求(包括常规 Codex CLI 和 App 轮次及子代理),或锚定到直接父任务的无会话请求,其绑定在关闭时最后一次 affinity 保存成功的情况下,代理正常重启后可保留,空闲时间最长为 24 小时。更深层的无会话链和 Codex App 主登录的绑定仅保存在内存中,重启后会重新分配;驱逐、账号删除、重新登录、崩溃或 affinity 重置仍可能使任务变为未绑定。输出前的 **429/402** 即使在关闭基于用量的主动切换时,也可在同一请求中对合格替代账号重试一次。 账号变化后会保留并重放对话上下文,但账号间的 provider prompt cache 不保证复用,可能需要重新预热。 暂停后仍会显示账号及其 quota metadata,但不会参与自动切换、重试/failover 选择、cooldown 恢复探测或手动激活。 diff --git a/docs-site/src/content/docs/zh-tw/reference/cli/providers-accounts.md b/docs-site/src/content/docs/zh-tw/reference/cli/providers-accounts.md index a743fe07a5d..c43aaade0e3 100644 --- a/docs-site/src/content/docs/zh-tw/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/zh-tw/reference/cli/providers-accounts.md @@ -158,7 +158,7 @@ Codex 池選擇套用於清除既有親和性後的下一個請求;進行中 `auto` 會清除手動選擇,讓池重新依自身策略分配工作 — 但若 Codex 帳號的 id 恰為 `auto`,則精確 id 比對優先;`ocx account clear ` 一律還原自動選擇。Codex 帳號可以用 `ocx account alias` 設定的別名代替 id 來指定;`priority`、`pause`、`resume`、`clear-cooldown`、`remove` 與 `alias` 亦然。對於 Codex 帳號,`auto`、`main` 和 `__main__` 為保留字(不區分大小寫),不能設為別名。OAuth 帳號與 API 金鑰的顯示名稱仍遵循原有規則。 -選擇既有的 Codex 帳號、OAuth 帳號或 API 金鑰。對於 `openai`,`main` 選擇 Codex App 登入。Codex 池選擇清除行程本地親和性並套用於下一個請求,包含來自既有可見任務的請求;代理重啟或親和性驅逐也可能使任務未綁定,而進行中的請求保留其擷取的帳號。這僅控制池路由;Direct 模式繼續使用呼叫者擁有/原生的 main 憑證。基於用量的主動切換、401/403 重新認證、429/retry-after 冷卻、排除,以及 pre-output 429/402 失敗復原稍後可能選擇另一個合格的池帳號。當基於用量的切換關閉時,這些復原路徑仍然活躍。OpenCodex 在帳號變更後重播對話,但供應商端的 prompt cache 可能是冷的。未知的供應商或 id 離開 1。 +選擇既有的 Codex 帳號、OAuth 帳號或 API 金鑰。對於 `openai`,`main` 選擇 Codex App 登入。Codex 池選擇清除親和性並套用於下一個請求,包含來自既有可見任務的請求;帶有工作階段 ID 的請求(包括一般 Codex CLI 和 App 回合及子代理),或錨定到直接父任務的無工作階段請求,其綁定在關閉時最後一次親和性儲存成功的情況下,代理正常重啟後可保留,閒置時間最長為 24 小時。更深層的無工作階段鏈和 Codex App 主要登入的綁定僅保留在記憶體中,重啟後會重新指派;驅逐、帳號刪除、重新登入、崩潰或親和性重置仍可能使任務未綁定,而進行中的請求保留其擷取的帳號。這僅控制池路由;Direct 模式繼續使用呼叫者擁有/原生的 main 憑證。基於用量的主動切換、401/403 重新認證、429/retry-after 冷卻、排除,以及 pre-output 429/402 失敗復原稍後可能選擇另一個合格的池帳號。當基於用量的切換關閉時,這些復原路徑仍然活躍。OpenCodex 在帳號變更後重播對話,但供應商端的 prompt cache 可能是冷的。未知的供應商或 id 離開 1。 在 **401/403** 時,App 登入清除該帳號的行程本地親和性並要求重新認證。 在 **429** 時,opencodex 遵循 `Retry-After`、啟動帳號冷卻、清除親和性,並可能將請求輪換到另一個合格的池帳號。這些失敗轉換在 `autoSwitchThreshold: 0` 時仍然活躍;該設定僅停用基於用量的主動切換。 `--json` 回傳: diff --git a/docs-site/src/content/docs/zh-tw/reference/configuration/providers.md b/docs-site/src/content/docs/zh-tw/reference/configuration/providers.md index b3e75e1da34..80b14de4608 100644 --- a/docs-site/src/content/docs/zh-tw/reference/configuration/providers.md +++ b/docs-site/src/content/docs/zh-tw/reference/configuration/providers.md @@ -53,7 +53,7 @@ ocx models provider openrouter on | `activeCodexAccountId?` | `string` | — | 為下一個請求手動選擇的池帳號。選擇清除執行緒親和性;進行中的請求保留擷取的憑證。 | | `autoSwitchThreshold?` | `number` | `80` | 主動切換的用量閾值。`quota` 可在下一個請求時重新評估未綁定任務。綁定任務預設(`pool.cacheAffinity`)在越過閾值後仍會保留帳號,直到該帳號耗盡或無法繼續服務,並且只改綁到確有額度餘裕且用量嚴格更低的帳號。將 `pool.cacheAffinity` 設為 `false` 才會在此閾值重新評估綁定任務。`fill-first` 僅將其用作未綁定指派的排空點;`round-robin` 僅在新/未綁定工作指派時使用它:只要仍有低於自身有效閾值的合格帳號,就略過達到或超過閾值的帳號,且不會因此移動已綁定任務。分數使用最熱的已知 5h、週或 30d 配額視窗。`0` 僅停用基於用量的主動切換,而非未綁定指派或失敗復原。 | | `codexAccountAutoSwitchThresholds?` | `Record` | — | 各帳號對 `autoSwitchThreshold` 的覆寫:帳號 ID → `0`–`100` 的整數。沒有項目時繼承全域值;`0` 只停用從該帳號發起的使用量主動切換。支援主帳號 `__main__`。可在 Codex Auth 的帳號卡片中管理。 啟用覆寫時,會將目前全域閾值複製為固定的帳號值。覆寫值(包括 `0`)在之後修改全域閾值時仍優先。停用時傳送 `threshold: null`,刪除項目,並恢復繼承目前全域閾值及其未來的變更。 | -| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | 新/未綁定 Codex 請求的指派策略。當請求沒有即時(父執行緒 id、配額 scope)親和性時即為未綁定;可見的既有任務在代理重啟或親和性重置後可變為未綁定。`quota` 在無現用帳號時選擇最低用量的合格帳號,將合格現用帳號保持在 `autoSwitchThreshold` 以下,且在閾值後可將未綁定請求移至較低用量的合格帳號。綁定任務預設會保留到帳號耗盡(已知用量 100%)或無法繼續服務,改綁時只前往確有額度餘裕且用量嚴格更低的帳號。關閉該設定後,也可在閾值將綁定任務的下一個請求改綁到確有額度餘裕且用量嚴格更低的帳號。`round-robin` 在有效 `autoSwitchThreshold` 以下的合格帳號間均勻分配未綁定請求,若全部達到或超過閾值則在所有合格帳號間分配;`fill-first` 持續將未綁定請求指派到現用帳號直到冷卻、不可用或設定的排空閾值。 `reset-first`: 在低於用量門檻的帳號中,優先選擇下次5小時或週額度重設最早的帳號。已綁定任務遵循設定的親和策略。獨立模型額度按用量排序。 此排序不使用月額度重設時間。 | +| `accountPoolStrategy?` | `"quota" \| "round-robin" \| "fill-first" \| "reset-first"` | `"quota"` | 新/未綁定 Codex 請求的指派策略。當請求沒有即時(父執行緒 id、配額 scope)親和性時即為未綁定;帶有工作階段 ID 的請求(包括一般 Codex CLI 和 App 回合及子代理),或錨定到直接父任務的無工作階段請求,其綁定在關閉時最後一次親和性儲存成功的情況下,代理正常重啟後可保留,閒置時間最長為 24 小時。更深層的無工作階段鏈和 Codex App 主要登入的綁定僅保留在記憶體中,重啟後會重新指派;驅逐、帳號刪除、重新登入、崩潰或親和性重置仍可能使任務未綁定。`quota` 在無現用帳號時選擇最低用量的合格帳號,將合格現用帳號保持在 `autoSwitchThreshold` 以下,且在閾值後可將未綁定請求移至較低用量的合格帳號。綁定任務預設會保留到帳號耗盡(已知用量 100%)或無法繼續服務,改綁時只前往確有額度餘裕且用量嚴格更低的帳號。關閉該設定後,也可在閾值將綁定任務的下一個請求改綁到確有額度餘裕且用量嚴格更低的帳號。`round-robin` 在有效 `autoSwitchThreshold` 以下的合格帳號間均勻分配未綁定請求,若全部達到或超過閾值則在所有合格帳號間分配;`fill-first` 持續將未綁定請求指派到現用帳號直到冷卻、不可用或設定的排空閾值。 `reset-first`: 在低於用量門檻的帳號中,優先選擇下次5小時或週額度重設最早的帳號。已綁定任務遵循設定的親和策略。獨立模型額度按用量排序。 此排序不使用月額度重設時間。 | | `pool.cacheAffinity?` | `boolean` | `true` | 綁定 Codex 執行緒的 cache-affinity 排序,獨立於 `pool.kernel`。預設開啟;省略該鍵或設為 `true` 即為開啟,格式錯誤視為開啟。即時綁定優先於配額餘裕:`quota` 不會只因用量越過 `autoSwitchThreshold` 就移動執行緒。帳號暫停、無法使用或真正耗盡(已知用量 100%)時仍會離開,且只改綁到確有額度餘裕且用量嚴格更低的帳號。用量未知的帳號不會作為綁定任務的改綁目標。設為 `false` 可恢復依閾值重新綁定。親和性是重排而非釘死。 | | `accountPoolStickyLimit?` | `number` | `1` | 在前進一個 round-robin 選擇前保留的新/未綁定任務指派;計數器在任務綁定時前進,而非在上游成功後。範圍 1–100。 | | `upstreamFailoverThreshold?` | `number` | `3` | 未來新 session 容錯移轉前的連續暫時性失敗。設 `0` 停用。 | @@ -186,7 +186,7 @@ API-key 供應商可持有字面值金鑰或環境參考。OAuth 供應商使用 ## Codex 帳號池 -在儀表板中使用 **Codex Auth** 新增池帳號並重新整理配額。`config.json` 儲存非秘密中繼資料;access 與 refresh token 使用強化的憑證存放。池路由將新/未綁定指派、基於用量的主動切換與失敗復原分開。綁定任務通常保留親和性。預設(`pool.cacheAffinity`)下,該重新綁定會等到綁定帳號耗盡或無法繼續服務,並且只改綁到確有額度餘裕且用量嚴格更低的帳號;所有帳號都高於閾值時,綁定任務留在原帳號。關閉該設定後,`quota` 可在超過用量閾值後的下一個請求時重新綁定它,但仍只改綁到確有額度餘裕且用量嚴格更低的帳號。暫停、冷卻、重新認證與失敗處理可獨立清除或移動路由。未綁定請求沒有即時帳號綁定;這可包含代理重啟或親和性重置後的既有可見任務。Pre-stream 的 429 或 402 在同一個請求中於一個合格的備用帳號上重試一次,即使基於用量的主動切換關閉。帳號變更保留並重播對話 context,但跨帳號的供應商端 prompt-cache 重用不保證,cache 可能需要重新暖機。 +在儀表板中使用 **Codex Auth** 新增池帳號並重新整理配額。`config.json` 儲存非秘密中繼資料;access 與 refresh token 使用強化的憑證存放。池路由將新/未綁定指派、基於用量的主動切換與失敗復原分開。綁定任務通常保留親和性。預設(`pool.cacheAffinity`)下,該重新綁定會等到綁定帳號耗盡或無法繼續服務,並且只改綁到確有額度餘裕且用量嚴格更低的帳號;所有帳號都高於閾值時,綁定任務留在原帳號。關閉該設定後,`quota` 可在超過用量閾值後的下一個請求時重新綁定它,但仍只改綁到確有額度餘裕且用量嚴格更低的帳號。暫停、冷卻、重新認證與失敗處理可獨立清除或移動路由。未綁定請求沒有即時帳號綁定;帶有工作階段 ID 的請求(包括一般 Codex CLI 和 App 回合及子代理),或錨定到直接父任務的無工作階段請求,其綁定在關閉時最後一次親和性儲存成功的情況下,代理正常重啟後可保留,閒置時間最長為 24 小時。更深層的無工作階段鏈和 Codex App 主要登入的綁定僅保留在記憶體中,重啟後會重新指派;驅逐、帳號刪除、重新登入、崩潰或親和性重置仍可能使任務未綁定。Pre-stream 的 429 或 402 在同一個請求中於一個合格的備用帳號上重試一次,即使基於用量的主動切換關閉。帳號變更保留並重播對話 context,但跨帳號的供應商端 prompt-cache 重用不保證,cache 可能需要重新暖機。 在 **401/403** 時,App 登入清除該帳號的行程本地親和性並要求重新認證。 在 **429** 時,opencodex 遵循 `Retry-After`、啟動帳號冷卻、清除親和性,並可能將請求輪換到另一個合格的池帳號。這些失敗轉換在 `autoSwitchThreshold: 0` 時仍然活躍;該設定僅停用基於用量的主動切換。 diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index 80b5b0185ef..3285320c8f1 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -645,7 +645,8 @@ "codex-integration-record.test.ts": "codex-integration", "codex-journal-recovery.test.ts": "codex-integration", "codex-journal.test.ts": "codex-integration", "codex-legacy-config-keys.test.ts": "codex-integration", - "codex-lineage-placement.test.ts": "codex-integration", + "codex-affinity-store.test.ts": "codex-integration", + "codex-lineage-placement.test.ts": "codex-integration", "codex-log-guard-coderabbit.test.ts": "codex-integration", "codex-log-guard-doctor-coderabbit.test.ts": "codex-integration", "codex-log-guard-doctor-protection.test.ts": "codex-integration", @@ -705,8 +706,7 @@ "codex-restart-route.test.ts": "codex-integration", "codex-restore-app-rewrite.test.ts": "codex-integration", "codex-retained-root-serialization.test.ts": "codex-integration", - "codex-routing-cache-affinity-detour.test.ts": "codex-integration", "codex-routing-elapsed-short-reset.test.ts": "codex-integration", - "codex-routing.test.ts": "codex-integration", + "codex-affinity-restart.test.ts": "codex-integration", "codex-affinity-restart-matrix.test.ts": "codex-integration", "codex-affinity-request-owned.test.ts": "codex-integration", "codex-affinity-lease-gap.test.ts": "codex-integration", "codex-routing-cache-affinity-detour.test.ts": "codex-integration", "codex-routing-elapsed-short-reset.test.ts": "codex-integration", "codex-routing.test.ts": "codex-integration", "codex-runtime.test.ts": "codex-integration", "codex-runtime-macos-desktop.test.ts": "codex-integration", "codex-clamp-notice.test.ts": "codex-integration", "codex-runtime-wsl-desktop.test.ts": "codex-integration", "codex-service-manager-probe-hardening.test.ts": "codex-integration", diff --git a/src/codex/lineage.ts b/src/codex/lineage.ts index 4788efbe274..a755e8ac690 100644 --- a/src/codex/lineage.ts +++ b/src/codex/lineage.ts @@ -31,12 +31,10 @@ * posture as the affinity key itself. Two callers presenting identical thread ids can never read * each other's lineage, and no raw identifier or durable hash is stored. * - * LIFETIME, stated plainly because the word "affinity" invites the opposite assumption: none of - * this survives the process. The binding map is in memory, and the HMAC key above is fresh random - * bytes taken at module load, so a restart does not merely forget the table -- it makes yesterday's - * keys unreproducible. This is a warm-start hint for the life of one proxy process, never durable - * account ownership, and nothing here should be read as a promise to a conversation that outlives - * a restart. + * LIFETIME: lineage records and their keys remain process-local. The HMAC key is fresh random + * bytes taken at module load, so yesterday's keys cannot be reproduced after a restart. An + * affinity store may persist separate digests of cohort anchors under its own secret; it must + * never persist these process-local keys. * * The one upgrade that is neither a fresh start nor an untouched process is a code swap under a * live conversation, where the binding map is still populated with entries made under the @@ -50,6 +48,12 @@ import { retainedUtf8Bytes } from "../lib/admission"; const CODEX_LINEAGE_COMPONENT_MAX_BYTES = 512; const CODEX_LINEAGE_KEY = randomBytes(32); +let conversationAnchorObserver: ((key: string, familyId: string, threadId: string) => void) | undefined; + +/** Register the consumer of derived cohort anchors, or remove it. */ +export function setCodexConversationAnchorObserver(fn?: (key: string, familyId: string, threadId: string) => void): void { + conversationAnchorObserver = fn; +} /** * Mirrors `CODEX_THREAD_AFFINITY_IDLE_TTL_MS` in ./routing. Deliberately duplicated rather than @@ -149,12 +153,14 @@ function boundedLineageComponent(value: string | null): string | undefined { * byte-identical to the key the thread actually binds under. */ export function codexConversationKeyFor(familyId: string, threadId: string): string { - return `app:${createHmac("sha256", CODEX_LINEAGE_KEY) + const key = `app:${createHmac("sha256", CODEX_LINEAGE_KEY) .update("opencodex-app-pool-affinity-v1\0") .update(familyId) .update("\0") .update(threadId) .digest("base64url")}`; + conversationAnchorObserver?.(key, familyId, threadId); + return key; } /** diff --git a/src/codex/request-owned-affinity-key.ts b/src/codex/request-owned-affinity-key.ts new file mode 100644 index 00000000000..72afaf4a4a4 --- /dev/null +++ b/src/codex/request-owned-affinity-key.ts @@ -0,0 +1,11 @@ +/** + * The namespace of caller-owned affinity keys, kept in a module with no imports so that stores + * which must refuse these keys (the durable Codex pool affinity store) can test for them without + * importing the routing modules that request-owned affinity itself depends on. + */ +export const REQUEST_OWNED_AFFINITY_KEY_PREFIX = "request-owned:v1:"; + +/** Identify namespace keys that must remain process-local. */ +export function isRequestOwnedAffinityKey(value: string): boolean { + return value.startsWith(REQUEST_OWNED_AFFINITY_KEY_PREFIX); +} diff --git a/src/codex/request-owned-affinity.ts b/src/codex/request-owned-affinity.ts index 514dc300c0b..a4adeb3190e 100644 --- a/src/codex/request-owned-affinity.ts +++ b/src/codex/request-owned-affinity.ts @@ -10,9 +10,11 @@ import { getThreadAffinity, getModelDetourAffinity, deleteThreadAffinity, delete import type { CodexQuotaScope } from "./routing/health-store"; import { classifyCodexUpstreamOutcome } from "./routing/cooldown-math"; import type { CodexAuthContext } from "./auth-context"; +import { isRequestOwnedAffinityKey, REQUEST_OWNED_AFFINITY_KEY_PREFIX } from "./request-owned-affinity-key"; +export { isRequestOwnedAffinityKey } from "./request-owned-affinity-key"; const key = randomBytes(32); -const prefix = "request-owned:v1:"; +const prefix = REQUEST_OWNED_AFFINITY_KEY_PREFIX; /** Derive the opaque key for this caller and conversation, if both exist. */ export function requestOwnedAffinityKey(headers: Headers): string | undefined { @@ -24,11 +26,6 @@ export function requestOwnedAffinityKey(headers: Headers): string | undefined { .digest("base64url"); } -/** Identify namespace keys that must remain process-local. */ -export function isRequestOwnedAffinityKey(value: string): boolean { - return value.startsWith(prefix); -} - /** Report a bind only when the selection-time entry names the selected account. */ export function honestAffinityDecision( decision: CodexAffinityDecision | undefined, diff --git a/src/codex/routing/thread-affinity-store.ts b/src/codex/routing/thread-affinity-store.ts new file mode 100644 index 00000000000..5fcf67f2292 --- /dev/null +++ b/src/codex/routing/thread-affinity-store.ts @@ -0,0 +1,899 @@ +import { Database } from "bun:sqlite"; +import { createHash, createHmac, randomBytes } from "node:crypto"; +import { + chmodSync, + closeSync, + lstatSync, + openSync, + realpathSync, + type Stats, +} from "node:fs"; +import { resolve } from "node:path"; +import { getConfigDir } from "../../config/paths"; +import { initializeConfigOwnership, recordOwnedConfigPath } from "../../lib/config-ownership"; +import { isPassiveRead } from "../../lib/passive-read"; +import { + assertStorageOwned, + currentSpendLedgerOwnerGeneration, + mintSpendLedgerStorage, + onSpendLedgerOwnerAcquired, + onSpendLedgerOwnerReleased, + onSpendLedgerOwnerReleasing, + spendLedgerStoragePath, + type SpendLedgerStorage, +} from "../../lib/spend-ledger-owner"; +import { assertNotRealHomeUnderTest } from "../../lib/test-home-guard"; +import { hardenSecretPath } from "../../lib/windows-secret-acl"; +import { readCodexAccountRecord } from "../account-store"; +import { isRequestOwnedAffinityKey } from "../request-owned-affinity-key"; +import { setCodexConversationAnchorObserver } from "../lineage"; +import type { CodexQuotaScope } from "./health-store"; + +export type StoredThreadRow = { + scope: string; + accountId: string; + fence: string; + createdAt: number; + lastUsedAt: number; +}; +export const CODEX_UNKNOWN_CONVERSATION_STATE_ISSUER = + "__unknown_codex_conversation_state_issuer__"; +type LiveReader = { + thread( + key: string, + scope: string, + ): + | { + accountId: string; + identityFence?: string; + createdAt: number; + lastUsedAt: number; + } + | undefined; + issuer( + key: string, + ): { accountId: string; fence?: string; lastUsedAt: number } | undefined; + clearLive(): void; +}; +type Op = { + sql: string; + args: (string | number | null)[]; + key?: string; + scope?: string; + kind: string; +}; +type Scope = { + home: string; + generation: number; + token: SpendLedgerStorage; + db?: Database; + secret?: Uint8Array; + disabled: boolean; + poisoned: boolean; + failures: number; + log: Op[]; + threads: Map; + issuers: Map; + anchors: Map; + threadKeys: Map }>; + issuerKeys: Map; + consulted: Set; + timer?: ReturnType; + pruneTimer?: ReturnType; + scheduled: boolean; +}; +const TTL = 24 * 60 * 60_000; +const BASE_SCOPES = [ + "shared", + "reserve", +] as const satisfies readonly CodexQuotaScope[]; +const BASE_SCOPES_EXHAUSTIVE: Exclude< + CodexQuotaScope, + (typeof BASE_SCOPES)[number] +> extends never + ? true + : never = true; +void BASE_SCOPES_EXHAUSTIVE; +let current: Scope | undefined; +let observedHome: string | undefined; +/** The home whose database the most recent scope in this process actually opened. */ +let persistedHome: string | undefined; +/** + * A persistable change to pins or issuers happened while that home's database was not writable + * (between leases, or while a scope could not open it). The database may still hold the row the + * change replaced or deleted, so the next scope that opens it clears it first. Live memory keeps + * routing as before; a later restart then restores nothing rather than something stale. Only a + * process that releases and reacquires its lease reaches this: a serving proxy holds one lease for + * its whole life. + */ +let needsClear = false; +/** Anchors of the last retired scope, handed to the next scope of the same home. */ +let carried: { home: string; anchors: Scope["anchors"]; threadKeys: Scope["threadKeys"]; issuerKeys: Scope["issuerKeys"] } | undefined; +let reader: LiveReader | undefined; + +export function registerCodexAffinityLiveState(value: LiveReader): void { + reader = value; + setCodexConversationAnchorObserver(observeAnchor); +} +function warning(): void { + console.warn("Codex affinity persistence unavailable; continuing in memory."); +} +/** Retire the lease-scoped handle without discarding in-memory affinity. */ +function retire(): void { + const s = current; + if (!s) return; + current = undefined; + // Anchors are process-local facts about this home's conversations; the next scope of the same + // home needs them to re-derive row keys for pins that are still live in memory. + // Row keys too: after an anchor is evicted they are the only way a delete can still reach its row. + if (s.db && !s.poisoned) carried = { home: s.home, anchors: s.anchors, threadKeys: s.threadKeys, issuerKeys: s.issuerKeys }; + if (s.timer) clearTimeout(s.timer); + if (s.pruneTimer) clearInterval(s.pruneTimer); + try { + s.db?.close(); + } catch { + warning(); + } +} +function checkFile(path: string): Stats { + const stat = lstatSync(path); + if ( + !stat.isFile() || + stat.isSymbolicLink() || + stat.nlink !== 1 || + (process.platform !== "win32" && stat.uid !== process.getuid!()) + ) + throw new Error("unsafe file"); + return stat; +} +function open(s: Scope): void { + const path = spendLedgerStoragePath(s.token); + let db: Database | undefined; + try { + assertNotRealHomeUnderTest(s.home); + // An owned home must list these files before they exist, so uninstall removes them. A home with + // no ownership manifest (one that predates ownership tracking) cannot record anything, and + // uninstall refuses to remove anything from it; like the spend-ledger owner database, the store + // still works there rather than silently losing persistence. + for (const suffix of ["", "-journal", "-wal", "-shm"]) + if (!recordOwnedConfigPath(s.home, path + suffix) && initializeConfigOwnership(s.home)) + throw new Error("ownership"); + try { + closeSync(openSync(path, "wx", 0o600)); + } catch (e) { + if ((e as NodeJS.ErrnoException).code !== "EEXIST") throw e; + } + const before = checkFile(path); + if (before.size > 8 * 1024 * 1024) throw new Error("oversized"); + if (process.platform !== "win32") chmodSync(path, 0o600); + if (!hardenSecretPath(path, { required: true }).ok) throw new Error("acl"); + checkFile(path); + assertStorageOwned(s.token); + // SQLite creates sidecars in the private, hardened config directory, as with + // spend-ledger-owner.sqlite and config-mutation.sqlite. + db = new Database(path); + db.exec("PRAGMA busy_timeout = 0; BEGIN IMMEDIATE"); + const version = ( + db.query("PRAGMA user_version").get() as { user_version: number } + ).user_version; + const objects = db + .query("SELECT type, name FROM sqlite_master ORDER BY name") + .all() as { type: string; name: string }[]; + const tables = objects.filter((o) => o.type === "table"); + if (version === 0 && objects.length === 0) { + db.exec( + "CREATE TABLE meta(name TEXT PRIMARY KEY, value BLOB); CREATE TABLE threads(row_key TEXT, scope TEXT, account_id TEXT, fence TEXT, created_at INTEGER, last_used_at INTEGER, PRIMARY KEY(row_key, scope)); CREATE TABLE issuers(row_key TEXT PRIMARY KEY, account_id TEXT, fence TEXT, last_used_at INTEGER); PRAGMA user_version = 1", + ); + db.query("INSERT INTO meta VALUES ('secret', ?), ('clean', 0)").run( + randomBytes(32), + ); + } else { + if ( + version !== 1 || + tables.map((t) => t.name).join(",") !== "issuers,meta,threads" + ) + throw new Error("version"); + const expected: Record = { + meta: "name:TEXT:1,value:BLOB:0", + threads: + "row_key:TEXT:1,scope:TEXT:2,account_id:TEXT:0,fence:TEXT:0,created_at:INTEGER:0,last_used_at:INTEGER:0", + issuers: + "row_key:TEXT:1,account_id:TEXT:0,fence:TEXT:0,last_used_at:INTEGER:0", + }; + for (const [table, columns] of Object.entries(expected)) { + const actual = db.query(`PRAGMA table_info(${table})`).all() as { + name: string; + type: string; + pk: number; + notnull: number; + dflt_value: unknown; + }[]; + if ( + actual.map((c) => `${c.name}:${c.type}:${c.pk}`).join(",") !== + columns || + actual.some((c) => c.notnull !== 0 || c.dflt_value !== null) + ) + throw new Error("shape"); + } + const indexes = objects + .filter((o) => o.type === "index") + .map((o) => o.name) + .join(","); + if ( + objects.length !== 6 || + indexes !== + "sqlite_autoindex_issuers_1,sqlite_autoindex_meta_1,sqlite_autoindex_threads_1" + ) + throw new Error("shape"); + const rows = db.query("SELECT name, value FROM meta").all() as { + name: string; + value: unknown; + }[]; + const secret = rows.find((r) => r.name === "secret")?.value; + const clean = rows.find((r) => r.name === "clean")?.value; + if ( + !(secret instanceof Uint8Array) || + secret.length !== 32 || + rows.length !== 2 || + !rows.some((r) => r.name === "clean") + ) + throw new Error("meta"); + db.exec("PRAGMA secure_delete = ON"); + // Only a completed final flush permits the next owner to restore rows. + if (clean !== 1) db.exec("DELETE FROM threads; DELETE FROM issuers"); + db.exec("UPDATE meta SET value=0 WHERE name='clean'"); + } + db.exec("PRAGMA secure_delete = ON"); + const pageSize = (db.query("PRAGMA page_size").get() as { page_size: number }).page_size; + db.exec(`PRAGMA max_page_count = ${Math.floor(8 * 1024 * 1024 / pageSize)}`); + prune(db, Date.now()); + const secret = ( + db.query("SELECT value FROM meta WHERE name='secret'").get() as { + value: Uint8Array; + } + ).value; + db.exec("COMMIT"); + const after = checkFile(path); + if (before.dev !== after.dev || before.ino !== after.ino) throw new Error("replaced"); + s.db = db; + s.secret = secret; + s.pruneTimer = setInterval(() => { + if (current === s) { + if (s.poisoned || isPassiveRead()) pruneOnly(s); + else flush(s, false); + } + }, 60 * 60_000); + s.pruneTimer.unref(); + } catch { + try { + db?.exec("ROLLBACK"); + } catch { + /* no transaction */ + } + try { + db?.close(); + } catch { + /* preserve open failure */ + } + s.disabled = true; + warning(); + } +} +function resolvedHome(acquiredHome?: string): string { + let home = resolve(acquiredHome ?? getConfigDir()); + try { + home = realpathSync.native(home); + } catch { + /* ownership check below refuses it */ + } + return process.platform === "win32" ? home.toLowerCase() : home; +} +function scope(acquiredHome?: string): Scope | undefined { + if (!acquiredHome && isPassiveRead()) return undefined; + const home = resolvedHome(acquiredHome); + // A lease ends a store scope; only a change of home invalidates live maps. + if (observedHome !== undefined && observedHome !== home) { + retire(); + carried = undefined; + persistedHome = undefined; + needsClear = false; + reader?.clearLive(); + } + observedHome = home; + const generation = currentSpendLedgerOwnerGeneration(); + if (current && (current.home !== home || current.generation !== generation)) + retire(); + if (current) { + try { + assertStorageOwned(current.token); + return current; + } catch { + retire(); + return undefined; + } + } + let token: SpendLedgerStorage; + try { + token = mintSpendLedgerStorage("codex-affinity.sqlite"); + assertStorageOwned(token); + } catch { + return undefined; + } + const s: Scope = { + home, + generation, + token, + disabled: false, + poisoned: false, + failures: 0, + log: [], + threads: new Map(), + issuers: new Map(), + anchors: carried?.home === home ? carried.anchors : new Map(), + threadKeys: carried?.home === home ? carried.threadKeys : new Map(), + issuerKeys: carried?.home === home ? carried.issuerKeys : new Map(), + consulted: new Set(), + scheduled: false, + }; + const prior = carried; + carried = undefined; + current = s; + open(s); + // A scope that could not open never touched the carried maps; keep them for the next one. + if (!s.db && prior?.home === home) carried = prior; + if (s.db) { + if (needsClear && persistedHome === home) recordAllCleared(); + needsClear = false; + persistedHome = home; + } + return s; +} +/** + * The scope for a change to which pins or issuers exist. When the change could have been persisted + * but this home's database is not writable right now, remember that the database is stale. + */ +function writableScope(persistable: boolean): Scope | undefined { + const s = usable(); + if (!s && persistable && persistedHome !== undefined && !isPassiveRead() && persistedHome === resolvedHome()) + needsClear = true; + return s; +} +function usable(): Scope | undefined { + const s = scope(); + return s && !s.disabled && !s.poisoned && s.db ? s : undefined; +} +function observeAnchor(key: string, family: string, thread: string): void { + // Caller-owned keys are process-local by contract (structure/providers/codex-request-owned-affinity.md). + if (isRequestOwnedAffinityKey(key)) return; + const s = usable(); + if (!s) return; + const now = Date.now(); + for (const [k, a] of s.anchors) { + if (now - a.at <= TTL) break; + s.anchors.delete(k); + } + s.anchors.delete(key); + s.anchors.set(key, { family, thread, at: now }); + while (s.anchors.size > 4096) + s.anchors.delete(s.anchors.keys().next().value!); +} +setCodexConversationAnchorObserver(observeAnchor); +function rowKey( + s: Scope, + key: string, + kind: "conversation" | "issuer", +): string | undefined { + // The single choke point for every bind, touch, delete, adoption and issuer path: a request-owned + // key never has a durable row key, so nothing for it is ever written or restored. + if (isRequestOwnedAffinityKey(key)) return undefined; + const a = s.anchors.get(key); + if (!a || Date.now() - a.at > TTL) { + s.anchors.delete(key); + return kind === "conversation" ? s.threadKeys.get(key)?.rowKey : s.issuerKeys.get(key); + } + return createHmac("sha256", s.secret!) + .update(`opencodex/codex-affinity/${kind}/v1\0`) + .update(a.family) + .update("\0") + .update(a.thread) + .digest("hex"); +} +export function codexAffinityIdentityFence( + accountId: string, +): string | undefined { + if (accountId === "__main__") return undefined; + const record = readCodexAccountRecord(accountId); + if ( + !record?.credential || + record.deletedAt != null || + !record.quotaHistoryIdentity + ) + return undefined; + return identityFence(record.quotaHistoryIdentity); +} +export function identityFence(identity: string | undefined): string | undefined { + if (!identity) return undefined; + return createHash("sha256") + .update("opencodex/codex-affinity/identity/v1\0") + .update(identity) + .digest("hex"); +} +function rememberThreadKey(s: Scope, key: string, rk: string, scopeName: string, accountId: string): void { + let entry = s.threadKeys.get(key); + if (!entry) s.threadKeys.set(key, entry = { rowKey: rk, scopes: new Map() }); + entry.scopes.set(scopeName, accountId); + if (s.threadKeys.size + s.issuerKeys.size > 8192) poison(s); +} +function rememberIssuerKey(s: Scope, key: string, rk: string): void { + s.issuerKeys.set(key, rk); + if (s.threadKeys.size + s.issuerKeys.size > 8192) poison(s); +} +/** A poisoned scope cannot safely declare itself clean on release. */ +function poison(s: Scope): void { + s.poisoned = true; + s.log = []; + s.threads.clear(); + s.issuers.clear(); + s.threadKeys.clear(); + s.issuerKeys.clear(); + if (s.timer) clearTimeout(s.timer); + warning(); +} +function enqueue(s: Scope, op: Op): void { + // Preserve structural ordering; only clearAll supersedes the whole log. + if (op.kind === "clearAll") s.log = []; + s.log.push(op); + if (s.log.length > 16384) { + poison(s); + return; + } + if (!s.scheduled) { + s.scheduled = true; + queueMicrotask(() => { + s.scheduled = false; + if (current === s && !isPassiveRead()) flush(s, false); + }); + } +} +function scheduleTouch(s: Scope): void { + if (s.timer) return; + s.timer = setTimeout(() => { + s.timer = undefined; + if (current === s && !isPassiveRead()) flush(s, false); + }, 1000); + s.timer.unref(); +} +function prune(db: Database, now: number): void { + for (const table of ["threads", "issuers"]) + db.query(`DELETE FROM ${table} WHERE last_used_at < ? OR last_used_at > ?`).run(now - TTL, now); + db.query("DELETE FROM threads WHERE created_at > ?").run(now); + db.exec("DELETE FROM threads WHERE rowid IN (SELECT rowid FROM threads ORDER BY (scope LIKE 'model-detour:%') ASC, last_used_at DESC, row_key, scope LIMIT -1 OFFSET 2048); DELETE FROM issuers WHERE rowid IN (SELECT rowid FROM issuers ORDER BY last_used_at DESC, row_key LIMIT -1 OFFSET 2048)"); +} +function pruneOnly(s: Scope): boolean { + if (!s.db || s.disabled) return false; + try { + assertStorageOwned(s.token); + s.db.exec("BEGIN IMMEDIATE"); + // Pending touches first, so a pin used since its last persisted timestamp is not evicted as idle. + if (!s.poisoned) applyTouches(s, s.db); + prune(s.db, Date.now()); + s.db.exec("COMMIT"); + return true; + } catch { + try { s.db.exec("ROLLBACK"); } catch { /* no transaction */ } + warning(); + return false; + } +} +/** Write the live last-used time of every touched row; UPDATE-only, so it never creates or revives a row. */ +function applyTouches(s: Scope, db: Database): void { + for (const t of s.threads.values()) { + const row = reader?.thread(t.key, t.scope); + if (row?.identityFence) + db.query( + "UPDATE threads SET last_used_at=max(last_used_at, ?) WHERE row_key=? AND scope=? AND account_id=? AND fence=?", + ).run( + row.lastUsedAt, + t.rowKey, + t.scope, + row.accountId, + row.identityFence, + ); + } + for (const t of s.issuers.values()) { + const row = reader?.issuer(t.key); + if (row) + db.query( + "UPDATE issuers SET last_used_at=max(last_used_at, ?) WHERE row_key=? AND account_id=? AND fence IS ?", + ).run(row.lastUsedAt, t.rowKey, row.accountId, row.fence ?? null); + } +} +/** + * Commit the ordered log and touches. The final release flush (clean=true) commits work that was + * logged outside any passive read, so it runs even if the release happens inside one. + */ +function flush(s: Scope, clean: boolean): boolean { + if (!s.db || s.disabled || s.poisoned || (!clean && isPassiveRead())) return false; + const db = s.db; + for (let attempt = 0; attempt < 2; attempt++) try { + assertStorageOwned(s.token); + db.exec("BEGIN IMMEDIATE"); + // Touches go before the log as well as after it, so the pruning between chunks sees the live + // last-used times and cannot evict a pin that is in use but persisted with an old timestamp. + applyTouches(s, db); + for (let i = 0; i < s.log.length; i++) { + const op = s.log[i]!; + if (op.args.length) db.query(op.sql).run(...op.args); + else db.exec(op.sql); + // Touches before every chunk prune, so rows this chunk inserted carry their live last-used time. + if ((i + 1) % 256 === 0) { + applyTouches(s, db); + prune(db, Date.now()); + } + } + // Again after the log: rows the log just inserted take their live last-used time. + applyTouches(s, db); + prune(db, Date.now()); + if (clean) db.exec("UPDATE meta SET value=1 WHERE name='clean'"); + db.exec("COMMIT"); + s.log = []; + s.threads.clear(); + s.issuers.clear(); + s.failures = 0; + return true; + } catch (error) { + try { + db.exec("ROLLBACK"); + } catch { + /* preserve failure */ + } + if (attempt === 0 && error instanceof Error && "code" in error && error.code === "SQLITE_FULL" && pruneOnly(s)) continue; + if (++s.failures >= 3) poison(s); + else warning(); + // Deleting expired rows does not depend on the failed batch; keep the retention bound. + pruneOnly(s); + return false; + } + return false; +} +// Open eagerly so the startup prune runs without traffic; a passive read never opens the store. +onSpendLedgerOwnerAcquired((home) => { if (!isPassiveRead()) scope(home); }); +// Commit clean before closing; a later close failure cannot undo that commit. +onSpendLedgerOwnerReleasing(() => { + const s = current; + if (s) { + flush(s, true); + retire(); + } +}); +onSpendLedgerOwnerReleased(() => retire()); +function pending(s: Scope, row: string, issuer: boolean): boolean { + return s.log.some( + (op) => + op.kind === "clearAll" || + (issuer + ? op.kind === "clearIssuers" || + (op.kind === "issuerDelete" && op.key === row) + : op.kind === "clearThreads" || (op.kind === "deleteKey" && op.key === row)), + ); +} +function consulted(s: Scope, key: string): boolean { + if (s.consulted.has(key)) return true; + s.consulted.add(key); + if (s.consulted.size > 8192) + s.consulted.delete(s.consulted.values().next().value!); + return false; +} +function validScope(value: string): boolean { + const bases: readonly string[] = ["legacy", ...BASE_SCOPES]; + if (bases.includes(value)) return true; + const m = /^model-detour:([^:]+):(.+)$/s.exec(value); + return ( + !!m && bases.includes(m[1]!) && Buffer.byteLength(m[2]!, "utf8") <= 512 + ); +} +export function adoptStoredThreadRows( + key: string, + now: number, + scopeName?: string, +): StoredThreadRow[] { + const s = usable(); + if (!s) return []; + const rk = rowKey(s, key, "conversation"); + // A completed unscoped read (marker "*") already adopted every stored scope for this key. + if ( + !rk + || pending(s, rk, false) + || s.consulted.has(`t:${rk}:*`) + || (scopeName !== undefined && s.consulted.has(`t:${rk}:${scopeName}`)) + ) return []; + try { + // Enumerating every scope matters: routing decides account-wide release from this view. The + // table itself is trimmed to 2048 rows at open and on every flush, which bounds the read. + const rows = s + .db!.query( + scopeName === undefined + ? "SELECT scope, account_id, fence, created_at, last_used_at FROM threads WHERE row_key=? ORDER BY last_used_at DESC, scope LIMIT 2048" + : "SELECT scope, account_id, fence, created_at, last_used_at FROM threads WHERE row_key=? AND scope=? LIMIT 1", + ) + .all(...(scopeName === undefined ? [rk] : [rk, scopeName])) as { + scope: string; + account_id: string; + fence: string; + created_at: number; + last_used_at: number; + }[]; + const result: StoredThreadRow[] = []; + for (const r of rows) { + if ( + s.log.some( + (op) => + op.kind === "deleteScope" && op.key === rk && op.scope === r.scope, + ) || + s.log.some( + (op) => (op.kind === "deleteAccount" && op.args[0] === r.account_id) || + (op.kind === "deleteKeyAccount" && op.key === rk && op.args[1] === r.account_id), + ) + ) + continue; + if ( + !validScope(r.scope) || + !Number.isFinite(r.created_at) || + !Number.isFinite(r.last_used_at) || + r.created_at > now || + r.last_used_at > now || + now - r.last_used_at > TTL || + !r.fence || + codexAffinityIdentityFence(r.account_id) !== r.fence + ) { + enqueue(s, { + kind: "deleteScope", + key: rk, + scope: r.scope, + sql: "DELETE FROM threads WHERE row_key=? AND scope=?", + args: [rk, r.scope], + }); + continue; + } + rememberThreadKey(s, key, rk, r.scope, r.account_id); + if (s.poisoned) return []; + result.push({ + scope: r.scope, + accountId: r.account_id, + fence: r.fence, + createdAt: r.created_at, + lastUsedAt: r.last_used_at, + }); + } + for (const row of rows) consulted(s, `t:${rk}:${row.scope}`); + if (scopeName !== undefined) consulted(s, `t:${rk}:${scopeName}`); + else consulted(s, `t:${rk}:*`); + return result; + } catch { + warning(); + return []; + } +} +export function adoptStoredIssuer( + key: string, + now: number, +): { issuer: string; storedAccountId: string; storedFence: string | null } | undefined { + const s = usable(); + if (!s) return; + const rk = rowKey(s, key, "issuer"); + if (!rk || pending(s, rk, true) || s.consulted.has(`i:${rk}`)) return; + try { + const r = s + .db!.query( + "SELECT account_id, fence, last_used_at FROM issuers WHERE row_key=?", + ) + .get(rk) as { + account_id: string; + fence: string | null; + last_used_at: number; + } | null; + if (!r) { + consulted(s, `i:${rk}`); + return; + } + if ( + !Number.isFinite(r.last_used_at) || + r.last_used_at > now || + now - r.last_used_at > TTL + ) { + enqueue(s, { + kind: "issuerDelete", + key: rk, + sql: "DELETE FROM issuers WHERE row_key=?", + args: [rk], + }); + return; + } + const result = + r.fence && codexAffinityIdentityFence(r.account_id) === r.fence + ? r.account_id + : CODEX_UNKNOWN_CONVERSATION_STATE_ISSUER; + rememberIssuerKey(s, key, rk); + if (s.poisoned) return; + consulted(s, `i:${rk}`); + return { issuer: result, storedAccountId: r.account_id, storedFence: r.fence }; + } catch { + warning(); + return; + } +} +export function recordThreadBind( + key: string, + scopeName: string, + row: StoredThreadRow, +): void { + if (isRequestOwnedAffinityKey(key)) return; + const s = writableScope(row.accountId !== "__main__" && !!row.fence); + if (!s || row.accountId === "__main__" || !row.fence) return; + const rk = rowKey(s, key, "conversation"); + if (!rk) return; + rememberThreadKey(s, key, rk, scopeName, row.accountId); + if (s.poisoned) return; + enqueue(s, { + kind: "bind", + key: rk, + scope: scopeName, + sql: "INSERT INTO threads VALUES (?,?,?,?,?,?) ON CONFLICT(row_key,scope) DO UPDATE SET account_id=excluded.account_id,fence=excluded.fence,created_at=excluded.created_at,last_used_at=excluded.last_used_at", + args: [ + rk, + scopeName, + row.accountId, + row.fence, + row.createdAt, + row.lastUsedAt, + ], + }); +} +export function recordThreadTouch(key: string, scopeName: string): void { + const s = usable(); + if (!s) return; + const rk = rowKey(s, key, "conversation"); + if (!rk) return; + s.threads.set(`${rk}\0${scopeName}`, { key, scope: scopeName, rowKey: rk }); + scheduleTouch(s); +} +export function recordThreadDelete(key: string, scopeName?: string): void { + if (isRequestOwnedAffinityKey(key)) return; + const s = writableScope(true); + if (!s) return; + const rk = rowKey(s, key, "conversation"); + if (!rk) return; + const known = s.threadKeys.get(key); + if (scopeName === undefined) s.threadKeys.delete(key); + else if (known) { known.scopes.delete(scopeName); if (!known.scopes.size) s.threadKeys.delete(key); } + enqueue( + s, + scopeName === undefined + ? { + kind: "deleteKey", + key: rk, + sql: "DELETE FROM threads WHERE row_key=?", + args: [rk], + } + : { + kind: "deleteScope", + key: rk, + scope: scopeName, + sql: "DELETE FROM threads WHERE row_key=? AND scope=?", + args: [rk, scopeName], + }, + ); +} +export function recordThreadAccountDeleted(key: string, id: string): void { + if (isRequestOwnedAffinityKey(key)) return; + const s = writableScope(true); + if (!s) return; + const rk = rowKey(s, key, "conversation"); + if (!rk) return; + const known = s.threadKeys.get(key); + if (known) { + for (const [scopeName, account] of known.scopes) if (account === id) known.scopes.delete(scopeName); + if (!known.scopes.size) s.threadKeys.delete(key); + } + enqueue(s, { kind: "deleteKeyAccount", key: rk, sql: "DELETE FROM threads WHERE row_key=? AND account_id=?", args: [rk, id] }); +} +export function recordAccountPinsCleared(id: string): void { + const s = writableScope(true); + if (s) { + for (const [key, entry] of s.threadKeys) { + for (const [scopeName, account] of entry.scopes) if (account === id) entry.scopes.delete(scopeName); + if (!entry.scopes.size) s.threadKeys.delete(key); + } + enqueue(s, { + kind: "deleteAccount", + sql: "DELETE FROM threads WHERE account_id=?", + args: [id], + }); + } +} +export function recordAllCleared(): void { + const s = writableScope(true); + if (s) { + s.threadKeys.clear(); s.issuerKeys.clear(); + enqueue(s, { + kind: "clearAll", + sql: "DELETE FROM threads; DELETE FROM issuers", + args: [], + }); + } +} +/** A manual account switch clears pins but keeps the issuers of carried state. */ +export function recordThreadsCleared(): void { + const s = writableScope(true); + if (s) { + s.threadKeys.clear(); + enqueue(s, { kind: "clearThreads", sql: "DELETE FROM threads", args: [] }); + } +} +/** Test seam: feed the anchor observer directly, as a future derivation path might. */ +export function noteCodexAffinityAnchorForTests(key: string, family: string, thread: string): void { + observeAnchor(key, family, thread); +} +export function recordIssuerSet( + key: string, + id: string, + fence: string | null, + lastUsedAt: number, +): void { + if (isRequestOwnedAffinityKey(key)) return; + const s = writableScope(id !== "__main__"); + if (!s || id === "__main__") return; + const rk = rowKey(s, key, "issuer"); + if (!rk) return; + rememberIssuerKey(s, key, rk); + if (s.poisoned) return; + enqueue(s, { + kind: "issuerSet", + key: rk, + sql: "INSERT INTO issuers VALUES (?,?,?,?) ON CONFLICT(row_key) DO UPDATE SET account_id=excluded.account_id,fence=excluded.fence,last_used_at=excluded.last_used_at", + args: [rk, id, fence, lastUsedAt], + }); +} +export function recordIssuerTouch(key: string): void { + const s = usable(); + if (!s) return; + const rk = rowKey(s, key, "issuer"); + if (!rk) return; + s.issuers.set(rk, { key, rowKey: rk }); + scheduleTouch(s); +} +export function recordIssuerDelete(key: string): void { + if (isRequestOwnedAffinityKey(key)) return; + const s = writableScope(true); + if (!s) return; + const rk = rowKey(s, key, "issuer"); + if (rk) { + s.issuerKeys.delete(key); + enqueue(s, { + kind: "issuerDelete", + key: rk, + sql: "DELETE FROM issuers WHERE row_key=?", + args: [rk], + }); + } +} +export function recordIssuersCleared(): void { + const s = writableScope(true); + if (s) { + s.issuerKeys.clear(); + enqueue(s, { kind: "clearIssuers", sql: "DELETE FROM issuers", args: [] }); + } +} +export function flushCodexAffinityStoreForTests(): void { + if (current && !isPassiveRead()) flush(current, false); +} +export function resetCodexAffinityStoreForTests(): void { + if (current) { + flush(current, false); + retire(); + } + // Model a fresh process: nothing carried from an earlier scope, nothing known to be stale. + carried = undefined; + persistedHome = undefined; + needsClear = false; +} diff --git a/src/codex/routing/thread-affinity.ts b/src/codex/routing/thread-affinity.ts index 643d64fc5c4..4ada4044eaa 100644 --- a/src/codex/routing/thread-affinity.ts +++ b/src/codex/routing/thread-affinity.ts @@ -6,10 +6,13 @@ import type { CodexThreadLineage } from "../lineage"; import type { CodexQuotaScope } from "./health-store"; import type { TransientProbeLease } from "../../routing/probe-lease"; import { clearPoolRecoveryState } from "../../routing/probe-lease"; +import { identityFence, adoptStoredThreadRows, adoptStoredIssuer, CODEX_UNKNOWN_CONVERSATION_STATE_ISSUER, registerCodexAffinityLiveState, recordThreadBind, recordThreadTouch, recordThreadDelete, recordThreadAccountDeleted, recordAccountPinsCleared, recordAllCleared, recordThreadsCleared, recordIssuerSet, recordIssuerTouch, recordIssuerDelete, recordIssuersCleared } from "./thread-affinity-store"; +export { CODEX_UNKNOWN_CONVERSATION_STATE_ISSUER } from "./thread-affinity-store"; export type ThreadAffinityEntry = { accountId: string; generation: number; + identityFence?: string; createdAt: number; lastUsedAt: number; // Last time the bound account's quota threshold was re-evaluated for this @@ -200,15 +203,32 @@ let threadAffinityEntryTotal = 0; * Which pool account minted the conversation's carried OpenAI state * (`previous_response_id`, encrypted reasoning, provider conversation/file ids). * Keyed by the same affinity key as {@link threadAccountMap}, bounded the same - * way, and process-local — raw account ids never reach a log. + * way. Durable rows use a separate keyed digest; raw account ids never reach a log. */ type ConversationStateIssuerEntry = { accountId: string; lastUsedAt: number; + fence?: string; + storedAccountId?: string; + storedFence?: string | null; }; const conversationStateIssuerMap = new Map(); +export function registerThreadAffinityLiveState(): void { +registerCodexAffinityLiveState({ + thread: (key, scope) => threadAccountMap.get(key)?.get(scope as ThreadAffinityScope), + issuer: key => { + const entry = conversationStateIssuerMap.get(key); + return entry && { accountId: entry.storedAccountId ?? entry.accountId, fence: entry.storedAccountId ? entry.storedFence ?? undefined : entry.fence, lastUsedAt: entry.lastUsedAt }; + }, + clearLive: () => { threadAccountMap.clear(); threadAffinityEntryTotal = 0; conversationStateIssuerMap.clear(); }, +}); +} +registerThreadAffinityLiveState(); + export function clearThreadAccountMap(options: { preserveConversationStateIssuers?: boolean } = {}): void { + if (options.preserveConversationStateIssuers) recordThreadsCleared(); + else recordAllCleared(); threadAccountMap.clear(); threadAffinityEntryTotal = 0; // A refresh cooldown is per-account runtime state learned alongside these bindings. Leaving it @@ -225,6 +245,7 @@ export function clearThreadAccountMap(options: { preserveConversationStateIssuer } export function clearConversationStateIssuerMap(): void { + recordIssuersCleared(); conversationStateIssuerMap.clear(); } @@ -232,6 +253,7 @@ export function clearThreadAccountMapForAccount( accountId: string, reason: CodexAffinityReason = "unusable", ): void { + recordAccountPinsCleared(accountId); for (const [threadId, affinities] of threadAccountMap) { for (const [scope, entry] of affinities) { if (entry.accountId === accountId && affinities.delete(scope)) { @@ -247,6 +269,7 @@ function pruneConversationStateIssuers(now: number): void { for (const [key, entry] of conversationStateIssuerMap) { if (now - entry.lastUsedAt > CODEX_THREAD_AFFINITY_IDLE_TTL_MS) { conversationStateIssuerMap.delete(key); + recordIssuerDelete(key); } } while (conversationStateIssuerMap.size > CODEX_THREAD_AFFINITY_MAX_ENTRIES) { @@ -260,22 +283,30 @@ function pruneConversationStateIssuers(now: number): void { } if (!oldestKey) break; conversationStateIssuerMap.delete(oldestKey); + recordIssuerDelete(oldestKey); } } /** * Record the pool account that just issued carried conversation state for this - * binding key. In-memory only; the id is never written to a request log. + * binding key. Persisted when an anchor is available; the id is never logged. */ export function rememberConversationStateIssuer( bindingKey: string, accountId: string, now = Date.now(), + credential?: { generation: number; chatgptAccountId: string }, ): void { if (!bindingKey.trim() || !accountId.trim()) return; if (!admissibleAffinityComponent(bindingKey) || !admissibleAffinityComponent(accountId)) return; pruneConversationStateIssuers(now); - conversationStateIssuerMap.set(bindingKey, { accountId, lastUsedAt: now }); + const record = accountId === MAIN_CODEX_ACCOUNT_ID ? undefined : readCodexAccountRecord(accountId); + const fence = record?.credential && record.deletedAt == null && credential + && record.generation === credential.generation && record.credential.chatgptAccountId === credential.chatgptAccountId + ? identityFence(record.quotaHistoryIdentity) : undefined; + if (accountId === MAIN_CODEX_ACCOUNT_ID) recordIssuerDelete(bindingKey); + else if (accountId !== CODEX_UNKNOWN_CONVERSATION_STATE_ISSUER) recordIssuerSet(bindingKey, accountId, fence ?? null, now); + conversationStateIssuerMap.set(bindingKey, { accountId, lastUsedAt: now, fence }); pruneConversationStateIssuers(now); } @@ -286,12 +317,25 @@ export function peekConversationStateIssuer( ): string | undefined { if (!bindingKey.trim() || !admissibleAffinityComponent(bindingKey)) return undefined; pruneConversationStateIssuers(now); - const entry = conversationStateIssuerMap.get(bindingKey); + recordIssuerTouch(bindingKey); + let entry = conversationStateIssuerMap.get(bindingKey); + if (!entry) { + const stored = adoptStoredIssuer(bindingKey, now); + if (stored !== undefined) { + entry = { accountId: stored.issuer, lastUsedAt: now, storedAccountId: stored.storedAccountId, storedFence: stored.storedFence }; + conversationStateIssuerMap.set(bindingKey, entry); + pruneConversationStateIssuers(now); + } + } if (!entry) return undefined; entry.lastUsedAt = now; return entry.accountId; } +export function peekConversationStateStoredIssuerAccount(bindingKey: string): string | undefined { + return conversationStateIssuerMap.get(bindingKey)?.storedAccountId; +} + /** * Why a binding was released, held until that thread's next resolve can report it (#4546). * @@ -349,9 +393,25 @@ function getThreadAffinityForScope( scope: ThreadAffinityScope, ): ThreadAffinityEntry | undefined { if (!admissibleAffinityComponent(threadId)) return undefined; + recordThreadTouch(threadId, scope); + if (!threadAccountMap.get(threadId)?.get(scope)) adoptThreadAffinities(threadId, Date.now(), scope); return threadAccountMap.get(threadId)?.get(scope); } +function adoptThreadAffinities(threadId: string, now: number, scopeName?: ThreadAffinityScope): void { + for (const row of adoptStoredThreadRows(threadId, now, scopeName)) { + const record = readCodexAccountRecord(row.accountId); + if (!record?.credential || record.deletedAt != null || identityFence(record.quotaHistoryIdentity) !== row.fence) continue; + const scope = row.scope as ThreadAffinityScope; + const affinities = threadAccountMap.get(threadId) ?? new Map(); + if (affinities.has(scope)) continue; + affinities.set(scope, { accountId: row.accountId, generation: record.generation, identityFence: row.fence, createdAt: row.createdAt, lastUsedAt: row.lastUsedAt, lastReevalAt: now }); + threadAccountMap.set(threadId, affinities); + threadAffinityEntryTotal += 1; + } + pruneLruThreadAffinities(); +} + export function getThreadAffinity(threadId: string, quotaScope?: CodexQuotaScope): ThreadAffinityEntry | undefined { return getThreadAffinityForScope(threadId, threadAffinityScope(quotaScope)); } @@ -367,6 +427,7 @@ export function getModelDetourAffinity( function deleteThreadAffinityForScope(threadId: string, scope: ThreadAffinityScope): void { if (!admissibleAffinityComponent(threadId)) return; + recordThreadDelete(threadId, scope); const affinities = threadAccountMap.get(threadId); if (!affinities) return; if (affinities.delete(scope)) { @@ -391,10 +452,12 @@ export function deleteModelDetourAffinity( /** Remove only the matching failed account's affinities for one thread. */ export function deleteThreadAffinitiesForAccount(threadId: string, accountId: string): void { if (!admissibleAffinityComponent(threadId) || !admissibleAffinityComponent(accountId)) return; + recordThreadAccountDeleted(threadId, accountId); const affinities = threadAccountMap.get(threadId); if (!affinities) return; for (const [scope, entry] of affinities) { if (entry.accountId === accountId && affinities.delete(scope)) { + recordThreadDelete(threadId, scope); threadAffinityEntryTotal = Math.max(0, threadAffinityEntryTotal - 1); } } @@ -467,6 +530,7 @@ function pruneExpiredThreadAffinities(now: number): void { for (const [threadId, affinities] of threadAccountMap) { for (const [scope, entry] of affinities) { if (isThreadAffinityExpired(entry, now) && affinities.delete(scope)) { + recordThreadDelete(threadId, scope); threadAffinityEntryTotal = Math.max(0, threadAffinityEntryTotal - 1); } } @@ -510,15 +574,21 @@ function bindThreadAffinityForScope( const record = accountId === MAIN_CODEX_ACCOUNT_ID ? undefined : readCodexAccountRecord(accountId); if (accountId !== MAIN_CODEX_ACCOUNT_ID && (!record?.credential || record.deletedAt != null)) return; pruneExpiredThreadAffinities(now); + recordThreadTouch(threadId, scope); const affinities = threadAccountMap.get(threadId) ?? new Map(); const previous = affinities.get(scope); - affinities.set(scope, { + const fence = identityFence(record?.quotaHistoryIdentity); + const entry: ThreadAffinityEntry = { accountId, generation: accountId === MAIN_CODEX_ACCOUNT_ID ? 0 : record!.generation, + identityFence: fence, createdAt: previous?.createdAt ?? now, lastUsedAt: now, lastReevalAt: now, - }); + }; + if (fence) recordThreadBind(threadId, scope, { scope, accountId, fence, createdAt: entry.createdAt, lastUsedAt: now }); + else recordThreadDelete(threadId, scope); + affinities.set(scope, entry); if (!previous) threadAffinityEntryTotal += 1; threadAccountMap.set(threadId, affinities); pruneLruThreadAffinities(); @@ -548,14 +618,14 @@ export function bindModelDetourAffinity( export function getThreadAffinityScopes( threadId: string, ): ReadonlyMap | undefined { + adoptThreadAffinities(threadId, Date.now()); return threadAccountMap.get(threadId); } /** * Move one scope's binding from the pre-#4546 RAW parent key onto the key this thread uses now. * - * Bindings and the key that derives them are process-local, so an ordinary restart already - * discards every binding and there is nothing to migrate. The case this exists for is the + * Legacy raw-parent keys are process-local and are not persisted. The case this exists for is the * narrow one: a code swap under a live conversation, where the map still holds entries made by * the old rule. Rebinding those cold is precisely the defect the lineage work exists to prevent, * so the conversation keeps its account and the legacy entry is retired in the same step. diff --git a/src/lib/config-ownership.ts b/src/lib/config-ownership.ts index a3494002b34..9b799fa9a83 100644 --- a/src/lib/config-ownership.ts +++ b/src/lib/config-ownership.ts @@ -53,6 +53,10 @@ const INITIAL_OWNED_PATHS = [ "config-mutation.sqlite-journal", "config-mutation.sqlite-shm", "config-mutation.sqlite-wal", + "codex-affinity.sqlite", + "codex-affinity.sqlite-journal", + "codex-affinity.sqlite-shm", + "codex-affinity.sqlite-wal", "local-credentials.json", "local-credential-observers", "local-credential-publication.sqlite", diff --git a/src/lib/spend-ledger-owner.ts b/src/lib/spend-ledger-owner.ts index 40cf6dd07b4..46833f4de63 100644 --- a/src/lib/spend-ledger-owner.ts +++ b/src/lib/spend-ledger-owner.ts @@ -47,6 +47,26 @@ let boundLedgerHome: string | null = null; */ let ownerGeneration = 0; const releaseHooks: Array<() => void> = []; +const acquiredHooks: Array<(home: string) => void> = []; + +/** Run once after each new ownership generation is acquired. */ +export function onSpendLedgerOwnerAcquired(hook: (home: string) => void): void { + acquiredHooks.push(hook); +} +const releasingHooks: Array<() => void> = []; +let releasing = false; + +/** Run before the final lease is released, while existing storage tokens remain valid. */ +export function onSpendLedgerOwnerReleasing(hook: () => void): void { + releasingHooks.push(hook); +} + +function assertNotReleasing(): void { + if (releasing) throw new SpendLedgerOwnerError( + "SPEND_LEDGER_OWNER_NOT_HELD", + "Spend-ledger ownership is required before the shared ledger can be used.", + ); +} /** * Run when the last lease on a state directory goes away. @@ -142,6 +162,7 @@ export function spendLedgerRestartEnvironment( * can evict a live owner or mistake a reused process identity for this lease. */ export function acquireSpendLedgerOwner(configDir = getConfigDir()): SpendLedgerOwnerLease { + assertNotReleasing(); const requestedHome = stateDirectoryIdentity(configDir); const busyTimeout = restartHandoffWaitMs(); if (boundLedgerHome !== null && boundLedgerHome !== requestedHome) { @@ -194,7 +215,11 @@ export function acquireSpendLedgerOwner(configDir = getConfigDir()): SpendLedger activeOwner = { home: prepared.home, database, references: 1 }; ownerGeneration += 1; - return leaseFor(activeOwner); + const owner = activeOwner; + for (const hook of acquiredHooks) { + try { hook(owner.home); } catch { /* one hook must not prevent acquisition */ } + } + return leaseFor(owner); } function leaseFor(owner: ActiveOwner): SpendLedgerOwnerLease { @@ -204,6 +229,16 @@ function leaseFor(owner: ActiveOwner): SpendLedgerOwnerLease { if (released) return; released = true; if (activeOwner !== owner || owner.references < 1) return; + if (owner.references === 1) { + releasing = true; + try { + for (const hook of releasingHooks) { + try { hook(); } catch { /* a flush hook must not prevent release */ } + } + } finally { + releasing = false; + } + } owner.references -= 1; if (owner.references > 0) return; activeOwner = null; @@ -265,6 +300,7 @@ function trustedStorage(storage: SpendLedgerStorage): { readonly path: string; r * choose the destination, which is the thing ownership is supposed to decide. */ export function mintSpendLedgerStorage(fileName: string): SpendLedgerStorage { + assertNotReleasing(); if (fileName.includes("/") || fileName.includes("\\") || fileName === "." || fileName === "..") { throw new SpendLedgerOwnerError( "SPEND_LEDGER_OWNER_UNAVAILABLE", diff --git a/src/server/responses/account-change-state.ts b/src/server/responses/account-change-state.ts index c76130dfb21..d594e3362dd 100644 --- a/src/server/responses/account-change-state.ts +++ b/src/server/responses/account-change-state.ts @@ -12,6 +12,7 @@ import { conversationStateAccountId } from "../../codex/request-owned-affinity"; import type { CodexAuthContext } from "../../codex/auth-context"; +import { CODEX_UNKNOWN_CONVERSATION_STATE_ISSUER, peekConversationStateStoredIssuerAccount } from "../../codex/routing/thread-affinity"; import { peekConversationStateIssuer, rememberConversationStateIssuer, @@ -239,7 +240,8 @@ export function rememberServingConversationStateIssuer( ): void { const binding = conversationStateBindingFromAuth(authCtx, fallbackAffinityKey); if (!binding) return; - rememberConversationStateIssuer(binding.bindingKey, binding.accountId); + rememberConversationStateIssuer(binding.bindingKey, binding.accountId, undefined, + authCtx.kind === "pool" ? { generation: authCtx.generation, chatgptAccountId: authCtx.chatgptAccountId } : undefined); } export interface ApplyAccountChangeConversationStateScrubArgs { @@ -321,7 +323,9 @@ export function accountChangeFileReferenceRefusal( const { body, bindingKey, servingAccountId, priorAccountId } = args; if (!servingAccountId || !bindingKey) return undefined; const issuer = peekConversationStateIssuer(bindingKey); - const accountChanged = (issuer != null && issuer !== servingAccountId) + const accountChanged = (issuer === CODEX_UNKNOWN_CONVERSATION_STATE_ISSUER + ? peekConversationStateStoredIssuerAccount(bindingKey) !== servingAccountId + : issuer != null && issuer !== servingAccountId) || (priorAccountId != null && priorAccountId !== servingAccountId); if (!accountChanged) return undefined; // Checked against the carriers directly rather than through the portability verdict: that diff --git a/src/server/responses/compact.ts b/src/server/responses/compact.ts index 01f90d542be..07e772c0575 100644 --- a/src/server/responses/compact.ts +++ b/src/server/responses/compact.ts @@ -1,5 +1,6 @@ import { conversationStateAccountId, releaseRequestOwnedMainOnOutcome, isKeyedRequestOwnedMain } from "../../codex/request-owned-affinity"; import { CodexInstallationIdUnavailableError } from "../../codex/installation-id"; +import { MAIN_CODEX_ACCOUNT_ID } from "../../codex/account-id"; import { isolateCodexPoolClientMetadata } from "../../codex/forward-transport-headers"; import { captureAccountAutoPauseAttempt, wasAccountAutoPaused, wasPermanentAccountRefusal } from "../../oauth/account-auto-pause"; import { spendLedgerStorageErrorResponse } from "./spend-storage-error"; @@ -985,6 +986,7 @@ export async function handleResponsesCompact( if (refusal) return refusal; applyAccountChangeConversationStateScrub({ body: raw, + headers, bindingKey: binding.bindingKey, servingAccountId: binding.accountId, logCtx, @@ -1003,7 +1005,11 @@ export async function handleResponsesCompact( && compactProvider.supportsNativeCompactEndpoint === true ? buildResponsesTransport({ ...compactProvider, apiKey: compactProvider.apiKey ? resolveProviderApiKey(compactProvider.apiKey) : undefined }, { headers: req.headers }) : undefined; - if (gatewayTransport) headers = new Headers(gatewayTransport.headers); + if (gatewayTransport) { + headers = new Headers(gatewayTransport.headers); + const binding = conversationStateBindingFromAuth(authCtx, codexPoolAffinityKey(req.headers)); + if (binding) applyAccountChangeConversationStateScrub({ body: compactBody, headers, bindingKey: binding.bindingKey, servingAccountId: binding.accountId, logCtx }); + } // Native v1 bypasses the adapter serializer. Bind the same replay provenance as ordinary // turns, but leave canonical compact's established account-state handling unchanged. const gatewayReplayParsed = gatewayTransport ? parseRequest(raw) : undefined; @@ -1159,7 +1165,9 @@ export async function handleResponsesCompact( onPhysicalDispatch?: () => void, ): Promise => { // A gateway send carries only its own transport headers, whatever recovery handed in. + // An account-change scrub that removed the turn state from the send headers still applies. let wireHeaders = gatewayTransport ? new Headers(gatewayTransport.headers) : sendHeaders; + if (gatewayTransport && !sendHeaders.has("x-codex-turn-state")) wireHeaders.delete("x-codex-turn-state"); sendHeaders = wireHeaders; const buildCompactSendBody = () => { if (gatewayReplayParsed) bindRouteReasoningReplayScope({ @@ -1388,6 +1396,8 @@ export async function handleResponsesCompact( outcomeCtx = replay.authCtx; compactProvider = replay.provider; headers = replay.headers; + const replayBinding = conversationStateBindingFromAuth(replay.authCtx, codexPoolAffinityKey(req.headers)); + if (replayBinding) applyAccountChangeConversationStateScrub({ body: compactBody, headers, bindingKey: replayBinding.bindingKey, servingAccountId: replayBinding.accountId, logCtx }); logCtx.accountLogLabel = codexAuthContextLogLabel(replay.authCtx, config); try { upstream = await sendCompactAttempt(compactProvider, headers, "single", authCtx); @@ -1431,15 +1441,21 @@ export async function handleResponsesCompact( recordCompactPoolOutcome(outcomeCtx, outcome); return formatErrorResponse(502, "upstream_error", "Failed to connect to compact upstream"); }; - const scrubCompactStateForAlternate = (alternateAuthCtx: CodexAuthContext): void => { - const binding = conversationStateBindingFromAuth( - alternateAuthCtx, - compactAlternateAffinityKey(authCtx, () => codexPoolAffinityKey(req.headers)), - ); + const scrubCompactStateForAlternate = (alternateAuthCtx: CodexAuthContext, alternateHeaders: Headers): void => { + const affinityKey = compactAlternateAffinityKey(authCtx, () => codexPoolAffinityKey(req.headers)) + ?? codexPoolAffinityKey(req.headers); + const priorAccountId = conversationStateAccountId(authCtx); + // An unkeyed caller-owned main alternate has no binding of its own, but moving off the issuing + // account still makes the carried state foreign. Scrub for this request only; nothing persists. + const binding = conversationStateBindingFromAuth(alternateAuthCtx, affinityKey) + ?? (alternateAuthCtx.kind === "main" && priorAccountId && affinityKey + ? { bindingKey: affinityKey, accountId: priorAccountId === MAIN_CODEX_ACCOUNT_ID ? "__caller_main__" : MAIN_CODEX_ACCOUNT_ID } + : null); if (!binding) return; for (const body of [raw, compactBody]) { applyAccountChangeConversationStateScrub({ body, + headers: alternateHeaders, bindingKey: binding.bindingKey, servingAccountId: binding.accountId, priorAccountId: conversationStateAccountId(authCtx), @@ -1545,7 +1561,7 @@ export async function handleResponsesCompact( await upstream.body?.cancel().catch(() => undefined); outcomeCtx = alternate.authCtx; logCtx.accountLogLabel = codexAuthContextLogLabel(alternate.authCtx, config); - scrubCompactStateForAlternate(alternate.authCtx); + scrubCompactStateForAlternate(alternate.authCtx, alternate.headers); try { upstream = await sendCompactAttempt(alternate.provider, alternate.headers, "single", alternate.authCtx); } catch (err) { @@ -1602,7 +1618,7 @@ export async function handleResponsesCompact( // B's identity before B's admission, so every budget and spend check runs against B. A's // response stays intact until B is actually sent. logCtx.accountLogLabel = codexAuthContextLogLabel(alternate.authCtx, config); - scrubCompactStateForAlternate(alternate.authCtx); + scrubCompactStateForAlternate(alternate.authCtx, alternate.headers); const recordFirstMove = () => { recordCompactPoolOutcome(authCtx, firstStatus, { retryAfter: firstRetryAfter, resetAt: firstResetAt }); void upstream.body?.cancel().catch(() => undefined); diff --git a/structure/INDEX.md b/structure/INDEX.md index 5e9f69f973e..b368a06639d 100644 --- a/structure/INDEX.md +++ b/structure/INDEX.md @@ -98,6 +98,7 @@ Per-vendor contracts and the adapter authority that constructs them. | [`providers/anthropic-account-pool.md`](providers/anthropic-account-pool.md) | Anthropic OAuth instances (primary and Pool 2), account pause, model routes, quota labels, and pool-bound helpers, quota, reset grants and management surfaces. | | [`providers/oauth-code-display-login.md`](providers/oauth-code-display-login.md) | Headless code-display OAuth login: flow ownership, expiry, unsupported providers, single-operator store. | | [`providers/openai-tiers.md`](providers/openai-tiers.md) | Pool/Direct account modes, API-key separation, and the public provider and quota contract. | +| [`providers/codex-pool-affinity.md`](providers/codex-pool-affinity.md) | Restart persistence of Codex pool pins and conversation-state issuers: store, fences, single-writer lease, fail-closed recovery. | | [`providers/pool-credit-renewal.md`](providers/pool-credit-renewal.md) | Independent credit-evidence renewal for opted-in exhausted Codex pool accounts. | | [`providers/openai-accounts.md`](providers/openai-accounts.md) | Migration and restore, wire identity, store concurrency, pool ordering and exclusions, quota observations, and account-bound retention. | | [`providers/codex-round-robin-placement.md`](providers/codex-round-robin-placement.md) | Round-robin new-conversation placement preferring accounts under their effective auto-switch threshold, with all-over fallback and bound, failover and lineage boundaries. | @@ -294,6 +295,8 @@ A source area can be described by more than one doc, because these docs are orga | `src/codex/request-owned-affinity.ts` | [`providers/codex-request-owned-affinity.md`](providers/codex-request-owned-affinity.md) | | `src/codex/request-owned-main-pin.ts` | [`providers/codex-request-owned-affinity.md`](providers/codex-request-owned-affinity.md) | | `src/codex/routing/selection.ts` | [`providers/codex-round-robin-placement.md`](providers/codex-round-robin-placement.md) | +| `src/codex/routing/thread-affinity-store.ts` | [`providers/codex-pool-affinity.md`](providers/codex-pool-affinity.md) | +| `src/codex/routing/thread-affinity.ts` | [`providers/codex-pool-affinity.md`](providers/codex-pool-affinity.md) | | `src/codex/runtime.ts` | [`catalog-effort-clamp.md`](catalog-effort-clamp.md) | | `src/codex/shim.ts` | [`codex-cli-update.md`](codex-cli-update.md) | | `src/codex/signed-in-identity.ts` | [`providers/openai-signed-in-preservation.md`](providers/openai-signed-in-preservation.md) | @@ -327,6 +330,7 @@ A source area can be described by more than one doc, because these docs are orga | `src/lib/account-auto-pause-response.ts` | [`account-auto-pause.md`](account-auto-pause.md) | | `src/lib/advisor-activation.ts` | [`advisor.md`](advisor.md) | | `src/lib/bounded-body.ts` | [`transports/timeouts.md`](transports/timeouts.md) | +| `src/lib/config-ownership.ts` | [`providers/codex-pool-affinity.md`](providers/codex-pool-affinity.md) | | `src/lib/decision-quota-sink.ts` | [`providers/jev-decision.md`](providers/jev-decision.md) | | `src/lib/gui-pair-intent.ts` | [`remote-link.md`](remote-link.md) | | `src/lib/local-upstream.ts` | [`transports/timeouts.md`](transports/timeouts.md) | diff --git a/structure/manifest.json b/structure/manifest.json index 494781fd41e..741745dc1d7 100644 --- a/structure/manifest.json +++ b/structure/manifest.json @@ -697,6 +697,17 @@ "src/providers/codex-capacity.ts" ] }, + { + "path": "providers/codex-pool-affinity.md", + "tier": 4, + "title": "Durable Codex Pool Affinity", + "scope": "Restart persistence of Codex pool pins and conversation-state issuers: store, fences, single-writer lease, fail-closed recovery.", + "documents": [ + "src/codex/routing/thread-affinity-store.ts", + "src/codex/routing/thread-affinity.ts", + "src/lib/config-ownership.ts" + ] + }, { "path": "providers/pool-credit-renewal.md", "tier": 4, diff --git a/structure/providers/codex-pool-affinity.md b/structure/providers/codex-pool-affinity.md new file mode 100644 index 00000000000..756d667e472 --- /dev/null +++ b/structure/providers/codex-pool-affinity.md @@ -0,0 +1,14 @@ +# Durable Codex Pool Affinity + +This doc owns how Codex pool session pins and conversation-state issuers survive a proxy restart. +`src/codex/routing/thread-affinity.ts` keeps the live maps and calls the store at every bind, delete, clear and lookup. +The conversation key, cohort anchors and lineage are owned by [OpenAI Provider Account Modes](openai-tiers.md); +the single-writer lease is owned by [Responses spend](../transports/responses-spend.md). + +`src/codex/routing/thread-affinity-store.ts` restores eligible pool bindings after a graceful proxy restart for up to 24 hours idle. Session-bearing requests and session-less requests anchored on their immediate parent have derivable anchors. Deeper session-less chains, keys derived under another config home, legacy raw-parent keys and evicted anchors remain memory-only. Removed, re-logged, expired or identity-less accounts are not restored; normal selection and usability rules still apply. + +The config home contains `codex-affinity.sqlite`, mode 0600 with a hardened Windows ACL. Its v1 schema has `meta` (store secret and clean flag), `threads` (scoped bindings), and `issuers` (conversation state issuers). Row keys are domain-separated HMACs of the cohort anchor under the store's own secret. Each row stores the local pool account id (the label that config.json and the credential store in this directory already key the account by, as the Claude affinity store does), an identity fence digest and timestamps. Session ids, conversation keys (raw or process-local), emails, ChatGPT account ids and tokens are not stored; a keyed digest of the pool id would hide nothing from a reader of this directory, which holds both the store secret and the account list. The identity fence derives from `quotaHistoryIdentity`, captured at bind and at issuance. Issuance requires both generation and `chatgptAccountId` to match the current record. `__main__` pins and issuers are never persisted. Request-owned keys (`isRequestOwnedAffinityKey`, from `src/codex/request-owned-affinity-key.ts`) are refused at the store's row-key derivation and anchor observer, so they are never anchored, written or restored, as the [request-owned persistence contract](codex-request-owned-affinity.md#persistence-contract) requires. An unknown restored issuer scrubs continuation state; uploaded files are refused when the stored account differs from the serving account, as for known account changes and prior-account moves. + +The spend-ledger lease is the single-writer authority. The final releasing hook flushes pending work and marks the store clean before ownership is released; it does so even when the release happens inside a passive read, because it commits only work recorded outside one. A crash, failed final flush or poisoned store leaves the clean flag unset, so the next owner discards rows. Structural changes use an ordered write log; UPDATE-only touches read live timestamps at flush, avoiding stale timestamps and resurrection. The 24-hour idle limit bounds reuse. Expired rows are removed by the next prune that commits: one is attempted when the store opens at lease acquisition, on an hourly timer while it stays open, and after every failed flush, including in a poisoned store. A prune can still be delayed or fail: a lease acquired inside a passive read does not open the store, a store that failed to open is disabled and cannot prune, a prune transaction can roll back, and timers can run late. SQLite secure_delete overwrites freed pages in the database file, but not filesystem snapshots, backups or storage remapping; its transient rollback journal is removed after each commit. The store secret pseudonymizes row keys and does not protect integrity from a local process that can already read the config directory. Pruning also removes future-dated rows and bounds each table to 2,048 entries, evicting model detours first. Other passive reads do not open, adopt or mutate the store. Live affinity survives a lease change in one process. A persistable change to pins or issuers made while the home's database is not writable (between two leases of one process, or while a scope could not open it) marks that database stale; the next scope that opens it clears it before use, so a restart restores nothing rather than a row the process had replaced or deleted. This also drops rows for conversations the process never loaded, which loses pins but never revives one; a serving proxy holds one lease for its whole life and does not reach this path. Row keys and anchors carry across a lease change in the same home, including past a scope that failed to open, so deletes still find their rows after an anchor is evicted. A change made after the final release, before the process exits without taking the lease again, cannot be saved: the lease is gone and another process may already own the database, so the next process can restore the row that change replaced. Such a row still has to pass the identity fence and the resolver's usability checks, and a serving proxy releases its lease only after its listeners have stopped. A manual account switch deletes saved pins and keeps saved issuers, matching the live maps; a full reset deletes both. + +`src/lib/config-ownership.ts` includes the database and sidecars in `INITIAL_OWNED_PATHS`; existing homes use `recordOwnedConfigPath`, whose ownership race is tracked in [#8093](https://github.com/lidge-jun/opencodex/issues/8093). A home without an ownership manifest, created before ownership tracking, still uses the store; uninstall removes nothing from such a home, as for every other file in it. `tests/codex-integration/codex-affinity-store.test.ts`, `tests/codex-integration/codex-affinity-restart.test.ts` and `tests/codex-integration/codex-affinity-request-owned.test.ts` cover store, restart and request-owned exclusion behavior. diff --git a/structure/providers/codex-request-owned-affinity.md b/structure/providers/codex-request-owned-affinity.md index d9945fff821..9e0d73efecd 100644 --- a/structure/providers/codex-request-owned-affinity.md +++ b/structure/providers/codex-request-owned-affinity.md @@ -66,7 +66,9 @@ is not caller-scoped by design and is unchanged by this feature. Persistence of thread affinity must, for every key where `isRequestOwnedAffinityKey` is true: never register an anchor for it, never serialize its thread rows (any scope, including model detours) or issuer rows, and never adopt a restored row into it. The conversation-state key carries the same prefix, so the predicate -covers issuer records too. +covers issuer records too. The durable store enforces this in `src/codex/routing/thread-affinity-store.ts` +([Durable Codex Pool Affinity](codex-pool-affinity.md)); `tests/codex-integration/codex-affinity-request-owned.test.ts` +proves it across a flush and restart. ## Tests diff --git a/structure/providers/openai-tiers.md b/structure/providers/openai-tiers.md index 0eafaec4b20..724149eed58 100644 --- a/structure/providers/openai-tiers.md +++ b/structure/providers/openai-tiers.md @@ -116,7 +116,7 @@ parent derives for itself, so a chain of parent-only turns converges rather than every depth. No caller-supplied identifier reaches Pool state. Which requests bind at all is unchanged -- a bare `thread-id` with neither a session nor a parent has no family anchor and stays unbound. Components are trimmed and bounded at 512 bytes, missing or -oversized values stay unbound, raw identifiers and durable hashes are never stored, and +oversized values stay unbound, raw identifiers never enter Pool state, and account-qualified selectors skip both lookup and mutation. Selection, subagent fallback preview, and terminal outcome accounting carry the same key so route planning cannot preview one account and authenticate another. A transient-failure streak does not delete the live binding that @@ -141,7 +141,7 @@ a behaviour change, not a refinement. It also interacts with the send-budget and thread's own conversation key, its immediate parent's thread id, and the transitive root, so a grandchild resolves to the same root as its parent. Records are held per authenticated scope (an HMAC of the caller's Authorization under the same process-local key), and bounded in both -dimensions -- idle TTL and an LRU cap on records per scope, and an LRU cap on scopes. +dimensions -- idle TTL and an LRU cap on records per scope, and an LRU cap on scopes. The key stays process-local; restart persistence uses its own secret ([Durable Codex Pool Affinity](codex-pool-affinity.md)). First placement is largely subsumed by cohort keying: a member of a tree any other member has already bound resolves to that same binding, so there is nothing to place. `pickLineageServingAccount` diff --git a/structure/transports/responses-spend.md b/structure/transports/responses-spend.md index fd0cbc511aa..1cc505212a6 100644 --- a/structure/transports/responses-spend.md +++ b/structure/transports/responses-spend.md @@ -368,7 +368,15 @@ identically with and without configured ceilings: observe-only still appends, se Two servers in one process and one directory share a reference-counted lease; that process cannot hold two directories at once. Sequential ownership is allowed and concurrent ownership is not: releasing the final reference discards the singleton, so a later directory replays its own -journal instead of inheriting figures. A ledger records the ownership it was built under and +journal instead of inheriting figures. +Final-release hooks run before that discard while existing storage tokens remain valid; each hook +is isolated from errors in the others. Acquiring another lease or minting storage during these +hooks is refused. Releasing a non-final reference or releasing the same lease twice runs no hooks. +Acquired hooks run once per new ownership generation, after the owner is recorded and before +`acquireSpendLedgerOwner` returns; a hook error does not block acquisition, and a nested lease on an +existing owner does not run them again. The durable Codex pool affinity store uses one to open and +prune at startup ([Durable Codex Pool Affinity](../providers/codex-pool-affinity.md)). +The ledger records the ownership it was built under and proves that exact identity on every accounting read and change, so a handle kept across a release and a reacquire of the same directory is refused rather than resuming over writes another owner may have made. File-backed journal and salt writers are owner-bound at construction, and a diff --git a/tests/codex-integration/codex-affinity-lease-gap.test.ts b/tests/codex-integration/codex-affinity-lease-gap.test.ts new file mode 100644 index 00000000000..4e1cea8f4cb --- /dev/null +++ b/tests/codex-integration/codex-affinity-lease-gap.test.ts @@ -0,0 +1,99 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, renameSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { readCodexAccountRecord, saveCodexAccountCredential } from "../../src/codex/account-store"; +import { codexPoolAffinityKey } from "../../src/codex/auth-context"; +import { requestOwnedAffinityKey } from "../../src/codex/request-owned-affinity"; +import { bindThreadAffinity, clearThreadAccountMap, deleteThreadAffinity, getThreadAffinity, rememberConversationStateIssuer } from "../../src/codex/routing/thread-affinity"; +import { adoptStoredIssuer, adoptStoredThreadRows, resetCodexAffinityStoreForTests } from "../../src/codex/routing/thread-affinity-store"; +import { acquireSpendLedgerOwner, type SpendLedgerOwnerLease } from "../../src/lib/spend-ledger-owner"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +let homes: string[] = []; +let prior: string | undefined; +let lease: SpendLedgerOwnerLease | undefined; +const conversation = (id: string) => new Headers({ authorization: "Bearer caller", "session-id": `gap-${id}`, "thread-id": `gap-${id}` }); + +function useHome(home: string): void { process.env.OPENCODEX_HOME = home; } +function newHome(): string { const home = mkdtempSync(join(tmpdir(), "ocx-affinity-gap-")); homes.push(home); return home; } +function seedAccounts(): void { + for (const id of ["a", "b"]) saveCodexAccountCredential(id, { accessToken: `access-${id}`, refreshToken: `refresh-${id}`, expiresAt: Date.now() + 600_000, chatgptAccountId: `chat-${id}` }); +} +function credential(id: string) { return { generation: readCodexAccountRecord(id)!.generation, chatgptAccountId: `chat-${id}` }; } +/** A fresh process: no live affinity, nothing carried in the store. */ +function freshProcess(): void { lease?.release(); lease = undefined; resetCodexAffinityStoreForTests(); clearThreadAccountMap(); resetCodexAffinityStoreForTests(); } +function storedPin(id: string): string | undefined { return adoptStoredThreadRows(codexPoolAffinityKey(conversation(id))!, Date.now())[0]?.accountId; } +function storedIssuer(id: string): string | undefined { return adoptStoredIssuer(codexPoolAffinityKey(conversation(id))!, Date.now())?.issuer; } + +beforeEach(() => { prior = process.env.OPENCODEX_HOME; freshProcess(); }); +afterEach(() => { + freshProcess(); + if (prior === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = prior; + for (const home of homes) removeTreeWithRetry(home); + homes = []; +}); + +test("a change made between leases makes the next lease clear stale rows instead of reviving them", () => { + useHome(newHome()); + lease = acquireSpendLedgerOwner(); seedAccounts(); + for (const id of ["one", "two"]) { + const key = codexPoolAffinityKey(conversation(id))!; + bindThreadAffinity(key, "a", Date.now()); + rememberConversationStateIssuer(key, "a", Date.now(), credential("a")); + } + freshProcess(); + // A later process loads only conversation "one", releases, and rebinds it with no lease held. + lease = acquireSpendLedgerOwner(); + const one = codexPoolAffinityKey(conversation("one"))!; + expect(getThreadAffinity(one)?.accountId).toBe("a"); + lease.release(); lease = undefined; + bindThreadAffinity(one, "b", Date.now()); + // A request-owned key changed in the same gap must not reach disk either. + bindThreadAffinity(requestOwnedAffinityKey(conversation("one"))!, "b", Date.now()); + lease = acquireSpendLedgerOwner(); + freshProcess(); lease = acquireSpendLedgerOwner(); + // The replaced pin must not come back as "a". Rows the process never loaded are cleared too: + // the database could not record the change, so it is treated as stale as a whole (fail closed). + expect(storedPin("one")).toBeUndefined(); + expect(storedPin("two")).toBeUndefined(); + expect(storedIssuer("two")).toBeUndefined(); +}); + +test("a change made between leases in one home never touches another home's database", () => { + const homeB = newHome(); + useHome(homeB); + lease = acquireSpendLedgerOwner(); seedAccounts(); + bindThreadAffinity(codexPoolAffinityKey(conversation("b-only"))!, "a", Date.now()); + freshProcess(); + const homeA = newHome(); + useHome(homeA); + lease = acquireSpendLedgerOwner(); seedAccounts(); + const inA = codexPoolAffinityKey(conversation("a-only"))!; + bindThreadAffinity(inA, "a", Date.now()); + lease.release(); lease = undefined; + bindThreadAffinity(inA, "b", Date.now()); + useHome(homeB); + lease = acquireSpendLedgerOwner(); + freshProcess(); useHome(homeB); lease = acquireSpendLedgerOwner(); + expect(storedPin("b-only")).toBe("a"); +}); + +test("a change made while the store could not open is still honoured by the next successful open", () => { + const home = newHome(); + useHome(home); + lease = acquireSpendLedgerOwner(); seedAccounts(); + const key = codexPoolAffinityKey(conversation("failed-open"))!; + bindThreadAffinity(key, "a", Date.now()); + lease.release(); lease = undefined; + // The next lease cannot open the database (a directory sits at its path); delete during it. + const file = join(home, "codex-affinity.sqlite"); + renameSync(file, `${file}.aside`); mkdirSync(file); + lease = acquireSpendLedgerOwner(); + deleteThreadAffinity(key); + lease.release(); lease = undefined; + removeTreeWithRetry(file); renameSync(`${file}.aside`, file); + lease = acquireSpendLedgerOwner(); + freshProcess(); lease = acquireSpendLedgerOwner(); + expect(storedPin("failed-open")).toBeUndefined(); +}); diff --git a/tests/codex-integration/codex-affinity-request-owned.test.ts b/tests/codex-integration/codex-affinity-request-owned.test.ts new file mode 100644 index 00000000000..29a97723086 --- /dev/null +++ b/tests/codex-integration/codex-affinity-request-owned.test.ts @@ -0,0 +1,86 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { Database } from "bun:sqlite"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { readCodexAccountRecord, saveCodexAccountCredential } from "../../src/codex/account-store"; +import { codexPoolAffinityKey } from "../../src/codex/auth-context"; +import { isRequestOwnedAffinityKey, requestOwnedAffinityKey } from "../../src/codex/request-owned-affinity"; +import { bindThreadAffinity, clearThreadAccountMap, getThreadAffinity, peekConversationStateIssuer, rememberConversationStateIssuer } from "../../src/codex/routing/thread-affinity"; +import { adoptStoredIssuer, adoptStoredThreadRows, flushCodexAffinityStoreForTests, noteCodexAffinityAnchorForTests, resetCodexAffinityStoreForTests } from "../../src/codex/routing/thread-affinity-store"; +import { acquireSpendLedgerOwner, type SpendLedgerOwnerLease } from "../../src/lib/spend-ledger-owner"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +let home: string; +let prior: string | undefined; +let lease: SpendLedgerOwnerLease | undefined; +const headers = () => new Headers({ authorization: "Bearer caller-owned-token", "session-id": "request-owned-session", "thread-id": "request-owned-thread" }); + +beforeEach(() => { + prior = process.env.OPENCODEX_HOME; home = mkdtempSync(join(tmpdir(), "ocx-affinity-request-owned-")); process.env.OPENCODEX_HOME = home; + clearThreadAccountMap(); resetCodexAffinityStoreForTests(); +}); +afterEach(() => { + lease?.release(); lease = undefined; resetCodexAffinityStoreForTests(); clearThreadAccountMap(); + if (prior === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = prior; + removeTreeWithRetry(home); +}); + +function rows(): { threads: number; issuers: number } { + const db = new Database(join(home, "codex-affinity.sqlite")); + try { + return { + threads: (db.query("SELECT count(*) AS n FROM threads").get() as { n: number }).n, + issuers: (db.query("SELECT count(*) AS n FROM issuers").get() as { n: number }).n, + }; + } finally { db.close(); } +} + +test("request-owned bindings and issuers are never saved or restored, even with an anchor", () => { + lease = acquireSpendLedgerOwner(); + saveCodexAccountCredential("account-a", { accessToken: "access", refreshToken: "refresh", expiresAt: Date.now() + 60_000, chatgptAccountId: "chat-account" }); + const record = readCodexAccountRecord("account-a")!; + const credential = { generation: record.generation, chatgptAccountId: "chat-account" }; + const conversationKey = codexPoolAffinityKey(headers())!; + const requestOwnedKey = requestOwnedAffinityKey(headers())!; + expect(isRequestOwnedAffinityKey(requestOwnedKey)).toBe(true); + // No production path anchors a request-owned key today; feed one in as a future derivation might. + // A distinct anchor matters: sharing the conversation's anchor would collapse both onto one row. + noteCodexAffinityAnchorForTests(requestOwnedKey, "future-anchor", "future-anchor"); + const now = Date.now(); + bindThreadAffinity(conversationKey, "account-a", now); + rememberConversationStateIssuer(conversationKey, "account-a", now, credential); + bindThreadAffinity(requestOwnedKey, "account-a", now); + rememberConversationStateIssuer(requestOwnedKey, "account-a", now, credential); + flushCodexAffinityStoreForTests(); + // Only the ordinary conversation reached disk. + expect(rows()).toEqual({ threads: 1, issuers: 1 }); + + // Restart: a new lease scope reads the database. Live memory survives an in-process lease change, + // so the restored state is read through the store's adoption, which sees only stored rows. + lease.release(); lease = acquireSpendLedgerOwner(); + noteCodexAffinityAnchorForTests(requestOwnedKey, "future-anchor", "future-anchor"); + const restoredConversation = codexPoolAffinityKey(headers())!; + expect(adoptStoredThreadRows(restoredConversation, Date.now()).map(row => row.accountId)).toEqual(["account-a"]); + expect(adoptStoredIssuer(restoredConversation, Date.now())?.issuer).toBe("account-a"); + expect(adoptStoredThreadRows(requestOwnedKey, Date.now())).toEqual([]); + expect(adoptStoredIssuer(requestOwnedKey, Date.now())).toBeUndefined(); +}); + +test("a manual switch keeps saved issuers while clearing saved pins", () => { + lease = acquireSpendLedgerOwner(); + saveCodexAccountCredential("account-a", { accessToken: "access", refreshToken: "refresh", expiresAt: Date.now() + 60_000, chatgptAccountId: "chat-account" }); + const record = readCodexAccountRecord("account-a")!; + const conversationKey = codexPoolAffinityKey(headers())!; + const now = Date.now(); + bindThreadAffinity(conversationKey, "account-a", now); + rememberConversationStateIssuer(conversationKey, "account-a", now, { generation: record.generation, chatgptAccountId: "chat-account" }); + flushCodexAffinityStoreForTests(); + clearThreadAccountMap({ preserveConversationStateIssuers: true }); + flushCodexAffinityStoreForTests(); + expect(rows()).toEqual({ threads: 0, issuers: 1 }); + lease.release(); lease = acquireSpendLedgerOwner(); + const restored = codexPoolAffinityKey(headers())!; + expect(getThreadAffinity(restored)).toBeUndefined(); + expect(peekConversationStateIssuer(restored)).toBe("account-a"); +}); diff --git a/tests/codex-integration/codex-affinity-restart-matrix.test.ts b/tests/codex-integration/codex-affinity-restart-matrix.test.ts new file mode 100644 index 00000000000..470f0bb221f --- /dev/null +++ b/tests/codex-integration/codex-affinity-restart-matrix.test.ts @@ -0,0 +1,226 @@ +import { expect, test } from "bun:test"; +import { Database } from "bun:sqlite"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, symlinkSync, truncateSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { initializeConfigOwnership, removeOwnedConfigState } from "../../src/lib/config-ownership"; +import { helperPath } from "../helpers/repo-root"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +const names = ["codex-affinity.sqlite", "codex-affinity.sqlite-journal", "codex-affinity.sqlite-wal", "codex-affinity.sqlite-shm"]; +function worker(home: string, file: string, action: string): any { + const result = Bun.spawnSync([process.execPath, helperPath(file), action], { env: { ...process.env, OPENCODEX_HOME: home, CODEX_HOME: home }, stdout: "pipe", stderr: "pipe" }); + expect(result.exitCode, result.stderr.toString()).toBe(0); + return result.stdout.length ? JSON.parse(result.stdout.toString()) : undefined; +} +function seed(home: string) { return worker(home, "codex-affinity-restart-worker.ts", "write"); } +function matrix(home: string, action: string) { return worker(home, "codex-affinity-matrix-worker.ts", action); } +function inHome(fn: (home: string) => void) { + const home = mkdtempSync(join(tmpdir(), "ocx-affinity-extra-")); + try { fn(home); } finally { if (existsSync(home)) removeTreeWithRetry(home); } +} + +test("a restored shared binding survives a model eligibility detour", () => inHome(home => { + expect(seed(home).account).toBe("a"); + matrix(home, "shared-write"); + const result = matrix(home, "model-excluded"); + expect(result.before).toBe("a"); + expect(result.result).toMatchObject({ status: "selected", accountId: "b" }); + expect(result.shared).toBe("a"); +})); + +test("fresh and existing owned homes list and remove all affinity paths", () => inHome(home => { + expect(initializeConfigOwnership(home)).toBe(true); + let manifest = JSON.parse(readFileSync(join(home, ".opencodex-uninstall.json"), "utf8")); + for (const name of names) expect(manifest.paths).toContain(name); + // Simulate an older owned home that predates these paths. + manifest.paths = manifest.paths.filter((path: string) => !names.includes(path)); + writeFileSync(join(home, ".opencodex-uninstall.json"), JSON.stringify(manifest)); + matrix(home, "probe"); + manifest = JSON.parse(readFileSync(join(home, ".opencodex-uninstall.json"), "utf8")); + for (const name of names) expect(manifest.paths).toContain(name); + for (const name of names.slice(1)) writeFileSync(join(home, name), "sidecar"); + expect(removeOwnedConfigState(home).status).toBe("removed"); + for (const name of names) expect(existsSync(join(home, name))).toBe(false); +})); + +for (const kind of ["symlink", "directory"] as const) { + test(`${kind} at the database path disables the store`, () => inHome(home => { + expect(initializeConfigOwnership(home)).toBe(true); + const target = join(home, "outside-target"); + if (kind === "symlink") symlinkSync(target, join(home, names[0]!)); + else mkdirSync(join(home, names[0]!)); + matrix(home, "probe"); + expect(existsSync(target)).toBe(false); + })); +} + +test("a home without an ownership manifest still persists affinity and gains no manifest", () => inHome(home => { + writeFileSync(join(home, "unowned"), "keep"); + expect(seed(home).account).toBe("a"); + expect(existsSync(join(home, names[0]!))).toBe(true); + expect(worker(home, "codex-affinity-restart-worker.ts", "read").account).toBe("a"); + expect(existsSync(join(home, ".opencodex-uninstall.json"))).toBe(false); +})); + +for (const kind of ["extra-table", "wrong-column"] as const) { + test(`v1 ${kind} is rejected without changing schema, metadata, or rows`, () => inHome(home => { + seed(home); + const file = join(home, names[0]!); + let db = new Database(file); + if (kind === "extra-table") db.exec("CREATE TABLE extra(value TEXT)"); + else db.exec("ALTER TABLE threads RENAME COLUMN account_id TO wrong_account"); + db.close(); + const before = readFileSync(file); + matrix(home, "probe"); + expect(readFileSync(file).equals(before)).toBe(true); + })); +} + +test("pruning keeps newest issuers and prioritizes ordinary bindings over detours", () => inHome(home => { + seed(home); + const file = join(home, names[0]!); + let db = new Database(file); + const now = Date.now() - 5000; + db.exec("BEGIN"); + const insertThread = db.query("INSERT INTO threads VALUES (?, ?, 'a', 'fence', ?, ?)"); + const insertIssuer = db.query("INSERT INTO issuers VALUES (?, 'a', 'fence', ?)"); + for (let i = 0; i < 2052; i++) { + const key = `bulk-${String(i).padStart(4, "0")}`; + insertThread.run(key, i < 4 ? "model-detour:shared:gpt-test" : "shared", now, now + i); + insertIssuer.run(key, now + i); + } + db.exec("COMMIT"); db.close(); + matrix(home, "probe"); + db = new Database(file); + expect(db.query("SELECT count(*) AS n FROM threads").get()).toEqual({ n: 2048 }); + expect(db.query("SELECT count(*) AS n FROM issuers").get()).toEqual({ n: 2048 }); + expect(db.query("SELECT count(*) AS n FROM threads WHERE scope LIKE 'model-detour:%'").get()).toEqual({ n: 0 }); + expect(db.query("SELECT count(*) AS n FROM issuers WHERE row_key LIKE 'bulk-%' AND row_key < 'bulk-0004'").get()).toEqual({ n: 0 }); + db.close(); +})); + +test("oversized database is disabled without changing its bytes", () => inHome(home => { + seed(home); + const file = join(home, names[0]!); + truncateSync(file, 8 * 1024 * 1024 + 1); + const before = readFileSync(file); + matrix(home, "probe"); + expect(readFileSync(file).equals(before)).toBe(true); +})); + +test("open immediately removes expired and excess rows", () => inHome(home => { + seed(home); + const db = new Database(join(home, names[0]!)); + const now = Date.now() - 5000; + db.exec("BEGIN"); + const thread = db.query("INSERT INTO threads VALUES (?, 'shared', 'a', 'fence', ?, ?)"); + const issuer = db.query("INSERT INTO issuers VALUES (?, 'a', 'fence', ?)"); + for (let i = 0; i < 2050; i++) { thread.run(`bulk-${i}`, now, now); issuer.run(`bulk-${i}`, now); } + thread.run("expired", now - 90_000_000, now - 90_000_000); + issuer.run("expired", now - 90_000_000); + db.exec("COMMIT"); db.close(); + const result = matrix(home, "open-count"); + expect(result.threads.n).toBe(2048); + expect(result.issuers.n).toBe(2048); + expect(result.expired.n).toBe(0); +})); + +test("hourly timer prunes an idle open store", () => inHome(home => { + seed(home); + const result = matrix(home, "hourly"); + expect(result.scheduled).toBe(true); + expect(result.threads.n).toBe(0); + expect(result.issuers.n).toBe(0); +})); + +test("adoption enumerates every stored scope for a row key", () => inHome(home => { + seed(home); + const db = new Database(join(home, names[0]!)); + const row = db.query("SELECT row_key, account_id, fence, created_at, last_used_at FROM threads LIMIT 1").get() as { row_key: string; account_id: string; fence: string; created_at: number; last_used_at: number }; + const insert = db.query("INSERT INTO threads VALUES (?, ?, ?, ?, ?, ?)"); + for (let i = 0; i < 80; i++) insert.run(row.row_key, `model-detour:shared:model-${i}`, row.account_id, row.fence, row.created_at, row.last_used_at - i - 1); + db.close(); + const scopes = matrix(home, "scopes").scopes; + expect(scopes).toHaveLength(81); + expect(scopes).toContain("model-detour:shared:model-0"); + expect(scopes).toContain("model-detour:shared:model-79"); +})); + +test("restoration accepts a 512-byte model component and rejects 513 bytes", () => inHome(home => { + seed(home); + const file = join(home, names[0]!); + let db = new Database(file); + const row = db.query("SELECT row_key, account_id, fence, created_at, last_used_at FROM threads LIMIT 1").get() as { row_key: string; account_id: string; fence: string; created_at: number; last_used_at: number }; + const insert = db.query("INSERT INTO threads VALUES (?, ?, ?, ?, ?, ?)"); + const valid = `model-detour:shared:${"é".repeat(256)}`; + const invalid = `${valid}x`; + insert.run(row.row_key, valid, row.account_id, row.fence, row.created_at, row.last_used_at); + insert.run(row.row_key, invalid, row.account_id, row.fence, row.created_at, row.last_used_at); + db.close(); + const result = matrix(home, "scopes"); + expect(result.scopes).toContain(valid); + expect(result.scopes).not.toContain(invalid); + db = new Database(file); + expect(db.query("SELECT count(*) AS n FROM threads WHERE scope=?").get(invalid)).toEqual({ n: 0 }); + db.close(); +})); + +test("home switching drops pending writes and does not carry recorded anchors across homes", () => inHome(homeA => inHome(homeB => { + seed(homeA); seed(homeB); + for (const home of [homeA, homeB]) { + const db = new Database(join(home, names[0]!)); + db.exec("DELETE FROM threads; DELETE FROM issuers"); + db.close(); + } + const result = Bun.spawnSync([process.execPath, helperPath("codex-affinity-home-switch-worker.ts"), homeB], { + env: { ...process.env, OPENCODEX_HOME: homeA, CODEX_HOME: homeA }, stdout: "pipe", stderr: "pipe", + }); + expect(result.exitCode, result.stderr.toString()).toBe(0); + expect(JSON.parse(result.stdout.toString())).toEqual({ first: "a", rowsB: 1, restoredB: "a" }); +}))); + +for (const mutation of ["bind", "delete", "issuer"] as const) { + test(`late ${mutation} after release is what a reacquired lease persists`, () => inHome(home => { + seed(home); + // Live memory keeps the change made while no lease was held. The database could not record it, + // so the next lease clears it: a restart restores nothing rather than the replaced row. + const expected = { + bind: { pin: "b", issuer: "a", restoredPin: undefined, restoredIssuer: undefined }, + delete: { pin: undefined, issuer: "a", restoredPin: undefined, restoredIssuer: undefined }, + issuer: { pin: "a", issuer: "b", restoredPin: undefined, restoredIssuer: undefined }, + }[mutation]; + expect(matrix(home, `late-${mutation}`)).toEqual({ pin: expected.pin, issuer: expected.issuer }); + const restored = matrix(home, "read"); + expect(restored.before).toBe(expected.restoredPin); + expect(restored.issuer).toBe(expected.restoredIssuer); + })); +} + +for (const path of ["responses", "compact"] as const) { + for (const issuer of ["unknown", "known"] as const) { + test(`${path} handler ${issuer} restored issuer with an uploaded file`, () => inHome(home => { + worker(home, "codex-affinity-restart-worker.ts", issuer === "unknown" ? "unknown-write" : "write"); + const result = worker(home, "codex-affinity-handler-worker.ts", path); + expect(result.status).toBe(400); + expect(result.bodies).toHaveLength(0); + })); + } +} + +for (const path of ["responses", "compact"] as const) { + test(`${path} permits a file for the same stored account with unknown issuer`, () => inHome(home => { + worker(home, "codex-affinity-restart-worker.ts", "unknown-write"); + const result = Bun.spawnSync([process.execPath, helperPath("codex-affinity-handler-worker.ts"), path, "same"], { env: { ...process.env, OPENCODEX_HOME: home, CODEX_HOME: home }, stdout: "pipe", stderr: "pipe" }); + expect(result.exitCode, result.stderr.toString()).toBe(0); + const parsed = JSON.parse(result.stdout.toString()); + expect(parsed.status, parsed.responseBody).toBe(200); + expect(parsed.bodies).toHaveLength(1); + })); +} + +test("touching an unknown restored issuer extends its durable lifetime", () => inHome(home => { + worker(home, "codex-affinity-restart-worker.ts", "unknown-write"); + expect(worker(home, "codex-affinity-restart-worker.ts", "touch-unknown").issuer).toBe("__unknown_codex_conversation_state_issuer__"); + expect(worker(home, "codex-affinity-restart-worker.ts", "read-unknown").issuer).toBe("__unknown_codex_conversation_state_issuer__"); +})); diff --git a/tests/codex-integration/codex-affinity-restart.test.ts b/tests/codex-integration/codex-affinity-restart.test.ts new file mode 100644 index 00000000000..babd27cac24 --- /dev/null +++ b/tests/codex-integration/codex-affinity-restart.test.ts @@ -0,0 +1,234 @@ +import { expect, test } from "bun:test"; +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { helperPath } from "../helpers/repo-root"; +import { Database } from "bun:sqlite"; + +function run(home: string, mode: string) { + const result = Bun.spawnSync([process.execPath, helperPath("codex-affinity-restart-worker.ts"), mode], { + env: { ...process.env, OPENCODEX_HOME: home, CODEX_HOME: home }, stdout: "pipe", stderr: "pipe", + }); + return { exit: result.exitCode, stdout: result.stdout.toString(), stderr: result.stderr.toString() }; +} + +test("pool binding and issuer survive a clean restart", () => { + const home = mkdtempSync(join(tmpdir(), "ocx-affinity-restart-")); + try { + const first = run(home, "write"); + expect(first.exit, first.stderr).toBe(0); + const second = run(home, "read"); + expect(second.exit, second.stderr).toBe(0); + const before = JSON.parse(first.stdout); + const after = JSON.parse(second.stdout); + expect(after.account).toBe(before.account); + expect(after.issuer).toBe(before.account); + expect(after.sameScrub).toBe(false); + expect(after.otherScrub).toBe(true); + expect(after.otherFileRefusal).toBe(400); + } finally { removeTreeWithRetry(home); } +}); + +test("an unclean owner discards persisted affinity", () => { + const home = mkdtempSync(join(tmpdir(), "ocx-affinity-crash-")); + try { + const first = run(home, "crash"); + expect(first.exit).not.toBe(0); + const second = run(home, "read"); + expect(second.exit, second.stderr).toBe(0); + expect(JSON.parse(second.stdout).issuer).toBeUndefined(); + expect(JSON.parse(second.stdout).account).toBe("b"); + } finally { removeTreeWithRetry(home); } +}); + +test("unknown issuer scrubs continuation and refuses files on account moves", () => { + const home = mkdtempSync(join(tmpdir(), "ocx-affinity-unknown-")); + try { + const first = run(home, "unknown-write"); + expect(first.exit, first.stderr).toBe(0); + const second = run(home, "unknown-read"); + expect(second.exit, second.stderr).toBe(0); + const result = JSON.parse(second.stdout); + expect(result.issuer).toBe("__unknown_codex_conversation_state_issuer__"); + expect(result.sameScrub).toBe(true); + expect(result.fileRefusal).toBeUndefined(); + expect(result.retryRefusal).toBe(400); + expect(result.otherFileRefusal).toBe(400); + } finally { removeTreeWithRetry(home); } +}); + +test("a replacement identity invalidates the old pin and makes its issuer unknown", () => { + const home = mkdtempSync(join(tmpdir(), "ocx-affinity-relogin-")); + try { + const first = run(home, "relogin"); + expect(first.exit, first.stderr).toBe(0); + const second = run(home, "read"); + expect(second.exit, second.stderr).toBe(0); + const before = JSON.parse(first.stdout); + const after = JSON.parse(second.stdout); + expect(after.account).not.toBe(before.account); + expect(after.issuer).toBe("__unknown_codex_conversation_state_issuer__"); + } finally { removeTreeWithRetry(home); } +}); + +function matrix(home: string, action: string) { + const result = Bun.spawnSync([process.execPath, helperPath("codex-affinity-matrix-worker.ts"), action], { + env: { ...process.env, OPENCODEX_HOME: home, CODEX_HOME: home }, stdout: "pipe", stderr: "pipe", + }); + expect(result.exitCode, result.stderr.toString()).toBe(0); + return result.stdout.length ? JSON.parse(result.stdout.toString()) : undefined; +} + +function withSeededHome(body: (home: string) => void) { + const home = mkdtempSync(join(tmpdir(), "ocx-affinity-matrix-")); + try { + const seed = run(home, "write"); + expect(seed.exit, seed.stderr).toBe(0); + expect(JSON.parse(seed.stdout).account).toBe("a"); + body(home); + } finally { removeTreeWithRetry(home); } +} + +for (const action of ["delete", "delete-account", "clear-account", "clear"] as const) { + test(`${action} reconciles a restored pin before its first lookup`, () => withSeededHome(home => { + const result = matrix(home, action); + expect(result.before).toBeUndefined(); + expect(result.selected).toBe("b"); + expect(result.rows).toBe(0); + expect(result.issuer).toBe(action === "clear" ? undefined : "a"); + })); +} + +test("a new bind and issuer replace unadopted restored rows", () => { + withSeededHome(home => { + const result = matrix(home, "bind"); + expect(result.before).toBe("b"); + expect(result.selected).toBe("b"); + expect(result.rows).toBe(0); + }); + withSeededHome(home => expect(matrix(home, "issuer").issuer).toBe("b")); + withSeededHome(home => { + const result = matrix(home, "clear-issuer"); + expect(result.issuer).toBeUndefined(); + expect(result.issuers).toBe(0); + }); +}); + +for (const action of ["removed", "relogin", "paused", "plan", "reauth", "cooldown"] as const) { + test(`${action} makes the resolver leave a restored account`, () => withSeededHome(home => { + const result = matrix(home, action); + expect(result.selected).toBe("b"); + expect(result.rows).toBe(0); + })); +} + +test("transient failure detours a restored pin while retaining its owner", () => withSeededHome(home => { + const result = matrix(home, "transient"); + expect(result.before).toBe("a"); + expect(result.selected).toBe("b"); + expect(result.after).toBe("a"); +})); + +test("a legacy account without an identity falls back and removes its stored row", () => withSeededHome(home => { + const file = join(home, "codex-accounts.json"); + const records = JSON.parse(readFileSync(file, "utf8")); + delete records.a.quotaHistoryIdentity; + writeFileSync(file, JSON.stringify(records)); + const result = matrix(home, "read"); + expect(result.before).toBeUndefined(); + expect(result.selected).toBe("b"); + expect(result.rows).toBe(0); +})); + +// Offsets, not timestamps: each case computes its time when it runs, because the subprocess +// workers can take long enough on a loaded host for a load-time "future" value to become past. +for (const [label, offsetMs] of [["expired", -25 * 60 * 60_000], ["future", 60 * 60_000]] as const) { + test(`${label} restored pin falls back and is deleted`, () => withSeededHome(home => { + const timestamp = Date.now() + offsetMs; + const db = new Database(join(home, "codex-affinity.sqlite")); + db.query("UPDATE threads SET last_used_at=?").run(timestamp); + db.close(); + const result = matrix(home, "read"); + expect(result.before).toBeUndefined(); + expect(result.selected).toBe("b"); + expect(result.rows).toBe(0); + })); +} + +test("main account bindings and issuers do not survive release", () => withSeededHome(home => { + matrix(home, "write-main"); + const result = matrix(home, "read"); + expect(result.before).toBeUndefined(); + expect(result.issuer).toBeUndefined(); +})); + +test("session-less depth one restores while depth two places independently", () => { + for (const [action, expected] of [["depth-one", "a"], ["depth-two", "b"]] as const) withSeededHome(home => { + matrix(home, "depth-write"); + expect(matrix(home, action).selected).toBe(expected); + }); +}); + +test("passive affinity operations leave a populated database untouched under a lease", () => withSeededHome(home => { + expect(matrix(home, "passive").unchanged).toBe(true); + expect(matrix(home, "read").before).toBe("a"); +})); + +test.skipIf(process.platform !== "win32")("Windows releases affinity handles before directory removal", () => { + const home = mkdtempSync(join(tmpdir(), "ocx-affinity-windows-")); + const first = run(home, "write"); + expect(first.exit, first.stderr).toBe(0); + removeTreeWithRetry(home); +}); + +for (const action of ["race-relogin", "race-delete-add"] as const) { + test(`${action} invalidates a binding written before the identity changed`, () => withSeededHome(home => { + matrix(home, action); + const result = matrix(home, "read"); + expect(result.before).toBeUndefined(); + expect(result.selected).toBe("b"); + })); +} + +for (const action of ["race-refresh", "race-external"] as const) { + test(`${action} keeps a binding when the account identity is unchanged`, () => withSeededHome(home => { + matrix(home, action); + expect(matrix(home, "read").before).toBe("a"); + })); +} + +test("issuer completion with a superseded credential restores as unknown", () => withSeededHome(home => { + matrix(home, "race-issuer"); + expect(matrix(home, "read").issuer).toBe("__unknown_codex_conversation_state_issuer__"); +})); + +test("only the last lease flushes and a token from the prior lease is refused", () => withSeededHome(home => { + // Remove the seeded binding through the public API before testing a pending bind. + matrix(home, "clear"); + const db = new Database(join(home, "codex-affinity.sqlite")); + db.exec("DELETE FROM threads"); + db.close(); + expect(matrix(home, "lease")).toEqual({ before: 0, rejected: true }); + expect(matrix(home, "read").before).toBe("a"); +})); + +test("resolver reuse persists its updated last-used time on release", () => withSeededHome(home => { + const db = new Database(join(home, "codex-affinity.sqlite")); + db.query("UPDATE threads SET last_used_at=?").run(Date.now() - 10_000); + db.close(); + const result = matrix(home, "touch"); + expect(result.row.timestamp).toBe(result.timestamp); +})); + +for (const [label, offsetMs] of [["expired", -25 * 60 * 60_000], ["future", 60 * 60_000]] as const) { + test(`${label} issuer is removed when read`, () => withSeededHome(home => { + const timestamp = Date.now() + offsetMs; + const db = new Database(join(home, "codex-affinity.sqlite")); + db.query("UPDATE issuers SET last_used_at=?").run(timestamp); + db.close(); + const result = matrix(home, "read"); + expect(result.issuer).toBeUndefined(); + expect(result.issuers).toBe(0); + })); +} diff --git a/tests/codex-integration/codex-affinity-store.test.ts b/tests/codex-integration/codex-affinity-store.test.ts new file mode 100644 index 00000000000..5e496adc5a2 --- /dev/null +++ b/tests/codex-integration/codex-affinity-store.test.ts @@ -0,0 +1,353 @@ +import { registerThreadAffinityLiveState } from "../../src/codex/routing/thread-affinity"; +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { Database } from "bun:sqlite"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { saveCodexAccountCredential } from "../../src/codex/account-store"; +import { codexConversationKeyFor } from "../../src/codex/lineage"; +import { acquireSpendLedgerOwner, type SpendLedgerOwnerLease } from "../../src/lib/spend-ledger-owner"; +import { runPassiveRead } from "../../src/lib/passive-read"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { adoptStoredIssuer, adoptStoredThreadRows, codexAffinityIdentityFence, CODEX_UNKNOWN_CONVERSATION_STATE_ISSUER, flushCodexAffinityStoreForTests, recordAccountPinsCleared, recordAllCleared, recordIssuerSet, recordIssuerDelete, recordThreadDelete, recordThreadBind, recordThreadTouch, registerCodexAffinityLiveState, resetCodexAffinityStoreForTests } from "../../src/codex/routing/thread-affinity-store"; + +let home: string; +let prior: string | undefined; +let lease: SpendLedgerOwnerLease | undefined; +let live: { accountId: string; identityFence: string; createdAt: number; lastUsedAt: number } | undefined; +const path = () => join(home, "codex-affinity.sqlite"); +const key = () => codexConversationKeyFor("private-family", "private-thread"); +function seed(): string { + saveCodexAccountCredential("account-a", { accessToken: "access", refreshToken: "refresh", expiresAt: Date.now() + 60_000, chatgptAccountId: "chat-account" }); + return codexAffinityIdentityFence("account-a")!; +} +function bind(fence: string): string { + const k = key(); const now = Date.now(); live = { accountId: "account-a", identityFence: fence, createdAt: now - 1000, lastUsedAt: now - 1000 }; + recordThreadBind(k, "legacy", { scope: "legacy", accountId: "account-a", fence, createdAt: live.createdAt, lastUsedAt: live.lastUsedAt }); return k; +} +beforeEach(() => { + prior = process.env.OPENCODEX_HOME; home = mkdtempSync(join(tmpdir(), "ocx-affinity-")); process.env.OPENCODEX_HOME = home; live = undefined; + registerCodexAffinityLiveState({ thread: () => live, issuer: () => undefined, clearLive: () => { live = undefined; } }); +}); +afterEach(() => { lease?.release(); lease = undefined; resetCodexAffinityStoreForTests(); registerThreadAffinityLiveState(); if (prior === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = prior; removeTreeWithRetry(home); }); + +test("inactive operations do not open and passive operations do not change the database", async () => { + key(); expect(existsSync(path())).toBe(false); + lease = acquireSpendLedgerOwner(); + flushCodexAffinityStoreForTests(); + const before = readFileSync(path()); + await runPassiveRead(async () => { key(); recordAllCleared(); }); + expect(readFileSync(path()).equals(before)).toBe(true); +}); +test("bind survives release and touch reads the live timestamp at flush", () => { + lease = acquireSpendLedgerOwner(); const fence = seed(); const k = bind(fence); const newer = Date.now(); + recordThreadTouch(k, "legacy"); live!.lastUsedAt = newer; flushCodexAffinityStoreForTests(); + lease.release(); lease = acquireSpendLedgerOwner(); const restored = adoptStoredThreadRows(key(), Date.now()); + expect(restored).toHaveLength(1); expect(restored[0]!.lastUsedAt).toBe(newer); + const bytes = readFileSync(path()); expect(bytes.includes(Buffer.from("private-family"))).toBe(false); expect(bytes.includes(Buffer.from("private-thread"))).toBe(false); expect(bytes.includes(Buffer.from(k))).toBe(false); + if (process.platform !== "win32") expect(statSync(path()).mode & 0o777).toBe(0o600); +}); +test("unclean database is discarded and unknown version remains unchanged", () => { + lease = acquireSpendLedgerOwner(); bind(seed()); lease.release(); + let db = new Database(path()); db.exec("UPDATE meta SET value=0 WHERE name='clean'"); db.close(); + lease = acquireSpendLedgerOwner(); expect(adoptStoredThreadRows(key(), Date.now())).toEqual([]); lease.release(); + db = new Database(path()); db.exec("PRAGMA user_version=99"); db.close(); const before = readFileSync(path()); + lease = acquireSpendLedgerOwner(); key(); lease.release(); expect(readFileSync(path()).equals(before)).toBe(true); +}); +test("issuer fence mismatch is unknown and account clearing preserves issuer", () => { + lease = acquireSpendLedgerOwner(); const fence = seed(); const k = bind(fence); recordIssuerSet(k, "account-a", fence, Date.now()); recordAccountPinsCleared("account-a"); lease.release(); + seed(); lease = acquireSpendLedgerOwner(); const restoredKey = key(); expect(adoptStoredThreadRows(restoredKey, Date.now())).toEqual([]); expect(adoptStoredIssuer(restoredKey, Date.now())?.issuer).toBe(CODEX_UNKNOWN_CONVERSATION_STATE_ISSUER); +}); +test("clear all followed by bind preserves the later bind", () => { + lease = acquireSpendLedgerOwner(); const fence = seed(); bind(fence); recordAllCleared(); bind(fence); lease.release(); lease = acquireSpendLedgerOwner(); expect(adoptStoredThreadRows(key(), Date.now())).toHaveLength(1); +}); + +test("expiry, future timestamps and identity replacement reject restored rows", () => { + lease = acquireSpendLedgerOwner(); const fence = seed(); bind(fence); lease.release(); + let db = new Database(path()); db.query("UPDATE threads SET last_used_at=?").run(Date.now() - 25 * 60 * 60_000); db.close(); + lease = acquireSpendLedgerOwner(); expect(adoptStoredThreadRows(key(), Date.now())).toEqual([]); lease.release(); + lease = acquireSpendLedgerOwner(); bind(fence); lease.release(); + db = new Database(path()); db.query("UPDATE threads SET last_used_at=?").run(Date.now() + 60_000); db.close(); + lease = acquireSpendLedgerOwner(); expect(adoptStoredThreadRows(key(), Date.now())).toEqual([]); lease.release(); + lease = acquireSpendLedgerOwner(); bind(fence); lease.release(); seed(); + lease = acquireSpendLedgerOwner(); expect(adoptStoredThreadRows(key(), Date.now())).toEqual([]); +}); +test("issuer expiration and future timestamps are absent", () => { + for (const timestamp of [Date.now() - 25 * 60 * 60_000, Date.now() + 60_000]) { + lease = acquireSpendLedgerOwner(); const fence = seed(); const k = key(); recordIssuerSet(k, "account-a", fence, Date.now()); lease.release(); + const db = new Database(path()); db.query("UPDATE issuers SET last_used_at=?").run(timestamp); db.close(); + lease = acquireSpendLedgerOwner(); expect(adoptStoredIssuer(key(), Date.now())).toBeUndefined(); lease.release(); lease = undefined; + } +}); +test("releasing transaction failure leaves the store unclean and emits identifier-free warnings", () => { + lease = acquireSpendLedgerOwner(); const fence = seed(); bind(fence); flushCodexAffinityStoreForTests(); + const blocker = new Database(path()); blocker.exec("BEGIN IMMEDIATE"); + const warnings: string[] = []; const original = console.warn; console.warn = (...args: unknown[]) => { warnings.push(args.join(" ")); }; + try { lease.release(); } finally { console.warn = original; blocker.exec("ROLLBACK"); blocker.close(); } + expect(warnings.length).toBeGreaterThan(0); expect(warnings.join(" ")).not.toContain(home); expect(warnings.join(" ")).not.toContain("account-a"); expect(warnings.join(" ")).not.toContain("private-family"); + const db = new Database(path()); expect(db.query("SELECT value FROM meta WHERE name='clean'").get()).toEqual({ value: 0 }); db.close(); + lease = acquireSpendLedgerOwner(); expect(adoptStoredThreadRows(key(), Date.now())).toEqual([]); +}); +test("three failed flushes poison persistence until the next owner discards rows", () => { + lease = acquireSpendLedgerOwner(); const fence = seed(); bind(fence); flushCodexAffinityStoreForTests(); + const blocker = new Database(path()); blocker.exec("BEGIN IMMEDIATE"); + const original = console.warn; console.warn = () => {}; + try { flushCodexAffinityStoreForTests(); flushCodexAffinityStoreForTests(); flushCodexAffinityStoreForTests(); } finally { console.warn = original; blocker.exec("ROLLBACK"); blocker.close(); } + lease.release(); lease = acquireSpendLedgerOwner(); expect(adoptStoredThreadRows(key(), Date.now())).toEqual([]); +}); + +test("known and fence-less issuers restore with distinct outcomes", () => { + lease = acquireSpendLedgerOwner(); const fence = seed(); const known = key(); const unknown = codexConversationKeyFor("other-family", "other-thread"); + recordIssuerSet(known, "account-a", fence, Date.now()); recordIssuerSet(unknown, "account-a", null, Date.now()); lease.release(); + lease = acquireSpendLedgerOwner(); expect(adoptStoredIssuer(key(), Date.now())?.issuer).toBe("account-a"); + expect(adoptStoredIssuer(codexConversationKeyFor("other-family", "other-thread"), Date.now())?.issuer).toBe(CODEX_UNKNOWN_CONVERSATION_STATE_ISSUER); +}); +test("account clear followed by bind retains the later pin", () => { + lease = acquireSpendLedgerOwner(); const fence = seed(); bind(fence); recordAccountPinsCleared("account-a"); bind(fence); lease.release(); + lease = acquireSpendLedgerOwner(); expect(adoptStoredThreadRows(key(), Date.now())).toHaveLength(1); +}); + +test("overflow poisons the store and the next owner discards committed rows", () => { + lease = acquireSpendLedgerOwner(); + const fence = seed(); + bind(fence); + flushCodexAffinityStoreForTests(); + const db = new Database(path()); + expect(db.query("SELECT count(*) AS count FROM threads").get()).toEqual({ count: 1 }); + db.close(); + const original = console.warn; + console.warn = () => {}; + try { + for (let i = 0; i < 16385; i++) recordAccountPinsCleared("other-account"); + } finally { + console.warn = original; + } + lease.release(); + lease = acquireSpendLedgerOwner(); + expect(adoptStoredThreadRows(key(), Date.now())).toEqual([]); +}); + +test("a close error after final commit leaves rows clean and restorable", () => { + lease = acquireSpendLedgerOwner(); + bind(seed()); + // Throw after the real close: the final transaction has already committed. + const originalClose = Database.prototype.close; + const originalWarn = console.warn; + let injected = false; + Database.prototype.close = function (...args) { + originalClose.apply(this, args); + if (!injected) { + injected = true; + throw new Error("injected close failure"); + } + }; + console.warn = () => {}; + try { + lease.release(); + } finally { + Database.prototype.close = originalClose; + console.warn = originalWarn; + } + expect(injected).toBe(true); + const db = new Database(path()); + expect(db.query("SELECT value FROM meta WHERE name='clean'").get()).toEqual({ value: 1 }); + db.close(); + lease = acquireSpendLedgerOwner(); + expect(adoptStoredThreadRows(key(), Date.now())).toHaveLength(1); +}); + +test("an evicted anchor makes a later bind memory-only", () => { + lease = acquireSpendLedgerOwner(); + const fence = seed(); + const evicted = key(); + for (let i = 0; i < 4096; i++) codexConversationKeyFor(`family-${i}`, `thread-${i}`); + const now = Date.now(); + recordThreadBind(evicted, "legacy", { scope: "legacy", accountId: "account-a", fence, createdAt: now, lastUsedAt: now }); + lease.release(); + lease = acquireSpendLedgerOwner(); + expect(adoptStoredThreadRows(key(), Date.now())).toEqual([]); +}); + +test("release preserves live state, while an observed home change clears it", () => { + lease = acquireSpendLedgerOwner(); + bind(seed()); + lease.release(); + lease = undefined; + expect(live).toBeDefined(); + const otherHome = mkdtempSync(join(tmpdir(), "ocx-affinity-other-")); + try { + process.env.OPENCODEX_HOME = otherHome; + key(); + expect(live).toBeUndefined(); + } finally { + process.env.OPENCODEX_HOME = home; + removeTreeWithRetry(otherHome); + } +}); + +for (const kind of ["thread", "issuer"] as const) { + test(`persisted ${kind} delete survives anchor eviction`, () => { + lease = acquireSpendLedgerOwner(); const fence = seed(); const k = bind(fence); + recordIssuerSet(k, "account-a", fence, Date.now()); flushCodexAffinityStoreForTests(); + for (let i = 0; i < 4096; i++) codexConversationKeyFor(`evict-family-${i}`, `evict-thread-${i}`); + if (kind === "thread") recordThreadDelete(k, "legacy"); else recordIssuerDelete(k); + lease.release(); lease = acquireSpendLedgerOwner(); + if (kind === "thread") expect(adoptStoredThreadRows(key(), Date.now())).toEqual([]); + else expect(adoptStoredIssuer(key(), Date.now())).toBeUndefined(); + }); +} + +test("adopted rows retain delete keys after anchor eviction", () => { + lease = acquireSpendLedgerOwner(); const fence = seed(); const k = bind(fence); + recordIssuerSet(k, "account-a", fence, Date.now()); lease.release(); + lease = acquireSpendLedgerOwner(); const adopted = key(); + expect(adoptStoredThreadRows(adopted, Date.now())).toHaveLength(1); + expect(adoptStoredIssuer(adopted, Date.now())?.issuer).toBe("account-a"); + for (let i = 0; i < 4096; i++) codexConversationKeyFor(`adopt-family-${i}`, `adopt-thread-${i}`); + recordThreadDelete(adopted, "legacy"); recordIssuerDelete(adopted); lease.release(); + lease = acquireSpendLedgerOwner(); expect(adoptStoredThreadRows(key(), Date.now())).toEqual([]); + expect(adoptStoredIssuer(key(), Date.now())).toBeUndefined(); +}); + +test("large worst-case batch flushes and restores newest rows", () => { + lease = acquireSpendLedgerOwner(); const fence = seed(); const now = Date.now(); + for (let i = 0; i < 7000; i++) { + const k = codexConversationKeyFor(`batch-${i}`, `batch-${i}`); + const scope = `model-detour:shared:${String(i).padStart(4, "0")}${"é".repeat(254)}`; + recordThreadBind(k, scope, { scope, accountId: "account-a", fence, createdAt: now, lastUsedAt: now - 7000 + i }); + } + flushCodexAffinityStoreForTests(); lease.release(); lease = acquireSpendLedgerOwner(); + expect(adoptStoredThreadRows(codexConversationKeyFor("batch-6999", "batch-6999"), Date.now())).toHaveLength(1); + const db = new Database(path()); expect(db.query("SELECT count(*) AS count FROM threads").get()).toEqual({ count: 2048 }); db.close(); +}); + +test("scoped lookup and account delete reach rows beyond the adoption limit", async () => { + const affinity = await import("../../src/codex/routing/thread-affinity"); + registerThreadAffinityLiveState(); lease = acquireSpendLedgerOwner(); const fence = seed(); const k = key(); const now = Date.now(); + recordThreadBind(k, "shared", { scope: "shared", accountId: "account-a", fence, createdAt: now - 100, lastUsedAt: now - 100 }); + for (let i = 0; i < 70; i++) { const scope = `model-detour:shared:model-${i}`; recordThreadBind(k, scope, { scope, accountId: "account-a", fence, createdAt: now, lastUsedAt: now }); } + lease.release(); lease = acquireSpendLedgerOwner(); const restored = key(); + affinity.getThreadAffinityScopes(restored); + expect(affinity.getThreadAffinity(restored, "shared")?.accountId).toBe("account-a"); + affinity.deleteThreadAffinitiesForAccount(restored, "account-a"); lease.release(); lease = acquireSpendLedgerOwner(); key(); + const db = new Database(path()); expect(db.query("SELECT count(*) AS count FROM threads").get()).toEqual({ count: 0 }); db.close(); +}); + +test("lease acquisition prunes expired rows without affinity access", () => { + lease = acquireSpendLedgerOwner(); bind(seed()); lease.release(); + const db = new Database(path()); db.query("UPDATE threads SET last_used_at=?").run(Date.now() - 25 * 60 * 60_000); db.close(); + lease = acquireSpendLedgerOwner(); + const check = new Database(path()); expect(check.query("SELECT count(*) AS count FROM threads").get()).toEqual({ count: 0 }); check.close(); +}); + +test("poisoned store prunes on its hourly timer", () => { + const originalInterval = globalThis.setInterval; let tick: (() => void) | undefined; + globalThis.setInterval = ((fn: () => void, ms: number) => { if (ms === 3600000) tick = fn; return originalInterval(fn, ms); }) as typeof setInterval; + try { + lease = acquireSpendLedgerOwner(); bind(seed()); flushCodexAffinityStoreForTests(); + const warn = console.warn; console.warn = () => {}; + try { for (let i = 0; i < 16385; i++) recordAccountPinsCleared("other-account"); } finally { console.warn = warn; } + expect(tick).toBeDefined(); const realNow = Date.now; Date.now = () => realNow() + 25 * 60 * 60_000; + try { tick!(); } finally { Date.now = realNow; } + const check = new Database(path()); expect(check.query("SELECT count(*) AS count FROM threads").get()).toEqual({ count: 0 }); expect(check.query("SELECT value FROM meta WHERE name='clean'").get()).toEqual({ value: 0 }); check.close(); + } finally { globalThis.setInterval = originalInterval; } +}); + +test("account deletion removes unadopted scopes and blocks pending adoption", async () => { + const affinity = await import("../../src/codex/routing/thread-affinity"); + registerThreadAffinityLiveState(); lease = acquireSpendLedgerOwner(); const fence = seed(); const k = key(); const now = Date.now(); + for (let i = 0; i < 70; i++) { const scope = `model-detour:shared:delete-${i}`; recordThreadBind(k, scope, { scope, accountId: "account-a", fence, createdAt: now, lastUsedAt: now }); } + lease.release(); lease = acquireSpendLedgerOwner(); const restored = key(); + affinity.deleteThreadAffinitiesForAccount(restored, "account-a"); + expect(affinity.getModelDetourAffinity(restored, "delete-69", "shared")).toBeUndefined(); + lease.release(); lease = acquireSpendLedgerOwner(); + const db = new Database(path()); expect(db.query("SELECT count(*) AS count FROM threads").get()).toEqual({ count: 0 }); db.close(); +}); + +test("SQLITE_FULL triggers one prune-only transaction before retrying the flush", () => { + lease = acquireSpendLedgerOwner(); const fence = seed(); const k = bind(fence); + const original = Database.prototype.exec; let begins = 0; + Database.prototype.exec = function (sql: string) { + if (sql === "BEGIN IMMEDIATE" && ++begins === 1) throw Object.assign(new Error("injected full"), { code: "SQLITE_FULL" }); + return original.call(this, sql); + }; + try { flushCodexAffinityStoreForTests(); } finally { Database.prototype.exec = original; } + expect(begins).toBe(3); + lease.release(); lease = acquireSpendLedgerOwner(); + expect(adoptStoredThreadRows(key(), Date.now())).toHaveLength(1); expect(k).toBeDefined(); +}); + +test("a pin touched since its last flush survives a chunk prune at the row limit", () => { + lease = acquireSpendLedgerOwner(); const fence = seed(); const k = bind(fence); flushCodexAffinityStoreForTests(); + const now = Date.now(); + const db = new Database(path()); const insert = db.query("INSERT INTO threads VALUES (?, ?, ?, ?, ?, ?)"); + db.exec("BEGIN"); for (let i = 0; i < 2047; i++) insert.run(`filler-${i}`, "legacy", "account-a", fence, now - 500, now - 500); db.exec("COMMIT"); db.close(); + recordThreadTouch(k, "legacy"); live!.lastUsedAt = now; + for (let i = 0; i < 256; i++) { const fresh = codexConversationKeyFor(`fresh-${i}`, `fresh-${i}`); recordThreadBind(fresh, "shared", { scope: "shared", accountId: "account-a", fence, createdAt: now, lastUsedAt: now }); } + flushCodexAffinityStoreForTests(); lease.release(); lease = acquireSpendLedgerOwner(); + expect(adoptStoredThreadRows(key(), Date.now())).toHaveLength(1); +}); +test("a failed flush still deletes expired rows", () => { + lease = acquireSpendLedgerOwner(); const fence = seed(); bind(fence); flushCodexAffinityStoreForTests(); + const db = new Database(path()); + db.query("INSERT INTO threads VALUES (?, ?, ?, ?, ?, ?)").run("expired-row", "legacy", "account-a", fence, Date.now() - 25 * 60 * 60_000, Date.now() - 25 * 60 * 60_000); + db.exec("CREATE TRIGGER fail_bind BEFORE INSERT ON threads WHEN NEW.account_id = 'boom' BEGIN SELECT RAISE(ABORT, 'injected'); END"); + db.close(); + recordThreadBind(codexConversationKeyFor("boom-family", "boom-family"), "legacy", { scope: "legacy", accountId: "boom", fence, createdAt: Date.now(), lastUsedAt: Date.now() }); + flushCodexAffinityStoreForTests(); + const check = new Database(path()); + expect((check.query("SELECT count(*) AS n FROM threads WHERE row_key = 'expired-row'").get() as { n: number }).n).toBe(0); + check.exec("DROP TRIGGER fail_bind"); check.close(); +}); +test("a lease acquired inside a passive read does not open the store", async () => { + await runPassiveRead(async () => { lease = acquireSpendLedgerOwner(); }); + expect(existsSync(path())).toBe(false); +}); +test("a release inside a passive read still commits the final flush", async () => { + lease = acquireSpendLedgerOwner(); bind(seed()); + await runPassiveRead(async () => { lease!.release(); }); + lease = acquireSpendLedgerOwner(); + expect(adoptStoredThreadRows(key(), Date.now())).toHaveLength(1); +}); + + +test("a pin bound and touched in the same pending batch survives a chunk prune", () => { + lease = acquireSpendLedgerOwner(); const fence = seed(); flushCodexAffinityStoreForTests(); + const now = Date.now(); + const db = new Database(path()); const insert = db.query("INSERT INTO threads VALUES (?, ?, ?, ?, ?, ?)"); + db.exec("BEGIN"); for (let i = 0; i < 2048; i++) insert.run(`filler-${i}`, "legacy", "account-a", fence, now - 500, now - 500); db.exec("COMMIT"); db.close(); + const k = bind(fence); recordThreadTouch(k, "legacy"); live!.lastUsedAt = now; + for (let i = 0; i < 255; i++) { const fresh = codexConversationKeyFor(`batch-${i}`, `batch-${i}`); recordThreadBind(fresh, "shared", { scope: "shared", accountId: "account-a", fence, createdAt: now, lastUsedAt: now }); } + flushCodexAffinityStoreForTests(); lease.release(); lease = acquireSpendLedgerOwner(); + expect(adoptStoredThreadRows(key(), Date.now())).toHaveLength(1); +}); + +test("row keys carried across a lease change still let a delete reach its row after anchor eviction", () => { + lease = acquireSpendLedgerOwner(); const fence = seed(); const k = bind(fence); + recordIssuerSet(k, "account-a", fence, Date.now()); lease.release(); + lease = acquireSpendLedgerOwner(); const adopted = key(); + expect(adoptStoredThreadRows(adopted, Date.now())).toHaveLength(1); + expect(adoptStoredIssuer(adopted, Date.now())?.issuer).toBe("account-a"); + lease.release(); lease = acquireSpendLedgerOwner(); + for (let i = 0; i < 4096; i++) codexConversationKeyFor(`carry-family-${i}`, `carry-thread-${i}`); + recordThreadDelete(adopted, "legacy"); recordIssuerDelete(adopted); lease.release(); + resetCodexAffinityStoreForTests(); lease = acquireSpendLedgerOwner(); + expect(adoptStoredThreadRows(key(), Date.now())).toEqual([]); + expect(adoptStoredIssuer(key(), Date.now())).toBeUndefined(); +}); + +test("row keys survive a failed reopen, so a later delete still reaches its row after anchor eviction", () => { + lease = acquireSpendLedgerOwner(); const fence = seed(); bind(fence); lease.release(); + lease = acquireSpendLedgerOwner(); const adopted = key(); + expect(adoptStoredThreadRows(adopted, Date.now())).toHaveLength(1); + lease.release(); + // One reacquisition cannot open the database (a directory sits at its path). + renameSync(path(), `${path()}.aside`); mkdirSync(path()); + lease = acquireSpendLedgerOwner(); lease.release(); + removeTreeWithRetry(path()); renameSync(`${path()}.aside`, path()); + lease = acquireSpendLedgerOwner(); + for (let i = 0; i < 4096; i++) codexConversationKeyFor(`reopen-family-${i}`, `reopen-thread-${i}`); + recordThreadDelete(adopted, "legacy"); lease.release(); + resetCodexAffinityStoreForTests(); lease = acquireSpendLedgerOwner(); + expect(adoptStoredThreadRows(key(), Date.now())).toEqual([]); +}); diff --git a/tests/codex-integration/codex-lineage-placement.test.ts b/tests/codex-integration/codex-lineage-placement.test.ts index 496c49e2929..5b492ffdbd7 100644 --- a/tests/codex-integration/codex-lineage-placement.test.ts +++ b/tests/codex-integration/codex-lineage-placement.test.ts @@ -30,11 +30,13 @@ import { CODEX_LINEAGE_MAX_ENTRIES, CODEX_LINEAGE_MAX_SCOPES, clearCodexThreadLineageForTests, + codexConversationKeyFor, codexLineageRootForRequest, codexLineageScopeKey, codexLineageWorkflowLane, codexThreadLineageLookup, recordCodexThreadLineage, + setCodexConversationAnchorObserver, } from "../../src/codex/lineage"; import { clearPoolRotationState } from "../../src/codex/pool-rotation"; import { saveCodexAccountCredential } from "../../src/codex/account-store"; @@ -52,6 +54,23 @@ const ICACLS_OK = { success: true, exitCode: 0, timedOut: false, stdout: "" }; const ACCOUNT_IDS = ["a", "b", "c"] as const; const NOW = 1_700_000_000_000; +test("lineage observer receives the derived key and cohort anchor", () => { + const seen: Array<[string, string, string]> = []; + setCodexConversationAnchorObserver((key, family, thread) => seen.push([key, family, thread])); + try { + const key = codexConversationKeyFor("cohort", "cohort"); + expect(seen).toEqual([[key, "cohort", "cohort"]]); + expect(codexConversationKeyFor("cohort", "cohort")).toBe(key); + expect(seen).toHaveLength(2); + const other = codexConversationKeyFor("family", "thread"); + expect(seen[2]).toEqual([other, "family", "thread"]); + } finally { + setCodexConversationAnchorObserver(); + } + codexConversationKeyFor("cohort", "cohort"); + expect(seen).toHaveLength(3); +}); + function installScratchHome(): void { previousOpencodexHome = process.env.OPENCODEX_HOME; previousCodexHome = process.env.CODEX_HOME; diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index a839b41d9d3..91ca46d40b0 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -657,6 +657,7 @@ "codex-inject-write-lock.test.ts": "codex-integration", "codex-inject.test.ts": "codex-integration", "codex-injected-marker.test.ts": "codex-integration", "codex-integration-record.test.ts": "codex-integration", "codex-journal-recovery.test.ts": "codex-integration", "codex-journal.test.ts": "codex-integration", "codex-legacy-config-keys.test.ts": "codex-integration", + "codex-affinity-store.test.ts": "codex-integration", "codex-lineage-placement.test.ts": "codex-integration", "codex-log-guard-coderabbit.test.ts": "codex-integration", "codex-log-guard-doctor-coderabbit.test.ts": "codex-integration", "codex-log-guard-doctor-protection.test.ts": "codex-integration", @@ -697,7 +698,7 @@ "codex-restart-contract-parity.test.ts": "codex-integration", "codex-restart-route.test.ts": "codex-integration", "codex-restore-app-rewrite.test.ts": "codex-integration", "codex-retained-root-serialization.test.ts": "codex-integration", - "codex-routing-cache-affinity-detour.test.ts": "codex-integration", "codex-routing-elapsed-short-reset.test.ts": "codex-integration", "codex-routing.test.ts": "codex-integration", + "codex-affinity-restart.test.ts": "codex-integration", "codex-affinity-restart-matrix.test.ts": "codex-integration", "codex-affinity-request-owned.test.ts": "codex-integration", "codex-affinity-lease-gap.test.ts": "codex-integration", "codex-routing-cache-affinity-detour.test.ts": "codex-integration", "codex-routing-elapsed-short-reset.test.ts": "codex-integration", "codex-routing.test.ts": "codex-integration", "codex-runtime.test.ts": "codex-integration", "codex-runtime-macos-desktop.test.ts": "codex-integration", "codex-runtime-wsl-desktop.test.ts": "codex-integration", "codex-clamp-notice.test.ts": "codex-integration", "codex-service-manager-probe-hardening.test.ts": "codex-integration", "codex-service-manager-probe.test.ts": "codex-integration", "codex-systemd-env-probe.test.ts": "codex-integration", diff --git a/tests/helpers/codex-affinity-handler-worker.ts b/tests/helpers/codex-affinity-handler-worker.ts new file mode 100644 index 00000000000..3e0e59182e9 --- /dev/null +++ b/tests/helpers/codex-affinity-handler-worker.ts @@ -0,0 +1,27 @@ +import { acquireSpendLedgerOwner } from "../../src/lib/spend-ledger-owner"; +import { handleResponses, handleResponsesCompact } from "../../src/server/responses"; +import { compactionRequest, completedPayload, jsonResponse, sseResponse, twoAccountPoolConfig } from "./compaction-routing-fixtures"; + +const lease = acquireSpendLedgerOwner(); +const config = twoAccountPoolConfig(); +config.codexAccounts = ["a", "b"].map(id => ({ id, email: `${id}@test`, isMain: false, chatgptAccountId: `acct-${id}` })); +config.activeCodexAccountId = "a"; +config.codexAccountNamespaces = { side: "b" }; +const bodies: Array> = []; +const turnStates: Array = []; +const mock = (async (input: string | URL | Request, init?: RequestInit) => { + const request = new Request(input, init); + turnStates.push(request.headers.get("x-codex-turn-state")); + bodies.push(await request.json() as Record); + return request.url.endsWith("/compact") ? jsonResponse({ output: [] }) : sseResponse([{ type: "response.completed", response: completedPayload("ok") }]); +}) as typeof fetch; +globalThis.fetch = mock; +for (const provider of Object.values(config.providers)) Object.assign(provider, { fetch: mock, upstreamWebsocket: false }); +const body = { model: process.argv[3] === "same" ? "gpt-5.5" : "side/gpt-5.5", stream: false, client_metadata: { "x-codex-turn-state": "old-state" }, input: [{ type: "message", role: "user", content: [{ type: "input_file", file_id: "file-test" }] }] }; +const request = compactionRequest(body, undefined, { "session-id": "restart-session", "thread-id": "restart-thread", "x-codex-turn-state": "old-state" }); +const response = process.argv[2] === "compact" + ? await handleResponsesCompact(request, config, { model: "", provider: "" }) + : await handleResponses(request, config, { model: "", provider: "" }); +const responseBody = await response.text(); +lease.release(); +console.log(JSON.stringify({ status: response.status, bodies, responseBody, turnStates })); diff --git a/tests/helpers/codex-affinity-home-switch-worker.ts b/tests/helpers/codex-affinity-home-switch-worker.ts new file mode 100644 index 00000000000..5f95f1cd7bc --- /dev/null +++ b/tests/helpers/codex-affinity-home-switch-worker.ts @@ -0,0 +1,40 @@ +import { Database } from "bun:sqlite"; +import { join } from "node:path"; +import { codexConversationKeyFor, recordCodexThreadLineage } from "../../src/codex/lineage"; +import { acquireSpendLedgerOwner } from "../../src/lib/spend-ledger-owner"; +import { bindThreadAffinity, getThreadAffinity } from "../../src/codex/routing/thread-affinity"; +import { resolveCodexAccountForThread } from "../../src/codex/routing"; +import type { OcxConfig } from "../../src/types"; + +const homeA = process.env.OPENCODEX_HOME!; +const homeB = process.argv[2]!; +const config = { providers: {}, codexAccounts: ["a", "b"].map(id => ({ id, email: `${id}@test`, isMain: false })), activeCodexAccountId: "a", accountPoolStrategy: "round-robin" } as OcxConfig; +let lease = acquireSpendLedgerOwner(); +const oldHeaders = new Headers({ "thread-id": "old-thread", "x-codex-parent-thread-id": "old-family" }); +const oldKey = recordCodexThreadLineage(oldHeaders)!.conversationKey; +bindThreadAffinity(oldKey, "a", Date.now()); // deliberately unflushed +process.env.OPENCODEX_HOME = homeB; +const freshKey = codexConversationKeyFor("new-family", "new-thread"); // retires A while its write is pending +lease.release(); +lease = acquireSpendLedgerOwner(); +// Derive again under B's owner, then route B's first request. +codexConversationKeyFor("new-family", "new-thread"); +const first = resolveCodexAccountForThread(freshKey, config); +bindThreadAffinity(oldKey, "b", Date.now()); // no anchor for A's key in B +lease.release(); +const dbB = new Database(join(homeB, "codex-affinity.sqlite")); +const rowsB = (dbB.query("SELECT count(*) AS n FROM threads").get() as { n: number }).n; +dbB.close(); +process.env.OPENCODEX_HOME = homeA; +codexConversationKeyFor("switch", "switch"); +process.env.OPENCODEX_HOME = homeB; +lease = acquireSpendLedgerOwner(); +const restoredB = getThreadAffinity(codexConversationKeyFor("new-family", "new-thread"))?.accountId; +const oldInB = getThreadAffinity(recordCodexThreadLineage(oldHeaders)!.conversationKey)?.accountId; +lease.release(); +process.env.OPENCODEX_HOME = homeA; +lease = acquireSpendLedgerOwner(); +const oldInA = getThreadAffinity(recordCodexThreadLineage(oldHeaders)!.conversationKey)?.accountId; +const newInA = getThreadAffinity(codexConversationKeyFor("new-family", "new-thread"))?.accountId; +lease.release(); +console.log(JSON.stringify({ first, rowsB, restoredB, oldInB, oldInA, newInA })); diff --git a/tests/helpers/codex-affinity-matrix-worker.ts b/tests/helpers/codex-affinity-matrix-worker.ts new file mode 100644 index 00000000000..4870a0ac057 --- /dev/null +++ b/tests/helpers/codex-affinity-matrix-worker.ts @@ -0,0 +1,191 @@ +import { Database } from "bun:sqlite"; +import { join } from "node:path"; +import { readFileSync } from "node:fs"; +import { acquireSpendLedgerOwner, assertStorageOwned, mintSpendLedgerStorage } from "../../src/lib/spend-ledger-owner"; +import { readCodexAccountRecord, removeCodexAccountCredential, saveCodexAccountCredential, saveCodexAccountCredentialIfGeneration } from "../../src/codex/account-store"; +import { codexPoolAffinityKey } from "../../src/codex/auth-context"; +import { recordCodexThreadLineage } from "../../src/codex/lineage"; +import { runPassiveRead } from "../../src/lib/passive-read"; +import { adoptStoredThreadRows } from "../../src/codex/routing/thread-affinity-store"; +import { recordCodexUpstreamOutcome, resolveCodexAccountForThread, resolveCodexAccountForThreadDetailed } from "../../src/codex/routing"; +import { bindThreadAffinity, clearConversationStateIssuerMap, clearThreadAccountMap, clearThreadAccountMapForAccount, deleteThreadAffinity, deleteThreadAffinitiesForAccount, getThreadAffinity, handOffThreadAffinityGeneration, peekConversationStateIssuer, rememberConversationStateIssuer } from "../../src/codex/routing/thread-affinity"; +import type { OcxConfig } from "../../src/types"; + +const action = process.argv[2]!; +let hourly: (() => void) | undefined; +if (action === "hourly") { + const original = globalThis.setInterval; + globalThis.setInterval = ((callback: TimerHandler, delay?: number) => { + if (delay === 3_600_000) hourly = callback as () => void; + return original(callback, delay); + }) as typeof setInterval; +} +const lease = acquireSpendLedgerOwner(); +const config = { providers: {}, codexAccounts: ["a", "b"].map(id => ({ id, email: `${id}@test`, isMain: false })), activeCodexAccountId: "a", accountPoolStrategy: "round-robin", autoSwitchThreshold: 80, upstreamFailoverThreshold: 3 } as OcxConfig; +if (action === "passive") { + const file = join(process.env.OPENCODEX_HOME!, "codex-affinity.sqlite"); + const before = readFileSync(file); + await runPassiveRead(async () => { + const passiveKey = codexPoolAffinityKey(new Headers({ "session-id": "restart-session", "thread-id": "restart-thread" }))!; + getThreadAffinity(passiveKey); + peekConversationStateIssuer(passiveKey); + clearThreadAccountMap(); + }); + const unchanged = before.equals(readFileSync(file)); + lease.release(); + console.log(JSON.stringify({ unchanged })); + process.exit(0); +} +const key = codexPoolAffinityKey(new Headers({ "session-id": "restart-session", "thread-id": "restart-thread" }))!; +const cred = (id: string) => ({ accessToken: `access-${id}`, refreshToken: `refresh-${id}`, expiresAt: Date.now() + 600_000, chatgptAccountId: `acct-${id}` }); + +if (action === "open-count" || action === "hourly") { + const db = new Database(join(process.env.OPENCODEX_HOME!, "codex-affinity.sqlite")); + if (action === "hourly") { + const realNow = Date.now; + Date.now = () => realNow() + 25 * 60 * 60_000; + hourly?.(); + } + const threads = db.query("SELECT count(*) AS n FROM threads").get(); + const issuers = db.query("SELECT count(*) AS n FROM issuers").get(); + const expired = db.query("SELECT count(*) AS n FROM threads WHERE row_key='expired'").get(); + db.close(); + lease.release(); + console.log(JSON.stringify({ threads, issuers, expired, scheduled: !!hourly })); + process.exit(0); +} + +if (action === "probe") { + getThreadAffinity(key); + lease.release(); + process.exit(0); +} +if (action.startsWith("late-")) { + bindThreadAffinity(key, "a", Date.now()); + const record = readCodexAccountRecord("a")!; + rememberConversationStateIssuer(key, "a", undefined, { generation: record.generation, chatgptAccountId: record.credential!.chatgptAccountId }); + lease.release(); + if (action === "late-bind") bindThreadAffinity(key, "b", Date.now()); + if (action === "late-delete") deleteThreadAffinity(key); + if (action === "late-issuer") rememberConversationStateIssuer(key, "b"); + const next = acquireSpendLedgerOwner(); + const freshKey = codexPoolAffinityKey(new Headers({ "session-id": "restart-session", "thread-id": "restart-thread" }))!; + const pin = getThreadAffinity(freshKey)?.accountId; + const issuer = peekConversationStateIssuer(freshKey); + next.release(); + console.log(JSON.stringify({ pin, issuer })); + process.exit(0); +} +if (action === "shared-write") { + bindThreadAffinity(key, "a", Date.now(), "shared"); + lease.release(); + process.exit(0); +} +if (action === "scopes") { + const scopes = adoptStoredThreadRows(key, Date.now()).map(row => row.scope); + lease.release(); + console.log(JSON.stringify({ scopes })); + process.exit(0); +} + +if (action.startsWith("depth-")) { + const child = new Headers({ "thread-id": "child", "x-codex-parent-thread-id": "root" }); + const grandchild = new Headers({ "thread-id": "grandchild", "x-codex-parent-thread-id": "child" }); + if (action === "depth-write") { + const lineage = recordCodexThreadLineage(child)!; + bindThreadAffinity(lineage.conversationKey, "a", Date.now()); + if (recordCodexThreadLineage(grandchild)!.conversationKey !== lineage.conversationKey) throw new Error("lineage did not converge"); + lease.release(); + } else { + resolveCodexAccountForThread("advance-cursor", config); + const headers = action === "depth-one" ? child : grandchild; + const selected = resolveCodexAccountForThread(codexPoolAffinityKey(headers)!, config); + lease.release(); + console.log(JSON.stringify({ selected })); + } + process.exit(0); +} else if (action.startsWith("race-")) { + const record = readCodexAccountRecord("a")!; + bindThreadAffinity(key, "a", Date.now()); + if (action === "race-relogin" || action === "race-issuer") saveCodexAccountCredential("a", cred("a")); + if (action === "race-delete-add") { + removeCodexAccountCredential("a"); + saveCodexAccountCredential("a", cred("a")); + } + if (action === "race-refresh" || action === "race-external") { + if (!saveCodexAccountCredentialIfGeneration("a", record.generation, { ...cred("a"), accessToken: "rotated" })) throw new Error("refresh failed"); + if (action === "race-refresh" && !handOffThreadAffinityGeneration("a", record.generation, record.generation + 1)) throw new Error("handoff failed"); + } + if (action === "race-issuer") rememberConversationStateIssuer(key, "a", undefined, { generation: record.generation, chatgptAccountId: record.credential!.chatgptAccountId }); +} else if (action === "write-main") { + bindThreadAffinity(key, "__main__", Date.now()); + rememberConversationStateIssuer(key, "__main__"); +} else if (action === "lease") { + const second = acquireSpendLedgerOwner(); + const token = mintSpendLedgerStorage("codex-affinity.sqlite"); + bindThreadAffinity(key, "a", Date.now()); + lease.release(); + const db = new Database(join(process.env.OPENCODEX_HOME!, "codex-affinity.sqlite")); + const before = db.query("SELECT count(*) AS n FROM threads").get() as { n: number }; + db.close(); + second.release(); + const again = acquireSpendLedgerOwner(); + let rejected = false; + try { assertStorageOwned(token); } catch { rejected = true; } + again.release(); + console.log(JSON.stringify({ before: before.n, rejected })); + process.exit(0); +} else { + if (action === "removed") removeCodexAccountCredential("a"); + if (action === "relogin") saveCodexAccountCredential("a", cred("a")); + if (action === "paused") config.pausedCodexAccountIds = ["a"]; + if (action === "plan") { + config.codexAccounts = [{ id: "a", email: "a@test", isMain: false, plan: "free" }, { id: "b", email: "b@test", isMain: false, plan: "plus" }]; + config.codexPool = { excludedPlans: ["free"] }; + } + if (action === "reauth" || action === "cooldown" || action === "transient") { + if (getThreadAffinity(key)?.accountId !== "a") throw new Error("expected restored affinity"); + const status = action === "reauth" ? 401 : action === "cooldown" ? 429 : 503; + for (let i = 0; i < (action === "transient" ? 3 : 1); i++) recordCodexUpstreamOutcome(config, "a", status, { now: Date.now() }); + } + if (action === "bind") bindThreadAffinity(key, "b", Date.now()); + if (action === "delete") deleteThreadAffinity(key); + if (action === "delete-account") deleteThreadAffinitiesForAccount(key, "a"); + if (action === "clear-account") clearThreadAccountMapForAccount("a"); + if (action === "clear") clearThreadAccountMap(); + if (action === "clear-issuer") clearConversationStateIssuerMap(); + if (action === "issuer") { + const record = readCodexAccountRecord("b")!; + rememberConversationStateIssuer(key, "b", undefined, { generation: record.generation, chatgptAccountId: record.credential!.chatgptAccountId }); + } + if (action === "touch") { + const timestamp = Date.now(); + resolveCodexAccountForThread(key, config, timestamp); + lease.release(); + const db = new Database(join(process.env.OPENCODEX_HOME!, "codex-affinity.sqlite")); + const row = db.query("SELECT last_used_at AS timestamp FROM threads").get(); + db.close(); + console.log(JSON.stringify({ timestamp, row })); + process.exit(0); + } + const before = getThreadAffinity(key, action === "model-excluded" ? "shared" : undefined)?.accountId; + const issuer = peekConversationStateIssuer(key); + resolveCodexAccountForThread("advance-cursor", config); + if (action === "model-excluded") { + const result = resolveCodexAccountForThreadDetailed(key, config, Date.now(), "shared", { modelEligibleAccountIds: new Set(["b"]) }, "gpt-test"); + const shared = resolveCodexAccountForThread(key, config, Date.now(), "shared"); + lease.release(); + console.log(JSON.stringify({ before, result, shared })); + process.exit(0); + } + const selected = resolveCodexAccountForThread(key, config); + const after = getThreadAffinity(key)?.accountId; + lease.release(); + const db = new Database(join(process.env.OPENCODEX_HOME!, "codex-affinity.sqlite")); + const rows = db.query("SELECT account_id FROM threads WHERE account_id='a'").all().length; + const issuers = db.query("SELECT count(*) AS n FROM issuers").get() as { n: number }; + db.close(); + console.log(JSON.stringify({ before, issuer, selected, after, rows, issuers: issuers.n })); + process.exit(0); +} +lease.release(); diff --git a/tests/helpers/codex-affinity-restart-worker.ts b/tests/helpers/codex-affinity-restart-worker.ts new file mode 100644 index 00000000000..8ae88a73858 --- /dev/null +++ b/tests/helpers/codex-affinity-restart-worker.ts @@ -0,0 +1,46 @@ +import { acquireSpendLedgerOwner } from "../../src/lib/spend-ledger-owner"; +import { readCodexAccountRecord, saveCodexAccountCredential } from "../../src/codex/account-store"; +import { codexPoolAffinityKey } from "../../src/codex/auth-context"; +import { resolveCodexAccountForThread, rememberConversationStateIssuer, peekConversationStateIssuer } from "../../src/codex/routing"; +import { applyAccountChangeConversationStateScrub, accountChangeFileReferenceRefusal } from "../../src/server/responses/account-change-state"; +import type { OcxConfig } from "../../src/types"; + +const action = process.argv[2]; +if (action === "touch-unknown" || action === "read-unknown") { + const realNow = Date.now; + Date.now = () => realNow() + (action === "touch-unknown" ? 23 : 25) * 60 * 60_000; +} +const lease = acquireSpendLedgerOwner(); +for (const id of ["a", "b"]) if (!readCodexAccountRecord(id)) saveCodexAccountCredential(id, { + accessToken: `access-${id}`, refreshToken: `refresh-${id}`, expiresAt: Date.now() + 600_000, chatgptAccountId: `acct-${id}`, +}); +const config = { providers: {}, codexAccounts: ["a", "b"].map(id => ({ id, email: `${id}@test`, isMain: false })), activeCodexAccountId: "a", accountPoolStrategy: "round-robin", autoSwitchThreshold: 80, upstreamFailoverThreshold: 3 } as OcxConfig; +if (process.argv[2] === "read") resolveCodexAccountForThread("advance-cursor", config); +const key = codexPoolAffinityKey(new Headers({ "session-id": "restart-session", "thread-id": "restart-thread" }))!; +const issuer = peekConversationStateIssuer(key); +if (action === "touch-unknown" || action === "read-unknown") { + lease.release(); + console.log(JSON.stringify({ issuer })); + process.exit(0); +} +const account = resolveCodexAccountForThread(key, config)!; +const sameBody = { previous_response_id: "previous" }; +const otherBody = { previous_response_id: "previous" }; +const sameScrub = applyAccountChangeConversationStateScrub({ body: sameBody, bindingKey: key, servingAccountId: account }); +const otherScrub = applyAccountChangeConversationStateScrub({ body: otherBody, bindingKey: key, servingAccountId: account === "a" ? "b" : "a" }); +const fileBody = { previous_response_id: "previous", input: [{ type: "input_file", file_id: "file-test" }] }; +const fileRefusal = accountChangeFileReferenceRefusal({ body: fileBody, bindingKey: key, servingAccountId: account })?.status; +const otherFileRefusal = accountChangeFileReferenceRefusal({ body: fileBody, bindingKey: key, servingAccountId: account === "a" ? "b" : "a" })?.status; +const retryRefusal = accountChangeFileReferenceRefusal({ body: fileBody, bindingKey: key, servingAccountId: account, priorAccountId: account === "a" ? "b" : "a" })?.status; +const record = readCodexAccountRecord(account)!; +rememberConversationStateIssuer(key, account, undefined, process.argv[2] === "unknown-write" ? undefined : { generation: record.generation, chatgptAccountId: record.credential!.chatgptAccountId }); +if (process.argv[2] === "relogin") saveCodexAccountCredential(account, { + accessToken: "new-access", refreshToken: "new-refresh", expiresAt: Date.now() + 600_000, chatgptAccountId: "new-identity", +}); +if (process.argv[2] === "crash") { + const store = await import("../../src/codex/routing/thread-affinity-store").catch(() => undefined); + store?.flushCodexAffinityStoreForTests(); + process.kill(process.pid, "SIGKILL"); +} +lease.release(); +console.log(JSON.stringify({ account, issuer, sameScrub, otherScrub, fileRefusal, otherFileRefusal, retryRefusal })); diff --git a/tests/lib/spend-ledger-owner.test.ts b/tests/lib/spend-ledger-owner.test.ts index 25584deb8bb..e0091e7e839 100644 --- a/tests/lib/spend-ledger-owner.test.ts +++ b/tests/lib/spend-ledger-owner.test.ts @@ -7,6 +7,9 @@ import { acquireSpendLedgerOwner, SPEND_LEDGER_OWNER_FILENAME, mintSpendLedgerStorage, + onSpendLedgerOwnerReleasing, + onSpendLedgerOwnerAcquired, + assertStorageOwned, SPEND_LEDGER_RESTART_PARENT_ENV, SpendLedgerOwnerError, spendLedgerRestartEnvironment, @@ -239,6 +242,47 @@ describe("in-process references and privacy", () => { for (const lease of leases.splice(0).reverse()) lease.release(); }); + test("acquired hooks run once per new owner and isolate failures", () => { + let enabled = true; let calls = 0; let later = 0; + onSpendLedgerOwnerAcquired(() => { if (enabled) { calls++; throw new Error("failure"); } }); + onSpendLedgerOwnerAcquired(() => { if (enabled) later++; }); + const first = acquireSpendLedgerOwner(); const second = acquireSpendLedgerOwner(); + expect([calls, later]).toEqual([1, 1]); first.release(); second.release(); + const third = acquireSpendLedgerOwner(); expect([calls, later]).toEqual([2, 2]); third.release(); enabled = false; + }); + + test("final release runs isolated hooks with existing storage but refuses new ownership", () => { + const first = acquireSpendLedgerOwner(); + const second = acquireSpendLedgerOwner(); + const token = mintSpendLedgerStorage("hook-test.sqlite"); + let calls = 0; + let enabled = true; + let tokenAccepted = false; + const refusalCodes: unknown[] = []; + onSpendLedgerOwnerReleasing(() => { + if (!enabled) return; + calls++; + try { assertStorageOwned(token); tokenAccepted = true; } catch { /* checked below */ } + for (const action of [() => acquireSpendLedgerOwner(), () => mintSpendLedgerStorage("new.sqlite")]) { + try { action(); refusalCodes.push("accepted"); } + catch (error) { refusalCodes.push((error as SpendLedgerOwnerError).code); } + } + throw new Error("hook failure"); + }); + let subsequent = 0; + onSpendLedgerOwnerReleasing(() => { if (enabled) subsequent++; }); + first.release(); + expect(calls).toBe(0); + second.release(); + second.release(); + expect(calls).toBe(1); + expect(subsequent).toBe(1); + expect(tokenAccepted).toBe(true); + expect(refusalCodes).toEqual(["SPEND_LEDGER_OWNER_NOT_HELD", "SPEND_LEDGER_OWNER_NOT_HELD"]); + expect(spendLedgerOwnerSnapshot().ownership).toBe("unheld"); + enabled = false; + }); + test("two leases share ownership and one release does not free it", async () => { const first = acquireSpendLedgerOwner(); const second = acquireSpendLedgerOwner(); @@ -435,6 +479,9 @@ describe("backing file identity", () => { readFileSync(join(home, CONFIG_UNINSTALL_MANIFEST), "utf8"), ) as { paths: string[] }; expect(manifest.paths).toContain(SPEND_LEDGER_OWNER_FILENAME); + for (const suffix of ["", "-journal", "-wal", "-shm"]) { + expect(manifest.paths).toContain(`codex-affinity.sqlite${suffix}`); + } for (const sidecar of ["-journal", "-wal", "-shm"]) { expect(manifest.paths).toContain(`${SPEND_LEDGER_OWNER_FILENAME}${sidecar}`); } diff --git a/tests/responses/native-compaction-gateway-credentials.test.ts b/tests/responses/native-compaction-gateway-credentials.test.ts index fb53f6d4ea8..035a6fe1bee 100644 --- a/tests/responses/native-compaction-gateway-credentials.test.ts +++ b/tests/responses/native-compaction-gateway-credentials.test.ts @@ -1,11 +1,17 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import * as registry from "../../src/providers/registry"; +import * as authContext from "../../src/codex/auth-context"; import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { createHash } from "node:crypto"; import { clearAccountNeedsReauth, clearAccountQuota } from "../../src/codex/auth-api"; import { clearCodexUpstreamHealth, clearThreadAccountMap } from "../../src/codex/routing"; +import { clearPoolRotationState } from "../../src/codex/pool-rotation"; +import { clearPoolRecoveryState } from "../../src/routing/probe-lease"; +import { setAccountQuotaFromParsed } from "../../src/codex/quota"; +import { codexPoolAffinityKey } from "../../src/codex/auth-context"; +import { peekConversationStateIssuer, rememberConversationStateIssuer } from "../../src/codex/routing/thread-affinity"; import { handleResponsesCompact } from "../../src/server/responses"; import { clearCompactHandoffRoutesForTests } from "../../src/server/responses/compact"; import { clearResponseStateForTests, clearResponseStateMemoryForTests } from "../../src/responses/state"; @@ -82,6 +88,9 @@ beforeEach(() => { clearAccountQuota(); clearCodexUpstreamHealth(); clearThreadAccountMap(); + clearPoolRotationState(); + clearPoolRecoveryState(); + setAccountQuotaFromParsed("work", { weeklyPercent: 10 }); clearResponseStateMemoryForTests(); writeFileSync(join(home, "codex-accounts.json"), JSON.stringify({ work: record("work-access", "work-refresh", "acc-work"), @@ -98,6 +107,8 @@ afterEach(() => { clearAccountQuota(); clearCodexUpstreamHealth(); clearThreadAccountMap(); + clearPoolRotationState(); + clearPoolRecoveryState(); clearResponseStateForTests(); if (previousOcxHome === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previousOcxHome; @@ -107,6 +118,26 @@ afterEach(() => { }); describe("native compact gateway credential boundary", () => { + test("gateway turn state is removed after an account-change scrub", async () => { + const realMode = registry.providerCodexAccountMode; + const modeSpy = spyOn(registry, "providerCodexAccountMode").mockImplementation((id, provider) => + id === "gw" ? "pool" : realMode(id, provider)); + const request = compactRequest(); + const key = codexPoolAffinityKey(request.headers)!; + rememberConversationStateIssuer(key, "other"); + const config = gatewayConfig(); + config.providers.gw!.headers!["x-codex-turn-state"] = "configured"; + const states: Array = []; + globalThis.fetch = (async (_input, init) => { + states.push(new Headers(init?.headers).get("x-codex-turn-state")); + return Response.json({ object: "response.compaction", output: [] }); + }) as typeof fetch; + try { + const response = await handleResponsesCompact(request, config, { model: "", provider: "" }); + expect(response.status).toBe(200); + expect(states).toEqual([null]); + } finally { modeSpy.mockRestore(); } + }); test.each([401, 429])("gateway %i never receives a stored Codex credential", async status => { // The router pins the only pool-mode row to the canonical URL today. Model a relaxation of that // pin: the native gateway send must hold the boundary on its own. @@ -124,3 +155,94 @@ describe("native compact gateway credential boundary", () => { } }); }); + +describe("native compact account-change replay", () => { + function request(key: string, file = false): Request { + return new Request("http://localhost/v1/responses/compact", { + method: "POST", + headers: { "content-type": "application/json", authorization: "Bearer caller-token", "chatgpt-account-id": "caller-account", "x-codex-parent-thread-id": key, "x-codex-turn-state": "old-turn" }, + body: JSON.stringify({ model: "gpt-5.5", previous_response_id: "old-response", conversation: "old-conversation", client_metadata: { "x-codex-turn-state": "old-turn" }, input: file ? [{ type: "message", role: "user", content: [{ type: "input_file", file_id: "file-fixture" }] }] : [{ role: "user", content: "history" }] }), + }); + } + function config(): OcxConfig { + return { ...gatewayConfig(), defaultProvider: "openai", providers: { openai: { + adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", authMode: "forward", codexAccountMode: "pool", + } }, codexAccounts: [{ id: "work", label: "work" }] } as OcxConfig; + } + test.each(["other", "work"])("401 refresh preserves only same-account turn state, issuer=%s", async issuer => { + const req = request(`refresh-${issuer}`); + rememberConversationStateIssuer(codexPoolAffinityKey(req.headers)!, issuer); + const resolve = authContext.resolveCodexAuthContext; + const spy = spyOn(authContext, "resolveCodexAuthContext").mockImplementation((headers, cfg, mode, options) => { + const poolHeaders = new Headers(headers); poolHeaders.delete("authorization"); poolHeaders.delete("chatgpt-account-id"); + return resolve(poolHeaders, cfg, mode, { ...options, requestScopedMainCredential: false }); + }); + const states: Array = []; + globalThis.fetch = (async (input, init) => { + if (String(input).includes("auth.openai.com")) return Response.json({ access_token: "refreshed-access", refresh_token: "rotated-refresh", expires_in: 3600 }); + states.push(new Headers(init?.headers).get("x-codex-turn-state")); + return states.length === 1 ? Response.json({ error: "unauthorized" }, { status: 401 }) : Response.json({ object: "response.compaction", output: [] }); + }) as typeof fetch; + try { + const response = await handleResponsesCompact(req, config(), { model: "", provider: "" }); + expect(response.status).toBe(200); + expect(states).toEqual(issuer === "other" ? [null, null] : ["old-turn", "old-turn"]); + } finally { spy.mockRestore(); } + }); + + test.each([429, 503])("pool to caller main scrubs request on %i alternate", async status => { + const req = request(`alternate-${status}`); + const key = codexPoolAffinityKey(req.headers)!; + rememberConversationStateIssuer(key, "work"); + const resolve = authContext.resolveCodexAuthContext; + const spy = spyOn(authContext, "resolveCodexAuthContext").mockImplementation((headers, cfg, mode, options) => { + if (options?.excludeAccountId) return Promise.resolve({ kind: "main", accountId: null }); + const poolHeaders = new Headers(headers); poolHeaders.delete("authorization"); poolHeaders.delete("chatgpt-account-id"); + return resolve(poolHeaders, cfg, mode, { ...options, requestScopedMainCredential: false }); + }); + const calls: Array<{ headers: Headers; body: Record }> = []; + globalThis.fetch = (async (_input, init) => { + calls.push({ headers: new Headers(init?.headers), body: JSON.parse(String(init?.body)) }); + return calls.length === 1 ? Response.json({ error: { message: "unavailable" } }, { status, headers: { "retry-after": "600" } }) : Response.json({ object: "response.compaction", output: [] }); + }) as typeof fetch; + try { + const response = await handleResponsesCompact(req, config(), { model: "", provider: "" }); + expect(response.status).toBe(200); + expect(calls).toHaveLength(2); + expect(calls[0]!.headers.get("authorization")).toBe("Bearer work-access"); + expect(calls[1]!.headers.get("authorization")).toBe("Bearer caller-token"); + expect(calls[0]!.headers.get("x-codex-turn-state")).toBe("old-turn"); + expect(calls[0]!.body.previous_response_id).toBe("old-response"); + expect(calls[1]!.headers.get("x-codex-turn-state")).toBeNull(); + expect(calls[1]!.body.previous_response_id).toBeUndefined(); + expect(calls[1]!.body.conversation).toBeUndefined(); + expect(calls[1]!.body.client_metadata?.["x-codex-turn-state"]).toBeUndefined(); + expect(peekConversationStateIssuer(key)).toBe("work"); + } finally { spy.mockRestore(); } + }); + + test.each([429, 503])("file references prevent a caller-main alternate on %i", async status => { + const req = request(`file-${status}`, true); + const key = codexPoolAffinityKey(req.headers)!; + rememberConversationStateIssuer(key, "work"); + const resolve = authContext.resolveCodexAuthContext; + let alternateResolutions = 0; + const spy = spyOn(authContext, "resolveCodexAuthContext").mockImplementation((headers, cfg, mode, options) => { + if (options?.excludeAccountId) { alternateResolutions++; return Promise.resolve({ kind: "main", accountId: null }); } + const poolHeaders = new Headers(headers); poolHeaders.delete("authorization"); poolHeaders.delete("chatgpt-account-id"); + return resolve(poolHeaders, cfg, mode, { ...options, requestScopedMainCredential: false }); + }); + let sends = 0; + globalThis.fetch = (async () => { + sends++; + return Response.json({ error: { message: "unavailable" } }, { status, headers: { "retry-after": "600" } }); + }) as typeof fetch; + try { + const response = await handleResponsesCompact(req, config(), { model: "", provider: "" }); + expect(response.status).toBe(status); + expect(sends).toBe(1); + expect(alternateResolutions).toBe(0); + expect(peekConversationStateIssuer(key)).toBe("work"); + } finally { spy.mockRestore(); } + }); +}); diff --git a/tests/responses/native-compaction-gateway.test.ts b/tests/responses/native-compaction-gateway.test.ts index e7e3509913a..aa3744069f1 100644 --- a/tests/responses/native-compaction-gateway.test.ts +++ b/tests/responses/native-compaction-gateway.test.ts @@ -117,6 +117,19 @@ describe("native gateway transport", () => { expect((await calls[0]!.json()).model).toBe("some-model"); }); + test("configured gateway turn state survives when no account changed", async () => { + let sent: Request | undefined; + globalThis.fetch = (async (url, init) => { + sent = new Request(url, init); + return Response.json({ object: "response.compaction", output: [compactItem] }); + }) as typeof fetch; + const provider = { ...gateway, supportsNativeCompactEndpoint: true, headers: { "x-codex-turn-state": "configured" } }; + const config = { ...getDefaultConfig(), defaultProvider: "gw", providers: { gw: provider } }; + const response = await handleResponsesCompact(compactionRequest(baseCompactionBody()), config, { model: "", provider: "" }); + expect(response.status).toBe(200); + expect(sent?.headers.get("x-codex-turn-state")).toBe("configured"); + }); + test.each([ { replay: undefined, blob: nativeBlob }, { replay: true, blob: encodeCompactionSummary("Portable retained task fixture.") }, From fd8152646fce8d9ce6872c9b859d236bef4630a9 Mon Sep 17 00:00:00 2001 From: JUN Date: Mon, 2 Nov 2026 21:02:49 +0900 Subject: [PATCH 07/43] Serve an Ollama-compatible inbound API (#8099) * Support outer request log finalization * Add Ollama protocol codec * Suppress protocol trace for internal chat requests * Extract admitted HTTP turn refusal ownership * Add Ollama route eligibility preflight * Coordinate native ingress final request logs * Register native ingress tests in the layout map * Serve Ollama-compatible inbound routes on the data-plane listener * Document the Ollama-compatible inbound surface * Keep returned tool call ids when an Ollama client replays them * Add an Ollama-compatible clients guide * Commit a cancelled NDJSON stream row during terminal settlement * Recheck client cancellation after settlement and reject data after the Chat terminator * Register the Ollama inbound tests in the layout maps * Note that Ollama success follows Chat settlement * Keep non-Ollama routes synchronous through the dispatcher and read the moved refusal wrapper * Keep upstream error text out of Ollama responses and rows, and carry workflow identity * Generate Ollama response headers instead of copying them * Map Ollama refusal codes to constants, answer fenced Ollama paths natively, and look up one show route * Clarify the Ollama missing-finish rule for streamed JSON fallback --- docs-site/astro.config.mjs | 1 + .../content/docs/fr/guides/ollama-clients.md | 66 ++++ .../src/content/docs/guides/ollama-clients.md | 68 ++++ .../content/docs/ja/guides/ollama-clients.md | 64 ++++ .../content/docs/ko/guides/ollama-clients.md | 64 ++++ .../content/docs/ru/guides/ollama-clients.md | 65 ++++ .../content/docs/tr/guides/ollama-clients.md | 65 ++++ .../docs/zh-cn/guides/ollama-clients.md | 62 ++++ .../docs/zh-tw/guides/ollama-clients.md | 62 ++++ .../test-layout/layout-server-inbound.json | 10 +- src/protocols/codecs/ollama.ts | 197 ++++++++++ src/protocols/trace.ts | 18 + src/server/admitted-http-turn.ts | 56 +++ src/server/chat-completions.ts | 4 +- src/server/chat-native.ts | 3 +- src/server/inbound-body-admission.ts | 15 +- src/server/index.ts | 42 +-- src/server/index/ollama-routes.ts | 89 +++++ src/server/index/serve-options.ts | 19 +- src/server/native-final-log.ts | 97 +++++ src/server/ollama-inbound.ts | 349 ++++++++++++++++++ src/server/ollama-native-paths.ts | 21 ++ src/server/ollama-route-policy.ts | 73 ++++ src/server/request-log-failure-attribution.ts | 22 ++ src/server/request-log.ts | 45 ++- structure/INDEX.md | 8 + structure/data-planes/inbound-compat.md | 2 +- structure/data-planes/ollama-inbound.md | 89 +++++ structure/data-planes/protocol-paths.md | 2 +- structure/manifest.json | 15 + .../package-tree-integrity.test.ts | 10 + tests/clients/link-routes.test.ts | 3 + tests/fixtures/test-layout-expected.json | 3 + tests/lib/workflow-budget.test.ts | 9 +- .../responses/responses-ollama-codec.test.ts | 109 ++++++ tests/server/admitted-http-turn.test.ts | 152 ++++++++ tests/server/inbound-body-admission.test.ts | 9 +- .../loopback-listener-integration.test.ts | 8 + .../server/protocol-trace-suppression.test.ts | 108 ++++++ tests/server/server-native-final-log.test.ts | 94 +++++ .../server-ollama-inbound-errors.test.ts | 172 +++++++++ .../server-ollama-inbound-lifecycle.test.ts | 336 +++++++++++++++++ tests/server/server-ollama-inbound.test.ts | 271 ++++++++++++++ .../server/server-ollama-route-policy.test.ts | 99 +++++ 44 files changed, 3019 insertions(+), 57 deletions(-) create mode 100644 docs-site/src/content/docs/fr/guides/ollama-clients.md create mode 100644 docs-site/src/content/docs/guides/ollama-clients.md create mode 100644 docs-site/src/content/docs/ja/guides/ollama-clients.md create mode 100644 docs-site/src/content/docs/ko/guides/ollama-clients.md create mode 100644 docs-site/src/content/docs/ru/guides/ollama-clients.md create mode 100644 docs-site/src/content/docs/tr/guides/ollama-clients.md create mode 100644 docs-site/src/content/docs/zh-cn/guides/ollama-clients.md create mode 100644 docs-site/src/content/docs/zh-tw/guides/ollama-clients.md create mode 100644 src/protocols/codecs/ollama.ts create mode 100644 src/server/admitted-http-turn.ts create mode 100644 src/server/index/ollama-routes.ts create mode 100644 src/server/native-final-log.ts create mode 100644 src/server/ollama-inbound.ts create mode 100644 src/server/ollama-native-paths.ts create mode 100644 src/server/ollama-route-policy.ts create mode 100644 structure/data-planes/ollama-inbound.md create mode 100644 tests/responses/responses-ollama-codec.test.ts create mode 100644 tests/server/admitted-http-turn.test.ts create mode 100644 tests/server/protocol-trace-suppression.test.ts create mode 100644 tests/server/server-native-final-log.test.ts create mode 100644 tests/server/server-ollama-inbound-errors.test.ts create mode 100644 tests/server/server-ollama-inbound-lifecycle.test.ts create mode 100644 tests/server/server-ollama-inbound.test.ts create mode 100644 tests/server/server-ollama-route-policy.test.ts diff --git a/docs-site/astro.config.mjs b/docs-site/astro.config.mjs index e81e8b1fb7e..7c9c1558a3e 100644 --- a/docs-site/astro.config.mjs +++ b/docs-site/astro.config.mjs @@ -92,6 +92,7 @@ export default defineConfig({ { label: "Remote Workspace", translations: { fr: "Espace de travail distant", ko: "원격 워크스페이스", "zh-CN": "远程工作区", "zh-TW": "遠端工作區", ru: "Удалённая рабочая область", ja: "リモートワークスペース", tr: "Uzak Çalışma Alanı" }, slug: "guides/remote-workspace" }, { label: "Providers", translations: { fr: "Fournisseurs", ko: "프로바이더", "zh-CN": "提供商", "zh-TW": "供應商", ru: "Провайдеры", ja: "プロバイダー", tr: "Sağlayıcılar" }, slug: "guides/providers" }, { label: "Factory Droid Bridge", translations: { fr: "Pont Factory Droid", ko: "Factory Droid 브리지", "zh-CN": "Factory Droid 桥接", "zh-TW": "Factory Droid 橋接", ru: "Мост Factory Droid", ja: "Factory Droid ブリッジ", tr: "Factory Droid köprüsü" }, slug: "guides/factory-droid" }, + { label: "Ollama-Compatible Clients", translations: { fr: "Clients compatibles Ollama", ko: "Ollama 호환 클라이언트", "zh-CN": "Ollama 兼容客户端", "zh-TW": "Ollama 相容用戶端", ru: "Клиенты, совместимые с Ollama", ja: "Ollama 互換クライアント", tr: "Ollama uyumlu istemciler" }, slug: "guides/ollama-clients" }, { label: "Cursor Private Inference", translations: { ko: "Cursor Private Inference", fr: "Cursor Private Inference", "zh-CN": "Cursor Private Inference", "zh-TW": "Cursor Private Inference", ru: "Cursor Private Inference", ja: "Cursor Private Inference", tr: "Cursor Private Inference" }, slug: "guides/cursor-private-inference" }, { label: "Model Routing", translations: { fr: "Routage des modèles", ko: "모델 라우팅", "zh-CN": "模型路由", "zh-TW": "模型路由", ru: "Маршрутизация моделей", ja: "モデルルーティング", tr: "Model Yönlendirme" }, slug: "guides/model-routing" }, { label: "Codex Integration", translations: { fr: "Intégration de Codex", ko: "Codex 통합", "zh-CN": "Codex 集成", "zh-TW": "Codex 整合", ru: "Интеграция с Codex", ja: "Codex 連携", tr: "Codex Entegrasyonu" }, slug: "guides/codex-integration" }, diff --git a/docs-site/src/content/docs/fr/guides/ollama-clients.md b/docs-site/src/content/docs/fr/guides/ollama-clients.md new file mode 100644 index 00000000000..a3e78b7a28f --- /dev/null +++ b/docs-site/src/content/docs/fr/guides/ollama-clients.md @@ -0,0 +1,66 @@ +--- +title: Clients compatibles Ollama +description: Dirigez les outils qui parlent l'API Ollama vers opencodex et utilisez les modèles de vos fournisseurs configurés. +--- + +opencodex répond à un sous-ensemble de l'API HTTP d'Ollama : un outil qui ne sait parler qu'à Ollama peut +ainsi utiliser les modèles déjà configurés dans opencodex. Les requêtes sont traduites vers le chemin Chat +Completions et envoyées au fournisseur choisi. opencodex ne télécharge, ne stocke et n'exécute aucun modèle sur +votre machine. + +## Connecter un client + +Utilisez l'adresse du proxy comme hôte Ollama. Pour une installation locale par défaut : + +```bash +export OLLAMA_HOST=http://127.0.0.1:10100 +curl "$OLLAMA_HOST/api/tags" +``` + +Lorsque le proxy exige une clé d'API (par exemple avec une liaison `0.0.0.0`), envoyez-la comme pour +`/v1/chat/completions`, par exemple `Authorization: Bearer `. Une clé limitée à certains modèles +ne voit et n'utilise que les modèles autorisés. Ces points de terminaison ne sont servis que par l'écouteur +principal ; l'écouteur loopback sans authentification, Remote Link et l'entrée de gestion du hub ne les exposent pas. + +## Points de terminaison + +| Point de terminaison | Comportement | +| --- | --- | +| `GET /api/version` | La version d'opencodex. | +| `GET /api/tags` | Les modèles des fournisseurs configurés, sous la forme `provider/model`. | +| `POST /api/show` | `{ "model": "provider/model" }` ne renvoie que des faits connus ; ni taille de fichier, ni empreinte, ni modèle de prompt, ni licence. | +| `POST /api/chat` | Conversation avec des messages `system`, `user`, `assistant` et `tool`. | +| `POST /api/generate` | Une seule invite, avec un `system` facultatif. | + +Tous les autres chemins `/api/*` restent dans l'API de gestion d'opencodex. + +## Champs de requête pris en charge + +- `model` : un nom renvoyé par `/api/tags`. +- `stream` : `true` par défaut (JSON délimité par des sauts de ligne). Indiquez `false` pour une seule réponse JSON. +- `images` : PNG, JPEG, GIF ou WebP en base64 sur les messages utilisateur (chat) ou sur la requête (generate). +- `tools` (chat uniquement) : outils de type fonction. Renvoyez le message assistant tel quel, y compris + l'`id` de chaque appel ; un résultat `tool` est associé par `tool_call_id` ou, à défaut, par `tool_name`. +- `options` : `temperature`, `top_p`, `num_predict` et `stop`. +- `format` : uniquement `"json"`. + +Tout le reste est refusé avec un HTTP 400 au lieu d'être ignoré : `think`, `keep_alive`, `suffix`, `raw`, +`template`, `context`, les autres `options`, un `format` en schéma JSON et les URL d'images. Les points de +terminaison Ollama de gestion des modèles et d'embeddings ne sont pas fournis. + +Les combos, les politiques de routage, les alias `--fast` ou d'effort, et les fournisseurs qui transmettent les +identifiants de l'appelant ne peuvent pas être sélectionnés ici. Ces requêtes échouent avant tout envoi en amont. + +## Réponses + +Une réponse terminée porte `done: true` avec un `done_reason` valant `stop`, `tool_calls` ou `length`. +`prompt_eval_count` et `eval_count` apparaissent lorsque le fournisseur a signalé l'usage ; les champs de durée +ne sont pas renseignés. Un flux envoie exactement une ligne `done: true`, une fois la réponse amont entièrement terminée. + +Les erreurs utilisent la forme Ollama `{ "error": "message" }` et conservent le statut HTTP, y compris +`Retry-After` pour les limites de débit et les refus pour surcharge. Une réponse interrompue par un filtre de contenu +ou pour une raison inconnue est renvoyée comme erreur, jamais comme un arrêt normal. Si un flux échoue après avoir +commencé, sa dernière ligne est un objet `error` et aucune ligne `done: true` ne suit. + +Les requêtes apparaissent dans le journal des requêtes du tableau de bord comme le reste du trafic, et l'en-tête +de réponse `x-opencodex-request-id` désigne la ligne correspondante. diff --git a/docs-site/src/content/docs/guides/ollama-clients.md b/docs-site/src/content/docs/guides/ollama-clients.md new file mode 100644 index 00000000000..9875a96a051 --- /dev/null +++ b/docs-site/src/content/docs/guides/ollama-clients.md @@ -0,0 +1,68 @@ +--- +title: Ollama-compatible clients +description: Point tools that speak the Ollama API at opencodex and use your configured provider models. +--- + +opencodex answers a subset of the Ollama HTTP API, so a tool that only knows how to talk to Ollama +can use the models you already configured in opencodex. Requests are translated onto the Chat +Completions path and sent to the selected provider. opencodex does not download, store or run +models on your machine. + +## Connect a client + +Use the proxy address as the Ollama host. For a default local install: + +```bash +export OLLAMA_HOST=http://127.0.0.1:10100 +curl "$OLLAMA_HOST/api/tags" +``` + +When the proxy requires an API key (for example on a `0.0.0.0` bind), send it the same way as for +`/v1/chat/completions`, for example `Authorization: Bearer `. A key with a model +scope only sees and uses the models it is allowed to. The endpoints are served on the main listener +only; the unauthenticated loopback listener, Remote Link and the hub management ingress do not +expose them. + +## Endpoints + +| Endpoint | Behavior | +| --- | --- | +| `GET /api/version` | The opencodex version. | +| `GET /api/tags` | Configured provider models as `provider/model` names. | +| `POST /api/show` | `{ "model": "provider/model" }` returns only known facts; no file size, digest, template or license. | +| `POST /api/chat` | Chat with `system`, `user`, `assistant` and `tool` messages. | +| `POST /api/generate` | Single prompt with optional `system`. | + +Every other `/api/*` path stays part of the opencodex management API. + +## Supported request fields + +- `model`: a name from `/api/tags`. +- `stream`: defaults to `true` (newline-delimited JSON). Set `false` for one JSON response. +- `images`: base64 PNG, JPEG, GIF or WebP on user messages (chat) or the request (generate). +- `tools` (chat only): function tools. Send the assistant message back unchanged, including each + call's `id`; a `tool` result is matched by `tool_call_id` or, failing that, by `tool_name`. +- `options`: `temperature`, `top_p`, `num_predict` and `stop`. +- `format`: `"json"` only. + +Anything else is rejected with HTTP 400 instead of being ignored. That includes `think`, +`keep_alive`, `suffix`, `raw`, `template`, `context`, other `options`, JSON-schema `format` and image +URLs. Ollama's model-management and embedding endpoints are not provided. + +Combos, routing policies, `--fast` or effort aliases, and providers that forward the caller's own +credentials cannot be selected here. Requests for them fail before anything is sent upstream. + +## Responses + +A finished reply carries `done: true` with `done_reason` set to `stop`, `tool_calls` or `length`. +`prompt_eval_count` and `eval_count` appear when the provider reported usage; duration fields are +not reported. A stream sends exactly one `done: true` line, after the upstream reply has fully +completed. + +Errors use the Ollama shape `{ "error": "message" }` and keep the HTTP status, including +`Retry-After` on rate limits and busy refusals. A reply stopped by a content filter or for an unknown +reason is returned as an error, never as a normal stop. If a stream fails after it started, its last +line is an `error` object and no `done: true` line follows. + +Requests appear in the dashboard request log like other traffic, and the response header +`x-opencodex-request-id` names the matching row. diff --git a/docs-site/src/content/docs/ja/guides/ollama-clients.md b/docs-site/src/content/docs/ja/guides/ollama-clients.md new file mode 100644 index 00000000000..da7f99a19a8 --- /dev/null +++ b/docs-site/src/content/docs/ja/guides/ollama-clients.md @@ -0,0 +1,64 @@ +--- +title: Ollama 互換クライアント +description: Ollama API を話すツールを opencodex に向け、設定済みのプロバイダーモデルを使います。 +--- + +opencodex は Ollama HTTP API の一部に応答します。Ollama としか通信できないツールでも、opencodex に +設定済みのモデルを使えます。リクエストは Chat Completions 経路に変換され、選択したプロバイダーに送られます。 +opencodex はお使いのマシン上でモデルをダウンロード、保存、実行しません。 + +## クライアントの接続 + +プロキシのアドレスを Ollama ホストとして指定します。既定のローカルインストールでは次のとおりです。 + +```bash +export OLLAMA_HOST=http://127.0.0.1:10100 +curl "$OLLAMA_HOST/api/tags" +``` + +プロキシが API キーを要求する場合(たとえば `0.0.0.0` バインド)は、`/v1/chat/completions` と同じ方法で +送ります。例: `Authorization: Bearer `。モデル範囲付きのキーでは、許可されたモデルだけが表示・使用 +されます。これらのエンドポイントはメインリスナーでのみ提供され、認証なしのループバックリスナー、Remote Link、 +ハブ管理イングレスでは公開されません。 + +## エンドポイント + +| エンドポイント | 動作 | +| --- | --- | +| `GET /api/version` | opencodex のバージョン。 | +| `GET /api/tags` | 設定済みのプロバイダーモデルを `provider/model` 名で返します。 | +| `POST /api/show` | `{ "model": "provider/model" }` は既知の情報のみを返します。ファイルサイズ、ダイジェスト、テンプレート、ライセンスは含みません。 | +| `POST /api/chat` | `system`、`user`、`assistant`、`tool` メッセージによるチャット。 | +| `POST /api/generate` | 任意の `system` を伴う単一プロンプト。 | + +それ以外の `/api/*` パスはすべて opencodex 管理 API のままです。 + +## 対応するリクエストフィールド + +- `model`: `/api/tags` に含まれる名前。 +- `stream`: 既定値は `true`(改行区切り JSON)。JSON 応答を 1 つだけ受け取るには `false` にします。 +- `images`: ユーザーメッセージ(chat)またはリクエスト(generate)に付ける base64 の PNG、JPEG、GIF、WebP。 +- `tools`(chat のみ): 関数ツール。assistant メッセージは各呼び出しの `id` を含めてそのまま送り返します。 + `tool` の結果は `tool_call_id`、なければ `tool_name` で対応付けられます。 +- `options`: `temperature`、`top_p`、`num_predict`、`stop`。 +- `format`: `"json"` のみ。 + +それ以外は無視されず、HTTP 400 で拒否されます。`think`、`keep_alive`、`suffix`、`raw`、`template`、 +`context`、その他の `options`、JSON スキーマ形式の `format`、画像 URL が該当します。Ollama のモデル管理および +埋め込みエンドポイントは提供されません。 + +コンボ、ルーティングポリシー、`--fast` や effort のエイリアス、呼び出し元自身の認証情報を転送するプロバイダーは +ここでは選択できません。これらのリクエストは、上流に何も送信される前に失敗します。 + +## レスポンス + +完了した応答には `done: true` と、`stop`、`tool_calls`、`length` のいずれかの `done_reason` が付きます。 +`prompt_eval_count` と `eval_count` はプロバイダーが使用量を報告した場合に現れ、所要時間のフィールドは報告されません。 +ストリームは、上流の応答が完全に終わった後に `done: true` の行をちょうど 1 回だけ送ります。 + +エラーは Ollama 形式の `{ "error": "message" }` を使い、HTTP ステータスを保ちます。レート制限と混雑による拒否では +`Retry-After` も含まれます。コンテンツフィルターや不明な理由で止まった応答は、通常の停止ではなくエラーとして返されます。 +ストリームが開始後に失敗した場合、最後の行は `error` オブジェクトになり、`done: true` の行は続きません。 + +リクエストは他のトラフィックと同様にダッシュボードのリクエストログに表示され、レスポンスヘッダー +`x-opencodex-request-id` が対応する行を示します。 diff --git a/docs-site/src/content/docs/ko/guides/ollama-clients.md b/docs-site/src/content/docs/ko/guides/ollama-clients.md new file mode 100644 index 00000000000..3ffd8c49749 --- /dev/null +++ b/docs-site/src/content/docs/ko/guides/ollama-clients.md @@ -0,0 +1,64 @@ +--- +title: Ollama 호환 클라이언트 +description: Ollama API를 사용하는 도구를 opencodex에 연결해 설정된 프로바이더 모델을 사용합니다. +--- + +opencodex는 Ollama HTTP API의 일부를 제공합니다. 따라서 Ollama와만 통신할 수 있는 도구도 opencodex에 +이미 설정한 모델을 사용할 수 있습니다. 요청은 Chat Completions 경로로 변환되어 선택한 프로바이더로 +전송됩니다. opencodex는 사용자의 컴퓨터에서 모델을 내려받거나 저장하거나 실행하지 않습니다. + +## 클라이언트 연결 + +프록시 주소를 Ollama 호스트로 사용합니다. 기본 로컬 설치에서는 다음과 같습니다. + +```bash +export OLLAMA_HOST=http://127.0.0.1:10100 +curl "$OLLAMA_HOST/api/tags" +``` + +프록시가 API 키를 요구하는 경우(예: `0.0.0.0` 바인드) `/v1/chat/completions`와 같은 방식으로 키를 +보냅니다. 예: `Authorization: Bearer `. 모델 범위가 지정된 키는 허용된 모델만 보고 사용할 수 +있습니다. 이 엔드포인트는 기본 리스너에서만 제공되며, 인증 없는 루프백 리스너, Remote Link, 허브 관리 +인그레스에서는 노출되지 않습니다. + +## 엔드포인트 + +| 엔드포인트 | 동작 | +| --- | --- | +| `GET /api/version` | opencodex 버전. | +| `GET /api/tags` | 설정된 프로바이더 모델을 `provider/model` 이름으로 나열합니다. | +| `POST /api/show` | `{ "model": "provider/model" }`은 알려진 정보만 반환합니다. 파일 크기, 다이제스트, 템플릿, 라이선스는 없습니다. | +| `POST /api/chat` | `system`, `user`, `assistant`, `tool` 메시지로 대화합니다. | +| `POST /api/generate` | 선택적 `system`이 있는 단일 프롬프트. | + +그 밖의 모든 `/api/*` 경로는 opencodex 관리 API로 남습니다. + +## 지원하는 요청 필드 + +- `model`: `/api/tags`에 있는 이름. +- `stream`: 기본값은 `true`(줄 단위 JSON)입니다. JSON 응답 하나를 받으려면 `false`로 설정합니다. +- `images`: 사용자 메시지(chat) 또는 요청(generate)에 넣는 base64 PNG, JPEG, GIF, WebP. +- `tools`(chat 전용): 함수 도구. assistant 메시지는 각 호출의 `id`를 포함해 그대로 다시 보냅니다. + `tool` 결과는 `tool_call_id`로, 없으면 `tool_name`으로 연결됩니다. +- `options`: `temperature`, `top_p`, `num_predict`, `stop`. +- `format`: `"json"`만 지원합니다. + +그 밖의 항목은 무시되지 않고 HTTP 400으로 거부됩니다. `think`, `keep_alive`, `suffix`, `raw`, +`template`, `context`, 기타 `options`, JSON 스키마 `format`, 이미지 URL이 여기에 해당합니다. Ollama의 모델 +관리 및 임베딩 엔드포인트는 제공되지 않습니다. + +콤보, 라우팅 정책, `--fast` 또는 effort 별칭, 호출자 자신의 자격 증명을 전달하는 프로바이더는 여기서 +선택할 수 없습니다. 이러한 요청은 업스트림으로 아무것도 보내기 전에 실패합니다. + +## 응답 + +완료된 응답에는 `done: true`와 `stop`, `tool_calls`, `length` 중 하나인 `done_reason`이 있습니다. +`prompt_eval_count`와 `eval_count`는 프로바이더가 사용량을 보고한 경우에만 나타나며, 소요 시간 필드는 +보고되지 않습니다. 스트림은 업스트림 응답이 완전히 끝난 뒤 `done: true` 줄을 정확히 한 번 보냅니다. + +오류는 Ollama 형식 `{ "error": "message" }`을 사용하며 HTTP 상태를 유지합니다. 속도 제한과 혼잡 거부에는 +`Retry-After`도 포함됩니다. 콘텐츠 필터나 알 수 없는 이유로 중단된 응답은 일반적인 중지가 아니라 오류로 +반환됩니다. 스트림이 시작된 뒤 실패하면 마지막 줄은 `error` 객체이며 `done: true` 줄은 뒤따르지 않습니다. + +요청은 다른 트래픽과 마찬가지로 대시보드 요청 로그에 표시되며, 응답 헤더 +`x-opencodex-request-id`가 해당 행을 가리킵니다. diff --git a/docs-site/src/content/docs/ru/guides/ollama-clients.md b/docs-site/src/content/docs/ru/guides/ollama-clients.md new file mode 100644 index 00000000000..0bef2a6a995 --- /dev/null +++ b/docs-site/src/content/docs/ru/guides/ollama-clients.md @@ -0,0 +1,65 @@ +--- +title: Клиенты, совместимые с Ollama +description: Направьте инструменты, работающие с API Ollama, на opencodex и используйте настроенные модели провайдеров. +--- + +opencodex отвечает на часть HTTP API Ollama, поэтому инструмент, умеющий работать только с Ollama, может +использовать модели, уже настроенные в opencodex. Запросы переводятся на путь Chat Completions и отправляются +выбранному провайдеру. opencodex не скачивает, не хранит и не запускает модели на вашем компьютере. + +## Подключение клиента + +Укажите адрес прокси как хост Ollama. Для локальной установки по умолчанию: + +```bash +export OLLAMA_HOST=http://127.0.0.1:10100 +curl "$OLLAMA_HOST/api/tags" +``` + +Если прокси требует ключ API (например, при привязке к `0.0.0.0`), передавайте его так же, как для +`/v1/chat/completions`, например `Authorization: Bearer `. Ключ с ограничением по моделям видит и +использует только разрешённые модели. Эти конечные точки доступны только на основном слушателе; слушатель loopback +без аутентификации, Remote Link и вход управления хабом их не предоставляют. + +## Конечные точки + +| Конечная точка | Поведение | +| --- | --- | +| `GET /api/version` | Версия opencodex. | +| `GET /api/tags` | Модели настроенных провайдеров в виде имён `provider/model`. | +| `POST /api/show` | `{ "model": "provider/model" }` возвращает только известные сведения; без размера файла, дайджеста, шаблона и лицензии. | +| `POST /api/chat` | Диалог с сообщениями `system`, `user`, `assistant` и `tool`. | +| `POST /api/generate` | Один запрос с необязательным `system`. | + +Все остальные пути `/api/*` остаются частью API управления opencodex. + +## Поддерживаемые поля запроса + +- `model`: имя из `/api/tags`. +- `stream`: по умолчанию `true` (JSON с разделением строками). Укажите `false`, чтобы получить один ответ JSON. +- `images`: PNG, JPEG, GIF или WebP в base64 в пользовательских сообщениях (chat) или в запросе (generate). +- `tools` (только chat): функциональные инструменты. Отправляйте сообщение assistant обратно без изменений, + включая `id` каждого вызова; результат `tool` сопоставляется по `tool_call_id`, а при его отсутствии — по `tool_name`. +- `options`: `temperature`, `top_p`, `num_predict` и `stop`. +- `format`: только `"json"`. + +Всё остальное отклоняется с HTTP 400, а не игнорируется: `think`, `keep_alive`, `suffix`, `raw`, +`template`, `context`, прочие `options`, `format` в виде JSON-схемы и URL изображений. Конечные точки Ollama для +управления моделями и эмбеддингов не предоставляются. + +Комбо, политики маршрутизации, псевдонимы `--fast` и effort, а также провайдеры, пересылающие собственные учётные +данные вызывающей стороны, здесь выбрать нельзя. Такие запросы завершаются ошибкой до отправки чего-либо наверх. + +## Ответы + +Завершённый ответ содержит `done: true` и `done_reason` со значением `stop`, `tool_calls` или `length`. +`prompt_eval_count` и `eval_count` появляются, когда провайдер сообщил об использовании; поля длительности не +передаются. Поток отправляет ровно одну строку `done: true` после полного завершения ответа вышестоящего сервиса. + +Ошибки имеют форму Ollama `{ "error": "message" }` и сохраняют HTTP-статус, включая `Retry-After` при +ограничении частоты и отказах из-за загрузки. Ответ, остановленный фильтром содержимого или по неизвестной причине, +возвращается как ошибка, а не как обычная остановка. Если поток сбоит после начала, его последняя строка — объект +`error`, и строка `done: true` за ней не следует. + +Запросы видны в журнале запросов панели управления, как и остальной трафик, а заголовок ответа +`x-opencodex-request-id` указывает на соответствующую строку. diff --git a/docs-site/src/content/docs/tr/guides/ollama-clients.md b/docs-site/src/content/docs/tr/guides/ollama-clients.md new file mode 100644 index 00000000000..6921e7b67b7 --- /dev/null +++ b/docs-site/src/content/docs/tr/guides/ollama-clients.md @@ -0,0 +1,65 @@ +--- +title: Ollama uyumlu istemciler +description: Ollama API'sini konuşan araçları opencodex'e yönlendirin ve yapılandırdığınız sağlayıcı modellerini kullanın. +--- + +opencodex, Ollama HTTP API'sinin bir alt kümesine yanıt verir; böylece yalnızca Ollama ile konuşabilen bir araç, +opencodex'te zaten yapılandırdığınız modelleri kullanabilir. İstekler Chat Completions yoluna çevrilir ve seçilen +sağlayıcıya gönderilir. opencodex makinenizde model indirmez, saklamaz veya çalıştırmaz. + +## Bir istemciyi bağlama + +Proxy adresini Ollama ana makinesi olarak kullanın. Varsayılan yerel kurulum için: + +```bash +export OLLAMA_HOST=http://127.0.0.1:10100 +curl "$OLLAMA_HOST/api/tags" +``` + +Proxy bir API anahtarı istediğinde (örneğin `0.0.0.0` bağlamasında) anahtarı `/v1/chat/completions` için +olduğu gibi gönderin; örneğin `Authorization: Bearer `. Model kapsamı olan bir anahtar yalnızca izin +verilen modelleri görür ve kullanır. Bu uç noktalar yalnızca ana dinleyicide sunulur; kimlik doğrulamasız loopback +dinleyicisi, Remote Link ve hub yönetim girişi bunları sunmaz. + +## Uç noktalar + +| Uç nokta | Davranış | +| --- | --- | +| `GET /api/version` | opencodex sürümü. | +| `GET /api/tags` | Yapılandırılmış sağlayıcı modelleri, `provider/model` adlarıyla. | +| `POST /api/show` | `{ "model": "provider/model" }` yalnızca bilinen bilgileri döndürür; dosya boyutu, özet, şablon veya lisans yoktur. | +| `POST /api/chat` | `system`, `user`, `assistant` ve `tool` mesajlarıyla sohbet. | +| `POST /api/generate` | İsteğe bağlı `system` ile tek bir istem. | + +Diğer tüm `/api/*` yolları opencodex yönetim API'sinin parçası olarak kalır. + +## Desteklenen istek alanları + +- `model`: `/api/tags` içindeki bir ad. +- `stream`: varsayılan `true` (satırla ayrılmış JSON). Tek bir JSON yanıtı için `false` kullanın. +- `images`: kullanıcı mesajlarında (chat) veya istekte (generate) base64 PNG, JPEG, GIF ya da WebP. +- `tools` (yalnızca chat): fonksiyon araçları. Asistan mesajını her çağrının `id` değeri dahil değiştirmeden + geri gönderin; bir `tool` sonucu `tool_call_id` ile, yoksa `tool_name` ile eşleştirilir. +- `options`: `temperature`, `top_p`, `num_predict` ve `stop`. +- `format`: yalnızca `"json"`. + +Bunların dışındaki her şey yok sayılmak yerine HTTP 400 ile reddedilir: `think`, `keep_alive`, `suffix`, +`raw`, `template`, `context`, diğer `options`, JSON şeması biçimindeki `format` ve görsel URL'leri. Ollama'nın +model yönetimi ve embedding uç noktaları sağlanmaz. + +Kombolar, yönlendirme ilkeleri, `--fast` veya effort takma adları ve çağıranın kendi kimlik bilgilerini ileten +sağlayıcılar burada seçilemez. Bu istekler yukarı akışa hiçbir şey gönderilmeden başarısız olur. + +## Yanıtlar + +Tamamlanan bir yanıt `done: true` ve `stop`, `tool_calls` ya da `length` değerinde bir `done_reason` +taşır. `prompt_eval_count` ve `eval_count`, sağlayıcı kullanım bildirdiğinde görünür; süre alanları bildirilmez. +Bir akış, yukarı akış yanıtı tamamen bittikten sonra tam olarak bir `done: true` satırı gönderir. + +Hatalar Ollama biçimindeki `{ "error": "message" }` yapısını kullanır ve HTTP durumunu korur; hız sınırları ve +yoğunluk retlerinde `Retry-After` de bulunur. İçerik filtresi veya bilinmeyen bir nedenle durdurulan yanıt normal bir +durma olarak değil, hata olarak döndürülür. Bir akış başladıktan sonra başarısız olursa son satırı bir `error` nesnesidir +ve ardından `done: true` satırı gelmez. + +İstekler diğer trafik gibi panodaki istek günlüğünde görünür ve `x-opencodex-request-id` yanıt başlığı +ilgili satırı belirtir. diff --git a/docs-site/src/content/docs/zh-cn/guides/ollama-clients.md b/docs-site/src/content/docs/zh-cn/guides/ollama-clients.md new file mode 100644 index 00000000000..2701bc4d13d --- /dev/null +++ b/docs-site/src/content/docs/zh-cn/guides/ollama-clients.md @@ -0,0 +1,62 @@ +--- +title: Ollama 兼容客户端 +description: 让使用 Ollama API 的工具连接 opencodex,并使用已配置的提供商模型。 +--- + +opencodex 支持 Ollama HTTP API 的一个子集,因此只能与 Ollama 通信的工具也可以使用你在 opencodex +中已配置的模型。请求会被转换到 Chat Completions 路径,并发送给所选提供商。opencodex 不会在你的机器上 +下载、存储或运行模型。 + +## 连接客户端 + +将代理地址用作 Ollama 主机。默认本地安装如下: + +```bash +export OLLAMA_HOST=http://127.0.0.1:10100 +curl "$OLLAMA_HOST/api/tags" +``` + +当代理要求 API 密钥时(例如绑定到 `0.0.0.0`),按与 `/v1/chat/completions` 相同的方式发送, +例如 `Authorization: Bearer `。带有模型范围的密钥只能看到并使用被允许的模型。这些端点只在主监听器上 +提供;无认证的回环监听器、Remote Link 和 hub 管理入口都不会暴露它们。 + +## 端点 + +| 端点 | 行为 | +| --- | --- | +| `GET /api/version` | opencodex 版本。 | +| `GET /api/tags` | 以 `provider/model` 名称列出已配置的提供商模型。 | +| `POST /api/show` | `{ "model": "provider/model" }` 只返回已知信息;不包含文件大小、摘要、模板或许可证。 | +| `POST /api/chat` | 使用 `system`、`user`、`assistant` 和 `tool` 消息进行对话。 | +| `POST /api/generate` | 单个提示词,可选 `system`。 | + +其他所有 `/api/*` 路径仍属于 opencodex 管理 API。 + +## 支持的请求字段 + +- `model`:`/api/tags` 中的名称。 +- `stream`:默认为 `true`(按行分隔的 JSON)。设为 `false` 可得到单个 JSON 响应。 +- `images`:用户消息(chat)或请求(generate)中的 base64 PNG、JPEG、GIF 或 WebP。 +- `tools`(仅 chat):函数工具。请原样回传 assistant 消息,包括每个调用的 `id`;`tool` 结果按 + `tool_call_id` 匹配,没有时按 `tool_name` 匹配。 +- `options`:`temperature`、`top_p`、`num_predict` 和 `stop`。 +- `format`:仅支持 `"json"`。 + +其他内容会以 HTTP 400 拒绝,而不是被忽略,包括 `think`、`keep_alive`、`suffix`、`raw`、 +`template`、`context`、其他 `options`、JSON Schema 形式的 `format` 以及图片 URL。不提供 Ollama 的模型管理和 +嵌入端点。 + +组合、路由策略、`--fast` 或 effort 别名,以及会转发调用方自身凭据的提供商,不能在这里选择。 +这类请求会在向上游发送任何内容之前失败。 + +## 响应 + +完成的回复带有 `done: true`,`done_reason` 为 `stop`、`tool_calls` 或 `length`。 +提供商报告用量时才会出现 `prompt_eval_count` 和 `eval_count`;不报告耗时字段。流式响应会在上游回复完全结束后 +恰好发送一行 `done: true`。 + +错误使用 Ollama 格式 `{ "error": "message" }` 并保留 HTTP 状态,速率限制和繁忙拒绝时也会带上 +`Retry-After`。因内容过滤或未知原因停止的回复会作为错误返回,而不会当作正常停止。如果流在开始后失败,最后一行是 +`error` 对象,之后不会有 `done: true` 行。 + +这些请求会像其他流量一样出现在仪表板的请求日志中,响应头 `x-opencodex-request-id` 指向对应的记录。 diff --git a/docs-site/src/content/docs/zh-tw/guides/ollama-clients.md b/docs-site/src/content/docs/zh-tw/guides/ollama-clients.md new file mode 100644 index 00000000000..fb4cf878e5b --- /dev/null +++ b/docs-site/src/content/docs/zh-tw/guides/ollama-clients.md @@ -0,0 +1,62 @@ +--- +title: Ollama 相容用戶端 +description: 讓使用 Ollama API 的工具連接 opencodex,並使用已設定的供應商模型。 +--- + +opencodex 支援 Ollama HTTP API 的一個子集,因此只能與 Ollama 溝通的工具也能使用你在 opencodex +中已設定的模型。請求會轉換到 Chat Completions 路徑,並送往所選供應商。opencodex 不會在你的電腦上 +下載、儲存或執行模型。 + +## 連接用戶端 + +將代理位址作為 Ollama 主機。預設本機安裝如下: + +```bash +export OLLAMA_HOST=http://127.0.0.1:10100 +curl "$OLLAMA_HOST/api/tags" +``` + +當代理要求 API 金鑰時(例如綁定到 `0.0.0.0`),請以與 `/v1/chat/completions` 相同的方式傳送, +例如 `Authorization: Bearer `。具有模型範圍的金鑰只能看到並使用允許的模型。這些端點只在主要監聽器上 +提供;無驗證的回送監聽器、Remote Link 與 hub 管理入口都不會公開它們。 + +## 端點 + +| 端點 | 行為 | +| --- | --- | +| `GET /api/version` | opencodex 版本。 | +| `GET /api/tags` | 以 `provider/model` 名稱列出已設定的供應商模型。 | +| `POST /api/show` | `{ "model": "provider/model" }` 只回傳已知資訊;不包含檔案大小、摘要、範本或授權。 | +| `POST /api/chat` | 使用 `system`、`user`、`assistant` 與 `tool` 訊息進行對話。 | +| `POST /api/generate` | 單一提示詞,可選 `system`。 | + +其他所有 `/api/*` 路徑仍屬於 opencodex 管理 API。 + +## 支援的請求欄位 + +- `model`:`/api/tags` 中的名稱。 +- `stream`:預設為 `true`(以換行分隔的 JSON)。設為 `false` 可取得單一 JSON 回應。 +- `images`:使用者訊息(chat)或請求(generate)中的 base64 PNG、JPEG、GIF 或 WebP。 +- `tools`(僅限 chat):函式工具。請原樣回傳 assistant 訊息,包括每個呼叫的 `id`;`tool` 結果依 + `tool_call_id` 對應,沒有時依 `tool_name` 對應。 +- `options`:`temperature`、`top_p`、`num_predict` 與 `stop`。 +- `format`:僅支援 `"json"`。 + +其他內容會以 HTTP 400 拒絕,而不是被忽略,包括 `think`、`keep_alive`、`suffix`、`raw`、 +`template`、`context`、其他 `options`、JSON Schema 形式的 `format` 以及圖片 URL。不提供 Ollama 的模型管理與 +嵌入端點。 + +組合、路由政策、`--fast` 或 effort 別名,以及會轉送呼叫者自身憑證的供應商,無法在這裡選擇。 +這類請求會在向上游傳送任何內容之前失敗。 + +## 回應 + +完成的回覆帶有 `done: true`,`done_reason` 為 `stop`、`tool_calls` 或 `length`。 +供應商回報用量時才會出現 `prompt_eval_count` 與 `eval_count`;不回報耗時欄位。串流會在上游回覆完全結束後 +恰好傳送一行 `done: true`。 + +錯誤使用 Ollama 格式 `{ "error": "message" }` 並保留 HTTP 狀態,速率限制與忙碌拒絕時也會附上 +`Retry-After`。因內容過濾或未知原因停止的回覆會以錯誤回傳,而不會當作正常停止。如果串流在開始後失敗,最後一行是 +`error` 物件,之後不會有 `done: true` 行。 + +這些請求會像其他流量一樣出現在儀表板的請求記錄中,回應標頭 `x-opencodex-request-id` 指向對應的記錄列。 diff --git a/scripts/test-layout/layout-server-inbound.json b/scripts/test-layout/layout-server-inbound.json index 41002edc674..090078c256f 100644 --- a/scripts/test-layout/layout-server-inbound.json +++ b/scripts/test-layout/layout-server-inbound.json @@ -3,5 +3,13 @@ "inbound-body-admission.test.ts": "server", "inbound-body-budget.test.ts": "server", "claude-bridge-pool-session.test.ts": "claude-integration", - "claude-bridge-pool-dispatch.test.ts": "claude-integration" + "claude-bridge-pool-dispatch.test.ts": "claude-integration", + "admitted-http-turn.test.ts": "server", + "server-native-final-log.test.ts": "server", + "server-ollama-route-policy.test.ts": "server", + "server-ollama-inbound.test.ts": "server", + "server-ollama-inbound-lifecycle.test.ts": "server", + "server-ollama-inbound-errors.test.ts": "server", + "protocol-trace-suppression.test.ts": "server", + "responses-ollama-codec.test.ts": "responses" } diff --git a/src/protocols/codecs/ollama.ts b/src/protocols/codecs/ollama.ts new file mode 100644 index 00000000000..85c1c7d151e --- /dev/null +++ b/src/protocols/codecs/ollama.ts @@ -0,0 +1,197 @@ +/** Pure Ollama native request and Chat response projections. */ +type Obj = Record; +export type OllamaKind = "chat" | "generate"; +export class OllamaCodecError extends Error { + readonly status = 400; + readonly code = "invalid_ollama_request"; + constructor(message: string) { super(message); this.name = "OllamaCodecError"; } +} +function fail(message: string): never { throw new OllamaCodecError(message); } +function object(value: unknown, label: string): Obj { + if (!value || typeof value !== "object" || Array.isArray(value)) fail(`Invalid ${label}`); + return value as Obj; +} +function keys(value: Obj, allowed: readonly string[], label: string): void { + if (Object.keys(value).some(k => !allowed.includes(k))) fail(`Unsupported ${label} field`); +} +function string(value: unknown, label: string, nonempty = false): string { + if (typeof value !== "string" || (nonempty && !value.trim())) fail(`Invalid ${label}`); + return value; +} +function image(value: unknown): Obj { + const data = string(value, "image", true); + if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data)) fail("Invalid image encoding"); + let bytes: Uint8Array; + // The pattern above already validated the whole string; decode only the signature window. + try { bytes = Uint8Array.from(atob(data.slice(0, 16)), c => c.charCodeAt(0)); } catch { return fail("Invalid image encoding"); } + const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + if ((data.endsWith("==") && (alphabet.indexOf(data[data.length - 3]!) & 15) !== 0) || + (data.endsWith("=") && !data.endsWith("==") && (alphabet.indexOf(data[data.length - 2]!) & 3) !== 0)) fail("Invalid image encoding"); + const starts = (...prefix: number[]) => prefix.every((b, i) => bytes[i] === b); + const mime = starts(137,80,78,71,13,10,26,10) ? "image/png" : starts(255,216,255) ? "image/jpeg" : starts(71,73,70,56,55,97) || starts(71,73,70,56,57,97) ? "image/gif" : starts(82,73,70,70) && bytes.length >= 12 && bytes[8] === 87 && bytes[9] === 69 && bytes[10] === 66 && bytes[11] === 80 ? "image/webp" : undefined; + if (!mime) fail("Unsupported image media"); + return { type: "image_url", image_url: { url: `data:${mime};base64,${data}` } }; +} +function content(text: unknown, images: unknown): unknown { + const value = string(text, "content"); + if (images === undefined) return value; + if (!Array.isArray(images)) fail("Invalid images"); + if (!images.length) return value; + return [{ type: "text", text: value }, ...images.map(image)]; +} +function requestTools(value: unknown): Obj[] { + if (!Array.isArray(value)) fail("Invalid tools"); + return value.map(item => { + const tool = object(item, "tool"); keys(tool, ["type", "function"], "tool"); + if (tool.type !== "function") fail("Unsupported tool type"); + const fn = object(tool.function, "tool function"); keys(fn, ["name", "description", "parameters"], "tool function"); + string(fn.name, "tool name", true); + if (fn.description !== undefined) string(fn.description, "tool description"); + object(fn.parameters, "tool parameters"); + return { type: "function", function: { ...fn } }; + }); +} +export function ollamaToChat(kind: OllamaKind, input: unknown): Obj { + const body = object(input, "request"); + keys(body, kind === "chat" ? ["model", "messages", "stream", "options", "format", "tools"] : ["model", "prompt", "system", "images", "stream", "options", "format"], "request"); + const model = string(body.model, "model", true); + if (body.stream !== undefined && typeof body.stream !== "boolean") fail("Invalid stream"); + const result: Obj = { model, stream: body.stream ?? true, messages: [] }; + const messages: Obj[] = []; + if (kind === "generate") { + if (body.system !== undefined) messages.push({ role: "system", content: string(body.system, "system") }); + messages.push({ role: "user", content: content(body.prompt, body.images) }); + } else { + if (!Array.isArray(body.messages)) fail("Invalid messages"); + const pending: { id: string; name: string; message: number; matched: boolean }[] = []; + body.messages.forEach((raw, mi) => { + const msg = object(raw, "message"); + const role = string(msg.role, "role"); + if (!["system", "user", "assistant", "tool"].includes(role)) fail("Unsupported role"); + keys(msg, role === "user" ? ["role", "content", "images"] : role === "assistant" ? ["role", "content", "tool_calls"] : role === "tool" ? ["role", "content", "tool_name", "tool_call_id"] : ["role", "content"], "message"); + const projected: Obj = { role, content: content(msg.content, role === "user" ? msg.images : undefined) }; + if (role === "assistant" && msg.tool_calls !== undefined) { + if (!Array.isArray(msg.tool_calls)) fail("Invalid tool calls"); + projected.tool_calls = msg.tool_calls.map((rawCall, ci) => { + // A replayed response call keeps the id this proxy returned for it; older clients send none. + const call = object(rawCall, "tool call"); keys(call, ["id", "function"], "tool call"); + const fn = object(call.function, "tool call function"); keys(fn, ["name", "arguments"], "tool call function"); + const name = string(fn.name, "tool name", true); const args = object(fn.arguments, "tool arguments"); + const id = call.id === undefined ? `call_ollama_${mi}_${ci}` : string(call.id, "tool call id", true); + if (pending.some(p => p.id === id)) fail("Duplicate tool call id"); + pending.push({ id, name, message: mi, matched: false }); + return { id, type: "function", function: { name, arguments: JSON.stringify(args) } }; + }); + } + if (role === "tool") { + const id = msg.tool_call_id === undefined ? undefined : string(msg.tool_call_id, "tool call id", true); + const name = msg.tool_name === undefined ? undefined : string(msg.tool_name, "tool name", true); + const candidates = pending.filter(p => !p.matched && (id ? p.id === id && (!name || p.name === name) : name && p.name === name)); + if (!id && name && candidates.length) { + const latestMessage = candidates[candidates.length - 1]!.message; + const latest = candidates.filter(p => p.message === latestMessage); + if (latest.length !== 1) fail("Ambiguous tool result"); + latest[0]!.matched = true; projected.tool_call_id = latest[0]!.id; + } else { + if (candidates.length !== 1) fail("Unmatched tool result"); + candidates[0]!.matched = true; projected.tool_call_id = candidates[0]!.id; + } + } + messages.push(projected); + }); + if (body.tools !== undefined) result.tools = requestTools(body.tools); + } + result.messages = messages; + if (body.options !== undefined) { + const opts = object(body.options, "options"); keys(opts, ["temperature", "top_p", "num_predict", "stop"], "option"); + for (const key of ["temperature", "top_p", "num_predict"] as const) if (opts[key] !== undefined) { + const v = opts[key]; if (typeof v !== "number" || !Number.isFinite(v) || (key === "num_predict" && (!Number.isSafeInteger(v) || v < 1))) fail("Invalid option"); + result[key === "num_predict" ? "max_tokens" : key] = v; + } + if (opts.stop !== undefined) { + if (!Array.isArray(opts.stop) || !opts.stop.every(v => typeof v === "string")) fail("Invalid stop option"); + result.stop = opts.stop; + } + } + if (body.format !== undefined) { if (body.format !== "json") fail("Unsupported format"); result.response_format = { type: "json_object" }; } + return result; +} + +function usage(value: unknown): Obj { + if (!value || typeof value !== "object" || Array.isArray(value)) return {}; + const u = value as Obj; const out: Obj = {}; + if (typeof u.prompt_tokens === "number" && Number.isSafeInteger(u.prompt_tokens) && u.prompt_tokens >= 0) out.prompt_eval_count = u.prompt_tokens; + if (typeof u.completion_tokens === "number" && Number.isSafeInteger(u.completion_tokens) && u.completion_tokens >= 0) out.eval_count = u.completion_tokens; + return out; +} +function finish(value: unknown): string | undefined { return value === "stop" || value === "tool_calls" || value === "length" ? value : undefined; } +function nativeError(): Obj { return { error: "Chat completion did not finish successfully" }; } +function nativeCalls(calls: unknown): Obj[] { + if (!Array.isArray(calls)) throw new Error("Invalid Chat tool calls"); + return calls.map((raw, i) => { + const call = object(raw, "response tool call"); const fn = object(call.function, "response tool function"); + const name = string(fn.name, "response tool name", true); + let args: unknown; try { args = typeof fn.arguments === "string" ? JSON.parse(fn.arguments) : fn.arguments; } catch { throw new Error("Invalid Chat tool arguments"); } + object(args, "response tool arguments"); + return { id: typeof call.id === "string" && call.id ? call.id : `call_ollama_response_${i}`, function: { name, arguments: args } }; + }); +} +function payload(kind: OllamaKind, text: string, calls?: Obj[]): Obj { + return kind === "chat" ? { message: { role: "assistant", content: text, ...(calls?.length ? { tool_calls: calls } : {}) } } : { response: text }; +} +export function ollamaBufferedResponse(kind: OllamaKind, model: string, input: unknown, createdAt: string): Obj { + try { + const body = object(input, "Chat response"); if (!Array.isArray(body.choices) || body.choices.length !== 1) return nativeError(); + const choice = object(body.choices[0], "Chat choice"); const reason = finish(choice.finish_reason); if (!reason) return nativeError(); + const msg = object(choice.message, "Chat message"); + if (msg.content != null && typeof msg.content !== "string") return nativeError(); + const calls = msg.tool_calls === undefined ? undefined : nativeCalls(msg.tool_calls); + if (kind === "generate" && calls?.length) return nativeError(); + return { model, created_at: createdAt, ...payload(kind, (msg.content as string | null | undefined) ?? "", calls), done: true, done_reason: reason, ...usage(body.usage) }; + } catch { return nativeError(); } +} +type StreamTool = { id?: string; name: string; arguments: string }; +export interface OllamaStreamState { kind: OllamaKind; model: string; createdAt: string; finishReason?: unknown; usage: Obj; tools: Map; toolsEmitted: boolean; } +export function createOllamaStreamState(kind: OllamaKind, model: string, createdAt: string): OllamaStreamState { + return { kind, model, createdAt, usage: {}, tools: new Map(), toolsEmitted: false }; +} +/** Consume one parsed Chat chunk. The caller owns settlement and may discard these records on failure. */ +export function consumeOllamaChatChunk(state: OllamaStreamState, input: unknown): Obj[] { + const body = object(input, "Chat chunk"); + if (body.error !== undefined) throw new Error("Chat stream error"); + if (body.usage != null) state.usage = usage(body.usage); + if (!Array.isArray(body.choices) || body.choices.length > 1) throw new Error("Invalid Chat chunk choices"); + if (!body.choices.length) return []; + const choice = object(body.choices[0], "Chat choice"); const delta = object(choice.delta, "Chat delta"); + if (state.finishReason !== undefined) throw new Error("Chat chunk after finish"); + const records: Obj[] = []; + if (delta.content != null) { + const text = string(delta.content, "Chat content"); + if (text) records.push({ model: state.model, created_at: state.createdAt, ...payload(state.kind, text), done: false }); + } + if (delta.tool_calls !== undefined) { + if (state.kind !== "chat" || !Array.isArray(delta.tool_calls) || state.toolsEmitted) throw new Error("Invalid Chat tool delta"); + for (const raw of delta.tool_calls) { + const call = object(raw, "tool delta"); if (!Number.isSafeInteger(call.index) || (call.index as number) < 0) throw new Error("Invalid tool index"); + const index = call.index as number; const current = state.tools.get(index) ?? { name: "", arguments: "" }; + if (call.id !== undefined) { const id = string(call.id, "tool id", true); if (current.id && current.id !== id) throw new Error("Conflicting tool id"); current.id = id; } + if (call.function !== undefined) { const fn = object(call.function, "tool function"); if (fn.name !== undefined) current.name += string(fn.name, "tool name"); if (fn.arguments !== undefined) current.arguments += string(fn.arguments, "tool arguments"); } + state.tools.set(index, current); + } + } + if (choice.finish_reason != null) { + if (state.finishReason !== undefined) throw new Error("Duplicate Chat finish"); + state.finishReason = choice.finish_reason; + if (choice.finish_reason === "tool_calls" && state.tools.size) { + const calls = [...state.tools.entries()].sort((a, b) => a[0] - b[0]).map(([index, tool]) => ({ id: tool.id ?? `call_ollama_response_${index}`, function: { name: tool.name, arguments: tool.arguments } })); + records.push({ model: state.model, created_at: state.createdAt, ...payload(state.kind, "", nativeCalls(calls)), done: false }); state.toolsEmitted = true; + } + } + return records; +} +/** Call only after the outer handler confirms successful upstream settlement. */ +export function ollamaStreamTerminal(state: OllamaStreamState): Obj { + const reason = finish(state.finishReason); + if (!reason || (state.tools.size > 0 && !state.toolsEmitted)) return nativeError(); + return { model: state.model, created_at: state.createdAt, ...payload(state.kind, ""), done: true, done_reason: reason, ...state.usage }; +} diff --git a/src/protocols/trace.ts b/src/protocols/trace.ts index b8c7836b048..d0c1994d23d 100644 --- a/src/protocols/trace.ts +++ b/src/protocols/trace.ts @@ -65,6 +65,18 @@ export interface ProtocolTraceAttempt { const requestMarks = new WeakMap(); const attemptMarks = new WeakMap(); const shadowInputs = new WeakMap(); +const suppressedContexts = new WeakSet(); + +/** Suppress diagnostics for an internal protocol bridge while preserving request behavior. */ +export function suppressProtocolTrace(logCtx: object): void { + suppressedContexts.add(logCtx); + requestMarks.delete(logCtx); + shadowInputs.delete(logCtx); +} + +export function protocolTraceSuppressed(logCtx: object): boolean { + return suppressedContexts.has(logCtx); +} function boundedReasons(codes: Iterable): ProtocolReasonCode[] { const out: ProtocolReasonCode[] = []; @@ -95,6 +107,7 @@ export function markProtocolEntry( logCtx: object, mark: { inbound: Protocol; lane: ProtocolLane; reasonCodes?: Iterable; features?: ProtocolFeatureSource }, ): void { + if (protocolTraceSuppressed(logCtx)) return; try { requestMarks.set(logCtx, { kind: "entry", @@ -110,6 +123,7 @@ export function markProtocolEntry( /** Features the request's entry or blocked mark recorded, for the shadow plan input. */ export function protocolMarkFeatures(logCtx: object): readonly ProtocolFeature[] | undefined { + if (protocolTraceSuppressed(logCtx)) return undefined; try { const mark = requestMarks.get(logCtx); return mark ? [...mark.features] : undefined; @@ -123,6 +137,7 @@ export function protocolMarkFeatures(logCtx: object): readonly ProtocolFeature[] * fixed vocabulary and the provider and model names the server already exposes, nothing else. */ export function markProtocolShadowPlanInput(logCtx: object, input: ProtocolPlanInput): void { + if (protocolTraceSuppressed(logCtx)) return; try { shadowInputs.set(logCtx, input); } catch { @@ -135,6 +150,7 @@ export function markProtocolBlocked( logCtx: object, mark: { inbound: Protocol; reasonCodes: Iterable; features?: ProtocolFeatureSource }, ): void { + if (protocolTraceSuppressed(logCtx)) return; try { requestMarks.set(logCtx, { kind: "blocked", @@ -152,6 +168,7 @@ export function markProtocolBlocked( * No-op without an entry mark, and a blocked mark is never reopened. */ export function addProtocolEntryReason(logCtx: object, code: ProtocolReasonCode): void { + if (protocolTraceSuppressed(logCtx)) return; try { const mark = requestMarks.get(logCtx); if (mark?.kind !== "entry") return; @@ -246,6 +263,7 @@ export function protocolTraceForRequest( logCtx: ProtocolTraceContext, attempts: readonly ProtocolTraceAttempt[] | undefined, ): ProtocolTraceV1 | undefined { + if (protocolTraceSuppressed(logCtx)) return undefined; const trace = observedTrace(logCtx, attempts); return trace ? withShadowPlan(logCtx, trace) : undefined; } diff --git a/src/server/admitted-http-turn.ts b/src/server/admitted-http-turn.ts new file mode 100644 index 00000000000..23c610b401d --- /dev/null +++ b/src/server/admitted-http-turn.ts @@ -0,0 +1,56 @@ +import { withCors, type RequestPolicyView } from "./auth-cors"; +import { runAdmittedBodyWork } from "./inbound-body-admission"; +import { tryAdmitTurn, type ActiveTurnLease } from "./lifecycle"; +import { addFinalRequestLog } from "./request-log"; +import { sessionLaneIdFromRequest } from "./request-log-conversation"; +import { admitHttpWorkflowTurn, workflowDecisionRefusalResponse, type WorkflowRefusalLog } from "./workflow-refusal"; + +export interface AdmittedHttpTurnOptions { + mapRefusal?: (response: Response) => Response; + onAdmissionError?: (error: unknown) => Response; +} + +export function createAdmittedHttpTurn( + configuredLimit: () => number | undefined, + serverBusyResponse: (req: Request, resource: string, policy: RequestPolicyView) => Response, +) { + return async function runAdmittedHttpTurn( + req: Request, + policy: RequestPolicyView, + work: (lease: ActiveTurnLease) => Promise, + refusalLog?: WorkflowRefusalLog, + options?: AdmittedHttpTurnOptions, + ): Promise { + const map = (response: Response) => options?.mapRefusal ? options.mapRefusal(response) : response; + const lease = tryAdmitTurn(sessionLaneIdFromRequest(req.headers), req.signal); + if (!lease) { + const response = serverBusyResponse(req, "active turns", policy); + return options?.mapRefusal ? withCors(map(response), req, policy) : response; + } + let workflow: ReturnType; + try { workflow = admitHttpWorkflowTurn(req.headers); } + catch (error) { lease.release(); throw error; } + if (workflow && !workflow.admitted) { + lease.release(); + return withCors(map(workflowDecisionRefusalResponse(workflow, undefined, refusalLog)), req, policy); + } + if (workflow?.admitted) lease.attach(workflow.lease); + try { + const response = await runAdmittedBodyWork(req, policy, configuredLimit(), () => work(lease), refusalLog, + options?.mapRefusal, options?.onAdmissionError ? error => { + if (!req.signal.aborted || error !== req.signal.reason) throw error; + lease.release(); + if (refusalLog) { + addFinalRequestLog(refusalLog.requestId, refusalLog.start, refusalLog.logCtx, 499, { closeReason: "client_cancel" }); + refusalLog.onLogged?.(); + } + return withCors(map(options.onAdmissionError!(error)), req, policy); + } : undefined); + if (!lease.isTransferred()) lease.release(); + return response; + } catch (error) { + lease.release(); + throw error; + } + }; +} diff --git a/src/server/chat-completions.ts b/src/server/chat-completions.ts index eb876f0983b..deabacb5aa1 100644 --- a/src/server/chat-completions.ts +++ b/src/server/chat-completions.ts @@ -95,7 +95,7 @@ import { credentialDomainFor } from "../protocols/opaque-state"; import { checkRepresentable, unrepresentableMessage } from "../protocols/guard"; import { requestPathForLane } from "../protocols/path"; import { resolveProtocolSettings } from "../protocols/settings"; -import { markProtocolBlocked, markProtocolEntry } from "../protocols/trace"; +import { markProtocolBlocked, markProtocolEntry, suppressProtocolTrace } from "../protocols/trace"; import { recordProtocolShadowPlan } from "../protocols/shadow-plan"; import { jsonCompletionSse } from "./chat-native-sse"; import { parseRequestEffortRowId } from "./effort-row"; @@ -125,8 +125,10 @@ export async function handleChatCompletions( logIds?: { requestId: string; start: number; turnAdmissionLease?: AdmissionLease; admission?: DataPlaneAdmission; advisorAdmissionPolicy?: CapturedAdmissionPolicy; + suppressProtocolTrace?: boolean; }, ): Promise { + if (logIds?.suppressProtocolTrace) suppressProtocolTrace(logCtx); // Set before routing so pre-dispatch refusals stay correlated. A Hermes-only id is marked as a // fallback, so a native id resolved later on the Responses bridge still replaces it. assignNativeLogConversationId(logCtx, nativeLogConversationIdFromHeaders(req.headers)); diff --git a/src/server/chat-native.ts b/src/server/chat-native.ts index ac3d861eb5e..bcd6e6fa335 100644 --- a/src/server/chat-native.ts +++ b/src/server/chat-native.ts @@ -86,6 +86,7 @@ import { attachRequestSpendTracker } from "./responses/request-spend"; import { workflowRefusalResponse } from "./workflow-refusal"; import type { ComboProtocolSource } from "./responses/core-combo-native"; import type { ProtocolEnvelope } from "../protocols/envelope"; +import { protocolTraceSuppressed } from "../protocols/trace"; import { nativeChatReplayScope, bindNativeChatReplayScope, nativeChatReasoningCapture } from "./chat-native-reasoning"; import { resolveMistralTransport } from "../providers/mistral-transport"; @@ -225,7 +226,7 @@ export interface NativeChatExecution extends HandleNativeChatOptions { */ export async function handleNativeChatCompletions(options: HandleNativeChatOptions): Promise { const { logCtx, logIds, route } = options; - logCtx.inboundProtocol = "chat"; + if (!protocolTraceSuppressed(logCtx)) logCtx.inboundProtocol = "chat"; const attemptHandle = beginInferenceAttempt(logCtx, { provider: route.providerName, model: route.modelId, diff --git a/src/server/inbound-body-admission.ts b/src/server/inbound-body-admission.ts index fded3630976..409e4dd2ee9 100644 --- a/src/server/inbound-body-admission.ts +++ b/src/server/inbound-body-admission.ts @@ -7,6 +7,7 @@ import { codexCompatibleUrl } from "../codex/context-compat"; import { addFinalRequestLog, markLocalRequestLogRefusal } from "./request-log"; import type { WorkflowRefusalLog } from "./workflow-refusal"; import { inboundBodyBudget, bindInboundBodyLease, type InboundBodyBudget } from "./inbound-body-budget"; +import { OLLAMA_JSON_BODY_ROUTES } from "./ollama-native-paths"; export { configureInboundBodyBudget, MAX_CONCURRENT_INBOUND_BODY_BYTES } from "./inbound-body-budget"; @@ -145,10 +146,12 @@ export async function withRaisedInboundBodyAdmission( configuredLimit: number | undefined, work: () => Promise, onRefusal: (response: Response) => Response = response => response, - options?: { budget?: InboundBodyBudget; maxWaitMs?: number }, + options?: { budget?: InboundBodyBudget; maxWaitMs?: number; onAdmissionError?: (error: unknown) => Response }, ): Promise { const maxBytes = resolveInboundBodyLimitBytes(configuredLimit); - if (req.method !== "POST" || !CONFIGURABLE_JSON_BODY_ROUTES.has(pathname) + // Native Ollama generation routes are served only on the authenticated listener, so they sit in + // their own set: the loopback oracle checks CONFIGURABLE_JSON_BODY_ROUTES against that allowlist. + if (req.method !== "POST" || !(CONFIGURABLE_JSON_BODY_ROUTES.has(pathname) || OLLAMA_JSON_BODY_ROUTES.has(pathname)) || maxBytes <= MAX_DECOMPRESSED_BODY_BYTES || req.signal.aborted) { return work(); } @@ -164,6 +167,7 @@ export async function withRaisedInboundBodyAdmission( lease = await (options?.budget ?? inboundBodyBudget).acquire(maxBytes, req.signal, options?.maxWaitMs); } catch (error) { cancelUnreadBody(req, error); + if (options?.onAdmissionError) return options.onAdmissionError(error); throw error; } if (!lease) { @@ -175,6 +179,7 @@ export async function withRaisedInboundBodyAdmission( if (req.signal.aborted) { lease.release(); cancelUnreadBody(req, req.signal.reason); + if (options?.onAdmissionError) return options.onAdmissionError(req.signal.reason); throw req.signal.reason; } const unbind = bindInboundBodyLease(req, lease); @@ -198,6 +203,8 @@ export function runAdmittedBodyWork( configuredLimit: number | undefined, work: () => Promise, refusalLog?: WorkflowRefusalLog, + mapRefusal?: (response: Response) => Response, + onAdmissionError?: (error: unknown) => Response, ): Promise { return withRaisedInboundBodyAdmission(req, codexCompatibleUrl(req.url).pathname, configuredLimit, work, refused => { if (refusalLog) { @@ -208,6 +215,6 @@ export function runAdmittedBodyWork( }); refusalLog.onLogged?.(); } - return withCors(refused, req, policy); - }); + return withCors(mapRefusal ? mapRefusal(refused) : refused, req, policy); + }, onAdmissionError ? { onAdmissionError } : undefined); } diff --git a/src/server/index.ts b/src/server/index.ts index e9e75346967..a4b4dde1613 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -2,7 +2,9 @@ import { remoteWorkspaceEnabled } from "../remote-control/workspace-activation"; import { scheduleDesktopCompatibilityStartup } from "./index/desktop-compatibility-startup"; import { AuxiliaryListenerBindError } from "./ports"; import { normalizeBindHostname } from "./bind-host"; -import { configureInboundBodyBudget, runAdmittedBodyWork } from "./inbound-body-admission"; +import { configureInboundBodyBudget } from "./inbound-body-admission"; +import { createAdmittedHttpTurn } from "./admitted-http-turn"; +import { isOllamaNativePath } from "./ollama-native-paths"; import { buildWarmupCompletionFrames, buildWsErrorFrame, @@ -93,9 +95,7 @@ import { runListenerShutdown, setServerRef, trackStreamLifetime, - tryAdmitTurn, unregisterTurn, - type ActiveTurnLease, } from "./lifecycle"; export { drainAndShutdown, @@ -116,9 +116,7 @@ import { type RequestLogContext, type RequestLogEntry, } from "./request-log"; -import { sessionLaneIdFromRequest } from "./request-log-conversation"; import { setUsageLedgerRetention } from "./usage-ledger-retention"; -import { admitHttpWorkflowTurn, workflowDecisionRefusalResponse, type WorkflowRefusalLog } from "./workflow-refusal"; export { addFinalRequestLog, filterRequestLogs, queryRequestLogs, @@ -450,6 +448,8 @@ function startServerWithSpendLedgerOwner(port: number | undefined, deps: StartSe } if (rawPath === "/remote-workspace/pair") return remoteWorkspaceEnabled(config) && req.method === "POST"; if (rawPath === "/opencodex-session") return req.method === "GET" || req.method === "POST"; + // Ollama-compatible inference paths are data plane, not management: never via Tailscale Serve. + if (isOllamaNativePath(rawPath)) return false; if (rawPath.startsWith("/api/")) return true; if (req.method !== "GET" && req.method !== "HEAD") return false; let decodedPath: string; @@ -500,37 +500,7 @@ function startServerWithSpendLedgerOwner(port: number | undefined, deps: StartSe }), req, policy); } - async function runAdmittedHttpTurn( - req: Request, - policy: RequestPolicyView, - work: (lease: ActiveTurnLease) => Promise, - refusalLog?: WorkflowRefusalLog, - ): Promise { - const lease = tryAdmitTurn(sessionLaneIdFromRequest(req.headers), req.signal); - if (!lease) return serverBusyResponse(req, "active turns", policy); - // Root, lane, and the refusal that follows from them, all live in ./workflow-refusal. - let workflow: ReturnType; - try { workflow = admitHttpWorkflowTurn(req.headers); } - catch (error) { lease.release(); throw error; } - if (workflow && !workflow.admitted) { - lease.release(); - // withCors, because without Access-Control-Allow-Origin the exposed refusal header is - // still unreadable to a browser dashboard -- which made exposing it pointless. - return withCors(workflowDecisionRefusalResponse(workflow, undefined, refusalLog), req, policy); - } - if (workflow?.admitted) lease.attach(workflow.lease); - let response: Response; - try { - response = await runAdmittedBodyWork(req, policy, config.maxInboundBodyBytes, () => work(lease), refusalLog); - } catch (error) { - lease.release(); - throw error; - } - if (!lease.isTransferred()) { - lease.release(); - } - return response; - } + const runAdmittedHttpTurn = createAdmittedHttpTurn(() => config.maxInboundBodyBytes, serverBusyResponse); // Readiness gate: one PRIVATE controller per startServer invocation, captured // by this listener's closure. Starting/failing a second server in the same diff --git a/src/server/index/ollama-routes.ts b/src/server/index/ollama-routes.ts new file mode 100644 index 00000000000..4797135da66 --- /dev/null +++ b/src/server/index/ollama-routes.ts @@ -0,0 +1,89 @@ +/** + * Dispatcher arm for the Ollama-compatible inbound API. It runs before the management /api/ + * catch-all and only for the exact native paths; every other /api/ path is untouched. Admission + * reuses the data-plane gates: generation takes the same key, origin, drain, active-turn, + * workflow and body admission as /v1/chat/completions, and the read-only routes take the + * model-discovery admission /v1/models uses. Refusals keep their status and retry advice and are + * reshaped into the native { "error": string } body. + */ +import type { Server } from "bun"; +import type { OcxConfig } from "../../types"; +import type { WsData } from "../ws-bridge"; +import { admissionFields, isAllowedRequestOrigin, resolveApiAuth, resolveResponsesApiAuth, withCors, type RequestPolicyView } from "../auth-cors"; +import { withCallerSessionIdentity } from "../caller-session-identity"; +import { captureAdmissionPolicy } from "../capture-admission-policy"; +import { isDraining, type ActiveTurnLease } from "../lifecycle"; +import { handleOllamaGeneration, handleOllamaShow, handleOllamaTags, handleOllamaVersion, ollamaError, toOllamaRefusal } from "../ollama-inbound"; +import { OLLAMA_NATIVE_ROUTES } from "../ollama-native-paths"; +import { nextRequestLogId, type RequestLogContext } from "../request-log"; +import { disableResponsesRequestTimeout } from "../responses"; +import type { AdmittedHttpTurnOptions } from "../admitted-http-turn"; +import type { WorkflowRefusalLog } from "../workflow-refusal"; +import { withRequestLogId } from "./startup-warnings"; + +export interface OllamaRouteDeps { + config: OcxConfig; + policy: RequestPolicyView; + requestServer: Server; + requestMetricsLogContext: Partial; + drainingResponse: (req: Request, policy: RequestPolicyView) => Response; + runAdmittedHttpTurn: ( + req: Request, + policy: RequestPolicyView, + work: (lease: ActiveTurnLease) => Promise, + refusalLog?: WorkflowRefusalLog, + options?: AdmittedHttpTurnOptions, + ) => Promise; +} + +/** Returns undefined when the path is not one of the native routes. */ +export async function dispatchOllamaRoute(req: Request, url: URL, deps: OllamaRouteDeps): Promise { + const route = OLLAMA_NATIVE_ROUTES.get(url.pathname); + if (!route) return undefined; + const { config, policy } = deps; + if (req.method !== route.method) { + const refused = ollamaError(405, `method ${req.method} not allowed`); + refused.headers.set("Allow", route.method); + return withCors(refused, req, policy); + } + if (route.kind === "version" || route.kind === "tags" || route.kind === "show") { + // Model discovery never forwards Authorization upstream, so the broader admission set is safe. + const admission = resolveApiAuth(req, policy); + if (!admission) return withCors(ollamaError(401, "opencodex API key required"), req, policy); + if (!isAllowedRequestOrigin(req, policy)) return withCors(ollamaError(403, "cross-origin data-plane request blocked"), req, policy); + const response = route.kind === "version" ? handleOllamaVersion() + : route.kind === "tags" ? handleOllamaTags(config, req, admission) + : await handleOllamaShow(config, req, admission); + return withCors(response, req, policy); + } + const kind = route.kind; + disableResponsesRequestTimeout(req, deps.requestServer); + if (isDraining()) return withCors(toOllamaRefusal(deps.drainingResponse(req, policy)), req, policy); + const admission = resolveResponsesApiAuth(req, policy); + if (!admission) return withCors(ollamaError(401, "opencodex API key required"), req, policy); + if (!isAllowedRequestOrigin(req, policy)) return withCors(ollamaError(403, "cross-origin data-plane request blocked"), req, policy); + const start = Date.now(); + const requestId = nextRequestLogId(start); + const logCtx: RequestLogContext = { + model: "unknown", + provider: "unknown", + ...deps.requestMetricsLogContext, + ...admissionFields(admission), + }; + const sessionReq = withCallerSessionIdentity(req, admission); + // Expose an id only when the handler or a logged refusal owns the history row. + let ownsRequestLog = false; + const advisorAdmissionPolicy = captureAdmissionPolicy(config, admission); + const response = await deps.runAdmittedHttpTurn(sessionReq, policy, async turnAdmissionLease => { + ownsRequestLog = true; + return withCors( + await handleOllamaGeneration(kind, sessionReq, config, logCtx, { requestId, start, turnAdmissionLease, admission, advisorAdmissionPolicy }), + req, + policy, + ); + }, { requestId, start, logCtx, onLogged: () => { ownsRequestLog = true; } }, { + mapRefusal: toOllamaRefusal, + onAdmissionError: () => ollamaError(499, "request cancelled"), + }); + return ownsRequestLog ? withRequestLogId(response, requestId) : response; +} diff --git a/src/server/index/serve-options.ts b/src/server/index/serve-options.ts index 66350dffa78..5d178b62cb5 100644 --- a/src/server/index/serve-options.ts +++ b/src/server/index/serve-options.ts @@ -203,6 +203,10 @@ import type { OcxConfig } from "../../types"; import type { PackageTreeIntegrityGuard } from "../../lib/package-tree-integrity"; import type { ReadinessGate } from "../readiness"; import type { WorkflowRefusalLog } from "../workflow-refusal"; +import type { AdmittedHttpTurnOptions } from "../admitted-http-turn"; +import { isOllamaNativePath } from "../ollama-native-paths"; +import { ollamaError } from "../ollama-inbound"; +import { dispatchOllamaRoute } from "./ollama-routes"; import { readyProtocolMetadata } from "../../remote/protocol"; import { homeInstanceId, stampServedBy } from "../../remote/served-by"; @@ -256,6 +260,7 @@ export interface ServeOptionsContext { policy: RequestPolicyView, work: (lease: ActiveTurnLease) => Promise, refusalLog?: WorkflowRefusalLog, + options?: AdmittedHttpTurnOptions, ) => Promise; config: OcxConfig; @@ -414,6 +419,7 @@ export function createServeOptions(ctx: ServeOptionsContext) { url.pathname === "/healthz" || readyzPath !== undefined || url.pathname.startsWith("/v1/") + || isOllamaNativePath(url.pathname) )) { const message = "OpenCodex package files changed while this proxy was running; it restarts on its own, or run 'ocx restart' ('ocx service restart' for a background service)."; const fencedPort = ctx.boundPort ?? requestServer.port ?? listenPort; @@ -437,7 +443,9 @@ export function createServeOptions(ctx: ServeOptionsContext) { } : {}), error: { code: "package_tree_changed", message }, }, 503, req, policy) - : packageTreeChangedResponse(req, policy, message); + : isOllamaNativePath(url.pathname) + ? withCors(ollamaError(503, message), req, policy) + : packageTreeChangedResponse(req, policy, message); const headers = new Headers(response.headers); headers.set("Retry-After", "5"); const challenge = fencedHealth ? req.headers.get(LOCAL_ATTESTATION_CHALLENGE_HEADER) : null; @@ -453,7 +461,8 @@ export function createServeOptions(ctx: ServeOptionsContext) { if (readyzPath !== undefined) { return withCors(formatErrorResponse(404, "not_found", `Unknown endpoint: ${req.method} ${url.pathname}`), req, policy); } - const managementPreflight = url.pathname.startsWith("/api/"); + // The exact Ollama-compatible paths are data-plane routes and take data-plane CORS. + const managementPreflight = url.pathname.startsWith("/api/") && !isOllamaNativePath(url.pathname); const allowed = managementPreflight ? isAllowedManagementOrigin(req, config) : isAllowedRequestOrigin(req, policy); @@ -695,6 +704,12 @@ export function createServeOptions(ctx: ServeOptionsContext) { return new Response(resp.body, { status: 503, headers }); } + // Checked synchronously: an await here would delay every later route's admission capture. + if (isOllamaNativePath(url.pathname)) { + const native = await dispatchOllamaRoute(req, url, { config, policy, requestServer, requestMetricsLogContext, drainingResponse, runAdmittedHttpTurn }); + if (native) return native; + } + if (url.pathname.startsWith("/api/")) { const localManagementAuth = { attestationSecret: localAttestationSecret, diff --git a/src/server/native-final-log.ts b/src/server/native-final-log.ts new file mode 100644 index 00000000000..7e58842ad48 --- /dev/null +++ b/src/server/native-final-log.ts @@ -0,0 +1,97 @@ +/** + * Final request-log ownership for a native ingress that converts an inner Chat response. + * + * The inner Chat path keeps its own observation, attempt and usage accounting and its own + * callback ordering. Its final-log requests are intercepted: the first one is recorded as the + * physical attempt's settlement and nothing is written. The native handler, which alone knows + * whether its conversion succeeded or the client went away, commits exactly once through the + * ordinary writer. Later inner requests stay inert, so a delayed callback cannot add a row. + */ +import type { ResponsesTerminalStatus } from "../bridge"; +import { + addRequestLog, + commitInterceptedFinalRequestLog, + interceptFinalRequestLog, + type RequestLogContext, + type RequestLogEntry, +} from "./request-log"; + +/** How long a known outer outcome waits for a missing inner settlement before cutting off. */ +export const NATIVE_FINAL_LOG_FALLBACK_MS = 100; +export const NATIVE_FINAL_LOG_CUTOFF_CODE = "observation_barrier_timeout"; + +export interface NativeFinalOutcome { + status: number; + terminalStatus?: ResponsesTerminalStatus; + closeReason: NonNullable; +} + +export interface NativeFinalLog { + /** True once the inner path requested its final log. */ + innerSettled(): boolean; + /** + * Call once the outer outcome is known. Resolves true when the inner path has settled, or + * false when the bounded fallback elapsed first. Never waits on an upstream cancellation. + */ + waitForInner(): Promise; + /** Write the single row. Returns false when a row was already committed. */ + commit(outcome: NativeFinalOutcome): boolean; +} + +export function createNativeFinalLog( + requestId: string, + start: number, + logCtx: RequestLogContext, + options: { fallbackMs?: number; addLog?: (entry: RequestLogEntry) => void } = {}, +): NativeFinalLog { + const fallbackMs = options.fallbackMs ?? NATIVE_FINAL_LOG_FALLBACK_MS; + let innerStatus: number | undefined; + let wake: (() => void) | undefined; + let waiting: Promise | undefined; + let committed = false; + interceptFinalRequestLog(logCtx, status => { + if (innerStatus !== undefined) return; + innerStatus = status; + // Resolved on a later microtask, so observations the inner producer makes later in the same + // synchronous pass (a relay's completed-response hook, for example) land before the commit. + wake?.(); + }); + return { + innerSettled: () => innerStatus !== undefined, + waitForInner() { + waiting ??= innerStatus !== undefined + ? Promise.resolve(true) + : new Promise(resolve => { + const timer = setTimeout(() => { wake = undefined; resolve(innerStatus !== undefined); }, fallbackMs); + wake = () => { clearTimeout(timer); wake = undefined; resolve(true); }; + }); + return waiting; + }, + commit(outcome) { + if (committed) return false; + committed = true; + // A native ingress row never persists upstream-authored text: an upstream error can echo + // a credential no redaction pattern recognizes. Status, codes we derive, and attribution stay. + delete logCtx.upstreamError; + delete logCtx.upstreamErrorCode; + delete logCtx.upstreamErrorType; + delete logCtx.upstreamRequestId; + let { status, terminalStatus } = outcome; + if (innerStatus === undefined) { + // Cut off before the inner path settled: what it observed so far is not a complete + // account. Drop it, so the row reads unreported and the terminal send settles as + // unresolved rather than being priced from a partial count, and never report success. + delete logCtx.usage; + delete logCtx.usageLogInputTokens; + if (logCtx.activeAttempt) delete logCtx.activeAttempt.usage; + logCtx.errorCode = NATIVE_FINAL_LOG_CUTOFF_CODE; + if (status < 400) { status = 502; terminalStatus = "failed"; } + } + commitInterceptedFinalRequestLog(requestId, start, logCtx, status, { + ...(terminalStatus ? { terminalStatus } : {}), + closeReason: status === 499 ? "client_cancel" : outcome.closeReason, + }, innerStatus ?? status, options.addLog ?? addRequestLog); + return true; + }, + }; +} diff --git a/src/server/ollama-inbound.ts b/src/server/ollama-inbound.ts new file mode 100644 index 00000000000..06762a9ff67 --- /dev/null +++ b/src/server/ollama-inbound.ts @@ -0,0 +1,349 @@ +/** + * Ollama-compatible inbound API: /api/version, /api/tags, /api/show, /api/chat and /api/generate. + * + * The model list describes configured provider routes this proxy can serve, not models stored on + * this machine. Generation is translated into an internal Chat Completions request and handled by + * the ordinary Chat path, so routing, admission scope, retries and usage accounting stay shared. + * The final request-log row is owned here (see ./native-final-log): only this handler knows + * whether its own conversion succeeded or the client went away. + */ +import { OllamaCodecError, consumeOllamaChatChunk, createOllamaStreamState, ollamaBufferedResponse, ollamaStreamTerminal, ollamaToChat, type OllamaKind } from "../protocols/codecs/ollama"; +import { createTranslatorBudget, isTranslatorBudgetExceededError } from "../lib/translator-budget"; +import { parseRetryAfterMs } from "../combos"; +import { WORKFLOW_LOCAL_REFUSAL_HEADER } from "../lib/workflow-budget"; +import type { OcxConfig } from "../types"; +import type { DataPlaneAdmission } from "./auth-cors"; +import type { CapturedAdmissionPolicy } from "../types/admission-policy"; +import type { AdmissionLease } from "../lib/admission"; +import { resolveAdmissionModelScope, routeAllowedByScope } from "./admission-model-scope"; +import { handleChatCompletions } from "./chat-completions"; +import { VERSION } from "./management-api"; +import { createNativeFinalLog, type NativeFinalLog } from "./native-final-log"; +import { findOllamaRoute, linkRequestSessionLane, listOllamaRoutes, preflightOllamaRoute } from "./ollama-route-policy"; +import { DecompressedBodyTooLargeError, readJsonRequestBody, resolveInboundBodyLimitBytes } from "./request-decompress"; +import { addFinalRequestLog, type RequestLogContext } from "./request-log"; + +const SHOW_BODY_LIMIT_BYTES = 64 * 1024; +// Session and workflow identity only: lineage, session lanes and the workflow root's spend +// ceiling read these from the request Chat sees. Never authorization, cookies or admission keys. +const IDENTITY_HEADERS = ["session_id", "session-id", "thread-id", "x-session-id", "x-codex-parent-thread-id"] as const; + +/** Upper bound for the retry advice this surface passes on. */ +export const OLLAMA_MAX_RETRY_AFTER_SECONDS = 3600; + +/** + * Retry-After as an integer we format ourselves. The incoming value may come from an upstream, + * so only the parsed delay crosses this boundary, never its bytes; unparseable values are dropped. + */ +export function ollamaRetryAfter(value: string | null | undefined, now = Date.now()): string | undefined { + if (value?.trim() === "0") return "0"; + const ms = parseRetryAfterMs(value, now); + if (ms === undefined) return undefined; + return String(Math.min(OLLAMA_MAX_RETRY_AFTER_SECONDS, Math.max(0, Math.ceil(ms / 1000)))); +} + +/** + * Every Ollama error response is built from scratch: content type, our own error text, and + * optionally a reformatted Retry-After. Callers add CORS and the request-log id; nothing is + * copied from another response. + */ +export function ollamaError(status: number, message: string, retryAfter?: string | null): Response { + const headers = new Headers({ "content-type": "application/json" }); + const advice = ollamaRetryAfter(retryAfter); + if (advice !== undefined) headers.set("Retry-After", advice); + return new Response(JSON.stringify({ error: message }), { status, headers }); +} + +/** + * The local refusal codes this surface passes on, each mapped to a constant defined here. The + * emitted header value is always the constant; an incoming value only selects it, and any value + * not in this table is dropped. + */ +const LOCAL_REFUSAL_CODES: ReadonlyMap = new Map([ + ["workflow_sends_exhausted", "workflow_sends_exhausted"], + ["workflow_children_exhausted", "workflow_children_exhausted"], + ["workflow_concurrency_exhausted", "workflow_concurrency_exhausted"], + ["workflow_spend_exhausted", "workflow_spend_exhausted"], + ["workflow_tracking_exhausted", "workflow_tracking_exhausted"], + ["workflow_send_replayed", "workflow_send_replayed"], + ["workflow_pool_history_unresolved", "workflow_pool_history_unresolved"], + ["workflow_spend_undurable", "workflow_spend_undurable"], +]); + +/** Reshape an existing proxy refusal (capacity, workflow, drain) keeping its status and retry advice. */ +export function toOllamaRefusal(response: Response): Response { + try { void response.body?.cancel().catch(() => {}); } catch { /* already consumed */ } + const message = response.status === 429 ? "request budget exhausted; retry later" + : response.status === 499 ? "request cancelled" + : response.status === 503 ? "server temporarily unavailable; retry later" : "request refused"; + const native = ollamaError(response.status, message, response.headers.get("retry-after")); + // The workflow refusal names its local reason; only a recognized code selects our constant. + const code = LOCAL_REFUSAL_CODES.get(response.headers.get(WORKFLOW_LOCAL_REFUSAL_HEADER) ?? ""); + if (code !== undefined) { + native.headers.set(WORKFLOW_LOCAL_REFUSAL_HEADER, code); + native.headers.set("Access-Control-Expose-Headers", WORKFLOW_LOCAL_REFUSAL_HEADER); + } + return native; +} + +export function handleOllamaVersion(): Response { + return Response.json({ version: VERSION }); +} + +function eligibleRoutes(config: OcxConfig, req: Request, admission: DataPlaneAdmission) { + const scope = resolveAdmissionModelScope(config, admission); + return listOllamaRoutes(config, req) + .filter(row => routeAllowedByScope(scope, { providerName: row.route.providerName, modelId: row.route.modelId })); +} + +export function handleOllamaTags(config: OcxConfig, req: Request, admission: DataPlaneAdmission): Response { + return Response.json({ models: eligibleRoutes(config, req, admission).map(row => ({ name: row.selector, model: row.selector })) }); +} + +export async function handleOllamaShow(config: OcxConfig, req: Request, admission: DataPlaneAdmission): Promise { + let body: unknown; + try { body = await readJsonRequestBody(req, undefined, SHOW_BODY_LIMIT_BYTES); } + catch (error) { return ollamaError(error instanceof DecompressedBodyTooLargeError ? 413 : 400, "invalid request body"); } + const record = body && typeof body === "object" && !Array.isArray(body) ? body as Record : undefined; + const model = record?.model; + if (!record || Object.keys(record).some(key => key !== "model" && key !== "verbose") || typeof model !== "string" || !model.trim()) { + return ollamaError(400, "model is required"); + } + // Same eligibility as /api/tags: a configured concrete route the caller's key may use. + // Same eligibility as /api/tags, resolved for this selector only. + const row = findOllamaRoute(config, model, req); + const scope = resolveAdmissionModelScope(config, admission); + if (!row || !routeAllowedByScope(scope, { providerName: row.route.providerName, modelId: row.route.modelId })) return ollamaError(404, "model not found"); + // Only facts this proxy knows. No file size, digest, template, license or local model details. + return Response.json({ details: {}, model_info: {}, capabilities: ["completion"] }); +} + +export interface OllamaLogIds { + requestId: string; + start: number; + turnAdmissionLease?: AdmissionLease; + admission?: DataPlaneAdmission; + advisorAdmissionPolicy?: CapturedAdmissionPolicy; +} + +function failBeforeInner(ids: OllamaLogIds, logCtx: RequestLogContext, status: number, message: string): Response { + addFinalRequestLog(ids.requestId, ids.start, logCtx, status, { closeReason: "non_stream" }); + return ollamaError(status, message); +} + +function internalChatRequest(req: Request, chatJson: string): Request { + const headers = new Headers({ "content-type": "application/json" }); + for (const name of IDENTITY_HEADERS) { + const value = req.headers.get(name); + if (value !== null) headers.set(name, value); + } + const internal = new Request(new URL("/v1/chat/completions", req.url), { method: "POST", headers, body: chatJson, signal: req.signal }); + linkRequestSessionLane(req, internal); + return internal; +} + +/** + * Native error text is chosen by status only. The inner body can carry upstream-authored text, + * which may echo a credential no pattern recognizes, so it is drained and never forwarded. + */ +const INNER_ERROR_MESSAGES: Readonly> = { + 400: "request rejected", + 401: "upstream authentication failed", + 402: "upstream payment required", + 403: "request not permitted", + 404: "model not found", + 408: "upstream request timed out", + 409: "request conflict", + 413: "request too large", + 422: "request rejected", + 429: "rate limited; retry later", + 499: "request cancelled", + 500: "upstream request failed", + 502: "upstream request failed", + 503: "upstream unavailable; retry later", + 504: "upstream request timed out", +}; + +export function ollamaInnerErrorMessage(status: number): string { + return INNER_ERROR_MESSAGES[status] ?? (status >= 500 ? "upstream request failed" : "request failed"); +} + +async function innerErrorMessage(response: Response): Promise { + await response.body?.cancel().catch(() => {}); + return ollamaInnerErrorMessage(response.ok ? 502 : response.status); +} + +/** /api/chat and /api/generate. `req` is the admitted, session-promoted request. */ +export async function handleOllamaGeneration( + kind: OllamaKind, + req: Request, + config: OcxConfig, + logCtx: RequestLogContext, + ids: OllamaLogIds, +): Promise { + const limit = resolveInboundBodyLimitBytes(config.maxInboundBodyBytes); + const budget = createTranslatorBudget(); + let chat: Record; + try { + chat = ollamaToChat(kind, await readJsonRequestBody(req, budget, limit)); + } catch (error) { + if (req.signal.aborted) return failBeforeInner(ids, logCtx, 499, "request cancelled"); + if (error instanceof DecompressedBodyTooLargeError) return failBeforeInner(ids, logCtx, 413, "request body too large"); + if (isTranslatorBudgetExceededError(error)) return failBeforeInner(ids, logCtx, 502, "request translation buffer exceeded the safe limit"); + return failBeforeInner(ids, logCtx, 400, error instanceof OllamaCodecError ? error.message : "invalid JSON body"); + } finally { + budget.dispose(); + } + const model = chat.model as string; + logCtx.requestedModel = model; + const preflight = preflightOllamaRoute(config, model, req); + if (!preflight.ok) { + logCtx.errorCode = preflight.error.code; + return failBeforeInner(ids, logCtx, preflight.error.status, preflight.error.message); + } + // Both Chat delivery paths already report streamed usage on their own; the body stays as a Chat caller sends it. + const stream = chat.stream === true; + const chatJson = JSON.stringify(chat); + if (Buffer.byteLength(chatJson) > limit) return failBeforeInner(ids, logCtx, 413, "request body too large"); + const internal = internalChatRequest(req, chatJson); + const finalLog = createNativeFinalLog(ids.requestId, ids.start, logCtx); + const createdAt = new Date().toISOString(); + let inner: Response; + try { + inner = await handleChatCompletions(internal, config, logCtx, { ...ids, suppressProtocolTrace: true }); + } catch { + await finalLog.waitForInner(); + if (req.signal.aborted) return cancelledNonStream(finalLog); + finalLog.commit({ status: 502, terminalStatus: "failed", closeReason: "non_stream" }); + return ollamaError(502, "request failed"); + } + if (!inner.ok || !inner.body) { + const message = await innerErrorMessage(inner); + await finalLog.waitForInner(); + if (req.signal.aborted) return cancelledNonStream(finalLog); + finalLog.commit({ status: inner.ok ? 502 : inner.status, terminalStatus: "failed", closeReason: "non_stream" }); + return ollamaError(inner.ok ? 502 : inner.status, message, inner.headers.get("retry-after")); + } + return stream + ? streamOllama(kind, model, createdAt, inner.body, finalLog, req.signal) + : bufferedOllama(kind, model, createdAt, inner, finalLog, req.signal); +} + +/** A client that left before the outer outcome was committed owns a 499 row, whatever the inner path reported. */ +function cancelledNonStream(finalLog: NativeFinalLog): Response { + finalLog.commit({ status: 499, closeReason: "client_cancel" }); + return ollamaError(499, "request cancelled"); +} + +/** Exported for the settlement-window cancellation test; production callers go through handleOllamaGeneration. */ +export async function bufferedOllama(kind: OllamaKind, model: string, createdAt: string, inner: Response, finalLog: NativeFinalLog, signal: AbortSignal): Promise { + let native: Record; + try { + native = ollamaBufferedResponse(kind, model, JSON.parse(await inner.text()), createdAt); + } catch { + await finalLog.waitForInner(); + if (signal.aborted) return cancelledNonStream(finalLog); + finalLog.commit({ status: 502, terminalStatus: "failed", closeReason: "non_stream" }); + return ollamaError(502, "invalid upstream response"); + } + const settled = await finalLog.waitForInner(); + if (signal.aborted) return cancelledNonStream(finalLog); + if (native.done !== true || !settled) { + finalLog.commit({ status: 502, terminalStatus: "failed", closeReason: "non_stream" }); + return ollamaError(502, typeof native.error === "string" ? native.error : "request did not complete"); + } + finalLog.commit({ status: 200, terminalStatus: "completed", closeReason: "non_stream" }); + return Response.json(native); +} + +const encoder = new TextEncoder(); +const line = (record: unknown) => encoder.encode(`${JSON.stringify(record)}\n`); + +/** Exported for the settlement-window cancellation test; production callers go through handleOllamaGeneration. */ +export function streamOllama(kind: OllamaKind, model: string, createdAt: string, body: ReadableStream, finalLog: NativeFinalLog, signal: AbortSignal): Response { + const reader = body.getReader(); + const decoder = new TextDecoder(); + const state = createOllamaStreamState(kind, model, createdAt); + let pending = ""; + // ended: no further reads or records. cancelled: the client went away, possibly while end() waits. + let ended = false; + let cancelled = false; + // The inner Chat path can finalize on EOF after [DONE], so keep draining to EOF before ending. + let sawDone = false; + const cancelInner = () => { try { void reader.cancel().catch(() => {}); } catch { /* released */ } }; + const commitCancelled = () => finalLog.commit({ status: 499, closeReason: "client_cancel" }); + const end = async (controller: ReadableStreamDefaultController, failure?: string) => { + if (ended) return; + ended = true; + if (failure !== undefined) cancelInner(); + const terminal = failure === undefined ? ollamaStreamTerminal(state) : undefined; + const settled = await finalLog.waitForInner(); + if (cancelled || signal.aborted) { + commitCancelled(); + try { controller.close(); } catch { /* already cancelled by the client */ } + return; + } + try { + if (terminal?.done === true && settled) { + controller.enqueue(line(terminal)); + finalLog.commit({ status: 200, terminalStatus: "completed", closeReason: "terminal" }); + } else { + controller.enqueue(line({ error: failure ?? (typeof terminal?.error === "string" ? terminal.error : "request did not complete") })); + finalLog.commit({ status: 502, terminalStatus: "failed", closeReason: "terminal" }); + } + controller.close(); + } catch { + // The client cancelled between settlement and the terminal record; the row still lands once. + commitCancelled(); + } + }; + // Returns how many native records were enqueued. Finish and usage frames enqueue nothing. + const consume = (controller: ReadableStreamDefaultController, block: string): number => { + let emitted = 0; + for (const raw of block.split("\n")) { + const text = raw.trimEnd(); + if (!text.startsWith("data:")) continue; + // Chat ends at [DONE]; any later data (an error frame, say) means the stream did not settle cleanly. + if (sawDone) throw new Error("data after the Chat stream terminator"); + const payload = text.slice(5).trim(); + if (payload === "[DONE]") { sawDone = true; continue; } + for (const record of consumeOllamaChatChunk(state, JSON.parse(payload))) { controller.enqueue(line(record)); emitted++; } + } + return emitted; + }; + return new Response(new ReadableStream({ + // A pull that resolves without enqueueing is not called again, so keep reading until this + // pull has produced a record or ended the stream. + async pull(controller) { + try { + while (!ended) { + const { done, value } = await reader.read(); + if (done) { + pending += decoder.decode(); + if (pending) consume(controller, pending); + pending = ""; + await end(controller); + return; + } + pending += decoder.decode(value, { stream: true }); + const boundary = pending.lastIndexOf("\n"); + if (boundary < 0) continue; + const complete = pending.slice(0, boundary); + pending = pending.slice(boundary + 1); + if (consume(controller, complete) > 0) return; + } + } catch { + await end(controller, signal.aborted ? "request cancelled" : "upstream stream failed"); + } + }, + async cancel() { + cancelled = true; + // When end() is already waiting for settlement it sees the flag and writes the 499 row. + if (ended) return; + ended = true; + cancelInner(); + await finalLog.waitForInner(); + commitCancelled(); + }, + }, { highWaterMark: 0 }), { status: 200, headers: { "content-type": "application/x-ndjson" } }); +} diff --git a/src/server/ollama-native-paths.ts b/src/server/ollama-native-paths.ts new file mode 100644 index 00000000000..d9a739b8c64 --- /dev/null +++ b/src/server/ollama-native-paths.ts @@ -0,0 +1,21 @@ +/** + * Exact Ollama-compatible paths served on the authenticated data-plane listener. Kept free of + * handler imports so listener allowlists and the package-tree fence can classify a path cheaply. + * Anything else under /api/ stays with the management API. + */ +export type OllamaNativeKind = "version" | "tags" | "show" | "chat" | "generate"; + +export const OLLAMA_NATIVE_ROUTES: ReadonlyMap = new Map([ + ["/api/version", { method: "GET", kind: "version" }], + ["/api/tags", { method: "GET", kind: "tags" }], + ["/api/show", { method: "POST", kind: "show" }], + ["/api/chat", { method: "POST", kind: "chat" }], + ["/api/generate", { method: "POST", kind: "generate" }], +]); + +/** Generation routes read a JSON body under maxInboundBodyBytes and take the raised-body admission. */ +export const OLLAMA_JSON_BODY_ROUTES: ReadonlySet = new Set(["/api/chat", "/api/generate"]); + +export function isOllamaNativePath(pathname: string): boolean { + return OLLAMA_NATIVE_ROUTES.has(pathname); +} diff --git a/src/server/ollama-route-policy.ts b/src/server/ollama-route-policy.ts new file mode 100644 index 00000000000..2a783382293 --- /dev/null +++ b/src/server/ollama-route-policy.ts @@ -0,0 +1,73 @@ +import type { OcxConfig } from "../types"; +import { captureRouteStaticPolicy, previewRouteModel, type RouteResult } from "../router"; +import { POLICY_NAMESPACE, resolvePolicyProfileId } from "../routing/profile"; +import { isShadowSourceModel } from "../lib/shadow-call"; +import { providerConsumesCallerAuthorization } from "../providers/caller-authorization"; +import { resolveOpenCodeGoTransport } from "../providers/opencode-go-transport"; +import { resolveWireProtocolOverride } from "./adapter-resolve"; +import { parseSyntheticRowId } from "./fast-row"; +import { getOrAllocateRequestSessionLane } from "./request-log-conversation"; + +export { linkRequestSessionLane } from "./request-log-conversation"; + +export type OllamaRouteError = + | { status: 400; code: "unsupported_synthetic_selector" | "unsupported_shadow_rewrite"; message: string } + | { status: 403; code: "unsupported_credential_domain"; message: string } + | { status: 404; code: "model_not_found"; message: string }; +export type OllamaRoutePreflight = { ok: true; route: RouteResult } | { ok: false; error: OllamaRouteError }; + +function fail(error: OllamaRouteError): OllamaRoutePreflight { return { ok: false, error }; } +const credentialError = (): OllamaRoutePreflight => fail({ status: 403, code: "unsupported_credential_domain", message: "This model requires an unsupported credential domain" }); + +/** Resolve exactly the Chat transport before admitting a native request. No send occurs here. */ +export function preflightOllamaRoute(config: OcxConfig, selector: string, req: Request): OllamaRoutePreflight { + const { fastRow, effortRow } = parseSyntheticRowId(selector, config); + if (fastRow || effortRow) return fail({ status: 400, code: "unsupported_synthetic_selector", message: "Synthetic model selectors are unsupported" }); + if (config.shadowCallIntercept?.enabled && isShadowSourceModel(selector, config.shadowCallIntercept.sourceModels)) { + return fail({ status: 400, code: "unsupported_shadow_rewrite", message: "Shadow model rewrites are unsupported" }); + } + if (resolvePolicyProfileId(config, selector) !== null || selector === POLICY_NAMESPACE || selector.startsWith(`${POLICY_NAMESPACE}/`)) return credentialError(); + let route: RouteResult; + try { route = previewRouteModel(config, selector); } + catch { return fail({ status: 404, code: "model_not_found", message: "Model route not found" }); } + const routedProvider = route.provider; + route.staticPolicy = captureRouteStaticPolicy(route.providerName, route.modelId, routedProvider, route.staticPolicy.effectiveAlias, "chat"); + const wireProvider = resolveWireProtocolOverride(route.providerName, route.modelId, routedProvider, "chat", route.staticPolicy); + route.provider = resolveOpenCodeGoTransport(wireProvider, getOrAllocateRequestSessionLane(req), routedProvider); + if (route.combo || route.routeKind === "combo" || route.routeKind === "policy" || route.credentialDomainRewrite || providerConsumesCallerAuthorization(route.provider)) return credentialError(); + if (!Object.hasOwn(config.providers, route.providerName) || config.providers[route.providerName]?.disabled === true) { + return fail({ status: 404, code: "model_not_found", message: "Model route not found" }); + } + return { ok: true, route }; +} + +/** The configured models one enabled provider offers here; shared by the list and the point lookup. */ +function providerCatalogModels(config: OcxConfig, name: string): string[] { + const provider = Object.hasOwn(config.providers, name) ? config.providers[name] : undefined; + if (!provider || provider.disabled === true) return []; + const models = new Set([...(provider.models ?? []), ...(provider.defaultModel ? [provider.defaultModel] : []), + ...(provider.retainModels ?? []), ...(provider.selectedModels ?? []), + ...(config.customModels ?? []).filter(model => model.provider === name).map(model => model.modelId)]); + return [...models].filter(model => model && !(provider.selectedModels?.length && !provider.selectedModels.includes(model))); +} + +function catalogRoute(config: OcxConfig, name: string, model: string, req: Request): { selector: string; route: RouteResult } | undefined { + const selector = `${name}/${model}`; + const result = preflightOllamaRoute(config, selector, req); + return result.ok && result.route.providerName === name && result.route.modelId === model ? { selector, route: result.route } : undefined; +} + +/** Configuration-only inventory; this does not imply any locally stored Ollama model. */ +export function listOllamaRoutes(config: OcxConfig, req: Request): Array<{ selector: string; route: RouteResult }> { + return Object.keys(config.providers).flatMap(name => + providerCatalogModels(config, name).flatMap(model => catalogRoute(config, name, model, req) ?? [])); +} + +/** The listed route for one selector, with the same eligibility as the list but one preflight. */ +export function findOllamaRoute(config: OcxConfig, selector: string, req: Request): { selector: string; route: RouteResult } | undefined { + const slash = selector.indexOf("/"); + if (slash <= 0) return undefined; + const name = selector.slice(0, slash); + const model = selector.slice(slash + 1); + return providerCatalogModels(config, name).includes(model) ? catalogRoute(config, name, model, req) : undefined; +} diff --git a/src/server/request-log-failure-attribution.ts b/src/server/request-log-failure-attribution.ts index 291634b4098..255276565d4 100644 --- a/src/server/request-log-failure-attribution.ts +++ b/src/server/request-log-failure-attribution.ts @@ -100,3 +100,25 @@ export function attributeSealedAttempt( if (attribution?.stage) attempt.failureStage = attribution.stage; if (attribution?.cause) attempt.failureCause = attribution.cause; } + +/** + * Re-derive the pair for the physical attempt alone, from its own status and observations. + * + * Used when a native ingress owns the request outcome separately (for example an upstream 200 + * whose native conversion then failed, or a client cancel after the send succeeded): the request + * row carries the outer outcome while the attempt keeps the exchange it actually had. + */ +export function attributePhysicalAttempt(attempt: PersistedUsageAttempt): void { + const attribution = deriveRequestFailureAttribution({ + status: attempt.status, + ...(attempt.streamAborted === true ? { streamAborted: true } : {}), + outputObserved: attempt.firstOutputMs !== undefined, + sideEffectObserved: (attempt.deliverySummary?.sideEffectEvents ?? 0) > 0, + locallyAnswered: false, + recoveryKinds: attempt.recoveryKinds, + }); + if (attribution?.stage) attempt.failureStage = attribution.stage; + else delete attempt.failureStage; + if (attribution?.cause) attempt.failureCause = attribution.cause; + else delete attempt.failureCause; +} diff --git a/src/server/request-log.ts b/src/server/request-log.ts index be3dde123cc..cbfb520c65f 100644 --- a/src/server/request-log.ts +++ b/src/server/request-log.ts @@ -66,7 +66,7 @@ import { } from "../usage/log"; import type { RequestExecutionBudget } from "../lib/request-execution-budget"; import type { WorkflowSpendDenialDetail } from "../lib/workflow-budget"; -import { attributeFinalRequest, attributeSealedAttempt } from "./request-log-failure-attribution"; +import { attributeFinalRequest, attributePhysicalAttempt, attributeSealedAttempt } from "./request-log-failure-attribution"; import { debugAttemptDeliverySummary } from "../lib/debug"; import { appendUsageDebug, @@ -1387,6 +1387,22 @@ export function recordKeyWireAttemptUsage(logCtx: RequestLogContext, usage: OcxU return true; } +type FinalRequestLogMetaArg = Pick; +const finalRequestLogInterceptors = new WeakMap void>(); + +/** Route inner final-log requests to an outer owner (native ingress) instead of writing them. */ +export function interceptFinalRequestLog(logCtx: RequestLogContext, onRequest: (status: number, meta?: FinalRequestLogMetaArg) => void): void { + finalRequestLogInterceptors.set(logCtx, onRequest); +} + +/** The outer owner's write: request-level status from the outer outcome, the physical attempt's from the inner one. */ +export function commitInterceptedFinalRequestLog( + requestId: string, start: number, logCtx: RequestLogContext, status: number, meta: FinalRequestLogMetaArg | undefined, + attemptStatus: number, addLog: (entry: RequestLogEntry) => void = addRequestLog, +): void { + writeFinalRequestLog(requestId, start, logCtx, status, meta, addLog, attemptStatus); +} + export function addFinalRequestLog( requestId: string, start: number, @@ -1394,10 +1410,25 @@ export function addFinalRequestLog( status: number, meta?: Pick, addLog: (entry: RequestLogEntry) => void = addRequestLog, +): void { + const intercept = finalRequestLogInterceptors.get(logCtx); + if (intercept) { intercept(status, meta); return; } + writeFinalRequestLog(requestId, start, logCtx, status, meta, addLog); +} + +function writeFinalRequestLog( + requestId: string, + start: number, + logCtx: RequestLogContext, + status: number, + meta?: Pick, + addLog: (entry: RequestLogEntry) => void = addRequestLog, + attemptStatus?: number, ): void { // Mid-stream web-search aborts used to emit response.failed and land as 502/upstream_server_error. // Prefer the client-close classification whenever the captured reason says so. - const effectiveStatus = status >= 500 && logCtx.upstreamError && isClientClosedMessage(logCtx.upstreamError) + // A coordinated (attemptStatus) write carries an authoritative outer outcome; skip the heuristic. + const effectiveStatus = attemptStatus === undefined && status >= 500 && logCtx.upstreamError && isClientClosedMessage(logCtx.upstreamError) ? 499 : status; // Locally assigned codes name proxy refusals that status and upstream text cannot reconstruct. @@ -1415,7 +1446,7 @@ export function addFinalRequestLog( if (logCtx.activeAttempt) { finishRequestAttempt( logCtx.activeAttempt, - effectiveStatus, + attemptStatus ?? effectiveStatus, Date.now() - (logCtx.activeAttemptStartedAt ?? start), keyUsageOwners.has(logCtx.activeAttempt) ? logCtx.activeAttempt.usage @@ -1423,7 +1454,9 @@ export function addFinalRequestLog( ); // The final row and its active physical attempt describe the same terminal. Preserve the // semantic code on both so detailed attempt telemetry cannot regress to a generic status code. - if (errorCode) logCtx.activeAttempt.errorCode = errorCode; + const attemptErrorCode = attemptStatus === undefined ? errorCode : attemptStatus < 400 ? undefined + : logCtx.errorCode ?? requestLogErrorCode(attemptStatus, logCtx.upstreamError, logCtx.terminalErrorCode, false); + if (attemptErrorCode) logCtx.activeAttempt.errorCode = attemptErrorCode; else delete logCtx.activeAttempt.errorCode; } // Derived and stamped in a sibling module, before the attempt snapshot below. Every input is @@ -1437,8 +1470,10 @@ export function addFinalRequestLog( outputObserved: logCtx.firstOutputMs !== undefined, ...(logCtx.causeHint ? { causeHint: logCtx.causeHint } : {}), locallyAnswered: logCtx.localTerminalReason !== undefined, - ...(logCtx.activeAttempt ? { attempt: logCtx.activeAttempt } : {}), + // A coordinated write derives the request pair from a copy and re-derives the attempt's own. + ...(logCtx.activeAttempt ? { attempt: attemptStatus === undefined ? logCtx.activeAttempt : { ...logCtx.activeAttempt } } : {}), }); + if (attemptStatus !== undefined && logCtx.activeAttempt) attributePhysicalAttempt(logCtx.activeAttempt); // The one seam every request passes exactly once, whatever transport served it and however // it ended. The terminal usage belongs to the last send that left; the ledger resolves every // earlier send of this request as unresolved spend rather than handing its tokens back. diff --git a/structure/INDEX.md b/structure/INDEX.md index b368a06639d..c30231aa765 100644 --- a/structure/INDEX.md +++ b/structure/INDEX.md @@ -67,6 +67,7 @@ The wire surfaces a client actually talks to. | [`data-planes/search.md`](data-planes/search.md) | Hosted search relay and exact account selectors. | | [`data-planes/inbound-compat.md`](data-planes/inbound-compat.md) | Chat Completions inbound, Anthropic-shaped clients, and JSON-upstream streaming clients. | | [`data-planes/claude-tool-loading.md`](data-planes/claude-tool-loading.md) | Physical-adapter tool-loading projection, preserved catalogs, fallback exclusions and opt-in prerequisites. | +| [`data-planes/ollama-inbound.md`](data-planes/ollama-inbound.md) | Ollama-shaped version/tags/show/chat/generate routes translated onto Chat Completions, their admission, native error shape and final request-log ownership. | | [`data-planes/chat-reasoning-details.md`](data-planes/chat-reasoning-details.md) | The reasoning_details carrier that lets Chat Completions clients round-trip signed Anthropic thinking across tool steps (#7429). | | [`data-planes/protocol-paths.md`](data-planes/protocol-paths.md) | Shared protocol vocabulary, declared feature dispositions, the ingress-by-upstream baseline, plan/trace shapes, and protocol settings. | | [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | Per-account Pool wire installation identity, private secret, existence gates and fail-closed delivery. | @@ -351,6 +352,7 @@ A source area can be described by more than one doc, because these docs are orga | `src/oauth/workbuddy.ts` | [`providers/workbuddy.md`](providers/workbuddy.md) | | `src/plugins/` | [`ops/plugins.md`](ops/plugins.md) | | `src/protocols/` | [`data-planes/protocol-paths.md`](data-planes/protocol-paths.md) | +| `src/protocols/codecs/ollama.ts` | [`data-planes/ollama-inbound.md`](data-planes/ollama-inbound.md) | | `src/providers/` | [`runtime.md`](runtime.md)
[`subagents.md`](subagents.md)
[`transports/inventory.md`](transports/inventory.md)
[`providers-and-adapters.md`](providers-and-adapters.md)
[`providers/anthropic-account-pool.md`](providers/anthropic-account-pool.md)
[`providers/xai-grok.md`](providers/xai-grok.md)
[`providers/lm-studio-chat.md`](providers/lm-studio-chat.md) | | `src/providers/account-quota-disk.ts` | [`quota-snapshots.md`](quota-snapshots.md) | | `src/providers/anthropic-billing-ownership.ts` | [`providers/anthropic-key-billing.md`](providers/anthropic-key-billing.md) | @@ -385,6 +387,7 @@ A source area can be described by more than one doc, because these docs are orga | `src/routing/` | [`catalog.md`](catalog.md)
[`fallback-policy.md`](fallback-policy.md) | | `src/routing/history/` | [`dashboard-and-usage.md`](dashboard-and-usage.md) | | `src/server/` | [`transports/timeouts.md`](transports/timeouts.md)
[`providers/generic-account-pool.md`](providers/generic-account-pool.md)
[`runtime.md`](runtime.md)
[`codex-prompts.md`](codex-prompts.md)
[`catalog.md`](catalog.md)
[`subagents.md`](subagents.md)
[`transports/byte-accounting.md`](transports/byte-accounting.md)
[`transports/responses.md`](transports/responses.md)
[`transports/native-reasoning-retention.md`](transports/native-reasoning-retention.md)
[`transports/responses-wire-shapes.md`](transports/responses-wire-shapes.md)
[`transports/responses-failover.md`](transports/responses-failover.md)
[`transports/responses-combo-boundaries.md`](transports/responses-combo-boundaries.md)
[`transports/policy-fallback.md`](transports/policy-fallback.md)
[`transports/streaming-health.md`](transports/streaming-health.md)
[`transports/inventory.md`](transports/inventory.md)
[`data-planes/images.md`](data-planes/images.md)
[`data-planes/inbound-compat.md`](data-planes/inbound-compat.md)
[`providers/anthropic-progress.md`](providers/anthropic-progress.md)
[`providers-and-adapters.md`](providers-and-adapters.md)
[`providers/jev-decision.md`](providers/jev-decision.md)
[`providers/xai-grok.md`](providers/xai-grok.md)
[`adapters/registry.md`](adapters/registry.md)
[`gui-and-management-api.md`](gui-and-management-api.md)
[`provider-completion-diagnostic.md`](provider-completion-diagnostic.md)
[`dashboard-and-usage.md`](dashboard-and-usage.md)
[`fallback-policy.md`](fallback-policy.md)
[`clients/claude-desktop.md`](clients/claude-desktop.md)
[`clients/claude-desktop-model-visibility.md`](clients/claude-desktop-model-visibility.md)
[`clients/hermes.md`](clients/hermes.md)
[`ops/service-and-sidecars.md`](ops/service-and-sidecars.md) | +| `src/server/admitted-http-turn.ts` | [`data-planes/ollama-inbound.md`](data-planes/ollama-inbound.md) | | `src/server/advisor-admission-scope.ts` | [`advisor.md`](advisor.md) | | `src/server/audio-dictation.ts` | [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | | `src/server/audio-live.ts` | [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | @@ -397,6 +400,7 @@ A source area can be described by more than one doc, because these docs are orga | `src/server/index.ts` | [`adapters/compatibility-lab.md`](adapters/compatibility-lab.md) | | `src/server/index/link-management.ts` | [`remote-link.md`](remote-link.md) | | `src/server/index/live-sideband.ts` | [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | +| `src/server/index/ollama-routes.ts` | [`data-planes/ollama-inbound.md`](data-planes/ollama-inbound.md) | | `src/server/index/serve-options.ts` | [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | | `src/server/index/websocket-handler.ts` | [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | | `src/server/inference/advisor-diagnostics.ts` | [`advisor.md`](advisor.md) | @@ -408,6 +412,10 @@ A source area can be described by more than one doc, because these docs are orga | `src/server/management/link-routes.ts` | [`remote-link.md`](remote-link.md) | | `src/server/management/model-routes.ts` | [`pricing.md`](pricing.md) | | `src/server/management/quota-pool-routes.ts` | [`quota-pool.md`](quota-pool.md) | +| `src/server/native-final-log.ts` | [`data-planes/ollama-inbound.md`](data-planes/ollama-inbound.md) | +| `src/server/ollama-inbound.ts` | [`data-planes/ollama-inbound.md`](data-planes/ollama-inbound.md) | +| `src/server/ollama-native-paths.ts` | [`data-planes/ollama-inbound.md`](data-planes/ollama-inbound.md) | +| `src/server/ollama-route-policy.ts` | [`data-planes/ollama-inbound.md`](data-planes/ollama-inbound.md) | | `src/server/responses/` | [`data-planes/claude-tool-loading.md`](data-planes/claude-tool-loading.md) | | `src/server/responses/account-auto-pause-recovery.ts` | [`account-auto-pause.md`](account-auto-pause.md) | | `src/server/responses/adapter-delivery.ts` | [`transports/response-turn-membership.md`](transports/response-turn-membership.md)
[`transports/max-output-completion.md`](transports/max-output-completion.md) | diff --git a/structure/data-planes/inbound-compat.md b/structure/data-planes/inbound-compat.md index b00ba62b047..ab30b477255 100644 --- a/structure/data-planes/inbound-compat.md +++ b/structure/data-planes/inbound-compat.md @@ -8,7 +8,7 @@ retain their previous allowance. No disabled header clock detaches client cancel Thinking enablement is separate from strength: `src/responses/schema.ts` accepts the OCX `reasoning.enabled` boolean and `src/responses/parser.ts` retains it as `options.thinkingEnabled`, independently of `options.reasoning`. Chat `thinking.type` and Anthropic `thinking.type` preserve this choice through their inbound translators; the existing Anthropic disabled-effort sentinel remains for legacy destinations. `src/clients/reasoning-controls.ts` decodes effort-only client aliases for declared toggle-only models before strength caps run. Route fallback restores the original choice alongside effort in `src/server/effort-policy.ts`; a cleared strength list does not clear a thinking switch. Regression coverage lives in `tests/responses/responses-parser.test.ts`, `tests/responses/chat-inbound-reasoning-none.test.ts`, `tests/claude-integration/claude-inbound.test.ts`, and `tests/codex-integration/effort-policy.test.ts`. The names used for these paths (native, translated, legacy bridge) and the declared per-feature -dispositions are owned by [Protocol Paths](protocol-paths.md). +dispositions are owned by [Protocol Paths](protocol-paths.md). The Ollama-compatible `/api/*` routes are owned by [Ollama-Compatible Inbound](ollama-inbound.md). Native result continuations and function-result injection follow [the mode-specific result and control contract](../transports/streaming-health.md#experimental-native-function-result-injection); this surface does not infer upstream support or alter its defaults. diff --git a/structure/data-planes/ollama-inbound.md b/structure/data-planes/ollama-inbound.md new file mode 100644 index 00000000000..6a332aab1c4 --- /dev/null +++ b/structure/data-planes/ollama-inbound.md @@ -0,0 +1,89 @@ +# Ollama-Compatible Inbound + +Ollama clients can use configured provider routes through five native endpoints. The surface is a +translation onto the [Chat Completions inbound](inbound-compat.md) path; it never runs local models. + +`src/server/ollama-native-paths.ts` names five exact routes: `GET /api/version`, `GET /api/tags`, +`POST /api/show`, `POST /api/chat` and `POST /api/generate`. `src/server/index/ollama-routes.ts` +matches them in `serve-options.ts` before the management `/api/` catch-all, so every other `/api/*` +path still reaches management authentication. A wrong method gets a native 405 with `Allow`, never +the management or GUI fallback. OPTIONS on the five paths takes data-plane origin policy and CORS. +The routes are served only by the authenticated data-plane listener: the unauthenticated loopback +and hub-link allowlists do not list them, and `managementIngressRouteAllowed` in `src/server/index.ts` +denies them before its `/api/*` admission. The package-tree fence covers them like `/v1/*`. + +Admission is reused, not reimplemented. Version, tags and show take the model-discovery admission +`/v1/models` uses. Chat and generate take the Chat Completions admission: drain, data-plane key, +origin, caller session promotion, the idle-timeout override, active-turn, workflow and raised body +admission (`OLLAMA_JSON_BODY_ROUTES` in `inbound-body-admission.ts`). `src/server/admitted-http-turn.ts` +owns the admitted turn for every HTTP route; its optional `mapRefusal` reshapes drain, active-turn, +workflow and body refusals into `{ "error": string }` with their status and `Retry-After`, and its +`onAdmissionError` turns a cancelled body-admission wait into one logged 499. Unlogged drain and +active-turn refusals carry no `x-opencodex-request-id`; logged refusals and handler-owned requests do. + +The catalog is configured concrete provider/model routes, not local models. +`src/server/ollama-route-policy.ts` refuses synthetic fast/effort selectors and configured shadow +sources (400), and policy selectors, combos and transports that consume the caller's own +authorization (403), before any dispatch; tags and show list only what passes the same check and the +key's model scope. Show returns no file, digest, template or license facts. + +`src/protocols/codecs/ollama.ts` validates the native body (unknown fields and options, `think`, +`keep_alive`, non-JSON formats and remote images are 400s) and projects it to Chat; base64 images +become Chat `image_url` data URLs with the sniffed media type. `src/server/ollama-inbound.ts` calls +`handleChatCompletions` with a synthesized request carrying only the content type, caller session +and workflow identity headers (`session_id`, `session-id`, `thread-id`, `x-session-id`, +`x-codex-parent-thread-id`, so the workflow root's spend ceiling still applies) and the client +signal, linked to the same session lane; authorization, cookies and admission keys never cross the +hop. Native error bodies are a fixed message chosen by HTTP status (`ollamaInnerErrorMessage`); +upstream-authored error text is never forwarded. Response headers are generated, never copied: +`content-type`, `Retry-After` reformatted by `ollamaRetryAfter` as an integer of seconds (at most +3600) or dropped, `Allow` on 405, an `x-opencodex-local-refusal` constant looked up from the known +workflow refusal codes (anything else is dropped), plus CORS and `x-opencodex-request-id` from the +dispatcher. The package-tree fence answers these paths in the same native shape. Buffered and NDJSON output map Chat +finish `stop`, `tool_calls` and `length` to `done_reason`; content filtering, unknown finishes and a +missing finish are native errors without `done: true`. A stream emits its single `done: true` record +only after the Chat stream reached EOF and the inner path settled, so trailing usage is included and +a later error never follows a success terminal. +Success is the Chat layer's settled outcome, not a second judgment: the native Chat relay ends at +`[DONE]` for every Chat client. For an NDJSON request answered by a non-streaming JSON Chat +completion, the shared fallback stream (`jsonCompletionSse`) supplies `stop` for a missing finish, as +it does for ordinary Chat clients; an actual SSE stream that settles without a finish stays a native +error. A buffered request passes the raw JSON through, so a missing finish there is a native error. + +## Final request log + +`src/server/native-final-log.ts` owns the row for these requests. `interceptFinalRequestLog` in +`request-log.ts` turns the inner Chat path's final-log requests into a settlement signal; the native +handler commits once through `commitInterceptedFinalRequestLog` with the outer status, so a +conversion failure after an inner 200 is a 502 row while the physical attempt keeps its 200. The +coordinated write skips the client-close 5xx-to-499 rewrite and derives the attempt's own failure +attribution from attempt facts. If the inner path has not settled 100 ms after the outer outcome is +known, the row drops partial usage (so the send settles as unresolved), records +`observation_barrier_timeout`, and never reports success. Inner Chat runs with +`suppressProtocolTrace`, so a native row persists no Chat protocol identity (see +[Protocol Paths](protocol-paths.md#observed-trace)). +The commit also drops upstream-authored text (`upstreamError`, `upstreamErrorCode`, +`upstreamErrorType`, `upstreamRequestId`) from the row; status, derived codes and attribution stay. + +## Protocol trace + +A native ingress that translates into Chat (the Ollama-compatible routes in +`src/server/ollama-inbound.ts`) passes `suppressProtocolTrace`. `suppressProtocolTrace(logCtx)` puts +the context in a process-local WeakSet; every request-context mark writer (entry, blocked, reason, +shadow) and `protocolTraceForRequest` check it, and native Chat does not set `inboundProtocol`, so no +Chat identity is persisted for that row. Envelope creation and the representability check still +run. `tests/server/protocol-trace-suppression.test.ts` pins this. + +## Coverage + +Coverage: `tests/server/server-ollama-inbound.test.ts` (routes, admission, CORS, buffered and NDJSON +chat/generate, finish mapping, tools, images, refusals and row agreement), +`tests/server/server-ollama-inbound-lifecycle.test.ts` (dispatcher ownership, drain, timeout override, +zero-send selector refusals, cancellation, failover attempts on live and persisted rows, workflow +root token ceiling), `tests/server/server-ollama-inbound-errors.test.ts` (fixed error bodies; an +upstream echoing a prefixless provider key never reaches the body, headers or either log), +`tests/responses/responses-ollama-codec.test.ts`, `tests/server/server-ollama-route-policy.test.ts`, +`tests/server/server-native-final-log.test.ts`, `tests/server/admitted-http-turn.test.ts` and +`tests/server/protocol-trace-suppression.test.ts`. Listener denial is pinned in +`tests/server/loopback-listener-integration.test.ts` and `tests/clients/link-routes.test.ts`, and +fencing in `tests/ci-workflows/package-tree-integrity.test.ts`. diff --git a/structure/data-planes/protocol-paths.md b/structure/data-planes/protocol-paths.md index 277fbcc2d4b..3e31d8e4909 100644 --- a/structure/data-planes/protocol-paths.md +++ b/structure/data-planes/protocol-paths.md @@ -103,7 +103,7 @@ one. `/api/logs` spreads the entry and accepts `protocolMode` an unknown value matches nothing. The dashboard renders it with `gui/src/components/protocols/` (a row badge and a detail-dialog section) and filters by mode client-side in `gui/src/pages/logs-filter.ts`. `tests/responses/protocol-trace.test.ts` and -`tests/usage/request-log-protocol-trace.test.ts` pin derivation, persistence and the filter. +`tests/usage/request-log-protocol-trace.test.ts` pin derivation, persistence and the filter. A translating native ingress can suppress the trace: see [Ollama-Compatible Inbound](ollama-inbound.md#protocol-trace). ## Planner and preview diff --git a/structure/manifest.json b/structure/manifest.json index 741745dc1d7..1bad5e80d07 100644 --- a/structure/manifest.json +++ b/structure/manifest.json @@ -518,6 +518,21 @@ "scope": "Physical-adapter tool-loading projection, preserved catalogs, fallback exclusions and opt-in prerequisites.", "documents": ["src/claude/", "src/server/responses/"] }, + { + "path": "data-planes/ollama-inbound.md", + "tier": 3, + "title": "Ollama-Compatible Inbound", + "scope": "Ollama-shaped version/tags/show/chat/generate routes translated onto Chat Completions, their admission, native error shape and final request-log ownership.", + "documents": [ + "src/server/ollama-inbound.ts", + "src/server/ollama-native-paths.ts", + "src/server/ollama-route-policy.ts", + "src/server/native-final-log.ts", + "src/server/admitted-http-turn.ts", + "src/server/index/ollama-routes.ts", + "src/protocols/codecs/ollama.ts" + ] + }, { "path": "data-planes/chat-reasoning-details.md", "tier": 3, diff --git a/tests/ci-workflows/package-tree-integrity.test.ts b/tests/ci-workflows/package-tree-integrity.test.ts index c63b75cc746..d2e31c4af59 100644 --- a/tests/ci-workflows/package-tree-integrity.test.ts +++ b/tests/ci-workflows/package-tree-integrity.test.ts @@ -836,6 +836,16 @@ console.log(JSON.stringify({ calls })); }, }); })); + test("refuses the Ollama-compatible routes like /v1/* inference", () => runServerCase(async (server, signal) => { + for (const [path, method] of [["/api/version", "GET"], ["/api/tags", "GET"], ["/api/show", "POST"], ["/api/chat", "POST"], ["/api/generate", "POST"]] as const) { + const native = await fetch(new URL(path, server.url), { + method, signal, ...(method === "POST" ? { headers: { "content-type": "application/json" }, body: JSON.stringify({ model: "test/gpt-test", prompt: "hi" }) } : {}), + }); + expect({ path, status: native.status, retryAfter: native.headers.get("retry-after") }).toEqual({ path, status: 503, retryAfter: "5" }); + // Ollama clients read error as a string. + expect(await native.json()).toEqual({ error: expect.stringContaining("restart") }); + } + })); }); describe("sustained package replacement", () => { diff --git a/tests/clients/link-routes.test.ts b/tests/clients/link-routes.test.ts index 072bafb65e8..abcca8e8f15 100644 --- a/tests/clients/link-routes.test.ts +++ b/tests/clients/link-routes.test.ts @@ -22,6 +22,9 @@ describe("shared link route table", () => { { path: "/v1/opencodex/artifacts/a", method: "GET", expected: true }, { path: "/v1/unknown", method: "GET", expected: false }, { path: "/api/config", method: "GET", expected: false }, + // Ollama-compatible inference is served only on the authenticated data-plane listener. + { path: "/api/chat", method: "POST", expected: false }, + { path: "/api/tags", method: "GET", expected: false }, { path: "/v1/responses", method: "POST", expected: false, headers: { upgrade: "websocket" } }, ])("admits the same route in server and client listener", ({ path, method, expected, headers }) => { const req = request(path, method, headers); diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 91ca46d40b0..7d478bd98e4 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -921,6 +921,9 @@ "initial-selection-write-fence.test.ts": "providers", "injection-model-api.test.ts": "codex-integration", "inbound-body-admission.test.ts": "server", "inbound-body-budget.test.ts": "server", + "admitted-http-turn.test.ts": "server", "server-native-final-log.test.ts": "server", "server-ollama-route-policy.test.ts": "server", + "server-ollama-inbound.test.ts": "server", "server-ollama-inbound-lifecycle.test.ts": "server", "server-ollama-inbound-errors.test.ts": "server", + "protocol-trace-suppression.test.ts": "server", "responses-ollama-codec.test.ts": "responses", "config-concurrent-inbound-body.test.ts": "config", "inline-think-boundaries.test.ts": "adapters/openai", "input-admission.test.ts": "server", "install-scripts.test.ts": "ci-workflows", "installed-gate-drivers.test.ts": "ci-workflows", diff --git a/tests/lib/workflow-budget.test.ts b/tests/lib/workflow-budget.test.ts index 6a35e44e91b..8f4f28469fe 100644 --- a/tests/lib/workflow-budget.test.ts +++ b/tests/lib/workflow-budget.test.ts @@ -472,12 +472,13 @@ describe("a refusal an operator can read, name and clear (#4546)", () => { // pointless until the refusal was CORS-wrapped, because without an allow-origin a browser // cannot read an exposed header either. // src/server/index.ts is a facade now. The runAdmittedHttpTurn call sites live in the - // serve-options leaf while the CORS-wrapped refusal stayed in the composition root, so - // read both. Reading the facade alone would find no call site and the "more than one + // serve-options leaf and the CORS-wrapped refusal in admitted-http-turn.ts, so read all + // three. Reading the facade alone would find no call site and the "more than one // surface" assertion would pass on an empty match array. const source = [ await Bun.file(repoPath("src/server/index.ts")).text(), await Bun.file(repoPath("src/server/index/serve-options.ts")).text(), + await Bun.file(repoPath("src/server/admitted-http-turn.ts")).text(), ].join("\n"); const callSites = source.match(/return runAdmittedHttpTurn\(/g) ?? []; const threaded = source.match(/, \{ requestId, start, logCtx \}\);/g) ?? []; @@ -487,8 +488,8 @@ describe("a refusal an operator can read, name and clear (#4546)", () => { expect(callSites.length - threaded.length).toBe(1); // The admission refusal goes through the decision-carrying wrapper, which forwards the // denial's own scope and ceiling. Forwarding `reason` alone would answer a token-ceiling - // refusal with a 429 that names no ceiling. - expect(source).toContain("withCors(workflowDecisionRefusalResponse("); + // refusal with a 429 that names no ceiling. A native ingress may reshape it (map) but not drop it. + expect(source).toMatch(/withCors\((?:map\()?workflowDecisionRefusalResponse\(/); }); test("every refusal lands on the record with the counts that caused it", () => { diff --git a/tests/responses/responses-ollama-codec.test.ts b/tests/responses/responses-ollama-codec.test.ts new file mode 100644 index 00000000000..f107706f405 --- /dev/null +++ b/tests/responses/responses-ollama-codec.test.ts @@ -0,0 +1,109 @@ +import { describe, expect, test } from "bun:test"; +import { ollamaToChat, ollamaBufferedResponse, createOllamaStreamState, consumeOllamaChatChunk, ollamaStreamTerminal, OllamaCodecError } from "../../src/protocols/codecs/ollama"; + +const png = "iVBORw0KGgo="; +const schema = { type: "object", properties: { q: { type: "string", enum: ["a", "b"] } }, required: ["q"], additionalProperties: false }; + +describe("Ollama codec", () => { + test("projects chat, images, tools and matched results without changing schema", () => { + const result = ollamaToChat("chat", { model: "m", messages: [ + { role: "system", content: "rules" }, { role: "user", content: "look", images: [png] }, + { role: "assistant", content: "", tool_calls: [{ function: { name: "find", arguments: { q: "a" } } }] }, + { role: "tool", tool_name: "find", content: "result" }, + ], tools: [{ type: "function", function: { name: "find", description: "Find", parameters: schema } }], options: { temperature: 0.3, top_p: 0.8, num_predict: 10, stop: ["end"] }, format: "json" }); + expect(result).toEqual({ model: "m", stream: true, messages: [ + { role: "system", content: "rules" }, { role: "user", content: [{ type: "text", text: "look" }, { type: "image_url", image_url: { url: `data:image/png;base64,${png}` } }] }, + { role: "assistant", content: "", tool_calls: [{ id: "call_ollama_2_0", type: "function", function: { name: "find", arguments: '{"q":"a"}' } }] }, + { role: "tool", content: "result", tool_call_id: "call_ollama_2_0" }, + ], tools: [{ type: "function", function: { name: "find", description: "Find", parameters: schema } }], temperature: 0.3, top_p: 0.8, max_tokens: 10, stop: ["end"], response_format: { type: "json_object" } }); + }); + test("generate maps system, prompt, image and explicit stream", () => { + expect(ollamaToChat("generate", { model: "m", prompt: "hi", system: "s", images: [png], stream: false })).toEqual({ model: "m", stream: false, messages: [{ role: "system", content: "s" }, { role: "user", content: [{ type: "text", text: "hi" }, { type: "image_url", image_url: { url: `data:image/png;base64,${png}` } }] }] }); + }); + test("matches explicit IDs and rejects ambiguous or reused results", () => { + const calls = [{ function: { name: "f", arguments: {} } }, { function: { name: "f", arguments: {} } }]; + const messages = [{ role: "assistant", content: "", tool_calls: calls }, { role: "tool", content: "x", tool_call_id: "call_ollama_0_1" }, { role: "tool", content: "y", tool_name: "f" }]; + expect((ollamaToChat("chat", { model: "m", messages }).messages as any[]).slice(1).map(m => m.tool_call_id)).toEqual(["call_ollama_0_1", "call_ollama_0_0"]); + expect(() => ollamaToChat("chat", { model: "m", messages: [messages[0], messages[2]] })).toThrow(OllamaCodecError); + expect(() => ollamaToChat("chat", { model: "m", messages: [...messages, messages[1]] })).toThrow(OllamaCodecError); + }); + test("a replayed response tool call keeps its returned id through the result", () => { + const replay = [ + { role: "assistant", content: "", tool_calls: [{ id: "id1", function: { name: "f", arguments: { x: 1 } } }, { id: "id2", function: { name: "f", arguments: {} } }] }, + { role: "tool", content: "x", tool_call_id: "id2" }, + { role: "tool", content: "y", tool_name: "f" }, + ]; + const out = ollamaToChat("chat", { model: "m", messages: replay }).messages as { tool_calls?: { id: string }[]; tool_call_id?: string }[]; + expect(out[0]!.tool_calls!.map(call => call.id)).toEqual(["id1", "id2"]); + expect(out.slice(1).map(m => m.tool_call_id)).toEqual(["id2", "id1"]); + const duplicate = [{ role: "assistant", content: "", tool_calls: [{ id: "same", function: { name: "f", arguments: {} } }, { id: "same", function: { name: "g", arguments: {} } }] }]; + expect(() => ollamaToChat("chat", { model: "m", messages: duplicate })).toThrow(OllamaCodecError); + expect(() => ollamaToChat("chat", { model: "m", messages: [{ role: "assistant", content: "", tool_calls: [{ id: 7, function: { name: "f", arguments: {} } }] }] })).toThrow(OllamaCodecError); + }); + test("rejects unsupported and malformed shapes with bounded errors", () => { + for (const body of [ + { model: "m", prompt: "x", suffix: "y" }, { model: "m", prompt: "x", think: false }, + { model: "m", prompt: "x", options: { top_k: 3 } }, { model: "m", prompt: "x", format: {} }, + { model: "m", prompt: "x", images: ["https://example.com/x"] }, { model: "m", prompt: "x", images: ["aGVsbG8="] }, + { model: "m", prompt: "x", images: ["iVBORw0KGgo=garbage"] }, { model: "m", prompt: 5 }, + ]) { + try { ollamaToChat("generate", body); throw new Error("accepted"); } catch (e) { expect(e).toBeInstanceOf(OllamaCodecError); expect((e as OllamaCodecError).status).toBe(400); expect((e as OllamaCodecError).message.length).toBeLessThan(200); } + } + }); + test("buffered responses preserve calls and usage and reject bad finishes", () => { + const base = { choices: [{ message: { content: "hello", tool_calls: [{ id: "id1", type: "function", function: { name: "f", arguments: '{"x":1}' } }] }, finish_reason: "tool_calls" }], usage: { prompt_tokens: 4, completion_tokens: 2 } }; + expect(ollamaBufferedResponse("chat", "m", base, "time")).toEqual({ model: "m", created_at: "time", message: { role: "assistant", content: "hello", tool_calls: [{ id: "id1", function: { name: "f", arguments: { x: 1 } } }] }, done: true, done_reason: "tool_calls", prompt_eval_count: 4, eval_count: 2 }); + expect(ollamaBufferedResponse("generate", "m", { choices: [{ message: { content: "hi" }, finish_reason: "length" }] }, "time")).toEqual({ model: "m", created_at: "time", response: "hi", done: true, done_reason: "length" }); + for (const finish_reason of ["content_filter", "other", null]) expect(ollamaBufferedResponse("chat", "m", { choices: [{ message: { content: "x" }, finish_reason }] }, "time")).toEqual({ error: expect.any(String) }); + }); + test("stream retains finish and latest usage without producing a success until settlement", () => { + const state = createOllamaStreamState("chat", "m", "time"); + expect(consumeOllamaChatChunk(state, { choices: [{ delta: { content: "hi" }, finish_reason: null }] })).toEqual([{ model: "m", created_at: "time", message: { role: "assistant", content: "hi" }, done: false }]); + expect(consumeOllamaChatChunk(state, { choices: [{ delta: {}, finish_reason: "stop" }] })).toEqual([]); + expect(consumeOllamaChatChunk(state, { choices: [], usage: { prompt_tokens: 3, completion_tokens: 1 } })).toEqual([]); + expect(ollamaStreamTerminal(state)).toEqual({ model: "m", created_at: "time", message: { role: "assistant", content: "" }, done: true, done_reason: "stop", prompt_eval_count: 3, eval_count: 1 }); + expect(ollamaStreamTerminal(createOllamaStreamState("generate", "m", "time"))).toEqual({ error: expect.any(String) }); + }); + test("streamed tool fragments retain identity and object arguments", () => { + const state = createOllamaStreamState("chat", "m", "time"); + consumeOllamaChatChunk(state, { choices: [{ delta: { tool_calls: [{ index: 0, id: "abc", function: { name: "f", arguments: '{"x":' } }] }, finish_reason: null }] }); + expect(consumeOllamaChatChunk(state, { choices: [{ delta: { tool_calls: [{ index: 0, function: { arguments: '1}' } }] }, finish_reason: "tool_calls" }] })).toEqual([{ model: "m", created_at: "time", message: { role: "assistant", content: "", tool_calls: [{ id: "abc", function: { name: "f", arguments: { x: 1 } } }] }, done: false }]); + }); + test("accepts supported image signatures with exact encoded bytes", () => { + for (const [data, mime] of [["/9j/AA==", "jpeg"], ["R0lGODlh", "gif"], ["UklGRgAAAABXRUJQ", "webp"]]) { + expect(ollamaToChat("generate", { model: "m", prompt: "", images: [data] })).toMatchObject({ messages: [{ content: [{ type: "text", text: "" }, { image_url: { url: `data:image/${mime};base64,${data}` } }] }] }); + } + }); + test("rejects extra message, call and tool fields and malformed options", () => { + for (const body of [ + { model: "m", messages: [{ role: "user", content: "x", audio: [] }] }, + { model: "m", messages: [{ role: "system", content: "x", images: [png] }] }, + { model: "m", messages: [{ role: "assistant", content: "", tool_calls: [{ function: { name: "f", arguments: "{}" } }] }] }, + { model: "m", messages: [{ role: "tool", content: "x", tool_name: "f" }] }, + { model: "m", messages: [], tools: [{ type: "function", function: { name: "f", parameters: schema, strict: true } }] }, + { model: "m", messages: [], options: { num_predict: -1 } }, + { model: "m", messages: [], options: { stop: "x" } }, + { model: "m", messages: [], stream: "false" }, + ]) expect(() => ollamaToChat("chat", body)).toThrow(OllamaCodecError); + expect(() => ollamaToChat("generate", { model: "m", prompt: "x", images: ["/9j/AB=="] })).toThrow(OllamaCodecError); + }); + test("stream terminal maps finishes and keeps failures distinct", () => { + for (const reason of ["stop", "length", "tool_calls", "content_filter", "unknown"]) { + const state = createOllamaStreamState("generate", "m", "time"); + consumeOllamaChatChunk(state, { choices: [{ delta: {}, finish_reason: reason }] }); + const terminal = ollamaStreamTerminal(state); + if (["stop", "length", "tool_calls"].includes(reason)) expect(terminal).toMatchObject({ done: true, done_reason: reason }); + else expect(terminal).toEqual({ error: expect.any(String) }); + expect(() => consumeOllamaChatChunk(state, { choices: [{ delta: { content: "late" }, finish_reason: null }] })).toThrow(); + expect(() => consumeOllamaChatChunk(state, { error: { message: "failure" }, choices: [] })).toThrow(); + } + }); + test("stable fallback IDs and invalid tool argument streams", () => { + const state = createOllamaStreamState("chat", "m", "time"); + const records = consumeOllamaChatChunk(state, { choices: [{ delta: { tool_calls: [{ index: 2, function: { name: "f", arguments: "{}" } }] }, finish_reason: "tool_calls" }] }); + expect(records[0]).toMatchObject({ message: { tool_calls: [{ id: "call_ollama_response_2" }] } }); + const bad = createOllamaStreamState("chat", "m", "time"); + expect(() => consumeOllamaChatChunk(bad, { choices: [{ delta: { tool_calls: [{ index: 0, function: { name: "f", arguments: "{" } }] }, finish_reason: "tool_calls" }] })).toThrow(); + expect(ollamaStreamTerminal(bad)).toEqual({ error: expect.any(String) }); + }); +}); diff --git a/tests/server/admitted-http-turn.test.ts b/tests/server/admitted-http-turn.test.ts new file mode 100644 index 00000000000..b0fd1fd0a4c --- /dev/null +++ b/tests/server/admitted-http-turn.test.ts @@ -0,0 +1,152 @@ +import { test } from "bun:test"; +import assert from "node:assert/strict"; +import { createAdmittedHttpTurn } from "../../src/server/admitted-http-turn"; +import { getDefaultConfig } from "../../src/config"; +import { MAX_CONFIGURABLE_INBOUND_BODY_BYTES } from "../../src/server/request-decompress"; +import { inboundBodyBudget, configureInboundBodyBudget, MAX_QUEUED_INBOUND_BODIES } from "../../src/server/inbound-body-budget"; +import { clearRequestLogsForTests, getRequestLogEntries } from "../../src/server/request-log"; +import { getActiveTurnCount, MAX_ACTIVE_TURNS, tryAdmitTurn } from "../../src/server/lifecycle"; +import { admitWorkflowTurn, resetWorkflowBudgetsForTest } from "../../src/lib/workflow-budget"; + +const limit = MAX_CONFIGURABLE_INBOUND_BODY_BYTES; +const policy = getDefaultConfig(); +const request = (signal?: AbortSignal) => new Request("http://localhost/v1/responses", { + method: "POST", body: "{}", signal, +}); +const mapRefusal = (response: Response) => new Response("native", { status: response.status, headers: response.headers }); +const busy = () => new Response("busy", { status: 503, headers: { "Retry-After": "1" } }); +const log = (id: string, onLogged: () => void) => ({ + requestId: id, start: Date.now(), logCtx: { model: "unknown", provider: "unknown" }, onLogged, +}); +const rows = (id: string) => getRequestLogEntries().filter(row => row.requestId === id); +const mapWithLoggedId = (id: string, logged: () => number) => (response: Response) => { + const mapped = mapRefusal(response); + if (logged()) mapped.headers.set("x-fixture-response-id", id); + return mapped; +}; + +test("admission cancellation owns the row and releases the turn on an immediate grant race", async () => { + clearRequestLogsForTests(); + inboundBodyBudget.setCapacity(limit); + const abort = new AbortController(); + let logged = 0; + let worked = false; + const before = getActiveTurnCount(); + const run = createAdmittedHttpTurn(() => limit, busy); + const pending = run(request(abort.signal), policy, async () => { worked = true; return new Response(); }, { + requestId: "native-cancel", start: Date.now(), logCtx: { model: "unknown", provider: "unknown" }, + onLogged: () => { logged++; }, + }, { mapRefusal: mapWithLoggedId("native-cancel", () => logged), onAdmissionError: () => new Response("cancelled", { status: 499 }) }); + abort.abort(new Error("client cancelled")); + const response = await pending; + assert.equal(response.status, 499); + assert.equal(await response.text(), "native"); + assert.equal(response.headers.get("x-fixture-response-id"), "native-cancel"); + assert.ok(response.headers.has("access-control-allow-origin")); + assert.equal(worked, false); + assert.equal(logged, 1); + assert.equal(getRequestLogEntries().filter(row => row.requestId === "native-cancel").length, 1); + assert.equal(getActiveTurnCount(), before); + assert.equal(inboundBodyBudget.snapshot().activeLeases, 0); + configureInboundBodyBudget(); +}); + +test("active-turn refusal maps without a row or callback, then recovers", async () => { + clearRequestLogsForTests(); + const leases = Array.from({ length: MAX_ACTIVE_TURNS }, () => tryAdmitTurn()); + assert.ok(leases.every(Boolean)); + let logged = 0; + const run = createAdmittedHttpTurn(() => undefined, busy); + try { + const response = await run(request(), policy, async () => new Response("work"), log("active", () => logged++), { mapRefusal: mapWithLoggedId("active", () => logged) }); + assert.equal(response.status, 503); + assert.equal(response.headers.get("retry-after"), "1"); + assert.equal(await response.text(), "native"); + assert.equal(response.headers.get("x-fixture-response-id"), null); + assert.ok(response.headers.has("access-control-allow-origin")); + assert.equal(logged, 0); + assert.equal(rows("active").length, 0); + } finally { leases.forEach(lease => lease?.release()); } + assert.equal(await (await run(request(), policy, async () => new Response("recovered"))).text(), "recovered"); +}); + +test("workflow refusal maps after its single row and recovers", async () => { + clearRequestLogsForTests(); + resetWorkflowBudgetsForTest(); + const leases = Array.from({ length: 8 }, () => admitWorkflowTurn("native-root", "interactive")); + assert.ok(leases.every(decision => decision?.admitted)); + let logged = 0; + const run = createAdmittedHttpTurn(() => undefined, busy); + const req = () => new Request("http://localhost/v1/responses", { method: "POST", body: "{}", headers: { "x-codex-parent-thread-id": "native-root" } }); + try { + const response = await run(req(), policy, async () => new Response("work"), log("workflow", () => logged++), { mapRefusal: mapWithLoggedId("workflow", () => logged) }); + assert.equal(response.status, 429); + assert.equal(await response.text(), "native"); + assert.equal(response.headers.get("x-fixture-response-id"), "workflow"); + assert.ok(response.headers.has("access-control-allow-origin")); + assert.equal(logged, 1); + assert.equal(rows("workflow").length, 1); + } finally { + for (const decision of leases) if (decision?.admitted) decision.lease.release(); + resetWorkflowBudgetsForTest(); + } + assert.equal(await (await run(req(), policy, async () => new Response("recovered"))).text(), "recovered"); +}); + +test("body refusal maps after its row, preserves retry advice and recovers", async () => { + clearRequestLogsForTests(); + inboundBodyBudget.setCapacity(limit); + const holder = await inboundBodyBudget.acquire(limit, new AbortController().signal); + const abort = new AbortController(); + const waiters = Array.from({ length: MAX_QUEUED_INBOUND_BODIES }, () => inboundBodyBudget.acquire(limit, abort.signal).catch(() => null)); + let logged = 0; + const run = createAdmittedHttpTurn(() => limit, busy); + try { + const response = await run(request(), policy, async () => new Response("work"), log("body", () => logged++), { mapRefusal: mapWithLoggedId("body", () => logged) }); + assert.equal(response.status, 503); + assert.equal(response.headers.get("retry-after"), "1"); + assert.equal(await response.text(), "native"); + assert.equal(response.headers.get("x-fixture-response-id"), "body"); + assert.ok(response.headers.has("access-control-allow-origin")); + assert.equal(logged, 1); + assert.equal(rows("body").length, 1); + } finally { + abort.abort(); + await Promise.all(waiters); + holder?.release(); + } + assert.equal(await (await run(request(), policy, async () => new Response("recovered"))).text(), "recovered"); + configureInboundBodyBudget(); +}); + +test("queued cancellation logs once, releases the turn, and unrelated admission errors propagate", async () => { + clearRequestLogsForTests(); + inboundBodyBudget.setCapacity(limit); + const holder = await inboundBodyBudget.acquire(limit, new AbortController().signal); + const abort = new AbortController(); + const before = getActiveTurnCount(); + let logged = 0; + const run = createAdmittedHttpTurn(() => limit, busy); + try { + const pending = run(request(abort.signal), policy, async () => new Response("work"), log("queued", () => logged++), { + mapRefusal, onAdmissionError: () => new Response("cancel", { status: 499 }), + }); + assert.equal(inboundBodyBudget.snapshot().queuedRequests, 1); + abort.abort(new Error("cancelled")); + const response = await pending; + assert.equal(response.status, 499); + assert.equal(await response.text(), "native"); + assert.equal(logged, 1); + assert.equal(rows("queued").length, 1); + assert.equal(getActiveTurnCount(), before); + assert.equal(inboundBodyBudget.snapshot().queuedRequests, 0); + } finally { holder?.release(); } + inboundBodyBudget.setCapacity(limit - 1); + await assert.rejects(run(request(), policy, async () => new Response(), log("error", () => logged++), { + mapRefusal, onAdmissionError: () => new Response(null, { status: 499 }), + }), RangeError); + assert.equal(rows("error").length, 0); + assert.equal(logged, 1); + assert.equal(getActiveTurnCount(), before); + configureInboundBodyBudget(); +}); diff --git a/tests/server/inbound-body-admission.test.ts b/tests/server/inbound-body-admission.test.ts index 2e42acef4ee..ffe4096ec88 100644 --- a/tests/server/inbound-body-admission.test.ts +++ b/tests/server/inbound-body-admission.test.ts @@ -21,6 +21,7 @@ import { UNGATED_LOOPBACK_ROUTES, } from "../../src/server/inbound-body-admission"; import { configureInboundBodyBudget, createInboundBodyBudget, inboundBodyBudget } from "../../src/server/inbound-body-budget"; +import { OLLAMA_JSON_BODY_ROUTES } from "../../src/server/ollama-native-paths"; import { drainAndRemoveFixtureRoots } from "../helpers/fixture-teardown"; import { saturateInboundBodyBudget } from "../helpers/inbound-body-budget"; import { installIsolatedCodexHome, type IsolatedCodexHome } from "../helpers/isolated-codex-home"; @@ -38,7 +39,7 @@ function fixtureAdmission(...args: Parameters void; @@ -815,6 +816,12 @@ describe("raised inbound body admission at the real HTTP boundary", () => { }); assert.equal(response.status, 503, path); assert.equal(response.headers.get("retry-after"), "1", path); + if (OLLAMA_JSON_BODY_ROUTES.has(path)) { + // Native clients get their own error shape; the refusal still owns one logged row. + assert.deepEqual(await response.json(), { error: "server temporarily unavailable; retry later" }, path); + assert.match(response.headers.get("x-opencodex-request-id") ?? "", /^ocx-/, path); + continue; + } const payload = await response.json() as { type?: string; error: { type: string; code: string } }; assert.equal(payload.error.code, "server_busy", path); assert.equal(payload.error.type, path.startsWith("/v1/messages") ? "overloaded_error" : "server_error", path); diff --git a/tests/server/loopback-listener-integration.test.ts b/tests/server/loopback-listener-integration.test.ts index 5cd0dd476ea..a1f2d9f13a5 100644 --- a/tests/server/loopback-listener-integration.test.ts +++ b/tests/server/loopback-listener-integration.test.ts @@ -239,6 +239,10 @@ describe("hub management ingress", () => { { path: "/readyz" }, { path: "/v1/responses", headers: { Connection: "Upgrade", Upgrade: "websocket" } }, { path: "/missing-static.js" }, + // Ollama-compatible paths live under /api/ but are data plane, never management ingress. + { path: "/api/version" }, + { path: "/api/tags" }, + { path: "/api/chat" }, ]; for (const entry of denied) { const response = await fetch(`${base}${entry.path}`, { headers: entry.headers }); @@ -376,6 +380,10 @@ describe("unauthenticated loopback listener", () => { { method: "GET", path: "/v1/alpha/search" }, { method: "GET", path: "/v1/images/generations" }, { method: "GET", path: "/v1/images/edits" }, + // Ollama-compatible inference stays on the authenticated listener. + { method: "POST", path: "/api/chat", body: "{}" }, + { method: "POST", path: "/api/generate", body: "{}" }, + { method: "GET", path: "/api/tags" }, ]; for (const { method, path, body } of denied) { const res = await fetch(`${base}${path}`, { diff --git a/tests/server/protocol-trace-suppression.test.ts b/tests/server/protocol-trace-suppression.test.ts new file mode 100644 index 00000000000..0997358f370 --- /dev/null +++ b/tests/server/protocol-trace-suppression.test.ts @@ -0,0 +1,108 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { addProtocolEntryReason, markAttemptProtocolPath, markProtocolBlocked, markProtocolEntry, + markProtocolShadowPlanInput, protocolMarkFeatures, protocolTraceForRequest, protocolTraceSuppressed, + suppressProtocolTrace } from "../../src/protocols/trace"; +import type { ProtocolPlanInput } from "../../src/protocols/plan"; +import { handleChatCompletions } from "../../src/server/chat-completions"; +import { getRequestLogEntries } from "../../src/server/request-log"; +import type { OcxConfig } from "../../src/types"; +import { acquireOwnedSpendHome } from "../helpers/owned-spend-home"; + +let server: ReturnType | undefined; +let releaseSpend: (() => void) | undefined; +let sends = 0; + +afterEach(async () => { + releaseSpend?.(); + releaseSpend = undefined; + await server?.stop(true); + server = undefined; +}); + +function config(adapter: "openai-chat" | "openai-responses", combo = false): OcxConfig { + sends = 0; + server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(req) { + sends++; + await req.text(); + return Response.json({ id: "chatcmpl-fixture", object: "chat.completion", model: "model", + choices: [{ index: 0, message: { role: "assistant", content: "ok" }, finish_reason: "stop" }], + usage: { prompt_tokens: 2, completion_tokens: 1, total_tokens: 3 } }); + } }); + releaseSpend = acquireOwnedSpendHome(); + return { port: 0, defaultProvider: "fixture", providers: { fixture: { + adapter, baseUrl: `http://127.0.0.1:${server.port}/v1`, authMode: "key", apiKey: "fixture-key", + allowPrivateNetwork: true, models: ["model"], + } }, protocols: { unrepresentable: "reject", rollout: { nativeChatCombos: true, shadowPlan: true } }, + ...(combo ? { combos: { pair: { strategy: "failover", targets: [{ provider: "fixture", model: "model" }] } } } : {}), + } as OcxConfig; +} + +async function send(cfg: OcxConfig, body: Record, suppressed: boolean) { + const requestId = `suppression-${crypto.randomUUID()}`; + const ctx: { model: string; provider: string; inboundProtocol?: "responses" | "chat" | "messages" } = + { model: "", provider: "", inboundProtocol: "responses" }; + const response = await handleChatCompletions(new Request("http://localhost/v1/chat/completions", { + method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), + }), cfg, ctx, { requestId, start: Date.now(), suppressProtocolTrace: suppressed }); + const text = await response.text(); + const rows = getRequestLogEntries().filter(row => row.requestId === requestId); + expect(rows).toHaveLength(1); + return { response, text, ctx, row: rows[0]! }; +} + +describe("protocol trace suppression", () => { + test("suppression clears prior marks and ignores every later request writer and attempt", () => { + const ctx = { inboundProtocol: "responses" as const }; + const attempt = { ordinal: 1, adapter: "openai-chat" }; + markProtocolEntry(ctx, { inbound: "chat", lane: "native", features: ["request.tools"] }); + suppressProtocolTrace(ctx); + expect(protocolTraceSuppressed(ctx)).toBe(true); + let scanned = false; + markProtocolEntry(ctx, { inbound: "chat", lane: "bridge", features: () => { scanned = true; return []; } }); + addProtocolEntryReason(ctx, "not-migrated"); + markProtocolShadowPlanInput(ctx, {} as ProtocolPlanInput); + markProtocolBlocked(ctx, { inbound: "chat", reasonCodes: ["feature-unrepresentable"] }); + markAttemptProtocolPath(attempt, { mode: "translated", requestPath: ["chat", "ir", "other"] }); + expect(scanned).toBe(false); + expect(protocolMarkFeatures(ctx)).toBeUndefined(); + expect(protocolTraceForRequest(ctx, [attempt])).toBeUndefined(); + expect(protocolTraceForRequest({ inboundProtocol: "responses" }, [attempt])).toBeDefined(); + }); + + for (const combo of [false, true]) test(`native ${combo ? "combo" : "direct"} success preserves the original inbound protocol`, async () => { + const cfg = config("openai-chat", combo); + const body = { model: combo ? "combo/pair" : "fixture/model", messages: [{ role: "user", content: "hi" }] }; + const result = await send(cfg, body, true); + expect(result.response.status).toBe(200); + expect(sends).toBe(1); + expect(result.ctx.inboundProtocol).toBe("responses"); + expect(result.row.inboundProtocol).toBe("responses"); + expect(result.row.protocolTrace).toBeUndefined(); + const ordinary = await send(cfg, body, false); + expect(ordinary.response.status).toBe(200); + if (!combo) expect(ordinary.ctx.inboundProtocol).toBe("chat"); + expect(ordinary.row.protocolTrace).toMatchObject({ inbound: "chat", mode: "native" }); + }); + + test("representability rejection still blocks the send with no trace", async () => { + const cfg = config("openai-responses"); + const body = { model: "fixture/model", n: 2, messages: [{ role: "user", content: "hi" }] }; + const result = await send(cfg, body, true); + expect(result.response.status).toBe(400); + expect(JSON.parse(result.text)).toMatchObject({ error: { code: "unsupported_feature" } }); + expect(sends).toBe(0); + expect(result.row.protocolTrace).toBeUndefined(); + const ordinary = await send(cfg, body, false); + expect(ordinary.response.status).toBe(400); + expect(ordinary.row.protocolTrace).toMatchObject({ inbound: "chat", mode: "blocked" }); + expect(sends).toBe(0); + }); + + test("parser refusal retains its error without producing a trace", async () => { + const cfg = config("openai-responses"); + const result = await send(cfg, { model: "fixture/model", messages: [{ role: "tool", content: "missing id" }] }, true); + expect(result.response.status).toBe(400); + expect(sends).toBe(0); + expect(result.row.protocolTrace).toBeUndefined(); + }); +}); diff --git a/tests/server/server-native-final-log.test.ts b/tests/server/server-native-final-log.test.ts new file mode 100644 index 00000000000..810113224a2 --- /dev/null +++ b/tests/server/server-native-final-log.test.ts @@ -0,0 +1,94 @@ +import { describe, expect, test } from "bun:test"; +import { + addFinalRequestLog, + beginRequestAttempt, + noteAttemptSend, + type RequestLogContext, + type RequestLogEntry, +} from "../../src/server/request-log"; +import { createNativeFinalLog, NATIVE_FINAL_LOG_CUTOFF_CODE } from "../../src/server/native-final-log"; + +function context(): RequestLogContext { + const attempt = beginRequestAttempt(1, "fixture", "model", "openai-chat"); + noteAttemptSend(attempt, undefined); + return { + model: "model", provider: "fixture", providerAdapter: "openai-chat", + attempts: [attempt], activeAttempt: attempt, usage: { inputTokens: 12, outputTokens: 3 }, + }; +} + +describe("native final request log", () => { + test("a conversion failure after an upstream 200 keeps the attempt's success", async () => { + const logCtx = context(); + const rows: RequestLogEntry[] = []; + const owner = createNativeFinalLog("conversion", 1, logCtx, { addLog: row => rows.push(row) }); + addFinalRequestLog("conversion", 1, logCtx, 200, { closeReason: "non_stream" }); + expect(rows).toHaveLength(0); + expect(await owner.waitForInner()).toBe(true); + expect(owner.commit({ status: 502, terminalStatus: "failed", closeReason: "non_stream" })).toBe(true); + addFinalRequestLog("conversion", 1, logCtx, 499, { closeReason: "client_cancel" }); + expect(owner.commit({ status: 200, closeReason: "non_stream" })).toBe(false); + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ status: 502, terminalStatus: "failed", usageStatus: "reported" }); + expect(rows[0]!.failureStage).toBeDefined(); + const attempt = rows[0]!.attempts![0]!; + expect(attempt.status).toBe(200); + expect(attempt.errorCode).toBeUndefined(); + expect(attempt.failureStage).toBeUndefined(); + expect(attempt.failureCause).toBeUndefined(); + }); + + test("a client cancel after inner success is a 499 row over a 200 attempt", async () => { + const logCtx = context(); + const rows: RequestLogEntry[] = []; + const owner = createNativeFinalLog("cancel", 1, logCtx, { addLog: row => rows.push(row) }); + addFinalRequestLog("cancel", 1, logCtx, 200, { terminalStatus: "completed", closeReason: "terminal" }); + await owner.waitForInner(); + owner.commit({ status: 499, closeReason: "client_cancel" }); + expect(rows[0]).toMatchObject({ status: 499, closeReason: "client_cancel" }); + expect(rows[0]!.attempts![0]!.status).toBe(200); + }); + + test("the outer status is authoritative over client-close-like inner text", async () => { + const logCtx = { ...context(), upstreamError: "client closed request" }; + const rows: RequestLogEntry[] = []; + const owner = createNativeFinalLog("outer", 1, logCtx, { addLog: row => rows.push(row) }); + addFinalRequestLog("outer", 1, logCtx, 502, { terminalStatus: "failed", closeReason: "terminal" }); + await owner.waitForInner(); + owner.commit({ status: 502, terminalStatus: "failed", closeReason: "terminal" }); + expect(rows[0]).toMatchObject({ status: 502, closeReason: "terminal" }); + }); + + test("a missing inner settlement cuts off: no partial usage, unresolved spend, never success", async () => { + const logCtx = { ...context(), usage: { inputTokens: 12, outputTokens: 0 }, usageLogInputTokens: 40 }; + const settled: unknown[] = []; + logCtx.spendTracker = { settle: (usage: unknown) => settled.push(usage) } as unknown as RequestLogContext["spendTracker"]; + const rows: RequestLogEntry[] = []; + const owner = createNativeFinalLog("cutoff", 1, logCtx, { fallbackMs: 5, addLog: row => rows.push(row) }); + const started = Date.now(); + expect(await owner.waitForInner()).toBe(false); + expect(Date.now() - started).toBeLessThan(1_000); + owner.commit({ status: 200, terminalStatus: "completed", closeReason: "terminal" }); + expect(rows[0]).toMatchObject({ status: 502, terminalStatus: "failed", usageStatus: "unreported", errorCode: NATIVE_FINAL_LOG_CUTOFF_CODE }); + expect(rows[0]!.usage).toBeUndefined(); + expect(settled).toEqual([undefined]); + addFinalRequestLog("cutoff", 1, logCtx, 200, { closeReason: "terminal" }); + expect(rows).toHaveLength(1); + }); + + test("an inner settlement inside the fallback window wakes the wait", async () => { + const logCtx = context(); + const owner = createNativeFinalLog("late", 1, logCtx, { fallbackMs: 10_000, addLog: () => {} }); + const waiting = owner.waitForInner(); + setTimeout(() => addFinalRequestLog("late", 1, logCtx, 200, { closeReason: "terminal" }), 1); + expect(await waiting).toBe(true); + }); + + test("ordinary request logging is unchanged without an owner", () => { + const rows: RequestLogEntry[] = []; + const logCtx = { ...context(), upstreamError: "client closed request" }; + addFinalRequestLog("ordinary", 1, logCtx, 502, { closeReason: "terminal" }, row => rows.push(row)); + expect(rows[0]).toMatchObject({ status: 499, closeReason: "client_cancel" }); + expect(rows[0]!.attempts![0]!.status).toBe(499); + }); +}); diff --git a/tests/server/server-ollama-inbound-errors.test.ts b/tests/server/server-ollama-inbound-errors.test.ts new file mode 100644 index 00000000000..f90cb6de33b --- /dev/null +++ b/tests/server/server-ollama-inbound-errors.test.ts @@ -0,0 +1,172 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test"; +import { existsSync, mkdtempSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { saveConfig } from "../../src/config"; +import { startServer } from "../../src/server"; +import { getRequestLogEntries } from "../../src/server/request-log"; +import { OLLAMA_MAX_RETRY_AFTER_SECONDS, ollamaRetryAfter, toOllamaRefusal } from "../../src/server/ollama-inbound"; +import { workflowDenialSummary, type WorkflowDenial } from "../../src/lib/workflow-budget"; +import { workflowRefusalResponse } from "../../src/server/workflow-refusal"; +import type { OcxConfig } from "../../src/types"; +import { usageLogPath } from "../../src/usage/log"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +// A provider key with no recognizable prefix: pattern-based redaction cannot spot it. +const PROVIDER_KEY = "zq7Vb2LmN4pX9tR1sK8wD3fH6jY0cA5e"; +// All digits, so a Retry-After parser accepts it as a delay in seconds. +const NUMERIC_KEY = "73915028461739205817"; +const saved = process.env.OPENCODEX_HOME; +let home = ""; +let mode: "status400" | "status401" | "status500" | "frame" | "retryAfter429" | "retryAfter400" = "status400"; +let upstream: ReturnType; + +beforeAll(() => { + home = mkdtempSync(join(tmpdir(), "ocx-ollama-errors-")); + process.env.OPENCODEX_HOME = home; + upstream = Bun.serve({ port: 0, async fetch(req) { + await req.json(); + // The upstream echoes the credential it received, as some gateways do in error text. + const echoed = (req.headers.get("authorization") ?? "").replace(/^Bearer /, ""); + const error = { message: "invalid key " + echoed, type: "invalid_request_error", code: echoed, param: echoed }; + if (mode === "frame") { + const frames = [ + "data: " + JSON.stringify({ id: "c", object: "chat.completion.chunk", created: 1, model: "m1", choices: [{ index: 0, delta: { role: "assistant", content: "partial" } }] }) + "\n\n", + "data: " + JSON.stringify({ error }) + "\n\n", + ]; + return new Response(frames.join(""), { headers: { "content-type": "text/event-stream" } }); + } + if (mode === "retryAfter429" || mode === "retryAfter400") { + return Response.json({ error: { message: "slow down" } }, { status: mode === "retryAfter429" ? 429 : 400, headers: { "retry-after": echoed } }); + } + const status = mode === "status401" ? 401 : mode === "status500" ? 500 : 400; + return Response.json({ error }, { status, headers: { "x-upstream-echo": echoed } }); + } }); +}); +afterAll(() => { + upstream.stop(true); + if (saved === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = saved; + if (home) removeTreeWithRetry(home); +}); +function saveProvider(apiKey: string) { + saveConfig({ + port: 0, defaultProvider: "fx", + providers: { fx: { adapter: "openai-chat", baseUrl: upstream.url.origin + "/v1", authMode: "key", apiKey, allowPrivateNetwork: true, models: ["m1"] } }, + } as unknown as OcxConfig); +} +beforeEach(() => saveProvider(PROVIDER_KEY)); + +async function exchange(path: string, body: Record) { + const server = startServer(0); + const earlier = new Set(getRequestLogEntries().map(entry => entry.requestId)); + try { + const res = await fetch(new URL(path, server.url), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + const text = await res.text(); + const headers = JSON.stringify([...res.headers.entries()]); + await Bun.sleep(150); + const rows = getRequestLogEntries().filter(entry => !earlier.has(entry.requestId)); + return { status: res.status, text, headers, rows }; + } finally { await server.stop(true); } +} + +describe("Ollama error bodies never carry upstream text", () => { + for (const path of ["/api/chat", "/api/generate"] as const) { + for (const stream of [false, true]) { + const request = (path === "/api/chat" + ? { model: "fx/m1", messages: [{ role: "user", content: "hi" }], stream } + : { model: "fx/m1", prompt: "hi", stream }); + for (const [errorMode, status, message] of [["status400", 400, "request rejected"], ["status401", 401, "upstream authentication failed"], ["status500", 500, "upstream request failed"]] as const) { + test(path + " stream=" + stream + " upstream " + status + " echoing the provider key", async () => { + mode = errorMode; + const result = await exchange(path, request); + expect(result.status).toBe(status); + expect(JSON.parse(result.text)).toEqual({ error: message }); + expect(result.text).not.toContain(PROVIDER_KEY); + expect(result.headers).not.toContain(PROVIDER_KEY); + expect(result.rows).toHaveLength(1); + expect(JSON.stringify(result.rows)).not.toContain(PROVIDER_KEY); + expect(existsSync(usageLogPath()) ? readFileSync(usageLogPath(), "utf8") : "").not.toContain(PROVIDER_KEY); + }); + } + } + test(path + " streamed error frame echoing the provider key ends with a fixed native error", async () => { + mode = "frame"; + const request = path === "/api/chat" ? { model: "fx/m1", messages: [{ role: "user", content: "hi" }] } : { model: "fx/m1", prompt: "hi" }; + const result = await exchange(path, request); + expect(result.text).not.toContain(PROVIDER_KEY); + expect(result.headers).not.toContain(PROVIDER_KEY); + const lines = result.text.split("\n").filter(Boolean).map(line => JSON.parse(line) as Record); + expect(lines.some(line => line.done === true)).toBe(false); + expect(lines.at(-1)).toEqual({ error: "upstream stream failed" }); + expect(JSON.stringify(result.rows)).not.toContain(PROVIDER_KEY); + expect(existsSync(usageLogPath()) ? readFileSync(usageLogPath(), "utf8") : "").not.toContain(PROVIDER_KEY); + }); + } +}); + +describe("Ollama responses never copy upstream header bytes", () => { + for (const path of ["/api/chat", "/api/generate"] as const) { + for (const stream of [false, true]) { + for (const [retryMode, status] of [["retryAfter429", 429], ["retryAfter400", 400]] as const) { + test(path + " stream=" + stream + " upstream " + status + " with a numeric key in Retry-After", async () => { + mode = retryMode; + saveProvider(NUMERIC_KEY); + const request = path === "/api/chat" + ? { model: "fx/m1", messages: [{ role: "user", content: "hi" }], stream } + : { model: "fx/m1", prompt: "hi", stream }; + const result = await exchange(path, request); + expect(result.status).toBe(status); + expect(result.text).not.toContain(NUMERIC_KEY); + expect(result.headers).not.toContain(NUMERIC_KEY); + // The advice survives only as an integer we formatted, clamped to the surface's bound. + const retryAfter = (JSON.parse(result.headers) as [string, string][]).find(([name]) => name === "retry-after")?.[1]; + expect(retryAfter).toMatch(/^[0-9]{1,4}$/); + expect(Number(retryAfter)).toBeLessThanOrEqual(OLLAMA_MAX_RETRY_AFTER_SECONDS); + expect(JSON.stringify(result.rows)).not.toContain(NUMERIC_KEY); + expect(existsSync(usageLogPath()) ? readFileSync(usageLogPath(), "utf8") : "").not.toContain(NUMERIC_KEY); + }); + } + } + } + + test("retry advice is reformatted, clamped, or dropped; never echoed", () => { + expect(ollamaRetryAfter("0")).toBe("0"); + expect(ollamaRetryAfter("7")).toBe("7"); + expect(ollamaRetryAfter("1.2")).toBe("2"); + expect(ollamaRetryAfter(" 07 ")).toBe("7"); + expect(Number(ollamaRetryAfter(NUMERIC_KEY))).toBeLessThanOrEqual(OLLAMA_MAX_RETRY_AFTER_SECONDS); + expect(ollamaRetryAfter(NUMERIC_KEY)).not.toBe(NUMERIC_KEY); + expect(ollamaRetryAfter(PROVIDER_KEY)).toBeUndefined(); + expect(ollamaRetryAfter(null)).toBeUndefined(); + const now = Date.UTC(2026, 0, 1); + expect(ollamaRetryAfter(new Date(now + 90_000).toUTCString(), now)).toBe("90"); + }); + + test("a refusal keeps only headers this surface generates", () => { + const refusal = new Response("{}", { status: 429, headers: { + "retry-after": NUMERIC_KEY, "x-opencodex-local-refusal": "workflow_sends_exhausted", + "x-upstream-echo": PROVIDER_KEY, "set-cookie": "a=" + PROVIDER_KEY, + } }); + const native = toOllamaRefusal(refusal); + expect([...native.headers.keys()].sort()).toEqual(["access-control-expose-headers", "content-type", "retry-after", "x-opencodex-local-refusal"]); + expect(Number(native.headers.get("retry-after"))).toBeLessThanOrEqual(OLLAMA_MAX_RETRY_AFTER_SECONDS); + // Values that are not a recognized local code never cross, whatever their shape. + for (const forged of [NUMERIC_KEY, PROVIDER_KEY, "workflow-sends-exhausted", "WORKFLOW_SENDS_EXHAUSTED", "constructor"]) { + const odd = toOllamaRefusal(new Response("{}", { status: 429, headers: { "x-opencodex-local-refusal": forged } })); + expect({ forged, headers: [...odd.headers.keys()] }).toEqual({ forged, headers: ["content-type"] }); + } + }); + + test("every real local refusal code maps to this surface's own constant", () => { + const reasons: WorkflowDenial[] = ["workflow-concurrency-exhausted", "workflow-sends-exhausted", "workflow-children-exhausted", + "workflow-spend-exhausted", "workflow-tracking-exhausted", "workflow-send-replayed", "workflow-spend-undurable", "workflow-pool-history-unresolved"]; + for (const reason of reasons) { + const produced = workflowRefusalResponse(reason); + const expected = workflowDenialSummary(reason).code; + expect(produced.headers.get("x-opencodex-local-refusal")).toBe(expected); + const native = toOllamaRefusal(produced); + expect({ reason, status: native.status, code: native.headers.get("x-opencodex-local-refusal") }).toEqual({ reason, status: 429, code: expected }); + expect(native.headers.get("access-control-expose-headers")).toBe("x-opencodex-local-refusal"); + } + }); +}); diff --git a/tests/server/server-ollama-inbound-lifecycle.test.ts b/tests/server/server-ollama-inbound-lifecycle.test.ts new file mode 100644 index 00000000000..9e922b80235 --- /dev/null +++ b/tests/server/server-ollama-inbound-lifecycle.test.ts @@ -0,0 +1,336 @@ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { loadConfig, saveConfig } from "../../src/config"; +import { startServer } from "../../src/server"; +import { dispatchOllamaRoute, type OllamaRouteDeps } from "../../src/server/index/ollama-routes"; +import { resetLifecycleDrainStateForTests, setDraining } from "../../src/server/lifecycle"; +import { resetWorkflowBudgetsForTest } from "../../src/lib/workflow-budget"; +import type { NativeFinalLog, NativeFinalOutcome } from "../../src/server/native-final-log"; +import { bufferedOllama, streamOllama } from "../../src/server/ollama-inbound"; +import { getRequestLogEntries } from "../../src/server/request-log"; +import type { OcxConfig } from "../../src/types"; +import { usageLogPath } from "../../src/usage/log"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +// Dispatcher ownership: which refusals expose a request id, the timeout override, drain. +describe("Ollama dispatcher arm", () => { + const local = { port: 0, providers: {} } as unknown as OcxConfig; + let timeouts: string[] = []; + let ran = 0; + const openAiRefusal = (status: number, retryAfter: string) => new Response(JSON.stringify({ error: { type: "server_error", code: "server_busy", message: "busy" } }), { + status, headers: { "content-type": "application/json", "Retry-After": retryAfter }, + }); + function deps(run: OllamaRouteDeps["runAdmittedHttpTurn"]): OllamaRouteDeps { + return { + config: local, policy: local, requestMetricsLogContext: {}, + requestServer: { timeout: (req: Request, seconds: number) => { timeouts.push(new URL(req.url).pathname + ":" + seconds); } } as never, + drainingResponse: () => openAiRefusal(503, "5"), + runAdmittedHttpTurn: run, + }; + } + const call = (path: string, run: OllamaRouteDeps["runAdmittedHttpTurn"], method = "POST") => { + const req = new Request("http://localhost" + path, { method, ...(method === "POST" ? { body: "{}", headers: { "content-type": "application/json" } } : {}) }); + return dispatchOllamaRoute(req, new URL(req.url), deps(run)); + }; + beforeEach(() => { timeouts = []; ran = 0; }); + afterEach(() => resetLifecycleDrainStateForTests()); + + test("generation disables the idle timeout; read-only routes and other paths do not", async () => { + const run: OllamaRouteDeps["runAdmittedHttpTurn"] = async () => { ran++; return new Response(null, { status: 204 }); }; + await call("/api/chat", run); + await call("/api/generate", run); + await call("/api/tags", run, "GET"); + expect(await call("/api/config", run, "GET")).toBeUndefined(); + expect(await call("/v1/chat/completions", run)).toBeUndefined(); + expect(timeouts).toEqual(["/api/chat:0", "/api/generate:0"]); + expect(ran).toBe(2); + }); + + test("drain refuses natively with retry advice, no row and no request id", async () => { + setDraining(true); + const res = (await call("/api/chat", async () => { ran++; return new Response(); }))!; + expect(res.status).toBe(503); + expect(res.headers.get("retry-after")).toBe("5"); + expect(res.headers.get("x-opencodex-request-id")).toBeNull(); + expect(await res.json()).toEqual({ error: "server temporarily unavailable; retry later" }); + expect(ran).toBe(0); + }); + + test("an unlogged active-turn refusal maps natively without an id", async () => { + const res = (await call("/api/generate", async (_req, _policy, _work, _log, options) => options!.mapRefusal!(openAiRefusal(503, "1"))))!; + expect(res.status).toBe(503); + expect(res.headers.get("retry-after")).toBe("1"); + expect(res.headers.get("x-opencodex-request-id")).toBeNull(); + expect(await res.json()).toEqual({ error: "server temporarily unavailable; retry later" }); + }); + + test("a logged workflow refusal and admission cancellation expose their row id", async () => { + const workflow = (await call("/api/chat", async (_req, _policy, _work, log, options) => { + log!.onLogged!(); + return options!.mapRefusal!(openAiRefusal(429, "30")); + }))!; + expect(workflow.status).toBe(429); + expect(workflow.headers.get("retry-after")).toBe("30"); + expect(workflow.headers.get("x-opencodex-request-id")).toMatch(/^ocx-/); + expect(await workflow.json()).toEqual({ error: "request budget exhausted; retry later" }); + const cancelled = (await call("/api/chat", async (_req, _policy, _work, log, options) => { + log!.onLogged!(); + return options!.onAdmissionError!(new Error("aborted")); + }))!; + expect(cancelled.status).toBe(499); + expect(cancelled.headers.get("x-opencodex-request-id")).toMatch(/^ocx-/); + expect(await cancelled.json()).toEqual({ error: "request cancelled" }); + }); + + test("wrong methods get a native 405 instead of reaching management or the GUI", async () => { + for (const [path, method, allow] of [["/api/chat", "GET", "POST"], ["/api/tags", "POST", "GET"], ["/api/version", "DELETE", "GET"]] as const) { + const res = (await call(path, async () => { ran++; return new Response(); }, method))!; + expect({ path, status: res.status, allow: res.headers.get("allow") }).toEqual({ path, status: 405, allow }); + } + expect(ran).toBe(0); + }); +}); + +// Real HTTP lifecycle: zero-send refusals, cancellation, retries, and trace suppression. +describe("Ollama NDJSON settlement window", () => { + test("a client cancel while the terminal waits for inner settlement still commits one 499", async () => { + let release!: (settled: boolean) => void; + const commits: NativeFinalOutcome[] = []; + const finalLog: NativeFinalLog = { + innerSettled: () => false, + waitForInner: () => new Promise(resolve => { release = resolve; }), + commit: outcome => { commits.push(outcome); return commits.length === 1; }, + }; + const frame = (body: unknown) => "data: " + JSON.stringify(body) + "\n\n"; + const inner = new Response([ + frame({ choices: [{ index: 0, delta: { role: "assistant", content: "hi" } }] }), + frame({ choices: [{ index: 0, delta: {}, finish_reason: "stop" }] }), + "data: [DONE]\n\n", + ].join("")).body!; + const reader = streamOllama("chat", "fx/m1", "time", inner, finalLog, new AbortController().signal).body!.getReader(); + expect(new TextDecoder().decode((await reader.read()).value)).toContain("\"hi\""); + const pendingTerminal = reader.read(); + await Bun.sleep(10); // The pull reached EOF and is now waiting in end() for settlement. + expect(release).toBeDefined(); + await reader.cancel(); + release(true); + await pendingTerminal.catch(() => undefined); + await Bun.sleep(10); + expect(commits).toEqual([{ status: 499, closeReason: "client_cancel" }]); + }); + + test("a buffered client that leaves while settlement is pending is a 499, not a success", async () => { + let release!: (settled: boolean) => void; + const commits: NativeFinalOutcome[] = []; + const finalLog: NativeFinalLog = { + innerSettled: () => false, + waitForInner: () => new Promise(resolve => { release = resolve; }), + commit: outcome => { commits.push(outcome); return commits.length === 1; }, + }; + const client = new AbortController(); + const inner = Response.json({ choices: [{ index: 0, message: { role: "assistant", content: "hi" }, finish_reason: "stop" }] }); + const pending = bufferedOllama("chat", "fx/m1", "time", inner, finalLog, client.signal); + await Bun.sleep(10); + client.abort(); + release(true); + const res = await pending; + expect(res.status).toBe(499); + expect(commits).toEqual([{ status: 499, closeReason: "client_cancel" }]); + }); + + test("data after the Chat terminator fails the stream instead of reporting success", async () => { + const commits: NativeFinalOutcome[] = []; + const finalLog: NativeFinalLog = { + innerSettled: () => true, + waitForInner: async () => true, + commit: outcome => { commits.push(outcome); return commits.length === 1; }, + }; + const frame = (body: unknown) => "data: " + JSON.stringify(body) + "\n\n"; + const inner = new Response([ + frame({ choices: [{ index: 0, delta: { role: "assistant", content: "hi" } }] }), + frame({ choices: [{ index: 0, delta: {}, finish_reason: "stop" }] }), + "data: [DONE]\n\n", + frame({ error: { message: "late failure" } }), + ].join("")).body!; + const text = await streamOllama("chat", "fx/m1", "time", inner, finalLog, new AbortController().signal).text(); + const lines = text.split("\n").filter(Boolean).map(line => JSON.parse(line) as Record); + expect(lines.some(line => line.done === true)).toBe(false); + expect(typeof lines.at(-1)!.error).toBe("string"); + expect(commits).toEqual([{ status: 502, terminalStatus: "failed", closeReason: "terminal" }]); + }); +}); + +const saved = process.env.OPENCODEX_HOME; +let home = ""; +let mode: "text" | "hang" | "flaky" = "text"; +let sends = 0; +let upstreamAborted = false; +let upstream: ReturnType; +const chunk = (choices: unknown[], extra: Record = {}) => + "data: " + JSON.stringify({ id: "c", object: "chat.completion.chunk", created: 1, model: "m1", choices, ...extra }) + "\n\n"; + +beforeAll(() => { + home = mkdtempSync(join(tmpdir(), "ocx-ollama-lifecycle-")); + process.env.OPENCODEX_HOME = home; + upstream = Bun.serve({ port: 0, idleTimeout: 30, async fetch(req) { + const body = await req.json() as { stream?: boolean }; + sends++; + if (mode === "flaky" && sends === 1) return Response.json({ error: { message: "fixture rate limit" } }, { status: 429, headers: { "retry-after": "30" } }); + if (mode === "hang") { + const encoder = new TextEncoder(); + return new Response(new ReadableStream({ + start(controller) { + controller.enqueue(encoder.encode(chunk([{ index: 0, delta: { role: "assistant", content: "partial" } }]))); + req.signal.addEventListener("abort", () => { upstreamAborted = true; try { controller.close(); } catch { /* closed */ } }); + }, + }), { headers: { "content-type": "text/event-stream" } }); + } + const usage = { prompt_tokens: 3, completion_tokens: 1, total_tokens: 4 }; + if (body.stream !== true) { + return Response.json({ id: "c", object: "chat.completion", created: 1, model: "m1", choices: [{ index: 0, message: { role: "assistant", content: "ok" }, finish_reason: "stop" }], usage }); + } + return new Response([chunk([{ index: 0, delta: { role: "assistant", content: "ok" } }]), chunk([{ index: 0, delta: {}, finish_reason: "stop" }]), chunk([], { usage }), "data: [DONE]\n\n"].join(""), { headers: { "content-type": "text/event-stream" } }); + } }); +}); +afterAll(() => { + upstream.stop(true); + if (saved === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = saved; + if (home) removeTreeWithRetry(home); +}); +beforeEach(() => { + mode = "text"; sends = 0; upstreamAborted = false; + saveConfig({ + port: 0, defaultProvider: "fx", + providers: { fx: { adapter: "openai-chat", baseUrl: upstream.url.origin + "/v1", authMode: "key", apiKey: "fixture-key-a", allowPrivateNetwork: true, models: ["m1"], + apiKeyPool: [{ id: "a", key: "fixture-key-a", addedAt: 1 }, { id: "b", key: "fixture-key-b", addedAt: 2 }] } }, + routingProfiles: { daily: { alias: "daily", candidates: [{ provider: "fx", model: "m1" }] } }, + combos: { group: { alias: "group", strategy: "round-robin", targets: [{ provider: "fx", model: "m1" }] } }, + } as unknown as OcxConfig); +}); + +async function withServer(run: (base: URL, rowsSince: () => ReturnType) => Promise) { + const server = startServer(0); + const earlier = new Set(getRequestLogEntries().map(entry => entry.requestId)); + try { await run(server.url, () => getRequestLogEntries().filter(entry => !earlier.has(entry.requestId))); } finally { await server.stop(true); } +} +const post = (base: URL, path: string, body: unknown, signal?: AbortSignal) => + fetch(new URL(path, base), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), signal }); +async function eventually(check: () => boolean, label: string) { + const deadline = Date.now() + 3_000; + while (!check()) { + if (Date.now() > deadline) throw new Error("timed out waiting for " + label); + await Bun.sleep(10); + } +} + +describe("Ollama generation lifecycle", () => { + test("combo, policy and synthetic selectors refuse natively with zero sends and one logged row each", async () => { + await withServer(async (base, rowsSince) => { + for (const [model, status] of [["combo/group", 403], ["group", 403], ["policy/daily", 403], ["daily", 403], ["fx/m1--fast", 400]] as const) { + const res = await post(base, "/api/chat", { model, messages: [{ role: "user", content: "hi" }], stream: false }); + expect({ model, status: res.status }).toEqual({ model, status }); + expect(typeof (await res.json() as { error: unknown }).error).toBe("string"); + const row = rowsSince().find(entry => entry.requestId === res.headers.get("x-opencodex-request-id")); + expect(row?.status).toBe(status); + } + expect(sends).toBe(0); + expect(rowsSince()).toHaveLength(5); + }); + }); + + test("client cancellation mid-stream aborts upstream and logs one 499 row", async () => { + mode = "hang"; + await withServer(async (base, rowsSince) => { + const abort = new AbortController(); + const res = await post(base, "/api/chat", { model: "fx/m1", messages: [{ role: "user", content: "hi" }] }, abort.signal); + expect(res.status).toBe(200); + const reader = res.body!.getReader(); + const first = await reader.read(); + expect(new TextDecoder().decode(first.value)).toContain("partial"); + abort.abort(); + await reader.cancel().catch(() => {}); + await eventually(() => upstreamAborted, "upstream abort"); + await eventually(() => rowsSince().length === 1, "one row"); + await Bun.sleep(150); + expect(rowsSince()).toHaveLength(1); + expect(rowsSince()[0]!.status).toBe(499); + }); + }); + + test("a key failover keeps both physical attempts on the live and persisted native row", async () => { + mode = "flaky"; + await withServer(async (base, rowsSince) => { + const res = await post(base, "/api/chat", { model: "fx/m1", messages: [{ role: "user", content: "hi" }], stream: false }); + expect(res.status).toBe(200); + await res.text(); + await Bun.sleep(20); + const rows = rowsSince(); + expect(rows).toHaveLength(1); + const live = rows[0]!; + expect(sends).toBe(2); + expect(live.status).toBe(200); + expect(live.usage).toMatchObject({ inputTokens: 3, outputTokens: 1 }); + const expected = [ + { ordinal: 1, status: 429, sendCount: 1, failureCause: "rate-limit" }, + { ordinal: 2, status: 200, sendCount: 1, recoveryKinds: ["key-429"], usageStatus: "reported" }, + ]; + expect(live.attempts).toMatchObject(expected); + expect((live as { attemptNormalizationDropped?: boolean }).attemptNormalizationDropped).not.toBe(true); + const persisted = readFileSync(usageLogPath(), "utf8").split("\n").filter(Boolean) + .map(line => JSON.parse(line) as { requestId: string; status: number; attempts?: unknown[]; attemptNormalizationDropped?: boolean }) + .find(entry => entry.requestId === live.requestId); + expect(persisted?.status).toBe(200); + expect(persisted?.attempts).toMatchObject(expected); + expect(persisted?.attemptNormalizationDropped).not.toBe(true); + }); + }); + + test("the workflow root survives the internal hop, so its token ceiling is enforced", async () => { + // Each fixture reply reports 4 tokens; a root ceiling of 20 is spent within a few requests. + const statuses = async (root: string | undefined) => { + resetWorkflowBudgetsForTest(); + saveConfig({ ...loadConfig(), spend: { root: { maxTokens: 20 } } } as OcxConfig); + const seen: number[] = []; + await withServer(async base => { + for (let i = 0; i < 10; i++) { + const res = await fetch(new URL("/api/chat", base), { + method: "POST", + headers: { "content-type": "application/json", ...(root ? { "x-codex-parent-thread-id": root } : {}) }, + body: JSON.stringify({ model: "fx/m1", messages: [{ role: "user", content: "hi" }], stream: false, options: { num_predict: 1 } }), + }); + seen.push(res.status); + await res.text(); + } + }); + return seen; + }; + const rooted = await statuses("ollama-workflow-root-" + crypto.randomUUID()); + expect(rooted[0]).toBe(200); + expect(rooted).toContain(429); + // Without a root the request has no root scope, so the root ceiling never applies. + expect(await statuses(undefined)).toEqual(Array(10).fill(200)); + resetWorkflowBudgetsForTest(); + }); + + test("native rows carry no Chat protocol identity", async () => { + await withServer(async (base, rowsSince) => { + for (const stream of [false, true]) { + const res = await post(base, "/api/generate", { model: "fx/m1", prompt: "hi", stream }); + expect(res.status).toBe(200); + await res.text(); + } + await Bun.sleep(20); + const rows = rowsSince(); + expect(rows).toHaveLength(2); + for (const row of rows) { + expect(row.protocolTrace).toBeUndefined(); + expect(row.inboundProtocol).toBeUndefined(); + expect(row.status).toBe(200); + expect(row.usage).toMatchObject({ inputTokens: 3, outputTokens: 1 }); + expect(row.attempts?.[0]).toMatchObject({ status: 200, sendCount: 1 }); + } + }); + }); +}); diff --git a/tests/server/server-ollama-inbound.test.ts b/tests/server/server-ollama-inbound.test.ts new file mode 100644 index 00000000000..057583ddf50 --- /dev/null +++ b/tests/server/server-ollama-inbound.test.ts @@ -0,0 +1,271 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { saveConfig } from "../../src/config"; +import { startServer } from "../../src/server"; +import { clearRequestLogsForTests, getRequestLogEntries } from "../../src/server/request-log"; +import type { OcxConfig } from "../../src/types"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +const DATA_TOKEN = "ocx_data_ollamafixture"; +const ADMIN_TOKEN = "admin-secret-for-ollama"; +const PROVIDER_KEY = "provider-fixture-key"; +const saved = { home: process.env.OPENCODEX_HOME, data: process.env.OPENCODEX_API_AUTH_TOKEN, admin: process.env.OPENCODEX_ADMIN_AUTH_TOKEN }; +let home = ""; +let mode: "text" | "tools" | "length" | "filter" | "unknown" | "error400" = "text"; +let seen: { auth: string | null; body: Record }[] = []; +let upstream: ReturnType; + +const chunk = (choices: unknown[], extra: Record = {}) => + "data: " + JSON.stringify({ id: "chatcmpl-fixture", object: "chat.completion.chunk", created: 1, model: "m1", choices, ...extra }) + "\n\n"; + +function finishFor(m: typeof mode): string { + return m === "tools" ? "tool_calls" : m === "length" ? "length" : m === "filter" ? "content_filter" : m === "unknown" ? "mystery" : "stop"; +} + +beforeAll(() => { + upstream = Bun.serve({ port: 0, async fetch(req) { + const body = await req.json() as Record; + seen.push({ auth: req.headers.get("authorization"), body }); + if (mode === "error400") return Response.json({ error: { message: "fixture upstream rejected the request", type: "invalid_request_error" } }, { status: 400 }); + const usage = { prompt_tokens: 5, completion_tokens: 2, total_tokens: 7 }; + const toolCall = { id: "call_fixture", type: "function", function: { name: "lookup", arguments: "{\"q\":\"x\"}" } }; + if (body.stream !== true) { + const message = mode === "tools" ? { role: "assistant", content: null, tool_calls: [toolCall] } : { role: "assistant", content: "Hello" }; + return Response.json({ id: "chatcmpl-fixture", object: "chat.completion", created: 1, model: "m1", choices: [{ index: 0, message, finish_reason: finishFor(mode) }], usage }); + } + const frames = mode === "tools" + ? [chunk([{ index: 0, delta: { role: "assistant", tool_calls: [{ index: 0, ...toolCall }] } }])] + : [chunk([{ index: 0, delta: { role: "assistant", content: "Hel" } }]), chunk([{ index: 0, delta: { content: "lo" } }])]; + frames.push(chunk([{ index: 0, delta: {}, finish_reason: finishFor(mode) }]), chunk([], { usage }), "data: [DONE]\n\n"); + return new Response(frames.join(""), { headers: { "content-type": "text/event-stream" } }); + } }); +}); +afterAll(() => { upstream.stop(true); }); + +function config(remote = false): OcxConfig { + return { + port: 0, + // A public bind is what makes the data-plane key mandatory. + ...(remote ? { hostname: "0.0.0.0" } : {}), + defaultProvider: "fx", + providers: { fx: { adapter: "openai-chat", baseUrl: upstream.url.origin + "/v1", authMode: "key", apiKey: PROVIDER_KEY, allowPrivateNetwork: true, models: ["m1"] } }, + } as OcxConfig; +} + +// The spend ledger binds one state directory per process, so the whole file shares one home. +beforeAll(() => { + home = mkdtempSync(join(tmpdir(), "ocx-ollama-inbound-")); + process.env.OPENCODEX_HOME = home; + process.env.OPENCODEX_API_AUTH_TOKEN = DATA_TOKEN; + process.env.OPENCODEX_ADMIN_AUTH_TOKEN = ADMIN_TOKEN; +}); +beforeEach(() => { + mode = "text"; + seen = []; + clearRequestLogsForTests(); + saveConfig(config()); +}); +afterAll(() => { + for (const [key, value] of [["OPENCODEX_HOME", saved.home], ["OPENCODEX_API_AUTH_TOKEN", saved.data], ["OPENCODEX_ADMIN_AUTH_TOKEN", saved.admin]] as const) { + if (value === undefined) delete process.env[key]; else process.env[key] = value; + } + if (home) removeTreeWithRetry(home); + home = ""; +}); + +async function withServer(run: (base: URL) => Promise): Promise { + const server = startServer(0); + earlierRows = new Set(getRequestLogEntries().map(entry => entry.requestId)); + try { await run(server.url); } finally { await server.stop(true); } +} +const auth = { authorization: "Bearer " + DATA_TOKEN }; +const post = (base: URL, path: string, body: unknown, headers: Record = auth) => + fetch(new URL(path, base), { method: "POST", headers: { "content-type": "application/json", ...headers }, body: typeof body === "string" ? body : JSON.stringify(body) }); +const ndjson = async (res: Response) => (await res.text()).split("\n").filter(Boolean).map(line => JSON.parse(line) as Record); +const rowFor = (res: Response) => getRequestLogEntries().find(entry => entry.requestId === res.headers.get("x-opencodex-request-id")); +// startServer hydrates earlier rows from disk, so a test counts only the rows it wrote. +let earlierRows = new Set(); +const newRows = () => getRequestLogEntries().filter(entry => !earlierRows.has(entry.requestId)); + +describe("Ollama-compatible inbound routes", () => { + test("version, tags and show answer with configured facts only", async () => { + await withServer(async base => { + const version = await fetch(new URL("/api/version", base), { headers: auth }); + expect(version.status).toBe(200); + expect(typeof (await version.json() as { version: unknown }).version).toBe("string"); + const tags = await fetch(new URL("/api/tags", base), { headers: auth }); + expect(await tags.json()).toEqual({ models: [{ name: "fx/m1", model: "fx/m1" }] }); + const show = await post(base, "/api/show", { model: "fx/m1" }); + expect(show.status).toBe(200); + expect(await show.json()).toEqual({ details: {}, model_info: {}, capabilities: ["completion"] }); + const unknown = await post(base, "/api/show", { model: "fx/absent-model" }); + expect(unknown.status).toBe(404); + expect(await unknown.json()).toEqual({ error: "model not found" }); + expect((await post(base, "/api/show", { model: "fx/m1", modelfile: "x" })).status).toBe(400); + }); + }); + + test("admission reuses the data-plane gates and keeps management routes intact", async () => { + saveConfig(config(true)); + await withServer(async base => { + for (const path of ["/api/version", "/api/tags"]) { + const res = await fetch(new URL(path, base)); + expect(res.status).toBe(401); + expect(await res.json()).toEqual({ error: "opencodex API key required" }); + } + const unauthorized = await post(base, "/api/chat", { model: "fx/m1", messages: [{ role: "user", content: "hi" }] }, {}); + expect(unauthorized.status).toBe(401); + expect(seen).toHaveLength(0); + const managementKeyOnly = await post(base, "/api/chat", { model: "fx/m1", messages: [] }, { "x-opencodex-api-key": ADMIN_TOKEN }); + expect(managementKeyOnly.status).toBe(401); + const wrongMethod = await fetch(new URL("/api/chat", base), { headers: auth }); + expect(wrongMethod.status).toBe(405); + expect(wrongMethod.headers.get("allow")).toBe("POST"); + expect(await wrongMethod.json()).toEqual({ error: "method GET not allowed" }); + const crossOrigin = await post(base, "/api/chat", { model: "fx/m1", messages: [] }, { ...auth, origin: "https://evil.example" }); + expect(crossOrigin.status).toBe(403); + // Unknown /api/* still reaches the management boundary. + expect((await fetch(new URL("/api/not-a-native-route", base))).status).toBe(401); + const managed = await fetch(new URL("/api/not-a-native-route", base), { headers: { "x-opencodex-api-key": ADMIN_TOKEN } }); + expect(managed.status).toBe(404); + expect(seen).toHaveLength(0); + }); + }); + + test("native preflight uses data-plane CORS, other /api preflight stays management", async () => { + await withServer(async base => { + const preflight = (path: string, origin: string) => fetch(new URL(path, base), { method: "OPTIONS", headers: { origin, "access-control-request-method": "POST" } }); + expect((await preflight("/api/chat", "https://evil.example")).status).toBe(403); + const local = await preflight("/api/chat", base.origin); + expect(local.status).toBe(204); + }); + }); + + for (const kind of ["chat", "generate"] as const) { + const request = (extra: Record = {}) => kind === "chat" + ? { model: "fx/m1", messages: [{ role: "user", content: "hi" }], ...extra } + : { model: "fx/m1", prompt: "hi", ...extra }; + const text = (record: Record) => kind === "chat" ? (record.message as { content?: string } | undefined)?.content : record.response; + + test(kind + " buffered returns one native record and logs one matching row", async () => { + await withServer(async base => { + const res = await post(base, "/api/" + kind, request({ stream: false })); + expect(res.status).toBe(200); + const body = await res.json() as Record; + expect(text(body)).toBe("Hello"); + expect(body).toMatchObject({ model: "fx/m1", done: true, done_reason: "stop", prompt_eval_count: 5, eval_count: 2 }); + expect(seen).toHaveLength(1); + expect(seen[0]!.auth).toBe("Bearer " + PROVIDER_KEY); + expect(seen[0]!.body.stream).not.toBe(true); + const row = rowFor(res); + expect(row).toBeDefined(); + expect(row!.status).toBe(200); + expect(newRows()).toHaveLength(1); + expect(row!.attempts?.[0]?.sendCount).toBe(1); + }); + }); + + test(kind + " streams NDJSON with exactly one done record after usage", async () => { + await withServer(async base => { + const res = await post(base, "/api/" + kind, request()); + expect(res.status).toBe(200); + expect(res.headers.get("content-type")).toContain("application/x-ndjson"); + const lines = await ndjson(res); + expect(lines.map(text).filter(Boolean).join("")).toBe("Hello"); + const done = lines.filter(line => line.done === true); + expect(done).toHaveLength(1); + expect(lines.at(-1)).toMatchObject({ done: true, done_reason: "stop", prompt_eval_count: 5, eval_count: 2 }); + expect(seen[0]!.body.stream).toBe(true); + await Bun.sleep(20); + expect(newRows()).toHaveLength(1); + expect(rowFor(res)!.status).toBe(200); + }); + }); + + for (const finish of ["length", "filter", "unknown"] as const) { + test(kind + " maps finish " + finish + " truthfully in both delivery modes", async () => { + mode = finish; + await withServer(async base => { + const buffered = await post(base, "/api/" + kind, request({ stream: false })); + const streamed = await post(base, "/api/" + kind, request()); + const lines = await ndjson(streamed); + if (finish === "length") { + expect(buffered.status).toBe(200); + expect(await buffered.json()).toMatchObject({ done: true, done_reason: "length" }); + expect(lines.at(-1)).toMatchObject({ done: true, done_reason: "length" }); + } else { + expect(buffered.status).toBe(502); + expect(typeof (await buffered.json() as { error: unknown }).error).toBe("string"); + expect(lines.some(line => line.done === true)).toBe(false); + expect(typeof lines.at(-1)!.error).toBe("string"); + } + await Bun.sleep(20); + const rows = newRows(); + expect(rows).toHaveLength(2); + for (const row of rows) expect(row.status).toBe(finish === "length" ? 200 : 502); + }); + }); + } + + test(kind + " upstream refusal keeps its status with a native error and one row", async () => { + mode = "error400"; + await withServer(async base => { + const res = await post(base, "/api/" + kind, request({ stream: false })); + expect(res.status).toBe(400); + // Upstream text is never forwarded; the status picks a fixed native message. + expect(await res.json()).toEqual({ error: "request rejected" }); + expect(newRows()).toHaveLength(1); + expect(rowFor(res)!.status).toBe(400); + }); + }); + + test(kind + " malformed input is a logged 400 before any send", async () => { + await withServer(async base => { + for (const body of ["{not json", JSON.stringify(request({ keep_alive: "5m" }))]) { + const res = await post(base, "/api/" + kind, body); + expect(res.status).toBe(400); + expect(typeof (await res.json() as { error: unknown }).error).toBe("string"); + expect(rowFor(res)!.status).toBe(400); + } + expect(seen).toHaveLength(0); + }); + }); + } + + test("chat tools round trip with stable call ids", async () => { + mode = "tools"; + await withServer(async base => { + const tools = [{ type: "function", function: { name: "lookup", description: "find", parameters: { type: "object", properties: { q: { type: "string" } } } } }]; + const buffered = await post(base, "/api/chat", { model: "fx/m1", messages: [{ role: "user", content: "hi" }], tools, stream: false }); + expect(await buffered.json()).toMatchObject({ done: true, done_reason: "tool_calls", message: { tool_calls: [{ function: { name: "lookup", arguments: { q: "x" } } }] } }); + expect(seen[0]!.body.tools).toEqual(tools); + const lines = await ndjson(await post(base, "/api/chat", { model: "fx/m1", messages: [{ role: "user", content: "hi" }], tools })); + expect(lines.at(-1)).toMatchObject({ done: true, done_reason: "tool_calls" }); + expect(lines.some(line => JSON.stringify(line).includes("lookup"))).toBe(true); + // A client that echoes the assistant message back unchanged continues the same call. + const first = await (await post(base, "/api/chat", { model: "fx/m1", messages: [{ role: "user", content: "hi" }], tools, stream: false })).json() as { message: Record }; + seen = []; + const followUp = await post(base, "/api/chat", { model: "fx/m1", tools, stream: false, messages: [ + { role: "user", content: "hi" }, first.message, { role: "tool", tool_name: "lookup", content: "found" }, + ] }); + expect(followUp.status).toBe(200); + await followUp.text(); + const sent = seen[0]!.body.messages as { tool_calls?: { id: string }[]; tool_call_id?: string }[]; + expect(sent[1]!.tool_calls![0]!.id).toBe("call_fixture"); + expect(sent[2]!.tool_call_id).toBe("call_fixture"); + }); + }); + + test("images reach the provider as Chat image_url data URLs with exact bytes", async () => { + await withServer(async base => { + const image = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3, 4]).toString("base64"); + const res = await post(base, "/api/chat", { model: "fx/m1", messages: [{ role: "user", content: "see", images: [image] }], stream: false }); + expect(res.status).toBe(200); + const content = (seen[0]!.body.messages as { content: unknown }[])[0]!.content as { type: string; image_url?: { url: string } }[]; + const part = content.find(item => item.type === "image_url"); + expect(part?.image_url?.url.endsWith(";base64," + image)).toBe(true); + }); + }); +}); diff --git a/tests/server/server-ollama-route-policy.test.ts b/tests/server/server-ollama-route-policy.test.ts new file mode 100644 index 00000000000..a817c14600c --- /dev/null +++ b/tests/server/server-ollama-route-policy.test.ts @@ -0,0 +1,99 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import type { OcxConfig } from "../../src/types"; +import { findOllamaRoute, listOllamaRoutes, preflightOllamaRoute, linkRequestSessionLane } from "../../src/server/ollama-route-policy"; +import { getOrAllocateRequestSessionLane } from "../../src/server/request-log-conversation"; + +const originalFetch = globalThis.fetch; +let sends = 0; +beforeEach(() => { sends = 0; globalThis.fetch = (() => { sends++; throw new Error("unexpected send"); }) as typeof fetch; }); +afterEach(() => { globalThis.fetch = originalFetch; }); +const req = (headers: Record = {}) => new Request("http://localhost/api/chat", { headers }); +function config(): OcxConfig { + return { port: 0, defaultProvider: "keyed", providers: { + keyed: { adapter: "openai-chat", baseUrl: "https://example.test/v1", authMode: "key", apiKey: "fixture", models: ["model"] }, + cursorless: { adapter: "cursor", baseUrl: "https://api2.cursor.sh/", authMode: "key", models: ["model"] }, + forward: { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", authMode: "forward", models: ["model"] }, + }, routingProfiles: { daily: { alias: "daily", candidates: [{ provider: "keyed", model: "model" }] }, empty: { alias: "empty", candidates: [] } }, + combos: { group: { alias: "group", strategy: "round-robin", targets: [{ provider: "keyed", model: "model" }] } }, + } as OcxConfig; +} +function rejected(c: OcxConfig, selector: string, code: string, status: number, request = req()) { + const result = preflightOllamaRoute(c, selector, request); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.error).toMatchObject({ code, status }); + expect(sends).toBe(0); +} + +describe("Ollama route preflight", () => { + test("lists configured eligible routes only and rejects caller credential transports", () => { + const c = config(); + c.customModels = [{ id: "custom", provider: "keyed", modelId: "custom" }]; + expect(listOllamaRoutes(c, req()).map(row => row.selector)).toEqual(["keyed/model", "keyed/custom"]); + const result = preflightOllamaRoute(c, "keyed/model", req({ authorization: "Bearer caller" })); + expect(result.ok).toBe(true); + rejected(c, "cursorless/model", "unsupported_credential_domain", 403); + rejected(c, "forward/model", "unsupported_credential_domain", 403); + c.providers.keyed!.selectedModels = ["model", "retained"]; + expect(listOllamaRoutes(c, req()).map(row => row.selector)).toEqual(["keyed/model", "keyed/retained"]); + expect(sends).toBe(0); + }); + test("rejects policy selectors before policy evaluation, including aliases and unknown namespace", () => { + const c = config(); + for (const selector of ["policy/daily", "daily", "policy/empty", "empty", "policy/missing", "policy/"]) { + rejected(c, selector, "unsupported_credential_domain", 403); + } + expect(listOllamaRoutes(c, req()).every(row => !row.selector.startsWith("policy/"))).toBe(true); + }); + test("rejects synthetic selectors before combo or policy handling", () => { + const c = config(); c.cursorEffortRows = true; + for (const selector of ["keyed/model--fast", "combo/group--fast", "policy/daily--fast", "daily--fast", "group--high", "daily--high"]) { + rejected(c, selector, "unsupported_synthetic_selector", 400); + } + rejected(c, "combo/group", "unsupported_credential_domain", 403); + }); + test("rejects configured shadow sources irrespective of provenance and target", () => { + const c = config(); + for (const target of ["keyed/model", "combo/group"]) { + c.shadowCallIntercept = { enabled: true, model: target, sourceModels: ["model"] }; + for (const headers of [{}, { "x-openai-subagent": "collab_spawn", "x-openai-parent-turn-id": "fixture" }]) { + rejected(c, "model", "unsupported_shadow_rewrite", 400, req(headers)); + } + expect(listOllamaRoutes(c, req()).map(row => row.selector)).toEqual(["keyed/model"]); + } + }); + test("rejects cross-provider blocked-model rewrites", () => { + const c = config(); c.providers.other = { adapter: "openai-chat", baseUrl: "https://other.example/v1", authMode: "key", apiKey: "fixture", models: ["model"] }; c.blockedModelRedirects = { "keyed/model": "other/model" }; + rejected(c, "keyed/model", "unsupported_credential_domain", 403); + }); + test("settles wire override and carries the sessionless Go lane to an internal request", () => { + const c = config(); + c.providers["opencode-go"] = { adapter: "openai-chat", baseUrl: "https://opencode.ai/zen/go/v1", authMode: "key", apiKey: "fixture", models: ["minimax-m3", "glm-5.2"], modelAdapters: { "glm-5.2": "openai-responses" } }; + const original = req(); const internal = req(); + const result = preflightOllamaRoute(c, "opencode-go/minimax-m3", original); + expect(result.ok).toBe(true); + if (!result.ok) return; + expect(result.route.provider.adapter).toBe("anthropic"); + expect(result.route.provider.headers?.["x-opencode-session"]).toMatch(/^ocx_/); + linkRequestSessionLane(original, internal); + expect(getOrAllocateRequestSessionLane(internal)).toBe(getOrAllocateRequestSessionLane(original)); + const again = preflightOllamaRoute(c, "opencode-go/minimax-m3", internal); + expect(again.ok && again.route.provider.headers?.["x-opencode-session"]).toBe(result.route.provider.headers?.["x-opencode-session"]); + const other = preflightOllamaRoute(c, "opencode-go/glm-5.2", original); + expect(other.ok && other.route.provider.adapter).toBe("openai-responses"); + expect(sends).toBe(0); + }); + test("the point lookup matches the list for every selector and refuses everything else", () => { + const c = config(); + c.customModels = [{ id: "custom", provider: "keyed", modelId: "vendor/custom" }]; + c.providers.off = { adapter: "openai-chat", baseUrl: "https://off.example/v1", authMode: "key", apiKey: "fixture", models: ["model"], disabled: true }; + const listed = listOllamaRoutes(c, req()); + expect(listed.map(row => row.selector)).toContain("keyed/vendor/custom"); + for (const row of listed) expect(findOllamaRoute(c, row.selector, req())?.selector).toBe(row.selector); + for (const selector of ["keyed/absent", "off/model", "cursorless/model", "policy/daily", "daily", "combo/group", "model", "/model", "constructor/model", "__proto__/model"]) { + expect({ selector, found: findOllamaRoute(c, selector, req()) }).toEqual({ selector, found: undefined }); + } + c.providers.keyed!.selectedModels = ["model"]; + expect(findOllamaRoute(c, "keyed/vendor/custom", req())).toBeUndefined(); + expect(sends).toBe(0); + }); +}); From 4948c04d9ced0cae90779ce03196088cc97aa906 Mon Sep 17 00:00:00 2001 From: JUN Date: Mon, 2 Nov 2026 22:15:05 +0900 Subject: [PATCH 08/43] feat(sync): Home ocx sync fans out to linked Children (sync.home-fanout/1) (#8100) * feat(sync): add fan-out execution primitives * feat(sync): fan out committed Home catalog to linked children * fix(sync): keep version probe refusals machine-readable * docs(devlog): plan for Home sync fan-out to linked Children (C2) Audited over eight rounds; records the contract, the per-Child execution and classification rules, isolation bounds and the decision to never restart a Child's Codex from the Home. * fix(sync): frame fan-out output and reject oversized probes * fix(sync): frame platform probes and reject incomplete output * test(sync): point sync source oracles at the moved sync runner The sync runner moved from src/cli/dispatch.ts to src/cli/sync-command.ts; the owned-client refresh and stale app-server wiring guards still read the old file and failed in the full Ubuntu shards. They now slice runSyncCommand from sync-command.ts; sync-cache keeps reading dispatch.ts. * fix(sync): secure fan-out capture and align references * docs(sync): state when Home fan-out exits 6 --- .../_plan/261102_sync_home_fanout/010_plan.md | 303 ++++++++++++++++++ .../docs/fr/reference/cli/lifecycle.md | 6 +- .../docs/ja/reference/cli/lifecycle.md | 6 +- .../docs/ko/reference/cli/lifecycle.md | 6 +- .../content/docs/reference/cli/lifecycle.md | 17 +- .../docs/ru/reference/cli/lifecycle.md | 6 +- .../docs/tr/reference/cli/lifecycle.md | 6 +- .../docs/zh-cn/reference/cli/lifecycle.md | 6 +- .../docs/zh-tw/reference/cli/lifecycle.md | 6 +- scripts/test-layout/layout.json | 2 +- scripts/test-layout/seeds.json | 3 +- skills/ocx/references/01_surface_lifecycle.md | 8 +- skills/ocx/references/04_failure_semantics.md | 2 + skills/ocx/references/05_remote_hub.md | 6 + src/cli/capabilities-base.ts | 8 +- src/cli/capabilities-command.ts | 15 +- src/cli/capability-contracts.ts | 1 + src/cli/dispatch.ts | 179 +---------- src/cli/help.ts | 4 +- src/cli/link.ts | 2 +- src/cli/registry.ts | 7 +- src/cli/root.ts | 6 + src/cli/sync-command.ts | 241 ++++++++++++++ src/cli/sync-fanout-process.ts | 92 ++++++ src/cli/sync-fanout.ts | 150 +++++++++ src/cli/sync-flags.ts | 10 + src/cli/sync-link-status.ts | 39 +++ src/link/remote-platform.ts | 14 + src/link/remote-windows.ts | 50 ++- src/link/ssh-argv.ts | 73 ++++- structure/cli-management.md | 6 +- structure/remote-link.md | 2 + tests/cli/cli-capabilities-arguments.test.ts | 16 + tests/cli/cli-json-contract.test.ts | 2 +- tests/cli/cli-transport-honesty.test.ts | 2 + tests/cli/sync-command-fanout.test.ts | 192 +++++++++++ tests/cli/sync-fanout-process.test.ts | 90 ++++++ tests/cli/sync-fanout.test.ts | 111 +++++++ tests/cli/sync-link-status.test.ts | 25 ++ tests/clients/link-pinned-sync-argv.test.ts | 185 +++++++++++ .../clients/sync-client-integrations.test.ts | 6 +- .../codex-app-server-processes.test.ts | 7 +- .../codex-catalog-writer.test.ts | 2 + tests/fixtures/test-layout-expected.json | 2 +- .../update/update-stop-classification.test.ts | 2 +- tests/update/update-teardown-handover.test.ts | 2 +- 46 files changed, 1699 insertions(+), 227 deletions(-) create mode 100644 devlog/_plan/261102_sync_home_fanout/010_plan.md create mode 100644 src/cli/capability-contracts.ts create mode 100644 src/cli/sync-command.ts create mode 100644 src/cli/sync-fanout-process.ts create mode 100644 src/cli/sync-fanout.ts create mode 100644 src/cli/sync-flags.ts create mode 100644 src/cli/sync-link-status.ts create mode 100644 tests/cli/sync-command-fanout.test.ts create mode 100644 tests/cli/sync-fanout-process.test.ts create mode 100644 tests/cli/sync-fanout.test.ts create mode 100644 tests/cli/sync-link-status.test.ts create mode 100644 tests/clients/link-pinned-sync-argv.test.ts diff --git a/devlog/_plan/261102_sync_home_fanout/010_plan.md b/devlog/_plan/261102_sync_home_fanout/010_plan.md new file mode 100644 index 00000000000..058699ee01f --- /dev/null +++ b/devlog/_plan/261102_sync_home_fanout/010_plan.md @@ -0,0 +1,303 @@ +# 10 — Home `ocx sync` fans out to linked Children (C2, `sync.home-fanout/1`) + +Class C4 (public CLI contract: new flags, a new JSON schema, a new exit code, a new capability +field). Single work-phase `wp1`. Sibling lanes: L1 `ocx update` orchestration (shares the capability +contracts list) and L3, the GOAT consumer. + +Revision 8 folds the round-7 audit: each candidate's `--version` runs once, in the background, +under a 10 s kill watchdog and a size bound, and that one run both selects and versions the +candidate; Windows reads through a new bounded C# helper; the capture file is removed before `exec`; +failed candidates fall through as today. It also reserves exit 7 for L1's sync/update mutex. +Revision 7 folded the round-6 audit: the POSIX version capture keeps the real exit status and is +size-limited with `ulimit -f` instead of a `head` pipeline. +Revision 6 folded the round-5 audit: the capability probe is removed (it could run shim repair +before the link check and buffered unbounded output on the Child). Children now identify themselves +by their own sync output, and success needs positive evidence in both forms. The wrapper's version +capture is bounded. +Revision 5 folded the round-4 audit (JSON support is probed from the selected executable, not +inferred from its version; best-effort store inspection on the thrown-Home path). +Revision 4 folded the round-3 audit (version marker and fail-closed modern output, exit 0 required +for success, thrown Home sync in human mode, strict SemVer bound, Windows execution tests). +Revision 3 folded the round-2 audit (single remote operation, machine-readable freshness, catalog +gate, bounded status deadline, termination-unconfirmed, store failure, restart wording). +Revision 2 folded the round-1 audit (terra xhigh, FAIL) and the origin's decision on its blocker: +`--restart-children` is removed (option A). Home fan-out never restarts a Child's Codex; restart +authority stays with GOAT, which knows real running turns, or with an operator running +`ocx sync --restart-codex` on the Child. + +## Problem + +To sync a Remote Link Home and its Children, GOAT or an operator has to SSH to every Child and run +`ocx sync --expect-link ` there. An operator who types `ocx sync` on the Home refreshes only +the Home, so Children keep a stale catalog until someone syncs them one by one. + +## Contract + +### When propagation runs + +- Only on the local branch of the `sync` runner (the machine is not a connected client) and only + without `--expect-link`/`--expect-hub-key`. A connected client never propagates. The pinned form is + the call a Home makes into a Child, so a chain cannot recurse. +- On by default; `--local-only` turns it off (accepted and a no-op on every other path). +- Only when the Home sync committed a current catalog: exit 0, `synced.status` is `applied` or + `catalog-only`, `synced.refreshOutcome === "committed"`, and `projectLocalSyncResult(synced).catalog.converged` + (catalog exists, not refused, no safety warning). An exit-0 run without that evidence (a refused or + thrown catalog refresh, `refreshOutcome` absent) skips every Child with `home-catalog-not-current` and + keeps the Home exit. The implementation must confirm with a test that an unchanged catalog reports + `committed`; if it does not, the gate uses the evidence the unchanged path does report, never weaker. A Child's + `/v1/catalog` fetch serializes the Home's persisted Codex catalog + (`src/server/index/serve-options.ts` `/v1/catalog` -> `src/server/catalog-download.ts`), so after a + failed or skipped Home sync a Child could only receive whatever the failed run left behind. Every + Child is then `skipped` with `home-sync-failed` or `home-sync-skipped`, and the Home exit code is + kept. A Home sync that throws is caught by the runner. JSON mode prints the document (`home.state + failed`, `home.exit` 1, every hub-initiated Child `skipped` `home-sync-failed` when the link store is + readable; an unreadable store instead yields `fanout.state` `failed`, reason `link-store-unreadable`, + and no children) and one sanitized + `Sync failed: ...` stderr line. Human mode prints + one stderr line, `Children were not synced because the Home sync failed.`, when a best-effort + store read (any error swallowed, so it can never replace the original error) finds a link, then + rethrows the original error unchanged so today's failure output and exit stay. +- Never requests a Codex app or app-server restart on a Child, and never restarts the Home proxy: + the command sent to a Child carries no restart flag. The Child's own pinned sync keeps its existing + behavior of restarting its OpenCodex client runtime after it applies changed Home settings + (`src/cli/link-apply-restart.ts`), which can interrupt a request relayed at that moment. Help and + docs state both and point to GOAT or `ocx sync --restart-codex` on the Child for a Codex restart. + +### Which links + +- Records come from `/link/links.json` (`readLinkStore`). `client-initiated` links are + `skipped` (`client-initiated-link`): the Home has no SSH path or pinned host key for them. +- Reachability comes from the Home runtime's `GET /api/link/status`, read once by + `readHomeLinkStatus` under one absolute 5 s deadline that covers live-runtime discovery, the + request headers and the body read (a `Promise.race` against a typed `LinkStatusTimeout` plus an + `AbortController` passed to fetch; discovery that ignores the deadline is abandoned, and the CLI + exits through `process.exit`). It uses the same discovery and admin headers as `runtimeRequest`. The route + admits the admin token on trusted loopback (`auth(ctx, "either")`). Outcomes, applied to every + hub-initiated Child: no live Home runtime -> `skipped` `home-runtime-not-running`; 401/403 -> + `failed` `home-link-status-unauthorized`; abort/timeout -> `failed` `home-link-status-timeout`; any + other error -> `failed` `home-link-status-unavailable`; a DTO that fails validation -> `failed` + `home-link-status-invalid`. Per link: absent from the DTO -> `skipped` `link-not-in-runtime`; state + not `connected` -> `skipped` `tunnel-` (state from the closed `LinkWireState` set). + +### Per Child + +Each Child runs in its own worker with one deadline (180 s from the moment the worker starts) +covering every ssh call. All commands use `buildExecArgv` with the link known_hosts +(`StrictHostKeyChecking=yes`) and `remoteOcxArgv(args, platform)`. + +1. Platform: `record.remotePlatform`, or when absent `requireRemotePlatformFramed` through the owned + runner with each call's timeout clamped to the remaining deadline. A successful Windows probe + identifies Windows when any trimmed stdout line is exactly `Windows_NT`. Otherwise a POSIX probe + prints `ocx-platform:`; exactly one framed line is required. Login-shell output is ignored; + exit 255 is a transport failure and ambiguous or failed probes -> `failed` `platform-probe-failed`. +2. One remote operation, `remotePinnedSyncArgv(linkId, platform)` (NEW in `src/link/ssh-argv.ts` for + POSIX and `src/link/remote-windows.ts` for Windows), sharing the candidate list and order with + `REMOTE_OCX_SCRIPT` / `windowsOcxArgv`. For each candidate in order it runs that executable's + `--version` exactly once, and that single run both decides selection and supplies the version: + - POSIX: `( ulimit -c 0; ulimit -f 1; exec "$c" --version ) >"$tmp" 2>/dev/null &`, a watchdog + `( sleep 10; kill -9 "$vp" ) &`, `wait "$vp"` for the real status, then the watchdog is killed and + reaped; the whole group's stderr goes to `/dev/null`. After exit, the capture file itself is + measured before parsing; a capture over 256 bytes is skipped even if the process exited 0. + Checked locally with `sh`: a writer that ignores SIGPIPE and SIGXFSZ and swallows its write + errors is killed at the watchdog (status 137, file at 512 bytes, its pid gone afterwards); a + version printing `opencodex 2.93.0` and exiting 17 returns 17; a normal one returns 0. + - Windows: a new `[OcxJob]::V(path)` in `OCX_JOB_SOURCE` starts the process with redirected + stdout and stderr, reads stdout in a loop into a 257-char buffer on a task, drains stderr on + another task discarding it, waits for the reading task and the exit together under one 10 s + deadline, kills and waits for the process on overflow or deadline, and returns the text only + when the process exited 0 with at most 256 characters. + - A candidate whose run exits nonzero, is killed by the watchdog or overflows is skipped and the + next candidate is tried, as today's `try_ocx` skips a failing one; it is never synced. No + qualifying candidate -> exit 127 as today. + - The first qualifying candidate is selected. Its output must parse as `opencodex ` or a + bare `` (the full `src/lib/strict-semver.ts` grammar: `MAJOR.MINOR.PATCH`, optional `-prerelease`, + optional `+build`; build metadata is accepted and ignored for precedence, as SemVer specifies, + and the marker carries the version string exactly as parsed); unparsable -> last stderr line `ocx-fanout:child-ocx-version-unknown`, exit 121. + A version that strict SemVer precedence orders below 2.93.0 (so `2.93.0-preview.*` is refused) + -> `ocx-fanout:child-ocx-lacks-expect-link`, exit 121. 2.93.0 is the first release with + `--expect-link` (959a07a5ea is in v2.93.0, not v2.92.0); checking first matters because an older + ocx ignores unknown flags and would run an unpinned sync. + - Otherwise it removes the capture file, clears the trap, writes exactly + `ocx-fanout:selected:` on stderr, then `ocx-fanout:stdout-begin` on stdout, and execs + ` sync --expect-link --json`. The trap removes the file on every refusal path. + - No `ocx` command other than `--version` runs on the Child before the pinned sync (platform + discovery may run its fixed OS probe first), so the pinned sync's "nothing changed on mismatch" + guarantee (shim repair deferred until after the identity check) is unchanged. + - Replacing the binary on disk between its version run and the exec is outside the threat model: + it needs write access to the Child's ocx install, which already controls the Child's OpenCodex. + The Windows script must stay within `POWERSHELL_ENCODED_MAX` (asserted by a test). +3. Classification, transport first (these apply whatever the output says): exit 255 -> `failed` `ssh-failed`; 127 -> `failed` + `child-ocx-not-found`; 126 (Windows containment) -> `failed` `child-ocx-not-contained`; 125 -> + `skipped` `child-platform-unsupported`; 121 with a known `ocx-fanout:` marker as the last stderr + line -> `skipped` with that code (121 without a marker -> `failed` `child-sync-failed`). Then the + sync result. Success needs exit 0 and positive evidence; a nonzero exit is never overridden by a + document. The Home requires exactly one stderr line matching `^ocx-fanout:selected:(.+)$` with a + strict SemVer version, and exactly one stdout line `ocx-fanout:stdout-begin`. Missing, duplicate, + or malformed framing -> `failed` `child-output-invalid` after the transport cases above. Login-shell + output before the markers is ignored; classification uses only stdout after the delimiter. For exit 0: + - that stdout, trimmed, starts with `{`: the Child claims the `--json` form (this release and later). + It must be exactly one valid `ocx.sync.fanout/1` document; `home.state "synced"` -> `synced`, + `home.state "stale"` -> `failed` `child-catalog-stale`; malformed JSON, an unknown schema, a + second document, an inconsistent document (any other state, or `home.exit` not 0) -> `failed` + `child-output-invalid`. + - otherwise the Child is a release from v2.93.0 up to the one before this change (it ignores + `--json`): stdout must contain the legacy success sentence `Remote Link Home catalog + synchronized.` -> `synced`, or the stale sentence `Home unavailable; retained and applied the + last-known-good remote catalog (stale).` -> `failed` `child-catalog-stale` (stale wins if both + appear); neither -> `failed` `child-output-invalid`. Both sentences are identical in v2.93.0, + v2.94.0, v2.95.0 and v2.96.0 (checked with `git show :src/cli/dispatch.ts`) and are exported + as constants that a test pins. + Exit 5 -> + `skipped` `child-link-mismatch:` when the final stderr line parses as + `{"phase":"child_link_mismatch","reason":R}` with R in the closed reason set, otherwise + `child-link-mismatch`; exit 7 -> `skipped` `child-updating` (reserved for L1's sync/update + mutex, `update-in-flight`; nothing changed on the Child); any other non-zero (including exit 1 after a fresh catalog when the apply + record or runtime restart failed) -> `failed` `child-sync-failed`. +4. Deadline -> `timed-out` `deadline-exceeded` with `exit: null`; when the process cannot be + confirmed gone after SIGKILL and its wait, the reason is `termination-unconfirmed` instead. Spawn failure -> `failed` + `ssh-spawn-failed`; output over the cap or undecodable -> `failed` `ssh-output`. A worker that + throws for any other reason -> `failed` `internal-error`. + +`reason` is always one of these fixed codes (null for `synced`). No ssh stderr or remote text +reaches the output. + +### Process ownership and isolation + +- A dedicated runner in `src/cli/sync-fanout-process.ts` spawns each ssh with `Bun.spawn` + (`stdin: "ignore"`, piped bounded stdout/stderr, `linkSshSpawnEnv()`). On deadline, output-limit or + decode failure it sends SIGTERM, waits up to 2 s for exit, then SIGKILL and waits up to 1 s more. + The worker returns only after that sequence, so the CLI's `process.exit` does not skip the + escalation. A `kill` that throws ESRCH counts as exited; any other signal error, or no exit within + the final wait, is reported as `termination-unconfirmed` and never claimed as gone. + Pipe readers are cancelled after exit plus a 250 ms grace, so a descendant holding an inherited + pipe cannot hold the worker. A grace-cancelled pipe is incomplete and fails as `ssh-output`. +- Concurrency cap 3. Workers catch every error. A Child's failure, hang or crash never stops another + active worker and never changes the Home result. A queued Child starts no later than + `ceil(position / 3)` waves of (180 s + 3 s kill grace); the whole run is bounded by + `ceil(n / 3) × 183 s` plus the 5 s status read. +- Propagation runs only in the CLI process. The Home server runs no propagation code. +- Killing the local ssh does not necessarily stop a remote `ocx sync` already running; it finishes + or fails on the Child by itself (documented). + +### Output and exit + +- `--json`: in JSON mode `console.log` is routed to stderr for the whole runner, and stdout carries + exactly one document on every path except usage errors: + `{schema:"ocx.sync.fanout/1", home:{state:"synced"|"stale"|"skipped"|"failed", exit}, fanout:{state:"ran"|"disabled"|"not-applicable"|"failed", reason}, children:[{linkId, alias, state, reason, exit}]}`. + `home.state` is `stale` when a connected sync applied the last-known-good catalog. `fanout` is + `disabled` under `--local-only`, `not-applicable` on connected, pinned and link-less runs, and + `failed` with `link-store-unreadable` when `links.json` cannot be read or parsed (Home ok -> exit 6). + `children` is empty on connected, pinned, `--local-only` and link-less runs. A pinned mismatch is + `home.state "failed"`, `exit 5`, with the existing stderr lines unchanged. +- Usage errors exit 2 with stderr only. New flags are validated in the root preflight + (`src/cli/root.ts`) before shim auto-restore and any other preflight side effect, alongside the + existing pinned-flag check. +- Exit 7 is reserved for L1's sync/update mutex (`update-in-flight`, nothing changed); the runner + keeps the Home's local sync as one step that ends before fan-out starts, so that mutex can cover + the Home's own mutation without being held for the fan-out. +- Exit: Home failure keeps its code (1, 5, 7, or `process.exitCode`); Home ok and every Child `synced` + or `skipped` -> 0; any Child `failed` or `timed-out`, or `fanout.state failed` -> **6** (partial). +- Human mode prints the existing Home lines, then one line per Child: + ` (): [ ()]`. An unreadable link store prints the fixed stderr line + `Children were not synced: the Remote Link store could not be read.` + +### Capabilities + +- `ocx capabilities --json` gains a top-level `contracts: string[]` (always present, unaffected by + `--route`/`--mutating-only`; schemaVersion stays 1) from `CAPABILITY_CONTRACTS` in + `src/cli/capability-contracts.ts`, containing `sync.home-fanout/1`. `ocx capabilities --contracts + --json` prints only `{"schemaVersion":1,"contracts":[...]}`; `--contracts` without `--json` prints + one contract per line; combined with `--route` or `--mutating-only` it exits 64. Agreed with L1 and + L3 (same file and constant name; the later merge adds one array entry). + +## Diff-level plan + +1. NEW `src/cli/capability-contracts.ts`: `export const CAPABILITY_CONTRACTS = ["sync.home-fanout/1"] as const;` + with no imports. +2. MODIFY `src/cli/capabilities-command.ts`: `--contracts` handling, 64 combinations, `contracts` on + every JSON document including the unmatched-route one, usage `[--contracts]`; capabilities-base + entry for `capabilities` gains the flag. +3. NEW `src/cli/sync-flags.ts`: `parseSyncFanoutFlags(args)` -> `{localOnly, json}` or a usage error + (repeated flag). Called from `root.ts` preflight and the runner. +4. NEW `src/cli/sync-command.ts`: the `sync` runner moved out of `dispatch.ts` with existing branches + unchanged, as `runSyncCommand(deps)`; JSON-mode stdout routing; Home result capture; fan-out call; + rendering; exit combination. `dispatch.ts` keeps a one-line delegate. Export + `STALE_REMOTE_CATALOG_MESSAGE` (link form) and use it in the existing print. +5. NEW `src/cli/sync-fanout.ts`: `runHomeFanout(deps)` with injected `readStore`, `readLinkStatus`, + `runChild`, `resolvePlatform`, `now`, `deadlineMs`, `concurrency`; `classifyVersionProbe`, + `classifySyncResult`, `parseOcxVersion`, `fanoutExitCode`, `renderFanoutJson`, `renderFanoutHuman`, + bounded pool, `SYNC_FANOUT_PARTIAL_EXIT = 6`. +6. NEW `src/cli/sync-fanout-process.ts`: the owned-process runner described above; it also + implements `SshRunner.run` (timeouts clamped to the remaining deadline) for `requireRemotePlatformFramed`. +6a. MODIFY `src/link/ssh-argv.ts` / `src/link/remote-windows.ts`: `remotePinnedSyncArgv` and its + Windows script, sharing the candidate lists with `REMOTE_OCX_SCRIPT` / `windowsOcxArgv`. +6b. NEW `src/cli/sync-link-status.ts`: `readHomeLinkStatus(deadlineMs)` with the typed errors. +7. MODIFY help, registry and capabilities-base `sync` entries (usage + `ocx sync [--expect-link | --expect-hub-key ] [--local-only] [--json] [--restart-codex] [--restart-app-server-only]`, + flags, details, `json: "payload"`), including that fan-out never requests a Codex app or + app-server restart on a Child and that the Child's pinned sync may restart its own client runtime. +8. Docs: `docs-site/src/content/docs/reference/cli/lifecycle.md` (English), + `skills/ocx/references/05_remote_hub.md`, `04_failure_semantics.md` (exit 6), + `01_surface_lifecycle.md` if it lists sync flags, `structure/cli-management.md` and + `structure/remote-link.md`; regenerate `bun run skill:surface`; review `structure/manifest.json` + ownership for the new files. +9. Guards: extend the source scans in `tests/cli/cli-transport-honesty.test.ts` and + `tests/cli/cli-json-contract.test.ts` that read `dispatch.ts` to cover `sync-command.ts` too. +10. Tests, each new file registered in `scripts/test-layout/layout.json` and + `tests/fixtures/test-layout-expected.json`: + - `tests/cli/sync-fanout.test.ts`: classification tables (probe, sync, stale, mismatch reason + parsing incl. an unknown reason), version gate, client-initiated skip, each status-read error, + link-not-in-runtime, tunnel states, Home failed/skipped/thrown -> Children skipped, exit + combination, JSON shape, concurrency never above 3 with 7 Children, three hung Children delay a + fourth by at most one wave, a throwing worker is isolated. + - `tests/cli/sync-fanout-process.test.ts`: the owned runner against real child processes: a + process that ignores SIGTERM is SIGKILLed and gone before the call returns; a process that + exits 255; a descendant holding the stdout pipe is rejected as incomplete without holding the + call, and is reaped by the test; output over the cap. + - `tests/cli/sync-command-fanout.test.ts`: through the real CLI entry (`bun run src/cli/index.ts` + with a temp `OPENCODEX_HOME` and a fake `ssh` on PATH, no live runtime): `--local-only` makes no + ssh call; JSON mode prints exactly one document; usage errors exit 2 before preflight; a pinned + sync never fans out. + - `tests/clients/link-pinned-sync-argv.test.ts`: run the POSIX script with `sh` against fake + candidate directories (2.92.0 first -> exit 121 marker, never sync; 2.93.0 -> sync argv on the + same path with the `ocx-fanout:selected:2.93.0` marker and no other command run on that fake; + a fake whose `--version` writes endlessly while ignoring SIGPIPE, SIGXFSZ and its write errors is + killed by the watchdog, skipped, and its pid is gone; a broken first candidate followed by a + working one selects the second; a fake printing a valid version but exiting 17 is skipped, + never run; the capture file is gone after both a refusal and a successful exec; a zero-exit + version probe over 256 bytes is skipped; the stdout delimiter precedes the sync output; + `2.93.0-preview.1` -> refused; unparsable -> marker; a + candidate set that changes between two runs still pins the version check and the exec to one + path per run). Windows: extend the existing `windowsOcxArgv` execution tests + (`tests/clients/link-ssh-argv*.test.ts` and any PowerShell-executing test they use) to the new + script: selection order, fragmented output, delayed extra bytes past 256, a process that never + writes (deadline), version refusal, the exact argv handed to `Invoke-Native` (so + containment is kept), the marker line, and the size budget. + - Classification: stdout after the delimiter starting with `{` that is malformed, of an unknown schema, or two + documents fails `child-output-invalid`; empty stdout at exit 0 fails `child-output-invalid`; a + legacy Child printing the success sentence is `synced` and with the stale sentence is + `child-catalog-stale`; a document saying `synced` with exit 1 fails `child-sync-failed`; + a legacy 2.96.0 Child with and without the stale sentence; no marker -> `child-output-invalid`. + - Human-mode thrown Home sync: the one stderr line, then the original error and exit; with a + damaged `links.json` the original error still surfaces unchanged. + - `tests/cli/sync-link-status.test.ts`: stalled discovery, stalled headers, stalled body each end + at the deadline as `home-link-status-timeout`; 401/403; invalid DTO; no runtime. + - Home gate cases: refused refresh, thrown refresh, unchanged committed catalog, missing catalog. + - capabilities: `contracts` in every JSON output, `--contracts` output and the 64 combinations. + +## Verification + +`bun run typecheck`; the new test files plus the capabilities tests, `tests/ci-workflows/skill-ocx.test.ts`, +`tests/test-layout*.test.ts`, `tests/cli/cli-sync-expect-link.test.ts`, `tests/cli/cli-registry.test.ts`, +the extended guard tests, `tests/lab/core-lab-boundary.test.ts` and the file-size ratchet; +`bun run test:changed`; `bun run privacy:scan`; `bun run structure:check`; `bun run skill:surface:check`; +`bun run lint:gui` is not affected (no `gui/` change). No real service, desktop app, GOAT server or +Codex app is touched. + +## Risks + +- A powered-off Child whose tunnel state still reads `connected` costs up to the ssh ConnectTimeout + (10 s), reports `failed` and makes the run exit 6. +- A remote `ocx sync` can keep running after the Home kills its ssh on deadline. +- Stale detection depends on a sentence shared through one constant; a future Child that changes it + must keep the constant, and the classifier test pins it. diff --git a/docs-site/src/content/docs/fr/reference/cli/lifecycle.md b/docs-site/src/content/docs/fr/reference/cli/lifecycle.md index fcd71d1fe5d..a123bf34797 100644 --- a/docs-site/src/content/docs/fr/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/fr/reference/cli/lifecycle.md @@ -157,7 +157,11 @@ La section **OAuth reliability** indique si le stockage des identifiants est acc ## Synchronisation du catalogue -### `ocx sync [--restart-codex] [--restart-app-server-only]` +### `ocx sync [--expect-link | --expect-hub-key ] [--local-only] [--json] [--restart-codex] [--restart-app-server-only]` + +Sur un Home Remote Link, après la validation et l’enregistrement d’un catalogue à jour, `ocx sync` synchronise aussi les Enfants liés admissibles. `--local-only` désactive cette propagation. `--json` produit un seul document `ocx.sync.fanout/1` contenant le résultat du Home et l’état de chaque Enfant ; un Enfant ignoré indique la raison. Le code de sortie non nul du Home est renvoyé sans modification. Si le Home réussit, un Enfant en échec ou en délai dépassé, ou un registre de liens illisible, entraîne le code de sortie 6 ; sinon, la commande se termine avec le code 0, y compris lorsque des Enfants sont ignorés. En mode texte, le registre illisible produit un message sans chemin. Le code 7 est réservé à une mise à jour en cours. Si la synchronisation du Home lève une erreur en mode JSON, stdout conserve un seul document et stderr fournit un diagnostic assaini. + +La propagation ne demande jamais le redémarrage de l’application Codex ni d’un app-server sur un Enfant. Pour cela, utilisez GOAT ou exécutez `ocx sync --restart-codex` sur l’Enfant. La synchronisation épinglée de l’Enfant peut néanmoins redémarrer son propre runtime client OpenCodex après l’application de réglages Home modifiés. Si le Home interrompt son processus SSH local après un délai dépassé, une synchronisation distante déjà lancée peut continuer sur l’Enfant. > **Enfant Remote Link :** `ocx sync` applique aussi les réglages Codex du Home et, si le runtime client a démarré avant cette application, le redémarre même sans option de redémarrage. Si le redémarrage échoue, l'ancien runtime continue de servir et la commande se termine avec un code non nul. Les champs correspondants de `ocx status --json` et `ocx link status --json` sont décrits dans [Remote Link apply parity](/reference/cli/lifecycle/#remote-link-apply-parity) (en anglais). diff --git a/docs-site/src/content/docs/ja/reference/cli/lifecycle.md b/docs-site/src/content/docs/ja/reference/cli/lifecycle.md index f66b720fdbb..73020dc2fc0 100644 --- a/docs-site/src/content/docs/ja/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/ja/reference/cli/lifecycle.md @@ -164,7 +164,11 @@ ocx status --json ## カタログの同期 -### `ocx sync [--restart-codex] [--restart-app-server-only]` +### `ocx sync [--expect-link | --expect-hub-key ] [--local-only] [--json] [--restart-codex] [--restart-app-server-only]` + +Remote Link の Home では、最新のカタログが正常にコミットされた後、`ocx sync` は対象となるリンク済み Child にも同期を伝播します。`--local-only` はこの伝播を無効にします。`--json` は Home の結果と各 Child の状態を含む単一の `ocx.sync.fanout/1` 文書を出力し、スキップされた Child の理由も示します。Home 自体の終了コードが 0 以外の場合は、そのコードを変更せずに返します。Home が成功した場合、Child の失敗やタイムアウト、またはリンクストアの読み取り不能は終了コード 6 となり、それ以外は Child がスキップされた場合も含めて 0 で終了します。リンクストアを読み取れない場合、テキスト表示ではパスを含まないエラーを出します。コード 7 は更新処理中のために予約されています。JSON モードで Home の同期が例外を送出した場合も、stdout は単一の結果文書を保ち、stderr に無害化された診断を出力します。 + +伝播は Child の Codex アプリや app-server の再起動を要求しません。必要な場合は GOAT を使うか、その Child で `ocx sync --restart-codex` を実行してください。ただし、Child の固定先同期は、変更された Home 設定を適用した後、自身の OpenCodex クライアントランタイムを再起動することがあります。Home がタイムアウトしてローカルの SSH プロセスを停止しても、すでに開始されたリモート同期は Child 上で続くことがあります。 > **Remote Link Child:** `ocx sync` は Home の Codex 設定も適用し、クライアントランタイムがその適用より前に起動していた場合は、再起動フラグなしでもランタイムを再起動します。再起動に失敗した場合は以前のランタイムが動作し続け、コマンドは 0 以外で終了します。`ocx status --json` と `ocx link status --json` の関連フィールドは [Remote Link apply parity](/reference/cli/lifecycle/#remote-link-apply-parity)(英語)を参照してください。 diff --git a/docs-site/src/content/docs/ko/reference/cli/lifecycle.md b/docs-site/src/content/docs/ko/reference/cli/lifecycle.md index f1467d731dc..90512b785e1 100644 --- a/docs-site/src/content/docs/ko/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/ko/reference/cli/lifecycle.md @@ -246,7 +246,11 @@ single-flight/lock 파일을 만들 수 있는지, 건강하지 않은 OAuth 또 ## 카탈로그 동기화 -### `ocx sync [--restart-codex] [--restart-app-server-only]` +### `ocx sync [--expect-link | --expect-hub-key ] [--local-only] [--json] [--restart-codex] [--restart-app-server-only]` + +Remote Link Home에서는 최신 카탈로그가 성공적으로 커밋된 뒤 `ocx sync`가 조건을 충족하는 연결된 Child에도 동기화를 전파합니다. `--local-only`는 이 전파를 끕니다. `--json`은 Home 결과와 각 Child의 상태를 담은 단일 `ocx.sync.fanout/1` 문서를 출력하며, 건너뛴 Child의 이유도 표시합니다. Home 자체의 종료 코드가 0이 아니면 그 코드를 그대로 반환합니다. Home이 성공한 경우 Child 실패나 시간 초과 또는 링크 저장소를 읽을 수 없는 경우 종료 코드 6을 반환하며, 그 외에는 Child를 건너뛴 경우를 포함해 0으로 종료합니다. 링크 저장소를 읽을 수 없으면 텍스트 모드에서 경로가 없는 오류를 출력합니다. 코드 7은 업데이트 진행 중을 위해 예약되어 있습니다. JSON 모드에서 Home 동기화가 예외를 던져도 stdout에는 결과 문서 하나만 출력하고 stderr에는 안전하게 변환된 진단을 출력합니다. + +전파는 Child의 Codex 앱이나 app-server 재시작을 요청하지 않습니다. 재시작이 필요하면 GOAT를 사용하거나 해당 Child에서 `ocx sync --restart-codex`를 실행하세요. 다만 Child의 고정 대상 동기화는 변경된 Home 설정을 적용한 뒤 자체 OpenCodex 클라이언트 런타임을 재시작할 수 있습니다. Home이 시간 초과로 로컬 SSH 프로세스를 중지하더라도 이미 시작된 원격 동기화는 Child에서 계속될 수 있습니다. > **Remote Link Child:** `ocx sync`는 Home의 Codex 설정도 적용하며, 클라이언트 런타임이 그 적용보다 먼저 시작되었으면 재시작 플래그 없이도 런타임을 재시작합니다. 재시작이 실패하면 이전 런타임이 계속 서비스하고 명령은 0이 아닌 코드로 끝납니다. `ocx status --json`과 `ocx link status --json`의 관련 필드는 [Remote Link apply parity](/reference/cli/lifecycle/#remote-link-apply-parity)(영문)를 참고하세요. diff --git a/docs-site/src/content/docs/reference/cli/lifecycle.md b/docs-site/src/content/docs/reference/cli/lifecycle.md index bdb0fbc1d0f..97695eed0c7 100644 --- a/docs-site/src/content/docs/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/reference/cli/lifecycle.md @@ -538,7 +538,22 @@ See [v2 outcomes](/reference/cli/agents/#explicit-v2-target-and-outcome) and for target, scope and spending boundaries. A reset-grant status read can contact upstream status but never consumes or resumes a grant. -### `ocx sync [--restart-codex] [--restart-app-server-only]` +### `ocx sync [--expect-link | --expect-hub-key ] [--local-only] [--json] [--restart-codex] [--restart-app-server-only]` + +On a Remote Link Home, a successfully committed current catalog is also synced to eligible linked +Children. `--local-only` disables this fan-out. `--json` prints one `ocx.sync.fanout/1` result with +the Home outcome and each Child's state. A skipped Child is identified by its reason. The Home's +own nonzero exit code is returned unchanged. When the Home exits 0, a failed or timed-out Child or +an unreadable link store produces exit 6; otherwise the command exits 0, including when Children +are skipped. An unreadable link store produces a path-free error in human output. Exit 7 is reserved +for an update in flight. +If the Home sync throws in JSON mode, stdout still contains one result document and stderr gives a +sanitized failure message. + +Fan-out never requests a Codex app or app-server restart on a Child. Use GOAT or run +`ocx sync --restart-codex` on that Child if a Codex restart is needed. The Child's pinned sync may +still restart its own OpenCodex client runtime after applying changed Home settings. If the Home +times out and stops its local SSH process, a remote sync already running may continue on the Child. An explicitly requested restart also runs after a successful committed `config.toml` change, even if the catalog and cache bytes are unchanged. A configuration-only no-op, refusal, preflight, or rolled-back write does not trigger it. Without a restart flag, sync never automatically restarts Codex. diff --git a/docs-site/src/content/docs/ru/reference/cli/lifecycle.md b/docs-site/src/content/docs/ru/reference/cli/lifecycle.md index 2ac1b18c144..2ecf0d288cc 100644 --- a/docs-site/src/content/docs/ru/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/ru/reference/cli/lifecycle.md @@ -242,7 +242,11 @@ credential'ы и не выполняет repair. ## Синхронизация каталога -### `ocx sync [--restart-codex] [--restart-app-server-only]` +### `ocx sync [--expect-link | --expect-hub-key ] [--local-only] [--json] [--restart-codex] [--restart-app-server-only]` + +На Home Remote Link после успешной фиксации актуального каталога `ocx sync` также синхронизирует подходящие связанные дочерние машины. `--local-only` отключает эту рассылку. `--json` выводит один документ `ocx.sync.fanout/1` с результатом Home и состоянием каждой дочерней машины; для пропущенной машины указана причина. Ненулевой код выхода самого Home возвращается без изменений. Если Home завершился успешно, сбой или тайм-аут дочерней машины либо недоступное хранилище связей дают код выхода 6; в остальных случаях команда завершается с кодом 0, в том числе когда дочерние машины пропущены. В текстовом режиме сообщение о недоступном хранилище не содержит путь. Код 7 зарезервирован для выполняющегося обновления. Если синхронизация Home выбрасывает исключение в режиме JSON, stdout по-прежнему содержит один документ результата, а stderr — безопасно отформатированную диагностику. + +Рассылка никогда не запрашивает перезапуск приложения Codex или app-server на дочерней машине. Для этого используйте GOAT или выполните `ocx sync --restart-codex` на самой машине. При этом её синхронизация с закреплённым Home может перезапустить собственный клиентский рантайм OpenCodex после применения изменённых настроек Home. Если Home завершит локальный процесс SSH по тайм-ауту, уже начатая удалённая синхронизация может продолжиться на дочерней машине. > **Дочерняя машина Remote Link:** `ocx sync` также применяет настройки Codex с Home и, если клиентский рантайм запущен раньше этого применения, перезапускает его даже без флага перезапуска. Если перезапуск не удался, прежний рантайм продолжает работать, а команда завершается с ненулевым кодом. Соответствующие поля `ocx status --json` и `ocx link status --json` описаны в разделе [Remote Link apply parity](/reference/cli/lifecycle/#remote-link-apply-parity) (на английском). diff --git a/docs-site/src/content/docs/tr/reference/cli/lifecycle.md b/docs-site/src/content/docs/tr/reference/cli/lifecycle.md index 311c2436d39..4a95d62b8a2 100644 --- a/docs-site/src/content/docs/tr/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/tr/reference/cli/lifecycle.md @@ -240,7 +240,11 @@ Doctor asla kimlik bilgilerini değiştirmez veya onarımlar uygulamaz. ## Katalog senkronizasyonu -### `ocx sync [--restart-codex] [--restart-app-server-only]` +### `ocx sync [--expect-link | --expect-hub-key ] [--local-only] [--json] [--restart-codex] [--restart-app-server-only]` + +Remote Link Home üzerinde güncel katalog başarıyla kaydedildikten sonra `ocx sync`, uygun bağlı Child makineleri de eşitler. `--local-only` bu dağıtımı kapatır. `--json`, Home sonucunu ve her Child durumunu içeren tek bir `ocx.sync.fanout/1` belgesi yazdırır; atlanan Child için neden de belirtilir. Home'un kendi sıfırdan farklı çıkış kodu değiştirilmeden döndürülür. Home başarılı olduğunda bir Child hatası veya zaman aşımı ya da okunamayan bağlantı deposu çıkış kodu 6 üretir; diğer durumlarda, Child makineler atlandığında da komut 0 koduyla çıkar. Metin kipindeki okunamayan depo hatası dosya yolu içermez. Kod 7, sürmekte olan bir güncelleme için ayrılmıştır. JSON kipinde Home eşitlemesi hata fırlatırsa stdout yine tek sonuç belgesi içerir ve stderr güvenli biçimde gösterilen bir tanı verir. + +Dağıtım, bir Child üzerinde Codex uygulamasının veya app-server'ın yeniden başlatılmasını asla istemez. Bunun için GOAT kullanın veya Child üzerinde `ocx sync --restart-codex` çalıştırın. Bununla birlikte Child'ın sabitlenmiş eşitlemesi, değişen Home ayarlarını uyguladıktan sonra kendi OpenCodex istemci çalışma zamanını yeniden başlatabilir. Home zaman aşımında yerel SSH işlemini durdursa bile başlamış bir uzak eşitleme Child üzerinde devam edebilir. > **Remote Link Child:** `ocx sync` Home'un Codex ayarlarını da uygular ve istemci çalışma zamanı bu uygulamadan önce başlamışsa, yeniden başlatma bayrağı olmadan da onu yeniden başlatır. Yeniden başlatma başarısız olursa önceki çalışma zamanı hizmet vermeye devam eder ve komut sıfırdan farklı bir kodla çıkar. `ocx status --json` ve `ocx link status --json` içindeki ilgili alanlar için [Remote Link apply parity](/reference/cli/lifecycle/#remote-link-apply-parity) (İngilizce) bölümüne bakın. diff --git a/docs-site/src/content/docs/zh-cn/reference/cli/lifecycle.md b/docs-site/src/content/docs/zh-cn/reference/cli/lifecycle.md index 7c34574b37e..d547e59f933 100644 --- a/docs-site/src/content/docs/zh-cn/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/zh-cn/reference/cli/lifecycle.md @@ -160,7 +160,11 @@ ocx status --json ## 目录同步 -### `ocx sync [--restart-codex] [--restart-app-server-only]` +### `ocx sync [--expect-link | --expect-hub-key ] [--local-only] [--json] [--restart-codex] [--restart-app-server-only]` + +在 Remote Link Home 上,成功提交最新目录后,`ocx sync` 也会向符合条件的已连接 Child 同步。`--local-only` 可关闭此传播。`--json` 输出一个 `ocx.sync.fanout/1` 文档,包含 Home 的结果和每个 Child 的状态;被跳过的 Child 会注明原因。Home 自身的非零退出码会原样返回。Home 成功时,若 Child 失败、超时或链接存储不可读,命令以退出码 6 结束;其他情况均以 0 结束,包括 Child 被跳过时。文本模式下,链接存储不可读的错误不包含路径。退出码 7 保留给正在进行的更新。JSON 模式下如果 Home 同步抛出异常,stdout 仍只包含一个结果文档,stderr 则输出经过安全转义的诊断信息。 + +传播不会请求重启 Child 上的 Codex 应用或 app-server。如需重启,请使用 GOAT 或在该 Child 上运行 `ocx sync --restart-codex`。不过,Child 的固定目标同步在应用已更改的 Home 设置后,仍可能重启它自己的 OpenCodex 客户端运行时。Home 超时并停止本地 SSH 进程后,已开始的远程同步仍可能在 Child 上继续。 > **Remote Link Child:** `ocx sync` 还会应用 Home 的 Codex 设置;如果客户端运行时在该次应用之前启动,即使没有重启参数也会重启运行时。重启失败时,原有运行时继续提供服务,命令以非零状态退出。`ocx status --json` 和 `ocx link status --json` 中的相关字段见 [Remote Link apply parity](/reference/cli/lifecycle/#remote-link-apply-parity)(英文)。 diff --git a/docs-site/src/content/docs/zh-tw/reference/cli/lifecycle.md b/docs-site/src/content/docs/zh-tw/reference/cli/lifecycle.md index ebb9af1eb57..c76ec26e196 100644 --- a/docs-site/src/content/docs/zh-tw/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/zh-tw/reference/cli/lifecycle.md @@ -148,7 +148,11 @@ ocx status --json ## 目錄同步 -### `ocx sync [--restart-codex] [--restart-app-server-only]` +### `ocx sync [--expect-link | --expect-hub-key ] [--local-only] [--json] [--restart-codex] [--restart-app-server-only]` + +在 Remote Link Home 上成功提交最新目錄後,`ocx sync` 也會向符合條件的已連結 Child 同步。`--local-only` 可停用這個傳播。`--json` 會輸出單一 `ocx.sync.fanout/1` 文件,包含 Home 的結果與各 Child 的狀態;遭略過的 Child 也會顯示原因。Home 自身的非零結束碼會原樣回傳。Home 成功時,若 Child 失敗、逾時或連結儲存區無法讀取,指令以結束碼 6 結束;其他情況均以 0 結束,包括 Child 遭略過時。文字模式下,連結儲存區無法讀取的錯誤不包含路徑。結束碼 7 保留給進行中的更新。JSON 模式下若 Home 同步擲出例外,stdout 仍只包含一份結果文件,stderr 則輸出經安全轉義的診斷訊息。 + +傳播不會要求重新啟動 Child 上的 Codex 應用程式或 app-server。若需要重新啟動,請使用 GOAT 或在該 Child 執行 `ocx sync --restart-codex`。不過,Child 的固定目標同步在套用變更後的 Home 設定時,仍可能重新啟動它自己的 OpenCodex 用戶端執行階段。Home 逾時並停止本機 SSH 程序後,已開始的遠端同步仍可能在 Child 上繼續。 > **Remote Link Child:** `ocx sync` 也會套用 Home 的 Codex 設定;如果用戶端執行階段在該次套用之前啟動,即使沒有重新啟動旗標也會重新啟動執行階段。重新啟動失敗時,原有執行階段會繼續提供服務,指令以非零狀態結束。`ocx status --json` 與 `ocx link status --json` 的相關欄位請見 [Remote Link apply parity](/reference/cli/lifecycle/#remote-link-apply-parity)(英文)。 diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index 3285320c8f1..bf9619797cc 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -2,7 +2,7 @@ "version": 1, "root": "tests", "explicitShards": ["layout-file-identity.json", "layout-clients.json", "layout-codex-collision.json", "layout-agent-assertion.json", "layout-chat.json", "layout-replay.json", "layout-adapters.json", "layout-jev.json", "layout-workbuddy.json", "layout-combos.json", "layout-credit-renewal.json", "layout-server-inbound.json", "layout-providers.json", "layout-responses.json", "layout-exec-boundary.json", "layout-persistent-dashboard.json", "layout-start-ownership.json", "layout-config.json", "layout-kiro-usage.json", "layout-usage.json"], - "explicit": { "codex-installation-acl.test.ts": "codex-integration", "codex-installation-id.test.ts": "codex-integration", "codex-installation-wire.test.ts": "codex-integration", "codex-installation-failover.test.ts": "responses", "service-desktop-recovery.test.ts": "service", "catalog-omit-disabled-native.test.ts": "codex-integration", "provider-input-modalities.test.ts": "providers", "combo-description.test.ts": "routing", "combo-description-catalog.test.ts": "codex-integration", "codex-provider-routing.test.ts": "codex-integration", "config-native-reasoning-retention.test.ts": "config", "server-native-reasoning-retention-merge.test.ts": "server", "server-native-reasoning-retention.test.ts": "server", "config-workflow-budget.test.ts": "config", "server-workflow-budget-settings.test.ts": "server", "responses-retained-reasoning-stream-recovery.test.ts": "responses", "openai-native-hosted-search-history.test.ts": "adapters/openai", "responses-native-compact-search-history.test.ts": "responses", "config-hosted-search-projection.test.ts": "config", "gcp-credential-boundary.test.ts": "adapters/google", "gcp-sa-marker.test.ts": "adapters/google", "gcp-sa-adapter.test.ts": "adapters/google", "management-gcp-credential-input.test.ts": "server", "codex-preserve-signed-in.test.ts": "codex-integration", "cli-account-preservation.test.ts": "cli", "cli-provider-list-active.test.ts": "cli", "service-state-isolation.test.ts": "service", "compaction-history-framing.test.ts": "responses", "catalog-native-max-context.test.ts": "codex-integration", "protocol-argon-thought-boundary.test.ts": "responses", "service-log.test.ts": "service", "messages-native-empty-inline.test.ts": "claude-integration", "catalog-auto-review-override.test.ts": "codex-integration", "management-auto-review-settings.test.ts": "server", "management-auto-review-auth.test.ts": "server", "prefer-model-alias-ids.test.ts": "server", "responses-mimo-envelope.test.ts": "responses", "responses-call-id-linkage.test.ts": "responses", "bridge-terminal-refusal.test.ts": "adapters", "loop-terminal-refusal.test.ts": "images", "web-search-terminal-refusal.test.ts": "web-search", "combo-terminal-refusal.test.ts": "routing", "server-terminal-refusal-wiring.test.ts": "server", "incomplete-reason-normalization.test.ts": "responses", "advisor-retention.test.ts": "advisor", "responses-native-key-cooldown.test.ts": "responses", "responses-run-turn-key-readmission.test.ts": "responses", "qoder-spawn-readmission.test.ts": "adapters", "api-key-selection-cooldown.test.ts": "providers", "api-key-auto-pause-distribution.test.ts": "providers", "explicit-key-pause-oauth-boundary.test.ts": "providers", "server-chat-native-key-selection.test.ts": "server", "compact-key-selection.test.ts": "responses", "messages-native-key-selection.test.ts": "claude-integration", "coding-agent-windows-dispatch.test.ts": "adapters", "coding-agent-native-empty-argv.test.ts": "windows", + "explicit": { "sync-fanout.test.ts": "cli", "sync-command-fanout.test.ts": "cli", "link-pinned-sync-argv.test.ts": "clients", "sync-link-status.test.ts": "cli", "sync-fanout-process.test.ts": "cli", "codex-installation-acl.test.ts": "codex-integration", "codex-installation-id.test.ts": "codex-integration", "codex-installation-wire.test.ts": "codex-integration", "codex-installation-failover.test.ts": "responses", "service-desktop-recovery.test.ts": "service", "catalog-omit-disabled-native.test.ts": "codex-integration", "provider-input-modalities.test.ts": "providers", "combo-description.test.ts": "routing", "combo-description-catalog.test.ts": "codex-integration", "codex-provider-routing.test.ts": "codex-integration", "config-native-reasoning-retention.test.ts": "config", "server-native-reasoning-retention-merge.test.ts": "server", "server-native-reasoning-retention.test.ts": "server", "config-workflow-budget.test.ts": "config", "server-workflow-budget-settings.test.ts": "server", "responses-retained-reasoning-stream-recovery.test.ts": "responses", "openai-native-hosted-search-history.test.ts": "adapters/openai", "responses-native-compact-search-history.test.ts": "responses", "config-hosted-search-projection.test.ts": "config", "gcp-credential-boundary.test.ts": "adapters/google", "gcp-sa-marker.test.ts": "adapters/google", "gcp-sa-adapter.test.ts": "adapters/google", "management-gcp-credential-input.test.ts": "server", "codex-preserve-signed-in.test.ts": "codex-integration", "cli-account-preservation.test.ts": "cli", "cli-provider-list-active.test.ts": "cli", "service-state-isolation.test.ts": "service", "compaction-history-framing.test.ts": "responses", "catalog-native-max-context.test.ts": "codex-integration", "protocol-argon-thought-boundary.test.ts": "responses", "service-log.test.ts": "service", "messages-native-empty-inline.test.ts": "claude-integration", "catalog-auto-review-override.test.ts": "codex-integration", "management-auto-review-settings.test.ts": "server", "management-auto-review-auth.test.ts": "server", "prefer-model-alias-ids.test.ts": "server", "responses-mimo-envelope.test.ts": "responses", "responses-call-id-linkage.test.ts": "responses", "bridge-terminal-refusal.test.ts": "adapters", "loop-terminal-refusal.test.ts": "images", "web-search-terminal-refusal.test.ts": "web-search", "combo-terminal-refusal.test.ts": "routing", "server-terminal-refusal-wiring.test.ts": "server", "incomplete-reason-normalization.test.ts": "responses", "advisor-retention.test.ts": "advisor", "responses-native-key-cooldown.test.ts": "responses", "responses-run-turn-key-readmission.test.ts": "responses", "qoder-spawn-readmission.test.ts": "adapters", "api-key-selection-cooldown.test.ts": "providers", "api-key-auto-pause-distribution.test.ts": "providers", "explicit-key-pause-oauth-boundary.test.ts": "providers", "server-chat-native-key-selection.test.ts": "server", "compact-key-selection.test.ts": "responses", "messages-native-key-selection.test.ts": "claude-integration", "coding-agent-windows-dispatch.test.ts": "adapters", "coding-agent-native-empty-argv.test.ts": "windows", "stop-restore-history-ownership.test.ts": "service", "cli-stop-refusal-transport.test.ts": "cli", "service-proxy-env.test.ts": "service", "openai-chat-standalone-bare-block.test.ts": "adapters/openai", diff --git a/scripts/test-layout/seeds.json b/scripts/test-layout/seeds.json index b28643d5b05..1c356fc21d7 100644 --- a/scripts/test-layout/seeds.json +++ b/scripts/test-layout/seeds.json @@ -115,7 +115,8 @@ "^aside-profile(?!s-routes)", "^cline-(?:client|writer)(?:-|[.])", "^opencode-kilo-", - "^(?:desktop|omp|pi|prime|remote|sync)-", + "^(?:desktop|omp|pi|prime|remote)-", + "^sync-(?!fanout(?:-process)?\\.test\\.ts$|link-status\\.test\\.ts$|command-fanout\\.test\\.ts$)", "^command-code-client(?:-|[.])" ] }, diff --git a/skills/ocx/references/01_surface_lifecycle.md b/skills/ocx/references/01_surface_lifecycle.md index 5ea0ee479b3..ab9ed73b5bd 100644 --- a/skills/ocx/references/01_surface_lifecycle.md +++ b/skills/ocx/references/01_surface_lifecycle.md @@ -77,6 +77,7 @@ Drives no management route. | Flag | Value | Meaning | |---|---|---| | `--json` | boolean | Emit the full capability table as JSON. | +| `--contracts` | boolean | List supported versioned contracts. | | `--mutating-only` | boolean | Restrict output to capabilities that mutate state. | | `--route` | string | Show which capabilities drive a management route. | @@ -84,11 +85,11 @@ Drives no management route. ### `ocx sync` -Usage: `ocx sync [--expect-link | --expect-hub-key ] [--restart-codex] [--restart-app-server-only]` +Usage: `ocx sync [--expect-link | --expect-hub-key ] [--local-only] [--json] [--restart-codex] [--restart-app-server-only]` Synchronize client catalogs, including Aside profiles through the running server's mutation owner. -State-changing: yes. JSON mode: `none`. +State-changing: yes. JSON mode: `payload`. | Method | Route | |---|---| @@ -96,6 +97,8 @@ State-changing: yes. JSON mode: `none`. | Flag | Value | Meaning | |---|---|---| +| `--local-only` | boolean | Do not fan out the Home sync to linked Children. | +| `--json` | boolean | Emit the sync fan-out result as JSON. | | `--restart-codex` | boolean | Restart the Codex app-servers and fully quit and relaunch the Codex desktop app after a catalog, cache, or changed configuration write, on macOS, Linux and Windows. | | `--restart-app-server-only` | boolean | Restart only the Codex app-servers and leave the desktop app running; wins over --restart-codex when both are given. | | `--restart-desktop-app` | boolean | Deprecated alias of --restart-codex. | @@ -103,6 +106,7 @@ State-changing: yes. JSON mode: `none`. | `--expect-hub-key` | string | Sync only when this machine is a hub client connected with this API key id; otherwise exit 5 with nothing changed. | - The Aside refresh uses the live server; other catalog synchronization also performs local work. +- A current Home catalog fans out to linked Children. Fan-out never requests a Codex app or app-server restart on a Child; use GOAT or ocx sync --restart-codex there. Applying changed Home settings may restart the Child's own OpenCodex client runtime. - --expect-link/--expect-hub-key are checked under the lock that selects the sync path. A mismatch writes nothing, never falls back to local providers, exits 5, and ends stderr with {"phase":"child_link_mismatch"|"hub_client_mismatch","reason":...}; reasons are disconnected, invalid_state, disconnect_pending, pending_operation, hub_client, link_client, other_link and other_key. Usage errors exit 2. ### `ocx stop` diff --git a/skills/ocx/references/04_failure_semantics.md b/skills/ocx/references/04_failure_semantics.md index 642b83e5642..66a3ad38209 100644 --- a/skills/ocx/references/04_failure_semantics.md +++ b/skills/ocx/references/04_failure_semantics.md @@ -14,6 +14,8 @@ exit contract. Its common mappings and the main exceptions are: | 64 | usage validation in `capabilities`, `ready`, `resolve` | fix arguments; no discovery/request for invalid input | | 4 | HTTP 404 — the named account, provider, key, or route does not exist | no | | 5 | HTTP 409 — conflict; a lock is held or state moved under you | inspect first; stale baselines require review | +| 6 | `ocx sync` completed the Home step but a Child failed or timed out, or the link store was unreadable | inspect the fan-out result | +| 7 | reserved for an update in flight during sync | wait for the update, then retry | | 1 | everything else: transport failure, 5xx, unexpected errors | depends on `reason` | Two consequences worth internalizing: diff --git a/skills/ocx/references/05_remote_hub.md b/skills/ocx/references/05_remote_hub.md index 14e89f9c220..001a6a38912 100644 --- a/skills/ocx/references/05_remote_hub.md +++ b/skills/ocx/references/05_remote_hub.md @@ -321,6 +321,12 @@ To sync only while that reading still holds, pass what you read back to sync: relinked in between, the sync changes nothing and exits 5 with a JSON `phase` line on stderr ([04_failure_semantics.md](04_failure_semantics.md#a-pinned-sync-that-refuses-exit-5)). +On the Home, `ocx sync` fans out only after it commits a current catalog. Use `--local-only` +to suppress propagation and `--json` to inspect Home and Child results. Fan-out never asks a Child +to restart a Codex app or app-server; use GOAT or `ocx sync --restart-codex` on that Child. Its +pinned sync can still restart its own OpenCodex client runtime after applying changed Home settings. +A Child sync already running can continue after the Home times out its local SSH process. + ## Key rotation is a two-step commit Starting a rotation issues the new key while **the old key stays valid**. The dashboard diff --git a/src/cli/capabilities-base.ts b/src/cli/capabilities-base.ts index da19fc790e2..0467719de70 100644 --- a/src/cli/capabilities-base.ts +++ b/src/cli/capabilities-base.ts @@ -221,6 +221,7 @@ export const CAPABILITIES: readonly Capability[] = [ routes: [], flags: [ { name: "--json", value: "boolean", summary: "Emit the full capability table as JSON." }, + { name: "--contracts", value: "boolean", summary: "List supported versioned contracts." }, { name: "--mutating-only", value: "boolean", summary: "Restrict output to capabilities that mutate state." }, { name: "--route", value: "string", summary: "Show which capabilities drive a management route." }, ], @@ -752,6 +753,8 @@ export const CAPABILITIES: readonly Capability[] = [ summary: "Synchronize client catalogs, including Aside profiles through the running server's mutation owner.", routes: [{ method: "POST", path: "/api/client-integrations/aside/sync" }], flags: [ + { name: "--local-only", value: "boolean", summary: "Do not fan out the Home sync to linked Children." }, + { name: "--json", value: "boolean", summary: "Emit the sync fan-out result as JSON." }, { name: "--restart-codex", value: "boolean", summary: "Restart the Codex app-servers and fully quit and relaunch the Codex desktop app after a catalog, cache, or changed configuration write, on macOS, Linux and Windows." }, { name: "--restart-app-server-only", value: "boolean", summary: "Restart only the Codex app-servers and leave the desktop app running; wins over --restart-codex when both are given." }, { name: "--restart-desktop-app", value: "boolean", summary: "Deprecated alias of --restart-codex." }, @@ -759,12 +762,13 @@ export const CAPABILITIES: readonly Capability[] = [ { name: "--expect-hub-key", value: "string", summary: "Sync only when this machine is a hub client connected with this API key id; otherwise exit 5 with nothing changed." }, ], mutates: true, - json: "none", + json: "payload", details: [ "The Aside refresh uses the live server; other catalog synchronization also performs local work.", + "A current Home catalog fans out to linked Children. Fan-out never requests a Codex app or app-server restart on a Child; use GOAT or ocx sync --restart-codex there. Applying changed Home settings may restart the Child's own OpenCodex client runtime.", "--expect-link/--expect-hub-key are checked under the lock that selects the sync path. A mismatch writes nothing, never falls back to local providers, exits 5, and ends stderr with {\"phase\":\"child_link_mismatch\"|\"hub_client_mismatch\",\"reason\":...}; reasons are disconnected, invalid_state, disconnect_pending, pending_operation, hub_client, link_client, other_link and other_key. Usage errors exit 2.", ], - usage: "ocx sync [--expect-link | --expect-hub-key ] [--restart-codex] [--restart-app-server-only]", + usage: "ocx sync [--expect-link | --expect-hub-key ] [--local-only] [--json] [--restart-codex] [--restart-app-server-only]", }, { command: ["agent","subagents","force"], diff --git a/src/cli/capabilities-command.ts b/src/cli/capabilities-command.ts index e2787549354..952e38807c6 100644 --- a/src/cli/capabilities-command.ts +++ b/src/cli/capabilities-command.ts @@ -13,6 +13,7 @@ import { type Capability, } from "./capabilities"; import { takeFlag } from "./runtime-api"; +import { CAPABILITY_CONTRACTS } from "./capability-contracts"; function takeValueFlag(args: string[], flag: string): string | undefined { // Order-independent by construction: scan for the flag anywhere in argv rather than @@ -50,13 +51,20 @@ export async function runCapabilities(argv: string[]): Promise { const args = [...argv]; const json = takeFlag(args, "--json"); const mutatingOnly = takeFlag(args, "--mutating-only"); + const contracts = takeFlag(args, "--contracts"); const route = takeValueFlag(args, "--route"); - if (args.length > 0 || (route !== undefined && route.trim().length === 0)) { - console.error("Usage: ocx capabilities [--json] [--mutating-only] [--route ]"); + if (args.length > 0 || (route !== undefined && route.trim().length === 0) || (contracts && (mutatingOnly || route !== undefined))) { + console.error("Usage: ocx capabilities [--json] [--contracts] [--mutating-only] [--route ]"); return 64; } + if (contracts) { + if (json) console.log(JSON.stringify({ schemaVersion: 1, contracts: CAPABILITY_CONTRACTS })); + else for (const contract of CAPABILITY_CONTRACTS) console.log(contract); + return 0; + } + let selected: readonly Capability[] = route === undefined ? CAPABILITIES : capabilitiesForRoute(route); if (mutatingOnly) selected = selected.filter(cap => cap.mutates); @@ -64,7 +72,7 @@ export async function runCapabilities(argv: string[]): Promise { // An unmatched route is a real answer, not an error: the route may be exempt or may // not exist. Say which, rather than exiting 0 with silence. if (json) { - console.log(JSON.stringify({ schemaVersion: 1, route, capabilities: [] }, null, 2)); + console.log(JSON.stringify({ schemaVersion: 1, contracts: CAPABILITY_CONTRACTS, route, capabilities: [] }, null, 2)); } else { console.error(`No CLI capability drives ${route}.`); } @@ -74,6 +82,7 @@ export async function runCapabilities(argv: string[]): Promise { if (json) { console.log(JSON.stringify({ schemaVersion: 1, + contracts: CAPABILITY_CONTRACTS, ...(route === undefined ? {} : { route }), capabilities: selected.map(cap => ({ command: cap.command, diff --git a/src/cli/capability-contracts.ts b/src/cli/capability-contracts.ts new file mode 100644 index 00000000000..ed7ef7e988b --- /dev/null +++ b/src/cli/capability-contracts.ts @@ -0,0 +1 @@ +export const CAPABILITY_CONTRACTS = ["sync.home-fanout/1"] as const; diff --git a/src/cli/dispatch.ts b/src/cli/dispatch.ts index d4d3f794166..e4c405fddba 100644 --- a/src/cli/dispatch.ts +++ b/src/cli/dispatch.ts @@ -15,7 +15,6 @@ import { uninstallArgsError, type CliHead } from "./root"; import type { ReadyArgs } from "./ready"; import type { LivenessIo, LiveProxy } from "../server/proxy-liveness"; import type { OcxConfig } from "../types"; -import type { OwnedIntegrationRefreshOutcome } from "../integrations/owned-refresh"; import { hasHelpFlag, printSubcommandUsage, printUsage } from "./help"; import { printUnknownCommand } from "./help-recovery"; import { @@ -30,9 +29,9 @@ import { syncModelsToCodex } from "../codex/sync"; import { collectOrcaCodexHomeDiagnostic } from "../codex/home"; import { restoreNativeCodexAsync, type CodexNativeRestoreResult } from "../codex/inject"; import { stripGrokConfig } from "../grok/inject"; -import { handleRestartScopeAfterWrite, readRestartScope, type RestartScope } from "./restart-scope"; +import { handleRestartScopeAfterWrite, readRestartScope } from "./restart-scope"; import { normalizeUpdateChannel, runGuiUpdateWorker } from "../update/job"; -import { isJsonOption, takeFlag, terminalSafeError, terminalSafeText } from "./runtime-api"; +import { isJsonOption, takeFlag } from "./runtime-api"; import { printStopSummary, type StopOutcome } from "./stop-report"; import { parseStopApproval, type StopApproval } from "./stop-approval"; import type { ResolveArgs } from "./resolve"; @@ -404,171 +403,7 @@ const commandRunners: Record = { const { handleLogoutCommand } = await import("./logout-command"); return handleLogoutCommand(deps.args.slice(1), { findLiveProxy: deps.findLiveProxy }); }, - sync: async deps => { - const syncArgs = deps.args.slice(1); - // #7694: parse the expected identity before anything else reads or writes state. - const { parseSyncExpectation, reportSyncExpectationMismatch, SYNC_EXPECTATION_USAGE_EXIT } = await import("./sync-expectation"); - const parsedExpectation = parseSyncExpectation(syncArgs); - if (!parsedExpectation.ok) { - console.error(parsedExpectation.message); - return SYNC_EXPECTATION_USAGE_EXIT; - } - const expectation = parsedExpectation.expectation; - const restartScope = readRestartScope(syncArgs, console); - // The wire field keeps APP-SERVER-ONLY meaning and is deliberately not widened. A - // remote hub must not end a local user's conversations because a field name acquired - // a wider meaning underneath it; the maintainer decision widened a local CLI flag and - // said nothing about remote callers. syncConnectedClient ignores it either way. - const restartCodex = restartScope.appServers; - const { readClientConnectionState } = await import("../client/state"); - const clientState = readClientConnectionState(); - // With an expectation the unlocked read decides nothing: the connected sync re-reads under its - // lock and refuses there, so a state that changes in between can never reach the local path. - if (!expectation && (clientState.kind === "invalid" || clientState.kind === "mismatched")) { - console.error(`Client state is ${clientState.kind}: ${clientState.reason}`); - return 1; - } - if (expectation || clientState.kind === "connected") { - try { - const { syncConnectedClient } = await import("../client/connect"); - const result = await syncConnectedClient(expectation ? { restartCodex, expect: expectation } : { restartCodex }); - if (expectation) { - // The root preflight skipped the shim repair for a pinned sync; the identity held, so - // run it now, as an unpinned sync would have. - const { runCodexShimAutoRestoreAsync } = await import("./codex-shim-autorestore"); - await runCodexShimAutoRestoreAsync(); - } - // The connection the sync ran under, read inside its lock; the read above may be stale. - const link = result.connection.transport === "link"; - console.log(result.stale - ? `${link ? "Home" : "Hub"} unavailable; retained and applied the last-known-good remote catalog (stale).` - : link ? "Remote Link Home catalog synchronized." : "Remote hub catalog synchronized."); - if (result.homeSettings) { - const { describeHomeCodexSettings } = await import("../link/codex-settings"); - const settings = result.homeSettings; - if (settings.source === "local") { - console.log(`Codex settings: kept this machine's local values (${terminalSafeText(settings.reason)}).`); - } else { - console.log(settings.source === "home" - ? `Codex settings applied from Home ${terminalSafeText(settings.document.home.name)}:` - : `Codex settings applied from the last recorded Home read (${terminalSafeText(settings.reason)}):`); - for (const line of describeHomeCodexSettings(settings.document.settings)) console.log(` ${terminalSafeText(line)}`); - } - } - await handleConnectedSyncCatalogWrite(result, restartScope); - if (result.applyRecordFailed) { - console.error("The Home's Codex settings were applied, but the apply record could not be written; the client runtime was not restarted. Run 'ocx sync' again."); - process.exitCode = 1; - } - // OCX-6: a link Child's runtime must have started after the apply it serves under. - if (link && result.appliedRecord) { - const { applyRestartMessage, restartRuntimeAfterApply } = await import("./link-apply-restart"); - const { sameClientConnectionOwner } = await import("../client/state"); - const applied = result.connection; - const outcome = await restartRuntimeAfterApply(result.appliedRecord, { - restart: startWhenStopped => deps.handleProxyRestart(startWhenStopped), - recoveryStart: recovering => deps.handleRestartStartWhenStopped(recovering), - connectionUnchanged: () => { - const current = readClientConnectionState(); - return current.kind === "connected" && sameClientConnectionOwner(current.value, applied) - && current.value.link?.linkId === applied.link?.linkId; - }, - }); - const message = applyRestartMessage(outcome); - if (outcome.kind === "failed" || outcome.kind === "connection-changed") { - console.error(message); - process.exitCode = 1; - } else { - console.log(message); - } - } - // `process.exitCode` rather than a literal 0, for the same reason every other - // runner does it (tests/cli/cli-transport-honesty.test.ts): the catalog-write helper - // drives app-server restarts, and one of those recording a failure must not be - // erased by the value this runner returns. It reads 0 on the ordinary path. Node - // types it as `number | string`; only a numeric code means anything here. - return typeof process.exitCode === "number" ? process.exitCode : 0; - } catch (error) { - const { ClientSyncExpectationError } = await import("../client/sync-expectation"); - if (error instanceof ClientSyncExpectationError) return reportSyncExpectationMismatch(error, console); - // The refresh path reaches the same hub catalog `ocx connect` validates, so a rejected - // reasoning level arrives here as hub-supplied text. Rendering it through the shared - // terminal boundary is what keeps the routine refresh from forging output; the domain - // error itself is left alone for callers that inspect it. - console.error(`Connected sync failed without local fallback: ${terminalSafeError(error).message}`); - return 1; - } - } - const live = await deps.findLiveProxy(); - const synced = await syncModelsToCodex( - live?.port, - undefined, - undefined, - undefined, - { catalogEvenWhenNotInjected: true }, - ); - let code = 0; - if (synced.status === "skipped") { - console.log(synced.skippedReason === "hub-gated" - ? `${HUB_GATED_SKIP_MESSAGE} sync skipped and no Codex files changed.` - : "Codex integration is OFF; sync skipped and no Codex files changed."); - } else if (synced.status === "catalog-only") { - // Explicit sync with the integration OFF still refreshes the catalog/cache - // for side profiles that consume the proxy without injection. - console.log(synced.message ?? "Codex integration is OFF; catalog refreshed, Codex config untouched."); - if (!synced.ok) code = 1; - } else if (!synced.ok) { - code = 1; - console.error("Codex sync did not complete. Fix the reported Codex config issue and retry."); - } - // Catalog/model-cache writes retain their warning/restart handling. This is - // deliberately not an `else`: refreshCodexModelCatalog runs before injectCodexConfig, - // so a sync can fail (`ok: false`) after the catalog was already rewritten — which is - // exactly when a long-lived app-server is holding the stale list. - // A configuration-only change also needs a reload, but only when explicitly - // requested. A successful no-op or refused write is never restart authority. - const requestedConfigRestart = (restartScope.appServers || restartScope.desktopApp) - && synced.ok && synced.configChanged === true; - if (synced.catalogWritten || synced.cacheSynced || requestedConfigRestart) { - await handleRestartScopeAfterWrite(restartScope, console); - } - // `ocx sync` is a direct CLI path; it does not call the management - // `/api/sync` route. Refresh already-connected file integrations here too, - // after Codex has published the catalog that supplies its capabilities. - if (synced.status !== "refused") { - const results: OwnedIntegrationRefreshOutcome[] = []; - if (live) { - try { - const config = deps.loadConfig(); - const { refreshOwnedCatalogIntegrations } = await import("../integrations/catalog-refresh"); - results.push(...await refreshOwnedCatalogIntegrations({ - models: async () => { - const { loadExportModels } = await import("../server/management/model-rows"); - return loadExportModels(config); - }, - config, - port: live.port, - }, ["mcode", "pi", "raycast", "omo", "cline", "commandcode", "droid", "opencode", "kilo", "qoder", "qoder-cn", "workbuddy", "workbuddy-ai", "hermes", "t3code"])); - } catch (error) { - console.warn(`Client integrations were not refreshed: ${error instanceof Error ? error.message : String(error)}`); - } - } - // Even without a live proxy, report why Aside could not sync. Its server - // owner is never bypassed, and another client's failure cannot hide it. - try { - const { refreshAsideProfilesThroughServer } = await import("./aside-profiles"); - results.push(...await refreshAsideProfilesThroughServer({ findLiveProxy: async () => live })); - } catch (error) { - console.warn(`Aside profiles were not refreshed: ${error instanceof Error ? error.message : String(error)}`); - } - for (const result of results) { - const label = result.profileId === undefined ? result.client : `${result.client}:${result.profileId}`; - if (result.changed) console.log(`${label} integration refreshed from the current catalog.`); - else if (result.reason) console.warn(`${label} integration was not refreshed: ${result.reason}${result.residual ? " Recovery did not finish." : ""}${result.snapshotPath ? ` Backup: ${result.snapshotPath}` : ""}`); - } - } - return code; - }, + sync: async deps => (await import("./sync-command")).runSyncCommand(deps), v2: async deps => { const { cmdV2 } = await import("./v2"); return await cmdV2(deps.args.slice(1), { runtimeApi: { findLiveProxy: deps.findLiveProxy } }, async () => (await deps.findLiveProxy())?.port); @@ -1254,14 +1089,6 @@ export async function dispatchCommand(head: CliHead, deps: CliDispatchDeps): Pro return await runner(deps); } -async function handleConnectedSyncCatalogWrite( - result: { catalogWritten: boolean; cacheSynced: boolean }, - scope: RestartScope, -): Promise { - if (!result.catalogWritten && !result.cacheSynced) return; - await handleRestartScopeAfterWrite(scope, console); -} - async function reconcileClientJournalBeforeLifecycle( state: ClientConnectionState, ): Promise { diff --git a/src/cli/help.ts b/src/cli/help.ts index c498abab8c7..67780c76753 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -49,7 +49,7 @@ Usage: ocx connect Connect this machine to a remote OpenCodex hub (credential via stdin) ocx remote-workspace Pair/run an OCX-only remote execution computer ocx disconnect Restore local state and clear the hub connection - ocx sync [--restart-codex] Fetch models from providers and inject into Codex config + ocx sync [--local-only] [--json] [--restart-codex] Sync models and linked Children --expect-link | --expect-hub-key : only from that Home/hub key (exit 5 otherwise) ocx sync-cache [--restart-codex] Refresh Codex's model cache from the active catalog @@ -72,7 +72,7 @@ Usage: ocx restart Stop and restart the proxy ocx v2 multi_agent_v2 surface (status|on|off|mode|keep-native-v1|threads|mode-hint) ocx health [--json] Check proxy health (exit 0=healthy, 1=not) - ocx capabilities [--json] List declared capabilities and the API routes they drive + ocx capabilities [--json] [--contracts] List capabilities and contracts ocx ready [--json] [--wait [--timeout ]] Check post-sync readiness (exit 0 only when ready) ocx resolve [--json] Config home, effective port, and liveness (JSON for shells) ocx provider Providers, connectivity, quota, and selected models diff --git a/src/cli/link.ts b/src/cli/link.ts index 213b7d9d58f..cdd57b09897 100644 --- a/src/cli/link.ts +++ b/src/cli/link.ts @@ -134,7 +134,7 @@ function validatePeer(value: unknown, index: number): LinkPeerStatus { }; } -function validateStatus(value: unknown): LinkStatusPayload { +export function validateStatus(value: unknown): LinkStatusPayload { if (!isRecord(value)) throw new Error("invalid link API response: status object"); assertKeys(value, ["role", "listener", "links", "child"], ["local"], "status"); if (value.role !== "standalone" && value.role !== "home" && value.role !== "child") { diff --git a/src/cli/registry.ts b/src/cli/registry.ts index bfab1a29715..0fa007974ae 100644 --- a/src/cli/registry.ts +++ b/src/cli/registry.ts @@ -183,9 +183,11 @@ export const CLI_COMMANDS: CliCommandEntry[] = [ }, { name: "sync", - usage: "ocx sync [--expect-link | --expect-hub-key ] [--restart-codex] [--restart-app-server-only]", + usage: "ocx sync [--expect-link | --expect-hub-key ] [--local-only] [--json] [--restart-codex] [--restart-app-server-only]", summary: "Fetch provider models and inject them into Codex config.", details: [ + "A current Home catalog fans out to linked Children; --local-only disables fan-out and --json emits the result. Partial fan-out exits 6.", + "Fan-out never requests a Codex app or app-server restart on a Child; use GOAT or ocx sync --restart-codex on the Child. The Child's pinned sync may restart its OpenCodex client runtime after applying changed Home settings.", "After writing the catalog, warns if long-lived Codex app-server processes are still running.", "--restart-codex restarts the app-servers AND fully quits and relaunches the Codex desktop app on macOS, Linux and Windows, after catalog/cache writes or a committed configuration change. It ends live conversations.", "--restart-app-server-only keeps the narrow behaviour: SIGTERM to matching app-server / code-mode-host processes, desktop app left running. It wins over --restart-codex when both are given.", @@ -731,10 +733,11 @@ export const CLI_COMMANDS: CliCommandEntry[] = [ }, { name: "capabilities", - usage: "ocx capabilities [--json] [--mutating-only] [--route ]", + usage: "ocx capabilities [--json] [--contracts] [--mutating-only] [--route ]", summary: "List the declared CLI capabilities and the management routes they drive.", details: [ "The machine-readable surface index: start here when driving ocx programmatically instead of parsing help text.", + "--contracts lists supported versioned contracts; it cannot be combined with --route or --mutating-only.", "--route answers the inverse question: which commands drive this management route.", ], }, diff --git a/src/cli/root.ts b/src/cli/root.ts index 2668b1fb8a8..9b7e3ad5fe8 100644 --- a/src/cli/root.ts +++ b/src/cli/root.ts @@ -13,6 +13,7 @@ import { parseReadyArgs, type ReadyArgs } from "./ready"; import { parseResolveArgs, type ResolveArgs } from "./resolve"; import { parseStopApproval } from "./stop-approval"; import { parseSyncExpectation, SYNC_EXPECTATION_USAGE_EXIT } from "./sync-expectation"; +import { parseSyncFanoutFlags } from "./sync-flags"; import { maybeAutoRestoreCodexShimAsync } from "./codex-shim-autorestore"; import { findCommand } from "./registry"; import { printUnknownCommand } from "./help-recovery"; @@ -147,6 +148,11 @@ export async function runCli(argv: string[]): Promise { } // #7694: a malformed pinned sync is refused before any preflight reads or repairs anything. if (head.command === "sync") { + const flags = parseSyncFanoutFlags(head.args.slice(1)); + if (!flags.ok) { + console.error(flags.message); + process.exit(SYNC_EXPECTATION_USAGE_EXIT); + } const pinned = parseSyncExpectation(head.args.slice(1)); if (!pinned.ok) { console.error(pinned.message); diff --git a/src/cli/sync-command.ts b/src/cli/sync-command.ts new file mode 100644 index 00000000000..304656a1707 --- /dev/null +++ b/src/cli/sync-command.ts @@ -0,0 +1,241 @@ +import type { CliDispatchDeps } from "./dispatch"; +import type { OwnedIntegrationRefreshOutcome } from "../integrations/owned-refresh"; +import { syncModelsToCodex } from "../codex/sync"; +import { HUB_GATED_SKIP_MESSAGE } from "../codex/desired-state"; +import { handleRestartScopeAfterWrite, readRestartScope, type RestartScope } from "./restart-scope"; +import { terminalSafeError, terminalSafeText } from "./runtime-api"; +import { parseSyncFanoutFlags } from "./sync-flags"; +import { projectLocalSyncResult } from "./local-sync-result"; +import { readLinkStore } from "../link/store"; +import { linkKnownHostsPath, linkStorePath } from "../link/paths"; +import { buildExecArgv, remotePinnedSyncArgv } from "../link/ssh-argv"; +import { requireRemotePlatformFramed } from "../link/remote-platform"; +import { FanoutProcessError, fanoutSshRunner, runFanoutProcess } from "./sync-fanout-process"; +import { readHomeLinkStatus } from "./sync-link-status"; +import { classifySyncResult, fanoutExitCode, renderFanoutHuman, renderFanoutJson, runHomeFanout, REMOTE_LINK_SYNC_MESSAGE, STALE_REMOTE_CATALOG_MESSAGE, type HomeResult } from "./sync-fanout"; + +export async function runSyncCommand(deps: CliDispatchDeps): Promise { + const flags = parseSyncFanoutFlags(deps.args.slice(1)); + if (!flags.ok) { console.error(flags.message); return 2; } + const originalLog = console.log; + if (flags.json) console.log = (...args: unknown[]) => console.error(...args); + let applicable = false, catalogCurrent = false; + let state: HomeResult["state"] = "failed"; + const runHome = async (): Promise => { + const syncArgs = deps.args.slice(1); + // #7694: parse the expected identity before anything else reads or writes state. + const { parseSyncExpectation, reportSyncExpectationMismatch, SYNC_EXPECTATION_USAGE_EXIT } = await import("./sync-expectation"); + const parsedExpectation = parseSyncExpectation(syncArgs); + if (!parsedExpectation.ok) { + console.error(parsedExpectation.message); + return SYNC_EXPECTATION_USAGE_EXIT; + } + const expectation = parsedExpectation.expectation; + const restartScope = readRestartScope(syncArgs, console); + // The wire field keeps APP-SERVER-ONLY meaning and is deliberately not widened. A + // remote hub must not end a local user's conversations because a field name acquired + // a wider meaning underneath it; the maintainer decision widened a local CLI flag and + // said nothing about remote callers. syncConnectedClient ignores it either way. + const restartCodex = restartScope.appServers; + const { readClientConnectionState } = await import("../client/state"); + const clientState = readClientConnectionState(); + // With an expectation the unlocked read decides nothing: the connected sync re-reads under its + // lock and refuses there, so a state that changes in between can never reach the local path. + if (!expectation && (clientState.kind === "invalid" || clientState.kind === "mismatched")) { + console.error(`Client state is ${clientState.kind}: ${clientState.reason}`); + return 1; + } + if (expectation || clientState.kind === "connected") { + try { + const { syncConnectedClient } = await import("../client/connect"); + const result = await syncConnectedClient(expectation ? { restartCodex, expect: expectation } : { restartCodex }); + if (expectation) { + // The root preflight skipped the shim repair for a pinned sync; the identity held, so + // run it now, as an unpinned sync would have. + const { runCodexShimAutoRestoreAsync } = await import("./codex-shim-autorestore"); + await runCodexShimAutoRestoreAsync(); + } + // The connection the sync ran under, read inside its lock; the read above may be stale. + const link = result.connection.transport === "link"; + state = result.stale ? "stale" : "synced"; + console.log(result.stale + ? link ? STALE_REMOTE_CATALOG_MESSAGE : "Hub unavailable; retained and applied the last-known-good remote catalog (stale)." + : link ? REMOTE_LINK_SYNC_MESSAGE : "Remote hub catalog synchronized."); + if (result.homeSettings) { + const { describeHomeCodexSettings } = await import("../link/codex-settings"); + const settings = result.homeSettings; + if (settings.source === "local") { + console.log(`Codex settings: kept this machine's local values (${terminalSafeText(settings.reason)}).`); + } else { + console.log(settings.source === "home" + ? `Codex settings applied from Home ${terminalSafeText(settings.document.home.name)}:` + : `Codex settings applied from the last recorded Home read (${terminalSafeText(settings.reason)}):`); + for (const line of describeHomeCodexSettings(settings.document.settings)) console.log(` ${terminalSafeText(line)}`); + } + } + await handleConnectedSyncCatalogWrite(result, restartScope); + if (result.applyRecordFailed) { + console.error("The Home's Codex settings were applied, but the apply record could not be written; the client runtime was not restarted. Run 'ocx sync' again."); + process.exitCode = 1; + } + // OCX-6: a link Child's runtime must have started after the apply it serves under. + if (link && result.appliedRecord) { + const { applyRestartMessage, restartRuntimeAfterApply } = await import("./link-apply-restart"); + const { sameClientConnectionOwner } = await import("../client/state"); + const applied = result.connection; + const outcome = await restartRuntimeAfterApply(result.appliedRecord, { + restart: startWhenStopped => deps.handleProxyRestart(startWhenStopped), + recoveryStart: recovering => deps.handleRestartStartWhenStopped(recovering), + connectionUnchanged: () => { + const current = readClientConnectionState(); + return current.kind === "connected" && sameClientConnectionOwner(current.value, applied) + && current.value.link?.linkId === applied.link?.linkId; + }, + }); + const message = applyRestartMessage(outcome); + if (outcome.kind === "failed" || outcome.kind === "connection-changed") { + console.error(message); + process.exitCode = 1; + } else { + console.log(message); + } + } + // `process.exitCode` rather than a literal 0, for the same reason every other + // runner does it (tests/cli/cli-transport-honesty.test.ts): the catalog-write helper + // drives app-server restarts, and one of those recording a failure must not be + // erased by the value this runner returns. It reads 0 on the ordinary path. Node + // types it as `number | string`; only a numeric code means anything here. + return typeof process.exitCode === "number" ? process.exitCode : 0; + } catch (error) { + const { ClientSyncExpectationError } = await import("../client/sync-expectation"); + if (error instanceof ClientSyncExpectationError) return reportSyncExpectationMismatch(error, console); + // The refresh path reaches the same hub catalog `ocx connect` validates, so a rejected + // reasoning level arrives here as hub-supplied text. Rendering it through the shared + // terminal boundary is what keeps the routine refresh from forging output; the domain + // error itself is left alone for callers that inspect it. + console.error(`Connected sync failed without local fallback: ${terminalSafeError(error).message}`); + return 1; + } + } + applicable = true; + const live = await deps.findLiveProxy(); + const synced = await syncModelsToCodex( + live?.port, + undefined, + undefined, + undefined, + { catalogEvenWhenNotInjected: true }, + ); + let code = 0; + state = synced.status === "skipped" ? "skipped" : synced.ok ? "synced" : "failed"; + catalogCurrent = (synced.status === "applied" || synced.status === "catalog-only") + && synced.refreshOutcome === "committed" && projectLocalSyncResult(synced).catalog?.converged === true; + if (synced.status === "skipped") { + console.log(synced.skippedReason === "hub-gated" + ? `${HUB_GATED_SKIP_MESSAGE} sync skipped and no Codex files changed.` + : "Codex integration is OFF; sync skipped and no Codex files changed."); + } else if (synced.status === "catalog-only") { + // Explicit sync with the integration OFF still refreshes the catalog/cache + // for side profiles that consume the proxy without injection. + console.log(synced.message ?? "Codex integration is OFF; catalog refreshed, Codex config untouched."); + if (!synced.ok) code = 1; + } else if (!synced.ok) { + code = 1; + console.error("Codex sync did not complete. Fix the reported Codex config issue and retry."); + } + // Catalog/model-cache writes retain their warning/restart handling. This is + // deliberately not an `else`: refreshCodexModelCatalog runs before injectCodexConfig, + // so a sync can fail (`ok: false`) after the catalog was already rewritten — which is + // exactly when a long-lived app-server is holding the stale list. + // A configuration-only change also needs a reload, but only when explicitly + // requested. A successful no-op or refused write is never restart authority. + const requestedConfigRestart = (restartScope.appServers || restartScope.desktopApp) + && synced.ok && synced.configChanged === true; + if (synced.catalogWritten || synced.cacheSynced || requestedConfigRestart) { + await handleRestartScopeAfterWrite(restartScope, console); + } + // `ocx sync` is a direct CLI path; it does not call the management + // `/api/sync` route. Refresh already-connected file integrations here too, + // after Codex has published the catalog that supplies its capabilities. + if (synced.status !== "refused") { + const results: OwnedIntegrationRefreshOutcome[] = []; + if (live) { + try { + const config = deps.loadConfig(); + const { refreshOwnedCatalogIntegrations } = await import("../integrations/catalog-refresh"); + results.push(...await refreshOwnedCatalogIntegrations({ + models: async () => { + const { loadExportModels } = await import("../server/management/model-rows"); + return loadExportModels(config); + }, + config, + port: live.port, + }, ["mcode", "pi", "raycast", "omo", "cline", "commandcode", "droid", "opencode", "kilo", "qoder", "qoder-cn", "workbuddy", "workbuddy-ai", "hermes", "t3code"])); + } catch (error) { + console.warn(`Client integrations were not refreshed: ${error instanceof Error ? error.message : String(error)}`); + } + } + // Even without a live proxy, report why Aside could not sync. Its server + // owner is never bypassed, and another client's failure cannot hide it. + try { + const { refreshAsideProfilesThroughServer } = await import("./aside-profiles"); + results.push(...await refreshAsideProfilesThroughServer({ findLiveProxy: async () => live })); + } catch (error) { + console.warn(`Aside profiles were not refreshed: ${error instanceof Error ? error.message : String(error)}`); + } + for (const result of results) { + const label = result.profileId === undefined ? result.client : `${result.client}:${result.profileId}`; + if (result.changed) console.log(`${label} integration refreshed from the current catalog.`); + else if (result.reason) console.warn(`${label} integration was not refreshed: ${result.reason}${result.residual ? " Recovery did not finish." : ""}${result.snapshotPath ? ` Backup: ${result.snapshotPath}` : ""}`); + } + } + return code || (typeof process.exitCode === "number" ? process.exitCode : 0); + }; + let code: number; + try { code = await runHome(); } + catch (error) { + if (!flags.json) { + try { if (readLinkStore(linkStorePath()).links.length) console.error("Children were not synced because the Home sync failed."); } catch { /* Preserve the original error. */ } + throw error; + } + console.error(`Sync failed: ${terminalSafeError(error).message}`); + code = 1; state = "failed"; applicable = true; + } finally { console.log = originalLog; } + if (code !== 0) state = "failed"; + const document = await runHomeFanout({ + home: { state, exit: code }, catalogCurrent, localOnly: flags.localOnly, applicable, + readStore: () => readLinkStore(linkStorePath()), readLinkStatus: () => readHomeLinkStatus(), + runChild: async (link, deadline) => { + const runner = fanoutSshRunner(deadline); + let platform: "posix" | "windows"; + try { platform = link.remotePlatform ?? await requireRemotePlatformFramed(runner, link.alias, linkKnownHostsPath()); } + catch (error) { + if (error instanceof FanoutProcessError && (error.reason === "deadline-exceeded" || error.reason === "termination-unconfirmed")) return { state: "timed-out", reason: error.reason, exit: null }; + return { state: "failed", reason: "platform-probe-failed", exit: null }; + } + try { + const result = await runFanoutProcess(buildExecArgv({ alias: link.alias, knownHostsFile: linkKnownHostsPath(), argv: remotePinnedSyncArgv(link.id, platform) }), { timeoutMs: Math.max(0, deadline - Date.now()) }); + return { ...classifySyncResult(result), exit: result.code }; + } catch (error) { + if (error instanceof FanoutProcessError) return { state: error.reason === "deadline-exceeded" || error.reason === "termination-unconfirmed" ? "timed-out" : "failed", reason: error.reason, exit: null }; + throw error; + } + }, + }); + if (flags.json) originalLog(renderFanoutJson(document)); + else { + for (const line of renderFanoutHuman(document)) originalLog(line); + if (document.fanout.state === "failed" && document.fanout.reason === "link-store-unreadable") { + console.error("Children were not synced: the Remote Link store could not be read."); + } + } + return fanoutExitCode(document); +} + +async function handleConnectedSyncCatalogWrite( + result: { catalogWritten: boolean; cacheSynced: boolean }, + scope: RestartScope, +): Promise { + if (!result.catalogWritten && !result.cacheSynced) return; + await handleRestartScopeAfterWrite(scope, console); +} diff --git a/src/cli/sync-fanout-process.ts b/src/cli/sync-fanout-process.ts new file mode 100644 index 00000000000..a75b3c0028f --- /dev/null +++ b/src/cli/sync-fanout-process.ts @@ -0,0 +1,92 @@ +import { linkSshSpawnEnv, type SshRunResult, type SshRunner } from "../link/ssh-runner"; + +export type FanoutProcessFailure = "deadline-exceeded" | "termination-unconfirmed" | "ssh-spawn-failed" | "ssh-output"; +export class FanoutProcessError extends Error { + constructor(readonly reason: FanoutProcessFailure, options?: ErrorOptions) { + super(reason, options); + this.name = "FanoutProcessError"; + } +} + +function delay(ms: number): Promise { return new Promise(resolve => setTimeout(resolve, ms)); } + +async function readBounded(stream: ReadableStream, cap: number, exited: Promise): Promise { + const reader = stream.getReader(); + let ended = false; + let graceExpired = false; + let timer: ReturnType | undefined; + void exited.then(() => { if (!ended) timer = setTimeout(() => { graceExpired = true; void reader.cancel().catch(() => {}); }, 250); }); + const chunks: Uint8Array[] = []; + let length = 0; + try { + while (true) { + const next = await reader.read(); + if (next.done) { + if (graceExpired) throw new FanoutProcessError("ssh-output"); + break; + } + length += next.value.length; + if (length > cap) throw new FanoutProcessError("ssh-output"); + chunks.push(next.value); + } + const bytes = new Uint8Array(length); + let offset = 0; + for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.length; } + try { return new TextDecoder("utf-8", { fatal: true }).decode(bytes); } + catch (cause) { throw new FanoutProcessError("ssh-output", { cause }); } + } finally { + ended = true; + if (timer !== undefined) clearTimeout(timer); + void reader.cancel().catch(() => {}); + reader.releaseLock(); + } +} + +export async function runFanoutProcess(argv: readonly string[], options: { + timeoutMs: number; maxOutputBytes?: number; onSpawn?: (pid: number) => void; +}): Promise { + if (options.timeoutMs <= 0) throw new FanoutProcessError("deadline-exceeded"); + const env = linkSshSpawnEnv(); + let child: Bun.Subprocess<"ignore", "pipe", "pipe">; + try { + child = Bun.spawn([...argv], { stdin: "ignore", stdout: "pipe", stderr: "pipe", ...(env ? { env } : {}) }); + } catch (cause) { throw new FanoutProcessError("ssh-spawn-failed", { cause }); } + options.onSpawn?.(child.pid); + let exited = false; + const exit = child.exited.then(code => { exited = true; return code; }); + const stdout = readBounded(child.stdout, options.maxOutputBytes ?? 65536, exit); + const stderr = readBounded(child.stderr, options.maxOutputBytes ?? 65536, exit); + let timer: ReturnType | undefined; + const deadline = new Promise((_, reject) => { timer = setTimeout(() => reject(new FanoutProcessError("deadline-exceeded")), Math.max(0, options.timeoutMs)); }); + try { + const [code, out, err] = await Promise.race([Promise.all([exit, stdout, stderr]), deadline]); + return { code, stdout: out, stderr: err }; + } catch (error) { + let signalError = false; + const signal = (name: NodeJS.Signals): void => { + if (exited) return; + try { child.kill(name); } catch (cause) { + if (cause && typeof cause === "object" && "code" in cause && cause.code === "ESRCH") { exited = true; return; } + signalError = true; + } + }; + signal("SIGTERM"); + if (!exited) await Promise.race([exit, delay(2000)]); + if (!exited) signal("SIGKILL"); + if (!exited) await Promise.race([exit, delay(1000)]); + if (signalError || !exited) throw new FanoutProcessError("termination-unconfirmed", { cause: error }); + if (error instanceof FanoutProcessError) throw error; + throw new FanoutProcessError("ssh-output", { cause: error }); + } finally { + if (timer !== undefined) clearTimeout(timer); + void Promise.allSettled([exit, stdout, stderr]); + } +} + +/** Platform discovery shares the worker deadline across its SSH calls. */ +export function fanoutSshRunner(deadline: number): Pick { + return { run: (argv, options = {}) => runFanoutProcess(argv, { + timeoutMs: Math.min(options.timeoutMs ?? 30_000, Math.max(0, deadline - Date.now())), + ...(options.maxOutputBytes === undefined ? {} : { maxOutputBytes: options.maxOutputBytes }), + }) }; +} diff --git a/src/cli/sync-fanout.ts b/src/cli/sync-fanout.ts new file mode 100644 index 00000000000..61a0f513184 --- /dev/null +++ b/src/cli/sync-fanout.ts @@ -0,0 +1,150 @@ +import { compareStrictSemver, parseStrictSemver } from "../lib/strict-semver"; +import type { LinkRecord, LinkStore } from "../link/store"; +import type { LinkStatusDto } from "../link/status-projection"; +import { LinkStatusError } from "./sync-link-status"; + +export const REMOTE_LINK_SYNC_MESSAGE = "Remote Link Home catalog synchronized."; +export const STALE_REMOTE_CATALOG_MESSAGE = "Home unavailable; retained and applied the last-known-good remote catalog (stale)."; +export const SYNC_FANOUT_PARTIAL_EXIT = 6; + +export type ChildVerdict = { state: "synced" | "skipped" | "failed"; reason: string | null }; +const failure = (reason: string): ChildVerdict => ({ state: "failed", reason }); +const skipped = (reason: string): ChildVerdict => ({ state: "skipped", reason }); +const minimum = parseStrictSemver("2.93.0")!; + +export function parseOcxVersion(output: string): string | null { + const version = output.trim().replace(/^opencodex /, ""); + return parseStrictSemver(version) ? version : null; +} + +export function classifyVersionProbe(output: string): "child-ocx-version-unknown" | "child-ocx-lacks-expect-link" | null { + const version = parseOcxVersion(output); + if (!version) return "child-ocx-version-unknown"; + return compareStrictSemver(parseStrictSemver(version)!, minimum) < 0 ? "child-ocx-lacks-expect-link" : null; +} + +const mismatchReasons = new Set(["disconnected", "invalid_state", "disconnect_pending", "pending_operation", "hub_client", "link_client", "other_link", "other_key"]); + +function validDocument(value: unknown): "synced" | "stale" | null { + if (!value || typeof value !== "object" || Array.isArray(value)) return null; + const v = value as Record; + const keysAre = (object: Record, keys: readonly string[]): boolean => Object.keys(object).length === keys.length && keys.every(key => Object.hasOwn(object, key)); + if (!keysAre(v, ["schema", "home", "fanout", "children"])) return null; + if (v.schema !== "ocx.sync.fanout/1" || !v.home || typeof v.home !== "object" || Array.isArray(v.home) + || !v.fanout || typeof v.fanout !== "object" || Array.isArray(v.fanout) || !Array.isArray(v.children)) return null; + const home = v.home as Record, fanout = v.fanout as Record; + if (!keysAre(home, ["state", "exit"]) || !keysAre(fanout, ["state", "reason"])) return null; + if (home.exit !== 0 || (home.state !== "synced" && home.state !== "stale")) return null; + if (fanout.state !== "not-applicable" || fanout.reason !== null || v.children.length !== 0) return null; + return home.state; +} + +export function classifySyncResult(result: { code: number; stdout: string; stderr: string }): ChildVerdict { + const { code, stdout, stderr } = result; + if (code === 255) return failure("ssh-failed"); + if (code === 127) return failure("child-ocx-not-found"); + if (code === 126) return failure("child-ocx-not-contained"); + if (code === 125) return skipped("child-platform-unsupported"); + const lines = stderr.split(/\r?\n/); + const last = stderr.trimEnd().split(/\r?\n/).at(-1); + if (code === 121) { + if (last === "ocx-fanout:child-ocx-lacks-expect-link") return skipped("child-ocx-lacks-expect-link"); + if (last === "ocx-fanout:child-ocx-version-unknown") return skipped("child-ocx-version-unknown"); + return failure("child-sync-failed"); + } + const markers = lines.map(line => /^ocx-fanout:selected:(.+)$/.exec(line)).filter(match => match !== null); + if (markers.length !== 1 || !parseStrictSemver(markers[0]![1]!)) return failure("child-output-invalid"); + const outputLines = stdout.split(/\r?\n/); + const delimiters = outputLines.flatMap((line, index) => line === "ocx-fanout:stdout-begin" ? [index] : []); + if (delimiters.length !== 1) return failure("child-output-invalid"); + if (code === 5) { + try { + const detail: unknown = JSON.parse(last ?? ""); + if (detail && typeof detail === "object" && "phase" in detail && detail.phase === "child_link_mismatch" + && "reason" in detail && typeof detail.reason === "string" && mismatchReasons.has(detail.reason)) return skipped(`child-link-mismatch:${detail.reason}`); + } catch { /* The generic mismatch is the only safe fallback. */ } + return skipped("child-link-mismatch"); + } + if (code === 7) return skipped("child-updating"); + if (code !== 0) return failure("child-sync-failed"); + const text = outputLines.slice(delimiters[0]! + 1).join("\n").trim(); + if (text.startsWith("{")) { + try { + const state = validDocument(JSON.parse(text)); + if (state === "synced") return { state: "synced", reason: null }; + if (state === "stale") return failure("child-catalog-stale"); + } catch { /* Reject invalid or multiple JSON documents. */ } + return failure("child-output-invalid"); + } + if (text.includes(STALE_REMOTE_CATALOG_MESSAGE)) return failure("child-catalog-stale"); + if (text.includes(REMOTE_LINK_SYNC_MESSAGE)) return { state: "synced", reason: null }; + return failure("child-output-invalid"); +} + +export type HomeResult = { state: "synced" | "stale" | "skipped" | "failed"; exit: number }; +export type ChildResult = { linkId: string; alias: string; state: "synced" | "skipped" | "failed" | "timed-out"; reason: string | null; exit: number | null }; +export type FanoutDocument = { schema: "ocx.sync.fanout/1"; home: HomeResult; fanout: { state: "ran" | "disabled" | "not-applicable" | "failed"; reason: string | null }; children: ChildResult[] }; + +export async function runHomeFanout(deps: { + home: HomeResult; catalogCurrent: boolean; localOnly?: boolean; applicable?: boolean; + readStore: () => LinkStore; readLinkStatus: () => Promise; + runChild: (link: LinkRecord, deadline: number) => Promise>; + now?: () => number; deadlineMs?: number; concurrency?: number; terminationGraceMs?: number; +}): Promise { + const result: FanoutDocument = { schema: "ocx.sync.fanout/1", home: deps.home, fanout: { state: deps.localOnly ? "disabled" : "not-applicable", reason: null }, children: [] }; + if (deps.localOnly || deps.applicable === false) return result; + let store: LinkStore; + try { store = deps.readStore(); } catch { result.fanout = { state: "failed", reason: "link-store-unreadable" }; return result; } + if (!store.links.length) return result; + result.fanout.state = "ran"; + const classify = (link: LinkRecord, state: ChildResult["state"], reason: string | null, exit: number | null = null): ChildResult => ({ linkId: link.id, alias: link.alias, state, reason, exit }); + result.children = store.links.map(link => classify(link, "skipped", link.direction === "client-initiated" ? "client-initiated-link" : "home-catalog-not-current")); + const skipReason = deps.home.state === "failed" || deps.home.exit !== 0 ? "home-sync-failed" : deps.home.state === "skipped" ? "home-sync-skipped" : !deps.catalogCurrent ? "home-catalog-not-current" : null; + if (skipReason) { + result.children = store.links.map(link => classify(link, "skipped", link.direction === "client-initiated" ? "client-initiated-link" : skipReason)); + return result; + } + let status: LinkStatusDto; + try { status = await deps.readLinkStatus(); } + catch (error) { + const reason = error instanceof LinkStatusError ? error.reason : "home-link-status-unavailable"; + result.children = store.links.map(link => link.direction === "client-initiated" ? classify(link, "skipped", "client-initiated-link") : classify(link, reason === "home-runtime-not-running" ? "skipped" : "failed", reason)); + return result; + } + let cursor = 0; + const workers = Array.from({ length: Math.max(1, Math.min(Math.floor(deps.concurrency ?? 3), 3, store.links.length)) }, async () => { + for (;;) { + const index = cursor++; + const link = store.links[index]; + if (!link) return; + if (link.direction === "client-initiated") continue; + const wire = status.links.find(row => row.id === link.id); + if (!wire) { result.children[index] = classify(link, "skipped", "link-not-in-runtime"); continue; } + if (wire.state !== "connected") { result.children[index] = classify(link, "skipped", `tunnel-${wire.state}`); continue; } + let timer: ReturnType | undefined; + try { + const budget = deps.deadlineMs ?? 180_000; + const child = await Promise.race([ + deps.runChild(link, (deps.now ?? Date.now)() + budget), + new Promise>(resolve => { + timer = setTimeout(() => resolve({ state: "timed-out", reason: "termination-unconfirmed", exit: null }), budget + (deps.terminationGraceMs ?? 3000)); + }), + ]); + result.children[index] = { linkId: link.id, alias: link.alias, ...child }; + } catch { result.children[index] = classify(link, "failed", "internal-error"); } + finally { if (timer !== undefined) clearTimeout(timer); } + } + }); + await Promise.all(workers); + return result; +} + +export function fanoutExitCode(document: FanoutDocument): number { + if (document.home.exit !== 0) return document.home.exit; + return document.fanout.state === "failed" || document.children.some(child => child.state === "failed" || child.state === "timed-out") ? SYNC_FANOUT_PARTIAL_EXIT : 0; +} + +export function renderFanoutJson(document: FanoutDocument): string { return JSON.stringify(document); } +export function renderFanoutHuman(document: FanoutDocument): string[] { + return document.children.map(child => `${child.alias} (${child.linkId}): ${child.state}${child.reason ? ` (${child.reason})` : ""}`); +} diff --git a/src/cli/sync-flags.ts b/src/cli/sync-flags.ts new file mode 100644 index 00000000000..845b5e8068d --- /dev/null +++ b/src/cli/sync-flags.ts @@ -0,0 +1,10 @@ +export type SyncFanoutFlags = { ok: true; localOnly: boolean; json: boolean } | { ok: false; message: string }; + +export function parseSyncFanoutFlags(args: readonly string[]): SyncFanoutFlags { + for (const flag of ["--local-only", "--json"]) { + if (args.filter(arg => arg === flag).length > 1 || args.some(arg => arg.startsWith(`${flag}=`))) { + return { ok: false, message: `ocx sync accepts ${flag} once without a value.` }; + } + } + return { ok: true, localOnly: args.includes("--local-only"), json: args.includes("--json") }; +} diff --git a/src/cli/sync-link-status.ts b/src/cli/sync-link-status.ts new file mode 100644 index 00000000000..6f0888ee986 --- /dev/null +++ b/src/cli/sync-link-status.ts @@ -0,0 +1,39 @@ +import { runningProxyUpdateHeaders } from "../oauth/login-cli"; +import { runtimeBaseUrl, RuntimeApiError } from "./runtime-api"; +import { validateStatus, type LinkStatusPayload } from "./link"; + +export type LinkStatusFailure = "home-runtime-not-running" | "home-link-status-unauthorized" | "home-link-status-timeout" | "home-link-status-unavailable" | "home-link-status-invalid"; +export class LinkStatusError extends Error { + constructor(readonly reason: LinkStatusFailure, options?: ErrorOptions) { super(reason, options); this.name = "LinkStatusError"; } +} + +/** A single absolute deadline covers discovery, response headers and the response body. */ +export async function readHomeLinkStatus(deadlineMs = 5000, deps: { + baseUrl?: () => Promise; fetchImpl?: typeof fetch; headers?: () => Headers; +} = {}): Promise { + const controller = new AbortController(); + let timer: ReturnType | undefined; + const timeout = new Promise((_, reject) => { + timer = setTimeout(() => { controller.abort(); reject(new LinkStatusError("home-link-status-timeout")); }, Math.max(0, deadlineMs)); + }); + const work = async (): Promise => { + let base: string | null; + try { base = await (deps.baseUrl ?? (() => runtimeBaseUrl()))(); } + catch (cause) { + if (cause instanceof RuntimeApiError && cause.code === "proxy_not_running") throw new LinkStatusError("home-runtime-not-running", { cause }); + throw new LinkStatusError("home-link-status-unavailable", { cause }); + } + if (controller.signal.aborted) throw new LinkStatusError("home-link-status-timeout"); + if (!base) throw new LinkStatusError("home-runtime-not-running"); + let response: Response; + try { response = await (deps.fetchImpl ?? fetch)(`${base}/api/link/status`, { headers: (deps.headers ?? runningProxyUpdateHeaders)(), signal: controller.signal }); } + catch (cause) { throw new LinkStatusError("home-link-status-unavailable", { cause }); } + if (response.status === 401 || response.status === 403) throw new LinkStatusError("home-link-status-unauthorized"); + if (!response.ok) throw new LinkStatusError("home-link-status-unavailable"); + let text: string; + try { text = await response.text(); } catch (cause) { throw new LinkStatusError("home-link-status-unavailable", { cause }); } + try { return validateStatus(JSON.parse(text)); } catch (cause) { throw new LinkStatusError("home-link-status-invalid", { cause }); } + }; + try { return await Promise.race([work(), timeout]); } + finally { if (timer !== undefined) clearTimeout(timer); controller.abort(); } +} diff --git a/src/link/remote-platform.ts b/src/link/remote-platform.ts index a4afb3a4008..96b11cbe483 100644 --- a/src/link/remote-platform.ts +++ b/src/link/remote-platform.ts @@ -14,6 +14,7 @@ const SSH_TRANSPORT_FAILURE = 255; /** Remote argv that prints the kernel name; under cmd or PowerShell, `sh` itself is refused. */ export const REMOTE_UNAME_ARGV: readonly string[] = ["sh", "-c", "uname -s 2>/dev/null", "ocx-platform"]; +const REMOTE_FRAMED_UNAME_ARGV: readonly string[] = ["sh", "-c", "printf 'ocx-platform:%s\\n' \"$(uname -s 2>/dev/null)\"", "ocx-platform"]; /** Does this output come from cmd.exe or PowerShell refusing a POSIX command? */ export function isWindowsShellRefusal(output: string): boolean { @@ -64,3 +65,16 @@ export async function requireRemotePlatform(runner: Pick, alia if (platform === "unknown") throw new Error("Remote platform could not be determined"); return platform; } + +/** Fan-out ignores login-shell output and trusts only one framed uname line. */ +export async function requireRemotePlatformFramed(runner: Pick, alias: string, knownHostsFile: string): Promise<"posix" | "windows"> { + const windows = await runner.run(buildWindowsProbeArgv({ alias, knownHostsFile }), { timeoutMs: 10_000 }); + if (windows.code === SSH_TRANSPORT_FAILURE) throw new Error("SSH platform discovery failed"); + if (windows.code === 0 && windows.stdout.split(/\r?\n/).some(line => line.trim() === "Windows_NT")) return "windows"; + const result = await runner.run(buildExecArgv({ alias, knownHostsFile, argv: REMOTE_FRAMED_UNAME_ARGV }), { timeoutMs: 10_000 }); + if (result.code === SSH_TRANSPORT_FAILURE) throw new Error("SSH platform discovery failed"); + const frames = result.stdout.split(/\r?\n/).filter(line => line.startsWith("ocx-platform:")); + const name = frames.length === 1 ? frames[0]!.slice("ocx-platform:".length) : ""; + if (result.code !== 0 || !POSIX_UNAME.test(name)) throw new Error("Remote platform could not be determined"); + return WINDOWS_UNAME.test(name) ? "windows" : "posix"; +} diff --git a/src/link/remote-windows.ts b/src/link/remote-windows.ts index 04e8f011617..510eecc157f 100644 --- a/src/link/remote-windows.ts +++ b/src/link/remote-windows.ts @@ -10,13 +10,24 @@ export const POWERSHELL_ENCODED_MAX = 8_000; export function powershellArgv(script: string): string[] { // Module preparation otherwise writes a CLIXML progress record to stderr, which Home would see. const encoded = Buffer.from("$ProgressPreference='SilentlyContinue'\n" + script, "utf16le").toString("base64"); - if (encoded.length > POWERSHELL_ENCODED_MAX) throw new Error("Remote PowerShell command exceeds the cmd.exe-compatible command-line budget"); + if (encoded.length > POWERSHELL_ENCODED_MAX) throw new Error(`Remote PowerShell command exceeds the cmd.exe-compatible command-line budget (${encoded.length})`); return ["powershell.exe", "-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", encoded]; } /** Exit status when the remote ocx cannot be contained; nothing ran. */ export const WINDOWS_CONTAINMENT_EXIT = 126; +const SCRIPT_PACKED_PREFIX = "$ocxPacked='"; +function packedPowerShellArgv(script: string): string[] { + const bytes = deflateRawSync(Buffer.from(script, "utf8"), { level: 9 }); + const packed = Array.from(bytes, byte => String.fromCharCode(byte + 256)).join(""); + return powershellArgv(`${SCRIPT_PACKED_PREFIX}${packed}'\n` + String.raw`$b=[byte[]]@($ocxPacked.ToCharArray()|%{[int]$_-256});$r=[IO.StreamReader]::new([IO.Compression.DeflateStream]::new([IO.MemoryStream]::new($b),[IO.Compression.CompressionMode]::Decompress));Invoke-Expression ($r.ReadToEnd())`); +} +function unpackPowerShell(script: string): string { + const match = /\$ocxPacked='([^']+)'/.exec(script); + return match ? inflateRawSync(Buffer.from(Array.from(match[1]!, ch => ch.charCodeAt(0) - 256))).toString("utf8") : script; +} + /** * OcxJob, compiled on the Child with Add-Type, contains the remote ocx. Run creates the process * with PROC_THREAD_ATTRIBUTE_JOB_LIST (STARTUPINFOEX, EXTENDED_STARTUPINFO_PRESENT), so it is a @@ -50,6 +61,12 @@ export const OCX_JOB_SOURCE = [ "var q=Process.Start(new ProcessStartInfo(x,\"--version\"){UseShellExecute=false,RedirectStandardInput=true,RedirectStandardOutput=true,RedirectStandardError=true});", "q.StandardInput.Close();q.StandardOutput.ReadToEndAsync();q.StandardError.ReadToEndAsync();", "if(q.WaitForExit(10000))return q.ExitCode==0;q.Kill();}catch{return false;}return false;}", + "public static string V(string x){Process q=null;try{", + "q=Process.Start(new ProcessStartInfo(x,\"--version\"){UseShellExecute=false,RedirectStandardInput=true,RedirectStandardOutput=true,RedirectStandardError=true});q.StandardInput.Close();", + "var p=q;var read=System.Threading.Tasks.Task.Run(()=>{var b=new char[257];int n=0,k;while(n<257&&(k=p.StandardOutput.Read(b,n,257-n))>0)n+=k;return n>256?null:new string(b,0,n);});", + "System.Threading.Tasks.Task.Run(()=>{var b=new char[1024];while(p.StandardError.Read(b,0,b.Length)>0){} });", + "var clock=Stopwatch.StartNew();var done=System.Threading.Tasks.Task.Run(()=>p.WaitForExit());if(!read.Wait(10000)||read.Result==null||!done.Wait(Math.Max(0,10000-(int)clock.ElapsedMilliseconds))){q.Kill();q.WaitForExit();return null;}return q.ExitCode==0?read.Result:null;", + "}catch{try{if(q!=null&&!q.HasExited){q.Kill();q.WaitForExit();}}catch{return null;}return null;}finally{if(q!=null)q.Dispose();}}", "public static int Run(string x,string c){", "IntPtr z=IntPtr.Zero,j=z,l=z,v=z,h=z,t=z;bool listed=false,done=false;", "try{", @@ -72,17 +89,18 @@ export const OCX_JOB_SOURCE = [ * The helper travels deflated so the whole command fits cmd.exe's line; PowerShell inflates it and * hands the text to Add-Type. It is never evaluated as PowerShell. */ -const OCX_JOB_PACKED = deflateRawSync(Buffer.from(OCX_JOB_SOURCE, "utf8"), { level: 9 }).toString("base64"); - const NATIVE_PROCESS = String.raw`$ErrorActionPreference='Stop' function Fail{try{[Console]::Error.WriteLine('Refusing to run ocx.exe outside a kill-on-close job.')}catch{$null=$_};exit 126} -try{Add-Type ([IO.StreamReader]::new([IO.Compression.DeflateStream]::new([IO.MemoryStream]::new([Convert]::FromBase64String('` + OCX_JOB_PACKED + String.raw`')),[IO.Compression.CompressionMode]::Decompress)).ReadToEnd())}catch{Fail} +try{Add-Type '` + OCX_JOB_SOURCE.replaceAll("'", "''") + String.raw`'}catch{Fail} function Quote-Native([string]$v){'"'+[regex]::Replace([regex]::Replace($v,'(\\*)"','$1$1\"'),'(\\+)$','$1$1')+'"'} function Invoke-Native([string]$e,[string[]]$a){try{$c=[OcxJob]::Run($e,((@($e)+$a|%{Quote-Native $_}) -join ' '))}catch{Fail};exit $c} `; /** The packed helper a script carries, inflated; for tests that check the transport. */ export function windowsScriptHelperSource(script: string): string | undefined { + script = unpackPowerShell(script); + const source = /try\{Add-Type '([\s\S]*?)'\}catch\{Fail\}/.exec(script); + if (source) return source[1]!.replaceAll("''", "'"); const match = /FromBase64String\('([A-Za-z0-9+/=]+)'\)\),\[IO\.Compression\.CompressionMode\]::Decompress\)\)\.ReadToEnd\(\)/.exec(script); if (!match) return undefined; return inflateRawSync(Buffer.from(match[1]!, "base64")).toString("utf8"); @@ -103,6 +121,7 @@ function dataLine(value: { executable?: string; args: readonly string[] }): stri * undefined for any other script. Test fixtures decode with this, never with their own pattern. */ export function windowsScriptData(script: string): { executable?: string; args: string[] } | undefined { + script = unpackPowerShell(script); const start = script.indexOf(DATA_OPEN); const end = start < 0 ? -1 : script.indexOf(DATA_CLOSE, start + DATA_OPEN.length); if (end < 0) return undefined; @@ -112,23 +131,40 @@ export function windowsScriptData(script: string): { executable?: string; args: } export function windowsNativeArgv(executable: string, args: readonly string[]): string[] { - return powershellArgv(NATIVE_PROCESS + dataLine({ executable, args }) + "Invoke-Native $d.executable @($d.args)\n"); + return packedPowerShellArgv(NATIVE_PROCESS + dataLine({ executable, args }) + "Invoke-Native $d.executable @($d.args)\n"); } /** * Desktop first, then the GOAT-managed current junction, then legacy and PATH candidates. Each * must answer --version within ten seconds; only the selected one runs the real command. */ -export function windowsOcxArgv(args: readonly string[]): string[] { - return powershellArgv(NATIVE_PROCESS + dataLine({ args }) + String.raw`$u=$env:USERPROFILE;$c=@("$u\.opencodex-desktop\bin\ocx.exe","$u\.local\share\goat\opencodex\current\ocx.exe","$u\.local\bin\ocx.exe") +const OCX_CANDIDATES = String.raw`$u=$env:USERPROFILE;$c=@("$u\.opencodex-desktop\bin\ocx.exe","$u\.local\share\goat\opencodex\current\ocx.exe","$u\.local\bin\ocx.exe") if($env:LOCALAPPDATA){$c+="$env:LOCALAPPDATA\Programs\OpenCodex\ocx.exe"} if($env:ProgramFiles){$c+="$env:ProgramFiles\OpenCodex\ocx.exe"} $c+=@((Get-Command ocx.exe -Type Application -EA 0).Source) +`; +export function windowsOcxArgv(args: readonly string[]): string[] { + return packedPowerShellArgv(NATIVE_PROCESS + dataLine({ args }) + OCX_CANDIDATES + String.raw` foreach($x in ($c|select -Unique)){if([IO.File]::Exists($x)-and[OcxJob]::Ok($x)){Invoke-Native $x @($d.args)}} [Console]::Error.WriteLine('No runnable ocx.exe found; install the Windows standalone archive.');exit 127 `); } +export function windowsPinnedSyncArgv(linkId: string): string[] { + return packedPowerShellArgv(NATIVE_PROCESS + dataLine({ args: ["sync", "--expect-link", linkId, "--json"] }) + OCX_CANDIDATES + String.raw` +foreach($x in ($c|select -Unique)){ + if(![IO.File]::Exists($x)){continue};$v=[OcxJob]::V($x);if($null -eq $v){continue};$v=$v.Trim();if($v.StartsWith('opencodex ')){$v=$v.Substring(10)} + $m=[regex]::Match($v,'^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-([0-9A-Za-z.-]+))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$') + $bad=(!$m.Success -or $v.Length -gt 128);if(!$bad -and $m.Groups[4].Success){foreach($p in $m.Groups[4].Value.Split('.')){if(!$p -or ($p -match '^\d+$' -and $p.Length -gt 1 -and $p[0] -eq '0')){$bad=$true}}} + if($bad){[Console]::Error.WriteLine('ocx-fanout:child-ocx-version-unknown');exit 121} + $a=@($m.Groups[1].Value,$m.Groups[2].Value,$m.Groups[3].Value);$b=@('2','93','0');$cmp=0 + for($i=0;$i -lt 3;$i++){if($a[$i].Length -ne $b[$i].Length){$cmp=$a[$i].Length-$b[$i].Length;break};$cmp=[string]::CompareOrdinal($a[$i],$b[$i]);if($cmp -ne 0){break}} + if($cmp -lt 0 -or ($cmp -eq 0 -and $m.Groups[4].Success)){[Console]::Error.WriteLine('ocx-fanout:child-ocx-lacks-expect-link');exit 121} + [Console]::Error.WriteLine('ocx-fanout:selected:'+$v);[Console]::Out.WriteLine('ocx-fanout:stdout-begin');Invoke-Native $x @($d.args) +};exit 127 +`); +} + /** Credential-free loopback probe of the Child; no proxy, no redirect, bounded body and deadline. */ export function windowsChildHttpArgv(port: number, path: "healthz" | "v1/catalog", timeoutMs: number): string[] { if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("invalid Child port"); diff --git a/src/link/ssh-argv.ts b/src/link/ssh-argv.ts index c2eb7ea211d..26ca2ea9b45 100644 --- a/src/link/ssh-argv.ts +++ b/src/link/ssh-argv.ts @@ -19,7 +19,7 @@ */ import { isAbsolute } from "node:path"; -import { POWERSHELL_ENCODED_MAX, windowsOcxArgv } from "./remote-windows"; +import { POWERSHELL_ENCODED_MAX, windowsOcxArgv, windowsPinnedSyncArgv } from "./remote-windows"; export type TunnelDirection = "R" | "L"; @@ -146,6 +146,16 @@ export const REMOTE_PLATFORM_UNSUPPORTED = 125; * ocx as `"$@"` without another round of parsing. Desktop binaries precede PATH candidates; * each candidate must run --version successfully. A missing runnable ocx exits 127. */ +const REMOTE_OCX_CANDIDATES = `for candidate in "$HOME/.opencodex-desktop/bin/ocx" "/Applications/OpenCodex.app/Contents/MacOS/ocx" "/usr/bin/ocx"; do + try_ocx "$candidate" "$@" +done +remaining=$PATH +while :; do + directory=\${remaining%%:*} + try_ocx "\${directory:-.}/ocx" "$@" + case "$remaining" in *:*) remaining=\${remaining#*:};; *) break;; esac +done`; + export const REMOTE_OCX_SCRIPT = `export PATH="$PATH:$HOME/.bun/bin:$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin" case "$(uname -s 2>/dev/null)" in Windows*|MSYS*|MINGW*|CYGWIN*) exit ${REMOTE_PLATFORM_UNSUPPORTED};; esac try_ocx() { @@ -155,15 +165,7 @@ try_ocx() { exec "$executable" "$@" fi } -for candidate in "$HOME/.opencodex-desktop/bin/ocx" "/Applications/OpenCodex.app/Contents/MacOS/ocx" "/usr/bin/ocx"; do - try_ocx "$candidate" "$@" -done -remaining=$PATH -while :; do - directory=\${remaining%%:*} - try_ocx "\${directory:-.}/ocx" "$@" - case "$remaining" in *:*) remaining=\${remaining#*:};; *) break;; esac -done +${REMOTE_OCX_CANDIDATES} exit ${REMOTE_COMMAND_NOT_FOUND}`; export function remoteOcxArgv(args: readonly string[], platform: "posix" | "windows" = "posix"): string[] { @@ -238,3 +240,54 @@ export function quoteRemote(argv: readonly string[]): string { return `'${arg.replaceAll("'", `'"'"'`)}'`; }).join(" "); } + +const REMOTE_PINNED_SYNC_SCRIPT = `export PATH="$PATH:$HOME/.bun/bin:$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin" +case "$(uname -s 2>/dev/null)" in Windows*|MSYS*|MINGW*|CYGWIN*) exit ${REMOTE_PLATFORM_UNSUPPORTED};; esac +umask 077 +dir=$(mktemp -d "\${TMPDIR:-/tmp}/ocx-fanout.XXXXXXXX") || exit 127 +tmp=$dir/version; ready=$dir/ready +trap 'rm -rf "$dir"' EXIT HUP INT TERM +try_ocx() { + c=$1; shift + [ -x "$c" ] || return + ( ulimit -c 0; ulimit -f 1; exec "$c" --version ) >"$tmp" 2>/dev/null & vp=$! + ( sleep 10 & timer=$!; trap 'kill "$timer" 2>/dev/null; wait "$timer" 2>/dev/null; exit' TERM HUP INT; : > "$ready"; wait "$timer" 2>/dev/null; kill -9 "$vp" 2>/dev/null ) >/dev/null 2>&1 & watchdog=$! + while [ ! -f "$ready" ]; do kill -0 "$watchdog" 2>/dev/null || break; sleep 0.01 >/dev/null 2>&1; done + { wait "$vp"; status=$?; } 2>/dev/null + kill "$watchdog" 2>/dev/null; wait "$watchdog" 2>/dev/null; rm -f "$ready" + [ "$status" -eq 0 ] || return + bytes=$(wc -c < "$tmp" 2>/dev/null) || return + [ "$bytes" -le 256 ] 2>/dev/null || return + version=$(cat "$tmp"); version=\${version#opencodex } + printf '%s\\n' "$version" | awk ' + function idlist(s,pre, n,a,i) { + n=split(s,a,/\\./); if (!n) return 0; + for(i=1;i<=n;i++) if(a[i]=="" || a[i] !~ /^[0-9A-Za-z-]+$/ || (pre && a[i] ~ /^[0-9]+$/ && length(a[i])>1 && substr(a[i],1,1)=="0")) return 0; + return 1 + } + function cmp(a,b) { if(length(a)!=length(b)) return length(a)>length(b)?1:-1; return ("x" a)==("x" b)?0:(("x" a)>("x" b)?1:-1) } + NR==1 { + v=$0; if(length(v)>128) { result=2; next } + plus=index(v,"+"); if(plus) { build=substr(v,plus+1); v=substr(v,1,plus-1); if(!idlist(build,0)) {result=2; next} } + dash=index(v,"-"); if(dash) { pre=substr(v,dash+1); v=substr(v,1,dash-1); if(!idlist(pre,1)) {result=2; next} } + if(split(v,a,/\\./)!=3) { result=2; next } + for(i=1;i<=3;i++) if(a[i] !~ /^(0|[1-9][0-9]*)$/) { result=2; next } + c=cmp(a[1],"2"); if(!c)c=cmp(a[2],"93"); if(!c)c=cmp(a[3],"0"); if(c<0 || (!c && dash))result=1 + } + NR>1 {result=2} + END {exit result} + ' 2>/dev/null + status=$? + if [ "$status" -eq 1 ]; then printf '%s\\n' 'ocx-fanout:child-ocx-lacks-expect-link' >&2; exit 121; fi + if [ "$status" -ne 0 ]; then printf '%s\\n' 'ocx-fanout:child-ocx-version-unknown' >&2; exit 121; fi + rm -rf "$dir"; trap - EXIT HUP INT TERM + printf 'ocx-fanout:selected:%s\\n' "$version" >&2 + printf '%s\\n' 'ocx-fanout:stdout-begin' + exec "$c" sync --expect-link "$1" --json +} +${REMOTE_OCX_CANDIDATES} +exit ${REMOTE_COMMAND_NOT_FOUND}`; + +export function remotePinnedSyncArgv(linkId: string, platform: "posix" | "windows" = "posix"): string[] { + return platform === "windows" ? windowsPinnedSyncArgv(linkId) : ["sh", "-c", REMOTE_PINNED_SYNC_SCRIPT, "ocx", linkId]; +} diff --git a/structure/cli-management.md b/structure/cli-management.md index 27f2c65acee..1553e7a5805 100644 --- a/structure/cli-management.md +++ b/structure/cli-management.md @@ -4,9 +4,11 @@ ## CLI readiness diagnostics +`src/cli/sync-command.ts` runs the Home sync before calling the fan-out primitives in `src/cli/sync-fanout.ts`, `src/cli/sync-fanout-process.ts` and `src/cli/sync-link-status.ts`. Fan-out requires a committed converged catalog, limits concurrency to three, and reports partial failure as exit 6; an unreadable link store produces a fixed path-free stderr message in human mode. A thrown Home error in JSON mode produces a sanitized stderr diagnostic. The subprocess helper bounds output, treats grace-cancelled pipes as incomplete, and escalates termination; the status helper shares one deadline across discovery and response body. Pinned and connected syncs do not fan out. + `src/cli/status.ts` retains connection transport in the status JSON. Link clients identify Remote Link Home in the banner and connection line. They read supported Hub state through the identity-checked local Child without a CLI credential, retain owner-bound cache fallback on transport errors, and report standalone Home role absence without obsolete Hub cache. Hub clients retain their existing remote provider and login report. -Catalog-derived reasoning-level diagnostics are escaped only at the human-output boundary, which `src/cli/runtime-api.ts` owns alongside the human/JSON print split. Every CLI path that prints a hub-supplied catalog value renders it there: the first-time refusal in `src/cli/connect.ts` and the connected `ocx sync` refusal in `src/cli/dispatch.ts`. C0/C1 controls, DEL, and Unicode line/paragraph separators print as visible hexadecimal escapes; structured status retains the exact reason, and a rendered failure keeps the domain error as its `cause`. The ready/unverified/incompatible classification and exit policy are unchanged. `src/cli/capabilities-command.ts` rejects leftover positional arguments, unknown or repeated flags, and blank route filters with exit 64 before emitting a capability index; a valid unmatched route remains exit 4. `printData` in `src/cli/runtime-api.ts` escapes each human-output line at the shared renderer, including role and delegation-model suggestion rationale. JSON output retains the exact original values. `src/cli/export-command.ts` passes native serialized documents as individual lines so their multiline layout is preserved. `tests/cli/cli-headless-parity.test.ts` checks both suggestion paths independently from their parsed JSON output; `tests/cli/cli-export-command.test.ts` covers export framing. `src/cli/hub-disable.ts` implements `ocx hub disable` as one fresh validated config mutation, with explicit `--client-key ` selection for `--revoke-clients` because saved keys lack immutable client origin; names never select keys and non-hub roles refuse. It projects only secret-redacted metadata and supervisor/external-publishing advice, without restarting anything. `src/cli/observe.ts` reports no matches for an empty filtered human log window while preserving JSON/JSONL; `src/server/request-log-filter.ts` matches whole bare IDs or provider/model pairs within a single row/attempt before pagination. +Catalog-derived reasoning-level diagnostics are escaped only at the human-output boundary, which `src/cli/runtime-api.ts` owns alongside the human/JSON print split. Every CLI path that prints a hub-supplied catalog value renders it there: the first-time refusal in `src/cli/connect.ts` and the connected `ocx sync` refusal in `src/cli/sync-command.ts`. C0/C1 controls, DEL, and Unicode line/paragraph separators print as visible hexadecimal escapes; structured status retains the exact reason, and a rendered failure keeps the domain error as its `cause`. The ready/unverified/incompatible classification and exit policy are unchanged. `src/cli/capabilities-command.ts` rejects leftover positional arguments, unknown or repeated flags, and blank route filters with exit 64 before emitting a capability index; a valid unmatched route remains exit 4. `printData` in `src/cli/runtime-api.ts` escapes each human-output line at the shared renderer, including role and delegation-model suggestion rationale. JSON output retains the exact original values. `src/cli/export-command.ts` passes native serialized documents as individual lines so their multiline layout is preserved. `tests/cli/cli-headless-parity.test.ts` checks both suggestion paths independently from their parsed JSON output; `tests/cli/cli-export-command.test.ts` covers export framing. `src/cli/hub-disable.ts` implements `ocx hub disable` as one fresh validated config mutation, with explicit `--client-key ` selection for `--revoke-clients` because saved keys lack immutable client origin; names never select keys and non-hub roles refuse. It projects only secret-redacted metadata and supervisor/external-publishing advice, without restarting anything. `src/cli/observe.ts` reports no matches for an empty filtered human log window while preserving JSON/JSONL; `src/server/request-log-filter.ts` matches whole bare IDs or provider/model pairs within a single row/attempt before pagination. `src/cli/desktop-runtime-guidance.ts` names verified Desktop supervision of the target for duplicate starts and accepted restart requests. Ordinary stop warns on stderr that Desktop @@ -167,7 +169,7 @@ Remote Link enrollment is shared with the dashboard through `src/server/manageme An explicit `sync --restart-codex` (or app-server-only scope) also reloads after a committed configuration-byte change, even when no catalog/cache was written. Without an explicit restart scope, configuration-only changes do not restart clients. Existing catalog/cache-write restart behavior remains unchanged; success alone is not proof of changed configuration. -`ocx sync --expect-link ` and `--expect-hub-key ` (#7694) pin the sync to one connection. `src/cli/sync-expectation.ts` parses them, first in `src/cli/root.ts` before any preflight (malformed, repeated or doubled flags exit 2), and renders a refusal as exit 5 with a final stderr JSON line `{phase, reason}`. `skipsCodexShimAutoRestore` exempts a pinned sync from the root shim repair, which the runner awaits (`runCodexShimAutoRestoreAsync`) only after the identity check passed. With an expectation, the `sync` runner in `src/cli/dispatch.ts` ignores its own unlocked state read and always enters `syncConnectedClient`, which checks the expectation (`src/client/sync-expectation.ts`) inside its first lifecycle/config-locked block, under the apply lock, before the token check, any request or any write. A refusal never reaches `syncModelsToCodex`, local proxy discovery or integration refreshes. The runner takes link-vs-hub wording and restart ownership from `result.connection`, the connection the sync ran under; `/api/machine/sync` strips that field from its response. If a lock the check needs is held before the check ran (`link_apply_busy` from `withLinkApply`, because a link connect keeps the apply lock across its network reads, `client_lifecycle_busy`, or `CONFIG_MUTATION_LOCK_UNAVAILABLE` caused by SQLite busy/locked), the pinned sync is refused as `pending_operation`; the same contention after the check, or without an expectation, stays an ordinary failure. A connection that changes after the check fails at the existing compare-and-swap (`client_connection_changed`, exit 1). Coverage: `tests/cli/cli-sync-expect-link.test.ts`. +`ocx sync --expect-link ` and `--expect-hub-key ` (#7694) pin the sync to one connection. `src/cli/sync-expectation.ts` parses them, first in `src/cli/root.ts` before any preflight (malformed, repeated or doubled flags exit 2), and renders a refusal as exit 5 with a final stderr JSON line `{phase, reason}`. `skipsCodexShimAutoRestore` exempts a pinned sync from the root shim repair, which the runner awaits (`runCodexShimAutoRestoreAsync`) only after the identity check passed. With an expectation, the `sync` runner in `src/cli/sync-command.ts` ignores its own unlocked state read and always enters `syncConnectedClient`, which checks the expectation (`src/client/sync-expectation.ts`) inside its first lifecycle/config-locked block, under the apply lock, before the token check, any request or any write. A refusal never reaches `syncModelsToCodex`, local proxy discovery or integration refreshes. The runner takes link-vs-hub wording and restart ownership from `result.connection`, the connection the sync ran under; `/api/machine/sync` strips that field from its response. If a lock the check needs is held before the check ran (`link_apply_busy` from `withLinkApply`, because a link connect keeps the apply lock across its network reads, `client_lifecycle_busy`, or `CONFIG_MUTATION_LOCK_UNAVAILABLE` caused by SQLite busy/locked), the pinned sync is refused as `pending_operation`; the same contention after the check, or without an expectation, stays an ordinary failure. A connection that changes after the check fails at the existing compare-and-swap (`client_connection_changed`, exit 1). Coverage: `tests/cli/cli-sync-expect-link.test.ts`. ## Custom Codex provider approval diff --git a/structure/remote-link.md b/structure/remote-link.md index 44f0dcb2004..2300d5f1c78 100644 --- a/structure/remote-link.md +++ b/structure/remote-link.md @@ -1,5 +1,7 @@ # Remote Link +`src/link/ssh-argv.ts` and `src/link/remote-windows.ts` build pinned Child sync commands that select and version-check the same executable before executing `sync --expect-link` without a restart flag. Fan-out platform discovery in `src/link/remote-platform.ts` accepts a Windows marker on any stdout line or one framed uname line, so login-shell output cannot decide the platform. The Home requires one valid selection marker on stderr and one stdout delimiter, and classifies only the text after that delimiter; login-shell output before them is ignored. Oversized version probes are skipped. POSIX version capture and watchdog readiness use a private temporary directory, removed before execution or on refusal. The Home's `src/cli/sync-command.ts` fans out only after its catalog is current; the Child may still restart its own OpenCodex client runtime after applying changed Home settings. + `src/link/` owns the building blocks for linking OpenCodex machines over SSH. The pure modules start no process, open no socket and schedule no timer on import. `src/link/ssh-argv.ts` builds every OpenSSH argument vector. All commands run with BatchMode and trust only the link known_hosts file, keyed by `HostKeyAlias=`: the global file is disabled with `GlobalKnownHostsFile=none`, and `KnownHostsCommand=none`, `VerifyHostKeyDNS=no` and `CheckHostIP=no` shut out every other source of host-key trust. Command-line options take precedence over `~/.ssh/config`, so a user config cannot re-enable them. `HashKnownHosts=no` preserves alias-prefixed records in these private files without changing the user's normal known_hosts file. Tunnel and exec commands use `StrictHostKeyChecking=yes`; only the probe uses `accept-new`, against an empty temporary file, so an offered key can be shown before it is trusted. The known_hosts path must be absolute and free of ssh expansion syntax. Forwards bind 127.0.0.1 on both ends, and aliases that could be parsed as options are refused. diff --git a/tests/cli/cli-capabilities-arguments.test.ts b/tests/cli/cli-capabilities-arguments.test.ts index ee6b4d9d1cd..083329ab3ed 100644 --- a/tests/cli/cli-capabilities-arguments.test.ts +++ b/tests/cli/cli-capabilities-arguments.test.ts @@ -6,6 +6,7 @@ describe("capabilities argument validation", () => { ["--mutating-onyl"], ["extra"], ["--json", "--json"], ["--route", "/api/logs", "--route", "/api/usage"], ["--route", "/not-a-route", "--typo"], ["--route", ""], + ["--contracts", "--route", "/api/logs"], ["--contracts", "--mutating-only"], ].map(args => [args]))("rejects %j without a successful payload", async args => { const out = spyOn(console, "log").mockImplementation(() => {}); const err = spyOn(console, "error").mockImplementation(() => {}); @@ -15,6 +16,21 @@ describe("capabilities argument validation", () => { expect(err).toHaveBeenCalled(); } finally { out.mockRestore(); err.mockRestore(); } }); + test("exposes the contract list in every JSON form", async () => { + const out = spyOn(console, "log").mockImplementation(() => {}); + try { + for (const args of [["--json"], ["--json", "--mutating-only"], ["--json", "--route", "/not-a-route"], ["--json", "--contracts"]]) { + out.mockClear(); + expect(await runCapabilities(args)).toBe(args.includes("/not-a-route") ? 4 : 0); + const payload = JSON.parse(String(out.mock.calls[0]![0])); + expect(payload.contracts).toContain("sync.home-fanout/1"); + if (args.includes("--contracts")) expect(Object.keys(payload)).toEqual(["schemaVersion", "contracts"]); + } + out.mockClear(); + expect(await runCapabilities(["--contracts"])).toBe(0); + expect(out.mock.calls.map(call => call[0])).toContain("sync.home-fanout/1"); + } finally { out.mockRestore(); } + }); test("keeps valid no-match distinct from invalid usage", async () => { const out = spyOn(console, "log").mockImplementation(() => {}); try { diff --git a/tests/cli/cli-json-contract.test.ts b/tests/cli/cli-json-contract.test.ts index a4672cb81b5..a8519fd158b 100644 --- a/tests/cli/cli-json-contract.test.ts +++ b/tests/cli/cli-json-contract.test.ts @@ -43,7 +43,7 @@ describe("--json is order-independent", () => { // Generalises the two known defects: any `args[] === "--json"` is the same bug // waiting to happen in another command. const offenders: string[] = []; - for (const rel of ["src/cli/dispatch.ts", "src/cli/index.ts", "src/cli/root.ts"]) { + for (const rel of ["src/cli/dispatch.ts", "src/cli/index.ts", "src/cli/root.ts", "src/cli/sync-command.ts"]) { const lines = read(rel).split("\n"); lines.forEach((line, i) => { if (/args\[\d+\]\s*===\s*"--json"/.test(line)) offenders.push(`${rel}:${i + 1}`); diff --git a/tests/cli/cli-transport-honesty.test.ts b/tests/cli/cli-transport-honesty.test.ts index f8f61359c22..10ca176b0ea 100644 --- a/tests/cli/cli-transport-honesty.test.ts +++ b/tests/cli/cli-transport-honesty.test.ts @@ -19,6 +19,7 @@ import { repoPath } from "../helpers/repo-root"; */ const DISPATCH_SOURCE = readFileSync(repoPath("src", "cli", "dispatch.ts"), "utf8"); +const SYNC_SOURCE = readFileSync(repoPath("src", "cli", "sync-command.ts"), "utf8"); /** * Matches `await someHandler(...); return 0;` — the shape that silently discards a @@ -107,6 +108,7 @@ describe("#2697 dispatch runners preserve handler exit codes", () => { test("no runner discards a handler exit code outside the allowlist", () => { const offenders = swallowingRunners(DISPATCH_SOURCE).filter(name => !CANNOT_FAIL_ALLOWLIST.has(name)); expect(offenders).toEqual([]); + expect(SYNC_SOURCE.match(SWALLOWED_EXIT_CODE) ?? []).toEqual([]); }); test("provider and models return process.exitCode rather than a literal 0", () => { diff --git a/tests/cli/sync-command-fanout.test.ts b/tests/cli/sync-command-fanout.test.ts new file mode 100644 index 00000000000..bc2fada5127 --- /dev/null +++ b/tests/cli/sync-command-fanout.test.ts @@ -0,0 +1,192 @@ +import { expect, spyOn, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { repoPath } from "../helpers/repo-root"; +import { parseSyncFanoutFlags } from "../../src/cli/sync-flags"; +import { runSyncCommand } from "../../src/cli/sync-command"; +import type { CliDispatchDeps } from "../../src/cli/dispatch"; +import * as codexSync from "../../src/codex/sync"; +import * as statusApi from "../../src/cli/sync-link-status"; +import * as processApi from "../../src/cli/sync-fanout-process"; + +test.each(["--json", "--local-only"])("parser rejects repeated %s", flag => { + expect(parseSyncFanoutFlags([flag, flag]).ok).toBe(false); +}); + +test.each(["--json", "--local-only"])("repeated %s is refused before preflight", flag => { + const temp = mkdtempSync(join(tmpdir(), "ocx-sync-flags-")); + try { + const result = Bun.spawnSync(["bun", "run", repoPath("src/cli/index.ts"), "sync", flag, flag], { + env: { ...process.env, OPENCODEX_HOME: join(temp, "ocx"), CODEX_HOME: join(temp, "codex") }, + stdout: "pipe", stderr: "pipe", + }); + expect(result.exitCode).toBe(2); + expect(result.stdout.toString()).toBe(""); + } finally { rmSync(temp, { recursive: true, force: true }); } +}); + +test("pinned JSON mismatch is one document and does not invoke ssh", () => { + const temp = mkdtempSync(join(tmpdir(), "ocx-sync-pinned-")); + try { + const result = Bun.spawnSync([process.execPath, "run", repoPath("src/cli/index.ts"), "sync", "--expect-link", "lnk_0123456789abcdef", "--json"], { + env: { ...process.env, OPENCODEX_HOME: join(temp, "ocx"), CODEX_HOME: join(temp, "codex"), PATH: temp }, + stdout: "pipe", stderr: "pipe", + }); + expect(result.exitCode).toBe(5); + expect(JSON.parse(result.stdout.toString())).toEqual({ schema: "ocx.sync.fanout/1", home: { state: "failed", exit: 5 }, fanout: { state: "not-applicable", reason: null }, children: [] }); + expect(result.stderr.toString()).toContain('"phase":"child_link_mismatch"'); + } finally { rmSync(temp, { recursive: true, force: true }); } +}); + +test("local-only JSON does not invoke ssh", async () => { + const temp = mkdtempSync(join(tmpdir(), "ocx-sync-local-")); + const server = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => new Response("not ocx", { status: 404 }) }); + try { + const home = join(temp, "ocx"), linkDir = join(home, "link"); + mkdirSync(linkDir, { recursive: true }); + writeFileSync(join(home, "config.json"), JSON.stringify({ port: server.port, providers: {}, defaultProvider: "openai" })); + writeFileSync(join(linkDir, "links.json"), JSON.stringify({ version: 1, listenerPort: 27000, links: [{ id: "lnk_0123456789abcdef", alias: "fake", direction: "hub-initiated", hostKeyFingerprint: "SHA256:AAAAAAAAAAAAAAAA", tunnelPort: 27001, apiKeyId: "test", createdAt: "2026-01-01T00:00:00Z" }] })); + writeFileSync(join(temp, "ssh"), `#!/bin/sh\nprintf called > '${join(temp, "ssh-called")}'\nexit 1\n`, { mode: 0o755 }); + const child = Bun.spawn([process.execPath, "run", repoPath("src/cli/index.ts"), "sync", "--local-only", "--json"], { + env: { HOME: temp, OPENCODEX_HOME: home, CODEX_HOME: join(temp, "codex"), PATH: `${temp}:/usr/bin:/bin` }, + stdout: "pipe", stderr: "pipe", + }); + const [code, stdout] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + const document = JSON.parse(stdout); + expect(document.schema).toBe("ocx.sync.fanout/1"); + expect(document.home.exit).toBe(code); + expect(document.fanout).toEqual({ state: "disabled", reason: null }); + expect(document.children).toEqual([]); + expect(existsSync(join(temp, "ssh-called"))).toBe(false); + } finally { server.stop(true); rmSync(temp, { recursive: true, force: true }); } +}, 15000); + +test("human sync reports a damaged link store without exposing its path", async () => { + const temp = mkdtempSync(join(tmpdir(), "ocx-sync-damaged-")); + const server = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => new Response("not ocx", { status: 404 }) }); + try { + const home = join(temp, "ocx"), linkDir = join(home, "link"); + mkdirSync(linkDir, { recursive: true }); + mkdirSync(join(temp, "codex")); + writeFileSync(join(temp, "codex", "config.toml"), `model_catalog_json = ${JSON.stringify(join(temp, "missing-catalog.json"))}\n`); + writeFileSync(join(home, "config.json"), JSON.stringify({ port: server.port, providers: {}, defaultProvider: "openai", clientIntegrations: { codex: false } })); + writeFileSync(join(linkDir, "links.json"), "invalid"); + const child = Bun.spawn([process.execPath, "run", repoPath("src/cli/index.ts"), "sync"], { + env: { HOME: temp, OPENCODEX_HOME: home, CODEX_HOME: join(temp, "codex"), PATH: `${temp}:/usr/bin:/bin` }, + stdout: "pipe", stderr: "pipe", + }); + const [code, stdout, stderr] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + expect(code).toBe(6); + expect(stderr).toContain("Children were not synced: the Remote Link store could not be read."); + expect(stderr).not.toContain(join(linkDir, "links.json")); + expect(stdout).not.toContain("link-store-unreadable"); + } finally { server.stop(true); rmSync(temp, { recursive: true, force: true }); } +}, 15000); + +test("committed Home catalog fans out after the Home step; refused refresh does not", async () => { + const temp = mkdtempSync(join(tmpdir(), "ocx-sync-gate-")); + const previousHome = process.env.OPENCODEX_HOME, previousExit = process.exitCode; + process.env.OPENCODEX_HOME = temp; process.exitCode = 0; + const linkDir = join(temp, "link"); mkdirSync(linkDir, { recursive: true }); + const link = { id: "lnk_0123456789abcdef", alias: "fake", direction: "hub-initiated" as const, hostKeyFingerprint: "SHA256:AAAAAAAAAAAAAAAA", tunnelPort: 27001, apiKeyId: "test", createdAt: "2026-01-01T00:00:00Z", remotePlatform: "posix" as const }; + writeFileSync(join(temp, "config.json"), JSON.stringify({ providers: {}, defaultProvider: "openai" })); + writeFileSync(join(linkDir, "links.json"), JSON.stringify({ version: 1, listenerPort: 27000, links: [link] })); + const base = { status: "catalog-only" as const, ok: true, added: 0, catalogPath: "fixture", catalogExists: true, catalogWritten: false, cacheSynced: false, message: "done" }; + const events: string[] = [], output: string[] = [], errors: string[] = []; + const sync = spyOn(codexSync, "syncModelsToCodex").mockImplementation(async () => { events.push("home"); return { ...base, refreshOutcome: "committed" }; }); + const status = spyOn(statusApi, "readHomeLinkStatus").mockImplementation(async () => { events.push("status"); return { role: "home", listener: { state: "listening", port: 27000 }, child: null, links: [{ ...link, state: "connected", since: link.createdAt, reason: null, lastApplyAt: null, runtimeStartedAt: null, appliedCodexSettingsDigest: null }] }; }); + const child = spyOn(processApi, "runFanoutProcess").mockImplementation(async argv => { events.push("child"); expect(argv.join(" ")).not.toContain("--restart-codex"); return { code: 0, stdout: "ocx-fanout:stdout-begin\nRemote Link Home catalog synchronized.", stderr: "ocx-fanout:selected:2.93.0+build.5\n" }; }); + const log = spyOn(console, "log").mockImplementation((...parts) => { output.push(parts.map(String).join(" ")); }); + const error = spyOn(console, "error").mockImplementation((...parts) => { errors.push(parts.map(String).join(" ")); }); + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + const deps = { args: ["sync", "--json"], findLiveProxy: async () => null } as unknown as CliDispatchDeps; + expect(await runSyncCommand(deps)).toBe(0); + expect(events).toEqual(["home", "status", "child"]); + expect(JSON.parse(output.at(-1)!).children[0]).toMatchObject({ state: "synced", reason: null }); + events.length = 0; output.length = 0; + sync.mockImplementation(async () => { events.push("home"); return { ...base, refreshOutcome: "refused" }; }); + expect(await runSyncCommand(deps)).toBe(0); + expect(events).toEqual(["home"]); + expect(JSON.parse(output.at(-1)!).children[0]).toMatchObject({ state: "skipped", reason: "home-catalog-not-current" }); + const original = new Error("fixture Home failure\n\u001b[31m"); + sync.mockImplementation(async () => { throw original; }); + output.length = 0; errors.length = 0; + expect(await runSyncCommand(deps)).toBe(1); + expect(output).toHaveLength(1); + expect(JSON.parse(output.at(-1)!)).toMatchObject({ home: { state: "failed", exit: 1 }, children: [{ state: "skipped", reason: "home-sync-failed" }] }); + expect(errors).toEqual(["Sync failed: fixture Home failure\\x0a\\x1b[31m"]); + errors.length = 0; + await expect(runSyncCommand({ ...deps, args: ["sync"] })).rejects.toBe(original); + expect(errors).toEqual(["Children were not synced because the Home sync failed."]); + writeFileSync(join(linkDir, "links.json"), "invalid"); errors.length = 0; + await expect(runSyncCommand({ ...deps, args: ["sync"] })).rejects.toBe(original); + expect(errors).toEqual([]); + } finally { + sync.mockRestore(); status.mockRestore(); child.mockRestore(); log.mockRestore(); error.mockRestore(); warn.mockRestore(); + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previousHome; + process.exitCode = previousExit ?? 0; rmSync(temp, { recursive: true, force: true }); + } +}); + +test("fan-out discovers unstored platforms despite shell startup output", async () => { + const temp = mkdtempSync(join(tmpdir(), "ocx-sync-platform-")); + const previousHome = process.env.OPENCODEX_HOME, previousExit = process.exitCode; + process.env.OPENCODEX_HOME = temp; process.exitCode = 0; + const linkDir = join(temp, "link"); mkdirSync(linkDir, { recursive: true }); + const link = { id: "lnk_0123456789abcdef", alias: "fake", direction: "hub-initiated" as const, hostKeyFingerprint: "SHA256:AAAAAAAAAAAAAAAA", tunnelPort: 27001, apiKeyId: "test", createdAt: "2026-01-01T00:00:00Z" }; + writeFileSync(join(temp, "config.json"), JSON.stringify({ providers: {}, defaultProvider: "openai" })); + writeFileSync(join(linkDir, "links.json"), JSON.stringify({ version: 1, listenerPort: 27000, links: [link] })); + const base = { status: "catalog-only" as const, ok: true, added: 0, catalogPath: "fixture", catalogExists: true, catalogWritten: false, cacheSynced: false, message: "done", refreshOutcome: "committed" as const }; + const sync = spyOn(codexSync, "syncModelsToCodex").mockResolvedValue(base); + const status = spyOn(statusApi, "readHomeLinkStatus").mockResolvedValue({ role: "home", listener: { state: "listening", port: 27000 }, child: null, links: [{ ...link, state: "connected", since: link.createdAt, reason: null, lastApplyAt: null, runtimeStartedAt: null, appliedCodexSettingsDigest: null }] }); + const output: string[] = [], commands: string[] = [], probes: string[][] = []; + const log = spyOn(console, "log").mockImplementation((...parts) => { output.push(parts.map(String).join(" ")); }); + const error = spyOn(console, "error").mockImplementation(() => {}); + const warn = spyOn(console, "warn").mockImplementation(() => {}); + let responses: Array<{ code: number; stdout: string; stderr: string }> = []; + const runner = spyOn(processApi, "fanoutSshRunner").mockImplementation(() => ({ run: async (argv, options) => { probes.push([...argv]); expect(options?.timeoutMs).toBe(10_000); return responses.shift()!; } })); + const child = spyOn(processApi, "runFanoutProcess").mockImplementation(async argv => { commands.push(argv.at(-1)!); return { code: 0, stdout: "ocx-fanout:stdout-begin\nRemote Link Home catalog synchronized.", stderr: "ocx-fanout:selected:2.93.0\n" }; }); + try { + const deps = { args: ["sync", "--json"], findLiveProxy: async () => null } as unknown as CliDispatchDeps; + const startup = "shell startup warning\n"; + responses = [{ code: 127, stdout: startup, stderr: startup }, { code: 0, stdout: `${startup}ocx-platform:Linux\n`, stderr: startup }]; + expect(await runSyncCommand(deps)).toBe(0); + expect(JSON.parse(output.at(-1)!).children[0]).toMatchObject({ state: "synced", reason: null }); + expect(commands.at(-1)).toContain("sh "); + expect(probes[0]!.at(-1)).toBe("cmd /c echo %OS%"); + expect(probes[1]!.at(-1)).toContain("ocx-platform:%s"); + expect(probes[1]).toContain("StrictHostKeyChecking=yes"); + responses = [{ code: 0, stdout: `${startup} Windows_NT \n`, stderr: startup }]; output.length = 0; commands.length = 0; probes.length = 0; + expect(await runSyncCommand(deps)).toBe(0); + expect(JSON.parse(output.at(-1)!).children[0]).toMatchObject({ state: "synced", reason: null }); + expect(commands.at(-1)).toContain("powershell.exe"); + expect(probes).toHaveLength(1); + responses = [{ code: 127, stdout: startup, stderr: startup }, { code: 0, stdout: `${startup}ocx-platform:Linux\nocx-platform:Linux\n`, stderr: startup }]; output.length = 0; commands.length = 0; probes.length = 0; + expect(await runSyncCommand(deps)).toBe(6); + expect(JSON.parse(output.at(-1)!).children[0]).toMatchObject({ state: "failed", reason: "platform-probe-failed" }); + expect(commands).toEqual([]); + responses = [{ code: 127, stdout: startup, stderr: startup }, { code: 0, stdout: startup, stderr: startup }]; output.length = 0; commands.length = 0; probes.length = 0; + expect(await runSyncCommand(deps)).toBe(6); + expect(JSON.parse(output.at(-1)!).children[0]).toMatchObject({ state: "failed", reason: "platform-probe-failed" }); + expect(commands).toEqual([]); + responses = [{ code: 127, stdout: startup, stderr: startup }, { code: 0, stdout: `${startup}ocx-platform:MINGW64_NT-10.0\n`, stderr: startup }]; output.length = 0; commands.length = 0; probes.length = 0; + expect(await runSyncCommand(deps)).toBe(0); + expect(commands.at(-1)).toContain("powershell.exe"); + responses = [{ code: 255, stdout: `${startup}Windows_NT\n`, stderr: startup }]; output.length = 0; commands.length = 0; probes.length = 0; + expect(await runSyncCommand(deps)).toBe(6); + expect(JSON.parse(output.at(-1)!).children[0]).toMatchObject({ state: "failed", reason: "platform-probe-failed" }); + expect(probes).toHaveLength(1); + expect(commands).toEqual([]); + responses = [{ code: 127, stdout: startup, stderr: startup }, { code: 255, stdout: "ocx-platform:Linux\n", stderr: startup }]; output.length = 0; commands.length = 0; probes.length = 0; + expect(await runSyncCommand(deps)).toBe(6); + expect(JSON.parse(output.at(-1)!).children[0]).toMatchObject({ state: "failed", reason: "platform-probe-failed" }); + expect(probes).toHaveLength(2); + expect(commands).toEqual([]); + } finally { + sync.mockRestore(); status.mockRestore(); runner.mockRestore(); child.mockRestore(); log.mockRestore(); error.mockRestore(); warn.mockRestore(); + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previousHome; + process.exitCode = previousExit ?? 0; rmSync(temp, { recursive: true, force: true }); + } +}); diff --git a/tests/cli/sync-fanout-process.test.ts b/tests/cli/sync-fanout-process.test.ts new file mode 100644 index 00000000000..d34e04e73ba --- /dev/null +++ b/tests/cli/sync-fanout-process.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, test } from "bun:test"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { repoPath } from "../helpers/repo-root"; +import { runFanoutProcess, FanoutProcessError } from "../../src/cli/sync-fanout-process"; + +describe.skipIf(process.platform === "win32")("fanout process ownership", () => { + test("returns a child exit code", async () => { + expect(await runFanoutProcess(["sh", "-c", "exit 255"], { timeoutMs: 1000 })).toEqual({ code: 255, stdout: "", stderr: "" }); + }); + test("escalates and waits for a child that ignores TERM", async () => { + let pid = 0; + try { + await runFanoutProcess(["sh", "-c", "trap '' TERM; printf '%s' $$; while :; do :; done"], { timeoutMs: 200, onSpawn: value => { pid = value; } }); + throw new Error("expected deadline"); + } catch (error) { + expect(error).toBeInstanceOf(FanoutProcessError); + expect((error as FanoutProcessError).reason).toBe("deadline-exceeded"); + expect(pid).toBeGreaterThan(0); + expect(() => process.kill(pid, 0)).toThrow(); + } + }, 6000); + test("rejects output above the cap", async () => { + await expect(runFanoutProcess(["sh", "-c", "printf 123456789"], { timeoutMs: 1000, maxOutputBytes: 4 })).rejects.toMatchObject({ reason: "ssh-output" }); + }); + test("an elapsed deadline does not spawn a process", async () => { + let spawned = false; + await expect(runFanoutProcess(["sh", "-c", "exit 0"], { timeoutMs: 0, onSpawn: () => { spawned = true; } })).rejects.toMatchObject({ reason: "deadline-exceeded" }); + expect(spawned).toBe(false); + }); +}); + +test.skipIf(process.platform !== "linux")("a pipe held by a descendant fails closed and the descendant is reaped", async () => { + const home = mkdtempSync(join(tmpdir(), "ocx-fanout-pipe-")); + const fixture = join(home, "subreaper.ts"), pidPath = join(home, "writer.pid"); + writeFileSync(fixture, String.raw` +import { dlopen, FFIType, ptr } from "bun:ffi"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { spyOn } from "bun:test"; +const libc = dlopen("libc.so.6", { + prctl: { args: [FFIType.i32, FFIType.i64, FFIType.i64, FFIType.i64, FFIType.i64], returns: FFIType.i32 }, + waitpid: { args: [FFIType.i32, FFIType.ptr, FFIType.i32], returns: FFIType.i32 }, +}); +if (libc.symbols.prctl(36, 1, 0, 0, 0) !== 0) throw new Error("subreaper setup failed"); +const commandApi = await import(process.argv[2]); +const processApi = await import(process.argv[3]); +const codexSync = await import(process.argv[4]); +const statusApi = await import(process.argv[5]); +const shell = "(sleep 0.8; printf '%s\\n' 'Home unavailable; retained and applied the last-known-good remote catalog (stale).') 2>/dev/null & echo $! > \"$1\"; printf '%s\\n' 'ocx-fanout:stdout-begin' 'Remote Link Home catalog synchronized.'; printf '%s\\n' 'ocx-fanout:selected:2.93.0' >&2; exit 0"; +const home = process.env.OPENCODEX_HOME, linkDir = join(home, "link"); +mkdirSync(linkDir, { recursive: true }); +const link = { id: "lnk_0123456789abcdef", alias: "fake", direction: "hub-initiated", hostKeyFingerprint: "SHA256:AAAAAAAAAAAAAAAA", tunnelPort: 27001, apiKeyId: "test", createdAt: "2026-01-01T00:00:00Z", remotePlatform: "posix" }; +writeFileSync(join(home, "config.json"), JSON.stringify({ providers: {}, defaultProvider: "openai" })); +writeFileSync(join(linkDir, "links.json"), JSON.stringify({ version: 1, listenerPort: 27000, links: [link] })); +spyOn(codexSync, "syncModelsToCodex").mockResolvedValue({ status: "catalog-only", ok: true, added: 0, catalogPath: "fixture", catalogExists: true, catalogWritten: false, cacheSynced: false, message: "done", refreshOutcome: "committed" }); +spyOn(statusApi, "readHomeLinkStatus").mockResolvedValue({ role: "home", listener: { state: "listening", port: 27000 }, child: null, links: [{ ...link, state: "connected", since: link.createdAt, reason: null, lastApplyAt: null, runtimeStartedAt: null, appliedCodexSettingsDigest: null }] }); +const realRun = processApi.runFanoutProcess; +spyOn(processApi, "runFanoutProcess").mockImplementation(() => realRun(["sh", "-c", shell, "fixture", process.argv[6]], { timeoutMs: 3000 })); +const savedLog = console.log, output = []; +console.log = (...parts) => { output.push(parts.map(String).join(" ")); }; +console.error = () => {}; +console.warn = () => {}; +const code = await commandApi.runSyncCommand({ args: ["sync", "--json"], findLiveProxy: async () => null }); +const document = JSON.parse(output[0]); +const { reason, state } = document.children[0]; +const pid = Number(readFileSync(process.argv[6], "utf8")); +const status = new Int32Array(1), deadline = Date.now() + 2500; +let reaped = false; +while (Date.now() < deadline) { + const result = libc.symbols.waitpid(pid, ptr(status), 1); + if (result === pid) { reaped = true; break; } + if (result < 0) break; + await Bun.sleep(20); +} +libc.close(); +savedLog(JSON.stringify({ code, reason, state, reaped })); +`); + try { + const child = Bun.spawn([process.execPath, "run", fixture, repoPath("src/cli/sync-command.ts"), repoPath("src/cli/sync-fanout-process.ts"), repoPath("src/codex/sync.ts"), repoPath("src/cli/sync-link-status.ts"), pidPath], { + env: { HOME: home, OPENCODEX_HOME: join(home, "ocx"), CODEX_HOME: join(home, "codex"), PATH: "/usr/bin:/bin" }, + stdout: "pipe", stderr: "pipe", + }); + const [code, stdout, stderr] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + expect({ code, stderr }).toEqual({ code: 0, stderr: "" }); + const result = JSON.parse(stdout); + expect(result).toMatchObject({ code: 6, reason: "ssh-output", state: "failed", reaped: true }); + } finally { rmSync(home, { recursive: true, force: true }); } +}, 6000); diff --git a/tests/cli/sync-fanout.test.ts b/tests/cli/sync-fanout.test.ts new file mode 100644 index 00000000000..21291bf2552 --- /dev/null +++ b/tests/cli/sync-fanout.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, test } from "bun:test"; +import { classifySyncResult, classifyVersionProbe, fanoutExitCode, runHomeFanout } from "../../src/cli/sync-fanout"; +import { LinkStatusError } from "../../src/cli/sync-link-status"; +import type { LinkRecord } from "../../src/link/store"; + +describe("sync fan-out child evidence", () => { + test("accepts startup output only outside exactly one set of framing markers", () => { + const marker = "ocx-fanout:selected:2.93.0+build.5"; + const delimiter = "ocx-fanout:stdout-begin"; + const doc = JSON.stringify({ schema: "ocx.sync.fanout/1", home: { state: "synced", exit: 0 }, fanout: { state: "not-applicable", reason: null }, children: [] }); + const run = (stdout: string, stderr: string) => classifySyncResult({ code: 0, stdout, stderr }); + for (const payload of [doc, "Remote Link Home catalog synchronized."]) { + expect(run(`shell startup warning\n${delimiter}\n${payload}\n`, `shell stderr warning\n${marker}\n`)).toEqual({ state: "synced", reason: null }); + expect(run(`${delimiter}\n${payload}`, `${marker}\n${marker}\n`)).toEqual({ state: "failed", reason: "child-output-invalid" }); + expect(run(payload, `${marker}\n`)).toEqual({ state: "failed", reason: "child-output-invalid" }); + expect(run(`${delimiter}\n${delimiter}\n${payload}`, `${marker}\n`)).toEqual({ state: "failed", reason: "child-output-invalid" }); + } + expect(run(`Home unavailable; retained and applied the last-known-good remote catalog (stale).\n${delimiter}\n${doc}`, `${marker}\n`)).toEqual({ state: "synced", reason: null }); + expect(run(`Remote Link Home catalog synchronized.\n${delimiter}\nno evidence`, `${marker}\n`)).toEqual({ state: "failed", reason: "child-output-invalid" }); + expect(run(`${delimiter}\n${doc}`, "startup\nocx-fanout:selected:2.93.0-01\n")).toEqual({ state: "failed", reason: "child-output-invalid" }); + expect(run(`${delimiter}\n${doc}`, "ocx-fanout:selected:2.93.0 \n")).toEqual({ state: "failed", reason: "child-output-invalid" }); + expect(classifySyncResult({ code: 5, stdout: `startup\n${delimiter}\n`, stderr: `warning\n${marker}\n{"phase":"child_link_mismatch","reason":"other_link"}\n` })).toEqual({ state: "skipped", reason: "child-link-mismatch:other_link" }); + expect(classifySyncResult({ code: 5, stdout: "startup\n", stderr: `${marker}\n` })).toEqual({ state: "failed", reason: "child-output-invalid" }); + expect(classifySyncResult({ code: 121, stdout: "startup\n", stderr: "warning\nocx-fanout:child-ocx-version-unknown\n" })).toEqual({ state: "skipped", reason: "child-ocx-version-unknown" }); + }); + test.each([ + ["2.93.0+build.5", null], ["2.92.9+build", "child-ocx-lacks-expect-link"], + ["2.93.0-preview.1", "child-ocx-lacks-expect-link"], ["garbage", "child-ocx-version-unknown"], + ])("version %s yields %s", (version, reason) => { + expect(classifyVersionProbe(version)).toBe(reason); + }); + + test("requires a valid marker and positive child output", () => { + const run = (code: number, stdout: string, stderr = "ocx-fanout:selected:2.93.0+build.5\n") => classifySyncResult({ code, stdout: `ocx-fanout:stdout-begin\n${stdout}`, stderr }); + expect(run(0, "Remote Link Home catalog synchronized.")).toEqual({ state: "synced", reason: null }); + expect(run(0, "")).toEqual({ state: "failed", reason: "child-output-invalid" }); + expect(run(0, "{bad")).toEqual({ state: "failed", reason: "child-output-invalid" }); + expect(run(0, "Remote Link Home catalog synchronized.", "")).toEqual({ state: "failed", reason: "child-output-invalid" }); + expect(run(1, '{"schema":"ocx.sync.fanout/1","home":{"state":"synced","exit":0},"fanout":{"state":"not-applicable","reason":null},"children":[]}')).toEqual({ state: "failed", reason: "child-sync-failed" }); + expect(run(255, "Remote Link Home catalog synchronized.")).toEqual({ state: "failed", reason: "ssh-failed" }); + const doc = (state: string) => JSON.stringify({ schema: "ocx.sync.fanout/1", home: { state, exit: 0 }, fanout: { state: "not-applicable", reason: null }, children: [] }); + expect(run(0, doc("synced"))).toEqual({ state: "synced", reason: null }); + expect(run(0, doc("stale"))).toEqual({ state: "failed", reason: "child-catalog-stale" }); + expect(run(0, doc("synced") + doc("synced"))).toEqual({ state: "failed", reason: "child-output-invalid" }); + expect(run(0, doc("synced").replace("ocx.sync.fanout/1", "future"))).toEqual({ state: "failed", reason: "child-output-invalid" }); + expect(run(0, doc("synced").replace('"exit":0', '"exit":0,"extra":true'))).toEqual({ state: "failed", reason: "child-output-invalid" }); + expect(run(0, "Remote Link Home catalog synchronized. Home unavailable; retained and applied the last-known-good remote catalog (stale).")) .toEqual({ state: "failed", reason: "child-catalog-stale" }); + expect(run(5, "", 'ocx-fanout:selected:2.93.0\n{"phase":"child_link_mismatch","reason":"other_link"}\n')).toEqual({ state: "skipped", reason: "child-link-mismatch:other_link" }); + expect(run(5, "", 'ocx-fanout:selected:2.93.0\n{"phase":"child_link_mismatch","reason":"surprise"}\n')).toEqual({ state: "skipped", reason: "child-link-mismatch" }); + expect(run(7, "")).toEqual({ state: "skipped", reason: "child-updating" }); + expect(run(127, "", "")).toEqual({ state: "failed", reason: "child-ocx-not-found" }); + expect(run(126, "", "")).toEqual({ state: "failed", reason: "child-ocx-not-contained" }); + expect(run(125, "", "")).toEqual({ state: "skipped", reason: "child-platform-unsupported" }); + expect(run(121, "", "ocx-fanout:child-ocx-version-unknown\n")).toEqual({ state: "skipped", reason: "child-ocx-version-unknown" }); + expect(run(121, "", "unexpected\n")).toEqual({ state: "failed", reason: "child-sync-failed" }); + expect(run(0, doc("synced"), "ocx-fanout:selected:2.93.0-01\n")).toEqual({ state: "failed", reason: "child-output-invalid" }); + }); +}); + +test("Home gate and status failures skip or fail the correct Children", async () => { + const link: LinkRecord = { id: "lnk_0000000000000001", alias: "host", direction: "hub-initiated", hostKeyFingerprint: "SHA256:AAAAAAAAAAAAAAAA", tunnelPort: 25000, apiKeyId: "key", createdAt: "2026-01-01T00:00:00Z" }; + const readStore = () => ({ version: 1 as const, listenerPort: 27000, links: [link, { ...link, id: "lnk_0000000000000002", direction: "client-initiated" as const, hostKeyFingerprint: null }] }); + const runChild = async () => { throw new Error("unexpected child"); }; + for (const [home, catalogCurrent, reason] of [ + [{ state: "failed", exit: 1 }, false, "home-sync-failed"], + [{ state: "skipped", exit: 0 }, false, "home-sync-skipped"], + [{ state: "synced", exit: 0 }, false, "home-catalog-not-current"], + ] as const) { + const result = await runHomeFanout({ home, catalogCurrent, readStore, readLinkStatus: async () => { throw new Error("unexpected status"); }, runChild }); + expect(result.children.map(child => child.reason)).toEqual([reason, "client-initiated-link"]); + expect(fanoutExitCode(result)).toBe(home.exit); + } + for (const reason of ["home-runtime-not-running", "home-link-status-unauthorized", "home-link-status-timeout", "home-link-status-unavailable", "home-link-status-invalid"] as const) { + const result = await runHomeFanout({ home: { state: "synced", exit: 0 }, catalogCurrent: true, readStore, readLinkStatus: async () => { throw new LinkStatusError(reason); }, runChild }); + expect(result.children[0]).toMatchObject({ state: reason === "home-runtime-not-running" ? "skipped" : "failed", reason }); + expect(fanoutExitCode(result)).toBe(reason === "home-runtime-not-running" ? 0 : 6); + } + const result = await runHomeFanout({ home: { state: "synced", exit: 0 }, catalogCurrent: true, readStore: () => { throw new Error("bad store"); }, readLinkStatus: async () => { throw new Error("unexpected status"); }, runChild }); + expect(result.fanout).toEqual({ state: "failed", reason: "link-store-unreadable" }); + expect(fanoutExitCode(result)).toBe(6); +}); + +test("bounds concurrent children and isolates a thrown worker", async () => { + const links: LinkRecord[] = Array.from({ length: 7 }, (_, i) => ({ id: `lnk_${String(i).padStart(16, "0")}`, alias: `host${i}`, direction: "hub-initiated", hostKeyFingerprint: "SHA256:AAAAAAAAAAAAAAAA", tunnelPort: 25000 + i, apiKeyId: `key${i}`, createdAt: "2026-01-01T00:00:00Z", remotePlatform: "posix" })); + let active = 0, peak = 0; + const result = await runHomeFanout({ + home: { state: "synced", exit: 0 }, catalogCurrent: true, concurrency: 9, + readStore: () => ({ version: 1, listenerPort: 27000, links }), + readLinkStatus: async () => ({ role: "home", listener: { state: "listening", port: 27000 }, child: null, links: links.map(link => ({ ...link, state: "connected", since: link.createdAt, reason: null, lastApplyAt: null, runtimeStartedAt: null, appliedCodexSettingsDigest: null })) }), + runChild: async link => { active++; peak = Math.max(active, peak); await Bun.sleep(5); active--; if (link.alias === "host2") throw new Error("private text"); return { state: "synced", reason: null, exit: 0 }; }, + }); + expect(peak).toBe(3); + expect(result.children).toHaveLength(7); + expect(result.children[2]).toMatchObject({ state: "failed", reason: "internal-error" }); + expect(result.children.filter(child => child.state === "synced")).toHaveLength(6); +}); + +test("three stalled workers release a fourth after one deadline wave", async () => { + const links: LinkRecord[] = Array.from({ length: 4 }, (_, i) => ({ id: `lnk_${String(i).padStart(16, "0")}`, alias: `host${i}`, direction: "hub-initiated", hostKeyFingerprint: "SHA256:AAAAAAAAAAAAAAAA", tunnelPort: 25000 + i, apiKeyId: `key${i}`, createdAt: "2026-01-01T00:00:00Z" })); + const starts: number[] = []; + const start = Date.now(); + const result = await runHomeFanout({ + home: { state: "synced", exit: 0 }, catalogCurrent: true, deadlineMs: 30, terminationGraceMs: 5, + readStore: () => ({ version: 1, listenerPort: 27000, links }), + readLinkStatus: async () => ({ role: "home", listener: { state: "listening", port: 27000 }, child: null, links: links.map(link => ({ ...link, state: "connected", since: link.createdAt, reason: null, lastApplyAt: null, runtimeStartedAt: null, appliedCodexSettingsDigest: null })) }), + runChild: async link => { starts.push(Date.now() - start); return link.alias === "host3" ? { state: "synced", reason: null, exit: 0 } : await new Promise(() => {}); }, + }); + expect(starts).toHaveLength(4); + expect(starts[3]).toBeLessThan(300); + expect(result.children.map(child => child.state)).toEqual(["timed-out", "timed-out", "timed-out", "synced"]); +}); diff --git a/tests/cli/sync-link-status.test.ts b/tests/cli/sync-link-status.test.ts new file mode 100644 index 00000000000..bbff10f5af7 --- /dev/null +++ b/tests/cli/sync-link-status.test.ts @@ -0,0 +1,25 @@ +import { expect, test } from "bun:test"; +import { readHomeLinkStatus } from "../../src/cli/sync-link-status"; + +const never = () => new Promise(() => {}); +test.each(["discovery", "headers", "body"] as const)("bounds stalled %s by the same deadline", async stage => { + const start = Date.now(); + await expect(readHomeLinkStatus(40, { + headers: () => new Headers(), + baseUrl: stage === "discovery" ? never : async () => "http://localhost", + fetchImpl: stage === "headers" ? never : async () => ({ ok: true, status: 200, text: never }) as Response, + })).rejects.toMatchObject({ reason: "home-link-status-timeout" }); + expect(Date.now() - start).toBeLessThan(500); +}); +test("classifies absent runtime, unauthorized and invalid bodies", async () => { + await expect(readHomeLinkStatus(100, { baseUrl: async () => null })).rejects.toMatchObject({ reason: "home-runtime-not-running" }); + for (const status of [401, 403]) { + await expect(readHomeLinkStatus(100, { headers: () => new Headers(), baseUrl: async () => "http://localhost", fetchImpl: async () => new Response("", { status }) })).rejects.toMatchObject({ reason: "home-link-status-unauthorized" }); + } + await expect(readHomeLinkStatus(100, { headers: () => new Headers(), baseUrl: async () => "http://localhost", fetchImpl: async () => new Response("{}") })).rejects.toMatchObject({ reason: "home-link-status-invalid" }); +}); +test("accepts the validated wire status", async () => { + const dto = { role: "home", listener: { state: "listening", port: 27000 }, child: null, links: [] }; + const result = await readHomeLinkStatus(100, { headers: () => new Headers(), baseUrl: async () => "http://localhost", fetchImpl: async () => Response.json(dto) }); + expect(result).toEqual(dto); +}); diff --git a/tests/clients/link-pinned-sync-argv.test.ts b/tests/clients/link-pinned-sync-argv.test.ts new file mode 100644 index 00000000000..bceddea2891 --- /dev/null +++ b/tests/clients/link-pinned-sync-argv.test.ts @@ -0,0 +1,185 @@ +import { afterEach, expect, test } from "bun:test"; +import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { remotePinnedSyncArgv } from "../../src/link/ssh-argv"; +import { inflateRawSync } from "node:zlib"; +import { POWERSHELL_ENCODED_MAX, powershellArgv, windowsScriptData, windowsScriptHelperSource } from "../../src/link/remote-windows"; + +const dirs: string[] = []; +afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); +function isolatedArgv(): string[] { + const argv = remotePinnedSyncArgv("lnk_0123456789abcdef", "posix"); + argv[2] = argv[2]!.replace('export PATH="$PATH:$HOME/.bun/bin:$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin"', 'export PATH="$PATH"').replace('"/Applications/OpenCodex.app/Contents/MacOS/ocx"', '"$HOME/missing-app"').replace('"/usr/bin/ocx"', '"$HOME/missing-system"'); + return argv; +} +function toolDir(home: string): string { + const bin = join(home, "bin"); mkdirSync(bin); + for (const command of ["sh", "uname", "mktemp", "sleep", "cat", "awk", "wc", "rm"]) { + const executable = Bun.which(command); + if (!executable) throw new Error(`Required test tool not found on PATH: ${command}`); + symlinkSync(executable, join(bin, command)); + } + return bin; +} +function run(version: string) { + const home = mkdtempSync(join(tmpdir(), "ocx-fanout-test-")); dirs.push(home); + const bin = toolDir(home); + const dir = join(home, ".opencodex-desktop", "bin"); mkdirSync(dir, { recursive: true }); + const executable = join(dir, "ocx"); + writeFileSync(executable, `#!/bin/sh\nprintf '%s\\n' "$*" >> "$HOME/calls"\nif [ "$1" = --version ]; then printf '%s\\n' '${version}'; exit 0; fi\nprintf 'synced\\n'\n`); + chmodSync(executable, 0o755); + const started = Date.now(); + const proc = Bun.spawnSync(isolatedArgv(), { env: { HOME: home, OPENCODEX_HOME: join(home, "ocx-home"), CODEX_HOME: join(home, "codex-home"), TMPDIR: home, PATH: bin }, stdout: "pipe", stderr: "pipe" }); + return { code: proc.exitCode, stdout: proc.stdout.toString(), stderr: proc.stderr.toString(), calls: readFileSync(join(home, "calls"), "utf8"), elapsed: Date.now() - started, remaining: readdirSync(home).filter(name => name.startsWith("ocx-fanout.")) }; +} +test.skipIf(process.platform === "win32").each([["2.93.0", 0], ["2.92.9", 121]] as const)("keeps the version capture private and removes it after %s", (version, expectedExit) => { + const home = mkdtempSync(join(tmpdir(), "ocx-fanout-private-")); dirs.push(home); + const bin = toolDir(home), desktop = join(home, ".opencodex-desktop", "bin"); + mkdirSync(desktop, { recursive: true }); + const realMktemp = Bun.which("mktemp"), realLn = Bun.which("ln"), realLs = Bun.which("ls"); + if (!realMktemp || !realLn || !realLs) throw new Error("mktemp, ln and ls are required for the private capture regression"); + unlinkSync(join(bin, "mktemp")); symlinkSync(realLn, join(bin, "ln")); symlinkSync(realLs, join(bin, "ls")); + writeFileSync(join(home, "victim"), "untouched"); + writeFileSync(join(bin, "mktemp"), '#!/bin/sh\np=$("$REAL_MKTEMP" "$@") || exit 1\nprintf "%s" "$p" > "$HOME/created"\nif [ -d "$p" ]; then ls -ld "$p" > "$HOME/mode"; fi\nln -s "$HOME/victim" "$p.ready"\nprintf "%s\\n" "$p"\n', { mode: 0o755 }); + writeFileSync(join(desktop, "ocx"), `#!/bin/sh\nif [ "$1" = --version ]; then sleep 0.1; printf '%s\\n' '${version}'; else printf 'synced\\n'; fi\n`, { mode: 0o755 }); + const child = Bun.spawnSync(isolatedArgv(), { env: { HOME: home, OPENCODEX_HOME: join(home, "ocx-home"), CODEX_HOME: join(home, "codex-home"), TMPDIR: home, PATH: bin, REAL_MKTEMP: realMktemp }, stdout: "pipe", stderr: "pipe" }); + expect(child.exitCode).toBe(expectedExit); + expect(readFileSync(join(home, "victim"), "utf8")).toBe("untouched"); + expect(readFileSync(join(home, "mode"), "utf8").slice(0, 10)).toBe("drwx------"); + expect(existsSync(readFileSync(join(home, "created"), "utf8"))).toBe(false); +}); +test.skipIf(process.platform === "win32").each(["2.93.0", "2.93.0+build.5"])("pins the selected %s executable", version => { + const result = run(version); + expect(result.code).toBe(0); + expect(result.stderr).toBe(`ocx-fanout:selected:${version}\n`); + expect(result.calls).toBe("--version\nsync --expect-link lnk_0123456789abcdef --json\n"); + expect(result.elapsed).toBeLessThan(2000); + expect(result.remaining).toEqual([]); +}); +test.skipIf(process.platform === "win32").each(["2.92.9+build", "2.93.0-preview.1"])("refuses %s before sync", version => { + const result = run(version); + expect(result.code).toBe(121); + expect(result.stderr.trim()).toBe("ocx-fanout:child-ocx-lacks-expect-link"); + expect(result.calls).toBe("--version\n"); + expect(result.remaining).toEqual([]); +}); +test.skipIf(process.platform === "win32")("rejects unknown versions and preserves the executable's prefix", () => { + const invalid = run("2.93.0-01"); + expect(invalid.code).toBe(121); + expect(invalid.stderr.trim()).toBe("ocx-fanout:child-ocx-version-unknown"); + expect(invalid.calls).toBe("--version\n"); + expect(run("opencodex 2.93.0+build.5").stderr).toBe("ocx-fanout:selected:2.93.0+build.5\n"); +}); +test("Windows pinned script fits the SSH budget and carries the contained argv", () => { + const argv = remotePinnedSyncArgv("lnk_0123456789abcdef", "windows"); + expect(argv[5]!.length).toBeLessThanOrEqual(POWERSHELL_ENCODED_MAX); + const script = Buffer.from(argv[5]!, "base64").toString("utf16le"); + expect(windowsScriptData(script)).toEqual({ args: ["sync", "--expect-link", "lnk_0123456789abcdef", "--json"] }); + expect(windowsScriptHelperSource(script)).toContain("public static string V("); + expect(windowsScriptHelperSource(script)).toContain("n>256?null"); +}); + +test.skipIf(process.platform === "win32")("POSIX wrapper puts the stdout delimiter immediately before the pinned sync output", () => { + expect(run("2.93.0").stdout).toBe("ocx-fanout:stdout-begin\nsynced\n"); +}); + +test("Windows wrapper emits the stdout delimiter before Invoke-Native", () => { + const argv = remotePinnedSyncArgv("lnk_0123456789abcdef", "windows"); + expect(argv[5]!.length).toBeLessThanOrEqual(POWERSHELL_ENCODED_MAX); + const outer = Buffer.from(argv[5]!, "base64").toString("utf16le"); + const packed = /\$ocxPacked='([^']+)'/.exec(outer)?.[1]; + expect(packed).toBeDefined(); + const script = inflateRawSync(Buffer.from(Array.from(packed!, ch => ch.charCodeAt(0) - 256))).toString("utf8"); + expect(script).toContain("[Console]::Out.WriteLine('ocx-fanout:stdout-begin');Invoke-Native $x @($d.args)"); +}); + +test.skipIf(process.platform === "win32")("an overflowing version writer that exits zero falls through", async () => { + const home = mkdtempSync(join(tmpdir(), "ocx-fanout-overflow-")); dirs.push(home); + const desktop = join(home, ".opencodex-desktop", "bin"), bin = toolDir(home); mkdirSync(desktop, { recursive: true }); + writeFileSync(join(desktop, "ocx"), '#!/bin/sh\necho "$*" >> "$HOME/first"\nif [ "$1" = --version ]; then trap "" XFSZ; printf 2.93.0; i=0; while [ "$i" -lt 300 ]; do printf "\\n"; i=$((i+1)); done; exit 0; fi\necho wrong\n', { mode: 0o755 }); + writeFileSync(join(bin, "ocx"), '#!/bin/sh\necho "$*" >> "$HOME/second"\nif [ "$1" = --version ]; then echo 2.93.0; else echo synced; fi\n', { mode: 0o755 }); + const child = Bun.spawn(isolatedArgv(), { env: { HOME: home, OPENCODEX_HOME: join(home, "ocx-home"), CODEX_HOME: join(home, "codex-home"), TMPDIR: home, PATH: bin }, stdout: "pipe", stderr: "pipe" }); + const [code, stdout, stderr] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + expect(readFileSync(join(home, "first"), "utf8")).toBe("--version\n"); + expect(readFileSync(join(home, "second"), "utf8")).toBe("--version\nsync --expect-link lnk_0123456789abcdef --json\n"); + expect({ code, stdout, stderr }).toEqual({ code: 0, stdout: "ocx-fanout:stdout-begin\nsynced\n", stderr: "ocx-fanout:selected:2.93.0\n" }); + expect(windowsScriptHelperSource(Buffer.from(remotePinnedSyncArgv("lnk_0123456789abcdef", "windows")[5]!, "base64").toString("utf16le"))).toContain("n>256?null"); +}); + +test.skipIf(process.platform !== "win32")("Windows bounds version probes and runs the selected pinned command", async () => { + const home = mkdtempSync(join(tmpdir(), "ocx-fanout-windows-")); dirs.push(home); + const dir = join(home, ".opencodex-desktop", "bin"); mkdirSync(dir, { recursive: true }); + const executable = join(dir, "ocx.exe"); + const source = 'using System;using System.IO;using System.Reflection;using System.Threading;public static class Program{public static int Main(string[] a){string p=Assembly.GetExecutingAssembly().Location,m=Environment.GetEnvironmentVariable("OCX_FIXTURE_MODE"),log=Environment.GetEnvironmentVariable("OCX_FIXTURE_LOG");File.AppendAllText(log,p+"|"+string.Join("|",a)+"\\n");bool first=p.IndexOf(".opencodex-desktop",StringComparison.OrdinalIgnoreCase)>=0;if(a.Length==1&&a[0]=="--version"){if(first&&m=="broken")return 17;if(first&&m=="hang"){Thread.Sleep(30000);return 1;}if(first&&m=="overflow"){Console.Write(new string(\u0027x\u0027,256));Console.Out.Flush();Thread.Sleep(100);Console.Write("x");Console.Out.Flush();Thread.Sleep(30000);return 1;}if(first&&m=="fragment"){Console.Write("2.93.");Console.Out.Flush();Thread.Sleep(30);Console.WriteLine("0");return 0;}Console.WriteLine(Environment.GetEnvironmentVariable("OCX_FIXTURE_VERSION"));return 0;}Console.WriteLine(string.Join("|",a));return 0;}}'; + const compile = Bun.spawn(powershellArgv(`Add-Type -TypeDefinition '${source.replaceAll("'", "''")}' -OutputAssembly '${executable.replaceAll("'", "''")}' -OutputType ConsoleApplication`), { stdout: "pipe", stderr: "pipe" }); + const [compiled, compileErr] = await Promise.all([compile.exited, new Response(compile.stderr).text(), new Response(compile.stdout).text()]); + expect({ compiled, compileErr }).toEqual({ compiled: 0, compileErr: "" }); + const managed = join(home, ".local", "share", "goat", "opencodex", "current", "ocx.exe"); + mkdirSync(join(home, ".local", "share", "goat", "opencodex", "current"), { recursive: true }); + copyFileSync(executable, managed); + const run = async (version: string, mode = "") => { + const log = join(home, "calls"); writeFileSync(log, ""); + const started = Date.now(); + const child = Bun.spawn(remotePinnedSyncArgv("lnk_0123456789abcdef", "windows"), { + env: { ...process.env, USERPROFILE: home, LOCALAPPDATA: home, ProgramFiles: home, PATH: join(process.env.SystemRoot ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0"), OPENCODEX_HOME: join(home, "ocx-home"), CODEX_HOME: join(home, "codex-home"), OCX_FIXTURE_VERSION: version, OCX_FIXTURE_MODE: mode, OCX_FIXTURE_LOG: log }, + stdout: "pipe", stderr: "pipe", + }); + const [actual, out, err] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + return { actual, out: out.replaceAll("\r\n", "\n").trim(), err: err.trim(), calls: readFileSync(log, "utf8"), elapsed: Date.now() - started }; + }; + for (const [version, code, stderr, stdout] of [ + ["2.93.0+build.5", 0, "ocx-fanout:selected:2.93.0+build.5", "ocx-fanout:stdout-begin\nsync|--expect-link|lnk_0123456789abcdef|--json"], + ["2.92.9+build", 121, "ocx-fanout:child-ocx-lacks-expect-link", ""], + ] as const) { + const { actual, out, err } = await run(version); + expect({ actual, out, err }).toEqual({ actual: code, out: stdout, err: stderr }); + } + const fragmented = await run("2.93.0", "fragment"); + expect(fragmented).toMatchObject({ actual: 0, err: "ocx-fanout:selected:2.93.0", out: "ocx-fanout:stdout-begin\nsync|--expect-link|lnk_0123456789abcdef|--json" }); + for (const mode of ["broken", "overflow", "hang"]) { + const result = await run("2.93.0", mode); + expect(result).toMatchObject({ actual: 0, err: "ocx-fanout:selected:2.93.0", out: "ocx-fanout:stdout-begin\nsync|--expect-link|lnk_0123456789abcdef|--json" }); + expect(result.calls).toContain(`${executable}|--version`); + expect(result.calls).not.toContain(`${executable}|sync`); + expect(result.calls).toContain(`${managed}|sync|--expect-link|lnk_0123456789abcdef|--json`); + expect(result.elapsed).toBeLessThan(mode === "hang" ? 20000 : 9000); + } +}, 60000); + +test.skipIf(process.platform === "win32")("a version command that exits nonzero falls through without being synced", async () => { + const home = mkdtempSync(join(tmpdir(), "ocx-fanout-fallthrough-")); dirs.push(home); + const desktop = join(home, ".opencodex-desktop", "bin"), bin = toolDir(home); mkdirSync(desktop, { recursive: true }); + writeFileSync(join(desktop, "ocx"), '#!/bin/sh\necho "$*" >> "$HOME/first"\necho 2.93.0\nexit 17\n', { mode: 0o755 }); + writeFileSync(join(bin, "ocx"), '#!/bin/sh\necho "$*" >> "$HOME/second"\nif [ "$1" = --version ]; then echo 2.93.0; else echo synced; fi\n', { mode: 0o755 }); + const child = Bun.spawn(isolatedArgv(), { env: { HOME: home, OPENCODEX_HOME: join(home, "ocx-home"), CODEX_HOME: join(home, "codex-home"), TMPDIR: home, PATH: bin }, stdout: "pipe", stderr: "pipe" }); + const [code, stdout, stderr] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + expect({ code, stdout, stderr }).toEqual({ code: 0, stdout: "ocx-fanout:stdout-begin\nsynced\n", stderr: "ocx-fanout:selected:2.93.0\n" }); + expect(readFileSync(join(home, "first"), "utf8")).toBe("--version\n"); + expect(readFileSync(join(home, "second"), "utf8")).toBe("--version\nsync --expect-link lnk_0123456789abcdef --json\n"); +}); + +test.skipIf(process.platform === "win32")("a missing version parser refuses without preceding shell diagnostics", () => { + const home = mkdtempSync(join(tmpdir(), "ocx-fanout-no-awk-")); dirs.push(home); + const bin = toolDir(home); unlinkSync(join(bin, "awk")); + const desktop = join(home, ".opencodex-desktop", "bin"); mkdirSync(desktop, { recursive: true }); + writeFileSync(join(desktop, "ocx"), '#!/bin/sh\necho 2.93.0\n', { mode: 0o755 }); + const child = Bun.spawnSync(isolatedArgv(), { env: { HOME: home, OPENCODEX_HOME: join(home, "ocx-home"), CODEX_HOME: join(home, "codex-home"), TMPDIR: home, PATH: bin }, stdout: "pipe", stderr: "pipe" }); + expect(child.exitCode).toBe(121); + expect(child.stderr.toString()).toBe("ocx-fanout:child-ocx-version-unknown\n"); +}); + +test.skipIf(process.platform === "win32")("a version writer ignoring signals is killed and the next candidate is selected", async () => { + const home = mkdtempSync(join(tmpdir(), "ocx-fanout-watchdog-")); dirs.push(home); + const desktop = join(home, ".opencodex-desktop", "bin"), bin = toolDir(home); + mkdirSync(desktop, { recursive: true }); + writeFileSync(join(desktop, "ocx"), '#!/bin/sh\nprintf "%s" $$ > "$HOME/writer.pid"\ntrap "" PIPE XFSZ\nwhile :; do printf "01234567890123456789"; done\n', { mode: 0o755 }); + writeFileSync(join(bin, "ocx"), '#!/bin/sh\nif [ "$1" = --version ]; then echo 2.93.0; else echo synced; fi\n', { mode: 0o755 }); + const child = Bun.spawn(isolatedArgv(), { env: { HOME: home, OPENCODEX_HOME: join(home, "ocx-home"), CODEX_HOME: join(home, "codex-home"), TMPDIR: home, PATH: bin }, stdout: "pipe", stderr: "pipe" }); + const [code, stdout, stderr] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + expect({ code, stderr }).toEqual({ code: 0, stderr: "ocx-fanout:selected:2.93.0\n" }); + expect(stdout).toBe("ocx-fanout:stdout-begin\nsynced\n"); + const pid = Number(readFileSync(join(home, "writer.pid"), "utf8")); + expect(() => process.kill(pid, 0)).toThrow(); + expect(readdirSync(home).filter(name => name.startsWith("ocx-fanout."))).toEqual([]); +}, 15000); diff --git a/tests/clients/sync-client-integrations.test.ts b/tests/clients/sync-client-integrations.test.ts index e5534a264d7..62a2f53c82e 100644 --- a/tests/clients/sync-client-integrations.test.ts +++ b/tests/clients/sync-client-integrations.test.ts @@ -904,9 +904,9 @@ describe("owned Pi/Aside catalogs follow filtered model selections", () => { }); test("the direct ocx sync command refreshes owned clients including OpenCode and Kilo and server-owned Aside", async () => { - const src = await Bun.file(new URL("../../src/cli/dispatch.ts", import.meta.url)).text(); - const start = src.indexOf("sync: async deps =>"); - const command = src.slice(start, src.indexOf("v2: async deps =>", start)); + const src = await Bun.file(new URL("../../src/cli/sync-command.ts", import.meta.url)).text(); + const start = src.indexOf("export async function runSyncCommand"); + const command = src.slice(start, src.indexOf("async function handleConnectedSyncCatalogWrite", start)); expect(command).toContain("refreshOwnedCatalogIntegrations"); // Command Code joined this fan-out with its integration: a sync must refresh its // provider block too, or the client keeps a stale catalog until the next apply. diff --git a/tests/codex-integration/codex-app-server-processes.test.ts b/tests/codex-integration/codex-app-server-processes.test.ts index 69cd2be4808..76d3aa9cab7 100644 --- a/tests/codex-integration/codex-app-server-processes.test.ts +++ b/tests/codex-integration/codex-app-server-processes.test.ts @@ -882,13 +882,14 @@ describe("Codex session process matching (#2811)", () => { describe("CLI /api sync wiring for stale app-servers (#476)", () => { const dispatchSource = readFileSync(repoPath("src", "cli", "dispatch.ts"), "utf8"); + const syncSource = readFileSync(repoPath("src", "cli", "sync-command.ts"), "utf8"); const configRoutesSource = readFileSync( repoPath("src", "server", "management", "config-routes.ts"), "utf8", ); test("ocx sync only handles app-servers after a catalog/cache write and forwards --restart-codex", () => { - const syncCase = dispatchSource.slice(dispatchSource.indexOf("sync: async"), dispatchSource.indexOf("v2: async")); + const syncCase = syncSource.slice(syncSource.indexOf("export async function runSyncCommand"), syncSource.indexOf("async function handleConnectedSyncCatalogWrite")); expect(syncCase).toContain("readRestartScope(syncArgs"); expect(syncCase).toContain("synced.catalogWritten || synced.cacheSynced"); expect(syncCase).toContain("handleRestartScopeAfterWrite"); @@ -908,8 +909,8 @@ describe("CLI /api sync wiring for stale app-servers (#476)", () => { // separate Windows-only opt-in. That decision was superseded by an explicit // maintainer instruction, and the narrow scope did not disappear: it moved to // --restart-app-server-only, which is what this now pins. - for (const [name, endMarker] of [["sync: async", "v2: async"], ['"sync-cache": async', "gui: async"]] as const) { - const handler = dispatchSource.slice(dispatchSource.indexOf(name), dispatchSource.indexOf(endMarker)); + for (const [source, name, endMarker] of [[syncSource, "export async function runSyncCommand", "async function handleConnectedSyncCatalogWrite"], [dispatchSource, '"sync-cache": async', "gui: async"]] as const) { + const handler = source.slice(source.indexOf(name), source.indexOf(endMarker)); // One reader for every command, so the same flag cannot mean different things in // sync, sync-cache and catalog pull. expect(handler).toContain("readRestartScope("); diff --git a/tests/codex-integration/codex-catalog-writer.test.ts b/tests/codex-integration/codex-catalog-writer.test.ts index 53c726a7f8e..9ee93e87d36 100644 --- a/tests/codex-integration/codex-catalog-writer.test.ts +++ b/tests/codex-integration/codex-catalog-writer.test.ts @@ -409,6 +409,8 @@ test("retained catalog sync initializes an empty home before publishing its back expect(readdirSync(openCodexHome)).toEqual([]); const result = await syncCatalogModels({ port: 10100, defaultProvider: "openai", providers: {}, subagentModels: [] }, { allowWhenDesiredDisabled: true }); expect(result.refreshOutcome).toBe("committed"); + const unchanged = await syncCatalogModels({ port: 10100, defaultProvider: "openai", providers: {}, subagentModels: [] }, { allowWhenDesiredDisabled: true }); + expect(unchanged).toMatchObject({ refreshOutcome: "committed", catalogWritten: false }); const backup = catalogBackupPathFor(path); expect(readFileSync(backup, "utf8")).toBe(pristine); expect(manifestPaths(openCodexHome)).toContain(backup.split(/[\\/]/).pop()!); diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 7d478bd98e4..1611c02a0c1 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1,4 +1,4 @@ -{ "codex-installation-acl.test.ts": "codex-integration", "codex-installation-id.test.ts": "codex-integration", "codex-installation-wire.test.ts": "codex-integration", "codex-installation-failover.test.ts": "responses", "lmstudio-system-policy.test.ts": "config", "openai-chat-single-system.test.ts": "adapters/openai", "update-reclaim-authorizer.test.ts": "update", "update-capability-policy.test.ts": "update", "update-service-home.test.ts": "update", "update-service-home-policy.test.ts": "update", "update-home-recovery.test.ts": "update", "update-recovery-authority.test.ts": "update", "update-recovery-boundaries.test.ts": "update", "update-home-launcher.test.ts": "update", "update-home-worker.test.ts": "update", "update-mutation-boundaries.test.ts": "update", "update-mutation-guard.test.ts": "update", "update-guarded-ops.test.ts": "update", "update-effect-authority.test.ts": "update", "update-windows-wrapper-authority.test.ts": "update", "update-mutation-scanner.test.ts": "update", "refreshed-upstream-deadlines.test.ts": "responses", "local-upstream-deadlines.test.ts": "responses", "service-desktop-recovery.test.ts": "service", "provider-input-modalities.test.ts": "providers", "turn-membership.test.ts": "responses", "turn-membership-ingress.test.ts": "responses", "workbuddy-quota.test.ts": "providers", "workbuddy-login.test.ts": "oauth", "workbuddy-adapter.test.ts": "adapters", "workbuddy-provider.test.ts": "providers", "link-tunnel-history.test.ts": "clients", "link-readiness.test.ts": "clients", "link-diagnostics.test.ts": "clients", "combo-description.test.ts": "routing", "combo-description-catalog.test.ts": "codex-integration", "catalog-auto-review-override.test.ts": "codex-integration", "management-auto-review-settings.test.ts": "server", "management-auto-review-auth.test.ts": "server", "prefer-model-alias-ids.test.ts": "server", "responses-mimo-envelope.test.ts": "responses", "responses-call-id-linkage.test.ts": "responses", "responses-phase-inference.test.ts": "responses", +{ "sync-fanout.test.ts": "cli", "sync-command-fanout.test.ts": "cli", "link-pinned-sync-argv.test.ts": "clients", "sync-link-status.test.ts": "cli", "sync-fanout-process.test.ts": "cli", "codex-installation-acl.test.ts": "codex-integration", "codex-installation-id.test.ts": "codex-integration", "codex-installation-wire.test.ts": "codex-integration", "codex-installation-failover.test.ts": "responses", "lmstudio-system-policy.test.ts": "config", "openai-chat-single-system.test.ts": "adapters/openai", "update-reclaim-authorizer.test.ts": "update", "update-capability-policy.test.ts": "update", "update-service-home.test.ts": "update", "update-service-home-policy.test.ts": "update", "update-home-recovery.test.ts": "update", "update-recovery-authority.test.ts": "update", "update-recovery-boundaries.test.ts": "update", "update-home-launcher.test.ts": "update", "update-home-worker.test.ts": "update", "update-mutation-boundaries.test.ts": "update", "update-mutation-guard.test.ts": "update", "update-guarded-ops.test.ts": "update", "update-effect-authority.test.ts": "update", "update-windows-wrapper-authority.test.ts": "update", "update-mutation-scanner.test.ts": "update", "refreshed-upstream-deadlines.test.ts": "responses", "local-upstream-deadlines.test.ts": "responses", "service-desktop-recovery.test.ts": "service", "provider-input-modalities.test.ts": "providers", "turn-membership.test.ts": "responses", "turn-membership-ingress.test.ts": "responses", "workbuddy-quota.test.ts": "providers", "workbuddy-login.test.ts": "oauth", "workbuddy-adapter.test.ts": "adapters", "workbuddy-provider.test.ts": "providers", "link-tunnel-history.test.ts": "clients", "link-readiness.test.ts": "clients", "link-diagnostics.test.ts": "clients", "combo-description.test.ts": "routing", "combo-description-catalog.test.ts": "codex-integration", "catalog-auto-review-override.test.ts": "codex-integration", "management-auto-review-settings.test.ts": "server", "management-auto-review-auth.test.ts": "server", "prefer-model-alias-ids.test.ts": "server", "responses-mimo-envelope.test.ts": "responses", "responses-call-id-linkage.test.ts": "responses", "responses-phase-inference.test.ts": "responses", "codex-installation-live-content.test.ts": "codex-integration", "codex-installation-invalid-account.test.ts": "codex-integration", "codex-installation-sidecars.test.ts": "codex-integration", diff --git a/tests/update/update-stop-classification.test.ts b/tests/update/update-stop-classification.test.ts index 779ba4c4d0d..a2f74556b1a 100644 --- a/tests/update/update-stop-classification.test.ts +++ b/tests/update/update-stop-classification.test.ts @@ -35,7 +35,7 @@ describe("stop failure classification (#3008)", () => { const cliCodes = [...read("src/cli/index.ts").matchAll(/process\.exit(?:Code)?\s*(?:=|\()\s*(\d+)/g)] .map(match => Number(match[1])); - const dispatchCodes = [...read("src/cli/dispatch.ts").matchAll(/return (\d+);/g)] + const dispatchCodes = ["src/cli/dispatch.ts", "src/cli/sync-command.ts"].flatMap(path => [...read(path).matchAll(/return (\d+);/g)]) .map(match => Number(match[1])); expect(cliCodes).not.toContain(STOP_HISTORY_INCOMPLETE_EXIT_CODE); expect(dispatchCodes).not.toContain(STOP_HISTORY_INCOMPLETE_EXIT_CODE); diff --git a/tests/update/update-teardown-handover.test.ts b/tests/update/update-teardown-handover.test.ts index c2ac7b59d58..688fc588724 100644 --- a/tests/update/update-teardown-handover.test.ts +++ b/tests/update/update-teardown-handover.test.ts @@ -62,7 +62,7 @@ describe("handover exit code and update decision", () => { expect(STOP_TEARDOWN_HANDED_OVER_EXIT_CODE).toBe(81); expect([STOP_HISTORY_INCOMPLETE_EXIT_CODE, STOP_HISTORY_DEFERRED_EXIT_CODE]).not.toContain(81); const cli = readFileSync(repoPath("src", "cli", "index.ts"), "utf8"); - const dispatch = readFileSync(repoPath("src", "cli", "dispatch.ts"), "utf8"); + const dispatch = ["dispatch.ts", "sync-command.ts"].map(file => readFileSync(repoPath("src", "cli", file), "utf8")).join("\n"); const literal = [...cli.matchAll(/process\.exit(?:Code)?\s*(?:=|\()\s*(\d+)/g), ...dispatch.matchAll(/return (\d+);/g)] .map(match => Number(match[1])); expect(literal).not.toContain(81); From 09b558580749e4a8ea2afa8617b8fb4c069049b4 Mon Sep 17 00:00:00 2001 From: JUN Date: Mon, 2 Nov 2026 23:32:15 +0900 Subject: [PATCH 09/43] fix: refuse links at SQLite store paths on Windows and rebalance CI shards for the new affinity tests (#8102) * fix(codex): refuse links at SQLite store and sidecar names before creating them Windows creates a new file through a symbolic link at its name, so the affinity store's create-then-lstat order created the link's target before refusing the path (windows 11/11, run 41437409412). The spend-ledger owner had the same order. SQLite's Windows VFS also opens -journal/-wal/-shm by name and follows a link there. src/lib/private-sqlite-path.ts checks the database and its sidecars before anything is created (and, on Windows, the reparse-point attribute), and the affinity store re-checks sidecars before every write transaction. * fix(codex): re-check the affinity database identity and link count before every write A hard link added to the open database is refused before the next write transaction, as a planted sidecar link already was. Docs now separate open-time from per-transaction checks and state that Windows relies on the hardened ACL rather than an ownership comparison. * test(layout): register private-sqlite-path in the file-identity shard Keeps scripts/test-layout/layout.json under the file-size ratchet, and narrows the clean-flag wording to the poisoned and failed-final-flush cases. * ci(test): rebalance shards for the new affinity tests and seed restart tests once Linux test 1/4 hit the 15-minute job timeout in run 41437409412: seven new affinity and bridge files had no recorded duration and weighed the median. Both duration tables are refreshed from that run with scripts/ci/test-durations.ts (the only run that measured them; the source lines record the cancelled shard and the retained Windows rows). The two affinity restart files spawned a full seeding worker before nearly every case. They now seed one template home per file and copy it, rebinding the ownership root; clean-restart, crash, unowned-home, two-home and one unknown-issuer handler case keep real seeding. Locally 19.2 s -> 13.2 s. * fix(lib): gate the Windows reparse probe on the real platform Tests replace process.platform with win32 to drive Windows branches on POSIX; the native GetFileAttributesW query must follow the operating system the process runs on, or those tests see every owner database refused (tests/server/server-stop-config-hardening.test.ts). * fix: keep Windows ARM64 startable and compare store identity as BigInt Bun on Windows ARM64 cannot execute bun:ffi, so the reparse attribute query failed closed there and the spend-ledger owner could never be acquired. On ARM64 the check relies on lstat, which reports symbolic links, junctions and app execution aliases as links; the docs state the narrower coverage. The affinity store compares database identity with BigInt stats through sameFileIdentity: NTFS file IDs exceed Number.MAX_SAFE_INTEGER. --- scripts/ci/test-durations.tsv | 5553 +++++++++-------- scripts/ci/test-durations.windows.tsv | 5228 ++++++++-------- scripts/test-layout/layout-file-identity.json | 3 +- src/codex/routing/thread-affinity-store.ts | 45 +- src/lib/private-sqlite-path.ts | 124 + src/lib/spend-ledger-owner.ts | 9 +- structure/providers/codex-pool-affinity.md | 2 +- structure/transports/responses-spend.md | 6 +- .../codex-affinity-restart-matrix.test.ts | 113 +- .../codex-affinity-restart.test.ts | 26 +- tests/fixtures/test-layout-expected.json | 2 +- tests/helpers/codex-affinity-matrix-worker.ts | 17 +- tests/helpers/codex-affinity-seed.ts | 52 + .../helpers/spend-ledger-owner-link-worker.ts | 10 + .../helpers/windows-link-create-emulation.ts | 31 + tests/helpers/windows-link-create-preload.ts | 4 + tests/lib/private-sqlite-path.test.ts | 117 + tests/lib/spend-ledger-owner.test.ts | 31 + 18 files changed, 6022 insertions(+), 5351 deletions(-) create mode 100644 src/lib/private-sqlite-path.ts create mode 100644 tests/helpers/codex-affinity-seed.ts create mode 100644 tests/helpers/spend-ledger-owner-link-worker.ts create mode 100644 tests/helpers/windows-link-create-emulation.ts create mode 100644 tests/helpers/windows-link-create-preload.ts create mode 100644 tests/lib/private-sqlite-path.test.ts diff --git a/scripts/ci/test-durations.tsv b/scripts/ci/test-durations.tsv index 72826b74614..ba3e49900b6 100644 --- a/scripts/ci/test-durations.tsv +++ b/scripts/ci/test-durations.tsv @@ -1,2780 +1,2861 @@ # Per-file Bun test durations in milliseconds, read from hosted CI job logs. # Consumed by scripts/ci/run-bun-test-batches.sh to balance shards; a file without a row weighs the median. # Regenerate with scripts/ci/test-durations.ts (usage in its header); do not edit by hand. -# Source: runs 40727740334, 40743681086, 40756291846 (attempt 1, workflow_dispatch, overall failure); successful Linux test 1/4-4/4 and macos 1/3-3/3 jobs only; arithmetic mean of all per-file observations -239 tests/adapters/abort-race.test.ts -396 tests/adapters/adapter-buffered-tool-conformance.test.ts -278 tests/adapters/adapter-error-inline.test.ts -1795 tests/adapters/adapter-inner-send-budget-wiring.test.ts -2993 tests/adapters/adapter-inner-send-budget.test.ts -188 tests/adapters/adapter-input-media-guard.test.ts -408 tests/adapters/adapter-registry-authority.test.ts -1090 tests/adapters/adapter-tool-conformance.test.ts -151 tests/adapters/adapter-usage.test.ts -777 tests/adapters/anthropic/anthropic-429-policy.test.ts -51 tests/adapters/anthropic/anthropic-account-metadata.test.ts -198 tests/adapters/anthropic/anthropic-account-pause-outbound.test.ts -539 tests/adapters/anthropic/anthropic-account-pause.test.ts -577 tests/adapters/anthropic/anthropic-account-pool.test.ts -611 tests/adapters/anthropic/anthropic-account-threshold.test.ts -166 tests/adapters/anthropic/anthropic-affinity-restart.test.ts -242 tests/adapters/anthropic/anthropic-affinity-store.test.ts -53 tests/adapters/anthropic/anthropic-agentrouter-language-framing.test.ts -102 tests/adapters/anthropic/anthropic-baseurl-override.test.ts -50 tests/adapters/anthropic/anthropic-beta-allowlist.test.ts -60 tests/adapters/anthropic/anthropic-beta-body-pairs.test.ts -405 tests/adapters/anthropic/anthropic-billing-ownership.test.ts -297 tests/adapters/anthropic/anthropic-billing-refusal.test.ts -57 tests/adapters/anthropic/anthropic-client-identity.test.ts -384 tests/adapters/anthropic/anthropic-combo-account-cooldown.test.ts -2566 tests/adapters/anthropic/anthropic-compatible-stream.test.ts -189 tests/adapters/anthropic/anthropic-cooldown-recovery.test.ts -48 tests/adapters/anthropic/anthropic-empty-content.test.ts -100 tests/adapters/anthropic/anthropic-eof-tolerance.test.ts +# Source: run 41437409412 (attempt 1, workflow_dispatch on dev 5cfd0ac11): successful macos 1/4-4/4 and Linux test 2/4-4/4, plus the completed files of Linux test 1/4, which hit the job timeout; arithmetic mean of all per-file observations +835 tests/adapters/abort-race.test.ts +427 tests/adapters/adapter-buffered-tool-conformance.test.ts +259 tests/adapters/adapter-error-inline.test.ts +1650 tests/adapters/adapter-inner-send-budget-wiring.test.ts +2954 tests/adapters/adapter-inner-send-budget.test.ts +142 tests/adapters/adapter-input-media-guard.test.ts +620 tests/adapters/adapter-registry-authority.test.ts +1794 tests/adapters/adapter-tool-conformance.test.ts +184 tests/adapters/adapter-usage.test.ts +870 tests/adapters/anthropic/anthropic-429-policy.test.ts +44 tests/adapters/anthropic/anthropic-account-metadata.test.ts +237 tests/adapters/anthropic/anthropic-account-pause-outbound.test.ts +504 tests/adapters/anthropic/anthropic-account-pause.test.ts +852 tests/adapters/anthropic/anthropic-account-pool.test.ts +708 tests/adapters/anthropic/anthropic-account-threshold.test.ts +175 tests/adapters/anthropic/anthropic-active-limit-routing.test.ts +214 tests/adapters/anthropic/anthropic-affinity-restart.test.ts +241 tests/adapters/anthropic/anthropic-affinity-store.test.ts +44 tests/adapters/anthropic/anthropic-agentrouter-language-framing.test.ts +108 tests/adapters/anthropic/anthropic-baseurl-override.test.ts +51 tests/adapters/anthropic/anthropic-beta-allowlist.test.ts +65 tests/adapters/anthropic/anthropic-beta-body-pairs.test.ts +704 tests/adapters/anthropic/anthropic-billing-ownership.test.ts +298 tests/adapters/anthropic/anthropic-billing-refusal.test.ts +69 tests/adapters/anthropic/anthropic-client-identity.test.ts +661 tests/adapters/anthropic/anthropic-combo-account-cooldown.test.ts +2636 tests/adapters/anthropic/anthropic-compatible-stream.test.ts +222 tests/adapters/anthropic/anthropic-cooldown-recovery.test.ts +56 tests/adapters/anthropic/anthropic-empty-content.test.ts +176 tests/adapters/anthropic/anthropic-eof-tolerance.test.ts 376 tests/adapters/anthropic/anthropic-error-body.test.ts -57 tests/adapters/anthropic/anthropic-error-stop-reason.test.ts -593 tests/adapters/anthropic/anthropic-fast-opt-in.test.ts -58 tests/adapters/anthropic/anthropic-fast-speed.test.ts -54 tests/adapters/anthropic/anthropic-haiku-5-5-contract.test.ts -46 tests/adapters/anthropic/anthropic-hardening.test.ts -131 tests/adapters/anthropic/anthropic-image-guard.test.ts -3922 tests/adapters/anthropic/anthropic-image-normalize.test.ts -1051 tests/adapters/anthropic/anthropic-image-retry-e2e.test.ts -224 tests/adapters/anthropic/anthropic-image-retry.test.ts -702 tests/adapters/anthropic/anthropic-instance-isolation.test.ts -687 tests/adapters/anthropic/anthropic-instance-pool-parity.test.ts -861 tests/adapters/anthropic/anthropic-instance-quota.test.ts -2281 tests/adapters/anthropic/anthropic-instance-recovery.test.ts -51 tests/adapters/anthropic/anthropic-message-stop-termination.test.ts -55 tests/adapters/anthropic/anthropic-messages-passthrough-oauth.test.ts -45 tests/adapters/anthropic/anthropic-messages-passthrough.test.ts -930 tests/adapters/anthropic/anthropic-model-routes.test.ts -787 tests/adapters/anthropic/anthropic-model-weekly-admission.test.ts -62 tests/adapters/anthropic/anthropic-opaque-strip.test.ts -82 tests/adapters/anthropic/anthropic-output-maxima.test.ts -55 tests/adapters/anthropic/anthropic-parallel-tool-disable.test.ts -121 tests/adapters/anthropic/anthropic-pool-toggle-copy.test.ts -324 tests/adapters/anthropic/anthropic-pool-usage-limit.test.ts -218 tests/adapters/anthropic/anthropic-progress-updates.test.ts -334 tests/adapters/anthropic/anthropic-quota-cooldown-recovery.test.ts -1008 tests/adapters/anthropic/anthropic-quota-dispatch.test.ts -283 tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts -146 tests/adapters/anthropic/anthropic-reasoning.test.ts -48 tests/adapters/anthropic/anthropic-replay.test.ts -88 tests/adapters/anthropic/anthropic-reset-grants.test.ts -331 tests/adapters/anthropic/anthropic-revoked-token-boundaries.test.ts -322 tests/adapters/anthropic/anthropic-revoked-token-continuation.test.ts -602 tests/adapters/anthropic/anthropic-revoked-token-sidecars.test.ts -1235 tests/adapters/anthropic/anthropic-revoked-token.test.ts -202 tests/adapters/anthropic/anthropic-sidecar-account-failover.test.ts -56 tests/adapters/anthropic/anthropic-sonnet-5-5-contract.test.ts -49 tests/adapters/anthropic/anthropic-stream-hardening.test.ts -767 tests/adapters/anthropic/anthropic-subscription-chain.test.ts -46 tests/adapters/anthropic/anthropic-tail-guard.test.ts -163 tests/adapters/anthropic/anthropic-thinking-signature.test.ts -56 tests/adapters/anthropic/anthropic-thinking-usage.test.ts -69 tests/adapters/anthropic/anthropic-tool-call-id.test.ts -115 tests/adapters/anthropic/anthropic-tool-declaration-constraints.test.ts -46 tests/adapters/anthropic/anthropic-tool-schema.test.ts -407 tests/adapters/anthropic/anthropic2-fast-parity.test.ts -43 tests/adapters/bridge-legacy-shell-normalization.test.ts -3569 tests/adapters/bridge-lifecycle.test.ts -239 tests/adapters/bridge-nonstreaming-terminal.test.ts -106 tests/adapters/bridge-raw-reasoning-hidden.test.ts -97 tests/adapters/bridge-reasoning-replay-batch.test.ts -144 tests/adapters/bridge-stall.test.ts -58 tests/adapters/bridge-terminal-refusal.test.ts +53 tests/adapters/anthropic/anthropic-error-stop-reason.test.ts +685 tests/adapters/anthropic/anthropic-fast-opt-in.test.ts +98 tests/adapters/anthropic/anthropic-fast-speed.test.ts +47 tests/adapters/anthropic/anthropic-haiku-5-5-contract.test.ts +53 tests/adapters/anthropic/anthropic-hardening.test.ts +130 tests/adapters/anthropic/anthropic-image-guard.test.ts +3244 tests/adapters/anthropic/anthropic-image-normalize.test.ts +1806 tests/adapters/anthropic/anthropic-image-retry-e2e.test.ts +184 tests/adapters/anthropic/anthropic-image-retry.test.ts +1024 tests/adapters/anthropic/anthropic-instance-isolation.test.ts +938 tests/adapters/anthropic/anthropic-instance-pool-parity.test.ts +1188 tests/adapters/anthropic/anthropic-instance-quota.test.ts +3015 tests/adapters/anthropic/anthropic-instance-recovery.test.ts +58 tests/adapters/anthropic/anthropic-message-stop-termination.test.ts +74 tests/adapters/anthropic/anthropic-messages-passthrough-oauth.test.ts +41 tests/adapters/anthropic/anthropic-messages-passthrough.test.ts +3179 tests/adapters/anthropic/anthropic-model-routes.test.ts +856 tests/adapters/anthropic/anthropic-model-weekly-admission.test.ts +47 tests/adapters/anthropic/anthropic-opaque-strip.test.ts +84 tests/adapters/anthropic/anthropic-output-maxima.test.ts +73 tests/adapters/anthropic/anthropic-parallel-tool-disable.test.ts +204 tests/adapters/anthropic/anthropic-pool-toggle-copy.test.ts +384 tests/adapters/anthropic/anthropic-pool-usage-limit.test.ts +397 tests/adapters/anthropic/anthropic-progress-updates.test.ts +391 tests/adapters/anthropic/anthropic-quota-cooldown-recovery.test.ts +1538 tests/adapters/anthropic/anthropic-quota-dispatch.test.ts +519 tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts +244 tests/adapters/anthropic/anthropic-reasoning.test.ts +40 tests/adapters/anthropic/anthropic-replay.test.ts +102 tests/adapters/anthropic/anthropic-reset-grants.test.ts +508 tests/adapters/anthropic/anthropic-revoked-token-boundaries.test.ts +255 tests/adapters/anthropic/anthropic-revoked-token-continuation.test.ts +766 tests/adapters/anthropic/anthropic-revoked-token-sidecars.test.ts +1498 tests/adapters/anthropic/anthropic-revoked-token.test.ts +199 tests/adapters/anthropic/anthropic-sidecar-account-failover.test.ts +64 tests/adapters/anthropic/anthropic-sonnet-5-5-contract.test.ts +91 tests/adapters/anthropic/anthropic-stream-hardening.test.ts +790 tests/adapters/anthropic/anthropic-subscription-chain.test.ts +50 tests/adapters/anthropic/anthropic-tail-guard.test.ts +142 tests/adapters/anthropic/anthropic-thinking-signature.test.ts +52 tests/adapters/anthropic/anthropic-thinking-usage.test.ts +38 tests/adapters/anthropic/anthropic-tool-call-id.test.ts +147 tests/adapters/anthropic/anthropic-tool-declaration-constraints.test.ts +115 tests/adapters/anthropic/anthropic-tool-schema.test.ts +616 tests/adapters/anthropic/anthropic2-fast-parity.test.ts +105 tests/adapters/bridge-legacy-shell-normalization.test.ts +3578 tests/adapters/bridge-lifecycle.test.ts +181 tests/adapters/bridge-nonstreaming-terminal.test.ts +120 tests/adapters/bridge-raw-reasoning-hidden.test.ts +125 tests/adapters/bridge-reasoning-replay-batch.test.ts +189 tests/adapters/bridge-stall.test.ts +86 tests/adapters/bridge-terminal-refusal.test.ts 49 tests/adapters/bridge-terminal-singleness.test.ts -137 tests/adapters/bridge.test.ts -89 tests/adapters/buffered-response-shape-guards.test.ts -70 tests/adapters/coding-agent-history-projection.test.ts -75 tests/adapters/coding-agent-tool-result-images.test.ts -62 tests/adapters/coding-agent-windows-dispatch.test.ts -88 tests/adapters/dsh-account-adapter.test.ts -404 tests/adapters/empty-tool-output-annotation.test.ts -119 tests/adapters/exec-tool-result-normalize.test.ts -250 tests/adapters/fix-tool-number-preservation.test.ts -139 tests/adapters/google/antigravity-account-roster.test.ts -82 tests/adapters/google/antigravity-baseurl-override.test.ts -57 tests/adapters/google/antigravity-discovered-families.test.ts -76 tests/adapters/google/antigravity-refusal.test.ts -181 tests/adapters/google/antigravity-routing-carry.test.ts -103 tests/adapters/google/antigravity-static-catalog.test.ts -857 tests/adapters/google/gcp-adc.test.ts -592 tests/adapters/google/gcp-credential-boundary.test.ts -379 tests/adapters/google/gcp-sa-adapter.test.ts -708 tests/adapters/google/gcp-sa-marker.test.ts -65 tests/adapters/google/gemini-37-flash-migration.test.ts -81 tests/adapters/google/gemini-4-argon-antigravity.test.ts -61 tests/adapters/google/gemini-progress-history.test.ts -218 tests/adapters/google/gemini-web-search.test.ts -90 tests/adapters/google/google-adapter.test.ts -70 tests/adapters/google/google-ai-studio-foreign-call-signature.test.ts -4094 tests/adapters/google/google-antigravity-oauth.test.ts -2346 tests/adapters/google/google-antigravity-replay.test.ts -82 tests/adapters/google/google-antigravity-wire.test.ts -73 tests/adapters/google/google-buffered-stop-reason.test.ts -65 tests/adapters/google/google-claude-prefill-guard.test.ts -57 tests/adapters/google/google-empty-content.test.ts -60 tests/adapters/google/google-errors.test.ts -64 tests/adapters/google/google-hardening.test.ts -128 tests/adapters/google/google-models-listing.test.ts -49 tests/adapters/google/google-output-clamp.test.ts -41 tests/adapters/google/google-provider-metadata-roundtrip.test.ts -94 tests/adapters/google/google-signature-history-roundtrip.test.ts -78 tests/adapters/google/google-stream-fragmentation.test.ts -50 tests/adapters/google/google-strict-tool-validated-mode.test.ts -51 tests/adapters/google/google-structured-output.test.ts -63 tests/adapters/google/google-tool-result-adjacency.test.ts -67 tests/adapters/google/google-tool-schema-contract.test.ts -65 tests/adapters/google/google-tool-schema.test.ts -4749 tests/adapters/google/google-vertex-http.test.ts -99 tests/adapters/google/google-vertex-key-project.test.ts -57 tests/adapters/google/google-vertex-stream.test.ts -73 tests/adapters/google/google-vertex-thought-signature.test.ts -49 tests/adapters/google/google-wire-compiler.test.ts -84 tests/adapters/google/google-wire-shape.test.ts -116 tests/adapters/google/vertex-catalog.test.ts -228 tests/adapters/identity-neutralize.test.ts -374 tests/adapters/identity-subagent.test.ts -571 tests/adapters/key-failover.test.ts -76 tests/adapters/openai/inline-think-boundaries.test.ts -2127 tests/adapters/openai/openai-api-virtual-models.test.ts -44 tests/adapters/openai/openai-chat-audio.test.ts -203 tests/adapters/openai/openai-chat-bounded-tool-names.test.ts -41 tests/adapters/openai/openai-chat-dangling-toolcalls.test.ts -51 tests/adapters/openai/openai-chat-developer-position.test.ts -82 tests/adapters/openai/openai-chat-eof.test.ts -84 tests/adapters/openai/openai-chat-glm-summary.test.ts -265 tests/adapters/openai/openai-chat-hardening.test.ts -5065 tests/adapters/openai/openai-chat-image-normalization.test.ts -64 tests/adapters/openai/openai-chat-inline-think-tags.test.ts -63 tests/adapters/openai/openai-chat-invalid-tool-call-diagnostics.test.ts -155 tests/adapters/openai/openai-chat-mistral-content.test.ts -142 tests/adapters/openai/openai-chat-model-suffix.test.ts -559 tests/adapters/openai/openai-chat-native-policy.test.ts -128 tests/adapters/openai/openai-chat-nonce-tool-call-content.test.ts -88 tests/adapters/openai/openai-chat-parallel-stream.test.ts -126 tests/adapters/openai/openai-chat-path-override.test.ts -56 tests/adapters/openai/openai-chat-qwen38-leading-system.test.ts -161 tests/adapters/openai/openai-chat-reasoning-wire-policy.test.ts -71 tests/adapters/openai/openai-chat-required-tool.test.ts -163 tests/adapters/openai/openai-chat-sanitization-review-regressions.test.ts -82 tests/adapters/openai/openai-chat-serialized-tool-call-content.test.ts -263 tests/adapters/openai/openai-chat-serialized-tool-call-hold-bound.test.ts -124 tests/adapters/openai/openai-chat-serialized-tool-call-scaling.test.ts -58 tests/adapters/openai/openai-chat-serialized-tool-call-think.test.ts -415 tests/adapters/openai/openai-chat-standalone-bare-block.test.ts -127 tests/adapters/openai/openai-chat-system-order.test.ts -59 tests/adapters/openai/openai-chat-tool-call-id-remint.test.ts -77 tests/adapters/openai/openai-chat-tool-result-images.test.ts -46 tests/adapters/openai/openai-chat-url.test.ts -53 tests/adapters/openai/openai-chat-video-part.test.ts -114 tests/adapters/openai/openai-empty-assistant-history.test.ts -275 tests/adapters/openai/openai-native-hosted-search-history.test.ts -1078 tests/adapters/openai/openai-provider-option-e2e.test.ts -412 tests/adapters/openai/openai-provider-option-migration.test.ts -65 tests/adapters/openai/openai-provider-option-startup.test.ts -124 tests/adapters/openai/openai-provider-option-tooling.test.ts -44 tests/adapters/openai/openai-provider-option.test.ts -40 tests/adapters/openai/opengateway-input.test.ts -106 tests/adapters/physical-send.test.ts -87 tests/adapters/qoder-spawn-readmission.test.ts -97 tests/adapters/reasoning-replay-identity.test.ts -170 tests/adapters/reasoning-replay-robustness.test.ts -197 tests/adapters/routed-agent-messages.test.ts -106 tests/adapters/run-turn-queue.test.ts -339 tests/adapters/terminal-continuation-owner-rotation.test.ts -61 tests/adapters/tool-argument-integers.test.ts -52 tests/adapters/tool-catalog-nudge.test.ts -51 tests/adapters/tool-choice-performance.test.ts -89 tests/adapters/tool-envelope-echo-whole-line.test.ts -37 tests/adapters/tool-identity-hash.test.ts -203 tests/adapters/translator-budget-lifetime.test.ts -3445 tests/adapters/translator-budget.test.ts -37 tests/adapters/upstream-http-error.test.ts -98 tests/adapters/workbuddy-adapter.test.ts -90 tests/advisor/advisor-adaptive.test.ts -93 tests/advisor/advisor-authority-transport.test.ts -52 tests/advisor/advisor-budget.test.ts -40 tests/advisor/advisor-consult.test.ts -57 tests/advisor/advisor-context.test.ts -50 tests/advisor/advisor-continuation-limit.test.ts -459 tests/advisor/advisor-core-boundary.test.ts -65 tests/advisor/advisor-evidence.test.ts -79 tests/advisor/advisor-guard.test.ts -252 tests/advisor/advisor-internal-authority.test.ts -72 tests/advisor/advisor-plan.test.ts -721 tests/advisor/advisor-responses-wiring.test.ts -385 tests/advisor/advisor-retention.test.ts -391 tests/advisor/advisor-scope-transport.test.ts -135 tests/advisor/advisor-settings.test.ts -132 tests/advisor/advisor-state.test.ts -3402 tests/ci-workflows/assert-mergeable-review.test.ts -48 tests/ci-workflows/brand-favicons.test.ts -70 tests/ci-workflows/build-desktop-icon-set.test.ts -81 tests/ci-workflows/build-release-changelog.test.ts -182 tests/ci-workflows/bump-dev-version.test.ts -171 tests/ci-workflows/bun-runtime.test.ts -69 tests/ci-workflows/ci-bun-crash-classifier.test.ts -10478 tests/ci-workflows/ci-bun-install-frozen.test.ts -52 tests/ci-workflows/ci-concurrency-groups.test.ts -5721 tests/ci-workflows/ci-crash-disposition.test.ts -1691 tests/ci-workflows/ci-gui-typecheck-gate.test.ts -143 tests/ci-workflows/ci-pr-hygiene-approvals.test.ts -1169 tests/ci-workflows/ci-privacy-gate.test.ts -8197 tests/ci-workflows/ci-review-lanes.test.ts -837 tests/ci-workflows/ci-scope-gaps.test.ts -676 tests/ci-workflows/ci-scope-reduction.test.ts -879 tests/ci-workflows/ci-shard-balance.test.ts -71 tests/ci-workflows/ci-structure-gate.test.ts -1487 tests/ci-workflows/ci-test-lane.test.ts -759 tests/ci-workflows/ci-workflows.test.ts -42 tests/ci-workflows/cleanup-orphaned-workflows.test.ts -48 tests/ci-workflows/closed-pr-branch-cleanup.test.ts -6803 tests/ci-workflows/cold-spawn-warmup.test.ts -384 tests/ci-workflows/compatibility-version.test.ts -53 tests/ci-workflows/docs-429-failover-claims.test.ts -38 tests/ci-workflows/docs-bun-source-requirement.test.ts -74 tests/ci-workflows/docs-developer-role-policy.test.ts -50 tests/ci-workflows/docs-gjc-reasoning-export.test.ts -72 tests/ci-workflows/docs-gpt61-terra.test.ts -47 tests/ci-workflows/docs-gui-screenshot-policy.test.ts -245 tests/ci-workflows/docs-link-targets.test.ts -47 tests/ci-workflows/docs-provider-billing-claims.test.ts -77 tests/ci-workflows/docs-provider-discovery-limits.test.ts -41 tests/ci-workflows/docs-provider-preset-counts.test.ts -170 tests/ci-workflows/docs-readme-memory-inventory.test.ts -51 tests/ci-workflows/docs-readme-translation-parity.test.ts -54 tests/ci-workflows/docs-remote-hub-claims.test.ts -163 tests/ci-workflows/dsh-path-contract.test.ts -375 tests/ci-workflows/dsh-rc6-compat-script.test.ts -151 tests/ci-workflows/dsh-writer-lock.test.ts -49 tests/ci-workflows/exhaustive-deps-suppression.test.ts -602 tests/ci-workflows/file-size-ratchet.test.ts -523 tests/ci-workflows/fixture-dir-uniqueness.test.ts -60 tests/ci-workflows/fixture-teardown-helper.test.ts -598 tests/ci-workflows/fixture-windows-runtime-preload.test.ts -442 tests/ci-workflows/import-cycle-ratchet.test.ts -352 tests/ci-workflows/install-scripts.test.ts -56 tests/ci-workflows/installed-gate-drivers.test.ts -98 tests/ci-workflows/keyring-smoke.test.ts -84 tests/ci-workflows/linux-desktop-packaged-ci.test.ts -45 tests/ci-workflows/linux-desktop-packaged-e2e.test.ts -5676 tests/ci-workflows/macos-serial-lanes.test.ts -2783 tests/ci-workflows/package-tree-fenced-restart.test.ts -2778 tests/ci-workflows/package-tree-integrity.test.ts -95 tests/ci-workflows/package-tree-restart-ownership.test.ts -144 tests/ci-workflows/package-tree-retarget.test.ts -76 tests/ci-workflows/pr-readiness-reattest.test.ts -62 tests/ci-workflows/privacy-scan-asset-names.test.ts +195 tests/adapters/bridge.test.ts +119 tests/adapters/buffered-response-shape-guards.test.ts +50 tests/adapters/coding-agent-history-projection.test.ts +24 tests/adapters/coding-agent-tool-result-images.test.ts +130 tests/adapters/coding-agent-windows-dispatch.test.ts +44 tests/adapters/dsh-account-adapter.test.ts +583 tests/adapters/empty-tool-output-annotation.test.ts +145 tests/adapters/exec-tool-result-normalize.test.ts +385 tests/adapters/fix-tool-number-preservation.test.ts +144 tests/adapters/google/antigravity-account-roster.test.ts +108 tests/adapters/google/antigravity-baseurl-override.test.ts +138 tests/adapters/google/antigravity-discovered-families.test.ts +56 tests/adapters/google/antigravity-refusal.test.ts +315 tests/adapters/google/antigravity-routing-carry.test.ts +116 tests/adapters/google/antigravity-static-catalog.test.ts +814 tests/adapters/google/gcp-adc.test.ts +572 tests/adapters/google/gcp-credential-boundary.test.ts +325 tests/adapters/google/gcp-sa-adapter.test.ts +713 tests/adapters/google/gcp-sa-marker.test.ts +76 tests/adapters/google/gemini-37-flash-migration.test.ts +109 tests/adapters/google/gemini-4-argon-antigravity.test.ts +60 tests/adapters/google/gemini-progress-history.test.ts +176 tests/adapters/google/gemini-web-search.test.ts +75 tests/adapters/google/google-adapter.test.ts +184 tests/adapters/google/google-ai-studio-foreign-call-signature.test.ts +4203 tests/adapters/google/google-antigravity-oauth.test.ts +2387 tests/adapters/google/google-antigravity-replay.test.ts +78 tests/adapters/google/google-antigravity-wire.test.ts +72 tests/adapters/google/google-buffered-stop-reason.test.ts +63 tests/adapters/google/google-claude-prefill-guard.test.ts +77 tests/adapters/google/google-empty-content.test.ts +423 tests/adapters/google/google-errors.test.ts +86 tests/adapters/google/google-hardening.test.ts +156 tests/adapters/google/google-models-listing.test.ts +91 tests/adapters/google/google-output-clamp.test.ts +61 tests/adapters/google/google-provider-metadata-roundtrip.test.ts +83 tests/adapters/google/google-signature-history-roundtrip.test.ts +47 tests/adapters/google/google-stream-fragmentation.test.ts +23 tests/adapters/google/google-strict-tool-validated-mode.test.ts +49 tests/adapters/google/google-structured-output.test.ts +55 tests/adapters/google/google-tool-result-adjacency.test.ts +133 tests/adapters/google/google-tool-schema-contract.test.ts +49 tests/adapters/google/google-tool-schema.test.ts +4701 tests/adapters/google/google-vertex-http.test.ts +93 tests/adapters/google/google-vertex-key-project.test.ts +56 tests/adapters/google/google-vertex-stream.test.ts +53 tests/adapters/google/google-vertex-thought-signature.test.ts +122 tests/adapters/google/google-wire-compiler.test.ts +115 tests/adapters/google/google-wire-shape.test.ts +108 tests/adapters/google/vertex-catalog.test.ts +195 tests/adapters/identity-neutralize.test.ts +445 tests/adapters/identity-subagent.test.ts +767 tests/adapters/key-failover.test.ts +81 tests/adapters/openai/inline-think-boundaries.test.ts +1774 tests/adapters/openai/openai-api-virtual-models.test.ts +76 tests/adapters/openai/openai-chat-audio.test.ts +178 tests/adapters/openai/openai-chat-bounded-tool-names.test.ts +89 tests/adapters/openai/openai-chat-dangling-toolcalls.test.ts +48 tests/adapters/openai/openai-chat-developer-position.test.ts +51 tests/adapters/openai/openai-chat-eof.test.ts +104 tests/adapters/openai/openai-chat-glm-summary.test.ts +618 tests/adapters/openai/openai-chat-hardening.test.ts +5444 tests/adapters/openai/openai-chat-image-normalization.test.ts +190 tests/adapters/openai/openai-chat-inline-think-tags.test.ts +48 tests/adapters/openai/openai-chat-invalid-tool-call-diagnostics.test.ts +112 tests/adapters/openai/openai-chat-mistral-content.test.ts +97 tests/adapters/openai/openai-chat-model-suffix.test.ts +357 tests/adapters/openai/openai-chat-native-policy.test.ts +108 tests/adapters/openai/openai-chat-nonce-tool-call-content.test.ts +61 tests/adapters/openai/openai-chat-parallel-stream.test.ts +90 tests/adapters/openai/openai-chat-path-override.test.ts +50 tests/adapters/openai/openai-chat-qwen38-leading-system.test.ts +96 tests/adapters/openai/openai-chat-reasoning-wire-policy.test.ts +118 tests/adapters/openai/openai-chat-required-tool.test.ts +188 tests/adapters/openai/openai-chat-sanitization-review-regressions.test.ts +138 tests/adapters/openai/openai-chat-serialized-tool-call-content.test.ts +315 tests/adapters/openai/openai-chat-serialized-tool-call-hold-bound.test.ts +160 tests/adapters/openai/openai-chat-serialized-tool-call-scaling.test.ts +73 tests/adapters/openai/openai-chat-serialized-tool-call-think.test.ts +53 tests/adapters/openai/openai-chat-single-system.test.ts +655 tests/adapters/openai/openai-chat-standalone-bare-block.test.ts +170 tests/adapters/openai/openai-chat-system-order.test.ts +241 tests/adapters/openai/openai-chat-tool-call-id-remint.test.ts +48 tests/adapters/openai/openai-chat-tool-result-images.test.ts +44 tests/adapters/openai/openai-chat-url.test.ts +61 tests/adapters/openai/openai-chat-video-part.test.ts +140 tests/adapters/openai/openai-empty-assistant-history.test.ts +214 tests/adapters/openai/openai-native-hosted-search-history.test.ts +1291 tests/adapters/openai/openai-provider-option-e2e.test.ts +368 tests/adapters/openai/openai-provider-option-migration.test.ts +68 tests/adapters/openai/openai-provider-option-startup.test.ts +64 tests/adapters/openai/openai-provider-option-tooling.test.ts +56 tests/adapters/openai/openai-provider-option.test.ts +46 tests/adapters/openai/opengateway-input.test.ts +121 tests/adapters/physical-send.test.ts +157 tests/adapters/qoder-spawn-readmission.test.ts +61 tests/adapters/reasoning-replay-identity.test.ts +168 tests/adapters/reasoning-replay-robustness.test.ts +140 tests/adapters/routed-agent-messages.test.ts +94 tests/adapters/run-turn-queue.test.ts +392 tests/adapters/terminal-continuation-owner-rotation.test.ts +127 tests/adapters/tool-argument-integers.test.ts +116 tests/adapters/tool-catalog-nudge.test.ts +44 tests/adapters/tool-choice-performance.test.ts +74 tests/adapters/tool-envelope-echo-whole-line.test.ts +156 tests/adapters/tool-identity-hash.test.ts +158 tests/adapters/translator-budget-lifetime.test.ts +4886 tests/adapters/translator-budget.test.ts +41 tests/adapters/upstream-http-error.test.ts +65 tests/adapters/workbuddy-adapter.test.ts +95 tests/advisor/advisor-adaptive.test.ts +51 tests/advisor/advisor-authority-transport.test.ts +87 tests/advisor/advisor-budget.test.ts +305 tests/advisor/advisor-caller-policy-compact.test.ts +360 tests/advisor/advisor-caller-policy-host-key.test.ts +409 tests/advisor/advisor-caller-policy-http.test.ts +194 tests/advisor/advisor-caller-policy-ingress.test.ts +285 tests/advisor/advisor-caller-policy-jev.test.ts +276 tests/advisor/advisor-caller-policy-replay.test.ts +650 tests/advisor/advisor-caller-policy-routing.test.ts +1120 tests/advisor/advisor-caller-policy-self-fetch.test.ts +224 tests/advisor/advisor-caller-policy-sidecar-authority.test.ts +496 tests/advisor/advisor-caller-policy-vision.test.ts +613 tests/advisor/advisor-caller-policy.test.ts +51 tests/advisor/advisor-consult.test.ts +34 tests/advisor/advisor-context.test.ts +63 tests/advisor/advisor-continuation-limit.test.ts +413 tests/advisor/advisor-core-boundary.test.ts +54 tests/advisor/advisor-evidence.test.ts +41 tests/advisor/advisor-guard.test.ts +294 tests/advisor/advisor-internal-authority.test.ts +64 tests/advisor/advisor-plan.test.ts +1240 tests/advisor/advisor-responses-wiring.test.ts +350 tests/advisor/advisor-retention.test.ts +450 tests/advisor/advisor-scope-transport.test.ts +138 tests/advisor/advisor-settings.test.ts +108 tests/advisor/advisor-state.test.ts +99 tests/advisor/advisor-web-search.test.ts +4334 tests/ci-workflows/assert-mergeable-review.test.ts +149 tests/ci-workflows/brand-favicons.test.ts +107 tests/ci-workflows/build-desktop-icon-set.test.ts +133 tests/ci-workflows/build-release-changelog.test.ts +242 tests/ci-workflows/bump-dev-version.test.ts +313 tests/ci-workflows/bun-runtime.test.ts +102 tests/ci-workflows/ci-bun-crash-classifier.test.ts +36771 tests/ci-workflows/ci-bun-install-frozen.test.ts +114 tests/ci-workflows/ci-concurrency-groups.test.ts +5977 tests/ci-workflows/ci-crash-disposition.test.ts +2466 tests/ci-workflows/ci-gui-typecheck-gate.test.ts +98 tests/ci-workflows/ci-pr-hygiene-approvals.test.ts +1623 tests/ci-workflows/ci-privacy-gate.test.ts +8025 tests/ci-workflows/ci-review-lanes.test.ts +1120 tests/ci-workflows/ci-scope-gaps.test.ts +684 tests/ci-workflows/ci-scope-reduction.test.ts +1548 tests/ci-workflows/ci-shard-balance.test.ts +44 tests/ci-workflows/ci-structure-gate.test.ts +1647 tests/ci-workflows/ci-test-lane.test.ts +887 tests/ci-workflows/ci-workflows.test.ts +38 tests/ci-workflows/cleanup-orphaned-workflows.test.ts +430 tests/ci-workflows/client-support-matrix.test.ts +1823 tests/ci-workflows/client-support-runtime.test.ts +86 tests/ci-workflows/closed-pr-branch-cleanup.test.ts +6908 tests/ci-workflows/cold-spawn-warmup.test.ts +360 tests/ci-workflows/compatibility-version.test.ts +85 tests/ci-workflows/docs-429-failover-claims.test.ts +56 tests/ci-workflows/docs-bun-source-requirement.test.ts +99 tests/ci-workflows/docs-developer-role-policy.test.ts +84 tests/ci-workflows/docs-gjc-reasoning-export.test.ts +127 tests/ci-workflows/docs-gpt61-terra.test.ts +45 tests/ci-workflows/docs-gui-screenshot-policy.test.ts +390 tests/ci-workflows/docs-link-targets.test.ts +23 tests/ci-workflows/docs-provider-billing-claims.test.ts +76 tests/ci-workflows/docs-provider-discovery-limits.test.ts +88 tests/ci-workflows/docs-provider-preset-counts.test.ts +249 tests/ci-workflows/docs-readme-memory-inventory.test.ts +58 tests/ci-workflows/docs-readme-translation-parity.test.ts +74 tests/ci-workflows/docs-remote-hub-claims.test.ts +135 tests/ci-workflows/dsh-path-contract.test.ts +500 tests/ci-workflows/dsh-rc6-compat-script.test.ts +190 tests/ci-workflows/dsh-writer-lock.test.ts +41 tests/ci-workflows/exhaustive-deps-suppression.test.ts +1654 tests/ci-workflows/file-size-ratchet.test.ts +962 tests/ci-workflows/fixture-dir-uniqueness.test.ts +48 tests/ci-workflows/fixture-teardown-helper.test.ts +624 tests/ci-workflows/fixture-windows-runtime-preload.test.ts +483 tests/ci-workflows/import-cycle-ratchet.test.ts +283 tests/ci-workflows/install-scripts.test.ts +162 tests/ci-workflows/installed-gate-drivers.test.ts +52 tests/ci-workflows/keyring-smoke.test.ts +50 tests/ci-workflows/linux-desktop-packaged-ci.test.ts +35 tests/ci-workflows/linux-desktop-packaged-e2e.test.ts +8890 tests/ci-workflows/macos-serial-lanes.test.ts +3207 tests/ci-workflows/package-tree-fenced-restart.test.ts +2983 tests/ci-workflows/package-tree-integrity.test.ts +284 tests/ci-workflows/package-tree-restart-ownership.test.ts +272 tests/ci-workflows/package-tree-retarget.test.ts +113 tests/ci-workflows/pr-readiness-reattest.test.ts +131 tests/ci-workflows/privacy-scan-asset-names.test.ts 47 tests/ci-workflows/privacy-scan-meta-key.test.ts -45 tests/ci-workflows/privacy-scan-ssh-endpoint.test.ts -95 tests/ci-workflows/release-desktop-scripts.test.ts -9154 tests/ci-workflows/release-helper.test.ts -63 tests/ci-workflows/release-notes.test.ts -137 tests/ci-workflows/release-outcome-report.test.ts -99 tests/ci-workflows/release-pipeline-contract.test.ts -2481 tests/ci-workflows/release-preflight.test.ts -139 tests/ci-workflows/release-resume-identity.test.ts -76 tests/ci-workflows/release-version-line.test.ts -174 tests/ci-workflows/release-version-sources.test.ts -23471 tests/ci-workflows/release-windows-signing.test.ts -222 tests/ci-workflows/repo-hygiene.test.ts -471 tests/ci-workflows/repo-import-resolution.test.ts -509 tests/ci-workflows/setup-hooks.test.ts -772 tests/ci-workflows/skill-ocx-generated.test.ts -123 tests/ci-workflows/skill-ocx-workflows.test.ts -70 tests/ci-workflows/skill-ocx.test.ts -591 tests/ci-workflows/structure-ssot.test.ts -991 tests/ci-workflows/test-home-guard-unpreloaded.test.ts -41436 tests/ci-workflows/test-home-guard.test.ts -21027 tests/ci-workflows/test-run-lock-generation.test.ts -196 tests/ci-workflows/test-runner-bun.test.ts -417 tests/ci-workflows/test-runner-spawnsync-finalizer.test.ts -18177 tests/ci-workflows/test-runner.test.ts -45 tests/ci-workflows/test-sandbox-cleanup.test.ts -70 tests/ci-workflows/test-temp-quarantine.test.ts -68 tests/ci-workflows/version-line.test.ts -78 tests/ci-workflows/warmup-registration.test.ts -43 tests/ci-workflows/zz-ci-api-usage-isolation.test.ts -39 tests/ci-workflows/zz-ci-storage-policy-isolation.test.ts -76 tests/ci-workflows/zz-pr-coderabbit-readiness-revalidation.test.ts -1793 tests/claude-integration/anthropic2-native-routing.test.ts -3168 tests/claude-integration/claude-529-mapping.test.ts -102 tests/claude-integration/claude-agent-startup-sync.test.ts -130 tests/claude-integration/claude-agents-inject-client.test.ts -116 tests/claude-integration/claude-agents-inject.test.ts -151 tests/claude-integration/claude-alias.test.ts -38 tests/claude-integration/claude-auth-detect.test.ts -156 tests/claude-integration/claude-auth-mode.test.ts -61 tests/claude-integration/claude-authmode-migration.test.ts -295 tests/claude-integration/claude-cli-picker-surface.test.ts -499 tests/claude-integration/claude-cli-picker.test.ts -109 tests/claude-integration/claude-cli.test.ts -1051 tests/claude-integration/claude-client-refusal-status.test.ts -163 tests/claude-integration/claude-code-thought-signature-scope.test.ts -43 tests/claude-integration/claude-compatibility.test.ts -407 tests/claude-integration/claude-config-home-isolation.test.ts -844 tests/claude-integration/claude-config-root-late-admission.test.ts -438 tests/claude-integration/claude-config-root-stale-updates.test.ts -507 tests/claude-integration/claude-config-root-writer-barrier.test.ts -112 tests/claude-integration/claude-context-accounting.test.ts -105 tests/claude-integration/claude-context-windows.test.ts -127 tests/claude-integration/claude-desktop-1m.test.ts -753 tests/claude-integration/claude-desktop-cli.test.ts -474 tests/claude-integration/claude-desktop-config-path.test.ts -677 tests/claude-integration/claude-desktop-discovery.test.ts -539 tests/claude-integration/claude-desktop-first-party-guards.test.ts -966 tests/claude-integration/claude-desktop-first-party.test.ts -128 tests/claude-integration/claude-desktop-mode-explanation.test.ts -133 tests/claude-integration/claude-desktop-native-context.test.ts -517 tests/claude-integration/claude-desktop-picker-profile.test.ts -563 tests/claude-integration/claude-desktop-picker-routes.test.ts -181 tests/claude-integration/claude-desktop-picker.test.ts -53 tests/claude-integration/claude-desktop-policy.test.ts -7276 tests/claude-integration/claude-desktop-remote-hub.test.ts -107 tests/claude-integration/claude-desktop-system-proxy.test.ts -316 tests/claude-integration/claude-devin-output-order.test.ts -126 tests/claude-integration/claude-dotenv-provenance-transport.test.ts -460 tests/claude-integration/claude-estimate-projection.test.ts -268 tests/claude-integration/claude-first-party-agent-sync.test.ts -170 tests/claude-integration/claude-first-party-union.test.ts -83 tests/claude-integration/claude-gateway-cache.test.ts -398 tests/claude-integration/claude-gateway-output-cap.test.ts -371 tests/claude-integration/claude-inbound-cache-stabilize.test.ts -70 tests/claude-integration/claude-inbound-debug.test.ts -79 tests/claude-integration/claude-inbound-token-footer.test.ts -486 tests/claude-integration/claude-inbound-tool-loading.test.ts -173 tests/claude-integration/claude-inbound-tool-reference.test.ts -137 tests/claude-integration/claude-inbound.test.ts -276 tests/claude-integration/claude-intercept-acl-barrier.test.ts -88 tests/claude-integration/claude-intercept-cleanup.test.ts -151 tests/claude-integration/claude-intercept-client-class.test.ts -99 tests/claude-integration/claude-intercept-local-ca-files.test.ts -146 tests/claude-integration/claude-intercept-local-ca-windows.test.ts -184 tests/claude-integration/claude-intercept-local-ca.test.ts -175 tests/claude-integration/claude-intercept-model-bindings.test.ts -168 tests/claude-integration/claude-intercept-no-proxy.test.ts -297 tests/claude-integration/claude-intercept-on-demand.test.ts -129 tests/claude-integration/claude-intercept-proxy-auth.test.ts -135 tests/claude-integration/claude-intercept-proxy.test.ts -131 tests/claude-integration/claude-intercept-settings.test.ts -97 tests/claude-integration/claude-long-context-eligibility.test.ts -5668 tests/claude-integration/claude-management-api.test.ts -5779 tests/claude-integration/claude-messages-endpoint.test.ts -431 tests/claude-integration/claude-messages-thread.test.ts -115 tests/claude-integration/claude-model-default-labels.test.ts -123 tests/claude-integration/claude-model-info.test.ts -1198 tests/claude-integration/claude-models-discovery.test.ts -2325 tests/claude-integration/claude-native-affinity.test.ts -1265 tests/claude-integration/claude-native-fast-1m-ingress.test.ts -8808 tests/claude-integration/claude-native-passthrough.test.ts -216 tests/claude-integration/claude-native-rate-limit-headers.test.ts -101 tests/claude-integration/claude-native-reasoning-continuity.test.ts -374 tests/claude-integration/claude-native-reasoning-provenance.test.ts -2776 tests/claude-integration/claude-outbound.test.ts -116 tests/claude-integration/claude-output-schema-strict.test.ts -258 tests/claude-integration/claude-picker-bootstrap.test.ts -766 tests/claude-integration/claude-picker-ca-store.test.ts -532 tests/claude-integration/claude-picker-ca.test.ts -96 tests/claude-integration/claude-picker-linger.test.ts -655 tests/claude-integration/claude-picker-listener.test.ts +49 tests/ci-workflows/privacy-scan-ssh-endpoint.test.ts +120 tests/ci-workflows/release-desktop-scripts.test.ts +12088 tests/ci-workflows/release-helper.test.ts +76 tests/ci-workflows/release-notes.test.ts +144 tests/ci-workflows/release-outcome-report.test.ts +122 tests/ci-workflows/release-pipeline-contract.test.ts +2338 tests/ci-workflows/release-preflight.test.ts +170 tests/ci-workflows/release-resume-identity.test.ts +96 tests/ci-workflows/release-version-line.test.ts +201 tests/ci-workflows/release-version-sources.test.ts +26969 tests/ci-workflows/release-windows-signing.test.ts +268 tests/ci-workflows/repo-hygiene.test.ts +420 tests/ci-workflows/repo-import-resolution.test.ts +538 tests/ci-workflows/setup-hooks.test.ts +750 tests/ci-workflows/skill-ocx-generated.test.ts +144 tests/ci-workflows/skill-ocx-workflows.test.ts +72 tests/ci-workflows/skill-ocx.test.ts +776 tests/ci-workflows/structure-ssot.test.ts +1201 tests/ci-workflows/test-home-guard-unpreloaded.test.ts +41237 tests/ci-workflows/test-home-guard.test.ts +20996 tests/ci-workflows/test-run-lock-generation.test.ts +202 tests/ci-workflows/test-runner-bun.test.ts +439 tests/ci-workflows/test-runner-spawnsync-finalizer.test.ts +18739 tests/ci-workflows/test-runner.test.ts +51 tests/ci-workflows/test-sandbox-cleanup.test.ts +89 tests/ci-workflows/test-temp-quarantine.test.ts +36 tests/ci-workflows/version-line.test.ts +96 tests/ci-workflows/warmup-registration.test.ts +55 tests/ci-workflows/zz-ci-api-usage-isolation.test.ts +101 tests/ci-workflows/zz-ci-storage-policy-isolation.test.ts +151 tests/ci-workflows/zz-pr-coderabbit-readiness-revalidation.test.ts +3556 tests/claude-integration/anthropic2-native-routing.test.ts +3179 tests/claude-integration/claude-529-mapping.test.ts +179 tests/claude-integration/claude-agent-startup-sync.test.ts +365 tests/claude-integration/claude-agents-inject-client.test.ts +224 tests/claude-integration/claude-agents-inject.test.ts +283 tests/claude-integration/claude-alias.test.ts +53 tests/claude-integration/claude-auth-detect.test.ts +142 tests/claude-integration/claude-auth-mode.test.ts +45 tests/claude-integration/claude-authmode-migration.test.ts +931 tests/claude-integration/claude-bridge-pool-dispatch.test.ts +132 tests/claude-integration/claude-bridge-pool-session.test.ts +380 tests/claude-integration/claude-cli-picker-surface.test.ts +560 tests/claude-integration/claude-cli-picker.test.ts +131 tests/claude-integration/claude-cli.test.ts +1128 tests/claude-integration/claude-client-refusal-status.test.ts +191 tests/claude-integration/claude-code-thought-signature-scope.test.ts +64 tests/claude-integration/claude-compatibility.test.ts +425 tests/claude-integration/claude-config-home-isolation.test.ts +1182 tests/claude-integration/claude-config-root-late-admission.test.ts +894 tests/claude-integration/claude-config-root-stale-updates.test.ts +631 tests/claude-integration/claude-config-root-writer-barrier.test.ts +113 tests/claude-integration/claude-context-accounting.test.ts +115 tests/claude-integration/claude-context-windows.test.ts +100 tests/claude-integration/claude-desktop-1m.test.ts +864 tests/claude-integration/claude-desktop-cli.test.ts +472 tests/claude-integration/claude-desktop-config-path.test.ts +1028 tests/claude-integration/claude-desktop-discovery.test.ts +684 tests/claude-integration/claude-desktop-first-party-guards.test.ts +1426 tests/claude-integration/claude-desktop-first-party.test.ts +129 tests/claude-integration/claude-desktop-mode-explanation.test.ts +669 tests/claude-integration/claude-desktop-model-visibility.test.ts +136 tests/claude-integration/claude-desktop-native-context.test.ts +600 tests/claude-integration/claude-desktop-picker-profile.test.ts +522 tests/claude-integration/claude-desktop-picker-routes.test.ts +237 tests/claude-integration/claude-desktop-picker.test.ts +51 tests/claude-integration/claude-desktop-policy.test.ts +7651 tests/claude-integration/claude-desktop-remote-hub.test.ts +238 tests/claude-integration/claude-desktop-system-proxy.test.ts +356 tests/claude-integration/claude-devin-output-order.test.ts +220 tests/claude-integration/claude-dotenv-provenance-transport.test.ts +553 tests/claude-integration/claude-estimate-projection.test.ts +300 tests/claude-integration/claude-first-party-agent-sync.test.ts +154 tests/claude-integration/claude-first-party-union.test.ts +85 tests/claude-integration/claude-gateway-cache.test.ts +436 tests/claude-integration/claude-gateway-output-cap.test.ts +404 tests/claude-integration/claude-inbound-cache-stabilize.test.ts +64 tests/claude-integration/claude-inbound-debug.test.ts +146 tests/claude-integration/claude-inbound-token-footer.test.ts +539 tests/claude-integration/claude-inbound-tool-loading.test.ts +107 tests/claude-integration/claude-inbound-tool-reference.test.ts +117 tests/claude-integration/claude-inbound.test.ts +287 tests/claude-integration/claude-installation-helper.test.ts +350 tests/claude-integration/claude-intercept-acl-barrier.test.ts +81 tests/claude-integration/claude-intercept-cleanup.test.ts +233 tests/claude-integration/claude-intercept-client-class.test.ts +105 tests/claude-integration/claude-intercept-local-ca-files.test.ts +181 tests/claude-integration/claude-intercept-local-ca-windows.test.ts +199 tests/claude-integration/claude-intercept-local-ca.test.ts +416 tests/claude-integration/claude-intercept-model-bindings.test.ts +153 tests/claude-integration/claude-intercept-no-proxy.test.ts +331 tests/claude-integration/claude-intercept-on-demand.test.ts +213 tests/claude-integration/claude-intercept-proxy-auth.test.ts +150 tests/claude-integration/claude-intercept-proxy.test.ts +178 tests/claude-integration/claude-intercept-settings.test.ts +121 tests/claude-integration/claude-long-context-eligibility.test.ts +7688 tests/claude-integration/claude-management-api.test.ts +7174 tests/claude-integration/claude-messages-endpoint.test.ts +426 tests/claude-integration/claude-messages-thread.test.ts +135 tests/claude-integration/claude-model-default-labels.test.ts +196 tests/claude-integration/claude-model-info.test.ts +1499 tests/claude-integration/claude-models-discovery.test.ts +2499 tests/claude-integration/claude-native-affinity.test.ts +1041 tests/claude-integration/claude-native-fast-1m-ingress.test.ts +10131 tests/claude-integration/claude-native-passthrough.test.ts +200 tests/claude-integration/claude-native-rate-limit-headers.test.ts +97 tests/claude-integration/claude-native-reasoning-continuity.test.ts +770 tests/claude-integration/claude-native-reasoning-provenance.test.ts +2318 tests/claude-integration/claude-outbound.test.ts +97 tests/claude-integration/claude-output-schema-strict.test.ts +230 tests/claude-integration/claude-picker-bootstrap.test.ts +699 tests/claude-integration/claude-picker-ca-store.test.ts +491 tests/claude-integration/claude-picker-ca.test.ts +89 tests/claude-integration/claude-picker-linger.test.ts +919 tests/claude-integration/claude-picker-listener.test.ts 138 tests/claude-integration/claude-picker-models.test.ts -1045 tests/claude-integration/claude-picker-recovery.test.ts -226 tests/claude-integration/claude-picker-relay-intent.test.ts -593 tests/claude-integration/claude-picker-runtime.test.ts -1445 tests/claude-integration/claude-picker-startup.test.ts -75 tests/claude-integration/claude-picker-trust-windows.test.ts -48 tests/claude-integration/claude-picker-trust.test.ts -4014 tests/claude-integration/claude-picker-upload.test.ts -560 tests/claude-integration/claude-picker-windows.test.ts -1978 tests/claude-integration/claude-prompt-too-long.test.ts -115 tests/claude-integration/claude-shell-hook.test.ts -125 tests/claude-integration/claude-sidecar-override.test.ts -87 tests/claude-integration/claude-source-envelope.test.ts -133 tests/claude-integration/claude-subagent-model-force.test.ts -112 tests/claude-integration/claude-system-env-auto.test.ts -335 tests/claude-integration/claude-tool-loading-destinations.test.ts -249 tests/claude-integration/claude-translated-cache-ttl.test.ts -605 tests/claude-integration/claude-translated-server-tools.test.ts -340 tests/claude-integration/messages-native-decline-trace.test.ts -468 tests/claude-integration/messages-native-empty-inline.test.ts -646 tests/claude-integration/messages-native-key-selection.test.ts -2124 tests/claude-integration/messages-native-oauth.test.ts -209 tests/claude-integration/messages-native-opaque-state.test.ts -468 tests/claude-integration/messages-native-scope.test.ts -2577 tests/claude-integration/messages-native.test.ts -1993 tests/claude-integration/messages-request-id-endpoint.test.ts -112 tests/claude-integration/messages-request-id-headers.test.ts -1216 tests/claude-integration/messages-revoked-token.test.ts -160 tests/claude-integration/messages-surface-matrix.test.ts -44 tests/cli/agent-driven.test.ts -79 tests/cli/agent-subagent-force.test.ts -712 tests/cli/bun-transpiler-cache-scope.test.ts -79 tests/cli/claude-config-first-party.test.ts -15199 tests/cli/cli-access-audio-live.test.ts -384 tests/cli/cli-access-audio.test.ts -136 tests/cli/cli-access-data-plane.test.ts -105 tests/cli/cli-access-key-guard.test.ts -132 tests/cli/cli-access-rename.test.ts -85 tests/cli/cli-account-alias-target.test.ts -89 tests/cli/cli-account-cancel-flow.test.ts -115 tests/cli/cli-account-key-pause.test.ts -109 tests/cli/cli-account-key-quota.test.ts -77 tests/cli/cli-account-kiro-device.test.ts -371 tests/cli/cli-account-login-options.test.ts -49 tests/cli/cli-account-orca-import.test.ts -93 tests/cli/cli-account-pin-drain.test.ts -648 tests/cli/cli-account-policy.test.ts -97 tests/cli/cli-account-pool-verbs.test.ts -87 tests/cli/cli-account-preservation.test.ts -119 tests/cli/cli-account-slot-identity.test.ts -175 tests/cli/cli-account-threshold.test.ts -87 tests/cli/cli-account-verify-status.test.ts -642 tests/cli/cli-account.test.ts -187 tests/cli/cli-agent-runtime-settings.test.ts -234 tests/cli/cli-agent-settings.test.ts -85 tests/cli/cli-alias-json.test.ts -74 tests/cli/cli-anthropic-account-threshold.test.ts -91 tests/cli/cli-anthropic2-account.test.ts -122 tests/cli/cli-api-protocols.test.ts -111 tests/cli/cli-aside-sync.test.ts -70 tests/cli/cli-capabilities-arguments.test.ts -116 tests/cli/cli-capabilities.test.ts -91 tests/cli/cli-capability-access-workflows.test.ts -99 tests/cli/cli-capability-account-workflows.test.ts -136 tests/cli/cli-capability-agent-workflows.test.ts -2037 tests/cli/cli-capability-data.test.ts -155 tests/cli/cli-capability-integration-workflows.test.ts -186 tests/cli/cli-capability-lab-workflows.test.ts -127 tests/cli/cli-capability-operation-workflows.test.ts -118 tests/cli/cli-capability-provider-workflows.test.ts -75 tests/cli/cli-catalog-command-result.test.ts -49 tests/cli/cli-catalog-prewarm.test.ts -418 tests/cli/cli-claude-desktop-profile.test.ts -111 tests/cli/cli-client-start-fence.test.ts -1997 tests/cli/cli-client-start-owner-e2e.test.ts -7187 tests/cli/cli-codex-cli-update-boundary.test.ts -824 tests/cli/cli-codex-cli-update.test.ts -76 tests/cli/cli-codex-log-guard-compact.test.ts -158 tests/cli/cli-codex-log-guard-protection.test.ts -98 tests/cli/cli-codex-log-guard.test.ts -177 tests/cli/cli-combo-parity.test.ts -78 tests/cli/cli-combo-partial-update.test.ts -160 tests/cli/cli-combo-session-pin.test.ts -179 tests/cli/cli-combo-set-targets.test.ts -105 tests/cli/cli-combo-stats.test.ts -130 tests/cli/cli-companion-timeline.test.ts -107 tests/cli/cli-companion-usage.test.ts -82 tests/cli/cli-companion.test.ts -822 tests/cli/cli-config-bom.test.ts -5120 tests/cli/cli-config-command.test.ts -1437 tests/cli/cli-config-default-show.test.ts -2437 tests/cli/cli-config-show-client.test.ts -5445 tests/cli/cli-connect-readiness.test.ts -254 tests/cli/cli-dispatch.test.ts -90 tests/cli/cli-dto-fidelity.test.ts -119 tests/cli/cli-effort-slug.test.ts -222 tests/cli/cli-effort.test.ts -112 tests/cli/cli-ensure-client-state.test.ts -123 tests/cli/cli-ensure-desktop-cold-start.test.ts -75 tests/cli/cli-ensure-readiness.test.ts -800 tests/cli/cli-export-command.test.ts -115 tests/cli/cli-export-model-names.test.ts -80 tests/cli/cli-fallback.test.ts -45 tests/cli/cli-head.test.ts -364 tests/cli/cli-headless-parity.test.ts -2803 tests/cli/cli-help-navigation.test.ts -14127 tests/cli/cli-help-paths.test.ts -6242 tests/cli/cli-help-recovery.test.ts -11192 tests/cli/cli-help.test.ts -1027 tests/cli/cli-init-port.test.ts -129 tests/cli/cli-injection-follow.test.ts -118 tests/cli/cli-integer-options.test.ts -133 tests/cli/cli-integration-cursor.test.ts -99 tests/cli/cli-integration-droid.test.ts -194 tests/cli/cli-integration-journal.test.ts -374 tests/cli/cli-integration-preview.test.ts -143 tests/cli/cli-json-contract.test.ts -288 tests/cli/cli-json-input.test.ts -101 tests/cli/cli-kiro-auto-selection.test.ts -134 tests/cli/cli-link-child.test.ts -132 tests/cli/cli-link-cleanup.test.ts -116 tests/cli/cli-link-enrollment.test.ts -236 tests/cli/cli-link-force.test.ts -136 tests/cli/cli-link.test.ts -313 tests/cli/cli-log-follow.test.ts -87 tests/cli/cli-log-history.test.ts -323 tests/cli/cli-log-view-filter.test.ts -118 tests/cli/cli-logout-runtime.test.ts -86 tests/cli/cli-logs-request-id.test.ts -100 tests/cli/cli-management-auth.test.ts -245 tests/cli/cli-models-custom-runtime.test.ts -155 tests/cli/cli-models-display-name.test.ts -90 tests/cli/cli-models-free-only.test.ts -168 tests/cli/cli-models-local-result.test.ts -132 tests/cli/cli-models-order.test.ts -98 tests/cli/cli-models-price.test.ts -87 tests/cli/cli-models-prompt-length-pricing.test.ts -174 tests/cli/cli-models-reasoning.test.ts -124 tests/cli/cli-models-runtime-dispatch.test.ts -104 tests/cli/cli-models-set.test.ts -11448 tests/cli/cli-models.test.ts -144 tests/cli/cli-native-profile.test.ts -88 tests/cli/cli-observe-logs.test.ts -104 tests/cli/cli-observe-snapshot.test.ts -57 tests/cli/cli-path-diagnostics.test.ts -286 tests/cli/cli-provider-batch.test.ts -141 tests/cli/cli-provider-lifecycle-runtime.test.ts -2258 tests/cli/cli-provider-list-active.test.ts -91 tests/cli/cli-provider-result.test.ts -105 tests/cli/cli-provider-settings.test.ts -349 tests/cli/cli-provider-sync-result.test.ts -23168 tests/cli/cli-provider.test.ts -1235 tests/cli/cli-ready-subprocess.test.ts -54 tests/cli/cli-ready.test.ts -121 tests/cli/cli-registry.test.ts -247 tests/cli/cli-remote-workspace-hub.test.ts -2729 tests/cli/cli-resolve-subprocess.test.ts -78 tests/cli/cli-resolve.test.ts -97 tests/cli/cli-restart-handoff.test.ts -3254 tests/cli/cli-restart-health.test.ts -2337 tests/cli/cli-restore-back.test.ts -119 tests/cli/cli-route-policy-not-found.test.ts -1067 tests/cli/cli-route-policy-write.test.ts -2955 tests/cli/cli-start-auxiliary-bind.test.ts -15162 tests/cli/cli-start-journal-order.test.ts -3426 tests/cli/cli-start-owner-absence.test.ts -3477 tests/cli/cli-start-owner-evidence.test.ts -39 tests/cli/cli-start-routing-heal-wiring.test.ts -121 tests/cli/cli-status-codex-routing-drift.test.ts -2426 tests/cli/cli-status-hub-state.test.ts -14616 tests/cli/cli-status-json.test.ts -127 tests/cli/cli-status-oauth-health.test.ts -1809 tests/cli/cli-status-startup-health.test.ts -134 tests/cli/cli-stop-json.test.ts -403 tests/cli/cli-stop-refusal-transport.test.ts -138 tests/cli/cli-storage-inspect.test.ts -208 tests/cli/cli-storage-policy-fields.test.ts -257 tests/cli/cli-sync-expect-link.test.ts -121 tests/cli/cli-system-health.test.ts -126 tests/cli/cli-system-settings-parity.test.ts +1125 tests/claude-integration/claude-picker-recovery.test.ts +281 tests/claude-integration/claude-picker-relay-intent.test.ts +494 tests/claude-integration/claude-picker-runtime.test.ts +1933 tests/claude-integration/claude-picker-startup.test.ts +97 tests/claude-integration/claude-picker-trust-windows.test.ts +54 tests/claude-integration/claude-picker-trust.test.ts +4387 tests/claude-integration/claude-picker-upload.test.ts +686 tests/claude-integration/claude-picker-windows.test.ts +2199 tests/claude-integration/claude-prompt-too-long.test.ts +142 tests/claude-integration/claude-shell-hook.test.ts +312 tests/claude-integration/claude-sidecar-override.test.ts +88 tests/claude-integration/claude-source-envelope.test.ts +240 tests/claude-integration/claude-subagent-model-force.test.ts +185 tests/claude-integration/claude-system-env-auto.test.ts +463 tests/claude-integration/claude-tool-loading-destinations.test.ts +256 tests/claude-integration/claude-translated-cache-ttl.test.ts +952 tests/claude-integration/claude-translated-server-tools.test.ts +503 tests/claude-integration/claude-translated-tool-restrictions.test.ts +451 tests/claude-integration/messages-native-clean-eof.test.ts +368 tests/claude-integration/messages-native-decline-trace.test.ts +730 tests/claude-integration/messages-native-empty-inline.test.ts +1199 tests/claude-integration/messages-native-key-selection.test.ts +2790 tests/claude-integration/messages-native-oauth.test.ts +402 tests/claude-integration/messages-native-opaque-state.test.ts +782 tests/claude-integration/messages-native-scope.test.ts +3122 tests/claude-integration/messages-native.test.ts +2549 tests/claude-integration/messages-request-id-endpoint.test.ts +101 tests/claude-integration/messages-request-id-headers.test.ts +1511 tests/claude-integration/messages-revoked-token.test.ts +302 tests/claude-integration/messages-shared-sse.test.ts +138 tests/claude-integration/messages-surface-matrix.test.ts +43 tests/cli/agent-driven.test.ts +93 tests/cli/agent-subagent-force.test.ts +1370 tests/cli/bun-transpiler-cache-scope.test.ts +93 tests/cli/claude-config-first-party.test.ts +15257 tests/cli/cli-access-audio-live.test.ts +866 tests/cli/cli-access-audio.test.ts +384 tests/cli/cli-access-data-plane.test.ts +134 tests/cli/cli-access-key-guard.test.ts +369 tests/cli/cli-access-rename.test.ts +94 tests/cli/cli-account-alias-target.test.ts +133 tests/cli/cli-account-cancel-flow.test.ts +149 tests/cli/cli-account-key-pause.test.ts +174 tests/cli/cli-account-key-quota.test.ts +329 tests/cli/cli-account-kiro-device.test.ts +917 tests/cli/cli-account-login-options.test.ts +81 tests/cli/cli-account-orca-import.test.ts +116 tests/cli/cli-account-pin-drain.test.ts +532 tests/cli/cli-account-policy.test.ts +87 tests/cli/cli-account-pool-verbs.test.ts +214 tests/cli/cli-account-preservation.test.ts +172 tests/cli/cli-account-slot-identity.test.ts +80 tests/cli/cli-account-threshold.test.ts +107 tests/cli/cli-account-verify-status.test.ts +979 tests/cli/cli-account.test.ts +277 tests/cli/cli-agent-runtime-settings.test.ts +474 tests/cli/cli-agent-settings.test.ts +203 tests/cli/cli-alias-json.test.ts +166 tests/cli/cli-anthropic-account-threshold.test.ts +113 tests/cli/cli-anthropic2-account.test.ts +414 tests/cli/cli-api-protocols.test.ts +128 tests/cli/cli-aside-sync.test.ts +77 tests/cli/cli-capabilities-arguments.test.ts +153 tests/cli/cli-capabilities.test.ts +99 tests/cli/cli-capability-access-workflows.test.ts +93 tests/cli/cli-capability-account-workflows.test.ts +160 tests/cli/cli-capability-agent-workflows.test.ts +2975 tests/cli/cli-capability-data.test.ts +228 tests/cli/cli-capability-integration-workflows.test.ts +205 tests/cli/cli-capability-lab-workflows.test.ts +352 tests/cli/cli-capability-operation-workflows.test.ts +115 tests/cli/cli-capability-provider-workflows.test.ts +114 tests/cli/cli-catalog-command-result.test.ts +52 tests/cli/cli-catalog-prewarm.test.ts +606 tests/cli/cli-claude-desktop-profile.test.ts +158 tests/cli/cli-client-start-fence.test.ts +2649 tests/cli/cli-client-start-owner-e2e.test.ts +8773 tests/cli/cli-codex-cli-update-boundary.test.ts +975 tests/cli/cli-codex-cli-update.test.ts +62 tests/cli/cli-codex-log-guard-compact.test.ts +120 tests/cli/cli-codex-log-guard-protection.test.ts +87 tests/cli/cli-codex-log-guard.test.ts +271 tests/cli/cli-combo-parity.test.ts +137 tests/cli/cli-combo-partial-update.test.ts +143 tests/cli/cli-combo-session-pin.test.ts +145 tests/cli/cli-combo-set-targets.test.ts +244 tests/cli/cli-combo-stats.test.ts +235 tests/cli/cli-companion-timeline.test.ts +234 tests/cli/cli-companion-usage.test.ts +79 tests/cli/cli-companion.test.ts +749 tests/cli/cli-config-bom.test.ts +5574 tests/cli/cli-config-command.test.ts +2226 tests/cli/cli-config-default-show.test.ts +2352 tests/cli/cli-config-show-client.test.ts +6959 tests/cli/cli-connect-readiness.test.ts +363 tests/cli/cli-dispatch.test.ts +124 tests/cli/cli-dto-fidelity.test.ts +103 tests/cli/cli-effort-slug.test.ts +185 tests/cli/cli-effort.test.ts +173 tests/cli/cli-ensure-client-state.test.ts +130 tests/cli/cli-ensure-desktop-cold-start.test.ts +113 tests/cli/cli-ensure-readiness.test.ts +768 tests/cli/cli-export-command.test.ts +153 tests/cli/cli-export-model-names.test.ts +89 tests/cli/cli-fallback.test.ts +47 tests/cli/cli-head.test.ts +684 tests/cli/cli-headless-parity.test.ts +2838 tests/cli/cli-help-navigation.test.ts +16831 tests/cli/cli-help-paths.test.ts +9080 tests/cli/cli-help-recovery.test.ts +12091 tests/cli/cli-help.test.ts +1066 tests/cli/cli-init-port.test.ts +131 tests/cli/cli-injection-follow.test.ts +83 tests/cli/cli-integer-options.test.ts +92 tests/cli/cli-integration-cursor.test.ts +109 tests/cli/cli-integration-droid.test.ts +268 tests/cli/cli-integration-journal.test.ts +643 tests/cli/cli-integration-preview.test.ts +153 tests/cli/cli-json-contract.test.ts +381 tests/cli/cli-json-input.test.ts +80 tests/cli/cli-kiro-auto-selection.test.ts +228 tests/cli/cli-link-child.test.ts +102 tests/cli/cli-link-cleanup.test.ts +103 tests/cli/cli-link-enrollment.test.ts +238 tests/cli/cli-link-force.test.ts +147 tests/cli/cli-link.test.ts +502 tests/cli/cli-log-follow.test.ts +123 tests/cli/cli-log-history.test.ts +315 tests/cli/cli-log-view-filter.test.ts +174 tests/cli/cli-logout-runtime.test.ts +100 tests/cli/cli-logs-request-id.test.ts +462 tests/cli/cli-management-auth.test.ts +1525 tests/cli/cli-message-mcp.test.ts +340 tests/cli/cli-models-custom-runtime.test.ts +167 tests/cli/cli-models-display-name.test.ts +85 tests/cli/cli-models-free-only.test.ts +157 tests/cli/cli-models-local-result.test.ts +131 tests/cli/cli-models-order.test.ts +252 tests/cli/cli-models-price.test.ts +92 tests/cli/cli-models-prompt-length-pricing.test.ts +153 tests/cli/cli-models-reasoning.test.ts +133 tests/cli/cli-models-runtime-dispatch.test.ts +216 tests/cli/cli-models-set.test.ts +12347 tests/cli/cli-models.test.ts +410 tests/cli/cli-native-profile.test.ts +109 tests/cli/cli-observe-logs.test.ts +116 tests/cli/cli-observe-snapshot.test.ts +93 tests/cli/cli-path-diagnostics.test.ts +545 tests/cli/cli-provider-batch.test.ts +121 tests/cli/cli-provider-cc-switch-import.test.ts +298 tests/cli/cli-provider-lifecycle-runtime.test.ts +2719 tests/cli/cli-provider-list-active.test.ts +306 tests/cli/cli-provider-result.test.ts +194 tests/cli/cli-provider-settings.test.ts +547 tests/cli/cli-provider-sync-result.test.ts +24795 tests/cli/cli-provider.test.ts +2131 tests/cli/cli-ready-subprocess.test.ts +111 tests/cli/cli-ready.test.ts +107 tests/cli/cli-registry.test.ts +231 tests/cli/cli-remote-workspace-hub.test.ts +2549 tests/cli/cli-resolve-subprocess.test.ts +131 tests/cli/cli-resolve.test.ts +129 tests/cli/cli-restart-handoff.test.ts +3408 tests/cli/cli-restart-health.test.ts +2658 tests/cli/cli-restore-back.test.ts +625 tests/cli/cli-role-suggestion-history.test.ts +133 tests/cli/cli-route-policy-not-found.test.ts +1109 tests/cli/cli-route-policy-write.test.ts +3723 tests/cli/cli-start-auxiliary-bind.test.ts +16336 tests/cli/cli-start-journal-order.test.ts +3756 tests/cli/cli-start-owner-absence.test.ts +3413 tests/cli/cli-start-owner-evidence.test.ts +21 tests/cli/cli-start-routing-heal-wiring.test.ts +511 tests/cli/cli-status-codex-routing-drift.test.ts +2557 tests/cli/cli-status-hub-state.test.ts +16755 tests/cli/cli-status-json.test.ts +137 tests/cli/cli-status-oauth-health.test.ts +1833 tests/cli/cli-status-startup-health.test.ts +107 tests/cli/cli-stop-json.test.ts +401 tests/cli/cli-stop-refusal-transport.test.ts +75 tests/cli/cli-storage-inspect.test.ts +266 tests/cli/cli-storage-policy-fields.test.ts +220 tests/cli/cli-sync-expect-link.test.ts +237 tests/cli/cli-system-health.test.ts +133 tests/cli/cli-system-settings-parity.test.ts 130 tests/cli/cli-transport-honesty.test.ts -1348 tests/cli/cli-update-badge.test.ts -440 tests/cli/cli-update-restart-admission.test.ts -35 tests/cli/cli-update-restart-child.test.ts -76 tests/cli/cli-update-restart-desktop-service.test.ts -148 tests/cli/cli-update-restart-home.test.ts -81 tests/cli/cli-update-restart-service-record.test.ts -45 tests/cli/cli-update-restart-supervision.test.ts -616 tests/cli/cli-update-restart-transport.test.ts -330 tests/cli/cli-update-restart.test.ts -2925 tests/cli/cli-usage-compare.test.ts -106 tests/cli/cli-usage-hub.test.ts -119 tests/cli/cli-usage-model-search.test.ts -95 tests/cli/cli-usage-report.test.ts -193 tests/cli/cli-usage-scope.test.ts -1106 tests/cli/cli-usage-top.test.ts -690 tests/cli/cli-v2-runtime.test.ts -8875 tests/cli/cli-version-skew.test.ts -114 tests/cli/cross-home-loopback-family.test.ts -119 tests/cli/ensure-desired-integrations-race.test.ts -1173 tests/cli/hub-disable.test.ts -178 tests/cli/hub-gated-local-clients.test.ts -96 tests/cli/hub-invite.test.ts -49 tests/cli/interactive-confirm.test.ts -62 tests/cli/link-apply-restart.test.ts -167 tests/cli/local-credentials.test.ts -76 tests/cli/model-selection-guidance.test.ts -2021 tests/cli/ocx-launcher-desktop-handoff.test.ts -44 tests/cli/ocx-launcher-fixture-trust.test.ts -2519 tests/cli/ocx-launcher-runtime.test.ts -47 tests/cli/ocx-launcher-source.test.ts -63 tests/cli/ocx-run.test.ts -1034 tests/cli/restore-completes-shared-teardown.test.ts -393 tests/cli/route-explainability.test.ts -15770 tests/cli/sibling-home-client-sync.test.ts -50 tests/cli/star-deferral.test.ts -66 tests/cli/start-args.test.ts -48 tests/cli/start-ownership-publication.test.ts -438 tests/cli/status-install-method.test.ts -53 tests/cli/system-restart-client-package-tree.test.ts -54 tests/cli/system-restart-client.test.ts -223 tests/cli/uninstall.test.ts -140 tests/clients/agent-clients.test.ts -118 tests/clients/aside-profile-identity.test.ts -201 tests/clients/aside-profile-paths.test.ts -1591 tests/clients/aside-profile-sync-owner.test.ts -135 tests/clients/aside-profiles-catalog-refresh.test.ts -604 tests/clients/aside-profiles.test.ts -76 tests/clients/client-catalog-compatibility.test.ts -19028 tests/clients/client-connect.test.ts -221 tests/clients/client-export-effective-metadata.test.ts -551 tests/clients/client-export-live-wire.test.ts -101 tests/clients/client-export-modality-enum.test.ts -241 tests/clients/client-export-model-names.test.ts -92 tests/clients/client-export-reasoning-controls.test.ts -89 tests/clients/client-export-reasoning-metadata.test.ts -47 tests/clients/client-fingerprint.test.ts -263 tests/clients/client-home-unreachable.test.ts -91 tests/clients/client-hub-relay.test.ts -93 tests/clients/client-hub-state.test.ts -70 tests/clients/client-hub-usage.test.ts -275 tests/clients/client-lifecycle-lock.test.ts -350 tests/clients/client-link-connect.test.ts -5351 tests/clients/client-link-relay.test.ts -6772 tests/clients/client-link-runtime.test.ts -50 tests/clients/client-link-state.test.ts -43 tests/clients/client-link-status.test.ts -188 tests/clients/client-link-teardown.test.ts -4448 tests/clients/client-link-tunnel.test.ts -5270 tests/clients/client-machine-listener.test.ts -108 tests/clients/client-path.test.ts -139 tests/clients/client-runtime-restart.test.ts -107 tests/clients/client-runtime.test.ts -105 tests/clients/cline-client.test.ts -326 tests/clients/cline-writer.test.ts -136 tests/clients/command-code-client-contract.test.ts -95 tests/clients/command-code-client.test.ts -121 tests/clients/desktop-3p-guard.test.ts -1246 tests/clients/desktop-3p-removal.test.ts -1042 tests/clients/desktop-3p-write-files.test.ts -254 tests/clients/desktop-3p.test.ts -59 tests/clients/desktop-app-restart-posix.test.ts -87 tests/clients/desktop-app-restart.test.ts -1884 tests/clients/desktop-app-server-shim-launcher.test.ts -77 tests/clients/desktop-app-server-shim.test.ts -16088 tests/clients/desktop-bundle-trust-async.test.ts -57 tests/clients/desktop-chatgpt-config.test.ts -63 tests/clients/desktop-cli-command-surface.test.ts -100 tests/clients/desktop-cli-contracts.test.ts +1281 tests/cli/cli-update-badge.test.ts +481 tests/cli/cli-update-restart-admission.test.ts +45 tests/cli/cli-update-restart-child.test.ts +96 tests/cli/cli-update-restart-desktop-service.test.ts +176 tests/cli/cli-update-restart-home.test.ts +96 tests/cli/cli-update-restart-service-record.test.ts +44 tests/cli/cli-update-restart-supervision.test.ts +644 tests/cli/cli-update-restart-transport.test.ts +408 tests/cli/cli-update-restart.test.ts +3391 tests/cli/cli-usage-compare.test.ts +98 tests/cli/cli-usage-hub.test.ts +96 tests/cli/cli-usage-model-search.test.ts +118 tests/cli/cli-usage-report.test.ts +167 tests/cli/cli-usage-scope.test.ts +1431 tests/cli/cli-usage-top.test.ts +743 tests/cli/cli-v2-runtime.test.ts +8820 tests/cli/cli-version-skew.test.ts +96 tests/cli/cross-home-loopback-family.test.ts +137 tests/cli/ensure-desired-integrations-race.test.ts +1320 tests/cli/hub-disable.test.ts +386 tests/cli/hub-gated-local-clients.test.ts +146 tests/cli/hub-invite.test.ts +52 tests/cli/interactive-confirm.test.ts +71 tests/cli/link-apply-restart.test.ts +213 tests/cli/local-credentials.test.ts +59 tests/cli/model-selection-guidance.test.ts +2296 tests/cli/ocx-launcher-desktop-handoff.test.ts +69 tests/cli/ocx-launcher-fixture-trust.test.ts +3584 tests/cli/ocx-launcher-runtime.test.ts +36 tests/cli/ocx-launcher-source.test.ts +33 tests/cli/ocx-run.test.ts +1012 tests/cli/restore-completes-shared-teardown.test.ts +773 tests/cli/route-explainability.test.ts +16310 tests/cli/sibling-home-client-sync.test.ts +62 tests/cli/star-deferral.test.ts +58 tests/cli/start-args.test.ts +42 tests/cli/start-ownership-publication.test.ts +444 tests/cli/status-install-method.test.ts +41 tests/cli/system-restart-client-package-tree.test.ts +82 tests/cli/system-restart-client.test.ts +338 tests/cli/uninstall.test.ts +171 tests/clients/agent-clients.test.ts +97 tests/clients/aside-profile-identity.test.ts +261 tests/clients/aside-profile-paths.test.ts +2024 tests/clients/aside-profile-sync-owner.test.ts +186 tests/clients/aside-profiles-catalog-refresh.test.ts +564 tests/clients/aside-profiles.test.ts +112 tests/clients/client-catalog-compatibility.test.ts +26804 tests/clients/client-connect.test.ts +141 tests/clients/client-export-effective-metadata.test.ts +725 tests/clients/client-export-live-wire.test.ts +149 tests/clients/client-export-modality-enum.test.ts +403 tests/clients/client-export-model-names.test.ts +99 tests/clients/client-export-reasoning-controls.test.ts +119 tests/clients/client-export-reasoning-metadata.test.ts +58 tests/clients/client-fingerprint.test.ts +265 tests/clients/client-home-unreachable.test.ts +56 tests/clients/client-hub-relay.test.ts +83 tests/clients/client-hub-state.test.ts +73 tests/clients/client-hub-usage.test.ts +378 tests/clients/client-lifecycle-lock.test.ts +392 tests/clients/client-link-connect.test.ts +5325 tests/clients/client-link-relay.test.ts +6608 tests/clients/client-link-runtime.test.ts +104 tests/clients/client-link-state.test.ts +48 tests/clients/client-link-status.test.ts +255 tests/clients/client-link-teardown.test.ts +4595 tests/clients/client-link-tunnel.test.ts +5285 tests/clients/client-machine-listener.test.ts +89 tests/clients/client-path.test.ts +161 tests/clients/client-runtime-restart.test.ts +109 tests/clients/client-runtime.test.ts +92 tests/clients/cline-client.test.ts +459 tests/clients/cline-writer.test.ts +208 tests/clients/command-code-client-contract.test.ts +117 tests/clients/command-code-client.test.ts +103 tests/clients/desktop-3p-guard.test.ts +1213 tests/clients/desktop-3p-removal.test.ts +1005 tests/clients/desktop-3p-write-files.test.ts +337 tests/clients/desktop-3p.test.ts +54 tests/clients/desktop-app-restart-posix.test.ts +127 tests/clients/desktop-app-restart.test.ts +152 tests/clients/desktop-app-server-exec-boundary.test.ts +4145 tests/clients/desktop-app-server-shim-launcher.test.ts +69 tests/clients/desktop-app-server-shim.test.ts +16075 tests/clients/desktop-bundle-trust-async.test.ts +66 tests/clients/desktop-chatgpt-config.test.ts +50 tests/clients/desktop-cli-command-surface.test.ts +114 tests/clients/desktop-cli-contracts.test.ts 97 tests/clients/desktop-compatibility-authority.test.ts -35 tests/clients/desktop-compatibility-build-probe.test.ts +50 tests/clients/desktop-compatibility-build-probe.test.ts 54 tests/clients/desktop-compatibility-certificate-service.test.ts -91 tests/clients/desktop-compatibility-connection-store.test.ts -43 tests/clients/desktop-compatibility-launch.test.ts -80 tests/clients/desktop-compatibility-native-identity.test.ts -162 tests/clients/desktop-compatibility-relay.test.ts -50 tests/clients/desktop-compatibility-routing.test.ts -238 tests/clients/desktop-compatibility-runtime.test.ts -40 tests/clients/desktop-compatibility-trust.test.ts -39 tests/clients/desktop-exit-ownership.test.ts +90 tests/clients/desktop-compatibility-connection-store.test.ts +63 tests/clients/desktop-compatibility-launch.test.ts +97 tests/clients/desktop-compatibility-native-identity.test.ts +172 tests/clients/desktop-compatibility-relay.test.ts +61 tests/clients/desktop-compatibility-routing.test.ts +325 tests/clients/desktop-compatibility-runtime.test.ts +52 tests/clients/desktop-compatibility-trust.test.ts +84 tests/clients/desktop-exit-ownership.test.ts 81 tests/clients/desktop-host-visibility.test.ts -43 tests/clients/desktop-install-identity.test.ts -432 tests/clients/desktop-profile.test.ts -74 tests/clients/desktop-proxy-direct-transport.test.ts +39 tests/clients/desktop-install-identity.test.ts +416 tests/clients/desktop-profile.test.ts +47 tests/clients/desktop-proxy-direct-transport.test.ts 583 tests/clients/desktop-remote-store.test.ts -47 tests/clients/desktop-restart-handoff.test.ts -40 tests/clients/desktop-runtime-identity.test.ts -56 tests/clients/desktop-start-at-login-default.test.ts -50 tests/clients/desktop-startup-surface.test.ts -497 tests/clients/desktop-supervised-restart.test.ts -92 tests/clients/desktop-tray-availability.test.ts -51 tests/clients/desktop-update-surface.test.ts +63 tests/clients/desktop-restart-handoff.test.ts +52 tests/clients/desktop-runtime-identity.test.ts +58 tests/clients/desktop-start-at-login-default.test.ts +51 tests/clients/desktop-startup-surface.test.ts +628 tests/clients/desktop-supervised-restart.test.ts +100 tests/clients/desktop-tray-availability.test.ts +61 tests/clients/desktop-update-surface.test.ts 46 tests/clients/desktop-widget-entry.test.ts -138 tests/clients/droid-client.test.ts -185 tests/clients/droid-managed-reasoning-defaults.test.ts -112 tests/clients/droid-normalized-reasoning-defaults.test.ts -169 tests/clients/gentle-shell-client.test.ts -167 tests/clients/gentle-shell-path.test.ts -210 tests/clients/hermes-catalog-refresh.test.ts -334 tests/clients/hermes-profile-routes.test.ts -109 tests/clients/hermes-profiles.test.ts -178 tests/clients/integrations-current-store.test.ts -297 tests/clients/integrations-dsh-profile-patch.test.ts -151 tests/clients/integrations-hermes-affinity.test.ts -152 tests/clients/integrations-journal.test.ts -244 tests/clients/integrations-merge.test.ts -277 tests/clients/integrations-model-names.test.ts -68 tests/clients/integrations-serialize.test.ts -196 tests/clients/integrations-state.test.ts -142 tests/clients/integrations-superseded-store.test.ts -194 tests/clients/integrations-writer-frozen-config.test.ts -154 tests/clients/integrations-writer-guard.test.ts -392 tests/clients/integrations-writer.test.ts -189 tests/clients/kilo-client.test.ts -52 tests/clients/lazycodex-detection.test.ts -36 tests/clients/link-admission-wait.test.ts -66 tests/clients/link-apply-record.test.ts -85 tests/clients/link-boundary.test.ts -45 tests/clients/link-codex-settings-digest.test.ts -87 tests/clients/link-compensation.test.ts -111 tests/clients/link-connection-generation.test.ts -128 tests/clients/link-diagnostics.test.ts -50 tests/clients/link-fingerprint.test.ts -65 tests/clients/link-home-settings.test.ts -51 tests/clients/link-parity-reporter.test.ts -123 tests/clients/link-peer-compatibility.test.ts -122 tests/clients/link-ports.test.ts -171 tests/clients/link-readiness.test.ts -400 tests/clients/link-relay-bound-transport.test.ts -122 tests/clients/link-routes.test.ts -372 tests/clients/link-ssh-argv-discovery.test.ts -673 tests/clients/link-ssh-argv.test.ts -49 tests/clients/link-ssh-config.test.ts -514 tests/clients/link-ssh-runner.test.ts -47 tests/clients/link-status-projection.test.ts -53 tests/clients/link-store.test.ts -1599 tests/clients/link-supervisor.test.ts -153 tests/clients/link-tunnel-history.test.ts -54 tests/clients/link-tunnel-state.test.ts -211 tests/clients/mutation-plan.test.ts -124 tests/clients/omo-client.test.ts -108 tests/clients/omo-role-models.test.ts -81 tests/clients/omp-path-contract.test.ts -69 tests/clients/omp-yaml-source-inline-comments.test.ts -191 tests/clients/opencode-kilo-refresh.test.ts -110 tests/clients/pi-path-contract.test.ts -106 tests/clients/prime-client.test.ts -232 tests/clients/qoder-client.test.ts -207 tests/clients/raycast-client.test.ts -42 tests/clients/raycast-detect.test.ts -6868 tests/clients/remote-catalog.test.ts -52 tests/clients/remote-control-prototype.test.ts -124 tests/clients/remote-workspace-activation.test.ts -64 tests/clients/remote-workspace-agent-wire.test.ts -108 tests/clients/remote-workspace-app-server.integration.test.ts -42 tests/clients/remote-workspace-claude.integration.test.ts -361 tests/clients/remote-workspace-cli-runtimes.test.ts -79 tests/clients/remote-workspace-cli.test.ts -4642 tests/clients/remote-workspace-codex-runtime.test.ts -94 tests/clients/remote-workspace-command-runner.test.ts -47 tests/clients/remote-workspace-device.test.ts -57 tests/clients/remote-workspace-hub.test.ts -42 tests/clients/remote-workspace-linux-confinement.test.ts -129 tests/clients/remote-workspace-management.test.ts -55 tests/clients/remote-workspace-platform.test.ts -51 tests/clients/remote-workspace-protocol.test.ts -44 tests/clients/remote-workspace-rpc-framing.test.ts -86 tests/clients/remote-workspace-secret-store.test.ts -702 tests/clients/remote-workspace-server.test.ts -52 tests/clients/remote-workspace-session-binding.test.ts -108 tests/clients/remote-workspace-sessions.test.ts -91 tests/clients/remote-workspace-tool-bridge.test.ts -280 tests/clients/remote-workspace.test.ts -545 tests/clients/sync-client-integrations-unattended.test.ts -282 tests/clients/sync-client-integrations.test.ts -186 tests/clients/t3code-client-lifecycle.test.ts -308 tests/clients/t3code-client.test.ts -191 tests/clients/workbuddy-selector-recovery.test.ts -631 tests/codex-integration/active-registry-admission.test.ts -1173 tests/codex-integration/active-turn-disconnect.test.ts -144 tests/codex-integration/anthropic2-catalog.test.ts -156 tests/codex-integration/app-owned-memory.test.ts -4094 tests/codex-integration/bearer-admission-routed-provider.test.ts -4161 tests/codex-integration/catalog-async-lifetime.test.ts -295 tests/codex-integration/catalog-auto-refresh-client-fanout.test.ts -940 tests/codex-integration/catalog-auto-refresh-scheduler.test.ts -71 tests/codex-integration/catalog-auto-review-override.test.ts -2305 tests/codex-integration/catalog-auto-review-row.test.ts -111 tests/codex-integration/catalog-context-window-ladder.test.ts -115 tests/codex-integration/catalog-cursor-search.test.ts -126 tests/codex-integration/catalog-custom-ordering.test.ts -165 tests/codex-integration/catalog-duplicate-slug-dedup.test.ts -118 tests/codex-integration/catalog-free-pricing-status.test.ts -4796 tests/codex-integration/catalog-full-picker-order.test.ts -81 tests/codex-integration/catalog-gated-native-suppression-reason.test.ts -94 tests/codex-integration/catalog-go-exact-efforts.test.ts -153 tests/codex-integration/catalog-hub-context-window.test.ts -123 tests/codex-integration/catalog-input-modality-enum.test.ts -81 tests/codex-integration/catalog-llamacpp-capabilities.test.ts -529 tests/codex-integration/catalog-modelalias-unique-sync.test.ts -102 tests/codex-integration/catalog-native-max-context.test.ts -152 tests/codex-integration/catalog-oauth-observation.test.ts -141 tests/codex-integration/catalog-opencode-go-context-window.test.ts -123 tests/codex-integration/catalog-opencode-go-static.test.ts -99 tests/codex-integration/catalog-opengateway-hints.test.ts -985 tests/codex-integration/catalog-remote-pull.test.ts -118 tests/codex-integration/catalog-retain-models.test.ts -113 tests/codex-integration/catalog-routed-comp-hash.test.ts -87 tests/codex-integration/catalog-seed-window-fill.test.ts -124 tests/codex-integration/catalog-slug-uniqueness-boundary.test.ts -112 tests/codex-integration/catalog-verbosity-default.test.ts -143 tests/codex-integration/catalog-vision-sidecar-disabled.test.ts -116 tests/codex-integration/catalog-vision-sidecar-modalities.test.ts -88 tests/codex-integration/catalog-zero-credit-picker.test.ts -4610 tests/codex-integration/client-injection-guard.test.ts -271 tests/codex-integration/code-mode-collab-surface.test.ts -117 tests/codex-integration/codex-account-clear-paused.test.ts -203 tests/codex-integration/codex-account-delete-atomicity.test.ts -39 tests/codex-integration/codex-account-label.test.ts -51 tests/codex-integration/codex-account-namespaces.test.ts -351 tests/codex-integration/codex-account-selection-atomicity.test.ts -149 tests/codex-integration/codex-account-selection-preferences.test.ts -219 tests/codex-integration/codex-account-slot-identity.test.ts -129 tests/codex-integration/codex-account-store-quota-isolation.test.ts -231 tests/codex-integration/codex-account-store-refresh-classification.test.ts -977 tests/codex-integration/codex-account-store.test.ts -487 tests/codex-integration/codex-account-threshold-api.test.ts -204 tests/codex-integration/codex-account-threshold-auth.test.ts -149 tests/codex-integration/codex-account-threshold-routing.test.ts -132 tests/codex-integration/codex-account-unusable-reason.test.ts -140 tests/codex-integration/codex-admission-primitives.test.ts +166 tests/clients/droid-client.test.ts +217 tests/clients/droid-managed-reasoning-defaults.test.ts +145 tests/clients/droid-normalized-reasoning-defaults.test.ts +158 tests/clients/gentle-shell-client.test.ts +166 tests/clients/gentle-shell-path.test.ts +288 tests/clients/hermes-catalog-refresh.test.ts +459 tests/clients/hermes-profile-routes.test.ts +126 tests/clients/hermes-profiles.test.ts +237 tests/clients/integrations-current-store.test.ts +284 tests/clients/integrations-dsh-profile-patch.test.ts +193 tests/clients/integrations-hermes-affinity.test.ts +147 tests/clients/integrations-journal.test.ts +146 tests/clients/integrations-merge.test.ts +333 tests/clients/integrations-model-names.test.ts +74 tests/clients/integrations-serialize.test.ts +134 tests/clients/integrations-state.test.ts +105 tests/clients/integrations-superseded-store.test.ts +252 tests/clients/integrations-writer-frozen-config.test.ts +150 tests/clients/integrations-writer-guard.test.ts +617 tests/clients/integrations-writer.test.ts +165 tests/clients/kilo-client.test.ts +43 tests/clients/lazycodex-detection.test.ts +51 tests/clients/link-admission-wait.test.ts +65 tests/clients/link-apply-record.test.ts +46 tests/clients/link-boundary.test.ts +49 tests/clients/link-codex-settings-digest.test.ts +76 tests/clients/link-compensation.test.ts +113 tests/clients/link-connection-generation.test.ts +165 tests/clients/link-diagnostics.test.ts +38 tests/clients/link-fingerprint.test.ts +68 tests/clients/link-home-settings.test.ts +61 tests/clients/link-parity-reporter.test.ts +113 tests/clients/link-peer-compatibility.test.ts +110 tests/clients/link-ports.test.ts +212 tests/clients/link-readiness.test.ts +393 tests/clients/link-relay-bound-transport.test.ts +91 tests/clients/link-routes.test.ts +719 tests/clients/link-ssh-argv-discovery.test.ts +704 tests/clients/link-ssh-argv.test.ts +75 tests/clients/link-ssh-config.test.ts +519 tests/clients/link-ssh-runner.test.ts +52 tests/clients/link-status-projection.test.ts +93 tests/clients/link-store.test.ts +1623 tests/clients/link-supervisor.test.ts +263 tests/clients/link-tunnel-history.test.ts +31 tests/clients/link-tunnel-state.test.ts +180 tests/clients/mutation-plan.test.ts +168 tests/clients/omo-client.test.ts +713 tests/clients/omo-responses-loop.test.ts +103 tests/clients/omo-role-models.test.ts +136 tests/clients/omp-path-contract.test.ts +83 tests/clients/omp-yaml-source-inline-comments.test.ts +277 tests/clients/opencode-kilo-refresh.test.ts +81 tests/clients/pi-path-contract.test.ts +203 tests/clients/prime-client.test.ts +366 tests/clients/qoder-client.test.ts +168 tests/clients/raycast-client.test.ts +45 tests/clients/raycast-detect.test.ts +6874 tests/clients/remote-catalog.test.ts +58 tests/clients/remote-control-prototype.test.ts +258 tests/clients/remote-workspace-activation.test.ts +69 tests/clients/remote-workspace-agent-wire.test.ts +60 tests/clients/remote-workspace-app-server.integration.test.ts +47 tests/clients/remote-workspace-claude.integration.test.ts +452 tests/clients/remote-workspace-cli-runtimes.test.ts +77 tests/clients/remote-workspace-cli.test.ts +6934 tests/clients/remote-workspace-codex-runtime.test.ts +74 tests/clients/remote-workspace-command-runner.test.ts +43 tests/clients/remote-workspace-device.test.ts +64 tests/clients/remote-workspace-hub.test.ts +40 tests/clients/remote-workspace-linux-confinement.test.ts +265 tests/clients/remote-workspace-management.test.ts +48 tests/clients/remote-workspace-platform.test.ts +37 tests/clients/remote-workspace-protocol.test.ts +41 tests/clients/remote-workspace-rpc-framing.test.ts +54 tests/clients/remote-workspace-secret-store.test.ts +810 tests/clients/remote-workspace-server.test.ts +140 tests/clients/remote-workspace-session-binding.test.ts +136 tests/clients/remote-workspace-sessions.test.ts +60 tests/clients/remote-workspace-tool-bridge.test.ts +402 tests/clients/remote-workspace.test.ts +621 tests/clients/sync-client-integrations-unattended.test.ts +340 tests/clients/sync-client-integrations.test.ts +168 tests/clients/t3code-client-lifecycle.test.ts +260 tests/clients/t3code-client.test.ts +242 tests/clients/workbuddy-selector-recovery.test.ts +845 tests/codex-integration/active-registry-admission.test.ts +1815 tests/codex-integration/active-turn-disconnect.test.ts +152 tests/codex-integration/anthropic2-catalog.test.ts +155 tests/codex-integration/app-owned-memory.test.ts +4166 tests/codex-integration/bearer-admission-routed-provider.test.ts +4174 tests/codex-integration/catalog-async-lifetime.test.ts +345 tests/codex-integration/catalog-auto-refresh-client-fanout.test.ts +1259 tests/codex-integration/catalog-auto-refresh-scheduler.test.ts +110 tests/codex-integration/catalog-auto-review-override.test.ts +2748 tests/codex-integration/catalog-auto-review-row.test.ts +98 tests/codex-integration/catalog-context-window-ladder.test.ts +84 tests/codex-integration/catalog-cursor-search.test.ts +117 tests/codex-integration/catalog-custom-ordering.test.ts +116 tests/codex-integration/catalog-duplicate-slug-dedup.test.ts +112 tests/codex-integration/catalog-free-pricing-status.test.ts +5128 tests/codex-integration/catalog-full-picker-order.test.ts +109 tests/codex-integration/catalog-gated-native-suppression-reason.test.ts +123 tests/codex-integration/catalog-go-exact-efforts.test.ts +159 tests/codex-integration/catalog-hub-context-window.test.ts +119 tests/codex-integration/catalog-input-modality-enum.test.ts +103 tests/codex-integration/catalog-llamacpp-capabilities.test.ts +795 tests/codex-integration/catalog-modelalias-unique-sync.test.ts +85 tests/codex-integration/catalog-native-max-context.test.ts +143 tests/codex-integration/catalog-oauth-observation.test.ts +4195 tests/codex-integration/catalog-omit-disabled-native.test.ts +130 tests/codex-integration/catalog-opencode-go-context-window.test.ts +241 tests/codex-integration/catalog-opencode-go-static.test.ts +81 tests/codex-integration/catalog-opengateway-hints.test.ts +1520 tests/codex-integration/catalog-remote-pull.test.ts +196 tests/codex-integration/catalog-retain-models.test.ts +119 tests/codex-integration/catalog-routed-comp-hash.test.ts +126 tests/codex-integration/catalog-seed-window-fill.test.ts +119 tests/codex-integration/catalog-slug-uniqueness-boundary.test.ts +138 tests/codex-integration/catalog-verbosity-default.test.ts +280 tests/codex-integration/catalog-vision-sidecar-disabled.test.ts +131 tests/codex-integration/catalog-vision-sidecar-modalities.test.ts +84 tests/codex-integration/catalog-zero-credit-picker.test.ts +4581 tests/codex-integration/client-injection-guard.test.ts +265 tests/codex-integration/code-mode-collab-surface.test.ts +101 tests/codex-integration/codex-account-clear-paused.test.ts +342 tests/codex-integration/codex-account-delete-atomicity.test.ts +30 tests/codex-integration/codex-account-label.test.ts +42 tests/codex-integration/codex-account-namespaces.test.ts +352 tests/codex-integration/codex-account-selection-atomicity.test.ts +135 tests/codex-integration/codex-account-selection-preferences.test.ts +189 tests/codex-integration/codex-account-slot-identity.test.ts +122 tests/codex-integration/codex-account-store-quota-isolation.test.ts +300 tests/codex-integration/codex-account-store-refresh-classification.test.ts +893 tests/codex-integration/codex-account-store.test.ts +642 tests/codex-integration/codex-account-threshold-api.test.ts +237 tests/codex-integration/codex-account-threshold-auth.test.ts +175 tests/codex-integration/codex-account-threshold-routing.test.ts +156 tests/codex-integration/codex-account-unusable-reason.test.ts +187 tests/codex-integration/codex-admission-primitives.test.ts 132 tests/codex-integration/codex-admission.test.ts -94 tests/codex-integration/codex-affinity-debug.test.ts -313 tests/codex-integration/codex-agent-thread-limit.test.ts -71 tests/codex-integration/codex-app-server-path-spaces.test.ts -1051 tests/codex-integration/codex-app-server-processes.test.ts -125 tests/codex-integration/codex-app-server-restart-service.test.ts -2140 tests/codex-integration/codex-auth-api.test.ts -83 tests/codex-integration/codex-auth-cancel-ownership.test.ts -137 tests/codex-integration/codex-auth-collision.test.ts -779 tests/codex-integration/codex-auth-context.test.ts -210 tests/codex-integration/codex-auth-headless-accounts.test.ts -222 tests/codex-integration/codex-auth-release.test.ts -100 tests/codex-integration/codex-catalog-admission.test.ts -106 tests/codex-integration/codex-catalog-exclusions.test.ts -86 tests/codex-integration/codex-catalog-golden.test.ts -356 tests/codex-integration/codex-catalog-heal-integration.test.ts -154 tests/codex-integration/codex-catalog-heal-reanchor.test.ts -116 tests/codex-integration/codex-catalog-identity-neutral.test.ts -160 tests/codex-integration/codex-catalog-intent.test.ts -115 tests/codex-integration/codex-catalog-ladders.test.ts -108 tests/codex-integration/codex-catalog-model-picker-order.test.ts -43 tests/codex-integration/codex-catalog-refresh-status.test.ts -1103 tests/codex-integration/codex-catalog-restore.test.ts -94 tests/codex-integration/codex-catalog-routed-removal.test.ts -196 tests/codex-integration/codex-catalog-self-heal.test.ts -25536 tests/codex-integration/codex-catalog-sync-hardening.test.ts -472 tests/codex-integration/codex-catalog-write-audit.test.ts -71 tests/codex-integration/codex-catalog-write-serialization.test.ts -243 tests/codex-integration/codex-catalog-writer.test.ts -1582 tests/codex-integration/codex-catalog.test.ts -124 tests/codex-integration/codex-clamp-notice.test.ts -336 tests/codex-integration/codex-cli-install-provenance.test.ts -43 tests/codex-integration/codex-cli-installation-identity.test.ts -43 tests/codex-integration/codex-cli-installation-targets.test.ts -5224 tests/codex-integration/codex-cli-update-admission.test.ts -101871 tests/codex-integration/codex-cli-update-apply.test.ts -2829 tests/codex-integration/codex-cli-update-artifacts.test.ts -49 tests/codex-integration/codex-cli-update-integrity.test.ts -52 tests/codex-integration/codex-cli-update-launcher-policy.test.ts -49 tests/codex-integration/codex-cli-update-paths.test.ts -1854 tests/codex-integration/codex-cli-update-plan.test.ts -2740 tests/codex-integration/codex-cli-update-recovery.test.ts -46 tests/codex-integration/codex-cli-update-windows-apply-install.test.ts -44 tests/codex-integration/codex-cli-update-windows-apply-outcomes.test.ts -46 tests/codex-integration/codex-cli-update-windows-apply-shared.test.ts -54 tests/codex-integration/codex-cli-update-windows-apply.test.ts -150 tests/codex-integration/codex-cli-update-windows-layout.test.ts -39 tests/codex-integration/codex-cli-update-windows-pending.test.ts -393 tests/codex-integration/codex-cli-update-windows-recovery.test.ts -41 tests/codex-integration/codex-cli-update-windows-review.test.ts -405 tests/codex-integration/codex-cli-update-worker.test.ts -1064 tests/codex-integration/codex-cli-update-zero-effect.test.ts -41 tests/codex-integration/codex-cli-windows-child.test.ts -46 tests/codex-integration/codex-cli-windows-installation-files.test.ts -91 tests/codex-integration/codex-cli-windows-plan.test.ts -17721 tests/codex-integration/codex-composed-acceptance.test.ts -1928 tests/codex-integration/codex-config-drift-heal.test.ts -277 tests/codex-integration/codex-config-generation.test.ts -2173 tests/codex-integration/codex-config-preservation.test.ts -5454 tests/codex-integration/codex-config-write-lock.test.ts -144 tests/codex-integration/codex-context-owner.test.ts -3802 tests/codex-integration/codex-convergence-account-selectors.test.ts -833 tests/codex-integration/codex-convergence-contract.test.ts -229 tests/codex-integration/codex-cooldown-recovery.test.ts -121 tests/codex-integration/codex-coordinator-doctor.test.ts -646 tests/codex-integration/codex-credit-retry-after.test.ts -353 tests/codex-integration/codex-credit-scoped-retry.test.ts -175 tests/codex-integration/codex-credits-after-limit-main.test.ts -218 tests/codex-integration/codex-credits-after-limit.test.ts -127 tests/codex-integration/codex-credits-probes.test.ts -236 tests/codex-integration/codex-credits-settings.test.ts -50 tests/codex-integration/codex-credits.test.ts -177 tests/codex-integration/codex-desired-state.test.ts -348 tests/codex-integration/codex-direct-credit-renewal.test.ts -232 tests/codex-integration/codex-direct-renewal-revocation.test.ts -126 tests/codex-integration/codex-entitlement-identity-read-fence.test.ts -521 tests/codex-integration/codex-envkey-admission-substitution.test.ts -92 tests/codex-integration/codex-exec-invocation.test.ts -503 tests/codex-integration/codex-failure-window.test.ts -65 tests/codex-integration/codex-features-cache.test.ts -39 tests/codex-integration/codex-features-residual.test.ts -93 tests/codex-integration/codex-filesystem-evidence.test.ts -89 tests/codex-integration/codex-forward-access-programs-writer.test.ts -376 tests/codex-integration/codex-gather-authority.test.ts -2126 tests/codex-integration/codex-history-job.test.ts -141 tests/codex-integration/codex-history-lock.test.ts -76 tests/codex-integration/codex-history-pending-wal.test.ts -2240 tests/codex-integration/codex-history-provider.test.ts -415 tests/codex-integration/codex-history-reachability.test.ts -47 tests/codex-integration/codex-history-worker-boundary.test.ts -1969 tests/codex-integration/codex-history-worker.test.ts -101 tests/codex-integration/codex-history-writer.test.ts -9214 tests/codex-integration/codex-home-owner-lifecycle.test.ts -1105 tests/codex-integration/codex-home-owner.test.ts -39 tests/codex-integration/codex-home-wsl-local-state.test.ts -110 tests/codex-integration/codex-home-wsl.test.ts -163 tests/codex-integration/codex-idle-window.test.ts -164 tests/codex-integration/codex-inject-history-wording.test.ts -62887 tests/codex-integration/codex-inject-integration.test.ts -2136 tests/codex-integration/codex-inject-missing-config.test.ts -817 tests/codex-integration/codex-inject-retained-table.test.ts -7266 tests/codex-integration/codex-inject-v1-reconcile.test.ts -8649 tests/codex-integration/codex-inject-write-lock.test.ts -135 tests/codex-integration/codex-inject.test.ts -48 tests/codex-integration/codex-injected-marker.test.ts -90 tests/codex-integration/codex-integration-record.test.ts -2877 tests/codex-integration/codex-journal-recovery.test.ts -15334 tests/codex-integration/codex-journal.test.ts -164 tests/codex-integration/codex-launcher-admission.test.ts -84 tests/codex-integration/codex-launcher-darwin-acl.test.ts -50 tests/codex-integration/codex-launcher-darwin-identity.test.ts -166 tests/codex-integration/codex-launcher-diagnostics.test.ts -275 tests/codex-integration/codex-launcher-env.test.ts -2401 tests/codex-integration/codex-launcher-process.test.ts -184 tests/codex-integration/codex-launcher-security.test.ts -108 tests/codex-integration/codex-launcher.test.ts -53 tests/codex-integration/codex-legacy-config-keys.test.ts -207 tests/codex-integration/codex-lineage-placement.test.ts -326 tests/codex-integration/codex-linked-account-pause.test.ts -86 tests/codex-integration/codex-log-guard-coderabbit.test.ts -42 tests/codex-integration/codex-log-guard-doctor-coderabbit.test.ts -42 tests/codex-integration/codex-log-guard-doctor-protection.test.ts -41 tests/codex-integration/codex-log-guard-doctor.test.ts -195 tests/codex-integration/codex-log-guard-inspect.test.ts -43 tests/codex-integration/codex-log-guard-lock.test.ts -312 tests/codex-integration/codex-log-guard-maintenance-coderabbit.test.ts -558 tests/codex-integration/codex-log-guard-maintenance.test.ts -44 tests/codex-integration/codex-log-guard-policy.test.ts -42 tests/codex-integration/codex-log-guard-processes.test.ts -156 tests/codex-integration/codex-log-guard-protection.test.ts -79 tests/codex-integration/codex-log-guard-status-zero-write.test.ts -137 tests/codex-integration/codex-main-account-refresh.test.ts -395 tests/codex-integration/codex-main-grant-refusal.test.ts -231 tests/codex-integration/codex-main-rotation.test.ts -144 tests/codex-integration/codex-main-token-invalidated.test.ts -120 tests/codex-integration/codex-management-convergence.test.ts -103 tests/codex-integration/codex-metadata-integrity.test.ts -7730 tests/codex-integration/codex-missing-home.test.ts -86 tests/codex-integration/codex-model-availability-error.test.ts -264 tests/codex-integration/codex-model-denial-evidence.test.ts -72 tests/codex-integration/codex-model-entitlement-admission.test.ts -75 tests/codex-integration/codex-model-entitlements-program-shape.test.ts -201 tests/codex-integration/codex-model-entitlements.test.ts -153 tests/codex-integration/codex-models-cache-invalidate.test.ts -933 tests/codex-integration/codex-native-availability-nux.test.ts -633 tests/codex-integration/codex-native-residue.test.ts -164 tests/codex-integration/codex-pin-drain-projection.test.ts -104 tests/codex-integration/codex-plan.test.ts -419 tests/codex-integration/codex-plugins-doctor.test.ts -121 tests/codex-integration/codex-pool-caller-fallback-policy.test.ts -192 tests/codex-integration/codex-pool-credit-policy.test.ts -127 tests/codex-integration/codex-pool-plan-exclusion.test.ts -91 tests/codex-integration/codex-pool-refresh-backoff.test.ts -152 tests/codex-integration/codex-pool-request-owned-main.test.ts -567 tests/codex-integration/codex-pool-rotation.test.ts -320 tests/codex-integration/codex-preserve-signed-in.test.ts -276 tests/codex-integration/codex-priority-failback.test.ts -44 tests/codex-integration/codex-proc-scan-errors.test.ts -91 tests/codex-integration/codex-prompt-adopt.test.ts -356 tests/codex-integration/codex-prompt-base-variants.test.ts -88 tests/codex-integration/codex-prompt-journal.test.ts -59 tests/codex-integration/codex-prompt-layers-read.test.ts -189 tests/codex-integration/codex-prompt-layers-write.test.ts -45 tests/codex-integration/codex-prompt-layers.test.ts -385 tests/codex-integration/codex-prompt-lock-sharing.test.ts -436 tests/codex-integration/codex-prompt-lock.test.ts -1181 tests/codex-integration/codex-prompt-route.test.ts -180 tests/codex-integration/codex-prompt-scalar-scope.test.ts -891 tests/codex-integration/codex-prompt-text-probe.test.ts -433 tests/codex-integration/codex-prompt-writes.test.ts -15457 tests/codex-integration/codex-provider-routing.test.ts -752 tests/codex-integration/codex-provider-table-retention.test.ts -119 tests/codex-integration/codex-quota-auto-refresh-generation.test.ts -191 tests/codex-integration/codex-quota-auto-refresh-main-admission.test.ts -403 tests/codex-integration/codex-quota-auto-refresh.test.ts -54 tests/codex-integration/codex-quota-capacity.test.ts -155 tests/codex-integration/codex-quota-history.test.ts -155 tests/codex-integration/codex-quota-parser-parity.test.ts -48 tests/codex-integration/codex-quota-persistence.test.ts -383 tests/codex-integration/codex-quota-prime.test.ts -95 tests/codex-integration/codex-quota-query-backoff.test.ts -257 tests/codex-integration/codex-quota-rejection.test.ts -124 tests/codex-integration/codex-refresh.test.ts -1072 tests/codex-integration/codex-reset-credit-auto-redeem.test.ts -394 tests/codex-integration/codex-reset-credit-operation-ledger.test.ts -365 tests/codex-integration/codex-reset-credit-recovery.test.ts -72 tests/codex-integration/codex-restart-contract-parity.test.ts -346 tests/codex-integration/codex-restart-route.test.ts -4457 tests/codex-integration/codex-restore-app-rewrite.test.ts -6966 tests/codex-integration/codex-retained-root-serialization.test.ts -136 tests/codex-integration/codex-routing-cache-affinity-detour.test.ts -3473 tests/codex-integration/codex-routing.test.ts -173 tests/codex-integration/codex-runtime-macos-desktop.test.ts -82 tests/codex-integration/codex-runtime-wsl-desktop.test.ts -163 tests/codex-integration/codex-runtime.test.ts -369 tests/codex-integration/codex-service-manager-probe-hardening.test.ts -224 tests/codex-integration/codex-service-manager-probe.test.ts -20487 tests/codex-integration/codex-shim-autorestore.test.ts -87 tests/codex-integration/codex-shim-bypass-token.test.ts -197 tests/codex-integration/codex-shim-destroyed-probe.test.ts -87 tests/codex-integration/codex-shim-ensure-failure.test.ts -123 tests/codex-integration/codex-shim-fnm.test.ts -446 tests/codex-integration/codex-shim-migration.test.ts -88 tests/codex-integration/codex-shim-overlay-candidates.test.ts -611 tests/codex-integration/codex-shim-overlay-readiness.test.ts -1940 tests/codex-integration/codex-shim-overlay-transaction.test.ts -713 tests/codex-integration/codex-shim-overlay.test.ts -2869 tests/codex-integration/codex-shim-path-readiness.test.ts -28079 tests/codex-integration/codex-shim-readiness.test.ts -53 tests/codex-integration/codex-shim-runtime-preflight.test.ts -681 tests/codex-integration/codex-shim-standalone.test.ts -187 tests/codex-integration/codex-shim-windows-revision.test.ts -25230 tests/codex-integration/codex-shim.test.ts -1697 tests/codex-integration/codex-sidecar-credit-policy.test.ts -113 tests/codex-integration/codex-signin-lockout.test.ts -178 tests/codex-integration/codex-spark-visibility.test.ts -69 tests/codex-integration/codex-sqlite-home.test.ts -384 tests/codex-integration/codex-stored-main-duplicate.test.ts -1496 tests/codex-integration/codex-sync-api.test.ts -319 tests/codex-integration/codex-sync-new-model-policy.test.ts -43 tests/codex-integration/codex-sync-response.test.ts -19595 tests/codex-integration/codex-sync-user-edits.test.ts -156 tests/codex-integration/codex-systemd-env-probe.test.ts -96 tests/codex-integration/codex-tool-mode.test.ts -600 tests/codex-integration/codex-transition-state-adoption.test.ts -152 tests/codex-integration/codex-transition-state-first-use-regression.test.ts -1561 tests/codex-integration/codex-transition-state-race.test.ts -207 tests/codex-integration/codex-transition-state.test.ts -182 tests/codex-integration/codex-use-remaining-quota.test.ts -77 tests/codex-integration/codex-user-identity.test.ts -762 tests/codex-integration/codex-v2-gate.test.ts -345 tests/codex-integration/codex-warmup.test.ts -3125 tests/codex-integration/codex-web-search-switch.test.ts -47 tests/codex-integration/codex-websocket-registry.test.ts -49 tests/codex-integration/codex-windows-current-sid.test.ts -2794 tests/codex-integration/codex-write-lock.test.ts -46 tests/codex-integration/combo-authoritative-reset.test.ts -54 tests/codex-integration/combo-codex-exhaustion-cooldown.test.ts -88 tests/codex-integration/combo-cooldown-reprobe.test.ts -635 tests/codex-integration/combo-description-catalog.test.ts -55 tests/codex-integration/combo-last-resort.test.ts -44 tests/codex-integration/combo-permanent-failure-cooldown.test.ts -54 tests/codex-integration/combo-reset-window-model-scope.test.ts -45 tests/codex-integration/combos-kiro-profile-hop.test.ts -257 tests/codex-integration/combos.test.ts -698 tests/codex-integration/compatibility-manifest.test.ts -120 tests/codex-integration/configured-native-models.test.ts -1640 tests/codex-integration/configured-ultrafast-picker.test.ts -54 tests/codex-integration/context-compat.test.ts -43 tests/codex-integration/custom-model-catalog-migration.test.ts -212 tests/codex-integration/deferred-collab-surface.test.ts -149 tests/codex-integration/discovered-native-models.test.ts -443 tests/codex-integration/doctor.test.ts -465 tests/codex-integration/effort-policy.test.ts -357 tests/codex-integration/exec-boundary-launch.test.ts -113 tests/codex-integration/exec-known-app-bundles.test.ts -679 tests/codex-integration/exec-trust-boundary.test.ts -138 tests/codex-integration/fast-row-listing.test.ts -94 tests/codex-integration/fast-row.test.ts -169 tests/codex-integration/gather-routed-models-single-flight.test.ts -130 tests/codex-integration/gpt6-native-rows.test.ts -111 tests/codex-integration/gpt61-sol-rows.test.ts -143 tests/codex-integration/gpt61-terra-rows.test.ts -54 tests/codex-integration/history-migration-guardian.test.ts -99 tests/codex-integration/history-ocx-compaction-recovery.test.ts -46 tests/codex-integration/history-paginated-openai-compat.test.ts -1877 tests/codex-integration/history-paginated-transition-destinations.test.ts -157 tests/codex-integration/injection-link-websocket.test.ts -524 tests/codex-integration/injection-model-api.test.ts -235 tests/codex-integration/injection-model-suggest-routes.test.ts -52 tests/codex-integration/injection-routing-drift.test.ts -4106 tests/codex-integration/injection-routing-heal-apply.test.ts -582 tests/codex-integration/injection-routing-healer.test.ts -6099 tests/codex-integration/issue-452-empty-503.test.ts -3794 tests/codex-integration/issue-702-expired-replay-state.test.ts -656 tests/codex-integration/issue-914-transport-attribution.test.ts -171 tests/codex-integration/low-quota-desktop-notifier.test.ts -1220 tests/codex-integration/low-quota-protection.test.ts -389 tests/codex-integration/main-account-credit-renewal.test.ts -50 tests/codex-integration/main-account-external-usage.test.ts -15522 tests/codex-integration/main-account-hard-lock-auth.test.ts -247 tests/codex-integration/main-account-hard-lock-default.test.ts -814 tests/codex-integration/main-account-hard-lock-fallback-off.test.ts -453 tests/codex-integration/main-account-hard-lock-fallback-routing.test.ts -49 tests/codex-integration/main-account-hard-lock-policy.test.ts -334 tests/codex-integration/main-account-hard-lock-profile-dispatch.test.ts -526 tests/codex-integration/main-account-hard-lock-recovery.test.ts -99 tests/codex-integration/main-account-hard-lock-retirement.test.ts -125 tests/codex-integration/main-account-hard-lock-thresholds.test.ts -132 tests/codex-integration/main-account-hard-lock-usage-limit.test.ts -541 tests/codex-integration/main-account-policy-binding-wait.test.ts -72 tests/codex-integration/main-device-reauth-api.test.ts -178 tests/codex-integration/main-device-reauth.test.ts -131 tests/codex-integration/main-quota-evidence-validation.test.ts -4263 tests/codex-integration/main-quota-provenance.test.ts -488 tests/codex-integration/main-quota-window-observation.test.ts -3411 tests/codex-integration/messaging-local-cli.test.ts +179 tests/codex-integration/codex-affinity-debug.test.ts +156 tests/codex-integration/codex-affinity-lease-gap.test.ts +116 tests/codex-integration/codex-affinity-request-owned.test.ts +16522 tests/codex-integration/codex-affinity-restart-matrix.test.ts +22436 tests/codex-integration/codex-affinity-restart.test.ts +1907 tests/codex-integration/codex-affinity-store.test.ts +362 tests/codex-integration/codex-agent-thread-limit.test.ts +68 tests/codex-integration/codex-app-server-path-spaces.test.ts +1046 tests/codex-integration/codex-app-server-processes.test.ts +160 tests/codex-integration/codex-app-server-restart-service.test.ts +3196 tests/codex-integration/codex-auth-api.test.ts +95 tests/codex-integration/codex-auth-cancel-ownership.test.ts +204 tests/codex-integration/codex-auth-collision.test.ts +946 tests/codex-integration/codex-auth-context.test.ts +285 tests/codex-integration/codex-auth-headless-accounts.test.ts +231 tests/codex-integration/codex-auth-release.test.ts +113 tests/codex-integration/codex-catalog-admission.test.ts +93 tests/codex-integration/codex-catalog-exclusions.test.ts +88 tests/codex-integration/codex-catalog-golden.test.ts +374 tests/codex-integration/codex-catalog-heal-integration.test.ts +109 tests/codex-integration/codex-catalog-heal-reanchor.test.ts +94 tests/codex-integration/codex-catalog-identity-neutral.test.ts +243 tests/codex-integration/codex-catalog-intent.test.ts +128 tests/codex-integration/codex-catalog-ladders.test.ts +90 tests/codex-integration/codex-catalog-model-picker-order.test.ts +40 tests/codex-integration/codex-catalog-refresh-status.test.ts +1385 tests/codex-integration/codex-catalog-restore.test.ts +161 tests/codex-integration/codex-catalog-routed-removal.test.ts +217 tests/codex-integration/codex-catalog-self-heal.test.ts +24633 tests/codex-integration/codex-catalog-sync-hardening.test.ts +584 tests/codex-integration/codex-catalog-write-audit.test.ts +91 tests/codex-integration/codex-catalog-write-serialization.test.ts +212 tests/codex-integration/codex-catalog-writer.test.ts +1615 tests/codex-integration/codex-catalog.test.ts +177 tests/codex-integration/codex-clamp-notice.test.ts +355 tests/codex-integration/codex-cli-install-provenance.test.ts +46 tests/codex-integration/codex-cli-installation-identity.test.ts +62 tests/codex-integration/codex-cli-installation-targets.test.ts +4739 tests/codex-integration/codex-cli-update-admission.test.ts +125741 tests/codex-integration/codex-cli-update-apply.test.ts +4248 tests/codex-integration/codex-cli-update-artifacts.test.ts +66 tests/codex-integration/codex-cli-update-integrity.test.ts +64 tests/codex-integration/codex-cli-update-launcher-policy.test.ts +306 tests/codex-integration/codex-cli-update-parent-async.test.ts +81 tests/codex-integration/codex-cli-update-paths.test.ts +1809 tests/codex-integration/codex-cli-update-plan.test.ts +3386 tests/codex-integration/codex-cli-update-recovery.test.ts +69 tests/codex-integration/codex-cli-update-windows-apply-install.test.ts +62 tests/codex-integration/codex-cli-update-windows-apply-outcomes.test.ts +80 tests/codex-integration/codex-cli-update-windows-apply-shared.test.ts +53 tests/codex-integration/codex-cli-update-windows-apply.test.ts +145 tests/codex-integration/codex-cli-update-windows-layout.test.ts +37 tests/codex-integration/codex-cli-update-windows-pending.test.ts +467 tests/codex-integration/codex-cli-update-windows-recovery.test.ts +65 tests/codex-integration/codex-cli-update-windows-review.test.ts +410 tests/codex-integration/codex-cli-update-worker.test.ts +1084 tests/codex-integration/codex-cli-update-zero-effect.test.ts +50 tests/codex-integration/codex-cli-windows-child.test.ts +49 tests/codex-integration/codex-cli-windows-installation-files.test.ts +165 tests/codex-integration/codex-cli-windows-plan.test.ts +24169 tests/codex-integration/codex-composed-acceptance.test.ts +2281 tests/codex-integration/codex-config-drift-heal.test.ts +330 tests/codex-integration/codex-config-generation.test.ts +2188 tests/codex-integration/codex-config-preservation.test.ts +5927 tests/codex-integration/codex-config-write-lock.test.ts +177 tests/codex-integration/codex-context-owner.test.ts +5768 tests/codex-integration/codex-convergence-account-selectors.test.ts +991 tests/codex-integration/codex-convergence-contract.test.ts +329 tests/codex-integration/codex-cooldown-recovery.test.ts +188 tests/codex-integration/codex-coordinator-doctor.test.ts +803 tests/codex-integration/codex-credit-retry-after.test.ts +883 tests/codex-integration/codex-credit-scoped-retry.test.ts +328 tests/codex-integration/codex-credits-after-limit-main.test.ts +225 tests/codex-integration/codex-credits-after-limit.test.ts +142 tests/codex-integration/codex-credits-probes.test.ts +309 tests/codex-integration/codex-credits-settings.test.ts +62 tests/codex-integration/codex-credits.test.ts +228 tests/codex-integration/codex-desired-state.test.ts +468 tests/codex-integration/codex-direct-credit-renewal.test.ts +440 tests/codex-integration/codex-direct-renewal-revocation.test.ts +150 tests/codex-integration/codex-entitlement-identity-read-fence.test.ts +660 tests/codex-integration/codex-envkey-admission-substitution.test.ts +149 tests/codex-integration/codex-exec-invocation.test.ts +528 tests/codex-integration/codex-failure-window.test.ts +77 tests/codex-integration/codex-features-cache.test.ts +40 tests/codex-integration/codex-features-residual.test.ts +76 tests/codex-integration/codex-filesystem-evidence.test.ts +86 tests/codex-integration/codex-forward-access-programs-writer.test.ts +426 tests/codex-integration/codex-gather-authority.test.ts +2408 tests/codex-integration/codex-history-job.test.ts +124 tests/codex-integration/codex-history-lock.test.ts +73 tests/codex-integration/codex-history-pending-wal.test.ts +2524 tests/codex-integration/codex-history-provider.test.ts +733 tests/codex-integration/codex-history-reachability.test.ts +62 tests/codex-integration/codex-history-worker-boundary.test.ts +1983 tests/codex-integration/codex-history-worker.test.ts +45 tests/codex-integration/codex-history-writer.test.ts +10243 tests/codex-integration/codex-home-owner-lifecycle.test.ts +1043 tests/codex-integration/codex-home-owner.test.ts +46 tests/codex-integration/codex-home-wsl-local-state.test.ts +129 tests/codex-integration/codex-home-wsl.test.ts +258 tests/codex-integration/codex-idle-window.test.ts +140 tests/codex-integration/codex-inject-history-wording.test.ts +65182 tests/codex-integration/codex-inject-integration.test.ts +2085 tests/codex-integration/codex-inject-missing-config.test.ts +1142 tests/codex-integration/codex-inject-retained-table.test.ts +7706 tests/codex-integration/codex-inject-v1-reconcile.test.ts +9083 tests/codex-integration/codex-inject-write-lock.test.ts +172 tests/codex-integration/codex-inject.test.ts +58 tests/codex-integration/codex-injected-marker.test.ts +64 tests/codex-integration/codex-installation-acl.test.ts +99 tests/codex-integration/codex-installation-id.test.ts +528 tests/codex-integration/codex-installation-invalid-account.test.ts +1099 tests/codex-integration/codex-installation-live-content.test.ts +562 tests/codex-integration/codex-installation-live-http.test.ts +874 tests/codex-integration/codex-installation-live-ws.test.ts +438 tests/codex-integration/codex-installation-sidecars.test.ts +127 tests/codex-integration/codex-installation-wire.test.ts +109 tests/codex-integration/codex-integration-record.test.ts +3779 tests/codex-integration/codex-journal-recovery.test.ts +15866 tests/codex-integration/codex-journal.test.ts +240 tests/codex-integration/codex-launcher-admission.test.ts +122 tests/codex-integration/codex-launcher-darwin-acl.test.ts +49 tests/codex-integration/codex-launcher-darwin-identity.test.ts +215 tests/codex-integration/codex-launcher-diagnostics.test.ts +229 tests/codex-integration/codex-launcher-env.test.ts +2914 tests/codex-integration/codex-launcher-process.test.ts +163 tests/codex-integration/codex-launcher-security.test.ts +153 tests/codex-integration/codex-launcher.test.ts +56 tests/codex-integration/codex-legacy-config-keys.test.ts +237 tests/codex-integration/codex-lineage-placement.test.ts +372 tests/codex-integration/codex-linked-account-pause.test.ts +82 tests/codex-integration/codex-log-guard-coderabbit.test.ts +76 tests/codex-integration/codex-log-guard-doctor-coderabbit.test.ts +43 tests/codex-integration/codex-log-guard-doctor-protection.test.ts +115 tests/codex-integration/codex-log-guard-doctor.test.ts +221 tests/codex-integration/codex-log-guard-inspect.test.ts +52 tests/codex-integration/codex-log-guard-lock.test.ts +306 tests/codex-integration/codex-log-guard-maintenance-coderabbit.test.ts +793 tests/codex-integration/codex-log-guard-maintenance.test.ts +39 tests/codex-integration/codex-log-guard-policy.test.ts +45 tests/codex-integration/codex-log-guard-processes.test.ts +167 tests/codex-integration/codex-log-guard-protection.test.ts +86 tests/codex-integration/codex-log-guard-status-zero-write.test.ts +170 tests/codex-integration/codex-main-account-refresh.test.ts +416 tests/codex-integration/codex-main-grant-refusal.test.ts +261 tests/codex-integration/codex-main-rotation.test.ts +128 tests/codex-integration/codex-main-token-invalidated.test.ts +215 tests/codex-integration/codex-management-convergence.test.ts +155 tests/codex-integration/codex-metadata-integrity.test.ts +7486 tests/codex-integration/codex-missing-home.test.ts +126 tests/codex-integration/codex-model-availability-error.test.ts +391 tests/codex-integration/codex-model-denial-evidence.test.ts +69 tests/codex-integration/codex-model-entitlement-admission.test.ts +159 tests/codex-integration/codex-model-entitlements-program-shape.test.ts +225 tests/codex-integration/codex-model-entitlements.test.ts +150 tests/codex-integration/codex-models-cache-invalidate.test.ts +1297 tests/codex-integration/codex-native-availability-nux.test.ts +675 tests/codex-integration/codex-native-residue.test.ts +143 tests/codex-integration/codex-pin-drain-projection.test.ts +146 tests/codex-integration/codex-plan.test.ts +414 tests/codex-integration/codex-plugins-doctor.test.ts +178 tests/codex-integration/codex-pool-caller-fallback-policy.test.ts +177 tests/codex-integration/codex-pool-credit-policy.test.ts +143 tests/codex-integration/codex-pool-plan-exclusion.test.ts +78 tests/codex-integration/codex-pool-refresh-backoff.test.ts +158 tests/codex-integration/codex-pool-request-owned-main.test.ts +685 tests/codex-integration/codex-pool-rotation.test.ts +353 tests/codex-integration/codex-preserve-signed-in.test.ts +314 tests/codex-integration/codex-priority-failback.test.ts +65 tests/codex-integration/codex-proc-scan-errors.test.ts +92 tests/codex-integration/codex-prompt-adopt.test.ts +322 tests/codex-integration/codex-prompt-base-variants.test.ts +76 tests/codex-integration/codex-prompt-journal.test.ts +70 tests/codex-integration/codex-prompt-layers-read.test.ts +249 tests/codex-integration/codex-prompt-layers-write.test.ts +53 tests/codex-integration/codex-prompt-layers.test.ts +337 tests/codex-integration/codex-prompt-lock-sharing.test.ts +499 tests/codex-integration/codex-prompt-lock.test.ts +1412 tests/codex-integration/codex-prompt-route.test.ts +169 tests/codex-integration/codex-prompt-scalar-scope.test.ts +964 tests/codex-integration/codex-prompt-text-probe.test.ts +758 tests/codex-integration/codex-prompt-writes.test.ts +17329 tests/codex-integration/codex-provider-routing.test.ts +779 tests/codex-integration/codex-provider-table-retention.test.ts +118 tests/codex-integration/codex-quota-auto-refresh-generation.test.ts +241 tests/codex-integration/codex-quota-auto-refresh-main-admission.test.ts +473 tests/codex-integration/codex-quota-auto-refresh.test.ts +53 tests/codex-integration/codex-quota-capacity.test.ts +136 tests/codex-integration/codex-quota-history.test.ts +212 tests/codex-integration/codex-quota-parser-parity.test.ts +69 tests/codex-integration/codex-quota-persistence.test.ts +404 tests/codex-integration/codex-quota-prime.test.ts +119 tests/codex-integration/codex-quota-query-backoff.test.ts +306 tests/codex-integration/codex-quota-rejection.test.ts +139 tests/codex-integration/codex-refresh.test.ts +527 tests/codex-integration/codex-request-owned-affinity.test.ts +789 tests/codex-integration/codex-reset-credit-auto-redeem.test.ts +491 tests/codex-integration/codex-reset-credit-operation-ledger.test.ts +444 tests/codex-integration/codex-reset-credit-recovery.test.ts +100 tests/codex-integration/codex-restart-contract-parity.test.ts +248 tests/codex-integration/codex-restart-route.test.ts +4522 tests/codex-integration/codex-restore-app-rewrite.test.ts +8427 tests/codex-integration/codex-retained-root-serialization.test.ts +238 tests/codex-integration/codex-round-robin-headroom.test.ts +109 tests/codex-integration/codex-routing-cache-affinity-detour.test.ts +89 tests/codex-integration/codex-routing-elapsed-short-reset.test.ts +4284 tests/codex-integration/codex-routing.test.ts +203 tests/codex-integration/codex-runtime-macos-desktop.test.ts +109 tests/codex-integration/codex-runtime-wsl-desktop.test.ts +266 tests/codex-integration/codex-runtime.test.ts +399 tests/codex-integration/codex-service-manager-probe-hardening.test.ts +355 tests/codex-integration/codex-service-manager-probe.test.ts +20983 tests/codex-integration/codex-shim-autorestore.test.ts +95 tests/codex-integration/codex-shim-bypass-token.test.ts +234 tests/codex-integration/codex-shim-destroyed-probe.test.ts +53 tests/codex-integration/codex-shim-ensure-failure.test.ts +132 tests/codex-integration/codex-shim-fnm.test.ts +498 tests/codex-integration/codex-shim-migration.test.ts +155 tests/codex-integration/codex-shim-overlay-candidates.test.ts +789 tests/codex-integration/codex-shim-overlay-readiness.test.ts +2412 tests/codex-integration/codex-shim-overlay-transaction.test.ts +707 tests/codex-integration/codex-shim-overlay.test.ts +5040 tests/codex-integration/codex-shim-path-readiness.test.ts +28478 tests/codex-integration/codex-shim-readiness.test.ts +60 tests/codex-integration/codex-shim-runtime-preflight.test.ts +1031 tests/codex-integration/codex-shim-standalone.test.ts +231 tests/codex-integration/codex-shim-windows-revision.test.ts +25602 tests/codex-integration/codex-shim.test.ts +1582 tests/codex-integration/codex-sidecar-credit-policy.test.ts +227 tests/codex-integration/codex-signin-lockout.test.ts +261 tests/codex-integration/codex-spark-visibility.test.ts +67 tests/codex-integration/codex-sqlite-home.test.ts +519 tests/codex-integration/codex-stored-main-duplicate.test.ts +1498 tests/codex-integration/codex-sync-api.test.ts +327 tests/codex-integration/codex-sync-new-model-policy.test.ts +47 tests/codex-integration/codex-sync-response.test.ts +20954 tests/codex-integration/codex-sync-user-edits.test.ts +200 tests/codex-integration/codex-systemd-env-probe.test.ts +109 tests/codex-integration/codex-tool-mode.test.ts +554 tests/codex-integration/codex-transition-state-adoption.test.ts +70 tests/codex-integration/codex-transition-state-first-use-regression.test.ts +1917 tests/codex-integration/codex-transition-state-race.test.ts +288 tests/codex-integration/codex-transition-state.test.ts +221 tests/codex-integration/codex-use-remaining-quota.test.ts +102 tests/codex-integration/codex-user-identity.test.ts +768 tests/codex-integration/codex-v2-gate.test.ts +570 tests/codex-integration/codex-warmup.test.ts +2902 tests/codex-integration/codex-web-search-switch.test.ts +63 tests/codex-integration/codex-websocket-registry.test.ts +40 tests/codex-integration/codex-windows-current-sid.test.ts +3680 tests/codex-integration/codex-write-lock.test.ts +49 tests/codex-integration/combo-authoritative-reset.test.ts +47 tests/codex-integration/combo-codex-exhaustion-cooldown.test.ts +181 tests/codex-integration/combo-cooldown-reprobe.test.ts +660 tests/codex-integration/combo-description-catalog.test.ts +51 tests/codex-integration/combo-last-resort.test.ts +43 tests/codex-integration/combo-permanent-failure-cooldown.test.ts +48 tests/codex-integration/combo-reset-window-model-scope.test.ts +108 tests/codex-integration/combos-kiro-profile-hop.test.ts +692 tests/codex-integration/combos.test.ts +699 tests/codex-integration/compatibility-manifest.test.ts +119 tests/codex-integration/configured-native-models.test.ts +1790 tests/codex-integration/configured-ultrafast-picker.test.ts +139 tests/codex-integration/context-compat.test.ts +46 tests/codex-integration/custom-model-catalog-migration.test.ts +176 tests/codex-integration/deferred-collab-surface.test.ts +313 tests/codex-integration/discovered-native-models.test.ts +382 tests/codex-integration/doctor.test.ts +355 tests/codex-integration/effort-policy.test.ts +465 tests/codex-integration/exec-boundary-launch.test.ts +83 tests/codex-integration/exec-cli-bundle-containment.test.ts +142 tests/codex-integration/exec-cli-renamed-app-bundle.test.ts +106 tests/codex-integration/exec-known-app-bundles.test.ts +111 tests/codex-integration/exec-launcher-boundary.test.ts +42 tests/codex-integration/exec-renamed-app-bundle.test.ts +523 tests/codex-integration/exec-trust-boundary.test.ts +122 tests/codex-integration/fast-row-listing.test.ts +110 tests/codex-integration/fast-row.test.ts +221 tests/codex-integration/gather-routed-models-single-flight.test.ts +115 tests/codex-integration/gpt6-native-rows.test.ts +90 tests/codex-integration/gpt61-sol-rows.test.ts +173 tests/codex-integration/gpt61-terra-rows.test.ts +53 tests/codex-integration/history-migration-guardian.test.ts +134 tests/codex-integration/history-ocx-compaction-recovery.test.ts +60 tests/codex-integration/history-paginated-openai-compat.test.ts +1930 tests/codex-integration/history-paginated-transition-destinations.test.ts +89 tests/codex-integration/injection-link-websocket.test.ts +685 tests/codex-integration/injection-model-api.test.ts +275 tests/codex-integration/injection-model-suggest-routes.test.ts +71 tests/codex-integration/injection-routing-drift.test.ts +4005 tests/codex-integration/injection-routing-heal-apply.test.ts +600 tests/codex-integration/injection-routing-healer.test.ts +5962 tests/codex-integration/issue-452-empty-503.test.ts +4078 tests/codex-integration/issue-702-expired-replay-state.test.ts +575 tests/codex-integration/issue-914-transport-attribution.test.ts +169 tests/codex-integration/low-quota-desktop-notifier.test.ts +1180 tests/codex-integration/low-quota-protection.test.ts +614 tests/codex-integration/main-account-credit-renewal.test.ts +68 tests/codex-integration/main-account-external-usage.test.ts +15417 tests/codex-integration/main-account-hard-lock-auth.test.ts +266 tests/codex-integration/main-account-hard-lock-default.test.ts +825 tests/codex-integration/main-account-hard-lock-fallback-off.test.ts +541 tests/codex-integration/main-account-hard-lock-fallback-routing.test.ts +53 tests/codex-integration/main-account-hard-lock-policy.test.ts +337 tests/codex-integration/main-account-hard-lock-profile-dispatch.test.ts +520 tests/codex-integration/main-account-hard-lock-recovery.test.ts +136 tests/codex-integration/main-account-hard-lock-retirement.test.ts +89 tests/codex-integration/main-account-hard-lock-thresholds.test.ts +130 tests/codex-integration/main-account-hard-lock-usage-limit.test.ts +518 tests/codex-integration/main-account-policy-binding-wait.test.ts +100 tests/codex-integration/main-device-reauth-api.test.ts +220 tests/codex-integration/main-device-reauth.test.ts +121 tests/codex-integration/main-quota-evidence-validation.test.ts +3462 tests/codex-integration/main-quota-provenance.test.ts +489 tests/codex-integration/main-quota-window-observation.test.ts +2824 tests/codex-integration/messaging-local-cli.test.ts 110 tests/codex-integration/messaging-local-discovery.test.ts -157 tests/codex-integration/messaging-local-envelope.test.ts -841 tests/codex-integration/messaging-local-lifecycle.test.ts -368 tests/codex-integration/messaging-local-send.test.ts -51 tests/codex-integration/messaging-local-socket.test.ts -5823 tests/codex-integration/messaging-remote-admission.test.ts -575 tests/codex-integration/messaging-remote-contract.test.ts -623 tests/codex-integration/messaging-remote-enrollment-gaps.test.ts -9857 tests/codex-integration/messaging-remote-enrollment.test.ts -3852 tests/codex-integration/messaging-remote-gaps.test.ts -50 tests/codex-integration/messaging-remote-interop.test.ts -14973 tests/codex-integration/messaging-remote-lifecycle.test.ts -49 tests/codex-integration/messaging-remote-native.test.ts -13192 tests/codex-integration/messaging-remote-process.test.ts -2348 tests/codex-integration/messaging-remote-replies.test.ts -1871 tests/codex-integration/messaging-remote-scratch.test.ts -8353 tests/codex-integration/messaging-remote-send.test.ts -513 tests/codex-integration/messaging-remote-store.test.ts -39 tests/codex-integration/model-cache-generation-tombstone.test.ts -48 tests/codex-integration/model-cache.test.ts -248 tests/codex-integration/model-display-names-management-api.test.ts -191 tests/codex-integration/model-metadata-sync.test.ts -743 tests/codex-integration/model-pinned-effort.test.ts -906 tests/codex-integration/model-visibility-management-api.test.ts -762 tests/codex-integration/multi-agent-compat.test.ts -240 tests/codex-integration/multi-agent-keep-native-v1.test.ts -81 tests/codex-integration/multi-agent-origin.test.ts -147 tests/codex-integration/native-alias-maintainer-regressions.test.ts -140 tests/codex-integration/native-claude-code-toggle.test.ts -483 tests/codex-integration/native-claude-desktop-toggle.test.ts -3945 tests/codex-integration/native-codex-toggle.test.ts -460 tests/codex-integration/native-grok-toggle.test.ts -58 tests/codex-integration/native-main-auth-temp.test.ts -36 tests/codex-integration/native-main-claim-cache.test.ts -133 tests/codex-integration/native-main-claim.test.ts -7515 tests/codex-integration/native-main-owner-lifetime.test.ts -1061 tests/codex-integration/native-main-refresh-mode.test.ts -462 tests/codex-integration/native-model-toggle.test.ts -72 tests/codex-integration/native-profile-api.test.ts -7332 tests/codex-integration/native-profile-crash-boundaries.test.ts -2161 tests/codex-integration/native-profile-drain-server.test.ts -2445 tests/codex-integration/native-profile-manager.test.ts -355 tests/codex-integration/native-profile-processes.test.ts -77 tests/codex-integration/native-profile-recovery.test.ts -466 tests/codex-integration/native-profile-route-security.test.ts -230 tests/codex-integration/native-profile-stage-lifecycle.test.ts -337 tests/codex-integration/native-profile-startup-release.test.ts -14172 tests/codex-integration/native-profile-startup.test.ts -324 tests/codex-integration/native-profile-store.test.ts -172 tests/codex-integration/native-source-priority.test.ts -1254 tests/codex-integration/native-ultrafast-picker.test.ts -387 tests/codex-integration/orca-import.test.ts -104 tests/codex-integration/parallel-tool-calls-optin.test.ts -82 tests/codex-integration/project-config-warning-snapshot.test.ts -156 tests/codex-integration/project-config-warnings.test.ts -158 tests/codex-integration/reasoning-effort.test.ts -84 tests/codex-integration/reasoning-metadata.test.ts -268 tests/codex-integration/reserve-auth-context.test.ts -71 tests/codex-integration/reserve-availability.test.ts -4766 tests/codex-integration/reserve-catalog-lifecycle.test.ts -119 tests/codex-integration/reserve-catalog.test.ts -1541 tests/codex-integration/reserve-dispatch.test.ts -154 tests/codex-integration/reserve-helper-boundary.test.ts -95 tests/codex-integration/reserve-passive-revocation.test.ts -156 tests/codex-integration/reserve-quota-scope.test.ts -94 tests/codex-integration/selected-models.test.ts -97 tests/codex-integration/slug-codec.test.ts -216 tests/codex-integration/token-guardian.test.ts -1021 tests/codex-integration/ultrafast-live-catalog.test.ts -1544 tests/codex-integration/ultrafast-tier-honesty.test.ts -124 tests/codex-integration/upstream-reachability.test.ts -142 tests/codex-integration/vendor-context.test.ts -58 tests/codex-integration/warmup.test.ts -262 tests/codex-integration/websocket-capacity-activity.test.ts -99 tests/config/atomic-write-exclusive.test.ts -93 tests/config/atomic-write-nofollow-streamed.test.ts -100 tests/config/client-config-export-new-clients.test.ts -89 tests/config/client-config-export-output-limit.test.ts -166 tests/config/client-config-export.test.ts -148 tests/config/client-config-new-clients.test.ts -164 tests/config/compaction-recovery-settings.test.ts -513 tests/config/config-account-auto-pause-revisions.test.ts -55 tests/config/config-account-thresholds.test.ts -314 tests/config/config-anthropic-instance-pool.test.ts -58 tests/config/config-blocked-model-redirects.test.ts -51 tests/config/config-catalog-auto-refresh.test.ts -42 tests/config/config-commandcode-claude-pin.test.ts -79 tests/config/config-concurrent-inbound-body.test.ts -64 tests/config/config-hosted-search-projection.test.ts -128 tests/config/config-load-degrade.test.ts -826 tests/config/config-mutation-lock.test.ts -70 tests/config/config-native-reasoning-retention.test.ts -61 tests/config/config-non-object-backup.test.ts -197 tests/config/config-opencode-go-upgrade.test.ts -153 tests/config/config-opencode-zen-upgrade.test.ts -101 tests/config/config-ownership-uninstall.test.ts -83 tests/config/config-rebase-provenance-writers.test.ts -127 tests/config/config-removed-opencode-free-preserve-failure.test.ts -2393 tests/config/config-removed-opencode-free.test.ts -68 tests/config/config-save-boundary.test.ts -81 tests/config/config-skills-catalog-refresh.test.ts -68 tests/config/config-spend-ceilings.test.ts -72 tests/config/config-spend-pool-collision.test.ts -464 tests/config/config-user-edits.test.ts -38 tests/config/expand-user-path.test.ts -356 tests/config/hub-disable-live-save.test.ts -1053 tests/config/local-credential-generation.test.ts -344 tests/config/model-pinned-effort-config.test.ts -51 tests/config/owner-registry-acl.test.ts -119 tests/config/owner-registry-isolation.test.ts -93 tests/config/protocol-settings.test.ts -1031 tests/config/serving-runtimes.test.ts -3572 tests/config/settings-desktop-switch-apply.test.ts -183 tests/config/settings-fast-rows.test.ts -227 tests/config/settings-main-account-hard-lock.test.ts -247 tests/config/settings-memory-models.test.ts -180 tests/config/settings-oauth-open-browser.test.ts -183 tests/config/settings-reasoning-retention.test.ts -131 tests/config/settings-startup-health-seam.test.ts -13371 tests/config/settings-stream-mode.test.ts -46 tests/config/types-barrel-identity.test.ts -79 tests/config/url-normalization.test.ts -48 tests/config/yaml-fragment-source.test.ts -166 tests/e2e-style/phase100-native-parity.test.ts -55 tests/gui/alibaba-intl-token-plan.test.ts -61 tests/gui/claude-manual-env.test.ts -53 tests/gui/codex-account-mode-state.test.ts -43 tests/gui/codex-auth-modal-status.test.ts -44 tests/gui/codex-set-prompt.test.ts -54 tests/gui/combo-workspace-data.test.ts -57 tests/gui/combo-workspace-jev-decision.test.ts -72 tests/gui/dashboard-sidecar-codex-write.test.ts -125 tests/gui/dashboard-uptime.test.ts -43 tests/gui/gui-api-error.test.ts -115 tests/gui/gui-codex-usage-score-parity.test.ts -40 tests/gui/gui-desktop-sidecar-script.test.ts -55 tests/gui/gui-desktop-sidecar-signing.test.ts -117 tests/gui/gui-management-session.test.ts -43 tests/gui/gui-pair-capability.test.ts -211 tests/gui/gui-pair-client.test.ts -250 tests/gui/gui-pair-delivery.test.ts -2314 tests/gui/gui-pair-http.test.ts -83 tests/gui/gui-static.test.ts -43 tests/gui/gui-tray-vibrancy-surface.test.ts -63 tests/gui/html-lang-boot-script.test.ts -308 tests/gui/integrations-invariants.test.ts -72 tests/gui/logs-model-tier-confirmation.test.ts -69 tests/gui/main-device-reauth-ui.test.ts -41 tests/gui/models-feedback-callback.test.ts -43 tests/gui/models-free-filter.test.ts -40 tests/gui/models-page-groups.test.ts -45 tests/gui/models-workspace-tabs.test.ts -38 tests/gui/oauth-first-add-hint.test.ts -68 tests/gui/oauth-tos-warning.test.ts -476 tests/gui/platform-dialog-guard.test.ts -79 tests/gui/provider-payload.test.ts -102 tests/gui/provider-subscription-cli.test.ts -90 tests/gui/provider-workspace-auth.test.ts -100 tests/gui/provider-workspace-data.test.ts -94 tests/gui/provider-workspace-rail.test.ts -60 tests/gui/provider-workspace-state.test.ts -107 tests/gui/quota-bars-rows.test.ts -47 tests/gui/qwen-cloud-endpoints.test.ts -47 tests/gui/rate-limit-reset-credits.test.ts -44 tests/gui/routing-intelligence-ui.test.ts -47 tests/gui/routing-profile-editor-data.test.ts -42 tests/gui/standalone-build-script.test.ts -123 tests/gui/startup-health-ui.test.ts -182 tests/gui/tencent-siliconflow-providers.test.ts -155 tests/gui/vision-sidecar-timeout-bounds.test.ts -260 tests/gui/volcengine-providers.test.ts -123 tests/images/artifacts-prune.test.ts -53 tests/images/artifacts-ssrf.test.ts -85 tests/images/download-cap-default.test.ts -88 tests/images/download-connect-deadline-default.test.ts -83 tests/images/gemini-inline.test.ts -111 tests/images/loop-reasoning-replay.test.ts -114 tests/images/loop-terminal-refusal.test.ts -3250 tests/images/loop.test.ts -49 tests/images/pinned-https-get.test.ts -73 tests/images/plan.test.ts -43 tests/images/synthetic-tool.test.ts -140 tests/images/xai-client.test.ts +207 tests/codex-integration/messaging-local-envelope.test.ts +1165 tests/codex-integration/messaging-local-lifecycle.test.ts +425 tests/codex-integration/messaging-local-send.test.ts +106 tests/codex-integration/messaging-local-socket.test.ts +12446 tests/codex-integration/messaging-mcp-queue.test.ts +7927 tests/codex-integration/messaging-remote-admission.test.ts +703 tests/codex-integration/messaging-remote-contract.test.ts +712 tests/codex-integration/messaging-remote-enrollment-gaps.test.ts +13782 tests/codex-integration/messaging-remote-enrollment.test.ts +78 tests/codex-integration/messaging-remote-forward-failure.test.ts +3131 tests/codex-integration/messaging-remote-gaps.test.ts +67 tests/codex-integration/messaging-remote-interop.test.ts +16866 tests/codex-integration/messaging-remote-lifecycle.test.ts +55 tests/codex-integration/messaging-remote-native.test.ts +50 tests/codex-integration/messaging-remote-port-reservation.test.ts +13144 tests/codex-integration/messaging-remote-process.test.ts +3697 tests/codex-integration/messaging-remote-replies.test.ts +2064 tests/codex-integration/messaging-remote-scratch.test.ts +12063 tests/codex-integration/messaging-remote-send.test.ts +968 tests/codex-integration/messaging-remote-store.test.ts +46 tests/codex-integration/model-cache-generation-tombstone.test.ts +43 tests/codex-integration/model-cache.test.ts +335 tests/codex-integration/model-display-names-management-api.test.ts +229 tests/codex-integration/model-metadata-sync.test.ts +952 tests/codex-integration/model-pinned-effort.test.ts +1054 tests/codex-integration/model-visibility-management-api.test.ts +945 tests/codex-integration/multi-agent-compat.test.ts +404 tests/codex-integration/multi-agent-keep-native-v1.test.ts +79 tests/codex-integration/multi-agent-origin.test.ts +119 tests/codex-integration/native-alias-maintainer-regressions.test.ts +177 tests/codex-integration/native-claude-code-toggle.test.ts +553 tests/codex-integration/native-claude-desktop-toggle.test.ts +3798 tests/codex-integration/native-codex-toggle.test.ts +437 tests/codex-integration/native-grok-toggle.test.ts +85 tests/codex-integration/native-main-auth-temp.test.ts +44 tests/codex-integration/native-main-claim-cache.test.ts +173 tests/codex-integration/native-main-claim.test.ts +9707 tests/codex-integration/native-main-owner-lifetime.test.ts +1203 tests/codex-integration/native-main-refresh-mode.test.ts +913 tests/codex-integration/native-model-toggle.test.ts +104 tests/codex-integration/native-profile-api.test.ts +10716 tests/codex-integration/native-profile-crash-boundaries.test.ts +2416 tests/codex-integration/native-profile-drain-server.test.ts +2839 tests/codex-integration/native-profile-manager.test.ts +343 tests/codex-integration/native-profile-processes.test.ts +68 tests/codex-integration/native-profile-recovery.test.ts +589 tests/codex-integration/native-profile-route-security.test.ts +259 tests/codex-integration/native-profile-stage-lifecycle.test.ts +295 tests/codex-integration/native-profile-startup-release.test.ts +16469 tests/codex-integration/native-profile-startup.test.ts +408 tests/codex-integration/native-profile-store.test.ts +161 tests/codex-integration/native-source-priority.test.ts +1433 tests/codex-integration/native-ultrafast-picker.test.ts +466 tests/codex-integration/orca-import.test.ts +197 tests/codex-integration/parallel-tool-calls-optin.test.ts +86 tests/codex-integration/project-config-warning-snapshot.test.ts +161 tests/codex-integration/project-config-warnings.test.ts +156 tests/codex-integration/reasoning-effort.test.ts +94 tests/codex-integration/reasoning-metadata.test.ts +416 tests/codex-integration/reserve-auth-context.test.ts +56 tests/codex-integration/reserve-availability.test.ts +5148 tests/codex-integration/reserve-catalog-lifecycle.test.ts +217 tests/codex-integration/reserve-catalog.test.ts +1666 tests/codex-integration/reserve-dispatch.test.ts +125 tests/codex-integration/reserve-helper-boundary.test.ts +113 tests/codex-integration/reserve-passive-revocation.test.ts +136 tests/codex-integration/reserve-quota-scope.test.ts +135 tests/codex-integration/selected-models.test.ts +107 tests/codex-integration/slug-codec.test.ts +275 tests/codex-integration/token-guardian.test.ts +1169 tests/codex-integration/ultrafast-live-catalog.test.ts +1391 tests/codex-integration/ultrafast-tier-honesty.test.ts +100 tests/codex-integration/upstream-reachability.test.ts +157 tests/codex-integration/vendor-context.test.ts +42 tests/codex-integration/warmup.test.ts +267 tests/codex-integration/websocket-capacity-activity.test.ts +142 tests/config/atomic-write-exclusive.test.ts +143 tests/config/atomic-write-nofollow-streamed.test.ts +117 tests/config/client-config-export-new-clients.test.ts +136 tests/config/client-config-export-output-limit.test.ts +202 tests/config/client-config-export.test.ts +158 tests/config/client-config-new-clients.test.ts +220 tests/config/compaction-recovery-settings.test.ts +464 tests/config/config-account-auto-pause-revisions.test.ts +77 tests/config/config-account-thresholds.test.ts +428 tests/config/config-anthropic-instance-pool.test.ts +49 tests/config/config-blocked-model-redirects.test.ts +69 tests/config/config-catalog-auto-refresh.test.ts +41 tests/config/config-commandcode-claude-pin.test.ts +81 tests/config/config-concurrent-inbound-body.test.ts +102 tests/config/config-hosted-search-projection.test.ts +198 tests/config/config-load-degrade.test.ts +749 tests/config/config-mutation-lock.test.ts +123 tests/config/config-native-reasoning-retention.test.ts +63 tests/config/config-non-object-backup.test.ts +264 tests/config/config-opencode-go-upgrade.test.ts +129 tests/config/config-opencode-zen-upgrade.test.ts +112 tests/config/config-ownership-uninstall.test.ts +45 tests/config/config-rebase-provenance-writers.test.ts +211 tests/config/config-removed-opencode-free-preserve-failure.test.ts +2856 tests/config/config-removed-opencode-free.test.ts +65 tests/config/config-save-boundary.test.ts +78 tests/config/config-skills-catalog-refresh.test.ts +86 tests/config/config-spend-ceilings.test.ts +68 tests/config/config-spend-pool-collision.test.ts +702 tests/config/config-user-edits.test.ts +54 tests/config/config-workflow-budget.test.ts +88 tests/config/expand-user-path.test.ts +365 tests/config/hub-disable-live-save.test.ts +59 tests/config/lmstudio-system-policy.test.ts +3948 tests/config/local-credential-generation.test.ts +555 tests/config/model-pinned-effort-config.test.ts +47 tests/config/owner-registry-acl.test.ts +122 tests/config/owner-registry-isolation.test.ts +103 tests/config/protocol-settings.test.ts +1079 tests/config/serving-runtimes.test.ts +3904 tests/config/settings-desktop-switch-apply.test.ts +168 tests/config/settings-fast-rows.test.ts +271 tests/config/settings-main-account-hard-lock.test.ts +200 tests/config/settings-memory-models.test.ts +241 tests/config/settings-oauth-open-browser.test.ts +156 tests/config/settings-reasoning-retention.test.ts +263 tests/config/settings-startup-health-seam.test.ts +14818 tests/config/settings-stream-mode.test.ts +53 tests/config/types-barrel-identity.test.ts +118 tests/config/url-normalization.test.ts +45 tests/config/yaml-fragment-source.test.ts +110 tests/e2e-style/phase100-native-parity.test.ts +84 tests/gui/alibaba-intl-token-plan.test.ts +42 tests/gui/claude-manual-env.test.ts +39 tests/gui/codex-account-mode-state.test.ts +69 tests/gui/codex-auth-modal-status.test.ts +38 tests/gui/codex-set-prompt.test.ts +51 tests/gui/combo-workspace-data.test.ts +73 tests/gui/combo-workspace-jev-decision.test.ts +49 tests/gui/dashboard-sidecar-codex-write.test.ts +104 tests/gui/dashboard-uptime.test.ts +44 tests/gui/gui-api-error.test.ts +204 tests/gui/gui-codex-usage-score-parity.test.ts +64 tests/gui/gui-desktop-sidecar-script.test.ts +48 tests/gui/gui-desktop-sidecar-signing.test.ts +208 tests/gui/gui-management-session.test.ts +46 tests/gui/gui-pair-capability.test.ts +186 tests/gui/gui-pair-client.test.ts +270 tests/gui/gui-pair-delivery.test.ts +2247 tests/gui/gui-pair-http.test.ts +62 tests/gui/gui-static.test.ts +40 tests/gui/gui-tray-vibrancy-surface.test.ts +82 tests/gui/html-lang-boot-script.test.ts +493 tests/gui/integrations-invariants.test.ts +76 tests/gui/logs-model-tier-confirmation.test.ts +80 tests/gui/main-device-reauth-ui.test.ts +39 tests/gui/models-feedback-callback.test.ts +158 tests/gui/models-free-filter.test.ts +44 tests/gui/models-page-groups.test.ts +48 tests/gui/models-workspace-tabs.test.ts +40 tests/gui/oauth-first-add-hint.test.ts +90 tests/gui/oauth-tos-warning.test.ts +720 tests/gui/platform-dialog-guard.test.ts +106 tests/gui/provider-payload.test.ts +49 tests/gui/provider-subscription-cli.test.ts +79 tests/gui/provider-workspace-auth.test.ts +282 tests/gui/provider-workspace-data.test.ts +117 tests/gui/provider-workspace-rail.test.ts +105 tests/gui/provider-workspace-state.test.ts +52 tests/gui/quota-bars-rows.test.ts +50 tests/gui/qwen-cloud-endpoints.test.ts +107 tests/gui/rate-limit-reset-credits.test.ts +47 tests/gui/routing-intelligence-ui.test.ts +56 tests/gui/routing-profile-editor-data.test.ts +106 tests/gui/standalone-build-script.test.ts +96 tests/gui/startup-health-ui.test.ts +125 tests/gui/tencent-siliconflow-providers.test.ts +117 tests/gui/vision-sidecar-timeout-bounds.test.ts +184 tests/gui/volcengine-providers.test.ts +102 tests/images/artifacts-prune.test.ts +128 tests/images/artifacts-ssrf.test.ts +109 tests/images/download-cap-default.test.ts +93 tests/images/download-connect-deadline-default.test.ts +179 tests/images/gemini-inline.test.ts +243 tests/images/loop-reasoning-replay.test.ts +130 tests/images/loop-terminal-refusal.test.ts +3089 tests/images/loop.test.ts +121 tests/images/pinned-https-get.test.ts +151 tests/images/plan.test.ts +48 tests/images/synthetic-tool.test.ts +124 tests/images/xai-client.test.ts 88 tests/images/z-fulfill.test.ts -304 tests/images/z-handler-activation.test.ts -453 tests/lab/core-lab-boundary.test.ts -253 tests/lab/core-link-boundary.test.ts -205 tests/lab/lab-activation.test.ts -241 tests/lab/lab-automation-coderabbit-regressions.test.ts -219 tests/lab/lab-automation-final-coderabbit-regressions.test.ts -137 tests/lab/lab-automation-ingwannu-regressions.test.ts -350 tests/lab/lab-automation-management-http.test.ts -40 tests/lab/lab-automation-persisted-cap-regression.test.ts -482 tests/lab/lab-automation-review-regressions.test.ts -454 tests/lab/lab-automation.test.ts -236 tests/lab/lab-community-evidence.test.ts -216 tests/lab/lab-community-filename-contract.test.ts -56 tests/lab/lab-community-mutation-lock.test.ts -157 tests/lab/lab-community-publisher-continuity.test.ts -174 tests/lab/lab-conformance-harness.test.ts -141 tests/lab/lab-conformance-runner-failures.test.ts -426 tests/lab/lab-evidence-ledger.test.ts -308 tests/lab/lab-evidence-sanitization.test.ts -180 tests/lab/lab-fabric-outcome-validation.test.ts -48 tests/lab/lab-fabric-persistence-boundary.test.ts -235 tests/lab/lab-fabric-producer-deadline.test.ts -95966 tests/lab/lab-fabric-task.test.ts -60 tests/lab/lab-installation-salt-cache.test.ts -849 tests/lab/lab-ledger-mutation-lock.test.ts -326 tests/lab/lab-live-pinned-timeouts.test.ts -160 tests/lab/lab-live-probe.test.ts -118 tests/lab/lab-live-receipt-integrity.test.ts -112 tests/lab/lab-live-review-regressions.test.ts -238 tests/lab/lab-live-sandbox.test.ts -201 tests/lab/lab-passive-production-evidence.test.ts -421 tests/lab/lab-passive-production-surfaces.test.ts -48 tests/lab/lab-paths-security.test.ts -138 tests/lab/lab-post-merge-hardening.test.ts -114 tests/lab/lab-post-merge-projection.test.ts -64 tests/lab/lab-private-file-consumer-recovery.test.ts -51 tests/lab/lab-private-file-durability.test.ts -214 tests/lab/lab-public-api-json.test.ts -110 tests/lab/lab-public-artifact-policy.test.ts -265 tests/lab/lab-public-coderabbit-regressions.test.ts -65 tests/lab/lab-public-core-contract.test.ts -175 tests/lab/lab-public-deep-review-regressions.test.ts -137 tests/lab/lab-public-evidence.test.ts -219 tests/lab/lab-public-export-transaction.test.ts -43 tests/lab/lab-public-file-safety.test.ts -240 tests/lab/lab-public-final-review-regressions.test.ts -168 tests/lab/lab-public-lifecycle-hardening.test.ts -40 tests/lab/lab-public-privacy-ipv6.test.ts -493 tests/lab/lab-public-provenance-recovery.test.ts -289 tests/lab/lab-public-review-fixes.test.ts -45 tests/lab/lab-public-route-registry.test.ts -55 tests/lab/lab-public-security-regressions.test.ts -231 tests/lab/lab-public-surfaces.test.ts -50 tests/lab/lab-public-wire-contract.test.ts -199 tests/lab/lab-read-filter-validation.test.ts -629 tests/lab/lab-read-surfaces.test.ts -747 tests/lib/abort-idle-deadline.test.ts -78 tests/lib/acl-error-classification.test.ts -334 tests/lib/ambiguous-resend-composition.test.ts -85 tests/lib/ambiguous-resend-gate.test.ts -80 tests/lib/authorization-scheme.test.ts -53 tests/lib/bounded-file-read.test.ts +277 tests/images/z-handler-activation.test.ts +524 tests/lab/core-lab-boundary.test.ts +277 tests/lab/core-link-boundary.test.ts +321 tests/lab/lab-activation.test.ts +290 tests/lab/lab-automation-coderabbit-regressions.test.ts +447 tests/lab/lab-automation-final-coderabbit-regressions.test.ts +146 tests/lab/lab-automation-ingwannu-regressions.test.ts +236 tests/lab/lab-automation-management-http.test.ts +42 tests/lab/lab-automation-persisted-cap-regression.test.ts +497 tests/lab/lab-automation-review-regressions.test.ts +386 tests/lab/lab-automation.test.ts +341 tests/lab/lab-community-evidence.test.ts +177 tests/lab/lab-community-filename-contract.test.ts +60 tests/lab/lab-community-mutation-lock.test.ts +178 tests/lab/lab-community-publisher-continuity.test.ts +158 tests/lab/lab-conformance-harness.test.ts +145 tests/lab/lab-conformance-runner-failures.test.ts +613 tests/lab/lab-evidence-ledger.test.ts +294 tests/lab/lab-evidence-sanitization.test.ts +218 tests/lab/lab-fabric-outcome-validation.test.ts +61 tests/lab/lab-fabric-persistence-boundary.test.ts +247 tests/lab/lab-fabric-producer-deadline.test.ts +96337 tests/lab/lab-fabric-task.test.ts +55 tests/lab/lab-installation-salt-cache.test.ts +901 tests/lab/lab-ledger-mutation-lock.test.ts +294 tests/lab/lab-live-pinned-timeouts.test.ts +159 tests/lab/lab-live-probe.test.ts +182 tests/lab/lab-live-receipt-integrity.test.ts +109 tests/lab/lab-live-review-regressions.test.ts +205 tests/lab/lab-live-sandbox.test.ts +484 tests/lab/lab-passive-production-evidence.test.ts +306 tests/lab/lab-passive-production-surfaces.test.ts +46 tests/lab/lab-paths-security.test.ts +121 tests/lab/lab-post-merge-hardening.test.ts +89 tests/lab/lab-post-merge-projection.test.ts +72 tests/lab/lab-private-file-consumer-recovery.test.ts +63 tests/lab/lab-private-file-durability.test.ts +219 tests/lab/lab-public-api-json.test.ts +174 tests/lab/lab-public-artifact-policy.test.ts +248 tests/lab/lab-public-coderabbit-regressions.test.ts +60 tests/lab/lab-public-core-contract.test.ts +170 tests/lab/lab-public-deep-review-regressions.test.ts +147 tests/lab/lab-public-evidence.test.ts +122 tests/lab/lab-public-export-transaction.test.ts +38 tests/lab/lab-public-file-safety.test.ts +338 tests/lab/lab-public-final-review-regressions.test.ts +234 tests/lab/lab-public-lifecycle-hardening.test.ts +83 tests/lab/lab-public-privacy-ipv6.test.ts +581 tests/lab/lab-public-provenance-recovery.test.ts +319 tests/lab/lab-public-review-fixes.test.ts +59 tests/lab/lab-public-route-registry.test.ts +71 tests/lab/lab-public-security-regressions.test.ts +203 tests/lab/lab-public-surfaces.test.ts +125 tests/lab/lab-public-wire-contract.test.ts +503 tests/lab/lab-read-filter-validation.test.ts +512 tests/lab/lab-read-surfaces.test.ts +742 tests/lib/abort-idle-deadline.test.ts +67 tests/lib/acl-error-classification.test.ts +383 tests/lib/ambiguous-resend-composition.test.ts +71 tests/lib/ambiguous-resend-gate.test.ts +44 tests/lib/authorization-scheme.test.ts +67 tests/lib/bounded-file-read.test.ts 118 tests/lib/bun-runtime-preflight.test.ts -51 tests/lib/bun-stream-caps.test.ts -134 tests/lib/clearable-deadline.test.ts -263 tests/lib/credential-redirect-guard.test.ts -56 tests/lib/debug.test.ts -170 tests/lib/execution-budget-permits.test.ts -58 tests/lib/failure-attribution.test.ts -49 tests/lib/failure-stage-model.test.ts -44 tests/lib/fix-jsonc-cr-comments.test.ts -47 tests/lib/fix-jsonc-empty-comma.test.ts -39 tests/lib/fix-plain-data-own-keys.test.ts -47 tests/lib/fix-plain-data-shape.test.ts -42 tests/lib/fix-retry-release-timer.test.ts -112 tests/lib/local-chat-completion.test.ts -48 tests/lib/local-destinations.test.ts -49 tests/lib/local-upstream.test.ts -3168 tests/lib/opaque-proxy-tunnel-protocol.test.ts -528 tests/lib/opaque-proxy-tunnel.test.ts -975 tests/lib/optional-desktop-upstream.test.ts -239 tests/lib/optional-shutdown-hooks.test.ts -90 tests/lib/pinned-http-content-coding.test.ts -1864 tests/lib/pinned-http.test.ts -350 tests/lib/plugin-loader.test.ts -49 tests/lib/plugin-upstream-hooks.test.ts -44 tests/lib/privacy-mask-account.test.ts -59 tests/lib/process-control-graceful.test.ts -44 tests/lib/process-control.test.ts -44 tests/lib/provider-egress.test.ts -58 tests/lib/reasoning-replay-scope-source.test.ts -797 tests/lib/redact.test.ts -64 tests/lib/remove-tree-helper.test.ts -45 tests/lib/self-launch-argv.test.ts -1436 tests/lib/socks5-fetch.test.ts -80 tests/lib/socks5-tls-lifecycle.test.ts -79 tests/lib/socks5-upload-lifecycle.test.ts -187 tests/lib/spend-ceiling-enforcement.test.ts -48 tests/lib/spend-contract-c.test.ts -49 tests/lib/spend-corruption-compat.test.ts -44 tests/lib/spend-experimental-history.test.ts -62 tests/lib/spend-ledger-file-journal.test.ts -1285 tests/lib/spend-ledger-owner.test.ts -238 tests/lib/spend-pool-continuity.test.ts -51 tests/lib/spend-reservation-ledger.test.ts -935 tests/lib/spend-seed-overflow.test.ts -47 tests/lib/spend-unbound-expiry.test.ts -83 tests/lib/spend-zero-config-compat.test.ts -55 tests/lib/stall-subprocess-exit.test.ts -87 tests/lib/stall-timeout.test.ts -36 tests/lib/standalone.test.ts -56 tests/lib/strict-semver.test.ts -50 tests/lib/synced-state-location.test.ts -46 tests/lib/system-restart-contract-security.test.ts -62 tests/lib/token-estimate.test.ts -56 tests/lib/transient-budget-scope-source.test.ts -98 tests/lib/transport-null-body.test.ts -185 tests/lib/upstream-error-message-fallback.test.ts -45 tests/lib/upstream-retry-zero-output.test.ts -8308 tests/lib/upstream-retry.test.ts -264 tests/lib/worker-embed-coverage.test.ts -53 tests/lib/worker-embed.test.ts -123 tests/lib/workflow-budget.test.ts -399 tests/oauth/adapter-event-oauth-failover.test.ts -679 tests/oauth/anthropic2-discovery-ownership.test.ts -4161 tests/oauth/chatgpt-device-auth.test.ts -72 tests/oauth/chatgpt-oauth.test.ts -126 tests/oauth/chatgpt-token-boundaries.test.ts -125 tests/oauth/chatgpt-token-expiry.test.ts +56 tests/lib/bun-stream-caps.test.ts +114 tests/lib/clearable-deadline.test.ts +218 tests/lib/credential-redirect-guard.test.ts +47 tests/lib/debug.test.ts +117 tests/lib/execution-budget-permits.test.ts +87 tests/lib/failure-attribution.test.ts +75 tests/lib/failure-stage-model.test.ts +120 tests/lib/file-identity-callers.test.ts +42 tests/lib/file-identity.test.ts +109 tests/lib/fix-jsonc-cr-comments.test.ts +125 tests/lib/fix-jsonc-empty-comma.test.ts +36 tests/lib/fix-plain-data-own-keys.test.ts +39 tests/lib/fix-plain-data-shape.test.ts +37 tests/lib/fix-retry-release-timer.test.ts +93 tests/lib/local-chat-completion.test.ts +46 tests/lib/local-destinations.test.ts +67 tests/lib/local-upstream.test.ts +3169 tests/lib/opaque-proxy-tunnel-protocol.test.ts +517 tests/lib/opaque-proxy-tunnel.test.ts +967 tests/lib/optional-desktop-upstream.test.ts +429 tests/lib/optional-shutdown-hooks.test.ts +127 tests/lib/pinned-http-content-coding.test.ts +2090 tests/lib/pinned-http.test.ts +446 tests/lib/plugin-loader.test.ts +47 tests/lib/plugin-upstream-hooks.test.ts +38 tests/lib/privacy-mask-account.test.ts +46 tests/lib/process-control-graceful.test.ts +50 tests/lib/process-control.test.ts +46 tests/lib/provider-egress.test.ts +49 tests/lib/reasoning-replay-scope-source.test.ts +521 tests/lib/redact.test.ts +99 tests/lib/remove-tree-helper.test.ts +46 tests/lib/self-launch-argv.test.ts +1195 tests/lib/socks5-fetch.test.ts +165 tests/lib/socks5-tls-lifecycle.test.ts +58 tests/lib/socks5-upload-lifecycle.test.ts +283 tests/lib/spend-ceiling-enforcement.test.ts +45 tests/lib/spend-contract-c.test.ts +58 tests/lib/spend-corruption-compat.test.ts +74 tests/lib/spend-experimental-history.test.ts +99 tests/lib/spend-ledger-file-journal.test.ts +1408 tests/lib/spend-ledger-owner.test.ts +285 tests/lib/spend-pool-continuity.test.ts +43 tests/lib/spend-reservation-ledger.test.ts +990 tests/lib/spend-seed-overflow.test.ts +37 tests/lib/spend-unbound-expiry.test.ts +52 tests/lib/spend-zero-config-compat.test.ts +73 tests/lib/stall-subprocess-exit.test.ts +84 tests/lib/stall-timeout.test.ts +41 tests/lib/standalone.test.ts +57 tests/lib/strict-semver.test.ts +42 tests/lib/synced-state-location.test.ts +40 tests/lib/system-restart-contract-security.test.ts +112 tests/lib/token-estimate.test.ts +39 tests/lib/transient-budget-scope-source.test.ts +74 tests/lib/transport-null-body.test.ts +163 tests/lib/upstream-error-message-fallback.test.ts +69 tests/lib/upstream-retry-zero-output.test.ts +8192 tests/lib/upstream-retry.test.ts +247 tests/lib/worker-embed-coverage.test.ts +49 tests/lib/worker-embed.test.ts +155 tests/lib/workflow-budget.test.ts +486 tests/oauth/adapter-event-oauth-failover.test.ts +643 tests/oauth/anthropic2-discovery-ownership.test.ts +4194 tests/oauth/chatgpt-device-auth.test.ts +68 tests/oauth/chatgpt-oauth.test.ts +111 tests/oauth/chatgpt-token-boundaries.test.ts +126 tests/oauth/chatgpt-token-expiry.test.ts 10132 tests/oauth/dsh-login.test.ts -289 tests/oauth/generic-oauth-combo-account-cooldown.test.ts -440 tests/oauth/generic-oauth-failover.test.ts -439 tests/oauth/generic-oauth-refusal-composition.test.ts -419 tests/oauth/generic-session-affinity.test.ts -465 tests/oauth/key-login-live-update.test.ts -87 tests/oauth/key-login-preserves-model-costs.test.ts -45 tests/oauth/local-token-detect.test.ts -312 tests/oauth/oauth-account-attribution.test.ts -1183 tests/oauth/oauth-account-auto-pause-revision.test.ts -377 tests/oauth/oauth-account-auto-pause.test.ts -102 tests/oauth/oauth-account-id-collision.test.ts -184 tests/oauth/oauth-account-plans.test.ts -144 tests/oauth/oauth-account-quota-rank.test.ts -1643 tests/oauth/oauth-accounts-api.test.ts -341 tests/oauth/oauth-anthropic-identity.test.ts -433 tests/oauth/oauth-anthropic-instance-health.test.ts -850 tests/oauth/oauth-anthropic-instance-multiprocess.test.ts -406 tests/oauth/oauth-anthropic-instance-refresh.test.ts -533 tests/oauth/oauth-anthropic-instance-registration.test.ts -40 tests/oauth/oauth-callback-binds.test.ts -64 tests/oauth/oauth-callback-server.test.ts -3476 tests/oauth/oauth-code-login.test.ts -38 tests/oauth/oauth-device-code-contract.test.ts -206 tests/oauth/oauth-health.test.ts -496 tests/oauth/oauth-kiro-refresh-attention.test.ts -48 tests/oauth/oauth-log.test.ts -126 tests/oauth/oauth-login-cli-browser-launch.test.ts -3079 tests/oauth/oauth-login-cli-errors.test.ts -704 tests/oauth/oauth-login-cli-live-update.test.ts -125 tests/oauth/oauth-login-open-browser.test.ts -135 tests/oauth/oauth-login-summary.test.ts -536 tests/oauth/oauth-manual-code.test.ts -277 tests/oauth/oauth-meta-muse-login-diagnostics.test.ts -126 tests/oauth/oauth-open-browser-choice.test.ts -103 tests/oauth/oauth-open-url-result.test.ts -155 tests/oauth/oauth-provider-reconcile.test.ts -413 tests/oauth/oauth-public-surface.test.ts -229 tests/oauth/oauth-reauth-bind.test.ts -131 tests/oauth/oauth-reconcile-operator-maps.test.ts -666 tests/oauth/oauth-refresh-generic-lock.test.ts -3027 tests/oauth/oauth-refresh-lock-multiprocess.test.ts -507 tests/oauth/oauth-refresh-stale-capacity.test.ts -1543 tests/oauth/oauth-refresh.test.ts -333 tests/oauth/oauth-status-privacy.test.ts -529 tests/oauth/oauth-store-multi.test.ts -175 tests/oauth/oauth-store-quota-isolation.test.ts -101 tests/oauth/oauth-upsert-paused-api-key.test.ts -216 tests/oauth/oauth-upsert-preserves-api-key.test.ts -48 tests/oauth/pool-kernel-generic-sweep.test.ts -205 tests/oauth/state-store-sweeper.test.ts -65 tests/oauth/workbuddy-login.test.ts -402 tests/providers/aistupidlevel-provider.test.ts -48 tests/providers/alibaba-region-backup.test.ts -116 tests/providers/alibaba-region-migration.test.ts -47 tests/providers/alibaba-region-startup.test.ts -165 tests/providers/alibaba-token-plan-responses-optin.test.ts -276 tests/providers/alibaba-token-plan-wire-defaults.test.ts -138 tests/providers/api-key-auto-pause-distribution.test.ts -108 tests/providers/api-key-catalog-authority.test.ts -41 tests/providers/api-key-selection-capture.test.ts -113 tests/providers/api-key-selection-cooldown.test.ts -142 tests/providers/aside-client.test.ts -43 tests/providers/auto-compact-budget.test.ts -106 tests/providers/azure-adapter.test.ts +292 tests/oauth/generic-oauth-combo-account-cooldown.test.ts +499 tests/oauth/generic-oauth-failover.test.ts +365 tests/oauth/generic-oauth-refusal-composition.test.ts +758 tests/oauth/generic-session-affinity.test.ts +427 tests/oauth/key-login-live-update.test.ts +78 tests/oauth/key-login-preserves-model-costs.test.ts +52 tests/oauth/local-token-detect.test.ts +416 tests/oauth/oauth-account-attribution.test.ts +1144 tests/oauth/oauth-account-auto-pause-revision.test.ts +533 tests/oauth/oauth-account-auto-pause.test.ts +85 tests/oauth/oauth-account-id-collision.test.ts +270 tests/oauth/oauth-account-plans.test.ts +263 tests/oauth/oauth-account-quota-rank.test.ts +1779 tests/oauth/oauth-accounts-api.test.ts +447 tests/oauth/oauth-anthropic-identity.test.ts +466 tests/oauth/oauth-anthropic-instance-health.test.ts +1050 tests/oauth/oauth-anthropic-instance-multiprocess.test.ts +548 tests/oauth/oauth-anthropic-instance-refresh.test.ts +775 tests/oauth/oauth-anthropic-instance-registration.test.ts +58 tests/oauth/oauth-callback-binds.test.ts +50 tests/oauth/oauth-callback-server.test.ts +4216 tests/oauth/oauth-code-login.test.ts +48 tests/oauth/oauth-device-code-contract.test.ts +192 tests/oauth/oauth-health.test.ts +954 tests/oauth/oauth-kiro-refresh-attention.test.ts +70 tests/oauth/oauth-log.test.ts +191 tests/oauth/oauth-login-cli-browser-launch.test.ts +5554 tests/oauth/oauth-login-cli-errors.test.ts +607 tests/oauth/oauth-login-cli-live-update.test.ts +244 tests/oauth/oauth-login-open-browser.test.ts +126 tests/oauth/oauth-login-summary.test.ts +599 tests/oauth/oauth-manual-code.test.ts +227 tests/oauth/oauth-meta-muse-login-diagnostics.test.ts +100 tests/oauth/oauth-open-browser-choice.test.ts +178 tests/oauth/oauth-open-url-result.test.ts +195 tests/oauth/oauth-provider-reconcile.test.ts +403 tests/oauth/oauth-public-surface.test.ts +328 tests/oauth/oauth-reauth-bind.test.ts +133 tests/oauth/oauth-reconcile-operator-maps.test.ts +1021 tests/oauth/oauth-refresh-generic-lock.test.ts +3197 tests/oauth/oauth-refresh-lock-multiprocess.test.ts +436 tests/oauth/oauth-refresh-stale-capacity.test.ts +1927 tests/oauth/oauth-refresh.test.ts +445 tests/oauth/oauth-status-privacy.test.ts +639 tests/oauth/oauth-store-multi.test.ts +153 tests/oauth/oauth-store-quota-isolation.test.ts +103 tests/oauth/oauth-upsert-paused-api-key.test.ts +198 tests/oauth/oauth-upsert-preserves-api-key.test.ts +44 tests/oauth/pool-kernel-generic-sweep.test.ts +314 tests/oauth/state-store-sweeper.test.ts +70 tests/oauth/workbuddy-login.test.ts +436 tests/providers/aistupidlevel-provider.test.ts +51 tests/providers/alibaba-region-backup.test.ts +106 tests/providers/alibaba-region-migration.test.ts +46 tests/providers/alibaba-region-startup.test.ts +222 tests/providers/alibaba-token-plan-responses-optin.test.ts +361 tests/providers/alibaba-token-plan-wire-defaults.test.ts +301 tests/providers/api-key-auto-pause-distribution.test.ts +128 tests/providers/api-key-catalog-authority.test.ts +43 tests/providers/api-key-selection-capture.test.ts +395 tests/providers/api-key-selection-cooldown.test.ts +158 tests/providers/aside-client.test.ts +45 tests/providers/auto-compact-budget.test.ts +124 tests/providers/azure-adapter.test.ts 46 tests/providers/azure-model-router-tool-schema.test.ts -178 tests/providers/azure-vendor-metadata.test.ts -118 tests/providers/baseten-provider.test.ts -119 tests/providers/chutes-provider.test.ts -601 tests/providers/claude-cli-adapter.test.ts -330 tests/providers/claude-cli-client-http.test.ts -50 tests/providers/claude-cli-efficiency.test.ts -95 tests/providers/claude-cli-tool-capture.test.ts -252 tests/providers/claude-cli-usage-admission.test.ts -134 tests/providers/cline-pass-deepseek-v4-tool-replay.test.ts -86 tests/providers/cline-pass-provider.test.ts -115 tests/providers/cline-pass-reasoning-efforts.test.ts -42 tests/providers/cline-provider.test.ts -2019 tests/providers/codebuddy-adapter.test.ts -48 tests/providers/codebuddy-live-acceptance.test.ts -114 tests/providers/codebuddy-live-models.test.ts -2982 tests/providers/codebuddy-mcp-server.test.ts -53 tests/providers/codebuddy-protocol.test.ts -315 tests/providers/codebuddy-tool-bridge-turn.test.ts -89 tests/providers/codebuddy-tool-bridge.test.ts -53 tests/providers/coding-agent-json-lines-scaling.test.ts -265 tests/providers/command-code-credit-failover.test.ts -503 tests/providers/command-code-credit-rotation.test.ts -645 tests/providers/command-code-efforts.test.ts -48 tests/providers/command-code-error-finish.test.ts -184 tests/providers/command-code-fakeip-discovery.test.ts -595 tests/providers/command-code-plan-denial.test.ts -2244 tests/providers/command-code-project-context.test.ts -843 tests/providers/command-code-provider.test.ts -102 tests/providers/command-code-quota.test.ts -321 tests/providers/command-code-tool-text-prose-split.test.ts -512 tests/providers/command-code-tool-text.test.ts -49 tests/providers/command-code-workspace-cache.test.ts -235 tests/providers/commandcode-provider.test.ts -41 tests/providers/context-cap-unknown-window.test.ts -81 tests/providers/context-window-seed-repair.test.ts -134 tests/providers/crusoe-provider.test.ts -241 tests/providers/cursor/cursor-adapter.test.ts -46 tests/providers/cursor/cursor-arg-normalize.test.ts -88 tests/providers/cursor/cursor-blob-claude-client-tools.test.ts -64 tests/providers/cursor/cursor-blob-integrity.test.ts -401 tests/providers/cursor/cursor-blob.test.ts -47 tests/providers/cursor/cursor-call-id.test.ts -81 tests/providers/cursor/cursor-cancel-provenance.test.ts -54 tests/providers/cursor/cursor-catalog.test.ts -48 tests/providers/cursor/cursor-claude-id.test.ts -163 tests/providers/cursor/cursor-continuation-invariants.test.ts -137 tests/providers/cursor/cursor-continuity-retention.test.ts -67 tests/providers/cursor/cursor-default-catalog-suppression.test.ts -109 tests/providers/cursor/cursor-desktop-exec.test.ts -46 tests/providers/cursor/cursor-discovery.test.ts -94 tests/providers/cursor/cursor-display-names.test.ts -719 tests/providers/cursor/cursor-effort-rows.test.ts -65 tests/providers/cursor/cursor-effort-suffix.test.ts -48 tests/providers/cursor/cursor-effort-table.test.ts -121 tests/providers/cursor/cursor-envelope-echo-retry.test.ts -121 tests/providers/cursor/cursor-eof-terminal.test.ts -76 tests/providers/cursor/cursor-errors.test.ts -43 tests/providers/cursor/cursor-exec-empty-result.test.ts -105 tests/providers/cursor/cursor-fast-listing.test.ts -71 tests/providers/cursor/cursor-fast-tier.test.ts -230 tests/providers/cursor/cursor-foreground-shell.test.ts -115 tests/providers/cursor/cursor-framing.test.ts -64 tests/providers/cursor/cursor-freeform-args.test.ts -210 tests/providers/cursor/cursor-h2-pool-shutdown.test.ts -2841 tests/providers/cursor/cursor-hardening.test.ts -94 tests/providers/cursor/cursor-http1-transport.test.ts -3304 tests/providers/cursor/cursor-images.test.ts -700 tests/providers/cursor/cursor-integration-status.test.ts -118 tests/providers/cursor/cursor-interaction-query.test.ts -56 tests/providers/cursor/cursor-kv-store.test.ts -52 tests/providers/cursor/cursor-live-smoke-gate.test.ts -219 tests/providers/cursor/cursor-live-transport.test.ts +200 tests/providers/azure-vendor-metadata.test.ts +137 tests/providers/baseten-provider.test.ts +489 tests/providers/cc-switch-import.test.ts +123 tests/providers/chutes-provider.test.ts +983 tests/providers/claude-cli-adapter.test.ts +344 tests/providers/claude-cli-client-http.test.ts +53 tests/providers/claude-cli-efficiency.test.ts +100 tests/providers/claude-cli-tool-capture.test.ts +391 tests/providers/claude-cli-usage-admission.test.ts +160 tests/providers/cline-pass-deepseek-v4-tool-replay.test.ts +144 tests/providers/cline-pass-provider.test.ts +124 tests/providers/cline-pass-reasoning-efforts.test.ts +56 tests/providers/cline-provider.test.ts +222 tests/providers/codebuddy-adapter.test.ts +46 tests/providers/codebuddy-live-acceptance.test.ts +228 tests/providers/codebuddy-live-models.test.ts +2768 tests/providers/codebuddy-mcp-server.test.ts +49 tests/providers/codebuddy-protocol.test.ts +316 tests/providers/codebuddy-tool-bridge-turn.test.ts +164 tests/providers/codebuddy-tool-bridge.test.ts +56 tests/providers/coding-agent-json-lines-scaling.test.ts +291 tests/providers/command-code-credit-failover.test.ts +1224 tests/providers/command-code-credit-rotation.test.ts +516 tests/providers/command-code-efforts.test.ts +106 tests/providers/command-code-error-finish.test.ts +186 tests/providers/command-code-fakeip-discovery.test.ts +774 tests/providers/command-code-plan-denial.test.ts +2203 tests/providers/command-code-project-context.test.ts +1588 tests/providers/command-code-provider.test.ts +138 tests/providers/command-code-quota.test.ts +346 tests/providers/command-code-tool-text-prose-split.test.ts +799 tests/providers/command-code-tool-text.test.ts +58 tests/providers/command-code-workspace-cache.test.ts +191 tests/providers/commandcode-provider.test.ts +67 tests/providers/context-cap-unknown-window.test.ts +43 tests/providers/context-window-seed-repair.test.ts +202 tests/providers/crusoe-provider.test.ts +273 tests/providers/cursor/cursor-adapter.test.ts +61 tests/providers/cursor/cursor-arg-normalize.test.ts +116 tests/providers/cursor/cursor-blob-claude-client-tools.test.ts +54 tests/providers/cursor/cursor-blob-integrity.test.ts +328 tests/providers/cursor/cursor-blob.test.ts +73 tests/providers/cursor/cursor-call-id.test.ts +110 tests/providers/cursor/cursor-cancel-provenance.test.ts +49 tests/providers/cursor/cursor-catalog.test.ts +49 tests/providers/cursor/cursor-claude-id.test.ts +146 tests/providers/cursor/cursor-continuation-invariants.test.ts +238 tests/providers/cursor/cursor-continuity-retention.test.ts +65 tests/providers/cursor/cursor-default-catalog-suppression.test.ts +125 tests/providers/cursor/cursor-desktop-exec.test.ts +64 tests/providers/cursor/cursor-discovery.test.ts +82 tests/providers/cursor/cursor-display-names.test.ts +822 tests/providers/cursor/cursor-effort-rows.test.ts +64 tests/providers/cursor/cursor-effort-suffix.test.ts +46 tests/providers/cursor/cursor-effort-table.test.ts +125 tests/providers/cursor/cursor-envelope-echo-retry.test.ts +124 tests/providers/cursor/cursor-eof-terminal.test.ts +67 tests/providers/cursor/cursor-errors.test.ts +61 tests/providers/cursor/cursor-exec-empty-result.test.ts +106 tests/providers/cursor/cursor-fast-listing.test.ts +76 tests/providers/cursor/cursor-fast-tier.test.ts +284 tests/providers/cursor/cursor-foreground-shell.test.ts +113 tests/providers/cursor/cursor-framing.test.ts +76 tests/providers/cursor/cursor-freeform-args.test.ts +212 tests/providers/cursor/cursor-h2-pool-shutdown.test.ts +2837 tests/providers/cursor/cursor-hardening.test.ts +106 tests/providers/cursor/cursor-http1-transport.test.ts +3165 tests/providers/cursor/cursor-images.test.ts +784 tests/providers/cursor/cursor-integration-status.test.ts +121 tests/providers/cursor/cursor-interaction-query.test.ts +40 tests/providers/cursor/cursor-kv-store.test.ts +40 tests/providers/cursor/cursor-live-smoke-gate.test.ts +355 tests/providers/cursor/cursor-live-transport.test.ts 40 tests/providers/cursor/cursor-local-installer.test.ts -512 tests/providers/cursor/cursor-local-models-schema.test.ts -139 tests/providers/cursor/cursor-mcp-manager.test.ts -400 tests/providers/cursor/cursor-mcp-stdio.test.ts -72 tests/providers/cursor/cursor-message-mapper.test.ts -62 tests/providers/cursor/cursor-native-exec-common.test.ts -163 tests/providers/cursor/cursor-native-exec-policy.test.ts -138 tests/providers/cursor/cursor-native-exec-shell.test.ts -266 tests/providers/cursor/cursor-native-exec.test.ts -84 tests/providers/cursor/cursor-native-grep-globs.test.ts -126 tests/providers/cursor/cursor-oauth-shell.test.ts -678 tests/providers/cursor/cursor-oauth.test.ts -51 tests/providers/cursor/cursor-pool.test.ts -80 tests/providers/cursor/cursor-protobuf-events.test.ts -141 tests/providers/cursor/cursor-repetition-breaker.test.ts -142 tests/providers/cursor/cursor-request-builder.test.ts -94 tests/providers/cursor/cursor-request-compat.test.ts -105 tests/providers/cursor/cursor-roster-account-scope.test.ts -60 tests/providers/cursor/cursor-silent-redirect.test.ts -135 tests/providers/cursor/cursor-static-catalog.test.ts -3539 tests/providers/cursor/cursor-stream-health.test.ts -96 tests/providers/cursor/cursor-structured-edit.test.ts +591 tests/providers/cursor/cursor-local-models-schema.test.ts +207 tests/providers/cursor/cursor-mcp-manager.test.ts +448 tests/providers/cursor/cursor-mcp-stdio.test.ts +83 tests/providers/cursor/cursor-message-mapper.test.ts +65 tests/providers/cursor/cursor-native-exec-common.test.ts +124 tests/providers/cursor/cursor-native-exec-policy.test.ts +159 tests/providers/cursor/cursor-native-exec-shell.test.ts +243 tests/providers/cursor/cursor-native-exec.test.ts +76 tests/providers/cursor/cursor-native-grep-globs.test.ts +120 tests/providers/cursor/cursor-oauth-shell.test.ts +635 tests/providers/cursor/cursor-oauth.test.ts +99 tests/providers/cursor/cursor-pool.test.ts +84 tests/providers/cursor/cursor-protobuf-events.test.ts +172 tests/providers/cursor/cursor-repetition-breaker.test.ts +136 tests/providers/cursor/cursor-request-builder.test.ts +119 tests/providers/cursor/cursor-request-compat.test.ts +142 tests/providers/cursor/cursor-roster-account-scope.test.ts +51 tests/providers/cursor/cursor-silent-redirect.test.ts +126 tests/providers/cursor/cursor-static-catalog.test.ts +3533 tests/providers/cursor/cursor-stream-health.test.ts +111 tests/providers/cursor/cursor-structured-edit.test.ts 68 tests/providers/cursor/cursor-tool-arg-decoding.test.ts -65 tests/providers/cursor/cursor-tool-choice.test.ts -92 tests/providers/cursor/cursor-tool-continuation.test.ts -72 tests/providers/cursor/cursor-tool-definitions.test.ts -4007 tests/providers/cursor/cursor-tool-finalize-race.test.ts -124 tests/providers/cursor/cursor-tool-result-image.test.ts -259 tests/providers/cursor/cursor-tool-result-invocation.test.ts -97 tests/providers/cursor/cursor-tool-suspended-checkpoint.test.ts -123 tests/providers/cursor/cursor-tool-wording.test.ts +105 tests/providers/cursor/cursor-tool-choice.test.ts +93 tests/providers/cursor/cursor-tool-continuation.test.ts +83 tests/providers/cursor/cursor-tool-definitions.test.ts +4028 tests/providers/cursor/cursor-tool-finalize-race.test.ts +105 tests/providers/cursor/cursor-tool-result-image.test.ts +275 tests/providers/cursor/cursor-tool-result-invocation.test.ts +72 tests/providers/cursor/cursor-tool-suspended-checkpoint.test.ts +217 tests/providers/cursor/cursor-tool-wording.test.ts 109 tests/providers/cursor/cursor-toolresult-normalize.test.ts -1849 tests/providers/cursor/cursor-transport-retry.test.ts -71 tests/providers/cursor/cursor-ultra-mode.test.ts -60 tests/providers/cursor/cursor-umbrella-rows.test.ts -42 tests/providers/cursor/cursor-uncallable-quarantine.test.ts -67 tests/providers/cursor/cursor-vision-wire-harness.test.ts -221 tests/providers/cyber-policy-error-fidelity.test.ts -215 tests/providers/deepinfra-provider.test.ts -52 tests/providers/deepseek-artifact-tool-schema.test.ts -130 tests/providers/deepseek-bare-tool-call-replay.test.ts -3648 tests/providers/deepseek-image-files.test.ts -411 tests/providers/deepseek-inbound-wire.test.ts -93 tests/providers/deepseek-quota-currency.test.ts -131 tests/providers/deepseek-reasoning-replay-gaps.test.ts -108 tests/providers/deepseek-reasoning-replay.test.ts -388 tests/providers/deepseek-responses-item-id-repair.test.ts -2101 tests/providers/devin-adapter-reset-wait.test.ts -160 tests/providers/devin-adapter.test.ts -218 tests/providers/devin-anthropic-signature-fallback.test.ts -218 tests/providers/devin-chat-wire-fixes.test.ts -76 tests/providers/devin-cli-authmode-migration.test.ts -59 tests/providers/devin-effort-ladder.test.ts -115 tests/providers/devin-family-resolution.test.ts -109 tests/providers/devin-hardening.test.ts -74 tests/providers/devin-image-passthrough.test.ts -110 tests/providers/devin-live-models.test.ts -111 tests/providers/devin-login.test.ts -79 tests/providers/devin-output-budget.test.ts -129 tests/providers/devin-prompt-cache.test.ts -87 tests/providers/devin-provider-merge-migration.test.ts -114 tests/providers/devin-quota.test.ts -99 tests/providers/devin-reasoning-continuation.test.ts -80 tests/providers/devin-stated-reset-hardening.test.ts -72 tests/providers/devin-stated-reset-retry.test.ts -81 tests/providers/devin-stream-deadline.test.ts -56 tests/providers/devin-trajectory.test.ts -144 tests/providers/digitalocean-scaleway-provider.test.ts -700 tests/providers/dsh-account.test.ts -118 tests/providers/exa-web-search.test.ts -226 tests/providers/explicit-key-pause-oauth-boundary.test.ts -77 tests/providers/fast-row-ingress.test.ts -121 tests/providers/featherless-provider.test.ts -122 tests/providers/flash-route-image-modalities.test.ts -544 tests/providers/forward-admission-separation.test.ts -76 tests/providers/free-directory-runcrate.test.ts -971 tests/providers/github-copilot/github-copilot-account-origin.test.ts -1238 tests/providers/github-copilot/github-copilot-auto-runtime.test.ts -84 tests/providers/github-copilot/github-copilot-auto.test.ts -113 tests/providers/github-copilot/github-copilot-catalog-hints.test.ts -96 tests/providers/github-copilot/github-copilot-context-tier.test.ts -16099 tests/providers/github-copilot/github-copilot-oauth.test.ts -56 tests/providers/github-copilot/github-copilot-sse-rewrite.test.ts -348 tests/providers/github-copilot/github-copilot-stream-contract.test.ts -329 tests/providers/github-copilot/github-copilot-wire-defaults.test.ts -1037 tests/providers/gpt61-terra-provider-rows.test.ts -76 tests/providers/haiku-5-5-catalog.test.ts -108 tests/providers/hyperbolic-provider.test.ts -455 tests/providers/initial-model-selection.test.ts -424 tests/providers/initial-selection-write-fence.test.ts -98 tests/providers/jev-provider.test.ts -94 tests/providers/kimi-oauth-identity.test.ts -113 tests/providers/kimi-responses-adjacency.test.ts -67 tests/providers/kiro/kiro-account-load.test.ts -130 tests/providers/kiro/kiro-account-quota.test.ts -3984 tests/providers/kiro/kiro-account-state-disk.test.ts -654 tests/providers/kiro/kiro-account-state-imports.test.ts -242 tests/providers/kiro/kiro-adapter.test.ts -193 tests/providers/kiro/kiro-auth-context-continuation.test.ts -98 tests/providers/kiro/kiro-auto-selection.test.ts -99 tests/providers/kiro/kiro-builder-id-profile.test.ts -45 tests/providers/kiro/kiro-calibration.test.ts -129 tests/providers/kiro/kiro-completion-with-real-tools.test.ts -88 tests/providers/kiro/kiro-device-builder.test.ts -214 tests/providers/kiro/kiro-device-social.test.ts -92 tests/providers/kiro/kiro-fallback-error-body.test.ts -3046 tests/providers/kiro/kiro-images.test.ts -1260 tests/providers/kiro/kiro-leased-responses.test.ts -48 tests/providers/kiro/kiro-metering-events.test.ts -83 tests/providers/kiro/kiro-metering-usage.test.ts -171 tests/providers/kiro/kiro-model-catalog.test.ts -119 tests/providers/kiro/kiro-model-preference.test.ts -220 tests/providers/kiro/kiro-oauth.test.ts -316 tests/providers/kiro/kiro-org-user-identity.test.ts -427 tests/providers/kiro/kiro-pool-load-settings.test.ts -147 tests/providers/kiro/kiro-pool-rank.test.ts -175 tests/providers/kiro/kiro-quota-metrics.test.ts -93 tests/providers/kiro/kiro-reasoning-roundtrip.test.ts -1587 tests/providers/kiro/kiro-refusal-failover.test.ts -71 tests/providers/kiro/kiro-refusal.test.ts -67 tests/providers/kiro/kiro-remote-image.test.ts -562 tests/providers/kiro/kiro-retry.test.ts -191 tests/providers/kiro/kiro-review-regressions.test.ts -101 tests/providers/kiro/kiro-single-final.test.ts -293 tests/providers/kiro/kiro-stream.test.ts -570 tests/providers/kiro/kiro-transport-parity.test.ts -83 tests/providers/kiro/kiro-usage-quota.test.ts -91 tests/providers/kiro/kiro-usage-restart.test.ts -41 tests/providers/kiro/kiro-windows-cli-db-path.test.ts -42 tests/providers/kiro/kiro-windows-cli-executable-path.test.ts -83 tests/providers/kiro/kiro-wire-estimate.test.ts -110 tests/providers/meta-model-api-provider.test.ts -116 tests/providers/meta-muse-device.test.ts -5190 tests/providers/meta-muse-keychain.test.ts -107 tests/providers/meta-muse-login-order.test.ts -173 tests/providers/meta-muse-oauth.test.ts -140 tests/providers/meta-muse-wonder.test.ts -84 tests/providers/mimo-effort.test.ts +1852 tests/providers/cursor/cursor-transport-retry.test.ts +108 tests/providers/cursor/cursor-ultra-mode.test.ts +104 tests/providers/cursor/cursor-umbrella-rows.test.ts +36 tests/providers/cursor/cursor-uncallable-quarantine.test.ts +93 tests/providers/cursor/cursor-vision-wire-harness.test.ts +308 tests/providers/cyber-policy-error-fidelity.test.ts +116 tests/providers/deepinfra-provider.test.ts +58 tests/providers/deepseek-artifact-tool-schema.test.ts +134 tests/providers/deepseek-bare-tool-call-replay.test.ts +10110 tests/providers/deepseek-image-files.test.ts +579 tests/providers/deepseek-inbound-wire.test.ts +97 tests/providers/deepseek-quota-currency.test.ts +124 tests/providers/deepseek-reasoning-replay-gaps.test.ts +142 tests/providers/deepseek-reasoning-replay.test.ts +442 tests/providers/deepseek-responses-item-id-repair.test.ts +2108 tests/providers/devin-adapter-reset-wait.test.ts +170 tests/providers/devin-adapter.test.ts +230 tests/providers/devin-anthropic-signature-fallback.test.ts +243 tests/providers/devin-chat-wire-fixes.test.ts +106 tests/providers/devin-cli-authmode-migration.test.ts +70 tests/providers/devin-effort-ladder.test.ts +128 tests/providers/devin-family-resolution.test.ts +120 tests/providers/devin-hardening.test.ts +101 tests/providers/devin-image-passthrough.test.ts +133 tests/providers/devin-live-models.test.ts +206 tests/providers/devin-login.test.ts +85 tests/providers/devin-output-budget.test.ts +142 tests/providers/devin-prompt-cache.test.ts +63 tests/providers/devin-provider-merge-migration.test.ts +188 tests/providers/devin-quota.test.ts +85 tests/providers/devin-reasoning-continuation.test.ts +44 tests/providers/devin-stated-reset-hardening.test.ts +76 tests/providers/devin-stated-reset-retry.test.ts +108 tests/providers/devin-stream-deadline.test.ts +83 tests/providers/devin-trajectory.test.ts +136 tests/providers/digitalocean-scaleway-provider.test.ts +689 tests/providers/dsh-account.test.ts +143 tests/providers/exa-web-search.test.ts +459 tests/providers/explicit-key-pause-oauth-boundary.test.ts +87 tests/providers/fast-row-ingress.test.ts +131 tests/providers/featherless-provider.test.ts +162 tests/providers/flash-route-image-modalities.test.ts +989 tests/providers/forward-admission-separation.test.ts +96 tests/providers/free-directory-runcrate.test.ts +1121 tests/providers/github-copilot/github-copilot-account-origin.test.ts +1632 tests/providers/github-copilot/github-copilot-auto-runtime.test.ts +87 tests/providers/github-copilot/github-copilot-auto.test.ts +94 tests/providers/github-copilot/github-copilot-catalog-hints.test.ts +121 tests/providers/github-copilot/github-copilot-context-tier.test.ts +16102 tests/providers/github-copilot/github-copilot-oauth.test.ts +74 tests/providers/github-copilot/github-copilot-sse-rewrite.test.ts +517 tests/providers/github-copilot/github-copilot-stream-contract.test.ts +288 tests/providers/github-copilot/github-copilot-wire-defaults.test.ts +1149 tests/providers/gpt61-terra-provider-rows.test.ts +58 tests/providers/haiku-5-5-catalog.test.ts +98 tests/providers/hyperbolic-provider.test.ts +640 tests/providers/initial-model-selection.test.ts +468 tests/providers/initial-selection-write-fence.test.ts +239 tests/providers/jev-provider.test.ts +118 tests/providers/kimi-oauth-identity.test.ts +125 tests/providers/kimi-responses-adjacency.test.ts +55 tests/providers/kiro/kiro-account-load.test.ts +231 tests/providers/kiro/kiro-account-quota.test.ts +4042 tests/providers/kiro/kiro-account-state-disk.test.ts +843 tests/providers/kiro/kiro-account-state-imports.test.ts +212 tests/providers/kiro/kiro-adapter.test.ts +348 tests/providers/kiro/kiro-auth-context-continuation.test.ts +102 tests/providers/kiro/kiro-auto-selection.test.ts +135 tests/providers/kiro/kiro-builder-id-profile.test.ts +40 tests/providers/kiro/kiro-calibration.test.ts +113 tests/providers/kiro/kiro-completion-with-real-tools.test.ts +161 tests/providers/kiro/kiro-device-builder.test.ts +170 tests/providers/kiro/kiro-device-iam.test.ts +301 tests/providers/kiro/kiro-device-social.test.ts +74 tests/providers/kiro/kiro-fallback-error-body.test.ts +2842 tests/providers/kiro/kiro-images.test.ts +1560 tests/providers/kiro/kiro-leased-responses.test.ts +46 tests/providers/kiro/kiro-metering-events.test.ts +71 tests/providers/kiro/kiro-metering-usage.test.ts +194 tests/providers/kiro/kiro-model-catalog.test.ts +222 tests/providers/kiro/kiro-model-preference.test.ts +210 tests/providers/kiro/kiro-oauth.test.ts +318 tests/providers/kiro/kiro-org-user-identity.test.ts +692 tests/providers/kiro/kiro-pool-load-settings.test.ts +153 tests/providers/kiro/kiro-pool-rank.test.ts +129 tests/providers/kiro/kiro-quota-metrics.test.ts +101 tests/providers/kiro/kiro-reasoning-roundtrip.test.ts +1569 tests/providers/kiro/kiro-refusal-failover.test.ts +85 tests/providers/kiro/kiro-refusal.test.ts +76 tests/providers/kiro/kiro-remote-image.test.ts +596 tests/providers/kiro/kiro-retry.test.ts +142 tests/providers/kiro/kiro-review-regressions.test.ts +85 tests/providers/kiro/kiro-single-final.test.ts +263 tests/providers/kiro/kiro-stream.test.ts +536 tests/providers/kiro/kiro-transport-parity.test.ts +74 tests/providers/kiro/kiro-usage-quota.test.ts +149 tests/providers/kiro/kiro-usage-restart.test.ts +56 tests/providers/kiro/kiro-windows-cli-db-path.test.ts +59 tests/providers/kiro/kiro-windows-cli-executable-path.test.ts +123 tests/providers/kiro/kiro-wire-estimate.test.ts +117 tests/providers/meta-model-api-provider.test.ts +161 tests/providers/meta-muse-device.test.ts +5225 tests/providers/meta-muse-keychain.test.ts +73 tests/providers/meta-muse-login-order.test.ts +154 tests/providers/meta-muse-oauth.test.ts +157 tests/providers/meta-muse-wonder.test.ts +67 tests/providers/mimo-effort.test.ts 183 tests/providers/mimo-free-provider.test.ts -122 tests/providers/mimo-token-plan-capacity.test.ts -118 tests/providers/mimo-token-plan-provider.test.ts -145 tests/providers/mimo-v26-catalog.test.ts -394 tests/providers/minimax-clients.test.ts -1489 tests/providers/minimax-combo-image-input.test.ts -119 tests/providers/minimax-quota.test.ts -125 tests/providers/minimax-reasoning-split.test.ts -437 tests/providers/mistral-recovery.test.ts +229 tests/providers/mimo-token-plan-capacity.test.ts +131 tests/providers/mimo-token-plan-provider.test.ts +131 tests/providers/mimo-v26-catalog.test.ts +446 tests/providers/minimax-clients.test.ts +1415 tests/providers/minimax-combo-image-input.test.ts +145 tests/providers/minimax-quota.test.ts +122 tests/providers/minimax-reasoning-split.test.ts +574 tests/providers/mistral-recovery.test.ts 48 tests/providers/model-presets.test.ts -176 tests/providers/model-rename-migration.test.ts -108 tests/providers/model-roster-seed-repair.test.ts -128 tests/providers/modelflare-provider.test.ts -46 tests/providers/moonshot-developer-role.test.ts -44 tests/providers/moonshot-endpoints.test.ts -343 tests/providers/moonshot-tool-schema.test.ts -44 tests/providers/muse-key-quota.test.ts -946 tests/providers/muse-passive-quota-cache.test.ts -123 tests/providers/muse-passive-quota-observation.test.ts -99 tests/providers/muse-spark-web-search-compat.test.ts -81 tests/providers/muse-subscription-usage.test.ts -126 tests/providers/muse-tool-name-alias.test.ts -199 tests/providers/new-model-policy-runtime.test.ts +177 tests/providers/model-rename-migration.test.ts +82 tests/providers/model-roster-seed-repair.test.ts +146 tests/providers/modelflare-provider.test.ts +40 tests/providers/moonshot-developer-role.test.ts +36 tests/providers/moonshot-endpoints.test.ts +324 tests/providers/moonshot-tool-schema.test.ts +43 tests/providers/muse-key-quota.test.ts +1004 tests/providers/muse-passive-quota-cache.test.ts +130 tests/providers/muse-passive-quota-observation.test.ts +109 tests/providers/muse-spark-web-search-compat.test.ts +52 tests/providers/muse-subscription-usage.test.ts +117 tests/providers/muse-tool-name-alias.test.ts +214 tests/providers/new-model-policy-runtime.test.ts 40 tests/providers/new-model-policy.test.ts 74 tests/providers/nous-oauth-live.test.ts -8210 tests/providers/nous-oauth.test.ts -114 tests/providers/novita-provider.test.ts -198 tests/providers/nscale-vultr-provider.test.ts -127 tests/providers/nvidia-nim-hardening.test.ts -466 tests/providers/ollama/ollama-native-parser.test.ts -103 tests/providers/ollama/ollama-native-reasoning-wire.test.ts -39 tests/providers/ollama/ollama-native-structured-output.test.ts -238 tests/providers/ollama/ollama-native-tool-continuations.test.ts -480 tests/providers/ollama/ollama-native-v4.test.ts -106 tests/providers/ollama/ollama-native.test.ts -466 tests/providers/ollama/ollama-show-enrichment-v7.test.ts -123 tests/providers/ollama/ollama-show-enrichment.test.ts -302 tests/providers/ollama/ollama-show-ignore-abort.test.ts -256 tests/providers/opencode-cli.test.ts -104 tests/providers/opencode-go-deepseek.test.ts -359 tests/providers/opencode-go-gemini-wire.test.ts -176 tests/providers/opencode-go-grok46-responses.test.ts -461 tests/providers/opencode-go-luna-wire.test.ts -406 tests/providers/opencode-go-model-protocols.test.ts -102 tests/providers/opencode-go-muse-context.test.ts -83 tests/providers/opencode-go-muse-vision.test.ts -74 tests/providers/opencode-go-quota.test.ts -1416 tests/providers/opencode-go-session-header.test.ts -532 tests/providers/opencode-management-transport.test.ts -46 tests/providers/opencode-muse-terminal-repair.test.ts -137 tests/providers/opencode-zen-deepseek-reasoning.test.ts -285 tests/providers/opencode-zen-gemini-wire.test.ts -70 tests/providers/opencode-zen-rate-limit.test.ts -44 tests/providers/opengateway-key-validation.test.ts -154 tests/providers/opengateway-provider.test.ts -112 tests/providers/openrouter-provider-routing.test.ts -85 tests/providers/openrouter-quota-reset-cooldown-4024.test.ts -162 tests/providers/opper-provider.test.ts -181 tests/providers/orcarouter-provider.test.ts -129 tests/providers/provider-account-quota-failure-reasons.test.ts -2934 tests/providers/provider-account-quota-persistence.test.ts -485 tests/providers/provider-account-quota.test.ts -77 tests/providers/provider-anthropic-instance-quota.test.ts -84 tests/providers/provider-anthropic-instance.test.ts -84 tests/providers/provider-antigravity-effort-families.test.ts -172 tests/providers/provider-antigravity-family-catalog.test.ts -79 tests/providers/provider-antigravity-model-quota.test.ts -83 tests/providers/provider-antigravity-quota-retry.test.ts -2386 tests/providers/provider-antigravity-wire-snapshot.test.ts -648 tests/providers/provider-api-keys.test.ts -45 tests/providers/provider-capacity.test.ts -346 tests/providers/provider-completion-test-authority.test.ts -297 tests/providers/provider-completion-test-ingress.test.ts -386 tests/providers/provider-completion-test.test.ts -373 tests/providers/provider-config-batch-management.test.ts -56 tests/providers/provider-config-validation.test.ts -328 tests/providers/provider-connection-test.test.ts -81 tests/providers/provider-cost-overlay-config.test.ts -47 tests/providers/provider-discovery-log-suppression.test.ts -51 tests/providers/provider-egress-outbound.test.ts -55 tests/providers/provider-id-rewrite.test.ts -175 tests/providers/provider-input-modalities.test.ts -492 tests/providers/provider-key-store.test.ts -108 tests/providers/provider-live-models.test.ts -124 tests/providers/provider-model-aliases.test.ts -171 tests/providers/provider-model-discovery-contract.test.ts -46 tests/providers/provider-outbound-private-network.test.ts -528 tests/providers/provider-outbound.test.ts -98 tests/providers/provider-quota-abliteration.test.ts -160 tests/providers/provider-quota-label-sanitize.test.ts -153 tests/providers/provider-quota-observed-marker.test.ts -97 tests/providers/provider-quota-ollama-cloud.test.ts -589 tests/providers/provider-quota.test.ts -260 tests/providers/provider-registry-parity.test.ts -42 tests/providers/provider-runtime-fetch.test.ts -88 tests/providers/provider-static-model-discovery.test.ts -85 tests/providers/provider-tls-profile.test.ts -311 tests/providers/qoder-adapter.test.ts -1278 tests/providers/qoder-cn-image-validation.test.ts -70 tests/providers/qoder-image-input.test.ts -101 tests/providers/qoder-live-models.test.ts -170 tests/providers/qoder-mcp-server.test.ts -97 tests/providers/qoder-scaffold-guard.test.ts -58 tests/providers/qwen38-preserve-reasoning.test.ts -293 tests/providers/rate-limit-retry.test.ts -84 tests/providers/registry-transport-alias.test.ts -151 tests/providers/resolved-model-policy.test.ts -140 tests/providers/sambanova-nebius-provider.test.ts -123 tests/providers/sponsor-presets.test.ts -153 tests/providers/stepfun-provider.test.ts -211 tests/providers/tokenlab-protocols.test.ts -118 tests/providers/tokenlab-provider.test.ts -126 tests/providers/umans-provider.test.ts -7268 tests/providers/upstream-transient-retry.test.ts -122 tests/providers/vercel-gateway-provider-routing.test.ts -97 tests/providers/vision-classification-seed-repair.test.ts -49 tests/providers/volcengine-ark-assistant-content.test.ts -497 tests/providers/workbuddy-provider.test.ts -132 tests/providers/workbuddy-quota.test.ts -46 tests/providers/xai/grok-47-build-fast-metadata.test.ts -5783 tests/providers/xai/grok-47-fast-model-wire.test.ts -108 tests/providers/xai/grok-47-fast-model.test.ts -197 tests/providers/xai/grok-attribution.test.ts -292 tests/providers/xai/grok-config-inject.test.ts -109 tests/providers/xai/grok-config-write-lock.test.ts -420 tests/providers/xai/grok-coupon-claim.test.ts -120 tests/providers/xai/grok-coupon-reconcile.test.ts -186 tests/providers/xai/grok-effort-inject.test.ts -126 tests/providers/xai/grok-lifecycle.test.ts -831 tests/providers/xai/grok-management-api.test.ts -598 tests/providers/xai/grok-models-effort-list.test.ts -332 tests/providers/xai/grok-orphan-adoption.test.ts -81 tests/providers/xai/grok-reset-coupon-cli.test.ts -78 tests/providers/xai/grok-reset-coupons.test.ts -119 tests/providers/xai/grok-selection.test.ts -168 tests/providers/xai/grok-session-identity.test.ts -111 tests/providers/xai/grok-status.test.ts -156 tests/providers/xai/grok-sync.test.ts -138 tests/providers/xai/grok-writer-boundary.test.ts -102 tests/providers/xai/xai-empty-catalog-tool-choice.test.ts -102 tests/providers/xai/xai-no-stop.test.ts -45 tests/providers/xai/xai-oauth-retry.test.ts -191 tests/providers/xai/xai-refresh-lock.test.ts -94 tests/providers/xai/xai-responses-adjacency.test.ts -73 tests/providers/xai/xai-tool-schema.test.ts -130 tests/providers/xai/xai-transport.test.ts -92 tests/providers/xai/xai-web-search-compat.test.ts -111 tests/providers/xai/xai-web-search.test.ts -101 tests/providers/zai-reasoning-replay.test.ts -517 tests/providers/zcode-client.test.ts -193 tests/providers/zed-argument-consistency.test.ts -142 tests/providers/zed-failure-relay.test.ts -269 tests/providers/zed-hosted-provider.test.ts -578 tests/providers/zed-lossless-arguments.test.ts -178 tests/providers/zed-openai-contract.test.ts -126 tests/providers/zed-retained-budget.test.ts -147 tests/providers/zhipu-bigmodel-provider.test.ts -77 tests/providers/zhipu-bigmodel-responses-quota.test.ts -642 tests/responses/agent-assertion-routes.test.ts -723 tests/responses/anthropic2-responses-parity.test.ts -48 tests/responses/apply-patch-envelope.test.ts -151 tests/responses/bare-echo-alias.test.ts -434 tests/responses/chat-anthropic-reasoning-details.test.ts -383 tests/responses/chat-completions-deferred-tools.test.ts -12786 tests/responses/chat-completions-endpoint.test.ts -504 tests/responses/chat-completions-pool-mode.test.ts -5018 tests/responses/chat-conversation-affinity.test.ts -377 tests/responses/chat-inbound-developer-position.test.ts -43 tests/responses/chat-inbound-reasoning-none.test.ts -101 tests/responses/chat-inbound-reasoning-replay.test.ts -271 tests/responses/chat-incomplete-length-reason.test.ts -125 tests/responses/chat-inline-document-bytes.test.ts -316 tests/responses/chat-json-sse-fallback.test.ts -1389 tests/responses/chat-legacy-functions-combo.test.ts -349 tests/responses/chat-media-translation.test.ts -3083 tests/responses/chat-native-combo.test.ts -132 tests/responses/chat-native-decline-reason.test.ts +8207 tests/providers/nous-oauth.test.ts +104 tests/providers/novita-provider.test.ts +167 tests/providers/nscale-vultr-provider.test.ts +122 tests/providers/nvidia-nim-hardening.test.ts +441 tests/providers/ollama/ollama-native-parser.test.ts +113 tests/providers/ollama/ollama-native-reasoning-wire.test.ts +67 tests/providers/ollama/ollama-native-scaling.test.ts +41 tests/providers/ollama/ollama-native-structured-output.test.ts +227 tests/providers/ollama/ollama-native-tool-continuations.test.ts +410 tests/providers/ollama/ollama-native-v4.test.ts +104 tests/providers/ollama/ollama-native.test.ts +603 tests/providers/ollama/ollama-show-enrichment-v7.test.ts +112 tests/providers/ollama/ollama-show-enrichment.test.ts +299 tests/providers/ollama/ollama-show-ignore-abort.test.ts +354 tests/providers/opencode-cli.test.ts +91 tests/providers/opencode-go-deepseek.test.ts +420 tests/providers/opencode-go-gemini-wire.test.ts +185 tests/providers/opencode-go-grok46-responses.test.ts +581 tests/providers/opencode-go-luna-wire.test.ts +677 tests/providers/opencode-go-model-protocols.test.ts +91 tests/providers/opencode-go-muse-context.test.ts +87 tests/providers/opencode-go-muse-vision.test.ts +111 tests/providers/opencode-go-quota.test.ts +1472 tests/providers/opencode-go-session-header.test.ts +627 tests/providers/opencode-management-transport.test.ts +41 tests/providers/opencode-muse-terminal-repair.test.ts +77 tests/providers/opencode-zen-deepseek-reasoning.test.ts +366 tests/providers/opencode-zen-gemini-wire.test.ts +51 tests/providers/opencode-zen-rate-limit.test.ts +40 tests/providers/opengateway-key-validation.test.ts +174 tests/providers/opengateway-provider.test.ts +118 tests/providers/openrouter-provider-routing.test.ts +79 tests/providers/openrouter-quota-reset-cooldown-4024.test.ts +241 tests/providers/opper-provider.test.ts +199 tests/providers/orcarouter-provider.test.ts +127 tests/providers/provider-account-quota-failure-reasons.test.ts +4506 tests/providers/provider-account-quota-persistence.test.ts +403 tests/providers/provider-account-quota.test.ts +70 tests/providers/provider-anthropic-instance-quota.test.ts +90 tests/providers/provider-anthropic-instance.test.ts +79 tests/providers/provider-anthropic-usage-windows.test.ts +79 tests/providers/provider-antigravity-effort-families.test.ts +225 tests/providers/provider-antigravity-family-catalog.test.ts +133 tests/providers/provider-antigravity-model-quota.test.ts +72 tests/providers/provider-antigravity-quota-retry.test.ts +2455 tests/providers/provider-antigravity-wire-snapshot.test.ts +657 tests/providers/provider-api-keys.test.ts +48 tests/providers/provider-capacity.test.ts +763 tests/providers/provider-completion-test-authority.test.ts +450 tests/providers/provider-completion-test-ingress.test.ts +341 tests/providers/provider-completion-test.test.ts +323 tests/providers/provider-config-batch-management.test.ts +53 tests/providers/provider-config-validation.test.ts +402 tests/providers/provider-connection-test.test.ts +77 tests/providers/provider-cost-overlay-config.test.ts +48 tests/providers/provider-discovery-log-suppression.test.ts +47 tests/providers/provider-egress-outbound.test.ts +49 tests/providers/provider-id-rewrite.test.ts +256 tests/providers/provider-input-modalities.test.ts +410 tests/providers/provider-key-store.test.ts +118 tests/providers/provider-live-models.test.ts +164 tests/providers/provider-model-aliases.test.ts +182 tests/providers/provider-model-discovery-contract.test.ts +61 tests/providers/provider-outbound-private-network.test.ts +462 tests/providers/provider-outbound.test.ts +83 tests/providers/provider-quota-abliteration.test.ts +88 tests/providers/provider-quota-label-sanitize.test.ts +137 tests/providers/provider-quota-observed-marker.test.ts +93 tests/providers/provider-quota-ollama-cloud.test.ts +772 tests/providers/provider-quota.test.ts +383 tests/providers/provider-registry-parity.test.ts +39 tests/providers/provider-runtime-fetch.test.ts +101 tests/providers/provider-static-model-discovery.test.ts +515 tests/providers/provider-tls-profile.test.ts +317 tests/providers/qoder-adapter.test.ts +1193 tests/providers/qoder-cn-image-validation.test.ts +65 tests/providers/qoder-image-input.test.ts +158 tests/providers/qoder-live-models.test.ts +165 tests/providers/qoder-mcp-server.test.ts +157 tests/providers/qoder-scaffold-guard.test.ts +59 tests/providers/qwen38-preserve-reasoning.test.ts +286 tests/providers/rate-limit-retry.test.ts +90 tests/providers/registry-transport-alias.test.ts +248 tests/providers/resolved-model-policy.test.ts +178 tests/providers/sambanova-nebius-provider.test.ts +191 tests/providers/sponsor-presets.test.ts +219 tests/providers/stepfun-provider.test.ts +286 tests/providers/tokenlab-protocols.test.ts +127 tests/providers/tokenlab-provider.test.ts +165 tests/providers/umans-provider.test.ts +7583 tests/providers/upstream-transient-retry.test.ts +79 tests/providers/vercel-gateway-provider-routing.test.ts +86 tests/providers/vision-classification-seed-repair.test.ts +77 tests/providers/volcengine-ark-assistant-content.test.ts +491 tests/providers/workbuddy-provider.test.ts +116 tests/providers/workbuddy-quota.test.ts +39 tests/providers/xai/grok-47-build-fast-metadata.test.ts +6418 tests/providers/xai/grok-47-fast-model-wire.test.ts +184 tests/providers/xai/grok-47-fast-model.test.ts +147 tests/providers/xai/grok-attribution.test.ts +242 tests/providers/xai/grok-config-inject.test.ts +108 tests/providers/xai/grok-config-write-lock.test.ts +603 tests/providers/xai/grok-coupon-claim.test.ts +93 tests/providers/xai/grok-coupon-reconcile.test.ts +164 tests/providers/xai/grok-effort-inject.test.ts +121 tests/providers/xai/grok-lifecycle.test.ts +1003 tests/providers/xai/grok-management-api.test.ts +580 tests/providers/xai/grok-models-effort-list.test.ts +494 tests/providers/xai/grok-orphan-adoption.test.ts +76 tests/providers/xai/grok-reset-coupon-cli.test.ts +93 tests/providers/xai/grok-reset-coupons.test.ts +144 tests/providers/xai/grok-selection.test.ts +332 tests/providers/xai/grok-session-identity.test.ts +119 tests/providers/xai/grok-status.test.ts +151 tests/providers/xai/grok-sync.test.ts +183 tests/providers/xai/grok-writer-boundary.test.ts +96 tests/providers/xai/xai-additional-tools.test.ts +104 tests/providers/xai/xai-empty-catalog-tool-choice.test.ts +441 tests/providers/xai/xai-loaded-tool-provenance.test.ts +91 tests/providers/xai/xai-no-stop.test.ts +65 tests/providers/xai/xai-oauth-retry.test.ts +253 tests/providers/xai/xai-refresh-lock.test.ts +119 tests/providers/xai/xai-replay-provenance.test.ts +122 tests/providers/xai/xai-responses-adjacency.test.ts +97 tests/providers/xai/xai-tool-schema.test.ts +160 tests/providers/xai/xai-transport.test.ts +116 tests/providers/xai/xai-web-search-compat.test.ts +104 tests/providers/xai/xai-web-search.test.ts +73 tests/providers/zai-reasoning-replay.test.ts +527 tests/providers/zcode-client.test.ts +167 tests/providers/zed-argument-consistency.test.ts +91 tests/providers/zed-failure-relay.test.ts +287 tests/providers/zed-hosted-provider.test.ts +409 tests/providers/zed-lossless-arguments.test.ts +147 tests/providers/zed-openai-contract.test.ts +101 tests/providers/zed-retained-budget.test.ts +80 tests/providers/zhipu-bigmodel-provider.test.ts +78 tests/providers/zhipu-bigmodel-responses-quota.test.ts +748 tests/responses/agent-assertion-routes.test.ts +769 tests/responses/anthropic2-responses-parity.test.ts +63 tests/responses/apply-patch-envelope.test.ts +115 tests/responses/bare-echo-alias.test.ts +585 tests/responses/chat-anthropic-reasoning-details.test.ts +422 tests/responses/chat-completions-deferred-tools.test.ts +13784 tests/responses/chat-completions-endpoint.test.ts +724 tests/responses/chat-completions-pool-mode.test.ts +5474 tests/responses/chat-conversation-affinity.test.ts +345 tests/responses/chat-inbound-developer-position.test.ts +52 tests/responses/chat-inbound-reasoning-none.test.ts +164 tests/responses/chat-inbound-reasoning-replay.test.ts +423 tests/responses/chat-incomplete-length-reason.test.ts +105 tests/responses/chat-inline-document-bytes.test.ts +454 tests/responses/chat-json-sse-fallback.test.ts +1428 tests/responses/chat-legacy-functions-combo.test.ts +346 tests/responses/chat-media-translation.test.ts +3690 tests/responses/chat-native-combo.test.ts +235 tests/responses/chat-native-decline-reason.test.ts 672 tests/responses/chat-native-developer-role.test.ts -143 tests/responses/chat-native-image-normalization.test.ts -49 tests/responses/chat-native-lenient-finish.test.ts -1131 tests/responses/chat-native-reasoning-replay.test.ts -101 tests/responses/chat-native-reasoning-scope.test.ts -18888 tests/responses/chat-native-spend.test.ts -301 tests/responses/chat-native-sse-stall.test.ts -1275 tests/responses/chat-raw-reasoning-delivery.test.ts -48 tests/responses/chat-refusal-scope.test.ts -196 tests/responses/chat-refusal.test.ts -1210 tests/responses/chat-request-id-endpoint.test.ts -356 tests/responses/chat-responses-control-integration.test.ts -81 tests/responses/chat-responses-control-scope.test.ts -325 tests/responses/chat-sse-framing-guard.test.ts -58 tests/responses/chat-tool-choice-allowed-tools.test.ts -57 tests/responses/citation-markers.test.ts -2371 tests/responses/codex-0164-request-compat.test.ts -2062 tests/responses/codex-ws-handshake-validation.test.ts -95 tests/responses/codex-ws-handshake.test.ts -51 tests/responses/codex-ws-pool-contention.test.ts -727 tests/responses/combo-replay-refusal-attribution.test.ts -456 tests/responses/compact-key-selection.test.ts -11058 tests/responses/compact-transient-alternate.test.ts -91 tests/responses/compaction-continuation-note.test.ts -290 tests/responses/compaction-continuation-wire.test.ts -109 tests/responses/compaction-event-ownership.test.ts -255 tests/responses/compaction-history-framing.test.ts -203 tests/responses/compaction-portable-history.test.ts -100 tests/responses/compaction-progress.test.ts -66 tests/responses/continuation-dedup.test.ts -57 tests/responses/custom-tool-compat.test.ts -170 tests/responses/direct-credit-renewal-ingress.test.ts -1004 tests/responses/droid-reasoning-defaults.test.ts -528 tests/responses/empty-completion-core.test.ts -61 tests/responses/empty-completion-guard.test.ts -1175 tests/responses/empty-completion-hardening.test.ts -45 tests/responses/eventstream-decoder.test.ts -84 tests/responses/eventstream-fragmentation.test.ts -688 tests/responses/explicit-empty-tool-catalog-history.test.ts -1264 tests/responses/explicit-empty-tool-catalog.test.ts -153 tests/responses/external-task-input-repair.test.ts -38 tests/responses/fix-eventstream-cancel-wait.test.ts -145 tests/responses/fresh-connection-optout.test.ts -1847 tests/responses/incomplete-reason-normalization.test.ts -837 tests/responses/jev-initial-effort-wire.test.ts -44 tests/responses/legacy-shell-compat.test.ts -336 tests/responses/local-upstream-deadlines.test.ts -151 tests/responses/messages-native-bridge-policy.test.ts -127 tests/responses/messages-native-eligibility.test.ts -109 tests/responses/messages-native-oauth-eligibility.test.ts -53 tests/responses/namespace-tool-compat.test.ts -265 tests/responses/native-compaction-gateway-credentials.test.ts -635 tests/responses/native-compaction-gateway-policy.test.ts -4133 tests/responses/native-compaction-gateway.test.ts -170 tests/responses/native-compaction-oauth.test.ts -740 tests/responses/native-compaction-provenance.test.ts -150 tests/responses/opaque-blob-wrapped-rejection.test.ts -324 tests/responses/openai-responses-passthrough.test.ts -133 tests/responses/openai-responses-summary-none.test.ts -112 tests/responses/opengateway-completion-receipts.test.ts -42 tests/responses/parser-content-audio.test.ts -279 tests/responses/passthrough-abort.test.ts -2636 tests/responses/passthrough-deferred-tools.test.ts -62 tests/responses/passthrough-grok-upstream-envelope-echo.test.ts -213 tests/responses/passthrough-headers.test.ts -161 tests/responses/passthrough-media-type.test.ts -99 tests/responses/passthrough-override.test.ts -109 tests/responses/plaintext-v2-agent-messages.test.ts -729 tests/responses/protocol-antigravity-direct-chat.test.ts -134 tests/responses/protocol-antigravity-direct-eligibility.test.ts -419 tests/responses/protocol-antigravity-direct-messages.test.ts -1137 tests/responses/protocol-argon-thought-boundary.test.ts -46 tests/responses/protocol-baseline.test.ts -63 tests/responses/protocol-chat-ir-parity.test.ts -52 tests/responses/protocol-contract.test.ts -113 tests/responses/protocol-direct-encoders-chat.test.ts -59 tests/responses/protocol-direct-encoders-local-upstream.test.ts -145 tests/responses/protocol-direct-encoders-messages.test.ts -50 tests/responses/protocol-direct-encoders-stall-disabled.test.ts -47 tests/responses/protocol-dto.test.ts -78 tests/responses/protocol-envelope.test.ts +136 tests/responses/chat-native-image-normalization.test.ts +58 tests/responses/chat-native-lenient-finish.test.ts +1644 tests/responses/chat-native-reasoning-replay.test.ts +121 tests/responses/chat-native-reasoning-scope.test.ts +19521 tests/responses/chat-native-spend.test.ts +295 tests/responses/chat-native-sse-stall.test.ts +1400 tests/responses/chat-raw-reasoning-delivery.test.ts +38 tests/responses/chat-refusal-scope.test.ts +235 tests/responses/chat-refusal.test.ts +1661 tests/responses/chat-request-id-endpoint.test.ts +825 tests/responses/chat-responses-control-integration.test.ts +140 tests/responses/chat-responses-control-scope.test.ts +406 tests/responses/chat-sse-framing-guard.test.ts +86 tests/responses/chat-tool-choice-allowed-tools.test.ts +80 tests/responses/citation-markers.test.ts +1968 tests/responses/codex-0164-request-compat.test.ts +297 tests/responses/codex-installation-compact-empty.test.ts +449 tests/responses/codex-installation-failover.test.ts +345 tests/responses/codex-installation-turn-limit.test.ts +2098 tests/responses/codex-ws-handshake-validation.test.ts +123 tests/responses/codex-ws-handshake.test.ts +106 tests/responses/codex-ws-pool-contention.test.ts +1124 tests/responses/combo-replay-refusal-attribution.test.ts +673 tests/responses/compact-key-selection.test.ts +11289 tests/responses/compact-transient-alternate.test.ts +144 tests/responses/compaction-continuation-note.test.ts +328 tests/responses/compaction-continuation-wire.test.ts +144 tests/responses/compaction-event-ownership.test.ts +233 tests/responses/compaction-history-framing.test.ts +229 tests/responses/compaction-portable-history.test.ts +78 tests/responses/compaction-progress.test.ts +92 tests/responses/continuation-dedup.test.ts +58 tests/responses/custom-tool-compat.test.ts +325 tests/responses/direct-credit-renewal-ingress.test.ts +1435 tests/responses/droid-reasoning-defaults.test.ts +805 tests/responses/empty-completion-core.test.ts +53 tests/responses/empty-completion-guard.test.ts +1219 tests/responses/empty-completion-hardening.test.ts +47 tests/responses/eventstream-decoder.test.ts +119 tests/responses/eventstream-fragmentation.test.ts +1038 tests/responses/explicit-empty-tool-catalog-history.test.ts +2007 tests/responses/explicit-empty-tool-catalog.test.ts +161 tests/responses/external-task-input-repair.test.ts +37 tests/responses/fix-eventstream-cancel-wait.test.ts +168 tests/responses/fresh-connection-optout.test.ts +97 tests/responses/graceful-max-output-tokens-exclusions.test.ts +461 tests/responses/graceful-max-output-tokens.test.ts +2705 tests/responses/incomplete-reason-normalization.test.ts +986 tests/responses/jev-initial-effort-wire.test.ts +85 tests/responses/legacy-shell-compat.test.ts +411 tests/responses/local-upstream-deadlines.test.ts +251 tests/responses/messages-native-bridge-policy.test.ts +199 tests/responses/messages-native-eligibility.test.ts +155 tests/responses/messages-native-oauth-eligibility.test.ts +57 tests/responses/namespace-tool-compat.test.ts +402 tests/responses/native-compaction-gateway-credentials.test.ts +814 tests/responses/native-compaction-gateway-policy.test.ts +4017 tests/responses/native-compaction-gateway.test.ts +255 tests/responses/native-compaction-oauth.test.ts +1373 tests/responses/native-compaction-provenance.test.ts +145 tests/responses/opaque-blob-wrapped-rejection.test.ts +538 tests/responses/openai-responses-passthrough.test.ts +200 tests/responses/openai-responses-summary-none.test.ts +166 tests/responses/opengateway-completion-receipts.test.ts +162 tests/responses/parser-content-audio.test.ts +242 tests/responses/passthrough-abort.test.ts +3003 tests/responses/passthrough-deferred-tools.test.ts +87 tests/responses/passthrough-grok-upstream-envelope-echo.test.ts +166 tests/responses/passthrough-headers.test.ts +167 tests/responses/passthrough-media-type.test.ts +84 tests/responses/passthrough-override.test.ts +100 tests/responses/plaintext-v2-agent-messages.test.ts +824 tests/responses/protocol-antigravity-direct-chat.test.ts +252 tests/responses/protocol-antigravity-direct-eligibility.test.ts +439 tests/responses/protocol-antigravity-direct-messages.test.ts +1652 tests/responses/protocol-argon-thought-boundary.test.ts +45 tests/responses/protocol-baseline.test.ts +78 tests/responses/protocol-chat-ir-parity.test.ts +58 tests/responses/protocol-contract.test.ts +123 tests/responses/protocol-direct-encoders-chat.test.ts +67 tests/responses/protocol-direct-encoders-local-upstream.test.ts +82 tests/responses/protocol-direct-encoders-messages.test.ts +45 tests/responses/protocol-direct-encoders-stall-disabled.test.ts +63 tests/responses/protocol-dto.test.ts +72 tests/responses/protocol-envelope.test.ts 41 tests/responses/protocol-features.test.ts -52 tests/responses/protocol-guard.test.ts -288 tests/responses/protocol-ingress-guard.test.ts -128 tests/responses/protocol-messages-ir-parity.test.ts -49 tests/responses/protocol-opaque-state.test.ts -43 tests/responses/protocol-path.test.ts -132 tests/responses/protocol-plan-snapshot.test.ts -41 tests/responses/protocol-plan.test.ts -127 tests/responses/protocol-shadow-plan.test.ts -50 tests/responses/protocol-trace.test.ts -52 tests/responses/provider-egress-fetch.test.ts -411 tests/responses/reasoning-archive-http.test.ts -626 tests/responses/reasoning-archive-ws.test.ts -223 tests/responses/reasoning-effort-summary-default.test.ts -190 tests/responses/reasoning-envelope.test.ts -92 tests/responses/reasoning-retention-quota.test.ts -1631 tests/responses/reasoning-retention-routing.test.ts -589 tests/responses/reasoning-retention-v2.test.ts -89 tests/responses/reasoning-retention.test.ts -501 tests/responses/refreshed-upstream-deadlines.test.ts -106 tests/responses/reserve-dispatch-ws.test.ts -101 tests/responses/responses-4546-incident-regression.test.ts -611 tests/responses/responses-account-auto-pause-wire-owner.test.ts -1018 tests/responses/responses-account-auto-pause.test.ts +41 tests/responses/protocol-guard.test.ts +216 tests/responses/protocol-ingress-guard.test.ts +112 tests/responses/protocol-messages-ir-parity.test.ts +50 tests/responses/protocol-opaque-state.test.ts +38 tests/responses/protocol-path.test.ts +121 tests/responses/protocol-plan-snapshot.test.ts +49 tests/responses/protocol-plan.test.ts +111 tests/responses/protocol-shadow-plan.test.ts +85 tests/responses/protocol-trace.test.ts +39 tests/responses/provider-egress-fetch.test.ts +551 tests/responses/reasoning-archive-http.test.ts +548 tests/responses/reasoning-archive-ws.test.ts +220 tests/responses/reasoning-effort-summary-default.test.ts +212 tests/responses/reasoning-envelope.test.ts +115 tests/responses/reasoning-retention-quota.test.ts +1371 tests/responses/reasoning-retention-routing.test.ts +633 tests/responses/reasoning-retention-v2.test.ts +71 tests/responses/reasoning-retention.test.ts +618 tests/responses/refreshed-upstream-deadlines.test.ts +127 tests/responses/reserve-dispatch-ws.test.ts +92 tests/responses/responses-4546-incident-regression.test.ts +637 tests/responses/responses-account-auto-pause-wire-owner.test.ts +976 tests/responses/responses-account-auto-pause.test.ts 94 tests/responses/responses-account-change-scrub.test.ts -2889 tests/responses/responses-account-label.test.ts -369 tests/responses/responses-alternate-main-cancellation.test.ts -442 tests/responses/responses-anthropic-billing-send-budget.test.ts -190 tests/responses/responses-anthropic-compaction-prefix.test.ts -243 tests/responses/responses-anthropic-fast-downgrade.test.ts -198 tests/responses/responses-anthropic-legal-history.test.ts -94 tests/responses/responses-anthropic-thinking-recovery.test.ts -963 tests/responses/responses-anthropic-thinking-signature-recovery.test.ts -324 tests/responses/responses-auto-pause-replay-owner.test.ts -240 tests/responses/responses-azure-opaque-blob-recovery.test.ts -126 tests/responses/responses-bare-echo-helper-fence.test.ts -49 tests/responses/responses-call-id-linkage.test.ts -544 tests/responses/responses-canonical-nonstream.test.ts -89 tests/responses/responses-canonical-only-top-level-fields.test.ts -164 tests/responses/responses-chat-tool-call-content.test.ts -83 tests/responses/responses-chatgpt-web-replay-metadata.test.ts -129 tests/responses/responses-claude-preflight-lease.test.ts -48 tests/responses/responses-code-mode-goal-helpers.test.ts -130 tests/responses/responses-code-mode-mcp-direct.test.ts -57 tests/responses/responses-code-mode-patch-compile.test.ts -109 tests/responses/responses-code-mode-shell-compile.test.ts -2751 tests/responses/responses-cold-opaque-recovery.test.ts -312 tests/responses/responses-combo-exhausted-error.test.ts -238 tests/responses/responses-combo-fallback-off.test.ts -212 tests/responses/responses-combo-replay-principal.test.ts -590 tests/responses/responses-combo-run-turn-classified-failure.test.ts -6137 tests/responses/responses-compact-handoff-admission.test.ts -2783 tests/responses/responses-compaction-http-isolation.test.ts -3086 tests/responses/responses-compaction-override.test.ts -139 tests/responses/responses-compaction-policy-identity.test.ts -43 tests/responses/responses-compaction-recovery-policy.test.ts -6689 tests/responses/responses-compaction-recovery.test.ts -3507 tests/responses/responses-compaction-routing.test.ts -250 tests/responses/responses-compaction.test.ts -5955 tests/responses/responses-console-go-upload-retry.test.ts -2746 tests/responses/responses-context-overflow.test.ts -164 tests/responses/responses-continuation-boundaries.test.ts -114 tests/responses/responses-core-modules.test.ts -78 tests/responses/responses-custom-tool-guidance.test.ts -152 tests/responses/responses-custom-tool-historical-replay.test.ts -252 tests/responses/responses-custom-tool-repair-dispatch.test.ts -70 tests/responses/responses-custom-tool-repair.test.ts -84 tests/responses/responses-custom-tool-stream-consistency.test.ts -46 tests/responses/responses-default-namespace-emit-normalize.test.ts -583 tests/responses/responses-devin-401-replay.test.ts -55 tests/responses/responses-dispatch-receipt.test.ts -304 tests/responses/responses-fetch-helpers-boundary.test.ts -49 tests/responses/responses-field-backfill.test.ts -9450 tests/responses/responses-first-send-reservation.test.ts -165 tests/responses/responses-first-send-spend-policy.test.ts -113 tests/responses/responses-forward-client-headers.test.ts -123 tests/responses/responses-forward-dangling-call.test.ts -221 tests/responses/responses-forward-incomplete-quota.test.ts -89 tests/responses/responses-forward-output-cap.test.ts +2784 tests/responses/responses-account-label.test.ts +572 tests/responses/responses-alternate-main-cancellation.test.ts +422 tests/responses/responses-anthropic-billing-send-budget.test.ts +377 tests/responses/responses-anthropic-compaction-prefix.test.ts +339 tests/responses/responses-anthropic-fast-downgrade.test.ts +185 tests/responses/responses-anthropic-legal-history.test.ts +144 tests/responses/responses-anthropic-thinking-recovery.test.ts +973 tests/responses/responses-anthropic-thinking-signature-recovery.test.ts +300 tests/responses/responses-auto-pause-replay-owner.test.ts +276 tests/responses/responses-azure-opaque-blob-recovery.test.ts +131 tests/responses/responses-bare-echo-helper-fence.test.ts +58 tests/responses/responses-call-id-linkage.test.ts +645 tests/responses/responses-canonical-nonstream.test.ts +92 tests/responses/responses-canonical-only-top-level-fields.test.ts +210 tests/responses/responses-chat-tool-call-content.test.ts +100 tests/responses/responses-chatgpt-web-replay-metadata.test.ts +159 tests/responses/responses-claude-preflight-lease.test.ts +50 tests/responses/responses-code-mode-goal-helpers.test.ts +121 tests/responses/responses-code-mode-mcp-direct.test.ts +52 tests/responses/responses-code-mode-patch-compile.test.ts +74 tests/responses/responses-code-mode-shell-compile.test.ts +2831 tests/responses/responses-cold-opaque-recovery.test.ts +232 tests/responses/responses-combo-bridge-usage.test.ts +565 tests/responses/responses-combo-exhausted-error.test.ts +277 tests/responses/responses-combo-fallback-off.test.ts +213 tests/responses/responses-combo-replay-principal.test.ts +621 tests/responses/responses-combo-run-turn-classified-failure.test.ts +6318 tests/responses/responses-compact-handoff-admission.test.ts +2529 tests/responses/responses-compaction-http-isolation.test.ts +3131 tests/responses/responses-compaction-override.test.ts +172 tests/responses/responses-compaction-policy-identity.test.ts +50 tests/responses/responses-compaction-recovery-policy.test.ts +6779 tests/responses/responses-compaction-recovery.test.ts +4561 tests/responses/responses-compaction-routing.test.ts +216 tests/responses/responses-compaction.test.ts +6000 tests/responses/responses-console-go-upload-retry.test.ts +2866 tests/responses/responses-context-overflow.test.ts +125 tests/responses/responses-continuation-boundaries.test.ts +92 tests/responses/responses-core-modules.test.ts +48 tests/responses/responses-custom-tool-guidance.test.ts +202 tests/responses/responses-custom-tool-historical-replay.test.ts +308 tests/responses/responses-custom-tool-repair-dispatch.test.ts +55 tests/responses/responses-custom-tool-repair.test.ts +108 tests/responses/responses-custom-tool-stream-consistency.test.ts +53 tests/responses/responses-default-namespace-emit-normalize.test.ts +1065 tests/responses/responses-devin-401-replay.test.ts +76 tests/responses/responses-dispatch-receipt.test.ts +298 tests/responses/responses-fetch-helpers-boundary.test.ts +80 tests/responses/responses-field-backfill.test.ts +9886 tests/responses/responses-first-send-reservation.test.ts +233 tests/responses/responses-first-send-spend-policy.test.ts +157 tests/responses/responses-forward-client-headers.test.ts +92 tests/responses/responses-forward-dangling-call.test.ts +368 tests/responses/responses-forward-incomplete-quota.test.ts +95 tests/responses/responses-forward-output-cap.test.ts 96 tests/responses/responses-forward-posit-continuation.test.ts 100 tests/responses/responses-forward-prompt-envelope.test.ts -45 tests/responses/responses-forward-transport-baseurl.test.ts -166 tests/responses/responses-freeform-wrapper-keys.test.ts -182 tests/responses/responses-function-tool-repair.test.ts -4655 tests/responses/responses-grok-devin-preflight.test.ts -243 tests/responses/responses-hide-raw-reasoning.test.ts -319 tests/responses/responses-hosted-image-delivery.test.ts -88 tests/responses/responses-hosted-image-display.test.ts -244 tests/responses/responses-hosted-image-limits.test.ts -248 tests/responses/responses-hosted-send-hop.test.ts -313 tests/responses/responses-hosted-send-producer.test.ts -388 tests/responses/responses-hosted-send-reservation.test.ts -191 tests/responses/responses-hosted-send-round-parity.test.ts -412 tests/responses/responses-hosted-send-unsent-hop.test.ts -334 tests/responses/responses-hosted-send-ws.test.ts +62 tests/responses/responses-forward-transport-baseurl.test.ts +163 tests/responses/responses-freeform-wrapper-keys.test.ts +249 tests/responses/responses-function-tool-repair.test.ts +4608 tests/responses/responses-grok-devin-preflight.test.ts +317 tests/responses/responses-hide-raw-reasoning.test.ts +379 tests/responses/responses-hosted-image-delivery.test.ts +85 tests/responses/responses-hosted-image-display.test.ts +460 tests/responses/responses-hosted-image-limits.test.ts +352 tests/responses/responses-hosted-send-hop.test.ts +484 tests/responses/responses-hosted-send-producer.test.ts +523 tests/responses/responses-hosted-send-reservation.test.ts +231 tests/responses/responses-hosted-send-round-parity.test.ts +475 tests/responses/responses-hosted-send-unsent-hop.test.ts +215 tests/responses/responses-hosted-send-ws.test.ts 112 tests/responses/responses-hosted-tool-declaration.test.ts -91 tests/responses/responses-hosted-tool-min-spread.test.ts -169 tests/responses/responses-image-gen-repair.test.ts -777 tests/responses/responses-inbound-store-default.test.ts -50 tests/responses/responses-item-id-repair.test.ts -42 tests/responses/responses-json-events.test.ts -48 tests/responses/responses-legacy-dotted-tool-name-repair.test.ts -386 tests/responses/responses-main-quota-observation.test.ts -240 tests/responses/responses-memory-models.test.ts -65 tests/responses/responses-mimo-envelope.test.ts -175 tests/responses/responses-muse-tool-choice.test.ts -174 tests/responses/responses-muse-tool-name-alias.test.ts -155 tests/responses/responses-native-compact-search-history.test.ts -169 tests/responses/responses-native-item-extensions-compact.test.ts -122 tests/responses/responses-native-item-extensions.test.ts -463 tests/responses/responses-native-key-cooldown.test.ts -826 tests/responses/responses-native-main-refresh.test.ts -677 tests/responses/responses-native-ultra-effort-wire.test.ts -1552 tests/responses/responses-oauth-refresh-capacity.test.ts -5295 tests/responses/responses-opaque-blob-recovery.test.ts -82 tests/responses/responses-parser-agent-message.test.ts -71 tests/responses/responses-parser-malformed-content.test.ts -196 tests/responses/responses-parser.test.ts -96 tests/responses/responses-passthrough-transient-policy.test.ts -63 tests/responses/responses-phase-inference.test.ts -4268 tests/responses/responses-pool-401-refresh.test.ts -8963 tests/responses/responses-pool-overload-failover.test.ts -139 tests/responses/responses-pool-refresh-attribution.test.ts -323 tests/responses/responses-preview-main-read-fence.test.ts -243 tests/responses/responses-reasoning-effort-downgrade.test.ts -218 tests/responses/responses-reasoning-summary-passthrough.test.ts -164 tests/responses/responses-replay-metadata-principal.test.ts -132 tests/responses/responses-request-compression.test.ts -303 tests/responses/responses-required-chat-tool.test.ts -87 tests/responses/responses-reset-replay.test.ts -2886 tests/responses/responses-retained-reasoning-stream-recovery.test.ts -102 tests/responses/responses-routed-web-search-fields.test.ts -195 tests/responses/responses-run-turn-key-pacing.test.ts -249 tests/responses/responses-run-turn-key-readmission.test.ts -707 tests/responses/responses-run-turn-web-search.test.ts -2060 tests/responses/responses-self-named-namespace-scrub.test.ts -6354 tests/responses/responses-send-budget-counts.test.ts -451 tests/responses/responses-send-budget-errors.test.ts -336 tests/responses/responses-shadow-intercept.test.ts -244 tests/responses/responses-show-thinking-summary.test.ts -890 tests/responses/responses-sidecar-context-overflow.test.ts -219 tests/responses/responses-sidecar-usage.test.ts -232 tests/responses/responses-skills-snapshot.test.ts -679 tests/responses/responses-snapshot-repair-server.test.ts -174 tests/responses/responses-snapshot-repair.test.ts -109 tests/responses/responses-sparse-terminal-tool-scope.test.ts -1727 tests/responses/responses-spend-anchor.test.ts -93 tests/responses/responses-spend-capacity-guard.test.ts -165 tests/responses/responses-spend-contract-c.test.ts -131 tests/responses/responses-spend-ledger-wiring.test.ts -56 tests/responses/responses-spill-acl-recovery.test.ts -250 tests/responses/responses-spill-admission-headroom.test.ts -74 tests/responses/responses-spill-inspection.test.ts -72 tests/responses/responses-spill-orphan-sweep.test.ts -280 tests/responses/responses-spill-shutdown-clock.test.ts -48 tests/responses/responses-state-flush-race.test.ts -86 tests/responses/responses-state-snapshot-select.test.ts -73 tests/responses/responses-state-snapshot-stubs.test.ts -379 tests/responses/responses-state-store-false.test.ts -184 tests/responses/responses-state-write-amplification.test.ts -7275 tests/responses/responses-state.test.ts -634 tests/responses/responses-stateless-dangling-call-repair.test.ts -52 tests/responses/responses-stream-tool-events.test.ts -104 tests/responses/responses-terminal-repair.test.ts -98 tests/responses/responses-tool-conformance.test.ts -41 tests/responses/responses-tool-groups.test.ts -164 tests/responses/responses-tool-search-repair.test.ts -412 tests/responses/responses-translated-replay-principal.test.ts -17798 tests/responses/responses-translated-reset.test.ts -207 tests/responses/responses-undeclared-tool-guard-inbound.test.ts -514 tests/responses/responses-undeclared-tool-guard.test.ts -111 tests/responses/responses-url-citation-title-repair.test.ts -96 tests/responses/responses-usage-passthrough.test.ts -867 tests/responses/responses-web-search-thinking-signature-recovery.test.ts -117 tests/responses/responses-xai-request-compat.test.ts -274 tests/responses/shadow-intercept-target-lifecycle.test.ts -52 tests/responses/sse-carriage-return.test.ts -548 tests/responses/sse-client-frame-bounds.test.ts -418 tests/responses/sse-decoder.test.ts -397 tests/responses/sse-failed-tail.test.ts -532 tests/responses/sse-inspector-bounds.test.ts -70 tests/responses/sse-null-data-frame.test.ts -114 tests/responses/sse-payload-rewrite.test.ts -136 tests/responses/sse-rewrite-line-endings.test.ts -49 tests/responses/sse-unspaced-data-fields.test.ts -51 tests/responses/thought-signature-credential-scope.test.ts -213 tests/responses/turn-membership-ingress.test.ts -74 tests/responses/turn-membership.test.ts -53 tests/responses/visualization-directives.test.ts -378 tests/responses/ws-ambiguous-resend.test.ts -4487 tests/responses/ws-capacity-reclamation.test.ts -272 tests/responses/ws-capacity-tool-ownership.test.ts -55 tests/responses/ws-committed-liveness.test.ts -138 tests/responses/ws-endpoint.test.ts -191 tests/responses/ws-failure-stage.test.ts -377 tests/responses/ws-native-injection.test.ts -366 tests/responses/ws-native-result-continuations.test.ts -2317 tests/responses/ws-native-steering.test.ts -127 tests/responses/ws-pre-output-refusal.test.ts -229 tests/responses/ws-replay-refusal-attribution.test.ts -370 tests/responses/ws-steering-completion.test.ts -307 tests/responses/ws-steering-smoke.test.ts -214 tests/responses/ws-steering-stability.test.ts -110 tests/responses/ws-upstream-reuse.test.ts -41 tests/responses/ws-upstream-socks5.test.ts -932 tests/responses/ws-upstream.test.ts +85 tests/responses/responses-hosted-tool-min-spread.test.ts +220 tests/responses/responses-image-gen-repair.test.ts +760 tests/responses/responses-inbound-store-default.test.ts +86 tests/responses/responses-item-id-repair.test.ts +40 tests/responses/responses-json-events.test.ts +72 tests/responses/responses-legacy-dotted-tool-name-repair.test.ts +654 tests/responses/responses-main-quota-observation.test.ts +375 tests/responses/responses-memory-models.test.ts +53 tests/responses/responses-mimo-envelope.test.ts +211 tests/responses/responses-muse-tool-choice.test.ts +214 tests/responses/responses-muse-tool-name-alias.test.ts +311 tests/responses/responses-native-compact-search-history.test.ts +163 tests/responses/responses-native-item-extensions-compact.test.ts +131 tests/responses/responses-native-item-extensions.test.ts +560 tests/responses/responses-native-key-cooldown.test.ts +895 tests/responses/responses-native-main-refresh.test.ts +760 tests/responses/responses-native-ultra-effort-wire.test.ts +2004 tests/responses/responses-oauth-refresh-capacity.test.ts +5977 tests/responses/responses-opaque-blob-recovery.test.ts +111 tests/responses/responses-parser-agent-message.test.ts +72 tests/responses/responses-parser-malformed-content.test.ts +173 tests/responses/responses-parser.test.ts +126 tests/responses/responses-passthrough-transient-policy.test.ts +50 tests/responses/responses-phase-inference.test.ts +4408 tests/responses/responses-pool-401-refresh.test.ts +8858 tests/responses/responses-pool-overload-failover.test.ts +115 tests/responses/responses-pool-refresh-attribution.test.ts +511 tests/responses/responses-preview-main-read-fence.test.ts +271 tests/responses/responses-reasoning-effort-downgrade.test.ts +282 tests/responses/responses-reasoning-summary-passthrough.test.ts +188 tests/responses/responses-replay-metadata-principal.test.ts +128 tests/responses/responses-request-compression.test.ts +845 tests/responses/responses-required-chat-tool.test.ts +112 tests/responses/responses-reset-replay.test.ts +2113 tests/responses/responses-retained-reasoning-stream-recovery.test.ts +268 tests/responses/responses-routed-web-search-fields.test.ts +357 tests/responses/responses-run-turn-key-pacing.test.ts +298 tests/responses/responses-run-turn-key-readmission.test.ts +674 tests/responses/responses-run-turn-web-search.test.ts +2255 tests/responses/responses-self-named-namespace-scrub.test.ts +6953 tests/responses/responses-send-budget-counts.test.ts +517 tests/responses/responses-send-budget-errors.test.ts +467 tests/responses/responses-shadow-intercept.test.ts +359 tests/responses/responses-show-thinking-summary.test.ts +729 tests/responses/responses-sidecar-context-overflow.test.ts +334 tests/responses/responses-sidecar-usage.test.ts +491 tests/responses/responses-skills-snapshot.test.ts +845 tests/responses/responses-snapshot-repair-server.test.ts +271 tests/responses/responses-snapshot-repair.test.ts +347 tests/responses/responses-snapshot-scaling.test.ts +94 tests/responses/responses-sparse-terminal-tool-scope.test.ts +2047 tests/responses/responses-spend-anchor.test.ts +85 tests/responses/responses-spend-capacity-guard.test.ts +171 tests/responses/responses-spend-contract-c.test.ts +187 tests/responses/responses-spend-ledger-wiring.test.ts +69 tests/responses/responses-spill-acl-recovery.test.ts +306 tests/responses/responses-spill-admission-headroom.test.ts +72 tests/responses/responses-spill-inspection.test.ts +99 tests/responses/responses-spill-orphan-sweep.test.ts +296 tests/responses/responses-spill-shutdown-clock.test.ts +67 tests/responses/responses-state-flush-race.test.ts +68 tests/responses/responses-state-snapshot-select.test.ts +68 tests/responses/responses-state-snapshot-stubs.test.ts +471 tests/responses/responses-state-store-false.test.ts +233 tests/responses/responses-state-write-amplification.test.ts +7548 tests/responses/responses-state.test.ts +753 tests/responses/responses-stateless-dangling-call-repair.test.ts +50 tests/responses/responses-stream-tool-events.test.ts +105 tests/responses/responses-terminal-repair.test.ts +147 tests/responses/responses-tool-conformance.test.ts +37 tests/responses/responses-tool-groups.test.ts +232 tests/responses/responses-tool-search-repair.test.ts +392 tests/responses/responses-translated-replay-principal.test.ts +18710 tests/responses/responses-translated-reset.test.ts +217 tests/responses/responses-undeclared-tool-guard-inbound.test.ts +968 tests/responses/responses-undeclared-tool-guard.test.ts +150 tests/responses/responses-url-citation-title-repair.test.ts +95 tests/responses/responses-usage-passthrough.test.ts +1298 tests/responses/responses-web-search-thinking-signature-recovery.test.ts +104 tests/responses/responses-xai-request-compat.test.ts +328 tests/responses/shadow-intercept-target-lifecycle.test.ts +75 tests/responses/sse-carriage-return.test.ts +248 tests/responses/sse-client-frame-bounds.test.ts +311 tests/responses/sse-decoder.test.ts +349 tests/responses/sse-failed-tail.test.ts +401 tests/responses/sse-inspector-bounds.test.ts +78 tests/responses/sse-null-data-frame.test.ts +188 tests/responses/sse-payload-rewrite.test.ts +126 tests/responses/sse-rewrite-line-endings.test.ts +48 tests/responses/sse-unspaced-data-fields.test.ts +62 tests/responses/thought-signature-credential-scope.test.ts +232 tests/responses/turn-membership-ingress.test.ts +72 tests/responses/turn-membership.test.ts +59 tests/responses/visualization-directives.test.ts +586 tests/responses/ws-ambiguous-resend.test.ts +4269 tests/responses/ws-capacity-reclamation.test.ts +484 tests/responses/ws-capacity-tool-ownership.test.ts +56 tests/responses/ws-committed-liveness.test.ts +146 tests/responses/ws-endpoint.test.ts +150 tests/responses/ws-failure-stage.test.ts +523 tests/responses/ws-native-injection.test.ts +227 tests/responses/ws-native-result-continuations.test.ts +2224 tests/responses/ws-native-steering.test.ts +149 tests/responses/ws-pre-output-refusal.test.ts +329 tests/responses/ws-replay-refusal-attribution.test.ts +329 tests/responses/ws-steering-completion.test.ts +291 tests/responses/ws-steering-smoke.test.ts +299 tests/responses/ws-steering-stability.test.ts +195 tests/responses/ws-upstream-reuse.test.ts +72 tests/responses/ws-upstream-socks5.test.ts +1210 tests/responses/ws-upstream.test.ts 229 tests/routing/always-on-429-failover.test.ts -126 tests/routing/anthropic-quorum-cache.test.ts -48 tests/routing/cl01-claude-outbound-review-regressions.test.ts -51 tests/routing/cl01-openai-chat-review-regressions.test.ts -97 tests/routing/cl01-review-regressions.test.ts -96 tests/routing/codex-agent-role-models.test.ts -50 tests/routing/codex-role-auto-assign.test.ts -43 tests/routing/codex-role-sizing.test.ts -129 tests/routing/combo-child-headers.test.ts -147 tests/routing/combo-description.test.ts -807 tests/routing/combo-management-api.test.ts -140 tests/routing/combo-required-tool-stream-preflight.test.ts -170 tests/routing/combo-stream-preflight.test.ts -111 tests/routing/combo-terminal-refusal.test.ts -298 tests/routing/combo-vision-enrollment.test.ts -118 tests/routing/compatibility-provider-equivalence.test.ts -53 tests/routing/destination-policy-resolved.test.ts -61 tests/routing/fallback-policy.test.ts -88 tests/routing/fastwire-characterization-routing.test.ts -437 tests/routing/fastwire-characterization-wire.test.ts -181 tests/routing/fastwire-observability.test.ts -129 tests/routing/fastwire-policy.test.ts -378 tests/routing/fastwire-response-authority.test.ts -57 tests/routing/jev-decision-destination.test.ts -271 tests/routing/jev-decision-model-config.test.ts -237 tests/routing/jev-decision-provider-combo.test.ts -119 tests/routing/jev-decision.test.ts +155 tests/routing/anthropic-quorum-cache.test.ts +43 tests/routing/cl01-claude-outbound-review-regressions.test.ts +45 tests/routing/cl01-openai-chat-review-regressions.test.ts +104 tests/routing/cl01-review-regressions.test.ts +117 tests/routing/codex-agent-role-models.test.ts +39 tests/routing/codex-role-auto-assign.test.ts +59 tests/routing/codex-role-capability-consent.test.ts +113 tests/routing/codex-role-capability-redirects.test.ts +36 tests/routing/codex-role-measured-ties.test.ts +63 tests/routing/codex-role-sizing.test.ts +175 tests/routing/combo-child-headers.test.ts +230 tests/routing/combo-description.test.ts +859 tests/routing/combo-management-api.test.ts +113 tests/routing/combo-required-tool-stream-preflight.test.ts +158 tests/routing/combo-stream-preflight.test.ts +94 tests/routing/combo-terminal-refusal.test.ts +343 tests/routing/combo-vision-enrollment.test.ts +313 tests/routing/compatibility-provider-equivalence.test.ts +46 tests/routing/destination-policy-resolved.test.ts +57 tests/routing/fallback-policy.test.ts +89 tests/routing/fastwire-characterization-routing.test.ts +488 tests/routing/fastwire-characterization-wire.test.ts +216 tests/routing/fastwire-observability.test.ts +102 tests/routing/fastwire-policy.test.ts +545 tests/routing/fastwire-response-authority.test.ts +47 tests/routing/jev-decision-destination.test.ts +286 tests/routing/jev-decision-model-config.test.ts +225 tests/routing/jev-decision-provider-combo.test.ts +192 tests/routing/jev-decision.test.ts 1090 tests/routing/jev-model-backend.test.ts -237 tests/routing/jev-quota-activation.test.ts -203 tests/routing/jev-quota-anthropic2.test.ts -152 tests/routing/jev-quota-antigravity.test.ts -138 tests/routing/jev-quota-codex-reset.test.ts -229 tests/routing/jev-quota-config.test.ts -536 tests/routing/jev-quota-core-boundary.test.ts +290 tests/routing/jev-quota-activation.test.ts +192 tests/routing/jev-quota-anthropic2.test.ts +159 tests/routing/jev-quota-antigravity.test.ts +200 tests/routing/jev-quota-codex-reset.test.ts +202 tests/routing/jev-quota-config.test.ts +515 tests/routing/jev-quota-core-boundary.test.ts 130 tests/routing/jev-quota-publication.test.ts -216 tests/routing/jev-quota-signals.test.ts -65 tests/routing/jev-service-exchange.test.ts -51 tests/routing/jev-session-pin.test.ts -61 tests/routing/jev-typesafe-golden.test.ts -118 tests/routing/policy-execution.test.ts -255 tests/routing/probe-lease-dispatch-wiring.test.ts -126 tests/routing/probe-lease.test.ts -114 tests/routing/resolved-model-policy-consumers.test.ts -64 tests/routing/router-anthropic-billing-failover.test.ts -164 tests/routing/router-blocked-cross-provider.test.ts -87 tests/routing/router-combo-failover-classification.test.ts -112 tests/routing/router-discarded-baseurl-warning.test.ts -158 tests/routing/router-template-baseurl.test.ts -112 tests/routing/router.test.ts -476 tests/routing/routing-analytics.test.ts -69 tests/routing/routing-capability-catalog.test.ts -203 tests/routing/routing-capability-model-matching.test.ts -59 tests/routing/routing-compatibility-auth-identity.test.ts -229 tests/routing/routing-compatibility-boundaries.test.ts -88 tests/routing/routing-compatibility-model-matching.test.ts -275 tests/routing/routing-compatibility.test.ts -46 tests/routing/routing-identity-domains.test.ts -244 tests/routing/routing-policy-dispatch-scope.test.ts -152 tests/routing/routing-policy-fallback-off.test.ts -371 tests/routing/routing-policy-fallback.test.ts -96 tests/routing/routing-policy-pool-quota.test.ts -203 tests/routing/routing-policy-surface-parity.test.ts -318 tests/routing/routing-profile-management-editor.test.ts -277 tests/routing/routing-profile.test.ts -120 tests/routing/subagent-context-staleness.test.ts -54 tests/routing/subagent-defaults.test.ts -4454 tests/routing/subagent-fallback-handle-responses.test.ts -58 tests/routing/subagent-fallback-preview-sites.test.ts -189 tests/routing/subagent-model-fallback-api.test.ts -139 tests/routing/subagent-model-fallback-off.test.ts -496 tests/routing/subagent-model-fallback.test.ts -126 tests/routing/subagent-roster-migration.test.ts -374 tests/routing/subagent-roster-retention.test.ts -87 tests/server/account-import-project-fallback.test.ts -158 tests/server/account-import.test.ts -2702 tests/server/account-pool-management-api.test.ts -133 tests/server/adapter-resolve.test.ts -55 tests/server/advisor-routes.test.ts -88 tests/server/agent-assertion-auth.test.ts -179 tests/server/agent-task-recovery-cache.test.ts -364 tests/server/agent-task-recovery-combo.test.ts -181 tests/server/agent-task-recovery-fallback.test.ts -249 tests/server/agent-task-recovery-security.test.ts -11736 tests/server/agent-task-recovery.test.ts -111 tests/server/alias-management-api.test.ts -209 tests/server/anthropic2-management.test.ts -87 tests/server/api-access-endpoints.test.ts -800 tests/server/api-catalog-route.test.ts -334 tests/server/api-codex-log-guard-compact.test.ts -157 tests/server/api-codex-log-guard-protection.test.ts -166 tests/server/api-codex-log-guard.test.ts -1014 tests/server/api-debug.test.ts -2879 tests/server/api-key-attribution.test.ts -104 tests/server/api-key-model-scope.test.ts -271 tests/server/api-key-scope-alpha-search.test.ts -191 tests/server/api-key-scope-audio.test.ts -116 tests/server/api-key-scope-images.test.ts -131 tests/server/api-key-scope-live.test.ts -2494 tests/server/api-keys-routes.test.ts -2565 tests/server/api-usage.test.ts -621 tests/server/aside-profiles-routes.test.ts -108 tests/server/audio-client.test.ts -872 tests/server/audio-dictation.test.ts -1111 tests/server/audio-transcriptions.test.ts -608 tests/server/bounded-body.test.ts -98 tests/server/bridge-live-delivery.test.ts -206 tests/server/caller-session-identity.test.ts -492 tests/server/caller-session-ingress.test.ts -2656 tests/server/cancel-body-on-abort.test.ts -937 tests/server/claude-intercept-integration.test.ts -437 tests/server/codex-agent-role-routes.test.ts -168 tests/server/codex-role-auto-assign-routes.test.ts -249 tests/server/codex-role-history-recovery.test.ts -557 tests/server/combo-loopback-metered-consent.test.ts -403 tests/server/combo-metered-consent.test.ts -49 tests/server/combo-requested-effort.test.ts -161 tests/server/companion-settings.test.ts -459 tests/server/config.test.ts -193 tests/server/consume-for-inspection-cancel.test.ts -366 tests/server/context-history-ownership.test.ts -145 tests/server/context-history.test.ts -254 tests/server/data-plane-admission-identity.test.ts +338 tests/routing/jev-quota-signals.test.ts +52 tests/routing/jev-service-exchange.test.ts +54 tests/routing/jev-session-pin.test.ts +98 tests/routing/jev-typesafe-golden.test.ts +125 tests/routing/policy-execution.test.ts +275 tests/routing/probe-lease-dispatch-wiring.test.ts +125 tests/routing/probe-lease.test.ts +106 tests/routing/resolved-model-policy-consumers.test.ts +47 tests/routing/router-anthropic-billing-failover.test.ts +168 tests/routing/router-blocked-cross-provider.test.ts +92 tests/routing/router-combo-failover-classification.test.ts +127 tests/routing/router-discarded-baseurl-warning.test.ts +109 tests/routing/router-template-baseurl.test.ts +107 tests/routing/router.test.ts +465 tests/routing/routing-analytics.test.ts +91 tests/routing/routing-capability-catalog.test.ts +127 tests/routing/routing-capability-model-matching.test.ts +36 tests/routing/routing-compatibility-auth-identity.test.ts +216 tests/routing/routing-compatibility-boundaries.test.ts +111 tests/routing/routing-compatibility-model-matching.test.ts +179 tests/routing/routing-compatibility.test.ts +67 tests/routing/routing-identity-domains.test.ts +254 tests/routing/routing-policy-dispatch-scope.test.ts +136 tests/routing/routing-policy-fallback-off.test.ts +362 tests/routing/routing-policy-fallback.test.ts +69 tests/routing/routing-policy-pool-quota.test.ts +420 tests/routing/routing-policy-surface-parity.test.ts +383 tests/routing/routing-profile-management-editor.test.ts +310 tests/routing/routing-profile.test.ts +110 tests/routing/subagent-context-staleness.test.ts +52 tests/routing/subagent-defaults.test.ts +5653 tests/routing/subagent-fallback-handle-responses.test.ts +100 tests/routing/subagent-fallback-preview-sites.test.ts +167 tests/routing/subagent-model-fallback-api.test.ts +251 tests/routing/subagent-model-fallback-off.test.ts +608 tests/routing/subagent-model-fallback.test.ts +137 tests/routing/subagent-roster-migration.test.ts +495 tests/routing/subagent-roster-retention.test.ts +113 tests/server/account-import-project-fallback.test.ts +107 tests/server/account-import.test.ts +3080 tests/server/account-pool-management-api.test.ts +227 tests/server/adapter-resolve.test.ts +75 tests/server/advisor-routes.test.ts +82 tests/server/agent-assertion-auth.test.ts +269 tests/server/agent-task-recovery-cache.test.ts +574 tests/server/agent-task-recovery-combo.test.ts +209 tests/server/agent-task-recovery-fallback.test.ts +265 tests/server/agent-task-recovery-security.test.ts +12031 tests/server/agent-task-recovery.test.ts +138 tests/server/alias-management-api.test.ts +162 tests/server/anthropic2-management.test.ts +84 tests/server/api-access-endpoints.test.ts +903 tests/server/api-catalog-route.test.ts +249 tests/server/api-codex-log-guard-compact.test.ts +175 tests/server/api-codex-log-guard-protection.test.ts +164 tests/server/api-codex-log-guard.test.ts +1281 tests/server/api-debug.test.ts +2680 tests/server/api-key-attribution.test.ts +105 tests/server/api-key-model-scope.test.ts +228 tests/server/api-key-scope-alpha-search.test.ts +246 tests/server/api-key-scope-audio.test.ts +198 tests/server/api-key-scope-images.test.ts +123 tests/server/api-key-scope-live.test.ts +3386 tests/server/api-keys-routes.test.ts +3181 tests/server/api-usage.test.ts +549 tests/server/aside-profiles-routes.test.ts +88 tests/server/audio-client.test.ts +1099 tests/server/audio-dictation.test.ts +1214 tests/server/audio-transcriptions.test.ts +562 tests/server/bounded-body.test.ts +128 tests/server/bridge-live-delivery.test.ts +217 tests/server/caller-session-identity.test.ts +642 tests/server/caller-session-ingress.test.ts +2564 tests/server/cancel-body-on-abort.test.ts +999 tests/server/claude-intercept-integration.test.ts +407 tests/server/codex-agent-role-routes.test.ts +148 tests/server/codex-role-auto-assign-routes.test.ts +124 tests/server/codex-role-configured-credentials.test.ts +247 tests/server/codex-role-history-recovery.test.ts +502 tests/server/combo-loopback-metered-consent.test.ts +450 tests/server/combo-metered-consent.test.ts +78 tests/server/combo-requested-effort.test.ts +150 tests/server/companion-settings.test.ts +399 tests/server/config.test.ts +200 tests/server/consume-for-inspection-cancel.test.ts +477 tests/server/context-history-ownership.test.ts +158 tests/server/context-history.test.ts +310 tests/server/data-plane-admission-identity.test.ts 45 tests/server/debug-settings.test.ts -44 tests/server/decision-discovery.test.ts -290 tests/server/decision-routes.test.ts -491 tests/server/distributed-key-401.test.ts -184 tests/server/error-fidelity.test.ts -164 tests/server/errors-adapter-failure.test.ts -234 tests/server/fallback-routes.test.ts -536 tests/server/fetch-header-timeout.test.ts -340 tests/server/health-scoring.test.ts -496 tests/server/hub-usage.test.ts -776 tests/server/inbound-body-admission.test.ts -132 tests/server/inbound-body-budget.test.ts -89 tests/server/inference-attempt.test.ts -196 tests/server/inference-client-encoder-delivery.test.ts -45 tests/server/inference-client-wire.test.ts -106 tests/server/inference-final-log.test.ts -1403 tests/server/inference-send-budget.test.ts -132 tests/server/input-admission.test.ts -154 tests/server/jev-decision-scope.test.ts -128 tests/server/link-child-parity.test.ts -208 tests/server/link-enrollment.test.ts -2547 tests/server/link-join-route.test.ts -460 tests/server/link-listener-admission.test.ts -177 tests/server/link-listener-lifecycle.test.ts -52 tests/server/link-listener-mutation.test.ts -6011 tests/server/link-management-relay.test.ts -512 tests/server/link-management-routes.test.ts -56 tests/server/live-call-bindings.test.ts -63 tests/server/live-native-calls.test.ts -179 tests/server/local-account-switch-capability.test.ts -234 tests/server/local-account-switch-ingress.test.ts -522 tests/server/local-aside-sync-capability.test.ts -39 tests/server/local-management-attestation.test.ts -55 tests/server/local-management-capability.test.ts -554 tests/server/local-management-direct-transport.test.ts -42 tests/server/local-provider-reload-client.test.ts -307 tests/server/local-read-response-proof.test.ts -632 tests/server/login-shell-path.test.ts -147 tests/server/logs-timezone.test.ts -151 tests/server/loopback-companion-client-targets.test.ts -124 tests/server/loopback-listener-admission.test.ts -2268 tests/server/loopback-listener-integration.test.ts -152 tests/server/management-account-auto-pause.test.ts -119 tests/server/management-anthropic-reset-grants.test.ts -220 tests/server/management-api-logs-metrics.test.ts -135 tests/server/management-api-logs-timing-basis.test.ts -299 tests/server/management-auto-review-auth.test.ts -143 tests/server/management-auto-review-settings.test.ts -615 tests/server/management-client-config-route.test.ts -231 tests/server/management-desktop-compatibility-routes.test.ts -196 tests/server/management-desktop-compatibility-runtime-routes.test.ts -200 tests/server/management-desktop-compatibility-settings.test.ts -161 tests/server/management-droid-reasoning-defaults.test.ts -324 tests/server/management-export-model-names.test.ts -812 tests/server/management-gcp-credential-input.test.ts -248 tests/server/management-google-tool-schema-policy.test.ts -196 tests/server/management-inference-port.test.ts -359 tests/server/management-integration-journal-delete.test.ts -944 tests/server/management-integration-routes.test.ts -1985 tests/server/management-metrics-export.test.ts -143 tests/server/management-model-roster-gather-race.test.ts -104 tests/server/management-model-roster.test.ts -48 tests/server/management-origin-tls.test.ts -243 tests/server/management-provider-atomicity.test.ts -1749 tests/server/management-provider-compat-carry.test.ts -159 tests/server/management-provider-context-inference.test.ts -637 tests/server/management-provider-hide-raw-reasoning.test.ts -308 tests/server/management-provider-pinsless-validation.test.ts -320 tests/server/management-provider-proto-override.test.ts -608 tests/server/management-provider-reasoning-lists.test.ts -161 tests/server/management-provider-request-pacing.test.ts -56 tests/server/management-provider-reset-replay.test.ts -579 tests/server/management-provider-responses-reasoning.test.ts -187 tests/server/management-provider-synthetic-max.test.ts -171 tests/server/management-provider-upstream-websocket.test.ts -8712 tests/server/management-provider-validation.test.ts -312 tests/server/management-provider-verbosity.test.ts -320 tests/server/management-qoder-selector-state.test.ts -683 tests/server/management-route-registry.test.ts -806 tests/server/management-sidecar-anthropic-instance.test.ts -137 tests/server/management-workflow-budget-routes.test.ts -470 tests/server/memory-watchdog.test.ts -267 tests/server/model-costs-management-api.test.ts -459 tests/server/model-costs-pricing-cache.test.ts -311 tests/server/model-costs-prompt-length-pricing.test.ts -251 tests/server/model-discovery-management-api.test.ts -297 tests/server/model-export-new-model-policy.test.ts -180 tests/server/model-settings-management-api.test.ts -60 tests/server/outbound-body-guard.test.ts -49 tests/server/owned-service-home.test.ts -54 tests/server/passive-route-linker.test.ts -313 tests/server/persistent-dashboard-admission.test.ts -394 tests/server/persistent-dashboard-consent.test.ts -407 tests/server/persistent-dashboard-session.test.ts -2117 tests/server/plaintext-v2-agent-messages-server.test.ts -983 tests/server/port-reclaim.test.ts -364 tests/server/ports.test.ts -884 tests/server/prefer-model-alias-ids.test.ts -1130 tests/server/probe-timeout-env.test.ts -125 tests/server/protocol-provider-summary.test.ts -106 tests/server/protocol-routes.test.ts -139 tests/server/protocol-settings-route.test.ts -140 tests/server/provider-account-quota-routes.test.ts -55 tests/server/provider-egress-management-validation.test.ts -176 tests/server/provider-send-path-import.test.ts -53 tests/server/proxy-env-macos.test.ts -74 tests/server/proxy-env.test.ts -337 tests/server/proxy-liveness-bind-scope.test.ts -101 tests/server/proxy-liveness-owner-evidence.test.ts -53 tests/server/proxy-liveness-package-tree-fence.test.ts -66 tests/server/proxy-liveness-recovery.test.ts -66 tests/server/proxy-liveness.test.ts -4863 tests/server/quota-pool-relay.test.ts -520 tests/server/readyz-features.test.ts -746 tests/server/relay-eager.test.ts -1594 tests/server/replay-refusal-parity.test.ts -360 tests/server/reserve-claude-policy.test.ts -2118 tests/server/reserve-ingress.test.ts -571 tests/server/response-log-inspection.test.ts -290 tests/server/response-model-identity.test.ts -1265 tests/server/restart-replacement-not-ready.test.ts -106 tests/server/restart-replacement.test.ts -133 tests/server/retry-after-429.test.ts -46 tests/server/retry-delay-hardening.test.ts +47 tests/server/decision-discovery.test.ts +247 tests/server/decision-routes.test.ts +403 tests/server/distributed-key-401.test.ts +306 tests/server/error-fidelity.test.ts +132 tests/server/errors-adapter-failure.test.ts +174 tests/server/fallback-routes.test.ts +502 tests/server/fetch-header-timeout.test.ts +414 tests/server/health-scoring.test.ts +481 tests/server/hub-usage.test.ts +887 tests/server/inbound-body-admission.test.ts +124 tests/server/inbound-body-budget.test.ts +119 tests/server/inference-attempt.test.ts +199 tests/server/inference-client-encoder-delivery.test.ts +85 tests/server/inference-client-wire.test.ts +110 tests/server/inference-final-log.test.ts +1414 tests/server/inference-send-budget.test.ts +133 tests/server/input-admission.test.ts +186 tests/server/jev-decision-scope.test.ts +133 tests/server/link-child-parity.test.ts +216 tests/server/link-enrollment.test.ts +2582 tests/server/link-join-route.test.ts +488 tests/server/link-listener-admission.test.ts +193 tests/server/link-listener-lifecycle.test.ts +47 tests/server/link-listener-mutation.test.ts +5939 tests/server/link-management-relay.test.ts +647 tests/server/link-management-routes.test.ts +53 tests/server/live-call-bindings.test.ts +59 tests/server/live-native-calls.test.ts +156 tests/server/local-account-switch-capability.test.ts +287 tests/server/local-account-switch-ingress.test.ts +566 tests/server/local-aside-sync-capability.test.ts +87 tests/server/local-management-attestation.test.ts +67 tests/server/local-management-capability.test.ts +539 tests/server/local-management-direct-transport.test.ts +63 tests/server/local-provider-reload-client.test.ts +561 tests/server/local-read-response-proof.test.ts +631 tests/server/login-shell-path.test.ts +124 tests/server/logs-timezone.test.ts +140 tests/server/loopback-companion-client-targets.test.ts +103 tests/server/loopback-listener-admission.test.ts +2542 tests/server/loopback-listener-integration.test.ts +200 tests/server/management-account-auto-pause.test.ts +134 tests/server/management-anthropic-reset-grants.test.ts +247 tests/server/management-api-logs-metrics.test.ts +119 tests/server/management-api-logs-timing-basis.test.ts +267 tests/server/management-auto-review-auth.test.ts +167 tests/server/management-auto-review-settings.test.ts +563 tests/server/management-client-config-route.test.ts +279 tests/server/management-desktop-compatibility-routes.test.ts +149 tests/server/management-desktop-compatibility-runtime-routes.test.ts +191 tests/server/management-desktop-compatibility-settings.test.ts +219 tests/server/management-droid-reasoning-defaults.test.ts +323 tests/server/management-export-model-names.test.ts +901 tests/server/management-gcp-credential-input.test.ts +345 tests/server/management-google-tool-schema-policy.test.ts +154 tests/server/management-inference-port.test.ts +314 tests/server/management-integration-journal-delete.test.ts +1138 tests/server/management-integration-routes.test.ts +1992 tests/server/management-metrics-export.test.ts +213 tests/server/management-model-roster-gather-race.test.ts +164 tests/server/management-model-roster.test.ts +38 tests/server/management-origin-tls.test.ts +211 tests/server/management-provider-atomicity.test.ts +1957 tests/server/management-provider-compat-carry.test.ts +264 tests/server/management-provider-context-inference.test.ts +750 tests/server/management-provider-hide-raw-reasoning.test.ts +348 tests/server/management-provider-pinsless-validation.test.ts +355 tests/server/management-provider-proto-override.test.ts +729 tests/server/management-provider-reasoning-lists.test.ts +145 tests/server/management-provider-request-pacing.test.ts +79 tests/server/management-provider-reset-replay.test.ts +699 tests/server/management-provider-responses-reasoning.test.ts +167 tests/server/management-provider-synthetic-max.test.ts +370 tests/server/management-provider-upstream-websocket.test.ts +10588 tests/server/management-provider-validation.test.ts +410 tests/server/management-provider-verbosity.test.ts +380 tests/server/management-qoder-selector-state.test.ts +824 tests/server/management-route-registry.test.ts +864 tests/server/management-sidecar-anthropic-instance.test.ts +144 tests/server/management-workflow-budget-routes.test.ts +509 tests/server/memory-watchdog.test.ts +335 tests/server/model-costs-management-api.test.ts +429 tests/server/model-costs-pricing-cache.test.ts +497 tests/server/model-costs-prompt-length-pricing.test.ts +203 tests/server/model-discovery-management-api.test.ts +444 tests/server/model-export-new-model-policy.test.ts +193 tests/server/model-settings-management-api.test.ts +94 tests/server/outbound-body-guard.test.ts +47 tests/server/owned-service-home.test.ts +67 tests/server/passive-route-linker.test.ts +471 tests/server/persistent-dashboard-admission.test.ts +484 tests/server/persistent-dashboard-consent.test.ts +230 tests/server/persistent-dashboard-session.test.ts +2266 tests/server/plaintext-v2-agent-messages-server.test.ts +971 tests/server/port-reclaim.test.ts +410 tests/server/ports.test.ts +1026 tests/server/prefer-model-alias-ids.test.ts +951 tests/server/probe-timeout-env.test.ts +179 tests/server/protocol-provider-summary.test.ts +180 tests/server/protocol-routes.test.ts +150 tests/server/protocol-settings-route.test.ts +229 tests/server/provider-account-quota-routes.test.ts +46 tests/server/provider-egress-management-validation.test.ts +174 tests/server/provider-send-path-import.test.ts +55 tests/server/proxy-env-macos.test.ts +64 tests/server/proxy-env.test.ts +384 tests/server/proxy-liveness-bind-scope.test.ts +80 tests/server/proxy-liveness-owner-evidence.test.ts +62 tests/server/proxy-liveness-package-tree-fence.test.ts +86 tests/server/proxy-liveness-recovery.test.ts +83 tests/server/proxy-liveness.test.ts +4849 tests/server/quota-pool-relay.test.ts +572 tests/server/readyz-features.test.ts +656 tests/server/relay-eager.test.ts +1816 tests/server/replay-refusal-parity.test.ts +469 tests/server/reserve-claude-policy.test.ts +2011 tests/server/reserve-ingress.test.ts +460 tests/server/response-log-inspection.test.ts +423 tests/server/response-model-identity.test.ts +1272 tests/server/restart-replacement-not-ready.test.ts +103 tests/server/restart-replacement.test.ts +137 tests/server/retry-after-429.test.ts +47 tests/server/retry-delay-hardening.test.ts 212 tests/server/route-decision-trace.test.ts -2231 tests/server/served-by-header.test.ts -389 tests/server/server-403-permission-e2e.test.ts -277 tests/server/server-agent-task-recovery-replay.test.ts -472 tests/server/server-anthropic-billing-boundaries.test.ts -1981 tests/server/server-anthropic-billing.test.ts -2056 tests/server/server-antigravity-model-denial-recovery.test.ts -477 tests/server/server-antigravity-model-roster-routing.test.ts -126 tests/server/server-antigravity-verify-replay-scope.test.ts -584 tests/server/server-antigravity-web-search-validation.test.ts -411 tests/server/server-auth-localhost-bind.test.ts -1814 tests/server/server-auth-scoped-quota.test.ts -19325 tests/server/server-auth.test.ts -1086 tests/server/server-background-lifecycle.test.ts -598 tests/server/server-chat-native-key-selection.test.ts -274 tests/server/server-cli-key-probe-admission.test.ts -44 tests/server/server-clickjacking-headers.test.ts -388 tests/server/server-combo-cooldown-fallback.test.ts -723 tests/server/server-combo-cooldown-recording.test.ts -9392 tests/server/server-combo-failover-e2e.test.ts -47 tests/server/server-combo-held-response.test.ts -735 tests/server/server-combo-plan-model-refusal.test.ts -157 tests/server/server-combo-quota-code-provenance.test.ts -3879 tests/server/server-combo-reasoning-replay-eligibility.test.ts -485 tests/server/server-combo-required-tool-contract.test.ts -395 tests/server/server-combo-stream-hosted-tool-contract.test.ts -657 tests/server/server-combo-stream-required-tool.test.ts -362 tests/server/server-combo-stream-send-contract.test.ts -5248 tests/server/server-combo-tool-loop-continuation.test.ts -378 tests/server/server-combo-zero-output-failover.test.ts -707 tests/server/server-desktop-compatibility-startup.test.ts -715 tests/server/server-generic-oauth-affinity.test.ts -3606 tests/server/server-google-antigravity-oauth-401-replay.test.ts -404 tests/server/server-google-antigravity-oauth-429-budget.test.ts -76 tests/server/server-gui-bundle-freshness.test.ts -151 tests/server/server-images-bodyless-content-length.test.ts -249 tests/server/server-images-pool-admission.test.ts -5327 tests/server/server-images.test.ts -363 tests/server/server-jev-combo-e2e.test.ts -250 tests/server/server-jev-model-decision-e2e.test.ts -399 tests/server/server-jev-model-quota-budget.test.ts -208 tests/server/server-jev-session-pin.test.ts -5793 tests/server/server-key-failover-e2e.test.ts -1480 tests/server/server-kiro-completion-e2e.test.ts -197 tests/server/server-kiro-device-login.test.ts -725 tests/server/server-kiro-oauth-401-replay.test.ts -3162 tests/server/server-kiro-refusal-e2e.test.ts -408 tests/server/server-live-cancel.test.ts -8784 tests/server/server-live-close.test.ts -499 tests/server/server-live-existing-call.test.ts -153 tests/server/server-live-frame-log.test.ts -1047 tests/server/server-live-realtime-fixtures.test.ts -5476 tests/server/server-live.test.ts -48 tests/server/server-loopback-host-gate.test.ts -1771 tests/server/server-management-auth.test.ts -484 tests/server/server-management-log-admission.test.ts -1266 tests/server/server-native-catalog-priority.test.ts -112 tests/server/server-native-reasoning-retention-merge.test.ts -137 tests/server/server-native-reasoning-retention.test.ts -998 tests/server/server-new-model-policy-arrival.test.ts -391 tests/server/server-opencode-go-goal-streaming.test.ts -1590 tests/server/server-rate-limit-retry-e2e.test.ts -967 tests/server/server-request-body-size.test.ts -2073 tests/server/server-search.test.ts -262 tests/server/server-startup-codex-off.test.ts -510 tests/server/server-startup-reconcile-resilience.test.ts -488 tests/server/server-stop-config-hardening.test.ts -360 tests/server/server-terminal-refusal-wiring.test.ts -294 tests/server/server-xai-chat-reasoning-streaming.test.ts -405 tests/server/server-xai-header-parity.test.ts -931 tests/server/server-xai-oauth-401-replay.test.ts -679 tests/server/server-xai-responses-streaming.test.ts -99 tests/server/session-affinity.test.ts -388 tests/server/session-lane-recall-harness.test.ts -160 tests/server/sidebar-routes.test.ts -48 tests/server/sidebar-star-state.test.ts -109 tests/server/spend-instrumentation-log.test.ts -144 tests/server/spend-ledger-lifecycle.test.ts -326 tests/server/spend-ledger-owner-startup.test.ts -103 tests/server/startup-action-control-elevation.test.ts -143 tests/server/startup-action-control.test.ts -11783 tests/server/startup-health-packaged-probe.test.ts -47 tests/server/startup-prompt.test.ts -120 tests/server/stream-aborted-marker.test.ts -210 tests/server/subagent-model-force-api.test.ts -836 tests/server/system-env.test.ts -134 tests/server/system-restart-admission.test.ts -4664 tests/server/system-restart-ownership.test.ts -182 tests/server/system-restart.test.ts -230 tests/server/system-routes.test.ts -4311 tests/server/terminal-guard-server.test.ts -103 tests/server/terminal-guard.test.ts -180 tests/server/update-async-routes.test.ts -69 tests/server/upstream-connect-error.test.ts -62 tests/server/upstream-http-version.test.ts -794 tests/server/v1-hub-state.test.ts -277 tests/server/v2-agent-message-failfast.test.ts -236 tests/service/autostart-health.test.ts -1263 tests/service/connected-stop-capability-auth.test.ts -2633 tests/service/container-bootstrap.test.ts -175 tests/service/crash-guard.test.ts -25280 tests/service/doctor-codex-envkey-readiness.test.ts -173 tests/service/doctor-oauth.test.ts -222 tests/service/doctor-provider-apikey.test.ts -37 tests/service/doctor-service-memory-contract.test.ts +2737 tests/server/served-by-header.test.ts +498 tests/server/server-403-permission-e2e.test.ts +351 tests/server/server-agent-task-recovery-replay.test.ts +591 tests/server/server-anthropic-billing-boundaries.test.ts +2823 tests/server/server-anthropic-billing.test.ts +2060 tests/server/server-antigravity-model-denial-recovery.test.ts +646 tests/server/server-antigravity-model-roster-routing.test.ts +142 tests/server/server-antigravity-verify-replay-scope.test.ts +703 tests/server/server-antigravity-web-search-validation.test.ts +481 tests/server/server-auth-localhost-bind.test.ts +1811 tests/server/server-auth-scoped-quota.test.ts +19895 tests/server/server-auth.test.ts +1304 tests/server/server-background-lifecycle.test.ts +1108 tests/server/server-chat-native-key-selection.test.ts +374 tests/server/server-cli-key-probe-admission.test.ts +46 tests/server/server-clickjacking-headers.test.ts +452 tests/server/server-combo-cooldown-fallback.test.ts +1018 tests/server/server-combo-cooldown-recording.test.ts +12170 tests/server/server-combo-failover-e2e.test.ts +43 tests/server/server-combo-held-response.test.ts +1194 tests/server/server-combo-plan-model-refusal.test.ts +147 tests/server/server-combo-quota-code-provenance.test.ts +3900 tests/server/server-combo-reasoning-replay-eligibility.test.ts +1879 tests/server/server-combo-required-tool-contract.test.ts +1059 tests/server/server-combo-stream-hosted-tool-contract.test.ts +783 tests/server/server-combo-stream-required-tool.test.ts +434 tests/server/server-combo-stream-send-contract.test.ts +5255 tests/server/server-combo-tool-loop-continuation.test.ts +564 tests/server/server-combo-zero-output-failover.test.ts +715 tests/server/server-desktop-compatibility-startup.test.ts +961 tests/server/server-generic-oauth-affinity.test.ts +4304 tests/server/server-google-antigravity-oauth-401-replay.test.ts +503 tests/server/server-google-antigravity-oauth-429-budget.test.ts +49 tests/server/server-gui-bundle-freshness.test.ts +186 tests/server/server-images-bodyless-content-length.test.ts +279 tests/server/server-images-pool-admission.test.ts +5025 tests/server/server-images.test.ts +352 tests/server/server-jev-combo-e2e.test.ts +281 tests/server/server-jev-model-decision-e2e.test.ts +465 tests/server/server-jev-model-quota-budget.test.ts +183 tests/server/server-jev-session-pin.test.ts +6763 tests/server/server-key-failover-e2e.test.ts +1741 tests/server/server-kiro-completion-e2e.test.ts +207 tests/server/server-kiro-device-login.test.ts +820 tests/server/server-kiro-oauth-401-replay.test.ts +4866 tests/server/server-kiro-refusal-e2e.test.ts +2486 tests/server/server-kiro-usage-log-e2e.test.ts +464 tests/server/server-live-cancel.test.ts +8773 tests/server/server-live-close.test.ts +587 tests/server/server-live-existing-call.test.ts +130 tests/server/server-live-frame-log.test.ts +1475 tests/server/server-live-realtime-fixtures.test.ts +6845 tests/server/server-live.test.ts +104 tests/server/server-loopback-host-gate.test.ts +3060 tests/server/server-management-auth.test.ts +433 tests/server/server-management-log-admission.test.ts +1309 tests/server/server-native-catalog-priority.test.ts +198 tests/server/server-native-reasoning-retention-merge.test.ts +226 tests/server/server-native-reasoning-retention.test.ts +896 tests/server/server-new-model-policy-arrival.test.ts +449 tests/server/server-opencode-go-goal-streaming.test.ts +1848 tests/server/server-rate-limit-retry-e2e.test.ts +986 tests/server/server-request-body-size.test.ts +1795 tests/server/server-search.test.ts +371 tests/server/server-startup-codex-off.test.ts +525 tests/server/server-startup-reconcile-resilience.test.ts +496 tests/server/server-stop-config-hardening.test.ts +514 tests/server/server-terminal-refusal-wiring.test.ts +212 tests/server/server-workflow-budget-settings.test.ts +530 tests/server/server-xai-chat-reasoning-streaming.test.ts +439 tests/server/server-xai-header-parity.test.ts +957 tests/server/server-xai-oauth-401-replay.test.ts +589 tests/server/server-xai-responses-streaming.test.ts +117 tests/server/session-affinity.test.ts +358 tests/server/session-lane-recall-harness.test.ts +244 tests/server/sidebar-routes.test.ts +50 tests/server/sidebar-star-state.test.ts +144 tests/server/spend-instrumentation-log.test.ts +132 tests/server/spend-ledger-lifecycle.test.ts +443 tests/server/spend-ledger-owner-startup.test.ts +136 tests/server/startup-action-control-elevation.test.ts +121 tests/server/startup-action-control.test.ts +12435 tests/server/startup-health-packaged-probe.test.ts +61 tests/server/startup-prompt.test.ts +132 tests/server/stream-aborted-marker.test.ts +233 tests/server/subagent-model-force-api.test.ts +857 tests/server/system-env.test.ts +155 tests/server/system-restart-admission.test.ts +4063 tests/server/system-restart-ownership.test.ts +162 tests/server/system-restart.test.ts +128 tests/server/system-routes.test.ts +4514 tests/server/terminal-guard-server.test.ts +82 tests/server/terminal-guard.test.ts +153 tests/server/update-async-routes.test.ts +49 tests/server/upstream-connect-error.test.ts +47 tests/server/upstream-http-version.test.ts +775 tests/server/v1-hub-state.test.ts +572 tests/server/v2-agent-message-failfast.test.ts +150 tests/service/autostart-health.test.ts +1381 tests/service/connected-stop-capability-auth.test.ts +2549 tests/service/container-bootstrap.test.ts +206 tests/service/crash-guard.test.ts +25261 tests/service/doctor-codex-envkey-readiness.test.ts +201 tests/service/doctor-oauth.test.ts +275 tests/service/doctor-provider-apikey.test.ts +70 tests/service/doctor-service-memory-contract.test.ts 111 tests/service/init-backup-cleanup.test.ts -5413 tests/service/init-eof.test.ts -83 tests/service/launchd-port-fallback.test.ts -356 tests/service/launchd-repair.test.ts -110 tests/service/live-service-manager-guard.test.ts -39 tests/service/managing-cli.test.ts -104 tests/service/ownership-mutation-lease-diagnostics.test.ts -59 tests/service/process-state.test.ts -182 tests/service/service-auth-qualified-localhost.test.ts -75 tests/service/service-child-ownership.test.ts -118 tests/service/service-claim.test.ts -147 tests/service/service-desktop-login-registration.test.ts -4006 tests/service/service-desktop-recovery.test.ts -51 tests/service/service-desktop-runtime-preflight.test.ts -106 tests/service/service-desktop-startup-health.test.ts -204 tests/service/service-desktop-startup-linux.test.ts -220 tests/service/service-desktop-startup.test.ts -196 tests/service/service-desktop-supervision-windows.test.ts -99 tests/service/service-handled-signal-exit.test.ts -93 tests/service/service-health-sentinel-launch.test.ts -50 tests/service/service-health-sentinel-linux.test.ts -58 tests/service/service-health-sentinel-policy.test.ts -7937 tests/service/service-health-sentinel-process.test.ts -407 tests/service/service-health-sentinel-runner.test.ts -160 tests/service/service-install-wrapper-cleanup.test.ts -1459 tests/service/service-log.test.ts -181 tests/service/service-multishell-path.test.ts +7589 tests/service/init-eof.test.ts +89 tests/service/launchd-port-fallback.test.ts +368 tests/service/launchd-repair.test.ts +121 tests/service/live-service-manager-guard.test.ts +49 tests/service/managing-cli.test.ts +52 tests/service/ownership-mutation-lease-diagnostics.test.ts +127 tests/service/process-state.test.ts +175 tests/service/service-auth-qualified-localhost.test.ts +71 tests/service/service-child-ownership.test.ts +101 tests/service/service-claim.test.ts +133 tests/service/service-desktop-login-registration.test.ts +4370 tests/service/service-desktop-recovery.test.ts +75 tests/service/service-desktop-runtime-preflight.test.ts +124 tests/service/service-desktop-startup-health.test.ts +214 tests/service/service-desktop-startup-linux.test.ts +279 tests/service/service-desktop-startup.test.ts +266 tests/service/service-desktop-supervision-windows.test.ts +62 tests/service/service-handled-signal-exit.test.ts +94 tests/service/service-health-sentinel-launch.test.ts +51 tests/service/service-health-sentinel-linux.test.ts +62 tests/service/service-health-sentinel-policy.test.ts +7956 tests/service/service-health-sentinel-process.test.ts +412 tests/service/service-health-sentinel-runner.test.ts +122 tests/service/service-install-wrapper-cleanup.test.ts +1602 tests/service/service-log.test.ts +129 tests/service/service-multishell-path.test.ts 49 tests/service/service-ownership-compatibility.test.ts -218 tests/service/service-ownership-handover.test.ts -249 tests/service/service-ownership-state.test.ts -46 tests/service/service-probe-docker.test.ts -50 tests/service/service-proxy-env.test.ts -133 tests/service/service-runtime-preflight.test.ts -165 tests/service/service-secrets.test.ts -262 tests/service/service-sqlite-home.test.ts -35 tests/service/service-start-environment.test.ts -328 tests/service/service-state-isolation.test.ts -2538 tests/service/service-status-json.test.ts -131 tests/service/service-stop-verification.test.ts -325 tests/service/service-tier-capability.test.ts -213 tests/service/service-wsl-home-ownership.test.ts -1118 tests/service/service.test.ts -258 tests/service/shutdown-drain.test.ts -9445 tests/service/shutdown-launcher.test.ts -47 tests/service/stale-state-purge.test.ts -51 tests/service/standalone-service.test.ts -33506 tests/service/stop-deferred-teardown.test.ts -322 tests/service/stop-direct-fetch.test.ts -1202 tests/service/stop-restoration-preflight.test.ts -5053 tests/service/stop-restore-history-ownership.test.ts -65 tests/service/systemd-install-cleanup-hardening.test.ts -183 tests/service/winsw.test.ts -3430 tests/storage/api-storage-cleanup.test.ts -1871 tests/storage/api-storage-policy-already-running.test.ts -1564 tests/storage/api-storage-policy-mutation-busy.test.ts -849 tests/storage/api-storage-policy-put-race.test.ts -1331 tests/storage/api-storage-policy-run.test.ts -627 tests/storage/api-storage-policy.test.ts -483 tests/storage/api-storage.test.ts -1023 tests/storage/storage-cleanup.test.ts -6501 tests/storage/storage-mutation-race.test.ts -111 tests/storage/storage-policy-config-race.test.ts -2035 tests/storage/storage-policy-job-responsive.test.ts -116 tests/storage/storage-policy.test.ts -42 tests/storage/storage-restore-job-errors.test.ts -4994 tests/storage/storage-restore-job-responsive.test.ts -219 tests/storage/storage-scanner.test.ts -942 tests/storage/storage-worker-lifecycle.test.ts -63 tests/storage/storage-worker-os-join-settle.test.ts -4352 tests/storage/storage-worker-teardown-isolate.test.ts -476 tests/test-layout-tooling.test.ts -113 tests/test-layout.test.ts -51 tests/update/pnpm-command-isolation.test.ts -84 tests/update/update-badge.test.ts -8720 tests/update/update-bun-ownership-lease.test.ts -64 tests/update/update-capability-policy.test.ts -49 tests/update/update-desktop-badge.test.ts -36 tests/update/update-desktop-owner.test.ts -58 tests/update/update-effect-authority.test.ts -125 tests/update/update-guarded-ops.test.ts -732 tests/update/update-home-launcher.test.ts -52 tests/update/update-home-recovery.test.ts -155 tests/update/update-home-worker.test.ts -146 tests/update/update-job-supervised-restart.test.ts -206 tests/update/update-job.test.ts -70 tests/update/update-mise-launcher-target.test.ts -43 tests/update/update-mise-node-runtime.test.ts -282 tests/update/update-mise.test.ts -113 tests/update/update-mutation-boundaries.test.ts -74 tests/update/update-mutation-guard.test.ts -89 tests/update/update-mutation-scanner.test.ts -64 tests/update/update-notify.test.ts -465 tests/update/update-npm-cache-preflight.test.ts -45 tests/update/update-npm-invocation.test.ts -49 tests/update/update-npm-supervisor-exit.test.ts -53 tests/update/update-npm-timeout.test.ts -112 tests/update/update-pnpm.test.ts -49 tests/update/update-reclaim-authorizer.test.ts -63 tests/update/update-recovery-authority.test.ts -257 tests/update/update-recovery-boundaries.test.ts -46 tests/update/update-recovery-host-free.test.ts -210 tests/update/update-refresh.test.ts -35955 tests/update/update-restart-lease.test.ts +160 tests/service/service-ownership-handover.test.ts +319 tests/service/service-ownership-state.test.ts +45 tests/service/service-probe-docker.test.ts +233 tests/service/service-proxy-env.test.ts +112 tests/service/service-runtime-preflight.test.ts +688 tests/service/service-secrets.test.ts +220 tests/service/service-sqlite-home.test.ts +91 tests/service/service-start-environment.test.ts +563 tests/service/service-state-isolation.test.ts +2452 tests/service/service-status-json.test.ts +212 tests/service/service-stop-verification.test.ts +727 tests/service/service-tier-capability.test.ts +234 tests/service/service-wsl-home-ownership.test.ts +945 tests/service/service.test.ts +267 tests/service/shutdown-drain.test.ts +9506 tests/service/shutdown-launcher.test.ts +53 tests/service/stale-state-purge.test.ts +37 tests/service/standalone-service.test.ts +27472 tests/service/stop-deferred-teardown.test.ts +969 tests/service/stop-direct-fetch.test.ts +1190 tests/service/stop-restoration-preflight.test.ts +4795 tests/service/stop-restore-history-ownership.test.ts +69 tests/service/systemd-install-cleanup-hardening.test.ts +309 tests/service/winsw.test.ts +3496 tests/storage/api-storage-cleanup.test.ts +1927 tests/storage/api-storage-policy-already-running.test.ts +1540 tests/storage/api-storage-policy-mutation-busy.test.ts +960 tests/storage/api-storage-policy-put-race.test.ts +1317 tests/storage/api-storage-policy-run.test.ts +794 tests/storage/api-storage-policy.test.ts +634 tests/storage/api-storage.test.ts +1080 tests/storage/storage-cleanup.test.ts +6922 tests/storage/storage-mutation-race.test.ts +222 tests/storage/storage-policy-config-race.test.ts +2054 tests/storage/storage-policy-job-responsive.test.ts +94 tests/storage/storage-policy.test.ts +58 tests/storage/storage-restore-job-errors.test.ts +5401 tests/storage/storage-restore-job-responsive.test.ts +226 tests/storage/storage-scanner.test.ts +1066 tests/storage/storage-worker-lifecycle.test.ts +37 tests/storage/storage-worker-os-join-settle.test.ts +4322 tests/storage/storage-worker-teardown-isolate.test.ts +498 tests/test-layout-tooling.test.ts +139 tests/test-layout.test.ts +50 tests/update/pnpm-command-isolation.test.ts +51 tests/update/update-badge.test.ts +8434 tests/update/update-bun-ownership-lease.test.ts +94 tests/update/update-capability-policy.test.ts +58 tests/update/update-desktop-badge.test.ts +49 tests/update/update-desktop-owner.test.ts +118 tests/update/update-effect-authority.test.ts +360 tests/update/update-guarded-ops.test.ts +782 tests/update/update-home-launcher.test.ts +65 tests/update/update-home-recovery.test.ts +334 tests/update/update-home-worker.test.ts +169 tests/update/update-job-supervised-restart.test.ts +258 tests/update/update-job.test.ts +65 tests/update/update-mise-launcher-target.test.ts +50 tests/update/update-mise-node-runtime.test.ts +493 tests/update/update-mise.test.ts +120 tests/update/update-mutation-boundaries.test.ts +126 tests/update/update-mutation-guard.test.ts +93 tests/update/update-mutation-scanner.test.ts +88 tests/update/update-notify.test.ts +353 tests/update/update-npm-cache-preflight.test.ts +48 tests/update/update-npm-invocation.test.ts +98 tests/update/update-npm-supervisor-exit.test.ts +40 tests/update/update-npm-timeout.test.ts +90 tests/update/update-pnpm.test.ts +47 tests/update/update-reclaim-authorizer.test.ts +89 tests/update/update-recovery-authority.test.ts +191 tests/update/update-recovery-boundaries.test.ts +30 tests/update/update-recovery-host-free.test.ts +208 tests/update/update-refresh.test.ts +35515 tests/update/update-restart-lease.test.ts 48 tests/update/update-service-home-policy.test.ts -175 tests/update/update-service-home.test.ts -165 tests/update/update-standalone.test.ts -1599 tests/update/update-stop-classification.test.ts -9466 tests/update/update-stop-first.test.ts -46 tests/update/update-supervised-recovery.test.ts -3200 tests/update/update-teardown-handover.test.ts -530 tests/update/update-transactional-leftovers.test.ts -196 tests/update/update-transactional.test.ts -1411 tests/update/update-tray-handoff.test.ts -202 tests/update/update-tree-ownership.test.ts -78 tests/update/update-windows-wrapper-authority.test.ts -68 tests/update/update-worker-launch.test.ts +139 tests/update/update-service-home.test.ts +85 tests/update/update-standalone.test.ts +1963 tests/update/update-stop-classification.test.ts +7923 tests/update/update-stop-first.test.ts +108 tests/update/update-supervised-recovery.test.ts +2994 tests/update/update-teardown-handover.test.ts +511 tests/update/update-transactional-leftovers.test.ts +631 tests/update/update-transactional.test.ts +1332 tests/update/update-tray-handoff.test.ts +179 tests/update/update-tree-ownership.test.ts +84 tests/update/update-windows-wrapper-authority.test.ts +115 tests/update/update-worker-launch.test.ts 55 tests/usage/anthropic2-usage-attribution.test.ts -90 tests/usage/cache-diagnostic.test.ts -356 tests/usage/cost-cap-unknown-evidence.test.ts -83 tests/usage/cost-scoring.test.ts -62 tests/usage/gpt61-terra-pricing.test.ts -61 tests/usage/jev-stats.test.ts -112 tests/usage/key-attribution.test.ts -301 tests/usage/quota-401-recovery-runtime.test.ts -77 tests/usage/quota-401-recovery.test.ts -3119 tests/usage/quota-pool.test.ts -78 tests/usage/quota-reset-account-key.test.ts -357 tests/usage/quota-reset-core-boundary.test.ts -46 tests/usage/quota-reset-detector.test.ts -46 tests/usage/quota-reset-notify-config.test.ts -411 tests/usage/quota-reset-notify.test.ts -597 tests/usage/quota-reset-observation.test.ts -1716 tests/usage/quota-reset-seen-store.test.ts -125 tests/usage/quota-scoring.test.ts -1452 tests/usage/request-decompress.test.ts -40 tests/usage/request-evidence.test.ts -891 tests/usage/request-history-index.test.ts -1252 tests/usage/request-history-rebuild-worker.test.ts -95 tests/usage/request-log-attempt-identity.test.ts -115 tests/usage/request-log-conversation.test.ts -151 tests/usage/request-log-estimate-cap.test.ts -243 tests/usage/request-log-generation-window.test.ts -86 tests/usage/request-log-jev.test.ts -45 tests/usage/request-log-model-filter.test.ts -216 tests/usage/request-log-nonstream.test.ts -94 tests/usage/request-log-protocol-trace.test.ts -92 tests/usage/request-log-served-model.test.ts -354 tests/usage/request-log.test.ts -153 tests/usage/request-outcome-agreement.test.ts -48 tests/usage/request-pacing-provenance.test.ts -222 tests/usage/request-pacing.test.ts -19159 tests/usage/upstream-failure-diagnostics.test.ts -200 tests/usage/usage-aggregate-cache.test.ts -56 tests/usage/usage-anthropic-fast-pricing.test.ts -50 tests/usage/usage-antigravity-55.test.ts -70 tests/usage/usage-attempt-delivery.test.ts -93 tests/usage/usage-cost.test.ts -43 tests/usage/usage-cursor-fast-pricing.test.ts -217 tests/usage/usage-debug.test.ts -43 tests/usage/usage-failure-fingerprint.test.ts -86 tests/usage/usage-failure-persistence.test.ts -36 tests/usage/usage-failure-projection.test.ts -53 tests/usage/usage-haiku-5-5-pricing.test.ts -165 tests/usage/usage-ledger-retention.test.ts -246 tests/usage/usage-ledger-scanner.test.ts -45 tests/usage/usage-log-ws-stage.test.ts -2726 tests/usage/usage-log.test.ts -114 tests/usage/usage-partly-measured-cost.test.ts -52 tests/usage/usage-prompt-length-pricing.test.ts -47 tests/usage/usage-provider-label.test.ts -256 tests/usage/usage-shape-extraction.test.ts -81 tests/usage/usage-snapshot-digest-reuse.test.ts -55 tests/usage/usage-spend-cache-provenance.test.ts -124 tests/usage/usage-summary.test.ts -61 tests/usage/usage-surfaces.test.ts +93 tests/usage/cache-diagnostic.test.ts +249 tests/usage/cost-cap-unknown-evidence.test.ts +123 tests/usage/cost-scoring.test.ts +67 tests/usage/gpt61-terra-pricing.test.ts +53 tests/usage/jev-stats.test.ts +100 tests/usage/key-attribution.test.ts +355 tests/usage/quota-401-recovery-runtime.test.ts +100 tests/usage/quota-401-recovery.test.ts +2927 tests/usage/quota-pool.test.ts +100 tests/usage/quota-reset-account-key.test.ts +340 tests/usage/quota-reset-core-boundary.test.ts +56 tests/usage/quota-reset-detector.test.ts +63 tests/usage/quota-reset-notify-config.test.ts +410 tests/usage/quota-reset-notify.test.ts +568 tests/usage/quota-reset-observation.test.ts +1755 tests/usage/quota-reset-seen-store.test.ts +105 tests/usage/quota-scoring.test.ts +2776 tests/usage/request-decompress.test.ts +45 tests/usage/request-evidence.test.ts +1729 tests/usage/request-history-index.test.ts +3273 tests/usage/request-history-integrity.test.ts +1387 tests/usage/request-history-rebuild-worker.test.ts +202 tests/usage/request-log-attempt-identity.test.ts +198 tests/usage/request-log-conversation.test.ts +170 tests/usage/request-log-estimate-cap.test.ts +286 tests/usage/request-log-generation-window.test.ts +92 tests/usage/request-log-jev.test.ts +44 tests/usage/request-log-model-filter.test.ts +198 tests/usage/request-log-nonstream.test.ts +112 tests/usage/request-log-normalization.test.ts +135 tests/usage/request-log-protocol-trace.test.ts +134 tests/usage/request-log-served-model.test.ts +568 tests/usage/request-log.test.ts +194 tests/usage/request-outcome-agreement.test.ts +47 tests/usage/request-pacing-provenance.test.ts +235 tests/usage/request-pacing.test.ts +19235 tests/usage/upstream-failure-diagnostics.test.ts +215 tests/usage/usage-aggregate-cache.test.ts +44 tests/usage/usage-anthropic-fast-pricing.test.ts +53 tests/usage/usage-antigravity-55.test.ts +93 tests/usage/usage-attempt-delivery.test.ts +69 tests/usage/usage-cost.test.ts +41 tests/usage/usage-cursor-fast-pricing.test.ts +210 tests/usage/usage-debug.test.ts +46 tests/usage/usage-failure-fingerprint.test.ts +141 tests/usage/usage-failure-persistence.test.ts +40 tests/usage/usage-failure-projection.test.ts +67 tests/usage/usage-haiku-5-5-pricing.test.ts +188 tests/usage/usage-ledger-retention.test.ts +257 tests/usage/usage-ledger-scanner.test.ts +41 tests/usage/usage-log-ws-stage.test.ts +3228 tests/usage/usage-log.test.ts +113 tests/usage/usage-partly-measured-cost.test.ts +42 tests/usage/usage-prompt-length-pricing.test.ts +42 tests/usage/usage-provider-label.test.ts +208 tests/usage/usage-shape-extraction.test.ts +84 tests/usage/usage-snapshot-digest-reuse.test.ts +73 tests/usage/usage-spend-cache-provenance.test.ts +114 tests/usage/usage-summary.test.ts +65 tests/usage/usage-surfaces.test.ts 50 tests/usage/usage-throughput.test.ts -51 tests/usage/usage-time-range.test.ts -3039 tests/usage/usage-timeline.test.ts -108 tests/usage/user-cost-overlay-coderabbit-regressions.test.ts -1307 tests/usage/user-cost-overlay-live-reconcile.test.ts -62 tests/usage/user-cost-overlay-provider-delete.test.ts -47 tests/videos/fulfill-video.test.ts +72 tests/usage/usage-time-range.test.ts +2816 tests/usage/usage-timeline.test.ts +100 tests/usage/user-cost-overlay-coderabbit-regressions.test.ts +1520 tests/usage/user-cost-overlay-live-reconcile.test.ts +137 tests/usage/user-cost-overlay-provider-delete.test.ts +87 tests/videos/fulfill-video.test.ts 84 tests/videos/plan-video.test.ts -55 tests/videos/xai-video-client.test.ts -830 tests/vision/mistral-vision-sidecar.test.ts -119 tests/vision/sidecar-abort.test.ts -160 tests/vision/sidecar-auth.test.ts -88 tests/vision/sidecar-candidates.test.ts -385 tests/vision/sidecar-settings-vision-catalog.test.ts -363 tests/vision/sidecar-settings-vision-controls.test.ts -233 tests/vision/sidecar-settings-vision-filter.test.ts -217 tests/vision/sidecar-settings-web-search-gate.test.ts -207 tests/vision/sidecar-settings-web-search-off.test.ts -278 tests/vision/sidecar-settings-web-search-stream.test.ts -44 tests/vision/sidecar-tracker.test.ts -295 tests/vision/vision-anthropic-instance-sidecar.test.ts -154 tests/vision/vision-anthropic.test.ts -247 tests/vision/vision-backend-union.test.ts -147 tests/vision/vision-cache.test.ts -87 tests/vision/vision-custom-row-precedence.test.ts -74 tests/vision/vision-eligibility.test.ts -150 tests/vision/vision-fail-closed.test.ts -219 tests/vision/vision-reasoning-contract.test.ts -571 tests/vision/vision-routed.test.ts -1544 tests/vision/vision-sidecar-e2e.test.ts -111 tests/vision/vision-text-only-predicate.test.ts -90 tests/web-search/devin-web-search.test.ts -60 tests/web-search/fix-search-frame-shapes.test.ts -42 tests/web-search/fix-search-orphan-source.test.ts -36 tests/web-search/fix-search-unicode-clamp.test.ts -57 tests/web-search/format-result.test.ts -247 tests/web-search/web-search-anthropic-instance.test.ts -104 tests/web-search/web-search-anthropic.test.ts -381 tests/web-search/web-search-backend-union.test.ts -93 tests/web-search/web-search-bridge-replay.test.ts -125 tests/web-search/web-search-candidates.test.ts -182 tests/web-search/web-search-forced-declaration.test.ts -108 tests/web-search/web-search-loop-error-usage.test.ts -90 tests/web-search/web-search-loop-iteration-usage.test.ts -162 tests/web-search/web-search-pacing-deadline.test.ts -54 tests/web-search/web-search-parse.test.ts -332 tests/web-search/web-search-passthrough-bridge.test.ts -2482 tests/web-search/web-search-progress-stream.test.ts -88 tests/web-search/web-search-recovery-kind.test.ts -1610 tests/web-search/web-search-retry-heartbeat.test.ts -212 tests/web-search/web-search-rotation-usage-attribution.test.ts -137 tests/web-search/web-search-run-turn-loop.test.ts -7168 tests/web-search/web-search-sidecar-429.test.ts -193 tests/web-search/web-search-sidecar-replay.test.ts -40 tests/web-search/web-search-sources.test.ts -166 tests/web-search/web-search-terminal-refusal.test.ts -423 tests/web-search/web-search-timeout-contract.test.ts -160 tests/web-search/web-search-timeout-plan.test.ts -5434 tests/web-search/web-search.test.ts -61 tests/windows/coding-agent-native-empty-argv.test.ts -36 tests/windows/tray-proxy-deadline.test.ts -2333 tests/windows/tray-proxy.test.ts -41 tests/windows/win-exec.test.ts -40 tests/windows/win-paths.test.ts -51 tests/windows/windows-acl-start-cost.test.ts -47 tests/windows/windows-atomic-replace.test.ts -98 tests/windows/windows-codex-cli-job-store.test.ts +64 tests/videos/xai-video-client.test.ts +944 tests/vision/mistral-vision-sidecar.test.ts +133 tests/vision/sidecar-abort.test.ts +128 tests/vision/sidecar-auth.test.ts +175 tests/vision/sidecar-candidates.test.ts +394 tests/vision/sidecar-settings-vision-catalog.test.ts +316 tests/vision/sidecar-settings-vision-controls.test.ts +443 tests/vision/sidecar-settings-vision-filter.test.ts +225 tests/vision/sidecar-settings-web-search-gate.test.ts +458 tests/vision/sidecar-settings-web-search-off.test.ts +331 tests/vision/sidecar-settings-web-search-stream.test.ts +46 tests/vision/sidecar-tracker.test.ts +417 tests/vision/vision-anthropic-instance-sidecar.test.ts +157 tests/vision/vision-anthropic.test.ts +248 tests/vision/vision-backend-union.test.ts +176 tests/vision/vision-cache.test.ts +301 tests/vision/vision-custom-row-precedence.test.ts +131 tests/vision/vision-eligibility.test.ts +104 tests/vision/vision-fail-closed.test.ts +300 tests/vision/vision-reasoning-contract.test.ts +802 tests/vision/vision-routed.test.ts +1619 tests/vision/vision-sidecar-e2e.test.ts +192 tests/vision/vision-text-only-predicate.test.ts +97 tests/web-search/devin-web-search.test.ts +45 tests/web-search/fix-search-frame-shapes.test.ts +40 tests/web-search/fix-search-orphan-source.test.ts +41 tests/web-search/fix-search-unicode-clamp.test.ts +147 tests/web-search/format-result.test.ts +304 tests/web-search/web-search-anthropic-instance.test.ts +122 tests/web-search/web-search-anthropic.test.ts +1473 tests/web-search/web-search-backend-union.test.ts +97 tests/web-search/web-search-bridge-replay.test.ts +117 tests/web-search/web-search-candidates.test.ts +47 tests/web-search/web-search-eof.test.ts +137 tests/web-search/web-search-forced-declaration.test.ts +118 tests/web-search/web-search-loop-error-usage.test.ts +103 tests/web-search/web-search-loop-iteration-usage.test.ts +183 tests/web-search/web-search-pacing-deadline.test.ts +108 tests/web-search/web-search-parse.test.ts +395 tests/web-search/web-search-passthrough-bridge.test.ts +2346 tests/web-search/web-search-progress-stream.test.ts +108 tests/web-search/web-search-recovery-kind.test.ts +1604 tests/web-search/web-search-retry-heartbeat.test.ts +148 tests/web-search/web-search-rotation-usage-attribution.test.ts +102 tests/web-search/web-search-run-turn-loop.test.ts +7583 tests/web-search/web-search-sidecar-429.test.ts +269 tests/web-search/web-search-sidecar-replay.test.ts +46 tests/web-search/web-search-sources.test.ts +246 tests/web-search/web-search-terminal-refusal.test.ts +525 tests/web-search/web-search-timeout-contract.test.ts +85 tests/web-search/web-search-timeout-plan.test.ts +5319 tests/web-search/web-search.test.ts +69 tests/windows/coding-agent-native-empty-argv.test.ts +63 tests/windows/tray-proxy-deadline.test.ts +2319 tests/windows/tray-proxy.test.ts +49 tests/windows/win-exec.test.ts +39 tests/windows/win-paths.test.ts +44 tests/windows/windows-acl-start-cost.test.ts +44 tests/windows/windows-atomic-replace.test.ts +97 tests/windows/windows-atomic-write-acl-rearm.test.ts +125 tests/windows/windows-codex-cli-job-store.test.ts 67 tests/windows/windows-config-read-acl-memo.test.ts -525 tests/windows/windows-config-root-async-writers.test.ts -49 tests/windows/windows-deploy-close-regressions.test.ts -353 tests/windows/windows-elevation-spawn.test.ts -47 tests/windows/windows-elevation.test.ts -51 tests/windows/windows-guarded-manager.test.ts -62 tests/windows/windows-lifecycle-root-acl.test.ts -42 tests/windows/windows-native-principal.test.ts -131 tests/windows/windows-popup-fix.test.ts -43 tests/windows/windows-process-priority.test.ts -44 tests/windows/windows-scheduler-errors.test.ts -158 tests/windows/windows-scheduler-install-verification.test.ts -56 tests/windows/windows-secret-acl-diagnostics.test.ts -48 tests/windows/windows-secret-acl-removal-flight.test.ts -370 tests/windows/windows-secret-acl.test.ts -177 tests/windows/windows-service-mutation-lock.test.ts -44 tests/windows/windows-service-wrappers.test.ts -73 tests/windows/windows-text-decoding.test.ts -52 tests/windows/windows-tray-restart-hardening.test.ts -57 tests/windows/windows-tray-run-limit.test.ts -1888 tests/windows/windows-tray.test.ts -78 tests/windows/windows-user-principal-nonascii.test.ts -50 tests/windows/windows-user-principal.test.ts -53 tests/windows/winsw-stop-hardening.test.ts +492 tests/windows/windows-config-root-async-writers.test.ts +48 tests/windows/windows-deploy-close-regressions.test.ts +360 tests/windows/windows-elevation-spawn.test.ts +53 tests/windows/windows-elevation.test.ts +77 tests/windows/windows-guarded-manager.test.ts +68 tests/windows/windows-lifecycle-root-acl.test.ts +75 tests/windows/windows-native-principal.test.ts +216 tests/windows/windows-popup-fix.test.ts +47 tests/windows/windows-process-priority.test.ts +62 tests/windows/windows-scheduler-errors.test.ts +228 tests/windows/windows-scheduler-install-verification.test.ts +57 tests/windows/windows-secret-acl-diagnostics.test.ts +128 tests/windows/windows-secret-acl-removal-flight.test.ts +355 tests/windows/windows-secret-acl.test.ts +147 tests/windows/windows-service-mutation-lock.test.ts +47 tests/windows/windows-service-wrappers.test.ts +77 tests/windows/windows-text-decoding.test.ts +72 tests/windows/windows-tray-restart-hardening.test.ts +51 tests/windows/windows-tray-run-limit.test.ts +1828 tests/windows/windows-tray.test.ts +116 tests/windows/windows-user-principal-nonascii.test.ts +41 tests/windows/windows-user-principal.test.ts +114 tests/windows/winsw-stop-hardening.test.ts diff --git a/scripts/ci/test-durations.windows.tsv b/scripts/ci/test-durations.windows.tsv index 61c67a8ed31..775d91ec853 100644 --- a/scripts/ci/test-durations.windows.tsv +++ b/scripts/ci/test-durations.windows.tsv @@ -1,2779 +1,2857 @@ # Per-file Bun test durations in milliseconds, read from hosted CI job logs. # Consumed by scripts/ci/run-bun-test-batches.sh to balance shards; a file without a row weighs the median. # Regenerate with scripts/ci/test-durations.ts (usage in its header); do not edit by hand. -# Source: runs 40756291846 and 40743681086, completed zero-failure primary Windows batches only; unfinished/failed batches and attribution excluded; prior rows retained for unmeasured files -2919 tests/adapters/abort-race.test.ts -2134 tests/adapters/adapter-buffered-tool-conformance.test.ts -1510 tests/adapters/adapter-error-inline.test.ts -3291 tests/adapters/adapter-inner-send-budget-wiring.test.ts -4305 tests/adapters/adapter-inner-send-budget.test.ts -743 tests/adapters/adapter-input-media-guard.test.ts -807 tests/adapters/adapter-registry-authority.test.ts -3134 tests/adapters/adapter-tool-conformance.test.ts -840 tests/adapters/adapter-usage.test.ts -10742 tests/adapters/anthropic/anthropic-429-policy.test.ts -396 tests/adapters/anthropic/anthropic-account-metadata.test.ts -1281 tests/adapters/anthropic/anthropic-account-pause-outbound.test.ts -27849 tests/adapters/anthropic/anthropic-account-pause.test.ts -29959 tests/adapters/anthropic/anthropic-account-pool.test.ts -26305 tests/adapters/anthropic/anthropic-account-threshold.test.ts -4564 tests/adapters/anthropic/anthropic-affinity-restart.test.ts -6088 tests/adapters/anthropic/anthropic-affinity-store.test.ts -81 tests/adapters/anthropic/anthropic-agentrouter-language-framing.test.ts -1230 tests/adapters/anthropic/anthropic-baseurl-override.test.ts -435 tests/adapters/anthropic/anthropic-beta-allowlist.test.ts -501 tests/adapters/anthropic/anthropic-beta-body-pairs.test.ts -16807 tests/adapters/anthropic/anthropic-billing-ownership.test.ts -332 tests/adapters/anthropic/anthropic-billing-refusal.test.ts +# Source: run 41437409412 (attempt 1, workflow_dispatch on dev 5cfd0ac11): windows 1/11-11/11 (11/11 failed one assertion; files measured to completion count); prior rows retained for unmeasured files +3673 tests/adapters/abort-race.test.ts +6047 tests/adapters/adapter-buffered-tool-conformance.test.ts +1404 tests/adapters/adapter-error-inline.test.ts +5027 tests/adapters/adapter-inner-send-budget-wiring.test.ts +3455 tests/adapters/adapter-inner-send-budget.test.ts +4299 tests/adapters/adapter-input-media-guard.test.ts +426 tests/adapters/adapter-registry-authority.test.ts +2066 tests/adapters/adapter-tool-conformance.test.ts +206 tests/adapters/adapter-usage.test.ts +18812 tests/adapters/anthropic/anthropic-429-policy.test.ts +141 tests/adapters/anthropic/anthropic-account-metadata.test.ts +1685 tests/adapters/anthropic/anthropic-account-pause-outbound.test.ts +18663 tests/adapters/anthropic/anthropic-account-pause.test.ts +29212 tests/adapters/anthropic/anthropic-account-pool.test.ts +31459 tests/adapters/anthropic/anthropic-account-threshold.test.ts +3056 tests/adapters/anthropic/anthropic-active-limit-routing.test.ts +4592 tests/adapters/anthropic/anthropic-affinity-restart.test.ts +6109 tests/adapters/anthropic/anthropic-affinity-store.test.ts +79 tests/adapters/anthropic/anthropic-agentrouter-language-framing.test.ts +110 tests/adapters/anthropic/anthropic-baseurl-override.test.ts +128 tests/adapters/anthropic/anthropic-beta-allowlist.test.ts +79 tests/adapters/anthropic/anthropic-beta-body-pairs.test.ts +16920 tests/adapters/anthropic/anthropic-billing-ownership.test.ts +333 tests/adapters/anthropic/anthropic-billing-refusal.test.ts 95 tests/adapters/anthropic/anthropic-client-identity.test.ts -7990 tests/adapters/anthropic/anthropic-combo-account-cooldown.test.ts -2801 tests/adapters/anthropic/anthropic-compatible-stream.test.ts -3410 tests/adapters/anthropic/anthropic-cooldown-recovery.test.ts -118 tests/adapters/anthropic/anthropic-empty-content.test.ts -113 tests/adapters/anthropic/anthropic-eof-tolerance.test.ts -2371 tests/adapters/anthropic/anthropic-error-body.test.ts +6530 tests/adapters/anthropic/anthropic-combo-account-cooldown.test.ts +2646 tests/adapters/anthropic/anthropic-compatible-stream.test.ts +3332 tests/adapters/anthropic/anthropic-cooldown-recovery.test.ts +65 tests/adapters/anthropic/anthropic-empty-content.test.ts +126 tests/adapters/anthropic/anthropic-eof-tolerance.test.ts +981 tests/adapters/anthropic/anthropic-error-body.test.ts 81 tests/adapters/anthropic/anthropic-error-stop-reason.test.ts -4875 tests/adapters/anthropic/anthropic-fast-opt-in.test.ts -126 tests/adapters/anthropic/anthropic-fast-speed.test.ts -88 tests/adapters/anthropic/anthropic-haiku-5-5-contract.test.ts -78 tests/adapters/anthropic/anthropic-hardening.test.ts -180 tests/adapters/anthropic/anthropic-image-guard.test.ts -3737 tests/adapters/anthropic/anthropic-image-normalize.test.ts -9512 tests/adapters/anthropic/anthropic-image-retry-e2e.test.ts -197 tests/adapters/anthropic/anthropic-image-retry.test.ts -21474 tests/adapters/anthropic/anthropic-instance-isolation.test.ts -28679 tests/adapters/anthropic/anthropic-instance-pool-parity.test.ts -49016 tests/adapters/anthropic/anthropic-instance-quota.test.ts -91036 tests/adapters/anthropic/anthropic-instance-recovery.test.ts -104 tests/adapters/anthropic/anthropic-message-stop-termination.test.ts -112 tests/adapters/anthropic/anthropic-messages-passthrough-oauth.test.ts -78 tests/adapters/anthropic/anthropic-messages-passthrough.test.ts -41094 tests/adapters/anthropic/anthropic-model-routes.test.ts -13437 tests/adapters/anthropic/anthropic-model-weekly-admission.test.ts -95 tests/adapters/anthropic/anthropic-opaque-strip.test.ts -122 tests/adapters/anthropic/anthropic-output-maxima.test.ts -88 tests/adapters/anthropic/anthropic-parallel-tool-disable.test.ts -119 tests/adapters/anthropic/anthropic-pool-toggle-copy.test.ts -5931 tests/adapters/anthropic/anthropic-pool-usage-limit.test.ts -204 tests/adapters/anthropic/anthropic-progress-updates.test.ts -9151 tests/adapters/anthropic/anthropic-quota-cooldown-recovery.test.ts -37852 tests/adapters/anthropic/anthropic-quota-dispatch.test.ts -9177 tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts -293 tests/adapters/anthropic/anthropic-reasoning.test.ts +3347 tests/adapters/anthropic/anthropic-fast-opt-in.test.ts +79 tests/adapters/anthropic/anthropic-fast-speed.test.ts +63 tests/adapters/anthropic/anthropic-haiku-5-5-contract.test.ts +63 tests/adapters/anthropic/anthropic-hardening.test.ts +175 tests/adapters/anthropic/anthropic-image-guard.test.ts +2092 tests/adapters/anthropic/anthropic-image-normalize.test.ts +7035 tests/adapters/anthropic/anthropic-image-retry-e2e.test.ts +270 tests/adapters/anthropic/anthropic-image-retry.test.ts +18091 tests/adapters/anthropic/anthropic-instance-isolation.test.ts +23342 tests/adapters/anthropic/anthropic-instance-pool-parity.test.ts +45495 tests/adapters/anthropic/anthropic-instance-quota.test.ts +125930 tests/adapters/anthropic/anthropic-instance-recovery.test.ts +80 tests/adapters/anthropic/anthropic-message-stop-termination.test.ts +82 tests/adapters/anthropic/anthropic-messages-passthrough-oauth.test.ts +111 tests/adapters/anthropic/anthropic-messages-passthrough.test.ts +38816 tests/adapters/anthropic/anthropic-model-routes.test.ts +16878 tests/adapters/anthropic/anthropic-model-weekly-admission.test.ts +45 tests/adapters/anthropic/anthropic-opaque-strip.test.ts +79 tests/adapters/anthropic/anthropic-output-maxima.test.ts +66 tests/adapters/anthropic/anthropic-parallel-tool-disable.test.ts +155 tests/adapters/anthropic/anthropic-pool-toggle-copy.test.ts +6680 tests/adapters/anthropic/anthropic-pool-usage-limit.test.ts +301 tests/adapters/anthropic/anthropic-progress-updates.test.ts +10551 tests/adapters/anthropic/anthropic-quota-cooldown-recovery.test.ts +37509 tests/adapters/anthropic/anthropic-quota-dispatch.test.ts +9646 tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts +317 tests/adapters/anthropic/anthropic-reasoning.test.ts 63 tests/adapters/anthropic/anthropic-replay.test.ts -1303 tests/adapters/anthropic/anthropic-reset-grants.test.ts -10438 tests/adapters/anthropic/anthropic-revoked-token-boundaries.test.ts -4682 tests/adapters/anthropic/anthropic-revoked-token-continuation.test.ts -12166 tests/adapters/anthropic/anthropic-revoked-token-sidecars.test.ts -67053 tests/adapters/anthropic/anthropic-revoked-token.test.ts -991 tests/adapters/anthropic/anthropic-sidecar-account-failover.test.ts -88 tests/adapters/anthropic/anthropic-sonnet-5-5-contract.test.ts -96 tests/adapters/anthropic/anthropic-stream-hardening.test.ts -10245 tests/adapters/anthropic/anthropic-subscription-chain.test.ts -71 tests/adapters/anthropic/anthropic-tail-guard.test.ts -221 tests/adapters/anthropic/anthropic-thinking-signature.test.ts -104 tests/adapters/anthropic/anthropic-thinking-usage.test.ts -79 tests/adapters/anthropic/anthropic-tool-call-id.test.ts -196 tests/adapters/anthropic/anthropic-tool-declaration-constraints.test.ts +1442 tests/adapters/anthropic/anthropic-reset-grants.test.ts +8675 tests/adapters/anthropic/anthropic-revoked-token-boundaries.test.ts +5961 tests/adapters/anthropic/anthropic-revoked-token-continuation.test.ts +12960 tests/adapters/anthropic/anthropic-revoked-token-sidecars.test.ts +64080 tests/adapters/anthropic/anthropic-revoked-token.test.ts +1168 tests/adapters/anthropic/anthropic-sidecar-account-failover.test.ts +65 tests/adapters/anthropic/anthropic-sonnet-5-5-contract.test.ts +63 tests/adapters/anthropic/anthropic-stream-hardening.test.ts +11768 tests/adapters/anthropic/anthropic-subscription-chain.test.ts +63 tests/adapters/anthropic/anthropic-tail-guard.test.ts +285 tests/adapters/anthropic/anthropic-thinking-signature.test.ts +73 tests/adapters/anthropic/anthropic-thinking-usage.test.ts +62 tests/adapters/anthropic/anthropic-tool-call-id.test.ts +129 tests/adapters/anthropic/anthropic-tool-declaration-constraints.test.ts 64 tests/adapters/anthropic/anthropic-tool-schema.test.ts -9243 tests/adapters/anthropic/anthropic2-fast-parity.test.ts -261 tests/adapters/bridge-legacy-shell-normalization.test.ts -3740 tests/adapters/bridge-lifecycle.test.ts -533 tests/adapters/bridge-nonstreaming-terminal.test.ts -235 tests/adapters/bridge-raw-reasoning-hidden.test.ts -158 tests/adapters/bridge-reasoning-replay-batch.test.ts -126 tests/adapters/bridge-stall.test.ts -174 tests/adapters/bridge-terminal-refusal.test.ts -228 tests/adapters/bridge-terminal-singleness.test.ts -202 tests/adapters/bridge.test.ts -65 tests/adapters/buffered-response-shape-guards.test.ts -79 tests/adapters/coding-agent-history-projection.test.ts -72 tests/adapters/coding-agent-tool-result-images.test.ts -141 tests/adapters/coding-agent-windows-dispatch.test.ts -185 tests/adapters/dsh-account-adapter.test.ts -2516 tests/adapters/empty-tool-output-annotation.test.ts -283 tests/adapters/exec-tool-result-normalize.test.ts -328 tests/adapters/fix-tool-number-preservation.test.ts -1235 tests/adapters/google/antigravity-account-roster.test.ts -104 tests/adapters/google/antigravity-baseurl-override.test.ts -245 tests/adapters/google/antigravity-discovered-families.test.ts -133 tests/adapters/google/antigravity-refusal.test.ts -3282 tests/adapters/google/antigravity-routing-carry.test.ts -166 tests/adapters/google/antigravity-static-catalog.test.ts -866 tests/adapters/google/gcp-adc.test.ts -11202 tests/adapters/google/gcp-credential-boundary.test.ts -790 tests/adapters/google/gcp-sa-adapter.test.ts -17491 tests/adapters/google/gcp-sa-marker.test.ts -103 tests/adapters/google/gemini-37-flash-migration.test.ts -284 tests/adapters/google/gemini-4-argon-antigravity.test.ts -111 tests/adapters/google/gemini-progress-history.test.ts -183 tests/adapters/google/gemini-web-search.test.ts -241 tests/adapters/google/google-adapter.test.ts -102 tests/adapters/google/google-ai-studio-foreign-call-signature.test.ts -4415 tests/adapters/google/google-antigravity-oauth.test.ts -2580 tests/adapters/google/google-antigravity-replay.test.ts -165 tests/adapters/google/google-antigravity-wire.test.ts -161 tests/adapters/google/google-buffered-stop-reason.test.ts -88 tests/adapters/google/google-claude-prefill-guard.test.ts -68 tests/adapters/google/google-empty-content.test.ts -97 tests/adapters/google/google-errors.test.ts -191 tests/adapters/google/google-hardening.test.ts -688 tests/adapters/google/google-models-listing.test.ts -72 tests/adapters/google/google-output-clamp.test.ts -70 tests/adapters/google/google-provider-metadata-roundtrip.test.ts -444 tests/adapters/google/google-signature-history-roundtrip.test.ts -95 tests/adapters/google/google-stream-fragmentation.test.ts -88 tests/adapters/google/google-strict-tool-validated-mode.test.ts -154 tests/adapters/google/google-structured-output.test.ts -79 tests/adapters/google/google-tool-result-adjacency.test.ts -111 tests/adapters/google/google-tool-schema-contract.test.ts -103 tests/adapters/google/google-tool-schema.test.ts -4670 tests/adapters/google/google-vertex-http.test.ts -320 tests/adapters/google/google-vertex-key-project.test.ts -118 tests/adapters/google/google-vertex-stream.test.ts -97 tests/adapters/google/google-vertex-thought-signature.test.ts -87 tests/adapters/google/google-wire-compiler.test.ts -121 tests/adapters/google/google-wire-shape.test.ts -157 tests/adapters/google/vertex-catalog.test.ts -480 tests/adapters/identity-neutralize.test.ts -787 tests/adapters/identity-subagent.test.ts -14391 tests/adapters/key-failover.test.ts -190 tests/adapters/openai/inline-think-boundaries.test.ts -8005 tests/adapters/openai/openai-api-virtual-models.test.ts -80 tests/adapters/openai/openai-chat-audio.test.ts -570 tests/adapters/openai/openai-chat-bounded-tool-names.test.ts -89 tests/adapters/openai/openai-chat-dangling-toolcalls.test.ts -150 tests/adapters/openai/openai-chat-developer-position.test.ts -95 tests/adapters/openai/openai-chat-eof.test.ts -142 tests/adapters/openai/openai-chat-glm-summary.test.ts -446 tests/adapters/openai/openai-chat-hardening.test.ts -5862 tests/adapters/openai/openai-chat-image-normalization.test.ts -134 tests/adapters/openai/openai-chat-inline-think-tags.test.ts -88 tests/adapters/openai/openai-chat-invalid-tool-call-diagnostics.test.ts -167 tests/adapters/openai/openai-chat-mistral-content.test.ts -205 tests/adapters/openai/openai-chat-model-suffix.test.ts -1300 tests/adapters/openai/openai-chat-native-policy.test.ts -245 tests/adapters/openai/openai-chat-nonce-tool-call-content.test.ts -119 tests/adapters/openai/openai-chat-parallel-stream.test.ts -174 tests/adapters/openai/openai-chat-path-override.test.ts -169 tests/adapters/openai/openai-chat-qwen38-leading-system.test.ts -189 tests/adapters/openai/openai-chat-reasoning-wire-policy.test.ts -111 tests/adapters/openai/openai-chat-required-tool.test.ts -238 tests/adapters/openai/openai-chat-sanitization-review-regressions.test.ts -104 tests/adapters/openai/openai-chat-serialized-tool-call-content.test.ts -244 tests/adapters/openai/openai-chat-serialized-tool-call-hold-bound.test.ts -380 tests/adapters/openai/openai-chat-serialized-tool-call-scaling.test.ts -96 tests/adapters/openai/openai-chat-serialized-tool-call-think.test.ts -380 tests/adapters/openai/openai-chat-standalone-bare-block.test.ts -262 tests/adapters/openai/openai-chat-system-order.test.ts -111 tests/adapters/openai/openai-chat-tool-call-id-remint.test.ts -92 tests/adapters/openai/openai-chat-tool-result-images.test.ts -78 tests/adapters/openai/openai-chat-url.test.ts -79 tests/adapters/openai/openai-chat-video-part.test.ts -260 tests/adapters/openai/openai-empty-assistant-history.test.ts -341 tests/adapters/openai/openai-native-hosted-search-history.test.ts -5479 tests/adapters/openai/openai-provider-option-e2e.test.ts -647 tests/adapters/openai/openai-provider-option-migration.test.ts -219 tests/adapters/openai/openai-provider-option-startup.test.ts -183 tests/adapters/openai/openai-provider-option-tooling.test.ts -64 tests/adapters/openai/openai-provider-option.test.ts -57 tests/adapters/openai/opengateway-input.test.ts -488 tests/adapters/physical-send.test.ts -165 tests/adapters/qoder-spawn-readmission.test.ts -184 tests/adapters/reasoning-replay-identity.test.ts -397 tests/adapters/reasoning-replay-robustness.test.ts -389 tests/adapters/routed-agent-messages.test.ts -249 tests/adapters/run-turn-queue.test.ts -2860 tests/adapters/terminal-continuation-owner-rotation.test.ts -175 tests/adapters/tool-argument-integers.test.ts -88 tests/adapters/tool-catalog-nudge.test.ts -146 tests/adapters/tool-choice-performance.test.ts -154 tests/adapters/tool-envelope-echo-whole-line.test.ts -157 tests/adapters/tool-identity-hash.test.ts -619 tests/adapters/translator-budget-lifetime.test.ts -4309 tests/adapters/translator-budget.test.ts -75 tests/adapters/upstream-http-error.test.ts -109 tests/adapters/workbuddy-adapter.test.ts -1552 tests/advisor/advisor-adaptive.test.ts -189 tests/advisor/advisor-authority-transport.test.ts -1404 tests/advisor/advisor-budget.test.ts -106 tests/advisor/advisor-consult.test.ts -181 tests/advisor/advisor-context.test.ts -156 tests/advisor/advisor-continuation-limit.test.ts -639 tests/advisor/advisor-core-boundary.test.ts -201 tests/advisor/advisor-evidence.test.ts -86 tests/advisor/advisor-guard.test.ts -414 tests/advisor/advisor-internal-authority.test.ts -112 tests/advisor/advisor-plan.test.ts -6915 tests/advisor/advisor-responses-wiring.test.ts -492 tests/advisor/advisor-retention.test.ts -1176 tests/advisor/advisor-scope-transport.test.ts -319 tests/advisor/advisor-settings.test.ts -134 tests/advisor/advisor-state.test.ts -191 tests/ci-workflows/assert-mergeable-review.test.ts -68 tests/ci-workflows/brand-favicons.test.ts -79 tests/ci-workflows/build-desktop-icon-set.test.ts -359 tests/ci-workflows/build-release-changelog.test.ts -428 tests/ci-workflows/bump-dev-version.test.ts -1238 tests/ci-workflows/bun-runtime.test.ts -77 tests/ci-workflows/ci-bun-crash-classifier.test.ts -163 tests/ci-workflows/ci-bun-install-frozen.test.ts -80 tests/ci-workflows/ci-concurrency-groups.test.ts -84 tests/ci-workflows/ci-crash-disposition.test.ts -5203 tests/ci-workflows/ci-gui-typecheck-gate.test.ts -198 tests/ci-workflows/ci-pr-hygiene-approvals.test.ts -153 tests/ci-workflows/ci-privacy-gate.test.ts -324 tests/ci-workflows/ci-review-lanes.test.ts -1536 tests/ci-workflows/ci-scope-gaps.test.ts -112 tests/ci-workflows/ci-scope-reduction.test.ts -112 tests/ci-workflows/ci-shard-balance.test.ts -84 tests/ci-workflows/ci-structure-gate.test.ts -159 tests/ci-workflows/ci-test-lane.test.ts -1114 tests/ci-workflows/ci-workflows.test.ts -84 tests/ci-workflows/cleanup-orphaned-workflows.test.ts -136 tests/ci-workflows/closed-pr-branch-cleanup.test.ts -6584 tests/ci-workflows/cold-spawn-warmup.test.ts -267 tests/ci-workflows/compatibility-version.test.ts -87 tests/ci-workflows/docs-429-failover-claims.test.ts -79 tests/ci-workflows/docs-bun-source-requirement.test.ts -64 tests/ci-workflows/docs-developer-role-policy.test.ts -80 tests/ci-workflows/docs-gjc-reasoning-export.test.ts -81 tests/ci-workflows/docs-gpt61-terra.test.ts -65 tests/ci-workflows/docs-gui-screenshot-policy.test.ts -349 tests/ci-workflows/docs-link-targets.test.ts -71 tests/ci-workflows/docs-provider-billing-claims.test.ts -215 tests/ci-workflows/docs-provider-discovery-limits.test.ts -73 tests/ci-workflows/docs-provider-preset-counts.test.ts -343 tests/ci-workflows/docs-readme-memory-inventory.test.ts -68 tests/ci-workflows/docs-readme-translation-parity.test.ts -169 tests/ci-workflows/docs-remote-hub-claims.test.ts -409 tests/ci-workflows/dsh-path-contract.test.ts -738 tests/ci-workflows/dsh-rc6-compat-script.test.ts -717 tests/ci-workflows/dsh-writer-lock.test.ts -100 tests/ci-workflows/exhaustive-deps-suppression.test.ts -531 tests/ci-workflows/file-size-ratchet.test.ts -361 tests/ci-workflows/fixture-dir-uniqueness.test.ts -152 tests/ci-workflows/fixture-teardown-helper.test.ts -1164 tests/ci-workflows/fixture-windows-runtime-preload.test.ts -650 tests/ci-workflows/import-cycle-ratchet.test.ts -127 tests/ci-workflows/install-scripts.test.ts -112 tests/ci-workflows/installed-gate-drivers.test.ts -111 tests/ci-workflows/keyring-smoke.test.ts -228 tests/ci-workflows/linux-desktop-packaged-ci.test.ts +10072 tests/adapters/anthropic/anthropic2-fast-parity.test.ts +159 tests/adapters/bridge-legacy-shell-normalization.test.ts +3758 tests/adapters/bridge-lifecycle.test.ts +183 tests/adapters/bridge-nonstreaming-terminal.test.ts +423 tests/adapters/bridge-raw-reasoning-hidden.test.ts +3173 tests/adapters/bridge-reasoning-replay-batch.test.ts +1042 tests/adapters/bridge-stall.test.ts +201 tests/adapters/bridge-terminal-refusal.test.ts +80 tests/adapters/bridge-terminal-singleness.test.ts +365 tests/adapters/bridge.test.ts +127 tests/adapters/buffered-response-shape-guards.test.ts +222 tests/adapters/coding-agent-history-projection.test.ts +221 tests/adapters/coding-agent-tool-result-images.test.ts +272 tests/adapters/coding-agent-windows-dispatch.test.ts +96 tests/adapters/dsh-account-adapter.test.ts +2893 tests/adapters/empty-tool-output-annotation.test.ts +111 tests/adapters/exec-tool-result-normalize.test.ts +293 tests/adapters/fix-tool-number-preservation.test.ts +1267 tests/adapters/google/antigravity-account-roster.test.ts +134 tests/adapters/google/antigravity-baseurl-override.test.ts +174 tests/adapters/google/antigravity-discovered-families.test.ts +47 tests/adapters/google/antigravity-refusal.test.ts +2963 tests/adapters/google/antigravity-routing-carry.test.ts +141 tests/adapters/google/antigravity-static-catalog.test.ts +901 tests/adapters/google/gcp-adc.test.ts +12340 tests/adapters/google/gcp-credential-boundary.test.ts +1356 tests/adapters/google/gcp-sa-adapter.test.ts +23094 tests/adapters/google/gcp-sa-marker.test.ts +207 tests/adapters/google/gemini-37-flash-migration.test.ts +161 tests/adapters/google/gemini-4-argon-antigravity.test.ts +80 tests/adapters/google/gemini-progress-history.test.ts +175 tests/adapters/google/gemini-web-search.test.ts +256 tests/adapters/google/google-adapter.test.ts +64 tests/adapters/google/google-ai-studio-foreign-call-signature.test.ts +4457 tests/adapters/google/google-antigravity-oauth.test.ts +2673 tests/adapters/google/google-antigravity-replay.test.ts +129 tests/adapters/google/google-antigravity-wire.test.ts +79 tests/adapters/google/google-buffered-stop-reason.test.ts +95 tests/adapters/google/google-claude-prefill-guard.test.ts +95 tests/adapters/google/google-empty-content.test.ts +82 tests/adapters/google/google-errors.test.ts +79 tests/adapters/google/google-hardening.test.ts +686 tests/adapters/google/google-models-listing.test.ts +49 tests/adapters/google/google-output-clamp.test.ts +61 tests/adapters/google/google-provider-metadata-roundtrip.test.ts +299 tests/adapters/google/google-signature-history-roundtrip.test.ts +109 tests/adapters/google/google-stream-fragmentation.test.ts +96 tests/adapters/google/google-strict-tool-validated-mode.test.ts +62 tests/adapters/google/google-structured-output.test.ts +98 tests/adapters/google/google-tool-result-adjacency.test.ts +80 tests/adapters/google/google-tool-schema-contract.test.ts +110 tests/adapters/google/google-tool-schema.test.ts +4576 tests/adapters/google/google-vertex-http.test.ts +127 tests/adapters/google/google-vertex-key-project.test.ts +111 tests/adapters/google/google-vertex-stream.test.ts +128 tests/adapters/google/google-vertex-thought-signature.test.ts +95 tests/adapters/google/google-wire-compiler.test.ts +113 tests/adapters/google/google-wire-shape.test.ts +251 tests/adapters/google/vertex-catalog.test.ts +468 tests/adapters/identity-neutralize.test.ts +939 tests/adapters/identity-subagent.test.ts +13932 tests/adapters/key-failover.test.ts +441 tests/adapters/openai/inline-think-boundaries.test.ts +8290 tests/adapters/openai/openai-api-virtual-models.test.ts +98 tests/adapters/openai/openai-chat-audio.test.ts +364 tests/adapters/openai/openai-chat-bounded-tool-names.test.ts +63 tests/adapters/openai/openai-chat-dangling-toolcalls.test.ts +249 tests/adapters/openai/openai-chat-developer-position.test.ts +130 tests/adapters/openai/openai-chat-eof.test.ts +94 tests/adapters/openai/openai-chat-glm-summary.test.ts +397 tests/adapters/openai/openai-chat-hardening.test.ts +5681 tests/adapters/openai/openai-chat-image-normalization.test.ts +97 tests/adapters/openai/openai-chat-inline-think-tags.test.ts +94 tests/adapters/openai/openai-chat-invalid-tool-call-diagnostics.test.ts +174 tests/adapters/openai/openai-chat-mistral-content.test.ts +142 tests/adapters/openai/openai-chat-model-suffix.test.ts +1679 tests/adapters/openai/openai-chat-native-policy.test.ts +177 tests/adapters/openai/openai-chat-nonce-tool-call-content.test.ts +142 tests/adapters/openai/openai-chat-parallel-stream.test.ts +159 tests/adapters/openai/openai-chat-path-override.test.ts +96 tests/adapters/openai/openai-chat-qwen38-leading-system.test.ts +125 tests/adapters/openai/openai-chat-reasoning-wire-policy.test.ts +126 tests/adapters/openai/openai-chat-required-tool.test.ts +223 tests/adapters/openai/openai-chat-sanitization-review-regressions.test.ts +80 tests/adapters/openai/openai-chat-serialized-tool-call-content.test.ts +316 tests/adapters/openai/openai-chat-serialized-tool-call-hold-bound.test.ts +125 tests/adapters/openai/openai-chat-serialized-tool-call-scaling.test.ts +110 tests/adapters/openai/openai-chat-serialized-tool-call-think.test.ts +112 tests/adapters/openai/openai-chat-single-system.test.ts +508 tests/adapters/openai/openai-chat-standalone-bare-block.test.ts +238 tests/adapters/openai/openai-chat-system-order.test.ts +94 tests/adapters/openai/openai-chat-tool-call-id-remint.test.ts +48 tests/adapters/openai/openai-chat-tool-result-images.test.ts +47 tests/adapters/openai/openai-chat-url.test.ts +66 tests/adapters/openai/openai-chat-video-part.test.ts +190 tests/adapters/openai/openai-empty-assistant-history.test.ts +410 tests/adapters/openai/openai-native-hosted-search-history.test.ts +4752 tests/adapters/openai/openai-provider-option-e2e.test.ts +1066 tests/adapters/openai/openai-provider-option-migration.test.ts +266 tests/adapters/openai/openai-provider-option-startup.test.ts +127 tests/adapters/openai/openai-provider-option-tooling.test.ts +79 tests/adapters/openai/openai-provider-option.test.ts +96 tests/adapters/openai/opengateway-input.test.ts +394 tests/adapters/physical-send.test.ts +183 tests/adapters/qoder-spawn-readmission.test.ts +95 tests/adapters/reasoning-replay-identity.test.ts +272 tests/adapters/reasoning-replay-robustness.test.ts +551 tests/adapters/routed-agent-messages.test.ts +233 tests/adapters/run-turn-queue.test.ts +2671 tests/adapters/terminal-continuation-owner-rotation.test.ts +95 tests/adapters/tool-argument-integers.test.ts +246 tests/adapters/tool-catalog-nudge.test.ts +246 tests/adapters/tool-choice-performance.test.ts +230 tests/adapters/tool-envelope-echo-whole-line.test.ts +79 tests/adapters/tool-identity-hash.test.ts +284 tests/adapters/translator-budget-lifetime.test.ts +5578 tests/adapters/translator-budget.test.ts +63 tests/adapters/upstream-http-error.test.ts +108 tests/adapters/workbuddy-adapter.test.ts +1320 tests/advisor/advisor-adaptive.test.ts +63 tests/advisor/advisor-authority-transport.test.ts +1187 tests/advisor/advisor-budget.test.ts +1880 tests/advisor/advisor-caller-policy-compact.test.ts +2821 tests/advisor/advisor-caller-policy-host-key.test.ts +2053 tests/advisor/advisor-caller-policy-http.test.ts +839 tests/advisor/advisor-caller-policy-ingress.test.ts +1889 tests/advisor/advisor-caller-policy-jev.test.ts +881 tests/advisor/advisor-caller-policy-replay.test.ts +3815 tests/advisor/advisor-caller-policy-routing.test.ts +2283 tests/advisor/advisor-caller-policy-self-fetch.test.ts +1158 tests/advisor/advisor-caller-policy-sidecar-authority.test.ts +1738 tests/advisor/advisor-caller-policy-vision.test.ts +5560 tests/advisor/advisor-caller-policy.test.ts +95 tests/advisor/advisor-consult.test.ts +81 tests/advisor/advisor-context.test.ts +79 tests/advisor/advisor-continuation-limit.test.ts +599 tests/advisor/advisor-core-boundary.test.ts +167 tests/advisor/advisor-evidence.test.ts +266 tests/advisor/advisor-guard.test.ts +191 tests/advisor/advisor-internal-authority.test.ts +303 tests/advisor/advisor-plan.test.ts +11627 tests/advisor/advisor-responses-wiring.test.ts +381 tests/advisor/advisor-retention.test.ts +1697 tests/advisor/advisor-scope-transport.test.ts +368 tests/advisor/advisor-settings.test.ts +108 tests/advisor/advisor-state.test.ts +273 tests/advisor/advisor-web-search.test.ts +101 tests/ci-workflows/assert-mergeable-review.test.ts +221 tests/ci-workflows/brand-favicons.test.ts +84 tests/ci-workflows/build-desktop-icon-set.test.ts +270 tests/ci-workflows/build-release-changelog.test.ts +351 tests/ci-workflows/bump-dev-version.test.ts +860 tests/ci-workflows/bun-runtime.test.ts +63 tests/ci-workflows/ci-bun-crash-classifier.test.ts +82 tests/ci-workflows/ci-bun-install-frozen.test.ts +93 tests/ci-workflows/ci-concurrency-groups.test.ts +64 tests/ci-workflows/ci-crash-disposition.test.ts +5324 tests/ci-workflows/ci-gui-typecheck-gate.test.ts +190 tests/ci-workflows/ci-pr-hygiene-approvals.test.ts +46 tests/ci-workflows/ci-privacy-gate.test.ts +440 tests/ci-workflows/ci-review-lanes.test.ts +1583 tests/ci-workflows/ci-scope-gaps.test.ts +91 tests/ci-workflows/ci-scope-reduction.test.ts +147 tests/ci-workflows/ci-shard-balance.test.ts +80 tests/ci-workflows/ci-structure-gate.test.ts +63 tests/ci-workflows/ci-test-lane.test.ts +902 tests/ci-workflows/ci-workflows.test.ts +81 tests/ci-workflows/cleanup-orphaned-workflows.test.ts +356 tests/ci-workflows/client-support-matrix.test.ts +2105 tests/ci-workflows/client-support-runtime.test.ts +91 tests/ci-workflows/closed-pr-branch-cleanup.test.ts +6492 tests/ci-workflows/cold-spawn-warmup.test.ts +428 tests/ci-workflows/compatibility-version.test.ts +64 tests/ci-workflows/docs-429-failover-claims.test.ts +63 tests/ci-workflows/docs-bun-source-requirement.test.ts +112 tests/ci-workflows/docs-developer-role-policy.test.ts +47 tests/ci-workflows/docs-gjc-reasoning-export.test.ts +97 tests/ci-workflows/docs-gpt61-terra.test.ts +77 tests/ci-workflows/docs-gui-screenshot-policy.test.ts +348 tests/ci-workflows/docs-link-targets.test.ts +81 tests/ci-workflows/docs-provider-billing-claims.test.ts +127 tests/ci-workflows/docs-provider-discovery-limits.test.ts +81 tests/ci-workflows/docs-provider-preset-counts.test.ts +286 tests/ci-workflows/docs-readme-memory-inventory.test.ts +50 tests/ci-workflows/docs-readme-translation-parity.test.ts +64 tests/ci-workflows/docs-remote-hub-claims.test.ts +300 tests/ci-workflows/dsh-path-contract.test.ts +495 tests/ci-workflows/dsh-rc6-compat-script.test.ts +538 tests/ci-workflows/dsh-writer-lock.test.ts +60 tests/ci-workflows/exhaustive-deps-suppression.test.ts +569 tests/ci-workflows/file-size-ratchet.test.ts +476 tests/ci-workflows/fixture-dir-uniqueness.test.ts +107 tests/ci-workflows/fixture-teardown-helper.test.ts +1149 tests/ci-workflows/fixture-windows-runtime-preload.test.ts +361 tests/ci-workflows/import-cycle-ratchet.test.ts +160 tests/ci-workflows/install-scripts.test.ts +81 tests/ci-workflows/installed-gate-drivers.test.ts +269 tests/ci-workflows/keyring-smoke.test.ts +151 tests/ci-workflows/linux-desktop-packaged-ci.test.ts 81 tests/ci-workflows/linux-desktop-packaged-e2e.test.ts -160 tests/ci-workflows/macos-serial-lanes.test.ts -6183 tests/ci-workflows/package-tree-fenced-restart.test.ts -5724 tests/ci-workflows/package-tree-integrity.test.ts -399 tests/ci-workflows/package-tree-restart-ownership.test.ts -420 tests/ci-workflows/package-tree-retarget.test.ts -245 tests/ci-workflows/pr-readiness-reattest.test.ts -207 tests/ci-workflows/privacy-scan-asset-names.test.ts -150 tests/ci-workflows/privacy-scan-meta-key.test.ts -135 tests/ci-workflows/privacy-scan-ssh-endpoint.test.ts -204 tests/ci-workflows/release-desktop-scripts.test.ts -33638 tests/ci-workflows/release-helper.test.ts -113 tests/ci-workflows/release-notes.test.ts -161 tests/ci-workflows/release-outcome-report.test.ts -650 tests/ci-workflows/release-pipeline-contract.test.ts -255 tests/ci-workflows/release-preflight.test.ts -169 tests/ci-workflows/release-resume-identity.test.ts -141 tests/ci-workflows/release-version-line.test.ts -423 tests/ci-workflows/release-version-sources.test.ts -12378 tests/ci-workflows/release-windows-signing.test.ts -762 tests/ci-workflows/repo-hygiene.test.ts -615 tests/ci-workflows/repo-import-resolution.test.ts -2124 tests/ci-workflows/setup-hooks.test.ts -1114 tests/ci-workflows/skill-ocx-generated.test.ts -372 tests/ci-workflows/skill-ocx-workflows.test.ts -101 tests/ci-workflows/skill-ocx.test.ts -3275 tests/ci-workflows/structure-ssot.test.ts -2408 tests/ci-workflows/test-home-guard-unpreloaded.test.ts -59691 tests/ci-workflows/test-home-guard.test.ts -24667 tests/ci-workflows/test-run-lock-generation.test.ts -254 tests/ci-workflows/test-runner-bun.test.ts -148 tests/ci-workflows/test-runner-spawnsync-finalizer.test.ts -28159 tests/ci-workflows/test-runner.test.ts -148 tests/ci-workflows/test-sandbox-cleanup.test.ts -96 tests/ci-workflows/test-temp-quarantine.test.ts -95 tests/ci-workflows/version-line.test.ts -120 tests/ci-workflows/warmup-registration.test.ts -80 tests/ci-workflows/zz-ci-api-usage-isolation.test.ts -77 tests/ci-workflows/zz-ci-storage-policy-isolation.test.ts -293 tests/ci-workflows/zz-pr-coderabbit-readiness-revalidation.test.ts -72128 tests/claude-integration/anthropic2-native-routing.test.ts -8167 tests/claude-integration/claude-529-mapping.test.ts -191 tests/claude-integration/claude-agent-startup-sync.test.ts -443 tests/claude-integration/claude-agents-inject-client.test.ts -437 tests/claude-integration/claude-agents-inject.test.ts -128 tests/claude-integration/claude-alias.test.ts -453 tests/claude-integration/claude-auth-detect.test.ts -231 tests/claude-integration/claude-auth-mode.test.ts -64 tests/claude-integration/claude-authmode-migration.test.ts -5101 tests/claude-integration/claude-cli-picker-surface.test.ts -1148 tests/claude-integration/claude-cli-picker.test.ts -153 tests/claude-integration/claude-cli.test.ts -15610 tests/claude-integration/claude-client-refusal-status.test.ts -992 tests/claude-integration/claude-code-thought-signature-scope.test.ts -283 tests/claude-integration/claude-compatibility.test.ts -603 tests/claude-integration/claude-config-home-isolation.test.ts -6599 tests/claude-integration/claude-config-root-late-admission.test.ts -2097 tests/claude-integration/claude-config-root-stale-updates.test.ts -1855 tests/claude-integration/claude-config-root-writer-barrier.test.ts -183 tests/claude-integration/claude-context-accounting.test.ts -167 tests/claude-integration/claude-context-windows.test.ts -254 tests/claude-integration/claude-desktop-1m.test.ts -48859 tests/claude-integration/claude-desktop-cli.test.ts -6472 tests/claude-integration/claude-desktop-config-path.test.ts -15767 tests/claude-integration/claude-desktop-discovery.test.ts -15680 tests/claude-integration/claude-desktop-first-party-guards.test.ts -92009 tests/claude-integration/claude-desktop-first-party.test.ts -168 tests/claude-integration/claude-desktop-mode-explanation.test.ts -306 tests/claude-integration/claude-desktop-native-context.test.ts -16895 tests/claude-integration/claude-desktop-picker-profile.test.ts -33734 tests/claude-integration/claude-desktop-picker-routes.test.ts -4767 tests/claude-integration/claude-desktop-picker.test.ts -95 tests/claude-integration/claude-desktop-policy.test.ts -40951 tests/claude-integration/claude-desktop-remote-hub.test.ts -165 tests/claude-integration/claude-desktop-system-proxy.test.ts -2830 tests/claude-integration/claude-devin-output-order.test.ts -158 tests/claude-integration/claude-dotenv-provenance-transport.test.ts -2962 tests/claude-integration/claude-estimate-projection.test.ts -23365 tests/claude-integration/claude-first-party-agent-sync.test.ts -35871 tests/claude-integration/claude-first-party-union.test.ts -119 tests/claude-integration/claude-gateway-cache.test.ts -2104 tests/claude-integration/claude-gateway-output-cap.test.ts -2297 tests/claude-integration/claude-inbound-cache-stabilize.test.ts -89 tests/claude-integration/claude-inbound-debug.test.ts -143 tests/claude-integration/claude-inbound-token-footer.test.ts -3285 tests/claude-integration/claude-inbound-tool-loading.test.ts -389 tests/claude-integration/claude-inbound-tool-reference.test.ts -174 tests/claude-integration/claude-inbound.test.ts -3300 tests/claude-integration/claude-intercept-acl-barrier.test.ts -128 tests/claude-integration/claude-intercept-cleanup.test.ts -190 tests/claude-integration/claude-intercept-client-class.test.ts -27567 tests/claude-integration/claude-intercept-local-ca-files.test.ts -12946 tests/claude-integration/claude-intercept-local-ca-windows.test.ts -19185 tests/claude-integration/claude-intercept-local-ca.test.ts -1093 tests/claude-integration/claude-intercept-model-bindings.test.ts -3475 tests/claude-integration/claude-intercept-no-proxy.test.ts -13769 tests/claude-integration/claude-intercept-on-demand.test.ts -8538 tests/claude-integration/claude-intercept-proxy-auth.test.ts -157 tests/claude-integration/claude-intercept-proxy.test.ts -2085 tests/claude-integration/claude-intercept-settings.test.ts -438 tests/claude-integration/claude-long-context-eligibility.test.ts -275691 tests/claude-integration/claude-management-api.test.ts -80480 tests/claude-integration/claude-messages-endpoint.test.ts -4657 tests/claude-integration/claude-messages-thread.test.ts -4149 tests/claude-integration/claude-model-default-labels.test.ts -402 tests/claude-integration/claude-model-info.test.ts -22199 tests/claude-integration/claude-models-discovery.test.ts -6569 tests/claude-integration/claude-native-affinity.test.ts -7234 tests/claude-integration/claude-native-fast-1m-ingress.test.ts -146254 tests/claude-integration/claude-native-passthrough.test.ts -311 tests/claude-integration/claude-native-rate-limit-headers.test.ts -151 tests/claude-integration/claude-native-reasoning-continuity.test.ts -737 tests/claude-integration/claude-native-reasoning-provenance.test.ts -30115 tests/claude-integration/claude-outbound.test.ts -328 tests/claude-integration/claude-output-schema-strict.test.ts -237 tests/claude-integration/claude-picker-bootstrap.test.ts -22112 tests/claude-integration/claude-picker-ca-store.test.ts -12312 tests/claude-integration/claude-picker-ca.test.ts -189 tests/claude-integration/claude-picker-linger.test.ts -1087 tests/claude-integration/claude-picker-listener.test.ts -95 tests/claude-integration/claude-picker-models.test.ts -10049 tests/claude-integration/claude-picker-recovery.test.ts -15525 tests/claude-integration/claude-picker-relay-intent.test.ts -42796 tests/claude-integration/claude-picker-runtime.test.ts -28335 tests/claude-integration/claude-picker-startup.test.ts -2435 tests/claude-integration/claude-picker-trust-windows.test.ts -96 tests/claude-integration/claude-picker-trust.test.ts -3995 tests/claude-integration/claude-picker-upload.test.ts -37593 tests/claude-integration/claude-picker-windows.test.ts -5166 tests/claude-integration/claude-prompt-too-long.test.ts -174 tests/claude-integration/claude-shell-hook.test.ts -215 tests/claude-integration/claude-sidecar-override.test.ts -159 tests/claude-integration/claude-source-envelope.test.ts -254 tests/claude-integration/claude-subagent-model-force.test.ts -198 tests/claude-integration/claude-system-env-auto.test.ts -3922 tests/claude-integration/claude-tool-loading-destinations.test.ts -806 tests/claude-integration/claude-translated-cache-ttl.test.ts -984 tests/claude-integration/claude-translated-server-tools.test.ts -888 tests/claude-integration/messages-native-decline-trace.test.ts -9971 tests/claude-integration/messages-native-empty-inline.test.ts -13991 tests/claude-integration/messages-native-key-selection.test.ts -58996 tests/claude-integration/messages-native-oauth.test.ts -2341 tests/claude-integration/messages-native-opaque-state.test.ts -9511 tests/claude-integration/messages-native-scope.test.ts -43427 tests/claude-integration/messages-native.test.ts -58906 tests/claude-integration/messages-request-id-endpoint.test.ts -175 tests/claude-integration/messages-request-id-headers.test.ts -35665 tests/claude-integration/messages-revoked-token.test.ts -314 tests/claude-integration/messages-surface-matrix.test.ts -162 tests/cli/agent-driven.test.ts -143 tests/cli/agent-subagent-force.test.ts -2107 tests/cli/bun-transpiler-cache-scope.test.ts -244 tests/cli/claude-config-first-party.test.ts -24270 tests/cli/cli-access-audio-live.test.ts -656 tests/cli/cli-access-audio.test.ts -327 tests/cli/cli-access-data-plane.test.ts -167 tests/cli/cli-access-key-guard.test.ts -514 tests/cli/cli-access-rename.test.ts -324 tests/cli/cli-account-alias-target.test.ts -118 tests/cli/cli-account-cancel-flow.test.ts -143 tests/cli/cli-account-key-pause.test.ts -223 tests/cli/cli-account-key-quota.test.ts -142 tests/cli/cli-account-kiro-device.test.ts -682 tests/cli/cli-account-login-options.test.ts -97 tests/cli/cli-account-orca-import.test.ts -245 tests/cli/cli-account-pin-drain.test.ts -2611 tests/cli/cli-account-policy.test.ts -151 tests/cli/cli-account-pool-verbs.test.ts -361 tests/cli/cli-account-preservation.test.ts +110 tests/ci-workflows/macos-serial-lanes.test.ts +4578 tests/ci-workflows/package-tree-fenced-restart.test.ts +5865 tests/ci-workflows/package-tree-integrity.test.ts +158 tests/ci-workflows/package-tree-restart-ownership.test.ts +257 tests/ci-workflows/package-tree-retarget.test.ts +255 tests/ci-workflows/pr-readiness-reattest.test.ts +47 tests/ci-workflows/privacy-scan-asset-names.test.ts +79 tests/ci-workflows/privacy-scan-meta-key.test.ts +240 tests/ci-workflows/privacy-scan-ssh-endpoint.test.ts +245 tests/ci-workflows/release-desktop-scripts.test.ts +31335 tests/ci-workflows/release-helper.test.ts +238 tests/ci-workflows/release-notes.test.ts +250 tests/ci-workflows/release-outcome-report.test.ts +504 tests/ci-workflows/release-pipeline-contract.test.ts +234 tests/ci-workflows/release-preflight.test.ts +80 tests/ci-workflows/release-resume-identity.test.ts +125 tests/ci-workflows/release-version-line.test.ts +301 tests/ci-workflows/release-version-sources.test.ts +10799 tests/ci-workflows/release-windows-signing.test.ts +710 tests/ci-workflows/repo-hygiene.test.ts +735 tests/ci-workflows/repo-import-resolution.test.ts +2104 tests/ci-workflows/setup-hooks.test.ts +742 tests/ci-workflows/skill-ocx-generated.test.ts +366 tests/ci-workflows/skill-ocx-workflows.test.ts +143 tests/ci-workflows/skill-ocx.test.ts +2256 tests/ci-workflows/structure-ssot.test.ts +2725 tests/ci-workflows/test-home-guard-unpreloaded.test.ts +53892 tests/ci-workflows/test-home-guard.test.ts +24725 tests/ci-workflows/test-run-lock-generation.test.ts +269 tests/ci-workflows/test-runner-bun.test.ts +96 tests/ci-workflows/test-runner-spawnsync-finalizer.test.ts +26971 tests/ci-workflows/test-runner.test.ts +63 tests/ci-workflows/test-sandbox-cleanup.test.ts +94 tests/ci-workflows/test-temp-quarantine.test.ts +238 tests/ci-workflows/version-line.test.ts +143 tests/ci-workflows/warmup-registration.test.ts +228 tests/ci-workflows/zz-ci-api-usage-isolation.test.ts +65 tests/ci-workflows/zz-ci-storage-policy-isolation.test.ts +91 tests/ci-workflows/zz-pr-coderabbit-readiness-revalidation.test.ts +67818 tests/claude-integration/anthropic2-native-routing.test.ts +9481 tests/claude-integration/claude-529-mapping.test.ts +270 tests/claude-integration/claude-agent-startup-sync.test.ts +437 tests/claude-integration/claude-agents-inject-client.test.ts +476 tests/claude-integration/claude-agents-inject.test.ts +242 tests/claude-integration/claude-alias.test.ts +78 tests/claude-integration/claude-auth-detect.test.ts +129 tests/claude-integration/claude-auth-mode.test.ts +79 tests/claude-integration/claude-authmode-migration.test.ts +13886 tests/claude-integration/claude-bridge-pool-dispatch.test.ts +238 tests/claude-integration/claude-bridge-pool-session.test.ts +2720 tests/claude-integration/claude-cli-picker-surface.test.ts +1138 tests/claude-integration/claude-cli-picker.test.ts +191 tests/claude-integration/claude-cli.test.ts +12303 tests/claude-integration/claude-client-refusal-status.test.ts +1662 tests/claude-integration/claude-code-thought-signature-scope.test.ts +93 tests/claude-integration/claude-compatibility.test.ts +586 tests/claude-integration/claude-config-home-isolation.test.ts +3914 tests/claude-integration/claude-config-root-late-admission.test.ts +4211 tests/claude-integration/claude-config-root-stale-updates.test.ts +3004 tests/claude-integration/claude-config-root-writer-barrier.test.ts +161 tests/claude-integration/claude-context-accounting.test.ts +142 tests/claude-integration/claude-context-windows.test.ts +316 tests/claude-integration/claude-desktop-1m.test.ts +55591 tests/claude-integration/claude-desktop-cli.test.ts +2672 tests/claude-integration/claude-desktop-config-path.test.ts +11697 tests/claude-integration/claude-desktop-discovery.test.ts +20367 tests/claude-integration/claude-desktop-first-party-guards.test.ts +56348 tests/claude-integration/claude-desktop-first-party.test.ts +239 tests/claude-integration/claude-desktop-mode-explanation.test.ts +7802 tests/claude-integration/claude-desktop-model-visibility.test.ts +205 tests/claude-integration/claude-desktop-native-context.test.ts +18610 tests/claude-integration/claude-desktop-picker-profile.test.ts +33195 tests/claude-integration/claude-desktop-picker-routes.test.ts +6320 tests/claude-integration/claude-desktop-picker.test.ts +158 tests/claude-integration/claude-desktop-policy.test.ts +36306 tests/claude-integration/claude-desktop-remote-hub.test.ts +458 tests/claude-integration/claude-desktop-system-proxy.test.ts +4687 tests/claude-integration/claude-devin-output-order.test.ts +300 tests/claude-integration/claude-dotenv-provenance-transport.test.ts +3657 tests/claude-integration/claude-estimate-projection.test.ts +17227 tests/claude-integration/claude-first-party-agent-sync.test.ts +31211 tests/claude-integration/claude-first-party-union.test.ts +127 tests/claude-integration/claude-gateway-cache.test.ts +3868 tests/claude-integration/claude-gateway-output-cap.test.ts +2527 tests/claude-integration/claude-inbound-cache-stabilize.test.ts +242 tests/claude-integration/claude-inbound-debug.test.ts +82 tests/claude-integration/claude-inbound-token-footer.test.ts +4251 tests/claude-integration/claude-inbound-tool-loading.test.ts +127 tests/claude-integration/claude-inbound-tool-reference.test.ts +312 tests/claude-integration/claude-inbound.test.ts +3687 tests/claude-integration/claude-installation-helper.test.ts +2629 tests/claude-integration/claude-intercept-acl-barrier.test.ts +112 tests/claude-integration/claude-intercept-cleanup.test.ts +174 tests/claude-integration/claude-intercept-client-class.test.ts +24827 tests/claude-integration/claude-intercept-local-ca-files.test.ts +7897 tests/claude-integration/claude-intercept-local-ca-windows.test.ts +13691 tests/claude-integration/claude-intercept-local-ca.test.ts +1155 tests/claude-integration/claude-intercept-model-bindings.test.ts +4762 tests/claude-integration/claude-intercept-no-proxy.test.ts +17462 tests/claude-integration/claude-intercept-on-demand.test.ts +5078 tests/claude-integration/claude-intercept-proxy-auth.test.ts +188 tests/claude-integration/claude-intercept-proxy.test.ts +2031 tests/claude-integration/claude-intercept-settings.test.ts +95 tests/claude-integration/claude-long-context-eligibility.test.ts +150870 tests/claude-integration/claude-management-api.test.ts +108197 tests/claude-integration/claude-messages-endpoint.test.ts +3805 tests/claude-integration/claude-messages-thread.test.ts +3681 tests/claude-integration/claude-model-default-labels.test.ts +510 tests/claude-integration/claude-model-info.test.ts +25934 tests/claude-integration/claude-models-discovery.test.ts +8966 tests/claude-integration/claude-native-affinity.test.ts +5423 tests/claude-integration/claude-native-fast-1m-ingress.test.ts +146239 tests/claude-integration/claude-native-passthrough.test.ts +366 tests/claude-integration/claude-native-rate-limit-headers.test.ts +173 tests/claude-integration/claude-native-reasoning-continuity.test.ts +936 tests/claude-integration/claude-native-reasoning-provenance.test.ts +24006 tests/claude-integration/claude-outbound.test.ts +175 tests/claude-integration/claude-output-schema-strict.test.ts +254 tests/claude-integration/claude-picker-bootstrap.test.ts +15580 tests/claude-integration/claude-picker-ca-store.test.ts +14360 tests/claude-integration/claude-picker-ca.test.ts +126 tests/claude-integration/claude-picker-linger.test.ts +734 tests/claude-integration/claude-picker-listener.test.ts +240 tests/claude-integration/claude-picker-models.test.ts +10949 tests/claude-integration/claude-picker-recovery.test.ts +14016 tests/claude-integration/claude-picker-relay-intent.test.ts +41747 tests/claude-integration/claude-picker-runtime.test.ts +35499 tests/claude-integration/claude-picker-startup.test.ts +299 tests/claude-integration/claude-picker-trust-windows.test.ts +64 tests/claude-integration/claude-picker-trust.test.ts +4019 tests/claude-integration/claude-picker-upload.test.ts +40308 tests/claude-integration/claude-picker-windows.test.ts +6011 tests/claude-integration/claude-prompt-too-long.test.ts +191 tests/claude-integration/claude-shell-hook.test.ts +301 tests/claude-integration/claude-sidecar-override.test.ts +158 tests/claude-integration/claude-source-envelope.test.ts +424 tests/claude-integration/claude-subagent-model-force.test.ts +236 tests/claude-integration/claude-system-env-auto.test.ts +3856 tests/claude-integration/claude-tool-loading-destinations.test.ts +792 tests/claude-integration/claude-translated-cache-ttl.test.ts +2478 tests/claude-integration/claude-translated-server-tools.test.ts +5054 tests/claude-integration/claude-translated-tool-restrictions.test.ts +2715 tests/claude-integration/messages-native-clean-eof.test.ts +1091 tests/claude-integration/messages-native-decline-trace.test.ts +15443 tests/claude-integration/messages-native-empty-inline.test.ts +11071 tests/claude-integration/messages-native-key-selection.test.ts +65012 tests/claude-integration/messages-native-oauth.test.ts +4464 tests/claude-integration/messages-native-opaque-state.test.ts +18027 tests/claude-integration/messages-native-scope.test.ts +46501 tests/claude-integration/messages-native.test.ts +56875 tests/claude-integration/messages-request-id-endpoint.test.ts +143 tests/claude-integration/messages-request-id-headers.test.ts +46348 tests/claude-integration/messages-revoked-token.test.ts +412 tests/claude-integration/messages-shared-sse.test.ts +209 tests/claude-integration/messages-surface-matrix.test.ts +50 tests/cli/agent-driven.test.ts +142 tests/cli/agent-subagent-force.test.ts +2241 tests/cli/bun-transpiler-cache-scope.test.ts +128 tests/cli/claude-config-first-party.test.ts +24194 tests/cli/cli-access-audio-live.test.ts +976 tests/cli/cli-access-audio.test.ts +418 tests/cli/cli-access-data-plane.test.ts +159 tests/cli/cli-access-key-guard.test.ts +538 tests/cli/cli-access-rename.test.ts +162 tests/cli/cli-account-alias-target.test.ts +126 tests/cli/cli-account-cancel-flow.test.ts +128 tests/cli/cli-account-key-pause.test.ts +159 tests/cli/cli-account-key-quota.test.ts +174 tests/cli/cli-account-kiro-device.test.ts +867 tests/cli/cli-account-login-options.test.ts +78 tests/cli/cli-account-orca-import.test.ts +215 tests/cli/cli-account-pin-drain.test.ts +1850 tests/cli/cli-account-policy.test.ts +160 tests/cli/cli-account-pool-verbs.test.ts +111 tests/cli/cli-account-preservation.test.ts 365 tests/cli/cli-account-slot-identity.test.ts -150 tests/cli/cli-account-threshold.test.ts -172 tests/cli/cli-account-verify-status.test.ts -953 tests/cli/cli-account.test.ts -1093 tests/cli/cli-agent-runtime-settings.test.ts -1338 tests/cli/cli-agent-settings.test.ts -120 tests/cli/cli-alias-json.test.ts -79 tests/cli/cli-anthropic-account-threshold.test.ts -174 tests/cli/cli-anthropic2-account.test.ts +143 tests/cli/cli-account-threshold.test.ts +444 tests/cli/cli-account-verify-status.test.ts +1094 tests/cli/cli-account.test.ts +841 tests/cli/cli-agent-runtime-settings.test.ts +2012 tests/cli/cli-agent-settings.test.ts +139 tests/cli/cli-alias-json.test.ts +141 tests/cli/cli-anthropic-account-threshold.test.ts +173 tests/cli/cli-anthropic2-account.test.ts 160 tests/cli/cli-api-protocols.test.ts -270 tests/cli/cli-aside-sync.test.ts -173 tests/cli/cli-capabilities-arguments.test.ts -230 tests/cli/cli-capabilities.test.ts -134 tests/cli/cli-capability-access-workflows.test.ts -199 tests/cli/cli-capability-account-workflows.test.ts -611 tests/cli/cli-capability-agent-workflows.test.ts -12444 tests/cli/cli-capability-data.test.ts -267 tests/cli/cli-capability-integration-workflows.test.ts -443 tests/cli/cli-capability-lab-workflows.test.ts -231 tests/cli/cli-capability-operation-workflows.test.ts -211 tests/cli/cli-capability-provider-workflows.test.ts -296 tests/cli/cli-catalog-command-result.test.ts -86 tests/cli/cli-catalog-prewarm.test.ts -2626 tests/cli/cli-claude-desktop-profile.test.ts -237 tests/cli/cli-client-start-fence.test.ts -886 tests/cli/cli-client-start-owner-e2e.test.ts -3082 tests/cli/cli-codex-cli-update-boundary.test.ts -205 tests/cli/cli-codex-cli-update.test.ts -127 tests/cli/cli-codex-log-guard-compact.test.ts -143 tests/cli/cli-codex-log-guard-protection.test.ts -158 tests/cli/cli-codex-log-guard.test.ts -2468 tests/cli/cli-combo-parity.test.ts -159 tests/cli/cli-combo-partial-update.test.ts -2126 tests/cli/cli-combo-session-pin.test.ts -1975 tests/cli/cli-combo-set-targets.test.ts -230 tests/cli/cli-combo-stats.test.ts -424 tests/cli/cli-companion-timeline.test.ts -264 tests/cli/cli-companion-usage.test.ts -249 tests/cli/cli-companion.test.ts -1606 tests/cli/cli-config-bom.test.ts -9678 tests/cli/cli-config-command.test.ts -3011 tests/cli/cli-config-default-show.test.ts -3557 tests/cli/cli-config-show-client.test.ts -14680 tests/cli/cli-connect-readiness.test.ts -5694 tests/cli/cli-dispatch.test.ts -261 tests/cli/cli-dto-fidelity.test.ts -912 tests/cli/cli-effort-slug.test.ts -2973 tests/cli/cli-effort.test.ts -184 tests/cli/cli-ensure-client-state.test.ts -401 tests/cli/cli-ensure-desktop-cold-start.test.ts -63 tests/cli/cli-ensure-readiness.test.ts -1491 tests/cli/cli-export-command.test.ts -341 tests/cli/cli-export-model-names.test.ts -122 tests/cli/cli-fallback.test.ts -85 tests/cli/cli-head.test.ts -2019 tests/cli/cli-headless-parity.test.ts -4603 tests/cli/cli-help-navigation.test.ts -20246 tests/cli/cli-help-paths.test.ts -9516 tests/cli/cli-help-recovery.test.ts -22375 tests/cli/cli-help.test.ts -1379 tests/cli/cli-init-port.test.ts -222 tests/cli/cli-injection-follow.test.ts -136 tests/cli/cli-integer-options.test.ts -301 tests/cli/cli-integration-cursor.test.ts -142 tests/cli/cli-integration-droid.test.ts -1395 tests/cli/cli-integration-journal.test.ts -3793 tests/cli/cli-integration-preview.test.ts -343 tests/cli/cli-json-contract.test.ts -380 tests/cli/cli-json-input.test.ts -167 tests/cli/cli-kiro-auto-selection.test.ts -246 tests/cli/cli-link-child.test.ts -1902 tests/cli/cli-link-cleanup.test.ts -159 tests/cli/cli-link-enrollment.test.ts -696 tests/cli/cli-link-force.test.ts -222 tests/cli/cli-link.test.ts -410 tests/cli/cli-log-follow.test.ts -264 tests/cli/cli-log-history.test.ts -598 tests/cli/cli-log-view-filter.test.ts -237 tests/cli/cli-logout-runtime.test.ts -166 tests/cli/cli-logs-request-id.test.ts -252 tests/cli/cli-management-auth.test.ts -5638 tests/cli/cli-models-custom-runtime.test.ts -363 tests/cli/cli-models-display-name.test.ts -111 tests/cli/cli-models-free-only.test.ts -2289 tests/cli/cli-models-local-result.test.ts -262 tests/cli/cli-models-order.test.ts -176 tests/cli/cli-models-price.test.ts -175 tests/cli/cli-models-prompt-length-pricing.test.ts -750 tests/cli/cli-models-reasoning.test.ts -244 tests/cli/cli-models-runtime-dispatch.test.ts -160 tests/cli/cli-models-set.test.ts -21553 tests/cli/cli-models.test.ts -245 tests/cli/cli-native-profile.test.ts -264 tests/cli/cli-observe-logs.test.ts -203 tests/cli/cli-observe-snapshot.test.ts -72 tests/cli/cli-path-diagnostics.test.ts -1174 tests/cli/cli-provider-batch.test.ts -254 tests/cli/cli-provider-lifecycle-runtime.test.ts -4784 tests/cli/cli-provider-list-active.test.ts -249 tests/cli/cli-provider-result.test.ts -308 tests/cli/cli-provider-settings.test.ts -6983 tests/cli/cli-provider-sync-result.test.ts -36456 tests/cli/cli-provider.test.ts -2172 tests/cli/cli-ready-subprocess.test.ts -82 tests/cli/cli-ready.test.ts -197 tests/cli/cli-registry.test.ts -404 tests/cli/cli-remote-workspace-hub.test.ts -4719 tests/cli/cli-resolve-subprocess.test.ts -87 tests/cli/cli-resolve.test.ts -207 tests/cli/cli-restart-handoff.test.ts -5457 tests/cli/cli-restart-health.test.ts -7048 tests/cli/cli-restore-back.test.ts -96 tests/cli/cli-route-policy-not-found.test.ts -1997 tests/cli/cli-route-policy-write.test.ts -11141 tests/cli/cli-start-auxiliary-bind.test.ts -106511 tests/cli/cli-start-journal-order.test.ts -13781 tests/cli/cli-start-owner-absence.test.ts -14129 tests/cli/cli-start-owner-evidence.test.ts -63 tests/cli/cli-start-routing-heal-wiring.test.ts -126 tests/cli/cli-status-codex-routing-drift.test.ts -5904 tests/cli/cli-status-hub-state.test.ts -30108 tests/cli/cli-status-json.test.ts -467 tests/cli/cli-status-oauth-health.test.ts -1861 tests/cli/cli-status-startup-health.test.ts -435 tests/cli/cli-stop-json.test.ts -546 tests/cli/cli-stop-refusal-transport.test.ts -330 tests/cli/cli-storage-inspect.test.ts -2292 tests/cli/cli-storage-policy-fields.test.ts -25958 tests/cli/cli-sync-expect-link.test.ts -369 tests/cli/cli-system-health.test.ts -176 tests/cli/cli-system-settings-parity.test.ts -271 tests/cli/cli-transport-honesty.test.ts -2203 tests/cli/cli-update-badge.test.ts -1181 tests/cli/cli-update-restart-admission.test.ts -79 tests/cli/cli-update-restart-child.test.ts -414 tests/cli/cli-update-restart-desktop-service.test.ts -325 tests/cli/cli-update-restart-home.test.ts -399 tests/cli/cli-update-restart-service-record.test.ts -81 tests/cli/cli-update-restart-supervision.test.ts -840 tests/cli/cli-update-restart-transport.test.ts -274 tests/cli/cli-update-restart.test.ts -4054 tests/cli/cli-usage-compare.test.ts -175 tests/cli/cli-usage-hub.test.ts -413 tests/cli/cli-usage-model-search.test.ts -176 tests/cli/cli-usage-report.test.ts -761 tests/cli/cli-usage-scope.test.ts -1590 tests/cli/cli-usage-top.test.ts -14312 tests/cli/cli-v2-runtime.test.ts -14515 tests/cli/cli-version-skew.test.ts -614 tests/cli/cross-home-loopback-family.test.ts -1120 tests/cli/ensure-desired-integrations-race.test.ts -3207 tests/cli/hub-disable.test.ts -1659 tests/cli/hub-gated-local-clients.test.ts -136 tests/cli/hub-invite.test.ts -88 tests/cli/interactive-confirm.test.ts -238 tests/cli/link-apply-restart.test.ts -1236 tests/cli/local-credentials.test.ts -135 tests/cli/model-selection-guidance.test.ts -532 tests/cli/ocx-launcher-desktop-handoff.test.ts +267 tests/cli/cli-aside-sync.test.ts +128 tests/cli/cli-capabilities-arguments.test.ts +302 tests/cli/cli-capabilities.test.ts +176 tests/cli/cli-capability-access-workflows.test.ts +204 tests/cli/cli-capability-account-workflows.test.ts +492 tests/cli/cli-capability-agent-workflows.test.ts +8416 tests/cli/cli-capability-data.test.ts +365 tests/cli/cli-capability-integration-workflows.test.ts +204 tests/cli/cli-capability-lab-workflows.test.ts +388 tests/cli/cli-capability-operation-workflows.test.ts +143 tests/cli/cli-capability-provider-workflows.test.ts +186 tests/cli/cli-catalog-command-result.test.ts +168 tests/cli/cli-catalog-prewarm.test.ts +2921 tests/cli/cli-claude-desktop-profile.test.ts +188 tests/cli/cli-client-start-fence.test.ts +786 tests/cli/cli-client-start-owner-e2e.test.ts +3176 tests/cli/cli-codex-cli-update-boundary.test.ts +161 tests/cli/cli-codex-cli-update.test.ts +174 tests/cli/cli-codex-log-guard-compact.test.ts +190 tests/cli/cli-codex-log-guard-protection.test.ts +221 tests/cli/cli-codex-log-guard.test.ts +2215 tests/cli/cli-combo-parity.test.ts +127 tests/cli/cli-combo-partial-update.test.ts +2280 tests/cli/cli-combo-session-pin.test.ts +2043 tests/cli/cli-combo-set-targets.test.ts +440 tests/cli/cli-combo-stats.test.ts +301 tests/cli/cli-companion-timeline.test.ts +472 tests/cli/cli-companion-usage.test.ts +79 tests/cli/cli-companion.test.ts +1908 tests/cli/cli-config-bom.test.ts +7247 tests/cli/cli-config-command.test.ts +2327 tests/cli/cli-config-default-show.test.ts +2230 tests/cli/cli-config-show-client.test.ts +16109 tests/cli/cli-connect-readiness.test.ts +5191 tests/cli/cli-dispatch.test.ts +127 tests/cli/cli-dto-fidelity.test.ts +901 tests/cli/cli-effort-slug.test.ts +3296 tests/cli/cli-effort.test.ts +222 tests/cli/cli-ensure-client-state.test.ts +127 tests/cli/cli-ensure-desktop-cold-start.test.ts +80 tests/cli/cli-ensure-readiness.test.ts +1262 tests/cli/cli-export-command.test.ts +386 tests/cli/cli-export-model-names.test.ts +82 tests/cli/cli-fallback.test.ts +111 tests/cli/cli-head.test.ts +2026 tests/cli/cli-headless-parity.test.ts +4366 tests/cli/cli-help-navigation.test.ts +22618 tests/cli/cli-help-paths.test.ts +9548 tests/cli/cli-help-recovery.test.ts +14854 tests/cli/cli-help.test.ts +943 tests/cli/cli-init-port.test.ts +172 tests/cli/cli-injection-follow.test.ts +95 tests/cli/cli-integer-options.test.ts +189 tests/cli/cli-integration-cursor.test.ts +251 tests/cli/cli-integration-droid.test.ts +1693 tests/cli/cli-integration-journal.test.ts +2322 tests/cli/cli-integration-preview.test.ts +190 tests/cli/cli-json-contract.test.ts +397 tests/cli/cli-json-input.test.ts +95 tests/cli/cli-kiro-auto-selection.test.ts +284 tests/cli/cli-link-child.test.ts +1440 tests/cli/cli-link-cleanup.test.ts +127 tests/cli/cli-link-enrollment.test.ts +474 tests/cli/cli-link-force.test.ts +189 tests/cli/cli-link.test.ts +300 tests/cli/cli-log-follow.test.ts +175 tests/cli/cli-log-history.test.ts +349 tests/cli/cli-log-view-filter.test.ts +222 tests/cli/cli-logout-runtime.test.ts +144 tests/cli/cli-logs-request-id.test.ts +239 tests/cli/cli-management-auth.test.ts +279 tests/cli/cli-message-mcp.test.ts +2029 tests/cli/cli-models-custom-runtime.test.ts +332 tests/cli/cli-models-display-name.test.ts +143 tests/cli/cli-models-free-only.test.ts +1618 tests/cli/cli-models-local-result.test.ts +175 tests/cli/cli-models-order.test.ts +113 tests/cli/cli-models-price.test.ts +209 tests/cli/cli-models-prompt-length-pricing.test.ts +714 tests/cli/cli-models-reasoning.test.ts +125 tests/cli/cli-models-runtime-dispatch.test.ts +143 tests/cli/cli-models-set.test.ts +21968 tests/cli/cli-models.test.ts +224 tests/cli/cli-native-profile.test.ts +125 tests/cli/cli-observe-logs.test.ts +174 tests/cli/cli-observe-snapshot.test.ts +96 tests/cli/cli-path-diagnostics.test.ts +1330 tests/cli/cli-provider-batch.test.ts +356 tests/cli/cli-provider-cc-switch-import.test.ts +222 tests/cli/cli-provider-lifecycle-runtime.test.ts +3600 tests/cli/cli-provider-list-active.test.ts +130 tests/cli/cli-provider-result.test.ts +534 tests/cli/cli-provider-settings.test.ts +4775 tests/cli/cli-provider-sync-result.test.ts +40750 tests/cli/cli-provider.test.ts +2345 tests/cli/cli-ready-subprocess.test.ts +119 tests/cli/cli-ready.test.ts +274 tests/cli/cli-registry.test.ts +365 tests/cli/cli-remote-workspace-hub.test.ts +3499 tests/cli/cli-resolve-subprocess.test.ts +100 tests/cli/cli-resolve.test.ts +450 tests/cli/cli-restart-handoff.test.ts +4136 tests/cli/cli-restart-health.test.ts +6136 tests/cli/cli-restore-back.test.ts +12918 tests/cli/cli-role-suggestion-history.test.ts +77 tests/cli/cli-route-policy-not-found.test.ts +1293 tests/cli/cli-route-policy-write.test.ts +8839 tests/cli/cli-start-auxiliary-bind.test.ts +177986 tests/cli/cli-start-journal-order.test.ts +32773 tests/cli/cli-start-owner-absence.test.ts +12752 tests/cli/cli-start-owner-evidence.test.ts +79 tests/cli/cli-start-routing-heal-wiring.test.ts +207 tests/cli/cli-status-codex-routing-drift.test.ts +3560 tests/cli/cli-status-hub-state.test.ts +44038 tests/cli/cli-status-json.test.ts +522 tests/cli/cli-status-oauth-health.test.ts +1802 tests/cli/cli-status-startup-health.test.ts +271 tests/cli/cli-stop-json.test.ts +408 tests/cli/cli-stop-refusal-transport.test.ts +399 tests/cli/cli-storage-inspect.test.ts +1312 tests/cli/cli-storage-policy-fields.test.ts +26151 tests/cli/cli-sync-expect-link.test.ts +508 tests/cli/cli-system-health.test.ts +191 tests/cli/cli-system-settings-parity.test.ts +363 tests/cli/cli-transport-honesty.test.ts +1361 tests/cli/cli-update-badge.test.ts +1790 tests/cli/cli-update-restart-admission.test.ts +80 tests/cli/cli-update-restart-child.test.ts +153 tests/cli/cli-update-restart-desktop-service.test.ts +331 tests/cli/cli-update-restart-home.test.ts +189 tests/cli/cli-update-restart-service-record.test.ts +223 tests/cli/cli-update-restart-supervision.test.ts +898 tests/cli/cli-update-restart-transport.test.ts +210 tests/cli/cli-update-restart.test.ts +4219 tests/cli/cli-usage-compare.test.ts +160 tests/cli/cli-usage-hub.test.ts +414 tests/cli/cli-usage-model-search.test.ts +177 tests/cli/cli-usage-report.test.ts +396 tests/cli/cli-usage-scope.test.ts +1811 tests/cli/cli-usage-top.test.ts +15573 tests/cli/cli-v2-runtime.test.ts +10739 tests/cli/cli-version-skew.test.ts +222 tests/cli/cross-home-loopback-family.test.ts +809 tests/cli/ensure-desired-integrations-race.test.ts +1915 tests/cli/hub-disable.test.ts +1220 tests/cli/hub-gated-local-clients.test.ts +439 tests/cli/hub-invite.test.ts +170 tests/cli/interactive-confirm.test.ts +189 tests/cli/link-apply-restart.test.ts +1455 tests/cli/local-credentials.test.ts +191 tests/cli/model-selection-guidance.test.ts +318 tests/cli/ocx-launcher-desktop-handoff.test.ts 80 tests/cli/ocx-launcher-fixture-trust.test.ts -22744 tests/cli/ocx-launcher-runtime.test.ts -82 tests/cli/ocx-launcher-source.test.ts -148 tests/cli/ocx-run.test.ts -6351 tests/cli/restore-completes-shared-teardown.test.ts -2692 tests/cli/route-explainability.test.ts -33975 tests/cli/sibling-home-client-sync.test.ts -95 tests/cli/star-deferral.test.ts -133 tests/cli/start-args.test.ts -63 tests/cli/start-ownership-publication.test.ts -1031 tests/cli/status-install-method.test.ts -95 tests/cli/system-restart-client-package-tree.test.ts -229 tests/cli/system-restart-client.test.ts -29530 tests/cli/uninstall.test.ts -3898 tests/clients/agent-clients.test.ts -254 tests/clients/aside-profile-identity.test.ts -682 tests/clients/aside-profile-paths.test.ts -6501 tests/clients/aside-profile-sync-owner.test.ts -1792 tests/clients/aside-profiles-catalog-refresh.test.ts -10898 tests/clients/aside-profiles.test.ts -136 tests/clients/client-catalog-compatibility.test.ts -82269 tests/clients/client-connect.test.ts -268 tests/clients/client-export-effective-metadata.test.ts -721 tests/clients/client-export-live-wire.test.ts -159 tests/clients/client-export-modality-enum.test.ts -347 tests/clients/client-export-model-names.test.ts -348 tests/clients/client-export-reasoning-controls.test.ts -199 tests/clients/client-export-reasoning-metadata.test.ts -95 tests/clients/client-fingerprint.test.ts -405 tests/clients/client-home-unreachable.test.ts -159 tests/clients/client-hub-relay.test.ts -595 tests/clients/client-hub-state.test.ts -126 tests/clients/client-hub-usage.test.ts -18384 tests/clients/client-lifecycle-lock.test.ts -14967 tests/clients/client-link-connect.test.ts -6035 tests/clients/client-link-relay.test.ts -15912 tests/clients/client-link-runtime.test.ts -928 tests/clients/client-link-state.test.ts -72 tests/clients/client-link-status.test.ts -3860 tests/clients/client-link-teardown.test.ts -9132 tests/clients/client-link-tunnel.test.ts -6719 tests/clients/client-machine-listener.test.ts -162 tests/clients/client-path.test.ts -591 tests/clients/client-runtime-restart.test.ts -785 tests/clients/client-runtime.test.ts -111 tests/clients/cline-client.test.ts -8175 tests/clients/cline-writer.test.ts -3908 tests/clients/command-code-client-contract.test.ts -876 tests/clients/command-code-client.test.ts -547 tests/clients/desktop-3p-guard.test.ts -11895 tests/clients/desktop-3p-removal.test.ts -17146 tests/clients/desktop-3p-write-files.test.ts -9761 tests/clients/desktop-3p.test.ts -118 tests/clients/desktop-app-restart-posix.test.ts -755 tests/clients/desktop-app-restart.test.ts -2582 tests/clients/desktop-app-server-shim-launcher.test.ts -161 tests/clients/desktop-app-server-shim.test.ts -10135 tests/clients/desktop-bundle-trust-async.test.ts -782 tests/clients/desktop-chatgpt-config.test.ts -104 tests/clients/desktop-cli-command-surface.test.ts -71 tests/clients/desktop-cli-contracts.test.ts -2296 tests/clients/desktop-compatibility-authority.test.ts -2195 tests/clients/desktop-compatibility-build-probe.test.ts -111 tests/clients/desktop-compatibility-certificate-service.test.ts -579 tests/clients/desktop-compatibility-connection-store.test.ts -2203 tests/clients/desktop-compatibility-launch.test.ts -199 tests/clients/desktop-compatibility-native-identity.test.ts -230 tests/clients/desktop-compatibility-relay.test.ts -95 tests/clients/desktop-compatibility-routing.test.ts -318 tests/clients/desktop-compatibility-runtime.test.ts -900 tests/clients/desktop-compatibility-trust.test.ts -88 tests/clients/desktop-exit-ownership.test.ts -72 tests/clients/desktop-host-visibility.test.ts -155 tests/clients/desktop-install-identity.test.ts -610 tests/clients/desktop-profile.test.ts -207 tests/clients/desktop-proxy-direct-transport.test.ts -48062 tests/clients/desktop-remote-store.test.ts -202 tests/clients/desktop-restart-handoff.test.ts -121 tests/clients/desktop-runtime-identity.test.ts -72 tests/clients/desktop-start-at-login-default.test.ts -87 tests/clients/desktop-startup-surface.test.ts -1664 tests/clients/desktop-supervised-restart.test.ts -119 tests/clients/desktop-tray-availability.test.ts -96 tests/clients/desktop-update-surface.test.ts -112 tests/clients/desktop-widget-entry.test.ts -3770 tests/clients/droid-client.test.ts -4914 tests/clients/droid-managed-reasoning-defaults.test.ts -1904 tests/clients/droid-normalized-reasoning-defaults.test.ts -1442 tests/clients/gentle-shell-client.test.ts -367 tests/clients/gentle-shell-path.test.ts -3745 tests/clients/hermes-catalog-refresh.test.ts -4558 tests/clients/hermes-profile-routes.test.ts -254 tests/clients/hermes-profiles.test.ts -8364 tests/clients/integrations-current-store.test.ts -9337 tests/clients/integrations-dsh-profile-patch.test.ts -5028 tests/clients/integrations-hermes-affinity.test.ts -3997 tests/clients/integrations-journal.test.ts -1310 tests/clients/integrations-merge.test.ts -5687 tests/clients/integrations-model-names.test.ts -96 tests/clients/integrations-serialize.test.ts -986 tests/clients/integrations-state.test.ts -755 tests/clients/integrations-superseded-store.test.ts -1056 tests/clients/integrations-writer-frozen-config.test.ts -1683 tests/clients/integrations-writer-guard.test.ts -14087 tests/clients/integrations-writer.test.ts -3477 tests/clients/kilo-client.test.ts -179 tests/clients/lazycodex-detection.test.ts -88 tests/clients/link-admission-wait.test.ts -2078 tests/clients/link-apply-record.test.ts -71 tests/clients/link-boundary.test.ts -115 tests/clients/link-codex-settings-digest.test.ts -261 tests/clients/link-compensation.test.ts -260 tests/clients/link-connection-generation.test.ts -1440 tests/clients/link-diagnostics.test.ts -191 tests/clients/link-fingerprint.test.ts -531 tests/clients/link-home-settings.test.ts -72 tests/clients/link-parity-reporter.test.ts -332 tests/clients/link-peer-compatibility.test.ts -1111 tests/clients/link-ports.test.ts -346 tests/clients/link-readiness.test.ts -819 tests/clients/link-relay-bound-transport.test.ts -191 tests/clients/link-routes.test.ts -11256 tests/clients/link-ssh-argv-discovery.test.ts -988 tests/clients/link-ssh-argv.test.ts -94 tests/clients/link-ssh-config.test.ts -538 tests/clients/link-ssh-runner.test.ts -261 tests/clients/link-status-projection.test.ts -215 tests/clients/link-store.test.ts -4791 tests/clients/link-supervisor.test.ts -489 tests/clients/link-tunnel-history.test.ts -72 tests/clients/link-tunnel-state.test.ts -1683 tests/clients/mutation-plan.test.ts -176 tests/clients/omo-client.test.ts -721 tests/clients/omo-role-models.test.ts -362 tests/clients/omp-path-contract.test.ts -218 tests/clients/omp-yaml-source-inline-comments.test.ts -3921 tests/clients/opencode-kilo-refresh.test.ts -296 tests/clients/pi-path-contract.test.ts -181 tests/clients/prime-client.test.ts -3522 tests/clients/qoder-client.test.ts -1150 tests/clients/raycast-client.test.ts -86 tests/clients/raycast-detect.test.ts -6920 tests/clients/remote-catalog.test.ts -219 tests/clients/remote-control-prototype.test.ts -375 tests/clients/remote-workspace-activation.test.ts -143 tests/clients/remote-workspace-agent-wire.test.ts -119 tests/clients/remote-workspace-app-server.integration.test.ts -128 tests/clients/remote-workspace-claude.integration.test.ts -863 tests/clients/remote-workspace-cli-runtimes.test.ts -232 tests/clients/remote-workspace-cli.test.ts -489 tests/clients/remote-workspace-codex-runtime.test.ts -238 tests/clients/remote-workspace-command-runner.test.ts -109 tests/clients/remote-workspace-device.test.ts -171 tests/clients/remote-workspace-hub.test.ts -102 tests/clients/remote-workspace-linux-confinement.test.ts -463 tests/clients/remote-workspace-management.test.ts -87 tests/clients/remote-workspace-platform.test.ts -175 tests/clients/remote-workspace-protocol.test.ts -63 tests/clients/remote-workspace-rpc-framing.test.ts -651 tests/clients/remote-workspace-secret-store.test.ts -14129 tests/clients/remote-workspace-server.test.ts -95 tests/clients/remote-workspace-session-binding.test.ts -130 tests/clients/remote-workspace-sessions.test.ts -126 tests/clients/remote-workspace-tool-bridge.test.ts -537 tests/clients/remote-workspace.test.ts -33492 tests/clients/sync-client-integrations-unattended.test.ts -6725 tests/clients/sync-client-integrations.test.ts -1036 tests/clients/t3code-client-lifecycle.test.ts -1465 tests/clients/t3code-client.test.ts -2839 tests/clients/workbuddy-selector-recovery.test.ts -6080 tests/codex-integration/active-registry-admission.test.ts -21912 tests/codex-integration/active-turn-disconnect.test.ts -492 tests/codex-integration/anthropic2-catalog.test.ts -210 tests/codex-integration/app-owned-memory.test.ts -123831 tests/codex-integration/bearer-admission-routed-provider.test.ts -932 tests/codex-integration/catalog-async-lifetime.test.ts -8214 tests/codex-integration/catalog-auto-refresh-client-fanout.test.ts -4392 tests/codex-integration/catalog-auto-refresh-scheduler.test.ts -128 tests/codex-integration/catalog-auto-review-override.test.ts -9827 tests/codex-integration/catalog-auto-review-row.test.ts -273 tests/codex-integration/catalog-context-window-ladder.test.ts -230 tests/codex-integration/catalog-cursor-search.test.ts -158 tests/codex-integration/catalog-custom-ordering.test.ts -444 tests/codex-integration/catalog-duplicate-slug-dedup.test.ts -537 tests/codex-integration/catalog-free-pricing-status.test.ts -34923 tests/codex-integration/catalog-full-picker-order.test.ts -237 tests/codex-integration/catalog-gated-native-suppression-reason.test.ts -269 tests/codex-integration/catalog-go-exact-efforts.test.ts -154 tests/codex-integration/catalog-hub-context-window.test.ts -278 tests/codex-integration/catalog-input-modality-enum.test.ts -334 tests/codex-integration/catalog-llamacpp-capabilities.test.ts -1518 tests/codex-integration/catalog-modelalias-unique-sync.test.ts -146 tests/codex-integration/catalog-native-max-context.test.ts -824 tests/codex-integration/catalog-oauth-observation.test.ts -190 tests/codex-integration/catalog-opencode-go-context-window.test.ts -246 tests/codex-integration/catalog-opencode-go-static.test.ts -94 tests/codex-integration/catalog-opengateway-hints.test.ts -3629 tests/codex-integration/catalog-remote-pull.test.ts -151 tests/codex-integration/catalog-retain-models.test.ts -261 tests/codex-integration/catalog-routed-comp-hash.test.ts -230 tests/codex-integration/catalog-seed-window-fill.test.ts -126 tests/codex-integration/catalog-slug-uniqueness-boundary.test.ts -495 tests/codex-integration/catalog-verbosity-default.test.ts -237 tests/codex-integration/catalog-vision-sidecar-disabled.test.ts -259 tests/codex-integration/catalog-vision-sidecar-modalities.test.ts -198 tests/codex-integration/catalog-zero-credit-picker.test.ts -14126 tests/codex-integration/client-injection-guard.test.ts -406 tests/codex-integration/code-mode-collab-surface.test.ts -585 tests/codex-integration/codex-account-clear-paused.test.ts -10173 tests/codex-integration/codex-account-delete-atomicity.test.ts -64 tests/codex-integration/codex-account-label.test.ts -92 tests/codex-integration/codex-account-namespaces.test.ts -19751 tests/codex-integration/codex-account-selection-atomicity.test.ts -792 tests/codex-integration/codex-account-selection-preferences.test.ts -1072 tests/codex-integration/codex-account-slot-identity.test.ts -776 tests/codex-integration/codex-account-store-quota-isolation.test.ts -1211 tests/codex-integration/codex-account-store-refresh-classification.test.ts -4453 tests/codex-integration/codex-account-store.test.ts -1475 tests/codex-integration/codex-account-threshold-api.test.ts -2012 tests/codex-integration/codex-account-threshold-auth.test.ts -1037 tests/codex-integration/codex-account-threshold-routing.test.ts -2324 tests/codex-integration/codex-account-unusable-reason.test.ts -651 tests/codex-integration/codex-admission-primitives.test.ts -340 tests/codex-integration/codex-admission.test.ts -88 tests/codex-integration/codex-affinity-debug.test.ts -3644 tests/codex-integration/codex-agent-thread-limit.test.ts -232 tests/codex-integration/codex-app-server-path-spaces.test.ts -4284 tests/codex-integration/codex-app-server-processes.test.ts -264 tests/codex-integration/codex-app-server-restart-service.test.ts -18364 tests/codex-integration/codex-auth-api.test.ts -356 tests/codex-integration/codex-auth-cancel-ownership.test.ts -3438 tests/codex-integration/codex-auth-collision.test.ts -3691 tests/codex-integration/codex-auth-context.test.ts -6432 tests/codex-integration/codex-auth-headless-accounts.test.ts -6360 tests/codex-integration/codex-auth-release.test.ts -949 tests/codex-integration/codex-catalog-admission.test.ts -119 tests/codex-integration/codex-catalog-exclusions.test.ts -351 tests/codex-integration/codex-catalog-golden.test.ts -5077 tests/codex-integration/codex-catalog-heal-integration.test.ts -403 tests/codex-integration/codex-catalog-heal-reanchor.test.ts -339 tests/codex-integration/codex-catalog-identity-neutral.test.ts -2298 tests/codex-integration/codex-catalog-intent.test.ts -285 tests/codex-integration/codex-catalog-ladders.test.ts -306 tests/codex-integration/codex-catalog-model-picker-order.test.ts -82 tests/codex-integration/codex-catalog-refresh-status.test.ts -3165 tests/codex-integration/codex-catalog-restore.test.ts -142 tests/codex-integration/codex-catalog-routed-removal.test.ts -627 tests/codex-integration/codex-catalog-self-heal.test.ts -58782 tests/codex-integration/codex-catalog-sync-hardening.test.ts -1855 tests/codex-integration/codex-catalog-write-audit.test.ts -341 tests/codex-integration/codex-catalog-write-serialization.test.ts -1587 tests/codex-integration/codex-catalog-writer.test.ts -6835 tests/codex-integration/codex-catalog.test.ts -795 tests/codex-integration/codex-clamp-notice.test.ts -121 tests/codex-integration/codex-cli-install-provenance.test.ts -111 tests/codex-integration/codex-cli-installation-identity.test.ts -175 tests/codex-integration/codex-cli-installation-targets.test.ts -1869 tests/codex-integration/codex-cli-update-admission.test.ts -316 tests/codex-integration/codex-cli-update-apply.test.ts -16689 tests/codex-integration/codex-cli-update-artifacts.test.ts -263 tests/codex-integration/codex-cli-update-integrity.test.ts -63 tests/codex-integration/codex-cli-update-launcher-policy.test.ts -147 tests/codex-integration/codex-cli-update-paths.test.ts -5255 tests/codex-integration/codex-cli-update-plan.test.ts -11844 tests/codex-integration/codex-cli-update-recovery.test.ts -188156 tests/codex-integration/codex-cli-update-windows-apply-install.test.ts -175021 tests/codex-integration/codex-cli-update-windows-apply-outcomes.test.ts -139941 tests/codex-integration/codex-cli-update-windows-apply-shared.test.ts -113488 tests/codex-integration/codex-cli-update-windows-apply.test.ts -188 tests/codex-integration/codex-cli-update-windows-layout.test.ts -163939 tests/codex-integration/codex-cli-update-windows-pending.test.ts -222630 tests/codex-integration/codex-cli-update-windows-recovery.test.ts -7684 tests/codex-integration/codex-cli-update-windows-review.test.ts -2402 tests/codex-integration/codex-cli-update-worker.test.ts -4350 tests/codex-integration/codex-cli-update-zero-effect.test.ts -10901 tests/codex-integration/codex-cli-windows-child.test.ts -365 tests/codex-integration/codex-cli-windows-installation-files.test.ts -16860 tests/codex-integration/codex-cli-windows-plan.test.ts -92794 tests/codex-integration/codex-composed-acceptance.test.ts -7884 tests/codex-integration/codex-config-drift-heal.test.ts -2953 tests/codex-integration/codex-config-generation.test.ts -10631 tests/codex-integration/codex-config-preservation.test.ts -16285 tests/codex-integration/codex-config-write-lock.test.ts -230 tests/codex-integration/codex-context-owner.test.ts -42731 tests/codex-integration/codex-convergence-account-selectors.test.ts -14618 tests/codex-integration/codex-convergence-contract.test.ts +42955 tests/cli/ocx-launcher-runtime.test.ts +48 tests/cli/ocx-launcher-source.test.ts +224 tests/cli/ocx-run.test.ts +12583 tests/cli/restore-completes-shared-teardown.test.ts +3201 tests/cli/route-explainability.test.ts +24592 tests/cli/sibling-home-client-sync.test.ts +109 tests/cli/star-deferral.test.ts +399 tests/cli/start-args.test.ts +206 tests/cli/start-ownership-publication.test.ts +681 tests/cli/status-install-method.test.ts +110 tests/cli/system-restart-client-package-tree.test.ts +105 tests/cli/system-restart-client.test.ts +25141 tests/cli/uninstall.test.ts +3647 tests/clients/agent-clients.test.ts +144 tests/clients/aside-profile-identity.test.ts +705 tests/clients/aside-profile-paths.test.ts +3902 tests/clients/aside-profile-sync-owner.test.ts +1890 tests/clients/aside-profiles-catalog-refresh.test.ts +12727 tests/clients/aside-profiles.test.ts +130 tests/clients/client-catalog-compatibility.test.ts +51260 tests/clients/client-connect.test.ts +269 tests/clients/client-export-effective-metadata.test.ts +683 tests/clients/client-export-live-wire.test.ts +128 tests/clients/client-export-modality-enum.test.ts +216 tests/clients/client-export-model-names.test.ts +281 tests/clients/client-export-reasoning-controls.test.ts +128 tests/clients/client-export-reasoning-metadata.test.ts +281 tests/clients/client-fingerprint.test.ts +428 tests/clients/client-home-unreachable.test.ts +97 tests/clients/client-hub-relay.test.ts +646 tests/clients/client-hub-state.test.ts +143 tests/clients/client-hub-usage.test.ts +12864 tests/clients/client-lifecycle-lock.test.ts +14313 tests/clients/client-link-connect.test.ts +5742 tests/clients/client-link-relay.test.ts +14617 tests/clients/client-link-runtime.test.ts +683 tests/clients/client-link-state.test.ts +220 tests/clients/client-link-status.test.ts +4520 tests/clients/client-link-teardown.test.ts +7782 tests/clients/client-link-tunnel.test.ts +6563 tests/clients/client-machine-listener.test.ts +176 tests/clients/client-path.test.ts +352 tests/clients/client-runtime-restart.test.ts +638 tests/clients/client-runtime.test.ts +158 tests/clients/cline-client.test.ts +4526 tests/clients/cline-writer.test.ts +2762 tests/clients/command-code-client-contract.test.ts +126 tests/clients/command-code-client.test.ts +2378 tests/clients/desktop-3p-guard.test.ts +9585 tests/clients/desktop-3p-removal.test.ts +18370 tests/clients/desktop-3p-write-files.test.ts +5624 tests/clients/desktop-3p.test.ts +111 tests/clients/desktop-app-restart-posix.test.ts +615 tests/clients/desktop-app-restart.test.ts +729 tests/clients/desktop-app-server-exec-boundary.test.ts +2537 tests/clients/desktop-app-server-shim-launcher.test.ts +96 tests/clients/desktop-app-server-shim.test.ts +10146 tests/clients/desktop-bundle-trust-async.test.ts +185 tests/clients/desktop-chatgpt-config.test.ts +111 tests/clients/desktop-cli-command-surface.test.ts +49 tests/clients/desktop-cli-contracts.test.ts +838 tests/clients/desktop-compatibility-authority.test.ts +2200 tests/clients/desktop-compatibility-build-probe.test.ts +62 tests/clients/desktop-compatibility-certificate-service.test.ts +674 tests/clients/desktop-compatibility-connection-store.test.ts +1869 tests/clients/desktop-compatibility-launch.test.ts +209 tests/clients/desktop-compatibility-native-identity.test.ts +219 tests/clients/desktop-compatibility-relay.test.ts +193 tests/clients/desktop-compatibility-routing.test.ts +221 tests/clients/desktop-compatibility-runtime.test.ts +1946 tests/clients/desktop-compatibility-trust.test.ts +97 tests/clients/desktop-exit-ownership.test.ts +61 tests/clients/desktop-host-visibility.test.ts +81 tests/clients/desktop-install-identity.test.ts +331 tests/clients/desktop-profile.test.ts +47 tests/clients/desktop-proxy-direct-transport.test.ts +36336 tests/clients/desktop-remote-store.test.ts +110 tests/clients/desktop-restart-handoff.test.ts +80 tests/clients/desktop-runtime-identity.test.ts +215 tests/clients/desktop-start-at-login-default.test.ts +49 tests/clients/desktop-startup-surface.test.ts +1568 tests/clients/desktop-supervised-restart.test.ts +90 tests/clients/desktop-tray-availability.test.ts +79 tests/clients/desktop-update-surface.test.ts +63 tests/clients/desktop-widget-entry.test.ts +3757 tests/clients/droid-client.test.ts +4618 tests/clients/droid-managed-reasoning-defaults.test.ts +1274 tests/clients/droid-normalized-reasoning-defaults.test.ts +1522 tests/clients/gentle-shell-client.test.ts +188 tests/clients/gentle-shell-path.test.ts +4381 tests/clients/hermes-catalog-refresh.test.ts +3999 tests/clients/hermes-profile-routes.test.ts +112 tests/clients/hermes-profiles.test.ts +6885 tests/clients/integrations-current-store.test.ts +8845 tests/clients/integrations-dsh-profile-patch.test.ts +5603 tests/clients/integrations-hermes-affinity.test.ts +2932 tests/clients/integrations-journal.test.ts +1172 tests/clients/integrations-merge.test.ts +3036 tests/clients/integrations-model-names.test.ts +80 tests/clients/integrations-serialize.test.ts +1095 tests/clients/integrations-state.test.ts +554 tests/clients/integrations-superseded-store.test.ts +968 tests/clients/integrations-writer-frozen-config.test.ts +1192 tests/clients/integrations-writer-guard.test.ts +17541 tests/clients/integrations-writer.test.ts +3349 tests/clients/kilo-client.test.ts +94 tests/clients/lazycodex-detection.test.ts +48 tests/clients/link-admission-wait.test.ts +1887 tests/clients/link-apply-record.test.ts +79 tests/clients/link-boundary.test.ts +47 tests/clients/link-codex-settings-digest.test.ts +469 tests/clients/link-compensation.test.ts +126 tests/clients/link-connection-generation.test.ts +1520 tests/clients/link-diagnostics.test.ts +64 tests/clients/link-fingerprint.test.ts +460 tests/clients/link-home-settings.test.ts +63 tests/clients/link-parity-reporter.test.ts +236 tests/clients/link-peer-compatibility.test.ts +967 tests/clients/link-ports.test.ts +634 tests/clients/link-readiness.test.ts +617 tests/clients/link-relay-bound-transport.test.ts +268 tests/clients/link-routes.test.ts +16555 tests/clients/link-ssh-argv-discovery.test.ts +1158 tests/clients/link-ssh-argv.test.ts +187 tests/clients/link-ssh-config.test.ts +490 tests/clients/link-ssh-runner.test.ts +239 tests/clients/link-status-projection.test.ts +225 tests/clients/link-store.test.ts +4465 tests/clients/link-supervisor.test.ts +555 tests/clients/link-tunnel-history.test.ts +78 tests/clients/link-tunnel-state.test.ts +1076 tests/clients/mutation-plan.test.ts +209 tests/clients/omo-client.test.ts +3036 tests/clients/omo-responses-loop.test.ts +602 tests/clients/omo-role-models.test.ts +174 tests/clients/omp-path-contract.test.ts +112 tests/clients/omp-yaml-source-inline-comments.test.ts +3742 tests/clients/opencode-kilo-refresh.test.ts +400 tests/clients/pi-path-contract.test.ts +159 tests/clients/prime-client.test.ts +3756 tests/clients/qoder-client.test.ts +1078 tests/clients/raycast-client.test.ts +80 tests/clients/raycast-detect.test.ts +7075 tests/clients/remote-catalog.test.ts +110 tests/clients/remote-control-prototype.test.ts +143 tests/clients/remote-workspace-activation.test.ts +63 tests/clients/remote-workspace-agent-wire.test.ts +142 tests/clients/remote-workspace-app-server.integration.test.ts +288 tests/clients/remote-workspace-claude.integration.test.ts +806 tests/clients/remote-workspace-cli-runtimes.test.ts +173 tests/clients/remote-workspace-cli.test.ts +661 tests/clients/remote-workspace-codex-runtime.test.ts +285 tests/clients/remote-workspace-command-runner.test.ts +95 tests/clients/remote-workspace-device.test.ts +94 tests/clients/remote-workspace-hub.test.ts +47 tests/clients/remote-workspace-linux-confinement.test.ts +377 tests/clients/remote-workspace-management.test.ts +128 tests/clients/remote-workspace-platform.test.ts +78 tests/clients/remote-workspace-protocol.test.ts +90 tests/clients/remote-workspace-rpc-framing.test.ts +635 tests/clients/remote-workspace-secret-store.test.ts +17798 tests/clients/remote-workspace-server.test.ts +83 tests/clients/remote-workspace-session-binding.test.ts +126 tests/clients/remote-workspace-sessions.test.ts +64 tests/clients/remote-workspace-tool-bridge.test.ts +365 tests/clients/remote-workspace.test.ts +31093 tests/clients/sync-client-integrations-unattended.test.ts +6915 tests/clients/sync-client-integrations.test.ts +1388 tests/clients/t3code-client-lifecycle.test.ts +1265 tests/clients/t3code-client.test.ts +2985 tests/clients/workbuddy-selector-recovery.test.ts +5399 tests/codex-integration/active-registry-admission.test.ts +25242 tests/codex-integration/active-turn-disconnect.test.ts +669 tests/codex-integration/anthropic2-catalog.test.ts +161 tests/codex-integration/app-owned-memory.test.ts +112200 tests/codex-integration/bearer-admission-routed-provider.test.ts +618 tests/codex-integration/catalog-async-lifetime.test.ts +3849 tests/codex-integration/catalog-auto-refresh-client-fanout.test.ts +4823 tests/codex-integration/catalog-auto-refresh-scheduler.test.ts +80 tests/codex-integration/catalog-auto-review-override.test.ts +7969 tests/codex-integration/catalog-auto-review-row.test.ts +246 tests/codex-integration/catalog-context-window-ladder.test.ts +208 tests/codex-integration/catalog-cursor-search.test.ts +206 tests/codex-integration/catalog-custom-ordering.test.ts +159 tests/codex-integration/catalog-duplicate-slug-dedup.test.ts +518 tests/codex-integration/catalog-free-pricing-status.test.ts +31637 tests/codex-integration/catalog-full-picker-order.test.ts +109 tests/codex-integration/catalog-gated-native-suppression-reason.test.ts +238 tests/codex-integration/catalog-go-exact-efforts.test.ts +94 tests/codex-integration/catalog-hub-context-window.test.ts +326 tests/codex-integration/catalog-input-modality-enum.test.ts +143 tests/codex-integration/catalog-llamacpp-capabilities.test.ts +1375 tests/codex-integration/catalog-modelalias-unique-sync.test.ts +595 tests/codex-integration/catalog-native-max-context.test.ts +1310 tests/codex-integration/catalog-oauth-observation.test.ts +62908 tests/codex-integration/catalog-omit-disabled-native.test.ts +223 tests/codex-integration/catalog-opencode-go-context-window.test.ts +176 tests/codex-integration/catalog-opencode-go-static.test.ts +128 tests/codex-integration/catalog-opengateway-hints.test.ts +2355 tests/codex-integration/catalog-remote-pull.test.ts +94 tests/codex-integration/catalog-retain-models.test.ts +397 tests/codex-integration/catalog-routed-comp-hash.test.ts +142 tests/codex-integration/catalog-seed-window-fill.test.ts +111 tests/codex-integration/catalog-slug-uniqueness-boundary.test.ts +236 tests/codex-integration/catalog-verbosity-default.test.ts +191 tests/codex-integration/catalog-vision-sidecar-disabled.test.ts +110 tests/codex-integration/catalog-vision-sidecar-modalities.test.ts +206 tests/codex-integration/catalog-zero-credit-picker.test.ts +9159 tests/codex-integration/client-injection-guard.test.ts +222 tests/codex-integration/code-mode-collab-surface.test.ts +618 tests/codex-integration/codex-account-clear-paused.test.ts +8884 tests/codex-integration/codex-account-delete-atomicity.test.ts +79 tests/codex-integration/codex-account-label.test.ts +82 tests/codex-integration/codex-account-namespaces.test.ts +22724 tests/codex-integration/codex-account-selection-atomicity.test.ts +1930 tests/codex-integration/codex-account-selection-preferences.test.ts +727 tests/codex-integration/codex-account-slot-identity.test.ts +537 tests/codex-integration/codex-account-store-quota-isolation.test.ts +1038 tests/codex-integration/codex-account-store-refresh-classification.test.ts +5293 tests/codex-integration/codex-account-store.test.ts +1416 tests/codex-integration/codex-account-threshold-api.test.ts +1386 tests/codex-integration/codex-account-threshold-auth.test.ts +1031 tests/codex-integration/codex-account-threshold-routing.test.ts +2253 tests/codex-integration/codex-account-unusable-reason.test.ts +902 tests/codex-integration/codex-admission-primitives.test.ts +380 tests/codex-integration/codex-admission.test.ts +145 tests/codex-integration/codex-affinity-debug.test.ts +3530 tests/codex-integration/codex-affinity-lease-gap.test.ts +1770 tests/codex-integration/codex-affinity-request-owned.test.ts +47058 tests/codex-integration/codex-affinity-restart-matrix.test.ts +68932 tests/codex-integration/codex-affinity-restart.test.ts +37766 tests/codex-integration/codex-affinity-store.test.ts +3349 tests/codex-integration/codex-agent-thread-limit.test.ts +95 tests/codex-integration/codex-app-server-path-spaces.test.ts +3171 tests/codex-integration/codex-app-server-processes.test.ts +234 tests/codex-integration/codex-app-server-restart-service.test.ts +20806 tests/codex-integration/codex-auth-api.test.ts +318 tests/codex-integration/codex-auth-cancel-ownership.test.ts +3410 tests/codex-integration/codex-auth-collision.test.ts +5208 tests/codex-integration/codex-auth-context.test.ts +5861 tests/codex-integration/codex-auth-headless-accounts.test.ts +7247 tests/codex-integration/codex-auth-release.test.ts +746 tests/codex-integration/codex-catalog-admission.test.ts +187 tests/codex-integration/codex-catalog-exclusions.test.ts +142 tests/codex-integration/codex-catalog-golden.test.ts +5725 tests/codex-integration/codex-catalog-heal-integration.test.ts +412 tests/codex-integration/codex-catalog-heal-reanchor.test.ts +207 tests/codex-integration/codex-catalog-identity-neutral.test.ts +2263 tests/codex-integration/codex-catalog-intent.test.ts +238 tests/codex-integration/codex-catalog-ladders.test.ts +142 tests/codex-integration/codex-catalog-model-picker-order.test.ts +233 tests/codex-integration/codex-catalog-refresh-status.test.ts +3724 tests/codex-integration/codex-catalog-restore.test.ts +111 tests/codex-integration/codex-catalog-routed-removal.test.ts +268 tests/codex-integration/codex-catalog-self-heal.test.ts +53548 tests/codex-integration/codex-catalog-sync-hardening.test.ts +2296 tests/codex-integration/codex-catalog-write-audit.test.ts +347 tests/codex-integration/codex-catalog-write-serialization.test.ts +2038 tests/codex-integration/codex-catalog-writer.test.ts +4555 tests/codex-integration/codex-catalog.test.ts +1000 tests/codex-integration/codex-clamp-notice.test.ts +111 tests/codex-integration/codex-cli-install-provenance.test.ts +96 tests/codex-integration/codex-cli-installation-identity.test.ts +112 tests/codex-integration/codex-cli-installation-targets.test.ts +2206 tests/codex-integration/codex-cli-update-admission.test.ts +222 tests/codex-integration/codex-cli-update-apply.test.ts +12036 tests/codex-integration/codex-cli-update-artifacts.test.ts +303 tests/codex-integration/codex-cli-update-integrity.test.ts +79 tests/codex-integration/codex-cli-update-launcher-policy.test.ts +9443 tests/codex-integration/codex-cli-update-parent-async.test.ts +93 tests/codex-integration/codex-cli-update-paths.test.ts +6430 tests/codex-integration/codex-cli-update-plan.test.ts +11470 tests/codex-integration/codex-cli-update-recovery.test.ts +170251 tests/codex-integration/codex-cli-update-windows-apply-install.test.ts +109915 tests/codex-integration/codex-cli-update-windows-apply-outcomes.test.ts +177494 tests/codex-integration/codex-cli-update-windows-apply-shared.test.ts +55402 tests/codex-integration/codex-cli-update-windows-apply.test.ts +190 tests/codex-integration/codex-cli-update-windows-layout.test.ts +133360 tests/codex-integration/codex-cli-update-windows-pending.test.ts +227421 tests/codex-integration/codex-cli-update-windows-recovery.test.ts +8625 tests/codex-integration/codex-cli-update-windows-review.test.ts +2424 tests/codex-integration/codex-cli-update-worker.test.ts +4820 tests/codex-integration/codex-cli-update-zero-effect.test.ts +10988 tests/codex-integration/codex-cli-windows-child.test.ts +206 tests/codex-integration/codex-cli-windows-installation-files.test.ts +15940 tests/codex-integration/codex-cli-windows-plan.test.ts +216776 tests/codex-integration/codex-composed-acceptance.test.ts +8033 tests/codex-integration/codex-config-drift-heal.test.ts +3255 tests/codex-integration/codex-config-generation.test.ts +10606 tests/codex-integration/codex-config-preservation.test.ts +17150 tests/codex-integration/codex-config-write-lock.test.ts +190 tests/codex-integration/codex-context-owner.test.ts +37676 tests/codex-integration/codex-convergence-account-selectors.test.ts +15675 tests/codex-integration/codex-convergence-contract.test.ts 7560 tests/codex-integration/codex-cooldown-recovery.test.ts 464 tests/codex-integration/codex-coordinator-doctor.test.ts -3053 tests/codex-integration/codex-credit-retry-after.test.ts -2709 tests/codex-integration/codex-credit-scoped-retry.test.ts -605 tests/codex-integration/codex-credits-after-limit-main.test.ts -1707 tests/codex-integration/codex-credits-after-limit.test.ts -1594 tests/codex-integration/codex-credits-probes.test.ts +2467 tests/codex-integration/codex-credit-retry-after.test.ts +2369 tests/codex-integration/codex-credit-scoped-retry.test.ts +697 tests/codex-integration/codex-credits-after-limit-main.test.ts +2421 tests/codex-integration/codex-credits-after-limit.test.ts +4013 tests/codex-integration/codex-credits-probes.test.ts 1061 tests/codex-integration/codex-credits-settings.test.ts -83 tests/codex-integration/codex-credits.test.ts -3394 tests/codex-integration/codex-desired-state.test.ts -17065 tests/codex-integration/codex-direct-credit-renewal.test.ts -7335 tests/codex-integration/codex-direct-renewal-revocation.test.ts -381 tests/codex-integration/codex-entitlement-identity-read-fence.test.ts -5785 tests/codex-integration/codex-envkey-admission-substitution.test.ts +198 tests/codex-integration/codex-credits.test.ts +3151 tests/codex-integration/codex-desired-state.test.ts +17312 tests/codex-integration/codex-direct-credit-renewal.test.ts +6591 tests/codex-integration/codex-direct-renewal-revocation.test.ts +412 tests/codex-integration/codex-entitlement-identity-read-fence.test.ts +4829 tests/codex-integration/codex-envkey-admission-substitution.test.ts 133 tests/codex-integration/codex-exec-invocation.test.ts 3103 tests/codex-integration/codex-failure-window.test.ts -287 tests/codex-integration/codex-features-cache.test.ts -64 tests/codex-integration/codex-features-residual.test.ts -316 tests/codex-integration/codex-filesystem-evidence.test.ts -314 tests/codex-integration/codex-forward-access-programs-writer.test.ts -1000 tests/codex-integration/codex-gather-authority.test.ts -8659 tests/codex-integration/codex-history-job.test.ts -301 tests/codex-integration/codex-history-lock.test.ts -372 tests/codex-integration/codex-history-pending-wal.test.ts -12280 tests/codex-integration/codex-history-provider.test.ts -649 tests/codex-integration/codex-history-reachability.test.ts -63 tests/codex-integration/codex-history-worker-boundary.test.ts -2343 tests/codex-integration/codex-history-worker.test.ts -269 tests/codex-integration/codex-history-writer.test.ts -15983 tests/codex-integration/codex-home-owner-lifecycle.test.ts -2802 tests/codex-integration/codex-home-owner.test.ts -72 tests/codex-integration/codex-home-wsl-local-state.test.ts -278 tests/codex-integration/codex-home-wsl.test.ts +143 tests/codex-integration/codex-features-cache.test.ts +79 tests/codex-integration/codex-features-residual.test.ts +397 tests/codex-integration/codex-filesystem-evidence.test.ts +239 tests/codex-integration/codex-forward-access-programs-writer.test.ts +998 tests/codex-integration/codex-gather-authority.test.ts +8640 tests/codex-integration/codex-history-job.test.ts +331 tests/codex-integration/codex-history-lock.test.ts +221 tests/codex-integration/codex-history-pending-wal.test.ts +25949 tests/codex-integration/codex-history-provider.test.ts +959 tests/codex-integration/codex-history-reachability.test.ts +257 tests/codex-integration/codex-history-worker-boundary.test.ts +2082 tests/codex-integration/codex-history-worker.test.ts +221 tests/codex-integration/codex-history-writer.test.ts +20951 tests/codex-integration/codex-home-owner-lifecycle.test.ts +3975 tests/codex-integration/codex-home-owner.test.ts +50 tests/codex-integration/codex-home-wsl-local-state.test.ts +333 tests/codex-integration/codex-home-wsl.test.ts 10204 tests/codex-integration/codex-idle-window.test.ts -307 tests/codex-integration/codex-inject-history-wording.test.ts -209151 tests/codex-integration/codex-inject-integration.test.ts -4589 tests/codex-integration/codex-inject-missing-config.test.ts -2128 tests/codex-integration/codex-inject-retained-table.test.ts -24191 tests/codex-integration/codex-inject-v1-reconcile.test.ts -21021 tests/codex-integration/codex-inject-write-lock.test.ts -144 tests/codex-integration/codex-inject.test.ts +161 tests/codex-integration/codex-inject-history-wording.test.ts +229555 tests/codex-integration/codex-inject-integration.test.ts +4978 tests/codex-integration/codex-inject-missing-config.test.ts +1881 tests/codex-integration/codex-inject-retained-table.test.ts +25097 tests/codex-integration/codex-inject-v1-reconcile.test.ts +23620 tests/codex-integration/codex-inject-write-lock.test.ts +194 tests/codex-integration/codex-inject.test.ts 209 tests/codex-integration/codex-injected-marker.test.ts -853 tests/codex-integration/codex-integration-record.test.ts -7131 tests/codex-integration/codex-journal-recovery.test.ts -36102 tests/codex-integration/codex-journal.test.ts -26465 tests/codex-integration/codex-launcher-admission.test.ts -62 tests/codex-integration/codex-launcher-darwin-acl.test.ts -134 tests/codex-integration/codex-launcher-darwin-identity.test.ts -7410 tests/codex-integration/codex-launcher-diagnostics.test.ts -22115 tests/codex-integration/codex-launcher-env.test.ts -4373 tests/codex-integration/codex-launcher-process.test.ts -20384 tests/codex-integration/codex-launcher-security.test.ts -368 tests/codex-integration/codex-launcher.test.ts -111 tests/codex-integration/codex-legacy-config-keys.test.ts -1407 tests/codex-integration/codex-lineage-placement.test.ts +1090 tests/codex-integration/codex-installation-acl.test.ts +807 tests/codex-integration/codex-installation-id.test.ts +12642 tests/codex-integration/codex-installation-invalid-account.test.ts +15302 tests/codex-integration/codex-installation-live-content.test.ts +2879 tests/codex-integration/codex-installation-live-http.test.ts +7478 tests/codex-integration/codex-installation-live-ws.test.ts +2186 tests/codex-integration/codex-installation-sidecars.test.ts +936 tests/codex-integration/codex-integration-record.test.ts +8125 tests/codex-integration/codex-journal-recovery.test.ts +30096 tests/codex-integration/codex-journal.test.ts +26434 tests/codex-integration/codex-launcher-admission.test.ts +65 tests/codex-integration/codex-launcher-darwin-acl.test.ts +113 tests/codex-integration/codex-launcher-darwin-identity.test.ts +5404 tests/codex-integration/codex-launcher-diagnostics.test.ts +19692 tests/codex-integration/codex-launcher-env.test.ts +4299 tests/codex-integration/codex-launcher-process.test.ts +19576 tests/codex-integration/codex-launcher-security.test.ts +127 tests/codex-integration/codex-launcher.test.ts +150 tests/codex-integration/codex-legacy-config-keys.test.ts +1471 tests/codex-integration/codex-lineage-placement.test.ts 2237 tests/codex-integration/codex-linked-account-pause.test.ts -958 tests/codex-integration/codex-log-guard-coderabbit.test.ts -86 tests/codex-integration/codex-log-guard-doctor-coderabbit.test.ts -93 tests/codex-integration/codex-log-guard-doctor-protection.test.ts +792 tests/codex-integration/codex-log-guard-coderabbit.test.ts +79 tests/codex-integration/codex-log-guard-doctor-coderabbit.test.ts +241 tests/codex-integration/codex-log-guard-doctor-protection.test.ts 80 tests/codex-integration/codex-log-guard-doctor.test.ts -1782 tests/codex-integration/codex-log-guard-inspect.test.ts -182 tests/codex-integration/codex-log-guard-lock.test.ts -2469 tests/codex-integration/codex-log-guard-maintenance-coderabbit.test.ts -14015 tests/codex-integration/codex-log-guard-maintenance.test.ts +1680 tests/codex-integration/codex-log-guard-inspect.test.ts +108 tests/codex-integration/codex-log-guard-lock.test.ts +3417 tests/codex-integration/codex-log-guard-maintenance-coderabbit.test.ts +18212 tests/codex-integration/codex-log-guard-maintenance.test.ts 138 tests/codex-integration/codex-log-guard-policy.test.ts -128 tests/codex-integration/codex-log-guard-processes.test.ts -2485 tests/codex-integration/codex-log-guard-protection.test.ts -428 tests/codex-integration/codex-log-guard-status-zero-write.test.ts -3692 tests/codex-integration/codex-main-account-refresh.test.ts -6471 tests/codex-integration/codex-main-grant-refusal.test.ts -7452 tests/codex-integration/codex-main-rotation.test.ts -397 tests/codex-integration/codex-main-token-invalidated.test.ts -168 tests/codex-integration/codex-management-convergence.test.ts -390 tests/codex-integration/codex-metadata-integrity.test.ts -13465 tests/codex-integration/codex-missing-home.test.ts -152 tests/codex-integration/codex-model-availability-error.test.ts -255 tests/codex-integration/codex-model-denial-evidence.test.ts -206 tests/codex-integration/codex-model-entitlement-admission.test.ts -237 tests/codex-integration/codex-model-entitlements-program-shape.test.ts -3940 tests/codex-integration/codex-model-entitlements.test.ts -1854 tests/codex-integration/codex-models-cache-invalidate.test.ts -4808 tests/codex-integration/codex-native-availability-nux.test.ts -6235 tests/codex-integration/codex-native-residue.test.ts -1348 tests/codex-integration/codex-pin-drain-projection.test.ts -3159 tests/codex-integration/codex-plan.test.ts -875 tests/codex-integration/codex-plugins-doctor.test.ts -919 tests/codex-integration/codex-pool-caller-fallback-policy.test.ts -1031 tests/codex-integration/codex-pool-credit-policy.test.ts -815 tests/codex-integration/codex-pool-plan-exclusion.test.ts -231 tests/codex-integration/codex-pool-refresh-backoff.test.ts -6812 tests/codex-integration/codex-pool-request-owned-main.test.ts -46329 tests/codex-integration/codex-pool-rotation.test.ts -3835 tests/codex-integration/codex-preserve-signed-in.test.ts -2909 tests/codex-integration/codex-priority-failback.test.ts -88 tests/codex-integration/codex-proc-scan-errors.test.ts -1032 tests/codex-integration/codex-prompt-adopt.test.ts -2662 tests/codex-integration/codex-prompt-base-variants.test.ts -419 tests/codex-integration/codex-prompt-journal.test.ts -134 tests/codex-integration/codex-prompt-layers-read.test.ts -3811 tests/codex-integration/codex-prompt-layers-write.test.ts -88 tests/codex-integration/codex-prompt-layers.test.ts -1960 tests/codex-integration/codex-prompt-lock-sharing.test.ts -1248 tests/codex-integration/codex-prompt-lock.test.ts -5197 tests/codex-integration/codex-prompt-route.test.ts -2600 tests/codex-integration/codex-prompt-scalar-scope.test.ts -1556 tests/codex-integration/codex-prompt-text-probe.test.ts -5569 tests/codex-integration/codex-prompt-writes.test.ts -21105 tests/codex-integration/codex-provider-routing.test.ts -3047 tests/codex-integration/codex-provider-table-retention.test.ts -1165 tests/codex-integration/codex-quota-auto-refresh-generation.test.ts -690 tests/codex-integration/codex-quota-auto-refresh-main-admission.test.ts -7242 tests/codex-integration/codex-quota-auto-refresh.test.ts -146 tests/codex-integration/codex-quota-capacity.test.ts -262 tests/codex-integration/codex-quota-history.test.ts -192 tests/codex-integration/codex-quota-parser-parity.test.ts -779 tests/codex-integration/codex-quota-persistence.test.ts -2733 tests/codex-integration/codex-quota-prime.test.ts -1885 tests/codex-integration/codex-quota-query-backoff.test.ts -475 tests/codex-integration/codex-quota-rejection.test.ts -792 tests/codex-integration/codex-refresh.test.ts -4699 tests/codex-integration/codex-reset-credit-auto-redeem.test.ts -18483 tests/codex-integration/codex-reset-credit-operation-ledger.test.ts -310 tests/codex-integration/codex-reset-credit-recovery.test.ts -237 tests/codex-integration/codex-restart-contract-parity.test.ts -1651 tests/codex-integration/codex-restart-route.test.ts -18563 tests/codex-integration/codex-restore-app-rewrite.test.ts -19300 tests/codex-integration/codex-retained-root-serialization.test.ts -572 tests/codex-integration/codex-routing-cache-affinity-detour.test.ts -25588 tests/codex-integration/codex-routing.test.ts -208 tests/codex-integration/codex-runtime-macos-desktop.test.ts -230 tests/codex-integration/codex-runtime-wsl-desktop.test.ts -1753 tests/codex-integration/codex-runtime.test.ts -1372 tests/codex-integration/codex-service-manager-probe-hardening.test.ts +65 tests/codex-integration/codex-log-guard-processes.test.ts +2122 tests/codex-integration/codex-log-guard-protection.test.ts +427 tests/codex-integration/codex-log-guard-status-zero-write.test.ts +4301 tests/codex-integration/codex-main-account-refresh.test.ts +7806 tests/codex-integration/codex-main-grant-refusal.test.ts +6340 tests/codex-integration/codex-main-rotation.test.ts +364 tests/codex-integration/codex-main-token-invalidated.test.ts +114 tests/codex-integration/codex-management-convergence.test.ts +461 tests/codex-integration/codex-metadata-integrity.test.ts +12862 tests/codex-integration/codex-missing-home.test.ts +415 tests/codex-integration/codex-model-availability-error.test.ts +463 tests/codex-integration/codex-model-denial-evidence.test.ts +374 tests/codex-integration/codex-model-entitlement-admission.test.ts +251 tests/codex-integration/codex-model-entitlements-program-shape.test.ts +3945 tests/codex-integration/codex-model-entitlements.test.ts +1919 tests/codex-integration/codex-models-cache-invalidate.test.ts +4502 tests/codex-integration/codex-native-availability-nux.test.ts +4390 tests/codex-integration/codex-native-residue.test.ts +1301 tests/codex-integration/codex-pin-drain-projection.test.ts +3300 tests/codex-integration/codex-plan.test.ts +905 tests/codex-integration/codex-plugins-doctor.test.ts +713 tests/codex-integration/codex-pool-caller-fallback-policy.test.ts +895 tests/codex-integration/codex-pool-credit-policy.test.ts +1109 tests/codex-integration/codex-pool-plan-exclusion.test.ts +48 tests/codex-integration/codex-pool-refresh-backoff.test.ts +5007 tests/codex-integration/codex-pool-request-owned-main.test.ts +46996 tests/codex-integration/codex-pool-rotation.test.ts +11235 tests/codex-integration/codex-preserve-signed-in.test.ts +15528 tests/codex-integration/codex-priority-failback.test.ts +124 tests/codex-integration/codex-proc-scan-errors.test.ts +1156 tests/codex-integration/codex-prompt-adopt.test.ts +2775 tests/codex-integration/codex-prompt-base-variants.test.ts +652 tests/codex-integration/codex-prompt-journal.test.ts +79 tests/codex-integration/codex-prompt-layers-read.test.ts +2548 tests/codex-integration/codex-prompt-layers-write.test.ts +65 tests/codex-integration/codex-prompt-layers.test.ts +1553 tests/codex-integration/codex-prompt-lock-sharing.test.ts +1371 tests/codex-integration/codex-prompt-lock.test.ts +5369 tests/codex-integration/codex-prompt-route.test.ts +2892 tests/codex-integration/codex-prompt-scalar-scope.test.ts +1457 tests/codex-integration/codex-prompt-text-probe.test.ts +9141 tests/codex-integration/codex-prompt-writes.test.ts +22501 tests/codex-integration/codex-provider-routing.test.ts +3529 tests/codex-integration/codex-provider-table-retention.test.ts +1188 tests/codex-integration/codex-quota-auto-refresh-generation.test.ts +573 tests/codex-integration/codex-quota-auto-refresh-main-admission.test.ts +7625 tests/codex-integration/codex-quota-auto-refresh.test.ts +64 tests/codex-integration/codex-quota-capacity.test.ts +140 tests/codex-integration/codex-quota-history.test.ts +206 tests/codex-integration/codex-quota-parser-parity.test.ts +586 tests/codex-integration/codex-quota-persistence.test.ts +1448 tests/codex-integration/codex-quota-prime.test.ts +2219 tests/codex-integration/codex-quota-query-backoff.test.ts +286 tests/codex-integration/codex-quota-rejection.test.ts +715 tests/codex-integration/codex-refresh.test.ts +2047 tests/codex-integration/codex-request-owned-affinity.test.ts +4713 tests/codex-integration/codex-reset-credit-auto-redeem.test.ts +11960 tests/codex-integration/codex-reset-credit-operation-ledger.test.ts +300 tests/codex-integration/codex-reset-credit-recovery.test.ts +370 tests/codex-integration/codex-restart-contract-parity.test.ts +1507 tests/codex-integration/codex-restart-route.test.ts +18654 tests/codex-integration/codex-restore-app-rewrite.test.ts +13302 tests/codex-integration/codex-retained-root-serialization.test.ts +11939 tests/codex-integration/codex-round-robin-headroom.test.ts +555 tests/codex-integration/codex-routing-cache-affinity-detour.test.ts +333 tests/codex-integration/codex-routing-elapsed-short-reset.test.ts +21444 tests/codex-integration/codex-routing.test.ts +346 tests/codex-integration/codex-runtime-macos-desktop.test.ts +207 tests/codex-integration/codex-runtime-wsl-desktop.test.ts +1873 tests/codex-integration/codex-runtime.test.ts +1650 tests/codex-integration/codex-service-manager-probe-hardening.test.ts 816 tests/codex-integration/codex-service-manager-probe.test.ts -160 tests/codex-integration/codex-shim-autorestore.test.ts -121 tests/codex-integration/codex-shim-bypass-token.test.ts +95 tests/codex-integration/codex-shim-autorestore.test.ts +79 tests/codex-integration/codex-shim-bypass-token.test.ts 237 tests/codex-integration/codex-shim-destroyed-probe.test.ts -151 tests/codex-integration/codex-shim-ensure-failure.test.ts -119 tests/codex-integration/codex-shim-fnm.test.ts -162 tests/codex-integration/codex-shim-migration.test.ts -113 tests/codex-integration/codex-shim-overlay-candidates.test.ts -190 tests/codex-integration/codex-shim-overlay-readiness.test.ts -48 tests/codex-integration/codex-shim-overlay-transaction.test.ts +96 tests/codex-integration/codex-shim-ensure-failure.test.ts +94 tests/codex-integration/codex-shim-fnm.test.ts +113 tests/codex-integration/codex-shim-migration.test.ts +114 tests/codex-integration/codex-shim-overlay-candidates.test.ts +354 tests/codex-integration/codex-shim-overlay-readiness.test.ts +100 tests/codex-integration/codex-shim-overlay-transaction.test.ts 153 tests/codex-integration/codex-shim-overlay.test.ts -809 tests/codex-integration/codex-shim-path-readiness.test.ts -3143 tests/codex-integration/codex-shim-readiness.test.ts -257 tests/codex-integration/codex-shim-runtime-preflight.test.ts -92 tests/codex-integration/codex-shim-standalone.test.ts -461 tests/codex-integration/codex-shim-windows-revision.test.ts -17336 tests/codex-integration/codex-shim.test.ts -2820 tests/codex-integration/codex-sidecar-credit-policy.test.ts -244 tests/codex-integration/codex-signin-lockout.test.ts -1077 tests/codex-integration/codex-spark-visibility.test.ts -95 tests/codex-integration/codex-sqlite-home.test.ts -10579 tests/codex-integration/codex-stored-main-duplicate.test.ts -3954 tests/codex-integration/codex-sync-api.test.ts -3358 tests/codex-integration/codex-sync-new-model-policy.test.ts -161 tests/codex-integration/codex-sync-response.test.ts -69638 tests/codex-integration/codex-sync-user-edits.test.ts -330 tests/codex-integration/codex-systemd-env-probe.test.ts +1012 tests/codex-integration/codex-shim-path-readiness.test.ts +2985 tests/codex-integration/codex-shim-readiness.test.ts +172 tests/codex-integration/codex-shim-runtime-preflight.test.ts +234 tests/codex-integration/codex-shim-standalone.test.ts +786 tests/codex-integration/codex-shim-windows-revision.test.ts +17438 tests/codex-integration/codex-shim.test.ts +3702 tests/codex-integration/codex-sidecar-credit-policy.test.ts +202 tests/codex-integration/codex-signin-lockout.test.ts +1125 tests/codex-integration/codex-spark-visibility.test.ts +77 tests/codex-integration/codex-sqlite-home.test.ts +13265 tests/codex-integration/codex-stored-main-duplicate.test.ts +2619 tests/codex-integration/codex-sync-api.test.ts +3903 tests/codex-integration/codex-sync-new-model-policy.test.ts +64 tests/codex-integration/codex-sync-response.test.ts +69364 tests/codex-integration/codex-sync-user-edits.test.ts +396 tests/codex-integration/codex-systemd-env-probe.test.ts 263 tests/codex-integration/codex-tool-mode.test.ts 1157 tests/codex-integration/codex-transition-state-adoption.test.ts -142 tests/codex-integration/codex-transition-state-first-use-regression.test.ts -2721 tests/codex-integration/codex-transition-state-race.test.ts -1689 tests/codex-integration/codex-transition-state.test.ts -966 tests/codex-integration/codex-use-remaining-quota.test.ts -150 tests/codex-integration/codex-user-identity.test.ts -13982 tests/codex-integration/codex-v2-gate.test.ts -491 tests/codex-integration/codex-warmup.test.ts -11636 tests/codex-integration/codex-web-search-switch.test.ts -213 tests/codex-integration/codex-websocket-registry.test.ts +473 tests/codex-integration/codex-transition-state-first-use-regression.test.ts +2996 tests/codex-integration/codex-transition-state-race.test.ts +2581 tests/codex-integration/codex-transition-state.test.ts +1060 tests/codex-integration/codex-use-remaining-quota.test.ts +190 tests/codex-integration/codex-user-identity.test.ts +13699 tests/codex-integration/codex-v2-gate.test.ts +412 tests/codex-integration/codex-warmup.test.ts +11190 tests/codex-integration/codex-web-search-switch.test.ts +173 tests/codex-integration/codex-websocket-registry.test.ts 205 tests/codex-integration/codex-windows-current-sid.test.ts -6694 tests/codex-integration/codex-write-lock.test.ts -87 tests/codex-integration/combo-authoritative-reset.test.ts -172 tests/codex-integration/combo-codex-exhaustion-cooldown.test.ts -293 tests/codex-integration/combo-cooldown-reprobe.test.ts -3488 tests/codex-integration/combo-description-catalog.test.ts -87 tests/codex-integration/combo-last-resort.test.ts +6883 tests/codex-integration/codex-write-lock.test.ts +80 tests/codex-integration/combo-authoritative-reset.test.ts +270 tests/codex-integration/combo-codex-exhaustion-cooldown.test.ts +177 tests/codex-integration/combo-cooldown-reprobe.test.ts +4013 tests/codex-integration/combo-description-catalog.test.ts +82 tests/codex-integration/combo-last-resort.test.ts 78 tests/codex-integration/combo-permanent-failure-cooldown.test.ts -78 tests/codex-integration/combo-reset-window-model-scope.test.ts +156 tests/codex-integration/combo-reset-window-model-scope.test.ts 48 tests/codex-integration/combos-kiro-profile-hop.test.ts -609 tests/codex-integration/combos.test.ts +493 tests/codex-integration/combos.test.ts 1197 tests/codex-integration/compatibility-manifest.test.ts -134 tests/codex-integration/configured-native-models.test.ts -4607 tests/codex-integration/configured-ultrafast-picker.test.ts -79 tests/codex-integration/context-compat.test.ts +160 tests/codex-integration/configured-native-models.test.ts +3963 tests/codex-integration/configured-ultrafast-picker.test.ts +62 tests/codex-integration/context-compat.test.ts 162 tests/codex-integration/custom-model-catalog-migration.test.ts -494 tests/codex-integration/deferred-collab-surface.test.ts -1755 tests/codex-integration/discovered-native-models.test.ts -7448 tests/codex-integration/doctor.test.ts -972 tests/codex-integration/effort-policy.test.ts -2655 tests/codex-integration/exec-boundary-launch.test.ts -351 tests/codex-integration/exec-known-app-bundles.test.ts -332 tests/codex-integration/exec-trust-boundary.test.ts -154 tests/codex-integration/fast-row-listing.test.ts -129 tests/codex-integration/fast-row.test.ts -291 tests/codex-integration/gather-routed-models-single-flight.test.ts -326 tests/codex-integration/gpt6-native-rows.test.ts -166 tests/codex-integration/gpt61-sol-rows.test.ts -199 tests/codex-integration/gpt61-terra-rows.test.ts -88 tests/codex-integration/history-migration-guardian.test.ts +708 tests/codex-integration/deferred-collab-surface.test.ts +1331 tests/codex-integration/discovered-native-models.test.ts +5469 tests/codex-integration/doctor.test.ts +616 tests/codex-integration/effort-policy.test.ts +2576 tests/codex-integration/exec-boundary-launch.test.ts +271 tests/codex-integration/exec-cli-bundle-containment.test.ts +401 tests/codex-integration/exec-cli-renamed-app-bundle.test.ts +221 tests/codex-integration/exec-known-app-bundles.test.ts +143 tests/codex-integration/exec-launcher-boundary.test.ts +111 tests/codex-integration/exec-renamed-app-bundle.test.ts +301 tests/codex-integration/exec-trust-boundary.test.ts +162 tests/codex-integration/fast-row-listing.test.ts +130 tests/codex-integration/fast-row.test.ts +270 tests/codex-integration/gather-routed-models-single-flight.test.ts +96 tests/codex-integration/gpt6-native-rows.test.ts +109 tests/codex-integration/gpt61-sol-rows.test.ts +171 tests/codex-integration/gpt61-terra-rows.test.ts +47 tests/codex-integration/history-migration-guardian.test.ts 427 tests/codex-integration/history-ocx-compaction-recovery.test.ts -129 tests/codex-integration/history-paginated-openai-compat.test.ts -4505 tests/codex-integration/history-paginated-transition-destinations.test.ts -165 tests/codex-integration/injection-link-websocket.test.ts -3062 tests/codex-integration/injection-model-api.test.ts -342 tests/codex-integration/injection-model-suggest-routes.test.ts -95 tests/codex-integration/injection-routing-drift.test.ts +64 tests/codex-integration/history-paginated-openai-compat.test.ts +4359 tests/codex-integration/history-paginated-transition-destinations.test.ts +109 tests/codex-integration/injection-link-websocket.test.ts +3092 tests/codex-integration/injection-model-api.test.ts +221 tests/codex-integration/injection-model-suggest-routes.test.ts +92 tests/codex-integration/injection-routing-drift.test.ts 7101 tests/codex-integration/injection-routing-heal-apply.test.ts -684 tests/codex-integration/injection-routing-healer.test.ts -17154 tests/codex-integration/issue-452-empty-503.test.ts -44621 tests/codex-integration/issue-702-expired-replay-state.test.ts -1592 tests/codex-integration/issue-914-transport-attribution.test.ts -197 tests/codex-integration/low-quota-desktop-notifier.test.ts -5434 tests/codex-integration/low-quota-protection.test.ts -1360 tests/codex-integration/main-account-credit-renewal.test.ts +924 tests/codex-integration/injection-routing-healer.test.ts +22857 tests/codex-integration/issue-452-empty-503.test.ts +55233 tests/codex-integration/issue-702-expired-replay-state.test.ts +1185 tests/codex-integration/issue-914-transport-attribution.test.ts +206 tests/codex-integration/low-quota-desktop-notifier.test.ts +13393 tests/codex-integration/low-quota-protection.test.ts +1395 tests/codex-integration/main-account-credit-renewal.test.ts 65 tests/codex-integration/main-account-external-usage.test.ts -38169 tests/codex-integration/main-account-hard-lock-auth.test.ts -766 tests/codex-integration/main-account-hard-lock-default.test.ts -7175 tests/codex-integration/main-account-hard-lock-fallback-off.test.ts -5388 tests/codex-integration/main-account-hard-lock-fallback-routing.test.ts -167 tests/codex-integration/main-account-hard-lock-policy.test.ts -614 tests/codex-integration/main-account-hard-lock-profile-dispatch.test.ts -1540 tests/codex-integration/main-account-hard-lock-recovery.test.ts -145 tests/codex-integration/main-account-hard-lock-retirement.test.ts +24015 tests/codex-integration/main-account-hard-lock-auth.test.ts +522 tests/codex-integration/main-account-hard-lock-default.test.ts +11474 tests/codex-integration/main-account-hard-lock-fallback-off.test.ts +8893 tests/codex-integration/main-account-hard-lock-fallback-routing.test.ts +129 tests/codex-integration/main-account-hard-lock-policy.test.ts +1029 tests/codex-integration/main-account-hard-lock-profile-dispatch.test.ts +1444 tests/codex-integration/main-account-hard-lock-recovery.test.ts +190 tests/codex-integration/main-account-hard-lock-retirement.test.ts 86 tests/codex-integration/main-account-hard-lock-thresholds.test.ts -610 tests/codex-integration/main-account-hard-lock-usage-limit.test.ts -1002 tests/codex-integration/main-account-policy-binding-wait.test.ts -203 tests/codex-integration/main-device-reauth-api.test.ts -460 tests/codex-integration/main-device-reauth.test.ts -585 tests/codex-integration/main-quota-evidence-validation.test.ts -9947 tests/codex-integration/main-quota-provenance.test.ts -1618 tests/codex-integration/main-quota-window-observation.test.ts +710 tests/codex-integration/main-account-hard-lock-usage-limit.test.ts +1122 tests/codex-integration/main-account-policy-binding-wait.test.ts +126 tests/codex-integration/main-device-reauth-api.test.ts +594 tests/codex-integration/main-device-reauth.test.ts +349 tests/codex-integration/main-quota-evidence-validation.test.ts +8112 tests/codex-integration/main-quota-provenance.test.ts +1924 tests/codex-integration/main-quota-window-observation.test.ts 404 tests/codex-integration/messaging-local-cli.test.ts -65 tests/codex-integration/messaging-local-discovery.test.ts +96 tests/codex-integration/messaging-local-discovery.test.ts 190 tests/codex-integration/messaging-local-envelope.test.ts -476 tests/codex-integration/messaging-local-lifecycle.test.ts -80 tests/codex-integration/messaging-local-send.test.ts -235 tests/codex-integration/messaging-local-socket.test.ts -140 tests/codex-integration/messaging-remote-admission.test.ts -88 tests/codex-integration/messaging-remote-contract.test.ts -110 tests/codex-integration/messaging-remote-enrollment-gaps.test.ts -196 tests/codex-integration/messaging-remote-enrollment.test.ts -144 tests/codex-integration/messaging-remote-gaps.test.ts +602 tests/codex-integration/messaging-local-lifecycle.test.ts +79 tests/codex-integration/messaging-local-send.test.ts +138 tests/codex-integration/messaging-local-socket.test.ts +63 tests/codex-integration/messaging-mcp-queue.test.ts +95 tests/codex-integration/messaging-remote-admission.test.ts +110 tests/codex-integration/messaging-remote-contract.test.ts +127 tests/codex-integration/messaging-remote-enrollment-gaps.test.ts +64 tests/codex-integration/messaging-remote-enrollment.test.ts +111 tests/codex-integration/messaging-remote-forward-failure.test.ts +95 tests/codex-integration/messaging-remote-gaps.test.ts 94 tests/codex-integration/messaging-remote-interop.test.ts -136 tests/codex-integration/messaging-remote-lifecycle.test.ts -200 tests/codex-integration/messaging-remote-native.test.ts -13230 tests/codex-integration/messaging-remote-process.test.ts -95 tests/codex-integration/messaging-remote-replies.test.ts -64 tests/codex-integration/messaging-remote-scratch.test.ts -88 tests/codex-integration/messaging-remote-send.test.ts +78 tests/codex-integration/messaging-remote-lifecycle.test.ts +225 tests/codex-integration/messaging-remote-native.test.ts +99 tests/codex-integration/messaging-remote-port-reservation.test.ts +13186 tests/codex-integration/messaging-remote-process.test.ts +111 tests/codex-integration/messaging-remote-replies.test.ts +76 tests/codex-integration/messaging-remote-scratch.test.ts +237 tests/codex-integration/messaging-remote-send.test.ts 625 tests/codex-integration/messaging-remote-store.test.ts -79 tests/codex-integration/model-cache-generation-tombstone.test.ts -201 tests/codex-integration/model-cache.test.ts -507 tests/codex-integration/model-display-names-management-api.test.ts -165 tests/codex-integration/model-metadata-sync.test.ts -6975 tests/codex-integration/model-pinned-effort.test.ts -14655 tests/codex-integration/model-visibility-management-api.test.ts -2181 tests/codex-integration/multi-agent-compat.test.ts +45 tests/codex-integration/model-cache-generation-tombstone.test.ts +80 tests/codex-integration/model-cache.test.ts +445 tests/codex-integration/model-display-names-management-api.test.ts +156 tests/codex-integration/model-metadata-sync.test.ts +12270 tests/codex-integration/model-pinned-effort.test.ts +9331 tests/codex-integration/model-visibility-management-api.test.ts +2090 tests/codex-integration/multi-agent-compat.test.ts 4082 tests/codex-integration/multi-agent-keep-native-v1.test.ts -112 tests/codex-integration/multi-agent-origin.test.ts -275 tests/codex-integration/native-alias-maintainer-regressions.test.ts -396 tests/codex-integration/native-claude-code-toggle.test.ts -10140 tests/codex-integration/native-claude-desktop-toggle.test.ts -21686 tests/codex-integration/native-codex-toggle.test.ts -2050 tests/codex-integration/native-grok-toggle.test.ts -188 tests/codex-integration/native-main-auth-temp.test.ts -135 tests/codex-integration/native-main-claim-cache.test.ts -299 tests/codex-integration/native-main-claim.test.ts +156 tests/codex-integration/multi-agent-origin.test.ts +443 tests/codex-integration/native-alias-maintainer-regressions.test.ts +1061 tests/codex-integration/native-claude-code-toggle.test.ts +27050 tests/codex-integration/native-claude-desktop-toggle.test.ts +20753 tests/codex-integration/native-codex-toggle.test.ts +1213 tests/codex-integration/native-grok-toggle.test.ts +155 tests/codex-integration/native-main-auth-temp.test.ts +132 tests/codex-integration/native-main-claim-cache.test.ts +252 tests/codex-integration/native-main-claim.test.ts 32198 tests/codex-integration/native-main-owner-lifetime.test.ts -5829 tests/codex-integration/native-main-refresh-mode.test.ts -1142 tests/codex-integration/native-model-toggle.test.ts -182 tests/codex-integration/native-profile-api.test.ts -20160 tests/codex-integration/native-profile-crash-boundaries.test.ts +5785 tests/codex-integration/native-main-refresh-mode.test.ts +919 tests/codex-integration/native-model-toggle.test.ts +244 tests/codex-integration/native-profile-api.test.ts +19426 tests/codex-integration/native-profile-crash-boundaries.test.ts 10580 tests/codex-integration/native-profile-drain-server.test.ts -12426 tests/codex-integration/native-profile-manager.test.ts -435 tests/codex-integration/native-profile-processes.test.ts -153 tests/codex-integration/native-profile-recovery.test.ts -5248 tests/codex-integration/native-profile-route-security.test.ts -1232 tests/codex-integration/native-profile-stage-lifecycle.test.ts -1067 tests/codex-integration/native-profile-startup-release.test.ts -54571 tests/codex-integration/native-profile-startup.test.ts -456 tests/codex-integration/native-profile-store.test.ts -312 tests/codex-integration/native-source-priority.test.ts -5156 tests/codex-integration/native-ultrafast-picker.test.ts -2818 tests/codex-integration/orca-import.test.ts -264 tests/codex-integration/parallel-tool-calls-optin.test.ts -77 tests/codex-integration/project-config-warning-snapshot.test.ts -96 tests/codex-integration/project-config-warnings.test.ts -286 tests/codex-integration/reasoning-effort.test.ts +8712 tests/codex-integration/native-profile-manager.test.ts +430 tests/codex-integration/native-profile-processes.test.ts +82 tests/codex-integration/native-profile-recovery.test.ts +6236 tests/codex-integration/native-profile-route-security.test.ts +1523 tests/codex-integration/native-profile-stage-lifecycle.test.ts +1187 tests/codex-integration/native-profile-startup-release.test.ts +62246 tests/codex-integration/native-profile-startup.test.ts +793 tests/codex-integration/native-profile-store.test.ts +253 tests/codex-integration/native-source-priority.test.ts +4535 tests/codex-integration/native-ultrafast-picker.test.ts +14169 tests/codex-integration/orca-import.test.ts +270 tests/codex-integration/parallel-tool-calls-optin.test.ts +94 tests/codex-integration/project-config-warning-snapshot.test.ts +139 tests/codex-integration/project-config-warnings.test.ts +395 tests/codex-integration/reasoning-effort.test.ts 296 tests/codex-integration/reasoning-metadata.test.ts -642 tests/codex-integration/reserve-auth-context.test.ts -89 tests/codex-integration/reserve-availability.test.ts -11703 tests/codex-integration/reserve-catalog-lifecycle.test.ts -165 tests/codex-integration/reserve-catalog.test.ts -1711 tests/codex-integration/reserve-dispatch.test.ts -470 tests/codex-integration/reserve-helper-boundary.test.ts -277 tests/codex-integration/reserve-passive-revocation.test.ts -2314 tests/codex-integration/reserve-quota-scope.test.ts -206 tests/codex-integration/selected-models.test.ts +1234 tests/codex-integration/reserve-auth-context.test.ts +245 tests/codex-integration/reserve-availability.test.ts +13016 tests/codex-integration/reserve-catalog-lifecycle.test.ts +159 tests/codex-integration/reserve-catalog.test.ts +2659 tests/codex-integration/reserve-dispatch.test.ts +127 tests/codex-integration/reserve-helper-boundary.test.ts +266 tests/codex-integration/reserve-passive-revocation.test.ts +2286 tests/codex-integration/reserve-quota-scope.test.ts +96 tests/codex-integration/selected-models.test.ts 420 tests/codex-integration/slug-codec.test.ts -8751 tests/codex-integration/token-guardian.test.ts -3569 tests/codex-integration/ultrafast-live-catalog.test.ts -3710 tests/codex-integration/ultrafast-tier-honesty.test.ts -158 tests/codex-integration/upstream-reachability.test.ts -360 tests/codex-integration/vendor-context.test.ts -64 tests/codex-integration/warmup.test.ts -411 tests/codex-integration/websocket-capacity-activity.test.ts -728 tests/config/atomic-write-exclusive.test.ts -197 tests/config/atomic-write-nofollow-streamed.test.ts -192 tests/config/client-config-export-new-clients.test.ts -439 tests/config/client-config-export-output-limit.test.ts -384 tests/config/client-config-export.test.ts -193 tests/config/client-config-new-clients.test.ts +5806 tests/codex-integration/token-guardian.test.ts +4095 tests/codex-integration/ultrafast-live-catalog.test.ts +4889 tests/codex-integration/ultrafast-tier-honesty.test.ts +113 tests/codex-integration/upstream-reachability.test.ts +284 tests/codex-integration/vendor-context.test.ts +47 tests/codex-integration/warmup.test.ts +480 tests/codex-integration/websocket-capacity-activity.test.ts +798 tests/config/atomic-write-exclusive.test.ts +364 tests/config/atomic-write-nofollow-streamed.test.ts +239 tests/config/client-config-export-new-clients.test.ts +127 tests/config/client-config-export-output-limit.test.ts +221 tests/config/client-config-export.test.ts +140 tests/config/client-config-new-clients.test.ts 273 tests/config/compaction-recovery-settings.test.ts -22158 tests/config/config-account-auto-pause-revisions.test.ts -446 tests/config/config-account-thresholds.test.ts -5391 tests/config/config-anthropic-instance-pool.test.ts -181 tests/config/config-blocked-model-redirects.test.ts -333 tests/config/config-catalog-auto-refresh.test.ts -65 tests/config/config-commandcode-claude-pin.test.ts -1426 tests/config/config-concurrent-inbound-body.test.ts -127 tests/config/config-hosted-search-projection.test.ts -3868 tests/config/config-load-degrade.test.ts -5365 tests/config/config-mutation-lock.test.ts -183 tests/config/config-native-reasoning-retention.test.ts -472 tests/config/config-non-object-backup.test.ts -2109 tests/config/config-opencode-go-upgrade.test.ts -1147 tests/config/config-opencode-zen-upgrade.test.ts -601 tests/config/config-ownership-uninstall.test.ts -87 tests/config/config-rebase-provenance-writers.test.ts -662 tests/config/config-removed-opencode-free-preserve-failure.test.ts -109485 tests/config/config-removed-opencode-free.test.ts -104 tests/config/config-save-boundary.test.ts -468 tests/config/config-skills-catalog-refresh.test.ts -485 tests/config/config-spend-ceilings.test.ts -191 tests/config/config-spend-pool-collision.test.ts -21001 tests/config/config-user-edits.test.ts -72 tests/config/expand-user-path.test.ts -10417 tests/config/hub-disable-live-save.test.ts +23040 tests/config/config-account-auto-pause-revisions.test.ts +364 tests/config/config-account-thresholds.test.ts +5856 tests/config/config-anthropic-instance-pool.test.ts +173 tests/config/config-blocked-model-redirects.test.ts +206 tests/config/config-catalog-auto-refresh.test.ts +64 tests/config/config-commandcode-claude-pin.test.ts +1237 tests/config/config-concurrent-inbound-body.test.ts +78 tests/config/config-hosted-search-projection.test.ts +2403 tests/config/config-load-degrade.test.ts +6750 tests/config/config-mutation-lock.test.ts +175 tests/config/config-native-reasoning-retention.test.ts +283 tests/config/config-non-object-backup.test.ts +2664 tests/config/config-opencode-go-upgrade.test.ts +1280 tests/config/config-opencode-zen-upgrade.test.ts +941 tests/config/config-ownership-uninstall.test.ts +64 tests/config/config-rebase-provenance-writers.test.ts +331 tests/config/config-removed-opencode-free-preserve-failure.test.ts +113227 tests/config/config-removed-opencode-free.test.ts +141 tests/config/config-save-boundary.test.ts +427 tests/config/config-skills-catalog-refresh.test.ts +589 tests/config/config-spend-ceilings.test.ts +190 tests/config/config-spend-pool-collision.test.ts +20109 tests/config/config-user-edits.test.ts +79 tests/config/expand-user-path.test.ts +8583 tests/config/hub-disable-live-save.test.ts +247 tests/config/lmstudio-system-policy.test.ts 6209 tests/config/local-credential-generation.test.ts -6379 tests/config/model-pinned-effort-config.test.ts -127 tests/config/owner-registry-acl.test.ts -394 tests/config/owner-registry-isolation.test.ts -275 tests/config/protocol-settings.test.ts -8870 tests/config/serving-runtimes.test.ts -4353 tests/config/settings-desktop-switch-apply.test.ts -1627 tests/config/settings-fast-rows.test.ts -2942 tests/config/settings-main-account-hard-lock.test.ts -1494 tests/config/settings-memory-models.test.ts -1381 tests/config/settings-oauth-open-browser.test.ts -1009 tests/config/settings-reasoning-retention.test.ts -218 tests/config/settings-startup-health-seam.test.ts -23183 tests/config/settings-stream-mode.test.ts -65 tests/config/types-barrel-identity.test.ts +6137 tests/config/model-pinned-effort-config.test.ts +111 tests/config/owner-registry-acl.test.ts +506 tests/config/owner-registry-isolation.test.ts +139 tests/config/protocol-settings.test.ts +8419 tests/config/serving-runtimes.test.ts +3502 tests/config/settings-desktop-switch-apply.test.ts +1169 tests/config/settings-fast-rows.test.ts +3264 tests/config/settings-main-account-hard-lock.test.ts +1754 tests/config/settings-memory-models.test.ts +1489 tests/config/settings-oauth-open-browser.test.ts +874 tests/config/settings-reasoning-retention.test.ts +270 tests/config/settings-startup-health-seam.test.ts +24079 tests/config/settings-stream-mode.test.ts +80 tests/config/types-barrel-identity.test.ts 62 tests/config/url-normalization.test.ts -71 tests/config/yaml-fragment-source.test.ts -245 tests/e2e-style/phase100-native-parity.test.ts -233 tests/gui/alibaba-intl-token-plan.test.ts -80 tests/gui/claude-manual-env.test.ts -62 tests/gui/codex-account-mode-state.test.ts -80 tests/gui/codex-auth-modal-status.test.ts -75 tests/gui/codex-set-prompt.test.ts -97 tests/gui/combo-workspace-data.test.ts -87 tests/gui/combo-workspace-jev-decision.test.ts -159 tests/gui/dashboard-sidecar-codex-write.test.ts -159 tests/gui/dashboard-uptime.test.ts -56 tests/gui/gui-api-error.test.ts -174 tests/gui/gui-codex-usage-score-parity.test.ts -72 tests/gui/gui-desktop-sidecar-script.test.ts -78 tests/gui/gui-desktop-sidecar-signing.test.ts -200 tests/gui/gui-management-session.test.ts -71 tests/gui/gui-pair-capability.test.ts -1189 tests/gui/gui-pair-client.test.ts -3287 tests/gui/gui-pair-delivery.test.ts -5954 tests/gui/gui-pair-http.test.ts -213 tests/gui/gui-static.test.ts -80 tests/gui/gui-tray-vibrancy-surface.test.ts -280 tests/gui/html-lang-boot-script.test.ts -12735 tests/gui/integrations-invariants.test.ts -110 tests/gui/logs-model-tier-confirmation.test.ts -115 tests/gui/main-device-reauth-ui.test.ts -73 tests/gui/models-feedback-callback.test.ts -90 tests/gui/models-free-filter.test.ts -64 tests/gui/models-page-groups.test.ts -50 tests/gui/models-workspace-tabs.test.ts -92 tests/gui/oauth-first-add-hint.test.ts -96 tests/gui/oauth-tos-warning.test.ts -530 tests/gui/platform-dialog-guard.test.ts -96 tests/gui/provider-payload.test.ts +155 tests/config/yaml-fragment-source.test.ts +238 tests/e2e-style/phase100-native-parity.test.ts +95 tests/gui/alibaba-intl-token-plan.test.ts +175 tests/gui/claude-manual-env.test.ts +63 tests/gui/codex-account-mode-state.test.ts +237 tests/gui/codex-auth-modal-status.test.ts +79 tests/gui/codex-set-prompt.test.ts +99 tests/gui/combo-workspace-data.test.ts +80 tests/gui/combo-workspace-jev-decision.test.ts +95 tests/gui/dashboard-sidecar-codex-write.test.ts +172 tests/gui/dashboard-uptime.test.ts +64 tests/gui/gui-api-error.test.ts +190 tests/gui/gui-codex-usage-score-parity.test.ts +46 tests/gui/gui-desktop-sidecar-script.test.ts +237 tests/gui/gui-desktop-sidecar-signing.test.ts +169 tests/gui/gui-management-session.test.ts +78 tests/gui/gui-pair-capability.test.ts +994 tests/gui/gui-pair-client.test.ts +3154 tests/gui/gui-pair-delivery.test.ts +3983 tests/gui/gui-pair-http.test.ts +218 tests/gui/gui-static.test.ts +79 tests/gui/gui-tray-vibrancy-surface.test.ts +222 tests/gui/html-lang-boot-script.test.ts +9556 tests/gui/integrations-invariants.test.ts +111 tests/gui/logs-model-tier-confirmation.test.ts +48 tests/gui/main-device-reauth-ui.test.ts +47 tests/gui/models-feedback-callback.test.ts +97 tests/gui/models-free-filter.test.ts +77 tests/gui/models-page-groups.test.ts +48 tests/gui/models-workspace-tabs.test.ts +64 tests/gui/oauth-first-add-hint.test.ts +110 tests/gui/oauth-tos-warning.test.ts +395 tests/gui/platform-dialog-guard.test.ts +326 tests/gui/provider-payload.test.ts 228 tests/gui/provider-subscription-cli.test.ts -104 tests/gui/provider-workspace-auth.test.ts -216 tests/gui/provider-workspace-data.test.ts -399 tests/gui/provider-workspace-rail.test.ts -171 tests/gui/provider-workspace-state.test.ts +81 tests/gui/provider-workspace-auth.test.ts +95 tests/gui/provider-workspace-data.test.ts +79 tests/gui/provider-workspace-rail.test.ts +243 tests/gui/provider-workspace-state.test.ts 112 tests/gui/quota-bars-rows.test.ts -244 tests/gui/qwen-cloud-endpoints.test.ts -97 tests/gui/rate-limit-reset-credits.test.ts -154 tests/gui/routing-intelligence-ui.test.ts -80 tests/gui/routing-profile-editor-data.test.ts -62 tests/gui/standalone-build-script.test.ts -206 tests/gui/startup-health-ui.test.ts -260 tests/gui/tencent-siliconflow-providers.test.ts -199 tests/gui/vision-sidecar-timeout-bounds.test.ts -410 tests/gui/volcengine-providers.test.ts -143 tests/images/artifacts-prune.test.ts -199 tests/images/artifacts-ssrf.test.ts -64 tests/images/download-cap-default.test.ts -239 tests/images/download-connect-deadline-default.test.ts -158 tests/images/gemini-inline.test.ts +50 tests/gui/qwen-cloud-endpoints.test.ts +109 tests/gui/rate-limit-reset-credits.test.ts +47 tests/gui/routing-intelligence-ui.test.ts +181 tests/gui/routing-profile-editor-data.test.ts +77 tests/gui/standalone-build-script.test.ts +301 tests/gui/startup-health-ui.test.ts +204 tests/gui/tencent-siliconflow-providers.test.ts +440 tests/gui/vision-sidecar-timeout-bounds.test.ts +398 tests/gui/volcengine-providers.test.ts +157 tests/images/artifacts-prune.test.ts +79 tests/images/artifacts-ssrf.test.ts +139 tests/images/download-cap-default.test.ts +79 tests/images/download-connect-deadline-default.test.ts +143 tests/images/gemini-inline.test.ts 215 tests/images/loop-reasoning-replay.test.ts -204 tests/images/loop-terminal-refusal.test.ts -3247 tests/images/loop.test.ts +189 tests/images/loop-terminal-refusal.test.ts +3512 tests/images/loop.test.ts 88 tests/images/pinned-https-get.test.ts -149 tests/images/plan.test.ts -73 tests/images/synthetic-tool.test.ts -235 tests/images/xai-client.test.ts -188 tests/images/z-fulfill.test.ts -649 tests/images/z-handler-activation.test.ts +208 tests/images/plan.test.ts +80 tests/images/synthetic-tool.test.ts +128 tests/images/xai-client.test.ts +307 tests/images/z-fulfill.test.ts +731 tests/images/z-handler-activation.test.ts 808 tests/lab/core-lab-boundary.test.ts -221 tests/lab/core-link-boundary.test.ts -15716 tests/lab/lab-activation.test.ts -1279 tests/lab/lab-automation-coderabbit-regressions.test.ts -1568 tests/lab/lab-automation-final-coderabbit-regressions.test.ts -791 tests/lab/lab-automation-ingwannu-regressions.test.ts -722 tests/lab/lab-automation-management-http.test.ts -148 tests/lab/lab-automation-persisted-cap-regression.test.ts -3288 tests/lab/lab-automation-review-regressions.test.ts +428 tests/lab/core-link-boundary.test.ts +15941 tests/lab/lab-activation.test.ts +777 tests/lab/lab-automation-coderabbit-regressions.test.ts +1850 tests/lab/lab-automation-final-coderabbit-regressions.test.ts +857 tests/lab/lab-automation-ingwannu-regressions.test.ts +710 tests/lab/lab-automation-management-http.test.ts +63 tests/lab/lab-automation-persisted-cap-regression.test.ts +4444 tests/lab/lab-automation-review-regressions.test.ts 2697 tests/lab/lab-automation.test.ts 1619 tests/lab/lab-community-evidence.test.ts -1206 tests/lab/lab-community-filename-contract.test.ts -418 tests/lab/lab-community-mutation-lock.test.ts -942 tests/lab/lab-community-publisher-continuity.test.ts -301 tests/lab/lab-conformance-harness.test.ts -207 tests/lab/lab-conformance-runner-failures.test.ts +738 tests/lab/lab-community-filename-contract.test.ts +124 tests/lab/lab-community-mutation-lock.test.ts +842 tests/lab/lab-community-publisher-continuity.test.ts +543 tests/lab/lab-conformance-harness.test.ts +371 tests/lab/lab-conformance-runner-failures.test.ts 2630 tests/lab/lab-evidence-ledger.test.ts 1511 tests/lab/lab-evidence-sanitization.test.ts -245 tests/lab/lab-fabric-outcome-validation.test.ts -191 tests/lab/lab-fabric-persistence-boundary.test.ts -404 tests/lab/lab-fabric-producer-deadline.test.ts -150774 tests/lab/lab-fabric-task.test.ts -192 tests/lab/lab-installation-salt-cache.test.ts -1016 tests/lab/lab-ledger-mutation-lock.test.ts -340 tests/lab/lab-live-pinned-timeouts.test.ts -798 tests/lab/lab-live-probe.test.ts -174 tests/lab/lab-live-receipt-integrity.test.ts -612 tests/lab/lab-live-review-regressions.test.ts -505 tests/lab/lab-live-sandbox.test.ts -320 tests/lab/lab-passive-production-evidence.test.ts -239 tests/lab/lab-passive-production-surfaces.test.ts -48 tests/lab/lab-paths-security.test.ts -317 tests/lab/lab-post-merge-hardening.test.ts -197 tests/lab/lab-post-merge-projection.test.ts -62 tests/lab/lab-private-file-consumer-recovery.test.ts -96 tests/lab/lab-private-file-durability.test.ts -587 tests/lab/lab-public-api-json.test.ts -182 tests/lab/lab-public-artifact-policy.test.ts +238 tests/lab/lab-fabric-outcome-validation.test.ts +63 tests/lab/lab-fabric-persistence-boundary.test.ts +623 tests/lab/lab-fabric-producer-deadline.test.ts +151650 tests/lab/lab-fabric-task.test.ts +79 tests/lab/lab-installation-salt-cache.test.ts +1410 tests/lab/lab-ledger-mutation-lock.test.ts +348 tests/lab/lab-live-pinned-timeouts.test.ts +457 tests/lab/lab-live-probe.test.ts +207 tests/lab/lab-live-receipt-integrity.test.ts +349 tests/lab/lab-live-review-regressions.test.ts +538 tests/lab/lab-live-sandbox.test.ts +238 tests/lab/lab-passive-production-evidence.test.ts +236 tests/lab/lab-passive-production-surfaces.test.ts +108 tests/lab/lab-paths-security.test.ts +204 tests/lab/lab-post-merge-hardening.test.ts +316 tests/lab/lab-post-merge-projection.test.ts +48 tests/lab/lab-private-file-consumer-recovery.test.ts +78 tests/lab/lab-private-file-durability.test.ts +332 tests/lab/lab-public-api-json.test.ts +97 tests/lab/lab-public-artifact-policy.test.ts 1466 tests/lab/lab-public-coderabbit-regressions.test.ts -176 tests/lab/lab-public-core-contract.test.ts -1147 tests/lab/lab-public-deep-review-regressions.test.ts -930 tests/lab/lab-public-evidence.test.ts -508 tests/lab/lab-public-export-transaction.test.ts -159 tests/lab/lab-public-file-safety.test.ts -1154 tests/lab/lab-public-final-review-regressions.test.ts -1703 tests/lab/lab-public-lifecycle-hardening.test.ts -87 tests/lab/lab-public-privacy-ipv6.test.ts -3918 tests/lab/lab-public-provenance-recovery.test.ts -1967 tests/lab/lab-public-review-fixes.test.ts -80 tests/lab/lab-public-route-registry.test.ts +145 tests/lab/lab-public-core-contract.test.ts +1681 tests/lab/lab-public-deep-review-regressions.test.ts +1322 tests/lab/lab-public-evidence.test.ts +509 tests/lab/lab-public-export-transaction.test.ts +61 tests/lab/lab-public-file-safety.test.ts +1141 tests/lab/lab-public-final-review-regressions.test.ts +2156 tests/lab/lab-public-lifecycle-hardening.test.ts +79 tests/lab/lab-public-privacy-ipv6.test.ts +4206 tests/lab/lab-public-provenance-recovery.test.ts +1979 tests/lab/lab-public-review-fixes.test.ts +178 tests/lab/lab-public-route-registry.test.ts 206 tests/lab/lab-public-security-regressions.test.ts -1243 tests/lab/lab-public-surfaces.test.ts -290 tests/lab/lab-public-wire-contract.test.ts -263 tests/lab/lab-read-filter-validation.test.ts -47356 tests/lab/lab-read-surfaces.test.ts -896 tests/lib/abort-idle-deadline.test.ts -79 tests/lib/acl-error-classification.test.ts -539 tests/lib/ambiguous-resend-composition.test.ts -86 tests/lib/ambiguous-resend-gate.test.ts -81 tests/lib/authorization-scheme.test.ts -96 tests/lib/bounded-file-read.test.ts -425 tests/lib/bun-runtime-preflight.test.ts -93 tests/lib/bun-stream-caps.test.ts -228 tests/lib/clearable-deadline.test.ts -333 tests/lib/credential-redirect-guard.test.ts -81 tests/lib/debug.test.ts -270 tests/lib/execution-budget-permits.test.ts -126 tests/lib/failure-attribution.test.ts -81 tests/lib/failure-stage-model.test.ts -72 tests/lib/fix-jsonc-cr-comments.test.ts -64 tests/lib/fix-jsonc-empty-comma.test.ts -87 tests/lib/fix-plain-data-own-keys.test.ts -46 tests/lib/fix-plain-data-shape.test.ts -86 tests/lib/fix-retry-release-timer.test.ts -136 tests/lib/local-chat-completion.test.ts -82 tests/lib/local-destinations.test.ts -81 tests/lib/local-upstream.test.ts -3263 tests/lib/opaque-proxy-tunnel-protocol.test.ts -603 tests/lib/opaque-proxy-tunnel.test.ts -1386 tests/lib/optional-desktop-upstream.test.ts -1060 tests/lib/optional-shutdown-hooks.test.ts -213 tests/lib/pinned-http-content-coding.test.ts -1457 tests/lib/pinned-http.test.ts +1347 tests/lab/lab-public-surfaces.test.ts +414 tests/lab/lab-public-wire-contract.test.ts +365 tests/lab/lab-read-filter-validation.test.ts +49678 tests/lab/lab-read-surfaces.test.ts +744 tests/lib/abort-idle-deadline.test.ts +48 tests/lib/acl-error-classification.test.ts +380 tests/lib/ambiguous-resend-composition.test.ts +110 tests/lib/ambiguous-resend-gate.test.ts +232 tests/lib/authorization-scheme.test.ts +80 tests/lib/bounded-file-read.test.ts +283 tests/lib/bun-runtime-preflight.test.ts +49 tests/lib/bun-stream-caps.test.ts +156 tests/lib/clearable-deadline.test.ts +268 tests/lib/credential-redirect-guard.test.ts +143 tests/lib/debug.test.ts +189 tests/lib/execution-budget-permits.test.ts +115 tests/lib/failure-attribution.test.ts +113 tests/lib/failure-stage-model.test.ts +145 tests/lib/file-identity-callers.test.ts +80 tests/lib/file-identity.test.ts +62 tests/lib/fix-jsonc-cr-comments.test.ts +79 tests/lib/fix-jsonc-empty-comma.test.ts +62 tests/lib/fix-plain-data-own-keys.test.ts +48 tests/lib/fix-plain-data-shape.test.ts +224 tests/lib/fix-retry-release-timer.test.ts +142 tests/lib/local-chat-completion.test.ts +95 tests/lib/local-destinations.test.ts +91 tests/lib/local-upstream.test.ts +3393 tests/lib/opaque-proxy-tunnel-protocol.test.ts +601 tests/lib/opaque-proxy-tunnel.test.ts +1006 tests/lib/optional-desktop-upstream.test.ts +582 tests/lib/optional-shutdown-hooks.test.ts +204 tests/lib/pinned-http-content-coding.test.ts +1484 tests/lib/pinned-http.test.ts 89 tests/lib/plugin-loader.test.ts -80 tests/lib/plugin-upstream-hooks.test.ts -78 tests/lib/privacy-mask-account.test.ts -175 tests/lib/process-control-graceful.test.ts -80 tests/lib/process-control.test.ts -88 tests/lib/provider-egress.test.ts -112 tests/lib/reasoning-replay-scope-source.test.ts -1020 tests/lib/redact.test.ts -64 tests/lib/remove-tree-helper.test.ts -150 tests/lib/self-launch-argv.test.ts -1500 tests/lib/socks5-fetch.test.ts -171 tests/lib/socks5-tls-lifecycle.test.ts -135 tests/lib/socks5-upload-lifecycle.test.ts -1641 tests/lib/spend-ceiling-enforcement.test.ts -179 tests/lib/spend-contract-c.test.ts -88 tests/lib/spend-corruption-compat.test.ts -147 tests/lib/spend-experimental-history.test.ts -2042 tests/lib/spend-ledger-file-journal.test.ts -6695 tests/lib/spend-ledger-owner.test.ts -2208 tests/lib/spend-pool-continuity.test.ts +96 tests/lib/plugin-upstream-hooks.test.ts +80 tests/lib/privacy-mask-account.test.ts +174 tests/lib/process-control-graceful.test.ts +47 tests/lib/process-control.test.ts +224 tests/lib/provider-egress.test.ts +91 tests/lib/reasoning-replay-scope-source.test.ts +365 tests/lib/redact.test.ts +111 tests/lib/remove-tree-helper.test.ts +173 tests/lib/self-launch-argv.test.ts +1230 tests/lib/socks5-fetch.test.ts +94 tests/lib/socks5-tls-lifecycle.test.ts +271 tests/lib/socks5-upload-lifecycle.test.ts +2722 tests/lib/spend-ceiling-enforcement.test.ts +95 tests/lib/spend-contract-c.test.ts +64 tests/lib/spend-corruption-compat.test.ts +44 tests/lib/spend-experimental-history.test.ts +3111 tests/lib/spend-ledger-file-journal.test.ts +6576 tests/lib/spend-ledger-owner.test.ts +4060 tests/lib/spend-pool-continuity.test.ts 81 tests/lib/spend-reservation-ledger.test.ts -1277 tests/lib/spend-seed-overflow.test.ts -164 tests/lib/spend-unbound-expiry.test.ts -88 tests/lib/spend-zero-config-compat.test.ts -89 tests/lib/stall-subprocess-exit.test.ts -88 tests/lib/stall-timeout.test.ts -79 tests/lib/standalone.test.ts -71 tests/lib/strict-semver.test.ts -150 tests/lib/synced-state-location.test.ts -79 tests/lib/system-restart-contract-security.test.ts +1505 tests/lib/spend-seed-overflow.test.ts +82 tests/lib/spend-unbound-expiry.test.ts +79 tests/lib/spend-zero-config-compat.test.ts +80 tests/lib/stall-subprocess-exit.test.ts +597 tests/lib/stall-timeout.test.ts +234 tests/lib/standalone.test.ts +79 tests/lib/strict-semver.test.ts +82 tests/lib/synced-state-location.test.ts +228 tests/lib/system-restart-contract-security.test.ts 109 tests/lib/token-estimate.test.ts -87 tests/lib/transient-budget-scope-source.test.ts -135 tests/lib/transport-null-body.test.ts -270 tests/lib/upstream-error-message-fallback.test.ts -81 tests/lib/upstream-retry-zero-output.test.ts -8110 tests/lib/upstream-retry.test.ts -284 tests/lib/worker-embed-coverage.test.ts +77 tests/lib/transient-budget-scope-source.test.ts +79 tests/lib/transport-null-body.test.ts +220 tests/lib/upstream-error-message-fallback.test.ts +95 tests/lib/upstream-retry-zero-output.test.ts +8254 tests/lib/upstream-retry.test.ts +237 tests/lib/worker-embed-coverage.test.ts 79 tests/lib/worker-embed.test.ts -214 tests/lib/workflow-budget.test.ts -6546 tests/oauth/adapter-event-oauth-failover.test.ts -14810 tests/oauth/anthropic2-discovery-ownership.test.ts -4175 tests/oauth/chatgpt-device-auth.test.ts -80 tests/oauth/chatgpt-oauth.test.ts -158 tests/oauth/chatgpt-token-boundaries.test.ts -209 tests/oauth/chatgpt-token-expiry.test.ts -10659 tests/oauth/dsh-login.test.ts -3817 tests/oauth/generic-oauth-combo-account-cooldown.test.ts +206 tests/lib/workflow-budget.test.ts +9662 tests/oauth/adapter-event-oauth-failover.test.ts +14681 tests/oauth/anthropic2-discovery-ownership.test.ts +4394 tests/oauth/chatgpt-device-auth.test.ts +96 tests/oauth/chatgpt-oauth.test.ts +143 tests/oauth/chatgpt-token-boundaries.test.ts +127 tests/oauth/chatgpt-token-expiry.test.ts +10446 tests/oauth/dsh-login.test.ts +3627 tests/oauth/generic-oauth-combo-account-cooldown.test.ts 19381 tests/oauth/generic-oauth-failover.test.ts -3193 tests/oauth/generic-oauth-refusal-composition.test.ts -7378 tests/oauth/generic-session-affinity.test.ts -3401 tests/oauth/key-login-live-update.test.ts -222 tests/oauth/key-login-preserves-model-costs.test.ts -97 tests/oauth/local-token-detect.test.ts -5518 tests/oauth/oauth-account-attribution.test.ts -14291 tests/oauth/oauth-account-auto-pause-revision.test.ts -4502 tests/oauth/oauth-account-auto-pause.test.ts -143 tests/oauth/oauth-account-id-collision.test.ts -7442 tests/oauth/oauth-account-plans.test.ts -3597 tests/oauth/oauth-account-quota-rank.test.ts -48703 tests/oauth/oauth-accounts-api.test.ts -15849 tests/oauth/oauth-anthropic-identity.test.ts -10946 tests/oauth/oauth-anthropic-instance-health.test.ts -3044 tests/oauth/oauth-anthropic-instance-multiprocess.test.ts -19591 tests/oauth/oauth-anthropic-instance-refresh.test.ts -23475 tests/oauth/oauth-anthropic-instance-registration.test.ts -79 tests/oauth/oauth-callback-binds.test.ts -185 tests/oauth/oauth-callback-server.test.ts -12059 tests/oauth/oauth-code-login.test.ts -79 tests/oauth/oauth-device-code-contract.test.ts -4349 tests/oauth/oauth-health.test.ts -8481 tests/oauth/oauth-kiro-refresh-attention.test.ts -169 tests/oauth/oauth-log.test.ts -2202 tests/oauth/oauth-login-cli-browser-launch.test.ts -4766 tests/oauth/oauth-login-cli-errors.test.ts -7714 tests/oauth/oauth-login-cli-live-update.test.ts -216 tests/oauth/oauth-login-open-browser.test.ts -224 tests/oauth/oauth-login-summary.test.ts -2215 tests/oauth/oauth-manual-code.test.ts -2875 tests/oauth/oauth-meta-muse-login-diagnostics.test.ts -252 tests/oauth/oauth-open-browser-choice.test.ts -128 tests/oauth/oauth-open-url-result.test.ts -3146 tests/oauth/oauth-provider-reconcile.test.ts -1894 tests/oauth/oauth-public-surface.test.ts -936 tests/oauth/oauth-reauth-bind.test.ts -1564 tests/oauth/oauth-reconcile-operator-maps.test.ts -7597 tests/oauth/oauth-refresh-generic-lock.test.ts +4141 tests/oauth/generic-oauth-refusal-composition.test.ts +8550 tests/oauth/generic-session-affinity.test.ts +9753 tests/oauth/key-login-live-update.test.ts +97 tests/oauth/key-login-preserves-model-costs.test.ts +95 tests/oauth/local-token-detect.test.ts +5052 tests/oauth/oauth-account-attribution.test.ts +11021 tests/oauth/oauth-account-auto-pause-revision.test.ts +7155 tests/oauth/oauth-account-auto-pause.test.ts +190 tests/oauth/oauth-account-id-collision.test.ts +8467 tests/oauth/oauth-account-plans.test.ts +3774 tests/oauth/oauth-account-quota-rank.test.ts +47676 tests/oauth/oauth-accounts-api.test.ts +13180 tests/oauth/oauth-anthropic-identity.test.ts +11707 tests/oauth/oauth-anthropic-instance-health.test.ts +18782 tests/oauth/oauth-anthropic-instance-multiprocess.test.ts +19764 tests/oauth/oauth-anthropic-instance-refresh.test.ts +19703 tests/oauth/oauth-anthropic-instance-registration.test.ts +220 tests/oauth/oauth-callback-binds.test.ts +111 tests/oauth/oauth-callback-server.test.ts +13298 tests/oauth/oauth-code-login.test.ts +63 tests/oauth/oauth-device-code-contract.test.ts +3074 tests/oauth/oauth-health.test.ts +11880 tests/oauth/oauth-kiro-refresh-attention.test.ts +247 tests/oauth/oauth-log.test.ts +1962 tests/oauth/oauth-login-cli-browser-launch.test.ts +6553 tests/oauth/oauth-login-cli-errors.test.ts +9935 tests/oauth/oauth-login-cli-live-update.test.ts +301 tests/oauth/oauth-login-open-browser.test.ts +205 tests/oauth/oauth-login-summary.test.ts +2850 tests/oauth/oauth-manual-code.test.ts +3081 tests/oauth/oauth-meta-muse-login-diagnostics.test.ts +205 tests/oauth/oauth-open-browser-choice.test.ts +130 tests/oauth/oauth-open-url-result.test.ts +4157 tests/oauth/oauth-provider-reconcile.test.ts +1879 tests/oauth/oauth-public-surface.test.ts +2216 tests/oauth/oauth-reauth-bind.test.ts +1614 tests/oauth/oauth-reconcile-operator-maps.test.ts +7388 tests/oauth/oauth-refresh-generic-lock.test.ts 3905 tests/oauth/oauth-refresh-lock-multiprocess.test.ts -6287 tests/oauth/oauth-refresh-stale-capacity.test.ts -29662 tests/oauth/oauth-refresh.test.ts +6376 tests/oauth/oauth-refresh-stale-capacity.test.ts +21734 tests/oauth/oauth-refresh.test.ts 743 tests/oauth/oauth-status-privacy.test.ts -2764 tests/oauth/oauth-store-multi.test.ts -627 tests/oauth/oauth-store-quota-isolation.test.ts -153 tests/oauth/oauth-upsert-paused-api-key.test.ts -1492 tests/oauth/oauth-upsert-preserves-api-key.test.ts -47 tests/oauth/pool-kernel-generic-sweep.test.ts -729 tests/oauth/state-store-sweeper.test.ts -95 tests/oauth/workbuddy-login.test.ts -4169 tests/providers/aistupidlevel-provider.test.ts -205 tests/providers/alibaba-region-backup.test.ts -609 tests/providers/alibaba-region-migration.test.ts -64 tests/providers/alibaba-region-startup.test.ts -728 tests/providers/alibaba-token-plan-responses-optin.test.ts -1285 tests/providers/alibaba-token-plan-wire-defaults.test.ts -1714 tests/providers/api-key-auto-pause-distribution.test.ts -1049 tests/providers/api-key-catalog-authority.test.ts -63 tests/providers/api-key-selection-capture.test.ts -1107 tests/providers/api-key-selection-cooldown.test.ts -624 tests/providers/aside-client.test.ts -130 tests/providers/auto-compact-budget.test.ts -372 tests/providers/azure-adapter.test.ts +1998 tests/oauth/oauth-store-multi.test.ts +557 tests/oauth/oauth-store-quota-isolation.test.ts +112 tests/oauth/oauth-upsert-paused-api-key.test.ts +1843 tests/oauth/oauth-upsert-preserves-api-key.test.ts +485 tests/oauth/pool-kernel-generic-sweep.test.ts +698 tests/oauth/state-store-sweeper.test.ts +80 tests/oauth/workbuddy-login.test.ts +4945 tests/providers/aistupidlevel-provider.test.ts +966 tests/providers/alibaba-region-backup.test.ts +603 tests/providers/alibaba-region-migration.test.ts +79 tests/providers/alibaba-region-startup.test.ts +1109 tests/providers/alibaba-token-plan-responses-optin.test.ts +1657 tests/providers/alibaba-token-plan-wire-defaults.test.ts +1744 tests/providers/api-key-auto-pause-distribution.test.ts +903 tests/providers/api-key-catalog-authority.test.ts +218 tests/providers/api-key-selection-capture.test.ts +1532 tests/providers/api-key-selection-cooldown.test.ts +253 tests/providers/aside-client.test.ts +48 tests/providers/auto-compact-budget.test.ts +871 tests/providers/azure-adapter.test.ts 84 tests/providers/azure-model-router-tool-schema.test.ts -637 tests/providers/azure-vendor-metadata.test.ts -207 tests/providers/baseten-provider.test.ts +840 tests/providers/azure-vendor-metadata.test.ts +189 tests/providers/baseten-provider.test.ts +1824 tests/providers/cc-switch-import.test.ts 190 tests/providers/chutes-provider.test.ts -910 tests/providers/claude-cli-adapter.test.ts -981 tests/providers/claude-cli-client-http.test.ts -147 tests/providers/claude-cli-efficiency.test.ts -229 tests/providers/claude-cli-tool-capture.test.ts -712 tests/providers/claude-cli-usage-admission.test.ts -253 tests/providers/cline-pass-deepseek-v4-tool-replay.test.ts -207 tests/providers/cline-pass-provider.test.ts +1416 tests/providers/claude-cli-adapter.test.ts +1435 tests/providers/claude-cli-client-http.test.ts +81 tests/providers/claude-cli-efficiency.test.ts +171 tests/providers/claude-cli-tool-capture.test.ts +744 tests/providers/claude-cli-usage-admission.test.ts +347 tests/providers/cline-pass-deepseek-v4-tool-replay.test.ts +174 tests/providers/cline-pass-provider.test.ts 175 tests/providers/cline-pass-reasoning-efforts.test.ts 80 tests/providers/cline-provider.test.ts -3278 tests/providers/codebuddy-adapter.test.ts -276 tests/providers/codebuddy-live-acceptance.test.ts +348 tests/providers/codebuddy-adapter.test.ts +96 tests/providers/codebuddy-live-acceptance.test.ts 244 tests/providers/codebuddy-live-models.test.ts -4926 tests/providers/codebuddy-mcp-server.test.ts -172 tests/providers/codebuddy-protocol.test.ts -490 tests/providers/codebuddy-tool-bridge-turn.test.ts -95 tests/providers/codebuddy-tool-bridge.test.ts -79 tests/providers/coding-agent-json-lines-scaling.test.ts -730 tests/providers/command-code-credit-failover.test.ts +3889 tests/providers/codebuddy-mcp-server.test.ts +67 tests/providers/codebuddy-protocol.test.ts +550 tests/providers/codebuddy-tool-bridge-turn.test.ts +90 tests/providers/codebuddy-tool-bridge.test.ts +111 tests/providers/coding-agent-json-lines-scaling.test.ts +583 tests/providers/command-code-credit-failover.test.ts 2369 tests/providers/command-code-credit-rotation.test.ts -627 tests/providers/command-code-efforts.test.ts -88 tests/providers/command-code-error-finish.test.ts -286 tests/providers/command-code-fakeip-discovery.test.ts -5326 tests/providers/command-code-plan-denial.test.ts -3229 tests/providers/command-code-project-context.test.ts -1627 tests/providers/command-code-provider.test.ts -547 tests/providers/command-code-quota.test.ts -522 tests/providers/command-code-tool-text-prose-split.test.ts -1280 tests/providers/command-code-tool-text.test.ts -72 tests/providers/command-code-workspace-cache.test.ts -376 tests/providers/commandcode-provider.test.ts +934 tests/providers/command-code-efforts.test.ts +240 tests/providers/command-code-error-finish.test.ts +223 tests/providers/command-code-fakeip-discovery.test.ts +4316 tests/providers/command-code-plan-denial.test.ts +2574 tests/providers/command-code-project-context.test.ts +1347 tests/providers/command-code-provider.test.ts +508 tests/providers/command-code-quota.test.ts +238 tests/providers/command-code-tool-text-prose-split.test.ts +1519 tests/providers/command-code-tool-text.test.ts +93 tests/providers/command-code-workspace-cache.test.ts +286 tests/providers/commandcode-provider.test.ts 64 tests/providers/context-cap-unknown-window.test.ts -267 tests/providers/context-window-seed-repair.test.ts -339 tests/providers/crusoe-provider.test.ts -413 tests/providers/cursor/cursor-adapter.test.ts -79 tests/providers/cursor/cursor-arg-normalize.test.ts -178 tests/providers/cursor/cursor-blob-claude-client-tools.test.ts -103 tests/providers/cursor/cursor-blob-integrity.test.ts -496 tests/providers/cursor/cursor-blob.test.ts -324 tests/providers/cursor/cursor-call-id.test.ts -159 tests/providers/cursor/cursor-cancel-provenance.test.ts +177 tests/providers/context-window-seed-repair.test.ts +478 tests/providers/crusoe-provider.test.ts +382 tests/providers/cursor/cursor-adapter.test.ts +96 tests/providers/cursor/cursor-arg-normalize.test.ts +96 tests/providers/cursor/cursor-blob-claude-client-tools.test.ts +156 tests/providers/cursor/cursor-blob-integrity.test.ts +477 tests/providers/cursor/cursor-blob.test.ts +79 tests/providers/cursor/cursor-call-id.test.ts +386 tests/providers/cursor/cursor-cancel-provenance.test.ts 80 tests/providers/cursor/cursor-catalog.test.ts 72 tests/providers/cursor/cursor-claude-id.test.ts -254 tests/providers/cursor/cursor-continuation-invariants.test.ts -206 tests/providers/cursor/cursor-continuity-retention.test.ts -112 tests/providers/cursor/cursor-default-catalog-suppression.test.ts -206 tests/providers/cursor/cursor-desktop-exec.test.ts -154 tests/providers/cursor/cursor-discovery.test.ts -191 tests/providers/cursor/cursor-display-names.test.ts -7039 tests/providers/cursor/cursor-effort-rows.test.ts -131 tests/providers/cursor/cursor-effort-suffix.test.ts -88 tests/providers/cursor/cursor-effort-table.test.ts -111 tests/providers/cursor/cursor-envelope-echo-retry.test.ts -166 tests/providers/cursor/cursor-eof-terminal.test.ts -213 tests/providers/cursor/cursor-errors.test.ts +300 tests/providers/cursor/cursor-continuation-invariants.test.ts +190 tests/providers/cursor/cursor-continuity-retention.test.ts +94 tests/providers/cursor/cursor-default-catalog-suppression.test.ts +252 tests/providers/cursor/cursor-desktop-exec.test.ts +80 tests/providers/cursor/cursor-discovery.test.ts +81 tests/providers/cursor/cursor-display-names.test.ts +10674 tests/providers/cursor/cursor-effort-rows.test.ts +128 tests/providers/cursor/cursor-effort-suffix.test.ts +78 tests/providers/cursor/cursor-effort-table.test.ts +208 tests/providers/cursor/cursor-envelope-echo-retry.test.ts +254 tests/providers/cursor/cursor-eof-terminal.test.ts +98 tests/providers/cursor/cursor-errors.test.ts 64 tests/providers/cursor/cursor-exec-empty-result.test.ts -174 tests/providers/cursor/cursor-fast-listing.test.ts +173 tests/providers/cursor/cursor-fast-listing.test.ts 126 tests/providers/cursor/cursor-fast-tier.test.ts -429 tests/providers/cursor/cursor-foreground-shell.test.ts +252 tests/providers/cursor/cursor-foreground-shell.test.ts 158 tests/providers/cursor/cursor-framing.test.ts -199 tests/providers/cursor/cursor-freeform-args.test.ts -204 tests/providers/cursor/cursor-h2-pool-shutdown.test.ts -2954 tests/providers/cursor/cursor-hardening.test.ts -159 tests/providers/cursor/cursor-http1-transport.test.ts +276 tests/providers/cursor/cursor-freeform-args.test.ts +252 tests/providers/cursor/cursor-h2-pool-shutdown.test.ts +3114 tests/providers/cursor/cursor-hardening.test.ts +125 tests/providers/cursor/cursor-http1-transport.test.ts 2991 tests/providers/cursor/cursor-images.test.ts -10206 tests/providers/cursor/cursor-integration-status.test.ts -191 tests/providers/cursor/cursor-interaction-query.test.ts -162 tests/providers/cursor/cursor-kv-store.test.ts -152 tests/providers/cursor/cursor-live-smoke-gate.test.ts +9466 tests/providers/cursor/cursor-integration-status.test.ts +159 tests/providers/cursor/cursor-interaction-query.test.ts +94 tests/providers/cursor/cursor-kv-store.test.ts +48 tests/providers/cursor/cursor-live-smoke-gate.test.ts 309 tests/providers/cursor/cursor-live-transport.test.ts -82 tests/providers/cursor/cursor-local-installer.test.ts -4370 tests/providers/cursor/cursor-local-models-schema.test.ts -222 tests/providers/cursor/cursor-mcp-manager.test.ts -835 tests/providers/cursor/cursor-mcp-stdio.test.ts -63 tests/providers/cursor/cursor-message-mapper.test.ts -104 tests/providers/cursor/cursor-native-exec-common.test.ts -222 tests/providers/cursor/cursor-native-exec-policy.test.ts -305 tests/providers/cursor/cursor-native-exec-shell.test.ts -143 tests/providers/cursor/cursor-native-exec.test.ts -168 tests/providers/cursor/cursor-native-grep-globs.test.ts -191 tests/providers/cursor/cursor-oauth-shell.test.ts -729 tests/providers/cursor/cursor-oauth.test.ts +156 tests/providers/cursor/cursor-local-installer.test.ts +4070 tests/providers/cursor/cursor-local-models-schema.test.ts +172 tests/providers/cursor/cursor-mcp-manager.test.ts +585 tests/providers/cursor/cursor-mcp-stdio.test.ts +62 tests/providers/cursor/cursor-message-mapper.test.ts +78 tests/providers/cursor/cursor-native-exec-common.test.ts +127 tests/providers/cursor/cursor-native-exec-policy.test.ts +303 tests/providers/cursor/cursor-native-exec-shell.test.ts +205 tests/providers/cursor/cursor-native-exec.test.ts +159 tests/providers/cursor/cursor-native-grep-globs.test.ts +127 tests/providers/cursor/cursor-oauth-shell.test.ts +659 tests/providers/cursor/cursor-oauth.test.ts 78 tests/providers/cursor/cursor-pool.test.ts -136 tests/providers/cursor/cursor-protobuf-events.test.ts -167 tests/providers/cursor/cursor-repetition-breaker.test.ts +96 tests/providers/cursor/cursor-protobuf-events.test.ts +223 tests/providers/cursor/cursor-repetition-breaker.test.ts 270 tests/providers/cursor/cursor-request-builder.test.ts -143 tests/providers/cursor/cursor-request-compat.test.ts -192 tests/providers/cursor/cursor-roster-account-scope.test.ts -105 tests/providers/cursor/cursor-silent-redirect.test.ts -287 tests/providers/cursor/cursor-static-catalog.test.ts -3591 tests/providers/cursor/cursor-stream-health.test.ts -166 tests/providers/cursor/cursor-structured-edit.test.ts -114 tests/providers/cursor/cursor-tool-arg-decoding.test.ts -119 tests/providers/cursor/cursor-tool-choice.test.ts -215 tests/providers/cursor/cursor-tool-continuation.test.ts -97 tests/providers/cursor/cursor-tool-definitions.test.ts -4014 tests/providers/cursor/cursor-tool-finalize-race.test.ts -150 tests/providers/cursor/cursor-tool-result-image.test.ts -318 tests/providers/cursor/cursor-tool-result-invocation.test.ts +112 tests/providers/cursor/cursor-request-compat.test.ts +143 tests/providers/cursor/cursor-roster-account-scope.test.ts +110 tests/providers/cursor/cursor-silent-redirect.test.ts +221 tests/providers/cursor/cursor-static-catalog.test.ts +3613 tests/providers/cursor/cursor-stream-health.test.ts +205 tests/providers/cursor/cursor-structured-edit.test.ts +180 tests/providers/cursor/cursor-tool-arg-decoding.test.ts +82 tests/providers/cursor/cursor-tool-choice.test.ts +192 tests/providers/cursor/cursor-tool-continuation.test.ts +141 tests/providers/cursor/cursor-tool-definitions.test.ts +4127 tests/providers/cursor/cursor-tool-finalize-race.test.ts +158 tests/providers/cursor/cursor-tool-result-image.test.ts +328 tests/providers/cursor/cursor-tool-result-invocation.test.ts 120 tests/providers/cursor/cursor-tool-suspended-checkpoint.test.ts -206 tests/providers/cursor/cursor-tool-wording.test.ts +286 tests/providers/cursor/cursor-tool-wording.test.ts 167 tests/providers/cursor/cursor-toolresult-normalize.test.ts -1952 tests/providers/cursor/cursor-transport-retry.test.ts +1964 tests/providers/cursor/cursor-transport-retry.test.ts 110 tests/providers/cursor/cursor-ultra-mode.test.ts 97 tests/providers/cursor/cursor-umbrella-rows.test.ts 71 tests/providers/cursor/cursor-uncallable-quarantine.test.ts -139 tests/providers/cursor/cursor-vision-wire-harness.test.ts -690 tests/providers/cyber-policy-error-fidelity.test.ts -472 tests/providers/deepinfra-provider.test.ts -242 tests/providers/deepseek-artifact-tool-schema.test.ts -110 tests/providers/deepseek-bare-tool-call-replay.test.ts -3810 tests/providers/deepseek-image-files.test.ts -2444 tests/providers/deepseek-inbound-wire.test.ts -414 tests/providers/deepseek-quota-currency.test.ts -358 tests/providers/deepseek-reasoning-replay-gaps.test.ts -228 tests/providers/deepseek-reasoning-replay.test.ts -819 tests/providers/deepseek-responses-item-id-repair.test.ts -2530 tests/providers/devin-adapter-reset-wait.test.ts -957 tests/providers/devin-adapter.test.ts -798 tests/providers/devin-anthropic-signature-fallback.test.ts -662 tests/providers/devin-chat-wire-fixes.test.ts -80 tests/providers/devin-cli-authmode-migration.test.ts -81 tests/providers/devin-effort-ladder.test.ts -207 tests/providers/devin-family-resolution.test.ts -158 tests/providers/devin-hardening.test.ts -136 tests/providers/devin-image-passthrough.test.ts -262 tests/providers/devin-live-models.test.ts -2205 tests/providers/devin-login.test.ts -262 tests/providers/devin-output-budget.test.ts -778 tests/providers/devin-prompt-cache.test.ts -1149 tests/providers/devin-provider-merge-migration.test.ts -918 tests/providers/devin-quota.test.ts -330 tests/providers/devin-reasoning-continuation.test.ts -56 tests/providers/devin-stated-reset-hardening.test.ts -127 tests/providers/devin-stated-reset-retry.test.ts +111 tests/providers/cursor/cursor-vision-wire-harness.test.ts +521 tests/providers/cyber-policy-error-fidelity.test.ts +453 tests/providers/deepinfra-provider.test.ts +84 tests/providers/deepseek-artifact-tool-schema.test.ts +236 tests/providers/deepseek-bare-tool-call-replay.test.ts +7261 tests/providers/deepseek-image-files.test.ts +4905 tests/providers/deepseek-inbound-wire.test.ts +472 tests/providers/deepseek-quota-currency.test.ts +471 tests/providers/deepseek-reasoning-replay-gaps.test.ts +277 tests/providers/deepseek-reasoning-replay.test.ts +761 tests/providers/deepseek-responses-item-id-repair.test.ts +2286 tests/providers/devin-adapter-reset-wait.test.ts +1152 tests/providers/devin-adapter.test.ts +380 tests/providers/devin-anthropic-signature-fallback.test.ts +707 tests/providers/devin-chat-wire-fixes.test.ts +285 tests/providers/devin-cli-authmode-migration.test.ts +164 tests/providers/devin-effort-ladder.test.ts +301 tests/providers/devin-family-resolution.test.ts +255 tests/providers/devin-hardening.test.ts +326 tests/providers/devin-image-passthrough.test.ts +252 tests/providers/devin-live-models.test.ts +1933 tests/providers/devin-login.test.ts +333 tests/providers/devin-output-budget.test.ts +1060 tests/providers/devin-prompt-cache.test.ts +1503 tests/providers/devin-provider-merge-migration.test.ts +952 tests/providers/devin-quota.test.ts +125 tests/providers/devin-reasoning-continuation.test.ts +48 tests/providers/devin-stated-reset-hardening.test.ts +154 tests/providers/devin-stated-reset-retry.test.ts 114 tests/providers/devin-stream-deadline.test.ts -93 tests/providers/devin-trajectory.test.ts -367 tests/providers/digitalocean-scaleway-provider.test.ts -5319 tests/providers/dsh-account.test.ts -302 tests/providers/exa-web-search.test.ts -4941 tests/providers/explicit-key-pause-oauth-boundary.test.ts -167 tests/providers/fast-row-ingress.test.ts -175 tests/providers/featherless-provider.test.ts -214 tests/providers/flash-route-image-modalities.test.ts -6712 tests/providers/forward-admission-separation.test.ts -84 tests/providers/free-directory-runcrate.test.ts +96 tests/providers/devin-trajectory.test.ts +456 tests/providers/digitalocean-scaleway-provider.test.ts +3922 tests/providers/dsh-account.test.ts +227 tests/providers/exa-web-search.test.ts +3321 tests/providers/explicit-key-pause-oauth-boundary.test.ts +361 tests/providers/fast-row-ingress.test.ts +236 tests/providers/featherless-provider.test.ts +190 tests/providers/flash-route-image-modalities.test.ts +5540 tests/providers/forward-admission-separation.test.ts +79 tests/providers/free-directory-runcrate.test.ts 12019 tests/providers/github-copilot/github-copilot-account-origin.test.ts -40230 tests/providers/github-copilot/github-copilot-auto-runtime.test.ts -111 tests/providers/github-copilot/github-copilot-auto.test.ts -152 tests/providers/github-copilot/github-copilot-catalog-hints.test.ts -168 tests/providers/github-copilot/github-copilot-context-tier.test.ts +32779 tests/providers/github-copilot/github-copilot-auto-runtime.test.ts +96 tests/providers/github-copilot/github-copilot-auto.test.ts +142 tests/providers/github-copilot/github-copilot-catalog-hints.test.ts +159 tests/providers/github-copilot/github-copilot-context-tier.test.ts 16102 tests/providers/github-copilot/github-copilot-oauth.test.ts -109 tests/providers/github-copilot/github-copilot-sse-rewrite.test.ts -700 tests/providers/github-copilot/github-copilot-stream-contract.test.ts -2649 tests/providers/github-copilot/github-copilot-wire-defaults.test.ts -2014 tests/providers/gpt61-terra-provider-rows.test.ts -97 tests/providers/haiku-5-5-catalog.test.ts -344 tests/providers/hyperbolic-provider.test.ts -7157 tests/providers/initial-model-selection.test.ts -5576 tests/providers/initial-selection-write-fence.test.ts -247 tests/providers/jev-provider.test.ts -1417 tests/providers/kimi-oauth-identity.test.ts +80 tests/providers/github-copilot/github-copilot-sse-rewrite.test.ts +618 tests/providers/github-copilot/github-copilot-stream-contract.test.ts +3881 tests/providers/github-copilot/github-copilot-wire-defaults.test.ts +3075 tests/providers/gpt61-terra-provider-rows.test.ts +95 tests/providers/haiku-5-5-catalog.test.ts +221 tests/providers/hyperbolic-provider.test.ts +4841 tests/providers/initial-model-selection.test.ts +5966 tests/providers/initial-selection-write-fence.test.ts +141 tests/providers/jev-provider.test.ts +790 tests/providers/kimi-oauth-identity.test.ts 318 tests/providers/kimi-responses-adjacency.test.ts -132 tests/providers/kiro/kiro-account-load.test.ts +95 tests/providers/kiro/kiro-account-load.test.ts 2252 tests/providers/kiro/kiro-account-quota.test.ts -7583 tests/providers/kiro/kiro-account-state-disk.test.ts -1148 tests/providers/kiro/kiro-account-state-imports.test.ts -1860 tests/providers/kiro/kiro-adapter.test.ts -2809 tests/providers/kiro/kiro-auth-context-continuation.test.ts -1124 tests/providers/kiro/kiro-auto-selection.test.ts +7367 tests/providers/kiro/kiro-account-state-disk.test.ts +1140 tests/providers/kiro/kiro-account-state-imports.test.ts +1599 tests/providers/kiro/kiro-adapter.test.ts +3299 tests/providers/kiro/kiro-auth-context-continuation.test.ts +792 tests/providers/kiro/kiro-auto-selection.test.ts 680 tests/providers/kiro/kiro-builder-id-profile.test.ts -155 tests/providers/kiro/kiro-calibration.test.ts +96 tests/providers/kiro/kiro-calibration.test.ts 256 tests/providers/kiro/kiro-completion-with-real-tools.test.ts -1156 tests/providers/kiro/kiro-device-builder.test.ts -8111 tests/providers/kiro/kiro-device-social.test.ts -215 tests/providers/kiro/kiro-fallback-error-body.test.ts -3238 tests/providers/kiro/kiro-images.test.ts -13640 tests/providers/kiro/kiro-leased-responses.test.ts -71 tests/providers/kiro/kiro-metering-events.test.ts -136 tests/providers/kiro/kiro-metering-usage.test.ts -3299 tests/providers/kiro/kiro-model-catalog.test.ts +1014 tests/providers/kiro/kiro-device-builder.test.ts +4823 tests/providers/kiro/kiro-device-iam.test.ts +6337 tests/providers/kiro/kiro-device-social.test.ts +192 tests/providers/kiro/kiro-fallback-error-body.test.ts +3136 tests/providers/kiro/kiro-images.test.ts +12402 tests/providers/kiro/kiro-leased-responses.test.ts +63 tests/providers/kiro/kiro-metering-events.test.ts +141 tests/providers/kiro/kiro-metering-usage.test.ts +2898 tests/providers/kiro/kiro-model-catalog.test.ts 2495 tests/providers/kiro/kiro-model-preference.test.ts -2787 tests/providers/kiro/kiro-oauth.test.ts -9768 tests/providers/kiro/kiro-org-user-identity.test.ts -6196 tests/providers/kiro/kiro-pool-load-settings.test.ts -4515 tests/providers/kiro/kiro-pool-rank.test.ts -3908 tests/providers/kiro/kiro-quota-metrics.test.ts -152 tests/providers/kiro/kiro-reasoning-roundtrip.test.ts -5027 tests/providers/kiro/kiro-refusal-failover.test.ts +2614 tests/providers/kiro/kiro-oauth.test.ts +5445 tests/providers/kiro/kiro-org-user-identity.test.ts +5792 tests/providers/kiro/kiro-pool-load-settings.test.ts +4409 tests/providers/kiro/kiro-pool-rank.test.ts +2754 tests/providers/kiro/kiro-quota-metrics.test.ts +174 tests/providers/kiro/kiro-reasoning-roundtrip.test.ts +6302 tests/providers/kiro/kiro-refusal-failover.test.ts 111 tests/providers/kiro/kiro-refusal.test.ts -149 tests/providers/kiro/kiro-remote-image.test.ts -625 tests/providers/kiro/kiro-retry.test.ts -3949 tests/providers/kiro/kiro-review-regressions.test.ts -301 tests/providers/kiro/kiro-single-final.test.ts -667 tests/providers/kiro/kiro-stream.test.ts -712 tests/providers/kiro/kiro-transport-parity.test.ts -134 tests/providers/kiro/kiro-usage-quota.test.ts -619 tests/providers/kiro/kiro-usage-restart.test.ts -65 tests/providers/kiro/kiro-windows-cli-db-path.test.ts -80 tests/providers/kiro/kiro-windows-cli-executable-path.test.ts -120 tests/providers/kiro/kiro-wire-estimate.test.ts -428 tests/providers/meta-model-api-provider.test.ts -711 tests/providers/meta-muse-device.test.ts -5323 tests/providers/meta-muse-keychain.test.ts -284 tests/providers/meta-muse-login-order.test.ts +96 tests/providers/kiro/kiro-remote-image.test.ts +568 tests/providers/kiro/kiro-retry.test.ts +6327 tests/providers/kiro/kiro-review-regressions.test.ts +190 tests/providers/kiro/kiro-single-final.test.ts +425 tests/providers/kiro/kiro-stream.test.ts +762 tests/providers/kiro/kiro-transport-parity.test.ts +79 tests/providers/kiro/kiro-usage-quota.test.ts +540 tests/providers/kiro/kiro-usage-restart.test.ts +47 tests/providers/kiro/kiro-windows-cli-db-path.test.ts +64 tests/providers/kiro/kiro-windows-cli-executable-path.test.ts +98 tests/providers/kiro/kiro-wire-estimate.test.ts +175 tests/providers/meta-model-api-provider.test.ts +466 tests/providers/meta-muse-device.test.ts +5187 tests/providers/meta-muse-keychain.test.ts +350 tests/providers/meta-muse-login-order.test.ts 300 tests/providers/meta-muse-oauth.test.ts 284 tests/providers/meta-muse-wonder.test.ts -148 tests/providers/mimo-effort.test.ts -366 tests/providers/mimo-free-provider.test.ts -319 tests/providers/mimo-token-plan-capacity.test.ts -341 tests/providers/mimo-token-plan-provider.test.ts -291 tests/providers/mimo-v26-catalog.test.ts -626 tests/providers/minimax-clients.test.ts +254 tests/providers/mimo-effort.test.ts +517 tests/providers/mimo-free-provider.test.ts +390 tests/providers/mimo-token-plan-capacity.test.ts +285 tests/providers/mimo-token-plan-provider.test.ts +317 tests/providers/mimo-v26-catalog.test.ts +778 tests/providers/minimax-clients.test.ts 1772 tests/providers/minimax-combo-image-input.test.ts -337 tests/providers/minimax-quota.test.ts -215 tests/providers/minimax-reasoning-split.test.ts -2436 tests/providers/mistral-recovery.test.ts -277 tests/providers/model-presets.test.ts +239 tests/providers/minimax-quota.test.ts +254 tests/providers/minimax-reasoning-split.test.ts +3822 tests/providers/mistral-recovery.test.ts +94 tests/providers/model-presets.test.ts 1659 tests/providers/model-rename-migration.test.ts -160 tests/providers/model-roster-seed-repair.test.ts -319 tests/providers/modelflare-provider.test.ts -78 tests/providers/moonshot-developer-role.test.ts -78 tests/providers/moonshot-endpoints.test.ts -716 tests/providers/moonshot-tool-schema.test.ts -80 tests/providers/muse-key-quota.test.ts -1726 tests/providers/muse-passive-quota-cache.test.ts -855 tests/providers/muse-passive-quota-observation.test.ts +127 tests/providers/model-roster-seed-repair.test.ts +542 tests/providers/modelflare-provider.test.ts +79 tests/providers/moonshot-developer-role.test.ts +174 tests/providers/moonshot-endpoints.test.ts +380 tests/providers/moonshot-tool-schema.test.ts +94 tests/providers/muse-key-quota.test.ts +1351 tests/providers/muse-passive-quota-cache.test.ts +865 tests/providers/muse-passive-quota-observation.test.ts 182 tests/providers/muse-spark-web-search-compat.test.ts -74 tests/providers/muse-subscription-usage.test.ts -182 tests/providers/muse-tool-name-alias.test.ts -5764 tests/providers/new-model-policy-runtime.test.ts -108 tests/providers/new-model-policy.test.ts -96 tests/providers/nous-oauth-live.test.ts -12381 tests/providers/nous-oauth.test.ts -346 tests/providers/novita-provider.test.ts -366 tests/providers/nscale-vultr-provider.test.ts -307 tests/providers/nvidia-nim-hardening.test.ts -429 tests/providers/ollama/ollama-native-parser.test.ts -144 tests/providers/ollama/ollama-native-reasoning-wire.test.ts -87 tests/providers/ollama/ollama-native-structured-output.test.ts -451 tests/providers/ollama/ollama-native-tool-continuations.test.ts -492 tests/providers/ollama/ollama-native-v4.test.ts -256 tests/providers/ollama/ollama-native.test.ts -491 tests/providers/ollama/ollama-show-enrichment-v7.test.ts -197 tests/providers/ollama/ollama-show-enrichment.test.ts -314 tests/providers/ollama/ollama-show-ignore-abort.test.ts -777 tests/providers/opencode-cli.test.ts -282 tests/providers/opencode-go-deepseek.test.ts -1192 tests/providers/opencode-go-gemini-wire.test.ts -261 tests/providers/opencode-go-grok46-responses.test.ts -2617 tests/providers/opencode-go-luna-wire.test.ts -2327 tests/providers/opencode-go-model-protocols.test.ts -94 tests/providers/opencode-go-muse-context.test.ts -269 tests/providers/opencode-go-muse-vision.test.ts -223 tests/providers/opencode-go-quota.test.ts -10039 tests/providers/opencode-go-session-header.test.ts -799 tests/providers/opencode-management-transport.test.ts -153 tests/providers/opencode-muse-terminal-repair.test.ts +49 tests/providers/muse-subscription-usage.test.ts +413 tests/providers/muse-tool-name-alias.test.ts +5720 tests/providers/new-model-policy-runtime.test.ts +95 tests/providers/new-model-policy.test.ts +139 tests/providers/nous-oauth-live.test.ts +13033 tests/providers/nous-oauth.test.ts +237 tests/providers/novita-provider.test.ts +340 tests/providers/nscale-vultr-provider.test.ts +190 tests/providers/nvidia-nim-hardening.test.ts +396 tests/providers/ollama/ollama-native-parser.test.ts +112 tests/providers/ollama/ollama-native-reasoning-wire.test.ts +80 tests/providers/ollama/ollama-native-scaling.test.ts +112 tests/providers/ollama/ollama-native-structured-output.test.ts +761 tests/providers/ollama/ollama-native-tool-continuations.test.ts +238 tests/providers/ollama/ollama-native-v4.test.ts +263 tests/providers/ollama/ollama-native.test.ts +571 tests/providers/ollama/ollama-show-enrichment-v7.test.ts +222 tests/providers/ollama/ollama-show-enrichment.test.ts +331 tests/providers/ollama/ollama-show-ignore-abort.test.ts +996 tests/providers/opencode-cli.test.ts +127 tests/providers/opencode-go-deepseek.test.ts +2630 tests/providers/opencode-go-gemini-wire.test.ts +239 tests/providers/opencode-go-grok46-responses.test.ts +3493 tests/providers/opencode-go-luna-wire.test.ts +4069 tests/providers/opencode-go-model-protocols.test.ts +143 tests/providers/opencode-go-muse-context.test.ts +160 tests/providers/opencode-go-muse-vision.test.ts +433 tests/providers/opencode-go-quota.test.ts +24120 tests/providers/opencode-go-session-header.test.ts +823 tests/providers/opencode-management-transport.test.ts +78 tests/providers/opencode-muse-terminal-repair.test.ts 168 tests/providers/opencode-zen-deepseek-reasoning.test.ts -857 tests/providers/opencode-zen-gemini-wire.test.ts +903 tests/providers/opencode-zen-gemini-wire.test.ts 87 tests/providers/opencode-zen-rate-limit.test.ts -231 tests/providers/opengateway-key-validation.test.ts -206 tests/providers/opengateway-provider.test.ts -491 tests/providers/openrouter-provider-routing.test.ts -143 tests/providers/openrouter-quota-reset-cooldown-4024.test.ts -267 tests/providers/opper-provider.test.ts -643 tests/providers/orcarouter-provider.test.ts -1791 tests/providers/provider-account-quota-failure-reasons.test.ts -3658 tests/providers/provider-account-quota-persistence.test.ts -16724 tests/providers/provider-account-quota.test.ts -182 tests/providers/provider-anthropic-instance-quota.test.ts -223 tests/providers/provider-anthropic-instance.test.ts -140 tests/providers/provider-antigravity-effort-families.test.ts -508 tests/providers/provider-antigravity-family-catalog.test.ts -184 tests/providers/provider-antigravity-model-quota.test.ts -244 tests/providers/provider-antigravity-quota-retry.test.ts -5393 tests/providers/provider-antigravity-wire-snapshot.test.ts -10047 tests/providers/provider-api-keys.test.ts -153 tests/providers/provider-capacity.test.ts -799 tests/providers/provider-completion-test-authority.test.ts -2128 tests/providers/provider-completion-test-ingress.test.ts -563 tests/providers/provider-completion-test.test.ts -3949 tests/providers/provider-config-batch-management.test.ts -262 tests/providers/provider-config-validation.test.ts -6446 tests/providers/provider-connection-test.test.ts -1293 tests/providers/provider-cost-overlay-config.test.ts -412 tests/providers/provider-discovery-log-suppression.test.ts -133 tests/providers/provider-egress-outbound.test.ts -106 tests/providers/provider-id-rewrite.test.ts -1216 tests/providers/provider-input-modalities.test.ts -6748 tests/providers/provider-key-store.test.ts +233 tests/providers/opengateway-key-validation.test.ts +144 tests/providers/opengateway-provider.test.ts +330 tests/providers/openrouter-provider-routing.test.ts +146 tests/providers/openrouter-quota-reset-cooldown-4024.test.ts +159 tests/providers/opper-provider.test.ts +681 tests/providers/orcarouter-provider.test.ts +1774 tests/providers/provider-account-quota-failure-reasons.test.ts +4986 tests/providers/provider-account-quota-persistence.test.ts +14443 tests/providers/provider-account-quota.test.ts +264 tests/providers/provider-anthropic-instance-quota.test.ts +174 tests/providers/provider-anthropic-instance.test.ts +161 tests/providers/provider-anthropic-usage-windows.test.ts +180 tests/providers/provider-antigravity-effort-families.test.ts +365 tests/providers/provider-antigravity-family-catalog.test.ts +157 tests/providers/provider-antigravity-model-quota.test.ts +135 tests/providers/provider-antigravity-quota-retry.test.ts +3114 tests/providers/provider-antigravity-wire-snapshot.test.ts +9453 tests/providers/provider-api-keys.test.ts +83 tests/providers/provider-capacity.test.ts +2328 tests/providers/provider-completion-test-authority.test.ts +2282 tests/providers/provider-completion-test-ingress.test.ts +472 tests/providers/provider-completion-test.test.ts +3637 tests/providers/provider-config-batch-management.test.ts +64 tests/providers/provider-config-validation.test.ts +6101 tests/providers/provider-connection-test.test.ts +1514 tests/providers/provider-cost-overlay-config.test.ts +64 tests/providers/provider-discovery-log-suppression.test.ts +76 tests/providers/provider-egress-outbound.test.ts +95 tests/providers/provider-id-rewrite.test.ts +1300 tests/providers/provider-input-modalities.test.ts +6488 tests/providers/provider-key-store.test.ts 285 tests/providers/provider-live-models.test.ts -173 tests/providers/provider-model-aliases.test.ts -396 tests/providers/provider-model-discovery-contract.test.ts -248 tests/providers/provider-outbound-private-network.test.ts -1187 tests/providers/provider-outbound.test.ts -291 tests/providers/provider-quota-abliteration.test.ts -547 tests/providers/provider-quota-label-sanitize.test.ts -649 tests/providers/provider-quota-observed-marker.test.ts -673 tests/providers/provider-quota-ollama-cloud.test.ts -13321 tests/providers/provider-quota.test.ts -479 tests/providers/provider-registry-parity.test.ts -64 tests/providers/provider-runtime-fetch.test.ts -158 tests/providers/provider-static-model-discovery.test.ts -64 tests/providers/provider-tls-profile.test.ts -609 tests/providers/qoder-adapter.test.ts -1398 tests/providers/qoder-cn-image-validation.test.ts -111 tests/providers/qoder-image-input.test.ts +300 tests/providers/provider-model-aliases.test.ts +301 tests/providers/provider-model-discovery-contract.test.ts +47 tests/providers/provider-outbound-private-network.test.ts +1351 tests/providers/provider-outbound.test.ts +293 tests/providers/provider-quota-abliteration.test.ts +522 tests/providers/provider-quota-label-sanitize.test.ts +937 tests/providers/provider-quota-observed-marker.test.ts +793 tests/providers/provider-quota-ollama-cloud.test.ts +15946 tests/providers/provider-quota.test.ts +681 tests/providers/provider-registry-parity.test.ts +79 tests/providers/provider-runtime-fetch.test.ts +191 tests/providers/provider-static-model-discovery.test.ts +93 tests/providers/provider-tls-profile.test.ts +360 tests/providers/qoder-adapter.test.ts +1717 tests/providers/qoder-cn-image-validation.test.ts +126 tests/providers/qoder-image-input.test.ts 128 tests/providers/qoder-live-models.test.ts -498 tests/providers/qoder-mcp-server.test.ts -158 tests/providers/qoder-scaffold-guard.test.ts +571 tests/providers/qoder-mcp-server.test.ts +111 tests/providers/qoder-scaffold-guard.test.ts 79 tests/providers/qwen38-preserve-reasoning.test.ts -919 tests/providers/rate-limit-retry.test.ts -141 tests/providers/registry-transport-alias.test.ts -263 tests/providers/resolved-model-policy.test.ts -258 tests/providers/sambanova-nebius-provider.test.ts -160 tests/providers/sponsor-presets.test.ts -214 tests/providers/stepfun-provider.test.ts -791 tests/providers/tokenlab-protocols.test.ts -159 tests/providers/tokenlab-provider.test.ts -226 tests/providers/umans-provider.test.ts -7383 tests/providers/upstream-transient-retry.test.ts -151 tests/providers/vercel-gateway-provider-routing.test.ts -235 tests/providers/vision-classification-seed-repair.test.ts -110 tests/providers/volcengine-ark-assistant-content.test.ts +740 tests/providers/rate-limit-retry.test.ts +143 tests/providers/registry-transport-alias.test.ts +271 tests/providers/resolved-model-policy.test.ts +455 tests/providers/sambanova-nebius-provider.test.ts +175 tests/providers/sponsor-presets.test.ts +157 tests/providers/stepfun-provider.test.ts +1397 tests/providers/tokenlab-protocols.test.ts +158 tests/providers/tokenlab-provider.test.ts +158 tests/providers/umans-provider.test.ts +7390 tests/providers/upstream-transient-retry.test.ts +188 tests/providers/vercel-gateway-provider-routing.test.ts +189 tests/providers/vision-classification-seed-repair.test.ts +96 tests/providers/volcengine-ark-assistant-content.test.ts 2747 tests/providers/workbuddy-provider.test.ts -1007 tests/providers/workbuddy-quota.test.ts -80 tests/providers/xai/grok-47-build-fast-metadata.test.ts -134605 tests/providers/xai/grok-47-fast-model-wire.test.ts -366 tests/providers/xai/grok-47-fast-model.test.ts +586 tests/providers/workbuddy-quota.test.ts +79 tests/providers/xai/grok-47-build-fast-metadata.test.ts +136825 tests/providers/xai/grok-47-fast-model-wire.test.ts +160 tests/providers/xai/grok-47-fast-model.test.ts 286 tests/providers/xai/grok-attribution.test.ts 5443 tests/providers/xai/grok-config-inject.test.ts -215 tests/providers/xai/grok-config-write-lock.test.ts +220 tests/providers/xai/grok-config-write-lock.test.ts 21632 tests/providers/xai/grok-coupon-claim.test.ts 2170 tests/providers/xai/grok-coupon-reconcile.test.ts -611 tests/providers/xai/grok-effort-inject.test.ts -200 tests/providers/xai/grok-lifecycle.test.ts -15821 tests/providers/xai/grok-management-api.test.ts -9979 tests/providers/xai/grok-models-effort-list.test.ts -4764 tests/providers/xai/grok-orphan-adoption.test.ts -162 tests/providers/xai/grok-reset-coupon-cli.test.ts -888 tests/providers/xai/grok-reset-coupons.test.ts +539 tests/providers/xai/grok-effort-inject.test.ts +191 tests/providers/xai/grok-lifecycle.test.ts +10314 tests/providers/xai/grok-management-api.test.ts +10234 tests/providers/xai/grok-models-effort-list.test.ts +5602 tests/providers/xai/grok-orphan-adoption.test.ts +110 tests/providers/xai/grok-reset-coupon-cli.test.ts +873 tests/providers/xai/grok-reset-coupons.test.ts 371 tests/providers/xai/grok-selection.test.ts -648 tests/providers/xai/grok-session-identity.test.ts -365 tests/providers/xai/grok-status.test.ts -730 tests/providers/xai/grok-sync.test.ts -253 tests/providers/xai/grok-writer-boundary.test.ts -157 tests/providers/xai/xai-empty-catalog-tool-choice.test.ts -155 tests/providers/xai/xai-no-stop.test.ts -97 tests/providers/xai/xai-oauth-retry.test.ts -2855 tests/providers/xai/xai-refresh-lock.test.ts -158 tests/providers/xai/xai-responses-adjacency.test.ts -96 tests/providers/xai/xai-tool-schema.test.ts -224 tests/providers/xai/xai-transport.test.ts -132 tests/providers/xai/xai-web-search-compat.test.ts -167 tests/providers/xai/xai-web-search.test.ts -206 tests/providers/zai-reasoning-replay.test.ts -391 tests/providers/zcode-client.test.ts -335 tests/providers/zed-argument-consistency.test.ts +362 tests/providers/xai/grok-session-identity.test.ts +253 tests/providers/xai/grok-status.test.ts +634 tests/providers/xai/grok-sync.test.ts +257 tests/providers/xai/grok-writer-boundary.test.ts +128 tests/providers/xai/xai-additional-tools.test.ts +127 tests/providers/xai/xai-empty-catalog-tool-choice.test.ts +2151 tests/providers/xai/xai-loaded-tool-provenance.test.ts +126 tests/providers/xai/xai-no-stop.test.ts +80 tests/providers/xai/xai-oauth-retry.test.ts +1739 tests/providers/xai/xai-refresh-lock.test.ts +172 tests/providers/xai/xai-replay-provenance.test.ts +113 tests/providers/xai/xai-responses-adjacency.test.ts +111 tests/providers/xai/xai-tool-schema.test.ts +220 tests/providers/xai/xai-transport.test.ts +187 tests/providers/xai/xai-web-search-compat.test.ts +126 tests/providers/xai/xai-web-search.test.ts +394 tests/providers/zai-reasoning-replay.test.ts +240 tests/providers/zcode-client.test.ts +206 tests/providers/zed-argument-consistency.test.ts 476 tests/providers/zed-failure-relay.test.ts -523 tests/providers/zed-hosted-provider.test.ts -864 tests/providers/zed-lossless-arguments.test.ts +659 tests/providers/zed-hosted-provider.test.ts +713 tests/providers/zed-lossless-arguments.test.ts 279 tests/providers/zed-openai-contract.test.ts -347 tests/providers/zed-retained-budget.test.ts +158 tests/providers/zed-retained-budget.test.ts 150 tests/providers/zhipu-bigmodel-provider.test.ts 387 tests/providers/zhipu-bigmodel-responses-quota.test.ts -11203 tests/responses/agent-assertion-routes.test.ts -15791 tests/responses/anthropic2-responses-parity.test.ts -157 tests/responses/apply-patch-envelope.test.ts -507 tests/responses/bare-echo-alias.test.ts -3186 tests/responses/chat-anthropic-reasoning-details.test.ts -3610 tests/responses/chat-completions-deferred-tools.test.ts -96136 tests/responses/chat-completions-endpoint.test.ts -3046 tests/responses/chat-completions-pool-mode.test.ts -8786 tests/responses/chat-conversation-affinity.test.ts -919 tests/responses/chat-inbound-developer-position.test.ts -262 tests/responses/chat-inbound-reasoning-none.test.ts -128 tests/responses/chat-inbound-reasoning-replay.test.ts -1005 tests/responses/chat-incomplete-length-reason.test.ts -144 tests/responses/chat-inline-document-bytes.test.ts -2289 tests/responses/chat-json-sse-fallback.test.ts -1940 tests/responses/chat-legacy-functions-combo.test.ts -2267 tests/responses/chat-media-translation.test.ts -9477 tests/responses/chat-native-combo.test.ts -383 tests/responses/chat-native-decline-reason.test.ts -13813 tests/responses/chat-native-developer-role.test.ts -419 tests/responses/chat-native-image-normalization.test.ts -71 tests/responses/chat-native-lenient-finish.test.ts -27353 tests/responses/chat-native-reasoning-replay.test.ts -174 tests/responses/chat-native-reasoning-scope.test.ts -46595 tests/responses/chat-native-spend.test.ts -316 tests/responses/chat-native-sse-stall.test.ts -28453 tests/responses/chat-raw-reasoning-delivery.test.ts -96 tests/responses/chat-refusal-scope.test.ts -1944 tests/responses/chat-refusal.test.ts +10044 tests/responses/agent-assertion-routes.test.ts +11686 tests/responses/anthropic2-responses-parity.test.ts +224 tests/responses/apply-patch-envelope.test.ts +138 tests/responses/bare-echo-alias.test.ts +6396 tests/responses/chat-anthropic-reasoning-details.test.ts +3517 tests/responses/chat-completions-deferred-tools.test.ts +97034 tests/responses/chat-completions-endpoint.test.ts +3105 tests/responses/chat-completions-pool-mode.test.ts +10410 tests/responses/chat-conversation-affinity.test.ts +1832 tests/responses/chat-inbound-developer-position.test.ts +96 tests/responses/chat-inbound-reasoning-none.test.ts +467 tests/responses/chat-inbound-reasoning-replay.test.ts +1698 tests/responses/chat-incomplete-length-reason.test.ts +115 tests/responses/chat-inline-document-bytes.test.ts +4704 tests/responses/chat-json-sse-fallback.test.ts +2198 tests/responses/chat-legacy-functions-combo.test.ts +2522 tests/responses/chat-media-translation.test.ts +12813 tests/responses/chat-native-combo.test.ts +208 tests/responses/chat-native-decline-reason.test.ts +13789 tests/responses/chat-native-developer-role.test.ts +238 tests/responses/chat-native-image-normalization.test.ts +94 tests/responses/chat-native-lenient-finish.test.ts +28035 tests/responses/chat-native-reasoning-replay.test.ts +78 tests/responses/chat-native-reasoning-scope.test.ts +34947 tests/responses/chat-native-spend.test.ts +402 tests/responses/chat-native-sse-stall.test.ts +43435 tests/responses/chat-raw-reasoning-delivery.test.ts +68 tests/responses/chat-refusal-scope.test.ts +3448 tests/responses/chat-refusal.test.ts 24467 tests/responses/chat-request-id-endpoint.test.ts -2716 tests/responses/chat-responses-control-integration.test.ts -127 tests/responses/chat-responses-control-scope.test.ts -4112 tests/responses/chat-sse-framing-guard.test.ts -71 tests/responses/chat-tool-choice-allowed-tools.test.ts -89 tests/responses/citation-markers.test.ts -4882 tests/responses/codex-0164-request-compat.test.ts -2104 tests/responses/codex-ws-handshake-validation.test.ts -79 tests/responses/codex-ws-handshake.test.ts -141 tests/responses/codex-ws-pool-contention.test.ts -9407 tests/responses/combo-replay-refusal-attribution.test.ts -8964 tests/responses/compact-key-selection.test.ts -17472 tests/responses/compact-transient-alternate.test.ts +2317 tests/responses/chat-responses-control-integration.test.ts +148 tests/responses/chat-responses-control-scope.test.ts +4241 tests/responses/chat-sse-framing-guard.test.ts +129 tests/responses/chat-tool-choice-allowed-tools.test.ts +185 tests/responses/citation-markers.test.ts +4832 tests/responses/codex-0164-request-compat.test.ts +13260 tests/responses/codex-installation-failover.test.ts +5633 tests/responses/codex-installation-turn-limit.test.ts +2073 tests/responses/codex-ws-handshake-validation.test.ts +78 tests/responses/codex-ws-handshake.test.ts +76 tests/responses/codex-ws-pool-contention.test.ts +9723 tests/responses/combo-replay-refusal-attribution.test.ts +10606 tests/responses/compact-key-selection.test.ts +21334 tests/responses/compact-transient-alternate.test.ts 192 tests/responses/compaction-continuation-note.test.ts -633 tests/responses/compaction-continuation-wire.test.ts -144 tests/responses/compaction-event-ownership.test.ts -848 tests/responses/compaction-history-framing.test.ts -784 tests/responses/compaction-portable-history.test.ts -191 tests/responses/compaction-progress.test.ts -256 tests/responses/continuation-dedup.test.ts -74 tests/responses/custom-tool-compat.test.ts +1090 tests/responses/compaction-continuation-wire.test.ts +160 tests/responses/compaction-event-ownership.test.ts +1290 tests/responses/compaction-history-framing.test.ts +411 tests/responses/compaction-portable-history.test.ts +158 tests/responses/compaction-progress.test.ts +191 tests/responses/continuation-dedup.test.ts +67 tests/responses/custom-tool-compat.test.ts 616 tests/responses/direct-credit-renewal-ingress.test.ts 6370 tests/responses/droid-reasoning-defaults.test.ts -3885 tests/responses/empty-completion-core.test.ts -91 tests/responses/empty-completion-guard.test.ts +8432 tests/responses/empty-completion-core.test.ts +63 tests/responses/empty-completion-guard.test.ts 1227 tests/responses/empty-completion-hardening.test.ts -70 tests/responses/eventstream-decoder.test.ts -110 tests/responses/eventstream-fragmentation.test.ts -11111 tests/responses/explicit-empty-tool-catalog-history.test.ts -21327 tests/responses/explicit-empty-tool-catalog.test.ts -301 tests/responses/external-task-input-repair.test.ts -56 tests/responses/fix-eventstream-cancel-wait.test.ts -747 tests/responses/fresh-connection-optout.test.ts -42482 tests/responses/incomplete-reason-normalization.test.ts -11638 tests/responses/jev-initial-effort-wire.test.ts -61 tests/responses/legacy-shell-compat.test.ts -3353 tests/responses/local-upstream-deadlines.test.ts -317 tests/responses/messages-native-bridge-policy.test.ts -286 tests/responses/messages-native-eligibility.test.ts -198 tests/responses/messages-native-oauth-eligibility.test.ts -82 tests/responses/namespace-tool-compat.test.ts -1220 tests/responses/native-compaction-gateway-credentials.test.ts +80 tests/responses/eventstream-decoder.test.ts +64 tests/responses/eventstream-fragmentation.test.ts +18475 tests/responses/explicit-empty-tool-catalog-history.test.ts +41460 tests/responses/explicit-empty-tool-catalog.test.ts +299 tests/responses/external-task-input-repair.test.ts +79 tests/responses/fix-eventstream-cancel-wait.test.ts +1261 tests/responses/fresh-connection-optout.test.ts +115 tests/responses/graceful-max-output-tokens-exclusions.test.ts +1051 tests/responses/graceful-max-output-tokens.test.ts +46749 tests/responses/incomplete-reason-normalization.test.ts +19028 tests/responses/jev-initial-effort-wire.test.ts +79 tests/responses/legacy-shell-compat.test.ts +4559 tests/responses/local-upstream-deadlines.test.ts +174 tests/responses/messages-native-bridge-policy.test.ts +660 tests/responses/messages-native-eligibility.test.ts +219 tests/responses/messages-native-oauth-eligibility.test.ts +79 tests/responses/namespace-tool-compat.test.ts +9529 tests/responses/native-compaction-gateway-credentials.test.ts 18819 tests/responses/native-compaction-gateway-policy.test.ts -12274 tests/responses/native-compaction-gateway.test.ts -339 tests/responses/native-compaction-oauth.test.ts -20954 tests/responses/native-compaction-provenance.test.ts -189 tests/responses/opaque-blob-wrapped-rejection.test.ts +13387 tests/responses/native-compaction-gateway.test.ts +572 tests/responses/native-compaction-oauth.test.ts +18724 tests/responses/native-compaction-provenance.test.ts +207 tests/responses/opaque-blob-wrapped-rejection.test.ts 1260 tests/responses/openai-responses-passthrough.test.ts -283 tests/responses/openai-responses-summary-none.test.ts -279 tests/responses/opengateway-completion-receipts.test.ts -81 tests/responses/parser-content-audio.test.ts -450 tests/responses/passthrough-abort.test.ts -75985 tests/responses/passthrough-deferred-tools.test.ts -127 tests/responses/passthrough-grok-upstream-envelope-echo.test.ts -342 tests/responses/passthrough-headers.test.ts -141 tests/responses/passthrough-media-type.test.ts +175 tests/responses/openai-responses-summary-none.test.ts +159 tests/responses/opengateway-completion-receipts.test.ts +93 tests/responses/parser-content-audio.test.ts +693 tests/responses/passthrough-abort.test.ts +74858 tests/responses/passthrough-deferred-tools.test.ts +113 tests/responses/passthrough-grok-upstream-envelope-echo.test.ts +319 tests/responses/passthrough-headers.test.ts +576 tests/responses/passthrough-media-type.test.ts 166 tests/responses/passthrough-override.test.ts -220 tests/responses/plaintext-v2-agent-messages.test.ts +403 tests/responses/plaintext-v2-agent-messages.test.ts 9906 tests/responses/protocol-antigravity-direct-chat.test.ts -286 tests/responses/protocol-antigravity-direct-eligibility.test.ts -9145 tests/responses/protocol-antigravity-direct-messages.test.ts -38602 tests/responses/protocol-argon-thought-boundary.test.ts -218 tests/responses/protocol-baseline.test.ts +314 tests/responses/protocol-antigravity-direct-eligibility.test.ts +10772 tests/responses/protocol-antigravity-direct-messages.test.ts +47353 tests/responses/protocol-argon-thought-boundary.test.ts +33 tests/responses/protocol-baseline.test.ts 127 tests/responses/protocol-chat-ir-parity.test.ts -64 tests/responses/protocol-contract.test.ts -255 tests/responses/protocol-direct-encoders-chat.test.ts -184 tests/responses/protocol-direct-encoders-local-upstream.test.ts -134 tests/responses/protocol-direct-encoders-messages.test.ts -79 tests/responses/protocol-direct-encoders-stall-disabled.test.ts -242 tests/responses/protocol-dto.test.ts -80 tests/responses/protocol-envelope.test.ts -162 tests/responses/protocol-features.test.ts -65 tests/responses/protocol-guard.test.ts -946 tests/responses/protocol-ingress-guard.test.ts -271 tests/responses/protocol-messages-ir-parity.test.ts -79 tests/responses/protocol-opaque-state.test.ts +80 tests/responses/protocol-contract.test.ts +190 tests/responses/protocol-direct-encoders-chat.test.ts +91 tests/responses/protocol-direct-encoders-local-upstream.test.ts +172 tests/responses/protocol-direct-encoders-messages.test.ts +94 tests/responses/protocol-direct-encoders-stall-disabled.test.ts +80 tests/responses/protocol-dto.test.ts +47 tests/responses/protocol-envelope.test.ts +81 tests/responses/protocol-features.test.ts +215 tests/responses/protocol-guard.test.ts +773 tests/responses/protocol-ingress-guard.test.ts +237 tests/responses/protocol-messages-ir-parity.test.ts +63 tests/responses/protocol-opaque-state.test.ts 111 tests/responses/protocol-path.test.ts 365 tests/responses/protocol-plan-snapshot.test.ts 93 tests/responses/protocol-plan.test.ts -207 tests/responses/protocol-shadow-plan.test.ts -80 tests/responses/protocol-trace.test.ts -164 tests/responses/provider-egress-fetch.test.ts -1189 tests/responses/reasoning-archive-http.test.ts -2339 tests/responses/reasoning-archive-ws.test.ts -182 tests/responses/reasoning-effort-summary-default.test.ts -492 tests/responses/reasoning-envelope.test.ts -295 tests/responses/reasoning-retention-quota.test.ts -2254 tests/responses/reasoning-retention-routing.test.ts -1066 tests/responses/reasoning-retention-v2.test.ts -174 tests/responses/reasoning-retention.test.ts -9432 tests/responses/refreshed-upstream-deadlines.test.ts -278 tests/responses/reserve-dispatch-ws.test.ts -303 tests/responses/responses-4546-incident-regression.test.ts -23090 tests/responses/responses-account-auto-pause-wire-owner.test.ts -9852 tests/responses/responses-account-auto-pause.test.ts -113 tests/responses/responses-account-change-scrub.test.ts -7215 tests/responses/responses-account-label.test.ts -3872 tests/responses/responses-alternate-main-cancellation.test.ts -626 tests/responses/responses-anthropic-billing-send-budget.test.ts -421 tests/responses/responses-anthropic-compaction-prefix.test.ts -2689 tests/responses/responses-anthropic-fast-downgrade.test.ts -666 tests/responses/responses-anthropic-legal-history.test.ts -256 tests/responses/responses-anthropic-thinking-recovery.test.ts -5552 tests/responses/responses-anthropic-thinking-signature-recovery.test.ts -3303 tests/responses/responses-auto-pause-replay-owner.test.ts -4280 tests/responses/responses-azure-opaque-blob-recovery.test.ts -241 tests/responses/responses-bare-echo-helper-fence.test.ts -80 tests/responses/responses-call-id-linkage.test.ts -2460 tests/responses/responses-canonical-nonstream.test.ts -218 tests/responses/responses-canonical-only-top-level-fields.test.ts +269 tests/responses/protocol-shadow-plan.test.ts +140 tests/responses/protocol-trace.test.ts +80 tests/responses/provider-egress-fetch.test.ts +1757 tests/responses/reasoning-archive-http.test.ts +2716 tests/responses/reasoning-archive-ws.test.ts +238 tests/responses/reasoning-effort-summary-default.test.ts +223 tests/responses/reasoning-envelope.test.ts +173 tests/responses/reasoning-retention-quota.test.ts +3326 tests/responses/reasoning-retention-routing.test.ts +3347 tests/responses/reasoning-retention-v2.test.ts +141 tests/responses/reasoning-retention.test.ts +15597 tests/responses/refreshed-upstream-deadlines.test.ts +142 tests/responses/reserve-dispatch-ws.test.ts +223 tests/responses/responses-4546-incident-regression.test.ts +35422 tests/responses/responses-account-auto-pause-wire-owner.test.ts +13396 tests/responses/responses-account-auto-pause.test.ts +190 tests/responses/responses-account-change-scrub.test.ts +8301 tests/responses/responses-account-label.test.ts +8220 tests/responses/responses-alternate-main-cancellation.test.ts +491 tests/responses/responses-anthropic-billing-send-budget.test.ts +744 tests/responses/responses-anthropic-compaction-prefix.test.ts +4820 tests/responses/responses-anthropic-fast-downgrade.test.ts +1077 tests/responses/responses-anthropic-legal-history.test.ts +190 tests/responses/responses-anthropic-thinking-recovery.test.ts +17095 tests/responses/responses-anthropic-thinking-signature-recovery.test.ts +3869 tests/responses/responses-auto-pause-replay-owner.test.ts +5218 tests/responses/responses-azure-opaque-blob-recovery.test.ts +206 tests/responses/responses-bare-echo-helper-fence.test.ts +112 tests/responses/responses-call-id-linkage.test.ts +5320 tests/responses/responses-canonical-nonstream.test.ts +159 tests/responses/responses-canonical-only-top-level-fields.test.ts 699 tests/responses/responses-chat-tool-call-content.test.ts -173 tests/responses/responses-chatgpt-web-replay-metadata.test.ts -632 tests/responses/responses-claude-preflight-lease.test.ts -79 tests/responses/responses-code-mode-goal-helpers.test.ts -245 tests/responses/responses-code-mode-mcp-direct.test.ts -79 tests/responses/responses-code-mode-patch-compile.test.ts -175 tests/responses/responses-code-mode-shell-compile.test.ts -5199 tests/responses/responses-cold-opaque-recovery.test.ts -2422 tests/responses/responses-combo-exhausted-error.test.ts -1699 tests/responses/responses-combo-fallback-off.test.ts +158 tests/responses/responses-chatgpt-web-replay-metadata.test.ts +745 tests/responses/responses-claude-preflight-lease.test.ts +80 tests/responses/responses-code-mode-goal-helpers.test.ts +222 tests/responses/responses-code-mode-mcp-direct.test.ts +249 tests/responses/responses-code-mode-patch-compile.test.ts +176 tests/responses/responses-code-mode-shell-compile.test.ts +5452 tests/responses/responses-cold-opaque-recovery.test.ts +1108 tests/responses/responses-combo-bridge-usage.test.ts +5811 tests/responses/responses-combo-exhausted-error.test.ts +2824 tests/responses/responses-combo-fallback-off.test.ts 787 tests/responses/responses-combo-replay-principal.test.ts -9230 tests/responses/responses-combo-run-turn-classified-failure.test.ts -7909 tests/responses/responses-compact-handoff-admission.test.ts -3559 tests/responses/responses-compaction-http-isolation.test.ts -8501 tests/responses/responses-compaction-override.test.ts -126 tests/responses/responses-compaction-policy-identity.test.ts -88 tests/responses/responses-compaction-recovery-policy.test.ts +7178 tests/responses/responses-combo-run-turn-classified-failure.test.ts +7323 tests/responses/responses-compact-handoff-admission.test.ts +3641 tests/responses/responses-compaction-http-isolation.test.ts +14926 tests/responses/responses-compaction-override.test.ts +127 tests/responses/responses-compaction-policy-identity.test.ts +64 tests/responses/responses-compaction-recovery-policy.test.ts 12563 tests/responses/responses-compaction-recovery.test.ts 6618 tests/responses/responses-compaction-routing.test.ts -246 tests/responses/responses-compaction.test.ts -8609 tests/responses/responses-console-go-upload-retry.test.ts -39646 tests/responses/responses-context-overflow.test.ts -204 tests/responses/responses-continuation-boundaries.test.ts -239 tests/responses/responses-core-modules.test.ts -71 tests/responses/responses-custom-tool-guidance.test.ts -468 tests/responses/responses-custom-tool-historical-replay.test.ts -1690 tests/responses/responses-custom-tool-repair-dispatch.test.ts -114 tests/responses/responses-custom-tool-repair.test.ts -118 tests/responses/responses-custom-tool-stream-consistency.test.ts -88 tests/responses/responses-default-namespace-emit-normalize.test.ts -17000 tests/responses/responses-devin-401-replay.test.ts -95 tests/responses/responses-dispatch-receipt.test.ts +286 tests/responses/responses-compaction.test.ts +10741 tests/responses/responses-console-go-upload-retry.test.ts +47381 tests/responses/responses-context-overflow.test.ts +111 tests/responses/responses-continuation-boundaries.test.ts +192 tests/responses/responses-core-modules.test.ts +47 tests/responses/responses-custom-tool-guidance.test.ts +790 tests/responses/responses-custom-tool-historical-replay.test.ts +2763 tests/responses/responses-custom-tool-repair-dispatch.test.ts +244 tests/responses/responses-custom-tool-repair.test.ts +143 tests/responses/responses-custom-tool-stream-consistency.test.ts +62 tests/responses/responses-default-namespace-emit-normalize.test.ts +20381 tests/responses/responses-devin-401-replay.test.ts +63 tests/responses/responses-dispatch-receipt.test.ts 342 tests/responses/responses-fetch-helpers-boundary.test.ts -87 tests/responses/responses-field-backfill.test.ts +47 tests/responses/responses-field-backfill.test.ts 13909 tests/responses/responses-first-send-reservation.test.ts -1322 tests/responses/responses-first-send-spend-policy.test.ts -305 tests/responses/responses-forward-client-headers.test.ts -135 tests/responses/responses-forward-dangling-call.test.ts -1589 tests/responses/responses-forward-incomplete-quota.test.ts -272 tests/responses/responses-forward-output-cap.test.ts -164 tests/responses/responses-forward-posit-continuation.test.ts -174 tests/responses/responses-forward-prompt-envelope.test.ts -67 tests/responses/responses-forward-transport-baseurl.test.ts -344 tests/responses/responses-freeform-wrapper-keys.test.ts -451 tests/responses/responses-function-tool-repair.test.ts -15200 tests/responses/responses-grok-devin-preflight.test.ts -943 tests/responses/responses-hide-raw-reasoning.test.ts -1170 tests/responses/responses-hosted-image-delivery.test.ts -358 tests/responses/responses-hosted-image-display.test.ts -317 tests/responses/responses-hosted-image-limits.test.ts -3347 tests/responses/responses-hosted-send-hop.test.ts -5530 tests/responses/responses-hosted-send-producer.test.ts -7830 tests/responses/responses-hosted-send-reservation.test.ts -499 tests/responses/responses-hosted-send-round-parity.test.ts -2394 tests/responses/responses-hosted-send-unsent-hop.test.ts -1414 tests/responses/responses-hosted-send-ws.test.ts -145 tests/responses/responses-hosted-tool-declaration.test.ts -150 tests/responses/responses-hosted-tool-min-spread.test.ts -764 tests/responses/responses-image-gen-repair.test.ts -1939 tests/responses/responses-inbound-store-default.test.ts -87 tests/responses/responses-item-id-repair.test.ts -62 tests/responses/responses-json-events.test.ts -75 tests/responses/responses-legacy-dotted-tool-name-repair.test.ts -5176 tests/responses/responses-main-quota-observation.test.ts -1815 tests/responses/responses-memory-models.test.ts -49 tests/responses/responses-mimo-envelope.test.ts -490 tests/responses/responses-muse-tool-choice.test.ts -1128 tests/responses/responses-muse-tool-name-alias.test.ts -1412 tests/responses/responses-native-compact-search-history.test.ts -968 tests/responses/responses-native-item-extensions-compact.test.ts -196 tests/responses/responses-native-item-extensions.test.ts -7902 tests/responses/responses-native-key-cooldown.test.ts -1942 tests/responses/responses-native-main-refresh.test.ts -6027 tests/responses/responses-native-ultra-effort-wire.test.ts -11218 tests/responses/responses-oauth-refresh-capacity.test.ts -23718 tests/responses/responses-opaque-blob-recovery.test.ts -71 tests/responses/responses-parser-agent-message.test.ts -195 tests/responses/responses-parser-malformed-content.test.ts -256 tests/responses/responses-parser.test.ts -208 tests/responses/responses-passthrough-transient-policy.test.ts -87 tests/responses/responses-phase-inference.test.ts -34549 tests/responses/responses-pool-401-refresh.test.ts -12899 tests/responses/responses-pool-overload-failover.test.ts +1376 tests/responses/responses-first-send-spend-policy.test.ts +158 tests/responses/responses-forward-client-headers.test.ts +157 tests/responses/responses-forward-dangling-call.test.ts +1107 tests/responses/responses-forward-incomplete-quota.test.ts +250 tests/responses/responses-forward-output-cap.test.ts +241 tests/responses/responses-forward-posit-continuation.test.ts +113 tests/responses/responses-forward-prompt-envelope.test.ts +226 tests/responses/responses-forward-transport-baseurl.test.ts +242 tests/responses/responses-freeform-wrapper-keys.test.ts +460 tests/responses/responses-function-tool-repair.test.ts +21995 tests/responses/responses-grok-devin-preflight.test.ts +969 tests/responses/responses-hide-raw-reasoning.test.ts +1506 tests/responses/responses-hosted-image-delivery.test.ts +114 tests/responses/responses-hosted-image-display.test.ts +270 tests/responses/responses-hosted-image-limits.test.ts +3518 tests/responses/responses-hosted-send-hop.test.ts +9308 tests/responses/responses-hosted-send-producer.test.ts +9614 tests/responses/responses-hosted-send-reservation.test.ts +519 tests/responses/responses-hosted-send-round-parity.test.ts +2228 tests/responses/responses-hosted-send-unsent-hop.test.ts +949 tests/responses/responses-hosted-send-ws.test.ts +449 tests/responses/responses-hosted-tool-declaration.test.ts +143 tests/responses/responses-hosted-tool-min-spread.test.ts +1061 tests/responses/responses-image-gen-repair.test.ts +1900 tests/responses/responses-inbound-store-default.test.ts +81 tests/responses/responses-item-id-repair.test.ts +82 tests/responses/responses-json-events.test.ts +264 tests/responses/responses-legacy-dotted-tool-name-repair.test.ts +6335 tests/responses/responses-main-quota-observation.test.ts +4426 tests/responses/responses-memory-models.test.ts +109 tests/responses/responses-mimo-envelope.test.ts +950 tests/responses/responses-muse-tool-choice.test.ts +1045 tests/responses/responses-muse-tool-name-alias.test.ts +1770 tests/responses/responses-native-compact-search-history.test.ts +999 tests/responses/responses-native-item-extensions-compact.test.ts +191 tests/responses/responses-native-item-extensions.test.ts +9423 tests/responses/responses-native-key-cooldown.test.ts +3705 tests/responses/responses-native-main-refresh.test.ts +7936 tests/responses/responses-native-ultra-effort-wire.test.ts +14518 tests/responses/responses-oauth-refresh-capacity.test.ts +44924 tests/responses/responses-opaque-blob-recovery.test.ts +64 tests/responses/responses-parser-agent-message.test.ts +124 tests/responses/responses-parser-malformed-content.test.ts +269 tests/responses/responses-parser.test.ts +223 tests/responses/responses-passthrough-transient-policy.test.ts +83 tests/responses/responses-phase-inference.test.ts +38468 tests/responses/responses-pool-401-refresh.test.ts +14550 tests/responses/responses-pool-overload-failover.test.ts 199 tests/responses/responses-pool-refresh-attribution.test.ts -4828 tests/responses/responses-preview-main-read-fence.test.ts -1316 tests/responses/responses-reasoning-effort-downgrade.test.ts +10953 tests/responses/responses-preview-main-read-fence.test.ts +1406 tests/responses/responses-reasoning-effort-downgrade.test.ts 969 tests/responses/responses-reasoning-summary-passthrough.test.ts -735 tests/responses/responses-replay-metadata-principal.test.ts -125 tests/responses/responses-request-compression.test.ts -2815 tests/responses/responses-required-chat-tool.test.ts -136 tests/responses/responses-reset-replay.test.ts -4946 tests/responses/responses-retained-reasoning-stream-recovery.test.ts -408 tests/responses/responses-routed-web-search-fields.test.ts -1042 tests/responses/responses-run-turn-key-pacing.test.ts -1170 tests/responses/responses-run-turn-key-readmission.test.ts -8028 tests/responses/responses-run-turn-web-search.test.ts -3185 tests/responses/responses-self-named-namespace-scrub.test.ts -9297 tests/responses/responses-send-budget-counts.test.ts -3584 tests/responses/responses-send-budget-errors.test.ts -1958 tests/responses/responses-shadow-intercept.test.ts -3864 tests/responses/responses-show-thinking-summary.test.ts -16641 tests/responses/responses-sidecar-context-overflow.test.ts -1332 tests/responses/responses-sidecar-usage.test.ts +648 tests/responses/responses-replay-metadata-principal.test.ts +204 tests/responses/responses-request-compression.test.ts +5041 tests/responses/responses-required-chat-tool.test.ts +97 tests/responses/responses-reset-replay.test.ts +5023 tests/responses/responses-retained-reasoning-stream-recovery.test.ts +208 tests/responses/responses-routed-web-search-fields.test.ts +932 tests/responses/responses-run-turn-key-pacing.test.ts +2213 tests/responses/responses-run-turn-key-readmission.test.ts +12524 tests/responses/responses-run-turn-web-search.test.ts +4898 tests/responses/responses-self-named-namespace-scrub.test.ts +12624 tests/responses/responses-send-budget-counts.test.ts +5460 tests/responses/responses-send-budget-errors.test.ts +2304 tests/responses/responses-shadow-intercept.test.ts +5172 tests/responses/responses-show-thinking-summary.test.ts +21521 tests/responses/responses-sidecar-context-overflow.test.ts +1585 tests/responses/responses-sidecar-usage.test.ts 1391 tests/responses/responses-skills-snapshot.test.ts -12166 tests/responses/responses-snapshot-repair-server.test.ts -476 tests/responses/responses-snapshot-repair.test.ts -158 tests/responses/responses-sparse-terminal-tool-scope.test.ts -12257 tests/responses/responses-spend-anchor.test.ts -271 tests/responses/responses-spend-capacity-guard.test.ts -509 tests/responses/responses-spend-contract-c.test.ts -363 tests/responses/responses-spend-ledger-wiring.test.ts -103 tests/responses/responses-spill-acl-recovery.test.ts -949 tests/responses/responses-spill-admission-headroom.test.ts -236 tests/responses/responses-spill-inspection.test.ts -238 tests/responses/responses-spill-orphan-sweep.test.ts -332 tests/responses/responses-spill-shutdown-clock.test.ts -635 tests/responses/responses-state-flush-race.test.ts -72 tests/responses/responses-state-snapshot-select.test.ts -95 tests/responses/responses-state-snapshot-stubs.test.ts -840 tests/responses/responses-state-store-false.test.ts -1264 tests/responses/responses-state-write-amplification.test.ts -13598 tests/responses/responses-state.test.ts -2769 tests/responses/responses-stateless-dangling-call-repair.test.ts -168 tests/responses/responses-stream-tool-events.test.ts -143 tests/responses/responses-terminal-repair.test.ts -159 tests/responses/responses-tool-conformance.test.ts -105 tests/responses/responses-tool-groups.test.ts -1029 tests/responses/responses-tool-search-repair.test.ts -2110 tests/responses/responses-translated-replay-principal.test.ts -33178 tests/responses/responses-translated-reset.test.ts -1906 tests/responses/responses-undeclared-tool-guard-inbound.test.ts -5082 tests/responses/responses-undeclared-tool-guard.test.ts -96 tests/responses/responses-url-citation-title-repair.test.ts -336 tests/responses/responses-usage-passthrough.test.ts -15501 tests/responses/responses-web-search-thinking-signature-recovery.test.ts -206 tests/responses/responses-xai-request-compat.test.ts -2159 tests/responses/shadow-intercept-target-lifecycle.test.ts -250 tests/responses/sse-carriage-return.test.ts -364 tests/responses/sse-client-frame-bounds.test.ts -511 tests/responses/sse-decoder.test.ts -634 tests/responses/sse-failed-tail.test.ts +15384 tests/responses/responses-snapshot-repair-server.test.ts +223 tests/responses/responses-snapshot-repair.test.ts +522 tests/responses/responses-snapshot-scaling.test.ts +161 tests/responses/responses-sparse-terminal-tool-scope.test.ts +16711 tests/responses/responses-spend-anchor.test.ts +115 tests/responses/responses-spend-capacity-guard.test.ts +714 tests/responses/responses-spend-contract-c.test.ts +379 tests/responses/responses-spend-ledger-wiring.test.ts +127 tests/responses/responses-spill-acl-recovery.test.ts +760 tests/responses/responses-spill-admission-headroom.test.ts +174 tests/responses/responses-spill-inspection.test.ts +206 tests/responses/responses-spill-orphan-sweep.test.ts +346 tests/responses/responses-spill-shutdown-clock.test.ts +721 tests/responses/responses-state-flush-race.test.ts +81 tests/responses/responses-state-snapshot-select.test.ts +125 tests/responses/responses-state-snapshot-stubs.test.ts +1151 tests/responses/responses-state-store-false.test.ts +1735 tests/responses/responses-state-write-amplification.test.ts +11688 tests/responses/responses-state.test.ts +5644 tests/responses/responses-stateless-dangling-call-repair.test.ts +80 tests/responses/responses-stream-tool-events.test.ts +480 tests/responses/responses-terminal-repair.test.ts +339 tests/responses/responses-tool-conformance.test.ts +94 tests/responses/responses-tool-groups.test.ts +1673 tests/responses/responses-tool-search-repair.test.ts +2963 tests/responses/responses-translated-replay-principal.test.ts +48677 tests/responses/responses-translated-reset.test.ts +2710 tests/responses/responses-undeclared-tool-guard-inbound.test.ts +14141 tests/responses/responses-undeclared-tool-guard.test.ts +111 tests/responses/responses-url-citation-title-repair.test.ts +93 tests/responses/responses-usage-passthrough.test.ts +26005 tests/responses/responses-web-search-thinking-signature-recovery.test.ts +192 tests/responses/responses-xai-request-compat.test.ts +2504 tests/responses/shadow-intercept-target-lifecycle.test.ts +78 tests/responses/sse-carriage-return.test.ts +412 tests/responses/sse-client-frame-bounds.test.ts +444 tests/responses/sse-decoder.test.ts +348 tests/responses/sse-failed-tail.test.ts 646 tests/responses/sse-inspector-bounds.test.ts -119 tests/responses/sse-null-data-frame.test.ts +129 tests/responses/sse-null-data-frame.test.ts 159 tests/responses/sse-payload-rewrite.test.ts -215 tests/responses/sse-rewrite-line-endings.test.ts -88 tests/responses/sse-unspaced-data-fields.test.ts -167 tests/responses/thought-signature-credential-scope.test.ts -735 tests/responses/turn-membership-ingress.test.ts -119 tests/responses/turn-membership.test.ts -119 tests/responses/visualization-directives.test.ts -3047 tests/responses/ws-ambiguous-resend.test.ts -39308 tests/responses/ws-capacity-reclamation.test.ts -3348 tests/responses/ws-capacity-tool-ownership.test.ts +337 tests/responses/sse-rewrite-line-endings.test.ts +95 tests/responses/sse-unspaced-data-fields.test.ts +174 tests/responses/thought-signature-credential-scope.test.ts +679 tests/responses/turn-membership-ingress.test.ts +81 tests/responses/turn-membership.test.ts +65 tests/responses/visualization-directives.test.ts +6591 tests/responses/ws-ambiguous-resend.test.ts +42648 tests/responses/ws-capacity-reclamation.test.ts +3359 tests/responses/ws-capacity-tool-ownership.test.ts 96 tests/responses/ws-committed-liveness.test.ts -210 tests/responses/ws-endpoint.test.ts -249 tests/responses/ws-failure-stage.test.ts +222 tests/responses/ws-endpoint.test.ts +141 tests/responses/ws-failure-stage.test.ts 3546 tests/responses/ws-native-injection.test.ts -1257 tests/responses/ws-native-result-continuations.test.ts +2125 tests/responses/ws-native-result-continuations.test.ts 4707 tests/responses/ws-native-steering.test.ts -261 tests/responses/ws-pre-output-refusal.test.ts -1070 tests/responses/ws-replay-refusal-attribution.test.ts -2239 tests/responses/ws-steering-completion.test.ts -269 tests/responses/ws-steering-smoke.test.ts -1011 tests/responses/ws-steering-stability.test.ts +351 tests/responses/ws-pre-output-refusal.test.ts +1388 tests/responses/ws-replay-refusal-attribution.test.ts +4176 tests/responses/ws-steering-completion.test.ts +643 tests/responses/ws-steering-smoke.test.ts +571 tests/responses/ws-steering-stability.test.ts 220 tests/responses/ws-upstream-reuse.test.ts 77 tests/responses/ws-upstream-socks5.test.ts -1322 tests/responses/ws-upstream.test.ts -3888 tests/routing/always-on-429-failover.test.ts -2326 tests/routing/anthropic-quorum-cache.test.ts -63 tests/routing/cl01-claude-outbound-review-regressions.test.ts +2564 tests/responses/ws-upstream.test.ts +5027 tests/routing/always-on-429-failover.test.ts +2286 tests/routing/anthropic-quorum-cache.test.ts +79 tests/routing/cl01-claude-outbound-review-regressions.test.ts 95 tests/routing/cl01-openai-chat-review-regressions.test.ts -175 tests/routing/cl01-review-regressions.test.ts -591 tests/routing/codex-agent-role-models.test.ts -120 tests/routing/codex-role-auto-assign.test.ts -80 tests/routing/codex-role-sizing.test.ts -207 tests/routing/combo-child-headers.test.ts -1665 tests/routing/combo-description.test.ts -15738 tests/routing/combo-management-api.test.ts -142 tests/routing/combo-required-tool-stream-preflight.test.ts -247 tests/routing/combo-stream-preflight.test.ts +126 tests/routing/cl01-review-regressions.test.ts +394 tests/routing/codex-agent-role-models.test.ts +95 tests/routing/codex-role-auto-assign.test.ts +320 tests/routing/codex-role-capability-consent.test.ts +62 tests/routing/codex-role-capability-redirects.test.ts +182 tests/routing/codex-role-measured-ties.test.ts +50 tests/routing/codex-role-sizing.test.ts +140 tests/routing/combo-child-headers.test.ts +1761 tests/routing/combo-description.test.ts +15836 tests/routing/combo-management-api.test.ts +282 tests/routing/combo-required-tool-stream-preflight.test.ts +128 tests/routing/combo-stream-preflight.test.ts 191 tests/routing/combo-terminal-refusal.test.ts 3272 tests/routing/combo-vision-enrollment.test.ts -15351 tests/routing/compatibility-provider-equivalence.test.ts -95 tests/routing/destination-policy-resolved.test.ts -94 tests/routing/fallback-policy.test.ts -254 tests/routing/fastwire-characterization-routing.test.ts -3060 tests/routing/fastwire-characterization-wire.test.ts -461 tests/routing/fastwire-observability.test.ts -291 tests/routing/fastwire-policy.test.ts -2202 tests/routing/fastwire-response-authority.test.ts -103 tests/routing/jev-decision-destination.test.ts -3087 tests/routing/jev-decision-model-config.test.ts -2781 tests/routing/jev-decision-provider-combo.test.ts -494 tests/routing/jev-decision.test.ts -1267 tests/routing/jev-model-backend.test.ts -7098 tests/routing/jev-quota-activation.test.ts -5204 tests/routing/jev-quota-anthropic2.test.ts -3187 tests/routing/jev-quota-antigravity.test.ts -2665 tests/routing/jev-quota-codex-reset.test.ts -3799 tests/routing/jev-quota-config.test.ts -1126 tests/routing/jev-quota-core-boundary.test.ts -2023 tests/routing/jev-quota-publication.test.ts -331 tests/routing/jev-quota-signals.test.ts -113 tests/routing/jev-service-exchange.test.ts +15167 tests/routing/compatibility-provider-equivalence.test.ts +241 tests/routing/destination-policy-resolved.test.ts +95 tests/routing/fallback-policy.test.ts +208 tests/routing/fastwire-characterization-routing.test.ts +6603 tests/routing/fastwire-characterization-wire.test.ts +720 tests/routing/fastwire-observability.test.ts +175 tests/routing/fastwire-policy.test.ts +3271 tests/routing/fastwire-response-authority.test.ts +81 tests/routing/jev-decision-destination.test.ts +2930 tests/routing/jev-decision-model-config.test.ts +2473 tests/routing/jev-decision-provider-combo.test.ts +190 tests/routing/jev-decision.test.ts +1073 tests/routing/jev-model-backend.test.ts +7863 tests/routing/jev-quota-activation.test.ts +5848 tests/routing/jev-quota-anthropic2.test.ts +2963 tests/routing/jev-quota-antigravity.test.ts +3288 tests/routing/jev-quota-codex-reset.test.ts +3410 tests/routing/jev-quota-config.test.ts +1174 tests/routing/jev-quota-core-boundary.test.ts +2558 tests/routing/jev-quota-publication.test.ts +364 tests/routing/jev-quota-signals.test.ts +127 tests/routing/jev-service-exchange.test.ts 79 tests/routing/jev-session-pin.test.ts -109 tests/routing/jev-typesafe-golden.test.ts -475 tests/routing/policy-execution.test.ts -2781 tests/routing/probe-lease-dispatch-wiring.test.ts -192 tests/routing/probe-lease.test.ts -581 tests/routing/resolved-model-policy-consumers.test.ts -63 tests/routing/router-anthropic-billing-failover.test.ts -459 tests/routing/router-blocked-cross-provider.test.ts -109 tests/routing/router-combo-failover-classification.test.ts -210 tests/routing/router-discarded-baseurl-warning.test.ts +53 tests/routing/jev-typesafe-golden.test.ts +274 tests/routing/policy-execution.test.ts +2376 tests/routing/probe-lease-dispatch-wiring.test.ts +218 tests/routing/probe-lease.test.ts +344 tests/routing/resolved-model-policy-consumers.test.ts +93 tests/routing/router-anthropic-billing-failover.test.ts +381 tests/routing/router-blocked-cross-provider.test.ts +121 tests/routing/router-combo-failover-classification.test.ts +142 tests/routing/router-discarded-baseurl-warning.test.ts 145 tests/routing/router-template-baseurl.test.ts -167 tests/routing/router.test.ts -3673 tests/routing/routing-analytics.test.ts -128 tests/routing/routing-capability-catalog.test.ts -1554 tests/routing/routing-capability-model-matching.test.ts -80 tests/routing/routing-compatibility-auth-identity.test.ts -30510 tests/routing/routing-compatibility-boundaries.test.ts -80 tests/routing/routing-compatibility-model-matching.test.ts +230 tests/routing/router.test.ts +4330 tests/routing/routing-analytics.test.ts +95 tests/routing/routing-capability-catalog.test.ts +366 tests/routing/routing-capability-model-matching.test.ts +63 tests/routing/routing-compatibility-auth-identity.test.ts +30471 tests/routing/routing-compatibility-boundaries.test.ts +96 tests/routing/routing-compatibility-model-matching.test.ts 15485 tests/routing/routing-compatibility.test.ts 80 tests/routing/routing-identity-domains.test.ts -1157 tests/routing/routing-policy-dispatch-scope.test.ts -333 tests/routing/routing-policy-fallback-off.test.ts -461 tests/routing/routing-policy-fallback.test.ts +411 tests/routing/routing-policy-dispatch-scope.test.ts +174 tests/routing/routing-policy-fallback-off.test.ts +491 tests/routing/routing-policy-fallback.test.ts 234 tests/routing/routing-policy-pool-quota.test.ts -15727 tests/routing/routing-policy-surface-parity.test.ts -30431 tests/routing/routing-profile-management-editor.test.ts -1019 tests/routing/routing-profile.test.ts +15468 tests/routing/routing-policy-surface-parity.test.ts +30866 tests/routing/routing-profile-management-editor.test.ts +776 tests/routing/routing-profile.test.ts 252 tests/routing/subagent-context-staleness.test.ts -83 tests/routing/subagent-defaults.test.ts -23481 tests/routing/subagent-fallback-handle-responses.test.ts -79 tests/routing/subagent-fallback-preview-sites.test.ts -492 tests/routing/subagent-model-fallback-api.test.ts -872 tests/routing/subagent-model-fallback-off.test.ts -35428 tests/routing/subagent-model-fallback.test.ts -3111 tests/routing/subagent-roster-migration.test.ts -1736 tests/routing/subagent-roster-retention.test.ts -236 tests/server/account-import-project-fallback.test.ts -2321 tests/server/account-import.test.ts -89298 tests/server/account-pool-management-api.test.ts -336 tests/server/adapter-resolve.test.ts -95 tests/server/advisor-routes.test.ts -159 tests/server/agent-assertion-auth.test.ts -1168 tests/server/agent-task-recovery-cache.test.ts +101 tests/routing/subagent-defaults.test.ts +30688 tests/routing/subagent-fallback-handle-responses.test.ts +78 tests/routing/subagent-fallback-preview-sites.test.ts +363 tests/routing/subagent-model-fallback-api.test.ts +1521 tests/routing/subagent-model-fallback-off.test.ts +38293 tests/routing/subagent-model-fallback.test.ts +2996 tests/routing/subagent-roster-migration.test.ts +1946 tests/routing/subagent-roster-retention.test.ts +342 tests/server/account-import-project-fallback.test.ts +2946 tests/server/account-import.test.ts +88278 tests/server/account-pool-management-api.test.ts +186 tests/server/adapter-resolve.test.ts +196 tests/server/advisor-routes.test.ts +406 tests/server/agent-assertion-auth.test.ts +2164 tests/server/agent-task-recovery-cache.test.ts 3795 tests/server/agent-task-recovery-combo.test.ts -356 tests/server/agent-task-recovery-fallback.test.ts +940 tests/server/agent-task-recovery-fallback.test.ts 1363 tests/server/agent-task-recovery-security.test.ts -18461 tests/server/agent-task-recovery.test.ts -268 tests/server/alias-management-api.test.ts -3187 tests/server/anthropic2-management.test.ts -160 tests/server/api-access-endpoints.test.ts -7690 tests/server/api-catalog-route.test.ts -2312 tests/server/api-codex-log-guard-compact.test.ts -680 tests/server/api-codex-log-guard-protection.test.ts -419 tests/server/api-codex-log-guard.test.ts -22768 tests/server/api-debug.test.ts -30301 tests/server/api-key-attribution.test.ts -531 tests/server/api-key-model-scope.test.ts -1665 tests/server/api-key-scope-alpha-search.test.ts -214 tests/server/api-key-scope-audio.test.ts -316 tests/server/api-key-scope-images.test.ts -423 tests/server/api-key-scope-live.test.ts -92275 tests/server/api-keys-routes.test.ts -60963 tests/server/api-usage.test.ts -6487 tests/server/aside-profiles-routes.test.ts -161 tests/server/audio-client.test.ts -20688 tests/server/audio-dictation.test.ts -35948 tests/server/audio-transcriptions.test.ts -852 tests/server/bounded-body.test.ts -174 tests/server/bridge-live-delivery.test.ts -1163 tests/server/caller-session-identity.test.ts -2825 tests/server/caller-session-ingress.test.ts -3254 tests/server/cancel-body-on-abort.test.ts -20719 tests/server/claude-intercept-integration.test.ts -5520 tests/server/codex-agent-role-routes.test.ts -511 tests/server/codex-role-auto-assign-routes.test.ts -1602 tests/server/codex-role-history-recovery.test.ts -2864 tests/server/combo-loopback-metered-consent.test.ts -1516 tests/server/combo-metered-consent.test.ts +29693 tests/server/agent-task-recovery.test.ts +222 tests/server/alias-management-api.test.ts +3443 tests/server/anthropic2-management.test.ts +161 tests/server/api-access-endpoints.test.ts +9456 tests/server/api-catalog-route.test.ts +2147 tests/server/api-codex-log-guard-compact.test.ts +788 tests/server/api-codex-log-guard-protection.test.ts +537 tests/server/api-codex-log-guard.test.ts +19958 tests/server/api-debug.test.ts +22524 tests/server/api-key-attribution.test.ts +415 tests/server/api-key-model-scope.test.ts +2048 tests/server/api-key-scope-alpha-search.test.ts +208 tests/server/api-key-scope-audio.test.ts +379 tests/server/api-key-scope-images.test.ts +175 tests/server/api-key-scope-live.test.ts +91218 tests/server/api-keys-routes.test.ts +60632 tests/server/api-usage.test.ts +6065 tests/server/aside-profiles-routes.test.ts +94 tests/server/audio-client.test.ts +20540 tests/server/audio-dictation.test.ts +35679 tests/server/audio-transcriptions.test.ts +948 tests/server/bounded-body.test.ts +158 tests/server/bridge-live-delivery.test.ts +2651 tests/server/caller-session-identity.test.ts +1783 tests/server/caller-session-ingress.test.ts +3505 tests/server/cancel-body-on-abort.test.ts +20864 tests/server/claude-intercept-integration.test.ts +5580 tests/server/codex-agent-role-routes.test.ts +394 tests/server/codex-role-auto-assign-routes.test.ts +220 tests/server/codex-role-configured-credentials.test.ts +947 tests/server/codex-role-history-recovery.test.ts +4667 tests/server/combo-loopback-metered-consent.test.ts +1868 tests/server/combo-metered-consent.test.ts 65 tests/server/combo-requested-effort.test.ts -468 tests/server/companion-settings.test.ts -9593 tests/server/config.test.ts -151 tests/server/consume-for-inspection-cancel.test.ts -6424 tests/server/context-history-ownership.test.ts -400 tests/server/context-history.test.ts +237 tests/server/companion-settings.test.ts +10582 tests/server/config.test.ts +191 tests/server/consume-for-inspection-cancel.test.ts +6327 tests/server/context-history-ownership.test.ts +496 tests/server/context-history.test.ts 1960 tests/server/data-plane-admission-identity.test.ts -113 tests/server/debug-settings.test.ts -78 tests/server/decision-discovery.test.ts -477 tests/server/decision-routes.test.ts -3235 tests/server/distributed-key-401.test.ts -247 tests/server/error-fidelity.test.ts -415 tests/server/errors-adapter-failure.test.ts -2709 tests/server/fallback-routes.test.ts -747 tests/server/fetch-header-timeout.test.ts -4287 tests/server/health-scoring.test.ts -4655 tests/server/hub-usage.test.ts -9337 tests/server/inbound-body-admission.test.ts -159 tests/server/inbound-body-budget.test.ts -176 tests/server/inference-attempt.test.ts -270 tests/server/inference-client-encoder-delivery.test.ts -79 tests/server/inference-client-wire.test.ts -175 tests/server/inference-final-log.test.ts -3040 tests/server/inference-send-budget.test.ts -151 tests/server/input-admission.test.ts -143 tests/server/jev-decision-scope.test.ts -1008 tests/server/link-child-parity.test.ts -3506 tests/server/link-enrollment.test.ts -2698 tests/server/link-join-route.test.ts -8791 tests/server/link-listener-admission.test.ts -388 tests/server/link-listener-lifecycle.test.ts -214 tests/server/link-listener-mutation.test.ts -23652 tests/server/link-management-relay.test.ts -1924 tests/server/link-management-routes.test.ts -97 tests/server/live-call-bindings.test.ts -85 tests/server/live-native-calls.test.ts -525 tests/server/local-account-switch-capability.test.ts +95 tests/server/debug-settings.test.ts +81 tests/server/decision-discovery.test.ts +333 tests/server/decision-routes.test.ts +2259 tests/server/distributed-key-401.test.ts +400 tests/server/error-fidelity.test.ts +292 tests/server/errors-adapter-failure.test.ts +2618 tests/server/fallback-routes.test.ts +587 tests/server/fetch-header-timeout.test.ts +4403 tests/server/health-scoring.test.ts +2692 tests/server/hub-usage.test.ts +5312 tests/server/inbound-body-admission.test.ts +250 tests/server/inbound-body-budget.test.ts +92 tests/server/inference-attempt.test.ts +222 tests/server/inference-client-encoder-delivery.test.ts +63 tests/server/inference-client-wire.test.ts +110 tests/server/inference-final-log.test.ts +4802 tests/server/inference-send-budget.test.ts +111 tests/server/input-admission.test.ts +415 tests/server/jev-decision-scope.test.ts +601 tests/server/link-child-parity.test.ts +3981 tests/server/link-enrollment.test.ts +2618 tests/server/link-join-route.test.ts +7523 tests/server/link-listener-admission.test.ts +365 tests/server/link-listener-lifecycle.test.ts +379 tests/server/link-listener-mutation.test.ts +25666 tests/server/link-management-relay.test.ts +2266 tests/server/link-management-routes.test.ts +95 tests/server/live-call-bindings.test.ts +64 tests/server/live-native-calls.test.ts +481 tests/server/local-account-switch-capability.test.ts 1296 tests/server/local-account-switch-ingress.test.ts 5799 tests/server/local-aside-sync-capability.test.ts -152 tests/server/local-management-attestation.test.ts +79 tests/server/local-management-attestation.test.ts 111 tests/server/local-management-capability.test.ts -617 tests/server/local-management-direct-transport.test.ts -80 tests/server/local-provider-reload-client.test.ts -1085 tests/server/local-read-response-proof.test.ts -756 tests/server/login-shell-path.test.ts -361 tests/server/logs-timezone.test.ts +565 tests/server/local-management-direct-transport.test.ts +222 tests/server/local-provider-reload-client.test.ts +1474 tests/server/local-read-response-proof.test.ts +662 tests/server/login-shell-path.test.ts +238 tests/server/logs-timezone.test.ts 215 tests/server/loopback-companion-client-targets.test.ts 256 tests/server/loopback-listener-admission.test.ts -68276 tests/server/loopback-listener-integration.test.ts -1396 tests/server/management-account-auto-pause.test.ts +83804 tests/server/loopback-listener-integration.test.ts +1205 tests/server/management-account-auto-pause.test.ts 1915 tests/server/management-anthropic-reset-grants.test.ts -428 tests/server/management-api-logs-metrics.test.ts -190 tests/server/management-api-logs-timing-basis.test.ts -2475 tests/server/management-auto-review-auth.test.ts -1320 tests/server/management-auto-review-settings.test.ts -816 tests/server/management-client-config-route.test.ts -200 tests/server/management-desktop-compatibility-routes.test.ts -215 tests/server/management-desktop-compatibility-runtime-routes.test.ts -539 tests/server/management-desktop-compatibility-settings.test.ts -514 tests/server/management-droid-reasoning-defaults.test.ts +413 tests/server/management-api-logs-metrics.test.ts +222 tests/server/management-api-logs-timing-basis.test.ts +2010 tests/server/management-auto-review-auth.test.ts +1713 tests/server/management-auto-review-settings.test.ts +1155 tests/server/management-client-config-route.test.ts +159 tests/server/management-desktop-compatibility-routes.test.ts +222 tests/server/management-desktop-compatibility-runtime-routes.test.ts +962 tests/server/management-desktop-compatibility-settings.test.ts +492 tests/server/management-droid-reasoning-defaults.test.ts 2045 tests/server/management-export-model-names.test.ts -33601 tests/server/management-gcp-credential-input.test.ts -1592 tests/server/management-google-tool-schema-policy.test.ts -603 tests/server/management-inference-port.test.ts -4251 tests/server/management-integration-journal-delete.test.ts -16509 tests/server/management-integration-routes.test.ts -30384 tests/server/management-metrics-export.test.ts +21725 tests/server/management-gcp-credential-input.test.ts +1857 tests/server/management-google-tool-schema-policy.test.ts +524 tests/server/management-inference-port.test.ts +3342 tests/server/management-integration-journal-delete.test.ts +15909 tests/server/management-integration-routes.test.ts +25508 tests/server/management-metrics-export.test.ts 270 tests/server/management-model-roster-gather-race.test.ts 207 tests/server/management-model-roster.test.ts 96 tests/server/management-origin-tls.test.ts 4578 tests/server/management-provider-atomicity.test.ts -36968 tests/server/management-provider-compat-carry.test.ts -568 tests/server/management-provider-context-inference.test.ts -11300 tests/server/management-provider-hide-raw-reasoning.test.ts -2134 tests/server/management-provider-pinsless-validation.test.ts -2666 tests/server/management-provider-proto-override.test.ts -12008 tests/server/management-provider-reasoning-lists.test.ts -855 tests/server/management-provider-request-pacing.test.ts -80 tests/server/management-provider-reset-replay.test.ts -12994 tests/server/management-provider-responses-reasoning.test.ts -1084 tests/server/management-provider-synthetic-max.test.ts -1698 tests/server/management-provider-upstream-websocket.test.ts +36191 tests/server/management-provider-compat-carry.test.ts +480 tests/server/management-provider-context-inference.test.ts +8136 tests/server/management-provider-hide-raw-reasoning.test.ts +2806 tests/server/management-provider-pinsless-validation.test.ts +1809 tests/server/management-provider-proto-override.test.ts +11935 tests/server/management-provider-reasoning-lists.test.ts +505 tests/server/management-provider-request-pacing.test.ts +63 tests/server/management-provider-reset-replay.test.ts +16781 tests/server/management-provider-responses-reasoning.test.ts +998 tests/server/management-provider-synthetic-max.test.ts +1636 tests/server/management-provider-upstream-websocket.test.ts 136959 tests/server/management-provider-validation.test.ts 2116 tests/server/management-provider-verbosity.test.ts -910 tests/server/management-qoder-selector-state.test.ts -1476 tests/server/management-route-registry.test.ts -8404 tests/server/management-sidecar-anthropic-instance.test.ts -379 tests/server/management-workflow-budget-routes.test.ts -544 tests/server/memory-watchdog.test.ts -833 tests/server/model-costs-management-api.test.ts -5075 tests/server/model-costs-pricing-cache.test.ts -6762 tests/server/model-costs-prompt-length-pricing.test.ts +711 tests/server/management-qoder-selector-state.test.ts +3508 tests/server/management-route-registry.test.ts +7021 tests/server/management-sidecar-anthropic-instance.test.ts +176 tests/server/management-workflow-budget-routes.test.ts +552 tests/server/memory-watchdog.test.ts +600 tests/server/model-costs-management-api.test.ts +4384 tests/server/model-costs-pricing-cache.test.ts +9249 tests/server/model-costs-prompt-length-pricing.test.ts 191 tests/server/model-discovery-management-api.test.ts -3693 tests/server/model-export-new-model-policy.test.ts -2232 tests/server/model-settings-management-api.test.ts -237 tests/server/outbound-body-guard.test.ts -333 tests/server/owned-service-home.test.ts +3455 tests/server/model-export-new-model-policy.test.ts +1826 tests/server/model-settings-management-api.test.ts +81 tests/server/outbound-body-guard.test.ts +192 tests/server/owned-service-home.test.ts 64 tests/server/passive-route-linker.test.ts -3664 tests/server/persistent-dashboard-admission.test.ts -6615 tests/server/persistent-dashboard-consent.test.ts -1655 tests/server/persistent-dashboard-session.test.ts -6934 tests/server/plaintext-v2-agent-messages-server.test.ts -1101 tests/server/port-reclaim.test.ts -434 tests/server/ports.test.ts -15842 tests/server/prefer-model-alias-ids.test.ts -1830 tests/server/probe-timeout-env.test.ts -217 tests/server/protocol-provider-summary.test.ts -393 tests/server/protocol-routes.test.ts -191 tests/server/protocol-settings-route.test.ts -1567 tests/server/provider-account-quota-routes.test.ts -95 tests/server/provider-egress-management-validation.test.ts -326 tests/server/provider-send-path-import.test.ts -113 tests/server/proxy-env-macos.test.ts -380 tests/server/proxy-env.test.ts -2901 tests/server/proxy-liveness-bind-scope.test.ts -1077 tests/server/proxy-liveness-owner-evidence.test.ts -71 tests/server/proxy-liveness-package-tree-fence.test.ts -73 tests/server/proxy-liveness-recovery.test.ts -106 tests/server/proxy-liveness.test.ts -11346 tests/server/quota-pool-relay.test.ts -3393 tests/server/readyz-features.test.ts -860 tests/server/relay-eager.test.ts -15000 tests/server/replay-refusal-parity.test.ts -1205 tests/server/reserve-claude-policy.test.ts -23655 tests/server/reserve-ingress.test.ts -637 tests/server/response-log-inspection.test.ts -1095 tests/server/response-model-identity.test.ts -984 tests/server/restart-replacement-not-ready.test.ts -206 tests/server/restart-replacement.test.ts -345 tests/server/retry-after-429.test.ts -78 tests/server/retry-delay-hardening.test.ts -410 tests/server/route-decision-trace.test.ts -12564 tests/server/served-by-header.test.ts -3650 tests/server/server-403-permission-e2e.test.ts -1309 tests/server/server-agent-task-recovery-replay.test.ts -5650 tests/server/server-anthropic-billing-boundaries.test.ts -10277 tests/server/server-anthropic-billing.test.ts -2089 tests/server/server-antigravity-model-denial-recovery.test.ts -13169 tests/server/server-antigravity-model-roster-routing.test.ts -191 tests/server/server-antigravity-verify-replay-scope.test.ts -21282 tests/server/server-antigravity-web-search-validation.test.ts -1331 tests/server/server-auth-localhost-bind.test.ts -9841 tests/server/server-auth-scoped-quota.test.ts -166990 tests/server/server-auth.test.ts -20243 tests/server/server-background-lifecycle.test.ts -9498 tests/server/server-chat-native-key-selection.test.ts -2407 tests/server/server-cli-key-probe-admission.test.ts -80 tests/server/server-clickjacking-headers.test.ts -2749 tests/server/server-combo-cooldown-fallback.test.ts -2629 tests/server/server-combo-cooldown-recording.test.ts -69653 tests/server/server-combo-failover-e2e.test.ts -64 tests/server/server-combo-held-response.test.ts -13621 tests/server/server-combo-plan-model-refusal.test.ts -236 tests/server/server-combo-quota-code-provenance.test.ts -4711 tests/server/server-combo-reasoning-replay-eligibility.test.ts -8051 tests/server/server-combo-required-tool-contract.test.ts -4929 tests/server/server-combo-stream-hosted-tool-contract.test.ts -7509 tests/server/server-combo-stream-required-tool.test.ts -2167 tests/server/server-combo-stream-send-contract.test.ts -6512 tests/server/server-combo-tool-loop-continuation.test.ts -4578 tests/server/server-combo-zero-output-failover.test.ts +2542 tests/server/persistent-dashboard-admission.test.ts +9041 tests/server/persistent-dashboard-consent.test.ts +1140 tests/server/persistent-dashboard-session.test.ts +11144 tests/server/plaintext-v2-agent-messages-server.test.ts +1110 tests/server/port-reclaim.test.ts +503 tests/server/ports.test.ts +19647 tests/server/prefer-model-alias-ids.test.ts +977 tests/server/probe-timeout-env.test.ts +268 tests/server/protocol-provider-summary.test.ts +190 tests/server/protocol-routes.test.ts +173 tests/server/protocol-settings-route.test.ts +1255 tests/server/provider-account-quota-routes.test.ts +253 tests/server/provider-egress-management-validation.test.ts +298 tests/server/provider-send-path-import.test.ts +263 tests/server/proxy-env-macos.test.ts +112 tests/server/proxy-env.test.ts +3413 tests/server/proxy-liveness-bind-scope.test.ts +1376 tests/server/proxy-liveness-owner-evidence.test.ts +95 tests/server/proxy-liveness-package-tree-fence.test.ts +247 tests/server/proxy-liveness-recovery.test.ts +199 tests/server/proxy-liveness.test.ts +9323 tests/server/quota-pool-relay.test.ts +2215 tests/server/readyz-features.test.ts +947 tests/server/relay-eager.test.ts +17583 tests/server/replay-refusal-parity.test.ts +1387 tests/server/reserve-claude-policy.test.ts +21057 tests/server/reserve-ingress.test.ts +982 tests/server/response-log-inspection.test.ts +1661 tests/server/response-model-identity.test.ts +957 tests/server/restart-replacement-not-ready.test.ts +201 tests/server/restart-replacement.test.ts +335 tests/server/retry-after-429.test.ts +114 tests/server/retry-delay-hardening.test.ts +235 tests/server/route-decision-trace.test.ts +13622 tests/server/served-by-header.test.ts +4544 tests/server/server-403-permission-e2e.test.ts +4023 tests/server/server-agent-task-recovery-replay.test.ts +6267 tests/server/server-anthropic-billing-boundaries.test.ts +12125 tests/server/server-anthropic-billing.test.ts +2075 tests/server/server-antigravity-model-denial-recovery.test.ts +15800 tests/server/server-antigravity-model-roster-routing.test.ts +254 tests/server/server-antigravity-verify-replay-scope.test.ts +23596 tests/server/server-antigravity-web-search-validation.test.ts +1061 tests/server/server-auth-localhost-bind.test.ts +8594 tests/server/server-auth-scoped-quota.test.ts +244552 tests/server/server-auth.test.ts +15177 tests/server/server-background-lifecycle.test.ts +11760 tests/server/server-chat-native-key-selection.test.ts +2560 tests/server/server-cli-key-probe-admission.test.ts +79 tests/server/server-clickjacking-headers.test.ts +3057 tests/server/server-combo-cooldown-fallback.test.ts +3375 tests/server/server-combo-cooldown-recording.test.ts +67226 tests/server/server-combo-failover-e2e.test.ts +244 tests/server/server-combo-held-response.test.ts +20721 tests/server/server-combo-plan-model-refusal.test.ts +190 tests/server/server-combo-quota-code-provenance.test.ts +5184 tests/server/server-combo-reasoning-replay-eligibility.test.ts +37119 tests/server/server-combo-required-tool-contract.test.ts +4133 tests/server/server-combo-stream-hosted-tool-contract.test.ts +11384 tests/server/server-combo-stream-required-tool.test.ts +3952 tests/server/server-combo-stream-send-contract.test.ts +7979 tests/server/server-combo-tool-loop-continuation.test.ts +5529 tests/server/server-combo-zero-output-failover.test.ts 909 tests/server/server-desktop-compatibility-startup.test.ts -18776 tests/server/server-generic-oauth-affinity.test.ts -109400 tests/server/server-google-antigravity-oauth-401-replay.test.ts -12825 tests/server/server-google-antigravity-oauth-429-budget.test.ts -95 tests/server/server-gui-bundle-freshness.test.ts -192 tests/server/server-images-bodyless-content-length.test.ts -3087 tests/server/server-images-pool-admission.test.ts +19801 tests/server/server-generic-oauth-affinity.test.ts +80940 tests/server/server-google-antigravity-oauth-401-replay.test.ts +8395 tests/server/server-google-antigravity-oauth-429-budget.test.ts +63 tests/server/server-gui-bundle-freshness.test.ts +237 tests/server/server-images-bodyless-content-length.test.ts +3438 tests/server/server-images-pool-admission.test.ts 90665 tests/server/server-images.test.ts -711 tests/server/server-jev-combo-e2e.test.ts -191 tests/server/server-jev-model-decision-e2e.test.ts -666 tests/server/server-jev-model-quota-budget.test.ts -688 tests/server/server-jev-session-pin.test.ts -90309 tests/server/server-key-failover-e2e.test.ts -24641 tests/server/server-kiro-completion-e2e.test.ts -1938 tests/server/server-kiro-device-login.test.ts +492 tests/server/server-jev-combo-e2e.test.ts +640 tests/server/server-jev-model-decision-e2e.test.ts +429 tests/server/server-jev-model-quota-budget.test.ts +399 tests/server/server-jev-session-pin.test.ts +74695 tests/server/server-key-failover-e2e.test.ts +25095 tests/server/server-kiro-completion-e2e.test.ts +2716 tests/server/server-kiro-device-login.test.ts 7822 tests/server/server-kiro-oauth-401-replay.test.ts -97105 tests/server/server-kiro-refusal-e2e.test.ts +117502 tests/server/server-kiro-refusal-e2e.test.ts 2921 tests/server/server-live-cancel.test.ts -8920 tests/server/server-live-close.test.ts -4840 tests/server/server-live-existing-call.test.ts +8965 tests/server/server-live-close.test.ts +4039 tests/server/server-live-existing-call.test.ts 333 tests/server/server-live-frame-log.test.ts 8565 tests/server/server-live-realtime-fixtures.test.ts -43936 tests/server/server-live.test.ts -162 tests/server/server-loopback-host-gate.test.ts +47614 tests/server/server-live.test.ts +237 tests/server/server-loopback-host-gate.test.ts 41641 tests/server/server-management-auth.test.ts -3439 tests/server/server-management-log-admission.test.ts -15883 tests/server/server-native-catalog-priority.test.ts -111 tests/server/server-native-reasoning-retention-merge.test.ts -269 tests/server/server-native-reasoning-retention.test.ts -12474 tests/server/server-new-model-policy-arrival.test.ts -5888 tests/server/server-opencode-go-goal-streaming.test.ts -12118 tests/server/server-rate-limit-retry-e2e.test.ts -4063 tests/server/server-request-body-size.test.ts -20480 tests/server/server-search.test.ts -2476 tests/server/server-startup-codex-off.test.ts -9030 tests/server/server-startup-reconcile-resilience.test.ts -5463 tests/server/server-stop-config-hardening.test.ts -2230 tests/server/server-terminal-refusal-wiring.test.ts -2324 tests/server/server-xai-chat-reasoning-streaming.test.ts -3768 tests/server/server-xai-header-parity.test.ts -12122 tests/server/server-xai-oauth-401-replay.test.ts -13480 tests/server/server-xai-responses-streaming.test.ts -2516 tests/server/session-affinity.test.ts -2179 tests/server/session-lane-recall-harness.test.ts -518 tests/server/sidebar-routes.test.ts -229 tests/server/sidebar-star-state.test.ts +3721 tests/server/server-management-log-admission.test.ts +19010 tests/server/server-native-catalog-priority.test.ts +127 tests/server/server-native-reasoning-retention-merge.test.ts +205 tests/server/server-native-reasoning-retention.test.ts +13214 tests/server/server-new-model-policy-arrival.test.ts +4772 tests/server/server-opencode-go-goal-streaming.test.ts +7999 tests/server/server-rate-limit-retry-e2e.test.ts +3246 tests/server/server-request-body-size.test.ts +22095 tests/server/server-search.test.ts +2531 tests/server/server-startup-codex-off.test.ts +9394 tests/server/server-startup-reconcile-resilience.test.ts +7932 tests/server/server-stop-config-hardening.test.ts +1883 tests/server/server-terminal-refusal-wiring.test.ts +222 tests/server/server-workflow-budget-settings.test.ts +2249 tests/server/server-xai-chat-reasoning-streaming.test.ts +3936 tests/server/server-xai-header-parity.test.ts +17849 tests/server/server-xai-oauth-401-replay.test.ts +15831 tests/server/server-xai-responses-streaming.test.ts +2381 tests/server/session-affinity.test.ts +3142 tests/server/session-lane-recall-harness.test.ts +427 tests/server/sidebar-routes.test.ts +96 tests/server/sidebar-star-state.test.ts 173 tests/server/spend-instrumentation-log.test.ts 1013 tests/server/spend-ledger-lifecycle.test.ts -3981 tests/server/spend-ledger-owner-startup.test.ts -176 tests/server/startup-action-control-elevation.test.ts -552 tests/server/startup-action-control.test.ts -33636 tests/server/startup-health-packaged-probe.test.ts +5046 tests/server/spend-ledger-owner-startup.test.ts +159 tests/server/startup-action-control-elevation.test.ts +254 tests/server/startup-action-control.test.ts +34335 tests/server/startup-health-packaged-probe.test.ts 73 tests/server/startup-prompt.test.ts 158 tests/server/stream-aborted-marker.test.ts -1205 tests/server/subagent-model-force-api.test.ts -714 tests/server/system-env.test.ts -262 tests/server/system-restart-admission.test.ts -846 tests/server/system-restart.test.ts -421 tests/server/system-routes.test.ts -7522 tests/server/terminal-guard-server.test.ts -130 tests/server/terminal-guard.test.ts -191 tests/server/update-async-routes.test.ts +1452 tests/server/subagent-model-force-api.test.ts +855 tests/server/system-env.test.ts +255 tests/server/system-restart-admission.test.ts +13375 tests/server/system-restart-ownership.test.ts +315 tests/server/system-restart.test.ts +222 tests/server/system-routes.test.ts +8840 tests/server/terminal-guard-server.test.ts +144 tests/server/terminal-guard.test.ts +207 tests/server/update-async-routes.test.ts 197 tests/server/upstream-connect-error.test.ts -88 tests/server/upstream-http-version.test.ts -8946 tests/server/v1-hub-state.test.ts -2236 tests/server/v2-agent-message-failfast.test.ts -271 tests/service/autostart-health.test.ts -3233 tests/service/connected-stop-capability-auth.test.ts -4662 tests/service/container-bootstrap.test.ts -155 tests/service/crash-guard.test.ts -175 tests/service/doctor-codex-envkey-readiness.test.ts -752 tests/service/doctor-oauth.test.ts -175 tests/service/doctor-provider-apikey.test.ts -74 tests/service/doctor-service-memory-contract.test.ts -331 tests/service/init-backup-cleanup.test.ts -6937 tests/service/init-eof.test.ts -616 tests/service/launchd-port-fallback.test.ts -7362 tests/service/launchd-repair.test.ts -141 tests/service/live-service-manager-guard.test.ts -80 tests/service/managing-cli.test.ts -195 tests/service/ownership-mutation-lease-diagnostics.test.ts +239 tests/server/upstream-http-version.test.ts +20792 tests/server/v1-hub-state.test.ts +4476 tests/server/v2-agent-message-failfast.test.ts +194 tests/service/autostart-health.test.ts +2513 tests/service/connected-stop-capability-auth.test.ts +2714 tests/service/container-bootstrap.test.ts +112 tests/service/crash-guard.test.ts +239 tests/service/doctor-codex-envkey-readiness.test.ts +947 tests/service/doctor-oauth.test.ts +329 tests/service/doctor-provider-apikey.test.ts +178 tests/service/doctor-service-memory-contract.test.ts +238 tests/service/init-backup-cleanup.test.ts +8102 tests/service/init-eof.test.ts +412 tests/service/launchd-port-fallback.test.ts +5688 tests/service/launchd-repair.test.ts +175 tests/service/live-service-manager-guard.test.ts +112 tests/service/managing-cli.test.ts +174 tests/service/ownership-mutation-lease-diagnostics.test.ts 966 tests/service/process-state.test.ts -1170 tests/service/service-auth-qualified-localhost.test.ts -556 tests/service/service-child-ownership.test.ts -230 tests/service/service-claim.test.ts -83 tests/service/service-desktop-login-registration.test.ts -293 tests/service/service-desktop-recovery.test.ts -50 tests/service/service-desktop-runtime-preflight.test.ts -204 tests/service/service-desktop-startup-health.test.ts -296 tests/service/service-desktop-startup-linux.test.ts -1242 tests/service/service-desktop-startup.test.ts -183 tests/service/service-desktop-supervision-windows.test.ts -155 tests/service/service-handled-signal-exit.test.ts -104 tests/service/service-health-sentinel-launch.test.ts -80 tests/service/service-health-sentinel-linux.test.ts +1239 tests/service/service-auth-qualified-localhost.test.ts +698 tests/service/service-child-ownership.test.ts +310 tests/service/service-claim.test.ts +81 tests/service/service-desktop-login-registration.test.ts +159 tests/service/service-desktop-recovery.test.ts +93 tests/service/service-desktop-runtime-preflight.test.ts +142 tests/service/service-desktop-startup-health.test.ts +268 tests/service/service-desktop-startup-linux.test.ts +1601 tests/service/service-desktop-startup.test.ts +128 tests/service/service-desktop-supervision-windows.test.ts +258 tests/service/service-handled-signal-exit.test.ts +108 tests/service/service-health-sentinel-launch.test.ts +75 tests/service/service-health-sentinel-linux.test.ts 88 tests/service/service-health-sentinel-policy.test.ts -8135 tests/service/service-health-sentinel-process.test.ts -540 tests/service/service-health-sentinel-runner.test.ts -142 tests/service/service-install-wrapper-cleanup.test.ts -2858 tests/service/service-log.test.ts +8162 tests/service/service-health-sentinel-process.test.ts +522 tests/service/service-health-sentinel-runner.test.ts +453 tests/service/service-install-wrapper-cleanup.test.ts +3184 tests/service/service-log.test.ts 160 tests/service/service-multishell-path.test.ts -79 tests/service/service-ownership-compatibility.test.ts -823 tests/service/service-ownership-handover.test.ts +97 tests/service/service-ownership-compatibility.test.ts +598 tests/service/service-ownership-handover.test.ts 5072 tests/service/service-ownership-state.test.ts -150 tests/service/service-probe-docker.test.ts -181 tests/service/service-proxy-env.test.ts -539 tests/service/service-runtime-preflight.test.ts -7145 tests/service/service-secrets.test.ts -408 tests/service/service-sqlite-home.test.ts -233 tests/service/service-start-environment.test.ts -1013 tests/service/service-state-isolation.test.ts -2988 tests/service/service-status-json.test.ts -405 tests/service/service-stop-verification.test.ts -1985 tests/service/service-tier-capability.test.ts -423 tests/service/service-wsl-home-ownership.test.ts -2641 tests/service/service.test.ts -636 tests/service/shutdown-drain.test.ts -111 tests/service/shutdown-launcher.test.ts -109 tests/service/stale-state-purge.test.ts -81 tests/service/standalone-service.test.ts -53448 tests/service/stop-deferred-teardown.test.ts -619 tests/service/stop-direct-fetch.test.ts -2875 tests/service/stop-restoration-preflight.test.ts -23021 tests/service/stop-restore-history-ownership.test.ts -63 tests/service/systemd-install-cleanup-hardening.test.ts -475 tests/service/winsw.test.ts -28998 tests/storage/api-storage-cleanup.test.ts -6489 tests/storage/api-storage-policy-already-running.test.ts -6914 tests/storage/api-storage-policy-mutation-busy.test.ts -5939 tests/storage/api-storage-policy-put-race.test.ts -6870 tests/storage/api-storage-policy-run.test.ts -5872 tests/storage/api-storage-policy.test.ts -2934 tests/storage/api-storage.test.ts -17115 tests/storage/storage-cleanup.test.ts -19594 tests/storage/storage-mutation-race.test.ts -1583 tests/storage/storage-policy-config-race.test.ts -6552 tests/storage/storage-policy-job-responsive.test.ts -254346 tests/storage/storage-policy.test.ts +62 tests/service/service-probe-docker.test.ts +91 tests/service/service-proxy-env.test.ts +460 tests/service/service-runtime-preflight.test.ts +7605 tests/service/service-secrets.test.ts +363 tests/service/service-sqlite-home.test.ts +172 tests/service/service-start-environment.test.ts +699 tests/service/service-state-isolation.test.ts +2813 tests/service/service-status-json.test.ts +111 tests/service/service-stop-verification.test.ts +3428 tests/service/service-tier-capability.test.ts +426 tests/service/service-wsl-home-ownership.test.ts +2993 tests/service/service.test.ts +442 tests/service/shutdown-drain.test.ts +265 tests/service/shutdown-launcher.test.ts +226 tests/service/stale-state-purge.test.ts +97 tests/service/standalone-service.test.ts +50776 tests/service/stop-deferred-teardown.test.ts +586 tests/service/stop-direct-fetch.test.ts +1939 tests/service/stop-restoration-preflight.test.ts +23394 tests/service/stop-restore-history-ownership.test.ts +48 tests/service/systemd-install-cleanup-hardening.test.ts +254 tests/service/winsw.test.ts +31188 tests/storage/api-storage-cleanup.test.ts +6076 tests/storage/api-storage-policy-already-running.test.ts +4729 tests/storage/api-storage-policy-mutation-busy.test.ts +4977 tests/storage/api-storage-policy-put-race.test.ts +6828 tests/storage/api-storage-policy-run.test.ts +7661 tests/storage/api-storage-policy.test.ts +3846 tests/storage/api-storage.test.ts +15008 tests/storage/storage-cleanup.test.ts +20269 tests/storage/storage-mutation-race.test.ts +2336 tests/storage/storage-policy-config-race.test.ts +5366 tests/storage/storage-policy-job-responsive.test.ts +254396 tests/storage/storage-policy.test.ts 135 tests/storage/storage-restore-job-errors.test.ts 12177 tests/storage/storage-restore-job-responsive.test.ts -2184 tests/storage/storage-scanner.test.ts +1352 tests/storage/storage-scanner.test.ts 4849 tests/storage/storage-worker-lifecycle.test.ts -149 tests/storage/storage-worker-os-join-settle.test.ts -25044 tests/storage/storage-worker-teardown-isolate.test.ts -2732 tests/test-layout-tooling.test.ts +1 tests/storage/storage-worker-os-join-settle.test.ts +25080 tests/storage/storage-worker-teardown-isolate.test.ts +2693 tests/test-layout-tooling.test.ts 209 tests/test-layout.test.ts -158 tests/update/pnpm-command-isolation.test.ts -97 tests/update/update-badge.test.ts -8893 tests/update/update-bun-ownership-lease.test.ts -1216 tests/update/update-capability-policy.test.ts -87 tests/update/update-desktop-badge.test.ts -58 tests/update/update-desktop-owner.test.ts -87 tests/update/update-effect-authority.test.ts +143 tests/update/pnpm-command-isolation.test.ts +96 tests/update/update-badge.test.ts +9964 tests/update/update-bun-ownership-lease.test.ts +1535 tests/update/update-capability-policy.test.ts +82 tests/update/update-desktop-badge.test.ts +97 tests/update/update-desktop-owner.test.ts +191 tests/update/update-effect-authority.test.ts 204 tests/update/update-guarded-ops.test.ts -802 tests/update/update-home-launcher.test.ts -119 tests/update/update-home-recovery.test.ts -3789 tests/update/update-home-worker.test.ts -1077 tests/update/update-job-supervised-restart.test.ts -6672 tests/update/update-job.test.ts -96 tests/update/update-mise-launcher-target.test.ts -81 tests/update/update-mise-node-runtime.test.ts +1344 tests/update/update-home-launcher.test.ts +81 tests/update/update-home-recovery.test.ts +2772 tests/update/update-home-worker.test.ts +1050 tests/update/update-job-supervised-restart.test.ts +6781 tests/update/update-job.test.ts +64 tests/update/update-mise-launcher-target.test.ts +63 tests/update/update-mise-node-runtime.test.ts 517 tests/update/update-mise.test.ts -306 tests/update/update-mutation-boundaries.test.ts -2342 tests/update/update-mutation-guard.test.ts -2650 tests/update/update-mutation-scanner.test.ts -435 tests/update/update-notify.test.ts -381 tests/update/update-npm-cache-preflight.test.ts -104 tests/update/update-npm-invocation.test.ts -3257 tests/update/update-npm-supervisor-exit.test.ts -7232 tests/update/update-npm-timeout.test.ts -299 tests/update/update-pnpm.test.ts -79 tests/update/update-reclaim-authorizer.test.ts -77 tests/update/update-recovery-authority.test.ts -680 tests/update/update-recovery-boundaries.test.ts -230 tests/update/update-recovery-host-free.test.ts -604 tests/update/update-refresh.test.ts -50463 tests/update/update-restart-lease.test.ts -81 tests/update/update-service-home-policy.test.ts -2101 tests/update/update-service-home.test.ts -349 tests/update/update-standalone.test.ts -2385 tests/update/update-stop-classification.test.ts -286 tests/update/update-stop-first.test.ts -80 tests/update/update-supervised-recovery.test.ts -8016 tests/update/update-teardown-handover.test.ts -710 tests/update/update-transactional-leftovers.test.ts -465 tests/update/update-transactional.test.ts -3999 tests/update/update-tray-handoff.test.ts -237 tests/update/update-tree-ownership.test.ts -121 tests/update/update-windows-wrapper-authority.test.ts -71 tests/update/update-worker-launch.test.ts -95 tests/usage/anthropic2-usage-attribution.test.ts -285 tests/usage/cache-diagnostic.test.ts -841 tests/usage/cost-cap-unknown-evidence.test.ts -127 tests/usage/cost-scoring.test.ts +236 tests/update/update-mutation-boundaries.test.ts +1286 tests/update/update-mutation-guard.test.ts +1793 tests/update/update-mutation-scanner.test.ts +316 tests/update/update-notify.test.ts +499 tests/update/update-npm-cache-preflight.test.ts +112 tests/update/update-npm-invocation.test.ts +3808 tests/update/update-npm-supervisor-exit.test.ts +9160 tests/update/update-npm-timeout.test.ts +222 tests/update/update-pnpm.test.ts +258 tests/update/update-reclaim-authorizer.test.ts +97 tests/update/update-recovery-authority.test.ts +633 tests/update/update-recovery-boundaries.test.ts +64 tests/update/update-recovery-host-free.test.ts +457 tests/update/update-refresh.test.ts +49298 tests/update/update-restart-lease.test.ts +47 tests/update/update-service-home-policy.test.ts +1346 tests/update/update-service-home.test.ts +175 tests/update/update-standalone.test.ts +2437 tests/update/update-stop-classification.test.ts +264 tests/update/update-stop-first.test.ts +150 tests/update/update-supervised-recovery.test.ts +5978 tests/update/update-teardown-handover.test.ts +776 tests/update/update-transactional-leftovers.test.ts +509 tests/update/update-transactional.test.ts +4075 tests/update/update-tray-handoff.test.ts +317 tests/update/update-tree-ownership.test.ts +63 tests/update/update-windows-wrapper-authority.test.ts +48 tests/update/update-worker-launch.test.ts +110 tests/usage/anthropic2-usage-attribution.test.ts +269 tests/usage/cache-diagnostic.test.ts +683 tests/usage/cost-cap-unknown-evidence.test.ts +375 tests/usage/cost-scoring.test.ts 152 tests/usage/gpt61-terra-pricing.test.ts -83 tests/usage/jev-stats.test.ts -176 tests/usage/key-attribution.test.ts -6776 tests/usage/quota-401-recovery-runtime.test.ts -152 tests/usage/quota-401-recovery.test.ts -6951 tests/usage/quota-pool.test.ts -206 tests/usage/quota-reset-account-key.test.ts -491 tests/usage/quota-reset-core-boundary.test.ts -147 tests/usage/quota-reset-detector.test.ts -116 tests/usage/quota-reset-notify-config.test.ts -1056 tests/usage/quota-reset-notify.test.ts -1646 tests/usage/quota-reset-observation.test.ts -2571 tests/usage/quota-reset-seen-store.test.ts -730 tests/usage/quota-scoring.test.ts -1016 tests/usage/request-decompress.test.ts -78 tests/usage/request-evidence.test.ts -13044 tests/usage/request-history-index.test.ts -5363 tests/usage/request-history-rebuild-worker.test.ts -155 tests/usage/request-log-attempt-identity.test.ts -236 tests/usage/request-log-conversation.test.ts -489 tests/usage/request-log-estimate-cap.test.ts -254 tests/usage/request-log-generation-window.test.ts -182 tests/usage/request-log-jev.test.ts -63 tests/usage/request-log-model-filter.test.ts -297 tests/usage/request-log-nonstream.test.ts -128 tests/usage/request-log-protocol-trace.test.ts -405 tests/usage/request-log-served-model.test.ts -867 tests/usage/request-log.test.ts -152 tests/usage/request-outcome-agreement.test.ts +105 tests/usage/jev-stats.test.ts +98 tests/usage/key-attribution.test.ts +7096 tests/usage/quota-401-recovery-runtime.test.ts +94 tests/usage/quota-401-recovery.test.ts +9287 tests/usage/quota-pool.test.ts +238 tests/usage/quota-reset-account-key.test.ts +666 tests/usage/quota-reset-core-boundary.test.ts +83 tests/usage/quota-reset-detector.test.ts +111 tests/usage/quota-reset-notify-config.test.ts +1009 tests/usage/quota-reset-notify.test.ts +1764 tests/usage/quota-reset-observation.test.ts +2337 tests/usage/quota-reset-seen-store.test.ts +568 tests/usage/quota-scoring.test.ts +838 tests/usage/request-decompress.test.ts +48 tests/usage/request-evidence.test.ts +11526 tests/usage/request-history-index.test.ts +29236 tests/usage/request-history-integrity.test.ts +6512 tests/usage/request-history-rebuild-worker.test.ts +289 tests/usage/request-log-attempt-identity.test.ts +128 tests/usage/request-log-conversation.test.ts +271 tests/usage/request-log-estimate-cap.test.ts +302 tests/usage/request-log-generation-window.test.ts +191 tests/usage/request-log-jev.test.ts +48 tests/usage/request-log-model-filter.test.ts +186 tests/usage/request-log-nonstream.test.ts +267 tests/usage/request-log-normalization.test.ts +124 tests/usage/request-log-protocol-trace.test.ts +126 tests/usage/request-log-served-model.test.ts +1061 tests/usage/request-log.test.ts +223 tests/usage/request-outcome-agreement.test.ts 95 tests/usage/request-pacing-provenance.test.ts -316 tests/usage/request-pacing.test.ts -25834 tests/usage/upstream-failure-diagnostics.test.ts -451 tests/usage/usage-aggregate-cache.test.ts -79 tests/usage/usage-anthropic-fast-pricing.test.ts -112 tests/usage/usage-antigravity-55.test.ts -71 tests/usage/usage-attempt-delivery.test.ts -130 tests/usage/usage-cost.test.ts -65 tests/usage/usage-cursor-fast-pricing.test.ts -557 tests/usage/usage-debug.test.ts -114 tests/usage/usage-failure-fingerprint.test.ts -134 tests/usage/usage-failure-persistence.test.ts -118 tests/usage/usage-failure-projection.test.ts -92 tests/usage/usage-haiku-5-5-pricing.test.ts -461 tests/usage/usage-ledger-retention.test.ts -388 tests/usage/usage-ledger-scanner.test.ts -151 tests/usage/usage-log-ws-stage.test.ts -3259 tests/usage/usage-log.test.ts -286 tests/usage/usage-partly-measured-cost.test.ts -97 tests/usage/usage-prompt-length-pricing.test.ts -63 tests/usage/usage-provider-label.test.ts -628 tests/usage/usage-shape-extraction.test.ts -95 tests/usage/usage-snapshot-digest-reuse.test.ts -96 tests/usage/usage-spend-cache-provenance.test.ts -190 tests/usage/usage-summary.test.ts -70 tests/usage/usage-surfaces.test.ts -170 tests/usage/usage-throughput.test.ts -56 tests/usage/usage-time-range.test.ts -3006 tests/usage/usage-timeline.test.ts -1326 tests/usage/user-cost-overlay-coderabbit-regressions.test.ts +237 tests/usage/request-pacing.test.ts +29860 tests/usage/upstream-failure-diagnostics.test.ts +331 tests/usage/usage-aggregate-cache.test.ts +64 tests/usage/usage-anthropic-fast-pricing.test.ts +63 tests/usage/usage-antigravity-55.test.ts +79 tests/usage/usage-attempt-delivery.test.ts +118 tests/usage/usage-cost.test.ts +177 tests/usage/usage-cursor-fast-pricing.test.ts +423 tests/usage/usage-debug.test.ts +63 tests/usage/usage-failure-fingerprint.test.ts +159 tests/usage/usage-failure-persistence.test.ts +63 tests/usage/usage-failure-projection.test.ts +117 tests/usage/usage-haiku-5-5-pricing.test.ts +315 tests/usage/usage-ledger-retention.test.ts +348 tests/usage/usage-ledger-scanner.test.ts +47 tests/usage/usage-log-ws-stage.test.ts +4066 tests/usage/usage-log.test.ts +95 tests/usage/usage-partly-measured-cost.test.ts +89 tests/usage/usage-prompt-length-pricing.test.ts +108 tests/usage/usage-provider-label.test.ts +401 tests/usage/usage-shape-extraction.test.ts +111 tests/usage/usage-snapshot-digest-reuse.test.ts +108 tests/usage/usage-spend-cache-provenance.test.ts +254 tests/usage/usage-summary.test.ts +302 tests/usage/usage-surfaces.test.ts +48 tests/usage/usage-throughput.test.ts +63 tests/usage/usage-time-range.test.ts +3970 tests/usage/usage-timeline.test.ts +1280 tests/usage/user-cost-overlay-coderabbit-regressions.test.ts 4366 tests/usage/user-cost-overlay-live-reconcile.test.ts -618 tests/usage/user-cost-overlay-provider-delete.test.ts -72 tests/videos/fulfill-video.test.ts -159 tests/videos/plan-video.test.ts -112 tests/videos/xai-video-client.test.ts -14083 tests/vision/mistral-vision-sidecar.test.ts -308 tests/vision/sidecar-abort.test.ts -345 tests/vision/sidecar-auth.test.ts -270 tests/vision/sidecar-candidates.test.ts +759 tests/usage/user-cost-overlay-provider-delete.test.ts +65 tests/videos/fulfill-video.test.ts +364 tests/videos/plan-video.test.ts +109 tests/videos/xai-video-client.test.ts +17132 tests/vision/mistral-vision-sidecar.test.ts +475 tests/vision/sidecar-abort.test.ts +144 tests/vision/sidecar-auth.test.ts +141 tests/vision/sidecar-candidates.test.ts 5515 tests/vision/sidecar-settings-vision-catalog.test.ts -1654 tests/vision/sidecar-settings-vision-controls.test.ts -1392 tests/vision/sidecar-settings-vision-filter.test.ts -1702 tests/vision/sidecar-settings-web-search-gate.test.ts -1266 tests/vision/sidecar-settings-web-search-off.test.ts -1005 tests/vision/sidecar-settings-web-search-stream.test.ts -48 tests/vision/sidecar-tracker.test.ts -6433 tests/vision/vision-anthropic-instance-sidecar.test.ts -562 tests/vision/vision-anthropic.test.ts -1039 tests/vision/vision-backend-union.test.ts -190 tests/vision/vision-cache.test.ts -160 tests/vision/vision-custom-row-precedence.test.ts +1998 tests/vision/sidecar-settings-vision-controls.test.ts +1317 tests/vision/sidecar-settings-vision-filter.test.ts +2089 tests/vision/sidecar-settings-web-search-gate.test.ts +1207 tests/vision/sidecar-settings-web-search-off.test.ts +1364 tests/vision/sidecar-settings-web-search-stream.test.ts +80 tests/vision/sidecar-tracker.test.ts +7708 tests/vision/vision-anthropic-instance-sidecar.test.ts +839 tests/vision/vision-anthropic.test.ts +778 tests/vision/vision-backend-union.test.ts +223 tests/vision/vision-cache.test.ts +158 tests/vision/vision-custom-row-precedence.test.ts 162 tests/vision/vision-eligibility.test.ts -151 tests/vision/vision-fail-closed.test.ts -1812 tests/vision/vision-reasoning-contract.test.ts -4097 tests/vision/vision-routed.test.ts -22430 tests/vision/vision-sidecar-e2e.test.ts -120 tests/vision/vision-text-only-predicate.test.ts -279 tests/web-search/devin-web-search.test.ts -230 tests/web-search/fix-search-frame-shapes.test.ts -72 tests/web-search/fix-search-orphan-source.test.ts -69 tests/web-search/fix-search-unicode-clamp.test.ts -95 tests/web-search/format-result.test.ts -5351 tests/web-search/web-search-anthropic-instance.test.ts +157 tests/vision/vision-fail-closed.test.ts +1039 tests/vision/vision-reasoning-contract.test.ts +4152 tests/vision/vision-routed.test.ts +25907 tests/vision/vision-sidecar-e2e.test.ts +234 tests/vision/vision-text-only-predicate.test.ts +317 tests/web-search/devin-web-search.test.ts +48 tests/web-search/fix-search-frame-shapes.test.ts +96 tests/web-search/fix-search-orphan-source.test.ts +63 tests/web-search/fix-search-unicode-clamp.test.ts +64 tests/web-search/format-result.test.ts +3022 tests/web-search/web-search-anthropic-instance.test.ts 391 tests/web-search/web-search-anthropic.test.ts -1313 tests/web-search/web-search-backend-union.test.ts -119 tests/web-search/web-search-bridge-replay.test.ts -317 tests/web-search/web-search-candidates.test.ts -183 tests/web-search/web-search-forced-declaration.test.ts -127 tests/web-search/web-search-loop-error-usage.test.ts -167 tests/web-search/web-search-loop-iteration-usage.test.ts -221 tests/web-search/web-search-pacing-deadline.test.ts -262 tests/web-search/web-search-parse.test.ts -2681 tests/web-search/web-search-passthrough-bridge.test.ts -3148 tests/web-search/web-search-progress-stream.test.ts -320 tests/web-search/web-search-recovery-kind.test.ts -1696 tests/web-search/web-search-retry-heartbeat.test.ts -1328 tests/web-search/web-search-rotation-usage-attribution.test.ts -184 tests/web-search/web-search-run-turn-loop.test.ts -7720 tests/web-search/web-search-sidecar-429.test.ts -452 tests/web-search/web-search-sidecar-replay.test.ts -64 tests/web-search/web-search-sources.test.ts +1540 tests/web-search/web-search-backend-union.test.ts +159 tests/web-search/web-search-bridge-replay.test.ts +113 tests/web-search/web-search-candidates.test.ts +80 tests/web-search/web-search-eof.test.ts +191 tests/web-search/web-search-forced-declaration.test.ts +206 tests/web-search/web-search-loop-error-usage.test.ts +481 tests/web-search/web-search-loop-iteration-usage.test.ts +487 tests/web-search/web-search-pacing-deadline.test.ts +193 tests/web-search/web-search-parse.test.ts +5024 tests/web-search/web-search-passthrough-bridge.test.ts +2795 tests/web-search/web-search-progress-stream.test.ts +205 tests/web-search/web-search-recovery-kind.test.ts +1612 tests/web-search/web-search-retry-heartbeat.test.ts +711 tests/web-search/web-search-rotation-usage-attribution.test.ts +113 tests/web-search/web-search-run-turn-loop.test.ts +7305 tests/web-search/web-search-sidecar-429.test.ts +618 tests/web-search/web-search-sidecar-replay.test.ts +147 tests/web-search/web-search-sources.test.ts 181 tests/web-search/web-search-terminal-refusal.test.ts -683 tests/web-search/web-search-timeout-contract.test.ts -126 tests/web-search/web-search-timeout-plan.test.ts -5635 tests/web-search/web-search.test.ts -1450 tests/windows/coding-agent-native-empty-argv.test.ts -222 tests/windows/tray-proxy-deadline.test.ts -2349 tests/windows/tray-proxy.test.ts -112 tests/windows/win-exec.test.ts -78 tests/windows/win-paths.test.ts -623 tests/windows/windows-acl-start-cost.test.ts -150 tests/windows/windows-atomic-replace.test.ts -79795 tests/windows/windows-codex-cli-job-store.test.ts +1004 tests/web-search/web-search-timeout-contract.test.ts +175 tests/web-search/web-search-timeout-plan.test.ts +5824 tests/web-search/web-search.test.ts +1611 tests/windows/coding-agent-native-empty-argv.test.ts +79 tests/windows/tray-proxy-deadline.test.ts +2363 tests/windows/tray-proxy.test.ts +81 tests/windows/win-exec.test.ts +133 tests/windows/win-paths.test.ts +111 tests/windows/windows-acl-start-cost.test.ts +81 tests/windows/windows-atomic-replace.test.ts +381 tests/windows/windows-atomic-write-acl-rearm.test.ts +90603 tests/windows/windows-codex-cli-job-store.test.ts 130 tests/windows/windows-config-read-acl-memo.test.ts -16806 tests/windows/windows-config-root-async-writers.test.ts -80 tests/windows/windows-deploy-close-regressions.test.ts -4914 tests/windows/windows-elevation-spawn.test.ts -71 tests/windows/windows-elevation.test.ts -74 tests/windows/windows-guarded-manager.test.ts -78 tests/windows/windows-lifecycle-root-acl.test.ts -582 tests/windows/windows-native-principal.test.ts +13597 tests/windows/windows-config-root-async-writers.test.ts +225 tests/windows/windows-deploy-close-regressions.test.ts +2700 tests/windows/windows-elevation-spawn.test.ts +94 tests/windows/windows-elevation.test.ts +116 tests/windows/windows-guarded-manager.test.ts +158 tests/windows/windows-lifecycle-root-acl.test.ts +479 tests/windows/windows-native-principal.test.ts 724 tests/windows/windows-popup-fix.test.ts -87 tests/windows/windows-process-priority.test.ts -245 tests/windows/windows-scheduler-errors.test.ts -271 tests/windows/windows-scheduler-install-verification.test.ts -177 tests/windows/windows-secret-acl-diagnostics.test.ts -313 tests/windows/windows-secret-acl-removal-flight.test.ts -2928 tests/windows/windows-secret-acl.test.ts -200 tests/windows/windows-service-mutation-lock.test.ts -1777 tests/windows/windows-service-wrappers.test.ts +142 tests/windows/windows-process-priority.test.ts +81 tests/windows/windows-scheduler-errors.test.ts +184 tests/windows/windows-scheduler-install-verification.test.ts +111 tests/windows/windows-secret-acl-diagnostics.test.ts +322 tests/windows/windows-secret-acl-removal-flight.test.ts +2314 tests/windows/windows-secret-acl.test.ts +110 tests/windows/windows-service-mutation-lock.test.ts +1567 tests/windows/windows-service-wrappers.test.ts 71 tests/windows/windows-text-decoding.test.ts -71 tests/windows/windows-tray-restart-hardening.test.ts -151 tests/windows/windows-tray-run-limit.test.ts -12885 tests/windows/windows-tray.test.ts -66 tests/windows/windows-user-principal-nonascii.test.ts -127 tests/windows/windows-user-principal.test.ts -131 tests/windows/winsw-stop-hardening.test.ts +79 tests/windows/windows-tray-restart-hardening.test.ts +62 tests/windows/windows-tray-run-limit.test.ts +13171 tests/windows/windows-tray.test.ts +79 tests/windows/windows-user-principal-nonascii.test.ts +80 tests/windows/windows-user-principal.test.ts +47 tests/windows/winsw-stop-hardening.test.ts diff --git a/scripts/test-layout/layout-file-identity.json b/scripts/test-layout/layout-file-identity.json index e9595bddef2..01a46916a9e 100644 --- a/scripts/test-layout/layout-file-identity.json +++ b/scripts/test-layout/layout-file-identity.json @@ -1,4 +1,5 @@ { "file-identity.test.ts": "lib", - "file-identity-callers.test.ts": "lib" + "file-identity-callers.test.ts": "lib", + "private-sqlite-path.test.ts": "lib" } diff --git a/src/codex/routing/thread-affinity-store.ts b/src/codex/routing/thread-affinity-store.ts index 5fcf67f2292..3458c7abec5 100644 --- a/src/codex/routing/thread-affinity-store.ts +++ b/src/codex/routing/thread-affinity-store.ts @@ -2,16 +2,15 @@ import { Database } from "bun:sqlite"; import { createHash, createHmac, randomBytes } from "node:crypto"; import { chmodSync, - closeSync, lstatSync, - openSync, realpathSync, - type Stats, } from "node:fs"; import { resolve } from "node:path"; import { getConfigDir } from "../../config/paths"; import { initializeConfigOwnership, recordOwnedConfigPath } from "../../lib/config-ownership"; +import { sameFileIdentity, type FileIdentity } from "../../lib/file-identity"; import { isPassiveRead } from "../../lib/passive-read"; +import { assertPrivateSqliteEntryOrMissing, assertPrivateSqliteSidecars, preparePrivateSqliteDatabase } from "../../lib/private-sqlite-path"; import { assertStorageOwned, currentSpendLedgerOwnerGeneration, @@ -67,6 +66,8 @@ type Scope = { generation: number; token: SpendLedgerStorage; db?: Database; + /** The database file the handle was opened on; every write transaction re-checks the path against it. */ + file?: FileIdentity; secret?: Uint8Array; disabled: boolean; poisoned: boolean; @@ -135,13 +136,15 @@ function retire(): void { warning(); } } -function checkFile(path: string): Stats { - const stat = lstatSync(path); +// BigInt stats: NTFS file IDs exceed Number.MAX_SAFE_INTEGER, and a rounded identity can match a +// different file. +function checkFile(path: string) { + const stat = lstatSync(path, { bigint: true }); if ( !stat.isFile() || stat.isSymbolicLink() || - stat.nlink !== 1 || - (process.platform !== "win32" && stat.uid !== process.getuid!()) + stat.nlink !== 1n || + (process.platform !== "win32" && stat.uid !== BigInt(process.getuid!())) ) throw new Error("unsafe file"); return stat; @@ -158,19 +161,18 @@ function open(s: Scope): void { for (const suffix of ["", "-journal", "-wal", "-shm"]) if (!recordOwnedConfigPath(s.home, path + suffix) && initializeConfigOwnership(s.home)) throw new Error("ownership"); - try { - closeSync(openSync(path, "wx", 0o600)); - } catch (e) { - if ((e as NodeJS.ErrnoException).code !== "EEXIST") throw e; - } + // Refuses a link or reparse point at the database or a sidecar before anything is created: + // Windows creates a new file through a link at its name. + preparePrivateSqliteDatabase(path); const before = checkFile(path); - if (before.size > 8 * 1024 * 1024) throw new Error("oversized"); + if (before.size > 8n * 1024n * 1024n) throw new Error("oversized"); if (process.platform !== "win32") chmodSync(path, 0o600); if (!hardenSecretPath(path, { required: true }).ok) throw new Error("acl"); checkFile(path); assertStorageOwned(s.token); // SQLite creates sidecars in the private, hardened config directory, as with // spend-ledger-owner.sqlite and config-mutation.sqlite. + assertPrivateSqliteSidecars(path); db = new Database(path); db.exec("PRAGMA busy_timeout = 0; BEGIN IMMEDIATE"); const version = ( @@ -254,8 +256,9 @@ function open(s: Scope): void { ).value; db.exec("COMMIT"); const after = checkFile(path); - if (before.dev !== after.dev || before.ino !== after.ino) throw new Error("replaced"); + if (!sameFileIdentity(before, after)) throw new Error("replaced"); s.db = db; + s.file = after; s.secret = secret; s.pruneTimer = setInterval(() => { if (current === s) { @@ -279,6 +282,18 @@ function open(s: Scope): void { warning(); } } +/** + * Refuse a write unless the database is still the single-link private file this handle opened and + * no sidecar name holds a link: the rollback journal is created per transaction, and a link added + * to the database since open would expose every later write. + */ +function assertWritable(s: Scope): void { + const path = spendLedgerStoragePath(s.token); + assertPrivateSqliteSidecars(path); + if (!assertPrivateSqliteEntryOrMissing(path)) throw new Error("missing"); + const now = checkFile(path); + if (!s.file || !sameFileIdentity(now, s.file)) throw new Error("replaced"); +} function resolvedHome(acquiredHome?: string): string { let home = resolve(acquiredHome ?? getConfigDir()); try { @@ -473,6 +488,7 @@ function pruneOnly(s: Scope): boolean { if (!s.db || s.disabled) return false; try { assertStorageOwned(s.token); + assertWritable(s); s.db.exec("BEGIN IMMEDIATE"); // Pending touches first, so a pin used since its last persisted timestamp is not evicted as idle. if (!s.poisoned) applyTouches(s, s.db); @@ -517,6 +533,7 @@ function flush(s: Scope, clean: boolean): boolean { const db = s.db; for (let attempt = 0; attempt < 2; attempt++) try { assertStorageOwned(s.token); + assertWritable(s); db.exec("BEGIN IMMEDIATE"); // Touches go before the log as well as after it, so the pruning between chunks sees the live // last-used times and cannot evict a pin that is in use but persisted with an old timestamp. diff --git a/src/lib/private-sqlite-path.ts b/src/lib/private-sqlite-path.ts new file mode 100644 index 00000000000..8cf616db6db --- /dev/null +++ b/src/lib/private-sqlite-path.ts @@ -0,0 +1,124 @@ +import { closeSync, lstatSync, openSync } from "node:fs"; + +/** The files SQLite opens next to a database: the rollback journal, and the WAL and its index. */ +export const SQLITE_SIDECAR_SUFFIXES = ["-journal", "-wal", "-shm"] as const; + +/** A database or sidecar name holds something other than a private regular file. Carries no path. */ +export class UnsafeSqlitePathError extends Error { + constructor() { + super("SQLite storage path is not a private regular file"); + this.name = "UnsafeSqlitePathError"; + } +} + +const FILE_ATTRIBUTE_REPARSE_POINT = 0x400; +const INVALID_FILE_ATTRIBUTES = 0xffffffff; +type ReparseProbe = (path: string) => boolean; +let nativeAttributes: ((path: string) => number) | undefined; +let probeForTests: ReparseProbe | null = null; +/** + * Whether the native attribute query runs: on Windows, except ARM64, whose Bun build cannot execute + * `bun:ffi` (the limitation src/lib/windows-user-principal.ts works around). There `lstat` still + * reports symbolic links, junctions and app execution aliases as links; other reparse tags are not + * visible without native code. + */ +export function nativeReparseProbeApplies(platform: string, arch: string): boolean { + return platform === "win32" && arch !== "arm64"; +} +// Read once at load: tests replace `process.platform` to drive Windows-only branches on POSIX, and +// the native query must follow the system the process actually runs on. +const NATIVE_ATTRIBUTES = nativeReparseProbeApplies(process.platform, process.arch); + +function errorCode(error: unknown): unknown { + return error !== null && typeof error === "object" && "code" in error ? error.code : undefined; +} + +/** + * Whether the entry at `path` itself is a Windows reparse point: a symbolic link, a junction, or any + * other tag. `GetFileAttributesW` reports the named entry rather than what it points to, so this + * sees what `lstat` cannot classify. Throws when the attribute cannot be read. + */ +export function isWindowsReparsePoint(path: string): boolean { + if (!nativeAttributes) { + // Loaded on first use, only on Windows; the repository's other Windows file checks use the same call. + const ffi = require("bun:ffi") as typeof import("bun:ffi"); + const kernel = ffi.dlopen("kernel32.dll", { + GetFileAttributesW: { args: [ffi.FFIType.ptr], returns: ffi.FFIType.u32 }, + }); + nativeAttributes = (name: string) => { + const wide = Buffer.from(`${name}\0`, "utf16le"); + return kernel.symbols.GetFileAttributesW(ffi.ptr(wide)) >>> 0; + }; + } + const attributes = nativeAttributes(path); + if (attributes === INVALID_FILE_ATTRIBUTES) throw new Error("file attributes unavailable"); + return (attributes & FILE_ATTRIBUTE_REPARSE_POINT) !== 0; +} + +/** Test seam: replace the reparse-point probe on every platform; null restores the default. */ +export function setSqlitePathReparseProbeForTests(probe: ReparseProbe | null): void { + probeForTests = probe; +} + +function isReparsePoint(path: string): boolean { + if (probeForTests) return probeForTests(path); + return NATIVE_ATTRIBUTES && isWindowsReparsePoint(path); +} + +/** + * Refuse unless nothing is at `path` or it is a private regular file: not a link or other reparse + * point, not a directory, a single directory entry, and on POSIX owned by this user. Returns + * whether an entry exists. A probe that cannot answer refuses. + */ +export function assertPrivateSqliteEntryOrMissing(path: string): boolean { + let stat; + try { + stat = lstatSync(path); + } catch (error) { + if (errorCode(error) === "ENOENT") return false; + throw error; + } + let reparse: boolean; + try { + reparse = isReparsePoint(path); + } catch { + throw new UnsafeSqlitePathError(); + } + if ( + reparse + || !stat.isFile() + || stat.isSymbolicLink() + || stat.nlink !== 1 + || (process.platform !== "win32" && stat.uid !== process.getuid!()) + ) throw new UnsafeSqlitePathError(); + return true; +} + +/** + * Refuse unless every sidecar of `databasePath` is absent or a private regular file. SQLite's POSIX + * VFS opens them with O_NOFOLLOW; its Windows VFS opens them by name with CreateFileW, which follows + * a link planted there. Check before opening the database and before every write transaction: the + * rollback journal is created and deleted per transaction. Something planted after the check, while + * SQLite opens the file, is outside what this can see. + */ +export function assertPrivateSqliteSidecars(databasePath: string): void { + for (const suffix of SQLITE_SIDECAR_SUFFIXES) assertPrivateSqliteEntryOrMissing(databasePath + suffix); +} + +/** + * Make sure `databasePath` is a private regular file without creating anything through a link at + * its name or at a sidecar's. POSIX O_CREAT|O_EXCL refuses a link at the final component, but + * Windows CREATE_NEW follows a dangling file symlink and creates its target, so every entry is + * checked before the create. An entry planted between the check and the create is not covered; + * callers check the file again after hardening it. + */ +export function preparePrivateSqliteDatabase(databasePath: string): void { + assertPrivateSqliteSidecars(databasePath); + if (assertPrivateSqliteEntryOrMissing(databasePath)) return; + try { + closeSync(openSync(databasePath, "wx", 0o600)); + } catch (error) { + if (errorCode(error) !== "EEXIST") throw error; + } + if (!assertPrivateSqliteEntryOrMissing(databasePath)) throw new UnsafeSqlitePathError(); +} diff --git a/src/lib/spend-ledger-owner.ts b/src/lib/spend-ledger-owner.ts index 46833f4de63..2799c748ed2 100644 --- a/src/lib/spend-ledger-owner.ts +++ b/src/lib/spend-ledger-owner.ts @@ -1,9 +1,10 @@ /** Process-lifetime single-writer ownership for the shared spend journal. */ import { Database } from "bun:sqlite"; -import { chmodSync, closeSync, lstatSync, mkdirSync, openSync, realpathSync } from "node:fs"; +import { chmodSync, lstatSync, mkdirSync, realpathSync } from "node:fs"; import { join, resolve } from "node:path"; import { getConfigDir } from "../config/paths"; import { recordOwnedConfigPath } from "./config-ownership"; +import { assertPrivateSqliteSidecars, preparePrivateSqliteDatabase } from "./private-sqlite-path"; import { assertNotRealHomeUnderTest } from "./test-home-guard"; import { hardenSecretDir, hardenSecretPath } from "./windows-secret-acl"; @@ -115,8 +116,9 @@ function prepareOwnerPath(configDir: string): { home: string; path: string } { // its sidecars were left behind by a later uninstall because nothing recorded them. recordOwnedConfigPath(home, path); for (const suffix of OWNER_SIDECARS) recordOwnedConfigPath(home, `${path}${suffix}`); - try { closeSync(openSync(path, "wx", 0o600)); } - catch (error) { if (errorCode(error) !== "EEXIST") throw error; } + // Refuses a link or reparse point at the database or a sidecar before anything is created: + // Windows creates a new file through a link at its name. + preparePrivateSqliteDatabase(path); assertPrivateFile(path); if (process.platform !== "win32") chmodSync(path, 0o600); hardenSecretPath(path, { required: true }); @@ -196,6 +198,7 @@ export function acquireSpendLedgerOwner(configDir = getConfigDir()): SpendLedger let database: Database | undefined; try { + assertPrivateSqliteSidecars(prepared.path); database = new Database(prepared.path, { create: true }); database.exec(`PRAGMA locking_mode = NORMAL; PRAGMA busy_timeout = ${busyTimeout}; BEGIN IMMEDIATE`); } catch (cause) { diff --git a/structure/providers/codex-pool-affinity.md b/structure/providers/codex-pool-affinity.md index 756d667e472..81e49fb9ecf 100644 --- a/structure/providers/codex-pool-affinity.md +++ b/structure/providers/codex-pool-affinity.md @@ -7,7 +7,7 @@ the single-writer lease is owned by [Responses spend](../transports/responses-sp `src/codex/routing/thread-affinity-store.ts` restores eligible pool bindings after a graceful proxy restart for up to 24 hours idle. Session-bearing requests and session-less requests anchored on their immediate parent have derivable anchors. Deeper session-less chains, keys derived under another config home, legacy raw-parent keys and evicted anchors remain memory-only. Removed, re-logged, expired or identity-less accounts are not restored; normal selection and usability rules still apply. -The config home contains `codex-affinity.sqlite`, mode 0600 with a hardened Windows ACL. Its v1 schema has `meta` (store secret and clean flag), `threads` (scoped bindings), and `issuers` (conversation state issuers). Row keys are domain-separated HMACs of the cohort anchor under the store's own secret. Each row stores the local pool account id (the label that config.json and the credential store in this directory already key the account by, as the Claude affinity store does), an identity fence digest and timestamps. Session ids, conversation keys (raw or process-local), emails, ChatGPT account ids and tokens are not stored; a keyed digest of the pool id would hide nothing from a reader of this directory, which holds both the store secret and the account list. The identity fence derives from `quotaHistoryIdentity`, captured at bind and at issuance. Issuance requires both generation and `chatgptAccountId` to match the current record. `__main__` pins and issuers are never persisted. Request-owned keys (`isRequestOwnedAffinityKey`, from `src/codex/request-owned-affinity-key.ts`) are refused at the store's row-key derivation and anchor observer, so they are never anchored, written or restored, as the [request-owned persistence contract](codex-request-owned-affinity.md#persistence-contract) requires. An unknown restored issuer scrubs continuation state; uploaded files are refused when the stored account differs from the serving account, as for known account changes and prior-account moves. +The config home contains `codex-affinity.sqlite`, mode 0600 with a hardened Windows ACL. Before the store creates or opens the database, `src/lib/private-sqlite-path.ts` requires the database and its `-journal`, `-wal` and `-shm` names to be absent or private regular files: a symbolic link, junction or other Windows reparse point, directory, hard link or (on POSIX) foreign-owned file disables persistence without creating or writing what it names. On Windows ARM64, whose Bun build cannot run the native attribute query, only the symbolic links, junctions and app execution aliases that `lstat` reports as links are seen. On Windows ownership is not compared; the boundary there is the hardened ACL of the config directory and file. Before every write transaction the store checks the sidecar names again and that the database path is still the single-link file it opened; a refusal there is a failed flush: three in a row poison the store, and when the store is poisoned or its final flush is refused the clean flag stays unset, so the next owner discards rows. The check comes before the create because Windows creates a new file through a link at its name, and SQLite opens Windows sidecars by name; an entry planted between the check and SQLite's own open is outside this guarantee. `tests/codex-integration/codex-affinity-restart-matrix.test.ts` (which emulates the Windows create-through-link behaviour on other platforms) and `tests/lib/private-sqlite-path.test.ts` cover it. Its v1 schema has `meta` (store secret and clean flag), `threads` (scoped bindings), and `issuers` (conversation state issuers). Row keys are domain-separated HMACs of the cohort anchor under the store's own secret. Each row stores the local pool account id (the label that config.json and the credential store in this directory already key the account by, as the Claude affinity store does), an identity fence digest and timestamps. Session ids, conversation keys (raw or process-local), emails, ChatGPT account ids and tokens are not stored; a keyed digest of the pool id would hide nothing from a reader of this directory, which holds both the store secret and the account list. The identity fence derives from `quotaHistoryIdentity`, captured at bind and at issuance. Issuance requires both generation and `chatgptAccountId` to match the current record. `__main__` pins and issuers are never persisted. Request-owned keys (`isRequestOwnedAffinityKey`, from `src/codex/request-owned-affinity-key.ts`) are refused at the store's row-key derivation and anchor observer, so they are never anchored, written or restored, as the [request-owned persistence contract](codex-request-owned-affinity.md#persistence-contract) requires. An unknown restored issuer scrubs continuation state; uploaded files are refused when the stored account differs from the serving account, as for known account changes and prior-account moves. The spend-ledger lease is the single-writer authority. The final releasing hook flushes pending work and marks the store clean before ownership is released; it does so even when the release happens inside a passive read, because it commits only work recorded outside one. A crash, failed final flush or poisoned store leaves the clean flag unset, so the next owner discards rows. Structural changes use an ordered write log; UPDATE-only touches read live timestamps at flush, avoiding stale timestamps and resurrection. The 24-hour idle limit bounds reuse. Expired rows are removed by the next prune that commits: one is attempted when the store opens at lease acquisition, on an hourly timer while it stays open, and after every failed flush, including in a poisoned store. A prune can still be delayed or fail: a lease acquired inside a passive read does not open the store, a store that failed to open is disabled and cannot prune, a prune transaction can roll back, and timers can run late. SQLite secure_delete overwrites freed pages in the database file, but not filesystem snapshots, backups or storage remapping; its transient rollback journal is removed after each commit. The store secret pseudonymizes row keys and does not protect integrity from a local process that can already read the config directory. Pruning also removes future-dated rows and bounds each table to 2,048 entries, evicting model detours first. Other passive reads do not open, adopt or mutate the store. Live affinity survives a lease change in one process. A persistable change to pins or issuers made while the home's database is not writable (between two leases of one process, or while a scope could not open it) marks that database stale; the next scope that opens it clears it before use, so a restart restores nothing rather than a row the process had replaced or deleted. This also drops rows for conversations the process never loaded, which loses pins but never revives one; a serving proxy holds one lease for its whole life and does not reach this path. Row keys and anchors carry across a lease change in the same home, including past a scope that failed to open, so deletes still find their rows after an anchor is evicted. A change made after the final release, before the process exits without taking the lease again, cannot be saved: the lease is gone and another process may already own the database, so the next process can restore the row that change replaced. Such a row still has to pass the identity fence and the resolver's usability checks, and a serving proxy releases its lease only after its listeners have stopped. A manual account switch deletes saved pins and keeps saved issuers, matching the live maps; a full reset deletes both. diff --git a/structure/transports/responses-spend.md b/structure/transports/responses-spend.md index 1cc505212a6..baac45e580e 100644 --- a/structure/transports/responses-spend.md +++ b/structure/transports/responses-spend.md @@ -381,7 +381,11 @@ proves that exact identity on every accounting read and change, so a handle kept and a reacquire of the same directory is refused rather than resuming over writes another owner may have made. File-backed journal and salt writers are owner-bound at construction, and a directory entry that is a link -- including one whose target does not exist -- is refused instead -of followed. A separate process may use a separate directory. SQLite crash release permits the +of followed. The owner database `spend-ledger-owner.sqlite` and its SQLite sidecars pass the same +`src/lib/private-sqlite-path.ts` check before the file is created and before SQLite opens it: a link, any +Windows reparse point, a directory or a hard link there fails acquisition with +`SPEND_LEDGER_OWNER_UNAVAILABLE` without creating what it names. On Windows ARM64, whose Bun build +cannot run the native attribute query, only the links and junctions `lstat` reports are refused. A separate process may use a separate directory. SQLite crash release permits the next owner without stale-PID or TTL reclamation. Every file check admits a ledger file only when it is a regular file, not a link, with exactly diff --git a/tests/codex-integration/codex-affinity-restart-matrix.test.ts b/tests/codex-integration/codex-affinity-restart-matrix.test.ts index 470f0bb221f..d0616802bf4 100644 --- a/tests/codex-integration/codex-affinity-restart-matrix.test.ts +++ b/tests/codex-integration/codex-affinity-restart-matrix.test.ts @@ -1,19 +1,29 @@ -import { expect, test } from "bun:test"; +import { afterAll, expect, test } from "bun:test"; import { Database } from "bun:sqlite"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, symlinkSync, truncateSync, writeFileSync } from "node:fs"; +import { existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, symlinkSync, truncateSync, unlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { initializeConfigOwnership, removeOwnedConfigState } from "../../src/lib/config-ownership"; import { helperPath } from "../helpers/repo-root"; import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { copySeededAffinityHome, removeSeededAffinityTemplates } from "../helpers/codex-affinity-seed"; + +afterAll(removeSeededAffinityTemplates); const names = ["codex-affinity.sqlite", "codex-affinity.sqlite-journal", "codex-affinity.sqlite-wal", "codex-affinity.sqlite-shm"]; +const memoryOnly = "Codex affinity persistence unavailable; continuing in memory."; +// Windows creates a file THROUGH a link at its name; other platforms refuse. Workers that may create +// the store run with that behaviour emulated, so a create-before-check mistake fails everywhere. +const windowsCreate = process.platform === "win32" ? [] : ["--preload", helperPath("windows-link-create-preload.ts")]; +function spawnWorker(home: string, file: string, action: string, preload: string[] = []) { + return Bun.spawnSync([process.execPath, ...preload, helperPath(file), action], { env: { ...process.env, OPENCODEX_HOME: home, CODEX_HOME: home }, stdout: "pipe", stderr: "pipe" }); +} function worker(home: string, file: string, action: string): any { - const result = Bun.spawnSync([process.execPath, helperPath(file), action], { env: { ...process.env, OPENCODEX_HOME: home, CODEX_HOME: home }, stdout: "pipe", stderr: "pipe" }); + const result = spawnWorker(home, file, action); expect(result.exitCode, result.stderr.toString()).toBe(0); return result.stdout.length ? JSON.parse(result.stdout.toString()) : undefined; } -function seed(home: string) { return worker(home, "codex-affinity-restart-worker.ts", "write"); } +function seed(home: string) { return copySeededAffinityHome("write", home); } function matrix(home: string, action: string) { return worker(home, "codex-affinity-matrix-worker.ts", action); } function inHome(fn: (home: string) => void) { const home = mkdtempSync(join(tmpdir(), "ocx-affinity-extra-")); @@ -44,20 +54,94 @@ test("fresh and existing owned homes list and remove all affinity paths", () => for (const name of names) expect(existsSync(join(home, name))).toBe(false); })); -for (const kind of ["symlink", "directory"] as const) { +function probeMemoryOnly(home: string): void { + const result = spawnWorker(home, "codex-affinity-matrix-worker.ts", "probe", windowsCreate); + expect(result.exitCode, result.stderr.toString()).toBe(0); + expect(result.stderr.toString()).toContain(memoryOnly); +} + +for (const kind of ["symlink", "symlink-existing", "hardlink", "junction", "directory"] as const) { test(`${kind} at the database path disables the store`, () => inHome(home => { expect(initializeConfigOwnership(home)).toBe(true); + const file = join(home, names[0]!); const target = join(home, "outside-target"); - if (kind === "symlink") symlinkSync(target, join(home, names[0]!)); - else mkdirSync(join(home, names[0]!)); - matrix(home, "probe"); + if (kind === "symlink") symlinkSync(target, file); + else if (kind === "symlink-existing" || kind === "hardlink") { + writeFileSync(target, "outside"); + if (kind === "hardlink") linkSync(target, file); + else symlinkSync(target, file); + } else if (kind === "junction") { + // A junction on Windows, a directory symlink elsewhere. + mkdirSync(target); + symlinkSync(target, file, "junction"); + } else mkdirSync(file); + probeMemoryOnly(home); + if (kind === "symlink") expect(existsSync(target)).toBe(false); + else if (kind === "junction") expect(readdirSync(target)).toEqual([]); + else if (kind !== "directory") expect(readFileSync(target, "utf8")).toBe("outside"); + })); +} + +for (const name of names.slice(1)) { + test(`a link at ${name} disables the store before anything is created`, () => inHome(home => { + expect(initializeConfigOwnership(home)).toBe(true); + const target = join(home, "outside-target"); + symlinkSync(target, join(home, name)); + probeMemoryOnly(home); expect(existsSync(target)).toBe(false); + expect(existsSync(join(home, names[0]!))).toBe(false); })); } +test("a journal link planted while the store is open is refused before the next write", () => inHome(home => { + seed(home); + const file = join(home, names[0]!); + expect(matrix(home, "late-journal-link")).toEqual({ planted: true }); + expect(existsSync(join(home, "outside-target"))).toBe(false); + // With the link gone, the database itself shows the release never committed clean, so the next + // owner discards the rows rather than restoring a pin the refused write could not record. + unlinkSync(`${file}-journal`); + const db = new Database(file, { readonly: true }); + expect(db.query("SELECT value FROM meta WHERE name='clean'").get()).toEqual({ value: 0 }); + db.close(); + expect(matrix(home, "read").before).toBeUndefined(); +})); + +test("a hard link added to the open database stops every later write", () => inHome(home => { + seed(home); + const file = join(home, names[0]!); + expect(matrix(home, "late-hard-link")).toEqual({ planted: true }); + const db = new Database(file, { readonly: true }); + // Neither the bind to b nor the clean release reached the twice-linked file. + expect(db.query("SELECT DISTINCT account_id FROM threads").all()).toEqual([{ account_id: "a" }]); + expect(db.query("SELECT value FROM meta WHERE name='clean'").get()).toEqual({ value: 0 }); + db.close(); +})); + +test("a hot rollback journal from an interrupted writer is recovered, not refused", () => inHome(home => { + seed(home); + const file = join(home, names[0]!); + // A one-page cache makes the open transaction spill into the database file, so the killed writer + // leaves a hot journal that SQLite must roll back on the next open. + const writer = Bun.spawnSync([process.execPath, "-e", [ + "const { Database } = require('bun:sqlite');", + "const db = new Database(process.argv[1]);", + "db.exec('PRAGMA cache_size=1; BEGIN');", + "const insert = db.query(\"INSERT INTO issuers VALUES (?, 'b', 'fence', 0)\");", + "for (let i = 0; i < 4000; i++) insert.run('interrupted-' + i);", + "process.kill(process.pid, 'SIGKILL');", + ].join(" "), file], { stdout: "pipe", stderr: "pipe" }); + expect(writer.exitCode).not.toBe(0); + expect(lstatSync(`${file}-journal`).isFile()).toBe(true); + expect(matrix(home, "read").before).toBe("a"); + const db = new Database(file, { readonly: true }); + expect(db.query("SELECT count(*) AS n FROM issuers WHERE row_key LIKE 'interrupted-%'").get()).toEqual({ n: 0 }); + db.close(); +})); + test("a home without an ownership manifest still persists affinity and gains no manifest", () => inHome(home => { writeFileSync(join(home, "unowned"), "keep"); - expect(seed(home).account).toBe("a"); + expect(worker(home, "codex-affinity-restart-worker.ts", "write").account).toBe("a"); expect(existsSync(join(home, names[0]!))).toBe(true); expect(worker(home, "codex-affinity-restart-worker.ts", "read").account).toBe("a"); expect(existsSync(join(home, ".opencodex-uninstall.json"))).toBe(false); @@ -167,12 +251,16 @@ test("restoration accepts a 512-byte model component and rejects 513 bytes", () })); test("home switching drops pending writes and does not carry recorded anchors across homes", () => inHome(homeA => inHome(homeB => { - seed(homeA); seed(homeB); + worker(homeA, "codex-affinity-restart-worker.ts", "write"); + worker(homeB, "codex-affinity-restart-worker.ts", "write"); + const secrets: unknown[] = []; for (const home of [homeA, homeB]) { const db = new Database(join(home, names[0]!)); + secrets.push((db.query("SELECT value FROM meta WHERE name='secret'").get() as { value: unknown }).value); db.exec("DELETE FROM threads; DELETE FROM issuers"); db.close(); } + expect(secrets[0]).not.toEqual(secrets[1]); const result = Bun.spawnSync([process.execPath, helperPath("codex-affinity-home-switch-worker.ts"), homeB], { env: { ...process.env, OPENCODEX_HOME: homeA, CODEX_HOME: homeA }, stdout: "pipe", stderr: "pipe", }); @@ -200,7 +288,8 @@ for (const mutation of ["bind", "delete", "issuer"] as const) { for (const path of ["responses", "compact"] as const) { for (const issuer of ["unknown", "known"] as const) { test(`${path} handler ${issuer} restored issuer with an uploaded file`, () => inHome(home => { - worker(home, "codex-affinity-restart-worker.ts", issuer === "unknown" ? "unknown-write" : "write"); + if (path === "responses" && issuer === "unknown") worker(home, "codex-affinity-restart-worker.ts", "unknown-write"); + else copySeededAffinityHome(issuer === "unknown" ? "unknown-write" : "write", home); const result = worker(home, "codex-affinity-handler-worker.ts", path); expect(result.status).toBe(400); expect(result.bodies).toHaveLength(0); @@ -210,7 +299,7 @@ for (const path of ["responses", "compact"] as const) { for (const path of ["responses", "compact"] as const) { test(`${path} permits a file for the same stored account with unknown issuer`, () => inHome(home => { - worker(home, "codex-affinity-restart-worker.ts", "unknown-write"); + copySeededAffinityHome("unknown-write", home); const result = Bun.spawnSync([process.execPath, helperPath("codex-affinity-handler-worker.ts"), path, "same"], { env: { ...process.env, OPENCODEX_HOME: home, CODEX_HOME: home }, stdout: "pipe", stderr: "pipe" }); expect(result.exitCode, result.stderr.toString()).toBe(0); const parsed = JSON.parse(result.stdout.toString()); diff --git a/tests/codex-integration/codex-affinity-restart.test.ts b/tests/codex-integration/codex-affinity-restart.test.ts index babd27cac24..2b44019489e 100644 --- a/tests/codex-integration/codex-affinity-restart.test.ts +++ b/tests/codex-integration/codex-affinity-restart.test.ts @@ -1,10 +1,14 @@ -import { expect, test } from "bun:test"; -import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { afterAll, expect, test } from "bun:test"; +import { mkdtempSync, readFileSync, realpathSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { removeTreeWithRetry } from "../helpers/remove-tree"; import { helperPath } from "../helpers/repo-root"; import { Database } from "bun:sqlite"; +import { removeOwnedConfigState } from "../../src/lib/config-ownership"; +import { copySeededAffinityHome, removeSeededAffinityTemplates } from "../helpers/codex-affinity-seed"; + +afterAll(removeSeededAffinityTemplates); function run(home: string, mode: string) { const result = Bun.spawnSync([process.execPath, helperPath("codex-affinity-restart-worker.ts"), mode], { @@ -83,13 +87,25 @@ function matrix(home: string, action: string) { function withSeededHome(body: (home: string) => void) { const home = mkdtempSync(join(tmpdir(), "ocx-affinity-matrix-")); try { - const seed = run(home, "write"); - expect(seed.exit, seed.stderr).toBe(0); - expect(JSON.parse(seed.stdout).account).toBe("a"); + expect(copySeededAffinityHome("write", home).account).toBe("a"); body(home); } finally { removeTreeWithRetry(home); } } +test("a copied seed home keeps its ownership and restores like a seeded one", () => { + const homeA = mkdtempSync(join(tmpdir(), "ocx-affinity-copy-")); + const homeB = mkdtempSync(join(tmpdir(), "ocx-affinity-copy-")); + try { + copySeededAffinityHome("write", homeA); + for (const name of [".opencodex-owner.json", ".opencodex-uninstall.json"]) { + expect(JSON.parse(readFileSync(join(homeA, name), "utf8")).root).toBe(realpathSync.native(homeA)); + } + expect(matrix(homeA, "read").before).toBe("a"); + copySeededAffinityHome("write", homeB); + expect(removeOwnedConfigState(homeB).status).toBe("removed"); + } finally { removeTreeWithRetry(homeA); removeTreeWithRetry(homeB); } +}); + for (const action of ["delete", "delete-account", "clear-account", "clear"] as const) { test(`${action} reconciles a restored pin before its first lookup`, () => withSeededHome(home => { const result = matrix(home, action); diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 1611c02a0c1..4e6e5fea080 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1162,7 +1162,7 @@ "policy-execution.test.ts": "routing", "pool-kernel-generic-sweep.test.ts": "oauth", "port-reclaim.test.ts": "server", "ports.test.ts": "server", "pr-readiness-reattest.test.ts": "ci-workflows", "prime-client.test.ts": "clients", - "privacy-mask-account.test.ts": "lib", "privacy-scan-asset-names.test.ts": "ci-workflows", + "private-sqlite-path.test.ts": "lib", "privacy-mask-account.test.ts": "lib", "privacy-scan-asset-names.test.ts": "ci-workflows", "privacy-scan-meta-key.test.ts": "ci-workflows", "privacy-scan-ssh-endpoint.test.ts": "ci-workflows", "probe-lease-dispatch-wiring.test.ts": "routing", "probe-lease.test.ts": "routing", "process-control-graceful.test.ts": "lib", "process-control.test.ts": "lib", diff --git a/tests/helpers/codex-affinity-matrix-worker.ts b/tests/helpers/codex-affinity-matrix-worker.ts index 4870a0ac057..4bc88787240 100644 --- a/tests/helpers/codex-affinity-matrix-worker.ts +++ b/tests/helpers/codex-affinity-matrix-worker.ts @@ -1,12 +1,12 @@ import { Database } from "bun:sqlite"; import { join } from "node:path"; -import { readFileSync } from "node:fs"; +import { linkSync, readFileSync, symlinkSync } from "node:fs"; import { acquireSpendLedgerOwner, assertStorageOwned, mintSpendLedgerStorage } from "../../src/lib/spend-ledger-owner"; import { readCodexAccountRecord, removeCodexAccountCredential, saveCodexAccountCredential, saveCodexAccountCredentialIfGeneration } from "../../src/codex/account-store"; import { codexPoolAffinityKey } from "../../src/codex/auth-context"; import { recordCodexThreadLineage } from "../../src/codex/lineage"; import { runPassiveRead } from "../../src/lib/passive-read"; -import { adoptStoredThreadRows } from "../../src/codex/routing/thread-affinity-store"; +import { adoptStoredThreadRows, flushCodexAffinityStoreForTests } from "../../src/codex/routing/thread-affinity-store"; import { recordCodexUpstreamOutcome, resolveCodexAccountForThread, resolveCodexAccountForThreadDetailed } from "../../src/codex/routing"; import { bindThreadAffinity, clearConversationStateIssuerMap, clearThreadAccountMap, clearThreadAccountMapForAccount, deleteThreadAffinity, deleteThreadAffinitiesForAccount, getThreadAffinity, handOffThreadAffinityGeneration, peekConversationStateIssuer, rememberConversationStateIssuer } from "../../src/codex/routing/thread-affinity"; import type { OcxConfig } from "../../src/types"; @@ -60,6 +60,19 @@ if (action === "probe") { lease.release(); process.exit(0); } +if (action === "late-journal-link" || action === "late-hard-link") { + // The store is open (the lease opened it). A rollback journal exists only during a write, so a + // link planted now is met by the next transaction, which must refuse it rather than follow it. + // A second name for the database itself must stop writes the same way. + const file = join(process.env.OPENCODEX_HOME!, "codex-affinity.sqlite"); + if (action === "late-hard-link") linkSync(file, join(process.env.OPENCODEX_HOME!, "outside-target")); + else symlinkSync(join(process.env.OPENCODEX_HOME!, "outside-target"), `${file}-journal`); + bindThreadAffinity(key, "b", Date.now()); + flushCodexAffinityStoreForTests(); + lease.release(); + console.log(JSON.stringify({ planted: true })); + process.exit(0); +} if (action.startsWith("late-")) { bindThreadAffinity(key, "a", Date.now()); const record = readCodexAccountRecord("a")!; diff --git a/tests/helpers/codex-affinity-seed.ts b/tests/helpers/codex-affinity-seed.ts new file mode 100644 index 00000000000..c12ea202621 --- /dev/null +++ b/tests/helpers/codex-affinity-seed.ts @@ -0,0 +1,52 @@ +import { cpSync, existsSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { helperPath } from "./repo-root"; +import { removeTreeWithRetry } from "./remove-tree"; + +type SeedMode = "write" | "unknown-write"; +type SeedOutput = { account: string; [key: string]: unknown }; +const templates = new Map(); + +/** Seed once per mode, after the worker releases its lease and exits. */ +export function seededAffinityTemplate(mode: SeedMode): string { + const cached = templates.get(mode); + if (cached) return cached.home; + const home = mkdtempSync(join(tmpdir(), "ocx-affinity-template-")); + try { + const result = Bun.spawnSync([process.execPath, helperPath("codex-affinity-restart-worker.ts"), mode], { + env: { ...process.env, OPENCODEX_HOME: home, CODEX_HOME: home }, stdout: "pipe", stderr: "pipe", + }); + if (result.exitCode !== 0) throw new Error(`Affinity seed ${mode} failed: ${result.stderr.toString()}`); + const output = JSON.parse(result.stdout.toString()) as SeedOutput; + if (mode === "write" && output.account !== "a") throw new Error("Affinity seed did not select account a"); + for (const database of ["codex-affinity.sqlite", "spend-ledger-owner.sqlite"]) { + for (const suffix of ["-journal", "-wal", "-shm"]) { + if (existsSync(join(home, database + suffix))) throw new Error(`Affinity seed left ${database + suffix}`); + } + } + templates.set(mode, { home, output }); + return home; + } catch (error) { + removeTreeWithRetry(home); + throw error; + } +} + +/** Ownership loading rejects a copied manifest whose root still names the template home. */ +export function copySeededAffinityHome(mode: SeedMode, destination: string): SeedOutput { + cpSync(seededAffinityTemplate(mode), destination, { recursive: true }); + for (const name of [".opencodex-owner.json", ".opencodex-uninstall.json"]) { + const path = join(destination, name); + if (!existsSync(path)) continue; + const manifest = JSON.parse(readFileSync(path, "utf8")); + manifest.root = realpathSync.native(destination); + writeFileSync(path, `${JSON.stringify(manifest, null, 2)}\n`); + } + return templates.get(mode)!.output; +} + +export function removeSeededAffinityTemplates(): void { + for (const { home } of templates.values()) removeTreeWithRetry(home); + templates.clear(); +} diff --git a/tests/helpers/spend-ledger-owner-link-worker.ts b/tests/helpers/spend-ledger-owner-link-worker.ts new file mode 100644 index 00000000000..3aae03656a6 --- /dev/null +++ b/tests/helpers/spend-ledger-owner-link-worker.ts @@ -0,0 +1,10 @@ +import { acquireSpendLedgerOwner, SpendLedgerOwnerError } from "../../src/lib/spend-ledger-owner"; + +// Acquire the owner for argv[2] in a fresh process, so a --preload can change how files are created +// before the owner module binds its imports. Prints the outcome code. +try { + acquireSpendLedgerOwner(process.argv[2]!).release(); + console.log(JSON.stringify({ code: "acquired" })); +} catch (error) { + console.log(JSON.stringify({ code: error instanceof SpendLedgerOwnerError ? error.code : "other" })); +} diff --git a/tests/helpers/windows-link-create-emulation.ts b/tests/helpers/windows-link-create-emulation.ts new file mode 100644 index 00000000000..98d4f991f7b --- /dev/null +++ b/tests/helpers/windows-link-create-emulation.ts @@ -0,0 +1,31 @@ +import { dirname, resolve } from "node:path"; + +/** + * Make POSIX create files the way Windows does when the name is a symbolic link. + * + * Windows CreateFile/NtCreateFile with CREATE_NEW reparses a symbolic link at the final component + * and creates the link's target; POSIX O_CREAT|O_EXCL refuses the link instead. Code that creates + * a file and only afterwards checks for a link therefore passes on macOS and Linux and writes + * outside its directory on Windows. With this installed, an exclusive create through a link opens + * the resolved target, so the same mistake fails on every platform. + * + * Bun binds `import { openSync } from "node:fs"` when the importing module loads, so this must run + * before the code under test is imported: use it from a `--preload` script. + */ +export function installWindowsLinkCreateEmulation(): () => void { + const fs = require("node:fs") as typeof import("node:fs"); + const original = fs.openSync; + const { O_CREAT, O_EXCL } = fs.constants; + const exclusive = (flags: unknown): boolean => + typeof flags === "string" ? flags.includes("x") + : typeof flags === "number" && (flags & O_CREAT) !== 0 && (flags & O_EXCL) !== 0; + fs.openSync = ((path: unknown, flags?: unknown, mode?: unknown) => { + if (typeof path === "string" && exclusive(flags)) { + let link: string | undefined; + try { if (fs.lstatSync(path).isSymbolicLink()) link = fs.readlinkSync(path); } catch { /* absent */ } + if (link !== undefined) return (original as Function)(resolve(dirname(path), link), flags, mode); + } + return (original as Function)(path, flags, mode); + }) as typeof fs.openSync; + return () => { fs.openSync = original; }; +} diff --git a/tests/helpers/windows-link-create-preload.ts b/tests/helpers/windows-link-create-preload.ts new file mode 100644 index 00000000000..242c32ebad1 --- /dev/null +++ b/tests/helpers/windows-link-create-preload.ts @@ -0,0 +1,4 @@ +import { installWindowsLinkCreateEmulation } from "./windows-link-create-emulation"; + +// Preload for test workers: on Windows the platform already behaves this way. +if (process.platform !== "win32") installWindowsLinkCreateEmulation(); diff --git a/tests/lib/private-sqlite-path.test.ts b/tests/lib/private-sqlite-path.test.ts new file mode 100644 index 00000000000..649b78df103 --- /dev/null +++ b/tests/lib/private-sqlite-path.test.ts @@ -0,0 +1,117 @@ +/** Refusing links and other reparse points at SQLite database and sidecar names before anything is created. */ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, statSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + assertPrivateSqliteSidecars, + isWindowsReparsePoint, + nativeReparseProbeApplies, + preparePrivateSqliteDatabase, + setSqlitePathReparseProbeForTests, + UnsafeSqlitePathError, +} from "../../src/lib/private-sqlite-path"; +import { acquireSpendLedgerOwner, SPEND_LEDGER_OWNER_FILENAME, SpendLedgerOwnerError } from "../../src/lib/spend-ledger-owner"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +let root = ""; +let database = ""; +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), "ocx-sqlite-path-")); + database = join(root, "store.sqlite"); +}); +afterEach(() => { + setSqlitePathReparseProbeForTests(null); + removeTreeWithRetry(root); +}); + +test("a missing database is created as a private regular file", () => { + preparePrivateSqliteDatabase(database); + const stat = statSync(database); + expect(stat.isFile()).toBe(true); + expect(stat.size).toBe(0); + if (process.platform !== "win32") expect(stat.mode & 0o777).toBe(0o600); +}); + +test("an existing database and a regular hot journal are accepted unchanged", () => { + writeFileSync(database, "db", { mode: 0o600 }); + writeFileSync(`${database}-journal`, "journal", { mode: 0o600 }); + preparePrivateSqliteDatabase(database); + expect(readFileSync(database, "utf8")).toBe("db"); + expect(readFileSync(`${database}-journal`, "utf8")).toBe("journal"); +}); + +for (const kind of ["dangling link", "link", "hard link", "directory"] as const) { + test(`a ${kind} at the database name is refused without touching what it names`, () => { + const target = join(root, "outside"); + if (kind === "dangling link") symlinkSync(target, database); + else if (kind === "directory") mkdirSync(database); + else { + writeFileSync(target, "outside"); + if (kind === "link") symlinkSync(target, database); + else linkSync(target, database); + } + expect(() => preparePrivateSqliteDatabase(database)).toThrow(UnsafeSqlitePathError); + if (kind === "dangling link") expect(existsSync(target)).toBe(false); + else if (kind !== "directory") expect(readFileSync(target, "utf8")).toBe("outside"); + }); +} + +for (const suffix of ["-journal", "-wal", "-shm"]) { + test(`a link at the ${suffix} sidecar is refused before the database is created`, () => { + const target = join(root, "outside"); + symlinkSync(target, `${database}${suffix}`); + expect(() => preparePrivateSqliteDatabase(database)).toThrow(UnsafeSqlitePathError); + expect(() => assertPrivateSqliteSidecars(database)).toThrow(UnsafeSqlitePathError); + expect(existsSync(database)).toBe(false); + expect(existsSync(target)).toBe(false); + }); +} + +test("an entry the reparse probe flags is refused, database or sidecar", () => { + writeFileSync(database, "db", { mode: 0o600 }); + setSqlitePathReparseProbeForTests(path => path === database); + expect(() => preparePrivateSqliteDatabase(database)).toThrow(UnsafeSqlitePathError); + expect(readFileSync(database, "utf8")).toBe("db"); + + const fresh = join(root, "fresh.sqlite"); + writeFileSync(`${fresh}-wal`, "", { mode: 0o600 }); + setSqlitePathReparseProbeForTests(path => path === `${fresh}-wal`); + expect(() => preparePrivateSqliteDatabase(fresh)).toThrow(UnsafeSqlitePathError); + expect(existsSync(fresh)).toBe(false); +}); + +test("a probe that cannot answer fails closed, and the spend-ledger owner reports it as unavailable", () => { + writeFileSync(database, "db", { mode: 0o600 }); + setSqlitePathReparseProbeForTests(() => { throw new Error("native attribute query unavailable"); }); + expect(() => preparePrivateSqliteDatabase(database)).toThrow(UnsafeSqlitePathError); + + const home = join(root, "owner-home"); + mkdirSync(home); + writeFileSync(join(home, SPEND_LEDGER_OWNER_FILENAME), "", { mode: 0o600 }); + let failure: unknown; + try { acquireSpendLedgerOwner(home).release(); } catch (error) { failure = error; } + expect(failure).toBeInstanceOf(SpendLedgerOwnerError); + expect((failure as SpendLedgerOwnerError).code).toBe("SPEND_LEDGER_OWNER_UNAVAILABLE"); +}); + +test("the native attribute query runs on Windows except ARM64, whose Bun build cannot load FFI", () => { + expect(nativeReparseProbeApplies("win32", "x64")).toBe(true); + expect(nativeReparseProbeApplies("win32", "arm64")).toBe(false); + expect(nativeReparseProbeApplies("darwin", "arm64")).toBe(false); + expect(nativeReparseProbeApplies("linux", "x64")).toBe(false); +}); + +test.skipIf(process.platform !== "win32" || process.arch === "arm64")("the native Windows probe reports links and junctions, not regular files", () => { + writeFileSync(database, "db"); + const fileLink = join(root, "file-link"); + symlinkSync(database, fileLink, "file"); + const directory = join(root, "directory"); + mkdirSync(directory); + const junction = join(root, "junction"); + symlinkSync(directory, junction, "junction"); + expect(isWindowsReparsePoint(database)).toBe(false); + expect(isWindowsReparsePoint(directory)).toBe(false); + expect(isWindowsReparsePoint(fileLink)).toBe(true); + expect(isWindowsReparsePoint(junction)).toBe(true); +}); diff --git a/tests/lib/spend-ledger-owner.test.ts b/tests/lib/spend-ledger-owner.test.ts index e0091e7e839..857e252dea2 100644 --- a/tests/lib/spend-ledger-owner.test.ts +++ b/tests/lib/spend-ledger-owner.test.ts @@ -545,6 +545,37 @@ describe("backing file identity", () => { expect((failure as SpendLedgerOwnerError).code).toBe("SPEND_LEDGER_OWNER_UNAVAILABLE"); }); + test("a dangling link at the owner database is refused without creating its target", () => { + const linkedHome = join(root, "owner-dangling"); + mkdirSync(linkedHome, { recursive: true }); + const target = join(root, "owner-dangling-target"); + symlinkSync(target, join(linkedHome, SPEND_LEDGER_OWNER_FILENAME)); + // A fresh process, so the preload can make other platforms create through the link as Windows + // does before the owner module binds its file functions. + const preload = process.platform === "win32" ? [] : ["--preload", helperPath("windows-link-create-preload.ts")]; + const result = Bun.spawnSync([process.execPath, ...preload, helperPath("spend-ledger-owner-link-worker.ts"), linkedHome], { + env: { ...process.env, OPENCODEX_HOME: linkedHome }, stdout: "pipe", stderr: "pipe", + }); + expect(result.exitCode, result.stderr.toString()).toBe(0); + expect(JSON.parse(result.stdout.toString())).toEqual({ code: "SPEND_LEDGER_OWNER_UNAVAILABLE" }); + expect(existsSync(target)).toBe(false); + }); + + for (const suffix of ["-journal", "-wal", "-shm"]) { + test(`a link at the owner database ${suffix} is refused before the database is created`, () => { + const linkedHome = join(root, `owner-sidecar${suffix}`); + mkdirSync(linkedHome, { recursive: true }); + const target = join(root, `owner-sidecar-target${suffix}`); + symlinkSync(target, join(linkedHome, `${SPEND_LEDGER_OWNER_FILENAME}${suffix}`)); + let failure: unknown; + try { acquireSpendLedgerOwner(linkedHome).release(); } catch (error) { failure = error; } + expect(failure).toBeInstanceOf(SpendLedgerOwnerError); + expect((failure as SpendLedgerOwnerError).code).toBe("SPEND_LEDGER_OWNER_UNAVAILABLE"); + expect(existsSync(join(linkedHome, SPEND_LEDGER_OWNER_FILENAME))).toBe(false); + expect(existsSync(target)).toBe(false); + }); + } + test("invalid or unusable owner databases fail closed", () => { const invalidHome = join(root, "owner-invalid"); mkdirSync(invalidHome, { recursive: true }); From 4d93716dd76273daa3f55f39dd15a58ac64d117e Mon Sep 17 00:00:00 2001 From: JUN Date: Tue, 3 Nov 2026 01:51:38 +0900 Subject: [PATCH 10/43] feat(update): orchestrated ocx update plan/apply contract (update.orchestrated/1) (#8103) Adds contract update.orchestrated/1 for external orchestrators (GOAT). - ocx update --plan --json: read-only, passive plan (ocx.update.plan/1) judged against the attested install serving the live runtime; refuses CLI/serving mismatch, desktop-app, source, mise and unknown installs; planToken, updateInFlight, mutationBoundMs. - ocx update --yes --json [--tag|--version] [--expect-plan] [--not-after]: non-interactive apply (ocx.update.result/1), exact version pin in npm, pnpm and Bun lanes; fence order sync/update mutex, ownership lease, in-flight marker with time fence, then deadline, plan-token and attested identity checks; supervised installers; exit 0/10/11/12/64 from installer outcome plus passive tree and runtime verification. - ocx sync and legacy ocx update share the sync/update mutex (sync exit 7 update-in-flight, 1 sync-in-progress; --json refusals emit one fan-out document); the launcher holds it across Desktop handoff with a delegate pid. - ocx capabilities --json gains top-level contracts; --contracts --json prints only the contract list (sync.home-fanout/1, update.orchestrated/1). Design and audit record: devlog/_plan/261102_ocx_update_orchestrated/010_plan.md. --- bin/ocx.mjs | 231 ++++++- .../010_plan.md | 323 ++++++++++ .../content/docs/reference/cli/lifecycle.md | 41 ++ scripts/test-layout/layout.json | 2 +- .../ocx/references/01_management_surface.md | 10 +- skills/ocx/references/01_surface_lifecycle.md | 1 + .../references/01_surface_observe-system.md | 22 +- src/cli/capabilities-base.ts | 18 + src/cli/capabilities-command.ts | 2 +- src/cli/capability-contracts.ts | 3 +- src/cli/codex-shim-autorestore.ts | 9 +- src/cli/dispatch.ts | 10 +- src/cli/index.ts | 2 + src/cli/registry.ts | 7 +- src/cli/root.ts | 2 + src/cli/sync-command.ts | 2 + src/cli/sync-update-guard.ts | 18 + src/client/runtime.ts | 5 +- src/config/process-state.ts | 2 + src/lib/desktop-cli-handoff.d.mts | 2 +- src/lib/desktop-cli-handoff.mjs | 12 +- src/service/ownership-mutation-lease.d.mts | 13 +- src/service/ownership-mutation-lease.mjs | 64 +- src/update/index.ts | 158 ++++- src/update/npm-install.d.mts | 8 + src/update/npm-install.mjs | 21 +- src/update/orchestrated-admission.d.mts | 4 + src/update/orchestrated-admission.mjs | 12 + src/update/orchestrated-arguments.d.mts | 12 + src/update/orchestrated-arguments.mjs | 58 ++ src/update/orchestrated-child.d.mts | 12 + src/update/orchestrated-child.mjs | 70 +++ src/update/orchestrated-entry.ts | 236 +++++++ .../orchestrated-identity-probe-entry.ts | 20 + src/update/orchestrated-identity.ts | 51 ++ src/update/orchestrated-live-identity.ts | 48 ++ src/update/orchestrated-node-driver.mjs | 103 +++ src/update/orchestrated-outcome.d.mts | 21 + src/update/orchestrated-outcome.mjs | 40 ++ src/update/orchestrated-plan.ts | 49 ++ src/update/orchestrated-pnpm.d.mts | 8 + src/update/orchestrated-pnpm.mjs | 33 + src/update/orchestrated-session.d.mts | 27 + src/update/orchestrated-session.mjs | 140 +++++ src/update/orchestrated-token.d.mts | 10 + src/update/orchestrated-token.mjs | 21 + src/update/orchestrated-token.ts | 3 + src/update/orchestrated-tree.d.mts | 1 + src/update/orchestrated-tree.mjs | 14 + src/update/pnpm-global-install.d.mts | 6 + src/update/pnpm-global-install.mjs | 11 +- src/update/posix-install-supervisor-entry.mjs | 6 + src/update/posix-install-supervisor.d.mts | 10 + src/update/posix-install-supervisor.mjs | 88 +++ src/update/sync-update-mutex.d.mts | 10 + src/update/sync-update-mutex.mjs | 164 +++++ src/update/sync-update-mutex.ts | 1 + src/update/test-home-guard.mjs | 33 + src/update/transactional-install.mjs | 4 +- structure/cli-management.md | 4 + structure/codex-cli-update.md | 4 + structure/config.md | 2 +- structure/ops/desktop-supervision.md | 2 + structure/ops/service-and-sidecars.md | 6 +- structure/remote-link.md | 2 +- structure/runtime.md | 4 +- tests/ci-workflows/install-scripts.test.ts | 13 +- tests/cli/cli-capabilities-arguments.test.ts | 51 ++ tests/cli/cli-client-start-fence.test.ts | 10 + tests/cli/cli-sync-expect-link.test.ts | 8 +- .../cli/ocx-launcher-desktop-handoff.test.ts | 107 +++- tests/cli/ocx-launcher-source.test.ts | 2 +- .../codex-cli-update-launcher-policy.test.ts | 2 +- .../codex-shim-autorestore.test.ts | 18 + tests/fixtures/test-layout-expected.json | 2 +- tests/helpers/update-bun-ownership-child.ts | 21 +- tests/helpers/update-node-home-child.mjs | 6 +- ...nership-mutation-lease-diagnostics.test.ts | 7 + .../update/update-bun-ownership-lease.test.ts | 12 +- tests/update/update-home-launcher.test.ts | 2 +- .../update/update-orchestrated-apply.test.ts | 190 ++++++ .../update-orchestrated-arguments.test.ts | 34 + .../update/update-orchestrated-entry.test.ts | 589 ++++++++++++++++++ .../update-orchestrated-identity.test.ts | 62 ++ tests/update/update-orchestrated-plan.test.ts | 176 ++++++ .../update-orchestrated-session.test.ts | 299 +++++++++ .../update/update-orchestrated-token.test.ts | 18 + tests/update/update-pnpm.test.ts | 32 + .../update/update-recovery-boundaries.test.ts | 7 +- tests/update/update-stop-first.test.ts | 19 +- tests/update/update-sync-mutex.test.ts | 345 ++++++++++ 91 files changed, 4258 insertions(+), 112 deletions(-) create mode 100644 devlog/_plan/261102_ocx_update_orchestrated/010_plan.md create mode 100644 src/cli/sync-update-guard.ts create mode 100644 src/update/npm-install.d.mts create mode 100644 src/update/orchestrated-admission.d.mts create mode 100644 src/update/orchestrated-admission.mjs create mode 100644 src/update/orchestrated-arguments.d.mts create mode 100644 src/update/orchestrated-arguments.mjs create mode 100644 src/update/orchestrated-child.d.mts create mode 100644 src/update/orchestrated-child.mjs create mode 100644 src/update/orchestrated-entry.ts create mode 100644 src/update/orchestrated-identity-probe-entry.ts create mode 100644 src/update/orchestrated-identity.ts create mode 100644 src/update/orchestrated-live-identity.ts create mode 100644 src/update/orchestrated-node-driver.mjs create mode 100644 src/update/orchestrated-outcome.d.mts create mode 100644 src/update/orchestrated-outcome.mjs create mode 100644 src/update/orchestrated-plan.ts create mode 100644 src/update/orchestrated-pnpm.d.mts create mode 100644 src/update/orchestrated-pnpm.mjs create mode 100644 src/update/orchestrated-session.d.mts create mode 100644 src/update/orchestrated-session.mjs create mode 100644 src/update/orchestrated-token.d.mts create mode 100644 src/update/orchestrated-token.mjs create mode 100644 src/update/orchestrated-token.ts create mode 100644 src/update/orchestrated-tree.d.mts create mode 100644 src/update/orchestrated-tree.mjs create mode 100644 src/update/posix-install-supervisor-entry.mjs create mode 100644 src/update/posix-install-supervisor.d.mts create mode 100644 src/update/posix-install-supervisor.mjs create mode 100644 src/update/sync-update-mutex.d.mts create mode 100644 src/update/sync-update-mutex.mjs create mode 100644 src/update/sync-update-mutex.ts create mode 100644 src/update/test-home-guard.mjs create mode 100644 tests/update/update-orchestrated-apply.test.ts create mode 100644 tests/update/update-orchestrated-arguments.test.ts create mode 100644 tests/update/update-orchestrated-entry.test.ts create mode 100644 tests/update/update-orchestrated-identity.test.ts create mode 100644 tests/update/update-orchestrated-plan.test.ts create mode 100644 tests/update/update-orchestrated-session.test.ts create mode 100644 tests/update/update-orchestrated-token.test.ts create mode 100644 tests/update/update-sync-mutex.test.ts diff --git a/bin/ocx.mjs b/bin/ocx.mjs index 2be5336d9b5..0bebcf274c0 100755 --- a/bin/ocx.mjs +++ b/bin/ocx.mjs @@ -12,6 +12,7 @@ import { guardedRun, guardedSpawn, guardedSpawnSync, guardedExit, probeProcessAl import { probeSpawn, probeSpawnSync } from "../src/update/mutation-guard.mjs"; import { createSupervisionLatch, inspectDesktopSupervision } from "../src/service/desktop-supervision.mjs"; import { planDesktopCliHandoff, runDesktopCliHandoff } from "../src/lib/desktop-cli-handoff.mjs"; +import { acquireSyncGuard } from "../src/update/sync-update-mutex.mjs"; import { desktopCliRecordPath } from "../src/lib/desktop-cli-record.mjs"; import { STOP_HISTORY_INCOMPLETE_EXIT_CODE } from "../src/update/stop-contract.mjs"; import { probeProxyLiveness } from "../src/update/proxy-liveness-probe.mjs"; @@ -43,9 +44,14 @@ import { isRealBunBinary } from "../src/lib/bun-binary-validator.mjs"; import { scopeTranspilerCacheToRuntime } from "../src/lib/bun-transpiler-cache-scope.mjs"; import { findDesktopCli, findPathBun } from "../src/lib/bun-path-runtime.mjs"; import { npmInvocation } from "../src/update/npm-invocation.mjs"; -import { runNpmInstall } from "../src/update/npm-install.mjs"; +import { runNpmInstall, runWindowsInstallerSync } from "../src/update/npm-install.mjs"; +import { runPosixInstallerSync } from "../src/update/posix-install-supervisor.mjs"; import { pnpmInvocationForPath, resolvePnpmCommands } from "../src/update/pnpm-invocation.mjs"; import { detectInstallOwnershipFromPath } from "../src/update/install-detection.mjs"; +import { isOrchestratedUpdateArgv, parseOrchestratedUpdateArgs, parseOrchestratedChildArgs } from "../src/update/orchestrated-arguments.mjs"; +import { createLegacyUpdateSession, createOrchestratedChildSession, decodeOrchestratedExpect } from "../src/update/orchestrated-session.mjs"; +import { createUpdatePlanToken } from "../src/update/orchestrated-token.mjs"; +import { applyNodeOrchestratedUpdate } from "../src/update/orchestrated-node-driver.mjs"; import { pnpmOwnerInvocation, resolvePnpmGlobalOwner, @@ -232,7 +238,48 @@ function runningPnpmShimPath() { return resolve(invoked); } -async function runPackageManagerSelfUpdate(manager) { +async function runPackageManagerSelfUpdate(manager, child) { + let session, enteredMutation = false; + let childOutcome = { phase: "failed", rollbackPerformed: false }; + if (child) { + try { + const expected = decodeOrchestratedExpect(child.expect); + session = createOrchestratedChildSession({ home: configDir(), resultPath: child.resultPath, expect: expected, + notAfter: child.notAfter, verifyIdentity: () => { + const bun = resolveBun({ allowInstall: false, allowMissing: true }); + if (!bun) return false; + const probe = probeSpawnSync(bun.path, ["--no-env-file", join(here, "../src/update/orchestrated-identity-probe-entry.ts"), "__update-orchestrated-identity"], { + encoding: "utf8", timeout: 8000, maxBuffer: 8192, windowsHide: true, stdio: ["ignore", "pipe", "ignore"], + env: { ...updateHomeProbeEnvironment(process.env, { codexHome: process.env.CODEX_HOME ?? "", opencodexHome: configDir() }), + OCX_IDENTITY_CLI_ROOT: resolve(here, ".."), OCX_IDENTITY_INSTALLER: manager, OCX_IDENTITY_TARGET: child.version }, + }); + if (probe.status !== 0 || probe.error || probe.signal || typeof probe.stdout !== "string") return false; + const observed = JSON.parse(probe.stdout); + return observed.permits === true && observed.cliRoot === expected.cliRoot && observed.planToken === expected.planToken + && (observed.kind === "absent" ? expected.servingRoot === null && expected.runtimePid === null + : observed.kind === "live" && observed.servingRoot === expected.servingRoot && observed.runtime?.pid === expected.runtimePid); + } }); + if (!session.start().ok) process.exit(10); + // The parent may forward a signal while a synchronous installer is running. Keep the + // owner alive through its transaction and recovery so the mutex cannot outlive us. + for (const signal of ["SIGINT", "SIGTERM", ...(process.platform === "win32" ? [] : ["SIGHUP"])]) process.on(signal, () => {}); + process.once("exit", () => { + try { if (enteredMutation) session.finish(childOutcome); else session.finishPreflight(); } + catch (error) { console.error(`Orchestrated outcome write failed: ${error?.message ?? error}`); process.exitCode = 1; } + }); + } catch (error) { + console.error(`Orchestrated update preflight failed: ${error?.message ?? error}`); + process.exit(1); + } + } else { + session = createLegacyUpdateSession({ home: configDir() }); + const started = session.start(); + if (!started.ok) { console.error(`opencodex: ${started.error}`); process.exit(1); } + process.once("exit", () => { + try { if (enteredMutation) session.finish(childOutcome); else session.finishPreflight(); } + catch (error) { console.error(`Update outcome write failed: ${error?.message ?? error}`); process.exitCode = 1; } + }); + } const current = currentPackageVersion(); const tag = updateTag(current); let owner; @@ -279,17 +326,18 @@ async function runPackageManagerSelfUpdate(manager) { : invocation.env ? { env: invocation.env } : {}), ...invocation.options, }); - const latestInvocation = managerInvocation(["view", `${PKG}@${tag}`, "version"]); + const selector = child?.version ?? tag; + const latestInvocation = managerInvocation(["view", `${PKG}@${selector}`, "version"]); const installArgs = manager === "pnpm" - ? ["add", "-g", "--allow-build=bun", `${PKG}@${tag}`] - : ["install", "-g", `${PKG}@${tag}`]; + ? ["add", "-g", "--allow-build=bun", `${PKG}@${selector}`] + : ["install", "-g", `${PKG}@${selector}`]; const installInvocation = managerInvocation(installArgs); if (!latestInvocation || !installInvocation) { console.error(`opencodex: could not resolve ${manager} from a trusted absolute PATH entry; aborting before stopping the proxy.`); process.exit(1); } const latestResult = probeSpawnSync(latestInvocation.file, latestInvocation.args, readProbeOptions(latestInvocation)); - const latest = latestResult.status === 0 && typeof latestResult.stdout === "string" ? latestResult.stdout.trim() : ""; + const latest = child?.version ?? (latestResult.status === 0 && typeof latestResult.stdout === "string" ? latestResult.stdout.trim() : ""); console.log(`opencodex v${current} (installed via ${manager}, tag ${tag})`); if (latest && latest === current) { @@ -752,6 +800,12 @@ async function runPackageManagerSelfUpdate(manager) { runtimePlan = lockedPlan; const stoppedOwnershipIdentity = ownershipIdentity(lockedOwnership); + if (session) { + const entered = await session.enterMutation(); + if (!entered.ok) { releaseUpdateLease(); process.exit(10); } + enteredMutation = true; + } + // Never replace package files under a live proxy — stop it first (full `ocx stop` // semantics: graceful drain, service stop, native Codex restore). Gate on the service // and the runtime-port record too: a service-managed or orphaned proxy can be live @@ -940,7 +994,7 @@ async function runPackageManagerSelfUpdate(manager) { try { if (manager === "npm") { const packageDir = resolve(here, ".."); - const transactionalNpmUpdate = process.platform === "win32" ? transactionalNpmUpdateAsync : transactionalNpmUpdateSync; + const transactionalNpmUpdate = session ? transactionalNpmUpdateAsync : transactionalNpmUpdateSync; if (!homePolicy.authorizeMutation("package")) throw new Error("Automatic package update refused."); const tx = await transactionalNpmUpdate({ packageDir, @@ -958,12 +1012,31 @@ async function runPackageManagerSelfUpdate(manager) { runNpm: (args) => { const invocation = npmInvocation(args); if (!homePolicy.authorizeMutation("package")) return { status: 1 }; - if (process.platform === "win32") return runNpmInstall(invocation, { - authorizeMutation: homePolicy.authorizeMutation, - env: unprivilegedOwnershipMutationEnvironment(invocation?.options?.env ?? process.env), - }); + if (process.platform === "win32") { + if (session) session.noteUntrackedInstaller(); + return runNpmInstall(invocation, { + authorizeMutation: homePolicy.authorizeMutation, + env: unprivilegedOwnershipMutationEnvironment(invocation?.options?.env ?? process.env), + }).then(result => { + if (session && result.processTreeExited === true && Number.isInteger(result.status)) session.confirmInstallerExit(); + else if (session) { session.retainInstallerFence(); return { ...result, processTreeExited: false }; } + return result; + }); + } if (!invocation) return { status: 1 }; if (!homePolicy.authorizeMutation("package")) return { status: 1 }; + if (session) { + try { + const result = runPosixInstallerSync({ file: invocation.file, args: invocation.args, + markerPath: join(configDir(), "update-orchestrated.json"), authorizeMutation: homePolicy.authorizeMutation, + env: unprivilegedOwnershipMutationEnvironment(invocation.options?.env ?? process.env) }); + if (!Number.isInteger(result.status) || result.signal || !result.groupExited || result.groupKilled !== false || result.processTreeExited === false) { + session.retainInstallerFence(); + return { ...result, processTreeExited: false }; + } + return { ...result, processTreeExited: true }; + } catch (error) { session.retainInstallerFence(); throw error; } + } return guardedSpawnSync(homePolicy.authorizeMutation, "package", invocation.file, invocation.args, { ...invocation.options, stdio: "inherit", @@ -974,6 +1047,9 @@ async function runPackageManagerSelfUpdate(manager) { }, log: (line) => console.log(line), }); + if (session) childOutcome = tx.ok ? { phase: "installed", activeRoot: packageDir } + : { phase: "failed", rollbackPerformed: tx.rolledBack === true, + ...(tx.processTreeExited === false ? { error: "installer-termination-unconfirmed", terminationConfirmed: false } : {}) }; postUpdateLauncherUsable = launcherUsableAfterNpmUpdate(tx); if (!tx.ok) npmFailure = tx; if (tx.ok) { @@ -998,6 +1074,25 @@ async function runPackageManagerSelfUpdate(manager) { runPnpm: (args, capture = false) => { const invocation = pnpmOwnerInvocation(owner, args); if (!invocation) return { status: 1 }; + if (session && !capture) return withPnpmCommandCwd(args, cwd => { + const env = pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(invocation.env ?? process.env)); + if (process.platform === "win32") { + session.noteUntrackedInstaller(); + const result = runWindowsInstallerSync(invocation, { cwd, env, authorizeMutation: homePolicy.authorizeMutation }); + if (result.processTreeExited === true && Number.isInteger(result.status)) session.confirmInstallerExit(); + else { session.retainInstallerFence(); return { ...result, processTreeExited: false }; } + return result; + } + try { + const result = runPosixInstallerSync({ file: invocation.file, args: invocation.args, cwd, markerPath: join(configDir(), "update-orchestrated.json"), + authorizeMutation: homePolicy.authorizeMutation, env }); + if (!Number.isInteger(result.status) || result.signal || !result.groupExited || result.groupKilled !== false || result.processTreeExited === false) { + session.retainInstallerFence(); + return { ...result, processTreeExited: false }; + } + return { ...result, processTreeExited: true }; + } catch (error) { session.retainInstallerFence(); throw error; } + }); return withPnpmCommandCwd(args, cwd => homePolicy.authorizeMutation("package") ? guardedSpawnSync(homePolicy.authorizeMutation, "package", invocation.file, invocation.args, { ...invocation.options, stdio: capture ? "pipe" : "inherit", @@ -1012,6 +1107,9 @@ async function runPackageManagerSelfUpdate(manager) { }, log: line => console.log(line), }); + if (session) childOutcome = update.ok ? { phase: "installed", activeRoot: update.path } + : { phase: "failed", rollbackPerformed: update.rollbackPerformed === true, + ...(update.processTreeExited === false ? { error: "installer-termination-unconfirmed", terminationConfirmed: false } : {}) }; if (update.ok) { // pnpm switches the active global group and updates its shim. Continue recovery // through that fresh package tree, not the old group whose launcher is still @@ -1037,12 +1135,13 @@ async function runPackageManagerSelfUpdate(manager) { `Run 'ocx update' again or follow the manual recovery steps below.`); res = { status: 1 }; } - if (res.status !== 0) recoverStoppedRuntimeAfterFailure("update failed"); + if (res.status !== 0 && childOutcome.error !== "installer-termination-unconfirmed") recoverStoppedRuntimeAfterFailure("update failed"); } finally { // Expected aborts release before process.exit(); this covers every thrown or newly-added // path and keeps token restoration coupled to the lease itself. releaseUpdateLease(); } + if (childOutcome.error === "installer-termination-unconfirmed") process.exit(1); const postInstallPlan = planUpdateRuntimeHandling({ ...readOwnership(), serviceInstalled: serviceWasInstalled, supervision: observeSupervision() }); if (res.status === 0) { authorityLauncher = postUpdateLauncher; @@ -1218,10 +1317,10 @@ function resolveBun({ allowInstall = true, launcherPath, allowMissing = false } // intercepts `update` before the Bun CLI starts, so the help short-circuit must live // here too — otherwise --help runs the real self-update, stops the proxy, and drops // in-flight routed streams (issue #168). -const updateHelpRequested = process.argv[2] === "update" && +const updateHelpRequested = process.argv[2] === "update" && !isOrchestratedUpdateArgv(process.argv.slice(3)) && process.argv.slice(3).some(a => a === "--help" || a === "-h" || a === "help"); if (updateHelpRequested) { - console.log("Usage: ocx update [--tag latest|preview]\n\nUpdate opencodex. Preview installs stay on the preview tag unless overridden."); + console.log("Usage: ocx update [--tag latest|preview]\n ocx update --plan --json [--tag latest|preview | --version ]\n ocx update --yes --json [--tag latest|preview | --version ] [--expect-plan ] [--not-after ]\n\nPreview with --plan; apply with --yes. --expect-plan binds apply to the planToken; --not-after sets a Unix millisecond mutation deadline.\nOrchestrated exit codes: 0 verified or up-to-date; 10 refused; 11 failed with previous version verified; 12 unverified or still running; 64 invalid usage.\nPreview installs stay on the preview tag unless overridden."); process.exit(0); } @@ -1237,7 +1336,59 @@ if (process.argv[2] === "__update-home-probe") { console.log(JSON.stringify({ schemaVersion: 1, ...readNodeUpdateHome(fileURLToPath(import.meta.url)), launcherProtocolVersion: UPDATE_HOME_LAUNCHER_PROTOCOL })); process.exit(0); } +if (process.argv[2] === "__update-orchestrated-identity") { + if (process.argv.length !== 3) process.exit(1); + const bun = resolveBun({ allowInstall: false, allowMissing: true }); + if (!bun) process.exit(1); + const result = probeSpawnSync(bun.path, ["--no-env-file", join(here, "../src/update/orchestrated-identity-probe-entry.ts"), process.argv[2]], { + stdio: "inherit", timeout: 8000, windowsHide: true, env: { ...process.env, OCX_IDENTITY_CLI_ROOT: resolve(here, ".."), OCX_IDENTITY_INSTALLER: "", OCX_IDENTITY_TARGET: "" }, + }); + process.exit(result.status ?? 1); +} +const orchestratedUpdate = process.argv[2] === "update" && isOrchestratedUpdateArgv(process.argv.slice(3)); +const childArgs = orchestratedUpdate && process.env.OCX_UPDATE_ORCHESTRATED_CHILD === "1" + ? parseOrchestratedChildArgs(process.argv.slice(3), process.env) : null; +const orchestratedArgs = orchestratedUpdate && !childArgs?.ok ? parseOrchestratedUpdateArgs(process.argv.slice(3)) : null; +if (orchestratedArgs && !orchestratedArgs.ok) { + console.log(JSON.stringify({ error: "usage" })); + console.error("Usage: ocx update (--plan | --yes) --json [--tag latest|preview | --version ]"); + process.exit(64); +} +if (childArgs?.ok && isNodeModulesInstall() && !isBunGlobalInstall() && (installMethod === "npm" || installMethod === "pnpm")) { + await runPackageManagerSelfUpdate(installMethod, childArgs); +} +if (orchestratedArgs?.ok && orchestratedArgs.mode === "apply" && process.env.OCX_UPDATE_ORCHESTRATED_CHILD !== "1" + && isNodeModulesInstall() && !isBunGlobalInstall() && (installMethod === "npm" || installMethod === "pnpm")) { + const result = await applyNodeOrchestratedUpdate(orchestratedArgs, { + installer: installMethod, currentVersion: String(currentPackageVersion()), cliRoot: resolve(here, ".."), + home: configDir(), launcher: fileURLToPath(import.meta.url), resolveBun: () => resolveBun({ allowInstall: false, allowMissing: true }), + plan: (bun, version, tag) => probeSpawnSync(bun.path, ["--no-env-file", cliPath, "update", "--plan", "--json", + ...(version ? ["--version", version] : tag ? ["--tag", tag] : [])], { encoding: "utf8", maxBuffer: 65536, timeout: 60000, windowsHide: true, + stdio: ["ignore", "pipe", 2], env: process.env }), + identity: bun => { + const probe = probeSpawnSync(bun.path, ["--no-env-file", join(here, "../src/update/orchestrated-identity-probe-entry.ts"), "__update-orchestrated-identity"], { + encoding: "utf8", maxBuffer: 8192, timeout: 8000, windowsHide: true, stdio: ["ignore", "pipe", 2], + env: { ...updateHomeProbeEnvironment(process.env, { codexHome: process.env.CODEX_HOME ?? "", opencodexHome: configDir() }), + OCX_IDENTITY_CLI_ROOT: resolve(here, ".."), OCX_IDENTITY_INSTALLER: "", OCX_IDENTITY_TARGET: "" }, + }); + if (probe.status !== 0 || probe.error || probe.signal) throw Error("identity unavailable"); + return JSON.parse(probe.stdout); + }, + pnpmCommands: resolvePnpmCommands(), runningShimPath: runningPnpmShimPath(), + runPnpm: (commandPath, args, capture = false) => { + const invocation = pnpmInvocationForPath(commandPath, args); + if (!invocation) return { status: 1 }; + return probeSpawnSync(invocation.file, invocation.args, { stdio: capture ? "pipe" : "ignore", encoding: "utf8", + timeout: 20000, windowsHide: true, cwd: PNPM_READ_CWD, + env: pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(process.env)), ...invocation.options }); + }, + spawn: probeSpawn, + }); + await new Promise(resolveOutput => process.stdout.write(`${JSON.stringify(result.result)}\n`, resolveOutput)); + process.exit(result.exitCode); +} +const passiveCapabilities = process.argv[2] === "capabilities"; const codexCliUpdateInspection = isCodexCliUpdateInspectionArgv(process.argv); // Windows inspection currently refuses before candidate I/O, so a long-lived // Windows server does not duplicate PATH into its inherited environment block. @@ -1249,6 +1400,7 @@ if (codexCliUpdateInspection && typeof process.versions.bun === "string") { } const { launchProof, launchContext, inheritedEnv } = createNodeLaunchContext(); +delete inheritedEnv.OCX_SYNC_MUTEX_HELD_BY; const desktopPlan = planDesktopCliHandoff({ selfPaths: [fileURLToPath(import.meta.url), process.execPath] }); if (desktopPlan.kind === "error") { if (desktopPlan.issue.startsWith("record-")) { @@ -1258,15 +1410,30 @@ if (desktopPlan.kind === "error") { } process.exit(1); } +let releaseSyncLease = () => {}; +let addSyncDelegate = () => {}; +if (process.argv[2] === "sync") { + const syncLease = acquireSyncGuard(configDir(), process.argv.slice(2)); + if (syncLease.kind === "refused") process.exit(syncLease.exit); + addSyncDelegate = pid => syncLease.addDelegate(pid); + inheritedEnv.OCX_SYNC_MUTEX_HELD_BY = String(process.pid); + let released = false; + releaseSyncLease = () => { + if (released) return; + try { syncLease.release(); released = true; } catch (error) { console.error(`opencodex: sync mutex release failed: ${error.message}`); } + }; + process.once("exit", releaseSyncLease); +} if (desktopPlan.kind === "handoff") { const result = await runDesktopCliHandoff(desktopPlan, { - argv: process.argv.slice(2), env: inheritedEnv, proof: launchProof, context: launchContext, + argv: process.argv.slice(2), env: inheritedEnv, proof: launchProof, context: launchContext, onSpawn: addSyncDelegate, }); if (result.kind === "error") { console.error(`opencodex: Desktop CLI handoff failed (${result.issue}). Repair the terminal command in OpenCodex Desktop, or run with OCX_NO_DESKTOP_HANDOFF=1.`); process.exit(127); } if (result.kind === "exit") { + releaseSyncLease(); if (result.signal) { relayOwnSignal(result.signal); } else { @@ -1278,7 +1445,7 @@ if (desktopPlan.kind === "handoff") { // Only confirmed target ENOENT reaches the ordinary package path below. } -if (process.argv[2] === "update" && installMethod === "mise") { +if (!orchestratedUpdate && process.argv[2] === "update" && installMethod === "mise") { if (installOwnership.owner) { console.error( `opencodex: this installation is externally managed by mise; update it with: mise upgrade ${installOwnership.owner.tool}`, @@ -1291,7 +1458,7 @@ if (process.argv[2] === "update" && installMethod === "mise") { process.exit(1); } -if (process.argv[2] === "update" && isNodeModulesInstall() && !isBunGlobalInstall()) { +if (!orchestratedUpdate && process.argv[2] === "update" && isNodeModulesInstall() && !isBunGlobalInstall()) { if (installMethod === "npm") await runNpmSelfUpdate(); if (installMethod === "pnpm") await runPnpmSelfUpdate(); } @@ -1299,7 +1466,7 @@ if (process.argv[2] === "update" && isNodeModulesInstall() && !isBunGlobalInstal // #1849 boot probe: a prior update that lost power (or double-faulted) mid-swap leaves a // backup sibling and a broken live tree. Restore before anything tries to run from the // broken tree; reap stale backups once the live tree verifies healthy. -if (!codexCliUpdateInspection && installMethod === "npm" && isNodeModulesInstall() && !isBunGlobalInstall()) { +if (process.argv[2] !== "sync" && !orchestratedUpdate && !passiveCapabilities && !codexCliUpdateInspection && installMethod === "npm" && isNodeModulesInstall() && !isBunGlobalInstall()) { try { const probe = bootRestoreProbe(resolve(here, "..")); if (probe.action === "restored") { @@ -1310,7 +1477,22 @@ if (!codexCliUpdateInspection && installMethod === "npm" && isNodeModulesInstall } catch { /* the probe must never block launch */ } } -const bunRuntime = resolveBun({ allowInstall: !codexCliUpdateInspection }); +const passiveSync = process.argv[2] === "sync"; +const bunRuntime = resolveBun({ allowInstall: !passiveSync && !orchestratedUpdate && !passiveCapabilities && !codexCliUpdateInspection, allowMissing: orchestratedUpdate || passiveSync }); +if (!bunRuntime && passiveSync) fail("Bun is unavailable; install Bun before running sync."); +if (!bunRuntime && orchestratedArgs?.ok) { + const currentVersion = String(currentPackageVersion()), cliRoot = resolve(here, ".."); + if (orchestratedArgs.mode === "plan") { + const identity = { currentVersion, targetVersion: null, installer: installMethod, cliRoot, servingRoot: null, runtimeOwner: "unknown", runtime: null }; + console.log(JSON.stringify({ schema: "ocx.update.plan/1", currentVersion, targetVersion: null, installer: installMethod, + runtimeOwner: "unknown", servingPath: null, cliPath: cliRoot, canApply: false, reason: "plan-unavailable", restartRequired: false, + planToken: createUpdatePlanToken(identity), updateInFlight: true, mutationBoundMs: 900000 })); + process.exit(0); + } + console.log(JSON.stringify({ schema: "ocx.update.result/1", applied: false, fromVersion: currentVersion, toVersion: null, + installer: installMethod, restarted: false, healthy: false, rolledBack: false, error: "plan-unavailable" })); + process.exit(10); +} const bun = bunRuntime.path; // Run the Bun child asynchronously and FORWARD termination signals to it, then wait @@ -1438,6 +1620,15 @@ const child = probeSpawn(bun, [cliPath, `${NODE_LAUNCH_PROOF_PREFIX}${launchProo [BUN_RUNTIME_PATH_ENV]: bunRuntime.path, }, }); +let delegateError = false; +if (child.pid) { + try { addSyncDelegate(child.pid); } + catch (error) { + delegateError = true; + console.error(`opencodex: sync mutex delegate publication failed: ${error.message}`); + try { child.kill(); } catch (killError) { console.error(`opencodex: failed to stop sync child: ${killError.message}`); } + } +} // Windows has no real POSIX signals (no SIGHUP); forwarding is best-effort there. const FORWARDED = process.platform === "win32" ? ["SIGINT", "SIGTERM"] : ["SIGINT", "SIGTERM", "SIGHUP"]; @@ -1464,6 +1655,8 @@ child.on("error", err => { child.on("exit", (code, signal) => { clearHandlers(); + releaseSyncLease(); + if (delegateError) process.exit(1); // Mirror the child's terminating signal/exit code so this launcher's status matches. if (signal) { relayOwnSignal(signal); diff --git a/devlog/_plan/261102_ocx_update_orchestrated/010_plan.md b/devlog/_plan/261102_ocx_update_orchestrated/010_plan.md new file mode 100644 index 00000000000..5cefbb8c208 --- /dev/null +++ b/devlog/_plan/261102_ocx_update_orchestrated/010_plan.md @@ -0,0 +1,323 @@ +# 010 — Orchestrated ocx update (contract C1) — diff-level plan + +Lane L1, branch feat/ocx-update-orchestrated, base origin/dev affd8403a. Class C4 (public CLI +output contract + update/install mutation path). Consumer: GOAT L3 (adopted-member update). + +## Contract (agreed with L3, cc L2, 2026-11-02) + +- `ocx update --plan --json [--tag latest|preview | --version X.Y.Z]` read-only. stdout is one JSON + object, exit 0 even when the plan refuses (usage errors exit 64; --tag with --version is 64). + {schema:"ocx.update.plan/1", currentVersion, targetVersion|null, installer: + "npm"|"pnpm"|"bun"|"mise"|"desktop-app"|"source"|"unknown", runtimeOwner: + "service"|"desktop-app"|"unmanaged"|"none"|"unknown", servingPath|null, cliPath, canApply, + reason?, restartRequired}. +- reason codes (first match wins, in this order): desktop-app-owned, source-checkout, mise-managed, + installer-unknown, serving-install-unknown, cli-not-serving-install, runtime-ownership-refused, + target-unresolved, downgrade-refused, up-to-date. canApply=true only with no reason. +- `ocx update --yes --json [...]` recomputes the plan, then applies. stdout is one JSON object + {schema:"ocx.update.result/1", applied, fromVersion, toVersion|null, installer, restarted, healthy, + rolledBack, error?}; progress goes to stderr. exit 0 = applied or up-to-date (applied=false), + 10 = refused (plan reason, nothing touched), 11 = failed with the previous version verified in + place (rollback or refusal before mutation), 12 = failed with state not verified, 64 = usage. +- `ocx capabilities --json` gains top-level `contracts: string[]` on every output shape (full, + --route, --mutating-only, unmatched route). `ocx capabilities --contracts --json` prints only + {"schemaVersion":1,"contracts":[...]} (output is small enough for GOAT's 256 KiB / SSH budget); + --contracts with --route/--mutating-only exits 64. List lives in + src/cli/capability-contracts.ts CAPABILITY_CONTRACTS (L2 appends "sync.home-fanout/1"). +- desktop-app: the Tauri updater's check/install commands require the update page window + (desktop/src-tauri/src/lib.rs update_check/update_install → window::require_update_page) and the + tray menu; there is no external trigger, so desktop-app installs plan canApply=false + reason "desktop-app-owned" and the CLI never edits app-owned files. + +## Serving-install identity (core rule) + +Decide against the install that serves the live runtime of the current home: +1. Live runtime = runtime-port.json {pid,port} whose /healthz answers service "opencodex" with the + same pid (bounded timeout). No record / dead → runtimeOwner "none", subject is the CLI install. +2. Serving command = argv of that pid (POSIX: ps -ww -o command= / Linux /proc//cmdline; + Windows: Win32_Process CommandLine through the existing bounded reader, or null). Resolve its + install root: compiled exe → exe path; bun + /src/cli/index.ts → ; node /bin/ocx.mjs + → . Cross-check with serving-runtimes.json (src/config/serving-runtimes.ts) record whose + command key matches and whose version equals healthz version. Unresolvable → servingPath null + → reason serving-install-unknown (fail closed). +3. cliPath = realpath of this CLI's package root (or standalone exe). servingPath ≠ cliPath → + cli-not-serving-install (lidge: PATH npm 2.50.0 vs serving 2.83.0). Nothing is touched. +4. runtimeOwner: desktop supervision (inspectDesktopSupervision) or recorded desktop owner → + desktop-app; service installed and recorded owner is this CLI → service; else unmanaged; + read failures → unknown. planUpdateRuntimeHandling(...).mayReplacePackage=false or ownership + unknown → runtime-ownership-refused. +5. installer: detectInstallOwnership(); standalone → desktop-app when the exe lives in the desktop + bundle/home or desktop owns the runtime, else unknown. +6. target: --version validated as strict semver and confirmed published (registry view of that exact + version through the installer's trusted invocation) else latestVersion(tag). Unresolved → + target-unresolved. target < current → downgrade-refused; equal → up-to-date. +7. restartRequired = a live runtime served by this install exists (the update stops/restarts it). + +## Apply lanes (reuse, no new mutation code) + +- npm/pnpm (node_modules, non-bun-global): bin/ocx.mjs must keep the package's bundled Bun idle + during replacement (Windows file locks), so the Node launcher drives apply: spawn Bun child + `update --plan --json ` (capture), refuse/up-to-date → result; else spawn Node child of the + existing lane `node bin/ocx.mjs update --tag T | --version X` with stdout→stderr, then readback. + `--plan` (and apply for other installers) skips the launcher's mise/npm/pnpm intercepts and falls + through to the Bun CLI. +- bun global: Bun handler spawns the existing runUpdate lane as a child (selfLaunchArgv) with + stdout→stderr, then readback. +- Version pin: runUpdate and runPackageManagerSelfUpdate accept `--version X` (install + PKG@X instead of PKG@tag, integrity pre-flight for X, already-current check against X). +- Readback (shared .mjs, usable from Node and Bun): installed package.json version at the install + root; runtime probe (runtime-port + /healthz pid/version) with bounded probation when + restartRequired. applied = installed == target; restarted = new live pid ≠ prior pid; + healthy = restartRequired ? live && version == target : installed == target. Child failure with + installed == from (and prior runtime live again when it was live) → exit 11 rolledBack=true; anything + else → 12. + +## Files + +- new src/update/orchestrated-contract.mjs/.d.mts: schemas, exit codes, argv parser, result builder, + readback helpers (Node+Bun safe, no TS imports). +- new src/update/orchestrated.ts: planOrchestratedUpdate(request, deps) with injectable deps; + runOrchestratedUpdate(argv) for plan + bun-lane apply. +- src/update/serving-identity (inside orchestrated.ts or own file): process argv reader + root resolver. +- src/update/index.ts (runUpdate pin), bin/ocx.mjs (intercept order, pin, npm/pnpm apply driver, help). +- src/cli/dispatch.ts update branch; src/cli/registry.ts usage; src/cli/capability-contracts.ts; + src/cli/capabilities-command.ts (+ capability entry for update flags if the registry requires it). +- skills/ocx surface regenerated (bun run skill:surface); structure doc owning src/update + manifest; + docs-site reference/cli/lifecycle.md section (English). +- tests: tests/update/update-orchestrated-plan.test.ts (decision matrix incl. lidge mismatch, + desktop-app, source, mise, unknown, serving unknown, ownership refused, up-to-date, downgrade, pin), + tests/update/update-orchestrated-apply.test.ts (exit 0/10/11/12 classification, stdout = 1 JSON, + fake child runner + temp home), launcher routing test (plan never runs npm self-update; fake npm + on PATH in temp home), tests/cli capabilities contracts/--contracts; real subprocess + `bun src/cli/index.ts update --plan --json` in a temp OPENCODEX_HOME. Layout registrations in + scripts/test-layout + tests/fixtures/test-layout-expected*.json. + +## Out of scope +desktop/ Rust, sync fanout (L2), GOAT (L3), releases. No real home, service, desktop app restart. + +## Verification +bun run typecheck; focused new/changed tests; bun run test:changed; bun run structure:check; +bun run skill:surface:check; bun run privacy:scan; bun run lint:gui not needed (no gui/). +PR to dev, exact-head CI per job, fresh terra xhigh review PASS, squash merge --match-head-commit. + + +## Audit r1 folds (terra xhigh FAIL → revised) + +A1 Passive entry. bin/ocx.mjs recognizes orchestrated argv (`update` with --plan/--yes+--json, any + malformed variant of them, and `capabilities`) BEFORE the boot-restore probe (bin/ocx.mjs:1299) and + resolves Bun with allowInstall:false; src/cli/root.ts skips the Codex shim auto-repair (root.ts:156) + for the same argv. Missing Bun → plan JSON reason "plan-unavailable" (exit 0) / apply exit 10. + Tests: recoverable backup untouched, placeholder Bun not installed, eligible shim repair not run. +A2 Identity bound to mutation. The apply child gets internal flags + --orchestrated-expect + and --orchestrated-result . Both legacy lanes re-run the serving-identity check inside their + existing mutation lease immediately before stop and again before replacement (Bun lane: + withUpdateOwnershipLease in runUpdate; Node lane: acquireOwnershipMutationLease in + runPackageManagerSelfUpdate). Change before stop → write {phase:"refused-before-mutation"} and exit + → parent exit 10. Change after stop → existing recoverStoppedRuntime, outcome "failed" → 12. + Deterministic tests: takeover between plan and stop, PID reuse (same pid, different process start / + command), different serving root. +A3 Runtime presence is tri-state via existing liveness evidence (proxy-liveness / probeProxyLiveness): + absent = no valid record AND configured endpoint proven dead; live = record pid == /healthz pid on the + record's hostname:port; anything else (unreadable record, timeout, pid mismatch, pidless/legacy health, + live configured endpoint without matching record) = unknown → reason serving-install-unknown. +A4 Exact pin. The apply child always receives --version (never --tag) in npm, pnpm + and Bun lanes; each lane keeps its integrity pre-flight for that exact version. Tests: tag moves + between plan and apply → installs planned version; pin reaches npm/pnpm/bun argv. +A5 Outcome evidence comes from the installers, not readback alone. Lanes write the --orchestrated-result + file at existing decision points: npm transactionalNpmUpdate(tx.phase/rolledBack), pnpm + runPnpmGlobalUpdate({ok,path,activePath,rolledBack}), Bun lane install status. Absent/garbled file → + 12. rolledBack=true only from installer-verified rollback (+ runtime restored when it was live) → 11. + Pre-mutation refusal → 10 with rolledBack=false. Post-success runtime readback is bound to the same home + and the installer-reported active root (pnpm may switch activePath): healthz pid == record pid, + serving identity root == active root, version == target. exit 0 requires applied && healthy; + applied && !healthy → 12 error "runtime-unhealthy". +A6 Identity matching without guessing. Live process evidence: Linux /proc//cmdline split on NUL + (preserve boundaries); macOS executable via existing processIdentity (comm=) plus `ps -ww -o command=` + string; Windows Win32_Process ExecutablePath + CommandLine via the existing bounded reader. A census + record (serving-runtimes.json, relaunch prefix = record.command, live command = prefix + "start …") + matches only if realpath(executable) == realpath(command[0]) and the live args begin with the record's + remaining prefix (Linux: element-wise; macOS/Windows: the prefix rendered unquoted and quoted must be a + whole-token prefix of the string). Exactly one matching record with version == healthz version is + required; zero or several → serving-install-unknown. servingRoot derives from the matched record + (exe for standalone; of /src/cli/index.ts). Tests: spaces, symlinks, Windows quoting, + standalone, ambiguous duplicates. +A7 One stdout owner. Node launcher driver (npm/pnpm apply) and the Bun handler (plan, other apply) own + stdout from entry to exit: progress → stderr, every failure path (Bun missing, plan-child non-zero / + malformed / >64 KiB, spawn failure, signal, uncaught error) prints exactly one JSON document. Before + mutation → plan "plan-unavailable" (exit 0) or result exit 10; after the update child started → 12. + Tests run the real launcher subprocess against a temp npm-shaped package and fake npm/pnpm on PATH, + plus desktop standalone (installer desktop-app). version-skew notice already skips --json. +Also: update all structure owners touched (launcher: codex-cli-update.md, ops/desktop-supervision.md; +CLI and update owners per structure/INDEX.md); PR gets ci:full (subprocess/read-as-data coverage); +core–Lab boundary unaffected (lazy imports only). New additive reason code "plan-unavailable" sent to L3. + + +## Audit r2 folds (supersede the matching A-items above where they conflict) + +B1 (A1) Capability discovery reflects the CLI that handles update. `update` is already excluded from + Desktop handoff (src/lib/desktop-cli-handoff.mjs:9); add `capabilities` invoked with --contracts to the + same exclusion so a package launcher answers for itself and never hands off to an older bundled CLI. + The desktop terminal shim (~/.opencodex-desktop/bin/ocx) runs the bundled CLI directly, which then + answers for itself (and plans desktop-app). root.ts skips shim auto-repair for `capabilities`. + Tests: handoff record present + `capabilities --contracts --json` stays local; update stays local. +B2 (A2) Pre-mutation check sits at the first mutation choke point, BEFORE tray handoff + (src/update/index.ts:524 region, bin/ocx.mjs:759 region): re-verify home, cliRoot, servingRoot and + live runtime pid against --orchestrated-expect; on mismatch write outcome phase "refused" and exit + without touching tray/runtime/package. The second check is post-stop, before replacement: home and + cliRoot unchanged and runtime liveness proven dead (the existing replacementLiveness === "dead" + gate); the original pid is expected to be gone. +B3 (A3) A valid record whose pid is dead counts as unknown (serving-install-unknown) even if the endpoint + is dead. Conservative by design; documented with remedy "run ocx start or ocx stop to settle state". +B4 (A5/A7) Outcome by phase, with independent verification. The child writes --orchestrated-result + atomically: {phase:"preflight"} at entry (write failure → exit before mutation); {phase:"mutating"} + immediately before the first tray/runtime/package mutation (write failure → abort before it); + final {phase:"installed", activeRoot} or {phase:"failed", installerRolledBack:boolean}. + Parent precedence (also on catchable signals SIGINT/SIGTERM/SIGHUP; SIGKILL has no guarantee): + - plan refused → 10. + - outcome missing/unreadable → 12 (cannot prove no mutation). + - last phase preflight or refused, child non-zero → 10 (no mutation), error carries the cause. + - phase mutating/failed → independent verification of the install root the plan named (pnpm: the + owner-resolved active path): package.json version == fromVersion AND bounded `/bin/ocx.mjs + --version` (standalone: exe --version) == fromVersion AND, when a runtime was live before, a live + runtime bound to the same home/root (B5) → 11; rolledBack = installerRolledBack && verified; + otherwise 12. + - phase installed, child exit 0 → verify activeRoot version + launcher probe == target; runtime readback + (B5) when restartRequired → 0 applied=true healthy=true; any verification miss → 12 (applied reflects + the install verification, error "runtime-unhealthy" or "install-unverified"). +B5 (A6) Serving identity is self-reported, argument-preserving. The runtime writes + command: currentServingCommand() (absolute relaunch prefix, src/config/serving-runtimes.ts:50) into + runtime-port.json next to pid/port (validators ignore unknown fields, so old readers are unaffected). + Live runtime = record.pid == /healthz pid on the record endpoint; servingRoot derives from + record.command (standalone exe → exe; [bun, /src/cli/index.ts] → ). No ps/CommandLine + parsing is used to PROVE identity. Without record.command (older runtime): if the live process's + executable (processIdentity comm= on macOS, /proc exe on Linux, Win32 ExecutablePath) realpath differs + from this CLI's own runtime executable → cli-not-serving-install (refusal is the safe direction; a pid + race can only cause a false refusal); otherwise serving-install-unknown. Census matching is dropped. + lidge (2.83.0 runtime, no record.command, different bun) → cli-not-serving-install or + serving-install-unknown; both refuse without touching the npm install. +B6 (A7) Single stdout owner: orchestrated update/capabilities never take Desktop handoff (B1), so the + package launcher (npm/pnpm apply driver) or the Bun handler owns stdout from entry to exit. + + +## Audit r3 folds (supersede B4/B5 where they conflict) + +C1 Attested serving identity. Live runtime = the record listener proves possession of the record's + attestationSecret via the existing proveLiveProxyOwnedByHome / attestFencedIdentity path + (src/server/proxy-liveness.ts:204) — only "proven" counts; "refuted"/"indeterminate" → unknown. + The record is read before and after the proof and must be byte-identical (pid, port, hostname, secret, + command); servingRoot derives from that record's command. The same attested check is re-run under + the mutation lease before tray handoff. The Node lane cannot run the TS proof in-process, so it calls a + passive Bun probe subprocess (hidden `__update-orchestrated-identity`, same pattern as + `__update-home-probe`/service-home-probe-entry.ts, bin/ocx.mjs:150) that exits before any mutation. + Tests: stale record + reused pid (proof refuted), record replaced during the probe, no secret. +C2 No launcher execution for verification. Version/tree verification is passive file reads in-process + (readPackageManifestVersionAt / packageManifestPathIn, src/lib/package-tree-integrity.ts:87/129); no + `--version` subprocess, no Desktop handoff, no backup restore, no Bun install. +C3 Active-tree verification uses installer-specific evidence before exit 11 or 0: npm — required package + files present (package.json, bin/ocx.mjs, src/cli/index.ts, bundled bun dir) + no leftover transactional + backup sibling for that root (read-only check of the transactional-install naming); pnpm — read-only + owner re-resolution (resolvePnpmGlobalOwner / readPnpmGlobalPackage) confirms the active group path, + its manifest version and the launcher shim target; bun global — required files + manifest. Any miss → + 12. Test: damaged tree that keeps package.json version → 12. +C4 Signals: on SIGINT/SIGTERM/SIGHUP the parent forwards the signal to the child, waits for confirmed child + exit (bounded 60 s), then reads the final atomic outcome; child still running or outcome uncertain → 12. + Deterministic test: signal delivered at the preflight→mutating transition. +C5 Exit classification (final): + 0 — applied and verified (installed + tree + runtime when restartRequired), or plan reason "up-to-date". + 10 — a plan refusal: the parent's plan reason (any reason except up-to-date), or the child's + lease-time identity re-check refusing (phase "refused") — the plan recomputed at the boundary. + 11 — the update failed and the previous version is verified active (C3) with the runtime restored when it + was live; covers preflight failures (child exited before "mutating") and installer rollbacks. + rolledBack=true only when the installer reported a rollback AND C3 verification passed. + 12 — everything else: outcome missing/garbled, verification miss, unconfirmed child termination, + installed-but-runtime-unhealthy. + 64 — usage. + + +## Audit r4 residuals (NEAR-PASS) — folded as implementation requirements +D1 npm success retains a backup sibling by design (transactional-install.mjs:535): a retained backup is + not failure; verify the active tree itself. +D2 Tree verification reuses/matches the installer verifier (transactional-install.mjs:107: Bun executable + present and complete, dependencies, launcher, source) — tests: truncated/missing Bun, missing dependency, + missing source file → 12. +D3 pnpm rolledBack flag can mean "previous package simply remained active" (pnpm-global-install.mjs:544): + result.rolledBack=true only for an actual rollback action; unchanged-active is rolledBack=false (exit 11 + when verified). + + +## L3 additive requests (accepted 2026-11-02) +E1 plan JSON adds "planToken": base64url sha256 (43 chars, matches ^[A-Za-z0-9_-]{16,128}$) over a canonical + JSON of {currentVersion, targetVersion, installer, cliRoot, servingRoot, runtimeOwner, runtime:{pid, port, + hostname, command} | null} — never the attestation secret. Apply accepts --expect-plan ; it + recomputes its plan and, if the token differs, exits 10 before any mutation (error "plan-changed"). + The child's lease-time identity re-check compares against the same bound fields. +E2 plan JSON adds "updateInFlight": boolean. true when the update ownership/mutation lease is held by a live + process, or the home-scoped orchestrated marker (/update-orchestrated.json {pid, phase, startedAt}, + written by the apply child at preflight/mutating and cleared/finalized at the end) shows phase + preflight|mutating with a live pid; true when this cannot be determined (fail closed); false only on + positive evidence. Read-only probe (no lease acquisition that could block a real update). + + +## L3 additive request E3 (accepted 2026-11-02): deadline fencing +E3 apply accepts --not-after (positive safe integer; invalid → 64). At the B2 choke point (before the first + tray/runtime/package mutation) and immediately before writing the "mutating" marker, now > notAfter → exit 10 + error "deadline-passed", nothing touched. Contract constant ORCHESTRATED_MUTATION_BOUND_MS = 900000 (15 min); + plan JSON adds "mutationBoundMs": 900000. A child that started mutating arms a watchdog at notAfter + bound + (or start + bound without --not-after): on expiry it records outcome/marker phase "overrun" (→ parent 12) but + does NOT kill an in-progress package transaction (a mid-swap abort is the unsafe direction); while that child + lives, updateInFlight stays true, so updateInFlight=false remains the authoritative "no further mutation" fence. + + +## L3 requests E4/E5 (accepted 2026-11-02) +E4 Deadline↔visibility ordering (contract wording): the apply child (1) acquires the update ownership lease, + (2) publishes marker phase "mutating" with its pid, THEN (3) performs the final --not-after, --expect-plan and + attested identity checks; on failure it rewrites the marker to "refused", releases the lease and exits 10. + Thus at the last deadline check updateInFlight is already observably true, and lease + marker stay held + until no further mutation can occur (final outcome written before the lease is released). +E5 sync↔update exclusion (L1 implements; L2 rebases onto it): `ocx sync` (all variants incl. --local-only and the + Child-side --expect-link run) first runs the read-only update-in-flight probe (same as plan.updateInFlight); + in flight or undeterminable → no changes, stderr code "update-in-flight", exit 7. Placed at the sync command + entry before any local sync, expectation check or fan-out. + + +## L3 request E6 (accepted 2026-11-02): atomic sync↔update exclusion (supersedes E5's probe-only guard) +E6 One dedicated cross-process mutex shared by `ocx sync` and orchestrated apply: same primitive as the ownership + mutation lease (src/service/ownership-mutation-lease.mjs, dead-owner recovery, non-blocking try-acquire) but a + separate lease file in the home, recording holder kind (sync|update) and pid — kept separate from the ownership + lease so sync's own start/stop/restart paths cannot deadlock against it. + - `ocx sync` (every variant) try-acquires it before its first mutation and holds it to the end; held by an update + or undeterminable → no changes, stderr "update-in-flight", exit 7. + - Apply child step ① try-acquires it (then the ownership lease, then marker "mutating", then E4 checks); held by + sync → exit 10 error "sync-in-progress", nothing touched; held by another update → exit 10 "update-in-flight". + Held until the final outcome is written. + - updateInFlight = true iff an update holds the mutex or the update ownership lease, or the marker shows + preflight|mutating with a live pid, or undeterminable. Sync holding alone → false. + - Each machine has its own mutex; a Home fan-out's Child-side `ocx sync` takes the Child's mutex. + Tests: sync holds (paused) → apply 10 sync-in-progress untouched; apply holds → sync 7; dead holder recovered. + + +## Implementation resolutions (2026-11-02, after slice 3) +F1 The existing lanes release the ownership lease around service-manager restarts (#5760; src/update/index.ts:626, + bin/ocx.mjs:1043) — keep that. E4's "held until no further mutation" is carried by the dedicated sync/update mutex + (E6) and the marker, which the apply child holds from step ① until its final outcome is written, across the whole + lane including service restart/recovery. `ocx start` never takes that mutex, so no deadlock. +F2 The synchronous npm transaction blocks the child's event loop, so the overrun watchdog runs in the PARENT driver: + at notAfter+bound (or start+bound) with the child still alive, the parent emits result exit 12 error "overrun" and + exits without killing the child; the child's marker stays preflight|mutating with a live pid, so updateInFlight + stays true until the child finishes (supersedes E3's "child records overrun"). + +## Review r3 resolutions (2026-11-02) +G1 Admission refuses when plan.updateInFlight is true (exit 10 "update-in-flight"); the child, after acquiring the mutex, + re-reads the marker and proceeds only if it is positively free (finalized or absent); otherwise refused, marker untouched. +G2 Legacy `ocx update` (both lanes, interactive and package-only workers) also takes the sync/update mutex as "update" for + its full mutation lifetime and publishes the marker; held by sync → refuse before any mutation with a clear message. +G3 Fail-closed fence by time bound: publish the mutating marker with fenceUntil = startedAt + 900000 before launching an + installer. A dead worker, timeout, killed group, or unconfirmed exit retains the fence; live or uninspectable recorded + installers remain active independently. A normally exited installer with its POSIX process group confirmed gone or + Windows Job Object confirmed empty clears the fence on finalization. A POSIX descendant that escapes the group can + outlive a normally exiting installer and mutate after the fence clears; this residual is accepted. Windows uses the + Job Object supervisor. A timed-out escaped POSIX descendant can also outlive the 15-minute bound. + +## Review r8 resolution +The sync launcher atomically publishes the spawned child PID in its lease. Reclamation requires both holder and delegate to be dead; a new Bun child verifies its own PID before mutation. An older Desktop CLI cannot verify it, so launcher SIGKILL between spawn and delegate publication leaves a residual window in which that child can outlive the stale lease. diff --git a/docs-site/src/content/docs/reference/cli/lifecycle.md b/docs-site/src/content/docs/reference/cli/lifecycle.md index 97695eed0c7..9dc04b30b64 100644 --- a/docs-site/src/content/docs/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/reference/cli/lifecycle.md @@ -555,6 +555,8 @@ Fan-out never requests a Codex app or app-server restart on a Child. Use GOAT or still restart its own OpenCodex client runtime after applying changed Home settings. If the Home times out and stops its local SSH process, a remote sync already running may continue on the Child. +If an update is in flight or the shared update/sync mutex cannot be determined, sync changes nothing, reports `update-in-flight`, and exits 7. If another sync holds the mutex, it reports `sync-in-progress` and exits 1; a Home counts that Child as failed and exits 6 when its own sync succeeded. With `--json`, either refusal prints one result document with the Home skipped and the refusal reason in `fanout.reason`. + An explicitly requested restart also runs after a successful committed `config.toml` change, even if the catalog and cache bytes are unchanged. A configuration-only no-op, refusal, preflight, or rolled-back write does not trigger it. Without a restart flag, sync never automatically restarts Codex. On a Remote Link Child, `ocx sync` also applies the Home's Codex settings and, when the client runtime @@ -1160,6 +1162,45 @@ package registry or install an update. ### `ocx update [--tag latest|preview]` +#### Orchestrated update + +Automation can discover support with `ocx capabilities --contracts --json`; the +`contracts` array contains `update.orchestrated/1`. The contracts-only option +cannot be combined with `--route` or `--mutating-only`. + +```bash +ocx update --plan --json [--tag latest|preview | --version ] +ocx update --yes --json [--version ] [--expect-plan ] [--not-after ] +``` + +Plan emits one `ocx.update.plan/1` JSON object: `currentVersion`, `targetVersion`, +`installer`, `runtimeOwner`, `servingPath`, `cliPath`, `canApply`, optional `reason`, +`restartRequired`, `planToken`, `updateInFlight`, and `mutationBoundMs`. A plan is +read-only. Reasons are `desktop-app-owned`, `source-checkout`, `mise-managed`, +`installer-unknown`, `plan-unavailable`, `serving-install-unknown`, +`cli-not-serving-install`, `runtime-ownership-refused`, `target-unresolved`, +`downgrade-refused`, and `up-to-date`. `desktop-app-owned` directs updates to the +Desktop app; uncertain serving identity refuses rather than guessing. Run `ocx start` +or `ocx stop` to settle a stale runtime record before planning again. + +Apply emits one `ocx.update.result/1` object with `applied`, `fromVersion`, +`toVersion`, `installer`, `restarted`, `healthy`, `rolledBack`, and an optional +`error`. Pass the plan's `planToken` as `--expect-plan` to refuse with +`plan-changed` if the selected install or runtime identity changes. `--not-after` +is a positive safe integer Unix timestamp in milliseconds; mutation is refused with +`deadline-passed` after that time. `mutationBoundMs` is 900000 (15 minutes): an +overrun reports an uncertain result without killing an in-progress transaction. +`updateInFlight` remains true while an update may still mutate, including when its +state cannot be determined; a sync alone does not set it. A concurrent sync can +refuse apply with `sync-in-progress`, and another update with `update-in-flight`. + +Orchestrated apply exits 0 when verified or already up to date, 10 on refusal, +11 when the update failed but the previous version is verified active (including +the runtime when required), 12 when the outcome is unverified or still running, +and 64 for invalid usage. `rolledBack` is true only when an actual installer +rollback and its verification succeeded. A plan command emits its plan with exit 0; +the `canApply` and `reason` fields describe eligibility. + Compiled standalone installs, including the Windows MSI Desktop bundle, are updated through **Check for Updates…** in OpenCodex Desktop, or by reinstalling the standalone binary from [GitHub Releases](https://github.com/lidge-jun/opencodex/releases). `ocx system update check` reports `installer: "standalone"`, `canUpdate: false`, and `reason: "standalone_install"` with that guidance. `ocx update` exits unsuccessfully with the same hint; it does not run a package-manager update for the compiled executable. A genuine source checkout still reports `installer: "source"` and `reason: "source_checkout"`. When OpenCodex is installed through mise, this command exits unsuccessfully before stopping the proxy or changing package files and shows `mise upgrade `, using the verified local mise alias. Update checks remain available and report the installation as externally managed. An unreadable or inconsistent mise ownership record fails closed without guessing a tool name, and `--tag preview` never changes mise's configured selection. diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index bf9619797cc..1621c385242 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -1841,7 +1841,7 @@ "update-desktop-badge.test.ts": "update", "update-desktop-owner.test.ts": "update", "update-supervised-recovery.test.ts": "update", "update-job.test.ts": "update", "update-recovery-host-free.test.ts": "update", "update-job-supervised-restart.test.ts": "update", "update-standalone.test.ts": "update", "update-worker-launch.test.ts": "update", "update-notify.test.ts": "update", "update-npm-cache-preflight.test.ts": "update", - "update-npm-invocation.test.ts": "update", "update-npm-timeout.test.ts": "update", "update-npm-supervisor-exit.test.ts": "update", "update-mise-launcher-target.test.ts": "update", + "update-orchestrated-session.test.ts": "update", "update-orchestrated-entry.test.ts": "update", "update-orchestrated-apply.test.ts": "update", "update-orchestrated-arguments.test.ts": "update", "update-orchestrated-plan.test.ts": "update", "update-sync-mutex.test.ts": "update", "update-orchestrated-identity.test.ts": "update", "update-orchestrated-token.test.ts": "update", "update-npm-invocation.test.ts": "update", "update-npm-timeout.test.ts": "update", "update-npm-supervisor-exit.test.ts": "update", "update-mise-launcher-target.test.ts": "update", "update-mise.test.ts": "update", "update-mise-node-runtime.test.ts": "update", "update-pnpm.test.ts": "update", "update-refresh.test.ts": "update", diff --git a/skills/ocx/references/01_management_surface.md b/skills/ocx/references/01_management_surface.md index 45326e7a834..4a55a25f971 100644 --- a/skills/ocx/references/01_management_surface.md +++ b/skills/ocx/references/01_management_surface.md @@ -30,7 +30,7 @@ These answer in the CLI head and never reach the proxy, so they work with nothin | [accounts](01_surface_accounts.md) | 42 | | [agents-routing](01_surface_agents-routing.md) | 68 | | [integrations](01_surface_integrations.md) | 41 | -| [observe-system](01_surface_observe-system.md) | 98 | +| [observe-system](01_surface_observe-system.md) | 99 | | [access-remote](01_surface_access-remote.md) | 33 | | [lab](01_surface_lab.md) | 21 | @@ -127,6 +127,10 @@ Original invocation order. These headings preserve links to the previous single- [State-changing task](01_surface_access-remote.md#ocx-connect-rotate) +### `ocx update` + +[State-changing task](01_surface_observe-system.md#ocx-update) + ### `ocx capabilities` [Read-oriented task](01_surface_lifecycle.md#ocx-capabilities) @@ -1517,6 +1521,6 @@ Original invocation order. These headings preserve links to the previous single- ## Counts -- declared capabilities: 367 -- of those, state-changing: 225 +- declared capabilities: 368 +- of those, state-changing: 226 - head-resolved invocations: 2 diff --git a/skills/ocx/references/01_surface_lifecycle.md b/skills/ocx/references/01_surface_lifecycle.md index ab9ed73b5bd..a0c3e3ee5db 100644 --- a/skills/ocx/references/01_surface_lifecycle.md +++ b/skills/ocx/references/01_surface_lifecycle.md @@ -106,6 +106,7 @@ State-changing: yes. JSON mode: `payload`. | `--expect-hub-key` | string | Sync only when this machine is a hub client connected with this API key id; otherwise exit 5 with nothing changed. | - The Aside refresh uses the live server; other catalog synchronization also performs local work. +- An update in flight or an unavailable update/sync mutex refuses without changes: update-in-flight, exit 7. Another sync reports sync-in-progress, exit 1. - A current Home catalog fans out to linked Children. Fan-out never requests a Codex app or app-server restart on a Child; use GOAT or ocx sync --restart-codex there. Applying changed Home settings may restart the Child's own OpenCodex client runtime. - --expect-link/--expect-hub-key are checked under the lock that selects the sync path. A mismatch writes nothing, never falls back to local providers, exits 5, and ends stderr with {"phase":"child_link_mismatch"|"hub_client_mismatch","reason":...}; reasons are disconnected, invalid_state, disconnect_pending, pending_operation, hub_client, link_client, other_link and other_key. Usage errors exit 2. diff --git a/skills/ocx/references/01_surface_observe-system.md b/skills/ocx/references/01_surface_observe-system.md index d3cea04a9b8..a2e086b04e7 100644 --- a/skills/ocx/references/01_surface_observe-system.md +++ b/skills/ocx/references/01_surface_observe-system.md @@ -8,7 +8,27 @@ Use these declarations to choose a task, then check its flags and authority before execution. Non-mutating probes may still contact providers, consume quota or refresh caches. -Declared capabilities: 98. +Declared capabilities: 99. + +### `ocx update` + +Plan or apply an OpenCodex update. + +State-changing: yes. JSON mode: `envelope`. + +Drives no management route. + +| Flag | Value | Meaning | +|---|---|---| +| `--plan` | boolean | Preview an orchestrated update with --json. | +| `--yes` | boolean | Apply an orchestrated update with --json. | +| `--json` | boolean | Emit a versioned plan or result. | +| `--tag` | string | Select latest or preview for the legacy update or plan. | +| `--version` | string | Select an exact version for a plan or apply. | +| `--expect-plan` | string | Require the apply plan to match this planToken. | +| `--not-after` | string | Refuse mutation after this Unix millisecond deadline. | + +- Orchestrated exit codes: 0 verified or up-to-date; 10 refused; 11 previous version verified; 12 uncertain; 64 usage. ### `ocx companion` diff --git a/src/cli/capabilities-base.ts b/src/cli/capabilities-base.ts index 0467719de70..5ad0304e337 100644 --- a/src/cli/capabilities-base.ts +++ b/src/cli/capabilities-base.ts @@ -215,6 +215,23 @@ export const CAPABILITIES: readonly Capability[] = [ "A rotation left pending by a crash is resumed here — startup and status stop rather than guess which key generation is live.", ], }, + { + command: ["update"], + summary: "Plan or apply an OpenCodex update.", + routes: [], + flags: [ + { name: "--plan", value: "boolean", summary: "Preview an orchestrated update with --json." }, + { name: "--yes", value: "boolean", summary: "Apply an orchestrated update with --json." }, + { name: "--json", value: "boolean", summary: "Emit a versioned plan or result." }, + { name: "--tag", value: "string", summary: "Select latest or preview for the legacy update or plan." }, + { name: "--version", value: "string", summary: "Select an exact version for a plan or apply." }, + { name: "--expect-plan", value: "string", summary: "Require the apply plan to match this planToken." }, + { name: "--not-after", value: "string", summary: "Refuse mutation after this Unix millisecond deadline." }, + ], + mutates: true, + json: "envelope", + details: ["Orchestrated exit codes: 0 verified or up-to-date; 10 refused; 11 previous version verified; 12 uncertain; 64 usage."], + }, { command: ["capabilities"], summary: "List the declared CLI capabilities and the management routes they drive.", @@ -765,6 +782,7 @@ export const CAPABILITIES: readonly Capability[] = [ json: "payload", details: [ "The Aside refresh uses the live server; other catalog synchronization also performs local work.", + "An update in flight or an unavailable update/sync mutex refuses without changes: update-in-flight, exit 7. Another sync reports sync-in-progress, exit 1.", "A current Home catalog fans out to linked Children. Fan-out never requests a Codex app or app-server restart on a Child; use GOAT or ocx sync --restart-codex there. Applying changed Home settings may restart the Child's own OpenCodex client runtime.", "--expect-link/--expect-hub-key are checked under the lock that selects the sync path. A mismatch writes nothing, never falls back to local providers, exits 5, and ends stderr with {\"phase\":\"child_link_mismatch\"|\"hub_client_mismatch\",\"reason\":...}; reasons are disconnected, invalid_state, disconnect_pending, pending_operation, hub_client, link_client, other_link and other_key. Usage errors exit 2.", ], diff --git a/src/cli/capabilities-command.ts b/src/cli/capabilities-command.ts index 952e38807c6..112eede2661 100644 --- a/src/cli/capabilities-command.ts +++ b/src/cli/capabilities-command.ts @@ -50,8 +50,8 @@ function renderHuman(caps: readonly Capability[], includeHead: boolean): void { export async function runCapabilities(argv: string[]): Promise { const args = [...argv]; const json = takeFlag(args, "--json"); - const mutatingOnly = takeFlag(args, "--mutating-only"); const contracts = takeFlag(args, "--contracts"); + const mutatingOnly = takeFlag(args, "--mutating-only"); const route = takeValueFlag(args, "--route"); if (args.length > 0 || (route !== undefined && route.trim().length === 0) || (contracts && (mutatingOnly || route !== undefined))) { diff --git a/src/cli/capability-contracts.ts b/src/cli/capability-contracts.ts index ed7ef7e988b..d4f9cba73c7 100644 --- a/src/cli/capability-contracts.ts +++ b/src/cli/capability-contracts.ts @@ -1 +1,2 @@ -export const CAPABILITY_CONTRACTS = ["sync.home-fanout/1"] as const; +/** Versioned machine contracts implemented by this CLI. */ +export const CAPABILITY_CONTRACTS = ["sync.home-fanout/1", "update.orchestrated/1"] as const; diff --git a/src/cli/codex-shim-autorestore.ts b/src/cli/codex-shim-autorestore.ts index 8ea964ac3c7..bac12067179 100644 --- a/src/cli/codex-shim-autorestore.ts +++ b/src/cli/codex-shim-autorestore.ts @@ -1,5 +1,6 @@ import { autoRestoreCodexShim, autoRestoreCodexShimAsync } from "../codex/shim"; import { codexShimAutoRestoreEnabled, readConfigDiagnostics } from "../config"; +import { isOrchestratedUpdateArgv } from "../update/orchestrated-arguments.mjs"; export interface CodexShimAutoRestoreCliDeps { env: NodeJS.ProcessEnv; @@ -18,6 +19,10 @@ const DEFAULT_DEPS: CodexShimAutoRestoreCliDeps = { /** Identify command namespaces whose execution must not trigger automatic shim repair. */ export function skipsCodexShimAutoRestore(command: string | undefined, args: string[]): boolean { if (command === "uninstall" || command === "remove") return true; + // Contract discovery and orchestrated update must validate before any repair. + if (command === "capabilities") return true; + if (command === "update" && isOrchestratedUpdateArgv(args)) return true; + if (command === "sync") return true; if (command === "status" || command === "doctor") return true; // The launcher owns shim handoff after classifying routing, including native fast paths. if (command === "codex") return true; @@ -38,10 +43,6 @@ export function skipsCodexShimAutoRestore(command: string | undefined, args: str // The desktop's approval-bound stop must validate its snapshot before any unrelated // CLI repair changes the installation it was approved against. if (command === "stop" && args.some(arg => arg.startsWith("--expect-"))) return true; - // A pinned sync (#7694) must change nothing when its expected Home or hub key does not hold, - // so the root preflight may not repair the shim first; the sync runner repairs it only after - // the locked identity check passed (runCodexShimAutoRestore in src/cli/dispatch.ts). - if (command === "sync" && args.some(arg => /^--expect-(link|hub-key)(=|$)/.test(arg))) return true; // The entire updater-inspection namespace is zero-effect, including malformed // or future actions. A later `apply` implementation must own its preflight. if (command === "system" && args[1] === "codex-cli-update") return true; diff --git a/src/cli/dispatch.ts b/src/cli/dispatch.ts index e4c405fddba..ae66dd7d7b8 100644 --- a/src/cli/dispatch.ts +++ b/src/cli/dispatch.ts @@ -403,7 +403,7 @@ const commandRunners: Record = { const { handleLogoutCommand } = await import("./logout-command"); return handleLogoutCommand(deps.args.slice(1), { findLiveProxy: deps.findLiveProxy }); }, - sync: async deps => (await import("./sync-command")).runSyncCommand(deps), + sync: async deps => (await import("./sync-update-guard")).withSyncUpdateGuard(async () => (await import("./sync-command")).runSyncCommand(deps), deps.args), v2: async deps => { const { cmdV2 } = await import("./v2"); return await cmdV2(deps.args.slice(1), { runtimeApi: { findLiveProxy: deps.findLiveProxy } }, async () => (await deps.findLiveProxy())?.port); @@ -610,6 +610,14 @@ const commandRunners: Record = { return 0; }, update: async deps => { + const { isOrchestratedUpdateArgv, parseOrchestratedChildArgs } = await import("../update/orchestrated-arguments.mjs"); + if (process.env.OCX_UPDATE_ORCHESTRATED_CHILD === "1" && deps.args.slice(1).some(arg => /^--orchestrated-(expect|result)(?:=|$)/.test(arg))) { + const child = parseOrchestratedChildArgs(deps.args.slice(1), process.env); + if (!child.ok) return 64; + await (await import("../update")).runUpdate(child); + return Number(process.exitCode ?? 0); + } + if (isOrchestratedUpdateArgv(deps.args.slice(1))) return (await import("../update/orchestrated-entry")).runOrchestratedUpdate(deps.args.slice(1)); // `ocx update --help` must print usage and exit WITHOUT side effects — running the // real self-update stops the proxy and drops in-flight routed streams (issue #168). if (hasHelpFlag(deps.args.slice(1))) { diff --git a/src/cli/index.ts b/src/cli/index.ts index 038b5275275..e2f98925666 100755 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -210,6 +210,7 @@ async function refreshOwnedRaycastCatalog( } } +if (process.argv[2] === "__update-orchestrated-identity") process.exit(await (await import("../update/orchestrated-identity-probe-entry")).runIdentityProbe(process.argv.slice(2))); if (process.argv[2] === "start" && process.env.OCX_SERVICE) startServiceLogging(join(getConfigDir(), "service.log")); const updateRestartChild = admitUpdateRestartChild(process.argv.slice(2)); initializeNodeLauncherContext(); @@ -606,6 +607,7 @@ async function handleStart(options: { block?: boolean } = {}) { port: bound.port, hostname: bound.config.hostname, attestationSecret: bound.localAttestationSecret, + command: currentServingCommand(), ...siblingRuntimeField(), }); updateRestartChild?.complete(); }, stopBound: bound => bound.server.stop(true), diff --git a/src/cli/registry.ts b/src/cli/registry.ts index 0fa007974ae..53db87d00e0 100644 --- a/src/cli/registry.ts +++ b/src/cli/registry.ts @@ -189,6 +189,7 @@ export const CLI_COMMANDS: CliCommandEntry[] = [ "A current Home catalog fans out to linked Children; --local-only disables fan-out and --json emits the result. Partial fan-out exits 6.", "Fan-out never requests a Codex app or app-server restart on a Child; use GOAT or ocx sync --restart-codex on the Child. The Child's pinned sync may restart its OpenCodex client runtime after applying changed Home settings.", "After writing the catalog, warns if long-lived Codex app-server processes are still running.", + "An update in flight or an unavailable update/sync mutex refuses without changes: update-in-flight, exit 7. Another sync reports sync-in-progress, exit 1.", "--restart-codex restarts the app-servers AND fully quits and relaunches the Codex desktop app on macOS, Linux and Windows, after catalog/cache writes or a committed configuration change. It ends live conversations.", "--restart-app-server-only keeps the narrow behaviour: SIGTERM to matching app-server / code-mode-host processes, desktop app left running. It wins over --restart-codex when both are given.", "--restart-desktop-app is a deprecated alias of --restart-codex and prints a notice.", @@ -292,8 +293,12 @@ export const CLI_COMMANDS: CliCommandEntry[] = [ }, { name: "update", - usage: "ocx update [--tag latest|preview]", + usage: "ocx update [--tag latest|preview] | --plan --json [--tag latest|preview | --version ] | --yes --json [--tag latest|preview | --version ] [--expect-plan ] [--not-after ]", summary: "Update opencodex. Preview installs stay on the preview tag unless overridden.", + details: [ + "--plan --json previews an orchestrated update; --yes --json applies it. --expect-plan binds apply to the returned planToken; --not-after sets a Unix millisecond mutation deadline.", + "Orchestrated exit codes: 0 verified or up-to-date; 10 refused; 11 failed with previous version verified; 12 unverified or still running; 64 invalid usage.", + ], }, { name: "provider", diff --git a/src/cli/root.ts b/src/cli/root.ts index 9b7e3ad5fe8..9d39f9aa7d1 100644 --- a/src/cli/root.ts +++ b/src/cli/root.ts @@ -19,6 +19,7 @@ import { findCommand } from "./registry"; import { printUnknownCommand } from "./help-recovery"; import { noteCredentialArgv, redactSecretArgs } from "./secret-args"; import { maybeNoticeVersionSkew } from "./version-skew-notice"; +import { isOrchestratedUpdateArgv } from "../update/orchestrated-arguments.mjs"; export interface CliHead { kind: "version" | "help" | "ready" | "resolve" | "command"; @@ -41,6 +42,7 @@ export function parseCliHead(argv: string[]): CliHead { const args = argv; // Codex owns its forwarded grammar; wrapper documentation is `ocx help codex`. if (command === "codex") return { kind: "command", command, args }; + if (command === "update" && isOrchestratedUpdateArgv(args.slice(1))) return { kind: "command", command, args }; if (command === "--version" || command === "-v" || command === "version") { return { kind: "version", command, args }; } diff --git a/src/cli/sync-command.ts b/src/cli/sync-command.ts index 304656a1707..c1ae28c6a9b 100644 --- a/src/cli/sync-command.ts +++ b/src/cli/sync-command.ts @@ -31,6 +31,8 @@ export async function runSyncCommand(deps: CliDispatchDeps): Promise { return SYNC_EXPECTATION_USAGE_EXIT; } const expectation = parsedExpectation.expectation; + // The root preflight skips shim repair for every sync so the update/sync mutex is held first. + if (!expectation) await (await import("./codex-shim-autorestore")).runCodexShimAutoRestoreAsync(); const restartScope = readRestartScope(syncArgs, console); // The wire field keeps APP-SERVER-ONLY meaning and is deliberately not widened. A // remote hub must not end a local user's conversations because a field name acquired diff --git a/src/cli/sync-update-guard.ts b/src/cli/sync-update-guard.ts new file mode 100644 index 00000000000..e9b7ec037bd --- /dev/null +++ b/src/cli/sync-update-guard.ts @@ -0,0 +1,18 @@ +import { getConfigDir } from "../config/paths"; +import { acquireSyncGuard, inspectUpdateMarker, inspectUpdateSyncMutex, parentHoldsSyncMutex, refuseSync } from "../update/sync-update-mutex"; + +/** Hold the home-scoped update/sync mutex until the complete sync operation settles. */ +export async function withSyncUpdateGuard(run: () => Promise, args: readonly string[] = []): Promise { + const home = getConfigDir(); + if (process.env.OCX_SYNC_MUTEX_HELD_BY) { + const deadline = Date.now() + 2_000; + while (!parentHoldsSyncMutex(home) && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 20)); + if (!parentHoldsSyncMutex(home)) return refuseSync(inspectUpdateSyncMutex(home) === "sync" ? "sync-in-progress" : "update-in-flight", args); + } + if (parentHoldsSyncMutex(home)) return inspectUpdateMarker(home) === "free" ? await run() : refuseSync("update-in-flight", args); + const lease = acquireSyncGuard(home, args); + if (lease.kind === "refused") return lease.exit; + try { + return await run(); + } finally { lease.release(); } +} diff --git a/src/client/runtime.ts b/src/client/runtime.ts index 81dc2e5d14c..7677170f3ae 100644 --- a/src/client/runtime.ts +++ b/src/client/runtime.ts @@ -5,6 +5,7 @@ import { siblingRuntimeField, withSiblingMarker } from "../codex/sibling-start"; import { issueSiblingHandoff } from "../codex/sibling-handoff"; import { loadConfig } from "../config"; import { removePid, removeRuntimePort, writePid, writeRuntimePort, type RuntimePortState } from "../config/process-state"; +import { currentServingCommand } from "../config/serving-runtimes"; import { installCrashGuards } from "../lib/crash-guard"; import { observeLocalCredentials } from "../local-credentials/runtime-observation"; import { verifiedHomeConnection } from "./link-connection"; @@ -94,7 +95,9 @@ export function clientRuntimeRecord( port: number, attestationSecret: string = createLocalAttestationSecret(), ): RuntimePortState { - return { pid, port, hostname: "127.0.0.1", attestationSecret, ...siblingRuntimeField() }; + let command: string[] | undefined; + try { command = currentServingCommand(); } catch { /* no reliable relaunch identity; update admission fails closed */ } + return { pid, port, hostname: "127.0.0.1", attestationSecret, ...(command ? { command } : {}), ...siblingRuntimeField() }; } export function standaloneRecycleEnv( diff --git a/src/config/process-state.ts b/src/config/process-state.ts index 4ac5191e57c..b7fa2349112 100644 --- a/src/config/process-state.ts +++ b/src/config/process-state.ts @@ -35,6 +35,8 @@ export type RuntimePortState = { pid: number; port: number; hostname?: string; + /** Absolute relaunch prefix written by runtimes that identify their serving install. */ + command?: string[]; /** Per-process proof key; protected by the config directory and never served. */ attestationSecret?: string; /** diff --git a/src/lib/desktop-cli-handoff.d.mts b/src/lib/desktop-cli-handoff.d.mts index 764095f5ae1..f49f8fa8efd 100644 --- a/src/lib/desktop-cli-handoff.d.mts +++ b/src/lib/desktop-cli-handoff.d.mts @@ -16,5 +16,5 @@ export function planDesktopCliHandoff(input?: { recordRead?: DesktopCliRecordRead; selfPaths?: (string | undefined)[]; }, deps?: { stat?: typeof statSync; access?: typeof accessSync; realpath?: (path: string) => string }): DesktopCliHandoffPlan; export function runDesktopCliHandoff(plan: Extract, launch: { - argv: string[]; env: NodeJS.ProcessEnv; proof: string; context: string; + argv: string[]; env: NodeJS.ProcessEnv; proof: string; context: string; onSpawn?: (pid: number) => void; }, deps?: { spawn?: typeof spawn; lstat?: typeof lstatSync; parent?: Pick; platform?: NodeJS.Platform }): Promise; diff --git a/src/lib/desktop-cli-handoff.mjs b/src/lib/desktop-cli-handoff.mjs index ece1a407ce6..2dddccc9daa 100644 --- a/src/lib/desktop-cli-handoff.mjs +++ b/src/lib/desktop-cli-handoff.mjs @@ -10,6 +10,7 @@ export function desktopHandoffExcluded(argv, env = process.env) { const args = argv.filter(arg => !arg.startsWith(PROOF_PREFIX)); return env.OCX_NO_DESKTOP_HANDOFF === "1" || ["update", "uninstall", "remove"].includes(args[0]) + || (args[0] === "capabilities" && args.includes("--contracts")) || (args[0] ?? "").startsWith("__") || isCodexCliUpdateInspectionArgv(["node", "ocx.mjs", ...args]); } @@ -87,6 +88,15 @@ export function runDesktopCliHandoff(plan, launch, deps = {}) { let done = false; const finish = result => { if (done) return; done = true; clear(); resolveExit(result); }; child.once("error", error => finish(spawnFailure(error))); - child.once("exit", (code, signal) => finish({ kind: "exit", code: code ?? 1, signal })); + let delegateError = false; + child.once("exit", (code, signal) => finish(delegateError ? { kind: "error", issue: "spawn-failed" } : { kind: "exit", code: code ?? 1, signal })); + if (child.pid && launch.onSpawn) { + try { launch.onSpawn(child.pid); } + catch (error) { + delegateError = true; + console.error(`opencodex: sync mutex delegate publication failed: ${error.message}`); + try { child.kill(); } catch (killError) { console.error(`opencodex: failed to stop sync child: ${killError.message}`); } + } + } }); } diff --git a/src/service/ownership-mutation-lease.d.mts b/src/service/ownership-mutation-lease.d.mts index 8ee827777ed..7c39a64475c 100644 --- a/src/service/ownership-mutation-lease.d.mts +++ b/src/service/ownership-mutation-lease.d.mts @@ -7,6 +7,11 @@ export interface OwnershipMutationLeaseOptions { readonly joinToken?: string; /** Names the current executable at the recorded PID, identity unverified; uses `ps` on POSIX and omits the default image lookup on Windows. */ readonly processImage?: (pid: number) => string | null; + /** Isolated locks cannot re-enter or inherit ownership delegation. */ + readonly isolated?: boolean; + readonly holderKind?: "sync" | "update"; + /** Explicit canonical lock path for isolated callers with no state-file authority. */ + readonly lockPath?: string; } /** The recorded lease owner, identity unverified, read for diagnostics; never used to reclaim it. */ @@ -14,8 +19,11 @@ export interface OwnershipMutationLeaseHolder { readonly path: string; /** The recorded PID; null when the directory holds no parseable owner. */ readonly pid: number | null; + readonly delegatePid: number | null; + readonly holderAlive: boolean | null; /** Liveness of the current process at the recorded PID; identity is not verified. */ readonly alive: boolean | null; + readonly holderKind: "sync" | "update" | null; /** The current executable at the recorded PID when alive and readable; identity is not verified. */ readonly image: string | null; /** Milliseconds since the owner was written, on the clock stale recovery uses. */ @@ -23,9 +31,10 @@ export interface OwnershipMutationLeaseHolder { readonly record: "complete" | "incomplete" | "empty" | "unreadable"; } -export interface OwnershipMutationLease { readonly token: string; release(): void } +export interface OwnershipMutationLease { readonly token: string; addDelegate(pid: number): void; release(): void } export declare const OWNERSHIP_MUTATION_LEASE_TOKEN_ENV: "OCX_OWNERSHIP_MUTATION_LEASE_TOKEN"; +export declare function ownershipMutationLeasePath(statePaths: readonly string[]): string; export declare function ownershipMutationLeaseChildEnvironment( environment: NodeJS.ProcessEnv, @@ -49,7 +58,7 @@ export declare function withOwnershipMutationLease( export declare function inspectOwnershipMutationLease( statePaths: readonly string[], - options?: Pick, + options?: Pick, ): OwnershipMutationLeaseHolder | null; export declare function ownershipMutationLeaseStatusLine( diff --git a/src/service/ownership-mutation-lease.mjs b/src/service/ownership-mutation-lease.mjs index a01d01d0538..0b2130d15a5 100644 --- a/src/service/ownership-mutation-lease.mjs +++ b/src/service/ownership-mutation-lease.mjs @@ -10,6 +10,7 @@ import { readFileSync, readdirSync, realpathSync, + renameSync, rmdirSync, unlinkSync, writeFileSync, @@ -51,6 +52,9 @@ function leasePath(statePaths) { } } +/** The same path used by acquisition, for conservative read-only inspection. */ +export function ownershipMutationLeasePath(statePaths) { return leasePath(statePaths); } + function ownerName(record) { return `v1-${record.pid}-${record.processInstance}-${record.token}.json`; } @@ -138,12 +142,18 @@ function leaseHolder(path, now, alive, image) { if (!observed && !incomplete && !existsSync(path)) return null; const pid = observed?.record.pid ?? incomplete?.pid ?? null; const since = observed ? Math.max(observed.record.createdAt, observed.mtimeMs) : incomplete?.mtimeMs ?? null; - const live = pid === null ? null : alive(pid); + const delegate = observed?.record.delegatePid; + const delegateValid = delegate === undefined || (Number.isSafeInteger(delegate) && delegate > 0); + const holderAlive = pid === null ? null : alive(pid); + const live = !delegateValid ? null : holderAlive === null ? null : holderAlive || (delegate !== undefined && alive(delegate)); return { path, pid, + delegatePid: delegateValid ? delegate ?? null : null, + holderAlive, alive: live, - image: live ? image(pid) : null, + holderKind: observed?.record.holderKind ?? null, + image: holderAlive ? image(pid) : null, ageMs: since === null ? null : Math.max(0, now() - since), record: observed ? "complete" : incomplete?.ownerPath ? "incomplete" : incomplete ? "empty" : "unreadable", }; @@ -153,16 +163,21 @@ function describeHolder(holder) { const age = holder.ageMs === null ? "" : `, lease age ${Math.round(holder.ageMs / 1_000)}s`; if (holder.record === "unreadable") return "holder unknown: the lock directory does not hold exactly one owner file"; if (holder.record === "empty") return `no owner file written yet${age}`; - const state = holder.alive ? ["alive", ...(holder.image ? [holder.image] : [])].join(", ") : "not alive"; + const state = holder.holderAlive ? ["alive", ...(holder.image ? [holder.image] : [])].join(", ") : "not alive"; const partial = holder.record === "incomplete" ? ", owner record incomplete" : ""; - return `recorded PID ${holder.pid} [${state}, identity unverified${partial}]${age}`; + const delegate = holder.delegatePid === null ? "" : `, delegate PID ${holder.delegatePid} (identity unverified)`; + return `recorded PID ${holder.pid} [${state}, identity unverified${partial}]${delegate}${age}`; } const RECLAIM_HINT = `stale leases are reclaimed after ${STALE_MS / 1_000}s once the recorded PID is no longer alive`; +function reclaimHint(holder) { + return holder.delegatePid !== null || (holder.record === "complete" && holder.alive === null) + ? `${RECLAIM_HINT} and any delegate is known absent or no longer alive` : RECLAIM_HINT; +} /** The recorded lease owner for `statePaths`, identity unverified, or null if free. Reads only; never reclaims. */ export function inspectOwnershipMutationLease(statePaths, options = {}) { - return leaseHolder(leasePath(statePaths), options.now ?? Date.now, options.processAlive ?? processAlive, + return leaseHolder(options.lockPath ?? leasePath(statePaths), options.now ?? Date.now, options.processAlive ?? processAlive, options.processImage ?? processImage); } @@ -171,13 +186,32 @@ export function ownershipMutationLeaseStatusLine(statePaths, options = {}) { const holder = inspectOwnershipMutationLease(statePaths, options); if (!holder) return null; return `Runtime mutation lease busy at ${holder.path} (${describeHolder(holder)}); ` - + `opencodex waits for it to start or change service state, and ${RECLAIM_HINT}.`; + + `opencodex waits for it to start or change service state, and ${reclaimHint(holder)}.`; } function createLeaseHandle(path, generation, token, options) { let released = false; return { token, + addDelegate: pid => { + if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error("invalid mutation lease delegate pid"); + const current = held.get(path); + const observed = readOwner(path); + if (released || !current || current.generation !== generation || current.delegated || !observed || !sameOwner(current.snapshot, observed)) throw new Error("mutation lease is no longer held"); + const temporary = `${path}.${randomUUID()}.tmp`; + let created = false; + try { + writeFileSync(temporary, `${JSON.stringify({ ...observed.record, delegatePid: pid })}\n`, { flag: "wx", mode: 0o600 }); + created = true; + renameSync(temporary, observed.ownerPath); + created = false; + const updated = readOwner(path); + if (!updated || updated.record.token !== token || updated.record.delegatePid !== pid) throw new Error("mutation lease delegate could not be verified"); + current.snapshot = updated; + } finally { + if (created) { try { unlinkSync(temporary); } catch (error) { if (error?.code !== "ENOENT") throw error; } } + } + }, release: () => { if (released) return; released = true; @@ -192,6 +226,8 @@ function reclaim(path, now, alive) { if (!observed && !incomplete) return false; const createdAt = observed ? Math.max(observed.record.createdAt, observed.mtimeMs) : incomplete.mtimeMs; const pid = observed?.record.pid ?? incomplete.pid; + const delegate = observed?.record.delegatePid; + if (delegate !== undefined && (!Number.isSafeInteger(delegate) || delegate <= 0 || alive(delegate))) return false; if (now() - createdAt <= STALE_MS || (pid !== null && alive(pid))) return false; if (observed) { const current = readOwner(path); @@ -209,17 +245,23 @@ export function acquireOwnershipMutationLease( statePaths, options = {}, ) { - const path = leasePath(statePaths); + const path = options.lockPath ?? leasePath(statePaths); const nested = held.get(path); if (nested) { + if (options.isolated) { + const error = new Error("another operation owns the isolated mutation lease"); + error.code = "OWNERSHIP_MUTATION_LEASE_BUSY"; + error.holder = leaseHolder(path, options.now ?? Date.now, options.processAlive ?? processAlive, options.processImage ?? processImage); + throw error; + } nested.depth += 1; return createLeaseHandle(path, nested.generation, nested.snapshot.record.token, options); } const now = options.now ?? Date.now; const alive = options.processAlive ?? processAlive; const explicitJoinToken = options.joinToken; - const envJoinToken = process.env[OWNERSHIP_MUTATION_LEASE_TOKEN_ENV]; - const joinToken = explicitJoinToken ?? envJoinToken ?? delegatedTokens.get(path); + const envJoinToken = options.isolated ? undefined : process.env[OWNERSHIP_MUTATION_LEASE_TOKEN_ENV]; + const joinToken = options.isolated ? undefined : explicitJoinToken ?? envJoinToken ?? delegatedTokens.get(path); if (joinToken) { const owner = readOwner(path); if (owner?.record.token === joinToken && alive(owner.record.pid)) { @@ -237,7 +279,7 @@ export function acquireOwnershipMutationLease( const deadline = now() + wait; if (!existsSync(dirname(path))) mkdirSync(dirname(path), { recursive: true, mode: 0o700 }); for (;;) { - const record = { version: 1, pid: process.pid, processInstance: PROCESS_INSTANCE, token: randomUUID(), createdAt: now() }; + const record = { version: 1, pid: process.pid, processInstance: PROCESS_INSTANCE, token: randomUUID(), createdAt: now(), ...(options.holderKind ? { holderKind: options.holderKind } : {}) }; const ownerPath = join(path, ownerName(record)); let madeDirectory = false; let descriptor = null; @@ -265,7 +307,7 @@ export function acquireOwnershipMutationLease( if (now() >= deadline) { const holder = leaseHolder(path, now, alive, options.processImage ?? processImage); const error = new Error(`another process owns the runtime mutation lease at ${path}` - + (holder ? ` (${describeHolder(holder)}; ${RECLAIM_HINT})` : "")); + + (holder ? ` (${describeHolder(holder)}; ${reclaimHint(holder)})` : "")); error.code = "OWNERSHIP_MUTATION_LEASE_BUSY"; error.holder = holder; throw error; diff --git a/src/update/index.ts b/src/update/index.ts index c47eb6556ec..7fe85501f82 100644 --- a/src/update/index.ts +++ b/src/update/index.ts @@ -5,8 +5,9 @@ import { manualUpdateFailureGuidance } from "./update-failure-guidance.mjs"; import { STOP_HISTORY_INCOMPLETE_EXIT_CODE } from "./stop-contract.mjs"; import { proxyIdentityAt } from "../server/proxy-liveness"; import { probeProxyLiveness } from "./proxy-liveness-probe.mjs"; +import { verifyOrchestratedInstall } from "./orchestrated-tree.mjs"; import { decidePostStopUpdate } from "./stop-decision.mjs"; -import { existsSync, readFileSync, readdirSync } from "node:fs"; +import { existsSync, readFileSync, readdirSync, realpathSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { dirname, join, resolve } from "node:path"; import { getConfigDir, loadConfig } from "../config"; @@ -43,6 +44,11 @@ import { withoutSiblingMarker } from "../codex/sibling-start"; import { packageVersion } from "../lib/package-version"; import { isStandaloneModuleUrl } from "../lib/standalone"; import { selfLaunchArgv } from "../lib/self-launch-argv"; +import { createLegacyUpdateSession, createOrchestratedChildSession, decodeOrchestratedExpect } from "./orchestrated-session.mjs"; +import { runPosixInstallerSync } from "./posix-install-supervisor.mjs"; +import { runWindowsInstallerSync } from "./npm-install.mjs"; +import { protectOrchestratedWorkerSignals } from "./orchestrated-child.mjs"; +import type { OrchestratedChildArgs } from "./orchestrated-arguments.mjs"; import { PNPM_READ_CWD, withPnpmCommandCwd, pnpmReadEnvironment } from "./pnpm-read-policy.mjs"; import { freshServingPid, hasRestartableServiceManager, readParentPid, readServiceManagerPid, restartServiceManagerJob, @@ -109,6 +115,7 @@ function runPnpmCandidate( args: readonly string[], capture = false, probeSpawn: typeof probeSpawnSync = probeSpawnSync, + probeEnv: NodeJS.ProcessEnv = process.env, ): { status: number | null; stdout?: string | null; stderr?: string | null } { const invocation = pnpmInvocationForPath(commandPath, args); if (!invocation) return { status: 1 }; @@ -118,7 +125,7 @@ function runPnpmCandidate( timeout: 20_000, windowsHide: true, cwd: PNPM_READ_CWD, - env: pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(process.env)), + env: pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(probeEnv)), ...invocation.options, }); } @@ -126,7 +133,7 @@ function runPnpmCandidate( /** Resolve the exact pnpm executable/group/bin that own this package. */ export function resolveCurrentPnpmGlobalOwner( invoked = process.argv[1], - deps: { commandPaths?: readonly string[]; spawn?: typeof probeSpawnSync } = {}, + deps: { commandPaths?: readonly string[]; spawn?: typeof probeSpawnSync; env?: NodeJS.ProcessEnv } = {}, ): PnpmGlobalOwnerResult { const probeSpawn = deps.spawn ?? probeSpawnSync; return resolvePnpmGlobalOwner({ @@ -134,7 +141,7 @@ export function resolveCurrentPnpmGlobalOwner( packagePath: packageRoot(), commandPaths: deps.commandPaths ?? resolvePnpmCommands(), runningShimPath: runningPnpmShimPath(invoked), - runPnpm: (commandPath, args, capture) => runPnpmCandidate(commandPath, args, capture, probeSpawn), + runPnpm: (commandPath, args, capture) => runPnpmCandidate(commandPath, args, capture, probeSpawn, deps.env), }); } @@ -159,10 +166,30 @@ export function runOwnedPnpm( stdio: "inherit" | "pipe" | "ignore" = capture ? "pipe" : "inherit", probeSpawn: typeof probeSpawnSync = probeSpawnSync, authorizeMutation: (kind: "package") => boolean = () => ["root", "bin", "list", "config", "view", "--version"].includes(args[0] ?? ""), -): { status: number | null; stdout?: string | null; stderr?: string | null } { + session?: Pick, "retainInstallerFence" | "noteUntrackedInstaller" | "confirmInstallerExit">, + markerPath = join(getConfigDir(), "update-orchestrated.json"), +): { status: number | null; stdout?: string | null; stderr?: string | null; processTreeExited?: boolean } { const target = ownerPnpmTarget(owner, args); if (!target) return { status: 1 }; - return withPnpmCommandCwd(args, cwd => authorizeMutation("package") ? guardedSpawnSync(authorizeMutation, "package", target.bin, target.args, { + const mutating = ["add", "install", "update", "remove", "uninstall"].includes(args[0] ?? ""); + try { return withPnpmCommandCwd(args, cwd => { + if (mutating && !capture && session && authorizeMutation("package")) { + const env = pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(target.env)); + if (process.platform === "win32") { + session.noteUntrackedInstaller(); + const result = runWindowsInstallerSync({ file: target.bin, args: target.args, options: target.options }, { cwd, env, authorizeMutation }); + if (result.processTreeExited && Number.isInteger(result.status)) session.confirmInstallerExit(); + else { session.retainInstallerFence(); return { ...result, processTreeExited: false }; } + return result; + } + const result = runPosixInstallerSync({ file: target.bin, args: target.args, markerPath, cwd, env, authorizeMutation }); + if (!Number.isInteger(result.status) || result.signal || !result.groupExited || result.groupKilled !== false || result.processTreeExited === false) { + session.retainInstallerFence(); + return { ...result, processTreeExited: false }; + } + return { ...result, processTreeExited: true }; + } + const result = authorizeMutation("package") ? guardedSpawnSync(authorizeMutation, "package", target.bin, target.args, { stdio, encoding: "utf8", timeout: 180_000, @@ -172,7 +199,10 @@ export function runOwnedPnpm( cwd, env: pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(target.env)), ...target.options, - }, probeSpawn) : { status: 1 }); + }, probeSpawn) : { status: 1, signal: null }; + if (mutating && (!Number.isInteger(result.status) || result.signal)) session?.retainInstallerFence(); + return result; + }); } catch (error) { if (mutating) session?.retainInstallerFence(); throw error; } } /** Re-read the owning group's active package and return its verified launcher. */ @@ -221,9 +251,9 @@ function npmSpawnTarget(args: readonly string[]): SpawnTarget | null { return { bin: invocation.file, args: invocation.args, options: invocation.options }; } -function pnpmSpawnTarget(args: readonly string[], owner?: PnpmGlobalOwner): SpawnTarget | null { +function pnpmSpawnTarget(args: readonly string[], owner?: PnpmGlobalOwner, env?: NodeJS.ProcessEnv): SpawnTarget | null { if (owner) { - const invocation = pnpmOwnerInvocation(owner, args); + const invocation = pnpmOwnerInvocation(owner, args, process.platform, env); if (!invocation) return null; return { bin: invocation.file, @@ -241,19 +271,20 @@ export function registrySpawnTarget( installer: Installer, args: readonly string[], owner?: PnpmGlobalOwner, + env?: NodeJS.ProcessEnv, ): SpawnTarget | null { if (installer === "standalone") return null; // A pnpm command without an owner would silently fall back to the first PATH // candidate. That is unsafe when multiple PNPM_HOME installations expose the // same version, so registry queries use the same hard binding as mutation. return installer === "pnpm" - ? owner ? pnpmSpawnTarget(args, owner) : null + ? owner ? pnpmSpawnTarget(args, owner, env) : null : npmSpawnTarget(args); } -function selectedPnpmOwner(owner?: PnpmGlobalOwner): PnpmGlobalOwner | undefined { +function selectedPnpmOwner(owner?: PnpmGlobalOwner, probeSpawn?: typeof probeSpawnSync, env?: NodeJS.ProcessEnv): PnpmGlobalOwner | undefined { if (owner) return owner; - const result = resolveCurrentPnpmGlobalOwner(); + const result = resolveCurrentPnpmGlobalOwner(undefined, { spawn: probeSpawn, env }); return result.ok ? result.owner : undefined; } @@ -299,10 +330,11 @@ export function latestVersion( installer: Installer = detectInstall(), owner?: PnpmGlobalOwner, probeSpawn: typeof probeSpawnSync = probeSpawnSync, + probeEnv?: NodeJS.ProcessEnv, ): string | null { - const resolvedOwner = installer === "pnpm" ? selectedPnpmOwner(owner) : undefined; + const resolvedOwner = installer === "pnpm" ? selectedPnpmOwner(owner, probeSpawn, probeEnv) : undefined; if (installer === "pnpm" && !resolvedOwner) return null; - const manager = registrySpawnTarget(installer, ["view", `${PKG}@${tag}`, "version"], resolvedOwner); + const manager = registrySpawnTarget(installer, ["view", `${PKG}@${tag}`, "version"], resolvedOwner, probeEnv); if (!manager) return null; const r = probeSpawn(manager.bin, manager.args, { encoding: "utf8", @@ -310,8 +342,8 @@ export function latestVersion( windowsHide: true, cwd: installer === "pnpm" ? PNPM_READ_CWD : undefined, env: installer === "pnpm" - ? pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(manager.env ?? process.env)) - : unprivilegedOwnershipMutationEnvironment(manager.env ?? process.env), + ? pnpmReadEnvironment(unprivilegedOwnershipMutationEnvironment(manager.env ?? probeEnv ?? process.env)) + : unprivilegedOwnershipMutationEnvironment(manager.env ?? probeEnv ?? process.env), ...manager.options, }); return r.status === 0 && typeof r.stdout === "string" ? (r.stdout.trim() || null) : null; @@ -417,9 +449,35 @@ async function resolvedRuntimeOwnership(): Promise * are updated in the Node bin launcher before Bun starts, so Windows does not replace the running * Bun binary. */ -export async function runUpdate(): Promise { +export async function runUpdate(child?: Extract): Promise { + let session: ReturnType | undefined; + if (child) { + try { + const expect = decodeOrchestratedExpect(child.expect); + session = createOrchestratedChildSession({ home: getConfigDir(), resultPath: child.resultPath, expect, notAfter: child.notAfter, + verifyIdentity: async () => (await import("./orchestrated-entry")).verifyOrchestratedChildIdentity(expect, child.version) }); + if (!session.start().ok) { process.exitCode = 10; return; } + protectOrchestratedWorkerSignals(); + } catch (error) { + console.error(`Orchestrated update preflight failed: ${error instanceof Error ? error.message : String(error)}`); + process.exitCode = 1; + return; + } + } else { + session = createLegacyUpdateSession({ home: getConfigDir() }); + const started = session.start(); + if (!started.ok) { console.error(`opencodex: ${started.error}`); process.exitCode = 1; return; } + process.once("exit", () => session?.finishPreflight()); + } + try { await runUpdateWithSession(child, session); } + finally { session?.finishPreflight(); } +} + +async function runUpdateWithSession(child: Extract | undefined, + session: ReturnType | undefined): Promise { const ownership = detectInstallOwnership(); const installer = ownership.installer; + if (child && installer !== "bun") { process.exitCode = 1; return; } const current = currentVersion(); const tag = updateTag(current); console.log(`opencodex v${current} (installed via ${installer}, tag ${tag})`); @@ -454,9 +512,10 @@ export async function runUpdate(): Promise { process.exit(1); } const owner = ownerResult?.ok ? ownerResult.owner : undefined; - const latest = latestVersion(tag, installer, owner); + const latest = child?.version ?? latestVersion(tag, installer, owner); if (latest && latest === current) { console.log(`Already on the latest ${tag} version (v${latest}).`); + if (child) process.exitCode = 1; return; } @@ -465,6 +524,7 @@ export async function runUpdate(): Promise { const integrity = checkUpdatePackageIntegrity(latest, probeSpawnSync, installer, owner); if (integrity.ok === false) { console.error(`⚠️ ${integrity.reason} — aborting the update before stopping the proxy.`); + if (child) { process.exitCode = 1; return; } process.exit(1); } if (integrity.ok === "skipped") { @@ -487,11 +547,15 @@ export async function runUpdate(): Promise { : updateSpawnTarget(bin, cmdArgs); if (!target) { console.error(`⚠️ Could not resolve ${bin} from a trusted absolute PATH entry; aborting before stopping the proxy.`); + if (child) { process.exitCode = 1; return; } process.exit(1); } const { serviceStatePaths } = await import("../service"); - const updateExitCode = await withUpdateOwnershipLease(serviceStatePaths(), async mutation => { + let mutationStarted = false, completed = false, installerUncertain = false, installedRoot: string | undefined; + let updateExitCode: number | undefined; + try { + updateExitCode = await withUpdateOwnershipLease(serviceStatePaths(), async mutation => { // Ownership inspection imports the service CLI, which reaches this update entry again. // Load it only after entering the lease; the policy itself stays a dependency-free import. const { inspectUpdateServiceHome } = await import("./service-home-authority"); @@ -519,6 +583,11 @@ export async function runUpdate(): Promise { console.error("⚠️ Update stopped before tray handoff, runtime stop, or package replacement because runtime authority does not permit it."); return 1; } + if (session) { + const admission = await session.enterMutation(); + if (!admission.ok) return 10; + mutationStarted = true; + } let trayWasInstalled = false; let trayWasRunning = false; if (!homePolicy.packageOnly && process.platform === "win32") { @@ -869,6 +938,7 @@ export async function runUpdate(): Promise { // Every post-update action below receives the verified active launcher. if (installer === "pnpm") { let update: ReturnType; + installerUncertain = true; try { if (!homePolicy.authorizeMutation("package")) return 1; update = runPnpmGlobalUpdate({ @@ -883,7 +953,7 @@ export async function runUpdate(): Promise { args, capture, capture ? "pipe" : installStdio, - probeSpawnSync, homePolicy.authorizeMutation, + probeSpawnSync, homePolicy.authorizeMutation, session, ) : { status: 1, stdout: "", stderr: "" }, log: line => console.log(line), }); @@ -894,9 +964,12 @@ export async function runUpdate(): Promise { ok: false, phase: "rollback", rolledBack: false, + processTreeExited: false, error: "pnpm update failed unexpectedly; active package could not be verified", }; + session?.retainInstallerFence(); } + installerUncertain = !update.ok && update.processTreeExited === false; if (update.ok) { postUpdateLauncher = join(update.path, "bin", "ocx.mjs"); postUpdateLauncherUsable = true; @@ -909,14 +982,35 @@ export async function runUpdate(): Promise { } } else { if (!homePolicy.authorizeMutation("package")) return 1; - r = guardedSpawnSync(homePolicy.authorizeMutation, "package", target.bin, target.args, { + installerUncertain = true; + if (session && process.platform === "win32") { + session.noteUntrackedInstaller(); + const supervised = runWindowsInstallerSync({ file: target.bin, args: target.args, options: target.options }, { + env: mutation.unprivilegedEnvironment(), authorizeMutation: homePolicy.authorizeMutation, + }); + if (supervised.processTreeExited === true && Number.isInteger(supervised.status)) session.confirmInstallerExit(); + else session.retainInstallerFence(); + r = supervised; + installerUncertain = supervised.processTreeExited !== true || !Number.isInteger(supervised.status); + } else if (session) { + try { + const supervised = runPosixInstallerSync({ file: target.bin, args: target.args, + markerPath: join(getConfigDir(), "update-orchestrated.json"), + authorizeMutation: homePolicy.authorizeMutation, env: mutation.unprivilegedEnvironment() }); + installerUncertain = !Number.isInteger(supervised.status) || Boolean(supervised.signal) || !supervised.groupExited || supervised.groupKilled !== false || supervised.processTreeExited === false; + if (installerUncertain) session.retainInstallerFence(); + r = supervised; + } catch (error) { session.retainInstallerFence(); throw error; } + } else r = guardedSpawnSync(homePolicy.authorizeMutation, "package", target.bin, target.args, { stdio: installStdio, encoding: installStdio === "pipe" ? "utf8" : undefined, - timeout: 180000, + // The parent watchdog reports overrun without killing an active transaction. + timeout: child ? undefined : 180000, windowsHide: true, ...target.options, env: mutation.unprivilegedEnvironment(), }); + if (!session) installerUncertain = r.status === null; } if (r && installStdio === "pipe") logSpawnOutput("", r); } @@ -932,6 +1026,11 @@ export async function runUpdate(): Promise { return 1; } if (!r) throw new Error("update replacement returned no result"); + if (installerUncertain) { console.error("Installer termination was not confirmed; update recovery is deferred."); return 1; } + if (session && r.status === 0 && latest) { + const root = realpathSync.native(packageRoot()); + if (verifyOrchestratedInstall(root, latest, "bun")) installedRoot = root; + } const postInstallPlan = planUpdateRuntimeHandling({ ...(await resolvedRuntimeOwnership()), serviceInstalled: serviceWasInstalled, @@ -1186,12 +1285,21 @@ export async function runUpdate(): Promise { return 1; } } catch (error) { - await recoverStoppedRuntime("update failed unexpectedly"); - if (trayWasRunning) { + if (!installerUncertain) await recoverStoppedRuntime("update failed unexpectedly"); + if (trayWasRunning && !installerUncertain) { try { const { guardedStartWindowsTray } = await import("./guarded-tray-ops"); if (homePolicy.authorizeMutation("own-tray")) guardedStartWindowsTray(homePolicy.authorizeMutation); } catch { /* retain original failure */ } } throw error; } }); - if (updateExitCode) process.exit(updateExitCode); + completed = true; + } finally { + if (session && mutationStarted) session.finish(installedRoot + ? { phase: "installed", activeRoot: installedRoot, ...(!completed || updateExitCode ? { recoveryFailed: true, error: "runtime-unhealthy" } : {}) } + : { phase: "failed", error: installerUncertain ? "installer-timeout" : "update-failed", ...(installerUncertain ? { terminationConfirmed: false } : {}) }); + } + if (updateExitCode) { + if (child) process.exitCode = updateExitCode; + else process.exit(updateExitCode); + } else if (child && !mutationStarted) process.exitCode = 1; } diff --git a/src/update/npm-install.d.mts b/src/update/npm-install.d.mts new file mode 100644 index 00000000000..e5cb2f94a6d --- /dev/null +++ b/src/update/npm-install.d.mts @@ -0,0 +1,8 @@ +import type { NpmInvocation } from "./npm-invocation.mjs"; + +export declare function runWindowsInstallerSync(invocation: NpmInvocation, options?: { + env?: NodeJS.ProcessEnv; + cwd?: string; + timeoutMs?: number; + authorizeMutation?: (kind: "package") => boolean; +}): { status: number | null; processTreeExited: boolean }; diff --git a/src/update/npm-install.mjs b/src/update/npm-install.mjs index b1ff4ff3d48..e29d6cd1cd7 100644 --- a/src/update/npm-install.mjs +++ b/src/update/npm-install.mjs @@ -1,12 +1,26 @@ // Windows Node-launcher compatibility code. The install owns its entire process tree until // exit is proved; a timeout signal alone never authorizes stage removal. -import { guardedSpawn, materializeMutationData } from "./mutation-guard.mjs"; +import { guardedSpawn, guardedSpawnSync, materializeMutationData } from "./mutation-guard.mjs"; import { dirname, join, win32 } from "node:path"; import { fileURLToPath } from "node:url"; const JOIN_MS = 10000; const failure = message => ({ status: null, processTreeExited: false, error: { code: "EINSTALLJOIN", message } }); +/** Bridge synchronous pnpm transactions to the same Windows Job Object barrier. */ +export function runWindowsInstallerSync(invocation, { env = process.env, cwd, timeoutMs = 180000, authorizeMutation = () => false } = {}) { + const moduleUrl = import.meta.url; + const script = `import {readFileSync} from 'node:fs';import {runNpmInstall} from ${JSON.stringify(moduleUrl)};const input=JSON.parse(readFileSync(0,'utf8'));console.log(JSON.stringify(await runNpmInstall(input.invocation,{timeoutMs:input.timeoutMs,authorizeMutation:()=>true})));`; + const result = guardedSpawnSync(authorizeMutation, "package", process.execPath, ["--input-type=module", "-e", script], { + input: JSON.stringify({ invocation, timeoutMs }), env, cwd, encoding: "utf8", windowsHide: true, stdio: ["pipe", "pipe", "inherit"], + }); + try { + const value = JSON.parse(result.stdout); + if (result.status !== 0 || typeof value.processTreeExited !== "boolean") throw Error("invalid supervisor result"); + return value; + } catch { return failure("Windows installer supervisor did not confirm process-tree exit"); } +} + function quoteWindowsArg(value) { return '"' + value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, "$1$1") + '"'; } @@ -16,6 +30,11 @@ export async function runNpmInstall(invocation, { env = process.env, timeoutMs = env = materializeMutationData(env); if (!invocation) return { status: 1, processTreeExited: true, error: { code: "ENOENT", message: "npm invocation unavailable" } }; if (process.platform === "win32") { + // The PowerShell helper assigns npm to a kill-on-close Job Object before it + // resumes the suspended process, then terminates the job on timeout and + // waits for the job to become empty. An unconfirmed join retains the stage. + // Windows acceptance still needs orchestrated npm and pnpm worker tests proving + // marker visibility across supervisor failure and Job Object termination. // Resolve from the same absolute system directory as the hardened cmd hop. // Never search PATH for PowerShell, and never interpolate the JSON as code. const roots = new Set(Object.entries(env).filter(([key, value]) => key.toLowerCase() === "systemroot" && value !== undefined).map(([, value]) => value)); diff --git a/src/update/orchestrated-admission.d.mts b/src/update/orchestrated-admission.d.mts new file mode 100644 index 00000000000..9aeb99ee6ed --- /dev/null +++ b/src/update/orchestrated-admission.d.mts @@ -0,0 +1,4 @@ +import type { observeOrchestratedPlan } from "./orchestrated-entry"; +import type { OrchestratedUpdateArgs } from "./orchestrated-arguments.mjs"; +export declare function decideOrchestratedApply(plan: Awaited>, request: Extract, now: number): + | { kind: "proceed" } | { kind: "done"; exitCode: 0 | 10; result: { schema: "ocx.update.result/1"; applied: boolean; fromVersion: string; toVersion: string | null; installer: string; restarted: boolean; healthy: boolean; rolledBack: boolean; error?: string } }; diff --git a/src/update/orchestrated-admission.mjs b/src/update/orchestrated-admission.mjs new file mode 100644 index 00000000000..057d1807c0f --- /dev/null +++ b/src/update/orchestrated-admission.mjs @@ -0,0 +1,12 @@ +/** Resolve decisions that require no mutation before starting an update worker. */ +export function decideOrchestratedApply(plan, request, now) { + const result = { schema: "ocx.update.result/1", applied: false, fromVersion: plan.currentVersion, + toVersion: plan.targetVersion, installer: plan.installer, restarted: false, healthy: false, rolledBack: false }; + const refuse = error => ({ kind: "done", exitCode: 10, result: { ...result, error } }); + if (request.expectPlan && request.expectPlan !== plan.planToken) return refuse("plan-changed"); + if (request.notAfter !== undefined && now > request.notAfter) return refuse("deadline-passed"); + if (plan.updateInFlight) return refuse("update-in-flight"); + if (plan.reason === "up-to-date") return { kind: "done", exitCode: 0, result }; + if (!plan.canApply) return refuse(plan.reason ?? "plan-unavailable"); + return { kind: "proceed" }; +} diff --git a/src/update/orchestrated-arguments.d.mts b/src/update/orchestrated-arguments.d.mts new file mode 100644 index 00000000000..fc834e7b4d2 --- /dev/null +++ b/src/update/orchestrated-arguments.d.mts @@ -0,0 +1,12 @@ +export type OrchestratedUpdateArgs = { ok: false } | { + ok: true; + mode: "plan" | "apply"; + tag?: "latest" | "preview"; + version?: string; + expectPlan?: string; + notAfter?: number; +}; +export declare function parseOrchestratedUpdateArgs(argv: readonly string[]): OrchestratedUpdateArgs; +export declare function isOrchestratedUpdateArgv(argv: readonly string[]): boolean; +export type OrchestratedChildArgs = { ok: false } | { ok: true; version: string; expect: string; resultPath: string; notAfter?: number }; +export declare function parseOrchestratedChildArgs(argv: readonly string[], env: Record): OrchestratedChildArgs; diff --git a/src/update/orchestrated-arguments.mjs b/src/update/orchestrated-arguments.mjs new file mode 100644 index 00000000000..f4c6eb5eb67 --- /dev/null +++ b/src/update/orchestrated-arguments.mjs @@ -0,0 +1,58 @@ +const CORE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/; + +export function isOrchestratedUpdateArgv(argv) { + return argv.some(arg => /^(--plan|--yes|--json|--expect-plan|--not-after|--orchestrated-expect|--orchestrated-result)(?:=|$)/.test(arg)); +} + +/** Internal child grammar is accepted only in the explicitly marked child process. */ +export function parseOrchestratedChildArgs(argv, env) { + if (env.OCX_UPDATE_ORCHESTRATED_CHILD !== "1") return { ok: false }; + const values = new Map(); + const allowed = new Set(["--version", "--orchestrated-expect", "--orchestrated-result", "--not-after"]); + for (let i = 0; i < argv.length; i++) { + const flag = argv[i], value = argv[++i]; + if (!allowed.has(flag) || values.has(flag) || !value || value.startsWith("-")) return { ok: false }; + values.set(flag, value); + } + const version = values.get("--version"), expect = values.get("--orchestrated-expect"), resultPath = values.get("--orchestrated-result"), deadline = values.get("--not-after"); + if (!version || !strictSemver(version) || !expect || !resultPath || (deadline !== undefined + && (!/^\d+$/.test(deadline) || !Number.isSafeInteger(Number(deadline)) || Number(deadline) <= 0))) return { ok: false }; + return { ok: true, version, expect, resultPath, ...(deadline === undefined ? {} : { notAfter: Number(deadline) }) }; +} + +function strictSemver(value) { + if (value.length > 128) return false; + const match = CORE.exec(value); + return Boolean(match && (match[4] === undefined || match[4].split(".").every(part => + part.length > 0 && /^[0-9A-Za-z-]+$/.test(part) && (!/^\d+$/.test(part) || /^(0|[1-9]\d*)$/.test(part))))); +} + +/** Parse only the public orchestrated grammar; callers map an invalid result to exit 64. */ +export function parseOrchestratedUpdateArgs(argv) { + const flags = new Map(); + const switches = new Set(["--plan", "--yes", "--json"]); + const values = new Set(["--tag", "--version", "--expect-plan", "--not-after"]); + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (switches.has(arg)) { + if (flags.has(arg)) return { ok: false }; + flags.set(arg, true); + } else if (values.has(arg)) { + if (flags.has(arg) || i + 1 >= argv.length || argv[i + 1].startsWith("-")) return { ok: false }; + flags.set(arg, argv[++i]); + } else return { ok: false }; + } + const plan = flags.has("--plan"), apply = flags.has("--yes"); + if (plan === apply || !flags.has("--json")) return { ok: false }; + if (flags.has("--tag") && flags.has("--version")) return { ok: false }; + const tag = flags.get("--tag"), version = flags.get("--version"); + if (tag !== undefined && tag !== "latest" && tag !== "preview") return { ok: false }; + if (version !== undefined && !strictSemver(version)) return { ok: false }; + const expectPlan = flags.get("--expect-plan"), deadline = flags.get("--not-after"); + if (plan && (expectPlan !== undefined || deadline !== undefined)) return { ok: false }; + if (expectPlan !== undefined && !/^[A-Za-z0-9_-]{16,128}$/.test(expectPlan)) return { ok: false }; + if (deadline !== undefined && (!/^\d+$/.test(deadline) || !Number.isSafeInteger(Number(deadline)) || Number(deadline) <= 0)) return { ok: false }; + return { ok: true, mode: plan ? "plan" : "apply", ...(tag === undefined ? {} : { tag }), + ...(version === undefined ? {} : { version }), ...(expectPlan === undefined ? {} : { expectPlan }), + ...(deadline === undefined ? {} : { notAfter: Number(deadline) }) }; +} diff --git a/src/update/orchestrated-child.d.mts b/src/update/orchestrated-child.d.mts new file mode 100644 index 00000000000..56b0a42b3c7 --- /dev/null +++ b/src/update/orchestrated-child.d.mts @@ -0,0 +1,12 @@ +import type { ChildProcess } from "node:child_process"; +import type { EventEmitter } from "node:events"; + +export declare function protectOrchestratedWorkerSignals(): void; + +export declare function waitForOrchestratedChild(child: ChildProcess, options?: { + signals?: EventEmitter; + timeoutMs?: number; + overrunMs?: number; + setTimer?: (callback: () => void, timeoutMs: number) => unknown; + clearTimer?: (timer: unknown) => void; +}): Promise<{ confirmed: boolean; code: number | null; signal: NodeJS.Signals | null; reason?: "overrun" }>; diff --git a/src/update/orchestrated-child.mjs b/src/update/orchestrated-child.mjs new file mode 100644 index 00000000000..b1cbbfaefca --- /dev/null +++ b/src/update/orchestrated-child.mjs @@ -0,0 +1,70 @@ +const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"]; + +/** Keep a worker alive until its synchronous installer and recovery finish. */ +export function protectOrchestratedWorkerSignals() { + for (const signal of process.platform === "win32" ? SIGNALS.slice(0, 2) : SIGNALS) process.on(signal, () => {}); +} + +/** Forward catchable signals and require a close event within 60 seconds after interruption. */ +export function waitForOrchestratedChild(child, options = {}) { + const signals = options.signals ?? process; + const startTimer = options.setTimer ?? setTimeout; + const stopTimer = options.clearTimer ?? clearTimeout; + const timeoutMs = options.timeoutMs ?? 60_000; + return new Promise(resolve => { + let timer; + let overrunTimer; + let settled = false; + const handlers = new Map(); + const cleanupSignals = () => { + for (const [signal, handler] of handlers) signals.removeListener(signal, handler); + if (timer !== undefined) stopTimer(timer); + if (overrunTimer !== undefined) stopTimer(overrunTimer); + }; + const onClose = (code, signal) => { + child.removeListener("error", onError); + if (settled) return; + settled = true; + cleanupSignals(); + resolve({ confirmed: true, code, signal }); + }; + const armTimer = () => { + if (timer !== undefined) return; + timer = startTimer(() => { + if (settled) return; + settled = true; + cleanupSignals(); + // Keep the child listeners until close: a late error must not become unhandled. + resolve({ confirmed: false, code: null, signal: null }); + }, timeoutMs); + }; + const onError = () => armTimer(); + child.once("close", onClose); + child.on("error", onError); + for (const signal of SIGNALS) { + const handler = () => { + armTimer(); + try { child.kill(signal); } catch { /* Wait for close or return uncertainty. */ } + }; + handlers.set(signal, handler); + signals.on(signal, handler); + } + if (options.overrunMs !== undefined) { + let remaining = Math.max(0, options.overrunMs); + const schedule = () => { + const delay = Math.min(remaining, 2_147_483_647); + overrunTimer = startTimer(() => { + if (settled) return; + remaining -= delay; + if (remaining > 0) { schedule(); return; } + settled = true; + cleanupSignals(); + // Do not signal a transaction in progress. The caller must detach its + // handles and leave the child's in-flight marker intact. + resolve({ confirmed: false, code: null, signal: null, reason: "overrun" }); + }, delay); + }; + schedule(); + } + }); +} diff --git a/src/update/orchestrated-entry.ts b/src/update/orchestrated-entry.ts new file mode 100644 index 00000000000..18c14c3fbd2 --- /dev/null +++ b/src/update/orchestrated-entry.ts @@ -0,0 +1,236 @@ +import { mkdtempSync, readFileSync, realpathSync, rmSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { tmpdir } from "node:os"; +import { spawn as spawnProcess, type ChildProcess } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { packageVersion } from "../lib/package-version"; +import { getConfigDir } from "../config/paths"; +import { readConfigDiagnostics } from "../config"; +import { resolveServiceOwnership } from "../service/state"; +import type { ServiceOwnershipResolution } from "../service/state"; +import { inspectDesktopSupervision, type SupervisionEvidence } from "../service/desktop-supervision.mjs"; +import { diagnoseService } from "../service/diagnostics"; +import { detectInstallOwnership, defaultUpdateTag, latestVersion } from "./index"; +import { parseOrchestratedUpdateArgs, type OrchestratedUpdateArgs } from "./orchestrated-arguments.mjs"; +import { buildOrchestratedPlan, type PlanInputs } from "./orchestrated-plan"; +import { inspectLiveOrchestratedIdentity } from "./orchestrated-live-identity"; +import type { ServingIdentity } from "./orchestrated-identity"; +import { planUpdateRuntimeHandling } from "./runtime-ownership.mjs"; +import { isUpdateInFlight } from "./sync-update-mutex"; +import { encodeOrchestratedExpect, type OrchestratedExpect } from "./orchestrated-session.mjs"; +import { waitForOrchestratedChild } from "./orchestrated-child.mjs"; +import { classifyOrchestratedOutcome, type Outcome } from "./orchestrated-outcome.mjs"; +import { verifyOrchestratedInstall } from "./orchestrated-tree.mjs"; +import { decideOrchestratedApply } from "./orchestrated-admission.mjs"; +import { createUpdatePlanToken } from "./orchestrated-token.mjs"; +import { selfLaunchArgv } from "../lib/self-launch-argv"; +import { proxyIdentityAt } from "../server/proxy-liveness"; +import { probeSpawnSync } from "./mutation-guard.mjs"; + +type Request = Extract; +type DetectedInstaller = PlanInputs["installer"] | "standalone"; +export interface OrchestratedPlanDeps { + install(): { installer: DetectedInstaller; cliRoot: string; desktopPath: boolean }; + currentVersion(): string; + identity(): Promise; + ownership(identity: ServingIdentity): { runtimeOwner: PlanInputs["runtimeOwner"]; permits: boolean }; + target(selector: string, installer: PlanInputs["installer"]): string | null; + inFlight(): boolean; +} + +export function classifyPlanRuntimeOwner(identity: ServingIdentity, owner: ServiceOwnershipResolution, + supervision: SupervisionEvidence, serviceInstalled: boolean | null): { runtimeOwner: PlanInputs["runtimeOwner"]; permits: boolean } { + const policy = planUpdateRuntimeHandling({ ownership: owner.kind === "owned" ? owner.ownership : null, + ownershipUnknown: owner.kind === "unknown", serviceInstalled: serviceInstalled === true, supervision }); + const desktop = supervision.kind === "desktop" || (owner.kind === "owned" && owner.ownership.owner !== "cli"); + const uncertain = owner.kind === "unknown" || supervision.kind === "unknown" || supervision.kind === "unsupported" || serviceInstalled === null; + const identityUnknown = identity.kind !== "live" && identity.kind !== "absent"; + const runtimeOwner = uncertain ? "unknown" : desktop ? "desktop-app" : identityUnknown ? "unknown" : identity.kind === "absent" ? "none" + : serviceInstalled && owner.kind === "owned" && owner.ownership.owner === "cli" ? "service" : "unmanaged"; + return { runtimeOwner, permits: !uncertain && !identityUnknown && policy.mayReplacePackage }; +} + +const defaultDeps: OrchestratedPlanDeps = { + install() { + const installer = detectInstallOwnership().installer; + const path = installer === "standalone" ? process.execPath : resolve(dirname(fileURLToPath(import.meta.url)), "../.."); + return { installer, cliRoot: realpathSync.native(path), desktopPath: /(?:[\\/]\.opencodex-desktop[\\/]|\.app[\\/]Contents[\\/])/i.test(path) }; + }, + currentVersion: packageVersion, + async identity() { + const config = readConfigDiagnostics({ passive: true }); + if (config.source === "fallback") return { kind: "unknown" }; + return inspectLiveOrchestratedIdentity(getConfigDir(), { port: config.config.port ?? 10100, hostname: config.config.hostname }); + }, + ownership(identity) { + const owner = resolveServiceOwnership(); + const supervision = identity.kind === "live" ? inspectDesktopSupervision({ targetPid: identity.runtime.pid }) : { kind: "none" as const }; + let serviceInstalled: boolean | null = false; + if (identity.kind === "live" && owner.kind === "owned" && owner.ownership.owner === "cli") { + const service = diagnoseService(); + serviceInstalled = service.supported && !service.conflict ? service.installed : null; + } + return classifyPlanRuntimeOwner(identity, owner, supervision, serviceInstalled); + }, + target: (selector, installer) => { + if (!["npm", "pnpm", "bun"].includes(installer)) return null; + const cache = mkdtempSync(join(tmpdir(), "ocx-registry-probe-")); + const overrides = { npm_config_cache: cache, npm_config_logs_dir: join(cache, "logs"), npm_config_logs_max: "0", + npm_config_update_notifier: "false", pnpm_config_cache_dir: join(cache, "pnpm-cache"), + npm_config_cache_dir: join(cache, "pnpm-cache"), npm_config_store_dir: join(cache, "pnpm-store"), + pnpm_config_store_dir: join(cache, "pnpm-store"), pnpm_config_state_dir: join(cache, "pnpm-state"), + BUN_INSTALL_CACHE_DIR: join(cache, "bun-cache"), XDG_CACHE_HOME: join(cache, "xdg-cache"), XDG_STATE_HOME: join(cache, "xdg-state") }; + const keys = new Set(Object.keys(overrides).map(key => key.toLowerCase())); + const env = { ...Object.fromEntries(Object.entries(process.env).filter(([key]) => !keys.has(key.toLowerCase()))), ...overrides }; + try { return latestVersion(selector, installer as "npm" | "pnpm" | "bun", undefined, probeSpawnSync, env); } + finally { rmSync(cache, { recursive: true, force: true }); } + }, + inFlight: () => isUpdateInFlight(getConfigDir()), +}; + +/** Passive identity and plan-bound fields for a Node update child. */ +export async function inspectNodeOrchestratedIdentity(cliRoot: string, targetVersion?: string, installer?: "npm" | "pnpm") { + const root = realpathSync.native(cliRoot); + const identity = await defaultDeps.identity(); + if (!targetVersion || !installer) return { ...identity, cliRoot: root }; + const ownership = defaultDeps.ownership(identity); + const live = identity.kind === "live" ? identity : null; + const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8")) as { version?: unknown }; + if (typeof manifest.version !== "string") throw new Error("invalid package version"); + return { ...identity, cliRoot: root, permits: ownership.permits, planToken: createUpdatePlanToken({ + currentVersion: manifest.version, targetVersion, installer, cliRoot: root, + servingRoot: live?.servingRoot ?? null, runtimeOwner: ownership.runtimeOwner, runtime: live?.runtime ?? null, + }) }; +} + +export async function verifyOrchestratedChildIdentity(expected: OrchestratedExpect, targetVersion: string): Promise { + if (getConfigDir() !== expected.home) return false; + const install = defaultDeps.install(); + const identity = await defaultDeps.identity(); + if (install.installer !== "bun" || install.cliRoot !== expected.cliRoot || (identity.kind !== "live" && identity.kind !== "absent")) return false; + const live = identity.kind === "live" ? identity : null; + if ((live?.servingRoot ?? null) !== expected.servingRoot || (live?.runtime.pid ?? null) !== expected.runtimePid) return false; + const ownership = defaultDeps.ownership(identity); + return ownership.permits && createUpdatePlanToken({ currentVersion: defaultDeps.currentVersion(), targetVersion, + installer: install.installer, cliRoot: install.cliRoot, servingRoot: live?.servingRoot ?? null, + runtimeOwner: ownership.runtimeOwner, runtime: live?.runtime ?? null }) === expected.planToken; +} + +/** Observe first, then classify; failures never become permission to update. */ +export async function observeOrchestratedPlan(request: Request, deps: OrchestratedPlanDeps = defaultDeps) { + let install: ReturnType = { installer: "unknown", cliRoot: process.execPath, desktopPath: false }; + let currentVersion = "unknown", targetVersion: string | null = null, identity: ServingIdentity = { kind: "unknown" }; + let runtimeOwner: PlanInputs["runtimeOwner"] = "unknown", permits = false, unavailable = false, updateInFlight = true; + try { install = deps.install(); currentVersion = deps.currentVersion(); } catch { unavailable = true; } + try { updateInFlight = deps.inFlight(); } catch { /* indeterminate means in flight */ } + try { identity = await deps.identity(); } catch { unavailable = true; } + try { const owner = deps.ownership(identity); runtimeOwner = owner.runtimeOwner; permits = owner.permits; } catch { runtimeOwner = "unknown"; } + const installer = install.installer === "standalone" ? (install.desktopPath || runtimeOwner === "desktop-app" ? "desktop-app" : "unknown") : install.installer; + try { + const selector = request.version ?? request.tag ?? defaultUpdateTag(currentVersion); + const resolved = deps.target(selector, installer); + targetVersion = request.version && resolved !== request.version ? null : resolved; + } catch { targetVersion = null; } + const plan = buildOrchestratedPlan({ currentVersion, targetVersion, installer, runtimeOwner, cliRoot: install.cliRoot, + identity, ownershipPermits: permits, updateInFlight }); + return unavailable ? { ...plan, canApply: false, reason: "plan-unavailable" as const } : plan; +} + +export { decideOrchestratedApply } from "./orchestrated-admission.mjs"; + +type Plan = Awaited>; +type BunDriverDeps = { + home: string; + identity: () => Promise; + now: () => number; + spawn: (exe: string, args: string[], options: { env: Record; stdio: ["ignore", number, number] }) => ChildProcess; +}; + +/** The parent owns stdout and verifies the child-reported outcome independently. */ +export async function applyOrchestratedBun(plan: Plan, request: Request, deps: BunDriverDeps) { + const base = { fromVersion: plan.currentVersion, toVersion: plan.targetVersion, installer: plan.installer, + childExited: false, childExitCode: null, outcome: null, previousVerified: false, targetVerified: false, runtimeHealthy: false, restarted: false } as const; + const uncertain = () => classifyOrchestratedOutcome(base); + let directory: string | undefined; + let childStarted = false, childEverStarted = false; + try { + const before = await deps.identity(); + const live = before.kind === "live" ? before : null; + const token = createUpdatePlanToken({ currentVersion: plan.currentVersion, targetVersion: plan.targetVersion, + installer: plan.installer, cliRoot: plan.cliPath, servingRoot: live?.servingRoot ?? null, + runtimeOwner: plan.runtimeOwner, runtime: live?.runtime ?? null }); + if ((before.kind !== "live" && before.kind !== "absent") || token !== plan.planToken || !plan.targetVersion) { + return { exitCode: 10 as const, result: { ...uncertain().result, error: "plan-changed" } }; + } + const started = deps.now(); + directory = mkdtempSync(join(tmpdir(), "ocx-update-")); + const resultPath = join(directory, "result.json"); + const expect = encodeOrchestratedExpect({ home: deps.home, cliRoot: plan.cliPath, servingRoot: live?.servingRoot ?? null, + runtimePid: live?.runtime.pid ?? null, planToken: plan.planToken }); + const args = ["update", "--version", plan.targetVersion, "--orchestrated-expect", expect, "--orchestrated-result", resultPath, + ...(request.notAfter === undefined ? [] : ["--not-after", String(request.notAfter)])]; + const child = deps.spawn(process.execPath, selfLaunchArgv(args), { env: { ...process.env, OCX_UPDATE_ORCHESTRATED_CHILD: "1" }, stdio: ["ignore", 2, 2] }); + childStarted = true; childEverStarted = true; + const waited = await waitForOrchestratedChild(child, { overrunMs: (request.notAfter ?? started) + plan.mutationBoundMs - deps.now() }); + if (!waited.confirmed) { + child.unref(); + if (waited.reason === "overrun") return { exitCode: 12 as const, result: { ...uncertain().result, error: "overrun" } }; + return uncertain(); + } + childStarted = false; + let outcome: Outcome | null = null; + try { outcome = JSON.parse(readFileSync(resultPath, "utf8")) as Outcome; } catch { /* no proof */ } + const activeRoot = outcome?.phase === "installed" ? outcome.activeRoot : plan.cliPath; + const targetVerified = outcome?.phase === "installed" && activeRoot === plan.cliPath + && verifyOrchestratedInstall(activeRoot, plan.targetVersion, "bun"); + const previousVerified = verifyOrchestratedInstall(plan.cliPath, plan.currentVersion, "bun"); + let runtimeHealthy = !plan.restartRequired, restarted = false; + if (plan.restartRequired) { + try { + const after = await deps.identity(); + if (after.kind === "live" && after.servingRoot === activeRoot) { + const health = await proxyIdentityAt(after.runtime.port, { hostname: after.runtime.hostname, expectedPid: after.runtime.pid }); + runtimeHealthy = health?.version === (outcome?.phase === "installed" ? plan.targetVersion : plan.currentVersion); + restarted = after.runtime.pid !== live?.runtime.pid; + } + } catch { + return { exitCode: 12 as const, result: { ...uncertain().result, applied: targetVerified, error: "runtime-unverified" } }; + } + } + return classifyOrchestratedOutcome({ ...base, childExited: true, childExitCode: waited.code, outcome, + previousVerified, targetVerified, runtimeHealthy, restarted }); + } catch { + if (childEverStarted) return uncertain(); + return { exitCode: 10 as const, result: { ...uncertain().result, error: "plan-unavailable" } }; + } finally { + if (directory && !childStarted) { try { rmSync(directory, { recursive: true, force: true }); } catch { /* outcome remains authoritative */ } } + } +} + +export async function runOrchestratedUpdate(argv: string[]): Promise { + const parsed = parseOrchestratedUpdateArgs(argv); + if (!parsed.ok) { + console.log(JSON.stringify({ error: "usage" })); + console.error("Usage: ocx update (--plan | --yes) --json [--tag latest|preview | --version ]"); + return 64; + } + const plan = await observeOrchestratedPlan(parsed); + if (parsed.mode === "plan") { + console.log(JSON.stringify(plan)); + return 0; + } + const admission = decideOrchestratedApply(plan, parsed, Date.now()); + if (admission.kind === "done") { + console.log(JSON.stringify(admission.result)); + return admission.exitCode; + } + if (plan.installer === "bun") { + const result = await applyOrchestratedBun(plan, parsed, { home: getConfigDir(), identity: defaultDeps.identity, + now: Date.now, spawn: (exe, args, options) => spawnProcess(exe, args, options) }); + console.log(JSON.stringify(result.result)); + return result.exitCode; + } + console.log(JSON.stringify({ schema: "ocx.update.result/1", applied: false, fromVersion: plan.currentVersion, + toVersion: null, installer: plan.installer, restarted: false, healthy: false, rolledBack: false, error: plan.reason ?? "plan-unavailable" })); + return 10; +} diff --git a/src/update/orchestrated-identity-probe-entry.ts b/src/update/orchestrated-identity-probe-entry.ts new file mode 100644 index 00000000000..ffb524b99e7 --- /dev/null +++ b/src/update/orchestrated-identity-probe-entry.ts @@ -0,0 +1,20 @@ +import { dirname, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { inspectNodeOrchestratedIdentity } from "./orchestrated-entry"; +import { proxyIdentityAt } from "../server/proxy-liveness"; + +// A direct Bun entry keeps the probe outside ordinary CLI startup and repair paths. +export async function runIdentityProbe(args: string[], cliRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../..")) { + if (args.length !== 1 || args[0] !== "__update-orchestrated-identity") return 1; + try { + const installer = process.env.OCX_IDENTITY_INSTALLER; + const target = process.env.OCX_IDENTITY_TARGET; + if ((installer || target) && (!(installer === "npm" || installer === "pnpm") || !target)) return 1; + const identity = await inspectNodeOrchestratedIdentity(cliRoot, target, installer as "npm" | "pnpm" | undefined); + const health = identity.kind === "live" ? await proxyIdentityAt(identity.runtime.port, + { hostname: identity.runtime.hostname, expectedPid: identity.runtime.pid }) : null; + console.log(JSON.stringify({ ...identity, healthVersion: health?.version ?? null })); + return 0; + } catch { return 1; } +} +if (import.meta.main) process.exitCode = await runIdentityProbe(process.argv.slice(2), process.env.OCX_IDENTITY_CLI_ROOT); diff --git a/src/update/orchestrated-identity.ts b/src/update/orchestrated-identity.ts new file mode 100644 index 00000000000..bbc8f0d08cd --- /dev/null +++ b/src/update/orchestrated-identity.ts @@ -0,0 +1,51 @@ +import { dirname, isAbsolute, join } from "node:path"; +import { isValidRuntimePortState, type RuntimePortState } from "../config/process-state"; +import { isLocalAttestationSecret } from "../lib/local-management-attestation"; +import type { HomeOwnershipProof } from "../server/proxy-liveness"; + +type RecordRead = { kind: "record"; raw: string } | { kind: "missing" } | { kind: "unreadable" }; +type RuntimeIdentity = { pid: number; port: number; hostname: string; command: readonly string[] }; +export type ServingIdentity = + | { kind: "unknown" | "absent" | "mismatch" } + | { kind: "live"; servingRoot: string; runtime: RuntimeIdentity }; + +export interface ServingIdentityDeps { + readRecord(): RecordRead; + prove(record: RuntimePortState): Promise; + probeConfigured(): Promise<"live" | "dead" | "unknown">; + legacyExecutableDiffers?(pid: number): Promise; + realpath(path: string): string; +} + +/** A live listener is usable only when it attests the same record observed before and after. */ +export async function inspectOrchestratedServingIdentity(deps: ServingIdentityDeps): Promise { + try { + const first = deps.readRecord(); + if (first.kind === "unreadable") return { kind: "unknown" }; + if (first.kind === "missing") { + const endpoint = await deps.probeConfigured(); + return endpoint === "dead" && deps.readRecord().kind === "missing" ? { kind: "absent" } : { kind: "unknown" }; + } + const parsed: unknown = JSON.parse(first.raw); + if (!isValidRuntimePortState(parsed) || !isLocalAttestationSecret(parsed.attestationSecret)) return { kind: "unknown" }; + if (await deps.prove(parsed) !== "proven") return { kind: "unknown" }; + const after = deps.readRecord(); + if (after.kind !== "record" || after.raw !== first.raw) return { kind: "unknown" }; + const command: unknown = parsed.command; + if (command === undefined) { + return await deps.legacyExecutableDiffers?.(parsed.pid) ? { kind: "mismatch" } : { kind: "unknown" }; + } + if (!Array.isArray(command) || command.length < 1 || command.length > 2 || !command.every(part => typeof part === "string" && isAbsolute(part))) return { kind: "unknown" }; + let servingRoot: string; + if (command.length === 1) servingRoot = deps.realpath(command[0]); + else { + const source = command[1] as string; + const root = dirname(dirname(dirname(source))); + if (join(root, "src", "cli", "index.ts") !== source) return { kind: "unknown" }; + servingRoot = deps.realpath(root); + } + return { kind: "live", servingRoot, runtime: { pid: parsed.pid, port: parsed.port, hostname: parsed.hostname ?? "127.0.0.1", command } }; + } catch { + return { kind: "unknown" }; + } +} diff --git a/src/update/orchestrated-live-identity.ts b/src/update/orchestrated-live-identity.ts new file mode 100644 index 00000000000..ee7b7dfeddc --- /dev/null +++ b/src/update/orchestrated-live-identity.ts @@ -0,0 +1,48 @@ +import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync } from "node:fs"; +import { join } from "node:path"; +import { assertNotRealHomeUnderTest } from "../lib/test-home-guard"; +import { probeEndpointLiveness, proveLiveProxyOwnedByHome } from "../server/proxy-liveness"; +import { processIdentity, procfs, windowsProcessPair } from "../service/desktop-supervision.mjs"; +import { inspectOrchestratedServingIdentity } from "./orchestrated-identity"; + +function readRuntimeRecord(home: string): { kind: "record"; raw: string } | { kind: "missing" } | { kind: "unreadable" } { + const path = join(home, "runtime-port.json"); + let observed = false, fd: number | undefined; + try { + const before = lstatSync(path); + observed = true; + if (!before.isFile() || before.size > 32_768) return { kind: "unreadable" }; + fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)); + const opened = fstatSync(fd); + if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino || opened.size !== before.size) return { kind: "unreadable" }; + const bytes = Buffer.alloc(32_769); + const count = readSync(fd, bytes, 0, bytes.length, 0); + if (count !== opened.size || count > 32_768) return { kind: "unreadable" }; + const after = lstatSync(path); + if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeMs !== after.mtimeMs) return { kind: "unreadable" }; + return { kind: "record", raw: new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, count)) }; + } catch (error) { + return !observed && (error as NodeJS.ErrnoException).code === "ENOENT" ? { kind: "missing" } : { kind: "unreadable" }; + } finally { if (fd !== undefined) closeSync(fd); } +} + +/** Read the specified home only; listener possession of its record key proves a live identity. */ +export async function inspectLiveOrchestratedIdentity(home: string, configured: { port: number; hostname?: string }) { + assertNotRealHomeUnderTest(home); + return inspectOrchestratedServingIdentity({ + readRecord: () => readRuntimeRecord(home), + realpath: path => realpathSync.native(path), + probeConfigured: () => probeEndpointLiveness(configured), + prove: record => proveLiveProxyOwnedByHome({ pid: record.pid, port: record.port, hostname: record.hostname, source: "runtime" }, { readRuntimeFn: () => record }), + legacyExecutableDiffers: async pid => { + try { + const executable = process.platform === "linux" ? procfs.exe(pid) + : process.platform === "darwin" ? processIdentity(pid)?.executable + : process.platform === "win32" ? windowsProcessPair(pid).child?.exe : undefined; + if (!executable) return false; + const key = (path: string) => process.platform === "win32" ? path.toLowerCase() : path; + return key(realpathSync.native(executable)) !== key(realpathSync.native(process.execPath)); + } catch { return false; } + }, + }); +} diff --git a/src/update/orchestrated-node-driver.mjs b/src/update/orchestrated-node-driver.mjs new file mode 100644 index 00000000000..bcaf5a16b0a --- /dev/null +++ b/src/update/orchestrated-node-driver.mjs @@ -0,0 +1,103 @@ +import { mkdtempSync, readFileSync, rmSync, realpathSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { decideOrchestratedApply } from "./orchestrated-admission.mjs"; +import { encodeOrchestratedExpect } from "./orchestrated-session.mjs"; +import { createUpdatePlanToken } from "./orchestrated-token.mjs"; +import { waitForOrchestratedChild } from "./orchestrated-child.mjs"; +import { classifyOrchestratedOutcome } from "./orchestrated-outcome.mjs"; +import { verifyOrchestratedInstall } from "./orchestrated-tree.mjs"; +import { verifyOrchestratedPnpmInstall } from "./orchestrated-pnpm.mjs"; +import { resolvePnpmGlobalOwner } from "./pnpm-global-install.mjs"; +import { parseOrchestratedUpdateArgs } from "./orchestrated-arguments.mjs"; + +const BOUND = 900_000; + +/** Parent retains stdout and independently verifies all child-reported effects. */ +export async function applyNodeOrchestratedUpdate(request, deps) { + let started = false, exited = false, directory; + let plan; + const base = () => ({ fromVersion: plan?.currentVersion ?? deps.currentVersion, toVersion: plan?.targetVersion ?? null, + installer: deps.installer, childExited: false, childExitCode: null, outcome: null, previousVerified: false, + targetVerified: false, runtimeHealthy: false, restarted: false }); + const uncertain = () => classifyOrchestratedOutcome(base()); + const fail = error => ({ exitCode: 10, result: { ...uncertain().result, error } }); + try { + const bun = deps.resolveBun(); + if (!bun) return fail("plan-unavailable"); + const p = deps.plan(bun, request.version, request.tag); + if (p.status !== 0 || p.error || p.signal || typeof p.stdout !== "string" || Buffer.byteLength(p.stdout) > 65536) return fail("plan-unavailable"); + plan = JSON.parse(p.stdout); + const validVersion = version => typeof version === "string" + && parseOrchestratedUpdateArgs(["--plan", "--json", "--version", version]).ok; + if (!plan || plan.schema !== "ocx.update.plan/1" || !validVersion(plan.currentVersion) + || !(typeof plan.targetVersion === "string" || plan.targetVersion === null) || plan.installer !== deps.installer + || typeof plan.cliPath !== "string" || realpathSync.native(plan.cliPath) !== realpathSync.native(deps.cliRoot) + || typeof plan.canApply !== "boolean" || typeof plan.restartRequired !== "boolean" + || (plan.targetVersion !== null && !validVersion(plan.targetVersion)) + || (plan.canApply && (!plan.targetVersion || plan.reason !== undefined)) + || (!plan.canApply && (typeof plan.reason !== "string" || !plan.reason)) + || !["service", "desktop-app", "unmanaged", "none", "unknown"].includes(plan.runtimeOwner) + || !(plan.servingPath === null || typeof plan.servingPath === "string") || typeof plan.updateInFlight !== "boolean" + || typeof plan.planToken !== "string" || !/^[A-Za-z0-9_-]{16,128}$/.test(plan.planToken) + || plan.mutationBoundMs !== BOUND) throw Error("invalid plan"); + const admission = decideOrchestratedApply(plan, request, Date.now()); + if (admission.kind === "done") return admission; + const before = deps.identity(bun); + const live = before.kind === "live" ? before : null; + if ((before.kind !== "live" && before.kind !== "absent") || !plan.targetVersion + || Boolean(live) !== plan.restartRequired || (live?.servingRoot ?? null) !== plan.servingPath + || createUpdatePlanToken({ currentVersion: plan.currentVersion, targetVersion: plan.targetVersion, + installer: plan.installer, cliRoot: plan.cliPath, servingRoot: live?.servingRoot ?? null, + runtimeOwner: plan.runtimeOwner, runtime: live?.runtime ?? null }) !== plan.planToken) return fail("plan-changed"); + let owner; + if (deps.installer === "pnpm") { + const resolved = resolvePnpmGlobalOwner({ packageName: "@bitkyc08/opencodex", packagePath: plan.cliPath, + commandPaths: deps.pnpmCommands, runningShimPath: deps.runningShimPath, runPnpm: deps.runPnpm }); + if (!resolved.ok) return fail("plan-unavailable"); + owner = resolved.owner; + } + const start = Date.now(); + directory = mkdtempSync(join(tmpdir(), "ocx-update-")); + const resultPath = join(directory, "result.json"); + const expect = encodeOrchestratedExpect({ home: deps.home, cliRoot: plan.cliPath, servingRoot: live?.servingRoot ?? null, + runtimePid: live?.runtime.pid ?? null, planToken: plan.planToken }); + const args = [deps.launcher, "update", "--version", plan.targetVersion, "--orchestrated-expect", expect, + "--orchestrated-result", resultPath, ...(request.notAfter === undefined ? [] : ["--not-after", String(request.notAfter)])]; + const child = deps.spawn(process.execPath, args, { env: { ...process.env, OCX_UPDATE_ORCHESTRATED_CHILD: "1" }, stdio: ["ignore", 2, 2] }); + started = true; + const waited = await waitForOrchestratedChild(child, { overrunMs: (request.notAfter ?? start) + BOUND - Date.now() }); + if (!waited.confirmed) { + child.unref(); + return waited.reason === "overrun" ? { exitCode: 12, result: { ...uncertain().result, error: "overrun" } } : uncertain(); + } + exited = true; + let outcome = null; + try { outcome = JSON.parse(readFileSync(resultPath, "utf8")); } catch { /* unknown outcome */ } + const activeRoot = outcome?.phase === "installed" ? outcome.activeRoot : plan.cliPath; + const verify = (root, version) => deps.installer === "npm" + ? root === plan.cliPath && verifyOrchestratedInstall(root, version, "npm") + : verifyOrchestratedPnpmInstall({ owner, activeRoot: root, version, runPnpm: deps.runPnpm }); + const targetVerified = outcome?.phase === "installed" && verify(activeRoot, plan.targetVersion); + const previousVerified = verify(plan.cliPath, plan.currentVersion); + let runtimeHealthy = !plan.restartRequired, restarted = false; + if (plan.restartRequired) { + try { + const afterBun = deps.resolveBun(); + const after = afterBun ? deps.identity(afterBun) : null; + if (after?.kind === "live" && after.servingRoot === activeRoot) { + runtimeHealthy = after.healthVersion === (outcome?.phase === "installed" ? plan.targetVersion : plan.currentVersion); + restarted = after.runtime.pid !== live?.runtime.pid; + } + } catch { + return { exitCode: 12, result: { ...uncertain().result, applied: targetVerified, error: "runtime-unverified" } }; + } + } + return classifyOrchestratedOutcome({ ...base(), childExited: true, childExitCode: waited.code, outcome, + previousVerified, targetVerified, runtimeHealthy, restarted }); + } catch { + return started ? uncertain() : fail("plan-unavailable"); + } finally { + if (directory && (!started || exited)) { try { rmSync(directory, { recursive: true, force: true }); } catch { /* best effort */ } } + } +} diff --git a/src/update/orchestrated-outcome.d.mts b/src/update/orchestrated-outcome.d.mts new file mode 100644 index 00000000000..35fb900d739 --- /dev/null +++ b/src/update/orchestrated-outcome.d.mts @@ -0,0 +1,21 @@ +export type Outcome = ({ phase: "preflight" | "mutating" | "overrun" } + | { phase: "installed"; activeRoot: string; recoveryFailed?: boolean; error?: string } + | { phase: "refused"; error?: string } + | { phase: "failed"; error?: string; rollbackPerformed?: boolean }) & { terminationConfirmed?: boolean }; +export interface OutcomeInput { + fromVersion: string; + toVersion: string | null; + installer: "npm" | "pnpm" | "bun" | "mise" | "desktop-app" | "source" | "unknown"; + childExited: boolean; + childExitCode: number | null; + outcome: Outcome | null; + previousVerified: boolean; + targetVerified: boolean; + runtimeHealthy: boolean; + restarted: boolean; +} +export declare function classifyOrchestratedOutcome(input: OutcomeInput): { + exitCode: 0 | 10 | 11 | 12; + result: { schema: "ocx.update.result/1"; applied: boolean; fromVersion: string; toVersion: string | null; + installer: OutcomeInput["installer"]; restarted: boolean; healthy: boolean; rolledBack: boolean; error?: string }; +}; diff --git a/src/update/orchestrated-outcome.mjs b/src/update/orchestrated-outcome.mjs new file mode 100644 index 00000000000..22487d8ad1e --- /dev/null +++ b/src/update/orchestrated-outcome.mjs @@ -0,0 +1,40 @@ +import { isAbsolute } from "node:path"; + +function validOutcome(outcome) { + if (!outcome || typeof outcome !== "object" || Array.isArray(outcome)) return false; + if (!["preflight", "mutating", "installed", "failed", "refused", "overrun"].includes(outcome.phase)) return false; + if (outcome.error !== undefined && typeof outcome.error !== "string") return false; + if (outcome.rollbackPerformed !== undefined && typeof outcome.rollbackPerformed !== "boolean") return false; + if (outcome.terminationConfirmed !== undefined && typeof outcome.terminationConfirmed !== "boolean") return false; + return outcome.phase !== "installed" || (typeof outcome.activeRoot === "string" && isAbsolute(outcome.activeRoot)); +} + +/** Classify only independently observed state after confirmed child termination. */ +export function classifyOrchestratedOutcome(input) { + const result = { + schema: "ocx.update.result/1", applied: false, fromVersion: input.fromVersion, + toVersion: input.toVersion, installer: input.installer, restarted: false, + healthy: false, rolledBack: false, + }; + const done = (exitCode, error) => ({ exitCode, result: error ? { ...result, error } : result }); + if (!input.childExited || input.childExitCode === null || !validOutcome(input.outcome) || input.outcome.phase === "overrun") return done(12, "outcome-unverified"); + if (input.outcome.terminationConfirmed === false) return done(12, input.outcome.error || "installer-termination-unconfirmed"); + if (input.outcome.phase === "refused" && input.childExitCode !== 0) return done(10, input.outcome.error || "runtime-ownership-refused"); + if (input.outcome.phase === "failed" && input.outcome.error === "installer-termination-unconfirmed") return done(12, input.outcome.error); + if (input.outcome.phase === "installed") { + result.applied = input.targetVerified; + result.restarted = input.restarted; + result.healthy = input.targetVerified && input.runtimeHealthy && input.childExitCode === 0; + if (!input.targetVerified) return done(12, "install-unverified"); + if (!result.healthy) return done(12, "runtime-unhealthy"); + return done(0); + } + if (["preflight", "mutating", "failed"].includes(input.outcome.phase) && input.childExitCode !== 0 + && input.previousVerified && input.runtimeHealthy) { + result.healthy = true; + result.restarted = input.restarted; + result.rolledBack = input.outcome.phase === "failed" && input.outcome.rollbackPerformed === true; + return done(11, input.outcome.error || "update-failed"); + } + return done(12, "outcome-unverified"); +} diff --git a/src/update/orchestrated-plan.ts b/src/update/orchestrated-plan.ts new file mode 100644 index 00000000000..92146e75f85 --- /dev/null +++ b/src/update/orchestrated-plan.ts @@ -0,0 +1,49 @@ +import { compareStrictSemver, parseStrictSemver } from "../lib/strict-semver"; +import { createUpdatePlanToken } from "./orchestrated-token.mjs"; +import type { ServingIdentity } from "./orchestrated-identity"; + +export const ORCHESTRATED_MUTATION_BOUND_MS = 900_000; +type Installer = "npm" | "pnpm" | "bun" | "mise" | "desktop-app" | "source" | "unknown"; +type RuntimeOwner = "service" | "desktop-app" | "unmanaged" | "none" | "unknown"; +type Reason = "desktop-app-owned" | "source-checkout" | "mise-managed" | "installer-unknown" | "plan-unavailable" | "serving-install-unknown" | "cli-not-serving-install" | "runtime-ownership-refused" | "target-unresolved" | "downgrade-refused" | "up-to-date"; + +export interface PlanInputs { + currentVersion: string; + targetVersion: string | null; + installer: Installer; + runtimeOwner: RuntimeOwner; + cliRoot: string; + identity: ServingIdentity; + ownershipPermits: boolean; + updateInFlight: boolean; +} + +/** Construct the public plan from already-observed facts, refusing every uncertain boundary. */ +export function buildOrchestratedPlan(input: PlanInputs) { + const live = input.identity.kind === "live" ? input.identity : null; + const servingRoot = live?.servingRoot ?? null; + const current = parseStrictSemver(input.currentVersion); + const target = parseStrictSemver(input.targetVersion); + let reason: Reason | undefined; + if (input.installer === "desktop-app") reason = "desktop-app-owned"; + else if (input.installer === "source") reason = "source-checkout"; + else if (input.installer === "mise") reason = "mise-managed"; + else if (input.installer === "unknown") reason = "installer-unknown"; + else if (input.identity.kind === "unknown") reason = "serving-install-unknown"; + else if (input.identity.kind === "mismatch") reason = "cli-not-serving-install"; + else if (live && servingRoot !== input.cliRoot) reason = "cli-not-serving-install"; + else if (!input.ownershipPermits || input.runtimeOwner === "unknown") reason = "runtime-ownership-refused"; + else if (!current || !target) reason = "target-unresolved"; + else if (compareStrictSemver(target, current) < 0) reason = "downgrade-refused"; + else if (compareStrictSemver(target, current) === 0) reason = "up-to-date"; + const planToken = createUpdatePlanToken({ + currentVersion: input.currentVersion, targetVersion: input.targetVersion, installer: input.installer, + cliRoot: input.cliRoot, servingRoot, runtimeOwner: input.runtimeOwner, runtime: live?.runtime ?? null, + }); + return { + schema: "ocx.update.plan/1" as const, currentVersion: input.currentVersion, targetVersion: input.targetVersion, + installer: input.installer, runtimeOwner: input.runtimeOwner, servingPath: servingRoot, cliPath: input.cliRoot, + canApply: reason === undefined, ...(reason ? { reason } : {}), restartRequired: live !== null, + planToken, updateInFlight: input.updateInFlight, mutationBoundMs: ORCHESTRATED_MUTATION_BOUND_MS, + }; +} diff --git a/src/update/orchestrated-pnpm.d.mts b/src/update/orchestrated-pnpm.d.mts new file mode 100644 index 00000000000..a6a4d86dac2 --- /dev/null +++ b/src/update/orchestrated-pnpm.d.mts @@ -0,0 +1,8 @@ +import type { PnpmGlobalOwner, RunPnpmCandidate } from "./pnpm-global-install.mjs"; + +export declare function verifyOrchestratedPnpmInstall(options: { + owner: PnpmGlobalOwner; + activeRoot: string; + version: string; + runPnpm: RunPnpmCandidate; +}): boolean; diff --git a/src/update/orchestrated-pnpm.mjs b/src/update/orchestrated-pnpm.mjs new file mode 100644 index 00000000000..6a6c133381c --- /dev/null +++ b/src/update/orchestrated-pnpm.mjs @@ -0,0 +1,33 @@ +import { readFileSync, realpathSync, statSync } from "node:fs"; +import { join } from "node:path"; +import { readPnpmGlobalPackage, resolvePnpmGlobalOwner } from "./pnpm-global-install.mjs"; +import { verifyPnpmInstallTree } from "./transactional-install.mjs"; + +const PACKAGE_NAME = "@bitkyc08/opencodex"; + +/** Re-resolve the selected pnpm group and verify its active tree and generated shims. */ +export function verifyOrchestratedPnpmInstall({ owner, activeRoot, version, runPnpm }) { + try { + const key = path => { + const result = realpathSync.native(path); + return process.platform === "win32" ? result.toLowerCase() : result; + }; + const verify = (path, expected) => { + try { + const manifest = JSON.parse(readFileSync(join(path, "package.json"), "utf8")); + const source = statSync(join(path, "src", "cli", "index.ts")); + return { ok: manifest.version === expected && Boolean(manifest.dependencies?.bun && manifest.dependencies?.zod) + && source.isFile() && source.size > 0 && verifyPnpmInstallTree(path, expected).ok }; + } catch { return { ok: false }; } + }; + const resolved = resolvePnpmGlobalOwner({ packageName: PACKAGE_NAME, packagePath: activeRoot, + commandPaths: [owner.commandPath], runPnpm, verify }); + if (!resolved.ok || key(resolved.owner.globalDir) !== key(owner.globalDir) + || key(resolved.owner.globalRoot) !== key(owner.globalRoot) + || key(resolved.owner.globalBinDir) !== key(owner.globalBinDir)) return false; + const active = readPnpmGlobalPackage(PACKAGE_NAME, + (args, capture) => runPnpm(owner.commandPath, args, capture), verify, + { owner, expectedPackagePath: activeRoot, expectedGlobalRoot: owner.globalRoot, globalBinDir: owner.globalBinDir }); + return active.ok && active.version === version && key(active.path) === key(activeRoot); + } catch { return false; } +} diff --git a/src/update/orchestrated-session.d.mts b/src/update/orchestrated-session.d.mts new file mode 100644 index 00000000000..01a65ff4ac2 --- /dev/null +++ b/src/update/orchestrated-session.d.mts @@ -0,0 +1,27 @@ +export interface OrchestratedExpect { + home: string; + cliRoot: string; + servingRoot: string | null; + runtimePid: number | null; + planToken: string; +} +export declare function encodeOrchestratedExpect(value: OrchestratedExpect): string; +export declare function decodeOrchestratedExpect(encoded: string): OrchestratedExpect; +export declare function createOrchestratedChildSession(options: { + home: string; + resultPath: string; + expect: OrchestratedExpect; + notAfter?: number; + now?: () => number; + pid?: number; + verifyIdentity: () => boolean | Promise; +}): { + start(): { ok: true } | { ok: false; error: "sync-in-progress" | "update-in-flight" }; + finishPreflight(): void; + enterMutation(): Promise<{ ok: true } | { ok: false; error: "sync-in-progress" | "update-in-flight" | "deadline-passed" | "plan-changed" }>; + noteUntrackedInstaller(): void; + confirmInstallerExit(): void; + retainInstallerFence(): void; + finish(outcome: ({ phase: "installed"; activeRoot: string } | { phase: "failed"; error?: string; rollbackPerformed?: boolean }) & { terminationConfirmed?: boolean }): void; +}; +export declare function createLegacyUpdateSession(options: { home: string }): ReturnType; diff --git a/src/update/orchestrated-session.mjs b/src/update/orchestrated-session.mjs new file mode 100644 index 00000000000..dbd6cf60fb1 --- /dev/null +++ b/src/update/orchestrated-session.mjs @@ -0,0 +1,140 @@ +import { randomUUID } from "node:crypto"; +import { readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs"; +import { basename, dirname, isAbsolute, join } from "node:path"; +import { inspectUpdateMarker, tryAcquireUpdateSyncMutex } from "./sync-update-mutex.mjs"; +import { assertNotRealHomeUnderTest } from "./test-home-guard.mjs"; + +function atomicJson(path, value) { + const temp = join(dirname(path), `.${basename(path)}.${process.pid}.${randomUUID()}.tmp`); + let created = false; + try { + writeFileSync(temp, `${JSON.stringify(value)}\n`, { encoding: "utf8", flag: "wx", mode: 0o600 }); + created = true; + renameSync(temp, path); + created = false; + } finally { + if (created) { try { unlinkSync(temp); } catch { /* preserve the original write error */ } } + } +} + +function validateExpect(value) { + if (!value || typeof value !== "object" || Array.isArray(value) + || Object.keys(value).sort().join(",") !== "cliRoot,home,planToken,runtimePid,servingRoot" + || typeof value.home !== "string" || !isAbsolute(value.home) + || typeof value.cliRoot !== "string" || !isAbsolute(value.cliRoot) + || (value.servingRoot !== null && (typeof value.servingRoot !== "string" || !isAbsolute(value.servingRoot))) + || (value.runtimePid !== null && (!Number.isSafeInteger(value.runtimePid) || value.runtimePid <= 0)) + || typeof value.planToken !== "string" || !/^[A-Za-z0-9_-]{16,128}$/.test(value.planToken)) { + throw new Error("invalid orchestrated expectation"); + } + return value; +} +export function encodeOrchestratedExpect(value) { + return Buffer.from(JSON.stringify(validateExpect(value)), "utf8").toString("base64url"); +} +export function decodeOrchestratedExpect(encoded) { + if (typeof encoded !== "string" || !/^[A-Za-z0-9_-]+$/.test(encoded)) throw new Error("invalid orchestrated expectation"); + const bytes = Buffer.from(encoded, "base64url"); + if (bytes.toString("base64url") !== encoded) throw new Error("invalid orchestrated expectation"); + let parsed; + try { parsed = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); } catch { throw new Error("invalid orchestrated expectation"); } + return validateExpect(parsed); +} + +export function createOrchestratedChildSession({ home, resultPath, expect, notAfter, now = Date.now, pid = process.pid, verifyIdentity }) { + if (expect !== undefined) validateExpect(expect); + if ((expect !== undefined && expect.home !== home) || (resultPath !== undefined && (typeof resultPath !== "string" || !isAbsolute(resultPath))) + || (notAfter !== undefined && (!Number.isSafeInteger(notAfter) || notAfter <= 0)) + || !Number.isSafeInteger(pid) || pid <= 0 || typeof now !== "function" || typeof verifyIdentity !== "function") { + throw new Error("invalid orchestrated session options"); + } + assertNotRealHomeUnderTest(home); + const markerPath = join(home, "update-orchestrated.json"); + const result = value => { if (resultPath !== undefined) atomicJson(resultPath, value); }; + let state = "new", mutex, startedAt, untrackedPending = false, retainFence = false; + const marker = (phase, preserveInstaller = false, terminationUnconfirmed = false, retainFence = false) => { + let installer = {}; + if (preserveInstaller) { + const current = JSON.parse(readFileSync(markerPath, "utf8")); + if (current.pid !== pid || current.startedAt !== startedAt) throw new Error("orchestrated marker changed"); + if (current.installerPid !== undefined) installer.installerPid = current.installerPid; + if (current.installerPgid !== undefined) installer.installerPgid = current.installerPgid; + } + atomicJson(markerPath, { pid, phase, startedAt, ...installer, + ...((phase === "mutating" || retainFence) ? { fenceUntil: startedAt + 900000 } : {}), + ...(terminationUnconfirmed ? { terminationUnconfirmed: true } : {}) }); + }; + return { + start() { + if (state !== "new") throw new Error("orchestrated session already started"); + result({ phase: "preflight" }); + const acquired = tryAcquireUpdateSyncMutex(home, "update"); + if (acquired.kind === "busy") { + const error = acquired.holder === "sync" ? "sync-in-progress" : "update-in-flight"; + result({ phase: "refused", error }); state = "refused"; + return { ok: false, error }; + } + mutex = acquired; + if (inspectUpdateMarker(home) !== "free") { + mutex.release(); mutex = undefined; + result({ phase: "refused", error: "update-in-flight" }); state = "refused"; + return { ok: false, error: "update-in-flight" }; + } + try { startedAt = now(); marker("preflight"); } + catch (error) { mutex.release(); mutex = undefined; throw error; } + state = "preflight"; + return { ok: true }; + }, + finishPreflight() { + if (state !== "preflight") return; + marker("failed"); + mutex.release(); mutex = undefined; state = "finished"; + }, + async enterMutation() { + if (state !== "preflight") throw new Error("orchestrated session is not in preflight"); + state = "entering"; + marker("mutating"); + result({ phase: "mutating" }); + let error; + if (notAfter !== undefined && now() > notAfter) error = "deadline-passed"; + else { + try { if (await verifyIdentity() !== true) error = "plan-changed"; } + catch { error = "plan-changed"; } + } + if (!error && notAfter !== undefined && now() > notAfter) error = "deadline-passed"; + if (error) { + marker("refused"); + result({ phase: "refused", error }); + mutex.release(); mutex = undefined; state = "refused"; + return { ok: false, error }; + } + state = "mutating"; + return { ok: true }; + }, + noteUntrackedInstaller() { + if (state !== "mutating") throw new Error("orchestrated session is not mutating"); + marker("mutating", true, true); untrackedPending = true; + }, + confirmInstallerExit() { + if (state !== "mutating" || !untrackedPending) throw new Error("no untracked installer"); + marker("mutating", true); untrackedPending = false; + }, + retainInstallerFence() { + if (state !== "mutating") throw new Error("orchestrated session is not mutating"); + retainFence = true; + }, + finish(outcome) { + if (state !== "mutating") throw new Error("orchestrated session is not mutating"); + if (!outcome || (outcome.phase !== "installed" && outcome.phase !== "failed")) throw new Error("invalid final outcome"); + if (untrackedPending) outcome = { phase: "failed", error: "installer-termination-unconfirmed", terminationConfirmed: false }; + result(outcome); + marker(outcome.phase, true, outcome.error === "installer-termination-unconfirmed", + retainFence || outcome.terminationConfirmed === false || outcome.error === "installer-termination-unconfirmed" || outcome.error === "installer-timeout"); + mutex.release(); mutex = undefined; state = "finished"; + }, + }; +} + +export function createLegacyUpdateSession({ home }) { + return createOrchestratedChildSession({ home, verifyIdentity: () => true }); +} diff --git a/src/update/orchestrated-token.d.mts b/src/update/orchestrated-token.d.mts new file mode 100644 index 00000000000..0d0a7a20f71 --- /dev/null +++ b/src/update/orchestrated-token.d.mts @@ -0,0 +1,10 @@ +export interface UpdatePlanTokenInput { + currentVersion: string; + targetVersion: string | null; + installer: string; + cliRoot: string; + servingRoot: string | null; + runtimeOwner: string; + runtime: { pid: number; port: number; hostname: string; command: readonly string[] } | null; +} +export declare function createUpdatePlanToken(input: UpdatePlanTokenInput): string; diff --git a/src/update/orchestrated-token.mjs b/src/update/orchestrated-token.mjs new file mode 100644 index 00000000000..2bc09e7a547 --- /dev/null +++ b/src/update/orchestrated-token.mjs @@ -0,0 +1,21 @@ +import { createHash } from "node:crypto"; + +/** Hash only the explicitly bound fields in a fixed order, never a runtime proof key. */ +export function createUpdatePlanToken(input) { + const runtime = input.runtime === null ? null : { + pid: input.runtime.pid, + port: input.runtime.port, + hostname: input.runtime.hostname, + command: [...input.runtime.command], + }; + const canonical = { + currentVersion: input.currentVersion, + targetVersion: input.targetVersion, + installer: input.installer, + cliRoot: input.cliRoot, + servingRoot: input.servingRoot, + runtimeOwner: input.runtimeOwner, + runtime, + }; + return createHash("sha256").update(JSON.stringify(canonical)).digest("base64url"); +} diff --git a/src/update/orchestrated-token.ts b/src/update/orchestrated-token.ts new file mode 100644 index 00000000000..0eeeaa4c1b0 --- /dev/null +++ b/src/update/orchestrated-token.ts @@ -0,0 +1,3 @@ +// Preserve the TypeScript import path while sharing the implementation with Node. +export { createUpdatePlanToken } from "./orchestrated-token.mjs"; +export type { UpdatePlanTokenInput } from "./orchestrated-token.mjs"; diff --git a/src/update/orchestrated-tree.d.mts b/src/update/orchestrated-tree.d.mts new file mode 100644 index 00000000000..25c8a9a54f3 --- /dev/null +++ b/src/update/orchestrated-tree.d.mts @@ -0,0 +1 @@ +export declare function verifyOrchestratedInstall(root: string, version: string, installer: "npm" | "bun"): boolean; diff --git a/src/update/orchestrated-tree.mjs b/src/update/orchestrated-tree.mjs new file mode 100644 index 00000000000..8256084e4c8 --- /dev/null +++ b/src/update/orchestrated-tree.mjs @@ -0,0 +1,14 @@ +import { readFileSync, statSync } from "node:fs"; +import { join } from "node:path"; +import { verifyInstallTree } from "./transactional-install.mjs"; + +/** npm and Bun verification reads the active tree only; retained backup siblings are irrelevant. */ +export function verifyOrchestratedInstall(root, version, installer) { + if (installer !== "npm" && installer !== "bun") return false; + try { + const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8")); + if (manifest.version !== version || !manifest.dependencies?.bun || !manifest.dependencies?.zod) return false; + const source = statSync(join(root, "src", "cli", "index.ts")); + return source.isFile() && source.size > 0 && verifyInstallTree(root, version).ok; + } catch { return false; } +} diff --git a/src/update/pnpm-global-install.d.mts b/src/update/pnpm-global-install.d.mts index 5dc5b6004a4..af9e18a5d2b 100644 --- a/src/update/pnpm-global-install.d.mts +++ b/src/update/pnpm-global-install.d.mts @@ -1,5 +1,7 @@ export interface PnpmRunResult { status: number | null; + processTreeExited?: boolean; + groupExited?: boolean; stdout?: string | Uint8Array | null; stderr?: string | Uint8Array | null; } @@ -119,6 +121,10 @@ export type PnpmGlobalUpdateResult = ok: false; phase: "preflight" | "install" | "rollback"; rolledBack?: boolean; + uncertain?: boolean; + processTreeExited?: boolean; + /** True only when a rollback transaction restored and verified the previous version. */ + rollbackPerformed?: boolean; activePath?: string; globalDir?: string; globalBinDir?: string; diff --git a/src/update/pnpm-global-install.mjs b/src/update/pnpm-global-install.mjs index a038a374f04..355d482c7ad 100644 --- a/src/update/pnpm-global-install.mjs +++ b/src/update/pnpm-global-install.mjs @@ -512,8 +512,10 @@ export function runPnpmGlobalUpdate({ try { install = runPnpm(ownerGlobalArgs(["add", "-g", PNPM_BUILD_APPROVAL, spec], owner), false); } catch { - install = { status: 1 }; + install = { status: null, processTreeExited: false }; } + if (!Number.isInteger(install?.status) || install?.processTreeExited === false || install?.groupExited === false) return { ok: false, phase: "install", processTreeExited: false, rolledBack: false, uncertain: true, + error: "installer-termination-unconfirmed" }; // The package path may switch to a different group link, so only constrain // the group/bin pair after the command; the active package path is intentionally open. @@ -548,6 +550,7 @@ export function runPnpmGlobalUpdate({ ok: false, phase: "install", rolledBack: true, + rollbackPerformed: false, activePath: after.path, globalDir: owner.globalDir, globalBinDir: owner.globalBinDir, @@ -560,8 +563,10 @@ export function runPnpmGlobalUpdate({ try { rollback = runPnpm(ownerGlobalArgs(["add", "-g", PNPM_BUILD_APPROVAL, packageSpec(packageName, before.version)], owner), false); } catch { - rollback = { status: 1 }; + rollback = { status: null, processTreeExited: false }; } + if (!Number.isInteger(rollback?.status) || rollback?.processTreeExited === false || rollback?.groupExited === false) return { ok: false, phase: "rollback", processTreeExited: false, rolledBack: false, uncertain: true, + error: "installer-termination-unconfirmed" }; const restored = readPnpmGlobalPackage( packageName, runPnpm, @@ -573,6 +578,7 @@ export function runPnpmGlobalUpdate({ ok: false, phase: "rollback", rolledBack: true, + rollbackPerformed: true, activePath: restored.path, globalDir: owner.globalDir, globalBinDir: owner.globalBinDir, @@ -583,6 +589,7 @@ export function runPnpmGlobalUpdate({ ok: false, phase: "rollback", rolledBack: false, + rollbackPerformed: false, ...(restored.ok ? { activePath: restored.path } : {}), globalDir: owner.globalDir, globalBinDir: owner.globalBinDir, diff --git a/src/update/posix-install-supervisor-entry.mjs b/src/update/posix-install-supervisor-entry.mjs new file mode 100644 index 00000000000..c9c2bc9eb54 --- /dev/null +++ b/src/update/posix-install-supervisor-entry.mjs @@ -0,0 +1,6 @@ +import { runPosixInstallerSupervisorMain } from "./posix-install-supervisor.mjs"; + +runPosixInstallerSupervisorMain().catch(error => { + console.error("opencodex: installer supervisor failed: " + (error instanceof Error ? error.message : String(error))); + process.exitCode = 1; +}); diff --git a/src/update/posix-install-supervisor.d.mts b/src/update/posix-install-supervisor.d.mts new file mode 100644 index 00000000000..2390c2b523f --- /dev/null +++ b/src/update/posix-install-supervisor.d.mts @@ -0,0 +1,10 @@ +export declare function runPosixInstallerSync(options: { + file: string; + args: string[]; + markerPath: string; + timeoutMs?: number; + env?: NodeJS.ProcessEnv; + cwd?: string; + authorizeMutation?: (kind: "package") => boolean; +}): { status: number | null; signal?: NodeJS.Signals | null; groupExited: boolean; groupKilled?: boolean; processTreeExited?: boolean }; +export declare function runPosixInstallerSupervisorMain(): Promise; diff --git a/src/update/posix-install-supervisor.mjs b/src/update/posix-install-supervisor.mjs new file mode 100644 index 00000000000..1eda6ad0293 --- /dev/null +++ b/src/update/posix-install-supervisor.mjs @@ -0,0 +1,88 @@ +import { spawn } from "node:child_process"; +import { guardedSpawnSync } from "./mutation-guard.mjs"; +import { readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { dirname, join } from "node:path"; +import { randomUUID } from "node:crypto"; + +// The supervisor runs through a dedicated entry file: this library is also bundled into the +// compiled CLI, where every module shares one entry URL, so it must have no top-level effects. +const entry = join(dirname(fileURLToPath(import.meta.url)), "posix-install-supervisor-entry.mjs"); +const failed = message => ({ status: null, groupExited: false, processTreeExited: false, error: { code: "EINSTALLJOIN", message } }); + +// The synchronous transaction waits for this separate supervisor, which keeps a +// detached group leader blocked until its pid and pgid are durable in the marker. +export function runPosixInstallerSync({ file, args, markerPath, timeoutMs = 180000, env, cwd, authorizeMutation = () => true }) { + if (!authorizeMutation("package")) return { status: 1, groupExited: true, groupKilled: false }; + const input = JSON.stringify({ file, args, markerPath, timeoutMs, cwd }); + const result = guardedSpawnSync(authorizeMutation, "package", process.execPath, [entry, "supervise"], { input, encoding: "utf8", env, cwd, stdio: ["pipe", "pipe", "inherit"] }); + try { + const value = JSON.parse(result.stdout); + if (result.status !== 0 || typeof value.groupExited !== "boolean" || typeof value.groupKilled !== "boolean" + || !(value.status === null || Number.isInteger(value.status)) || !(value.signal === null || typeof value.signal === "string")) throw Error("invalid result"); + return value; + } catch { return failed("installer supervisor did not confirm process-tree exit"); } +} + +function publish(path, pid) { + const marker = JSON.parse(readFileSync(path, "utf8")); + if (marker.phase !== "mutating" || !Number.isSafeInteger(marker.pid)) throw Error("invalid update marker"); + const temp = `${path}.${randomUUID()}.tmp`; + let created = false; + try { + writeFileSync(temp, JSON.stringify({ ...marker, installerPid: pid, installerPgid: pid }), { flag: "wx", mode: 0o600 }); + created = true; + renameSync(temp, path); + created = false; + } finally { + if (created) try { unlinkSync(temp); } catch (error) { if (error.code !== "ENOENT") throw error; } + } +} + +function alive(pgid) { + try { process.kill(-pgid, 0); return true; } + catch (error) { if (error.code === "ESRCH") return false; if (error.code === "EPERM") return true; throw error; } +} + +async function supervise(config) { + const group = spawn(process.execPath, [entry, "install"], { detached: true, stdio: ["pipe", "ignore", "inherit"], cwd: config.cwd, env: process.env }); + const spawned = await new Promise(resolve => { group.once("spawn", () => resolve(true)); group.once("error", () => resolve(false)); }); + if (!spawned || !group.pid) return { status: null, groupExited: true, processTreeExited: false, error: { code: "ESPAWN", message: "installer group could not start" } }; + const pid = group.pid; + try { publish(config.markerPath, pid); } + catch (error) { + try { process.kill(-pid, "SIGKILL"); } + catch (killError) { if (killError.code !== "ESRCH") return failed(`could not publish or terminate installer group: ${killError.message}`); } + return failed(`could not publish installer group: ${error.message}`); + } + const closed = new Promise(resolve => group.once("close", (status, signal) => resolve({ status, signal }))); + group.stdin.on("error", () => {}); + group.stdin.end(JSON.stringify({ file: config.file, args: config.args, cwd: config.cwd })); + let timer; + const timed = new Promise(resolve => { timer = setTimeout(() => resolve(null), config.timeoutMs); }); + const result = await Promise.race([closed, timed]); clearTimeout(timer); + // Even an exited leader may have left descendants in its process group. + let groupKilled = false; + try { if (alive(pid)) { process.kill(-pid, "SIGKILL"); groupKilled = true; } } + catch (error) { if (error.code !== "ESRCH") return failed("could not terminate installer group"); } + const deadline = Date.now() + 10000; + while (Date.now() < deadline) { + try { if (!alive(pid)) return { status: result?.status ?? null, signal: result?.signal ?? null, groupExited: true, groupKilled, + ...(result?.status == null ? { processTreeExited: false } : {}) }; } + catch (error) { return failed(`could not inspect installer group: ${error.code ?? error.message}`); } + await new Promise(resolve => setTimeout(resolve, 50)); + } + return failed("installer group termination was not confirmed"); +} + +/** Entry-point body for posix-install-supervisor-entry.mjs. */ +export async function runPosixInstallerSupervisorMain() { + const input = JSON.parse(readFileSync(0, "utf8")); + if (process.argv[2] === "supervise") { + console.log(JSON.stringify(await supervise(input))); + } else if (process.argv[2] === "install") { + const child = spawn(input.file, input.args, { cwd: input.cwd, env: process.env, stdio: ["ignore", "inherit", "inherit"] }); + child.on("error", () => { process.exitCode = 1; }); + child.on("close", (code, signal) => { if (signal) process.kill(process.pid, signal); else process.exitCode = code ?? 1; }); + } +} diff --git a/src/update/sync-update-mutex.d.mts b/src/update/sync-update-mutex.d.mts new file mode 100644 index 00000000000..7501061d7e2 --- /dev/null +++ b/src/update/sync-update-mutex.d.mts @@ -0,0 +1,10 @@ +export type Holder = "sync" | "update" | "free" | "unknown"; +export type Observation = "free" | "active" | "unknown"; +export type Acquisition = { kind: "acquired"; addDelegate(pid: number): void; release(): void } | { kind: "busy"; holder: Exclude }; +export declare function tryAcquireUpdateSyncMutex(home: string, kind: "sync" | "update", deps?: { now?: () => number; processAlive?: (pid: number) => boolean }): Acquisition; +export declare function inspectUpdateSyncMutex(home: string): Holder; +export declare function parentHoldsSyncMutex(home: string, claimedPid?: string): boolean; +export declare function refuseSync(reason: "update-in-flight" | "sync-in-progress", args: readonly string[]): number; +export declare function acquireSyncGuard(home: string, args: readonly string[]): { kind: "acquired"; addDelegate(pid: number): void; release(): void } | { kind: "refused"; exit: number }; +export declare function inspectUpdateMarker(home: string, deps?: { now?: () => number }): Observation; +export declare function isUpdateInFlight(home: string, deps?: { mutex(home: string): Holder; ownershipLease(home: string): Observation; marker(home: string): Observation }): boolean; diff --git a/src/update/sync-update-mutex.mjs b/src/update/sync-update-mutex.mjs new file mode 100644 index 00000000000..1aefb0dbe9a --- /dev/null +++ b/src/update/sync-update-mutex.mjs @@ -0,0 +1,164 @@ +import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readSync, realpathSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { acquireOwnershipMutationLease, inspectOwnershipMutationLease, ownershipMutationLeasePath } from "../service/ownership-mutation-lease.mjs"; +import { serviceStateFilesFor } from "../service/install-state-contract.mjs"; +import { homedir } from "node:os"; +import { assertNotRealHomeUnderTest, isTestHomeGuardArmed } from "./test-home-guard.mjs"; + + +function paths(home) { return [join(home, "sync-update")]; } +function ensureHome(home) { + try { lstatSync(home); return; } catch (error) { if (error?.code !== "ENOENT") throw error; } + const parent = dirname(home); + if (parent === home) throw new Error("missing home authority"); + ensureHome(parent); + try { mkdirSync(home, { mode: 0o700 }); } + catch (error) { if (error?.code !== "EEXIST") throw error; } + const stat = lstatSync(home); + if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("home creation was replaced"); +} +function missingHome(home) { + let current = home; + for (;;) { + try { lstatSync(current); realpathSync.native(current); return current !== home; } + catch (error) { + if (error?.code !== "ENOENT") throw error; + // A dangling symlink is not evidence that the home is absent. + try { lstatSync(current); throw new Error("unresolved home authority"); } + catch (again) { if (again?.code !== "ENOENT") throw again; } + const parent = dirname(current); + if (parent === current) throw new Error("missing home authority"); + current = parent; + } + } +} +function mutexPath(home) { + const canonicalHome = realpathSync.native(home); + try { lstatSync(join(canonicalHome, "sync-update")); throw new Error("mutex authority path is occupied"); } + catch (error) { if (error?.code !== "ENOENT") throw error; } + return join(canonicalHome, "sync-update.mutation.lock"); +} +function holderKind(holder) { + return holder?.alive === true && (holder.holderKind === "sync" || holder.holderKind === "update") + ? holder.holderKind : "unknown"; +} + +/** Non-blocking and never joins the separate service-ownership lease. */ +export function tryAcquireUpdateSyncMutex(home, kind, deps = {}) { + assertNotRealHomeUnderTest(home); + try { + ensureHome(home); + const lease = acquireOwnershipMutationLease(paths(home), { ...deps, waitMs: 0, isolated: true, holderKind: kind, processImage: () => null, lockPath: mutexPath(home) }); + return { kind: "acquired", addDelegate: pid => lease.addDelegate(pid), release: () => lease.release() }; + } catch (error) { + if (error && typeof error === "object" && "holder" in error) { + return { kind: "busy", holder: holderKind(error.holder) }; + } + return { kind: "busy", holder: "unknown" }; + } +} + +/** Read only: absence is accepted only after an explicit filesystem absence check. */ +export function inspectUpdateSyncMutex(home) { + assertNotRealHomeUnderTest(home); + try { + if (missingHome(home)) return "free"; + const lock = mutexPath(home); + try { lstatSync(lock); } catch (error) { + return error?.code === "ENOENT" ? "free" : "unknown"; + } + return holderKind(inspectOwnershipMutationLease(paths(home), { processImage: () => null, lockPath: lock })); + } catch { return "unknown"; } +} + +/** A delegated child may reuse only its live parent's sync lease. */ +export function parentHoldsSyncMutex(home, claimedPid = process.env.OCX_SYNC_MUTEX_HELD_BY) { + if (!claimedPid) return false; + try { + const holder = inspectOwnershipMutationLease(paths(home), { processImage: () => null, lockPath: mutexPath(home) }); + return holder?.alive === true && holder.record === "complete" && holder.holderKind === "sync" && String(holder.pid) === claimedPid && holder.delegatePid === process.pid; + } catch { return false; } +} + +/** Shared wire format for launcher and Bun sync admission refusals. */ +export function refuseSync(reason, args) { + const exit = reason === "sync-in-progress" ? 1 : 7; + console.error(reason); + if (args.includes("--json")) console.log(JSON.stringify({ schema: "ocx.sync.fanout/1", home: { state: "skipped", exit }, fanout: { state: "not-applicable", reason }, children: [] })); + return exit; +} + +export function acquireSyncGuard(home, args) { + const lease = tryAcquireUpdateSyncMutex(home, "sync"); + if (lease.kind !== "acquired") return { kind: "refused", exit: refuseSync(lease.holder === "sync" ? "sync-in-progress" : "update-in-flight", args) }; + if (inspectUpdateMarker(home) !== "free") { + lease.release(); + return { kind: "refused", exit: refuseSync("update-in-flight", args) }; + } + return lease; +} + +function inspectOwnershipLease(home) { + try { + const statePaths = serviceStateFilesFor(home, isTestHomeGuardArmed() ? home : join(homedir(), ".opencodex")); + const path = ownershipMutationLeasePath(statePaths); + try { lstatSync(path); } catch (error) { + return error?.code === "ENOENT" ? "free" : "unknown"; + } + const holder = inspectOwnershipMutationLease(statePaths, { processImage: () => null }); + return holder?.alive === true ? "active" : holder?.alive === false ? "free" : "unknown"; + } catch { return "unknown"; } +} + +export function inspectUpdateMarker(home, { now = Date.now } = {}) { + const path = join(home, "update-orchestrated.json"); + let found = false; + let fd; + try { + const before = lstatSync(path); + found = true; + if (!before.isFile() || before.size > 4096) return "unknown"; + fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)); + const opened = fstatSync(fd); + if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino || opened.size !== before.size) return "unknown"; + const buffer = Buffer.alloc(4097); + const count = readSync(fd, buffer, 0, buffer.length, 0); + if (count > 4096 || count !== opened.size) return "unknown"; + const raw = buffer.subarray(0, count).toString("utf8"); + const after = lstatSync(path); + if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeMs !== after.mtimeMs) return "unknown"; + const value = JSON.parse(raw); + if (!value || typeof value !== "object") return "unknown"; + const marker = value; + if (!Number.isSafeInteger(marker.pid) || Number(marker.pid) <= 0 || typeof marker.phase !== "string" + || !Number.isSafeInteger(marker.startedAt) || Number(marker.startedAt) <= 0) return "unknown"; + const terminal = ["installed", "failed", "refused"].includes(marker.phase); + if (!terminal && !["preflight", "mutating", "overrun"].includes(marker.phase)) return "unknown"; + if (marker.terminationUnconfirmed !== undefined && marker.terminationUnconfirmed !== true) return "unknown"; + if (marker.fenceUntil !== undefined && (!Number.isSafeInteger(marker.fenceUntil) || marker.fenceUntil < marker.startedAt)) return "unknown"; + if (marker.fenceUntil !== undefined && now() < marker.fenceUntil) return "active"; + const ids = []; + if (!terminal) ids.push(marker.pid); + for (const key of ["installerPid", "installerPgid"]) { + if (marker[key] === undefined) continue; + if (!Number.isSafeInteger(marker[key]) || marker[key] <= 0 || (key === "installerPgid" && process.platform === "win32")) return "unknown"; + ids.push(key === "installerPgid" ? -marker[key] : marker[key]); + } + let unknown = false; + for (const id of ids) { + try { process.kill(id, 0); return "active"; } + catch (error) { if (error?.code !== "ESRCH") unknown = true; } + } + return unknown || (marker.terminationUnconfirmed && marker.installerPgid === undefined) ? "unknown" : "free"; + } catch (error) { return !found && error?.code === "ENOENT" ? "free" : "unknown"; } + finally { if (fd !== undefined) closeSync(fd); } +} + +/** False requires positive absence of an update across all three read-only observations. */ +export function isUpdateInFlight(home, deps = { mutex: inspectUpdateSyncMutex, ownershipLease: inspectOwnershipLease, marker: inspectUpdateMarker }) { + try { + const mutex = deps.mutex(home); + if (mutex !== "free" && mutex !== "sync") return true; + return deps.ownershipLease(home) !== "free" || deps.marker(home) !== "free"; + } catch { return true; } +} diff --git a/src/update/sync-update-mutex.ts b/src/update/sync-update-mutex.ts new file mode 100644 index 00000000000..fd81d8f2e01 --- /dev/null +++ b/src/update/sync-update-mutex.ts @@ -0,0 +1 @@ +export * from "./sync-update-mutex.mjs"; diff --git a/src/update/test-home-guard.mjs b/src/update/test-home-guard.mjs new file mode 100644 index 00000000000..d792523bd0b --- /dev/null +++ b/src/update/test-home-guard.mjs @@ -0,0 +1,33 @@ +// Match the test home guard in ../lib/test-home-guard.ts for the Node launcher. +import { homedir } from "node:os"; +import { basename, dirname, join, resolve } from "node:path"; +import { realpathSync } from "node:fs"; + +function canonicalize(path) { + let current = resolve(path); + const remaining = []; + for (;;) { + try { return join(realpathSync.native(current), ...remaining.reverse()); } + catch { + const parent = dirname(current); + if (parent === current) return resolve(path); + remaining.push(current.slice(parent.length + 1)); current = parent; + } + } +} +const protectedHome = canonicalize(join(process.env.OCX_REAL_HOME?.trim() || homedir(), ".opencodex")); +export function isTestHomeGuardArmed() { + if (process.env.OCX_TEST_HOME_GUARD === "1") return true; + if (process.env.OCX_TEST_HOME_GUARD === "0") return false; + const entry = globalThis.Bun?.main ?? process.argv[1]; + return typeof entry === "string" && /[._](?:test|spec)\.[cm]?[jt]sx?$/i.test(basename(entry)); +} +if (process.env.OCX_TEST_HOME_GUARD !== "0" && process.env.OCX_TEST_HOME_GUARD !== "1" && isTestHomeGuardArmed()) { + process.env.OCX_TEST_HOME_GUARD = "1"; +} +export function assertNotRealHomeUnderTest(home) { + if (!isTestHomeGuardArmed()) return; + const path = canonicalize(home); + const normalize = value => process.platform === "win32" || process.platform === "darwin" ? value.toLowerCase() : value; + if (normalize(path) === normalize(protectedHome)) throw new Error("refusing to write the real OpenCodex home from a test process"); +} diff --git a/src/update/transactional-install.mjs b/src/update/transactional-install.mjs index 62c4cad8e30..c95605bb527 100644 --- a/src/update/transactional-install.mjs +++ b/src/update/transactional-install.mjs @@ -449,7 +449,7 @@ function* npmUpdateTransaction({ const detail = install.error ? [install.error.code, install.error.message].filter(Boolean).join(": ") : install.signal ?? install.status ?? "?"; - return { ok: false, phase: "stage", error: "npm staging install failed (" + detail + ")" }; + return { ok: false, phase: "stage", ...(install.processTreeExited === false ? { processTreeExited: false } : {}), error: "npm staging install failed (" + detail + ")" }; } const stagedPackage = stagedCandidatesIn(stageRoot).find(dir => existsSync(join(dir, "package.json"))); if (!stagedPackage) { @@ -556,7 +556,7 @@ export async function transactionalNpmUpdateAsync(options) { let install; try { install = await options.runNpm(step.value); } catch (error) { install = { status: null, error, processTreeExited: false }; } - if (install.processTreeExited !== true) install = { ...install, status: null, processTreeExited: false, + if (install.processTreeExited !== true && !(install.groupExited === true && typeof install.status === "number")) install = { ...install, status: null, processTreeExited: false, error: install.error ?? { code: "EINSTALLJOIN", message: "npm process-tree exit was not confirmed" } }; return transaction.next(install).value; } diff --git a/structure/cli-management.md b/structure/cli-management.md index 1553e7a5805..f291df75e71 100644 --- a/structure/cli-management.md +++ b/structure/cli-management.md @@ -157,6 +157,10 @@ The operating guide's eight-domain workflow table is navigation rather than pari ## ocx command selection +`capabilities --contracts` and `update` remain on the invoked package path even when a Desktop command record is present. +All `capabilities` calls, sync calls and update calls carrying orchestration flags skip root automatic Codex shim repair, including malformed calls. Sync holds a separate home-scoped sync/update mutex for its work and performs eligible shim repair only after acquiring it. +The CLI discovery registry exposes the orchestrated plan/apply grammar and exit codes, and `capabilities --contracts` reports the versioned update contract. Sync reports `update-in-flight` and exits 7 when an update holds its mutex, the mutex is unavailable, or an update marker is active; a sync holder produces `sync-in-progress` and exit 1. A guarded `--json` refusal prints one fan-out document with a skipped Home, the refusal reason, and no Children. A missing home is observed as free and is created with private permissions when sync acquires its guard; an unresolved home symlink remains uncertain. + `src/cli/cli-path-diagnostics.ts` reads the settled Desktop record through `src/lib/desktop-cli-record.mjs` and observes regular executable candidates on this process's PATH without executing them. `pathFirst` follows PATH/PATHEXT order, including cwd-relative and empty entries; Windows's possible cmd current-directory candidate is separate. The expected command is the owned POSIX shim or the recorded Windows bundled executable. Windows package-launcher handoff is disabled before any record read or target check; user `Path` order selects the Desktop executable, while diagnostics still read the record and report PATH order. A stale package candidate first on PATH is reported even if its current launcher would hand off. `src/cli/status.ts` exposes additive `cliCommand` JSON and a human-view line; `src/cli/doctor.ts` prints the separate “ocx command selection” checks. Neither observation supplies runtime ownership or service control authority. Parent-shell aliases, functions and caches remain unobserved. Before JSON interpretation, the POSIX reader requires a real private directory and regular non-symlink record owned by the effective uid, no group/other bits, and matching descriptor dev/ino/uid/mode after nonblocking no-follow open; macOS also refuses extended ACL entries or a failed one-second ACL check. Safety failures report `record-unsafe`. Invalid, unsafe or enabled-pending records and unusable Desktop targets are FAIL; disabled records with `cleanupPending` report `cleanup-pending` as WARN, as do PATH ordering and incomplete scans. Internal version observations in `src/service/managing-cli.ts` (`probeVersionOnce`) set `OCX_NO_DESKTOP_HANDOFF=1` in the spawned child's environment so the selected package executable reports its own version. This flag suppresses the package launcher's Desktop handoff only; it does not bypass service ownership or update guards. Normal user `ocx --version` remains eligible for handoff. diff --git a/structure/codex-cli-update.md b/structure/codex-cli-update.md index 310df791db4..e40caef437d 100644 --- a/structure/codex-cli-update.md +++ b/structure/codex-cli-update.md @@ -17,6 +17,10 @@ npm resolver. The resolver replaces all ambient aliases with the captured entrie project dotenv cannot supply missing settings or change the captured precedence. An older snapshot without a transport map conveys no transport settings, with no ambient fallback. Snapshot values are internal inputs, never report or diagnostic fields. +For orchestrated OpenCodex updates the launcher intercepts plan/apply before desktop +handoff and boot restoration, resolves Bun without installation, and delegates npm/pnpm +apply to the Node driver. The [update transaction contract](ops/service-and-sidecars.md#bun-updater-ownership-transaction) owns admission and verification. +For `sync`, the launcher acquires the home sync/update mutex before Desktop handoff or Bun launch and holds it until that child exits. A current Bun child reuses the lease only when its recorded live sync holder is its parent and the launcher pid matches the inherited claim; old Desktop CLIs remain protected by the launcher lease. Registry integrity requires a canonical base64 SHA-512 digest of exactly 64 bytes; malformed or truncated tokens refuse the target. Plan identity also binds a bounded content observation (installContentDigest): a versioned file set fixed by the supported npm-global layout — the package manifest, its declared bin/codex.js diff --git a/structure/config.md b/structure/config.md index 5e33e304171..a0ee01fe7dd 100644 --- a/structure/config.md +++ b/structure/config.md @@ -64,7 +64,7 @@ silently move the active installation. Config reads in this leaf and `src/config `withConfigDirHardeningSettled` in `src/config/paths.ts` admits synchronous mutation after the last unrelated await. Its registry includes the optional config flight, ancestors and retained timeout children; one existing ACL deadline bounds admission, including newly overlapping work. Expiry throws sanitized `WindowsSecretAclSettleTimeoutError` (`ETIMEDOUT`) without running the writer or dropping child cleanup ownership. The final empty-registry check and callback share one turn, with no await in the callback. Intercept/picker CA, token, cleanup, profile and snapshot phases re-enter after trust/discovery awaits. Config saves in `src/server/management/agent-settings-routes.ts` and `src/server/management/config-routes.ts`, Desktop intent/mode commits in `src/server/management/native-integration-routes.ts`, and gateway publication/cleanup in those routes and `src/cli/ensure-desired-integrations.ts` use the same admission. `src/cli/claude-desktop.ts` admits local profile/mode commits and the complete remote-store transaction again after hub download. Lifecycle/config locks are acquired inside admission; refresh re-read, mode/freshness checks, profile and marker publication share one callback. Live setting edits and their save/publication share the admitted synchronous callback; a refused admission leaves both live and durable state untouched. Ordered post-commit phases preserve applied-state warnings or settled compensation, including mode/fingerprint marker refusal and retained CLI intent after incomplete rollback. Synchronous leaf APIs retain their contracts. `tests/claude-integration/claude-config-root-writer-barrier.test.ts` holds parent flights and drives refusal deadlines without sleeps. Lexical/canonical aliases and uncertain identities drain conservatively; removal keeps its separate at-or-below scope and actual-exit requirement. Async local config commands (`src/cli/config-command.ts`, `src/cli/effort.ts`, `src/cli/models.ts`, `src/cli/provider.ts`) admit complete synchronous read/validate/save phases through `withConfigDirHardeningSettled`. Preliminary model selection and client-connection diagnostics use passive observations that cannot publish recovery copies. Final authority and recovery publication are re-read inside admission without starting optional hardening. `src/cli/config-mutation.ts` refuses invalid or unreadable authority, including array/non-object roots rejected before defaults repair, with `CliUsageError`; full-config commands retain fresh-install initialization when the file is absent, while set/unset retain the persisted mutation owner's missing-file refusal. Custom-model removal revalidates the confirmed row by identity and contents while retaining current siblings. Import reads its input and checks its target inside admission. Provider-add credential cleanup shares the synchronous post-save phase and retains its existing post-commit warning. Timeout leaves the mutation database and config untouched and follows existing CLI failure handling. `tests/windows/windows-config-root-async-writers.test.ts` covers held parent flights, deadline refusal, recovery copies, invalid authority and concurrent edits. Codex multi-agent management changes that can resolve a runtime additionally await fresh [selection admission](codex-cli-update.md#worker-realm-and-the-selection-commit-window) before entering this barrier, keep that owner across hardening, and re-evaluate the mode plan inside the synchronous callback; neither ACL wait is inserted into the callback, and refusal leaves the combined mutation untouched. Timer-driven caches under the config root admit their write the same way and build the snapshot inside the callback: the provider account quota cache (`src/providers/account-quota-disk.ts`), the Codex account quota cache (`src/codex/quota.ts`) and the reasoning support cache, while a models.dev refresh admits its publication after the network read (`src/providers/reasoning-metadata.ts`). A timed-out admission skips a best-effort cache write and fails that refresh unpublished, a joined refresh reports the same failure, and a cancel, clear or reset invalidates a write still waiting for admission (#7815; `tests/providers/provider-account-quota-persistence.test.ts`, `tests/codex-integration/reasoning-metadata.test.ts`). -`src/config/process-state.ts` derives `ocx.pid` and `runtime-port.json` from that resolved directory. +`src/config/process-state.ts` derives `ocx.pid` and `runtime-port.json` from that resolved directory. Ordinary and connected-client runtimes publish their absolute relaunch command in the runtime record; older records can omit it. It owns their byte-compatible writes, parsing, expected-PID filters, cheap liveness, full OCX command identity, and snapshot-guarded removal. `RuntimePortState.attestationSecret` and `siblingOfPort` (the live owner's port, written only by a sibling instance) remain optional, owner-only state and are validated before a record is returned. `src/config.ts` re-exports the same diff --git a/structure/ops/desktop-supervision.md b/structure/ops/desktop-supervision.md index 1dbc951c14d..1f4c2d9f216 100644 --- a/structure/ops/desktop-supervision.md +++ b/structure/ops/desktop-supervision.md @@ -109,6 +109,8 @@ plain `unknown` or `unsupported` cannot clear a prior block. Without a prior blo unknown and unsupported preserve the existing durable-owner and liveness decisions. Service install, repair, start and restart refuse before mutation, including registration staging. Update gates re-read supervision before stop, package replacement, restoration and recovery; +Orchestrated plans classify a Desktop-owned installation as `desktop-app-owned` and +refuse apply; the package launcher handles orchestrated requests before Desktop handoff. they refuse even for a separate npm/Bun install. Use the app updater for its bundle, or quit Desktop before updating the CLI install. Service stop and uninstall remain available. `src/service/desktop-command-guard.ts` carries that refusal for `src/service/cli.ts`, diff --git a/structure/ops/service-and-sidecars.md b/structure/ops/service-and-sidecars.md index fc84ee93356..5d2902c9043 100644 --- a/structure/ops/service-and-sidecars.md +++ b/structure/ops/service-and-sidecars.md @@ -413,11 +413,11 @@ directory is located by `src/server/gui-static.ts`; ## Bun updater ownership transaction -`src/update/ownership-transaction.ts` holds one mutation lease across the Bun updater's awaited +For orchestrated Bun installs, `src/update/orchestrated-entry.ts` starts an exact-version child and classifies its recorded outcome against passive tree and live runtime verification. For npm/pnpm, `src/update/orchestrated-node-driver.mjs` obtains a bounded Bun plan, shares admission decisions with the Bun driver, starts the same launcher with the pinned version, and independently verifies the installed or previous tree and any restarted runtime. The npm/pnpm Node child uses `src/update/orchestrated-identity-probe-entry.ts` to recheck the attested identity and plan token before mutation, and records the installer outcome after recovery. Orchestrated and legacy update workers hold the sync/update mutex from preflight through recovery and the final marker; a parent watchdog reports an orchestrated overrun without killing the child. The ordinary ownership lease may still be released for service-manager recovery. `src/update/orchestrated-arguments.mjs` parses the orchestrated update grammar for Node and Bun; `src/update/orchestrated-outcome.mjs` classifies verified child outcomes without treating an uncertain child as settled; `src/update/orchestrated-tree.mjs` checks the active npm/Bun package tree without touching retained backups; `src/update/orchestrated-plan.ts` constructs a fail-closed plan from observed install, owner, runtime and version facts. `src/update/orchestrated-token.mjs` hashes an explicitly selected, canonical install and runtime identity; runtime attestation secrets are excluded from the digest input. `src/update/orchestrated-identity.ts` and `src/update/orchestrated-live-identity.ts` require an attestation proof and an unchanged runtime record before returning a serving identity; older records can only prove an executable mismatch or remain unknown. `src/update/sync-update-mutex.mjs` uses a separate, non-reentrant home-scoped lease that records whether sync or update holds it. The Node sync launcher publishes its child PID as delegate; reclamation waits for both PIDs to die, and a new Bun child waits at most two seconds to verify its own PID before mutation. An older Desktop child cannot verify the publication: if the launcher is killed between spawning it and publishing its PID, that child can outlive the stale lease. `src/update/orchestrated-session.mjs` publishes preflight and mutation outcomes, holds that lease through final outcome and marker publication, and fences mutation on deadline and identity checks. `src/update/ownership-transaction.ts` holds one mutation lease across the Bun updater's awaited stop, package replacement and recovery work. The parent never puts its token in the global environment. Fixed stop/service/direct-recovery children can join it; package-manager and ancillary children receive environments without the capability. Refusals return through the -lease boundary before exiting, and thrown failures release it after owner-aware recovery. +lease boundary before exiting, and thrown failures release it after owner-aware recovery. Before installer launch the mutation marker carries a 15-minute fence from worker start; a dead worker, timed-out or killed installer, or unconfirmed exit retains that fence, while live or uninspectable recorded installers remain fenced independently. For POSIX npm, pnpm and Bun installs, `src/update/posix-install-supervisor.mjs` starts a gated process-group leader, publishes its PID and group ID before allowing the installer to run, and terminates the group on the 180-second deadline. On normal installer exit and confirmed group disappearance, finalization clears the fence. Process groups cannot contain detached descendants: an escaped descendant can outlive a normally exiting installer and continue after the fence clears, an accepted residual; it can also outlive a timeout fence. Windows uses the Job Object supervisor in `src/update/npm-install.mjs` and clears the fence only after normal exit and an empty job; an unconfirmed termination without a group ID keeps the marker uncertain. Replacement and recovery inspect both the captured endpoint and the freshly read runtime record. Malformed or unreadable records remain unknown. Recovery requires the same complete owner identity and proven-dead liveness; unknown or transferred ownership never starts another proxy. @@ -591,7 +591,7 @@ detached replacement's environment drops the marker. Coverage: src/update/refresh-scheduler.ts owns the package cache timer and per-channel singleflight for the running proxy. Eligible npm, pnpm and Bun installs refresh missing or 20-hour-stale `version.json` after bind, check staleness hourly and retry failures with bounded backoff. Each server start owns one scheduler reference; the last matching stop disarms the timer. A stopped automatic lookup cannot write a late result, but an explicit check joining that lookup marks explicit interest and writes its successful result even if the last listener stops before it resolves. Source/mise/standalone installs and `OCX_DISABLE_UPDATE_CHECK=1` do not start automatic lookup; explicit requests remain available. -src/update/async-check.ts uses the existing owner-bound registry target with a bounded asynchronous child; pnpm owner discovery runs in src/update/pnpm-owner-worker.ts off the request loop. Read-only pnpm owner and registry probes — in the scheduler, the synchronous updater, and the `bin/ocx.mjs` package-manager self-update — run from the installed update module directory via `src/update/pnpm-read-policy.mjs` with project pnpmfiles disabled, never from the caller's workspace. pnpm mutations (`add -g`, rollback) instead run in unique private temporary workspaces outside the package, with an explicit empty workspace boundary to stop parent-project discovery. Both npm_config_ and pnpm_config_ ignore-pnpmfile controls are set case-insensitively for pnpm 10/11. Cleanup removes only known files and an empty unchanged directory; unexpected contents remain for inspection. On Windows, this also avoids pinning the replaced package as cwd. `src/update/notify.ts` writes successful results atomically and preserves a dismissal only for the same channel and version. The interactive pre-bind prompt reads the cache and does not launch a second detached refresh. `src/update/badge.ts` only reads the cache and reports unknown at 40 hours. +src/update/async-check.ts uses the existing owner-bound registry target with a bounded asynchronous child; pnpm owner discovery runs in src/update/pnpm-owner-worker.ts off the request loop. Read-only pnpm owner and registry probes — in the scheduler, the synchronous updater, and the `bin/ocx.mjs` package-manager self-update — run from the installed update module directory via `src/update/pnpm-read-policy.mjs` with project pnpmfiles disabled, never from the caller's workspace. pnpm mutations (`add -g`, rollback) instead run in unique private temporary workspaces outside the package, with an explicit empty workspace boundary to stop parent-project discovery. Both updater lanes supervise these mutations with a POSIX process group or Windows Job Object; unconfirmed termination retains the fence and prevents readback or another mutation. Both npm_config_ and pnpm_config_ ignore-pnpmfile controls are set case-insensitively for pnpm 10/11. Cleanup removes only known files and an empty unchanged directory; unexpected contents remain for inspection. On Windows, this also avoids pinning the replaced package as cwd. `src/update/notify.ts` writes successful results atomically and preserves a dismissal only for the same channel and version. The interactive pre-bind prompt reads the cache and does not launch a second detached refresh. `src/update/badge.ts` only reads the cache and reports unknown at 40 hours. The pnpm update result retains its legacy `rolledBack` signal for a verified previous version, including an unchanged active tree. Its `rollbackPerformed` field is true only when a rollback transaction succeeds and the restored tree and shims verify; orchestration must use that distinction when reporting an actual rollback. `src/update/orchestrated-pnpm.mjs` provides read-only post-update evidence: it re-resolves the selected pnpm owner, requires the original global group and bin directory, and verifies the active package version, source, dependencies and generated shims. It is a verification building block; it does not itself initiate an update. The orchestrated outcome classifier treats malformed phase records and unconfirmed installer termination as uncertain (exit 12), and requires an absolute active root on an installed record before it can report success. `src/update/orchestrated-child.mjs` forwards catchable signals and waits at most 60 seconds for child close after interruption; a timeout is unconfirmed, not evidence of termination. Its optional parent watchdog reports overrun without signalling the child; the caller must detach its handles and preserve in-flight evidence. The desktop badge snapshot in src/update/desktop-badge.ts is process-local display state keyed by a Tauri session id. A 60-second shell heartbeat renews receipt time; entries expire after 180 seconds and the store retains at most 32 sessions. It is separate from the package version cache and from the updater job/ownership transaction. A proxy restart reports unknown until a bound desktop shell republishes; no update installation can be authorized by this snapshot. diff --git a/structure/remote-link.md b/structure/remote-link.md index 2300d5f1c78..511f913af6a 100644 --- a/structure/remote-link.md +++ b/structure/remote-link.md @@ -174,6 +174,6 @@ Coverage: `tests/server/link-management-relay.test.ts` (the real hub-link listen `ocx status --json` reports `appliedCodexSettingsDigest` on every device (a Child's record, or a Home's own projection, which is what it serves), and on a Child `lastApplyAt` and `runtimeStartedAt` as epoch ms (`src/cli/status-codex-settings.ts`). The client runtime's `/healthz` reports `startedAt`. After `ocx sync` records an apply, `src/cli/link-apply-restart.ts` restarts the client runtime through `handleProxyRestart`, the `ocx restart` path, only when the live client runtime started before `appliedAt` or reports no start; its start callback starts nothing unless an accepted restart left no runtime, which takes the ordinary recovery start. -The client listener serves that bound restart (`src/client/machine-listener.ts`, `src/client/runtime-restart.ts`). `/healthz` answers the attestation challenge with the secret the runtime publishes in `runtime-port.json` and advertises `restartCapability: "v1"`; `POST /api/system/restart` admits only the HMAC capability bound to this pid and port, never a dashboard session, admin token or link key. Under the desktop app or a viable service it answers `409 restart_supervised` naming the supervisor and keeps serving, because handing off to a supervisor means exiting before the replacement is proven; the CLI reports "not performed, runtime kept". Otherwise one budget (`CLIENT_RESTART_BUDGET_MS`, 90 s from acceptance) covers a 20 s listener drain, a replacement `ocx start` that must answer by 70 s (`spawnReplacementStart` with `notReady: "terminate"`, which stops an unready replacement and returns only after its exit is observed), and a rollback that binds the port again with a 10 s wait, builds a fresh tunnel supervisor (a stopped one cannot restart) and republishes the same attestation secret and start time. Before binding, and again under the client lifecycle lock right before it publishes, it checks that the durable connection is still the one it served; a disconnect, a new connection or a held lock closes the new listener unpublished and hands off to the standalone recycle, which starts what the current state calls for. `requestBoundSystemRestart` sends the request to a client target only while `CLIENT_RESTART_REQUEST_MIN_REMAINING_MS` remains, so a rollback always ends before the CLI's replacement observation and its recovery start. Coverage: `tests/clients/client-runtime-restart.test.ts`, `tests/server/restart-replacement-not-ready.test.ts`, `tests/cli/link-apply-restart.test.ts`. +The client listener serves that bound restart (`src/client/machine-listener.ts`, `src/client/runtime-restart.ts`). `/healthz` answers the attestation challenge with the secret the runtime publishes in `runtime-port.json` and advertises `restartCapability: "v1"`; `POST /api/system/restart` admits only the HMAC capability bound to this pid and port, never a dashboard session, admin token or link key. If the relaunch command cannot be identified, `src/client/runtime.ts` omits it from the runtime record; update admission treats the identity as unproven, while client startup and shutdown continue. Under the desktop app or a viable service it answers `409 restart_supervised` naming the supervisor and keeps serving, because handing off to a supervisor means exiting before the replacement is proven; the CLI reports "not performed, runtime kept". Otherwise one budget (`CLIENT_RESTART_BUDGET_MS`, 90 s from acceptance) covers a 20 s listener drain, a replacement `ocx start` that must answer by 70 s (`spawnReplacementStart` with `notReady: "terminate"`, which stops an unready replacement and returns only after its exit is observed), and a rollback that binds the port again with a 10 s wait, builds a fresh tunnel supervisor (a stopped one cannot restart) and republishes the same attestation secret and start time. Before binding, and again under the client lifecycle lock right before it publishes, it checks that the durable connection is still the one it served; a disconnect, a new connection or a held lock closes the new listener unpublished and hands off to the standalone recycle, which starts what the current state calls for. `requestBoundSystemRestart` sends the request to a client target only while `CLIENT_RESTART_REQUEST_MIN_REMAINING_MS` remains, so a rollback always ends before the CLI's replacement observation and its recovery start. Coverage: `tests/clients/client-runtime-restart.test.ts`, `tests/server/restart-replacement-not-ready.test.ts`, `tests/cli/link-apply-restart.test.ts`. The Home learns a Child's apply from the Child (`src/link/child-parity.ts`, `src/client/link-parity-reporter.ts`). The linked client runtime POSTs `{linkId, lastApplyAt, runtimeStartedAt, appliedCodexSettingsDigest, sequence}` to `/v1/link-management/child-parity` through the connection-bound relay, shortly after start with backoff and then once a minute; a 404 stops it. On the Home the hub-link listener admits exactly that POST beside the read table, and `src/server/index/link-management.ts` handles it before the passive-read dispatch: the admitting key must own the named link, the body is capped at 1 KiB and 5 s, the parse is strict, and the only effect is an in-memory entry pruned to current links. Entries are ordered by `runtimeStartedAt`, then by `sequence` (process-wide, so a rollback keeps counting), and an older report is ignored, so a late POST from a replaced runtime or an earlier send never moves the row backward. `GET /api/link/status` and `ocx link status --json` carry `lastApplyAt`, `runtimeStartedAt`, `appliedCodexSettingsDigest` and `reportedAt` (epoch ms) on every link row, null without a report; the CLI accepts their absence from an older runtime. Coverage: `tests/server/link-child-parity.test.ts`, `tests/clients/link-parity-reporter.test.ts`. diff --git a/structure/runtime.md b/structure/runtime.md index b61361243b3..9220a9659b0 100644 --- a/structure/runtime.md +++ b/structure/runtime.md @@ -104,7 +104,7 @@ does not perform OAuth, and runtime credential resolution rereads the owned sour | Path | Responsibility | | --- | --- | -| `bin/ocx.mjs` | Published npm `bin` entry (Node shim). An inherited explicit `BUN_RUNTIME_TRANSPILER_CACHE_PATH` is scoped to a `bun-` leaf beneath the configured directory — appended on a version change, kept unchanged when the path already ends in that leaf — for the bundled or PATH runtime it starts (`src/lib/bun-transpiler-cache-scope.mjs`), because another Bun version sharing the directory evicts its entries. Before project dotenv: explicit Bun override, bundle, permitted installer recovery, then `src/lib/bun-path-runtime.mjs` validates absolute PATH Bun candidates with canonical regular/executable and size checks, POSIX validation of every original and symlink-expanded ancestor (root or effective-user ownership; group/world write permission is refused in every ancestor, including shared sticky directories), plus non-writable resolved files and final parent directories and a canonical realpath recheck that permits case-variant spelling, and bounded version-policy and identity checks (`--version` must match `-e`'s `Bun.version`; stable version has the dependency pin's major and is at least the pinned version); PATH selection stamps `process` with its canonical path and prints a version-only stderr notice. Failure names an executable macOS Desktop CLI when present without delegating. The proof-bound Anthropic snapshot, signal/exit propagation and zero-install updater inspection stay intact. `src/cli/version-skew-notice.ts`, called from `src/cli/root.ts`, makes one identity-checked 200 ms advisory probe for start/stop/restart/update/service, excluding JSON/help/internal; Node-managed update bypasses this notice. Before package repair or Bun resolution, `src/lib/desktop-cli-record.mjs` validates the bounded settled Desktop command record before JSON (POSIX private ownership/modes, no symlinks, matching no-follow nonblocking descriptor and macOS ACL checks; failures are `record-unsafe`) and `src/lib/desktop-cli-handoff.mjs` delegates eligible POSIX commands to its validated target with a regenerated argv proof, inherited IO and mirrored exit/signal. Windows always retains the package path and selects Desktop through user `Path` order. Update, removal, internal inspection and `OCX_NO_DESKTOP_HANDOFF=1` retain the package path; only target ENOENT confirmed by a post-spawn `lstat` resumes it after selection. Command selection is separate from runtime/service authority; see [command selection](cli-management.md#ocx-command-selection). | +| `bin/ocx.mjs` | Published npm `bin` entry (Node shim). An inherited explicit `BUN_RUNTIME_TRANSPILER_CACHE_PATH` is scoped to a `bun-` leaf beneath the configured directory — appended on a version change, kept unchanged when the path already ends in that leaf — for the bundled or PATH runtime it starts (`src/lib/bun-transpiler-cache-scope.mjs`), because another Bun version sharing the directory evicts its entries. Before project dotenv: explicit Bun override, bundle, permitted installer recovery, then `src/lib/bun-path-runtime.mjs` validates absolute PATH Bun candidates with canonical regular/executable and size checks, POSIX validation of every original and symlink-expanded ancestor (root or effective-user ownership; group/world write permission is refused in every ancestor, including shared sticky directories), plus non-writable resolved files and final parent directories and a canonical realpath recheck that permits case-variant spelling, and bounded version-policy and identity checks (`--version` must match `-e`'s `Bun.version`; stable version has the dependency pin's major and is at least the pinned version); PATH selection stamps `process` with its canonical path and prints a version-only stderr notice. Failure names an executable macOS Desktop CLI when present without delegating. The proof-bound Anthropic snapshot, signal/exit propagation and zero-install updater inspection stay intact. `src/cli/version-skew-notice.ts`, called from `src/cli/root.ts`, makes one identity-checked 200 ms advisory probe for start/stop/restart/update/service, excluding JSON/help/internal; Node-managed update bypasses this notice. Before package repair or Bun resolution, `src/lib/desktop-cli-record.mjs` validates the bounded settled Desktop command record before JSON (POSIX private ownership/modes, no symlinks, matching no-follow nonblocking descriptor and macOS ACL checks; failures are `record-unsafe`) and `src/lib/desktop-cli-handoff.mjs` delegates eligible POSIX commands to its validated target with a regenerated argv proof, inherited IO and mirrored exit/signal. Windows always retains the package path and selects Desktop through user `Path` order. Update, removal, `capabilities --contracts`, internal inspection and `OCX_NO_DESKTOP_HANDOFF=1` retain the package path; only target ENOENT confirmed by a post-spawn `lstat` resumes it after selection. Command selection is separate from runtime/service authority; see [command selection](cli-management.md#ocx-command-selection). | | `src/lib/bun-runtime.ts` | Bundled-Bun resolution: `isRealBunBinary()` (size gate vs the ~450-byte placeholder stub), `bundledBunPath()`, and `durableBunPath()` (path baked into service/shim artifacts). Durable selection accepts only the source/path pair already stamped for the running executable; it never re-reads a project-dotenv `OPENCODEX_BUN_PATH`. | | `src/lib/plain-data.ts` | Detached copies for a consumer that must not observe later edits. Descriptor-based reads, including array elements, so an accessor is refused rather than invoked; refuses cycles, functions, class instances and anything else JSON could not have produced, and returns a copy-or-refusal union rather than degrading silently. Symbol-keyed process bookkeeping is skipped. Each copied object property, including one named `__proto__`, is defined as an own data property on the detached copy; object properties whose value is `undefined` are omitted, and arrays copy only their indexed elements. | | `src/cli/index.ts` | `ocx` / `opencodex` CLI. Lifecycle: init, start, stop, restart, status, sync, restore/eject, gui, service, update. Stop preserves connected hub/Link client integrations; disconnect owns their teardown, and start serves them without re-injecting routing. `restart` refuses an in-place restart requested by a CLI whose version differs from the attested `/healthz` version; a newer CLI may use the guarded standalone update path described below, because an in-place replacement respawns from the live installation; placeholder versions (unknown/0.0.0) stay incomparable and keep the restart path. Configuration: provider, account, models, combo/route, access, integrations, v2. Client launchers: Claude, OpenCode, MiniMax Code, and MiniMax CLI text. The MMX launcher owns a child-lifetime loopback path bridge from the client's hard-coded `/anthropic/v1/messages` path to the canonical `/v1/messages` data plane; the server does not expose an extra auth surface. Diagnostics: doctor, debug, observe, health. Windows adds tray. Hidden `__update-badge` prints the read-only package badge JSON without refresh or shim repair for the npm tray. The full top-level reference is rendered by `src/cli/help.ts`; this table names the groups, not every verb. After help/version and unknown-root early exits, recognized commands run the bounded best-effort Codex-shim auto-restore policy before dispatch. `status`, `doctor`, and `codex-shim status` skip shim auto-repair; `system codex-cli-update` and [command-local messaging](local-messaging.md#command-local-cli) suppress it for their whole namespaces, including malformed invocations. Keeps the `#!/usr/bin/env bun` shebang for from-source dev (`bun run src/cli/index.ts`). `src/cli/init.ts` validates an explicit setup port as a decimal integer from 1 through 65535 before publishing the initial configuration. Only an empty answer selects 10100; malformed input is reported and the port question is asked again, while EOF or SIGINT still cancels without saving. | @@ -595,6 +595,6 @@ remains a reported recovery requirement. Dashboard restart delegates the lease t The registration is never deleted; `ocx service install` releases the marker only after the registration succeeds. Busy lease diagnostics name the recorded PID, current liveness, optional executable (omitted by default on Windows), and lease age. The process identity is unverified because a PID may be reused. -Bun updater lease and recovery behavior follows the [update transaction contract](ops/service-and-sidecars.md#bun-updater-ownership-transaction). On Windows, the Node npm self-update awaits `src/update/transactional-install.mjs`'s full installer-tree exit barrier before stage cleanup or verification: a staging-only Job Object owns the tree atomically from root creation, missing exit evidence retains the stage and marker, and stage failures preserve the untouched launcher for owner-aware recovery. Windows 10+ Job List attributes are required; unavailable atomic supervision fails before installer creation. POSIX retains its synchronous install path. +Bun updater lease and recovery behavior follows the [update transaction contract](ops/service-and-sidecars.md#bun-updater-ownership-transaction). On Windows, the Node npm self-update awaits `src/update/transactional-install.mjs`'s full installer-tree exit barrier before stage cleanup or verification: a staging-only Job Object owns the tree atomically from root creation, missing exit evidence retains the stage and marker, and stage failures preserve the untouched launcher for owner-aware recovery. Windows 10+ Job List attributes are required; unavailable atomic supervision fails before installer creation. POSIX retains its synchronous install path. The pnpm updater distinguishes a verified unchanged active tree from a verified rollback transaction; see [package refresh](ops/service-and-sidecars.md#package-cache-refresh). Both updater lanes supervise pnpm mutations with a POSIX process group or Windows Job Object. An unconfirmed mutation retains the time fence and stops before readback or rollback. Orchestrated plan registry and pnpm-owner probes use a temporary private cache and disable npm logs and update notices. The orchestrated pnpm verifier re-resolves the selected owner and validates the active tree and shims without executing the package launcher. Orchestrated outcome classification refuses malformed phase records and installed records without an absolute active root. Its child-wait helper forwards catchable signals and reports uncertainty if close is not observed within 60 seconds; an optional watchdog reports an overrun without signalling the child. Orchestrated Bun workers retain catchable-signal handlers through installer completion and recovery, keeping the mutex held until the final outcome is written. Companion timeline and filtered totals follow the [companion usage contract](companion.md). [Ongoing priority failback](providers/openai-accounts.md#ongoing-priority-failback) reuses request-triggered quota priming and captured-account dispatch; it adds no periodic worker or mid-request account switch. The serving-install census and bounded foreground delegation in `src/config/serving-runtimes.ts` follow [service command selection](ops/service-and-sidecars.md#background-service-command-selection). The live main-account policy projection is fetched from the attested account-list management API. `src/cli/status-oauth.ts` renders its state and effective thresholds with an optional outside-usage advisory; `src/cli/status.ts` includes the same whitelisted projection in `ocx status --json`. No policy state is inferred from the CLI process's local quota cache when the live read is unavailable. The experimental macOS `ocx chatgpt` launcher, restore and status commands follow the [ChatGPT Desktop contract](clients/chatgpt-desktop.md); the internal stdout filter remains hidden from public capability discovery. Generic OAuth conversation ownership follows [the generic account-pool contract](providers/generic-account-pool.md#conversation-affinity). diff --git a/tests/ci-workflows/install-scripts.test.ts b/tests/ci-workflows/install-scripts.test.ts index e8bc6028e92..7e7d981b436 100644 --- a/tests/ci-workflows/install-scripts.test.ts +++ b/tests/ci-workflows/install-scripts.test.ts @@ -218,13 +218,22 @@ exit 0 const launcher = await readText("bin/ocx.mjs"); expect(launcher).toContain('process.argv[2] === "update"'); - expect(launcher).toContain('["install", "-g", `${PKG}@${tag}`]'); - expect(launcher).toContain('["add", "-g", "--allow-build=bun", `${PKG}@${tag}`]'); + expect(launcher).toContain('const selector = child?.version ?? tag;'); + expect(launcher).toContain('["install", "-g", `${PKG}@${selector}`]'); + expect(launcher).toContain('["add", "-g", "--allow-build=bun", `${PKG}@${selector}`]'); + expect(launcher).toContain('const tag = updateTag(current);'); expect(launcher).toContain('return String(currentVersion).includes("-preview.") ? "preview" : "latest"'); expect(launcher).toContain("!isBunGlobalInstall()"); expect(launcher).toContain("repairCodexShimIfNeeded(postUpdateLauncher, homePolicy.authorizeMutation)"); expect(launcher).toContain("runNpmSelfUpdate()"); expect(launcher).toContain("runPnpmSelfUpdate()"); + const bunStart = launcher.indexOf('const child = probeSpawn(bun,'); + for (const entry of ['if (installMethod === "npm") await runNpmSelfUpdate();', + 'if (installMethod === "pnpm") await runPnpmSelfUpdate();', + 'await runPackageManagerSelfUpdate(installMethod, childArgs);']) { + expect(launcher.indexOf(entry)).toBeGreaterThan(-1); + expect(launcher.indexOf(entry)).toBeLessThan(bunStart); + } }); test("release helper watches the workflow run it just dispatched", async () => { diff --git a/tests/cli/cli-capabilities-arguments.test.ts b/tests/cli/cli-capabilities-arguments.test.ts index 083329ab3ed..40a37824ba9 100644 --- a/tests/cli/cli-capabilities-arguments.test.ts +++ b/tests/cli/cli-capabilities-arguments.test.ts @@ -1,7 +1,51 @@ import { describe, expect, spyOn, test } from "bun:test"; import { runCapabilities } from "../../src/cli/capabilities-command"; +import { findCommand } from "../../src/cli/registry"; +import { CAPABILITY_CONTRACTS } from "../../src/cli/capability-contracts"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { repoPath } from "../helpers/repo-root"; describe("capabilities argument validation", () => { + test("update, sync and capabilities help expose orchestration contracts", () => { + const home = mkdtempSync(join(tmpdir(), "ocx-help-")); + try { + const launcher = spawnSync(process.execPath, [repoPath("bin/ocx.mjs"), "update", "--help"], { + encoding: "utf8", env: { ...process.env, HOME: home, OPENCODEX_HOME: join(home, "ocx"), CODEX_HOME: join(home, "codex") }, + }); + expect(launcher.status).toBe(0); + const entry = findCommand("update")!; + for (const flag of ["--plan", "--yes", "--json", "--expect-plan", "--not-after"]) { + expect([entry.usage, ...entry.details ?? []].join(" ")).toContain(flag); + expect(launcher.stdout).toContain(flag); + } + for (const code of ["10", "11", "12", "64"]) expect(launcher.stdout).toContain(code); + expect(findCommand("capabilities")!.usage).toContain("--contracts"); + expect(findCommand("sync")!.details!.join(" ")).toContain("exit 7"); + } finally { rmSync(home, { recursive: true, force: true }); } + }); + test("contracts are present in every JSON shape and can be queried alone", async () => { + const out = spyOn(console, "log").mockImplementation(() => {}); + const err = spyOn(console, "error").mockImplementation(() => {}); + try { + for (const args of [["--json"], ["--json", "--route", "/api/logs"], ["--json", "--mutating-only"], ["--json", "--route", "/missing"]]) { + out.mockClear(); + expect(await runCapabilities(args)).toBe(args.includes("/missing") ? 4 : 0); + expect(JSON.parse(String(out.mock.calls[0]![0])).contracts).toEqual([...CAPABILITY_CONTRACTS]); + } + out.mockClear(); + expect(await runCapabilities(["--contracts", "--json"])).toBe(0); + expect(JSON.parse(String(out.mock.calls[0]![0]))).toEqual({ schemaVersion: 1, contracts: [...CAPABILITY_CONTRACTS] }); + out.mockClear(); + expect(await runCapabilities(["--contracts"])).toBe(0); + expect(out.mock.calls.map(call => call[0])).toEqual([...CAPABILITY_CONTRACTS]); + expect(CAPABILITY_CONTRACTS).toContain("update.orchestrated/1"); + expect(CAPABILITY_CONTRACTS).toContain("sync.home-fanout/1"); + for (const args of [["--contracts", "--mutating-only"], ["--contracts", "--route", "/api/logs"]]) expect(await runCapabilities(args)).toBe(64); + } finally { out.mockRestore(); err.mockRestore(); } + }); test.each([ ["--mutating-onyl"], ["extra"], ["--json", "--json"], ["--route", "/api/logs", "--route", "/api/usage"], @@ -38,4 +82,11 @@ describe("capabilities argument validation", () => { expect(JSON.parse(String(out.mock.calls[0]![0])).capabilities).toEqual([]); } finally { out.mockRestore(); } }); + test("invalid capability arguments advertise contracts", async () => { + const err = spyOn(console, "error").mockImplementation(() => {}); + try { + expect(await runCapabilities(["--invalid"])).toBe(64); + expect(String(err.mock.calls[0]![0])).toContain("--contracts"); + } finally { err.mockRestore(); } + }); }); diff --git a/tests/cli/cli-client-start-fence.test.ts b/tests/cli/cli-client-start-fence.test.ts index 30f16536d00..cad64e78baa 100644 --- a/tests/cli/cli-client-start-fence.test.ts +++ b/tests/cli/cli-client-start-fence.test.ts @@ -5,10 +5,20 @@ import { startClientRuntimeUnderOwnershipLease } from "../../src/cli/client-star import { recoverStartStateUnderOwnershipLease } from "../../src/cli/start-owner-fence"; import { serviceChildOwnershipDecisionForClassifiedChild } from "../../src/service/service-child-ownership"; import type { ServiceOwnershipResolution } from "../../src/service/state"; +import { clientRuntimeRecord } from "../../src/client/runtime"; +import { currentServingCommand } from "../../src/config/serving-runtimes"; class StayOut extends Error {} describe("connected-client start ownership fence", () => { + test("published connected-client identity retains the current serving command", () => { + expect(clientRuntimeRecord(123, 12345).command).toEqual(currentServingCommand()); + }); + test("ordinary start publishes its serving command alongside the attestation secret", () => { + const cli = readFileSync(repoPath("src/cli/index.ts"), "utf8"); + const record = cli.slice(cli.indexOf("writeRuntime: bound =>"), cli.indexOf("stopBound: bound =>")); + expect(record).toContain("command: currentServingCommand()"); + }); test("a desktop claim committed at recovery lease acquisition skips sibling marking and journal reconciliation", async () => { let ownership: ServiceOwnershipResolution = { kind: "none", revision: 0 }; expect(serviceChildOwnershipDecisionForClassifiedChild(true, () => ownership)).toEqual({ kind: "proceed" }); diff --git a/tests/cli/cli-sync-expect-link.test.ts b/tests/cli/cli-sync-expect-link.test.ts index 0cf79030200..299c1e7fe69 100644 --- a/tests/cli/cli-sync-expect-link.test.ts +++ b/tests/cli/cli-sync-expect-link.test.ts @@ -416,13 +416,13 @@ describe("ocx sync --expect-link / --expect-hub-key", () => { }); }); -describe("the CLI root leaves a pinned sync to its own check", () => { - test("the shim preflight skips a pinned sync and keeps repairing a plain one", () => { +describe("the CLI root leaves sync to its own guard", () => { + test("the shim preflight skips sync until the mutex is acquired", () => { const skips = shimAutoRestore.skipsCodexShimAutoRestore; expect(skips("sync", ["sync", "--expect-link", LINK_ID])).toBe(true); expect(skips("sync", ["sync", `--expect-hub-key=${HUB_KEY_ID}`])).toBe(true); - expect(skips("sync", ["sync"])).toBe(false); - expect(skips("sync", ["sync", "--expect-linked"])).toBe(false); + expect(skips("sync", ["sync"])).toBe(true); + expect(skips("sync", ["sync", "--expect-linked"])).toBe(true); }); test("a malformed pinned sync exits 2 at the root, before any preflight", async () => { diff --git a/tests/cli/ocx-launcher-desktop-handoff.test.ts b/tests/cli/ocx-launcher-desktop-handoff.test.ts index f15b757dec2..85d997dc12f 100644 --- a/tests/cli/ocx-launcher-desktop-handoff.test.ts +++ b/tests/cli/ocx-launcher-desktop-handoff.test.ts @@ -11,6 +11,8 @@ import { initializeNodeLauncherContext } from "../../src/cli/launcher-context"; import { buildNativeClaudeEnv } from "../../src/cli/claude"; import { observeManagingClis } from "../../src/service/managing-cli"; import { repoPath } from "../helpers/repo-root"; +import { tryAcquireUpdateSyncMutex } from "../../src/update/sync-update-mutex.mjs"; +import { createLegacyUpdateSession, createOrchestratedChildSession } from "../../src/update/orchestrated-session.mjs"; // Explicit private fixtures; only temp paths are written by this helper. function writeFileSync(path: string, data: Parameters[1]): void { @@ -64,6 +66,14 @@ function fakeSpawn(error?: string, exitSignal: NodeJS.Signals | null = null) { } describe("Desktop record and handoff policy", () => { + test("contract discovery and updates answer from the invoked package even with a Desktop record", () => { + for (const argv of [["capabilities", "--contracts", "--json"], ["update", "--plan", "--json"]]) { + expect(planDesktopCliHandoff({ platform: "linux", argv, env: {}, recordRead: ready() }, deps)) + .toEqual({ kind: "continue", reason: "excluded" }); + } + expect(planDesktopCliHandoff({ platform: "linux", argv: ["capabilities", "--json"], env: {}, recordRead: ready() }, deps).kind) + .toBe("handoff"); + }); test("fixed record location and injected reader path", () => { expect(desktopCliRecordPath({ platform: "darwin", home: "/Users/example" })).toBe("/Users/example" + "/.opencodex-desktop/cli.json"); expect(desktopCliRecordPath({ platform: "win32", env: { USERPROFILE: "C:\\Users\\example" } })).toBe("C:\\Users\\example\\.opencodex-desktop\\cli.json"); @@ -226,6 +236,101 @@ function packageFixture() { } const posixTest = process.platform === "win32" ? test.skip : test; const launcher = repoPath("bin", "ocx.mjs"); +posixTest("sync Desktop handoff refuses an update before executing the target", () => { + const fixture = packageFixture(), ran = join(fixture.home, "ran"); + writeFileSync(fixture.target, `#!/bin/sh\necho ran > '${ran}'\n`); chmodSync(fixture.target, 0o700); + const lock = tryAcquireUpdateSyncMutex(fixture.env.OPENCODEX_HOME!, "update"); + if (lock.kind !== "acquired") throw Error("fixture lock"); + try { + const result = spawnSync("node", [launcher, "sync", "--json"], { env: { ...fixture.env, npm_config_registry: "http://127.0.0.1:9", NPM_CONFIG_REGISTRY: "http://127.0.0.1:9" }, encoding: "utf8", timeout: 12000 }); + expect({ status: result.status, stderr: result.stderr }).toMatchObject({ status: 7, stderr: expect.stringContaining("update-in-flight") }); + expect(JSON.parse(result.stdout)).toEqual({ schema: "ocx.sync.fanout/1", home: { state: "skipped", exit: 7 }, fanout: { state: "not-applicable", reason: "update-in-flight" }, children: [] }); + expect(lstatExists(ran)).toBe(false); + } finally { lock.release(); } +}, 15000); + +posixTest("sync Desktop handoff refuses a malformed lease before executing the target", () => { + const fixture = packageFixture(), ran = join(fixture.home, "ran"); + writeFileSync(fixture.target, `#!/bin/sh\necho ran > '${ran}'\n`); chmodSync(fixture.target, 0o700); + const lock = join(fixture.env.OPENCODEX_HOME!, "sync-update.mutation.lock"); + mkdirSync(lock); writeFileSync(join(lock, "malformed.json"), "{"); + for (const json of [false, true]) { + const result = spawnSync("node", [launcher, "sync", ...(json ? ["--json"] : [])], { env: { ...fixture.env, OCX_TEST_HOME_GUARD: "1", npm_config_registry: "http://127.0.0.1:9", NPM_CONFIG_REGISTRY: "http://127.0.0.1:9" }, encoding: "utf8", timeout: 12000 }); + expect(result.status).toBe(7); expect(result.stderr.trim()).toBe("update-in-flight"); + if (json) expect(JSON.parse(result.stdout)).toEqual({ schema: "ocx.sync.fanout/1", home: { state: "skipped", exit: 7 }, fanout: { state: "not-applicable", reason: "update-in-flight" }, children: [] }); + else expect(result.stdout).toBe(""); + expect(lstatExists(ran)).toBe(false); + } +}, 15000); + +function lstatExists(path: string) { try { lstatSync(path); return true; } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; throw error; } } + +posixTest("old Desktop sync stays under launcher mutex until it exits", async () => { + const fixture = packageFixture(); + writeFileSync(fixture.target, "#!/bin/sh\necho ready:$OCX_SYNC_MUTEX_HELD_BY\nread line\n"); chmodSync(fixture.target, 0o700); + const child = spawn("node", [launcher, "sync"], { env: { ...fixture.env, npm_config_registry: "http://127.0.0.1:9", NPM_CONFIG_REGISTRY: "http://127.0.0.1:9" }, stdio: ["pipe", "pipe", "pipe"] }); + const exited = new Promise((resolve, reject) => { child.once("error", reject); child.once("exit", resolve); }); + try { + const ready = await new Promise((resolve, reject) => { child.stdout!.once("data", data => resolve(String(data))); child.once("error", reject); child.once("exit", () => reject(Error("target exited before ready"))); }); + expect(ready.trim()).toBe(`ready:${child.pid}`); + const session = createLegacyUpdateSession({ home: fixture.env.OPENCODEX_HOME! }); + expect(session.start()).toEqual({ ok: false, error: "sync-in-progress" }); + child.stdin!.end("done\n"); + expect(await exited).toBe(0); + } finally { if (child.exitCode === null) child.kill("SIGKILL"); } +}, 15000); +posixTest("a killed launcher leaves the live Desktop delegate fenced past the stale interval", async () => { + const fixture = packageFixture(), home = fixture.env.OPENCODEX_HOME!; + const stop = join(fixture.home, "stop-delegate"); + writeFileSync(fixture.target, `#!/bin/sh\necho ready\nwhile [ ! -f '${stop}' ]; do sleep 0.1; done\n`); chmodSync(fixture.target, 0o700); + const launcherChild = spawn("node", [launcher, "sync"], { env: { ...fixture.env, OCX_TEST_HOME_GUARD: "1", npm_config_registry: "http://127.0.0.1:9", NPM_CONFIG_REGISTRY: "http://127.0.0.1:9" }, stdio: ["pipe", "pipe", "pipe"] }); + let delegate = 0; + try { + await new Promise((resolve, reject) => { launcherChild.stdout!.once("data", () => resolve()); launcherChild.once("error", reject); launcherChild.once("exit", () => reject(Error("launcher exited early"))); }); + const lockPath = join(home, "sync-update.mutation.lock"); + const deadline = Date.now() + 3000; + while (!delegate && Date.now() < deadline) { + const entries = readdirSync(lockPath); + if (entries.length === 1) delegate = JSON.parse(readFileSync(join(lockPath, entries[0]!), "utf8")).delegatePid ?? 0; + if (!delegate) await Bun.sleep(10); + } + expect(delegate).toBeGreaterThan(0); + const exited = new Promise(resolve => launcherChild.once("exit", () => resolve())); + launcherChild.kill("SIGKILL"); await exited; + const futureTime = Date.now() + 31_000, future = () => futureTime; + expect(tryAcquireUpdateSyncMutex(home, "update", { now: future })).toEqual({ kind: "busy", holder: "sync" }); + const realNow = Date.now; + try { + Date.now = future; + expect(createLegacyUpdateSession({ home }).start()).toEqual({ ok: false, error: "sync-in-progress" }); + expect(createOrchestratedChildSession({ home, verifyIdentity: () => true }).start()).toEqual({ ok: false, error: "sync-in-progress" }); + } finally { Date.now = realNow; } + writeFileSync(stop, "stop"); + const end = Date.now() + 3000; + let lease = tryAcquireUpdateSyncMutex(home, "update", { now: future }); + while (lease.kind !== "acquired" && Date.now() < end) { await Bun.sleep(10); lease = tryAcquireUpdateSyncMutex(home, "update", { now: future }); } + expect(lease.kind).toBe("acquired"); + if (lease.kind === "acquired") { delegate = 0; lease.release(); } + } finally { + if (launcherChild.exitCode === null && launcherChild.signalCode === null) launcherChild.kill("SIGKILL"); + if (delegate) { try { process.kill(delegate, "SIGKILL"); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; } } + } +}, 15000); +posixTest("sync launcher releases its mutex after forwarding a signal and waiting for Desktop", async () => { + const fixture = packageFixture(); + writeFileSync(fixture.target, "#!/bin/sh\ntrap 'exit 29' TERM\necho ready\nwhile :; do sleep 1; done\n"); chmodSync(fixture.target, 0o700); + const child = spawn("node", [launcher, "sync"], { env: { ...fixture.env, npm_config_registry: "http://127.0.0.1:9", NPM_CONFIG_REGISTRY: "http://127.0.0.1:9" }, stdio: ["ignore", "pipe", "pipe"] }); + try { + const code = await new Promise((resolve, reject) => { + child.once("error", reject); child.once("exit", resolve); + child.stdout!.once("data", () => child.kill("SIGTERM")); + }); + expect(code).toBe(29); + const lease = tryAcquireUpdateSyncMutex(fixture.env.OPENCODEX_HOME!, "update"); + expect(lease.kind).toBe("acquired"); + if (lease.kind === "acquired") lease.release(); + } finally { if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL"); } +}, 15000); posixTest("real Node launcher regenerates proof, forwards argv/stdin, mirrors exit and bypasses Bun lookup", () => { const fixture = packageFixture(); writeFileSync(fixture.target, `#!/usr/bin/env node\nconst fs = require('node:fs');\nconsole.log(JSON.stringify({ argv: process.argv.slice(2), context: JSON.parse(process.env.OCX_NODE_LAUNCH_CONTEXT), stdin: fs.readFileSync(0, 'utf8'), bypass: process.env.OCX_NO_DESKTOP_HANDOFF }));\nprocess.exit(23);\n`); @@ -297,7 +402,7 @@ test("launcher source anchors preserve exceptions before handoff and handoff bef const source = readFileSync(launcher, "utf8"); const hook = source.indexOf("const desktopPlan ="); expect(hook).toBeGreaterThan(source.indexOf("const codexCliUpdateInspection =")); - expect(hook).toBeLessThan(source.indexOf('if (process.argv[2] === "update" && installMethod === "mise")')); + expect(hook).toBeLessThan(source.indexOf('process.argv[2] === "update" && installMethod === "mise"')); expect(hook).toBeLessThan(source.indexOf("const probe = bootRestoreProbe(")); expect(hook).toBeLessThan(source.indexOf("const bunRuntime = resolveBun(")); expect(source).toContain("const { launchProof, launchContext, inheritedEnv } = createNodeLaunchContext();"); diff --git a/tests/cli/ocx-launcher-source.test.ts b/tests/cli/ocx-launcher-source.test.ts index c3aff7940cb..32cdabecbab 100644 --- a/tests/cli/ocx-launcher-source.test.ts +++ b/tests/cli/ocx-launcher-source.test.ts @@ -65,7 +65,7 @@ describe("ocx.mjs package launcher (source invariants)", () => { expect(spawnCall).toContain("[BUN_RUNTIME_SOURCE_ENV]: bunRuntime.source"); // Path and source come from one resolution, so the marker cannot describe another binary. - expect(source).toContain("const bunRuntime = resolveBun({ allowInstall: !codexCliUpdateInspection });"); + expect(source).toContain("const bunRuntime = resolveBun({ allowInstall: !passiveSync && !orchestratedUpdate && !passiveCapabilities && !codexCliUpdateInspection, allowMissing: orchestratedUpdate || passiveSync });"); expect(source).toContain("const bun = bunRuntime.path;"); expect(source).toContain('return { path: bin, source: "bundled", version: bundledBunVersion(bunDir) };'); diff --git a/tests/codex-integration/codex-cli-update-launcher-policy.test.ts b/tests/codex-integration/codex-cli-update-launcher-policy.test.ts index 67fe73a7b36..8f3b8b3c183 100644 --- a/tests/codex-integration/codex-cli-update-launcher-policy.test.ts +++ b/tests/codex-integration/codex-cli-update-launcher-policy.test.ts @@ -40,7 +40,7 @@ describe("Codex CLI updater launcher policy", () => { const guard = source.slice(source.lastIndexOf("if (", probeCall), probeCall); expect(guard).toContain("!codexCliUpdateInspection"); expect(guard).toContain("isNodeModulesInstall()"); - expect(source).toContain("resolveBun({ allowInstall: !codexCliUpdateInspection })"); + expect(source).toContain("const bunRuntime = resolveBun({ allowInstall: !passiveSync && !orchestratedUpdate && !passiveCapabilities && !codexCliUpdateInspection, allowMissing: orchestratedUpdate || passiveSync });"); // A missing bundle makes installJs nullable; allowInstall still gates its execution. expect(source).toContain( 'if (allowInstall && installJs && existsSync(installJs)) {\n const r = probeSpawnSync(process.execPath, [installJs], { stdio: "inherit" });', diff --git a/tests/codex-integration/codex-shim-autorestore.test.ts b/tests/codex-integration/codex-shim-autorestore.test.ts index 7f11b97ff02..9525541fed1 100644 --- a/tests/codex-integration/codex-shim-autorestore.test.ts +++ b/tests/codex-integration/codex-shim-autorestore.test.ts @@ -53,6 +53,10 @@ describe("Codex shim CLI auto-restore policy", () => { expect(skipsCodexShimAutoRestore("system", ["system", "update", "check"])).toBe(false); // resolve is read-only inspection for embedding shells: a lookup made to populate a // consent surface must not trigger a shim repair side effect first. + for (const args of [["capabilities"], ["update", "--plan"], ["update", "--yes", "--json"], ["update", "--plan", "--bad"], ["update", "--not-after", "123"], ["sync"]]) { + expect(skipsCodexShimAutoRestore(args[0], args)).toBe(true); + } + expect(skipsCodexShimAutoRestore("update", ["update", "--tag", "latest"])).toBe(false); expect(skipsCodexShimAutoRestore("resolve", ["resolve"])).toBe(true); expect(skipsCodexShimAutoRestore("resolve", ["resolve", "--json"])).toBe(true); for (const command of ["status", "doctor"]) { @@ -220,4 +224,18 @@ describe("Codex shim CLI auto-restore policy", () => { } }); }, 30_000); + + test("real orchestrated child entry does not repair a missing shim before admission", () => { + if (process.platform === "win32") return; + withInstalledShim(({ home, wrappers }) => { + rmSync(wrappers[0]); + const expected = Buffer.from(JSON.stringify({ home, cliRoot: home, servingRoot: null, runtimePid: null, planToken: "a".repeat(43) })).toString("base64url"); + const result = spawnSync(process.execPath, [repoPath("src/cli/index.ts"), "update", "--version", "99.0.0", + "--orchestrated-expect", expected, "--orchestrated-result", join(home, "result.json")], { + encoding: "utf8", env: { ...process.env, USERPROFILE: home, OCX_UPDATE_ORCHESTRATED_CHILD: "1", OPENCODEX_CODEX_SHIM_AUTO_RESTORE: "1" }, + }); + expect(result.status).not.toBe(0); + expect(existsSync(wrappers[0])).toBe(false); + }); + }, 30000); }); diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 4e6e5fea080..7349ad6a7cd 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1434,7 +1434,7 @@ "update-job.test.ts": "update", "update-recovery-host-free.test.ts": "update", "update-job-supervised-restart.test.ts": "update", "update-standalone.test.ts": "update", "update-worker-launch.test.ts": "update", "update-notify.test.ts": "update", - "update-npm-cache-preflight.test.ts": "update", "update-npm-invocation.test.ts": "update", "update-npm-timeout.test.ts": "update", "update-npm-supervisor-exit.test.ts": "update", + "update-orchestrated-session.test.ts": "update", "update-orchestrated-entry.test.ts": "update", "update-orchestrated-apply.test.ts": "update", "update-orchestrated-arguments.test.ts": "update", "update-orchestrated-plan.test.ts": "update", "update-sync-mutex.test.ts": "update", "update-orchestrated-identity.test.ts": "update", "update-orchestrated-token.test.ts": "update", "update-npm-cache-preflight.test.ts": "update", "update-npm-invocation.test.ts": "update", "update-npm-timeout.test.ts": "update", "update-npm-supervisor-exit.test.ts": "update", "update-mise-launcher-target.test.ts": "update", "update-mise.test.ts": "update", "update-mise-node-runtime.test.ts": "update", "update-pnpm.test.ts": "update", "update-refresh.test.ts": "update", "update-restart-lease.test.ts": "update", diff --git a/tests/helpers/update-bun-ownership-child.ts b/tests/helpers/update-bun-ownership-child.ts index 2b54f49f0c6..07454250d8a 100644 --- a/tests/helpers/update-bun-ownership-child.ts +++ b/tests/helpers/update-bun-ownership-child.ts @@ -134,11 +134,21 @@ mock.module("node:child_process", () => ({ ...processTools, Date.now = () => realNow() + clockOffset; return directChild; }, - spawnSync: (_bin: string, args: string[], options: { env?: NodeJS.ProcessEnv; windowsVerbatimArguments?: boolean } = {}) => { + spawnSync: (_bin: string, args: string[], options: { env?: NodeJS.ProcessEnv; windowsVerbatimArguments?: boolean; input?: string } = {}) => { if (spawnedNpmOperation(args, options) === "view") return { status: 0, stdout: "99.0.0\n", stderr: "" }; + const supervisor = args[0] === repoPath("src/update/posix-install-supervisor-entry.mjs") && args[1] === "supervise"; + if (supervisor) { + const request = JSON.parse(options.input ?? "null"); + const marker = JSON.parse(readFileSync(join(home, "update-orchestrated.json"), "utf8")); + if (request?.markerPath !== join(home, "update-orchestrated.json") || marker.phase !== "mutating" + || marker.pid !== process.pid || !Array.isArray(request.args) + || !request.args.some((arg: unknown) => typeof arg === "string" && arg.includes("@bitkyc08/opencodex"))) { + throw new Error("invalid installer supervisor request"); + } + } const env = options.env ?? process.env; const phase = args.includes("stop") ? "stop" : args.includes("service") ? "recovery" - : args.some(arg => arg.includes("@bitkyc08/opencodex")) ? "replacement" : "ancillary"; + : supervisor || args.some(arg => arg.includes("@bitkyc08/opencodex")) ? "replacement" : "ancillary"; trace.push({ phase, contenderBlocked: probe(unprivileged()) === 17, delegated: !!env[tokenKey], canJoin: probe(env) === 0 }); if (phase === "stop") { @@ -149,9 +159,12 @@ mock.module("node:child_process", () => ({ ...processTools, } if (phase === "replacement") { packageReplaced = true; - if (scenario === "replacement-throw") throw new Error("injected replacement failure"); + // The real supervisor converts an installer exception into a confirmed nonzero exit. + if (scenario === "replacement-throw" && !supervisor) throw new Error("injected replacement failure"); if (scenario === "foreign-owner") writeFileSync(authority, JSON.stringify({ revision: 2, owner: "desktop", installId: "owner-b", consentGeneration: 2 })); - if (direct || scenario === "home-unknown-fail" || scenario === "package-fail" || scenario === "foreign-owner" || scenario === "recovery-throw") return { status: 1 }; + const status = direct || ["home-unknown-fail", "package-fail", "foreign-owner", "recovery-throw", "replacement-throw"].includes(scenario) ? 1 : 0; + if (supervisor) return { status: 0, stdout: scenario === "supervisor-unconfirmed" ? "" : JSON.stringify({ status, signal: null, groupExited: true, groupKilled: false }), stderr: "" }; + if (status) return { status }; } if (phase === "recovery") { if (scenario === "recovery-throw") throw new Error("injected recovery failure"); diff --git a/tests/helpers/update-node-home-child.mjs b/tests/helpers/update-node-home-child.mjs index 18c48ea1fed..85ff946c030 100644 --- a/tests/helpers/update-node-home-child.mjs +++ b/tests/helpers/update-node-home-child.mjs @@ -8,12 +8,13 @@ import { createUpdateServiceHomePolicy, parseUpdateWorkerHome, UPDATE_PACKAGE_ON import { inspectPackageRuntimeLiveness, planUpdateRuntimeHandling } from "../../src/update/runtime-ownership.mjs"; import { handoffWindowsTrayForUpdate, planWindowsTrayUpdate } from "../../src/update/tray-update-plan.mjs"; import { manualUpdateFailureGuidance, npmUpdateFailureGuidance } from "../../src/update/update-failure-guidance.mjs"; +import { createLegacyUpdateSession } from "../../src/update/orchestrated-session.mjs"; const [home, observed, ...argv] = process.argv.slice(2); if (!home || process.env.OPENCODEX_HOME !== home) throw new Error("isolated fixture home required"); const launcher = fileURLToPath(new URL("../../bin/ocx.mjs", import.meta.url)); const source = readFileSync(launcher, "utf8"); -const from = source.indexOf("async function runPackageManagerSelfUpdate(manager) {"); +const from = source.indexOf("async function runPackageManagerSelfUpdate(manager, child) {"); const to = source.indexOf("function bunBinDir(", from); if (from < 0 || to < from) throw new Error("production function boundary missing"); const body = source.slice(from, to).replaceAll("import.meta.url", JSON.stringify(new URL("../../bin/ocx.mjs", import.meta.url).href)); @@ -24,7 +25,8 @@ let trayRunning = trayInitiallyRunning; let packageReplaced = false; process.on("exit", () => process.stdout.write(`NODE_HOME_PROBE:${JSON.stringify(trace)}\n`)); const dependencies = { - process: { argv: [process.execPath, launcher, "update", ...argv], env: process.env, execPath: process.execPath, platform: process.platform, exit: code => process.exit(code) }, + process: { argv: [process.execPath, launcher, "update", ...argv], env: process.env, execPath: process.execPath, platform: process.platform, once: process.once.bind(process), exit: code => process.exit(code) }, + createLegacyUpdateSession, console, PKG: "@bitkyc08/opencodex", here: dirname(launcher), dirname, join, resolve, fileURLToPath, currentPackageVersion: () => "1.0.0", updateTag: () => "latest", npmInvocation: args => ({ file: "fixture-npm", args }), diff --git a/tests/service/ownership-mutation-lease-diagnostics.test.ts b/tests/service/ownership-mutation-lease-diagnostics.test.ts index 3fe8b610764..2db08c0199b 100644 --- a/tests/service/ownership-mutation-lease-diagnostics.test.ts +++ b/tests/service/ownership-mutation-lease-diagnostics.test.ts @@ -46,6 +46,13 @@ describe("ownership mutation lease diagnostic lookup (carry #6655)", () => { }); } + test("diagnostics distinguish a dead holder from its live delegate", () => { + writeFileSync(owner, JSON.stringify({ version: 1, pid, delegatePid: 9876, processInstance: instance, token, createdAt: 1000 })); + const line = ownershipMutationLeaseStatusLine(paths, { processAlive: value => value === 9876, processImage: () => "wrong-image" }); + expect(line).toContain(`recorded PID ${pid} [not alive, identity unverified]`); + expect(line).toContain("delegate PID 9876"); + }); + test("Windows inspection, status and busy refusal launch zero diagnostic subprocesses and preserve the owner", () => { const bytes = readFileSync(owner); const identity = lstatSync(owner); diff --git a/tests/update/update-bun-ownership-lease.test.ts b/tests/update/update-bun-ownership-lease.test.ts index 01389f9e3d5..053b4b51887 100644 --- a/tests/update/update-bun-ownership-lease.test.ts +++ b/tests/update/update-bun-ownership-lease.test.ts @@ -27,7 +27,9 @@ async function run(scenario: string) { while (alive() && Date.now() < deadline) await Bun.sleep(20); expect(alive(), "owned recovery fixture must exit").toBe(false); } - return { exit, trace, log: out + err, pendingReceipt: existsSync(home.path("pending-teardown-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.unreadable.json")) }; + const markerPath = home.path("update-orchestrated.json"); + const marker = existsSync(markerPath) ? JSON.parse(readFileSync(markerPath, "utf8")) : null; + return { exit, trace, marker, log: out + err, pendingReceipt: existsSync(home.path("pending-teardown-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.unreadable.json")) }; } finally { home.remove(); } } @@ -50,6 +52,14 @@ test.skipIf(process.platform === "win32")("the actual Bun updater leases stop th expect(result.trace.at(-1)).toMatchObject({ phase: "after", reacquired: true, parentToken: false }); }, 30_000); +test.skipIf(process.platform === "win32")("unconfirmed installer termination retains the fence and defers recovery", async () => { + const result = await run("supervisor-unconfirmed"); + expect(result.exit, result.log).toBe(1); + expect(result.trace.map(row => row.phase)).toEqual(["stop", "replacement", "after"]); + expect(result.marker).toMatchObject({ phase: "failed", fenceUntil: expect.any(Number) }); + expect(result.log).toContain("Installer termination was not confirmed"); +}, 30_000); + test.skipIf(process.platform === "win32").each(["package-fail", "stop-throw", "replacement-throw", "recovery-throw"])("%s keeps recovery owned and releases before exit", async scenario => { const result = await run(scenario); expect(result.exit, result.log).not.toBe(0); diff --git a/tests/update/update-home-launcher.test.ts b/tests/update/update-home-launcher.test.ts index 641a885e0b0..613599e97a4 100644 --- a/tests/update/update-home-launcher.test.ts +++ b/tests/update/update-home-launcher.test.ts @@ -276,7 +276,7 @@ test("the new package remains inspectable by an already-running v1 updater", () && value?.entry === "__update-home-probe" && Object.keys(value).length === 3; expect(legacyAccepts(declaration)).toBe(true); const start = source.indexOf('if (process.argv[2] === "__update-home-probe")'); - const end = source.indexOf("const desktopPlan =", start); + const end = source.indexOf('if (process.argv[2] === "__update-orchestrated-identity")', start); const run = updateSourceFunction("deps", `with (deps) { ${source.slice(start, end).replace("import.meta.url", "\"fixture\"")} }`); let response = ""; const terminal = new Error("exit"); diff --git a/tests/update/update-orchestrated-apply.test.ts b/tests/update/update-orchestrated-apply.test.ts new file mode 100644 index 00000000000..b439417560e --- /dev/null +++ b/tests/update/update-orchestrated-apply.test.ts @@ -0,0 +1,190 @@ +import { expect, test } from "bun:test"; +import { chmodSync, closeSync, mkdirSync, mkdtempSync, openSync, rmSync, truncateSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { EventEmitter } from "node:events"; +import { classifyOrchestratedOutcome, type OutcomeInput } from "../../src/update/orchestrated-outcome.mjs"; +import { verifyOrchestratedInstall } from "../../src/update/orchestrated-tree.mjs"; +import { verifyOrchestratedPnpmInstall } from "../../src/update/orchestrated-pnpm.mjs"; +import { waitForOrchestratedChild } from "../../src/update/orchestrated-child.mjs"; + +const base: OutcomeInput = { + fromVersion: "2.0.0", toVersion: "2.1.0", installer: "npm", childExited: true, + childExitCode: 1, outcome: { phase: "preflight" }, previousVerified: true, + targetVerified: false, runtimeHealthy: true, restarted: false, +}; + +test("the parent watchdog reports overrun without signalling a still-running child", async () => { + const signals = new EventEmitter(), child = new EventEmitter(); + const forwarded: string[] = []; + Object.assign(child, { kill: (signal: string) => { forwarded.push(signal); return true; } }); + const timers: Array<{ callback: () => void; ms: number }> = []; + const cleared: number[] = []; + const waiting = waitForOrchestratedChild(child as never, { + signals, overrunMs: 900_000, + setTimer: (callback: () => void, ms: number) => { timers.push({ callback, ms }); return timers.length; }, + clearTimer: (id: unknown) => { cleared.push(id as number); }, + }); + expect(timers.map(timer => timer.ms)).toEqual([900_000]); + timers[0]!.callback(); + expect(await waiting).toEqual({ confirmed: false, code: null, signal: null, reason: "overrun" }); + expect(forwarded).toEqual([]); + expect(signals.listenerCount("SIGTERM")).toBe(0); + expect(cleared).toContain(1); + child.emit("close", 0, null); + + const completed = new EventEmitter(); + Object.assign(completed, { kill: () => true }); + const normal = waitForOrchestratedChild(completed as never, { + signals, overrunMs: 900_000, + setTimer: (callback: () => void, ms: number) => { timers.push({ callback, ms }); return timers.length; }, + clearTimer: (id: unknown) => { cleared.push(id as number); }, + }); + completed.emit("close", 0, null); + expect(await normal).toEqual({ confirmed: true, code: 0, signal: null }); + expect(cleared).toContain(2); +}); + +test("a distant watchdog deadline is not shortened by the platform timer limit", async () => { + const signals = new EventEmitter(), child = new EventEmitter(); + Object.assign(child, { kill: () => true }); + const timers: Array<{ callback: () => void; ms: number }> = []; + const waiting = waitForOrchestratedChild(child as never, { + signals, overrunMs: 2_147_483_647 + 42, + setTimer: (callback: () => void, ms: number) => { timers.push({ callback, ms }); return timers.length; }, + clearTimer: () => {}, + }); + expect(timers[0]!.ms).toBe(2_147_483_647); + timers[0]!.callback(); + expect(timers[1]!.ms).toBe(42); + timers[1]!.callback(); + expect(await waiting).toMatchObject({ confirmed: false, reason: "overrun" }); +}); + +test("a signal is forwarded and completion waits for close or the bounded timer", async () => { + const signals = new EventEmitter(), child = new EventEmitter(); + const forwarded: string[] = []; + Object.assign(child, { kill: (signal: string) => { forwarded.push(signal); return true; } }); + let deadline: (() => void) | undefined; + const deps = { signals, setTimer: (callback: () => void) => { deadline = callback; return 1; }, clearTimer: () => {} }; + const waiting = waitForOrchestratedChild(child as never, deps); + signals.emit("SIGTERM"); + expect(forwarded).toEqual(["SIGTERM"]); + expect(deadline).toBeDefined(); + child.emit("close", 1, null); + expect(await waiting).toEqual({ confirmed: true, code: 1, signal: null }); + + const stillRunning = new EventEmitter(); + Object.assign(stillRunning, { kill: () => true }); + const uncertain = waitForOrchestratedChild(stillRunning as never, deps); + signals.emit("SIGINT"); + deadline!(); + expect(await uncertain).toEqual({ confirmed: false, code: null, signal: null }); + expect(signals.listenerCount("SIGINT")).toBe(0); +}); + +test("a signal-killed worker cannot prove its installer stopped", () => { + for (const outcome of [{ phase: "refused" as const, error: "plan-changed" }, { phase: "failed" as const }]) { + expect(classifyOrchestratedOutcome({ ...base, childExitCode: null, outcome })) + .toMatchObject({ exitCode: 12, result: { error: "outcome-unverified" } }); + } +}); + +test("an unconfirmed installer termination is never classified as a safe rollback", () => { + expect(classifyOrchestratedOutcome({ ...base, outcome: { phase: "failed", error: "installer-termination-unconfirmed" } })) + .toMatchObject({ exitCode: 12, result: { error: "installer-termination-unconfirmed", applied: false } }); +}); + +test("explicitly unconfirmed termination overrides previous-state proof for every outcome", () => { + for (const outcome of [ + { phase: "failed", error: "installer-timeout", terminationConfirmed: false }, + { phase: "refused", error: "plan-changed", terminationConfirmed: false }, + { phase: "installed", activeRoot: join(tmpdir(), "fixture"), terminationConfirmed: false }, + ]) { + expect(classifyOrchestratedOutcome({ ...base, outcome: outcome as OutcomeInput["outcome"], targetVerified: true })).toMatchObject({ exitCode: 12 }); + } +}); + +test("exit classification requires confirmed termination and independently verified active state", () => { + expect(classifyOrchestratedOutcome({ ...base, outcome: { phase: "refused", error: "plan-changed" } })).toMatchObject({ exitCode: 10, result: { applied: false, error: "plan-changed", rolledBack: false } }); + expect(classifyOrchestratedOutcome(base)).toMatchObject({ exitCode: 11, result: { applied: false, rolledBack: false } }); + expect(classifyOrchestratedOutcome({ ...base, outcome: { phase: "failed", rollbackPerformed: true } })).toMatchObject({ exitCode: 11, result: { rolledBack: true } }); + expect(classifyOrchestratedOutcome({ ...base, outcome: { phase: "failed", rollbackPerformed: false } })).toMatchObject({ exitCode: 11, result: { rolledBack: false } }); + expect(classifyOrchestratedOutcome({ ...base, previousVerified: false })).toMatchObject({ exitCode: 12 }); + expect(classifyOrchestratedOutcome({ ...base, childExited: false })).toMatchObject({ exitCode: 12 }); + expect(classifyOrchestratedOutcome({ ...base, outcome: null })).toMatchObject({ exitCode: 12 }); + expect(classifyOrchestratedOutcome({ ...base, outcome: { phase: "overrun" } })).toMatchObject({ exitCode: 12 }); + const installed = { phase: "installed" as const, activeRoot: join(tmpdir(), "fixture", "install") }; + expect(classifyOrchestratedOutcome({ ...base, childExitCode: 0, outcome: installed, targetVerified: true })).toMatchObject({ exitCode: 0, result: { applied: true, healthy: true } }); + expect(classifyOrchestratedOutcome({ ...base, childExitCode: 0, outcome: installed, targetVerified: true, runtimeHealthy: false })).toMatchObject({ exitCode: 12, result: { applied: true, healthy: false, error: "runtime-unhealthy" } }); + expect(classifyOrchestratedOutcome({ ...base, childExitCode: 0, outcome: installed, targetVerified: false })).toMatchObject({ exitCode: 12, result: { applied: false, error: "install-unverified" } }); + for (const malformed of [{ phase: "installed" }, { phase: "installed", activeRoot: "" }, { phase: "refused", error: 42 }, { phase: "failed", rollbackPerformed: "yes" }, { phase: "failed", terminationConfirmed: "yes" }]) { + expect(classifyOrchestratedOutcome({ ...base, childExitCode: malformed.phase === "installed" ? 0 : 1, outcome: malformed as OutcomeInput["outcome"], targetVerified: true })).toMatchObject({ exitCode: 12 }); + } +}); + +test.each(["npm", "pnpm", "bun"] as const)("%s verified install remains applied when recovery fails", installer => { + const outcome = { phase: "installed" as const, activeRoot: join(tmpdir(), "fixture", "install") }; + expect(classifyOrchestratedOutcome({ ...base, installer, outcome, childExitCode: 1, targetVerified: true, runtimeHealthy: true })) + .toMatchObject({ exitCode: 12, result: { applied: true, healthy: false, error: "runtime-unhealthy" } }); + expect(classifyOrchestratedOutcome({ ...base, installer, outcome, childExitCode: 1, targetVerified: false })) + .toMatchObject({ exitCode: 12, result: { applied: false, healthy: false, error: "install-unverified" } }); +}); + +test("passive install verification rejects a damaged tree and permits a retained backup", () => { + const parent = mkdtempSync(join(tmpdir(), "ocx-update-tree-")), root = join(parent, "package"); + try { + for (const dir of ["bin", "src/cli", "node_modules/bun/bin", "node_modules/zod"]) mkdirSync(join(root, dir), { recursive: true }); + writeFileSync(join(root, "package.json"), JSON.stringify({ version: "2.1.0", dependencies: { bun: "1", zod: "1" } })); + writeFileSync(join(root, "bin/ocx.mjs"), "x".repeat(1024)); + writeFileSync(join(root, "src/cli/index.ts"), "export {};\n"); + writeFileSync(join(root, "node_modules/bun/package.json"), "{}"); + writeFileSync(join(root, "node_modules/zod/package.json"), "{}"); + const bun = join(root, "node_modules/bun/bin/bun"); + closeSync(openSync(bun, "w")); truncateSync(bun, 10 * 1024 * 1024); + mkdirSync(join(parent, ".ocx-backup-retained")); + expect(verifyOrchestratedInstall(root, "2.1.0", "npm")).toBe(true); + truncateSync(bun, 10); + expect(verifyOrchestratedInstall(root, "2.1.0", "npm")).toBe(false); + truncateSync(bun, 10 * 1024 * 1024); + rmSync(join(root, "src/cli/index.ts")); + expect(verifyOrchestratedInstall(root, "2.1.0", "npm")).toBe(false); + writeFileSync(join(root, "src/cli/index.ts"), "export {};\n"); + rmSync(join(root, "node_modules/zod/package.json")); + expect(verifyOrchestratedInstall(root, "2.1.0", "npm")).toBe(false); + } finally { rmSync(parent, { recursive: true, force: true }); } +}); + +test("pnpm verification re-resolves the pinned owner and checks the active tree and shims", () => { + const home = mkdtempSync(join(tmpdir(), "ocx-orchestrated-pnpm-")); + const globalDir = join(home, "global"), globalRoot = join(globalDir, "v11"), globalBinDir = join(home, "bin"); + const root = join(globalRoot, "node_modules", "@bitkyc08", "opencodex"), commandPath = join(home, "pnpm"); + const owner = { commandPath, packagePath: root, globalDir, globalRoot, globalBinDir }; + try { + for (const dir of [globalBinDir, join(root, "bin"), join(root, "src/cli"), join(root, "node_modules/bun/bin"), join(root, "node_modules/zod")]) mkdirSync(dir, { recursive: true }); + writeFileSync(join(root, "package.json"), JSON.stringify({ version: "2.1.0", dependencies: { bun: "1", zod: "1" } })); + writeFileSync(join(root, "bin/ocx.mjs"), "x".repeat(1024)); + writeFileSync(join(root, "src/cli/index.ts"), "export {};\n"); + writeFileSync(join(root, "node_modules/bun/package.json"), "{}"); + writeFileSync(join(root, "node_modules/zod/package.json"), "{}"); + const bun = join(root, "node_modules/bun/bin/bun"); + closeSync(openSync(bun, "w")); truncateSync(bun, 10 * 1024 * 1024); + const names = process.platform === "win32" ? ["ocx.cmd", "ocx.ps1", "opencodex.cmd", "opencodex.ps1"] : ["ocx", "opencodex"]; + for (const name of names) { const shim = join(globalBinDir, name); writeFileSync(shim, `#!/bin/sh\nexec node '${join(root, "bin/ocx.mjs")}' "$@"\n`); chmodSync(shim, 0o755); } + let listedVersion = "2.1.0", listedGroup = globalRoot; + const runPnpm = (_command: string, args: readonly string[]) => { + if (args[0] === "list") return { status: 0, stdout: JSON.stringify([{ path: listedGroup, dependencies: { "@bitkyc08/opencodex": { path: root, version: listedVersion } } }]) }; + if (args[0] === "root") return { status: 0, stdout: `${listedGroup}\n` }; + if (args[0] === "config" && args[2] === "global-dir") return { status: 0, stdout: `${globalDir}\n` }; + if (args[0] === "config" && args[2] === "global-bin-dir") return { status: 0, stdout: `${globalBinDir}\n` }; + return { status: 1 }; + }; + const options = { owner, activeRoot: root, version: "2.1.0", runPnpm }; + expect(verifyOrchestratedPnpmInstall(options)).toBe(true); + listedVersion = "2.0.0"; expect(verifyOrchestratedPnpmInstall(options)).toBe(false); listedVersion = "2.1.0"; + listedGroup = join(globalDir, "v99"); expect(verifyOrchestratedPnpmInstall(options)).toBe(false); listedGroup = globalRoot; + rmSync(join(root, "src/cli/index.ts")); expect(verifyOrchestratedPnpmInstall(options)).toBe(false); + writeFileSync(join(root, "src/cli/index.ts"), "export {};\n"); + writeFileSync(join(globalBinDir, names[0]!), "#!/bin/sh\nexit 0\n"); expect(verifyOrchestratedPnpmInstall(options)).toBe(false); + } finally { rmSync(home, { recursive: true, force: true }); } +}); diff --git a/tests/update/update-orchestrated-arguments.test.ts b/tests/update/update-orchestrated-arguments.test.ts new file mode 100644 index 00000000000..130982922aa --- /dev/null +++ b/tests/update/update-orchestrated-arguments.test.ts @@ -0,0 +1,34 @@ +import { expect, test } from "bun:test"; +import { isOrchestratedUpdateArgv, parseOrchestratedUpdateArgs, parseOrchestratedChildArgs } from "../../src/update/orchestrated-arguments.mjs"; + +test("internal child flags require the parent environment and an exact pin", () => { + const args = ["--version", "2.1.0", "--orchestrated-expect", "encoded", "--orchestrated-result", "/tmp/result", "--not-after", "123"]; + expect(parseOrchestratedChildArgs(args, {})).toEqual({ ok: false }); + expect(parseOrchestratedChildArgs(args, { OCX_UPDATE_ORCHESTRATED_CHILD: "1" })).toMatchObject({ ok: true, version: "2.1.0", expect: "encoded", resultPath: "/tmp/result", notAfter: 123 }); + for (const invalid of [args.slice(2), [...args, "--tag", "latest"], [...args, "--version", "2.2.0"], args.slice(0, -1)]) { + expect(parseOrchestratedChildArgs(invalid, { OCX_UPDATE_ORCHESTRATED_CHILD: "1" })).toEqual({ ok: false }); + } +}); + +test("orchestrated arguments validate selectors, deadline, and plan binding", () => { + expect(parseOrchestratedUpdateArgs(["--plan", "--json", "--tag", "preview"])).toMatchObject({ ok: true, mode: "plan", tag: "preview" }); + expect(parseOrchestratedUpdateArgs(["--yes", "--json", "--tag", "preview"])).toMatchObject({ ok: true, mode: "apply", tag: "preview" }); + expect(parseOrchestratedUpdateArgs(["--yes", "--json", "--version", "2.1.0-preview.2", "--expect-plan", "A".repeat(43), "--not-after", "123456"])).toMatchObject({ ok: true, mode: "apply", version: "2.1.0-preview.2", notAfter: 123456 }); + for (const args of [ + ["--plan"], ["--yes", "--json", "--plan"], ["--plan", "--json", "--tag", "latest", "--version", "2.0.0"], + ["--plan", "--json", "--version", "01.2.3"], ["--plan", "--json", "--version", "1.2.3-01"], + ["--yes", "--json", "--not-after", "0"], ["--yes", "--json", "--not-after", "9007199254740992"], + ["--yes", "--json", "--expect-plan", "short"], ["--plan", "--json", "--not-after", "5"], + ["--yes", "--json", "--tag", "preview", "--version", "2.1.0"], + ["--plan", "--json", "--tag", "latest", "--tag", "preview"], + ]) expect(parseOrchestratedUpdateArgs(args)).toMatchObject({ ok: false }); +}); + +test("orchestrated or malformed orchestration flags never reach legacy update", () => { + for (const args of [["--plan"], ["--yes"], ["--json"], ["--plan=true"], ["--yes=1"], ["--json=false"], ["--not-after=3"], ["--expect-plan", "token"]]) expect(isOrchestratedUpdateArgv(args)).toBe(true); + expect(isOrchestratedUpdateArgv(["--tag", "latest"])).toBe(false); + for (const args of [["--version", "2.0.0", "--orchestrated-result", "/fixture"], ["--orchestrated-expect", "fixture"], ["--orchestrated-result=/fixture"]]) { + expect(isOrchestratedUpdateArgv(args)).toBe(true); + expect(parseOrchestratedUpdateArgs(args)).toMatchObject({ ok: false }); + } +}); diff --git a/tests/update/update-orchestrated-entry.test.ts b/tests/update/update-orchestrated-entry.test.ts new file mode 100644 index 00000000000..4394816381b --- /dev/null +++ b/tests/update/update-orchestrated-entry.test.ts @@ -0,0 +1,589 @@ +import { expect, test } from "bun:test"; +import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { homedir, tmpdir } from "node:os"; +import { spawnSync } from "node:child_process"; +import { join } from "node:path"; +import { repoPath } from "../helpers/repo-root"; +import { assertNotRealHomeUnderTest } from "../../src/lib/test-home-guard"; +import { encodeOrchestratedExpect } from "../../src/update/orchestrated-session.mjs"; +import { createUpdatePlanToken } from "../../src/update/orchestrated-token.mjs"; +import { inspectUpdateMarker, inspectUpdateSyncMutex, tryAcquireUpdateSyncMutex } from "../../src/update/sync-update-mutex.mjs"; +import { isUpdateInFlight } from "../../src/update/sync-update-mutex"; +import { watch } from "node:fs"; + +// These scenarios run sequentially in one disposable home. Simulate the bound +// passing only after the fixture worker and recorded installer have settled. +function expireFixtureFence(home: string) { + const path = join(home, "update-orchestrated.json"), marker = JSON.parse(readFileSync(path, "utf8")); + expect(["failed", "installed", "refused"]).toContain(marker.phase); + expect(inspectUpdateSyncMutex(home)).toBe("free"); + if (marker.fenceUntil === undefined) { expect(inspectUpdateMarker(home)).toBe("free"); return; } + expect(inspectUpdateMarker(home, { now: () => marker.fenceUntil })).toBe("free"); + marker.fenceUntil = marker.startedAt; + writeFileSync(path, JSON.stringify(marker)); +} + +function expectSyncAdmission(pkg: string, cwd: string, env: Record, admitted: boolean) { + const sync = spawnSync(process.execPath, [join(pkg, "src/cli/index.ts"), "sync", "--local-only", "--expect-link", "lnk_0000000000000000"], + { cwd, env, encoding: "utf8", timeout: 30000 }); + // A disconnected-link refusal is reached only after the update guard admits sync. + expect({ status: sync.status, stderr: sync.stderr }).toMatchObject({ status: admitted ? 5 : 7 }); +} + +test.skipIf(process.platform === "win32")("npm child fences identity, deadline and sync before mutation and installs the pinned version", async () => { + const root = realpathSync.native(mkdtempSync(join(tmpdir(), "ocx-node-pin-"))); + const home = join(root, "home"), pkg = join(root, "lib/node_modules/@bitkyc08/opencodex"), path = join(root, "path"); + const result = join(root, "result.json"), log = join(root, "npm.log"), cache = join(root, "cache"); + mkdirSync(home); mkdirSync(path); mkdirSync(cache); mkdirSync(pkg, { recursive: true }); + try { + cpSync(repoPath("src"), join(pkg, "src"), { recursive: true }); + cpSync(repoPath("bin"), join(pkg, "bin"), { recursive: true }); + const launcher = join(pkg, "bin/ocx.mjs"); + const originalLauncher = readFileSync(launcher, "utf8"); + writeFileSync(launcher, originalLauncher.replace("#!/usr/bin/env node\n", `#!/usr/bin/env node\nif (process.env.OCX_UPDATE_ORCHESTRATED_CHILD === '1' && process.env.OCX_FIXTURE_EXIT_EFFECT) {\n const once = process.once.bind(process);\n process.once = function(event, listener) {\n const result = once(event, listener);\n if (event === 'exit') once('exit', () => {\n const fs = requireFixtureFs;\n const output = process.argv[process.argv.indexOf('--orchestrated-result') + 1];\n if (process.env.OCX_FIXTURE_EXIT_EFFECT === 'missing') fs.unlinkSync(output);\n if (process.env.OCX_FIXTURE_EXIT_EFFECT === 'damage') fs.unlinkSync(process.env.OCX_FIXTURE_PKG + '/src/cli/index.ts');\n });\n return result;\n };\n}\nimport * as requireFixtureFs from 'node:fs';\n`)); + const timedLauncher = readFileSync(launcher, "utf8").replace("import * as requireFixtureFs from 'node:fs';", `import * as requireFixtureFs from 'node:fs'; +if (process.env.OCX_FIXTURE_OVERRUN === '1' && process.argv.includes('--yes')) { + const start = globalThis.setTimeout, clear = globalThis.clearTimeout; + globalThis.setTimeout = (fn, ms, ...args) => { + if (ms < 800000) return start(fn, ms, ...args); + const state = { watcher: null, timer: null }; + state.watcher = requireFixtureFs.watch(process.env.OPENCODEX_HOME, () => { + try { + const marker = JSON.parse(requireFixtureFs.readFileSync(process.env.OPENCODEX_HOME + '/update-orchestrated.json')); + if (marker.phase === 'mutating') { state.watcher.close(); clear(state.timer); fn(...args); } + } catch (error) { + // The marker is published by atomic rename: only absence or a not-yet-JSON read is expected here. + if (error.code !== 'ENOENT' && !(error instanceof SyntaxError)) throw error; + } + }); + state.timer = start(() => { state.watcher.close(); fn(...args); }, 15000); + return state; + }; + globalThis.clearTimeout = handle => { + if (handle && handle.watcher) { handle.watcher.close(); clear(handle.timer); } + else clear(handle); + }; +}`); + const supervisedLauncher = timedLauncher.replace('markerPath: join(configDir(), "update-orchestrated.json"), authorizeMutation:', + 'markerPath: join(configDir(), "update-orchestrated.json"), timeoutMs: process.env.OCX_FIXTURE_TIMEOUT ? 1000 : 180000, authorizeMutation:'); + if (supervisedLauncher === timedLauncher) throw new Error("installer timeout injection point missing"); + writeFileSync(launcher, supervisedLauncher); + const manifest = JSON.parse(readFileSync(repoPath("package.json"), "utf8")); manifest.version = "2.0.0"; + writeFileSync(join(pkg, "package.json"), JSON.stringify(manifest)); + symlinkSync(repoPath("node_modules"), join(pkg, "node_modules")); + writeFileSync(join(home, "config.json"), JSON.stringify({ port: 1 })); + const executable = Bun.which("node"); if (!executable) throw new Error("Node required"); + const node = spawnSync(executable, ["-p", "process.execPath"], { encoding: "utf8" }).stdout.trim(); + if (!node || !node.startsWith("/")) throw new Error("Node executable is not an absolute path"); + writeFileSync(join(path, "npm"), `#!${node}\nconst fs=require('node:fs'), p=require('node:path'), a=process.argv.slice(2);\nfs.appendFileSync(process.env.OCX_FIXTURE_LOG,JSON.stringify({args:a,outcome:JSON.parse(fs.readFileSync(process.env.OCX_FIXTURE_RESULT))})+'\\n');\nif(a[0]==='config') console.log(process.env.OCX_FIXTURE_CACHE);\nelse if(a[0]==='view') console.log(a.includes('dist.integrity')?'sha512-YWJj':(process.env.OCX_FIXTURE_MOVED==='1' && a.some(x=>x.endsWith('@2.1.0'))?'2.2.0':'2.1.0'));\nelse if(a[0]==='install'){const s=a[a.indexOf('--prefix')+1],d=p.join(s,'lib/node_modules/@bitkyc08/opencodex');fs.cpSync(process.env.OCX_FIXTURE_PKG,d,{recursive:true});const m=JSON.parse(fs.readFileSync(p.join(d,'package.json')));m.version='2.1.0';fs.writeFileSync(p.join(d,'package.json'),JSON.stringify(m));if(process.env.OCX_FIXTURE_ROLLBACK==='1'){const l=p.join(d,'bin/ocx.mjs'),t=p.join(s,'temporary-launcher');fs.copyFileSync(l,t);fs.unlinkSync(l);fs.symlinkSync(p.relative(p.dirname(l),t),l);}}\nelse process.exit(90);\n`); + chmodSync(join(path, "npm"), 0o755); + const npmScript = join(path, "npm"), npmSource = readFileSync(npmScript, "utf8"); + const npmTimed = npmSource.replace("const s=a[a.indexOf('--prefix')+1]", "if(process.env.OCX_FIXTURE_TIMEOUT==='1'){const c=require('node:child_process').spawn(process.execPath,['-e','setInterval(()=>{},1000)'],{stdio:'ignore'});fs.writeFileSync(process.env.OCX_FIXTURE_DESCENDANT,String(c.pid));setInterval(()=>{},1000);return;}const s=a[a.indexOf('--prefix')+1]"); + if (npmTimed === npmSource) throw new Error("installer fixture injection point missing"); + writeFileSync(npmScript, npmTimed); + const token = createUpdatePlanToken({ currentVersion: "2.0.0", targetVersion: "2.1.0", installer: "npm", cliRoot: pkg, servingRoot: null, runtimeOwner: "none", runtime: null }); + const env = { ...process.env, HOME: root, USERPROFILE: root, OPENCODEX_HOME: home, CODEX_HOME: join(root, "codex"), + OCX_TEST_HOME_GUARD: "1", OCX_REAL_HOME: process.env.OCX_REAL_HOME ?? homedir(), OCX_UPDATE_ORCHESTRATED_CHILD: "1", + OPENCODEX_BUN_PATH: process.execPath, PATH: path, OCX_FIXTURE_LOG: log, OCX_FIXTURE_CACHE: cache, OCX_FIXTURE_PKG: pkg, OCX_FIXTURE_RESULT: result }; + const backup = join(root, "lib/node_modules/@bitkyc08/.ocx-backup-sync/opencodex"); + mkdirSync(backup, { recursive: true }); + writeFileSync(join(backup, "package.json"), JSON.stringify({ version: "1.9.0" })); + const update = tryAcquireUpdateSyncMutex(home, "update"); + if (update.kind !== "acquired") throw new Error("fixture update mutex unavailable"); + try { + const blockedSync = spawnSync(node, [launcher, "sync", "--local-only"], { cwd: root, env, encoding: "utf8", timeout: 30000 }); + expect({ status: blockedSync.status, stderr: blockedSync.stderr }).toMatchObject({ status: 7, stderr: expect.stringContaining("update-in-flight") }); + expect(existsSync(join(backup, "package.json"))).toBe(true); + expect(JSON.parse(readFileSync(join(pkg, "package.json"), "utf8")).version).toBe("2.0.0"); + } finally { update.release(); } + const run = (planToken: string, deadline?: number, rollback = false) => { + const encoded = encodeOrchestratedExpect({ home, cliRoot: pkg, servingRoot: null, runtimePid: null, planToken }); + const args = [join(pkg, "bin/ocx.mjs"), "update", "--version", "2.1.0", "--orchestrated-expect", encoded, "--orchestrated-result", result]; + if (deadline) args.push("--not-after", String(deadline)); + return spawnSync(node, args, { cwd: root, env: { ...env, OCX_FIXTURE_ROLLBACK: rollback ? "1" : "0" }, encoding: "utf8", timeout: 30000 }); + }; + const encoded = encodeOrchestratedExpect({ home, cliRoot: pkg, servingRoot: null, runtimePid: null, planToken: token }); + const descendant = join(root, "installer-descendant"); + const timeout = spawnSync(node, [launcher, "update", "--version", "2.1.0", "--orchestrated-expect", encoded, "--orchestrated-result", result], { + cwd: root, env: { ...env, OCX_FIXTURE_TIMEOUT: "1", OCX_FIXTURE_DESCENDANT: descendant }, encoding: "utf8", timeout: 30000, + }); + expect({ status: timeout.status, stderr: timeout.stderr }).toMatchObject({ status: 1 }); + expect(JSON.parse(readFileSync(result, "utf8"))).toMatchObject({ phase: "failed", terminationConfirmed: false }); + expect(() => process.kill(Number(readFileSync(descendant, "utf8")), 0)).toThrow(); + expect(isUpdateInFlight(home)).toBe(true); + expectSyncAdmission(pkg, root, env, false); + expireFixtureFence(home); + rmSync(result); rmSync(log); + const unauthorized = spawnSync(node, [join(pkg, "bin/ocx.mjs"), "update", "--version", "2.1.0", "--orchestrated-expect", encoded, "--orchestrated-result", result], { + cwd: root, env: { ...env, OCX_UPDATE_ORCHESTRATED_CHILD: "0" }, encoding: "utf8", timeout: 30000, + }); + expect(unauthorized.status).toBe(64); expect(existsSync(result)).toBe(false); expect(existsSync(log)).toBe(false); + const holder = tryAcquireUpdateSyncMutex(home, "sync"); + expect(holder.kind).toBe("acquired"); + try { expect(run(token).status).toBe(10); expect(JSON.parse(readFileSync(result, "utf8"))).toMatchObject({ phase: "refused", error: "sync-in-progress" }); } + finally { if (holder.kind === "acquired") holder.release(); } + const deadline = run(token, 1); + expect({ status: deadline.status, stderr: deadline.stderr }).toMatchObject({ status: 10 }); + expect(JSON.parse(readFileSync(result, "utf8"))).toMatchObject({ phase: "refused", error: "deadline-passed" }); + const changed = run("a".repeat(43)); + expect({ status: changed.status, stderr: changed.stderr }).toMatchObject({ status: 10 }); + expect(JSON.parse(readFileSync(result, "utf8"))).toMatchObject({ phase: "refused", error: "plan-changed" }); + expect(JSON.parse(readFileSync(join(pkg, "package.json"), "utf8")).version).toBe("2.0.0"); + expect(readFileSync(log, "utf8")).not.toContain('"install"'); + const rolledBack = run(token, undefined, true); + expect({ status: rolledBack.status, stdout: rolledBack.stdout, stderr: rolledBack.stderr }).toMatchObject({ status: 1 }); + expect(JSON.parse(readFileSync(result, "utf8"))).toEqual({ phase: "failed", rollbackPerformed: true }); + expect(JSON.parse(readFileSync(join(pkg, "package.json"), "utf8")).version).toBe("2.0.0"); + expireFixtureFence(home); + const updated = run(token); + expect({ status: updated.status, stdout: updated.stdout, stderr: updated.stderr }).toMatchObject({ status: 0 }); + expect(JSON.parse(readFileSync(result, "utf8"))).toEqual({ phase: "installed", activeRoot: pkg }); + expect(JSON.parse(readFileSync(join(home, "update-orchestrated.json"), "utf8")).fenceUntil).toBeUndefined(); + expect(isUpdateInFlight(home)).toBe(false); + expectSyncAdmission(pkg, root, env, true); + expect(JSON.parse(readFileSync(join(pkg, "package.json"), "utf8")).version).toBe("2.1.0"); + expect(readFileSync(log, "utf8")).toContain("@bitkyc08/opencodex@2.1.0"); + const calls = readFileSync(log, "utf8").trim().split("\n").map(line => JSON.parse(line)); + expect(calls.find(call => call.args[0] === "view").outcome.phase).toBe("preflight"); + expect(calls.some(call => call.args[0] === "view" && call.args.includes("dist.integrity") && call.args.includes("@bitkyc08/opencodex@2.1.0"))).toBe(true); + expect(calls.find(call => call.args[0] === "install").outcome.phase).toBe("mutating"); + expect(calls.find(call => call.args[0] === "install").args).toContain("@bitkyc08/opencodex@2.1.0"); + const installs = calls.filter(call => call.args[0] === "install").length; + expireFixtureFence(home); + const current = run(token); + expect({ status: current.status, stderr: current.stderr }).toMatchObject({ status: 0 }); + expect(JSON.parse(readFileSync(result, "utf8"))).toEqual({ phase: "preflight" }); + expect(readFileSync(log, "utf8").trim().split("\n").map(line => JSON.parse(line)).filter(call => call.args[0] === "install")).toHaveLength(installs); + const restored = JSON.parse(readFileSync(join(pkg, "package.json"), "utf8")); restored.version = "2.0.0"; + writeFileSync(join(pkg, "package.json"), JSON.stringify(restored)); + const parentArgs = [join(pkg, "bin/ocx.mjs"), "update", "--yes", "--json", "--tag", "preview"]; + const parentEnv = { ...env, OCX_UPDATE_ORCHESTRATED_CHILD: "0" }; + const parent = (extraEnv = {}) => spawnSync(node, parentArgs, { cwd: root, env: { ...parentEnv, ...extraEnv }, encoding: "utf8", timeout: 30000 }); + const parentTimeout = parent({ OCX_FIXTURE_TIMEOUT: "1", OCX_FIXTURE_DESCENDANT: descendant }); + expect({ status: parentTimeout.status, stderr: parentTimeout.stderr }).toMatchObject({ status: 12 }); + expect(JSON.parse(parentTimeout.stdout)).toMatchObject({ applied: false, error: "installer-termination-unconfirmed" }); + expect(isUpdateInFlight(home)).toBe(true); + expireFixtureFence(home); + const sync = tryAcquireUpdateSyncMutex(home, "sync"); + expect(sync.kind).toBe("acquired"); + try { const blocked = parent(); expect(blocked.status).toBe(10); expect(JSON.parse(blocked.stdout).error).toBe("sync-in-progress"); } + finally { if (sync.kind === "acquired") sync.release(); } + const parentRollback = parent({ OCX_FIXTURE_ROLLBACK: "1" }); + expect({ status: parentRollback.status, stderr: parentRollback.stderr }).toMatchObject({ status: 11 }); + expect(JSON.parse(parentRollback.stdout)).toMatchObject({ rolledBack: true, applied: false }); + expireFixtureFence(home); + const parentApplied = parent({ OCX_FIXTURE_MOVED: "1" }); + expect({ status: parentApplied.status, stderr: parentApplied.stderr }).toMatchObject({ status: 0 }); + expect(JSON.parse(parentApplied.stdout)).toMatchObject({ applied: true, toVersion: "2.1.0" }); + expect(readFileSync(log, "utf8")).toContain("@bitkyc08/opencodex@2.1.0"); + expect(readFileSync(log, "utf8")).toContain("@bitkyc08/opencodex@preview"); + expireFixtureFence(home); + const resetVersion = () => { + const m = JSON.parse(readFileSync(join(pkg, "package.json"), "utf8")); m.version = "2.0.0"; + writeFileSync(join(pkg, "package.json"), JSON.stringify(m)); + }; + resetVersion(); + const overrun = spawnSync(node, parentArgs, { cwd: root, env: { ...parentEnv, OCX_FIXTURE_OVERRUN: "1" }, + encoding: "utf8", timeout: 30000, stdio: ["ignore", "pipe", "ignore"] }); + expect(overrun.status).toBe(12); + expect(JSON.parse(overrun.stdout).error).toBe("overrun"); + const marker = JSON.parse(readFileSync(join(home, "update-orchestrated.json"), "utf8")); + expect(marker.phase).toBe("mutating"); + expect(() => process.kill(marker.pid, 0)).not.toThrow(); + expect(isUpdateInFlight(home)).toBe(true); + await new Promise((resolveDone, rejectDone) => { + const timer = setTimeout(() => { observer.close(); rejectDone(new Error("fixture child did not finish")); }, 30000); + const check = () => { + const current = JSON.parse(readFileSync(join(home, "update-orchestrated.json"), "utf8")); + if (["installed", "failed", "refused"].includes(current.phase) && inspectUpdateSyncMutex(home) === "free") { + clearTimeout(timer); observer.close(); resolveDone(); + } + }; + const observer = watch(home, check); + check(); + }); + expireFixtureFence(home); + resetVersion(); + const missing = parent({ OCX_FIXTURE_EXIT_EFFECT: "missing" }); + expect({ status: missing.status, stderr: missing.stderr }).toMatchObject({ status: 12 }); + expect(JSON.parse(missing.stdout).error).toBe("outcome-unverified"); + expireFixtureFence(home); + resetVersion(); + const damaged = parent({ OCX_FIXTURE_EXIT_EFFECT: "damage" }); + expect({ status: damaged.status, stderr: damaged.stderr }).toMatchObject({ status: 12 }); + expect(JSON.parse(damaged.stdout)).toMatchObject({ error: "install-unverified", applied: false }); + } finally { rmSync(root, { recursive: true, force: true }); } +}, 90000); + +test.skipIf(process.platform === "win32")("pnpm child reports unchanged active tree without rollback and installs the pinned version", () => { + const root = realpathSync.native(mkdtempSync(join(tmpdir(), "ocx-pnpm-child-"))); + const home = join(root, "home"), group = join(root, "global/v11"), bin = join(root, "bin"); + const pkg = join(group, "node_modules/@bitkyc08/opencodex"), result = join(root, "result.json"), log = join(root, "pnpm.log"); + mkdirSync(home); mkdirSync(bin); mkdirSync(pkg, { recursive: true }); + try { + cpSync(repoPath("src"), join(pkg, "src"), { recursive: true }); cpSync(repoPath("bin"), join(pkg, "bin"), { recursive: true }); + const manifest = JSON.parse(readFileSync(repoPath("package.json"), "utf8")); manifest.version = "2.0.0"; + writeFileSync(join(pkg, "package.json"), JSON.stringify(manifest)); symlinkSync(repoPath("node_modules"), join(pkg, "node_modules")); + writeFileSync(join(group, "node_modules/.modules.yaml"), "layoutVersion: 5\n"); + writeFileSync(join(home, "config.json"), JSON.stringify({ port: 1 })); + const executable = Bun.which("node"); if (!executable) throw new Error("Node required"); + const node = spawnSync(executable, ["-p", "process.execPath"], { encoding: "utf8" }).stdout.trim(); + if (!node || !node.startsWith("/")) throw new Error("Node executable is not an absolute path"); + for (const name of ["ocx", "opencodex"]) { writeFileSync(join(bin, name), `#!/bin/sh\nexec '${node}' '${pkg}/bin/ocx.mjs' "$@"\n`); chmodSync(join(bin, name), 0o755); } + writeFileSync(join(bin, "pnpm"), `#!${node}\nconst fs=require('node:fs'),p=require('node:path'),a=process.argv.slice(2),e=process.env;\nfs.appendFileSync(e.OCX_FIXTURE_LOG,JSON.stringify({args:a,outcome:JSON.parse(fs.readFileSync(e.OCX_FIXTURE_RESULT)),mutex:fs.existsSync(p.join(e.OPENCODEX_HOME,'sync-update.mutation.lock'))})+'\\n');\nconst m=JSON.parse(fs.readFileSync(p.join(e.OCX_FIXTURE_PKG,'package.json')));\nif(a[0]==='list') console.log(JSON.stringify([{path:e.OCX_FIXTURE_GROUP,dependencies:{'@bitkyc08/opencodex':{version:m.version,path:e.OCX_FIXTURE_PKG}}}]));\nelse if(a[0]==='root') console.log(e.OCX_FIXTURE_GROUP+'/node_modules');\nelse if(a[0]==='config') console.log(a[2]==='global-dir'?p.dirname(e.OCX_FIXTURE_GROUP):e.OCX_FIXTURE_BIN);\nelse if(a[0]==='view') console.log(a.includes('dist.integrity')?'sha512-YWJj':'2.1.0');\nelse if(a[0]==='add'){if(e.OCX_FIXTURE_FAIL==='1')process.exit(1);m.version='2.1.0';fs.writeFileSync(p.join(e.OCX_FIXTURE_PKG,'package.json'),JSON.stringify(m));}\nelse process.exit(90);\n`); chmodSync(join(bin, "pnpm"), 0o755); + const token = createUpdatePlanToken({ currentVersion: "2.0.0", targetVersion: "2.1.0", installer: "pnpm", cliRoot: pkg, servingRoot: null, runtimeOwner: "none", runtime: null }); + const encoded = encodeOrchestratedExpect({ home, cliRoot: pkg, servingRoot: null, runtimePid: null, planToken: token }); + const args = [join(pkg, "bin/ocx.mjs"), "update", "--version", "2.1.0", "--orchestrated-expect", encoded, "--orchestrated-result", result]; + const env = { ...process.env, HOME: root, USERPROFILE: root, OPENCODEX_HOME: home, CODEX_HOME: join(root, "codex"), + OCX_TEST_HOME_GUARD: "1", OCX_REAL_HOME: process.env.OCX_REAL_HOME ?? homedir(), OCX_UPDATE_ORCHESTRATED_CHILD: "1", OPENCODEX_BUN_PATH: process.execPath, + PATH: bin, OCX_FIXTURE_LOG: log, OCX_FIXTURE_PKG: pkg, OCX_FIXTURE_GROUP: group, OCX_FIXTURE_BIN: bin, OCX_FIXTURE_RESULT: result }; + const failed = spawnSync(node, args, { cwd: root, env: { ...env, OCX_FIXTURE_FAIL: "1" }, encoding: "utf8", timeout: 30000 }); + expect({ status: failed.status, stdout: failed.stdout, stderr: failed.stderr }).toMatchObject({ status: 1 }); + expect(JSON.parse(readFileSync(result, "utf8"))).toEqual({ phase: "failed", rollbackPerformed: false }); + expect(JSON.parse(readFileSync(join(pkg, "package.json"), "utf8")).version).toBe("2.0.0"); + expireFixtureFence(home); + const updated = spawnSync(node, args, { cwd: root, env, encoding: "utf8", timeout: 30000 }); + expect({ status: updated.status, stdout: updated.stdout, stderr: updated.stderr }).toMatchObject({ status: 0 }); + expect(JSON.parse(readFileSync(result, "utf8"))).toEqual({ phase: "installed", activeRoot: pkg }); + expect(JSON.parse(readFileSync(join(home, "update-orchestrated.json"), "utf8")).fenceUntil).toBeUndefined(); + expect(isUpdateInFlight(home)).toBe(false); + expectSyncAdmission(pkg, root, env, true); + expect(readFileSync(log, "utf8")).toContain("@bitkyc08/opencodex@2.1.0"); + const calls = readFileSync(log, "utf8").trim().split("\n").map(line => JSON.parse(line)); + expect(calls.find(call => call.args[0] === "list").outcome.phase).toBe("preflight"); + expect(calls.find(call => call.args[0] === "add")).toMatchObject({ outcome: { phase: "mutating" }, mutex: true }); + expect(calls.some(call => call.args[0] === "view" && call.args.includes("dist.integrity") && call.args.includes("@bitkyc08/opencodex@2.1.0"))).toBe(true); + expect(calls.find(call => call.args[0] === "add").args).toContain("@bitkyc08/opencodex@2.1.0"); + expireFixtureFence(home); + const restored = JSON.parse(readFileSync(join(pkg, "package.json"), "utf8")); restored.version = "2.0.0"; + writeFileSync(join(pkg, "package.json"), JSON.stringify(restored)); + const parentArgs = [join(pkg, "bin/ocx.mjs"), "update", "--yes", "--json"]; + const parentEnv = { ...env, OCX_UPDATE_ORCHESTRATED_CHILD: "0" }; + const parent = (extraEnv = {}) => spawnSync(node, parentArgs, { cwd: root, env: { ...parentEnv, ...extraEnv }, encoding: "utf8", timeout: 30000 }); + const unchanged = parent({ OCX_FIXTURE_FAIL: "1" }); + expect({ status: unchanged.status, stderr: unchanged.stderr }).toMatchObject({ status: 11 }); + expect(JSON.parse(unchanged.stdout)).toMatchObject({ rolledBack: false, applied: false }); + expireFixtureFence(home); + const parentApplied = parent(); + expect({ status: parentApplied.status, stderr: parentApplied.stderr }).toMatchObject({ status: 0 }); + expect(JSON.parse(parentApplied.stdout)).toMatchObject({ applied: true, toVersion: "2.1.0" }); + } finally { rmSync(root, { recursive: true, force: true }); } +}, 90000); + +test.skipIf(process.platform === "win32")("identity probe is passive through both Node and Bun entrypoints", () => { + const root = mkdtempSync(join(tmpdir(), "ocx-identity-probe-")); + const home = join(root, "home"), pkg = join(root, "node_modules/@bitkyc08/opencodex"); + mkdirSync(home); mkdirSync(pkg, { recursive: true }); + try { + cpSync(repoPath("src"), join(pkg, "src"), { recursive: true }); + cpSync(repoPath("bin"), join(pkg, "bin"), { recursive: true }); + cpSync(repoPath("package.json"), join(pkg, "package.json")); + symlinkSync(repoPath("node_modules"), join(pkg, "node_modules")); + writeFileSync(join(home, "config.json"), JSON.stringify({ port: 1 })); + const backup = join(root, "node_modules/@bitkyc08/.ocx-backup-fixture/opencodex"); + mkdirSync(backup, { recursive: true }); writeFileSync(join(backup, "keep"), "backup"); + mkdirSync(join(root, ".opencodex-desktop")); + writeFileSync(join(root, ".opencodex-desktop/cli.json"), "malformed desktop record"); + const executable = Bun.which("node"); if (!executable) throw new Error("Node required"); + const node = spawnSync(executable, ["-p", "process.execPath"], { encoding: "utf8" }).stdout.trim(); + const env = { ...process.env, HOME: root, USERPROFILE: root, OPENCODEX_HOME: home, CODEX_HOME: join(root, "codex"), + OCX_TEST_HOME_GUARD: "1", OCX_REAL_HOME: process.env.OCX_REAL_HOME ?? homedir(), OPENCODEX_BUN_PATH: process.execPath, + OPENCODEX_CODEX_SHIM_AUTO_RESTORE: "1", PATH: root }; + for (const [bin, entry] of [[node, join(pkg, "bin/ocx.mjs")], [process.execPath, join(pkg, "src/cli/index.ts")]]) { + const result = spawnSync(bin!, [entry!, "__update-orchestrated-identity"], { cwd: root, env, encoding: "utf8", timeout: 15000 }); + expect({ status: result.status, stderr: result.stderr }).toMatchObject({ status: 0 }); + expect(JSON.parse(result.stdout)).toMatchObject({ kind: "absent", cliRoot: realpathSync.native(pkg) }); + } + expect(readdirSync(home)).toEqual(["config.json"]); + expect(readFileSync(join(backup, "keep"), "utf8")).toBe("backup"); + const missing = join(root, "missing/node_modules/@bitkyc08/opencodex"); + mkdirSync(join(missing, "bin"), { recursive: true }); mkdirSync(join(missing, "node_modules/bun"), { recursive: true }); + cpSync(repoPath("bin/ocx.mjs"), join(missing, "bin/ocx.mjs")); symlinkSync(repoPath("src"), join(missing, "src")); + writeFileSync(join(missing, "package.json"), JSON.stringify({ name: "@bitkyc08/opencodex", version: "2.0.0" })); + writeFileSync(join(missing, "node_modules/bun/package.json"), JSON.stringify({ name: "bun", version: "1.0.0" })); + writeFileSync(join(missing, "node_modules/bun/install.js"), `require('node:fs').writeFileSync(${JSON.stringify(join(root, "bun-installed"))},'bad')`); + const noBun = spawnSync(node, [join(missing, "bin/ocx.mjs"), "__update-orchestrated-identity"], { + cwd: root, env: { ...env, OPENCODEX_BUN_PATH: "" }, encoding: "utf8", timeout: 15000, + }); + expect(noBun.status).not.toBe(0); + expect(existsSync(join(root, "bun-installed"))).toBe(false); + } finally { rmSync(root, { recursive: true, force: true }); } +}, 40000); + +test.skipIf(process.platform === "win32")("authorized npm launcher child writes a preflight outcome before package checks", () => { + const root = mkdtempSync(join(tmpdir(), "ocx-node-child-")); + const home = join(root, "home"), pkg = join(root, "node_modules/@bitkyc08/opencodex"); + const result = join(root, "result.json"); + try { + mkdirSync(home); mkdirSync(join(pkg, "bin"), { recursive: true }); + cpSync(repoPath("bin/ocx.mjs"), join(pkg, "bin/ocx.mjs")); + symlinkSync(repoPath("src"), join(pkg, "src")); + writeFileSync(join(pkg, "package.json"), JSON.stringify({ name: "@bitkyc08/opencodex", version: "2.0.0", type: "module" })); + const node = Bun.spawnSync(["node", "-p", "process.execPath"], { stdout: "pipe" }).stdout.toString().trim(); + const expected = encodeOrchestratedExpect({ home, cliRoot: pkg, servingRoot: null, runtimePid: null, planToken: "a".repeat(43) }); + const child = spawnSync(node, [join(pkg, "bin/ocx.mjs"), "update", "--version", "2.1.0", "--orchestrated-expect", expected, "--orchestrated-result", result], { + cwd: root, encoding: "utf8", timeout: 30000, + env: { ...process.env, HOME: root, USERPROFILE: root, OPENCODEX_HOME: home, CODEX_HOME: join(root, "codex"), + OCX_TEST_HOME_GUARD: "1", OCX_REAL_HOME: process.env.OCX_REAL_HOME ?? homedir(), OCX_UPDATE_ORCHESTRATED_CHILD: "1", PATH: root }, + }); + expect(child.status).not.toBe(64); + expect(JSON.parse(readFileSync(result, "utf8"))).toMatchObject({ phase: "preflight" }); + } finally { rmSync(root, { recursive: true, force: true }); } +}, 35000); + +test("authorized child reaches Bun update preflight while internal flags without authorization are rejected", async () => { + const root = mkdtempSync(join(tmpdir(), "ocx-child-entry-")); + const home = join(root, "home"), codex = join(root, "codex"), result = join(root, "result.json"); + mkdirSync(home); mkdirSync(codex); assertNotRealHomeUnderTest(home); + const expectValue = encodeOrchestratedExpect({ home, cliRoot: repoPath(), servingRoot: null, runtimePid: null, planToken: "a".repeat(43) }); + const args = ["update", "--version", "99.0.0", "--orchestrated-expect", expectValue, "--orchestrated-result", result]; + const run = async (authorized: boolean) => { + const proc = Bun.spawn([process.execPath, repoPath("src/cli/index.ts"), ...args], { cwd: root, stdout: "pipe", stderr: "pipe", + env: { ...process.env, HOME: root, USERPROFILE: root, OPENCODEX_HOME: home, CODEX_HOME: codex, + OCX_TEST_HOME_GUARD: "1", OCX_REAL_HOME: process.env.OCX_REAL_HOME ?? homedir(), + OCX_UPDATE_ORCHESTRATED_CHILD: authorized ? "1" : "0" } }); + return { stdout: await new Response(proc.stdout).text(), stderr: await new Response(proc.stderr).text(), code: await proc.exited }; + }; + try { + const rejected = await run(false); + expect(rejected.code).toBe(64); expect(JSON.parse(rejected.stdout)).toEqual({ error: "usage" }); expect(existsSync(result)).toBe(false); + const child = await run(true); + expect(child.code).toBe(1); + expect(JSON.parse(readFileSync(result, "utf8"))).toEqual({ phase: "preflight" }); + expect(JSON.parse(readFileSync(join(home, "update-orchestrated.json"), "utf8")).phase).toBe("failed"); + } finally { rmSync(root, { recursive: true, force: true }); } +}, 30000); + +test.skipIf(process.platform === "win32")("Bun-global apply runs the real child with the plan's exact target", async () => { + const root = mkdtempSync(join(tmpdir(), "ocx-bun-global-")); + const home = join(root, "home"), ocxHome = join(home, ".opencodex"), path = join(root, "path"); + const pkg = join(home, ".bun/install/global/node_modules/@bitkyc08/opencodex"), log = join(root, "commands"); + mkdirSync(pkg, { recursive: true }); mkdirSync(ocxHome, { recursive: true }); mkdirSync(path); + writeFileSync(join(ocxHome, "config.json"), JSON.stringify({ port: 1, hostname: "127.0.0.1" })); + cpSync(repoPath("src"), join(pkg, "src"), { recursive: true }); + cpSync(repoPath("bin"), join(pkg, "bin"), { recursive: true }); + const manifest = JSON.parse(readFileSync(repoPath("package.json"), "utf8")); manifest.version = "2.0.0"; + writeFileSync(join(pkg, "package.json"), JSON.stringify(manifest)); + symlinkSync(repoPath("node_modules"), join(pkg, "node_modules")); + writeFileSync(join(path, "npm"), `#!/bin/sh\nprintf '%s\\n' "$*" >> "$OCX_FIXTURE_LOG"\ncase "$*" in *dist.integrity*) printf 'sha512-YWJj\\n';; *) if [ -e "$OCX_FIXTURE_PKG/tag-queried" ]; then printf '2.2.0\\n'; else : > "$OCX_FIXTURE_PKG/tag-queried"; printf '2.1.0\\n'; fi;; esac\n`); + chmodSync(join(path, "npm"), 0o755); + writeFileSync(join(path, "bun"), `#!/bin/sh\nprintf '%s\\n' "$*" >> "$OCX_FIXTURE_LOG"\nexec '${process.execPath}' -e 'const fs=require("node:fs"),root=process.env.OCX_FIXTURE_PKG;fs.writeFileSync(root+"/installer-ready","");const end=Date.now()+10000;const t=setInterval(()=>{if(!fs.existsSync(root+"/installer-release") && Date.now() true), Bun.sleep(15000).then(() => false)]); + if (!ended) throw new Error(`test worker did not exit; retained ${root}`); + } + rmSync(root, { recursive: true, force: true }); + } +}, 60000); + +test("a source checkout update plan emits one JSON refusal in a temporary home", async () => { + const root = mkdtempSync(join(tmpdir(), "ocx-update-entry-")); + const home = join(root, "ocx"), codex = join(root, "codex"); + mkdirSync(home); mkdirSync(codex); assertNotRealHomeUnderTest(home); + writeFileSync(join(home, "config.json"), JSON.stringify({ port: 1 })); + const proc = Bun.spawn([process.execPath, repoPath("src/cli/index.ts"), "update", "--plan", "--json"], { + cwd: root, stdout: "pipe", stderr: "pipe", + env: { ...process.env, HOME: root, USERPROFILE: root, OPENCODEX_HOME: home, CODEX_HOME: codex, + CODEX_SQLITE_HOME: codex, CLAUDE_CONFIG_DIR: join(root, "claude"), OCX_REAL_HOME: process.env.OCX_REAL_HOME ?? homedir(), OCX_TEST_HOME_GUARD: "1" }, + }); + try { + const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]); + expect(code).toBe(0); + expect(JSON.parse(stdout)).toMatchObject({ schema: "ocx.update.plan/1", installer: "source", canApply: false, reason: "source-checkout", updateInFlight: false }); + expect(stderr).not.toContain("shim repair"); + writeFileSync(join(home, "update-orchestrated.json"), JSON.stringify({ pid: process.pid, phase: "mutating", startedAt: Date.now() })); + const active = Bun.spawn([process.execPath, repoPath("src/cli/index.ts"), "update", "--plan", "--json"], { + cwd: root, stdout: "pipe", stderr: "pipe", + env: { ...process.env, HOME: root, USERPROFILE: root, OPENCODEX_HOME: home, CODEX_HOME: codex, + CODEX_SQLITE_HOME: codex, CLAUDE_CONFIG_DIR: join(root, "claude"), OCX_REAL_HOME: process.env.OCX_REAL_HOME ?? homedir(), OCX_TEST_HOME_GUARD: "1" }, + }); + const [activeOutput, activeError, activeCode] = await Promise.all([new Response(active.stdout).text(), new Response(active.stderr).text(), active.exited]); + expect(activeCode).toBe(0); + expect(activeError).not.toContain("shim repair"); + expect(JSON.parse(activeOutput).updateInFlight).toBe(true); + } finally { rmSync(root, { recursive: true, force: true }); } +}, 30000); + +test.skipIf(process.platform === "win32")("npm-shaped launcher plans without repair or Desktop handoff, including missing Bun", async () => { + const root = mkdtempSync(join(tmpdir(), "ocx-plan-launcher-")); + const home = join(root, "home"), ocxHome = join(home, ".opencodex"), path = join(root, "path"); + const pkg = join(root, "lib", "node_modules", "@bitkyc08", "opencodex"); + const backup = join(root, "lib", "node_modules", "@bitkyc08", ".ocx-backup-123", "opencodex"); + const npmLog = join(root, "npm-log"); + const envLog = join(root, "npm-env"); + mkdirSync(pkg, { recursive: true }); mkdirSync(ocxHome, { recursive: true }); mkdirSync(path); mkdirSync(backup, { recursive: true }); + mkdirSync(join(home, ".opencodex-desktop"), { recursive: true }); + writeFileSync(join(home, ".opencodex-desktop", "cli.json"), JSON.stringify({ version: 1, enabled: true, bundle: { platform: process.platform, kind: process.platform === "darwin" ? "macos-app" : "linux-deb", cliExecutable: join(root, "no-desktop") } })); + writeFileSync(join(backup, "keep"), "backup"); + mkdirSync(join(ocxHome, "codex-shim.json")); + writeFileSync(join(ocxHome, "config.json"), JSON.stringify({ port: 1 })); + cpSync(repoPath("src"), join(pkg, "src"), { recursive: true }); + cpSync(repoPath("bin"), join(pkg, "bin"), { recursive: true }); + cpSync(repoPath("package.json"), join(pkg, "package.json")); + mkdirSync(join(pkg, "node_modules")); + for (const name of readdirSync(repoPath("node_modules"))) { + if (name !== "bun") symlinkSync(repoPath("node_modules", name), join(pkg, "node_modules", name)); + } + symlinkSync(repoPath("node_modules", "bun"), join(pkg, "node_modules", "bun")); + writeFileSync(join(path, "npm"), `#!/bin/sh\nprintf '%s\\n' "$*" >> '${npmLog}'\nprintf '%s|%s|%s|%s|%s|%s\\n' "$npm_config_cache" "$npm_config_logs_dir" "$npm_config_logs_max" "$npm_config_update_notifier" "$pnpm_config_cache_dir" "$BUN_INSTALL_CACHE_DIR" >> '${envLog}'\n/bin/mkdir -p "$npm_config_cache"\n: > "$npm_config_cache/probe-write"\n[ "$1" = view ] || exit 1\nprintf '99.0.0\\n'\n`); chmodSync(join(path, "npm"), 0o755); + const nodeCommand = Bun.which("node"); if (!nodeCommand) throw Error("Node required"); + const node = spawnSync(nodeCommand, ["-p", "process.execPath"], { encoding: "utf8" }).stdout.trim(); + if (!node) throw Error("Node executable could not be resolved"); + const env = { ...process.env, HOME: home, USERPROFILE: home, OPENCODEX_HOME: ocxHome, CODEX_HOME: join(home, ".codex"), + CLAUDE_CONFIG_DIR: join(home, ".claude"), PATH: path, npm_config_cache: join(home, "user-cache"), OPENCODEX_BUN_PATH: "", OCX_TEST_HOME_GUARD: "1", OCX_REAL_HOME: process.env.OCX_REAL_HOME ?? homedir(), OPENCODEX_CODEX_SHIM_AUTO_RESTORE: "1" }; + const launch = async (args = ["--plan", "--json", "--version", "99.0.0"]) => { + const child = Bun.spawn([node, join(pkg, "bin", "ocx.mjs"), "update", ...args], { cwd: root, env, stdout: "pipe", stderr: "pipe" }); + return { stdout: await new Response(child.stdout).text(), stderr: await new Response(child.stderr).text(), code: await child.exited }; + }; + try { + for (const [executable, entry] of [[node, join(pkg, "bin/ocx.mjs")], [process.execPath, join(pkg, "src/cli/index.ts")]]) { + for (const args of [["--plan=true"], ["--plan=true", "--json=true"], ["--yes=1", "--json"], ["--json=false"]]) { + const child = Bun.spawn([executable!, entry!, "update", ...args], { cwd: root, env, stdout: "pipe", stderr: "pipe" }); + const [stdout, code] = await Promise.all([new Response(child.stdout).text(), child.exited]); + expect({ args, code }).toEqual({ args, code: 64 }); + expect(JSON.parse(stdout)).toEqual({ error: "usage" }); + expect(existsSync(npmLog)).toBe(false); + expect(readFileSync(join(backup, "keep"), "utf8")).toBe("backup"); + expect(existsSync(join(ocxHome, "update-orchestrated.json"))).toBe(false); + expect(existsSync(join(ocxHome, "codex-shim.json"))).toBe(true); + } + } + const first = await launch(); + const [cache, logs, logsMax, notifier, pnpmCache, bunCache] = readFileSync(envLog, "utf8").trim().split("|"); + expect(cache).toBeTruthy(); expect(cache!.startsWith(home)).toBe(false); + expect(logs!.startsWith(cache!)).toBe(true); expect(logsMax).toBe("0"); expect(notifier).toBe("false"); + expect(pnpmCache!.startsWith(cache!)).toBe(true); expect(bunCache!.startsWith(cache!)).toBe(true); + expect(existsSync(cache!)).toBe(false); expect(existsSync(join(home, "user-cache"))).toBe(false); + expect({ code: first.code, stderr: first.stderr }).toMatchObject({ code: 0 }); + expect({ stderr: first.stderr, npmLog: existsSync(npmLog) ? readFileSync(npmLog, "utf8") : "missing" }).toMatchObject({ npmLog: expect.stringContaining("@bitkyc08/opencodex@99.0.0") }); + expect(first.stderr).not.toContain("auto-restore"); + expect(JSON.parse(first.stdout)).toMatchObject({ installer: "npm", targetVersion: "99.0.0", canApply: true }); + const mismatch = await launch(["--yes", "--json", "--version", "99.0.0", "--expect-plan", "a".repeat(43)]); + expect(mismatch.code).toBe(10); + expect(JSON.parse(mismatch.stdout)).toMatchObject({ error: "plan-changed" }); + const deadline = await launch(["--yes", "--json", "--version", "99.0.0", "--not-after", "1"]); + expect(deadline.code).toBe(10); + expect(JSON.parse(deadline.stdout)).toMatchObject({ error: "deadline-passed" }); + const apply = await launch(["--yes", "--json", "--version", "99.0.0"]); + expect(apply.stderr).toContain("opencodex v"); + expect(JSON.parse(apply.stdout).error).not.toBe("plan-unavailable"); + expect(readFileSync(npmLog, "utf8")).toContain("@bitkyc08/opencodex@99.0.0"); + const entry = join(pkg, "src/cli/index.ts"), originalEntry = readFileSync(entry, "utf8"); + for (const invalidPlan of ["console.log('not json')", "process.stdout.write('x'.repeat(65537))", "process.exit(1)"]) { + writeFileSync(entry, invalidPlan); + const invalid = await launch(["--yes", "--json", "--version", "99.0.0"]); + expect(invalid.code).toBe(10); + expect(JSON.parse(invalid.stdout)).toMatchObject({ error: "plan-unavailable", applied: false }); + } + writeFileSync(entry, originalEntry); + rmSync(join(pkg, "node_modules", "bun")); + const missing = await launch(); + expect(missing.code).toBe(0); + expect(JSON.parse(missing.stdout)).toMatchObject({ installer: "npm", reason: "plan-unavailable", canApply: false }); + const missingApply = await launch(["--yes", "--json", "--version", "99.0.0"]); + expect(missingApply.code).toBe(10); + expect(JSON.parse(missingApply.stdout)).toMatchObject({ error: "plan-unavailable", applied: false }); + const bunDir = join(pkg, "node_modules", "bun"), installed = join(root, "unexpected-bun-install"); + mkdirSync(bunDir); writeFileSync(join(bunDir, "package.json"), JSON.stringify({ name: "bun", version: "1.4.4" })); + writeFileSync(join(bunDir, "install.js"), `require('node:fs').writeFileSync(${JSON.stringify(installed)},'unexpected')`); + const sync = spawnSync(node, [join(pkg, "bin/ocx.mjs"), "sync", "--local-only"], { cwd: root, env: { ...env, OCX_NO_DESKTOP_HANDOFF: "1" }, encoding: "utf8", timeout: 30000 }); + expect({ status: sync.status, stderr: sync.stderr }).toMatchObject({ status: 1, stderr: expect.stringContaining("Bun is unavailable") }); + expect(existsSync(installed)).toBe(false); + expect(readFileSync(join(backup, "keep"), "utf8")).toBe("backup"); + expect(missing.stderr).not.toContain("auto-restore"); + } finally { rmSync(root, { recursive: true, force: true }); } +}, 30000); + +test("the Node launcher classifies orchestration before package-manager update and boot recovery", () => { + const source = readFileSync(repoPath("bin/ocx.mjs"), "utf8"); + const classification = source.indexOf("const orchestratedUpdate ="); + expect(classification).toBeGreaterThan(-1); + expect(classification).toBeLessThan(source.indexOf('process.argv[2] === "update" && installMethod === "mise"')); + expect(classification).toBeLessThan(source.indexOf('const probe = bootRestoreProbe(')); +}); + +test("malformed and unsupported internal orchestration is rejected before legacy update", async () => { + const root = mkdtempSync(join(tmpdir(), "ocx-update-help-")); + const home = join(root, "ocx"), codex = join(root, "codex"); + mkdirSync(home); mkdirSync(codex); assertNotRealHomeUnderTest(home); + const node = Bun.which("node"); + if (!node) throw new Error("Node is required to test the published launcher"); + try { + for (const [executable, entry] of [[node, repoPath("bin/ocx.mjs")], [process.execPath, repoPath("src/cli/index.ts")]]) { + for (const args of [["--plan", "--json", "--help"], ["--version", "99.0.0", "--orchestrated-result", join(root, "result.json")]]) { + const proc = Bun.spawn([executable!, entry!, "update", ...args], { + cwd: root, stdout: "pipe", stderr: "pipe", + env: { ...process.env, HOME: root, USERPROFILE: root, OPENCODEX_HOME: home, CODEX_HOME: codex, + OCX_REAL_HOME: process.env.OCX_REAL_HOME ?? homedir(), OCX_TEST_HOME_GUARD: "1" }, + }); + const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]); + expect(code).toBe(64); + expect(JSON.parse(stdout)).toEqual({ error: "usage" }); + expect(stderr).toContain("Usage:"); + expect(existsSync(join(root, "result.json"))).toBe(false); + } + } + } finally { rmSync(root, { recursive: true, force: true }); } +}, 30000); diff --git a/tests/update/update-orchestrated-identity.test.ts b/tests/update/update-orchestrated-identity.test.ts new file mode 100644 index 00000000000..343bf0ebb44 --- /dev/null +++ b/tests/update/update-orchestrated-identity.test.ts @@ -0,0 +1,62 @@ +import { expect, test } from "bun:test"; +import { inspectOrchestratedServingIdentity } from "../../src/update/orchestrated-identity"; +import { inspectLiveOrchestratedIdentity } from "../../src/update/orchestrated-live-identity"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { LOCAL_ATTESTATION_CHALLENGE_HEADER, LOCAL_ATTESTATION_PROOF_HEADER, createLocalAttestationProof } from "../../src/lib/local-management-attestation"; + +const command = ["/fixture/bun", "/fixture/install/src/cli/index.ts"]; +const record = JSON.stringify({ pid: 22, port: 10101, hostname: "127.0.0.1", attestationSecret: "a".repeat(43), command }); +const base = { + readRecord: () => ({ kind: "record" as const, raw: record }), + prove: async () => "proven" as const, + probeConfigured: async () => "dead" as const, + realpath: (path: string) => path, +}; + +test("identity requires a stable, attested runtime record", async () => { + expect(await inspectOrchestratedServingIdentity(base)).toMatchObject({ kind: "live", servingRoot: "/fixture/install", runtime: { pid: 22, command } }); + for (const proof of ["refuted", "indeterminate"] as const) { + expect(await inspectOrchestratedServingIdentity({ ...base, prove: async () => proof })).toEqual({ kind: "unknown" }); + } + let count = 0; + expect(await inspectOrchestratedServingIdentity({ ...base, readRecord: () => ({ kind: "record", raw: ++count === 1 ? record : record + " " }) })).toEqual({ kind: "unknown" }); + expect(await inspectOrchestratedServingIdentity({ ...base, readRecord: () => ({ kind: "record", raw: JSON.stringify({ pid: 22, port: 10101, hostname: "127.0.0.1", command }) }) })).toEqual({ kind: "unknown" }); +}); + +test("only a missing record plus a dead configured listener proves absence", async () => { + const absent = { ...base, readRecord: () => ({ kind: "missing" as const }) }; + expect(await inspectOrchestratedServingIdentity(absent)).toEqual({ kind: "absent" }); + expect(await inspectOrchestratedServingIdentity({ ...absent, probeConfigured: async () => "unknown" })).toEqual({ kind: "unknown" }); + expect(await inspectOrchestratedServingIdentity({ ...absent, probeConfigured: async () => "live" })).toEqual({ kind: "unknown" }); + expect(await inspectOrchestratedServingIdentity({ ...base, readRecord: () => ({ kind: "unreadable" }) })).toEqual({ kind: "unknown" }); +}); + +test("an attested legacy record refuses a proven executable mismatch without guessing its install root", async () => { + const legacy = JSON.stringify({ pid: 22, port: 10101, hostname: "127.0.0.1", attestationSecret: "a".repeat(43) }); + const deps = { ...base, readRecord: () => ({ kind: "record" as const, raw: legacy }) }; + expect(await inspectOrchestratedServingIdentity({ ...deps, legacyExecutableDiffers: async () => true })).toEqual({ kind: "mismatch" }); + expect(await inspectOrchestratedServingIdentity({ ...deps, legacyExecutableDiffers: async () => false })).toEqual({ kind: "unknown" }); +}); + +test("a real temporary listener proves its record and a replacement record is refused", async () => { + const root = mkdtempSync(join(tmpdir(), "ocx-orchestrated-identity-")); + const source = join(root, "install", "src", "cli", "index.ts"); + mkdirSync(join(root, "install", "src", "cli"), { recursive: true }); + writeFileSync(source, "fixture"); + const secret = "a".repeat(43), recordPath = join(root, "runtime-port.json"); + let replace = false; + const server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch(request) { + const challenge = request.headers.get(LOCAL_ATTESTATION_CHALLENGE_HEADER); + if (replace) writeFileSync(recordPath, JSON.stringify({ pid: process.pid, port: server.port, hostname: "127.0.0.1", attestationSecret: secret, command: [process.execPath, source], changed: true })); + const proof = challenge ? createLocalAttestationProof(secret, challenge, process.pid, server.port!) : null; + return Response.json({ service: "opencodex", status: "ok", pid: process.pid, version: "2.0.0" }, { headers: proof ? { [LOCAL_ATTESTATION_PROOF_HEADER]: proof } : {} }); + } }); + try { + writeFileSync(recordPath, JSON.stringify({ pid: process.pid, port: server.port, hostname: "127.0.0.1", attestationSecret: secret, command: [process.execPath, source] })); + expect(await inspectLiveOrchestratedIdentity(root, { port: server.port!, hostname: "127.0.0.1" })).toMatchObject({ kind: "live", runtime: { pid: process.pid } }); + replace = true; + expect(await inspectLiveOrchestratedIdentity(root, { port: server.port!, hostname: "127.0.0.1" })).toEqual({ kind: "unknown" }); + } finally { server.stop(true); rmSync(root, { recursive: true, force: true }); } +}); diff --git a/tests/update/update-orchestrated-plan.test.ts b/tests/update/update-orchestrated-plan.test.ts new file mode 100644 index 00000000000..9c0437bd17a --- /dev/null +++ b/tests/update/update-orchestrated-plan.test.ts @@ -0,0 +1,176 @@ +import { expect, test } from "bun:test"; +import { buildOrchestratedPlan, type PlanInputs } from "../../src/update/orchestrated-plan"; +import { classifyPlanRuntimeOwner, decideOrchestratedApply, observeOrchestratedPlan, type OrchestratedPlanDeps } from "../../src/update/orchestrated-entry"; +import { applyOrchestratedBun } from "../../src/update/orchestrated-entry"; +import { EventEmitter } from "node:events"; +import { mkdtempSync, mkdirSync, writeFileSync, openSync, closeSync, truncateSync, rmSync, cpSync, realpathSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { createOrchestratedChildSession, decodeOrchestratedExpect } from "../../src/update/orchestrated-session.mjs"; +import { isUpdateInFlight } from "../../src/update/sync-update-mutex"; + +test("Bun apply runs a pinned child and verifies the installed tree", async () => { + const home = mkdtempSync(join(tmpdir(), "ocx-bun-apply-")); + const root = join(home, "bun", "install", "global", "node_modules", "@bitkyc08", "opencodex"); + try { + for (const dir of ["bin", "src/cli", "node_modules/bun/bin", "node_modules/zod"]) mkdirSync(join(root, dir), { recursive: true }); + writeFileSync(join(root, "package.json"), JSON.stringify({ version: "2.1.0", dependencies: { bun: "1", zod: "1" } })); + writeFileSync(join(root, "bin/ocx.mjs"), "x".repeat(1024)); + writeFileSync(join(root, "src/cli/index.ts"), "export {};\n"); + writeFileSync(join(root, "node_modules/bun/package.json"), "{}"); + writeFileSync(join(root, "node_modules/zod/package.json"), "{}"); + const bun = join(root, "node_modules/bun/bin/bun"); closeSync(openSync(bun, "w")); truncateSync(bun, 10 * 1024 * 1024); + const plan = buildOrchestratedPlan({ ...base, installer: "bun", cliRoot: root }); + const child = new EventEmitter(); + Object.assign(child, { kill: () => true, unref: () => {} }); + const spawn = (_exe: string, args: string[], options: { env: Record }) => { + expect(args.slice(args.indexOf("update") + 1, args.indexOf("update") + 3)).toEqual(["--version", "2.1.0"]); + expect(options.env.OCX_UPDATE_ORCHESTRATED_CHILD).toBe("1"); + writeFileSync(args[args.indexOf("--orchestrated-result") + 1]!, JSON.stringify({ phase: "installed", activeRoot: root })); + queueMicrotask(() => child.emit("close", 0, null)); + return child; + }; + const result = await applyOrchestratedBun(plan, { ok: true, mode: "apply" }, { home, identity: async () => ({ kind: "absent" }), spawn, now: () => 100 }); + expect(result).toMatchObject({ exitCode: 0, result: { applied: true, healthy: true } }); + const manifest = join(root, "package.json"); + const setVersion = (version: string) => writeFileSync(manifest, JSON.stringify({ version, dependencies: { bun: "1", zod: "1" } })); + setVersion("2.0.0"); + const run = async (outcome: string | null, code: number) => { + const fake = new EventEmitter(); Object.assign(fake, { kill: () => true, unref: () => {} }); + return applyOrchestratedBun(plan, { ok: true, mode: "apply" }, { home, identity: async () => ({ kind: "absent" }), now: () => 100, + spawn: (_exe, args) => { + if (outcome !== null) writeFileSync(args[args.indexOf("--orchestrated-result") + 1]!, outcome); + queueMicrotask(() => fake.emit("close", code, null)); return fake as never; + } }); + }; + expect(await run(JSON.stringify({ phase: "refused", error: "plan-changed" }), 10)).toMatchObject({ exitCode: 10, result: { error: "plan-changed" } }); + expect(await run(JSON.stringify({ phase: "preflight" }), 1)).toMatchObject({ exitCode: 11, result: { applied: false } }); + expect(await run(JSON.stringify({ phase: "failed", error: "install-failed" }), 1)).toMatchObject({ exitCode: 11 }); + const other = join(home, "other"); cpSync(root, other, { recursive: true }); + writeFileSync(join(other, "package.json"), JSON.stringify({ version: "2.1.0", dependencies: { bun: "1", zod: "1" } })); + expect(await run(JSON.stringify({ phase: "installed", activeRoot: other }), 0)).toMatchObject({ exitCode: 12 }); + expect(await run(null, 1)).toMatchObject({ exitCode: 12 }); + expect(await run("{", 1)).toMatchObject({ exitCode: 12 }); + truncateSync(bun, 1); + expect(await run(JSON.stringify({ phase: "failed" }), 1)).toMatchObject({ exitCode: 12 }); + + let killed = false, session: ReturnType | undefined, resultDir = ""; + const running = new EventEmitter(); Object.assign(running, { kill: () => { killed = true; return true; }, unref: () => {} }); + const overrun = await applyOrchestratedBun(plan, { ok: true, mode: "apply", notAfter: 1 }, { home, identity: async () => ({ kind: "absent" }), now: () => 900_002, + spawn: (_exe, args) => { + resultDir = dirname(args[args.indexOf("--orchestrated-result") + 1]!); + session = createOrchestratedChildSession({ home, resultPath: args[args.indexOf("--orchestrated-result") + 1]!, + expect: decodeOrchestratedExpect(args[args.indexOf("--orchestrated-expect") + 1]!), verifyIdentity: () => true }); + session.start(); return running as never; + } }); + expect(overrun).toMatchObject({ exitCode: 12, result: { error: "overrun" } }); + expect(killed).toBe(false); expect(isUpdateInFlight(home)).toBe(true); + session!.finishPreflight(); running.emit("close", 1, null); + rmSync(resultDir, { recursive: true, force: true }); + } finally { rmSync(home, { recursive: true, force: true }); } +}); + +const base: PlanInputs = { + currentVersion: "2.0.0", targetVersion: "2.1.0", installer: "npm", runtimeOwner: "none", + cliRoot: "/fixture/ocx", identity: { kind: "absent" }, ownershipPermits: true, updateInFlight: false, +}; + +test.each(["bun", "npm"] as const)("%s driver retains verified install when its post-install identity probe throws", async installer => { + const home = realpathSync.native(mkdtempSync(join(tmpdir(), "ocx-probe-throw-"))), root = join(home, "package"); + try { + for (const dir of ["bin", "src/cli", "node_modules/bun/bin", "node_modules/zod"]) mkdirSync(join(root, dir), { recursive: true }); + writeFileSync(join(root, "package.json"), JSON.stringify({ version: "2.1.0", dependencies: { bun: "1", zod: "1" } })); + writeFileSync(join(root, "bin/ocx.mjs"), "x".repeat(1024)); writeFileSync(join(root, "src/cli/index.ts"), "export {};\n"); + for (const dep of ["bun", "zod"]) writeFileSync(join(root, `node_modules/${dep}/package.json`), "{}"); + const bun = join(root, "node_modules/bun/bin/bun"); closeSync(openSync(bun, "w")); truncateSync(bun, 10 * 1024 * 1024); + const identity = { kind: "live" as const, servingRoot: root, runtime: { pid: 123, port: 1234, hostname: "127.0.0.1", command: ["/bun", "/fixture"] } }; + const plan = buildOrchestratedPlan({ ...base, installer, cliRoot: root, identity, runtimeOwner: "unmanaged" }); + let calls = 0; + const probe = () => { if (++calls > 1) throw new Error("identity unavailable"); return identity; }; + const spawn = (_exe: string, args: string[]) => { + const child = new EventEmitter(); Object.assign(child, { kill: () => true, unref: () => {} }); + writeFileSync(args[args.indexOf("--orchestrated-result") + 1]!, JSON.stringify({ phase: "installed", activeRoot: root })); + queueMicrotask(() => child.emit("close", 0, null)); return child as never; + }; + const result = installer === "bun" + ? await applyOrchestratedBun(plan, { ok: true, mode: "apply" }, { home, identity: async () => probe(), now: () => 100, spawn }) + : await (await import("../../src/update/" + "orchestrated-node-driver.mjs")).applyNodeOrchestratedUpdate({ ok: true, mode: "apply" }, { + installer, currentVersion: "2.0.0", cliRoot: root, home, launcher: join(root, "bin/ocx.mjs"), resolveBun: () => ({ path: bun }), + plan: () => ({ status: 0, stdout: JSON.stringify(plan) }), identity: probe, spawn, + }); + expect(result).toMatchObject({ exitCode: 12, result: { applied: true, healthy: false, error: "runtime-unverified" } }); + } finally { rmSync(home, { recursive: true, force: true }); } +}); + +test("apply admission binds the observed plan and deadline before any update driver runs", () => { + const plan = buildOrchestratedPlan(base); + const request = { ok: true, mode: "apply" } as const; + expect(decideOrchestratedApply(plan, request, 100)).toEqual({ kind: "proceed" }); + expect(decideOrchestratedApply({ ...plan, updateInFlight: true }, request, 100)).toMatchObject({ exitCode: 10, result: { error: "update-in-flight" } }); + expect(decideOrchestratedApply(plan, { ...request, expectPlan: "different-plan-token" }, 100)).toMatchObject({ exitCode: 10, result: { error: "plan-changed", applied: false } }); + expect(decideOrchestratedApply(plan, { ...request, notAfter: 99 }, 100)).toMatchObject({ exitCode: 10, result: { error: "deadline-passed", applied: false } }); + expect(decideOrchestratedApply(plan, { ...request, notAfter: 100, expectPlan: plan.planToken }, 100)).toEqual({ kind: "proceed" }); + expect(decideOrchestratedApply(buildOrchestratedPlan({ ...base, identity: { kind: "unknown" } }), request, 100)).toMatchObject({ exitCode: 10, result: { error: "serving-install-unknown" } }); + expect(decideOrchestratedApply(buildOrchestratedPlan({ ...base, targetVersion: "2.0.0" }), request, 100)).toMatchObject({ exitCode: 0, result: { applied: false, fromVersion: "2.0.0", toVersion: "2.0.0" } }); +}); + +test("plan decision matrix refuses unsafe installs, unknown identity and unsafe versions", () => { + const live = { kind: "live", servingRoot: "/fixture/ocx", runtime: { pid: 3, port: 10101, hostname: "127.0.0.1", command: ["/fixture/bun", "/fixture/ocx/src/cli/index.ts"] } } as const; + const cases: [Partial, string][] = [ + [{ installer: "desktop-app" }, "desktop-app-owned"], + [{ installer: "source" }, "source-checkout"], + [{ installer: "mise" }, "mise-managed"], + [{ installer: "unknown" }, "installer-unknown"], + [{ identity: { kind: "unknown" } }, "serving-install-unknown"], + [{ identity: { kind: "mismatch" } }, "cli-not-serving-install"], + [{ identity: { ...live, servingRoot: "/fixture/other" } }, "cli-not-serving-install"], + [{ ownershipPermits: false }, "runtime-ownership-refused"], + [{ runtimeOwner: "unknown" }, "runtime-ownership-refused"], + [{ targetVersion: null }, "target-unresolved"], + [{ targetVersion: "1.9.0" }, "downgrade-refused"], + [{ targetVersion: "2.0.0" }, "up-to-date"], + ]; + for (const [change, reason] of cases) { + expect(buildOrchestratedPlan({ ...base, ...change })).toMatchObject({ canApply: false, reason }); + } + const plan = buildOrchestratedPlan({ ...base, identity: live, runtimeOwner: "service" }); + expect(plan).toMatchObject({ schema: "ocx.update.plan/1", canApply: true, restartRequired: true, servingPath: "/fixture/ocx", updateInFlight: false, mutationBoundMs: 900000 }); + expect(plan.planToken).toMatch(/^[A-Za-z0-9_-]{43}$/); + expect("reason" in plan).toBe(false); +}); + +test("observed plans bind the selected registry target, serving identity, owner and in-flight status", async () => { + const live = { kind: "live" as const, servingRoot: "/fixture/ocx", runtime: { pid: 3, port: 10101, hostname: "127.0.0.1", command: ["/fixture/bun", "/fixture/ocx/src/cli/index.ts"] } }; + let requested = ""; + const deps: OrchestratedPlanDeps = { + install: () => ({ installer: "npm", cliRoot: "/fixture/ocx", desktopPath: false }), + currentVersion: () => "2.0.0", + identity: async () => live, + ownership: () => ({ runtimeOwner: "service", permits: true }), + target: (selector) => { requested = selector; return selector === "2.2.0" ? selector : "2.1.0"; }, + inFlight: () => false, + }; + const first = await observeOrchestratedPlan({ ok: true, mode: "plan", tag: "preview" }, deps); + expect(requested).toBe("preview"); + expect(first).toMatchObject({ canApply: true, targetVersion: "2.1.0", runtimeOwner: "service", restartRequired: true, updateInFlight: false }); + expect((await observeOrchestratedPlan({ ok: true, mode: "plan", tag: "preview" }, deps)).planToken).toBe(first.planToken); + const pinned = await observeOrchestratedPlan({ ok: true, mode: "plan", version: "2.2.0" }, deps); + expect(requested).toBe("2.2.0"); + expect(pinned.targetVersion).toBe("2.2.0"); + expect(pinned.planToken).not.toBe(first.planToken); + expect((await observeOrchestratedPlan({ ok: true, mode: "plan", version: "2.2.0" }, { ...deps, target: () => "2.3.0" })).reason).toBe("target-unresolved"); + expect((await observeOrchestratedPlan({ ok: true, mode: "plan" }, { ...deps, identity: async () => ({ kind: "unknown" }), inFlight: () => { throw Error("unknown"); } })).updateInFlight).toBe(true); + expect((await observeOrchestratedPlan({ ok: true, mode: "plan" }, { ...deps, identity: async () => ({ kind: "live", ...live, servingRoot: "/fixture/other" }) })).reason).toBe("cli-not-serving-install"); + expect((await observeOrchestratedPlan({ ok: true, mode: "plan" }, { ...deps, ownership: () => ({ runtimeOwner: "unknown", permits: false }) })).reason).toBe("runtime-ownership-refused"); + expect((await observeOrchestratedPlan({ ok: true, mode: "plan" }, { ...deps, install: () => ({ installer: "standalone", cliRoot: "/fixture/ocx", desktopPath: true }) })).reason).toBe("desktop-app-owned"); + expect((await observeOrchestratedPlan({ ok: true, mode: "plan" }, { ...deps, identity: async () => { throw Error("unavailable"); } })).reason).toBe("plan-unavailable"); +}); + +test("a recorded CLI claim is service ownership only when a service is installed", () => { + const identity = { kind: "live" as const, servingRoot: "/fixture/ocx", runtime: { pid: 3, port: 10101, hostname: "127.0.0.1", command: ["/fixture/bun", "/fixture/ocx/src/cli/index.ts"] } }; + const owner = { kind: "owned" as const, revision: 1, ownership: { owner: "cli" as const, installId: "fixture", consentGeneration: 1 } }; + expect(classifyPlanRuntimeOwner(identity, owner, { kind: "none" }, false)).toMatchObject({ runtimeOwner: "unmanaged", permits: true }); + expect(classifyPlanRuntimeOwner(identity, owner, { kind: "none" }, true)).toMatchObject({ runtimeOwner: "service", permits: true }); + expect(classifyPlanRuntimeOwner(identity, owner, { kind: "unknown", reason: "fixture", desktopSeen: false }, true)).toMatchObject({ runtimeOwner: "unknown", permits: false }); + expect(classifyPlanRuntimeOwner({ kind: "unknown" }, { kind: "none", revision: 1 }, { kind: "none" }, false)).toMatchObject({ runtimeOwner: "unknown", permits: false }); +}); diff --git a/tests/update/update-orchestrated-session.test.ts b/tests/update/update-orchestrated-session.test.ts new file mode 100644 index 00000000000..4a8fea07c52 --- /dev/null +++ b/tests/update/update-orchestrated-session.test.ts @@ -0,0 +1,299 @@ +import { afterEach, expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { spawnSync } from "node:child_process"; +import { pathToFileURL } from "node:url"; +import { repoPath } from "../helpers/repo-root"; +import { inspectUpdateMarker, isUpdateInFlight, tryAcquireUpdateSyncMutex } from "../../src/update/sync-update-mutex"; +import { createOrchestratedChildSession, encodeOrchestratedExpect, decodeOrchestratedExpect } from "../../src/update/orchestrated-session.mjs"; +import { runOwnedPnpm } from "../../src/update/index"; + +const roots: string[] = []; +afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); +function fixture() { + const home = mkdtempSync(join(tmpdir(), "ocx-session-")); roots.push(home); + return { home, resultPath: join(home, "result.json"), expect: { home, cliRoot: join(home, "cli"), servingRoot: null, runtimePid: null, planToken: "a".repeat(43) } }; +} +function read(path: string) { return JSON.parse(readFileSync(path, "utf8")); } + +test.skipIf(process.platform === "win32")("Bun pnpm supervises a mutation's remaining process group", async () => { + for (const timed of [true, false]) { + const f = fixture(), descendant = join(f.home, "descendant"), pnpm = join(f.home, "pnpm"); + writeFileSync(pnpm, `#!/bin/sh\n${timed ? `sleep 10 /dev/null 2>&1 &\necho $! > '${descendant}'` : "exit 0"}\n`, { mode: 0o700 }); + const owner = { commandPath: pnpm, packagePath: f.home, globalDir: f.home, globalRoot: f.home, globalBinDir: f.home }; + const session = createOrchestratedChildSession({ ...f, verifyIdentity: () => true }); + try { + expect(session.start()).toEqual({ ok: true }); await session.enterMutation(); + const spawnShort = ((file, args, options) => spawnSync(file, args, { ...options, timeout: 2000 })) as typeof spawnSync; + const result = runOwnedPnpm(owner, ["add", "-g", "fixture@1"], false, "pipe", spawnShort, () => true, session, join(f.home, "update-orchestrated.json")); + session.finish({ phase: "failed" }); + const marker = read(join(f.home, "update-orchestrated.json")); + if (timed) { + expect({ exists: existsSync(descendant), stderr: result.stderr }).toMatchObject({ exists: true }); + expect(() => process.kill(Number(readFileSync(descendant, "utf8")), 0)).toThrow(); + expect(marker.fenceUntil).toBeGreaterThan(Date.now()); + expect(isUpdateInFlight(f.home)).toBe(true); + } else expect(marker.fenceUntil).toBeUndefined(); + } finally { + if (existsSync(descendant)) { + try { process.kill(Number(readFileSync(descendant, "utf8")), "SIGKILL"); } + catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; } + } + } + } +}, 10000); + +test.each([ + { pid: 2147483647, phase: "mutating", startedAt: 1, installerPid: process.pid }, + { pid: 2147483647, phase: "failed", startedAt: 1, terminationUnconfirmed: true }, +])("prior installer marker refuses and remains untouched: %j", marker => { + const f = fixture(), path = join(f.home, "update-orchestrated.json"); + const original = JSON.stringify(marker); writeFileSync(path, original); + const session = createOrchestratedChildSession({ ...f, verifyIdentity: () => true }); + expect(session.start()).toEqual({ ok: false, error: "update-in-flight" }); + expect(readFileSync(path, "utf8")).toBe(original); +}); + +test.skipIf(process.platform === "win32")("POSIX installer timeout terminates its descendant group before returning", () => { + const f = fixture(), marker = join(f.home, "update-orchestrated.json"), descendant = join(f.home, "descendant"); + writeFileSync(marker, JSON.stringify({ pid: process.pid, phase: "mutating", startedAt: Date.now() })); + const installer = join(f.home, "installer.cjs"); + writeFileSync(installer, `const {spawn}=require('node:child_process'),fs=require('node:fs'); const c=spawn(process.execPath,['-e','setInterval(()=>{},1000)'],{stdio:'ignore'});fs.writeFileSync(process.argv[2],String(c.pid));setInterval(()=>{},1000);`); + const node = Bun.which("node"); if (!node) throw new Error("node unavailable"); + const entry = pathToFileURL(repoPath("src/update/posix-install-supervisor.mjs")).href; + const script = `import {runPosixInstallerSync} from ${JSON.stringify(entry)}; const result=runPosixInstallerSync({file:${JSON.stringify(node)},args:[${JSON.stringify(installer)},${JSON.stringify(descendant)}],markerPath:${JSON.stringify(marker)},timeoutMs:1000,env:process.env});console.log(JSON.stringify(result));`; + const result = spawnSync(node, ["--input-type=module", "-e", script], { encoding: "utf8", timeout: 15000 }); + expect({ status: result.status, stderr: result.stderr }).toMatchObject({ status: 0 }); + expect(JSON.parse(result.stdout)).toMatchObject({ groupExited: true, processTreeExited: false, status: null }); + const pid = Number(readFileSync(descendant, "utf8")); + expect(() => process.kill(pid, 0)).toThrow(); +}, 20000); + +test.skipIf(process.platform === "win32")("POSIX supervisor distinguishes a signalled installer from a normal exit", () => { + const f = fixture(), marker = join(f.home, "update-orchestrated.json"); + const node = Bun.which("node"); if (!node) throw new Error("node unavailable"); + const entry = pathToFileURL(repoPath("src/update/posix-install-supervisor.mjs")).href; + for (const [code, expected] of [["process.exit(0)", { status: 0, signal: null, groupExited: true, groupKilled: false }], + ["process.kill(process.pid, 'SIGTERM')", { status: null, signal: "SIGTERM", groupExited: true, groupKilled: false }]] as const) { + writeFileSync(marker, JSON.stringify({ pid: process.pid, phase: "mutating", startedAt: Date.now() })); + const script = `import {runPosixInstallerSync} from ${JSON.stringify(entry)};console.log(JSON.stringify(runPosixInstallerSync({file:${JSON.stringify(node)},args:['-e',${JSON.stringify(code)}],markerPath:${JSON.stringify(marker)},env:process.env})));`; + const result = spawnSync(node, ["--input-type=module", "-e", script], { encoding: "utf8", timeout: 15000 }); + expect({ status: result.status, stderr: result.stderr }).toMatchObject({ status: 0 }); + expect(JSON.parse(result.stdout)).toMatchObject(expected); + } +}, 20000); + +test.skipIf(process.platform === "win32")("escaped installer descendant keeps the timed-out marker fenced", () => { + const f = fixture(), marker = join(f.home, "update-orchestrated.json"), descendant = join(f.home, "escaped"); + writeFileSync(marker, JSON.stringify({ pid: 2147483647, phase: "mutating", startedAt: 100, fenceUntil: 200 })); + const installer = join(f.home, "escape.cjs"); + writeFileSync(installer, `const {spawn}=require('node:child_process'),fs=require('node:fs'); const c=spawn(process.execPath,['-e','setInterval(()=>{},1000)'],{detached:true,stdio:'ignore'}); c.unref(); fs.writeFileSync(process.argv[2],String(c.pid)); setInterval(()=>{},1000);`); + const node = Bun.which("node"); if (!node) throw Error("node unavailable"); + const entry = pathToFileURL(repoPath("src/update/posix-install-supervisor.mjs")).href; + const script = `import {runPosixInstallerSync} from ${JSON.stringify(entry)}; console.log(JSON.stringify(runPosixInstallerSync({file:${JSON.stringify(node)},args:[${JSON.stringify(installer)},${JSON.stringify(descendant)}],markerPath:${JSON.stringify(marker)},timeoutMs:1000,env:process.env})));`; + try { + const result = spawnSync(node, ["--input-type=module", "-e", script], { encoding: "utf8", timeout: 15000 }); + expect({ status: result.status, stderr: result.stderr }).toMatchObject({ status: 0 }); + expect(JSON.parse(result.stdout)).toMatchObject({ groupExited: true, processTreeExited: false, status: null }); + expect(() => process.kill(Number(readFileSync(descendant, "utf8")), 0)).not.toThrow(); + expect(inspectUpdateMarker(f.home, { now: () => 199 })).toBe("active"); + expect(inspectUpdateMarker(f.home, { now: () => 200 })).toBe("free"); + } finally { + if (existsSync(descendant)) { + try { process.kill(Number(readFileSync(descendant, "utf8")), "SIGKILL"); } + catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; } + } + } +}, 20000); + +test("preflight owns the update mutex and remains visible until finalized", () => { + const f = fixture(); const session = createOrchestratedChildSession({ ...f, verifyIdentity: () => true }); + expect(session.start()).toEqual({ ok: true }); + expect(isUpdateInFlight(f.home)).toBe(true); + expect(tryAcquireUpdateSyncMutex(f.home, "sync")).toMatchObject({ kind: "busy", holder: "update" }); + session.finishPreflight(); + expect(isUpdateInFlight(f.home)).toBe(false); + expect(read(f.resultPath)).toEqual({ phase: "preflight" }); +}); + +test("finalizing a failed transaction retains the recorded installer identity", async () => { + const f = fixture(), session = createOrchestratedChildSession({ ...f, verifyIdentity: () => true }); + session.start(); await session.enterMutation(); + const path = join(f.home, "update-orchestrated.json"), marker = read(path); + writeFileSync(path, JSON.stringify({ ...marker, installerPid: process.pid })); + session.finish({ phase: "failed", error: "installer-termination-unconfirmed" }); + expect(read(path)).toMatchObject({ phase: "failed", installerPid: process.pid }); + expect(isUpdateInFlight(f.home)).toBe(true); +}); + +test("an untracked installer is fenced before it can start", async () => { + const f = fixture(), session = createOrchestratedChildSession({ ...f, verifyIdentity: () => true }); + session.start(); await session.enterMutation(); + session.noteUntrackedInstaller(); + expect(read(join(f.home, "update-orchestrated.json"))).toMatchObject({ phase: "mutating", terminationUnconfirmed: true }); + session.finish({ phase: "failed", error: "installer-termination-unconfirmed" }); + expect(isUpdateInFlight(f.home)).toBe(true); +}); + +test("mutation marker publishes the time fence before launching an installer and retains it on timeout", async () => { + const f = fixture(), marker = join(f.home, "update-orchestrated.json"); + const session = createOrchestratedChildSession({ ...f, now: () => 1000, verifyIdentity: () => true }); + session.start(); await session.enterMutation(); + expect(read(marker)).toMatchObject({ phase: "mutating", fenceUntil: 901000 }); + session.finish({ phase: "failed", error: "installer-termination-unconfirmed" }); + expect(read(marker)).toMatchObject({ phase: "failed", fenceUntil: 901000 }); +}); + +test("group-only supervision keeps the fence even after a successful install", async () => { + const f = fixture(), marker = join(f.home, "update-orchestrated.json"); + const session = createOrchestratedChildSession({ ...f, now: () => 1000, verifyIdentity: () => true }); + session.start(); await session.enterMutation(); session.retainInstallerFence(); + session.finish({ phase: "installed", activeRoot: f.home }); + expect(read(marker)).toMatchObject({ phase: "installed", fenceUntil: 901000 }); +}); + +test("a confirmed untracked installer releases its fence only after finalization", async () => { + const f = fixture(), session = createOrchestratedChildSession({ ...f, verifyIdentity: () => true }); + session.start(); await session.enterMutation(); session.noteUntrackedInstaller(); + session.confirmInstallerExit(); + expect(isUpdateInFlight(f.home)).toBe(true); + session.finish({ phase: "installed", activeRoot: f.home }); + expect(read(join(f.home, "update-orchestrated.json")).fenceUntil).toBeUndefined(); + expect(isUpdateInFlight(f.home)).toBe(false); +}); + +test("preflight must be writable before proceeding", () => { + const f = fixture(); + const session = createOrchestratedChildSession({ ...f, resultPath: join(f.home, "missing", "result"), verifyIdentity: () => true }); + expect(() => session.start()).toThrow(); + expect(isUpdateInFlight(f.home)).toBe(false); +}); + +test("sync holder refuses without writing an orchestrated marker", async () => { + const f = fixture(); const lock = tryAcquireUpdateSyncMutex(f.home, "sync"); + if (lock.kind !== "acquired") throw new Error("fixture lock"); + try { + const session = createOrchestratedChildSession({ ...f, verifyIdentity: () => true }); + expect(session.start()).toEqual({ ok: false, error: "sync-in-progress" }); + expect(read(f.resultPath)).toEqual({ phase: "refused", error: "sync-in-progress" }); + expect(existsSync(join(f.home, "update-orchestrated.json"))).toBe(false); + } finally { lock.release(); } +}); + +test("deadline check sees update in flight before refusing and releases the lock", async () => { + const f = fixture(); let observed = false; + const session = createOrchestratedChildSession({ ...f, notAfter: 10, now: () => { + if (existsSync(join(f.home, "update-orchestrated.json"))) observed = isUpdateInFlight(f.home); + return 11; + }, verifyIdentity: () => { throw new Error("should not run"); } }); + session.start(); expect(await session.enterMutation()).toEqual({ ok: false, error: "deadline-passed" }); + expect(observed).toBe(true); + expect(read(join(f.home, "update-orchestrated.json")).phase).toBe("refused"); + expect(read(f.resultPath)).toEqual({ phase: "refused", error: "deadline-passed" }); + expect(isUpdateInFlight(f.home)).toBe(false); +}); + +test("deadline is rechecked after asynchronous identity verification", async () => { + const f = fixture(); let clock = 99; + const session = createOrchestratedChildSession({ ...f, notAfter: 100, now: () => clock, + verifyIdentity: async () => { clock = 101; return true; } }); + expect(session.start()).toEqual({ ok: true }); + expect(await session.enterMutation()).toEqual({ ok: false, error: "deadline-passed" }); + expect(read(f.resultPath)).toEqual({ phase: "refused", error: "deadline-passed" }); + expect(isUpdateInFlight(f.home)).toBe(false); +}); + +test.each([false, "throw"] as const)("identity %s refuses after publishing in-flight", async value => { + const f = fixture(); let observed = false; + const session = createOrchestratedChildSession({ ...f, verifyIdentity: async () => { + observed = isUpdateInFlight(f.home); if (value === "throw") throw new Error("identity"); return value; + } }); + session.start(); expect(await session.enterMutation()).toEqual({ ok: false, error: "plan-changed" }); + expect(observed).toBe(true); expect(isUpdateInFlight(f.home)).toBe(false); + expect(read(join(f.home, "update-orchestrated.json")).phase).toBe("refused"); +}); + +test("finish writes final outcome before releasing mutex; failed marker write keeps mutex", async () => { + const f = fixture(); const session = createOrchestratedChildSession({ ...f, verifyIdentity: () => true }); + session.start(); expect(await session.enterMutation()).toEqual({ ok: true }); + const marker = join(f.home, "update-orchestrated.json"), original = read(marker); rmSync(marker); mkdirSync(marker); + expect(() => session.finish({ phase: "installed", activeRoot: "/active" })).toThrow(); + expect(read(f.resultPath)).toEqual({ phase: "installed", activeRoot: "/active" }); + expect(isUpdateInFlight(f.home)).toBe(true); + rmSync(marker, { recursive: true }); writeFileSync(marker, JSON.stringify(original)); session.finish({ phase: "installed", activeRoot: "/active" }); + expect(isUpdateInFlight(f.home)).toBe(false); expect(read(marker).phase).toBe("installed"); +}); + +test("unreadable marker fails closed and a stale dead holder is recovered", () => { + const f = fixture(); const marker = join(f.home, "update-orchestrated.json"); mkdirSync(marker); + expect(isUpdateInFlight(f.home)).toBe(true); rmSync(marker, { recursive: true }); + const lock = join(f.home, "sync-update.mutation.lock"); mkdirSync(lock); + const instance = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", token = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; + const owner = join(lock, `v1-${process.pid}-${instance}-${token}.json`); + writeFileSync(owner, JSON.stringify({ version: 1, pid: process.pid, processInstance: instance, token, createdAt: 1000, holderKind: "sync" })); utimesSync(owner, 1, 1); + const acquired = tryAcquireUpdateSyncMutex(f.home, "update", { now: () => 100_000, processAlive: () => false }); + expect(acquired.kind).toBe("acquired"); if (acquired.kind === "acquired") acquired.release(); +}); + +test("expect round trips and malformed payloads are rejected", () => { + const f = fixture(); expect(decodeOrchestratedExpect(encodeOrchestratedExpect(f.expect))).toEqual(f.expect); + for (const bad of ["", "!", "e30", "eyJob21lIjoxfQ", Buffer.from(JSON.stringify({ ...f.expect, runtimePid: -1 })).toString("base64url"), Buffer.from(JSON.stringify({ ...f.expect, planToken: "short" })).toString("base64url")]) { + expect(() => decodeOrchestratedExpect(bad)).toThrow(); + } +}); + +test("plain Node performs the session lifecycle", () => { + const f = fixture(); + const url = pathToFileURL(repoPath("src/update/orchestrated-session.mjs")).href; + const script = `const { createOrchestratedChildSession } = await import(${JSON.stringify(url)}); + const f = ${JSON.stringify(f)}; + const session = createOrchestratedChildSession({ ...f, verifyIdentity: () => true }); + session.start(); if (!(await session.enterMutation()).ok) process.exit(2); + session.finish({ phase: "failed", error: "test" });`; + const result = spawnSync("node", ["--input-type=module", "-e", script], { encoding: "utf8" }); + expect(result.stderr).toBe(""); expect(result.status).toBe(0); + expect(read(f.resultPath)).toEqual({ phase: "failed", error: "test" }); + expect(read(join(f.home, "update-orchestrated.json")).phase).toBe("failed"); + expect(isUpdateInFlight(f.home)).toBe(false); +}); + +test.skipIf(process.platform === "win32")("Bun worker retains its mutex through a signalled synchronous installer", async () => { + const f = fixture(); + const childModule = pathToFileURL(repoPath("src/update/orchestrated-child.mjs")).href; + const sessionModule = pathToFileURL(repoPath("src/update/orchestrated-session.mjs")).href; + const ready = join(f.home, "ready"), release = join(f.home, "release"); + const installer = `const fs=require('fs'); fs.writeFileSync(${JSON.stringify(ready)},'ready'); const end=Date.now()+10000; const t=setInterval(()=>{if(fs.existsSync(${JSON.stringify(release)}) || Date.now()>end){clearInterval(t)}},10);`; + const script = `import { protectOrchestratedWorkerSignals } from ${JSON.stringify(childModule)}; + import { createOrchestratedChildSession } from ${JSON.stringify(sessionModule)}; + import { spawnSync } from 'node:child_process'; + const s=createOrchestratedChildSession({...${JSON.stringify(f)},verifyIdentity:()=>true}); + if(!s.start().ok || !(await s.enterMutation()).ok) process.exit(2); + protectOrchestratedWorkerSignals(); + const r=spawnSync(process.execPath,['-e',${JSON.stringify(installer)}]); + s.finish({phase:'installed',activeRoot:${JSON.stringify(f.home)}}); if(r.status!==0) process.exitCode=3;`; + const worker = Bun.spawn([process.execPath, "-e", script], { stdout: "ignore", stderr: "pipe" }); + try { + const deadline = Date.now() + 10000; + while (!existsSync(ready) && Date.now() < deadline && worker.exitCode === null) await Bun.sleep(10); + expect(existsSync(ready)).toBe(true); + worker.kill("SIGTERM"); + await Bun.sleep(150); + expect(worker.exitCode).toBeNull(); + expect(tryAcquireUpdateSyncMutex(f.home, "sync")).toMatchObject({ kind: "busy", holder: "update" }); + writeFileSync(release, "release"); + expect(await worker.exited).toBe(0); + expect(read(f.resultPath)).toEqual({ phase: "installed", activeRoot: f.home }); + expect(isUpdateInFlight(f.home)).toBe(false); + } finally { writeFileSync(release, "release"); if (worker.exitCode === null) { worker.kill("SIGKILL"); await worker.exited; } } +}, 20000); + +// The compiled CLI bundles this library and gives every module the same entry URL, so the +// library itself must never act as an entry point (a top-level main once failed every packaged start). +test("POSIX supervisor library has no entry-point side effects when it shares the entry URL", () => { + const node = Bun.which("node"); if (!node) throw new Error("node unavailable"); + const library = repoPath("src/update/posix-install-supervisor.mjs"); + const script = `process.argv[1] = ${JSON.stringify(library)}; await import(${JSON.stringify(pathToFileURL(library).href)}); console.log("loaded");`; + const result = spawnSync(node, ["--input-type=module", "-e", script], { encoding: "utf8", input: "", timeout: 10000 }); + expect({ status: result.status, stdout: result.stdout.trim(), stderr: result.stderr }).toEqual({ status: 0, stdout: "loaded", stderr: "" }); +}); diff --git a/tests/update/update-orchestrated-token.test.ts b/tests/update/update-orchestrated-token.test.ts new file mode 100644 index 00000000000..823e3353997 --- /dev/null +++ b/tests/update/update-orchestrated-token.test.ts @@ -0,0 +1,18 @@ +import { expect, test } from "bun:test"; +import { createUpdatePlanToken } from "../../src/update/orchestrated-token.mjs"; + +test("plan token binds canonical install and runtime fields without the attestation secret", () => { + const input = { + currentVersion: "1.0.0", targetVersion: "1.1.0", installer: "npm", + cliRoot: "/fixture/one", servingRoot: "/fixture/one", runtimeOwner: "service", + runtime: { pid: 45, port: 10101, hostname: "127.0.0.1", command: ["/fixture/bun", "/fixture/one/src/cli/index.ts"] }, + }; + const token = createUpdatePlanToken(input); + expect(token).toMatch(/^[A-Za-z0-9_-]{43}$/); + expect(createUpdatePlanToken({ ...input, runtime: { ...input.runtime } })).toBe(token); + expect(createUpdatePlanToken({ ...input, runtime: { ...input.runtime, pid: 46 } })).not.toBe(token); + expect(createUpdatePlanToken({ ...input, servingRoot: "/fixture/two" })).not.toBe(token); + expect(createUpdatePlanToken({ ...input, runtime: { ...input.runtime, command: [...input.runtime.command, "other"] } })).not.toBe(token); + const runtimeWithSecret = { ...input.runtime, attestationSecret: "fixture-secret" }; + expect(createUpdatePlanToken({ ...input, runtime: runtimeWithSecret })).toBe(token); +}); diff --git a/tests/update/update-pnpm.test.ts b/tests/update/update-pnpm.test.ts index f0918250b2e..9adf032b499 100644 --- a/tests/update/update-pnpm.test.ts +++ b/tests/update/update-pnpm.test.ts @@ -532,6 +532,35 @@ function fakeShims(state: FakePnpmState) { } describe("pnpm global update", () => { + test("unconfirmed installer exit stops before inspection or rollback", () => { + const owner = ownerFor(), state: FakePnpmState = { activeVersion: "1.0.0", calls: [] }; + const run = fakePnpm(state, owner); + const result = runPnpmGlobalUpdate({ packageName: PKG, currentVersion: "1.0.0", targetVersion: "2.0.0", tag: "latest", owner, + runPnpm: (args, capture) => args[0] === "add" ? { status: null, processTreeExited: false } : run(args, capture), + verify: fakeVerify(state, owner), verifyShims: fakeShims(state) }); + expect(result).toMatchObject({ ok: false, error: "installer-termination-unconfirmed", processTreeExited: false }); + expect(state.calls.filter(call => call.args[0] === "list")).toHaveLength(1); + }); + test.each([{ status: null }, { status: 0, groupExited: false }, { status: 0, processTreeExited: false }])("uncertain mutation %j forbids readback and rollback", uncertain => { + const owner = ownerFor(), state: FakePnpmState = { activeVersion: "1.0.0", calls: [] }; + const run = fakePnpm(state, owner); let mutations = 0; + const result = runPnpmGlobalUpdate({ packageName: PKG, currentVersion: "1.0.0", targetVersion: "2.0.0", tag: "latest", owner, + runPnpm: (args, capture) => args[0] === "add" ? (mutations++, uncertain) : run(args, capture), + verify: fakeVerify(state, owner), verifyShims: fakeShims(state) }); + expect(result).toMatchObject({ ok: false, rolledBack: false, uncertain: true, processTreeExited: false, error: "installer-termination-unconfirmed" }); + expect(mutations).toBe(1); + expect(state.calls.filter(call => call.args[0] === "list")).toHaveLength(1); + }); + test("an unconfirmed rollback stops before final readback", () => { + const owner = ownerFor(), state: FakePnpmState = { activeVersion: "1.0.0", calls: [] }; + const run = fakePnpm(state, owner); let mutations = 0; + const result = runPnpmGlobalUpdate({ packageName: PKG, currentVersion: "1.0.0", targetVersion: "2.0.0", tag: "latest", owner, + runPnpm: (args, capture) => { if (args[0] === "add" && ++mutations === 2) return { status: null }; const value = run(args, capture); return args[0] === "add" ? { ...value, status: 1 } : value; }, + verify: fakeVerify(state, owner), verifyShims: fakeShims(state) }); + expect(result).toMatchObject({ ok: false, phase: "rollback", rolledBack: false, uncertain: true, processTreeExited: false }); + expect(mutations).toBe(2); + expect(state.calls.filter(call => call.args[0] === "list")).toHaveLength(2); + }); test("updates through the selected pnpm owner and verifies the new active group", () => { const owner = ownerFor(); const state: FakePnpmState = { activeVersion: "1.0.0", calls: [] }; @@ -578,6 +607,7 @@ describe("pnpm global update", () => { runPnpm: fakePnpm(state, owner), verify: fakeVerify(state, owner), verifyShims: fakeShims(state), }); expect(result).toMatchObject({ ok: false, phase: "install", rolledBack: true, activePath: owner.packagePath }); + expect(result).toHaveProperty("rollbackPerformed", false); expect(state.calls.filter(call => call.args[0] === "add")).toHaveLength(1); }); @@ -596,6 +626,7 @@ describe("pnpm global update", () => { expect(result).toMatchObject({ ok: false, phase: "rollback", rolledBack: true, activePath: owner.packagePath, }); + expect(result).toHaveProperty("rollbackPerformed", true); expect(state.calls.filter(call => call.args[0] === "add").map(call => call.args.at(-1))).toEqual([ `${PKG}@2.0.0`, `${PKG}@1.0.0`, ]); @@ -614,6 +645,7 @@ describe("pnpm global update", () => { runPnpm: fakePnpm(state, owner), verify: fakeVerify(state, owner), verifyShims: fakeShims(state), }); expect(result).toMatchObject({ ok: false, phase: "rollback", rolledBack: false }); + expect(result).toHaveProperty("rollbackPerformed", false); expect((result as { activePath?: string }).activePath).toBeUndefined(); }); }); diff --git a/tests/update/update-recovery-boundaries.test.ts b/tests/update/update-recovery-boundaries.test.ts index 28015a6ca57..bde387661c9 100644 --- a/tests/update/update-recovery-boundaries.test.ts +++ b/tests/update/update-recovery-boundaries.test.ts @@ -12,6 +12,7 @@ import { prepareWorkerUpdateHome } from "../../src/update/job-update-home"; import { createSupervisionLatch } from "../../src/service/desktop-supervision.mjs"; import { handoffWindowsTrayForUpdate, planWindowsTrayUpdate } from "../../src/update/tray-update-plan.mjs"; import { transactionalNpmUpdate, transactionalNpmUpdateAsync, launcherUsableAfterNpmUpdate } from "../../src/update/transactional-install.mjs"; +import { createLegacyUpdateSession } from "../../src/update/orchestrated-session.mjs"; const node = readFileSync(repoPath("bin/ocx.mjs"), "utf8"); const bun = readFileSync(repoPath("src/update/index.ts"), "utf8"); @@ -54,7 +55,7 @@ for (const platform of ["win32", "linux"] as const) { expect(command.args).toContain("--update-package-only"); expect(command.args).toContain("--update-worker-home"); } - const body = section(node, "async function runPackageManagerSelfUpdate(manager) {", "function bunBinDir(") + const body = section(node, "async function runPackageManagerSelfUpdate(manager, child) {", "function bunBinDir(") .replaceAll("import.meta.url", JSON.stringify(new URL("../../bin/ocx.mjs", import.meta.url).href)); const stage = (args: string[]) => { tree(join(args[args.indexOf("--prefix") + 1]!, "node_modules", "@bitkyc08", "opencodex"), "2.0.0"); @@ -64,8 +65,9 @@ for (const platform of ["win32", "linux"] as const) { return { status: 0, processTreeExited: true }; }; await execute(body + 'return runPackageManagerSelfUpdate("npm");', { - process: { argv: packageOnly ? [process.execPath, ...command.args] : [process.execPath, launcher, "update"], env: {}, execPath: process.execPath, platform, + process: { argv: packageOnly ? [process.execPath, ...command.args] : [process.execPath, launcher, "update"], env: {}, execPath: process.execPath, platform, once: () => {}, exit: (code: number) => { exits.push(code); throw code; } }, + createLegacyUpdateSession, console: { log: (line: string) => logs.push(line), warn: (line: string) => logs.push(line), error: (line: string) => logs.push(line) }, PKG: "@bitkyc08/opencodex", here: join(live, "bin"), dirname, join, resolve, fileURLToPath, currentPackageVersion: () => "1.0.0", updateTag: () => "latest", @@ -92,6 +94,7 @@ for (const platform of ["win32", "linux"] as const) { acquireOwnershipMutationLease: () => ({ token: "fixture", release() {} }), transactionalNpmUpdateAsync, transactionalNpmUpdateSync: transactionalNpmUpdate, runNpmInstall: async (invocation: { args: string[] }) => { await Promise.resolve(); return stage(invocation.args); }, + runPosixInstallerSync: ({ args }: { args: string[] }) => ({ ...stage(args), groupExited: true, groupKilled: false }), launcherUsableAfterNpmUpdate, npmUpdateFailureGuidance, repairCodexShimIfNeeded() {}, launcherStartHint: () => "fixture start", }).catch((error: unknown) => { if (typeof error !== "number") throw error; }); expect(installed).toBe(true); diff --git a/tests/update/update-stop-first.test.ts b/tests/update/update-stop-first.test.ts index 0dbc658d27f..ea596e1a100 100644 --- a/tests/update/update-stop-first.test.ts +++ b/tests/update/update-stop-first.test.ts @@ -244,7 +244,7 @@ function instrumentRecoveryLauncher(source: string, directory: string): string { const boot = 'const probe = bootRestoreProbe(resolve(here, ".."));'; replaceOnce(boot, `fixtureStatus("boot-restore-enter");\n ${boot}\n fixtureStatus("boot-restore-result", { action: probe.action });`); replaceOnce('} catch { /* the probe must never block launch */ }', '} catch (error) { fixtureStatus("boot-restore-error", recoveryErrorFields(error)); /* the probe must never block launch */ }'); - const runtime = 'const bunRuntime = resolveBun({ allowInstall: !codexCliUpdateInspection });'; + const runtime = 'const bunRuntime = resolveBun({ allowInstall: !passiveSync && !orchestratedUpdate && !passiveCapabilities && !codexCliUpdateInspection, allowMissing: orchestratedUpdate || passiveSync });'; replaceOnce(runtime, `fixtureStatus("runtime-resolution-enter");\n${runtime}\nfixtureStatus("runtime-resolved", { source: bunRuntime.source });`); const install = 'const r = probeSpawnSync(process.execPath, [installJs], { stdio: "inherit" });'; replaceOnce(install, `fixtureStatus("runtime-install-enter");\n ${install}\n fixtureStatus("runtime-install-result", { exitCode: r.status, signal: r.signal, ...recoveryErrorFields(r.error) });`); @@ -345,7 +345,7 @@ describe("bounded recovery diagnostics", () => { 'import { probeSpawn, probeSpawnSync } from "../src/update/mutation-guard.mjs";', 'const probe = bootRestoreProbe(resolve(here, ".."));', '} catch { /* the probe must never block launch */ }', - 'const bunRuntime = resolveBun({ allowInstall: !codexCliUpdateInspection });', + 'const bunRuntime = resolveBun({ allowInstall: !passiveSync && !orchestratedUpdate && !passiveCapabilities && !codexCliUpdateInspection, allowMissing: orchestratedUpdate || passiveSync });', 'const r = probeSpawnSync(process.execPath, [installJs], { stdio: "inherit" });', 'const child = probeSpawn(bun,', 'child.on("exit", (code, signal) => {', 'child.on("error", err => {', 'const clearHandlers = () => {', @@ -432,7 +432,8 @@ function resolveBun() { const r = probeSpawnSync(process.execPath, [installJs], { stdio: "inherit" }); return { source: "bundled", path: "fixture-bun" }; } -const bunRuntime = resolveBun({ allowInstall: !codexCliUpdateInspection }); +const passiveSync = false; +const bunRuntime = resolveBun({ allowInstall: !passiveSync && !orchestratedUpdate && !passiveCapabilities && !codexCliUpdateInspection, allowMissing: orchestratedUpdate || passiveSync }); const bun = bunRuntime.path; const child = probeSpawn(bun, ["fixture-cli", "start"], childOptions); const clearHandlers = () => { events.push("clear"); }; @@ -465,7 +466,8 @@ return child;`; process: { argv: ["node", "fixture", "start"], pid: 123, execPath: "node", on: () => {}, exit: (code: number) => events.push(code), kill: (pid: number, signal: string) => events.push([pid, signal]) }, bootRestoreProbe: () => ({ action: "none" }), resolve: () => "/fixture", here: "/fixture", - installJs: "fixture-install", codexCliUpdateInspection: false, childOptions, events, + installJs: "fixture-install", orchestratedUpdate: false, passiveCapabilities: false, + codexCliUpdateInspection: false, childOptions, events, }; const execute = new Function("io", `const { ${Object.keys(io).join(", ")} } = io;\n${source}`); expect(execute(io)).toBe(child); @@ -678,7 +680,10 @@ esac `); chmodSync(fakeNpm, 0o755); - const result = Bun.spawnSync(["node", launcher, "update"], { + // Resolve wrapper-managed Node to its actual executable: wrappers can prepend + // their own npm directory to PATH and bypass the fixture's failing npm. + const node = Bun.spawnSync(["node", "-p", "process.execPath"], { stdout: "pipe" }).stdout.toString().trim(); + const result = Bun.spawnSync([node, launcher, "update"], { cwd: root, env, stdout: "pipe", @@ -687,7 +692,7 @@ esac }); const output = result.stdout.toString() + result.stderr.toString(); - expect(result.exitCode).toBe(1); + expect(result.exitCode, output).toBe(1); expect(output).toContain("Stopping the running proxy before updating"); expect(output).toContain("restarting the previous version directly"); expect(output).toContain("'ocx status'"); @@ -823,7 +828,7 @@ esac expect(stopEnvAt).toBeLessThan(replacementAt); expect(launcherSource.slice(lockedPlanAt, stopAt)).toContain("!runtimePlan.mayStopRuntime"); const packageReplacement = launcherSource.slice(stopAt, launcherSource.indexOf("const postInstallPlan", stopAt)); - expect(packageReplacement.match(/unprivilegedOwnershipMutationEnvironment/g)).toHaveLength(3); // Windows npm, POSIX npm, pnpm. + expect(packageReplacement.match(/unprivilegedOwnershipMutationEnvironment/g)).toHaveLength(5); // Windows npm, both POSIX npm paths, both pnpm paths. }); test("replacement refusal reaches owner-aware recovery before releasing authority", () => { diff --git a/tests/update/update-sync-mutex.test.ts b/tests/update/update-sync-mutex.test.ts new file mode 100644 index 00000000000..b53d115a481 --- /dev/null +++ b/tests/update/update-sync-mutex.test.ts @@ -0,0 +1,345 @@ +import { afterEach, expect, spyOn, test } from "bun:test"; +import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync } from "node:fs"; +import { spawn, spawnSync } from "node:child_process"; +import { repoPath } from "../helpers/repo-root"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { inspectUpdateMarker, inspectUpdateSyncMutex, isUpdateInFlight, tryAcquireUpdateSyncMutex } from "../../src/update/sync-update-mutex"; +import { dispatchCommand, type CliDispatchDeps } from "../../src/cli/dispatch"; +import { withSyncUpdateGuard } from "../../src/cli/sync-update-guard"; +import { observeOrchestratedPlan } from "../../src/update/orchestrated-entry"; +import { classifySyncResult, fanoutExitCode } from "../../src/cli/sync-fanout"; + +const roots: string[] = []; +afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); +function home() { const root = mkdtempSync(join(tmpdir(), "ocx-update-sync-")); roots.push(root); return root; } + +test.each(["malformed", "absent", "different-sync"] as const)("delegated sync refuses %s lease in plain and JSON mode", kind => { + const root = home(), ran = join(root, "ran"); + const lock = kind === "different-sync" ? tryAcquireUpdateSyncMutex(root, "sync") : null; + if (lock && lock.kind !== "acquired") throw Error("fixture lock"); + if (kind === "malformed") { + const path = join(root, "sync-update.mutation.lock"); mkdirSync(path); + writeFileSync(join(path, "malformed.json"), "{"); + } + const exit = kind === "different-sync" ? 1 : 7; + const reason = exit === 1 ? "sync-in-progress" : "update-in-flight"; + const script = `import {writeFileSync} from 'node:fs'; import {withSyncUpdateGuard} from ${JSON.stringify(repoPath("src/cli/sync-update-guard.ts"))}; process.exit(await withSyncUpdateGuard(async () => { writeFileSync(${JSON.stringify(ran)}, 'ran'); return 0; }, ${JSON.stringify(["--json"])}));`; + try { + for (const json of [false, true]) { + const source = json ? script : script.replace('["--json"]', '[]'); + const result = spawnSync(process.execPath, ["--no-env-file", "-e", source], { env: { ...process.env, HOME: root, USERPROFILE: root, CODEX_HOME: join(root, "codex"), OPENCODEX_HOME: root, OCX_TEST_HOME_GUARD: "1", OCX_SYNC_MUTEX_HELD_BY: String(process.pid + 1) }, encoding: "utf8", timeout: 12000 }); + expect(result.status).toBe(exit); + expect(result.stderr.trim()).toBe(reason); + if (json) expect(JSON.parse(result.stdout)).toEqual({ schema: "ocx.sync.fanout/1", home: { state: "skipped", exit }, fanout: { state: "not-applicable", reason }, children: [] }); + else expect(result.stdout).toBe(""); + expect(() => statSync(ran)).toThrow(); + } + } finally { if (lock?.kind === "acquired") lock.release(); } +}, 30000); + +test("a sync child refuses a parent lease without its delegate pid", () => { + const root = home(), lock = tryAcquireUpdateSyncMutex(root, "sync"); + if (lock.kind !== "acquired") throw Error("fixture lock"); + try { + const script = `import {withSyncUpdateGuard} from ${JSON.stringify(repoPath("src/cli/sync-update-guard.ts"))}; process.exit(await withSyncUpdateGuard(async () => 0));`; + const result = spawnSync(process.execPath, ["--no-env-file", "-e", script], { env: { ...process.env, OPENCODEX_HOME: root, OCX_TEST_HOME_GUARD: "1", OCX_SYNC_MUTEX_HELD_BY: String(process.pid), npm_config_registry: "http://127.0.0.1:9", NPM_CONFIG_REGISTRY: "http://127.0.0.1:9" }, encoding: "utf8", timeout: 12000 }); + expect({ status: result.status, stderr: result.stderr }).toMatchObject({ status: 1, stderr: expect.stringContaining("sync-in-progress") }); + } finally { lock.release(); } +}, 15000); + +test("a stale sync lease remains held by its live delegate", () => { + const root = home(), lock = join(root, "sync-update.mutation.lock"); + const instance = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", token = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; + mkdirSync(lock); + const owner = join(lock, `v1-2147483647-${instance}-${token}.json`); + writeFileSync(owner, JSON.stringify({ version: 1, pid: 2147483647, delegatePid: process.pid, processInstance: instance, token, createdAt: 1000, holderKind: "sync" })); + utimesSync(owner, 1, 1); + const lease = tryAcquireUpdateSyncMutex(root, "update", { now: () => 100_000, processAlive: pid => pid === process.pid }); + expect(lease).toEqual({ kind: "busy", holder: "sync" }); + if (lease.kind === "acquired") lease.release(); +}); + +test("an invalid delegate pid prevents stale lease reclamation", () => { + const root = home(), lock = join(root, "sync-update.mutation.lock"); + const instance = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", token = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; + mkdirSync(lock); + const owner = join(lock, `v1-2147483647-${instance}-${token}.json`); + writeFileSync(owner, JSON.stringify({ version: 1, pid: 2147483647, delegatePid: "unreadable", processInstance: instance, token, createdAt: 1000, holderKind: "sync" })); + utimesSync(owner, 1, 1); + expect(tryAcquireUpdateSyncMutex(root, "update", { now: () => 100_000, processAlive: () => false })).toEqual({ kind: "busy", holder: "unknown" }); +}); + +test("sync child accepts only a matching parent-held mutex", async () => { + const root = home(), lock = tryAcquireUpdateSyncMutex(root, "sync"); + if (lock.kind !== "acquired") throw Error("fixture lock"); + try { + const script = `import {withSyncUpdateGuard} from ${JSON.stringify(repoPath("src/cli/sync-update-guard.ts"))}; process.exit(await withSyncUpdateGuard(async () => 0));`; + for (const [heldBy, expected] of [[String(process.pid), 0], [String(process.pid + 1), 1], ["", 1]] as const) { + const child = spawn(process.execPath, ["--no-env-file", "-e", script], { env: { ...process.env, OPENCODEX_HOME: root, OCX_TEST_HOME_GUARD: "1", OCX_SYNC_MUTEX_HELD_BY: heldBy, npm_config_registry: "http://127.0.0.1:9", NPM_CONFIG_REGISTRY: "http://127.0.0.1:9" }, stdio: "ignore" }); + if (!child.pid) throw Error("child did not start"); + if (expected === 0) lock.addDelegate(child.pid); + const status = await new Promise((resolve, reject) => { child.once("exit", resolve); child.once("error", reject); }); + expect(status).toBe(expected); + } + } finally { lock.release(); } +}, 45000); + +test("a matching parent pid cannot turn an update lease into a sync lease", () => { + const root = home(), lock = tryAcquireUpdateSyncMutex(root, "update"); + if (lock.kind !== "acquired") throw Error("fixture lock"); + try { + const script = `import {withSyncUpdateGuard} from ${JSON.stringify(repoPath("src/cli/sync-update-guard.ts"))}; process.exit(await withSyncUpdateGuard(async () => 0));`; + const result = spawnSync(process.execPath, ["--no-env-file", "-e", script], { env: { ...process.env, OPENCODEX_HOME: root, OCX_TEST_HOME_GUARD: "1", OCX_SYNC_MUTEX_HELD_BY: String(process.pid), npm_config_registry: "http://127.0.0.1:9", NPM_CONFIG_REGISTRY: "http://127.0.0.1:9" }, encoding: "utf8", timeout: 12000 }); + expect({ status: result.status, stderr: result.stderr }).toMatchObject({ status: 7, stderr: expect.stringContaining("update-in-flight") }); + } finally { lock.release(); } +}, 15000); + +test.skipIf(process.platform === "win32")("legacy Node and Bun update refuse a sync holder before their work", () => { + const root = home(), config = join(root, "config"), packageRoot = join(root, "node_modules", "@bitkyc08", "opencodex"); + mkdirSync(join(packageRoot, "bin"), { recursive: true }); mkdirSync(config); + copyFileSync(repoPath("bin/ocx.mjs"), join(packageRoot, "bin", "ocx.mjs")); + symlinkSync(repoPath("src"), join(packageRoot, "src"), "dir"); + writeFileSync(join(packageRoot, "package.json"), JSON.stringify({ name: "@bitkyc08/opencodex", version: "1.0.0", type: "module" })); + const env = { ...process.env, HOME: root, CODEX_HOME: join(root, "codex"), OPENCODEX_HOME: config, + OCX_TEST_HOME_GUARD: "1", OCX_NO_DESKTOP_HANDOFF: "1", npm_config_registry: "http://127.0.0.1:9", NPM_CONFIG_REGISTRY: "http://127.0.0.1:9" }; + const lock = tryAcquireUpdateSyncMutex(config, "sync"); if (lock.kind !== "acquired") throw Error("fixture lock"); + try { + const before = readFileSync(join(packageRoot, "package.json"), "utf8"); + const node = spawnSync("node", [join(packageRoot, "bin", "ocx.mjs"), "update"], { env, encoding: "utf8", timeout: 12000 }); + expect({ status: node.status, stderr: node.stderr }).toMatchObject({ status: 1, stderr: expect.stringContaining("sync-in-progress") }); + const script = `import {runUpdate} from ${JSON.stringify(repoPath("src/update/index.ts"))}; await runUpdate();`; + const bun = spawnSync(process.execPath, ["--no-env-file", "-e", script], { env, encoding: "utf8", timeout: 12000 }); + expect({ status: bun.status, stderr: bun.stderr }).toMatchObject({ status: 1, stderr: expect.stringContaining("sync-in-progress") }); + expect(readFileSync(join(packageRoot, "package.json"), "utf8")).toBe(before); + } finally { lock.release(); } +}, 20000); + +test("sync refuses while a legacy update session holds its marker and mutex", async () => { + const root = home(), previous = process.env.OPENCODEX_HOME; process.env.OPENCODEX_HOME = root; + const { createLegacyUpdateSession } = await import("../../src/update/orchestrated-session.mjs"); + const session = createLegacyUpdateSession({ home: root }); + const err = spyOn(console, "error").mockImplementation(() => {}); + try { + expect(session.start()).toEqual({ ok: true }); + expect(await withSyncUpdateGuard(async () => { throw Error("sync work reached"); })).toBe(7); + } finally { + session.finishPreflight(); err.mockRestore(); + if (previous === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previous; + } +}); + +test("a fresh home is free in plans and sync can acquire its guard", async () => { + const root = home(), fresh = join(root, "missing"), previous = process.env.OPENCODEX_HOME; + process.env.OPENCODEX_HOME = fresh; + try { + expect(inspectUpdateSyncMutex(fresh)).toBe("free"); + expect(isUpdateInFlight(fresh)).toBe(false); + const plan = await observeOrchestratedPlan({ ok: true, mode: "plan" }, { + install: () => ({ installer: "npm", cliRoot: root, desktopPath: false }), currentVersion: () => "2.0.0", + identity: async () => ({ kind: "absent" }), ownership: () => ({ runtimeOwner: "none", permits: true }), + target: () => "2.1.0", inFlight: () => isUpdateInFlight(fresh), + }); + expect(plan.updateInFlight).toBe(false); + let ran = false; + expect(await withSyncUpdateGuard(async () => { ran = true; return 0; })).toBe(0); + expect(ran).toBe(true); + if (process.platform !== "win32") expect(statSync(fresh).mode & 0o777).toBe(0o700); + expect(inspectUpdateSyncMutex(fresh)).toBe("free"); + } finally { if (previous === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previous; } +}); + +test.skipIf(process.platform === "win32")("a dangling home symlink remains uncertain", () => { + const root = home(), link = join(root, "link"); + symlinkSync(join(root, "absent"), link); + expect(inspectUpdateSyncMutex(link)).toBe("unknown"); + expect(tryAcquireUpdateSyncMutex(link, "sync")).toEqual({ kind: "busy", holder: "unknown" }); +}); + +test("sync and update holders exclude one another and identify their kind", () => { + const root = home(); + const sync = tryAcquireUpdateSyncMutex(root, "sync"); + expect(sync.kind).toBe("acquired"); + if (sync.kind !== "acquired") throw new Error("fixture lease not acquired"); + try { + expect(inspectUpdateSyncMutex(root)).toBe("sync"); + expect(tryAcquireUpdateSyncMutex(root, "update")).toEqual({ kind: "busy", holder: "sync" }); + } finally { sync.release(); } + const update = tryAcquireUpdateSyncMutex(root, "update"); + expect(update.kind).toBe("acquired"); + if (update.kind !== "acquired") throw new Error("fixture lease not acquired"); + try { + expect(inspectUpdateSyncMutex(root)).toBe("update"); + expect(tryAcquireUpdateSyncMutex(root, "sync")).toEqual({ kind: "busy", holder: "update" }); + } finally { update.release(); } + expect(inspectUpdateSyncMutex(root)).toBe("free"); +}); + +test("an occupied mutex authority path is uncertain and cannot acquire a lease", () => { + const root = home(); + const target = join(root, "other-name"); + mkdirSync(target); + symlinkSync(target, join(root, "sync-update"), process.platform === "win32" ? "junction" : "dir"); + expect(inspectUpdateSyncMutex(root)).toBe("unknown"); + expect(isUpdateInFlight(root)).toBe(true); + expect(tryAcquireUpdateSyncMutex(root, "update")).toEqual({ kind: "busy", holder: "unknown" }); +}); + +test("sync refuses before its work while an update holds the mutex", async () => { + const root = home(); + const previous = process.env.OPENCODEX_HOME; + process.env.OPENCODEX_HOME = root; + const update = tryAcquireUpdateSyncMutex(root, "update"); + if (update.kind !== "acquired") throw new Error("fixture lease not acquired"); + const err = spyOn(console, "error").mockImplementation(() => {}); + try { + const args = ["sync"]; + const deps = { args, findLiveProxy: async () => { throw new Error("sync work reached"); } } as unknown as CliDispatchDeps; + expect(await dispatchCommand({ kind: "command", command: "sync", args }, deps)).toBe(7); + expect(err).toHaveBeenCalledWith("update-in-flight"); + } finally { + err.mockRestore(); update.release(); + if (previous === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previous; + } +}); + +test.each(["sync", "update", "unknown"] as const)("sync guard classifies a %s mutex holder", async holder => { + const root = home(), previous = process.env.OPENCODEX_HOME; + process.env.OPENCODEX_HOME = root; + const lock = holder === "unknown" ? null : tryAcquireUpdateSyncMutex(root, holder); + if (lock && lock.kind !== "acquired") throw new Error("fixture lease not acquired"); + if (!lock) mkdirSync(join(root, "sync-update")); + const err = spyOn(console, "error").mockImplementation(() => {}); + try { + const code = await withSyncUpdateGuard(async () => { throw new Error("sync work reached"); }); + const reason = holder === "sync" ? "sync-in-progress" : "update-in-flight"; + expect(code).toBe(holder === "sync" ? 1 : 7); + expect(err).toHaveBeenCalledWith(reason); + const child = classifySyncResult({ code, stdout: "ocx-fanout:stdout-begin\n", stderr: `ocx-fanout:selected:2.93.0\n${reason}\n` }); + if (holder === "sync") { + expect(child).toEqual({ state: "failed", reason: "child-sync-failed" }); + expect(fanoutExitCode({ schema: "ocx.sync.fanout/1", home: { state: "synced", exit: 0 }, fanout: { state: "ran", reason: null }, children: [{ linkId: "child", alias: "host", ...child, exit: code }] })).toBe(6); + } else expect(child).toEqual({ state: "skipped", reason: "child-updating" }); + } finally { + err.mockRestore(); if (lock?.kind === "acquired") lock.release(); + if (previous === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previous; + } +}); + +test.each(["sync", "update", "unknown", "marker"] as const)("sync --json emits one fan-out refusal for %s", async holder => { + const root = home(), previous = process.env.OPENCODEX_HOME; process.env.OPENCODEX_HOME = root; + const lock = holder === "sync" || holder === "update" ? tryAcquireUpdateSyncMutex(root, holder) : null; + if (lock && lock.kind !== "acquired") throw new Error("fixture lease not acquired"); + if (holder === "unknown") mkdirSync(join(root, "sync-update")); + if (holder === "marker") writeFileSync(join(root, "update-orchestrated.json"), JSON.stringify({ pid: process.pid, phase: "mutating", startedAt: 1 })); + const out = spyOn(console, "log").mockImplementation(() => {}); + const err = spyOn(console, "error").mockImplementation(() => {}); + try { + const args = ["sync", "--json", "--local-only"]; + const deps = { args, findLiveProxy: async () => { throw new Error("sync work reached"); } } as unknown as CliDispatchDeps; + const code = await dispatchCommand({ kind: "command", command: "sync", args }, deps); + const reason = holder === "sync" ? "sync-in-progress" : "update-in-flight"; + expect(code).toBe(holder === "sync" ? 1 : 7); + expect(err).toHaveBeenCalledWith(reason); + expect(out).toHaveBeenCalledTimes(1); + const output = out.mock.calls[0]![0] as string; + expect(JSON.parse(output)).toEqual({ schema: "ocx.sync.fanout/1", home: { state: "skipped", exit: code }, fanout: { state: "not-applicable", reason }, children: [] }); + expect(classifySyncResult({ code, stdout: `ocx-fanout:stdout-begin\n${output}\n`, stderr: `ocx-fanout:selected:2.93.0\n${reason}\n` })).toEqual(holder === "sync" ? { state: "failed", reason: "child-sync-failed" } : { state: "skipped", reason: "child-updating" }); + } finally { + out.mockRestore(); err.mockRestore(); if (lock?.kind === "acquired") lock.release(); + if (previous === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previous; + } +}); + +test("sync refuses a live update marker even if its mutex is unexpectedly absent", async () => { + const root = home(), previous = process.env.OPENCODEX_HOME; + process.env.OPENCODEX_HOME = root; + writeFileSync(join(root, "update-orchestrated.json"), JSON.stringify({ pid: process.pid, phase: "mutating", startedAt: 1 })); + const err = spyOn(console, "error").mockImplementation(() => {}); + const shim = spyOn(await import("../../src/cli/codex-shim-autorestore"), "runCodexShimAutoRestoreAsync").mockResolvedValue(undefined); + try { + const args = ["sync"]; + const deps = { args, findLiveProxy: async () => { throw new Error("sync work reached"); } } as unknown as CliDispatchDeps; + expect(await dispatchCommand({ kind: "command", command: "sync", args }, deps)).toBe(7); + expect(shim).not.toHaveBeenCalled(); + } finally { + shim.mockRestore(); err.mockRestore(); + if (previous === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previous; + } +}); + +test("a stale, proven-dead holder is recovered without waiting", () => { + const root = home(); + const lock = join(root, "sync-update.mutation.lock"); + const instance = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", token = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; + mkdirSync(lock); + const owner = join(lock, `v1-${process.pid}-${instance}-${token}.json`); + writeFileSync(owner, JSON.stringify({ version: 1, pid: process.pid, processInstance: instance, token, createdAt: 1000, holderKind: "sync" })); + utimesSync(owner, 1, 1); + const lease = tryAcquireUpdateSyncMutex(root, "update", { now: () => 100_000, processAlive: () => false }); + expect(lease.kind).toBe("acquired"); + if (lease.kind === "acquired") lease.release(); +}); + +test("in-flight observation is fail-closed and distinguishes a sync-only holder", () => { + const root = home(); + const deps = { ownershipLease: () => "free" as const, mutex: () => "free" as const, marker: () => "free" as const }; + expect(isUpdateInFlight(root, deps)).toBe(false); + expect(isUpdateInFlight(root, { ...deps, mutex: () => "sync" })).toBe(false); + expect(isUpdateInFlight(root, { ...deps, mutex: () => "update" })).toBe(true); + expect(isUpdateInFlight(root, { ...deps, mutex: () => "unknown" })).toBe(true); + expect(isUpdateInFlight(root, { ...deps, ownershipLease: () => "unknown" })).toBe(true); + expect(isUpdateInFlight(root, { ...deps, marker: () => "active" })).toBe(true); + expect(isUpdateInFlight(root, { ...deps, marker: () => "unknown" })).toBe(true); +}); + +test("a live overrun marker remains in flight and malformed markers are uncertain", () => { + const root = home(); + const path = join(root, "update-orchestrated.json"); + const deps = { ownershipLease: () => "free" as const, mutex: () => "free" as const, marker: inspectUpdateMarker }; + expect(isUpdateInFlight(root, deps)).toBe(false); + writeFileSync(path, JSON.stringify({ pid: process.pid, phase: "overrun", startedAt: 1 })); + expect(isUpdateInFlight(root, deps)).toBe(true); + writeFileSync(path, JSON.stringify({ pid: process.pid, phase: "installed" })); + expect(isUpdateInFlight(root, deps)).toBe(true); + writeFileSync(path, "{"); + expect(isUpdateInFlight(root, deps)).toBe(true); +}); + +test("a failed marker retains the update fence while its installer remains alive", () => { + const root = home(), path = join(root, "update-orchestrated.json"); + writeFileSync(path, JSON.stringify({ pid: 2147483647, installerPid: process.pid, phase: "failed", startedAt: 1 })); + expect(inspectUpdateMarker(root)).toBe("active"); + expect(isUpdateInFlight(root)).toBe(true); +}); + +test("unconfirmed installer termination without a recorded pid remains uncertain", () => { + const root = home(), path = join(root, "update-orchestrated.json"); + writeFileSync(path, JSON.stringify({ pid: process.pid, phase: "failed", startedAt: 1, terminationUnconfirmed: true })); + expect(inspectUpdateMarker(root)).toBe("unknown"); + expect(isUpdateInFlight(root)).toBe(true); +}); + +test.each([undefined, 2147483646])("dead worker with installer pid %s remains fenced until deadline", installerPid => { + const root = home(), path = join(root, "update-orchestrated.json"), now = { value: 199 }; + writeFileSync(path, JSON.stringify({ pid: 2147483647, phase: "mutating", startedAt: 100, fenceUntil: 200, + ...(installerPid === undefined ? {} : { installerPid }) })); + expect(inspectUpdateMarker(root, { now: () => now.value })).toBe("active"); + now.value = 200; + expect(inspectUpdateMarker(root, { now: () => now.value })).toBe("free"); +}); + +test("a timed-out final marker remains fenced only until the bound when recorded processes are gone", () => { + const root = home(), path = join(root, "update-orchestrated.json"); + writeFileSync(path, JSON.stringify({ pid: 2147483647, phase: "failed", startedAt: 100, fenceUntil: 200 })); + expect(inspectUpdateMarker(root, { now: () => 199 })).toBe("active"); + expect(inspectUpdateMarker(root, { now: () => 200 })).toBe("free"); +}); + +test("sync refuses a fenced dead worker before the deadline", async () => { + const root = home(), previous = process.env.OPENCODEX_HOME; process.env.OPENCODEX_HOME = root; + writeFileSync(join(root, "update-orchestrated.json"), JSON.stringify({ pid: 2147483647, phase: "mutating", startedAt: Date.now(), fenceUntil: Date.now() + 900000 })); + const err = spyOn(console, "error").mockImplementation(() => {}); + try { expect(await withSyncUpdateGuard(async () => { throw Error("sync reached"); })).toBe(7); } + finally { err.mockRestore(); if (previous === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previous; } +}); From ebcb6640b2cfd6957540af5afa9dfe938877afd5 Mon Sep 17 00:00:00 2001 From: JUN Date: Tue, 3 Nov 2026 01:56:36 +0900 Subject: [PATCH 11/43] Normalize upstream error details in request logs and Retry-After advice (#8104) * Normalize upstream error details in request logs and Retry-After advice * Update request-log and quota observation tests for normalized error details * Add regression tests for normalized error details and client retry advice * Document proxy-owned request-log error detail and client retry advice * Project final request-log rows before any writer and keep native evidence through classification * Keep long account-cooldown retry advice and the Ollama retry bound unchanged * Leave successful output-limit stops without an upstream condition * Keep proxy-written failure sentences, update row expectations and user docs * Format every computed client Retry-After and keep local diagnostics out of upstream conditions * Log combo hop failures by classified condition only * Record closed failure detail, bounded tiers and model identities, and normalized response metadata headers * Normalize response metadata headers by exact lookup and integer limits Header normalizers are selected from a Map and return primitive strings only, so names matching Object.prototype members are never relayed. Rate-limit counts are rebuilt as bounded non-negative integers and resets as whole seconds (or whole milliseconds below one second), clamped to eight days. Also: the hydration projection bounds service tiers itself; Retry-After accepts RFC 850 and asctime dates read as GMT; condition classification reuses the definite context-overflow verdict (moved to a dependency-free module), treats usage_limit_exceeded and 1308 as billing exhaustion, and is captured where the Messages passthrough parses the error; the combo hop warning passes the error type; dashboard docs note that older usage.jsonl rows are dropped on read. * Rebuild WebSocket response metadata from proxy-owned values Response metadata relayed to clients no longer copies upstream values. The turn-state token is replaced by a random proxy handle that is mapped back at request ingress (HTTP header, WebSocket upgrade and frame client_metadata). Request ids, the models etag and quota limit labels are not relayed, and quota windows are limited to the known limit families. The native codex.rate_limits frame is rebuilt from an explicit schema with bounded numbers and closed labels, and the upgrade inclusion header keeps its presence with a proxy-owned value. The error-detail boundary test polls for its live and persisted rows and asserts they are non-empty before checking for absent values. * Bind turn-state handles to the send and keep only known model ids Turn-state handles are bound at issuance to the admitted caller, the provider and the outbound account, and are redeemed only at the outbound send after admission and routing, when the send has the same binding; otherwise the value is removed and a fixed service-log flag is written. Each request and WebSocket frame records its admitted caller in a request-scoped slot. An upstream-reported model (relayed model headers, served and resolved models in request-log rows) is kept only when it equals a model id the request or a bundled catalog already names, and the proxy's copy is used. The rebuilt codex.rate_limits frame omits the credit balance, which stays available as the proxy-formatted header. * Apply the known-model rule inside passthrough header sanitization sanitizePassthroughHeaders now keeps openai-model and x-codex-safety-buffering-faster-model only as a model id the proxy already knows, so every passthrough branch (redirects, error statuses, JSON answered as JSON or re-framed as SSE) relays the proxy's copy or nothing. Known ids for a passthrough also include the models configured for the selected provider and its cached discovered models, so a provider-owned hint naming one of them is kept. Adds end-to-end tests that obtain a turn-state handle from a mock Codex WebSocket upstream and redeem it over HTTP and WebSocket, including two concurrent API-key callers. * Do not trust live-discovered model ids for relayed model headers Ids from a provider's live /models discovery come from the upstream itself, so they no longer count as known models when relaying openai-model or x-codex-safety-buffering-faster-model. Trusted ids stay the route's own ids, the bundled catalogs and the models configured for the provider. Adds a regression test that seeds discovery through the real discovery path and checks that both headers and the request-log fields drop the value. * Exclude preset-selected models from trusted passthrough model ids A model preset fills selectedModels from the discovered catalog, so it is not a user-declared source. Passthrough model headers now trust route ids, bundled catalogs, and the provider models, retainModels and defaultModel only. --- .../src/content/docs/fr/guides/claude-code.md | 2 +- .../content/docs/fr/guides/web-dashboard.md | 2 +- .../src/content/docs/guides/claude-code.md | 2 +- .../src/content/docs/guides/web-dashboard.md | 2 +- .../src/content/docs/ja/guides/claude-code.md | 2 +- .../content/docs/ja/guides/web-dashboard.md | 2 +- .../src/content/docs/ko/guides/claude-code.md | 2 +- .../content/docs/ko/guides/web-dashboard.md | 2 +- .../src/content/docs/ru/guides/claude-code.md | 2 +- .../content/docs/ru/guides/web-dashboard.md | 2 +- .../src/content/docs/tr/guides/claude-code.md | 2 +- .../content/docs/tr/guides/web-dashboard.md | 2 +- .../content/docs/zh-cn/guides/claude-code.md | 2 +- .../docs/zh-cn/guides/web-dashboard.md | 2 +- .../content/docs/zh-tw/guides/claude-code.md | 2 +- .../docs/zh-tw/guides/web-dashboard.md | 2 +- gui/src/i18n/de.ts | 29 ++ gui/src/i18n/en.ts | 29 ++ gui/src/i18n/fr.ts | 29 ++ gui/src/i18n/ja.ts | 29 ++ gui/src/i18n/ko.ts | 29 ++ gui/src/i18n/pt.ts | 29 ++ gui/src/i18n/ru.ts | 29 ++ gui/src/i18n/tr.ts | 29 ++ gui/src/i18n/vi.ts | 29 ++ gui/src/i18n/zh-TW.ts | 29 ++ gui/src/i18n/zh.ts | 29 ++ gui/src/muse-limit-observation.ts | 9 +- gui/src/pages/Logs.tsx | 9 +- gui/src/pages/logs-failure-summary.ts | 65 +++++ gui/tests/logs-failure-detail.test.ts | 34 +++ gui/tests/muse-limit-observation.test.ts | 19 +- scripts/test-layout/layout-usage.json | 11 +- src/bridge/errors.ts | 7 +- src/codex/auth-context.ts | 4 +- src/combos/failover.ts | 112 +------- src/lib/client-retry-after.ts | 66 +++++ src/lib/context-overflow-verdict.ts | 113 ++++++++ src/lib/failure-detail.ts | 66 +++++ src/lib/model-identity.ts | 44 +++ src/lib/response-service-tier.ts | 17 ++ src/lib/retry-after.ts | 3 + src/lib/upstream-condition.ts | 142 ++++++++++ src/providers/fastwire.ts | 5 +- src/routing/fallback-policy.ts | 4 +- src/server/auth-cors.ts | 5 + src/server/chat-completions.ts | 4 +- src/server/chat-native.ts | 10 +- src/server/claude-messages.ts | 35 ++- src/server/context-history.ts | 6 +- src/server/index/serve-options.ts | 6 +- src/server/index/websocket-handler.ts | 6 +- src/server/messages-native.ts | 14 +- src/server/messages-shared.ts | 8 +- src/server/native-final-log.ts | 8 +- src/server/relay.ts | 18 +- src/server/request-log-failure-detail.ts | 54 ++++ src/server/request-log-terminal-status.ts | 6 +- src/server/request-log.ts | 66 ++--- src/server/responses/codex-ws-exchange.ts | 19 +- src/server/responses/codex-ws-metadata.ts | 115 ++++++-- src/server/responses/codex-ws-request.ts | 4 +- src/server/responses/compact.ts | 8 +- src/server/responses/core-combo.ts | 13 +- src/server/responses/core-errors.ts | 8 +- src/server/responses/fetch-helpers.ts | 8 +- src/server/responses/passthrough-delivery.ts | 32 ++- src/server/responses/passthrough-error.ts | 18 +- src/server/responses/request-transport.ts | 4 +- src/server/responses/run-turn-execution.ts | 3 +- src/server/responses/ws-upstream.ts | 9 + src/server/safe-response-headers.ts | 175 +++++++++++- src/server/turn-state-handles.ts | 164 ++++++++++++ src/usage/error-detail.ts | 225 ++++++++++++++++ src/usage/log.ts | 83 ++++-- structure/INDEX.md | 9 + structure/clients/claude-desktop.md | 4 +- structure/dashboard-and-usage.md | 6 +- structure/data-planes/error-detail.md | 151 +++++++++++ structure/data-planes/ollama-inbound.md | 5 +- structure/manifest.json | 16 ++ .../transports/responses-combo-boundaries.md | 6 +- structure/transports/responses-wire-shapes.md | 4 +- structure/transports/responses.md | 2 +- .../anthropic/anthropic-error-body.test.ts | 6 +- .../claude-messages-endpoint.test.ts | 2 +- .../claude-native-passthrough.test.ts | 77 +++--- .../messages-native.test.ts | 9 +- .../catalog-omit-disabled-native.test.ts.snap | 2 + tests/fixtures/test-layout-expected.json | 1 + tests/lib/client-retry-after.test.ts | 56 ++++ tests/lib/upstream-condition.test.ts | 95 +++++++ .../github-copilot-auto-runtime.test.ts | 11 + .../chat-completions-endpoint.test.ts | 4 +- .../codex-ws-handshake-validation.test.ts | 8 +- .../openai-responses-passthrough.test.ts | 6 +- tests/responses/passthrough-headers.test.ts | 14 + .../responses-combo-exhausted-error.test.ts | 28 +- .../responses-fetch-helpers-boundary.test.ts | 2 + tests/responses/ws-endpoint.test.ts | 9 +- tests/responses/ws-pre-output-refusal.test.ts | 2 +- tests/responses/ws-upstream.test.ts | 72 +++-- tests/routing/fastwire-observability.test.ts | 7 +- .../routing-policy-dispatch-scope.test.ts | 5 +- tests/server/client-retry-after-sites.test.ts | 68 +++++ tests/server/context-history.test.ts | 9 + tests/server/response-model-identity.test.ts | 167 ++++++++++++ tests/server/safe-response-headers.test.ts | 217 +++++++++++++++ .../server/server-403-permission-e2e.test.ts | 3 +- tests/server/server-auth.test.ts | 3 +- .../server/server-combo-failover-e2e.test.ts | 9 +- tests/server/server-native-final-log.test.ts | 22 ++ tests/server/turn-state-handles-e2e.test.ts | 201 ++++++++++++++ tests/server/turn-state-handles.test.ts | 189 +++++++++++++ .../upstream-error-detail-boundaries.test.ts | 141 ++++++++++ tests/usage/request-log-error-detail.test.ts | 250 ++++++++++++++++++ .../usage/request-log-identity-bounds.test.ts | 137 ++++++++++ tests/usage/request-log-nonstream.test.ts | 11 +- tests/usage/request-log-served-model.test.ts | 23 +- tests/usage/request-log.test.ts | 38 +-- .../upstream-failure-diagnostics.test.ts | 18 +- tests/usage/usage-failure-persistence.test.ts | 5 +- .../web-search-timeout-contract.test.ts | 6 +- 123 files changed, 3882 insertions(+), 469 deletions(-) create mode 100644 gui/tests/logs-failure-detail.test.ts create mode 100644 src/lib/client-retry-after.ts create mode 100644 src/lib/context-overflow-verdict.ts create mode 100644 src/lib/failure-detail.ts create mode 100644 src/lib/model-identity.ts create mode 100644 src/lib/response-service-tier.ts create mode 100644 src/lib/upstream-condition.ts create mode 100644 src/server/request-log-failure-detail.ts create mode 100644 src/server/turn-state-handles.ts create mode 100644 src/usage/error-detail.ts create mode 100644 structure/data-planes/error-detail.md create mode 100644 tests/lib/client-retry-after.test.ts create mode 100644 tests/lib/upstream-condition.test.ts create mode 100644 tests/server/client-retry-after-sites.test.ts create mode 100644 tests/server/safe-response-headers.test.ts create mode 100644 tests/server/turn-state-handles-e2e.test.ts create mode 100644 tests/server/turn-state-handles.test.ts create mode 100644 tests/server/upstream-error-detail-boundaries.test.ts create mode 100644 tests/usage/request-log-error-detail.test.ts create mode 100644 tests/usage/request-log-identity-bounds.test.ts diff --git a/docs-site/src/content/docs/fr/guides/claude-code.md b/docs-site/src/content/docs/fr/guides/claude-code.md index 3c68aea0926..82880ab2039 100644 --- a/docs-site/src/content/docs/fr/guides/claude-code.md +++ b/docs-site/src/content/docs/fr/guides/claude-code.md @@ -695,7 +695,7 @@ Sur l’adaptateur Anthropic prévu, les blocs signés non masqués (y compris t **Taxonomie des erreurs :** 400 `invalid_request_error`, 401 `authentication_error`, 402 `billing_error`, 403 `permission_error`, 404 `not_found_error`, 409 `conflict_error`, 413 `request_too_large`, 429 `rate_limit_error`, 504 `timeout_error`, 529 `overloaded_error`, -autre 5xx `api_error`. `Retry-After` est conservé. +autre 5xx `api_error`. `Retry-After` est envoyé en secondes entières (une date HTTP devient le nombre de secondes restantes), plafonné à huit jours. ## Mise en cache des prompts et utilisation des jetons diff --git a/docs-site/src/content/docs/fr/guides/web-dashboard.md b/docs-site/src/content/docs/fr/guides/web-dashboard.md index 6b11e7cc80e..7cbabfafc72 100644 --- a/docs-site/src/content/docs/fr/guides/web-dashboard.md +++ b/docs-site/src/content/docs/fr/guides/web-dashboard.md @@ -93,7 +93,7 @@ Les vues Utilisation, Tableau de bord, Fournisseurs, Catalogue des fournisseurs ### Filtrer les requêtes -Le détail d’une requête privilégie la cause d’échec amont enregistrée plutôt qu’un message générique d’erreur du proxy. Le nombre d’envois physiques est toujours affiché lorsqu’il est valide ; une comptabilité absente ou invalide affiche **Unavailable**, et non zéro. **Retries** compte les envois après le premier uniquement lorsqu’une seule tentative entièrement réglée et cohérente est enregistrée. Les tentatives multiples, les comptabilités non résolues ou incohérentes et les normalisations avec perte omettent les retries au lieu d’en inventer. Une cause persistante inconnue revient au titre fondé sur le statut, sans attribution brute. +Le détail d’une requête privilégie la cause d’échec amont enregistrée plutôt qu’un message générique d’erreur du proxy. Le nombre d’envois physiques est toujours affiché lorsqu’il est valide ; une comptabilité absente ou invalide affiche **Unavailable**, et non zéro. **Retries** compte les envois après le premier uniquement lorsqu’une seule tentative entièrement réglée et cohérente est enregistrée. Les tentatives multiples, les comptabilités non résolues ou incohérentes et les normalisations avec perte omettent les retries au lieu d’en inventer. Une cause persistante inconnue revient au titre fondé sur le statut, sans attribution brute. **Upstream reason** affiche une condition fournisseur classée (par exemple limite de débit atteinte, quota ou crédits épuisés, fenêtre de contexte dépassée, emplacement non pris en charge, vérification du compte requise ou modèle indisponible), et **Failure detail** affiche un texte rédigé par le proxy, comme un délai d’inactivité ou une limite d’octets ; les nouvelles lignes ne conservent pas le texte d’erreur propre au fournisseur. D’anciens fichiers `usage.jsonl` peuvent encore le contenir, mais le tableau de bord l’écarte à la lecture. Les filtres combinent interface, requêtes interceptées, fournisseur, modèle exact, statut, période, vitesse et identifiant de conversation dans le journal chargé. Les choix incluent les tentatives de repli ; les modèles ignorent la casse et les espaces externes, sans correspondance partielle. Un choix disparu revient à Tous. diff --git a/docs-site/src/content/docs/guides/claude-code.md b/docs-site/src/content/docs/guides/claude-code.md index 169e401349c..ed1152d6289 100644 --- a/docs-site/src/content/docs/guides/claude-code.md +++ b/docs-site/src/content/docs/guides/claude-code.md @@ -1097,7 +1097,7 @@ on the schema to reject a malformed argument. **Error taxonomy:** 400 `invalid_request_error`, 401 `authentication_error`, 402 `billing_error`, 403 `permission_error`, 404 `not_found_error`, 409 `conflict_error`, 413 `request_too_large`, 429 `rate_limit_error`, 504 `timeout_error`, 529 `overloaded_error`, -other 5xx `api_error`. `Retry-After` is preserved. +other 5xx `api_error`. `Retry-After` is sent as whole seconds (an HTTP date becomes the remaining seconds), capped at eight days. ## Prompt caching and token usage diff --git a/docs-site/src/content/docs/guides/web-dashboard.md b/docs-site/src/content/docs/guides/web-dashboard.md index 7426627eeab..81d8950e5fc 100644 --- a/docs-site/src/content/docs/guides/web-dashboard.md +++ b/docs-site/src/content/docs/guides/web-dashboard.md @@ -154,7 +154,7 @@ timer. Requests already sent upstream retain their original credentials. ### Filtering request logs -Request details prefer a recognized upstream failure cause over generic proxy-error copy. Physical sends are always shown when valid; missing or invalid accounting shows **Unavailable**, not zero. **Retries** counts sends after the first only when one fully settled, consistent attempt is recorded. Multi-attempt, unresolved, inconsistent, or lossy-normalized records omit retries instead of inventing them. Unknown persisted causes use the status-based headline without raw attribution. +Request details prefer a recognized upstream failure cause over generic proxy-error copy. Physical sends are always shown when valid; missing or invalid accounting shows **Unavailable**, not zero. **Retries** counts sends after the first only when one fully settled, consistent attempt is recorded. Multi-attempt, unresolved, inconsistent, or lossy-normalized records omit retries instead of inventing them. Unknown persisted causes use the status-based headline without raw attribution. **Upstream reason** shows a classified provider condition (for example rate limited, quota or credits exhausted, context window exceeded, location not supported, account verification required, or model unavailable), and **Failure detail** shows text written by the proxy, such as a stall timeout or byte-cap limit; new rows do not store the provider's own error text. Older `usage.jsonl` files may still contain it, but the dashboard drops it when reading them. A proxy replay refusal keeps HTTP 429 and error code `upstream_reset_replay_refused`, but its request and attempt failure cause is `transport-ambiguous`, with resend permission diff --git a/docs-site/src/content/docs/ja/guides/claude-code.md b/docs-site/src/content/docs/ja/guides/claude-code.md index f07c99ff38e..fb67723e542 100644 --- a/docs-site/src/content/docs/ja/guides/claude-code.md +++ b/docs-site/src/content/docs/ja/guides/claude-code.md @@ -568,7 +568,7 @@ role、`tool_use_id` のない `tool_result`、id/name のない `tool_use`、na **エラー分類:** 400 `invalid_request_error`、401 `authentication_error`、 402 `billing_error`、403 `permission_error`、404 `not_found_error`、409 `conflict_error`、 413 `request_too_large`、429 `rate_limit_error`、504 `timeout_error`、529 `overloaded_error`、 -それ以外の 5xx は `api_error` です。`Retry-After` はそのまま維持します。 +それ以外の 5xx は `api_error` です。`Retry-After` は整数の秒数で送信し(HTTP 日付は残り秒数に変換)、上限は 8 日です。 ## プロンプトキャッシュとトークン使用量 diff --git a/docs-site/src/content/docs/ja/guides/web-dashboard.md b/docs-site/src/content/docs/ja/guides/web-dashboard.md index eb8c7522c07..c218a30e41f 100644 --- a/docs-site/src/content/docs/ja/guides/web-dashboard.md +++ b/docs-site/src/content/docs/ja/guides/web-dashboard.md @@ -70,7 +70,7 @@ bun run dev:gui ### リクエストログの絞り込み -リクエスト詳細では、一般的なプロキシエラーの文言よりも、記録されたアップストリームの失敗原因を優先して表示します。物理的なアップストリーム送信数は有効な場合に常に表示し、会計情報がない、または無効な場合は 0 ではなく **Unavailable** と表示します。**Retries** は、完全に精算され整合する単一の試行が記録されている場合に限り、最初の送信以降の追加送信回数として表示します。複数の試行、未解決・不整合な会計、または損失のある attempt 正規化では、再試行回数を推測せず非表示にします。未知の永続化された原因は、状態に基づく見出しに戻ります。 +リクエスト詳細では、一般的なプロキシエラーの文言よりも、記録されたアップストリームの失敗原因を優先して表示します。物理的なアップストリーム送信数は有効な場合に常に表示し、会計情報がない、または無効な場合は 0 ではなく **Unavailable** と表示します。**Retries** は、完全に精算され整合する単一の試行が記録されている場合に限り、最初の送信以降の追加送信回数として表示します。複数の試行、未解決・不整合な会計、または損失のある attempt 正規化では、再試行回数を推測せず非表示にします。未知の永続化された原因は、状態に基づく見出しに戻ります。**Upstream reason** には分類されたプロバイダーの状態(レート制限、クォータまたはクレジットの枯渇、コンテキストウィンドウ超過、未対応の地域、アカウント確認が必要、モデル利用不可など)を、**Failure detail** にはストールタイムアウトやバイト上限などプロキシが記述したテキストを表示します。新しい行にはプロバイダー自身のエラーテキストを保存しません。古い `usage.jsonl` ファイルには残っている場合がありますが、ダッシュボードは読み込み時にそれを破棄します。 Logsではサーフェス、インターセプトされたリクエスト、プロバイダー、完全なモデル名、ステータス、時間、速度、会話IDを組み合わせて、読み込み済みログを絞り込みます。選択肢にはフォールバック試行も含まれます。モデル名は大文字小文字と前後の空白を無視しますが、部分一致ではありません。ログから消えた選択肢は全件に戻ります。 diff --git a/docs-site/src/content/docs/ko/guides/claude-code.md b/docs-site/src/content/docs/ko/guides/claude-code.md index e6f0ebe5d2b..c27e736927e 100644 --- a/docs-site/src/content/docs/ko/guides/claude-code.md +++ b/docs-site/src/content/docs/ko/guides/claude-code.md @@ -636,7 +636,7 @@ role, `tool_use_id` 없는 `tool_result`, id/name 없는 `tool_use`, name 없는 **오류 분류:** 400 `invalid_request_error`, 401 `authentication_error`, 402 `billing_error`, 403 `permission_error`, 404 `not_found_error`, 409 `conflict_error`, 413 `request_too_large`, 429 `rate_limit_error`, 504 `timeout_error`, 529 `overloaded_error`, -그 밖의 5xx는 `api_error`예요. `Retry-After`는 그대로 유지해요. +그 밖의 5xx는 `api_error`예요. `Retry-After`는 정수 초로 보내며(HTTP 날짜는 남은 초로 바꿔요) 최대 8일로 제한해요. ## 프롬프트 캐싱과 토큰 사용량 diff --git a/docs-site/src/content/docs/ko/guides/web-dashboard.md b/docs-site/src/content/docs/ko/guides/web-dashboard.md index c34d9d2a70c..d8d719d67fe 100644 --- a/docs-site/src/content/docs/ko/guides/web-dashboard.md +++ b/docs-site/src/content/docs/ko/guides/web-dashboard.md @@ -70,7 +70,7 @@ Usage, Dashboard, 공급자 작업 화면·카탈로그, API 키 화면은 읽 ### 요청 로그 필터 -요청 상세 화면은 일반 프록시 오류 문구 대신 기록된 업스트림 실패 원인을 우선 표시합니다. 물리적 업스트림 전송 수는 유효할 때 항상 표시하며, 회계 정보가 없거나 유효하지 않으면 0이 아니라 **Unavailable**로 표시합니다. **Retries**는 완전히 정산되고 일관된 단일 시도가 기록된 경우에만 첫 전송 이후 추가 전송 횟수로 표시합니다. 여러 시도, 미해결·불일치 회계 또는 손실 있는 attempt 정규화에서는 재시도 횟수를 만들어 내지 않고 숨깁니다. 알 수 없는 영속 원인은 상태 기반 제목으로 돌아갑니다. +요청 상세 화면은 일반 프록시 오류 문구 대신 기록된 업스트림 실패 원인을 우선 표시합니다. 물리적 업스트림 전송 수는 유효할 때 항상 표시하며, 회계 정보가 없거나 유효하지 않으면 0이 아니라 **Unavailable**로 표시합니다. **Retries**는 완전히 정산되고 일관된 단일 시도가 기록된 경우에만 첫 전송 이후 추가 전송 횟수로 표시합니다. 여러 시도, 미해결·불일치 회계 또는 손실 있는 attempt 정규화에서는 재시도 횟수를 만들어 내지 않고 숨깁니다. 알 수 없는 영속 원인은 상태 기반 제목으로 돌아갑니다. **Upstream reason**은 분류된 공급자 상태(속도 제한, 할당량 또는 크레딧 소진, 컨텍스트 창 초과, 지원되지 않는 위치, 계정 인증 필요, 모델 사용 불가 등)를, **Failure detail**은 정지 시간 초과나 바이트 상한처럼 프록시가 작성한 텍스트를 표시합니다. 새 행에는 공급자 자체의 오류 텍스트를 저장하지 않습니다. 이전 `usage.jsonl` 파일에는 남아 있을 수 있지만, 대시보드는 읽을 때 이를 버립니다. Logs에서는 클라이언트 종류, 가로챈 요청, 공급자, 정확한 모델명, 상태, 시간, 속도, 대화 ID 조건을 함께 적용할 수 있습니다. 현재 불러온 로그만 필터링하며, diff --git a/docs-site/src/content/docs/ru/guides/claude-code.md b/docs-site/src/content/docs/ru/guides/claude-code.md index 298ad33242c..5d93a3efab4 100644 --- a/docs-site/src/content/docs/ru/guides/claude-code.md +++ b/docs-site/src/content/docs/ru/guides/claude-code.md @@ -605,7 +605,7 @@ id/name; именованный `tool_choice` без имени. **Таксономия ошибок:** 400 `invalid_request_error`, 401 `authentication_error`, 402 `billing_error`, 403 `permission_error`, 404 `not_found_error`, 409 `conflict_error`, 413 `request_too_large`, 429 `rate_limit_error`, 504 `timeout_error`, 529 `overloaded_error`, -прочие 5xx — `api_error`. `Retry-After` сохраняется. +прочие 5xx — `api_error`. `Retry-After` передаётся целым числом секунд (HTTP-дата переводится в оставшиеся секунды) и ограничивается восемью днями. ## Кеширование промптов и расход токенов diff --git a/docs-site/src/content/docs/ru/guides/web-dashboard.md b/docs-site/src/content/docs/ru/guides/web-dashboard.md index 1d912d7f48e..58a72e5dd61 100644 --- a/docs-site/src/content/docs/ru/guides/web-dashboard.md +++ b/docs-site/src/content/docs/ru/guides/web-dashboard.md @@ -73,7 +73,7 @@ bun run dev:gui ### Фильтрация запросов -В деталях запроса распознанная причина сбоя upstream имеет приоритет над общим текстом об ошибке прокси. Число физических отправок всегда показывается, если оно корректно; при отсутствующем или некорректном учёте отображается **Unavailable**, а не ноль. **Retries** считает отправки после первой только при наличии одной попытки с полностью урегулированным и согласованным учётом. При нескольких попытках, незавершённом или противоречивом учёте и при нормализации с потерями retries не выводятся, вместо того чтобы выдумывать их. Неизвестные сохранённые причины возвращают заголовок по статусу без сырой атрибуции. +В деталях запроса распознанная причина сбоя upstream имеет приоритет над общим текстом об ошибке прокси. Число физических отправок всегда показывается, если оно корректно; при отсутствующем или некорректном учёте отображается **Unavailable**, а не ноль. **Retries** считает отправки после первой только при наличии одной попытки с полностью урегулированным и согласованным учётом. При нескольких попытках, незавершённом или противоречивом учёте и при нормализации с потерями retries не выводятся, вместо того чтобы выдумывать их. Неизвестные сохранённые причины возвращают заголовок по статусу без сырой атрибуции. **Upstream reason** показывает классифицированное состояние провайдера (например, превышен лимит запросов, исчерпаны квота или кредиты, превышено окно контекста, регион не поддерживается, требуется подтверждение аккаунта или модель недоступна), а **Failure detail** — текст, сформированный прокси, например о тайм-ауте простоя или лимите байтов; новые строки не сохраняют собственный текст ошибки провайдера. Он может оставаться в старых файлах `usage.jsonl`, но панель отбрасывает его при чтении. Фильтры объединяют источник, перехваченные запросы, провайдера, точную модель, статус, время, скорость и ID диалога в загруженном журнале. Варианты включают резервные попытки; модель сравнивается без учёта регистра и крайних пробелов, но не по подстроке. Исчезнувший вариант сбрасывается на все записи. diff --git a/docs-site/src/content/docs/tr/guides/claude-code.md b/docs-site/src/content/docs/tr/guides/claude-code.md index 66b385d0809..61e45749515 100644 --- a/docs-site/src/content/docs/tr/guides/claude-code.md +++ b/docs-site/src/content/docs/tr/guides/claude-code.md @@ -770,7 +770,7 @@ kimlik/ad içermeyen `tool_use`; ad içermeyen adlandırılmış `tool_choice`. 402 `billing_error`, 403 `permission_error`, 404 `not_found_error`, 409 `conflict_error`, 413 `request_too_large`, 429 `rate_limit_error`, 504 `timeout_error`, 529 `overloaded_error`, diğer 5xx `api_error`. `Retry-After` -korunur. +tam saniye olarak gönderilir (HTTP tarihi kalan saniyeye çevrilir) ve en fazla sekiz gündür. ## İstem önbellekleme ve token kullanımı diff --git a/docs-site/src/content/docs/tr/guides/web-dashboard.md b/docs-site/src/content/docs/tr/guides/web-dashboard.md index fee8d7b1d78..16d07ad6a4c 100644 --- a/docs-site/src/content/docs/tr/guides/web-dashboard.md +++ b/docs-site/src/content/docs/tr/guides/web-dashboard.md @@ -94,7 +94,7 @@ Kullanım, panel, sağlayıcı çalışma alanı, sağlayıcı kataloğu ve API ### İstek günlüklerini filtreleme -İstek ayrıntıları, genel proxy hatası metni yerine kaydedilmiş upstream hata nedenini öncelikli gösterir. Fiziksel gönderim sayısı geçerliyse her zaman gösterilir; eksik veya geçersiz muhasebe bilgisi sıfır yerine **Unavailable** olarak görüntülenir. **Retries**, yalnızca muhasebesi tamamen kesinleşmiş ve tutarlı tek bir deneme kaydı bulunduğunda ilk gönderimden sonraki ek gönderim sayısını gösterir. Birden fazla deneme, çözümlenmemiş veya tutarsız muhasebe ve kayıplı attempt normalizasyonu, uydurma yeniden deneme sayısı yerine retries alanını gizler. Bilinmeyen kalıcı nedenler, ham atıf olmadan durum tabanlı başlığa döner. +İstek ayrıntıları, genel proxy hatası metni yerine kaydedilmiş upstream hata nedenini öncelikli gösterir. Fiziksel gönderim sayısı geçerliyse her zaman gösterilir; eksik veya geçersiz muhasebe bilgisi sıfır yerine **Unavailable** olarak görüntülenir. **Retries**, yalnızca muhasebesi tamamen kesinleşmiş ve tutarlı tek bir deneme kaydı bulunduğunda ilk gönderimden sonraki ek gönderim sayısını gösterir. Birden fazla deneme, çözümlenmemiş veya tutarsız muhasebe ve kayıplı attempt normalizasyonu, uydurma yeniden deneme sayısı yerine retries alanını gizler. Bilinmeyen kalıcı nedenler, ham atıf olmadan durum tabanlı başlığa döner. **Upstream reason**, sınıflandırılmış bir sağlayıcı durumunu (örneğin hız sınırı, kota veya kredinin tükenmesi, bağlam penceresinin aşılması, desteklenmeyen konum, hesap doğrulaması gerekmesi veya modelin kullanılamaması), **Failure detail** ise takılma zaman aşımı veya bayt sınırı gibi proxy tarafından yazılan metni gösterir; yeni satırlar sağlayıcının kendi hata metnini saklamaz. Eski `usage.jsonl` dosyalarında hâlâ bulunabilir, ancak pano okurken bu metni atar. Filtreler yüklü günlükte yüzey, yakalanan istekler, sağlayıcı, tam model adı, durum, zaman, hız ve konuşma kimliğini birleştirir. Seçenekler yedek denemeleri de içerir; model eşleşmesi büyük/küçük harfi ve dış boşlukları yok sayar, kısmi adları eşleştirmez. Kaybolan seçenek tüm kayıtlara döner. diff --git a/docs-site/src/content/docs/zh-cn/guides/claude-code.md b/docs-site/src/content/docs/zh-cn/guides/claude-code.md index d7575506f5a..f570743571c 100644 --- a/docs-site/src/content/docs/zh-cn/guides/claude-code.md +++ b/docs-site/src/content/docs/zh-cn/guides/claude-code.md @@ -531,7 +531,7 @@ role;`tool_result` 缺少 `tool_use_id`;`tool_use` 缺少 id/name;指定 **错误分类:**400 `invalid_request_error`、401 `authentication_error`、 402 `billing_error`、403 `permission_error`、404 `not_found_error`、409 `conflict_error`、 413 `request_too_large`、429 `rate_limit_error`、504 `timeout_error`、529 `overloaded_error`, -其他 5xx 为 `api_error`。`Retry-After` 会保留。 +其他 5xx 为 `api_error`。`Retry-After` 以整数秒发送(HTTP 日期会换算为剩余秒数),上限为 8 天。 ## 提示缓存与 token 用量 diff --git a/docs-site/src/content/docs/zh-cn/guides/web-dashboard.md b/docs-site/src/content/docs/zh-cn/guides/web-dashboard.md index 2c2cde7bd9f..9c40d009abe 100644 --- a/docs-site/src/content/docs/zh-cn/guides/web-dashboard.md +++ b/docs-site/src/content/docs/zh-cn/guides/web-dashboard.md @@ -70,7 +70,7 @@ bun run dev:gui ### 筛选请求日志 -请求详情优先显示已记录的上游失败原因,而不是通用的代理错误文案。有效的物理上游发送次数始终显示;缺失或无效的会计信息显示为 **Unavailable**,而不是 0。只有在记录到一次已完全结算且一致的尝试时,**Retries** 才显示首次发送后的额外发送次数。多次尝试、未解决或不一致的会计信息,以及有损失的 attempt 归一化,都不会编造重试次数。未知的持久化原因回退为基于状态的标题。 +请求详情优先显示已记录的上游失败原因,而不是通用的代理错误文案。有效的物理上游发送次数始终显示;缺失或无效的会计信息显示为 **Unavailable**,而不是 0。只有在记录到一次已完全结算且一致的尝试时,**Retries** 才显示首次发送后的额外发送次数。多次尝试、未解决或不一致的会计信息,以及有损失的 attempt 归一化,都不会编造重试次数。未知的持久化原因回退为基于状态的标题。**Upstream reason** 显示经过分类的提供方状态(例如速率受限、配额或额度耗尽、超出上下文窗口、所在地区不受支持、需要验证账户、模型不可用),**Failure detail** 显示由代理撰写的文本,例如停滞超时或字节上限;新记录不会保存提供方自身的错误文本。较旧的 `usage.jsonl` 文件中可能仍有此类文本,但仪表盘读取时会将其丢弃。 Logs 可组合界面、被拦截请求、提供商、完整模型名、状态、时间、速度和会话 ID,筛选当前已加载的日志。选项包含回退尝试;模型匹配忽略大小写及首尾空格,但不做部分匹配。日志中消失的选项恢复为全部。 diff --git a/docs-site/src/content/docs/zh-tw/guides/claude-code.md b/docs-site/src/content/docs/zh-tw/guides/claude-code.md index bba0718e4dd..74746b8b60b 100644 --- a/docs-site/src/content/docs/zh-tw/guides/claude-code.md +++ b/docs-site/src/content/docs/zh-tw/guides/claude-code.md @@ -588,7 +588,7 @@ role;`tool_result` 缺少 `tool_use_id`;`tool_use` 缺少 id/name;指定 **錯誤分類:**400 `invalid_request_error`、401 `authentication_error`、 402 `billing_error`、403 `permission_error`、404 `not_found_error`、409 `conflict_error`、 413 `request_too_large`、429 `rate_limit_error`、504 `timeout_error`、529 `overloaded_error`, -其他 5xx 為 `api_error`。`Retry-After` 會保留。 +其他 5xx 為 `api_error`。`Retry-After` 以整數秒傳送(HTTP 日期會換算為剩餘秒數),上限為 8 天。 ## 提示快取與 token 用量 diff --git a/docs-site/src/content/docs/zh-tw/guides/web-dashboard.md b/docs-site/src/content/docs/zh-tw/guides/web-dashboard.md index ea24d88142b..fe69dcaa07f 100644 --- a/docs-site/src/content/docs/zh-tw/guides/web-dashboard.md +++ b/docs-site/src/content/docs/zh-tw/guides/web-dashboard.md @@ -79,7 +79,7 @@ GUI session 簽發到服務的頁面中,並在到期或代理重啟時靜默 ### 篩選請求日誌 -請求詳細資訊會優先顯示已記錄的上游失敗原因,而不是通用的代理錯誤文案。有效的上游實際傳送次數一律顯示;缺少或無效的記帳資訊則顯示 **Unavailable**,而非 0。只有在記錄到一次已完全結算且一致的嘗試時,**Retries** 才顯示首次傳送後的額外傳送次數。多次嘗試、未解決或不一致的記帳資訊,以及有損失的 attempt 正規化,都不會憑空產生重試次數。未知的持久化原因會回退為依狀態顯示的標題。 +請求詳細資訊會優先顯示已記錄的上游失敗原因,而不是通用的代理錯誤文案。有效的上游實際傳送次數一律顯示;缺少或無效的記帳資訊則顯示 **Unavailable**,而非 0。只有在記錄到一次已完全結算且一致的嘗試時,**Retries** 才顯示首次傳送後的額外傳送次數。多次嘗試、未解決或不一致的記帳資訊,以及有損失的 attempt 正規化,都不會憑空產生重試次數。未知的持久化原因會回退為依狀態顯示的標題。**Upstream reason** 顯示經過分類的供應商狀態(例如速率受限、配額或額度用盡、超出上下文視窗、所在地區不受支援、需要驗證帳戶、模型無法使用),**Failure detail** 顯示由代理撰寫的文字,例如停滯逾時或位元組上限;新記錄不會儲存供應商本身的錯誤文字。較舊的 `usage.jsonl` 檔案中可能仍有此類文字,但儀表板讀取時會將其捨棄。 Logs 可組合介面、被攔截請求、供應商、完整模型名稱、狀態、時間、速度和對話 ID,篩選目前已載入的日誌。選項包含回退嘗試;模型比對忽略大小寫及頭尾空白,但不做部分比對。日誌中消失的選項恢復為全部。 diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index affe092dcec..d09851ddcb0 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -1330,6 +1330,35 @@ export const de: Record = { "logs.detail.estimate.priority_lower_bound": "Der bestätigte Priority-Preis ist nicht verfügbar; die angezeigte Schätzung ist eine bekannte Untergrenze.", "logs.col.error": "Fehler", "logs.col.upstreamReason": "Upstream-Grund", + "logs.col.failureDetail": "Fehlerdetail", + "logs.detail.condition.authFailed": "Zugangsdaten abgelehnt", + "logs.detail.condition.accessDenied": "Zugriff verweigert", + "logs.detail.condition.contextOverflow": "Kontextfenster überschritten", + "logs.detail.condition.locationUnsupported": "Standort nicht unterstützt", + "logs.detail.condition.accountVerificationRequired": "Kontoverifizierung erforderlich", + "logs.detail.condition.billingExhausted": "Kontingent oder Guthaben aufgebraucht", + "logs.detail.condition.modelUnavailable": "Modell nicht verfügbar", + "logs.detail.condition.rateLimited": "Ratenlimit erreicht", + "logs.detail.condition.upstreamUnavailable": "Anbieter nicht verfügbar", + "logs.detail.condition.upstreamFailed": "Anbieter fehlgeschlagen", + "logs.detail.condition.requestRejected": "Anfrage abgelehnt", + "logs.failureDetail.providerError": "Der Anbieter hat einen Fehler zurückgegeben", + "logs.failureDetail.providerErrorTyped": "Der Anbieter hat einen Fehler zurückgegeben ({type})", + "logs.failureDetail.headerTimeout": "Zeitüberschreitung beim Warten auf Antwort-Header", + "logs.failureDetail.headerTimeoutAfter": "Zeitüberschreitung beim Warten auf Antwort-Header nach {value} ms", + "logs.failureDetail.connectTimeout": "Verbindung zum Anbieter nach {value} ms abgelaufen", + "logs.failureDetail.connectFailed": "Verbindung zum Anbieter nicht möglich", + "logs.failureDetail.clientClosed": "Der Client hat die Anfrage geschlossen", + "logs.failureDetail.bodyStall": "Der Antwortinhalt ist {value} ms lang stehen geblieben", + "logs.failureDetail.bodyOverflow": "Der Antwortinhalt hat {value} Bytes überschritten", + "logs.failureDetail.streamErrorStop": "Der Anbieter hat den Durchgang mit einem Fehler beendet", + "logs.failureDetail.streamEndedEarly": "Der Antwortstream endete vor seinem letzten Ereignis", + "logs.failureDetail.streamFailed": "Der Antwortstream ist fehlgeschlagen", + "logs.failureDetail.outputLimit": "Die Ausgabe hat das angeforderte Token-Limit erreicht", + "logs.failureDetail.stallTimeout": "Der Anbieter hat innerhalb des Stall-Timeouts keine Daten gesendet", + "logs.failureDetail.adapterEof": "Der Anbieterstream endete ohne abschließendes Ereignis", + "logs.failureDetail.generationTimeout": "Das geroutete Modell hat innerhalb von {value} ms nicht geantwortet", + "logs.failureDetail.turnInactivity": "Der Durchgang war {value} ms lang inaktiv", "logs.col.duration": "Dauer", "logs.modelTooltip.model": "Modell", "logs.modelTooltip.resolvedModel": "aufgelöstes Modell", diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index 4f4cd4ffe0f..9905eace401 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -1388,6 +1388,35 @@ export const en = { "logs.detail.estimate.priority_lower_bound": "The confirmed Priority price is unavailable; the displayed estimate is a known lower bound.", "logs.col.error": "Error", "logs.col.upstreamReason": "Upstream reason", + "logs.col.failureDetail": "Failure detail", + "logs.detail.condition.authFailed": "Credentials rejected", + "logs.detail.condition.accessDenied": "Access denied", + "logs.detail.condition.contextOverflow": "Context window exceeded", + "logs.detail.condition.locationUnsupported": "Location not supported", + "logs.detail.condition.accountVerificationRequired": "Account verification required", + "logs.detail.condition.billingExhausted": "Quota or credits exhausted", + "logs.detail.condition.modelUnavailable": "Model unavailable", + "logs.detail.condition.rateLimited": "Rate limited", + "logs.detail.condition.upstreamUnavailable": "Provider unavailable", + "logs.detail.condition.upstreamFailed": "Provider failed", + "logs.detail.condition.requestRejected": "Request rejected", + "logs.failureDetail.providerError": "The provider returned an error", + "logs.failureDetail.providerErrorTyped": "The provider returned an error ({type})", + "logs.failureDetail.headerTimeout": "Timed out waiting for response headers", + "logs.failureDetail.headerTimeoutAfter": "Timed out waiting for response headers after {value} ms", + "logs.failureDetail.connectTimeout": "Connecting to the provider timed out after {value} ms", + "logs.failureDetail.connectFailed": "Could not connect to the provider", + "logs.failureDetail.clientClosed": "The client closed the request", + "logs.failureDetail.bodyStall": "The response body stalled for {value} ms", + "logs.failureDetail.bodyOverflow": "The response body exceeded {value} bytes", + "logs.failureDetail.streamErrorStop": "The provider ended the turn with an error", + "logs.failureDetail.streamEndedEarly": "The response stream ended before its final event", + "logs.failureDetail.streamFailed": "The response stream failed", + "logs.failureDetail.outputLimit": "Output reached the requested token limit", + "logs.failureDetail.stallTimeout": "The provider sent no data within the stall timeout", + "logs.failureDetail.adapterEof": "The provider stream ended without a final event", + "logs.failureDetail.generationTimeout": "The routed model sent no response within {value} ms", + "logs.failureDetail.turnInactivity": "The turn was inactive for {value} ms", "logs.col.duration": "Duration", "logs.modelTooltip.model": "model", "logs.modelTooltip.resolvedModel": "resolved model", diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index 4b8cf58b1de..16970c283ee 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -1369,6 +1369,35 @@ export const fr: Record = { "logs.detail.estimate.priority_lower_bound": "Le tarif Priority confirmé n’est pas disponible ; l’estimation affichée est une borne inférieure connue.", "logs.col.error": "Erreur", "logs.col.upstreamReason": "Motif en amont", + "logs.col.failureDetail": "Détail de l'échec", + "logs.detail.condition.authFailed": "Identifiants refusés", + "logs.detail.condition.accessDenied": "Accès refusé", + "logs.detail.condition.contextOverflow": "Fenêtre de contexte dépassée", + "logs.detail.condition.locationUnsupported": "Emplacement non pris en charge", + "logs.detail.condition.accountVerificationRequired": "Vérification du compte requise", + "logs.detail.condition.billingExhausted": "Quota ou crédits épuisés", + "logs.detail.condition.modelUnavailable": "Modèle indisponible", + "logs.detail.condition.rateLimited": "Limite de débit atteinte", + "logs.detail.condition.upstreamUnavailable": "Fournisseur indisponible", + "logs.detail.condition.upstreamFailed": "Échec du fournisseur", + "logs.detail.condition.requestRejected": "Requête refusée", + "logs.failureDetail.providerError": "Le fournisseur a renvoyé une erreur", + "logs.failureDetail.providerErrorTyped": "Le fournisseur a renvoyé une erreur ({type})", + "logs.failureDetail.headerTimeout": "Délai dépassé en attendant les en-têtes de réponse", + "logs.failureDetail.headerTimeoutAfter": "Délai dépassé en attendant les en-têtes de réponse après {value} ms", + "logs.failureDetail.connectTimeout": "La connexion au fournisseur a expiré après {value} ms", + "logs.failureDetail.connectFailed": "Impossible de se connecter au fournisseur", + "logs.failureDetail.clientClosed": "Le client a fermé la requête", + "logs.failureDetail.bodyStall": "Le corps de la réponse est resté bloqué pendant {value} ms", + "logs.failureDetail.bodyOverflow": "Le corps de la réponse a dépassé {value} octets", + "logs.failureDetail.streamErrorStop": "Le fournisseur a terminé le tour avec une erreur", + "logs.failureDetail.streamEndedEarly": "Le flux de réponse s'est terminé avant son dernier événement", + "logs.failureDetail.streamFailed": "Le flux de réponse a échoué", + "logs.failureDetail.outputLimit": "La sortie a atteint la limite de jetons demandée", + "logs.failureDetail.stallTimeout": "Le fournisseur n'a envoyé aucune donnée dans le délai d'inactivité", + "logs.failureDetail.adapterEof": "Le flux du fournisseur s'est terminé sans événement final", + "logs.failureDetail.generationTimeout": "Le modèle routé n'a pas répondu dans un délai de {value} ms", + "logs.failureDetail.turnInactivity": "Le tour est resté inactif pendant {value} ms", "logs.col.duration": "Durée", "logs.modelTooltip.model": "modèle", "logs.modelTooltip.resolvedModel": "modèle résolu", diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index 4c99bb76162..ec377277851 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -1271,6 +1271,35 @@ export const ja: Record = { "logs.detail.estimate.priority_lower_bound": "確認済みの Priority 価格を利用できないため、表示される見積もりは既知の下限です。", "logs.col.error": "エラー", "logs.col.upstreamReason": "上流の理由", + "logs.col.failureDetail": "失敗の詳細", + "logs.detail.condition.authFailed": "認証情報が拒否されました", + "logs.detail.condition.accessDenied": "アクセスが拒否されました", + "logs.detail.condition.contextOverflow": "コンテキストウィンドウを超過", + "logs.detail.condition.locationUnsupported": "この地域はサポートされていません", + "logs.detail.condition.accountVerificationRequired": "アカウント認証が必要です", + "logs.detail.condition.billingExhausted": "クォータまたはクレジットが不足", + "logs.detail.condition.modelUnavailable": "モデルを利用できません", + "logs.detail.condition.rateLimited": "レート制限に達しました", + "logs.detail.condition.upstreamUnavailable": "プロバイダーを利用できません", + "logs.detail.condition.upstreamFailed": "プロバイダーでエラー", + "logs.detail.condition.requestRejected": "リクエストが拒否されました", + "logs.failureDetail.providerError": "プロバイダーがエラーを返しました", + "logs.failureDetail.providerErrorTyped": "プロバイダーがエラーを返しました({type})", + "logs.failureDetail.headerTimeout": "レスポンスヘッダーの待機がタイムアウトしました", + "logs.failureDetail.headerTimeoutAfter": "{value} ms 後にレスポンスヘッダーの待機がタイムアウトしました", + "logs.failureDetail.connectTimeout": "プロバイダーへの接続が {value} ms 後にタイムアウトしました", + "logs.failureDetail.connectFailed": "プロバイダーに接続できませんでした", + "logs.failureDetail.clientClosed": "クライアントがリクエストを閉じました", + "logs.failureDetail.bodyStall": "レスポンス本文が {value} ms 停止しました", + "logs.failureDetail.bodyOverflow": "レスポンス本文が {value} バイトを超えました", + "logs.failureDetail.streamErrorStop": "プロバイダーがエラーでターンを終了しました", + "logs.failureDetail.streamEndedEarly": "レスポンスストリームが最終イベントの前に終了しました", + "logs.failureDetail.streamFailed": "レスポンスストリームが失敗しました", + "logs.failureDetail.outputLimit": "出力が要求されたトークン上限に達しました", + "logs.failureDetail.stallTimeout": "プロバイダーが停止タイムアウト内にデータを送信しませんでした", + "logs.failureDetail.adapterEof": "プロバイダーのストリームが最終イベントなしで終了しました", + "logs.failureDetail.generationTimeout": "ルーティング先のモデルが {value} ms 以内に応答しませんでした", + "logs.failureDetail.turnInactivity": "ターンが {value} ms 非アクティブでした", "logs.col.duration": "所要時間", "logs.modelTooltip.model": "モデル", "logs.modelTooltip.resolvedModel": "解決後モデル", diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index b073cfed72c..770a9c87096 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -1369,6 +1369,35 @@ export const ko: Record = { "logs.detail.estimate.priority_lower_bound": "확인된 Priority 가격을 사용할 수 없어 표시된 추정치는 알려진 하한입니다.", "logs.col.error": "오류", "logs.col.upstreamReason": "업스트림 원인", + "logs.col.failureDetail": "실패 상세", + "logs.detail.condition.authFailed": "자격 증명 거부됨", + "logs.detail.condition.accessDenied": "접근 거부됨", + "logs.detail.condition.contextOverflow": "컨텍스트 창 초과", + "logs.detail.condition.locationUnsupported": "지원되지 않는 위치", + "logs.detail.condition.accountVerificationRequired": "계정 인증 필요", + "logs.detail.condition.billingExhausted": "할당량 또는 크레딧 소진", + "logs.detail.condition.modelUnavailable": "모델을 사용할 수 없음", + "logs.detail.condition.rateLimited": "속도 제한 도달", + "logs.detail.condition.upstreamUnavailable": "프로바이더 사용 불가", + "logs.detail.condition.upstreamFailed": "프로바이더 실패", + "logs.detail.condition.requestRejected": "요청 거부됨", + "logs.failureDetail.providerError": "공급자가 오류를 반환했습니다", + "logs.failureDetail.providerErrorTyped": "공급자가 오류를 반환했습니다 ({type})", + "logs.failureDetail.headerTimeout": "응답 헤더를 기다리다 시간이 초과되었습니다", + "logs.failureDetail.headerTimeoutAfter": "{value} ms 후 응답 헤더를 기다리다 시간이 초과되었습니다", + "logs.failureDetail.connectTimeout": "공급자 연결이 {value} ms 후 시간 초과되었습니다", + "logs.failureDetail.connectFailed": "공급자에 연결할 수 없습니다", + "logs.failureDetail.clientClosed": "클라이언트가 요청을 닫았습니다", + "logs.failureDetail.bodyStall": "응답 본문이 {value} ms 동안 멈췄습니다", + "logs.failureDetail.bodyOverflow": "응답 본문이 {value} 바이트를 초과했습니다", + "logs.failureDetail.streamErrorStop": "공급자가 오류로 턴을 종료했습니다", + "logs.failureDetail.streamEndedEarly": "응답 스트림이 마지막 이벤트 전에 끝났습니다", + "logs.failureDetail.streamFailed": "응답 스트림이 실패했습니다", + "logs.failureDetail.outputLimit": "출력이 요청한 토큰 한도에 도달했습니다", + "logs.failureDetail.stallTimeout": "공급자가 정지 시간 제한 안에 데이터를 보내지 않았습니다", + "logs.failureDetail.adapterEof": "공급자 스트림이 마지막 이벤트 없이 끝났습니다", + "logs.failureDetail.generationTimeout": "라우팅된 모델이 {value} ms 안에 응답하지 않았습니다", + "logs.failureDetail.turnInactivity": "턴이 {value} ms 동안 비활성 상태였습니다", "logs.col.duration": "소요 시간", "logs.modelTooltip.model": "모델", "logs.modelTooltip.resolvedModel": "해석된 모델", diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index f170560e262..c2871c9b07b 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -1383,6 +1383,35 @@ export const pt: Record = { "logs.detail.estimate.priority_lower_bound": "O preço Priority confirmado está indisponível; a estimativa exibida é um limite inferior conhecido.", "logs.col.error": "Erro", "logs.col.upstreamReason": "Motivo do upstream", + "logs.col.failureDetail": "Detalhe da falha", + "logs.detail.condition.authFailed": "Credenciais rejeitadas", + "logs.detail.condition.accessDenied": "Acesso negado", + "logs.detail.condition.contextOverflow": "Janela de contexto excedida", + "logs.detail.condition.locationUnsupported": "Local não suportado", + "logs.detail.condition.accountVerificationRequired": "Verificação da conta necessária", + "logs.detail.condition.billingExhausted": "Cota ou créditos esgotados", + "logs.detail.condition.modelUnavailable": "Modelo indisponível", + "logs.detail.condition.rateLimited": "Limite de taxa atingido", + "logs.detail.condition.upstreamUnavailable": "Provedor indisponível", + "logs.detail.condition.upstreamFailed": "Falha do provedor", + "logs.detail.condition.requestRejected": "Solicitação rejeitada", + "logs.failureDetail.providerError": "O provedor retornou um erro", + "logs.failureDetail.providerErrorTyped": "O provedor retornou um erro ({type})", + "logs.failureDetail.headerTimeout": "Tempo esgotado aguardando os cabeçalhos da resposta", + "logs.failureDetail.headerTimeoutAfter": "Tempo esgotado aguardando os cabeçalhos da resposta após {value} ms", + "logs.failureDetail.connectTimeout": "A conexão com o provedor expirou após {value} ms", + "logs.failureDetail.connectFailed": "Não foi possível conectar ao provedor", + "logs.failureDetail.clientClosed": "O cliente fechou a solicitação", + "logs.failureDetail.bodyStall": "O corpo da resposta ficou parado por {value} ms", + "logs.failureDetail.bodyOverflow": "O corpo da resposta excedeu {value} bytes", + "logs.failureDetail.streamErrorStop": "O provedor encerrou o turno com um erro", + "logs.failureDetail.streamEndedEarly": "O fluxo de resposta terminou antes do evento final", + "logs.failureDetail.streamFailed": "O fluxo de resposta falhou", + "logs.failureDetail.outputLimit": "A saída atingiu o limite de tokens solicitado", + "logs.failureDetail.stallTimeout": "O provedor não enviou dados dentro do tempo limite de inatividade", + "logs.failureDetail.adapterEof": "O fluxo do provedor terminou sem um evento final", + "logs.failureDetail.generationTimeout": "O modelo roteado não respondeu em {value} ms", + "logs.failureDetail.turnInactivity": "O turno ficou inativo por {value} ms", "logs.col.duration": "Duração", "logs.modelTooltip.model": "modelo", "logs.modelTooltip.resolvedModel": "modelo resolvido", diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index 7c7d951edde..3033fc66dcf 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -1347,6 +1347,35 @@ export const ru: Record = { "logs.detail.estimate.priority_lower_bound": "Подтверждённая цена Priority недоступна; показанная оценка является известной нижней границей.", "logs.col.error": "Ошибка", "logs.col.upstreamReason": "Причина от провайдера", + "logs.col.failureDetail": "Подробности сбоя", + "logs.detail.condition.authFailed": "Учётные данные отклонены", + "logs.detail.condition.accessDenied": "Доступ запрещён", + "logs.detail.condition.contextOverflow": "Превышено окно контекста", + "logs.detail.condition.locationUnsupported": "Регион не поддерживается", + "logs.detail.condition.accountVerificationRequired": "Требуется подтверждение аккаунта", + "logs.detail.condition.billingExhausted": "Квота или кредиты исчерпаны", + "logs.detail.condition.modelUnavailable": "Модель недоступна", + "logs.detail.condition.rateLimited": "Достигнут лимит запросов", + "logs.detail.condition.upstreamUnavailable": "Провайдер недоступен", + "logs.detail.condition.upstreamFailed": "Сбой провайдера", + "logs.detail.condition.requestRejected": "Запрос отклонён", + "logs.failureDetail.providerError": "Провайдер вернул ошибку", + "logs.failureDetail.providerErrorTyped": "Провайдер вернул ошибку ({type})", + "logs.failureDetail.headerTimeout": "Истекло время ожидания заголовков ответа", + "logs.failureDetail.headerTimeoutAfter": "Истекло время ожидания заголовков ответа через {value} мс", + "logs.failureDetail.connectTimeout": "Подключение к провайдеру истекло через {value} мс", + "logs.failureDetail.connectFailed": "Не удалось подключиться к провайдеру", + "logs.failureDetail.clientClosed": "Клиент закрыл запрос", + "logs.failureDetail.bodyStall": "Тело ответа простаивало {value} мс", + "logs.failureDetail.bodyOverflow": "Тело ответа превысило {value} байт", + "logs.failureDetail.streamErrorStop": "Провайдер завершил ход с ошибкой", + "logs.failureDetail.streamEndedEarly": "Поток ответа завершился до последнего события", + "logs.failureDetail.streamFailed": "Поток ответа завершился сбоем", + "logs.failureDetail.outputLimit": "Вывод достиг запрошенного лимита токенов", + "logs.failureDetail.stallTimeout": "Провайдер не передал данные в пределах тайм-аута простоя", + "logs.failureDetail.adapterEof": "Поток провайдера завершился без последнего события", + "logs.failureDetail.generationTimeout": "Маршрутизированная модель не ответила за {value} мс", + "logs.failureDetail.turnInactivity": "Ход был неактивен {value} мс", "logs.col.duration": "Длительность", "logs.modelTooltip.model": "модель", "logs.modelTooltip.resolvedModel": "разрешённая модель", diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index ab1fd6ee3b1..00d7a5f2769 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -1374,6 +1374,35 @@ export const tr: Record = { "logs.detail.estimate.priority_lower_bound": "Doğrulanan Priority fiyatı kullanılamıyor; gösterilen tahmin bilinen bir alt sınırdır.", "logs.col.error": "Hata", "logs.col.upstreamReason": "Yukarı akış nedeni", + "logs.col.failureDetail": "Hata ayrıntısı", + "logs.detail.condition.authFailed": "Kimlik bilgileri reddedildi", + "logs.detail.condition.accessDenied": "Erişim reddedildi", + "logs.detail.condition.contextOverflow": "Bağlam penceresi aşıldı", + "logs.detail.condition.locationUnsupported": "Konum desteklenmiyor", + "logs.detail.condition.accountVerificationRequired": "Hesap doğrulaması gerekli", + "logs.detail.condition.billingExhausted": "Kota veya kredi tükendi", + "logs.detail.condition.modelUnavailable": "Model kullanılamıyor", + "logs.detail.condition.rateLimited": "Hız sınırına ulaşıldı", + "logs.detail.condition.upstreamUnavailable": "Sağlayıcı kullanılamıyor", + "logs.detail.condition.upstreamFailed": "Sağlayıcı başarısız oldu", + "logs.detail.condition.requestRejected": "İstek reddedildi", + "logs.failureDetail.providerError": "Sağlayıcı bir hata döndürdü", + "logs.failureDetail.providerErrorTyped": "Sağlayıcı bir hata döndürdü ({type})", + "logs.failureDetail.headerTimeout": "Yanıt başlıkları beklenirken zaman aşımı oluştu", + "logs.failureDetail.headerTimeoutAfter": "{value} ms sonra yanıt başlıkları beklenirken zaman aşımı oluştu", + "logs.failureDetail.connectTimeout": "Sağlayıcıya bağlantı {value} ms sonra zaman aşımına uğradı", + "logs.failureDetail.connectFailed": "Sağlayıcıya bağlanılamadı", + "logs.failureDetail.clientClosed": "İstemci isteği kapattı", + "logs.failureDetail.bodyStall": "Yanıt gövdesi {value} ms boyunca durdu", + "logs.failureDetail.bodyOverflow": "Yanıt gövdesi {value} baytı aştı", + "logs.failureDetail.streamErrorStop": "Sağlayıcı turu bir hatayla sonlandırdı", + "logs.failureDetail.streamEndedEarly": "Yanıt akışı son olayından önce bitti", + "logs.failureDetail.streamFailed": "Yanıt akışı başarısız oldu", + "logs.failureDetail.outputLimit": "Çıktı istenen belirteç sınırına ulaştı", + "logs.failureDetail.stallTimeout": "Sağlayıcı takılma zaman aşımı içinde veri göndermedi", + "logs.failureDetail.adapterEof": "Sağlayıcı akışı son olay olmadan bitti", + "logs.failureDetail.generationTimeout": "Yönlendirilen model {value} ms içinde yanıt vermedi", + "logs.failureDetail.turnInactivity": "Tur {value} ms boyunca etkin değildi", "logs.col.duration": "Süre", "logs.modelTooltip.model": "model", "logs.modelTooltip.resolvedModel": "çözümlenen model", diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index 807a752f49e..263d12b2644 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -1368,6 +1368,35 @@ export const vi: Record = { "logs.detail.estimate.priority_lower_bound": "Giá Ưu tiên (Priority price) đã xác nhận không khả dụng; ước tính hiển thị là giới hạn dưới đã biết.", "logs.col.error": "Lỗi", "logs.col.upstreamReason": "Lý do upstream", + "logs.col.failureDetail": "Chi tiết lỗi", + "logs.detail.condition.authFailed": "Thông tin xác thực bị từ chối", + "logs.detail.condition.accessDenied": "Truy cập bị từ chối", + "logs.detail.condition.contextOverflow": "Vượt quá cửa sổ ngữ cảnh", + "logs.detail.condition.locationUnsupported": "Vị trí không được hỗ trợ", + "logs.detail.condition.accountVerificationRequired": "Cần xác minh tài khoản", + "logs.detail.condition.billingExhausted": "Hết hạn mức hoặc tín dụng", + "logs.detail.condition.modelUnavailable": "Mô hình không khả dụng", + "logs.detail.condition.rateLimited": "Đã đạt giới hạn tốc độ", + "logs.detail.condition.upstreamUnavailable": "Nhà cung cấp không khả dụng", + "logs.detail.condition.upstreamFailed": "Nhà cung cấp gặp lỗi", + "logs.detail.condition.requestRejected": "Yêu cầu bị từ chối", + "logs.failureDetail.providerError": "Nhà cung cấp đã trả về lỗi", + "logs.failureDetail.providerErrorTyped": "Nhà cung cấp đã trả về lỗi ({type})", + "logs.failureDetail.headerTimeout": "Hết thời gian chờ tiêu đề phản hồi", + "logs.failureDetail.headerTimeoutAfter": "Hết thời gian chờ tiêu đề phản hồi sau {value} ms", + "logs.failureDetail.connectTimeout": "Kết nối tới nhà cung cấp đã hết thời gian sau {value} ms", + "logs.failureDetail.connectFailed": "Không thể kết nối tới nhà cung cấp", + "logs.failureDetail.clientClosed": "Máy khách đã đóng yêu cầu", + "logs.failureDetail.bodyStall": "Nội dung phản hồi bị dừng trong {value} ms", + "logs.failureDetail.bodyOverflow": "Nội dung phản hồi vượt quá {value} byte", + "logs.failureDetail.streamErrorStop": "Nhà cung cấp đã kết thúc lượt với một lỗi", + "logs.failureDetail.streamEndedEarly": "Luồng phản hồi kết thúc trước sự kiện cuối", + "logs.failureDetail.streamFailed": "Luồng phản hồi thất bại", + "logs.failureDetail.outputLimit": "Đầu ra đã đạt giới hạn token được yêu cầu", + "logs.failureDetail.stallTimeout": "Nhà cung cấp không gửi dữ liệu trong thời gian chờ đình trệ", + "logs.failureDetail.adapterEof": "Luồng của nhà cung cấp kết thúc mà không có sự kiện cuối", + "logs.failureDetail.generationTimeout": "Mô hình được định tuyến không phản hồi trong {value} ms", + "logs.failureDetail.turnInactivity": "Lượt không hoạt động trong {value} ms", "logs.col.duration": "Thời lượng", "logs.modelTooltip.model": "mô hình", "logs.modelTooltip.resolvedModel": "mô hình sau khi định tuyến", diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index 63c1ac42d41..26460d0bc48 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -1085,6 +1085,35 @@ export const zhTW: Record = { "logs.detail.estimate.expected_price_overlay": "使用了已驗證的 Expected 標價。", "logs.col.error": "錯誤", "logs.col.upstreamReason": "上游原因", + "logs.col.failureDetail": "失敗詳情", + "logs.detail.condition.authFailed": "憑證遭拒", + "logs.detail.condition.accessDenied": "存取遭拒", + "logs.detail.condition.contextOverflow": "超出上下文視窗", + "logs.detail.condition.locationUnsupported": "不支援目前地區", + "logs.detail.condition.accountVerificationRequired": "需要驗證帳號", + "logs.detail.condition.billingExhausted": "配額或額度已用盡", + "logs.detail.condition.modelUnavailable": "模型無法使用", + "logs.detail.condition.rateLimited": "已達速率限制", + "logs.detail.condition.upstreamUnavailable": "供應商無法使用", + "logs.detail.condition.upstreamFailed": "供應商發生錯誤", + "logs.detail.condition.requestRejected": "請求遭拒", + "logs.failureDetail.providerError": "供應商傳回了錯誤", + "logs.failureDetail.providerErrorTyped": "供應商傳回了錯誤({type})", + "logs.failureDetail.headerTimeout": "等待回應標頭逾時", + "logs.failureDetail.headerTimeoutAfter": "等待回應標頭 {value} 毫秒後逾時", + "logs.failureDetail.connectTimeout": "連線至供應商在 {value} 毫秒後逾時", + "logs.failureDetail.connectFailed": "無法連線至供應商", + "logs.failureDetail.clientClosed": "用戶端關閉了請求", + "logs.failureDetail.bodyStall": "回應內文停滯了 {value} 毫秒", + "logs.failureDetail.bodyOverflow": "回應內文超過 {value} 位元組", + "logs.failureDetail.streamErrorStop": "供應商以錯誤結束了本回合", + "logs.failureDetail.streamEndedEarly": "回應串流在最終事件之前結束", + "logs.failureDetail.streamFailed": "回應串流失敗", + "logs.failureDetail.outputLimit": "輸出已達到要求的權杖上限", + "logs.failureDetail.stallTimeout": "供應商在停滯逾時內未傳送資料", + "logs.failureDetail.adapterEof": "供應商的串流在沒有最終事件的情況下結束", + "logs.failureDetail.generationTimeout": "路由的模型在 {value} 毫秒內沒有回應", + "logs.failureDetail.turnInactivity": "本回合已閒置 {value} 毫秒", "logs.col.duration": "耗時", "logs.modelTooltip.model": "模型", "logs.modelTooltip.resolvedModel": "解析後模型", diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index 005f5099ab1..c7247b4896a 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -1342,6 +1342,35 @@ export const zh: Record = { "logs.detail.estimate.priority_lower_bound": "暂无已确认的 Priority 价格;当前显示的估算是已知下界。", "logs.col.error": "错误", "logs.col.upstreamReason": "上游原因", + "logs.col.failureDetail": "失败详情", + "logs.detail.condition.authFailed": "凭据被拒绝", + "logs.detail.condition.accessDenied": "访问被拒绝", + "logs.detail.condition.contextOverflow": "超出上下文窗口", + "logs.detail.condition.locationUnsupported": "不支持当前地区", + "logs.detail.condition.accountVerificationRequired": "需要验证账号", + "logs.detail.condition.billingExhausted": "配额或额度已用尽", + "logs.detail.condition.modelUnavailable": "模型不可用", + "logs.detail.condition.rateLimited": "已达到速率限制", + "logs.detail.condition.upstreamUnavailable": "提供商不可用", + "logs.detail.condition.upstreamFailed": "提供商出错", + "logs.detail.condition.requestRejected": "请求被拒绝", + "logs.failureDetail.providerError": "提供方返回了错误", + "logs.failureDetail.providerErrorTyped": "提供方返回了错误({type})", + "logs.failureDetail.headerTimeout": "等待响应头超时", + "logs.failureDetail.headerTimeoutAfter": "等待响应头 {value} 毫秒后超时", + "logs.failureDetail.connectTimeout": "连接提供方在 {value} 毫秒后超时", + "logs.failureDetail.connectFailed": "无法连接到提供方", + "logs.failureDetail.clientClosed": "客户端关闭了请求", + "logs.failureDetail.bodyStall": "响应正文停滞了 {value} 毫秒", + "logs.failureDetail.bodyOverflow": "响应正文超过了 {value} 字节", + "logs.failureDetail.streamErrorStop": "提供方以错误结束了本轮", + "logs.failureDetail.streamEndedEarly": "响应流在最终事件之前结束", + "logs.failureDetail.streamFailed": "响应流失败", + "logs.failureDetail.outputLimit": "输出达到了请求的令牌上限", + "logs.failureDetail.stallTimeout": "提供方在停滞超时内未发送数据", + "logs.failureDetail.adapterEof": "提供方的流在没有最终事件的情况下结束", + "logs.failureDetail.generationTimeout": "路由的模型在 {value} 毫秒内没有响应", + "logs.failureDetail.turnInactivity": "本轮已闲置 {value} 毫秒", "logs.col.duration": "耗时", "logs.modelTooltip.model": "模型", "logs.modelTooltip.resolvedModel": "解析后模型", diff --git a/gui/src/muse-limit-observation.ts b/gui/src/muse-limit-observation.ts index e4806b526f8..2aff8ce7d01 100644 --- a/gui/src/muse-limit-observation.ts +++ b/gui/src/muse-limit-observation.ts @@ -16,11 +16,10 @@ export function museLimitReport(value: unknown, accountLabel: string, now = Date const row = value as Record; if (row.provider !== PROVIDER || row.accountLogLabel !== accountLabel || row.status !== 429 || row.errorCode !== "rate_limit_exceeded" || typeof row.timestamp !== "number" - || !Number.isFinite(row.timestamp) || row.timestamp > now || typeof row.upstreamError !== "string") return null; - const match = /^Subscription quota exhausted\. Your usage window resets at (\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z)\.$/.exec(row.upstreamError); - if (!match) return null; - const resetAt = Date.parse(match[1]!); - if (!Number.isFinite(resetAt) || resetAt <= now || resetAt <= row.timestamp + || !Number.isFinite(row.timestamp) || row.timestamp > now) return null; + // The server derives this from the provider's quota sentence; the row carries no message text. + const resetAt = row.rateLimitResetAt; + if (typeof resetAt !== "number" || !Number.isFinite(resetAt) || resetAt <= now || resetAt <= row.timestamp || resetAt - row.timestamp > MAX_RESET_DELAY_MS) return null; return { label: "Muse Code", source: "meta-muse:rate-limit-observation", observed: true, updatedAt: row.timestamp, diff --git a/gui/src/pages/Logs.tsx b/gui/src/pages/Logs.tsx index 439a3e07368..a8749eaff41 100644 --- a/gui/src/pages/Logs.tsx +++ b/gui/src/pages/Logs.tsx @@ -23,7 +23,7 @@ import { logsTabKeyDown, readTabFromHash, selectLogsTab } from "./logs-tab-keydo import { isModelRerouted, modelTitle, type ModelTitleTierOutcome } from "./logs-model-title"; import { speedLabel } from "./logs-speed-label"; import { decodeRateLabelKeys } from "./logs-decode-rate"; -import { failureAttributionLabels, failureSummary } from "./logs-failure-summary"; +import { failureAttributionLabels, failureDetailLabel, failureSummary, upstreamConditionLabel } from "./logs-failure-summary"; import "./logs-decode-rate.css"; import { formatEstimatedUsd, formatEstimatedUsdValue, summarizeEstimatedCosts } from "./logs-cost-format"; import { cacheSplit, isCursorUsageProvider, tokensTitle } from "./logs-token-title"; @@ -192,7 +192,9 @@ export interface LogEntry extends LogFailureAttribution { status: number; durationMs: number; errorCode?: string; - upstreamError?: string; + /** Classified upstream condition (closed enum) and proxy-authored failure text; never upstream text. */ + upstreamCondition?: string; + failureDetail?: unknown; /** * Semantic terminal facts. `/api/logs` has always carried these -- `requestLogDto` spreads the * whole durable entry -- but this page declared neither, so it classified every request by its @@ -1113,7 +1115,8 @@ function LogDetailDialog({ <>{t("logs.col.effort")}{effortLabel(detail)}{reasoningWire ? ` (${reasoningWire})` : ""} )} {detail.errorCode && (<>{t("logs.col.error")}{detail.errorCode})} - {detail.upstreamError && (<>{t("logs.col.upstreamReason")}{detail.upstreamError})} + {upstreamConditionLabel(detail.upstreamCondition, t) && (<>{t("logs.col.upstreamReason")}{upstreamConditionLabel(detail.upstreamCondition, t)})} + {failureDetailLabel(detail.failureDetail, t) && (<>{t("logs.col.failureDetail")}{failureDetailLabel(detail.failureDetail, t)})} diff --git a/gui/src/pages/logs-failure-summary.ts b/gui/src/pages/logs-failure-summary.ts index 73f383693f3..789f51ad2dd 100644 --- a/gui/src/pages/logs-failure-summary.ts +++ b/gui/src/pages/logs-failure-summary.ts @@ -1,5 +1,7 @@ import type { TFn } from "../i18n/shared"; import type { RequestFailureCause, RequestFailureStage, ResendPermission, RequestSpendTotals } from "../../../src/usage/telemetry-contract"; +import type { UpstreamCondition } from "../../../src/lib/upstream-condition"; +import { boundedFailureDetail, type FailureDetailCode } from "../../../src/lib/failure-detail"; interface LogFailureAttribution { failureCause?: RequestFailureCause; @@ -101,3 +103,66 @@ export function failureSummary( } return result; } + +/** i18n key for each upstream condition the server classified; total over the closed enum. */ +const UPSTREAM_CONDITION_KEYS = { + auth_failed: "logs.detail.condition.authFailed", + access_denied: "logs.detail.condition.accessDenied", + context_overflow: "logs.detail.condition.contextOverflow", + location_unsupported: "logs.detail.condition.locationUnsupported", + account_verification_required: "logs.detail.condition.accountVerificationRequired", + billing_exhausted: "logs.detail.condition.billingExhausted", + model_unavailable: "logs.detail.condition.modelUnavailable", + rate_limited: "logs.detail.condition.rateLimited", + upstream_unavailable: "logs.detail.condition.upstreamUnavailable", + upstream_failed: "logs.detail.condition.upstreamFailed", + request_rejected: "logs.detail.condition.requestRejected", +} as const satisfies Record; + +/** Localized label for a row's classified upstream condition; unknown values (newer servers) get none. */ +export function upstreamConditionLabel(condition: unknown, t: TFn): string | undefined { + return typeof condition === "string" && Object.hasOwn(UPSTREAM_CONDITION_KEYS, condition) + ? t(UPSTREAM_CONDITION_KEYS[condition as UpstreamCondition]) + : undefined; +} + +/** i18n key for each closed failure-detail code; total over the code set. */ +const FAILURE_DETAIL_KEYS = { + provider_error: "logs.failureDetail.providerError", + header_timeout: "logs.failureDetail.headerTimeout", + connect_timeout: "logs.failureDetail.connectTimeout", + connect_failed: "logs.failureDetail.connectFailed", + client_closed: "logs.failureDetail.clientClosed", + body_stall: "logs.failureDetail.bodyStall", + body_overflow: "logs.failureDetail.bodyOverflow", + stream_error_stop: "logs.failureDetail.streamErrorStop", + stream_ended_early: "logs.failureDetail.streamEndedEarly", + stream_failed: "logs.failureDetail.streamFailed", + output_limit: "logs.failureDetail.outputLimit", + stall_timeout: "logs.failureDetail.stallTimeout", + adapter_eof: "logs.failureDetail.adapterEof", + generation_timeout: "logs.failureDetail.generationTimeout", + turn_inactivity: "logs.failureDetail.turnInactivity", +} as const satisfies Record; + +const VALUE_REQUIRED: ReadonlySet = new Set([ + "connect_timeout", "body_stall", "body_overflow", "generation_timeout", "turn_inactivity", +]); + +/** + * Localized text for a row's failure detail. Only a closed code with valid parameters renders; free + * text (a legacy or edited row) and malformed details render nothing. + */ +export function failureDetailLabel(value: unknown, t: TFn): string | undefined { + const detail = boundedFailureDetail(value); + if (!detail) return undefined; + if (detail.code === "provider_error" && detail.type) return t("logs.failureDetail.providerErrorTyped", { type: detail.type }); + if (detail.code === "header_timeout" && detail.value !== undefined) { + return t("logs.failureDetail.headerTimeoutAfter", { value: detail.value }); + } + if (VALUE_REQUIRED.has(detail.code)) { + return detail.value === undefined ? undefined : t(FAILURE_DETAIL_KEYS[detail.code], { value: detail.value }); + } + return t(FAILURE_DETAIL_KEYS[detail.code]); +} + diff --git a/gui/tests/logs-failure-detail.test.ts b/gui/tests/logs-failure-detail.test.ts new file mode 100644 index 00000000000..027ef455352 --- /dev/null +++ b/gui/tests/logs-failure-detail.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, test } from "bun:test"; +import { en, type TKey } from "../src/i18n/en"; +import { interpolate, type Vars } from "../src/i18n/shared"; +import { failureDetailLabel } from "../src/pages/logs-failure-summary"; +import { FAILURE_DETAIL_CODES } from "../../src/lib/failure-detail"; + +// A provider key with no recognizable prefix, so pattern-based redaction cannot spot it. +const PROVIDER_KEY = "zq7Vb2LmN4pX9tR1sK8wD3fH6jY0cA5e"; +const t = (key: TKey, vars?: Vars) => interpolate(en[key], vars); + +describe("failure detail renders as proxy-owned localized text", () => { + test("each closed code renders, with its bounded parameter", () => { + expect(failureDetailLabel({ code: "header_timeout" }, t)).toBe("Timed out waiting for response headers"); + expect(failureDetailLabel({ code: "header_timeout", value: 300 }, t)).toBe("Timed out waiting for response headers after 300 ms"); + expect(failureDetailLabel({ code: "body_overflow", value: 1024 }, t)).toBe("The response body exceeded 1024 bytes"); + expect(failureDetailLabel({ code: "provider_error", type: "permission_error" }, t)).toBe("The provider returned an error (permission_error)"); + expect(failureDetailLabel({ code: "provider_error" }, t)).toBe("The provider returned an error"); + for (const code of FAILURE_DETAIL_CODES) { + expect(failureDetailLabel({ code, value: 1 }, t)).toBeString(); + } + }); + + test("free text, forged codes and malformed parameters render nothing", () => { + for (const value of [ + "anthropic passthrough timed out " + PROVIDER_KEY, { code: PROVIDER_KEY }, { code: "constructor" }, null, [], + { code: "body_stall" }, { code: "body_overflow", value: -1 }, { code: "connect_timeout", value: PROVIDER_KEY }, + ]) { + expect(failureDetailLabel(value, t)).toBeUndefined(); + } + const typed = failureDetailLabel({ code: "provider_error", type: PROVIDER_KEY }, t); + expect(typed).toBe("The provider returned an error"); + }); +}); + diff --git a/gui/tests/muse-limit-observation.test.ts b/gui/tests/muse-limit-observation.test.ts index 2f76418256b..68eada1da10 100644 --- a/gui/tests/muse-limit-observation.test.ts +++ b/gui/tests/muse-limit-observation.test.ts @@ -2,8 +2,9 @@ import { expect, test } from "bun:test"; import { formatMuseResetCountdown, museLimitReport, withMuseLimitObservation } from "../src/muse-limit-observation"; const now = Date.parse("2026-10-25T19:08:28Z"); +// Rows carry the server-derived numeric reset; the dashboard never reads provider message text. const row = { provider: "meta-muse", accountLogLabel: "o527765", status: 429, errorCode: "rate_limit_exceeded", timestamp: now, - upstreamError: "Subscription quota exhausted. Your usage window resets at 2026-10-26T00:00:00Z." }; + rateLimitResetAt: Date.parse("2026-10-26T00:00:00Z") }; test("the visible countdown decreases and stops at zero", () => { expect(formatMuseResetCountdown(now + 3661000, now)).toBe("01:01:01"); @@ -21,12 +22,19 @@ test("an explicit subscription refusal preserves the observed reset without inve test("expired, malformed, unrelated and cross-account evidence never becomes a quota", () => { for (const invalid of [ { ...row, status: 200 }, { ...row, provider: "xai" }, { ...row, accountLogLabel: "o000000" }, - { ...row, upstreamError: "Too many requests. Try again later." }, { ...row, timestamp: now + 1000 }, - { ...row, upstreamError: "Subscription quota exhausted. Your usage window resets at 2099-10-26T00:00:00Z." }, + { ...row, rateLimitResetAt: undefined }, { ...row, timestamp: now + 1000 }, + { ...row, rateLimitResetAt: Date.parse("2099-10-26T00:00:00Z") }, { ...row, rateLimitResetAt: Number.NaN }, + { ...row, rateLimitResetAt: "2026-10-26T00:00:00Z" }, { ...row, rateLimitResetAt: now - 1 }, ]) expect(museLimitReport(invalid, "o527765", now)).toBeNull(); expect(museLimitReport(row, "o527765", Date.parse("2026-10-26T00:00:00Z"))).toBeNull(); }); +test("a legacy quota sentence without the numeric reset is not parsed in the dashboard", () => { + const { rateLimitResetAt: _reset, ...legacy } = row; + const sentence = { ...legacy, upstreamError: "Subscription quota exhausted. Your usage window resets at 2026-10-26T00:00:00Z." }; + expect(museLimitReport(sentence, "o527765", now)).toBeNull(); +}); + test("an existing measured quota is authoritative and needs no fallback reads", async () => { const reports = { "meta-muse": { updatedAt: now, quota: { weeklyPercent: 40 } } }; const fetcher = (() => { throw Error("unexpected request"); }) as typeof fetch; @@ -39,7 +47,7 @@ test("fallback reads bind the latest request to the active account and never inv const url = String(input); paths.push(url); if (url === "/api/providers") return Response.json([{ name: "meta-muse", authMode: "oauth", baseUrl: "https://api.meta.ai/v1" }]); if (url.startsWith("/api/oauth/accounts?")) return Response.json({ activeAccountId: "fixture-muse-account", accounts: [{ id: "fixture-muse-account" }] }); - if (url === "/api/logs?provider=meta-muse&account=o527765") return Response.json({ logs: [{ ...row, timestamp: Date.now(), upstreamError: `Subscription quota exhausted. Your usage window resets at ${new Date(Date.now() + 3600000).toISOString().replace(/\.\d{3}Z$/, "Z")}.` }] }); + if (url === "/api/logs?provider=meta-muse&account=o527765") return Response.json({ logs: [{ ...row, timestamp: Date.now(), rateLimitResetAt: Date.now() + 3600000 }] }); throw Error("unexpected request"); }) as typeof fetch; const result = await withMuseLimitObservation({}, "", new AbortController().signal, fetcher); @@ -97,8 +105,7 @@ async function observeFinalizedRows(logs: unknown[]) { function overlappingRows() { const started = Date.now() - 2000; - const refusal = { ...row, timestamp: started, - upstreamError: `Subscription quota exhausted. Your usage window resets at ${new Date(started + 3600000).toISOString().replace(/\.\d{3}Z$/, "Z")}.` }; + const refusal = { ...row, timestamp: started, rateLimitResetAt: started + 3600000 }; return { refusal, success: { ...refusal, status: 200, timestamp: started + 1000 } }; } diff --git a/scripts/test-layout/layout-usage.json b/scripts/test-layout/layout-usage.json index 6638799267c..4413278a67f 100644 --- a/scripts/test-layout/layout-usage.json +++ b/scripts/test-layout/layout-usage.json @@ -1,4 +1,13 @@ { "request-log.test.ts": "usage", - "request-log-normalization.test.ts": "usage" + "request-log-normalization.test.ts": "usage", + "request-log-error-detail.test.ts": "usage", + "upstream-condition.test.ts": "lib", + "client-retry-after.test.ts": "lib", + "client-retry-after-sites.test.ts": "server", + "upstream-error-detail-boundaries.test.ts": "server", + "request-log-identity-bounds.test.ts": "usage", + "safe-response-headers.test.ts": "server", + "turn-state-handles.test.ts": "server", + "turn-state-handles-e2e.test.ts": "server" } diff --git a/src/bridge/errors.ts b/src/bridge/errors.ts index 703e18d61bf..3a1524cca9c 100644 --- a/src/bridge/errors.ts +++ b/src/bridge/errors.ts @@ -6,6 +6,7 @@ import { REPLAY_REFUSED_STATUS, retainReplayRefusal, } from "../lib/upstream-retry"; +import { formatClientRetryAfter } from "../lib/client-retry-after"; import { adapterFailureFromMessage, classifyError, @@ -93,7 +94,8 @@ export function formatErrorResponse( : error.code === SPEND_LEDGER_STORAGE_UNAVAILABLE_CODE ? 503 : isReplayRefusalCode(error.code) ? REPLAY_REFUSED_STATUS : status; const headers = new Headers({ "Content-Type": "application/json" }); - const retryAfter = options?.retryAfter?.trim(); + // Re-emitted as an integer this proxy formats; the incoming text is never echoed. + const retryAfter = formatClientRetryAfter(options?.retryAfter); if (error.code !== CYBER_POLICY_ERROR_CODE && !replayBlocked && retryAfter @@ -155,6 +157,7 @@ export function formatUsageLimitReachedResponse(message: string, resetsAtMs: num ...(resetsAtMs !== null ? { resets_at: Math.ceil(resetsAtMs / 1000) } : {}), }; const headers = new Headers({ "Content-Type": "application/json" }); - if (retryAfterSeconds !== null) headers.set("Retry-After", String(retryAfterSeconds)); + const advice = retryAfterSeconds !== null ? formatClientRetryAfter(retryAfterSeconds) : undefined; + if (advice !== undefined) headers.set("Retry-After", advice); return new Response(JSON.stringify({ error }), { status: 429, headers }); } diff --git a/src/codex/auth-context.ts b/src/codex/auth-context.ts index 7a17e2144ed..cd841429bee 100644 --- a/src/codex/auth-context.ts +++ b/src/codex/auth-context.ts @@ -1,3 +1,4 @@ +import { formatClientRetryAfter } from "../lib/client-retry-after"; import { requestOwnedAffinityKey, honestAffinityDecision, callerOwnedFallbackAffinityDecision, captureRequestOwnedAffinityBindings, type RequestOwnedBindingSnapshot } from "./request-owned-affinity"; import { requestOwnedMainPinState, mainCreditsHoldResetAt, callerMatchesObservedMain } from "./request-owned-main-pin"; export { requestOwnedMainPinState } from "./request-owned-main-pin"; @@ -925,7 +926,8 @@ export function cooldownErrorResponse( const res = formatErrorResponse(429, "rate_limit_error", cooldownErrorMessage(err, accountSelector)); const headers = new Headers(res.headers); if (!(err instanceof CodexReserveUnavailableError)) { - headers.set("Retry-After", String(Math.max(1, Math.ceil((err.cooldownUntil - now) / 1000)))); + const advice = formatClientRetryAfter(Math.max(1, Math.ceil((err.cooldownUntil - now) / 1000))); + if (advice !== undefined) headers.set("Retry-After", advice); } return new Response(res.body, { status: res.status, headers }); } diff --git a/src/combos/failover.ts b/src/combos/failover.ts index e9a29a5607d..3ebd6bdf5ff 100644 --- a/src/combos/failover.ts +++ b/src/combos/failover.ts @@ -5,6 +5,10 @@ import { isAnthropicBillingFailure } from "../providers/anthropic-billing-refusa import { isKiroAccountProfileRefusal } from "../adapters/kiro-refusal"; import type { OcxComboTarget } from "../types"; import { targetKey } from "./types"; +import { isDefiniteContextOverflow } from "../lib/context-overflow-verdict"; + +// The verdict lives in a dependency-free leaf so the presentation classifier can share it. +export { isDefiniteContextOverflow }; import { captureConfigGeneration, sweepExpiredOnWrite, @@ -704,114 +708,6 @@ function isProviderTargetContextOverflow( && /\bprompt\s+\d+\s*>\s*\d+\s+maximum context length\b/i.test(message); } -/** A status can carry a verdict about the REQUEST; 401/403/429 speak about the credential. */ -const CONTEXT_VERDICT_STATUSES: ReadonlySet = new Set([400, 413, 422]); - -/** - * Phrases a provider emits when the INPUT does not fit this model's context window. Matched - * against the innermost provider message only, so an unrelated refusal that merely quotes one - * of these tokens in a code field cannot authorize a replay. - */ -const DEFINITE_CONTEXT_OVERFLOW_PHRASES = [ - "exceeds the context window", - "exceed the context window", - "context window exceeded", - "context length exceeded", - "maximum context length", - "maximum context window", - "too many tokens", -]; - -/** - * Short provider verdicts that a validation error could otherwise echo as the caller's own value - * (#7443). Each counts only at the very start of the provider's leaf message, after JSON envelopes - * are unwrapped, and Anthropic's only with its token counts. Text that merely contains one, including - * a serialized SDK exception or a quoted caller object, is not evidence: only the phrases dev already - * matched as substrings keep that wider reach. - */ -const ANCHORED_CONTEXT_OVERFLOW_VERDICTS: readonly RegExp[] = [ - /^prompt is too long: \d+ tokens > \d+ maximum/i, - /^input is too long for requested model\b/i, - /^please reduce the length of the messages or completion\b/i, -]; - -/** Wrapper envelopes unwrapped before the leaf message is read. */ -const MAX_CONTEXT_OVERFLOW_ENVELOPES = 4; - -/** - * Parameter validation echoes the caller's own value, so its prose is not a context verdict even - * when the value reads like one: "Invalid 'tools[0].function.name': 'prompt is too long'". These - * markers are read anywhere in the text, so an SDK error wrapper that serializes such a record as a - * Python dict is refused too, while a quoted genuine verdict in the same wrapper stays evidence. - */ -const CONTEXT_PARAM_NAMES = "messages|input|input_text|input_tokens|prompt|contents?|max_tokens|max_completion_tokens|max_output_tokens"; -/** A `param` naming the conversation or a token budget is consistent with an overflow. */ -const CONTEXT_PARAM = new RegExp(`^(?:${CONTEXT_PARAM_NAMES})(?:$|[.[])`, "i"); -const PARAMETER_VALIDATION_CODES: ReadonlySet = new Set(["invalid_value", "invalid_type"]); -const PARAMETER_VALIDATION_MARKERS: readonly RegExp[] = [ - /\binvalid_(?:value|type)\b/i, - new RegExp(`['"]param['"]\\s*:\\s*['"](?!(?:${CONTEXT_PARAM_NAMES})(?:['".[]))`, "i"), - /\binvalid\s+(?:value\s+for\s+)?['"`\u2018\u201c]/i, - /\binvalid\s+(?:tool|function|parameter|argument|field|value)\b/i, - /\binput_value\s*=/i, - /\bvalidation errors? for\b/i, -]; - -function isParameterValidationRecord(record: Record): boolean { - if (typeof record.code === "string" && PARAMETER_VALIDATION_CODES.has(record.code.toLowerCase())) return true; - return typeof record.param === "string" && record.param.length > 0 && !CONTEXT_PARAM.test(record.param); -} - -function isDefiniteContextOverflowMessage(text: string): boolean { - if (PARAMETER_VALIDATION_MARKERS.some(marker => marker.test(text))) return false; - const normalized = text.toLowerCase(); - return normalized === "context_length_exceeded" - || DEFINITE_CONTEXT_OVERFLOW_PHRASES.some(phrase => normalized.includes(phrase)) - || ANCHORED_CONTEXT_OVERFLOW_VERDICTS.some(verdict => verdict.test(text.trim())); -} - -/** - * Confirm a context overflow from the provider MESSAGE rather than from a code token that - * merely appears somewhere in the envelope. An upstream controls both fields and can emit a - * contradictory pair -- `context_length_exceeded` beside `Unsupported parameter: user` -- and - * that is not evidence the turn is too large for this model. `classifyError` reads the whole - * blob, which is exactly the looseness this must not inherit. - * - * A JSON-shaped body that fails to parse is truncated or corrupt, not prose: `classificationText` - * is capped at 500 characters by `normalizeUpstreamErrorText` before it reaches this function, so - * a long envelope arrives here as a JSON prefix. Reading that prefix as plain text would let an - * arbitrary field that happens to sit in the first 500 bytes authorize a hop, so it fails closed. - * - * Only the exact proxy wrapper is unwrapped, within a fixed envelope budget and 16,384 characters. - * Exported for the sidecar loops, which classify their own provider failures with the same rule. - */ -export function isDefiniteContextOverflow(status: number, message: string): boolean { - if (!CONTEXT_VERDICT_STATUSES.has(status) && status < 500) return false; - if (message.length > 16_384) return false; - let text = message.trim(); - // One pass per unwrapped envelope, plus one for the leaf the last envelope yields. - for (let unwrapped = 0; unwrapped <= MAX_CONTEXT_OVERFLOW_ENVELOPES; unwrapped += 1) { - const providerPrefix = /^Provider error \d{3}:\s*/.exec(text); - if (providerPrefix) text = text.slice(providerPrefix[0].length).trim(); - if (!text.startsWith("{")) return isDefiniteContextOverflowMessage(text); - if (unwrapped === MAX_CONTEXT_OVERFLOW_ENVELOPES) return false; - let payload: unknown; - try { payload = JSON.parse(text); } catch { return false; } - if (!payload || typeof payload !== "object" || Array.isArray(payload)) return false; - const record = payload as Record; - const response = record.response && typeof record.response === "object" && !Array.isArray(record.response) - ? record.response as Record - : undefined; - const source = [record.error, response?.error, response?.last_error, record.last_error, record] - .find((candidate): candidate is Record => - !!candidate && typeof candidate === "object" && !Array.isArray(candidate) - && typeof (candidate as Record).message === "string"); - if (!source || isParameterValidationRecord(source)) return false; - text = (source.message as string).trim(); - } - return false; -} - const CODEX_ACCOUNT_MODEL_REFUSAL = /^The '[^']{1,256}' model is not supported when using Codex with a ChatGPT account\.$/; export type CodexAccountModelRefusal = "other" | "refusal" | "ambiguous"; diff --git a/src/lib/client-retry-after.ts b/src/lib/client-retry-after.ts new file mode 100644 index 00000000000..f1bbc113e09 --- /dev/null +++ b/src/lib/client-retry-after.ts @@ -0,0 +1,66 @@ +/** + * Client-facing Retry-After formatting, dependency-free so leaf header modules can use it. + */ + +/** + * Longest wait this proxy advertises to a client: eight days, so a weekly usage window's reset + * (a local Codex account cooldown, for example) still reaches the client intact. Internal cooldowns + * keep their own parsed values. + */ +export const MAX_CLIENT_RETRY_AFTER_SECONDS = 8 * 24 * 60 * 60; + +// RFC 9110 HTTP-date forms: IMF-fixdate, obsolete RFC 850, and asctime. All are GMT; they are +// parsed field by field because Date.parse reads a zoneless asctime date in local time. +const IMF_FIXDATE = /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/; +const RFC850_DATE = /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-([A-Za-z]{3})-(\d{2}) (\d{2}):(\d{2}):(\d{2}) GMT$/; +const ASCTIME_DATE = /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) ([A-Za-z]{3}) ([ \d]\d) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/; +const MONTHS = new Map(["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"].map((name, index) => [name, index])); + +function utcMs(day: string, monthName: string, year: number, hour: string, minute: string, second: string): number | undefined { + const month = MONTHS.get(monthName.toLowerCase()); + const [d, h, m, s] = [Number(day), Number(hour), Number(minute), Number(second)]; + if (month === undefined || d < 1 || h > 23 || m > 59 || s > 60) return undefined; + const at = Date.UTC(year, month, d, h, m, s); + return new Date(at).getUTCDate() === d ? at : undefined; +} + +/** Milliseconds since the epoch for an RFC 9110 HTTP-date, or undefined. */ +function httpDateMs(value: string, now: number): number | undefined { + let match = IMF_FIXDATE.exec(value); + if (match) return utcMs(match[1]!, match[2]!, Number(match[3]), match[4]!, match[5]!, match[6]!); + match = RFC850_DATE.exec(value); + if (match) { + // A two-digit year more than 50 years ahead is read as the previous century (RFC 9110 5.6.7). + let year = 2000 + Number(match[3]); + if (year > new Date(now).getUTCFullYear() + 50) year -= 100; + return utcMs(match[1]!, match[2]!, year, match[4]!, match[5]!, match[6]!); + } + match = ASCTIME_DATE.exec(value); + if (match) return utcMs(match[2]!.trim(), match[1]!, Number(match[6]), match[3]!, match[4]!, match[5]!); + return undefined; +} + +/** + * Retry advice as bytes this proxy writes: a non-negative integer number of seconds, clamped to + * {@link MAX_CLIENT_RETRY_AFTER_SECONDS}, or undefined. Accepts delay seconds (including "0" and + * fractions, rounded up) and HTTP dates in any RFC 9110 form (past or current -> "0"). The input + * string is never echoed. For client headers and bodies only; cooldown and retry scheduling read + * the parsed evidence. + */ +export function formatClientRetryAfter(value: string | number | null | undefined, now = Date.now()): string | undefined { + let seconds: number | undefined; + if (typeof value === "number") { + seconds = Number.isFinite(value) && value >= 0 ? value : undefined; + } else if (typeof value === "string") { + const trimmed = value.trim(); + if (!trimmed || trimmed.length > 128) return undefined; + if (/^\d+(?:\.\d+)?$/.test(trimmed)) { + seconds = Number(trimmed); + } else { + const at = httpDateMs(trimmed, now); + if (at !== undefined) seconds = Math.max(0, (at - now) / 1000); + } + } + if (seconds === undefined || !Number.isFinite(seconds)) return undefined; + return String(Math.min(MAX_CLIENT_RETRY_AFTER_SECONDS, Math.ceil(seconds))); +} diff --git a/src/lib/context-overflow-verdict.ts b/src/lib/context-overflow-verdict.ts new file mode 100644 index 00000000000..267c534b740 --- /dev/null +++ b/src/lib/context-overflow-verdict.ts @@ -0,0 +1,113 @@ +/** + * The definite context-window overflow verdict, shared by combo failover (src/combos/failover.ts, + * which re-exports it) and the presentation classifier (src/lib/upstream-condition.ts). It has no + * imports, so the dashboard's type-only use of the classifier never pulls in server modules. + */ + +/** A status can carry a verdict about the REQUEST; 401/403/429 speak about the credential. */ +const CONTEXT_VERDICT_STATUSES: ReadonlySet = new Set([400, 413, 422]); + +/** + * Phrases a provider emits when the INPUT does not fit this model's context window. Matched + * against the innermost provider message only, so an unrelated refusal that merely quotes one + * of these tokens in a code field cannot authorize a replay. + */ +const DEFINITE_CONTEXT_OVERFLOW_PHRASES = [ + "exceeds the context window", + "exceed the context window", + "context window exceeded", + "context length exceeded", + "maximum context length", + "maximum context window", + "too many tokens", +]; + +/** + * Short provider verdicts that a validation error could otherwise echo as the caller's own value + * (#7443). Each counts only at the very start of the provider's leaf message, after JSON envelopes + * are unwrapped, and Anthropic's only with its token counts. Text that merely contains one, including + * a serialized SDK exception or a quoted caller object, is not evidence: only the phrases dev already + * matched as substrings keep that wider reach. + */ +const ANCHORED_CONTEXT_OVERFLOW_VERDICTS: readonly RegExp[] = [ + /^prompt is too long: \d+ tokens > \d+ maximum/i, + /^input is too long for requested model\b/i, + /^please reduce the length of the messages or completion\b/i, +]; + +/** Wrapper envelopes unwrapped before the leaf message is read. */ +const MAX_CONTEXT_OVERFLOW_ENVELOPES = 4; + +/** + * Parameter validation echoes the caller's own value, so its prose is not a context verdict even + * when the value reads like one: "Invalid 'tools[0].function.name': 'prompt is too long'". These + * markers are read anywhere in the text, so an SDK error wrapper that serializes such a record as a + * Python dict is refused too, while a quoted genuine verdict in the same wrapper stays evidence. + */ +const CONTEXT_PARAM_NAMES = "messages|input|input_text|input_tokens|prompt|contents?|max_tokens|max_completion_tokens|max_output_tokens"; +/** A `param` naming the conversation or a token budget is consistent with an overflow. */ +const CONTEXT_PARAM = new RegExp(`^(?:${CONTEXT_PARAM_NAMES})(?:$|[.[])`, "i"); +const PARAMETER_VALIDATION_CODES: ReadonlySet = new Set(["invalid_value", "invalid_type"]); +const PARAMETER_VALIDATION_MARKERS: readonly RegExp[] = [ + /\binvalid_(?:value|type)\b/i, + new RegExp(`['"]param['"]\\s*:\\s*['"](?!(?:${CONTEXT_PARAM_NAMES})(?:['".[]))`, "i"), + /\binvalid\s+(?:value\s+for\s+)?['"`\u2018\u201c]/i, + /\binvalid\s+(?:tool|function|parameter|argument|field|value)\b/i, + /\binput_value\s*=/i, + /\bvalidation errors? for\b/i, +]; + +function isParameterValidationRecord(record: Record): boolean { + if (typeof record.code === "string" && PARAMETER_VALIDATION_CODES.has(record.code.toLowerCase())) return true; + return typeof record.param === "string" && record.param.length > 0 && !CONTEXT_PARAM.test(record.param); +} + +function isDefiniteContextOverflowMessage(text: string): boolean { + if (PARAMETER_VALIDATION_MARKERS.some(marker => marker.test(text))) return false; + const normalized = text.toLowerCase(); + return normalized === "context_length_exceeded" + || DEFINITE_CONTEXT_OVERFLOW_PHRASES.some(phrase => normalized.includes(phrase)) + || ANCHORED_CONTEXT_OVERFLOW_VERDICTS.some(verdict => verdict.test(text.trim())); +} + +/** + * Confirm a context overflow from the provider MESSAGE rather than from a code token that + * merely appears somewhere in the envelope. An upstream controls both fields and can emit a + * contradictory pair -- `context_length_exceeded` beside `Unsupported parameter: user` -- and + * that is not evidence the turn is too large for this model. `classifyError` reads the whole + * blob, which is exactly the looseness this must not inherit. + * + * A JSON-shaped body that fails to parse is truncated or corrupt, not prose: `classificationText` + * is capped at 500 characters by `normalizeUpstreamErrorText` before it reaches this function, so + * a long envelope arrives here as a JSON prefix. Reading that prefix as plain text would let an + * arbitrary field that happens to sit in the first 500 bytes authorize a hop, so it fails closed. + * + * Only the exact proxy wrapper is unwrapped, within a fixed envelope budget and 16,384 characters. + * Exported for the sidecar loops, which classify their own provider failures with the same rule. + */ +export function isDefiniteContextOverflow(status: number, message: string): boolean { + if (!CONTEXT_VERDICT_STATUSES.has(status) && status < 500) return false; + if (message.length > 16_384) return false; + let text = message.trim(); + // One pass per unwrapped envelope, plus one for the leaf the last envelope yields. + for (let unwrapped = 0; unwrapped <= MAX_CONTEXT_OVERFLOW_ENVELOPES; unwrapped += 1) { + const providerPrefix = /^Provider error \d{3}:\s*/.exec(text); + if (providerPrefix) text = text.slice(providerPrefix[0].length).trim(); + if (!text.startsWith("{")) return isDefiniteContextOverflowMessage(text); + if (unwrapped === MAX_CONTEXT_OVERFLOW_ENVELOPES) return false; + let payload: unknown; + try { payload = JSON.parse(text); } catch { return false; } + if (!payload || typeof payload !== "object" || Array.isArray(payload)) return false; + const record = payload as Record; + const response = record.response && typeof record.response === "object" && !Array.isArray(record.response) + ? record.response as Record + : undefined; + const source = [record.error, response?.error, response?.last_error, record.last_error, record] + .find((candidate): candidate is Record => + !!candidate && typeof candidate === "object" && !Array.isArray(candidate) + && typeof (candidate as Record).message === "string"); + if (!source || isParameterValidationRecord(source)) return false; + text = (source.message as string).trim(); + } + return false; +} diff --git a/src/lib/failure-detail.ts b/src/lib/failure-detail.ts new file mode 100644 index 00000000000..6a78bb4d5c3 --- /dev/null +++ b/src/lib/failure-detail.ts @@ -0,0 +1,66 @@ +/** + * Failure detail a request-log row may carry: a closed code plus bounded numeric or closed parameters. + * The dashboard renders each code as localized text; rows never hold free-form failure text. + */ +export const FAILURE_DETAIL_CODES = [ + "provider_error", + "header_timeout", + "connect_timeout", + "connect_failed", + "client_closed", + "body_stall", + "body_overflow", + "stream_error_stop", + "stream_ended_early", + "stream_failed", + "output_limit", + "stall_timeout", + "adapter_eof", + "generation_timeout", + "turn_inactivity", +] as const; + +export type FailureDetailCode = typeof FAILURE_DETAIL_CODES[number]; + +/** Closed provider error classes a provider_error detail may name (the Anthropic error envelope types). */ +export const FAILURE_DETAIL_PROVIDER_TYPES = [ + "invalid_request_error", "authentication_error", "permission_error", "not_found_error", + "rate_limit_error", "api_error", "overloaded_error", "request_too_large", +] as const; + +export type FailureDetailProviderType = typeof FAILURE_DETAIL_PROVIDER_TYPES[number]; + +export interface FailureDetail { + code: FailureDetailCode; + /** Milliseconds for timeouts and stalls, bytes for an overflow. */ + value?: number; + type?: FailureDetailProviderType; +} + +const CODES: ReadonlySet = new Set(FAILURE_DETAIL_CODES); +const TYPES: ReadonlySet = new Set(FAILURE_DETAIL_PROVIDER_TYPES); +const MAX_VALUE = 1e12; + +/** Codes whose value parameter carries meaning; the value is dropped for any other code. */ +const VALUED: ReadonlySet = new Set([ + "header_timeout", "connect_timeout", "body_stall", "body_overflow", "generation_timeout", "turn_inactivity", +]); + +/** + * The detail when it is a closed code with valid parameters, else undefined. Free text (a legacy or + * edited row) is never accepted. Returns the same object when it is already exactly valid. + */ +export function boundedFailureDetail(value: unknown): FailureDetail | undefined { + if (!value || typeof value !== "object" || Array.isArray(value)) return undefined; + const record = value as Record; + if (typeof record.code !== "string" || !CODES.has(record.code)) return undefined; + const code = record.code as FailureDetailCode; + const number = record.value; + const valid = typeof number === "number" && Number.isSafeInteger(number) && number >= 0 && number <= MAX_VALUE && VALUED.has(code); + const type = code === "provider_error" && typeof record.type === "string" && TYPES.has(record.type) + ? record.type as FailureDetailProviderType : undefined; + const keys = Object.keys(record); + const exact = keys.every(key => key === "code" || (key === "value" && valid) || (key === "type" && type !== undefined)); + if (exact) return record as unknown as FailureDetail; + return { code, ...(valid ? { value: number as number } : {}), ...(type ? { type } : {}) }; +} diff --git a/src/lib/model-identity.ts b/src/lib/model-identity.ts new file mode 100644 index 00000000000..47367a49fd4 --- /dev/null +++ b/src/lib/model-identity.ts @@ -0,0 +1,44 @@ +import { redactSecretString } from "./redact"; +import { pinnedNativeModelRows } from "../codex/catalog/pinned-models"; +import { getModelMetadata, resolveMetadataProvider } from "../generated/model-metadata"; + +/** Longest model identity a row or relayed header may carry. */ +export const MAX_MODEL_IDENTITY_LENGTH = 128; + +/** + * A model identity (served, resolved, or a relayed model header) is an identifier, never free-form + * text to truncate into one: `[A-Za-z0-9._:/@-]`, at most 128 characters. A value the secret redactor + * would change is dropped, because credential-shaped text can fit the identifier alphabet. + */ +export function boundedModelIdentity(value: unknown): string | undefined { + return typeof value === "string" + && value.length <= MAX_MODEL_IDENTITY_LENGTH + && /^[A-Za-z0-9._:/@-]+$/.test(value) + && redactSecretString(value) === value + ? value + : undefined; +} + +/** Model ids this build pins for the Codex catalog; a known id a route can be served without config. */ +const PINNED_MODEL_IDS: ReadonlyMap = new Map( + pinnedNativeModelRows().flatMap(row => typeof row.slug === "string" ? [[row.slug, row.slug] as [string, string]] : []), +); + +/** + * An upstream-reported model string is kept only when it exactly equals a model id this proxy + * already knows: one of `known` (the requested model, the routed target, the wire model, a + * configured target), a model the bundled Codex catalog pins, or a model in the bundled metadata + * catalog for `provider` (the selected provider). The identity grammar still applies first. What is + * returned is the proxy's own copy of the matched id; anything else is undefined, because no grammar + * can tell a prefixless credential from a model name. + */ +export function knownModelIdentity(value: unknown, known: Iterable = [], provider?: string): string | undefined { + const bounded = boundedModelIdentity(value); + if (bounded === undefined) return undefined; + for (const candidate of known) { + if (typeof candidate === "string" && candidate === bounded) return candidate; + } + const pinned = PINNED_MODEL_IDS.get(bounded); + if (pinned !== undefined || !provider) return pinned; + return getModelMetadata(resolveMetadataProvider(provider) ?? provider, bounded)?.id; +} diff --git a/src/lib/response-service-tier.ts b/src/lib/response-service-tier.ts new file mode 100644 index 00000000000..9e68bf65d64 --- /dev/null +++ b/src/lib/response-service-tier.ts @@ -0,0 +1,17 @@ +/** + * Response service tiers a request-log row may record. A provider can return any string in + * `service_tier` (or an Anthropic `speed`), so only these closed members are kept; anything else + * is omitted. Pricing and Fast confirmation read the raw observation separately. + */ +export const RESPONSE_SERVICE_TIERS = ["auto", "default", "flex", "scale", "priority", "fast", "standard", "ultrafast"] as const; + +export type ResponseServiceTier = typeof RESPONSE_SERVICE_TIERS[number]; + +const TIERS: ReadonlySet = new Set(RESPONSE_SERVICE_TIERS); + +/** The closed member a tier names (case-insensitive), or undefined. */ +export function boundedServiceTier(value: unknown): ResponseServiceTier | undefined { + if (typeof value !== "string") return undefined; + const folded = value.trim().toLowerCase(); + return TIERS.has(folded) ? folded as ResponseServiceTier : undefined; +} diff --git a/src/lib/retry-after.ts b/src/lib/retry-after.ts index 1b63d17f4d0..061a4c59b3e 100644 --- a/src/lib/retry-after.ts +++ b/src/lib/retry-after.ts @@ -1,5 +1,8 @@ import { parseRetryAfterMs } from "../combos"; import { classifyError, parseRetryAfterFromMessage } from "./errors"; +import { formatClientRetryAfter } from "./client-retry-after"; + +export { formatClientRetryAfter, MAX_CLIENT_RETRY_AFTER_SECONDS } from "./client-retry-after"; /** Small default when a retryable 429 has no upstream Retry-After (#507). */ export const DEFAULT_RETRYABLE_429_RETRY_AFTER_SEC = "2"; diff --git a/src/lib/upstream-condition.ts b/src/lib/upstream-condition.ts new file mode 100644 index 00000000000..0467ff83b3a --- /dev/null +++ b/src/lib/upstream-condition.ts @@ -0,0 +1,142 @@ +/** + * Presentation-only classification of an upstream failure into a small closed set of conditions. + * + * The output is what request logs and client-facing error text may name. It never carries input + * bytes: callers pass bounded structured tokens (status, type, code, reason) and optionally the + * upstream message, which is read here only through fixed lowercase keyword sets and never stored + * or returned. Routing, retry and recovery keep using their own classifiers (src/lib/errors.ts); + * this module must not feed them. + */ + +import { isDefiniteContextOverflow } from "./context-overflow-verdict"; + +export const UPSTREAM_CONDITIONS = [ + "auth_failed", + "access_denied", + "context_overflow", + "location_unsupported", + "account_verification_required", + "billing_exhausted", + "model_unavailable", + "rate_limited", + "upstream_unavailable", + "upstream_failed", + "request_rejected", +] as const; + +export type UpstreamCondition = typeof UPSTREAM_CONDITIONS[number]; + +const CONDITION_SET: ReadonlySet = new Set(UPSTREAM_CONDITIONS); + +export function isUpstreamCondition(value: unknown): value is UpstreamCondition { + return typeof value === "string" && CONDITION_SET.has(value); +} + +export interface UpstreamConditionEvidence { + status: number; + type?: string; + code?: string; + reason?: string; + message?: string; +} + +// Structured tokens are compared after lowercasing; anything longer than this is not a token. +const MAX_TOKEN_LENGTH = 128; +// Keyword matching reads at most this much of the message. +const MAX_MESSAGE_SCAN = 4096; + +const STRUCTURED: ReadonlyArray]> = [ + ["context_overflow", new Set(["context_length_exceeded", "string_above_max_length", "context_window_exceeded", "prompt_too_long"])], + ["location_unsupported", new Set(["location_not_supported", "unsupported_country_region_territory", "unsupported_country", "user_location_is_not_supported"])], + ["account_verification_required", new Set(["validation_required", "verification_required", "organization_verification_required"])], + ["billing_exhausted", new Set(["insufficient_quota", "billing_hard_limit_reached", "usage_limit_reached", "usage_limit_exceeded", "1308", "monthly_request_count", "overage_request_limit_exceeded", "payment_required", "insufficient_balance", "credit_balance_too_low"])], + ["model_unavailable", new Set(["model_not_found", "unsupported_model", "model_not_available", "model_not_supported", "deployment_not_found"])], + ["rate_limited", new Set(["rate_limit_exceeded", "rate_limit_error", "too_many_requests", "throttling", "throttled", "rate_limited"])], + ["upstream_unavailable", new Set(["server_is_overloaded", "overloaded_error", "service_unavailable", "unavailable"])], +]; + +// Context overflow from message text uses the same verdict the combo router trusts, so a validation +// error that merely quotes "prompt is too long" (an invalid tool name, for example) is not an overflow. +const KEYWORDS: Readonly> = { + location_unsupported: ["location is not supported", "unsupported location", "not supported in your region", "region is not supported", "country, region, or territory", "not available in your country", "not available in your region"], + account_verification_required: ["verify your organization", "organization must be verified", "verification required", "verify your account", "account verification"], + billing_exhausted: ["insufficient quota", "quota exceeded", "quota exhausted", "exceeded your current quota", "run out of credits", "out of credits", "insufficient credits", "credit balance", "insufficient balance", "billing", "payment required"], + model_unavailable: ["model not found", "model does not exist", "unsupported model", "not allowed to use this model", "does not have access to model", "model is not available", "no such model"], + rate_limited: ["rate limit", "too many requests", "throttl"], +}; + +function token(value: string | undefined): string | undefined { + if (typeof value !== "string") return undefined; + const trimmed = value.trim(); + return trimmed && trimmed.length <= MAX_TOKEN_LENGTH ? trimmed.toLowerCase() : undefined; +} + +function structuredCondition(tokens: readonly string[]): UpstreamCondition | undefined { + for (const [condition, set] of STRUCTURED) { + if (tokens.some(value => set.has(value))) return condition; + } + return undefined; +} + +function mentions(message: string, condition: keyof typeof KEYWORDS): boolean { + return KEYWORDS[condition].some(keyword => message.includes(keyword)); +} + +function statusFallback(status: number): UpstreamCondition | undefined { + if (status === 401) return "auth_failed"; + if (status === 403) return "access_denied"; + if (status === 402) return "billing_exhausted"; + if (status === 404) return "model_unavailable"; + if (status === 429) return "rate_limited"; + if (status === 503 || status === 529) return "upstream_unavailable"; + if (status >= 500) return "upstream_failed"; + if (status >= 400) return "request_rejected"; + return undefined; +} + +/** + * Precedence: 401 is authoritative; structured tokens next; keyword evidence only for 4xx + * statuses (a 5xx stays a server failure whatever its text says); a bare status last. + */ +export function classifyUpstreamCondition(evidence: UpstreamConditionEvidence): UpstreamCondition | undefined { + const { status } = evidence; + if (!Number.isInteger(status)) return undefined; + if (status === 401) return "auth_failed"; + const tokens = [token(evidence.code), token(evidence.type), token(evidence.reason)].filter((value): value is string => value !== undefined); + const structured = structuredCondition(tokens); + if (structured) return structured; + const message = typeof evidence.message === "string" ? evidence.message.slice(0, MAX_MESSAGE_SCAN).toLowerCase() : ""; + if (message && status >= 400 && status < 500) { + if (isDefiniteContextOverflow(status, evidence.message!.slice(0, MAX_MESSAGE_SCAN))) return "context_overflow"; + if (mentions(message, "location_unsupported")) return "location_unsupported"; + if (mentions(message, "account_verification_required")) return "account_verification_required"; + // A 429 that names a rate limit is a rate limit even when it also mentions quota. + if (status === 429 && mentions(message, "rate_limited")) return "rate_limited"; + if (mentions(message, "billing_exhausted")) return "billing_exhausted"; + if (mentions(message, "model_unavailable")) return "model_unavailable"; + if (mentions(message, "rate_limited")) return "rate_limited"; + } + return statusFallback(status); +} + +const MESSAGES: Readonly> = { + auth_failed: "The provider rejected the configured credentials.", + access_denied: "The provider denied access to this request.", + context_overflow: "The request exceeds the model's context window.", + location_unsupported: "The provider does not serve this request from the current location.", + account_verification_required: "The provider requires account verification before serving this model.", + billing_exhausted: "The provider account has no remaining quota or credits.", + model_unavailable: "The requested model is not available from the provider.", + rate_limited: "The provider rate limit was reached; retry later.", + upstream_unavailable: "The provider is temporarily unavailable; retry later.", + upstream_failed: "The provider failed to complete the request.", + request_rejected: "The provider rejected the request.", +}; + +const PROVIDER_ID = /^[A-Za-z0-9._-]{1,64}$/; + +/** Proxy-written text for a condition; the provider id comes from configuration, never from an error. */ +export function upstreamConditionMessage(condition: UpstreamCondition, providerId?: string): string { + const base = MESSAGES[condition]; + return providerId !== undefined && PROVIDER_ID.test(providerId) ? `${base} (provider: ${providerId})` : base; +} diff --git a/src/providers/fastwire.ts b/src/providers/fastwire.ts index 61bea92fe9c..a2a4087b037 100644 --- a/src/providers/fastwire.ts +++ b/src/providers/fastwire.ts @@ -1,3 +1,4 @@ +import { boundedServiceTier } from "../lib/response-service-tier"; import type { AttemptTierOutcome, FastWire, @@ -361,7 +362,7 @@ export function createAdapterTierMetadata( return { outcome, observeResponseServiceTier(value: unknown) { - const sanitized = sanitizeLogMetadataString(value); + const sanitized = boundedServiceTier(value); if (sanitized) outcome.responseServiceTier = sanitized; }, markResponseUnparseable() {}, @@ -413,7 +414,7 @@ export function createAdapterTierMetadata( } return; } - const sanitized = sanitizeLogMetadataString(value); + const sanitized = boundedServiceTier(value); if (sanitized) outcome.responseServiceTier = sanitized; if (!responseCanConfirmFast) return; if (canonicalFromWire(context.fastWire, value) === "priority") { diff --git a/src/routing/fallback-policy.ts b/src/routing/fallback-policy.ts index 6a47f71301f..a517c014d3d 100644 --- a/src/routing/fallback-policy.ts +++ b/src/routing/fallback-policy.ts @@ -13,6 +13,7 @@ * Privacy: events carry public selectors, coarse trigger codes and device ids only. No request * body, credential, account id, label or email reaches the ring or the refusal body. */ +import { formatClientRetryAfter } from "../lib/client-retry-after"; import type { OcxConfig } from "../types"; import type { OcxFallbackConfig, OcxFallbackKind, OcxFallbackSwitches } from "../types/fallback"; import { FALLBACK_DEVICE_ID, FALLBACK_SELECTOR } from "../config/schema/fallback-policy"; @@ -262,7 +263,8 @@ export function fallbackRefusedResponse(event: FallbackEvent, hop: Pick { + const fail = (status: number, closeReason: PassthroughCloseReason | "non_stream", message: string, type: string, + detail: FailureDetail, storedReason = message) => { const safeMessage = redactSecretString(message); - logCtx.upstreamError = storedReason.slice(0, 500); + recordLocalFailureDetail(logCtx, storedReason, detail); finalize(status, { closeReason }); return anthropicErrorResponse(status, safeMessage, type); }; @@ -370,11 +373,11 @@ async function anthropicNativePassthrough( req.signal, ); if (result.kind === "timeout") { - return fail(504, "non_stream", "anthropic passthrough timed out waiting for response headers", "timeout_error"); + return fail(504, "non_stream", "anthropic passthrough timed out waiting for response headers", "timeout_error", { code: "header_timeout" }); } if (result.kind === "error") { const err = result.error; - return fail(502, "non_stream", `anthropic passthrough failed: ${err instanceof Error ? err.message : String(err)}`, "api_error", "anthropic passthrough failed: upstream connection error"); + return fail(502, "non_stream", `anthropic passthrough failed: ${err instanceof Error ? err.message : String(err)}`, "api_error", { code: "connect_failed" }, "anthropic passthrough failed: upstream connection error"); } const upstream = result.upstream; @@ -399,13 +402,15 @@ async function anthropicNativePassthrough( // idle/size bounds — headers are NOT yet sent here, so real statuses are available. const bodyResult = await readBoundedPassthroughBody(upstream, bodyGuard); if (bodyResult.kind === "client_cancel") { - return fail(499, "client_cancel", "client closed request during anthropic passthrough", "api_error"); + return fail(499, "client_cancel", "client closed request during anthropic passthrough", "api_error", { code: "client_closed" }); } if (bodyResult.kind === "stall") { - return fail(504, "body_stall", `anthropic passthrough body stalled: no upstream bytes for ${Math.round(bodyGuard.stallMs / 1000)}s`, "timeout_error"); + return fail(504, "body_stall", `anthropic passthrough body stalled: no upstream bytes for ${Math.round(bodyGuard.stallMs / 1000)}s`, "timeout_error", + { code: "body_stall", value: bodyGuard.stallMs }); } if (bodyResult.kind === "overflow") { - return fail(502, "body_overflow", `anthropic passthrough body exceeded ${bodyGuard.maxBytes} bytes`, "api_error"); + return fail(502, "body_overflow", `anthropic passthrough body exceeded ${bodyGuard.maxBytes} bytes`, "api_error", + { code: "body_overflow", value: bodyGuard.maxBytes }); } const text = bodyResult.text; if (upstream.ok) { @@ -417,20 +422,25 @@ async function anthropicNativePassthrough( // Upstream text is untrusted: retain only a closed type vocabulary in history. // Bound parsing work independently of the larger response-relay body limit. const statusReason = `Provider error ${upstream.status}`; - logCtx.upstreamError = statusReason; + recordLocalFailureDetail(logCtx, statusReason, { code: "provider_error" }, { upstreamEvidence: true }); if (text.length <= PASSTHROUGH_ERROR_DETAIL_MAX_CHARS) { try { const parsed: unknown = JSON.parse(text); if (isRec(parsed) && parsed.type === "error" && isRec(parsed.error)) { const upstreamType = parsed.error.type; const knownType = PASSTHROUGH_ERROR_TYPES.find(type => type === upstreamType); - if (knownType) logCtx.upstreamError = `${statusReason}: ${knownType}`; + if (knownType) { + recordLocalFailureDetail(logCtx, `${statusReason}: ${knownType}`, { code: "provider_error", type: knownType }, { upstreamEvidence: true }); + } + // The condition is classified here from the upstream message; only the closed member is kept. + const upstreamMessage = typeof parsed.error.message === "string" ? parsed.error.message : undefined; + logCtx.upstreamCondition = classifyUpstreamCondition({ status: upstream.status, type: knownType, message: upstreamMessage }); } } catch { /* Malformed errors keep the fixed status-only diagnostic. */ } } } finalize(upstream.status, { closeReason: "non_stream" }); - const retryAfter = upstream.headers.get("retry-after"); + const retryAfter = formatClientRetryAfter(upstream.headers.get("retry-after")); return new Response(text, { status: upstream.status, headers: { ...rateLimitHeaders, "Content-Type": contentType, ...(retryAfter ? { "Retry-After": retryAfter } : {}) }, @@ -1312,7 +1322,8 @@ async function handleClaudeMessagesWithBudget( ? REPLAY_REFUSED_STATUS : nativeMainFence ? 503 : contextError ? 400 : transient ? 529 : response.status; const outHeaders = new Headers({ "Content-Type": "application/json" }); - if (retryAfter) outHeaders.set("Retry-After", retryAfter); + const clientRetryAfter = formatClientRetryAfter(retryAfter); + if (clientRetryAfter) outHeaders.set("Retry-After", clientRetryAfter); else if (transient) outHeaders.set("Retry-After", "2"); if (replayRefusal) applyReplayRefusalClientHeaders(outHeaders); const out = new Response(JSON.stringify(anthropicErrorBody( diff --git a/src/server/context-history.ts b/src/server/context-history.ts index 3e1db1f75e7..107c61f3383 100644 --- a/src/server/context-history.ts +++ b/src/server/context-history.ts @@ -1,3 +1,4 @@ +import { formatClientRetryAfter } from "../lib/client-retry-after"; import { isolateCodexPoolClientMetadata, mergeCodexSelectedHeaders } from "../codex/forward-transport-headers"; import { CodexInstallationIdUnavailableError } from "../codex/installation-id"; /** Native history/notes JSON relay. No interpretation of encrypted tool arguments or retries. */ @@ -185,7 +186,10 @@ async function relayContextHistory( if (result.oversized) return formatErrorResponse(502, "upstream_error", "Context response exceeded 16 MiB"); const outputHeaders = new Headers(); for (const key of RESPONSE_HEADERS) { - const value = response.headers.get(key); if (value !== null) outputHeaders.set(key, value); + const raw = response.headers.get(key); + // Retry advice leaves as an integer this proxy formats, never the upstream bytes. + const value = key === "retry-after" ? formatClientRetryAfter(raw) ?? null : raw; + if (value !== null) outputHeaders.set(key, value); } // A context 403 is not evidence that the model credential is invalid. Don't mutate pool // health/quota or retry writes; preserve the real upstream result for the caller. diff --git a/src/server/index/serve-options.ts b/src/server/index/serve-options.ts index 5d178b62cb5..14a1002d795 100644 --- a/src/server/index/serve-options.ts +++ b/src/server/index/serve-options.ts @@ -216,6 +216,7 @@ import { reasoningArchiveErrorResponse } from "../responses/reasoning-archive-er import { withGrokSessionIdentity } from "../../grok/session-identity"; import { withCallerSessionIdentity } from "../caller-session-identity"; import { agentAssertionUnsupportedResponse, hasAgentAssertionAuthorization } from "../../lib/authorization-scheme"; +import { runTurnStateCallerScope } from "../turn-state-handles"; export type ServerIngress = "public" | "unauthenticated-loopback" | "hub-management" | "claude-intercept" | "hub-link"; @@ -1986,6 +1987,7 @@ export function createServeOptions(ctx: ServeOptionsContext) { } as const; const routeFetch = serveOptions.fetch; // x-opencodex-served-by on GET /v1/models, whichever branch answered (src/remote/served-by.ts). - return { ...serveOptions, fetch: async (req: Request, requestServer: Server): Promise => - stampServedBy(req.method, codexCompatibleUrl(req.url).pathname, await routeFetch(req, requestServer)) } as const; + // Each request runs with its own caller slot, which admission fills for turn-state handle binding. + return { ...serveOptions, fetch: (req: Request, requestServer: Server): Promise => runTurnStateCallerScope(async () => + stampServedBy(req.method, codexCompatibleUrl(req.url).pathname, await routeFetch(req, requestServer))) } as const; } diff --git a/src/server/index/websocket-handler.ts b/src/server/index/websocket-handler.ts index d97d63266e1..37781d2014a 100644 --- a/src/server/index/websocket-handler.ts +++ b/src/server/index/websocket-handler.ts @@ -93,6 +93,7 @@ import type { ServeOptionsContext } from "./serve-options"; import type { RequestMetricsRecorder } from "../request-metrics"; import { resolveInboundBodyLimitBytes } from "../request-decompress"; import { responseToolOwnership } from "../responses/response-tool-ownership"; +import { runTurnStateCallerScope } from "../turn-state-handles"; /** * The WebSocket half of the Bun.serve options, split out of serve-options.ts to keep that file @@ -310,7 +311,8 @@ export function createWebsocketHandler( const payload: Record = { ...frame }; delete payload.type; turnAdmissionLease.bindAbortController(turnAbort); - void (async () => { + // The frame runs with its own caller slot, which admission fills for turn-state handle binding. + void runTurnStateCallerScope(async () => { const start = Date.now(); const requestId = nextRequestLogId(start); // Resolved once at the handshake — a frame has no request headers left @@ -431,7 +433,7 @@ export function createWebsocketHandler( if (!logged && turnAbort.signal.aborted) finalizeLog(499); if (ws.data.cancel === cancelTurn) ws.data.cancel = undefined; } - })(); + }); }, close(ws: ServerWebSocket, code: number, reason: string) { if (ws.data.kind === "remote-workspace-agent") { diff --git a/src/server/messages-native.ts b/src/server/messages-native.ts index c15763f9398..0e23514b8cc 100644 --- a/src/server/messages-native.ts +++ b/src/server/messages-native.ts @@ -44,7 +44,7 @@ import { readBoundedResponseBody } from "../lib/bounded-body"; import { classifyError } from "../lib/errors"; import { relaySseWithPayloadRewrite } from "./sse-payload-rewrite"; import { redactSecretString } from "../lib/redact"; -import { resolveClientRetryAfter } from "../lib/retry-after"; +import { formatClientRetryAfter, resolveClientRetryAfter } from "../lib/retry-after"; import { enrichOpenCodeZenUpstreamMessage } from "../providers/opencode-zen-rate-limit"; import { isTranslatorBudgetExceededError, type TranslatorBudget } from "../lib/translator-budget"; import { @@ -380,7 +380,8 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions) const localOAuthFailure = (error: unknown): Response | null => { if (error instanceof AnthropicAccountCooldownError) { const response = fail(429, error.message, "rate_limit_error"); - if (error.retryAfterSeconds !== null) response.headers.set("retry-after", String(error.retryAfterSeconds)); + const advice = error.retryAfterSeconds !== null ? formatClientRetryAfter(error.retryAfterSeconds) : undefined; + if (advice !== undefined) response.headers.set("retry-after", advice); return response; } if (error instanceof OAuthAccountPausedError) return fail(403, publicOAuthAuthenticationErrorMessage(error), "permission_error"); @@ -454,7 +455,8 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions) cleanupAbort(); upstream.abort(); if (!(error instanceof RequestPacingQueueOverloadError)) throw error; const refusal = fail(429, error.message, "rate_limit_error"); - refusal.headers.set("Retry-After", String(error.retryAfterSeconds)); + const advice = formatClientRetryAfter(error.retryAfterSeconds); + if (advice !== undefined) refusal.headers.set("Retry-After", advice); return refusal; } } @@ -835,7 +837,8 @@ export async function handleNativeMessages(options: HandleNativeMessagesOptions) const sendError = error instanceof UpstreamRetryEvidenceError ? error.cause : error; if (sendError instanceof RequestPacingQueueOverloadError) { const refusal = fail(429, sendError.message, "rate_limit_error"); - refusal.headers.set("Retry-After", String(sendError.retryAfterSeconds)); + const advice = formatClientRetryAfter(sendError.retryAfterSeconds); + if (advice !== undefined) refusal.headers.set("Retry-After", advice); return refusal; } if (sendError instanceof SendBudgetExhaustedError) return fail(429, sendError.message, "send_budget_exhausted", "send_budget_exhausted"); @@ -1085,7 +1088,8 @@ function nativeMessagesErrorResponse(response: Response, bodyText: string, finis ?? (upstreamRetryAfter?.trim() === "0" ? "0" : undefined); finishLog(response.status, safeMessage); const headers = new Headers({ "Content-Type": "application/json" }); - if (retryAfter) headers.set("Retry-After", retryAfter); + const clientRetryAfter = formatClientRetryAfter(retryAfter); + if (clientRetryAfter) headers.set("Retry-After", clientRetryAfter); else if (transient) headers.set("Retry-After", "2"); if (replayRefusal) applyReplayRefusalClientHeaders(headers); // The native envelope keeps its shape (no added code); only an overflow's wording changes, so diff --git a/src/server/messages-shared.ts b/src/server/messages-shared.ts index 20310e4e88f..eab799e7dd3 100644 --- a/src/server/messages-shared.ts +++ b/src/server/messages-shared.ts @@ -28,6 +28,7 @@ import { isTranslatorBudgetExceededError } from "../lib/translator-budget"; import { AnthropicRequestError, isRec, type Rec } from "../claude/inbound-records"; import type { RequestLogContext } from "./request-log"; import { recordGenerationEvent } from "./request-log-generation-window"; +import { recordLocalFailureDetail } from "./request-log-failure-detail"; import type { OcxConfig } from "../types"; export function anthropicUsageToOcx(usage: Rec | undefined): { inputTokens: number; outputTokens: number; cachedInputTokens?: number; cacheReadInputTokens?: number; cacheCreationInputTokens?: number; cacheCreation1hInputTokens?: number } | undefined { @@ -267,7 +268,8 @@ export function tapAnthropicSseForLog( // A cut-short turn, logged as the Responses relay logs a stall-timeout incomplete // (httpStatusForRequestLogTerminal: only a max_output_tokens incomplete is a 200). A 200 // row with no terminalStatus also lost its failure diagnostics in usage.jsonl. - logCtx.upstreamError = message.slice(0, 500); + recordLocalFailureDetail(logCtx, message, closeReason === "body_stall" + ? { code: "body_stall", value: guard?.stallMs ?? 0 } : { code: "body_overflow", value: guard?.maxBytes ?? 0 }); finalize(502, { terminalStatus: "incomplete", closeReason }); closeWithErrorFrame(errType, message); } @@ -350,7 +352,7 @@ export function tapAnthropicSseForLog( // reset (below), so the client never reads a partial answer as a finished message. logCtx.transportPhase = "mid_stream"; logCtx.terminalSource = "synthetic"; - logCtx.upstreamError = failure; + recordLocalFailureDetail(logCtx, failure, { code: lastDeliveredStop === "error" ? "stream_error_stop" : "stream_ended_early" }); if (logCtx.activeAttempt) logCtx.activeAttempt.streamAborted = true; finalize(502, { terminalStatus: "failed", closeReason: "terminal" }); closeWithErrorFrame("api_error", failure); @@ -411,6 +413,8 @@ export function tapAnthropicSseForLog( const message = redactSecretString(`anthropic passthrough upstream stream failed: ${err instanceof Error ? err.message : String(err)}`); logCtx.transportPhase = "mid_stream"; logCtx.terminalSource = "synthetic"; + // The runtime error text stays internal; the row keeps the fixed sentence only. + recordLocalFailureDetail(logCtx, "anthropic passthrough upstream stream failed", { code: "stream_failed" }); logCtx.upstreamError = message.slice(0, 500); if (logCtx.activeAttempt) logCtx.activeAttempt.streamAborted = true; finalize(502, { terminalStatus: "failed", closeReason: "terminal" }); diff --git a/src/server/native-final-log.ts b/src/server/native-final-log.ts index 7e58842ad48..ce04995a9ec 100644 --- a/src/server/native-final-log.ts +++ b/src/server/native-final-log.ts @@ -70,12 +70,8 @@ export function createNativeFinalLog( commit(outcome) { if (committed) return false; committed = true; - // A native ingress row never persists upstream-authored text: an upstream error can echo - // a credential no redaction pattern recognizes. Status, codes we derive, and attribution stay. - delete logCtx.upstreamError; - delete logCtx.upstreamErrorCode; - delete logCtx.upstreamErrorType; - delete logCtx.upstreamRequestId; + // Upstream evidence stays on the context so the final writer can classify it; the row + // projection (src/usage/error-detail.ts) removes upstream-authored text before any writer. let { status, terminalStatus } = outcome; if (innerStatus === undefined) { // Cut off before the inner path settled: what it observed so far is not a complete diff --git a/src/server/relay.ts b/src/server/relay.ts index 133d11d3ae0..db51a8e5332 100644 --- a/src/server/relay.ts +++ b/src/server/relay.ts @@ -36,6 +36,7 @@ import { import { replaceSseDataPayload, splitSseBlock, sseDataPayload } from "./sse-payload-rewrite"; import { createBoundedResponseLogBody } from "./response-log-body"; import { clientWireLogOf } from "./inference/client-wire"; +import { knownModelIdentity } from "../lib/model-identity"; import { recordClientWireRequestLog } from "./inference/client-wire-log"; import { nativeResponseFingerprint } from "./responses/native-response-json"; import { nativeResponseOutput } from "./responses/native-response-output"; @@ -1824,13 +1825,28 @@ export function codexSafetyBufferingFilterOptions( return { dropCodexSafetyBuffering: config.dropCodexSafetyBuffering === true }; } -export function sanitizePassthroughHeaders(upstream: Headers, options?: CodexSafetyBufferingFilterOptions): Headers { +/** Model ids a passthrough route knows, for the relayed model headers. */ +export interface PassthroughHeaderOptions extends CodexSafetyBufferingFilterOptions { + knownModels?: readonly string[]; + provider?: string; +} + +// Upstream-reported model headers: relayed only as a model id the proxy already knows (the route's +// own ids, the bundled Codex catalog, or the selected provider's catalog), never as upstream bytes. +const PASSTHROUGH_MODEL_HEADERS: ReadonlySet = new Set(["openai-model", "x-codex-safety-buffering-faster-model"]); + +export function sanitizePassthroughHeaders(upstream: Headers, options?: PassthroughHeaderOptions): Headers { const dropSafetyBuffering = options?.dropCodexSafetyBuffering === true; const out = new Headers(); upstream.forEach((value, key) => { const lower = key.toLowerCase(); if (PASSTHROUGH_DROP_HEADERS.has(lower)) return; if (dropSafetyBuffering && CODEX_SAFETY_BUFFERING_HEADER_SET.has(lower)) return; + if (PASSTHROUGH_MODEL_HEADERS.has(lower)) { + const known = knownModelIdentity(value.trim(), options?.knownModels, options?.provider); + if (known) out.set(key, known); + return; + } out.set(key, value); }); return out; diff --git a/src/server/request-log-failure-detail.ts b/src/server/request-log-failure-detail.ts new file mode 100644 index 00000000000..d7c0568ba1e --- /dev/null +++ b/src/server/request-log-failure-detail.ts @@ -0,0 +1,54 @@ +/** + * Proxy-authored failure detail for request logs. + * + * Some transports describe a failure themselves (header timeout, body stall, byte cap, client close, + * a restated upstream status and closed error type). The row keeps a closed FailureDetail code with + * bounded parameters (src/lib/failure-detail.ts); the English text goes only into the context's + * upstreamError, which internal classifiers and status heuristics read and which never reaches a row. + * Only proxy-composed text may be passed here. + */ +import type { FailureDetail, FailureDetailCode } from "../lib/failure-detail"; + +export type { FailureDetail }; + +export const FAILURE_DETAIL_MAX_LENGTH = 500; + +/** Contexts whose upstreamError currently holds proxy text rather than upstream evidence. */ +const localOnly = new WeakSet(); + +/** + * Pass `upstreamEvidence: true` only when the text restates an upstream response (its status and a + * closed type); a local timeout, cap or cancel is not evidence of an upstream condition. + */ +export function recordLocalFailureDetail( + logCtx: { upstreamError?: string; failureDetail?: FailureDetail }, + text: string, + detail: FailureDetail, + options: { upstreamEvidence?: boolean } = {}, +): void { + // The classifier and status heuristics keep reading upstreamError; the row keeps the closed detail. + logCtx.upstreamError = text.slice(0, FAILURE_DETAIL_MAX_LENGTH); + logCtx.failureDetail = detail; + if (options.upstreamEvidence) localOnly.delete(logCtx); + else localOnly.add(logCtx); +} + +/** True when the context's upstreamError is proxy text; the final row then carries no upstream evidence. */ +export function upstreamErrorIsLocal(logCtx: object): boolean { + return localOnly.has(logCtx); +} + +const INCOMPLETE_REASONS: Readonly> = { + max_output_tokens: ["Output reached the requested token limit (max_output_tokens)", "output_limit"], + upstream_stall_timeout: ["Upstream stalled: no data for the stall-timeout window (upstream_stall_timeout)", "stall_timeout"], + adapter_eof: ["Upstream stream ended unexpectedly without a terminal event (adapter_eof)", "adapter_eof"], +}; + +/** + * A structured `incomplete_details.reason` (emitted by the bridge on a stall timeout or adapter EOF): + * the context text that explains it, and a closed detail for a known reason. + */ +export function incompleteReasonDetail(reason: string): { text: string; detail?: FailureDetail } { + const known = Object.prototype.hasOwnProperty.call(INCOMPLETE_REASONS, reason) ? INCOMPLETE_REASONS[reason] : undefined; + return known ? { text: known[0], detail: { code: known[1] } } : { text: `Upstream incomplete: ${reason}` }; +} diff --git a/src/server/request-log-terminal-status.ts b/src/server/request-log-terminal-status.ts index 80174c82084..514caf93f0b 100644 --- a/src/server/request-log-terminal-status.ts +++ b/src/server/request-log-terminal-status.ts @@ -84,8 +84,10 @@ function noteBoundedDiagnostic( logCtx[field] = value; const status = logCtx.terminalHttpStatus; if (status === undefined || status >= 500) { - const { upstreamErrorCode: code, upstreamRequestId: requestId } = upstreamDiagnosticLogFields(logCtx); - console.warn(`[opencodex] upstream failure${status ? ` status=${status}` : ""}${code ? ` code=${code}` : ""}${requestId ? ` request_id=${requestId}` : ""}`); + // Service logs persist too: print only closed-vocabulary values, never an upstream id or code. + const { upstreamErrorCode: rawCode, upstreamErrorType: type } = upstreamDiagnosticLogFields(logCtx); + const code = rawCode !== undefined && KNOWN_BARE_ERROR_CODES.has(rawCode) ? rawCode : undefined; + console.warn(`[opencodex] upstream failure${status ? ` status=${status}` : ""}${type ? ` type=${type}` : ""}${code ? ` code=${code}` : ""}`); } } diff --git a/src/server/request-log.ts b/src/server/request-log.ts index cbfb520c65f..b4a0cf347b1 100644 --- a/src/server/request-log.ts +++ b/src/server/request-log.ts @@ -30,6 +30,9 @@ import type { RequestSpendSettlement } from "./responses/request-spend"; import type { AdapterTierMetadata } from "../providers/fastwire"; import { UPSTREAM_RESET_REPLAY_REFUSED_CODE } from "../lib/upstream-retry"; import { redactSecretString, sanitizeLogMetadataString } from "../lib/redact"; +import type { UpstreamCondition } from "../lib/upstream-condition"; +import { boundedServiceTier, errorDetailFor, projectErrorDetail } from "../usage/error-detail"; +import { incompleteReasonDetail, upstreamErrorIsLocal, type FailureDetail } from "./request-log-failure-detail"; import { appendUsageEntry, classifyCacheTelemetryProvenance, @@ -243,6 +246,8 @@ export interface RequestLogContext extends UpstreamErrorDiagnostics { * message) extracted from a `response.failed` SSE payload or non-streaming error body, so the * request log / GUI shows the actual upstream failure rather than only the HTTP-mapped code. */ upstreamError?: string; + failureDetail?: FailureDetail; // closed code + bounded params (src/lib/failure-detail.ts) + upstreamCondition?: UpstreamCondition; // classified at capture where the evidence is not kept on the context /** HTTP status derived from a terminal `response.failed` SSE payload (429/401/503/etc.). */ terminalHttpStatus?: number; /** Recognized structured terminal code whose exact identity must survive status mapping. */ @@ -353,8 +358,11 @@ export interface RequestLogEntry extends UpstreamErrorDiagnostics { errorCode?: string; terminalStatus?: ResponsesTerminalStatus; closeReason?: "terminal" | "client_cancel" | "non_stream" | "body_stall" | "body_overflow"; - /** Secret-redacted upstream error reason, surfaced in /api/logs and the GUI detail modal. */ + /** Input only: addRequestLog derives the two fields below from it, then removes it. */ upstreamError?: string; + upstreamCondition?: UpstreamCondition; // closed enum, src/lib/upstream-condition.ts + failureDetail?: FailureDetail; // closed code + bounded params, see request-log-failure-detail.ts + rateLimitResetAt?: number; // provider quota window end, epoch ms, bounded usageStatus: UsageStatus; usage?: OcxUsage; totalTokens?: number; @@ -473,7 +481,10 @@ export function requestLogEntryFromPersistedUsage(entry: PersistedUsageEntry): R const claudeCompatibility = normalizeClaudeCompatibilityUsageLog(entry.claudeCompatibility); const spend = normalizeRequestSpend(entry.spend); const protocolTrace = parseProtocolTraceV1(entry.protocolTrace); - return { + // projectErrorDetail bounds the tier fields (top-level and per attempt) itself, so this stays safe + // for a row that did not come through the disk reader; attempts are copied before it edits them. + const attempts = Array.isArray(entry.attempts) ? entry.attempts.map(attempt => ({ ...attempt })) : entry.attempts; + return projectErrorDetail({ requestId: entry.requestId, ...(isLogicalRequestId(entry.logicalRequestId) ? { logicalRequestId: entry.logicalRequestId } : {}), timestamp: entry.timestamp, @@ -509,14 +520,14 @@ export function requestLogEntryFromPersistedUsage(entry: PersistedUsageEntry): R ...modelIdentityLogFields(entry), status: entry.status, durationMs: entry.durationMs, - ...(entry.errorCode ? { errorCode: entry.errorCode } : {}), + // Closed code, condition, failure detail and quota reset; legacy upstream text is read once and dropped. + ...errorDetailFor(entry), ...(terminalStatus ? { terminalStatus } : {}), ...(closeReason ? { closeReason } : {}), - ...(entry.upstreamError ? { upstreamError: entry.upstreamError } : {}), usageStatus: entry.usageStatus, ...(entry.usage ? { usage: entry.usage } : {}), ...(entry.totalTokens !== undefined ? { totalTokens: entry.totalTokens } : {}), - ...(entry.attempts !== undefined ? { attempts: entry.attempts } : {}), + ...(attempts !== undefined ? { attempts } : {}), ...(entry.attemptNormalizationDropped === true ? { attemptNormalizationDropped: true } : {}), ...(spend ? { spend } : {}), @@ -534,7 +545,7 @@ export function requestLogEntryFromPersistedUsage(entry: PersistedUsageEntry): R : {}), ...normalizeRequestFailureAttribution(entry), ...(protocolTrace ? { protocolTrace } : {}), - }; + }); } /** @@ -613,6 +624,9 @@ export function rehydrateRequestLogsAfterLedgerReplacement( } export function addRequestLog(entry: RequestLogEntry) { + // Rows keep proxy-owned error facts only; upstream error text and tokens stop here (both the + // retained ring row and the usage.jsonl projection below read the projected entry). + entry = projectErrorDetail(entry); // Sanitize ONCE, at the ingress, and use that one value for both destinations. // // `addFinalRequestLog` is not the only way in: `addRequestLog` is exported and callable @@ -622,13 +636,13 @@ export function addRequestLog(entry: RequestLogEntry) { // line-oriented viewer — while `usage.jsonl` looked clean, which is the worst shape for a // sanitization bug because the safe surface is the one you check. const shadowCallRewrittenFrom = sanitizeLogMetadataString(entry.shadowCallRewrittenFrom); - const servedModel = modelIdentityLogFields(entry).servedModel; + const identity = modelIdentityLogFields(entry), servedModel = identity.servedModel; const claudeCompatibility = normalizeClaudeCompatibilityUsageLog(entry.claudeCompatibility); const jevDecision = normalizePersistedJevDecision(entry.jevDecision); const attempts = normalizedAttempts(entry.attempts); const attemptsDropped = Array.isArray(entry.attempts) && attempts.length < entry.attempts.length; const retained: RequestLogEntry = shadowCallRewrittenFrom === entry.shadowCallRewrittenFrom - && servedModel === entry.servedModel + && servedModel === entry.servedModel && identity.resolvedModel === entry.resolvedModel && entry.claudeCompatibility === undefined && entry.jevDecision === undefined && !attemptsDropped @@ -636,10 +650,7 @@ export function addRequestLog(entry: RequestLogEntry) { : { ...entry, ...(entry.attemptNormalizationDropped === true || attemptsDropped ? { attemptNormalizationDropped: true } : {}), ...(shadowCallRewrittenFrom ? { shadowCallRewrittenFrom } : {}) }; if (!shadowCallRewrittenFrom && retained !== entry) delete retained.shadowCallRewrittenFrom; - if (!servedModel && retained !== entry) { - delete retained.servedModel; - if (retained.resolvedModel === entry.servedModel) delete retained.resolvedModel; - } + if (retained !== entry) { if (!servedModel) delete retained.servedModel; if (!identity.resolvedModel) delete retained.resolvedModel; } if (claudeCompatibility) retained.claudeCompatibility = claudeCompatibility; else if (retained !== entry) delete retained.claudeCompatibility; if (jevDecision) retained.jevDecision = jevDecision; @@ -658,7 +669,8 @@ export function addRequestLog(entry: RequestLogEntry) { ...(entry.errorCode ? { errorCode: entry.errorCode } : {}), ...(entry.terminalStatus ? { terminalStatus: entry.terminalStatus } : {}), ...(entry.closeReason ? { closeReason: entry.closeReason } : {}), - ...(entry.upstreamError ? { upstreamError: entry.upstreamError } : {}), + ...(entry.upstreamCondition ? { upstreamCondition: entry.upstreamCondition } : {}), ...(entry.failureDetail ? { failureDetail: entry.failureDetail } : {}), + ...(entry.rateLimitResetAt !== undefined ? { rateLimitResetAt: entry.rateLimitResetAt } : {}), } : {}; appendUsageEntry({ @@ -972,7 +984,7 @@ export function applyResponseLogMetadata(logCtx: RequestLogContext, payload: unk recordObservedServedModel(logCtx, (source as { model?: unknown }).model); const serviceTier = (source as { service_tier?: unknown }).service_tier; if (typeof serviceTier === "string" && serviceTier.trim()) { - const sanitized = sanitizeLogMetadataString(serviceTier); + const sanitized = boundedServiceTier(serviceTier); if (sanitized) logCtx.responseServiceTier = sanitized; logCtx.activeTierMetadata?.observeResponseServiceTier(serviceTier); } else if (Object.prototype.hasOwnProperty.call(source, "service_tier")) { @@ -1157,7 +1169,9 @@ function captureUpstreamErrorParsed( // reader-facing label so a generic 502 in /api/logs explains WHY the turn ended, not just the // mapped HTTP code. if (typeof reason === "string" && reason.trim()) { - logCtx.upstreamError = redactSecretString(incompleteReasonLabel(reason.trim())).slice(0, 500); + const incomplete = incompleteReasonDetail(reason.trim()); // A known reason also gets a closed row detail. + logCtx.upstreamError = redactSecretString(incomplete.text).slice(0, 500); + if (incomplete.detail) logCtx.failureDetail = incomplete.detail; } return; } @@ -1168,20 +1182,6 @@ function captureUpstreamErrorParsed( } } -/** Map a raw `incomplete_details.reason` (emitted by the bridge) to a reader-facing label. */ -function incompleteReasonLabel(reason: string): string { - switch (reason) { - case "max_output_tokens": - return `Output reached the requested token limit (${reason})`; - case "upstream_stall_timeout": - return `Upstream stalled: no data for the stall-timeout window (${reason})`; - case "adapter_eof": - return `Upstream stream ended unexpectedly without a terminal event (${reason})`; - default: - return `Upstream incomplete: ${reason}`; - } -} - /** Map a terminal Responses error object to the HTTP status we record in /api/logs. */ export function httpStatusFromTerminalError(error: { type?: string; @@ -1551,7 +1551,8 @@ function writeFinalRequestLog( const jevDecision = normalizePersistedJevDecision(logCtx.jevDecision); // Keyed by the live attempt objects, not the detached copies above. const protocolTrace = protocolTraceForRequest(logCtx, logCtx.attempts); - addLog({ + // Projected before any writer (an injected one too): the row keeps only proxy-owned error facts. + addLog(projectErrorDetail({ requestId, ...(isLogicalRequestId(logicalRequestId) ? { logicalRequestId } : {}), timestamp: start, @@ -1593,7 +1594,8 @@ function writeFinalRequestLog( ...(errorCode ? { errorCode } : {}), ...(meta?.terminalStatus ? { terminalStatus: meta.terminalStatus } : {}), ...(closeReason ? { closeReason } : {}), - ...(logCtx.upstreamError ? { upstreamError: logCtx.upstreamError } : {}), + ...(logCtx.upstreamError && !upstreamErrorIsLocal(logCtx) ? { upstreamError: logCtx.upstreamError } : {}), ...(logCtx.failureDetail ? { failureDetail: logCtx.failureDetail } : {}), + ...(logCtx.upstreamCondition ? { upstreamCondition: logCtx.upstreamCondition } : {}), ...upstreamDiagnosticLogFields(logCtx), usageStatus, ...(loggedUsage ? { usage: loggedUsage } : {}), @@ -1616,7 +1618,7 @@ function writeFinalRequestLog( ...(claudeCompatibility ? { claudeCompatibility } : {}), ...(protocolTrace ? { protocolTrace } : {}), ...attribution, - }); + })); // Formatted from the finalized snapshot, so the ring shows exactly what the ledger holds. for (const attempt of attempts ?? []) debugAttemptDeliverySummary(requestId, attempt); if (isUsageDebugEnabled()) { diff --git a/src/server/responses/codex-ws-exchange.ts b/src/server/responses/codex-ws-exchange.ts index 11e0c8b5422..4fa9cdc097f 100644 --- a/src/server/responses/codex-ws-exchange.ts +++ b/src/server/responses/codex-ws-exchange.ts @@ -3,7 +3,7 @@ import { mergeSteeringContinuation } from "./native-steering-settings"; import { markNativeControlResponse } from "./native-response-control"; import type { NativeResponseControl } from "./native-response-control"; import { MAX_CLIENT_SSE_FRAME_BYTES } from "../sse-frame-buffer"; -import { isSafeResponseHeader } from "../safe-response-headers"; +import { isSafeResponseHeader, type ResponseMetadataContext } from "../safe-response-headers"; import { CodexWsMetadata, type CodexWsQuotaObserver } from "./codex-ws-metadata"; import { CODEX_RESPONSES_HTTP_URL, type PreparedCodexWsRequest } from "./codex-ws-request"; import { CodexWsCorrelation } from "./codex-ws-correlation"; @@ -36,6 +36,8 @@ interface ExchangeOptions { * control exchanges and on transports without the metadata channel. */ preOutputRefusalHold?: CodexWsPreOutputRefusalHold; + /** Turn-state binding and known models for the metadata this exchange relays. */ + metadataContext?: ResponseMetadataContext; } const HTTP_HEADER_TOKEN = /^[!#$%&'*+.^_`|~0-9a-z-]+$/i; @@ -45,7 +47,7 @@ function record(value: unknown): value is Record { } /** Rebuild only permitted metadata: upstream framing describes a different body. */ -function rejectionHeaders(source: Record, prelude: Headers): Headers { +function rejectionHeaders(source: Record, prelude: Headers, context: ResponseMetadataContext): Headers { const connectionHeaders = new Set(); for (const [name, value] of Object.entries(source)) { if (name.toLowerCase() !== "connection" || typeof value !== "string") continue; @@ -57,7 +59,7 @@ function rejectionHeaders(source: Record, prelude: Headers): He // Reuse the metadata owner's count/value/family budgets and window freshness // rules, without publishing quota twice. Pool bookkeeping consumes the HTTP // projection; plain-main publication belongs only to the WS observer. - const projected = new CodexWsMetadata(); + const projected = new CodexWsMetadata(undefined, context); try { for (const values of [Object.fromEntries(prelude), source]) { const headers = Object.fromEntries(Object.entries(values).filter(([name, value]) => { @@ -88,7 +90,7 @@ function rejectionHeaders(source: Record, prelude: Headers): He * The one 5xx exception is the opt-in pre-output refusal below (#6969): a structured upstream * refusal with nothing relayed but empty lifecycle frames, which the caller may replay. */ -function wrappedRejectionResponse(payload: Record, prelude: Headers): Response | null { +function wrappedRejectionResponse(payload: Record, prelude: Headers, context: ResponseMetadataContext): Response | null { if (payload.type !== "error" || payload.stream_id !== undefined) return null; // The native typed wrapper has one aliased field, not two competing statuses. if (Object.hasOwn(payload, "status_code") && Object.hasOwn(payload, "status")) return null; @@ -98,7 +100,7 @@ function wrappedRejectionResponse(payload: Record, prelude: Hea if (error != null && (!record(error) || [error.code, error.message].some(value => value != null && typeof value !== "string"))) return null; if (payload.headers != null && !record(payload.headers)) return null; - const headers = rejectionHeaders(record(payload.headers) ? payload.headers : {}, prelude); + const headers = rejectionHeaders(record(payload.headers) ? payload.headers : {}, prelude, context); return new Response(JSON.stringify({ error: error ?? { type: "upstream_error", message: "Upstream rejected the request" }, }), { status, headers }); @@ -118,6 +120,7 @@ function refusalErrorBody(source: unknown): Record { export function codexWsExchange(options: ExchangeOptions): Promise { const { session, url, init, prepared, sseFallback, onQuota, beforeDispatch, bunVersion, nativeControl, beforeContinuation, preOutputRefusalHold } = options; + const metadataContext = options.metadataContext ?? {}; const { frameText, headers } = prepared; const signal = init.signal ?? undefined; return new Promise((resolve, reject) => { @@ -148,7 +151,7 @@ export function codexWsExchange(options: ExchangeOptions): Promise { let terminalErrorStatus: number | null = null; let controller: ReadableStreamDefaultController | null = null; const encoder = new TextEncoder(); - const metadata = url === CODEX_RESPONSES_HTTP_URL ? new CodexWsMetadata(onQuota) : null; + const metadata = url === CODEX_RESPONSES_HTTP_URL ? new CodexWsMetadata(onQuota, metadataContext) : null; const correlation = session.retainable ? new CodexWsCorrelation(session.reused, id => session.hasCompleted(id)) : null; let detachOwner = () => {}; let detachSteering = () => {}; @@ -656,7 +659,7 @@ export function codexWsExchange(options: ExchangeOptions): Promise { // in-body delivery, so a held 429 can never become a quota rotation it was not before. if (metadata && sent && !responseCommitted && !deferredCommit && type === "error") { let rejection: Response | null; - try { rejection = wrappedRejectionResponse(normalized.payload, metadata.snapshot()); } + try { rejection = wrappedRejectionResponse(normalized.payload, metadata.snapshot(), metadataContext); } catch (error) { failStream(error); return; } if (rejection) { terminal = true; @@ -677,7 +680,7 @@ export function codexWsExchange(options: ExchangeOptions): Promise { try { refusalPrelude = heldHeaders ?? metadata?.snapshot() ?? new Headers(); const declared = normalized.payload.headers; - refusalHeaders = rejectionHeaders(record(declared) ? declared : {}, refusalPrelude); + refusalHeaders = rejectionHeaders(record(declared) ? declared : {}, refusalPrelude, metadataContext); } catch { refusalStatus = undefined; } diff --git a/src/server/responses/codex-ws-metadata.ts b/src/server/responses/codex-ws-metadata.ts index 5e641e5edf4..9d64242eed8 100644 --- a/src/server/responses/codex-ws-metadata.ts +++ b/src/server/responses/codex-ws-metadata.ts @@ -1,4 +1,6 @@ -import { isSafeResponseHeader, safeResponseHeaders } from "../safe-response-headers"; +import { + CODEX_QUOTA_FAMILIES, isSafeResponseHeader, normalizeSafeResponseHeader, safeResponseHeaders, type ResponseMetadataContext, +} from "../safe-response-headers"; export const CODEX_WS_METADATA_MAX_BYTES = 32 * 1024; export const CODEX_WS_METADATA_MAX_FAMILIES = 16; @@ -52,35 +54,98 @@ function finiteNonnegative(value: unknown): value is number { return typeof value === "number" && Number.isFinite(value) && value >= 0; } -function nativeLimitFamily(event: Record): string | null { - const raw = event.metered_limit_name ?? event.limit_name ?? "codex"; +function boundedInteger(value: unknown, max: number): value is number { + return finiteNonnegative(value) && Number.isSafeInteger(value) && value <= max; +} + +// Native limit ids this proxy relays, keyed by their folded spelling; the value is the canonical id. +const NATIVE_LIMIT_IDS = new Map([ + ["codex", "codex"], ...CODEX_QUOTA_FAMILIES.map(family => [`codex-${family}`, `codex_${family}`] as [string, string]), +]); +// ChatGPT plan labels relayed in the native frame; anything else is omitted. +const PLAN_TYPES = new Set(["free", "go", "plus", "pro", "team", "business", "enterprise", "edu"]); + +/** Canonical native limit id, undefined when absent, null when present but not a known id. */ +function nativeLimitId(raw: unknown): string | null | undefined { + if (raw === undefined) return undefined; if (typeof raw !== "string") return null; - const name = raw.trim().toLowerCase().replaceAll("_", "-"); - return name.length <= 64 && /^codex(?:-[a-z0-9-]+)?$/.test(name) ? name : null; + return NATIVE_LIMIT_IDS.get(raw.trim().toLowerCase().replaceAll("_", "-")) ?? null; +} + +function nativeLimitFamily(event: Record): string | null { + const id = nativeLimitId(event.metered_limit_name ?? event.limit_name ?? "codex"); + return id ? id.replaceAll("_", "-") : null; +} + +type QuotaWindow = { used_percent: number; window_minutes?: number; reset_at?: number }; + +/** A quota window rebuilt from bounded numbers: percent clamped to 100 at two decimals, integer window and reset. */ +function quotaWindow(value: unknown): QuotaWindow | undefined { + if (!record(value) || !finiteNonnegative(value.used_percent)) return undefined; + const window: QuotaWindow = { used_percent: Math.round(Math.min(value.used_percent, 100) * 100) / 100 }; + if (boundedInteger(value.window_minutes, 1e7)) window.window_minutes = value.window_minutes; + if (boundedInteger(value.reset_at, 1e11)) window.reset_at = value.reset_at; + return window; } -function writeWindow(headers: Headers, prefix: string, value: unknown): void { - if (!record(value) || !finiteNonnegative(value.used_percent)) return; - headers.set(`${prefix}-used-percent`, String(value.used_percent)); - for (const [field, suffix] of [["window_minutes", "window-minutes"], ["reset_at", "reset-at"]]) { - const number = value[field!]; - if (finiteNonnegative(number) && Number.isSafeInteger(number)) headers.set(`${prefix}-${suffix}`, String(number)); +function writeWindow(headers: Headers, prefix: string, window: QuotaWindow | undefined): void { + if (!window) return; + headers.set(`${prefix}-used-percent`, String(window.used_percent)); + if (window.window_minutes !== undefined) headers.set(`${prefix}-window-minutes`, String(window.window_minutes)); + if (window.reset_at !== undefined) headers.set(`${prefix}-reset-at`, String(window.reset_at)); +} + +/** + * The `codex.rate_limits` frame relayed to the client, rebuilt field by field: known limit ids and + * plan labels, boolean flags and bounded quota windows. Every other field is discarded, including + * the credit balance (it is only relayed as the proxy-formatted `x-codex-credits-balance` header). + * Windows of an unknown limit id are dropped, never relabelled as ordinary quota. + */ +function rateLimitsFrame(event: Record): Record { + const frame: Record = { type: "codex.rate_limits" }; + if (typeof event.plan_type === "string" && PLAN_TYPES.has(event.plan_type)) frame.plan_type = event.plan_type; + for (const field of ["metered_limit_name", "limit_name"] as const) { + const id = nativeLimitId(event[field]); + if (id) frame[field] = id; + } + if (record(event.rate_limits)) { + const limits: Record = {}; + for (const flag of ["allowed", "limit_reached"]) { + if (typeof event.rate_limits[flag] === "boolean") limits[flag] = event.rate_limits[flag]; + } + if (nativeLimitFamily(event)) { + for (const name of ["primary", "secondary"]) { + const window = quotaWindow(event.rate_limits[name]); + if (window) limits[name] = window; + } + } + frame.rate_limits = limits; + } + if (record(event.credits)) { + const credits: Record = {}; + for (const flag of ["has_credits", "unlimited"]) { + if (typeof event.credits[flag] === "boolean") credits[flag] = event.credits[flag]; + } + frame.credits = credits; } + return frame; } function quotaHeaders(event: Record): Headers { const headers = new Headers(); const family = nativeLimitFamily(event); if (family && record(event.rate_limits)) { - writeWindow(headers, `x-${family}-primary`, event.rate_limits.primary); - writeWindow(headers, `x-${family}-secondary`, event.rate_limits.secondary); + writeWindow(headers, `x-${family}-primary`, quotaWindow(event.rate_limits.primary)); + writeWindow(headers, `x-${family}-secondary`, quotaWindow(event.rate_limits.secondary)); } if (record(event.credits)) { for (const [field, suffix] of [["has_credits", "has-credits"], ["unlimited", "unlimited"]]) { const value = event.credits[field!]; if (typeof value === "boolean") headers.set(`x-codex-credits-${suffix}`, String(value)); } - if (typeof event.credits.balance === "string") setMetadataHeader(headers, "x-codex-credits-balance", event.credits.balance); + const balance = typeof event.credits.balance === "string" + ? normalizeSafeResponseHeader("x-codex-credits-balance", event.credits.balance) : undefined; + if (balance !== undefined) setMetadataHeader(headers, "x-codex-credits-balance", balance); } return headers; } @@ -91,13 +156,17 @@ function setMetadataHeader(headers: Headers, name: string, value: string): void try { headers.set(name, value); } catch { /* invalid provider header is not HTTP authority */ } } -function responseHeaders(value: unknown): Headers { +function responseHeaders(value: unknown, context: ResponseMetadataContext): Headers { const headers = new Headers(); if (!record(value)) return headers; for (const [name, field] of Object.entries(value)) { if (!isSafeResponseHeader(name)) continue; if (typeof field !== "string" && typeof field !== "number" && typeof field !== "boolean") continue; - setMetadataHeader(headers, name, String(field)); + const raw = String(field); + // The byte budget applies to what the upstream sent; then only a value that fits its contract stays. + if (Buffer.byteLength(raw) > CODEX_WS_METADATA_MAX_VALUE_BYTES) throw new Error("codex websocket metadata value exceeds the size limit"); + const normalized = normalizeSafeResponseHeader(name, raw, context); + if (normalized !== undefined) setMetadataHeader(headers, name, normalized); } return headers; } @@ -124,7 +193,7 @@ export class CodexWsMetadata { private preludeBytes = 0; private committed = false; - constructor(private observer?: CodexWsQuotaObserver) {} + constructor(private observer?: CodexWsQuotaObserver, private readonly context: ResponseMetadataContext = {}) {} snapshot(): Headers { return new Headers(this.headers); } @@ -132,7 +201,11 @@ export class CodexWsMetadata { seed(headers: Headers): void { if (this.ended || this.committed || this.headers.has(REASONING_INCLUDED_HEADER)) return; const value = headers.get(REASONING_INCLUDED_HEADER); - if (value !== null) setMetadataHeader(this.headers, REASONING_INCLUDED_HEADER, value); + if (value === null) return; + // Codex reads this header by presence. Keep it present, but only as bytes this proxy writes: + // an exact boolean, otherwise an empty value. + const folded = value.trim().toLowerCase(); + setMetadataHeader(this.headers, REASONING_INCLUDED_HEADER, folded === "true" || folded === "false" ? folded : ""); } private publishQuota(headers: Headers): void { @@ -152,7 +225,7 @@ export class CodexWsMetadata { if (bytes > CODEX_WS_METADATA_MAX_BYTES) throw new Error("codex websocket metadata frame exceeds the size limit"); if (!this.committed) this.preludeBytes += bytes; if (this.preludeBytes > CODEX_WS_METADATA_MAX_BYTES) throw new Error("codex websocket metadata prelude exceeds the size limit"); - const updates = event.type === "codex.rate_limits" ? quotaHeaders(event) : responseHeaders(event.headers); + const updates = event.type === "codex.rate_limits" ? quotaHeaders(event) : responseHeaders(event.headers, this.context); const next = this.snapshot(); for (const name of updates.keys()) { if (!name.endsWith("-used-percent")) continue; @@ -167,8 +240,8 @@ export class CodexWsMetadata { this.publishQuota(updates); } return event.type === "codex.response.metadata" - ? JSON.stringify({ type: event.type, headers: safeResponseHeaders(updates) }) - : JSON.stringify(event); + ? JSON.stringify({ type: event.type, headers: safeResponseHeaders(updates, this.context) }) + : JSON.stringify(rateLimitsFrame(event)); } finish(): void { diff --git a/src/server/responses/codex-ws-request.ts b/src/server/responses/codex-ws-request.ts index 2e312b837bf..509b0e20814 100644 --- a/src/server/responses/codex-ws-request.ts +++ b/src/server/responses/codex-ws-request.ts @@ -18,6 +18,8 @@ export interface PreparedCodexWsRequest { /** Original HTTP body/framing/options with only the canonical routing hint re-derived. */ httpInit: RequestInit; canonical: boolean; + /** The request's model id, when the body names one: a model the relayed metadata may report. */ + model?: string; } function isRecord(value: unknown): value is Record { @@ -83,7 +85,7 @@ export function prepareCodexWsRequest(url: string, init: RequestInit): PreparedC ? headers["openai-beta"] : `${headers["openai-beta"]}, ${WS_BETA}` : WS_BETA; - return { frameText, headers, httpInit, canonical }; + return { frameText, headers, httpInit, canonical, ...(typeof body.model === "string" ? { model: body.model } : {}) }; } catch { return null; } diff --git a/src/server/responses/compact.ts b/src/server/responses/compact.ts index 07e772c0575..760173e0e28 100644 --- a/src/server/responses/compact.ts +++ b/src/server/responses/compact.ts @@ -1,3 +1,4 @@ +import { formatClientRetryAfter } from "../../lib/client-retry-after"; import { conversationStateAccountId, releaseRequestOwnedMainOnOutcome, isKeyedRequestOwnedMain } from "../../codex/request-owned-affinity"; import { CodexInstallationIdUnavailableError } from "../../codex/installation-id"; import { MAIN_CODEX_ACCOUNT_ID } from "../../codex/account-id"; @@ -611,7 +612,12 @@ function compactResponseHeaders(upstream: Response): Headers { const headers = new Headers({ "Content-Type": upstream.headers.get("content-type") ?? "application/json" }); for (const name of COMPACT_PASSTHROUGH_HEADERS) { const value = upstream.headers.get(name); - if (value !== null) headers.set(name, value); + if (value === null) continue; + if (name === "retry-after") { + // Retry advice leaves as an integer this proxy formats, never the upstream bytes. + const advice = formatClientRetryAfter(value); + if (advice !== undefined) headers.set(name, advice); + } else headers.set(name, value); } return headers; } diff --git a/src/server/responses/core-combo.ts b/src/server/responses/core-combo.ts index 20dae280c0a..c4940a8ca81 100644 --- a/src/server/responses/core-combo.ts +++ b/src/server/responses/core-combo.ts @@ -1,3 +1,4 @@ +import { classifyUpstreamCondition } from "../../lib/upstream-condition"; import { effectiveAzureOutputBudget } from "../../adapters/azure"; import { buildResponsesTransport } from "../../adapters/openai-responses/transport"; import { isMetaAiResponsesDestination } from "../../responses/muse-tool-name-alias"; @@ -54,7 +55,6 @@ import { } from "../../combos"; import { formatErrorResponse } from "../../bridge"; import { SEND_BUDGET_EXHAUSTED_CODE } from "../../lib/errors"; -import { redactSecretString, sanitizeLogMetadataString } from "../../lib/redact"; import { expandPreviousResponseInput, previousResponseReplayFailure, @@ -1445,12 +1445,11 @@ export async function executeComboResponses( contextFailure = { childLog, response: formatErrorResponse(400, "invalid_request_error", failure.upstreamMessage ?? failure.classificationText, { code: "context_length_exceeded", classified: true }) }; } - // A bare status made a revoked credential read as a provider outage. Log only the parsed - // code and message, never the raw envelope, as one redacted, bounded line. - const failureReason = sanitizeLogMetadataString( - redactSecretString([failure.upstreamCode, failure.upstreamMessage].filter(Boolean).join(": ")).replace(/\s+/g, " "), - 200, - ); + // A bare status made a revoked credential read as a provider outage. Log the classified + // condition (a closed member), never upstream-authored code or message text. + const failureReason = classifyUpstreamCondition({ + status: failure.response.status, code: failure.upstreamCode, type: failure.upstreamType, message: failure.upstreamMessage, + }); console.warn( `[combo] ${comboId}: ${targetKey(pick.target)} failed with ${failure.response.status}` + ` after ${Date.now() - started}ms${failureReason ? `: ${failureReason}` : ""}`, diff --git a/src/server/responses/core-errors.ts b/src/server/responses/core-errors.ts index 32fa78e6ef9..00224535d07 100644 --- a/src/server/responses/core-errors.ts +++ b/src/server/responses/core-errors.ts @@ -1,3 +1,4 @@ +import { formatClientRetryAfter } from "../../lib/client-retry-after"; import { readBoundedResponseBody } from "../../lib/bounded-body"; import { redactSecretString } from "../../lib/redact"; import { isCyberPolicyMessage, isCyberPolicyCode } from "../../lib/errors"; @@ -102,10 +103,9 @@ export function comboUnavailableResponse( options?: { retryAfter?: string | null }, ): Response { const headers = new Headers({ "Content-Type": "application/json" }); - const retryAfter = options?.retryAfter?.trim(); - if (retryAfter && retryAfter.length > 0 && retryAfter.length <= 128) { - headers.set("Retry-After", retryAfter); - } + // Advice leaves in this proxy's format, whatever form the earliest cooldown was recorded in. + const advice = formatClientRetryAfter(options?.retryAfter); + if (advice !== undefined) headers.set("Retry-After", advice); return new Response( JSON.stringify({ error: { message, type: "server_error", code: "combo_unavailable" }, diff --git a/src/server/responses/fetch-helpers.ts b/src/server/responses/fetch-helpers.ts index 469cbdb8341..52d1db3d340 100644 --- a/src/server/responses/fetch-helpers.ts +++ b/src/server/responses/fetch-helpers.ts @@ -33,6 +33,7 @@ import { import { redactSecretString } from "../../lib/redact"; import { outboundCredentials } from "../../lib/outbound-credential-registry"; import { compressUpstreamRequestBody, isCanonicalCodexResponsesUrl } from "./request-compression"; +import { redeemOutboundTurnState, TURN_STATE_BINDING_INIT, turnStateBinding } from "../turn-state-handles"; export { withUpstreamHttpVersion }; @@ -382,6 +383,10 @@ export function providerFetch( // else keeps the provider's HTTP fetch. See ws-upstream.ts for the details. const unobserved = async (input: Parameters[0], init?: RequestInit, reacquirePacing?: (provider: OcxProviderConfig, modelId?: string) => Promise) => { + // Turn-state handles are redeemed here, at the send, where the admitted caller, the provider and + // the outbound account are all settled; a handle bound to anything else is not forwarded. + const sendHeaders = (sent?: RequestInit) => new Headers(sent?.headers ?? (input instanceof Request ? input.headers : undefined)); + init = redeemOutboundTurnState(init, turnStateBinding(providerName, sendHeaders(init))); const upstreamWebsocket = provider.upstreamWebsocket; if (!options.httpOnly && typeof input === "string" && init && shouldUseCodexWsUpstream(input, init, runtime, upstreamWebsocket)) { @@ -412,7 +417,8 @@ export function providerFetch( }; const fallback = ((url: Parameters[0], fallbackInit?: RequestInit) => httpFetch(url, { ...fallbackInit, [WS_FALLBACK_RECEIPT]: notifyOnce } as RequestInit, reacquirePacing, null)) as typeof globalThis.fetch; - const wsSend = codexWsExecutor((url: Parameters[0], wsInit?: RequestInit) => codexWsUpstreamFetch(String(url), wsInit ?? init, + const wsSend = codexWsExecutor((url: Parameters[0], wsInit?: RequestInit) => codexWsUpstreamFetch(String(url), + { ...(wsInit ?? init), [TURN_STATE_BINDING_INIT]: turnStateBinding(providerName, sendHeaders(wsInit ?? init)) } as RequestInit, fallback, runtime, options.onCodexWsQuota, options.beforeDispatch, options.nativeControl, async () => { (await waitForPacing(init.signal ?? undefined))?.release(); }, notifyOnce, options.preOutputRefusalHold), { provider, http: markEgressTransparentExecutor(fallback) }); diff --git a/src/server/responses/passthrough-delivery.ts b/src/server/responses/passthrough-delivery.ts index 8b7bba1ecc5..bdf67c61db2 100644 --- a/src/server/responses/passthrough-delivery.ts +++ b/src/server/responses/passthrough-delivery.ts @@ -1,6 +1,8 @@ import { releaseRequestOwnedMainOnOutcome, isKeyedRequestOwnedMain } from "../../codex/request-owned-affinity"; import { wasPermanentAccountRefusal } from "../../oauth/account-auto-pause"; import { hasResponseMediaType } from "../../lib/http-response-semantics"; +import { routeKnownModels } from "../../usage/log"; +import type { OcxProviderConfig } from "../../types"; import { isNativeControlResponse } from "./native-response-control"; import { guardBufferedComboRequiredTool } from "./combo-required-tool-contract"; import { createComboRequiredToolStreamGuard } from "./combo-required-tool-stream"; @@ -484,9 +486,16 @@ export async function deliverPassthroughResponse( }); } - const headers = sanitizePassthroughHeaders(upstreamResponse.headers, codexSafetyBufferingOptions); + // Every relayed header set below goes through this filter with the route's known models, so a + // reported model (row and header) is only ever a model id this route or a catalog already names. + const passthroughHeaderOptions = { + ...codexSafetyBufferingOptions, + knownModels: [...routeKnownModels(logCtx), ...providerKnownModels(route.provider)], + provider: logCtx.provider, + }; + const headers = sanitizePassthroughHeaders(upstreamResponse.headers, passthroughHeaderOptions); if (!upstreamResponse.ok) noteUpstreamRequestId(logCtx, headers); - const resolvedModel = headers.get("openai-model")?.trim(); + const resolvedModel = headers.get("openai-model") ?? undefined; if (resolvedModel) { logCtx.servedModel = resolvedModel; if (!logCtx.preserveResolvedModelFromRoute) logCtx.resolvedModel = resolvedModel; @@ -616,7 +625,7 @@ export async function deliverPassthroughResponse( return new Response(upstreamResponse.body, { status: upstreamResponse.status, statusText: upstreamResponse.statusText, - headers: sanitizePassthroughHeaders(upstreamResponse.headers, codexSafetyBufferingOptions), + headers: sanitizePassthroughHeaders(upstreamResponse.headers, passthroughHeaderOptions), }); } if (!upstreamResponse.ok) { @@ -1161,7 +1170,7 @@ export async function deliverPassthroughResponse( rememberPassthroughResponseChecked(client.terminal.response); } - const jsonHeaders = sanitizePassthroughHeaders(headers, codexSafetyBufferingOptions); + const jsonHeaders = sanitizePassthroughHeaders(headers, passthroughHeaderOptions); jsonHeaders.set("content-type", "application/json"); return markPreinspectedJsonResponse(new Response(clientJson, { status: upstreamResponse.status, @@ -1503,7 +1512,7 @@ export async function deliverPassthroughResponse( } throw error; } - const sseHeaders = sanitizePassthroughHeaders(headers, codexSafetyBufferingOptions); + const sseHeaders = sanitizePassthroughHeaders(headers, passthroughHeaderOptions); sseHeaders.set("content-type", "text/event-stream"); sseHeaders.set("cache-control", "no-store"); return new Response(stream, { @@ -1551,3 +1560,16 @@ export async function deliverPassthroughResponse( headers, }); } + +/** + * Model ids the user configured for the selected provider: its models and retention lists and + * default. A provider-owned model hint that names one of them is relayed as the proxy's copy. + * Live-discovered ids are not trusted here, because the upstream's own /models answer chose them; + * neither is the selection list, which a model preset fills from that same discovered catalog. + */ +function providerKnownModels(provider: OcxProviderConfig): string[] { + return [ + ...(provider.models ?? []), ...(provider.retainModels ?? []), + ...(provider.defaultModel ? [provider.defaultModel] : []), + ]; +} diff --git a/src/server/responses/passthrough-error.ts b/src/server/responses/passthrough-error.ts index 15deda0b9c4..b71bd8bf853 100644 --- a/src/server/responses/passthrough-error.ts +++ b/src/server/responses/passthrough-error.ts @@ -7,8 +7,8 @@ import { UPSTREAM_RESET_REPLAY_REFUSED_CODE, } from "../../lib/upstream-retry"; import { + formatClientRetryAfter, resolveClientRetryAfter, - validateClientRetryAfterHeader, } from "../../lib/retry-after"; function isCyberPolicyBody(body: string): boolean { @@ -93,7 +93,6 @@ export function formatPassthroughUpstreamError( const trimmed = bodyText.trim(); const now = options?.now ?? Date.now(); const upstreamRetryAfter = options?.headers?.get("retry-after")?.trim() || undefined; - const originalValid = validateClientRetryAfterHeader(upstreamRetryAfter, now); const cyberPolicyFailure = isCyberPolicyBody(trimmed); const replayRefusal = options?.replayRefusal === true || isReplayRefusalBody(trimmed); // Two different reasons to answer with no wait at all, handled the same way: a hard policy @@ -108,12 +107,12 @@ export function formatPassthroughUpstreamError( now, }); + // The header leaves in this proxy's own format: an integer of seconds, never the upstream bytes. + const formatted = resolved === undefined ? undefined : formatClientRetryAfter(resolved, now); + if (trimmed) { - const needsSet = resolved !== undefined && upstreamRetryAfter !== resolved; - const needsDelete = (suppressRetryAfter && upstreamRetryAfter !== undefined) - || (resolved === undefined - && upstreamRetryAfter !== undefined - && originalValid === undefined); + const needsSet = formatted !== undefined && upstreamRetryAfter !== formatted; + const needsDelete = formatted === undefined && upstreamRetryAfter !== undefined; // A refusal always takes the rewriting path: it has a header to add even when the // upstream named no wait for it to remove. @@ -128,7 +127,7 @@ export function formatPassthroughUpstreamError( const headers = options?.headers ? new Headers(options.headers) : new Headers({ "Content-Type": "application/json" }); - if (needsSet) headers.set("Retry-After", resolved!); + if (needsSet) headers.set("Retry-After", formatted!); else headers.delete("Retry-After"); if (replayRefusal) applyReplayRefusalClientHeaders(headers); const rewritten = new Response(bodyText, { @@ -152,7 +151,8 @@ export function formatPassthroughUpstreamError( ); const headers = new Headers(response.headers); headers.set("Content-Type", "application/json"); - if (resolved !== undefined) headers.set("Retry-After", resolved); + if (formatted !== undefined) headers.set("Retry-After", formatted); + else headers.delete("Retry-After"); if (replayRefusal) applyReplayRefusalClientHeaders(headers); const wrapped = new Response(response.body, { status: response.status, headers }); return replayRefusal ? retainReplayRefusal(wrapped) : wrapped; diff --git a/src/server/responses/request-transport.ts b/src/server/responses/request-transport.ts index aceb6dfea01..ebf02e68987 100644 --- a/src/server/responses/request-transport.ts +++ b/src/server/responses/request-transport.ts @@ -1,3 +1,4 @@ +import { formatClientRetryAfter } from "../../lib/client-retry-after"; import { SendBudgetExhaustedError } from "../../lib/upstream-retry"; import { appendLoadedToolDefinitions, appendOnlyToolLoadingMatches } from "../../claude/inbound-tool-loading"; import { isRec } from "../../claude/inbound-records"; @@ -348,7 +349,8 @@ export async function prepareResponsesTransport( if (!(error instanceof CopilotAutoHttpError) || ![401, 403, 429].includes(error.status)) return; const response = formatErrorResponse(error.status, error.status === 429 ? "rate_limit_error" : "authentication_error", error.message); - if (error.retryAfter) response.headers.set("retry-after", error.retryAfter); + const advice = formatClientRetryAfter(error.retryAfter); + if (advice !== undefined) response.headers.set("retry-after", advice); return response; }; let copilotSessionExpiresAt = Infinity; diff --git a/src/server/responses/run-turn-execution.ts b/src/server/responses/run-turn-execution.ts index d6a607ba15d..b8d60efba16 100644 --- a/src/server/responses/run-turn-execution.ts +++ b/src/server/responses/run-turn-execution.ts @@ -1,3 +1,4 @@ +import { formatClientRetryAfter } from "../../lib/client-retry-after"; import { mapSpendLedgerStorageError } from "./spend-storage-error"; import type { ResponsesRequestContext, ResponsesAdmissionState } from "./core-options"; import type { PreparedResponsesRequest } from "./request-prepare"; @@ -196,7 +197,7 @@ export async function executeResponsesRunTurn( } }), { status: 429, headers: { "Content-Type": "application/json", - ...(usage.resetAt ? { "Retry-After": String(Math.max(1, Math.ceil((usage.resetAt - Date.now()) / 1000))) } : {}), + ...(usage.resetAt ? { "Retry-After": formatClientRetryAfter(Math.max(1, Math.ceil((usage.resetAt - Date.now()) / 1000)))! } : {}), }, }); markResponseNonReplayable(refusal); diff --git a/src/server/responses/ws-upstream.ts b/src/server/responses/ws-upstream.ts index b7a7b98a1ca..a3ee0747a3d 100644 --- a/src/server/responses/ws-upstream.ts +++ b/src/server/responses/ws-upstream.ts @@ -21,6 +21,7 @@ import { resolveProxyRoute, socks5ProxyFromEnv } from "../../lib/proxy-env"; import type { CodexWsQuotaObserver } from "./codex-ws-metadata"; import { CODEX_RESPONSES_HTTP_URL, CODEX_RESPONSES_WS_URL, CODEX_WS_FRAME_HEADERS, prepareCodexHttpInit, prepareCodexWsRequest } from "./codex-ws-request"; import { codexWsExchange } from "./codex-ws-exchange"; +import { TURN_STATE_BINDING_INIT } from "../turn-state-handles"; import { CodexWsSession } from "./codex-ws-session"; import { codexWsPool, codexWsReuseIdentity } from "./codex-ws-pool"; import { codexWsCreateFrameExceedsLimit, type CodexWsPreOutputRefusalHold } from "./codex-ws-wire"; @@ -252,5 +253,13 @@ export async function codexWsUpstreamFetch( beforeContinuation, onPhysicalDispatch, preOutputRefusalHold, bunVersion: typeof runtime === "string" ? runtime : runtime.version, + metadataContext: codexWsMetadataContext(init, prepared.model), }); } + +/** The binding the provider fetch attached to this send, and the requested model, for relayed metadata. */ +function codexWsMetadataContext(init: RequestInit, model: string | undefined): { turnStateBinding?: string; knownModels: string[]; provider: string } { + const binding = (init as Record)[TURN_STATE_BINDING_INIT]; + // This upstream is the ChatGPT Codex backend, so its bundled model catalog also counts as known. + return { ...(typeof binding === "string" ? { turnStateBinding: binding } : {}), knownModels: model ? [model] : [], provider: "openai-codex" }; +} diff --git a/src/server/safe-response-headers.ts b/src/server/safe-response-headers.ts index d0a0c9379b8..f48de7546b1 100644 --- a/src/server/safe-response-headers.ts +++ b/src/server/safe-response-headers.ts @@ -1,23 +1,172 @@ -const SAFE_RESPONSE_HEADER_EXACT = new Set([ - "retry-after", "x-request-id", "openai-request-id", "x-codex-turn-state", - "openai-model", "x-models-etag", "x-reasoning-included", - "x-codex-credits-has-credits", "x-codex-credits-unlimited", "x-codex-credits-balance", - "x-codex-promo-message", "x-codex-safety-buffering-enabled", "x-codex-safety-buffering-faster-model", +import { formatClientRetryAfter } from "../lib/client-retry-after"; +import { knownModelIdentity } from "../lib/model-identity"; +import { isLiveTurnStateHandle, issueTurnStateHandle } from "./turn-state-handles"; + +/** + * Upstream response headers a client may receive as response metadata (WebSocket frames, the + * WS-to-HTTP projection). Each name is listed explicitly and each value is validated or rebuilt + * against its contract; a value that does not fit is dropped. No value is copied: numbers and + * booleans are reformatted, a model header is kept only as a model id the proxy already knows for + * the request, and the turn-state token is replaced by a handle bound to the request. Request ids, + * the models etag and quota limit labels are not relayed. + */ +export type ResponseMetadataContext = { + /** Binding of the send that produced these headers; without one, a turn-state token is dropped. */ + turnStateBinding?: string; + /** Model ids the request already names (requested and routed); the bundled catalog also counts. */ + knownModels?: readonly string[]; + /** Provider (or metadata vendor) whose bundled model catalog also counts as known. */ + provider?: string; +}; +type Normalize = (value: string, context: ResponseMetadataContext) => string | undefined; + +const OPAQUE_TOKEN = /^[A-Za-z0-9._~+/=:-]{1,8192}$/; +const NUMBER = /^\d{1,15}(?:\.\d{1,6})?$/; + +function bool(value: string): string | undefined { + const folded = value.trim().toLowerCase(); + return folded === "true" || folded === "false" ? folded : undefined; +} + +function parseNonNegative(value: string): number | undefined { + const trimmed = value.trim(); + if (!NUMBER.test(trimmed)) return undefined; + const number = Number(trimmed); + return Number.isFinite(number) ? number : undefined; +} + +/** A non-negative decimal rebuilt by this proxy (so "1e3", signs and padding never pass through). */ +function decimal(max: number): Normalize { + return value => { + const number = parseNonNegative(value); + return number !== undefined && number <= max ? String(number) : undefined; + }; +} + +/** A non-negative integer formatted by this proxy: fractions round down, large values clamp to max. */ +function count(max: number): Normalize { + return value => { + const number = parseNonNegative(value); + return number === undefined ? undefined : String(Math.min(Math.floor(number), max)); + }; +} + +/** A non-negative integer exact to the contract (an epoch or window length); anything else drops. */ +function integer(max: number): Normalize { + return value => { + const trimmed = value.trim(); + if (!/^\d{1,15}$/.test(trimmed)) return undefined; + const number = Number(trimmed); + return number <= max ? String(number) : undefined; + }; +} + +const DURATION_PART = /(\d{1,9}(?:\.\d{1,6})?)(h|ms|m|s)/gy; +const DURATION_UNIT_MS = new Map([["h", 3_600_000], ["m", 60_000], ["s", 1_000], ["ms", 1]]); +const MAX_RESET_MS = 8 * 24 * 60 * 60 * 1000; + +/** + * A rate-limit reset: plain seconds, or a Go-style duration ("6m0s", "20ms"). Both are rebuilt from + * whole units — seconds round up, sub-second durations become whole milliseconds — and clamp to 8 days. + */ +function resetDuration(value: string): string | undefined { + const trimmed = value.trim(); + const seconds = parseNonNegative(trimmed); + if (seconds !== undefined) return String(Math.min(Math.ceil(seconds), MAX_RESET_MS / 1000)); + if (!trimmed || trimmed.length > 64) return undefined; + let ms = 0; + let offset = 0; + DURATION_PART.lastIndex = 0; + for (let match = DURATION_PART.exec(trimmed); match; match = DURATION_PART.exec(trimmed)) { + ms += Number(match[1]) * DURATION_UNIT_MS.get(match[2]!)!; + offset = DURATION_PART.lastIndex; + } + if (offset === 0 || offset !== trimmed.length || !Number.isFinite(ms)) return undefined; + const clamped = Math.min(ms, MAX_RESET_MS); + if (clamped < 1000) return `${Math.ceil(clamped)}ms`; + const whole = Math.ceil(clamped / 1000); + const hours = Math.floor(whole / 3600); + const minutes = Math.floor((whole % 3600) / 60); + const secs = whole % 60; + return `${hours ? `${hours}h` : ""}${hours || minutes ? `${minutes}m` : ""}${secs}s`; +} + +const COUNT = count(1e12); + +// A Map, so a header named after an Object.prototype member ("constructor", "__proto__", +// "toString") can never resolve to an inherited value. +const EXACT: ReadonlyMap = new Map([ + ["retry-after", value => formatClientRetryAfter(value)], + // Codex echoes the turn-state token on later requests of the turn; it receives a handle bound to + // this send, which src/server/turn-state-handles.ts maps back only for a send with the same binding. + ["x-codex-turn-state", (value, context) => !OPAQUE_TOKEN.test(value) ? undefined + : isLiveTurnStateHandle(value) ? value + : context.turnStateBinding ? issueTurnStateHandle(value, context.turnStateBinding) : undefined], + ["openai-model", (value, context) => knownModelIdentity(value, context.knownModels, context.provider)], + ["x-codex-safety-buffering-faster-model", (value, context) => knownModelIdentity(value, context.knownModels, context.provider)], + ["x-reasoning-included", bool], + ["x-codex-credits-has-credits", bool], + ["x-codex-credits-unlimited", bool], + ["x-codex-credits-balance", decimal(1e12)], + ["x-codex-safety-buffering-enabled", bool], + ["x-ratelimit-limit", COUNT], + ["x-ratelimit-remaining", COUNT], + ["x-ratelimit-reset", resetDuration], + ["x-ratelimit-limit-requests", COUNT], + ["x-ratelimit-limit-tokens", COUNT], + ["x-ratelimit-remaining-requests", COUNT], + ["x-ratelimit-remaining-tokens", COUNT], + ["x-ratelimit-reset-requests", resetDuration], + ["x-ratelimit-reset-tokens", resetDuration], + ["x-ratelimit-limit-req-minute", COUNT], + ["x-ratelimit-remaining-req-minute", COUNT], + ["x-ratelimit-limit-tokens-minute", COUNT], + ["x-ratelimit-remaining-tokens-minute", COUNT], + ["x-ratelimit-limit-tokens-month", COUNT], + ["x-ratelimit-remaining-tokens-month", COUNT], + ["x-ratelimit-tokens-query-cost", COUNT], ]); -/** Response metadata may carry only the same non-credential headers as native WS errors. */ +/** + * Codex quota limit families this proxy relays: the ordinary windows (`x-codex-primary-...`) and the + * metered `bengalfox` family (`x-codex-bengalfox-primary-...`, native `codex_bengalfox`). A header + * name is upstream text too, so any other family is dropped rather than echoed. + */ +export const CODEX_QUOTA_FAMILIES = ["bengalfox"] as const; +const QUOTA_WINDOW = new RegExp(`^x-codex(?:-(?:${CODEX_QUOTA_FAMILIES.join("|")}))?-(?:primary|secondary|tertiary)-(used-percent|window-minutes|reset-at)$`); +const QUOTA_VALUE: ReadonlyMap = new Map([ + ["used-percent", decimal(100)], + ["window-minutes", integer(1e7)], + ["reset-at", integer(1e11)], +]); + +function normalizer(lower: string): Normalize | undefined { + if (lower.length > 96) return undefined; + const exact = EXACT.get(lower); + if (exact) return exact; + const window = QUOTA_WINDOW.exec(lower); + if (window) return QUOTA_VALUE.get(window[1]!); + return undefined; +} + +/** True for a header name this proxy may relay as response metadata. */ export function isSafeResponseHeader(name: string): boolean { - const lower = name.toLowerCase(); - return SAFE_RESPONSE_HEADER_EXACT.has(lower) - || lower.startsWith("x-ratelimit-") - || /^x-codex(?:-[a-z0-9-]+)?-(primary|secondary|tertiary)-(used-percent|window-minutes|reset-at)$/.test(lower) - || /^x-codex(?:-[a-z0-9-]+)?-limit-name$/.test(lower); + return typeof name === "string" && normalizer(name.toLowerCase()) !== undefined; +} + +/** The value this proxy relays for an allowlisted header, rebuilt or validated; undefined drops it. */ +export function normalizeSafeResponseHeader(name: string, value: string, context: ResponseMetadataContext = {}): string | undefined { + if (typeof name !== "string" || typeof value !== "string") return undefined; + const normalize = normalizer(name.toLowerCase()); + const normalized = normalize?.(value, context); + return typeof normalized === "string" ? normalized : undefined; } -export function safeResponseHeaders(headers: Headers): Record { +export function safeResponseHeaders(headers: Headers, context: ResponseMetadataContext = {}): Record { const out: Record = {}; for (const [name, value] of headers) { - if (isSafeResponseHeader(name)) out[name.toLowerCase()] = value; + const normalized = normalizeSafeResponseHeader(name, value, context); + if (normalized !== undefined) out[name.toLowerCase()] = normalized; } return out; } diff --git a/src/server/turn-state-handles.ts b/src/server/turn-state-handles.ts new file mode 100644 index 00000000000..6d0e6fcc345 --- /dev/null +++ b/src/server/turn-state-handles.ts @@ -0,0 +1,164 @@ +import { AsyncLocalStorage } from "node:async_hooks"; +import { createHash } from "node:crypto"; + +/** + * Proxy-owned handles for the Codex turn-state token. + * + * Codex reads `x-codex-turn-state` from a response (or the WebSocket upgrade) and sends it back on + * later requests of the same turn, so the upstream can keep the turn on one backend. The client + * receives a random handle this proxy generates instead of the upstream bytes. Each handle is bound + * at issuance to the admitted caller, the selected provider and the outbound account, and maps back + * to the upstream token here, in process memory, only at the physical send of a request with the + * same binding. A mismatched, unknown or expired handle is not forwarded. The map is bounded (oldest + * entries are evicted) and entries expire. Handles, tokens and bindings are never logged. + */ + +export const TURN_STATE_HEADER = "x-codex-turn-state"; +/** Where the provider fetch attaches a send's binding on the RequestInit it hands the WebSocket upstream. */ +export const TURN_STATE_BINDING_INIT: unique symbol = Symbol("opencodex.turn-state-binding"); +const HANDLE_PREFIX = "ocx-ts-"; +const HANDLE = /^ocx-ts-[0-9a-f]{32}$/; +const MAX_HANDLES = 4096; +const HANDLE_TTL_MS = 6 * 60 * 60 * 1000; + +type Entry = { value: string; binding: string; expiresAt: number }; +const byHandle = new Map(); +const byBoundValue = new Map(); + +// The admitted caller of the request being served. Admission records it; the provider fetch reads it. +type CallerScope = { caller?: string }; +const callerScope = new AsyncLocalStorage(); + +/** Run one request (or one WebSocket frame) with its own caller slot. */ +export function runTurnStateCallerScope(run: () => T): T { + return callerScope.run({}, run); +} + +/** Record the admitted caller for the current request: a configured key id, an environment principal, or loopback. */ +export function noteTurnStateCaller(admission: { kind: string; keyId?: string; contextPrincipalId?: string }): void { + const scope = callerScope.getStore(); + if (!scope) return; + scope.caller = admission.kind === "configured" ? `configured:${admission.keyId ?? ""}` + : admission.kind === "environment" ? `environment:${admission.contextPrincipalId ?? ""}` : admission.kind; +} + +/** + * The binding of an outbound send: a digest of the admitted caller, the provider name and the account + * the send goes out as (the ChatGPT account id, or the outbound credential when there is none). + */ +export function turnStateBinding(providerName: string, headers: Headers): string { + const account = headers.get("chatgpt-account-id")?.trim() ?? ""; + const credential = account ? "" : headers.get("authorization") ?? ""; + return createHash("sha256") + .update(JSON.stringify([callerScope.getStore()?.caller ?? "unadmitted", providerName, account, credential])) + .digest("hex"); +} + +function randomHandle(): string { + const bytes = crypto.getRandomValues(new Uint8Array(16)); + return HANDLE_PREFIX + Array.from(bytes, byte => byte.toString(16).padStart(2, "0")).join(""); +} + +function boundKey(entry: { binding: string; value: string }): string { + return entry.binding + "\0" + entry.value; +} + +function live(handle: string, now: number): Entry | undefined { + const entry = byHandle.get(handle); + if (!entry) return undefined; + if (entry.expiresAt > now) return entry; + byHandle.delete(handle); + if (byBoundValue.get(boundKey(entry)) === handle) byBoundValue.delete(boundKey(entry)); + return undefined; +} + +/** True for a handle this proxy issued that has not expired. */ +export function isLiveTurnStateHandle(value: string, now = Date.now()): boolean { + return HANDLE.test(value) && live(value, now) !== undefined; +} + +/** The handle a client receives for an upstream turn-state token under `binding`; a live handle is returned as is. */ +export function issueTurnStateHandle(value: string, binding: string, now = Date.now()): string { + if (isLiveTurnStateHandle(value, now)) return value; + const key = boundKey({ binding, value }); + const existing = byBoundValue.get(key); + if (existing && live(existing, now)) return existing; + const handle = randomHandle(); + byHandle.set(handle, { value, binding, expiresAt: now + HANDLE_TTL_MS }); + byBoundValue.set(key, handle); + while (byHandle.size > MAX_HANDLES) { + const [oldest, entry] = byHandle.entries().next().value as [string, Entry]; + byHandle.delete(oldest); + if (byBoundValue.get(boundKey(entry)) === oldest) byBoundValue.delete(boundKey(entry)); + } + return handle; +} + +export type TurnStateResolution = { value: string } | { dropped: "unknown" | "mismatch" }; + +/** + * What to forward for an inbound turn-state under `binding`: the upstream token for a live handle + * with the same binding, nothing for an unknown, expired or differently bound handle, and any other + * value unchanged (it did not come from a handle). + */ +export function resolveTurnStateHandle(value: string, binding: string, now = Date.now()): TurnStateResolution { + if (!value.startsWith(HANDLE_PREFIX)) return { value }; + const entry = live(value, now); + if (!entry) return { dropped: "unknown" }; + return entry.binding === binding ? { value: entry.value } : { dropped: "mismatch" }; +} + +/** Fixed service-log flag for a handle presented under a different binding; it never names the handle. */ +export const TURN_STATE_MISMATCH_NOTICE = "[opencodex] turn_state_binding_mismatch: a turn-state handle was not forwarded"; +const MISMATCH_NOTICE_INTERVAL_MS = 60_000; +let lastMismatchNotice = 0; + +function redeem(value: string, binding: string): string | undefined { + const resolution = resolveTurnStateHandle(value, binding); + if ("value" in resolution) return resolution.value; + if (resolution.dropped === "mismatch" && Date.now() - lastMismatchNotice >= MISMATCH_NOTICE_INTERVAL_MS) { + lastMismatchNotice = Date.now(); + console.warn(TURN_STATE_MISMATCH_NOTICE); + } + return undefined; +} + +function record(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +/** + * Translate turn-state handles in an outbound send, after admission and routing: the request header + * and `client_metadata["x-codex-turn-state"]` in a JSON body. The init is returned unchanged when it + * carries no handle, so ordinary sends keep their exact headers and body bytes. + */ +export function redeemOutboundTurnState(init: RequestInit | undefined, binding: string): RequestInit | undefined { + if (!init) return init; + let next: RequestInit = init; + const headers = new Headers(init.headers); + const header = headers.get(TURN_STATE_HEADER); + if (header !== null && header.startsWith(HANDLE_PREFIX)) { + const value = redeem(header, binding); + if (value === undefined) headers.delete(TURN_STATE_HEADER); else headers.set(TURN_STATE_HEADER, value); + next = { ...next, headers }; + } + if (typeof init.body === "string" && init.body.includes(HANDLE_PREFIX)) { + let body: unknown; + try { body = JSON.parse(init.body); } catch { return next; } + const metadata = record(body) ? body.client_metadata : undefined; + const handle = record(metadata) ? metadata[TURN_STATE_HEADER] : undefined; + if (record(body) && record(metadata) && typeof handle === "string" && handle.startsWith(HANDLE_PREFIX)) { + const value = redeem(handle, binding); + const nextMetadata = { ...metadata }; + if (value === undefined) delete nextMetadata[TURN_STATE_HEADER]; else nextMetadata[TURN_STATE_HEADER] = value; + next = { ...next, body: JSON.stringify({ ...body, client_metadata: nextMetadata }) }; + } + } + return next; +} + +export function resetTurnStateHandlesForTests(): void { + byHandle.clear(); + byBoundValue.clear(); + lastMismatchNotice = 0; +} diff --git a/src/usage/error-detail.ts b/src/usage/error-detail.ts new file mode 100644 index 00000000000..b75e6aeb3aa --- /dev/null +++ b/src/usage/error-detail.ts @@ -0,0 +1,225 @@ +/** + * Error detail kept on request-log rows (live ring, /api/logs, usage.jsonl and hydration). + * + * Rows carry only proxy-owned error facts: a code from a closed vocabulary, a classified upstream + * condition, and, for one provider, a numeric quota reset time. Upstream-authored error text and + * tokens are read here once to derive those facts and are never retained. + */ +import { classifyUpstreamCondition, isUpstreamCondition, type UpstreamCondition } from "../lib/upstream-condition"; +import { boundedFailureDetail, type FailureDetail, type FailureDetailCode } from "../lib/failure-detail"; +import { boundedServiceTier } from "../lib/response-service-tier"; + +export { boundedServiceTier }; + +/** + * Every error code a row may carry. Codes outside this set (an upstream-supplied code that reached a + * writer, a future writer's typo) collapse to the status fallback below. http_NNN codes are formatted + * by the proxy from a numeric status and stay valid. + */ +export const LOG_ERROR_CODES: ReadonlySet = new Set([ + // classifyError and requestLogErrorCode outputs + "spend_ledger_storage_unavailable", "previous_response_not_found", "client_cancelled", "client_closed_request", + "cyber_policy", "input_admission_refused", "inbound_body_too_large", "context_length_exceeded", + "tool_catalog_too_large", "rate_limit_exceeded", "insufficient_quota", "request_send_budget_exhausted", + "origin_rejected", "upstream_server_error", "invalid_api_key", "permission_denied", "location_not_supported", + "subscription_required", "server_is_overloaded", "invalid_request_error", "upstream_error", + // local refusals and proxy decisions + "server_busy", "unsupported_feature", "usage_limit_reached", "undeclared_tool_call", "outbound_body_too_large", + "codex_no_account", "upstream_reset_replay_refused", "memory_model_target_unavailable", + "intercept_target_unavailable", "observation_barrier_timeout", "claude_thread_unsupported", + "claude_compatibility_configuration", "claude_compatibility_unsupported", + "unsupported_credential_domain", "unsupported_synthetic_selector", "unsupported_shadow_rewrite", + // workflow budget refusals + "workflow_sends_exhausted", "workflow_children_exhausted", "workflow_concurrency_exhausted", + "workflow_spend_exhausted", "workflow_tracking_exhausted", "workflow_send_replayed", + "workflow_pool_history_unresolved", "workflow_spend_undurable", +]); + +const HTTP_CODE = /^http_[1-5][0-9]{2}$/; + +function statusFallbackCode(status: number | undefined): string | undefined { + if (status === undefined || !Number.isInteger(status) || status < 400) return undefined; + if (status === 499) return "client_closed_request"; + if (status === 400 || status === 409) return "invalid_request_error"; + if (status === 401) return "invalid_api_key"; + if (status === 403) return "permission_denied"; + if (status === 429) return "rate_limit_exceeded"; + if (status === 503) return "server_is_overloaded"; + if (status >= 500) return "upstream_server_error"; + return `http_${status}`; +} + +/** A code from the closed vocabulary, or the proxy's own code for the status, or nothing. */ +export function normalizeLogErrorCode(code: unknown, status?: number): string | undefined { + if (typeof code === "string" && (LOG_ERROR_CODES.has(code) || HTTP_CODE.test(code))) return code; + return typeof code === "string" && code ? statusFallbackCode(status) ?? "upstream_error" : undefined; +} + +// Meta Muse states its quota window in one fixed sentence. The reset time is kept as a number so +// the dashboard needs no message text. +const MUSE_PROVIDER = "meta-muse"; +const MUSE_RESET_SENTENCE = /^Subscription quota exhausted\. Your usage window resets at (\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z)\.$/; +export const RATE_LIMIT_RESET_MAX_MS = 8 * 24 * 60 * 60 * 1000; + +/** A reset time is kept only when it is a finite epoch-ms value after the request and within 8 days. */ +export function boundedRateLimitResetAt(value: unknown, timestamp: unknown): number | undefined { + if (typeof value !== "number" || !Number.isSafeInteger(value)) return undefined; + if (typeof timestamp !== "number" || !Number.isFinite(timestamp)) return undefined; + return value > timestamp && value - timestamp <= RATE_LIMIT_RESET_MAX_MS ? value : undefined; +} + +export function deriveRateLimitResetAt(entry: { + provider?: unknown; status?: unknown; errorCode?: unknown; upstreamError?: unknown; timestamp?: unknown; +}): number | undefined { + if (entry.provider !== MUSE_PROVIDER || entry.status !== 429 || entry.errorCode !== "rate_limit_exceeded") return undefined; + if (typeof entry.upstreamError !== "string") return undefined; + const match = MUSE_RESET_SENTENCE.exec(entry.upstreamError); + if (!match) return undefined; + const parsed = Date.parse(match[1]!); + return boundedRateLimitResetAt(Number.isFinite(parsed) ? parsed : undefined, entry.timestamp); +} + +/** The fields an error-detail projection reads; all optional so legacy rows qualify. */ +export interface ErrorDetailSource { + status?: unknown; + timestamp?: unknown; + provider?: unknown; + errorCode?: unknown; + terminalStatus?: unknown; + upstreamError?: unknown; + upstreamErrorCode?: unknown; + upstreamErrorType?: unknown; + upstreamCondition?: unknown; + rateLimitResetAt?: unknown; + failureDetail?: unknown; +} + +export interface ErrorDetail { + errorCode?: string; + upstreamCondition?: UpstreamCondition; + rateLimitResetAt?: number; + failureDetail?: FailureDetail; +} + +const str = (value: unknown): string | undefined => typeof value === "string" ? value : undefined; + +// Sentences this proxy writes into a relayed error body (web-search and image-bridge loops, body +// inactivity guard). The request log only sees them as captured error text, so a match becomes a +// closed code with the parsed number; the number is bounded so no credential-length value can fit. +const PROXY_SENTENCES: ReadonlyArray = [ + [/^Provider response-header timeout after (\d{1,7})ms during (?:web-search|image-bridge)$/, "header_timeout"], + [/^Upstream response body stalled for (\d{1,7})ms$/, "body_stall"], + [/^Routed model generation timeout after (\d{1,7})ms without response bytes during web-search$/, "generation_timeout"], + [/^runTurn inactivity timeout after (\d{1,7})ms during image-bridge$/, "turn_inactivity"], + [/^Provider connect timeout after (\d{1,7})ms$/, "connect_timeout"], + [/^client closed request during web-search$/, "client_closed"], +]; + +function proxySentenceDetail(text: string | undefined): FailureDetail | undefined { + if (text === undefined) return undefined; + for (const [pattern, code] of PROXY_SENTENCES) { + const match = pattern.exec(text); + if (match) return match[1] === undefined ? { code } : { code, value: Number(match[1]) }; + } + return undefined; +} + +/** + * Derive the proxy-owned error facts for one row. An existing condition or reset time is kept only + * when valid; otherwise both are derived from upstream evidence, which the caller then drops. + * A condition is derived only when the row carries upstream evidence, so local refusals get none. + */ +export function errorDetailFor(entry: ErrorDetailSource): ErrorDetail { + const status = typeof entry.status === "number" ? entry.status : undefined; + const errorCode = normalizeLogErrorCode(entry.errorCode, status); + // The HTTP status decides when present: a 200 that stopped at the requested output limit is an + // incomplete terminal but a successful request, not an upstream failure. + const failed = status !== undefined ? status >= 400 : typeof entry.terminalStatus === "string" && entry.terminalStatus !== "completed"; + // A client that closed the request is not an upstream condition. + const clientClosed = status === 499 || errorCode === "client_closed_request" || errorCode === "client_cancelled"; + // A recorded condition is kept under the same rules that derive one: failed and not a client close. + let upstreamCondition: UpstreamCondition | undefined = failed && !clientClosed && isUpstreamCondition(entry.upstreamCondition) + ? entry.upstreamCondition : undefined; + const evidence = str(entry.upstreamError) ?? str(entry.upstreamErrorCode) ?? str(entry.upstreamErrorType); + if (!upstreamCondition && failed && !clientClosed && evidence !== undefined && status !== undefined) { + upstreamCondition = classifyUpstreamCondition({ + status, + code: str(entry.upstreamErrorCode), + type: str(entry.upstreamErrorType), + message: str(entry.upstreamError), + }); + } + const rateLimitResetAt = boundedRateLimitResetAt(entry.rateLimitResetAt, entry.timestamp) + ?? deriveRateLimitResetAt({ ...entry, errorCode }); + // A closed code with bounded parameters; free text (a legacy or edited row) is dropped. + const failureDetail = boundedFailureDetail(entry.failureDetail) ?? proxySentenceDetail(str(entry.upstreamError)); + return { + ...(errorCode ? { errorCode } : {}), + ...(upstreamCondition ? { upstreamCondition } : {}), + ...(rateLimitResetAt !== undefined ? { rateLimitResetAt } : {}), + ...(failureDetail ? { failureDetail } : {}), + }; +} + +/** Upstream-authored fields that never leave the request context. */ +export const UPSTREAM_TEXT_FIELDS = ["upstreamError", "upstreamErrorCode", "upstreamErrorType", "upstreamRequestId"] as const; + +type ProjectableEntry = ErrorDetailSource & { + attempts?: unknown; attemptNormalizationDropped?: unknown; responseServiceTier?: unknown; tierOutcome?: unknown; +}; + +/** A tier outcome whose recorded response tier is a closed member (or absent); same object when unchanged. */ +function boundedTierOutcome(outcome: unknown): unknown { + if (!outcome || typeof outcome !== "object" || !("responseServiceTier" in outcome)) return outcome; + const record = outcome as Record; + const tier = boundedServiceTier(record.responseServiceTier); + if (tier === record.responseServiceTier) return outcome; + const { responseServiceTier: _dropped, ...rest } = record; + return tier === undefined ? rest : { ...rest, responseServiceTier: tier }; +} + +/** + * The live-row form of {@link errorDetailFor}: attach the proxy-owned facts and remove upstream text. + * Returns the same object when nothing changes, so callers that rely on identity keep it. Attempt + * codes outside the vocabulary are corrected, and upstream text fields removed, in place (attempts + * keep their identity too). + */ +export function projectErrorDetail(entry: T): T { + if (Array.isArray(entry.attempts)) { + for (const attempt of entry.attempts as unknown[]) { + if (!attempt || typeof attempt !== "object") continue; + const record = attempt as Record; + for (const field of UPSTREAM_TEXT_FIELDS) if (field in record) delete record[field]; + if ("tierOutcome" in record) record.tierOutcome = boundedTierOutcome(record.tierOutcome); + if (typeof record.errorCode !== "string") continue; + const code = normalizeLogErrorCode(record.errorCode, typeof record.status === "number" ? record.status : undefined); + if (code !== record.errorCode) { + if (code === undefined) delete record.errorCode; + else record.errorCode = code; + } + } + } + const detail = errorDetailFor(entry); + const responseServiceTier = boundedServiceTier(entry.responseServiceTier); + const tierOutcome = boundedTierOutcome(entry.tierOutcome); + const unchanged = UPSTREAM_TEXT_FIELDS.every(field => entry[field as keyof ErrorDetailSource] === undefined) + && entry.responseServiceTier === responseServiceTier && entry.tierOutcome === tierOutcome + && entry.errorCode === detail.errorCode + && entry.upstreamCondition === detail.upstreamCondition + && entry.rateLimitResetAt === detail.rateLimitResetAt + && entry.failureDetail === detail.failureDetail; + if (unchanged) return entry; + const out = { ...entry } as Record; + // A non-enumerable marker does not survive a spread; carry it explicitly. + if (entry.attemptNormalizationDropped === true) out.attemptNormalizationDropped = true; + for (const field of UPSTREAM_TEXT_FIELDS) delete out[field]; + if (responseServiceTier === undefined) delete out.responseServiceTier; + else out.responseServiceTier = responseServiceTier; + if (tierOutcome === undefined) delete out.tierOutcome; + else out.tierOutcome = tierOutcome; + for (const field of ["errorCode", "upstreamCondition", "rateLimitResetAt", "failureDetail"] as const) { + if (detail[field] === undefined) delete out[field]; + else out[field] = detail[field]; + } + return out as T; +} diff --git a/src/usage/log.ts b/src/usage/log.ts index 8a0f9ca5e1c..b3430110630 100644 --- a/src/usage/log.ts +++ b/src/usage/log.ts @@ -1,3 +1,6 @@ +import type { FailureDetail } from "../lib/failure-detail"; +import { boundedModelIdentity, knownModelIdentity } from "../lib/model-identity"; +import { boundedServiceTier } from "../lib/response-service-tier"; import { createHash, type Hash } from "node:crypto"; import { chmodSync, closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, appendFileSync } from "node:fs"; import { join } from "node:path"; @@ -5,7 +8,7 @@ import { getConfigDir } from "../config"; import type { CodexAffinityMove, CodexAffinityReason } from "../codex/routing"; import { enforceAppOwnedMemoryBudget } from "../lib/app-owned-memory"; import { recordOwnedConfigPath } from "../lib/config-ownership"; -import { redactSecretString, sanitizeLogMetadataString } from "../lib/redact"; +import { sanitizeLogMetadataString } from "../lib/redact"; import { usageDisplayTotalTokens } from "./totals"; import { normalizePersistedJevDecision, @@ -23,6 +26,8 @@ import { normalizeRouteDecisionTrace, type RouteDecisionTraceV1 } from "../routi import { parseProtocolTraceV1, type ProtocolTraceV1 } from "../protocols/dto"; import { ACCOUNT_LOG_LABEL_RE, CODEX_ACCOUNT_LOG_LABEL_RE } from "../codex/account-label"; import { claudeCompatibilityReason, normalizeClaudeFeatureCodes, type ClaudeFeatureCode } from "../claude/compatibility"; +import type { UpstreamCondition } from "../lib/upstream-condition"; +import { errorDetailFor, normalizeLogErrorCode } from "./error-detail"; import type { CodexWsStageRecord, CodexWsTerminalEvent } from "../server/responses/codex-ws-wire"; import { ATTEMPT_RECOVERY_KIND_ROSTER, @@ -370,8 +375,17 @@ export interface PersistedUsageEntry { */ terminalStatus?: RequestTerminalStatus; closeReason?: RequestCloseReason; - /** Already redacted + capped at capture (request-log.ts redactSecretString().slice(0,500)). */ + /** + * Legacy input only: older rows carried upstream error text here. It is read once on load to + * derive upstreamCondition / rateLimitResetAt and is never written or returned. + */ upstreamError?: string; + /** Proxy-classified upstream condition (src/lib/upstream-condition.ts); a closed enum. */ + upstreamCondition?: UpstreamCondition; + /** Provider quota window end in epoch ms, derived server-side and bounded (src/usage/error-detail.ts). */ + rateLimitResetAt?: number; + /** Proxy-authored failure text (src/server/request-log-failure-detail.ts), never upstream text. */ + failureDetail?: FailureDetail; /** Where the terminal/failure was observed; absent on historic rows. */ transportPhase?: "pre_headers" | "mid_stream" | "terminal_sse"; /** Whether the terminal came from upstream or a proxy-generated tail. */ @@ -672,7 +686,7 @@ function normalizeAttemptTierOutcome(raw: unknown): AttemptTierOutcome | null { if ("responseServiceTier" in outcome && typeof outcome.responseServiceTier !== "string") return null; if ("responseTierAuthoritative" in outcome && typeof outcome.responseTierAuthoritative !== "boolean") return null; const wireValue = sanitizeLogMetadataString(outcome.wireValue); - const responseServiceTier = sanitizeLogMetadataString(outcome.responseServiceTier); + const responseServiceTier = boundedServiceTier(outcome.responseServiceTier); return { ...(outcome.canonical === "priority" ? { canonical: "priority" as const } : {}), ...(outcome.wireKind === null @@ -750,6 +764,7 @@ function normalizeUsageAttempt(raw: unknown): PersistedUsageAttempt | null { && ATTEMPT_RECOVERY_WITHHELD.has(value as AttemptRecoveryWithheld), ))] : []; + const attemptErrorCode = normalizeLogErrorCode(attempt.errorCode, attempt.status as number); return { ordinal: attempt.ordinal as number, provider: attempt.provider, @@ -781,7 +796,7 @@ function normalizeUsageAttempt(raw: unknown): PersistedUsageAttempt | null { ...(isNonNegativeFiniteNumber(attempt.totalTokens) ? { totalTokens: attempt.totalTokens } : {}), - ...(typeof attempt.errorCode === "string" ? { errorCode: attempt.errorCode } : {}), + ...(attemptErrorCode ? { errorCode: attemptErrorCode } : {}), ...(isKnownCacheTelemetryProvenance(attempt.cacheProvenance) ? { cacheProvenance: attempt.cacheProvenance } : {}), @@ -896,19 +911,9 @@ function capMetadataString(s: string): string { return s.length > MAX_METADATA_STRING_LEN ? s.slice(0, MAX_METADATA_STRING_LEN) : s; } -const MAX_SERVED_MODEL_LENGTH = 200; -/** - * An upstream model is an identifier, never free-form text to truncate into one. A value the - * secret redactor would change is dropped rather than logged, because credential-shaped text can - * fit the identifier alphabet. - */ +/** Served and resolved models on a row use the shared model-identity bound (src/lib/model-identity.ts). */ export function sanitizeServedModel(value: unknown): string | undefined { - return typeof value === "string" - && value.length <= MAX_SERVED_MODEL_LENGTH - && /^[A-Za-z0-9._:/@+-]+$/.test(value) - && redactSecretString(value) === value - ? value - : undefined; + return boundedModelIdentity(value); } /** The identity fields that decide whether a response model is ocx's own echo. */ @@ -941,28 +946,56 @@ export function isClientSelectorEcho(source: ServedModelEchoSource, served: stri /** Record a response-body model as the served model when it is a real upstream observation. */ export function recordObservedServedModel( - target: ServedModelEchoSource & { servedModel?: string; resolvedModel?: string; preserveResolvedModelFromRoute?: boolean }, + target: ServedModelEchoSource & { servedModel?: string; resolvedModel?: string; preserveResolvedModelFromRoute?: boolean; attempts?: unknown }, value: unknown, ): void { - const servedModel = sanitizeServedModel(value); + const servedModel = knownModelIdentity(value, routeKnownModels(target), target.provider); if (!servedModel || isClientSelectorEcho(target, servedModel)) return; target.servedModel = servedModel; if (!target.preserveResolvedModelFromRoute) target.resolvedModel = servedModel; } +/** + * Model ids a row's own route already names, which an upstream-reported served or resolved model + * must equal to be recorded: the routed model (also without its provider prefix), the wire model, + * the requested model and alias, and each attempt's target. The bundled Codex catalog is checked + * by {@link knownModelIdentity} itself. + */ +export function routeKnownModels(source: ServedModelEchoSource & { attempts?: unknown }): string[] { + const known: string[] = []; + const add = (value: unknown) => { if (typeof value === "string" && value) known.push(value); }; + add(source.model); + if (typeof source.model === "string" && source.model.includes("/")) add(source.model.slice(source.model.indexOf("/") + 1)); + add(source.wireModel); + add(source.requestedModel); + add(source.requestedAlias); + if (Array.isArray(source.attempts)) { + for (const attempt of source.attempts as unknown[]) { + if (attempt && typeof attempt === "object") { + add((attempt as { model?: unknown }).model); + add((attempt as { wireModel?: unknown }).wireModel); + } + } + } + return known; +} + /** * Model identity fields for a log row. The served model is sanitized, and a resolvedModel that * only echoed a dropped served model is dropped with it, so the rejected value cannot survive * under the other name. A client-selector echo is dropped the same way, which also repairs - * rows persisted before the echo was filtered at capture. + * rows persisted before the echo was filtered at capture. Both are kept only when they equal a + * model id the row's route already names (or the bundled catalog pins); see {@link knownModelIdentity}. */ -export function modelIdentityLogFields(source: ServedModelEchoSource & { resolvedModel?: string; servedModel?: unknown }): { +export function modelIdentityLogFields(source: ServedModelEchoSource & { resolvedModel?: string; servedModel?: unknown; attempts?: unknown }): { resolvedModel?: string; servedModel?: string; wireModel?: string; } { - const sanitized = sanitizeServedModel(source.servedModel); + const known = routeKnownModels(source); + const sanitized = knownModelIdentity(source.servedModel, known, source.provider); const servedModel = isClientSelectorEcho(source, sanitized) ? undefined : sanitized; + // The resolved model passes the same validator on its own; it also leaves with a dropped served echo. const resolvedModel = source.servedModel !== undefined && source.resolvedModel === source.servedModel && !servedModel - ? undefined : source.resolvedModel; + ? undefined : knownModelIdentity(source.resolvedModel, known, source.provider); return { ...(resolvedModel ? { resolvedModel } : {}), ...(servedModel ? { servedModel } : {}), @@ -979,7 +1012,7 @@ function normalizeUsageEntry(entry: PersistedUsageEntry): PersistedUsageEntry { const attempts = normalizedAttempts(entry.attempts); const tierOutcome = entry.tierOutcome ? normalizeAttemptTierOutcome(entry.tierOutcome) : undefined; const callerServiceTier = sanitizeLogMetadataString(entry.callerServiceTier); - const responseServiceTier = sanitizeLogMetadataString(entry.responseServiceTier); + const responseServiceTier = boundedServiceTier(entry.responseServiceTier); const shadowCallRewrittenFrom = sanitizeLogMetadataString(entry.shadowCallRewrittenFrom); const { servedModel, resolvedModel } = modelIdentityLogFields(entry); const claudeCompatibility = normalizeClaudeCompatibilityUsageLog(entry.claudeCompatibility); @@ -1086,13 +1119,13 @@ function normalizeUsageEntry(entry: PersistedUsageEntry): PersistedUsageEntry { ...(affinity ? { affinity } : {}), ...(affinityReason ? { affinityReason } : {}), ...(conversationStateScrub ? { conversationStateScrub } : {}), - ...(entry.errorCode ? { errorCode: entry.errorCode } : {}), + // Closed code, classified condition and numeric reset only; upstream text is never kept. + ...errorDetailFor(entry), // Validated rather than copied on truthiness, like the inbound protocol and transport phase // above. Harmless while these were only rendered; not harmless once the terminal status is // a grouping-key slot, because the string is assembled from an upstream frame. ...(isRequestTerminalStatus(entry.terminalStatus) ? { terminalStatus: entry.terminalStatus } : {}), ...(isRequestCloseReason(entry.closeReason) ? { closeReason: entry.closeReason } : {}), - ...(entry.upstreamError ? { upstreamError: entry.upstreamError } : {}), ...(routeDecision ? { routeDecision } : {}), ...(jevDecision ? { jevDecision } : {}), ...(claudeCompatibility ? { claudeCompatibility } : {}), diff --git a/structure/INDEX.md b/structure/INDEX.md index c30231aa765..91600d26e8b 100644 --- a/structure/INDEX.md +++ b/structure/INDEX.md @@ -68,6 +68,7 @@ The wire surfaces a client actually talks to. | [`data-planes/inbound-compat.md`](data-planes/inbound-compat.md) | Chat Completions inbound, Anthropic-shaped clients, and JSON-upstream streaming clients. | | [`data-planes/claude-tool-loading.md`](data-planes/claude-tool-loading.md) | Physical-adapter tool-loading projection, preserved catalogs, fallback exclusions and opt-in prerequisites. | | [`data-planes/ollama-inbound.md`](data-planes/ollama-inbound.md) | Ollama-shaped version/tags/show/chat/generate routes translated onto Chat Completions, their admission, native error shape and final request-log ownership. | +| [`data-planes/error-detail.md`](data-planes/error-detail.md) | Closed error codes, upstream condition classification, numeric quota reset, closed failure detail, service tier and model identity bounds on request-log rows; response metadata header normalization and the client Retry-After format. | | [`data-planes/chat-reasoning-details.md`](data-planes/chat-reasoning-details.md) | The reasoning_details carrier that lets Chat Completions clients round-trip signed Anthropic thinking across tool steps (#7429). | | [`data-planes/protocol-paths.md`](data-planes/protocol-paths.md) | Shared protocol vocabulary, declared feature dispositions, the ingress-by-upstream baseline, plan/trace shapes, and protocol settings. | | [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | Per-account Pool wire installation identity, private secret, existence gates and fail-closed delivery. | @@ -331,11 +332,16 @@ A source area can be described by more than one doc, because these docs are orga | `src/lib/account-auto-pause-response.ts` | [`account-auto-pause.md`](account-auto-pause.md) | | `src/lib/advisor-activation.ts` | [`advisor.md`](advisor.md) | | `src/lib/bounded-body.ts` | [`transports/timeouts.md`](transports/timeouts.md) | +| `src/lib/client-retry-after.ts` | [`data-planes/error-detail.md`](data-planes/error-detail.md) | | `src/lib/config-ownership.ts` | [`providers/codex-pool-affinity.md`](providers/codex-pool-affinity.md) | | `src/lib/decision-quota-sink.ts` | [`providers/jev-decision.md`](providers/jev-decision.md) | +| `src/lib/failure-detail.ts` | [`data-planes/error-detail.md`](data-planes/error-detail.md) | | `src/lib/gui-pair-intent.ts` | [`remote-link.md`](remote-link.md) | | `src/lib/local-upstream.ts` | [`transports/timeouts.md`](transports/timeouts.md) | +| `src/lib/model-identity.ts` | [`data-planes/error-detail.md`](data-planes/error-detail.md) | +| `src/lib/response-service-tier.ts` | [`data-planes/error-detail.md`](data-planes/error-detail.md) | | `src/lib/tool-argument-integers.ts` | [`providers-and-adapters.md`](providers-and-adapters.md) | +| `src/lib/upstream-condition.ts` | [`data-planes/error-detail.md`](data-planes/error-detail.md) | | `src/lib/windows-owner-acl.ts` | [`codex-cli-update.md`](codex-cli-update.md)
[`remote-link.md`](remote-link.md) | | `src/link/` | [`remote-messaging.md`](remote-messaging.md)
[`remote-link.md`](remote-link.md) | | `src/local-credentials/` | [`remote-link.md`](remote-link.md) | @@ -416,6 +422,7 @@ A source area can be described by more than one doc, because these docs are orga | `src/server/ollama-inbound.ts` | [`data-planes/ollama-inbound.md`](data-planes/ollama-inbound.md) | | `src/server/ollama-native-paths.ts` | [`data-planes/ollama-inbound.md`](data-planes/ollama-inbound.md) | | `src/server/ollama-route-policy.ts` | [`data-planes/ollama-inbound.md`](data-planes/ollama-inbound.md) | +| `src/server/request-log-failure-detail.ts` | [`data-planes/error-detail.md`](data-planes/error-detail.md) | | `src/server/responses/` | [`data-planes/claude-tool-loading.md`](data-planes/claude-tool-loading.md) | | `src/server/responses/account-auto-pause-recovery.ts` | [`account-auto-pause.md`](account-auto-pause.md) | | `src/server/responses/adapter-delivery.ts` | [`transports/response-turn-membership.md`](transports/response-turn-membership.md)
[`transports/max-output-completion.md`](transports/max-output-completion.md) | @@ -434,6 +441,7 @@ A source area can be described by more than one doc, because these docs are orga | `src/server/responses/request-transport.ts` | [`transports/response-turn-membership.md`](transports/response-turn-membership.md)
[`account-auto-pause.md`](account-auto-pause.md) | | `src/server/responses/run-turn-execution.ts` | [`transports/max-output-completion.md`](transports/max-output-completion.md) | | `src/server/responses/turn-membership.ts` | [`transports/response-turn-membership.md`](transports/response-turn-membership.md) | +| `src/server/safe-response-headers.ts` | [`data-planes/error-detail.md`](data-planes/error-detail.md) | | `src/server/search.ts` | [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | | `src/server/ws-bridge.ts` | [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | | `src/service-manager-probe.ts` | [`ops/service-and-sidecars.md`](ops/service-and-sidecars.md) | @@ -479,6 +487,7 @@ A source area can be described by more than one doc, because these docs are orga | `src/update/supervised-recovery.mjs` | [`ops/update-supervised-recovery.md`](ops/update-supervised-recovery.md) | | `src/usage/` | [`runtime.md`](runtime.md)
[`providers/jev-decision.md`](providers/jev-decision.md)
[`gui-and-management-api.md`](gui-and-management-api.md)
[`dashboard-and-usage.md`](dashboard-and-usage.md)
[`companion.md`](companion.md) | | `src/usage/cost.ts` | [`pricing.md`](pricing.md) | +| `src/usage/error-detail.ts` | [`data-planes/error-detail.md`](data-planes/error-detail.md) | | `src/usage/timeline.ts` | [`gui-and-management-api.md`](gui-and-management-api.md) | | `src/usage/user-cost-overlays.ts` | [`pricing.md`](pricing.md) | | `src/usage/user-cost-validation.ts` | [`pricing.md`](pricing.md) | diff --git a/structure/clients/claude-desktop.md b/structure/clients/claude-desktop.md index b44dcfb480a..7011f377ae7 100644 --- a/structure/clients/claude-desktop.md +++ b/structure/clients/claude-desktop.md @@ -593,8 +593,8 @@ Native Anthropic passthrough in `src/server/claude-messages.ts` forwards the cal Native passthrough retains upstream `anthropic-ratelimit-*` response headers for Claude Code quota/statusLine consumers on SSE, JSON and upstream errors. `src/server/anthropic-rate-limit-headers.ts` selects only that family instead of copying all upstream headers, so cookies and unrelated metadata are not relayed. Missing rate-limit headers are not fabricated; body, status, content type and existing non-stream `Retry-After` behavior stay unchanged. `tests/claude-integration/claude-native-rate-limit-headers.test.ts` exercises the production ingress against a synthetic upstream for all four response shapes (SSE, JSON, upstream error and count_tokens). -`tapAnthropicSseForLog` in `src/server/messages-shared.ts` (re-exported by `src/server/claude-messages.ts`) relays the streamed body of both the native passthrough and the managed native Messages lane (`src/server/messages-native.ts`). The response headers are already sent, so a stall, a byte-cap overflow, or an upstream read failure ends the body with an Anthropic `event: error` frame after a blank-line boundary and a clean close: `timeout_error` for an idle stall, `api_error` for the byte cap, and `api_error` when an upstream read fails mid-stream (a socket reset). The mid-stream reset is logged like the Responses relay's read error: status 502, `terminalStatus: "failed"`, `closeReason: "terminal"`, `transportPhase: "mid_stream"`, a synthetic terminal source, the attempt marked `streamAborted`, the redacted reason in `upstreamError`, and the usage seen before the reset. The non-streaming fold in the managed lane closes its row with the tap's meta for a reset, a stall or the byte cap, so its row matches the streaming lane's. The request is not replayed. Every one of these frames logs status 502. A stall is `terminalStatus: "incomplete"` with `closeReason: "body_stall"`, the status the Responses relay gives a stall-timeout incomplete. The byte cap is `incomplete` with `closeReason: "body_overflow"`, the same 502 the non-stream passthrough answers for it. Both carry the proxy's message in `upstreamError`, and a reset is `terminalStatus: "failed"`. Either way the row keeps its failure diagnostics in usage.jsonl. A stall or overflow after the turn's own terminal (`message_stop` or an upstream `error` event) is a finished turn: it logs 200 and closes without an error frame, as the read-error branch does. The tap normalizes and scans only newly decoded text, holding a trailing CR and LF across reads so split CRLF and blank-line delimiters stay intact; it forwards the original bytes unchanged. Unfinished frames remain in fragments and are joined only at a frame boundary or tail flush. Tiny fragments are coalesced after at least 4096 code units, avoiding one retained array entry per byte on one-byte feeds. Each code unit is normalized once and joined at most twice; `tests/claude-integration/messages-shared-sse.test.ts` checks the linear work budget, tiny-fragment coalescing, split UTF-8 and line endings, usage, terminal-tail repair, byte caps and cancellation. At a clean EOF or a stall/reset flush, the held LF and CR rejoin the fragments in wire order and a held CR counts as a line ending; every frame that completes there is inspected as a complete event, and only the remainder after the last blank line is the undelimited tail. Some read failures are not upstream failures. When the cancel signal is already aborted, the rejection is a `499` client cancel, because Bun can reject the read before it dispatches the abort listener. The managed lane passes its upstream controller's signal, so shutdown and turn release count as cancels too. When `message_stop` or an upstream `error` event has been seen, including one still in the buffer without its blank-line delimiter, the turn is complete: it logs 200 and closes with no error frame. A terminal found only in that unterminated tail gets its blank line restored, because an SSE parser drops an event that EOF cuts off. A translator budget overflow is a local cap, so it still errors the stream, and the non-streaming fold answers it with 413. `tests/claude-integration/claude-native-passthrough.test.ts` and `tests/claude-integration/messages-native.test.ts` cover both lanes against an upstream that resets after a partial or a complete body, plus both cancel paths. A clean upstream EOF (no reset) ends the turn only when the client already has its terminal (`message_stop` or an upstream `error` event), or when the last message event it received as a complete SSE event was a `message_delta` with a non-error `stop_reason` and nothing but whitespace, comments or a ping follows it undelimited: compatible providers may omit `message_stop`, and the translated adapter accepts the same shape. Those bytes are relayed unchanged and log 200. Every other clean EOF is a cut turn and fails exactly like a mid-stream reset (502, `terminalStatus: "failed"`, `transportPhase: "mid_stream"`, `streamAborted`, an `api_error` frame): a partial body, an EOF after `stop_reason: "error"`, a stop reason left undelimited in the tail, or a message event cut off after an earlier stop reason (later content clears an earlier stop reason). A frame counts as evidence only when its payload `type` and its `event` name agree or the event line is absent, so a `ping`-named frame carrying a `message_stop` payload is not a terminal. In the managed lane, a routed provider with `anthropicEofTolerance` keeps a content-only EOF (no stop reason, nothing cut) as a finished turn, while caller-forward passthrough treats it as a failed turn; an error stop reason or a cut tail fails on both lanes. A done read after the cancel signal aborted is a 499 client cancel, the same rule as a rejected read. The non-streaming fold (`collectAnthropicMessage` in `src/claude/outbound.ts`) frames on a CRLF/CR-normalized copy and names a data-only frame by its payload type, so CRLF and data-only streams fold with their content. `tests/claude-integration/messages-native-clean-eof.test.ts` covers the tap's verdict for each EOF shape, the cancel race, the fold, and the managed lane end to end. +`tapAnthropicSseForLog` in `src/server/messages-shared.ts` (re-exported by `src/server/claude-messages.ts`) relays the streamed body of both the native passthrough and the managed native Messages lane (`src/server/messages-native.ts`). The response headers are already sent, so a stall, a byte-cap overflow, or an upstream read failure ends the body with an Anthropic `event: error` frame after a blank-line boundary and a clean close: `timeout_error` for an idle stall, `api_error` for the byte cap, and `api_error` when an upstream read fails mid-stream (a socket reset). The mid-stream reset is logged like the Responses relay's read error: status 502, `terminalStatus: "failed"`, `closeReason: "terminal"`, `transportPhase: "mid_stream"`, a synthetic terminal source, the attempt marked `streamAborted`, `failureDetail` code `stream_failed`, and the usage seen before the reset. The non-streaming fold in the managed lane closes its row with the tap's meta for a reset, a stall or the byte cap, so its row matches the streaming lane's. The request is not replayed. Every one of these frames logs status 502. A stall is `terminalStatus: "incomplete"` with `closeReason: "body_stall"`, the status the Responses relay gives a stall-timeout incomplete. The byte cap is `incomplete` with `closeReason: "body_overflow"`, the same 502 the non-stream passthrough answers for it. Both record `failureDetail` (`body_stall` with the stall window in milliseconds, `body_overflow` with the byte cap), and a reset is `terminalStatus: "failed"`. Either way the row keeps its failure diagnostics in usage.jsonl. A stall or overflow after the turn's own terminal (`message_stop` or an upstream `error` event) is a finished turn: it logs 200 and closes without an error frame, as the read-error branch does. The tap normalizes and scans only newly decoded text, holding a trailing CR and LF across reads so split CRLF and blank-line delimiters stay intact; it forwards the original bytes unchanged. Unfinished frames remain in fragments and are joined only at a frame boundary or tail flush. Tiny fragments are coalesced after at least 4096 code units, avoiding one retained array entry per byte on one-byte feeds. Each code unit is normalized once and joined at most twice; `tests/claude-integration/messages-shared-sse.test.ts` checks the linear work budget, tiny-fragment coalescing, split UTF-8 and line endings, usage, terminal-tail repair, byte caps and cancellation. At a clean EOF or a stall/reset flush, the held LF and CR rejoin the fragments in wire order and a held CR counts as a line ending; every frame that completes there is inspected as a complete event, and only the remainder after the last blank line is the undelimited tail. Some read failures are not upstream failures. When the cancel signal is already aborted, the rejection is a `499` client cancel, because Bun can reject the read before it dispatches the abort listener. The managed lane passes its upstream controller's signal, so shutdown and turn release count as cancels too. When `message_stop` or an upstream `error` event has been seen, including one still in the buffer without its blank-line delimiter, the turn is complete: it logs 200 and closes with no error frame. A terminal found only in that unterminated tail gets its blank line restored, because an SSE parser drops an event that EOF cuts off. A translator budget overflow is a local cap, so it still errors the stream, and the non-streaming fold answers it with 413. `tests/claude-integration/claude-native-passthrough.test.ts` and `tests/claude-integration/messages-native.test.ts` cover both lanes against an upstream that resets after a partial or a complete body, plus both cancel paths. A clean upstream EOF (no reset) ends the turn only when the client already has its terminal (`message_stop` or an upstream `error` event), or when the last message event it received as a complete SSE event was a `message_delta` with a non-error `stop_reason` and nothing but whitespace, comments or a ping follows it undelimited: compatible providers may omit `message_stop`, and the translated adapter accepts the same shape. Those bytes are relayed unchanged and log 200. Every other clean EOF is a cut turn and fails exactly like a mid-stream reset (502, `terminalStatus: "failed"`, `transportPhase: "mid_stream"`, `streamAborted`, an `api_error` frame): a partial body, an EOF after `stop_reason: "error"`, a stop reason left undelimited in the tail, or a message event cut off after an earlier stop reason (later content clears an earlier stop reason). A frame counts as evidence only when its payload `type` and its `event` name agree or the event line is absent, so a `ping`-named frame carrying a `message_stop` payload is not a terminal. In the managed lane, a routed provider with `anthropicEofTolerance` keeps a content-only EOF (no stop reason, nothing cut) as a finished turn, while caller-forward passthrough treats it as a failed turn; an error stop reason or a cut tail fails on both lanes. A done read after the cancel signal aborted is a 499 client cancel, the same rule as a rejected read. The non-streaming fold (`collectAnthropicMessage` in `src/claude/outbound.ts`) frames on a CRLF/CR-normalized copy and names a data-only frame by its payload type, so CRLF and data-only streams fold with their content. `tests/claude-integration/messages-native-clean-eof.test.ts` covers the tap's verdict for each EOF shape, the cancel race, the fold, and the managed lane end to end. -A native passthrough answered without a stream records its reason in `upstreamError`, so the row and the failure diagnostics in usage.jsonl name the cause. An upstream error response (status 400 or above) is relayed verbatim; the stored diagnostic is `Provider error : ` only for a valid Anthropic error envelope with one of the closed types `invalid_request_error`, `authentication_error`, `permission_error`, `not_found_error`, `rate_limit_error`, `api_error`, `overloaded_error` or `request_too_large`. Upstream messages and arbitrary type strings never enter this diagnostic. Unknown or malformed envelopes, non-JSON bodies and bodies over 64 Ki characters log `Provider error `. Local header timeout, body stall, byte-cap overflow and cancel diagnostics contain fixed text plus validated guard limits. Fetch failures log the fixed reason `anthropic passthrough failed: upstream connection error`; the existing redacted client response is preserved. Classification uses these stored reasons and HTTP status, so a `permission_error` at 403 is `permission_denied` regardless of upstream message wording. `tests/claude-integration/claude-native-passthrough.test.ts` covers these cases and checks that echoed account identifiers and request content are absent from both history sinks. +A native passthrough answered without a stream records a closed `failureDetail` code ([proxy-owned error detail](../data-planes/error-detail.md)), so the row and the failure diagnostics in usage.jsonl name the cause. An upstream error response (status 400 or above) is relayed verbatim; the stored detail is `provider_error` with its `type` only for a valid Anthropic error envelope with one of the closed types `invalid_request_error`, `authentication_error`, `permission_error`, `not_found_error`, `rate_limit_error`, `api_error`, `overloaded_error` or `request_too_large`. Upstream messages and arbitrary type strings never enter this diagnostic. Unknown or malformed envelopes, non-JSON bodies and bodies over 64 Ki characters record `provider_error` without a type. Local header timeout, body stall, byte-cap overflow and cancel record `header_timeout`, `body_stall`, `body_overflow` and `client_closed` with validated guard limits. Fetch failures record `connect_failed`; the existing redacted client response is preserved. Classification uses these stored reasons and HTTP status, so a `permission_error` at 403 is `permission_denied` regardless of upstream message wording. `tests/claude-integration/claude-native-passthrough.test.ts` covers these cases and checks that echoed account identifiers and request content are absent from both history sinks. Linked-machine data uses the [connection-bound relay contract](../remote-link.md#connection-bound-relay-authentication); client-local credentials and routing policy remain unchanged. diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 9e9b8b49b10..ad9c2ec20b6 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -267,7 +267,7 @@ An opt-in shadow-call rewrite persists the bounded, redacted original helper mod request content or inferring a helper subtype from timing. A failed request persists closed `failureStage` and `failureCause` members on the attempt that ended it and on the logical row, derived once at `addFinalRequestLog` from facts that are themselves -closed; `errorCode` and `upstreamError` carry upstream text and are deliberately not read there. The +closed; `errorCode` and the context's `upstreamError` are open inputs and are deliberately not read there. The resend verdict they imply is never stored — `/api/logs` computes `resendPermission` at read time, so a row written by an older build cannot assert a permission the current tables refuse. An attempt also carries `deliverySummary`: adapter events, relayed frames, semantic bytes, side effects and terminal @@ -555,14 +555,14 @@ enabling it takes effect without a restart. ## Usage history and model identity -`src/server/request-log-terminal-status.ts` owns the diagnostics shared by request contexts and final rows in `src/server/request-log.ts`. It provisionally maps bare upstream `error` events with recognized rate-limit classes to 429 and explicit overload to 503; an unknown code takes the 5xx its Codex WebSocket wrapper states (top-level integer `status` or `status_code`, not both, read by `codexWsWrapperStatus` in `src/server/responses/codex-ws-wire.ts`, as the native client does), otherwise it remains 502; a wrapper 4xx is not adopted because it would move quota or credential routing, and policy refusals retain precedence (#6740). Genuine completed, failed, or incomplete terminals supersede provisional status before account-health recording. Final rows keep the first `upstreamErrorType` (closed provider-class vocabulary), `upstreamErrorCode` (nested envelopes, or a known bare class) and `upstreamRequestId` within the 128-character token allowlist, and drop any value that repeats a credential: `src/server/configured-credentials.ts` reads every configured provider key, pool key, header value and OAuth-store token when checking (observe-only and quiet; rebuilt when the bytes of `config.json` or `auth.json` change (every check reads both stores and compares a content digest, never inode/size/mtime, so a same-length rewrite inside one timestamp tick or a timestamp-preserving writer is still seen), when a keychain secret is replaced in this process, or when a referenced env value changes; an incomplete set is retried after 30 s; `upstreamDiagnosticLogFields` takes one snapshot per projected row, only once a field is populated), and `src/lib/outbound-credential-registry.ts` records final HTTP (`sendWithConnectionPolicy`) and Codex WebSocket headers in a strict tier (credential-named, any length) and a best-effort tier (8+ characters, never disabling), split into components. The check runs at capture, in warnings and at projection; an incomplete configured source (until it recovers) or an evicted strict value (until restart) makes all three fields fail closed; the event discriminator is not an error class. It preserves upstream `servedModel` independently of route-derived +`src/server/request-log-terminal-status.ts` owns the diagnostics shared by request contexts and final rows in `src/server/request-log.ts`. It provisionally maps bare upstream `error` events with recognized rate-limit classes to 429 and explicit overload to 503; an unknown code takes the 5xx its Codex WebSocket wrapper states (top-level integer `status` or `status_code`, not both, read by `codexWsWrapperStatus` in `src/server/responses/codex-ws-wire.ts`, as the native client does), otherwise it remains 502; a wrapper 4xx is not adopted because it would move quota or credential routing, and policy refusals retain precedence (#6740). Genuine completed, failed, or incomplete terminals supersede provisional status before account-health recording. The request context keeps the first `upstreamErrorType` (closed provider-class vocabulary), `upstreamErrorCode` (nested envelopes, or a known bare class) and `upstreamRequestId` within the 128-character token allowlist for classification and the service warning (rows drop all three, see [proxy-owned error detail](data-planes/error-detail.md)), and drops any value that repeats a credential: `src/server/configured-credentials.ts` reads every configured provider key, pool key, header value and OAuth-store token when checking (observe-only and quiet; rebuilt when the bytes of `config.json` or `auth.json` change (every check reads both stores and compares a content digest, never inode/size/mtime, so a same-length rewrite inside one timestamp tick or a timestamp-preserving writer is still seen), when a keychain secret is replaced in this process, or when a referenced env value changes; an incomplete set is retried after 30 s; `upstreamDiagnosticLogFields` takes one snapshot per projected row, only once a field is populated), and `src/lib/outbound-credential-registry.ts` records final HTTP (`sendWithConnectionPolicy`) and Codex WebSocket headers in a strict tier (credential-named, any length) and a best-effort tier (8+ characters, never disabling), split into components. The check runs at capture, in warnings and at projection; an incomplete configured source (until it recovers) or an evicted strict value (until restart) makes all three fields fail closed; the event discriminator is not an error class. It preserves upstream `servedModel` independently of route-derived `resolvedModel`; `src/usage/log.ts` persists it with `wireModel`. The Logs model column and detail view compare `servedModel` with `wireModel ?? model`. `recordObservedServedModel` in `src/usage/log.ts` refuses the client's own selector echoed in `response.model` (Anthropic routes keep `anthropic/` there), and `modelIdentityLogFields` drops the same echo from older rows on read, so neither draws a false reroute. An absent upstream model stays absent; the tooltip retains all available model identities. Historical Codex `openai`, `chatgpt` and `openai-multi` main -labels collapse for reporting; configured provider names ending in `-main` remain separate. Native Messages request and attempt `requestedEffort` labels follow the [native Messages logging contract](data-planes/protocol-paths.md#managed-native-messages). +labels collapse for reporting; configured provider names ending in `-main` remain separate. Native Messages request and attempt `requestedEffort` labels follow the [native Messages logging contract](data-planes/protocol-paths.md#managed-native-messages). Row error fields follow [Proxy-Owned Error Detail](data-planes/error-detail.md): closed codes, a classified condition, a numeric quota reset and proxy-authored failure detail; upstream error text never reaches a row. The Logs request detail headline prefers a recognized request-level cause over the HTTP status label and omits the status description; unknown persisted causes are dropped and use the status fallback without raw attribution. Physical sends are unavailable for absent or invalid spend; retries appear only for one attempt with fully settled, consistent accounting and no flagged loss during attempt normalization, as sends after the first, floored at zero. Direct request-log ingress validates attempts with the persistence normalization rule, marks any loss, and retains the original live roster and its metadata. The ledger writer removes malformed attempts and persists the loss flag, so hydrated rosters can differ from live ones; both suppress retries when loss is marked. A loss detected while normalizing a legacy row is a non-enumerable in-memory flag, retained through re-normalization without changing JSON serialization; an explicitly persisted true flag stays enumerable. The persisted-to-request-log conversion and direct DTO projection preserve the flag. Other attempts and recovery reasons remain visible. Rows also carry the observed protocol path (`protocolTrace`), persisted in `usage.jsonl` and re-validated on read; the Logs list shows it as a text badge, the detail dialog as a section, and diff --git a/structure/data-planes/error-detail.md b/structure/data-planes/error-detail.md new file mode 100644 index 00000000000..7f334a6eb48 --- /dev/null +++ b/structure/data-planes/error-detail.md @@ -0,0 +1,151 @@ +# Proxy-Owned Error Detail + +Request-log rows carry only error facts this proxy owns. `projectErrorDetail` in +`src/usage/error-detail.ts` runs on the final row in `addFinalRequestLog` before any writer (an +injected one included) and again first in `addRequestLog`, so the live ring, `/api/logs` and the +`usage.jsonl` projection read one projected entry; `normalizeUsageEntry` applies `errorDetailFor` to every +append and read, and `requestLogEntryFromPersistedUsage` runs `projectErrorDetail` on hydration (on a copy +of the attempts), so it bounds tiers and drops upstream fields itself even for a row that did not come +through the disk reader. A row keeps: + +- `errorCode` from the literal `LOG_ERROR_CODES` vocabulary or a proxy-formatted `http_NNN`; any other + value (an upstream code that reached a writer) collapses to the status fallback (`invalid_request_error`, + `invalid_api_key`, `permission_denied`, `rate_limit_exceeded`, `client_closed_request`, + `server_is_overloaded`, `upstream_server_error`, `http_NNN`, else `upstream_error`). Attempt codes are + normalized the same way, and upstream text fields removed from attempts, in place. +- `upstreamCondition`, a member of the closed set in `src/lib/upstream-condition.ts`, derived only for a + failed row with upstream evidence; a client close (499, `client_closed_request`, `client_cancelled`) gets + none, and a stored condition is kept only under the same rules. Text set through + `recordLocalFailureDetail` is not upstream evidence unless the caller passes `upstreamEvidence: true` + (the Messages passthrough restating an upstream status and closed type); `upstreamErrorIsLocal` keeps + it out of the final row's evidence. The Messages passthrough classifies the condition where it parses the + upstream error and stores only the member on the context (`upstreamCondition`), so a native Anthropic + overflow is recorded as `context_overflow`. `classifyUpstreamCondition` reads status, bounded structured + tokens and, for 4xx only, fixed lowercase keyword sets: 401 is authoritative, structured tokens come next + (account usage-limit codes `usage_limit_exceeded` and `1308` are billing exhaustion), context overflow + from text needs the definite verdict `isDefiniteContextOverflow` in the dependency-free + `src/lib/context-overflow-verdict.ts` (the one combo failover uses, re-exported by + `src/combos/failover.ts`), so a validation error that quotes "prompt is too long" stays rejected, a 429 that + names a rate limit stays `rate_limited` even when it also mentions quota, a 5xx stays a server failure + whatever its text says, and a bare status maps to a fixed condition. It is presentation-only; routing, + retry and recovery keep their own classifiers in `src/lib/errors.ts`. `upstreamConditionMessage` holds the + proxy-written sentence for each member and names only a well-formed configured provider id. +- `rateLimitResetAt`, finite epoch milliseconds after the request and at most eight days later, derived + server-side from the exact Meta Muse quota sentence on a Muse 429; the dashboard quota observation in + `gui/src/muse-limit-observation.ts` reads only this number. Legacy rows that stored the sentence recover + the number on hydration. +- `failureDetail`, a closed `{ code, value?, type? }` from `src/lib/failure-detail.ts`: `code` is a member of + `FAILURE_DETAIL_CODES`, `value` a safe integer (milliseconds or bytes) kept only for codes that take one, + and `type` a closed Anthropic error class kept only on `provider_error`. `recordLocalFailureDetail` in + `src/server/request-log-failure-detail.ts` takes the detail beside the English text it leaves on the + context; `incompleteReasonDetail` maps the known `incomplete_details.reason` values (`max_output_tokens`, + `upstream_stall_timeout`, `adapter_eof`), and an unknown reason stays on the context only. A relayed error + that exactly matches one of the proxy's own timeout or client-close sentences (`PROXY_SENTENCES`) becomes + its code with the parsed number, bounded to seven digits. `boundedFailureDetail` validates every append, + read and hydration; free text (a row from an earlier build or an edited one) is dropped. The dashboard + renders the code through `failureDetailLabel` in `gui/src/pages/logs-failure-summary.ts` and the + `logs.failureDetail.*` catalog keys in every locale. + +`upstreamError`, `upstreamErrorCode`, `upstreamErrorType` and `upstreamRequestId` stay on the request +context, where status heuristics and classifiers read them, and never reach a row, `usage.jsonl` or the +service log. Bytes already in `usage.jsonl` from earlier builds are not rewritten; they are dropped on every +read and hydration. The Logs detail shows the localized condition and the failure detail. +`tests/usage/request-log-error-detail.test.ts` covers the vocabulary, projection, hydration and the Muse +round trip; `tests/server/upstream-error-detail-boundaries.test.ts` drives native Chat, Responses +passthrough and both Messages lanes against an upstream that echoes its credential, and checks the live +row, `usage.jsonl`, hydration and console output. + +## Service tier and model identity + +A recorded response service tier is a member of `RESPONSE_SERVICE_TIERS` in +`src/lib/response-service-tier.ts` (`auto`, `default`, `flex`, `scale`, `priority`, `fast`, `standard`, +`ultrafast`, case-folded); any other value is omitted. `boundedServiceTier` applies at capture (the +Responses payload in `src/server/request-log.ts`, both FastWire observers in `src/providers/fastwire.ts`), in +the live projection for the row and every nested `tierOutcome`, and in `normalizeUsageEntry`. Fast +confirmation still reads the raw observation, so a configured wire value outside the set confirms Fast +without being recorded. + +An upstream-reported model is kept only when it equals a model id this proxy already knows, because no +identifier grammar can tell a prefixless credential from a model name. `knownModelIdentity` in +`src/lib/model-identity.ts` applies `boundedModelIdentity` (`[A-Za-z0-9._:/@-]`, at most 128 characters, +unchanged by the secret redactor) and then requires an exact match with one of: the ids the route names +(`routeKnownModels` in `src/usage/log.ts`: the routed model and its unprefixed form, the wire model, the +requested model and alias, and every attempt's target), the bundled Codex catalog +(`src/codex/catalog/pinned-models.ts`), or the bundled metadata catalog for the selected provider +(`src/generated/model-metadata.ts`). It returns the proxy's copy of the matched id. `servedModel` and +`resolvedModel` pass it independently at capture (`recordObservedServedModel` and the passthrough +`openai-model` header in `src/server/responses/passthrough-delivery.ts`), and again in `addRequestLog`, +`normalizeUsageEntry` and hydration through `modelIdentityLogFields`; anything else is not recorded. Relayed +WebSocket model headers use the same rule with the requested model as the known id. +`sanitizePassthroughHeaders` in `src/server/relay.ts` applies the rule to the relayed `openai-model` and +`x-codex-safety-buffering-faster-model` headers itself, so no passthrough branch (redirects, error +statuses, JSON answered as JSON or re-framed as SSE) can relay an unknown value. The passthrough passes it +the route's ids plus the models the user configured for the selected provider (`models`, +`retainModels`, `defaultModel`), so a provider-owned hint naming one of them survives as the proxy's +copy. Live-discovered ids are never trusted anywhere the rule applies: the upstream's own `/models` +answer chose them, so a hint naming a model known only from discovery is not relayed. `selectedModels` +is not trusted either, because a model preset fills it from that same discovered catalog; a hint naming +a model that is only preset-selected is not relayed. Rows do not see that provider list, +so a served model that only it names is relayed in the header but not recorded. +`tests/usage/request-log-identity-bounds.test.ts`, `tests/usage/request-log-served-model.test.ts` and +`tests/server/response-model-identity.test.ts` cover capture, live, ledger, hydration, the `/api/logs` DTO +and the passthrough header. + +## Response metadata headers + +`src/server/safe-response-headers.ts` lists each upstream response header a client may receive as +response metadata (WebSocket metadata frames, the WS-to-HTTP projection, the HTTP-to-WS error bridge) by +exact name in a `Map`, so a header named after an `Object.prototype` member (`constructor`, `__proto__`, +`toString`) never resolves, and `normalizeSafeResponseHeader` returns only primitive strings, validating or +rebuilding each value against its contract, so no upstream bytes are copied: +retry advice through `formatClientRetryAfter`; models through `boundedModelIdentity`; rate-limit counts +as non-negative integers (fractions round down, clamped to 10^12); rate-limit resets as integer seconds +(rounded up, clamped to eight days) or Go-style durations rebuilt from whole seconds (whole milliseconds +below one second); booleans, credit balances and quota percentages, windows and reset times as numbers +this proxy formats. Codex quota windows are relayed for the ordinary family and the metered +`bengalfox` family only (`CODEX_QUOTA_FAMILIES`): a header name is upstream text too, so any other family +is dropped. Request ids, the models etag (the client reads this proxy's own catalog, which carries no +validator), quota limit labels and free-text headers such as the promo message are not relayed. + +The turn-state token is the one value a client must send back: Codex replays `x-codex-turn-state` on +later requests of the turn, and on the WebSocket upgrade, to keep the turn on one backend. +`src/server/turn-state-handles.ts` issues a random handle (`ocx-ts-` and 32 hex digits) per token and +binds it to the send that received the token: a digest of the admitted caller (configured key id, +environment principal or loopback), the provider name and the outbound account (the ChatGPT account id, +or the outbound credential when there is none). The mapping lives in process memory (bounded to 4096 +entries, six-hour expiry). Each request and each WebSocket `response.create` frame runs in its own caller +scope (`runTurnStateCallerScope`, opened by the server's `fetch` wrapper and the frame handler), which +`admissionFields` in `src/server/auth-cors.ts` fills. A handle is redeemed only at the physical send in +`src/server/responses/fetch-helpers.ts`, after admission and routing: the outbound header and +`client_metadata["x-codex-turn-state"]` map back to the token when the send's binding matches, and are +removed otherwise, with the fixed service-log flag `turn_state_binding_mismatch` for a mismatch. The WS +upstream receives the same binding on its init, and the exchange issues handles with it; without a +binding a token is dropped. Handles, tokens and bindings are never logged; a value that is not a handle +passes unchanged. + +`codex-ws-metadata.ts` checks the raw byte budget first, then keeps only normalized values. It rebuilds +the native `codex.rate_limits` frame field by field: known limit ids (`codex`, `codex_bengalfox`), a +closed set of plan labels, the `allowed`/`limit_reached` flags, quota windows with the percent clamped to +100 at two decimals and integer window and reset values, and the credit flags. Every other field is +discarded, including the credit balance, which clients receive only as the proxy-formatted +`x-codex-credits-balance` header; the windows of an unknown limit id are dropped rather than relabelled. +The connection-level `x-reasoning-included` seed stays present, since Codex reads it by presence, but +carries only an exact `true`/`false` or an empty value. +`tests/server/safe-response-headers.test.ts` covers the allowlist, each contract and both WebSocket +consumers; `tests/server/turn-state-handles.test.ts` covers the handle map and drives a real server over +HTTP and WebSocket. + +## Client retry advice + +Client `Retry-After` advice is a string this proxy formats: `formatClientRetryAfter` in +`src/lib/client-retry-after.ts` turns delay seconds (fractions round up) or an HTTP date in any RFC 9110 +form (IMF-fixdate, RFC 850, asctime, all read as GMT field by field) into +an integer of seconds clamped to 0..691200 (eight days, so a weekly usage-window reset such as a local Codex account +cooldown still reaches the client), and yields nothing for any other input. The Ollama surface keeps its +own smaller bound (`ollamaRetryAfter`). Every other client boundary uses `formatClientRetryAfter` +(translated errors, native Chat and Messages including pacing refusals, Messages passthrough, the Responses +error re-wrap, compact, context history, WebSocket response metadata, fallback refusal, Copilot refusal, +usage-limit and combo-unavailable refusals, Codex account cooldowns and the Claude subscription cooldown). Internal cooldown and +retry scheduling keep reading the parsed evidence through `resolveClientRetryAfter` and +`src/combos/failover.ts`. `tests/server/client-retry-after-sites.test.ts` and +`tests/lib/client-retry-after.test.ts` cover the sites and the format. diff --git a/structure/data-planes/ollama-inbound.md b/structure/data-planes/ollama-inbound.md index 6a332aab1c4..cae06d0e81a 100644 --- a/structure/data-planes/ollama-inbound.md +++ b/structure/data-planes/ollama-inbound.md @@ -62,8 +62,9 @@ known, the row drops partial usage (so the send settles as unresolved), records `observation_barrier_timeout`, and never reports success. Inner Chat runs with `suppressProtocolTrace`, so a native row persists no Chat protocol identity (see [Protocol Paths](protocol-paths.md#observed-trace)). -The commit also drops upstream-authored text (`upstreamError`, `upstreamErrorCode`, -`upstreamErrorType`, `upstreamRequestId`) from the row; status, derived codes and attribution stay. +Upstream evidence stays on the context through the final write, so the condition and quota reset are +derived from it; the [row projection](error-detail.md) then drops the upstream-authored text +(`upstreamError`, `upstreamErrorCode`, `upstreamErrorType`, `upstreamRequestId`) before any writer. ## Protocol trace diff --git a/structure/manifest.json b/structure/manifest.json index 1bad5e80d07..522672fbc74 100644 --- a/structure/manifest.json +++ b/structure/manifest.json @@ -533,6 +533,22 @@ "src/protocols/codecs/ollama.ts" ] }, + { + "path": "data-planes/error-detail.md", + "tier": 3, + "title": "Proxy-Owned Error Detail", + "scope": "Closed error codes, upstream condition classification, numeric quota reset, closed failure detail, service tier and model identity bounds on request-log rows; response metadata header normalization and the client Retry-After format.", + "documents": [ + "src/usage/error-detail.ts", + "src/lib/upstream-condition.ts", + "src/lib/client-retry-after.ts", + "src/lib/failure-detail.ts", + "src/lib/response-service-tier.ts", + "src/lib/model-identity.ts", + "src/server/safe-response-headers.ts", + "src/server/request-log-failure-detail.ts" + ] + }, { "path": "data-planes/chat-reasoning-details.md", "tier": 3, diff --git a/structure/transports/responses-combo-boundaries.md b/structure/transports/responses-combo-boundaries.md index 4ffdf66af74..a03a28c0925 100644 --- a/structure/transports/responses-combo-boundaries.md +++ b/structure/transports/responses-combo-boundaries.md @@ -139,9 +139,9 @@ accepted stream lifetime, cancellation, and exactly-once attached-lease release. Plain admission leases without controller binding do not register or unregister a ladder controller. Reasonless incomplete snapshots containing output items stay committed; an explicit `reason: null` also stays terminal. `tests/routing/combo-stream-preflight.test.ts` pins these conservative boundaries. -Hop warnings in `src/server/responses/core-combo.ts` include only parsed upstream code/message, -redacted before whitespace flattening and bounded to 200 characters; unparsed bodies stay out. -`tests/responses/responses-combo-exhausted-error.test.ts` pins that log boundary. +Hop warnings in `src/server/responses/core-combo.ts` name the status and the closed condition from +`classifyUpstreamCondition` ([proxy-owned error detail](../data-planes/error-detail.md)); upstream codes, +messages and bodies stay out. `tests/responses/responses-combo-exhausted-error.test.ts` pins that log boundary. A `runTurn` adapter has the equivalent boundary in `preflightAdapterEvents` (`src/adapters/run-turn-queue.ts`), streaming and non-streaming alike: when its first meaningful event is a tool call the current request did not declare, and no earlier replay-unsafe heartbeat recorded a side effect, `src/server/responses/run-turn-execution.ts` projects the fail-closed undeclared-tool refusal as a pre-commit 502 so the combo can hop with the unchanged catalog. After any output or a replay-unsafe heartbeat the refusal stays with that child. Chat Completions and Anthropic Messages inbound requests do not use this classification. The same heartbeat also decides an ordinary pre-output adapter error or an empty end: after a replay-unsafe heartbeat the child's 502 is marked non-replayable, so the combo stops on it instead of sending the turn to the next target. diff --git a/structure/transports/responses-wire-shapes.md b/structure/transports/responses-wire-shapes.md index eced4076992..56e12dfdf64 100644 --- a/structure/transports/responses-wire-shapes.md +++ b/structure/transports/responses-wire-shapes.md @@ -464,8 +464,8 @@ Lite identity still retires the previous socket, and subsequent eligible request identity can reuse the new socket. Malformed native metadata retains HTTP fallback eligibility without rewriting its body. -Canonical WS quota and response metadata preceding the first Responses event are projected into bounded, allowlisted HTTP headers before commitment. -`src/server/responses/codex-ws-session.ts` also retains the actual `x-reasoning-included` upgrade header when Bun exposes its handshake event, promoting the bounded candidate only after `open` validates the connection. No other upgrade header is retained: request ids, model, turn state, quota and credits are response-scoped. +Canonical WS quota and response metadata preceding the first Responses event are projected into bounded, allowlisted HTTP headers before commitment; each name and value follows the [response metadata header contract](../data-planes/error-detail.md#response-metadata-headers). +`src/server/responses/codex-ws-session.ts` also retains the `x-reasoning-included` upgrade header when Bun exposes its handshake event, promoting the bounded candidate only after `open` validates the connection; the seed keeps the header present but carries only an exact `true`/`false` or an empty value. No other upgrade header is retained: request ids, model, turn state, quota and credits are response-scoped. `src/server/responses/codex-ws-metadata.ts` rejects malformed or oversized raw headers and connection-nominated inclusion headers without changing transport failure or replay policy. Each canonical exchange starts from that connection signal; its own prelude metadata wins, including an explicit `false` value, and no prior exchange's metadata carries over. No signal is inferred from a model, configuration or encrypted input, and usage numbers are unchanged. Later metadata remains in the SSE body, while quota observations update only the captured serving account; neither changes committed HTTP headers. The pre-output hold freezes the same snapshot at its first Responses event. A client-facing WebSocket upgrade is already complete before upstream dispatch and cannot acquire this HTTP/SSE response header retroactively. `tests/responses/codex-ws-handshake.test.ts` and `tests/responses/codex-ws-handshake-validation.test.ts` cover the native loopback, reuse, bounds and failed-upgrade boundaries. Control frames remain bounded, and provider credential/cookie headers are not forwarded. diff --git a/structure/transports/responses.md b/structure/transports/responses.md index 4e3fed3a638..159563a40fb 100644 --- a/structure/transports/responses.md +++ b/structure/transports/responses.md @@ -288,7 +288,7 @@ alone never opt a gateway in. Response-tier evidence is governed by `src/provide ### Response-tier observation authority -`src/providers/fastwire.ts` copies a defined authority flag into `AttemptTierOutcome`. With false, an eligible serialized priority request remains `fastOutcome: applied` and `confirmation: assumed`: the parameter was sent, while actual scheduling is unconfirmed. Neither a `default` nor a `priority` echo can confirm or deny Fast; sanitized `responseServiceTier` remains for inspection, while local capability and wire failures still downgrade. Logs and persisted attempts retain the flag, and `src/usage/cost.ts` uses requested-tier estimation without promoting an untrusted echo or a confirmed label to response-confirmed pricing. Official API and undeclared destinations retain legacy response judgments. +`src/providers/fastwire.ts` copies a defined authority flag into `AttemptTierOutcome`. With false, an eligible serialized priority request remains `fastOutcome: applied` and `confirmation: assumed`: the parameter was sent, while actual scheduling is unconfirmed. Neither a `default` nor a `priority` echo can confirm or deny Fast; a closed-member `responseServiceTier` ([service tier and model identity](../data-planes/error-detail.md#service-tier-and-model-identity)) remains for inspection, while local capability and wire failures still downgrade. Logs and persisted attempts retain the flag, and `src/usage/cost.ts` uses requested-tier estimation without promoting an untrusted echo or a confirmed label to response-confirmed pricing. Official API and undeclared destinations retain legacy response judgments. Anthropic Fast eligibility and downgrade recovery use the [Responses failover contract](responses-failover.md#anthropic-fast-downgrade-recovery). The [instance runtime contract](../providers/anthropic-account-pool.md#instance-scoped-runtime) governs Anthropic pool selection, physical-send ownership and continuation recovery. diff --git a/tests/adapters/anthropic/anthropic-error-body.test.ts b/tests/adapters/anthropic/anthropic-error-body.test.ts index 91f84507dc9..3fff101ad81 100644 --- a/tests/adapters/anthropic/anthropic-error-body.test.ts +++ b/tests/adapters/anthropic/anthropic-error-body.test.ts @@ -119,7 +119,7 @@ describe("anthropic adapter through the web-search bridge", () => { ); }); - test("the formatted message flows into the persisted request log upstreamError", async () => { + test("the formatted failure reaches the request log as a closed condition without provider text", async () => { const envelope = JSON.stringify({ type: "error", error: { type: "invalid_request_error", message: "prompt shape rejected" }, @@ -141,7 +141,9 @@ describe("anthropic adapter through the web-search bridge", () => { ); await logged.text(); expect(entries).toHaveLength(1); - expect(entries[0].upstreamError).toBe("Provider error 400: invalid_request_error: prompt shape rejected"); + expect(entries[0].upstreamError).toBeUndefined(); + expect(entries[0].upstreamCondition).toBe("request_rejected"); + expect(JSON.stringify(entries[0])).not.toContain("prompt shape rejected"); expect(entries[0].status).toBe(400); }); diff --git a/tests/claude-integration/claude-messages-endpoint.test.ts b/tests/claude-integration/claude-messages-endpoint.test.ts index c539c0c4ed0..3d971dc65b2 100644 --- a/tests/claude-integration/claude-messages-endpoint.test.ts +++ b/tests/claude-integration/claude-messages-endpoint.test.ts @@ -780,7 +780,7 @@ test("native openai-responses Claude route logs cyber terminals as 400 cyber_pol errorCode: "cyber_policy", terminalStatus: "failed", closeReason: "terminal", - upstreamError: "blocked", + upstreamCondition: "request_rejected", }); } finally { await server.stop(true); diff --git a/tests/claude-integration/claude-native-passthrough.test.ts b/tests/claude-integration/claude-native-passthrough.test.ts index 15337c44b9b..bf2c525ca46 100644 --- a/tests/claude-integration/claude-native-passthrough.test.ts +++ b/tests/claude-integration/claude-native-passthrough.test.ts @@ -866,7 +866,7 @@ test("a mid-stream upstream reset ends the native stream with an Anthropic error transportPhase?: string; terminalSource?: string; failureCause?: string; - upstreamError?: string; + upstreamError?: string; failureDetail?: unknown; usage?: { inputTokens?: number }; }>(await (await fetch(new URL("/api/logs?tail=1", server.url))).json()); expect(logs).toHaveLength(1); @@ -879,7 +879,9 @@ test("a mid-stream upstream reset ends the native stream with an Anthropic error expect(row.transportPhase).toBe("mid_stream"); expect(row.terminalSource).toBe("synthetic"); expect(row.failureCause).toBe("transport-ambiguous"); - expect(row.upstreamError).toContain("anthropic passthrough upstream stream failed: "); + // The row keeps the fixed sentence; the runtime error text stays internal. + expect(row.failureDetail).toEqual({ code: "stream_failed" }); + expect(row.upstreamError).toBeUndefined(); // Usage seen before the reset is still recorded. expect(row.usage?.inputTokens).toBe(12); } finally { @@ -965,7 +967,7 @@ test("a reset after message_stop is a finished turn: no error event and a comple const text = await res.text(); expect(text.endsWith(`event: message_stop\ndata: ${JSON.stringify({ type: "message_stop" })}\n\n`)).toBe(true); expect(text).not.toContain("event: error"); - const logs = logsFromApiBody<{ status?: number; closeReason?: string; transportPhase?: string; upstreamError?: string }>( + const logs = logsFromApiBody<{ status?: number; closeReason?: string; transportPhase?: string; upstreamError?: string; failureDetail?: unknown }>( await (await fetch(new URL("/api/logs?tail=1", server.url))).json(), ); expect(logs).toHaveLength(1); @@ -1016,7 +1018,7 @@ async function nativeFailureRow(upstreamBase: string, extraClaude?: Record( + const logs = logsFromApiBody<{ status?: number; closeReason?: string; upstreamError?: string; failureDetail?: unknown; errorCode?: string; upstreamCondition?: string }>( await (await fetch(new URL("/api/logs?tail=1", server.url))).json(), ); expect(logs).toHaveLength(1); @@ -1026,17 +1028,26 @@ async function nativeFailureRow(upstreamBase: string, extraClaude?: Record { - const errorBody = { type: "error", error: { type: "invalid_request_error", message: "prompt is too long: 213000 tokens > 200000 maximum" }, request_id: "req_fixture" }; +test.each([ + "prompt is too long: 213000 tokens > 200000 maximum", + "This model's maximum context length is 200000 tokens", +])("an upstream error response is relayed verbatim and its reason reaches the request log and usage.jsonl (%s)", async message => { + const errorBody = { type: "error", error: { type: "invalid_request_error", message }, request_id: "req_fixture" }; const upstream = Bun.serve({ port: 0, fetch: () => Response.json(errorBody, { status: 400 }) }); try { const { res, text, row } = await nativeFailureRow(upstream.url.toString().replace(/\/$/, "")); expect(res.status).toBe(400); expect(JSON.parse(text)).toEqual(errorBody); expect(row.status).toBe(400); - expect(row.upstreamError).toBe("Provider error 400: invalid_request_error"); + expect(row.failureDetail).toEqual({ code: "provider_error", type: "invalid_request_error" }); + // The condition is classified from the message where it is read; only the closed member is kept. + expect(row.upstreamCondition).toBe("context_overflow"); + const persisted = readRecentUsageEntries(1)[0]; // usage.jsonl carries failure diagnostics for >= 400 rows; this row used to persist none. - expect(readRecentUsageEntries(1)[0]?.upstreamError).toBe(row.upstreamError); + expect(persisted?.failureDetail).toEqual(row.failureDetail); + expect(persisted?.upstreamCondition).toBe("context_overflow"); + expect(JSON.stringify(row)).not.toContain(message); + expect(JSON.stringify(persisted)).not.toContain(message); } finally { upstream.stop(true); } @@ -1047,7 +1058,7 @@ test("a non-JSON upstream error still logs its status as the reason", async () = try { const { res, row } = await nativeFailureRow(upstream.url.toString().replace(/\/$/, "")); expect(res.status).toBe(502); - expect(row.upstreamError).toBe("Provider error 502"); + expect(row.failureDetail).toEqual({ code: "provider_error" }); } finally { upstream.stop(true); } @@ -1059,9 +1070,10 @@ test("a credential echoed in an upstream error message is excluded from persiste try { const { row } = await nativeFailureRow(upstream.url.toString().replace(/\/$/, "")); expect(row.status).toBe(401); - expect(row.upstreamError).toBe("Provider error 401: authentication_error"); - expect(readRecentUsageEntries(1)[0]?.upstreamError).toBe(row.upstreamError); - expect(row.upstreamError).not.toContain(leaked); + expect(row.failureDetail).toEqual({ code: "provider_error", type: "authentication_error" }); + expect(readRecentUsageEntries(1)[0]?.failureDetail).toEqual(row.failureDetail); + expect(JSON.stringify(row.failureDetail)).not.toContain(leaked); + expect(row.upstreamError).toBeUndefined(); } finally { upstream.stop(true); } @@ -1090,7 +1102,7 @@ test.each(["account", "request body"] as const)("an upstream message cannot pers const usage = readRecentUsageEntries(1); expect(usage).toHaveLength(1); for (const record of [row, usage[0]]) { - expect(record?.upstreamError).toBe(`Provider error 400: ${errorType}`); + expect(record?.failureDetail).toEqual({ code: "provider_error", type: errorType }); expect(JSON.stringify(record)).not.toContain(privateValue); } } finally { @@ -1106,8 +1118,8 @@ test.each([ const upstream = Bun.serve({ port: 0, fetch: () => Response.json({ type: "error", error: { type: errorType, message: privateValue } }, { status: 500 }) }); try { const { row } = await nativeFailureRow(upstream.url.origin); - expect(row.upstreamError).toBe(`Provider error 500: ${errorType}`); - expect(readRecentUsageEntries(1)[0]?.upstreamError).toBe(row.upstreamError); + expect(row.failureDetail).toEqual({ code: "provider_error", type: errorType }); + expect(readRecentUsageEntries(1)[0]?.failureDetail).toEqual(row.failureDetail); expect(JSON.stringify(row)).not.toContain(privateValue); } finally { upstream.stop(true); @@ -1129,8 +1141,8 @@ test.each([ try { const { text, row } = await nativeFailureRow(upstream.url.origin); expect(JSON.parse(text)).toEqual(errorBody); - expect(row.upstreamError).toBe("Provider error 502"); - expect(readRecentUsageEntries(1)[0]?.upstreamError).toBe("Provider error 502"); + expect(row.failureDetail).toEqual({ code: "provider_error" }); + expect(readRecentUsageEntries(1)[0]?.failureDetail).toEqual({ code: "provider_error" }); } finally { upstream.stop(true); } @@ -1150,7 +1162,7 @@ test("an unreachable upstream logs the fetch failure as the reason", async () => const { res, text, row } = await nativeFailureRow(refusedOrigin); expect(res.status).toBe(502); expect(row.status).toBe(502); - expect(row.upstreamError).toBe("anthropic passthrough failed: upstream connection error"); + expect(row.failureDetail).toEqual({ code: "connect_failed" }); expect(JSON.parse(text).error.message).toBe("anthropic passthrough failed: connect ECONNREFUSED"); } finally { globalThis.fetch = originalFetch; @@ -1172,12 +1184,13 @@ test("a credential in a local failure message is redacted for the client as well const { res, text, row } = await nativeFailureRow(refusedOrigin); expect(res.status).toBe(502); expect(text).not.toContain(leaked); - expect(row.upstreamError).toBe("anthropic passthrough failed: upstream connection error"); - expect(row.upstreamError).not.toContain(leaked); + expect(row.failureDetail).toEqual({ code: "connect_failed" }); + expect(JSON.stringify(row.failureDetail)).not.toContain(leaked); + expect(row.upstreamError).toBeUndefined(); expect(JSON.parse(text).error.message).toStartWith("anthropic passthrough failed: proxy rejected key "); const usage = readRecentUsageEntries(1); expect(usage).toHaveLength(1); - expect(usage[0]?.upstreamError).toBe(row.upstreamError); + expect(usage[0]?.failureDetail).toEqual(row.failureDetail); for (const record of [row, usage[0]]) { expect(JSON.stringify(record)).not.toContain(privateValue); expect(JSON.stringify(record)).not.toContain(leaked); @@ -1194,7 +1207,7 @@ test("an upstream that never sends headers logs the header timeout as the reason const { res, row } = await nativeFailureRow(`http://127.0.0.1:${silent.port}`, undefined, { connectTimeoutMs: 250 }); expect(res.status).toBe(504); expect(row.status).toBe(504); - expect(row.upstreamError).toBe("anthropic passthrough timed out waiting for response headers"); + expect(row.failureDetail).toEqual({ code: "header_timeout" }); } finally { silent.stop(true); } @@ -1206,7 +1219,7 @@ test("a non-stream body over the byte cap logs the cap as the reason", async () const { res, row } = await nativeFailureRow(upstream.url.toString().replace(/\/$/, ""), { bodyMaxBytes: 1024 }); expect(res.status).toBe(502); expect(row).toMatchObject({ status: 502, closeReason: "body_overflow" }); - expect(row.upstreamError).toBe("anthropic passthrough body exceeded 1024 bytes"); + expect(row.failureDetail).toEqual({ code: "body_overflow", value: 1024 }); } finally { upstream.stop(true); } @@ -1220,7 +1233,7 @@ test("an oversized upstream error body is relayed verbatim but not parsed for th const { res, text, row } = await nativeFailureRow(upstream.url.toString().replace(/\/$/, "")); expect(res.status).toBe(400); expect(JSON.parse(text)).toEqual(errorBody); - expect(row.upstreamError).toBe("Provider error 400"); + expect(row.failureDetail).toEqual({ code: "provider_error" }); } finally { upstream.stop(true); } @@ -1243,7 +1256,7 @@ test("a 403 permission error is classified without consulting its upstream messa try { const { row } = await nativeFailureRow(upstream.url.toString().replace(/\/$/, "")); expect(row.status).toBe(403); - expect(row.upstreamError).toBe("Provider error 403: permission_error"); + expect(row.failureDetail).toEqual({ code: "provider_error", type: "permission_error" }); expect(row.errorCode).toBe("permission_denied"); } finally { upstream.stop(true); @@ -1274,7 +1287,7 @@ test("a non-stream body that stalls logs the stall as the reason", async () => { const { res, row } = await nativeFailureRow(`http://127.0.0.1:${upstream.port}`, { bodyStallSec: 1 }); expect(res.status).toBe(504); expect(row).toMatchObject({ status: 504, closeReason: "body_stall" }); - expect(row.upstreamError).toBe("anthropic passthrough body stalled: no upstream bytes for 1s"); + expect(row.failureDetail).toMatchObject({ code: "body_stall" }); } finally { upstream.stop(); } @@ -1300,15 +1313,15 @@ test("a client that leaves while a non-stream body is pending logs the cancel as await Bun.sleep(50); client.abort(); await pending; - let row: { status?: number; closeReason?: string; upstreamError?: string } | undefined; + let row: { status?: number; closeReason?: string; upstreamError?: string; failureDetail?: unknown } | undefined; for (let i = 0; i < 100 && !row; i++) { - row = logsFromApiBody<{ status?: number; closeReason?: string; upstreamError?: string }>( + row = logsFromApiBody<{ status?: number; closeReason?: string; upstreamError?: string; failureDetail?: unknown }>( await (await fetch(new URL("/api/logs?tail=1", server.url))).json(), )[0]; if (!row) await Bun.sleep(20); } expect(row).toMatchObject({ status: 499, closeReason: "client_cancel" }); - expect(row!.upstreamError).toBe("client closed request during anthropic passthrough"); + expect(row!.failureDetail).toEqual({ code: "client_closed" }); } finally { await server.stop(true); upstream.stop(); @@ -1330,7 +1343,7 @@ async function stalledStreamRow(upstream: { url: URL }, extraClaude: Record( + const logs = logsFromApiBody<{ status?: number; terminalStatus?: string; closeReason?: string; upstreamError?: string; failureDetail?: unknown }>( await (await fetch(new URL("/api/logs?tail=1", server.url))).json(), ); expect(logs).toHaveLength(1); @@ -1350,7 +1363,7 @@ test("a stalled native stream logs a 502 incomplete row and keeps its diagnostic expect(text).toContain('"type":"timeout_error"'); // Same row the Responses relay writes for a stall-timeout incomplete (httpStatusForRequestLogTerminal). expect(row).toMatchObject({ status: 502, terminalStatus: "incomplete", closeReason: "body_stall" }); - expect(row.upstreamError).toBe("anthropic passthrough body stalled: no upstream bytes for 1s"); + expect(row.failureDetail).toMatchObject({ code: "body_stall" }); // usage.jsonl keeps failure diagnostics only for failed or non-completed rows; a 200 row dropped them. expect(usage).toMatchObject({ status: 502, terminalStatus: "incomplete", closeReason: "body_stall" }); } finally { @@ -1364,7 +1377,7 @@ test("a native stream over the byte cap logs a 502 incomplete row and keeps its const { text, row, usage } = await stalledStreamRow(upstream, { bodyMaxBytes: 64 }); expect(text).toContain("exceeded 64 bytes"); expect(row).toMatchObject({ status: 502, terminalStatus: "incomplete", closeReason: "body_overflow" }); - expect(row.upstreamError).toBe("anthropic passthrough body exceeded 64 bytes"); + expect(row.failureDetail).toEqual({ code: "body_overflow", value: 64 }); expect(usage).toMatchObject({ status: 502, terminalStatus: "incomplete", closeReason: "body_overflow" }); } finally { upstream.stop(true); diff --git a/tests/claude-integration/messages-native.test.ts b/tests/claude-integration/messages-native.test.ts index a2e5e65357b..88d886325ee 100644 --- a/tests/claude-integration/messages-native.test.ts +++ b/tests/claude-integration/messages-native.test.ts @@ -445,7 +445,9 @@ describe("managed native Messages", () => { } else { expect(message).toBe(upstreamMessage); } - expect(row.upstreamError).toBe(message); + // The row carries the classified condition, never the provider's message. + expect(row.upstreamError).toBeUndefined(); + expect(row.upstreamCondition).toBe("rate_limited"); expect(text).not.toContain("fixture-key-alpha"); }); test("an upstream error answers in Anthropic shape without the key", async () => { @@ -503,7 +505,8 @@ describe("managed native Messages", () => { expect(row.terminalSource).toBe("synthetic"); expect(row.failureCause).toBe("transport-ambiguous"); expect(row.attempts?.at(-1)?.streamAborted).toBe(true); - expect(row.upstreamError).toContain("anthropic passthrough upstream stream failed: "); + expect(row.failureDetail).toEqual({ code: "stream_failed" }); + expect(row.upstreamError).toBeUndefined(); expect(JSON.stringify(row)).not.toContain("fixture-key-alpha"); } finally { truncated.stop(); @@ -562,7 +565,7 @@ describe("managed native Messages", () => { expect(row.status).toBe(502); expect(row.terminalStatus).toBe("incomplete"); expect(row.closeReason).toBe("body_stall"); - expect(row.upstreamError).toBe("anthropic passthrough body stalled: no upstream bytes for 1s"); + expect(row.failureDetail).toMatchObject({ code: "body_stall" }); }); test("a client that disconnects mid-stream is logged as a cancel, not an upstream failure", async () => { diff --git a/tests/codex-integration/__snapshots__/catalog-omit-disabled-native.test.ts.snap b/tests/codex-integration/__snapshots__/catalog-omit-disabled-native.test.ts.snap index 003553c32ee..7a6cdc7e54e 100644 --- a/tests/codex-integration/__snapshots__/catalog-omit-disabled-native.test.ts.snap +++ b/tests/codex-integration/__snapshots__/catalog-omit-disabled-native.test.ts.snap @@ -17,3 +17,5 @@ exports[`upgraded gpt-6-luna after 2 convergence passes (unnamed) 1`] = `"cad289 exports[`upgraded gpt-6-luna after 1 retained sync passes (unnamed) 1`] = `"4b7e6430befcb01070fee32c962d0478412a7000112deab41c9da2bed5ce758b"`; exports[`upgraded gpt-6-luna after 2 retained sync passes (unnamed) 1`] = `"cad289facd9854199bb0247d1ed25f02c00bd782ef7e0842ebccb32706ae3003"`; + +exports[`upgraded gpt-6-luna after 1 retained sync passes (unnamed) 2`] = `"4b7e6430befcb01070fee32c962d0478412a7000112deab41c9da2bed5ce758b"`; diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 7349ad6a7cd..20b052ff660 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1588,4 +1588,5 @@ "hermes-profiles.test.ts": "clients", "hermes-profile-routes.test.ts": "clients" ,"cli-sync-expect-link.test.ts": "cli" ,"local-credentials.test.ts": "cli", "local-credential-generation.test.ts": "config", "link-connection-generation.test.ts": "clients" + ,"request-log-error-detail.test.ts": "usage", "upstream-condition.test.ts": "lib", "client-retry-after.test.ts": "lib", "client-retry-after-sites.test.ts": "server", "upstream-error-detail-boundaries.test.ts": "server", "request-log-identity-bounds.test.ts": "usage", "safe-response-headers.test.ts": "server", "turn-state-handles.test.ts": "server", "turn-state-handles-e2e.test.ts": "server" } diff --git a/tests/lib/client-retry-after.test.ts b/tests/lib/client-retry-after.test.ts new file mode 100644 index 00000000000..15ad1e192ac --- /dev/null +++ b/tests/lib/client-retry-after.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, test } from "bun:test"; +import { formatClientRetryAfter, MAX_CLIENT_RETRY_AFTER_SECONDS } from "../../src/lib/client-retry-after"; + +const now = Date.parse("2026-11-02T00:00:00Z"); + +describe("formatClientRetryAfter", () => { + test("delay seconds become a proxy-formatted integer", () => { + expect(formatClientRetryAfter("15", now)).toBe("15"); + expect(formatClientRetryAfter(" 15 ", now)).toBe("15"); + expect(formatClientRetryAfter("0", now)).toBe("0"); + expect(formatClientRetryAfter("000", now)).toBe("0"); + expect(formatClientRetryAfter("1.2", now)).toBe("2"); + expect(formatClientRetryAfter("007", now)).toBe("7"); + expect(formatClientRetryAfter(0, now)).toBe("0"); + expect(formatClientRetryAfter(7.01, now)).toBe("8"); + }); + + test("long delays clamp to the client maximum", () => { + expect(MAX_CLIENT_RETRY_AFTER_SECONDS).toBe(691_200); + expect(formatClientRetryAfter("84692", now)).toBe("84692"); + expect(formatClientRetryAfter("172800", now)).toBe("172800"); + expect(formatClientRetryAfter("691200", now)).toBe("691200"); + expect(formatClientRetryAfter("691201", now)).toBe("691200"); + // An all-digit value of credential length is a valid delay, but its bytes are never echoed. + expect(formatClientRetryAfter("73915028461739205817", now)).toBe("691200"); + expect(formatClientRetryAfter(1e30, now)).toBe("691200"); + }); + + test("HTTP dates become seconds from now", () => { + expect(formatClientRetryAfter("Mon, 02 Nov 2026 00:00:30 GMT", now)).toBe("30"); + expect(formatClientRetryAfter("Mon, 02 Nov 2026 00:00:00 GMT", now)).toBe("0"); + expect(formatClientRetryAfter("Sun, 01 Nov 2026 23:00:00 GMT", now)).toBe("0"); + expect(formatClientRetryAfter("Tue, 03 Nov 2026 00:00:00 GMT", now)).toBe("86400"); + expect(formatClientRetryAfter("Mon, 30 Nov 2026 00:00:00 GMT", now)).toBe("691200"); + }); + + test("obsolete RFC 850 and asctime dates are read as GMT", () => { + expect(formatClientRetryAfter("Monday, 02-Nov-26 00:00:30 GMT", now)).toBe("30"); + expect(formatClientRetryAfter("Sunday, 01-Nov-26 23:00:00 GMT", now)).toBe("0"); + // A two-digit year far in the future is the previous century, so it is already past. + expect(formatClientRetryAfter("Friday, 02-Nov-99 00:00:30 GMT", now)).toBe("0"); + expect(formatClientRetryAfter("Mon Nov 2 00:00:30 2026", now)).toBe("30"); + expect(formatClientRetryAfter("Tue Nov 03 00:00:00 2026", now)).toBe("86400"); + expect(formatClientRetryAfter("Mon Feb 30 00:00:00 2026", now)).toBeUndefined(); + expect(formatClientRetryAfter("Monday, 02-Xyz-26 00:00:30 GMT", now)).toBeUndefined(); + expect(formatClientRetryAfter("Mon, 02 Nov 2026 25:00:00 GMT", now)).toBeUndefined(); + }); + + test("anything else yields no advice", () => { + for (const value of ["", " ", "-1", "1e3", "Infinity", "NaN", "15s", "0x10", "must-not-echo", + "2026-11-02T00:00:30Z", "Mon, 02 Nov 2026 00:00:30 GMT extra", "9".repeat(200), null, undefined, + -1, Number.NaN, Number.POSITIVE_INFINITY]) { + expect(formatClientRetryAfter(value as string | number | null | undefined, now)).toBeUndefined(); + } + }); +}); diff --git a/tests/lib/upstream-condition.test.ts b/tests/lib/upstream-condition.test.ts new file mode 100644 index 00000000000..e2afb06c02d --- /dev/null +++ b/tests/lib/upstream-condition.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, test } from "bun:test"; +import { + classifyUpstreamCondition, isUpstreamCondition, UPSTREAM_CONDITIONS, upstreamConditionMessage, +} from "../../src/lib/upstream-condition"; + +// A provider key with no recognizable prefix, so pattern-based redaction cannot spot it. +const PROVIDER_KEY = "zq7Vb2LmN4pX9tR1sK8wD3fH6jY0cA5e"; + +describe("classifyUpstreamCondition", () => { + test("structured tokens map to their condition", () => { + expect(classifyUpstreamCondition({ status: 400, code: "context_length_exceeded" })).toBe("context_overflow"); + expect(classifyUpstreamCondition({ status: 403, code: "unsupported_country_region_territory" })).toBe("location_unsupported"); + expect(classifyUpstreamCondition({ status: 403, code: "organization_verification_required" })).toBe("account_verification_required"); + expect(classifyUpstreamCondition({ status: 429, code: "insufficient_quota" })).toBe("billing_exhausted"); + expect(classifyUpstreamCondition({ status: 404, code: "model_not_found" })).toBe("model_unavailable"); + expect(classifyUpstreamCondition({ status: 429, type: "rate_limit_error" })).toBe("rate_limited"); + expect(classifyUpstreamCondition({ status: 529, type: "overloaded_error" })).toBe("upstream_unavailable"); + expect(classifyUpstreamCondition({ status: 400, code: " Context_Length_Exceeded " })).toBe("context_overflow"); + }); + + test("keyword evidence classifies 4xx failures", () => { + expect(classifyUpstreamCondition({ status: 400, message: "prompt is too long: 210000 tokens > 200000 maximum" })).toBe("context_overflow"); + expect(classifyUpstreamCondition({ status: 400, message: "This model's maximum context length is 8192 tokens." })).toBe("context_overflow"); + expect(classifyUpstreamCondition({ status: 400, message: "User location is not supported for the API use." })).toBe("location_unsupported"); + expect(classifyUpstreamCondition({ status: 403, message: "Your organization must be verified to stream this model." })).toBe("account_verification_required"); + expect(classifyUpstreamCondition({ status: 400, message: "Your credit balance is too low" })).toBe("billing_exhausted"); + expect(classifyUpstreamCondition({ status: 400, message: "The model does not exist" })).toBe("model_unavailable"); + }); + + test("context overflow from text needs the combo router's definite verdict", () => { + // A validation error that quotes the caller's own value is not an overflow. + const sdkValidation = "Error code: 400 - {'error': {'message': \"Invalid 'tools[0].function.name': 'prompt is too long'. Expected a string that matches the pattern.\", 'type': 'invalid_request_error', 'param': 'tools[0].function.name', 'code': 'invalid_value'}}"; + expect(classifyUpstreamCondition({ status: 400, message: sdkValidation })).toBe("request_rejected"); + expect(classifyUpstreamCondition({ status: 400, message: "Invalid tool name: prompt is too long" })).toBe("request_rejected"); + expect(classifyUpstreamCondition({ status: 400, message: "This prompt is too long for the model" })).toBe("request_rejected"); + // 401/403 bodies that quote context prose speak about the credential. + expect(classifyUpstreamCondition({ status: 403, message: "maximum context length reached for this key" })).toBe("access_denied"); + }); + + test("account usage-limit codes are billing exhaustion whatever the message says", () => { + expect(classifyUpstreamCondition({ status: 400, code: "1308", message: "Bad request" })).toBe("billing_exhausted"); + expect(classifyUpstreamCondition({ status: 400, code: "usage_limit_exceeded", message: "Bad request" })).toBe("billing_exhausted"); + expect(classifyUpstreamCondition({ status: 429, type: "usage_limit_exceeded" })).toBe("billing_exhausted"); + }); + + test("conflicting evidence follows the documented precedence", () => { + // 401 is authoritative over billing or upgrade wording. + expect(classifyUpstreamCondition({ status: 401, code: "insufficient_quota", message: "billing required" })).toBe("auth_failed"); + // A 429 naming a rate limit stays a rate limit even when it also mentions quota. + expect(classifyUpstreamCondition({ status: 429, message: "Rate limit reached; quota exceeded for this minute" })).toBe("rate_limited"); + // Quota wording without rate wording on a 429 is exhaustion. + expect(classifyUpstreamCondition({ status: 429, message: "You exceeded your current quota" })).toBe("billing_exhausted"); + // A 5xx stays a server failure whatever its text says. + expect(classifyUpstreamCondition({ status: 500, message: "location is not supported" })).toBe("upstream_failed"); + expect(classifyUpstreamCondition({ status: 503, message: "insufficient quota" })).toBe("upstream_unavailable"); + // Structured tokens win over keywords. + expect(classifyUpstreamCondition({ status: 400, code: "model_not_found", message: "prompt is too long" })).toBe("model_unavailable"); + }); + + test("bare statuses fall back to a fixed condition", () => { + expect(classifyUpstreamCondition({ status: 401 })).toBe("auth_failed"); + expect(classifyUpstreamCondition({ status: 402 })).toBe("billing_exhausted"); + expect(classifyUpstreamCondition({ status: 403 })).toBe("access_denied"); + expect(classifyUpstreamCondition({ status: 404 })).toBe("model_unavailable"); + expect(classifyUpstreamCondition({ status: 429 })).toBe("rate_limited"); + expect(classifyUpstreamCondition({ status: 529 })).toBe("upstream_unavailable"); + expect(classifyUpstreamCondition({ status: 503 })).toBe("upstream_unavailable"); + expect(classifyUpstreamCondition({ status: 502 })).toBe("upstream_failed"); + expect(classifyUpstreamCondition({ status: 422 })).toBe("request_rejected"); + expect(classifyUpstreamCondition({ status: 200 })).toBeUndefined(); + expect(classifyUpstreamCondition({ status: Number.NaN })).toBeUndefined(); + }); + + test("oversized tokens are ignored rather than truncated into a match", () => { + expect(classifyUpstreamCondition({ status: 400, code: "context_length_exceeded" + "x".repeat(200) })).toBe("request_rejected"); + }); + + test("results and messages never carry input bytes", () => { + for (const status of [400, 401, 403, 404, 429, 500, 503]) { + const condition = classifyUpstreamCondition({ status, code: PROVIDER_KEY, type: PROVIDER_KEY, reason: PROVIDER_KEY, + message: "invalid key " + PROVIDER_KEY }); + expect(isUpstreamCondition(condition)).toBe(true); + expect(upstreamConditionMessage(condition!)).not.toContain(PROVIDER_KEY); + } + }); + + test("messages are proxy constants and name only a well-formed configured provider id", () => { + for (const condition of UPSTREAM_CONDITIONS) { + expect(upstreamConditionMessage(condition)).toMatch(/^[A-Z][^\n]*\.$/); + expect(upstreamConditionMessage(condition, "openai")).toEndWith("(provider: openai)"); + expect(upstreamConditionMessage(condition, "bad id\nwith text")).toBe(upstreamConditionMessage(condition)); + } + expect(isUpstreamCondition("constructor")).toBe(false); + }); +}); diff --git a/tests/providers/github-copilot/github-copilot-auto-runtime.test.ts b/tests/providers/github-copilot/github-copilot-auto-runtime.test.ts index a891fb44fa0..bcbc649eebf 100644 --- a/tests/providers/github-copilot/github-copilot-auto-runtime.test.ts +++ b/tests/providers/github-copilot/github-copilot-auto-runtime.test.ts @@ -268,6 +268,17 @@ describe("Copilot Auto through the Responses pipeline", () => { expect(await response.text()).not.toContain("must-not-echo"); expect(f.sent.find(call => call.path === "/responses")!.signal!.aborted).toBe(true); }); + test("passthrough refresh regenerates numeric retry advice instead of relaying its bytes", async () => { + const numericKey = "73915028461739205817"; + for (const [raw, expected] of [["9999", "3600"], [numericKey, null]] as const) { + await accounts(); + const f = fixture({ nativeFirst: true, negotiationRefusal: 429, negotiationRefusalAt: 2, negotiationRetryAfter: raw }); + const response = await handleResponses(request("hello", false), f.config, { model: "", provider: "" }); + expect(response.status).toBe(429); + expect(response.headers.get("retry-after")).toBe(expected); + expect(await response.text()).not.toContain(numericKey); + } + }); test("passthrough refresh malformed session remains a bounded 502", async () => { await accounts(); const f = fixture({ nativeFirst: true, malformedSessionAt: 2 }); diff --git a/tests/responses/chat-completions-endpoint.test.ts b/tests/responses/chat-completions-endpoint.test.ts index 1913cd76177..810b1cbe160 100644 --- a/tests/responses/chat-completions-endpoint.test.ts +++ b/tests/responses/chat-completions-endpoint.test.ts @@ -2333,8 +2333,10 @@ test("POST /v1/chat/completions logs native cyber terminals as 400 cyber_policy" errorCode: "cyber_policy", terminalStatus: "failed", closeReason: "terminal", - upstreamError: "blocked", + upstreamCondition: "request_rejected", }); + // The row keeps the classified condition only, never the provider's words. + expect(entry?.upstreamError).toBeUndefined(); } finally { await server.stop(true); await upstream.stop(true); diff --git a/tests/responses/codex-ws-handshake-validation.test.ts b/tests/responses/codex-ws-handshake-validation.test.ts index 31290af35e9..ac464fb7e01 100644 --- a/tests/responses/codex-ws-handshake-validation.test.ts +++ b/tests/responses/codex-ws-handshake-validation.test.ts @@ -106,8 +106,12 @@ test.each(["true", "false", ""])("preserves the actual upgrade value %j with mix expect((await exchange(upgrade(["X-Reasoning-Included", value]))).headers.get(flag)).toBe(value); }); -test("duplicate inclusion headers preserve their HTTP-combined value", async () => { - expect((await exchange(upgrade([flag, "true", "X-Reasoning-Included", "false"]))).headers.get(flag)).toBe("true, false"); +test("duplicate inclusion headers stay present without echoing their combined value", async () => { + expect((await exchange(upgrade([flag, "true", "X-Reasoning-Included", "false"]))).headers.get(flag)).toBe(""); +}); + +test("an upgrade inclusion value outside true/false stays present as an empty value", async () => { + expect((await exchange(upgrade([flag, "zq7Vb2LmN4pX9tR1sK8wD3fH6jY0cA5e"]))).headers.get(flag)).toBe(""); }); test("a handshake event after open cannot replace the validated connection default", async () => { diff --git a/tests/responses/openai-responses-passthrough.test.ts b/tests/responses/openai-responses-passthrough.test.ts index d5bbb818b3d..2cd15ecf883 100644 --- a/tests/responses/openai-responses-passthrough.test.ts +++ b/tests/responses/openai-responses-passthrough.test.ts @@ -552,13 +552,13 @@ test("noncanonical Responses preserves provider-owned safety-buffering hints", a adapter: "openai-responses", baseUrl: "https://fixture.test/v1", authMode: "key" as const, - apiKey: "fixture-key", + apiKey: "fixture-key", models: ["model", "provider-model"], }, { adapter: "openai-responses", baseUrl: "https://fixture.test/v1", authMode: "forward" as const, - headers: { authorization: "Bearer provider-static" }, + headers: { authorization: "Bearer provider-static" }, models: ["model", "provider-model"], }, ]) { const config = { @@ -575,7 +575,7 @@ test("noncanonical Responses preserves provider-owned safety-buffering hints", a }), config, { model: "", provider: "" }); expect(response.headers.get("x-codex-safety-buffering-enabled")).toBe("provider-owned"); - expect(response.headers.get("x-codex-safety-buffering-faster-model")).toBe("provider-model"); + expect(response.headers.get("x-codex-safety-buffering-faster-model")).toBe("provider-model"); // a configured model of this provider expect(await response.text()).toBe(upstream); } } finally { diff --git a/tests/responses/passthrough-headers.test.ts b/tests/responses/passthrough-headers.test.ts index 2cd52616096..2cccc765a1b 100644 --- a/tests/responses/passthrough-headers.test.ts +++ b/tests/responses/passthrough-headers.test.ts @@ -43,6 +43,20 @@ describe("passthrough header sanitization (RC5 / F4)", () => { expect(sanitized.has("set-cookie2")).toBe(false); expect(sanitized.get("content-type")).toBe("text/event-stream"); }); + + test("model headers are relayed only as a model id the route or a catalog already knows", () => { + const key = "zq7Vb2LmN4pX9tR1sK8wD3fH6jY0cA5e"; + const upstream = (model: string) => new Headers({ "content-type": "application/json", "openai-model": model, "x-codex-safety-buffering-faster-model": model }); + // Non-vacuous: ordinary headers still pass on every call below. + const unknown = sanitizePassthroughHeaders(upstream(key), { knownModels: ["gpt-5.5"], provider: "openai" }); + expect(unknown.get("content-type")).toBe("application/json"); + expect([unknown.has("openai-model"), unknown.has("x-codex-safety-buffering-faster-model")]).toEqual([false, false]); + const routed = sanitizePassthroughHeaders(upstream("custom-route-model"), { knownModels: ["custom-route-model"] }); + expect(routed.get("openai-model")).toBe("custom-route-model"); + // Without route context only a bundled catalog id passes. + expect(sanitizePassthroughHeaders(upstream("gpt-5.6-sol")).get("openai-model")).toBe("gpt-5.6-sol"); + expect(sanitizePassthroughHeaders(upstream("custom-route-model")).has("openai-model")).toBe(false); + }); }); describe("codex safety-buffering hint headers", () => { diff --git a/tests/responses/responses-combo-exhausted-error.test.ts b/tests/responses/responses-combo-exhausted-error.test.ts index 1fe674c5d23..1faef1b33d9 100644 --- a/tests/responses/responses-combo-exhausted-error.test.ts +++ b/tests/responses/responses-combo-exhausted-error.test.ts @@ -356,7 +356,7 @@ describe("combo exhaustion reports the primary's quota refusal", () => { expect(logCtx.attempts).toHaveLength(2); }); - test("the hop warning names the upstream refusal on one redacted line", async () => { + test("the hop warning names the classified condition, never the upstream text", async () => { const key = "sk-proj-" + "a1B2c3D4e5F6g7H8i9J0k1L2m3N4o5P6"; globalThis.fetch = (async () => Response.json( { error: { code: "invalid_api_key", message: `Incorrect API key provided: ${key}.\nRotate it.` } }, @@ -366,14 +366,15 @@ describe("combo exhaustion reports the primary's quota refusal", () => { try { await loggedCombo(config, { model: "", provider: "" }); const line = warn.mock.calls.map(call => String(call[0])).find(text => text.includes("primary/model-primary failed with")); - expect(line).toMatch(/failed with 401 after \d+ms: invalid_api_key: Incorrect API key provided: .* Rotate it\.$/); + expect(line).toMatch(/failed with 401 after \d+ms: auth_failed$/); expect(line).not.toContain(key); + expect(line).not.toContain("Incorrect API key"); } finally { warn.mockRestore(); } }); - test("the hop warning redacts credential framing before flattening parsed codes", async () => { + test("the hop warning never prints a parsed upstream code", async () => { const credential = "synthetic-multipart-credential"; globalThis.fetch = (async () => Response.json({ error: { code: `name="authorization"\r\n\r\n${credential}`, @@ -385,8 +386,22 @@ describe("combo exhaustion reports the primary's quota refusal", () => { const line = warn.mock.calls.map(call => String(call[0])).find(text => text.includes("primary/model-primary failed with")); expect(line).toBeDefined(); expect(line!.includes(credential)).toBe(false); - expect(line).toContain("[REDACTED]"); - expect(line).not.toMatch(/[\r\n]/); + expect(line).toMatch(/failed with 502 after \d+ms: upstream_failed$/); + expect(line).not.toContain("upstream refused"); + } finally { warn.mockRestore(); } + }); + + test("the hop warning classifies from the structured error type", async () => { + globalThis.fetch = (async () => Response.json( + { error: { type: "insufficient_quota", message: "generic" } }, + { status: 429 }, + )) as unknown as typeof fetch; + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + await loggedCombo(config, { model: "", provider: "" }); + const line = warn.mock.calls.map(call => String(call[0])).find(text => text.includes("primary/model-primary failed with")); + expect(line).toMatch(/failed with 429 after \d+ms: billing_exhausted$/); + expect(line).not.toContain("generic"); } finally { warn.mockRestore(); } }); @@ -396,7 +411,8 @@ describe("combo exhaustion reports the primary's quota refusal", () => { try { await loggedCombo(config, { model: "", provider: "" }); const line = warn.mock.calls.map(call => String(call[0])).find(text => text.includes("primary/model-primary failed with")); - expect(line).toMatch(/failed with 502 after \d+ms$/); + expect(line).toMatch(/failed with 502 after \d+ms: upstream_failed$/); + expect(line).not.toContain("session=abc123"); } finally { warn.mockRestore(); } diff --git a/tests/responses/responses-fetch-helpers-boundary.test.ts b/tests/responses/responses-fetch-helpers-boundary.test.ts index 32a4c232426..713ca37346e 100644 --- a/tests/responses/responses-fetch-helpers-boundary.test.ts +++ b/tests/responses/responses-fetch-helpers-boundary.test.ts @@ -201,6 +201,8 @@ describe("Responses fetch-helper import boundary", () => { // Import-free plugin rewrite slot (src/plugins/upstream-hooks.ts). "../../plugins/upstream-hooks", "../../providers/request-pacing", + // Turn-state handle redemption at the send (src/server/turn-state-handles.ts); node: built-ins only. + "../turn-state-handles", // Opt-in request-body codec at the final send (#7247); runtime imports are node: built-ins only. "./request-compression", "./ws-upstream", diff --git a/tests/responses/ws-endpoint.test.ts b/tests/responses/ws-endpoint.test.ts index bf90559bd92..88aa3ddc183 100644 --- a/tests/responses/ws-endpoint.test.ts +++ b/tests/responses/ws-endpoint.test.ts @@ -1,5 +1,6 @@ import { readFileSync } from "node:fs"; import { describe, expect, test } from "bun:test"; +import { resolveTurnStateHandle } from "../../src/server/turn-state-handles"; import { buildWarmupCompletionFrames, pumpResponsesSseToWebSocket, @@ -323,15 +324,15 @@ describe("WS endpoint re-framer (120/132)", () => { "x-codex-secondary-primary-reset-at": "1781928000", "x-codex-secondary-limit-name": "Secondary", })); + // Without a send binding the turn-state token is dropped; unknown families and limit labels are too. expect(outbound).toEqual({ "retry-after": "2", - "x-codex-turn-state": "state", - "x-codex-primary-used-percent": "100.0", + "x-codex-primary-used-percent": "100", "x-codex-primary-window-minutes": "15", - "x-codex-secondary-primary-reset-at": "1781928000", - "x-codex-secondary-limit-name": "Secondary", "x-ratelimit-remaining": "4", }); + const bound = safeResponseHeaders(new Headers({ "x-codex-turn-state": "state" }), { turnStateBinding: "send-a" }); + expect(resolveTurnStateHandle(bound["x-codex-turn-state"]!, "send-a")).toEqual({ value: "state" }); }); test("bounded sniffing replays the full body without dropping bytes", async () => { diff --git a/tests/responses/ws-pre-output-refusal.test.ts b/tests/responses/ws-pre-output-refusal.test.ts index 2ce9fd2bdac..65a849f3baa 100644 --- a/tests/responses/ws-pre-output-refusal.test.ts +++ b/tests/responses/ws-pre-output-refusal.test.ts @@ -223,7 +223,7 @@ describe("everything else keeps today's settle", () => { ["first", [] as unknown[]], ["after the held preamble", [CREATED]], ])("a refusal whose metadata cannot be projected is delivered in the body when it arrives %s", async (_name, before) => { - const oversized = { ...OVERLOADED, headers: { "x-request-id": "a".repeat(5_000) } }; + const oversized = { ...OVERLOADED, headers: { "x-codex-turn-state": "a".repeat(5_000) } }; expect(await committed(await exchange(opened(...before, oversized)))).toContain("server_is_overloaded"); }); diff --git a/tests/responses/ws-upstream.test.ts b/tests/responses/ws-upstream.test.ts index 1522e4bb192..076090f87bf 100644 --- a/tests/responses/ws-upstream.test.ts +++ b/tests/responses/ws-upstream.test.ts @@ -29,11 +29,13 @@ import { CODEX_WS_LIVENESS_PING_INTERVAL_MS, shouldUseCodexWsUpstream as rawShouldUseCodexWsUpstream, } from "../../src/server/responses/ws-upstream"; -import type { OcxProviderConfig } from "../../src/types"; -import type { OcxConfig } from "../../src/types"; +import type { OcxConfig, OcxProviderConfig } from "../../src/types"; +import { resolveTurnStateHandle, TURN_STATE_BINDING_INIT } from "../../src/server/turn-state-handles"; import { BOUNDED_WS_RUNTIME, codexWsUpstreamFetch, shouldUseCodexWsUpstream, streamingInit } from "../helpers/ws-upstream-fixtures"; import { acquireOwnedSpendHome } from "../helpers/owned-spend-home"; import { installCompactionRoutingAclFixture as installRoutingAclFixture } from "../helpers/compaction-routing-fixtures"; +// Quota headers under families this proxy does not know: ten per family, all of them dropped. +const quotaFamilyHeaders = (count: number) => Object.fromEntries(Array.from({ length: count }, (_, i) => [`x-codex-family-${Math.floor(i / 10)}-${["primary-used-percent", "primary-window-minutes", "primary-reset-at", "secondary-used-percent", "secondary-window-minutes", "secondary-reset-at", "tertiary-used-percent", "tertiary-window-minutes", "tertiary-reset-at", "limit-name"][i % 10]}`, "1"])); installRoutingAclFixture(); const CODEX_URL = "https://chatgpt.com/backend-api/codex/responses"; @@ -757,14 +759,16 @@ describe("codexWsUpstreamFetch", () => { ws.emit("message", { data: JSON.stringify({ type: "response.created", response: { id: "r1" } }) }); ws.emit("message", { data: JSON.stringify({ type: "response.completed", response: { id: "r1", status: "completed" } }) }); }); - const response = await codexWsUpstreamFetch(CODEX_URL, streamingInit(), (() => { + const response = await codexWsUpstreamFetch(CODEX_URL, { ...streamingInit(), [TURN_STATE_BINDING_INIT]: "send-a" } as RequestInit, (() => { throw new Error("fallback must not run"); }) as unknown as typeof fetch); expect(response.headers.get("x-codex-primary-used-percent")).toBe("31"); expect(response.headers.get("x-codex-primary-window-minutes")).toBe("10080"); expect(response.headers.get("x-codex-credits-balance")).toBe("12.5"); - expect(response.headers.get("x-models-etag")).toBe("catalog-v2"); - expect(response.headers.get("x-codex-turn-state")).toBe("turn-state"); + expect(response.headers.has("x-models-etag")).toBe(false); + // The handle is bound to the send that received it, and redeems only under that binding. + expect(resolveTurnStateHandle(response.headers.get("x-codex-turn-state")!, "send-a")).toEqual({ value: "turn-state" }); + expect(resolveTurnStateHandle(response.headers.get("x-codex-turn-state")!, "send-b")).toEqual({ dropped: "mismatch" }); expect(response.headers.has("authorization")).toBe(false); expect(response.headers.has("set-cookie")).toBe(false); const text = await response.text(); @@ -921,13 +925,13 @@ describe("codexWsUpstreamFetch", () => { expect(response.status).toBe(429); expect(response.headers.get("content-type")).toBe("application/json"); expect(response.headers.get("cache-control")).toBe("no-store"); - expect(response.headers.get("x-codex-primary-used-percent")).toBe("100.0"); + expect(response.headers.get("x-codex-primary-used-percent")).toBe("100"); expect(response.headers.get("x-codex-primary-window-minutes")).toBe("15"); expect(response.headers.get("x-codex-primary-reset-at")).toBe("1800000000"); expect(response.headers.get("x-codex-credits-has-credits")).toBe("true"); expect(response.headers.get("retry-after")).toBe("60"); - expect(response.headers.get("x-request-id")).toBe("fixture-request"); - expect(response.headers.get("x-codex-extra-secondary-used-percent")).toBe("25"); + expect(response.headers.has("x-request-id")).toBe(false); + expect(response.headers.has("x-codex-extra-secondary-used-percent")).toBe(false); expect(response.headers.get("x-ratelimit-remaining-requests")).toBe("0"); expect(isCodexWsUpstreamResponse(response)).toBe(false); expect(isCodexWsQuotaObservedResponse(response)).toBe(false); @@ -1005,30 +1009,25 @@ describe("codexWsUpstreamFetch", () => { expect(response.headers.has("x-codex-primary-reset-at")).toBe(false); expect(response.headers.get("x-codex-secondary-used-percent")).toBe("40"); expect(response.headers.get("x-codex-secondary-reset-at")).toBe("1900000000"); - expect(response.headers.get("x-models-etag")).toBe("prelude-catalog"); + expect(response.headers.has("x-models-etag")).toBe(false); expect(observations).toEqual(["30"]); expect(isCodexWsQuotaObservedResponse(response)).toBe(false); expect(await response.json()).toEqual({ error: refusal.error }); }); - const boundedHeaders = (count: number, value = "1") => - Object.fromEntries(Array.from({ length: count }, (_, i) => [`x-ratelimit-fixture-${i}`, value])); const quotaFamilies = (count: number) => Object.fromEntries( Array.from({ length: count }, (_, i) => [`x-codex-family-${i}-primary-used-percent`, "1"])); test.each([ - ["value", { "x-models-etag": "x".repeat(4096) }, true], - ["value overflow", { "x-models-etag": "x".repeat(4097) }, false], - ["UTF-8 value", { "x-models-etag": "é".repeat(2048) }, true], - ["UTF-8 overflow", { "x-models-etag": "é".repeat(2049) }, false], - ["header count", boundedHeaders(128), true], ["header count overflow", boundedHeaders(129), false], - ["families", quotaFamilies(16), true], ["family overflow", quotaFamilies(17), false], - ["total bytes", boundedHeaders(8, "x".repeat(3990)), true], - ["total byte overflow", boundedHeaders(8, "x".repeat(4096)), false], + ["value", { "x-codex-turn-state": "x".repeat(4096) }, true], + ["value overflow", { "x-codex-turn-state": "x".repeat(4097) }, false], + ["UTF-8 overflow", { "x-codex-turn-state": "é".repeat(2049) }, false], + ["unknown families are dropped", { ...quotaFamilyHeaders(129), ...quotaFamilies(17) }, true], ] as Array<[string, Record, boolean]>)("enforces metadata budget: %s", async (_name, headers, accepted) => { const response = await receive({ ...refusal, headers }); if (accepted) { expect(response.status).toBe(429); - for (const [name, value] of Object.entries(headers)) expect(response.headers.get(name)).toBe(value); + // Without a send binding the turn-state token is dropped; unknown quota families never pass. + for (const name of Object.keys(headers)) expect(response.headers.get(name)).toBeNull(); expect(await response.json()).toEqual({ error: refusal.error }); } else { // The overflow lands before any response event: an honest 502, never a 200 whose @@ -1043,9 +1042,9 @@ describe("codexWsUpstreamFetch", () => { }); test("bounds the cumulative prelude and rejection metadata even when updates replace values", async () => { - const response = await receive({ ...refusal, headers: boundedHeaders(5, "x".repeat(4096)) }, [ - { type: "codex.response.metadata", headers: boundedHeaders(4, "y".repeat(4096)) }, - ]); + // Each frame replaces the same allowlisted value; the prelude still counts every frame's bytes. + const response = await receive({ ...refusal, headers: { "x-codex-turn-state": "x".repeat(4096) } }, + Array.from({ length: 8 }, () => ({ type: "codex.response.metadata", headers: { "x-codex-turn-state": "y".repeat(4096) } }))); expect(response.status).toBe(502); expect(((await response.json()) as { error: { message: string } }).error.message).toContain("metadata"); }); @@ -1657,12 +1656,12 @@ describe("codexWsUpstreamFetch", () => { }); describe("native WS metadata boundaries", () => { - test("tertiary and label-only metadata families share the native family budget", () => { + test("unknown tertiary and label-only metadata families are dropped without spending the budget", () => { for (const suffix of ["tertiary-used-percent", "limit-name"]) { const owner = new CodexWsMetadata(); owner.commit(); const headers = Object.fromEntries(Array.from({ length: 17 }, (_, i) => [`x-codex-family-${i}-${suffix}`, "1"])); - expect(() => owner.consume({ type: "codex.response.metadata", headers }, 2000)).toThrow("header budget"); + expect(owner.consume({ type: "codex.response.metadata", headers }, 2000)).toBe('{"type":"codex.response.metadata","headers":{}}'); expect([...owner.snapshot()]).toHaveLength(0); } }); @@ -1711,8 +1710,8 @@ describe("native WS metadata boundaries", () => { test("metadata value and cumulative prelude bounds cannot be bypassed by small frames", () => { const owner = new CodexWsMetadata(); - owner.consume({ type: "codex.response.metadata", headers: { "x-models-etag": "x".repeat(CODEX_WS_METADATA_MAX_VALUE_BYTES) } }, CODEX_WS_METADATA_MAX_VALUE_BYTES); - expect(() => owner.consume({ type: "codex.response.metadata", headers: { "x-models-etag": "x".repeat(CODEX_WS_METADATA_MAX_VALUE_BYTES + 1) } }, CODEX_WS_METADATA_MAX_VALUE_BYTES + 1)).toThrow("value"); + owner.consume({ type: "codex.response.metadata", headers: { "x-codex-turn-state": "x".repeat(CODEX_WS_METADATA_MAX_VALUE_BYTES) } }, CODEX_WS_METADATA_MAX_VALUE_BYTES); + expect(() => owner.consume({ type: "codex.response.metadata", headers: { "x-codex-turn-state": "x".repeat(CODEX_WS_METADATA_MAX_VALUE_BYTES + 1) } }, CODEX_WS_METADATA_MAX_VALUE_BYTES + 1)).toThrow("value"); const prelude = new CodexWsMetadata(); prelude.consume({ type: "codex.rate_limits" }, CODEX_WS_METADATA_MAX_BYTES); expect(() => prelude.consume({ type: "codex.rate_limits" }, 1)).toThrow("prelude"); @@ -1723,7 +1722,7 @@ describe("native WS metadata boundaries", () => { const owner = new CodexWsMetadata(() => { calls++; }); owner.commit(); const text = owner.consume({ type: "codex.response.metadata", headers: { "x-models-etag": "good", authorization: "secret", "set-cookie": "secret", "x-codex-turn-state": "bad\r\nvalue" } }, 100); - expect(text).toBe('{"type":"codex.response.metadata","headers":{"x-models-etag":"good"}}'); + expect(text).toBe('{"type":"codex.response.metadata","headers":{}}'); owner.finish(); const endedCalls = calls; owner.consume({ type: "codex.rate_limits", rate_limits: { primary: { used_percent: 40 } } }, 100); @@ -1731,21 +1730,16 @@ describe("native WS metadata boundaries", () => { expect(owner.snapshot().has("x-codex-primary-used-percent")).toBe(false); }); - test("metadata family and header-count caps reject only the overflowing addition", () => { + test("only known quota families are relayed, so unknown family names never reach the budget", () => { const families = new CodexWsMetadata(); families.commit(); - for (let i = 0; i < 16; i++) { + for (let i = 0; i < 17; i++) { families.consume({ type: "codex.rate_limits", metered_limit_name: `codex-family-${i}`, rate_limits: { primary: { used_percent: i } } }, 100); } - expect(families.snapshot().get("x-codex-family-15-primary-used-percent")).toBe("15"); - expect(() => families.consume({ type: "codex.rate_limits", metered_limit_name: "codex-family-16", rate_limits: { primary: { used_percent: 16 } } }, 100)).toThrow("header budget"); - expect(families.snapshot().has("x-codex-family-16-primary-used-percent")).toBe(false); - const headers = new CodexWsMetadata(); - headers.commit(); - headers.consume({ type: "codex.response.metadata", headers: Object.fromEntries(Array.from({ length: 128 }, (_, i) => [`x-ratelimit-fixture-${i}`, "1"])) }, 4000); - expect([...headers.snapshot()]).toHaveLength(128); - expect(() => headers.consume({ type: "codex.response.metadata", headers: { "x-ratelimit-extra": "1" } }, 100)).toThrow("header budget"); - expect([...headers.snapshot()]).toHaveLength(128); + families.consume({ type: "codex.response.metadata", headers: quotaFamilyHeaders(129) }, 4000); + expect([...families.snapshot()]).toHaveLength(0); + families.consume({ type: "codex.rate_limits", metered_limit_name: "codex_bengalfox", rate_limits: { primary: { used_percent: 3 } } }, 100); + expect([...families.snapshot()]).toEqual([["x-codex-bengalfox-primary-used-percent", "3"]]); }); }); diff --git a/tests/routing/fastwire-observability.test.ts b/tests/routing/fastwire-observability.test.ts index 587f98242fd..c4d698c7cd0 100644 --- a/tests/routing/fastwire-observability.test.ts +++ b/tests/routing/fastwire-observability.test.ts @@ -154,8 +154,9 @@ describe("FastWire attempt outcomes", () => { canonical: "priority", fastOutcome: "applied", confirmation: "confirmed", - responseServiceTier: "performance", }); + // The configured wire value confirms Fast, but only closed tier members are recorded. + expect(confirmed.outcome.responseServiceTier).toBeUndefined(); expect(serviceTierContextFromOutcome(confirmed.outcome)).toEqual({ responseServiceTier: "priority", }); @@ -368,10 +369,10 @@ describe("FastWire logging and persistence", () => { expect(normalized.callerServiceTier).toBe(`priority${"y".repeat(56)}`); }); - test("upstream service tiers are sanitized before live and durable logging", () => { + test("upstream service tiers outside the closed set are omitted from live and durable logging", () => { const secret = ["sk", "proj", "upstream", "A".repeat(40)].join("-"); const rawTier = ` authorization: Bearer ${secret}\n\u0085\u2028\u2029${"x".repeat(80)} `; - const expected = sanitizeLogMetadataString(rawTier)!; + const expected = undefined; const tracker = createAdapterTierMetadata( observation({ capability: undefined, eligibility: "unclassified" }), { kind: "forward-caller" }, diff --git a/tests/routing/routing-policy-dispatch-scope.test.ts b/tests/routing/routing-policy-dispatch-scope.test.ts index e96f0a36b40..f956b45c395 100644 --- a/tests/routing/routing-policy-dispatch-scope.test.ts +++ b/tests/routing/routing-policy-dispatch-scope.test.ts @@ -314,7 +314,7 @@ describe("policy scope through real request preparation", () => { expect(rows).toHaveLength(1); expect(rows[0]).toMatchObject({ provider: "openai-apikey", model: "gpt-5.6-sol-pro", usage, totalTokens: 20, - upstreamError: "fixture busy", status: 429, spend: { sends: 1, settled: 1, unresolved: 0 }, + upstreamCondition: "rate_limited", status: 429, spend: { sends: 1, settled: 1, unresolved: 0 }, }); expect(rows[0]?.attempts).toHaveLength(1); expect(rows[0]?.attempts?.[0]).toMatchObject({ provider: "openai-apikey", model: "gpt-5.6-sol", usage, status: 429, sendCount: 1 }); @@ -383,6 +383,7 @@ describe("policy scope through real request preparation", () => { }); expect(rows[0]?.attempts?.map(attempt => attempt.provider)).toEqual(expected); expect(rows[0]?.attempts?.every(attempt => attempt.sendCount === 1 && attempt.usage !== undefined)).toBe(true); - expect(rows[0]?.upstreamError).toBe(scenario === "skip-then-success" ? undefined : `busy-${expected.at(-1)}`); + expect(rows[0]?.upstreamError).toBeUndefined(); + expect(JSON.stringify(rows[0])).not.toContain("busy-"); }); }); diff --git a/tests/server/client-retry-after-sites.test.ts b/tests/server/client-retry-after-sites.test.ts new file mode 100644 index 00000000000..eed5adf4cea --- /dev/null +++ b/tests/server/client-retry-after-sites.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, test } from "bun:test"; +import { formatErrorResponse } from "../../src/bridge"; +import { formatUsageLimitReachedResponse } from "../../src/bridge/errors"; +import { comboUnavailableResponse } from "../../src/server/responses/core-errors"; +import { fallbackRefusedResponse, type FallbackEvent } from "../../src/routing/fallback-policy"; +import { formatPassthroughUpstreamError } from "../../src/server/responses/passthrough-error"; +import { bufferCompactResponse } from "../../src/server/responses/compact"; +import { safeResponseHeaders } from "../../src/server/safe-response-headers"; + +// All digits, so a Retry-After parser accepts it as a delay in seconds. +const NUMERIC_KEY = "73915028461739205817"; +const now = Date.parse("2026-11-02T00:00:00Z"); + +const event: FallbackEvent = { + at: new Date(now).toISOString(), site: "routing-profile", route: "profile", kind: "provider", from: "a", to: "b", + trigger: "rate_limited", outcome: "refused", scope: "global", +} as FallbackEvent; + +describe("client Retry-After is regenerated at every boundary", () => { + test("WebSocket response metadata", () => { + expect(safeResponseHeaders(new Headers({ "retry-after": NUMERIC_KEY }))["retry-after"]).toBe("691200"); + expect(safeResponseHeaders(new Headers({ "retry-after": "12" }))["retry-after"]).toBe("12"); + expect(safeResponseHeaders(new Headers({ "retry-after": "must-not-echo" }))["retry-after"]).toBeUndefined(); + }); + + test("fallback refusal", () => { + expect(fallbackRefusedResponse(event, { failureStatus: 429, retryAfter: NUMERIC_KEY }).headers.get("retry-after")).toBe("691200"); + expect(fallbackRefusedResponse(event, { failureStatus: 429, retryAfter: "30" }).headers.get("retry-after")).toBe("30"); + expect(fallbackRefusedResponse(event, { failureStatus: 429, retryAfter: "must-not-echo" }).headers.get("retry-after")).toBeNull(); + }); + + test("Responses error re-wrap", () => { + const body = JSON.stringify({ error: { message: "slow down", type: "rate_limit_error" } }); + for (const raw of [NUMERIC_KEY, " 691201 ", "Mon, 02 Nov 2026 00:00:30 GMT"]) { + const response = formatPassthroughUpstreamError(429, body, { headers: new Headers({ "retry-after": raw }), now }); + const value = response.headers.get("retry-after"); + expect(value).toMatch(/^\d+$/); + expect(value).not.toBe(raw); + expect(Number(value)).toBeLessThanOrEqual(691200); + } + const empty = formatPassthroughUpstreamError(429, "", { headers: new Headers({ "retry-after": NUMERIC_KEY }), now }); + expect(empty.headers.get("retry-after")).toBe("691200"); + }); + + test("translated error response", () => { + expect(formatErrorResponse(429, "rate_limit_error", "slow down", { retryAfter: NUMERIC_KEY }).headers.get("retry-after")).toBe("691200"); + expect(formatErrorResponse(429, "rate_limit_error", "slow down", { retryAfter: "must-not-echo" }).headers.get("retry-after")).toBeNull(); + }); + + test("usage-limit and combo-unavailable refusals", () => { + expect(formatUsageLimitReachedResponse("spent", null, 900_000).headers.get("retry-after")).toBe("691200"); + expect(formatUsageLimitReachedResponse("spent", null, 84_692).headers.get("retry-after")).toBe("84692"); + expect(formatUsageLimitReachedResponse("spent", null, null).headers.get("retry-after")).toBeNull(); + expect(comboUnavailableResponse("none", { retryAfter: "900000" }).headers.get("retry-after")).toBe("691200"); + expect(comboUnavailableResponse("none", { retryAfter: NUMERIC_KEY }).headers.get("retry-after")).toBe("691200"); + expect(comboUnavailableResponse("none", { retryAfter: "must-not-echo" }).headers.get("retry-after")).toBeNull(); + expect(comboUnavailableResponse("none", { retryAfter: "60" }).headers.get("retry-after")).toBe("60"); + }); + + test("compact response buffering", async () => { + const upstream = new Response(JSON.stringify({ error: { message: "slow down" } }), { + status: 429, headers: { "content-type": "application/json", "retry-after": NUMERIC_KEY }, + }); + const response = await bufferCompactResponse(upstream, new AbortController().signal); + expect(response.status).toBe(429); + expect(response.headers.get("retry-after")).toBe("691200"); + }); +}); diff --git a/tests/server/context-history.test.ts b/tests/server/context-history.test.ts index 5acca68f6e5..cdc90ffe94c 100644 --- a/tests/server/context-history.test.ts +++ b/tests/server/context-history.test.ts @@ -130,6 +130,15 @@ describe("context relay contract",()=>{ const r=await handleContextHistory(req, config, logContext(), "alpha/notes/v2/write_file", undefined, keyAdmission); expect(r.status).toBe(403);expect(await r.text()).toBe('{"error":"feature denied"}');expect(r.headers.get("retry-after")).toBe("7");expect(calls).toBe(1); }); + test("regenerates retry advice instead of relaying upstream bytes",async()=>{ + const numericKey="73915028461739205817"; + for(const [raw,expected] of [[numericKey,"691200"],["must-not-echo",null]] as const){ + setFetch(async()=>new Response('{"error":"slow down"}',{status:429,headers:{"retry-after":raw}})); + const req=new Request("http://localhost/v1/alpha/notes/v2/write_file",{method:"POST",headers:{authorization:"Bearer test","content-type":"application/json"},body:JSON.stringify({context:{session_id:"s"}})}); + const r=await handleContextHistory(req, config, logContext(), "alpha/notes/v2/write_file", undefined, keyAdmission); + expect(r.status).toBe(429);expect(r.headers.get("retry-after")).toBe(expected); + } + }); test("rejects malformed context before any account selection",async()=>{ const req=new Request("http://localhost/v1/alpha/notes/v2/write_file",{method:"POST",headers:{authorization:"Bearer test","content-type":"application/json"},body:"{}"}); expect((await handleContextHistory(req, config, logContext(), "alpha/notes/v2/write_file", undefined, keyAdmission)).status).toBe(400);expect(selection).toBeUndefined(); diff --git a/tests/server/response-model-identity.test.ts b/tests/server/response-model-identity.test.ts index f32db20c316..744e1837f0d 100644 --- a/tests/server/response-model-identity.test.ts +++ b/tests/server/response-model-identity.test.ts @@ -5,6 +5,11 @@ import { } from "../../src/server/request-log"; import type { OcxConfig, OcxProviderConfig } from "../../src/types"; import { acquireOwnedSpendHome } from "../helpers/owned-spend-home"; +import { fetchProviderModels } from "../../src/codex/catalog/provider-models"; +import { clearModelCache, getStaleCached } from "../../src/codex/model-cache"; +import { stubbedProviderFetch } from "../helpers/catalog-provider-fetch"; +import { materializeModelPreset } from "../../src/providers/model-presets"; +import { modelIdentityLogFields } from "../../src/usage/log"; const originalFetch = globalThis.fetch; let releaseSpendHome: (() => void) | undefined; @@ -37,6 +42,168 @@ function routedConfig( } as OcxConfig; } +describe("a passthrough openai-model header is kept only as a known model id", () => { + const PROVIDER_KEY = "zq7Vb2LmN4pX9tR1sK8wD3fH6jY0cA5e"; + test.each([ + [PROVIDER_KEY, undefined], + ["gpt-5.6-sol", "gpt-5.6-sol"], + ])("upstream reports %s", async (reported, expected) => { + releaseSpendHome = acquireOwnedSpendHome(); + // No body model, so only the header can set the served model. + globalThis.fetch = (async () => new Response(JSON.stringify(responseSnapshot(undefined)), { + status: 200, + headers: { "content-type": "application/json", "openai-model": reported, "x-codex-safety-buffering-faster-model": reported }, + })) as unknown as typeof fetch; + const logCtx: RequestLogContext = { model: "", provider: "" }; + const response = await handleResponses(new Request("http://localhost/v1/responses", { + method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "fixture-openai/gpt-5.5", input: "hi", stream: false }), + }), routedConfig("fixture-openai", "openai-responses", "gpt-5.5"), logCtx, {}); + const body = await response.text(); + // Non-vacuous: the passthrough answered and its row context was filled in. + expect(response.status).toBe(200); + expect(logCtx.provider).toBe("fixture-openai"); + expect(response.headers.get("openai-model") ?? undefined).toBe(expected); + expect(response.headers.get("x-codex-safety-buffering-faster-model") ?? undefined).toBe(expected); + expect(logCtx.servedModel).toBe(expected); + expect(JSON.stringify([...response.headers, body, logCtx.servedModel, logCtx.resolvedModel])).not.toContain(PROVIDER_KEY); + }); + + // Every alternate passthrough branch builds its headers through the same filter: redirects, error + // statuses, and a JSON upstream answered as JSON or re-framed as SSE. + const ALTERNATES: Array<[string, number, boolean, Record, string]> = [ + ...[301, 302, 307, 308].map(status => [`redirect ${status}`, status, false, { location: "https://provider.example.test/moved" }, "location"] as [string, number, boolean, Record, string]), + ["error 429", 429, false, { "content-type": "application/json" }, "content-type"], + ["error 500", 500, false, { "content-type": "application/json" }, "content-type"], + ["JSON answered as JSON", 200, false, { "content-type": "application/json" }, "content-type"], + ["JSON re-framed as SSE", 200, true, { "content-type": "application/json" }, "content-type"], + ]; + test.each(ALTERNATES)("%s never relays an unknown model header", async (_name, status, stream, extra, present) => { + releaseSpendHome = acquireOwnedSpendHome(); + const redirect = status >= 300 && status < 400; + const body = redirect ? null : status >= 400 + ? JSON.stringify({ error: { type: "server_error", message: "fixture failure" } }) + : JSON.stringify(responseSnapshot(undefined)); + globalThis.fetch = (async () => new Response(body, { + status, + headers: { ...extra, "openai-model": PROVIDER_KEY, "x-codex-safety-buffering-faster-model": PROVIDER_KEY }, + })) as unknown as typeof fetch; + const logCtx: RequestLogContext = { model: "", provider: "" }; + const response = await handleResponses(new Request("http://localhost/v1/responses", { + method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "fixture-openai/gpt-5.5", input: "hi", stream }), + }), routedConfig("fixture-openai", "openai-responses", "gpt-5.5"), logCtx, {}); + const text = await response.text(); + // Non-vacuous: the response took this branch and kept its ordinary headers. + expect(response.status).toBe(status); + expect(response.headers.has(present)).toBe(true); + expect(response.headers.has("openai-model")).toBe(false); + expect(response.headers.has("x-codex-safety-buffering-faster-model")).toBe(false); + expect(JSON.stringify([...response.headers, text, logCtx.servedModel, logCtx.resolvedModel])).not.toContain(PROVIDER_KEY); + }); + + // A provider-owned hint naming a model the user configured for this provider survives as the + // proxy's copy; an unconfigured or prefixless value is still dropped. + test.each([ + ["a configured model", "configured-hint-model", "configured-hint-model"], + ["an unconfigured model", "unconfigured-hint-model", undefined], + ["a prefixless key", PROVIDER_KEY, undefined], + ])("the faster-model hint naming %s", async (_name, hint, expected) => { + releaseSpendHome = acquireOwnedSpendHome(); + globalThis.fetch = (async () => new Response(JSON.stringify(responseSnapshot(undefined)), { + status: 200, + headers: { "content-type": "application/json", "x-codex-safety-buffering-enabled": "true", "x-codex-safety-buffering-faster-model": hint }, + })) as unknown as typeof fetch; + const config = routedConfig("fixture-openai", "openai-responses", "gpt-5.5"); + config.providers["fixture-openai"]!.models = ["gpt-5.5", "configured-hint-model"]; + const response = await handleResponses(new Request("http://localhost/v1/responses", { + method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "fixture-openai/gpt-5.5", input: "hi", stream: false }), + }), config, { model: "", provider: "" }, {}); + const text = await response.text(); + // Non-vacuous: the passthrough answered and relayed its other safety-buffering hint. + expect(response.status).toBe(200); + expect(response.headers.get("x-codex-safety-buffering-enabled")).toBe("true"); + expect(response.headers.get("x-codex-safety-buffering-faster-model") ?? undefined).toBe(expected); + expect(JSON.stringify([...response.headers, text])).not.toContain(PROVIDER_KEY); + }); + + // Live discovery is the upstream's own answer, so a model id it lists is not trusted: an upstream + // that seeds a prefixless key into /models still cannot relay it later as a model header or row. + test.each([[302], [200]])("a model id known only from live discovery is dropped (%d)", async status => { + releaseSpendHome = acquireOwnedSpendHome(); + clearModelCache("fixture-openai"); + try { + globalThis.fetch = (async (input: RequestInfo | URL) => { + const url = input instanceof Request ? input.url : String(input); + if (url.endsWith("/models")) { + return Response.json({ object: "list", data: [{ id: "gpt-5.5", object: "model" }, { id: PROVIDER_KEY, object: "model" }] }); + } + const headers = { "content-type": "application/json", "openai-model": PROVIDER_KEY, "x-codex-safety-buffering-faster-model": PROVIDER_KEY }; + return status === 302 + ? new Response(null, { status, headers: { ...headers, location: "https://provider.example.test/moved" } }) + : new Response(JSON.stringify(responseSnapshot(PROVIDER_KEY)), { status, headers }); + }) as unknown as typeof fetch; + const config = routedConfig("fixture-openai", "openai-responses", "gpt-5.5"); + const discovered = await fetchProviderModels("fixture-openai", { ...config.providers["fixture-openai"]!, fetch: stubbedProviderFetch } as OcxProviderConfig); + // Non-vacuous: discovery really cached the key as a model of this provider. + expect(discovered.map(model => model.id)).toContain(PROVIDER_KEY); + expect((getStaleCached("fixture-openai") ?? []).map(model => model.id)).toContain(PROVIDER_KEY); + const logCtx: RequestLogContext = { model: "", provider: "" }; + const response = await handleResponses(new Request("http://localhost/v1/responses", { + method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "fixture-openai/gpt-5.5", input: "hi", stream: false }), + }), config, logCtx, {}); + await response.text(); + expect(response.status).toBe(status); + expect(logCtx.provider).toBe("fixture-openai"); + expect(response.headers.has("openai-model")).toBe(false); + expect(response.headers.has("x-codex-safety-buffering-faster-model")).toBe(false); + expect(logCtx.servedModel).toBeUndefined(); + expect(JSON.stringify([...response.headers, logCtx.servedModel, logCtx.resolvedModel])).not.toContain(PROVIDER_KEY); + } finally { + clearModelCache("fixture-openai"); + } + }); + + // A model preset fills selectedModels from the discovered catalog, so a preset-selected id is not + // trusted either; an explicit provider.models entry still is. + test.each([ + ["a preset-selected upstream id", `openai/gpt-5.5-${PROVIDER_KEY}`, false], + ["an explicit provider.models entry", "openai/gpt-5.5-configured", true], + ])("a model header naming %s", async (_name, reported, relayed) => { + releaseSpendHome = acquireOwnedSpendHome(); + globalThis.fetch = (async () => new Response(JSON.stringify(responseSnapshot(undefined)), { + status: 200, + headers: { "content-type": "application/json", "x-codex-safety-buffering-enabled": "true", "openai-model": reported, "x-codex-safety-buffering-faster-model": reported }, + })) as unknown as typeof fetch; + const config = routedConfig("fixture-openai", "openai-responses", "openai/gpt-5.5"); + const provider = config.providers["fixture-openai"]!; + // The ids a preset would persist after evaluating its rules against a discovered catalog. + provider.selectedModels = materializeModelPreset("openrouter", ["openai/gpt-5.5", `openai/gpt-5.5-${PROVIDER_KEY}`, "unrelated/model"]); + if (relayed) provider.models = ["openai/gpt-5.5", reported]; + // Non-vacuous: the preset really persisted the upstream-shaped id as a selected model. + expect(provider.selectedModels).toEqual(["openai/gpt-5.5", `openai/gpt-5.5-${PROVIDER_KEY}`]); + const logCtx: RequestLogContext = { model: "", provider: "" }; + const response = await handleResponses(new Request("http://localhost/v1/responses", { + method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "fixture-openai/openai/gpt-5.5", input: "hi", stream: false }), + }), config, logCtx, {}); + const text = await response.text(); + // Non-vacuous: the passthrough answered and relayed its other safety-buffering hint. + expect(response.status).toBe(200); + expect(logCtx.provider).toBe("fixture-openai"); + expect(response.headers.get("x-codex-safety-buffering-enabled")).toBe("true"); + const expected = relayed ? reported : undefined; + expect(response.headers.get("openai-model") ?? undefined).toBe(expected); + expect(response.headers.get("x-codex-safety-buffering-faster-model") ?? undefined).toBe(expected); + expect(logCtx.servedModel).toBe(expected); + // The recorded row trusts only the route's own ids, so even the configured hint is not stored. + expect(modelIdentityLogFields(logCtx).servedModel).toBeUndefined(); + expect(JSON.stringify([...response.headers, text, logCtx.servedModel, logCtx.resolvedModel, modelIdentityLogFields(logCtx)])).not.toContain(PROVIDER_KEY); + }); +}); + function responseSnapshot(model: unknown): Record { return { id: "resp_fixture", diff --git a/tests/server/safe-response-headers.test.ts b/tests/server/safe-response-headers.test.ts new file mode 100644 index 00000000000..f953cf48291 --- /dev/null +++ b/tests/server/safe-response-headers.test.ts @@ -0,0 +1,217 @@ +import { describe, expect, test } from "bun:test"; +import { CodexWsMetadata } from "../../src/server/responses/codex-ws-metadata"; +import { isSafeResponseHeader, normalizeSafeResponseHeader, safeResponseHeaders } from "../../src/server/safe-response-headers"; +import { resolveTurnStateHandle } from "../../src/server/turn-state-handles"; +import { buildWsErrorFrame } from "../../src/server/ws-bridge"; + +// A provider key with no recognizable prefix, so pattern-based redaction cannot spot it. +const PROVIDER_KEY = "zq7Vb2LmN4pX9tR1sK8wD3fH6jY0cA5e"; +const NUMERIC_KEY = "73915028461739205817"; + +describe("response metadata headers are allowlisted by name and rebuilt by contract", () => { + test("unlisted names never pass, whatever their prefix", () => { + const out = safeResponseHeaders(new Headers({ + "x-ratelimit-secret": PROVIDER_KEY, "x-ratelimit-fixture-1": "1", "x-codex-private-token": PROVIDER_KEY, + "x-codex-promo-message": "Upgrade now " + PROVIDER_KEY, "set-cookie": PROVIDER_KEY, + })); + expect(out).toEqual({}); + expect(isSafeResponseHeader("x-ratelimit-secret")).toBe(false); + expect(isSafeResponseHeader("x-codex-promo-message")).toBe(false); + }); + + test("numeric values are rebuilt; anything else is dropped", () => { + const out = safeResponseHeaders(new Headers({ + "x-ratelimit-remaining-requests": PROVIDER_KEY, "x-ratelimit-limit-tokens": "0400", "x-ratelimit-remaining-tokens": "1e3", + "x-codex-primary-used-percent": "100.0", "x-codex-primary-window-minutes": PROVIDER_KEY, + "x-codex-primary-reset-at": NUMERIC_KEY, "x-codex-credits-balance": "12.50", + "x-codex-credits-has-credits": "TRUE", "x-codex-credits-unlimited": PROVIDER_KEY, + })); + expect(out).toEqual({ + "x-ratelimit-limit-tokens": "400", "x-codex-primary-used-percent": "100", + "x-codex-credits-balance": "12.5", "x-codex-credits-has-credits": "true", + }); + }); + + test("rate-limit resets are rebuilt from whole units and clamp to eight days", () => { + expect(normalizeSafeResponseHeader("x-ratelimit-reset-requests", "6m0s")).toBe("6m0s"); + expect(normalizeSafeResponseHeader("x-ratelimit-reset-tokens", "1h2m3.5s")).toBe("1h2m4s"); + expect(normalizeSafeResponseHeader("x-ratelimit-reset-tokens", "20ms")).toBe("20ms"); + expect(normalizeSafeResponseHeader("x-ratelimit-reset-tokens", "0.5ms")).toBe("1ms"); + expect(normalizeSafeResponseHeader("x-ratelimit-reset", "30")).toBe("30"); + expect(normalizeSafeResponseHeader("x-ratelimit-reset", "2.75")).toBe("3"); + expect(normalizeSafeResponseHeader("x-ratelimit-reset", "0")).toBe("0"); + expect(normalizeSafeResponseHeader("x-ratelimit-reset", "-1")).toBeUndefined(); + expect(normalizeSafeResponseHeader("x-ratelimit-reset", "soon")).toBeUndefined(); + expect(normalizeSafeResponseHeader("x-ratelimit-reset", "900000000")).toBe("691200"); + expect(normalizeSafeResponseHeader("x-ratelimit-reset", NUMERIC_KEY)).toBeUndefined(); + expect(normalizeSafeResponseHeader("x-ratelimit-reset-requests", PROVIDER_KEY)).toBeUndefined(); + expect(normalizeSafeResponseHeader("x-ratelimit-reset-requests", "999999h")).toBe("192h0m0s"); + expect(normalizeSafeResponseHeader("x-ratelimit-reset-requests", "")).toBeUndefined(); + }); + + test("rate-limit counts are rebuilt as bounded non-negative integers", () => { + const name = "x-ratelimit-limit"; + expect(normalizeSafeResponseHeader(name, "1.25")).toBe("1"); + expect(normalizeSafeResponseHeader(name, "0.999999")).toBe("0"); + expect(normalizeSafeResponseHeader(name, "-5")).toBeUndefined(); + expect(normalizeSafeResponseHeader(name, "NaN")).toBeUndefined(); + expect(normalizeSafeResponseHeader(name, "Infinity")).toBeUndefined(); + expect(normalizeSafeResponseHeader(name, "12 requests")).toBeUndefined(); + expect(normalizeSafeResponseHeader(name, "999999999999999")).toBe("1000000000000"); + expect(normalizeSafeResponseHeader(name, NUMERIC_KEY)).toBeUndefined(); + expect(normalizeSafeResponseHeader("x-ratelimit-remaining-tokens", "4000.5")).toBe("4000"); + expect(normalizeSafeResponseHeader("x-codex-primary-window-minutes", "60.5")).toBeUndefined(); + expect(normalizeSafeResponseHeader("x-codex-primary-reset-at", "1790000000")).toBe("1790000000"); + }); + + test("header names that match Object.prototype members are never relayed", () => { + const names = ["constructor", "__proto__", "toString", "hasOwnProperty", "valueOf", "__defineGetter__"]; + for (const name of names) { + expect(isSafeResponseHeader(name)).toBe(false); + expect(normalizeSafeResponseHeader(name, PROVIDER_KEY)).toBeUndefined(); + } + const headers = new Headers(); + for (const name of names.filter(name => name !== "__proto__" && name !== "__defineGetter__")) headers.set(name, PROVIDER_KEY); + headers.set("x-ratelimit-remaining", "7"); + const frame = buildWsErrorFrame(429, { message: "Rate limited" }, headers); + expect(frame.headers).toEqual({ "x-ratelimit-remaining": "7" }); + expect(JSON.stringify(frame)).not.toContain(PROVIDER_KEY); + }); + + test("the native WebSocket metadata path ignores prototype-member header names", () => { + const owner = new CodexWsMetadata(); + owner.commit(); + const event = JSON.parse( + '{"type":"codex.response.metadata","headers":{"constructor":"' + PROVIDER_KEY + '","__proto__":"' + PROVIDER_KEY + + '","toString":"' + PROVIDER_KEY + '","hasOwnProperty":"' + PROVIDER_KEY + '","x-ratelimit-limit":"1.25"}}', + ) as Record; + const text = owner.consume(event, 200); + expect(text).toBe('{"type":"codex.response.metadata","headers":{"x-ratelimit-limit":"1"}}'); + expect(JSON.stringify([...owner.snapshot()])).not.toContain(PROVIDER_KEY); + }); + + test("request ids, the models etag and quota limit labels are never relayed", () => { + for (const name of ["x-request-id", "openai-request-id", "x-models-etag", "x-codex-primary-limit-name", "x-codex-bengalfox-limit-name"]) { + expect(isSafeResponseHeader(name)).toBe(false); + expect(normalizeSafeResponseHeader(name, "req_abc-123")).toBeUndefined(); + } + }); + + test("a model header is kept only as a model id the proxy already knows", () => { + // A catalog model, and a requested model the send names, pass as the proxy's own copy. + expect(normalizeSafeResponseHeader("openai-model", "gpt-5.6-sol")).toBe("gpt-5.6-sol"); + expect(normalizeSafeResponseHeader("openai-model", "custom-model-1", { knownModels: ["custom-model-1"] })).toBe("custom-model-1"); + // A prefixless key fits the identifier grammar but names no known model, so it is dropped. + for (const name of ["openai-model", "x-codex-safety-buffering-faster-model"]) { + expect(normalizeSafeResponseHeader(name, PROVIDER_KEY)).toBeUndefined(); + expect(normalizeSafeResponseHeader(name, PROVIDER_KEY, { knownModels: ["gpt-5.5"] })).toBeUndefined(); + expect(normalizeSafeResponseHeader(name, "custom-model-1")).toBeUndefined(); + } + expect(normalizeSafeResponseHeader("openai-model", "model+" + PROVIDER_KEY)).toBeUndefined(); + }); + + test("the turn-state token is replaced by a handle bound to the send, or dropped without one", () => { + const handle = normalizeSafeResponseHeader("x-codex-turn-state", PROVIDER_KEY, { turnStateBinding: "send-a" })!; + expect(handle).toMatch(/^ocx-ts-[0-9a-f]{32}$/); + expect(handle).not.toContain(PROVIDER_KEY); + expect(resolveTurnStateHandle(handle, "send-a")).toEqual({ value: PROVIDER_KEY }); + expect(resolveTurnStateHandle(handle, "send-b")).toEqual({ dropped: "mismatch" }); + // An already issued handle passes a second normalization; a raw token without a binding does not. + expect(normalizeSafeResponseHeader("x-codex-turn-state", handle)).toBe(handle); + expect(normalizeSafeResponseHeader("x-codex-turn-state", PROVIDER_KEY)).toBeUndefined(); + expect(normalizeSafeResponseHeader("x-codex-turn-state", "bad value", { turnStateBinding: "send-a" })).toBeUndefined(); + }); + + test("quota windows are relayed only for known limit families", () => { + expect(normalizeSafeResponseHeader("x-codex-primary-used-percent", "5")).toBe("5"); + expect(normalizeSafeResponseHeader("x-codex-bengalfox-primary-used-percent", "5")).toBe("5"); + expect(normalizeSafeResponseHeader(`x-codex-${PROVIDER_KEY.toLowerCase()}-primary-used-percent`, "5")).toBeUndefined(); + expect(normalizeSafeResponseHeader("x-codex-extra-secondary-used-percent", "5")).toBeUndefined(); + }); + + test("no upstream header bytes reach the WebSocket error frame or the metadata frame", () => { + const upstreamHeaders: Record = { + "x-request-id": PROVIDER_KEY, "openai-request-id": PROVIDER_KEY, "x-models-etag": PROVIDER_KEY, + "x-codex-turn-state": PROVIDER_KEY, "x-codex-primary-limit-name": PROVIDER_KEY, "x-codex-primary-reset-at": NUMERIC_KEY, + "openai-model": PROVIDER_KEY, "x-codex-safety-buffering-faster-model": PROVIDER_KEY, + [`x-codex-${PROVIDER_KEY.toLowerCase()}-primary-used-percent`]: "5", "x-ratelimit-remaining": "7", + }; + const errorFrame = JSON.stringify(buildWsErrorFrame(429, { message: "Rate limited" }, new Headers(upstreamHeaders))); + const owner = new CodexWsMetadata(undefined, { turnStateBinding: "send-a", knownModels: ["gpt-5.5"] }); + owner.commit(); + const metadataFrame = owner.consume({ type: "codex.response.metadata", headers: upstreamHeaders }, 700)!; + const snapshot = JSON.stringify([...owner.snapshot()]); + // Non-vacuous: each output carries the allowlisted count; the bound outputs carry the handle. + expect(errorFrame).not.toContain("x-codex-turn-state"); + for (const text of [errorFrame, metadataFrame, snapshot]) { + expect(text).toContain("x-ratelimit-remaining"); + if (text !== errorFrame) expect(text).toMatch(/ocx-ts-[0-9a-f]{32}/); + expect(text).not.toContain("openai-model"); + expect(text.toLowerCase()).not.toContain(PROVIDER_KEY.toLowerCase()); + expect(text).not.toContain(NUMERIC_KEY); + } + }); + + test("the codex.rate_limits frame is rebuilt from known fields with bounded values", () => { + const owner = new CodexWsMetadata(); + owner.commit(); + const text = owner.consume({ + type: "codex.rate_limits", secret: PROVIDER_KEY, nested: { deeper: { key: PROVIDER_KEY } }, + plan_type: "plus", metered_limit_name: "codex_bengalfox", limit_name: PROVIDER_KEY, + rate_limits: { + allowed: true, limit_reached: false, extra: PROVIDER_KEY, + primary: { used_percent: 33.333333, window_minutes: 300, reset_at: 1_900_000_000, note: PROVIDER_KEY }, + secondary: { used_percent: Number(NUMERIC_KEY), window_minutes: Number(NUMERIC_KEY), reset_at: 1.5 }, + }, + credits: { has_credits: true, unlimited: false, balance: "12.50", owner: PROVIDER_KEY }, + }, 900)!; + expect(JSON.parse(text)).toEqual({ + type: "codex.rate_limits", plan_type: "plus", metered_limit_name: "codex_bengalfox", + rate_limits: { + allowed: true, limit_reached: false, + primary: { used_percent: 33.33, window_minutes: 300, reset_at: 1_900_000_000 }, + secondary: { used_percent: 100 }, + }, + credits: { has_credits: true, unlimited: false }, + }); + // The balance reaches clients only as the proxy-formatted header. + expect(owner.snapshot().get("x-codex-credits-balance")).toBe("12.5"); + expect(owner.snapshot().get("x-codex-bengalfox-secondary-used-percent")).toBe("100"); + for (const output of [text, JSON.stringify([...owner.snapshot()])]) { + expect(output).not.toContain(PROVIDER_KEY); + expect(output).not.toContain(NUMERIC_KEY.slice(0, 12)); + } + }); + + test("every retained rate-limit field drops a prefixless key", () => { + const owner = new CodexWsMetadata(); + owner.commit(); + const text = owner.consume({ + type: "codex.rate_limits", plan_type: PROVIDER_KEY, metered_limit_name: PROVIDER_KEY, + rate_limits: { allowed: PROVIDER_KEY, primary: { used_percent: 5, reset_at: Number(NUMERIC_KEY) } }, + credits: { has_credits: PROVIDER_KEY, balance: NUMERIC_KEY }, + }, 600)!; + // An unknown limit id drops its windows rather than relabelling them as ordinary quota. + expect(JSON.parse(text)).toEqual({ type: "codex.rate_limits", rate_limits: {}, credits: {} }); + expect([...owner.snapshot()]).toHaveLength(0); + const ordinary = owner.consume({ type: "codex.rate_limits", rate_limits: { primary: { used_percent: 5, reset_at: Number(NUMERIC_KEY) } } }, 200)!; + expect(JSON.parse(ordinary)).toEqual({ type: "codex.rate_limits", rate_limits: { primary: { used_percent: 5 } } }); + expect([...owner.snapshot()]).toEqual([["x-codex-primary-used-percent", "5"]]); + }); + + test("the native WebSocket metadata path relays the same rebuilt values", () => { + const owner = new CodexWsMetadata(); + owner.commit(); + const text = owner.consume({ type: "codex.response.metadata", headers: { + "x-ratelimit-secret": PROVIDER_KEY, "x-request-id": PROVIDER_KEY + "!", "x-ratelimit-remaining-requests": "7", + "x-codex-promo-message": PROVIDER_KEY, + } }, 200); + expect(text).toBe('{"type":"codex.response.metadata","headers":{"x-ratelimit-remaining-requests":"7"}}'); + expect(JSON.stringify([...owner.snapshot()])).not.toContain(PROVIDER_KEY); + const quota = new CodexWsMetadata(); + quota.commit(); + quota.consume({ type: "codex.rate_limits", credits: { balance: PROVIDER_KEY, has_credits: true } }, 200); + expect(quota.snapshot().get("x-codex-credits-balance")).toBeNull(); + expect(quota.snapshot().get("x-codex-credits-has-credits")).toBe("true"); + }); +}); diff --git a/tests/server/server-403-permission-e2e.test.ts b/tests/server/server-403-permission-e2e.test.ts index 4cf61d88241..1cd450a6c22 100644 --- a/tests/server/server-403-permission-e2e.test.ts +++ b/tests/server/server-403-permission-e2e.test.ts @@ -113,7 +113,8 @@ describe("upstream 401/403 classification (end-to-end)", () => { status: 403, errorCode: "subscription_required", }); - expect(result.log.upstreamError).toContain(SUBSCRIPTION_MESSAGE); + expect(result.log.upstreamCondition).toBe("access_denied"); + expect(JSON.stringify(result.log)).not.toContain(SUBSCRIPTION_MESSAGE); }); test("the same subscription body under authoritative 401 stays invalid_api_key", async () => { diff --git a/tests/server/server-auth.test.ts b/tests/server/server-auth.test.ts index f24cc0b0206..8aadb2aae3a 100644 --- a/tests/server/server-auth.test.ts +++ b/tests/server/server-auth.test.ts @@ -3895,9 +3895,10 @@ describe("server local API auth", () => { errorCode: "cyber_policy", terminalStatus: "failed", closeReason: "terminal", - upstreamError: message, + upstreamCondition: "request_rejected", attempts: [expect.objectContaining({ status: 400, errorCode: "cyber_policy" })], }); + expect(JSON.stringify(logs.at(-1))).not.toContain(message); } finally { await server.stop(true); await upstream.stop(true); diff --git a/tests/server/server-combo-failover-e2e.test.ts b/tests/server/server-combo-failover-e2e.test.ts index 1fd65f10304..7dd0c45a84c 100644 --- a/tests/server/server-combo-failover-e2e.test.ts +++ b/tests/server/server-combo-failover-e2e.test.ts @@ -926,8 +926,13 @@ describe("server combo failover 030 activation matrix", () => { expect(logs[0]).toMatchObject({ provider: "combo", model: "combo/free", resolvedModel: "m1", status: scenario.logStatus, terminalStatus: scenario.status, - closeReason: "terminal", upstreamError: scenario.message, + closeReason: "terminal", }); + // A failed row keeps a closed condition (a successful output-limit stop has none); the + // upstream message stays on the request context. + if (scenario.logStatus >= 400) expect(logs[0]!.upstreamCondition).toBeDefined(); + else expect(logs[0]!.upstreamCondition).toBeUndefined(); + expect(JSON.stringify(logs[0])).not.toContain(scenario.message); expect(logs[0]!.attempts).toMatchObject([{ provider: "a", model: "m1", status: scenario.logStatus }]); expect(logs[0]!.attempts).toHaveLength(1); if (scenario.status === "failed") expect(logs[0]!.errorCode).toBe("cyber_policy"); @@ -3392,7 +3397,7 @@ describe("server combo failover 030 activation matrix", () => { expect(statuses).toEqual(["completed"]); expect(cancels).toBe(0); expect(snapshots).toHaveLength(1); - expect(snapshots[0]).toMatchObject({ provider: "combo", model: "combo/free", resolvedModel: "final-b" }); + expect(snapshots[0]).toMatchObject({ provider: "combo", model: "combo/free", resolvedModel: "m2" }); for (const field of ["terminalHttpStatus", "terminalIncompleteReason", "terminalErrorCode", "upstreamError"] as const) { expect(snapshots[0]![field]).toBeUndefined(); } diff --git a/tests/server/server-native-final-log.test.ts b/tests/server/server-native-final-log.test.ts index 810113224a2..549f0be0b6d 100644 --- a/tests/server/server-native-final-log.test.ts +++ b/tests/server/server-native-final-log.test.ts @@ -84,6 +84,28 @@ describe("native final request log", () => { expect(await waiting).toBe(true); }); + test("upstream evidence informs the final row and never reaches it", async () => { + const credential = "zq7Vb2LmN4pX9tR1sK8wD3fH6jY0cA5e"; + const timestamp = Date.now(); + const resetAt = Math.floor((timestamp + 3_600_000) / 1000) * 1000; + const sentence = "Subscription quota exhausted. Your usage window resets at " + new Date(resetAt).toISOString().replace(/\.\d{3}Z$/, "Z") + "."; + for (const [status, upstreamError, provider, expected] of [ + [429, sentence, "meta-muse", { errorCode: "rate_limit_exceeded", upstreamCondition: "billing_exhausted", rateLimitResetAt: resetAt }], + [400, "This model's maximum context length is 8192 tokens; key " + credential, "fixture", { errorCode: "invalid_request_error", upstreamCondition: "context_overflow" }], + ] as const) { + const logCtx = { ...context(), provider, upstreamError, upstreamErrorCode: credential, upstreamRequestId: credential }; + const rows: RequestLogEntry[] = []; + const owner = createNativeFinalLog("evidence", timestamp, logCtx, { addLog: row => rows.push(row) }); + addFinalRequestLog("evidence", timestamp, logCtx, status, { terminalStatus: "failed", closeReason: "terminal" }); + await owner.waitForInner(); + owner.commit({ status, terminalStatus: "failed", closeReason: "terminal" }); + expect(rows[0]).toMatchObject({ status, ...expected }); + const serialized = JSON.stringify(rows[0]); + expect(serialized).not.toContain(credential); + expect(serialized).not.toContain("Subscription quota exhausted"); + } + }); + test("ordinary request logging is unchanged without an owner", () => { const rows: RequestLogEntry[] = []; const logCtx = { ...context(), upstreamError: "client closed request" }; diff --git a/tests/server/turn-state-handles-e2e.test.ts b/tests/server/turn-state-handles-e2e.test.ts new file mode 100644 index 00000000000..fc79dc23ff7 --- /dev/null +++ b/tests/server/turn-state-handles-e2e.test.ts @@ -0,0 +1,201 @@ +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { saveConfig } from "../../src/config"; +import { startServer } from "../../src/server"; +import { resetTurnStateHandlesForTests } from "../../src/server/turn-state-handles"; +import type { OcxConfig } from "../../src/types"; +import { fakeChatGptJwt } from "../helpers/fake-chatgpt-jwt"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +/** + * End to end: the proxy obtains a turn-state token from a (mock) ChatGPT Codex WebSocket upstream, + * hands the client a handle, and maps the handle back when the same client sends it on its next + * request, over HTTP and over WebSocket. Only the upstream socket is faked; the server, its + * admission, routing and the client's own sockets are real. + */ + +type Listener = (event: unknown) => void; +const sentFrames: Array> = []; + +/** The token the mock upstream issues for a request is derived from its input, so each turn differs. */ +const tokenFor = (frame: Record) => `upstream-turn-${String(frame.input)}`; + +class FakeCodexSocket { + readyState = 0; + private readonly listeners = new Map(); + constructor(_url: string, _options?: unknown) { + queueMicrotask(() => { this.readyState = 1; this.emit("open", {}); }); + } + addEventListener(type: string, listener: Listener) { + this.listeners.set(type, [...(this.listeners.get(type) ?? []), listener]); + } + removeEventListener(type: string, listener: Listener) { + this.listeners.set(type, (this.listeners.get(type) ?? []).filter(value => value !== listener)); + } + private emit(type: string, event: unknown) { + for (const listener of this.listeners.get(type) ?? []) listener(event); + } + send(data: string) { + const frame = JSON.parse(data) as Record; + sentFrames.push(frame); + const id = `resp_${sentFrames.length}`; + queueMicrotask(() => { + this.emit("message", { data: JSON.stringify({ type: "codex.response.metadata", headers: { "x-codex-turn-state": tokenFor(frame) } }) }); + this.emit("message", { data: JSON.stringify({ type: "response.created", response: { id, object: "response", status: "in_progress", output: [] } }) }); + this.emit("message", { data: JSON.stringify({ type: "response.completed", response: { id, object: "response", status: "completed", output: [] } }) }); + }); + } + close() { this.readyState = 3; } + terminate() { this.readyState = 3; } + ref() {} + unref() {} +} + +const RealWebSocket = globalThis.WebSocket; +const PROXY_ENV_KEYS = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "all_proxy", "no_proxy"] as const; +const savedEnv: Record = {}; +let home = ""; + +const KEYS = { a: "ocx_data_turn_state_caller_a", b: "ocx_data_turn_state_caller_b" } as const; +const bearer = `Bearer ${fakeChatGptJwt({ chatgpt_account_id: "turn-state-fixture", exp: Math.floor(Date.now() / 1000) + 3600 })}`; + +beforeEach(() => { + for (const key of [...PROXY_ENV_KEYS, "OPENCODEX_HOME"]) savedEnv[key] = process.env[key]; + for (const key of PROXY_ENV_KEYS) delete process.env[key]; + home = mkdtempSync(join(tmpdir(), "ocx-turn-state-e2e-")); + process.env.OPENCODEX_HOME = home; + sentFrames.length = 0; + resetTurnStateHandlesForTests(); + // Only the ChatGPT Codex upstream socket is faked; the test's own client sockets are real. + globalThis.WebSocket = new Proxy(RealWebSocket, { + construct(target, args) { + return String(args[0]).startsWith("wss://chatgpt.com/") ? new FakeCodexSocket(String(args[0]), args[1]) : Reflect.construct(target, args); + }, + }); + saveFixtureConfig(); +}); + +/** A loopback proxy admits every local caller as one session; a public bind admits each key as its own caller. */ +function saveFixtureConfig(hostname?: string): void { + saveConfig({ + port: 0, defaultProvider: "openai", websockets: true, ...(hostname ? { hostname } : {}), + apiKeys: [ + { id: "caller-a", name: "caller a", key: KEYS.a, createdAt: "2026-11-03T00:00:00.000Z" }, + { id: "caller-b", name: "caller b", key: KEYS.b, createdAt: "2026-11-03T00:00:00.000Z" }, + ], + providers: { openai: { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", authMode: "forward" } }, + } as unknown as OcxConfig); +} + +afterEach(() => { + globalThis.WebSocket = RealWebSocket; + for (const [key, value] of Object.entries(savedEnv)) { + if (value === undefined) delete process.env[key]; else process.env[key] = value; + } + removeTreeWithRetry(home); +}); + +/** One HTTP turn; returns the turn-state value the client received. */ +async function httpTurn(server: { url: URL }, caller: keyof typeof KEYS, input: string, turnState?: string): Promise { + const response = await fetch(new URL("/v1/responses", server.url), { + method: "POST", + headers: { + "content-type": "application/json", authorization: bearer, "x-opencodex-api-key": KEYS[caller], + ...(turnState ? { "x-codex-turn-state": turnState } : {}), + }, + body: JSON.stringify({ model: "gpt-5.5", input, stream: true }), + }); + const text = await response.text(); + expect(response.status).toBe(200); + expect(text).toContain("response.completed"); + return response.headers.get("x-codex-turn-state"); +} + +/** One WebSocket turn per frame on a single connection; returns the handle each metadata frame carried. */ +async function wsTurns(server: { url: URL }, caller: keyof typeof KEYS, turns: Array<{ input: string; turnState?: string }>): Promise> { + const ws = new WebSocket(new URL("/v1/responses", server.url).href.replace(/^http/, "ws"), { + headers: { authorization: bearer, "x-opencodex-api-key": KEYS[caller] }, + } as unknown as string[]); + const handles: Array = []; + let resolveTurn: (() => void) | undefined; + let current: string | undefined; + ws.onmessage = event => { + const frame = JSON.parse(String(event.data)) as { type?: string; headers?: Record }; + if (frame.type === "codex.response.metadata") current = frame.headers?.["x-codex-turn-state"]; + if (frame.type === "response.completed") { handles.push(current); current = undefined; resolveTurn?.(); } + }; + await new Promise((resolve, reject) => { ws.onopen = () => resolve(); ws.onerror = () => reject(new Error("websocket error")); }); + for (const turn of turns) { + const done = new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error("no terminal frame")), 10_000); + resolveTurn = () => { clearTimeout(timer); resolve(); }; + }); + ws.send(JSON.stringify({ type: "response.create", model: "gpt-5.5", input: turn.input, + ...(turn.turnState ? { client_metadata: { "x-codex-turn-state": turn.turnState } } : {}) })); + await done; + } + ws.close(); + return handles; +} + +const forwardedTurnState = (index: number) => (sentFrames[index]?.client_metadata as Record | undefined)?.["x-codex-turn-state"]; + +describe("a turn-state handle obtained from an upstream response is redeemed on the next request", () => { + test("HTTP: the handle in the response header maps back to the upstream token", async () => { + const server = startServer(0); + try { + const handle = await httpTurn(server, "a", "first"); + // Non-vacuous: the upstream answered and the client received a handle, not the token. + expect(sentFrames).toHaveLength(1); + expect(handle).toMatch(/^ocx-ts-[0-9a-f]{32}$/); + expect(handle).not.toContain("upstream-turn"); + await httpTurn(server, "a", "second", handle!); + expect(sentFrames).toHaveLength(2); + expect(forwardedTurnState(1)).toBe("upstream-turn-first"); + } finally { await server.stop(true); } + }); + + test("WebSocket: the handle in the relayed metadata frame maps back to the upstream token", async () => { + const server = startServer(0); + try { + const [first] = await wsTurns(server, "a", [{ input: "first" }]); + expect(sentFrames).toHaveLength(1); + expect(first).toMatch(/^ocx-ts-[0-9a-f]{32}$/); + await wsTurns(server, "a", [{ input: "second", turnState: first }]); + expect(sentFrames).toHaveLength(2); + expect(forwardedTurnState(1)).toBe("upstream-turn-first"); + } finally { await server.stop(true); } + }); + + test("two concurrent callers each redeem only their own handle", async () => { + // API keys admit as distinct callers only where admission is required, which a public bind makes it. + saveFixtureConfig("0.0.0.0"); + const server = startServer(0); + const warn = spyOn(console, "warn"); + try { + const [handleA, handleB] = await Promise.all([httpTurn(server, "a", "turn-a"), httpTurn(server, "b", "turn-b")]); + expect(sentFrames).toHaveLength(2); + expect(handleA).toMatch(/^ocx-ts-[0-9a-f]{32}$/); + expect(handleB).toMatch(/^ocx-ts-[0-9a-f]{32}$/); + expect(handleA).not.toBe(handleB); + // Concurrently: each caller redeems its own handle, and caller b presents caller a's handle too. + await Promise.all([ + httpTurn(server, "a", "next-a", handleA!), + httpTurn(server, "b", "next-b", handleB!), + httpTurn(server, "b", "stolen-by-b", handleA!), + ]); + expect(sentFrames).toHaveLength(5); + const byInput = new Map(sentFrames.map(frame => [String(frame.input), (frame.client_metadata as Record | undefined)?.["x-codex-turn-state"]])); + expect(byInput.get("next-a")).toBe("upstream-turn-turn-a"); + expect(byInput.get("next-b")).toBe("upstream-turn-turn-b"); + expect(byInput.get("stolen-by-b")).toBeUndefined(); + expect(warn.mock.calls.map(call => String(call[0])).some(text => text.includes("turn_state_binding_mismatch"))).toBe(true); + expect(warn.mock.calls.flat().map(String).join("\n")).not.toContain("upstream-turn"); + } finally { + warn.mockRestore(); + await server.stop(true); + } + }); +}); diff --git a/tests/server/turn-state-handles.test.ts b/tests/server/turn-state-handles.test.ts new file mode 100644 index 00000000000..c3b922e6a7b --- /dev/null +++ b/tests/server/turn-state-handles.test.ts @@ -0,0 +1,189 @@ +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { saveConfig } from "../../src/config"; +import { startServer } from "../../src/server"; +import { + issueTurnStateHandle, noteTurnStateCaller, redeemOutboundTurnState, resetTurnStateHandlesForTests, + resolveTurnStateHandle, runTurnStateCallerScope, TURN_STATE_MISMATCH_NOTICE, turnStateBinding, +} from "../../src/server/turn-state-handles"; +import type { OcxConfig } from "../../src/types"; +import { fakeChatGptJwt } from "../helpers/fake-chatgpt-jwt"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +// An upstream token with no recognizable prefix. +const UPSTREAM_TOKEN = "zq7Vb2LmN4pX9tR1sK8wD3fH6jY0cA5e"; +const HANDLE = /^ocx-ts-[0-9a-f]{32}$/; + +beforeEach(() => resetTurnStateHandlesForTests()); + +/** The binding the proxy computes for a send with these outbound headers, under a given caller. */ +function bindingFor(caller: { kind: string; keyId?: string }, provider: string, headers: Headers): string { + return runTurnStateCallerScope(() => { + noteTurnStateCaller(caller); + return turnStateBinding(provider, headers); + }); +} + +describe("turn-state handles", () => { + test("a handle is proxy-generated, stable per token and binding, and maps back only under its binding", () => { + const handle = issueTurnStateHandle(UPSTREAM_TOKEN, "send-a"); + expect(handle).toMatch(HANDLE); + expect(handle).not.toContain(UPSTREAM_TOKEN); + expect(issueTurnStateHandle(UPSTREAM_TOKEN, "send-a")).toBe(handle); + expect(issueTurnStateHandle(handle, "send-a")).toBe(handle); + expect(issueTurnStateHandle(UPSTREAM_TOKEN, "send-b")).not.toBe(handle); + expect(resolveTurnStateHandle(handle, "send-a")).toEqual({ value: UPSTREAM_TOKEN }); + expect(resolveTurnStateHandle(handle, "send-b")).toEqual({ dropped: "mismatch" }); + }); + + test("unknown and expired handles resolve to nothing; other values pass unchanged", () => { + const now = Date.now(); + const handle = issueTurnStateHandle(UPSTREAM_TOKEN, "send-a", now); + expect(resolveTurnStateHandle("ocx-ts-" + "0".repeat(32), "send-a", now)).toEqual({ dropped: "unknown" }); + expect(resolveTurnStateHandle(handle, "send-a", now + 7 * 60 * 60 * 1000)).toEqual({ dropped: "unknown" }); + expect(resolveTurnStateHandle("raw-upstream-token", "send-a", now)).toEqual({ value: "raw-upstream-token" }); + }); + + test("the map is bounded: the oldest handle is evicted first", () => { + const first = issueTurnStateHandle("token-0", "send-a"); + for (let i = 1; i <= 4096; i++) issueTurnStateHandle(`token-${i}`, "send-a"); + expect(resolveTurnStateHandle(first, "send-a")).toEqual({ dropped: "unknown" }); + }); + + test("the binding covers caller, provider and account, and differs when any of them does", () => { + const headers = new Headers({ "chatgpt-account-id": "account-a", authorization: "Bearer a" }); + const base = bindingFor({ kind: "loopback" }, "openai", headers); + expect(bindingFor({ kind: "loopback" }, "openai", headers)).toBe(base); + expect(bindingFor({ kind: "configured", keyId: "key-1" }, "openai", headers)).not.toBe(base); + expect(bindingFor({ kind: "loopback" }, "other", headers)).not.toBe(base); + expect(bindingFor({ kind: "loopback" }, "openai", new Headers({ "chatgpt-account-id": "account-b" }))).not.toBe(base); + // Without an account id the outbound credential stands in for the account. + expect(bindingFor({ kind: "loopback" }, "openai", new Headers({ authorization: "Bearer a" }))) + .not.toBe(bindingFor({ kind: "loopback" }, "openai", new Headers({ authorization: "Bearer b" }))); + expect(base).not.toContain("account-a"); + }); + + test("an outbound send is translated only for a handle with the same binding", () => { + const handle = issueTurnStateHandle(UPSTREAM_TOKEN, "send-a"); + const init = { headers: { "x-codex-turn-state": handle }, body: JSON.stringify({ client_metadata: { "x-codex-turn-state": handle, keep: "1" } }) }; + const same = redeemOutboundTurnState(init, "send-a")!; + expect(new Headers(same.headers).get("x-codex-turn-state")).toBe(UPSTREAM_TOKEN); + expect(JSON.parse(same.body as string).client_metadata).toEqual({ "x-codex-turn-state": UPSTREAM_TOKEN, keep: "1" }); + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + const other = redeemOutboundTurnState(init, "send-b")!; + expect(new Headers(other.headers).has("x-codex-turn-state")).toBe(false); + expect(JSON.parse(other.body as string).client_metadata).toEqual({ keep: "1" }); + expect(warn.mock.calls.map(call => String(call[0]))).toEqual([TURN_STATE_MISMATCH_NOTICE]); + expect(TURN_STATE_MISMATCH_NOTICE).not.toContain("ocx-ts-"); + } finally { warn.mockRestore(); } + // A send without a handle is returned as is, bytes and all. + const plain = { headers: { "x-codex-turn-state": "raw" }, body: "{\"a\":1}" }; + expect(redeemOutboundTurnState(plain, "send-a")).toBe(plain); + }); +}); + +describe("the server redeems a handle only for the same caller, provider and account", () => { + const originalFetch = globalThis.fetch; + const previousHome = process.env.OPENCODEX_HOME; + let home = ""; + let forwarded: Array<{ headers: Headers; body?: Record }> = []; + + beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "ocx-turn-state-")); + process.env.OPENCODEX_HOME = home; + forwarded = []; + saveConfig({ + port: 0, defaultProvider: "openai", websockets: true, + // HTTP/SSE upstream, so the fixture never opens a real WebSocket. + providers: { openai: { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", authMode: "forward", upstreamWebsocket: false } }, + } as unknown as OcxConfig); + }); + afterEach(() => { + globalThis.fetch = originalFetch; + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previousHome; + removeTreeWithRetry(home); + }); + + const bearer = `Bearer ${fakeChatGptJwt({ chatgpt_account_id: "turn-state-fixture", exp: Math.floor(Date.now() / 1000) + 3600 })}`; + function captureUpstream(server: { url: URL }): void { + const local = new URL(server.url).origin; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = input instanceof Request ? input.url : String(input); + if (url.startsWith(local)) return originalFetch(input, init); + forwarded.push({ + headers: new Headers(input instanceof Request ? input.headers : init?.headers), + ...(typeof init?.body === "string" ? { body: JSON.parse(init.body) as Record } : {}), + }); + const completed = { type: "response.completed", response: { id: "resp_1", object: "response", status: "completed", output: [] } }; + return new Response(`event: response.completed\ndata: ${JSON.stringify(completed)}\n\n`, { headers: { "content-type": "text/event-stream" } }); + }) as typeof fetch; + } + async function post(server: { url: URL }, turnState?: string): Promise { + const response = await originalFetch(new URL("/v1/responses", server.url), { + method: "POST", + headers: { "content-type": "application/json", authorization: bearer, ...(turnState ? { "x-codex-turn-state": turnState } : {}) }, + body: JSON.stringify({ model: "gpt-5.5", input: "hi", stream: true }), + }); + await response.text(); + } + async function frame(server: { url: URL }, turnState: string): Promise { + const ws = new WebSocket(new URL("/v1/responses", server.url).href.replace(/^http/, "ws"), { + headers: { "x-codex-turn-state": turnState, authorization: bearer }, + } as unknown as string[]); + const terminal = new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error("no terminal frame")), 10_000); + ws.onmessage = event => { if (String(event.data).includes("response.completed")) { clearTimeout(timer); resolve(); } }; + ws.onerror = () => { clearTimeout(timer); reject(new Error("websocket error")); }; + }); + await new Promise(resolve => { ws.onopen = () => resolve(); }); + ws.send(JSON.stringify({ type: "response.create", model: "gpt-5.5", input: "hi", client_metadata: { "x-codex-turn-state": turnState } })); + await terminal; + ws.close(); + } + + // Each case issues a handle under the binding of the first (handle-free) send, or a variation of it. + const CASES: Array<[string, (headers: Headers) => string, string | null]> = [ + ["same caller, provider and account", headers => bindingFor({ kind: "loopback" }, "openai", headers), UPSTREAM_TOKEN], + ["another account", headers => { + const other = new Headers(headers); + if (other.has("chatgpt-account-id")) other.set("chatgpt-account-id", "other-account"); else other.set("authorization", "Bearer other"); + return bindingFor({ kind: "loopback" }, "openai", other); + }, null], + ["another provider", headers => bindingFor({ kind: "loopback" }, "other-provider", headers), null], + ["another caller", headers => bindingFor({ kind: "configured", keyId: "other-key" }, "openai", headers), null], + ]; + + for (const transport of ["HTTP", "WebSocket"] as const) { + for (const [name, binding, expected] of CASES) { + test(`${transport}: ${name}`, async () => { + const server = startServer(0); + captureUpstream(server); + const warn = spyOn(console, "warn"); + try { + await post(server); + expect(forwarded.length).toBe(1); + const handle = issueTurnStateHandle(UPSTREAM_TOKEN, binding(forwarded[0]!.headers)); + if (transport === "HTTP") await post(server, handle); else await frame(server, handle); + // Non-vacuous: the second send reached the upstream before its turn state is checked. + expect(forwarded.length).toBe(2); + const sent = forwarded[1]!; + expect(sent.headers.get("x-codex-turn-state")).toBe(expected); + if (transport === "WebSocket") { + const metadata = (sent.body?.client_metadata ?? {}) as Record; + expect(metadata["x-codex-turn-state"]).toBe(expected ?? undefined); + } + expect(JSON.stringify({ headers: [...sent.headers], body: sent.body })).not.toContain("ocx-ts-"); + const notices = warn.mock.calls.map(call => String(call[0])).filter(text => text.includes("turn_state_binding_mismatch")); + expect(notices.length > 0).toBe(expected === null); + expect(warn.mock.calls.flat().map(String).join("\n")).not.toContain(handle); + } finally { + warn.mockRestore(); + await server.stop(true); + } + }); + } + } +}); diff --git a/tests/server/upstream-error-detail-boundaries.test.ts b/tests/server/upstream-error-detail-boundaries.test.ts new file mode 100644 index 00000000000..9959c4f9176 --- /dev/null +++ b/tests/server/upstream-error-detail-boundaries.test.ts @@ -0,0 +1,141 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { existsSync, mkdtempSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { saveConfig } from "../../src/config"; +import { startServer } from "../../src/server"; +import { getRequestLogEntries, requestLogEntryFromPersistedUsage } from "../../src/server/request-log"; +import type { OcxConfig } from "../../src/types"; +import { readUsageEntries, usageLogPath } from "../../src/usage/log"; +import { acquireOwnedSpendHome } from "../helpers/owned-spend-home"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +// A provider key with no recognizable prefix, so pattern-based redaction cannot spot it. +const PROVIDER_KEY = "zq7Vb2LmN4pX9tR1sK8wD3fH6jY0cA5e"; +// All digits, so a Retry-After parser accepts it as a delay in seconds. +const NUMERIC_KEY = "73915028461739205817"; +const saved = { home: process.env.OPENCODEX_HOME }; +let home = ""; +let status = 400; +let upstream: ReturnType; +let releaseSpendHome: (() => void) | undefined; + +beforeAll(() => { + home = mkdtempSync(join(tmpdir(), "ocx-error-detail-")); + process.env.OPENCODEX_HOME = home; + upstream = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(req) { + await req.text(); + // The upstream repeats the credential it received, as some gateways do in error details. + const echoed = (req.headers.get("authorization") ?? "").replace(/^Bearer /, "") || req.headers.get("x-api-key") || ""; + const anthropic = new URL(req.url).pathname.endsWith("/messages"); + const error = { message: "invalid key " + echoed + "; retry in " + NUMERIC_KEY + " seconds", type: echoed, code: echoed, param: echoed }; + const body = anthropic ? { type: "error", error: { type: echoed, message: error.message } } : { error }; + return Response.json(body, { status, headers: { "retry-after": NUMERIC_KEY, "x-request-id": echoed, "request-id": echoed } }); + } }); + releaseSpendHome = acquireOwnedSpendHome(); +}); +afterAll(() => { + upstream.stop(true); + releaseSpendHome?.(); + if (saved.home === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = saved.home; + if (home) removeTreeWithRetry(home); +}); + +function saveProviders(messagesNative: boolean) { + const base = upstream.url.origin; + saveConfig({ + port: 0, defaultProvider: "fxc", + providers: { + fxc: { adapter: "openai-chat", baseUrl: base + "/v1", authMode: "key", apiKey: PROVIDER_KEY, allowPrivateNetwork: true, models: ["m1"] }, + fxr: { adapter: "openai-responses", baseUrl: base + "/v1", authMode: "key", apiKey: PROVIDER_KEY, allowPrivateNetwork: true, models: ["m1"] }, + fxa: { adapter: "anthropic", baseUrl: base, authMode: "key", apiKey: PROVIDER_KEY, allowPrivateNetwork: true, models: ["claude-x"] }, + }, + combos: { echo: { strategy: "failover", targets: [{ provider: "fxc", model: "m1" }, { provider: "fxr", model: "m1" }] } }, + ...(messagesNative ? { protocols: { rollout: { managedMessagesNative: true } } } : {}), + } as unknown as OcxConfig); +} + +async function exchange(path: string, body: Record, headers: Record = {}) { + const printed: string[] = []; + const originals = { warn: console.warn, error: console.error, log: console.log, info: console.info }; + for (const name of ["warn", "error", "log", "info"] as const) { + console[name] = (...args: unknown[]) => { printed.push(args.map(String).join(" ")); }; + } + let server: ReturnType | undefined; + try { + // Started inside the try, so the console is restored even if startup throws. + server = startServer(0); + const earlier = new Set(getRequestLogEntries().map(entry => entry.requestId)); + const res = await fetch(new URL(path, server.url), { + method: "POST", headers: { "content-type": "application/json", ...headers }, body: JSON.stringify(body), + }); + await res.text(); + const responseHeaders = [...res.headers.entries()]; + // Poll until the request's row is live and persisted, so no absence check can pass on an empty read. + const deadline = Date.now() + 5_000; + let rows = getRequestLogEntries().filter(entry => !earlier.has(entry.requestId)); + while (rows.length === 0 || !rows.every(row => readUsageEntries().some(entry => entry.requestId === row.requestId))) { + if (Date.now() > deadline) throw new Error(`no persisted request-log row for ${path} within 5s (live rows: ${rows.length})`); + await Bun.sleep(20); + rows = getRequestLogEntries().filter(entry => !earlier.has(entry.requestId)); + } + return { status: res.status, responseHeaders, rows, printed }; + } finally { + try { await server?.stop(true); } finally { Object.assign(console, originals); } + } +} + +const CASES = [ + { name: "native Chat Completions", path: "/v1/chat/completions", messagesNative: false, + body: (stream: boolean) => ({ model: "fxc/m1", messages: [{ role: "user", content: "hi" }], stream }) }, + { name: "Responses passthrough", path: "/v1/responses", messagesNative: false, + body: (stream: boolean) => ({ model: "fxr/m1", input: "hi", stream }) }, + { name: "combo route", path: "/v1/responses", messagesNative: false, + body: (stream: boolean) => ({ model: "combo/echo", input: "hi", stream }) }, + { name: "native Messages", path: "/v1/messages", messagesNative: true, + body: (stream: boolean) => ({ model: "fxa/claude-x", max_tokens: 16, messages: [{ role: "user", content: "hi" }], stream }) }, + { name: "Messages passthrough", path: "/v1/messages", messagesNative: false, + body: (stream: boolean) => ({ model: "fxa/claude-x", max_tokens: 16, messages: [{ role: "user", content: "hi" }], stream }) }, +] as const; + +describe("upstream error details stay out of retry advice and request logs", () => { + for (const scenario of CASES) { + for (const stream of [false, true]) { + for (const upstreamStatus of [400, 429, 503]) { + test(scenario.name + " stream=" + stream + " upstream " + upstreamStatus, async () => { + saveProviders(scenario.messagesNative); + status = upstreamStatus; + const before = existsSync(usageLogPath()) ? readFileSync(usageLogPath(), "utf8").length : 0; + const result = await exchange(scenario.path, scenario.body(stream), { "anthropic-version": "2023-06-01" }); + expect(result.status).toBeGreaterThanOrEqual(400); + // Retry advice is regenerated here; other relayed response headers have their own boundary. + for (const [name, value] of result.responseHeaders) { + expect(value).not.toContain(NUMERIC_KEY); + if (name === "retry-after") { + expect(value).not.toContain(PROVIDER_KEY); + expect(value).toMatch(/^\d+$/); + expect(Number(value)).toBeLessThanOrEqual(691200); + } + } + expect(result.rows.length).toBeGreaterThan(0); + const live = JSON.stringify(result.rows); + expect(live).not.toContain(PROVIDER_KEY); + expect(live).not.toContain(NUMERIC_KEY); + const persisted = existsSync(usageLogPath()) ? readFileSync(usageLogPath(), "utf8").slice(before) : ""; + expect(persisted.length).toBeGreaterThan(0); + expect(persisted).not.toContain(PROVIDER_KEY); + expect(persisted).not.toContain(NUMERIC_KEY); + const ids = new Set(result.rows.map(row => row.requestId)); + const hydratedRows = readUsageEntries().filter(entry => ids.has(entry.requestId)).map(requestLogEntryFromPersistedUsage); + expect(hydratedRows.length).toBe(ids.size); + const hydrated = JSON.stringify(hydratedRows); + expect(hydrated).not.toContain(PROVIDER_KEY); + expect(hydrated).not.toContain(NUMERIC_KEY); + const printed = result.printed.join("\n"); + expect(printed).not.toContain(PROVIDER_KEY); + expect(printed).not.toContain(NUMERIC_KEY); + }); + } + } + } +}); diff --git a/tests/usage/request-log-error-detail.test.ts b/tests/usage/request-log-error-detail.test.ts new file mode 100644 index 00000000000..680bf03cbe7 --- /dev/null +++ b/tests/usage/request-log-error-detail.test.ts @@ -0,0 +1,250 @@ +import { describe, expect, test } from "bun:test"; +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + addFinalRequestLog, addRequestLog, clearRequestLogsForTests, getRequestLogEntries, requestLogEntryFromPersistedUsage, + type RequestLogContext, type RequestLogEntry, +} from "../../src/server/request-log"; +import { recordLocalFailureDetail } from "../../src/server/request-log-failure-detail"; +import { + appendUsageEntry, readUsageEntries, resetUsageReadCacheForTests, usageLogPath, type PersistedUsageEntry, +} from "../../src/usage/log"; +import { + boundedRateLimitResetAt, deriveRateLimitResetAt, errorDetailFor, LOG_ERROR_CODES, normalizeLogErrorCode, + projectErrorDetail, RATE_LIMIT_RESET_MAX_MS, +} from "../../src/usage/error-detail"; +import { museLimitReport } from "../../gui/src/muse-limit-observation"; +import { requestLogDto } from "../../src/server/management/shared"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { log } from "../helpers/request-log-entry"; + +// A provider key with no recognizable prefix, so pattern-based redaction cannot spot it. +const PROVIDER_KEY = "zq7Vb2LmN4pX9tR1sK8wD3fH6jY0cA5e"; +const NUMERIC_KEY = "73915028461739205817"; +const UPSTREAM_TEXT = { + upstreamError: "invalid key " + PROVIDER_KEY + " " + NUMERIC_KEY, + upstreamErrorCode: PROVIDER_KEY, + upstreamErrorType: "invalid_request_error", + upstreamRequestId: PROVIDER_KEY, +}; + +function withHome(run: () => T): T { + const previous = process.env.OPENCODEX_HOME; + const home = mkdtempSync(join(tmpdir(), "ocx-error-detail-unit-")); + process.env.OPENCODEX_HOME = home; + clearRequestLogsForTests(); + resetUsageReadCacheForTests(); + try { + return run(); + } finally { + clearRequestLogsForTests(); + resetUsageReadCacheForTests(); + if (previous === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = previous; + removeTreeWithRetry(home); + } +} + +function persisted(): string { + return readFileSync(usageLogPath(), "utf8"); +} + +describe("normalizeLogErrorCode", () => { + test("vocabulary codes and proxy-formatted status codes are kept", () => { + for (const code of LOG_ERROR_CODES) expect(normalizeLogErrorCode(code, 500)).toBe(code); + expect(normalizeLogErrorCode("http_418", 418)).toBe("http_418"); + }); + + test("anything else collapses to the proxy's code for the status", () => { + expect(normalizeLogErrorCode(PROVIDER_KEY, 400)).toBe("invalid_request_error"); + expect(normalizeLogErrorCode(PROVIDER_KEY, 401)).toBe("invalid_api_key"); + expect(normalizeLogErrorCode(PROVIDER_KEY, 403)).toBe("permission_denied"); + expect(normalizeLogErrorCode(PROVIDER_KEY, 429)).toBe("rate_limit_exceeded"); + expect(normalizeLogErrorCode(PROVIDER_KEY, 499)).toBe("client_closed_request"); + expect(normalizeLogErrorCode(PROVIDER_KEY, 503)).toBe("server_is_overloaded"); + expect(normalizeLogErrorCode(PROVIDER_KEY, 502)).toBe("upstream_server_error"); + expect(normalizeLogErrorCode(PROVIDER_KEY, 422)).toBe("http_422"); + expect(normalizeLogErrorCode(PROVIDER_KEY, 200)).toBe("upstream_error"); + expect(normalizeLogErrorCode(PROVIDER_KEY)).toBe("upstream_error"); + expect(normalizeLogErrorCode("http_999", 500)).toBe("upstream_server_error"); + expect(normalizeLogErrorCode("constructor", 400)).toBe("invalid_request_error"); + expect(normalizeLogErrorCode(undefined, 500)).toBeUndefined(); + expect(normalizeLogErrorCode("", 500)).toBeUndefined(); + }); +}); + +describe("errorDetailFor", () => { + test("a failed row with upstream evidence gets a condition and no upstream text", () => { + const detail = errorDetailFor({ status: 403, errorCode: PROVIDER_KEY, upstreamError: "User location is not supported", ...{ upstreamErrorCode: PROVIDER_KEY } }); + expect(detail).toEqual({ errorCode: "permission_denied", upstreamCondition: "location_unsupported" }); + }); + + test("local refusals and successes get no condition", () => { + expect(errorDetailFor({ status: 503, errorCode: "server_busy" })).toEqual({ errorCode: "server_busy" }); + expect(errorDetailFor({ status: 200, upstreamError: "rate limit" })).toEqual({}); + expect(errorDetailFor({ status: 200, terminalStatus: "incomplete", upstreamError: "Output reached the requested token limit" })).toEqual({}); + // A client close is not an upstream condition, whatever text the context captured. + expect(errorDetailFor({ status: 499, upstreamError: "client closed request" })).toEqual({}); + expect(errorDetailFor({ status: 502, errorCode: "client_closed_request", upstreamError: "x" })).toEqual({ errorCode: "client_closed_request" }); + }); + + test("a recorded condition is kept only when it is a known member", () => { + expect(errorDetailFor({ status: 429, upstreamCondition: "billing_exhausted", upstreamError: "rate limit" }).upstreamCondition).toBe("billing_exhausted"); + expect(errorDetailFor({ status: 429, upstreamCondition: PROVIDER_KEY }).upstreamCondition).toBeUndefined(); + // A recorded condition follows the derivation rules: none on a success or a client close. + expect(errorDetailFor({ status: 200, upstreamCondition: "rate_limited" }).upstreamCondition).toBeUndefined(); + expect(errorDetailFor({ status: 499, upstreamCondition: "rate_limited" }).upstreamCondition).toBeUndefined(); + expect(errorDetailFor({ status: 429, upstreamCondition: "constructor", upstreamError: "x" }).upstreamCondition).toBe("rate_limited"); + }); + + test("only closed proxy sentences become failure detail, rebuilt from their bounded number", () => { + expect(errorDetailFor({ status: 504, upstreamError: "Provider response-header timeout after 0300ms during web-search" }).failureDetail) + .toEqual({ code: "header_timeout", value: 300 }); + expect(errorDetailFor({ status: 502, upstreamError: "Provider connect timeout after 15000ms" }).failureDetail) + .toEqual({ code: "connect_timeout", value: 15000 }); + expect(errorDetailFor({ status: 499, upstreamError: "client closed request during web-search" }).failureDetail) + .toEqual({ code: "client_closed" }); + for (const text of ["Provider connect timeout after " + NUMERIC_KEY + "ms", "x Provider connect timeout after 1ms", + "Provider connect timeout after 1ms " + PROVIDER_KEY, "invalid key " + PROVIDER_KEY]) { + expect(errorDetailFor({ status: 502, upstreamError: text }).failureDetail).toBeUndefined(); + } + }); + + test("failure detail is a closed code with bounded parameters; free text never survives", () => { + expect(errorDetailFor({ status: 504, failureDetail: "anthropic passthrough timed out " + PROVIDER_KEY }).failureDetail).toBeUndefined(); + expect(errorDetailFor({ status: 504, failureDetail: { code: PROVIDER_KEY } }).failureDetail).toBeUndefined(); + expect(errorDetailFor({ status: 504, failureDetail: { code: "constructor" } }).failureDetail).toBeUndefined(); + expect(errorDetailFor({ status: 504, failureDetail: { code: "body_stall", value: 1000 } }).failureDetail) + .toEqual({ code: "body_stall", value: 1000 }); + // Extra keys, unsafe numbers and unknown types are dropped from an otherwise valid detail. + expect(errorDetailFor({ status: 502, failureDetail: { code: "body_overflow", value: Number(NUMERIC_KEY), note: PROVIDER_KEY } }).failureDetail) + .toEqual({ code: "body_overflow" }); + expect(errorDetailFor({ status: 400, failureDetail: { code: "provider_error", type: PROVIDER_KEY } }).failureDetail) + .toEqual({ code: "provider_error" }); + expect(errorDetailFor({ status: 400, failureDetail: { code: "provider_error", type: "permission_error" } }).failureDetail) + .toEqual({ code: "provider_error", type: "permission_error" }); + expect(errorDetailFor({ status: 400, failureDetail: { code: "client_closed", value: 5 } }).failureDetail) + .toEqual({ code: "client_closed" }); + }); +}); + +describe("Meta Muse reset time", () => { + const timestamp = Date.parse("2026-10-25T19:08:28Z"); + const resetAt = Date.parse("2026-10-26T00:00:00Z"); + const row = { provider: "meta-muse", status: 429, errorCode: "rate_limit_exceeded", timestamp, + upstreamError: "Subscription quota exhausted. Your usage window resets at 2026-10-26T00:00:00Z." }; + + test("only the exact sentence on a Muse 429 yields a bounded reset time", () => { + expect(deriveRateLimitResetAt(row)).toBe(resetAt); + for (const invalid of [{ ...row, provider: "xai" }, { ...row, status: 400 }, { ...row, errorCode: "insufficient_quota" }, + { ...row, upstreamError: row.upstreamError + " " }, { ...row, upstreamError: "prefix " + row.upstreamError }, + { ...row, upstreamError: "Subscription quota exhausted. Your usage window resets at 2099-10-26T00:00:00Z." }, + { ...row, upstreamError: "Subscription quota exhausted. Your usage window resets at 2026-10-25T00:00:00Z." }, + { ...row, timestamp: Number.NaN }]) expect(deriveRateLimitResetAt(invalid)).toBeUndefined(); + }); + + test("stored reset times are kept only inside the eight-day window", () => { + expect(boundedRateLimitResetAt(timestamp + RATE_LIMIT_RESET_MAX_MS, timestamp)).toBe(timestamp + RATE_LIMIT_RESET_MAX_MS); + expect(boundedRateLimitResetAt(timestamp + RATE_LIMIT_RESET_MAX_MS + 1, timestamp)).toBeUndefined(); + expect(boundedRateLimitResetAt(timestamp, timestamp)).toBeUndefined(); + expect(boundedRateLimitResetAt(timestamp + 0.5, timestamp)).toBeUndefined(); + expect(boundedRateLimitResetAt(String(resetAt), timestamp)).toBeUndefined(); + }); + + test("derive, persist, hydrate and render without the sentence", () => withHome(() => { + addRequestLog(log({ requestId: "muse-reset", ...row, accountLogLabel: "o527765" })); + const live = getRequestLogEntries().find(entry => entry.requestId === "muse-reset")!; + expect(live.rateLimitResetAt).toBe(resetAt); + expect(JSON.stringify(live)).not.toContain("Subscription quota exhausted"); + expect(persisted()).not.toContain("Subscription quota exhausted"); + const hydrated = requestLogEntryFromPersistedUsage(readUsageEntries().find(entry => entry.requestId === "muse-reset")!); + expect(hydrated.rateLimitResetAt).toBe(resetAt); + const report = museLimitReport(JSON.parse(JSON.stringify(hydrated)), "o527765", timestamp + 1000); + expect(report?.quota?.customWindows?.[0]?.resetAt).toBe(resetAt); + })); + + test("a legacy persisted sentence is recovered as the numeric reset on hydration", () => withHome(() => { + const legacy = { requestId: "muse-legacy", timestamp, provider: "meta-muse", model: "m", status: 429, durationMs: 1, + usageStatus: "unreported", errorCode: "rate_limit_exceeded", accountLogLabel: "o527765", upstreamError: row.upstreamError }; + writeFileSync(usageLogPath(), JSON.stringify(legacy) + "\n", { mode: 0o600 }); + resetUsageReadCacheForTests(); + const hydrated = requestLogEntryFromPersistedUsage(readUsageEntries().find(entry => entry.requestId === "muse-legacy")!); + expect(hydrated.rateLimitResetAt).toBe(resetAt); + expect((hydrated as Record).upstreamError).toBeUndefined(); + })); +}); + +describe("request-log rows keep only proxy-owned error facts", () => { + test("direct addRequestLog drops upstream text from the live row, ledger and hydration", () => withHome(() => { + const attempt = { ordinal: 1, provider: "openai", model: "model", adapter: "openai-chat", status: 400, durationMs: 1, + sendCount: 1, recoveryKinds: [], usageStatus: "unreported" as const, errorCode: PROVIDER_KEY, ...UPSTREAM_TEXT }; + addRequestLog(log({ requestId: "canary-direct", status: 400, errorCode: PROVIDER_KEY, attempts: [attempt], ...UPSTREAM_TEXT })); + const live = getRequestLogEntries().find(entry => entry.requestId === "canary-direct")!; + expect(JSON.stringify(live)).not.toContain(PROVIDER_KEY); + expect(JSON.stringify(live)).not.toContain(NUMERIC_KEY); + expect(live.errorCode).toBe("invalid_request_error"); + expect(live.attempts?.[0]?.errorCode).toBe("invalid_request_error"); + expect(live.upstreamCondition).toBe("request_rejected"); + const dto = JSON.stringify(requestLogDto(live)); + expect(dto).not.toContain(PROVIDER_KEY); + expect(dto).not.toContain(NUMERIC_KEY); + for (const field of ["upstreamError", "upstreamErrorCode", "upstreamErrorType", "upstreamRequestId"]) { + expect((live as Record)[field]).toBeUndefined(); + } + expect(persisted()).not.toContain(PROVIDER_KEY); + expect(persisted()).not.toContain(NUMERIC_KEY); + const hydrated = requestLogEntryFromPersistedUsage(readUsageEntries().find(entry => entry.requestId === "canary-direct")!); + expect(JSON.stringify(hydrated)).not.toContain(PROVIDER_KEY); + expect(hydrated.upstreamCondition).toBe("request_rejected"); + })); + + test("direct appendUsageEntry never writes upstream text", () => withHome(() => { + appendUsageEntry({ requestId: "canary-append", timestamp: Date.now(), provider: "openai", model: "m", status: 502, + durationMs: 1, usageStatus: "unreported", errorCode: PROVIDER_KEY, ...UPSTREAM_TEXT } as unknown as PersistedUsageEntry); + expect(persisted()).not.toContain(PROVIDER_KEY); + expect(persisted()).not.toContain(NUMERIC_KEY); + const row = JSON.parse(persisted().trim()) as Record; + expect(row.errorCode).toBe("upstream_server_error"); + expect(row.upstreamCondition).toBe("upstream_failed"); + })); + + test("legacy rows holding upstream text hydrate to closed facts only", () => withHome(() => { + const legacy = { requestId: "canary-legacy", timestamp: Date.now(), provider: "openai", model: "m", status: 403, + durationMs: 1, usageStatus: "unreported", errorCode: PROVIDER_KEY, + upstreamError: "Your organization must be verified " + PROVIDER_KEY, upstreamErrorCode: PROVIDER_KEY, upstreamRequestId: PROVIDER_KEY }; + writeFileSync(usageLogPath(), JSON.stringify(legacy) + "\n", { mode: 0o600 }); + resetUsageReadCacheForTests(); + const entry = readUsageEntries().find(row => row.requestId === "canary-legacy")!; + expect(JSON.stringify(entry)).not.toContain(PROVIDER_KEY); + const hydrated = requestLogEntryFromPersistedUsage(entry); + expect(JSON.stringify(hydrated)).not.toContain(PROVIDER_KEY); + expect(hydrated.errorCode).toBe("permission_denied"); + expect(hydrated.upstreamCondition).toBe("account_verification_required"); + })); + + test("a local diagnostic is failure detail, not upstream evidence", () => { + const final = (record: (ctx: RequestLogContext) => void, status: number) => { + const ctx: RequestLogContext = { model: "m", provider: "anthropic-native" }; + record(ctx); + const rows: RequestLogEntry[] = []; + addFinalRequestLog("local-" + status, Date.now(), ctx, status, { closeReason: "non_stream" }, row => rows.push(row)); + return rows[0]!; + }; + const timeout = final(ctx => recordLocalFailureDetail(ctx, "anthropic passthrough timed out waiting for response headers", + { code: "header_timeout" }), 504); + expect(timeout.failureDetail).toEqual({ code: "header_timeout" }); + expect(timeout.upstreamCondition).toBeUndefined(); + const restated = final(ctx => recordLocalFailureDetail(ctx, "Provider error 429: rate_limit_error", + { code: "provider_error", type: "rate_limit_error" }, { upstreamEvidence: true }), 429); + expect(restated.failureDetail).toEqual({ code: "provider_error", type: "rate_limit_error" }); + expect(restated.upstreamCondition).toBe("rate_limited"); + }); + + test("projection keeps identity when nothing changes", () => { + const entry = log({ requestId: "unchanged", status: 503, errorCode: "server_busy" }); + expect(projectErrorDetail(entry)).toBe(entry); + const changed = log({ requestId: "changed", status: 503, errorCode: "server_busy", ...UPSTREAM_TEXT }); + expect(projectErrorDetail(changed)).not.toBe(changed); + }); +}); diff --git a/tests/usage/request-log-identity-bounds.test.ts b/tests/usage/request-log-identity-bounds.test.ts new file mode 100644 index 00000000000..cb436a02828 --- /dev/null +++ b/tests/usage/request-log-identity-bounds.test.ts @@ -0,0 +1,137 @@ +import { describe, expect, test } from "bun:test"; +import { mkdtempSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { boundedServiceTier } from "../../src/lib/response-service-tier"; +import { boundedModelIdentity, knownModelIdentity } from "../../src/lib/model-identity"; +import { + addFinalRequestLog, addRequestLog, clearRequestLogsForTests, getRequestLogEntries, inspectResponseLogJson, + requestLogEntryFromPersistedUsage, type RequestLogContext, type RequestLogEntry, +} from "../../src/server/request-log"; +import { requestLogDto } from "../../src/server/management/shared"; +import { readUsageEntries, resetUsageReadCacheForTests, usageLogPath } from "../../src/usage/log"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { log } from "../helpers/request-log-entry"; + +// A provider key with no recognizable prefix, so pattern-based redaction cannot spot it. +const PROVIDER_KEY = "zq7Vb2LmN4pX9tR1sK8wD3fH6jY0cA5e"; + +function withHome(run: () => T): T { + const previous = process.env.OPENCODEX_HOME; + const home = mkdtempSync(join(tmpdir(), "ocx-identity-bounds-")); + process.env.OPENCODEX_HOME = home; + clearRequestLogsForTests(); + resetUsageReadCacheForTests(); + try { + return run(); + } finally { + clearRequestLogsForTests(); + resetUsageReadCacheForTests(); + if (previous === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = previous; + removeTreeWithRetry(home); + } +} + +describe("response service tier is a closed member", () => { + test("members are kept (case-folded); anything else is omitted", () => { + for (const tier of ["auto", "default", "flex", "scale", "priority", "fast", "standard", "ultrafast"]) { + expect(boundedServiceTier(tier)).toBe(tier); + } + expect(boundedServiceTier(" Priority ")).toBe("priority"); + for (const value of [PROVIDER_KEY, "performance", "", "priority " + PROVIDER_KEY, 1, null]) { + expect(boundedServiceTier(value)).toBeUndefined(); + } + }); + + test("capture from a response payload keeps only members", () => { + const ctx: RequestLogContext = { model: "m", provider: "openai" }; + inspectResponseLogJson(ctx, JSON.stringify({ type: "response.completed", response: { status: "completed", service_tier: PROVIDER_KEY } })); + expect(ctx.responseServiceTier).toBeUndefined(); + const known: RequestLogContext = { model: "m", provider: "openai" }; + inspectResponseLogJson(known, JSON.stringify({ type: "response.completed", response: { status: "completed", service_tier: "flex" } })); + expect(known.responseServiceTier).toBe("flex"); + }); + + test("live row, attempts, ledger, hydration and the logs DTO never carry an unknown tier", () => withHome(() => { + const attempt = { ordinal: 1, provider: "openai", model: "m", adapter: "openai-responses", status: 200, durationMs: 1, + sendCount: 1, recoveryKinds: [], usageStatus: "unreported" as const, + tierOutcome: { fastOutcome: "not-requested", confirmation: "unknown", responseServiceTier: PROVIDER_KEY } }; + addRequestLog(log({ requestId: "tier-canary", status: 200, responseServiceTier: PROVIDER_KEY, + tierOutcome: { fastOutcome: "not-requested", confirmation: "unknown", responseServiceTier: PROVIDER_KEY }, + attempts: [attempt] } as unknown as RequestLogEntry)); + const live = getRequestLogEntries().find(entry => entry.requestId === "tier-canary")!; + expect(JSON.stringify(live)).not.toContain(PROVIDER_KEY); + expect(JSON.stringify(requestLogDto(live))).not.toContain(PROVIDER_KEY); + expect(readFileSync(usageLogPath(), "utf8")).not.toContain(PROVIDER_KEY); + const hydrated = requestLogEntryFromPersistedUsage(readUsageEntries().find(entry => entry.requestId === "tier-canary")!); + expect(JSON.stringify(hydrated)).not.toContain(PROVIDER_KEY); + })); + + test("the hydration projection bounds tiers itself, without relying on the disk reader", () => { + const outcome = { fastOutcome: "not-requested", confirmation: "unknown", responseServiceTier: PROVIDER_KEY }; + const attempt = { ordinal: 1, provider: "openai", model: "m", adapter: "openai-responses", status: 200, durationMs: 1, + sendCount: 1, recoveryKinds: [], usageStatus: "unreported", tierOutcome: { ...outcome } }; + const raw = { requestId: "raw-tier", timestamp: 1, model: "m", provider: "openai", status: 200, durationMs: 1, + usageStatus: "unreported", responseServiceTier: PROVIDER_KEY, tierOutcome: { ...outcome }, attempts: [attempt] }; + const hydrated = requestLogEntryFromPersistedUsage(raw as unknown as Parameters[0]); + expect(JSON.stringify(hydrated)).not.toContain(PROVIDER_KEY); + expect(hydrated.responseServiceTier).toBeUndefined(); + expect(hydrated.tierOutcome).toEqual({ fastOutcome: "not-requested", confirmation: "unknown" }); + // The caller's row is not edited in place. + expect(attempt.tierOutcome.responseServiceTier).toBe(PROVIDER_KEY); + const known = requestLogEntryFromPersistedUsage({ ...raw, responseServiceTier: "Priority", attempts: [] } as unknown as Parameters[0]); + expect(known.responseServiceTier).toBe("priority"); + }); +}); + +describe("model identity fields share one bound", () => { + test("the grammar is [A-Za-z0-9._:/@-] up to 128 characters", () => { + expect(boundedModelIdentity("anthropic/claude-opus-5-5")).toBe("anthropic/claude-opus-5-5"); + expect(boundedModelIdentity("accounts/fireworks/models/llama-v3p1:latest@2026")).toBe("accounts/fireworks/models/llama-v3p1:latest@2026"); + expect(boundedModelIdentity("m".repeat(128))).toBe("m".repeat(128)); + for (const value of ["m".repeat(129), "model+" + PROVIDER_KEY, "model " + PROVIDER_KEY, "sk-proj-" + PROVIDER_KEY, "", 5]) { + expect(boundedModelIdentity(value)).toBeUndefined(); + } + }); + + test("served and resolved models are kept only as model ids the route already knows, on every surface", () => withHome(() => { + // A prefixless key fits the identifier grammar, so only the known-model rule can refuse it. + expect(boundedModelIdentity(PROVIDER_KEY)).toBe(PROVIDER_KEY); + expect(knownModelIdentity(PROVIDER_KEY, ["m", "gpt-5.5"])).toBeUndefined(); + expect(knownModelIdentity("gpt-5.6-sol")).toBe("gpt-5.6-sol"); + expect(knownModelIdentity("m", ["m"])).toBe("m"); + addRequestLog(log({ requestId: "identity-canary", status: 200, servedModel: "gpt-5.6-sol", resolvedModel: PROVIDER_KEY })); + addRequestLog(log({ requestId: "identity-unknown", status: 200, servedModel: "gpt-served", resolvedModel: "gpt-resolved" })); + const ctx: RequestLogContext = { model: "m", provider: "openai", wireModel: "m-wire", servedModel: PROVIDER_KEY, resolvedModel: "m-wire" }; + const rows: RequestLogEntry[] = []; + addFinalRequestLog("identity-final", Date.now(), ctx, 200, { closeReason: "terminal" }, row => rows.push(row)); + addRequestLog(rows[0]!); + // The response-body capture path applies the same rule before anything is recorded. + const observed: RequestLogContext = { model: "m", provider: "openai" }; + inspectResponseLogJson(observed, JSON.stringify({ model: PROVIDER_KEY })); + expect(observed.servedModel).toBeUndefined(); + inspectResponseLogJson(observed, JSON.stringify({ model: "gpt-5.6-sol" })); + expect(observed.servedModel).toBe("gpt-5.6-sol"); + for (const id of ["identity-canary", "identity-unknown", "identity-final"]) { + const live = getRequestLogEntries().find(entry => entry.requestId === id)!; + expect(live).toBeDefined(); + expect(JSON.stringify(live)).not.toContain(PROVIDER_KEY); + expect(JSON.stringify(requestLogDto(live))).not.toContain(PROVIDER_KEY); + } + const canary = getRequestLogEntries().find(entry => entry.requestId === "identity-canary")!; + expect(canary.servedModel).toBe("gpt-5.6-sol"); + expect(canary.resolvedModel).toBeUndefined(); + const unknown = getRequestLogEntries().find(entry => entry.requestId === "identity-unknown")!; + expect([unknown.servedModel, unknown.resolvedModel]).toEqual([undefined, undefined]); + const final = getRequestLogEntries().find(entry => entry.requestId === "identity-final")!; + expect([final.servedModel, final.resolvedModel]).toEqual([undefined, "m-wire"]); + expect(readFileSync(usageLogPath(), "utf8")).not.toContain(PROVIDER_KEY); + const persisted = readUsageEntries(); + expect(persisted.length).toBeGreaterThanOrEqual(3); + for (const entry of persisted) expect(JSON.stringify(requestLogEntryFromPersistedUsage(entry))).not.toContain(PROVIDER_KEY); + // Hydration applies the rule itself to a row that did not come through the disk reader. + const hydrated = requestLogEntryFromPersistedUsage({ ...persisted[0]!, servedModel: PROVIDER_KEY, resolvedModel: PROVIDER_KEY }); + expect(JSON.stringify(hydrated)).not.toContain(PROVIDER_KEY); + })); +}); diff --git a/tests/usage/request-log-nonstream.test.ts b/tests/usage/request-log-nonstream.test.ts index bd6c3759008..809213100a0 100644 --- a/tests/usage/request-log-nonstream.test.ts +++ b/tests/usage/request-log-nonstream.test.ts @@ -39,11 +39,11 @@ describe("deferred non-stream request log integration", () => { }); test("inspects complete small JSON using the existing metadata parser", async () => { - const payload = JSON.stringify({ model: "resolved-model", usage: { input_tokens: 3, output_tokens: 2, total_tokens: 5 } }); + const payload = JSON.stringify({ model: "gpt-5.6-sol", usage: { input_tokens: 3, output_tokens: 2, total_tokens: 5 } }); const { result, entries } = tracked(new Response(payload, { headers: { "content-type": "application/json" } })); expect(await result.text()).toBe(payload); expect(entries).toHaveLength(1); - expect(entries[0]?.resolvedModel).toBe("resolved-model"); + expect(entries[0]?.resolvedModel).toBe("gpt-5.6-sol"); expect(entries[0]?.status).toBe(200); }); @@ -55,6 +55,7 @@ describe("deferred non-stream request log integration", () => { const logCtx: RequestLogContext = { model: "requested-model", provider: "fixture-provider", + wireModel: "already-inspected", resolvedModel: "already-inspected", usage: { inputTokens: 3, outputTokens: 2, totalTokens: 5 }, }; @@ -87,8 +88,10 @@ describe("deferred non-stream request log integration", () => { const { result, entries } = tracked(new Response(payload, { status: 502, headers: { "content-type": "text/plain" } })); expect(await result.text()).toBe(payload); expect(entries).toHaveLength(1); - expect(entries[0]?.upstreamError?.startsWith("synthetic provider failed:")).toBe(true); - expect(entries[0]?.upstreamError?.length).toBeLessThanOrEqual(500); + // The parser path still classifies the text; the row keeps the closed condition only. + expect(entries[0]?.upstreamError).toBeUndefined(); + expect(entries[0]?.upstreamCondition).toBe("upstream_failed"); + expect(JSON.stringify(entries[0])).not.toContain("synthetic provider failed"); }); test("cancellation follows the existing 499 convention without changing wire status", async () => { diff --git a/tests/usage/request-log-served-model.test.ts b/tests/usage/request-log-served-model.test.ts index d41b4e57559..dc5928b2cb1 100644 --- a/tests/usage/request-log-served-model.test.ts +++ b/tests/usage/request-log-served-model.test.ts @@ -17,17 +17,19 @@ import { import { removeTreeWithRetry } from "../helpers/remove-tree"; import { log } from "../helpers/request-log-entry"; -test("upstream served model persists only when it is a plausible bounded identifier", () => { +test("upstream served model persists only when it is a model id the route or catalog already knows", () => { const home = mkdtempSync(join(tmpdir(), "ocx-served-model-")); const previousHome = process.env.OPENCODEX_HOME; process.env.OPENCODEX_HOME = home; clearRequestLogsForTests(); resetUsageReadCacheForTests(); try { - const valid = "vendor/model.v2:@+-_"; + // A catalog model for the selected provider; anything else, however well formed, is not recorded. + const valid = "gpt-5.5"; // Credential-shaped but inside the identifier alphabet; built at runtime so no token-like literal is committed. const credentialShaped = ["eyJ" + "a".repeat(12), "b".repeat(12), "c".repeat(8)].join("."); - const invalid = ["m".repeat(201), "model\ninjected", "model with space", "model\twith-tab", credentialShaped]; + const invalid = ["m".repeat(129), "model+plus", "model\ninjected", "model with space", "model\twith-tab", credentialShaped, + "vendor/model.v2:@-_", "zq7Vb2LmN4pX9tR1sK8wD3fH6jY0cA5e"]; for (const [index, model] of [valid, ...invalid].entries()) { const context: RequestLogContext = { model: "route-model", @@ -92,8 +94,12 @@ test("the client selector echoed in response.model is not recorded as the served // A model the upstream really answered with is still an observation. const rerouted = anthropicContext(); - applyResponseLogMetadata(rerouted, { response: { model: "claude-opus-5-1" } }); - expect(rerouted.servedModel).toBe("claude-opus-5-1"); + applyResponseLogMetadata(rerouted, { response: { model: "claude-sonnet-5-5" } }); + expect(rerouted.servedModel).toBe("claude-sonnet-5-5"); + // A model the provider catalog does not know is not recorded, whatever its shape. + const unknown = anthropicContext(); + applyResponseLogMetadata(unknown, { response: { model: "claude-opus-5-1" } }); + expect(unknown.servedModel).toBeUndefined(); // A combo parent inherits a child's echo of the combo selector. const combo: RequestLogContext = { @@ -128,6 +134,9 @@ test("rows persisted with a selector echo lose it on read", () => { })); expect(combo).not.toHaveProperty("servedModel"); - const genuine = normalizeUsageEntryForTest(row({ wireModel: "claude-opus-5-5", servedModel: "claude-opus-5-1" })); - expect(genuine.servedModel).toBe("claude-opus-5-1"); + const genuine = normalizeUsageEntryForTest(row({ wireModel: "claude-opus-5-5", servedModel: "claude-sonnet-5-5" })); + expect(genuine.servedModel).toBe("claude-sonnet-5-5"); + const unknown = normalizeUsageEntryForTest(row({ wireModel: "claude-opus-5-5", servedModel: "claude-opus-5-1", resolvedModel: "claude-opus-5-1" })); + expect(unknown).not.toHaveProperty("servedModel"); + expect(unknown).not.toHaveProperty("resolvedModel"); }); diff --git a/tests/usage/request-log.test.ts b/tests/usage/request-log.test.ts index 29a7c38ee1f..a87d350ff59 100644 --- a/tests/usage/request-log.test.ts +++ b/tests/usage/request-log.test.ts @@ -816,7 +816,7 @@ describe("request log metadata", () => { expect(entries[0]).toMatchObject({ status: 403, errorCode: "permission_denied", - upstreamError: "Provider error 403", + upstreamCondition: "access_denied", }); const subEntries: RequestLogEntry[] = []; @@ -1185,7 +1185,7 @@ describe("request log metadata", () => { expect(entries).toHaveLength(1); expect(entries[0]).toMatchObject({ terminalStatus: "failed", - upstreamError: cursorMessage, + upstreamCondition: "rate_limited", status: 429, errorCode: "rate_limit_exceeded", }); @@ -1217,7 +1217,7 @@ describe("request log metadata", () => { expect(entries).toHaveLength(1); expect(entries[0]).toMatchObject({ terminalStatus: "failed", - upstreamError: "blocked", + upstreamCondition: "request_rejected", status: 400, errorCode: "cyber_policy", closeReason: "terminal", @@ -1252,7 +1252,7 @@ describe("request log metadata", () => { expect(entries).toHaveLength(1); expect(entries[0]).toMatchObject({ terminalStatus: "failed", - upstreamError: "blocked", + upstreamCondition: "request_rejected", status: 400, errorCode: "cyber_policy", closeReason: "terminal", @@ -1290,7 +1290,7 @@ describe("request log metadata", () => { expect(entries).toHaveLength(1); expect(entries[0]).toMatchObject({ terminalStatus: "failed", - upstreamError: policyMessage, + upstreamCondition: "request_rejected", status: 400, errorCode: "cyber_policy", closeReason: "terminal", @@ -1418,7 +1418,6 @@ describe("request log metadata", () => { expect(entries).toHaveLength(1); expect(entries[0]).toMatchObject({ terminalStatus: "failed", - upstreamError: message, status: 499, errorCode: "client_closed_request", closeReason: "client_cancel", @@ -1443,7 +1442,6 @@ describe("request log metadata", () => { status: 499, errorCode: "client_closed_request", closeReason: "client_cancel", - upstreamError: "client closed request during web-search", }); }); @@ -1515,8 +1513,8 @@ describe("request log metadata", () => { const text = await response.text(); expect(text).toContain("\"message\":\"unauthorized: Bearer secret-leak-abc123\""); expect(entries).toHaveLength(1); - expect(entries[0].upstreamError).not.toContain("secret-leak-abc123"); - expect(entries[0].upstreamError).toContain("[REDACTED]"); + expect(JSON.stringify(entries[0])).not.toContain("secret-leak-abc123"); + expect(entries[0].upstreamError).toBeUndefined(); }); test("plain-text upstream errors are captured in deferred logging", async () => { @@ -1532,7 +1530,7 @@ describe("request log metadata", () => { const text = await response.text(); expect(text).toBe("provider says nope"); expect(entries).toHaveLength(1); - expect(entries[0].upstreamError).toBe("provider says nope"); + expect(entries[0].upstreamError).toBeUndefined(); expect(entries[0].upstreamCondition).toBeDefined(); }); test("deferred SSE logging uses adapter-provided Kiro log input tokens", async () => { @@ -1701,7 +1699,7 @@ describe("request log metadata", () => { }); }); - test("deferred SSE logging surfaces upstream_stall_timeout reason as upstreamError", async () => { + test("deferred SSE logging surfaces upstream_stall_timeout reason as failure detail", async () => { const entries: RequestLogEntry[] = []; const incompletePayload = JSON.stringify({ type: "response.incomplete", @@ -1731,8 +1729,7 @@ describe("request log metadata", () => { status: 502, errorCode: "upstream_server_error", }); - expect(entries[0].upstreamError).toContain("upstream_stall_timeout"); - expect(entries[0].upstreamError).toContain("Upstream stalled"); + expect(entries[0].failureDetail).toEqual({ code: "stall_timeout" }); }); test("deferred SSE logging treats the requested output limit as a successful terminal", async () => { @@ -1766,12 +1763,14 @@ describe("request log metadata", () => { status: 200, usageStatus: "reported", usage: { inputTokens: 9, outputTokens: 64 }, - upstreamError: "Output reached the requested token limit (max_output_tokens)", + failureDetail: { code: "output_limit" }, }); + // A successful output-limit terminal is not an upstream failure. + expect(entries[0].upstreamCondition).toBeUndefined(); expect(entries[0]).not.toHaveProperty("errorCode"); }); - test("deferred SSE logging surfaces adapter_eof reason as upstreamError", async () => { + test("deferred SSE logging surfaces adapter_eof reason as failure detail", async () => { const entries: RequestLogEntry[] = []; const incompletePayload = JSON.stringify({ type: "response.incomplete", @@ -1801,8 +1800,7 @@ describe("request log metadata", () => { status: 502, errorCode: "upstream_server_error", }); - expect(entries[0].upstreamError).toContain("adapter_eof"); - expect(entries[0].upstreamError).toContain("ended unexpectedly"); + expect(entries[0].failureDetail).toEqual({ code: "adapter_eof" }); }); }); @@ -1858,6 +1856,8 @@ describe("request log restart hydrate", () => { closeReason: "terminal", upstreamError: "socket connection was closed unexpectedly", }; + // Legacy upstream text is read once to classify the failure and never returned. + expect(requestLogEntryFromPersistedUsage(persisted).upstreamError).toBeUndefined(); expect(requestLogEntryFromPersistedUsage(persisted)).toEqual({ requestId: "ocx-revive", timestamp: 1_800_000_000_000, @@ -1879,7 +1879,7 @@ describe("request log restart hydrate", () => { errorCode: "upstream_server_error", terminalStatus: "failed", closeReason: "terminal", - upstreamError: "socket connection was closed unexpectedly", + upstreamCondition: "upstream_failed", }); }); @@ -1922,7 +1922,7 @@ describe("request log restart hydrate", () => { requestId: "ocx-sticky-502", status: 502, errorCode: "upstream_server_error", - upstreamError: "Provider unreachable", + upstreamCondition: "upstream_failed", requestedEffort: "xhigh", shadowCallRewrittenFrom: "gpt-5.6-luna", }); diff --git a/tests/usage/upstream-failure-diagnostics.test.ts b/tests/usage/upstream-failure-diagnostics.test.ts index 85adb5e8bf8..4ed9589b381 100644 --- a/tests/usage/upstream-failure-diagnostics.test.ts +++ b/tests/usage/upstream-failure-diagnostics.test.ts @@ -42,7 +42,9 @@ test("upstream failures record the error code and request id without the body", expect(log.upstreamErrorCode).toBe("server_error"); expect(log.upstreamErrorType).toBe("server_error"); expect(warnings.join("\n")).not.toContain("secret upstream body"); - expect(warnings.some(line => line.includes("code=server_error") && line.includes("request_id=req_abc123"))).toBe(true); + // Service logs persist: only closed-vocabulary values are printed, never an upstream request id. + expect(warnings.some(line => line.includes("type=server_error"))).toBe(true); + expect(warnings.join("\n")).not.toContain("req_abc123"); }); @@ -131,7 +133,7 @@ test("an unrecognized bare top-level code is never recorded as a diagnostic", () }); -test("final request rows expose original upstream error type, code, request id and mapped status", () => { +test("final request rows keep the mapped status and closed condition; upstream diagnostics stay on the context", () => { const log = context(); noteUpstreamRequestId(log, new Headers({ "openai-request-id": "req_diagnostic_fixture" })); inspectResponseLogJson(log, JSON.stringify({ type: "error", @@ -141,9 +143,12 @@ test("final request rows expose original upstream error type, code, request id a { terminalStatus: "failed", closeReason: "terminal" }, entry => rows.push(entry)); expect(rows).toHaveLength(1); expect(rows[0]!.status).toBe(503); - expect(rows[0]!.upstreamErrorType).toBe("overloaded_error"); - expect(rows[0]!.upstreamErrorCode).toBe("overloaded_error"); - expect(rows[0]!.upstreamRequestId).toBe("req_diagnostic_fixture"); + // The context keeps the bounded upstream diagnostics; the row keeps only the closed condition. + expect(log.upstreamErrorType).toBe("overloaded_error"); + expect(log.upstreamErrorCode).toBe("overloaded_error"); + expect(log.upstreamRequestId).toBe("req_diagnostic_fixture"); + expect(rows[0]!.upstreamCondition).toBe("upstream_unavailable"); + expect(JSON.stringify(rows[0])).not.toContain("req_diagnostic_fixture"); }); // #6740: the Codex WebSocket wraps a backend failure as {type:"error", status|status_code, error}. @@ -202,7 +207,8 @@ test("a wrapped 503 reaches the final row as an upstream overload instead of a g expect(rows[0]!.status).toBe(503); expect(rows[0]!.errorCode).toBe("server_is_overloaded"); expect(rows[0]!.failureCause).toBe("upstream-declined"); - expect(rows[0]!.upstreamErrorCode).toBe("server_error"); + expect(log.upstreamErrorCode).toBe("server_error"); + expect(rows[0]!.upstreamErrorCode).toBeUndefined(); // Same transient class as the 502 it replaces: account health and rotation do not move. expect(classifyCodexUpstreamOutcome(503)).toBe(classifyCodexUpstreamOutcome(502)); }); diff --git a/tests/usage/usage-failure-persistence.test.ts b/tests/usage/usage-failure-persistence.test.ts index c53d740b839..340a2b96587 100644 --- a/tests/usage/usage-failure-persistence.test.ts +++ b/tests/usage/usage-failure-persistence.test.ts @@ -45,7 +45,10 @@ test("5xx entry persists failure diagnostics to usage.jsonl (survives the ring b expect(row.errorCode).toBe("upstream_server_error"); expect(row.terminalStatus).toBe("failed"); expect(row.closeReason).toBe("terminal"); - expect(row.upstreamError).toContain("request ID test-42"); + // The persisted row keeps the classified condition, never the provider's words. + expect(row.upstreamError).toBeUndefined(); + expect(row.upstreamCondition).toBe("upstream_failed"); + expect(JSON.stringify(row)).not.toContain("test-42"); }); test("successful entry keeps the existing persisted shape (no diagnostic fields)", () => { diff --git a/tests/web-search/web-search-timeout-contract.test.ts b/tests/web-search/web-search-timeout-contract.test.ts index 39e152d57ed..ecb1f746b12 100644 --- a/tests/web-search/web-search-timeout-contract.test.ts +++ b/tests/web-search/web-search-timeout-contract.test.ts @@ -233,7 +233,7 @@ describe("web-search timeout runtime contracts", () => { status: 504, errorCode: "upstream_server_error", closeReason: "non_stream", - upstreamError: message, + failureDetail: { code: "header_timeout", value: connectTimeoutMs }, }); expect(entries[0].terminalStatus).toBeUndefined(); }, 1_000); @@ -278,7 +278,7 @@ describe("web-search timeout runtime contracts", () => { errorCode: "upstream_server_error", terminalStatus: "failed", closeReason: "terminal", - upstreamError: message, + failureDetail: { code: "generation_timeout", value: stallMs }, }); }, 1_000); @@ -331,7 +331,7 @@ describe("web-search timeout runtime contracts", () => { status: 504, terminalStatus: "failed", closeReason: "terminal", - upstreamError: message, + failureDetail: { code: "generation_timeout", value: stallMs }, }); }, 1_000); From 43e2e4e5765254aabc1a6f22d5d114db9da863b5 Mon Sep 17 00:00:00 2001 From: JUN Date: Tue, 3 Nov 2026 03:18:53 +0900 Subject: [PATCH 12/43] fix(link): keep Windows containment refusal at 126; correct the #8100 fan-out test fixture (#8106) * fix(link): keep Windows containment refusal at 126 and correct the fan-out test fixture #8100 packed every Windows remote command and inflated it before the containment helper existed, outside any try. A Child whose PowerShell runs in Constrained Language Mode could not inflate it and exited 1, which the Home reads as an ordinary ocx failure. Guard only the inflate so it exits 126; Invoke-Expression stays outside the guard so the inflated script's own errors and exit codes pass through. The new local-only fan-out test spawned the CLI with a stripped POSIX environment (no SystemRoot, a ':' PATH, a sh-script ssh) and without the owned-service-home preload that keeps Codex write admission away from the runner's real Task Scheduler. It timed out on Windows and could not prove "no ssh" there at all. Give CLI children the inherited environment and the owned-service-home fixture, add a Bun-spawn ssh sentinel with positive controls, and prove local-only in process as well. * docs(structure): separate inflation refusal from contained-run failures in the Windows contract * docs(devlog): record the measured encoded-size cost of the inflate guard * docs(devlog): quote the shipped wrapper and control in the plan * test(link): pin the fan-out Home outcome and keep inflated script errors out of 126 Address review: the local-only subprocess case now asserts the Home outcome its fixture is built for, and a Windows case shows an error raised by an inflated script keeps its own exit instead of the containment refusal (packedPowerShellArgv is exported for it). * ci(test): record durations for the #8099/#8100/#8103/#8104 test files and shorten the pinned-sync watchdog case PR test 4/4 at 7f4924ec4 hit the 15-minute job timeout (job 125416446261) with no failing test. Its merge with dev ran tests/update/update-orchestrated-entry.test.ts (#8103) for 98 s, and like the other files #8099, #8100, #8103 and #8104 added it had no recorded duration and weighed the 176 ms median: the shard predicted 728 s and ran 852 s of tests. Both tables are refreshed with scripts/ci/test-durations.ts. Linux/macOS: run 41462914814 (dev 09b558580, Linux and macOS shards) plus the Linux shards of pull_request runs 41485932590, 41482553737 (#8103) and 41483744349 (#8104); every test file now has a row and the four Linux shards predict 716 s each. Windows: run 41462914814's eleven shards; the #8103/#8104 files and three files of the two stopped shards have no Windows measurement yet and still weigh the median. The POSIX "version writer ignoring signals" case waited out the production ten-second watchdog. It now runs the same script with a one-second watchdog and asserts the shipped script keeps "sleep 10": the case drops from about 10.4 s to 1.4 s. --- .../261103_fix_8100_windows_batch/010_plan.md | 70 + scripts/ci/test-durations.tsv | 5693 +++++++++-------- scripts/ci/test-durations.windows.tsv | 4879 +++++++------- src/link/remote-windows.ts | 14 +- structure/remote-link.md | 2 +- tests/cli/sync-command-fanout.test.ts | 126 +- tests/clients/link-pinned-sync-argv.test.ts | 10 +- tests/clients/link-ssh-argv-discovery.test.ts | 33 +- tests/helpers/ssh-spawn-sentinel-preload.ts | 39 + 9 files changed, 5581 insertions(+), 5285 deletions(-) create mode 100644 devlog/_plan/261103_fix_8100_windows_batch/010_plan.md create mode 100644 tests/helpers/ssh-spawn-sentinel-preload.ts diff --git a/devlog/_plan/261103_fix_8100_windows_batch/010_plan.md b/devlog/_plan/261103_fix_8100_windows_batch/010_plan.md new file mode 100644 index 00000000000..8a0bb5c5e1e --- /dev/null +++ b/devlog/_plan/261103_fix_8100_windows_batch/010_plan.md @@ -0,0 +1,70 @@ +# Fix the red dev batch: #8100 Windows containment exit and sync fan-out fixture (C3) + +Batch run https://github.com/lidge-jun/opencodex/actions/runs/41462914814 at `09b558580` failed two Windows shards. The tree before #8100 (`be51cb817`, run 41455278872) was green on every platform, and both failures trace to #8100 (`4948c04d9`). + +## Failure 1 — product regression: an uncontainable Windows ocx exits 1 instead of 126 + +`tests/clients/link-ssh-argv-discovery.test.ts` "a Windows ocx that cannot be contained in a kill-on-close job is refused before it runs" expects `WINDOWS_CONTAINMENT_EXIT` (126) and received 1 (windows 10/11). + +Cause. #8100 moved `windowsNativeArgv`, `windowsOcxArgv` and the new `windowsPinnedSyncArgv` onto `packedPowerShellArgv`. Its wrapper inflates the whole script with `[IO.MemoryStream]::new`, `[IO.Compression.DeflateStream]::new` and `[IO.StreamReader]::new`, then `Invoke-Expression`s it. That stage runs before the inflated script defines `Fail` (`exit 126`), outside any `try`, with the default `Continue` error preference. Constrained Language Mode (the AppLocker/WDAC case `structure/remote-link.md` names) blocks construction of those non-core types, so the inflate errors, `Invoke-Expression` receives `$null`, and `powershell.exe` ends with 1. Before #8100 only the helper source was deflated, and its inflation sat inside `try{Add-Type ...}catch{Fail}`, so the same session exited 126. + +Why it matters. 126 is the documented contract "the remote ocx could not be contained; nothing ran", and the Home classifies it as `child-ocx-not-contained` (`src/cli/sync-fanout.ts` `classifySyncResult`). An exit of 1 reads as an ordinary ocx failure (`child-sync-failed` for fan-out, a generic failure for link commands). Nothing runs uncontained, but the refusal is misreported. + +Change (`src/link/remote-windows.ts`, `packedPowerShellArgv` only): + +```text +$ocxPacked='' +$ErrorActionPreference='Stop';try{$b=...;$r=[IO.StreamReader]::new(...);$s=$r.ReadToEnd()}catch{try{[Console]::Error.WriteLine('Refusing to run ocx.exe outside a kill-on-close job.')}catch{$null=$_};exit 126};Invoke-Expression $s +``` + +- Only the inflate is inside the `try`. `Invoke-Expression` stays outside, so an error or exit code from the inflated script is never relabelled 126. CI already shows an inner `exit 23` propagating through `Invoke-Expression` ("Windows native execution preserves ... stdin bytes"). +- `$ErrorActionPreference='Stop'` makes every inflate failure terminating, so the `catch` sees it. The inflated `NATIVE_PROCESS` sets `Stop` on its first line already, so the inner script runs under the same preference as today. +- The message write is itself guarded because Constrained Language Mode also blocks `[Console]`, which matches the existing `Fail`. +- Encoded size, measured with realistic inputs: native 5,320 → 5,736, ocx 5,820 → 6,240, pinned sync 6,924 → 7,344 (measured on `09b558580` and on the fix), all under `POWERSHELL_ENCODED_MAX` (8,000). The existing `powershellArgv` throw still guards longer inputs. +- `unpackPowerShell`, `windowsScriptData` and `windowsScriptHelperSource` find `$ocxPacked='...'` by pattern and are unaffected. + +Regression tests (`tests/clients/link-ssh-argv-discovery.test.ts`, Windows-only, same file and seam as the failing case): run all three packed builders (`windowsNativeArgv` with the marker script, `windowsOcxArgv`, `windowsPinnedSyncArgv`) in a session that enters ConstrainedLanguage first, and expect 126 for each, with the native marker still absent. The two discovery builders run with `USERPROFILE`, `LOCALAPPDATA` and `ProgramFiles` pointed at an empty temp directory, and `PATH` set to `%SystemRoot%\System32` only. That directory holds no `ocx.exe`, and the session is launched by the absolute `%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe`. No candidate exists, so a 126 can only be the refusal: a candidate cannot produce it, and an unguarded run would exit 1 or 127. The marker additionally proves "nothing ran" for the native builder. The failing case on `dev` is the before-fix evidence. + +The success paths through the guarded wrapper are already covered on Windows and must stay green on the final dispatch: "Windows native execution preserves spaces quotes Unicode empty arguments and stdin bytes" (an inner `exit 23` and stdin bytes through `Invoke-Expression`), "Windows discovery selects Desktop before the managed current junction before a legacy executable" (`windowsOcxArgv`), "closing the SSH channel terminates the remote ocx and its PowerShell host" (Job kill-on-close), and `tests/clients/link-pinned-sync-argv.test.ts` "Windows bounds version probes and runs the selected pinned command". A portable assertion that the wrapper refuses before `Invoke-Expression` cannot be made behaviorally off Windows, so none is added. The size budget stays covered portably: the POSIX cases in `link-pinned-sync-argv.test.ts` build the Windows pinned command, and the builder throws above `POWERSHELL_ENCODED_MAX`. The guard costs a fixed 416–420 encoded characters, so the variable argument headroom for `windowsOcxArgv` shrinks by that amount. Its production arguments are short CLI flags and ids; the key travels on stdin. + +Also correct the stale comment above `NATIVE_PROCESS` ("The helper travels deflated ... PowerShell inflates it and hands the text to Add-Type"). Since #8100 the whole script travels deflated, and the helper reaches `Add-Type` as a quoted literal. + +Docs. `structure/remote-link.md` still says the helper is "carried deflated ... and inflated only into `Add-Type`", which has been stale since #8100. Update it: the whole script travels deflated, and a failed inflation exits 126 before anything runs. + +## Failure 2 — the new test's fixture is wrong on Windows + +`tests/cli/sync-command-fanout.test.ts` "local-only JSON does not invoke ssh" (added by #8100) timed out at 15,000 ms on windows 2/11 with empty stdout. The same case takes about 300 ms on macOS. + +What the evidence establishes. The fixture is provably wrong on Windows (points 2 and 3). That the stall itself comes from the fixture, and not from product code, is a hypothesis supported by point 4: the log discards the child's stderr, so the blocking operation was not observed. The single Windows dispatch on the final head validates it. If the corrected case fails there, the outcome is unresolved, reported with the child stderr the new diagnostics capture, and nothing is weakened. + +1. With `--local-only`, `runHomeFanout` returns before reading the store, the status API or any SSH runner (`src/cli/sync-fanout.ts`). Everything that runs is the Home sync #8100 moved from `dispatch.ts` into `sync-command.ts` (the runner body is unchanged apart from routing `console.log` to stderr under `--json`), plus the new flag parse in `root.ts`, which is pure. +2. The child gets only `{HOME, OPENCODEX_HOME, CODEX_HOME, PATH: ":/usr/bin:/bin"}`. On Windows that has no `SystemRoot`, `USERPROFILE` or `PATHEXT`, a POSIX `:` delimiter, and an extensionless `#!/bin/sh` "ssh" Windows cannot execute. So even a passing run proves nothing about ssh on Windows (fan-out spawns `ssh` by PATH lookup with the inherited environment, `src/link/ssh-runner.ts`). +3. The Home sync reaches Codex write admission, whose ownership probe runs the machine's real `schtasks.exe`/`sc.exe`, resolved from System32 by `GetSystemDirectoryW`. A targeted query answer other than the English not-found text falls through to a full listing with a 20 s budget (`SERVICE_PROBE_LISTING_TIMEOUT_MS`, #2914). The repository's convention for any subprocess test reaching admission on Windows is `claimOwnedServiceHome` + `withOwnedServiceHomePreload` (`tests/helpers/owned-service-home.ts`: "PATH fixtures cannot isolate it"). This test skips it. +4. The same scenario written to that convention — `ocx sync` as a subprocess, Codex on, inherited env with temp `HOME`/`USERPROFILE`, owned-service-home preload (`tests/cli/cli-restore-back.test.ts`) — passed on Windows in this same batch in 688–721 ms (windows 9/11). + +The exact operation that blocked in the stripped environment is not observable from the log, because the test discards the child's stderr. No timeout is raised and no case is skipped. + +Changes (`tests/cli/sync-command-fanout.test.ts`): + +- Subprocess case: build the env the way `cli-restore-back.test.ts` does. Create a temp home directory, call `claimOwnedServiceHome(codexHome, opencodexHome, home)`, and use `{...process.env, HOME: home, USERPROFILE: home, OPENCODEX_HOME, CODEX_HOME, ...owned.env, PATH}`. PATH is `[sentinelDir, owned.env.PATH ?? process.env.PATH].join(delimiter)`, so the helper's Linux `systemctl` fixture survives. The argv goes through `withOwnedServiceHomePreload`. Codex integration stays on and the Codex home stays absent, so the Home path under test is unchanged. The child gets a spawn timeout below the 15,000 ms test budget. If stdout is not one document, the case fails with the child's exit code and stderr, so a future stall names its stage. +- Platform-neutral ssh sentinel. Add `tests/helpers/ssh-spawn-sentinel-preload.ts`, a test-only Bun preload enabled by `OCX_TEST_SSH_SENTINEL=`. It wraps exactly `Bun.spawn` and `Bun.spawnSync`, the APIs fan-out uses (`runFanoutProcess` calls `Bun.spawn` directly, and `fanoutSshRunner` delegates to it). An argv whose first element has basename `ssh` or `ssh.exe` (case-insensitive, either separator) appends one line ` ` to the marker and throws, so it never runs. Every other call passes through unchanged. It does not touch `node:child_process`, so it composes with the Windows service preload, which mocks that module, without either replacing the other. Its claim is scoped to those two APIs in the CLI process. No production module reads the flag. The subprocess case loads it as `withOwnedServiceHomePreload(["run", "--preload", sentinel, cli, ...])`, the exact combination the controls use. It asserts the marker is absent and the expected document (`schema`, `home.exit === code`, `fanout: disabled`, `children: []`) is present, so a thrown sentinel error cannot pass as a valid run. +- Positive control (same file, same preload combination and env shape). A child runs a script that calls `Bun.spawn(["ssh", "-V"])` and then `Bun.spawnSync(["C:\\fixture\\SSH.EXE", "-V"])`, each in its own try (the sentinel records each attempt), then `Bun.spawnSync([process.execPath, "--version"])` and prints that exit code. On Windows it also calls `child_process.spawnSync("schtasks.exe", ["/query", "/tn", "opencodex-proxy", "/xml"], { encoding: "buffer" })` and prints its stderr. The case asserts two marker lines, `Bun.spawn ssh` and `Bun.spawnSync ssh.exe`, a pass-through exit of 0, and on Windows the `[OCX_TEST_SERVICE_HOME]` stderr, which shows the service fixture is still active beside the sentinel. The `#!/bin/sh` PATH sentinel stays as a second, POSIX-only check. Helpers need no test-layout registration (`tests/test-layout.test.ts` treats `helpers/` as support files). +- New in-process case, `sync --local-only --json` with a committed Home catalog and a connected hub-initiated link, using the file's existing spies. It asserts that `readHomeLinkStatus`, `fanoutSshRunner` and `runFanoutProcess` are never called, and that the document reports `fanout: {state: "disabled", reason: null}` with no children. This is the platform-neutral proof that local-only never reaches ssh, including on Windows, where the PATH sentinel cannot run. +- The "human sync reports a damaged link store" case uses the same stripped POSIX env and reaches the same admission probe; it gets the same env correction, without changing what it asserts. + +Nothing in `src/` changes for failure 2. + +## Out of scope + +Workflows, timeouts, the Windows probe budgets, the slow pinned case (passes, 9.8 s on Windows), any refactor. + +## Verification + +- `bun test tests/clients/link-ssh-argv-discovery.test.ts tests/cli/sync-command-fanout.test.ts tests/clients/link-pinned-sync-argv.test.ts tests/cli/sync-fanout.test.ts tests/cli/sync-fanout-process.test.ts` (macOS: the Windows cases skip) +- `bun run typecheck`, `bun run structure:check`, `bun run privacy:scan`, `bun scripts/test.ts --changed=dev --parallel=1` +- Full `bun run test`: the PR carries `ci:full`, so the four full Ubuntu shards run on the PR head, and the one dispatch runs every platform. Locally, the focused files plus `test:changed` are the floor. The PR's Verification section records the exact commands and anything left to CI, per AGENTS.md's resource exception, because several concurrent worktrees share this host. +- The one authorized `gh workflow run ci.yml --ref ` on the final head: windows 2/11 and 10/11 green, plus the new Windows CLM cases. +- Terra plan audit to PASS, a Terra security review of the containment change, and a Terra code review. + + + diff --git a/scripts/ci/test-durations.tsv b/scripts/ci/test-durations.tsv index ba3e49900b6..edef94f1ecb 100644 --- a/scripts/ci/test-durations.tsv +++ b/scripts/ci/test-durations.tsv @@ -1,2861 +1,2892 @@ # Per-file Bun test durations in milliseconds, read from hosted CI job logs. # Consumed by scripts/ci/run-bun-test-batches.sh to balance shards; a file without a row weighs the median. # Regenerate with scripts/ci/test-durations.ts (usage in its header); do not edit by hand. -# Source: run 41437409412 (attempt 1, workflow_dispatch on dev 5cfd0ac11): successful macos 1/4-4/4 and Linux test 2/4-4/4, plus the completed files of Linux test 1/4, which hit the job timeout; arithmetic mean of all per-file observations -835 tests/adapters/abort-race.test.ts -427 tests/adapters/adapter-buffered-tool-conformance.test.ts -259 tests/adapters/adapter-error-inline.test.ts -1650 tests/adapters/adapter-inner-send-budget-wiring.test.ts -2954 tests/adapters/adapter-inner-send-budget.test.ts -142 tests/adapters/adapter-input-media-guard.test.ts -620 tests/adapters/adapter-registry-authority.test.ts -1794 tests/adapters/adapter-tool-conformance.test.ts -184 tests/adapters/adapter-usage.test.ts -870 tests/adapters/anthropic/anthropic-429-policy.test.ts -44 tests/adapters/anthropic/anthropic-account-metadata.test.ts -237 tests/adapters/anthropic/anthropic-account-pause-outbound.test.ts -504 tests/adapters/anthropic/anthropic-account-pause.test.ts -852 tests/adapters/anthropic/anthropic-account-pool.test.ts -708 tests/adapters/anthropic/anthropic-account-threshold.test.ts -175 tests/adapters/anthropic/anthropic-active-limit-routing.test.ts -214 tests/adapters/anthropic/anthropic-affinity-restart.test.ts -241 tests/adapters/anthropic/anthropic-affinity-store.test.ts -44 tests/adapters/anthropic/anthropic-agentrouter-language-framing.test.ts -108 tests/adapters/anthropic/anthropic-baseurl-override.test.ts -51 tests/adapters/anthropic/anthropic-beta-allowlist.test.ts -65 tests/adapters/anthropic/anthropic-beta-body-pairs.test.ts -704 tests/adapters/anthropic/anthropic-billing-ownership.test.ts -298 tests/adapters/anthropic/anthropic-billing-refusal.test.ts -69 tests/adapters/anthropic/anthropic-client-identity.test.ts -661 tests/adapters/anthropic/anthropic-combo-account-cooldown.test.ts -2636 tests/adapters/anthropic/anthropic-compatible-stream.test.ts -222 tests/adapters/anthropic/anthropic-cooldown-recovery.test.ts -56 tests/adapters/anthropic/anthropic-empty-content.test.ts -176 tests/adapters/anthropic/anthropic-eof-tolerance.test.ts -376 tests/adapters/anthropic/anthropic-error-body.test.ts -53 tests/adapters/anthropic/anthropic-error-stop-reason.test.ts -685 tests/adapters/anthropic/anthropic-fast-opt-in.test.ts -98 tests/adapters/anthropic/anthropic-fast-speed.test.ts -47 tests/adapters/anthropic/anthropic-haiku-5-5-contract.test.ts -53 tests/adapters/anthropic/anthropic-hardening.test.ts -130 tests/adapters/anthropic/anthropic-image-guard.test.ts -3244 tests/adapters/anthropic/anthropic-image-normalize.test.ts -1806 tests/adapters/anthropic/anthropic-image-retry-e2e.test.ts -184 tests/adapters/anthropic/anthropic-image-retry.test.ts -1024 tests/adapters/anthropic/anthropic-instance-isolation.test.ts -938 tests/adapters/anthropic/anthropic-instance-pool-parity.test.ts -1188 tests/adapters/anthropic/anthropic-instance-quota.test.ts -3015 tests/adapters/anthropic/anthropic-instance-recovery.test.ts -58 tests/adapters/anthropic/anthropic-message-stop-termination.test.ts -74 tests/adapters/anthropic/anthropic-messages-passthrough-oauth.test.ts -41 tests/adapters/anthropic/anthropic-messages-passthrough.test.ts -3179 tests/adapters/anthropic/anthropic-model-routes.test.ts -856 tests/adapters/anthropic/anthropic-model-weekly-admission.test.ts -47 tests/adapters/anthropic/anthropic-opaque-strip.test.ts -84 tests/adapters/anthropic/anthropic-output-maxima.test.ts -73 tests/adapters/anthropic/anthropic-parallel-tool-disable.test.ts -204 tests/adapters/anthropic/anthropic-pool-toggle-copy.test.ts -384 tests/adapters/anthropic/anthropic-pool-usage-limit.test.ts -397 tests/adapters/anthropic/anthropic-progress-updates.test.ts -391 tests/adapters/anthropic/anthropic-quota-cooldown-recovery.test.ts -1538 tests/adapters/anthropic/anthropic-quota-dispatch.test.ts -519 tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts -244 tests/adapters/anthropic/anthropic-reasoning.test.ts -40 tests/adapters/anthropic/anthropic-replay.test.ts -102 tests/adapters/anthropic/anthropic-reset-grants.test.ts -508 tests/adapters/anthropic/anthropic-revoked-token-boundaries.test.ts -255 tests/adapters/anthropic/anthropic-revoked-token-continuation.test.ts -766 tests/adapters/anthropic/anthropic-revoked-token-sidecars.test.ts -1498 tests/adapters/anthropic/anthropic-revoked-token.test.ts -199 tests/adapters/anthropic/anthropic-sidecar-account-failover.test.ts -64 tests/adapters/anthropic/anthropic-sonnet-5-5-contract.test.ts -91 tests/adapters/anthropic/anthropic-stream-hardening.test.ts -790 tests/adapters/anthropic/anthropic-subscription-chain.test.ts -50 tests/adapters/anthropic/anthropic-tail-guard.test.ts -142 tests/adapters/anthropic/anthropic-thinking-signature.test.ts -52 tests/adapters/anthropic/anthropic-thinking-usage.test.ts -38 tests/adapters/anthropic/anthropic-tool-call-id.test.ts -147 tests/adapters/anthropic/anthropic-tool-declaration-constraints.test.ts -115 tests/adapters/anthropic/anthropic-tool-schema.test.ts -616 tests/adapters/anthropic/anthropic2-fast-parity.test.ts -105 tests/adapters/bridge-legacy-shell-normalization.test.ts -3578 tests/adapters/bridge-lifecycle.test.ts -181 tests/adapters/bridge-nonstreaming-terminal.test.ts -120 tests/adapters/bridge-raw-reasoning-hidden.test.ts -125 tests/adapters/bridge-reasoning-replay-batch.test.ts -189 tests/adapters/bridge-stall.test.ts -86 tests/adapters/bridge-terminal-refusal.test.ts -49 tests/adapters/bridge-terminal-singleness.test.ts -195 tests/adapters/bridge.test.ts -119 tests/adapters/buffered-response-shape-guards.test.ts -50 tests/adapters/coding-agent-history-projection.test.ts -24 tests/adapters/coding-agent-tool-result-images.test.ts -130 tests/adapters/coding-agent-windows-dispatch.test.ts -44 tests/adapters/dsh-account-adapter.test.ts -583 tests/adapters/empty-tool-output-annotation.test.ts -145 tests/adapters/exec-tool-result-normalize.test.ts -385 tests/adapters/fix-tool-number-preservation.test.ts -144 tests/adapters/google/antigravity-account-roster.test.ts -108 tests/adapters/google/antigravity-baseurl-override.test.ts -138 tests/adapters/google/antigravity-discovered-families.test.ts -56 tests/adapters/google/antigravity-refusal.test.ts -315 tests/adapters/google/antigravity-routing-carry.test.ts -116 tests/adapters/google/antigravity-static-catalog.test.ts -814 tests/adapters/google/gcp-adc.test.ts -572 tests/adapters/google/gcp-credential-boundary.test.ts -325 tests/adapters/google/gcp-sa-adapter.test.ts -713 tests/adapters/google/gcp-sa-marker.test.ts -76 tests/adapters/google/gemini-37-flash-migration.test.ts -109 tests/adapters/google/gemini-4-argon-antigravity.test.ts -60 tests/adapters/google/gemini-progress-history.test.ts -176 tests/adapters/google/gemini-web-search.test.ts -75 tests/adapters/google/google-adapter.test.ts -184 tests/adapters/google/google-ai-studio-foreign-call-signature.test.ts -4203 tests/adapters/google/google-antigravity-oauth.test.ts -2387 tests/adapters/google/google-antigravity-replay.test.ts -78 tests/adapters/google/google-antigravity-wire.test.ts -72 tests/adapters/google/google-buffered-stop-reason.test.ts -63 tests/adapters/google/google-claude-prefill-guard.test.ts -77 tests/adapters/google/google-empty-content.test.ts -423 tests/adapters/google/google-errors.test.ts -86 tests/adapters/google/google-hardening.test.ts -156 tests/adapters/google/google-models-listing.test.ts -91 tests/adapters/google/google-output-clamp.test.ts -61 tests/adapters/google/google-provider-metadata-roundtrip.test.ts -83 tests/adapters/google/google-signature-history-roundtrip.test.ts -47 tests/adapters/google/google-stream-fragmentation.test.ts -23 tests/adapters/google/google-strict-tool-validated-mode.test.ts -49 tests/adapters/google/google-structured-output.test.ts -55 tests/adapters/google/google-tool-result-adjacency.test.ts -133 tests/adapters/google/google-tool-schema-contract.test.ts -49 tests/adapters/google/google-tool-schema.test.ts -4701 tests/adapters/google/google-vertex-http.test.ts -93 tests/adapters/google/google-vertex-key-project.test.ts -56 tests/adapters/google/google-vertex-stream.test.ts -53 tests/adapters/google/google-vertex-thought-signature.test.ts -122 tests/adapters/google/google-wire-compiler.test.ts -115 tests/adapters/google/google-wire-shape.test.ts -108 tests/adapters/google/vertex-catalog.test.ts -195 tests/adapters/identity-neutralize.test.ts -445 tests/adapters/identity-subagent.test.ts -767 tests/adapters/key-failover.test.ts -81 tests/adapters/openai/inline-think-boundaries.test.ts -1774 tests/adapters/openai/openai-api-virtual-models.test.ts -76 tests/adapters/openai/openai-chat-audio.test.ts -178 tests/adapters/openai/openai-chat-bounded-tool-names.test.ts -89 tests/adapters/openai/openai-chat-dangling-toolcalls.test.ts -48 tests/adapters/openai/openai-chat-developer-position.test.ts -51 tests/adapters/openai/openai-chat-eof.test.ts -104 tests/adapters/openai/openai-chat-glm-summary.test.ts -618 tests/adapters/openai/openai-chat-hardening.test.ts -5444 tests/adapters/openai/openai-chat-image-normalization.test.ts -190 tests/adapters/openai/openai-chat-inline-think-tags.test.ts -48 tests/adapters/openai/openai-chat-invalid-tool-call-diagnostics.test.ts -112 tests/adapters/openai/openai-chat-mistral-content.test.ts -97 tests/adapters/openai/openai-chat-model-suffix.test.ts -357 tests/adapters/openai/openai-chat-native-policy.test.ts -108 tests/adapters/openai/openai-chat-nonce-tool-call-content.test.ts -61 tests/adapters/openai/openai-chat-parallel-stream.test.ts -90 tests/adapters/openai/openai-chat-path-override.test.ts -50 tests/adapters/openai/openai-chat-qwen38-leading-system.test.ts +# Source: run 41462914814 (workflow_dispatch on dev 09b558580): Linux test 1/4-4/4 and macos 1/4-4/4, all successful; plus Linux test 1/4-4/4 of pull_request runs 41485932590 (#8106 at 7f4924ec4; test 4/4 hit the job timeout, files measured to completion count), 41482553737 (#8103) and 41483744349 (#8104), which measured the files #8103 and #8104 added; arithmetic mean of all per-file observations +560 tests/adapters/abort-race.test.ts +349 tests/adapters/adapter-buffered-tool-conformance.test.ts +289 tests/adapters/adapter-error-inline.test.ts +1925 tests/adapters/adapter-inner-send-budget-wiring.test.ts +2947 tests/adapters/adapter-inner-send-budget.test.ts +146 tests/adapters/adapter-input-media-guard.test.ts +138 tests/adapters/adapter-registry-authority.test.ts +1467 tests/adapters/adapter-tool-conformance.test.ts +170 tests/adapters/adapter-usage.test.ts +869 tests/adapters/anthropic/anthropic-429-policy.test.ts +61 tests/adapters/anthropic/anthropic-account-metadata.test.ts +142 tests/adapters/anthropic/anthropic-account-pause-outbound.test.ts +516 tests/adapters/anthropic/anthropic-account-pause.test.ts +595 tests/adapters/anthropic/anthropic-account-pool.test.ts +916 tests/adapters/anthropic/anthropic-account-threshold.test.ts +161 tests/adapters/anthropic/anthropic-active-limit-routing.test.ts +181 tests/adapters/anthropic/anthropic-affinity-restart.test.ts +170 tests/adapters/anthropic/anthropic-affinity-store.test.ts +51 tests/adapters/anthropic/anthropic-agentrouter-language-framing.test.ts +123 tests/adapters/anthropic/anthropic-baseurl-override.test.ts +62 tests/adapters/anthropic/anthropic-beta-allowlist.test.ts +59 tests/adapters/anthropic/anthropic-beta-body-pairs.test.ts +510 tests/adapters/anthropic/anthropic-billing-ownership.test.ts +316 tests/adapters/anthropic/anthropic-billing-refusal.test.ts +65 tests/adapters/anthropic/anthropic-client-identity.test.ts +556 tests/adapters/anthropic/anthropic-combo-account-cooldown.test.ts +2579 tests/adapters/anthropic/anthropic-compatible-stream.test.ts +244 tests/adapters/anthropic/anthropic-cooldown-recovery.test.ts +48 tests/adapters/anthropic/anthropic-empty-content.test.ts +116 tests/adapters/anthropic/anthropic-eof-tolerance.test.ts +366 tests/adapters/anthropic/anthropic-error-body.test.ts +50 tests/adapters/anthropic/anthropic-error-stop-reason.test.ts +446 tests/adapters/anthropic/anthropic-fast-opt-in.test.ts +66 tests/adapters/anthropic/anthropic-fast-speed.test.ts +64 tests/adapters/anthropic/anthropic-haiku-5-5-contract.test.ts +46 tests/adapters/anthropic/anthropic-hardening.test.ts +162 tests/adapters/anthropic/anthropic-image-guard.test.ts +3879 tests/adapters/anthropic/anthropic-image-normalize.test.ts +1167 tests/adapters/anthropic/anthropic-image-retry-e2e.test.ts +164 tests/adapters/anthropic/anthropic-image-retry.test.ts +864 tests/adapters/anthropic/anthropic-instance-isolation.test.ts +689 tests/adapters/anthropic/anthropic-instance-pool-parity.test.ts +819 tests/adapters/anthropic/anthropic-instance-quota.test.ts +1863 tests/adapters/anthropic/anthropic-instance-recovery.test.ts +64 tests/adapters/anthropic/anthropic-message-stop-termination.test.ts +71 tests/adapters/anthropic/anthropic-messages-passthrough-oauth.test.ts +60 tests/adapters/anthropic/anthropic-messages-passthrough.test.ts +1203 tests/adapters/anthropic/anthropic-model-routes.test.ts +631 tests/adapters/anthropic/anthropic-model-weekly-admission.test.ts +58 tests/adapters/anthropic/anthropic-opaque-strip.test.ts +89 tests/adapters/anthropic/anthropic-output-maxima.test.ts +66 tests/adapters/anthropic/anthropic-parallel-tool-disable.test.ts +95 tests/adapters/anthropic/anthropic-pool-toggle-copy.test.ts +377 tests/adapters/anthropic/anthropic-pool-usage-limit.test.ts +204 tests/adapters/anthropic/anthropic-progress-updates.test.ts +422 tests/adapters/anthropic/anthropic-quota-cooldown-recovery.test.ts +2216 tests/adapters/anthropic/anthropic-quota-dispatch.test.ts +318 tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts +148 tests/adapters/anthropic/anthropic-reasoning.test.ts +55 tests/adapters/anthropic/anthropic-replay.test.ts +96 tests/adapters/anthropic/anthropic-reset-grants.test.ts +366 tests/adapters/anthropic/anthropic-revoked-token-boundaries.test.ts +306 tests/adapters/anthropic/anthropic-revoked-token-continuation.test.ts +636 tests/adapters/anthropic/anthropic-revoked-token-sidecars.test.ts +1386 tests/adapters/anthropic/anthropic-revoked-token.test.ts +241 tests/adapters/anthropic/anthropic-sidecar-account-failover.test.ts +77 tests/adapters/anthropic/anthropic-sonnet-5-5-contract.test.ts +55 tests/adapters/anthropic/anthropic-stream-hardening.test.ts +910 tests/adapters/anthropic/anthropic-subscription-chain.test.ts +65 tests/adapters/anthropic/anthropic-tail-guard.test.ts +141 tests/adapters/anthropic/anthropic-thinking-signature.test.ts +75 tests/adapters/anthropic/anthropic-thinking-usage.test.ts +57 tests/adapters/anthropic/anthropic-tool-call-id.test.ts +157 tests/adapters/anthropic/anthropic-tool-declaration-constraints.test.ts +65 tests/adapters/anthropic/anthropic-tool-schema.test.ts +558 tests/adapters/anthropic/anthropic2-fast-parity.test.ts +49 tests/adapters/bridge-legacy-shell-normalization.test.ts +3446 tests/adapters/bridge-lifecycle.test.ts +193 tests/adapters/bridge-nonstreaming-terminal.test.ts +101 tests/adapters/bridge-raw-reasoning-hidden.test.ts +47 tests/adapters/bridge-reasoning-replay-batch.test.ts +137 tests/adapters/bridge-stall.test.ts +59 tests/adapters/bridge-terminal-refusal.test.ts +109 tests/adapters/bridge-terminal-singleness.test.ts +199 tests/adapters/bridge.test.ts +127 tests/adapters/buffered-response-shape-guards.test.ts +57 tests/adapters/coding-agent-history-projection.test.ts +79 tests/adapters/coding-agent-tool-result-images.test.ts +111 tests/adapters/coding-agent-windows-dispatch.test.ts +83 tests/adapters/dsh-account-adapter.test.ts +1030 tests/adapters/empty-tool-output-annotation.test.ts +230 tests/adapters/exec-tool-result-normalize.test.ts +241 tests/adapters/fix-tool-number-preservation.test.ts +161 tests/adapters/google/antigravity-account-roster.test.ts +79 tests/adapters/google/antigravity-baseurl-override.test.ts +65 tests/adapters/google/antigravity-discovered-families.test.ts +49 tests/adapters/google/antigravity-refusal.test.ts +170 tests/adapters/google/antigravity-routing-carry.test.ts +117 tests/adapters/google/antigravity-static-catalog.test.ts +842 tests/adapters/google/gcp-adc.test.ts +513 tests/adapters/google/gcp-credential-boundary.test.ts +300 tests/adapters/google/gcp-sa-adapter.test.ts +784 tests/adapters/google/gcp-sa-marker.test.ts +86 tests/adapters/google/gemini-37-flash-migration.test.ts +104 tests/adapters/google/gemini-4-argon-antigravity.test.ts +86 tests/adapters/google/gemini-progress-history.test.ts +139 tests/adapters/google/gemini-web-search.test.ts +99 tests/adapters/google/google-adapter.test.ts +65 tests/adapters/google/google-ai-studio-foreign-call-signature.test.ts +4198 tests/adapters/google/google-antigravity-oauth.test.ts +2309 tests/adapters/google/google-antigravity-replay.test.ts +100 tests/adapters/google/google-antigravity-wire.test.ts +99 tests/adapters/google/google-buffered-stop-reason.test.ts +57 tests/adapters/google/google-claude-prefill-guard.test.ts +93 tests/adapters/google/google-empty-content.test.ts +48 tests/adapters/google/google-errors.test.ts +67 tests/adapters/google/google-hardening.test.ts +163 tests/adapters/google/google-models-listing.test.ts +54 tests/adapters/google/google-output-clamp.test.ts +53 tests/adapters/google/google-provider-metadata-roundtrip.test.ts +108 tests/adapters/google/google-signature-history-roundtrip.test.ts +69 tests/adapters/google/google-stream-fragmentation.test.ts +48 tests/adapters/google/google-strict-tool-validated-mode.test.ts +56 tests/adapters/google/google-structured-output.test.ts +71 tests/adapters/google/google-tool-result-adjacency.test.ts +79 tests/adapters/google/google-tool-schema-contract.test.ts +62 tests/adapters/google/google-tool-schema.test.ts +4669 tests/adapters/google/google-vertex-http.test.ts +109 tests/adapters/google/google-vertex-key-project.test.ts +67 tests/adapters/google/google-vertex-stream.test.ts +85 tests/adapters/google/google-vertex-thought-signature.test.ts +57 tests/adapters/google/google-wire-compiler.test.ts +77 tests/adapters/google/google-wire-shape.test.ts +123 tests/adapters/google/vertex-catalog.test.ts +260 tests/adapters/identity-neutralize.test.ts +328 tests/adapters/identity-subagent.test.ts +481 tests/adapters/key-failover.test.ts +72 tests/adapters/openai/inline-think-boundaries.test.ts +2566 tests/adapters/openai/openai-api-virtual-models.test.ts +42 tests/adapters/openai/openai-chat-audio.test.ts +184 tests/adapters/openai/openai-chat-bounded-tool-names.test.ts +98 tests/adapters/openai/openai-chat-dangling-toolcalls.test.ts +61 tests/adapters/openai/openai-chat-developer-position.test.ts +60 tests/adapters/openai/openai-chat-eof.test.ts +87 tests/adapters/openai/openai-chat-glm-summary.test.ts +261 tests/adapters/openai/openai-chat-hardening.test.ts +5201 tests/adapters/openai/openai-chat-image-normalization.test.ts +82 tests/adapters/openai/openai-chat-inline-think-tags.test.ts +51 tests/adapters/openai/openai-chat-invalid-tool-call-diagnostics.test.ts +89 tests/adapters/openai/openai-chat-mistral-content.test.ts +132 tests/adapters/openai/openai-chat-model-suffix.test.ts +506 tests/adapters/openai/openai-chat-native-policy.test.ts +177 tests/adapters/openai/openai-chat-nonce-tool-call-content.test.ts +80 tests/adapters/openai/openai-chat-parallel-stream.test.ts +96 tests/adapters/openai/openai-chat-path-override.test.ts +57 tests/adapters/openai/openai-chat-qwen38-leading-system.test.ts 96 tests/adapters/openai/openai-chat-reasoning-wire-policy.test.ts -118 tests/adapters/openai/openai-chat-required-tool.test.ts -188 tests/adapters/openai/openai-chat-sanitization-review-regressions.test.ts -138 tests/adapters/openai/openai-chat-serialized-tool-call-content.test.ts -315 tests/adapters/openai/openai-chat-serialized-tool-call-hold-bound.test.ts -160 tests/adapters/openai/openai-chat-serialized-tool-call-scaling.test.ts -73 tests/adapters/openai/openai-chat-serialized-tool-call-think.test.ts -53 tests/adapters/openai/openai-chat-single-system.test.ts -655 tests/adapters/openai/openai-chat-standalone-bare-block.test.ts -170 tests/adapters/openai/openai-chat-system-order.test.ts -241 tests/adapters/openai/openai-chat-tool-call-id-remint.test.ts -48 tests/adapters/openai/openai-chat-tool-result-images.test.ts -44 tests/adapters/openai/openai-chat-url.test.ts -61 tests/adapters/openai/openai-chat-video-part.test.ts -140 tests/adapters/openai/openai-empty-assistant-history.test.ts -214 tests/adapters/openai/openai-native-hosted-search-history.test.ts -1291 tests/adapters/openai/openai-provider-option-e2e.test.ts -368 tests/adapters/openai/openai-provider-option-migration.test.ts -68 tests/adapters/openai/openai-provider-option-startup.test.ts -64 tests/adapters/openai/openai-provider-option-tooling.test.ts -56 tests/adapters/openai/openai-provider-option.test.ts -46 tests/adapters/openai/opengateway-input.test.ts -121 tests/adapters/physical-send.test.ts -157 tests/adapters/qoder-spawn-readmission.test.ts -61 tests/adapters/reasoning-replay-identity.test.ts -168 tests/adapters/reasoning-replay-robustness.test.ts -140 tests/adapters/routed-agent-messages.test.ts -94 tests/adapters/run-turn-queue.test.ts -392 tests/adapters/terminal-continuation-owner-rotation.test.ts -127 tests/adapters/tool-argument-integers.test.ts -116 tests/adapters/tool-catalog-nudge.test.ts -44 tests/adapters/tool-choice-performance.test.ts -74 tests/adapters/tool-envelope-echo-whole-line.test.ts -156 tests/adapters/tool-identity-hash.test.ts -158 tests/adapters/translator-budget-lifetime.test.ts -4886 tests/adapters/translator-budget.test.ts -41 tests/adapters/upstream-http-error.test.ts -65 tests/adapters/workbuddy-adapter.test.ts -95 tests/advisor/advisor-adaptive.test.ts -51 tests/advisor/advisor-authority-transport.test.ts -87 tests/advisor/advisor-budget.test.ts -305 tests/advisor/advisor-caller-policy-compact.test.ts -360 tests/advisor/advisor-caller-policy-host-key.test.ts -409 tests/advisor/advisor-caller-policy-http.test.ts -194 tests/advisor/advisor-caller-policy-ingress.test.ts -285 tests/advisor/advisor-caller-policy-jev.test.ts -276 tests/advisor/advisor-caller-policy-replay.test.ts -650 tests/advisor/advisor-caller-policy-routing.test.ts -1120 tests/advisor/advisor-caller-policy-self-fetch.test.ts -224 tests/advisor/advisor-caller-policy-sidecar-authority.test.ts -496 tests/advisor/advisor-caller-policy-vision.test.ts -613 tests/advisor/advisor-caller-policy.test.ts -51 tests/advisor/advisor-consult.test.ts -34 tests/advisor/advisor-context.test.ts -63 tests/advisor/advisor-continuation-limit.test.ts -413 tests/advisor/advisor-core-boundary.test.ts -54 tests/advisor/advisor-evidence.test.ts -41 tests/advisor/advisor-guard.test.ts -294 tests/advisor/advisor-internal-authority.test.ts -64 tests/advisor/advisor-plan.test.ts -1240 tests/advisor/advisor-responses-wiring.test.ts -350 tests/advisor/advisor-retention.test.ts -450 tests/advisor/advisor-scope-transport.test.ts -138 tests/advisor/advisor-settings.test.ts -108 tests/advisor/advisor-state.test.ts -99 tests/advisor/advisor-web-search.test.ts -4334 tests/ci-workflows/assert-mergeable-review.test.ts -149 tests/ci-workflows/brand-favicons.test.ts -107 tests/ci-workflows/build-desktop-icon-set.test.ts -133 tests/ci-workflows/build-release-changelog.test.ts -242 tests/ci-workflows/bump-dev-version.test.ts -313 tests/ci-workflows/bun-runtime.test.ts -102 tests/ci-workflows/ci-bun-crash-classifier.test.ts -36771 tests/ci-workflows/ci-bun-install-frozen.test.ts -114 tests/ci-workflows/ci-concurrency-groups.test.ts -5977 tests/ci-workflows/ci-crash-disposition.test.ts -2466 tests/ci-workflows/ci-gui-typecheck-gate.test.ts -98 tests/ci-workflows/ci-pr-hygiene-approvals.test.ts -1623 tests/ci-workflows/ci-privacy-gate.test.ts -8025 tests/ci-workflows/ci-review-lanes.test.ts -1120 tests/ci-workflows/ci-scope-gaps.test.ts -684 tests/ci-workflows/ci-scope-reduction.test.ts -1548 tests/ci-workflows/ci-shard-balance.test.ts -44 tests/ci-workflows/ci-structure-gate.test.ts -1647 tests/ci-workflows/ci-test-lane.test.ts -887 tests/ci-workflows/ci-workflows.test.ts -38 tests/ci-workflows/cleanup-orphaned-workflows.test.ts -430 tests/ci-workflows/client-support-matrix.test.ts -1823 tests/ci-workflows/client-support-runtime.test.ts -86 tests/ci-workflows/closed-pr-branch-cleanup.test.ts -6908 tests/ci-workflows/cold-spawn-warmup.test.ts -360 tests/ci-workflows/compatibility-version.test.ts -85 tests/ci-workflows/docs-429-failover-claims.test.ts -56 tests/ci-workflows/docs-bun-source-requirement.test.ts -99 tests/ci-workflows/docs-developer-role-policy.test.ts -84 tests/ci-workflows/docs-gjc-reasoning-export.test.ts -127 tests/ci-workflows/docs-gpt61-terra.test.ts -45 tests/ci-workflows/docs-gui-screenshot-policy.test.ts -390 tests/ci-workflows/docs-link-targets.test.ts -23 tests/ci-workflows/docs-provider-billing-claims.test.ts -76 tests/ci-workflows/docs-provider-discovery-limits.test.ts -88 tests/ci-workflows/docs-provider-preset-counts.test.ts -249 tests/ci-workflows/docs-readme-memory-inventory.test.ts -58 tests/ci-workflows/docs-readme-translation-parity.test.ts -74 tests/ci-workflows/docs-remote-hub-claims.test.ts -135 tests/ci-workflows/dsh-path-contract.test.ts -500 tests/ci-workflows/dsh-rc6-compat-script.test.ts -190 tests/ci-workflows/dsh-writer-lock.test.ts -41 tests/ci-workflows/exhaustive-deps-suppression.test.ts -1654 tests/ci-workflows/file-size-ratchet.test.ts -962 tests/ci-workflows/fixture-dir-uniqueness.test.ts -48 tests/ci-workflows/fixture-teardown-helper.test.ts -624 tests/ci-workflows/fixture-windows-runtime-preload.test.ts -483 tests/ci-workflows/import-cycle-ratchet.test.ts -283 tests/ci-workflows/install-scripts.test.ts -162 tests/ci-workflows/installed-gate-drivers.test.ts -52 tests/ci-workflows/keyring-smoke.test.ts -50 tests/ci-workflows/linux-desktop-packaged-ci.test.ts -35 tests/ci-workflows/linux-desktop-packaged-e2e.test.ts -8890 tests/ci-workflows/macos-serial-lanes.test.ts -3207 tests/ci-workflows/package-tree-fenced-restart.test.ts -2983 tests/ci-workflows/package-tree-integrity.test.ts -284 tests/ci-workflows/package-tree-restart-ownership.test.ts -272 tests/ci-workflows/package-tree-retarget.test.ts -113 tests/ci-workflows/pr-readiness-reattest.test.ts -131 tests/ci-workflows/privacy-scan-asset-names.test.ts -47 tests/ci-workflows/privacy-scan-meta-key.test.ts -49 tests/ci-workflows/privacy-scan-ssh-endpoint.test.ts -120 tests/ci-workflows/release-desktop-scripts.test.ts -12088 tests/ci-workflows/release-helper.test.ts -76 tests/ci-workflows/release-notes.test.ts -144 tests/ci-workflows/release-outcome-report.test.ts -122 tests/ci-workflows/release-pipeline-contract.test.ts -2338 tests/ci-workflows/release-preflight.test.ts -170 tests/ci-workflows/release-resume-identity.test.ts -96 tests/ci-workflows/release-version-line.test.ts -201 tests/ci-workflows/release-version-sources.test.ts -26969 tests/ci-workflows/release-windows-signing.test.ts -268 tests/ci-workflows/repo-hygiene.test.ts -420 tests/ci-workflows/repo-import-resolution.test.ts -538 tests/ci-workflows/setup-hooks.test.ts -750 tests/ci-workflows/skill-ocx-generated.test.ts -144 tests/ci-workflows/skill-ocx-workflows.test.ts -72 tests/ci-workflows/skill-ocx.test.ts -776 tests/ci-workflows/structure-ssot.test.ts -1201 tests/ci-workflows/test-home-guard-unpreloaded.test.ts -41237 tests/ci-workflows/test-home-guard.test.ts -20996 tests/ci-workflows/test-run-lock-generation.test.ts -202 tests/ci-workflows/test-runner-bun.test.ts -439 tests/ci-workflows/test-runner-spawnsync-finalizer.test.ts -18739 tests/ci-workflows/test-runner.test.ts -51 tests/ci-workflows/test-sandbox-cleanup.test.ts -89 tests/ci-workflows/test-temp-quarantine.test.ts -36 tests/ci-workflows/version-line.test.ts -96 tests/ci-workflows/warmup-registration.test.ts -55 tests/ci-workflows/zz-ci-api-usage-isolation.test.ts -101 tests/ci-workflows/zz-ci-storage-policy-isolation.test.ts -151 tests/ci-workflows/zz-pr-coderabbit-readiness-revalidation.test.ts -3556 tests/claude-integration/anthropic2-native-routing.test.ts -3179 tests/claude-integration/claude-529-mapping.test.ts -179 tests/claude-integration/claude-agent-startup-sync.test.ts -365 tests/claude-integration/claude-agents-inject-client.test.ts -224 tests/claude-integration/claude-agents-inject.test.ts -283 tests/claude-integration/claude-alias.test.ts -53 tests/claude-integration/claude-auth-detect.test.ts -142 tests/claude-integration/claude-auth-mode.test.ts -45 tests/claude-integration/claude-authmode-migration.test.ts -931 tests/claude-integration/claude-bridge-pool-dispatch.test.ts -132 tests/claude-integration/claude-bridge-pool-session.test.ts -380 tests/claude-integration/claude-cli-picker-surface.test.ts -560 tests/claude-integration/claude-cli-picker.test.ts -131 tests/claude-integration/claude-cli.test.ts -1128 tests/claude-integration/claude-client-refusal-status.test.ts -191 tests/claude-integration/claude-code-thought-signature-scope.test.ts -64 tests/claude-integration/claude-compatibility.test.ts -425 tests/claude-integration/claude-config-home-isolation.test.ts -1182 tests/claude-integration/claude-config-root-late-admission.test.ts -894 tests/claude-integration/claude-config-root-stale-updates.test.ts -631 tests/claude-integration/claude-config-root-writer-barrier.test.ts -113 tests/claude-integration/claude-context-accounting.test.ts -115 tests/claude-integration/claude-context-windows.test.ts -100 tests/claude-integration/claude-desktop-1m.test.ts -864 tests/claude-integration/claude-desktop-cli.test.ts -472 tests/claude-integration/claude-desktop-config-path.test.ts -1028 tests/claude-integration/claude-desktop-discovery.test.ts -684 tests/claude-integration/claude-desktop-first-party-guards.test.ts -1426 tests/claude-integration/claude-desktop-first-party.test.ts -129 tests/claude-integration/claude-desktop-mode-explanation.test.ts -669 tests/claude-integration/claude-desktop-model-visibility.test.ts -136 tests/claude-integration/claude-desktop-native-context.test.ts -600 tests/claude-integration/claude-desktop-picker-profile.test.ts -522 tests/claude-integration/claude-desktop-picker-routes.test.ts -237 tests/claude-integration/claude-desktop-picker.test.ts -51 tests/claude-integration/claude-desktop-policy.test.ts -7651 tests/claude-integration/claude-desktop-remote-hub.test.ts -238 tests/claude-integration/claude-desktop-system-proxy.test.ts -356 tests/claude-integration/claude-devin-output-order.test.ts -220 tests/claude-integration/claude-dotenv-provenance-transport.test.ts -553 tests/claude-integration/claude-estimate-projection.test.ts -300 tests/claude-integration/claude-first-party-agent-sync.test.ts -154 tests/claude-integration/claude-first-party-union.test.ts -85 tests/claude-integration/claude-gateway-cache.test.ts -436 tests/claude-integration/claude-gateway-output-cap.test.ts -404 tests/claude-integration/claude-inbound-cache-stabilize.test.ts -64 tests/claude-integration/claude-inbound-debug.test.ts -146 tests/claude-integration/claude-inbound-token-footer.test.ts -539 tests/claude-integration/claude-inbound-tool-loading.test.ts -107 tests/claude-integration/claude-inbound-tool-reference.test.ts -117 tests/claude-integration/claude-inbound.test.ts -287 tests/claude-integration/claude-installation-helper.test.ts -350 tests/claude-integration/claude-intercept-acl-barrier.test.ts -81 tests/claude-integration/claude-intercept-cleanup.test.ts -233 tests/claude-integration/claude-intercept-client-class.test.ts -105 tests/claude-integration/claude-intercept-local-ca-files.test.ts -181 tests/claude-integration/claude-intercept-local-ca-windows.test.ts -199 tests/claude-integration/claude-intercept-local-ca.test.ts -416 tests/claude-integration/claude-intercept-model-bindings.test.ts -153 tests/claude-integration/claude-intercept-no-proxy.test.ts -331 tests/claude-integration/claude-intercept-on-demand.test.ts -213 tests/claude-integration/claude-intercept-proxy-auth.test.ts -150 tests/claude-integration/claude-intercept-proxy.test.ts -178 tests/claude-integration/claude-intercept-settings.test.ts -121 tests/claude-integration/claude-long-context-eligibility.test.ts -7688 tests/claude-integration/claude-management-api.test.ts -7174 tests/claude-integration/claude-messages-endpoint.test.ts -426 tests/claude-integration/claude-messages-thread.test.ts -135 tests/claude-integration/claude-model-default-labels.test.ts -196 tests/claude-integration/claude-model-info.test.ts -1499 tests/claude-integration/claude-models-discovery.test.ts -2499 tests/claude-integration/claude-native-affinity.test.ts -1041 tests/claude-integration/claude-native-fast-1m-ingress.test.ts -10131 tests/claude-integration/claude-native-passthrough.test.ts -200 tests/claude-integration/claude-native-rate-limit-headers.test.ts -97 tests/claude-integration/claude-native-reasoning-continuity.test.ts -770 tests/claude-integration/claude-native-reasoning-provenance.test.ts -2318 tests/claude-integration/claude-outbound.test.ts -97 tests/claude-integration/claude-output-schema-strict.test.ts -230 tests/claude-integration/claude-picker-bootstrap.test.ts -699 tests/claude-integration/claude-picker-ca-store.test.ts -491 tests/claude-integration/claude-picker-ca.test.ts -89 tests/claude-integration/claude-picker-linger.test.ts -919 tests/claude-integration/claude-picker-listener.test.ts -138 tests/claude-integration/claude-picker-models.test.ts -1125 tests/claude-integration/claude-picker-recovery.test.ts -281 tests/claude-integration/claude-picker-relay-intent.test.ts -494 tests/claude-integration/claude-picker-runtime.test.ts -1933 tests/claude-integration/claude-picker-startup.test.ts -97 tests/claude-integration/claude-picker-trust-windows.test.ts -54 tests/claude-integration/claude-picker-trust.test.ts -4387 tests/claude-integration/claude-picker-upload.test.ts -686 tests/claude-integration/claude-picker-windows.test.ts -2199 tests/claude-integration/claude-prompt-too-long.test.ts -142 tests/claude-integration/claude-shell-hook.test.ts -312 tests/claude-integration/claude-sidecar-override.test.ts -88 tests/claude-integration/claude-source-envelope.test.ts -240 tests/claude-integration/claude-subagent-model-force.test.ts -185 tests/claude-integration/claude-system-env-auto.test.ts -463 tests/claude-integration/claude-tool-loading-destinations.test.ts -256 tests/claude-integration/claude-translated-cache-ttl.test.ts -952 tests/claude-integration/claude-translated-server-tools.test.ts -503 tests/claude-integration/claude-translated-tool-restrictions.test.ts -451 tests/claude-integration/messages-native-clean-eof.test.ts -368 tests/claude-integration/messages-native-decline-trace.test.ts -730 tests/claude-integration/messages-native-empty-inline.test.ts -1199 tests/claude-integration/messages-native-key-selection.test.ts -2790 tests/claude-integration/messages-native-oauth.test.ts -402 tests/claude-integration/messages-native-opaque-state.test.ts -782 tests/claude-integration/messages-native-scope.test.ts -3122 tests/claude-integration/messages-native.test.ts -2549 tests/claude-integration/messages-request-id-endpoint.test.ts -101 tests/claude-integration/messages-request-id-headers.test.ts -1511 tests/claude-integration/messages-revoked-token.test.ts -302 tests/claude-integration/messages-shared-sse.test.ts -138 tests/claude-integration/messages-surface-matrix.test.ts -43 tests/cli/agent-driven.test.ts -93 tests/cli/agent-subagent-force.test.ts -1370 tests/cli/bun-transpiler-cache-scope.test.ts -93 tests/cli/claude-config-first-party.test.ts -15257 tests/cli/cli-access-audio-live.test.ts -866 tests/cli/cli-access-audio.test.ts -384 tests/cli/cli-access-data-plane.test.ts -134 tests/cli/cli-access-key-guard.test.ts -369 tests/cli/cli-access-rename.test.ts -94 tests/cli/cli-account-alias-target.test.ts -133 tests/cli/cli-account-cancel-flow.test.ts -149 tests/cli/cli-account-key-pause.test.ts -174 tests/cli/cli-account-key-quota.test.ts -329 tests/cli/cli-account-kiro-device.test.ts -917 tests/cli/cli-account-login-options.test.ts -81 tests/cli/cli-account-orca-import.test.ts -116 tests/cli/cli-account-pin-drain.test.ts -532 tests/cli/cli-account-policy.test.ts -87 tests/cli/cli-account-pool-verbs.test.ts -214 tests/cli/cli-account-preservation.test.ts -172 tests/cli/cli-account-slot-identity.test.ts -80 tests/cli/cli-account-threshold.test.ts -107 tests/cli/cli-account-verify-status.test.ts -979 tests/cli/cli-account.test.ts -277 tests/cli/cli-agent-runtime-settings.test.ts -474 tests/cli/cli-agent-settings.test.ts -203 tests/cli/cli-alias-json.test.ts -166 tests/cli/cli-anthropic-account-threshold.test.ts -113 tests/cli/cli-anthropic2-account.test.ts -414 tests/cli/cli-api-protocols.test.ts -128 tests/cli/cli-aside-sync.test.ts -77 tests/cli/cli-capabilities-arguments.test.ts -153 tests/cli/cli-capabilities.test.ts -99 tests/cli/cli-capability-access-workflows.test.ts -93 tests/cli/cli-capability-account-workflows.test.ts -160 tests/cli/cli-capability-agent-workflows.test.ts -2975 tests/cli/cli-capability-data.test.ts -228 tests/cli/cli-capability-integration-workflows.test.ts -205 tests/cli/cli-capability-lab-workflows.test.ts -352 tests/cli/cli-capability-operation-workflows.test.ts -115 tests/cli/cli-capability-provider-workflows.test.ts -114 tests/cli/cli-catalog-command-result.test.ts -52 tests/cli/cli-catalog-prewarm.test.ts -606 tests/cli/cli-claude-desktop-profile.test.ts -158 tests/cli/cli-client-start-fence.test.ts -2649 tests/cli/cli-client-start-owner-e2e.test.ts -8773 tests/cli/cli-codex-cli-update-boundary.test.ts -975 tests/cli/cli-codex-cli-update.test.ts -62 tests/cli/cli-codex-log-guard-compact.test.ts -120 tests/cli/cli-codex-log-guard-protection.test.ts -87 tests/cli/cli-codex-log-guard.test.ts -271 tests/cli/cli-combo-parity.test.ts -137 tests/cli/cli-combo-partial-update.test.ts -143 tests/cli/cli-combo-session-pin.test.ts -145 tests/cli/cli-combo-set-targets.test.ts -244 tests/cli/cli-combo-stats.test.ts -235 tests/cli/cli-companion-timeline.test.ts -234 tests/cli/cli-companion-usage.test.ts -79 tests/cli/cli-companion.test.ts -749 tests/cli/cli-config-bom.test.ts -5574 tests/cli/cli-config-command.test.ts -2226 tests/cli/cli-config-default-show.test.ts -2352 tests/cli/cli-config-show-client.test.ts -6959 tests/cli/cli-connect-readiness.test.ts -363 tests/cli/cli-dispatch.test.ts -124 tests/cli/cli-dto-fidelity.test.ts -103 tests/cli/cli-effort-slug.test.ts -185 tests/cli/cli-effort.test.ts -173 tests/cli/cli-ensure-client-state.test.ts -130 tests/cli/cli-ensure-desktop-cold-start.test.ts -113 tests/cli/cli-ensure-readiness.test.ts -768 tests/cli/cli-export-command.test.ts -153 tests/cli/cli-export-model-names.test.ts -89 tests/cli/cli-fallback.test.ts -47 tests/cli/cli-head.test.ts -684 tests/cli/cli-headless-parity.test.ts -2838 tests/cli/cli-help-navigation.test.ts -16831 tests/cli/cli-help-paths.test.ts -9080 tests/cli/cli-help-recovery.test.ts -12091 tests/cli/cli-help.test.ts -1066 tests/cli/cli-init-port.test.ts -131 tests/cli/cli-injection-follow.test.ts -83 tests/cli/cli-integer-options.test.ts -92 tests/cli/cli-integration-cursor.test.ts -109 tests/cli/cli-integration-droid.test.ts -268 tests/cli/cli-integration-journal.test.ts -643 tests/cli/cli-integration-preview.test.ts -153 tests/cli/cli-json-contract.test.ts -381 tests/cli/cli-json-input.test.ts -80 tests/cli/cli-kiro-auto-selection.test.ts -228 tests/cli/cli-link-child.test.ts -102 tests/cli/cli-link-cleanup.test.ts -103 tests/cli/cli-link-enrollment.test.ts -238 tests/cli/cli-link-force.test.ts -147 tests/cli/cli-link.test.ts -502 tests/cli/cli-log-follow.test.ts -123 tests/cli/cli-log-history.test.ts -315 tests/cli/cli-log-view-filter.test.ts -174 tests/cli/cli-logout-runtime.test.ts -100 tests/cli/cli-logs-request-id.test.ts -462 tests/cli/cli-management-auth.test.ts -1525 tests/cli/cli-message-mcp.test.ts -340 tests/cli/cli-models-custom-runtime.test.ts -167 tests/cli/cli-models-display-name.test.ts -85 tests/cli/cli-models-free-only.test.ts -157 tests/cli/cli-models-local-result.test.ts -131 tests/cli/cli-models-order.test.ts -252 tests/cli/cli-models-price.test.ts -92 tests/cli/cli-models-prompt-length-pricing.test.ts -153 tests/cli/cli-models-reasoning.test.ts -133 tests/cli/cli-models-runtime-dispatch.test.ts -216 tests/cli/cli-models-set.test.ts -12347 tests/cli/cli-models.test.ts -410 tests/cli/cli-native-profile.test.ts -109 tests/cli/cli-observe-logs.test.ts -116 tests/cli/cli-observe-snapshot.test.ts -93 tests/cli/cli-path-diagnostics.test.ts -545 tests/cli/cli-provider-batch.test.ts -121 tests/cli/cli-provider-cc-switch-import.test.ts -298 tests/cli/cli-provider-lifecycle-runtime.test.ts -2719 tests/cli/cli-provider-list-active.test.ts -306 tests/cli/cli-provider-result.test.ts -194 tests/cli/cli-provider-settings.test.ts -547 tests/cli/cli-provider-sync-result.test.ts -24795 tests/cli/cli-provider.test.ts -2131 tests/cli/cli-ready-subprocess.test.ts -111 tests/cli/cli-ready.test.ts -107 tests/cli/cli-registry.test.ts -231 tests/cli/cli-remote-workspace-hub.test.ts -2549 tests/cli/cli-resolve-subprocess.test.ts -131 tests/cli/cli-resolve.test.ts -129 tests/cli/cli-restart-handoff.test.ts -3408 tests/cli/cli-restart-health.test.ts -2658 tests/cli/cli-restore-back.test.ts -625 tests/cli/cli-role-suggestion-history.test.ts -133 tests/cli/cli-route-policy-not-found.test.ts -1109 tests/cli/cli-route-policy-write.test.ts -3723 tests/cli/cli-start-auxiliary-bind.test.ts -16336 tests/cli/cli-start-journal-order.test.ts -3756 tests/cli/cli-start-owner-absence.test.ts -3413 tests/cli/cli-start-owner-evidence.test.ts -21 tests/cli/cli-start-routing-heal-wiring.test.ts -511 tests/cli/cli-status-codex-routing-drift.test.ts -2557 tests/cli/cli-status-hub-state.test.ts -16755 tests/cli/cli-status-json.test.ts -137 tests/cli/cli-status-oauth-health.test.ts -1833 tests/cli/cli-status-startup-health.test.ts -107 tests/cli/cli-stop-json.test.ts -401 tests/cli/cli-stop-refusal-transport.test.ts -75 tests/cli/cli-storage-inspect.test.ts +93 tests/adapters/openai/openai-chat-required-tool.test.ts +117 tests/adapters/openai/openai-chat-sanitization-review-regressions.test.ts +110 tests/adapters/openai/openai-chat-serialized-tool-call-content.test.ts +248 tests/adapters/openai/openai-chat-serialized-tool-call-hold-bound.test.ts +141 tests/adapters/openai/openai-chat-serialized-tool-call-scaling.test.ts +82 tests/adapters/openai/openai-chat-serialized-tool-call-think.test.ts +67 tests/adapters/openai/openai-chat-single-system.test.ts +388 tests/adapters/openai/openai-chat-standalone-bare-block.test.ts +128 tests/adapters/openai/openai-chat-system-order.test.ts +52 tests/adapters/openai/openai-chat-tool-call-id-remint.test.ts +51 tests/adapters/openai/openai-chat-tool-result-images.test.ts +52 tests/adapters/openai/openai-chat-url.test.ts +60 tests/adapters/openai/openai-chat-video-part.test.ts +184 tests/adapters/openai/openai-empty-assistant-history.test.ts +266 tests/adapters/openai/openai-native-hosted-search-history.test.ts +1138 tests/adapters/openai/openai-provider-option-e2e.test.ts +406 tests/adapters/openai/openai-provider-option-migration.test.ts +69 tests/adapters/openai/openai-provider-option-startup.test.ts +63 tests/adapters/openai/openai-provider-option-tooling.test.ts +64 tests/adapters/openai/openai-provider-option.test.ts +44 tests/adapters/openai/opengateway-input.test.ts +186 tests/adapters/physical-send.test.ts +87 tests/adapters/qoder-spawn-readmission.test.ts +85 tests/adapters/reasoning-replay-identity.test.ts +169 tests/adapters/reasoning-replay-robustness.test.ts +215 tests/adapters/routed-agent-messages.test.ts +106 tests/adapters/run-turn-queue.test.ts +832 tests/adapters/terminal-continuation-owner-rotation.test.ts +85 tests/adapters/tool-argument-integers.test.ts +68 tests/adapters/tool-catalog-nudge.test.ts +47 tests/adapters/tool-choice-performance.test.ts +108 tests/adapters/tool-envelope-echo-whole-line.test.ts +54 tests/adapters/tool-identity-hash.test.ts +270 tests/adapters/translator-budget-lifetime.test.ts +4651 tests/adapters/translator-budget.test.ts +44 tests/adapters/upstream-http-error.test.ts +126 tests/adapters/workbuddy-adapter.test.ts +96 tests/advisor/advisor-adaptive.test.ts +85 tests/advisor/advisor-authority-transport.test.ts +60 tests/advisor/advisor-budget.test.ts +486 tests/advisor/advisor-caller-policy-compact.test.ts +367 tests/advisor/advisor-caller-policy-host-key.test.ts +336 tests/advisor/advisor-caller-policy-http.test.ts +361 tests/advisor/advisor-caller-policy-ingress.test.ts +320 tests/advisor/advisor-caller-policy-jev.test.ts +374 tests/advisor/advisor-caller-policy-replay.test.ts +786 tests/advisor/advisor-caller-policy-routing.test.ts +387 tests/advisor/advisor-caller-policy-self-fetch.test.ts +183 tests/advisor/advisor-caller-policy-sidecar-authority.test.ts +452 tests/advisor/advisor-caller-policy-vision.test.ts +695 tests/advisor/advisor-caller-policy.test.ts +62 tests/advisor/advisor-consult.test.ts +61 tests/advisor/advisor-context.test.ts +61 tests/advisor/advisor-continuation-limit.test.ts +353 tests/advisor/advisor-core-boundary.test.ts +85 tests/advisor/advisor-evidence.test.ts +66 tests/advisor/advisor-guard.test.ts +168 tests/advisor/advisor-internal-authority.test.ts +75 tests/advisor/advisor-plan.test.ts +926 tests/advisor/advisor-responses-wiring.test.ts +332 tests/advisor/advisor-retention.test.ts +311 tests/advisor/advisor-scope-transport.test.ts +149 tests/advisor/advisor-settings.test.ts +83 tests/advisor/advisor-state.test.ts +224 tests/advisor/advisor-web-search.test.ts +3210 tests/ci-workflows/assert-mergeable-review.test.ts +65 tests/ci-workflows/brand-favicons.test.ts +52 tests/ci-workflows/build-desktop-icon-set.test.ts +72 tests/ci-workflows/build-release-changelog.test.ts +178 tests/ci-workflows/bump-dev-version.test.ts +200 tests/ci-workflows/bun-runtime.test.ts +47 tests/ci-workflows/ci-bun-crash-classifier.test.ts +35975 tests/ci-workflows/ci-bun-install-frozen.test.ts +63 tests/ci-workflows/ci-concurrency-groups.test.ts +5124 tests/ci-workflows/ci-crash-disposition.test.ts +1798 tests/ci-workflows/ci-gui-typecheck-gate.test.ts +114 tests/ci-workflows/ci-pr-hygiene-approvals.test.ts +1099 tests/ci-workflows/ci-privacy-gate.test.ts +6271 tests/ci-workflows/ci-review-lanes.test.ts +701 tests/ci-workflows/ci-scope-gaps.test.ts +566 tests/ci-workflows/ci-scope-reduction.test.ts +760 tests/ci-workflows/ci-shard-balance.test.ts +107 tests/ci-workflows/ci-structure-gate.test.ts +1275 tests/ci-workflows/ci-test-lane.test.ts +619 tests/ci-workflows/ci-workflows.test.ts +55 tests/ci-workflows/cleanup-orphaned-workflows.test.ts +176 tests/ci-workflows/client-support-matrix.test.ts +1077 tests/ci-workflows/client-support-runtime.test.ts +66 tests/ci-workflows/closed-pr-branch-cleanup.test.ts +6545 tests/ci-workflows/cold-spawn-warmup.test.ts +316 tests/ci-workflows/compatibility-version.test.ts +60 tests/ci-workflows/docs-429-failover-claims.test.ts +55 tests/ci-workflows/docs-bun-source-requirement.test.ts +87 tests/ci-workflows/docs-developer-role-policy.test.ts +120 tests/ci-workflows/docs-gjc-reasoning-export.test.ts +68 tests/ci-workflows/docs-gpt61-terra.test.ts +54 tests/ci-workflows/docs-gui-screenshot-policy.test.ts +225 tests/ci-workflows/docs-link-targets.test.ts +44 tests/ci-workflows/docs-provider-billing-claims.test.ts +79 tests/ci-workflows/docs-provider-discovery-limits.test.ts +95 tests/ci-workflows/docs-provider-preset-counts.test.ts +227 tests/ci-workflows/docs-readme-memory-inventory.test.ts +53 tests/ci-workflows/docs-readme-translation-parity.test.ts +75 tests/ci-workflows/docs-remote-hub-claims.test.ts +178 tests/ci-workflows/dsh-path-contract.test.ts +270 tests/ci-workflows/dsh-rc6-compat-script.test.ts +182 tests/ci-workflows/dsh-writer-lock.test.ts +47 tests/ci-workflows/exhaustive-deps-suppression.test.ts +457 tests/ci-workflows/file-size-ratchet.test.ts +463 tests/ci-workflows/fixture-dir-uniqueness.test.ts +72 tests/ci-workflows/fixture-teardown-helper.test.ts +607 tests/ci-workflows/fixture-windows-runtime-preload.test.ts +413 tests/ci-workflows/import-cycle-ratchet.test.ts +207 tests/ci-workflows/install-scripts.test.ts +121 tests/ci-workflows/installed-gate-drivers.test.ts +56 tests/ci-workflows/keyring-smoke.test.ts +72 tests/ci-workflows/linux-desktop-packaged-ci.test.ts +46 tests/ci-workflows/linux-desktop-packaged-e2e.test.ts +4231 tests/ci-workflows/macos-serial-lanes.test.ts +2722 tests/ci-workflows/package-tree-fenced-restart.test.ts +2927 tests/ci-workflows/package-tree-integrity.test.ts +149 tests/ci-workflows/package-tree-restart-ownership.test.ts +159 tests/ci-workflows/package-tree-retarget.test.ts +110 tests/ci-workflows/pr-readiness-reattest.test.ts +120 tests/ci-workflows/privacy-scan-asset-names.test.ts +43 tests/ci-workflows/privacy-scan-meta-key.test.ts +50 tests/ci-workflows/privacy-scan-ssh-endpoint.test.ts +87 tests/ci-workflows/release-desktop-scripts.test.ts +7895 tests/ci-workflows/release-helper.test.ts +65 tests/ci-workflows/release-notes.test.ts +102 tests/ci-workflows/release-outcome-report.test.ts +118 tests/ci-workflows/release-pipeline-contract.test.ts +1768 tests/ci-workflows/release-preflight.test.ts +160 tests/ci-workflows/release-resume-identity.test.ts +64 tests/ci-workflows/release-version-line.test.ts +170 tests/ci-workflows/release-version-sources.test.ts +23376 tests/ci-workflows/release-windows-signing.test.ts +211 tests/ci-workflows/repo-hygiene.test.ts +467 tests/ci-workflows/repo-import-resolution.test.ts +468 tests/ci-workflows/setup-hooks.test.ts +561 tests/ci-workflows/skill-ocx-generated.test.ts +146 tests/ci-workflows/skill-ocx-workflows.test.ts +70 tests/ci-workflows/skill-ocx.test.ts +476 tests/ci-workflows/structure-ssot.test.ts +1092 tests/ci-workflows/test-home-guard-unpreloaded.test.ts +41562 tests/ci-workflows/test-home-guard.test.ts +20921 tests/ci-workflows/test-run-lock-generation.test.ts +191 tests/ci-workflows/test-runner-bun.test.ts +405 tests/ci-workflows/test-runner-spawnsync-finalizer.test.ts +18212 tests/ci-workflows/test-runner.test.ts +61 tests/ci-workflows/test-sandbox-cleanup.test.ts +48 tests/ci-workflows/test-temp-quarantine.test.ts +44 tests/ci-workflows/version-line.test.ts +81 tests/ci-workflows/warmup-registration.test.ts +62 tests/ci-workflows/zz-ci-api-usage-isolation.test.ts +57 tests/ci-workflows/zz-ci-storage-policy-isolation.test.ts +80 tests/ci-workflows/zz-pr-coderabbit-readiness-revalidation.test.ts +2078 tests/claude-integration/anthropic2-native-routing.test.ts +3173 tests/claude-integration/claude-529-mapping.test.ts +117 tests/claude-integration/claude-agent-startup-sync.test.ts +106 tests/claude-integration/claude-agents-inject-client.test.ts +219 tests/claude-integration/claude-agents-inject.test.ts +209 tests/claude-integration/claude-alias.test.ts +43 tests/claude-integration/claude-auth-detect.test.ts +148 tests/claude-integration/claude-auth-mode.test.ts +53 tests/claude-integration/claude-authmode-migration.test.ts +760 tests/claude-integration/claude-bridge-pool-dispatch.test.ts +171 tests/claude-integration/claude-bridge-pool-session.test.ts +405 tests/claude-integration/claude-cli-picker-surface.test.ts +525 tests/claude-integration/claude-cli-picker.test.ts +157 tests/claude-integration/claude-cli.test.ts +1040 tests/claude-integration/claude-client-refusal-status.test.ts +286 tests/claude-integration/claude-code-thought-signature-scope.test.ts +59 tests/claude-integration/claude-compatibility.test.ts +288 tests/claude-integration/claude-config-home-isolation.test.ts +859 tests/claude-integration/claude-config-root-late-admission.test.ts +465 tests/claude-integration/claude-config-root-stale-updates.test.ts +433 tests/claude-integration/claude-config-root-writer-barrier.test.ts +95 tests/claude-integration/claude-context-accounting.test.ts +132 tests/claude-integration/claude-context-windows.test.ts +125 tests/claude-integration/claude-desktop-1m.test.ts +884 tests/claude-integration/claude-desktop-cli.test.ts +597 tests/claude-integration/claude-desktop-config-path.test.ts +1222 tests/claude-integration/claude-desktop-discovery.test.ts +433 tests/claude-integration/claude-desktop-first-party-guards.test.ts +1042 tests/claude-integration/claude-desktop-first-party.test.ts +147 tests/claude-integration/claude-desktop-mode-explanation.test.ts +881 tests/claude-integration/claude-desktop-model-visibility.test.ts +107 tests/claude-integration/claude-desktop-native-context.test.ts +696 tests/claude-integration/claude-desktop-picker-profile.test.ts +703 tests/claude-integration/claude-desktop-picker-routes.test.ts +162 tests/claude-integration/claude-desktop-picker.test.ts +48 tests/claude-integration/claude-desktop-policy.test.ts +7727 tests/claude-integration/claude-desktop-remote-hub.test.ts +133 tests/claude-integration/claude-desktop-system-proxy.test.ts +566 tests/claude-integration/claude-devin-output-order.test.ts +114 tests/claude-integration/claude-dotenv-provenance-transport.test.ts +833 tests/claude-integration/claude-estimate-projection.test.ts +457 tests/claude-integration/claude-first-party-agent-sync.test.ts +152 tests/claude-integration/claude-first-party-union.test.ts +88 tests/claude-integration/claude-gateway-cache.test.ts +385 tests/claude-integration/claude-gateway-output-cap.test.ts +405 tests/claude-integration/claude-inbound-cache-stabilize.test.ts +73 tests/claude-integration/claude-inbound-debug.test.ts +106 tests/claude-integration/claude-inbound-token-footer.test.ts +416 tests/claude-integration/claude-inbound-tool-loading.test.ts +136 tests/claude-integration/claude-inbound-tool-reference.test.ts +131 tests/claude-integration/claude-inbound.test.ts +407 tests/claude-integration/claude-installation-helper.test.ts +370 tests/claude-integration/claude-intercept-acl-barrier.test.ts +89 tests/claude-integration/claude-intercept-cleanup.test.ts +181 tests/claude-integration/claude-intercept-client-class.test.ts +91 tests/claude-integration/claude-intercept-local-ca-files.test.ts +155 tests/claude-integration/claude-intercept-local-ca-windows.test.ts +180 tests/claude-integration/claude-intercept-local-ca.test.ts +175 tests/claude-integration/claude-intercept-model-bindings.test.ts +162 tests/claude-integration/claude-intercept-no-proxy.test.ts +258 tests/claude-integration/claude-intercept-on-demand.test.ts +166 tests/claude-integration/claude-intercept-proxy-auth.test.ts +145 tests/claude-integration/claude-intercept-proxy.test.ts +138 tests/claude-integration/claude-intercept-settings.test.ts +119 tests/claude-integration/claude-long-context-eligibility.test.ts +5469 tests/claude-integration/claude-management-api.test.ts +6495 tests/claude-integration/claude-messages-endpoint.test.ts +566 tests/claude-integration/claude-messages-thread.test.ts +133 tests/claude-integration/claude-model-default-labels.test.ts +126 tests/claude-integration/claude-model-info.test.ts +1143 tests/claude-integration/claude-models-discovery.test.ts +2488 tests/claude-integration/claude-native-affinity.test.ts +1044 tests/claude-integration/claude-native-fast-1m-ingress.test.ts +9103 tests/claude-integration/claude-native-passthrough.test.ts +191 tests/claude-integration/claude-native-rate-limit-headers.test.ts +96 tests/claude-integration/claude-native-reasoning-continuity.test.ts +391 tests/claude-integration/claude-native-reasoning-provenance.test.ts +2485 tests/claude-integration/claude-outbound.test.ts +110 tests/claude-integration/claude-output-schema-strict.test.ts +266 tests/claude-integration/claude-picker-bootstrap.test.ts +387 tests/claude-integration/claude-picker-ca-store.test.ts +456 tests/claude-integration/claude-picker-ca.test.ts +82 tests/claude-integration/claude-picker-linger.test.ts +672 tests/claude-integration/claude-picker-listener.test.ts +168 tests/claude-integration/claude-picker-models.test.ts +1313 tests/claude-integration/claude-picker-recovery.test.ts +285 tests/claude-integration/claude-picker-relay-intent.test.ts +490 tests/claude-integration/claude-picker-runtime.test.ts +1656 tests/claude-integration/claude-picker-startup.test.ts +88 tests/claude-integration/claude-picker-trust-windows.test.ts +45 tests/claude-integration/claude-picker-trust.test.ts +4150 tests/claude-integration/claude-picker-upload.test.ts +699 tests/claude-integration/claude-picker-windows.test.ts +2024 tests/claude-integration/claude-prompt-too-long.test.ts +118 tests/claude-integration/claude-shell-hook.test.ts +127 tests/claude-integration/claude-sidecar-override.test.ts +113 tests/claude-integration/claude-source-envelope.test.ts +124 tests/claude-integration/claude-subagent-model-force.test.ts +141 tests/claude-integration/claude-system-env-auto.test.ts +446 tests/claude-integration/claude-tool-loading-destinations.test.ts +339 tests/claude-integration/claude-translated-cache-ttl.test.ts +865 tests/claude-integration/claude-translated-server-tools.test.ts +330 tests/claude-integration/claude-translated-tool-restrictions.test.ts +261 tests/claude-integration/messages-native-clean-eof.test.ts +183 tests/claude-integration/messages-native-decline-trace.test.ts +613 tests/claude-integration/messages-native-empty-inline.test.ts +666 tests/claude-integration/messages-native-key-selection.test.ts +2246 tests/claude-integration/messages-native-oauth.test.ts +289 tests/claude-integration/messages-native-opaque-state.test.ts +576 tests/claude-integration/messages-native-scope.test.ts +2810 tests/claude-integration/messages-native.test.ts +2443 tests/claude-integration/messages-request-id-endpoint.test.ts +126 tests/claude-integration/messages-request-id-headers.test.ts +1549 tests/claude-integration/messages-revoked-token.test.ts +287 tests/claude-integration/messages-shared-sse.test.ts +244 tests/claude-integration/messages-surface-matrix.test.ts +51 tests/cli/agent-driven.test.ts +106 tests/cli/agent-subagent-force.test.ts +575 tests/cli/bun-transpiler-cache-scope.test.ts +218 tests/cli/claude-config-first-party.test.ts +15213 tests/cli/cli-access-audio-live.test.ts +381 tests/cli/cli-access-audio.test.ts +159 tests/cli/cli-access-data-plane.test.ts +96 tests/cli/cli-access-key-guard.test.ts +247 tests/cli/cli-access-rename.test.ts +125 tests/cli/cli-account-alias-target.test.ts +56 tests/cli/cli-account-cancel-flow.test.ts +144 tests/cli/cli-account-key-pause.test.ts +139 tests/cli/cli-account-key-quota.test.ts +96 tests/cli/cli-account-kiro-device.test.ts +616 tests/cli/cli-account-login-options.test.ts +53 tests/cli/cli-account-orca-import.test.ts +104 tests/cli/cli-account-pin-drain.test.ts +686 tests/cli/cli-account-policy.test.ts +94 tests/cli/cli-account-pool-verbs.test.ts +102 tests/cli/cli-account-preservation.test.ts +76 tests/cli/cli-account-slot-identity.test.ts +70 tests/cli/cli-account-threshold.test.ts +114 tests/cli/cli-account-verify-status.test.ts +556 tests/cli/cli-account.test.ts +210 tests/cli/cli-agent-runtime-settings.test.ts +303 tests/cli/cli-agent-settings.test.ts +82 tests/cli/cli-alias-json.test.ts +79 tests/cli/cli-anthropic-account-threshold.test.ts +107 tests/cli/cli-anthropic2-account.test.ts +163 tests/cli/cli-api-protocols.test.ts +121 tests/cli/cli-aside-sync.test.ts +114 tests/cli/cli-capabilities-arguments.test.ts +177 tests/cli/cli-capabilities.test.ts +107 tests/cli/cli-capability-access-workflows.test.ts +137 tests/cli/cli-capability-account-workflows.test.ts +149 tests/cli/cli-capability-agent-workflows.test.ts +2429 tests/cli/cli-capability-data.test.ts +181 tests/cli/cli-capability-integration-workflows.test.ts +202 tests/cli/cli-capability-lab-workflows.test.ts +135 tests/cli/cli-capability-operation-workflows.test.ts +80 tests/cli/cli-capability-provider-workflows.test.ts +109 tests/cli/cli-catalog-command-result.test.ts +49 tests/cli/cli-catalog-prewarm.test.ts +467 tests/cli/cli-claude-desktop-profile.test.ts +130 tests/cli/cli-client-start-fence.test.ts +1939 tests/cli/cli-client-start-owner-e2e.test.ts +8021 tests/cli/cli-codex-cli-update-boundary.test.ts +706 tests/cli/cli-codex-cli-update.test.ts +101 tests/cli/cli-codex-log-guard-compact.test.ts +208 tests/cli/cli-codex-log-guard-protection.test.ts +91 tests/cli/cli-codex-log-guard.test.ts +197 tests/cli/cli-combo-parity.test.ts +105 tests/cli/cli-combo-partial-update.test.ts +176 tests/cli/cli-combo-session-pin.test.ts +195 tests/cli/cli-combo-set-targets.test.ts +121 tests/cli/cli-combo-stats.test.ts +124 tests/cli/cli-companion-timeline.test.ts +110 tests/cli/cli-companion-usage.test.ts +93 tests/cli/cli-companion.test.ts +986 tests/cli/cli-config-bom.test.ts +6223 tests/cli/cli-config-command.test.ts +1636 tests/cli/cli-config-default-show.test.ts +2245 tests/cli/cli-config-show-client.test.ts +6253 tests/cli/cli-connect-readiness.test.ts +289 tests/cli/cli-dispatch.test.ts +92 tests/cli/cli-dto-fidelity.test.ts +128 tests/cli/cli-effort-slug.test.ts +227 tests/cli/cli-effort.test.ts +156 tests/cli/cli-ensure-client-state.test.ts +126 tests/cli/cli-ensure-desktop-cold-start.test.ts +82 tests/cli/cli-ensure-readiness.test.ts +811 tests/cli/cli-export-command.test.ts +112 tests/cli/cli-export-model-names.test.ts +86 tests/cli/cli-fallback.test.ts +56 tests/cli/cli-head.test.ts +367 tests/cli/cli-headless-parity.test.ts +3015 tests/cli/cli-help-navigation.test.ts +16954 tests/cli/cli-help-paths.test.ts +6281 tests/cli/cli-help-recovery.test.ts +13720 tests/cli/cli-help.test.ts +1181 tests/cli/cli-init-port.test.ts +130 tests/cli/cli-injection-follow.test.ts +92 tests/cli/cli-integer-options.test.ts +90 tests/cli/cli-integration-cursor.test.ts +105 tests/cli/cli-integration-droid.test.ts +252 tests/cli/cli-integration-journal.test.ts +411 tests/cli/cli-integration-preview.test.ts +118 tests/cli/cli-json-contract.test.ts +356 tests/cli/cli-json-input.test.ts +90 tests/cli/cli-kiro-auto-selection.test.ts +166 tests/cli/cli-link-child.test.ts +177 tests/cli/cli-link-cleanup.test.ts +131 tests/cli/cli-link-enrollment.test.ts +261 tests/cli/cli-link-force.test.ts +226 tests/cli/cli-link.test.ts +351 tests/cli/cli-log-follow.test.ts +113 tests/cli/cli-log-history.test.ts +281 tests/cli/cli-log-view-filter.test.ts +196 tests/cli/cli-logout-runtime.test.ts +129 tests/cli/cli-logs-request-id.test.ts +106 tests/cli/cli-management-auth.test.ts +1695 tests/cli/cli-message-mcp.test.ts +229 tests/cli/cli-models-custom-runtime.test.ts +207 tests/cli/cli-models-display-name.test.ts +87 tests/cli/cli-models-free-only.test.ts +178 tests/cli/cli-models-local-result.test.ts +114 tests/cli/cli-models-order.test.ts +121 tests/cli/cli-models-price.test.ts +101 tests/cli/cli-models-prompt-length-pricing.test.ts +148 tests/cli/cli-models-reasoning.test.ts +119 tests/cli/cli-models-runtime-dispatch.test.ts +155 tests/cli/cli-models-set.test.ts +11439 tests/cli/cli-models.test.ts +172 tests/cli/cli-native-profile.test.ts +98 tests/cli/cli-observe-logs.test.ts +108 tests/cli/cli-observe-snapshot.test.ts +91 tests/cli/cli-path-diagnostics.test.ts +217 tests/cli/cli-provider-batch.test.ts +112 tests/cli/cli-provider-cc-switch-import.test.ts +204 tests/cli/cli-provider-lifecycle-runtime.test.ts +2979 tests/cli/cli-provider-list-active.test.ts +74 tests/cli/cli-provider-result.test.ts +139 tests/cli/cli-provider-settings.test.ts +454 tests/cli/cli-provider-sync-result.test.ts +24137 tests/cli/cli-provider.test.ts +1218 tests/cli/cli-ready-subprocess.test.ts +56 tests/cli/cli-ready.test.ts +116 tests/cli/cli-registry.test.ts +157 tests/cli/cli-remote-workspace-hub.test.ts +2708 tests/cli/cli-resolve-subprocess.test.ts +70 tests/cli/cli-resolve.test.ts +93 tests/cli/cli-restart-handoff.test.ts +3091 tests/cli/cli-restart-health.test.ts +2194 tests/cli/cli-restore-back.test.ts +563 tests/cli/cli-role-suggestion-history.test.ts +104 tests/cli/cli-route-policy-not-found.test.ts +1270 tests/cli/cli-route-policy-write.test.ts +3200 tests/cli/cli-start-auxiliary-bind.test.ts +16894 tests/cli/cli-start-journal-order.test.ts +4029 tests/cli/cli-start-owner-absence.test.ts +3974 tests/cli/cli-start-owner-evidence.test.ts +83 tests/cli/cli-start-routing-heal-wiring.test.ts +117 tests/cli/cli-status-codex-routing-drift.test.ts +2948 tests/cli/cli-status-hub-state.test.ts +14097 tests/cli/cli-status-json.test.ts +129 tests/cli/cli-status-oauth-health.test.ts +1781 tests/cli/cli-status-startup-health.test.ts +131 tests/cli/cli-stop-json.test.ts +420 tests/cli/cli-stop-refusal-transport.test.ts +94 tests/cli/cli-storage-inspect.test.ts 266 tests/cli/cli-storage-policy-fields.test.ts -220 tests/cli/cli-sync-expect-link.test.ts -237 tests/cli/cli-system-health.test.ts -133 tests/cli/cli-system-settings-parity.test.ts -130 tests/cli/cli-transport-honesty.test.ts -1281 tests/cli/cli-update-badge.test.ts -481 tests/cli/cli-update-restart-admission.test.ts -45 tests/cli/cli-update-restart-child.test.ts -96 tests/cli/cli-update-restart-desktop-service.test.ts -176 tests/cli/cli-update-restart-home.test.ts -96 tests/cli/cli-update-restart-service-record.test.ts -44 tests/cli/cli-update-restart-supervision.test.ts -644 tests/cli/cli-update-restart-transport.test.ts -408 tests/cli/cli-update-restart.test.ts -3391 tests/cli/cli-usage-compare.test.ts -98 tests/cli/cli-usage-hub.test.ts -96 tests/cli/cli-usage-model-search.test.ts -118 tests/cli/cli-usage-report.test.ts -167 tests/cli/cli-usage-scope.test.ts -1431 tests/cli/cli-usage-top.test.ts -743 tests/cli/cli-v2-runtime.test.ts -8820 tests/cli/cli-version-skew.test.ts -96 tests/cli/cross-home-loopback-family.test.ts -137 tests/cli/ensure-desired-integrations-race.test.ts -1320 tests/cli/hub-disable.test.ts -386 tests/cli/hub-gated-local-clients.test.ts -146 tests/cli/hub-invite.test.ts -52 tests/cli/interactive-confirm.test.ts -71 tests/cli/link-apply-restart.test.ts -213 tests/cli/local-credentials.test.ts -59 tests/cli/model-selection-guidance.test.ts -2296 tests/cli/ocx-launcher-desktop-handoff.test.ts -69 tests/cli/ocx-launcher-fixture-trust.test.ts -3584 tests/cli/ocx-launcher-runtime.test.ts -36 tests/cli/ocx-launcher-source.test.ts -33 tests/cli/ocx-run.test.ts -1012 tests/cli/restore-completes-shared-teardown.test.ts -773 tests/cli/route-explainability.test.ts -16310 tests/cli/sibling-home-client-sync.test.ts -62 tests/cli/star-deferral.test.ts -58 tests/cli/start-args.test.ts -42 tests/cli/start-ownership-publication.test.ts -444 tests/cli/status-install-method.test.ts -41 tests/cli/system-restart-client-package-tree.test.ts -82 tests/cli/system-restart-client.test.ts -338 tests/cli/uninstall.test.ts -171 tests/clients/agent-clients.test.ts -97 tests/clients/aside-profile-identity.test.ts -261 tests/clients/aside-profile-paths.test.ts -2024 tests/clients/aside-profile-sync-owner.test.ts -186 tests/clients/aside-profiles-catalog-refresh.test.ts -564 tests/clients/aside-profiles.test.ts -112 tests/clients/client-catalog-compatibility.test.ts -26804 tests/clients/client-connect.test.ts -141 tests/clients/client-export-effective-metadata.test.ts -725 tests/clients/client-export-live-wire.test.ts -149 tests/clients/client-export-modality-enum.test.ts -403 tests/clients/client-export-model-names.test.ts -99 tests/clients/client-export-reasoning-controls.test.ts -119 tests/clients/client-export-reasoning-metadata.test.ts -58 tests/clients/client-fingerprint.test.ts -265 tests/clients/client-home-unreachable.test.ts -56 tests/clients/client-hub-relay.test.ts -83 tests/clients/client-hub-state.test.ts -73 tests/clients/client-hub-usage.test.ts -378 tests/clients/client-lifecycle-lock.test.ts -392 tests/clients/client-link-connect.test.ts -5325 tests/clients/client-link-relay.test.ts -6608 tests/clients/client-link-runtime.test.ts -104 tests/clients/client-link-state.test.ts -48 tests/clients/client-link-status.test.ts -255 tests/clients/client-link-teardown.test.ts -4595 tests/clients/client-link-tunnel.test.ts -5285 tests/clients/client-machine-listener.test.ts -89 tests/clients/client-path.test.ts -161 tests/clients/client-runtime-restart.test.ts -109 tests/clients/client-runtime.test.ts -92 tests/clients/cline-client.test.ts -459 tests/clients/cline-writer.test.ts -208 tests/clients/command-code-client-contract.test.ts -117 tests/clients/command-code-client.test.ts -103 tests/clients/desktop-3p-guard.test.ts -1213 tests/clients/desktop-3p-removal.test.ts -1005 tests/clients/desktop-3p-write-files.test.ts -337 tests/clients/desktop-3p.test.ts -54 tests/clients/desktop-app-restart-posix.test.ts -127 tests/clients/desktop-app-restart.test.ts -152 tests/clients/desktop-app-server-exec-boundary.test.ts -4145 tests/clients/desktop-app-server-shim-launcher.test.ts -69 tests/clients/desktop-app-server-shim.test.ts -16075 tests/clients/desktop-bundle-trust-async.test.ts -66 tests/clients/desktop-chatgpt-config.test.ts -50 tests/clients/desktop-cli-command-surface.test.ts -114 tests/clients/desktop-cli-contracts.test.ts -97 tests/clients/desktop-compatibility-authority.test.ts +402 tests/cli/cli-sync-expect-link.test.ts +162 tests/cli/cli-system-health.test.ts +172 tests/cli/cli-system-settings-parity.test.ts +136 tests/cli/cli-transport-honesty.test.ts +1631 tests/cli/cli-update-badge.test.ts +470 tests/cli/cli-update-restart-admission.test.ts +61 tests/cli/cli-update-restart-child.test.ts +103 tests/cli/cli-update-restart-desktop-service.test.ts +131 tests/cli/cli-update-restart-home.test.ts +82 tests/cli/cli-update-restart-service-record.test.ts +57 tests/cli/cli-update-restart-supervision.test.ts +665 tests/cli/cli-update-restart-transport.test.ts +343 tests/cli/cli-update-restart.test.ts +2668 tests/cli/cli-usage-compare.test.ts +152 tests/cli/cli-usage-hub.test.ts +193 tests/cli/cli-usage-model-search.test.ts +104 tests/cli/cli-usage-report.test.ts +232 tests/cli/cli-usage-scope.test.ts +1457 tests/cli/cli-usage-top.test.ts +727 tests/cli/cli-v2-runtime.test.ts +10326 tests/cli/cli-version-skew.test.ts +135 tests/cli/cross-home-loopback-family.test.ts +152 tests/cli/ensure-desired-integrations-race.test.ts +1353 tests/cli/hub-disable.test.ts +257 tests/cli/hub-gated-local-clients.test.ts +131 tests/cli/hub-invite.test.ts +59 tests/cli/interactive-confirm.test.ts +87 tests/cli/link-apply-restart.test.ts +182 tests/cli/local-credentials.test.ts +107 tests/cli/model-selection-guidance.test.ts +2989 tests/cli/ocx-launcher-desktop-handoff.test.ts +61 tests/cli/ocx-launcher-fixture-trust.test.ts +2973 tests/cli/ocx-launcher-runtime.test.ts +103 tests/cli/ocx-launcher-source.test.ts +72 tests/cli/ocx-run.test.ts +1023 tests/cli/restore-completes-shared-teardown.test.ts +736 tests/cli/route-explainability.test.ts +15934 tests/cli/sibling-home-client-sync.test.ts +55 tests/cli/star-deferral.test.ts +56 tests/cli/start-args.test.ts +57 tests/cli/start-ownership-publication.test.ts +433 tests/cli/status-install-method.test.ts +2453 tests/cli/sync-command-fanout.test.ts +3284 tests/cli/sync-fanout-process.test.ts +154 tests/cli/sync-fanout.test.ts +237 tests/cli/sync-link-status.test.ts +57 tests/cli/system-restart-client-package-tree.test.ts +75 tests/cli/system-restart-client.test.ts +281 tests/cli/uninstall.test.ts +134 tests/clients/agent-clients.test.ts +157 tests/clients/aside-profile-identity.test.ts +185 tests/clients/aside-profile-paths.test.ts +1735 tests/clients/aside-profile-sync-owner.test.ts +200 tests/clients/aside-profiles-catalog-refresh.test.ts +666 tests/clients/aside-profiles.test.ts +115 tests/clients/client-catalog-compatibility.test.ts +22696 tests/clients/client-connect.test.ts +188 tests/clients/client-export-effective-metadata.test.ts +603 tests/clients/client-export-live-wire.test.ts +100 tests/clients/client-export-modality-enum.test.ts +244 tests/clients/client-export-model-names.test.ts +255 tests/clients/client-export-reasoning-controls.test.ts +92 tests/clients/client-export-reasoning-metadata.test.ts +65 tests/clients/client-fingerprint.test.ts +302 tests/clients/client-home-unreachable.test.ts +86 tests/clients/client-hub-relay.test.ts +67 tests/clients/client-hub-state.test.ts +78 tests/clients/client-hub-usage.test.ts +289 tests/clients/client-lifecycle-lock.test.ts +351 tests/clients/client-link-connect.test.ts +5313 tests/clients/client-link-relay.test.ts +6852 tests/clients/client-link-runtime.test.ts +83 tests/clients/client-link-state.test.ts +61 tests/clients/client-link-status.test.ts +239 tests/clients/client-link-teardown.test.ts +4159 tests/clients/client-link-tunnel.test.ts +5363 tests/clients/client-machine-listener.test.ts +116 tests/clients/client-path.test.ts +168 tests/clients/client-runtime-restart.test.ts +223 tests/clients/client-runtime.test.ts +108 tests/clients/cline-client.test.ts +382 tests/clients/cline-writer.test.ts +169 tests/clients/command-code-client-contract.test.ts +111 tests/clients/command-code-client.test.ts +90 tests/clients/desktop-3p-guard.test.ts +1070 tests/clients/desktop-3p-removal.test.ts +1221 tests/clients/desktop-3p-write-files.test.ts +287 tests/clients/desktop-3p.test.ts +62 tests/clients/desktop-app-restart-posix.test.ts +131 tests/clients/desktop-app-restart.test.ts +123 tests/clients/desktop-app-server-exec-boundary.test.ts +3515 tests/clients/desktop-app-server-shim-launcher.test.ts +58 tests/clients/desktop-app-server-shim.test.ts +16093 tests/clients/desktop-bundle-trust-async.test.ts +57 tests/clients/desktop-chatgpt-config.test.ts +120 tests/clients/desktop-cli-command-surface.test.ts +121 tests/clients/desktop-cli-contracts.test.ts +79 tests/clients/desktop-compatibility-authority.test.ts 50 tests/clients/desktop-compatibility-build-probe.test.ts -54 tests/clients/desktop-compatibility-certificate-service.test.ts -90 tests/clients/desktop-compatibility-connection-store.test.ts -63 tests/clients/desktop-compatibility-launch.test.ts -97 tests/clients/desktop-compatibility-native-identity.test.ts -172 tests/clients/desktop-compatibility-relay.test.ts -61 tests/clients/desktop-compatibility-routing.test.ts -325 tests/clients/desktop-compatibility-runtime.test.ts -52 tests/clients/desktop-compatibility-trust.test.ts -84 tests/clients/desktop-exit-ownership.test.ts -81 tests/clients/desktop-host-visibility.test.ts -39 tests/clients/desktop-install-identity.test.ts -416 tests/clients/desktop-profile.test.ts -47 tests/clients/desktop-proxy-direct-transport.test.ts -583 tests/clients/desktop-remote-store.test.ts -63 tests/clients/desktop-restart-handoff.test.ts -52 tests/clients/desktop-runtime-identity.test.ts -58 tests/clients/desktop-start-at-login-default.test.ts -51 tests/clients/desktop-startup-surface.test.ts -628 tests/clients/desktop-supervised-restart.test.ts -100 tests/clients/desktop-tray-availability.test.ts -61 tests/clients/desktop-update-surface.test.ts -46 tests/clients/desktop-widget-entry.test.ts -166 tests/clients/droid-client.test.ts -217 tests/clients/droid-managed-reasoning-defaults.test.ts -145 tests/clients/droid-normalized-reasoning-defaults.test.ts -158 tests/clients/gentle-shell-client.test.ts -166 tests/clients/gentle-shell-path.test.ts -288 tests/clients/hermes-catalog-refresh.test.ts -459 tests/clients/hermes-profile-routes.test.ts -126 tests/clients/hermes-profiles.test.ts -237 tests/clients/integrations-current-store.test.ts -284 tests/clients/integrations-dsh-profile-patch.test.ts -193 tests/clients/integrations-hermes-affinity.test.ts -147 tests/clients/integrations-journal.test.ts -146 tests/clients/integrations-merge.test.ts -333 tests/clients/integrations-model-names.test.ts -74 tests/clients/integrations-serialize.test.ts -134 tests/clients/integrations-state.test.ts -105 tests/clients/integrations-superseded-store.test.ts -252 tests/clients/integrations-writer-frozen-config.test.ts -150 tests/clients/integrations-writer-guard.test.ts -617 tests/clients/integrations-writer.test.ts -165 tests/clients/kilo-client.test.ts -43 tests/clients/lazycodex-detection.test.ts -51 tests/clients/link-admission-wait.test.ts -65 tests/clients/link-apply-record.test.ts -46 tests/clients/link-boundary.test.ts -49 tests/clients/link-codex-settings-digest.test.ts -76 tests/clients/link-compensation.test.ts -113 tests/clients/link-connection-generation.test.ts -165 tests/clients/link-diagnostics.test.ts -38 tests/clients/link-fingerprint.test.ts -68 tests/clients/link-home-settings.test.ts -61 tests/clients/link-parity-reporter.test.ts -113 tests/clients/link-peer-compatibility.test.ts -110 tests/clients/link-ports.test.ts -212 tests/clients/link-readiness.test.ts -393 tests/clients/link-relay-bound-transport.test.ts -91 tests/clients/link-routes.test.ts -719 tests/clients/link-ssh-argv-discovery.test.ts -704 tests/clients/link-ssh-argv.test.ts -75 tests/clients/link-ssh-config.test.ts -519 tests/clients/link-ssh-runner.test.ts -52 tests/clients/link-status-projection.test.ts -93 tests/clients/link-store.test.ts -1623 tests/clients/link-supervisor.test.ts -263 tests/clients/link-tunnel-history.test.ts -31 tests/clients/link-tunnel-state.test.ts -180 tests/clients/mutation-plan.test.ts -168 tests/clients/omo-client.test.ts -713 tests/clients/omo-responses-loop.test.ts -103 tests/clients/omo-role-models.test.ts -136 tests/clients/omp-path-contract.test.ts -83 tests/clients/omp-yaml-source-inline-comments.test.ts -277 tests/clients/opencode-kilo-refresh.test.ts -81 tests/clients/pi-path-contract.test.ts -203 tests/clients/prime-client.test.ts -366 tests/clients/qoder-client.test.ts -168 tests/clients/raycast-client.test.ts -45 tests/clients/raycast-detect.test.ts -6874 tests/clients/remote-catalog.test.ts -58 tests/clients/remote-control-prototype.test.ts -258 tests/clients/remote-workspace-activation.test.ts -69 tests/clients/remote-workspace-agent-wire.test.ts -60 tests/clients/remote-workspace-app-server.integration.test.ts -47 tests/clients/remote-workspace-claude.integration.test.ts -452 tests/clients/remote-workspace-cli-runtimes.test.ts -77 tests/clients/remote-workspace-cli.test.ts -6934 tests/clients/remote-workspace-codex-runtime.test.ts -74 tests/clients/remote-workspace-command-runner.test.ts -43 tests/clients/remote-workspace-device.test.ts -64 tests/clients/remote-workspace-hub.test.ts -40 tests/clients/remote-workspace-linux-confinement.test.ts -265 tests/clients/remote-workspace-management.test.ts -48 tests/clients/remote-workspace-platform.test.ts -37 tests/clients/remote-workspace-protocol.test.ts -41 tests/clients/remote-workspace-rpc-framing.test.ts -54 tests/clients/remote-workspace-secret-store.test.ts -810 tests/clients/remote-workspace-server.test.ts -140 tests/clients/remote-workspace-session-binding.test.ts -136 tests/clients/remote-workspace-sessions.test.ts -60 tests/clients/remote-workspace-tool-bridge.test.ts -402 tests/clients/remote-workspace.test.ts -621 tests/clients/sync-client-integrations-unattended.test.ts -340 tests/clients/sync-client-integrations.test.ts -168 tests/clients/t3code-client-lifecycle.test.ts -260 tests/clients/t3code-client.test.ts -242 tests/clients/workbuddy-selector-recovery.test.ts -845 tests/codex-integration/active-registry-admission.test.ts -1815 tests/codex-integration/active-turn-disconnect.test.ts -152 tests/codex-integration/anthropic2-catalog.test.ts -155 tests/codex-integration/app-owned-memory.test.ts -4166 tests/codex-integration/bearer-admission-routed-provider.test.ts -4174 tests/codex-integration/catalog-async-lifetime.test.ts -345 tests/codex-integration/catalog-auto-refresh-client-fanout.test.ts -1259 tests/codex-integration/catalog-auto-refresh-scheduler.test.ts -110 tests/codex-integration/catalog-auto-review-override.test.ts -2748 tests/codex-integration/catalog-auto-review-row.test.ts -98 tests/codex-integration/catalog-context-window-ladder.test.ts -84 tests/codex-integration/catalog-cursor-search.test.ts -117 tests/codex-integration/catalog-custom-ordering.test.ts -116 tests/codex-integration/catalog-duplicate-slug-dedup.test.ts -112 tests/codex-integration/catalog-free-pricing-status.test.ts -5128 tests/codex-integration/catalog-full-picker-order.test.ts -109 tests/codex-integration/catalog-gated-native-suppression-reason.test.ts -123 tests/codex-integration/catalog-go-exact-efforts.test.ts -159 tests/codex-integration/catalog-hub-context-window.test.ts -119 tests/codex-integration/catalog-input-modality-enum.test.ts -103 tests/codex-integration/catalog-llamacpp-capabilities.test.ts -795 tests/codex-integration/catalog-modelalias-unique-sync.test.ts -85 tests/codex-integration/catalog-native-max-context.test.ts -143 tests/codex-integration/catalog-oauth-observation.test.ts -4195 tests/codex-integration/catalog-omit-disabled-native.test.ts -130 tests/codex-integration/catalog-opencode-go-context-window.test.ts -241 tests/codex-integration/catalog-opencode-go-static.test.ts -81 tests/codex-integration/catalog-opengateway-hints.test.ts -1520 tests/codex-integration/catalog-remote-pull.test.ts -196 tests/codex-integration/catalog-retain-models.test.ts -119 tests/codex-integration/catalog-routed-comp-hash.test.ts -126 tests/codex-integration/catalog-seed-window-fill.test.ts -119 tests/codex-integration/catalog-slug-uniqueness-boundary.test.ts +52 tests/clients/desktop-compatibility-certificate-service.test.ts +109 tests/clients/desktop-compatibility-connection-store.test.ts +57 tests/clients/desktop-compatibility-launch.test.ts +117 tests/clients/desktop-compatibility-native-identity.test.ts +154 tests/clients/desktop-compatibility-relay.test.ts +62 tests/clients/desktop-compatibility-routing.test.ts +207 tests/clients/desktop-compatibility-runtime.test.ts +64 tests/clients/desktop-compatibility-trust.test.ts +52 tests/clients/desktop-exit-ownership.test.ts +59 tests/clients/desktop-host-visibility.test.ts +58 tests/clients/desktop-install-identity.test.ts +401 tests/clients/desktop-profile.test.ts +45 tests/clients/desktop-proxy-direct-transport.test.ts +642 tests/clients/desktop-remote-store.test.ts +46 tests/clients/desktop-restart-handoff.test.ts +49 tests/clients/desktop-runtime-identity.test.ts +69 tests/clients/desktop-start-at-login-default.test.ts +56 tests/clients/desktop-startup-surface.test.ts +497 tests/clients/desktop-supervised-restart.test.ts +45 tests/clients/desktop-tray-availability.test.ts +50 tests/clients/desktop-update-surface.test.ts +50 tests/clients/desktop-widget-entry.test.ts +169 tests/clients/droid-client.test.ts +133 tests/clients/droid-managed-reasoning-defaults.test.ts +129 tests/clients/droid-normalized-reasoning-defaults.test.ts +125 tests/clients/gentle-shell-client.test.ts +224 tests/clients/gentle-shell-path.test.ts +138 tests/clients/hermes-catalog-refresh.test.ts +502 tests/clients/hermes-profile-routes.test.ts +93 tests/clients/hermes-profiles.test.ts +198 tests/clients/integrations-current-store.test.ts +347 tests/clients/integrations-dsh-profile-patch.test.ts +228 tests/clients/integrations-hermes-affinity.test.ts +164 tests/clients/integrations-journal.test.ts +161 tests/clients/integrations-merge.test.ts +295 tests/clients/integrations-model-names.test.ts +87 tests/clients/integrations-serialize.test.ts +254 tests/clients/integrations-state.test.ts +112 tests/clients/integrations-superseded-store.test.ts +166 tests/clients/integrations-writer-frozen-config.test.ts +168 tests/clients/integrations-writer-guard.test.ts +470 tests/clients/integrations-writer.test.ts +139 tests/clients/kilo-client.test.ts +57 tests/clients/lazycodex-detection.test.ts +52 tests/clients/link-admission-wait.test.ts +76 tests/clients/link-apply-record.test.ts +49 tests/clients/link-boundary.test.ts +50 tests/clients/link-codex-settings-digest.test.ts +93 tests/clients/link-compensation.test.ts +128 tests/clients/link-connection-generation.test.ts +138 tests/clients/link-diagnostics.test.ts +52 tests/clients/link-fingerprint.test.ts +73 tests/clients/link-home-settings.test.ts +62 tests/clients/link-parity-reporter.test.ts +131 tests/clients/link-peer-compatibility.test.ts +10862 tests/clients/link-pinned-sync-argv.test.ts +146 tests/clients/link-ports.test.ts +171 tests/clients/link-readiness.test.ts +355 tests/clients/link-relay-bound-transport.test.ts +126 tests/clients/link-routes.test.ts +241 tests/clients/link-ssh-argv-discovery.test.ts +638 tests/clients/link-ssh-argv.test.ts +66 tests/clients/link-ssh-config.test.ts +472 tests/clients/link-ssh-runner.test.ts +49 tests/clients/link-status-projection.test.ts +39 tests/clients/link-store.test.ts +1596 tests/clients/link-supervisor.test.ts +172 tests/clients/link-tunnel-history.test.ts +57 tests/clients/link-tunnel-state.test.ts +197 tests/clients/mutation-plan.test.ts +249 tests/clients/omo-client.test.ts +462 tests/clients/omo-responses-loop.test.ts +114 tests/clients/omo-role-models.test.ts +107 tests/clients/omp-path-contract.test.ts +101 tests/clients/omp-yaml-source-inline-comments.test.ts +168 tests/clients/opencode-kilo-refresh.test.ts +144 tests/clients/pi-path-contract.test.ts +184 tests/clients/prime-client.test.ts +351 tests/clients/qoder-client.test.ts +135 tests/clients/raycast-client.test.ts +53 tests/clients/raycast-detect.test.ts +6887 tests/clients/remote-catalog.test.ts +61 tests/clients/remote-control-prototype.test.ts +170 tests/clients/remote-workspace-activation.test.ts +78 tests/clients/remote-workspace-agent-wire.test.ts +42 tests/clients/remote-workspace-app-server.integration.test.ts +58 tests/clients/remote-workspace-claude.integration.test.ts +274 tests/clients/remote-workspace-cli-runtimes.test.ts +103 tests/clients/remote-workspace-cli.test.ts +7990 tests/clients/remote-workspace-codex-runtime.test.ts +111 tests/clients/remote-workspace-command-runner.test.ts +54 tests/clients/remote-workspace-device.test.ts +57 tests/clients/remote-workspace-hub.test.ts +51 tests/clients/remote-workspace-linux-confinement.test.ts +142 tests/clients/remote-workspace-management.test.ts +53 tests/clients/remote-workspace-platform.test.ts +70 tests/clients/remote-workspace-protocol.test.ts +58 tests/clients/remote-workspace-rpc-framing.test.ts +59 tests/clients/remote-workspace-secret-store.test.ts +796 tests/clients/remote-workspace-server.test.ts +83 tests/clients/remote-workspace-session-binding.test.ts +91 tests/clients/remote-workspace-sessions.test.ts +69 tests/clients/remote-workspace-tool-bridge.test.ts +285 tests/clients/remote-workspace.test.ts +730 tests/clients/sync-client-integrations-unattended.test.ts +366 tests/clients/sync-client-integrations.test.ts +144 tests/clients/t3code-client-lifecycle.test.ts +241 tests/clients/t3code-client.test.ts +372 tests/clients/workbuddy-selector-recovery.test.ts +790 tests/codex-integration/active-registry-admission.test.ts +1653 tests/codex-integration/active-turn-disconnect.test.ts +114 tests/codex-integration/anthropic2-catalog.test.ts +205 tests/codex-integration/app-owned-memory.test.ts +5005 tests/codex-integration/bearer-admission-routed-provider.test.ts +4146 tests/codex-integration/catalog-async-lifetime.test.ts +212 tests/codex-integration/catalog-auto-refresh-client-fanout.test.ts +957 tests/codex-integration/catalog-auto-refresh-scheduler.test.ts +77 tests/codex-integration/catalog-auto-review-override.test.ts +2861 tests/codex-integration/catalog-auto-review-row.test.ts +121 tests/codex-integration/catalog-context-window-ladder.test.ts +89 tests/codex-integration/catalog-cursor-search.test.ts +151 tests/codex-integration/catalog-custom-ordering.test.ts +131 tests/codex-integration/catalog-duplicate-slug-dedup.test.ts +190 tests/codex-integration/catalog-free-pricing-status.test.ts +4888 tests/codex-integration/catalog-full-picker-order.test.ts +201 tests/codex-integration/catalog-gated-native-suppression-reason.test.ts +115 tests/codex-integration/catalog-go-exact-efforts.test.ts +115 tests/codex-integration/catalog-hub-context-window.test.ts +184 tests/codex-integration/catalog-input-modality-enum.test.ts +99 tests/codex-integration/catalog-llamacpp-capabilities.test.ts +649 tests/codex-integration/catalog-modelalias-unique-sync.test.ts +84 tests/codex-integration/catalog-native-max-context.test.ts +168 tests/codex-integration/catalog-oauth-observation.test.ts +3797 tests/codex-integration/catalog-omit-disabled-native.test.ts +149 tests/codex-integration/catalog-opencode-go-context-window.test.ts +137 tests/codex-integration/catalog-opencode-go-static.test.ts +106 tests/codex-integration/catalog-opengateway-hints.test.ts +1256 tests/codex-integration/catalog-remote-pull.test.ts +161 tests/codex-integration/catalog-retain-models.test.ts +107 tests/codex-integration/catalog-routed-comp-hash.test.ts +95 tests/codex-integration/catalog-seed-window-fill.test.ts +165 tests/codex-integration/catalog-slug-uniqueness-boundary.test.ts 138 tests/codex-integration/catalog-verbosity-default.test.ts -280 tests/codex-integration/catalog-vision-sidecar-disabled.test.ts -131 tests/codex-integration/catalog-vision-sidecar-modalities.test.ts -84 tests/codex-integration/catalog-zero-credit-picker.test.ts -4581 tests/codex-integration/client-injection-guard.test.ts -265 tests/codex-integration/code-mode-collab-surface.test.ts -101 tests/codex-integration/codex-account-clear-paused.test.ts -342 tests/codex-integration/codex-account-delete-atomicity.test.ts -30 tests/codex-integration/codex-account-label.test.ts -42 tests/codex-integration/codex-account-namespaces.test.ts -352 tests/codex-integration/codex-account-selection-atomicity.test.ts -135 tests/codex-integration/codex-account-selection-preferences.test.ts -189 tests/codex-integration/codex-account-slot-identity.test.ts -122 tests/codex-integration/codex-account-store-quota-isolation.test.ts -300 tests/codex-integration/codex-account-store-refresh-classification.test.ts -893 tests/codex-integration/codex-account-store.test.ts -642 tests/codex-integration/codex-account-threshold-api.test.ts -237 tests/codex-integration/codex-account-threshold-auth.test.ts -175 tests/codex-integration/codex-account-threshold-routing.test.ts -156 tests/codex-integration/codex-account-unusable-reason.test.ts -187 tests/codex-integration/codex-admission-primitives.test.ts -132 tests/codex-integration/codex-admission.test.ts -179 tests/codex-integration/codex-affinity-debug.test.ts -156 tests/codex-integration/codex-affinity-lease-gap.test.ts -116 tests/codex-integration/codex-affinity-request-owned.test.ts -16522 tests/codex-integration/codex-affinity-restart-matrix.test.ts -22436 tests/codex-integration/codex-affinity-restart.test.ts -1907 tests/codex-integration/codex-affinity-store.test.ts -362 tests/codex-integration/codex-agent-thread-limit.test.ts -68 tests/codex-integration/codex-app-server-path-spaces.test.ts -1046 tests/codex-integration/codex-app-server-processes.test.ts -160 tests/codex-integration/codex-app-server-restart-service.test.ts -3196 tests/codex-integration/codex-auth-api.test.ts -95 tests/codex-integration/codex-auth-cancel-ownership.test.ts -204 tests/codex-integration/codex-auth-collision.test.ts -946 tests/codex-integration/codex-auth-context.test.ts -285 tests/codex-integration/codex-auth-headless-accounts.test.ts -231 tests/codex-integration/codex-auth-release.test.ts -113 tests/codex-integration/codex-catalog-admission.test.ts -93 tests/codex-integration/codex-catalog-exclusions.test.ts -88 tests/codex-integration/codex-catalog-golden.test.ts -374 tests/codex-integration/codex-catalog-heal-integration.test.ts -109 tests/codex-integration/codex-catalog-heal-reanchor.test.ts -94 tests/codex-integration/codex-catalog-identity-neutral.test.ts -243 tests/codex-integration/codex-catalog-intent.test.ts -128 tests/codex-integration/codex-catalog-ladders.test.ts -90 tests/codex-integration/codex-catalog-model-picker-order.test.ts -40 tests/codex-integration/codex-catalog-refresh-status.test.ts -1385 tests/codex-integration/codex-catalog-restore.test.ts -161 tests/codex-integration/codex-catalog-routed-removal.test.ts -217 tests/codex-integration/codex-catalog-self-heal.test.ts -24633 tests/codex-integration/codex-catalog-sync-hardening.test.ts -584 tests/codex-integration/codex-catalog-write-audit.test.ts -91 tests/codex-integration/codex-catalog-write-serialization.test.ts -212 tests/codex-integration/codex-catalog-writer.test.ts -1615 tests/codex-integration/codex-catalog.test.ts -177 tests/codex-integration/codex-clamp-notice.test.ts -355 tests/codex-integration/codex-cli-install-provenance.test.ts +150 tests/codex-integration/catalog-vision-sidecar-disabled.test.ts +116 tests/codex-integration/catalog-vision-sidecar-modalities.test.ts +103 tests/codex-integration/catalog-zero-credit-picker.test.ts +4096 tests/codex-integration/client-injection-guard.test.ts +370 tests/codex-integration/code-mode-collab-surface.test.ts +109 tests/codex-integration/codex-account-clear-paused.test.ts +195 tests/codex-integration/codex-account-delete-atomicity.test.ts +63 tests/codex-integration/codex-account-label.test.ts +55 tests/codex-integration/codex-account-namespaces.test.ts +376 tests/codex-integration/codex-account-selection-atomicity.test.ts +246 tests/codex-integration/codex-account-selection-preferences.test.ts +147 tests/codex-integration/codex-account-slot-identity.test.ts +152 tests/codex-integration/codex-account-store-quota-isolation.test.ts +200 tests/codex-integration/codex-account-store-refresh-classification.test.ts +1289 tests/codex-integration/codex-account-store.test.ts +545 tests/codex-integration/codex-account-threshold-api.test.ts +268 tests/codex-integration/codex-account-threshold-auth.test.ts +204 tests/codex-integration/codex-account-threshold-routing.test.ts +148 tests/codex-integration/codex-account-unusable-reason.test.ts +194 tests/codex-integration/codex-admission-primitives.test.ts +167 tests/codex-integration/codex-admission.test.ts +56 tests/codex-integration/codex-affinity-debug.test.ts +197 tests/codex-integration/codex-affinity-lease-gap.test.ts +146 tests/codex-integration/codex-affinity-request-owned.test.ts +13789 tests/codex-integration/codex-affinity-restart-matrix.test.ts +14295 tests/codex-integration/codex-affinity-restart.test.ts +1791 tests/codex-integration/codex-affinity-store.test.ts +438 tests/codex-integration/codex-agent-thread-limit.test.ts +65 tests/codex-integration/codex-app-server-path-spaces.test.ts +946 tests/codex-integration/codex-app-server-processes.test.ts +143 tests/codex-integration/codex-app-server-restart-service.test.ts +1982 tests/codex-integration/codex-auth-api.test.ts +122 tests/codex-integration/codex-auth-cancel-ownership.test.ts +156 tests/codex-integration/codex-auth-collision.test.ts +1157 tests/codex-integration/codex-auth-context.test.ts +504 tests/codex-integration/codex-auth-headless-accounts.test.ts +328 tests/codex-integration/codex-auth-release.test.ts +138 tests/codex-integration/codex-catalog-admission.test.ts +106 tests/codex-integration/codex-catalog-exclusions.test.ts +107 tests/codex-integration/codex-catalog-golden.test.ts +351 tests/codex-integration/codex-catalog-heal-integration.test.ts +138 tests/codex-integration/codex-catalog-heal-reanchor.test.ts +108 tests/codex-integration/codex-catalog-identity-neutral.test.ts +218 tests/codex-integration/codex-catalog-intent.test.ts +212 tests/codex-integration/codex-catalog-ladders.test.ts +101 tests/codex-integration/codex-catalog-model-picker-order.test.ts +56 tests/codex-integration/codex-catalog-refresh-status.test.ts +1192 tests/codex-integration/codex-catalog-restore.test.ts +82 tests/codex-integration/codex-catalog-routed-removal.test.ts +139 tests/codex-integration/codex-catalog-self-heal.test.ts +26099 tests/codex-integration/codex-catalog-sync-hardening.test.ts +650 tests/codex-integration/codex-catalog-write-audit.test.ts +80 tests/codex-integration/codex-catalog-write-serialization.test.ts +226 tests/codex-integration/codex-catalog-writer.test.ts +1803 tests/codex-integration/codex-catalog.test.ts +143 tests/codex-integration/codex-clamp-notice.test.ts +392 tests/codex-integration/codex-cli-install-provenance.test.ts 46 tests/codex-integration/codex-cli-installation-identity.test.ts -62 tests/codex-integration/codex-cli-installation-targets.test.ts -4739 tests/codex-integration/codex-cli-update-admission.test.ts -125741 tests/codex-integration/codex-cli-update-apply.test.ts -4248 tests/codex-integration/codex-cli-update-artifacts.test.ts +43 tests/codex-integration/codex-cli-installation-targets.test.ts +8250 tests/codex-integration/codex-cli-update-admission.test.ts +95740 tests/codex-integration/codex-cli-update-apply.test.ts +3512 tests/codex-integration/codex-cli-update-artifacts.test.ts 66 tests/codex-integration/codex-cli-update-integrity.test.ts -64 tests/codex-integration/codex-cli-update-launcher-policy.test.ts -306 tests/codex-integration/codex-cli-update-parent-async.test.ts -81 tests/codex-integration/codex-cli-update-paths.test.ts -1809 tests/codex-integration/codex-cli-update-plan.test.ts -3386 tests/codex-integration/codex-cli-update-recovery.test.ts -69 tests/codex-integration/codex-cli-update-windows-apply-install.test.ts -62 tests/codex-integration/codex-cli-update-windows-apply-outcomes.test.ts -80 tests/codex-integration/codex-cli-update-windows-apply-shared.test.ts -53 tests/codex-integration/codex-cli-update-windows-apply.test.ts -145 tests/codex-integration/codex-cli-update-windows-layout.test.ts -37 tests/codex-integration/codex-cli-update-windows-pending.test.ts -467 tests/codex-integration/codex-cli-update-windows-recovery.test.ts -65 tests/codex-integration/codex-cli-update-windows-review.test.ts -410 tests/codex-integration/codex-cli-update-worker.test.ts -1084 tests/codex-integration/codex-cli-update-zero-effect.test.ts -50 tests/codex-integration/codex-cli-windows-child.test.ts -49 tests/codex-integration/codex-cli-windows-installation-files.test.ts -165 tests/codex-integration/codex-cli-windows-plan.test.ts -24169 tests/codex-integration/codex-composed-acceptance.test.ts -2281 tests/codex-integration/codex-config-drift-heal.test.ts -330 tests/codex-integration/codex-config-generation.test.ts -2188 tests/codex-integration/codex-config-preservation.test.ts -5927 tests/codex-integration/codex-config-write-lock.test.ts -177 tests/codex-integration/codex-context-owner.test.ts -5768 tests/codex-integration/codex-convergence-account-selectors.test.ts -991 tests/codex-integration/codex-convergence-contract.test.ts -329 tests/codex-integration/codex-cooldown-recovery.test.ts -188 tests/codex-integration/codex-coordinator-doctor.test.ts -803 tests/codex-integration/codex-credit-retry-after.test.ts -883 tests/codex-integration/codex-credit-scoped-retry.test.ts -328 tests/codex-integration/codex-credits-after-limit-main.test.ts -225 tests/codex-integration/codex-credits-after-limit.test.ts -142 tests/codex-integration/codex-credits-probes.test.ts -309 tests/codex-integration/codex-credits-settings.test.ts -62 tests/codex-integration/codex-credits.test.ts -228 tests/codex-integration/codex-desired-state.test.ts -468 tests/codex-integration/codex-direct-credit-renewal.test.ts -440 tests/codex-integration/codex-direct-renewal-revocation.test.ts -150 tests/codex-integration/codex-entitlement-identity-read-fence.test.ts -660 tests/codex-integration/codex-envkey-admission-substitution.test.ts -149 tests/codex-integration/codex-exec-invocation.test.ts -528 tests/codex-integration/codex-failure-window.test.ts -77 tests/codex-integration/codex-features-cache.test.ts -40 tests/codex-integration/codex-features-residual.test.ts -76 tests/codex-integration/codex-filesystem-evidence.test.ts -86 tests/codex-integration/codex-forward-access-programs-writer.test.ts -426 tests/codex-integration/codex-gather-authority.test.ts -2408 tests/codex-integration/codex-history-job.test.ts -124 tests/codex-integration/codex-history-lock.test.ts -73 tests/codex-integration/codex-history-pending-wal.test.ts -2524 tests/codex-integration/codex-history-provider.test.ts -733 tests/codex-integration/codex-history-reachability.test.ts -62 tests/codex-integration/codex-history-worker-boundary.test.ts -1983 tests/codex-integration/codex-history-worker.test.ts -45 tests/codex-integration/codex-history-writer.test.ts -10243 tests/codex-integration/codex-home-owner-lifecycle.test.ts -1043 tests/codex-integration/codex-home-owner.test.ts -46 tests/codex-integration/codex-home-wsl-local-state.test.ts -129 tests/codex-integration/codex-home-wsl.test.ts -258 tests/codex-integration/codex-idle-window.test.ts -140 tests/codex-integration/codex-inject-history-wording.test.ts -65182 tests/codex-integration/codex-inject-integration.test.ts -2085 tests/codex-integration/codex-inject-missing-config.test.ts -1142 tests/codex-integration/codex-inject-retained-table.test.ts -7706 tests/codex-integration/codex-inject-v1-reconcile.test.ts -9083 tests/codex-integration/codex-inject-write-lock.test.ts -172 tests/codex-integration/codex-inject.test.ts -58 tests/codex-integration/codex-injected-marker.test.ts -64 tests/codex-integration/codex-installation-acl.test.ts -99 tests/codex-integration/codex-installation-id.test.ts -528 tests/codex-integration/codex-installation-invalid-account.test.ts -1099 tests/codex-integration/codex-installation-live-content.test.ts -562 tests/codex-integration/codex-installation-live-http.test.ts -874 tests/codex-integration/codex-installation-live-ws.test.ts -438 tests/codex-integration/codex-installation-sidecars.test.ts -127 tests/codex-integration/codex-installation-wire.test.ts -109 tests/codex-integration/codex-integration-record.test.ts -3779 tests/codex-integration/codex-journal-recovery.test.ts -15866 tests/codex-integration/codex-journal.test.ts -240 tests/codex-integration/codex-launcher-admission.test.ts -122 tests/codex-integration/codex-launcher-darwin-acl.test.ts -49 tests/codex-integration/codex-launcher-darwin-identity.test.ts -215 tests/codex-integration/codex-launcher-diagnostics.test.ts -229 tests/codex-integration/codex-launcher-env.test.ts -2914 tests/codex-integration/codex-launcher-process.test.ts -163 tests/codex-integration/codex-launcher-security.test.ts -153 tests/codex-integration/codex-launcher.test.ts -56 tests/codex-integration/codex-legacy-config-keys.test.ts -237 tests/codex-integration/codex-lineage-placement.test.ts -372 tests/codex-integration/codex-linked-account-pause.test.ts -82 tests/codex-integration/codex-log-guard-coderabbit.test.ts -76 tests/codex-integration/codex-log-guard-doctor-coderabbit.test.ts +108 tests/codex-integration/codex-cli-update-launcher-policy.test.ts +241 tests/codex-integration/codex-cli-update-parent-async.test.ts +66 tests/codex-integration/codex-cli-update-paths.test.ts +1859 tests/codex-integration/codex-cli-update-plan.test.ts +3185 tests/codex-integration/codex-cli-update-recovery.test.ts +42 tests/codex-integration/codex-cli-update-windows-apply-install.test.ts +47 tests/codex-integration/codex-cli-update-windows-apply-outcomes.test.ts +65 tests/codex-integration/codex-cli-update-windows-apply-shared.test.ts +59 tests/codex-integration/codex-cli-update-windows-apply.test.ts +176 tests/codex-integration/codex-cli-update-windows-layout.test.ts +52 tests/codex-integration/codex-cli-update-windows-pending.test.ts +449 tests/codex-integration/codex-cli-update-windows-recovery.test.ts +72 tests/codex-integration/codex-cli-update-windows-review.test.ts +489 tests/codex-integration/codex-cli-update-worker.test.ts +1107 tests/codex-integration/codex-cli-update-zero-effect.test.ts +45 tests/codex-integration/codex-cli-windows-child.test.ts +43 tests/codex-integration/codex-cli-windows-installation-files.test.ts +107 tests/codex-integration/codex-cli-windows-plan.test.ts +19954 tests/codex-integration/codex-composed-acceptance.test.ts +1988 tests/codex-integration/codex-config-drift-heal.test.ts +294 tests/codex-integration/codex-config-generation.test.ts +2418 tests/codex-integration/codex-config-preservation.test.ts +6206 tests/codex-integration/codex-config-write-lock.test.ts +147 tests/codex-integration/codex-context-owner.test.ts +4938 tests/codex-integration/codex-convergence-account-selectors.test.ts +841 tests/codex-integration/codex-convergence-contract.test.ts +259 tests/codex-integration/codex-cooldown-recovery.test.ts +167 tests/codex-integration/codex-coordinator-doctor.test.ts +683 tests/codex-integration/codex-credit-retry-after.test.ts +438 tests/codex-integration/codex-credit-scoped-retry.test.ts +151 tests/codex-integration/codex-credits-after-limit-main.test.ts +253 tests/codex-integration/codex-credits-after-limit.test.ts +165 tests/codex-integration/codex-credits-probes.test.ts +279 tests/codex-integration/codex-credits-settings.test.ts +68 tests/codex-integration/codex-credits.test.ts +192 tests/codex-integration/codex-desired-state.test.ts +392 tests/codex-integration/codex-direct-credit-renewal.test.ts +207 tests/codex-integration/codex-direct-renewal-revocation.test.ts +79 tests/codex-integration/codex-entitlement-identity-read-fence.test.ts +709 tests/codex-integration/codex-envkey-admission-substitution.test.ts +146 tests/codex-integration/codex-exec-invocation.test.ts +459 tests/codex-integration/codex-failure-window.test.ts +64 tests/codex-integration/codex-features-cache.test.ts +53 tests/codex-integration/codex-features-residual.test.ts +88 tests/codex-integration/codex-filesystem-evidence.test.ts +116 tests/codex-integration/codex-forward-access-programs-writer.test.ts +401 tests/codex-integration/codex-gather-authority.test.ts +2018 tests/codex-integration/codex-history-job.test.ts +122 tests/codex-integration/codex-history-lock.test.ts +71 tests/codex-integration/codex-history-pending-wal.test.ts +1845 tests/codex-integration/codex-history-provider.test.ts +342 tests/codex-integration/codex-history-reachability.test.ts +50 tests/codex-integration/codex-history-worker-boundary.test.ts +1443 tests/codex-integration/codex-history-worker.test.ts +62 tests/codex-integration/codex-history-writer.test.ts +10031 tests/codex-integration/codex-home-owner-lifecycle.test.ts +1233 tests/codex-integration/codex-home-owner.test.ts +100 tests/codex-integration/codex-home-wsl-local-state.test.ts +148 tests/codex-integration/codex-home-wsl.test.ts +217 tests/codex-integration/codex-idle-window.test.ts +202 tests/codex-integration/codex-inject-history-wording.test.ts +68329 tests/codex-integration/codex-inject-integration.test.ts +1818 tests/codex-integration/codex-inject-missing-config.test.ts +812 tests/codex-integration/codex-inject-retained-table.test.ts +7954 tests/codex-integration/codex-inject-v1-reconcile.test.ts +8842 tests/codex-integration/codex-inject-write-lock.test.ts +154 tests/codex-integration/codex-inject.test.ts +53 tests/codex-integration/codex-injected-marker.test.ts +96 tests/codex-integration/codex-installation-acl.test.ts +84 tests/codex-integration/codex-installation-id.test.ts +430 tests/codex-integration/codex-installation-invalid-account.test.ts +833 tests/codex-integration/codex-installation-live-content.test.ts +646 tests/codex-integration/codex-installation-live-http.test.ts +834 tests/codex-integration/codex-installation-live-ws.test.ts +451 tests/codex-integration/codex-installation-sidecars.test.ts +123 tests/codex-integration/codex-installation-wire.test.ts +113 tests/codex-integration/codex-integration-record.test.ts +3003 tests/codex-integration/codex-journal-recovery.test.ts +14339 tests/codex-integration/codex-journal.test.ts +164 tests/codex-integration/codex-launcher-admission.test.ts +93 tests/codex-integration/codex-launcher-darwin-acl.test.ts +82 tests/codex-integration/codex-launcher-darwin-identity.test.ts +157 tests/codex-integration/codex-launcher-diagnostics.test.ts +240 tests/codex-integration/codex-launcher-env.test.ts +3019 tests/codex-integration/codex-launcher-process.test.ts +162 tests/codex-integration/codex-launcher-security.test.ts +144 tests/codex-integration/codex-launcher.test.ts +67 tests/codex-integration/codex-legacy-config-keys.test.ts +251 tests/codex-integration/codex-lineage-placement.test.ts +409 tests/codex-integration/codex-linked-account-pause.test.ts +91 tests/codex-integration/codex-log-guard-coderabbit.test.ts +54 tests/codex-integration/codex-log-guard-doctor-coderabbit.test.ts 43 tests/codex-integration/codex-log-guard-doctor-protection.test.ts -115 tests/codex-integration/codex-log-guard-doctor.test.ts -221 tests/codex-integration/codex-log-guard-inspect.test.ts -52 tests/codex-integration/codex-log-guard-lock.test.ts -306 tests/codex-integration/codex-log-guard-maintenance-coderabbit.test.ts -793 tests/codex-integration/codex-log-guard-maintenance.test.ts -39 tests/codex-integration/codex-log-guard-policy.test.ts -45 tests/codex-integration/codex-log-guard-processes.test.ts -167 tests/codex-integration/codex-log-guard-protection.test.ts -86 tests/codex-integration/codex-log-guard-status-zero-write.test.ts -170 tests/codex-integration/codex-main-account-refresh.test.ts -416 tests/codex-integration/codex-main-grant-refusal.test.ts -261 tests/codex-integration/codex-main-rotation.test.ts -128 tests/codex-integration/codex-main-token-invalidated.test.ts -215 tests/codex-integration/codex-management-convergence.test.ts -155 tests/codex-integration/codex-metadata-integrity.test.ts -7486 tests/codex-integration/codex-missing-home.test.ts -126 tests/codex-integration/codex-model-availability-error.test.ts -391 tests/codex-integration/codex-model-denial-evidence.test.ts -69 tests/codex-integration/codex-model-entitlement-admission.test.ts -159 tests/codex-integration/codex-model-entitlements-program-shape.test.ts -225 tests/codex-integration/codex-model-entitlements.test.ts -150 tests/codex-integration/codex-models-cache-invalidate.test.ts -1297 tests/codex-integration/codex-native-availability-nux.test.ts -675 tests/codex-integration/codex-native-residue.test.ts -143 tests/codex-integration/codex-pin-drain-projection.test.ts -146 tests/codex-integration/codex-plan.test.ts -414 tests/codex-integration/codex-plugins-doctor.test.ts -178 tests/codex-integration/codex-pool-caller-fallback-policy.test.ts -177 tests/codex-integration/codex-pool-credit-policy.test.ts -143 tests/codex-integration/codex-pool-plan-exclusion.test.ts -78 tests/codex-integration/codex-pool-refresh-backoff.test.ts -158 tests/codex-integration/codex-pool-request-owned-main.test.ts -685 tests/codex-integration/codex-pool-rotation.test.ts -353 tests/codex-integration/codex-preserve-signed-in.test.ts -314 tests/codex-integration/codex-priority-failback.test.ts -65 tests/codex-integration/codex-proc-scan-errors.test.ts -92 tests/codex-integration/codex-prompt-adopt.test.ts -322 tests/codex-integration/codex-prompt-base-variants.test.ts -76 tests/codex-integration/codex-prompt-journal.test.ts -70 tests/codex-integration/codex-prompt-layers-read.test.ts -249 tests/codex-integration/codex-prompt-layers-write.test.ts -53 tests/codex-integration/codex-prompt-layers.test.ts -337 tests/codex-integration/codex-prompt-lock-sharing.test.ts -499 tests/codex-integration/codex-prompt-lock.test.ts -1412 tests/codex-integration/codex-prompt-route.test.ts -169 tests/codex-integration/codex-prompt-scalar-scope.test.ts -964 tests/codex-integration/codex-prompt-text-probe.test.ts -758 tests/codex-integration/codex-prompt-writes.test.ts -17329 tests/codex-integration/codex-provider-routing.test.ts -779 tests/codex-integration/codex-provider-table-retention.test.ts -118 tests/codex-integration/codex-quota-auto-refresh-generation.test.ts -241 tests/codex-integration/codex-quota-auto-refresh-main-admission.test.ts -473 tests/codex-integration/codex-quota-auto-refresh.test.ts -53 tests/codex-integration/codex-quota-capacity.test.ts -136 tests/codex-integration/codex-quota-history.test.ts -212 tests/codex-integration/codex-quota-parser-parity.test.ts -69 tests/codex-integration/codex-quota-persistence.test.ts -404 tests/codex-integration/codex-quota-prime.test.ts -119 tests/codex-integration/codex-quota-query-backoff.test.ts -306 tests/codex-integration/codex-quota-rejection.test.ts -139 tests/codex-integration/codex-refresh.test.ts -527 tests/codex-integration/codex-request-owned-affinity.test.ts -789 tests/codex-integration/codex-reset-credit-auto-redeem.test.ts -491 tests/codex-integration/codex-reset-credit-operation-ledger.test.ts -444 tests/codex-integration/codex-reset-credit-recovery.test.ts -100 tests/codex-integration/codex-restart-contract-parity.test.ts -248 tests/codex-integration/codex-restart-route.test.ts -4522 tests/codex-integration/codex-restore-app-rewrite.test.ts -8427 tests/codex-integration/codex-retained-root-serialization.test.ts -238 tests/codex-integration/codex-round-robin-headroom.test.ts -109 tests/codex-integration/codex-routing-cache-affinity-detour.test.ts -89 tests/codex-integration/codex-routing-elapsed-short-reset.test.ts -4284 tests/codex-integration/codex-routing.test.ts -203 tests/codex-integration/codex-runtime-macos-desktop.test.ts -109 tests/codex-integration/codex-runtime-wsl-desktop.test.ts -266 tests/codex-integration/codex-runtime.test.ts -399 tests/codex-integration/codex-service-manager-probe-hardening.test.ts -355 tests/codex-integration/codex-service-manager-probe.test.ts -20983 tests/codex-integration/codex-shim-autorestore.test.ts -95 tests/codex-integration/codex-shim-bypass-token.test.ts -234 tests/codex-integration/codex-shim-destroyed-probe.test.ts -53 tests/codex-integration/codex-shim-ensure-failure.test.ts -132 tests/codex-integration/codex-shim-fnm.test.ts -498 tests/codex-integration/codex-shim-migration.test.ts -155 tests/codex-integration/codex-shim-overlay-candidates.test.ts -789 tests/codex-integration/codex-shim-overlay-readiness.test.ts -2412 tests/codex-integration/codex-shim-overlay-transaction.test.ts -707 tests/codex-integration/codex-shim-overlay.test.ts -5040 tests/codex-integration/codex-shim-path-readiness.test.ts -28478 tests/codex-integration/codex-shim-readiness.test.ts -60 tests/codex-integration/codex-shim-runtime-preflight.test.ts -1031 tests/codex-integration/codex-shim-standalone.test.ts -231 tests/codex-integration/codex-shim-windows-revision.test.ts -25602 tests/codex-integration/codex-shim.test.ts -1582 tests/codex-integration/codex-sidecar-credit-policy.test.ts -227 tests/codex-integration/codex-signin-lockout.test.ts -261 tests/codex-integration/codex-spark-visibility.test.ts -67 tests/codex-integration/codex-sqlite-home.test.ts -519 tests/codex-integration/codex-stored-main-duplicate.test.ts -1498 tests/codex-integration/codex-sync-api.test.ts -327 tests/codex-integration/codex-sync-new-model-policy.test.ts +54 tests/codex-integration/codex-log-guard-doctor.test.ts +224 tests/codex-integration/codex-log-guard-inspect.test.ts +54 tests/codex-integration/codex-log-guard-lock.test.ts +359 tests/codex-integration/codex-log-guard-maintenance-coderabbit.test.ts +857 tests/codex-integration/codex-log-guard-maintenance.test.ts +51 tests/codex-integration/codex-log-guard-policy.test.ts +70 tests/codex-integration/codex-log-guard-processes.test.ts +209 tests/codex-integration/codex-log-guard-protection.test.ts +113 tests/codex-integration/codex-log-guard-status-zero-write.test.ts +156 tests/codex-integration/codex-main-account-refresh.test.ts +336 tests/codex-integration/codex-main-grant-refusal.test.ts +310 tests/codex-integration/codex-main-rotation.test.ts +189 tests/codex-integration/codex-main-token-invalidated.test.ts +120 tests/codex-integration/codex-management-convergence.test.ts +130 tests/codex-integration/codex-metadata-integrity.test.ts +7613 tests/codex-integration/codex-missing-home.test.ts +89 tests/codex-integration/codex-model-availability-error.test.ts +253 tests/codex-integration/codex-model-denial-evidence.test.ts +79 tests/codex-integration/codex-model-entitlement-admission.test.ts +151 tests/codex-integration/codex-model-entitlements-program-shape.test.ts +244 tests/codex-integration/codex-model-entitlements.test.ts +181 tests/codex-integration/codex-models-cache-invalidate.test.ts +1175 tests/codex-integration/codex-native-availability-nux.test.ts +614 tests/codex-integration/codex-native-residue.test.ts +180 tests/codex-integration/codex-pin-drain-projection.test.ts +110 tests/codex-integration/codex-plan.test.ts +505 tests/codex-integration/codex-plugins-doctor.test.ts +161 tests/codex-integration/codex-pool-caller-fallback-policy.test.ts +245 tests/codex-integration/codex-pool-credit-policy.test.ts +139 tests/codex-integration/codex-pool-plan-exclusion.test.ts +88 tests/codex-integration/codex-pool-refresh-backoff.test.ts +167 tests/codex-integration/codex-pool-request-owned-main.test.ts +642 tests/codex-integration/codex-pool-rotation.test.ts +401 tests/codex-integration/codex-preserve-signed-in.test.ts +309 tests/codex-integration/codex-priority-failback.test.ts +61 tests/codex-integration/codex-proc-scan-errors.test.ts +89 tests/codex-integration/codex-prompt-adopt.test.ts +336 tests/codex-integration/codex-prompt-base-variants.test.ts +79 tests/codex-integration/codex-prompt-journal.test.ts +54 tests/codex-integration/codex-prompt-layers-read.test.ts +165 tests/codex-integration/codex-prompt-layers-write.test.ts +59 tests/codex-integration/codex-prompt-layers.test.ts +336 tests/codex-integration/codex-prompt-lock-sharing.test.ts +486 tests/codex-integration/codex-prompt-lock.test.ts +1097 tests/codex-integration/codex-prompt-route.test.ts +170 tests/codex-integration/codex-prompt-scalar-scope.test.ts +854 tests/codex-integration/codex-prompt-text-probe.test.ts +489 tests/codex-integration/codex-prompt-writes.test.ts +17037 tests/codex-integration/codex-provider-routing.test.ts +807 tests/codex-integration/codex-provider-table-retention.test.ts +96 tests/codex-integration/codex-quota-auto-refresh-generation.test.ts +201 tests/codex-integration/codex-quota-auto-refresh-main-admission.test.ts +439 tests/codex-integration/codex-quota-auto-refresh.test.ts +39 tests/codex-integration/codex-quota-capacity.test.ts +149 tests/codex-integration/codex-quota-history.test.ts +180 tests/codex-integration/codex-quota-parser-parity.test.ts +62 tests/codex-integration/codex-quota-persistence.test.ts +425 tests/codex-integration/codex-quota-prime.test.ts +113 tests/codex-integration/codex-quota-query-backoff.test.ts +328 tests/codex-integration/codex-quota-rejection.test.ts +148 tests/codex-integration/codex-refresh.test.ts +228 tests/codex-integration/codex-request-owned-affinity.test.ts +906 tests/codex-integration/codex-reset-credit-auto-redeem.test.ts +511 tests/codex-integration/codex-reset-credit-operation-ledger.test.ts +316 tests/codex-integration/codex-reset-credit-recovery.test.ts +77 tests/codex-integration/codex-restart-contract-parity.test.ts +393 tests/codex-integration/codex-restart-route.test.ts +4731 tests/codex-integration/codex-restore-app-rewrite.test.ts +8212 tests/codex-integration/codex-retained-root-serialization.test.ts +307 tests/codex-integration/codex-round-robin-headroom.test.ts +134 tests/codex-integration/codex-routing-cache-affinity-detour.test.ts +113 tests/codex-integration/codex-routing-elapsed-short-reset.test.ts +3764 tests/codex-integration/codex-routing.test.ts +175 tests/codex-integration/codex-runtime-macos-desktop.test.ts +84 tests/codex-integration/codex-runtime-wsl-desktop.test.ts +156 tests/codex-integration/codex-runtime.test.ts +436 tests/codex-integration/codex-service-manager-probe-hardening.test.ts +277 tests/codex-integration/codex-service-manager-probe.test.ts +22763 tests/codex-integration/codex-shim-autorestore.test.ts +66 tests/codex-integration/codex-shim-bypass-token.test.ts +176 tests/codex-integration/codex-shim-destroyed-probe.test.ts +87 tests/codex-integration/codex-shim-ensure-failure.test.ts +131 tests/codex-integration/codex-shim-fnm.test.ts +405 tests/codex-integration/codex-shim-migration.test.ts +133 tests/codex-integration/codex-shim-overlay-candidates.test.ts +596 tests/codex-integration/codex-shim-overlay-readiness.test.ts +1889 tests/codex-integration/codex-shim-overlay-transaction.test.ts +765 tests/codex-integration/codex-shim-overlay.test.ts +2999 tests/codex-integration/codex-shim-path-readiness.test.ts +28771 tests/codex-integration/codex-shim-readiness.test.ts +87 tests/codex-integration/codex-shim-runtime-preflight.test.ts +592 tests/codex-integration/codex-shim-standalone.test.ts +203 tests/codex-integration/codex-shim-windows-revision.test.ts +25204 tests/codex-integration/codex-shim.test.ts +1570 tests/codex-integration/codex-sidecar-credit-policy.test.ts +132 tests/codex-integration/codex-signin-lockout.test.ts +282 tests/codex-integration/codex-spark-visibility.test.ts +55 tests/codex-integration/codex-sqlite-home.test.ts +409 tests/codex-integration/codex-stored-main-duplicate.test.ts +1375 tests/codex-integration/codex-sync-api.test.ts +346 tests/codex-integration/codex-sync-new-model-policy.test.ts 47 tests/codex-integration/codex-sync-response.test.ts -20954 tests/codex-integration/codex-sync-user-edits.test.ts -200 tests/codex-integration/codex-systemd-env-probe.test.ts -109 tests/codex-integration/codex-tool-mode.test.ts -554 tests/codex-integration/codex-transition-state-adoption.test.ts -70 tests/codex-integration/codex-transition-state-first-use-regression.test.ts -1917 tests/codex-integration/codex-transition-state-race.test.ts -288 tests/codex-integration/codex-transition-state.test.ts -221 tests/codex-integration/codex-use-remaining-quota.test.ts -102 tests/codex-integration/codex-user-identity.test.ts -768 tests/codex-integration/codex-v2-gate.test.ts -570 tests/codex-integration/codex-warmup.test.ts -2902 tests/codex-integration/codex-web-search-switch.test.ts -63 tests/codex-integration/codex-websocket-registry.test.ts -40 tests/codex-integration/codex-windows-current-sid.test.ts -3680 tests/codex-integration/codex-write-lock.test.ts -49 tests/codex-integration/combo-authoritative-reset.test.ts -47 tests/codex-integration/combo-codex-exhaustion-cooldown.test.ts -181 tests/codex-integration/combo-cooldown-reprobe.test.ts -660 tests/codex-integration/combo-description-catalog.test.ts -51 tests/codex-integration/combo-last-resort.test.ts -43 tests/codex-integration/combo-permanent-failure-cooldown.test.ts -48 tests/codex-integration/combo-reset-window-model-scope.test.ts -108 tests/codex-integration/combos-kiro-profile-hop.test.ts -692 tests/codex-integration/combos.test.ts -699 tests/codex-integration/compatibility-manifest.test.ts -119 tests/codex-integration/configured-native-models.test.ts -1790 tests/codex-integration/configured-ultrafast-picker.test.ts -139 tests/codex-integration/context-compat.test.ts -46 tests/codex-integration/custom-model-catalog-migration.test.ts -176 tests/codex-integration/deferred-collab-surface.test.ts -313 tests/codex-integration/discovered-native-models.test.ts -382 tests/codex-integration/doctor.test.ts -355 tests/codex-integration/effort-policy.test.ts -465 tests/codex-integration/exec-boundary-launch.test.ts -83 tests/codex-integration/exec-cli-bundle-containment.test.ts -142 tests/codex-integration/exec-cli-renamed-app-bundle.test.ts -106 tests/codex-integration/exec-known-app-bundles.test.ts -111 tests/codex-integration/exec-launcher-boundary.test.ts -42 tests/codex-integration/exec-renamed-app-bundle.test.ts -523 tests/codex-integration/exec-trust-boundary.test.ts -122 tests/codex-integration/fast-row-listing.test.ts -110 tests/codex-integration/fast-row.test.ts -221 tests/codex-integration/gather-routed-models-single-flight.test.ts -115 tests/codex-integration/gpt6-native-rows.test.ts -90 tests/codex-integration/gpt61-sol-rows.test.ts -173 tests/codex-integration/gpt61-terra-rows.test.ts -53 tests/codex-integration/history-migration-guardian.test.ts -134 tests/codex-integration/history-ocx-compaction-recovery.test.ts -60 tests/codex-integration/history-paginated-openai-compat.test.ts -1930 tests/codex-integration/history-paginated-transition-destinations.test.ts -89 tests/codex-integration/injection-link-websocket.test.ts -685 tests/codex-integration/injection-model-api.test.ts -275 tests/codex-integration/injection-model-suggest-routes.test.ts -71 tests/codex-integration/injection-routing-drift.test.ts -4005 tests/codex-integration/injection-routing-heal-apply.test.ts -600 tests/codex-integration/injection-routing-healer.test.ts -5962 tests/codex-integration/issue-452-empty-503.test.ts -4078 tests/codex-integration/issue-702-expired-replay-state.test.ts -575 tests/codex-integration/issue-914-transport-attribution.test.ts +20982 tests/codex-integration/codex-sync-user-edits.test.ts +144 tests/codex-integration/codex-systemd-env-probe.test.ts +97 tests/codex-integration/codex-tool-mode.test.ts +555 tests/codex-integration/codex-transition-state-adoption.test.ts +125 tests/codex-integration/codex-transition-state-first-use-regression.test.ts +1858 tests/codex-integration/codex-transition-state-race.test.ts +287 tests/codex-integration/codex-transition-state.test.ts +215 tests/codex-integration/codex-use-remaining-quota.test.ts +73 tests/codex-integration/codex-user-identity.test.ts +833 tests/codex-integration/codex-v2-gate.test.ts +355 tests/codex-integration/codex-warmup.test.ts +3399 tests/codex-integration/codex-web-search-switch.test.ts +52 tests/codex-integration/codex-websocket-registry.test.ts +52 tests/codex-integration/codex-windows-current-sid.test.ts +3312 tests/codex-integration/codex-write-lock.test.ts +51 tests/codex-integration/combo-authoritative-reset.test.ts +54 tests/codex-integration/combo-codex-exhaustion-cooldown.test.ts +105 tests/codex-integration/combo-cooldown-reprobe.test.ts +720 tests/codex-integration/combo-description-catalog.test.ts +73 tests/codex-integration/combo-last-resort.test.ts +63 tests/codex-integration/combo-permanent-failure-cooldown.test.ts +55 tests/codex-integration/combo-reset-window-model-scope.test.ts +52 tests/codex-integration/combos-kiro-profile-hop.test.ts +325 tests/codex-integration/combos.test.ts +784 tests/codex-integration/compatibility-manifest.test.ts +136 tests/codex-integration/configured-native-models.test.ts +1396 tests/codex-integration/configured-ultrafast-picker.test.ts +55 tests/codex-integration/context-compat.test.ts +53 tests/codex-integration/custom-model-catalog-migration.test.ts +250 tests/codex-integration/deferred-collab-surface.test.ts +150 tests/codex-integration/discovered-native-models.test.ts +523 tests/codex-integration/doctor.test.ts +278 tests/codex-integration/effort-policy.test.ts +377 tests/codex-integration/exec-boundary-launch.test.ts +101 tests/codex-integration/exec-cli-bundle-containment.test.ts +90 tests/codex-integration/exec-cli-renamed-app-bundle.test.ts +129 tests/codex-integration/exec-known-app-bundles.test.ts +129 tests/codex-integration/exec-launcher-boundary.test.ts +65 tests/codex-integration/exec-renamed-app-bundle.test.ts +880 tests/codex-integration/exec-trust-boundary.test.ts +184 tests/codex-integration/fast-row-listing.test.ts +94 tests/codex-integration/fast-row.test.ts +161 tests/codex-integration/gather-routed-models-single-flight.test.ts +110 tests/codex-integration/gpt6-native-rows.test.ts +146 tests/codex-integration/gpt61-sol-rows.test.ts +179 tests/codex-integration/gpt61-terra-rows.test.ts +49 tests/codex-integration/history-migration-guardian.test.ts +93 tests/codex-integration/history-ocx-compaction-recovery.test.ts +50 tests/codex-integration/history-paginated-openai-compat.test.ts +2184 tests/codex-integration/history-paginated-transition-destinations.test.ts +141 tests/codex-integration/injection-link-websocket.test.ts +433 tests/codex-integration/injection-model-api.test.ts +324 tests/codex-integration/injection-model-suggest-routes.test.ts +57 tests/codex-integration/injection-routing-drift.test.ts +3912 tests/codex-integration/injection-routing-heal-apply.test.ts +526 tests/codex-integration/injection-routing-healer.test.ts +6005 tests/codex-integration/issue-452-empty-503.test.ts +3913 tests/codex-integration/issue-702-expired-replay-state.test.ts +651 tests/codex-integration/issue-914-transport-attribution.test.ts 169 tests/codex-integration/low-quota-desktop-notifier.test.ts -1180 tests/codex-integration/low-quota-protection.test.ts -614 tests/codex-integration/main-account-credit-renewal.test.ts -68 tests/codex-integration/main-account-external-usage.test.ts -15417 tests/codex-integration/main-account-hard-lock-auth.test.ts -266 tests/codex-integration/main-account-hard-lock-default.test.ts -825 tests/codex-integration/main-account-hard-lock-fallback-off.test.ts -541 tests/codex-integration/main-account-hard-lock-fallback-routing.test.ts -53 tests/codex-integration/main-account-hard-lock-policy.test.ts -337 tests/codex-integration/main-account-hard-lock-profile-dispatch.test.ts -520 tests/codex-integration/main-account-hard-lock-recovery.test.ts -136 tests/codex-integration/main-account-hard-lock-retirement.test.ts -89 tests/codex-integration/main-account-hard-lock-thresholds.test.ts -130 tests/codex-integration/main-account-hard-lock-usage-limit.test.ts -518 tests/codex-integration/main-account-policy-binding-wait.test.ts -100 tests/codex-integration/main-device-reauth-api.test.ts -220 tests/codex-integration/main-device-reauth.test.ts -121 tests/codex-integration/main-quota-evidence-validation.test.ts -3462 tests/codex-integration/main-quota-provenance.test.ts -489 tests/codex-integration/main-quota-window-observation.test.ts -2824 tests/codex-integration/messaging-local-cli.test.ts -110 tests/codex-integration/messaging-local-discovery.test.ts -207 tests/codex-integration/messaging-local-envelope.test.ts -1165 tests/codex-integration/messaging-local-lifecycle.test.ts -425 tests/codex-integration/messaging-local-send.test.ts -106 tests/codex-integration/messaging-local-socket.test.ts -12446 tests/codex-integration/messaging-mcp-queue.test.ts -7927 tests/codex-integration/messaging-remote-admission.test.ts -703 tests/codex-integration/messaging-remote-contract.test.ts -712 tests/codex-integration/messaging-remote-enrollment-gaps.test.ts -13782 tests/codex-integration/messaging-remote-enrollment.test.ts -78 tests/codex-integration/messaging-remote-forward-failure.test.ts -3131 tests/codex-integration/messaging-remote-gaps.test.ts -67 tests/codex-integration/messaging-remote-interop.test.ts -16866 tests/codex-integration/messaging-remote-lifecycle.test.ts -55 tests/codex-integration/messaging-remote-native.test.ts -50 tests/codex-integration/messaging-remote-port-reservation.test.ts -13144 tests/codex-integration/messaging-remote-process.test.ts -3697 tests/codex-integration/messaging-remote-replies.test.ts -2064 tests/codex-integration/messaging-remote-scratch.test.ts -12063 tests/codex-integration/messaging-remote-send.test.ts -968 tests/codex-integration/messaging-remote-store.test.ts -46 tests/codex-integration/model-cache-generation-tombstone.test.ts -43 tests/codex-integration/model-cache.test.ts -335 tests/codex-integration/model-display-names-management-api.test.ts -229 tests/codex-integration/model-metadata-sync.test.ts -952 tests/codex-integration/model-pinned-effort.test.ts -1054 tests/codex-integration/model-visibility-management-api.test.ts -945 tests/codex-integration/multi-agent-compat.test.ts -404 tests/codex-integration/multi-agent-keep-native-v1.test.ts -79 tests/codex-integration/multi-agent-origin.test.ts -119 tests/codex-integration/native-alias-maintainer-regressions.test.ts -177 tests/codex-integration/native-claude-code-toggle.test.ts -553 tests/codex-integration/native-claude-desktop-toggle.test.ts -3798 tests/codex-integration/native-codex-toggle.test.ts -437 tests/codex-integration/native-grok-toggle.test.ts -85 tests/codex-integration/native-main-auth-temp.test.ts -44 tests/codex-integration/native-main-claim-cache.test.ts -173 tests/codex-integration/native-main-claim.test.ts -9707 tests/codex-integration/native-main-owner-lifetime.test.ts -1203 tests/codex-integration/native-main-refresh-mode.test.ts -913 tests/codex-integration/native-model-toggle.test.ts -104 tests/codex-integration/native-profile-api.test.ts -10716 tests/codex-integration/native-profile-crash-boundaries.test.ts -2416 tests/codex-integration/native-profile-drain-server.test.ts -2839 tests/codex-integration/native-profile-manager.test.ts -343 tests/codex-integration/native-profile-processes.test.ts -68 tests/codex-integration/native-profile-recovery.test.ts -589 tests/codex-integration/native-profile-route-security.test.ts -259 tests/codex-integration/native-profile-stage-lifecycle.test.ts -295 tests/codex-integration/native-profile-startup-release.test.ts -16469 tests/codex-integration/native-profile-startup.test.ts -408 tests/codex-integration/native-profile-store.test.ts -161 tests/codex-integration/native-source-priority.test.ts -1433 tests/codex-integration/native-ultrafast-picker.test.ts -466 tests/codex-integration/orca-import.test.ts -197 tests/codex-integration/parallel-tool-calls-optin.test.ts -86 tests/codex-integration/project-config-warning-snapshot.test.ts -161 tests/codex-integration/project-config-warnings.test.ts -156 tests/codex-integration/reasoning-effort.test.ts -94 tests/codex-integration/reasoning-metadata.test.ts -416 tests/codex-integration/reserve-auth-context.test.ts -56 tests/codex-integration/reserve-availability.test.ts -5148 tests/codex-integration/reserve-catalog-lifecycle.test.ts -217 tests/codex-integration/reserve-catalog.test.ts -1666 tests/codex-integration/reserve-dispatch.test.ts -125 tests/codex-integration/reserve-helper-boundary.test.ts -113 tests/codex-integration/reserve-passive-revocation.test.ts -136 tests/codex-integration/reserve-quota-scope.test.ts -135 tests/codex-integration/selected-models.test.ts -107 tests/codex-integration/slug-codec.test.ts -275 tests/codex-integration/token-guardian.test.ts -1169 tests/codex-integration/ultrafast-live-catalog.test.ts -1391 tests/codex-integration/ultrafast-tier-honesty.test.ts -100 tests/codex-integration/upstream-reachability.test.ts -157 tests/codex-integration/vendor-context.test.ts -42 tests/codex-integration/warmup.test.ts -267 tests/codex-integration/websocket-capacity-activity.test.ts -142 tests/config/atomic-write-exclusive.test.ts -143 tests/config/atomic-write-nofollow-streamed.test.ts -117 tests/config/client-config-export-new-clients.test.ts -136 tests/config/client-config-export-output-limit.test.ts -202 tests/config/client-config-export.test.ts -158 tests/config/client-config-new-clients.test.ts -220 tests/config/compaction-recovery-settings.test.ts -464 tests/config/config-account-auto-pause-revisions.test.ts -77 tests/config/config-account-thresholds.test.ts -428 tests/config/config-anthropic-instance-pool.test.ts -49 tests/config/config-blocked-model-redirects.test.ts -69 tests/config/config-catalog-auto-refresh.test.ts -41 tests/config/config-commandcode-claude-pin.test.ts -81 tests/config/config-concurrent-inbound-body.test.ts -102 tests/config/config-hosted-search-projection.test.ts -198 tests/config/config-load-degrade.test.ts -749 tests/config/config-mutation-lock.test.ts -123 tests/config/config-native-reasoning-retention.test.ts -63 tests/config/config-non-object-backup.test.ts -264 tests/config/config-opencode-go-upgrade.test.ts -129 tests/config/config-opencode-zen-upgrade.test.ts -112 tests/config/config-ownership-uninstall.test.ts -45 tests/config/config-rebase-provenance-writers.test.ts -211 tests/config/config-removed-opencode-free-preserve-failure.test.ts -2856 tests/config/config-removed-opencode-free.test.ts -65 tests/config/config-save-boundary.test.ts -78 tests/config/config-skills-catalog-refresh.test.ts -86 tests/config/config-spend-ceilings.test.ts -68 tests/config/config-spend-pool-collision.test.ts -702 tests/config/config-user-edits.test.ts -54 tests/config/config-workflow-budget.test.ts -88 tests/config/expand-user-path.test.ts -365 tests/config/hub-disable-live-save.test.ts -59 tests/config/lmstudio-system-policy.test.ts -3948 tests/config/local-credential-generation.test.ts -555 tests/config/model-pinned-effort-config.test.ts -47 tests/config/owner-registry-acl.test.ts -122 tests/config/owner-registry-isolation.test.ts -103 tests/config/protocol-settings.test.ts -1079 tests/config/serving-runtimes.test.ts -3904 tests/config/settings-desktop-switch-apply.test.ts -168 tests/config/settings-fast-rows.test.ts -271 tests/config/settings-main-account-hard-lock.test.ts -200 tests/config/settings-memory-models.test.ts -241 tests/config/settings-oauth-open-browser.test.ts -156 tests/config/settings-reasoning-retention.test.ts -263 tests/config/settings-startup-health-seam.test.ts -14818 tests/config/settings-stream-mode.test.ts -53 tests/config/types-barrel-identity.test.ts -118 tests/config/url-normalization.test.ts -45 tests/config/yaml-fragment-source.test.ts -110 tests/e2e-style/phase100-native-parity.test.ts -84 tests/gui/alibaba-intl-token-plan.test.ts -42 tests/gui/claude-manual-env.test.ts -39 tests/gui/codex-account-mode-state.test.ts -69 tests/gui/codex-auth-modal-status.test.ts -38 tests/gui/codex-set-prompt.test.ts -51 tests/gui/combo-workspace-data.test.ts -73 tests/gui/combo-workspace-jev-decision.test.ts -49 tests/gui/dashboard-sidecar-codex-write.test.ts -104 tests/gui/dashboard-uptime.test.ts -44 tests/gui/gui-api-error.test.ts -204 tests/gui/gui-codex-usage-score-parity.test.ts -64 tests/gui/gui-desktop-sidecar-script.test.ts -48 tests/gui/gui-desktop-sidecar-signing.test.ts -208 tests/gui/gui-management-session.test.ts -46 tests/gui/gui-pair-capability.test.ts -186 tests/gui/gui-pair-client.test.ts -270 tests/gui/gui-pair-delivery.test.ts -2247 tests/gui/gui-pair-http.test.ts -62 tests/gui/gui-static.test.ts -40 tests/gui/gui-tray-vibrancy-surface.test.ts -82 tests/gui/html-lang-boot-script.test.ts -493 tests/gui/integrations-invariants.test.ts -76 tests/gui/logs-model-tier-confirmation.test.ts -80 tests/gui/main-device-reauth-ui.test.ts -39 tests/gui/models-feedback-callback.test.ts -158 tests/gui/models-free-filter.test.ts +1398 tests/codex-integration/low-quota-protection.test.ts +420 tests/codex-integration/main-account-credit-renewal.test.ts +55 tests/codex-integration/main-account-external-usage.test.ts +16893 tests/codex-integration/main-account-hard-lock-auth.test.ts +172 tests/codex-integration/main-account-hard-lock-default.test.ts +602 tests/codex-integration/main-account-hard-lock-fallback-off.test.ts +619 tests/codex-integration/main-account-hard-lock-fallback-routing.test.ts +71 tests/codex-integration/main-account-hard-lock-policy.test.ts +257 tests/codex-integration/main-account-hard-lock-profile-dispatch.test.ts +562 tests/codex-integration/main-account-hard-lock-recovery.test.ts +94 tests/codex-integration/main-account-hard-lock-retirement.test.ts +100 tests/codex-integration/main-account-hard-lock-thresholds.test.ts +163 tests/codex-integration/main-account-hard-lock-usage-limit.test.ts +511 tests/codex-integration/main-account-policy-binding-wait.test.ts +80 tests/codex-integration/main-device-reauth-api.test.ts +154 tests/codex-integration/main-device-reauth.test.ts +133 tests/codex-integration/main-quota-evidence-validation.test.ts +3983 tests/codex-integration/main-quota-provenance.test.ts +548 tests/codex-integration/main-quota-window-observation.test.ts +3474 tests/codex-integration/messaging-local-cli.test.ts +103 tests/codex-integration/messaging-local-discovery.test.ts +157 tests/codex-integration/messaging-local-envelope.test.ts +715 tests/codex-integration/messaging-local-lifecycle.test.ts +365 tests/codex-integration/messaging-local-send.test.ts +61 tests/codex-integration/messaging-local-socket.test.ts +12512 tests/codex-integration/messaging-mcp-queue.test.ts +3322 tests/codex-integration/messaging-remote-admission.test.ts +231 tests/codex-integration/messaging-remote-contract.test.ts +339 tests/codex-integration/messaging-remote-enrollment-gaps.test.ts +6065 tests/codex-integration/messaging-remote-enrollment.test.ts +63 tests/codex-integration/messaging-remote-forward-failure.test.ts +1653 tests/codex-integration/messaging-remote-gaps.test.ts +46 tests/codex-integration/messaging-remote-interop.test.ts +13646 tests/codex-integration/messaging-remote-lifecycle.test.ts +46 tests/codex-integration/messaging-remote-native.test.ts +59 tests/codex-integration/messaging-remote-port-reservation.test.ts +13210 tests/codex-integration/messaging-remote-process.test.ts +1557 tests/codex-integration/messaging-remote-replies.test.ts +978 tests/codex-integration/messaging-remote-scratch.test.ts +3352 tests/codex-integration/messaging-remote-send.test.ts +439 tests/codex-integration/messaging-remote-store.test.ts +51 tests/codex-integration/model-cache-generation-tombstone.test.ts +49 tests/codex-integration/model-cache.test.ts +193 tests/codex-integration/model-display-names-management-api.test.ts +195 tests/codex-integration/model-metadata-sync.test.ts +879 tests/codex-integration/model-pinned-effort.test.ts +734 tests/codex-integration/model-visibility-management-api.test.ts +710 tests/codex-integration/multi-agent-compat.test.ts +582 tests/codex-integration/multi-agent-keep-native-v1.test.ts +78 tests/codex-integration/multi-agent-origin.test.ts +111 tests/codex-integration/native-alias-maintainer-regressions.test.ts +135 tests/codex-integration/native-claude-code-toggle.test.ts +481 tests/codex-integration/native-claude-desktop-toggle.test.ts +4015 tests/codex-integration/native-codex-toggle.test.ts +559 tests/codex-integration/native-grok-toggle.test.ts +62 tests/codex-integration/native-main-auth-temp.test.ts +48 tests/codex-integration/native-main-claim-cache.test.ts +196 tests/codex-integration/native-main-claim.test.ts +8458 tests/codex-integration/native-main-owner-lifetime.test.ts +947 tests/codex-integration/native-main-refresh-mode.test.ts +472 tests/codex-integration/native-model-toggle.test.ts +109 tests/codex-integration/native-profile-api.test.ts +8041 tests/codex-integration/native-profile-crash-boundaries.test.ts +2395 tests/codex-integration/native-profile-drain-server.test.ts +2454 tests/codex-integration/native-profile-manager.test.ts +352 tests/codex-integration/native-profile-processes.test.ts +93 tests/codex-integration/native-profile-recovery.test.ts +453 tests/codex-integration/native-profile-route-security.test.ts +236 tests/codex-integration/native-profile-stage-lifecycle.test.ts +282 tests/codex-integration/native-profile-startup-release.test.ts +15710 tests/codex-integration/native-profile-startup.test.ts +430 tests/codex-integration/native-profile-store.test.ts +265 tests/codex-integration/native-source-priority.test.ts +1767 tests/codex-integration/native-ultrafast-picker.test.ts +473 tests/codex-integration/orca-import.test.ts +109 tests/codex-integration/parallel-tool-calls-optin.test.ts +89 tests/codex-integration/project-config-warning-snapshot.test.ts +155 tests/codex-integration/project-config-warnings.test.ts +169 tests/codex-integration/reasoning-effort.test.ts +112 tests/codex-integration/reasoning-metadata.test.ts +482 tests/codex-integration/reserve-auth-context.test.ts +68 tests/codex-integration/reserve-availability.test.ts +5805 tests/codex-integration/reserve-catalog-lifecycle.test.ts +216 tests/codex-integration/reserve-catalog.test.ts +1566 tests/codex-integration/reserve-dispatch.test.ts +231 tests/codex-integration/reserve-helper-boundary.test.ts +94 tests/codex-integration/reserve-passive-revocation.test.ts +147 tests/codex-integration/reserve-quota-scope.test.ts +119 tests/codex-integration/selected-models.test.ts +120 tests/codex-integration/slug-codec.test.ts +519 tests/codex-integration/token-guardian.test.ts +1149 tests/codex-integration/ultrafast-live-catalog.test.ts +1281 tests/codex-integration/ultrafast-tier-honesty.test.ts +114 tests/codex-integration/upstream-reachability.test.ts +154 tests/codex-integration/vendor-context.test.ts +50 tests/codex-integration/warmup.test.ts +222 tests/codex-integration/websocket-capacity-activity.test.ts +120 tests/config/atomic-write-exclusive.test.ts +125 tests/config/atomic-write-nofollow-streamed.test.ts +138 tests/config/client-config-export-new-clients.test.ts +141 tests/config/client-config-export-output-limit.test.ts +176 tests/config/client-config-export.test.ts +178 tests/config/client-config-new-clients.test.ts +171 tests/config/compaction-recovery-settings.test.ts +565 tests/config/config-account-auto-pause-revisions.test.ts +83 tests/config/config-account-thresholds.test.ts +293 tests/config/config-anthropic-instance-pool.test.ts +79 tests/config/config-blocked-model-redirects.test.ts +86 tests/config/config-catalog-auto-refresh.test.ts +62 tests/config/config-commandcode-claude-pin.test.ts +95 tests/config/config-concurrent-inbound-body.test.ts +107 tests/config/config-hosted-search-projection.test.ts +139 tests/config/config-load-degrade.test.ts +846 tests/config/config-mutation-lock.test.ts +83 tests/config/config-native-reasoning-retention.test.ts +51 tests/config/config-non-object-backup.test.ts +226 tests/config/config-opencode-go-upgrade.test.ts +151 tests/config/config-opencode-zen-upgrade.test.ts +104 tests/config/config-ownership-uninstall.test.ts +50 tests/config/config-rebase-provenance-writers.test.ts +150 tests/config/config-removed-opencode-free-preserve-failure.test.ts +2494 tests/config/config-removed-opencode-free.test.ts +68 tests/config/config-save-boundary.test.ts +86 tests/config/config-skills-catalog-refresh.test.ts +131 tests/config/config-spend-ceilings.test.ts +82 tests/config/config-spend-pool-collision.test.ts +556 tests/config/config-user-edits.test.ts +58 tests/config/config-workflow-budget.test.ts +45 tests/config/expand-user-path.test.ts +403 tests/config/hub-disable-live-save.test.ts +51 tests/config/lmstudio-system-policy.test.ts +3790 tests/config/local-credential-generation.test.ts +283 tests/config/model-pinned-effort-config.test.ts +58 tests/config/owner-registry-acl.test.ts +109 tests/config/owner-registry-isolation.test.ts +112 tests/config/protocol-settings.test.ts +1002 tests/config/serving-runtimes.test.ts +4218 tests/config/settings-desktop-switch-apply.test.ts +208 tests/config/settings-fast-rows.test.ts +228 tests/config/settings-main-account-hard-lock.test.ts +249 tests/config/settings-memory-models.test.ts +259 tests/config/settings-oauth-open-browser.test.ts +215 tests/config/settings-reasoning-retention.test.ts +154 tests/config/settings-startup-health-seam.test.ts +13573 tests/config/settings-stream-mode.test.ts +42 tests/config/types-barrel-identity.test.ts +70 tests/config/url-normalization.test.ts +56 tests/config/yaml-fragment-source.test.ts +242 tests/e2e-style/phase100-native-parity.test.ts +117 tests/gui/alibaba-intl-token-plan.test.ts +41 tests/gui/claude-manual-env.test.ts +49 tests/gui/codex-account-mode-state.test.ts +42 tests/gui/codex-auth-modal-status.test.ts +43 tests/gui/codex-set-prompt.test.ts +46 tests/gui/combo-workspace-data.test.ts +70 tests/gui/combo-workspace-jev-decision.test.ts +47 tests/gui/dashboard-sidecar-codex-write.test.ts +181 tests/gui/dashboard-uptime.test.ts +46 tests/gui/gui-api-error.test.ts +128 tests/gui/gui-codex-usage-score-parity.test.ts +42 tests/gui/gui-desktop-sidecar-script.test.ts +50 tests/gui/gui-desktop-sidecar-signing.test.ts +67 tests/gui/gui-management-session.test.ts +48 tests/gui/gui-pair-capability.test.ts +198 tests/gui/gui-pair-client.test.ts +223 tests/gui/gui-pair-delivery.test.ts +2134 tests/gui/gui-pair-http.test.ts +67 tests/gui/gui-static.test.ts +50 tests/gui/gui-tray-vibrancy-surface.test.ts +170 tests/gui/html-lang-boot-script.test.ts +359 tests/gui/integrations-invariants.test.ts +67 tests/gui/logs-model-tier-confirmation.test.ts +83 tests/gui/main-device-reauth-ui.test.ts +50 tests/gui/models-feedback-callback.test.ts +56 tests/gui/models-free-filter.test.ts 44 tests/gui/models-page-groups.test.ts -48 tests/gui/models-workspace-tabs.test.ts -40 tests/gui/oauth-first-add-hint.test.ts -90 tests/gui/oauth-tos-warning.test.ts -720 tests/gui/platform-dialog-guard.test.ts -106 tests/gui/provider-payload.test.ts -49 tests/gui/provider-subscription-cli.test.ts -79 tests/gui/provider-workspace-auth.test.ts -282 tests/gui/provider-workspace-data.test.ts -117 tests/gui/provider-workspace-rail.test.ts -105 tests/gui/provider-workspace-state.test.ts -52 tests/gui/quota-bars-rows.test.ts -50 tests/gui/qwen-cloud-endpoints.test.ts -107 tests/gui/rate-limit-reset-credits.test.ts -47 tests/gui/routing-intelligence-ui.test.ts -56 tests/gui/routing-profile-editor-data.test.ts -106 tests/gui/standalone-build-script.test.ts -96 tests/gui/startup-health-ui.test.ts -125 tests/gui/tencent-siliconflow-providers.test.ts -117 tests/gui/vision-sidecar-timeout-bounds.test.ts -184 tests/gui/volcengine-providers.test.ts -102 tests/images/artifacts-prune.test.ts -128 tests/images/artifacts-ssrf.test.ts -109 tests/images/download-cap-default.test.ts -93 tests/images/download-connect-deadline-default.test.ts -179 tests/images/gemini-inline.test.ts -243 tests/images/loop-reasoning-replay.test.ts -130 tests/images/loop-terminal-refusal.test.ts -3089 tests/images/loop.test.ts -121 tests/images/pinned-https-get.test.ts -151 tests/images/plan.test.ts -48 tests/images/synthetic-tool.test.ts -124 tests/images/xai-client.test.ts -88 tests/images/z-fulfill.test.ts -277 tests/images/z-handler-activation.test.ts -524 tests/lab/core-lab-boundary.test.ts -277 tests/lab/core-link-boundary.test.ts -321 tests/lab/lab-activation.test.ts -290 tests/lab/lab-automation-coderabbit-regressions.test.ts -447 tests/lab/lab-automation-final-coderabbit-regressions.test.ts -146 tests/lab/lab-automation-ingwannu-regressions.test.ts -236 tests/lab/lab-automation-management-http.test.ts -42 tests/lab/lab-automation-persisted-cap-regression.test.ts -497 tests/lab/lab-automation-review-regressions.test.ts -386 tests/lab/lab-automation.test.ts -341 tests/lab/lab-community-evidence.test.ts -177 tests/lab/lab-community-filename-contract.test.ts -60 tests/lab/lab-community-mutation-lock.test.ts -178 tests/lab/lab-community-publisher-continuity.test.ts -158 tests/lab/lab-conformance-harness.test.ts -145 tests/lab/lab-conformance-runner-failures.test.ts -613 tests/lab/lab-evidence-ledger.test.ts -294 tests/lab/lab-evidence-sanitization.test.ts -218 tests/lab/lab-fabric-outcome-validation.test.ts -61 tests/lab/lab-fabric-persistence-boundary.test.ts -247 tests/lab/lab-fabric-producer-deadline.test.ts -96337 tests/lab/lab-fabric-task.test.ts -55 tests/lab/lab-installation-salt-cache.test.ts -901 tests/lab/lab-ledger-mutation-lock.test.ts -294 tests/lab/lab-live-pinned-timeouts.test.ts -159 tests/lab/lab-live-probe.test.ts -182 tests/lab/lab-live-receipt-integrity.test.ts -109 tests/lab/lab-live-review-regressions.test.ts -205 tests/lab/lab-live-sandbox.test.ts -484 tests/lab/lab-passive-production-evidence.test.ts -306 tests/lab/lab-passive-production-surfaces.test.ts -46 tests/lab/lab-paths-security.test.ts -121 tests/lab/lab-post-merge-hardening.test.ts -89 tests/lab/lab-post-merge-projection.test.ts -72 tests/lab/lab-private-file-consumer-recovery.test.ts -63 tests/lab/lab-private-file-durability.test.ts -219 tests/lab/lab-public-api-json.test.ts -174 tests/lab/lab-public-artifact-policy.test.ts -248 tests/lab/lab-public-coderabbit-regressions.test.ts -60 tests/lab/lab-public-core-contract.test.ts -170 tests/lab/lab-public-deep-review-regressions.test.ts -147 tests/lab/lab-public-evidence.test.ts -122 tests/lab/lab-public-export-transaction.test.ts -38 tests/lab/lab-public-file-safety.test.ts -338 tests/lab/lab-public-final-review-regressions.test.ts -234 tests/lab/lab-public-lifecycle-hardening.test.ts -83 tests/lab/lab-public-privacy-ipv6.test.ts -581 tests/lab/lab-public-provenance-recovery.test.ts -319 tests/lab/lab-public-review-fixes.test.ts -59 tests/lab/lab-public-route-registry.test.ts -71 tests/lab/lab-public-security-regressions.test.ts -203 tests/lab/lab-public-surfaces.test.ts -125 tests/lab/lab-public-wire-contract.test.ts -503 tests/lab/lab-read-filter-validation.test.ts -512 tests/lab/lab-read-surfaces.test.ts -742 tests/lib/abort-idle-deadline.test.ts -67 tests/lib/acl-error-classification.test.ts -383 tests/lib/ambiguous-resend-composition.test.ts -71 tests/lib/ambiguous-resend-gate.test.ts -44 tests/lib/authorization-scheme.test.ts -67 tests/lib/bounded-file-read.test.ts -118 tests/lib/bun-runtime-preflight.test.ts -56 tests/lib/bun-stream-caps.test.ts -114 tests/lib/clearable-deadline.test.ts -218 tests/lib/credential-redirect-guard.test.ts -47 tests/lib/debug.test.ts -117 tests/lib/execution-budget-permits.test.ts -87 tests/lib/failure-attribution.test.ts -75 tests/lib/failure-stage-model.test.ts -120 tests/lib/file-identity-callers.test.ts -42 tests/lib/file-identity.test.ts -109 tests/lib/fix-jsonc-cr-comments.test.ts -125 tests/lib/fix-jsonc-empty-comma.test.ts -36 tests/lib/fix-plain-data-own-keys.test.ts -39 tests/lib/fix-plain-data-shape.test.ts -37 tests/lib/fix-retry-release-timer.test.ts -93 tests/lib/local-chat-completion.test.ts -46 tests/lib/local-destinations.test.ts -67 tests/lib/local-upstream.test.ts -3169 tests/lib/opaque-proxy-tunnel-protocol.test.ts -517 tests/lib/opaque-proxy-tunnel.test.ts -967 tests/lib/optional-desktop-upstream.test.ts -429 tests/lib/optional-shutdown-hooks.test.ts -127 tests/lib/pinned-http-content-coding.test.ts -2090 tests/lib/pinned-http.test.ts -446 tests/lib/plugin-loader.test.ts -47 tests/lib/plugin-upstream-hooks.test.ts -38 tests/lib/privacy-mask-account.test.ts -46 tests/lib/process-control-graceful.test.ts -50 tests/lib/process-control.test.ts -46 tests/lib/provider-egress.test.ts -49 tests/lib/reasoning-replay-scope-source.test.ts -521 tests/lib/redact.test.ts -99 tests/lib/remove-tree-helper.test.ts -46 tests/lib/self-launch-argv.test.ts -1195 tests/lib/socks5-fetch.test.ts -165 tests/lib/socks5-tls-lifecycle.test.ts -58 tests/lib/socks5-upload-lifecycle.test.ts -283 tests/lib/spend-ceiling-enforcement.test.ts -45 tests/lib/spend-contract-c.test.ts -58 tests/lib/spend-corruption-compat.test.ts -74 tests/lib/spend-experimental-history.test.ts -99 tests/lib/spend-ledger-file-journal.test.ts -1408 tests/lib/spend-ledger-owner.test.ts -285 tests/lib/spend-pool-continuity.test.ts -43 tests/lib/spend-reservation-ledger.test.ts -990 tests/lib/spend-seed-overflow.test.ts -37 tests/lib/spend-unbound-expiry.test.ts -52 tests/lib/spend-zero-config-compat.test.ts -73 tests/lib/stall-subprocess-exit.test.ts -84 tests/lib/stall-timeout.test.ts -41 tests/lib/standalone.test.ts -57 tests/lib/strict-semver.test.ts -42 tests/lib/synced-state-location.test.ts -40 tests/lib/system-restart-contract-security.test.ts -112 tests/lib/token-estimate.test.ts -39 tests/lib/transient-budget-scope-source.test.ts -74 tests/lib/transport-null-body.test.ts -163 tests/lib/upstream-error-message-fallback.test.ts -69 tests/lib/upstream-retry-zero-output.test.ts -8192 tests/lib/upstream-retry.test.ts -247 tests/lib/worker-embed-coverage.test.ts -49 tests/lib/worker-embed.test.ts -155 tests/lib/workflow-budget.test.ts -486 tests/oauth/adapter-event-oauth-failover.test.ts -643 tests/oauth/anthropic2-discovery-ownership.test.ts -4194 tests/oauth/chatgpt-device-auth.test.ts -68 tests/oauth/chatgpt-oauth.test.ts -111 tests/oauth/chatgpt-token-boundaries.test.ts -126 tests/oauth/chatgpt-token-expiry.test.ts -10132 tests/oauth/dsh-login.test.ts -292 tests/oauth/generic-oauth-combo-account-cooldown.test.ts -499 tests/oauth/generic-oauth-failover.test.ts -365 tests/oauth/generic-oauth-refusal-composition.test.ts -758 tests/oauth/generic-session-affinity.test.ts -427 tests/oauth/key-login-live-update.test.ts -78 tests/oauth/key-login-preserves-model-costs.test.ts -52 tests/oauth/local-token-detect.test.ts -416 tests/oauth/oauth-account-attribution.test.ts -1144 tests/oauth/oauth-account-auto-pause-revision.test.ts -533 tests/oauth/oauth-account-auto-pause.test.ts -85 tests/oauth/oauth-account-id-collision.test.ts -270 tests/oauth/oauth-account-plans.test.ts -263 tests/oauth/oauth-account-quota-rank.test.ts -1779 tests/oauth/oauth-accounts-api.test.ts -447 tests/oauth/oauth-anthropic-identity.test.ts -466 tests/oauth/oauth-anthropic-instance-health.test.ts -1050 tests/oauth/oauth-anthropic-instance-multiprocess.test.ts -548 tests/oauth/oauth-anthropic-instance-refresh.test.ts -775 tests/oauth/oauth-anthropic-instance-registration.test.ts -58 tests/oauth/oauth-callback-binds.test.ts -50 tests/oauth/oauth-callback-server.test.ts -4216 tests/oauth/oauth-code-login.test.ts -48 tests/oauth/oauth-device-code-contract.test.ts -192 tests/oauth/oauth-health.test.ts -954 tests/oauth/oauth-kiro-refresh-attention.test.ts -70 tests/oauth/oauth-log.test.ts -191 tests/oauth/oauth-login-cli-browser-launch.test.ts -5554 tests/oauth/oauth-login-cli-errors.test.ts -607 tests/oauth/oauth-login-cli-live-update.test.ts -244 tests/oauth/oauth-login-open-browser.test.ts -126 tests/oauth/oauth-login-summary.test.ts -599 tests/oauth/oauth-manual-code.test.ts -227 tests/oauth/oauth-meta-muse-login-diagnostics.test.ts -100 tests/oauth/oauth-open-browser-choice.test.ts -178 tests/oauth/oauth-open-url-result.test.ts -195 tests/oauth/oauth-provider-reconcile.test.ts -403 tests/oauth/oauth-public-surface.test.ts -328 tests/oauth/oauth-reauth-bind.test.ts -133 tests/oauth/oauth-reconcile-operator-maps.test.ts -1021 tests/oauth/oauth-refresh-generic-lock.test.ts -3197 tests/oauth/oauth-refresh-lock-multiprocess.test.ts -436 tests/oauth/oauth-refresh-stale-capacity.test.ts -1927 tests/oauth/oauth-refresh.test.ts -445 tests/oauth/oauth-status-privacy.test.ts -639 tests/oauth/oauth-store-multi.test.ts -153 tests/oauth/oauth-store-quota-isolation.test.ts -103 tests/oauth/oauth-upsert-paused-api-key.test.ts -198 tests/oauth/oauth-upsert-preserves-api-key.test.ts -44 tests/oauth/pool-kernel-generic-sweep.test.ts -314 tests/oauth/state-store-sweeper.test.ts -70 tests/oauth/workbuddy-login.test.ts -436 tests/providers/aistupidlevel-provider.test.ts +50 tests/gui/models-workspace-tabs.test.ts +44 tests/gui/oauth-first-add-hint.test.ts +61 tests/gui/oauth-tos-warning.test.ts +398 tests/gui/platform-dialog-guard.test.ts +77 tests/gui/provider-payload.test.ts +134 tests/gui/provider-subscription-cli.test.ts +112 tests/gui/provider-workspace-auth.test.ts +132 tests/gui/provider-workspace-data.test.ts +137 tests/gui/provider-workspace-rail.test.ts +94 tests/gui/provider-workspace-state.test.ts +154 tests/gui/quota-bars-rows.test.ts +54 tests/gui/qwen-cloud-endpoints.test.ts +57 tests/gui/rate-limit-reset-credits.test.ts +53 tests/gui/routing-intelligence-ui.test.ts +50 tests/gui/routing-profile-editor-data.test.ts +112 tests/gui/standalone-build-script.test.ts +128 tests/gui/startup-health-ui.test.ts +146 tests/gui/tencent-siliconflow-providers.test.ts +85 tests/gui/vision-sidecar-timeout-bounds.test.ts +263 tests/gui/volcengine-providers.test.ts +98 tests/images/artifacts-prune.test.ts +80 tests/images/artifacts-ssrf.test.ts +51 tests/images/download-cap-default.test.ts +68 tests/images/download-connect-deadline-default.test.ts +85 tests/images/gemini-inline.test.ts +133 tests/images/loop-reasoning-replay.test.ts +96 tests/images/loop-terminal-refusal.test.ts +3291 tests/images/loop.test.ts +60 tests/images/pinned-https-get.test.ts +89 tests/images/plan.test.ts +47 tests/images/synthetic-tool.test.ts +127 tests/images/xai-client.test.ts +112 tests/images/z-fulfill.test.ts +295 tests/images/z-handler-activation.test.ts +470 tests/lab/core-lab-boundary.test.ts +332 tests/lab/core-link-boundary.test.ts +180 tests/lab/lab-activation.test.ts +348 tests/lab/lab-automation-coderabbit-regressions.test.ts +281 tests/lab/lab-automation-final-coderabbit-regressions.test.ts +214 tests/lab/lab-automation-ingwannu-regressions.test.ts +180 tests/lab/lab-automation-management-http.test.ts +62 tests/lab/lab-automation-persisted-cap-regression.test.ts +472 tests/lab/lab-automation-review-regressions.test.ts +486 tests/lab/lab-automation.test.ts +396 tests/lab/lab-community-evidence.test.ts +170 tests/lab/lab-community-filename-contract.test.ts +70 tests/lab/lab-community-mutation-lock.test.ts +150 tests/lab/lab-community-publisher-continuity.test.ts +146 tests/lab/lab-conformance-harness.test.ts +181 tests/lab/lab-conformance-runner-failures.test.ts +471 tests/lab/lab-evidence-ledger.test.ts +311 tests/lab/lab-evidence-sanitization.test.ts +216 tests/lab/lab-fabric-outcome-validation.test.ts +49 tests/lab/lab-fabric-persistence-boundary.test.ts +206 tests/lab/lab-fabric-producer-deadline.test.ts +95859 tests/lab/lab-fabric-task.test.ts +70 tests/lab/lab-installation-salt-cache.test.ts +772 tests/lab/lab-ledger-mutation-lock.test.ts +303 tests/lab/lab-live-pinned-timeouts.test.ts +192 tests/lab/lab-live-probe.test.ts +175 tests/lab/lab-live-receipt-integrity.test.ts +133 tests/lab/lab-live-review-regressions.test.ts +272 tests/lab/lab-live-sandbox.test.ts +207 tests/lab/lab-passive-production-evidence.test.ts +222 tests/lab/lab-passive-production-surfaces.test.ts +62 tests/lab/lab-paths-security.test.ts +125 tests/lab/lab-post-merge-hardening.test.ts +248 tests/lab/lab-post-merge-projection.test.ts +63 tests/lab/lab-private-file-consumer-recovery.test.ts +60 tests/lab/lab-private-file-durability.test.ts +252 tests/lab/lab-public-api-json.test.ts +137 tests/lab/lab-public-artifact-policy.test.ts +267 tests/lab/lab-public-coderabbit-regressions.test.ts +61 tests/lab/lab-public-core-contract.test.ts +137 tests/lab/lab-public-deep-review-regressions.test.ts +164 tests/lab/lab-public-evidence.test.ts +157 tests/lab/lab-public-export-transaction.test.ts +58 tests/lab/lab-public-file-safety.test.ts +233 tests/lab/lab-public-final-review-regressions.test.ts +153 tests/lab/lab-public-lifecycle-hardening.test.ts +97 tests/lab/lab-public-privacy-ipv6.test.ts +452 tests/lab/lab-public-provenance-recovery.test.ts +335 tests/lab/lab-public-review-fixes.test.ts +55 tests/lab/lab-public-route-registry.test.ts +62 tests/lab/lab-public-security-regressions.test.ts +472 tests/lab/lab-public-surfaces.test.ts +67 tests/lab/lab-public-wire-contract.test.ts +208 tests/lab/lab-read-filter-validation.test.ts +575 tests/lab/lab-read-surfaces.test.ts +794 tests/lib/abort-idle-deadline.test.ts +96 tests/lib/acl-error-classification.test.ts +321 tests/lib/ambiguous-resend-composition.test.ts +72 tests/lib/ambiguous-resend-gate.test.ts +98 tests/lib/authorization-scheme.test.ts +63 tests/lib/bounded-file-read.test.ts +132 tests/lib/bun-runtime-preflight.test.ts +41 tests/lib/bun-stream-caps.test.ts +128 tests/lib/clearable-deadline.test.ts +50 tests/lib/client-retry-after.test.ts +266 tests/lib/credential-redirect-guard.test.ts +49 tests/lib/debug.test.ts +168 tests/lib/execution-budget-permits.test.ts +67 tests/lib/failure-attribution.test.ts +57 tests/lib/failure-stage-model.test.ts +70 tests/lib/file-identity-callers.test.ts +57 tests/lib/file-identity.test.ts +56 tests/lib/fix-jsonc-cr-comments.test.ts +43 tests/lib/fix-jsonc-empty-comma.test.ts +43 tests/lib/fix-plain-data-own-keys.test.ts +48 tests/lib/fix-plain-data-shape.test.ts +45 tests/lib/fix-retry-release-timer.test.ts +118 tests/lib/local-chat-completion.test.ts +55 tests/lib/local-destinations.test.ts +71 tests/lib/local-upstream.test.ts +3118 tests/lib/opaque-proxy-tunnel-protocol.test.ts +542 tests/lib/opaque-proxy-tunnel.test.ts +994 tests/lib/optional-desktop-upstream.test.ts +292 tests/lib/optional-shutdown-hooks.test.ts +102 tests/lib/pinned-http-content-coding.test.ts +1521 tests/lib/pinned-http.test.ts +279 tests/lib/plugin-loader.test.ts +50 tests/lib/plugin-upstream-hooks.test.ts +53 tests/lib/privacy-mask-account.test.ts +97 tests/lib/private-sqlite-path.test.ts +49 tests/lib/process-control-graceful.test.ts +42 tests/lib/process-control.test.ts +42 tests/lib/provider-egress.test.ts +56 tests/lib/reasoning-replay-scope-source.test.ts +220 tests/lib/redact.test.ts +66 tests/lib/remove-tree-helper.test.ts +50 tests/lib/self-launch-argv.test.ts +1330 tests/lib/socks5-fetch.test.ts +84 tests/lib/socks5-tls-lifecycle.test.ts +81 tests/lib/socks5-upload-lifecycle.test.ts +167 tests/lib/spend-ceiling-enforcement.test.ts +44 tests/lib/spend-contract-c.test.ts +46 tests/lib/spend-corruption-compat.test.ts +51 tests/lib/spend-experimental-history.test.ts +123 tests/lib/spend-ledger-file-journal.test.ts +1036 tests/lib/spend-ledger-owner.test.ts +459 tests/lib/spend-pool-continuity.test.ts +59 tests/lib/spend-reservation-ledger.test.ts +953 tests/lib/spend-seed-overflow.test.ts +52 tests/lib/spend-unbound-expiry.test.ts +50 tests/lib/spend-zero-config-compat.test.ts +42 tests/lib/stall-subprocess-exit.test.ts +49 tests/lib/stall-timeout.test.ts +45 tests/lib/standalone.test.ts +53 tests/lib/strict-semver.test.ts +45 tests/lib/synced-state-location.test.ts +53 tests/lib/system-restart-contract-security.test.ts +57 tests/lib/token-estimate.test.ts +41 tests/lib/transient-budget-scope-source.test.ts +86 tests/lib/transport-null-body.test.ts +58 tests/lib/upstream-condition.test.ts +157 tests/lib/upstream-error-message-fallback.test.ts +45 tests/lib/upstream-retry-zero-output.test.ts +8191 tests/lib/upstream-retry.test.ts +212 tests/lib/worker-embed-coverage.test.ts +67 tests/lib/worker-embed.test.ts +97 tests/lib/workflow-budget.test.ts +437 tests/oauth/adapter-event-oauth-failover.test.ts +702 tests/oauth/anthropic2-discovery-ownership.test.ts +4144 tests/oauth/chatgpt-device-auth.test.ts +57 tests/oauth/chatgpt-oauth.test.ts +107 tests/oauth/chatgpt-token-boundaries.test.ts +103 tests/oauth/chatgpt-token-expiry.test.ts +10141 tests/oauth/dsh-login.test.ts +332 tests/oauth/generic-oauth-combo-account-cooldown.test.ts +359 tests/oauth/generic-oauth-failover.test.ts +376 tests/oauth/generic-oauth-refusal-composition.test.ts +318 tests/oauth/generic-session-affinity.test.ts +346 tests/oauth/key-login-live-update.test.ts +81 tests/oauth/key-login-preserves-model-costs.test.ts +43 tests/oauth/local-token-detect.test.ts +336 tests/oauth/oauth-account-attribution.test.ts +1275 tests/oauth/oauth-account-auto-pause-revision.test.ts +354 tests/oauth/oauth-account-auto-pause.test.ts +100 tests/oauth/oauth-account-id-collision.test.ts +292 tests/oauth/oauth-account-plans.test.ts +161 tests/oauth/oauth-account-quota-rank.test.ts +2285 tests/oauth/oauth-accounts-api.test.ts +317 tests/oauth/oauth-anthropic-identity.test.ts +371 tests/oauth/oauth-anthropic-instance-health.test.ts +1123 tests/oauth/oauth-anthropic-instance-multiprocess.test.ts +358 tests/oauth/oauth-anthropic-instance-refresh.test.ts +479 tests/oauth/oauth-anthropic-instance-registration.test.ts +41 tests/oauth/oauth-callback-binds.test.ts +58 tests/oauth/oauth-callback-server.test.ts +2746 tests/oauth/oauth-code-login.test.ts +50 tests/oauth/oauth-device-code-contract.test.ts +167 tests/oauth/oauth-health.test.ts +653 tests/oauth/oauth-kiro-refresh-attention.test.ts +47 tests/oauth/oauth-log.test.ts +153 tests/oauth/oauth-login-cli-browser-launch.test.ts +4713 tests/oauth/oauth-login-cli-errors.test.ts +529 tests/oauth/oauth-login-cli-live-update.test.ts +182 tests/oauth/oauth-login-open-browser.test.ts +123 tests/oauth/oauth-login-summary.test.ts +691 tests/oauth/oauth-manual-code.test.ts +282 tests/oauth/oauth-meta-muse-login-diagnostics.test.ts +179 tests/oauth/oauth-open-browser-choice.test.ts +114 tests/oauth/oauth-open-url-result.test.ts +185 tests/oauth/oauth-provider-reconcile.test.ts +496 tests/oauth/oauth-public-surface.test.ts +247 tests/oauth/oauth-reauth-bind.test.ts +125 tests/oauth/oauth-reconcile-operator-maps.test.ts +674 tests/oauth/oauth-refresh-generic-lock.test.ts +3039 tests/oauth/oauth-refresh-lock-multiprocess.test.ts +555 tests/oauth/oauth-refresh-stale-capacity.test.ts +1536 tests/oauth/oauth-refresh.test.ts +271 tests/oauth/oauth-status-privacy.test.ts +543 tests/oauth/oauth-store-multi.test.ts +98 tests/oauth/oauth-store-quota-isolation.test.ts +75 tests/oauth/oauth-upsert-paused-api-key.test.ts +283 tests/oauth/oauth-upsert-preserves-api-key.test.ts +48 tests/oauth/pool-kernel-generic-sweep.test.ts +218 tests/oauth/state-store-sweeper.test.ts +101 tests/oauth/workbuddy-login.test.ts +565 tests/providers/aistupidlevel-provider.test.ts 51 tests/providers/alibaba-region-backup.test.ts -106 tests/providers/alibaba-region-migration.test.ts -46 tests/providers/alibaba-region-startup.test.ts -222 tests/providers/alibaba-token-plan-responses-optin.test.ts -361 tests/providers/alibaba-token-plan-wire-defaults.test.ts -301 tests/providers/api-key-auto-pause-distribution.test.ts -128 tests/providers/api-key-catalog-authority.test.ts -43 tests/providers/api-key-selection-capture.test.ts -395 tests/providers/api-key-selection-cooldown.test.ts -158 tests/providers/aside-client.test.ts -45 tests/providers/auto-compact-budget.test.ts -124 tests/providers/azure-adapter.test.ts -46 tests/providers/azure-model-router-tool-schema.test.ts -200 tests/providers/azure-vendor-metadata.test.ts -137 tests/providers/baseten-provider.test.ts -489 tests/providers/cc-switch-import.test.ts -123 tests/providers/chutes-provider.test.ts -983 tests/providers/claude-cli-adapter.test.ts -344 tests/providers/claude-cli-client-http.test.ts +114 tests/providers/alibaba-region-migration.test.ts +62 tests/providers/alibaba-region-startup.test.ts +303 tests/providers/alibaba-token-plan-responses-optin.test.ts +308 tests/providers/alibaba-token-plan-wire-defaults.test.ts +147 tests/providers/api-key-auto-pause-distribution.test.ts +136 tests/providers/api-key-catalog-authority.test.ts +44 tests/providers/api-key-selection-capture.test.ts +159 tests/providers/api-key-selection-cooldown.test.ts +119 tests/providers/aside-client.test.ts +50 tests/providers/auto-compact-budget.test.ts +139 tests/providers/azure-adapter.test.ts +48 tests/providers/azure-model-router-tool-schema.test.ts +204 tests/providers/azure-vendor-metadata.test.ts +150 tests/providers/baseten-provider.test.ts +466 tests/providers/cc-switch-import.test.ts +203 tests/providers/chutes-provider.test.ts +937 tests/providers/claude-cli-adapter.test.ts +306 tests/providers/claude-cli-client-http.test.ts 53 tests/providers/claude-cli-efficiency.test.ts -100 tests/providers/claude-cli-tool-capture.test.ts -391 tests/providers/claude-cli-usage-admission.test.ts -160 tests/providers/cline-pass-deepseek-v4-tool-replay.test.ts -144 tests/providers/cline-pass-provider.test.ts -124 tests/providers/cline-pass-reasoning-efforts.test.ts -56 tests/providers/cline-provider.test.ts -222 tests/providers/codebuddy-adapter.test.ts -46 tests/providers/codebuddy-live-acceptance.test.ts -228 tests/providers/codebuddy-live-models.test.ts -2768 tests/providers/codebuddy-mcp-server.test.ts -49 tests/providers/codebuddy-protocol.test.ts -316 tests/providers/codebuddy-tool-bridge-turn.test.ts -164 tests/providers/codebuddy-tool-bridge.test.ts -56 tests/providers/coding-agent-json-lines-scaling.test.ts -291 tests/providers/command-code-credit-failover.test.ts -1224 tests/providers/command-code-credit-rotation.test.ts -516 tests/providers/command-code-efforts.test.ts -106 tests/providers/command-code-error-finish.test.ts +90 tests/providers/claude-cli-tool-capture.test.ts +280 tests/providers/claude-cli-usage-admission.test.ts +150 tests/providers/cline-pass-deepseek-v4-tool-replay.test.ts +102 tests/providers/cline-pass-provider.test.ts +146 tests/providers/cline-pass-reasoning-efforts.test.ts +52 tests/providers/cline-provider.test.ts +209 tests/providers/codebuddy-adapter.test.ts +47 tests/providers/codebuddy-live-acceptance.test.ts +125 tests/providers/codebuddy-live-models.test.ts +2679 tests/providers/codebuddy-mcp-server.test.ts +55 tests/providers/codebuddy-protocol.test.ts +306 tests/providers/codebuddy-tool-bridge-turn.test.ts +146 tests/providers/codebuddy-tool-bridge.test.ts +63 tests/providers/coding-agent-json-lines-scaling.test.ts +313 tests/providers/command-code-credit-failover.test.ts +281 tests/providers/command-code-credit-rotation.test.ts +259 tests/providers/command-code-efforts.test.ts +86 tests/providers/command-code-error-finish.test.ts 186 tests/providers/command-code-fakeip-discovery.test.ts -774 tests/providers/command-code-plan-denial.test.ts -2203 tests/providers/command-code-project-context.test.ts -1588 tests/providers/command-code-provider.test.ts -138 tests/providers/command-code-quota.test.ts -346 tests/providers/command-code-tool-text-prose-split.test.ts -799 tests/providers/command-code-tool-text.test.ts -58 tests/providers/command-code-workspace-cache.test.ts -191 tests/providers/commandcode-provider.test.ts -67 tests/providers/context-cap-unknown-window.test.ts -43 tests/providers/context-window-seed-repair.test.ts -202 tests/providers/crusoe-provider.test.ts -273 tests/providers/cursor/cursor-adapter.test.ts -61 tests/providers/cursor/cursor-arg-normalize.test.ts -116 tests/providers/cursor/cursor-blob-claude-client-tools.test.ts -54 tests/providers/cursor/cursor-blob-integrity.test.ts -328 tests/providers/cursor/cursor-blob.test.ts -73 tests/providers/cursor/cursor-call-id.test.ts -110 tests/providers/cursor/cursor-cancel-provenance.test.ts -49 tests/providers/cursor/cursor-catalog.test.ts -49 tests/providers/cursor/cursor-claude-id.test.ts -146 tests/providers/cursor/cursor-continuation-invariants.test.ts -238 tests/providers/cursor/cursor-continuity-retention.test.ts -65 tests/providers/cursor/cursor-default-catalog-suppression.test.ts -125 tests/providers/cursor/cursor-desktop-exec.test.ts -64 tests/providers/cursor/cursor-discovery.test.ts -82 tests/providers/cursor/cursor-display-names.test.ts -822 tests/providers/cursor/cursor-effort-rows.test.ts -64 tests/providers/cursor/cursor-effort-suffix.test.ts -46 tests/providers/cursor/cursor-effort-table.test.ts -125 tests/providers/cursor/cursor-envelope-echo-retry.test.ts -124 tests/providers/cursor/cursor-eof-terminal.test.ts -67 tests/providers/cursor/cursor-errors.test.ts -61 tests/providers/cursor/cursor-exec-empty-result.test.ts -106 tests/providers/cursor/cursor-fast-listing.test.ts -76 tests/providers/cursor/cursor-fast-tier.test.ts -284 tests/providers/cursor/cursor-foreground-shell.test.ts -113 tests/providers/cursor/cursor-framing.test.ts -76 tests/providers/cursor/cursor-freeform-args.test.ts -212 tests/providers/cursor/cursor-h2-pool-shutdown.test.ts -2837 tests/providers/cursor/cursor-hardening.test.ts -106 tests/providers/cursor/cursor-http1-transport.test.ts -3165 tests/providers/cursor/cursor-images.test.ts -784 tests/providers/cursor/cursor-integration-status.test.ts -121 tests/providers/cursor/cursor-interaction-query.test.ts -40 tests/providers/cursor/cursor-kv-store.test.ts -40 tests/providers/cursor/cursor-live-smoke-gate.test.ts -355 tests/providers/cursor/cursor-live-transport.test.ts -40 tests/providers/cursor/cursor-local-installer.test.ts -591 tests/providers/cursor/cursor-local-models-schema.test.ts -207 tests/providers/cursor/cursor-mcp-manager.test.ts -448 tests/providers/cursor/cursor-mcp-stdio.test.ts -83 tests/providers/cursor/cursor-message-mapper.test.ts -65 tests/providers/cursor/cursor-native-exec-common.test.ts -124 tests/providers/cursor/cursor-native-exec-policy.test.ts -159 tests/providers/cursor/cursor-native-exec-shell.test.ts -243 tests/providers/cursor/cursor-native-exec.test.ts -76 tests/providers/cursor/cursor-native-grep-globs.test.ts -120 tests/providers/cursor/cursor-oauth-shell.test.ts -635 tests/providers/cursor/cursor-oauth.test.ts -99 tests/providers/cursor/cursor-pool.test.ts -84 tests/providers/cursor/cursor-protobuf-events.test.ts -172 tests/providers/cursor/cursor-repetition-breaker.test.ts -136 tests/providers/cursor/cursor-request-builder.test.ts -119 tests/providers/cursor/cursor-request-compat.test.ts -142 tests/providers/cursor/cursor-roster-account-scope.test.ts -51 tests/providers/cursor/cursor-silent-redirect.test.ts -126 tests/providers/cursor/cursor-static-catalog.test.ts -3533 tests/providers/cursor/cursor-stream-health.test.ts -111 tests/providers/cursor/cursor-structured-edit.test.ts -68 tests/providers/cursor/cursor-tool-arg-decoding.test.ts -105 tests/providers/cursor/cursor-tool-choice.test.ts -93 tests/providers/cursor/cursor-tool-continuation.test.ts -83 tests/providers/cursor/cursor-tool-definitions.test.ts -4028 tests/providers/cursor/cursor-tool-finalize-race.test.ts -105 tests/providers/cursor/cursor-tool-result-image.test.ts -275 tests/providers/cursor/cursor-tool-result-invocation.test.ts -72 tests/providers/cursor/cursor-tool-suspended-checkpoint.test.ts -217 tests/providers/cursor/cursor-tool-wording.test.ts -109 tests/providers/cursor/cursor-toolresult-normalize.test.ts -1852 tests/providers/cursor/cursor-transport-retry.test.ts -108 tests/providers/cursor/cursor-ultra-mode.test.ts -104 tests/providers/cursor/cursor-umbrella-rows.test.ts -36 tests/providers/cursor/cursor-uncallable-quarantine.test.ts -93 tests/providers/cursor/cursor-vision-wire-harness.test.ts -308 tests/providers/cyber-policy-error-fidelity.test.ts -116 tests/providers/deepinfra-provider.test.ts -58 tests/providers/deepseek-artifact-tool-schema.test.ts -134 tests/providers/deepseek-bare-tool-call-replay.test.ts -10110 tests/providers/deepseek-image-files.test.ts -579 tests/providers/deepseek-inbound-wire.test.ts -97 tests/providers/deepseek-quota-currency.test.ts -124 tests/providers/deepseek-reasoning-replay-gaps.test.ts -142 tests/providers/deepseek-reasoning-replay.test.ts -442 tests/providers/deepseek-responses-item-id-repair.test.ts -2108 tests/providers/devin-adapter-reset-wait.test.ts -170 tests/providers/devin-adapter.test.ts -230 tests/providers/devin-anthropic-signature-fallback.test.ts -243 tests/providers/devin-chat-wire-fixes.test.ts -106 tests/providers/devin-cli-authmode-migration.test.ts -70 tests/providers/devin-effort-ladder.test.ts -128 tests/providers/devin-family-resolution.test.ts -120 tests/providers/devin-hardening.test.ts -101 tests/providers/devin-image-passthrough.test.ts -133 tests/providers/devin-live-models.test.ts -206 tests/providers/devin-login.test.ts -85 tests/providers/devin-output-budget.test.ts -142 tests/providers/devin-prompt-cache.test.ts -63 tests/providers/devin-provider-merge-migration.test.ts -188 tests/providers/devin-quota.test.ts -85 tests/providers/devin-reasoning-continuation.test.ts -44 tests/providers/devin-stated-reset-hardening.test.ts -76 tests/providers/devin-stated-reset-retry.test.ts -108 tests/providers/devin-stream-deadline.test.ts -83 tests/providers/devin-trajectory.test.ts -136 tests/providers/digitalocean-scaleway-provider.test.ts -689 tests/providers/dsh-account.test.ts -143 tests/providers/exa-web-search.test.ts -459 tests/providers/explicit-key-pause-oauth-boundary.test.ts -87 tests/providers/fast-row-ingress.test.ts -131 tests/providers/featherless-provider.test.ts -162 tests/providers/flash-route-image-modalities.test.ts -989 tests/providers/forward-admission-separation.test.ts -96 tests/providers/free-directory-runcrate.test.ts -1121 tests/providers/github-copilot/github-copilot-account-origin.test.ts -1632 tests/providers/github-copilot/github-copilot-auto-runtime.test.ts -87 tests/providers/github-copilot/github-copilot-auto.test.ts -94 tests/providers/github-copilot/github-copilot-catalog-hints.test.ts -121 tests/providers/github-copilot/github-copilot-context-tier.test.ts -16102 tests/providers/github-copilot/github-copilot-oauth.test.ts -74 tests/providers/github-copilot/github-copilot-sse-rewrite.test.ts -517 tests/providers/github-copilot/github-copilot-stream-contract.test.ts -288 tests/providers/github-copilot/github-copilot-wire-defaults.test.ts -1149 tests/providers/gpt61-terra-provider-rows.test.ts -58 tests/providers/haiku-5-5-catalog.test.ts -98 tests/providers/hyperbolic-provider.test.ts -640 tests/providers/initial-model-selection.test.ts -468 tests/providers/initial-selection-write-fence.test.ts -239 tests/providers/jev-provider.test.ts -118 tests/providers/kimi-oauth-identity.test.ts -125 tests/providers/kimi-responses-adjacency.test.ts -55 tests/providers/kiro/kiro-account-load.test.ts -231 tests/providers/kiro/kiro-account-quota.test.ts -4042 tests/providers/kiro/kiro-account-state-disk.test.ts -843 tests/providers/kiro/kiro-account-state-imports.test.ts -212 tests/providers/kiro/kiro-adapter.test.ts -348 tests/providers/kiro/kiro-auth-context-continuation.test.ts -102 tests/providers/kiro/kiro-auto-selection.test.ts -135 tests/providers/kiro/kiro-builder-id-profile.test.ts -40 tests/providers/kiro/kiro-calibration.test.ts -113 tests/providers/kiro/kiro-completion-with-real-tools.test.ts -161 tests/providers/kiro/kiro-device-builder.test.ts -170 tests/providers/kiro/kiro-device-iam.test.ts -301 tests/providers/kiro/kiro-device-social.test.ts -74 tests/providers/kiro/kiro-fallback-error-body.test.ts -2842 tests/providers/kiro/kiro-images.test.ts -1560 tests/providers/kiro/kiro-leased-responses.test.ts -46 tests/providers/kiro/kiro-metering-events.test.ts -71 tests/providers/kiro/kiro-metering-usage.test.ts -194 tests/providers/kiro/kiro-model-catalog.test.ts -222 tests/providers/kiro/kiro-model-preference.test.ts -210 tests/providers/kiro/kiro-oauth.test.ts -318 tests/providers/kiro/kiro-org-user-identity.test.ts -692 tests/providers/kiro/kiro-pool-load-settings.test.ts +823 tests/providers/command-code-plan-denial.test.ts +2175 tests/providers/command-code-project-context.test.ts +706 tests/providers/command-code-provider.test.ts +106 tests/providers/command-code-quota.test.ts +98 tests/providers/command-code-tool-text-prose-split.test.ts +1612 tests/providers/command-code-tool-text.test.ts +71 tests/providers/command-code-workspace-cache.test.ts +201 tests/providers/commandcode-provider.test.ts +37 tests/providers/context-cap-unknown-window.test.ts +44 tests/providers/context-window-seed-repair.test.ts +192 tests/providers/crusoe-provider.test.ts +265 tests/providers/cursor/cursor-adapter.test.ts +56 tests/providers/cursor/cursor-arg-normalize.test.ts +104 tests/providers/cursor/cursor-blob-claude-client-tools.test.ts +74 tests/providers/cursor/cursor-blob-integrity.test.ts +339 tests/providers/cursor/cursor-blob.test.ts +58 tests/providers/cursor/cursor-call-id.test.ts +88 tests/providers/cursor/cursor-cancel-provenance.test.ts +59 tests/providers/cursor/cursor-catalog.test.ts +51 tests/providers/cursor/cursor-claude-id.test.ts +214 tests/providers/cursor/cursor-continuation-invariants.test.ts +124 tests/providers/cursor/cursor-continuity-retention.test.ts +54 tests/providers/cursor/cursor-default-catalog-suppression.test.ts +108 tests/providers/cursor/cursor-desktop-exec.test.ts +50 tests/providers/cursor/cursor-discovery.test.ts +126 tests/providers/cursor/cursor-display-names.test.ts +863 tests/providers/cursor/cursor-effort-rows.test.ts +83 tests/providers/cursor/cursor-effort-suffix.test.ts +58 tests/providers/cursor/cursor-effort-table.test.ts +154 tests/providers/cursor/cursor-envelope-echo-retry.test.ts +135 tests/providers/cursor/cursor-eof-terminal.test.ts +70 tests/providers/cursor/cursor-errors.test.ts +46 tests/providers/cursor/cursor-exec-empty-result.test.ts +135 tests/providers/cursor/cursor-fast-listing.test.ts +78 tests/providers/cursor/cursor-fast-tier.test.ts +248 tests/providers/cursor/cursor-foreground-shell.test.ts +136 tests/providers/cursor/cursor-framing.test.ts +80 tests/providers/cursor/cursor-freeform-args.test.ts +220 tests/providers/cursor/cursor-h2-pool-shutdown.test.ts +2725 tests/providers/cursor/cursor-hardening.test.ts +119 tests/providers/cursor/cursor-http1-transport.test.ts +2718 tests/providers/cursor/cursor-images.test.ts +687 tests/providers/cursor/cursor-integration-status.test.ts +171 tests/providers/cursor/cursor-interaction-query.test.ts +91 tests/providers/cursor/cursor-kv-store.test.ts +42 tests/providers/cursor/cursor-live-smoke-gate.test.ts +249 tests/providers/cursor/cursor-live-transport.test.ts +56 tests/providers/cursor/cursor-local-installer.test.ts +605 tests/providers/cursor/cursor-local-models-schema.test.ts +209 tests/providers/cursor/cursor-mcp-manager.test.ts +406 tests/providers/cursor/cursor-mcp-stdio.test.ts +65 tests/providers/cursor/cursor-message-mapper.test.ts +88 tests/providers/cursor/cursor-native-exec-common.test.ts +223 tests/providers/cursor/cursor-native-exec-policy.test.ts +180 tests/providers/cursor/cursor-native-exec-shell.test.ts +358 tests/providers/cursor/cursor-native-exec.test.ts +86 tests/providers/cursor/cursor-native-grep-globs.test.ts +98 tests/providers/cursor/cursor-oauth-shell.test.ts +674 tests/providers/cursor/cursor-oauth.test.ts +53 tests/providers/cursor/cursor-pool.test.ts +72 tests/providers/cursor/cursor-protobuf-events.test.ts +148 tests/providers/cursor/cursor-repetition-breaker.test.ts +149 tests/providers/cursor/cursor-request-builder.test.ts +92 tests/providers/cursor/cursor-request-compat.test.ts +116 tests/providers/cursor/cursor-roster-account-scope.test.ts +78 tests/providers/cursor/cursor-silent-redirect.test.ts +147 tests/providers/cursor/cursor-static-catalog.test.ts +3557 tests/providers/cursor/cursor-stream-health.test.ts +94 tests/providers/cursor/cursor-structured-edit.test.ts +75 tests/providers/cursor/cursor-tool-arg-decoding.test.ts +64 tests/providers/cursor/cursor-tool-choice.test.ts +89 tests/providers/cursor/cursor-tool-continuation.test.ts +95 tests/providers/cursor/cursor-tool-definitions.test.ts +3994 tests/providers/cursor/cursor-tool-finalize-race.test.ts +126 tests/providers/cursor/cursor-tool-result-image.test.ts +300 tests/providers/cursor/cursor-tool-result-invocation.test.ts +111 tests/providers/cursor/cursor-tool-suspended-checkpoint.test.ts +154 tests/providers/cursor/cursor-tool-wording.test.ts +106 tests/providers/cursor/cursor-toolresult-normalize.test.ts +1907 tests/providers/cursor/cursor-transport-retry.test.ts +79 tests/providers/cursor/cursor-ultra-mode.test.ts +74 tests/providers/cursor/cursor-umbrella-rows.test.ts +41 tests/providers/cursor/cursor-uncallable-quarantine.test.ts +75 tests/providers/cursor/cursor-vision-wire-harness.test.ts +195 tests/providers/cyber-policy-error-fidelity.test.ts +160 tests/providers/deepinfra-provider.test.ts +57 tests/providers/deepseek-artifact-tool-schema.test.ts +184 tests/providers/deepseek-bare-tool-call-replay.test.ts +4304 tests/providers/deepseek-image-files.test.ts +474 tests/providers/deepseek-inbound-wire.test.ts +111 tests/providers/deepseek-quota-currency.test.ts +177 tests/providers/deepseek-reasoning-replay-gaps.test.ts +130 tests/providers/deepseek-reasoning-replay.test.ts +430 tests/providers/deepseek-responses-item-id-repair.test.ts +2119 tests/providers/devin-adapter-reset-wait.test.ts +159 tests/providers/devin-adapter.test.ts +218 tests/providers/devin-anthropic-signature-fallback.test.ts +194 tests/providers/devin-chat-wire-fixes.test.ts +61 tests/providers/devin-cli-authmode-migration.test.ts +103 tests/providers/devin-effort-ladder.test.ts +160 tests/providers/devin-family-resolution.test.ts +118 tests/providers/devin-hardening.test.ts +86 tests/providers/devin-image-passthrough.test.ts +127 tests/providers/devin-live-models.test.ts +101 tests/providers/devin-login.test.ts +113 tests/providers/devin-output-budget.test.ts +127 tests/providers/devin-prompt-cache.test.ts +67 tests/providers/devin-provider-merge-migration.test.ts +154 tests/providers/devin-quota.test.ts +99 tests/providers/devin-reasoning-continuation.test.ts +45 tests/providers/devin-stated-reset-hardening.test.ts +85 tests/providers/devin-stated-reset-retry.test.ts +112 tests/providers/devin-stream-deadline.test.ts +55 tests/providers/devin-trajectory.test.ts +154 tests/providers/digitalocean-scaleway-provider.test.ts +621 tests/providers/dsh-account.test.ts +150 tests/providers/exa-web-search.test.ts +294 tests/providers/explicit-key-pause-oauth-boundary.test.ts +99 tests/providers/fast-row-ingress.test.ts +174 tests/providers/featherless-provider.test.ts +136 tests/providers/flash-route-image-modalities.test.ts +711 tests/providers/forward-admission-separation.test.ts +76 tests/providers/free-directory-runcrate.test.ts +1174 tests/providers/github-copilot/github-copilot-account-origin.test.ts +1285 tests/providers/github-copilot/github-copilot-auto-runtime.test.ts +99 tests/providers/github-copilot/github-copilot-auto.test.ts +117 tests/providers/github-copilot/github-copilot-catalog-hints.test.ts +118 tests/providers/github-copilot/github-copilot-context-tier.test.ts +16078 tests/providers/github-copilot/github-copilot-oauth.test.ts +51 tests/providers/github-copilot/github-copilot-sse-rewrite.test.ts +440 tests/providers/github-copilot/github-copilot-stream-contract.test.ts +384 tests/providers/github-copilot/github-copilot-wire-defaults.test.ts +1169 tests/providers/gpt61-terra-provider-rows.test.ts +57 tests/providers/haiku-5-5-catalog.test.ts +112 tests/providers/hyperbolic-provider.test.ts +539 tests/providers/initial-model-selection.test.ts +481 tests/providers/initial-selection-write-fence.test.ts +146 tests/providers/jev-provider.test.ts +143 tests/providers/kimi-oauth-identity.test.ts +128 tests/providers/kimi-responses-adjacency.test.ts +70 tests/providers/kiro/kiro-account-load.test.ts +145 tests/providers/kiro/kiro-account-quota.test.ts +3980 tests/providers/kiro/kiro-account-state-disk.test.ts +664 tests/providers/kiro/kiro-account-state-imports.test.ts +241 tests/providers/kiro/kiro-adapter.test.ts +247 tests/providers/kiro/kiro-auth-context-continuation.test.ts +101 tests/providers/kiro/kiro-auto-selection.test.ts +98 tests/providers/kiro/kiro-builder-id-profile.test.ts +58 tests/providers/kiro/kiro-calibration.test.ts +125 tests/providers/kiro/kiro-completion-with-real-tools.test.ts +101 tests/providers/kiro/kiro-device-builder.test.ts +193 tests/providers/kiro/kiro-device-iam.test.ts +255 tests/providers/kiro/kiro-device-social.test.ts +112 tests/providers/kiro/kiro-fallback-error-body.test.ts +2948 tests/providers/kiro/kiro-images.test.ts +1310 tests/providers/kiro/kiro-leased-responses.test.ts +54 tests/providers/kiro/kiro-metering-events.test.ts +97 tests/providers/kiro/kiro-metering-usage.test.ts +195 tests/providers/kiro/kiro-model-catalog.test.ts +138 tests/providers/kiro/kiro-model-preference.test.ts +267 tests/providers/kiro/kiro-oauth.test.ts +330 tests/providers/kiro/kiro-org-user-identity.test.ts +408 tests/providers/kiro/kiro-pool-load-settings.test.ts 153 tests/providers/kiro/kiro-pool-rank.test.ts -129 tests/providers/kiro/kiro-quota-metrics.test.ts -101 tests/providers/kiro/kiro-reasoning-roundtrip.test.ts -1569 tests/providers/kiro/kiro-refusal-failover.test.ts -85 tests/providers/kiro/kiro-refusal.test.ts -76 tests/providers/kiro/kiro-remote-image.test.ts -596 tests/providers/kiro/kiro-retry.test.ts -142 tests/providers/kiro/kiro-review-regressions.test.ts -85 tests/providers/kiro/kiro-single-final.test.ts -263 tests/providers/kiro/kiro-stream.test.ts -536 tests/providers/kiro/kiro-transport-parity.test.ts -74 tests/providers/kiro/kiro-usage-quota.test.ts -149 tests/providers/kiro/kiro-usage-restart.test.ts -56 tests/providers/kiro/kiro-windows-cli-db-path.test.ts -59 tests/providers/kiro/kiro-windows-cli-executable-path.test.ts -123 tests/providers/kiro/kiro-wire-estimate.test.ts -117 tests/providers/meta-model-api-provider.test.ts -161 tests/providers/meta-muse-device.test.ts -5225 tests/providers/meta-muse-keychain.test.ts -73 tests/providers/meta-muse-login-order.test.ts +165 tests/providers/kiro/kiro-quota-metrics.test.ts +108 tests/providers/kiro/kiro-reasoning-roundtrip.test.ts +1546 tests/providers/kiro/kiro-refusal-failover.test.ts +169 tests/providers/kiro/kiro-refusal.test.ts +85 tests/providers/kiro/kiro-remote-image.test.ts +562 tests/providers/kiro/kiro-retry.test.ts +202 tests/providers/kiro/kiro-review-regressions.test.ts +137 tests/providers/kiro/kiro-single-final.test.ts +273 tests/providers/kiro/kiro-stream.test.ts +557 tests/providers/kiro/kiro-transport-parity.test.ts +95 tests/providers/kiro/kiro-usage-quota.test.ts +107 tests/providers/kiro/kiro-usage-restart.test.ts +49 tests/providers/kiro/kiro-windows-cli-db-path.test.ts +43 tests/providers/kiro/kiro-windows-cli-executable-path.test.ts +74 tests/providers/kiro/kiro-wire-estimate.test.ts +125 tests/providers/meta-model-api-provider.test.ts +103 tests/providers/meta-muse-device.test.ts +5209 tests/providers/meta-muse-keychain.test.ts +86 tests/providers/meta-muse-login-order.test.ts 154 tests/providers/meta-muse-oauth.test.ts -157 tests/providers/meta-muse-wonder.test.ts -67 tests/providers/mimo-effort.test.ts -183 tests/providers/mimo-free-provider.test.ts -229 tests/providers/mimo-token-plan-capacity.test.ts -131 tests/providers/mimo-token-plan-provider.test.ts -131 tests/providers/mimo-v26-catalog.test.ts -446 tests/providers/minimax-clients.test.ts -1415 tests/providers/minimax-combo-image-input.test.ts -145 tests/providers/minimax-quota.test.ts -122 tests/providers/minimax-reasoning-split.test.ts -574 tests/providers/mistral-recovery.test.ts -48 tests/providers/model-presets.test.ts -177 tests/providers/model-rename-migration.test.ts -82 tests/providers/model-roster-seed-repair.test.ts -146 tests/providers/modelflare-provider.test.ts -40 tests/providers/moonshot-developer-role.test.ts -36 tests/providers/moonshot-endpoints.test.ts -324 tests/providers/moonshot-tool-schema.test.ts -43 tests/providers/muse-key-quota.test.ts -1004 tests/providers/muse-passive-quota-cache.test.ts -130 tests/providers/muse-passive-quota-observation.test.ts -109 tests/providers/muse-spark-web-search-compat.test.ts -52 tests/providers/muse-subscription-usage.test.ts -117 tests/providers/muse-tool-name-alias.test.ts -214 tests/providers/new-model-policy-runtime.test.ts -40 tests/providers/new-model-policy.test.ts -74 tests/providers/nous-oauth-live.test.ts -8207 tests/providers/nous-oauth.test.ts -104 tests/providers/novita-provider.test.ts -167 tests/providers/nscale-vultr-provider.test.ts -122 tests/providers/nvidia-nim-hardening.test.ts -441 tests/providers/ollama/ollama-native-parser.test.ts -113 tests/providers/ollama/ollama-native-reasoning-wire.test.ts -67 tests/providers/ollama/ollama-native-scaling.test.ts -41 tests/providers/ollama/ollama-native-structured-output.test.ts -227 tests/providers/ollama/ollama-native-tool-continuations.test.ts -410 tests/providers/ollama/ollama-native-v4.test.ts -104 tests/providers/ollama/ollama-native.test.ts -603 tests/providers/ollama/ollama-show-enrichment-v7.test.ts -112 tests/providers/ollama/ollama-show-enrichment.test.ts -299 tests/providers/ollama/ollama-show-ignore-abort.test.ts -354 tests/providers/opencode-cli.test.ts +139 tests/providers/meta-muse-wonder.test.ts +63 tests/providers/mimo-effort.test.ts +187 tests/providers/mimo-free-provider.test.ts +125 tests/providers/mimo-token-plan-capacity.test.ts +116 tests/providers/mimo-token-plan-provider.test.ts +162 tests/providers/mimo-v26-catalog.test.ts +447 tests/providers/minimax-clients.test.ts +1661 tests/providers/minimax-combo-image-input.test.ts +74 tests/providers/minimax-quota.test.ts +166 tests/providers/minimax-reasoning-split.test.ts +484 tests/providers/mistral-recovery.test.ts +49 tests/providers/model-presets.test.ts +191 tests/providers/model-rename-migration.test.ts +104 tests/providers/model-roster-seed-repair.test.ts +152 tests/providers/modelflare-provider.test.ts +52 tests/providers/moonshot-developer-role.test.ts +48 tests/providers/moonshot-endpoints.test.ts +390 tests/providers/moonshot-tool-schema.test.ts +48 tests/providers/muse-key-quota.test.ts +962 tests/providers/muse-passive-quota-cache.test.ts +112 tests/providers/muse-passive-quota-observation.test.ts +114 tests/providers/muse-spark-web-search-compat.test.ts +49 tests/providers/muse-subscription-usage.test.ts +120 tests/providers/muse-tool-name-alias.test.ts +197 tests/providers/new-model-policy-runtime.test.ts +43 tests/providers/new-model-policy.test.ts +73 tests/providers/nous-oauth-live.test.ts +8256 tests/providers/nous-oauth.test.ts +133 tests/providers/novita-provider.test.ts +175 tests/providers/nscale-vultr-provider.test.ts +167 tests/providers/nvidia-nim-hardening.test.ts +476 tests/providers/ollama/ollama-native-parser.test.ts +116 tests/providers/ollama/ollama-native-reasoning-wire.test.ts +68 tests/providers/ollama/ollama-native-scaling.test.ts +53 tests/providers/ollama/ollama-native-structured-output.test.ts +214 tests/providers/ollama/ollama-native-tool-continuations.test.ts +377 tests/providers/ollama/ollama-native-v4.test.ts +147 tests/providers/ollama/ollama-native.test.ts +463 tests/providers/ollama/ollama-show-enrichment-v7.test.ts +134 tests/providers/ollama/ollama-show-enrichment.test.ts +306 tests/providers/ollama/ollama-show-ignore-abort.test.ts +252 tests/providers/opencode-cli.test.ts 91 tests/providers/opencode-go-deepseek.test.ts -420 tests/providers/opencode-go-gemini-wire.test.ts -185 tests/providers/opencode-go-grok46-responses.test.ts -581 tests/providers/opencode-go-luna-wire.test.ts -677 tests/providers/opencode-go-model-protocols.test.ts -91 tests/providers/opencode-go-muse-context.test.ts -87 tests/providers/opencode-go-muse-vision.test.ts -111 tests/providers/opencode-go-quota.test.ts -1472 tests/providers/opencode-go-session-header.test.ts -627 tests/providers/opencode-management-transport.test.ts -41 tests/providers/opencode-muse-terminal-repair.test.ts -77 tests/providers/opencode-zen-deepseek-reasoning.test.ts -366 tests/providers/opencode-zen-gemini-wire.test.ts -51 tests/providers/opencode-zen-rate-limit.test.ts -40 tests/providers/opengateway-key-validation.test.ts -174 tests/providers/opengateway-provider.test.ts -118 tests/providers/openrouter-provider-routing.test.ts -79 tests/providers/openrouter-quota-reset-cooldown-4024.test.ts -241 tests/providers/opper-provider.test.ts -199 tests/providers/orcarouter-provider.test.ts -127 tests/providers/provider-account-quota-failure-reasons.test.ts -4506 tests/providers/provider-account-quota-persistence.test.ts -403 tests/providers/provider-account-quota.test.ts -70 tests/providers/provider-anthropic-instance-quota.test.ts -90 tests/providers/provider-anthropic-instance.test.ts -79 tests/providers/provider-anthropic-usage-windows.test.ts -79 tests/providers/provider-antigravity-effort-families.test.ts -225 tests/providers/provider-antigravity-family-catalog.test.ts -133 tests/providers/provider-antigravity-model-quota.test.ts -72 tests/providers/provider-antigravity-quota-retry.test.ts -2455 tests/providers/provider-antigravity-wire-snapshot.test.ts -657 tests/providers/provider-api-keys.test.ts -48 tests/providers/provider-capacity.test.ts -763 tests/providers/provider-completion-test-authority.test.ts -450 tests/providers/provider-completion-test-ingress.test.ts -341 tests/providers/provider-completion-test.test.ts -323 tests/providers/provider-config-batch-management.test.ts -53 tests/providers/provider-config-validation.test.ts -402 tests/providers/provider-connection-test.test.ts -77 tests/providers/provider-cost-overlay-config.test.ts -48 tests/providers/provider-discovery-log-suppression.test.ts -47 tests/providers/provider-egress-outbound.test.ts -49 tests/providers/provider-id-rewrite.test.ts -256 tests/providers/provider-input-modalities.test.ts -410 tests/providers/provider-key-store.test.ts -118 tests/providers/provider-live-models.test.ts -164 tests/providers/provider-model-aliases.test.ts -182 tests/providers/provider-model-discovery-contract.test.ts -61 tests/providers/provider-outbound-private-network.test.ts -462 tests/providers/provider-outbound.test.ts -83 tests/providers/provider-quota-abliteration.test.ts -88 tests/providers/provider-quota-label-sanitize.test.ts -137 tests/providers/provider-quota-observed-marker.test.ts -93 tests/providers/provider-quota-ollama-cloud.test.ts -772 tests/providers/provider-quota.test.ts -383 tests/providers/provider-registry-parity.test.ts -39 tests/providers/provider-runtime-fetch.test.ts -101 tests/providers/provider-static-model-discovery.test.ts -515 tests/providers/provider-tls-profile.test.ts -317 tests/providers/qoder-adapter.test.ts -1193 tests/providers/qoder-cn-image-validation.test.ts -65 tests/providers/qoder-image-input.test.ts -158 tests/providers/qoder-live-models.test.ts -165 tests/providers/qoder-mcp-server.test.ts -157 tests/providers/qoder-scaffold-guard.test.ts +423 tests/providers/opencode-go-gemini-wire.test.ts +159 tests/providers/opencode-go-grok46-responses.test.ts +496 tests/providers/opencode-go-luna-wire.test.ts +386 tests/providers/opencode-go-model-protocols.test.ts +90 tests/providers/opencode-go-muse-context.test.ts +88 tests/providers/opencode-go-muse-vision.test.ts +103 tests/providers/opencode-go-quota.test.ts +1747 tests/providers/opencode-go-session-header.test.ts +568 tests/providers/opencode-management-transport.test.ts +56 tests/providers/opencode-muse-terminal-repair.test.ts +122 tests/providers/opencode-zen-deepseek-reasoning.test.ts +401 tests/providers/opencode-zen-gemini-wire.test.ts +79 tests/providers/opencode-zen-rate-limit.test.ts +59 tests/providers/opengateway-key-validation.test.ts +188 tests/providers/opengateway-provider.test.ts +109 tests/providers/openrouter-provider-routing.test.ts +122 tests/providers/openrouter-quota-reset-cooldown-4024.test.ts +160 tests/providers/opper-provider.test.ts +161 tests/providers/orcarouter-provider.test.ts +162 tests/providers/provider-account-quota-failure-reasons.test.ts +4521 tests/providers/provider-account-quota-persistence.test.ts +511 tests/providers/provider-account-quota.test.ts +79 tests/providers/provider-anthropic-instance-quota.test.ts +91 tests/providers/provider-anthropic-instance.test.ts +108 tests/providers/provider-anthropic-usage-windows.test.ts +42 tests/providers/provider-antigravity-effort-families.test.ts +157 tests/providers/provider-antigravity-family-catalog.test.ts +110 tests/providers/provider-antigravity-model-quota.test.ts +84 tests/providers/provider-antigravity-quota-retry.test.ts +3083 tests/providers/provider-antigravity-wire-snapshot.test.ts +826 tests/providers/provider-api-keys.test.ts +51 tests/providers/provider-capacity.test.ts +654 tests/providers/provider-completion-test-authority.test.ts +377 tests/providers/provider-completion-test-ingress.test.ts +380 tests/providers/provider-completion-test.test.ts +412 tests/providers/provider-config-batch-management.test.ts +62 tests/providers/provider-config-validation.test.ts +327 tests/providers/provider-connection-test.test.ts +103 tests/providers/provider-cost-overlay-config.test.ts +42 tests/providers/provider-discovery-log-suppression.test.ts +61 tests/providers/provider-egress-outbound.test.ts +58 tests/providers/provider-id-rewrite.test.ts +192 tests/providers/provider-input-modalities.test.ts +543 tests/providers/provider-key-store.test.ts +132 tests/providers/provider-live-models.test.ts +137 tests/providers/provider-model-aliases.test.ts +214 tests/providers/provider-model-discovery-contract.test.ts +53 tests/providers/provider-outbound-private-network.test.ts +582 tests/providers/provider-outbound.test.ts +102 tests/providers/provider-quota-abliteration.test.ts +182 tests/providers/provider-quota-label-sanitize.test.ts +221 tests/providers/provider-quota-observed-marker.test.ts +118 tests/providers/provider-quota-ollama-cloud.test.ts +643 tests/providers/provider-quota.test.ts +345 tests/providers/provider-registry-parity.test.ts +67 tests/providers/provider-runtime-fetch.test.ts +107 tests/providers/provider-static-model-discovery.test.ts +66 tests/providers/provider-tls-profile.test.ts +307 tests/providers/qoder-adapter.test.ts +1359 tests/providers/qoder-cn-image-validation.test.ts +78 tests/providers/qoder-image-input.test.ts +118 tests/providers/qoder-live-models.test.ts +211 tests/providers/qoder-mcp-server.test.ts +91 tests/providers/qoder-scaffold-guard.test.ts 59 tests/providers/qwen38-preserve-reasoning.test.ts -286 tests/providers/rate-limit-retry.test.ts -90 tests/providers/registry-transport-alias.test.ts -248 tests/providers/resolved-model-policy.test.ts -178 tests/providers/sambanova-nebius-provider.test.ts -191 tests/providers/sponsor-presets.test.ts -219 tests/providers/stepfun-provider.test.ts -286 tests/providers/tokenlab-protocols.test.ts -127 tests/providers/tokenlab-provider.test.ts -165 tests/providers/umans-provider.test.ts -7583 tests/providers/upstream-transient-retry.test.ts -79 tests/providers/vercel-gateway-provider-routing.test.ts -86 tests/providers/vision-classification-seed-repair.test.ts -77 tests/providers/volcengine-ark-assistant-content.test.ts -491 tests/providers/workbuddy-provider.test.ts -116 tests/providers/workbuddy-quota.test.ts -39 tests/providers/xai/grok-47-build-fast-metadata.test.ts -6418 tests/providers/xai/grok-47-fast-model-wire.test.ts -184 tests/providers/xai/grok-47-fast-model.test.ts -147 tests/providers/xai/grok-attribution.test.ts -242 tests/providers/xai/grok-config-inject.test.ts -108 tests/providers/xai/grok-config-write-lock.test.ts -603 tests/providers/xai/grok-coupon-claim.test.ts -93 tests/providers/xai/grok-coupon-reconcile.test.ts -164 tests/providers/xai/grok-effort-inject.test.ts -121 tests/providers/xai/grok-lifecycle.test.ts -1003 tests/providers/xai/grok-management-api.test.ts -580 tests/providers/xai/grok-models-effort-list.test.ts -494 tests/providers/xai/grok-orphan-adoption.test.ts -76 tests/providers/xai/grok-reset-coupon-cli.test.ts -93 tests/providers/xai/grok-reset-coupons.test.ts -144 tests/providers/xai/grok-selection.test.ts -332 tests/providers/xai/grok-session-identity.test.ts -119 tests/providers/xai/grok-status.test.ts -151 tests/providers/xai/grok-sync.test.ts -183 tests/providers/xai/grok-writer-boundary.test.ts -96 tests/providers/xai/xai-additional-tools.test.ts -104 tests/providers/xai/xai-empty-catalog-tool-choice.test.ts -441 tests/providers/xai/xai-loaded-tool-provenance.test.ts -91 tests/providers/xai/xai-no-stop.test.ts -65 tests/providers/xai/xai-oauth-retry.test.ts -253 tests/providers/xai/xai-refresh-lock.test.ts -119 tests/providers/xai/xai-replay-provenance.test.ts -122 tests/providers/xai/xai-responses-adjacency.test.ts -97 tests/providers/xai/xai-tool-schema.test.ts -160 tests/providers/xai/xai-transport.test.ts -116 tests/providers/xai/xai-web-search-compat.test.ts -104 tests/providers/xai/xai-web-search.test.ts -73 tests/providers/zai-reasoning-replay.test.ts -527 tests/providers/zcode-client.test.ts -167 tests/providers/zed-argument-consistency.test.ts -91 tests/providers/zed-failure-relay.test.ts -287 tests/providers/zed-hosted-provider.test.ts -409 tests/providers/zed-lossless-arguments.test.ts -147 tests/providers/zed-openai-contract.test.ts -101 tests/providers/zed-retained-budget.test.ts -80 tests/providers/zhipu-bigmodel-provider.test.ts -78 tests/providers/zhipu-bigmodel-responses-quota.test.ts -748 tests/responses/agent-assertion-routes.test.ts -769 tests/responses/anthropic2-responses-parity.test.ts -63 tests/responses/apply-patch-envelope.test.ts -115 tests/responses/bare-echo-alias.test.ts -585 tests/responses/chat-anthropic-reasoning-details.test.ts -422 tests/responses/chat-completions-deferred-tools.test.ts -13784 tests/responses/chat-completions-endpoint.test.ts -724 tests/responses/chat-completions-pool-mode.test.ts -5474 tests/responses/chat-conversation-affinity.test.ts -345 tests/responses/chat-inbound-developer-position.test.ts -52 tests/responses/chat-inbound-reasoning-none.test.ts -164 tests/responses/chat-inbound-reasoning-replay.test.ts -423 tests/responses/chat-incomplete-length-reason.test.ts -105 tests/responses/chat-inline-document-bytes.test.ts -454 tests/responses/chat-json-sse-fallback.test.ts -1428 tests/responses/chat-legacy-functions-combo.test.ts -346 tests/responses/chat-media-translation.test.ts -3690 tests/responses/chat-native-combo.test.ts -235 tests/responses/chat-native-decline-reason.test.ts -672 tests/responses/chat-native-developer-role.test.ts -136 tests/responses/chat-native-image-normalization.test.ts -58 tests/responses/chat-native-lenient-finish.test.ts -1644 tests/responses/chat-native-reasoning-replay.test.ts -121 tests/responses/chat-native-reasoning-scope.test.ts -19521 tests/responses/chat-native-spend.test.ts -295 tests/responses/chat-native-sse-stall.test.ts -1400 tests/responses/chat-raw-reasoning-delivery.test.ts -38 tests/responses/chat-refusal-scope.test.ts -235 tests/responses/chat-refusal.test.ts -1661 tests/responses/chat-request-id-endpoint.test.ts -825 tests/responses/chat-responses-control-integration.test.ts -140 tests/responses/chat-responses-control-scope.test.ts -406 tests/responses/chat-sse-framing-guard.test.ts -86 tests/responses/chat-tool-choice-allowed-tools.test.ts -80 tests/responses/citation-markers.test.ts -1968 tests/responses/codex-0164-request-compat.test.ts -297 tests/responses/codex-installation-compact-empty.test.ts -449 tests/responses/codex-installation-failover.test.ts -345 tests/responses/codex-installation-turn-limit.test.ts -2098 tests/responses/codex-ws-handshake-validation.test.ts -123 tests/responses/codex-ws-handshake.test.ts -106 tests/responses/codex-ws-pool-contention.test.ts -1124 tests/responses/combo-replay-refusal-attribution.test.ts -673 tests/responses/compact-key-selection.test.ts -11289 tests/responses/compact-transient-alternate.test.ts -144 tests/responses/compaction-continuation-note.test.ts -328 tests/responses/compaction-continuation-wire.test.ts -144 tests/responses/compaction-event-ownership.test.ts -233 tests/responses/compaction-history-framing.test.ts -229 tests/responses/compaction-portable-history.test.ts -78 tests/responses/compaction-progress.test.ts -92 tests/responses/continuation-dedup.test.ts -58 tests/responses/custom-tool-compat.test.ts -325 tests/responses/direct-credit-renewal-ingress.test.ts -1435 tests/responses/droid-reasoning-defaults.test.ts -805 tests/responses/empty-completion-core.test.ts -53 tests/responses/empty-completion-guard.test.ts -1219 tests/responses/empty-completion-hardening.test.ts -47 tests/responses/eventstream-decoder.test.ts -119 tests/responses/eventstream-fragmentation.test.ts -1038 tests/responses/explicit-empty-tool-catalog-history.test.ts -2007 tests/responses/explicit-empty-tool-catalog.test.ts -161 tests/responses/external-task-input-repair.test.ts -37 tests/responses/fix-eventstream-cancel-wait.test.ts -168 tests/responses/fresh-connection-optout.test.ts -97 tests/responses/graceful-max-output-tokens-exclusions.test.ts -461 tests/responses/graceful-max-output-tokens.test.ts -2705 tests/responses/incomplete-reason-normalization.test.ts -986 tests/responses/jev-initial-effort-wire.test.ts -85 tests/responses/legacy-shell-compat.test.ts -411 tests/responses/local-upstream-deadlines.test.ts -251 tests/responses/messages-native-bridge-policy.test.ts -199 tests/responses/messages-native-eligibility.test.ts -155 tests/responses/messages-native-oauth-eligibility.test.ts -57 tests/responses/namespace-tool-compat.test.ts -402 tests/responses/native-compaction-gateway-credentials.test.ts -814 tests/responses/native-compaction-gateway-policy.test.ts -4017 tests/responses/native-compaction-gateway.test.ts -255 tests/responses/native-compaction-oauth.test.ts -1373 tests/responses/native-compaction-provenance.test.ts -145 tests/responses/opaque-blob-wrapped-rejection.test.ts -538 tests/responses/openai-responses-passthrough.test.ts -200 tests/responses/openai-responses-summary-none.test.ts -166 tests/responses/opengateway-completion-receipts.test.ts -162 tests/responses/parser-content-audio.test.ts -242 tests/responses/passthrough-abort.test.ts -3003 tests/responses/passthrough-deferred-tools.test.ts -87 tests/responses/passthrough-grok-upstream-envelope-echo.test.ts -166 tests/responses/passthrough-headers.test.ts -167 tests/responses/passthrough-media-type.test.ts -84 tests/responses/passthrough-override.test.ts -100 tests/responses/plaintext-v2-agent-messages.test.ts -824 tests/responses/protocol-antigravity-direct-chat.test.ts -252 tests/responses/protocol-antigravity-direct-eligibility.test.ts -439 tests/responses/protocol-antigravity-direct-messages.test.ts -1652 tests/responses/protocol-argon-thought-boundary.test.ts -45 tests/responses/protocol-baseline.test.ts -78 tests/responses/protocol-chat-ir-parity.test.ts -58 tests/responses/protocol-contract.test.ts -123 tests/responses/protocol-direct-encoders-chat.test.ts -67 tests/responses/protocol-direct-encoders-local-upstream.test.ts -82 tests/responses/protocol-direct-encoders-messages.test.ts -45 tests/responses/protocol-direct-encoders-stall-disabled.test.ts -63 tests/responses/protocol-dto.test.ts -72 tests/responses/protocol-envelope.test.ts -41 tests/responses/protocol-features.test.ts -41 tests/responses/protocol-guard.test.ts -216 tests/responses/protocol-ingress-guard.test.ts -112 tests/responses/protocol-messages-ir-parity.test.ts -50 tests/responses/protocol-opaque-state.test.ts +200 tests/providers/rate-limit-retry.test.ts +103 tests/providers/registry-transport-alias.test.ts +126 tests/providers/resolved-model-policy.test.ts +153 tests/providers/sambanova-nebius-provider.test.ts +167 tests/providers/sponsor-presets.test.ts +161 tests/providers/stepfun-provider.test.ts +297 tests/providers/tokenlab-protocols.test.ts +220 tests/providers/tokenlab-provider.test.ts +98 tests/providers/umans-provider.test.ts +7353 tests/providers/upstream-transient-retry.test.ts +108 tests/providers/vercel-gateway-provider-routing.test.ts +133 tests/providers/vision-classification-seed-repair.test.ts +48 tests/providers/volcengine-ark-assistant-content.test.ts +417 tests/providers/workbuddy-provider.test.ts +204 tests/providers/workbuddy-quota.test.ts +52 tests/providers/xai/grok-47-build-fast-metadata.test.ts +6091 tests/providers/xai/grok-47-fast-model-wire.test.ts +114 tests/providers/xai/grok-47-fast-model.test.ts +154 tests/providers/xai/grok-attribution.test.ts +289 tests/providers/xai/grok-config-inject.test.ts +116 tests/providers/xai/grok-config-write-lock.test.ts +456 tests/providers/xai/grok-coupon-claim.test.ts +130 tests/providers/xai/grok-coupon-reconcile.test.ts +219 tests/providers/xai/grok-effort-inject.test.ts +133 tests/providers/xai/grok-lifecycle.test.ts +865 tests/providers/xai/grok-management-api.test.ts +725 tests/providers/xai/grok-models-effort-list.test.ts +336 tests/providers/xai/grok-orphan-adoption.test.ts +96 tests/providers/xai/grok-reset-coupon-cli.test.ts +74 tests/providers/xai/grok-reset-coupons.test.ts +115 tests/providers/xai/grok-selection.test.ts +175 tests/providers/xai/grok-session-identity.test.ts +126 tests/providers/xai/grok-status.test.ts +168 tests/providers/xai/grok-sync.test.ts +135 tests/providers/xai/grok-writer-boundary.test.ts +117 tests/providers/xai/xai-additional-tools.test.ts +94 tests/providers/xai/xai-empty-catalog-tool-choice.test.ts +249 tests/providers/xai/xai-loaded-tool-provenance.test.ts +105 tests/providers/xai/xai-no-stop.test.ts +61 tests/providers/xai/xai-oauth-retry.test.ts +191 tests/providers/xai/xai-refresh-lock.test.ts +112 tests/providers/xai/xai-replay-provenance.test.ts +126 tests/providers/xai/xai-responses-adjacency.test.ts +84 tests/providers/xai/xai-tool-schema.test.ts +144 tests/providers/xai/xai-transport.test.ts +113 tests/providers/xai/xai-web-search-compat.test.ts +127 tests/providers/xai/xai-web-search.test.ts +143 tests/providers/zai-reasoning-replay.test.ts +572 tests/providers/zcode-client.test.ts +113 tests/providers/zed-argument-consistency.test.ts +175 tests/providers/zed-failure-relay.test.ts +332 tests/providers/zed-hosted-provider.test.ts +479 tests/providers/zed-lossless-arguments.test.ts +280 tests/providers/zed-openai-contract.test.ts +167 tests/providers/zed-retained-budget.test.ts +108 tests/providers/zhipu-bigmodel-provider.test.ts +72 tests/providers/zhipu-bigmodel-responses-quota.test.ts +747 tests/responses/agent-assertion-routes.test.ts +717 tests/responses/anthropic2-responses-parity.test.ts +59 tests/responses/apply-patch-envelope.test.ts +178 tests/responses/bare-echo-alias.test.ts +546 tests/responses/chat-anthropic-reasoning-details.test.ts +430 tests/responses/chat-completions-deferred-tools.test.ts +13353 tests/responses/chat-completions-endpoint.test.ts +631 tests/responses/chat-completions-pool-mode.test.ts +4823 tests/responses/chat-conversation-affinity.test.ts +256 tests/responses/chat-inbound-developer-position.test.ts +65 tests/responses/chat-inbound-reasoning-none.test.ts +100 tests/responses/chat-inbound-reasoning-replay.test.ts +406 tests/responses/chat-incomplete-length-reason.test.ts +119 tests/responses/chat-inline-document-bytes.test.ts +477 tests/responses/chat-json-sse-fallback.test.ts +1347 tests/responses/chat-legacy-functions-combo.test.ts +395 tests/responses/chat-media-translation.test.ts +3115 tests/responses/chat-native-combo.test.ts +118 tests/responses/chat-native-decline-reason.test.ts +723 tests/responses/chat-native-developer-role.test.ts +157 tests/responses/chat-native-image-normalization.test.ts +45 tests/responses/chat-native-lenient-finish.test.ts +1374 tests/responses/chat-native-reasoning-replay.test.ts +108 tests/responses/chat-native-reasoning-scope.test.ts +18542 tests/responses/chat-native-spend.test.ts +300 tests/responses/chat-native-sse-stall.test.ts +1640 tests/responses/chat-raw-reasoning-delivery.test.ts +45 tests/responses/chat-refusal-scope.test.ts +503 tests/responses/chat-refusal.test.ts +1091 tests/responses/chat-request-id-endpoint.test.ts +531 tests/responses/chat-responses-control-integration.test.ts +107 tests/responses/chat-responses-control-scope.test.ts +353 tests/responses/chat-sse-framing-guard.test.ts +69 tests/responses/chat-tool-choice-allowed-tools.test.ts +56 tests/responses/citation-markers.test.ts +2345 tests/responses/codex-0164-request-compat.test.ts +327 tests/responses/codex-installation-compact-empty.test.ts +469 tests/responses/codex-installation-failover.test.ts +263 tests/responses/codex-installation-turn-limit.test.ts +2074 tests/responses/codex-ws-handshake-validation.test.ts +83 tests/responses/codex-ws-handshake.test.ts +53 tests/responses/codex-ws-pool-contention.test.ts +756 tests/responses/combo-replay-refusal-attribution.test.ts +527 tests/responses/compact-key-selection.test.ts +11324 tests/responses/compact-transient-alternate.test.ts +117 tests/responses/compaction-continuation-note.test.ts +283 tests/responses/compaction-continuation-wire.test.ts +126 tests/responses/compaction-event-ownership.test.ts +218 tests/responses/compaction-history-framing.test.ts +222 tests/responses/compaction-portable-history.test.ts +138 tests/responses/compaction-progress.test.ts +76 tests/responses/continuation-dedup.test.ts +67 tests/responses/custom-tool-compat.test.ts +424 tests/responses/direct-credit-renewal-ingress.test.ts +1171 tests/responses/droid-reasoning-defaults.test.ts +759 tests/responses/empty-completion-core.test.ts +63 tests/responses/empty-completion-guard.test.ts +1192 tests/responses/empty-completion-hardening.test.ts +104 tests/responses/eventstream-decoder.test.ts +71 tests/responses/eventstream-fragmentation.test.ts +1042 tests/responses/explicit-empty-tool-catalog-history.test.ts +1789 tests/responses/explicit-empty-tool-catalog.test.ts +224 tests/responses/external-task-input-repair.test.ts +47 tests/responses/fix-eventstream-cancel-wait.test.ts +157 tests/responses/fresh-connection-optout.test.ts +88 tests/responses/graceful-max-output-tokens-exclusions.test.ts +486 tests/responses/graceful-max-output-tokens.test.ts +2074 tests/responses/incomplete-reason-normalization.test.ts +1243 tests/responses/jev-initial-effort-wire.test.ts +45 tests/responses/legacy-shell-compat.test.ts +320 tests/responses/local-upstream-deadlines.test.ts +133 tests/responses/messages-native-bridge-policy.test.ts +166 tests/responses/messages-native-eligibility.test.ts +130 tests/responses/messages-native-oauth-eligibility.test.ts +56 tests/responses/namespace-tool-compat.test.ts +351 tests/responses/native-compaction-gateway-credentials.test.ts +862 tests/responses/native-compaction-gateway-policy.test.ts +4354 tests/responses/native-compaction-gateway.test.ts +230 tests/responses/native-compaction-oauth.test.ts +956 tests/responses/native-compaction-provenance.test.ts +139 tests/responses/opaque-blob-wrapped-rejection.test.ts +348 tests/responses/openai-responses-passthrough.test.ts +231 tests/responses/openai-responses-summary-none.test.ts +137 tests/responses/opengateway-completion-receipts.test.ts +50 tests/responses/parser-content-audio.test.ts +328 tests/responses/passthrough-abort.test.ts +2900 tests/responses/passthrough-deferred-tools.test.ts +73 tests/responses/passthrough-grok-upstream-envelope-echo.test.ts +196 tests/responses/passthrough-headers.test.ts +133 tests/responses/passthrough-media-type.test.ts +99 tests/responses/passthrough-override.test.ts +116 tests/responses/plaintext-v2-agent-messages.test.ts +826 tests/responses/protocol-antigravity-direct-chat.test.ts +116 tests/responses/protocol-antigravity-direct-eligibility.test.ts +490 tests/responses/protocol-antigravity-direct-messages.test.ts +1418 tests/responses/protocol-argon-thought-boundary.test.ts +49 tests/responses/protocol-baseline.test.ts +88 tests/responses/protocol-chat-ir-parity.test.ts +57 tests/responses/protocol-contract.test.ts +133 tests/responses/protocol-direct-encoders-chat.test.ts +62 tests/responses/protocol-direct-encoders-local-upstream.test.ts +104 tests/responses/protocol-direct-encoders-messages.test.ts +57 tests/responses/protocol-direct-encoders-stall-disabled.test.ts +46 tests/responses/protocol-dto.test.ts +58 tests/responses/protocol-envelope.test.ts +56 tests/responses/protocol-features.test.ts +49 tests/responses/protocol-guard.test.ts +224 tests/responses/protocol-ingress-guard.test.ts +174 tests/responses/protocol-messages-ir-parity.test.ts +60 tests/responses/protocol-opaque-state.test.ts 38 tests/responses/protocol-path.test.ts -121 tests/responses/protocol-plan-snapshot.test.ts -49 tests/responses/protocol-plan.test.ts -111 tests/responses/protocol-shadow-plan.test.ts -85 tests/responses/protocol-trace.test.ts -39 tests/responses/provider-egress-fetch.test.ts -551 tests/responses/reasoning-archive-http.test.ts -548 tests/responses/reasoning-archive-ws.test.ts -220 tests/responses/reasoning-effort-summary-default.test.ts -212 tests/responses/reasoning-envelope.test.ts -115 tests/responses/reasoning-retention-quota.test.ts -1371 tests/responses/reasoning-retention-routing.test.ts -633 tests/responses/reasoning-retention-v2.test.ts -71 tests/responses/reasoning-retention.test.ts -618 tests/responses/refreshed-upstream-deadlines.test.ts -127 tests/responses/reserve-dispatch-ws.test.ts -92 tests/responses/responses-4546-incident-regression.test.ts -637 tests/responses/responses-account-auto-pause-wire-owner.test.ts -976 tests/responses/responses-account-auto-pause.test.ts -94 tests/responses/responses-account-change-scrub.test.ts -2784 tests/responses/responses-account-label.test.ts -572 tests/responses/responses-alternate-main-cancellation.test.ts -422 tests/responses/responses-anthropic-billing-send-budget.test.ts -377 tests/responses/responses-anthropic-compaction-prefix.test.ts -339 tests/responses/responses-anthropic-fast-downgrade.test.ts -185 tests/responses/responses-anthropic-legal-history.test.ts -144 tests/responses/responses-anthropic-thinking-recovery.test.ts -973 tests/responses/responses-anthropic-thinking-signature-recovery.test.ts -300 tests/responses/responses-auto-pause-replay-owner.test.ts -276 tests/responses/responses-azure-opaque-blob-recovery.test.ts -131 tests/responses/responses-bare-echo-helper-fence.test.ts -58 tests/responses/responses-call-id-linkage.test.ts -645 tests/responses/responses-canonical-nonstream.test.ts -92 tests/responses/responses-canonical-only-top-level-fields.test.ts -210 tests/responses/responses-chat-tool-call-content.test.ts -100 tests/responses/responses-chatgpt-web-replay-metadata.test.ts -159 tests/responses/responses-claude-preflight-lease.test.ts -50 tests/responses/responses-code-mode-goal-helpers.test.ts -121 tests/responses/responses-code-mode-mcp-direct.test.ts -52 tests/responses/responses-code-mode-patch-compile.test.ts -74 tests/responses/responses-code-mode-shell-compile.test.ts -2831 tests/responses/responses-cold-opaque-recovery.test.ts -232 tests/responses/responses-combo-bridge-usage.test.ts -565 tests/responses/responses-combo-exhausted-error.test.ts -277 tests/responses/responses-combo-fallback-off.test.ts -213 tests/responses/responses-combo-replay-principal.test.ts -621 tests/responses/responses-combo-run-turn-classified-failure.test.ts -6318 tests/responses/responses-compact-handoff-admission.test.ts -2529 tests/responses/responses-compaction-http-isolation.test.ts -3131 tests/responses/responses-compaction-override.test.ts -172 tests/responses/responses-compaction-policy-identity.test.ts -50 tests/responses/responses-compaction-recovery-policy.test.ts -6779 tests/responses/responses-compaction-recovery.test.ts -4561 tests/responses/responses-compaction-routing.test.ts -216 tests/responses/responses-compaction.test.ts -6000 tests/responses/responses-console-go-upload-retry.test.ts -2866 tests/responses/responses-context-overflow.test.ts -125 tests/responses/responses-continuation-boundaries.test.ts -92 tests/responses/responses-core-modules.test.ts -48 tests/responses/responses-custom-tool-guidance.test.ts -202 tests/responses/responses-custom-tool-historical-replay.test.ts -308 tests/responses/responses-custom-tool-repair-dispatch.test.ts -55 tests/responses/responses-custom-tool-repair.test.ts -108 tests/responses/responses-custom-tool-stream-consistency.test.ts -53 tests/responses/responses-default-namespace-emit-normalize.test.ts -1065 tests/responses/responses-devin-401-replay.test.ts -76 tests/responses/responses-dispatch-receipt.test.ts -298 tests/responses/responses-fetch-helpers-boundary.test.ts -80 tests/responses/responses-field-backfill.test.ts -9886 tests/responses/responses-first-send-reservation.test.ts -233 tests/responses/responses-first-send-spend-policy.test.ts -157 tests/responses/responses-forward-client-headers.test.ts -92 tests/responses/responses-forward-dangling-call.test.ts -368 tests/responses/responses-forward-incomplete-quota.test.ts -95 tests/responses/responses-forward-output-cap.test.ts -96 tests/responses/responses-forward-posit-continuation.test.ts -100 tests/responses/responses-forward-prompt-envelope.test.ts -62 tests/responses/responses-forward-transport-baseurl.test.ts -163 tests/responses/responses-freeform-wrapper-keys.test.ts +154 tests/responses/protocol-plan-snapshot.test.ts +42 tests/responses/protocol-plan.test.ts +149 tests/responses/protocol-shadow-plan.test.ts +48 tests/responses/protocol-trace.test.ts +59 tests/responses/provider-egress-fetch.test.ts +587 tests/responses/reasoning-archive-http.test.ts +559 tests/responses/reasoning-archive-ws.test.ts +290 tests/responses/reasoning-effort-summary-default.test.ts +257 tests/responses/reasoning-envelope.test.ts +93 tests/responses/reasoning-retention-quota.test.ts +2030 tests/responses/reasoning-retention-routing.test.ts +720 tests/responses/reasoning-retention-v2.test.ts +69 tests/responses/reasoning-retention.test.ts +533 tests/responses/refreshed-upstream-deadlines.test.ts +97 tests/responses/reserve-dispatch-ws.test.ts +116 tests/responses/responses-4546-incident-regression.test.ts +813 tests/responses/responses-account-auto-pause-wire-owner.test.ts +1102 tests/responses/responses-account-auto-pause.test.ts +92 tests/responses/responses-account-change-scrub.test.ts +2923 tests/responses/responses-account-label.test.ts +400 tests/responses/responses-alternate-main-cancellation.test.ts +500 tests/responses/responses-anthropic-billing-send-budget.test.ts +244 tests/responses/responses-anthropic-compaction-prefix.test.ts +298 tests/responses/responses-anthropic-fast-downgrade.test.ts +410 tests/responses/responses-anthropic-legal-history.test.ts +122 tests/responses/responses-anthropic-thinking-recovery.test.ts +1001 tests/responses/responses-anthropic-thinking-signature-recovery.test.ts +331 tests/responses/responses-auto-pause-replay-owner.test.ts +333 tests/responses/responses-azure-opaque-blob-recovery.test.ts +156 tests/responses/responses-bare-echo-helper-fence.test.ts +51 tests/responses/responses-call-id-linkage.test.ts +671 tests/responses/responses-canonical-nonstream.test.ts +102 tests/responses/responses-canonical-only-top-level-fields.test.ts +229 tests/responses/responses-chat-tool-call-content.test.ts +102 tests/responses/responses-chatgpt-web-replay-metadata.test.ts +153 tests/responses/responses-claude-preflight-lease.test.ts +52 tests/responses/responses-code-mode-goal-helpers.test.ts +150 tests/responses/responses-code-mode-mcp-direct.test.ts +51 tests/responses/responses-code-mode-patch-compile.test.ts +116 tests/responses/responses-code-mode-shell-compile.test.ts +2670 tests/responses/responses-cold-opaque-recovery.test.ts +255 tests/responses/responses-combo-bridge-usage.test.ts +545 tests/responses/responses-combo-exhausted-error.test.ts +326 tests/responses/responses-combo-fallback-off.test.ts +255 tests/responses/responses-combo-replay-principal.test.ts +550 tests/responses/responses-combo-run-turn-classified-failure.test.ts +6391 tests/responses/responses-compact-handoff-admission.test.ts +2717 tests/responses/responses-compaction-http-isolation.test.ts +3660 tests/responses/responses-compaction-override.test.ts +115 tests/responses/responses-compaction-policy-identity.test.ts +45 tests/responses/responses-compaction-recovery-policy.test.ts +6909 tests/responses/responses-compaction-recovery.test.ts +4163 tests/responses/responses-compaction-routing.test.ts +353 tests/responses/responses-compaction.test.ts +5947 tests/responses/responses-console-go-upload-retry.test.ts +2906 tests/responses/responses-context-overflow.test.ts +106 tests/responses/responses-continuation-boundaries.test.ts +116 tests/responses/responses-core-modules.test.ts +50 tests/responses/responses-custom-tool-guidance.test.ts +321 tests/responses/responses-custom-tool-historical-replay.test.ts +286 tests/responses/responses-custom-tool-repair-dispatch.test.ts +59 tests/responses/responses-custom-tool-repair.test.ts +98 tests/responses/responses-custom-tool-stream-consistency.test.ts +45 tests/responses/responses-default-namespace-emit-normalize.test.ts +717 tests/responses/responses-devin-401-replay.test.ts +110 tests/responses/responses-dispatch-receipt.test.ts +316 tests/responses/responses-fetch-helpers-boundary.test.ts +67 tests/responses/responses-field-backfill.test.ts +9490 tests/responses/responses-first-send-reservation.test.ts +201 tests/responses/responses-first-send-spend-policy.test.ts +114 tests/responses/responses-forward-client-headers.test.ts +119 tests/responses/responses-forward-dangling-call.test.ts +271 tests/responses/responses-forward-incomplete-quota.test.ts +123 tests/responses/responses-forward-output-cap.test.ts +128 tests/responses/responses-forward-posit-continuation.test.ts +175 tests/responses/responses-forward-prompt-envelope.test.ts +50 tests/responses/responses-forward-transport-baseurl.test.ts +182 tests/responses/responses-freeform-wrapper-keys.test.ts 249 tests/responses/responses-function-tool-repair.test.ts -4608 tests/responses/responses-grok-devin-preflight.test.ts -317 tests/responses/responses-hide-raw-reasoning.test.ts -379 tests/responses/responses-hosted-image-delivery.test.ts -85 tests/responses/responses-hosted-image-display.test.ts -460 tests/responses/responses-hosted-image-limits.test.ts -352 tests/responses/responses-hosted-send-hop.test.ts -484 tests/responses/responses-hosted-send-producer.test.ts -523 tests/responses/responses-hosted-send-reservation.test.ts -231 tests/responses/responses-hosted-send-round-parity.test.ts -475 tests/responses/responses-hosted-send-unsent-hop.test.ts -215 tests/responses/responses-hosted-send-ws.test.ts -112 tests/responses/responses-hosted-tool-declaration.test.ts -85 tests/responses/responses-hosted-tool-min-spread.test.ts -220 tests/responses/responses-image-gen-repair.test.ts -760 tests/responses/responses-inbound-store-default.test.ts -86 tests/responses/responses-item-id-repair.test.ts -40 tests/responses/responses-json-events.test.ts -72 tests/responses/responses-legacy-dotted-tool-name-repair.test.ts -654 tests/responses/responses-main-quota-observation.test.ts -375 tests/responses/responses-memory-models.test.ts -53 tests/responses/responses-mimo-envelope.test.ts -211 tests/responses/responses-muse-tool-choice.test.ts -214 tests/responses/responses-muse-tool-name-alias.test.ts -311 tests/responses/responses-native-compact-search-history.test.ts -163 tests/responses/responses-native-item-extensions-compact.test.ts -131 tests/responses/responses-native-item-extensions.test.ts -560 tests/responses/responses-native-key-cooldown.test.ts -895 tests/responses/responses-native-main-refresh.test.ts -760 tests/responses/responses-native-ultra-effort-wire.test.ts -2004 tests/responses/responses-oauth-refresh-capacity.test.ts -5977 tests/responses/responses-opaque-blob-recovery.test.ts -111 tests/responses/responses-parser-agent-message.test.ts -72 tests/responses/responses-parser-malformed-content.test.ts -173 tests/responses/responses-parser.test.ts -126 tests/responses/responses-passthrough-transient-policy.test.ts -50 tests/responses/responses-phase-inference.test.ts -4408 tests/responses/responses-pool-401-refresh.test.ts -8858 tests/responses/responses-pool-overload-failover.test.ts -115 tests/responses/responses-pool-refresh-attribution.test.ts -511 tests/responses/responses-preview-main-read-fence.test.ts -271 tests/responses/responses-reasoning-effort-downgrade.test.ts -282 tests/responses/responses-reasoning-summary-passthrough.test.ts -188 tests/responses/responses-replay-metadata-principal.test.ts -128 tests/responses/responses-request-compression.test.ts -845 tests/responses/responses-required-chat-tool.test.ts -112 tests/responses/responses-reset-replay.test.ts -2113 tests/responses/responses-retained-reasoning-stream-recovery.test.ts -268 tests/responses/responses-routed-web-search-fields.test.ts -357 tests/responses/responses-run-turn-key-pacing.test.ts -298 tests/responses/responses-run-turn-key-readmission.test.ts -674 tests/responses/responses-run-turn-web-search.test.ts -2255 tests/responses/responses-self-named-namespace-scrub.test.ts -6953 tests/responses/responses-send-budget-counts.test.ts -517 tests/responses/responses-send-budget-errors.test.ts -467 tests/responses/responses-shadow-intercept.test.ts -359 tests/responses/responses-show-thinking-summary.test.ts -729 tests/responses/responses-sidecar-context-overflow.test.ts -334 tests/responses/responses-sidecar-usage.test.ts -491 tests/responses/responses-skills-snapshot.test.ts -845 tests/responses/responses-snapshot-repair-server.test.ts -271 tests/responses/responses-snapshot-repair.test.ts -347 tests/responses/responses-snapshot-scaling.test.ts -94 tests/responses/responses-sparse-terminal-tool-scope.test.ts -2047 tests/responses/responses-spend-anchor.test.ts -85 tests/responses/responses-spend-capacity-guard.test.ts -171 tests/responses/responses-spend-contract-c.test.ts -187 tests/responses/responses-spend-ledger-wiring.test.ts -69 tests/responses/responses-spill-acl-recovery.test.ts -306 tests/responses/responses-spill-admission-headroom.test.ts -72 tests/responses/responses-spill-inspection.test.ts -99 tests/responses/responses-spill-orphan-sweep.test.ts -296 tests/responses/responses-spill-shutdown-clock.test.ts -67 tests/responses/responses-state-flush-race.test.ts -68 tests/responses/responses-state-snapshot-select.test.ts -68 tests/responses/responses-state-snapshot-stubs.test.ts -471 tests/responses/responses-state-store-false.test.ts -233 tests/responses/responses-state-write-amplification.test.ts -7548 tests/responses/responses-state.test.ts -753 tests/responses/responses-stateless-dangling-call-repair.test.ts -50 tests/responses/responses-stream-tool-events.test.ts -105 tests/responses/responses-terminal-repair.test.ts -147 tests/responses/responses-tool-conformance.test.ts -37 tests/responses/responses-tool-groups.test.ts -232 tests/responses/responses-tool-search-repair.test.ts -392 tests/responses/responses-translated-replay-principal.test.ts -18710 tests/responses/responses-translated-reset.test.ts -217 tests/responses/responses-undeclared-tool-guard-inbound.test.ts -968 tests/responses/responses-undeclared-tool-guard.test.ts -150 tests/responses/responses-url-citation-title-repair.test.ts -95 tests/responses/responses-usage-passthrough.test.ts -1298 tests/responses/responses-web-search-thinking-signature-recovery.test.ts -104 tests/responses/responses-xai-request-compat.test.ts -328 tests/responses/shadow-intercept-target-lifecycle.test.ts -75 tests/responses/sse-carriage-return.test.ts -248 tests/responses/sse-client-frame-bounds.test.ts -311 tests/responses/sse-decoder.test.ts -349 tests/responses/sse-failed-tail.test.ts -401 tests/responses/sse-inspector-bounds.test.ts -78 tests/responses/sse-null-data-frame.test.ts -188 tests/responses/sse-payload-rewrite.test.ts -126 tests/responses/sse-rewrite-line-endings.test.ts -48 tests/responses/sse-unspaced-data-fields.test.ts +4706 tests/responses/responses-grok-devin-preflight.test.ts +176 tests/responses/responses-hide-raw-reasoning.test.ts +317 tests/responses/responses-hosted-image-delivery.test.ts +68 tests/responses/responses-hosted-image-display.test.ts +306 tests/responses/responses-hosted-image-limits.test.ts +337 tests/responses/responses-hosted-send-hop.test.ts +454 tests/responses/responses-hosted-send-producer.test.ts +514 tests/responses/responses-hosted-send-reservation.test.ts +149 tests/responses/responses-hosted-send-round-parity.test.ts +268 tests/responses/responses-hosted-send-unsent-hop.test.ts +218 tests/responses/responses-hosted-send-ws.test.ts +122 tests/responses/responses-hosted-tool-declaration.test.ts +133 tests/responses/responses-hosted-tool-min-spread.test.ts +203 tests/responses/responses-image-gen-repair.test.ts +1122 tests/responses/responses-inbound-store-default.test.ts +49 tests/responses/responses-item-id-repair.test.ts +54 tests/responses/responses-json-events.test.ts +62 tests/responses/responses-legacy-dotted-tool-name-repair.test.ts +581 tests/responses/responses-main-quota-observation.test.ts +362 tests/responses/responses-memory-models.test.ts +94 tests/responses/responses-mimo-envelope.test.ts +226 tests/responses/responses-muse-tool-choice.test.ts +222 tests/responses/responses-muse-tool-name-alias.test.ts +269 tests/responses/responses-native-compact-search-history.test.ts +180 tests/responses/responses-native-item-extensions-compact.test.ts +132 tests/responses/responses-native-item-extensions.test.ts +644 tests/responses/responses-native-key-cooldown.test.ts +1026 tests/responses/responses-native-main-refresh.test.ts +881 tests/responses/responses-native-ultra-effort-wire.test.ts +1706 tests/responses/responses-oauth-refresh-capacity.test.ts +56 tests/responses/responses-ollama-codec.test.ts +5379 tests/responses/responses-opaque-blob-recovery.test.ts +78 tests/responses/responses-parser-agent-message.test.ts +78 tests/responses/responses-parser-malformed-content.test.ts +169 tests/responses/responses-parser.test.ts +95 tests/responses/responses-passthrough-transient-policy.test.ts +58 tests/responses/responses-phase-inference.test.ts +4848 tests/responses/responses-pool-401-refresh.test.ts +8803 tests/responses/responses-pool-overload-failover.test.ts +142 tests/responses/responses-pool-refresh-attribution.test.ts +361 tests/responses/responses-preview-main-read-fence.test.ts +478 tests/responses/responses-reasoning-effort-downgrade.test.ts +218 tests/responses/responses-reasoning-summary-passthrough.test.ts +211 tests/responses/responses-replay-metadata-principal.test.ts +147 tests/responses/responses-request-compression.test.ts +407 tests/responses/responses-required-chat-tool.test.ts +82 tests/responses/responses-reset-replay.test.ts +2377 tests/responses/responses-retained-reasoning-stream-recovery.test.ts +121 tests/responses/responses-routed-web-search-fields.test.ts +194 tests/responses/responses-run-turn-key-pacing.test.ts +273 tests/responses/responses-run-turn-key-readmission.test.ts +831 tests/responses/responses-run-turn-web-search.test.ts +2251 tests/responses/responses-self-named-namespace-scrub.test.ts +6301 tests/responses/responses-send-budget-counts.test.ts +439 tests/responses/responses-send-budget-errors.test.ts +326 tests/responses/responses-shadow-intercept.test.ts +331 tests/responses/responses-show-thinking-summary.test.ts +1016 tests/responses/responses-sidecar-context-overflow.test.ts +224 tests/responses/responses-sidecar-usage.test.ts +249 tests/responses/responses-skills-snapshot.test.ts +759 tests/responses/responses-snapshot-repair-server.test.ts +149 tests/responses/responses-snapshot-repair.test.ts +415 tests/responses/responses-snapshot-scaling.test.ts +97 tests/responses/responses-sparse-terminal-tool-scope.test.ts +1845 tests/responses/responses-spend-anchor.test.ts +91 tests/responses/responses-spend-capacity-guard.test.ts +191 tests/responses/responses-spend-contract-c.test.ts +200 tests/responses/responses-spend-ledger-wiring.test.ts +64 tests/responses/responses-spill-acl-recovery.test.ts +298 tests/responses/responses-spill-admission-headroom.test.ts +107 tests/responses/responses-spill-inspection.test.ts +59 tests/responses/responses-spill-orphan-sweep.test.ts +337 tests/responses/responses-spill-shutdown-clock.test.ts +59 tests/responses/responses-state-flush-race.test.ts +43 tests/responses/responses-state-snapshot-select.test.ts +56 tests/responses/responses-state-snapshot-stubs.test.ts +348 tests/responses/responses-state-store-false.test.ts +208 tests/responses/responses-state-write-amplification.test.ts +7078 tests/responses/responses-state.test.ts +757 tests/responses/responses-stateless-dangling-call-repair.test.ts +55 tests/responses/responses-stream-tool-events.test.ts +131 tests/responses/responses-terminal-repair.test.ts +105 tests/responses/responses-tool-conformance.test.ts +49 tests/responses/responses-tool-groups.test.ts +231 tests/responses/responses-tool-search-repair.test.ts +475 tests/responses/responses-translated-replay-principal.test.ts +18418 tests/responses/responses-translated-reset.test.ts +297 tests/responses/responses-undeclared-tool-guard-inbound.test.ts +682 tests/responses/responses-undeclared-tool-guard.test.ts +123 tests/responses/responses-url-citation-title-repair.test.ts +111 tests/responses/responses-usage-passthrough.test.ts +1140 tests/responses/responses-web-search-thinking-signature-recovery.test.ts +145 tests/responses/responses-xai-request-compat.test.ts +330 tests/responses/shadow-intercept-target-lifecycle.test.ts +69 tests/responses/sse-carriage-return.test.ts +283 tests/responses/sse-client-frame-bounds.test.ts +454 tests/responses/sse-decoder.test.ts +481 tests/responses/sse-failed-tail.test.ts +444 tests/responses/sse-inspector-bounds.test.ts +82 tests/responses/sse-null-data-frame.test.ts +115 tests/responses/sse-payload-rewrite.test.ts +147 tests/responses/sse-rewrite-line-endings.test.ts +61 tests/responses/sse-unspaced-data-fields.test.ts 62 tests/responses/thought-signature-credential-scope.test.ts -232 tests/responses/turn-membership-ingress.test.ts -72 tests/responses/turn-membership.test.ts -59 tests/responses/visualization-directives.test.ts -586 tests/responses/ws-ambiguous-resend.test.ts -4269 tests/responses/ws-capacity-reclamation.test.ts -484 tests/responses/ws-capacity-tool-ownership.test.ts -56 tests/responses/ws-committed-liveness.test.ts -146 tests/responses/ws-endpoint.test.ts -150 tests/responses/ws-failure-stage.test.ts -523 tests/responses/ws-native-injection.test.ts -227 tests/responses/ws-native-result-continuations.test.ts -2224 tests/responses/ws-native-steering.test.ts -149 tests/responses/ws-pre-output-refusal.test.ts -329 tests/responses/ws-replay-refusal-attribution.test.ts -329 tests/responses/ws-steering-completion.test.ts -291 tests/responses/ws-steering-smoke.test.ts -299 tests/responses/ws-steering-stability.test.ts -195 tests/responses/ws-upstream-reuse.test.ts -72 tests/responses/ws-upstream-socks5.test.ts -1210 tests/responses/ws-upstream.test.ts -229 tests/routing/always-on-429-failover.test.ts -155 tests/routing/anthropic-quorum-cache.test.ts -43 tests/routing/cl01-claude-outbound-review-regressions.test.ts -45 tests/routing/cl01-openai-chat-review-regressions.test.ts -104 tests/routing/cl01-review-regressions.test.ts -117 tests/routing/codex-agent-role-models.test.ts -39 tests/routing/codex-role-auto-assign.test.ts -59 tests/routing/codex-role-capability-consent.test.ts -113 tests/routing/codex-role-capability-redirects.test.ts -36 tests/routing/codex-role-measured-ties.test.ts -63 tests/routing/codex-role-sizing.test.ts -175 tests/routing/combo-child-headers.test.ts -230 tests/routing/combo-description.test.ts -859 tests/routing/combo-management-api.test.ts -113 tests/routing/combo-required-tool-stream-preflight.test.ts -158 tests/routing/combo-stream-preflight.test.ts -94 tests/routing/combo-terminal-refusal.test.ts +276 tests/responses/turn-membership-ingress.test.ts +105 tests/responses/turn-membership.test.ts +69 tests/responses/visualization-directives.test.ts +492 tests/responses/ws-ambiguous-resend.test.ts +3917 tests/responses/ws-capacity-reclamation.test.ts +365 tests/responses/ws-capacity-tool-ownership.test.ts +52 tests/responses/ws-committed-liveness.test.ts +127 tests/responses/ws-endpoint.test.ts +179 tests/responses/ws-failure-stage.test.ts +506 tests/responses/ws-native-injection.test.ts +360 tests/responses/ws-native-result-continuations.test.ts +2691 tests/responses/ws-native-steering.test.ts +144 tests/responses/ws-pre-output-refusal.test.ts +247 tests/responses/ws-replay-refusal-attribution.test.ts +313 tests/responses/ws-steering-completion.test.ts +193 tests/responses/ws-steering-smoke.test.ts +309 tests/responses/ws-steering-stability.test.ts +238 tests/responses/ws-upstream-reuse.test.ts +50 tests/responses/ws-upstream-socks5.test.ts +1010 tests/responses/ws-upstream.test.ts +230 tests/routing/always-on-429-failover.test.ts +136 tests/routing/anthropic-quorum-cache.test.ts +55 tests/routing/cl01-claude-outbound-review-regressions.test.ts +49 tests/routing/cl01-openai-chat-review-regressions.test.ts +129 tests/routing/cl01-review-regressions.test.ts +93 tests/routing/codex-agent-role-models.test.ts +45 tests/routing/codex-role-auto-assign.test.ts +69 tests/routing/codex-role-capability-consent.test.ts +50 tests/routing/codex-role-capability-redirects.test.ts +55 tests/routing/codex-role-measured-ties.test.ts +55 tests/routing/codex-role-sizing.test.ts +135 tests/routing/combo-child-headers.test.ts +171 tests/routing/combo-description.test.ts +812 tests/routing/combo-management-api.test.ts +143 tests/routing/combo-required-tool-stream-preflight.test.ts +176 tests/routing/combo-stream-preflight.test.ts +137 tests/routing/combo-terminal-refusal.test.ts 343 tests/routing/combo-vision-enrollment.test.ts -313 tests/routing/compatibility-provider-equivalence.test.ts -46 tests/routing/destination-policy-resolved.test.ts -57 tests/routing/fallback-policy.test.ts -89 tests/routing/fastwire-characterization-routing.test.ts -488 tests/routing/fastwire-characterization-wire.test.ts -216 tests/routing/fastwire-observability.test.ts -102 tests/routing/fastwire-policy.test.ts -545 tests/routing/fastwire-response-authority.test.ts -47 tests/routing/jev-decision-destination.test.ts -286 tests/routing/jev-decision-model-config.test.ts -225 tests/routing/jev-decision-provider-combo.test.ts -192 tests/routing/jev-decision.test.ts -1090 tests/routing/jev-model-backend.test.ts -290 tests/routing/jev-quota-activation.test.ts -192 tests/routing/jev-quota-anthropic2.test.ts -159 tests/routing/jev-quota-antigravity.test.ts -200 tests/routing/jev-quota-codex-reset.test.ts -202 tests/routing/jev-quota-config.test.ts -515 tests/routing/jev-quota-core-boundary.test.ts -130 tests/routing/jev-quota-publication.test.ts -338 tests/routing/jev-quota-signals.test.ts -52 tests/routing/jev-service-exchange.test.ts -54 tests/routing/jev-session-pin.test.ts -98 tests/routing/jev-typesafe-golden.test.ts -125 tests/routing/policy-execution.test.ts -275 tests/routing/probe-lease-dispatch-wiring.test.ts -125 tests/routing/probe-lease.test.ts -106 tests/routing/resolved-model-policy-consumers.test.ts -47 tests/routing/router-anthropic-billing-failover.test.ts -168 tests/routing/router-blocked-cross-provider.test.ts -92 tests/routing/router-combo-failover-classification.test.ts -127 tests/routing/router-discarded-baseurl-warning.test.ts -109 tests/routing/router-template-baseurl.test.ts -107 tests/routing/router.test.ts -465 tests/routing/routing-analytics.test.ts -91 tests/routing/routing-capability-catalog.test.ts -127 tests/routing/routing-capability-model-matching.test.ts -36 tests/routing/routing-compatibility-auth-identity.test.ts -216 tests/routing/routing-compatibility-boundaries.test.ts +305 tests/routing/compatibility-provider-equivalence.test.ts +53 tests/routing/destination-policy-resolved.test.ts +70 tests/routing/fallback-policy.test.ts +111 tests/routing/fastwire-characterization-routing.test.ts +375 tests/routing/fastwire-characterization-wire.test.ts +273 tests/routing/fastwire-observability.test.ts +116 tests/routing/fastwire-policy.test.ts +511 tests/routing/fastwire-response-authority.test.ts +52 tests/routing/jev-decision-destination.test.ts +304 tests/routing/jev-decision-model-config.test.ts +297 tests/routing/jev-decision-provider-combo.test.ts +173 tests/routing/jev-decision.test.ts +1062 tests/routing/jev-model-backend.test.ts +248 tests/routing/jev-quota-activation.test.ts +191 tests/routing/jev-quota-anthropic2.test.ts +152 tests/routing/jev-quota-antigravity.test.ts +165 tests/routing/jev-quota-codex-reset.test.ts +197 tests/routing/jev-quota-config.test.ts +610 tests/routing/jev-quota-core-boundary.test.ts +153 tests/routing/jev-quota-publication.test.ts +203 tests/routing/jev-quota-signals.test.ts +65 tests/routing/jev-service-exchange.test.ts +65 tests/routing/jev-session-pin.test.ts +72 tests/routing/jev-typesafe-golden.test.ts +127 tests/routing/policy-execution.test.ts +366 tests/routing/probe-lease-dispatch-wiring.test.ts +134 tests/routing/probe-lease.test.ts +133 tests/routing/resolved-model-policy-consumers.test.ts +49 tests/routing/router-anthropic-billing-failover.test.ts +199 tests/routing/router-blocked-cross-provider.test.ts +119 tests/routing/router-combo-failover-classification.test.ts +106 tests/routing/router-discarded-baseurl-warning.test.ts +112 tests/routing/router-template-baseurl.test.ts +102 tests/routing/router.test.ts +483 tests/routing/routing-analytics.test.ts +65 tests/routing/routing-capability-catalog.test.ts +221 tests/routing/routing-capability-model-matching.test.ts +96 tests/routing/routing-compatibility-auth-identity.test.ts +245 tests/routing/routing-compatibility-boundaries.test.ts 111 tests/routing/routing-compatibility-model-matching.test.ts -179 tests/routing/routing-compatibility.test.ts -67 tests/routing/routing-identity-domains.test.ts -254 tests/routing/routing-policy-dispatch-scope.test.ts -136 tests/routing/routing-policy-fallback-off.test.ts -362 tests/routing/routing-policy-fallback.test.ts -69 tests/routing/routing-policy-pool-quota.test.ts -420 tests/routing/routing-policy-surface-parity.test.ts -383 tests/routing/routing-profile-management-editor.test.ts -310 tests/routing/routing-profile.test.ts -110 tests/routing/subagent-context-staleness.test.ts -52 tests/routing/subagent-defaults.test.ts -5653 tests/routing/subagent-fallback-handle-responses.test.ts -100 tests/routing/subagent-fallback-preview-sites.test.ts -167 tests/routing/subagent-model-fallback-api.test.ts -251 tests/routing/subagent-model-fallback-off.test.ts -608 tests/routing/subagent-model-fallback.test.ts -137 tests/routing/subagent-roster-migration.test.ts -495 tests/routing/subagent-roster-retention.test.ts -113 tests/server/account-import-project-fallback.test.ts -107 tests/server/account-import.test.ts -3080 tests/server/account-pool-management-api.test.ts -227 tests/server/adapter-resolve.test.ts -75 tests/server/advisor-routes.test.ts -82 tests/server/agent-assertion-auth.test.ts -269 tests/server/agent-task-recovery-cache.test.ts -574 tests/server/agent-task-recovery-combo.test.ts -209 tests/server/agent-task-recovery-fallback.test.ts -265 tests/server/agent-task-recovery-security.test.ts -12031 tests/server/agent-task-recovery.test.ts -138 tests/server/alias-management-api.test.ts -162 tests/server/anthropic2-management.test.ts -84 tests/server/api-access-endpoints.test.ts -903 tests/server/api-catalog-route.test.ts -249 tests/server/api-codex-log-guard-compact.test.ts -175 tests/server/api-codex-log-guard-protection.test.ts -164 tests/server/api-codex-log-guard.test.ts -1281 tests/server/api-debug.test.ts -2680 tests/server/api-key-attribution.test.ts -105 tests/server/api-key-model-scope.test.ts -228 tests/server/api-key-scope-alpha-search.test.ts -246 tests/server/api-key-scope-audio.test.ts -198 tests/server/api-key-scope-images.test.ts -123 tests/server/api-key-scope-live.test.ts -3386 tests/server/api-keys-routes.test.ts -3181 tests/server/api-usage.test.ts -549 tests/server/aside-profiles-routes.test.ts -88 tests/server/audio-client.test.ts -1099 tests/server/audio-dictation.test.ts -1214 tests/server/audio-transcriptions.test.ts -562 tests/server/bounded-body.test.ts +262 tests/routing/routing-compatibility.test.ts +48 tests/routing/routing-identity-domains.test.ts +278 tests/routing/routing-policy-dispatch-scope.test.ts +153 tests/routing/routing-policy-fallback-off.test.ts +372 tests/routing/routing-policy-fallback.test.ts +98 tests/routing/routing-policy-pool-quota.test.ts +267 tests/routing/routing-policy-surface-parity.test.ts +324 tests/routing/routing-profile-management-editor.test.ts +305 tests/routing/routing-profile.test.ts +171 tests/routing/subagent-context-staleness.test.ts +57 tests/routing/subagent-defaults.test.ts +4137 tests/routing/subagent-fallback-handle-responses.test.ts +42 tests/routing/subagent-fallback-preview-sites.test.ts +161 tests/routing/subagent-model-fallback-api.test.ts +390 tests/routing/subagent-model-fallback-off.test.ts +433 tests/routing/subagent-model-fallback.test.ts +117 tests/routing/subagent-roster-migration.test.ts +434 tests/routing/subagent-roster-retention.test.ts +109 tests/server/account-import-project-fallback.test.ts +143 tests/server/account-import.test.ts +3213 tests/server/account-pool-management-api.test.ts +135 tests/server/adapter-resolve.test.ts +135 tests/server/admitted-http-turn.test.ts +72 tests/server/advisor-routes.test.ts +118 tests/server/agent-assertion-auth.test.ts +292 tests/server/agent-task-recovery-cache.test.ts +452 tests/server/agent-task-recovery-combo.test.ts +261 tests/server/agent-task-recovery-fallback.test.ts +324 tests/server/agent-task-recovery-security.test.ts +12051 tests/server/agent-task-recovery.test.ts +136 tests/server/alias-management-api.test.ts +244 tests/server/anthropic2-management.test.ts +114 tests/server/api-access-endpoints.test.ts +800 tests/server/api-catalog-route.test.ts +330 tests/server/api-codex-log-guard-compact.test.ts +208 tests/server/api-codex-log-guard-protection.test.ts +158 tests/server/api-codex-log-guard.test.ts +1068 tests/server/api-debug.test.ts +2896 tests/server/api-key-attribution.test.ts +120 tests/server/api-key-model-scope.test.ts +216 tests/server/api-key-scope-alpha-search.test.ts +125 tests/server/api-key-scope-audio.test.ts +186 tests/server/api-key-scope-images.test.ts +218 tests/server/api-key-scope-live.test.ts +2820 tests/server/api-keys-routes.test.ts +1937 tests/server/api-usage.test.ts +463 tests/server/aside-profiles-routes.test.ts +140 tests/server/audio-client.test.ts +998 tests/server/audio-dictation.test.ts +1103 tests/server/audio-transcriptions.test.ts +500 tests/server/bounded-body.test.ts 128 tests/server/bridge-live-delivery.test.ts -217 tests/server/caller-session-identity.test.ts -642 tests/server/caller-session-ingress.test.ts -2564 tests/server/cancel-body-on-abort.test.ts -999 tests/server/claude-intercept-integration.test.ts -407 tests/server/codex-agent-role-routes.test.ts -148 tests/server/codex-role-auto-assign-routes.test.ts +246 tests/server/caller-session-identity.test.ts +452 tests/server/caller-session-ingress.test.ts +2676 tests/server/cancel-body-on-abort.test.ts +904 tests/server/claude-intercept-integration.test.ts +118 tests/server/client-retry-after-sites.test.ts +416 tests/server/codex-agent-role-routes.test.ts +187 tests/server/codex-role-auto-assign-routes.test.ts 124 tests/server/codex-role-configured-credentials.test.ts -247 tests/server/codex-role-history-recovery.test.ts -502 tests/server/combo-loopback-metered-consent.test.ts -450 tests/server/combo-metered-consent.test.ts -78 tests/server/combo-requested-effort.test.ts -150 tests/server/companion-settings.test.ts -399 tests/server/config.test.ts -200 tests/server/consume-for-inspection-cancel.test.ts -477 tests/server/context-history-ownership.test.ts -158 tests/server/context-history.test.ts -310 tests/server/data-plane-admission-identity.test.ts -45 tests/server/debug-settings.test.ts -47 tests/server/decision-discovery.test.ts -247 tests/server/decision-routes.test.ts -403 tests/server/distributed-key-401.test.ts -306 tests/server/error-fidelity.test.ts -132 tests/server/errors-adapter-failure.test.ts -174 tests/server/fallback-routes.test.ts -502 tests/server/fetch-header-timeout.test.ts -414 tests/server/health-scoring.test.ts -481 tests/server/hub-usage.test.ts -887 tests/server/inbound-body-admission.test.ts -124 tests/server/inbound-body-budget.test.ts -119 tests/server/inference-attempt.test.ts -199 tests/server/inference-client-encoder-delivery.test.ts -85 tests/server/inference-client-wire.test.ts -110 tests/server/inference-final-log.test.ts -1414 tests/server/inference-send-budget.test.ts -133 tests/server/input-admission.test.ts -186 tests/server/jev-decision-scope.test.ts -133 tests/server/link-child-parity.test.ts -216 tests/server/link-enrollment.test.ts -2582 tests/server/link-join-route.test.ts -488 tests/server/link-listener-admission.test.ts -193 tests/server/link-listener-lifecycle.test.ts -47 tests/server/link-listener-mutation.test.ts -5939 tests/server/link-management-relay.test.ts -647 tests/server/link-management-routes.test.ts -53 tests/server/live-call-bindings.test.ts -59 tests/server/live-native-calls.test.ts -156 tests/server/local-account-switch-capability.test.ts -287 tests/server/local-account-switch-ingress.test.ts -566 tests/server/local-aside-sync-capability.test.ts -87 tests/server/local-management-attestation.test.ts -67 tests/server/local-management-capability.test.ts -539 tests/server/local-management-direct-transport.test.ts -63 tests/server/local-provider-reload-client.test.ts -561 tests/server/local-read-response-proof.test.ts -631 tests/server/login-shell-path.test.ts -124 tests/server/logs-timezone.test.ts -140 tests/server/loopback-companion-client-targets.test.ts -103 tests/server/loopback-listener-admission.test.ts -2542 tests/server/loopback-listener-integration.test.ts -200 tests/server/management-account-auto-pause.test.ts -134 tests/server/management-anthropic-reset-grants.test.ts -247 tests/server/management-api-logs-metrics.test.ts -119 tests/server/management-api-logs-timing-basis.test.ts -267 tests/server/management-auto-review-auth.test.ts -167 tests/server/management-auto-review-settings.test.ts -563 tests/server/management-client-config-route.test.ts -279 tests/server/management-desktop-compatibility-routes.test.ts -149 tests/server/management-desktop-compatibility-runtime-routes.test.ts -191 tests/server/management-desktop-compatibility-settings.test.ts -219 tests/server/management-droid-reasoning-defaults.test.ts -323 tests/server/management-export-model-names.test.ts -901 tests/server/management-gcp-credential-input.test.ts -345 tests/server/management-google-tool-schema-policy.test.ts -154 tests/server/management-inference-port.test.ts -314 tests/server/management-integration-journal-delete.test.ts -1138 tests/server/management-integration-routes.test.ts -1992 tests/server/management-metrics-export.test.ts -213 tests/server/management-model-roster-gather-race.test.ts -164 tests/server/management-model-roster.test.ts -38 tests/server/management-origin-tls.test.ts -211 tests/server/management-provider-atomicity.test.ts -1957 tests/server/management-provider-compat-carry.test.ts -264 tests/server/management-provider-context-inference.test.ts -750 tests/server/management-provider-hide-raw-reasoning.test.ts -348 tests/server/management-provider-pinsless-validation.test.ts -355 tests/server/management-provider-proto-override.test.ts -729 tests/server/management-provider-reasoning-lists.test.ts -145 tests/server/management-provider-request-pacing.test.ts -79 tests/server/management-provider-reset-replay.test.ts -699 tests/server/management-provider-responses-reasoning.test.ts -167 tests/server/management-provider-synthetic-max.test.ts -370 tests/server/management-provider-upstream-websocket.test.ts -10588 tests/server/management-provider-validation.test.ts -410 tests/server/management-provider-verbosity.test.ts -380 tests/server/management-qoder-selector-state.test.ts -824 tests/server/management-route-registry.test.ts -864 tests/server/management-sidecar-anthropic-instance.test.ts -144 tests/server/management-workflow-budget-routes.test.ts -509 tests/server/memory-watchdog.test.ts -335 tests/server/model-costs-management-api.test.ts -429 tests/server/model-costs-pricing-cache.test.ts -497 tests/server/model-costs-prompt-length-pricing.test.ts -203 tests/server/model-discovery-management-api.test.ts -444 tests/server/model-export-new-model-policy.test.ts -193 tests/server/model-settings-management-api.test.ts -94 tests/server/outbound-body-guard.test.ts -47 tests/server/owned-service-home.test.ts -67 tests/server/passive-route-linker.test.ts -471 tests/server/persistent-dashboard-admission.test.ts -484 tests/server/persistent-dashboard-consent.test.ts -230 tests/server/persistent-dashboard-session.test.ts -2266 tests/server/plaintext-v2-agent-messages-server.test.ts -971 tests/server/port-reclaim.test.ts -410 tests/server/ports.test.ts -1026 tests/server/prefer-model-alias-ids.test.ts -951 tests/server/probe-timeout-env.test.ts -179 tests/server/protocol-provider-summary.test.ts -180 tests/server/protocol-routes.test.ts +327 tests/server/codex-role-history-recovery.test.ts +712 tests/server/combo-loopback-metered-consent.test.ts +462 tests/server/combo-metered-consent.test.ts +69 tests/server/combo-requested-effort.test.ts +131 tests/server/companion-settings.test.ts +405 tests/server/config.test.ts +131 tests/server/consume-for-inspection-cancel.test.ts +465 tests/server/context-history-ownership.test.ts +185 tests/server/context-history.test.ts +349 tests/server/data-plane-admission-identity.test.ts +49 tests/server/debug-settings.test.ts +59 tests/server/decision-discovery.test.ts +295 tests/server/decision-routes.test.ts +437 tests/server/distributed-key-401.test.ts +257 tests/server/error-fidelity.test.ts +149 tests/server/errors-adapter-failure.test.ts +187 tests/server/fallback-routes.test.ts +526 tests/server/fetch-header-timeout.test.ts +476 tests/server/health-scoring.test.ts +377 tests/server/hub-usage.test.ts +736 tests/server/inbound-body-admission.test.ts +143 tests/server/inbound-body-budget.test.ts +99 tests/server/inference-attempt.test.ts +182 tests/server/inference-client-encoder-delivery.test.ts +49 tests/server/inference-client-wire.test.ts +103 tests/server/inference-final-log.test.ts +1415 tests/server/inference-send-budget.test.ts +118 tests/server/input-admission.test.ts +152 tests/server/jev-decision-scope.test.ts +120 tests/server/link-child-parity.test.ts +264 tests/server/link-enrollment.test.ts +2519 tests/server/link-join-route.test.ts +507 tests/server/link-listener-admission.test.ts +194 tests/server/link-listener-lifecycle.test.ts +67 tests/server/link-listener-mutation.test.ts +6117 tests/server/link-management-relay.test.ts +360 tests/server/link-management-routes.test.ts +66 tests/server/live-call-bindings.test.ts +39 tests/server/live-native-calls.test.ts +175 tests/server/local-account-switch-capability.test.ts +316 tests/server/local-account-switch-ingress.test.ts +577 tests/server/local-aside-sync-capability.test.ts +78 tests/server/local-management-attestation.test.ts +73 tests/server/local-management-capability.test.ts +577 tests/server/local-management-direct-transport.test.ts +47 tests/server/local-provider-reload-client.test.ts +312 tests/server/local-read-response-proof.test.ts +618 tests/server/login-shell-path.test.ts +181 tests/server/logs-timezone.test.ts +129 tests/server/loopback-companion-client-targets.test.ts +125 tests/server/loopback-listener-admission.test.ts +2854 tests/server/loopback-listener-integration.test.ts +175 tests/server/management-account-auto-pause.test.ts +143 tests/server/management-anthropic-reset-grants.test.ts +180 tests/server/management-api-logs-metrics.test.ts +163 tests/server/management-api-logs-timing-basis.test.ts +347 tests/server/management-auto-review-auth.test.ts +198 tests/server/management-auto-review-settings.test.ts +1249 tests/server/management-client-config-route.test.ts +193 tests/server/management-desktop-compatibility-routes.test.ts +117 tests/server/management-desktop-compatibility-runtime-routes.test.ts +184 tests/server/management-desktop-compatibility-settings.test.ts +235 tests/server/management-droid-reasoning-defaults.test.ts +344 tests/server/management-export-model-names.test.ts +834 tests/server/management-gcp-credential-input.test.ts +365 tests/server/management-google-tool-schema-policy.test.ts +192 tests/server/management-inference-port.test.ts +350 tests/server/management-integration-journal-delete.test.ts +1005 tests/server/management-integration-routes.test.ts +1973 tests/server/management-metrics-export.test.ts +148 tests/server/management-model-roster-gather-race.test.ts +145 tests/server/management-model-roster.test.ts +113 tests/server/management-origin-tls.test.ts +232 tests/server/management-provider-atomicity.test.ts +2017 tests/server/management-provider-compat-carry.test.ts +162 tests/server/management-provider-context-inference.test.ts +660 tests/server/management-provider-hide-raw-reasoning.test.ts +423 tests/server/management-provider-pinsless-validation.test.ts +470 tests/server/management-provider-proto-override.test.ts +725 tests/server/management-provider-reasoning-lists.test.ts +153 tests/server/management-provider-request-pacing.test.ts +59 tests/server/management-provider-reset-replay.test.ts +688 tests/server/management-provider-responses-reasoning.test.ts +145 tests/server/management-provider-synthetic-max.test.ts +176 tests/server/management-provider-upstream-websocket.test.ts +11097 tests/server/management-provider-validation.test.ts +346 tests/server/management-provider-verbosity.test.ts +300 tests/server/management-qoder-selector-state.test.ts +641 tests/server/management-route-registry.test.ts +604 tests/server/management-sidecar-anthropic-instance.test.ts +121 tests/server/management-workflow-budget-routes.test.ts +437 tests/server/memory-watchdog.test.ts +332 tests/server/model-costs-management-api.test.ts +576 tests/server/model-costs-pricing-cache.test.ts +338 tests/server/model-costs-prompt-length-pricing.test.ts +231 tests/server/model-discovery-management-api.test.ts +352 tests/server/model-export-new-model-policy.test.ts +222 tests/server/model-settings-management-api.test.ts +78 tests/server/outbound-body-guard.test.ts +40 tests/server/owned-service-home.test.ts +48 tests/server/passive-route-linker.test.ts +398 tests/server/persistent-dashboard-admission.test.ts +393 tests/server/persistent-dashboard-consent.test.ts +447 tests/server/persistent-dashboard-session.test.ts +2171 tests/server/plaintext-v2-agent-messages-server.test.ts +968 tests/server/port-reclaim.test.ts +365 tests/server/ports.test.ts +904 tests/server/prefer-model-alias-ids.test.ts +837 tests/server/probe-timeout-env.test.ts +139 tests/server/protocol-provider-summary.test.ts +170 tests/server/protocol-routes.test.ts 150 tests/server/protocol-settings-route.test.ts -229 tests/server/provider-account-quota-routes.test.ts -46 tests/server/provider-egress-management-validation.test.ts -174 tests/server/provider-send-path-import.test.ts -55 tests/server/proxy-env-macos.test.ts -64 tests/server/proxy-env.test.ts -384 tests/server/proxy-liveness-bind-scope.test.ts -80 tests/server/proxy-liveness-owner-evidence.test.ts -62 tests/server/proxy-liveness-package-tree-fence.test.ts -86 tests/server/proxy-liveness-recovery.test.ts -83 tests/server/proxy-liveness.test.ts -4849 tests/server/quota-pool-relay.test.ts -572 tests/server/readyz-features.test.ts -656 tests/server/relay-eager.test.ts -1816 tests/server/replay-refusal-parity.test.ts -469 tests/server/reserve-claude-policy.test.ts -2011 tests/server/reserve-ingress.test.ts -460 tests/server/response-log-inspection.test.ts -423 tests/server/response-model-identity.test.ts -1272 tests/server/restart-replacement-not-ready.test.ts -103 tests/server/restart-replacement.test.ts -137 tests/server/retry-after-429.test.ts -47 tests/server/retry-delay-hardening.test.ts -212 tests/server/route-decision-trace.test.ts -2737 tests/server/served-by-header.test.ts -498 tests/server/server-403-permission-e2e.test.ts -351 tests/server/server-agent-task-recovery-replay.test.ts -591 tests/server/server-anthropic-billing-boundaries.test.ts -2823 tests/server/server-anthropic-billing.test.ts -2060 tests/server/server-antigravity-model-denial-recovery.test.ts -646 tests/server/server-antigravity-model-roster-routing.test.ts -142 tests/server/server-antigravity-verify-replay-scope.test.ts -703 tests/server/server-antigravity-web-search-validation.test.ts -481 tests/server/server-auth-localhost-bind.test.ts -1811 tests/server/server-auth-scoped-quota.test.ts -19895 tests/server/server-auth.test.ts -1304 tests/server/server-background-lifecycle.test.ts -1108 tests/server/server-chat-native-key-selection.test.ts -374 tests/server/server-cli-key-probe-admission.test.ts -46 tests/server/server-clickjacking-headers.test.ts -452 tests/server/server-combo-cooldown-fallback.test.ts -1018 tests/server/server-combo-cooldown-recording.test.ts -12170 tests/server/server-combo-failover-e2e.test.ts -43 tests/server/server-combo-held-response.test.ts -1194 tests/server/server-combo-plan-model-refusal.test.ts -147 tests/server/server-combo-quota-code-provenance.test.ts -3900 tests/server/server-combo-reasoning-replay-eligibility.test.ts -1879 tests/server/server-combo-required-tool-contract.test.ts -1059 tests/server/server-combo-stream-hosted-tool-contract.test.ts -783 tests/server/server-combo-stream-required-tool.test.ts -434 tests/server/server-combo-stream-send-contract.test.ts -5255 tests/server/server-combo-tool-loop-continuation.test.ts -564 tests/server/server-combo-zero-output-failover.test.ts -715 tests/server/server-desktop-compatibility-startup.test.ts -961 tests/server/server-generic-oauth-affinity.test.ts -4304 tests/server/server-google-antigravity-oauth-401-replay.test.ts -503 tests/server/server-google-antigravity-oauth-429-budget.test.ts -49 tests/server/server-gui-bundle-freshness.test.ts -186 tests/server/server-images-bodyless-content-length.test.ts -279 tests/server/server-images-pool-admission.test.ts -5025 tests/server/server-images.test.ts -352 tests/server/server-jev-combo-e2e.test.ts -281 tests/server/server-jev-model-decision-e2e.test.ts -465 tests/server/server-jev-model-quota-budget.test.ts -183 tests/server/server-jev-session-pin.test.ts -6763 tests/server/server-key-failover-e2e.test.ts -1741 tests/server/server-kiro-completion-e2e.test.ts -207 tests/server/server-kiro-device-login.test.ts -820 tests/server/server-kiro-oauth-401-replay.test.ts -4866 tests/server/server-kiro-refusal-e2e.test.ts -2486 tests/server/server-kiro-usage-log-e2e.test.ts -464 tests/server/server-live-cancel.test.ts -8773 tests/server/server-live-close.test.ts -587 tests/server/server-live-existing-call.test.ts -130 tests/server/server-live-frame-log.test.ts -1475 tests/server/server-live-realtime-fixtures.test.ts -6845 tests/server/server-live.test.ts -104 tests/server/server-loopback-host-gate.test.ts -3060 tests/server/server-management-auth.test.ts -433 tests/server/server-management-log-admission.test.ts -1309 tests/server/server-native-catalog-priority.test.ts -198 tests/server/server-native-reasoning-retention-merge.test.ts -226 tests/server/server-native-reasoning-retention.test.ts -896 tests/server/server-new-model-policy-arrival.test.ts -449 tests/server/server-opencode-go-goal-streaming.test.ts -1848 tests/server/server-rate-limit-retry-e2e.test.ts -986 tests/server/server-request-body-size.test.ts -1795 tests/server/server-search.test.ts -371 tests/server/server-startup-codex-off.test.ts -525 tests/server/server-startup-reconcile-resilience.test.ts -496 tests/server/server-stop-config-hardening.test.ts -514 tests/server/server-terminal-refusal-wiring.test.ts -212 tests/server/server-workflow-budget-settings.test.ts -530 tests/server/server-xai-chat-reasoning-streaming.test.ts -439 tests/server/server-xai-header-parity.test.ts -957 tests/server/server-xai-oauth-401-replay.test.ts -589 tests/server/server-xai-responses-streaming.test.ts -117 tests/server/session-affinity.test.ts -358 tests/server/session-lane-recall-harness.test.ts -244 tests/server/sidebar-routes.test.ts -50 tests/server/sidebar-star-state.test.ts -144 tests/server/spend-instrumentation-log.test.ts -132 tests/server/spend-ledger-lifecycle.test.ts -443 tests/server/spend-ledger-owner-startup.test.ts -136 tests/server/startup-action-control-elevation.test.ts -121 tests/server/startup-action-control.test.ts -12435 tests/server/startup-health-packaged-probe.test.ts -61 tests/server/startup-prompt.test.ts -132 tests/server/stream-aborted-marker.test.ts -233 tests/server/subagent-model-force-api.test.ts -857 tests/server/system-env.test.ts -155 tests/server/system-restart-admission.test.ts -4063 tests/server/system-restart-ownership.test.ts -162 tests/server/system-restart.test.ts -128 tests/server/system-routes.test.ts -4514 tests/server/terminal-guard-server.test.ts -82 tests/server/terminal-guard.test.ts -153 tests/server/update-async-routes.test.ts -49 tests/server/upstream-connect-error.test.ts -47 tests/server/upstream-http-version.test.ts -775 tests/server/v1-hub-state.test.ts -572 tests/server/v2-agent-message-failfast.test.ts -150 tests/service/autostart-health.test.ts -1381 tests/service/connected-stop-capability-auth.test.ts -2549 tests/service/container-bootstrap.test.ts -206 tests/service/crash-guard.test.ts -25261 tests/service/doctor-codex-envkey-readiness.test.ts -201 tests/service/doctor-oauth.test.ts -275 tests/service/doctor-provider-apikey.test.ts -70 tests/service/doctor-service-memory-contract.test.ts -111 tests/service/init-backup-cleanup.test.ts -7589 tests/service/init-eof.test.ts -89 tests/service/launchd-port-fallback.test.ts -368 tests/service/launchd-repair.test.ts -121 tests/service/live-service-manager-guard.test.ts -49 tests/service/managing-cli.test.ts -52 tests/service/ownership-mutation-lease-diagnostics.test.ts -127 tests/service/process-state.test.ts -175 tests/service/service-auth-qualified-localhost.test.ts -71 tests/service/service-child-ownership.test.ts -101 tests/service/service-claim.test.ts -133 tests/service/service-desktop-login-registration.test.ts -4370 tests/service/service-desktop-recovery.test.ts -75 tests/service/service-desktop-runtime-preflight.test.ts -124 tests/service/service-desktop-startup-health.test.ts -214 tests/service/service-desktop-startup-linux.test.ts -279 tests/service/service-desktop-startup.test.ts -266 tests/service/service-desktop-supervision-windows.test.ts -62 tests/service/service-handled-signal-exit.test.ts -94 tests/service/service-health-sentinel-launch.test.ts -51 tests/service/service-health-sentinel-linux.test.ts -62 tests/service/service-health-sentinel-policy.test.ts -7956 tests/service/service-health-sentinel-process.test.ts -412 tests/service/service-health-sentinel-runner.test.ts -122 tests/service/service-install-wrapper-cleanup.test.ts -1602 tests/service/service-log.test.ts -129 tests/service/service-multishell-path.test.ts -49 tests/service/service-ownership-compatibility.test.ts -160 tests/service/service-ownership-handover.test.ts -319 tests/service/service-ownership-state.test.ts -45 tests/service/service-probe-docker.test.ts -233 tests/service/service-proxy-env.test.ts -112 tests/service/service-runtime-preflight.test.ts -688 tests/service/service-secrets.test.ts -220 tests/service/service-sqlite-home.test.ts -91 tests/service/service-start-environment.test.ts -563 tests/service/service-state-isolation.test.ts -2452 tests/service/service-status-json.test.ts -212 tests/service/service-stop-verification.test.ts -727 tests/service/service-tier-capability.test.ts -234 tests/service/service-wsl-home-ownership.test.ts -945 tests/service/service.test.ts -267 tests/service/shutdown-drain.test.ts -9506 tests/service/shutdown-launcher.test.ts -53 tests/service/stale-state-purge.test.ts -37 tests/service/standalone-service.test.ts -27472 tests/service/stop-deferred-teardown.test.ts -969 tests/service/stop-direct-fetch.test.ts -1190 tests/service/stop-restoration-preflight.test.ts -4795 tests/service/stop-restore-history-ownership.test.ts -69 tests/service/systemd-install-cleanup-hardening.test.ts -309 tests/service/winsw.test.ts -3496 tests/storage/api-storage-cleanup.test.ts -1927 tests/storage/api-storage-policy-already-running.test.ts -1540 tests/storage/api-storage-policy-mutation-busy.test.ts -960 tests/storage/api-storage-policy-put-race.test.ts -1317 tests/storage/api-storage-policy-run.test.ts -794 tests/storage/api-storage-policy.test.ts -634 tests/storage/api-storage.test.ts -1080 tests/storage/storage-cleanup.test.ts -6922 tests/storage/storage-mutation-race.test.ts -222 tests/storage/storage-policy-config-race.test.ts -2054 tests/storage/storage-policy-job-responsive.test.ts -94 tests/storage/storage-policy.test.ts -58 tests/storage/storage-restore-job-errors.test.ts -5401 tests/storage/storage-restore-job-responsive.test.ts -226 tests/storage/storage-scanner.test.ts -1066 tests/storage/storage-worker-lifecycle.test.ts -37 tests/storage/storage-worker-os-join-settle.test.ts -4322 tests/storage/storage-worker-teardown-isolate.test.ts -498 tests/test-layout-tooling.test.ts -139 tests/test-layout.test.ts -50 tests/update/pnpm-command-isolation.test.ts -51 tests/update/update-badge.test.ts -8434 tests/update/update-bun-ownership-lease.test.ts -94 tests/update/update-capability-policy.test.ts -58 tests/update/update-desktop-badge.test.ts -49 tests/update/update-desktop-owner.test.ts -118 tests/update/update-effect-authority.test.ts -360 tests/update/update-guarded-ops.test.ts -782 tests/update/update-home-launcher.test.ts -65 tests/update/update-home-recovery.test.ts -334 tests/update/update-home-worker.test.ts -169 tests/update/update-job-supervised-restart.test.ts -258 tests/update/update-job.test.ts -65 tests/update/update-mise-launcher-target.test.ts -50 tests/update/update-mise-node-runtime.test.ts -493 tests/update/update-mise.test.ts -120 tests/update/update-mutation-boundaries.test.ts -126 tests/update/update-mutation-guard.test.ts -93 tests/update/update-mutation-scanner.test.ts -88 tests/update/update-notify.test.ts -353 tests/update/update-npm-cache-preflight.test.ts -48 tests/update/update-npm-invocation.test.ts -98 tests/update/update-npm-supervisor-exit.test.ts -40 tests/update/update-npm-timeout.test.ts -90 tests/update/update-pnpm.test.ts -47 tests/update/update-reclaim-authorizer.test.ts -89 tests/update/update-recovery-authority.test.ts -191 tests/update/update-recovery-boundaries.test.ts -30 tests/update/update-recovery-host-free.test.ts -208 tests/update/update-refresh.test.ts -35515 tests/update/update-restart-lease.test.ts -48 tests/update/update-service-home-policy.test.ts -139 tests/update/update-service-home.test.ts -85 tests/update/update-standalone.test.ts -1963 tests/update/update-stop-classification.test.ts -7923 tests/update/update-stop-first.test.ts -108 tests/update/update-supervised-recovery.test.ts -2994 tests/update/update-teardown-handover.test.ts -511 tests/update/update-transactional-leftovers.test.ts -631 tests/update/update-transactional.test.ts -1332 tests/update/update-tray-handoff.test.ts -179 tests/update/update-tree-ownership.test.ts -84 tests/update/update-windows-wrapper-authority.test.ts -115 tests/update/update-worker-launch.test.ts -55 tests/usage/anthropic2-usage-attribution.test.ts -93 tests/usage/cache-diagnostic.test.ts -249 tests/usage/cost-cap-unknown-evidence.test.ts -123 tests/usage/cost-scoring.test.ts -67 tests/usage/gpt61-terra-pricing.test.ts -53 tests/usage/jev-stats.test.ts -100 tests/usage/key-attribution.test.ts -355 tests/usage/quota-401-recovery-runtime.test.ts -100 tests/usage/quota-401-recovery.test.ts -2927 tests/usage/quota-pool.test.ts -100 tests/usage/quota-reset-account-key.test.ts -340 tests/usage/quota-reset-core-boundary.test.ts -56 tests/usage/quota-reset-detector.test.ts -63 tests/usage/quota-reset-notify-config.test.ts -410 tests/usage/quota-reset-notify.test.ts -568 tests/usage/quota-reset-observation.test.ts -1755 tests/usage/quota-reset-seen-store.test.ts -105 tests/usage/quota-scoring.test.ts -2776 tests/usage/request-decompress.test.ts -45 tests/usage/request-evidence.test.ts -1729 tests/usage/request-history-index.test.ts -3273 tests/usage/request-history-integrity.test.ts -1387 tests/usage/request-history-rebuild-worker.test.ts -202 tests/usage/request-log-attempt-identity.test.ts -198 tests/usage/request-log-conversation.test.ts -170 tests/usage/request-log-estimate-cap.test.ts -286 tests/usage/request-log-generation-window.test.ts -92 tests/usage/request-log-jev.test.ts -44 tests/usage/request-log-model-filter.test.ts -198 tests/usage/request-log-nonstream.test.ts -112 tests/usage/request-log-normalization.test.ts -135 tests/usage/request-log-protocol-trace.test.ts -134 tests/usage/request-log-served-model.test.ts -568 tests/usage/request-log.test.ts -194 tests/usage/request-outcome-agreement.test.ts -47 tests/usage/request-pacing-provenance.test.ts -235 tests/usage/request-pacing.test.ts -19235 tests/usage/upstream-failure-diagnostics.test.ts -215 tests/usage/usage-aggregate-cache.test.ts -44 tests/usage/usage-anthropic-fast-pricing.test.ts -53 tests/usage/usage-antigravity-55.test.ts -93 tests/usage/usage-attempt-delivery.test.ts -69 tests/usage/usage-cost.test.ts -41 tests/usage/usage-cursor-fast-pricing.test.ts -210 tests/usage/usage-debug.test.ts -46 tests/usage/usage-failure-fingerprint.test.ts -141 tests/usage/usage-failure-persistence.test.ts -40 tests/usage/usage-failure-projection.test.ts -67 tests/usage/usage-haiku-5-5-pricing.test.ts -188 tests/usage/usage-ledger-retention.test.ts -257 tests/usage/usage-ledger-scanner.test.ts -41 tests/usage/usage-log-ws-stage.test.ts -3228 tests/usage/usage-log.test.ts -113 tests/usage/usage-partly-measured-cost.test.ts -42 tests/usage/usage-prompt-length-pricing.test.ts -42 tests/usage/usage-provider-label.test.ts -208 tests/usage/usage-shape-extraction.test.ts -84 tests/usage/usage-snapshot-digest-reuse.test.ts -73 tests/usage/usage-spend-cache-provenance.test.ts -114 tests/usage/usage-summary.test.ts -65 tests/usage/usage-surfaces.test.ts -50 tests/usage/usage-throughput.test.ts -72 tests/usage/usage-time-range.test.ts -2816 tests/usage/usage-timeline.test.ts -100 tests/usage/user-cost-overlay-coderabbit-regressions.test.ts -1520 tests/usage/user-cost-overlay-live-reconcile.test.ts -137 tests/usage/user-cost-overlay-provider-delete.test.ts -87 tests/videos/fulfill-video.test.ts -84 tests/videos/plan-video.test.ts -64 tests/videos/xai-video-client.test.ts -944 tests/vision/mistral-vision-sidecar.test.ts -133 tests/vision/sidecar-abort.test.ts -128 tests/vision/sidecar-auth.test.ts -175 tests/vision/sidecar-candidates.test.ts -394 tests/vision/sidecar-settings-vision-catalog.test.ts -316 tests/vision/sidecar-settings-vision-controls.test.ts -443 tests/vision/sidecar-settings-vision-filter.test.ts -225 tests/vision/sidecar-settings-web-search-gate.test.ts -458 tests/vision/sidecar-settings-web-search-off.test.ts -331 tests/vision/sidecar-settings-web-search-stream.test.ts -46 tests/vision/sidecar-tracker.test.ts -417 tests/vision/vision-anthropic-instance-sidecar.test.ts -157 tests/vision/vision-anthropic.test.ts -248 tests/vision/vision-backend-union.test.ts -176 tests/vision/vision-cache.test.ts -301 tests/vision/vision-custom-row-precedence.test.ts -131 tests/vision/vision-eligibility.test.ts -104 tests/vision/vision-fail-closed.test.ts -300 tests/vision/vision-reasoning-contract.test.ts -802 tests/vision/vision-routed.test.ts -1619 tests/vision/vision-sidecar-e2e.test.ts -192 tests/vision/vision-text-only-predicate.test.ts -97 tests/web-search/devin-web-search.test.ts -45 tests/web-search/fix-search-frame-shapes.test.ts -40 tests/web-search/fix-search-orphan-source.test.ts -41 tests/web-search/fix-search-unicode-clamp.test.ts -147 tests/web-search/format-result.test.ts -304 tests/web-search/web-search-anthropic-instance.test.ts -122 tests/web-search/web-search-anthropic.test.ts -1473 tests/web-search/web-search-backend-union.test.ts -97 tests/web-search/web-search-bridge-replay.test.ts -117 tests/web-search/web-search-candidates.test.ts -47 tests/web-search/web-search-eof.test.ts -137 tests/web-search/web-search-forced-declaration.test.ts -118 tests/web-search/web-search-loop-error-usage.test.ts -103 tests/web-search/web-search-loop-iteration-usage.test.ts -183 tests/web-search/web-search-pacing-deadline.test.ts -108 tests/web-search/web-search-parse.test.ts -395 tests/web-search/web-search-passthrough-bridge.test.ts -2346 tests/web-search/web-search-progress-stream.test.ts -108 tests/web-search/web-search-recovery-kind.test.ts -1604 tests/web-search/web-search-retry-heartbeat.test.ts -148 tests/web-search/web-search-rotation-usage-attribution.test.ts -102 tests/web-search/web-search-run-turn-loop.test.ts -7583 tests/web-search/web-search-sidecar-429.test.ts -269 tests/web-search/web-search-sidecar-replay.test.ts -46 tests/web-search/web-search-sources.test.ts -246 tests/web-search/web-search-terminal-refusal.test.ts -525 tests/web-search/web-search-timeout-contract.test.ts -85 tests/web-search/web-search-timeout-plan.test.ts -5319 tests/web-search/web-search.test.ts -69 tests/windows/coding-agent-native-empty-argv.test.ts -63 tests/windows/tray-proxy-deadline.test.ts -2319 tests/windows/tray-proxy.test.ts +261 tests/server/protocol-trace-suppression.test.ts +198 tests/server/provider-account-quota-routes.test.ts +44 tests/server/provider-egress-management-validation.test.ts +229 tests/server/provider-send-path-import.test.ts +58 tests/server/proxy-env-macos.test.ts +88 tests/server/proxy-env.test.ts +309 tests/server/proxy-liveness-bind-scope.test.ts +90 tests/server/proxy-liveness-owner-evidence.test.ts +106 tests/server/proxy-liveness-package-tree-fence.test.ts +67 tests/server/proxy-liveness-recovery.test.ts +69 tests/server/proxy-liveness.test.ts +4762 tests/server/quota-pool-relay.test.ts +592 tests/server/readyz-features.test.ts +637 tests/server/relay-eager.test.ts +1700 tests/server/replay-refusal-parity.test.ts +432 tests/server/reserve-claude-policy.test.ts +2281 tests/server/reserve-ingress.test.ts +443 tests/server/response-log-inspection.test.ts +543 tests/server/response-model-identity.test.ts +1276 tests/server/restart-replacement-not-ready.test.ts +99 tests/server/restart-replacement.test.ts +171 tests/server/retry-after-429.test.ts +51 tests/server/retry-delay-hardening.test.ts +240 tests/server/route-decision-trace.test.ts +148 tests/server/safe-response-headers.test.ts +1990 tests/server/served-by-header.test.ts +488 tests/server/server-403-permission-e2e.test.ts +270 tests/server/server-agent-task-recovery-replay.test.ts +574 tests/server/server-anthropic-billing-boundaries.test.ts +2350 tests/server/server-anthropic-billing.test.ts +2070 tests/server/server-antigravity-model-denial-recovery.test.ts +474 tests/server/server-antigravity-model-roster-routing.test.ts +153 tests/server/server-antigravity-verify-replay-scope.test.ts +664 tests/server/server-antigravity-web-search-validation.test.ts +357 tests/server/server-auth-localhost-bind.test.ts +1815 tests/server/server-auth-scoped-quota.test.ts +23206 tests/server/server-auth.test.ts +1227 tests/server/server-background-lifecycle.test.ts +611 tests/server/server-chat-native-key-selection.test.ts +301 tests/server/server-cli-key-probe-admission.test.ts +53 tests/server/server-clickjacking-headers.test.ts +473 tests/server/server-combo-cooldown-fallback.test.ts +871 tests/server/server-combo-cooldown-recording.test.ts +10495 tests/server/server-combo-failover-e2e.test.ts +45 tests/server/server-combo-held-response.test.ts +1140 tests/server/server-combo-plan-model-refusal.test.ts +165 tests/server/server-combo-quota-code-provenance.test.ts +3926 tests/server/server-combo-reasoning-replay-eligibility.test.ts +1421 tests/server/server-combo-required-tool-contract.test.ts +399 tests/server/server-combo-stream-hosted-tool-contract.test.ts +772 tests/server/server-combo-stream-required-tool.test.ts +401 tests/server/server-combo-stream-send-contract.test.ts +5134 tests/server/server-combo-tool-loop-continuation.test.ts +468 tests/server/server-combo-zero-output-failover.test.ts +696 tests/server/server-desktop-compatibility-startup.test.ts +711 tests/server/server-generic-oauth-affinity.test.ts +4442 tests/server/server-google-antigravity-oauth-401-replay.test.ts +449 tests/server/server-google-antigravity-oauth-429-budget.test.ts +47 tests/server/server-gui-bundle-freshness.test.ts +168 tests/server/server-images-bodyless-content-length.test.ts +234 tests/server/server-images-pool-admission.test.ts +5976 tests/server/server-images.test.ts +443 tests/server/server-jev-combo-e2e.test.ts +224 tests/server/server-jev-model-decision-e2e.test.ts +412 tests/server/server-jev-model-quota-budget.test.ts +374 tests/server/server-jev-session-pin.test.ts +6138 tests/server/server-key-failover-e2e.test.ts +1509 tests/server/server-kiro-completion-e2e.test.ts +265 tests/server/server-kiro-device-login.test.ts +851 tests/server/server-kiro-oauth-401-replay.test.ts +3546 tests/server/server-kiro-refusal-e2e.test.ts +2118 tests/server/server-kiro-usage-log-e2e.test.ts +470 tests/server/server-live-cancel.test.ts +8811 tests/server/server-live-close.test.ts +492 tests/server/server-live-existing-call.test.ts +186 tests/server/server-live-frame-log.test.ts +1196 tests/server/server-live-realtime-fixtures.test.ts +6046 tests/server/server-live.test.ts +51 tests/server/server-loopback-host-gate.test.ts +1957 tests/server/server-management-auth.test.ts +562 tests/server/server-management-log-admission.test.ts +1541 tests/server/server-native-catalog-priority.test.ts +122 tests/server/server-native-final-log.test.ts +117 tests/server/server-native-reasoning-retention-merge.test.ts +154 tests/server/server-native-reasoning-retention.test.ts +749 tests/server/server-new-model-policy-arrival.test.ts +4876 tests/server/server-ollama-inbound-errors.test.ts +1085 tests/server/server-ollama-inbound-lifecycle.test.ts +1747 tests/server/server-ollama-inbound.test.ts +166 tests/server/server-ollama-route-policy.test.ts +485 tests/server/server-opencode-go-goal-streaming.test.ts +1498 tests/server/server-rate-limit-retry-e2e.test.ts +1134 tests/server/server-request-body-size.test.ts +1817 tests/server/server-search.test.ts +352 tests/server/server-startup-codex-off.test.ts +566 tests/server/server-startup-reconcile-resilience.test.ts +555 tests/server/server-stop-config-hardening.test.ts +329 tests/server/server-terminal-refusal-wiring.test.ts +232 tests/server/server-workflow-budget-settings.test.ts +403 tests/server/server-xai-chat-reasoning-streaming.test.ts +415 tests/server/server-xai-header-parity.test.ts +973 tests/server/server-xai-oauth-401-replay.test.ts +736 tests/server/server-xai-responses-streaming.test.ts +161 tests/server/session-affinity.test.ts +465 tests/server/session-lane-recall-harness.test.ts +209 tests/server/sidebar-routes.test.ts +58 tests/server/sidebar-star-state.test.ts +112 tests/server/spend-instrumentation-log.test.ts +171 tests/server/spend-ledger-lifecycle.test.ts +337 tests/server/spend-ledger-owner-startup.test.ts +127 tests/server/startup-action-control-elevation.test.ts +179 tests/server/startup-action-control.test.ts +11555 tests/server/startup-health-packaged-probe.test.ts +62 tests/server/startup-prompt.test.ts +114 tests/server/stream-aborted-marker.test.ts +197 tests/server/subagent-model-force-api.test.ts +564 tests/server/system-env.test.ts +211 tests/server/system-restart-admission.test.ts +4404 tests/server/system-restart-ownership.test.ts +219 tests/server/system-restart.test.ts +216 tests/server/system-routes.test.ts +4305 tests/server/terminal-guard-server.test.ts +119 tests/server/terminal-guard.test.ts +474 tests/server/turn-state-handles-e2e.test.ts +3327 tests/server/turn-state-handles.test.ts +174 tests/server/update-async-routes.test.ts +53 tests/server/upstream-connect-error.test.ts +2347 tests/server/upstream-error-detail-boundaries.test.ts +102 tests/server/upstream-http-version.test.ts +899 tests/server/v1-hub-state.test.ts +445 tests/server/v2-agent-message-failfast.test.ts +334 tests/service/autostart-health.test.ts +1508 tests/service/connected-stop-capability-auth.test.ts +3142 tests/service/container-bootstrap.test.ts +179 tests/service/crash-guard.test.ts +25287 tests/service/doctor-codex-envkey-readiness.test.ts +127 tests/service/doctor-oauth.test.ts +156 tests/service/doctor-provider-apikey.test.ts +74 tests/service/doctor-service-memory-contract.test.ts +120 tests/service/init-backup-cleanup.test.ts +6542 tests/service/init-eof.test.ts +71 tests/service/launchd-port-fallback.test.ts +372 tests/service/launchd-repair.test.ts +105 tests/service/live-service-manager-guard.test.ts +55 tests/service/managing-cli.test.ts +66 tests/service/ownership-mutation-lease-diagnostics.test.ts +76 tests/service/process-state.test.ts +250 tests/service/service-auth-qualified-localhost.test.ts +84 tests/service/service-child-ownership.test.ts +157 tests/service/service-claim.test.ts +157 tests/service/service-desktop-login-registration.test.ts +5328 tests/service/service-desktop-recovery.test.ts +68 tests/service/service-desktop-runtime-preflight.test.ts +109 tests/service/service-desktop-startup-health.test.ts +206 tests/service/service-desktop-startup-linux.test.ts +185 tests/service/service-desktop-startup.test.ts +129 tests/service/service-desktop-supervision-windows.test.ts +49 tests/service/service-handled-signal-exit.test.ts +122 tests/service/service-health-sentinel-launch.test.ts +46 tests/service/service-health-sentinel-linux.test.ts +51 tests/service/service-health-sentinel-policy.test.ts +7918 tests/service/service-health-sentinel-process.test.ts +424 tests/service/service-health-sentinel-runner.test.ts +126 tests/service/service-install-wrapper-cleanup.test.ts +1830 tests/service/service-log.test.ts +165 tests/service/service-multishell-path.test.ts +47 tests/service/service-ownership-compatibility.test.ts +207 tests/service/service-ownership-handover.test.ts +374 tests/service/service-ownership-state.test.ts +52 tests/service/service-probe-docker.test.ts +63 tests/service/service-proxy-env.test.ts +174 tests/service/service-runtime-preflight.test.ts +184 tests/service/service-secrets.test.ts +175 tests/service/service-sqlite-home.test.ts +43 tests/service/service-start-environment.test.ts +335 tests/service/service-state-isolation.test.ts +2489 tests/service/service-status-json.test.ts +123 tests/service/service-stop-verification.test.ts +553 tests/service/service-tier-capability.test.ts +248 tests/service/service-wsl-home-ownership.test.ts +866 tests/service/service.test.ts +278 tests/service/shutdown-drain.test.ts +9528 tests/service/shutdown-launcher.test.ts +65 tests/service/stale-state-purge.test.ts +106 tests/service/standalone-service.test.ts +24701 tests/service/stop-deferred-teardown.test.ts +403 tests/service/stop-direct-fetch.test.ts +1397 tests/service/stop-restoration-preflight.test.ts +5581 tests/service/stop-restore-history-ownership.test.ts +84 tests/service/systemd-install-cleanup-hardening.test.ts +196 tests/service/winsw.test.ts +3406 tests/storage/api-storage-cleanup.test.ts +1600 tests/storage/api-storage-policy-already-running.test.ts +1936 tests/storage/api-storage-policy-mutation-busy.test.ts +866 tests/storage/api-storage-policy-put-race.test.ts +1164 tests/storage/api-storage-policy-run.test.ts +451 tests/storage/api-storage-policy.test.ts +421 tests/storage/api-storage.test.ts +1194 tests/storage/storage-cleanup.test.ts +6496 tests/storage/storage-mutation-race.test.ts +112 tests/storage/storage-policy-config-race.test.ts +2231 tests/storage/storage-policy-job-responsive.test.ts +107 tests/storage/storage-policy.test.ts +41 tests/storage/storage-restore-job-errors.test.ts +5067 tests/storage/storage-restore-job-responsive.test.ts +187 tests/storage/storage-scanner.test.ts +962 tests/storage/storage-worker-lifecycle.test.ts +60 tests/storage/storage-worker-os-join-settle.test.ts +4305 tests/storage/storage-worker-teardown-isolate.test.ts +510 tests/test-layout-tooling.test.ts +106 tests/test-layout.test.ts +52 tests/update/pnpm-command-isolation.test.ts +69 tests/update/update-badge.test.ts +7648 tests/update/update-bun-ownership-lease.test.ts +84 tests/update/update-capability-policy.test.ts +46 tests/update/update-desktop-badge.test.ts +67 tests/update/update-desktop-owner.test.ts +76 tests/update/update-effect-authority.test.ts +227 tests/update/update-guarded-ops.test.ts +887 tests/update/update-home-launcher.test.ts +50 tests/update/update-home-recovery.test.ts +235 tests/update/update-home-worker.test.ts +138 tests/update/update-job-supervised-restart.test.ts +205 tests/update/update-job.test.ts +69 tests/update/update-mise-launcher-target.test.ts +42 tests/update/update-mise-node-runtime.test.ts +222 tests/update/update-mise.test.ts +151 tests/update/update-mutation-boundaries.test.ts +104 tests/update/update-mutation-guard.test.ts +104 tests/update/update-mutation-scanner.test.ts +70 tests/update/update-notify.test.ts +368 tests/update/update-npm-cache-preflight.test.ts +54 tests/update/update-npm-invocation.test.ts +58 tests/update/update-npm-supervisor-exit.test.ts +54 tests/update/update-npm-timeout.test.ts +44 tests/update/update-orchestrated-apply.test.ts +60 tests/update/update-orchestrated-arguments.test.ts +95964 tests/update/update-orchestrated-entry.test.ts +74 tests/update/update-orchestrated-identity.test.ts +68 tests/update/update-orchestrated-plan.test.ts +2966 tests/update/update-orchestrated-session.test.ts +60 tests/update/update-orchestrated-token.test.ts +123 tests/update/update-pnpm.test.ts +110 tests/update/update-reclaim-authorizer.test.ts +65 tests/update/update-recovery-authority.test.ts +194 tests/update/update-recovery-boundaries.test.ts +52 tests/update/update-recovery-host-free.test.ts +188 tests/update/update-refresh.test.ts +35360 tests/update/update-restart-lease.test.ts +42 tests/update/update-service-home-policy.test.ts +136 tests/update/update-service-home.test.ts +115 tests/update/update-standalone.test.ts +1430 tests/update/update-stop-classification.test.ts +9385 tests/update/update-stop-first.test.ts +47 tests/update/update-supervised-recovery.test.ts +18695 tests/update/update-sync-mutex.test.ts +3709 tests/update/update-teardown-handover.test.ts +544 tests/update/update-transactional-leftovers.test.ts +280 tests/update/update-transactional.test.ts +1709 tests/update/update-tray-handoff.test.ts +238 tests/update/update-tree-ownership.test.ts +70 tests/update/update-windows-wrapper-authority.test.ts +63 tests/update/update-worker-launch.test.ts +62 tests/usage/anthropic2-usage-attribution.test.ts +107 tests/usage/cache-diagnostic.test.ts +334 tests/usage/cost-cap-unknown-evidence.test.ts +83 tests/usage/cost-scoring.test.ts +54 tests/usage/gpt61-terra-pricing.test.ts +47 tests/usage/jev-stats.test.ts +102 tests/usage/key-attribution.test.ts +369 tests/usage/quota-401-recovery-runtime.test.ts +96 tests/usage/quota-401-recovery.test.ts +2298 tests/usage/quota-pool.test.ts +86 tests/usage/quota-reset-account-key.test.ts +374 tests/usage/quota-reset-core-boundary.test.ts +60 tests/usage/quota-reset-detector.test.ts +60 tests/usage/quota-reset-notify-config.test.ts +492 tests/usage/quota-reset-notify.test.ts +531 tests/usage/quota-reset-observation.test.ts +1681 tests/usage/quota-reset-seen-store.test.ts +130 tests/usage/quota-scoring.test.ts +1294 tests/usage/request-decompress.test.ts +53 tests/usage/request-evidence.test.ts +1702 tests/usage/request-history-index.test.ts +3640 tests/usage/request-history-integrity.test.ts +1515 tests/usage/request-history-rebuild-worker.test.ts +139 tests/usage/request-log-attempt-identity.test.ts +113 tests/usage/request-log-conversation.test.ts +125 tests/usage/request-log-error-detail.test.ts +183 tests/usage/request-log-estimate-cap.test.ts +135 tests/usage/request-log-generation-window.test.ts +83 tests/usage/request-log-identity-bounds.test.ts +99 tests/usage/request-log-jev.test.ts +50 tests/usage/request-log-model-filter.test.ts +255 tests/usage/request-log-nonstream.test.ts +139 tests/usage/request-log-normalization.test.ts +94 tests/usage/request-log-protocol-trace.test.ts +115 tests/usage/request-log-served-model.test.ts +515 tests/usage/request-log.test.ts +216 tests/usage/request-outcome-agreement.test.ts +43 tests/usage/request-pacing-provenance.test.ts +218 tests/usage/request-pacing.test.ts +18751 tests/usage/upstream-failure-diagnostics.test.ts +178 tests/usage/usage-aggregate-cache.test.ts +85 tests/usage/usage-anthropic-fast-pricing.test.ts +52 tests/usage/usage-antigravity-55.test.ts +56 tests/usage/usage-attempt-delivery.test.ts +84 tests/usage/usage-cost.test.ts +48 tests/usage/usage-cursor-fast-pricing.test.ts +111 tests/usage/usage-debug.test.ts +54 tests/usage/usage-failure-fingerprint.test.ts +140 tests/usage/usage-failure-persistence.test.ts +43 tests/usage/usage-failure-projection.test.ts +60 tests/usage/usage-haiku-5-5-pricing.test.ts +114 tests/usage/usage-ledger-retention.test.ts +288 tests/usage/usage-ledger-scanner.test.ts +52 tests/usage/usage-log-ws-stage.test.ts +2439 tests/usage/usage-log.test.ts +110 tests/usage/usage-partly-measured-cost.test.ts +47 tests/usage/usage-prompt-length-pricing.test.ts +57 tests/usage/usage-provider-label.test.ts +312 tests/usage/usage-shape-extraction.test.ts +55 tests/usage/usage-snapshot-digest-reuse.test.ts +50 tests/usage/usage-spend-cache-provenance.test.ts +156 tests/usage/usage-summary.test.ts +76 tests/usage/usage-surfaces.test.ts +59 tests/usage/usage-throughput.test.ts +47 tests/usage/usage-time-range.test.ts +3120 tests/usage/usage-timeline.test.ts +104 tests/usage/user-cost-overlay-coderabbit-regressions.test.ts +1277 tests/usage/user-cost-overlay-live-reconcile.test.ts +102 tests/usage/user-cost-overlay-provider-delete.test.ts +66 tests/videos/fulfill-video.test.ts +82 tests/videos/plan-video.test.ts +53 tests/videos/xai-video-client.test.ts +801 tests/vision/mistral-vision-sidecar.test.ts +150 tests/vision/sidecar-abort.test.ts +138 tests/vision/sidecar-auth.test.ts +91 tests/vision/sidecar-candidates.test.ts +456 tests/vision/sidecar-settings-vision-catalog.test.ts +238 tests/vision/sidecar-settings-vision-controls.test.ts +208 tests/vision/sidecar-settings-vision-filter.test.ts +249 tests/vision/sidecar-settings-web-search-gate.test.ts +318 tests/vision/sidecar-settings-web-search-off.test.ts +428 tests/vision/sidecar-settings-web-search-stream.test.ts +65 tests/vision/sidecar-tracker.test.ts +258 tests/vision/vision-anthropic-instance-sidecar.test.ts +173 tests/vision/vision-anthropic.test.ts +326 tests/vision/vision-backend-union.test.ts +166 tests/vision/vision-cache.test.ts +112 tests/vision/vision-custom-row-precedence.test.ts +92 tests/vision/vision-eligibility.test.ts +107 tests/vision/vision-fail-closed.test.ts +223 tests/vision/vision-reasoning-contract.test.ts +539 tests/vision/vision-routed.test.ts +1150 tests/vision/vision-sidecar-e2e.test.ts +103 tests/vision/vision-text-only-predicate.test.ts +119 tests/web-search/devin-web-search.test.ts +51 tests/web-search/fix-search-frame-shapes.test.ts +76 tests/web-search/fix-search-orphan-source.test.ts +82 tests/web-search/fix-search-unicode-clamp.test.ts +50 tests/web-search/format-result.test.ts +245 tests/web-search/web-search-anthropic-instance.test.ts +118 tests/web-search/web-search-anthropic.test.ts +408 tests/web-search/web-search-backend-union.test.ts +118 tests/web-search/web-search-bridge-replay.test.ts +214 tests/web-search/web-search-candidates.test.ts +51 tests/web-search/web-search-eof.test.ts +194 tests/web-search/web-search-forced-declaration.test.ts +106 tests/web-search/web-search-loop-error-usage.test.ts +134 tests/web-search/web-search-loop-iteration-usage.test.ts +169 tests/web-search/web-search-pacing-deadline.test.ts +77 tests/web-search/web-search-parse.test.ts +530 tests/web-search/web-search-passthrough-bridge.test.ts +2384 tests/web-search/web-search-progress-stream.test.ts +120 tests/web-search/web-search-recovery-kind.test.ts +1634 tests/web-search/web-search-retry-heartbeat.test.ts +250 tests/web-search/web-search-rotation-usage-attribution.test.ts +115 tests/web-search/web-search-run-turn-loop.test.ts +7093 tests/web-search/web-search-sidecar-429.test.ts +167 tests/web-search/web-search-sidecar-replay.test.ts +45 tests/web-search/web-search-sources.test.ts +146 tests/web-search/web-search-terminal-refusal.test.ts +449 tests/web-search/web-search-timeout-contract.test.ts +132 tests/web-search/web-search-timeout-plan.test.ts +5338 tests/web-search/web-search.test.ts +68 tests/windows/coding-agent-native-empty-argv.test.ts +53 tests/windows/tray-proxy-deadline.test.ts +2407 tests/windows/tray-proxy.test.ts 49 tests/windows/win-exec.test.ts -39 tests/windows/win-paths.test.ts -44 tests/windows/windows-acl-start-cost.test.ts -44 tests/windows/windows-atomic-replace.test.ts -97 tests/windows/windows-atomic-write-acl-rearm.test.ts -125 tests/windows/windows-codex-cli-job-store.test.ts -67 tests/windows/windows-config-read-acl-memo.test.ts -492 tests/windows/windows-config-root-async-writers.test.ts -48 tests/windows/windows-deploy-close-regressions.test.ts -360 tests/windows/windows-elevation-spawn.test.ts -53 tests/windows/windows-elevation.test.ts -77 tests/windows/windows-guarded-manager.test.ts -68 tests/windows/windows-lifecycle-root-acl.test.ts -75 tests/windows/windows-native-principal.test.ts -216 tests/windows/windows-popup-fix.test.ts +45 tests/windows/win-paths.test.ts +53 tests/windows/windows-acl-start-cost.test.ts +58 tests/windows/windows-atomic-replace.test.ts +94 tests/windows/windows-atomic-write-acl-rearm.test.ts +159 tests/windows/windows-codex-cli-job-store.test.ts +85 tests/windows/windows-config-read-acl-memo.test.ts +525 tests/windows/windows-config-root-async-writers.test.ts +45 tests/windows/windows-deploy-close-regressions.test.ts +370 tests/windows/windows-elevation-spawn.test.ts +48 tests/windows/windows-elevation.test.ts +62 tests/windows/windows-guarded-manager.test.ts +71 tests/windows/windows-lifecycle-root-acl.test.ts +43 tests/windows/windows-native-principal.test.ts +106 tests/windows/windows-popup-fix.test.ts 47 tests/windows/windows-process-priority.test.ts -62 tests/windows/windows-scheduler-errors.test.ts -228 tests/windows/windows-scheduler-install-verification.test.ts -57 tests/windows/windows-secret-acl-diagnostics.test.ts -128 tests/windows/windows-secret-acl-removal-flight.test.ts -355 tests/windows/windows-secret-acl.test.ts -147 tests/windows/windows-service-mutation-lock.test.ts -47 tests/windows/windows-service-wrappers.test.ts -77 tests/windows/windows-text-decoding.test.ts -72 tests/windows/windows-tray-restart-hardening.test.ts -51 tests/windows/windows-tray-run-limit.test.ts -1828 tests/windows/windows-tray.test.ts -116 tests/windows/windows-user-principal-nonascii.test.ts -41 tests/windows/windows-user-principal.test.ts -114 tests/windows/winsw-stop-hardening.test.ts +49 tests/windows/windows-scheduler-errors.test.ts +214 tests/windows/windows-scheduler-install-verification.test.ts +49 tests/windows/windows-secret-acl-diagnostics.test.ts +55 tests/windows/windows-secret-acl-removal-flight.test.ts +333 tests/windows/windows-secret-acl.test.ts +125 tests/windows/windows-service-mutation-lock.test.ts +63 tests/windows/windows-service-wrappers.test.ts +104 tests/windows/windows-text-decoding.test.ts +61 tests/windows/windows-tray-restart-hardening.test.ts +49 tests/windows/windows-tray-run-limit.test.ts +1777 tests/windows/windows-tray.test.ts +96 tests/windows/windows-user-principal-nonascii.test.ts +48 tests/windows/windows-user-principal.test.ts +68 tests/windows/winsw-stop-hardening.test.ts diff --git a/scripts/ci/test-durations.windows.tsv b/scripts/ci/test-durations.windows.tsv index 775d91ec853..6f5aa1aafe0 100644 --- a/scripts/ci/test-durations.windows.tsv +++ b/scripts/ci/test-durations.windows.tsv @@ -1,2857 +1,2872 @@ # Per-file Bun test durations in milliseconds, read from hosted CI job logs. # Consumed by scripts/ci/run-bun-test-batches.sh to balance shards; a file without a row weighs the median. # Regenerate with scripts/ci/test-durations.ts (usage in its header); do not edit by hand. -# Source: run 41437409412 (attempt 1, workflow_dispatch on dev 5cfd0ac11): windows 1/11-11/11 (11/11 failed one assertion; files measured to completion count); prior rows retained for unmeasured files -3673 tests/adapters/abort-race.test.ts -6047 tests/adapters/adapter-buffered-tool-conformance.test.ts -1404 tests/adapters/adapter-error-inline.test.ts -5027 tests/adapters/adapter-inner-send-budget-wiring.test.ts -3455 tests/adapters/adapter-inner-send-budget.test.ts -4299 tests/adapters/adapter-input-media-guard.test.ts -426 tests/adapters/adapter-registry-authority.test.ts -2066 tests/adapters/adapter-tool-conformance.test.ts -206 tests/adapters/adapter-usage.test.ts -18812 tests/adapters/anthropic/anthropic-429-policy.test.ts -141 tests/adapters/anthropic/anthropic-account-metadata.test.ts -1685 tests/adapters/anthropic/anthropic-account-pause-outbound.test.ts -18663 tests/adapters/anthropic/anthropic-account-pause.test.ts -29212 tests/adapters/anthropic/anthropic-account-pool.test.ts -31459 tests/adapters/anthropic/anthropic-account-threshold.test.ts -3056 tests/adapters/anthropic/anthropic-active-limit-routing.test.ts -4592 tests/adapters/anthropic/anthropic-affinity-restart.test.ts -6109 tests/adapters/anthropic/anthropic-affinity-store.test.ts -79 tests/adapters/anthropic/anthropic-agentrouter-language-framing.test.ts -110 tests/adapters/anthropic/anthropic-baseurl-override.test.ts -128 tests/adapters/anthropic/anthropic-beta-allowlist.test.ts -79 tests/adapters/anthropic/anthropic-beta-body-pairs.test.ts -16920 tests/adapters/anthropic/anthropic-billing-ownership.test.ts -333 tests/adapters/anthropic/anthropic-billing-refusal.test.ts -95 tests/adapters/anthropic/anthropic-client-identity.test.ts -6530 tests/adapters/anthropic/anthropic-combo-account-cooldown.test.ts -2646 tests/adapters/anthropic/anthropic-compatible-stream.test.ts -3332 tests/adapters/anthropic/anthropic-cooldown-recovery.test.ts -65 tests/adapters/anthropic/anthropic-empty-content.test.ts -126 tests/adapters/anthropic/anthropic-eof-tolerance.test.ts -981 tests/adapters/anthropic/anthropic-error-body.test.ts -81 tests/adapters/anthropic/anthropic-error-stop-reason.test.ts -3347 tests/adapters/anthropic/anthropic-fast-opt-in.test.ts -79 tests/adapters/anthropic/anthropic-fast-speed.test.ts -63 tests/adapters/anthropic/anthropic-haiku-5-5-contract.test.ts -63 tests/adapters/anthropic/anthropic-hardening.test.ts +# Source: run 41462914814 (workflow_dispatch on dev 09b558580): windows 1/11-11/11 (2/11 and 10/11 failed one assertion each; files measured to completion count); prior rows retained for unmeasured files +3964 tests/adapters/abort-race.test.ts +2174 tests/adapters/adapter-buffered-tool-conformance.test.ts +445 tests/adapters/adapter-error-inline.test.ts +4083 tests/adapters/adapter-inner-send-budget-wiring.test.ts +2985 tests/adapters/adapter-inner-send-budget.test.ts +2260 tests/adapters/adapter-input-media-guard.test.ts +176 tests/adapters/adapter-registry-authority.test.ts +3795 tests/adapters/adapter-tool-conformance.test.ts +1309 tests/adapters/adapter-usage.test.ts +18976 tests/adapters/anthropic/anthropic-429-policy.test.ts +95 tests/adapters/anthropic/anthropic-account-metadata.test.ts +1619 tests/adapters/anthropic/anthropic-account-pause-outbound.test.ts +22367 tests/adapters/anthropic/anthropic-account-pause.test.ts +28662 tests/adapters/anthropic/anthropic-account-pool.test.ts +32339 tests/adapters/anthropic/anthropic-account-threshold.test.ts +4163 tests/adapters/anthropic/anthropic-active-limit-routing.test.ts +7951 tests/adapters/anthropic/anthropic-affinity-restart.test.ts +5590 tests/adapters/anthropic/anthropic-affinity-store.test.ts +2971 tests/adapters/anthropic/anthropic-agentrouter-language-framing.test.ts +143 tests/adapters/anthropic/anthropic-baseurl-override.test.ts +65 tests/adapters/anthropic/anthropic-beta-allowlist.test.ts +142 tests/adapters/anthropic/anthropic-beta-body-pairs.test.ts +24002 tests/adapters/anthropic/anthropic-billing-ownership.test.ts +467 tests/adapters/anthropic/anthropic-billing-refusal.test.ts +97 tests/adapters/anthropic/anthropic-client-identity.test.ts +7890 tests/adapters/anthropic/anthropic-combo-account-cooldown.test.ts +2588 tests/adapters/anthropic/anthropic-compatible-stream.test.ts +3503 tests/adapters/anthropic/anthropic-cooldown-recovery.test.ts +120 tests/adapters/anthropic/anthropic-empty-content.test.ts +129 tests/adapters/anthropic/anthropic-eof-tolerance.test.ts +4429 tests/adapters/anthropic/anthropic-error-body.test.ts +111 tests/adapters/anthropic/anthropic-error-stop-reason.test.ts +5817 tests/adapters/anthropic/anthropic-fast-opt-in.test.ts +96 tests/adapters/anthropic/anthropic-fast-speed.test.ts +80 tests/adapters/anthropic/anthropic-haiku-5-5-contract.test.ts +95 tests/adapters/anthropic/anthropic-hardening.test.ts 175 tests/adapters/anthropic/anthropic-image-guard.test.ts -2092 tests/adapters/anthropic/anthropic-image-normalize.test.ts -7035 tests/adapters/anthropic/anthropic-image-retry-e2e.test.ts -270 tests/adapters/anthropic/anthropic-image-retry.test.ts -18091 tests/adapters/anthropic/anthropic-instance-isolation.test.ts -23342 tests/adapters/anthropic/anthropic-instance-pool-parity.test.ts -45495 tests/adapters/anthropic/anthropic-instance-quota.test.ts -125930 tests/adapters/anthropic/anthropic-instance-recovery.test.ts -80 tests/adapters/anthropic/anthropic-message-stop-termination.test.ts -82 tests/adapters/anthropic/anthropic-messages-passthrough-oauth.test.ts -111 tests/adapters/anthropic/anthropic-messages-passthrough.test.ts -38816 tests/adapters/anthropic/anthropic-model-routes.test.ts -16878 tests/adapters/anthropic/anthropic-model-weekly-admission.test.ts -45 tests/adapters/anthropic/anthropic-opaque-strip.test.ts -79 tests/adapters/anthropic/anthropic-output-maxima.test.ts -66 tests/adapters/anthropic/anthropic-parallel-tool-disable.test.ts -155 tests/adapters/anthropic/anthropic-pool-toggle-copy.test.ts -6680 tests/adapters/anthropic/anthropic-pool-usage-limit.test.ts -301 tests/adapters/anthropic/anthropic-progress-updates.test.ts -10551 tests/adapters/anthropic/anthropic-quota-cooldown-recovery.test.ts -37509 tests/adapters/anthropic/anthropic-quota-dispatch.test.ts -9646 tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts -317 tests/adapters/anthropic/anthropic-reasoning.test.ts -63 tests/adapters/anthropic/anthropic-replay.test.ts -1442 tests/adapters/anthropic/anthropic-reset-grants.test.ts -8675 tests/adapters/anthropic/anthropic-revoked-token-boundaries.test.ts -5961 tests/adapters/anthropic/anthropic-revoked-token-continuation.test.ts -12960 tests/adapters/anthropic/anthropic-revoked-token-sidecars.test.ts -64080 tests/adapters/anthropic/anthropic-revoked-token.test.ts -1168 tests/adapters/anthropic/anthropic-sidecar-account-failover.test.ts -65 tests/adapters/anthropic/anthropic-sonnet-5-5-contract.test.ts -63 tests/adapters/anthropic/anthropic-stream-hardening.test.ts -11768 tests/adapters/anthropic/anthropic-subscription-chain.test.ts +3133 tests/adapters/anthropic/anthropic-image-normalize.test.ts +6423 tests/adapters/anthropic/anthropic-image-retry-e2e.test.ts +1412 tests/adapters/anthropic/anthropic-image-retry.test.ts +22628 tests/adapters/anthropic/anthropic-instance-isolation.test.ts +27724 tests/adapters/anthropic/anthropic-instance-pool-parity.test.ts +40334 tests/adapters/anthropic/anthropic-instance-quota.test.ts +87714 tests/adapters/anthropic/anthropic-instance-recovery.test.ts +111 tests/adapters/anthropic/anthropic-message-stop-termination.test.ts +134 tests/adapters/anthropic/anthropic-messages-passthrough-oauth.test.ts +77 tests/adapters/anthropic/anthropic-messages-passthrough.test.ts +39377 tests/adapters/anthropic/anthropic-model-routes.test.ts +16626 tests/adapters/anthropic/anthropic-model-weekly-admission.test.ts +174 tests/adapters/anthropic/anthropic-opaque-strip.test.ts +299 tests/adapters/anthropic/anthropic-output-maxima.test.ts +79 tests/adapters/anthropic/anthropic-parallel-tool-disable.test.ts +113 tests/adapters/anthropic/anthropic-pool-toggle-copy.test.ts +7134 tests/adapters/anthropic/anthropic-pool-usage-limit.test.ts +476 tests/adapters/anthropic/anthropic-progress-updates.test.ts +9714 tests/adapters/anthropic/anthropic-quota-cooldown-recovery.test.ts +33131 tests/adapters/anthropic/anthropic-quota-dispatch.test.ts +9968 tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts +219 tests/adapters/anthropic/anthropic-reasoning.test.ts +94 tests/adapters/anthropic/anthropic-replay.test.ts +1347 tests/adapters/anthropic/anthropic-reset-grants.test.ts +13433 tests/adapters/anthropic/anthropic-revoked-token-boundaries.test.ts +6110 tests/adapters/anthropic/anthropic-revoked-token-continuation.test.ts +11027 tests/adapters/anthropic/anthropic-revoked-token-sidecars.test.ts +65972 tests/adapters/anthropic/anthropic-revoked-token.test.ts +1253 tests/adapters/anthropic/anthropic-sidecar-account-failover.test.ts +79 tests/adapters/anthropic/anthropic-sonnet-5-5-contract.test.ts +81 tests/adapters/anthropic/anthropic-stream-hardening.test.ts +14013 tests/adapters/anthropic/anthropic-subscription-chain.test.ts 63 tests/adapters/anthropic/anthropic-tail-guard.test.ts -285 tests/adapters/anthropic/anthropic-thinking-signature.test.ts -73 tests/adapters/anthropic/anthropic-thinking-usage.test.ts -62 tests/adapters/anthropic/anthropic-tool-call-id.test.ts -129 tests/adapters/anthropic/anthropic-tool-declaration-constraints.test.ts -64 tests/adapters/anthropic/anthropic-tool-schema.test.ts -10072 tests/adapters/anthropic/anthropic2-fast-parity.test.ts -159 tests/adapters/bridge-legacy-shell-normalization.test.ts -3758 tests/adapters/bridge-lifecycle.test.ts -183 tests/adapters/bridge-nonstreaming-terminal.test.ts -423 tests/adapters/bridge-raw-reasoning-hidden.test.ts -3173 tests/adapters/bridge-reasoning-replay-batch.test.ts -1042 tests/adapters/bridge-stall.test.ts -201 tests/adapters/bridge-terminal-refusal.test.ts -80 tests/adapters/bridge-terminal-singleness.test.ts -365 tests/adapters/bridge.test.ts -127 tests/adapters/buffered-response-shape-guards.test.ts -222 tests/adapters/coding-agent-history-projection.test.ts -221 tests/adapters/coding-agent-tool-result-images.test.ts -272 tests/adapters/coding-agent-windows-dispatch.test.ts +174 tests/adapters/anthropic/anthropic-thinking-signature.test.ts +97 tests/adapters/anthropic/anthropic-thinking-usage.test.ts +80 tests/adapters/anthropic/anthropic-tool-call-id.test.ts +267 tests/adapters/anthropic/anthropic-tool-declaration-constraints.test.ts +80 tests/adapters/anthropic/anthropic-tool-schema.test.ts +10323 tests/adapters/anthropic/anthropic2-fast-parity.test.ts +185 tests/adapters/bridge-legacy-shell-normalization.test.ts +3726 tests/adapters/bridge-lifecycle.test.ts +2710 tests/adapters/bridge-nonstreaming-terminal.test.ts +106 tests/adapters/bridge-raw-reasoning-hidden.test.ts +981 tests/adapters/bridge-reasoning-replay-batch.test.ts +3027 tests/adapters/bridge-stall.test.ts +1290 tests/adapters/bridge-terminal-refusal.test.ts +225 tests/adapters/bridge-terminal-singleness.test.ts +267 tests/adapters/bridge.test.ts +84 tests/adapters/buffered-response-shape-guards.test.ts +230 tests/adapters/coding-agent-history-projection.test.ts +227 tests/adapters/coding-agent-tool-result-images.test.ts +128 tests/adapters/coding-agent-windows-dispatch.test.ts 96 tests/adapters/dsh-account-adapter.test.ts -2893 tests/adapters/empty-tool-output-annotation.test.ts -111 tests/adapters/exec-tool-result-normalize.test.ts -293 tests/adapters/fix-tool-number-preservation.test.ts -1267 tests/adapters/google/antigravity-account-roster.test.ts -134 tests/adapters/google/antigravity-baseurl-override.test.ts -174 tests/adapters/google/antigravity-discovered-families.test.ts -47 tests/adapters/google/antigravity-refusal.test.ts -2963 tests/adapters/google/antigravity-routing-carry.test.ts -141 tests/adapters/google/antigravity-static-catalog.test.ts -901 tests/adapters/google/gcp-adc.test.ts -12340 tests/adapters/google/gcp-credential-boundary.test.ts -1356 tests/adapters/google/gcp-sa-adapter.test.ts -23094 tests/adapters/google/gcp-sa-marker.test.ts -207 tests/adapters/google/gemini-37-flash-migration.test.ts -161 tests/adapters/google/gemini-4-argon-antigravity.test.ts -80 tests/adapters/google/gemini-progress-history.test.ts -175 tests/adapters/google/gemini-web-search.test.ts -256 tests/adapters/google/google-adapter.test.ts -64 tests/adapters/google/google-ai-studio-foreign-call-signature.test.ts -4457 tests/adapters/google/google-antigravity-oauth.test.ts -2673 tests/adapters/google/google-antigravity-replay.test.ts -129 tests/adapters/google/google-antigravity-wire.test.ts -79 tests/adapters/google/google-buffered-stop-reason.test.ts -95 tests/adapters/google/google-claude-prefill-guard.test.ts -95 tests/adapters/google/google-empty-content.test.ts -82 tests/adapters/google/google-errors.test.ts -79 tests/adapters/google/google-hardening.test.ts -686 tests/adapters/google/google-models-listing.test.ts -49 tests/adapters/google/google-output-clamp.test.ts -61 tests/adapters/google/google-provider-metadata-roundtrip.test.ts -299 tests/adapters/google/google-signature-history-roundtrip.test.ts -109 tests/adapters/google/google-stream-fragmentation.test.ts -96 tests/adapters/google/google-strict-tool-validated-mode.test.ts -62 tests/adapters/google/google-structured-output.test.ts -98 tests/adapters/google/google-tool-result-adjacency.test.ts -80 tests/adapters/google/google-tool-schema-contract.test.ts +4452 tests/adapters/empty-tool-output-annotation.test.ts +285 tests/adapters/exec-tool-result-normalize.test.ts +253 tests/adapters/fix-tool-number-preservation.test.ts +1444 tests/adapters/google/antigravity-account-roster.test.ts +111 tests/adapters/google/antigravity-baseurl-override.test.ts +141 tests/adapters/google/antigravity-discovered-families.test.ts +233 tests/adapters/google/antigravity-refusal.test.ts +3056 tests/adapters/google/antigravity-routing-carry.test.ts +143 tests/adapters/google/antigravity-static-catalog.test.ts +1074 tests/adapters/google/gcp-adc.test.ts +13931 tests/adapters/google/gcp-credential-boundary.test.ts +951 tests/adapters/google/gcp-sa-adapter.test.ts +19259 tests/adapters/google/gcp-sa-marker.test.ts +81 tests/adapters/google/gemini-37-flash-migration.test.ts +128 tests/adapters/google/gemini-4-argon-antigravity.test.ts +251 tests/adapters/google/gemini-progress-history.test.ts +141 tests/adapters/google/gemini-web-search.test.ts +158 tests/adapters/google/google-adapter.test.ts +130 tests/adapters/google/google-ai-studio-foreign-call-signature.test.ts +4353 tests/adapters/google/google-antigravity-oauth.test.ts +2675 tests/adapters/google/google-antigravity-replay.test.ts +113 tests/adapters/google/google-antigravity-wire.test.ts +95 tests/adapters/google/google-buffered-stop-reason.test.ts +96 tests/adapters/google/google-claude-prefill-guard.test.ts +65 tests/adapters/google/google-empty-content.test.ts +67 tests/adapters/google/google-errors.test.ts +111 tests/adapters/google/google-hardening.test.ts +586 tests/adapters/google/google-models-listing.test.ts +236 tests/adapters/google/google-output-clamp.test.ts +78 tests/adapters/google/google-provider-metadata-roundtrip.test.ts +188 tests/adapters/google/google-signature-history-roundtrip.test.ts +76 tests/adapters/google/google-stream-fragmentation.test.ts +95 tests/adapters/google/google-strict-tool-validated-mode.test.ts +80 tests/adapters/google/google-structured-output.test.ts +97 tests/adapters/google/google-tool-result-adjacency.test.ts +127 tests/adapters/google/google-tool-schema-contract.test.ts 110 tests/adapters/google/google-tool-schema.test.ts -4576 tests/adapters/google/google-vertex-http.test.ts -127 tests/adapters/google/google-vertex-key-project.test.ts -111 tests/adapters/google/google-vertex-stream.test.ts -128 tests/adapters/google/google-vertex-thought-signature.test.ts +4772 tests/adapters/google/google-vertex-http.test.ts +143 tests/adapters/google/google-vertex-key-project.test.ts +96 tests/adapters/google/google-vertex-stream.test.ts +125 tests/adapters/google/google-vertex-thought-signature.test.ts 95 tests/adapters/google/google-wire-compiler.test.ts -113 tests/adapters/google/google-wire-shape.test.ts -251 tests/adapters/google/vertex-catalog.test.ts -468 tests/adapters/identity-neutralize.test.ts -939 tests/adapters/identity-subagent.test.ts -13932 tests/adapters/key-failover.test.ts -441 tests/adapters/openai/inline-think-boundaries.test.ts -8290 tests/adapters/openai/openai-api-virtual-models.test.ts -98 tests/adapters/openai/openai-chat-audio.test.ts -364 tests/adapters/openai/openai-chat-bounded-tool-names.test.ts -63 tests/adapters/openai/openai-chat-dangling-toolcalls.test.ts -249 tests/adapters/openai/openai-chat-developer-position.test.ts -130 tests/adapters/openai/openai-chat-eof.test.ts -94 tests/adapters/openai/openai-chat-glm-summary.test.ts -397 tests/adapters/openai/openai-chat-hardening.test.ts -5681 tests/adapters/openai/openai-chat-image-normalization.test.ts -97 tests/adapters/openai/openai-chat-inline-think-tags.test.ts -94 tests/adapters/openai/openai-chat-invalid-tool-call-diagnostics.test.ts +99 tests/adapters/google/google-wire-shape.test.ts +236 tests/adapters/google/vertex-catalog.test.ts +350 tests/adapters/identity-neutralize.test.ts +1604 tests/adapters/identity-subagent.test.ts +14364 tests/adapters/key-failover.test.ts +108 tests/adapters/openai/inline-think-boundaries.test.ts +6187 tests/adapters/openai/openai-api-virtual-models.test.ts +78 tests/adapters/openai/openai-chat-audio.test.ts +235 tests/adapters/openai/openai-chat-bounded-tool-names.test.ts +78 tests/adapters/openai/openai-chat-dangling-toolcalls.test.ts +64 tests/adapters/openai/openai-chat-developer-position.test.ts +94 tests/adapters/openai/openai-chat-eof.test.ts +126 tests/adapters/openai/openai-chat-glm-summary.test.ts +316 tests/adapters/openai/openai-chat-hardening.test.ts +5625 tests/adapters/openai/openai-chat-image-normalization.test.ts +106 tests/adapters/openai/openai-chat-inline-think-tags.test.ts +128 tests/adapters/openai/openai-chat-invalid-tool-call-diagnostics.test.ts 174 tests/adapters/openai/openai-chat-mistral-content.test.ts -142 tests/adapters/openai/openai-chat-model-suffix.test.ts -1679 tests/adapters/openai/openai-chat-native-policy.test.ts -177 tests/adapters/openai/openai-chat-nonce-tool-call-content.test.ts -142 tests/adapters/openai/openai-chat-parallel-stream.test.ts -159 tests/adapters/openai/openai-chat-path-override.test.ts -96 tests/adapters/openai/openai-chat-qwen38-leading-system.test.ts -125 tests/adapters/openai/openai-chat-reasoning-wire-policy.test.ts -126 tests/adapters/openai/openai-chat-required-tool.test.ts -223 tests/adapters/openai/openai-chat-sanitization-review-regressions.test.ts -80 tests/adapters/openai/openai-chat-serialized-tool-call-content.test.ts -316 tests/adapters/openai/openai-chat-serialized-tool-call-hold-bound.test.ts -125 tests/adapters/openai/openai-chat-serialized-tool-call-scaling.test.ts -110 tests/adapters/openai/openai-chat-serialized-tool-call-think.test.ts -112 tests/adapters/openai/openai-chat-single-system.test.ts -508 tests/adapters/openai/openai-chat-standalone-bare-block.test.ts -238 tests/adapters/openai/openai-chat-system-order.test.ts -94 tests/adapters/openai/openai-chat-tool-call-id-remint.test.ts -48 tests/adapters/openai/openai-chat-tool-result-images.test.ts -47 tests/adapters/openai/openai-chat-url.test.ts -66 tests/adapters/openai/openai-chat-video-part.test.ts -190 tests/adapters/openai/openai-empty-assistant-history.test.ts -410 tests/adapters/openai/openai-native-hosted-search-history.test.ts -4752 tests/adapters/openai/openai-provider-option-e2e.test.ts -1066 tests/adapters/openai/openai-provider-option-migration.test.ts -266 tests/adapters/openai/openai-provider-option-startup.test.ts -127 tests/adapters/openai/openai-provider-option-tooling.test.ts -79 tests/adapters/openai/openai-provider-option.test.ts -96 tests/adapters/openai/opengateway-input.test.ts -394 tests/adapters/physical-send.test.ts -183 tests/adapters/qoder-spawn-readmission.test.ts -95 tests/adapters/reasoning-replay-identity.test.ts -272 tests/adapters/reasoning-replay-robustness.test.ts -551 tests/adapters/routed-agent-messages.test.ts -233 tests/adapters/run-turn-queue.test.ts -2671 tests/adapters/terminal-continuation-owner-rotation.test.ts -95 tests/adapters/tool-argument-integers.test.ts -246 tests/adapters/tool-catalog-nudge.test.ts -246 tests/adapters/tool-choice-performance.test.ts -230 tests/adapters/tool-envelope-echo-whole-line.test.ts -79 tests/adapters/tool-identity-hash.test.ts -284 tests/adapters/translator-budget-lifetime.test.ts -5578 tests/adapters/translator-budget.test.ts -63 tests/adapters/upstream-http-error.test.ts -108 tests/adapters/workbuddy-adapter.test.ts -1320 tests/advisor/advisor-adaptive.test.ts -63 tests/advisor/advisor-authority-transport.test.ts -1187 tests/advisor/advisor-budget.test.ts -1880 tests/advisor/advisor-caller-policy-compact.test.ts -2821 tests/advisor/advisor-caller-policy-host-key.test.ts -2053 tests/advisor/advisor-caller-policy-http.test.ts -839 tests/advisor/advisor-caller-policy-ingress.test.ts -1889 tests/advisor/advisor-caller-policy-jev.test.ts -881 tests/advisor/advisor-caller-policy-replay.test.ts -3815 tests/advisor/advisor-caller-policy-routing.test.ts -2283 tests/advisor/advisor-caller-policy-self-fetch.test.ts -1158 tests/advisor/advisor-caller-policy-sidecar-authority.test.ts -1738 tests/advisor/advisor-caller-policy-vision.test.ts -5560 tests/advisor/advisor-caller-policy.test.ts -95 tests/advisor/advisor-consult.test.ts -81 tests/advisor/advisor-context.test.ts -79 tests/advisor/advisor-continuation-limit.test.ts -599 tests/advisor/advisor-core-boundary.test.ts -167 tests/advisor/advisor-evidence.test.ts -266 tests/advisor/advisor-guard.test.ts -191 tests/advisor/advisor-internal-authority.test.ts -303 tests/advisor/advisor-plan.test.ts -11627 tests/advisor/advisor-responses-wiring.test.ts -381 tests/advisor/advisor-retention.test.ts -1697 tests/advisor/advisor-scope-transport.test.ts -368 tests/advisor/advisor-settings.test.ts -108 tests/advisor/advisor-state.test.ts -273 tests/advisor/advisor-web-search.test.ts -101 tests/ci-workflows/assert-mergeable-review.test.ts -221 tests/ci-workflows/brand-favicons.test.ts -84 tests/ci-workflows/build-desktop-icon-set.test.ts -270 tests/ci-workflows/build-release-changelog.test.ts -351 tests/ci-workflows/bump-dev-version.test.ts -860 tests/ci-workflows/bun-runtime.test.ts -63 tests/ci-workflows/ci-bun-crash-classifier.test.ts -82 tests/ci-workflows/ci-bun-install-frozen.test.ts -93 tests/ci-workflows/ci-concurrency-groups.test.ts -64 tests/ci-workflows/ci-crash-disposition.test.ts -5324 tests/ci-workflows/ci-gui-typecheck-gate.test.ts -190 tests/ci-workflows/ci-pr-hygiene-approvals.test.ts -46 tests/ci-workflows/ci-privacy-gate.test.ts -440 tests/ci-workflows/ci-review-lanes.test.ts -1583 tests/ci-workflows/ci-scope-gaps.test.ts -91 tests/ci-workflows/ci-scope-reduction.test.ts -147 tests/ci-workflows/ci-shard-balance.test.ts -80 tests/ci-workflows/ci-structure-gate.test.ts -63 tests/ci-workflows/ci-test-lane.test.ts -902 tests/ci-workflows/ci-workflows.test.ts -81 tests/ci-workflows/cleanup-orphaned-workflows.test.ts -356 tests/ci-workflows/client-support-matrix.test.ts -2105 tests/ci-workflows/client-support-runtime.test.ts -91 tests/ci-workflows/closed-pr-branch-cleanup.test.ts -6492 tests/ci-workflows/cold-spawn-warmup.test.ts -428 tests/ci-workflows/compatibility-version.test.ts -64 tests/ci-workflows/docs-429-failover-claims.test.ts -63 tests/ci-workflows/docs-bun-source-requirement.test.ts -112 tests/ci-workflows/docs-developer-role-policy.test.ts -47 tests/ci-workflows/docs-gjc-reasoning-export.test.ts -97 tests/ci-workflows/docs-gpt61-terra.test.ts -77 tests/ci-workflows/docs-gui-screenshot-policy.test.ts -348 tests/ci-workflows/docs-link-targets.test.ts -81 tests/ci-workflows/docs-provider-billing-claims.test.ts -127 tests/ci-workflows/docs-provider-discovery-limits.test.ts -81 tests/ci-workflows/docs-provider-preset-counts.test.ts -286 tests/ci-workflows/docs-readme-memory-inventory.test.ts -50 tests/ci-workflows/docs-readme-translation-parity.test.ts -64 tests/ci-workflows/docs-remote-hub-claims.test.ts -300 tests/ci-workflows/dsh-path-contract.test.ts -495 tests/ci-workflows/dsh-rc6-compat-script.test.ts -538 tests/ci-workflows/dsh-writer-lock.test.ts -60 tests/ci-workflows/exhaustive-deps-suppression.test.ts -569 tests/ci-workflows/file-size-ratchet.test.ts -476 tests/ci-workflows/fixture-dir-uniqueness.test.ts -107 tests/ci-workflows/fixture-teardown-helper.test.ts -1149 tests/ci-workflows/fixture-windows-runtime-preload.test.ts -361 tests/ci-workflows/import-cycle-ratchet.test.ts -160 tests/ci-workflows/install-scripts.test.ts -81 tests/ci-workflows/installed-gate-drivers.test.ts -269 tests/ci-workflows/keyring-smoke.test.ts -151 tests/ci-workflows/linux-desktop-packaged-ci.test.ts -81 tests/ci-workflows/linux-desktop-packaged-e2e.test.ts -110 tests/ci-workflows/macos-serial-lanes.test.ts -4578 tests/ci-workflows/package-tree-fenced-restart.test.ts -5865 tests/ci-workflows/package-tree-integrity.test.ts -158 tests/ci-workflows/package-tree-restart-ownership.test.ts -257 tests/ci-workflows/package-tree-retarget.test.ts -255 tests/ci-workflows/pr-readiness-reattest.test.ts -47 tests/ci-workflows/privacy-scan-asset-names.test.ts -79 tests/ci-workflows/privacy-scan-meta-key.test.ts -240 tests/ci-workflows/privacy-scan-ssh-endpoint.test.ts -245 tests/ci-workflows/release-desktop-scripts.test.ts -31335 tests/ci-workflows/release-helper.test.ts -238 tests/ci-workflows/release-notes.test.ts -250 tests/ci-workflows/release-outcome-report.test.ts -504 tests/ci-workflows/release-pipeline-contract.test.ts -234 tests/ci-workflows/release-preflight.test.ts -80 tests/ci-workflows/release-resume-identity.test.ts -125 tests/ci-workflows/release-version-line.test.ts -301 tests/ci-workflows/release-version-sources.test.ts -10799 tests/ci-workflows/release-windows-signing.test.ts -710 tests/ci-workflows/repo-hygiene.test.ts -735 tests/ci-workflows/repo-import-resolution.test.ts -2104 tests/ci-workflows/setup-hooks.test.ts -742 tests/ci-workflows/skill-ocx-generated.test.ts -366 tests/ci-workflows/skill-ocx-workflows.test.ts -143 tests/ci-workflows/skill-ocx.test.ts -2256 tests/ci-workflows/structure-ssot.test.ts -2725 tests/ci-workflows/test-home-guard-unpreloaded.test.ts -53892 tests/ci-workflows/test-home-guard.test.ts -24725 tests/ci-workflows/test-run-lock-generation.test.ts -269 tests/ci-workflows/test-runner-bun.test.ts -96 tests/ci-workflows/test-runner-spawnsync-finalizer.test.ts -26971 tests/ci-workflows/test-runner.test.ts -63 tests/ci-workflows/test-sandbox-cleanup.test.ts -94 tests/ci-workflows/test-temp-quarantine.test.ts -238 tests/ci-workflows/version-line.test.ts -143 tests/ci-workflows/warmup-registration.test.ts -228 tests/ci-workflows/zz-ci-api-usage-isolation.test.ts -65 tests/ci-workflows/zz-ci-storage-policy-isolation.test.ts -91 tests/ci-workflows/zz-pr-coderabbit-readiness-revalidation.test.ts -67818 tests/claude-integration/anthropic2-native-routing.test.ts -9481 tests/claude-integration/claude-529-mapping.test.ts -270 tests/claude-integration/claude-agent-startup-sync.test.ts -437 tests/claude-integration/claude-agents-inject-client.test.ts -476 tests/claude-integration/claude-agents-inject.test.ts -242 tests/claude-integration/claude-alias.test.ts -78 tests/claude-integration/claude-auth-detect.test.ts -129 tests/claude-integration/claude-auth-mode.test.ts -79 tests/claude-integration/claude-authmode-migration.test.ts -13886 tests/claude-integration/claude-bridge-pool-dispatch.test.ts -238 tests/claude-integration/claude-bridge-pool-session.test.ts -2720 tests/claude-integration/claude-cli-picker-surface.test.ts -1138 tests/claude-integration/claude-cli-picker.test.ts -191 tests/claude-integration/claude-cli.test.ts -12303 tests/claude-integration/claude-client-refusal-status.test.ts -1662 tests/claude-integration/claude-code-thought-signature-scope.test.ts -93 tests/claude-integration/claude-compatibility.test.ts -586 tests/claude-integration/claude-config-home-isolation.test.ts -3914 tests/claude-integration/claude-config-root-late-admission.test.ts -4211 tests/claude-integration/claude-config-root-stale-updates.test.ts -3004 tests/claude-integration/claude-config-root-writer-barrier.test.ts -161 tests/claude-integration/claude-context-accounting.test.ts -142 tests/claude-integration/claude-context-windows.test.ts -316 tests/claude-integration/claude-desktop-1m.test.ts -55591 tests/claude-integration/claude-desktop-cli.test.ts -2672 tests/claude-integration/claude-desktop-config-path.test.ts -11697 tests/claude-integration/claude-desktop-discovery.test.ts -20367 tests/claude-integration/claude-desktop-first-party-guards.test.ts -56348 tests/claude-integration/claude-desktop-first-party.test.ts -239 tests/claude-integration/claude-desktop-mode-explanation.test.ts -7802 tests/claude-integration/claude-desktop-model-visibility.test.ts -205 tests/claude-integration/claude-desktop-native-context.test.ts -18610 tests/claude-integration/claude-desktop-picker-profile.test.ts -33195 tests/claude-integration/claude-desktop-picker-routes.test.ts -6320 tests/claude-integration/claude-desktop-picker.test.ts -158 tests/claude-integration/claude-desktop-policy.test.ts -36306 tests/claude-integration/claude-desktop-remote-hub.test.ts -458 tests/claude-integration/claude-desktop-system-proxy.test.ts -4687 tests/claude-integration/claude-devin-output-order.test.ts -300 tests/claude-integration/claude-dotenv-provenance-transport.test.ts -3657 tests/claude-integration/claude-estimate-projection.test.ts -17227 tests/claude-integration/claude-first-party-agent-sync.test.ts -31211 tests/claude-integration/claude-first-party-union.test.ts -127 tests/claude-integration/claude-gateway-cache.test.ts -3868 tests/claude-integration/claude-gateway-output-cap.test.ts -2527 tests/claude-integration/claude-inbound-cache-stabilize.test.ts -242 tests/claude-integration/claude-inbound-debug.test.ts -82 tests/claude-integration/claude-inbound-token-footer.test.ts -4251 tests/claude-integration/claude-inbound-tool-loading.test.ts +126 tests/adapters/openai/openai-chat-model-suffix.test.ts +1567 tests/adapters/openai/openai-chat-native-policy.test.ts +112 tests/adapters/openai/openai-chat-nonce-tool-call-content.test.ts +111 tests/adapters/openai/openai-chat-parallel-stream.test.ts +127 tests/adapters/openai/openai-chat-path-override.test.ts +95 tests/adapters/openai/openai-chat-qwen38-leading-system.test.ts +190 tests/adapters/openai/openai-chat-reasoning-wire-policy.test.ts +112 tests/adapters/openai/openai-chat-required-tool.test.ts +252 tests/adapters/openai/openai-chat-sanitization-review-regressions.test.ts +129 tests/adapters/openai/openai-chat-serialized-tool-call-content.test.ts +380 tests/adapters/openai/openai-chat-serialized-tool-call-hold-bound.test.ts +189 tests/adapters/openai/openai-chat-serialized-tool-call-scaling.test.ts +97 tests/adapters/openai/openai-chat-serialized-tool-call-think.test.ts +91 tests/adapters/openai/openai-chat-single-system.test.ts +522 tests/adapters/openai/openai-chat-standalone-bare-block.test.ts +190 tests/adapters/openai/openai-chat-system-order.test.ts +111 tests/adapters/openai/openai-chat-tool-call-id-remint.test.ts +78 tests/adapters/openai/openai-chat-tool-result-images.test.ts +80 tests/adapters/openai/openai-chat-url.test.ts +78 tests/adapters/openai/openai-chat-video-part.test.ts +174 tests/adapters/openai/openai-empty-assistant-history.test.ts +380 tests/adapters/openai/openai-native-hosted-search-history.test.ts +4428 tests/adapters/openai/openai-provider-option-e2e.test.ts +795 tests/adapters/openai/openai-provider-option-migration.test.ts +252 tests/adapters/openai/openai-provider-option-startup.test.ts +50 tests/adapters/openai/openai-provider-option-tooling.test.ts +64 tests/adapters/openai/openai-provider-option.test.ts +78 tests/adapters/openai/opengateway-input.test.ts +440 tests/adapters/physical-send.test.ts +259 tests/adapters/qoder-spawn-readmission.test.ts +271 tests/adapters/reasoning-replay-identity.test.ts +253 tests/adapters/reasoning-replay-robustness.test.ts +318 tests/adapters/routed-agent-messages.test.ts +247 tests/adapters/run-turn-queue.test.ts +2754 tests/adapters/terminal-continuation-owner-rotation.test.ts +235 tests/adapters/tool-argument-integers.test.ts +80 tests/adapters/tool-catalog-nudge.test.ts +95 tests/adapters/tool-choice-performance.test.ts +79 tests/adapters/tool-envelope-echo-whole-line.test.ts +89 tests/adapters/tool-identity-hash.test.ts +655 tests/adapters/translator-budget-lifetime.test.ts +5444 tests/adapters/translator-budget.test.ts +180 tests/adapters/upstream-http-error.test.ts +144 tests/adapters/workbuddy-adapter.test.ts +1818 tests/advisor/advisor-adaptive.test.ts +94 tests/advisor/advisor-authority-transport.test.ts +1454 tests/advisor/advisor-budget.test.ts +2343 tests/advisor/advisor-caller-policy-compact.test.ts +2166 tests/advisor/advisor-caller-policy-host-key.test.ts +2297 tests/advisor/advisor-caller-policy-http.test.ts +1030 tests/advisor/advisor-caller-policy-ingress.test.ts +2694 tests/advisor/advisor-caller-policy-jev.test.ts +1213 tests/advisor/advisor-caller-policy-replay.test.ts +4410 tests/advisor/advisor-caller-policy-routing.test.ts +3050 tests/advisor/advisor-caller-policy-self-fetch.test.ts +1365 tests/advisor/advisor-caller-policy-sidecar-authority.test.ts +1596 tests/advisor/advisor-caller-policy-vision.test.ts +6095 tests/advisor/advisor-caller-policy.test.ts +220 tests/advisor/advisor-consult.test.ts +111 tests/advisor/advisor-context.test.ts +234 tests/advisor/advisor-continuation-limit.test.ts +522 tests/advisor/advisor-core-boundary.test.ts +110 tests/advisor/advisor-evidence.test.ts +82 tests/advisor/advisor-guard.test.ts +193 tests/advisor/advisor-internal-authority.test.ts +115 tests/advisor/advisor-plan.test.ts +11893 tests/advisor/advisor-responses-wiring.test.ts +508 tests/advisor/advisor-retention.test.ts +1821 tests/advisor/advisor-scope-transport.test.ts +375 tests/advisor/advisor-settings.test.ts +309 tests/advisor/advisor-state.test.ts +156 tests/advisor/advisor-web-search.test.ts +82 tests/ci-workflows/assert-mergeable-review.test.ts +95 tests/ci-workflows/brand-favicons.test.ts +79 tests/ci-workflows/build-desktop-icon-set.test.ts +286 tests/ci-workflows/build-release-changelog.test.ts +429 tests/ci-workflows/bump-dev-version.test.ts +902 tests/ci-workflows/bun-runtime.test.ts +142 tests/ci-workflows/ci-bun-crash-classifier.test.ts +68 tests/ci-workflows/ci-bun-install-frozen.test.ts +80 tests/ci-workflows/ci-concurrency-groups.test.ts +80 tests/ci-workflows/ci-crash-disposition.test.ts +4360 tests/ci-workflows/ci-gui-typecheck-gate.test.ts +264 tests/ci-workflows/ci-pr-hygiene-approvals.test.ts +64 tests/ci-workflows/ci-privacy-gate.test.ts +384 tests/ci-workflows/ci-review-lanes.test.ts +1425 tests/ci-workflows/ci-scope-gaps.test.ts +79 tests/ci-workflows/ci-scope-reduction.test.ts +204 tests/ci-workflows/ci-shard-balance.test.ts +64 tests/ci-workflows/ci-structure-gate.test.ts +79 tests/ci-workflows/ci-test-lane.test.ts +743 tests/ci-workflows/ci-workflows.test.ts +111 tests/ci-workflows/cleanup-orphaned-workflows.test.ts +534 tests/ci-workflows/client-support-matrix.test.ts +2243 tests/ci-workflows/client-support-runtime.test.ts +81 tests/ci-workflows/closed-pr-branch-cleanup.test.ts +6582 tests/ci-workflows/cold-spawn-warmup.test.ts +269 tests/ci-workflows/compatibility-version.test.ts +79 tests/ci-workflows/docs-429-failover-claims.test.ts +226 tests/ci-workflows/docs-bun-source-requirement.test.ts +269 tests/ci-workflows/docs-developer-role-policy.test.ts +176 tests/ci-workflows/docs-gjc-reasoning-export.test.ts +95 tests/ci-workflows/docs-gpt61-terra.test.ts +94 tests/ci-workflows/docs-gui-screenshot-policy.test.ts +285 tests/ci-workflows/docs-link-targets.test.ts +64 tests/ci-workflows/docs-provider-billing-claims.test.ts +125 tests/ci-workflows/docs-provider-discovery-limits.test.ts +16 tests/ci-workflows/docs-provider-preset-counts.test.ts +208 tests/ci-workflows/docs-readme-memory-inventory.test.ts +97 tests/ci-workflows/docs-readme-translation-parity.test.ts +79 tests/ci-workflows/docs-remote-hub-claims.test.ts +222 tests/ci-workflows/dsh-path-contract.test.ts +1513 tests/ci-workflows/dsh-rc6-compat-script.test.ts +682 tests/ci-workflows/dsh-writer-lock.test.ts +79 tests/ci-workflows/exhaustive-deps-suppression.test.ts +487 tests/ci-workflows/file-size-ratchet.test.ts +395 tests/ci-workflows/fixture-dir-uniqueness.test.ts +110 tests/ci-workflows/fixture-teardown-helper.test.ts +1333 tests/ci-workflows/fixture-windows-runtime-preload.test.ts +554 tests/ci-workflows/import-cycle-ratchet.test.ts +256 tests/ci-workflows/install-scripts.test.ts +98 tests/ci-workflows/installed-gate-drivers.test.ts +95 tests/ci-workflows/keyring-smoke.test.ts +47 tests/ci-workflows/linux-desktop-packaged-ci.test.ts +96 tests/ci-workflows/linux-desktop-packaged-e2e.test.ts +89 tests/ci-workflows/macos-serial-lanes.test.ts +4880 tests/ci-workflows/package-tree-fenced-restart.test.ts +5953 tests/ci-workflows/package-tree-integrity.test.ts +253 tests/ci-workflows/package-tree-restart-ownership.test.ts +160 tests/ci-workflows/package-tree-retarget.test.ts +154 tests/ci-workflows/pr-readiness-reattest.test.ts +79 tests/ci-workflows/privacy-scan-asset-names.test.ts +63 tests/ci-workflows/privacy-scan-meta-key.test.ts +82 tests/ci-workflows/privacy-scan-ssh-endpoint.test.ts +205 tests/ci-workflows/release-desktop-scripts.test.ts +27725 tests/ci-workflows/release-helper.test.ts +196 tests/ci-workflows/release-notes.test.ts +91 tests/ci-workflows/release-outcome-report.test.ts +681 tests/ci-workflows/release-pipeline-contract.test.ts +81 tests/ci-workflows/release-preflight.test.ts +76 tests/ci-workflows/release-resume-identity.test.ts +326 tests/ci-workflows/release-version-line.test.ts +238 tests/ci-workflows/release-version-sources.test.ts +11390 tests/ci-workflows/release-windows-signing.test.ts +586 tests/ci-workflows/repo-hygiene.test.ts +679 tests/ci-workflows/repo-import-resolution.test.ts +2108 tests/ci-workflows/setup-hooks.test.ts +1049 tests/ci-workflows/skill-ocx-generated.test.ts +495 tests/ci-workflows/skill-ocx-workflows.test.ts +127 tests/ci-workflows/skill-ocx.test.ts +3524 tests/ci-workflows/structure-ssot.test.ts +2231 tests/ci-workflows/test-home-guard-unpreloaded.test.ts +59710 tests/ci-workflows/test-home-guard.test.ts +24471 tests/ci-workflows/test-run-lock-generation.test.ts +238 tests/ci-workflows/test-runner-bun.test.ts +79 tests/ci-workflows/test-runner-spawnsync-finalizer.test.ts +28754 tests/ci-workflows/test-runner.test.ts +240 tests/ci-workflows/test-sandbox-cleanup.test.ts +64 tests/ci-workflows/test-temp-quarantine.test.ts +126 tests/ci-workflows/version-line.test.ts +129 tests/ci-workflows/warmup-registration.test.ts +79 tests/ci-workflows/zz-ci-api-usage-isolation.test.ts +79 tests/ci-workflows/zz-ci-storage-policy-isolation.test.ts +95 tests/ci-workflows/zz-pr-coderabbit-readiness-revalidation.test.ts +64668 tests/claude-integration/anthropic2-native-routing.test.ts +9449 tests/claude-integration/claude-529-mapping.test.ts +222 tests/claude-integration/claude-agent-startup-sync.test.ts +238 tests/claude-integration/claude-agents-inject-client.test.ts +459 tests/claude-integration/claude-agents-inject.test.ts +175 tests/claude-integration/claude-alias.test.ts +80 tests/claude-integration/claude-auth-detect.test.ts +270 tests/claude-integration/claude-auth-mode.test.ts +78 tests/claude-integration/claude-authmode-migration.test.ts +17193 tests/claude-integration/claude-bridge-pool-dispatch.test.ts +285 tests/claude-integration/claude-bridge-pool-session.test.ts +2201 tests/claude-integration/claude-cli-picker-surface.test.ts +1191 tests/claude-integration/claude-cli-picker.test.ts +196 tests/claude-integration/claude-cli.test.ts +16434 tests/claude-integration/claude-client-refusal-status.test.ts +1650 tests/claude-integration/claude-code-thought-signature-scope.test.ts +65 tests/claude-integration/claude-compatibility.test.ts +626 tests/claude-integration/claude-config-home-isolation.test.ts +4835 tests/claude-integration/claude-config-root-late-admission.test.ts +2030 tests/claude-integration/claude-config-root-stale-updates.test.ts +1851 tests/claude-integration/claude-config-root-writer-barrier.test.ts +193 tests/claude-integration/claude-context-accounting.test.ts +418 tests/claude-integration/claude-context-windows.test.ts +219 tests/claude-integration/claude-desktop-1m.test.ts +49560 tests/claude-integration/claude-desktop-cli.test.ts +4056 tests/claude-integration/claude-desktop-config-path.test.ts +13103 tests/claude-integration/claude-desktop-discovery.test.ts +14395 tests/claude-integration/claude-desktop-first-party-guards.test.ts +56646 tests/claude-integration/claude-desktop-first-party.test.ts +269 tests/claude-integration/claude-desktop-mode-explanation.test.ts +10135 tests/claude-integration/claude-desktop-model-visibility.test.ts +222 tests/claude-integration/claude-desktop-native-context.test.ts +16029 tests/claude-integration/claude-desktop-picker-profile.test.ts +33508 tests/claude-integration/claude-desktop-picker-routes.test.ts +7042 tests/claude-integration/claude-desktop-picker.test.ts +79 tests/claude-integration/claude-desktop-policy.test.ts +36297 tests/claude-integration/claude-desktop-remote-hub.test.ts +444 tests/claude-integration/claude-desktop-system-proxy.test.ts +6040 tests/claude-integration/claude-devin-output-order.test.ts +218 tests/claude-integration/claude-dotenv-provenance-transport.test.ts +3886 tests/claude-integration/claude-estimate-projection.test.ts +23658 tests/claude-integration/claude-first-party-agent-sync.test.ts +39670 tests/claude-integration/claude-first-party-union.test.ts +277 tests/claude-integration/claude-gateway-cache.test.ts +2456 tests/claude-integration/claude-gateway-output-cap.test.ts +3239 tests/claude-integration/claude-inbound-cache-stabilize.test.ts +80 tests/claude-integration/claude-inbound-debug.test.ts +144 tests/claude-integration/claude-inbound-token-footer.test.ts +4143 tests/claude-integration/claude-inbound-tool-loading.test.ts 127 tests/claude-integration/claude-inbound-tool-reference.test.ts -312 tests/claude-integration/claude-inbound.test.ts -3687 tests/claude-integration/claude-installation-helper.test.ts -2629 tests/claude-integration/claude-intercept-acl-barrier.test.ts -112 tests/claude-integration/claude-intercept-cleanup.test.ts -174 tests/claude-integration/claude-intercept-client-class.test.ts -24827 tests/claude-integration/claude-intercept-local-ca-files.test.ts -7897 tests/claude-integration/claude-intercept-local-ca-windows.test.ts -13691 tests/claude-integration/claude-intercept-local-ca.test.ts -1155 tests/claude-integration/claude-intercept-model-bindings.test.ts -4762 tests/claude-integration/claude-intercept-no-proxy.test.ts -17462 tests/claude-integration/claude-intercept-on-demand.test.ts -5078 tests/claude-integration/claude-intercept-proxy-auth.test.ts -188 tests/claude-integration/claude-intercept-proxy.test.ts -2031 tests/claude-integration/claude-intercept-settings.test.ts -95 tests/claude-integration/claude-long-context-eligibility.test.ts -150870 tests/claude-integration/claude-management-api.test.ts -108197 tests/claude-integration/claude-messages-endpoint.test.ts -3805 tests/claude-integration/claude-messages-thread.test.ts -3681 tests/claude-integration/claude-model-default-labels.test.ts -510 tests/claude-integration/claude-model-info.test.ts -25934 tests/claude-integration/claude-models-discovery.test.ts -8966 tests/claude-integration/claude-native-affinity.test.ts -5423 tests/claude-integration/claude-native-fast-1m-ingress.test.ts -146239 tests/claude-integration/claude-native-passthrough.test.ts -366 tests/claude-integration/claude-native-rate-limit-headers.test.ts -173 tests/claude-integration/claude-native-reasoning-continuity.test.ts -936 tests/claude-integration/claude-native-reasoning-provenance.test.ts -24006 tests/claude-integration/claude-outbound.test.ts -175 tests/claude-integration/claude-output-schema-strict.test.ts -254 tests/claude-integration/claude-picker-bootstrap.test.ts -15580 tests/claude-integration/claude-picker-ca-store.test.ts -14360 tests/claude-integration/claude-picker-ca.test.ts -126 tests/claude-integration/claude-picker-linger.test.ts -734 tests/claude-integration/claude-picker-listener.test.ts -240 tests/claude-integration/claude-picker-models.test.ts -10949 tests/claude-integration/claude-picker-recovery.test.ts -14016 tests/claude-integration/claude-picker-relay-intent.test.ts -41747 tests/claude-integration/claude-picker-runtime.test.ts -35499 tests/claude-integration/claude-picker-startup.test.ts -299 tests/claude-integration/claude-picker-trust-windows.test.ts -64 tests/claude-integration/claude-picker-trust.test.ts -4019 tests/claude-integration/claude-picker-upload.test.ts -40308 tests/claude-integration/claude-picker-windows.test.ts -6011 tests/claude-integration/claude-prompt-too-long.test.ts -191 tests/claude-integration/claude-shell-hook.test.ts -301 tests/claude-integration/claude-sidecar-override.test.ts -158 tests/claude-integration/claude-source-envelope.test.ts -424 tests/claude-integration/claude-subagent-model-force.test.ts -236 tests/claude-integration/claude-system-env-auto.test.ts -3856 tests/claude-integration/claude-tool-loading-destinations.test.ts -792 tests/claude-integration/claude-translated-cache-ttl.test.ts -2478 tests/claude-integration/claude-translated-server-tools.test.ts -5054 tests/claude-integration/claude-translated-tool-restrictions.test.ts -2715 tests/claude-integration/messages-native-clean-eof.test.ts -1091 tests/claude-integration/messages-native-decline-trace.test.ts -15443 tests/claude-integration/messages-native-empty-inline.test.ts -11071 tests/claude-integration/messages-native-key-selection.test.ts -65012 tests/claude-integration/messages-native-oauth.test.ts -4464 tests/claude-integration/messages-native-opaque-state.test.ts -18027 tests/claude-integration/messages-native-scope.test.ts -46501 tests/claude-integration/messages-native.test.ts -56875 tests/claude-integration/messages-request-id-endpoint.test.ts -143 tests/claude-integration/messages-request-id-headers.test.ts -46348 tests/claude-integration/messages-revoked-token.test.ts -412 tests/claude-integration/messages-shared-sse.test.ts -209 tests/claude-integration/messages-surface-matrix.test.ts -50 tests/cli/agent-driven.test.ts -142 tests/cli/agent-subagent-force.test.ts -2241 tests/cli/bun-transpiler-cache-scope.test.ts -128 tests/cli/claude-config-first-party.test.ts -24194 tests/cli/cli-access-audio-live.test.ts -976 tests/cli/cli-access-audio.test.ts -418 tests/cli/cli-access-data-plane.test.ts -159 tests/cli/cli-access-key-guard.test.ts -538 tests/cli/cli-access-rename.test.ts -162 tests/cli/cli-account-alias-target.test.ts -126 tests/cli/cli-account-cancel-flow.test.ts -128 tests/cli/cli-account-key-pause.test.ts -159 tests/cli/cli-account-key-quota.test.ts -174 tests/cli/cli-account-kiro-device.test.ts -867 tests/cli/cli-account-login-options.test.ts -78 tests/cli/cli-account-orca-import.test.ts -215 tests/cli/cli-account-pin-drain.test.ts -1850 tests/cli/cli-account-policy.test.ts -160 tests/cli/cli-account-pool-verbs.test.ts -111 tests/cli/cli-account-preservation.test.ts -365 tests/cli/cli-account-slot-identity.test.ts -143 tests/cli/cli-account-threshold.test.ts -444 tests/cli/cli-account-verify-status.test.ts -1094 tests/cli/cli-account.test.ts -841 tests/cli/cli-agent-runtime-settings.test.ts -2012 tests/cli/cli-agent-settings.test.ts -139 tests/cli/cli-alias-json.test.ts -141 tests/cli/cli-anthropic-account-threshold.test.ts -173 tests/cli/cli-anthropic2-account.test.ts -160 tests/cli/cli-api-protocols.test.ts -267 tests/cli/cli-aside-sync.test.ts -128 tests/cli/cli-capabilities-arguments.test.ts -302 tests/cli/cli-capabilities.test.ts -176 tests/cli/cli-capability-access-workflows.test.ts -204 tests/cli/cli-capability-account-workflows.test.ts -492 tests/cli/cli-capability-agent-workflows.test.ts -8416 tests/cli/cli-capability-data.test.ts -365 tests/cli/cli-capability-integration-workflows.test.ts -204 tests/cli/cli-capability-lab-workflows.test.ts -388 tests/cli/cli-capability-operation-workflows.test.ts -143 tests/cli/cli-capability-provider-workflows.test.ts -186 tests/cli/cli-catalog-command-result.test.ts -168 tests/cli/cli-catalog-prewarm.test.ts -2921 tests/cli/cli-claude-desktop-profile.test.ts -188 tests/cli/cli-client-start-fence.test.ts -786 tests/cli/cli-client-start-owner-e2e.test.ts -3176 tests/cli/cli-codex-cli-update-boundary.test.ts -161 tests/cli/cli-codex-cli-update.test.ts -174 tests/cli/cli-codex-log-guard-compact.test.ts -190 tests/cli/cli-codex-log-guard-protection.test.ts -221 tests/cli/cli-codex-log-guard.test.ts -2215 tests/cli/cli-combo-parity.test.ts -127 tests/cli/cli-combo-partial-update.test.ts -2280 tests/cli/cli-combo-session-pin.test.ts -2043 tests/cli/cli-combo-set-targets.test.ts -440 tests/cli/cli-combo-stats.test.ts -301 tests/cli/cli-companion-timeline.test.ts -472 tests/cli/cli-companion-usage.test.ts -79 tests/cli/cli-companion.test.ts -1908 tests/cli/cli-config-bom.test.ts -7247 tests/cli/cli-config-command.test.ts -2327 tests/cli/cli-config-default-show.test.ts -2230 tests/cli/cli-config-show-client.test.ts -16109 tests/cli/cli-connect-readiness.test.ts -5191 tests/cli/cli-dispatch.test.ts -127 tests/cli/cli-dto-fidelity.test.ts -901 tests/cli/cli-effort-slug.test.ts -3296 tests/cli/cli-effort.test.ts -222 tests/cli/cli-ensure-client-state.test.ts -127 tests/cli/cli-ensure-desktop-cold-start.test.ts -80 tests/cli/cli-ensure-readiness.test.ts -1262 tests/cli/cli-export-command.test.ts -386 tests/cli/cli-export-model-names.test.ts -82 tests/cli/cli-fallback.test.ts -111 tests/cli/cli-head.test.ts -2026 tests/cli/cli-headless-parity.test.ts -4366 tests/cli/cli-help-navigation.test.ts -22618 tests/cli/cli-help-paths.test.ts -9548 tests/cli/cli-help-recovery.test.ts -14854 tests/cli/cli-help.test.ts -943 tests/cli/cli-init-port.test.ts -172 tests/cli/cli-injection-follow.test.ts -95 tests/cli/cli-integer-options.test.ts -189 tests/cli/cli-integration-cursor.test.ts -251 tests/cli/cli-integration-droid.test.ts -1693 tests/cli/cli-integration-journal.test.ts -2322 tests/cli/cli-integration-preview.test.ts -190 tests/cli/cli-json-contract.test.ts -397 tests/cli/cli-json-input.test.ts -95 tests/cli/cli-kiro-auto-selection.test.ts -284 tests/cli/cli-link-child.test.ts -1440 tests/cli/cli-link-cleanup.test.ts -127 tests/cli/cli-link-enrollment.test.ts -474 tests/cli/cli-link-force.test.ts -189 tests/cli/cli-link.test.ts -300 tests/cli/cli-log-follow.test.ts -175 tests/cli/cli-log-history.test.ts -349 tests/cli/cli-log-view-filter.test.ts -222 tests/cli/cli-logout-runtime.test.ts -144 tests/cli/cli-logs-request-id.test.ts -239 tests/cli/cli-management-auth.test.ts -279 tests/cli/cli-message-mcp.test.ts -2029 tests/cli/cli-models-custom-runtime.test.ts -332 tests/cli/cli-models-display-name.test.ts -143 tests/cli/cli-models-free-only.test.ts -1618 tests/cli/cli-models-local-result.test.ts -175 tests/cli/cli-models-order.test.ts -113 tests/cli/cli-models-price.test.ts -209 tests/cli/cli-models-prompt-length-pricing.test.ts -714 tests/cli/cli-models-reasoning.test.ts -125 tests/cli/cli-models-runtime-dispatch.test.ts -143 tests/cli/cli-models-set.test.ts -21968 tests/cli/cli-models.test.ts -224 tests/cli/cli-native-profile.test.ts -125 tests/cli/cli-observe-logs.test.ts +268 tests/claude-integration/claude-inbound.test.ts +2818 tests/claude-integration/claude-installation-helper.test.ts +3469 tests/claude-integration/claude-intercept-acl-barrier.test.ts +176 tests/claude-integration/claude-intercept-cleanup.test.ts +494 tests/claude-integration/claude-intercept-client-class.test.ts +25361 tests/claude-integration/claude-intercept-local-ca-files.test.ts +7114 tests/claude-integration/claude-intercept-local-ca-windows.test.ts +25665 tests/claude-integration/claude-intercept-local-ca.test.ts +1217 tests/claude-integration/claude-intercept-model-bindings.test.ts +4094 tests/claude-integration/claude-intercept-no-proxy.test.ts +15401 tests/claude-integration/claude-intercept-on-demand.test.ts +10845 tests/claude-integration/claude-intercept-proxy-auth.test.ts +189 tests/claude-integration/claude-intercept-proxy.test.ts +2048 tests/claude-integration/claude-intercept-settings.test.ts +144 tests/claude-integration/claude-long-context-eligibility.test.ts +158610 tests/claude-integration/claude-management-api.test.ts +101345 tests/claude-integration/claude-messages-endpoint.test.ts +4087 tests/claude-integration/claude-messages-thread.test.ts +3217 tests/claude-integration/claude-model-default-labels.test.ts +699 tests/claude-integration/claude-model-info.test.ts +26155 tests/claude-integration/claude-models-discovery.test.ts +14563 tests/claude-integration/claude-native-affinity.test.ts +6145 tests/claude-integration/claude-native-fast-1m-ingress.test.ts +141928 tests/claude-integration/claude-native-passthrough.test.ts +222 tests/claude-integration/claude-native-rate-limit-headers.test.ts +208 tests/claude-integration/claude-native-reasoning-continuity.test.ts +8415 tests/claude-integration/claude-native-reasoning-provenance.test.ts +21648 tests/claude-integration/claude-outbound.test.ts +176 tests/claude-integration/claude-output-schema-strict.test.ts +507 tests/claude-integration/claude-picker-bootstrap.test.ts +22201 tests/claude-integration/claude-picker-ca-store.test.ts +13406 tests/claude-integration/claude-picker-ca.test.ts +127 tests/claude-integration/claude-picker-linger.test.ts +955 tests/claude-integration/claude-picker-listener.test.ts +239 tests/claude-integration/claude-picker-models.test.ts +11805 tests/claude-integration/claude-picker-recovery.test.ts +16973 tests/claude-integration/claude-picker-relay-intent.test.ts +41345 tests/claude-integration/claude-picker-runtime.test.ts +34309 tests/claude-integration/claude-picker-startup.test.ts +287 tests/claude-integration/claude-picker-trust-windows.test.ts +80 tests/claude-integration/claude-picker-trust.test.ts +3966 tests/claude-integration/claude-picker-upload.test.ts +46377 tests/claude-integration/claude-picker-windows.test.ts +5410 tests/claude-integration/claude-prompt-too-long.test.ts +173 tests/claude-integration/claude-shell-hook.test.ts +364 tests/claude-integration/claude-sidecar-override.test.ts +127 tests/claude-integration/claude-source-envelope.test.ts +159 tests/claude-integration/claude-subagent-model-force.test.ts +269 tests/claude-integration/claude-system-env-auto.test.ts +5279 tests/claude-integration/claude-tool-loading-destinations.test.ts +1143 tests/claude-integration/claude-translated-cache-ttl.test.ts +2441 tests/claude-integration/claude-translated-server-tools.test.ts +5401 tests/claude-integration/claude-translated-tool-restrictions.test.ts +2856 tests/claude-integration/messages-native-clean-eof.test.ts +1173 tests/claude-integration/messages-native-decline-trace.test.ts +13428 tests/claude-integration/messages-native-empty-inline.test.ts +17108 tests/claude-integration/messages-native-key-selection.test.ts +55037 tests/claude-integration/messages-native-oauth.test.ts +2818 tests/claude-integration/messages-native-opaque-state.test.ts +13006 tests/claude-integration/messages-native-scope.test.ts +54653 tests/claude-integration/messages-native.test.ts +100301 tests/claude-integration/messages-request-id-endpoint.test.ts +174 tests/claude-integration/messages-request-id-headers.test.ts +40530 tests/claude-integration/messages-revoked-token.test.ts +364 tests/claude-integration/messages-shared-sse.test.ts +479 tests/claude-integration/messages-surface-matrix.test.ts +221 tests/cli/agent-driven.test.ts +143 tests/cli/agent-subagent-force.test.ts +3759 tests/cli/bun-transpiler-cache-scope.test.ts +207 tests/cli/claude-config-first-party.test.ts +24244 tests/cli/cli-access-audio-live.test.ts +618 tests/cli/cli-access-audio.test.ts +191 tests/cli/cli-access-data-plane.test.ts +333 tests/cli/cli-access-key-guard.test.ts +913 tests/cli/cli-access-rename.test.ts +173 tests/cli/cli-account-alias-target.test.ts +286 tests/cli/cli-account-cancel-flow.test.ts +345 tests/cli/cli-account-key-pause.test.ts +253 tests/cli/cli-account-key-quota.test.ts +356 tests/cli/cli-account-kiro-device.test.ts +838 tests/cli/cli-account-login-options.test.ts +48 tests/cli/cli-account-orca-import.test.ts +126 tests/cli/cli-account-pin-drain.test.ts +2278 tests/cli/cli-account-policy.test.ts +159 tests/cli/cli-account-pool-verbs.test.ts +129 tests/cli/cli-account-preservation.test.ts +142 tests/cli/cli-account-slot-identity.test.ts +126 tests/cli/cli-account-threshold.test.ts +237 tests/cli/cli-account-verify-status.test.ts +1075 tests/cli/cli-account.test.ts +1125 tests/cli/cli-agent-runtime-settings.test.ts +1893 tests/cli/cli-agent-settings.test.ts +110 tests/cli/cli-alias-json.test.ts +146 tests/cli/cli-anthropic-account-threshold.test.ts +114 tests/cli/cli-anthropic2-account.test.ts +207 tests/cli/cli-api-protocols.test.ts +255 tests/cli/cli-aside-sync.test.ts +142 tests/cli/cli-capabilities-arguments.test.ts +237 tests/cli/cli-capabilities.test.ts +174 tests/cli/cli-capability-access-workflows.test.ts +192 tests/cli/cli-capability-account-workflows.test.ts +477 tests/cli/cli-capability-agent-workflows.test.ts +9855 tests/cli/cli-capability-data.test.ts +311 tests/cli/cli-capability-integration-workflows.test.ts +364 tests/cli/cli-capability-lab-workflows.test.ts +567 tests/cli/cli-capability-operation-workflows.test.ts +235 tests/cli/cli-capability-provider-workflows.test.ts +143 tests/cli/cli-catalog-command-result.test.ts +81 tests/cli/cli-catalog-prewarm.test.ts +2983 tests/cli/cli-claude-desktop-profile.test.ts +159 tests/cli/cli-client-start-fence.test.ts +1091 tests/cli/cli-client-start-owner-e2e.test.ts +2675 tests/cli/cli-codex-cli-update-boundary.test.ts +190 tests/cli/cli-codex-cli-update.test.ts +110 tests/cli/cli-codex-log-guard-compact.test.ts +126 tests/cli/cli-codex-log-guard-protection.test.ts +388 tests/cli/cli-codex-log-guard.test.ts +2183 tests/cli/cli-combo-parity.test.ts +280 tests/cli/cli-combo-partial-update.test.ts +1993 tests/cli/cli-combo-session-pin.test.ts +2134 tests/cli/cli-combo-set-targets.test.ts +238 tests/cli/cli-combo-stats.test.ts +283 tests/cli/cli-companion-timeline.test.ts +254 tests/cli/cli-companion-usage.test.ts +111 tests/cli/cli-companion.test.ts +1491 tests/cli/cli-config-bom.test.ts +7592 tests/cli/cli-config-command.test.ts +2851 tests/cli/cli-config-default-show.test.ts +3149 tests/cli/cli-config-show-client.test.ts +13766 tests/cli/cli-connect-readiness.test.ts +5324 tests/cli/cli-dispatch.test.ts +161 tests/cli/cli-dto-fidelity.test.ts +889 tests/cli/cli-effort-slug.test.ts +2359 tests/cli/cli-effort.test.ts +207 tests/cli/cli-ensure-client-state.test.ts +254 tests/cli/cli-ensure-desktop-cold-start.test.ts +63 tests/cli/cli-ensure-readiness.test.ts +1817 tests/cli/cli-export-command.test.ts +225 tests/cli/cli-export-model-names.test.ts +128 tests/cli/cli-fallback.test.ts +142 tests/cli/cli-head.test.ts +1839 tests/cli/cli-headless-parity.test.ts +4621 tests/cli/cli-help-navigation.test.ts +19017 tests/cli/cli-help-paths.test.ts +7111 tests/cli/cli-help-recovery.test.ts +21817 tests/cli/cli-help.test.ts +1329 tests/cli/cli-init-port.test.ts +206 tests/cli/cli-injection-follow.test.ts +126 tests/cli/cli-integer-options.test.ts +223 tests/cli/cli-integration-cursor.test.ts +171 tests/cli/cli-integration-droid.test.ts +1633 tests/cli/cli-integration-journal.test.ts +2761 tests/cli/cli-integration-preview.test.ts +488 tests/cli/cli-json-contract.test.ts +444 tests/cli/cli-json-input.test.ts +127 tests/cli/cli-kiro-auto-selection.test.ts +539 tests/cli/cli-link-child.test.ts +1870 tests/cli/cli-link-cleanup.test.ts +159 tests/cli/cli-link-enrollment.test.ts +730 tests/cli/cli-link-force.test.ts +509 tests/cli/cli-link.test.ts +422 tests/cli/cli-log-follow.test.ts +125 tests/cli/cli-log-history.test.ts +380 tests/cli/cli-log-view-filter.test.ts +238 tests/cli/cli-logout-runtime.test.ts +159 tests/cli/cli-logs-request-id.test.ts +269 tests/cli/cli-management-auth.test.ts +94 tests/cli/cli-message-mcp.test.ts +2094 tests/cli/cli-models-custom-runtime.test.ts +302 tests/cli/cli-models-display-name.test.ts +286 tests/cli/cli-models-free-only.test.ts +1712 tests/cli/cli-models-local-result.test.ts +318 tests/cli/cli-models-order.test.ts +161 tests/cli/cli-models-price.test.ts +359 tests/cli/cli-models-prompt-length-pricing.test.ts +650 tests/cli/cli-models-reasoning.test.ts +159 tests/cli/cli-models-runtime-dispatch.test.ts +156 tests/cli/cli-models-set.test.ts +14996 tests/cli/cli-models.test.ts +462 tests/cli/cli-native-profile.test.ts +141 tests/cli/cli-observe-logs.test.ts 174 tests/cli/cli-observe-snapshot.test.ts -96 tests/cli/cli-path-diagnostics.test.ts -1330 tests/cli/cli-provider-batch.test.ts -356 tests/cli/cli-provider-cc-switch-import.test.ts -222 tests/cli/cli-provider-lifecycle-runtime.test.ts -3600 tests/cli/cli-provider-list-active.test.ts -130 tests/cli/cli-provider-result.test.ts -534 tests/cli/cli-provider-settings.test.ts -4775 tests/cli/cli-provider-sync-result.test.ts -40750 tests/cli/cli-provider.test.ts -2345 tests/cli/cli-ready-subprocess.test.ts -119 tests/cli/cli-ready.test.ts -274 tests/cli/cli-registry.test.ts -365 tests/cli/cli-remote-workspace-hub.test.ts -3499 tests/cli/cli-resolve-subprocess.test.ts -100 tests/cli/cli-resolve.test.ts -450 tests/cli/cli-restart-handoff.test.ts -4136 tests/cli/cli-restart-health.test.ts -6136 tests/cli/cli-restore-back.test.ts -12918 tests/cli/cli-role-suggestion-history.test.ts -77 tests/cli/cli-route-policy-not-found.test.ts -1293 tests/cli/cli-route-policy-write.test.ts -8839 tests/cli/cli-start-auxiliary-bind.test.ts -177986 tests/cli/cli-start-journal-order.test.ts -32773 tests/cli/cli-start-owner-absence.test.ts -12752 tests/cli/cli-start-owner-evidence.test.ts -79 tests/cli/cli-start-routing-heal-wiring.test.ts -207 tests/cli/cli-status-codex-routing-drift.test.ts -3560 tests/cli/cli-status-hub-state.test.ts -44038 tests/cli/cli-status-json.test.ts -522 tests/cli/cli-status-oauth-health.test.ts -1802 tests/cli/cli-status-startup-health.test.ts -271 tests/cli/cli-stop-json.test.ts -408 tests/cli/cli-stop-refusal-transport.test.ts -399 tests/cli/cli-storage-inspect.test.ts -1312 tests/cli/cli-storage-policy-fields.test.ts -26151 tests/cli/cli-sync-expect-link.test.ts -508 tests/cli/cli-system-health.test.ts -191 tests/cli/cli-system-settings-parity.test.ts -363 tests/cli/cli-transport-honesty.test.ts -1361 tests/cli/cli-update-badge.test.ts -1790 tests/cli/cli-update-restart-admission.test.ts -80 tests/cli/cli-update-restart-child.test.ts -153 tests/cli/cli-update-restart-desktop-service.test.ts -331 tests/cli/cli-update-restart-home.test.ts -189 tests/cli/cli-update-restart-service-record.test.ts -223 tests/cli/cli-update-restart-supervision.test.ts -898 tests/cli/cli-update-restart-transport.test.ts -210 tests/cli/cli-update-restart.test.ts -4219 tests/cli/cli-usage-compare.test.ts -160 tests/cli/cli-usage-hub.test.ts -414 tests/cli/cli-usage-model-search.test.ts -177 tests/cli/cli-usage-report.test.ts -396 tests/cli/cli-usage-scope.test.ts -1811 tests/cli/cli-usage-top.test.ts -15573 tests/cli/cli-v2-runtime.test.ts -10739 tests/cli/cli-version-skew.test.ts -222 tests/cli/cross-home-loopback-family.test.ts -809 tests/cli/ensure-desired-integrations-race.test.ts -1915 tests/cli/hub-disable.test.ts -1220 tests/cli/hub-gated-local-clients.test.ts -439 tests/cli/hub-invite.test.ts -170 tests/cli/interactive-confirm.test.ts -189 tests/cli/link-apply-restart.test.ts -1455 tests/cli/local-credentials.test.ts -191 tests/cli/model-selection-guidance.test.ts -318 tests/cli/ocx-launcher-desktop-handoff.test.ts -80 tests/cli/ocx-launcher-fixture-trust.test.ts -42955 tests/cli/ocx-launcher-runtime.test.ts -48 tests/cli/ocx-launcher-source.test.ts -224 tests/cli/ocx-run.test.ts -12583 tests/cli/restore-completes-shared-teardown.test.ts -3201 tests/cli/route-explainability.test.ts -24592 tests/cli/sibling-home-client-sync.test.ts -109 tests/cli/star-deferral.test.ts -399 tests/cli/start-args.test.ts -206 tests/cli/start-ownership-publication.test.ts -681 tests/cli/status-install-method.test.ts -110 tests/cli/system-restart-client-package-tree.test.ts -105 tests/cli/system-restart-client.test.ts -25141 tests/cli/uninstall.test.ts -3647 tests/clients/agent-clients.test.ts -144 tests/clients/aside-profile-identity.test.ts -705 tests/clients/aside-profile-paths.test.ts -3902 tests/clients/aside-profile-sync-owner.test.ts -1890 tests/clients/aside-profiles-catalog-refresh.test.ts -12727 tests/clients/aside-profiles.test.ts -130 tests/clients/client-catalog-compatibility.test.ts -51260 tests/clients/client-connect.test.ts -269 tests/clients/client-export-effective-metadata.test.ts -683 tests/clients/client-export-live-wire.test.ts -128 tests/clients/client-export-modality-enum.test.ts -216 tests/clients/client-export-model-names.test.ts +80 tests/cli/cli-path-diagnostics.test.ts +903 tests/cli/cli-provider-batch.test.ts +111 tests/cli/cli-provider-cc-switch-import.test.ts +365 tests/cli/cli-provider-lifecycle-runtime.test.ts +4376 tests/cli/cli-provider-list-active.test.ts +131 tests/cli/cli-provider-result.test.ts +333 tests/cli/cli-provider-settings.test.ts +7613 tests/cli/cli-provider-sync-result.test.ts +40814 tests/cli/cli-provider.test.ts +2190 tests/cli/cli-ready-subprocess.test.ts +107 tests/cli/cli-ready.test.ts +158 tests/cli/cli-registry.test.ts +396 tests/cli/cli-remote-workspace-hub.test.ts +3578 tests/cli/cli-resolve-subprocess.test.ts +97 tests/cli/cli-resolve.test.ts +222 tests/cli/cli-restart-handoff.test.ts +4462 tests/cli/cli-restart-health.test.ts +6133 tests/cli/cli-restore-back.test.ts +17229 tests/cli/cli-role-suggestion-history.test.ts +143 tests/cli/cli-route-policy-not-found.test.ts +2027 tests/cli/cli-route-policy-write.test.ts +12341 tests/cli/cli-start-auxiliary-bind.test.ts +119143 tests/cli/cli-start-journal-order.test.ts +18693 tests/cli/cli-start-owner-absence.test.ts +16388 tests/cli/cli-start-owner-evidence.test.ts +186 tests/cli/cli-start-routing-heal-wiring.test.ts +349 tests/cli/cli-status-codex-routing-drift.test.ts +5506 tests/cli/cli-status-hub-state.test.ts +27958 tests/cli/cli-status-json.test.ts +397 tests/cli/cli-status-oauth-health.test.ts +1821 tests/cli/cli-status-startup-health.test.ts +253 tests/cli/cli-stop-json.test.ts +536 tests/cli/cli-stop-refusal-transport.test.ts +127 tests/cli/cli-storage-inspect.test.ts +2091 tests/cli/cli-storage-policy-fields.test.ts +26641 tests/cli/cli-sync-expect-link.test.ts +318 tests/cli/cli-system-health.test.ts +176 tests/cli/cli-system-settings-parity.test.ts +430 tests/cli/cli-transport-honesty.test.ts +1581 tests/cli/cli-update-badge.test.ts +1459 tests/cli/cli-update-restart-admission.test.ts +238 tests/cli/cli-update-restart-child.test.ts +221 tests/cli/cli-update-restart-desktop-service.test.ts +298 tests/cli/cli-update-restart-home.test.ts +174 tests/cli/cli-update-restart-service-record.test.ts +234 tests/cli/cli-update-restart-supervision.test.ts +680 tests/cli/cli-update-restart-transport.test.ts +177 tests/cli/cli-update-restart.test.ts +4211 tests/cli/cli-usage-compare.test.ts +272 tests/cli/cli-usage-hub.test.ts +161 tests/cli/cli-usage-model-search.test.ts +383 tests/cli/cli-usage-report.test.ts +364 tests/cli/cli-usage-scope.test.ts +1856 tests/cli/cli-usage-top.test.ts +15331 tests/cli/cli-v2-runtime.test.ts +11439 tests/cli/cli-version-skew.test.ts +175 tests/cli/cross-home-loopback-family.test.ts +841 tests/cli/ensure-desired-integrations-race.test.ts +2568 tests/cli/hub-disable.test.ts +1602 tests/cli/hub-gated-local-clients.test.ts +128 tests/cli/hub-invite.test.ts +77 tests/cli/interactive-confirm.test.ts +237 tests/cli/link-apply-restart.test.ts +1457 tests/cli/local-credentials.test.ts +110 tests/cli/model-selection-guidance.test.ts +286 tests/cli/ocx-launcher-desktop-handoff.test.ts +175 tests/cli/ocx-launcher-fixture-trust.test.ts +21416 tests/cli/ocx-launcher-runtime.test.ts +90 tests/cli/ocx-launcher-source.test.ts +63 tests/cli/ocx-run.test.ts +6491 tests/cli/restore-completes-shared-teardown.test.ts +3943 tests/cli/route-explainability.test.ts +34647 tests/cli/sibling-home-client-sync.test.ts +147 tests/cli/star-deferral.test.ts +207 tests/cli/start-args.test.ts +64 tests/cli/start-ownership-publication.test.ts +796 tests/cli/status-install-method.test.ts +26856 tests/cli/sync-command-fanout.test.ts +222 tests/cli/sync-fanout-process.test.ts +240 tests/cli/sync-fanout.test.ts +487 tests/cli/sync-link-status.test.ts +256 tests/cli/system-restart-client-package-tree.test.ts +96 tests/cli/system-restart-client.test.ts +27543 tests/cli/uninstall.test.ts +3890 tests/clients/agent-clients.test.ts +173 tests/clients/aside-profile-identity.test.ts +652 tests/clients/aside-profile-paths.test.ts +6182 tests/clients/aside-profile-sync-owner.test.ts +1891 tests/clients/aside-profiles-catalog-refresh.test.ts +12093 tests/clients/aside-profiles.test.ts +112 tests/clients/client-catalog-compatibility.test.ts +103686 tests/clients/client-connect.test.ts +253 tests/clients/client-export-effective-metadata.test.ts +603 tests/clients/client-export-live-wire.test.ts +175 tests/clients/client-export-modality-enum.test.ts +412 tests/clients/client-export-model-names.test.ts 281 tests/clients/client-export-reasoning-controls.test.ts -128 tests/clients/client-export-reasoning-metadata.test.ts -281 tests/clients/client-fingerprint.test.ts -428 tests/clients/client-home-unreachable.test.ts +143 tests/clients/client-export-reasoning-metadata.test.ts +80 tests/clients/client-fingerprint.test.ts +444 tests/clients/client-home-unreachable.test.ts 97 tests/clients/client-hub-relay.test.ts -646 tests/clients/client-hub-state.test.ts -143 tests/clients/client-hub-usage.test.ts -12864 tests/clients/client-lifecycle-lock.test.ts -14313 tests/clients/client-link-connect.test.ts +346 tests/clients/client-hub-state.test.ts +272 tests/clients/client-hub-usage.test.ts +19112 tests/clients/client-lifecycle-lock.test.ts +14710 tests/clients/client-link-connect.test.ts 5742 tests/clients/client-link-relay.test.ts -14617 tests/clients/client-link-runtime.test.ts -683 tests/clients/client-link-state.test.ts -220 tests/clients/client-link-status.test.ts -4520 tests/clients/client-link-teardown.test.ts -7782 tests/clients/client-link-tunnel.test.ts -6563 tests/clients/client-machine-listener.test.ts -176 tests/clients/client-path.test.ts -352 tests/clients/client-runtime-restart.test.ts -638 tests/clients/client-runtime.test.ts +14129 tests/clients/client-link-runtime.test.ts +1064 tests/clients/client-link-state.test.ts +77 tests/clients/client-link-status.test.ts +3579 tests/clients/client-link-teardown.test.ts +9362 tests/clients/client-link-tunnel.test.ts +6385 tests/clients/client-machine-listener.test.ts +272 tests/clients/client-path.test.ts +510 tests/clients/client-runtime-restart.test.ts +390 tests/clients/client-runtime.test.ts 158 tests/clients/cline-client.test.ts -4526 tests/clients/cline-writer.test.ts -2762 tests/clients/command-code-client-contract.test.ts -126 tests/clients/command-code-client.test.ts -2378 tests/clients/desktop-3p-guard.test.ts -9585 tests/clients/desktop-3p-removal.test.ts -18370 tests/clients/desktop-3p-write-files.test.ts -5624 tests/clients/desktop-3p.test.ts -111 tests/clients/desktop-app-restart-posix.test.ts -615 tests/clients/desktop-app-restart.test.ts -729 tests/clients/desktop-app-server-exec-boundary.test.ts -2537 tests/clients/desktop-app-server-shim-launcher.test.ts -96 tests/clients/desktop-app-server-shim.test.ts -10146 tests/clients/desktop-bundle-trust-async.test.ts -185 tests/clients/desktop-chatgpt-config.test.ts -111 tests/clients/desktop-cli-command-surface.test.ts -49 tests/clients/desktop-cli-contracts.test.ts -838 tests/clients/desktop-compatibility-authority.test.ts -2200 tests/clients/desktop-compatibility-build-probe.test.ts -62 tests/clients/desktop-compatibility-certificate-service.test.ts -674 tests/clients/desktop-compatibility-connection-store.test.ts -1869 tests/clients/desktop-compatibility-launch.test.ts -209 tests/clients/desktop-compatibility-native-identity.test.ts +7282 tests/clients/cline-writer.test.ts +2453 tests/clients/command-code-client-contract.test.ts +434 tests/clients/command-code-client.test.ts +778 tests/clients/desktop-3p-guard.test.ts +11443 tests/clients/desktop-3p-removal.test.ts +18731 tests/clients/desktop-3p-write-files.test.ts +7333 tests/clients/desktop-3p.test.ts +95 tests/clients/desktop-app-restart-posix.test.ts +839 tests/clients/desktop-app-restart.test.ts +79 tests/clients/desktop-app-server-exec-boundary.test.ts +2425 tests/clients/desktop-app-server-shim-launcher.test.ts +82 tests/clients/desktop-app-server-shim.test.ts +10219 tests/clients/desktop-bundle-trust-async.test.ts +139 tests/clients/desktop-chatgpt-config.test.ts +65 tests/clients/desktop-cli-command-surface.test.ts +111 tests/clients/desktop-cli-contracts.test.ts +789 tests/clients/desktop-compatibility-authority.test.ts +2655 tests/clients/desktop-compatibility-build-probe.test.ts +597 tests/clients/desktop-compatibility-certificate-service.test.ts +664 tests/clients/desktop-compatibility-connection-store.test.ts +2031 tests/clients/desktop-compatibility-launch.test.ts +274 tests/clients/desktop-compatibility-native-identity.test.ts 219 tests/clients/desktop-compatibility-relay.test.ts -193 tests/clients/desktop-compatibility-routing.test.ts -221 tests/clients/desktop-compatibility-runtime.test.ts -1946 tests/clients/desktop-compatibility-trust.test.ts +95 tests/clients/desktop-compatibility-routing.test.ts +520 tests/clients/desktop-compatibility-runtime.test.ts +2029 tests/clients/desktop-compatibility-trust.test.ts 97 tests/clients/desktop-exit-ownership.test.ts -61 tests/clients/desktop-host-visibility.test.ts -81 tests/clients/desktop-install-identity.test.ts -331 tests/clients/desktop-profile.test.ts -47 tests/clients/desktop-proxy-direct-transport.test.ts -36336 tests/clients/desktop-remote-store.test.ts -110 tests/clients/desktop-restart-handoff.test.ts -80 tests/clients/desktop-runtime-identity.test.ts -215 tests/clients/desktop-start-at-login-default.test.ts -49 tests/clients/desktop-startup-surface.test.ts -1568 tests/clients/desktop-supervised-restart.test.ts -90 tests/clients/desktop-tray-availability.test.ts -79 tests/clients/desktop-update-surface.test.ts -63 tests/clients/desktop-widget-entry.test.ts -3757 tests/clients/droid-client.test.ts -4618 tests/clients/droid-managed-reasoning-defaults.test.ts -1274 tests/clients/droid-normalized-reasoning-defaults.test.ts -1522 tests/clients/gentle-shell-client.test.ts -188 tests/clients/gentle-shell-path.test.ts -4381 tests/clients/hermes-catalog-refresh.test.ts -3999 tests/clients/hermes-profile-routes.test.ts -112 tests/clients/hermes-profiles.test.ts -6885 tests/clients/integrations-current-store.test.ts +79 tests/clients/desktop-host-visibility.test.ts +78 tests/clients/desktop-install-identity.test.ts +444 tests/clients/desktop-profile.test.ts +215 tests/clients/desktop-proxy-direct-transport.test.ts +47645 tests/clients/desktop-remote-store.test.ts +109 tests/clients/desktop-restart-handoff.test.ts +52 tests/clients/desktop-runtime-identity.test.ts +80 tests/clients/desktop-start-at-login-default.test.ts +67 tests/clients/desktop-startup-surface.test.ts +1407 tests/clients/desktop-supervised-restart.test.ts +224 tests/clients/desktop-tray-availability.test.ts +96 tests/clients/desktop-update-surface.test.ts +91 tests/clients/desktop-widget-entry.test.ts +3023 tests/clients/droid-client.test.ts +3280 tests/clients/droid-managed-reasoning-defaults.test.ts +2571 tests/clients/droid-normalized-reasoning-defaults.test.ts +1652 tests/clients/gentle-shell-client.test.ts +300 tests/clients/gentle-shell-path.test.ts +4368 tests/clients/hermes-catalog-refresh.test.ts +4172 tests/clients/hermes-profile-routes.test.ts +126 tests/clients/hermes-profiles.test.ts +10997 tests/clients/integrations-current-store.test.ts 8845 tests/clients/integrations-dsh-profile-patch.test.ts -5603 tests/clients/integrations-hermes-affinity.test.ts -2932 tests/clients/integrations-journal.test.ts +7380 tests/clients/integrations-hermes-affinity.test.ts +3310 tests/clients/integrations-journal.test.ts 1172 tests/clients/integrations-merge.test.ts -3036 tests/clients/integrations-model-names.test.ts -80 tests/clients/integrations-serialize.test.ts -1095 tests/clients/integrations-state.test.ts -554 tests/clients/integrations-superseded-store.test.ts -968 tests/clients/integrations-writer-frozen-config.test.ts -1192 tests/clients/integrations-writer-guard.test.ts -17541 tests/clients/integrations-writer.test.ts -3349 tests/clients/kilo-client.test.ts -94 tests/clients/lazycodex-detection.test.ts -48 tests/clients/link-admission-wait.test.ts -1887 tests/clients/link-apply-record.test.ts -79 tests/clients/link-boundary.test.ts -47 tests/clients/link-codex-settings-digest.test.ts -469 tests/clients/link-compensation.test.ts -126 tests/clients/link-connection-generation.test.ts +6790 tests/clients/integrations-model-names.test.ts +94 tests/clients/integrations-serialize.test.ts +938 tests/clients/integrations-state.test.ts +552 tests/clients/integrations-superseded-store.test.ts +985 tests/clients/integrations-writer-frozen-config.test.ts +1567 tests/clients/integrations-writer-guard.test.ts +15779 tests/clients/integrations-writer.test.ts +5317 tests/clients/kilo-client.test.ts +111 tests/clients/lazycodex-detection.test.ts +96 tests/clients/link-admission-wait.test.ts +1536 tests/clients/link-apply-record.test.ts +80 tests/clients/link-boundary.test.ts +95 tests/clients/link-codex-settings-digest.test.ts +368 tests/clients/link-compensation.test.ts +254 tests/clients/link-connection-generation.test.ts 1520 tests/clients/link-diagnostics.test.ts -64 tests/clients/link-fingerprint.test.ts -460 tests/clients/link-home-settings.test.ts -63 tests/clients/link-parity-reporter.test.ts -236 tests/clients/link-peer-compatibility.test.ts -967 tests/clients/link-ports.test.ts -634 tests/clients/link-readiness.test.ts -617 tests/clients/link-relay-bound-transport.test.ts -268 tests/clients/link-routes.test.ts -16555 tests/clients/link-ssh-argv-discovery.test.ts -1158 tests/clients/link-ssh-argv.test.ts -187 tests/clients/link-ssh-config.test.ts +301 tests/clients/link-fingerprint.test.ts +691 tests/clients/link-home-settings.test.ts +228 tests/clients/link-parity-reporter.test.ts +318 tests/clients/link-peer-compatibility.test.ts +22263 tests/clients/link-pinned-sync-argv.test.ts +1175 tests/clients/link-ports.test.ts +492 tests/clients/link-readiness.test.ts +551 tests/clients/link-relay-bound-transport.test.ts +317 tests/clients/link-routes.test.ts +12077 tests/clients/link-ssh-argv-discovery.test.ts +1075 tests/clients/link-ssh-argv.test.ts +175 tests/clients/link-ssh-config.test.ts 490 tests/clients/link-ssh-runner.test.ts -239 tests/clients/link-status-projection.test.ts -225 tests/clients/link-store.test.ts -4465 tests/clients/link-supervisor.test.ts -555 tests/clients/link-tunnel-history.test.ts -78 tests/clients/link-tunnel-state.test.ts +205 tests/clients/link-status-projection.test.ts +143 tests/clients/link-store.test.ts +4755 tests/clients/link-supervisor.test.ts +815 tests/clients/link-tunnel-history.test.ts +95 tests/clients/link-tunnel-state.test.ts 1076 tests/clients/mutation-plan.test.ts -209 tests/clients/omo-client.test.ts +159 tests/clients/omo-client.test.ts 3036 tests/clients/omo-responses-loop.test.ts -602 tests/clients/omo-role-models.test.ts -174 tests/clients/omp-path-contract.test.ts -112 tests/clients/omp-yaml-source-inline-comments.test.ts -3742 tests/clients/opencode-kilo-refresh.test.ts -400 tests/clients/pi-path-contract.test.ts -159 tests/clients/prime-client.test.ts -3756 tests/clients/qoder-client.test.ts -1078 tests/clients/raycast-client.test.ts -80 tests/clients/raycast-detect.test.ts -7075 tests/clients/remote-catalog.test.ts -110 tests/clients/remote-control-prototype.test.ts -143 tests/clients/remote-workspace-activation.test.ts -63 tests/clients/remote-workspace-agent-wire.test.ts -142 tests/clients/remote-workspace-app-server.integration.test.ts -288 tests/clients/remote-workspace-claude.integration.test.ts +745 tests/clients/omo-role-models.test.ts +173 tests/clients/omp-path-contract.test.ts +111 tests/clients/omp-yaml-source-inline-comments.test.ts +3261 tests/clients/opencode-kilo-refresh.test.ts +175 tests/clients/pi-path-contract.test.ts +127 tests/clients/prime-client.test.ts +3238 tests/clients/qoder-client.test.ts +824 tests/clients/raycast-client.test.ts +94 tests/clients/raycast-detect.test.ts +7081 tests/clients/remote-catalog.test.ts +174 tests/clients/remote-control-prototype.test.ts +407 tests/clients/remote-workspace-activation.test.ts +285 tests/clients/remote-workspace-agent-wire.test.ts +1820 tests/clients/remote-workspace-app-server.integration.test.ts +142 tests/clients/remote-workspace-claude.integration.test.ts 806 tests/clients/remote-workspace-cli-runtimes.test.ts -173 tests/clients/remote-workspace-cli.test.ts +313 tests/clients/remote-workspace-cli.test.ts 661 tests/clients/remote-workspace-codex-runtime.test.ts 285 tests/clients/remote-workspace-command-runner.test.ts -95 tests/clients/remote-workspace-device.test.ts -94 tests/clients/remote-workspace-hub.test.ts +365 tests/clients/remote-workspace-device.test.ts +257 tests/clients/remote-workspace-hub.test.ts 47 tests/clients/remote-workspace-linux-confinement.test.ts -377 tests/clients/remote-workspace-management.test.ts +253 tests/clients/remote-workspace-management.test.ts 128 tests/clients/remote-workspace-platform.test.ts -78 tests/clients/remote-workspace-protocol.test.ts -90 tests/clients/remote-workspace-rpc-framing.test.ts -635 tests/clients/remote-workspace-secret-store.test.ts -17798 tests/clients/remote-workspace-server.test.ts -83 tests/clients/remote-workspace-session-binding.test.ts -126 tests/clients/remote-workspace-sessions.test.ts -64 tests/clients/remote-workspace-tool-bridge.test.ts +127 tests/clients/remote-workspace-protocol.test.ts +63 tests/clients/remote-workspace-rpc-framing.test.ts +1174 tests/clients/remote-workspace-secret-store.test.ts +17301 tests/clients/remote-workspace-server.test.ts +80 tests/clients/remote-workspace-session-binding.test.ts +444 tests/clients/remote-workspace-sessions.test.ts +111 tests/clients/remote-workspace-tool-bridge.test.ts 365 tests/clients/remote-workspace.test.ts -31093 tests/clients/sync-client-integrations-unattended.test.ts -6915 tests/clients/sync-client-integrations.test.ts +53138 tests/clients/sync-client-integrations-unattended.test.ts +5641 tests/clients/sync-client-integrations.test.ts 1388 tests/clients/t3code-client-lifecycle.test.ts -1265 tests/clients/t3code-client.test.ts -2985 tests/clients/workbuddy-selector-recovery.test.ts -5399 tests/codex-integration/active-registry-admission.test.ts -25242 tests/codex-integration/active-turn-disconnect.test.ts +1461 tests/clients/t3code-client.test.ts +2186 tests/clients/workbuddy-selector-recovery.test.ts +4993 tests/codex-integration/active-registry-admission.test.ts +22679 tests/codex-integration/active-turn-disconnect.test.ts 669 tests/codex-integration/anthropic2-catalog.test.ts -161 tests/codex-integration/app-owned-memory.test.ts -112200 tests/codex-integration/bearer-admission-routed-provider.test.ts -618 tests/codex-integration/catalog-async-lifetime.test.ts -3849 tests/codex-integration/catalog-auto-refresh-client-fanout.test.ts +316 tests/codex-integration/app-owned-memory.test.ts +97807 tests/codex-integration/bearer-admission-routed-provider.test.ts +918 tests/codex-integration/catalog-async-lifetime.test.ts +3661 tests/codex-integration/catalog-auto-refresh-client-fanout.test.ts 4823 tests/codex-integration/catalog-auto-refresh-scheduler.test.ts -80 tests/codex-integration/catalog-auto-review-override.test.ts -7969 tests/codex-integration/catalog-auto-review-row.test.ts -246 tests/codex-integration/catalog-context-window-ladder.test.ts -208 tests/codex-integration/catalog-cursor-search.test.ts -206 tests/codex-integration/catalog-custom-ordering.test.ts -159 tests/codex-integration/catalog-duplicate-slug-dedup.test.ts -518 tests/codex-integration/catalog-free-pricing-status.test.ts -31637 tests/codex-integration/catalog-full-picker-order.test.ts -109 tests/codex-integration/catalog-gated-native-suppression-reason.test.ts -238 tests/codex-integration/catalog-go-exact-efforts.test.ts -94 tests/codex-integration/catalog-hub-context-window.test.ts -326 tests/codex-integration/catalog-input-modality-enum.test.ts -143 tests/codex-integration/catalog-llamacpp-capabilities.test.ts -1375 tests/codex-integration/catalog-modelalias-unique-sync.test.ts +128 tests/codex-integration/catalog-auto-review-override.test.ts +8373 tests/codex-integration/catalog-auto-review-row.test.ts +143 tests/codex-integration/catalog-context-window-ladder.test.ts +267 tests/codex-integration/catalog-cursor-search.test.ts +160 tests/codex-integration/catalog-custom-ordering.test.ts +141 tests/codex-integration/catalog-duplicate-slug-dedup.test.ts +270 tests/codex-integration/catalog-free-pricing-status.test.ts +27621 tests/codex-integration/catalog-full-picker-order.test.ts +142 tests/codex-integration/catalog-gated-native-suppression-reason.test.ts +491 tests/codex-integration/catalog-go-exact-efforts.test.ts +126 tests/codex-integration/catalog-hub-context-window.test.ts +534 tests/codex-integration/catalog-input-modality-enum.test.ts +127 tests/codex-integration/catalog-llamacpp-capabilities.test.ts +1890 tests/codex-integration/catalog-modelalias-unique-sync.test.ts 595 tests/codex-integration/catalog-native-max-context.test.ts 1310 tests/codex-integration/catalog-oauth-observation.test.ts -62908 tests/codex-integration/catalog-omit-disabled-native.test.ts -223 tests/codex-integration/catalog-opencode-go-context-window.test.ts -176 tests/codex-integration/catalog-opencode-go-static.test.ts -128 tests/codex-integration/catalog-opengateway-hints.test.ts -2355 tests/codex-integration/catalog-remote-pull.test.ts -94 tests/codex-integration/catalog-retain-models.test.ts +54877 tests/codex-integration/catalog-omit-disabled-native.test.ts +204 tests/codex-integration/catalog-opencode-go-context-window.test.ts +208 tests/codex-integration/catalog-opencode-go-static.test.ts +156 tests/codex-integration/catalog-opengateway-hints.test.ts +3548 tests/codex-integration/catalog-remote-pull.test.ts +207 tests/codex-integration/catalog-retain-models.test.ts 397 tests/codex-integration/catalog-routed-comp-hash.test.ts -142 tests/codex-integration/catalog-seed-window-fill.test.ts -111 tests/codex-integration/catalog-slug-uniqueness-boundary.test.ts -236 tests/codex-integration/catalog-verbosity-default.test.ts +368 tests/codex-integration/catalog-seed-window-fill.test.ts +128 tests/codex-integration/catalog-slug-uniqueness-boundary.test.ts +190 tests/codex-integration/catalog-verbosity-default.test.ts 191 tests/codex-integration/catalog-vision-sidecar-disabled.test.ts -110 tests/codex-integration/catalog-vision-sidecar-modalities.test.ts -206 tests/codex-integration/catalog-zero-credit-picker.test.ts +128 tests/codex-integration/catalog-vision-sidecar-modalities.test.ts +79 tests/codex-integration/catalog-zero-credit-picker.test.ts 9159 tests/codex-integration/client-injection-guard.test.ts -222 tests/codex-integration/code-mode-collab-surface.test.ts -618 tests/codex-integration/codex-account-clear-paused.test.ts -8884 tests/codex-integration/codex-account-delete-atomicity.test.ts -79 tests/codex-integration/codex-account-label.test.ts +287 tests/codex-integration/code-mode-collab-surface.test.ts +682 tests/codex-integration/codex-account-clear-paused.test.ts +9984 tests/codex-integration/codex-account-delete-atomicity.test.ts +95 tests/codex-integration/codex-account-label.test.ts 82 tests/codex-integration/codex-account-namespaces.test.ts -22724 tests/codex-integration/codex-account-selection-atomicity.test.ts +11872 tests/codex-integration/codex-account-selection-atomicity.test.ts 1930 tests/codex-integration/codex-account-selection-preferences.test.ts -727 tests/codex-integration/codex-account-slot-identity.test.ts -537 tests/codex-integration/codex-account-store-quota-isolation.test.ts +1111 tests/codex-integration/codex-account-slot-identity.test.ts +1096 tests/codex-integration/codex-account-store-quota-isolation.test.ts 1038 tests/codex-integration/codex-account-store-refresh-classification.test.ts -5293 tests/codex-integration/codex-account-store.test.ts -1416 tests/codex-integration/codex-account-threshold-api.test.ts -1386 tests/codex-integration/codex-account-threshold-auth.test.ts -1031 tests/codex-integration/codex-account-threshold-routing.test.ts -2253 tests/codex-integration/codex-account-unusable-reason.test.ts -902 tests/codex-integration/codex-admission-primitives.test.ts -380 tests/codex-integration/codex-admission.test.ts -145 tests/codex-integration/codex-affinity-debug.test.ts -3530 tests/codex-integration/codex-affinity-lease-gap.test.ts -1770 tests/codex-integration/codex-affinity-request-owned.test.ts -47058 tests/codex-integration/codex-affinity-restart-matrix.test.ts -68932 tests/codex-integration/codex-affinity-restart.test.ts -37766 tests/codex-integration/codex-affinity-store.test.ts -3349 tests/codex-integration/codex-agent-thread-limit.test.ts -95 tests/codex-integration/codex-app-server-path-spaces.test.ts -3171 tests/codex-integration/codex-app-server-processes.test.ts -234 tests/codex-integration/codex-app-server-restart-service.test.ts +6485 tests/codex-integration/codex-account-store.test.ts +1944 tests/codex-integration/codex-account-threshold-api.test.ts +1899 tests/codex-integration/codex-account-threshold-auth.test.ts +1378 tests/codex-integration/codex-account-threshold-routing.test.ts +2332 tests/codex-integration/codex-account-unusable-reason.test.ts +749 tests/codex-integration/codex-admission-primitives.test.ts +302 tests/codex-integration/codex-admission.test.ts +82 tests/codex-integration/codex-affinity-debug.test.ts +3842 tests/codex-integration/codex-affinity-lease-gap.test.ts +1694 tests/codex-integration/codex-affinity-request-owned.test.ts +41570 tests/codex-integration/codex-affinity-restart-matrix.test.ts +45290 tests/codex-integration/codex-affinity-restart.test.ts +33918 tests/codex-integration/codex-affinity-store.test.ts +3559 tests/codex-integration/codex-agent-thread-limit.test.ts +63 tests/codex-integration/codex-app-server-path-spaces.test.ts +3596 tests/codex-integration/codex-app-server-processes.test.ts +175 tests/codex-integration/codex-app-server-restart-service.test.ts 20806 tests/codex-integration/codex-auth-api.test.ts 318 tests/codex-integration/codex-auth-cancel-ownership.test.ts -3410 tests/codex-integration/codex-auth-collision.test.ts -5208 tests/codex-integration/codex-auth-context.test.ts -5861 tests/codex-integration/codex-auth-headless-accounts.test.ts -7247 tests/codex-integration/codex-auth-release.test.ts +3232 tests/codex-integration/codex-auth-collision.test.ts +3500 tests/codex-integration/codex-auth-context.test.ts +8352 tests/codex-integration/codex-auth-headless-accounts.test.ts +6611 tests/codex-integration/codex-auth-release.test.ts 746 tests/codex-integration/codex-catalog-admission.test.ts -187 tests/codex-integration/codex-catalog-exclusions.test.ts +174 tests/codex-integration/codex-catalog-exclusions.test.ts 142 tests/codex-integration/codex-catalog-golden.test.ts -5725 tests/codex-integration/codex-catalog-heal-integration.test.ts +6531 tests/codex-integration/codex-catalog-heal-integration.test.ts 412 tests/codex-integration/codex-catalog-heal-reanchor.test.ts 207 tests/codex-integration/codex-catalog-identity-neutral.test.ts 2263 tests/codex-integration/codex-catalog-intent.test.ts -238 tests/codex-integration/codex-catalog-ladders.test.ts -142 tests/codex-integration/codex-catalog-model-picker-order.test.ts -233 tests/codex-integration/codex-catalog-refresh-status.test.ts -3724 tests/codex-integration/codex-catalog-restore.test.ts +227 tests/codex-integration/codex-catalog-ladders.test.ts +254 tests/codex-integration/codex-catalog-model-picker-order.test.ts +76 tests/codex-integration/codex-catalog-refresh-status.test.ts +3631 tests/codex-integration/codex-catalog-restore.test.ts 111 tests/codex-integration/codex-catalog-routed-removal.test.ts -268 tests/codex-integration/codex-catalog-self-heal.test.ts +507 tests/codex-integration/codex-catalog-self-heal.test.ts 53548 tests/codex-integration/codex-catalog-sync-hardening.test.ts -2296 tests/codex-integration/codex-catalog-write-audit.test.ts +2406 tests/codex-integration/codex-catalog-write-audit.test.ts 347 tests/codex-integration/codex-catalog-write-serialization.test.ts -2038 tests/codex-integration/codex-catalog-writer.test.ts -4555 tests/codex-integration/codex-catalog.test.ts -1000 tests/codex-integration/codex-clamp-notice.test.ts -111 tests/codex-integration/codex-cli-install-provenance.test.ts -96 tests/codex-integration/codex-cli-installation-identity.test.ts -112 tests/codex-integration/codex-cli-installation-targets.test.ts -2206 tests/codex-integration/codex-cli-update-admission.test.ts -222 tests/codex-integration/codex-cli-update-apply.test.ts -12036 tests/codex-integration/codex-cli-update-artifacts.test.ts -303 tests/codex-integration/codex-cli-update-integrity.test.ts +1765 tests/codex-integration/codex-catalog-writer.test.ts +5782 tests/codex-integration/codex-catalog.test.ts +935 tests/codex-integration/codex-clamp-notice.test.ts +217 tests/codex-integration/codex-cli-install-provenance.test.ts +94 tests/codex-integration/codex-cli-installation-identity.test.ts +245 tests/codex-integration/codex-cli-installation-targets.test.ts +2123 tests/codex-integration/codex-cli-update-admission.test.ts +305 tests/codex-integration/codex-cli-update-apply.test.ts +14023 tests/codex-integration/codex-cli-update-artifacts.test.ts +207 tests/codex-integration/codex-cli-update-integrity.test.ts 79 tests/codex-integration/codex-cli-update-launcher-policy.test.ts -9443 tests/codex-integration/codex-cli-update-parent-async.test.ts -93 tests/codex-integration/codex-cli-update-paths.test.ts -6430 tests/codex-integration/codex-cli-update-plan.test.ts -11470 tests/codex-integration/codex-cli-update-recovery.test.ts -170251 tests/codex-integration/codex-cli-update-windows-apply-install.test.ts -109915 tests/codex-integration/codex-cli-update-windows-apply-outcomes.test.ts -177494 tests/codex-integration/codex-cli-update-windows-apply-shared.test.ts -55402 tests/codex-integration/codex-cli-update-windows-apply.test.ts -190 tests/codex-integration/codex-cli-update-windows-layout.test.ts -133360 tests/codex-integration/codex-cli-update-windows-pending.test.ts -227421 tests/codex-integration/codex-cli-update-windows-recovery.test.ts -8625 tests/codex-integration/codex-cli-update-windows-review.test.ts -2424 tests/codex-integration/codex-cli-update-worker.test.ts -4820 tests/codex-integration/codex-cli-update-zero-effect.test.ts -10988 tests/codex-integration/codex-cli-windows-child.test.ts +9395 tests/codex-integration/codex-cli-update-parent-async.test.ts +112 tests/codex-integration/codex-cli-update-paths.test.ts +5813 tests/codex-integration/codex-cli-update-plan.test.ts +9450 tests/codex-integration/codex-cli-update-recovery.test.ts +153364 tests/codex-integration/codex-cli-update-windows-apply-install.test.ts +200318 tests/codex-integration/codex-cli-update-windows-apply-outcomes.test.ts +131799 tests/codex-integration/codex-cli-update-windows-apply-shared.test.ts +72821 tests/codex-integration/codex-cli-update-windows-apply.test.ts +369 tests/codex-integration/codex-cli-update-windows-layout.test.ts +191002 tests/codex-integration/codex-cli-update-windows-pending.test.ts +220972 tests/codex-integration/codex-cli-update-windows-recovery.test.ts +8361 tests/codex-integration/codex-cli-update-windows-review.test.ts +2420 tests/codex-integration/codex-cli-update-worker.test.ts +5089 tests/codex-integration/codex-cli-update-zero-effect.test.ts +11002 tests/codex-integration/codex-cli-windows-child.test.ts 206 tests/codex-integration/codex-cli-windows-installation-files.test.ts -15940 tests/codex-integration/codex-cli-windows-plan.test.ts -216776 tests/codex-integration/codex-composed-acceptance.test.ts -8033 tests/codex-integration/codex-config-drift-heal.test.ts -3255 tests/codex-integration/codex-config-generation.test.ts +23376 tests/codex-integration/codex-cli-windows-plan.test.ts +164001 tests/codex-integration/codex-composed-acceptance.test.ts +7203 tests/codex-integration/codex-config-drift-heal.test.ts +3164 tests/codex-integration/codex-config-generation.test.ts 10606 tests/codex-integration/codex-config-preservation.test.ts 17150 tests/codex-integration/codex-config-write-lock.test.ts 190 tests/codex-integration/codex-context-owner.test.ts -37676 tests/codex-integration/codex-convergence-account-selectors.test.ts +47488 tests/codex-integration/codex-convergence-account-selectors.test.ts 15675 tests/codex-integration/codex-convergence-contract.test.ts -7560 tests/codex-integration/codex-cooldown-recovery.test.ts -464 tests/codex-integration/codex-coordinator-doctor.test.ts -2467 tests/codex-integration/codex-credit-retry-after.test.ts -2369 tests/codex-integration/codex-credit-scoped-retry.test.ts -697 tests/codex-integration/codex-credits-after-limit-main.test.ts +8310 tests/codex-integration/codex-cooldown-recovery.test.ts +5865 tests/codex-integration/codex-coordinator-doctor.test.ts +6720 tests/codex-integration/codex-credit-retry-after.test.ts +3341 tests/codex-integration/codex-credit-scoped-retry.test.ts +492 tests/codex-integration/codex-credits-after-limit-main.test.ts 2421 tests/codex-integration/codex-credits-after-limit.test.ts -4013 tests/codex-integration/codex-credits-probes.test.ts -1061 tests/codex-integration/codex-credits-settings.test.ts -198 tests/codex-integration/codex-credits.test.ts -3151 tests/codex-integration/codex-desired-state.test.ts -17312 tests/codex-integration/codex-direct-credit-renewal.test.ts -6591 tests/codex-integration/codex-direct-renewal-revocation.test.ts +3928 tests/codex-integration/codex-credits-probes.test.ts +999 tests/codex-integration/codex-credits-settings.test.ts +66 tests/codex-integration/codex-credits.test.ts +3333 tests/codex-integration/codex-desired-state.test.ts +19042 tests/codex-integration/codex-direct-credit-renewal.test.ts +7215 tests/codex-integration/codex-direct-renewal-revocation.test.ts 412 tests/codex-integration/codex-entitlement-identity-read-fence.test.ts -4829 tests/codex-integration/codex-envkey-admission-substitution.test.ts -133 tests/codex-integration/codex-exec-invocation.test.ts +5485 tests/codex-integration/codex-envkey-admission-substitution.test.ts +142 tests/codex-integration/codex-exec-invocation.test.ts 3103 tests/codex-integration/codex-failure-window.test.ts -143 tests/codex-integration/codex-features-cache.test.ts -79 tests/codex-integration/codex-features-residual.test.ts -397 tests/codex-integration/codex-filesystem-evidence.test.ts -239 tests/codex-integration/codex-forward-access-programs-writer.test.ts -998 tests/codex-integration/codex-gather-authority.test.ts -8640 tests/codex-integration/codex-history-job.test.ts -331 tests/codex-integration/codex-history-lock.test.ts -221 tests/codex-integration/codex-history-pending-wal.test.ts -25949 tests/codex-integration/codex-history-provider.test.ts -959 tests/codex-integration/codex-history-reachability.test.ts -257 tests/codex-integration/codex-history-worker-boundary.test.ts -2082 tests/codex-integration/codex-history-worker.test.ts +570 tests/codex-integration/codex-features-cache.test.ts +63 tests/codex-integration/codex-features-residual.test.ts +380 tests/codex-integration/codex-filesystem-evidence.test.ts +158 tests/codex-integration/codex-forward-access-programs-writer.test.ts +935 tests/codex-integration/codex-gather-authority.test.ts +21357 tests/codex-integration/codex-history-job.test.ts +333 tests/codex-integration/codex-history-lock.test.ts +333 tests/codex-integration/codex-history-pending-wal.test.ts +11180 tests/codex-integration/codex-history-provider.test.ts +984 tests/codex-integration/codex-history-reachability.test.ts +78 tests/codex-integration/codex-history-worker-boundary.test.ts +2023 tests/codex-integration/codex-history-worker.test.ts 221 tests/codex-integration/codex-history-writer.test.ts -20951 tests/codex-integration/codex-home-owner-lifecycle.test.ts -3975 tests/codex-integration/codex-home-owner.test.ts +20532 tests/codex-integration/codex-home-owner-lifecycle.test.ts +3013 tests/codex-integration/codex-home-owner.test.ts 50 tests/codex-integration/codex-home-wsl-local-state.test.ts -333 tests/codex-integration/codex-home-wsl.test.ts -10204 tests/codex-integration/codex-idle-window.test.ts -161 tests/codex-integration/codex-inject-history-wording.test.ts -229555 tests/codex-integration/codex-inject-integration.test.ts +286 tests/codex-integration/codex-home-wsl.test.ts +11148 tests/codex-integration/codex-idle-window.test.ts +238 tests/codex-integration/codex-inject-history-wording.test.ts +214705 tests/codex-integration/codex-inject-integration.test.ts 4978 tests/codex-integration/codex-inject-missing-config.test.ts -1881 tests/codex-integration/codex-inject-retained-table.test.ts -25097 tests/codex-integration/codex-inject-v1-reconcile.test.ts -23620 tests/codex-integration/codex-inject-write-lock.test.ts -194 tests/codex-integration/codex-inject.test.ts -209 tests/codex-integration/codex-injected-marker.test.ts -1090 tests/codex-integration/codex-installation-acl.test.ts -807 tests/codex-integration/codex-installation-id.test.ts +2090 tests/codex-integration/codex-inject-retained-table.test.ts +23550 tests/codex-integration/codex-inject-v1-reconcile.test.ts +22177 tests/codex-integration/codex-inject-write-lock.test.ts +272 tests/codex-integration/codex-inject.test.ts +79 tests/codex-integration/codex-injected-marker.test.ts +1252 tests/codex-integration/codex-installation-acl.test.ts +901 tests/codex-integration/codex-installation-id.test.ts 12642 tests/codex-integration/codex-installation-invalid-account.test.ts -15302 tests/codex-integration/codex-installation-live-content.test.ts -2879 tests/codex-integration/codex-installation-live-http.test.ts -7478 tests/codex-integration/codex-installation-live-ws.test.ts -2186 tests/codex-integration/codex-installation-sidecars.test.ts -936 tests/codex-integration/codex-integration-record.test.ts -8125 tests/codex-integration/codex-journal-recovery.test.ts -30096 tests/codex-integration/codex-journal.test.ts -26434 tests/codex-integration/codex-launcher-admission.test.ts -65 tests/codex-integration/codex-launcher-darwin-acl.test.ts +14162 tests/codex-integration/codex-installation-live-content.test.ts +4710 tests/codex-integration/codex-installation-live-http.test.ts +9380 tests/codex-integration/codex-installation-live-ws.test.ts +1754 tests/codex-integration/codex-installation-sidecars.test.ts +1571 tests/codex-integration/codex-installation-wire.test.ts +746 tests/codex-integration/codex-integration-record.test.ts +6597 tests/codex-integration/codex-journal-recovery.test.ts +42502 tests/codex-integration/codex-journal.test.ts +20912 tests/codex-integration/codex-launcher-admission.test.ts +194 tests/codex-integration/codex-launcher-darwin-acl.test.ts 113 tests/codex-integration/codex-launcher-darwin-identity.test.ts -5404 tests/codex-integration/codex-launcher-diagnostics.test.ts -19692 tests/codex-integration/codex-launcher-env.test.ts -4299 tests/codex-integration/codex-launcher-process.test.ts -19576 tests/codex-integration/codex-launcher-security.test.ts +6402 tests/codex-integration/codex-launcher-diagnostics.test.ts +31169 tests/codex-integration/codex-launcher-env.test.ts +4221 tests/codex-integration/codex-launcher-process.test.ts +19597 tests/codex-integration/codex-launcher-security.test.ts 127 tests/codex-integration/codex-launcher.test.ts -150 tests/codex-integration/codex-legacy-config-keys.test.ts -1471 tests/codex-integration/codex-lineage-placement.test.ts -2237 tests/codex-integration/codex-linked-account-pause.test.ts +229 tests/codex-integration/codex-legacy-config-keys.test.ts +1385 tests/codex-integration/codex-lineage-placement.test.ts +1408 tests/codex-integration/codex-linked-account-pause.test.ts 792 tests/codex-integration/codex-log-guard-coderabbit.test.ts 79 tests/codex-integration/codex-log-guard-doctor-coderabbit.test.ts 241 tests/codex-integration/codex-log-guard-doctor-protection.test.ts 80 tests/codex-integration/codex-log-guard-doctor.test.ts -1680 tests/codex-integration/codex-log-guard-inspect.test.ts -108 tests/codex-integration/codex-log-guard-lock.test.ts -3417 tests/codex-integration/codex-log-guard-maintenance-coderabbit.test.ts -18212 tests/codex-integration/codex-log-guard-maintenance.test.ts -138 tests/codex-integration/codex-log-guard-policy.test.ts +2167 tests/codex-integration/codex-log-guard-inspect.test.ts +95 tests/codex-integration/codex-log-guard-lock.test.ts +43646 tests/codex-integration/codex-log-guard-maintenance-coderabbit.test.ts +13999 tests/codex-integration/codex-log-guard-maintenance.test.ts +79 tests/codex-integration/codex-log-guard-policy.test.ts 65 tests/codex-integration/codex-log-guard-processes.test.ts -2122 tests/codex-integration/codex-log-guard-protection.test.ts -427 tests/codex-integration/codex-log-guard-status-zero-write.test.ts -4301 tests/codex-integration/codex-main-account-refresh.test.ts -7806 tests/codex-integration/codex-main-grant-refusal.test.ts -6340 tests/codex-integration/codex-main-rotation.test.ts -364 tests/codex-integration/codex-main-token-invalidated.test.ts -114 tests/codex-integration/codex-management-convergence.test.ts +3618 tests/codex-integration/codex-log-guard-protection.test.ts +585 tests/codex-integration/codex-log-guard-status-zero-write.test.ts +3582 tests/codex-integration/codex-main-account-refresh.test.ts +7395 tests/codex-integration/codex-main-grant-refusal.test.ts +9483 tests/codex-integration/codex-main-rotation.test.ts +1220 tests/codex-integration/codex-main-token-invalidated.test.ts +111 tests/codex-integration/codex-management-convergence.test.ts 461 tests/codex-integration/codex-metadata-integrity.test.ts -12862 tests/codex-integration/codex-missing-home.test.ts -415 tests/codex-integration/codex-model-availability-error.test.ts -463 tests/codex-integration/codex-model-denial-evidence.test.ts +15150 tests/codex-integration/codex-missing-home.test.ts +222 tests/codex-integration/codex-model-availability-error.test.ts +444 tests/codex-integration/codex-model-denial-evidence.test.ts 374 tests/codex-integration/codex-model-entitlement-admission.test.ts 251 tests/codex-integration/codex-model-entitlements-program-shape.test.ts -3945 tests/codex-integration/codex-model-entitlements.test.ts -1919 tests/codex-integration/codex-models-cache-invalidate.test.ts +3868 tests/codex-integration/codex-model-entitlements.test.ts +2208 tests/codex-integration/codex-models-cache-invalidate.test.ts 4502 tests/codex-integration/codex-native-availability-nux.test.ts -4390 tests/codex-integration/codex-native-residue.test.ts +4436 tests/codex-integration/codex-native-residue.test.ts 1301 tests/codex-integration/codex-pin-drain-projection.test.ts -3300 tests/codex-integration/codex-plan.test.ts +4191 tests/codex-integration/codex-plan.test.ts 905 tests/codex-integration/codex-plugins-doctor.test.ts -713 tests/codex-integration/codex-pool-caller-fallback-policy.test.ts +934 tests/codex-integration/codex-pool-caller-fallback-policy.test.ts 895 tests/codex-integration/codex-pool-credit-policy.test.ts -1109 tests/codex-integration/codex-pool-plan-exclusion.test.ts +6117 tests/codex-integration/codex-pool-plan-exclusion.test.ts 48 tests/codex-integration/codex-pool-refresh-backoff.test.ts -5007 tests/codex-integration/codex-pool-request-owned-main.test.ts +5768 tests/codex-integration/codex-pool-request-owned-main.test.ts 46996 tests/codex-integration/codex-pool-rotation.test.ts -11235 tests/codex-integration/codex-preserve-signed-in.test.ts -15528 tests/codex-integration/codex-priority-failback.test.ts -124 tests/codex-integration/codex-proc-scan-errors.test.ts -1156 tests/codex-integration/codex-prompt-adopt.test.ts -2775 tests/codex-integration/codex-prompt-base-variants.test.ts -652 tests/codex-integration/codex-prompt-journal.test.ts -79 tests/codex-integration/codex-prompt-layers-read.test.ts -2548 tests/codex-integration/codex-prompt-layers-write.test.ts -65 tests/codex-integration/codex-prompt-layers.test.ts -1553 tests/codex-integration/codex-prompt-lock-sharing.test.ts -1371 tests/codex-integration/codex-prompt-lock.test.ts -5369 tests/codex-integration/codex-prompt-route.test.ts +2343 tests/codex-integration/codex-preserve-signed-in.test.ts +2011 tests/codex-integration/codex-priority-failback.test.ts +138 tests/codex-integration/codex-proc-scan-errors.test.ts +2591 tests/codex-integration/codex-prompt-adopt.test.ts +2200 tests/codex-integration/codex-prompt-base-variants.test.ts +491 tests/codex-integration/codex-prompt-journal.test.ts +143 tests/codex-integration/codex-prompt-layers-read.test.ts +4189 tests/codex-integration/codex-prompt-layers-write.test.ts +79 tests/codex-integration/codex-prompt-layers.test.ts +1600 tests/codex-integration/codex-prompt-lock-sharing.test.ts +1847 tests/codex-integration/codex-prompt-lock.test.ts +5286 tests/codex-integration/codex-prompt-route.test.ts 2892 tests/codex-integration/codex-prompt-scalar-scope.test.ts 1457 tests/codex-integration/codex-prompt-text-probe.test.ts -9141 tests/codex-integration/codex-prompt-writes.test.ts -22501 tests/codex-integration/codex-provider-routing.test.ts -3529 tests/codex-integration/codex-provider-table-retention.test.ts -1188 tests/codex-integration/codex-quota-auto-refresh-generation.test.ts -573 tests/codex-integration/codex-quota-auto-refresh-main-admission.test.ts -7625 tests/codex-integration/codex-quota-auto-refresh.test.ts -64 tests/codex-integration/codex-quota-capacity.test.ts -140 tests/codex-integration/codex-quota-history.test.ts +10965 tests/codex-integration/codex-prompt-writes.test.ts +33725 tests/codex-integration/codex-provider-routing.test.ts +3088 tests/codex-integration/codex-provider-table-retention.test.ts +1220 tests/codex-integration/codex-quota-auto-refresh-generation.test.ts +790 tests/codex-integration/codex-quota-auto-refresh-main-admission.test.ts +19759 tests/codex-integration/codex-quota-auto-refresh.test.ts +78 tests/codex-integration/codex-quota-capacity.test.ts +175 tests/codex-integration/codex-quota-history.test.ts 206 tests/codex-integration/codex-quota-parser-parity.test.ts 586 tests/codex-integration/codex-quota-persistence.test.ts -1448 tests/codex-integration/codex-quota-prime.test.ts -2219 tests/codex-integration/codex-quota-query-backoff.test.ts -286 tests/codex-integration/codex-quota-rejection.test.ts -715 tests/codex-integration/codex-refresh.test.ts -2047 tests/codex-integration/codex-request-owned-affinity.test.ts -4713 tests/codex-integration/codex-reset-credit-auto-redeem.test.ts -11960 tests/codex-integration/codex-reset-credit-operation-ledger.test.ts -300 tests/codex-integration/codex-reset-credit-recovery.test.ts +2642 tests/codex-integration/codex-quota-prime.test.ts +2713 tests/codex-integration/codex-quota-query-backoff.test.ts +474 tests/codex-integration/codex-quota-rejection.test.ts +2360 tests/codex-integration/codex-refresh.test.ts +1743 tests/codex-integration/codex-request-owned-affinity.test.ts +8328 tests/codex-integration/codex-reset-credit-auto-redeem.test.ts +10843 tests/codex-integration/codex-reset-credit-operation-ledger.test.ts +315 tests/codex-integration/codex-reset-credit-recovery.test.ts 370 tests/codex-integration/codex-restart-contract-parity.test.ts -1507 tests/codex-integration/codex-restart-route.test.ts -18654 tests/codex-integration/codex-restore-app-rewrite.test.ts -13302 tests/codex-integration/codex-retained-root-serialization.test.ts +1183 tests/codex-integration/codex-restart-route.test.ts +18259 tests/codex-integration/codex-restore-app-rewrite.test.ts +18470 tests/codex-integration/codex-retained-root-serialization.test.ts 11939 tests/codex-integration/codex-round-robin-headroom.test.ts 555 tests/codex-integration/codex-routing-cache-affinity-detour.test.ts -333 tests/codex-integration/codex-routing-elapsed-short-reset.test.ts -21444 tests/codex-integration/codex-routing.test.ts -346 tests/codex-integration/codex-runtime-macos-desktop.test.ts -207 tests/codex-integration/codex-runtime-wsl-desktop.test.ts -1873 tests/codex-integration/codex-runtime.test.ts -1650 tests/codex-integration/codex-service-manager-probe-hardening.test.ts -816 tests/codex-integration/codex-service-manager-probe.test.ts -95 tests/codex-integration/codex-shim-autorestore.test.ts -79 tests/codex-integration/codex-shim-bypass-token.test.ts -237 tests/codex-integration/codex-shim-destroyed-probe.test.ts +285 tests/codex-integration/codex-routing-elapsed-short-reset.test.ts +30913 tests/codex-integration/codex-routing.test.ts +191 tests/codex-integration/codex-runtime-macos-desktop.test.ts +319 tests/codex-integration/codex-runtime-wsl-desktop.test.ts +1269 tests/codex-integration/codex-runtime.test.ts +1430 tests/codex-integration/codex-service-manager-probe-hardening.test.ts +3821 tests/codex-integration/codex-service-manager-probe.test.ts +193 tests/codex-integration/codex-shim-autorestore.test.ts +112 tests/codex-integration/codex-shim-bypass-token.test.ts +95 tests/codex-integration/codex-shim-destroyed-probe.test.ts 96 tests/codex-integration/codex-shim-ensure-failure.test.ts 94 tests/codex-integration/codex-shim-fnm.test.ts -113 tests/codex-integration/codex-shim-migration.test.ts -114 tests/codex-integration/codex-shim-overlay-candidates.test.ts -354 tests/codex-integration/codex-shim-overlay-readiness.test.ts -100 tests/codex-integration/codex-shim-overlay-transaction.test.ts -153 tests/codex-integration/codex-shim-overlay.test.ts -1012 tests/codex-integration/codex-shim-path-readiness.test.ts -2985 tests/codex-integration/codex-shim-readiness.test.ts -172 tests/codex-integration/codex-shim-runtime-preflight.test.ts -234 tests/codex-integration/codex-shim-standalone.test.ts -786 tests/codex-integration/codex-shim-windows-revision.test.ts -17438 tests/codex-integration/codex-shim.test.ts -3702 tests/codex-integration/codex-sidecar-credit-policy.test.ts -202 tests/codex-integration/codex-signin-lockout.test.ts -1125 tests/codex-integration/codex-spark-visibility.test.ts +66 tests/codex-integration/codex-shim-migration.test.ts +313 tests/codex-integration/codex-shim-overlay-candidates.test.ts +160 tests/codex-integration/codex-shim-overlay-readiness.test.ts +69 tests/codex-integration/codex-shim-overlay-transaction.test.ts +81 tests/codex-integration/codex-shim-overlay.test.ts +791 tests/codex-integration/codex-shim-path-readiness.test.ts +3093 tests/codex-integration/codex-shim-readiness.test.ts +205 tests/codex-integration/codex-shim-runtime-preflight.test.ts +79 tests/codex-integration/codex-shim-standalone.test.ts +379 tests/codex-integration/codex-shim-windows-revision.test.ts +14502 tests/codex-integration/codex-shim.test.ts +3465 tests/codex-integration/codex-sidecar-credit-policy.test.ts +175 tests/codex-integration/codex-signin-lockout.test.ts +1284 tests/codex-integration/codex-spark-visibility.test.ts 77 tests/codex-integration/codex-sqlite-home.test.ts 13265 tests/codex-integration/codex-stored-main-duplicate.test.ts -2619 tests/codex-integration/codex-sync-api.test.ts -3903 tests/codex-integration/codex-sync-new-model-policy.test.ts -64 tests/codex-integration/codex-sync-response.test.ts -69364 tests/codex-integration/codex-sync-user-edits.test.ts -396 tests/codex-integration/codex-systemd-env-probe.test.ts -263 tests/codex-integration/codex-tool-mode.test.ts -1157 tests/codex-integration/codex-transition-state-adoption.test.ts -473 tests/codex-integration/codex-transition-state-first-use-regression.test.ts -2996 tests/codex-integration/codex-transition-state-race.test.ts +3214 tests/codex-integration/codex-sync-api.test.ts +3808 tests/codex-integration/codex-sync-new-model-policy.test.ts +292 tests/codex-integration/codex-sync-response.test.ts +68091 tests/codex-integration/codex-sync-user-edits.test.ts +918 tests/codex-integration/codex-systemd-env-probe.test.ts +236 tests/codex-integration/codex-tool-mode.test.ts +1046 tests/codex-integration/codex-transition-state-adoption.test.ts +286 tests/codex-integration/codex-transition-state-first-use-regression.test.ts +2216 tests/codex-integration/codex-transition-state-race.test.ts 2581 tests/codex-integration/codex-transition-state.test.ts 1060 tests/codex-integration/codex-use-remaining-quota.test.ts -190 tests/codex-integration/codex-user-identity.test.ts +143 tests/codex-integration/codex-user-identity.test.ts 13699 tests/codex-integration/codex-v2-gate.test.ts -412 tests/codex-integration/codex-warmup.test.ts -11190 tests/codex-integration/codex-web-search-switch.test.ts -173 tests/codex-integration/codex-websocket-registry.test.ts +507 tests/codex-integration/codex-warmup.test.ts +11081 tests/codex-integration/codex-web-search-switch.test.ts +176 tests/codex-integration/codex-websocket-registry.test.ts 205 tests/codex-integration/codex-windows-current-sid.test.ts 6883 tests/codex-integration/codex-write-lock.test.ts 80 tests/codex-integration/combo-authoritative-reset.test.ts 270 tests/codex-integration/combo-codex-exhaustion-cooldown.test.ts -177 tests/codex-integration/combo-cooldown-reprobe.test.ts -4013 tests/codex-integration/combo-description-catalog.test.ts -82 tests/codex-integration/combo-last-resort.test.ts -78 tests/codex-integration/combo-permanent-failure-cooldown.test.ts -156 tests/codex-integration/combo-reset-window-model-scope.test.ts -48 tests/codex-integration/combos-kiro-profile-hop.test.ts -493 tests/codex-integration/combos.test.ts -1197 tests/codex-integration/compatibility-manifest.test.ts -160 tests/codex-integration/configured-native-models.test.ts -3963 tests/codex-integration/configured-ultrafast-picker.test.ts -62 tests/codex-integration/context-compat.test.ts -162 tests/codex-integration/custom-model-catalog-migration.test.ts -708 tests/codex-integration/deferred-collab-surface.test.ts +176 tests/codex-integration/combo-cooldown-reprobe.test.ts +3414 tests/codex-integration/combo-description-catalog.test.ts +242 tests/codex-integration/combo-last-resort.test.ts +79 tests/codex-integration/combo-permanent-failure-cooldown.test.ts +64 tests/codex-integration/combo-reset-window-model-scope.test.ts +47 tests/codex-integration/combos-kiro-profile-hop.test.ts +412 tests/codex-integration/combos.test.ts +1380 tests/codex-integration/compatibility-manifest.test.ts +140 tests/codex-integration/configured-native-models.test.ts +4005 tests/codex-integration/configured-ultrafast-picker.test.ts +79 tests/codex-integration/context-compat.test.ts +64 tests/codex-integration/custom-model-catalog-migration.test.ts +348 tests/codex-integration/deferred-collab-surface.test.ts 1331 tests/codex-integration/discovered-native-models.test.ts -5469 tests/codex-integration/doctor.test.ts -616 tests/codex-integration/effort-policy.test.ts -2576 tests/codex-integration/exec-boundary-launch.test.ts +7198 tests/codex-integration/doctor.test.ts +950 tests/codex-integration/effort-policy.test.ts +2435 tests/codex-integration/exec-boundary-launch.test.ts 271 tests/codex-integration/exec-cli-bundle-containment.test.ts -401 tests/codex-integration/exec-cli-renamed-app-bundle.test.ts -221 tests/codex-integration/exec-known-app-bundles.test.ts -143 tests/codex-integration/exec-launcher-boundary.test.ts -111 tests/codex-integration/exec-renamed-app-bundle.test.ts -301 tests/codex-integration/exec-trust-boundary.test.ts -162 tests/codex-integration/fast-row-listing.test.ts -130 tests/codex-integration/fast-row.test.ts -270 tests/codex-integration/gather-routed-models-single-flight.test.ts -96 tests/codex-integration/gpt6-native-rows.test.ts +206 tests/codex-integration/exec-cli-renamed-app-bundle.test.ts +320 tests/codex-integration/exec-known-app-bundles.test.ts +129 tests/codex-integration/exec-launcher-boundary.test.ts +95 tests/codex-integration/exec-renamed-app-bundle.test.ts +235 tests/codex-integration/exec-trust-boundary.test.ts +128 tests/codex-integration/fast-row-listing.test.ts +159 tests/codex-integration/fast-row.test.ts +266 tests/codex-integration/gather-routed-models-single-flight.test.ts +174 tests/codex-integration/gpt6-native-rows.test.ts 109 tests/codex-integration/gpt61-sol-rows.test.ts -171 tests/codex-integration/gpt61-terra-rows.test.ts -47 tests/codex-integration/history-migration-guardian.test.ts -427 tests/codex-integration/history-ocx-compaction-recovery.test.ts +400 tests/codex-integration/gpt61-terra-rows.test.ts +93 tests/codex-integration/history-migration-guardian.test.ts +889 tests/codex-integration/history-ocx-compaction-recovery.test.ts 64 tests/codex-integration/history-paginated-openai-compat.test.ts -4359 tests/codex-integration/history-paginated-transition-destinations.test.ts -109 tests/codex-integration/injection-link-websocket.test.ts -3092 tests/codex-integration/injection-model-api.test.ts -221 tests/codex-integration/injection-model-suggest-routes.test.ts +3877 tests/codex-integration/history-paginated-transition-destinations.test.ts +205 tests/codex-integration/injection-link-websocket.test.ts +2674 tests/codex-integration/injection-model-api.test.ts +262 tests/codex-integration/injection-model-suggest-routes.test.ts 92 tests/codex-integration/injection-routing-drift.test.ts 7101 tests/codex-integration/injection-routing-heal-apply.test.ts -924 tests/codex-integration/injection-routing-healer.test.ts -22857 tests/codex-integration/issue-452-empty-503.test.ts +664 tests/codex-integration/injection-routing-healer.test.ts +17971 tests/codex-integration/issue-452-empty-503.test.ts 55233 tests/codex-integration/issue-702-expired-replay-state.test.ts -1185 tests/codex-integration/issue-914-transport-attribution.test.ts -206 tests/codex-integration/low-quota-desktop-notifier.test.ts -13393 tests/codex-integration/low-quota-protection.test.ts -1395 tests/codex-integration/main-account-credit-renewal.test.ts -65 tests/codex-integration/main-account-external-usage.test.ts -24015 tests/codex-integration/main-account-hard-lock-auth.test.ts +1683 tests/codex-integration/issue-914-transport-attribution.test.ts +296 tests/codex-integration/low-quota-desktop-notifier.test.ts +5743 tests/codex-integration/low-quota-protection.test.ts +1061 tests/codex-integration/main-account-credit-renewal.test.ts +63 tests/codex-integration/main-account-external-usage.test.ts +29509 tests/codex-integration/main-account-hard-lock-auth.test.ts 522 tests/codex-integration/main-account-hard-lock-default.test.ts -11474 tests/codex-integration/main-account-hard-lock-fallback-off.test.ts -8893 tests/codex-integration/main-account-hard-lock-fallback-routing.test.ts -129 tests/codex-integration/main-account-hard-lock-policy.test.ts +9643 tests/codex-integration/main-account-hard-lock-fallback-off.test.ts +8558 tests/codex-integration/main-account-hard-lock-fallback-routing.test.ts +285 tests/codex-integration/main-account-hard-lock-policy.test.ts 1029 tests/codex-integration/main-account-hard-lock-profile-dispatch.test.ts -1444 tests/codex-integration/main-account-hard-lock-recovery.test.ts -190 tests/codex-integration/main-account-hard-lock-retirement.test.ts -86 tests/codex-integration/main-account-hard-lock-thresholds.test.ts -710 tests/codex-integration/main-account-hard-lock-usage-limit.test.ts +1681 tests/codex-integration/main-account-hard-lock-recovery.test.ts +175 tests/codex-integration/main-account-hard-lock-retirement.test.ts +112 tests/codex-integration/main-account-hard-lock-thresholds.test.ts +650 tests/codex-integration/main-account-hard-lock-usage-limit.test.ts 1122 tests/codex-integration/main-account-policy-binding-wait.test.ts 126 tests/codex-integration/main-device-reauth-api.test.ts -594 tests/codex-integration/main-device-reauth.test.ts -349 tests/codex-integration/main-quota-evidence-validation.test.ts +443 tests/codex-integration/main-device-reauth.test.ts +413 tests/codex-integration/main-quota-evidence-validation.test.ts 8112 tests/codex-integration/main-quota-provenance.test.ts -1924 tests/codex-integration/main-quota-window-observation.test.ts -404 tests/codex-integration/messaging-local-cli.test.ts -96 tests/codex-integration/messaging-local-discovery.test.ts -190 tests/codex-integration/messaging-local-envelope.test.ts -602 tests/codex-integration/messaging-local-lifecycle.test.ts +1705 tests/codex-integration/main-quota-window-observation.test.ts +475 tests/codex-integration/messaging-local-cli.test.ts +64 tests/codex-integration/messaging-local-discovery.test.ts +339 tests/codex-integration/messaging-local-envelope.test.ts +730 tests/codex-integration/messaging-local-lifecycle.test.ts 79 tests/codex-integration/messaging-local-send.test.ts -138 tests/codex-integration/messaging-local-socket.test.ts -63 tests/codex-integration/messaging-mcp-queue.test.ts -95 tests/codex-integration/messaging-remote-admission.test.ts -110 tests/codex-integration/messaging-remote-contract.test.ts -127 tests/codex-integration/messaging-remote-enrollment-gaps.test.ts -64 tests/codex-integration/messaging-remote-enrollment.test.ts +64 tests/codex-integration/messaging-local-socket.test.ts +80 tests/codex-integration/messaging-mcp-queue.test.ts +94 tests/codex-integration/messaging-remote-admission.test.ts +111 tests/codex-integration/messaging-remote-contract.test.ts +62 tests/codex-integration/messaging-remote-enrollment-gaps.test.ts +114 tests/codex-integration/messaging-remote-enrollment.test.ts 111 tests/codex-integration/messaging-remote-forward-failure.test.ts -95 tests/codex-integration/messaging-remote-gaps.test.ts -94 tests/codex-integration/messaging-remote-interop.test.ts -78 tests/codex-integration/messaging-remote-lifecycle.test.ts +77 tests/codex-integration/messaging-remote-gaps.test.ts +111 tests/codex-integration/messaging-remote-interop.test.ts +190 tests/codex-integration/messaging-remote-lifecycle.test.ts 225 tests/codex-integration/messaging-remote-native.test.ts 99 tests/codex-integration/messaging-remote-port-reservation.test.ts -13186 tests/codex-integration/messaging-remote-process.test.ts -111 tests/codex-integration/messaging-remote-replies.test.ts -76 tests/codex-integration/messaging-remote-scratch.test.ts -237 tests/codex-integration/messaging-remote-send.test.ts -625 tests/codex-integration/messaging-remote-store.test.ts -45 tests/codex-integration/model-cache-generation-tombstone.test.ts -80 tests/codex-integration/model-cache.test.ts -445 tests/codex-integration/model-display-names-management-api.test.ts -156 tests/codex-integration/model-metadata-sync.test.ts +13223 tests/codex-integration/messaging-remote-process.test.ts +108 tests/codex-integration/messaging-remote-replies.test.ts +143 tests/codex-integration/messaging-remote-scratch.test.ts +80 tests/codex-integration/messaging-remote-send.test.ts +632 tests/codex-integration/messaging-remote-store.test.ts +64 tests/codex-integration/model-cache-generation-tombstone.test.ts +77 tests/codex-integration/model-cache.test.ts +412 tests/codex-integration/model-display-names-management-api.test.ts +142 tests/codex-integration/model-metadata-sync.test.ts 12270 tests/codex-integration/model-pinned-effort.test.ts 9331 tests/codex-integration/model-visibility-management-api.test.ts -2090 tests/codex-integration/multi-agent-compat.test.ts -4082 tests/codex-integration/multi-agent-keep-native-v1.test.ts +2333 tests/codex-integration/multi-agent-compat.test.ts +6630 tests/codex-integration/multi-agent-keep-native-v1.test.ts 156 tests/codex-integration/multi-agent-origin.test.ts -443 tests/codex-integration/native-alias-maintainer-regressions.test.ts -1061 tests/codex-integration/native-claude-code-toggle.test.ts +206 tests/codex-integration/native-alias-maintainer-regressions.test.ts +476 tests/codex-integration/native-claude-code-toggle.test.ts 27050 tests/codex-integration/native-claude-desktop-toggle.test.ts -20753 tests/codex-integration/native-codex-toggle.test.ts -1213 tests/codex-integration/native-grok-toggle.test.ts -155 tests/codex-integration/native-main-auth-temp.test.ts -132 tests/codex-integration/native-main-claim-cache.test.ts -252 tests/codex-integration/native-main-claim.test.ts -32198 tests/codex-integration/native-main-owner-lifetime.test.ts -5785 tests/codex-integration/native-main-refresh-mode.test.ts -919 tests/codex-integration/native-model-toggle.test.ts -244 tests/codex-integration/native-profile-api.test.ts +22925 tests/codex-integration/native-codex-toggle.test.ts +2065 tests/codex-integration/native-grok-toggle.test.ts +256 tests/codex-integration/native-main-auth-temp.test.ts +207 tests/codex-integration/native-main-claim-cache.test.ts +471 tests/codex-integration/native-main-claim.test.ts +31537 tests/codex-integration/native-main-owner-lifetime.test.ts +5670 tests/codex-integration/native-main-refresh-mode.test.ts +998 tests/codex-integration/native-model-toggle.test.ts +158 tests/codex-integration/native-profile-api.test.ts 19426 tests/codex-integration/native-profile-crash-boundaries.test.ts -10580 tests/codex-integration/native-profile-drain-server.test.ts -8712 tests/codex-integration/native-profile-manager.test.ts -430 tests/codex-integration/native-profile-processes.test.ts -82 tests/codex-integration/native-profile-recovery.test.ts -6236 tests/codex-integration/native-profile-route-security.test.ts -1523 tests/codex-integration/native-profile-stage-lifecycle.test.ts -1187 tests/codex-integration/native-profile-startup-release.test.ts -62246 tests/codex-integration/native-profile-startup.test.ts -793 tests/codex-integration/native-profile-store.test.ts -253 tests/codex-integration/native-source-priority.test.ts -4535 tests/codex-integration/native-ultrafast-picker.test.ts +11792 tests/codex-integration/native-profile-drain-server.test.ts +20023 tests/codex-integration/native-profile-manager.test.ts +429 tests/codex-integration/native-profile-processes.test.ts +65 tests/codex-integration/native-profile-recovery.test.ts +4730 tests/codex-integration/native-profile-route-security.test.ts +1733 tests/codex-integration/native-profile-stage-lifecycle.test.ts +870 tests/codex-integration/native-profile-startup-release.test.ts +56965 tests/codex-integration/native-profile-startup.test.ts +670 tests/codex-integration/native-profile-store.test.ts +220 tests/codex-integration/native-source-priority.test.ts +5627 tests/codex-integration/native-ultrafast-picker.test.ts 14169 tests/codex-integration/orca-import.test.ts -270 tests/codex-integration/parallel-tool-calls-optin.test.ts -94 tests/codex-integration/project-config-warning-snapshot.test.ts -139 tests/codex-integration/project-config-warnings.test.ts -395 tests/codex-integration/reasoning-effort.test.ts -296 tests/codex-integration/reasoning-metadata.test.ts -1234 tests/codex-integration/reserve-auth-context.test.ts +238 tests/codex-integration/parallel-tool-calls-optin.test.ts +237 tests/codex-integration/project-config-warning-snapshot.test.ts +159 tests/codex-integration/project-config-warnings.test.ts +398 tests/codex-integration/reasoning-effort.test.ts +238 tests/codex-integration/reasoning-metadata.test.ts +1741 tests/codex-integration/reserve-auth-context.test.ts 245 tests/codex-integration/reserve-availability.test.ts -13016 tests/codex-integration/reserve-catalog-lifecycle.test.ts -159 tests/codex-integration/reserve-catalog.test.ts +9931 tests/codex-integration/reserve-catalog-lifecycle.test.ts +271 tests/codex-integration/reserve-catalog.test.ts 2659 tests/codex-integration/reserve-dispatch.test.ts -127 tests/codex-integration/reserve-helper-boundary.test.ts -266 tests/codex-integration/reserve-passive-revocation.test.ts -2286 tests/codex-integration/reserve-quota-scope.test.ts -96 tests/codex-integration/selected-models.test.ts -420 tests/codex-integration/slug-codec.test.ts -5806 tests/codex-integration/token-guardian.test.ts -4095 tests/codex-integration/ultrafast-live-catalog.test.ts -4889 tests/codex-integration/ultrafast-tier-honesty.test.ts -113 tests/codex-integration/upstream-reachability.test.ts -284 tests/codex-integration/vendor-context.test.ts -47 tests/codex-integration/warmup.test.ts -480 tests/codex-integration/websocket-capacity-activity.test.ts -798 tests/config/atomic-write-exclusive.test.ts -364 tests/config/atomic-write-nofollow-streamed.test.ts +364 tests/codex-integration/reserve-helper-boundary.test.ts +205 tests/codex-integration/reserve-passive-revocation.test.ts +2497 tests/codex-integration/reserve-quota-scope.test.ts +145 tests/codex-integration/selected-models.test.ts +497 tests/codex-integration/slug-codec.test.ts +9259 tests/codex-integration/token-guardian.test.ts +2946 tests/codex-integration/ultrafast-live-catalog.test.ts +3768 tests/codex-integration/ultrafast-tier-honesty.test.ts +140 tests/codex-integration/upstream-reachability.test.ts +237 tests/codex-integration/vendor-context.test.ts +80 tests/codex-integration/warmup.test.ts +31 tests/codex-integration/websocket-capacity-activity.test.ts +780 tests/config/atomic-write-exclusive.test.ts +205 tests/config/atomic-write-nofollow-streamed.test.ts 239 tests/config/client-config-export-new-clients.test.ts 127 tests/config/client-config-export-output-limit.test.ts -221 tests/config/client-config-export.test.ts -140 tests/config/client-config-new-clients.test.ts -273 tests/config/compaction-recovery-settings.test.ts -23040 tests/config/config-account-auto-pause-revisions.test.ts -364 tests/config/config-account-thresholds.test.ts +222 tests/config/client-config-export.test.ts +144 tests/config/client-config-new-clients.test.ts +173 tests/config/compaction-recovery-settings.test.ts +20971 tests/config/config-account-auto-pause-revisions.test.ts +536 tests/config/config-account-thresholds.test.ts 5856 tests/config/config-anthropic-instance-pool.test.ts 173 tests/config/config-blocked-model-redirects.test.ts -206 tests/config/config-catalog-auto-refresh.test.ts -64 tests/config/config-commandcode-claude-pin.test.ts -1237 tests/config/config-concurrent-inbound-body.test.ts +402 tests/config/config-catalog-auto-refresh.test.ts +78 tests/config/config-commandcode-claude-pin.test.ts +1488 tests/config/config-concurrent-inbound-body.test.ts 78 tests/config/config-hosted-search-projection.test.ts -2403 tests/config/config-load-degrade.test.ts -6750 tests/config/config-mutation-lock.test.ts -175 tests/config/config-native-reasoning-retention.test.ts -283 tests/config/config-non-object-backup.test.ts -2664 tests/config/config-opencode-go-upgrade.test.ts +3553 tests/config/config-load-degrade.test.ts +5722 tests/config/config-mutation-lock.test.ts +174 tests/config/config-native-reasoning-retention.test.ts +333 tests/config/config-non-object-backup.test.ts +2384 tests/config/config-opencode-go-upgrade.test.ts 1280 tests/config/config-opencode-zen-upgrade.test.ts 941 tests/config/config-ownership-uninstall.test.ts -64 tests/config/config-rebase-provenance-writers.test.ts +79 tests/config/config-rebase-provenance-writers.test.ts 331 tests/config/config-removed-opencode-free-preserve-failure.test.ts -113227 tests/config/config-removed-opencode-free.test.ts +107871 tests/config/config-removed-opencode-free.test.ts 141 tests/config/config-save-boundary.test.ts -427 tests/config/config-skills-catalog-refresh.test.ts -589 tests/config/config-spend-ceilings.test.ts +379 tests/config/config-skills-catalog-refresh.test.ts +459 tests/config/config-spend-ceilings.test.ts 190 tests/config/config-spend-pool-collision.test.ts -20109 tests/config/config-user-edits.test.ts -79 tests/config/expand-user-path.test.ts +19714 tests/config/config-user-edits.test.ts +127 tests/config/config-workflow-budget.test.ts +187 tests/config/expand-user-path.test.ts 8583 tests/config/hub-disable-live-save.test.ts -247 tests/config/lmstudio-system-policy.test.ts -6209 tests/config/local-credential-generation.test.ts +96 tests/config/lmstudio-system-policy.test.ts +11829 tests/config/local-credential-generation.test.ts 6137 tests/config/model-pinned-effort-config.test.ts -111 tests/config/owner-registry-acl.test.ts -506 tests/config/owner-registry-isolation.test.ts +142 tests/config/owner-registry-acl.test.ts +580 tests/config/owner-registry-isolation.test.ts 139 tests/config/protocol-settings.test.ts -8419 tests/config/serving-runtimes.test.ts -3502 tests/config/settings-desktop-switch-apply.test.ts -1169 tests/config/settings-fast-rows.test.ts -3264 tests/config/settings-main-account-hard-lock.test.ts -1754 tests/config/settings-memory-models.test.ts -1489 tests/config/settings-oauth-open-browser.test.ts -874 tests/config/settings-reasoning-retention.test.ts -270 tests/config/settings-startup-health-seam.test.ts -24079 tests/config/settings-stream-mode.test.ts -80 tests/config/types-barrel-identity.test.ts -62 tests/config/url-normalization.test.ts -155 tests/config/yaml-fragment-source.test.ts -238 tests/e2e-style/phase100-native-parity.test.ts -95 tests/gui/alibaba-intl-token-plan.test.ts +8316 tests/config/serving-runtimes.test.ts +3373 tests/config/settings-desktop-switch-apply.test.ts +1681 tests/config/settings-fast-rows.test.ts +2774 tests/config/settings-main-account-hard-lock.test.ts +1238 tests/config/settings-memory-models.test.ts +1377 tests/config/settings-oauth-open-browser.test.ts +647 tests/config/settings-reasoning-retention.test.ts +223 tests/config/settings-startup-health-seam.test.ts +21783 tests/config/settings-stream-mode.test.ts +97 tests/config/types-barrel-identity.test.ts +216 tests/config/url-normalization.test.ts +61 tests/config/yaml-fragment-source.test.ts +222 tests/e2e-style/phase100-native-parity.test.ts +236 tests/gui/alibaba-intl-token-plan.test.ts 175 tests/gui/claude-manual-env.test.ts -63 tests/gui/codex-account-mode-state.test.ts -237 tests/gui/codex-auth-modal-status.test.ts -79 tests/gui/codex-set-prompt.test.ts -99 tests/gui/combo-workspace-data.test.ts -80 tests/gui/combo-workspace-jev-decision.test.ts -95 tests/gui/dashboard-sidecar-codex-write.test.ts -172 tests/gui/dashboard-uptime.test.ts -64 tests/gui/gui-api-error.test.ts -190 tests/gui/gui-codex-usage-score-parity.test.ts -46 tests/gui/gui-desktop-sidecar-script.test.ts -237 tests/gui/gui-desktop-sidecar-signing.test.ts -169 tests/gui/gui-management-session.test.ts -78 tests/gui/gui-pair-capability.test.ts -994 tests/gui/gui-pair-client.test.ts -3154 tests/gui/gui-pair-delivery.test.ts +167 tests/gui/codex-account-mode-state.test.ts +78 tests/gui/codex-auth-modal-status.test.ts +64 tests/gui/codex-set-prompt.test.ts +98 tests/gui/combo-workspace-data.test.ts +99 tests/gui/combo-workspace-jev-decision.test.ts +224 tests/gui/dashboard-sidecar-codex-write.test.ts +162 tests/gui/dashboard-uptime.test.ts +47 tests/gui/gui-api-error.test.ts +112 tests/gui/gui-codex-usage-score-parity.test.ts +79 tests/gui/gui-desktop-sidecar-script.test.ts +80 tests/gui/gui-desktop-sidecar-signing.test.ts +205 tests/gui/gui-management-session.test.ts +76 tests/gui/gui-pair-capability.test.ts +1536 tests/gui/gui-pair-client.test.ts +3314 tests/gui/gui-pair-delivery.test.ts 3983 tests/gui/gui-pair-http.test.ts -218 tests/gui/gui-static.test.ts -79 tests/gui/gui-tray-vibrancy-surface.test.ts -222 tests/gui/html-lang-boot-script.test.ts -9556 tests/gui/integrations-invariants.test.ts -111 tests/gui/logs-model-tier-confirmation.test.ts -48 tests/gui/main-device-reauth-ui.test.ts -47 tests/gui/models-feedback-callback.test.ts -97 tests/gui/models-free-filter.test.ts -77 tests/gui/models-page-groups.test.ts +371 tests/gui/gui-static.test.ts +78 tests/gui/gui-tray-vibrancy-surface.test.ts +173 tests/gui/html-lang-boot-script.test.ts +12039 tests/gui/integrations-invariants.test.ts +95 tests/gui/logs-model-tier-confirmation.test.ts +64 tests/gui/main-device-reauth-ui.test.ts +172 tests/gui/models-feedback-callback.test.ts +96 tests/gui/models-free-filter.test.ts +63 tests/gui/models-page-groups.test.ts 48 tests/gui/models-workspace-tabs.test.ts 64 tests/gui/oauth-first-add-hint.test.ts 110 tests/gui/oauth-tos-warning.test.ts -395 tests/gui/platform-dialog-guard.test.ts -326 tests/gui/provider-payload.test.ts -228 tests/gui/provider-subscription-cli.test.ts -81 tests/gui/provider-workspace-auth.test.ts -95 tests/gui/provider-workspace-data.test.ts -79 tests/gui/provider-workspace-rail.test.ts -243 tests/gui/provider-workspace-state.test.ts +680 tests/gui/platform-dialog-guard.test.ts +77 tests/gui/provider-payload.test.ts +222 tests/gui/provider-subscription-cli.test.ts +76 tests/gui/provider-workspace-auth.test.ts +176 tests/gui/provider-workspace-data.test.ts +376 tests/gui/provider-workspace-rail.test.ts +171 tests/gui/provider-workspace-state.test.ts 112 tests/gui/quota-bars-rows.test.ts -50 tests/gui/qwen-cloud-endpoints.test.ts -109 tests/gui/rate-limit-reset-credits.test.ts -47 tests/gui/routing-intelligence-ui.test.ts -181 tests/gui/routing-profile-editor-data.test.ts -77 tests/gui/standalone-build-script.test.ts +81 tests/gui/qwen-cloud-endpoints.test.ts +80 tests/gui/rate-limit-reset-credits.test.ts +218 tests/gui/routing-intelligence-ui.test.ts +81 tests/gui/routing-profile-editor-data.test.ts +62 tests/gui/standalone-build-script.test.ts 301 tests/gui/startup-health-ui.test.ts -204 tests/gui/tencent-siliconflow-providers.test.ts -440 tests/gui/vision-sidecar-timeout-bounds.test.ts -398 tests/gui/volcengine-providers.test.ts -157 tests/images/artifacts-prune.test.ts -79 tests/images/artifacts-ssrf.test.ts -139 tests/images/download-cap-default.test.ts +176 tests/gui/tencent-siliconflow-providers.test.ts +254 tests/gui/vision-sidecar-timeout-bounds.test.ts +365 tests/gui/volcengine-providers.test.ts +140 tests/images/artifacts-prune.test.ts +110 tests/images/artifacts-ssrf.test.ts +64 tests/images/download-cap-default.test.ts 79 tests/images/download-connect-deadline-default.test.ts 143 tests/images/gemini-inline.test.ts -215 tests/images/loop-reasoning-replay.test.ts +125 tests/images/loop-reasoning-replay.test.ts 189 tests/images/loop-terminal-refusal.test.ts -3512 tests/images/loop.test.ts -88 tests/images/pinned-https-get.test.ts +3477 tests/images/loop.test.ts +111 tests/images/pinned-https-get.test.ts 208 tests/images/plan.test.ts -80 tests/images/synthetic-tool.test.ts -128 tests/images/xai-client.test.ts -307 tests/images/z-fulfill.test.ts -731 tests/images/z-handler-activation.test.ts -808 tests/lab/core-lab-boundary.test.ts -428 tests/lab/core-link-boundary.test.ts -15941 tests/lab/lab-activation.test.ts +78 tests/images/synthetic-tool.test.ts +157 tests/images/xai-client.test.ts +206 tests/images/z-fulfill.test.ts +958 tests/images/z-handler-activation.test.ts +634 tests/lab/core-lab-boundary.test.ts +332 tests/lab/core-link-boundary.test.ts +16036 tests/lab/lab-activation.test.ts 777 tests/lab/lab-automation-coderabbit-regressions.test.ts -1850 tests/lab/lab-automation-final-coderabbit-regressions.test.ts -857 tests/lab/lab-automation-ingwannu-regressions.test.ts -710 tests/lab/lab-automation-management-http.test.ts -63 tests/lab/lab-automation-persisted-cap-regression.test.ts -4444 tests/lab/lab-automation-review-regressions.test.ts -2697 tests/lab/lab-automation.test.ts -1619 tests/lab/lab-community-evidence.test.ts -738 tests/lab/lab-community-filename-contract.test.ts -124 tests/lab/lab-community-mutation-lock.test.ts -842 tests/lab/lab-community-publisher-continuity.test.ts -543 tests/lab/lab-conformance-harness.test.ts -371 tests/lab/lab-conformance-runner-failures.test.ts -2630 tests/lab/lab-evidence-ledger.test.ts -1511 tests/lab/lab-evidence-sanitization.test.ts -238 tests/lab/lab-fabric-outcome-validation.test.ts +1954 tests/lab/lab-automation-final-coderabbit-regressions.test.ts +986 tests/lab/lab-automation-ingwannu-regressions.test.ts +887 tests/lab/lab-automation-management-http.test.ts +64 tests/lab/lab-automation-persisted-cap-regression.test.ts +3695 tests/lab/lab-automation-review-regressions.test.ts +2100 tests/lab/lab-automation.test.ts +1851 tests/lab/lab-community-evidence.test.ts +1363 tests/lab/lab-community-filename-contract.test.ts +270 tests/lab/lab-community-mutation-lock.test.ts +680 tests/lab/lab-community-publisher-continuity.test.ts +302 tests/lab/lab-conformance-harness.test.ts +239 tests/lab/lab-conformance-runner-failures.test.ts +2995 tests/lab/lab-evidence-ledger.test.ts +1172 tests/lab/lab-evidence-sanitization.test.ts +127 tests/lab/lab-fabric-outcome-validation.test.ts 63 tests/lab/lab-fabric-persistence-boundary.test.ts -623 tests/lab/lab-fabric-producer-deadline.test.ts -151650 tests/lab/lab-fabric-task.test.ts -79 tests/lab/lab-installation-salt-cache.test.ts -1410 tests/lab/lab-ledger-mutation-lock.test.ts -348 tests/lab/lab-live-pinned-timeouts.test.ts -457 tests/lab/lab-live-probe.test.ts +413 tests/lab/lab-fabric-producer-deadline.test.ts +151034 tests/lab/lab-fabric-task.test.ts +206 tests/lab/lab-installation-salt-cache.test.ts +883 tests/lab/lab-ledger-mutation-lock.test.ts +379 tests/lab/lab-live-pinned-timeouts.test.ts +682 tests/lab/lab-live-probe.test.ts 207 tests/lab/lab-live-receipt-integrity.test.ts 349 tests/lab/lab-live-review-regressions.test.ts -538 tests/lab/lab-live-sandbox.test.ts -238 tests/lab/lab-passive-production-evidence.test.ts -236 tests/lab/lab-passive-production-surfaces.test.ts -108 tests/lab/lab-paths-security.test.ts +507 tests/lab/lab-live-sandbox.test.ts +207 tests/lab/lab-passive-production-evidence.test.ts +365 tests/lab/lab-passive-production-surfaces.test.ts +178 tests/lab/lab-paths-security.test.ts 204 tests/lab/lab-post-merge-hardening.test.ts -316 tests/lab/lab-post-merge-projection.test.ts -48 tests/lab/lab-private-file-consumer-recovery.test.ts +174 tests/lab/lab-post-merge-projection.test.ts +94 tests/lab/lab-private-file-consumer-recovery.test.ts 78 tests/lab/lab-private-file-durability.test.ts -332 tests/lab/lab-public-api-json.test.ts -97 tests/lab/lab-public-artifact-policy.test.ts -1466 tests/lab/lab-public-coderabbit-regressions.test.ts -145 tests/lab/lab-public-core-contract.test.ts -1681 tests/lab/lab-public-deep-review-regressions.test.ts -1322 tests/lab/lab-public-evidence.test.ts -509 tests/lab/lab-public-export-transaction.test.ts -61 tests/lab/lab-public-file-safety.test.ts -1141 tests/lab/lab-public-final-review-regressions.test.ts -2156 tests/lab/lab-public-lifecycle-hardening.test.ts +301 tests/lab/lab-public-api-json.test.ts +129 tests/lab/lab-public-artifact-policy.test.ts +1506 tests/lab/lab-public-coderabbit-regressions.test.ts +681 tests/lab/lab-public-core-contract.test.ts +1584 tests/lab/lab-public-deep-review-regressions.test.ts +650 tests/lab/lab-public-evidence.test.ts +788 tests/lab/lab-public-export-transaction.test.ts +224 tests/lab/lab-public-file-safety.test.ts +1239 tests/lab/lab-public-final-review-regressions.test.ts +1934 tests/lab/lab-public-lifecycle-hardening.test.ts 79 tests/lab/lab-public-privacy-ipv6.test.ts -4206 tests/lab/lab-public-provenance-recovery.test.ts +4344 tests/lab/lab-public-provenance-recovery.test.ts 1979 tests/lab/lab-public-review-fixes.test.ts -178 tests/lab/lab-public-route-registry.test.ts +79 tests/lab/lab-public-route-registry.test.ts 206 tests/lab/lab-public-security-regressions.test.ts -1347 tests/lab/lab-public-surfaces.test.ts -414 tests/lab/lab-public-wire-contract.test.ts -365 tests/lab/lab-read-filter-validation.test.ts -49678 tests/lab/lab-read-surfaces.test.ts -744 tests/lib/abort-idle-deadline.test.ts -48 tests/lib/acl-error-classification.test.ts -380 tests/lib/ambiguous-resend-composition.test.ts -110 tests/lib/ambiguous-resend-gate.test.ts -232 tests/lib/authorization-scheme.test.ts -80 tests/lib/bounded-file-read.test.ts +1690 tests/lab/lab-public-surfaces.test.ts +430 tests/lab/lab-public-wire-contract.test.ts +601 tests/lab/lab-read-filter-validation.test.ts +46982 tests/lab/lab-read-surfaces.test.ts +756 tests/lib/abort-idle-deadline.test.ts +79 tests/lib/acl-error-classification.test.ts +490 tests/lib/ambiguous-resend-composition.test.ts +64 tests/lib/ambiguous-resend-gate.test.ts +64 tests/lib/authorization-scheme.test.ts +126 tests/lib/bounded-file-read.test.ts 283 tests/lib/bun-runtime-preflight.test.ts -49 tests/lib/bun-stream-caps.test.ts -156 tests/lib/clearable-deadline.test.ts -268 tests/lib/credential-redirect-guard.test.ts -143 tests/lib/debug.test.ts -189 tests/lib/execution-budget-permits.test.ts -115 tests/lib/failure-attribution.test.ts -113 tests/lib/failure-stage-model.test.ts +64 tests/lib/bun-stream-caps.test.ts +158 tests/lib/clearable-deadline.test.ts +346 tests/lib/credential-redirect-guard.test.ts +95 tests/lib/debug.test.ts +144 tests/lib/execution-budget-permits.test.ts +79 tests/lib/failure-attribution.test.ts +80 tests/lib/failure-stage-model.test.ts 145 tests/lib/file-identity-callers.test.ts -80 tests/lib/file-identity.test.ts +177 tests/lib/file-identity.test.ts 62 tests/lib/fix-jsonc-cr-comments.test.ts -79 tests/lib/fix-jsonc-empty-comma.test.ts -62 tests/lib/fix-plain-data-own-keys.test.ts -48 tests/lib/fix-plain-data-shape.test.ts -224 tests/lib/fix-retry-release-timer.test.ts +209 tests/lib/fix-jsonc-empty-comma.test.ts +64 tests/lib/fix-plain-data-own-keys.test.ts +222 tests/lib/fix-plain-data-shape.test.ts +78 tests/lib/fix-retry-release-timer.test.ts 142 tests/lib/local-chat-completion.test.ts 95 tests/lib/local-destinations.test.ts 91 tests/lib/local-upstream.test.ts -3393 tests/lib/opaque-proxy-tunnel-protocol.test.ts +3177 tests/lib/opaque-proxy-tunnel-protocol.test.ts 601 tests/lib/opaque-proxy-tunnel.test.ts -1006 tests/lib/optional-desktop-upstream.test.ts -582 tests/lib/optional-shutdown-hooks.test.ts -204 tests/lib/pinned-http-content-coding.test.ts -1484 tests/lib/pinned-http.test.ts -89 tests/lib/plugin-loader.test.ts -96 tests/lib/plugin-upstream-hooks.test.ts -80 tests/lib/privacy-mask-account.test.ts -174 tests/lib/process-control-graceful.test.ts -47 tests/lib/process-control.test.ts -224 tests/lib/provider-egress.test.ts -91 tests/lib/reasoning-replay-scope-source.test.ts -365 tests/lib/redact.test.ts -111 tests/lib/remove-tree-helper.test.ts -173 tests/lib/self-launch-argv.test.ts -1230 tests/lib/socks5-fetch.test.ts -94 tests/lib/socks5-tls-lifecycle.test.ts -271 tests/lib/socks5-upload-lifecycle.test.ts +1090 tests/lib/optional-desktop-upstream.test.ts +822 tests/lib/optional-shutdown-hooks.test.ts +142 tests/lib/pinned-http-content-coding.test.ts +1486 tests/lib/pinned-http.test.ts +97 tests/lib/plugin-loader.test.ts +97 tests/lib/plugin-upstream-hooks.test.ts +78 tests/lib/privacy-mask-account.test.ts +126 tests/lib/private-sqlite-path.test.ts +142 tests/lib/process-control-graceful.test.ts +174 tests/lib/process-control.test.ts +66 tests/lib/provider-egress.test.ts +80 tests/lib/reasoning-replay-scope-source.test.ts +368 tests/lib/redact.test.ts +109 tests/lib/remove-tree-helper.test.ts +79 tests/lib/self-launch-argv.test.ts +1246 tests/lib/socks5-fetch.test.ts +237 tests/lib/socks5-tls-lifecycle.test.ts +95 tests/lib/socks5-upload-lifecycle.test.ts 2722 tests/lib/spend-ceiling-enforcement.test.ts 95 tests/lib/spend-contract-c.test.ts 64 tests/lib/spend-corruption-compat.test.ts -44 tests/lib/spend-experimental-history.test.ts -3111 tests/lib/spend-ledger-file-journal.test.ts -6576 tests/lib/spend-ledger-owner.test.ts +139 tests/lib/spend-experimental-history.test.ts +2738 tests/lib/spend-ledger-file-journal.test.ts +10166 tests/lib/spend-ledger-owner.test.ts 4060 tests/lib/spend-pool-continuity.test.ts -81 tests/lib/spend-reservation-ledger.test.ts -1505 tests/lib/spend-seed-overflow.test.ts +64 tests/lib/spend-reservation-ledger.test.ts +1314 tests/lib/spend-seed-overflow.test.ts 82 tests/lib/spend-unbound-expiry.test.ts -79 tests/lib/spend-zero-config-compat.test.ts -80 tests/lib/stall-subprocess-exit.test.ts -597 tests/lib/stall-timeout.test.ts -234 tests/lib/standalone.test.ts -79 tests/lib/strict-semver.test.ts -82 tests/lib/synced-state-location.test.ts -228 tests/lib/system-restart-contract-security.test.ts -109 tests/lib/token-estimate.test.ts +95 tests/lib/spend-zero-config-compat.test.ts +231 tests/lib/stall-subprocess-exit.test.ts +64 tests/lib/stall-timeout.test.ts +63 tests/lib/standalone.test.ts +64 tests/lib/strict-semver.test.ts +64 tests/lib/synced-state-location.test.ts +74 tests/lib/system-restart-contract-security.test.ts +80 tests/lib/token-estimate.test.ts 77 tests/lib/transient-budget-scope-source.test.ts -79 tests/lib/transport-null-body.test.ts -220 tests/lib/upstream-error-message-fallback.test.ts +110 tests/lib/transport-null-body.test.ts +366 tests/lib/upstream-error-message-fallback.test.ts 95 tests/lib/upstream-retry-zero-output.test.ts -8254 tests/lib/upstream-retry.test.ts +8003 tests/lib/upstream-retry.test.ts 237 tests/lib/worker-embed-coverage.test.ts -79 tests/lib/worker-embed.test.ts -206 tests/lib/workflow-budget.test.ts -9662 tests/oauth/adapter-event-oauth-failover.test.ts -14681 tests/oauth/anthropic2-discovery-ownership.test.ts -4394 tests/oauth/chatgpt-device-auth.test.ts -96 tests/oauth/chatgpt-oauth.test.ts -143 tests/oauth/chatgpt-token-boundaries.test.ts -127 tests/oauth/chatgpt-token-expiry.test.ts -10446 tests/oauth/dsh-login.test.ts -3627 tests/oauth/generic-oauth-combo-account-cooldown.test.ts -19381 tests/oauth/generic-oauth-failover.test.ts +175 tests/lib/worker-embed.test.ts +254 tests/lib/workflow-budget.test.ts +8276 tests/oauth/adapter-event-oauth-failover.test.ts +14115 tests/oauth/anthropic2-discovery-ownership.test.ts +4150 tests/oauth/chatgpt-device-auth.test.ts +67 tests/oauth/chatgpt-oauth.test.ts +159 tests/oauth/chatgpt-token-boundaries.test.ts +125 tests/oauth/chatgpt-token-expiry.test.ts +10751 tests/oauth/dsh-login.test.ts +3629 tests/oauth/generic-oauth-combo-account-cooldown.test.ts +15241 tests/oauth/generic-oauth-failover.test.ts 4141 tests/oauth/generic-oauth-refusal-composition.test.ts -8550 tests/oauth/generic-session-affinity.test.ts -9753 tests/oauth/key-login-live-update.test.ts +6181 tests/oauth/generic-session-affinity.test.ts +3217 tests/oauth/key-login-live-update.test.ts 97 tests/oauth/key-login-preserves-model-costs.test.ts -95 tests/oauth/local-token-detect.test.ts -5052 tests/oauth/oauth-account-attribution.test.ts -11021 tests/oauth/oauth-account-auto-pause-revision.test.ts +82 tests/oauth/local-token-detect.test.ts +5822 tests/oauth/oauth-account-attribution.test.ts +13351 tests/oauth/oauth-account-auto-pause-revision.test.ts 7155 tests/oauth/oauth-account-auto-pause.test.ts -190 tests/oauth/oauth-account-id-collision.test.ts -8467 tests/oauth/oauth-account-plans.test.ts -3774 tests/oauth/oauth-account-quota-rank.test.ts -47676 tests/oauth/oauth-accounts-api.test.ts -13180 tests/oauth/oauth-anthropic-identity.test.ts -11707 tests/oauth/oauth-anthropic-instance-health.test.ts -18782 tests/oauth/oauth-anthropic-instance-multiprocess.test.ts -19764 tests/oauth/oauth-anthropic-instance-refresh.test.ts -19703 tests/oauth/oauth-anthropic-instance-registration.test.ts -220 tests/oauth/oauth-callback-binds.test.ts -111 tests/oauth/oauth-callback-server.test.ts -13298 tests/oauth/oauth-code-login.test.ts -63 tests/oauth/oauth-device-code-contract.test.ts -3074 tests/oauth/oauth-health.test.ts -11880 tests/oauth/oauth-kiro-refresh-attention.test.ts -247 tests/oauth/oauth-log.test.ts -1962 tests/oauth/oauth-login-cli-browser-launch.test.ts -6553 tests/oauth/oauth-login-cli-errors.test.ts -9935 tests/oauth/oauth-login-cli-live-update.test.ts -301 tests/oauth/oauth-login-open-browser.test.ts -205 tests/oauth/oauth-login-summary.test.ts -2850 tests/oauth/oauth-manual-code.test.ts -3081 tests/oauth/oauth-meta-muse-login-diagnostics.test.ts -205 tests/oauth/oauth-open-browser-choice.test.ts -130 tests/oauth/oauth-open-url-result.test.ts -4157 tests/oauth/oauth-provider-reconcile.test.ts -1879 tests/oauth/oauth-public-surface.test.ts -2216 tests/oauth/oauth-reauth-bind.test.ts -1614 tests/oauth/oauth-reconcile-operator-maps.test.ts -7388 tests/oauth/oauth-refresh-generic-lock.test.ts +142 tests/oauth/oauth-account-id-collision.test.ts +8721 tests/oauth/oauth-account-plans.test.ts +3743 tests/oauth/oauth-account-quota-rank.test.ts +45583 tests/oauth/oauth-accounts-api.test.ts +15324 tests/oauth/oauth-anthropic-identity.test.ts +11526 tests/oauth/oauth-anthropic-instance-health.test.ts +7016 tests/oauth/oauth-anthropic-instance-multiprocess.test.ts +20064 tests/oauth/oauth-anthropic-instance-refresh.test.ts +20687 tests/oauth/oauth-anthropic-instance-registration.test.ts +76 tests/oauth/oauth-callback-binds.test.ts +140 tests/oauth/oauth-callback-server.test.ts +15626 tests/oauth/oauth-code-login.test.ts +78 tests/oauth/oauth-device-code-contract.test.ts +4169 tests/oauth/oauth-health.test.ts +9115 tests/oauth/oauth-kiro-refresh-attention.test.ts +64 tests/oauth/oauth-log.test.ts +2723 tests/oauth/oauth-login-cli-browser-launch.test.ts +6513 tests/oauth/oauth-login-cli-errors.test.ts +7852 tests/oauth/oauth-login-cli-live-update.test.ts +436 tests/oauth/oauth-login-open-browser.test.ts +206 tests/oauth/oauth-login-summary.test.ts +2110 tests/oauth/oauth-manual-code.test.ts +2898 tests/oauth/oauth-meta-muse-login-diagnostics.test.ts +398 tests/oauth/oauth-open-browser-choice.test.ts +113 tests/oauth/oauth-open-url-result.test.ts +3427 tests/oauth/oauth-provider-reconcile.test.ts +2026 tests/oauth/oauth-public-surface.test.ts +1136 tests/oauth/oauth-reauth-bind.test.ts +1593 tests/oauth/oauth-reconcile-operator-maps.test.ts +7193 tests/oauth/oauth-refresh-generic-lock.test.ts 3905 tests/oauth/oauth-refresh-lock-multiprocess.test.ts -6376 tests/oauth/oauth-refresh-stale-capacity.test.ts -21734 tests/oauth/oauth-refresh.test.ts +6246 tests/oauth/oauth-refresh-stale-capacity.test.ts +29545 tests/oauth/oauth-refresh.test.ts 743 tests/oauth/oauth-status-privacy.test.ts -1998 tests/oauth/oauth-store-multi.test.ts -557 tests/oauth/oauth-store-quota-isolation.test.ts -112 tests/oauth/oauth-upsert-paused-api-key.test.ts +3057 tests/oauth/oauth-store-multi.test.ts +541 tests/oauth/oauth-store-quota-isolation.test.ts +128 tests/oauth/oauth-upsert-paused-api-key.test.ts 1843 tests/oauth/oauth-upsert-preserves-api-key.test.ts 485 tests/oauth/pool-kernel-generic-sweep.test.ts -698 tests/oauth/state-store-sweeper.test.ts -80 tests/oauth/workbuddy-login.test.ts -4945 tests/providers/aistupidlevel-provider.test.ts -966 tests/providers/alibaba-region-backup.test.ts +746 tests/oauth/state-store-sweeper.test.ts +259 tests/oauth/workbuddy-login.test.ts +4076 tests/providers/aistupidlevel-provider.test.ts +288 tests/providers/alibaba-region-backup.test.ts 603 tests/providers/alibaba-region-migration.test.ts -79 tests/providers/alibaba-region-startup.test.ts -1109 tests/providers/alibaba-token-plan-responses-optin.test.ts +234 tests/providers/alibaba-region-startup.test.ts +1185 tests/providers/alibaba-token-plan-responses-optin.test.ts 1657 tests/providers/alibaba-token-plan-wire-defaults.test.ts -1744 tests/providers/api-key-auto-pause-distribution.test.ts -903 tests/providers/api-key-catalog-authority.test.ts -218 tests/providers/api-key-selection-capture.test.ts -1532 tests/providers/api-key-selection-cooldown.test.ts -253 tests/providers/aside-client.test.ts -48 tests/providers/auto-compact-budget.test.ts -871 tests/providers/azure-adapter.test.ts -84 tests/providers/azure-model-router-tool-schema.test.ts -840 tests/providers/azure-vendor-metadata.test.ts -189 tests/providers/baseten-provider.test.ts -1824 tests/providers/cc-switch-import.test.ts -190 tests/providers/chutes-provider.test.ts -1416 tests/providers/claude-cli-adapter.test.ts -1435 tests/providers/claude-cli-client-http.test.ts -81 tests/providers/claude-cli-efficiency.test.ts +1821 tests/providers/api-key-auto-pause-distribution.test.ts +825 tests/providers/api-key-catalog-authority.test.ts +66 tests/providers/api-key-selection-capture.test.ts +2534 tests/providers/api-key-selection-cooldown.test.ts +285 tests/providers/aside-client.test.ts +61 tests/providers/auto-compact-budget.test.ts +286 tests/providers/azure-adapter.test.ts +96 tests/providers/azure-model-router-tool-schema.test.ts +682 tests/providers/azure-vendor-metadata.test.ts +239 tests/providers/baseten-provider.test.ts +3478 tests/providers/cc-switch-import.test.ts +157 tests/providers/chutes-provider.test.ts +996 tests/providers/claude-cli-adapter.test.ts +1267 tests/providers/claude-cli-client-http.test.ts +82 tests/providers/claude-cli-efficiency.test.ts 171 tests/providers/claude-cli-tool-capture.test.ts -744 tests/providers/claude-cli-usage-admission.test.ts -347 tests/providers/cline-pass-deepseek-v4-tool-replay.test.ts -174 tests/providers/cline-pass-provider.test.ts -175 tests/providers/cline-pass-reasoning-efforts.test.ts +480 tests/providers/claude-cli-usage-admission.test.ts +509 tests/providers/cline-pass-deepseek-v4-tool-replay.test.ts +111 tests/providers/cline-pass-provider.test.ts +189 tests/providers/cline-pass-reasoning-efforts.test.ts 80 tests/providers/cline-provider.test.ts -348 tests/providers/codebuddy-adapter.test.ts -96 tests/providers/codebuddy-live-acceptance.test.ts -244 tests/providers/codebuddy-live-models.test.ts -3889 tests/providers/codebuddy-mcp-server.test.ts -67 tests/providers/codebuddy-protocol.test.ts -550 tests/providers/codebuddy-tool-bridge-turn.test.ts -90 tests/providers/codebuddy-tool-bridge.test.ts -111 tests/providers/coding-agent-json-lines-scaling.test.ts +236 tests/providers/codebuddy-adapter.test.ts +187 tests/providers/codebuddy-live-acceptance.test.ts +205 tests/providers/codebuddy-live-models.test.ts +4523 tests/providers/codebuddy-mcp-server.test.ts +93 tests/providers/codebuddy-protocol.test.ts +554 tests/providers/codebuddy-tool-bridge-turn.test.ts +206 tests/providers/codebuddy-tool-bridge.test.ts +63 tests/providers/coding-agent-json-lines-scaling.test.ts 583 tests/providers/command-code-credit-failover.test.ts 2369 tests/providers/command-code-credit-rotation.test.ts -934 tests/providers/command-code-efforts.test.ts -240 tests/providers/command-code-error-finish.test.ts -223 tests/providers/command-code-fakeip-discovery.test.ts -4316 tests/providers/command-code-plan-denial.test.ts -2574 tests/providers/command-code-project-context.test.ts -1347 tests/providers/command-code-provider.test.ts +777 tests/providers/command-code-efforts.test.ts +79 tests/providers/command-code-error-finish.test.ts +176 tests/providers/command-code-fakeip-discovery.test.ts +6843 tests/providers/command-code-plan-denial.test.ts +3098 tests/providers/command-code-project-context.test.ts +1505 tests/providers/command-code-provider.test.ts 508 tests/providers/command-code-quota.test.ts 238 tests/providers/command-code-tool-text-prose-split.test.ts -1519 tests/providers/command-code-tool-text.test.ts -93 tests/providers/command-code-workspace-cache.test.ts -286 tests/providers/commandcode-provider.test.ts -64 tests/providers/context-cap-unknown-window.test.ts -177 tests/providers/context-window-seed-repair.test.ts -478 tests/providers/crusoe-provider.test.ts -382 tests/providers/cursor/cursor-adapter.test.ts +1425 tests/providers/command-code-tool-text.test.ts +63 tests/providers/command-code-workspace-cache.test.ts +270 tests/providers/commandcode-provider.test.ts +79 tests/providers/context-cap-unknown-window.test.ts +50 tests/providers/context-window-seed-repair.test.ts +191 tests/providers/crusoe-provider.test.ts +286 tests/providers/cursor/cursor-adapter.test.ts 96 tests/providers/cursor/cursor-arg-normalize.test.ts -96 tests/providers/cursor/cursor-blob-claude-client-tools.test.ts +174 tests/providers/cursor/cursor-blob-claude-client-tools.test.ts 156 tests/providers/cursor/cursor-blob-integrity.test.ts -477 tests/providers/cursor/cursor-blob.test.ts -79 tests/providers/cursor/cursor-call-id.test.ts -386 tests/providers/cursor/cursor-cancel-provenance.test.ts +493 tests/providers/cursor/cursor-blob.test.ts +81 tests/providers/cursor/cursor-call-id.test.ts +367 tests/providers/cursor/cursor-cancel-provenance.test.ts 80 tests/providers/cursor/cursor-catalog.test.ts -72 tests/providers/cursor/cursor-claude-id.test.ts -300 tests/providers/cursor/cursor-continuation-invariants.test.ts -190 tests/providers/cursor/cursor-continuity-retention.test.ts -94 tests/providers/cursor/cursor-default-catalog-suppression.test.ts +95 tests/providers/cursor/cursor-claude-id.test.ts +316 tests/providers/cursor/cursor-continuation-invariants.test.ts +245 tests/providers/cursor/cursor-continuity-retention.test.ts +79 tests/providers/cursor/cursor-default-catalog-suppression.test.ts 252 tests/providers/cursor/cursor-desktop-exec.test.ts -80 tests/providers/cursor/cursor-discovery.test.ts -81 tests/providers/cursor/cursor-display-names.test.ts -10674 tests/providers/cursor/cursor-effort-rows.test.ts -128 tests/providers/cursor/cursor-effort-suffix.test.ts -78 tests/providers/cursor/cursor-effort-table.test.ts -208 tests/providers/cursor/cursor-envelope-echo-retry.test.ts -254 tests/providers/cursor/cursor-eof-terminal.test.ts -98 tests/providers/cursor/cursor-errors.test.ts +223 tests/providers/cursor/cursor-discovery.test.ts +127 tests/providers/cursor/cursor-display-names.test.ts +8701 tests/providers/cursor/cursor-effort-rows.test.ts +114 tests/providers/cursor/cursor-effort-suffix.test.ts +80 tests/providers/cursor/cursor-effort-table.test.ts +415 tests/providers/cursor/cursor-envelope-echo-retry.test.ts +159 tests/providers/cursor/cursor-eof-terminal.test.ts +111 tests/providers/cursor/cursor-errors.test.ts 64 tests/providers/cursor/cursor-exec-empty-result.test.ts -173 tests/providers/cursor/cursor-fast-listing.test.ts -126 tests/providers/cursor/cursor-fast-tier.test.ts -252 tests/providers/cursor/cursor-foreground-shell.test.ts -158 tests/providers/cursor/cursor-framing.test.ts -276 tests/providers/cursor/cursor-freeform-args.test.ts -252 tests/providers/cursor/cursor-h2-pool-shutdown.test.ts -3114 tests/providers/cursor/cursor-hardening.test.ts +175 tests/providers/cursor/cursor-fast-listing.test.ts +128 tests/providers/cursor/cursor-fast-tier.test.ts +299 tests/providers/cursor/cursor-foreground-shell.test.ts +177 tests/providers/cursor/cursor-framing.test.ts +142 tests/providers/cursor/cursor-freeform-args.test.ts +218 tests/providers/cursor/cursor-h2-pool-shutdown.test.ts +3181 tests/providers/cursor/cursor-hardening.test.ts 125 tests/providers/cursor/cursor-http1-transport.test.ts 2991 tests/providers/cursor/cursor-images.test.ts 9466 tests/providers/cursor/cursor-integration-status.test.ts -159 tests/providers/cursor/cursor-interaction-query.test.ts -94 tests/providers/cursor/cursor-kv-store.test.ts -48 tests/providers/cursor/cursor-live-smoke-gate.test.ts -309 tests/providers/cursor/cursor-live-transport.test.ts -156 tests/providers/cursor/cursor-local-installer.test.ts -4070 tests/providers/cursor/cursor-local-models-schema.test.ts -172 tests/providers/cursor/cursor-mcp-manager.test.ts -585 tests/providers/cursor/cursor-mcp-stdio.test.ts -62 tests/providers/cursor/cursor-message-mapper.test.ts -78 tests/providers/cursor/cursor-native-exec-common.test.ts -127 tests/providers/cursor/cursor-native-exec-policy.test.ts -303 tests/providers/cursor/cursor-native-exec-shell.test.ts -205 tests/providers/cursor/cursor-native-exec.test.ts -159 tests/providers/cursor/cursor-native-grep-globs.test.ts -127 tests/providers/cursor/cursor-oauth-shell.test.ts -659 tests/providers/cursor/cursor-oauth.test.ts -78 tests/providers/cursor/cursor-pool.test.ts -96 tests/providers/cursor/cursor-protobuf-events.test.ts -223 tests/providers/cursor/cursor-repetition-breaker.test.ts -270 tests/providers/cursor/cursor-request-builder.test.ts -112 tests/providers/cursor/cursor-request-compat.test.ts -143 tests/providers/cursor/cursor-roster-account-scope.test.ts -110 tests/providers/cursor/cursor-silent-redirect.test.ts -221 tests/providers/cursor/cursor-static-catalog.test.ts -3613 tests/providers/cursor/cursor-stream-health.test.ts +111 tests/providers/cursor/cursor-interaction-query.test.ts +63 tests/providers/cursor/cursor-kv-store.test.ts +79 tests/providers/cursor/cursor-live-smoke-gate.test.ts +316 tests/providers/cursor/cursor-live-transport.test.ts +81 tests/providers/cursor/cursor-local-installer.test.ts +4600 tests/providers/cursor/cursor-local-models-schema.test.ts +190 tests/providers/cursor/cursor-mcp-manager.test.ts +840 tests/providers/cursor/cursor-mcp-stdio.test.ts +94 tests/providers/cursor/cursor-message-mapper.test.ts +96 tests/providers/cursor/cursor-native-exec-common.test.ts +206 tests/providers/cursor/cursor-native-exec-policy.test.ts +258 tests/providers/cursor/cursor-native-exec-shell.test.ts +159 tests/providers/cursor/cursor-native-exec.test.ts +158 tests/providers/cursor/cursor-native-grep-globs.test.ts +190 tests/providers/cursor/cursor-oauth-shell.test.ts +758 tests/providers/cursor/cursor-oauth.test.ts +64 tests/providers/cursor/cursor-pool.test.ts +128 tests/providers/cursor/cursor-protobuf-events.test.ts +160 tests/providers/cursor/cursor-repetition-breaker.test.ts +190 tests/providers/cursor/cursor-request-builder.test.ts +158 tests/providers/cursor/cursor-request-compat.test.ts +142 tests/providers/cursor/cursor-roster-account-scope.test.ts +80 tests/providers/cursor/cursor-silent-redirect.test.ts +301 tests/providers/cursor/cursor-static-catalog.test.ts +3605 tests/providers/cursor/cursor-stream-health.test.ts 205 tests/providers/cursor/cursor-structured-edit.test.ts -180 tests/providers/cursor/cursor-tool-arg-decoding.test.ts -82 tests/providers/cursor/cursor-tool-choice.test.ts +97 tests/providers/cursor/cursor-tool-arg-decoding.test.ts +80 tests/providers/cursor/cursor-tool-choice.test.ts 192 tests/providers/cursor/cursor-tool-continuation.test.ts -141 tests/providers/cursor/cursor-tool-definitions.test.ts -4127 tests/providers/cursor/cursor-tool-finalize-race.test.ts -158 tests/providers/cursor/cursor-tool-result-image.test.ts -328 tests/providers/cursor/cursor-tool-result-invocation.test.ts -120 tests/providers/cursor/cursor-tool-suspended-checkpoint.test.ts -286 tests/providers/cursor/cursor-tool-wording.test.ts -167 tests/providers/cursor/cursor-toolresult-normalize.test.ts -1964 tests/providers/cursor/cursor-transport-retry.test.ts +127 tests/providers/cursor/cursor-tool-definitions.test.ts +4029 tests/providers/cursor/cursor-tool-finalize-race.test.ts +140 tests/providers/cursor/cursor-tool-result-image.test.ts +300 tests/providers/cursor/cursor-tool-result-invocation.test.ts +109 tests/providers/cursor/cursor-tool-suspended-checkpoint.test.ts +254 tests/providers/cursor/cursor-tool-wording.test.ts +159 tests/providers/cursor/cursor-toolresult-normalize.test.ts +1960 tests/providers/cursor/cursor-transport-retry.test.ts 110 tests/providers/cursor/cursor-ultra-mode.test.ts -97 tests/providers/cursor/cursor-umbrella-rows.test.ts -71 tests/providers/cursor/cursor-uncallable-quarantine.test.ts -111 tests/providers/cursor/cursor-vision-wire-harness.test.ts -521 tests/providers/cyber-policy-error-fidelity.test.ts -453 tests/providers/deepinfra-provider.test.ts -84 tests/providers/deepseek-artifact-tool-schema.test.ts +111 tests/providers/cursor/cursor-umbrella-rows.test.ts +64 tests/providers/cursor/cursor-uncallable-quarantine.test.ts +113 tests/providers/cursor/cursor-vision-wire-harness.test.ts +882 tests/providers/cyber-policy-error-fidelity.test.ts +476 tests/providers/deepinfra-provider.test.ts +243 tests/providers/deepseek-artifact-tool-schema.test.ts 236 tests/providers/deepseek-bare-tool-call-replay.test.ts -7261 tests/providers/deepseek-image-files.test.ts -4905 tests/providers/deepseek-inbound-wire.test.ts -472 tests/providers/deepseek-quota-currency.test.ts -471 tests/providers/deepseek-reasoning-replay-gaps.test.ts -277 tests/providers/deepseek-reasoning-replay.test.ts +4753 tests/providers/deepseek-image-files.test.ts +4003 tests/providers/deepseek-inbound-wire.test.ts +268 tests/providers/deepseek-quota-currency.test.ts +176 tests/providers/deepseek-reasoning-replay-gaps.test.ts +160 tests/providers/deepseek-reasoning-replay.test.ts 761 tests/providers/deepseek-responses-item-id-repair.test.ts -2286 tests/providers/devin-adapter-reset-wait.test.ts -1152 tests/providers/devin-adapter.test.ts -380 tests/providers/devin-anthropic-signature-fallback.test.ts +2405 tests/providers/devin-adapter-reset-wait.test.ts +871 tests/providers/devin-adapter.test.ts +630 tests/providers/devin-anthropic-signature-fallback.test.ts 707 tests/providers/devin-chat-wire-fixes.test.ts 285 tests/providers/devin-cli-authmode-migration.test.ts 164 tests/providers/devin-effort-ladder.test.ts -301 tests/providers/devin-family-resolution.test.ts -255 tests/providers/devin-hardening.test.ts -326 tests/providers/devin-image-passthrough.test.ts -252 tests/providers/devin-live-models.test.ts -1933 tests/providers/devin-login.test.ts -333 tests/providers/devin-output-budget.test.ts -1060 tests/providers/devin-prompt-cache.test.ts -1503 tests/providers/devin-provider-merge-migration.test.ts +436 tests/providers/devin-family-resolution.test.ts +253 tests/providers/devin-hardening.test.ts +142 tests/providers/devin-image-passthrough.test.ts +447 tests/providers/devin-live-models.test.ts +2040 tests/providers/devin-login.test.ts +238 tests/providers/devin-output-budget.test.ts +1067 tests/providers/devin-prompt-cache.test.ts +1085 tests/providers/devin-provider-merge-migration.test.ts 952 tests/providers/devin-quota.test.ts -125 tests/providers/devin-reasoning-continuation.test.ts -48 tests/providers/devin-stated-reset-hardening.test.ts -154 tests/providers/devin-stated-reset-retry.test.ts +128 tests/providers/devin-reasoning-continuation.test.ts +229 tests/providers/devin-stated-reset-hardening.test.ts +97 tests/providers/devin-stated-reset-retry.test.ts 114 tests/providers/devin-stream-deadline.test.ts -96 tests/providers/devin-trajectory.test.ts -456 tests/providers/digitalocean-scaleway-provider.test.ts -3922 tests/providers/dsh-account.test.ts -227 tests/providers/exa-web-search.test.ts -3321 tests/providers/explicit-key-pause-oauth-boundary.test.ts -361 tests/providers/fast-row-ingress.test.ts -236 tests/providers/featherless-provider.test.ts -190 tests/providers/flash-route-image-modalities.test.ts -5540 tests/providers/forward-admission-separation.test.ts -79 tests/providers/free-directory-runcrate.test.ts -12019 tests/providers/github-copilot/github-copilot-account-origin.test.ts +192 tests/providers/devin-trajectory.test.ts +381 tests/providers/digitalocean-scaleway-provider.test.ts +5701 tests/providers/dsh-account.test.ts +279 tests/providers/exa-web-search.test.ts +5112 tests/providers/explicit-key-pause-oauth-boundary.test.ts +140 tests/providers/fast-row-ingress.test.ts +205 tests/providers/featherless-provider.test.ts +439 tests/providers/flash-route-image-modalities.test.ts +7921 tests/providers/forward-admission-separation.test.ts +70 tests/providers/free-directory-runcrate.test.ts +14343 tests/providers/github-copilot/github-copilot-account-origin.test.ts 32779 tests/providers/github-copilot/github-copilot-auto-runtime.test.ts 96 tests/providers/github-copilot/github-copilot-auto.test.ts 142 tests/providers/github-copilot/github-copilot-catalog-hints.test.ts 159 tests/providers/github-copilot/github-copilot-context-tier.test.ts -16102 tests/providers/github-copilot/github-copilot-oauth.test.ts -80 tests/providers/github-copilot/github-copilot-sse-rewrite.test.ts +16077 tests/providers/github-copilot/github-copilot-oauth.test.ts +79 tests/providers/github-copilot/github-copilot-sse-rewrite.test.ts 618 tests/providers/github-copilot/github-copilot-stream-contract.test.ts -3881 tests/providers/github-copilot/github-copilot-wire-defaults.test.ts -3075 tests/providers/gpt61-terra-provider-rows.test.ts -95 tests/providers/haiku-5-5-catalog.test.ts -221 tests/providers/hyperbolic-provider.test.ts -4841 tests/providers/initial-model-selection.test.ts -5966 tests/providers/initial-selection-write-fence.test.ts +5219 tests/providers/github-copilot/github-copilot-wire-defaults.test.ts +3187 tests/providers/gpt61-terra-provider-rows.test.ts +97 tests/providers/haiku-5-5-catalog.test.ts +157 tests/providers/hyperbolic-provider.test.ts +7898 tests/providers/initial-model-selection.test.ts +5091 tests/providers/initial-selection-write-fence.test.ts 141 tests/providers/jev-provider.test.ts -790 tests/providers/kimi-oauth-identity.test.ts -318 tests/providers/kimi-responses-adjacency.test.ts -95 tests/providers/kiro/kiro-account-load.test.ts +1303 tests/providers/kimi-oauth-identity.test.ts +128 tests/providers/kimi-responses-adjacency.test.ts +78 tests/providers/kiro/kiro-account-load.test.ts 2252 tests/providers/kiro/kiro-account-quota.test.ts -7367 tests/providers/kiro/kiro-account-state-disk.test.ts -1140 tests/providers/kiro/kiro-account-state-imports.test.ts -1599 tests/providers/kiro/kiro-adapter.test.ts -3299 tests/providers/kiro/kiro-auth-context-continuation.test.ts -792 tests/providers/kiro/kiro-auto-selection.test.ts -680 tests/providers/kiro/kiro-builder-id-profile.test.ts -96 tests/providers/kiro/kiro-calibration.test.ts -256 tests/providers/kiro/kiro-completion-with-real-tools.test.ts -1014 tests/providers/kiro/kiro-device-builder.test.ts -4823 tests/providers/kiro/kiro-device-iam.test.ts -6337 tests/providers/kiro/kiro-device-social.test.ts -192 tests/providers/kiro/kiro-fallback-error-body.test.ts -3136 tests/providers/kiro/kiro-images.test.ts -12402 tests/providers/kiro/kiro-leased-responses.test.ts -63 tests/providers/kiro/kiro-metering-events.test.ts -141 tests/providers/kiro/kiro-metering-usage.test.ts +7051 tests/providers/kiro/kiro-account-state-disk.test.ts +1125 tests/providers/kiro/kiro-account-state-imports.test.ts +1964 tests/providers/kiro/kiro-adapter.test.ts +2539 tests/providers/kiro/kiro-auth-context-continuation.test.ts +1170 tests/providers/kiro/kiro-auto-selection.test.ts +973 tests/providers/kiro/kiro-builder-id-profile.test.ts +97 tests/providers/kiro/kiro-calibration.test.ts +206 tests/providers/kiro/kiro-completion-with-real-tools.test.ts +1219 tests/providers/kiro/kiro-device-builder.test.ts +4489 tests/providers/kiro/kiro-device-iam.test.ts +6737 tests/providers/kiro/kiro-device-social.test.ts +173 tests/providers/kiro/kiro-fallback-error-body.test.ts +2627 tests/providers/kiro/kiro-images.test.ts +12451 tests/providers/kiro/kiro-leased-responses.test.ts +80 tests/providers/kiro/kiro-metering-events.test.ts +158 tests/providers/kiro/kiro-metering-usage.test.ts 2898 tests/providers/kiro/kiro-model-catalog.test.ts -2495 tests/providers/kiro/kiro-model-preference.test.ts -2614 tests/providers/kiro/kiro-oauth.test.ts +2346 tests/providers/kiro/kiro-model-preference.test.ts +3797 tests/providers/kiro/kiro-oauth.test.ts 5445 tests/providers/kiro/kiro-org-user-identity.test.ts -5792 tests/providers/kiro/kiro-pool-load-settings.test.ts +5054 tests/providers/kiro/kiro-pool-load-settings.test.ts 4409 tests/providers/kiro/kiro-pool-rank.test.ts -2754 tests/providers/kiro/kiro-quota-metrics.test.ts -174 tests/providers/kiro/kiro-reasoning-roundtrip.test.ts -6302 tests/providers/kiro/kiro-refusal-failover.test.ts +4256 tests/providers/kiro/kiro-quota-metrics.test.ts +190 tests/providers/kiro/kiro-reasoning-roundtrip.test.ts +5772 tests/providers/kiro/kiro-refusal-failover.test.ts 111 tests/providers/kiro/kiro-refusal.test.ts -96 tests/providers/kiro/kiro-remote-image.test.ts -568 tests/providers/kiro/kiro-retry.test.ts -6327 tests/providers/kiro/kiro-review-regressions.test.ts -190 tests/providers/kiro/kiro-single-final.test.ts -425 tests/providers/kiro/kiro-stream.test.ts -762 tests/providers/kiro/kiro-transport-parity.test.ts +127 tests/providers/kiro/kiro-remote-image.test.ts +597 tests/providers/kiro/kiro-retry.test.ts +5310 tests/providers/kiro/kiro-review-regressions.test.ts +254 tests/providers/kiro/kiro-single-final.test.ts +507 tests/providers/kiro/kiro-stream.test.ts +646 tests/providers/kiro/kiro-transport-parity.test.ts 79 tests/providers/kiro/kiro-usage-quota.test.ts 540 tests/providers/kiro/kiro-usage-restart.test.ts 47 tests/providers/kiro/kiro-windows-cli-db-path.test.ts -64 tests/providers/kiro/kiro-windows-cli-executable-path.test.ts -98 tests/providers/kiro/kiro-wire-estimate.test.ts -175 tests/providers/meta-model-api-provider.test.ts -466 tests/providers/meta-muse-device.test.ts +54 tests/providers/kiro/kiro-windows-cli-executable-path.test.ts +111 tests/providers/kiro/kiro-wire-estimate.test.ts +447 tests/providers/meta-model-api-provider.test.ts +566 tests/providers/meta-muse-device.test.ts 5187 tests/providers/meta-muse-keychain.test.ts -350 tests/providers/meta-muse-login-order.test.ts +128 tests/providers/meta-muse-login-order.test.ts 300 tests/providers/meta-muse-oauth.test.ts -284 tests/providers/meta-muse-wonder.test.ts +161 tests/providers/meta-muse-wonder.test.ts 254 tests/providers/mimo-effort.test.ts -517 tests/providers/mimo-free-provider.test.ts -390 tests/providers/mimo-token-plan-capacity.test.ts -285 tests/providers/mimo-token-plan-provider.test.ts -317 tests/providers/mimo-v26-catalog.test.ts -778 tests/providers/minimax-clients.test.ts -1772 tests/providers/minimax-combo-image-input.test.ts +298 tests/providers/mimo-free-provider.test.ts +297 tests/providers/mimo-token-plan-capacity.test.ts +143 tests/providers/mimo-token-plan-provider.test.ts +285 tests/providers/mimo-v26-catalog.test.ts +758 tests/providers/minimax-clients.test.ts +1733 tests/providers/minimax-combo-image-input.test.ts 239 tests/providers/minimax-quota.test.ts -254 tests/providers/minimax-reasoning-split.test.ts -3822 tests/providers/mistral-recovery.test.ts -94 tests/providers/model-presets.test.ts -1659 tests/providers/model-rename-migration.test.ts -127 tests/providers/model-roster-seed-repair.test.ts -542 tests/providers/modelflare-provider.test.ts -79 tests/providers/moonshot-developer-role.test.ts +221 tests/providers/minimax-reasoning-split.test.ts +3473 tests/providers/mistral-recovery.test.ts +63 tests/providers/model-presets.test.ts +1951 tests/providers/model-rename-migration.test.ts +143 tests/providers/model-roster-seed-repair.test.ts +219 tests/providers/modelflare-provider.test.ts +112 tests/providers/moonshot-developer-role.test.ts 174 tests/providers/moonshot-endpoints.test.ts -380 tests/providers/moonshot-tool-schema.test.ts +413 tests/providers/moonshot-tool-schema.test.ts 94 tests/providers/muse-key-quota.test.ts -1351 tests/providers/muse-passive-quota-cache.test.ts -865 tests/providers/muse-passive-quota-observation.test.ts -182 tests/providers/muse-spark-web-search-compat.test.ts -49 tests/providers/muse-subscription-usage.test.ts -413 tests/providers/muse-tool-name-alias.test.ts -5720 tests/providers/new-model-policy-runtime.test.ts -95 tests/providers/new-model-policy.test.ts -139 tests/providers/nous-oauth-live.test.ts +1661 tests/providers/muse-passive-quota-cache.test.ts +1092 tests/providers/muse-passive-quota-observation.test.ts +437 tests/providers/muse-spark-web-search-compat.test.ts +315 tests/providers/muse-subscription-usage.test.ts +142 tests/providers/muse-tool-name-alias.test.ts +6306 tests/providers/new-model-policy-runtime.test.ts +64 tests/providers/new-model-policy.test.ts +95 tests/providers/nous-oauth-live.test.ts 13033 tests/providers/nous-oauth.test.ts -237 tests/providers/novita-provider.test.ts -340 tests/providers/nscale-vultr-provider.test.ts +235 tests/providers/novita-provider.test.ts +191 tests/providers/nscale-vultr-provider.test.ts 190 tests/providers/nvidia-nim-hardening.test.ts -396 tests/providers/ollama/ollama-native-parser.test.ts -112 tests/providers/ollama/ollama-native-reasoning-wire.test.ts -80 tests/providers/ollama/ollama-native-scaling.test.ts -112 tests/providers/ollama/ollama-native-structured-output.test.ts -761 tests/providers/ollama/ollama-native-tool-continuations.test.ts -238 tests/providers/ollama/ollama-native-v4.test.ts -263 tests/providers/ollama/ollama-native.test.ts -571 tests/providers/ollama/ollama-show-enrichment-v7.test.ts +365 tests/providers/ollama/ollama-native-parser.test.ts +159 tests/providers/ollama/ollama-native-reasoning-wire.test.ts +128 tests/providers/ollama/ollama-native-scaling.test.ts +79 tests/providers/ollama/ollama-native-structured-output.test.ts +602 tests/providers/ollama/ollama-native-tool-continuations.test.ts +350 tests/providers/ollama/ollama-native-v4.test.ts +256 tests/providers/ollama/ollama-native.test.ts +491 tests/providers/ollama/ollama-show-enrichment-v7.test.ts 222 tests/providers/ollama/ollama-show-enrichment.test.ts -331 tests/providers/ollama/ollama-show-ignore-abort.test.ts -996 tests/providers/opencode-cli.test.ts -127 tests/providers/opencode-go-deepseek.test.ts -2630 tests/providers/opencode-go-gemini-wire.test.ts -239 tests/providers/opencode-go-grok46-responses.test.ts -3493 tests/providers/opencode-go-luna-wire.test.ts -4069 tests/providers/opencode-go-model-protocols.test.ts +348 tests/providers/ollama/ollama-show-ignore-abort.test.ts +713 tests/providers/opencode-cli.test.ts +175 tests/providers/opencode-go-deepseek.test.ts +1947 tests/providers/opencode-go-gemini-wire.test.ts +588 tests/providers/opencode-go-grok46-responses.test.ts +5154 tests/providers/opencode-go-luna-wire.test.ts +5406 tests/providers/opencode-go-model-protocols.test.ts 143 tests/providers/opencode-go-muse-context.test.ts 160 tests/providers/opencode-go-muse-vision.test.ts -433 tests/providers/opencode-go-quota.test.ts -24120 tests/providers/opencode-go-session-header.test.ts -823 tests/providers/opencode-management-transport.test.ts -78 tests/providers/opencode-muse-terminal-repair.test.ts -168 tests/providers/opencode-zen-deepseek-reasoning.test.ts -903 tests/providers/opencode-zen-gemini-wire.test.ts +412 tests/providers/opencode-go-quota.test.ts +20675 tests/providers/opencode-go-session-header.test.ts +1018 tests/providers/opencode-management-transport.test.ts +177 tests/providers/opencode-muse-terminal-repair.test.ts +126 tests/providers/opencode-zen-deepseek-reasoning.test.ts +1047 tests/providers/opencode-zen-gemini-wire.test.ts 87 tests/providers/opencode-zen-rate-limit.test.ts -233 tests/providers/opengateway-key-validation.test.ts -144 tests/providers/opengateway-provider.test.ts -330 tests/providers/openrouter-provider-routing.test.ts +182 tests/providers/opengateway-key-validation.test.ts +207 tests/providers/opengateway-provider.test.ts +495 tests/providers/openrouter-provider-routing.test.ts 146 tests/providers/openrouter-quota-reset-cooldown-4024.test.ts -159 tests/providers/opper-provider.test.ts -681 tests/providers/orcarouter-provider.test.ts -1774 tests/providers/provider-account-quota-failure-reasons.test.ts -4986 tests/providers/provider-account-quota-persistence.test.ts -14443 tests/providers/provider-account-quota.test.ts -264 tests/providers/provider-anthropic-instance-quota.test.ts -174 tests/providers/provider-anthropic-instance.test.ts -161 tests/providers/provider-anthropic-usage-windows.test.ts -180 tests/providers/provider-antigravity-effort-families.test.ts +429 tests/providers/opper-provider.test.ts +631 tests/providers/orcarouter-provider.test.ts +1936 tests/providers/provider-account-quota-failure-reasons.test.ts +4967 tests/providers/provider-account-quota-persistence.test.ts +17155 tests/providers/provider-account-quota.test.ts +191 tests/providers/provider-anthropic-instance-quota.test.ts +157 tests/providers/provider-anthropic-instance.test.ts +171 tests/providers/provider-anthropic-usage-windows.test.ts +95 tests/providers/provider-antigravity-effort-families.test.ts 365 tests/providers/provider-antigravity-family-catalog.test.ts -157 tests/providers/provider-antigravity-model-quota.test.ts -135 tests/providers/provider-antigravity-quota-retry.test.ts -3114 tests/providers/provider-antigravity-wire-snapshot.test.ts -9453 tests/providers/provider-api-keys.test.ts -83 tests/providers/provider-capacity.test.ts -2328 tests/providers/provider-completion-test-authority.test.ts -2282 tests/providers/provider-completion-test-ingress.test.ts +339 tests/providers/provider-antigravity-model-quota.test.ts +353 tests/providers/provider-antigravity-quota-retry.test.ts +4625 tests/providers/provider-antigravity-wire-snapshot.test.ts +8047 tests/providers/provider-api-keys.test.ts +67 tests/providers/provider-capacity.test.ts +2583 tests/providers/provider-completion-test-authority.test.ts +2219 tests/providers/provider-completion-test-ingress.test.ts 472 tests/providers/provider-completion-test.test.ts -3637 tests/providers/provider-config-batch-management.test.ts -64 tests/providers/provider-config-validation.test.ts -6101 tests/providers/provider-connection-test.test.ts -1514 tests/providers/provider-cost-overlay-config.test.ts +3559 tests/providers/provider-config-batch-management.test.ts +96 tests/providers/provider-config-validation.test.ts +7452 tests/providers/provider-connection-test.test.ts +1314 tests/providers/provider-cost-overlay-config.test.ts 64 tests/providers/provider-discovery-log-suppression.test.ts -76 tests/providers/provider-egress-outbound.test.ts -95 tests/providers/provider-id-rewrite.test.ts -1300 tests/providers/provider-input-modalities.test.ts +78 tests/providers/provider-egress-outbound.test.ts +94 tests/providers/provider-id-rewrite.test.ts +1680 tests/providers/provider-input-modalities.test.ts 6488 tests/providers/provider-key-store.test.ts -285 tests/providers/provider-live-models.test.ts -300 tests/providers/provider-model-aliases.test.ts -301 tests/providers/provider-model-discovery-contract.test.ts -47 tests/providers/provider-outbound-private-network.test.ts -1351 tests/providers/provider-outbound.test.ts -293 tests/providers/provider-quota-abliteration.test.ts -522 tests/providers/provider-quota-label-sanitize.test.ts -937 tests/providers/provider-quota-observed-marker.test.ts -793 tests/providers/provider-quota-ollama-cloud.test.ts -15946 tests/providers/provider-quota.test.ts +269 tests/providers/provider-live-models.test.ts +301 tests/providers/provider-model-aliases.test.ts +706 tests/providers/provider-model-discovery-contract.test.ts +81 tests/providers/provider-outbound-private-network.test.ts +1282 tests/providers/provider-outbound.test.ts +316 tests/providers/provider-quota-abliteration.test.ts +721 tests/providers/provider-quota-label-sanitize.test.ts +681 tests/providers/provider-quota-observed-marker.test.ts +650 tests/providers/provider-quota-ollama-cloud.test.ts +15392 tests/providers/provider-quota.test.ts 681 tests/providers/provider-registry-parity.test.ts 79 tests/providers/provider-runtime-fetch.test.ts -191 tests/providers/provider-static-model-discovery.test.ts +111 tests/providers/provider-static-model-discovery.test.ts 93 tests/providers/provider-tls-profile.test.ts -360 tests/providers/qoder-adapter.test.ts -1717 tests/providers/qoder-cn-image-validation.test.ts -126 tests/providers/qoder-image-input.test.ts -128 tests/providers/qoder-live-models.test.ts -571 tests/providers/qoder-mcp-server.test.ts -111 tests/providers/qoder-scaffold-guard.test.ts +491 tests/providers/qoder-adapter.test.ts +1265 tests/providers/qoder-cn-image-validation.test.ts +110 tests/providers/qoder-image-input.test.ts +127 tests/providers/qoder-live-models.test.ts +742 tests/providers/qoder-mcp-server.test.ts +144 tests/providers/qoder-scaffold-guard.test.ts 79 tests/providers/qwen38-preserve-reasoning.test.ts -740 tests/providers/rate-limit-retry.test.ts -143 tests/providers/registry-transport-alias.test.ts +1094 tests/providers/rate-limit-retry.test.ts +365 tests/providers/registry-transport-alias.test.ts 271 tests/providers/resolved-model-policy.test.ts -455 tests/providers/sambanova-nebius-provider.test.ts -175 tests/providers/sponsor-presets.test.ts -157 tests/providers/stepfun-provider.test.ts -1397 tests/providers/tokenlab-protocols.test.ts -158 tests/providers/tokenlab-provider.test.ts -158 tests/providers/umans-provider.test.ts -7390 tests/providers/upstream-transient-retry.test.ts -188 tests/providers/vercel-gateway-provider-routing.test.ts -189 tests/providers/vision-classification-seed-repair.test.ts -96 tests/providers/volcengine-ark-assistant-content.test.ts -2747 tests/providers/workbuddy-provider.test.ts -586 tests/providers/workbuddy-quota.test.ts -79 tests/providers/xai/grok-47-build-fast-metadata.test.ts +238 tests/providers/sambanova-nebius-provider.test.ts +330 tests/providers/sponsor-presets.test.ts +205 tests/providers/stepfun-provider.test.ts +1171 tests/providers/tokenlab-protocols.test.ts +382 tests/providers/tokenlab-provider.test.ts +126 tests/providers/umans-provider.test.ts +8083 tests/providers/upstream-transient-retry.test.ts +113 tests/providers/vercel-gateway-provider-routing.test.ts +146 tests/providers/vision-classification-seed-repair.test.ts +107 tests/providers/volcengine-ark-assistant-content.test.ts +3284 tests/providers/workbuddy-provider.test.ts +793 tests/providers/workbuddy-quota.test.ts +47 tests/providers/xai/grok-47-build-fast-metadata.test.ts 136825 tests/providers/xai/grok-47-fast-model-wire.test.ts -160 tests/providers/xai/grok-47-fast-model.test.ts -286 tests/providers/xai/grok-attribution.test.ts -5443 tests/providers/xai/grok-config-inject.test.ts -220 tests/providers/xai/grok-config-write-lock.test.ts -21632 tests/providers/xai/grok-coupon-claim.test.ts -2170 tests/providers/xai/grok-coupon-reconcile.test.ts -539 tests/providers/xai/grok-effort-inject.test.ts -191 tests/providers/xai/grok-lifecycle.test.ts -10314 tests/providers/xai/grok-management-api.test.ts -10234 tests/providers/xai/grok-models-effort-list.test.ts -5602 tests/providers/xai/grok-orphan-adoption.test.ts -110 tests/providers/xai/grok-reset-coupon-cli.test.ts -873 tests/providers/xai/grok-reset-coupons.test.ts -371 tests/providers/xai/grok-selection.test.ts -362 tests/providers/xai/grok-session-identity.test.ts +203 tests/providers/xai/grok-47-fast-model.test.ts +461 tests/providers/xai/grok-attribution.test.ts +5140 tests/providers/xai/grok-config-inject.test.ts +221 tests/providers/xai/grok-config-write-lock.test.ts +20644 tests/providers/xai/grok-coupon-claim.test.ts +2523 tests/providers/xai/grok-coupon-reconcile.test.ts +585 tests/providers/xai/grok-effort-inject.test.ts +210 tests/providers/xai/grok-lifecycle.test.ts +15795 tests/providers/xai/grok-management-api.test.ts +9649 tests/providers/xai/grok-models-effort-list.test.ts +5792 tests/providers/xai/grok-orphan-adoption.test.ts +162 tests/providers/xai/grok-reset-coupon-cli.test.ts +921 tests/providers/xai/grok-reset-coupons.test.ts +428 tests/providers/xai/grok-selection.test.ts +555 tests/providers/xai/grok-session-identity.test.ts 253 tests/providers/xai/grok-status.test.ts -634 tests/providers/xai/grok-sync.test.ts +697 tests/providers/xai/grok-sync.test.ts 257 tests/providers/xai/grok-writer-boundary.test.ts -128 tests/providers/xai/xai-additional-tools.test.ts -127 tests/providers/xai/xai-empty-catalog-tool-choice.test.ts +175 tests/providers/xai/xai-additional-tools.test.ts +159 tests/providers/xai/xai-empty-catalog-tool-choice.test.ts 2151 tests/providers/xai/xai-loaded-tool-provenance.test.ts -126 tests/providers/xai/xai-no-stop.test.ts -80 tests/providers/xai/xai-oauth-retry.test.ts +112 tests/providers/xai/xai-no-stop.test.ts +95 tests/providers/xai/xai-oauth-retry.test.ts 1739 tests/providers/xai/xai-refresh-lock.test.ts -172 tests/providers/xai/xai-replay-provenance.test.ts +159 tests/providers/xai/xai-replay-provenance.test.ts 113 tests/providers/xai/xai-responses-adjacency.test.ts -111 tests/providers/xai/xai-tool-schema.test.ts +107 tests/providers/xai/xai-tool-schema.test.ts 220 tests/providers/xai/xai-transport.test.ts -187 tests/providers/xai/xai-web-search-compat.test.ts -126 tests/providers/xai/xai-web-search.test.ts -394 tests/providers/zai-reasoning-replay.test.ts -240 tests/providers/zcode-client.test.ts -206 tests/providers/zed-argument-consistency.test.ts -476 tests/providers/zed-failure-relay.test.ts -659 tests/providers/zed-hosted-provider.test.ts +142 tests/providers/xai/xai-web-search-compat.test.ts +142 tests/providers/xai/xai-web-search.test.ts +399 tests/providers/zai-reasoning-replay.test.ts +234 tests/providers/zcode-client.test.ts +478 tests/providers/zed-argument-consistency.test.ts +204 tests/providers/zed-failure-relay.test.ts +476 tests/providers/zed-hosted-provider.test.ts 713 tests/providers/zed-lossless-arguments.test.ts -279 tests/providers/zed-openai-contract.test.ts -158 tests/providers/zed-retained-budget.test.ts -150 tests/providers/zhipu-bigmodel-provider.test.ts -387 tests/providers/zhipu-bigmodel-responses-quota.test.ts -10044 tests/responses/agent-assertion-routes.test.ts -11686 tests/responses/anthropic2-responses-parity.test.ts -224 tests/responses/apply-patch-envelope.test.ts -138 tests/responses/bare-echo-alias.test.ts -6396 tests/responses/chat-anthropic-reasoning-details.test.ts -3517 tests/responses/chat-completions-deferred-tools.test.ts +176 tests/providers/zed-openai-contract.test.ts +236 tests/providers/zed-retained-budget.test.ts +302 tests/providers/zhipu-bigmodel-provider.test.ts +142 tests/providers/zhipu-bigmodel-responses-quota.test.ts +13273 tests/responses/agent-assertion-routes.test.ts +19468 tests/responses/anthropic2-responses-parity.test.ts +83 tests/responses/apply-patch-envelope.test.ts +175 tests/responses/bare-echo-alias.test.ts +6445 tests/responses/chat-anthropic-reasoning-details.test.ts +4410 tests/responses/chat-completions-deferred-tools.test.ts 97034 tests/responses/chat-completions-endpoint.test.ts -3105 tests/responses/chat-completions-pool-mode.test.ts +2984 tests/responses/chat-completions-pool-mode.test.ts 10410 tests/responses/chat-conversation-affinity.test.ts -1832 tests/responses/chat-inbound-developer-position.test.ts -96 tests/responses/chat-inbound-reasoning-none.test.ts +1582 tests/responses/chat-inbound-developer-position.test.ts +75 tests/responses/chat-inbound-reasoning-none.test.ts 467 tests/responses/chat-inbound-reasoning-replay.test.ts -1698 tests/responses/chat-incomplete-length-reason.test.ts -115 tests/responses/chat-inline-document-bytes.test.ts +1503 tests/responses/chat-incomplete-length-reason.test.ts +188 tests/responses/chat-inline-document-bytes.test.ts 4704 tests/responses/chat-json-sse-fallback.test.ts -2198 tests/responses/chat-legacy-functions-combo.test.ts +2103 tests/responses/chat-legacy-functions-combo.test.ts 2522 tests/responses/chat-media-translation.test.ts -12813 tests/responses/chat-native-combo.test.ts -208 tests/responses/chat-native-decline-reason.test.ts -13789 tests/responses/chat-native-developer-role.test.ts -238 tests/responses/chat-native-image-normalization.test.ts -94 tests/responses/chat-native-lenient-finish.test.ts -28035 tests/responses/chat-native-reasoning-replay.test.ts -78 tests/responses/chat-native-reasoning-scope.test.ts -34947 tests/responses/chat-native-spend.test.ts -402 tests/responses/chat-native-sse-stall.test.ts -43435 tests/responses/chat-raw-reasoning-delivery.test.ts -68 tests/responses/chat-refusal-scope.test.ts -3448 tests/responses/chat-refusal.test.ts -24467 tests/responses/chat-request-id-endpoint.test.ts +12405 tests/responses/chat-native-combo.test.ts +193 tests/responses/chat-native-decline-reason.test.ts +12861 tests/responses/chat-native-developer-role.test.ts +221 tests/responses/chat-native-image-normalization.test.ts +81 tests/responses/chat-native-lenient-finish.test.ts +25867 tests/responses/chat-native-reasoning-replay.test.ts +111 tests/responses/chat-native-reasoning-scope.test.ts +43202 tests/responses/chat-native-spend.test.ts +331 tests/responses/chat-native-sse-stall.test.ts +40144 tests/responses/chat-raw-reasoning-delivery.test.ts +222 tests/responses/chat-refusal-scope.test.ts +2950 tests/responses/chat-refusal.test.ts +25940 tests/responses/chat-request-id-endpoint.test.ts 2317 tests/responses/chat-responses-control-integration.test.ts -148 tests/responses/chat-responses-control-scope.test.ts -4241 tests/responses/chat-sse-framing-guard.test.ts -129 tests/responses/chat-tool-choice-allowed-tools.test.ts -185 tests/responses/citation-markers.test.ts -4832 tests/responses/codex-0164-request-compat.test.ts -13260 tests/responses/codex-installation-failover.test.ts +128 tests/responses/chat-responses-control-scope.test.ts +4824 tests/responses/chat-sse-framing-guard.test.ts +112 tests/responses/chat-tool-choice-allowed-tools.test.ts +95 tests/responses/citation-markers.test.ts +6029 tests/responses/codex-0164-request-compat.test.ts +12268 tests/responses/codex-installation-failover.test.ts 5633 tests/responses/codex-installation-turn-limit.test.ts 2073 tests/responses/codex-ws-handshake-validation.test.ts -78 tests/responses/codex-ws-handshake.test.ts -76 tests/responses/codex-ws-pool-contention.test.ts -9723 tests/responses/combo-replay-refusal-attribution.test.ts -10606 tests/responses/compact-key-selection.test.ts -21334 tests/responses/compact-transient-alternate.test.ts -192 tests/responses/compaction-continuation-note.test.ts -1090 tests/responses/compaction-continuation-wire.test.ts -160 tests/responses/compaction-event-ownership.test.ts -1290 tests/responses/compaction-history-framing.test.ts -411 tests/responses/compaction-portable-history.test.ts -158 tests/responses/compaction-progress.test.ts -191 tests/responses/continuation-dedup.test.ts -67 tests/responses/custom-tool-compat.test.ts -616 tests/responses/direct-credit-renewal-ingress.test.ts -6370 tests/responses/droid-reasoning-defaults.test.ts +258 tests/responses/codex-ws-handshake.test.ts +189 tests/responses/codex-ws-pool-contention.test.ts +11555 tests/responses/combo-replay-refusal-attribution.test.ts +10532 tests/responses/compact-key-selection.test.ts +21561 tests/responses/compact-transient-alternate.test.ts +254 tests/responses/compaction-continuation-note.test.ts +585 tests/responses/compaction-continuation-wire.test.ts +177 tests/responses/compaction-event-ownership.test.ts +729 tests/responses/compaction-history-framing.test.ts +873 tests/responses/compaction-portable-history.test.ts +172 tests/responses/compaction-progress.test.ts +144 tests/responses/continuation-dedup.test.ts +95 tests/responses/custom-tool-compat.test.ts +396 tests/responses/direct-credit-renewal-ingress.test.ts +9244 tests/responses/droid-reasoning-defaults.test.ts 8432 tests/responses/empty-completion-core.test.ts 63 tests/responses/empty-completion-guard.test.ts -1227 tests/responses/empty-completion-hardening.test.ts -80 tests/responses/eventstream-decoder.test.ts -64 tests/responses/eventstream-fragmentation.test.ts -18475 tests/responses/explicit-empty-tool-catalog-history.test.ts -41460 tests/responses/explicit-empty-tool-catalog.test.ts +1297 tests/responses/empty-completion-hardening.test.ts +64 tests/responses/eventstream-decoder.test.ts +111 tests/responses/eventstream-fragmentation.test.ts +25680 tests/responses/explicit-empty-tool-catalog-history.test.ts +40009 tests/responses/explicit-empty-tool-catalog.test.ts 299 tests/responses/external-task-input-repair.test.ts 79 tests/responses/fix-eventstream-cancel-wait.test.ts -1261 tests/responses/fresh-connection-optout.test.ts -115 tests/responses/graceful-max-output-tokens-exclusions.test.ts -1051 tests/responses/graceful-max-output-tokens.test.ts -46749 tests/responses/incomplete-reason-normalization.test.ts -19028 tests/responses/jev-initial-effort-wire.test.ts -79 tests/responses/legacy-shell-compat.test.ts -4559 tests/responses/local-upstream-deadlines.test.ts -174 tests/responses/messages-native-bridge-policy.test.ts -660 tests/responses/messages-native-eligibility.test.ts -219 tests/responses/messages-native-oauth-eligibility.test.ts -79 tests/responses/namespace-tool-compat.test.ts -9529 tests/responses/native-compaction-gateway-credentials.test.ts -18819 tests/responses/native-compaction-gateway-policy.test.ts -13387 tests/responses/native-compaction-gateway.test.ts -572 tests/responses/native-compaction-oauth.test.ts -18724 tests/responses/native-compaction-provenance.test.ts -207 tests/responses/opaque-blob-wrapped-rejection.test.ts +1135 tests/responses/fresh-connection-optout.test.ts +310 tests/responses/graceful-max-output-tokens-exclusions.test.ts +1299 tests/responses/graceful-max-output-tokens.test.ts +44507 tests/responses/incomplete-reason-normalization.test.ts +15845 tests/responses/jev-initial-effort-wire.test.ts +65 tests/responses/legacy-shell-compat.test.ts +4128 tests/responses/local-upstream-deadlines.test.ts +206 tests/responses/messages-native-bridge-policy.test.ts +238 tests/responses/messages-native-eligibility.test.ts +408 tests/responses/messages-native-oauth-eligibility.test.ts +78 tests/responses/namespace-tool-compat.test.ts +7249 tests/responses/native-compaction-gateway-credentials.test.ts +24484 tests/responses/native-compaction-gateway-policy.test.ts +16945 tests/responses/native-compaction-gateway.test.ts +824 tests/responses/native-compaction-oauth.test.ts +29385 tests/responses/native-compaction-provenance.test.ts +222 tests/responses/opaque-blob-wrapped-rejection.test.ts 1260 tests/responses/openai-responses-passthrough.test.ts -175 tests/responses/openai-responses-summary-none.test.ts +198 tests/responses/openai-responses-summary-none.test.ts 159 tests/responses/opengateway-completion-receipts.test.ts -93 tests/responses/parser-content-audio.test.ts -693 tests/responses/passthrough-abort.test.ts -74858 tests/responses/passthrough-deferred-tools.test.ts -113 tests/responses/passthrough-grok-upstream-envelope-echo.test.ts -319 tests/responses/passthrough-headers.test.ts -576 tests/responses/passthrough-media-type.test.ts -166 tests/responses/passthrough-override.test.ts -403 tests/responses/plaintext-v2-agent-messages.test.ts -9906 tests/responses/protocol-antigravity-direct-chat.test.ts -314 tests/responses/protocol-antigravity-direct-eligibility.test.ts +79 tests/responses/parser-content-audio.test.ts +857 tests/responses/passthrough-abort.test.ts +61378 tests/responses/passthrough-deferred-tools.test.ts +273 tests/responses/passthrough-grok-upstream-envelope-echo.test.ts +592 tests/responses/passthrough-headers.test.ts +186 tests/responses/passthrough-media-type.test.ts +459 tests/responses/passthrough-override.test.ts +175 tests/responses/plaintext-v2-agent-messages.test.ts +11246 tests/responses/protocol-antigravity-direct-chat.test.ts +151 tests/responses/protocol-antigravity-direct-eligibility.test.ts 10772 tests/responses/protocol-antigravity-direct-messages.test.ts 47353 tests/responses/protocol-argon-thought-boundary.test.ts 33 tests/responses/protocol-baseline.test.ts -127 tests/responses/protocol-chat-ir-parity.test.ts -80 tests/responses/protocol-contract.test.ts -190 tests/responses/protocol-direct-encoders-chat.test.ts -91 tests/responses/protocol-direct-encoders-local-upstream.test.ts +257 tests/responses/protocol-chat-ir-parity.test.ts +64 tests/responses/protocol-contract.test.ts +142 tests/responses/protocol-direct-encoders-chat.test.ts +79 tests/responses/protocol-direct-encoders-local-upstream.test.ts 172 tests/responses/protocol-direct-encoders-messages.test.ts -94 tests/responses/protocol-direct-encoders-stall-disabled.test.ts -80 tests/responses/protocol-dto.test.ts +80 tests/responses/protocol-direct-encoders-stall-disabled.test.ts +79 tests/responses/protocol-dto.test.ts 47 tests/responses/protocol-envelope.test.ts 81 tests/responses/protocol-features.test.ts -215 tests/responses/protocol-guard.test.ts -773 tests/responses/protocol-ingress-guard.test.ts -237 tests/responses/protocol-messages-ir-parity.test.ts -63 tests/responses/protocol-opaque-state.test.ts +77 tests/responses/protocol-guard.test.ts +1409 tests/responses/protocol-ingress-guard.test.ts +269 tests/responses/protocol-messages-ir-parity.test.ts +80 tests/responses/protocol-opaque-state.test.ts 111 tests/responses/protocol-path.test.ts -365 tests/responses/protocol-plan-snapshot.test.ts -93 tests/responses/protocol-plan.test.ts -269 tests/responses/protocol-shadow-plan.test.ts -140 tests/responses/protocol-trace.test.ts -80 tests/responses/provider-egress-fetch.test.ts -1757 tests/responses/reasoning-archive-http.test.ts -2716 tests/responses/reasoning-archive-ws.test.ts +188 tests/responses/protocol-plan-snapshot.test.ts +64 tests/responses/protocol-plan.test.ts +397 tests/responses/protocol-shadow-plan.test.ts +80 tests/responses/protocol-trace.test.ts +95 tests/responses/provider-egress-fetch.test.ts +2926 tests/responses/reasoning-archive-http.test.ts +2614 tests/responses/reasoning-archive-ws.test.ts 238 tests/responses/reasoning-effort-summary-default.test.ts -223 tests/responses/reasoning-envelope.test.ts +207 tests/responses/reasoning-envelope.test.ts 173 tests/responses/reasoning-retention-quota.test.ts -3326 tests/responses/reasoning-retention-routing.test.ts -3347 tests/responses/reasoning-retention-v2.test.ts -141 tests/responses/reasoning-retention.test.ts -15597 tests/responses/refreshed-upstream-deadlines.test.ts -142 tests/responses/reserve-dispatch-ws.test.ts -223 tests/responses/responses-4546-incident-regression.test.ts -35422 tests/responses/responses-account-auto-pause-wire-owner.test.ts -13396 tests/responses/responses-account-auto-pause.test.ts -190 tests/responses/responses-account-change-scrub.test.ts -8301 tests/responses/responses-account-label.test.ts +3778 tests/responses/reasoning-retention-routing.test.ts +2614 tests/responses/reasoning-retention-v2.test.ts +117 tests/responses/reasoning-retention.test.ts +11354 tests/responses/refreshed-upstream-deadlines.test.ts +172 tests/responses/reserve-dispatch-ws.test.ts +200 tests/responses/responses-4546-incident-regression.test.ts +28995 tests/responses/responses-account-auto-pause-wire-owner.test.ts +10834 tests/responses/responses-account-auto-pause.test.ts +240 tests/responses/responses-account-change-scrub.test.ts +7770 tests/responses/responses-account-label.test.ts 8220 tests/responses/responses-alternate-main-cancellation.test.ts 491 tests/responses/responses-anthropic-billing-send-budget.test.ts -744 tests/responses/responses-anthropic-compaction-prefix.test.ts -4820 tests/responses/responses-anthropic-fast-downgrade.test.ts -1077 tests/responses/responses-anthropic-legal-history.test.ts -190 tests/responses/responses-anthropic-thinking-recovery.test.ts -17095 tests/responses/responses-anthropic-thinking-signature-recovery.test.ts -3869 tests/responses/responses-auto-pause-replay-owner.test.ts -5218 tests/responses/responses-azure-opaque-blob-recovery.test.ts -206 tests/responses/responses-bare-echo-helper-fence.test.ts -112 tests/responses/responses-call-id-linkage.test.ts -5320 tests/responses/responses-canonical-nonstream.test.ts -159 tests/responses/responses-canonical-only-top-level-fields.test.ts -699 tests/responses/responses-chat-tool-call-content.test.ts -158 tests/responses/responses-chatgpt-web-replay-metadata.test.ts -745 tests/responses/responses-claude-preflight-lease.test.ts -80 tests/responses/responses-code-mode-goal-helpers.test.ts +728 tests/responses/responses-anthropic-compaction-prefix.test.ts +3325 tests/responses/responses-anthropic-fast-downgrade.test.ts +792 tests/responses/responses-anthropic-legal-history.test.ts +501 tests/responses/responses-anthropic-thinking-recovery.test.ts +15990 tests/responses/responses-anthropic-thinking-signature-recovery.test.ts +3532 tests/responses/responses-auto-pause-replay-owner.test.ts +5099 tests/responses/responses-azure-opaque-blob-recovery.test.ts +270 tests/responses/responses-bare-echo-helper-fence.test.ts +79 tests/responses/responses-call-id-linkage.test.ts +4582 tests/responses/responses-canonical-nonstream.test.ts +157 tests/responses/responses-canonical-only-top-level-fields.test.ts +1410 tests/responses/responses-chat-tool-call-content.test.ts +401 tests/responses/responses-chatgpt-web-replay-metadata.test.ts +890 tests/responses/responses-claude-preflight-lease.test.ts +95 tests/responses/responses-code-mode-goal-helpers.test.ts 222 tests/responses/responses-code-mode-mcp-direct.test.ts 249 tests/responses/responses-code-mode-patch-compile.test.ts -176 tests/responses/responses-code-mode-shell-compile.test.ts -5452 tests/responses/responses-cold-opaque-recovery.test.ts -1108 tests/responses/responses-combo-bridge-usage.test.ts -5811 tests/responses/responses-combo-exhausted-error.test.ts -2824 tests/responses/responses-combo-fallback-off.test.ts +241 tests/responses/responses-code-mode-shell-compile.test.ts +6201 tests/responses/responses-cold-opaque-recovery.test.ts +791 tests/responses/responses-combo-bridge-usage.test.ts +5596 tests/responses/responses-combo-exhausted-error.test.ts +3030 tests/responses/responses-combo-fallback-off.test.ts 787 tests/responses/responses-combo-replay-principal.test.ts -7178 tests/responses/responses-combo-run-turn-classified-failure.test.ts +10152 tests/responses/responses-combo-run-turn-classified-failure.test.ts 7323 tests/responses/responses-compact-handoff-admission.test.ts -3641 tests/responses/responses-compaction-http-isolation.test.ts -14926 tests/responses/responses-compaction-override.test.ts +3772 tests/responses/responses-compaction-http-isolation.test.ts +16936 tests/responses/responses-compaction-override.test.ts 127 tests/responses/responses-compaction-policy-identity.test.ts -64 tests/responses/responses-compaction-recovery-policy.test.ts -12563 tests/responses/responses-compaction-recovery.test.ts +67 tests/responses/responses-compaction-recovery-policy.test.ts +19225 tests/responses/responses-compaction-recovery.test.ts 6618 tests/responses/responses-compaction-routing.test.ts -286 tests/responses/responses-compaction.test.ts -10741 tests/responses/responses-console-go-upload-retry.test.ts -47381 tests/responses/responses-context-overflow.test.ts -111 tests/responses/responses-continuation-boundaries.test.ts -192 tests/responses/responses-core-modules.test.ts -47 tests/responses/responses-custom-tool-guidance.test.ts -790 tests/responses/responses-custom-tool-historical-replay.test.ts -2763 tests/responses/responses-custom-tool-repair-dispatch.test.ts -244 tests/responses/responses-custom-tool-repair.test.ts +413 tests/responses/responses-compaction.test.ts +10570 tests/responses/responses-console-go-upload-retry.test.ts +39295 tests/responses/responses-context-overflow.test.ts +174 tests/responses/responses-continuation-boundaries.test.ts +175 tests/responses/responses-core-modules.test.ts +78 tests/responses/responses-custom-tool-guidance.test.ts +539 tests/responses/responses-custom-tool-historical-replay.test.ts +2919 tests/responses/responses-custom-tool-repair-dispatch.test.ts +97 tests/responses/responses-custom-tool-repair.test.ts 143 tests/responses/responses-custom-tool-stream-consistency.test.ts -62 tests/responses/responses-default-namespace-emit-normalize.test.ts -20381 tests/responses/responses-devin-401-replay.test.ts -63 tests/responses/responses-dispatch-receipt.test.ts -342 tests/responses/responses-fetch-helpers-boundary.test.ts -47 tests/responses/responses-field-backfill.test.ts +180 tests/responses/responses-default-namespace-emit-normalize.test.ts +19795 tests/responses/responses-devin-401-replay.test.ts +246 tests/responses/responses-dispatch-receipt.test.ts +359 tests/responses/responses-fetch-helpers-boundary.test.ts +98 tests/responses/responses-field-backfill.test.ts 13909 tests/responses/responses-first-send-reservation.test.ts -1376 tests/responses/responses-first-send-spend-policy.test.ts +1630 tests/responses/responses-first-send-spend-policy.test.ts 158 tests/responses/responses-forward-client-headers.test.ts -157 tests/responses/responses-forward-dangling-call.test.ts -1107 tests/responses/responses-forward-incomplete-quota.test.ts -250 tests/responses/responses-forward-output-cap.test.ts -241 tests/responses/responses-forward-posit-continuation.test.ts -113 tests/responses/responses-forward-prompt-envelope.test.ts -226 tests/responses/responses-forward-transport-baseurl.test.ts -242 tests/responses/responses-freeform-wrapper-keys.test.ts -460 tests/responses/responses-function-tool-repair.test.ts +239 tests/responses/responses-forward-dangling-call.test.ts +1695 tests/responses/responses-forward-incomplete-quota.test.ts +204 tests/responses/responses-forward-output-cap.test.ts +127 tests/responses/responses-forward-posit-continuation.test.ts +191 tests/responses/responses-forward-prompt-envelope.test.ts +78 tests/responses/responses-forward-transport-baseurl.test.ts +252 tests/responses/responses-freeform-wrapper-keys.test.ts +618 tests/responses/responses-function-tool-repair.test.ts 21995 tests/responses/responses-grok-devin-preflight.test.ts -969 tests/responses/responses-hide-raw-reasoning.test.ts +855 tests/responses/responses-hide-raw-reasoning.test.ts 1506 tests/responses/responses-hosted-image-delivery.test.ts -114 tests/responses/responses-hosted-image-display.test.ts -270 tests/responses/responses-hosted-image-limits.test.ts -3518 tests/responses/responses-hosted-send-hop.test.ts -9308 tests/responses/responses-hosted-send-producer.test.ts -9614 tests/responses/responses-hosted-send-reservation.test.ts -519 tests/responses/responses-hosted-send-round-parity.test.ts -2228 tests/responses/responses-hosted-send-unsent-hop.test.ts +320 tests/responses/responses-hosted-image-display.test.ts +349 tests/responses/responses-hosted-image-limits.test.ts +5109 tests/responses/responses-hosted-send-hop.test.ts +8675 tests/responses/responses-hosted-send-producer.test.ts +10117 tests/responses/responses-hosted-send-reservation.test.ts +523 tests/responses/responses-hosted-send-round-parity.test.ts +3715 tests/responses/responses-hosted-send-unsent-hop.test.ts 949 tests/responses/responses-hosted-send-ws.test.ts -449 tests/responses/responses-hosted-tool-declaration.test.ts +160 tests/responses/responses-hosted-tool-declaration.test.ts 143 tests/responses/responses-hosted-tool-min-spread.test.ts -1061 tests/responses/responses-image-gen-repair.test.ts -1900 tests/responses/responses-inbound-store-default.test.ts -81 tests/responses/responses-item-id-repair.test.ts -82 tests/responses/responses-json-events.test.ts -264 tests/responses/responses-legacy-dotted-tool-name-repair.test.ts -6335 tests/responses/responses-main-quota-observation.test.ts -4426 tests/responses/responses-memory-models.test.ts +871 tests/responses/responses-image-gen-repair.test.ts +2313 tests/responses/responses-inbound-store-default.test.ts +80 tests/responses/responses-item-id-repair.test.ts +80 tests/responses/responses-json-events.test.ts +95 tests/responses/responses-legacy-dotted-tool-name-repair.test.ts +5880 tests/responses/responses-main-quota-observation.test.ts +4532 tests/responses/responses-memory-models.test.ts 109 tests/responses/responses-mimo-envelope.test.ts -950 tests/responses/responses-muse-tool-choice.test.ts -1045 tests/responses/responses-muse-tool-name-alias.test.ts +1062 tests/responses/responses-muse-tool-choice.test.ts +2188 tests/responses/responses-muse-tool-name-alias.test.ts 1770 tests/responses/responses-native-compact-search-history.test.ts 999 tests/responses/responses-native-item-extensions-compact.test.ts -191 tests/responses/responses-native-item-extensions.test.ts -9423 tests/responses/responses-native-key-cooldown.test.ts -3705 tests/responses/responses-native-main-refresh.test.ts -7936 tests/responses/responses-native-ultra-effort-wire.test.ts -14518 tests/responses/responses-oauth-refresh-capacity.test.ts -44924 tests/responses/responses-opaque-blob-recovery.test.ts -64 tests/responses/responses-parser-agent-message.test.ts -124 tests/responses/responses-parser-malformed-content.test.ts +190 tests/responses/responses-native-item-extensions.test.ts +11506 tests/responses/responses-native-key-cooldown.test.ts +2837 tests/responses/responses-native-main-refresh.test.ts +5447 tests/responses/responses-native-ultra-effort-wire.test.ts +11259 tests/responses/responses-oauth-refresh-capacity.test.ts +31337 tests/responses/responses-opaque-blob-recovery.test.ts +237 tests/responses/responses-parser-agent-message.test.ts +95 tests/responses/responses-parser-malformed-content.test.ts 269 tests/responses/responses-parser.test.ts -223 tests/responses/responses-passthrough-transient-policy.test.ts +305 tests/responses/responses-passthrough-transient-policy.test.ts 83 tests/responses/responses-phase-inference.test.ts -38468 tests/responses/responses-pool-401-refresh.test.ts +48612 tests/responses/responses-pool-401-refresh.test.ts 14550 tests/responses/responses-pool-overload-failover.test.ts -199 tests/responses/responses-pool-refresh-attribution.test.ts +444 tests/responses/responses-pool-refresh-attribution.test.ts 10953 tests/responses/responses-preview-main-read-fence.test.ts -1406 tests/responses/responses-reasoning-effort-downgrade.test.ts -969 tests/responses/responses-reasoning-summary-passthrough.test.ts +1808 tests/responses/responses-reasoning-effort-downgrade.test.ts +1266 tests/responses/responses-reasoning-summary-passthrough.test.ts 648 tests/responses/responses-replay-metadata-principal.test.ts -204 tests/responses/responses-request-compression.test.ts -5041 tests/responses/responses-required-chat-tool.test.ts -97 tests/responses/responses-reset-replay.test.ts -5023 tests/responses/responses-retained-reasoning-stream-recovery.test.ts -208 tests/responses/responses-routed-web-search-fields.test.ts -932 tests/responses/responses-run-turn-key-pacing.test.ts +336 tests/responses/responses-request-compression.test.ts +5046 tests/responses/responses-required-chat-tool.test.ts +190 tests/responses/responses-reset-replay.test.ts +4889 tests/responses/responses-retained-reasoning-stream-recovery.test.ts +407 tests/responses/responses-routed-web-search-fields.test.ts +908 tests/responses/responses-run-turn-key-pacing.test.ts 2213 tests/responses/responses-run-turn-key-readmission.test.ts -12524 tests/responses/responses-run-turn-web-search.test.ts +12274 tests/responses/responses-run-turn-web-search.test.ts 4898 tests/responses/responses-self-named-namespace-scrub.test.ts -12624 tests/responses/responses-send-budget-counts.test.ts -5460 tests/responses/responses-send-budget-errors.test.ts +13097 tests/responses/responses-send-budget-counts.test.ts +5602 tests/responses/responses-send-budget-errors.test.ts 2304 tests/responses/responses-shadow-intercept.test.ts -5172 tests/responses/responses-show-thinking-summary.test.ts -21521 tests/responses/responses-sidecar-context-overflow.test.ts -1585 tests/responses/responses-sidecar-usage.test.ts -1391 tests/responses/responses-skills-snapshot.test.ts -15384 tests/responses/responses-snapshot-repair-server.test.ts +4309 tests/responses/responses-show-thinking-summary.test.ts +16485 tests/responses/responses-sidecar-context-overflow.test.ts +1633 tests/responses/responses-sidecar-usage.test.ts +2331 tests/responses/responses-skills-snapshot.test.ts +12691 tests/responses/responses-snapshot-repair-server.test.ts 223 tests/responses/responses-snapshot-repair.test.ts -522 tests/responses/responses-snapshot-scaling.test.ts -161 tests/responses/responses-sparse-terminal-tool-scope.test.ts +348 tests/responses/responses-snapshot-scaling.test.ts +128 tests/responses/responses-sparse-terminal-tool-scope.test.ts 16711 tests/responses/responses-spend-anchor.test.ts -115 tests/responses/responses-spend-capacity-guard.test.ts -714 tests/responses/responses-spend-contract-c.test.ts -379 tests/responses/responses-spend-ledger-wiring.test.ts -127 tests/responses/responses-spill-acl-recovery.test.ts -760 tests/responses/responses-spill-admission-headroom.test.ts +159 tests/responses/responses-spend-capacity-guard.test.ts +618 tests/responses/responses-spend-contract-c.test.ts +523 tests/responses/responses-spend-ledger-wiring.test.ts +221 tests/responses/responses-spill-acl-recovery.test.ts +840 tests/responses/responses-spill-admission-headroom.test.ts 174 tests/responses/responses-spill-inspection.test.ts -206 tests/responses/responses-spill-orphan-sweep.test.ts -346 tests/responses/responses-spill-shutdown-clock.test.ts -721 tests/responses/responses-state-flush-race.test.ts -81 tests/responses/responses-state-snapshot-select.test.ts -125 tests/responses/responses-state-snapshot-stubs.test.ts -1151 tests/responses/responses-state-store-false.test.ts -1735 tests/responses/responses-state-write-amplification.test.ts -11688 tests/responses/responses-state.test.ts -5644 tests/responses/responses-stateless-dangling-call-repair.test.ts +284 tests/responses/responses-spill-orphan-sweep.test.ts +315 tests/responses/responses-spill-shutdown-clock.test.ts +443 tests/responses/responses-state-flush-race.test.ts +79 tests/responses/responses-state-snapshot-select.test.ts +111 tests/responses/responses-state-snapshot-stubs.test.ts +1141 tests/responses/responses-state-store-false.test.ts +1442 tests/responses/responses-state-write-amplification.test.ts +16362 tests/responses/responses-state.test.ts +3959 tests/responses/responses-stateless-dangling-call-repair.test.ts 80 tests/responses/responses-stream-tool-events.test.ts 480 tests/responses/responses-terminal-repair.test.ts -339 tests/responses/responses-tool-conformance.test.ts -94 tests/responses/responses-tool-groups.test.ts +345 tests/responses/responses-tool-conformance.test.ts +79 tests/responses/responses-tool-groups.test.ts 1673 tests/responses/responses-tool-search-repair.test.ts -2963 tests/responses/responses-translated-replay-principal.test.ts -48677 tests/responses/responses-translated-reset.test.ts -2710 tests/responses/responses-undeclared-tool-guard-inbound.test.ts -14141 tests/responses/responses-undeclared-tool-guard.test.ts -111 tests/responses/responses-url-citation-title-repair.test.ts -93 tests/responses/responses-usage-passthrough.test.ts +2491 tests/responses/responses-translated-replay-principal.test.ts +44648 tests/responses/responses-translated-reset.test.ts +3688 tests/responses/responses-undeclared-tool-guard-inbound.test.ts +11886 tests/responses/responses-undeclared-tool-guard.test.ts +271 tests/responses/responses-url-citation-title-repair.test.ts +128 tests/responses/responses-usage-passthrough.test.ts 26005 tests/responses/responses-web-search-thinking-signature-recovery.test.ts -192 tests/responses/responses-xai-request-compat.test.ts -2504 tests/responses/shadow-intercept-target-lifecycle.test.ts -78 tests/responses/sse-carriage-return.test.ts +206 tests/responses/responses-xai-request-compat.test.ts +2555 tests/responses/shadow-intercept-target-lifecycle.test.ts +108 tests/responses/sse-carriage-return.test.ts 412 tests/responses/sse-client-frame-bounds.test.ts 444 tests/responses/sse-decoder.test.ts -348 tests/responses/sse-failed-tail.test.ts -646 tests/responses/sse-inspector-bounds.test.ts -129 tests/responses/sse-null-data-frame.test.ts -159 tests/responses/sse-payload-rewrite.test.ts +865 tests/responses/sse-failed-tail.test.ts +711 tests/responses/sse-inspector-bounds.test.ts +111 tests/responses/sse-null-data-frame.test.ts +319 tests/responses/sse-payload-rewrite.test.ts 337 tests/responses/sse-rewrite-line-endings.test.ts -95 tests/responses/sse-unspaced-data-fields.test.ts -174 tests/responses/thought-signature-credential-scope.test.ts -679 tests/responses/turn-membership-ingress.test.ts -81 tests/responses/turn-membership.test.ts +112 tests/responses/sse-unspaced-data-fields.test.ts +305 tests/responses/thought-signature-credential-scope.test.ts +1199 tests/responses/turn-membership-ingress.test.ts +125 tests/responses/turn-membership.test.ts 65 tests/responses/visualization-directives.test.ts -6591 tests/responses/ws-ambiguous-resend.test.ts +6217 tests/responses/ws-ambiguous-resend.test.ts 42648 tests/responses/ws-capacity-reclamation.test.ts -3359 tests/responses/ws-capacity-tool-ownership.test.ts -96 tests/responses/ws-committed-liveness.test.ts +4521 tests/responses/ws-capacity-tool-ownership.test.ts +80 tests/responses/ws-committed-liveness.test.ts 222 tests/responses/ws-endpoint.test.ts -141 tests/responses/ws-failure-stage.test.ts +127 tests/responses/ws-failure-stage.test.ts 3546 tests/responses/ws-native-injection.test.ts -2125 tests/responses/ws-native-result-continuations.test.ts -4707 tests/responses/ws-native-steering.test.ts +1965 tests/responses/ws-native-result-continuations.test.ts +6413 tests/responses/ws-native-steering.test.ts 351 tests/responses/ws-pre-output-refusal.test.ts 1388 tests/responses/ws-replay-refusal-attribution.test.ts 4176 tests/responses/ws-steering-completion.test.ts -643 tests/responses/ws-steering-smoke.test.ts -571 tests/responses/ws-steering-stability.test.ts -220 tests/responses/ws-upstream-reuse.test.ts -77 tests/responses/ws-upstream-socks5.test.ts +245 tests/responses/ws-steering-smoke.test.ts +728 tests/responses/ws-steering-stability.test.ts +453 tests/responses/ws-upstream-reuse.test.ts +63 tests/responses/ws-upstream-socks5.test.ts 2564 tests/responses/ws-upstream.test.ts -5027 tests/routing/always-on-429-failover.test.ts -2286 tests/routing/anthropic-quorum-cache.test.ts -79 tests/routing/cl01-claude-outbound-review-regressions.test.ts -95 tests/routing/cl01-openai-chat-review-regressions.test.ts -126 tests/routing/cl01-review-regressions.test.ts -394 tests/routing/codex-agent-role-models.test.ts -95 tests/routing/codex-role-auto-assign.test.ts -320 tests/routing/codex-role-capability-consent.test.ts -62 tests/routing/codex-role-capability-redirects.test.ts +4729 tests/routing/always-on-429-failover.test.ts +1852 tests/routing/anthropic-quorum-cache.test.ts +78 tests/routing/cl01-claude-outbound-review-regressions.test.ts +219 tests/routing/cl01-openai-chat-review-regressions.test.ts +111 tests/routing/cl01-review-regressions.test.ts +459 tests/routing/codex-agent-role-models.test.ts +191 tests/routing/codex-role-auto-assign.test.ts +174 tests/routing/codex-role-capability-consent.test.ts +95 tests/routing/codex-role-capability-redirects.test.ts 182 tests/routing/codex-role-measured-ties.test.ts -50 tests/routing/codex-role-sizing.test.ts -140 tests/routing/combo-child-headers.test.ts -1761 tests/routing/combo-description.test.ts -15836 tests/routing/combo-management-api.test.ts -282 tests/routing/combo-required-tool-stream-preflight.test.ts -128 tests/routing/combo-stream-preflight.test.ts +82 tests/routing/codex-role-sizing.test.ts +349 tests/routing/combo-child-headers.test.ts +1640 tests/routing/combo-description.test.ts +13691 tests/routing/combo-management-api.test.ts +188 tests/routing/combo-required-tool-stream-preflight.test.ts +457 tests/routing/combo-stream-preflight.test.ts 191 tests/routing/combo-terminal-refusal.test.ts -3272 tests/routing/combo-vision-enrollment.test.ts -15167 tests/routing/compatibility-provider-equivalence.test.ts -241 tests/routing/destination-policy-resolved.test.ts +3781 tests/routing/combo-vision-enrollment.test.ts +15202 tests/routing/compatibility-provider-equivalence.test.ts +99 tests/routing/destination-policy-resolved.test.ts 95 tests/routing/fallback-policy.test.ts -208 tests/routing/fastwire-characterization-routing.test.ts -6603 tests/routing/fastwire-characterization-wire.test.ts -720 tests/routing/fastwire-observability.test.ts -175 tests/routing/fastwire-policy.test.ts -3271 tests/routing/fastwire-response-authority.test.ts -81 tests/routing/jev-decision-destination.test.ts -2930 tests/routing/jev-decision-model-config.test.ts -2473 tests/routing/jev-decision-provider-combo.test.ts +129 tests/routing/fastwire-characterization-routing.test.ts +6232 tests/routing/fastwire-characterization-wire.test.ts +710 tests/routing/fastwire-observability.test.ts +192 tests/routing/fastwire-policy.test.ts +4582 tests/routing/fastwire-response-authority.test.ts +92 tests/routing/jev-decision-destination.test.ts +3731 tests/routing/jev-decision-model-config.test.ts +2428 tests/routing/jev-decision-provider-combo.test.ts 190 tests/routing/jev-decision.test.ts -1073 tests/routing/jev-model-backend.test.ts -7863 tests/routing/jev-quota-activation.test.ts -5848 tests/routing/jev-quota-anthropic2.test.ts -2963 tests/routing/jev-quota-antigravity.test.ts +1256 tests/routing/jev-model-backend.test.ts +6367 tests/routing/jev-quota-activation.test.ts +4231 tests/routing/jev-quota-anthropic2.test.ts +3152 tests/routing/jev-quota-antigravity.test.ts 3288 tests/routing/jev-quota-codex-reset.test.ts 3410 tests/routing/jev-quota-config.test.ts -1174 tests/routing/jev-quota-core-boundary.test.ts -2558 tests/routing/jev-quota-publication.test.ts -364 tests/routing/jev-quota-signals.test.ts -127 tests/routing/jev-service-exchange.test.ts -79 tests/routing/jev-session-pin.test.ts +1112 tests/routing/jev-quota-core-boundary.test.ts +2029 tests/routing/jev-quota-publication.test.ts +379 tests/routing/jev-quota-signals.test.ts +102 tests/routing/jev-service-exchange.test.ts +81 tests/routing/jev-session-pin.test.ts 53 tests/routing/jev-typesafe-golden.test.ts -274 tests/routing/policy-execution.test.ts -2376 tests/routing/probe-lease-dispatch-wiring.test.ts -218 tests/routing/probe-lease.test.ts -344 tests/routing/resolved-model-policy-consumers.test.ts -93 tests/routing/router-anthropic-billing-failover.test.ts -381 tests/routing/router-blocked-cross-provider.test.ts -121 tests/routing/router-combo-failover-classification.test.ts -142 tests/routing/router-discarded-baseurl-warning.test.ts +330 tests/routing/policy-execution.test.ts +2708 tests/routing/probe-lease-dispatch-wiring.test.ts +190 tests/routing/probe-lease.test.ts +206 tests/routing/resolved-model-policy-consumers.test.ts +223 tests/routing/router-anthropic-billing-failover.test.ts +317 tests/routing/router-blocked-cross-provider.test.ts +137 tests/routing/router-combo-failover-classification.test.ts +333 tests/routing/router-discarded-baseurl-warning.test.ts 145 tests/routing/router-template-baseurl.test.ts 230 tests/routing/router.test.ts -4330 tests/routing/routing-analytics.test.ts -95 tests/routing/routing-capability-catalog.test.ts -366 tests/routing/routing-capability-model-matching.test.ts -63 tests/routing/routing-compatibility-auth-identity.test.ts -30471 tests/routing/routing-compatibility-boundaries.test.ts -96 tests/routing/routing-compatibility-model-matching.test.ts -15485 tests/routing/routing-compatibility.test.ts +2882 tests/routing/routing-analytics.test.ts +143 tests/routing/routing-capability-catalog.test.ts +602 tests/routing/routing-capability-model-matching.test.ts +80 tests/routing/routing-compatibility-auth-identity.test.ts +30561 tests/routing/routing-compatibility-boundaries.test.ts +82 tests/routing/routing-compatibility-model-matching.test.ts +16301 tests/routing/routing-compatibility.test.ts 80 tests/routing/routing-identity-domains.test.ts -411 tests/routing/routing-policy-dispatch-scope.test.ts -174 tests/routing/routing-policy-fallback-off.test.ts -491 tests/routing/routing-policy-fallback.test.ts -234 tests/routing/routing-policy-pool-quota.test.ts +511 tests/routing/routing-policy-dispatch-scope.test.ts +266 tests/routing/routing-policy-fallback-off.test.ts +381 tests/routing/routing-policy-fallback.test.ts +142 tests/routing/routing-policy-pool-quota.test.ts 15468 tests/routing/routing-policy-surface-parity.test.ts -30866 tests/routing/routing-profile-management-editor.test.ts -776 tests/routing/routing-profile.test.ts -252 tests/routing/subagent-context-staleness.test.ts -101 tests/routing/subagent-defaults.test.ts +30770 tests/routing/routing-profile-management-editor.test.ts +1132 tests/routing/routing-profile.test.ts +348 tests/routing/subagent-context-staleness.test.ts +64 tests/routing/subagent-defaults.test.ts 30688 tests/routing/subagent-fallback-handle-responses.test.ts -78 tests/routing/subagent-fallback-preview-sites.test.ts -363 tests/routing/subagent-model-fallback-api.test.ts -1521 tests/routing/subagent-model-fallback-off.test.ts -38293 tests/routing/subagent-model-fallback.test.ts -2996 tests/routing/subagent-roster-migration.test.ts -1946 tests/routing/subagent-roster-retention.test.ts -342 tests/server/account-import-project-fallback.test.ts -2946 tests/server/account-import.test.ts +95 tests/routing/subagent-fallback-preview-sites.test.ts +475 tests/routing/subagent-model-fallback-api.test.ts +1446 tests/routing/subagent-model-fallback-off.test.ts +30031 tests/routing/subagent-model-fallback.test.ts +2633 tests/routing/subagent-roster-migration.test.ts +1644 tests/routing/subagent-roster-retention.test.ts +110 tests/server/account-import-project-fallback.test.ts +2149 tests/server/account-import.test.ts 88278 tests/server/account-pool-management-api.test.ts -186 tests/server/adapter-resolve.test.ts +133 tests/server/adapter-resolve.test.ts +158 tests/server/admitted-http-turn.test.ts 196 tests/server/advisor-routes.test.ts -406 tests/server/agent-assertion-auth.test.ts -2164 tests/server/agent-task-recovery-cache.test.ts -3795 tests/server/agent-task-recovery-combo.test.ts -940 tests/server/agent-task-recovery-fallback.test.ts +175 tests/server/agent-assertion-auth.test.ts +2783 tests/server/agent-task-recovery-cache.test.ts +5693 tests/server/agent-task-recovery-combo.test.ts +411 tests/server/agent-task-recovery-fallback.test.ts 1363 tests/server/agent-task-recovery-security.test.ts -29693 tests/server/agent-task-recovery.test.ts -222 tests/server/alias-management-api.test.ts -3443 tests/server/anthropic2-management.test.ts -161 tests/server/api-access-endpoints.test.ts -9456 tests/server/api-catalog-route.test.ts -2147 tests/server/api-codex-log-guard-compact.test.ts -788 tests/server/api-codex-log-guard-protection.test.ts -537 tests/server/api-codex-log-guard.test.ts +29835 tests/server/agent-task-recovery.test.ts +269 tests/server/alias-management-api.test.ts +2626 tests/server/anthropic2-management.test.ts +144 tests/server/api-access-endpoints.test.ts +8550 tests/server/api-catalog-route.test.ts +2436 tests/server/api-codex-log-guard-compact.test.ts +572 tests/server/api-codex-log-guard-protection.test.ts +427 tests/server/api-codex-log-guard.test.ts 19958 tests/server/api-debug.test.ts -22524 tests/server/api-key-attribution.test.ts -415 tests/server/api-key-model-scope.test.ts -2048 tests/server/api-key-scope-alpha-search.test.ts -208 tests/server/api-key-scope-audio.test.ts +29504 tests/server/api-key-attribution.test.ts +753 tests/server/api-key-model-scope.test.ts +1586 tests/server/api-key-scope-alpha-search.test.ts +205 tests/server/api-key-scope-audio.test.ts 379 tests/server/api-key-scope-images.test.ts -175 tests/server/api-key-scope-live.test.ts -91218 tests/server/api-keys-routes.test.ts -60632 tests/server/api-usage.test.ts +189 tests/server/api-key-scope-live.test.ts +96673 tests/server/api-keys-routes.test.ts +62858 tests/server/api-usage.test.ts 6065 tests/server/aside-profiles-routes.test.ts 94 tests/server/audio-client.test.ts -20540 tests/server/audio-dictation.test.ts -35679 tests/server/audio-transcriptions.test.ts -948 tests/server/bounded-body.test.ts -158 tests/server/bridge-live-delivery.test.ts -2651 tests/server/caller-session-identity.test.ts +22599 tests/server/audio-dictation.test.ts +34544 tests/server/audio-transcriptions.test.ts +943 tests/server/bounded-body.test.ts +174 tests/server/bridge-live-delivery.test.ts +1205 tests/server/caller-session-identity.test.ts 1783 tests/server/caller-session-ingress.test.ts 3505 tests/server/cancel-body-on-abort.test.ts -20864 tests/server/claude-intercept-integration.test.ts +18163 tests/server/claude-intercept-integration.test.ts 5580 tests/server/codex-agent-role-routes.test.ts -394 tests/server/codex-role-auto-assign-routes.test.ts -220 tests/server/codex-role-configured-credentials.test.ts -947 tests/server/codex-role-history-recovery.test.ts -4667 tests/server/combo-loopback-metered-consent.test.ts -1868 tests/server/combo-metered-consent.test.ts -65 tests/server/combo-requested-effort.test.ts +734 tests/server/codex-role-auto-assign-routes.test.ts +253 tests/server/codex-role-configured-credentials.test.ts +1158 tests/server/codex-role-history-recovery.test.ts +4537 tests/server/combo-loopback-metered-consent.test.ts +2048 tests/server/combo-metered-consent.test.ts +227 tests/server/combo-requested-effort.test.ts 237 tests/server/companion-settings.test.ts -10582 tests/server/config.test.ts -191 tests/server/consume-for-inspection-cancel.test.ts +8922 tests/server/config.test.ts +143 tests/server/consume-for-inspection-cancel.test.ts 6327 tests/server/context-history-ownership.test.ts -496 tests/server/context-history.test.ts -1960 tests/server/data-plane-admission-identity.test.ts +381 tests/server/context-history.test.ts +2729 tests/server/data-plane-admission-identity.test.ts 95 tests/server/debug-settings.test.ts 81 tests/server/decision-discovery.test.ts -333 tests/server/decision-routes.test.ts -2259 tests/server/distributed-key-401.test.ts -400 tests/server/error-fidelity.test.ts -292 tests/server/errors-adapter-failure.test.ts +508 tests/server/decision-routes.test.ts +3875 tests/server/distributed-key-401.test.ts +287 tests/server/error-fidelity.test.ts +607 tests/server/errors-adapter-failure.test.ts 2618 tests/server/fallback-routes.test.ts -587 tests/server/fetch-header-timeout.test.ts -4403 tests/server/health-scoring.test.ts +554 tests/server/fetch-header-timeout.test.ts +3589 tests/server/health-scoring.test.ts 2692 tests/server/hub-usage.test.ts 5312 tests/server/inbound-body-admission.test.ts -250 tests/server/inbound-body-budget.test.ts -92 tests/server/inference-attempt.test.ts -222 tests/server/inference-client-encoder-delivery.test.ts -63 tests/server/inference-client-wire.test.ts -110 tests/server/inference-final-log.test.ts -4802 tests/server/inference-send-budget.test.ts -111 tests/server/input-admission.test.ts -415 tests/server/jev-decision-scope.test.ts -601 tests/server/link-child-parity.test.ts -3981 tests/server/link-enrollment.test.ts -2618 tests/server/link-join-route.test.ts -7523 tests/server/link-listener-admission.test.ts -365 tests/server/link-listener-lifecycle.test.ts -379 tests/server/link-listener-mutation.test.ts -25666 tests/server/link-management-relay.test.ts -2266 tests/server/link-management-routes.test.ts -95 tests/server/live-call-bindings.test.ts -64 tests/server/live-native-calls.test.ts -481 tests/server/local-account-switch-capability.test.ts -1296 tests/server/local-account-switch-ingress.test.ts -5799 tests/server/local-aside-sync-capability.test.ts -79 tests/server/local-management-attestation.test.ts -111 tests/server/local-management-capability.test.ts +157 tests/server/inbound-body-budget.test.ts +143 tests/server/inference-attempt.test.ts +254 tests/server/inference-client-encoder-delivery.test.ts +181 tests/server/inference-client-wire.test.ts +205 tests/server/inference-final-log.test.ts +5728 tests/server/inference-send-budget.test.ts +159 tests/server/input-admission.test.ts +207 tests/server/jev-decision-scope.test.ts +919 tests/server/link-child-parity.test.ts +3065 tests/server/link-enrollment.test.ts +2548 tests/server/link-join-route.test.ts +9402 tests/server/link-listener-admission.test.ts +302 tests/server/link-listener-lifecycle.test.ts +239 tests/server/link-listener-mutation.test.ts +24661 tests/server/link-management-relay.test.ts +1665 tests/server/link-management-routes.test.ts +110 tests/server/live-call-bindings.test.ts +50 tests/server/live-native-calls.test.ts +314 tests/server/local-account-switch-capability.test.ts +1201 tests/server/local-account-switch-ingress.test.ts +4888 tests/server/local-aside-sync-capability.test.ts +96 tests/server/local-management-attestation.test.ts +261 tests/server/local-management-capability.test.ts 565 tests/server/local-management-direct-transport.test.ts -222 tests/server/local-provider-reload-client.test.ts -1474 tests/server/local-read-response-proof.test.ts -662 tests/server/login-shell-path.test.ts -238 tests/server/logs-timezone.test.ts +77 tests/server/local-provider-reload-client.test.ts +1335 tests/server/local-read-response-proof.test.ts +646 tests/server/login-shell-path.test.ts +301 tests/server/logs-timezone.test.ts 215 tests/server/loopback-companion-client-targets.test.ts -256 tests/server/loopback-listener-admission.test.ts -83804 tests/server/loopback-listener-integration.test.ts +158 tests/server/loopback-listener-admission.test.ts +78131 tests/server/loopback-listener-integration.test.ts 1205 tests/server/management-account-auto-pause.test.ts -1915 tests/server/management-anthropic-reset-grants.test.ts -413 tests/server/management-api-logs-metrics.test.ts +1728 tests/server/management-anthropic-reset-grants.test.ts +315 tests/server/management-api-logs-metrics.test.ts 222 tests/server/management-api-logs-timing-basis.test.ts -2010 tests/server/management-auto-review-auth.test.ts -1713 tests/server/management-auto-review-settings.test.ts -1155 tests/server/management-client-config-route.test.ts -159 tests/server/management-desktop-compatibility-routes.test.ts -222 tests/server/management-desktop-compatibility-runtime-routes.test.ts -962 tests/server/management-desktop-compatibility-settings.test.ts -492 tests/server/management-droid-reasoning-defaults.test.ts -2045 tests/server/management-export-model-names.test.ts +1774 tests/server/management-auto-review-auth.test.ts +1634 tests/server/management-auto-review-settings.test.ts +728 tests/server/management-client-config-route.test.ts +206 tests/server/management-desktop-compatibility-routes.test.ts +524 tests/server/management-desktop-compatibility-runtime-routes.test.ts +649 tests/server/management-desktop-compatibility-settings.test.ts +891 tests/server/management-droid-reasoning-defaults.test.ts +1970 tests/server/management-export-model-names.test.ts 21725 tests/server/management-gcp-credential-input.test.ts -1857 tests/server/management-google-tool-schema-policy.test.ts -524 tests/server/management-inference-port.test.ts -3342 tests/server/management-integration-journal-delete.test.ts -15909 tests/server/management-integration-routes.test.ts -25508 tests/server/management-metrics-export.test.ts +2192 tests/server/management-google-tool-schema-policy.test.ts +695 tests/server/management-inference-port.test.ts +3996 tests/server/management-integration-journal-delete.test.ts +16483 tests/server/management-integration-routes.test.ts +32290 tests/server/management-metrics-export.test.ts 270 tests/server/management-model-roster-gather-race.test.ts -207 tests/server/management-model-roster.test.ts +480 tests/server/management-model-roster.test.ts 96 tests/server/management-origin-tls.test.ts -4578 tests/server/management-provider-atomicity.test.ts +4250 tests/server/management-provider-atomicity.test.ts 36191 tests/server/management-provider-compat-carry.test.ts -480 tests/server/management-provider-context-inference.test.ts -8136 tests/server/management-provider-hide-raw-reasoning.test.ts -2806 tests/server/management-provider-pinsless-validation.test.ts +412 tests/server/management-provider-context-inference.test.ts +14377 tests/server/management-provider-hide-raw-reasoning.test.ts +2186 tests/server/management-provider-pinsless-validation.test.ts 1809 tests/server/management-provider-proto-override.test.ts -11935 tests/server/management-provider-reasoning-lists.test.ts -505 tests/server/management-provider-request-pacing.test.ts -63 tests/server/management-provider-reset-replay.test.ts -16781 tests/server/management-provider-responses-reasoning.test.ts -998 tests/server/management-provider-synthetic-max.test.ts -1636 tests/server/management-provider-upstream-websocket.test.ts -136959 tests/server/management-provider-validation.test.ts -2116 tests/server/management-provider-verbosity.test.ts -711 tests/server/management-qoder-selector-state.test.ts -3508 tests/server/management-route-registry.test.ts -7021 tests/server/management-sidecar-anthropic-instance.test.ts +11942 tests/server/management-provider-reasoning-lists.test.ts +949 tests/server/management-provider-request-pacing.test.ts +95 tests/server/management-provider-reset-replay.test.ts +12073 tests/server/management-provider-responses-reasoning.test.ts +1077 tests/server/management-provider-synthetic-max.test.ts +1585 tests/server/management-provider-upstream-websocket.test.ts +147509 tests/server/management-provider-validation.test.ts +2177 tests/server/management-provider-verbosity.test.ts +760 tests/server/management-qoder-selector-state.test.ts +1282 tests/server/management-route-registry.test.ts +9158 tests/server/management-sidecar-anthropic-instance.test.ts 176 tests/server/management-workflow-budget-routes.test.ts -552 tests/server/memory-watchdog.test.ts -600 tests/server/model-costs-management-api.test.ts -4384 tests/server/model-costs-pricing-cache.test.ts +810 tests/server/memory-watchdog.test.ts +952 tests/server/model-costs-management-api.test.ts +5607 tests/server/model-costs-pricing-cache.test.ts 9249 tests/server/model-costs-prompt-length-pricing.test.ts -191 tests/server/model-discovery-management-api.test.ts -3455 tests/server/model-export-new-model-policy.test.ts -1826 tests/server/model-settings-management-api.test.ts -81 tests/server/outbound-body-guard.test.ts -192 tests/server/owned-service-home.test.ts +251 tests/server/model-discovery-management-api.test.ts +3248 tests/server/model-export-new-model-policy.test.ts +2075 tests/server/model-settings-management-api.test.ts +218 tests/server/outbound-body-guard.test.ts +348 tests/server/owned-service-home.test.ts 64 tests/server/passive-route-linker.test.ts -2542 tests/server/persistent-dashboard-admission.test.ts -9041 tests/server/persistent-dashboard-consent.test.ts -1140 tests/server/persistent-dashboard-session.test.ts -11144 tests/server/plaintext-v2-agent-messages-server.test.ts -1110 tests/server/port-reclaim.test.ts +3308 tests/server/persistent-dashboard-admission.test.ts +6600 tests/server/persistent-dashboard-consent.test.ts +1866 tests/server/persistent-dashboard-session.test.ts +9634 tests/server/plaintext-v2-agent-messages-server.test.ts +1031 tests/server/port-reclaim.test.ts 503 tests/server/ports.test.ts -19647 tests/server/prefer-model-alias-ids.test.ts -977 tests/server/probe-timeout-env.test.ts -268 tests/server/protocol-provider-summary.test.ts -190 tests/server/protocol-routes.test.ts -173 tests/server/protocol-settings-route.test.ts -1255 tests/server/provider-account-quota-routes.test.ts -253 tests/server/provider-egress-management-validation.test.ts -298 tests/server/provider-send-path-import.test.ts -263 tests/server/proxy-env-macos.test.ts -112 tests/server/proxy-env.test.ts -3413 tests/server/proxy-liveness-bind-scope.test.ts +18261 tests/server/prefer-model-alias-ids.test.ts +1618 tests/server/probe-timeout-env.test.ts +220 tests/server/protocol-provider-summary.test.ts +207 tests/server/protocol-routes.test.ts +159 tests/server/protocol-settings-route.test.ts +1078 tests/server/protocol-trace-suppression.test.ts +1588 tests/server/provider-account-quota-routes.test.ts +96 tests/server/provider-egress-management-validation.test.ts +251 tests/server/provider-send-path-import.test.ts +96 tests/server/proxy-env-macos.test.ts +145 tests/server/proxy-env.test.ts +2602 tests/server/proxy-liveness-bind-scope.test.ts 1376 tests/server/proxy-liveness-owner-evidence.test.ts -95 tests/server/proxy-liveness-package-tree-fence.test.ts -247 tests/server/proxy-liveness-recovery.test.ts -199 tests/server/proxy-liveness.test.ts -9323 tests/server/quota-pool-relay.test.ts -2215 tests/server/readyz-features.test.ts -947 tests/server/relay-eager.test.ts -17583 tests/server/replay-refusal-parity.test.ts -1387 tests/server/reserve-claude-policy.test.ts -21057 tests/server/reserve-ingress.test.ts +79 tests/server/proxy-liveness-package-tree-fence.test.ts +80 tests/server/proxy-liveness-recovery.test.ts +126 tests/server/proxy-liveness.test.ts +10967 tests/server/quota-pool-relay.test.ts +2869 tests/server/readyz-features.test.ts +868 tests/server/relay-eager.test.ts +14150 tests/server/replay-refusal-parity.test.ts +1487 tests/server/reserve-claude-policy.test.ts +22537 tests/server/reserve-ingress.test.ts 982 tests/server/response-log-inspection.test.ts -1661 tests/server/response-model-identity.test.ts -957 tests/server/restart-replacement-not-ready.test.ts +1760 tests/server/response-model-identity.test.ts +1126 tests/server/restart-replacement-not-ready.test.ts 201 tests/server/restart-replacement.test.ts -335 tests/server/retry-after-429.test.ts -114 tests/server/retry-delay-hardening.test.ts +430 tests/server/retry-after-429.test.ts +80 tests/server/retry-delay-hardening.test.ts 235 tests/server/route-decision-trace.test.ts -13622 tests/server/served-by-header.test.ts -4544 tests/server/server-403-permission-e2e.test.ts -4023 tests/server/server-agent-task-recovery-replay.test.ts -6267 tests/server/server-anthropic-billing-boundaries.test.ts -12125 tests/server/server-anthropic-billing.test.ts -2075 tests/server/server-antigravity-model-denial-recovery.test.ts -15800 tests/server/server-antigravity-model-roster-routing.test.ts +15628 tests/server/served-by-header.test.ts +4094 tests/server/server-403-permission-e2e.test.ts +2802 tests/server/server-agent-task-recovery-replay.test.ts +7179 tests/server/server-anthropic-billing-boundaries.test.ts +14829 tests/server/server-anthropic-billing.test.ts +2198 tests/server/server-antigravity-model-denial-recovery.test.ts +14800 tests/server/server-antigravity-model-roster-routing.test.ts 254 tests/server/server-antigravity-verify-replay-scope.test.ts 23596 tests/server/server-antigravity-web-search-validation.test.ts -1061 tests/server/server-auth-localhost-bind.test.ts -8594 tests/server/server-auth-scoped-quota.test.ts +1172 tests/server/server-auth-localhost-bind.test.ts +9473 tests/server/server-auth-scoped-quota.test.ts 244552 tests/server/server-auth.test.ts -15177 tests/server/server-background-lifecycle.test.ts -11760 tests/server/server-chat-native-key-selection.test.ts -2560 tests/server/server-cli-key-probe-admission.test.ts +19818 tests/server/server-background-lifecycle.test.ts +11577 tests/server/server-chat-native-key-selection.test.ts +3356 tests/server/server-cli-key-probe-admission.test.ts 79 tests/server/server-clickjacking-headers.test.ts -3057 tests/server/server-combo-cooldown-fallback.test.ts -3375 tests/server/server-combo-cooldown-recording.test.ts -67226 tests/server/server-combo-failover-e2e.test.ts -244 tests/server/server-combo-held-response.test.ts +3974 tests/server/server-combo-cooldown-fallback.test.ts +3196 tests/server/server-combo-cooldown-recording.test.ts +103988 tests/server/server-combo-failover-e2e.test.ts +79 tests/server/server-combo-held-response.test.ts 20721 tests/server/server-combo-plan-model-refusal.test.ts -190 tests/server/server-combo-quota-code-provenance.test.ts -5184 tests/server/server-combo-reasoning-replay-eligibility.test.ts -37119 tests/server/server-combo-required-tool-contract.test.ts -4133 tests/server/server-combo-stream-hosted-tool-contract.test.ts +160 tests/server/server-combo-quota-code-provenance.test.ts +5400 tests/server/server-combo-reasoning-replay-eligibility.test.ts +45660 tests/server/server-combo-required-tool-contract.test.ts +6723 tests/server/server-combo-stream-hosted-tool-contract.test.ts 11384 tests/server/server-combo-stream-required-tool.test.ts -3952 tests/server/server-combo-stream-send-contract.test.ts -7979 tests/server/server-combo-tool-loop-continuation.test.ts +3852 tests/server/server-combo-stream-send-contract.test.ts +7708 tests/server/server-combo-tool-loop-continuation.test.ts 5529 tests/server/server-combo-zero-output-failover.test.ts -909 tests/server/server-desktop-compatibility-startup.test.ts -19801 tests/server/server-generic-oauth-affinity.test.ts -80940 tests/server/server-google-antigravity-oauth-401-replay.test.ts -8395 tests/server/server-google-antigravity-oauth-429-budget.test.ts -63 tests/server/server-gui-bundle-freshness.test.ts -237 tests/server/server-images-bodyless-content-length.test.ts +711 tests/server/server-desktop-compatibility-startup.test.ts +19221 tests/server/server-generic-oauth-affinity.test.ts +131291 tests/server/server-google-antigravity-oauth-401-replay.test.ts +13779 tests/server/server-google-antigravity-oauth-429-budget.test.ts +95 tests/server/server-gui-bundle-freshness.test.ts +189 tests/server/server-images-bodyless-content-length.test.ts 3438 tests/server/server-images-pool-admission.test.ts -90665 tests/server/server-images.test.ts -492 tests/server/server-jev-combo-e2e.test.ts -640 tests/server/server-jev-model-decision-e2e.test.ts -429 tests/server/server-jev-model-quota-budget.test.ts -399 tests/server/server-jev-session-pin.test.ts -74695 tests/server/server-key-failover-e2e.test.ts +88086 tests/server/server-images.test.ts +555 tests/server/server-jev-combo-e2e.test.ts +287 tests/server/server-jev-model-decision-e2e.test.ts +539 tests/server/server-jev-model-quota-budget.test.ts +268 tests/server/server-jev-session-pin.test.ts +98620 tests/server/server-key-failover-e2e.test.ts 25095 tests/server/server-kiro-completion-e2e.test.ts 2716 tests/server/server-kiro-device-login.test.ts 7822 tests/server/server-kiro-oauth-401-replay.test.ts -117502 tests/server/server-kiro-refusal-e2e.test.ts -2921 tests/server/server-live-cancel.test.ts -8965 tests/server/server-live-close.test.ts -4039 tests/server/server-live-existing-call.test.ts +105975 tests/server/server-kiro-refusal-e2e.test.ts +50237 tests/server/server-kiro-usage-log-e2e.test.ts +2653 tests/server/server-live-cancel.test.ts +8767 tests/server/server-live-close.test.ts +4438 tests/server/server-live-existing-call.test.ts 333 tests/server/server-live-frame-log.test.ts -8565 tests/server/server-live-realtime-fixtures.test.ts -47614 tests/server/server-live.test.ts -237 tests/server/server-loopback-host-gate.test.ts -41641 tests/server/server-management-auth.test.ts +10022 tests/server/server-live-realtime-fixtures.test.ts +41610 tests/server/server-live.test.ts +224 tests/server/server-loopback-host-gate.test.ts +39167 tests/server/server-management-auth.test.ts 3721 tests/server/server-management-log-admission.test.ts -19010 tests/server/server-native-catalog-priority.test.ts +18613 tests/server/server-native-catalog-priority.test.ts +388 tests/server/server-native-final-log.test.ts 127 tests/server/server-native-reasoning-retention-merge.test.ts -205 tests/server/server-native-reasoning-retention.test.ts +300 tests/server/server-native-reasoning-retention.test.ts 13214 tests/server/server-new-model-policy-arrival.test.ts -4772 tests/server/server-opencode-go-goal-streaming.test.ts -7999 tests/server/server-rate-limit-retry-e2e.test.ts +43068 tests/server/server-ollama-inbound-errors.test.ts +11652 tests/server/server-ollama-inbound-lifecycle.test.ts +30821 tests/server/server-ollama-inbound.test.ts +6259 tests/server/server-opencode-go-goal-streaming.test.ts +12166 tests/server/server-rate-limit-retry-e2e.test.ts 3246 tests/server/server-request-body-size.test.ts -22095 tests/server/server-search.test.ts -2531 tests/server/server-startup-codex-off.test.ts -9394 tests/server/server-startup-reconcile-resilience.test.ts +21361 tests/server/server-search.test.ts +2378 tests/server/server-startup-codex-off.test.ts +9371 tests/server/server-startup-reconcile-resilience.test.ts 7932 tests/server/server-stop-config-hardening.test.ts -1883 tests/server/server-terminal-refusal-wiring.test.ts -222 tests/server/server-workflow-budget-settings.test.ts -2249 tests/server/server-xai-chat-reasoning-streaming.test.ts -3936 tests/server/server-xai-header-parity.test.ts -17849 tests/server/server-xai-oauth-401-replay.test.ts -15831 tests/server/server-xai-responses-streaming.test.ts -2381 tests/server/session-affinity.test.ts +2947 tests/server/server-terminal-refusal-wiring.test.ts +207 tests/server/server-workflow-budget-settings.test.ts +2677 tests/server/server-xai-chat-reasoning-streaming.test.ts +3842 tests/server/server-xai-header-parity.test.ts +19655 tests/server/server-xai-oauth-401-replay.test.ts +13607 tests/server/server-xai-responses-streaming.test.ts +2335 tests/server/session-affinity.test.ts 3142 tests/server/session-lane-recall-harness.test.ts -427 tests/server/sidebar-routes.test.ts -96 tests/server/sidebar-star-state.test.ts -173 tests/server/spend-instrumentation-log.test.ts -1013 tests/server/spend-ledger-lifecycle.test.ts -5046 tests/server/spend-ledger-owner-startup.test.ts -159 tests/server/startup-action-control-elevation.test.ts -254 tests/server/startup-action-control.test.ts -34335 tests/server/startup-health-packaged-probe.test.ts -73 tests/server/startup-prompt.test.ts +318 tests/server/sidebar-routes.test.ts +79 tests/server/sidebar-star-state.test.ts +142 tests/server/spend-instrumentation-log.test.ts +1521 tests/server/spend-ledger-lifecycle.test.ts +4221 tests/server/spend-ledger-owner-startup.test.ts +143 tests/server/startup-action-control-elevation.test.ts +505 tests/server/startup-action-control.test.ts +33880 tests/server/startup-health-packaged-probe.test.ts +95 tests/server/startup-prompt.test.ts 158 tests/server/stream-aborted-marker.test.ts -1452 tests/server/subagent-model-force-api.test.ts +1219 tests/server/subagent-model-force-api.test.ts 855 tests/server/system-env.test.ts -255 tests/server/system-restart-admission.test.ts -13375 tests/server/system-restart-ownership.test.ts -315 tests/server/system-restart.test.ts -222 tests/server/system-routes.test.ts -8840 tests/server/terminal-guard-server.test.ts -144 tests/server/terminal-guard.test.ts -207 tests/server/update-async-routes.test.ts -197 tests/server/upstream-connect-error.test.ts -239 tests/server/upstream-http-version.test.ts -20792 tests/server/v1-hub-state.test.ts -4476 tests/server/v2-agent-message-failfast.test.ts -194 tests/service/autostart-health.test.ts -2513 tests/service/connected-stop-capability-auth.test.ts -2714 tests/service/container-bootstrap.test.ts +207 tests/server/system-restart-admission.test.ts +13304 tests/server/system-restart-ownership.test.ts +477 tests/server/system-restart.test.ts +434 tests/server/system-routes.test.ts +7479 tests/server/terminal-guard-server.test.ts +125 tests/server/terminal-guard.test.ts +237 tests/server/update-async-routes.test.ts +192 tests/server/upstream-connect-error.test.ts +81 tests/server/upstream-http-version.test.ts +16338 tests/server/v1-hub-state.test.ts +4026 tests/server/v2-agent-message-failfast.test.ts +176 tests/service/autostart-health.test.ts +1579 tests/service/connected-stop-capability-auth.test.ts +4759 tests/service/container-bootstrap.test.ts 112 tests/service/crash-guard.test.ts -239 tests/service/doctor-codex-envkey-readiness.test.ts +175 tests/service/doctor-codex-envkey-readiness.test.ts 947 tests/service/doctor-oauth.test.ts -329 tests/service/doctor-provider-apikey.test.ts -178 tests/service/doctor-service-memory-contract.test.ts -238 tests/service/init-backup-cleanup.test.ts -8102 tests/service/init-eof.test.ts +238 tests/service/doctor-provider-apikey.test.ts +78 tests/service/doctor-service-memory-contract.test.ts +221 tests/service/init-backup-cleanup.test.ts +7851 tests/service/init-eof.test.ts 412 tests/service/launchd-port-fallback.test.ts -5688 tests/service/launchd-repair.test.ts -175 tests/service/live-service-manager-guard.test.ts -112 tests/service/managing-cli.test.ts -174 tests/service/ownership-mutation-lease-diagnostics.test.ts -966 tests/service/process-state.test.ts -1239 tests/service/service-auth-qualified-localhost.test.ts -698 tests/service/service-child-ownership.test.ts -310 tests/service/service-claim.test.ts -81 tests/service/service-desktop-login-registration.test.ts +7048 tests/service/launchd-repair.test.ts +420 tests/service/live-service-manager-guard.test.ts +111 tests/service/managing-cli.test.ts +140 tests/service/ownership-mutation-lease-diagnostics.test.ts +887 tests/service/process-state.test.ts +1835 tests/service/service-auth-qualified-localhost.test.ts +557 tests/service/service-child-ownership.test.ts +251 tests/service/service-claim.test.ts +67 tests/service/service-desktop-login-registration.test.ts 159 tests/service/service-desktop-recovery.test.ts -93 tests/service/service-desktop-runtime-preflight.test.ts -142 tests/service/service-desktop-startup-health.test.ts -268 tests/service/service-desktop-startup-linux.test.ts -1601 tests/service/service-desktop-startup.test.ts -128 tests/service/service-desktop-supervision-windows.test.ts -258 tests/service/service-handled-signal-exit.test.ts -108 tests/service/service-health-sentinel-launch.test.ts -75 tests/service/service-health-sentinel-linux.test.ts -88 tests/service/service-health-sentinel-policy.test.ts -8162 tests/service/service-health-sentinel-process.test.ts -522 tests/service/service-health-sentinel-runner.test.ts -453 tests/service/service-install-wrapper-cleanup.test.ts -3184 tests/service/service-log.test.ts -160 tests/service/service-multishell-path.test.ts -97 tests/service/service-ownership-compatibility.test.ts -598 tests/service/service-ownership-handover.test.ts -5072 tests/service/service-ownership-state.test.ts -62 tests/service/service-probe-docker.test.ts +257 tests/service/service-desktop-runtime-preflight.test.ts +143 tests/service/service-desktop-startup-health.test.ts +114 tests/service/service-desktop-startup-linux.test.ts +1076 tests/service/service-desktop-startup.test.ts +255 tests/service/service-desktop-supervision-windows.test.ts +78 tests/service/service-handled-signal-exit.test.ts +262 tests/service/service-health-sentinel-launch.test.ts +99 tests/service/service-health-sentinel-linux.test.ts +76 tests/service/service-health-sentinel-policy.test.ts +8151 tests/service/service-health-sentinel-process.test.ts +584 tests/service/service-health-sentinel-runner.test.ts +318 tests/service/service-install-wrapper-cleanup.test.ts +3730 tests/service/service-log.test.ts +395 tests/service/service-multishell-path.test.ts +80 tests/service/service-ownership-compatibility.test.ts +809 tests/service/service-ownership-handover.test.ts +4535 tests/service/service-ownership-state.test.ts +65 tests/service/service-probe-docker.test.ts 91 tests/service/service-proxy-env.test.ts 460 tests/service/service-runtime-preflight.test.ts -7605 tests/service/service-secrets.test.ts +7347 tests/service/service-secrets.test.ts 363 tests/service/service-sqlite-home.test.ts -172 tests/service/service-start-environment.test.ts -699 tests/service/service-state-isolation.test.ts +215 tests/service/service-start-environment.test.ts +638 tests/service/service-state-isolation.test.ts 2813 tests/service/service-status-json.test.ts -111 tests/service/service-stop-verification.test.ts -3428 tests/service/service-tier-capability.test.ts -426 tests/service/service-wsl-home-ownership.test.ts -2993 tests/service/service.test.ts -442 tests/service/shutdown-drain.test.ts -265 tests/service/shutdown-launcher.test.ts +125 tests/service/service-stop-verification.test.ts +3522 tests/service/service-tier-capability.test.ts +341 tests/service/service-wsl-home-ownership.test.ts +3037 tests/service/service.test.ts +649 tests/service/shutdown-drain.test.ts +107 tests/service/shutdown-launcher.test.ts 226 tests/service/stale-state-purge.test.ts -97 tests/service/standalone-service.test.ts -50776 tests/service/stop-deferred-teardown.test.ts -586 tests/service/stop-direct-fetch.test.ts +61 tests/service/standalone-service.test.ts +56621 tests/service/stop-deferred-teardown.test.ts +567 tests/service/stop-direct-fetch.test.ts 1939 tests/service/stop-restoration-preflight.test.ts -23394 tests/service/stop-restore-history-ownership.test.ts -48 tests/service/systemd-install-cleanup-hardening.test.ts -254 tests/service/winsw.test.ts +24156 tests/service/stop-restore-history-ownership.test.ts +80 tests/service/systemd-install-cleanup-hardening.test.ts +348 tests/service/winsw.test.ts 31188 tests/storage/api-storage-cleanup.test.ts -6076 tests/storage/api-storage-policy-already-running.test.ts +5453 tests/storage/api-storage-policy-already-running.test.ts 4729 tests/storage/api-storage-policy-mutation-busy.test.ts -4977 tests/storage/api-storage-policy-put-race.test.ts -6828 tests/storage/api-storage-policy-run.test.ts -7661 tests/storage/api-storage-policy.test.ts -3846 tests/storage/api-storage.test.ts -15008 tests/storage/storage-cleanup.test.ts -20269 tests/storage/storage-mutation-race.test.ts -2336 tests/storage/storage-policy-config-race.test.ts -5366 tests/storage/storage-policy-job-responsive.test.ts -254396 tests/storage/storage-policy.test.ts -135 tests/storage/storage-restore-job-errors.test.ts -12177 tests/storage/storage-restore-job-responsive.test.ts -1352 tests/storage/storage-scanner.test.ts -4849 tests/storage/storage-worker-lifecycle.test.ts -1 tests/storage/storage-worker-os-join-settle.test.ts -25080 tests/storage/storage-worker-teardown-isolate.test.ts -2693 tests/test-layout-tooling.test.ts -209 tests/test-layout.test.ts -143 tests/update/pnpm-command-isolation.test.ts -96 tests/update/update-badge.test.ts -9964 tests/update/update-bun-ownership-lease.test.ts +5252 tests/storage/api-storage-policy-put-race.test.ts +6794 tests/storage/api-storage-policy-run.test.ts +5428 tests/storage/api-storage-policy.test.ts +4196 tests/storage/api-storage.test.ts +15654 tests/storage/storage-cleanup.test.ts +20412 tests/storage/storage-mutation-race.test.ts +1888 tests/storage/storage-policy-config-race.test.ts +6157 tests/storage/storage-policy-job-responsive.test.ts +254714 tests/storage/storage-policy.test.ts +234 tests/storage/storage-restore-job-errors.test.ts +14038 tests/storage/storage-restore-job-responsive.test.ts +2173 tests/storage/storage-scanner.test.ts +4874 tests/storage/storage-worker-lifecycle.test.ts +127 tests/storage/storage-worker-os-join-settle.test.ts +25537 tests/storage/storage-worker-teardown-isolate.test.ts +5869 tests/test-layout-tooling.test.ts +221 tests/test-layout.test.ts +157 tests/update/pnpm-command-isolation.test.ts +240 tests/update/update-badge.test.ts +8624 tests/update/update-bun-ownership-lease.test.ts 1535 tests/update/update-capability-policy.test.ts -82 tests/update/update-desktop-badge.test.ts -97 tests/update/update-desktop-owner.test.ts -191 tests/update/update-effect-authority.test.ts -204 tests/update/update-guarded-ops.test.ts -1344 tests/update/update-home-launcher.test.ts -81 tests/update/update-home-recovery.test.ts -2772 tests/update/update-home-worker.test.ts -1050 tests/update/update-job-supervised-restart.test.ts -6781 tests/update/update-job.test.ts +185 tests/update/update-desktop-badge.test.ts +82 tests/update/update-desktop-owner.test.ts +96 tests/update/update-effect-authority.test.ts +269 tests/update/update-guarded-ops.test.ts +1093 tests/update/update-home-launcher.test.ts +79 tests/update/update-home-recovery.test.ts +3696 tests/update/update-home-worker.test.ts +871 tests/update/update-job-supervised-restart.test.ts +5827 tests/update/update-job.test.ts 64 tests/update/update-mise-launcher-target.test.ts -63 tests/update/update-mise-node-runtime.test.ts -517 tests/update/update-mise.test.ts -236 tests/update/update-mutation-boundaries.test.ts -1286 tests/update/update-mutation-guard.test.ts -1793 tests/update/update-mutation-scanner.test.ts +48 tests/update/update-mise-node-runtime.test.ts +493 tests/update/update-mise.test.ts +175 tests/update/update-mutation-boundaries.test.ts +1711 tests/update/update-mutation-guard.test.ts +1934 tests/update/update-mutation-scanner.test.ts 316 tests/update/update-notify.test.ts -499 tests/update/update-npm-cache-preflight.test.ts -112 tests/update/update-npm-invocation.test.ts -3808 tests/update/update-npm-supervisor-exit.test.ts -9160 tests/update/update-npm-timeout.test.ts -222 tests/update/update-pnpm.test.ts +333 tests/update/update-npm-cache-preflight.test.ts +96 tests/update/update-npm-invocation.test.ts +2888 tests/update/update-npm-supervisor-exit.test.ts +8517 tests/update/update-npm-timeout.test.ts +372 tests/update/update-pnpm.test.ts 258 tests/update/update-reclaim-authorizer.test.ts -97 tests/update/update-recovery-authority.test.ts -633 tests/update/update-recovery-boundaries.test.ts -64 tests/update/update-recovery-host-free.test.ts -457 tests/update/update-refresh.test.ts -49298 tests/update/update-restart-lease.test.ts +282 tests/update/update-recovery-authority.test.ts +600 tests/update/update-recovery-boundaries.test.ts +225 tests/update/update-recovery-host-free.test.ts +475 tests/update/update-refresh.test.ts +50319 tests/update/update-restart-lease.test.ts 47 tests/update/update-service-home-policy.test.ts -1346 tests/update/update-service-home.test.ts +2029 tests/update/update-service-home.test.ts 175 tests/update/update-standalone.test.ts 2437 tests/update/update-stop-classification.test.ts -264 tests/update/update-stop-first.test.ts -150 tests/update/update-supervised-recovery.test.ts -5978 tests/update/update-teardown-handover.test.ts -776 tests/update/update-transactional-leftovers.test.ts -509 tests/update/update-transactional.test.ts +212 tests/update/update-stop-first.test.ts +187 tests/update/update-supervised-recovery.test.ts +7233 tests/update/update-teardown-handover.test.ts +667 tests/update/update-transactional-leftovers.test.ts +503 tests/update/update-transactional.test.ts 4075 tests/update/update-tray-handoff.test.ts -317 tests/update/update-tree-ownership.test.ts +313 tests/update/update-tree-ownership.test.ts 63 tests/update/update-windows-wrapper-authority.test.ts 48 tests/update/update-worker-launch.test.ts -110 tests/usage/anthropic2-usage-attribution.test.ts -269 tests/usage/cache-diagnostic.test.ts -683 tests/usage/cost-cap-unknown-evidence.test.ts -375 tests/usage/cost-scoring.test.ts -152 tests/usage/gpt61-terra-pricing.test.ts -105 tests/usage/jev-stats.test.ts -98 tests/usage/key-attribution.test.ts -7096 tests/usage/quota-401-recovery-runtime.test.ts -94 tests/usage/quota-401-recovery.test.ts -9287 tests/usage/quota-pool.test.ts -238 tests/usage/quota-reset-account-key.test.ts -666 tests/usage/quota-reset-core-boundary.test.ts +80 tests/usage/anthropic2-usage-attribution.test.ts +286 tests/usage/cache-diagnostic.test.ts +507 tests/usage/cost-cap-unknown-evidence.test.ts +266 tests/usage/cost-scoring.test.ts +80 tests/usage/gpt61-terra-pricing.test.ts +103 tests/usage/jev-stats.test.ts +239 tests/usage/key-attribution.test.ts +5924 tests/usage/quota-401-recovery-runtime.test.ts +79 tests/usage/quota-401-recovery.test.ts +9068 tests/usage/quota-pool.test.ts +158 tests/usage/quota-reset-account-key.test.ts +633 tests/usage/quota-reset-core-boundary.test.ts 83 tests/usage/quota-reset-detector.test.ts -111 tests/usage/quota-reset-notify-config.test.ts -1009 tests/usage/quota-reset-notify.test.ts -1764 tests/usage/quota-reset-observation.test.ts -2337 tests/usage/quota-reset-seen-store.test.ts -568 tests/usage/quota-scoring.test.ts -838 tests/usage/request-decompress.test.ts -48 tests/usage/request-evidence.test.ts -11526 tests/usage/request-history-index.test.ts -29236 tests/usage/request-history-integrity.test.ts +74 tests/usage/quota-reset-notify-config.test.ts +839 tests/usage/quota-reset-notify.test.ts +1587 tests/usage/quota-reset-observation.test.ts +2412 tests/usage/quota-reset-seen-store.test.ts +964 tests/usage/quota-scoring.test.ts +1328 tests/usage/request-decompress.test.ts +47 tests/usage/request-evidence.test.ts +12834 tests/usage/request-history-index.test.ts +20010 tests/usage/request-history-integrity.test.ts 6512 tests/usage/request-history-rebuild-worker.test.ts -289 tests/usage/request-log-attempt-identity.test.ts +146 tests/usage/request-log-attempt-identity.test.ts 128 tests/usage/request-log-conversation.test.ts -271 tests/usage/request-log-estimate-cap.test.ts -302 tests/usage/request-log-generation-window.test.ts -191 tests/usage/request-log-jev.test.ts -48 tests/usage/request-log-model-filter.test.ts -186 tests/usage/request-log-nonstream.test.ts -267 tests/usage/request-log-normalization.test.ts -124 tests/usage/request-log-protocol-trace.test.ts -126 tests/usage/request-log-served-model.test.ts -1061 tests/usage/request-log.test.ts -223 tests/usage/request-outcome-agreement.test.ts -95 tests/usage/request-pacing-provenance.test.ts -237 tests/usage/request-pacing.test.ts -29860 tests/usage/upstream-failure-diagnostics.test.ts +318 tests/usage/request-log-estimate-cap.test.ts +364 tests/usage/request-log-generation-window.test.ts +156 tests/usage/request-log-jev.test.ts +62 tests/usage/request-log-model-filter.test.ts +252 tests/usage/request-log-nonstream.test.ts +158 tests/usage/request-log-normalization.test.ts +157 tests/usage/request-log-protocol-trace.test.ts +431 tests/usage/request-log-served-model.test.ts +935 tests/usage/request-log.test.ts +286 tests/usage/request-outcome-agreement.test.ts +64 tests/usage/request-pacing-provenance.test.ts +338 tests/usage/request-pacing.test.ts +26797 tests/usage/upstream-failure-diagnostics.test.ts 331 tests/usage/usage-aggregate-cache.test.ts -64 tests/usage/usage-anthropic-fast-pricing.test.ts -63 tests/usage/usage-antigravity-55.test.ts -79 tests/usage/usage-attempt-delivery.test.ts +79 tests/usage/usage-anthropic-fast-pricing.test.ts +111 tests/usage/usage-antigravity-55.test.ts +96 tests/usage/usage-attempt-delivery.test.ts 118 tests/usage/usage-cost.test.ts -177 tests/usage/usage-cursor-fast-pricing.test.ts +98 tests/usage/usage-cursor-fast-pricing.test.ts 423 tests/usage/usage-debug.test.ts -63 tests/usage/usage-failure-fingerprint.test.ts -159 tests/usage/usage-failure-persistence.test.ts +80 tests/usage/usage-failure-fingerprint.test.ts +386 tests/usage/usage-failure-persistence.test.ts 63 tests/usage/usage-failure-projection.test.ts 117 tests/usage/usage-haiku-5-5-pricing.test.ts 315 tests/usage/usage-ledger-retention.test.ts 348 tests/usage/usage-ledger-scanner.test.ts -47 tests/usage/usage-log-ws-stage.test.ts -4066 tests/usage/usage-log.test.ts -95 tests/usage/usage-partly-measured-cost.test.ts -89 tests/usage/usage-prompt-length-pricing.test.ts -108 tests/usage/usage-provider-label.test.ts -401 tests/usage/usage-shape-extraction.test.ts -111 tests/usage/usage-snapshot-digest-reuse.test.ts +77 tests/usage/usage-log-ws-stage.test.ts +2830 tests/usage/usage-log.test.ts +112 tests/usage/usage-partly-measured-cost.test.ts +97 tests/usage/usage-prompt-length-pricing.test.ts +263 tests/usage/usage-provider-label.test.ts +746 tests/usage/usage-shape-extraction.test.ts +95 tests/usage/usage-snapshot-digest-reuse.test.ts 108 tests/usage/usage-spend-cache-provenance.test.ts -254 tests/usage/usage-summary.test.ts -302 tests/usage/usage-surfaces.test.ts +226 tests/usage/usage-summary.test.ts +105 tests/usage/usage-surfaces.test.ts 48 tests/usage/usage-throughput.test.ts -63 tests/usage/usage-time-range.test.ts -3970 tests/usage/usage-timeline.test.ts -1280 tests/usage/user-cost-overlay-coderabbit-regressions.test.ts +79 tests/usage/usage-time-range.test.ts +3086 tests/usage/usage-timeline.test.ts +1112 tests/usage/user-cost-overlay-coderabbit-regressions.test.ts 4366 tests/usage/user-cost-overlay-live-reconcile.test.ts -759 tests/usage/user-cost-overlay-provider-delete.test.ts -65 tests/videos/fulfill-video.test.ts +555 tests/usage/user-cost-overlay-provider-delete.test.ts +95 tests/videos/fulfill-video.test.ts 364 tests/videos/plan-video.test.ts -109 tests/videos/xai-video-client.test.ts -17132 tests/vision/mistral-vision-sidecar.test.ts -475 tests/vision/sidecar-abort.test.ts -144 tests/vision/sidecar-auth.test.ts -141 tests/vision/sidecar-candidates.test.ts -5515 tests/vision/sidecar-settings-vision-catalog.test.ts -1998 tests/vision/sidecar-settings-vision-controls.test.ts -1317 tests/vision/sidecar-settings-vision-filter.test.ts -2089 tests/vision/sidecar-settings-web-search-gate.test.ts -1207 tests/vision/sidecar-settings-web-search-off.test.ts -1364 tests/vision/sidecar-settings-web-search-stream.test.ts -80 tests/vision/sidecar-tracker.test.ts +111 tests/videos/xai-video-client.test.ts +12579 tests/vision/mistral-vision-sidecar.test.ts +518 tests/vision/sidecar-abort.test.ts +127 tests/vision/sidecar-auth.test.ts +270 tests/vision/sidecar-candidates.test.ts +5497 tests/vision/sidecar-settings-vision-catalog.test.ts +2219 tests/vision/sidecar-settings-vision-controls.test.ts +1092 tests/vision/sidecar-settings-vision-filter.test.ts +1713 tests/vision/sidecar-settings-web-search-gate.test.ts +1441 tests/vision/sidecar-settings-web-search-off.test.ts +888 tests/vision/sidecar-settings-web-search-stream.test.ts +64 tests/vision/sidecar-tracker.test.ts 7708 tests/vision/vision-anthropic-instance-sidecar.test.ts 839 tests/vision/vision-anthropic.test.ts -778 tests/vision/vision-backend-union.test.ts -223 tests/vision/vision-cache.test.ts -158 tests/vision/vision-custom-row-precedence.test.ts -162 tests/vision/vision-eligibility.test.ts -157 tests/vision/vision-fail-closed.test.ts -1039 tests/vision/vision-reasoning-contract.test.ts -4152 tests/vision/vision-routed.test.ts -25907 tests/vision/vision-sidecar-e2e.test.ts -234 tests/vision/vision-text-only-predicate.test.ts -317 tests/web-search/devin-web-search.test.ts -48 tests/web-search/fix-search-frame-shapes.test.ts -96 tests/web-search/fix-search-orphan-source.test.ts -63 tests/web-search/fix-search-unicode-clamp.test.ts +1045 tests/vision/vision-backend-union.test.ts +190 tests/vision/vision-cache.test.ts +172 tests/vision/vision-custom-row-precedence.test.ts +329 tests/vision/vision-eligibility.test.ts +142 tests/vision/vision-fail-closed.test.ts +1932 tests/vision/vision-reasoning-contract.test.ts +4110 tests/vision/vision-routed.test.ts +21367 tests/vision/vision-sidecar-e2e.test.ts +222 tests/vision/vision-text-only-predicate.test.ts +332 tests/web-search/devin-web-search.test.ts +95 tests/web-search/fix-search-frame-shapes.test.ts +63 tests/web-search/fix-search-orphan-source.test.ts +79 tests/web-search/fix-search-unicode-clamp.test.ts 64 tests/web-search/format-result.test.ts -3022 tests/web-search/web-search-anthropic-instance.test.ts +3867 tests/web-search/web-search-anthropic-instance.test.ts 391 tests/web-search/web-search-anthropic.test.ts -1540 tests/web-search/web-search-backend-union.test.ts -159 tests/web-search/web-search-bridge-replay.test.ts -113 tests/web-search/web-search-candidates.test.ts -80 tests/web-search/web-search-eof.test.ts -191 tests/web-search/web-search-forced-declaration.test.ts -206 tests/web-search/web-search-loop-error-usage.test.ts -481 tests/web-search/web-search-loop-iteration-usage.test.ts -487 tests/web-search/web-search-pacing-deadline.test.ts -193 tests/web-search/web-search-parse.test.ts -5024 tests/web-search/web-search-passthrough-bridge.test.ts -2795 tests/web-search/web-search-progress-stream.test.ts -205 tests/web-search/web-search-recovery-kind.test.ts -1612 tests/web-search/web-search-retry-heartbeat.test.ts -711 tests/web-search/web-search-rotation-usage-attribution.test.ts -113 tests/web-search/web-search-run-turn-loop.test.ts -7305 tests/web-search/web-search-sidecar-429.test.ts -618 tests/web-search/web-search-sidecar-replay.test.ts -147 tests/web-search/web-search-sources.test.ts -181 tests/web-search/web-search-terminal-refusal.test.ts -1004 tests/web-search/web-search-timeout-contract.test.ts -175 tests/web-search/web-search-timeout-plan.test.ts -5824 tests/web-search/web-search.test.ts +1907 tests/web-search/web-search-backend-union.test.ts +127 tests/web-search/web-search-bridge-replay.test.ts +175 tests/web-search/web-search-candidates.test.ts +187 tests/web-search/web-search-eof.test.ts +336 tests/web-search/web-search-forced-declaration.test.ts +141 tests/web-search/web-search-loop-error-usage.test.ts +127 tests/web-search/web-search-loop-iteration-usage.test.ts +222 tests/web-search/web-search-pacing-deadline.test.ts +67 tests/web-search/web-search-parse.test.ts +4123 tests/web-search/web-search-passthrough-bridge.test.ts +3264 tests/web-search/web-search-progress-stream.test.ts +190 tests/web-search/web-search-recovery-kind.test.ts +1653 tests/web-search/web-search-retry-heartbeat.test.ts +1316 tests/web-search/web-search-rotation-usage-attribution.test.ts +177 tests/web-search/web-search-run-turn-loop.test.ts +7558 tests/web-search/web-search-sidecar-429.test.ts +617 tests/web-search/web-search-sidecar-replay.test.ts +212 tests/web-search/web-search-sources.test.ts +129 tests/web-search/web-search-terminal-refusal.test.ts +571 tests/web-search/web-search-timeout-contract.test.ts +143 tests/web-search/web-search-timeout-plan.test.ts +5744 tests/web-search/web-search.test.ts 1611 tests/windows/coding-agent-native-empty-argv.test.ts 79 tests/windows/tray-proxy-deadline.test.ts -2363 tests/windows/tray-proxy.test.ts -81 tests/windows/win-exec.test.ts -133 tests/windows/win-paths.test.ts +2447 tests/windows/tray-proxy.test.ts +82 tests/windows/win-exec.test.ts +80 tests/windows/win-paths.test.ts 111 tests/windows/windows-acl-start-cost.test.ts -81 tests/windows/windows-atomic-replace.test.ts +65 tests/windows/windows-atomic-replace.test.ts 381 tests/windows/windows-atomic-write-acl-rearm.test.ts -90603 tests/windows/windows-codex-cli-job-store.test.ts -130 tests/windows/windows-config-read-acl-memo.test.ts -13597 tests/windows/windows-config-root-async-writers.test.ts -225 tests/windows/windows-deploy-close-regressions.test.ts -2700 tests/windows/windows-elevation-spawn.test.ts -94 tests/windows/windows-elevation.test.ts -116 tests/windows/windows-guarded-manager.test.ts -158 tests/windows/windows-lifecycle-root-acl.test.ts -479 tests/windows/windows-native-principal.test.ts -724 tests/windows/windows-popup-fix.test.ts -142 tests/windows/windows-process-priority.test.ts +80469 tests/windows/windows-codex-cli-job-store.test.ts +108 tests/windows/windows-config-read-acl-memo.test.ts +19749 tests/windows/windows-config-root-async-writers.test.ts +80 tests/windows/windows-deploy-close-regressions.test.ts +4348 tests/windows/windows-elevation-spawn.test.ts +83 tests/windows/windows-elevation.test.ts +109 tests/windows/windows-guarded-manager.test.ts +222 tests/windows/windows-lifecycle-root-acl.test.ts +491 tests/windows/windows-native-principal.test.ts +713 tests/windows/windows-popup-fix.test.ts +79 tests/windows/windows-process-priority.test.ts 81 tests/windows/windows-scheduler-errors.test.ts -184 tests/windows/windows-scheduler-install-verification.test.ts -111 tests/windows/windows-secret-acl-diagnostics.test.ts +130 tests/windows/windows-scheduler-install-verification.test.ts +107 tests/windows/windows-secret-acl-diagnostics.test.ts 322 tests/windows/windows-secret-acl-removal-flight.test.ts -2314 tests/windows/windows-secret-acl.test.ts -110 tests/windows/windows-service-mutation-lock.test.ts -1567 tests/windows/windows-service-wrappers.test.ts -71 tests/windows/windows-text-decoding.test.ts -79 tests/windows/windows-tray-restart-hardening.test.ts -62 tests/windows/windows-tray-run-limit.test.ts -13171 tests/windows/windows-tray.test.ts -79 tests/windows/windows-user-principal-nonascii.test.ts -80 tests/windows/windows-user-principal.test.ts -47 tests/windows/winsw-stop-hardening.test.ts +2837 tests/windows/windows-secret-acl.test.ts +201 tests/windows/windows-service-mutation-lock.test.ts +1236 tests/windows/windows-service-wrappers.test.ts +63 tests/windows/windows-text-decoding.test.ts +209 tests/windows/windows-tray-restart-hardening.test.ts +58 tests/windows/windows-tray-run-limit.test.ts +12635 tests/windows/windows-tray.test.ts +181 tests/windows/windows-user-principal-nonascii.test.ts +126 tests/windows/windows-user-principal.test.ts +219 tests/windows/winsw-stop-hardening.test.ts diff --git a/src/link/remote-windows.ts b/src/link/remote-windows.ts index 510eecc157f..b93ff831c10 100644 --- a/src/link/remote-windows.ts +++ b/src/link/remote-windows.ts @@ -18,10 +18,16 @@ export function powershellArgv(script: string): string[] { export const WINDOWS_CONTAINMENT_EXIT = 126; const SCRIPT_PACKED_PREFIX = "$ocxPacked='"; -function packedPowerShellArgv(script: string): string[] { +/** + * The whole script travels deflated and is inflated on the Child before anything in it exists, + * including Fail. A session that cannot inflate it (Constrained Language Mode blocks the stream + * types) must still exit 126, so only the inflate is guarded: Invoke-Expression stays outside the + * try, and the inflated script's own errors and exit status are never relabelled as containment. + */ +export function packedPowerShellArgv(script: string): string[] { const bytes = deflateRawSync(Buffer.from(script, "utf8"), { level: 9 }); const packed = Array.from(bytes, byte => String.fromCharCode(byte + 256)).join(""); - return powershellArgv(`${SCRIPT_PACKED_PREFIX}${packed}'\n` + String.raw`$b=[byte[]]@($ocxPacked.ToCharArray()|%{[int]$_-256});$r=[IO.StreamReader]::new([IO.Compression.DeflateStream]::new([IO.MemoryStream]::new($b),[IO.Compression.CompressionMode]::Decompress));Invoke-Expression ($r.ReadToEnd())`); + return powershellArgv(`${SCRIPT_PACKED_PREFIX}${packed}'\n` + String.raw`$ErrorActionPreference='Stop';try{$b=[byte[]]@($ocxPacked.ToCharArray()|%{[int]$_-256});$r=[IO.StreamReader]::new([IO.Compression.DeflateStream]::new([IO.MemoryStream]::new($b),[IO.Compression.CompressionMode]::Decompress));$s=$r.ReadToEnd()}catch{try{[Console]::Error.WriteLine('Refusing to run ocx.exe outside a kill-on-close job.')}catch{$null=$_};exit ${WINDOWS_CONTAINMENT_EXIT}};Invoke-Expression $s`); } function unpackPowerShell(script: string): string { const match = /\$ocxPacked='([^']+)'/.exec(script); @@ -86,8 +92,8 @@ export const OCX_JOB_SOURCE = [ ].join("\n"); /** - * The helper travels deflated so the whole command fits cmd.exe's line; PowerShell inflates it and - * hands the text to Add-Type. It is never evaluated as PowerShell. + * The helper reaches Add-Type as a quoted literal inside the packed script; it is never evaluated + * as PowerShell. */ const NATIVE_PROCESS = String.raw`$ErrorActionPreference='Stop' function Fail{try{[Console]::Error.WriteLine('Refusing to run ocx.exe outside a kill-on-close job.')}catch{$null=$_};exit 126} diff --git a/structure/remote-link.md b/structure/remote-link.md index 511f913af6a..6276cd8cffd 100644 --- a/structure/remote-link.md +++ b/structure/remote-link.md @@ -6,7 +6,7 @@ `src/link/ssh-argv.ts` builds every OpenSSH argument vector. All commands run with BatchMode and trust only the link known_hosts file, keyed by `HostKeyAlias=`: the global file is disabled with `GlobalKnownHostsFile=none`, and `KnownHostsCommand=none`, `VerifyHostKeyDNS=no` and `CheckHostIP=no` shut out every other source of host-key trust. Command-line options take precedence over `~/.ssh/config`, so a user config cannot re-enable them. `HashKnownHosts=no` preserves alias-prefixed records in these private files without changing the user's normal known_hosts file. Tunnel and exec commands use `StrictHostKeyChecking=yes`; only the probe uses `accept-new`, against an empty temporary file, so an offered key can be shown before it is trusted. The known_hosts path must be absolute and free of ssh expansion syntax. Forwards bind 127.0.0.1 on both ends, and aliases that could be parsed as options are refused. -Every remote `ocx` call goes through `remoteOcxArgv` with the link's platform. On POSIX it is a quoted `sh -c` script that tries executable Desktop and system candidates before generic PATH shims: `$HOME/.opencodex-desktop/bin/ocx`, `/Applications/OpenCodex.app/Contents/MacOS/ocx`, `/usr/bin/ocx`, then inherited PATH plus Bun/local/Homebrew directories. Each candidate must successfully report `--version`; an unrunnable stale shim is skipped. Arguments remain quoted once. The script still exits 125 on a Windows/MSYS/Cygwin `uname`, a guard against POSIX dispatch to a Windows host; exhaustion exits 127 (`remote_ocx_missing`). On Windows, `src/link/remote-windows.ts` builds one `powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand` command whose arguments travel as base64 JSON data, never as shell text, and `quoteRemote` admits only that exact shape. The script tries the Desktop `ocx.exe`, the GOAT-managed `.local/share/goat/opencodex/current/ocx.exe` junction under the user profile, `.local/bin/ocx.exe`, the per-user and Program Files OpenCodex directories, then PATH. Each candidate must answer `--version` within ten seconds, and only the selected one runs the real command with CRT-quoted arguments and inherited standard handles, so the link key still arrives on stdin and the exit status passes through. A helper compiled with `Add-Type` (`OCX_JOB_SOURCE`, carried deflated so the command fits and inflated only into `Add-Type`) creates that process with `PROC_THREAD_ATTRIBUTE_JOB_LIST`, so it is a member of a Win32 Job with kill-on-close and silent breakaway from the moment it exists: terminating the PowerShell host, which is what the SSH server does with a dropped channel, kills that `ocx.exe`, while a runtime it starts on its own breaks away and survives. One finally block releases the attribute list and the process, thread and Job handles on every path and terminates the child through its own handle if anything fails after creation. If `Add-Type` or any step fails (Constrained Language Mode, for example), the command exits 126; there is no uncontained fallback. The encoded command stays under 8,000 characters for cmd.exe's 8,191-character command line. A dropped real OpenSSH channel is a required native release gate: the opt-in case in `tests/clients/link-ssh-argv-discovery.test.ts` runs against a disposable Windows OpenSSH host named by `OCX_WINDOWS_OPENSSH_FIXTURE`. Exhaustion exits 127. Coverage: `tests/clients/link-ssh-argv-discovery.test.ts`. +Every remote `ocx` call goes through `remoteOcxArgv` with the link's platform. On POSIX it is a quoted `sh -c` script that tries executable Desktop and system candidates before generic PATH shims: `$HOME/.opencodex-desktop/bin/ocx`, `/Applications/OpenCodex.app/Contents/MacOS/ocx`, `/usr/bin/ocx`, then inherited PATH plus Bun/local/Homebrew directories. Each candidate must successfully report `--version`; an unrunnable stale shim is skipped. Arguments remain quoted once. The script still exits 125 on a Windows/MSYS/Cygwin `uname`, a guard against POSIX dispatch to a Windows host; exhaustion exits 127 (`remote_ocx_missing`). On Windows, `src/link/remote-windows.ts` builds one `powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand` command whose arguments travel as base64 JSON data, never as shell text, and `quoteRemote` admits only that exact shape. The script tries the Desktop `ocx.exe`, the GOAT-managed `.local/share/goat/opencodex/current/ocx.exe` junction under the user profile, `.local/bin/ocx.exe`, the per-user and Program Files OpenCodex directories, then PATH. Each candidate must answer `--version` within ten seconds, and only the selected one runs the real command with CRT-quoted arguments and inherited standard handles, so the link key still arrives on stdin and the exit status passes through. The whole script travels deflated so the command fits, and the Child inflates it before anything in it runs. A helper compiled with `Add-Type` (`OCX_JOB_SOURCE`, a quoted literal inside that script, never evaluated as PowerShell) creates that process with `PROC_THREAD_ATTRIBUTE_JOB_LIST`, so it is a member of a Win32 Job with kill-on-close and silent breakaway from the moment it exists: terminating the PowerShell host, which is what the SSH server does with a dropped channel, kills that `ocx.exe`, while a runtime it starts on its own breaks away and survives. One finally block releases the attribute list and the process, thread and Job handles on every path and terminates the child through its own handle if anything fails after creation. If the inflation or `Add-Type` fails (Constrained Language Mode blocks both the stream types and `Add-Type`, for example), the command exits 126 before any `ocx.exe` is probed or started. A failure while the helper creates, waits on or reads the selected process also exits 126, after the finally block above has terminated that process. There is no uncontained fallback. The `--version` probes that choose a candidate run outside the Job, bounded to ten seconds each; only the selected command runs inside it. The inflation guard covers the inflation alone, so the exit status and errors of the inflated script itself pass through unchanged. The encoded command stays under 8,000 characters for cmd.exe's 8,191-character command line. A dropped real OpenSSH channel is a required native release gate: the opt-in case in `tests/clients/link-ssh-argv-discovery.test.ts` runs against a disposable Windows OpenSSH host named by `OCX_WINDOWS_OPENSSH_FIXTURE`. Exhaustion exits 127. Coverage: `tests/clients/link-ssh-argv-discovery.test.ts`. `src/link/remote-platform.ts` discovers the platform through the pinned host key: `requireRemotePlatform` runs the fixed, locale-independent `cmd /c echo %OS%` (`WINDOWS_OS_PROBE`), treats `Windows_NT` as Windows, and otherwise classifies `uname -s`. An ssh transport failure or an unclassifiable answer throws, so enrollment answers `probe_failed` before it trusts the host or issues a key. The first-contact probe runs the cross-shell `echo ocx-link-probe` and requires that exact output. The probe stores the platform on the pending host, confirmation and apply reuse it, and the link record keeps it as the optional `remotePlatform` in `src/link/store.ts`; a record written before the field existed is discovered again under its pinned key. On Windows, enrollment skips the curl preflight and reads the Child's loopback `/healthz` and `/v1/catalog` with a bounded .NET request that ignores proxies, never follows a redirect and caps the body at 4 MiB (`windowsChildHttpArgv`). Ordinary revoke, the Child-initiated issue and revoke in `src/client/link-join.ts` and `src/client/link-teardown.ts`, and the read-only `ocx link cleanup` in `src/cli/link-cleanup.ts` use the same adapter. Coverage: `tests/server/link-enrollment.test.ts`, `tests/server/link-management-routes.test.ts`, `tests/cli/cli-link-cleanup.test.ts`, `tests/clients/link-store.test.ts`. diff --git a/tests/cli/sync-command-fanout.test.ts b/tests/cli/sync-command-fanout.test.ts index bc2fada5127..c8b894cd259 100644 --- a/tests/cli/sync-command-fanout.test.ts +++ b/tests/cli/sync-command-fanout.test.ts @@ -1,8 +1,9 @@ import { expect, spyOn, test } from "bun:test"; -import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { delimiter, join } from "node:path"; import { tmpdir } from "node:os"; -import { repoPath } from "../helpers/repo-root"; +import { helperPath, repoPath } from "../helpers/repo-root"; +import { claimOwnedServiceHome, withOwnedServiceHomePreload } from "../helpers/owned-service-home"; import { parseSyncFanoutFlags } from "../../src/cli/sync-flags"; import { runSyncCommand } from "../../src/cli/sync-command"; import type { CliDispatchDeps } from "../../src/cli/dispatch"; @@ -10,6 +11,47 @@ import * as codexSync from "../../src/codex/sync"; import * as statusApi from "../../src/cli/sync-link-status"; import * as processApi from "../../src/cli/sync-fanout-process"; +const SSH_SENTINEL_PRELOAD = helperPath("ssh-spawn-sentinel-preload.ts"); +// Below the 15 s case budget, so a stalled child is reported with its stderr instead of a bare timeout. +const CHILD_TIMEOUT_MS = 12_000; + +/** + * The environment a real CLI child gets on every platform: the inherited one (Windows needs + * SystemRoot, PATHEXT and the rest), temp user and product homes, the owned-service-home fixture + * that isolates the Codex write admission probe from the runner's own service manager, the ssh + * sentinel marker, and `fixtureBin` ahead of PATH. Overrides replace inherited keys + * case-insensitively, so Windows never sees both `Path` and `PATH`. + */ +function cliChildEnv(temp: string, opencodexHome: string, codexHome: string, fixtureBin: string): Record { + const userHome = join(temp, "home"); + mkdirSync(userHome, { recursive: true }); + mkdirSync(opencodexHome, { recursive: true }); + const owned = claimOwnedServiceHome(codexHome, opencodexHome, userHome); + const overrides: Record = { + HOME: userHome, USERPROFILE: userHome, OPENCODEX_HOME: opencodexHome, CODEX_HOME: codexHome, ...owned.env, + PATH: [fixtureBin, owned.env.PATH ?? process.env.PATH ?? ""].filter(Boolean).join(delimiter), + OCX_TEST_SSH_SENTINEL: join(temp, "ssh-sentinel"), + }; + const replaced = new Set(Object.keys(overrides).map(key => key.toLowerCase())); + const inherited = Object.entries(process.env).filter((entry): entry is [string, string] => entry[1] !== undefined && !replaced.has(entry[0].toLowerCase())); + return { ...Object.fromEntries(inherited), ...overrides }; +} + +function cliChildArgv(args: readonly string[]): string[] { + return [process.execPath, ...withOwnedServiceHomePreload(["run", "--preload", SSH_SENTINEL_PRELOAD, ...args])]; +} + +async function runCliChild(argv: string[], env: Record): Promise<{ code: number; stdout: string; stderr: string }> { + const child = Bun.spawn(argv, { env, stdout: "pipe", stderr: "pipe", timeout: CHILD_TIMEOUT_MS }); + const [code, stdout, stderr] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + return { code, stdout, stderr }; +} + +function parseOneDocument(result: { code: number; stdout: string; stderr: string }): Record { + try { return JSON.parse(result.stdout) as Record; } + catch { throw new Error(`expected one JSON document on stdout; exit ${result.code}, stderr:\n${result.stderr}`); } +} + test.each(["--json", "--local-only"])("parser rejects repeated %s", flag => { expect(parseSyncFanoutFlags([flag, flag]).ok).toBe(false); }); @@ -47,21 +89,45 @@ test("local-only JSON does not invoke ssh", async () => { mkdirSync(linkDir, { recursive: true }); writeFileSync(join(home, "config.json"), JSON.stringify({ port: server.port, providers: {}, defaultProvider: "openai" })); writeFileSync(join(linkDir, "links.json"), JSON.stringify({ version: 1, listenerPort: 27000, links: [{ id: "lnk_0123456789abcdef", alias: "fake", direction: "hub-initiated", hostKeyFingerprint: "SHA256:AAAAAAAAAAAAAAAA", tunnelPort: 27001, apiKeyId: "test", createdAt: "2026-01-01T00:00:00Z" }] })); + // A second, POSIX-only check: Windows cannot execute this script, which is why the preload sentinel exists. writeFileSync(join(temp, "ssh"), `#!/bin/sh\nprintf called > '${join(temp, "ssh-called")}'\nexit 1\n`, { mode: 0o755 }); - const child = Bun.spawn([process.execPath, "run", repoPath("src/cli/index.ts"), "sync", "--local-only", "--json"], { - env: { HOME: temp, OPENCODEX_HOME: home, CODEX_HOME: join(temp, "codex"), PATH: `${temp}:/usr/bin:/bin` }, - stdout: "pipe", stderr: "pipe", - }); - const [code, stdout] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); - const document = JSON.parse(stdout); + const env = cliChildEnv(temp, home, join(temp, "codex"), temp); + const result = await runCliChild(cliChildArgv([repoPath("src/cli/index.ts"), "sync", "--local-only", "--json"]), env); + const document = parseOneDocument(result) as { schema: unknown; home: { exit: unknown }; fanout: unknown; children: unknown }; expect(document.schema).toBe("ocx.sync.fanout/1"); - expect(document.home.exit).toBe(code); + expect(document.home.exit).toBe(result.code); + // The Home step ran to the outcome this fixture is built for (Codex on, no Codex home yet), so + // the document is not the residue of an earlier, unexpected failure. + expect(document.home).toEqual({ state: "failed", exit: 1 }); + expect(result.stderr).toContain("does not exist yet, so there is no config.toml to route"); expect(document.fanout).toEqual({ state: "disabled", reason: null }); expect(document.children).toEqual([]); + expect(existsSync(env.OCX_TEST_SSH_SENTINEL!)).toBe(false); expect(existsSync(join(temp, "ssh-called"))).toBe(false); } finally { server.stop(true); rmSync(temp, { recursive: true, force: true }); } }, 15000); +test("the ssh sentinel stops both Bun spawn APIs and passes every other command through", async () => { + const temp = mkdtempSync(join(tmpdir(), "ocx-sync-sentinel-")); + try { + const script = join(temp, "control.ts"); + writeFileSync(script, [ + 'import { spawnSync } from "node:child_process";', + 'for (const start of [() => Bun.spawn(["ssh", "-V"]), () => Bun.spawnSync(["C:\\\\fixture\\\\SSH.EXE", "-V"])]) { try { start(); console.log("ssh-started"); } catch { /* the sentinel refused */ } }', + 'console.log(`passthrough ${Bun.spawnSync([process.execPath, "--version"]).exitCode}`);', + 'if (process.platform === "win32") console.log(`service ${spawnSync("schtasks.exe", ["/query", "/tn", "opencodex-proxy", "/xml"], { encoding: "buffer" }).stderr.toString()}`);', + ].join("\n")); + const env = cliChildEnv(temp, join(temp, "ocx"), join(temp, "codex"), temp); + const result = await runCliChild(cliChildArgv([script]), env); + expect(result.code).toBe(0); + expect(readFileSync(env.OCX_TEST_SSH_SENTINEL!, "utf8")).toBe("Bun.spawn ssh\nBun.spawnSync ssh.exe\n"); + expect(result.stdout).not.toContain("ssh-started"); + expect(result.stdout).toContain("passthrough 0"); + // The Windows service fixture still answers beside the sentinel, so the CLI cases keep both. + if (process.platform === "win32") expect(result.stdout).toContain("[OCX_TEST_SERVICE_HOME]"); + } finally { rmSync(temp, { recursive: true, force: true }); } +}, 15000); + test("human sync reports a damaged link store without exposing its path", async () => { const temp = mkdtempSync(join(tmpdir(), "ocx-sync-damaged-")); const server = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => new Response("not ocx", { status: 404 }) }); @@ -72,11 +138,7 @@ test("human sync reports a damaged link store without exposing its path", async writeFileSync(join(temp, "codex", "config.toml"), `model_catalog_json = ${JSON.stringify(join(temp, "missing-catalog.json"))}\n`); writeFileSync(join(home, "config.json"), JSON.stringify({ port: server.port, providers: {}, defaultProvider: "openai", clientIntegrations: { codex: false } })); writeFileSync(join(linkDir, "links.json"), "invalid"); - const child = Bun.spawn([process.execPath, "run", repoPath("src/cli/index.ts"), "sync"], { - env: { HOME: temp, OPENCODEX_HOME: home, CODEX_HOME: join(temp, "codex"), PATH: `${temp}:/usr/bin:/bin` }, - stdout: "pipe", stderr: "pipe", - }); - const [code, stdout, stderr] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + const { code, stdout, stderr } = await runCliChild(cliChildArgv([repoPath("src/cli/index.ts"), "sync"]), cliChildEnv(temp, home, join(temp, "codex"), temp)); expect(code).toBe(6); expect(stderr).toContain("Children were not synced: the Remote Link store could not be read."); expect(stderr).not.toContain(join(linkDir, "links.json")); @@ -190,3 +252,37 @@ test("fan-out discovers unstored platforms despite shell startup output", async process.exitCode = previousExit ?? 0; rmSync(temp, { recursive: true, force: true }); } }); + +test("local-only never reads link status or starts a Child process, even when fan-out would run", async () => { + const temp = mkdtempSync(join(tmpdir(), "ocx-sync-local-inprocess-")); + const previousHome = process.env.OPENCODEX_HOME, previousExit = process.exitCode; + process.env.OPENCODEX_HOME = temp; process.exitCode = 0; + const linkDir = join(temp, "link"); mkdirSync(linkDir, { recursive: true }); + const link = { id: "lnk_0123456789abcdef", alias: "fake", direction: "hub-initiated" as const, hostKeyFingerprint: "SHA256:AAAAAAAAAAAAAAAA", tunnelPort: 27001, apiKeyId: "test", createdAt: "2026-01-01T00:00:00Z", remotePlatform: "windows" as const }; + writeFileSync(join(temp, "config.json"), JSON.stringify({ providers: {}, defaultProvider: "openai" })); + writeFileSync(join(linkDir, "links.json"), JSON.stringify({ version: 1, listenerPort: 27000, links: [link] })); + const base = { status: "catalog-only" as const, ok: true, added: 0, catalogPath: "fixture", catalogExists: true, catalogWritten: false, cacheSynced: false, message: "done", refreshOutcome: "committed" as const }; + const calls: string[] = [], output: string[] = []; + const sync = spyOn(codexSync, "syncModelsToCodex").mockImplementation(async () => { calls.push("home"); return base; }); + const status = spyOn(statusApi, "readHomeLinkStatus").mockImplementation(async () => { calls.push("status"); return { role: "home", listener: { state: "listening", port: 27000 }, child: null, links: [{ ...link, state: "connected", since: link.createdAt, reason: null, lastApplyAt: null, runtimeStartedAt: null, appliedCodexSettingsDigest: null }] }; }); + const runner = spyOn(processApi, "fanoutSshRunner").mockImplementation(() => { calls.push("ssh-runner"); return { run: async () => ({ code: 255, stdout: "", stderr: "" }) }; }); + const child = spyOn(processApi, "runFanoutProcess").mockImplementation(async () => { calls.push("child"); return { code: 255, stdout: "", stderr: "" }; }); + const log = spyOn(console, "log").mockImplementation((...parts) => { output.push(parts.map(String).join(" ")); }); + const error = spyOn(console, "error").mockImplementation(() => {}); + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + const deps = { findLiveProxy: async () => null } as unknown as CliDispatchDeps; + // The same Home result and store fan out without --local-only, so the spies can be reached. + expect(await runSyncCommand({ ...deps, args: ["sync", "--json"] })).toBe(6); + expect(calls).toEqual(["home", "status", "ssh-runner", "child"]); + calls.length = 0; output.length = 0; + expect(await runSyncCommand({ ...deps, args: ["sync", "--local-only", "--json"] })).toBe(0); + expect(calls).toEqual(["home"]); + expect(output).toHaveLength(1); + expect(JSON.parse(output[0]!)).toEqual({ schema: "ocx.sync.fanout/1", home: { state: "synced", exit: 0 }, fanout: { state: "disabled", reason: null }, children: [] }); + } finally { + sync.mockRestore(); status.mockRestore(); runner.mockRestore(); child.mockRestore(); log.mockRestore(); error.mockRestore(); warn.mockRestore(); + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previousHome; + process.exitCode = previousExit ?? 0; rmSync(temp, { recursive: true, force: true }); + } +}); diff --git a/tests/clients/link-pinned-sync-argv.test.ts b/tests/clients/link-pinned-sync-argv.test.ts index bceddea2891..53187a5111c 100644 --- a/tests/clients/link-pinned-sync-argv.test.ts +++ b/tests/clients/link-pinned-sync-argv.test.ts @@ -175,10 +175,18 @@ test.skipIf(process.platform === "win32")("a version writer ignoring signals is mkdirSync(desktop, { recursive: true }); writeFileSync(join(desktop, "ocx"), '#!/bin/sh\nprintf "%s" $$ > "$HOME/writer.pid"\ntrap "" PIPE XFSZ\nwhile :; do printf "01234567890123456789"; done\n', { mode: 0o755 }); writeFileSync(join(bin, "ocx"), '#!/bin/sh\nif [ "$1" = --version ]; then echo 2.93.0; else echo synced; fi\n', { mode: 0o755 }); - const child = Bun.spawn(isolatedArgv(), { env: { HOME: home, OPENCODEX_HOME: join(home, "ocx-home"), CODEX_HOME: join(home, "codex-home"), TMPDIR: home, PATH: bin }, stdout: "pipe", stderr: "pipe" }); + // The kill path is the subject here, not the ten-second budget: run the same script with a one-second + // watchdog, and keep the shipped budget pinned so a shortened production deadline still fails. + const argv = isolatedArgv(); + expect(argv[2]!.split("( sleep 10 & timer=$!;").length).toBe(2); + argv[2] = argv[2]!.replace("( sleep 10 & timer=$!;", "( sleep 1 & timer=$!;"); + const started = Date.now(); + const child = Bun.spawn(argv, { env: { HOME: home, OPENCODEX_HOME: join(home, "ocx-home"), CODEX_HOME: join(home, "codex-home"), TMPDIR: home, PATH: bin }, stdout: "pipe", stderr: "pipe" }); const [code, stdout, stderr] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); expect({ code, stderr }).toEqual({ code: 0, stderr: "ocx-fanout:selected:2.93.0\n" }); expect(stdout).toBe("ocx-fanout:stdout-begin\nsynced\n"); + // The writer was stopped by the watchdog, not by finishing early. + expect(Date.now() - started).toBeGreaterThanOrEqual(1000); const pid = Number(readFileSync(join(home, "writer.pid"), "utf8")); expect(() => process.kill(pid, 0)).toThrow(); expect(readdirSync(home).filter(name => name.startsWith("ocx-fanout."))).toEqual([]); diff --git a/tests/clients/link-ssh-argv-discovery.test.ts b/tests/clients/link-ssh-argv-discovery.test.ts index c7cd25196a0..37c302e709c 100644 --- a/tests/clients/link-ssh-argv-discovery.test.ts +++ b/tests/clients/link-ssh-argv-discovery.test.ts @@ -2,7 +2,7 @@ import { afterEach, expect, test } from "bun:test"; import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; -import { windowsOcxArgv, windowsNativeArgv, windowsChildHttpArgv, powershellArgv, windowsScriptData, windowsScriptHelperSource, OCX_JOB_SOURCE, WINDOWS_CONTAINMENT_EXIT } from "../../src/link/remote-windows"; +import { windowsOcxArgv, windowsNativeArgv, windowsChildHttpArgv, windowsPinnedSyncArgv, packedPowerShellArgv, powershellArgv, windowsScriptData, windowsScriptHelperSource, OCX_JOB_SOURCE, WINDOWS_CONTAINMENT_EXIT } from "../../src/link/remote-windows"; import { quoteRemote, REMOTE_OCX_SCRIPT, remoteOcxArgv } from "../../src/link/ssh-argv"; import { removeTreeWithRetry } from "../helpers/remove-tree"; import { spawnTestChild } from "../helpers/spawn-test-child"; @@ -227,6 +227,37 @@ test.skipIf(process.platform !== "win32")("a Windows ocx that cannot be containe expect(existsSync(marker)).toBe(false); }, SPAWN_BUDGET_MS); +// Every packed command inflates itself before its containment helper exists; a session that cannot +// inflate must still refuse with 126. The candidate homes and PATH hold no ocx.exe, so 126 can only +// be that refusal: an unguarded inflate exits 1 and exhausted discovery exits 127. +for (const [name, build] of [ + ["discovery", () => windowsOcxArgv(["--version"])], + ["pinned sync", () => windowsPinnedSyncArgv("lnk_0123456789abcdef")], +] as const) { + test.skipIf(process.platform !== "win32")(`a Windows ${name} command that cannot be contained is refused before any candidate is probed`, async () => { + const empty = mkdtempSync(join(tmpdir(), "ocx-windows-refuse-candidates-")); roots.push(empty); + const system32 = join(process.env.SystemRoot ?? "C:\\Windows", "System32"); + const isolated = new Set(["path", "userprofile", "localappdata", "programfiles"]); + const env: Record = {}; + for (const [key, value] of Object.entries(process.env)) if (value !== undefined && !isolated.has(key.toLowerCase())) env[key] = value; + Object.assign(env, { PATH: system32, USERPROFILE: empty, LOCALAPPDATA: empty, ProgramFiles: empty }); + const constrained = powershellArgv("$ExecutionContext.SessionState.LanguageMode='ConstrainedLanguage'\n" + Buffer.from(build().at(-1)!, "base64").toString("utf16le")); + const child = Bun.spawn([join(system32, "WindowsPowerShell", "v1.0", "powershell.exe"), ...constrained.slice(1)], { env, stdin: "ignore", stdout: "pipe", stderr: "pipe" }); + const [code] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + expect(code).toBe(WINDOWS_CONTAINMENT_EXIT); + }, SPAWN_BUDGET_MS); +} + +// The guard covers the inflation alone: an error the inflated script raises itself keeps its own +// failure and is never reported as a containment refusal. +test.skipIf(process.platform !== "win32")("an inflated script's own error is not relabelled as a containment refusal", async () => { + const child = Bun.spawn(packedPowerShellArgv("throw 'ocx-post-inflate-error'\n"), { stdin: "ignore", stdout: "pipe", stderr: "pipe" }); + const [code, , stderr] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); + expect(code).not.toBe(WINDOWS_CONTAINMENT_EXIT); + expect(code).toBe(1); + expect(stderr).toContain("ocx-post-inflate-error"); +}, SPAWN_BUDGET_MS); + // Required native release gate: set OCX_WINDOWS_OPENSSH_FIXTURE to a key-authenticated SSH alias of a // disposable Windows x64 OpenSSH host (cmd.exe or PowerShell default shell). Never a real user host. const OPENSSH_FIXTURE = process.env.OCX_WINDOWS_OPENSSH_FIXTURE; diff --git a/tests/helpers/ssh-spawn-sentinel-preload.ts b/tests/helpers/ssh-spawn-sentinel-preload.ts new file mode 100644 index 00000000000..718f207f8c0 --- /dev/null +++ b/tests/helpers/ssh-spawn-sentinel-preload.ts @@ -0,0 +1,39 @@ +/** + * Test-only ssh sentinel for CLI children. + * + * A PATH fixture cannot prove that a CLI child never starts ssh on every platform: Windows does + * not run an extensionless `#!/bin/sh` script, and an inherited PATH can reach the runner's real + * ssh.exe. This preload wraps exactly the APIs Remote Link fan-out uses to start ssh, + * `Bun.spawn` and `Bun.spawnSync`. An argv whose executable basename is `ssh` or `ssh.exe` + * appends `Bun. ` to the marker named by OCX_TEST_SSH_SENTINEL and throws, so it + * never runs. Every other call passes through unchanged. + * + * It leaves `node:child_process` alone, so it composes with owned-service-home-preload.ts, which + * mocks that module on Windows. No production module reads the flag or imports this file. + */ +import { appendFileSync } from "node:fs"; + +const marker = process.env.OCX_TEST_SSH_SENTINEL; + +function sshBasename(input: unknown): string | null { + const cmd = Array.isArray(input) ? input + : input !== null && typeof input === "object" && Array.isArray((input as { cmd?: unknown }).cmd) ? (input as { cmd: unknown[] }).cmd + : null; + const first = cmd?.[0]; + if (typeof first !== "string") return null; + const base = (first.split(/[\\/]/).pop() ?? "").toLowerCase(); + return base === "ssh" || base === "ssh.exe" ? base : null; +} + +if (marker) { + const target = Bun as unknown as Record<"spawn" | "spawnSync", (...args: unknown[]) => unknown>; + for (const api of ["spawn", "spawnSync"] as const) { + const real = target[api]; + target[api] = (...args: unknown[]) => { + const ssh = sshBasename(args[0]); + if (ssh === null) return real.apply(Bun, args); + appendFileSync(marker, `Bun.${api} ${ssh}\n`); + throw new Error(`ssh sentinel: Bun.${api} ${ssh} was not started`); + }; + } +} From 6f915d865f457f84703d4a3102dbbc2228ae9aae Mon Sep 17 00:00:00 2001 From: JUN Date: Tue, 3 Nov 2026 09:14:07 +0900 Subject: [PATCH 13/43] fix(ci): make the Windows batch shards green after #8103 (#8109) * fix(ci): make the Windows batch shards green after #8103 Run 41491122166 left four Windows shards red; dev was green on all eleven in 41262132337 before #8103. - update-orchestrated-identity: the fixture used POSIX paths that are not native on win32. The product also rejected a Windows source path written with '/' separators, so a live install could read as unknown; win32 now equates only the separators (dotted, doubled and wrong-suffix forms still fail closed). - update-bun-ownership-lease: the fixture did not recognize the Windows installer bridge (runWindowsInstallerSync) that #8103 introduced, so it answered unconfirmed and the updater kept its fence. - claude-intercept-acl-barrier: stub the PowerShell owner-ACL probe like the writer-barrier suite, so a slow cold probe cannot use up the 1 s ACL budget before the mocked icacls runs. - update-mutation-guard (windows 9/11): this lint runs only on Windows, where Bun can start the TypeScript sync client, so #8103 landed with 1258 unreviewed findings. Review every #8103 site into the existing tables plus two orchestrated-module sidecars; accept exit 10 only for the exact enterMutation refusal branch, with mutants; orchestrated-entry launches its child through probeSpawn, as job.ts does. - Windows durations refreshed from runs 41491122166 and 41462914814. - storage-policy and lab-read-surfaces left unfinalized prepared statements that keep SQLite files open, so each Windows afterEach removal waited its 15 s retry budget (about 210 s per run) and leaked the home. Plan and evidence: devlog/_plan/261103_windows_batch_shards/010_plan.md * test(update): reject relaxed mutation-entry refusal shapes Add mutants for an unawaited or different initializer, an inverted entered.ok predicate and an else branch (CodeRabbit review). * test(update): pin the deferred-import admission fixture to runUpdateWithSession #8103 moved the three reviewed guardedStartWindowsTray deferred imports from runUpdate into runUpdateWithSession, and the policy table follows the code. The fixture now uses that context; the fourth binding, raw namespace, unreviewed binding and other-context cases stay rejected. Windows-only lint; reproduced and verified under Node. * fix(update): hand the orchestrated child a parent-issued result channel The orchestrated update child now writes its outcome records only into a result file its parent created for it. The parent creates a fresh temp directory holding one exclusively created capability file and passes the token in OCX_UPDATE_RESULT_CAPABILITY. Before any session write, mutex use or identity probe, the child accepts only a canonical, single-link, non-symlink regular file (owner-only on POSIX) whose size and entire content equal that capability document, then publishes every record through the descriptor it validated (truncate, then write at explicit offsets). The parent reads, unlinks and non-recursively removes only the file and directory identities it recorded, and bounds the record size. Update-lint rows are re-reviewed for the new sites, and the POSIX supervisor and marker rows now state only what the code enforces. Tests cover rejected destinations left byte-identical, a path swap after validation, interrupted and oversized records classifying as uncertain, identity-bound cleanup, and real Bun and Node parent-to-child handoffs under a symlinked temp root. * fix(update): compare result-channel file identity with BigInt stats NTFS and ReFS file ids can exceed Number.MAX_SAFE_INTEGER; every identity-bearing lstat/fstat in the result channel and destination validation now uses { bigint: true } (CodeRabbit review). * fix(update): scope the result handoff token and channel cleanup Remove the result capability from the parsed environment so probes and installers never inherit it; the Node launcher passes it only to the Bun process continuing the same child. Channel cleanup removes by path only on POSIX with non-replaceable ancestors, and otherwise leaves the channel. Cover symlinked and junction destinations in both Node and Bun. * test(update): qualify result channel and marker review rows State that cleanup identity checks precede path-based removal on POSIX only, and that marker publication assumes the OpenCodex home cannot be replaced. --- bin/ocx.mjs | 4 +- .../261103_windows_batch_shards/010_plan.md | 64 + scripts/ci/test-durations.windows.tsv | 5046 +++++++++-------- src/update/index.ts | 2 +- src/update/orchestrated-arguments.d.mts | 2 +- src/update/orchestrated-arguments.mjs | 10 +- src/update/orchestrated-entry.ts | 22 +- src/update/orchestrated-identity.ts | 4 +- src/update/orchestrated-node-driver.mjs | 20 +- src/update/orchestrated-session.d.mts | 10 + src/update/orchestrated-session.mjs | 144 +- structure/ops/service-and-sidecars.md | 2 +- structure/ops/update-supervised-recovery.md | 8 +- .../claude-intercept-acl-barrier.test.ts | 5 + .../cli/ocx-launcher-desktop-handoff.test.ts | 8 +- .../codex-shim-autorestore.test.ts | 20 +- tests/helpers/update-bun-ownership-child.ts | 18 +- .../update-helper-control-contracts.ts | 26 +- tests/helpers/update-import-policy.ts | 91 +- tests/helpers/update-mutation-scanner.ts | 19 +- tests/helpers/update-primitive-allowlist.ts | 38 +- tests/helpers/update-process-allowlist.ts | 29 +- .../update-review-orchestrated-child.ts | 109 + .../update-review-orchestrated-entry.ts | 86 + tests/helpers/update-review-table.ts | 24 + tests/lab/lab-read-surfaces.test.ts | 11 +- tests/storage/storage-policy.test.ts | 3 + tests/update/update-capability-policy.test.ts | 4 +- tests/update/update-mutation-scanner.test.ts | 19 + .../update-orchestrated-arguments.test.ts | 17 +- .../update/update-orchestrated-entry.test.ts | 55 +- .../update-orchestrated-identity.test.ts | 22 +- tests/update/update-orchestrated-plan.test.ts | 4 +- .../update-orchestrated-session.test.ts | 169 +- 34 files changed, 3480 insertions(+), 2635 deletions(-) create mode 100644 devlog/_plan/261103_windows_batch_shards/010_plan.md create mode 100644 tests/helpers/update-review-orchestrated-child.ts create mode 100644 tests/helpers/update-review-orchestrated-entry.ts create mode 100644 tests/helpers/update-review-table.ts diff --git a/bin/ocx.mjs b/bin/ocx.mjs index 0bebcf274c0..7c69900a36e 100755 --- a/bin/ocx.mjs +++ b/bin/ocx.mjs @@ -244,7 +244,7 @@ async function runPackageManagerSelfUpdate(manager, child) { if (child) { try { const expected = decodeOrchestratedExpect(child.expect); - session = createOrchestratedChildSession({ home: configDir(), resultPath: child.resultPath, expect: expected, + session = createOrchestratedChildSession({ home: configDir(), resultPath: child.resultPath, resultCapability: child.resultCapability, expect: expected, notAfter: child.notAfter, verifyIdentity: () => { const bun = resolveBun({ allowInstall: false, allowMissing: true }); if (!bun) return false; @@ -1401,6 +1401,8 @@ if (codexCliUpdateInspection && typeof process.versions.bun === "string") { const { launchProof, launchContext, inheritedEnv } = createNodeLaunchContext(); delete inheritedEnv.OCX_SYNC_MUTEX_HELD_BY; +// The parsed child capability was removed from process.env; only the Bun CLI handoff of this same child receives it. +if (childArgs?.ok) inheritedEnv.OCX_UPDATE_RESULT_CAPABILITY = childArgs.resultCapability; const desktopPlan = planDesktopCliHandoff({ selfPaths: [fileURLToPath(import.meta.url), process.execPath] }); if (desktopPlan.kind === "error") { if (desktopPlan.issue.startsWith("record-")) { diff --git a/devlog/_plan/261103_windows_batch_shards/010_plan.md b/devlog/_plan/261103_windows_batch_shards/010_plan.md new file mode 100644 index 00000000000..db205b13790 --- /dev/null +++ b/devlog/_plan/261103_windows_batch_shards/010_plan.md @@ -0,0 +1,64 @@ +# Windows batch shards green after #8103/#8104 (dev @ 43e2e4e57) + +Run [41491122166](https://github.com/lidge-jun/opencodex/actions/runs/41491122166) (head 1800b4d7f = dev with #8103, #8104, #8106) left four Windows shards red. The previous full Windows run on dev, 41262132337, was green on all eleven shards, and its head is an ancestor of #8103's parent. Every failure below traces to #8103 (4d93716dd) or to a test fixture that depends on Windows runner timing. None is caused by #8106. + +## Findings + +| Shard | Failing file | Root cause | Side to fix | +|---|---|---|---| +| windows 10/11 | tests/update/update-orchestrated-identity.test.ts "identity requires a stable, attested runtime record" | The fixture uses POSIX paths (`/fixture/install/src/cli/index.ts`). On win32, `dirname` three times gives `/fixture/install`, and `join(root, "src", "cli", "index.ts")` rebuilds it with backslashes, so the equality check in src/update/orchestrated-identity.ts fails and the function correctly fails closed to `unknown`. Real records come from `currentServingCommand()` (src/config/serving-runtimes.ts), which uses `process.execPath` and `process.argv[1]` and joins relative parts with `node:path`, so they are native whenever Bun reports `process.argv[1]` natively; nothing forces that, which is why T1 also fixes the product. The real-listener case in the same file passed on Windows. Reproduced with `path.win32` in .tmp/research/win32-identity.ts. | Fixture is POSIX-only. The product also compares separators too strictly: `selfLaunchArgv` passes `process.argv[1]` through unchanged, and `currentServingCommand` keeps any absolute part as given, so a valid Windows path written with `/` would make a live install read as `unknown` (fail closed, but wrong). Fixed on both sides. | +| windows 7/11 | tests/update/update-bun-ownership-lease.test.ts (6 cases: home-unknown, home-unknown-fail, parent-package-only, parent-package-only-result, delegated-unknown-unknown, delegated-post-replacement) | #8103 routes the Windows Bun package replacement through `runWindowsInstallerSync` (src/update/npm-install.mjs). That spawns `process.execPath --input-type=module -e