From 27a57ac6ab7053cc6138433b25b3104ab03fee61 Mon Sep 17 00:00:00 2001 From: Reidar Date: Thu, 12 Nov 2026 07:46:22 +0100 Subject: [PATCH 01/11] fix(responses): infer phases from terminal snapshot tool work --- .../es/reference/configuration/providers.md | 2 +- .../docs/reference/configuration/providers.md | 2 +- src/server/responses-phase-inference.ts | 35 ++++++++++++--- structure/transports/responses.md | 2 +- .../responses-phase-inference.test.ts | 44 +++++++++++++++++++ 5 files changed, 75 insertions(+), 10 deletions(-) diff --git a/docs-site/src/content/docs/es/reference/configuration/providers.md b/docs-site/src/content/docs/es/reference/configuration/providers.md index 999c610f6a7..8a6784e5528 100644 --- a/docs-site/src/content/docs/es/reference/configuration/providers.md +++ b/docs-site/src/content/docs/es/reference/configuration/providers.md @@ -308,7 +308,7 @@ Los proveedores pueden exponer una abreviatura incorporada, como `agy` para `goo | `terminalContinuationGuard?` | `boolean` | Opte por un proveedor `openai-chat` a una re-pregunta interna limitada cuando un giro accionable anuncia el trabajo, luego se detiene limpiamente sin una llamada de herramienta. Por defecto a `false`; explícito `false` se comporta como omisión. Se excluyen los intentos combinados y los giros de compactación enrutados, y los adaptadores que no son `openai-chat` ignoran esta opción. | | `responsesItemIdRepair?` | `{ message?: string[]; reasoning?: string[]; repairMissingTerminalIds?: boolean; repairInvalidIds?: boolean }` | Deshabilitado por defecto aguas abajo SSE reparación para ids de marcador de posición exacto, ids de terminal faltantes, y (con `repairInvalidIds` ) mensaje / ids de razonamiento faltantes el prefijo canónico `msg_` / `rs_`. Los identificadores de llamada de función nunca se reescriben. El DeepSeek incorporado habilita los dos últimos por defecto. | | `responsesSnapshotRepair?` | `boolean` | Deshabilitado por defecto de cara al cliente de reparación para escasa Responses instantáneas del ciclo de vida en SSE y JSON. Rellena el estado canónico faltante, la salida y los metadatos de la herramienta, mientras que la inspección en bruto y la persistencia permanecen sin cambios. | -| `messagePhaseInference?` | `boolean` | Desactivado por defecto. En streams Responses de paso directo, infiere las fases de mensaje ausentes al completarlo: otro evento de protocolo posterior determina `commentary`; un evento terminal o `[DONE]`, `final_answer`. Conserva las fases explícitas commentary/final_answer; infiere valores nulos o desconocidos igual que los ausentes. Los keepalives no determinan la fase. Las instantáneas completed/incomplete reutilizan la decisión por elemento si no tienen fase. El texto se sigue transmitiendo mientras la finalización del mensaje espera su clasificación. El estado retenido usa el presupuesto de traducción de la solicitud. También se aplica al JSON reconstruido desde SSE del proveedor; el JSON ordinario del proveedor no cambia. | +| `messagePhaseInference?` | `boolean` | Desactivado por defecto. En streams Responses de paso directo, infiere las fases de mensaje ausentes al completarlo: otro evento de protocolo posterior determina `commentary`; si se omitieron los eventos de elementos, las llamadas a herramientas que aparecen después del mensaje en una instantánea completed/incomplete también determinan `commentary`; en los demás casos, un evento terminal o `[DONE]` determina `final_answer`. Conserva las fases explícitas commentary/final_answer; infiere valores nulos o desconocidos igual que los ausentes. Los keepalives no determinan la fase. Las instantáneas completed/incomplete reutilizan la decisión por elemento si no tienen fase. El texto se sigue transmitiendo mientras la finalización del mensaje espera su clasificación. El estado retenido usa el presupuesto de traducción de la solicitud. También se aplica al JSON reconstruido desde SSE del proveedor; el JSON ordinario del proveedor no cambia. | | `estimateMissingUsage?` | `boolean` | Desactivado por defecto. En una ruta Responses nativa (`openai-responses`) cuyo proveedor envía una respuesta completada sin `usage`, añade una estimación para que un cliente como Codex mantenga su medidor de contexto: `input_tokens` se estima a partir de la solicitud y `output_tokens` a partir de la salida de la propia respuesta. El uso que envía el proveedor nunca se modifica. Las respuestas con una estimación llevan la cabecera `x-opencodex-usage-estimated`: `true` en una respuesta JSON cuyo uso se estimó, `when-missing` en un stream, donde se estima cualquier uso que el proveedor omitió. Las estimaciones son solo para mostrar: el historial de solicitudes, el coste, los límites de gasto y la cuota de OpenCodex siguen leyendo las cifras del propio proveedor. Esto también se aplica a las rutas Combo: si el proveedor omite el uso, la reserva de gasto sigue sin resolverse, incluso si todos los destinos agotan el límite de salida sin producir contenido. El uso real sigue siendo la fuente válida aunque llegue después de que empiece la salida del stream o después de que Combo envíe keepalives mientras selecciona un destino. Solo se estiman las solicitudes HTTP Responses (`/v1/responses`): los puentes Chat Completions (`/v1/chat/completions`) y Claude Messages (`/v1/messages`), el transporte WebSocket y las llamadas de decisión internas de OpenCodex nunca reciben una estimación, porque reconstruyen el uso a partir de la respuesta o liquidan el gasto con ella. Una instancia de OpenCodex que consume este proxy como proveedor `openai-responses` no lee `x-opencodex-usage-estimated` y registraría la estimación como uso informado, así que deja `estimateMissingUsage` desactivado en un proxy detrás del cual haya otro OpenCodex. | | `webSearchBridge?` | `{ enabled?: boolean; backend?: "ollama" \| "openai" \| "anthropic" \| "xai" \| "gemini" \| "exa"; maxSearches?: number; timeoutMs?: number; endpoint?: string }` | Key-auth `openai-responses` solo proveedores de pases. Desactivado por defecto. Codex siempre declara la herramienta `web_search` alojada, y el paso a través la retransmite en el supuesto de que el destino la ejecute. Una puerta de enlace que no ejecuta respuestas de búsqueda alojadas con un `function_call` llamado `web_search` que no se ejecuta, y el guardia de herramientas no declaradas termina el turno. Con `enabled: true` y un `backend` OpenCodex explícito intercepta esa llamada, ejecuta la búsqueda en sí misma, devuelve el resultado al mismo flujo ascendente y muestra Codex una celda `web_search_call` alojada. Nunca armado para `authMode: "forward"` (ChatGPT ya busca) o para un proveedor que ejecuta la búsqueda alojada aguas arriba. `backend` es necesario; no hay un valor predeterminado implícito y una credencial faltante para el backend nombrado deja el puente desarmado en lugar de caer a través de otra búsqueda pagada. `ollama` reutiliza la tecla API de este proveedor en `POST /api/web_search`, por lo que el origen debe ser `https://ollama.com` a menos que el operador nombre `endpoint` explícitamente. `openai` / `anthropic` / `xai` / `gemini` / `exa` reutilizar el ejecutor sidecar coincidente y que propia credencial del ejecutor (`webSearchSidecar.exaApiKey` para Exa). El modelo de búsqueda viene de `webSearchSidecar.model` solo cuando `webSearchSidecar.backend` resuelve el mismo nombre de este puente; de lo contrario, el puente ejecuta el propio valor predeterminado de ese backend, porque un modelo elegido para un proveedor es rechazado por otro. Un unset `webSearchSidecar.backend` resuelve a `openai`, así que un modelo unset-backend alcanza un puente `openai` y ningún otro. No hay anulación del modelo de puente por proveedor. Streaming de giros solamente. Un turno que mezcla `web_search` con otra llamada de herramienta de cliente aún falla en cerrar en lugar de dejar caer la llamada del cliente. No se ejecuta texto auxiliar como prosa XML-like ``. Valores predeterminados: `maxSearches: 3` (1..10), `timeoutMs: 60000` (1000..600000). | | `retryOn429?` | `{ enabled?: boolean; attempts?: number; intervalMs?: number; maxIntervalMs?: number; respectRetryAfter?: boolean }` | Solo proveedores con clave API (`authMode: "key"`). Reintenta el mismo destino ante un 429. Ausente significa desactivado, salvo OpenCode Go y Command Code oficiales con clave, y Mistral `openai-chat` oficial: usan seis repeticiones, intervalo de diez segundos y límite de espera de 60 segundos. El objeto habilita la opción salvo `enabled: false`, que también desactiva esos valores especiales. Ante un 429, espera `Retry-After` o el intervalo fijo y repite la misma solicitud con la misma clave antes de cambiarla, en el bucle principal de texto, paso directo de Responses, puentes de imágenes y video, sidecar de búsqueda y continuaciones finales. Solo admite HTTP 429 antes del streaming; los transportes `runTurn` personalizados quedan fuera. `attempts` cuenta las repeticiones tras el primer 429: envíos totales = `attempts` + 1. Es un presupuesto compartido por toda la solicitud. Agotarlo detiene esas repeticiones; se aplica después el cambio de clave o el error final según los destinos disponibles. El paso directo autenticado con clave no cambia de destino y devuelve el 429. Para Mistral Chat oficial, un plazo explícito superior al permitido detiene la repetición con esa clave, aunque otra del grupo todavía puede servir, y devuelve el `Retry-After` original. Otros proveedores mantienen la espera acotada. Mistral comparte plazos por credencial y modelo salvo `requestPacing.enabled: false` o `retryOn429.respectRetryAfter: false`. Un 429 con presión válida sobre el presupuesto por minuto y sin plazo activa una espera conservadora de 60 segundos y después una sola consulta de prueba; si funciona, vuelve el tráfico normal. El tráfico correcto no predice el costo de la consulta siguiente. La política usa los límites anunciados, excluye cuotas mensuales conocidas como agotadas, no afirma una hora exacta de restablecimiento y nunca inicia compactación. Codex no reintenta por sí mismo los 429. Valores predeterminados: `enabled: true`, `attempts: 3`, `intervalMs: 5000`, `maxIntervalMs: 60000` (cada espera se limita a `maxIntervalMs`, acotado a 600000), `respectRetryAfter: true`. | diff --git a/docs-site/src/content/docs/reference/configuration/providers.md b/docs-site/src/content/docs/reference/configuration/providers.md index bbe26723c45..d0ca4ddd5a2 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -431,7 +431,7 @@ Providers can expose a built-in shorthand, such as `agy` for `google-antigravity | `terminalContinuationGuard?` | `boolean` | Opt in an `openai-chat` provider to one bounded internal re-ask when an actionable turn announces work, then cleanly stops without a tool call. Defaults to `false`; explicit `false` behaves like omission. Combo attempts and routed compaction turns are excluded, and non-`openai-chat` adapters ignore this option. | | `responsesItemIdRepair?` | `{ message?: string[]; reasoning?: string[]; repairMissingTerminalIds?: boolean; repairInvalidIds?: boolean }` | Disabled-by-default downstream SSE repair for exact placeholder ids, missing terminal ids, and (with `repairInvalidIds`) message/reasoning ids missing the canonical `msg_`/`rs_` prefix. Function-call ids are never rewritten. Built-in DeepSeek enables the last two by default. | | `responsesSnapshotRepair?` | `boolean` | Disabled-by-default client-facing repair for sparse Responses lifecycle snapshots in SSE and JSON. Fills missing canonical status, output, and tool metadata while raw inspection and persistence remain unchanged. | -| `messagePhaseInference?` | `boolean` | Off by default. For Responses passthrough streams, infer missing message phases at completion: a subsequent protocol event yields `commentary`; a terminal event or `[DONE]` yields `final_answer`. Explicit commentary/final_answer phases are preserved (null or unknown values are inferred like missing ones), keepalives do not decide phase, and completed/incomplete snapshots reuse per-item decisions when their phase is absent. Live text keeps streaming while message completion waits for classification. Retained state uses the request's translator budget. Also applies to JSON reconstructed from upstream SSE; ordinary upstream JSON is unchanged. | +| `messagePhaseInference?` | `boolean` | Off by default. For Responses passthrough streams, infer missing message phases at completion: a subsequent protocol event yields `commentary`; following tool work in a completed/incomplete snapshot also yields `commentary` when item events were omitted; otherwise a terminal event or `[DONE]` yields `final_answer`. Explicit commentary/final_answer phases are preserved (null or unknown values are inferred like missing ones), keepalives do not decide phase, and completed/incomplete snapshots reuse per-item decisions when their phase is absent. Live text keeps streaming while message completion waits for classification. Retained state uses the request's translator budget. Also applies to JSON reconstructed from upstream SSE; ordinary upstream JSON is unchanged. | | `estimateMissingUsage?` | `boolean` | Off by default. For a native Responses route (`openai-responses`) whose provider sends a completed response without `usage`, add an estimate so a client such as Codex keeps its context meter: `input_tokens` is estimated from the request and `output_tokens` from the response's own output. Usage the provider sent is never changed. Responses carrying an estimate are marked with the `x-opencodex-usage-estimated` header: `true` on a JSON response whose usage was estimated, `when-missing` on a stream, where any usage the provider omitted is estimated. Estimates are for display only: OpenCodex's request history, cost, spend limits and quota keep reading the provider's own figures. This also applies to Combo routes: missing provider usage keeps the spend reservation unresolved, including when all targets exhaust the output limit without producing output. Actual usage stays authoritative, including when it arrives after streaming output begins or after Combo has sent connection keepalives while selecting a target. Only HTTP Responses requests (`/v1/responses`) are estimated: the Chat Completions (`/v1/chat/completions`) and Claude Messages (`/v1/messages`) bridges, the WebSocket transport and OpenCodex's internal decision calls never get an estimate, because they rebuild usage from the response or settle spend from it. An OpenCodex instance that consumes this proxy as an `openai-responses` provider does not read `x-opencodex-usage-estimated` and would record the estimate as reported usage, so leave `estimateMissingUsage` off on a proxy that another OpenCodex sits behind. | | `webSearchBridge?` | `{ enabled?: boolean; backend?: "ollama" \| "openai" \| "anthropic" \| "xai" \| "gemini" \| "exa"; maxSearches?: number; timeoutMs?: number; endpoint?: string }` | Key-auth `openai-responses` passthrough providers only. Off by default. Codex always declares the hosted `web_search` tool, and the passthrough relays it on the assumption the destination executes it. A gateway that does not run hosted search answers with a `function_call` named `web_search` that nothing runs, and the undeclared-tool guard ends the turn. With `enabled: true` and an explicit `backend` OpenCodex intercepts that call, runs the search itself, feeds the result back to the same upstream, and shows Codex a hosted `web_search_call` cell. Never armed for `authMode: "forward"` (ChatGPT already searches) or for a provider that executes hosted search upstream. `backend` is required; there is no implicit default and a missing credential for the named backend leaves the bridge disarmed rather than falling through to another paid search. `ollama` reuses this provider's own API key on `POST /api/web_search`, so the origin must be `https://ollama.com` unless the operator names `endpoint` explicitly. `openai` / `anthropic` / `xai` / `gemini` / `exa` reuse the matching sidecar executor and that executor's own credential (`webSearchSidecar.exaApiKey` for Exa). The search model comes from `webSearchSidecar.model` only when `webSearchSidecar.backend` resolves to the same backend this bridge names; otherwise the bridge runs that backend's own default, because a model chosen for one vendor is rejected by another. An unset `webSearchSidecar.backend` resolves to `openai`, so an unset-backend model reaches an `openai` bridge and no other. There is no per-provider bridge model override. Streaming turns only. A turn that mixes `web_search` with another client tool call still fails closed rather than dropping the client's call. Assistant text such as XML-like `` prose is not executed. Defaults: `maxSearches: 3` (1..10), `timeoutMs: 60000` (1000..600000). | | `retryOn429?` | `{ enabled?: boolean; attempts?: number; intervalMs?: number; maxIntervalMs?: number; respectRetryAfter?: boolean }` | API-key providers only (`authMode: "key"`). Opt-in same-target 429 retry: when `retryOn429` is absent the feature is off, except that key-auth OpenCode Go and Command Code (canonical endpoints) fall back to a patient policy (6 replays, 10 s interval, 60 s cap), and canonical Mistral `openai-chat` falls back to 6 replays with a 10 s interval and 60 s cap; object presence enables it unless `enabled: false`, which also turns that fallback off. On 429 the proxy waits (upstream `Retry-After` or the fixed interval) and replays the identical request on the same key before any key failover — across the main text-turn recovery loop, the Responses passthrough wire, the image/video bridge, the web-search sidecar, and terminal continuations. Only pre-stream HTTP 429 responses are eligible for replay; custom `runTurn` transports are outside the HTTP retry loop. `attempts` counts same-key replays after the first 429 (total sends = `attempts` + 1) and is one request-wide budget shared by the main recovery loop, the terminal-guard continuation, and bridge retries. Exhausting `attempts` only stops further same-key replays: normal key failover or final-error handling then applies per the available targets — on the key-auth passthrough wire there is no failover, so the exhausted 429 surfaces as-is. For canonical Mistral Chat, an explicit upstream delay above the allowed wait stops same-key replay (another pooled key may still serve) and returns the original `Retry-After`; other providers retain the capped-delay behavior. Mistral shares retry deadlines per credential/model unless `requestPacing.enabled: false` or `retryOn429.respectRetryAfter: false`. A 429 with validated minute-budget pressure and no retry time activates a conservative 60 s recovery wait, followed by one probe; success restores ordinary traffic. Healthy traffic never predicts the next token charge. This policy uses advertised allowances, excludes known exhausted monthly allowances, does not claim an exact reset time, and never triggers compaction. Codex itself never retries 429, so this is the only defense for single-key providers. Defaults: `enabled: true`, `attempts: 3`, `intervalMs: 5000`, `maxIntervalMs: 60000` (any single wait is capped at `maxIntervalMs`, itself capped at 600000), `respectRetryAfter: true`. | diff --git a/src/server/responses-phase-inference.ts b/src/server/responses-phase-inference.ts index 41557548624..7c9fa350695 100644 --- a/src/server/responses-phase-inference.ts +++ b/src/server/responses-phase-inference.ts @@ -21,7 +21,8 @@ import { replaceSseDataPayload, sseDataPayload } from "./sse-payload-rewrite"; * Live text deltas are not buffered, but message completion waits for that * event. Snapshots reuse each item decision when their phase is absent, * matched by item id or, when either side lacks an id, by output index; - * explicit snapshot phases take precedence, and failed snapshots are untouched. + * terminal snapshot tool work also proves continuation when item events were + * omitted. Explicit snapshot phases take precedence; failed snapshots are untouched. */ const TERMINAL_EVENT_TYPES = new Set([ @@ -115,20 +116,29 @@ function decidedPhase(decisions: PhaseDecisions, id: string | null, position: nu return byIndex && (byIndex.id === null || id === null) ? byIndex.phase : undefined; } +function snapshotPhase(output: unknown[], position: number): OcxMessagePhase { + if (position < 0 || position >= output.length) return "final_answer"; + const item = output[position]; + if (!isPlainObject(item) || item.type !== "message") return "final_answer"; + if (isMessagePhase(item.phase)) return item.phase; + return output.slice(position + 1).some(isToolCallItem) ? "commentary" : "final_answer"; +} + function withSnapshotPhases(block: string, decisions: PhaseDecisions): string { const parsed = parseDataPayload(block); if (!parsed) return block; const response = parsed.response; if (!isPlainObject(response) || !Array.isArray(response.output)) return block; + const sourceOutput = response.output; let changed = false; const output = response.output.map((item: unknown, position: number) => { if (isPlainObject(item) && item.type === "message" && !isMessagePhase(item.phase)) { // Mirror the decision already emitted for this item on the wire, so // clients reconciling the final snapshot never re-expand a message - // whose output_item.done said commentary. Items the rewrite never saw - // (joined mid-stream, no buffered decision) fall back to final_answer. + // whose output_item.done said commentary. Otherwise, use following + // snapshot tool work as continuation evidence; no work means final. const id = typeof item.id === "string" ? item.id : null; - const phase = decidedPhase(decisions, id, position) ?? "final_answer"; + const phase = decidedPhase(decisions, id, position) ?? snapshotPhase(sourceOutput, position); changed = true; return { ...item, phase }; } @@ -205,9 +215,20 @@ export function createResponsesPhaseInferenceBlockRewrite(budget: TranslatorBudg const parsed = parseDataPayload(block); const type = typeof parsed?.type === "string" ? parsed.type : null; if (TERMINAL_EVENT_TYPES.has(type!)) { - // Turn end: any still-buffered message is the final answer, and the - // terminal snapshot mirrors the same per-item decisions for consistency. - const released = releasePending("final_answer"); + // A terminal snapshot can reveal tool work omitted from item events. + // Use that continuation evidence before committing a pending phase. + const output = isPlainObject(parsed?.response) && Array.isArray(parsed.response.output) ? parsed.response.output : []; + const held = pending === null ? null : parseDataPayload(pending); + const heldItem = held?.item; + const id = isPlainObject(heldItem) && typeof heldItem.id === "string" ? heldItem.id : null; + const matched = id !== null + ? output.findIndex(item => isPlainObject(item) && item.id === id) + : -1; + const index = outputIndexOf(held?.output_index); + const indexed = index === null ? undefined : output[index]; + const position = matched >= 0 ? matched + : index !== null && (id === null || (isPlainObject(indexed) && typeof indexed.id !== "string")) ? index : -1; + const released = releasePending(type === "response.failed" ? "final_answer" : snapshotPhase(output, position)); const snapshot = type === "response.failed" ? block : withSnapshotPhases(block, decisions); clearState(); return [...released, snapshot]; diff --git a/structure/transports/responses.md b/structure/transports/responses.md index 9c42361d85b..7158ddc1218 100644 --- a/structure/transports/responses.md +++ b/structure/transports/responses.md @@ -30,7 +30,7 @@ namespace scrubbing remain shared compatibility behavior. Codex quota/reset evid ### Passthrough message phase inference -Opt-in `messagePhaseInference` gives native passthrough Responses streams the commentary/final_answer semantics the Chat bridge owns under [ADR-0069](../decisions/ADR-0069-chat-to-responses-message-phase-inference.md). The block rewrite in `src/server/responses-phase-inference.ts`, wired through the `src/server/responses/passthrough-delivery.ts` chain, retains each completed message whose phase is missing, null, or not commentary/final_answer until the next typed protocol event: a following tool call, reasoning, or message classifies it as commentary; a terminal event or `[DONE]` classifies it as final_answer. Text deltas keep streaming, but completion may wait for that next event. Explicitly phased messages forward immediately; keepalives and unparseable blocks pass through without consuming the pending decision. Valid explicit phases are retained like inferred ones. Each decision is keyed by item id and by `output_index`; completed and incomplete snapshots fill absent phases from the decision with the same id, or from the decision at the same output position when the event or the snapshot item has no id, so an item-done event and its snapshot entry never disagree. Unmatched items, including a different id at a known position, fall back to final_answer; explicit snapshot phases take precedence even when they disagree with an earlier event. Failed terminal bodies remain unchanged. The pending block and per-id decisions are charged to the request's translator budget; overflow fails through the shared buffer-limit error. State is released on every terminal event, `[DONE]`, rewrite failure, and relay teardown (`tests/responses/responses-phase-inference.test.ts`). The same client rewrite chain also runs when upstream SSE is reconstructed into a buffered JSON response; ordinary upstream JSON is not phase-rewritten. +Opt-in `messagePhaseInference` gives native passthrough Responses streams the commentary/final_answer semantics the Chat bridge owns under [ADR-0069](../decisions/ADR-0069-chat-to-responses-message-phase-inference.md). The block rewrite in `src/server/responses-phase-inference.ts`, wired through the `src/server/responses/passthrough-delivery.ts` chain, retains each completed message whose phase is missing, null, or not commentary/final_answer until the next typed protocol event: a following tool call, reasoning, or message classifies it as commentary; a terminal snapshot's following tool work classifies it as commentary even if item events were omitted; otherwise a terminal event or `[DONE]` classifies it as final_answer. Text deltas keep streaming, but completion may wait for that next event. Explicitly phased messages forward immediately; keepalives and unparseable blocks pass through without consuming the pending decision. Valid explicit phases are retained like inferred ones. Each decision is keyed by item id and by `output_index`; completed and incomplete snapshots fill absent phases from the decision with the same id, or from the decision at the same output position when the event or the snapshot item has no id, so an item-done event and its snapshot entry never disagree. Unmatched snapshot messages infer commentary only when followed by tool-call work in that snapshot; otherwise they fall back to final_answer. A pending message with a different id never borrows that continuation; explicit snapshot phases take precedence even when they disagree with an earlier event. Failed terminal bodies remain unchanged. The pending block and per-id decisions are charged to the request's translator budget; overflow fails through the shared buffer-limit error. State is released on every terminal event, `[DONE]`, rewrite failure, and relay teardown (`tests/responses/responses-phase-inference.test.ts`). The same client rewrite chain also runs when upstream SSE is reconstructed into a buffered JSON response; ordinary upstream JSON is not phase-rewritten. Opt-in `estimateMissingUsage` (#7427) adds estimated `usage` to a native passthrough response the provider sent without one. `src/server/responses/estimated-usage.ts` fills `input_tokens` from `estimateInputTokens` and `output_tokens` from the completed response's own output items (or, when a streamed terminal closes with an empty `output`, from a running count of the stream's `response.output_item.done` items, retaining no item); usage the provider sent, error bodies, non-terminal events, and response bodies whose `status` is not `completed`/`incomplete` or that carry an `error` are left alone, even under HTTP 200. `passthrough-delivery.ts` applies it as the last client block rewrite on SSE `response.completed`/`response.incomplete` (marked `x-opencodex-usage-estimated: when-missing`) and on bounded JSON responses (marked `true` when applied), never on the canonical JSON fold. The request log, spend and quota read the provider's original bytes (the tee inspection branch, the eager relay's pre-rewrite inspection, and `inspectResponseLogJson` before rewrites; an applied JSON estimate also records local estimate provenance in `clientResponseUsage` on the request-log context so the finalizer's second parse of the delivered body skips its usage). Preflight of a process-marked native stream uses `createSseInspector({ collectUsage: false })` when rereading client-facing bytes: terminal and error metadata still participate in selection. The retryable failure envelope leaves usage to the original inspector as well. A zero-output exhaustion terminal delivers `failure.usage` when present, otherwise the failed child's usage; settlement reads the adopted child log, and the log finalizer skips the synthesized body's usage. This is local response ownership, not trust in the estimate header; raw inspection remains enabled. A committed Combo forwards later raw child usage and its wire provenance before the parent finalizes spend. Behind a committed selection keepalive, `combo-selection-keepalive.ts` identifies the accepted native response before forwarding bytes and marks only the outer client-body tap to skip usage; its dynamic inspector still reads terminal and error metadata, and the native raw inspector remains active. Scope is HTTP Responses ingress only (`estimatesMissingUsage` in `estimated-usage.ts`): the Chat Completions and Claude Messages bridges and the WebSocket transport rebuild usage from the response and would forward an estimate without the marker, and an internal decision call (`internalDecisionCall`) settles spend from its response body, so none of them is estimated. The JEV invoker (`jev-model-invoke.ts`) reads process-owned usage provenance. Native response ingress strips the reserved header from upstream responses. Translated adapter routes are not covered. An OpenCodex instance that consumes an estimating proxy as a provider does not read the marker and records the estimate as reported usage; operators leave the flag off on such a proxy. Coverage: `tests/responses/responses-estimated-usage.test.ts`, `tests/responses/responses-combo-estimated-usage-spend.test.ts`, `tests/server/server-jev-model-quota-budget.test.ts`. ### Credential-bearing HTTP redirects diff --git a/tests/responses/responses-phase-inference.test.ts b/tests/responses/responses-phase-inference.test.ts index e7bec3bbe3f..11ef36038f1 100644 --- a/tests/responses/responses-phase-inference.test.ts +++ b/tests/responses/responses-phase-inference.test.ts @@ -35,6 +35,50 @@ function phaseOf(block: string): string | undefined { } describe("Responses phase inference block rewrite", () => { + test("snapshot-only tool work classifies preceding messages as commentary", () => { + const rewrite = createResponsesPhaseInferenceBlockRewrite(createTestTranslatorBudget()); + const call = { type: "custom_tool_call", id: "tool", call_id: "read", name: "exec", input: "read source" }; + const [out] = rewrite(completed([{ type: "message", id: "progress" }, call])); + expect(phaseOf(out!)).toBe("commentary,"); + expect(JSON.parse(out!.split("data: ")[1]!).response.output[1]).toEqual(call); + rewrite.dispose?.(); + }); + + test("pending message uses following terminal snapshot tool work", () => { + const rewrite = createResponsesPhaseInferenceBlockRewrite(createTestTranslatorBudget()); + const out = [messageDone(0, "reading"), completed([ + { type: "message", id: "msg_0" }, + { type: "function_call", id: "tool", call_id: "read", name: "shell", arguments: "{}" }, + ])].flatMap(block => rewrite(block)); + expect(out.map(phaseOf)).toEqual(["commentary", "commentary,"]); + rewrite.dispose?.(); + }); + + test("snapshot continuation preserves explicit phases and cannot borrow a different item id", () => { + const rewrite = createResponsesPhaseInferenceBlockRewrite(createTestTranslatorBudget()); + const out = [messageDone(0, "reading"), completed([ + { type: "message", id: "other", phase: "final_answer" }, + { type: "function_call", id: "tool", call_id: "read", name: "shell", arguments: "{}" }, + { type: "message", id: "last" }, + ])].flatMap(block => rewrite(block)); + expect(out.map(phaseOf)).toEqual(["final_answer", "final_answer,,final_answer"]); + rewrite.dispose?.(); + }); + + for (const missingId of ["event", "snapshot"]) { + test(`pending snapshot continuation matches by index with a missing ${missingId} id`, () => { + const rewrite = createResponsesPhaseInferenceBlockRewrite(createTestTranslatorBudget()); + const item = { type: "message", ...(missingId === "snapshot" ? {} : { id: "msg_0" }) }; + const held = missingId === "event" + ? sse("response.output_item.done", { output_index: 0, item: { type: "message" } }) + : messageDone(0, "reading"); + const out = [held, completed([item, { type: "custom_tool_call", id: "tool", call_id: "read", name: "exec", input: "read" }])] + .flatMap(block => rewrite(block)); + expect(out.map(phaseOf)).toEqual(["commentary", "commentary,"]); + rewrite.dispose?.(); + }); + } + test("message followed by a tool call becomes commentary", () => { const rewrite = createResponsesPhaseInferenceBlockRewrite(createTestTranslatorBudget()); const out = [messageDone(0, "checking the grid"), functionCallAdded(1)].flatMap(b => rewrite(b)); From 18d1dab82396d3d665cb195a45734e55ca414a58 Mon Sep 17 00:00:00 2001 From: Reidar Date: Thu, 12 Nov 2026 08:56:01 +0100 Subject: [PATCH 02/11] test: isolate sandbox service identity from live install --- scripts/test.ts | 5 ++++- structure/ops/test-sandbox-cleanup.md | 5 +++++ tests/ci-workflows/test-runner.test.ts | 6 +++++- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/scripts/test.ts b/scripts/test.ts index 5b73037fb54..321e56fc8e8 100644 --- a/scripts/test.ts +++ b/scripts/test.ts @@ -26,7 +26,8 @@ export interface IsolatedTestEnvironment { } /** - * Settings from the developer's own OpenCodex install that the sandbox must not inherit. A + * Live credentials, service identity, and settings from the developer's own OpenCodex install that + * the sandbox must not inherit. A * Windows install stores its data-plane token as a user environment variable, so every shell on * that machine carries it; a test that then builds a service definition or starts a proxy reads * the live token instead of its fixture and fails only on a developer machine. @@ -36,6 +37,8 @@ export const LIVE_INSTALL_ENV = [ "OPENCODEX_ADMIN_AUTH_TOKEN", "OCX_API_TOKEN_FILE", "OCX_MANAGED_RELEASE", + "OCX_SERVICE", + "OCX_SERVICE_MANAGED", ] as const; export function createIsolatedTestEnvironment( diff --git a/structure/ops/test-sandbox-cleanup.md b/structure/ops/test-sandbox-cleanup.md index dd2a109d745..4eb7b534c26 100644 --- a/structure/ops/test-sandbox-cleanup.md +++ b/structure/ops/test-sandbox-cleanup.md @@ -58,6 +58,11 @@ paths, delayed generation transitions, member/release ordering and gate-holder d ## Sandbox lifecycle +The runner and preload both remove live credentials and `OCX_SERVICE`/`OCX_SERVICE_MANAGED` +before executing tests. A proxy-launched test process must not inherit service-child authority +or require its temporary fixture home to own the developer's service. The owner regression in +`tests/ci-workflows/test-runner.test.ts` checks service identity removal alongside credential removal. + The batch runner's per-process home isolation and live-home/service-manager guards remain active because the preload installs them before the lock boundary. `tests/preload.ts` resolves cleanup dependencies after home/lock admission and before test cases. Teardown awaits native-main startup diff --git a/tests/ci-workflows/test-runner.test.ts b/tests/ci-workflows/test-runner.test.ts index 620ba849342..120fc4d1dff 100644 --- a/tests/ci-workflows/test-runner.test.ts +++ b/tests/ci-workflows/test-runner.test.ts @@ -338,7 +338,7 @@ describe("test runner isolation", () => { expect(existsSync(isolated.root)).toBe(false); }); - test("drops the developer's live install settings and keeps the rest of the environment", () => { + test("drops the developer's live credentials, service identity, and install settings while keeping fixture environment", () => { const isolated = createIsolatedTestEnvironment({ PATH: "/test/bin", FIXTURE: "unchanged", @@ -346,10 +346,14 @@ describe("test runner isolation", () => { OPENCODEX_ADMIN_AUTH_TOKEN: "live-admin-token", OCX_API_TOKEN_FILE: "/real/home/.opencodex/service-api-token", OCX_MANAGED_RELEASE: "1", + OCX_SERVICE: "1", + OCX_SERVICE_MANAGED: "1", }); try { for (const name of LIVE_INSTALL_ENV) expect(name in isolated.env).toBe(false); expect("OCX_MANAGED_RELEASE" in isolated.env).toBe(false); + expect(isolated.env.OCX_SERVICE).toBeUndefined(); + expect(isolated.env.OCX_SERVICE_MANAGED).toBeUndefined(); expect(isolated.env.FIXTURE).toBe("unchanged"); expect(isolated.env.PATH).toBe("/test/bin"); } finally { From b6b83084d6d5c85e889f8be34ad0f0f79ca61fb6 Mon Sep 17 00:00:00 2001 From: Reidar Date: Thu, 12 Nov 2026 08:56:50 +0100 Subject: [PATCH 03/11] test(catalog): bind child reaper assertions to the target process --- tests/codex-integration/catalog-async-lifetime.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/codex-integration/catalog-async-lifetime.test.ts b/tests/codex-integration/catalog-async-lifetime.test.ts index 4aa26b6443e..333d2ce1922 100644 --- a/tests/codex-integration/catalog-async-lifetime.test.ts +++ b/tests/codex-integration/catalog-async-lifetime.test.ts @@ -260,9 +260,12 @@ for (const mode of ["abort", "deadline"] as const) { const exited = hold(); const controller = new AbortController(); let child: childProcess.ChildProcess | undefined; + const script = "if (process.platform !== 'win32') process.on('SIGTERM', () => {}); console.log('READY'); setInterval(() => {}, 20);"; const actualExec = childProcess.execFile; const spawn = spyOn(childProcess, "execFile").mockImplementation(((...args: Parameters) => { - child = actualExec(...args); + const spawned = actualExec(...args); + if (args[0] !== process.execPath || !Array.isArray(args[1]) || args[1].length !== 2 || args[1][0] !== "-e" || args[1][1] !== script) return spawned; + child = spawned; let output = ""; child.stdout?.on("data", chunk => { output += String(chunk); if (output.includes("READY")) ready.resolve(); }); child.once("exit", () => exited.resolve()); @@ -277,7 +280,6 @@ for (const mode of ["abort", "deadline"] as const) { } return set(fn, delay, ...args); }) as typeof setTimeout); - const script = "if (process.platform !== 'win32') process.on('SIGTERM', () => {}); console.log('READY'); setInterval(() => {}, 20);"; const pending = runtime.execCodexFileAsync(process.execPath, ["-e", script], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: mode === "deadline" ? 1234 : 10_000, windowsHide: true, signal: controller.signal, @@ -286,6 +288,7 @@ for (const mode of ["abort", "deadline"] as const) { const rejected = pending.then(() => { throw new Error("held child unexpectedly completed"); }, error => error); try { await Promise.race([ready.promise, Bun.sleep(3000).then(() => { throw new Error("child never became READY"); })]); + await new Promise((resolve, reject) => childProcess.execFile(process.execPath, ["-e", "process.exit(0)"], error => error ? reject(error) : resolve())); const started = Date.now(); if (mode === "abort") controller.abort(); const error = await rejected; From dda1918203b3adb12c5a12faac6e2f982a846d94 Mon Sep 17 00:00:00 2001 From: Reidar Date: Thu, 12 Nov 2026 08:57:02 +0100 Subject: [PATCH 04/11] test: prepare derived caches and bound real process fixtures --- tests/cli/cli-status-json.test.ts | 4 ++-- .../catalog-omit-disabled-native.test.ts | 1 + .../codex-catalog-sync-hardening.test.ts | 3 ++- .../messaging-remote-replies.test.ts | 3 ++- .../native-ultrafast-picker.test.ts | 3 ++- tests/update/update-stop-first.test.ts | 19 +++++++++++++++++-- 6 files changed, 26 insertions(+), 7 deletions(-) diff --git a/tests/cli/cli-status-json.test.ts b/tests/cli/cli-status-json.test.ts index 2260eca75f5..4c03551853f 100644 --- a/tests/cli/cli-status-json.test.ts +++ b/tests/cli/cli-status-json.test.ts @@ -999,7 +999,7 @@ describe("status reports stale process records end to end", () => { } finally { removeTreeWithRetry(home); } - }); + }, SPAWN_BUDGET_MS); test("a clean home reports false and says nothing about a previous run", () => { const home = mkdtempSync(join(tmpdir(), "ocx-stale-clean-")); @@ -1019,7 +1019,7 @@ describe("status reports stale process records end to end", () => { } finally { removeTreeWithRetry(home); } - }); + }, SPAWN_BUDGET_MS); // Review blocker 3: a recycled pid must suppress rather than assert. This process is // certainly alive, so recording it stands in for a reused pid. diff --git a/tests/codex-integration/catalog-omit-disabled-native.test.ts b/tests/codex-integration/catalog-omit-disabled-native.test.ts index 8980d518bf9..f417280a155 100644 --- a/tests/codex-integration/catalog-omit-disabled-native.test.ts +++ b/tests/codex-integration/catalog-omit-disabled-native.test.ts @@ -195,6 +195,7 @@ test("retained sync and serve-options omit the same rows without changing routed const next = config(true); saveConfig(next); expect((await syncCatalogModels(next, { allowWhenDesiredDisabled: true })).refreshOutcome).toBe("committed"); + invalidateCodexModelsCache({ allowWhenDesiredDisabled: true }); const server = startServer(0); try { const response = await fetch(new URL("/v1/models?client_version=0.160.0", server.url)); diff --git a/tests/codex-integration/codex-catalog-sync-hardening.test.ts b/tests/codex-integration/codex-catalog-sync-hardening.test.ts index a28975af281..6f5d52659ae 100644 --- a/tests/codex-integration/codex-catalog-sync-hardening.test.ts +++ b/tests/codex-integration/codex-catalog-sync-hardening.test.ts @@ -8,6 +8,7 @@ import { ACCOUNT_GATED_NATIVE_OPENAI_MODELS } from "../../src/codex/catalog/nati import { removeTreeWithRetry } from "../helpers/remove-tree"; import { withConfigMutationLockSync } from "../../src/config/mutation-lock"; import { NEUTRAL_IDENTITY_LINE } from "../../src/adapters/identity"; +import { SPAWN_BUDGET_MS } from "../helpers/test-budget"; const repoRoot = dirname(fileURLToPath(new URL("../../package.json", import.meta.url))); @@ -1137,7 +1138,7 @@ describe("Codex catalog sync hardening", () => { slugs = (JSON.parse(readFileSync(catalogPath, "utf8")).models as Array<{ slug: string }>).map(m => m.slug); expect(slugs).not.toContain("future-grok/legacy-model"); expect(slugs).toContain("cursor/composer-2.5"); - }); + }, SPAWN_BUDGET_MS); test("drops legacy combo-alias ghost rows in both gather branches", () => { const legacyComboAlias = { diff --git a/tests/codex-integration/messaging-remote-replies.test.ts b/tests/codex-integration/messaging-remote-replies.test.ts index 1b375f7ba68..400a2eff435 100644 --- a/tests/codex-integration/messaging-remote-replies.test.ts +++ b/tests/codex-integration/messaging-remote-replies.test.ts @@ -4,6 +4,7 @@ import { RemoteReplyGrants, REPLY_GRANT_LIMIT, REPLY_GRANT_MS } from "../../src/ import { parseRemoteState } from "../../src/messaging/remote-store"; import { LOCAL_OTHER, LOCAL_TARGET } from "../helpers/messaging-local"; import { remoteMessagingPair } from "../helpers/messaging-remote"; +import { STORE_BUDGET_MS } from "../helpers/test-budget"; test.skipIf(process.platform === "win32")("reply grants bind peer, generation, local target, kind and correlation before await", async () => { const pair = remoteMessagingPair(); @@ -84,4 +85,4 @@ test.skipIf(process.platform === "win32")("reply routes have fixed capacity and for (let i = 0; i < REPLY_GRANT_LIMIT; i++) grants.control({ ...request, messageId: crypto.randomUUID() }); expect(() => grants.control({ ...request, messageId: crypto.randomUUID() })).toThrow("capacity"); } finally { await pair.close(); } -}); +}, STORE_BUDGET_MS); diff --git a/tests/codex-integration/native-ultrafast-picker.test.ts b/tests/codex-integration/native-ultrafast-picker.test.ts index c7e03e887c0..ff3da869212 100644 --- a/tests/codex-integration/native-ultrafast-picker.test.ts +++ b/tests/codex-integration/native-ultrafast-picker.test.ts @@ -15,6 +15,7 @@ import { join } from "node:path"; import { repoRoot } from "../helpers/repo-root"; import { acquireOwnedSpendHome } from "../helpers/owned-spend-home"; import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { SPAWN_BUDGET_MS } from "../helpers/test-budget"; import type { RawEntry } from "../../src/codex/catalog/parsing"; import { mergeCatalogEntriesFromObservedState, type ObservedCatalogMergeInput } from "../../src/codex/catalog/build-entries"; import { applyNativeUltraFastTier, NATIVE_ULTRAFAST_SERVICE_TIER } from "../../src/codex/catalog/native-ultrafast"; @@ -204,7 +205,7 @@ for (const writer of ["retained-sync", "convergence"] as const) { } } } finally { rmSync(root, { recursive: true, force: true }); } - }); + }, SPAWN_BUDGET_MS); } /** diff --git a/tests/update/update-stop-first.test.ts b/tests/update/update-stop-first.test.ts index 5fb37a0d242..f41b5e8e41b 100644 --- a/tests/update/update-stop-first.test.ts +++ b/tests/update/update-stop-first.test.ts @@ -234,7 +234,7 @@ process.on("exit", code => fixtureStatus("launcher-exit", { exitCode: code, sign `; } -function instrumentRecoveryLauncher(source: string, directory: string): string { +function instrumentRecoveryLauncher(source: string, directory: string, serviceHome?: "absent" | "unknown"): string { // Fail closed on drift, preserving the real calls and every original handler. const replaceOnce = (needle: string, replacement: string) => { if (source.split(needle).length !== 2) throw new Error("recovery diagnostic fixture: launcher seam changed"); @@ -256,6 +256,8 @@ function instrumentRecoveryLauncher(source: string, directory: string): string { replaceOnce('child.on("error", err => {', `child.on("error", err => { fixtureStatus("runtime-spawn-error", recoveryErrorFields(err));`); replaceOnce('forwarding.attach(child);', 'forwarding.attach(child);\nchild.on("spawn", () => fixtureStatus("runtime-spawned", { pid: child.pid }));'); + // Host service-manager availability must not choose this fixture's recovery policy. + if (serviceHome) replaceOnce('() => readNodeUpdateHome(authorityLauncher)', `() => ({ kind: ${JSON.stringify(serviceHome)} })`); return source; } const updateSource = readFileSync(join(repoRoot, "src", "update", "index.ts"), "utf8"); @@ -668,7 +670,7 @@ describe("update stops the running proxy before replacing files", () => { for (const name of ["stdout", "stderr", "status"]) { writeFileSync(join(diagnostics, name), "", { mode: 0o600, flag: "wx" }); } - writeFileSync(launcher, instrumentRecoveryLauncher(launcherSource, diagnostics)); + writeFileSync(launcher, instrumentRecoveryLauncher(launcherSource, diagnostics, "unknown")); chmodSync(launcher, 0o755); symlinkSync(join(repoRoot, "src"), join(packageRoot, "src"), "dir"); symlinkSync(bundledBun, join(packageRoot, "node_modules", "bun"), "dir"); @@ -694,6 +696,19 @@ esac // 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 refused = Bun.spawnSync([node, launcher, "update"], { + cwd: root, + env, + stdout: "pipe", + stderr: "pipe", + timeout: UPDATE_SPAWN_TIMEOUT_MS, + }); + const refusal = refused.stdout.toString() + refused.stderr.toString(); + expect(refused.exitCode, refusal).toBe(1); + expect(refusal).toContain("service registration ownership could not be verified"); + expect(refusal).not.toContain("Stopping the running proxy before updating"); + expect(refusal).not.toContain(`Attempting to restart the proxy on port ${port}.`); + writeFileSync(launcher, instrumentRecoveryLauncher(launcherSource, diagnostics, "absent")); const result = Bun.spawnSync([node, launcher, "update"], { cwd: root, env, From 8d432ce0a2fbf2e2eb703e87e0c8d5602a3db9c2 Mon Sep 17 00:00:00 2001 From: Reidar Date: Thu, 12 Nov 2026 09:16:24 +0100 Subject: [PATCH 05/11] test(update): include refusal control in recovery budget --- tests/update/update-stop-first.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/update/update-stop-first.test.ts b/tests/update/update-stop-first.test.ts index f41b5e8e41b..11538fca042 100644 --- a/tests/update/update-stop-first.test.ts +++ b/tests/update/update-stop-first.test.ts @@ -34,6 +34,7 @@ function freePort(): Promise { * a 60s Bun timeout, a 45s wait leaves the readiness probe unable to finish inside the case at * all — observed failing at 46-47s on macOS, which reads as a product defect and is not one. * + * The unknown-ownership negative control adds one separately bounded launcher invocation. * So the budget is derived from the timeout rather than guessed against it: the wait gets what * remains after the spawns, and the Bun timeout is stated as the sum of its parts. The deadline * exists to stop a HUNG proxy, not to assert a boot deadline the suite never intended to @@ -44,8 +45,8 @@ const UPDATE_SPAWN_TIMEOUT_MS = 30_000; // on at least four unrelated PRs; the detached Bun proxy can take >45s to // serve /healthz there). 90s keeps the derived case budget honest below. const PROXY_READY_TIMEOUT_MS = 90_000; -/** Spawn + readiness + teardown spawn, plus headroom for fixture IO on a loaded runner. */ -const RECOVERY_CASE_TIMEOUT_MS = UPDATE_SPAWN_TIMEOUT_MS + PROXY_READY_TIMEOUT_MS + UPDATE_SPAWN_TIMEOUT_MS + 15_000; +/** Refusal spawn + update spawn + readiness + teardown spawn, plus fixture IO headroom. */ +const RECOVERY_CASE_TIMEOUT_MS = 3 * UPDATE_SPAWN_TIMEOUT_MS + PROXY_READY_TIMEOUT_MS + 15_000; async function waitForProxy(port: number, onFailure: (lastProbe: string) => void): Promise { const deadline = Date.now() + PROXY_READY_TIMEOUT_MS; From 539920e31bc53f0ad4e0d3bd0e8964d41a4fcb4f Mon Sep 17 00:00:00 2001 From: Reidar Date: Thu, 12 Nov 2026 09:22:01 +0100 Subject: [PATCH 06/11] test(catalog): use the existing child-process suite budget --- .../codex-integration/codex-catalog-sync-hardening.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/codex-integration/codex-catalog-sync-hardening.test.ts b/tests/codex-integration/codex-catalog-sync-hardening.test.ts index 6f5d52659ae..b73b44707e2 100644 --- a/tests/codex-integration/codex-catalog-sync-hardening.test.ts +++ b/tests/codex-integration/codex-catalog-sync-hardening.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, setDefaultTimeout, test } from "bun:test"; import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from "node:fs"; import { spawnSync } from "node:child_process"; import { tmpdir } from "node:os"; @@ -10,6 +10,9 @@ import { withConfigMutationLockSync } from "../../src/config/mutation-lock"; import { NEUTRAL_IDENTITY_LINE } from "../../src/adapters/identity"; import { SPAWN_BUDGET_MS } from "../helpers/test-budget"; +// Catalog reconciliation is exercised through real child processes, including cold imports. +setDefaultTimeout(SPAWN_BUDGET_MS); + const repoRoot = dirname(fileURLToPath(new URL("../../package.json", import.meta.url))); function runScript( @@ -1138,7 +1141,7 @@ describe("Codex catalog sync hardening", () => { slugs = (JSON.parse(readFileSync(catalogPath, "utf8")).models as Array<{ slug: string }>).map(m => m.slug); expect(slugs).not.toContain("future-grok/legacy-model"); expect(slugs).toContain("cursor/composer-2.5"); - }, SPAWN_BUDGET_MS); + }); test("drops legacy combo-alias ghost rows in both gather branches", () => { const legacyComboAlias = { From f0075f7948a8409c276f2c786d77fe4bf4300963 Mon Sep 17 00:00:00 2001 From: Reidar Date: Thu, 12 Nov 2026 09:34:44 +0100 Subject: [PATCH 07/11] fix(responses): compute snapshot continuation in one scan --- src/server/responses-phase-inference.ts | 14 ++++---- .../responses-phase-inference.test.ts | 33 ++++++++++++++++++- 2 files changed, 40 insertions(+), 7 deletions(-) diff --git a/src/server/responses-phase-inference.ts b/src/server/responses-phase-inference.ts index 7c9fa350695..26d4e2c7cb2 100644 --- a/src/server/responses-phase-inference.ts +++ b/src/server/responses-phase-inference.ts @@ -116,15 +116,15 @@ function decidedPhase(decisions: PhaseDecisions, id: string | null, position: nu return byIndex && (byIndex.id === null || id === null) ? byIndex.phase : undefined; } -function snapshotPhase(output: unknown[], position: number): OcxMessagePhase { +function snapshotPhase(output: unknown[], position: number, lastToolIndex: number): OcxMessagePhase { if (position < 0 || position >= output.length) return "final_answer"; const item = output[position]; if (!isPlainObject(item) || item.type !== "message") return "final_answer"; if (isMessagePhase(item.phase)) return item.phase; - return output.slice(position + 1).some(isToolCallItem) ? "commentary" : "final_answer"; + return position < lastToolIndex ? "commentary" : "final_answer"; } -function withSnapshotPhases(block: string, decisions: PhaseDecisions): string { +function withSnapshotPhases(block: string, decisions: PhaseDecisions, lastToolIndex: number): string { const parsed = parseDataPayload(block); if (!parsed) return block; const response = parsed.response; @@ -138,7 +138,7 @@ function withSnapshotPhases(block: string, decisions: PhaseDecisions): string { // whose output_item.done said commentary. Otherwise, use following // snapshot tool work as continuation evidence; no work means final. const id = typeof item.id === "string" ? item.id : null; - const phase = decidedPhase(decisions, id, position) ?? snapshotPhase(sourceOutput, position); + const phase = decidedPhase(decisions, id, position) ?? snapshotPhase(sourceOutput, position, lastToolIndex); changed = true; return { ...item, phase }; } @@ -218,6 +218,8 @@ export function createResponsesPhaseInferenceBlockRewrite(budget: TranslatorBudg // A terminal snapshot can reveal tool work omitted from item events. // Use that continuation evidence before committing a pending phase. const output = isPlainObject(parsed?.response) && Array.isArray(parsed.response.output) ? parsed.response.output : []; + // Any later tool proves continuation; one reverse scan suffices for every message. + const lastToolIndex = type === "response.failed" ? -1 : output.findLastIndex(isToolCallItem); const held = pending === null ? null : parseDataPayload(pending); const heldItem = held?.item; const id = isPlainObject(heldItem) && typeof heldItem.id === "string" ? heldItem.id : null; @@ -228,8 +230,8 @@ export function createResponsesPhaseInferenceBlockRewrite(budget: TranslatorBudg const indexed = index === null ? undefined : output[index]; const position = matched >= 0 ? matched : index !== null && (id === null || (isPlainObject(indexed) && typeof indexed.id !== "string")) ? index : -1; - const released = releasePending(type === "response.failed" ? "final_answer" : snapshotPhase(output, position)); - const snapshot = type === "response.failed" ? block : withSnapshotPhases(block, decisions); + const released = releasePending(type === "response.failed" ? "final_answer" : snapshotPhase(output, position, lastToolIndex)); + const snapshot = type === "response.failed" ? block : withSnapshotPhases(block, decisions, lastToolIndex); clearState(); return [...released, snapshot]; } diff --git a/tests/responses/responses-phase-inference.test.ts b/tests/responses/responses-phase-inference.test.ts index 11ef36038f1..ffc552074d6 100644 --- a/tests/responses/responses-phase-inference.test.ts +++ b/tests/responses/responses-phase-inference.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, test } from "bun:test"; +import { describe, expect, spyOn, test } from "bun:test"; import { createResponsesPhaseInferenceBlockRewrite } from "../../src/server/responses-phase-inference"; import { createTestTranslatorBudget } from "../helpers/translator-budget"; import { relaySseWithBlockRewrite } from "../../src/server/sse-payload-rewrite"; @@ -35,6 +35,27 @@ function phaseOf(block: string): string | undefined { } describe("Responses phase inference block rewrite", () => { + for (const hasTool of [false, true]) { + test(`large snapshot continuation avoids quadratic suffix copies (tool=${hasTool})`, () => { + const messages = Array.from({ length: 512 }, (_, i) => ({ type: "message", id: `copy-budget-${i}` })); + const output = hasTool ? [...messages, { type: "function_call", id: "tool" }] : messages; + const slice = Array.prototype.slice; + let copiedEntries = 0; + const copies = spyOn(Array.prototype, "slice").mockImplementation(function (this: unknown[], start?: number, end?: number) { + const result = slice.call(this, start, end); + if (this.length === output.length && (this[0] as { id?: string })?.id === "copy-budget-0") copiedEntries += result.length; + return result; + }); + const rewrite = createResponsesPhaseInferenceBlockRewrite(createTestTranslatorBudget()); + try { + const [out] = rewrite(completed(output)); + const phases = JSON.parse(out!.split("data: ")[1]!).response.output.map((item: { phase?: string }) => item.phase); + expect(phases.slice(0, messages.length)).toEqual(messages.map(() => hasTool ? "commentary" : "final_answer")); + expect(copiedEntries).toBeLessThanOrEqual(output.length); + } finally { copies.mockRestore(); rewrite.dispose?.(); } + }); + } + test("snapshot-only tool work classifies preceding messages as commentary", () => { const rewrite = createResponsesPhaseInferenceBlockRewrite(createTestTranslatorBudget()); const call = { type: "custom_tool_call", id: "tool", call_id: "read", name: "exec", input: "read source" }; @@ -65,6 +86,16 @@ describe("Responses phase inference block rewrite", () => { rewrite.dispose?.(); }); + test("different explicit IDs cannot borrow unphased snapshot continuation by index", () => { + const rewrite = createResponsesPhaseInferenceBlockRewrite(createTestTranslatorBudget()); + const out = [messageDone(0, "reading"), completed([ + { type: "message", id: "other" }, + { type: "function_call", id: "tool", call_id: "read", name: "shell", arguments: "{}" }, + ])].flatMap(block => rewrite(block)); + expect(out.map(phaseOf)).toEqual(["final_answer", "commentary,"]); + rewrite.dispose?.(); + }); + for (const missingId of ["event", "snapshot"]) { test(`pending snapshot continuation matches by index with a missing ${missingId} id`, () => { const rewrite = createResponsesPhaseInferenceBlockRewrite(createTestTranslatorBudget()); From 487ee4ec67b93cd9f22f702eb4c7868c8e8cc486 Mon Sep 17 00:00:00 2001 From: Reidar Date: Thu, 12 Nov 2026 09:34:51 +0100 Subject: [PATCH 08/11] test(catalog): measure rejection from the actual deadline --- .../catalog-async-lifetime.test.ts | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/tests/codex-integration/catalog-async-lifetime.test.ts b/tests/codex-integration/catalog-async-lifetime.test.ts index 333d2ce1922..ddb8382a24e 100644 --- a/tests/codex-integration/catalog-async-lifetime.test.ts +++ b/tests/codex-integration/catalog-async-lifetime.test.ts @@ -272,10 +272,12 @@ for (const mode of ["abort", "deadline"] as const) { return child; }) as typeof actualExec); const set = globalThis.setTimeout; + let started: number | undefined; + let rejectedAt: number | undefined; // Arm the deadline only after the child has installed its signal handler. const timer = spyOn(globalThis, "setTimeout").mockImplementation(((fn, delay, ...args) => { if (mode === "deadline" && delay === 1234) { - const scheduled = set(() => { void ready.promise.then(() => fn(...args)); }, 0); + const scheduled = set(() => { void ready.promise.then(() => { started = performance.now(); fn(...args); }); }, 0); return scheduled; } return set(fn, delay, ...args); @@ -285,15 +287,16 @@ for (const mode of ["abort", "deadline"] as const) { windowsHide: true, signal: controller.signal, }); // Observe rejection before a fast Windows kill can settle it. - const rejected = pending.then(() => { throw new Error("held child unexpectedly completed"); }, error => error); + const rejected = pending.then(() => { throw new Error("held child unexpectedly completed"); }, error => { rejectedAt = performance.now(); return error; }); try { await Promise.race([ready.promise, Bun.sleep(3000).then(() => { throw new Error("child never became READY"); })]); await new Promise((resolve, reject) => childProcess.execFile(process.execPath, ["-e", "process.exit(0)"], error => error ? reject(error) : resolve())); - const started = Date.now(); - if (mode === "abort") controller.abort(); + if (mode === "abort") { started = performance.now(); controller.abort(); } const error = await rejected; expect(String(error)).toMatch(mode === "abort" ? /abort/i : /deadline|timed out|kill/i); - expect(Date.now() - started).toBeLessThan(1000); + expect(started).toBeDefined(); + expect(rejectedAt! - started!).toBeGreaterThanOrEqual(0); + expect(rejectedAt! - started!).toBeLessThan(1000); const didExit = await Promise.race([ exited.promise.then(() => true), Bun.sleep(SUBPROCESS_KILL_GRACE_MS + 1000).then(() => false), ]); From 1b6a0ba6466ff4e95a679f7442f9e75a40854eed Mon Sep 17 00:00:00 2001 From: Reidar Date: Sat, 14 Nov 2026 01:25:40 +0100 Subject: [PATCH 09/11] fix(test): strip Windows live environment names regardless of case --- .github/scripts/release-evidence-policy.json | 34 ++++++++++++++++++ scripts/test.ts | 5 ++- structure/ops/test-sandbox-cleanup.md | 2 ++ tests/ci-workflows/test-runner.test.ts | 36 ++++++++++++++++++++ 4 files changed, 76 insertions(+), 1 deletion(-) diff --git a/.github/scripts/release-evidence-policy.json b/.github/scripts/release-evidence-policy.json index 96901acc8c5..e4f815096e8 100644 --- a/.github/scripts/release-evidence-policy.json +++ b/.github/scripts/release-evidence-policy.json @@ -874,5 +874,39 @@ "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c", "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d" } + }, + { + "kind": "ci", + "version": 1, + "windowsShards": 14, + "files": { + ".github/workflows/ci.yml": "74f5dfb883786792c872c58f2311b0299818b702", + ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d", + ".github/scripts/release-evidence.cjs": "ace2b9006b2d58ef84ed0996b4e179ff4be15900", + ".github/scripts/release-evidence.test.cjs": "9cc686390e5c37d8e693b98d049e8b505d0273cf", + "scripts/ci/select-test-lane.sh": "b25836cb55f962d1ffd9e68ed00f45f8b45becc8", + "scripts/ci/windows-sensitive-diff.sh": "03495f256c671aff57e750febffe19ca7face6a1", + "scripts/ci/run-bun-test-batches.sh": "f8aa18e80aff1c95c584cd2c879dfbb6806c11fb", + "scripts/ci/bun-crash-signatures.sh": "d34662ddd07864d97bed909135095db33fe42c9e", + "scripts/ci/bun-install-frozen.sh": "e6d7bc3aec044e12297c7c4c04015a33df0eb22b", + "scripts/ci/docker-smoke.ts": "4eea7637d8658156feeaa356c0c3086c00d75fa5", + "scripts/ci/test-durations.tsv": "6ff82545debbd95286928a7a99abfdeb10020a7a", + "scripts/ci/test-durations.windows.tsv": "523cef871c3e17fc0344c98fb15eef79feb04c84", + "scripts/test.ts": "98bf791579ac67d125bd62a54946efce22e8cc72", + "scripts/lib/test-runner-bun.ts": "8763806104a851dbdefeea8cffe8d7dd8d1c8da1", + "scripts/test-temp-lock.ts": "ee83fb254b728de119028f52b9894bf52d7aea15", + "scripts/git-repository-env.ts": "267950490fffb4c48d9adb90bdcf5a873733b324", + "scripts/ci/run-changed-tests.sh": "9a54d3a5db9849bcbe0dd766954a840185419fa5", + "scripts/keyring-smoke.ts": "cd3be07ad57796172696dfa053ea1fb129f29365", + "scripts/privacy-scan.ts": "86314e891b45e49739b94c76cddd9e4cc2d4340f", + "scripts/structure-ssot.ts": "5b2d2918dae877fddfb16cdba6e89f0d10e82298", + "scripts/generate-ocx-skill-surface.ts": "155e866656ba2d71e8fd48adda857451caf16322", + "desktop/scripts/prepare-sidecar.ts": "20f7eec61f73635ea681e25f13dd850b62bb41e2", + "desktop/scripts/build-widget.sh": "38e0eb9d713804b603aa75c32383aa18ef01d06c", + "desktop/scripts/verify-macos-runtime.sh": "43f1a31375c6f6fe7dcafb9d96c231b98d1f6ba4", + "desktop/scripts/verify-linux-sidecar.sh": "c502bb5c8ba8346c722a8f5274f2274bb325a934", + "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c", + "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d" + } } ] diff --git a/scripts/test.ts b/scripts/test.ts index 321e56fc8e8..3e66df4d7de 100644 --- a/scripts/test.ts +++ b/scripts/test.ts @@ -75,7 +75,10 @@ export function createIsolatedTestEnvironment( } writeTestTempOwner(root, baseEnv[TEST_RUN_ID_ENV]); const inherited = { ...baseEnv }; - for (const name of LIVE_INSTALL_ENV) delete inherited[name]; + for (const name of Object.keys(inherited)) { + const match = process.platform === "win32" ? name.toUpperCase() : name; + if (LIVE_INSTALL_ENV.some(liveName => liveName === match)) delete inherited[name]; + } // A GIT_DIR/GIT_WORK_TREE inherited from a hook or wrapper re-points every git command the suite // spawns, and fixture helpers then init, configure and commit into that repository. Starting the // children without them also covers Bun.spawn calls that pass no env (scripts/git-repository-env.ts). diff --git a/structure/ops/test-sandbox-cleanup.md b/structure/ops/test-sandbox-cleanup.md index 4eb7b534c26..fd7183fc1c5 100644 --- a/structure/ops/test-sandbox-cleanup.md +++ b/structure/ops/test-sandbox-cleanup.md @@ -62,6 +62,8 @@ The runner and preload both remove live credentials and `OCX_SERVICE`/`OCX_SERVI before executing tests. A proxy-launched test process must not inherit service-child authority or require its temporary fixture home to own the developer's service. The owner regression in `tests/ci-workflows/test-runner.test.ts` checks service identity removal alongside credential removal. +The runner matches inherited names case-insensitively on Windows, including differently cased +credential and service keys in a copied environment; POSIX keeps case-sensitive name matching. The batch runner's per-process home isolation and live-home/service-manager guards remain active because the preload installs them before the lock boundary. `tests/preload.ts` resolves cleanup diff --git a/tests/ci-workflows/test-runner.test.ts b/tests/ci-workflows/test-runner.test.ts index 120fc4d1dff..b2aa309f1e7 100644 --- a/tests/ci-workflows/test-runner.test.ts +++ b/tests/ci-workflows/test-runner.test.ts @@ -361,6 +361,42 @@ describe("test runner isolation", () => { } }); + for (const platform of ["win32", "linux", "darwin"] as const) { + test(`matches live environment names with ${platform} case semantics`, () => { + const descriptor = Object.getOwnPropertyDescriptor(process, "platform")!; + const baseEnv = { + opencodex_api_auth_token: "fixture-data", + OpenCodex_Admin_Auth_Token: "fixture-admin", + ocx_api_token_file: "fixture-token-file", + ocx_service: "1", + Ocx_Service_Managed: "1", + OCX_SERVICE: "1", + OPENCODEX_API_AUTH_TOKEN: "fixture-uppercase", + OCX_SERVICE_EXTRA: "keep", + FIXTURE: "unchanged", + }; + let isolated: ReturnType | undefined; + try { + Object.defineProperty(process, "platform", { ...descriptor, value: platform }); + isolated = createIsolatedTestEnvironment(baseEnv); + for (const key of [ + "opencodex_api_auth_token", "OpenCodex_Admin_Auth_Token", "ocx_api_token_file", + "ocx_service", "Ocx_Service_Managed", + ] as const) { + expect(isolated.env[key]).toBe(platform === "win32" ? undefined : baseEnv[key]); + } + expect(isolated.env.OCX_SERVICE).toBeUndefined(); + expect(isolated.env.OPENCODEX_API_AUTH_TOKEN).toBeUndefined(); + expect(isolated.env.OCX_SERVICE_EXTRA).toBe("keep"); + expect(isolated.env.FIXTURE).toBe("unchanged"); + expect(baseEnv.ocx_service).toBe("1"); + } finally { + Object.defineProperty(process, "platform", descriptor); + isolated?.cleanup(); + } + }); + } + test.if(process.platform === "win32")("gives the Windows sandbox a real profile shape", () => { const isolated = createIsolatedTestEnvironment({ PATH: "C:\\test\\bin" }); try { From e5400b0e7cb95b40b037912138d4787e4677648d Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 18 Nov 2026 21:35:40 +0900 Subject: [PATCH 10/11] Keep live install state out of Bun tests --- .github/scripts/release-evidence-policy.json | 70 +++++++++++++++++++- scripts/test.ts | 15 +++-- structure/ops/test-sandbox-cleanup.md | 12 ++-- tests/ci-workflows/test-runner.test.ts | 51 +++++++++++++- tests/preload.ts | 14 ++-- 5 files changed, 144 insertions(+), 18 deletions(-) diff --git a/.github/scripts/release-evidence-policy.json b/.github/scripts/release-evidence-policy.json index e4f815096e8..d54057e1e50 100644 --- a/.github/scripts/release-evidence-policy.json +++ b/.github/scripts/release-evidence-policy.json @@ -892,7 +892,75 @@ "scripts/ci/docker-smoke.ts": "4eea7637d8658156feeaa356c0c3086c00d75fa5", "scripts/ci/test-durations.tsv": "6ff82545debbd95286928a7a99abfdeb10020a7a", "scripts/ci/test-durations.windows.tsv": "523cef871c3e17fc0344c98fb15eef79feb04c84", - "scripts/test.ts": "98bf791579ac67d125bd62a54946efce22e8cc72", + "scripts/test.ts": "58c52fd2002c2692b9744dc5ea032af247807367", + "scripts/lib/test-runner-bun.ts": "8763806104a851dbdefeea8cffe8d7dd8d1c8da1", + "scripts/test-temp-lock.ts": "ee83fb254b728de119028f52b9894bf52d7aea15", + "scripts/git-repository-env.ts": "267950490fffb4c48d9adb90bdcf5a873733b324", + "scripts/ci/run-changed-tests.sh": "9a54d3a5db9849bcbe0dd766954a840185419fa5", + "scripts/keyring-smoke.ts": "cd3be07ad57796172696dfa053ea1fb129f29365", + "scripts/privacy-scan.ts": "86314e891b45e49739b94c76cddd9e4cc2d4340f", + "scripts/structure-ssot.ts": "5b2d2918dae877fddfb16cdba6e89f0d10e82298", + "scripts/generate-ocx-skill-surface.ts": "155e866656ba2d71e8fd48adda857451caf16322", + "desktop/scripts/prepare-sidecar.ts": "20f7eec61f73635ea681e25f13dd850b62bb41e2", + "desktop/scripts/build-widget.sh": "38e0eb9d713804b603aa75c32383aa18ef01d06c", + "desktop/scripts/verify-macos-runtime.sh": "43f1a31375c6f6fe7dcafb9d96c231b98d1f6ba4", + "desktop/scripts/verify-linux-sidecar.sh": "c502bb5c8ba8346c722a8f5274f2274bb325a934", + "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c", + "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d" + } + }, + { + "kind": "ci", + "version": 1, + "windowsShards": 14, + "files": { + ".github/workflows/ci.yml": "74f5dfb883786792c872c58f2311b0299818b702", + ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d", + ".github/scripts/release-evidence.cjs": "ace2b9006b2d58ef84ed0996b4e179ff4be15900", + ".github/scripts/release-evidence.test.cjs": "9cc686390e5c37d8e693b98d049e8b505d0273cf", + "scripts/ci/select-test-lane.sh": "b25836cb55f962d1ffd9e68ed00f45f8b45becc8", + "scripts/ci/windows-sensitive-diff.sh": "03495f256c671aff57e750febffe19ca7face6a1", + "scripts/ci/run-bun-test-batches.sh": "59b1783aadf8109c0fa2d37047ff0d90300aa267", + "scripts/ci/bun-crash-signatures.sh": "d34662ddd07864d97bed909135095db33fe42c9e", + "scripts/ci/bun-install-frozen.sh": "e6d7bc3aec044e12297c7c4c04015a33df0eb22b", + "scripts/ci/docker-smoke.ts": "4eea7637d8658156feeaa356c0c3086c00d75fa5", + "scripts/ci/test-durations.tsv": "9dd8d4194c7950c9aaa2e3f96f9225869c854b72", + "scripts/ci/test-durations.windows.tsv": "523cef871c3e17fc0344c98fb15eef79feb04c84", + "scripts/test.ts": "b29da2511aae387c13cace2e66f697b7092e42f2", + "scripts/lib/test-runner-bun.ts": "8763806104a851dbdefeea8cffe8d7dd8d1c8da1", + "scripts/test-temp-lock.ts": "ee83fb254b728de119028f52b9894bf52d7aea15", + "scripts/git-repository-env.ts": "267950490fffb4c48d9adb90bdcf5a873733b324", + "scripts/ci/run-changed-tests.sh": "9a54d3a5db9849bcbe0dd766954a840185419fa5", + "scripts/keyring-smoke.ts": "cd3be07ad57796172696dfa053ea1fb129f29365", + "scripts/privacy-scan.ts": "86314e891b45e49739b94c76cddd9e4cc2d4340f", + "scripts/structure-ssot.ts": "5b2d2918dae877fddfb16cdba6e89f0d10e82298", + "scripts/generate-ocx-skill-surface.ts": "155e866656ba2d71e8fd48adda857451caf16322", + "desktop/scripts/prepare-sidecar.ts": "20f7eec61f73635ea681e25f13dd850b62bb41e2", + "desktop/scripts/build-widget.sh": "38e0eb9d713804b603aa75c32383aa18ef01d06c", + "desktop/scripts/verify-macos-runtime.sh": "43f1a31375c6f6fe7dcafb9d96c231b98d1f6ba4", + "desktop/scripts/verify-linux-sidecar.sh": "c502bb5c8ba8346c722a8f5274f2274bb325a934", + "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c", + "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d" + } + }, + { + "kind": "ci", + "version": 1, + "windowsShards": 14, + "files": { + ".github/workflows/ci.yml": "4ae44e193c6813a0378700f37c1cebaca7327cf1", + ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d", + ".github/scripts/release-evidence.cjs": "ace2b9006b2d58ef84ed0996b4e179ff4be15900", + ".github/scripts/release-evidence.test.cjs": "9cc686390e5c37d8e693b98d049e8b505d0273cf", + "scripts/ci/select-test-lane.sh": "b25836cb55f962d1ffd9e68ed00f45f8b45becc8", + "scripts/ci/windows-sensitive-diff.sh": "03495f256c671aff57e750febffe19ca7face6a1", + "scripts/ci/run-bun-test-batches.sh": "59b1783aadf8109c0fa2d37047ff0d90300aa267", + "scripts/ci/bun-crash-signatures.sh": "d34662ddd07864d97bed909135095db33fe42c9e", + "scripts/ci/bun-install-frozen.sh": "e6d7bc3aec044e12297c7c4c04015a33df0eb22b", + "scripts/ci/docker-smoke.ts": "4eea7637d8658156feeaa356c0c3086c00d75fa5", + "scripts/ci/test-durations.tsv": "a07f90e6098082e1452ea5cc075c801271321eca", + "scripts/ci/test-durations.windows.tsv": "523cef871c3e17fc0344c98fb15eef79feb04c84", + "scripts/test.ts": "c18e561ba35cb72ff83d8e592146dcea8bd1b27f", "scripts/lib/test-runner-bun.ts": "8763806104a851dbdefeea8cffe8d7dd8d1c8da1", "scripts/test-temp-lock.ts": "ee83fb254b728de119028f52b9894bf52d7aea15", "scripts/git-repository-env.ts": "267950490fffb4c48d9adb90bdcf5a873733b324", diff --git a/scripts/test.ts b/scripts/test.ts index 3e66df4d7de..c18e561ba35 100644 --- a/scripts/test.ts +++ b/scripts/test.ts @@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto"; import { existsSync, mkdirSync, mkdtempSync } from "node:fs"; import { homedir, tmpdir } from "node:os"; import { basename, join } from "node:path"; +import { SUPERVISOR_MARKER_ENVS } from "../src/lib/supervisor-markers"; import { gitRepositoryEnvNames, withoutGitRepositoryEnv } from "./git-repository-env"; import { getTestRunnerBun } from "./lib/test-runner-bun"; import { @@ -38,9 +39,16 @@ export const LIVE_INSTALL_ENV = [ "OCX_API_TOKEN_FILE", "OCX_MANAGED_RELEASE", "OCX_SERVICE", - "OCX_SERVICE_MANAGED", + ...SUPERVISOR_MARKER_ENVS, ] as const; +export function liveInstallEnvNames(env: NodeJS.ProcessEnv): string[] { + return Object.keys(env).filter(name => { + const match = process.platform === "win32" ? name.toUpperCase() : name; + return LIVE_INSTALL_ENV.some(liveName => liveName === match); + }); +} + export function createIsolatedTestEnvironment( baseEnv: Record = process.env, ): IsolatedTestEnvironment { @@ -75,10 +83,7 @@ export function createIsolatedTestEnvironment( } writeTestTempOwner(root, baseEnv[TEST_RUN_ID_ENV]); const inherited = { ...baseEnv }; - for (const name of Object.keys(inherited)) { - const match = process.platform === "win32" ? name.toUpperCase() : name; - if (LIVE_INSTALL_ENV.some(liveName => liveName === match)) delete inherited[name]; - } + for (const name of liveInstallEnvNames(inherited)) delete inherited[name]; // A GIT_DIR/GIT_WORK_TREE inherited from a hook or wrapper re-points every git command the suite // spawns, and fixture helpers then init, configure and commit into that repository. Starting the // children without them also covers Bun.spawn calls that pass no env (scripts/git-repository-env.ts). diff --git a/structure/ops/test-sandbox-cleanup.md b/structure/ops/test-sandbox-cleanup.md index fd7183fc1c5..dabff1151e4 100644 --- a/structure/ops/test-sandbox-cleanup.md +++ b/structure/ops/test-sandbox-cleanup.md @@ -58,12 +58,12 @@ paths, delayed generation transitions, member/release ordering and gate-holder d ## Sandbox lifecycle -The runner and preload both remove live credentials and `OCX_SERVICE`/`OCX_SERVICE_MANAGED` -before executing tests. A proxy-launched test process must not inherit service-child authority -or require its temporary fixture home to own the developer's service. The owner regression in -`tests/ci-workflows/test-runner.test.ts` checks service identity removal alongside credential removal. -The runner matches inherited names case-insensitively on Windows, including differently cased -credential and service keys in a copied environment; POSIX keeps case-sensitive name matching. +`scripts/test.ts` removes live credential keys, `OCX_SERVICE`, and the markers from +`src/lib/supervisor-markers.ts` before spawning test processes. Bun 1.4.4 can pass its startup +environment to children spawned without an explicit environment. When Bun loads `tests/preload.ts`, +the preload refuses to run tests if any of those keys are present and directs callers to +`bun run test`. Both paths match names case-insensitively on Windows and case-sensitively on POSIX. +`tests/ci-workflows/test-runner.test.ts` covers the scrub, bare-run refusal, and child inheritance. The batch runner's per-process home isolation and live-home/service-manager guards remain active because the preload installs them before the lock boundary. `tests/preload.ts` resolves cleanup diff --git a/tests/ci-workflows/test-runner.test.ts b/tests/ci-workflows/test-runner.test.ts index b2aa309f1e7..3854c29518a 100644 --- a/tests/ci-workflows/test-runner.test.ts +++ b/tests/ci-workflows/test-runner.test.ts @@ -348,12 +348,16 @@ describe("test runner isolation", () => { OCX_MANAGED_RELEASE: "1", OCX_SERVICE: "1", OCX_SERVICE_MANAGED: "1", + OCX_WINDOWS_WRAPPER_PROTOCOL: "1", + OCX_DESKTOP_SUPERVISED: "1", }); try { for (const name of LIVE_INSTALL_ENV) expect(name in isolated.env).toBe(false); expect("OCX_MANAGED_RELEASE" in isolated.env).toBe(false); expect(isolated.env.OCX_SERVICE).toBeUndefined(); expect(isolated.env.OCX_SERVICE_MANAGED).toBeUndefined(); + expect(isolated.env.OCX_WINDOWS_WRAPPER_PROTOCOL).toBeUndefined(); + expect(isolated.env.OCX_DESKTOP_SUPERVISED).toBeUndefined(); expect(isolated.env.FIXTURE).toBe("unchanged"); expect(isolated.env.PATH).toBe("/test/bin"); } finally { @@ -370,6 +374,8 @@ describe("test runner isolation", () => { ocx_api_token_file: "fixture-token-file", ocx_service: "1", Ocx_Service_Managed: "1", + Ocx_Windows_Wrapper_Protocol: "1", + ocx_desktop_supervised: "1", OCX_SERVICE: "1", OPENCODEX_API_AUTH_TOKEN: "fixture-uppercase", OCX_SERVICE_EXTRA: "keep", @@ -381,7 +387,7 @@ describe("test runner isolation", () => { isolated = createIsolatedTestEnvironment(baseEnv); for (const key of [ "opencodex_api_auth_token", "OpenCodex_Admin_Auth_Token", "ocx_api_token_file", - "ocx_service", "Ocx_Service_Managed", + "ocx_service", "Ocx_Service_Managed", "Ocx_Windows_Wrapper_Protocol", "ocx_desktop_supervised", ] as const) { expect(isolated.env[key]).toBe(platform === "win32" ? undefined : baseEnv[key]); } @@ -984,7 +990,13 @@ describe("bun test argv", () => { mkdirSync(sentinelTemp); writeFileSync( fixturePath, - `import { test } from "bun:test"; import { writeFileSync } from "node:fs"; test("smoke", () => writeFileSync(${JSON.stringify(markerPath)}, "executed"));\n`, + `import { expect, test } from "bun:test"; + import { writeFileSync } from "node:fs"; + test("smoke", () => { + const child = Bun.spawnSync([process.execPath, "-e", "process.exit(Number('OCX_WINDOWS_WRAPPER_PROTOCOL' in process.env))"]); + expect(child.exitCode).toBe(0); + writeFileSync(${JSON.stringify(markerPath)}, "executed"); + });\n`, ); try { const result = Bun.spawnSync([ @@ -999,6 +1011,7 @@ describe("bun test argv", () => { TMP: sentinelTemp, TMPDIR: sentinelTemp, OCX_TEST_NO_QUEUE: "1", + OCX_WINDOWS_WRAPPER_PROTOCOL: "1", }, stdout: "pipe", stderr: "pipe", @@ -1015,6 +1028,40 @@ describe("bun test argv", () => { } }, { timeout: SPAWN_BUDGET_MS }); + test.each(["serial", "parallel"] as const)( + "refuses a bare %s run with a live-install marker before executing the test file", + mode => { + const fixtureRoot = mkdtempSync(join(tmpdir(), "opencodex-bare-live-install-")); + const fixturePath = join(fixtureRoot, "bare-live-install.test.ts"); + const markerPath = join(fixtureRoot, "loaded.marker"); + writeFileSync(fixturePath, ` + import { test } from "bun:test"; + import { writeFileSync } from "node:fs"; + writeFileSync(${JSON.stringify(markerPath)}, "loaded"); + test("fixture", () => {}); + `); + try { + const envName = mode === "serial" ? "OPENCODEX_API_AUTH_TOKEN" + : process.platform === "win32" ? "Ocx_Windows_Wrapper_Protocol" : "OCX_WINDOWS_WRAPPER_PROTOCOL"; + const result = Bun.spawnSync([ + process.execPath, "test", ...(mode === "parallel" ? ["--parallel=1"] : []), fixturePath, + ], { + cwd: repoRoot(), + env: { ...process.env, [envName]: "1", OCX_TEST_NO_QUEUE: "1" }, + stdout: "pipe", + stderr: "pipe", + timeout: INTERNAL_DEADLINE_MS, + }); + expect(result.exitCode).toBe(1); + expect(result.stderr.toString()).toContain("bun run test"); + expect(existsSync(markerPath)).toBe(false); + } finally { + removeTreeWithRetry(fixtureRoot); + } + }, + { timeout: SPAWN_BUDGET_MS }, + ); + test.each(["pass", "fail"] as const)( "a bare %s run removes its preload-owned TEMP root", outcome => { diff --git a/tests/preload.ts b/tests/preload.ts index daff7216b09..dd171edbb5d 100644 --- a/tests/preload.ts +++ b/tests/preload.ts @@ -27,7 +27,7 @@ */ import { afterAll, afterEach } from "bun:test"; import { isTestHomeGuardArmed, protectedHomeForTests } from "../src/lib/test-home-guard"; -import { createIsolatedTestEnvironment, LIVE_INSTALL_ENV } from "../scripts/test"; +import { createIsolatedTestEnvironment, liveInstallEnvNames } from "../scripts/test"; import { gitRepositoryEnvNames } from "../scripts/git-repository-env"; import { createGitConfigGuard } from "./helpers/git-config-guard"; import { installNetworkEgressGuard } from "./helpers/network-egress-guard"; @@ -42,6 +42,14 @@ import { TEST_RUN_LOCK_TOKEN_ENV, } from "../scripts/test-run-lock"; +// Bun.spawn with no explicit env can inherit the startup environment after process.env +// has been edited. Exit before a test file can run, including in a parallel worker. +const liveInstallNames = liveInstallEnvNames(process.env); +if (liveInstallNames.length > 0) { + console.error(`[test] refusing to run with live-install environment keys (${liveInstallNames.join(", ")}). Run through \`bun run test\` or unset those keys.`); + process.exit(1); +} + // Under `bun run test` the wrapper already handed us a sandbox (and OCX_REAL_HOME so the // guard could still see the true home). Isolating again is harmless and deliberate: the // alternative — inferring "already isolated" from path shapes — would trust exactly the @@ -50,9 +58,7 @@ const isolated = createIsolatedTestEnvironment(); for (const [key, value] of Object.entries(isolated.env)) { if (value !== undefined) process.env[key] = value; } -// The sandbox drops these from its env, but this process started with them, so remove them here. -for (const name of LIVE_INSTALL_ENV) delete process.env[name]; -// Same for an inherited GIT_DIR/GIT_WORK_TREE (scripts/git-repository-env.ts). Deleting them reaches +// Drop inherited GIT_DIR/GIT_WORK_TREE (scripts/git-repository-env.ts). Deleting them reaches // node:child_process and spread envs only: Bun.spawn without an `env` option keeps the environment // this process started with, which is why tests/helpers/git-fixture.ts always passes one. const inheritedGitEnv = gitRepositoryEnvNames(process.env); From 419a94f23a3d5a575a97339da6fd0bf48a263758 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 18 Nov 2026 21:50:31 +0900 Subject: [PATCH 11/11] Fix nested Bun test environment and dotenv guidance --- structure/ops/test-sandbox-cleanup.md | 8 +++++--- tests/clients/route-intent-runtime-stop.test.ts | 2 +- tests/preload.ts | 2 +- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/structure/ops/test-sandbox-cleanup.md b/structure/ops/test-sandbox-cleanup.md index dabff1151e4..80d4d38d819 100644 --- a/structure/ops/test-sandbox-cleanup.md +++ b/structure/ops/test-sandbox-cleanup.md @@ -58,11 +58,13 @@ paths, delayed generation transitions, member/release ordering and gate-holder d ## Sandbox lifecycle -`scripts/test.ts` removes live credential keys, `OCX_SERVICE`, and the markers from +`scripts/test.ts` removes inherited live credential keys, `OCX_SERVICE`, and the markers from `src/lib/supervisor-markers.ts` before spawning test processes. Bun 1.4.4 can pass its startup environment to children spawned without an explicit environment. When Bun loads `tests/preload.ts`, -the preload refuses to run tests if any of those keys are present and directs callers to -`bun run test`. Both paths match names case-insensitively on Windows and case-sensitively on POSIX. +the preload refuses to run tests if any of those keys are present. Use `bun run test` or unset +inherited keys. Remove the listed keys from any dotenv files Bun loads, including `.env.test`, +because Bun can load those files again in the test process. Both paths match names +case-insensitively on Windows and case-sensitively on POSIX. `tests/ci-workflows/test-runner.test.ts` covers the scrub, bare-run refusal, and child inheritance. The batch runner's per-process home isolation and live-home/service-manager guards remain active diff --git a/tests/clients/route-intent-runtime-stop.test.ts b/tests/clients/route-intent-runtime-stop.test.ts index 6eb574de463..6de8b64e092 100644 --- a/tests/clients/route-intent-runtime-stop.test.ts +++ b/tests/clients/route-intent-runtime-stop.test.ts @@ -70,7 +70,7 @@ test("runtime recycle cancels its watch and tick before replacement handoff", () const child = spawnSync(process.execPath, ["test", "--preload", repoPath("tests/preload.ts"), fixture], { cwd: repoRoot(), timeout: SPAWN_BUDGET_MS - 5_000, encoding: "utf8", env: { ...process.env, HOME: home.root, USERPROFILE: home.root, OPENCODEX_HOME: home.root, CODEX_HOME: home.codexHome, - OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR: join(home.root, "desktop"), OCX_SERVICE: "", OCX_DESKTOP_SUPERVISED: "" }, + OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR: join(home.root, "desktop") }, }); expect({ status: child.status, stderr: child.stderr, error: child.error?.message }).toMatchObject({ status: 0 }); } finally { home.remove(); } diff --git a/tests/preload.ts b/tests/preload.ts index dd171edbb5d..7a89f6bf4ec 100644 --- a/tests/preload.ts +++ b/tests/preload.ts @@ -46,7 +46,7 @@ import { // has been edited. Exit before a test file can run, including in a parallel worker. const liveInstallNames = liveInstallEnvNames(process.env); if (liveInstallNames.length > 0) { - console.error(`[test] refusing to run with live-install environment keys (${liveInstallNames.join(", ")}). Run through \`bun run test\` or unset those keys.`); + console.error(`[test] refusing to run with live-install environment keys (${liveInstallNames.join(", ")}). Remove the listed keys from any dotenv files Bun loads (such as .env.test). For inherited keys, run through \`bun run test\` or unset them.`); process.exit(1); }