diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index 2c55f34f9d8..1d91b2a7081 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -1992,6 +1992,6 @@ "responses-claude-preflight-lease.test.ts": "responses", "injection-routing-drift.test.ts": "codex-integration", "injection-routing-healer.test.ts": "codex-integration", "injection-routing-heal-apply.test.ts": "codex-integration", "cli-start-routing-heal-wiring.test.ts": "cli", - "cli-status-codex-routing-drift.test.ts": "cli", "advisor-settings.test.ts": "advisor", "advisor-context.test.ts": "advisor", "advisor-state.test.ts": "advisor", "advisor-guard.test.ts": "advisor", "advisor-consult.test.ts": "advisor", "advisor-plan.test.ts": "advisor", "advisor-responses-wiring.test.ts": "advisor", "advisor-routes.test.ts": "server", "advisor-internal-authority.test.ts": "advisor", "advisor-core-boundary.test.ts": "advisor", "advisor-continuation-limit.test.ts": "advisor", "advisor-authority-transport.test.ts": "advisor", "advisor-evidence.test.ts": "advisor", "advisor-budget.test.ts": "advisor", "advisor-adaptive.test.ts": "advisor", "advisor-scope-transport.test.ts": "advisor", "local-credentials.test.ts": "cli", "local-credential-fence.test.ts": "config", "local-credential-generation.test.ts": "config", "link-websocket-upgrade.test.ts": "server", "link-websocket-gate.test.ts": "server", "link-websocket-drain.test.ts": "server", "link-websocket-pump.test.ts": "server", "link-websocket-rss.test.ts": "e2e-style", "link-websocket-holds.test.ts": "server", "link-websocket-traffic.test.ts": "server", "link-ws-activity-holds.test.ts": "clients", "link-websocket-fingerprints.test.ts": "server", "link-activity-holds-routes.test.ts": "server", "link-ws-activity-holds-operator.test.ts": "clients", "cli-link-activity.test.ts": "cli", "link-child-ops-ignore-activity.test.ts": "clients", "link-request-log-fields.test.ts": "server", "link-websocket-transport-status.test.ts": "server", "link-websocket-release-gate.test.ts": "e2e-style" + "cli-status-codex-routing-drift.test.ts": "cli", "advisor-settings.test.ts": "advisor", "advisor-context.test.ts": "advisor", "advisor-state.test.ts": "advisor", "advisor-guard.test.ts": "advisor", "advisor-consult.test.ts": "advisor", "advisor-plan.test.ts": "advisor", "advisor-responses-wiring.test.ts": "advisor", "advisor-routes.test.ts": "server", "advisor-internal-authority.test.ts": "advisor", "advisor-core-boundary.test.ts": "advisor", "advisor-continuation-limit.test.ts": "advisor", "advisor-authority-transport.test.ts": "advisor", "advisor-evidence.test.ts": "advisor", "advisor-budget.test.ts": "advisor", "advisor-adaptive.test.ts": "advisor", "advisor-scope-transport.test.ts": "advisor", "local-credentials.test.ts": "cli", "local-credential-fence.test.ts": "config", "local-credential-generation.test.ts": "config", "link-websocket-upgrade.test.ts": "server", "link-websocket-gate.test.ts": "server", "link-websocket-drain.test.ts": "server", "link-websocket-pump.test.ts": "server", "link-websocket-rss.test.ts": "e2e-style", "link-websocket-holds.test.ts": "server", "link-websocket-traffic.test.ts": "server", "link-ws-activity-holds.test.ts": "clients", "link-websocket-fingerprints.test.ts": "server", "link-activity-holds-routes.test.ts": "server", "link-ws-activity-holds-operator.test.ts": "clients", "cli-link-activity.test.ts": "cli", "link-child-ops-ignore-activity.test.ts": "clients", "link-request-log-fields.test.ts": "server", "link-websocket-transport-status.test.ts": "server", "link-websocket-release-gate.test.ts": "e2e-style", "link-gate-codex-binary.test.ts": "e2e-style" } } diff --git a/structure/remote-link.md b/structure/remote-link.md index 0d028d2b880..05a79934d8b 100644 --- a/structure/remote-link.md +++ b/structure/remote-link.md @@ -216,7 +216,7 @@ The link listener's websocket handler wraps the shared Responses handler with 8 DELETE `/api/link/:id`, which `ocx link revoke` calls, closes that link's sockets with 4401 in the same task as its commit, including a socket already upgraded but not yet opened, which closes as soon as Bun opens it, and last-link `close()` refuses further link upgrades and closes every link socket before it drains. Process `stop()` stays forceful. A change made any other way (the API-key routes, a rotation that expires, another process, a hand edit) stops new turns at the next frame and running turns at the sweep, which runs every 30 s only while a link socket exists. Switching either setting off starts a drain on each open link socket, at the first sweep or frame that sees it off. The drain never cancels a running turn: a `response.create` that arrives while a turn runs is dropped and the socket closes with 1000 after that turn; with no turn running, a create is admitted only when it returns a result the socket is waiting for (`returnsPending` in `src/codex/websocket-activity.ts`) and nothing is untracked, so the tool loop that was running continues; any other create, and every create 60 minutes after the drain began, fences and closes the socket. A draining socket that becomes idle closes. Outside a drain, a link socket idle for 10 minutes closes with 1000, and one older than 60 minutes closes at its next idle moment so it re-authenticates; a busy socket is never closed on a timer. When the shared 128-socket gate is full, a link upgrade may reclaim the least recently used idle link socket (`tryReserveCodexWebSocket({ reclaim: "link" })`), never a local one. A link socket counts in the per-link activity book (`beginSocket` in `src/link/child-activity.ts`) while it is busy, that is while a turn runs, a client tool or approval result is pending, results are untracked or it is closing, so activity-gated Child restarts wait for it; the busy-to-idle transition stamps the last data end. A socket that closes while busy ends its count. Coverage: `tests/server/link-websocket-upgrade.test.ts` (a real Home: switched-off characterization, a turn, S2, revocation, same-size and same-mtime edits, native control, close and stop) and `tests/server/link-websocket-gate.test.ts` (each lease transition, caps, budget, no eviction, the sweep on an injected timer, an upgrade racing last-link `close()`), and `tests/server/link-websocket-drain.test.ts` (each drain row, the deadline, idle and age closes, socket activity, link-only reclaim), and `tests/server/link-websocket-pump.test.ts` (the 5 MiB bound with a stalled reader, framing slices, the drain wiring, the stall bound). -A link socket that closes while busy, for any reason except revocation, leaves a durable activity hold (`src/link/ws-activity-holds.ts`, `/link/activity-holds.json`): the HMAC of its own thread id (the `thread-id` handshake header, else the first create's `client_metadata.thread_id`) under a private key in `/link/activity-ref-key`, the hashed result keys it was waiting for, one running mark per turn that was running (a fingerprint, or unknown; below), and whether its results were untracked. Holds count in the link's activity `inFlight`, one each and one more for an unknown link, so the existing activity gates withhold automatic and activity-gated Child restarts. A later request from the same link and own thread that returns pending results, over the link WebSocket once every admission accepted the turn and its pipeline answered ok (a warmup, a refused or a failed create releases nothing); on the link socket itself, a turn that is refused or fails puts the results it returned back to pending, so a later busy close still leaves a hold, while local sockets keep settling results when a turn begins; a call that reuses an id while an older turn on the same socket could still put that id back makes the socket untracked, because the key cannot tell the two calls apart; and an upstream output item never settles a link socket's pending client call, since provider-executed calls never become pending or a relayed `POST /v1/responses` (whose body copy is taken only while the link has a releasable hold and read only after the handler answered below 400: a refusal, the inbound body budget's 503 included, cancels the copy unread (#8608); an accepted copy is decoded through `decodeRequestBody` under the listener's resolved inbound limit, the same `maxInboundBodyBytes` resolution the handler uses, so a body the Child sent zstd-coded (#8594) releases like a plain one and a body that does not decode releases nothing), removes those keys; a hold ends when no key, running mark or untracked flag is left. A running mark carries the fingerprint of the cut request. `src/server/link-turn.ts` is the seam through which `prepareResponsesRequest` reports a link turn's input right after continuation expansion and before upstream I/O, and the final request log reports its terminal status and provenance. A link socket passes one observer per turn in the `handleResponses` options; each writes and clears only its own entry in a per-socket map keyed by the handler's turn id (pending, then `{ n, inputHmac, turnRef }` over the canonical JSON of the expanded items and Codex's `client_metadata.turn_id`, or unknown; done at its own terminal; removed by its own cleanup). The close snapshot turns each pending or unknown entry, and each running turn without an entry, into an unknown mark. A relayed HTTP request reaches the seam only while its link holds a fingerprinted mark, through a random per-request token header that the relay sets after removing any peer copy and the pipeline removes before anything is forwarded; the relay's decision, made when the handler answers or when the request aborts first, drops a token preparation never claimed. A mark is released only by a later request from the same link that is an inference request (`generate` is not false) of the same own thread and turn, whose first `n` expanded items have the same HMAC, and whose terminal is `completed` with upstream provenance (rules (a)-(d) of the design). Each stored mark has its own random id, and a release removes only the marks that request matched at its expansion, never an identical mark created after it; a failed, synthesized or unattributed terminal, another turn or thread, and an input that does not extend the cut one never match. Unknown marks, holds without a thread id and untracked holds are released only by the operator; nothing releases a hold on a timer, and link removal deletes the link's holds. The operator's view and clear (owner decision D8): `?children=1` status rows carry `child.holds` (each hold's reasons, `pending-results`, `running-turn`, `running-unknown`, `untracked` or `no-thread`, its counts and since, plus the link's unknown reason) only while something holds that link, so the default document and the children document of an unheld Home are unchanged; nothing hashed leaves the store. `ocx link activity clear --link-id` (`POST /api/link/children/activity/clear`, exactly `{ linkId }`, the Child-operations auth, refused on a Child runtime) forgets one link's holds and unknown state: the holds file is written without the link before memory forgets it, so a failed write clears nothing (503), and an all-links unknown state from unreadable links is first written per link, so a clear while links still cannot be listed is refused (503). In a process that has not armed the fence (no link socket since start), the clear sets the fence running first; the durable holds write is the commit point. If it fails, even after its rename, the fence stays running, the clear answers 503 and the next start keeps every link unknown. Once it succeeded the clear is committed and the fence is set clean; a clean write that fails can leave it running (every link unknown at the next start) or clean (the committed clear), and neither contradicts the answer. An armed process keeps the fence running until its graceful stop. The other half of D8 is the explicit restart override: `ignoreActivity: true` on a Child operation (`ocx link sync --link-id --restart-* --ignore-activity`, `ocx link restart-codex ... --ignore-activity`) is accepted only as true, on a sync or restart-codex operation with a restart and exactly one link id (an update keeps its gate); the engine copies it onto the job only for a manual request, and the runners then skip the activity gate (relayed requests and holds alike) for that item, logging the link id and its in-flight count. Platform, Child-kind and sync refusals still apply, the scheduler and `ocx sync --restart-children` never set it, and a job without it is unchanged. Request-log fields (design 9.1): while the link WebSocket feature is on (switch and release gate), a link request's final row carries an optional `link` object, validated by `src/usage/link-log-fields.ts` for the in-memory log and usage.jsonl alike: `transport` (`websocket` for a link socket turn, `http` for a relayed `POST /v1/responses`), `continuation` (`chained` when `previous_response_id` was expanded locally or left for an upstream that owns the history; `miss` with the replay failure's reason, or `missing` when preparation refuses an unexpanded continuation; `full` otherwise, reason `first` for a socket's first turn and `client` for the rest and for HTTP), and `threadRef`/`turnRef`, HMAC-SHA256 under the activity reference key with a domain of their own per kind and the link id as a separate field, so one id gives unrelated refs on two links; never the raw ids. The relay sets its turn token on every relayed `POST /v1/responses` while the feature is on, and only while marks exist otherwise; with the switch unset no link row gains a field. Requests that never reach preparation, and local requests, carry none. Live counters (design 9.3): `GET /api/link/status?transport=1` (what `ocx link status` asks for) adds to every current link row `ws: { open, upgrades, refused{reason}, closes{reason}, holds }`. The gate counts admitted upgrades, refusals by reason (`aborted`, `draining`, `unauthorized`, `unavailable`, `memory`, `cap`, `failed`) and closes by reason (its own fences `revoked`, `disabled`, `idle`, `age`, else the peer's code: `client`, `dropped`, `other`); `open` is the current socket count and `holds` the link's hold count. They are in memory, display only, reset at restart, and dropped with the link; without the query, and with the feature off, the documents are unchanged. Release gate (design 11.1 item 13): `tests/e2e-style/link-websocket-release-gate.test.ts` drives the pinned Codex binary (`OCX_LINK_GATE_CODEX`, codex-rs built at openai/codex 88c5856; every case is skipped with that reason when it is absent) through `tests/fixtures/link-child-relay-standin.ts`, a test-only stand-in for the Child's relay (challenge, bearer upgrade, its own 101 with the 8 MiB limit, 426 to Codex on a Home refusal). The scenarios are: the switch going off under a running turn (it finishes, its tool result is admitted, the idle socket is fenced, and the next session ends on HTTP); the drain past its deadline within one session (a zero deadline through the test-only `setLinkWebsocketLimitsForTests`: the session's tool-result create is fenced on the socket, never reaches the upstream, and the same request completes over HTTP after Codex's retry is refused an upgrade); a request over 8 MiB going over HTTP, and a Home restart mid-turn completing. The 503 sequence while the Child's tunnel reconnects runs the real Child listener (lane T6) with a tunnel gate the test drives: two 503s and then the socket on the WebSocket, and, separately, 503s through Codex's whole retry budget and then the same request once over HTTP. A run counts as release evidence only when the binary's sha256 equals the digest recorded for openai/codex 88c5856 in `tests/fixtures/link-gate-codex.json`, which changes only through review and records none until a build is attested; any other executable is labelled a smoke check in every test title. The stand-in records each create forwarded on a socket and each HTTP request, so the oversize case proves the request never went on the socket (with a control run that drops the advertised limit) and the restart case proves the stalled request was the socket's. The clear is logged with the link id and counts only, and nothing calls it automatically. The management routes reach the store through the optional-listener facade (`src/server/index/optional-listeners.ts` forwards `linkHolds`, `clearLinkHolds` and `linkTransport`); a listener without the clear hook answers 503 `activity_holds_unavailable`, never an empty success. Before the first link upgrade of a process, `/link/ws-run-state.json` is written durably as `running` (a private temp file, content fsync, rename, and a directory fsync whose failure fails the write; Windows has no directory fsync); if that write fails, link upgrades are refused. The holds file and the reference key use the same write. A graceful stop writes the holds and then `clean`; an all-links unknown state that is still only in memory is first written per link, and if the links still cannot be listed the fence stays `running`. A start that finds `running` or an unreadable fence makes every link unknown, persists that, and only then cleans the fence; if `links.json` cannot be read at that moment every link counts as unknown and the fence stays `running`. A reference key that cannot be loaded or replaced does not stop the Home: every link stays unknown and nothing is cleaned. a corrupt holds file, overflow (64 per link, 1,024 in total), a failed hold write or a replaced reference key also make the link unknown. No file is read or written unless a fence exists or an upgrade arms one. Coverage: `tests/clients/link-ws-activity-holds.test.ts` (fence, corruption, overflow, write failure, key rotation, release rules, SIGKILL at each durability point) and `tests/server/link-websocket-holds.test.ts` (busy, idle and revoked closes, release over the WebSocket and over HTTP, a fence that cannot be written). +A link socket that closes while busy, for any reason except revocation, leaves a durable activity hold (`src/link/ws-activity-holds.ts`, `/link/activity-holds.json`): the HMAC of its own thread id (the `thread-id` handshake header, else the first create's `client_metadata.thread_id`) under a private key in `/link/activity-ref-key`, the hashed result keys it was waiting for, one running mark per turn that was running (a fingerprint, or unknown; below), and whether its results were untracked. Holds count in the link's activity `inFlight`, one each and one more for an unknown link, so the existing activity gates withhold automatic and activity-gated Child restarts. A later request from the same link and own thread that returns pending results, over the link WebSocket once every admission accepted the turn and its pipeline answered ok (a warmup, a refused or a failed create releases nothing); on the link socket itself, a turn that is refused or fails puts the results it returned back to pending, so a later busy close still leaves a hold, while local sockets keep settling results when a turn begins; a call that reuses an id while an older turn on the same socket could still put that id back makes the socket untracked, because the key cannot tell the two calls apart; and an upstream output item never settles a link socket's pending client call, since provider-executed calls never become pending or a relayed `POST /v1/responses` (whose body copy is taken only while the link has a releasable hold and read only after the handler answered below 400: a refusal, the inbound body budget's 503 included, cancels the copy unread (#8608); an accepted copy is decoded through `decodeRequestBody` under the listener's resolved inbound limit, the same `maxInboundBodyBytes` resolution the handler uses, so a body the Child sent zstd-coded (#8594) releases like a plain one and a body that does not decode releases nothing), removes those keys; a hold ends when no key, running mark or untracked flag is left. A running mark carries the fingerprint of the cut request. `src/server/link-turn.ts` is the seam through which `prepareResponsesRequest` reports a link turn's input right after continuation expansion and before upstream I/O, and the final request log reports its terminal status and provenance. A link socket passes one observer per turn in the `handleResponses` options; each writes and clears only its own entry in a per-socket map keyed by the handler's turn id (pending, then `{ n, inputHmac, turnRef }` over the canonical JSON of the expanded items and Codex's `client_metadata.turn_id`, or unknown; done at its own terminal; removed by its own cleanup). The close snapshot turns each pending or unknown entry, and each running turn without an entry, into an unknown mark. A relayed HTTP request reaches the seam only while its link holds a fingerprinted mark, through a random per-request token header that the relay sets after removing any peer copy and the pipeline removes before anything is forwarded; the relay's decision, made when the handler answers or when the request aborts first, drops a token preparation never claimed. A mark is released only by a later request from the same link that is an inference request (`generate` is not false) of the same own thread and turn, whose first `n` expanded items have the same HMAC, and whose terminal is `completed` with upstream provenance (rules (a)-(d) of the design). Each stored mark has its own random id, and a release removes only the marks that request matched at its expansion, never an identical mark created after it; a failed, synthesized or unattributed terminal, another turn or thread, and an input that does not extend the cut one never match. Unknown marks, holds without a thread id and untracked holds are released only by the operator; nothing releases a hold on a timer, and link removal deletes the link's holds. The operator's view and clear (owner decision D8): `?children=1` status rows carry `child.holds` (each hold's reasons, `pending-results`, `running-turn`, `running-unknown`, `untracked` or `no-thread`, its counts and since, plus the link's unknown reason) only while something holds that link, so the default document and the children document of an unheld Home are unchanged; nothing hashed leaves the store. `ocx link activity clear --link-id` (`POST /api/link/children/activity/clear`, exactly `{ linkId }`, the Child-operations auth, refused on a Child runtime) forgets one link's holds and unknown state: the holds file is written without the link before memory forgets it, so a failed write clears nothing (503), and an all-links unknown state from unreadable links is first written per link, so a clear while links still cannot be listed is refused (503). In a process that has not armed the fence (no link socket since start), the clear sets the fence running first; the durable holds write is the commit point. If it fails, even after its rename, the fence stays running, the clear answers 503 and the next start keeps every link unknown. Once it succeeded the clear is committed and the fence is set clean; a clean write that fails can leave it running (every link unknown at the next start) or clean (the committed clear), and neither contradicts the answer. An armed process keeps the fence running until its graceful stop. The other half of D8 is the explicit restart override: `ignoreActivity: true` on a Child operation (`ocx link sync --link-id --restart-* --ignore-activity`, `ocx link restart-codex ... --ignore-activity`) is accepted only as true, on a sync or restart-codex operation with a restart and exactly one link id (an update keeps its gate); the engine copies it onto the job only for a manual request, and the runners then skip the activity gate (relayed requests and holds alike) for that item, logging the link id and its in-flight count. Platform, Child-kind and sync refusals still apply, the scheduler and `ocx sync --restart-children` never set it, and a job without it is unchanged. Request-log fields (design 9.1): while the link WebSocket feature is on (switch and release gate), a link request's final row carries an optional `link` object, validated by `src/usage/link-log-fields.ts` for the in-memory log and usage.jsonl alike: `transport` (`websocket` for a link socket turn, `http` for a relayed `POST /v1/responses`), `continuation` (`chained` when `previous_response_id` was expanded locally or left for an upstream that owns the history; `miss` with the replay failure's reason, or `missing` when preparation refuses an unexpanded continuation; `full` otherwise, reason `first` for a socket's first turn and `client` for the rest and for HTTP), and `threadRef`/`turnRef`, HMAC-SHA256 under the activity reference key with a domain of their own per kind and the link id as a separate field, so one id gives unrelated refs on two links; never the raw ids. The relay sets its turn token on every relayed `POST /v1/responses` while the feature is on, and only while marks exist otherwise; with the switch unset no link row gains a field. Requests that never reach preparation, and local requests, carry none. Live counters (design 9.3): `GET /api/link/status?transport=1` (what `ocx link status` asks for) adds to every current link row `ws: { open, upgrades, refused{reason}, closes{reason}, holds }`. The gate counts admitted upgrades, refusals by reason (`aborted`, `draining`, `unauthorized`, `unavailable`, `memory`, `cap`, `failed`) and closes by reason (its own fences `revoked`, `disabled`, `idle`, `age`, else the peer's code: `client`, `dropped`, `other`); `open` is the current socket count and `holds` the link's hold count. They are in memory, display only, reset at restart, and dropped with the link; without the query, and with the feature off, the documents are unchanged. Release gate (design 11.1 item 13): `tests/e2e-style/link-websocket-release-gate.test.ts` drives the pinned Codex binary (`OCX_LINK_GATE_CODEX`, codex-rs built at openai/codex 88c5856; every Codex scenario is skipped with that reason when it is absent, and the pin test always runs) through `tests/fixtures/link-child-relay-standin.ts`, a test-only stand-in for the Child's relay (challenge, bearer upgrade, its own 101 with the 8 MiB limit, 426 to Codex on a Home refusal). The scenarios are: the switch going off under a running turn (it finishes, its tool result is admitted, the idle socket is fenced, and the next session ends on HTTP); the drain past its deadline within one session (a zero deadline through the test-only `setLinkWebsocketLimitsForTests`: the session's tool-result create is fenced on the socket, never reaches the upstream, and the same request completes over HTTP after Codex's retry is refused an upgrade); a request over 8 MiB going over HTTP, and a Home restart mid-turn completing. The 503 sequence while the Child's tunnel reconnects runs the real Child listener (lane T6) with a tunnel gate the test drives: two 503s and then the socket on the WebSocket, and, separately, 503s through Codex's whole retry budget and then the same request once over HTTP. A run counts as release evidence only when the sha256 of the executable it runs equals the digest recorded for openai/codex 88c5856 in `tests/fixtures/link-gate-codex.json`, which changes only through review: the test resolves `OCX_LINK_GATE_CODEX` once to an executable file, copies it read-only into a scratch directory, and both hashes and spawns that copy by absolute path (`tests/helpers/link-gate-binary.ts`, covered by `tests/e2e-style/link-gate-codex-binary.test.ts`). The fixture records the digest of one attested build, codex-rs at 88c5856 for x86_64-unknown-linux-gnu, whose note lists the builder, date, toolchain and command; it is one attested build, not a reproducible one, so a build for another platform, with another toolchain or in another build directory may have another digest. Any binary whose digest differs runs as a smoke check, and each Codex scenario's title says which. The stand-in records each create forwarded on a socket and each HTTP request, so the oversize case proves the request never went on the socket (with a control run that drops the advertised limit) and the restart case proves the stalled request was the socket's. The clear is logged with the link id and counts only, and nothing calls it automatically. The management routes reach the store through the optional-listener facade (`src/server/index/optional-listeners.ts` forwards `linkHolds`, `clearLinkHolds` and `linkTransport`); a listener without the clear hook answers 503 `activity_holds_unavailable`, never an empty success. Before the first link upgrade of a process, `/link/ws-run-state.json` is written durably as `running` (a private temp file, content fsync, rename, and a directory fsync whose failure fails the write; Windows has no directory fsync); if that write fails, link upgrades are refused. The holds file and the reference key use the same write. A graceful stop writes the holds and then `clean`; an all-links unknown state that is still only in memory is first written per link, and if the links still cannot be listed the fence stays `running`. A start that finds `running` or an unreadable fence makes every link unknown, persists that, and only then cleans the fence; if `links.json` cannot be read at that moment every link counts as unknown and the fence stays `running`. A reference key that cannot be loaded or replaced does not stop the Home: every link stays unknown and nothing is cleaned. a corrupt holds file, overflow (64 per link, 1,024 in total), a failed hold write or a replaced reference key also make the link unknown. No file is read or written unless a fence exists or an upgrade arms one. Coverage: `tests/clients/link-ws-activity-holds.test.ts` (fence, corruption, overflow, write failure, key rotation, release rules, SIGKILL at each durability point) and `tests/server/link-websocket-holds.test.ts` (busy, idle and revoked closes, release over the WebSocket and over HTTP, a fence that cannot be written). Child side (lane T6). `src/client/link-ws-advertisement.ts` keeps, per link and in memory only, whether the Home advertised the link WebSocket on its last applied relay-auth answer. `relayChallenge` in `src/client/link-relay-transport.ts` takes a number from one process counter when every preflight starts (data requests, catalog reads, the parity report and the readiness probe alike), and `noteHomeConnection` applies the answer only when its number is higher than the last one applied for that link, so a late reply to an earlier preflight, from whichever Home or Home process, never overwrites a newer one. An answer without the state pair, or whose `x-opencodex-link-ws-proof` does not verify for that nonce and both identities, applies as off; a restart starts from off, a relink is a new link id, and at most 256 links are kept. `src/client/link-ws-transport.ts` opens the Home leg of one link socket: a preflight and the upgrade on one `SingleConnectionAgent` connection, never a second; the upgrade proceeds only when that preflight's own answer is a verified on, carries the session nonce, the link key as a Bearer and a fresh `Sec-WebSocket-Key`, and drops `Origin`, `Sec-WebSocket-Extensions` and `Sec-WebSocket-Protocol`; a 101 counts only on the authenticated socket with `Upgrade: websocket`, a `Connection` naming upgrade, the right accept value and no extension or subprotocol (a 101 the HTTP parser does not take as an upgrade is a broken handshake too). It checks the Child's release gate itself before any I/O (`disabled`), and the upgrade has its own 8 s bound after the preflight (`timeout`). Every failure is a closed word (`disabled`, `credential`, `preflight`, `not_advertised`, `home_refused`, `handshake`, `timeout`, `aborted`) and destroys the connection; nothing retries. The handed-off socket carries an error listener until its owner adds one, so an early reset is never unhandled. The Home leg's frames go through `src/client/link-ws-framer.ts`, a client framer written here because Bun resolves `ws` to its built-in shim, whose framer classes are not implemented: masked client frames, and on the read side RSV bits, opcodes, control-frame size and fragmentation, continuation order, minimal lengths, UTF-8 of whole text messages and close reasons, wire-valid close codes (1012-1014 included), unmasked server frames, a message limit and a fragment limit, each violation mapped to the close code to send (1002, 1007 or 1009). The Child's caps, budgets and timeouts are named in `src/client/link-websocket-limits.ts`, with a Child-side release gate (`linkWebsocketChildReady`) that stays false until the framer's client conformance run and the Child's memory acceptance have passed. `src/client/link-websocket.ts` carries Codex's upgrade over the link once the gate is open and the Home's last applied answer was on (design 3.2); while either is not the case the ingress answers today's 426 byte for byte and opens no connection, except during a restart drain (below), when an open gate sends every upgrade to the 503 whatever the Home last advertised. A tried upgrade passes, in order: no `Origin` header at all (a local one included; a non-local one still gets the 403); the link key; the Child's caps (8 sockets open or setting up, 4 setting up) and a 32 MiB reservation from a 256 MiB budget; the tunnel gate, where a Child-initiated tunnel that is connecting or reconnecting is held up to 3 s and then answered `503` with `link_websocket_unavailable` and no `Retry-After` (the only transient answer, never one of the codes codex-rs treats as terminal), a failed tunnel gets 426 and a Home-initiated link goes straight on; then the Home leg above; all within an 8 s budget. Every other failure, the budget included, is the same 426, so that Codex session uses HTTP (C1). The local 101 carries `x-codex-websocket-max-message-bytes: 8388608`, so Codex sends a larger request over HTTP. The listener's websocket handler (8 MiB messages, an 8 MiB backpressure limit that never closes, no idle timeout, no compression) relays whole text messages both ways and never parses or writes one of its own: a binary message from Codex closes both legs with 1003; a Home message over 4 MiB + 64 KiB, or any frame the framer refuses, closes Codex with 1011 and the Home with the framer's code; close codes are relayed (1000-1003, 1007-1014 and 3000-4999); toward Codex 1005, 1006, 1015 and a dropped Home connection become 1011, and toward the Home Codex's drop (1006 with no reason) ends the Home connection without a close frame, Codex's close without a status (1005) becomes an empty close frame, and a 1006 Bun reports with its own reason (an oversized message it refused with 1009) or 1015 becomes 1011; pings stay on their hop; a second message from Codex while the first is still unflushed toward the Home closes both legs (1013 to Codex, 1001 to the Home), and the Home leg stops being read while more than 1 MiB waits toward Codex, resuming on Bun's drain. A close the Child starts on the Home leg waits up to 5 s for the Home's close, and a close the Home starts is ended by the Home or after the same bound; a socket keeps its slot and reservation until its Home connection has actually closed. A close decided before Bun opened Codex's socket is applied when it opens; Bun 1.4 runs `open` inside `server.upgrade`, and if a Bun ever upgraded a socket without opening it, the leg stops after the 5 s close bound so it cannot hold its slot. A local upgrade that fails (`server.upgrade` returns false or throws) closes the Home leg, counts only the `handshake` fallback (no close, no request in the traffic book) and frees the slot when the Home connection closes. Ownership checks are raced against the setup budget. Any stop of the listener, graceful or forced, first aborts every upgrade still in setup and closes every link socket with 1001 on both legs, so a drain never waits on an idle Codex socket. A Child restart drains earlier: the tunnel supervisor tells the relay when its `stop()` begins, or when the link ended (its sidecar gone or naming another link, or the connected link id unreadable for several checks in a row) and the runtime is about to recycle, before it signals the tunnel, and from then on open link sockets close with 1001 on both legs and every upgrade, new or still in setup, gets the transient 503 (counted as `draining`; while draining the Home's last advertisement no longer sends an upgrade to the 426, though a closed Child gate or the Child's opt-out still does), so Codex keeps its WebSocket session for the replacement instead of falling back to HTTP for the rest of it; the Home's activity gate keeps its automatic restarts away from busy links (design 5), and a socket Codex loses mid-turn closes the Home leg at once, which the Home records as a hold. The Child never re-sends a frame: a turn cut by a tunnel drop is retried by Codex alone, on a new socket whose first request is full, or over HTTP once its retry budget is spent. A link socket counts in the Child's traffic book as one request: message payload bytes, toward the Home once the socket write completed and from the Home per complete message, without framing, handshake or control frames, complete when a close frame ended it (a socket Bun reports closed with 1006, Codex's drop or Bun's own close of an oversized message, counts incomplete, as the Home counts it); HTTP requests are counted exactly as before, and per-body zstd stays HTTP-only. Diagnostics are fixed words in the existing sink: `link_ws_open`, `link_ws_close` (why: `client`, `home`, `home_dropped`, `binary`, `protocol`, `overload`, `stopped`) and `link_ws_fallback` (why: `origin`, `credential`, `cap`, `memory`, `tunnel_failed`, `tunnel_connecting_timeout`, `preflight`, `not_advertised`, `home_refused`, `handshake`, `timeout`, `aborted`, `draining`); the dashboard's diagnostics table does not list these events yet. `linkResponsesWebsocketOptOut: true` in a Child's config keeps that Child on HTTP whatever its Home advertises (owner decision D4; read once when the listener starts; anything but `true` follows the Home). `GET /api/link/status?transport=1` on the Child adds `websocket: { open, settingUp, upgrades, fallbacks{reason}, closes{reason}, fromCodexBytes, toCodexBytes }` (design 9.3): in memory, display only, reset at restart; with the Child gate closed nothing is counted, and with it open the opt-out and an unadvertised Home count as `local_optout` and `not_advertised` without writing a diagnostic. A non-local `Origin` is refused (403) by the ingress before the relay and is not counted; `fromCodexBytes` counts text messages arriving while the Home leg is open (a binary message, or anything after the Home leg began closing, is not). The shape differs from the Home's on purpose: the Home's `ws` is per link row and counts what the Home did with upgrades (`refused`), while a Child serves one link, so its counters are one top-level object, and its `fallbacks` count the attempts the Child itself sent back to HTTP (or told to retry), with reasons only a Child can see (its opt-out, its tunnel, its own setup). Without the query the document is unchanged. Coverage: `tests/clients/link-ws-advertisement.test.ts`, `tests/clients/link-ws-framer.test.ts`, `tests/clients/link-ws-transport.test.ts`, `tests/clients/link-ws-relay.test.ts`, `tests/clients/link-ws-fallback.test.ts`, `tests/clients/link-ws-relay-edges.test.ts` and `tests/clients/link-ws-child-status.test.ts` (against `tests/fixtures/link-ws-standin-home.ts`, a raw-TCP stand-in Home, with a client that follows codex-rs's retry and fallback policy in `tests/helpers/link-ws-child.ts`), and `tests/e2e-style/link-ws-child-home.test.ts` (a real Home: a relayed turn counts as the link's activity while it runs, and a socket lost mid-turn leaves the Home's hold). The release gate's 503 sequence (below) runs the real Child listener. diff --git a/tests/e2e-style/link-gate-codex-binary.test.ts b/tests/e2e-style/link-gate-codex-binary.test.ts new file mode 100644 index 00000000000..d16960c90b8 --- /dev/null +++ b/tests/e2e-style/link-gate-codex-binary.test.ts @@ -0,0 +1,104 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { chmodSync, copyFileSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { delimiter, isAbsolute, join, resolve } from "node:path"; +import { createHash } from "node:crypto"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { preparePinnedCodex } from "../helpers/link-gate-binary"; + +// The link WebSocket release gate labels a run "release gate" when the sha256 of OCX_LINK_GATE_CODEX matches the +// reviewed digest (tests/fixtures/link-gate-codex.json). That label is only honest if the bytes it hashed are the bytes +// it runs. These cases need no real Codex: copies of the running Bun executable, named codex, stand in for it, and each +// copy prints its own path, so a run shows which file executed. That works the same on every platform. + +const NAME = process.platform === "win32" ? "codex.exe" : "codex"; +const PRINT_SELF = ["-e", "console.log(process.execPath)"]; + +let root = ""; +afterEach(() => { if (root) removeTreeWithRetry(root); root = ""; }); + +/** A copy of this Bun named codex in `dir`. */ +function fakeCodex(dir: string): string { + mkdirSync(dir, { recursive: true }); + const file = join(dir, NAME); + copyFileSync(process.execPath, file); + chmodSync(file, 0o755); + return file; +} + +const sha256 = (file: string) => createHash("sha256").update(readFileSync(file)).digest("hex"); + +/** Runs `path` from `cwd` with only `pathDir` on PATH; resolves with the path of the executable that ran. */ +async function whoRan(path: string, cwd: string, pathDir: string): Promise { + const child = Bun.spawn([path, ...PRINT_SELF], { cwd, env: { PATH: pathDir + delimiter + (process.env.PATH ?? "") }, stdout: "pipe", stderr: "pipe" }); + await child.exited; + return realpathSync((await new Response(child.stdout).text()).trim()); +} + +describe("the pinned Codex binary of the release gate: what is hashed is what runs", () => { + test("a bare name runs the file that was hashed, not another codex on PATH", async () => { + root = mkdtempSync(join(tmpdir(), "ocx-gate-binary-")); + const cwd = join(root, "work"); const onPath = join(root, "bin"); const scratch = join(root, "scratch"); + const hashed = fakeCodex(cwd); + // The codex on PATH has other bytes than the hashed file, so the digest tells the two apart. It is executable + // (0755) but never has to run: the gate must not reach it. + mkdirSync(onPath); + const onPathFile = join(onPath, NAME); + writeFileSync(onPathFile, "another codex on PATH, not the hashed one\n"); + chmodSync(onPathFile, 0o755); + mkdirSync(scratch); + const prepared = preparePinnedCodex(NAME, { cwd, scratch })!; + expect(prepared.digest).toBe(sha256(hashed)); + expect(prepared.digest).not.toBe(sha256(onPathFile)); + // The executable that runs is the file the gate names (the copy of the hashed file), never the codex on PATH. + expect(await whoRan(prepared.path, cwd, onPath)).toBe(realpathSync(resolve(cwd, prepared.path))); + expect(isAbsolute(prepared.path)).toBe(true); + expect(sha256(prepared.path)).toBe(prepared.digest); + }); + + test("replacing the file after it was hashed does not change what runs", async () => { + root = mkdtempSync(join(tmpdir(), "ocx-gate-binary-")); + const cwd = join(root, "work"); const scratch = join(root, "scratch"); + const original = fakeCodex(cwd); + mkdirSync(scratch); + const prepared = preparePinnedCodex(original, { cwd, scratch })!; + writeFileSync(original, "replaced after hashing"); + expect(await whoRan(prepared.path, cwd, join(root, "none"))).toBe(realpathSync(prepared.path)); + expect(sha256(prepared.path)).toBe(prepared.digest); + // The copy that runs is read-only. + if (process.platform !== "win32") expect(statSync(prepared.path).mode & 0o222).toBe(0); + }); + + test("the copy never replaces an existing file: a second copy into the same scratch directory is refused", () => { + root = mkdtempSync(join(tmpdir(), "ocx-gate-binary-")); + const cwd = join(root, "work"); const scratch = join(root, "scratch"); + const original = fakeCodex(cwd); + mkdirSync(scratch); + const prepared = preparePinnedCodex(original, { cwd, scratch })!; + // Writable again, so only the exclusive flag (not the copy's 0555 mode) can refuse the second copy. + chmodSync(prepared.path, 0o755); + writeFileSync(original, "other bytes for the second copy"); + chmodSync(original, 0o755); + let refused: unknown = null; + try { preparePinnedCodex(original, { cwd, scratch }); } catch (error) { refused = error; } + expect((refused as NodeJS.ErrnoException | null)?.code).toBe("EEXIST"); + expect(sha256(prepared.path)).toBe(prepared.digest); + }); + + test("a value that names no file is refused", () => { + root = mkdtempSync(join(tmpdir(), "ocx-gate-binary-")); + const scratch = join(root, "scratch"); + mkdirSync(scratch); + expect(preparePinnedCodex("", { cwd: root, scratch })).toBeNull(); + expect(preparePinnedCodex("missing", { cwd: root, scratch })).toBeNull(); + expect(preparePinnedCodex(root, { cwd: root, scratch })).toBeNull(); + }); + + test.skipIf(process.platform === "win32")("a file without execute permission is refused (POSIX permissions)", () => { + root = mkdtempSync(join(tmpdir(), "ocx-gate-binary-")); + const scratch = join(root, "scratch"); + mkdirSync(scratch); + writeFileSync(join(root, "plain"), "not executable"); + expect(preparePinnedCodex("plain", { cwd: root, scratch })).toBeNull(); + }); +}); diff --git a/tests/e2e-style/link-websocket-release-gate.test.ts b/tests/e2e-style/link-websocket-release-gate.test.ts index da7faa45f42..c3bffacc228 100644 --- a/tests/e2e-style/link-websocket-release-gate.test.ts +++ b/tests/e2e-style/link-websocket-release-gate.test.ts @@ -1,8 +1,7 @@ -import { afterEach, describe, expect, setDefaultTimeout, test } from "bun:test"; -import { accessSync, constants, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { afterAll, afterEach, describe, expect, setDefaultTimeout, test } from "bun:test"; +import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { createHash } from "node:crypto"; import type { OcxConfig } from "../../src/types"; import { setLinkWebsocketLimitsForTests, setLinkWebsocketTransportReadyForTests } from "../../src/server/index/link-websocket-limits"; import { serviceApiTokenFingerprint } from "../../src/lib/service-secrets"; @@ -12,6 +11,7 @@ import { installIsolatedCodexHome, type IsolatedCodexHome } from "../helpers/iso import { removeTreeWithRetry } from "../helpers/remove-tree"; import { STANDIN_MAX_MESSAGE_BYTES, startRelayStandin, type RelayStandin } from "../fixtures/link-child-relay-standin"; import { fixturePath } from "../helpers/repo-root"; +import { preparePinnedCodex } from "../helpers/link-gate-binary"; import { startChild } from "../helpers/link-ws-child"; import { probeLinkRelayPreflight } from "../../src/client/link-relay-transport"; import { forgetLinkWebsocketAdvertisementsForTests } from "../../src/client/link-ws-advertisement"; @@ -20,22 +20,36 @@ import type { LinkDiagnosticRecord } from "../../src/link/diagnostics"; import type { Server } from "bun"; // Lane T5f: the link WebSocket release gate of design T4 11.1 item 13, with the pinned Codex binary as the client (U13). -// The pinned binary is codex-rs built at openai/codex 88c5856 (design section 0). These tests run only when -// OCX_LINK_GATE_CODEX names an executable; otherwise each is skipped with that reason. A run is release evidence only +// The pinned binary is codex-rs built at openai/codex 88c5856 (design section 0). The Codex scenarios run only when +// OCX_LINK_GATE_CODEX names an executable file; otherwise every Codex scenario is skipped with that reason, and the pin +// test always runs. A run is release evidence only // when the binary's sha256 equals the digest recorded for that revision in tests/fixtures/link-gate-codex.json, a file -// that changes only through review; any other executable runs as a smoke check, and every test title says which. Codex reaches the Home through a test-only +// that changes only through review; any other executable runs as a smoke check, and each Codex scenario's title says which. Codex reaches the Home through a test-only // stand-in for the Child's relay (tests/fixtures/link-child-relay-standin.ts), except in the 503 sequence, which needs the // Child's own relay and tunnel gate (lane T6, src/client/link-websocket.ts) and runs the real Child listener. // Codex is an external process with no clock to inject, so each test carries a per-test bound instead of sleeps. -const BIN = process.env.OCX_LINK_GATE_CODEX ?? ""; -const usable = (() => { if (!BIN) return false; try { accessSync(BIN, constants.X_OK); return true; } catch { return false; } })(); +// OCX_LINK_GATE_CODEX is resolved once to an executable file and copied read-only into a scratch directory; that copy is +// what is hashed and what every scenario spawns, by absolute path (tests/helpers/link-gate-binary.ts). +// The scratch copy is removed after the file, and at once if preparing it throws or the value is refused. +const BIN_SCRATCH = process.env.OCX_LINK_GATE_CODEX ? mkdtempSync(join(tmpdir(), "ocx-link-gate-bin-")) : ""; +afterAll(() => { if (BIN_SCRATCH) removeTreeWithRetry(BIN_SCRATCH); }); +const PREPARED = (() => { + if (!BIN_SCRATCH) return null; + try { + const prepared = preparePinnedCodex(process.env.OCX_LINK_GATE_CODEX!, { scratch: BIN_SCRATCH }); + if (!prepared) removeTreeWithRetry(BIN_SCRATCH); + return prepared; + } catch (error) { removeTreeWithRetry(BIN_SCRATCH); throw error; } +})(); +const BIN = PREPARED?.path ?? ""; +const usable = PREPARED !== null; const PIN = JSON.parse(readFileSync(fixturePath("link-gate-codex.json"), "utf8")) as { revision: string; sha256: string | null }; const PINNED_SHA256 = typeof PIN.sha256 === "string" ? PIN.sha256.toLowerCase() : ""; -const digest = usable ? createHash("sha256").update(readFileSync(BIN)).digest("hex") : ""; +const digest = PREPARED?.digest ?? ""; const mode: "absent" | "gate" | "smoke" = !usable ? "absent" : PINNED_SHA256 && digest === PINNED_SHA256 ? "gate" : "smoke"; const LABEL = { - absent: " [skipped: pinned Codex binary absent (U13); set OCX_LINK_GATE_CODEX to codex-rs built at openai/codex 88c5856]", + absent: " [skipped: pinned Codex binary absent (U13); set OCX_LINK_GATE_CODEX to an executable file of codex-rs built at openai/codex 88c5856]", gate: " [release gate: Codex sha256 " + digest + " matches the reviewed digest for openai/codex " + PIN.revision.slice(0, 7) + " in tests/fixtures/link-gate-codex.json]", smoke: " [smoke only, not release evidence: Codex sha256 " + digest + " is not the reviewed digest for openai/codex " + PIN.revision.slice(0, 7) + " (tests/fixtures/link-gate-codex.json" + (PINNED_SHA256 ? "" : " records none yet") + ")]", }[mode]; diff --git a/tests/fixtures/link-gate-codex.json b/tests/fixtures/link-gate-codex.json index 91f7541dfb7..1b2913d3160 100644 --- a/tests/fixtures/link-gate-codex.json +++ b/tests/fixtures/link-gate-codex.json @@ -1,5 +1,5 @@ { "revision": "88c58562580aa4abe2da6ce4d7676bf171682230", - "sha256": null, - "note": "The sha256 of codex-rs built at this openai/codex revision, recorded by whoever builds and attests it, in a reviewed change to this file. While it is null, no run of tests/e2e-style/link-websocket-release-gate.test.ts is release evidence." + "sha256": "c80d5ba4a92ffef0ef1ad1e9345429740ada15fa158b1792900e36892573a23c", + "note": "The sha256 of codex-rs/target/release/codex built at this openai/codex revision, attested by OpenCodex agent lane G on its build VM on 2026-11-13 in #8668 (system clock, UTC; the successful build ran 05:35:07Z to 06:54:37Z). Command, in codex-rs of a clean checkout of this revision: cargo build --release --locked -j 1 -p codex-cli --bin codex. Toolchain: rustc 1.95.0 (59807616e 2026-04-14, LLVM 22.1.2) and cargo 1.95.0, selected by the revision's rust-toolchain.toml. Target x86_64-unknown-linux-gnu; Ubuntu 24.04.5 LTS, Linux 6.12.113, glibc 2.39, cc clang 18.1.3, libcap-dev 2.66 and libssl-dev 3.0.13 from Ubuntu. The revision's release profile is unchanged (thin LTO, 4 codegen units, line-table debug info, not stripped); -j 1 was used only because the kernel's memory-cgroup OOM killer killed rustc at the default width on the 16 GiB VM. The binary is 1618990456 bytes and prints codex-cli 0.0.0 for --version. This is one attested build, not a reproducible one: the digest identifies this Linux x86_64 binary only. A build on another platform, or with another toolchain, C compiler or system library, or in another build directory, may have a different digest; only a binary whose sha256 matches this one exactly gets the release-gate label, and any other runs as a smoke check by design. While this digest is recorded, a run of tests/e2e-style/link-websocket-release-gate.test.ts with this binary is release evidence for that test file only. This file changes only through review." } diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 520b4052b2e..57cb1ff75b6 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1718,6 +1718,7 @@ "link-request-log-fields.test.ts": "server", "link-websocket-transport-status.test.ts": "server", "link-websocket-release-gate.test.ts": "e2e-style", + "link-gate-codex-binary.test.ts": "e2e-style", "link-websocket-drain.test.ts": "server", "link-websocket-pump.test.ts": "server", "link-websocket-rss.test.ts": "e2e-style", diff --git a/tests/helpers/link-gate-binary.ts b/tests/helpers/link-gate-binary.ts new file mode 100644 index 00000000000..81a492afc9d --- /dev/null +++ b/tests/helpers/link-gate-binary.ts @@ -0,0 +1,36 @@ +import { createHash } from "node:crypto"; +import { accessSync, chmodSync, closeSync, constants, copyFileSync, openSync, readSync, statSync } from "node:fs"; +import { basename, join, resolve } from "node:path"; + +/** + * The executable a release-gate run hashes and runs (tests/e2e-style/link-websocket-release-gate.test.ts). `value` is + * OCX_LINK_GATE_CODEX: it is resolved against `cwd` once and must name an executable regular file; anything else is + * refused (null). That file is copied read-only into `scratch`, and the copy is both what is hashed and what is spawned, + * by absolute path. So a bare name cannot hash one file and run another found on PATH, and replacing the original after + * it was hashed cannot change what runs. + */ +export function preparePinnedCodex(value: string, options: { cwd?: string; scratch: string }): { path: string; digest: string } | null { + if (!value) return null; + const file = resolve(options.cwd ?? process.cwd(), value); + try { + if (!statSync(file).isFile()) return null; + accessSync(file, constants.X_OK); + } catch { return null; } + // The copy keeps the file name, so an extension a platform needs to execute it (codex.exe) stays. + const copy = join(options.scratch, basename(file)); + // Exclusive: never over an existing file. FICLONE makes the copy a reflink where the file system has them (APFS, btrfs, + // XFS), so the 1.6 GB binary costs no space there; elsewhere it is an ordinary copy. + copyFileSync(file, copy, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE); + chmodSync(copy, 0o555); + return { path: copy, digest: sha256File(copy) }; +} + +function sha256File(file: string): string { + const hash = createHash("sha256"); + const buffer = Buffer.allocUnsafe(8 * 1024 * 1024); + const fd = openSync(file, "r"); + try { + for (let read = readSync(fd, buffer); read > 0; read = readSync(fd, buffer)) hash.update(buffer.subarray(0, read)); + } finally { closeSync(fd); } + return hash.digest("hex"); +}