diff --git a/docs/ADRs/0104-per-persona-model-resolution.md b/docs/ADRs/0104-per-persona-model-resolution.md index 24c791b988..b6c2d5f81c 100644 --- a/docs/ADRs/0104-per-persona-model-resolution.md +++ b/docs/ADRs/0104-per-persona-model-resolution.md @@ -17,6 +17,9 @@ Date: 2026-09-05 Accepted +Codex-specific model precedence and protected native role dispatch are defined +in [ADR 0126](0126-runner-owned-codex-child-policy.md). + ## Context Sub-agent skills (pr-review, retro-analysis) dispatch children by passing a diff --git a/docs/ADRs/0126-runner-owned-codex-child-policy.md b/docs/ADRs/0126-runner-owned-codex-child-policy.md new file mode 100644 index 0000000000..5c1361ed14 --- /dev/null +++ b/docs/ADRs/0126-runner-owned-codex-child-policy.md @@ -0,0 +1,73 @@ +--- +title: "126. Runner-owned policy for native Codex children" +status: Accepted +relates_to: + - agent-architecture + - security-threat-model +topics: + - runtime + - sub-agents + - security +--- + +# 126. Runner-owned policy for native Codex children + +Date: 2026-09-28 + +## Status + +Accepted + +## Context + +Review and retrospective workflows need independent child contexts, selected +personas, bounded execution and attributable usage +([agent architecture](../problems/agent-architecture.md)). Codex provides native +children, but reads role configuration again when each child starts. Checking a +file only before the parent starts does not protect subsequent child dispatch. + +[ADR 0104](0104-per-persona-model-resolution.md) makes model selection a runner +concern. Its Claude aliases and persona tool lists cannot be applied directly +to Codex. [ADR 0100](0100-codex-sandbox-hooks.md) translates the shared security +hooks; their wiring must also remain intact when native children load it. + +## Decision + +The runner provisions and protects the policy for native Codex children. +For an agent with the Agent tool, it registers skill personas plus generic and +Explore roles; other agents get no roles, as on Claude Code and pi. For Codex, model +precedence is an explicit persona mapping, `FULLSEND_CODEX_SUBAGENT_MODEL`, +`subagents.default`, then `gpt-5.6-luna`. Claude frontmatter models and tool +lists are reported as documentation only. Invalid or unavailable explicit +models never fall back to another model. + +Before sourcing the sandbox environment or starting Codex, the runner applies +an inherited Linux Landlock write restriction. Role files, `CODEX_HOME` +configuration, hooks and their directory entries remain protected; exact +native state paths remain writable. The launcher closes inherited writable +descriptors and verifies authority files against runner-held hashes after +applying the restriction. A missing capability or changed policy fails the run. + +Native configuration bounds open child IDs to four, including completed children +that have not been closed. A mandatory dispatch +hook rejects grandchildren, context inheritance, model overrides and resuming +any child, including when optional security scanning is disabled. Native +resume can replace a child's role policy with the parent's; a new task must +use a fresh spawn. Shared security hooks apply to parent and child tools. +Model metadata determines the native collaboration API: validation must cover +the selected model's lifecycle, not infer it from the CLI version alone. +The dispatch guard accepts only V1's explicit `fork_context: false` contract +and rejects V2-shaped arguments. A child model override does not select the +parent's collaboration API; a model-name allowlist is not a substitute for +enforcing the actual dispatch contract. + +Native review and retro ship only as a paired runtime and companion release; +existing deployments keep their prior pins until they adopt the validated pair. + +## Consequences + +- Persona selection remains a workflow decision; models and dispatch constraints remain runner decisions. +- Codex requires a system Python outside the agent's write roots and Linux Landlock ABI 3 or newer inside its OpenShell sandbox, including for runs without children. Top-level `$HOME` entries that Bootstrap does not pre-create cannot be created during a run. +- Native state paths, role loading, hook inheritance and collaboration APIs require revalidation on CLI or model changes. +- Parent and child usage and transcripts are collected by native thread identity; incomplete evidence fails visibly, and unreported dollar cost remains unavailable. +- These restrictions protect the launched native hierarchy; tool hooks remain defense in depth within the outer sandbox, not a prohibition on every interpreter an agent can invoke. diff --git a/docs/architecture.md b/docs/architecture.md index 55bff57d85..f7eb8205c0 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -239,6 +239,12 @@ flowchart TB - The `fullsend run` runner delegates in-sandbox agent execution to a `runtime.Runtime` interface; production orgs default to Claude Code, with [pi](https://github.com/earendil-works/pi) available as an opt-in second runtime (`runtime: pi`, Claude-on-Vertex through the same WIF credential path) and [codex](https://github.com/openai/codex) as a third (`runtime: codex`, OpenAI-only through a custom model provider whose bearer token comes from a runner-seeded file, with the sandbox tool hooks behind a translating adapter — [ADR 0099](ADRs/0099-codex-agent-runtime.md) and [ADR 0100](ADRs/0100-codex-sandbox-hooks.md)). Runtime selection is configured per repo with `runtime:` in `.fullsend/config.yaml` (per-agent `runtime`/`model`/`effort`/`subagents` on the agent's `agents:` entry sit above it and below the `--runtime`/`--model`/`--effort` flags and `FULLSEND_*` variables, [ADR 0091](ADRs/0091-per-agent-runtime-model-effort.md)) and resolved via `runtime.ResolveForAgent()`. Test-only runtimes — **dummy** (scripted operations) and **dummy-playback** (playlist-based replay of canned results) — execute in the real OpenShell sandbox for behaviour tests without inference. Bootstrap uses a portable `BootstrapInput` interface with optional extensions such as `SandboxHooksBootstrap` for the runtime-neutral sandbox tool hooks ([ADR 0090](ADRs/0090-runtime-neutral-sandbox-hooks-contract.md)); runtimes declare further capabilities through small optional interfaces (`DebugLogNamer`, `ContextBridger`) rather than `Name()` checks in the runner. Transcript and debug artifact handling use a separate `TranscriptHandler` interface. See [runtimes.md](runtimes.md) for the per-runtime security feature matrix required when adding a new backend. - Plugins are runtime-scoped harness resources: a harness declares `plugins:` as one list of directories in its own repository (same trust and fetch path as skills), and each entry's format decides which runtime loads it — a `plugin.json` bundle is Claude Code's, a directory pi's `-e` loader resolves is uploaded and loaded after a tree-hash preflight computed from the host copy. Each runtime names and skips the entries in the other format, so the list survives a runtime switch. Because `--no-extensions` plus explicit `-e` closes the set of code that can register tools, no per-tool declaration is needed ([ADR 0094](ADRs/0094-pi-extensions-are-harness-resources.md)). +Codex provisions native child roles with runner-selected models and protects +their configuration and hooks throughout the parent and child processes using +inherited Landlock restrictions. Native dispatch is bounded to four children; +usage and transcripts are collected by thread identity +([ADR 0126](ADRs/0126-runner-owned-codex-child-policy.md)). + ### Behaviour testing End-to-end **behaviour tests** use the shared framework in `pkg/behaviourtest/` (with live-test infrastructure in `internal/e2etest/`); the in-repo runner and Gherkin features live under `e2e/behaviour/`. They validate deterministic platform code — dispatch routing, harness loading, sandbox policy, SCM mutations — with the LLM layer removed via the dummy and dummy-playback runtimes. Tests exercise real GitHub (and GitLab) SCM and GitHub Actions CI through pluggable drivers; Gherkin scenarios stay install-mode agnostic while runner env vars select backends. This coverage is **orthogonal** to LLM and instruction testing in [testing-agents.md](problems/testing-agents.md). See [ADR 0066](ADRs/0066-behaviour-tests-with-gherkin-and-drivers.md). diff --git a/docs/cli/agent.md b/docs/cli/agent.md index e413df7220..1cabf5e642 100644 --- a/docs/cli/agent.md +++ b/docs/cli/agent.md @@ -467,11 +467,13 @@ fullsend agent set review --fullsend-dir .fullsend --subagent correctness=opus - | `--runtime` | Agent runtime for this agent (`claude`, `pi` or `codex`) | | `--model` | Model for this agent — an alias, a model id, or `provider/id` on pi and codex (codex takes OpenAI ids only) | | `--effort` | Effort level for this agent (`low`, `medium`, `high`, `xhigh`, `max`) | -| `--subagent` | Per-persona model override as `key=value` (repeatable). Key is a persona name or `default`; value is a model reference. Pass an empty value (`--subagent key=`) to clear an inherited entry — that writes `key: ~` in the config, after which the persona resolves the way an unmentioned one does (its frontmatter model, then `subagents.default`) | +| `--subagent` | Per-persona model override as `key=value` (repeatable). Key is a persona name or `default`; value is a model reference. Pass an empty value (`--subagent key=`) to clear an inherited entry — that writes `key: ~` in the config. Resolution depends on the runtime; see below and [Codex native children](../runtimes/codex.md#native-children) | See [Runtimes — per-agent settings](../runtimes.md#per-agent-runtime-model-and-effort) for precedence. -See [pi § Per-persona model configuration](../runtimes/pi.md#per-persona-model-configuration) for -how `subagents` map to persona dispatch. +On [pi](../runtimes/pi.md#per-persona-model-configuration), an unmentioned or cleared persona +uses its frontmatter model, then `subagents.default`. On +[Codex](../runtimes/codex.md#native-children), Claude frontmatter is ignored; the fallback is +`FULLSEND_CODEX_SUBAGENT_MODEL`, then `subagents.default`, then `gpt-5.6-luna`. ## `agent remove` diff --git a/docs/cli/run.md b/docs/cli/run.md index 0fe4065429..9753fffe1d 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -48,9 +48,9 @@ The **Runtime** line shows which runtime was selected and the config source it w ## Runtime selection -The runtime for a run is resolved once, in this order: `--runtime` flag, `FULLSEND_RUNTIME`, `runtime:` on the agent's `agents:` entry in `config.yaml` / `.fullsend/config.yaml`, the repo-wide `runtime:` there, then the built-in `claude`. The same order applies to the model (`--model`, `FULLSEND_MODEL`, `model:` on the agent's `agents:` entry, harness `model:`, agent frontmatter; `FULLSEND_PI_MODEL` on pi and `FULLSEND_CODEX_MODEL` on codex are lower-precedence aliases, each read only when that runtime is the one selected) and to effort (`--effort`, `FULLSEND_EFFORT`, `effort:` on the agent's `agents:` entry, harness `effort:`). `` is the name given to `fullsend run` (`triage`, `code`, …); see [Runtimes — per-agent settings](../runtimes.md#per-agent-runtime-model-and-effort). `FULLSEND_FALLBACK_MODELS=a,b` becomes Claude Code's `--fallback-model`; pi uses it for aliased models on the top-level run when Vertex does not serve the model (two specific 404/403 messages, same provider only; sub-agent children get none); codex ignores it with a warning. +The runtime for a run is resolved once, in this order: `--runtime` flag, `FULLSEND_RUNTIME`, `runtime:` on the agent's `agents:` entry in `config.yaml` / `.fullsend/config.yaml`, the repo-wide `runtime:` there, then the built-in `claude`. The same order applies to the model (`--model`, `FULLSEND_MODEL`, `model:` on the agent's `agents:` entry, harness `model:`, agent frontmatter; `FULLSEND_PI_MODEL` on pi and `FULLSEND_CODEX_MODEL` on codex are lower-precedence aliases, each read only when that runtime is the one selected) and to effort (`--effort`, `FULLSEND_EFFORT`, `effort:` on the agent's `agents:` entry, harness `effort:`). `` is the name given to `fullsend run` (`triage`, `code`, …); see [Runtimes — per-agent settings](../runtimes.md#per-agent-runtime-model-and-effort). For Codex native children, `--effort` sets the root only; child roles retain their native model defaults (see [Codex native children](../runtimes/codex.md#native-children)). `FULLSEND_FALLBACK_MODELS=a,b` becomes Claude Code's `--fallback-model`; pi uses it for aliased models on the top-level run when Vertex does not serve the model (two specific 404/403 messages, same provider only; sub-agent children get none); codex ignores it with a warning. -The plan block prints `Runtime: (from )` and, when an override applied, `Model: (from )`; stderr carries `runtime: selected "" from ` (and `model: requested "" from `) for scripts. A value from the config file is labelled with the file path, suffixed ` agents.` when the agent's entry decided. When `models.aliases` in `.fullsend/config.yaml` remaps the alias, the line keeps the alias and its source and adds the remap: `Model: sonnet (from ) → claude-sonnet-5 (from models.aliases)`, with `model: alias "sonnet" remapped to "claude-sonnet-5" from models.aliases` on stderr. Aliased entries in the `Fallback models` line show as `alias → id` (`sonnet → claude-sonnet-5, claude-opus-4-6 (from FULLSEND_FALLBACK_MODELS)`); literal ids print as written; pi uses the chain for aliased models when Vertex does not serve the model and ignores it for pinned ids. An invalid override — unknown runtime, unknown effort level, an `agents:` entry that names no agent, or a `models.aliases` key or value the block does not accept — fails before the sandbox is created. +The plan block prints `Runtime: (from )` and, when an override applied, `Model: (from )`; stderr carries `runtime: selected "" from ` (and `model: requested "" from `) for scripts. A value from the config file is labelled with the file path, suffixed ` agents.` when the agent's entry decided. When `models.aliases` in `.fullsend/config.yaml` remaps the alias, the line keeps the alias and its source and adds the remap: `Model: sonnet (from ) → claude-sonnet-5 (from models.aliases)`, with `model: alias "sonnet" remapped to "claude-sonnet-5" from models.aliases` on stderr. Aliased entries in the `Fallback models` line show as `alias → id` (`sonnet → claude-sonnet-5, claude-opus-4-6 (from FULLSEND_FALLBACK_MODELS)`); literal ids print as written; pi uses the chain for aliased models when Vertex does not serve the model and ignores it for pinned ids. An invalid override — unknown runtime, unknown effort level, an `agents:` entry that names no agent, or a `models.aliases` key or value the block does not accept — fails before the sandbox is created. Codex still requires an explicit OpenAI model ID: `models.aliases` does not make Claude aliases valid for Codex, even if the shared plan display shows a remap. ```bash # try a repo's triage on pi with Gemini Flash, without touching its config @@ -98,29 +98,28 @@ depend on the process cwd. | `override_source` | Where `requested_model` came from (`--model flag`, `FULLSEND_MODEL`, `FULLSEND_PI_MODEL`, `FULLSEND_CODEX_MODEL`, ` agents.`, `harness`, `default`), suffixed `, remapped by models.aliases` when a per-repo alias override applied to it | | `runtime_source` | Where `requested_runtime` came from (`--runtime flag`, `FULLSEND_RUNTIME`, the config file path — suffixed ` agents.` when the agent's entry decided — or `default (config not found)`) | | `total_cost_usd` | Total inference cost in USD, as reported by the runtime (raw floating-point aggregate across all iterations; no fullsend-side pricing-table fallback). See [Cost data contract](../guides/infrastructure/distributed-tracing.md#cost-data-contract) | +| `cost_unavailable` | When true, the runtime did not report complete dollar cost. Codex sets this; zero in `total_cost_usd` does not mean free inference. Omitted for runtimes with known cost | | `num_turns` | Number of conversation turns | | `iterations` | Number of agent iterations run; an iteration killed at the budget is not retried (see [Budget and deadline](#budget-and-deadline)) | -| `per_model_usage` | Per-model-spec breakdown, present only when a runtime reports one (today: `pi` with the `Agent` tool enabled). See below | +| `per_model_usage` | Per-model breakdown when supplied by the runtime (`pi` with the `Agent` tool enabled, and Codex). See below | #### Per-model usage -A map from pi model spec (`anthropic-vertex/claude-opus-4-6`) to -`{requests, input_tokens, output_tokens, cache_creation_input_tokens, cache_read_input_tokens, cost_usd}`. -It exists because a pi sub-agent is a separate `pi` process whose tokens never appear in the -parent's stream, so without it `total_cost_usd` would grow with no way to attribute it. +A map from model spec (`anthropic-vertex/claude-opus-4-6` on pi, `gpt-5.6-luna` on Codex) to +`{requests, input_tokens, output_tokens, reasoning_tokens, cache_creation_input_tokens, cache_read_input_tokens, cost_usd, cost_unavailable}`. +Optional zero/false fields may be omitted. It attributes usage from both the parent and children; +child usage does not appear in the parent's ordinary stream counters. - **What folds.** Tokens and cost, from both the parent and every child, summed across retry - iterations. Each iteration contributes one `requests` for the parent plus one per sub-agent call, - so `requests` counts inference *episodes*, not HTTP requests. -- **The invariant.** The breakdown sums to the run totals for the five fields an entry has: - `sum(cost_usd) == total_cost_usd`, and likewise for `input_tokens`, `output_tokens`, - `cache_creation_input_tokens` and `cache_read_input_tokens`. `reasoning_tokens` is a run-level - total with no per-model counterpart, so it is outside the invariant. The parent's entry is - recorded on every iteration of an `Agent`-enabled run, including ones that dispatched no - sub-agent, which is what keeps the invariant true across a retry. + iterations. Pi counts one `requests` for the parent plus one per sub-agent call. Codex counts + unique native thread/model invocations with recorded usage. Neither counts HTTP requests. +- **The invariant.** The breakdown sums to the run's input, output, cache-creation and cache-read + token totals. Codex also attributes reasoning tokens per model; pi child records do not yet + provide that split. Cost sums are meaningful only when cost is available. An incomplete Codex + collection preserves known usage and fails the run; it must not be read as complete accounting. - **What stays parent-only.** `num_turns` and `tool_calls` are read from the parent's stream and are not broken down or added to per model — a child's turns and tool calls are recorded in its own - session transcript (`transcripts/-sub-*.jsonl`) instead. + session transcript (pi's `-sub-*.jsonl`, Codex's native thread-ID filename) instead. - A model spec of `unknown` is a usage record that carries no model spec at all; its cost is bucketed there rather than dropped. A dispatch rejected *before* a model was resolved writes no record, so it never reaches the breakdown. diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 2b09754de7..0c665a4675 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -1051,9 +1051,9 @@ flowchart TB codex records a trust level for a git checkout it starts in when none is set, and only skips that when one already is. This is codex's equivalent of pi's `defaultProjectTrust: "never"`. - **Config layering.** The sandbox image bakes a root-owned managed `/etc/codex/config.toml`; the - runner's `$CODEX_HOME/config.toml` layers above it, and the `-c` SessionFlags above that. Only - the `-c` layer is beyond an agent's reach between iterations, which is why the security-relevant - keys are passed there as well as written to the file. + runner's `$CODEX_HOME/config.toml` layers above it, and the `-c` SessionFlags above that. The + native process hierarchy inherits a Landlock write restriction protecting the configuration and + child roles. Security-relevant keys are also passed in the `-c` layer. - **No `CLAUDE.md` pointer.** `CodexRuntime` does not implement `ContextBridger`; it gets the repo's `AGENTS.md` through `$CODEX_HOME/AGENTS.md` instead (see **AGENTS.md** below). - **Tool names**: the shell tool is already `Bash`; `apply_patch` covers Claude's `Write` and `Edit` @@ -1102,9 +1102,11 @@ flowchart TB - **Exit code**: `codex exec` exits 0 on a failed turn *and* on an interrupted one, so the stream's verdict overrides it, exactly as for pi. Distinct guard exits: **97** (a runner-owned file is missing or no longer matches its embedded copy) and **98** (`config.toml` no longer pins the - provider endpoint or its auth command, or trusts the project). -- **Cost is never reported** — the stream carries no cost field, so `total_cost_usd` stays 0. The - model id in `metrics.json` comes from the run parameters, not the wire. + provider endpoint or its auth command, or trusts the project), both behind the Landlock + launcher's **78**, which checks the same files first. +- **Cost is unavailable** — Codex reports no dollar cost. Aggregate and per-model usage carry + `cost_unavailable: true`, the renderer says unavailable, and cost span attributes are omitted. + Root and child usage is folded from persisted response records as described below. ### Credential path @@ -1139,7 +1141,7 @@ Matcher translation, per group: |---|---|---| | `Bash` | `Bash` | codex's shell tool has the same name | | `Write`, `Edit`, `MultiEdit` | `apply_patch` | the canonical name; `Write`/`Edit` would also match as aliases | -| `Agent`, `Task` | `spawn_agent` | not reachable in v1 — no sub-agent roster is wired | +| `Agent`, `Task` | `spawn_agent` | native child dispatch; the mandatory policy hook also covers `resume_agent` | | `Read`, `Glob`, `Grep`, `LS`, `WebFetch`, `WebSearch` | *dropped, with a note* | no codex tool; the `Bash` groups cover this work | | `*` (`security.AllTools`) | *matcher key omitted* | an absent matcher matches every tool | | `PostToolUseFailure` (any tools) | *not wired* | codex has no such event and does not need one — see below | @@ -1195,16 +1197,21 @@ Consequences of those, recorded in the matrix and [ADR 0100](../ADRs/0100-codex- ### Where the guards' expected values come from -Everything under `CODEX_HOME` is agent-writable between iterations, so a guard is worth only as much -as the place its expected value comes from. There are two trustworthy places — this binary, and +Authority files under `CODEX_HOME` and the separate role directory are protected throughout the +launched hierarchy by Landlock. Digests still catch changes introduced outside that hierarchy; +their expected values come from two trustworthy places — this binary, and **runner-held digests**, meaning digests the runner records outside the sandbox at Bootstrap and injects into the launch command at Run — and the manifest is not one of them: | File | Anchor | Guard | |---|---|---| -| hook adapter, auth script | **compile-time** — `go:embed`ed, so the digest is a literal in the run command | SHA-256, exit 97 | -| the shared hook scripts | **compile-time** for the bytes, **runner-held** for which names — Bootstrap records the name → digest map for the set the harness enabled | SHA-256 per filename, plus an exhaustive directory check, exit 97 | -| `config.toml`, `hooks.json` | **runner-held** — rendered per run, so Bootstrap records what it uploaded outside the sandbox and Run injects it into the launch command (`codex_integrity.go`) | whole-file SHA-256, exit 98 | -| `fullsend-manifest.json` | none — it is a file in the same agent-writable directory | information only; never authority | +| hook adapter, auth script | **compile-time** — `go:embed`ed, so the digest is a literal in the run command | SHA-256; launcher exit 78, shell exit 97 | +| the shared hook scripts | **compile-time** for the bytes, **runner-held** for which names — Bootstrap records the name → digest map for the set the harness enabled | SHA-256 per filename, plus an exhaustive directory check; launcher exit 78, shell exit 97 | +| `config.toml`, `hooks.json` | **runner-held** — rendered per run, so Bootstrap records what it uploaded outside the sandbox and Run injects it into the launch command (`codex_integrity.go`) | whole-file SHA-256; launcher exit 78, shell exit 98 | +| native role files and dispatch policy | **runner-held** — Bootstrap records exact paths and digests; the launcher restricts writes before checking them | exhaustive authority check, exit 78 | +| `fullsend-manifest.json` | none | information only; never authority | + +The launcher checks these files before the shell starts, so the shell's 97 and 98 appear only for a +missing manifest or a change made after the launcher's check. The hook-script check makes codex **stricter than Claude Code and pi**, where the scripts stay agent-writable between iterations with no integrity check at all. Each digest is bound to its @@ -1223,26 +1230,30 @@ agent-writable between iterations with no integrity check at all. Each digest is All five were reproduced under `/bin/sh` before the guard was rewritten, and each has a case in `TestCodexHookScriptsGuard_Executes`. -That guard runs once, before codex starts. The agent then has the whole iteration — with full -sandbox access — to rewrite a script before the next tool call reaches it, a window Claude Code and -pi leave open too. On codex it is cheap to close: the run command exports the name → digest map into -the codex process's environment after `.env` and before launch, and a running process's environment -is not something the agent can reach, so **the adapter re-reads and re-verifies each script -immediately before spawning it** and blocks on a mismatch. A missing or malformed map is itself a -block, since the adapter only ever runs when the runner enabled hooks. +The launcher applies its kernel write restriction before sourcing `.env`, closes inherited file +descriptors and then checks authority files. This closes the window in which a running parent could +rewrite a role before a native child rereads it. The run command also exports the name → digest map +after `.env`; **the adapter re-verifies each script immediately before spawning it** and blocks on +a mismatch. A missing or malformed map is itself a block. The mandatory dispatch guard remains +installed when optional security scanners are disabled. **PATH is pinned across `.env` for the same reason the interpreter is.** The hook scripts resolve their tools by name — `tirith_check.py` runs a bare `tirith` — so a `.env` that prepends a directory holding a fake `tirith` that exits 0 neuters the entire PreToolUse chain while every digest stays -green. Reproduced before the pin existed. `Run` captures `PATH` into a readonly variable before -sourcing `.env` and restores it afterwards, and unsets `LD_PRELOAD`, `LD_LIBRARY_PATH` and +green. Reproduced before the pin existed. `Run` captures the base `PATH` into a readonly variable +before sourcing `.env`; scanners use that base path. Agent shells get the workspace helper and Go +directories plus the base path. `allow_login_shell=false` prevents startup files from discarding +those helper paths. `Run` also unsets `LD_PRELOAD`, `LD_LIBRARY_PATH` and `LD_AUDIT`, which would otherwise load code into any dynamically linked program the run starts — codex's own binary, `tirith`, `git` — before its `main`. The adapter strips `LD_*` and `PYTHON*` from the children's environment too, while passing the scripts' own configuration through. +The run command unsets `BASH_ENV`, `ENV`, `ZDOTDIR` and `SHELL` after `.env`: the image's non-interactive Bash hook +shell still reads `BASH_ENV`, which could otherwise exit before the dispatch guard executes. -**Why not record the config digest in the manifest.** It would be a digest in the same -agent-writable directory as the file it describes, so an agent could rewrite both and the guard would pass. That is -not theoretical: `projects."".trust_level = "trusted"` in `config.toml` makes codex load the +**Why the manifest is not a trust anchor.** Before Landlock, an agent could rewrite both the config +and a digest beside it. The inherited write restriction now prevents that within the launched +hierarchy; runner-held digests still detect external or pre-launch changes. The original failure +was reproducible: `projects."".trust_level = "trusted"` in `config.toml` makes codex load the target repo's own `.codex/config.toml`, which then supplies `developer_instructions`, `model`, and — under `--dangerously-bypass-hook-trust` — repo-authored hooks. Verified against 0.152.1: with the line the repo layer applied, without it it did not. An earlier grep-based guard here looked for a @@ -1352,6 +1363,68 @@ Two artefacts of the run are worth knowing about: `turn.failed` carrying the 404, not as a startup error — which is why `Run` returns 1 from the stream verdict rather than trusting the exit code. +### Native children (#6970) + +[ADR 0126](../ADRs/0126-runner-owned-codex-child-policy.md) describes the authority boundary. +`codex_personas.go` discovers personas from selected skills and renders native role TOML files. +The runner applies explicit persona model → `FULLSEND_CODEX_SUBAGENT_MODEL` → `subagents.default` → +`gpt-5.6-luna` precedence. Claude model/tool frontmatter is not native configuration. Generic and +Explore roles are explicit entries too; invalid mappings fail bootstrap. Only an agent with the +Agent tool (pi's `piAgentToolEnabled`) gets roles; any other agent gets `[agents] enabled = false`. + +The native configuration allows four open child IDs, including completed-but-unclosed children, +and depth one. A synchronous mandatory +PreToolUse guard rejects nested dispatch, inherited context, per-call model/effort overrides, +unknown roles and all resume calls. Native V1 cold resume can reconstruct a child with the root's +configuration, so it cannot preserve the role/model contract. A fresh spawn is required instead. +The runner requires a nonempty completed result and a close event for every successful spawn; +waiting for one child or merely seeing a successful spawn is insufficient. + +`codex_landlock.go` and the embedded launcher require Linux Landlock ABI 3 or newer. Configuration, +role and hook directories remain read-only, while native sessions, logs and SQLite state have +explicit writable paths; the runner re-seeds the credential placeholder outside the restricted +hierarchy. The launcher closes descriptors above stderr, +checks for symlinks/hardlinks and verifies authority after restriction. These controls apply to +the native hierarchy; shared tool hooks remain defense in depth, including their upstream +failure/timeout semantics. + +`codex_usage.go` folds `token_usage_record.payload.usage` **deltas**, deduplicated by native thread +and response ID. The corresponding turn context supplies the model. Persisted parent records +replace the stream snapshot when present, including usage incurred before an interrupted final +turn; completed and failed children's recorded usage is added once. Reasoning output is split from +other output tokens. Per-model `requests` counts native thread/model invocations with recorded +usage, not individual Responses API calls. Missing or inconsistent expected child evidence is an +error, not zero usage. + +Rollout enumeration and transfer are bounded and use private host staging, with a 256 MiB +aggregate transfer budget. A native JSONL record can exceed 1 MiB because command events retain +multiple copies of tool output. Persisted rollout readers accept records within that artifact +budget and validate the complete file. The live `exec --json` stream and its output redactor +instead have an 8 MiB record limit; an oversized live record fails evidence collection rather +than silently dropping child dispatch. Each complete JSONL file is redacted and atomically published; +partial transfers and unreadable directories +are errors. The runner retains expected thread IDs and raw file digests after usage collection; +extraction must publish the same root and child evidence. A disappeared file or +`codex transcript changed after usage collection for thread ` fails extraction; valid siblings +are retained, but a changed file is withheld. A stream that ended without a terminal event (a +timeout) keeps no digests, because Codex writes until the runner terminates it; extraction then +publishes the final bytes. `runtime.ErrIncompleteEvidence` lets the CLI preserve output, transcripts and metrics +while still failing the run, even if inline or sweep validation succeeds. It also stops further +iterations, since a retry cannot restore the missing evidence. Post-scripts cannot run +after that sentinel. Debug logs also use private staging before redaction and publication. + +### Native-child validation + +Validated locally at runtime `b668fee` with Codex CLI 0.157.0 and 0.158.0, `gpt-5.6-luna` as root +and child (V1 collaboration API) and medium effort: representative review and retro runs with the +[agents #1542](https://github.com/fullsend-ai/agents/pull/1542) instructions closed every child, +produced schema-valid output and reconciled root/child transcripts and usage. That build still had +the security collector and the image's venv Python, and predates the Agent-tool gate, the dispatch +matcher change and the pre-created `$HOME` entries; later changes have unit and Linux Landlock +tests but no live run. Not validated: lower effort, V2-selecting or mixed child models, other Codex +agents (code and fix have the Agent tool, so they get roles), live forge posting, CI Workload +Identity and the full fleet lifecycle. Reduced fixtures are in `internal/runtime/testdata/codex/native-subagents`. + ### Not yet exercised `runtime: codex` is selectable per repo or per agent. Outstanding: @@ -1362,13 +1435,16 @@ Two artefacts of the run are worth knowing about: and local smoke runs. - The rollout session files are archived as transcripts but not error-classified: only the tee'd `exec --json` capture yields a verdict, which is what the runner's exit-code override reads. -- Sub-agent rosters are not wired, so `review`/`retro` are unsupported; `Bootstrap` appends a runtime - note telling the agent to execute sub-agent definitions itself, in order, as it does for pi. +- General review/retro support requires the validated runtime and companion revisions together. + The local validation above does not establish the outstanding environments or close the + cross-repository merge dependency. Single-context execution is not an acceptable substitute. ### Re-check on a `CODEX_VERSION` bump | What | Why it matters | Where | |---|---|---| +| Native role rereads, state paths, hook inheritance and model-selected V1/V2 lifecycle | role/model authority, Landlock compatibility, depth/concurrency and complete child closure must still hold | native child source plus the pinned/latest live workflow matrix | +| `token_usage_record` response deltas and turn/model linkage | a cumulative snapshot or missing attribution can double-count or lose child usage | recorded native fixtures and parent/child reconciliation | | Hook exit-code semantics (0/2 blocking, everything else `Failed`) | the adapter's block translation is built on it; a change makes hooks fail open | `codex-rs/hooks/src/events/{pre,post}_tool_use.rs` | | `async` and `can_apply_control_effects` | a synchronous-only rule that changed would alter what the wiring must omit | `codex-rs/hooks/src/engine/mod.rs` | | `PostToolUse` output fields | if `updatedToolOutput` ever lands, the sanitizers can start redacting again | `codex-rs/hooks/src/schema.rs` | diff --git a/docs/guides/dev/tracing.md b/docs/guides/dev/tracing.md index c0b3d4a2d1..b45719fe39 100644 --- a/docs/guides/dev/tracing.md +++ b/docs/guides/dev/tracing.md @@ -110,8 +110,9 @@ Start attributes include: `fullsend.agent`, `fullsend.work_item_id`, `gen_ai.operation.name`, `gen_ai.agent.name`. End attributes (set in a deferred cleanup): `exit_code`, -`fullsend.cost_usd`, `fullsend.num_turns`, `fullsend.tool_calls`, -`fullsend.iterations`. +`fullsend.num_turns`, `fullsend.tool_calls`, `fullsend.iterations`, and +`fullsend.cost_usd` when dollar cost is available. Otherwise (including Codex), +`fullsend.cost_unavailable: true` is emitted and `fullsend.cost_usd` is omitted. For the full attribute list (including `fullsend.security_trace_id` and `fullsend.prescript.*`), see the @@ -131,8 +132,10 @@ The helper functions `agentSpanStartAttrs()` and `agentSpanEndAttrs()` build the attribute slices. Start attributes: `iteration`, `gen_ai.operation.name`, `gen_ai.agent.name`. End attributes: `iteration`, `exit_code`, `gen_ai.system` and `gen_ai.provider.name` (same serving-endpoint -value), model, token counts, `fullsend.cost_usd`, `fullsend.runtime`, -`fullsend.tool_calls`. Multi-provider runtimes resolve the provider from the +value), model, token counts, `fullsend.runtime`, and `fullsend.tool_calls`. +Cost follows the root span's rule: `fullsend.cost_usd` when available, otherwise +`fullsend.cost_unavailable: true` with no `fullsend.cost_usd` attribute. +Multi-provider runtimes resolve the provider from the effective model via `runtime.GenAISystemFor`; `System()` is only the fallback. ### execute_tool spans diff --git a/docs/guides/getting-started/choosing-a-runtime.md b/docs/guides/getting-started/choosing-a-runtime.md index 1f0b44fb81..9b71cdd24e 100644 --- a/docs/guides/getting-started/choosing-a-runtime.md +++ b/docs/guides/getting-started/choosing-a-runtime.md @@ -4,7 +4,7 @@ sidebar_label: Choose a Runtime # Choose an agent runtime -> **Claude Code is the stable default.** The fleet agents have run on Claude Code in production for a long time; it is what a new installation gets unless you ask for something else. **pi and codex are experimental** — pi works end to end for `triage`, `prioritize`, `code`, `fix` and `review`/`retro`; codex runs OpenAI models through the same secretless credential path but has no sub-agent roster yet, so `review`/`retro` are best left on Claude Code there. Neither runtime has completed a fleet pilot. Unless you are taking part in one, keep the default. +> **Claude Code is the stable default.** The fleet agents have run on Claude Code in production for a long time; it is what a new installation gets unless you ask for something else. **pi and codex are experimental** — pi works end to end for `triage`, `prioritize`, `code`, `fix` and `review`/`retro`. Codex supports native review and retro children within the [locally validated Luna/V1 profile](../../runtimes/codex.md#native-children), using the matching runtime and companion instructions. Its CI credential path remains unverified. Neither runtime has completed a fleet pilot. Unless you are taking part in one, keep the default. This page explains what the choice means and where it is made. **You do not select anything on this page** — the selection happens in the next step. On GitHub, [Configuring GitHub](configuring-github.md) asks when you run `fullsend github setup` (press Enter for `claude`) or you pass `--runtime`. On GitLab, pass `--runtime` to `fullsend repos install` — see [Configuring GitLab](configuring-gitlab.md). @@ -16,7 +16,7 @@ Fullsend supports multiple agent runtimes. A runtime is the program that runs in |---------|--------|-------------|-------------| | `claude` | **Stable (default)** | Claude Code on Vertex AI | Every production deployment — mature, full sub-agent support for `review`/`retro` | | `pi` | Experimental (enablement phase) | [Pi](https://github.com/earendil-works/pi) — Claude on Vertex by default; any provider pi supports by model name (e.g. Gemini on Vertex with the same credentials) | Opt-in pilots only; see [Runtimes](../../runtimes.md) for known constraints | -| `codex` | Experimental | [Codex](https://github.com/openai/codex) — OpenAI models only, through the same secretless credential path | Opt-in pilots only, when you want GPT specifically. No sub-agent roster, so keeping `review`/`retro` on Claude Code is recommended; needs an OpenAI model named (`FULLSEND_CODEX_MODEL`) because the fleet harnesses ask for `opus`; see [Codex](../../runtimes/codex.md) | +| `codex` | Experimental | [Codex](https://github.com/openai/codex) — OpenAI models only; local API-key validation, CI credential path not yet exercised | Opt-in pilots when you want GPT. Native review/retro require the companion work in [agents #1542](https://github.com/fullsend-ai/agents/pull/1542); the verified profile uses `openai/gpt-5.6-luna` with medium effort. Select an OpenAI model explicitly because the fleet harnesses request `opus`; see [Codex requirements and limits](../../runtimes/codex.md#native-children). | ## When and how the runtime is selected diff --git a/docs/guides/infrastructure/distributed-tracing.md b/docs/guides/infrastructure/distributed-tracing.md index 6f101015b5..a0f659a9c3 100644 --- a/docs/guides/infrastructure/distributed-tracing.md +++ b/docs/guides/infrastructure/distributed-tracing.md @@ -239,6 +239,7 @@ The `agent` span's provider identity reflects only the parent run's serving endp | `fullsend.work_item_id` | `run` | Work item identity (e.g. `owner/repo#123`); primary cross-run correlation key | | `fullsend.agent` | `run` | Agent name | | `fullsend.cost_usd` | `run` (aggregated), `agent` | Cost in USD, rounded to cents (see [Cost data contract](#cost-data-contract)) | +| `fullsend.cost_unavailable` | `run`, `agent` | Present (`true`) when dollar cost is unavailable; `fullsend.cost_usd` is then omitted | | `fullsend.tool_calls` | `run` (aggregated), `agent` | Number of tool invocations | | `fullsend.num_turns` | `run` | Total conversation turns across all iterations | | `fullsend.iterations` | `run` | Number of agent iterations (validation loop included) | @@ -279,7 +280,7 @@ Additional resource attributes from `OTEL_RESOURCE_ATTRIBUTES` are merged in. ## Cost data contract Fullsend does not calculate inference cost from token counts or maintain a -model-price table. Each runtime reports a USD cost value and fullsend +model-price table. When a runtime reports a USD cost value, fullsend records it as-is. This section defines the source, aggregation, rounding, and display behavior of that value across every output surface. @@ -292,6 +293,7 @@ Each runtime extracts cost differently from its agent process: | `claude` | Claude Code stream JSON | Reads `result.total_cost_usd` from the final result event — a single value covering the entire iteration | | `pi` | Pi assistant message stream | Sums `usage.cost.total` across all assistant messages in the iteration | | `opencode` | OpenCode step stream | Sums `step_finish.part.cost` across all step-finish events in the iteration | +| `codex` | No dollar-cost field | Sets `cost_unavailable: true`; parent and child token usage remains available | The runtime-reported value includes whatever the provider prices — input tokens, output tokens, cache-creation tokens, cache-read tokens, and @@ -311,13 +313,13 @@ sums raw costs: run_total_cost_usd = sum(iteration.total_cost_usd for each completed iteration) ``` -This sum is the single aggregate cost for the run, used by every -downstream surface. +If any iteration marks cost unavailable, the aggregate also marks it unavailable; +any numeric partial sum is not a complete price for the run. ### Rounding and precision by surface -The raw aggregate is a floating-point sum. Different output surfaces -apply different precision: +For available cost, the raw aggregate is a floating-point sum. Different output +surfaces apply different precision: | Surface | Value | Precision | Example | |---------|-------|-----------|---------| @@ -337,9 +339,12 @@ differently than the sum of parts. ### No pricing-table fallback -If a runtime does not report cost (returns zero or the field is absent), -fullsend records zero. There is no fallback cost calculation from token -counts. A missing runtime cost propagates as `$0.00` on all surfaces. +There is no fallback cost calculation from token counts. Codex explicitly marks +cost unavailable in aggregate and per-model metrics; its terminal result displays +unavailable, and run/agent spans omit `fullsend.cost_usd` and carry +`fullsend.cost_unavailable: true`. Consumers must check the availability flag before +interpreting a numeric zero. A zero without an availability signal from another +runtime retains that runtime's existing reporting behavior. ### Distinction from backend-derived cost estimates diff --git a/docs/guides/user/running-agents-locally.md b/docs/guides/user/running-agents-locally.md index b032823d9e..1b6bd8b8ff 100644 --- a/docs/guides/user/running-agents-locally.md +++ b/docs/guides/user/running-agents-locally.md @@ -229,6 +229,15 @@ fullsend run review \ --forge github ``` +To exercise review with Codex, use the companion native-child instructions and add +`--runtime codex --model openai/gpt-5.6-luna --effort medium --env-file fullsend-openai.env` +to the review command above. Keep the key in the runner's env file. Use +`--no-post-script` while validating so the run saves its output without posting a +review. Read the [Codex requirements and validation status](../../runtimes/codex.md#native-children) +first; the selected model must expose the verified native child lifecycle. +The local retro validation uses the same model and medium effort; supply its own +trigger inputs and retain `--no-post-script` while checking the generated proposals. + ### Code agent Add to an env file: diff --git a/docs/problems/agent-architecture.md b/docs/problems/agent-architecture.md index bc0cb40639..30d963f1f2 100644 --- a/docs/problems/agent-architecture.md +++ b/docs/problems/agent-architecture.md @@ -217,7 +217,7 @@ The multi-agent framework space is expanding rapidly, with new entries appearing ## Open questions -- Should agents be stateless (fresh context per task) or stateful (accumulated knowledge of the codebase)? Stateless is safer (no poisoned state persists) but less efficient. +- Should agents be stateless (fresh context per task) or stateful (accumulated knowledge of the codebase)? Stateless is safer (no poisoned state persists) but less efficient. (Native Codex delegation uses fresh child contexts and runner-owned role policy; see [ADR 0126](../ADRs/0126-runner-owned-codex-child-policy.md). Cross-task agent memory remains open.) - Should there be one instance of each agent type per repo, per org, or shared? Per-repo is simpler but more expensive. Shared agents need careful isolation. (Infrastructure constrains this — see [agent-infrastructure.md](agent-infrastructure.md).) - ~~What's the right model for agent identity? Agents need GitHub accounts to post comments and status checks. Separate bot accounts per agent role? A single bot account with role indicated in the comment? GitHub App installations?~~ Decided in [ADR 0007](../ADRs/0007-per-role-github-apps.md): per-role GitHub Apps with manifest-based creation. - How do we test the interaction model? Can we simulate adversarial scenarios (injection attempts, unauthorized changes, agent disagreements) in a sandbox repo? diff --git a/docs/problems/security-threat-model.md b/docs/problems/security-threat-model.md index 90ba71d00f..c06c34614b 100644 --- a/docs/problems/security-threat-model.md +++ b/docs/problems/security-threat-model.md @@ -91,7 +91,7 @@ In fullsend, agents cannot take forge actions directly — credentialed operatio Another injection variant documented in Shapira et al. (2026) bypasses the immutability principle by storing malicious instructions in an external resource (e.g., a GitHub Gist) that the agent references from its persistent state. The attacker convinces the agent to link to a shared document, then modifies the document after the fact to inject instructions the agent follows in subsequent sessions. -In fullsend's architecture, this is mitigated by several design decisions: agent configuration is immutable from within the sandbox ([ADR 0017](../ADRs/0017-credential-isolation-for-sandboxed-agents.md)), agents cannot modify their own guardrails (with one qualification: the sandbox *tool hook* scripts are written once at bootstrap and stay writable between iterations of the same run on Claude Code and pi — on the codex runtime they are digest-verified before every invocation, see [ADR 0100](../ADRs/0100-codex-sandbox-hooks.md)), and the harness validates agent output against a schema ([ADR 0022](../ADRs/0022-harness-level-output-schema-enforcement.md)). However, the pattern is worth noting because any mechanism that allows agents to fetch and follow external content (URLs in issues, linked documents, referenced specifications) creates a potential injection surface that persists across sessions. +In fullsend's architecture, this is mitigated by several design decisions: agent configuration is immutable from within the sandbox ([ADR 0017](../ADRs/0017-credential-isolation-for-sandboxed-agents.md)), agents cannot modify their own guardrails (with one qualification: the sandbox *tool hook* scripts are written once at bootstrap and stay writable between iterations of the same run on Claude Code and pi — the Codex hierarchy inherits a kernel write restriction protecting configuration, child roles and hooks, with runner-held digest checks as described in [ADR 0126](../ADRs/0126-runner-owned-codex-child-policy.md)), and the harness validates agent output against a schema ([ADR 0022](../ADRs/0022-harness-level-output-schema-enforcement.md)). However, the pattern is worth noting because any mechanism that allows agents to fetch and follow external content (URLs in issues, linked documents, referenced specifications) creates a potential injection surface that persists across sessions. ### Open questions diff --git a/docs/reference/config-reference.md b/docs/reference/config-reference.md index 9ae7a92ced..e5642401b5 100644 --- a/docs/reference/config-reference.md +++ b/docs/reference/config-reference.md @@ -182,6 +182,15 @@ effort, and sub-agent models. value tombstones an inherited entry. Keys must be lowercase alphanumeric segments joined by hyphens (max 64 chars). +For Codex, a named child uses its explicit `subagents.` override (`` other +than `default`), then `FULLSEND_CODEX_SUBAGENT_MODEL`, then `subagents.default`, then +`gpt-5.6-luna`. The generic `default` role starts with the environment variable; +`subagents.default` does not outrank it. +Use OpenAI model IDs; Claude aliases, `inherit`, unknown persona names and other +provider prefixes are rejected. A persona's Claude frontmatter does not override +this selection. See [Codex native children](../runtimes/codex.md#native-children) +for the supported model lifecycle and companion instruction requirements. + In the layered config system, agents use keyed merge by `DerivedName()` — see [Layered Config Reference](../guides/infrastructure/layered-config-reference.md). diff --git a/docs/runtimes.md b/docs/runtimes.md index f5d4e732ee..33bc2f75cf 100644 --- a/docs/runtimes.md +++ b/docs/runtimes.md @@ -55,13 +55,13 @@ sequenceDiagram | | Claude Code | pi | codex | |---|---|---|---| | Models | Anthropic on Vertex | Claude, **Grok** and **Gemini** on Vertex; **GPT** via OpenAI WIF (opt-in, [not yet exercised live](runtimes/pi.md#models-and-providers)) | **GPT only**, via OpenAI WIF ([not yet exercised live](runtimes/codex.md#not-yet-exercised)) | -| Sub-agents | Native (`Agent` tool) | `Agent`/`Task` via a fullsend extension | Not available | +| Sub-agents | Native (`Agent` tool) | `Agent`/`Task` via a fullsend extension | Native personas, generic and Explore children; [model/lifecycle constraints](runtimes/codex.md#native-children) | | Fallback model chain | `FULLSEND_FALLBACK_MODELS`, tried in order | Top-level run only: alias requests tried in order when Vertex does not serve the model ([two 404/403 messages](runtimes/pi.md#per-repo-alias-overrides)), same provider only; pinned ids and sub-agent children fail loudly | Ignored with a warning | -| Roles | All | All; `review`/`retro` at `--thinking medium` by default | Same recommendation as before — no sub-agent roster on codex | +| Roles | All | All; `review`/`retro` at `--thinking medium` by default | `review`/`retro` require the companion native-child instructions; [validation status](contributing/runtime-implementation.md#native-child-validation) | | Effort | `--effort low..max` | `--thinking`, same levels (`high` when unset) | `model_reasoning_effort`, same levels | -| Tools | Native Claude permission syntax | `--tools` (strict) + a first-token Bash allowlist | Shell + `apply_patch` only; `tools:` is recorded, not enforced (the allowlist hook is opt-in) | +| Tools | Native Claude permission syntax | `--tools` (strict) + a first-token Bash allowlist | Shell, `apply_patch`, native collaboration; `tools:` is recorded, not enforced (the allowlist hook is opt-in) | | Security controls | Full matrix | Full matrix; stricter on failed-call sanitizing | Full matrix; post-tool hooks detect and block but cannot rewrite output | -| Cost in `metrics.json` | Reported | Reported | Not reported — codex sends none | +| Cost in `metrics.json` | Reported | Reported | `cost_unavailable: true`; parent and child token usage reported | | Content capture (Level 3) | Text, reasoning, tool calls and tool results (correlating ids) | Text, reasoning, tool calls (no correlating ids) — pi's parser emits neither ids nor tool results yet ([#7414](https://github.com/fullsend-ai/fullsend/issues/7414)) | Text, reasoning, tool calls (no correlating ids) — codex's parser emits neither ids nor tool results ([#7414](https://github.com/fullsend-ai/fullsend/issues/7414)) | | Tool spans (`execute_tool`) | One per id-bearing tool call (server-side tools get none), up to 1,024 per iteration, a child of the iteration's `agent` span, timed at receipt | None — the parser emits no call ids ([#7414](https://github.com/fullsend-ai/fullsend/issues/7414)) | None — the parser emits no call ids ([#7414](https://github.com/fullsend-ai/fullsend/issues/7414)) | @@ -196,8 +196,9 @@ Harness `model:` and `agents:` entry `model:` values accept provider-qualified ` ### Per-repo alias overrides Point an alias at a different model for one repo with `models.aliases` in `.fullsend/config.yaml` -— `sonnet: claude-sonnet-5` changes `sonnet` and leaves the other aliases alone. Works on both -runtimes; the override applies to the parent run and to sub-agent dispatch on pi (children +— `sonnet: claude-sonnet-5` changes `sonnet` and leaves the other aliases alone. Alias overrides +apply to Claude Code and pi; Codex requires an explicit OpenAI model ID. The override applies to +the parent run and to sub-agent dispatch on pi (children resolve aliases through the same merged table). See [Pi › Per-repo alias overrides](runtimes/pi.md#per-repo-alias-overrides) for the syntax and what the plan block shows, and [Claude Code › Models](runtimes/claude.md#models) for the one limit there (sub-agent `model:` diff --git a/docs/runtimes/codex.md b/docs/runtimes/codex.md index f62151a81a..7d649db332 100644 --- a/docs/runtimes/codex.md +++ b/docs/runtimes/codex.md @@ -57,7 +57,7 @@ agents: Effort maps onto codex's own reasoning levels: -| `--effort` | Codex `model_reasoning_effort` | +| `--effort` | Root Codex `model_reasoning_effort`; native children retain their model defaults | |---|---| | `low` | `low` | | `medium` | `medium` | @@ -75,11 +75,92 @@ warning. | Credentials | A runner-exchanged OpenAI WIF token in CI, or your `OPENAI_API_KEY` on the runner locally — never in the sandbox. Codex reads a placeholder from a runner-owned token file and re-reads it when the credential is refreshed ([ADR 0092](../ADRs/0092-openai-wif-credential-delivery.md)) | | Unattended | Approvals off; codex's own sandbox off, because OpenShell is the boundary. A missing credential exits before the agent starts | | Artifacts | `output.jsonl` (the `codex exec --json` stream), `transcripts/-.jsonl`, `metrics.json` with `runtime: codex`, plus `codex-debug.log` with `--debug`. Only uncompressed rollouts are extracted — codex compresses older sessions, so a `.jsonl.zst` is never the run's own transcript. The agent's final message is in the stream; `--output-last-message` also drops it in the runner-owned config directory inside the sandbox, which is a convenience when inspecting a kept sandbox rather than a downloaded artifact | -| Extra knobs | `FULLSEND_CODEX_MODEL` (the runner-side model default for codex runs; see [Models](#models)) | -| Not supported | Sub-agents, `plugins:`, fallback chains, non-OpenAI providers | +| Extra knobs | `FULLSEND_CODEX_MODEL` (root model) and `FULLSEND_CODEX_SUBAGENT_MODEL` (child model default) | +| Sub-agents | Native named personas, generic and Explore children; see [Native children](#native-children) for model and lifecycle requirements | +| Not supported | `plugins:`, fallback chains, non-OpenAI providers, resuming children | + +Codex does not report dollar cost. The terminal displays **unavailable**, and aggregate and +per-model metrics carry `cost_unavailable: true`; a numeric zero in a legacy cost field is not +evidence of a free run. Token counts include the parent and children, including failed children +with recorded usage. Reasoning tokens are reported separately from non-reasoning output tokens. + +## Native children + +Fullsend registers personas found in the selected harness skills as native Codex roles. The +workflow selects the personas: review chooses its review dimensions and a separate challenger; +retro chooses investigations relevant to the failure and dispatches each with `agent_type: "default"`, +including read-only and duplicate checks. The generic `default` and `explore` roles +are available even when a harness supplies no personas. As on Claude Code and pi, only an agent +whose `tools:` frontmatter is absent or names `Agent` delegates. Any other agent gets no roles, +Codex's multi-agent tools are turned off, and its runtime note says to run each sub-agent +definition itself. Use the companion instructions tracked +in [agents #1542](https://github.com/fullsend-ai/agents/pull/1542); runtime support alone does not +teach an older workflow how to dispatch native children. + +For each child, model selection uses this precedence: + +1. Its explicit named override in `agents[].subagents.`, where `` is not `default`. +2. The runner's `FULLSEND_CODEX_SUBAGENT_MODEL`. +3. `agents[].subagents.default`. +4. `gpt-5.6-luna`. + +For the generic `default` role, selection starts at step 2: `subagents.default` never +outranks `FULLSEND_CODEX_SUBAGENT_MODEL`. -Cost is **not** in `metrics.json` on codex: the `codex exec --json` stream carries no cost field, so -the value stays `0`. Token counts are recorded normally. +```yaml +agents: + - name: review + runtime: codex + model: openai/gpt-5.6-luna + subagents: + default: openai/gpt-5.6-luna + security: openai/gpt-5.5 +``` + +Use an actual registered persona name for an explicit override. Unknown names, Claude aliases, +`inherit`, and non-OpenAI model prefixes are rejected. An unavailable explicit model fails rather +than falling back. Child models must be listed by the pinned CLI's `codex debug models --bundled`: +Codex resolves the default child model against that catalog on every spawn, named personas +included, so a missing default fails every spawn. Fullsend does not check this at Bootstrap. A null entry removes an inherited override. Claude `model:` and `tools:` +frontmatter in a persona is reported but does not control the native child. Every persona needs a +non-empty `description:`; Codex drops a role without one, so Bootstrap rejects it. + +`--effort` sets root reasoning effort. Generated child roles select the model but do not set +reasoning effort; native model defaults apply. In the local Luna runs, children used medium +even when the root used low. Compare recorded per-thread effort when interpreting usage. +The verified local Fullsend review/retro profile uses `openai/gpt-5.6-luna` with +`--effort medium`. Earlier low-effort runs missed required reads or child closure; the runner +rejects incomplete child evidence even when the final output passes its schema. + +Children start with fresh context (`fork_context: false`), their role instructions and the task +the parent explicitly supplies. The challenger therefore receives the review packet, without +inheriting the parent's conversation. At most four child IDs can remain open, including completed +children that have not been closed; children cannot +spawn grandchildren. The parent must wait for a final result from **every** child and close every +child before finishing, including the challenger. A wait that returns one completed child does +not mean the other children finished. Resuming a child is blocked; start a fresh child instead. + +These requirements apply even when optional security scanning is disabled. The native hierarchy +inherits a Linux Landlock write restriction protecting the runner's configuration, roles and +hook files. Bootstrap requires a system `python3` 3.11+ outside `/sandbox` and `/tmp`; launch +requires Landlock ABI 3 or newer. An incompatible sandbox fails before inference rather than +silently dropping this protection. `$HOME` (`/sandbox`) is the configuration's parent, so +processes cannot add new top-level entries to it. Bootstrap pre-creates `~/.cache`, `~/.cargo`, +`~/.config/git` (git `--global` writes its `config`), `~/.local` and `~/.npm`; tools that need +any other new `$HOME` entry (for example `~/.rustup` or `~/.m2`) fail with a permission error. + +Delegation requires Codex's V1 collaboration API. **The parent model's metadata selects that +API, not the child model override or CLI version alone.** The mandatory dispatch guard requires +`fork_context: false` and rejects V2 arguments; a V2 parent cannot delegate under this policy, +and there is no automatic model fallback. A run without delegation can still use other OpenAI +models. Local live workflow validation uses `gpt-5.6-luna` for both parent and children. +In the inspected model catalogue, `gpt-5.5` falls back to V1 and GPT-6 entries select V2; that inspection +is not live workflow validation of those models. Mixed-model children remain unverified. +Revalidate on a model or CLI change. + +Each child has a separate transcript named with its native thread ID. Missing child usage, +missing final results, unclosed children or transcript extraction failures fail the run even if +the final output passes its JSON schema. Artifacts and known usage are retained for diagnosis. ## Running it locally @@ -159,7 +240,8 @@ What a local codex run needs, beyond the guide: - **The repository's own `.codex/` config is never loaded.** fullsend pins the cloned repo's project trust to untrusted, so `.codex/config.toml` and `.codex/hooks.json` (model, instructions, MCP servers, hooks) never apply. A target repo cannot change how the agent runs. -- **Two tools, not a menu.** Codex works through a shell and `apply_patch`, so a harness `tools:` +- **Tool lists are not native permissions.** Codex works through a shell, `apply_patch` and native + collaboration tools, so a harness `tools:` list has no native allowlist to map onto. A `Bash(...)` allowlist is **recorded but not enforced** on codex, and the run says so: @@ -188,8 +270,12 @@ What a local codex run needs, beyond the guide: content before the agent sees them. Codex 0.157.0 also picks up `.codex/skills` even though the project is untrusted; that is not documented upstream and may change, so keep repository skills in `.agents/skills`. Codex's bundled skills (`skill-installer`, `imagegen` and friends) are - switched off, so an agent sees only yours. -- **No cost in metrics** — see [At a glance](#at-a-glance). + switched off, so an agent sees only yours. Harness skills are installed under their declared + frontmatter name (directory name when absent); duplicate names from different directories fail + bootstrap. Nested skills are retained when their parent directory is uploaded. +- **Shells are non-login shells.** This preserves the runner's workspace helper and Go paths, + including `fullsend-check-output`. Security scanners use a separately pinned base `PATH`. +- **Cost is unavailable** — see [At a glance](#at-a-glance). ## Not yet exercised @@ -202,16 +288,19 @@ has no default behaviour-test coverage; its scenario is gated. What was run, and is recorded in [codex runtime internals](../contributing/runtime-implementation.md#codex-runtime-internals-6920). -**Keep `review` and `retro` on Claude Code.** Codex has a `spawn_agent` tool, but fullsend does not -build a persona roster for it yet, so those two agents run in a single context instead of with their -reviewer personas. Nothing prevents a repo-wide `runtime: codex` from applying to them — they will -run — so pin them with `runtime: claude` on their `agents:` entries if you want the roster: +Native review and retro require both this runtime implementation and the companion instructions. +The cross-repository completion gate remains [#6970](https://github.com/fullsend-ai/fullsend/issues/6970) +and [agents #1500](https://github.com/fullsend-ai/agents/issues/1500). Local synthetic workflows +exercise analysis, child lifecycle, schema output, transcripts and usage; they do not establish +live forge retrieval/posting, CI Workload Identity, Fedora coverage or the full fleet lifecycle. +See the [validation status](../contributing/runtime-implementation.md#native-child-validation) +before treating the combination as generally available. -```yaml -agents: - - name: review - runtime: claude -``` +Security hooks can add model turns when a blocked tool needs an alternative. Those turns are +included in usage. Pre-tool denials and post-tool withholding were exercised in both parent and +child contexts. They do not terminate the session: the existing runner does not enforce +`security.escalation.on_critical: halt` on downloaded findings. Treat that as a remaining dependency, +not a verified run-level halt guarantee. ## Troubleshooting @@ -277,8 +366,12 @@ rewritten config can trust the target repo, which loads its .codex/ layer and it ``` The first two exit 97 and mean the hook wiring cannot be trusted; the third exits 98 and is the -credential-and-trust guard. All three are fail-closed by design. Between iterations the agent runs -as the same user as those files, so "did the agent write there?" is the question to ask first. +credential-and-trust guard. The Landlock launcher checks the same files first, so these appear +only for a missing manifest or a change made after its check. A Landlock setup or authority +failure, including a missing or changed file, exits 78 and fails the run with +`codex write protection failed`: Codex runs require Linux Landlock ABI 3+ (kernel 6.2+). The +launched Codex hierarchy cannot write these files; check the sandbox kernel and any external +sandbox mutation when diagnosing a failure. **`--debug "..."` fails with `accepts 1 arg(s)`.** `--debug` takes an optional value: write `--debug='*'` (with `=`). diff --git a/internal/cli/cost_availability_test.go b/internal/cli/cost_availability_test.go new file mode 100644 index 0000000000..52fe274caa --- /dev/null +++ b/internal/cli/cost_availability_test.go @@ -0,0 +1,64 @@ +package cli + +import ( + "encoding/json" + "testing" + + agentruntime "github.com/fullsend-ai/fullsend/internal/runtime" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.opentelemetry.io/otel/attribute" +) + +func TestCostAvailability_AggregateAndTelemetry(t *testing.T) { + var unknown agentruntime.RunMetrics + require.NoError(t, json.Unmarshal([]byte(`{"cost_unavailable":true,"input_tokens":10,"per_model_usage":{"model":{"cost_unavailable":true,"input_tokens":10}}}`), &unknown)) + known := agentruntime.RunMetrics{TotalCostUSD: 0.25, InputTokens: 5, + PerModelUsage: map[string]agentruntime.ModelUsage{"model": {CostUSD: 0.25, InputTokens: 5}}} + for _, unknownFirst := range []bool{false, true} { + var agg aggregateMetrics + if unknownFirst { + aggregateRunMetrics(&agg, &unknown, 1) + aggregateRunMetrics(&agg, &known, 2) + } else { + aggregateRunMetrics(&agg, &known, 1) + aggregateRunMetrics(&agg, &unknown, 2) + } + data, err := json.Marshal(agg) + require.NoError(t, err) + var fields map[string]any + require.NoError(t, json.Unmarshal(data, &fields)) + assert.Equal(t, true, fields["cost_unavailable"]) + assert.Equal(t, true, fields["per_model_usage"].(map[string]any)["model"].(map[string]any)["cost_unavailable"]) + assert.Equal(t, 0.25, agg.TotalCostUSD) + assert.Equal(t, 15, agg.TokenUsage.Input) + assertUnknownCostAttrs(t, rootSpanEndAttrs(agg, 2)) + } + assertUnknownCostAttrs(t, agentSpanEndAttrs(1, 0, "openai", "codex", &unknown)) +} + +func assertUnknownCostAttrs(t *testing.T, attrs []attribute.KeyValue) { + t.Helper() + got := make(map[attribute.Key]attribute.Value, len(attrs)) + for _, attr := range attrs { + got[attr.Key] = attr.Value + } + assert.NotContains(t, got, attribute.Key("fullsend.cost_usd"), "unreported cost must not emit a free or partial-cost measurement") + assert.Equal(t, attribute.BoolValue(true), got["fullsend.cost_unavailable"]) +} + +func TestCostAvailability_KnownZeroRemainsAReportedCost(t *testing.T) { + var agg aggregateMetrics + data, err := json.Marshal(agg) + require.NoError(t, err) + assert.NotContains(t, string(data), "cost_unavailable") + for _, attrs := range [][]attribute.KeyValue{ + rootSpanEndAttrs(agg, 1), + agentSpanEndAttrs(1, 0, "anthropic", "claude", &agentruntime.RunMetrics{}), + } { + assert.Contains(t, attrs, attribute.Float64("fullsend.cost_usd", 0)) + for _, attr := range attrs { + assert.NotEqual(t, attribute.Key("fullsend.cost_unavailable"), attr.Key) + } + } +} diff --git a/internal/cli/run.go b/internal/cli/run.go index 20cb1a664b..2b7f626d11 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -180,9 +180,10 @@ type statusOpts struct { // aggregateMetrics holds accumulated behavioral metrics across retry iterations. type aggregateMetrics struct { - NumTurns int `json:"num_turns"` - TotalCostUSD float64 `json:"total_cost_usd"` - TokenUsage struct { + NumTurns int `json:"num_turns"` + TotalCostUSD float64 `json:"total_cost_usd"` + CostUnavailable bool `json:"cost_unavailable,omitempty"` + TokenUsage struct { Input int `json:"input"` Output int `json:"output"` Reasoning int `json:"reasoning"` @@ -506,6 +507,13 @@ func newRunCmd() *cobra.Command { } func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRepo, fullsendBinary string, envFiles []string, noPostScript bool, debug string, forgeFlag string, eventFile string, rFlags resolveFlags, sOpts statusOpts, printer *ui.Printer, keepSandbox bool, oFlags runOverrideFlags) (runErr error) { + return runAgentWithRuntimeResolver(ctx, agentName, fullsendDir, outputBase, targetRepo, fullsendBinary, envFiles, noPostScript, debug, forgeFlag, eventFile, rFlags, sOpts, printer, keepSandbox, oFlags, resolveBackendFrom) +} + +// runAgentWithRuntimeResolver scopes backend injection to one invocation. Tests +// can exercise runner failure boundaries without replacing a package-global +// resolver that another concurrent run could observe. +func runAgentWithRuntimeResolver(ctx context.Context, agentName, fullsendDir, outputBase, targetRepo, fullsendBinary string, envFiles []string, noPostScript bool, debug string, forgeFlag string, eventFile string, rFlags resolveFlags, sOpts statusOpts, printer *ui.Printer, keepSandbox bool, oFlags runOverrideFlags, resolveRuntime func(runOverrides, runConfig, string) (agentruntime.Backend, string, error)) (runErr error) { printer.Banner(Version()) printer.Blank() printer.Header("Running agent: " + agentName) @@ -1050,7 +1058,7 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep } } } - runtimeBackend, runtimeConfigSource, runtimeErr := resolveBackendFrom(overrides, runCfg, agentName) + runtimeBackend, runtimeConfigSource, runtimeErr := resolveRuntime(overrides, runCfg, agentName) if runtimeErr != nil { switch { case errors.Is(runtimeErr, errParsingConfigRuntime): @@ -1568,6 +1576,7 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep // post-script defer must only run when validation has passed — running it // on unvalidated output would violate ADR 0022's zero-trust model. var validationPassed bool + var evidenceErr error defer func() { exitCode := telemetryExitCode(lastExitCode, runErr) @@ -2239,7 +2248,8 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep // models and Claude's fallbacks stay on Anthropic (#7245). genAISystem := agentruntime.GenAISystemFor(rt, h.Model, agentDefModel, configModelAliases) - for iteration := 1; iteration <= maxIterations; iteration++ { + // A retry cannot restore missing runtime evidence, so it stops inference. + for iteration := 1; iteration <= maxIterations && evidenceErr == nil; iteration++ { runCount = iteration transcriptErrorOverride = false @@ -2375,7 +2385,7 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep return cancelledErr } - if runErr != nil { + if runErr != nil && !errors.Is(runErr, agentruntime.ErrIncompleteEvidence) { attachIterationContent("error") finalizeAgentSpan(agentSpan, runErr, iteration, exitCode, genAISystem, rt.Name(), &metrics, "", toolSpans) printer.StepFail("Agent execution failed") @@ -2390,6 +2400,11 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep } return fmt.Errorf("running agent (iteration %d): %w", iteration, runErr) } + if runErr != nil { + // Preserve partial output and transcripts below, but a schema + // pass cannot replace required runtime evidence. + evidenceErr = errors.Join(evidenceErr, fmt.Errorf("running agent (iteration %d): %w", iteration, runErr)) + } lastExitCode = exitCode // Check the tee'd output.jsonl for is_error:true result events. @@ -2420,11 +2435,11 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep // that enum value means a model-side length stop, and telemetry // cuts are marked by fullsend.content.truncated instead. contentFinishReason := "stop" - if exitCode != 0 || transcriptErrMsg != "" { + if runErr != nil || exitCode != 0 || transcriptErrMsg != "" { contentFinishReason = "error" } attachIterationContent(contentFinishReason) - finalizeAgentSpan(agentSpan, nil, iteration, exitCode, genAISystem, rt.Name(), &metrics, transcriptErrMsg, toolSpans) + finalizeAgentSpan(agentSpan, runErr, iteration, exitCode, genAISystem, rt.Name(), &metrics, transcriptErrMsg, toolSpans) printer.Blank() // Non-zero exit is a warning, not a failure — the validation loop is the success gate. @@ -2472,6 +2487,9 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep printer.StepStart("Extracting transcripts") if err := tx.ExtractTranscripts(sandboxName, agentName, iterTranscriptDir); err != nil { printer.StepWarn("Failed to extract transcripts: " + err.Error()) + if errors.Is(err, agentruntime.ErrIncompleteEvidence) { + evidenceErr = errors.Join(evidenceErr, fmt.Errorf("extracting transcripts (iteration %d): %w", iteration, err)) + } } else { printer.StepDone(fmt.Sprintf("Transcripts extracted (%.1fs)", time.Since(transcriptStart).Seconds())) } @@ -2591,7 +2609,7 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep } break } - if iteration < maxIterations { + if iteration < maxIterations && evidenceErr == nil { printer.StepInfo(fmt.Sprintf("Will retry (%d iterations remaining)", maxIterations-iteration)) } } @@ -2681,7 +2699,7 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep } printer.Blank() - return runTerminalError(h.ValidationLoop != nil, validationPassed, lastIterTimedOut, runCount, lastIterElapsed, timeout) + return errors.Join(evidenceErr, runTerminalError(h.ValidationLoop != nil, validationPassed, lastIterTimedOut, runCount, lastIterElapsed, timeout)) } func bootstrapCommon(sandboxName, fullsendBinary string, h *harness.Harness) error { @@ -3648,12 +3666,15 @@ func agentSpanStartAttrs(iteration int, agentName string) []attribute.KeyValue { } func rootSpanEndAttrs(agg aggregateMetrics, runCount int) []attribute.KeyValue { - return []attribute.KeyValue{ + attrs := []attribute.KeyValue{ attribute.Int("fullsend.num_turns", agg.NumTurns), attribute.Int("fullsend.tool_calls", agg.ToolCalls), - attribute.Float64("fullsend.cost_usd", roundUSD(agg.TotalCostUSD)), attribute.Int("fullsend.iterations", runCount), } + if agg.CostUnavailable { + return append(attrs, attribute.Bool("fullsend.cost_unavailable", true)) + } + return append(attrs, attribute.Float64("fullsend.cost_usd", roundUSD(agg.TotalCostUSD))) } func agentSpanEndAttrs(iteration, exitCode int, system, runtimeName string, m *agentruntime.RunMetrics) []attribute.KeyValue { @@ -3670,9 +3691,13 @@ func agentSpanEndAttrs(iteration, exitCode int, system, runtimeName string, m *a attribute.Int("gen_ai.usage.output_tokens", m.OutputTokens), attribute.Int("gen_ai.usage.cache_creation.input_tokens", m.CacheCreationInputTokens), attribute.Int("gen_ai.usage.cache_read.input_tokens", m.CacheReadInputTokens), - attribute.Float64("fullsend.cost_usd", roundUSD(m.TotalCostUSD)), attribute.Int("fullsend.tool_calls", int(m.ToolCalls.Load())), } + if m.CostUnavailable { + attrs = append(attrs, attribute.Bool("fullsend.cost_unavailable", true)) + } else { + attrs = append(attrs, attribute.Float64("fullsend.cost_usd", roundUSD(m.TotalCostUSD))) + } if m.ReasoningTokens > 0 { attrs = append(attrs, attribute.Int("gen_ai.usage.reasoning_tokens", m.ReasoningTokens)) } @@ -3685,6 +3710,7 @@ func agentSpanEndAttrs(iteration, exitCode int, system, runtimeName string, m *a func aggregateRunMetrics(agg *aggregateMetrics, m *agentruntime.RunMetrics, iteration int) { agg.NumTurns += m.NumTurns agg.TotalCostUSD += m.TotalCostUSD + agg.CostUnavailable = agg.CostUnavailable || m.CostUnavailable agg.TokenUsage.Input += m.InputTokens agg.TokenUsage.Output += m.OutputTokens agg.TokenUsage.Reasoning += m.ReasoningTokens diff --git a/internal/cli/run_evidence_test.go b/internal/cli/run_evidence_test.go new file mode 100644 index 0000000000..932f5c33d4 --- /dev/null +++ b/internal/cli/run_evidence_test.go @@ -0,0 +1,172 @@ +package cli + +import ( + "bytes" + "context" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "testing" + "time" + + agentruntime "github.com/fullsend-ai/fullsend/internal/runtime" + "github.com/fullsend-ai/fullsend/internal/ui" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type evidenceTestRuntime struct { + agentruntime.DummyRuntime + runErr error + extractErr error + exitCode int + remoteDir string + runs int + extracted bool +} + +func (*evidenceTestRuntime) Bootstrap(agentruntime.BootstrapInput) error { return nil } + +func (r *evidenceTestRuntime) Run(_ context.Context, params agentruntime.RunParams, _ *ui.Printer, _ time.Time, metrics *agentruntime.RunMetrics) (int, error) { + r.runs++ + metrics.NumTurns = 2 + metrics.InputTokens = 17 + metrics.CostUnavailable = true + if err := os.WriteFile(filepath.Join(r.remoteDir, "result.json"), []byte(`{"ok":true}`+"\n"), 0o600); err != nil { + return -1, err + } + if err := os.WriteFile(params.OutputPath, []byte("{\"type\":\"turn.completed\"}\n"), 0o600); err != nil { + return -1, err + } + return r.exitCode, r.runErr +} + +func (r *evidenceTestRuntime) ExtractTranscripts(_, _ string, outputDir string) error { + r.extracted = true + if err := os.MkdirAll(outputDir, 0o700); err != nil { + return err + } + if err := os.WriteFile(filepath.Join(outputDir, "root.jsonl"), []byte("{\"preserved\":true}\n"), 0o600); err != nil { + return err + } + return r.extractErr +} + +func TestRunAgent_IncompleteEvidencePreservesArtifactsAndFailsValidationGate(t *testing.T) { + for _, tc := range []struct { + name string + runErr error + extractErr error + exitCode int + sweep bool + retry bool + wantErr bool + }{ + {name: "missing runtime evidence", runErr: fmt.Errorf("missing child: %w", agentruntime.ErrIncompleteEvidence), exitCode: 1, wantErr: true}, + {name: "missing evidence stops validation retries", runErr: agentruntime.ErrIncompleteEvidence, exitCode: 1, retry: true, wantErr: true}, + {name: "missing extracted evidence", extractErr: fmt.Errorf("missing child transcript: %w", agentruntime.ErrIncompleteEvidence), wantErr: true}, + {name: "sweep cannot erase missing evidence", extractErr: agentruntime.ErrIncompleteEvidence, sweep: true, wantErr: true}, + {name: "ordinary extraction warning remains nonfatal", extractErr: errors.New("optional transcript unavailable")}, + {name: "ordinary nonzero exit remains validation gated", exitCode: 1}, + } { + t.Run(tc.name, func(t *testing.T) { + neutralizeAgentsRepoFallback(t) + for _, key := range []string{"GITHUB_ACTIONS", "GITHUB_OUTPUT", "FULLSEND_MINT_URL", "FULLSEND_GCP_OIDC_URL", "ACTIONS_ID_TOKEN_REQUEST_URL", "ACTIONS_ID_TOKEN_REQUEST_TOKEN", "TRACEPARENT", "FULLSEND_RUNTIME", "FULLSEND_MODEL", "OTEL_EXPORTER_OTLP_ENDPOINT", "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"} { + t.Setenv(key, "") + } + t.Setenv("TMPDIR", t.TempDir()) + t.Setenv("FULLSEND_SANDBOX_ARCH", "amd64") + dir, outputBase, repoDir, remoteDir := t.TempDir(), t.TempDir(), t.TempDir(), t.TempDir() + t.Setenv("FULLSEND_EVIDENCE_TEST_REMOTE", remoteDir) + if tc.sweep { + t.Setenv("FULLSEND_EVIDENCE_TEST_FAIL_REPO", "1") + } else { + t.Setenv("FULLSEND_EVIDENCE_TEST_FAIL_REPO", "") + } + postMarker := filepath.Join(dir, "post-ran") + validate := "#!/bin/sh\nset -eu\ntest -s \"$FULLSEND_OUTPUT_SCHEMA\"\ntest \"$(cat output/result.json)\" = '{\"ok\":true}'\necho 'schema fixture passed'\n" + maxIterations := 1 + if tc.retry { + validate += "exit 1\n" + maxIterations = 2 + } + files := map[string]string{ + "config.yaml": "agents:\n - harness/probe.yaml\n", + "agents/probe.md": "Return a valid result.\n", + "schema.json": `{"type":"object","required":["ok"],"properties":{"ok":{"const":true}},"additionalProperties":false}`, + "validate.sh": validate, + "post.sh": "#!/bin/sh\ntouch " + shellQuoteForTest(postMarker) + "\n", + "harness/probe.yaml": fmt.Sprintf("agent: agents/probe.md\nrole: test\nsecurity:\n enabled: false\npost_script: post.sh\nvalidation_loop:\n max_iterations: %d\n script: validate.sh\n schema: schema.json\n", maxIterations), + } + for name, contents := range files { + path := filepath.Join(dir, name) + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, os.WriteFile(path, []byte(contents), 0o755)) + } + // This ELF header only satisfies host-side upload validation. The + // openshell stub never executes it or any sandbox command. + elfHeader := make([]byte, 64) + copy(elfHeader, []byte{0x7f, 'E', 'L', 'F', 2, 1, 1}) + binary.LittleEndian.PutUint16(elfHeader[16:], 2) + binary.LittleEndian.PutUint16(elfHeader[18:], 62) + binary.LittleEndian.PutUint32(elfHeader[20:], 1) + binary.LittleEndian.PutUint16(elfHeader[52:], 64) + localBinary := filepath.Join(dir, "test-linux-binary") + require.NoError(t, os.WriteFile(localBinary, elfHeader, 0o600)) + binDir := t.TempDir() + stub := `#!/bin/sh +set -eu +case "$1 $2" in + 'gateway list') echo test-gateway ;; + 'sandbox get') echo 'Phase: Ready' ;; + 'sandbox exec') + for command do :; done + case "$command" in + 'find /sandbox/workspace/output -type f'*) echo /sandbox/workspace/output/result.json ;; + *'echo NOTOKEN'*) echo NOTOKEN ;; + esac ;; + 'sandbox download') + case "$4" in + /sandbox/workspace/output/result.json) mkdir -p "$5"; cp "$FULLSEND_EVIDENCE_TEST_REMOTE/result.json" "$5/result.json" ;; + *) test -z "$FULLSEND_EVIDENCE_TEST_FAIL_REPO" || exit 1; mkdir -p "$5" ;; + esac ;; + 'sandbox create'|'sandbox delete'|'sandbox upload'|'logs '*) ;; + *) echo "unexpected openshell operation: $1 $2" >&2; exit 1 ;; +esac +` + require.NoError(t, os.WriteFile(filepath.Join(binDir, "openshell"), []byte(stub), 0o755)) + t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH")) + rt := &evidenceTestRuntime{runErr: tc.runErr, extractErr: tc.extractErr, exitCode: tc.exitCode, remoteDir: remoteDir} + resolver := func(runOverrides, runConfig, string) (agentruntime.Backend, string, error) { + return agentruntime.Backend{Runtime: rt, Transcripts: rt}, "test", nil + } + var out bytes.Buffer + err := runAgentWithRuntimeResolver(context.Background(), "probe", dir, outputBase, repoDir, localBinary, nil, false, "", "", "", resolveFlags{maxDepth: 10, maxResources: 50}, statusOpts{}, ui.New(&out), false, runOverrideFlags{}, resolver) + if tc.wantErr { + assert.ErrorIs(t, err, agentruntime.ErrIncompleteEvidence, out.String()) + assert.NoFileExists(t, postMarker, "incomplete evidence must suppress post-script side effects") + } else { + require.NoError(t, err, out.String()) + assert.FileExists(t, postMarker) + } + require.Equal(t, 1, rt.runs, "a retry cannot restore missing evidence: %s", out.String()) + assert.NotContains(t, out.String(), "Will retry") + assert.True(t, rt.extracted, "runtime evidence errors must still collect available transcripts") + assert.Contains(t, out.String(), "schema fixture passed", "the output passes validation independently of evidence completeness") + runs, err := filepath.Glob(filepath.Join(outputBase, "fs-*")) + require.NoError(t, err) + require.Len(t, runs, 1) + assert.FileExists(t, filepath.Join(runs[0], "iteration-1", "transcripts", "root.jsonl")) + assert.FileExists(t, filepath.Join(runs[0], "iteration-1", "output", "result.json")) + data, err := os.ReadFile(filepath.Join(runs[0], "metrics.json")) + require.NoError(t, err) + var metrics aggregateMetrics + require.NoError(t, json.Unmarshal(data, &metrics)) + assert.Equal(t, 17, metrics.TokenUsage.Input) + assert.True(t, metrics.CostUnavailable) + }) + } +} diff --git a/internal/runtime/codex_bootstrap.go b/internal/runtime/codex_bootstrap.go index e4fd5cbb9b..e841efdd1d 100644 --- a/internal/runtime/codex_bootstrap.go +++ b/internal/runtime/codex_bootstrap.go @@ -9,6 +9,8 @@ import ( "strings" "time" + "github.com/google/uuid" + "github.com/fullsend-ai/fullsend/internal/sandbox" "github.com/fullsend-ai/fullsend/internal/security" ) @@ -103,6 +105,7 @@ const codexLastMessageFile = "last-message.txt" // manifest Run reads. It also preflights the pinned codex binary so a broken // image fails here rather than as a silent zero-turn run. func (r CodexRuntime) Bootstrap(input BootstrapInput) error { + clearCodexTranscriptIdentities(input.SandboxName()) agentPath := input.AgentPath() if agentPath == "" { return fmt.Errorf("agent path is required") @@ -132,13 +135,32 @@ func (r CodexRuntime) Bootstrap(input BootstrapInput) error { agentName = strings.TrimSuffix(agentDestName("", agentPath), ".md") } + // As on Claude and pi, only an agent with the Agent tool delegates. With + // no roster the dispatch guard denies every spawn, and codexPersonaConfig + // turns Codex's multi-agent tools off. + var roles []codexPersona + if piAgentToolEnabled(def) { + if roles, err = codexPersonas(input, agentName); err != nil { + return err + } + } sandboxName := input.SandboxName() cfg := r.ConfigDir() + version, err := codexPreflightVersion(sandboxName) + if err != nil { + return err + } // codex refuses to start when CODEX_HOME is not a directory, and the - // sessions directory is where its rollout transcripts land. - mkdirCmd := fmt.Sprintf("mkdir -p %s %s %s", - shellQuote(cfg+"/skills"), shellQuote(r.codexSessionsDir()), shellQuote(r.codexHooksDir())) + // sessions directory is where its rollout transcripts land. /sandbox is + // $HOME and CODEX_HOME's parent, so the Landlock launcher grants only the + // entries it already has: pre-create the common tool homes. git --global + // writes the XDG file when ~/.gitconfig is absent. + // ponytail: fixed list; any other new top-level $HOME entry (~/.rustup, + // ~/.m2, ~/.gitconfig) still fails. Moving CODEX_HOME and codex-policy out + // of /sandbox lifts the limit. + mkdirCmd := fmt.Sprintf("mkdir -p %s %s %s %s /sandbox/.cache /sandbox/.cargo /sandbox/.config/git /sandbox/.local /sandbox/.npm && touch /sandbox/.config/git/config", + shellQuote(cfg+"/skills"), shellQuote(r.codexSessionsDir()), shellQuote(r.codexHooksDir()), shellQuote(codexRolesDir)) if err := codexExecOK(sandboxName, mkdirCmd, "creating codex config dirs"); err != nil { return err } @@ -151,6 +173,12 @@ func (r CodexRuntime) Bootstrap(input BootstrapInput) error { if err != nil { return err } + configTOML = append(configTOML, []byte(codexPersonaConfig(roles, codexRolesDir))...) + for _, role := range roles { + if err := uploadBytes(sandboxName, codexRolesDir+"/"+role.Name+".toml", role.config()); err != nil { + return fmt.Errorf("writing codex role %s: %w", role.Name, err) + } + } if err := uploadBytes(sandboxName, r.codexConfigPath(), configTOML); err != nil { return fmt.Errorf("writing %s: %w", codexConfigFile, err) } @@ -159,6 +187,29 @@ func (r CodexRuntime) Bootstrap(input BootstrapInput) error { digests := codexRunnerHeldDigestSet{ ConfigTOML: codexAssetSHA256(configTOML), AgentModel: def.Model, + Roles: map[string]string{}, + } + for _, role := range roles { + digests.Roles[role.Name+".toml"] = codexAssetSHA256(role.config()) + } + python, err := codexPreflightPython(sandboxName) + if err != nil { + return err + } + digests.Python = python + for _, dir := range codexStateDirs { + if err := codexExecOK(sandboxName, "mkdir -p "+shellQuote(cfg+"/"+dir), "creating codex state directory"); err != nil { + return err + } + } + for _, name := range codexStateFiles { + var content []byte + if name == "installation_id" { + content = []byte(uuid.NewString()) + } + if err := uploadBytes(sandboxName, cfg+"/"+name, content); err != nil { + return fmt.Errorf("initializing codex state: %w", err) + } } // uploadBytes does not set a mode, and codex executes this one. @@ -173,19 +224,9 @@ func (r CodexRuntime) Bootstrap(input BootstrapInput) error { return err } - if err := duplicateDestinationNameError("skill", input.SkillDirs()); err != nil { + if err := codexUploadSkills(sandboxName, cfg, input.SkillDirs()); err != nil { return err } - for _, skillPath := range input.SkillDirs() { - if skillPath == "" { - continue - } - // codex discovers $CODEX_HOME/skills natively. - if err := sandbox.Upload(sandboxName, skillPath, cfg+"/skills/"); err != nil { - return fmt.Errorf("copying skill %q: %w", skillPath, err) - } - fmt.Fprintf(os.Stderr, "Skill %q: uploaded to sandbox\n", resolveSkillDisplayName(skillPath)) - } for _, e := range input.Plugins() { if e.Path != "" { @@ -211,6 +252,7 @@ func (r CodexRuntime) Bootstrap(input BootstrapInput) error { BashAllowlist: def.BashAllowlist, } + hooksJSON := []byte(`{"hooks":{}}`) if hooksInput, ok := input.(SandboxHooksBootstrap); ok { hooks := hooksInput.SandboxHookConfig() if err := installHookScripts(sandboxName, r.codexHooksDir(), hooks); err != nil { @@ -241,28 +283,25 @@ func (r CodexRuntime) Bootstrap(input BootstrapInput) error { if err := uploadBytes(sandboxName, r.codexAdapterPath(), codexHookAdapterPy); err != nil { return fmt.Errorf("installing hook adapter: %w", err) } - python, err := codexPreflightPython(sandboxName) - if err != nil { - return err - } - hooksJSON, notes, err := codexHooksJSON(cfg, python, hooks) + var notes []string + hooksJSON, notes, err = codexHooksJSON(cfg, python, hooks) if err != nil { return err } for _, note := range notes { fmt.Fprintf(os.Stderr, "Sandbox hooks: %s\n", note) } - if err := uploadBytes(sandboxName, r.codexHooksPath(), hooksJSON); err != nil { - return fmt.Errorf("writing %s: %w", codexHooksFile, err) - } - digests.HooksJSON = codexAssetSHA256(hooksJSON) manifest.Hooks = codexHooksManifestFor(r.codexHooksDir(), hooks) } - - version, err := codexPreflightVersion(sandboxName) + hooksJSON, err = codexAddDispatchGuard(hooksJSON, python, roles) if err != nil { return err } + if err := uploadBytes(sandboxName, r.codexHooksPath(), hooksJSON); err != nil { + return fmt.Errorf("writing %s: %w", codexHooksFile, err) + } + digests.HooksJSON = codexAssetSHA256(hooksJSON) + manifest.CodexVersion = version manifestJSON, err := json.MarshalIndent(manifest, "", " ") @@ -308,15 +347,18 @@ func codexDeveloperInstructions(agentName string, def *piAgentDef) string { } b.WriteString(def.Body) b.WriteString("\n") - b.WriteString(codexNoSubagentNote) + if piAgentToolEnabled(def) { + b.WriteString(codexSubagentNote) + } else { + b.WriteString(codexNoSubagentNote) + } return b.String() } // codexNoSubagentNote makes the absence of a sub-agent tool explicit so skills -// written for Claude Code's Agent tool (pr-review, retro) take their -// single-context path deliberately instead of recording a failed dispatch. -// codex does have a spawn_agent tool, but fullsend wires no sub-agent roster -// for it in v1, the same position pi was in (#6527). +// written for Claude Code's Agent tool take their single-context path +// deliberately instead of recording a failed dispatch. Bootstrap registers no +// roles for an agent whose tools: list omits Agent, as pi does (#6527). const codexNoSubagentNote = "\n## Runtime note\n\n" + "This agent runs on the codex runtime (FULLSEND_RUNTIME=codex). No fullsend sub-agent " + "roster is available. When a skill says to dispatch sub-agents, execute each sub-agent " + @@ -456,9 +498,11 @@ func codexReadHarnessSecurityEnv(sandboxName string) ([]codexEnvPair, error) { // will name. It is resolved here, on a shell the agent has not touched, rather // than left as a bare `python3` in hooks.json: codex spawns hooks after the // agent-writable .env is sourced, so PATH resolution at that point is the -// agent's to influence. +// agent's to influence. The image's PATH is too: it leads with the +// agent-writable /sandbox/.venv, whose .pth files -I still loads, so +// `command -p` searches only the system path. func codexPreflightPython(sandboxName string) (string, error) { - stdout, _, exitCode, err := sandbox.Exec(sandboxName, "command -v python3", 10*time.Second) + stdout, _, exitCode, err := sandbox.Exec(sandboxName, "command -p -v python3", 10*time.Second) if err != nil { return "", fmt.Errorf("resolving python3 for the hook adapter: %w", err) } @@ -490,7 +534,7 @@ func codexPreflightPython(sandboxName string) (string, error) { const codexMinPythonMinor = 11 func codexPreflightPythonVersion(sandboxName, python string) error { - cmd := shellQuote(python) + ` -c 'import sys; print("%d.%d" % sys.version_info[:2])'` + cmd := shellQuote(python) + ` -I -c 'import os, sys; print("%d.%d" % sys.version_info[:2], *map(os.path.realpath, (sys.executable, sys.prefix, sys.base_prefix)), sep="\t")'` stdout, stderr, exitCode, err := sandbox.Exec(sandboxName, cmd, 10*time.Second) if err != nil { return fmt.Errorf("checking the hook interpreter version: %w", err) @@ -499,10 +543,12 @@ func codexPreflightPythonVersion(sandboxName, python string) error { return fmt.Errorf("checking the hook interpreter version: exited %d: %s", exitCode, strings.TrimSpace(sanitizeOutput(stderr))) } - version := strings.TrimSpace(stdout) - if i := strings.LastIndexByte(version, '\n'); i >= 0 { - version = strings.TrimSpace(version[i+1:]) + line := strings.TrimSpace(stdout) + if i := strings.LastIndexByte(line, '\n'); i >= 0 { + line = strings.TrimSpace(line[i+1:]) } + fields := strings.Split(line, "\t") + version := fields[0] major, minor, ok := strings.Cut(version, ".") if !ok || major != "3" { return fmt.Errorf("hook interpreter %s reports version %q, expected 3.x", python, sanitizeOutput(version)) @@ -516,6 +562,17 @@ func codexPreflightPythonVersion(sandboxName, python string) error { "hook interpreter %s is Python %s; the sandbox hook adapter needs at least 3.%d", python, sanitizeOutput(version), codexMinPythonMinor) } + // The launcher, dispatch guard and hooks all run on this interpreter, so + // neither it nor its site-packages or stdlib may be agent-writable. + if len(fields) != 4 { + return fmt.Errorf("hook interpreter %s did not report its location", python) + } + for _, path := range fields[1:] { + if !strings.HasPrefix(path, "/") || codexUnderWriteRoot(path) { + return fmt.Errorf("hook interpreter %s loads from %q, which the agent can write; Codex needs a system python3 outside %s", + python, sanitizeOutput(path), strings.Join(codexWriteRoots, ", ")) + } + } return nil } diff --git a/internal/runtime/codex_bootstrap_test.go b/internal/runtime/codex_bootstrap_test.go index 10e6af271a..4444061b77 100644 --- a/internal/runtime/codex_bootstrap_test.go +++ b/internal/runtime/codex_bootstrap_test.go @@ -24,13 +24,15 @@ import ( func fakeOpenshellCodex(t *testing.T, logPath, storeDir, versionOutput string, streamFixture ...string) { t.Helper() require.NoError(t, os.MkdirAll(storeDir, 0o755)) - streamCase := "exit 0" + streamCase := `exit "${FULLSEND_TEST_RUN_EXIT:-0}"` if len(streamFixture) > 0 && streamFixture[0] != "" { streamCase = "cat '" + streamFixture[0] + "'; exit 0" } - findCase := "exit 0" + findCase := "echo '[]'; exit 0" if len(streamFixture) > 1 && streamFixture[1] != "" { - findCase = "echo '" + streamFixture[1] + "'; exit 0" + listing, err := json.Marshal(strings.Split(streamFixture[1], "\n")) + require.NoError(t, err) + findCase = "printf '%s\\n' " + shellQuote(string(listing)) + "; exit 0" } binDir := t.TempDir() script := `#!/bin/sh @@ -61,12 +63,19 @@ if [ "$2" = "exec" ]; then for last; do :; done case "$last" in "codex --version") echo "` + versionOutput + `"; exit 0 ;; - "command -v python3") echo "/usr/bin/python3"; exit 0 ;; - *"sys.version_info"*) echo "${FULLSEND_TEST_PYVER:-3.12}"; exit 0 ;; + "command -p -v python3") echo "/usr/bin/python3"; exit 0 ;; + *"sys.version_info"*) printf '%s\t/usr/bin/python3.12\t%s\t/usr\n' "${FULLSEND_TEST_PYVER:-3.12}" "${FULLSEND_TEST_PYPREFIX:-/usr}"; exit 0 ;; *fullsend-env-sep*) printf '%s' "${FULLSEND_TEST_ENV_READ-|fullsend-env-sep|}"; exit 0 ;; cat\ *) f=$(printf '%s' "${last#cat }" | tr -d "'" | tr '/' '_'); cat '` + storeDir + `'/"$f"; exit $? ;; + *"fullsend-codex-rollout"*) + default_body='{"type":"session_meta","payload":{}}' + case "$last" in + *planted*) printf 'not a rollout\n' ;; + *) printf '%s\n' "${FULLSEND_TEST_DOWNLOAD_BODY:-$default_body}" ;; + esac + exit 0 ;; *"exec --json"*) ` + streamCase + ` ;; - find\ *) ` + findCase + ` ;; + *"fullsend-codex-list"*) ` + findCase + ` ;; esac exit 0 fi @@ -92,6 +101,10 @@ model: openai/gpt-5.6-luna You are the triage agent. Use gh. ` +// codexTestReviewAgentDef declares no tools: list, so it keeps the Agent tool +// and delegates to native children. +const codexTestReviewAgentDef = "---\nname: review\ndescription: Review a change.\n---\nYou are the review agent.\n" + func TestCodexRuntimeBootstrap_WritesConfigAndManifest(t *testing.T) { logPath := filepath.Join(t.TempDir(), "openshell.log") storeDir := t.TempDir() @@ -117,6 +130,8 @@ func TestCodexRuntimeBootstrap_WritesConfigAndManifest(t *testing.T) { // does not do on its own. assert.Equal(t, codexAuthScriptSH, storedUpload(t, storeDir, r.codexAuthScriptPath())) assert.Contains(t, readFileString(t, logPath), "chmod 755 '"+r.codexAuthScriptPath()+"'") + // Landlock grants only $HOME entries that exist at launch. + assert.Contains(t, readFileString(t, logPath), "/sandbox/.npm && touch /sandbox/.config/git/config") var m codexManifest require.NoError(t, json.Unmarshal(storedUpload(t, storeDir, r.codexManifestPath()), &m)) @@ -129,10 +144,16 @@ func TestCodexRuntimeBootstrap_WritesConfigAndManifest(t *testing.T) { assert.Equal(t, []string{"gh", "jq"}, m.BashAllowlist) assert.Nil(t, m.Hooks, "no hook plan when the input carries no sandbox hook config") - // Without SandboxHooksBootstrap nothing hook-related is installed. + // Native dispatch policy is always installed, independently of shared security hooks. log := readFileString(t, logPath) assert.NotContains(t, log, codexAdapterFile) - assert.NotContains(t, log, codexHooksFile) + assert.Contains(t, log, codexHooksFile) + // tools: omits Agent, so triage runs sub-agent definitions inline (#6970). + assert.Contains(t, cfg, "No fullsend sub-agent roster is available") + assert.NotContains(t, cfg, "Use native spawn_agent") + assert.Equal(t, map[string]any{"enabled": false}, codexParseTOML(t, []byte(cfg))["agents"], "no roles, and no native multi-agent tools") + assert.NotContains(t, log, codexRolesDir+"/") + assert.Contains(t, string(storedUpload(t, storeDir, r.codexHooksPath())), shellQuote("[]"), "the guard denies every spawn") } func TestCodexRuntimeBootstrap_RejectsAgentNameMismatch(t *testing.T) { @@ -262,14 +283,23 @@ func TestCodexDeveloperInstructions(t *testing.T) { def, err := parsePiAgent([]byte(codexTestAgentDef)) require.NoError(t, err) got := codexDeveloperInstructions("triage", def) - assert.Contains(t, got, "# Agent: triage") assert.Contains(t, got, "Inspect an issue.") assert.Contains(t, got, "You are the triage agent. Use gh.") - // Skills written for Claude Code's Agent tool must take their - // single-context path deliberately rather than recording a failed - // dispatch (the same note pi carries, #6527). - assert.Contains(t, got, "No fullsend sub-agent roster is available") + assert.Contains(t, got, "execute each sub-agent definition yourself", "tools: omits Agent") + assert.NotContains(t, got, "spawn_agent") + + def, err = parsePiAgent([]byte(codexTestReviewAgentDef)) + require.NoError(t, err) + got = codexDeveloperInstructions("review", def) + assert.Contains(t, got, "Use native spawn_agent") + assert.Contains(t, got, "fork_context=false") + assert.Contains(t, got, "Delegation requires a V1 parent") + assert.Contains(t, got, "V2 arguments (fork_turns or task_name) are rejected") + assert.NotContains(t, got, "fork_turns=\"none\"") + assert.Contains(t, got, "only ONE child finishes") + assert.Contains(t, got, "close_agent") + assert.NotContains(t, got, "execute each sub-agent definition yourself") } func TestReadCodexManifest_RejectsGarbage(t *testing.T) { @@ -326,18 +356,33 @@ func TestCodexRuntimeBootstrap_ReportsInfrastructureFailures(t *testing.T) { "auth script": {codexAuthScriptFile, "writing " + codexAuthScriptFile}, "version": {"codex --version", "codex preflight"}, "manifest": {codexManifestFile, "writing " + codexManifestFile}, + "native role": {codexRolesDir + "/default.toml", "writing codex role default"}, + "python": {"command -p -v python3", "resolving python3"}, + "state dir": {"mkdir -p " + shellQuote(r.ConfigDir()+"/archived_sessions"), "creating codex state directory"}, + "state file": {r.ConfigDir() + "/installation_id", "initializing codex state"}, + "hooks.json": {codexHooksFile, "writing " + codexHooksFile}, } { t.Run(name, func(t *testing.T) { - fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "codex-cli 0.152.1") + storeDir := t.TempDir() + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), storeDir, "codex-cli 0.157.0") t.Setenv("FULLSEND_TEST_FAIL_MATCH", tc.match) + sandboxName := "bootstrap-infrastructure-failure" + t.Cleanup(func() { forgetRunnerHeldDigests(sandboxName) }) err := r.Bootstrap(bootstrapInput{ - sandboxName: "sb", - agentPath: writeAgentFile(t, codexTestAgentDef), - agentName: "triage", + sandboxName: sandboxName, + agentPath: writeAgentFile(t, codexTestReviewAgentDef), + agentName: "review", }) require.Error(t, err) assert.Contains(t, err.Error(), tc.want) + // A partially installed role/configuration must never become a + // trusted input for Run, even if earlier uploads succeeded. + _, trusted := lookupRunnerHeldDigests(sandboxName) + assert.False(t, trusted, "failed bootstrap must not publish integrity digests") + manifestPath := filepath.Join(storeDir, strings.ReplaceAll(r.codexManifestPath(), "/", "_")) + _, statErr := os.Stat(manifestPath) + assert.ErrorIs(t, statErr, os.ErrNotExist, "failed bootstrap must not publish its manifest") }) } } @@ -458,6 +503,25 @@ func TestCodexPreflightPythonVersion(t *testing.T) { assert.Contains(t, err.Error(), "needs at least 3.11") }) + // The image's PATH leads with the agent-writable /sandbox/.venv. + t.Run("refuses an agent-writable interpreter", func(t *testing.T) { + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "codex-cli 0.152.1") + t.Setenv("FULLSEND_TEST_PYPREFIX", "/sandbox/.venv") + + err := codexPreflightPythonVersion("sb", "/usr/bin/python3") + require.ErrorContains(t, err, `loads from "/sandbox/.venv", which the agent can write`) + }) + + // Login-shell noise precedes the probe's own last line. + t.Run("refuses a probe that omits the interpreter's location", func(t *testing.T) { + binDir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(binDir, "openshell"), []byte("#!/bin/sh\nprintf 'motd\\n3.12\\n'\n"), 0o755)) + t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH")) + + err := codexPreflightPythonVersion("sb", "/usr/bin/python3") + require.ErrorContains(t, err, "did not report its location") + }) + t.Run("refuses an unreadable version", func(t *testing.T) { fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "codex-cli 0.152.1") t.Setenv("FULLSEND_TEST_PYVER", "python 2 maybe") diff --git a/internal/runtime/codex_collection_test.go b/internal/runtime/codex_collection_test.go new file mode 100644 index 0000000000..be73675483 --- /dev/null +++ b/internal/runtime/codex_collection_test.go @@ -0,0 +1,543 @@ +package runtime + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "sort" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/ui" +) + +const recordedRoot0158 = "01a0e868-0083-7571-b0e2-de21c3a6c910" +const recordedAlpha0158 = "01a0e868-0ff5-7b90-8852-e23f529ca223" + +func testCodexRootUsage(rootID, model string, input, output, reasoning int) string { + return fmt.Sprintf(`{"type":"session_meta","payload":{"id":%q,"session_id":%q}} +{"type":"turn_context","payload":{"turn_id":"root-turn","model":%q}} +{"type":"token_usage_record","payload":{"thread_id":%q,"session_id":%q,"turn_id":"root-turn","root_turn_id":"root-turn","response_id":"root-response","usage":{"input_tokens":%d,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":%d,"reasoning_output_tokens":%d}}} +`, rootID, rootID, model, rootID, rootID, input, output, reasoning) +} + +// Give each native session its own file, as the real CLI does. The regular +// openshell stub still handles bootstrap, the exec stream and file discovery. +func fakeOpenshellCodexWithRollouts(t *testing.T, logPath, storeDir, stream string, bodies map[string]string) { + t.Helper() + var names, paths []string + for name := range bodies { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + paths = append(paths, CodexRuntime{}.codexSessionsDir()+"/"+name) + } + fakeOpenshellCodex(t, logPath, storeDir, "codex-cli 0.158.0", stream, strings.Join(paths, "\n")) + fake, err := exec.LookPath("openshell") + require.NoError(t, err) + require.NoError(t, os.Rename(fake, fake+"-base")) + script := "#!/bin/sh\nfor last; do :; done\ncase \"$last\" in\n" + for _, name := range names { + path := filepath.Join(t.TempDir(), name) + require.NoError(t, os.WriteFile(path, []byte(bodies[name]), 0o600)) + script += " *" + shellQuote("/"+name) + "*fullsend-codex-rollout*) cat " + shellQuote(path) + "; exit $?;;\n" + } + script += "esac\nexec " + shellQuote(fake+"-base") + " \"$@\"\n" + require.NoError(t, os.WriteFile(fake, []byte(script), 0o755)) +} + +func testBasicCodexRootUsage() string { + root := testCodexRootUsage("01a0da3c-7f1d-7342-84df-2e3c0c50aa08", "gpt-5.6-luna", 33237, 251, 20) + root = strings.Replace(root, `"cached_input_tokens":0`, `"cached_input_tokens":22013`, 1) + return strings.Replace(root, `"cache_write_input_tokens":0`, `"cache_write_input_tokens":11215`, 1) +} + +func TestCodexCollection_RunRequiresRootEvidence(t *testing.T) { + complete := testCodexRootUsage(recordedRoot0158, "gpt-5.6-luna", 20, 10, 2) + metadata := strings.SplitN(complete, "\n", 2)[0] + for _, tc := range []struct { + name, body, problem string + omitIdentity, failStart, zeroUsage, zeroStream bool + }{ + {name: "missing thread identity", omitIdentity: true, problem: "root thread identity"}, + {name: "missing root rollout", problem: "root has no collected response usage"}, + {name: "zero-token success still requires evidence", zeroStream: true, problem: "root has no collected response usage"}, + {name: "metadata without response", body: metadata, problem: "root has no collected response usage"}, + {name: "wrong root session", body: strings.ReplaceAll(complete, recordedRoot0158, "unrelated-root"), problem: "root has no collected response usage"}, + {name: "root with a parent", body: strings.Replace(complete, `"session_id":`, `"parent_thread_id":"other","session_id":`, 1), problem: "root has no collected response usage"}, + {name: "copied child response", body: strings.Replace(complete, `"thread_id":"`+recordedRoot0158+`"`, `"thread_id":"other"`, 1), problem: "root has no collected response usage"}, + {name: "truncated native root", body: complete + `{"type":`, problem: "not JSON"}, + {name: "complete native root", body: complete}, + {name: "reported zero usage", body: testCodexRootUsage(recordedRoot0158, "gpt-5.6-luna", 0, 0, 0), zeroUsage: true}, + {name: "failed startup keeps provider error", body: metadata, failStart: true}, + {name: "failed startup without identity", failStart: true, omitIdentity: true}, + } { + t.Run(tc.name, func(t *testing.T) { + stream := fmt.Sprintf("{\"type\":\"thread.started\",\"thread_id\":%q}\n", recordedRoot0158) + if tc.omitIdentity { + stream = "" + } + stream += "{\"type\":\"turn.started\"}\n" + if tc.failStart { + stream += "{\"type\":\"turn.failed\",\"error\":{\"message\":\"provider authentication failed\"}}\n" + } else { + stream += "{\"type\":\"turn.completed\",\"usage\":{\"input_tokens\":20,\"cached_input_tokens\":0,\"output_tokens\":10,\"reasoning_output_tokens\":2}}\n" + if tc.zeroStream { + stream = strings.NewReplacer(`"input_tokens":20`, `"input_tokens":0`, `"output_tokens":10`, `"output_tokens":0`, `"reasoning_output_tokens":2`, `"reasoning_output_tokens":0`).Replace(stream) + } + } + fixture := filepath.Join(t.TempDir(), "stream.jsonl") + require.NoError(t, os.WriteFile(fixture, []byte(stream), 0o600)) + store := t.TempDir() + seedCodexManifest(t, store, CodexRuntime{}, nil) + listing := "" + if tc.body != "" { + listing = CodexRuntime{}.codexSessionsDir() + "/root.jsonl" + } + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), store, "codex-cli 0.158.0", fixture, listing) + t.Setenv("FULLSEND_TEST_DOWNLOAD_BODY", tc.body) + var results []ResultEvent + metrics := &RunMetrics{} + exit, err := (CodexRuntime{}).Run(t.Context(), RunParams{ + SandboxName: "sb", RepoDir: "/sandbox/workspace/repo", Model: "gpt-5.6-luna", Timeout: time.Minute, + OnEvent: func(event AgentEvent) { + if result, ok := event.(ResultEvent); ok { + results = append(results, result) + } + }, + }, ui.New(&bytes.Buffer{}), time.Now(), metrics) + require.Len(t, results, 1) + if tc.problem != "" { + require.ErrorIs(t, err, ErrIncompleteEvidence) + assert.Contains(t, err.Error(), tc.problem) + assert.Equal(t, 1, exit) + assert.True(t, results[0].IsError) + } else { + require.NoError(t, err) + if tc.failStart { + assert.Equal(t, 1, exit) + assert.Equal(t, "provider authentication failed", results[0].ErrorMessage) + assert.Equal(t, codexSubtypeFailed, results[0].Subtype) + } else { + assert.Zero(t, exit) + } + } + if tc.failStart || tc.zeroUsage || tc.zeroStream { + assert.Zero(t, metrics.InputTokens) + assert.Zero(t, metrics.OutputTokens) + } else { + assert.Equal(t, 20, metrics.InputTokens, "known stream input must survive incomplete evidence") + assert.Equal(t, 8, metrics.OutputTokens, "known stream output must survive incomplete evidence") + assert.Equal(t, 2, metrics.ReasoningTokens) + } + }) + } +} + +func TestCodexCollection_InvalidRootTotalsPreserveStreamUsage(t *testing.T) { + first := testCodexRootUsage(recordedRoot0158, "model-a", int(^uint(0)>>1), 0, 0) + second := testCodexRootUsage(recordedRoot0158, "model-b", 1, 0, 0) + second = strings.NewReplacer("root-turn", "other-turn", "root-response", "other-response").Replace(second) + fakeOpenshellCodexWithRollouts(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "", map[string]string{"root-a.jsonl": first, "root-b.jsonl": second}) + metrics := &RunMetrics{Model: "stream-model", InputTokens: 20, OutputTokens: 8, ReasoningTokens: 2} + err := (CodexRuntime{}).collectCodexUsage(t.Context(), "overflow-root", recordedRoot0158, metrics, nil, true) + require.ErrorContains(t, err, "overflows") + assert.Equal(t, 20, metrics.InputTokens) + assert.Equal(t, 8, metrics.OutputTokens) + assert.Equal(t, 2, metrics.ReasoningTokens) + assert.Equal(t, map[string]ModelUsage{"stream-model": {Requests: 1, InputTokens: 20, OutputTokens: 8, ReasoningTokens: 2, CostUnavailable: true}}, metrics.PerModelUsage) +} + +func TestCodexCollection_ChildUsageStillRequiresMissingRoot(t *testing.T) { + body, err := os.ReadFile("testdata/codex/native-subagents/0158/probe-alpha.jsonl") + require.NoError(t, err) + fakeOpenshellCodexWithRollouts(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "", map[string]string{"child.jsonl": string(body)}) + metrics := &RunMetrics{Model: "gpt-5.6-luna"} + err = (CodexRuntime{}).collectCodexUsage(t.Context(), "child-only", recordedRoot0158, metrics, nil, false) + require.ErrorContains(t, err, "root has no collected response usage") + assert.Equal(t, 3, metrics.InputTokens) + assert.Equal(t, 8, metrics.OutputTokens) + assert.Equal(t, 9201, metrics.CacheCreationInputTokens, "retain child usage even when the stream had no counters") +} + +func TestCodexCollection_RequiresExpectedChildEvidence(t *testing.T) { + body, err := os.ReadFile("testdata/codex/native-subagents/0158/probe-alpha.jsonl") + require.NoError(t, err) + for _, tc := range []struct { + name, body, missing string + listed, completed bool + wantChildUsage bool + }{ + {"missing rollout", "", "no collected response usage", false, true, false}, + {"metadata without response", strings.SplitN(string(body), "\n", 2)[0], "no collected response usage", true, true, false}, + {"stale root", strings.ReplaceAll(string(body), recordedRoot0158, "another-root"), "no collected response usage", true, true, false}, + {"unfinished with incurred usage", string(body), "did not deliver a completed result", true, false, true}, + {"complete", string(body), "", true, true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + bodies := map[string]string{"root.jsonl": testCodexRootUsage(recordedRoot0158, "root-model", 20, 10, 2)} + if tc.listed { + bodies["child.jsonl"] = tc.body + } + fakeOpenshellCodexWithRollouts(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "", bodies) + metrics := &RunMetrics{Model: "root-model", InputTokens: 20, OutputTokens: 8, ReasoningTokens: 2} + err := (CodexRuntime{}).collectCodexUsage(t.Context(), "usage-evidence", recordedRoot0158, metrics, map[string]bool{recordedAlpha0158: tc.completed}, true) + if tc.missing == "" { + require.NoError(t, err) + } else { + require.ErrorContains(t, err, tc.missing) + assert.Contains(t, err.Error(), recordedAlpha0158) + } + assert.Equal(t, ModelUsage{Requests: 1, InputTokens: 20, OutputTokens: 8, ReasoningTokens: 2, CostUnavailable: true}, metrics.PerModelUsage["root-model"]) + if tc.wantChildUsage { + assert.Equal(t, 23, metrics.InputTokens, "incomplete results still retain incurred usage") + assert.Equal(t, 16, metrics.OutputTokens) + assert.Equal(t, 9201, metrics.CacheCreationInputTokens) + assert.Equal(t, ModelUsage{Requests: 1, InputTokens: 3, OutputTokens: 8, CacheCreationInputTokens: 9201, CostUnavailable: true}, metrics.PerModelUsage["gpt-5.6-luna"]) + } else { + assert.Equal(t, 20, metrics.InputTokens) + assert.NotContains(t, metrics.PerModelUsage, "gpt-5.6-luna") + } + }) + } +} + +func TestCodexCollection_InterruptedRootRecoversRecordedUsage(t *testing.T) { + body, err := os.ReadFile("testdata/codex/native-subagents/0158/root.jsonl") + require.NoError(t, err) + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "codex-cli 0.158.0", "", CodexRuntime{}.codexSessionsDir()+"/root.jsonl") + t.Setenv("FULLSEND_TEST_DOWNLOAD_BODY", string(body)) + metrics := &RunMetrics{Model: "gpt-5.6-luna"} + require.NoError(t, (CodexRuntime{}).collectCodexUsage(t.Context(), "interrupted-root", recordedRoot0158, metrics, nil, true)) + assert.Equal(t, 18, metrics.InputTokens) + assert.Equal(t, 624, metrics.OutputTokens) + assert.Equal(t, 170, metrics.ReasoningTokens) + assert.Equal(t, 78328, metrics.CacheReadInputTokens) + assert.Equal(t, 17845, metrics.CacheCreationInputTokens) + assert.Equal(t, 1, metrics.PerModelUsage["gpt-5.6-luna"].Requests) + assert.Zero(t, metrics.NumTurns, "accounting recovery must not invent successful completion") +} + +func TestCodexCollection_LaterInterruptedRootDoesNotLoseUsage(t *testing.T) { + body, err := os.ReadFile("testdata/codex/native-subagents/0158/root.jsonl") + require.NoError(t, err) + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "codex-cli 0.158.0", "", CodexRuntime{}.codexSessionsDir()+"/root.jsonl") + t.Setenv("FULLSEND_TEST_DOWNLOAD_BODY", string(body)) + metrics := &RunMetrics{Model: "gpt-5.6-luna", NumTurns: 1, InputTokens: 3, OutputTokens: 14} + require.NoError(t, (CodexRuntime{}).collectCodexUsage(t.Context(), "later-interrupted-root", recordedRoot0158, metrics, nil, true)) + assert.Equal(t, 18, metrics.InputTokens, "persisted later responses replace, rather than add to, an earlier stream snapshot") + assert.Equal(t, 624, metrics.OutputTokens) + assert.Equal(t, 170, metrics.ReasoningTokens) + assert.Equal(t, 78328, metrics.CacheReadInputTokens) + assert.Equal(t, 17845, metrics.CacheCreationInputTokens) + assert.Equal(t, 1, metrics.NumTurns, "accounting must not invent completed turns") +} + +func TestCodexCollection_RunRequiresChildFinalResult(t *testing.T) { + body, err := os.ReadFile("testdata/codex/native-subagents/0158/probe-alpha.jsonl") + require.NoError(t, err) + for _, tc := range []struct { + name, state, message, followup string + wantExit int + }{ + {"no final", "running", "", "", 1}, + {"empty completed result", "completed", "", "", 1}, + {"failed child", "errored", "provider error", "", 1}, + {"root failed with unfinished child", "running", "", "", 1}, + {"completed final", "completed", "Verified the requested result.", "", 0}, + {"unclosed final challenger", "completed", "Verified the requested result.", "", 1}, + {"reopened child must finish again", "completed", "First task is complete.", "send_input", 1}, + // Codex removes a closed thread; later calls report it not_found. + {"wait after close", "completed", "Verified the requested result.", "wait", 0}, + {"double close", "completed", "Verified the requested result.", "close_agent", 0}, + } { + t.Run(tc.name, func(t *testing.T) { + state, err := json.Marshal(map[string]any{recordedAlpha0158: map[string]string{"status": tc.state, "message": tc.message}}) + require.NoError(t, err) + followup := "" + closed := "" + if tc.name != "unclosed final challenger" { + closed = fmt.Sprintf(`{"type":"item.completed","item":{"id":"close","type":"collab_tool_call","tool":"close_agent","status":"completed","receiver_thread_ids":[%q],"agents_states":%s}}`+"\n", recordedAlpha0158, state) + } + switch tc.followup { + case "send_input": + followup = fmt.Sprintf(`{"type":"item.completed","item":{"id":"followup","type":"collab_tool_call","tool":"send_input","status":"completed","receiver_thread_ids":[%q],"agents_states":{%q:{"status":"running","message":null}}}}`+"\n", recordedAlpha0158, recordedAlpha0158) + case "wait", "close_agent": + followup = fmt.Sprintf(`{"type":"item.completed","item":{"id":"followup","type":"collab_tool_call","tool":%q,"status":"failed","receiver_thread_ids":[%q],"agents_states":{%q:{"status":"not_found","message":null}}}}`+"\n", tc.followup, recordedAlpha0158, recordedAlpha0158) + } + stream := fmt.Sprintf(`{"type":"thread.started","thread_id":%q} +{"type":"turn.started"} +{"type":"item.completed","item":{"id":"spawn","type":"collab_tool_call","tool":"spawn_agent","status":"completed","receiver_thread_ids":[%q],"agents_states":{}}} +{"type":"item.completed","item":{"id":"wait","type":"collab_tool_call","tool":"wait","status":"completed","receiver_thread_ids":[%q],"agents_states":%s}} +%s%s{"type":"turn.completed","usage":{"input_tokens":20,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":10,"reasoning_output_tokens":2}} +`, recordedRoot0158, recordedAlpha0158, recordedAlpha0158, state, closed, followup) + if tc.name == "root failed with unfinished child" { + stream += "{\"type\":\"turn.failed\",\"error\":{\"message\":\"root provider failed after dispatch\"}}\n" + } + fixture := filepath.Join(t.TempDir(), "stream.ndjson") + require.NoError(t, os.WriteFile(fixture, []byte(stream), 0o600)) + store := t.TempDir() + seedCodexManifest(t, store, CodexRuntime{}, nil) + fakeOpenshellCodexWithRollouts(t, filepath.Join(t.TempDir(), "log"), store, fixture, map[string]string{ + "root.jsonl": testCodexRootUsage(recordedRoot0158, "gpt-5.6-luna", 20, 10, 2), + "child.jsonl": string(body), + }) + metrics := &RunMetrics{} + var results []ResultEvent + exit, err := (CodexRuntime{}).Run(t.Context(), RunParams{ + SandboxName: "sb", RepoDir: "/sandbox/workspace/repo", Model: "gpt-5.6-luna", Timeout: time.Minute, + OnEvent: func(event AgentEvent) { + if result, ok := event.(ResultEvent); ok { + results = append(results, result) + } + }, + }, ui.New(&bytes.Buffer{}), time.Now(), metrics) + if tc.wantExit == 0 { + require.NoError(t, err) + } else { + require.ErrorIs(t, err, ErrIncompleteEvidence) + if tc.name == "root failed with unfinished child" { + assert.ErrorContains(t, err, "did not deliver a completed result") + } + } + assert.Equal(t, tc.wantExit, exit, "a successful parent cannot hide an unfinished or unclosed child") + assert.Equal(t, 23, metrics.InputTokens) + assert.Equal(t, 16, metrics.OutputTokens) + assert.Equal(t, 2, metrics.PerModelUsage["gpt-5.6-luna"].Requests) + require.Len(t, results, 1, "emit one terminal result after child accounting") + assert.Equal(t, 23, results[0].InputTokens) + assert.Equal(t, 16, results[0].OutputTokens) + assert.Equal(t, 2, results[0].ReasoningTokens) + assert.Equal(t, 9201, results[0].CacheCreationInputTokens) + assert.True(t, results[0].CostUnavailable, "unreported dollar cost is not a free run") + assert.Equal(t, tc.wantExit != 0, results[0].IsError, "terminal summary and exit verdict agree") + }) + } +} + +func TestCodexCollection_FailedDispatchCannotAuthenticateChild(t *testing.T) { + child, err := os.ReadFile("testdata/codex/native-subagents/0158/probe-alpha.jsonl") + require.NoError(t, err) + for _, includeChild := range []bool{false, true} { + t.Run(fmt.Sprintf("child-rollout-%t", includeChild), func(t *testing.T) { + // A rejected V2-shaped spawn is not a successful child dispatch, + // even if the failed event includes an ID and a completed status. + stream := fmt.Sprintf(`{"type":"thread.started","thread_id":%q} +{"type":"turn.started"} +{"type":"item.completed","item":{"id":"denied","type":"collab_tool_call","tool":"spawn_agent","status":"failed","receiver_thread_ids":[%q],"agents_states":{%q:{"status":"completed","message":"not authenticated"}}}} +{"type":"turn.completed","usage":{"input_tokens":20,"output_tokens":10,"reasoning_output_tokens":2}} +`, recordedRoot0158, recordedAlpha0158, recordedAlpha0158) + fixture := filepath.Join(t.TempDir(), "stream.ndjson") + require.NoError(t, os.WriteFile(fixture, []byte(stream), 0o600)) + store := t.TempDir() + seedCodexManifest(t, store, CodexRuntime{}, nil) + bodies := map[string]string{"root.jsonl": testCodexRootUsage(recordedRoot0158, "gpt-5.6-luna", 20, 10, 2)} + if includeChild { + bodies["child.jsonl"] = string(child) + } + fakeOpenshellCodexWithRollouts(t, filepath.Join(t.TempDir(), "log"), store, fixture, bodies) + metrics := &RunMetrics{} + exit, err := (CodexRuntime{}).Run(t.Context(), RunParams{ + SandboxName: "sb", RepoDir: "/sandbox/workspace/repo", Model: "gpt-5.6-luna", Timeout: time.Minute, + }, ui.New(&bytes.Buffer{}), time.Now(), metrics) + if includeChild { + require.ErrorIs(t, err, ErrIncompleteEvidence) + assert.ErrorContains(t, err, "no observed dispatch") + assert.NotZero(t, exit) + assert.Equal(t, 23, metrics.InputTokens, "keep incurred child usage even when dispatch evidence is incomplete") + } else { + require.NoError(t, err) + assert.Zero(t, exit, "a root-only run need not delegate") + assert.Equal(t, 20, metrics.InputTokens) + } + }) + } +} + +func TestCodexCollection_StreamLossReturnsIncompleteEvidence(t *testing.T) { + stream := fmt.Sprintf(`{"type":"thread.started","thread_id":%q} +{"type":"turn.completed","usage":{"input_tokens":20,"output_tokens":10,"reasoning_output_tokens":2}} +`, recordedRoot0158) + strings.Repeat("x", codexRedactMaxLine+1024) + "\n" + fixture := filepath.Join(t.TempDir(), "stream.ndjson") + require.NoError(t, os.WriteFile(fixture, []byte(stream), 0o600)) + store := t.TempDir() + seedCodexManifest(t, store, CodexRuntime{}, nil) + fakeOpenshellCodexWithRollouts(t, filepath.Join(t.TempDir(), "log"), store, fixture, map[string]string{ + "root.jsonl": testCodexRootUsage(recordedRoot0158, "gpt-5.6-luna", 20, 10, 2), + }) + metrics := &RunMetrics{} + var result ResultEvent + exit, err := (CodexRuntime{}).Run(t.Context(), RunParams{ + SandboxName: "sb", RepoDir: "/sandbox/workspace/repo", Model: "gpt-5.6-luna", Timeout: time.Minute, + OnEvent: func(event AgentEvent) { + if final, ok := event.(ResultEvent); ok { + result = final + } + }, + }, ui.New(&bytes.Buffer{}), time.Now(), metrics) + require.ErrorIs(t, err, ErrIncompleteEvidence) + assert.NotZero(t, exit) + assert.True(t, result.IsError, "an earlier completed turn cannot certify dropped later records") + assert.Equal(t, 20, metrics.InputTokens) + assert.Equal(t, 8, metrics.OutputTokens) +} + +func TestCodexCollection_ListingRejectsUnboundedAndFailedDiscovery(t *testing.T) { + for _, tc := range []struct { + name string + count, length int + fail, cancel bool + wantError bool + }{ + {"at file limit", 128, 0, false, false, false}, + {"over file limit", 129, 0, false, false, true}, + {"over byte limit", 1, 65536, false, false, true}, + {"remote enumeration failed", 1, 0, true, false, true}, + {"cancelled collection", 1, 0, false, true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + paths := make([]string, tc.count) + for i := range paths { + paths[i] = fmt.Sprintf("%s/%s%d.jsonl", CodexRuntime{}.codexSessionsDir(), strings.Repeat("x", tc.length), i) + } + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "codex-cli 0.158.0", "", strings.Join(paths, "\n")) + if tc.fail { + t.Setenv("FULLSEND_TEST_FAIL_MATCH", "fullsend-codex-list") + } + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + if tc.cancel { + cancel() + } + got, err := (CodexRuntime{}).listCodexRollouts(ctx, "bounded-discovery") + if tc.wantError { + require.Error(t, err) + assert.Empty(t, got, "an incomplete listing must never look complete") + } else { + require.NoError(t, err) + assert.Equal(t, paths, got) + } + }) + } +} + +func TestCodexCollection_EmbeddedListingBoundsAndSymlinks(t *testing.T) { + python := pythonWithTomllib(t) + root := t.TempDir() + outside := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(outside, "outside.jsonl"), []byte("private"), 0o600)) + require.NoError(t, os.Symlink(outside, filepath.Join(root, "linked-directory"))) + require.NoError(t, os.Symlink(filepath.Join(outside, "outside.jsonl"), filepath.Join(root, "linked-file.jsonl"))) + require.NoError(t, os.WriteFile(filepath.Join(root, "normal.jsonl"), nil, 0o600)) + out, err := exec.Command(python, "-I", "-c", codexListRolloutsPy, root).CombinedOutput() + require.NoError(t, err, "%s", out) + var listed []string + require.NoError(t, json.Unmarshal(out, &listed)) + assert.Equal(t, []string{filepath.Join(root, "normal.jsonl")}, listed) + for i := 0; i < 128; i++ { + require.NoError(t, os.WriteFile(filepath.Join(root, fmt.Sprintf("extra-%03d.jsonl", i)), nil, 0o600)) + } + cmd := exec.Command(python, "-I", "-c", codexListRolloutsPy, root) + var stdout bytes.Buffer + cmd.Stdout = &stdout + err = cmd.Run() + require.Error(t, err) + assert.Empty(t, stdout.String(), "overflow must not publish a partial JSON listing") + link := filepath.Join(t.TempDir(), "sessions") + require.NoError(t, os.Symlink(outside, link)) + require.Error(t, exec.Command(python, "-I", "-c", codexListRolloutsPy, link).Run()) +} + +func TestCodexCollection_EmbeddedListingRejectsUnreadableSubdirectory(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root can enumerate mode-000 directories") + } + root := t.TempDir() + child := filepath.Join(root, "unreadable") + require.NoError(t, os.Mkdir(child, 0o700)) + require.NoError(t, os.WriteFile(filepath.Join(child, "child.jsonl"), nil, 0o600)) + require.NoError(t, os.Chmod(child, 0)) + t.Cleanup(func() { _ = os.Chmod(child, 0o700) }) + cmd := exec.Command(pythonWithTomllib(t), "-I", "-c", codexListRolloutsPy, root) + var stdout bytes.Buffer + cmd.Stdout = &stdout + err := cmd.Run() + require.Error(t, err, "inaccessible child evidence must not become a successful empty listing") + assert.Empty(t, stdout.String()) +} + +func TestCodexCollection_PartialExtractionReturnsErrorAndKeepsSafeArtifacts(t *testing.T) { + for _, tc := range []struct{ name, badName, fail string }{ + {"failed transfer", "unavailable.jsonl", "unavailable.jsonl"}, + {"invalid rollout", "planted.jsonl", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + root := CodexRuntime{}.codexSessionsDir() + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "codex-cli 0.158.0", "", root+"/good.jsonl\n"+root+"/"+tc.badName) + t.Setenv("FULLSEND_TEST_DOWNLOAD_BODY", `{"type":"session_meta","payload":{"id":"root"}}`) + t.Setenv("FULLSEND_TEST_FAIL_MATCH", tc.fail) + out := t.TempDir() + err := (CodexRuntime{}).ExtractTranscripts("partial-extraction", "review", out) + require.Error(t, err, "missing one transcript must surface to the artifact caller") + entries, err := os.ReadDir(out) + require.NoError(t, err) + require.Len(t, entries, 1) + assert.Equal(t, "review-good.jsonl", entries[0].Name()) + assert.JSONEq(t, `{"type":"session_meta","payload":{"id":"root"}}`, strings.TrimSpace(readFileString(t, filepath.Join(out, entries[0].Name())))) + }) + } +} + +func TestCodexCollection_PublishFailureKeepsPreviousArtifact(t *testing.T) { + out := t.TempDir() + root, err := os.OpenRoot(out) + require.NoError(t, err) + defer root.Close() + previous := filepath.Join(out, "child.jsonl") + require.NoError(t, os.WriteFile(previous, []byte("previous redacted artifact"), 0o600)) + err = codexPublishTranscript(root, filepath.Join(t.TempDir(), "missing.jsonl"), "child.jsonl") + require.Error(t, err) + assert.Equal(t, "previous redacted artifact", readFileString(t, previous)) + entries, err := os.ReadDir(out) + require.NoError(t, err) + require.Len(t, entries, 1, "failed publication leaves no staging artifact") +} + +func TestCodexCollection_CancellationStopsRemainingTransfers(t *testing.T) { + listed := CodexRuntime{}.codexSessionsDir() + "/first.jsonl\n" + CodexRuntime{}.codexSessionsDir() + "/second.jsonl" + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "codex-cli 0.158.0", "", listed) + fake, err := exec.LookPath("openshell") + require.NoError(t, err) + require.NoError(t, os.Rename(fake, fake+"-base")) + started := filepath.Join(t.TempDir(), "transfer-started") + wrapper := "#!/bin/sh\ncase \"$*\" in *fullsend-codex-rollout*) touch " + shellQuote(started) + "; exec sleep 30;; esac\nexec " + shellQuote(fake+"-base") + " \"$@\"\n" + require.NoError(t, os.WriteFile(fake, []byte(wrapper), 0o755)) + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + private := t.TempDir() + finished := make(chan error, 1) + go func() { + _, err := (CodexRuntime{}).downloadCodexRollouts(ctx, "cancel-transfer", private) + finished <- err + }() + require.Eventually(t, func() bool { _, err := os.Stat(started); return err == nil }, 10*time.Second, 10*time.Millisecond) + cancel() + select { + case err := <-finished: + require.ErrorIs(t, err, context.Canceled, "stop before scheduling another transfer") + case <-time.After(10 * time.Second): + t.Fatal("collection did not stop after cancellation") + } + entries, err := os.ReadDir(private) + require.NoError(t, err) + assert.Empty(t, entries, "interrupted transfers leave no raw partial file") +} diff --git a/internal/runtime/codex_config.go b/internal/runtime/codex_config.go index 12903dc5ce..f9e42beb17 100644 --- a/internal/runtime/codex_config.go +++ b/internal/runtime/codex_config.go @@ -22,8 +22,8 @@ const ( // cannot move the provider, the approval policy or the sandbox mode. codexConfigFile = "config.toml" // codexHooksFile is codex's hook wiring, read from $CODEX_HOME/hooks.json - // (codex-rs/hooks/src/engine/discovery.rs). Written only when the harness - // enables security; its absence is how hooks stay off. + // (codex-rs/hooks/src/engine/discovery.rs). The mandatory native dispatch + // policy is always installed, plus the harness's optional security hooks. codexHooksFile = "hooks.json" // codexAdapterFile is the embedded adapter every hook handler invokes. codexAdapterFile = "fullsend-codex-hook.py" @@ -117,10 +117,12 @@ var codexConfigTemplate = template.Must(template.New("codex-config").Parse( # Integrity-checked before every iteration — see buildCodexRunCommand. model_provider = "{{ .ProviderID }}" approval_policy = "never" +allow_login_shell = false sandbox_mode = "danger-full-access" web_search = "disabled" check_for_update_on_startup = false hide_agent_reasoning = false +sqlite_home = {{ .StateDir }} developer_instructions = {{ .DeveloperInstructions }} [analytics] @@ -167,6 +169,7 @@ type codexConfigData struct { ProjectKey string RefreshIntervalMS int TimeoutMS int + StateDir string } // renderCodexConfig produces $CODEX_HOME/config.toml for one agent run. @@ -186,6 +189,7 @@ func renderCodexConfig(configDir, repoDir, developerInstructions string) ([]byte ProjectKey: codexTOMLString(repoDir), RefreshIntervalMS: codexAuthRefreshIntervalMS, TimeoutMS: codexAuthTimeoutMS, + StateDir: codexTOMLString(configDir + "/db"), }) if err != nil { return nil, fmt.Errorf("rendering codex %s: %w", codexConfigFile, err) diff --git a/internal/runtime/codex_dispatch_test.go b/internal/runtime/codex_dispatch_test.go new file mode 100644 index 0000000000..c669595fd3 --- /dev/null +++ b/internal/runtime/codex_dispatch_test.go @@ -0,0 +1,40 @@ +package runtime + +import ( + "bytes" + "encoding/json" + "os/exec" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCodexDispatchFailureBlocksOnRealStderr(t *testing.T) { + for _, tc := range []struct{ name, setup string }{ + {"input read failure", "def fail(*args): raise OSError('read failed')\njson.load = fail"}, + {"memory failure", "def fail(*args): raise MemoryError()\njson.load = fail"}, + {"interrupted policy", "def fail(*args): raise KeyboardInterrupt()\njson.load = fail"}, + {"unexpected exit", "def fail(*args): raise SystemExit(1)\njson.load = fail"}, + {"missing stderr wrapper", "sys.stderr = None"}, + {"closed stderr wrapper", "sys.stderr = open(os.devnull, 'w')\nsys.stderr.close()"}, + {"misdirected stderr wrapper", "sys.stderr = open(os.devnull, 'w')"}, + } { + t.Run(tc.name, func(t *testing.T) { + source, err := json.Marshal(codexDispatchPy) + require.NoError(t, err) + program := "import json,os,sys\n" + tc.setup + "\nexec(" + string(source) + ")" + cmd := exec.Command(pythonWithTomllib(t), "-I", "-c", program, `["default"]`) + cmd.Stdin = strings.NewReader(`{"tool_name":"spawn_agent","tool_input":{"fork_context":true}}`) + var stdout, stderr bytes.Buffer + cmd.Stdout, cmd.Stderr = &stdout, &stderr + err = cmd.Run() + var exit *exec.ExitError + require.ErrorAs(t, err, &exit) + assert.Equal(t, 2, exit.ExitCode(), "other exit codes do not block native Codex") + assert.NotEmpty(t, strings.TrimSpace(stderr.String()), "Codex requires the reason on the real stderr pipe") + assert.Empty(t, stdout.String(), "a block is not a JSON allow response or a redirected stderr print") + }) + } +} diff --git a/internal/runtime/codex_hook/fullsend-codex-dispatch.py b/internal/runtime/codex_hook/fullsend-codex-dispatch.py new file mode 100644 index 0000000000..99a882eee1 --- /dev/null +++ b/internal/runtime/codex_hook/fullsend-codex-dispatch.py @@ -0,0 +1,53 @@ +"""Native child policy. Invoked inline by a protected PreToolUse hook.""" + +import json +import os +import sys + + +def block(reason): + # Codex treats exit 2 with stderr as blocking. Bypass Python's replaceable + # stderr wrapper, and avoid shutdown flushing changing the exit status. + try: + message = ("fullsend: " + reason + "\n").encode() + while message: + written = os.write(2, message) + if written <= 0: + break + message = message[written:] + except BaseException: + pass + os._exit(2) + + +def check(payload, roles): + # Codex prefixes namespaced tools: multi_agent_v1resume_agent, collaborationspawn_agent. + name = str(payload.get("tool_name")) if isinstance(payload, dict) else "" + if name.endswith("resume_agent"): + return "resuming children does not preserve role policy; spawn a fresh child" + if name.endswith("spawn_agent") and name != "spawn_agent": + return "V2 collaboration is unsupported; native delegation requires the V1 spawn_agent" + if name != "spawn_agent": + return "invalid spawn hook payload" + if payload.get("agent_id") or payload.get("agent_type"): + return "children may not dispatch grandchildren" + args = payload.get("tool_input") + if not isinstance(args, dict): + return "missing spawn arguments" + if args.get("agent_type", "default") not in roles: + return "unknown native role; select a registered role or default" + if any(key in args and args[key] is not None for key in ("model", "reasoning_effort")): + return "child model and effort are selected by the runtime; omit overrides" + if "fork_turns" in args or "task_name" in args: + return "native delegation requires the V1 tool schema; V2 arguments are unsupported" + if args.get("fork_context") is not False: + return "native children require fork_context=false" + return None + + +try: + reason = check(json.load(sys.stdin), json.loads(sys.argv[1])) +except BaseException: + block("native child policy failed; refusing tool call") +if reason: + block(reason) diff --git a/internal/runtime/codex_hook/fullsend-codex-landlock.py b/internal/runtime/codex_hook/fullsend-codex-landlock.py new file mode 100644 index 0000000000..1068db8aac --- /dev/null +++ b/internal/runtime/codex_hook/fullsend-codex-landlock.py @@ -0,0 +1,141 @@ +"""Add a write restriction before sourcing .env or starting any agent process. + +The runner supplies this program inline and supplies its policy in argv. Neither +is loaded from the agent's filesystem, and Bootstrap refuses an interpreter +under an agent-writable root. OpenShell remains the outer sandbox; +this additional, inherited Landlock ruleset only removes write permissions. +Linux Landlock ABI 3+ is required so truncate is mediated too. +""" + +import contextlib +import ctypes +import hashlib +import json +import os +import stat +import sys + +WRITE = 1 << 1 +TRUNCATE = 1 << 14 +WRITE_RIGHTS = WRITE | sum(1 << bit for bit in range(4, 15)) + + +class Ruleset(ctypes.Structure): + _fields_ = [("handled_access_fs", ctypes.c_uint64)] + + +class PathRule(ctypes.Structure): + _pack_ = 1 + _layout_ = "ms" # Python 3.14 deprecates _pack_ without it + _fields_ = [("allowed_access", ctypes.c_uint64), ("parent_fd", ctypes.c_int32)] + + +def launch(policy, command): + # Landlock cannot revoke writes through a descriptor opened beforehand. + # Preserve only the runner's stdin/stdout/stderr across the boundary. + for name in os.listdir("/proc/self/fd"): + if int(name) >= 3: + # The descriptor used by listdir may already have closed. + with contextlib.suppress(OSError): + os.close(int(name)) + libc = ctypes.CDLL(None, use_errno=True) + libc.syscall.restype = ctypes.c_long + + def syscall(number, *args): + result = libc.syscall(ctypes.c_long(number), *args) + if result == -1: + code = ctypes.get_errno() + raise OSError(code, os.strerror(code)) + return result + + if syscall(444, ctypes.c_void_p(), ctypes.c_size_t(0), ctypes.c_uint(1)) < 3: + raise RuntimeError("Codex runs require Linux Landlock ABI 3+") + + # Freeze the roots, including their directory entries. Granting an ancestor + # such as /sandbox would also grant policy replacement, so descend through + # ancestors and grant only siblings. Symlinks are never grant authorities. + protected = set(policy["protected"]) + ruleset = syscall( + 444, ctypes.byref(Ruleset(WRITE_RIGHTS)), ctypes.c_size_t(8), ctypes.c_uint(0) + ) + + def grant(path): + if any(path == p or path.startswith(p + "/") for p in protected): + return + info = os.lstat(path) + if stat.S_ISLNK(info.st_mode): + return + if any(p.startswith(path + "/") for p in protected): + if not stat.S_ISDIR(info.st_mode): + raise RuntimeError("non-directory policy ancestor") + for name in sorted(os.listdir(path)): + grant(path + "/" + name) + return + fd = os.open(path, os.O_PATH | os.O_CLOEXEC | os.O_NOFOLLOW) + try: + mode = os.fstat(fd).st_mode + if stat.S_ISDIR(mode): + rights = WRITE_RIGHTS + elif stat.S_ISREG(mode): + rights = WRITE | TRUNCATE + elif path == "/dev/null" and stat.S_ISCHR(mode): + rights = WRITE + else: + return + syscall( + 445, + ctypes.c_int(ruleset), + ctypes.c_int(1), + ctypes.byref(PathRule(rights, fd)), + ctypes.c_uint(0), + ) + finally: + os.close(fd) + + try: + for path in policy["write_roots"]: + grant(path) + # Mutable native state is beneath a frozen CODEX_HOME. These are exact + # runner-selected paths, never values from config.toml or .env. + protected.clear() + for path in policy["state_paths"]: + grant(path) + if libc.prctl(38, 1, 0, 0, 0) != 0: + raise OSError(ctypes.get_errno(), "PR_SET_NO_NEW_PRIVS failed") + syscall(446, ctypes.c_int(ruleset), ctypes.c_uint(0)) + finally: + os.close(ruleset) + + # Validate AFTER restricting writes, closing the check-to-load race. Parent + # directories are frozen too; reject preexisting symlinks and hardlinks. + def regular(path, directory=False): + current = "/" + for part in path.strip("/").split("/"): + current = os.path.join(current, part) + info = os.lstat(current) + if stat.S_ISLNK(info.st_mode): + raise RuntimeError("symlink in Codex policy path") + if directory: + if not stat.S_ISDIR(info.st_mode): + raise RuntimeError("Codex policy directory missing") + elif not stat.S_ISREG(info.st_mode) or info.st_nlink != 1: + raise RuntimeError("Codex policy must contain singly linked regular files") + + for path, expected in policy["files"].items(): + regular(path) + with open(path, "rb") as source: + content = source.read((1 << 20) + 1) + if len(content) > 1 << 20 or hashlib.sha256(content).hexdigest() != expected: + raise RuntimeError("Codex policy file missing or modified: " + path) + for path, names in policy["directories"].items(): + regular(path, directory=True) + if sorted(os.listdir(path)) != sorted(names): + raise RuntimeError("Codex policy file set modified: " + path) + os.execv(command[0], command) + + +try: + launch(json.loads(sys.argv[1]), sys.argv[2:]) +except (OSError, ValueError, KeyError, RuntimeError) as error: + print("fullsend: Codex write protection failed: " + str(error), file=sys.stderr) + sys.exit(78) diff --git a/internal/runtime/codex_integrity.go b/internal/runtime/codex_integrity.go index eb26b4e21c..0dcd22e203 100644 --- a/internal/runtime/codex_integrity.go +++ b/internal/runtime/codex_integrity.go @@ -41,6 +41,8 @@ import ( type codexRunnerHeldDigestSet struct { ConfigTOML string HooksJSON string + Python string + Roles map[string]string // SecurityEnv is the hook configuration the runner knows at Bootstrap: // what it derived from SandboxHookConfig, plus the harness-supplied // variables read back from the workspace .env before any agent iteration diff --git a/internal/runtime/codex_landlock.go b/internal/runtime/codex_landlock.go new file mode 100644 index 0000000000..07562853a6 --- /dev/null +++ b/internal/runtime/codex_landlock.go @@ -0,0 +1,72 @@ +package runtime + +import ( + _ "embed" + "encoding/json" + "sort" + "strings" +) + +//go:embed codex_hook/fullsend-codex-landlock.py +var codexLandlockPy string + +type codexWritePolicy struct { + Protected []string `json:"protected"` + WriteRoots []string `json:"write_roots"` + StatePaths []string `json:"state_paths"` + Files map[string]string `json:"files"` + Directories map[string][]string `json:"directories"` +} + +// These are native runtime state, never configuration or executable hooks. +var codexStateDirs = []string{"sessions", "archived_sessions", "thread-writer-locks", "tmp", ".tmp", "shell_snapshots", "log", "cache", "db"} +var codexStateFiles = []string{"installation_id", "session_index.jsonl", codexLastMessageFile} + +// codexWriteRoots are the OpenShell read-write paths: everything the agent can write. +var codexWriteRoots = []string{"/sandbox", "/tmp", "/dev/null"} + +func codexUnderWriteRoot(path string) bool { + for _, root := range codexWriteRoots { + if path == root || strings.HasPrefix(path, root+"/") { + return true + } + } + return false +} + +func codexWritePolicyFor(r CodexRuntime, digests codexRunnerHeldDigestSet) codexWritePolicy { + policy := codexWritePolicy{ + Protected: []string{r.ConfigDir(), "/sandbox/codex-policy"}, + WriteRoots: codexWriteRoots, + Files: map[string]string{r.codexConfigPath(): digests.ConfigTOML, r.codexAuthScriptPath(): codexAssetSHA256(codexAuthScriptSH)}, + Directories: map[string][]string{codexRolesDir: {}}, + } + for _, name := range append(append([]string{}, codexStateDirs...), codexStateFiles...) { + policy.StatePaths = append(policy.StatePaths, r.ConfigDir()+"/"+name) + } + for name, digest := range digests.Roles { + policy.Files[codexRolesDir+"/"+name] = digest + policy.Directories[codexRolesDir] = append(policy.Directories[codexRolesDir], name) + } + sort.Strings(policy.Directories[codexRolesDir]) + if digests.HooksJSON != "" { + policy.Files[r.codexHooksPath()] = digests.HooksJSON + } + if digests.HookScripts != nil { + policy.Files[r.codexAdapterPath()] = codexAssetSHA256(codexHookAdapterPy) + for name, digest := range digests.HookScripts { + policy.Files[r.codexHooksDir()+"/"+name] = digest + policy.Directories[r.codexHooksDir()] = append(policy.Directories[r.codexHooksDir()], name) + } + sort.Strings(policy.Directories[r.codexHooksDir()]) + } + return policy +} + +// The restriction precedes the shell, including .env. Otherwise a previous +// iteration could leave executable .env content that writes policy before the +// restriction is installed. All its descendants inherit the restriction. +func codexProtectedCommand(command string, digests codexRunnerHeldDigestSet) string { + policy, _ := json.Marshal(codexWritePolicyFor(CodexRuntime{}, digests)) // string-only fields + return shellQuote(digests.Python) + " -I -c " + shellQuote(codexLandlockPy) + " " + shellQuote(string(policy)) + " /bin/sh -c " + shellQuote(command) +} diff --git a/internal/runtime/codex_landlock_test.go b/internal/runtime/codex_landlock_test.go new file mode 100644 index 0000000000..acc742c82f --- /dev/null +++ b/internal/runtime/codex_landlock_test.go @@ -0,0 +1,190 @@ +package runtime + +import ( + "encoding/json" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCodexDispatchPolicy(t *testing.T) { + for _, input := range []string{`{"hooks":{}}`, `{}`, `{"hooks":null}`} { + hooks, err := codexAddDispatchGuard([]byte(input), "/usr/bin/python3", nil) + require.NoError(t, err, input) + var config codexHooksConfig + require.NoError(t, json.Unmarshal(hooks, &config)) + matcher := config.Hooks["PreToolUse"][0].Matcher + // Codex matches a [A-Za-z0-9_|] matcher by exact alternation + // (codex-rs/hooks/src/events/common.rs), against the names its + // 0.157.0 and 0.158.0 binaries were observed to send. + require.Regexp(t, `^[A-Za-z0-9_|]+$`, matcher) + for _, emitted := range []string{"spawn_agent", "multi_agent_v1resume_agent", "collaborationspawn_agent"} { + assert.Contains(t, strings.Split(matcher, "|"), emitted, "resume and V2 spawns must reach the guard") + } + } + _, err := codexAddDispatchGuard([]byte("{"), "/usr/bin/python3", nil) + require.ErrorContains(t, err, "parsing codex hooks") + for _, tt := range []struct { + name string + payload string + allowed bool + }{ + {"fresh named", `{"tool_name":"spawn_agent","tool_input":{"agent_type":"correctness","fork_context":false}}`, true}, + {"fresh generic", `{"tool_name":"spawn_agent","tool_input":{"fork_context":false}}`, true}, + {"unsupported V2", `{"tool_name":"collaborationspawn_agent","tool_input":{"agent_type":"explore","fork_turns":"none","task_name":"inspect","message":"x"}}`, false}, + {"V2 arguments without a namespace", `{"tool_name":"spawn_agent","tool_input":{"agent_type":"explore","fork_turns":"none","task_name":"inspect"}}`, false}, + {"mixed V1 and V2", `{"tool_name":"spawn_agent","tool_input":{"fork_context":false,"fork_turns":"none"}}`, false}, + {"V2 task with V1 freshness", `{"tool_name":"spawn_agent","tool_input":{"fork_context":false,"task_name":"inspect"}}`, false}, + {"parent context", `{"tool_name":"spawn_agent","tool_input":{"fork_context":true}}`, false}, + {"default context", `{"tool_name":"spawn_agent","tool_input":{}}`, false}, + {"V2 full context", `{"tool_name":"spawn_agent","tool_input":{"fork_turns":"all"}}`, false}, + {"model override", `{"tool_name":"spawn_agent","tool_input":{"fork_context":false,"model":"gpt-6-sol"}}`, false}, + {"unknown role", `{"tool_name":"spawn_agent","tool_input":{"fork_context":false,"agent_type":"made-up"}}`, false}, + {"grandchild", `{"tool_name":"spawn_agent","agent_id":"child","tool_input":{"fork_context":false}}`, false}, + {"resume changes policy", `{"tool_name":"multi_agent_v1resume_agent","tool_input":{"id":"closed-child"}}`, false}, + {"resume without a namespace", `{"tool_name":"resume_agent","tool_input":{"id":"closed-child"}}`, false}, + {"invalid payload", `[]`, false}, + {"unrelated tool", `{"tool_name":"Bash","tool_input":{"command":"true"}}`, false}, + } { + t.Run(tt.name, func(t *testing.T) { + cmd := exec.Command(pythonWithTomllib(t), "-I", "-c", codexDispatchPy, `["default","explore","correctness"]`) + cmd.Stdin = strings.NewReader(tt.payload) + out, err := cmd.CombinedOutput() + if tt.allowed { + require.NoError(t, err, "%s", out) + assert.Empty(t, out) + } else { + var exit *exec.ExitError + require.ErrorAs(t, err, &exit) + assert.Equal(t, 2, exit.ExitCode(), "Codex treats other nonzero exits as fail-open") + assert.Contains(t, string(out), "fullsend:") + } + switch tt.name { + case "unsupported V2": + assert.Contains(t, string(out), "V2 collaboration is unsupported") + case "resume changes policy": + assert.Contains(t, string(out), "resuming children") + } + }) + } +} + +func TestCodexWritePolicyProtectsAllAuthorities(t *testing.T) { + d := testRunnerHeldDigests + d.Roles = map[string]string{"default.toml": "digest"} + p := codexWritePolicyFor(CodexRuntime{}, d) + assert.Contains(t, p.Protected, CodexRuntime{}.ConfigDir()) + assert.Contains(t, p.Files, CodexRuntime{}.codexConfigPath()) + assert.Contains(t, p.Files, CodexRuntime{}.codexHooksPath()) + assert.Contains(t, p.Files, CodexRuntime{}.codexAdapterPath()) + assert.Equal(t, []string{"default.toml"}, p.Directories[codexRolesDir]) + assert.NotContains(t, p.StatePaths, CodexRuntime{}.OpenAIAuthFile(), "only the runner may refresh the credential file") + assert.NotContains(t, p.StatePaths, CodexRuntime{}.ConfigDir()+"/models_cache.json") +} + +// Run this test on Linux (also cross-compiled and executed in the real +// OpenShell sandbox). It exercises the actual embedded launcher, not a mock. +func TestCodexLandlockEnforcesInheritedProtection(t *testing.T) { + if runtime.GOOS != "linux" { + t.Skip("Landlock is a Linux kernel interface; covered by sandbox validation") + } + dir := t.TempDir() + policyDir := filepath.Join(dir, "policy") + work := filepath.Join(dir, "workspace") + require.NoError(t, os.Mkdir(policyDir, 0o755)) + require.NoError(t, os.Mkdir(work, 0o755)) + // dir stands in for $HOME=/sandbox: Bootstrap's pre-created entries. + require.NoError(t, os.MkdirAll(filepath.Join(dir, ".config", "git"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, ".config", "git", "config"), nil, 0o644)) + role := filepath.Join(policyDir, "default.toml") + body := []byte("model = \"gpt-5.6-luna\"\n") + require.NoError(t, os.WriteFile(role, body, 0o644)) + policy := codexWritePolicy{Protected: []string{policyDir}, WriteRoots: []string{dir, "/dev/null"}, StatePaths: []string{}, Files: map[string]string{role: codexAssetSHA256(body)}, Directories: map[string][]string{policyDir: {"default.toml"}}} + raw, err := json.Marshal(policy) + require.NoError(t, err) + program := `import errno,os,pathlib,shutil,subprocess,sys +role,work=sys.argv[1:] +home=os.path.dirname(work) +def denied(fn): + try: fn() + except OSError as e: + assert e.errno in (errno.EACCES,errno.EPERM,errno.EXDEV,errno.EBADF),str(e) + else: raise AssertionError("policy write permitted") +denied(lambda: pathlib.Path(role).write_text("changed")) +denied(lambda: os.truncate(role,0)) +denied(lambda: os.unlink(role)) +denied(lambda: os.rename(os.path.dirname(role),work+"/moved")) +denied(lambda: pathlib.Path(os.path.dirname(role)+"/new.toml").write_text("new")) +denied(lambda: os.link(role,work+"/hardlink")) +os.symlink(role,work+"/link") +denied(lambda: pathlib.Path(work+"/link").write_text("changed")) +os.chmod(role,0o666) +denied(lambda: pathlib.Path(role).write_text("changed")) +denied(lambda: os.write(3,b"inherited-fd-write")) +pathlib.Path(work+"/normal").write_text("allowed") +denied(lambda: os.mkdir(home+"/.npm")) +os.makedirs(home+"/.config/tool") +env={k:v for k,v in os.environ.items() if not k.startswith(("GIT_","XDG_"))} +if shutil.which("git"): + subprocess.run(["git","config","--global","user.name","probe"],env={**env,"HOME":home},check=True) + assert "probe" in pathlib.Path(home+"/.config/git/config").read_text() +child=subprocess.run([sys.executable,"-I","-c","import pathlib,sys;pathlib.Path(sys.argv[1]).write_text('bad')",role],capture_output=True) +assert child.returncode != 0 +print("PROTECTION_OK")` + python := pythonWithTomllib(t) + // -W error fails on ctypes deprecations, such as 3.14's _pack_ without _layout_. + cmd := exec.Command(python, "-I", "-W", "error", "-c", codexLandlockPy, string(raw), python, "-I", "-c", program, role, work) + fd, err := os.OpenFile(role, os.O_WRONLY, 0) + require.NoError(t, err) + defer fd.Close() + cmd.ExtraFiles = []*os.File{fd} + out, err := cmd.CombinedOutput() + require.NoError(t, err, "%s", out) + assert.Contains(t, string(out), "PROTECTION_OK") + assert.Equal(t, string(body), readFileString(t, role)) + // Tampering before launch also fails closed, and the protected command + // never executes; an added role cannot broaden the registered file set. + // This case runs on the system python3 production resolves (codexPreflightPython). + require.NoError(t, os.WriteFile(filepath.Join(policyDir, "extra.toml"), body, 0o644)) + system, err := exec.Command("sh", "-c", "command -p -v python3").Output() + require.NoError(t, err) + cmd = exec.Command(strings.TrimSpace(string(system)), "-I", "-W", "error", "-c", codexLandlockPy, string(raw), "/bin/echo", "UNEXPECTED") + out, err = cmd.CombinedOutput() + require.Error(t, err) + assert.Contains(t, string(out), "file set modified") + assert.NotContains(t, string(out), "UNEXPECTED") +} + +// The image's PATH leads with the agent-writable /sandbox/.venv. A .pth planted +// there must not reach the interpreter the dispatch guard and launcher run on. +func TestCodexPreflightPythonIgnoresPlantedVenv(t *testing.T) { + if runtime.GOOS != "linux" { + t.Skip("resolves the system python3 through a real sh, as the sandbox does") + } + bin, venv := t.TempDir(), t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(bin, "openshell"), []byte("#!/bin/sh\nfor last; do :; done\nexec /bin/sh -c \"$last\"\n"), 0o755)) + out, err := exec.Command(pythonWithTomllib(t), "-m", "venv", "--without-pip", venv).CombinedOutput() + require.NoError(t, err, "%s", out) + site, err := filepath.Glob(filepath.Join(venv, "lib", "python3*", "site-packages")) + require.NoError(t, err) + require.Len(t, site, 1) + require.NoError(t, os.WriteFile(filepath.Join(site[0], "zz-bypass.pth"), []byte("import os; os._exit(0)\n"), 0o644)) + t.Setenv("PATH", bin+":"+filepath.Join(venv, "bin")+":"+os.Getenv("PATH")) + guard := func(python string) error { + cmd := exec.Command(python, "-I", "-c", codexDispatchPy, `["default"]`) + cmd.Stdin = strings.NewReader(`{"tool_name":"spawn_agent","tool_input":{"fork_context":true}}`) + return cmd.Run() + } + require.NoError(t, guard(filepath.Join(venv, "bin", "python3")), "the planted .pth bypasses the guard") + python, err := codexPreflightPython("sb") + require.NoError(t, err) + var exit *exec.ExitError + require.ErrorAs(t, guard(python), &exit, "resolved %s", python) + assert.Equal(t, 2, exit.ExitCode()) +} diff --git a/internal/runtime/codex_personas.go b/internal/runtime/codex_personas.go new file mode 100644 index 0000000000..fd0b28d692 --- /dev/null +++ b/internal/runtime/codex_personas.go @@ -0,0 +1,213 @@ +package runtime + +import ( + _ "embed" + "encoding/json" + "fmt" + "os" + "path/filepath" + "slices" + "strings" +) + +//go:embed codex_hook/fullsend-codex-dispatch.py +var codexDispatchPy string + +// codexDispatchMatcher is an exact alternation of hook tool names. Codex +// canonicalizes only V1 spawn_agent; other namespaced tools reach hooks as +// namespace+name with no separator (codex-rs/core/src/tools/mod.rs +// flat_tool_name): V1 resume is multi_agent_v1resume_agent and V2 spawn is +// collaborationspawn_agent. The plain names cover providers without +// namespaced tools. +const codexDispatchMatcher = "spawn_agent|resume_agent|multi_agent_v1resume_agent|collaborationspawn_agent" + +func codexAddDispatchGuard(data []byte, python string, roles []codexPersona) ([]byte, error) { + var hooks codexHooksConfig + if err := json.Unmarshal(data, &hooks); err != nil { + return nil, fmt.Errorf("parsing codex hooks: %w", err) + } + if hooks.Hooks == nil { + hooks.Hooks = map[string][]codexHookMatcherSet{} + } + names := make([]string, 0, len(roles)) + for _, role := range roles { + names = append(names, role.Name) + } + roster, _ := json.Marshal(names) + guard := codexHookMatcherSet{Matcher: codexDispatchMatcher, Hooks: []codexHookEntry{{ + Type: "command", Timeout: 5, + Command: shellQuote(python) + " -I -c " + shellQuote(codexDispatchPy) + " " + shellQuote(string(roster)), + }}} + hooks.Hooks["PreToolUse"] = append([]codexHookMatcherSet{guard}, hooks.Hooks["PreToolUse"]...) + return json.MarshalIndent(hooks, "", " ") +} + +const codexDefaultSubagentModel = "gpt-5.6-luna" + +const codexRolesDir = "/sandbox/codex-policy/roles" + +// codexPersona is a native role. Claude model aliases and tool declarations +// never enter its TOML; model selection belongs to the harness configuration. +type codexPersona struct { + Name, Description, Model, Instructions string +} + +func codexPersonas(input BootstrapInput, agentName string) ([]codexPersona, error) { + // Pi deliberately skips invalid personas for compatibility. Codex is a new + // consumer and fails closed rather than dispatching a misspelled role as a + // generic child. Check filesystem types before the shared discovery reads. + for _, skill := range input.SkillDirs() { + if skill == "" { + continue + } + dir := filepath.Join(skill, "sub-agents") + info, err := os.Lstat(dir) + if os.IsNotExist(err) { + continue + } + if err != nil { + return nil, fmt.Errorf("codex personas: %w", err) + } + if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return nil, fmt.Errorf("codex personas: %s must be a regular directory", dir) + } + entries, err := os.ReadDir(dir) + if err != nil { + return nil, fmt.Errorf("codex personas: %w", err) + } + for _, entry := range entries { + if strings.HasSuffix(entry.Name(), ".md") && !entry.Type().IsRegular() { + return nil, fmt.Errorf("codex persona %s must be a regular file", filepath.Join(dir, entry.Name())) + } + } + } + personas, skipped, err := discoverPersonas(input.SkillDirs(), agentName) + if err != nil { + return nil, fmt.Errorf("codex personas: %w", err) + } + if len(skipped) != 0 { + return nil, fmt.Errorf("codex persona %s: %s", skipped[0].Path, skipped[0].Reason) + } + models := map[string]string{} + known := map[string]bool{"default": true, "explore": true} + for _, persona := range personas { + known[persona.Name] = true + } + keys := make([]string, 0, len(input.AgentSubagents())) + for key := range input.AgentSubagents() { + keys = append(keys, key) + } + slices.Sort(keys) + for _, key := range keys { + value := input.AgentSubagents()[key] + if value == nil { // A layered-config tombstone removes an override. + continue + } + if !known[key] { + return nil, fmt.Errorf("codex subagents.%s: no such persona in the selected skills", key) + } + model, err := codexPersonaModel(*value) + if err != nil { + return nil, fmt.Errorf("codex subagents.%s: %w", key, err) + } + models[key] = model + } + defaultModel := codexDefaultSubagentModel + if model := models["default"]; model != "" { + defaultModel = model + } + if value := strings.TrimSpace(os.Getenv("FULLSEND_CODEX_SUBAGENT_MODEL")); value != "" { + model, err := codexPersonaModel(value) + if err != nil { + return nil, fmt.Errorf("FULLSEND_CODEX_SUBAGENT_MODEL: %w", err) + } + defaultModel = model + } + resolve := func(name string) string { + if name != "default" && models[name] != "" { + return models[name] + } + return defaultModel + } + roles := []codexPersona{ + { + Name: "default", Description: "Investigate the explicit task package supplied by the parent.", + Model: defaultModel, Instructions: codexChildInstructions, + }, + { + Name: "explore", Description: "Read-only exploration and evidence gathering.", + Model: resolve("explore"), Instructions: "Explore using read-only tools. Do not edit files or execute state-changing commands.\n\n" + codexChildInstructions, + }, + } + for _, persona := range personas { + if persona.Description == "" { + return nil, fmt.Errorf("codex persona %s: frontmatter description is required (Codex drops a role without one)", persona.Name) + } + if persona.Model != "" { + fmt.Fprintf(os.Stderr, "Codex persona %q: ignoring Claude frontmatter model %q; resolved model %q\n", persona.Name, persona.Model, resolve(persona.Name)) + } + if len(persona.Tools) != 0 || len(persona.BashAllowlist) != 0 { + fmt.Fprintf(os.Stderr, "Codex persona %q: Claude frontmatter tools are documentation only; shared security hooks still apply\n", persona.Name) + } + roles = append(roles, codexPersona{ + Name: persona.Name, Description: persona.Description, + Model: resolve(persona.Name), Instructions: persona.Body + "\n\n" + codexChildInstructions, + }) + } + slices.SortFunc(roles, func(a, b codexPersona) int { return strings.Compare(a.Name, b.Name) }) + return roles, nil +} + +func codexPersonaModel(value string) (string, error) { + value = strings.TrimSpace(value) + model, err := translateCodexModel(value) + if err != nil { + return "", err + } + if strings.EqualFold(model, "inherit") || codexClaudeAliases[strings.ToLower(model)] || strings.ContainsAny(model, "/ \t\r\n") { + return "", fmt.Errorf("an explicit OpenAI model ID is required, got %q", value) + } + return model, nil +} + +func (p codexPersona) config() []byte { + return []byte("# Written by fullsend; do not edit.\nmodel = " + codexTOMLString(p.Model) + + "\ndeveloper_instructions = " + codexTOMLString(p.Instructions) + "\n") +} + +func codexPersonaConfig(roles []codexPersona, dir string) string { + if len(roles) == 0 { + // The model's catalog entry overrides [features] multi_agent; only + // this removes spawn_agent (verified on 0.157.0 and 0.158.0). + return "\n[agents]\nenabled = false\n" + } + var b strings.Builder + b.WriteString("\n[agents]\nmax_concurrent_threads_per_session = 4\nmax_depth = 1\n") + for _, role := range roles { + if role.Name == "default" { + fmt.Fprintf(&b, "default_subagent_model = %s\n", codexTOMLString(role.Model)) + } + } + for _, role := range roles { + fmt.Fprintf(&b, "\n[agents.%s]\ndescription = %s\nconfig_file = %s\n", codexTOMLString(role.Name), codexTOMLString(role.Description), codexTOMLString(dir+"/"+role.Name+".toml")) + } + return b.String() +} + +const codexChildInstructions = `Work only on the explicit task supplied by the parent. Return your evidence and result to the parent. Do not dispatch further children. Do not write the parent's final agent-result.json; synthesis and final output belong to the parent.` + +const codexSubagentNote = ` +## Native Codex delegation + +This agent runs on FULLSEND_RUNTIME=codex. + +Use native spawn_agent for skill-requested delegation. Named personas use the matching agent_type; generic tasks use default; Explore tasks use explore. Explore is an instruction to use read-only operations, not an additional filesystem sandbox. The runtime selects child models: omit model and reasoning overrides, and never translate Claude aliases or pass inherit. + +Give each child a complete, explicit task package and fresh context using the V1 tool schema with fork_context=false. Delegation requires a V1 parent: the parent model's metadata selects its tool API, independently of the selected child model. V2 arguments (fork_turns or task_name) are rejected, with no automatic fallback. If the session exposes V2 tools, report delegation as unsupported. + +At most four children may be open at once. Dispatch larger batches in waves. Wait can return when only ONE child finishes: keep waiting for every outstanding child, collect each result, and close each finished child (completed, errored, shutdown or not_found) with close_agent before opening another slot. Never close a still-running child to collect its result. Missing results, failed children, and cancellation are not successful completion. Keep root synthesis and agent-result.json with the parent. Start any challenger only after collecting the original findings, with a new task and fresh context. Children must not dispatch grandchildren. + +Do not resume closed children: native resume does not preserve the selected role policy. Spawn a new child with an explicit fresh task instead. + +Before writing the final output, confirm that EVERY spawned child ID, including the final challenger, has finished and been closed. A final child still needs closing even when no further slot will be opened. Do not wait on or close an already-closed ID again. +` diff --git a/internal/runtime/codex_personas_test.go b/internal/runtime/codex_personas_test.go new file mode 100644 index 0000000000..f6de2876d1 --- /dev/null +++ b/internal/runtime/codex_personas_test.go @@ -0,0 +1,166 @@ +package runtime + +import ( + "encoding/json" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type codexPersonaInput struct { + bootstrapInput + subagents map[string]*string +} + +func (b codexPersonaInput) AgentSubagents() map[string]*string { return b.subagents } + +func codexPersonaSkill(t *testing.T, name, body string) string { + t.Helper() + dir := t.TempDir() + require.NoError(t, os.Mkdir(filepath.Join(dir, "sub-agents"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "sub-agents", name+".md"), []byte(body), 0o644)) + return dir +} + +func codexParseTOML(t *testing.T, data []byte) map[string]any { + t.Helper() + cmd := exec.Command(pythonWithTomllib(t), "-c", "import json,sys,tomllib; print(json.dumps(tomllib.loads(sys.stdin.read())))") + cmd.Stdin = strings.NewReader(string(data)) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "%s", out) + var result map[string]any + require.NoError(t, json.Unmarshal(out, &result)) + return result +} + +func TestCodexBootstrapPersonaModels(t *testing.T) { + ptr := func(s string) *string { return &s } + for _, tt := range []struct { + name, envDefault, wantNamed, wantGeneric string + settings map[string]*string + }{ + {name: "cheap default ignores Claude frontmatter", wantNamed: "gpt-5.6-luna", wantGeneric: "gpt-5.6-luna"}, + {name: "configured default", settings: map[string]*string{"default": ptr("openai/gpt-5.5")}, wantNamed: "gpt-5.5", wantGeneric: "gpt-5.5"}, + {name: "child model does not select parent tool API", settings: map[string]*string{"default": ptr("openai/gpt-6-sol")}, wantNamed: "gpt-6-sol", wantGeneric: "gpt-6-sol"}, + {name: "environment overrides configured default", envDefault: "openai/gpt-5.6-luna", settings: map[string]*string{"default": ptr("gpt-5.5")}, wantNamed: "gpt-5.6-luna", wantGeneric: "gpt-5.6-luna"}, + {name: "persona overrides environment", envDefault: "gpt-5.6-luna", settings: map[string]*string{"correctness": ptr("openai/gpt-5.5")}, wantNamed: "gpt-5.5", wantGeneric: "gpt-5.6-luna"}, + {name: "tombstone removes persona override", envDefault: "gpt-5.6-luna", settings: map[string]*string{"correctness": nil, "default": ptr("gpt-5.5")}, wantNamed: "gpt-5.6-luna", wantGeneric: "gpt-5.6-luna"}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Setenv("FULLSEND_CODEX_SUBAGENT_MODEL", tt.envDefault) + store := t.TempDir() + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), store, "codex-cli 0.157.0") + skill := codexPersonaSkill(t, "correctness", "---\nname: correctness\ndescription: Find defects.\nmodel: opus\ntools: Read\n---\nReturn only independently verified defects.\n") + r := CodexRuntime{} + err := r.Bootstrap(codexPersonaInput{bootstrapInput: bootstrapInput{ + sandboxName: "personas", agentPath: writeAgentFile(t, codexTestReviewAgentDef), agentName: "review", skillDirs: []string{skill}, + }, subagents: tt.settings}) + require.NoError(t, err) + cfg := codexParseTOML(t, storedUpload(t, store, r.codexConfigPath())) + agents, ok := cfg["agents"].(map[string]any) + require.True(t, ok, "Bootstrap must register native children") + assert.NotContains(t, agents, "enabled", "Codex's default keeps multi-agent tools on") + assert.Equal(t, tt.wantGeneric, agents["default_subagent_model"]) + assert.Equal(t, float64(4), agents["max_concurrent_threads_per_session"]) + assert.Equal(t, float64(1), agents["max_depth"]) + for name, model := range map[string]string{"correctness": tt.wantNamed, "default": tt.wantGeneric, "explore": tt.wantGeneric} { + decl, ok := agents[name].(map[string]any) + require.True(t, ok, "role %s missing", name) + rolePath, ok := decl["config_file"].(string) + require.True(t, ok) + role := codexParseTOML(t, storedUpload(t, store, rolePath)) + assert.Equal(t, model, role["model"], "role %s", name) + if name == "correctness" { + assert.Contains(t, role["developer_instructions"], "Return only independently verified defects.") + assert.Equal(t, "Find defects.", decl["description"]) + } + assert.NotContains(t, role, "tools", "Claude fields must not enter native TOML") + } + }) + } +} + +func TestCodexBootstrapRejectsInvalidPersonaConfiguration(t *testing.T) { + for _, tt := range []struct{ name, model string }{ + {"Claude alias", "opus"}, {"prefixed alias", "openai/opus"}, {"inherit is not a model", "inherit"}, {"prefixed inherit", "OPENAI/inherit"}, {"other provider", "anthropic/claude-opus"}, {"blank", ""}, + } { + t.Run(tt.name, func(t *testing.T) { + t.Setenv("FULLSEND_CODEX_SUBAGENT_MODEL", "") + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "codex-cli 0.157.0") + err := (CodexRuntime{}).Bootstrap(codexPersonaInput{bootstrapInput: bootstrapInput{sandboxName: "invalid", agentPath: writeAgentFile(t, codexTestReviewAgentDef)}, subagents: map[string]*string{"default": &tt.model}}) + require.Error(t, err) + assert.Contains(t, err.Error(), "subagents.default") + }) + } +} + +func TestCodexPersonaSerializationAndGenericRoles(t *testing.T) { + t.Setenv("FULLSEND_CODEX_SUBAGENT_MODEL", "") + roles, err := codexPersonas(codexPersonaInput{bootstrapInput: bootstrapInput{skillDirs: []string{"", t.TempDir()}}}, "retro") + require.NoError(t, err) + require.Len(t, roles, 2, "retro can delegate without persona files") + assert.Equal(t, "default", roles[0].Name) + assert.Equal(t, "explore", roles[1].Name) + instructions := "quoted \"\"\"\n[agents.evil]\nmodel = \"opus\"\nbackslash \\ and tab\t" + role := codexPersona{Name: "test", Description: "Test", Model: "gpt-5.6-luna", Instructions: instructions} + parsed := codexParseTOML(t, role.config()) + assert.Equal(t, instructions, parsed["developer_instructions"]) + assert.NotContains(t, parsed, "agents") +} + +func TestCodexPersonaInvalidDiscoveryAndSettings(t *testing.T) { + for _, body := range []string{"---\nname: [broken\n---\nBody", "---\nname: mismatch\n---\nBody", "Body with no name"} { + _, err := codexPersonas(codexPersonaInput{bootstrapInput: bootstrapInput{skillDirs: []string{codexPersonaSkill(t, "test", body)}}}, "retro") + require.Error(t, err) + } + _, err := codexPersonas(codexPersonaInput{bootstrapInput: bootstrapInput{skillDirs: []string{codexPersonaSkill(t, "test", "---\nname: test\n---\nBody")}}}, "retro") + require.ErrorContains(t, err, "description is required", "Codex silently drops a role with a blank description") + file := filepath.Join(t.TempDir(), "not-a-skill-dir") + require.NoError(t, os.WriteFile(file, nil, 0o644)) + _, err = codexPersonas(codexPersonaInput{bootstrapInput: bootstrapInput{skillDirs: []string{file}}}, "retro") + require.ErrorContains(t, err, "codex personas:", "an unreadable skill path fails closed") + if os.Geteuid() != 0 { + roster := filepath.Join(codexPersonaSkill(t, "correctness", "---\nname: correctness\ndescription: Find defects.\n---\nBody"), "sub-agents") + require.NoError(t, os.Chmod(roster, 0)) + t.Cleanup(func() { _ = os.Chmod(roster, 0o755) }) + _, err = codexPersonas(codexPersonaInput{bootstrapInput: bootstrapInput{skillDirs: []string{filepath.Dir(roster)}}}, "retro") + require.ErrorContains(t, err, "codex personas:", "an unreadable roster fails closed; pi only skips it") + } + model := "gpt-5.6-luna" + _, err = codexPersonas(codexPersonaInput{subagents: map[string]*string{"unknown": &model}}, "retro") + require.ErrorContains(t, err, "no such persona") + t.Setenv("FULLSEND_CODEX_SUBAGENT_MODEL", "inherit") + _, err = codexPersonas(codexPersonaInput{}, "retro") + require.ErrorContains(t, err, "FULLSEND_CODEX_SUBAGENT_MODEL") +} + +func TestCodexBootstrapRejectsDuplicateAndSymlinkPersonas(t *testing.T) { + definition := "---\nname: correctness\ndescription: Find defects.\n---\nFind defects.\n" + for _, kind := range []string{"duplicate", "file symlink", "directory symlink", "reserved name"} { + t.Run(kind, func(t *testing.T) { + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "codex-cli 0.157.0") + skill := codexPersonaSkill(t, "correctness", definition) + dirs := []string{skill} + switch kind { + case "duplicate": + dirs = append(dirs, codexPersonaSkill(t, "correctness", definition)) + case "file symlink": + file := filepath.Join(skill, "sub-agents", "correctness.md") + require.NoError(t, os.Rename(file, filepath.Join(skill, "target.md"))) + require.NoError(t, os.Symlink("../target.md", file)) + case "directory symlink": + require.NoError(t, os.Rename(filepath.Join(skill, "sub-agents"), filepath.Join(skill, "target"))) + require.NoError(t, os.Symlink("target", filepath.Join(skill, "sub-agents"))) + case "reserved name": + dirs = []string{codexPersonaSkill(t, "default", "---\nname: default\n---\nOverride native default.\n")} + } + err := (CodexRuntime{}).Bootstrap(bootstrapInput{sandboxName: "bad-persona", agentPath: writeAgentFile(t, codexTestReviewAgentDef), skillDirs: dirs}) + require.Error(t, err) + }) + } +} diff --git a/internal/runtime/codex_progress.go b/internal/runtime/codex_progress.go index d99005e30f..c0f6466d8a 100644 --- a/internal/runtime/codex_progress.go +++ b/internal/runtime/codex_progress.go @@ -4,6 +4,7 @@ import ( "bufio" "bytes" "encoding/json" + "errors" "fmt" "io" "os" @@ -195,6 +196,10 @@ type codexCollabToolCallItem struct { Tool string `json:"tool"` ReceiverThreadIDs []string `json:"receiver_thread_ids"` Status string `json:"status"` + AgentStates map[string]struct { + Status string `json:"status"` + Message string `json:"message"` + } `json:"agents_states"` } type codexWebSearchItem struct { @@ -371,8 +376,11 @@ const ( // - A turn interrupted (Ctrl-C, kill) emits *neither* terminal event — the // processor shuts down silently — so a stream with no terminal event is // reported as an incomplete, failed run rather than a success. -func parseCodexStream(r io.Reader, onEvent func(AgentEvent)) (threadID string, err error) { - br := bufio.NewReaderSize(r, streamBufSize) +func parseCodexStream(r io.Reader, onEvent func(AgentEvent), onCollab ...func(codexCollabToolCallItem)) (threadID string, err error) { + // Collaboration events include full prompts and child results, so they can + // exceed the shared 1 MiB progress buffer. Use the Codex stream artifact's + // bound and reject larger records rather than losing lifecycle evidence. + br := bufio.NewReaderSize(r, codexRedactMaxLine) var ( numTurns int @@ -484,6 +492,9 @@ func parseCodexStream(r io.Reader, onEvent func(AgentEvent)) (threadID string, e summary += " (failed)" } onEvent(ToolUseEvent{Name: "Agent", Summary: piSummarize(summary)}) + for _, observe := range onCollab { + observe(item) + } case "web_search": var item codexWebSearchItem if json.Unmarshal(raw, &item) != nil { @@ -516,6 +527,7 @@ func parseCodexStream(r io.Reader, onEvent func(AgentEvent)) (threadID string, e result := ResultEvent{ NumTurns: numTurns, TotalCostUSD: 0, // codex reports no cost + CostUnavailable: true, InputTokens: counters.Input, OutputTokens: counters.Output, ReasoningTokens: counters.Reasoning, @@ -549,12 +561,11 @@ func parseCodexStream(r io.Reader, onEvent func(AgentEvent)) (threadID string, e finish() return threadID, readErr } - // Skip lines exceeding the buffer (same pattern as the other parsers). if isPrefix { - for isPrefix && readErr == nil { - _, isPrefix, readErr = br.ReadLine() - } - continue + terminal = codexTerminalNone + criticalErrMsg = fmt.Sprintf("codex stream record exceeds %d-byte limit", codexRedactMaxLine) + finish() + return threadID, errors.New(criticalErrMsg) } if len(line) == 0 { continue @@ -672,6 +683,7 @@ func applyCodexMetrics(metrics *RunMetrics, evt AgentEvent) { switch e := evt.(type) { case ResultEvent: metrics.NumTurns = e.NumTurns + metrics.CostUnavailable = metrics.CostUnavailable || e.CostUnavailable metrics.InputTokens = e.InputTokens metrics.OutputTokens = e.OutputTokens metrics.ReasoningTokens = e.ReasoningTokens diff --git a/internal/runtime/codex_progress_test.go b/internal/runtime/codex_progress_test.go index d7a48e1083..57708b8576 100644 --- a/internal/runtime/codex_progress_test.go +++ b/internal/runtime/codex_progress_test.go @@ -549,7 +549,7 @@ func TestParseCodexStream_ReadErrorStillEmitsResult(t *testing.T) { assert.Equal(t, codexSubtypeIncomplete, result.Subtype) } -func TestParseCodexStream_OverlongLineIsSkipped(t *testing.T) { +func TestParseCodexStream_LargeMessageIsNotDropped(t *testing.T) { t.Parallel() huge := `{"type":"item.completed","item":{"id":"i0","type":"agent_message","text":"` + @@ -568,11 +568,41 @@ func TestParseCodexStream_OverlongLineIsSkipped(t *testing.T) { require.NoError(t, err) texts := codexEventsOfType[TextEvent](events) - require.Len(t, texts, 1, "the oversized line is dropped, the stream continues") - assert.Equal(t, "after", texts[0].Text) + require.Len(t, texts, 2, "records larger than the shared parser buffer must be retained") + assert.Len(t, texts[0].Text, streamBufSize+1024) + assert.Equal(t, "after", texts[1].Text) assert.False(t, codexOnlyResult(t, events).IsError) } +func TestParseCodexStream_LargeCollaborationIsNotDropped(t *testing.T) { + large := strings.Repeat("e", streamBufSize+1024) + stream := fmt.Sprintf(`{"type":"thread.started","thread_id":"root"} +{"type":"item.completed","item":{"id":"spawn","type":"collab_tool_call","tool":"spawn_agent","prompt":%q,"receiver_thread_ids":["child"],"status":"completed"}} +{"type":"item.completed","item":{"id":"wait","type":"collab_tool_call","tool":"wait","receiver_thread_ids":["child"],"agents_states":{"child":{"status":"completed","message":%q}},"status":"completed"}} +{"type":"turn.completed","usage":{"input_tokens":10,"output_tokens":2}} +`, large, large) + var calls []codexCollabToolCallItem + _, err := parseCodexStream(strings.NewReader(stream), func(AgentEvent) {}, func(call codexCollabToolCallItem) { calls = append(calls, call) }) + require.NoError(t, err) + require.Len(t, calls, 2, "losing either event loses child identity or completion") + assert.Equal(t, "spawn_agent", calls[0].Tool) + assert.Equal(t, []string{"child"}, calls[0].ReceiverThreadIDs) + assert.Equal(t, "completed", calls[1].AgentStates["child"].Status) + assert.Equal(t, large, calls[1].AgentStates["child"].Message) +} + +func TestParseCodexStream_OverLimitCannotRetainEarlierSuccess(t *testing.T) { + stream := "{\"type\":\"turn.completed\",\"usage\":{\"input_tokens\":10,\"output_tokens\":2}}\n" + + strings.Repeat("x", codexRedactMaxLine+1024) + "\n" + var events []AgentEvent + _, err := parseCodexStream(strings.NewReader(stream), func(event AgentEvent) { events = append(events, event) }) + require.Error(t, err, "discarded records could include a child dispatch after the last completed turn") + result := codexOnlyResult(t, events) + assert.True(t, result.IsError) + assert.Equal(t, codexSubtypeIncomplete, result.Subtype) + assert.Equal(t, 10, result.InputTokens, "retain usage recorded before the incomplete evidence") +} + // --- redaction -------------------------------------------------------------- func TestCodexSummaries_RedactSecrets(t *testing.T) { diff --git a/internal/runtime/codex_redact.go b/internal/runtime/codex_redact.go index 5ae10e5145..814ab30e4f 100644 --- a/internal/runtime/codex_redact.go +++ b/internal/runtime/codex_redact.go @@ -208,7 +208,10 @@ var codexRolloutEnvelopes = map[string]bool{ // codexMaxArtifactBytes bounds what the artifact filters will read. A codex // rollout for a long run is megabytes; the sessions directory is // agent-writable, so without a bound a planted multi-gigabyte file would be -// read into the runner's memory to be "redacted". +// read into the runner's memory to be "redacted". Native CommandExecution +// records duplicate tool output in multiple fields and can exceed the shared +// transcript line limit. Codex rollout scanners allow a line up to this whole +// artifact bound, plus one byte to detect overflow or the final newline. const codexMaxArtifactBytes = 256 << 20 // codexIsRolloutFile reports whether path is a codex rollout, by parsing @@ -228,7 +231,7 @@ func codexIsRolloutFile(path string) error { } scanner := bufio.NewScanner(f) - scanner.Buffer(make([]byte, 0, 64*1024), maxTranscriptLineSize) + scanner.Buffer(make([]byte, 0, 64*1024), codexMaxArtifactBytes+1) seen := 0 for scanner.Scan() { line := bytes.TrimSpace(scanner.Bytes()) diff --git a/internal/runtime/codex_redact_test.go b/internal/runtime/codex_redact_test.go index 60a7df177d..c29e6e73b9 100644 --- a/internal/runtime/codex_redact_test.go +++ b/internal/runtime/codex_redact_test.go @@ -153,7 +153,7 @@ func TestCodexRun_TeedOutputIsRedacted(t *testing.T) { `{"type":"item.completed","item":{"id":"i1","type":"command_execution","command":"cat .env",`+ `"aggregated_output":"GITHUB_TOKEN=`+codexTestSecret+`","exit_code":0,"status":"completed"}}`+"\n"+ `{"type":"turn.completed","usage":{"input_tokens":10,"output_tokens":5}}`+"\n"), 0o644)) - fakeOpenshellCodex(t, logPath, storeDir, "codex-cli 0.152.1", fixture) + fakeOpenshellCodexWithRollouts(t, logPath, storeDir, fixture, map[string]string{"root.jsonl": testCodexRootUsage("t1", "gpt-5-mini", 10, 5, 0)}) outPath := filepath.Join(t.TempDir(), "output.jsonl") metrics := &RunMetrics{} diff --git a/internal/runtime/codex_rollout_limits_test.go b/internal/runtime/codex_rollout_limits_test.go new file mode 100644 index 0000000000..beeb50811c --- /dev/null +++ b/internal/runtime/codex_rollout_limits_test.go @@ -0,0 +1,135 @@ +package runtime + +import ( + "bytes" + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCodexRolloutLargeCommandOutput(t *testing.T) { + // Native item_completed records retain stdout and aggregated_output. A + // real 0.157.0 command produced a 1,455,304-byte JSONL record this way, + // exceeding the other runtimes' 1 MiB line limit within a small artifact. + output := strings.Repeat("harmless command output\n", 32000) + codexTestSecret + event, err := json.Marshal(map[string]any{ + "type": "event_msg", + "payload": map[string]any{ + "type": "item_completed", "thread_id": "child", "turn_id": "turn", + "item": map[string]any{ + "type": "CommandExecution", "status": "completed", + "stdout": output, "aggregated_output": output, "stderr": "", + }, + }, + }) + require.NoError(t, err) + data := strings.Join([]string{ + codexUsageTestMeta, + codexUsageTestContext("turn", "gpt-5.6-luna"), + string(event), + codexUsageTestRecord(t, "after-large-output", "turn", codexUsage{InputTokens: 123, OutputTokens: 45}), + }, "\n") // Exercise a final record without a trailing newline too. + + t.Run("usage after large output is retained", func(t *testing.T) { + got, err := parseCodexRolloutUsage(strings.NewReader(data)) + require.NoError(t, err) + require.Len(t, got.Responses, 1) + assert.Equal(t, "after-large-output", got.Responses[0].Record.ResponseID) + assert.Equal(t, "gpt-5.6-luna", got.Responses[0].Model) + assert.Equal(t, 123, got.Responses[0].Record.Usage.InputTokens) + assert.Equal(t, 45, got.Responses[0].Record.Usage.OutputTokens) + }) + + t.Run("complete artifact is validated and redacted", func(t *testing.T) { + path := filepath.Join(t.TempDir(), "rollout.jsonl") + require.NoError(t, os.WriteFile(path, []byte(data), 0o600)) + require.NoError(t, codexIsRolloutFile(path)) + require.NoError(t, codexRedactFile(path)) + redacted, err := os.ReadFile(path) + require.NoError(t, err) + require.NotContains(t, string(redacted), codexTestSecret) + lines := bytes.Split(redacted, []byte{'\n'}) + require.Len(t, lines, 4, "large records must not be split or discarded") + for _, line := range lines { + require.True(t, json.Valid(line)) + } + var item struct { + Payload struct { + Item struct { + Stdout string `json:"stdout"` + } `json:"item"` + } `json:"payload"` + } + require.NoError(t, json.Unmarshal(lines[2], &item)) + assert.Equal(t, 32000, strings.Count(item.Payload.Item.Stdout, "harmless command output\n")) + assert.Contains(t, string(lines[3]), "after-large-output") + require.NoError(t, codexIsRolloutFile(path)) + }) + + t.Run("invalid evidence after large output is rejected", func(t *testing.T) { + for _, tail := range []string{"not JSON", `{"type":"not_a_codex_envelope","payload":{}}`} { + bad := data + "\n" + tail + _, err := parseCodexRolloutUsage(strings.NewReader(bad)) + require.Error(t, err) + assert.Contains(t, err.Error(), "line 5", "must validate past the large record") + path := filepath.Join(t.TempDir(), "rollout.jsonl") + require.NoError(t, os.WriteFile(path, []byte(bad), 0o600)) + err = codexIsRolloutFile(path) + require.Error(t, err) + assert.Contains(t, err.Error(), "line 5") + } + }) +} + +func TestCodexRolloutScannerPreviousLineBoundary(t *testing.T) { + // An exact-size buffer needs room to discover EOF or consume a newline. + // Both paths must accept records around the previous 1 MiB boundary. + const prefix = `{"type":"response_item","payload":{"type":"function_call_output","output":"` + const suffix = `"}}` + for _, size := range []int{1<<20 - 1, 1 << 20, 1<<20 + 1} { + for _, newline := range []bool{false, true} { + t.Run(fmt.Sprintf("bytes=%d/newline=%t", size, newline), func(t *testing.T) { + line := prefix + strings.Repeat("x", size-len(prefix)-len(suffix)) + suffix + data := codexUsageTestMeta + "\n" + line + if newline { + data += "\n" + } + _, err := parseCodexRolloutUsage(strings.NewReader(data)) + require.NoError(t, err) + path := filepath.Join(t.TempDir(), "rollout.jsonl") + require.NoError(t, os.WriteFile(path, []byte(data), 0o600)) + require.NoError(t, codexIsRolloutFile(path)) + }) + } + } +} + +// Generate an unending stream without allocating an artifact-sized fixture. +// Blank records force the parser to reach its byte bound instead of stopping +// earlier at an invalid JSON record. +type codexBlankRolloutReader struct{ bytesRead int } + +func (r *codexBlankRolloutReader) Read(p []byte) (int, error) { + for i := range p { + p[i] = ' ' + } + if len(p) > 0 { + p[len(p)-1] = '\n' + } + r.bytesRead += len(p) + return len(p), nil +} + +func TestCodexRolloutUsageRejectsArtifactPastByteLimit(t *testing.T) { + r := &codexBlankRolloutReader{} + _, err := parseCodexRolloutUsage(r) + require.Error(t, err) + assert.Contains(t, err.Error(), "artifact limit") + assert.LessOrEqual(t, r.bytesRead, 256<<20+1, "read no further than the bound plus its overflow probe") +} diff --git a/internal/runtime/codex_run.go b/internal/runtime/codex_run.go index 15da61bbd0..472d50a694 100644 --- a/internal/runtime/codex_run.go +++ b/internal/runtime/codex_run.go @@ -2,6 +2,7 @@ package runtime import ( "context" + "errors" "fmt" "io" "os" @@ -27,6 +28,10 @@ const codexHooksMissingExit = 97 // Run can name the actual cause. const codexConfigTamperedExit = 98 +// codexWriteProtectionExit is the Landlock launcher's sys.exit(78): no Landlock +// ABI 3+, or a runner-held file changed before launch. +const codexWriteProtectionExit = 78 + // codexBinaryVar holds the absolute path of the codex binary, resolved before // .env is sourced and marked read-only. const codexBinaryVar = "FULLSEND_CODEX_BIN" @@ -167,8 +172,8 @@ func codexBinaryPin() string { // codexAssetGuard is the POSIX sh fragment run before codex: the runner-owned // files must exist, and the two whose contents are fixed at compile time — the // hook adapter and the provider auth script — must be byte-identical to the -// copies embedded in this binary. The config directory is agent-writable -// between iterations, exactly as Claude Code's hooks.json and its scripts are. +// copies embedded in this binary. Landlock protects the launched hierarchy; +// these runner-held checks also detect external or pre-launch changes. // // `command -p` bypasses shell functions and uses the system default PATH, so // nothing left in the environment can stand in for sha256sum or cut; test, [ @@ -185,21 +190,8 @@ func codexAssetGuard(r CodexRuntime, hooksEnabled bool, digests codexRunnerHeldD "test -f "+shellQuote(r.codexManifestPath()), "test -f "+shellQuote(r.codexAdapterPath()), codexSHACheck(r.codexAdapterPath(), codexAssetSHA256(codexHookAdapterPy)), - // The wiring is rendered per run, so it cannot be pinned by a - // compile-time hash. Instead every handler line must carry both the - // "command" key and this adapter's path, so the two counts are - // equal: replacing one handler's command with something else, or - // adding a handler of the agent's own, breaks the equality. - // - // What it does not catch is deletion — removing whole handlers - // keeps the counts equal and narrows the wiring. That residue is - // the same one Claude Code has with its own hooks.json, which is - // likewise written once at Bootstrap and agent-writable after. - codexHooksAdapterCheck(r.codexHooksPath(), r.codexAdapterPath()), - // Every script in the hooks directory must be one this binary - // installed: the scripts are agent-writable between iterations, - // and a tirith_check.py rewritten to exit 0 would disable a - // control while every other check still passed. + // Bind every installed script to its name, including against + // external changes before the protected native hierarchy starts. codexHookScriptsGuard(r.codexHooksDir(), digests.HookScripts), ) } @@ -208,36 +200,8 @@ func codexAssetGuard(r CodexRuntime, hooksEnabled bool, digests codexRunnerHeldD strings.Join(checks, " && "), codexHooksMissingExit) } -// codexHooksAdapterCheck asserts that every command handler in hooks.json -// still invokes adapter. -// -// This is **defense in depth, not the boundary**. On its own the count -// comparison is bypassable — swap one handler's command and pad the adapter's -// path into the free-form `description` field to restore parity. What actually -// makes hooks.json tamper-evident is codexConfigGuard's whole-file digest, -// a runner-held digest; this check survives as a cheap, readable -// assertion that fails first and names the wiring rather than the file. -// -// The grouping braces are load-bearing: `&&` and `||` are left-associative in -// sh, so an ungrouped alternation inside the guard's chain would rescue every -// earlier failure and make the whole guard fail open. -func codexHooksAdapterCheck(hooksPath, adapter string) string { - // `grep -o | wc -l` counts occurrences rather than matching lines: the - // runner writes one handler per line, but an agent rewriting the file is - // under no such obligation, and a compacted single-line hooks.json would - // make a line count collapse to 1 = 1 and pass. - count := func(pattern string) string { - return fmt.Sprintf(`$(command -p grep -o %s %s | command -p wc -l)`, - shellQuote(pattern), shellQuote(hooksPath)) - } - // The key, with its colon: a bare `"command"` would also match the value - // in `"type": "command"` and double every handler's count. - return fmt.Sprintf(`[ "%s" = "%s" ]`, count(`"command":`), count(adapter)) -} - -func codexSHACheck(path, sum string) string { - return fmt.Sprintf(`[ "$(command -p sha256sum %s | command -p cut -d' ' -f1)" = %s ]`, - shellQuote(path), shellQuote(sum)) +func codexSHACheck(path, expected string) string { + return `[ "$(command -p sha256sum ` + shellQuote(path) + ` | command -p cut -d' ' -f1)" = ` + shellQuote(expected) + ` ]` } // codexConfigGuard is the POSIX sh fragment that fails closed when a @@ -305,15 +269,13 @@ func buildCodexRunCommand(params RunParams, model, effort string, hooksEnabled b "&& readonly "+codexPathVar+`="$PATH"`, "&& "+codexAssetGuard(r, hooksEnabled, digests), "&& "+codexConfigGuard(r, digests), - "&& "+r.OpenAIAuthSeed(), "&& . "+shellQuote(envFile), // .env is agent-writable; re-pin the runner-owned config location // after it so a rewritten .env cannot move codex's home out from // under the guards. "&& "+strings.Join(r.EnvExports(), " && "), - // Restored for codex itself, and exported so the hook adapter can set - // it for its children from a value that never passed through .env — - // rather than trusting whatever PATH it happens to inherit. + // Keep the npm launcher's env-node interpreter, provider auth and hooks + // on the trusted base PATH. Writable helpers belong only in tool shells. "&& export PATH=\"$"+codexPathVar+"\" && export "+codexPathVar, "&& export "+codexRuntimeEnv+"=codex", // NODE_* would load code into npm's codex launcher; PYTHON* would do @@ -323,7 +285,10 @@ func buildCodexRunCommand(params RunParams, model, effort string, hooksEnabled b // LD_* would load code into any dynamically linked binary the run // starts — codex's own native binary, tirith, git — before its main // runs, which no digest of ours would see. - "&& unset OPENAI_BASE_URL OPENAI_API_KEY CODEX_API_KEY NODE_OPTIONS NODE_PATH PYTHONPATH PYTHONHOME PYTHONSTARTUP LD_PRELOAD LD_LIBRARY_PATH LD_AUDIT", + // Native hooks invoke the image's shell non-interactively. Bash still + // sources BASH_ENV in that mode, so a planted startup script could exit + // before the mandatory guard even with allow_login_shell=false. + "&& unset OPENAI_BASE_URL OPENAI_API_KEY CODEX_API_KEY NODE_OPTIONS NODE_PATH PYTHONPATH PYTHONHOME PYTHONSTARTUP LD_PRELOAD LD_LIBRARY_PATH LD_AUDIT BASH_ENV ENV ZDOTDIR SHELL", // `unset -f` is a special builtin, which a function .env defined // cannot shadow, so it restores the real utilities before the second // pass; `command -p` inside the guard defeats a PATH swap. @@ -369,19 +334,21 @@ func buildCodexRunCommand(params RunParams, model, effort string, hooksEnabled b "--skip-git-repo-check", "--dangerously-bypass-approvals-and-sandbox", ) - if hooksEnabled { - // Unmanaged hooks otherwise run only when their recorded trusted_hash - // matches. fullsend's own SHA-256 guard above already vets the adapter - // the handlers invoke, and the alternative — baking a managed hook - // layer into /etc/codex at image build — would tie hook wiring to - // image releases (ADR 0099). - parts = append(parts, "--dangerously-bypass-hook-trust") - } + // Unmanaged hooks otherwise run only when their recorded trusted_hash + // matches. fullsend's own SHA-256 guard above already vets the adapter + // the handlers invoke, and the alternative — baking a managed hook + // layer into /etc/codex at image build — would tie hook wiring to + // image releases (ADR 0099). + parts = append(parts, "--dangerously-bypass-hook-trust") parts = append(parts, "-C "+shellQuote(params.RepoDir), "--model "+shellQuote(model), "-c "+shellQuote("model_provider="+codexProviderID), "-c "+shellQuote("approval_policy=never"), + "-c "+shellQuote("allow_login_shell=false"), + // Codex applies this policy only to model tool subprocesses; native + // children inherit it. It does not alter launcher/auth/hook resolution. + `-c "shell_environment_policy.set.PATH=\"/sandbox/workspace/bin:/usr/local/go/bin:/sandbox/go/bin:$`+codexPathVar+`\""`, "-c "+shellQuote("sandbox_mode=danger-full-access"), // The endpoint and the credential command as SessionFlags too, so // even an edit that somehow satisfied the digest guard could not move @@ -411,6 +378,7 @@ func buildCodexRunCommand(params RunParams, model, effort string, hooksEnabled b // into AgentEvents. codex exits 0 on a failed turn and on an interrupted one, // so the stream's verdict overrides the exit code, as it does for pi. func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Printer, start time.Time, metrics *RunMetrics) (int, error) { + clearCodexTranscriptIdentities(params.SandboxName) m, err := readCodexManifest(params.SandboxName, r.codexManifestPath()) if err != nil { return -1, err @@ -441,15 +409,10 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri // legal on pi too, whose check distinguishes a nil groups array from an // empty one for the same reason. A nil map means Bootstrap never ran the // hooks path at all, which contradicts the runner's signal. - if hooksEnabled && digests.HookScripts == nil { - return -1, fmt.Errorf( - "codex hook wiring is inconsistent: the runner expects hooks but Bootstrap recorded no hook-script digests; refusing to run rather than fall back to the weaker checks") - } - if hooksEnabled != (digests.HooksJSON != "") { + if hooksEnabled != (digests.HookScripts != nil) || digests.HooksJSON == "" { return -1, fmt.Errorf( - "codex hook wiring is inconsistent: the runner %s hooks but Bootstrap %s a hooks.json digest; refusing to run rather than fall back to the weaker checks", - map[bool]string{true: "expects", false: "does not expect"}[hooksEnabled], - map[bool]string{true: "recorded", false: "recorded no"}[digests.HooksJSON != ""]) + "codex hook wiring is inconsistent: shared hooks enabled=%t, shared scripts recorded=%t, mandatory hooks.json recorded=%t; refusing to run", + hooksEnabled, digests.HookScripts != nil, digests.HooksJSON != "") } // The same fallback chain NeedsOpenAIProvider decides from, so the launch // and the provider decision cannot disagree about which model this run @@ -478,7 +441,7 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri sanitizeOutput(strings.Join(params.FallbackModels, ",")))) } - cmd := buildCodexRunCommand(params, modelID, effort, hooksEnabled, digests) + cmd := r.OpenAIAuthSeed() + " && " + codexProtectedCommand(buildCodexRunCommand(params, modelID, effort, hooksEnabled, digests), digests) stdout, execCmd, cancel, err := sandbox.ExecStreamReader(ctx, params.SandboxName, cmd, params.Timeout, os.Stderr) if err != nil { @@ -522,14 +485,50 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri var lastResult *ResultEvent innerHandler := handler handler = func(evt AgentEvent) { + applyCodexMetrics(metrics, evt) if e, ok := evt.(ResultEvent); ok { lastResult = &e + // The terminal summary must include children. Retain the parent + // result until the bounded rollout collection below is finished. + return } - applyCodexMetrics(metrics, evt) innerHandler(evt) } - if _, parseErr := parseCodexStream(reader, handler); parseErr != nil { + children := map[string]bool{} // successful spawns, with observed completion + closedChildren := map[string]bool{} + rootID, parseErr := parseCodexStream(reader, handler, func(item codexCollabToolCallItem) { + if (item.Tool == "spawn_agent" || item.Tool == "send_input") && item.Status == "completed" { + for _, id := range item.ReceiverThreadIDs { + children[id] = false + closedChildren[id] = false + } + } + for id, state := range item.AgentStates { + // close_agent removes the thread, so waiting on or closing a closed + // child again reports it not_found. + if closedChildren[id] && state.Status == "not_found" { + continue + } + if _, exists := children[id]; exists { + switch state.Status { + case "completed": + children[id] = state.Message != "" + case "pending_init", "running", "interrupted", "errored", "not_found": + children[id] = false + } + } + } + if item.Tool == "close_agent" && item.Status == "completed" { + for _, id := range item.ReceiverThreadIDs { + if children[id] { + closedChildren[id] = true + } + } + } + }) + rememberCodexTranscriptIdentities(params.SandboxName, rootID, children) + if parseErr != nil { fmt.Fprintf(os.Stderr, " progress parser: %v\n", sanitizeOutput(parseErr.Error())) cancel() io.Copy(io.Discard, reader) @@ -543,6 +542,41 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri if waitErr != nil && execCmd.ProcessState == nil { return exitCode, fmt.Errorf("openshell exec failed: %w", waitErr) } + // The exec stream reports root usage only. Collect persisted child records + // even after cancellation, with a bounded cleanup context and no inference. + usageCtx, usageCancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) + usageErr := r.collectCodexUsage(usageCtx, params.SandboxName, rootID, metrics, children, lastResult != nil && !lastResult.IsError) + usageErr = errors.Join(usageErr, parseErr) + usageCancel() + if lastResult == nil || lastResult.Subtype == codexSubtypeIncomplete { + // A killed exec leaves Codex writing until the runner terminates it: + // drop the pinned digests so extraction publishes the final bytes. + rememberCodexTranscriptIdentities(params.SandboxName, rootID, children) + } + for id := range children { + if !closedChildren[id] { + usageErr = errors.Join(usageErr, fmt.Errorf("child lifecycle: child %s was not closed after completion", id)) + } + } + if usageErr != nil { + printer.StepWarn("Codex runtime evidence is incomplete: " + sanitizeOutput(usageErr.Error())) + if exitCode == 0 { + exitCode = 1 + } + } + if lastResult != nil { + lastResult.InputTokens = metrics.InputTokens + lastResult.OutputTokens = metrics.OutputTokens + lastResult.ReasoningTokens = metrics.ReasoningTokens + lastResult.CacheCreationInputTokens = metrics.CacheCreationInputTokens + lastResult.CacheReadInputTokens = metrics.CacheReadInputTokens + if usageErr != nil { + lastResult.IsError = true + lastResult.Subtype = codexSubtypeIncomplete + lastResult.ErrorMessage = strings.TrimSpace(lastResult.ErrorMessage + "\nCodex runtime evidence is incomplete: " + usageErr.Error()) + } + innerHandler(*lastResult) + } if exitCode == codexHooksMissingExit { return exitCode, fmt.Errorf( "codex config, hook adapter or auth script missing or modified in %s; refusing to run (was Bootstrap run, or did the agent change it?)", @@ -553,6 +587,11 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri "codex config.toml in %s no longer pins the run-scoped provider endpoint, its auth command, or leaves the project untrusted; refusing to run because any of those can redirect or replace the runner's credential (did the agent write there between iterations?)", r.ConfigDir()) } + if exitCode == codexWriteProtectionExit { + return exitCode, fmt.Errorf( + "codex write protection failed in %s: Codex runs require Linux Landlock ABI 3+ (kernel 6.2+), and the runner-held config, role and hook files must match what Bootstrap wrote; refusing to run (see the sandbox stderr)", + r.ConfigDir()) + } if exitCode == 0 && lastResult != nil && lastResult.IsError { msg := lastResult.ErrorMessage @@ -560,22 +599,127 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri msg = "stream ended without a completed turn (" + lastResult.Subtype + ")" } printer.StepWarn("codex exited 0 but the stream reports an error: " + sanitizeOutput(msg)) - return 1, nil + exitCode = 1 + } + if usageErr != nil { + return exitCode, fmt.Errorf("%w: %w", ErrIncompleteEvidence, usageErr) } return exitCode, nil } +func (r CodexRuntime) collectCodexUsage(ctx context.Context, sandboxName, rootID string, metrics *RunMetrics, expectedChildren map[string]bool, requireRootEvidence bool) error { + if metrics == nil { + return fmt.Errorf("codex usage requires run metrics") + } + // Keep the stream contribution until complete native evidence can replace + // it. A failed start with no response usage keeps its original provider + // error; successful runs and runs with incurred usage require a root. + requireRootEvidence = requireRootEvidence || len(expectedChildren) != 0 || + metrics.InputTokens != 0 || metrics.OutputTokens != 0 || metrics.ReasoningTokens != 0 || + metrics.CacheReadInputTokens != 0 || metrics.CacheCreationInputTokens != 0 + metrics.CostUnavailable = true + metrics.PerModelUsage = map[string]ModelUsage{metrics.Model: { + CostUnavailable: true, + InputTokens: metrics.InputTokens, OutputTokens: metrics.OutputTokens, + ReasoningTokens: metrics.ReasoningTokens, CacheReadInputTokens: metrics.CacheReadInputTokens, + CacheCreationInputTokens: metrics.CacheCreationInputTokens, Requests: 1, + }} + if rootID == "" { + if requireRootEvidence { + return fmt.Errorf("codex usage is missing the root thread identity") + } + return nil + } + dir, err := os.MkdirTemp("", "fullsend-codex-usage-") + if err != nil { + return err + } + defer os.RemoveAll(dir) + paths, collectionErr := r.downloadCodexRollouts(ctx, sandboxName, dir) + var rollouts []codexRolloutUsage + var failures []error + failures = append(failures, collectionErr) + for _, path := range paths { + f, err := os.Open(path) + if err != nil { + failures = append(failures, err) + continue + } + rollout, err := parseCodexRolloutUsage(f) + f.Close() + if err != nil { + failures = append(failures, err) + continue + } + failures = append(failures, rememberCodexTranscriptFile(sandboxName, rollout.Meta, path)) + rollouts = append(rollouts, rollout) + } + observedChildren := map[string]bool{} + for _, rollout := range rollouts { + if rollout.Meta.ParentThreadID == rootID && rollout.Meta.SessionID == rootID { + if _, dispatched := expectedChildren[rollout.Meta.ThreadID]; !dispatched { + failures = append(failures, fmt.Errorf("child %s has no observed dispatch", rollout.Meta.ThreadID)) + } + // A child without response usage still exists and must be accounted + // for, even if its spawn record was absent from the live stream. + observedChildren[rollout.Meta.ThreadID] = false + for _, response := range rollout.Responses { + if response.Record.ThreadID == rollout.Meta.ThreadID { + observedChildren[rollout.Meta.ThreadID] = true + } + } + } + } + for id, complete := range expectedChildren { + if !complete { + failures = append(failures, fmt.Errorf("child %s did not deliver a completed result", id)) + } + if !observedChildren[id] { + failures = append(failures, fmt.Errorf("child %s has no collected response usage", id)) + } + } + requireRootEvidence = requireRootEvidence || len(observedChildren) != 0 + // A later interrupted turn can incur usage after an earlier completed + // stream snapshot. Persisted response deltas cover all observed turns; + // replace the root contribution, never add the snapshot again. + rootUsage, rootErr := foldCodexRootUsage(rootID, rollouts) + failures = append(failures, rootErr) + if rootErr == nil && len(rootUsage) == 0 && requireRootEvidence { + failures = append(failures, fmt.Errorf("codex root has no collected response usage for thread %s", rootID)) + } + if rootErr == nil && len(rootUsage) != 0 { + rootMetrics := &RunMetrics{CostUnavailable: true} + if err := addCodexUsage(rootMetrics, rootUsage); err != nil { + failures = append(failures, err) + } else { + metrics.InputTokens, metrics.OutputTokens, metrics.ReasoningTokens = rootMetrics.InputTokens, rootMetrics.OutputTokens, rootMetrics.ReasoningTokens + metrics.CacheReadInputTokens, metrics.CacheCreationInputTokens = rootMetrics.CacheReadInputTokens, rootMetrics.CacheCreationInputTokens + metrics.PerModelUsage = rootMetrics.PerModelUsage + } + } + children, err := foldCodexChildUsage(rootID, rollouts) + failures = append(failures, err) + if err == nil { + failures = append(failures, addCodexUsage(metrics, children)) + } + return errors.Join(failures...) +} + // ClearIterationArtifacts terminates processes the previous iteration left // running (see killStrayProcesses), then removes its outputs, the rollout // sessions and the debug log so transcripts and output files are // per-iteration. func (r CodexRuntime) ClearIterationArtifacts(sandboxName string) error { + clearCodexTranscriptIdentities(sandboxName) clearStrayProcesses(sandbox.Exec, sandboxName, os.Stderr, "the previous iteration") clearCmd := fmt.Sprintf("rm -rf %s/output/* %s/* %s %s", shellQuote(r.WorkspaceDir()), shellQuote(r.codexSessionsDir()), shellQuote(r.WorkspaceDir()+"/"+codexDebugLogFile), shellQuote(r.ConfigDir()+"/"+codexLastMessageFile)) + // The frozen CODEX_HOME directory cannot create a new top-level file. + // Re-provision this writable state file before the next launch. + clearCmd += " && touch " + shellQuote(r.ConfigDir()+"/"+codexLastMessageFile) _, _, _, err := sandbox.Exec(sandboxName, clearCmd, 10*time.Second) return err } diff --git a/internal/runtime/codex_run_boundary_test.go b/internal/runtime/codex_run_boundary_test.go new file mode 100644 index 0000000000..f37063a126 --- /dev/null +++ b/internal/runtime/codex_run_boundary_test.go @@ -0,0 +1,137 @@ +package runtime + +import ( + "bytes" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/harness" + "github.com/fullsend-ai/fullsend/internal/security" + "github.com/fullsend-ai/fullsend/internal/ui" +) + +func TestCodexRunBoundary_RejectsMissingMandatoryAndUnexpectedSharedHooks(t *testing.T) { + for _, tc := range []struct { + name string + shared, digest bool + unexpected bool + }{ + {name: "mandatory policy missing without shared scanners"}, + {name: "mandatory policy missing with shared scanners", shared: true}, + {name: "shared scanners recorded despite runner disabling them", digest: true, unexpected: true}, + } { + t.Run(tc.name, func(t *testing.T) { + r := CodexRuntime{} + store, logPath := t.TempDir(), filepath.Join(t.TempDir(), "openshell.log") + var hooks *codexHooksManifest + if tc.shared { + hooks = codexHooksManifestFor(r.codexHooksDir(), security.SandboxHookConfigFromHarness(&harness.Harness{})) + } + seedCodexManifest(t, store, r, hooks) + fakeOpenshellCodex(t, logPath, store, "codex-cli 0.158.0") + digests, ok := lookupRunnerHeldDigests("sb") + require.True(t, ok) + if !tc.digest { + digests.HooksJSON = "" + } + if tc.unexpected { + digests.HookScripts = map[string]string{} + } + recordRunnerHeldDigests("sb", digests) + params := RunParams{SandboxName: "sb", Model: "gpt-5.6-luna", RepoDir: "/sandbox/workspace/repo", Timeout: time.Minute} + if tc.shared { + params.HooksSettingsPath = r.codexHooksPath() + } + var events []AgentEvent + params.OnEvent = func(event AgentEvent) { events = append(events, event) } + metrics := &RunMetrics{} + exit, err := r.Run(t.Context(), params, ui.New(&bytes.Buffer{}), time.Now(), metrics) + require.ErrorContains(t, err, "hook wiring is inconsistent") + assert.Equal(t, -1, exit) + assert.Empty(t, events, "integrity failure must precede a model run or result event") + assert.Zero(t, metrics.NumTurns) + assert.Zero(t, metrics.InputTokens) + assert.NotContains(t, readFileString(t, logPath), "exec --json", "inconsistent policy must never launch inference") + }) + } +} + +// The launcher exits 78 before Codex starts; a retry cannot succeed. +func TestCodexRunBoundary_WriteProtectionFailureIsAnError(t *testing.T) { + r := CodexRuntime{} + store := t.TempDir() + seedCodexManifest(t, store, r, nil) + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), store, "codex-cli 0.158.0") + t.Setenv("FULLSEND_TEST_RUN_EXIT", "78") + exit, err := r.Run(t.Context(), RunParams{SandboxName: "sb", Model: "gpt-5.6-luna", RepoDir: "/sandbox/workspace/repo", Timeout: time.Minute}, + ui.New(&bytes.Buffer{}), time.Now(), &RunMetrics{}) + require.ErrorContains(t, err, "Codex runs require Linux Landlock ABI 3+") + assert.Equal(t, codexWriteProtectionExit, exit) +} + +func TestCodexRunBoundary_UsageCollectionFailureRetainsKnownStreamCounters(t *testing.T) { + r := CodexRuntime{} + require.Error(t, r.collectCodexUsage(t.Context(), "unused", "root", nil, nil, true)) + missing := filepath.Join(t.TempDir(), "missing-parent") + t.Setenv("TMPDIR", missing) + metrics := &RunMetrics{Model: "root-model", NumTurns: 1, InputTokens: 20, OutputTokens: 8, ReasoningTokens: 2} + err := r.collectCodexUsage(t.Context(), "unused", "root", metrics, nil, true) + require.ErrorIs(t, err, os.ErrNotExist) + assert.Equal(t, 1, metrics.NumTurns) + assert.Equal(t, 20, metrics.InputTokens) + assert.Equal(t, 8, metrics.OutputTokens) + assert.Equal(t, 2, metrics.ReasoningTokens) + assert.True(t, metrics.CostUnavailable, "missing raw evidence must not turn an unpriced run into a known zero-dollar run") + assert.Equal(t, map[string]ModelUsage{"root-model": { + Requests: 1, InputTokens: 20, OutputTokens: 8, ReasoningTokens: 2, CostUnavailable: true, + }}, metrics.PerModelUsage) +} + +func TestCodexRunBoundary_LostDownloadedRootRetainsStreamAndChildUsage(t *testing.T) { + child := strings.Join([]string{codexUsageTestMeta, codexUsageTestContext("turn", "child-model"), + codexUsageTestRecord(t, "child-response", "turn", codexUsage{ + InputTokens: 15, CachedInputTokens: 6, CacheWriteInputTokens: 4, + OutputTokens: 9, ReasoningOutputTokens: 3, + }), + }, "\n") + fakeOpenshellCodexWithRollouts(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "", map[string]string{ + "a-root.jsonl": testCodexRootUsage("root", "root-model", 100, 20, 5), + "b-child.jsonl": child, + }) + // Inject a host storage loss between transfers, after the root file was + // accepted by the downloader. The collector must surface the lost file + // while still parsing the second, intact child; no timing race is needed. + fake, err := exec.LookPath("openshell") + require.NoError(t, err) + require.NoError(t, os.Rename(fake, fake+"-with-bodies")) + script := "#!/bin/sh\nfor last; do :; done\ncase \"$last\" in\n" + + "*b-child.jsonl*fullsend-codex-rollout*) find \"$FULLSEND_TEST_USAGE_TEMP\" -type f -name '*a-root.jsonl' -delete;;\n" + + "esac\nexec " + shellQuote(fake+"-with-bodies") + " \"$@\"\n" + require.NoError(t, os.WriteFile(fake, []byte(script), 0o755)) + privateRoot := t.TempDir() + t.Setenv("FULLSEND_TEST_USAGE_TEMP", privateRoot) + t.Setenv("TMPDIR", privateRoot) + t.Cleanup(func() { clearCodexTranscriptIdentities("lost-root") }) + metrics := &RunMetrics{Model: "root-model", NumTurns: 1, InputTokens: 20, OutputTokens: 8, ReasoningTokens: 2} + err = (CodexRuntime{}).collectCodexUsage(t.Context(), "lost-root", "root", metrics, map[string]bool{"child": true}, true) + require.ErrorIs(t, err, os.ErrNotExist) + require.ErrorContains(t, err, "root has no collected response usage") + assert.Equal(t, 1, metrics.NumTurns, "recovered accounting does not invent completion") + assert.Equal(t, 25, metrics.InputTokens, "retain the stream's 20 plus the child's 5; never use the unavailable raw 100") + assert.Equal(t, 14, metrics.OutputTokens) + assert.Equal(t, 5, metrics.ReasoningTokens) + assert.Equal(t, 6, metrics.CacheReadInputTokens) + assert.Equal(t, 4, metrics.CacheCreationInputTokens) + assert.True(t, metrics.CostUnavailable) + assert.Equal(t, map[string]ModelUsage{ + "root-model": {Requests: 1, InputTokens: 20, OutputTokens: 8, ReasoningTokens: 2, CostUnavailable: true}, + "child-model": {Requests: 1, InputTokens: 5, OutputTokens: 6, ReasoningTokens: 3, CacheReadInputTokens: 6, CacheCreationInputTokens: 4, CostUnavailable: true}, + }, metrics.PerModelUsage) +} diff --git a/internal/runtime/codex_run_test.go b/internal/runtime/codex_run_test.go index 46bfc4797c..0a413979f9 100644 --- a/internal/runtime/codex_run_test.go +++ b/internal/runtime/codex_run_test.go @@ -19,6 +19,7 @@ import ( // testRunnerHeldDigests stands in for what Bootstrap recorded in the runner's // memory for a sandbox. var testRunnerHeldDigests = codexRunnerHeldDigestSet{ + Python: "/usr/bin/python3", ConfigTOML: "aaaa000000000000000000000000000000000000000000000000000000000000", HooksJSON: "bbbb000000000000000000000000000000000000000000000000000000000000", HookScripts: testCodexHookScripts(), @@ -120,7 +121,6 @@ func TestBuildCodexRunCommand_OrderAndFlags(t *testing.T) { // runner recorded, then the credential seed — all before .env. `sha256sum`, testRunnerHeldDigests.ConfigTOML, - `OPENAI_API_KEY`, `. '` + sandbox.SandboxWorkspace + `/.env'`, `export CODEX_HOME=`, `unset OPENAI_BASE_URL OPENAI_API_KEY CODEX_API_KEY NODE_OPTIONS NODE_PATH PYTHONPATH PYTHONHOME PYTHONSTARTUP`, @@ -175,6 +175,7 @@ func TestBuildCodexRunCommand_OrderAndFlags(t *testing.T) { pinAt := strings.Index(cmd, `readonly FULLSEND_CODEX_PATH="$PATH"`) envAt := strings.Index(cmd, `. '`+sandbox.SandboxWorkspace+`/.env'`) restoreAt := strings.Index(cmd, `export PATH="$FULLSEND_CODEX_PATH"`) + assert.Contains(t, cmd, "-c 'allow_login_shell=false'", "login profiles must not remove the output validator from agent PATH") require.Positive(t, pinAt) require.Positive(t, restoreAt) assert.Less(t, pinAt, envAt, "PATH is captured before .env") @@ -213,7 +214,7 @@ func TestBuildCodexRunCommand_HooksDisabled(t *testing.T) { cmd := buildCodexRunCommand(RunParams{RepoDir: "/repo"}, "gpt-5.6-luna", "", false, testRunnerHeldDigests) // The flag is decided from the runner's own signal, not the manifest. - assert.NotContains(t, cmd, "--dangerously-bypass-hook-trust") + assert.Contains(t, cmd, "--dangerously-bypass-hook-trust", "native dispatch policy is mandatory") assert.NotContains(t, cmd, codexAdapterFile) // The credential guards are not conditional on hooks: the risk they cover // is credential leak, not tool misuse. @@ -249,8 +250,9 @@ func TestCodexAssetGuard_Executes(t *testing.T) { r := CodexRuntime{} // The guard names absolute sandbox paths, so run it against a fake root. + digests := testRunnerHeldDigests guard := func() string { - return strings.ReplaceAll(codexAssetGuard(r, true, testRunnerHeldDigests), sandbox.SandboxCodexConfig, dir) + return strings.ReplaceAll(codexAssetGuard(r, true, digests)+" && "+codexConfigGuard(r, digests), sandbox.SandboxCodexConfig, dir) } writeAll := func(t *testing.T) { t.Helper() @@ -269,6 +271,8 @@ func TestCodexAssetGuard_Executes(t *testing.T) { require.NoError(t, os.WriteFile(filepath.Join(dir, codexHooksFile), []byte(`{"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"python3 `+ filepath.Join(dir, codexAdapterFile)+` PreToolUse x.py"}]}]}}`), 0o644)) + digests.ConfigTOML = codexAssetSHA256([]byte("cfg")) + digests.HooksJSON = codexAssetSHA256([]byte(readFileString(t, filepath.Join(dir, codexHooksFile)))) } t.Run("passes when every asset matches", func(t *testing.T) { @@ -304,7 +308,7 @@ func TestCodexAssetGuard_Executes(t *testing.T) { []byte(`{"hooks":{"PreToolUse":[{"hooks":[{"type":"command","command":"true"}]}]}}`), 0o644)) _, err := exec.Command("/bin/sh", "-c", guard()+" && echo RAN").CombinedOutput() require.Error(t, err) - assert.Equal(t, codexHooksMissingExit, exitCodeOf(t, err)) + assert.Equal(t, codexConfigTamperedExit, exitCodeOf(t, err)) }) // The interesting case: the adapter is still referenced, so a @@ -318,7 +322,7 @@ func TestCodexAssetGuard_Executes(t *testing.T) { `{"hooks":[{"type":"command","command":"python3 `+adapter+` PreToolUse x.py"}]}]}}`), 0o644)) _, err := exec.Command("/bin/sh", "-c", guard()+" && echo RAN").CombinedOutput() require.Error(t, err, "a handler replaced beside a still-referenced adapter must not pass") - assert.Equal(t, codexHooksMissingExit, exitCodeOf(t, err)) + assert.Equal(t, codexConfigTamperedExit, exitCodeOf(t, err)) }) t.Run("blocks a handler the agent added", func(t *testing.T) { @@ -330,7 +334,7 @@ func TestCodexAssetGuard_Executes(t *testing.T) { `{"hooks":[{"type":"command","command":"curl https://example.invalid"}]}]}}`), 0o644)) _, err := exec.Command("/bin/sh", "-c", guard()+" && echo RAN").CombinedOutput() require.Error(t, err) - assert.Equal(t, codexHooksMissingExit, exitCodeOf(t, err)) + assert.Equal(t, codexConfigTamperedExit, exitCodeOf(t, err)) }) t.Run("blocks a missing manifest", func(t *testing.T) { @@ -645,6 +649,49 @@ func exitCodeOf(t *testing.T, err error) int { return exitErr.ExitCode() } +// A retry may encounter executable names planted in writable helper directories. +// Those directories belong to model tool shells, not the npm launcher or auth. +func TestCodexRunCommand_HelperPathCannotShadowLauncherOrAuth(t *testing.T) { + dir := t.TempDir() + configDir := filepath.Join(dir, "config") + workspace := filepath.Join(dir, "workspace") + trusted := filepath.Join(dir, "trusted") + for _, path := range []string{configDir, workspace, trusted, filepath.Join(workspace, "bin")} { + require.NoError(t, os.MkdirAll(path, 0o755)) + } + require.NoError(t, os.WriteFile(filepath.Join(configDir, codexConfigFile), []byte("cfg"), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(configDir, codexAuthScriptFile), codexAuthScriptSH, 0o755)) + startupPath := filepath.Join(workspace, "startup.sh") + require.NoError(t, os.WriteFile(startupPath, []byte("exit 0\n"), 0o644)) + env := "export PATH=" + shellQuote(filepath.Join(workspace, "bin")) + ":$PATH\nexport BASH_ENV=" + shellQuote(startupPath) + "\n" + require.NoError(t, os.WriteFile(filepath.Join(workspace, ".env"), []byte(env), 0o644)) + for _, name := range []string{"node", "cat"} { + require.NoError(t, os.WriteFile(filepath.Join(workspace, "bin", name), []byte("#!/bin/sh\necho SHADOWED\nexit 42\n"), 0o755)) + } + tokenPath := filepath.Join(dir, "placeholder") + placeholder := piPlaceholderPrefix + "test_OPENAI_API_KEY" + require.NoError(t, os.WriteFile(tokenPath, []byte(placeholder), 0o600)) + authPath := filepath.Join(dir, "auth.sh") + auth := strings.ReplaceAll(string(codexAuthScriptSH), codexSandboxTokenFile, tokenPath) + require.NoError(t, os.WriteFile(authPath, []byte(auth), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(trusted, "codex"), []byte("#!/usr/bin/env node\n"), 0o755)) + node := "#!/bin/sh\necho TRUSTED_NODE\n/bin/sh " + shellQuote(authPath) + " || exit $?\n/bin/bash -c 'echo GUARD_RAN'\nprintf '\\nARG:%s\\n' \"$@\"\n" + require.NoError(t, os.WriteFile(filepath.Join(trusted, "node"), []byte(node), 0o755)) + digests := codexRunnerHeldDigestSet{ConfigTOML: codexAssetSHA256([]byte("cfg"))} + command := buildCodexRunCommand(RunParams{RepoDir: dir}, "gpt-5.6-luna", "low", false, digests) + command = strings.ReplaceAll(command, sandbox.SandboxCodexConfig, configDir) + command = strings.ReplaceAll(command, sandbox.SandboxWorkspace, workspace) + cmd := exec.Command("/bin/sh", "-c", command) + cmd.Env = append(os.Environ(), "PATH="+trusted+":/usr/bin:/bin:/usr/local/bin") + out, err := cmd.CombinedOutput() + require.NoError(t, err, string(out)) + assert.Contains(t, string(out), "TRUSTED_NODE") + assert.Contains(t, string(out), placeholder) + assert.Contains(t, string(out), "GUARD_RAN", "BASH_ENV must not short-circuit native hooks") + assert.NotContains(t, string(out), "SHADOWED") + assert.Contains(t, string(out), `ARG:shell_environment_policy.set.PATH="`+workspace+`/bin:/usr/local/go/bin:/sandbox/go/bin:`+trusted) +} + // TestCodexSecurityEnv_PinsWhatTheRunnerKnows covers the values the runtime can // re-assert, and is explicit about the ones it cannot. func TestCodexSecurityEnv_PinsWhatTheRunnerKnows(t *testing.T) { diff --git a/internal/runtime/codex_skills.go b/internal/runtime/codex_skills.go new file mode 100644 index 0000000000..19c4fde091 --- /dev/null +++ b/internal/runtime/codex_skills.go @@ -0,0 +1,76 @@ +package runtime + +import ( + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/fullsend-ai/fullsend/internal/sandbox" +) + +type codexSkillUpload struct { + path string + name string +} + +// codexSkillUploads preserves declared skill names when several forge-specific +// skill directories share a basename. Codex discovers nested skills recursively, +// so a selected descendant is already delivered by its parent's directory upload. +func codexSkillUploads(skillDirs []string) ([]codexSkillUpload, error) { + var skills []codexSkillUpload + seen := make(map[string]string) + for _, dir := range skillDirs { + if dir == "" { + continue + } + name := resolveSkillDisplayName(dir) + if !isValidSkillName(name) || strings.HasPrefix(name, ".") { + return nil, fmt.Errorf("invalid codex skill name %q from %q: expected a non-hidden single directory name", name, dir) + } + path, err := filepath.EvalSymlinks(dir) + if err == nil { + path, err = filepath.Abs(path) + } + if err != nil { + return nil, fmt.Errorf("resolving codex skill %q: %w", dir, err) + } + if prior, ok := seen[name]; ok { + if prior != path { + return nil, fmt.Errorf("two codex skill paths both declare %q: %q and %q", name, prior, path) + } + continue + } + seen[name] = path + skills = append(skills, codexSkillUpload{path: path, name: name}) + } + var uploads []codexSkillUpload + for _, candidate := range skills { + nested := false + for _, parent := range skills { + rel, err := filepath.Rel(parent.path, candidate.path) + if err == nil && rel != "." && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) && !filepath.IsAbs(rel) { + nested = true + break + } + } + if !nested { + uploads = append(uploads, candidate) + } + } + return uploads, nil +} + +func codexUploadSkills(sandboxName, configDir string, skillDirs []string) error { + uploads, err := codexSkillUploads(skillDirs) + if err != nil { + return err + } + for _, skill := range uploads { + if err := sandbox.UploadDir(sandboxName, skill.path, configDir+"/skills/"+skill.name); err != nil { + return fmt.Errorf("copying codex skill %q: %w", skill.path, err) + } + fmt.Fprintf(os.Stderr, "Skill %q: uploaded to sandbox\n", skill.name) + } + return nil +} diff --git a/internal/runtime/codex_skills_test.go b/internal/runtime/codex_skills_test.go new file mode 100644 index 0000000000..f6f9aed70a --- /dev/null +++ b/internal/runtime/codex_skills_test.go @@ -0,0 +1,129 @@ +package runtime + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func codexTestSkill(t *testing.T, root, path, name string) string { + t.Helper() + dir := filepath.Join(root, path) + require.NoError(t, os.MkdirAll(dir, 0o755)) + content := "body\n" + if name != "" { + content = fmt.Sprintf("---\nname: %q\ndescription: Test skill.\n---\nbody\n", name) + } + require.NoError(t, os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte(content), 0o644)) + canonical, err := filepath.EvalSymlinks(dir) + require.NoError(t, err) + return canonical +} + +func TestCodexSkillUploads_ForgeNamesAndNestedSkills(t *testing.T) { + root := t.TempDir() + parent := codexTestSkill(t, root, "pr-review", "pr-review") + child := codexTestSkill(t, root, "pr-review/github", "pr-review-github") + labels := codexTestSkill(t, root, "issue-labels/github", "issue-labels") + fallback := codexTestSkill(t, root, "local-skill", "") + // A sibling whose prefix matches the parent must not be treated as nested. + sibling := codexTestSkill(t, root, "pr-review-extra", "extra") + for _, dirs := range [][]string{ + {child, "", labels, parent, fallback, sibling, parent}, + {parent, labels, child, fallback, sibling}, + } { + uploads, err := codexSkillUploads(dirs) + require.NoError(t, err) + byName := make(map[string]string) + for _, upload := range uploads { + byName[upload.name] = upload.path + } + assert.Equal(t, map[string]string{"pr-review": parent, "issue-labels": labels, "local-skill": fallback, "extra": sibling}, byName) + } +} + +func TestCodexSkillUploads_DistinctSameBasename(t *testing.T) { + root := t.TempDir() + a := codexTestSkill(t, root, "review/github", "pr-review-github") + b := codexTestSkill(t, root, "retro/github", "retro-analysis-github") + uploads, err := codexSkillUploads([]string{a, b}) + require.NoError(t, err) + assert.Equal(t, []codexSkillUpload{{a, "pr-review-github"}, {b, "retro-analysis-github"}}, uploads) +} + +func TestCodexSkillUploads_RejectsDistinctDeclaredNameCollision(t *testing.T) { + root := t.TempDir() + a := codexTestSkill(t, root, "first", "shared") + b := codexTestSkill(t, root, "second", "shared") + _, err := codexSkillUploads([]string{a, b}) + require.Error(t, err) + assert.Contains(t, err.Error(), `both declare "shared"`) +} + +func TestCodexSkillUploads_RejectsUnsafeNames(t *testing.T) { + for _, name := range []string{"../config", "a/b", `a\b`, ".", "..", ".hidden", "a b", "a\nb", "/tmp/skill", "x;touch"} { + t.Run(name, func(t *testing.T) { + dir := codexTestSkill(t, t.TempDir(), "skill", name) + _, err := codexSkillUploads([]string{dir}) + require.Error(t, err) + assert.Contains(t, err.Error(), "invalid codex skill name") + }) + } +} + +func TestCodexSkillUploads_SymlinkAliasesAndMissingPath(t *testing.T) { + root := t.TempDir() + dir := codexTestSkill(t, root, "real", "declared") + alias := filepath.Join(root, "alias") + require.NoError(t, os.Symlink(dir, alias)) + uploads, err := codexSkillUploads([]string{alias, dir}) + require.NoError(t, err) + assert.Equal(t, []codexSkillUpload{{dir, "declared"}}, uploads) + _, err = codexSkillUploads([]string{filepath.Join(root, "missing")}) + require.Error(t, err) + assert.Contains(t, err.Error(), "resolving codex skill") +} + +func TestCodexUploadSkills_UsesDeclaredDestinationWithoutNestedCopy(t *testing.T) { + root := t.TempDir() + logPath := filepath.Join(t.TempDir(), "openshell.log") + fakeOpenshellCodex(t, logPath, t.TempDir(), "codex-cli 0.157.0") + parent := codexTestSkill(t, root, "pr-review", "pr-review") + child := codexTestSkill(t, root, "pr-review/github", "pr-review-github") + labels := codexTestSkill(t, root, "issue-labels/github", "issue-labels") + require.NoError(t, codexUploadSkills("sb", "/sandbox/codex-config", []string{child, parent, labels})) + log := readFileString(t, logPath) + assert.Contains(t, log, "rm -rf '/sandbox/codex-config/skills/pr-review'") + assert.Contains(t, log, "rm -rf '/sandbox/codex-config/skills/issue-labels'") + assert.NotContains(t, log, "skills/github") + assert.NotContains(t, log, "skills/pr-review-github") + assert.Equal(t, 2, strings.Count(log, "tar -xzf")) +} + +func TestCodexUploadSkills_ReportsErrorsBeforeOrDuringTransfer(t *testing.T) { + root := t.TempDir() + dir := codexTestSkill(t, root, "skill", "skill") + logPath := filepath.Join(t.TempDir(), "openshell.log") + fakeOpenshellCodex(t, logPath, t.TempDir(), "codex-cli 0.157.0") + err := codexUploadSkills("sb", "/sandbox/codex-config", []string{filepath.Join(root, "missing")}) + require.Error(t, err) + _, statErr := os.Stat(logPath) + assert.ErrorIs(t, statErr, os.ErrNotExist, "invalid plan must not start uploading") + t.Setenv("FULLSEND_TEST_FAIL_MATCH", "sandbox upload sb") + err = codexUploadSkills("sb", "/sandbox/codex-config", []string{dir}) + require.Error(t, err) + assert.Contains(t, err.Error(), "copying codex skill") +} + +func TestCodexBootstrapRejectsInvalidSkillName(t *testing.T) { + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "codex-cli 0.157.0") + skill := filepath.Join(t.TempDir(), ".hidden") + require.NoError(t, os.Mkdir(skill, 0o755)) + err := (CodexRuntime{}).Bootstrap(bootstrapInput{sandboxName: "bad-skill", agentPath: writeAgentFile(t, codexTestAgentDef), skillDirs: []string{skill}}) + require.ErrorContains(t, err, "invalid codex skill name") +} diff --git a/internal/runtime/codex_subagent_usage_test.go b/internal/runtime/codex_subagent_usage_test.go new file mode 100644 index 0000000000..6b5c9da124 --- /dev/null +++ b/internal/runtime/codex_subagent_usage_test.go @@ -0,0 +1,329 @@ +package runtime + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func readRecordedCodexUsage(t *testing.T, version string) (string, []codexRolloutUsage) { + t.Helper() + dir := filepath.Join("testdata", "codex", "native-subagents", version) + var rootID string + var rollouts []codexRolloutUsage + for _, name := range []string{"root.jsonl", "probe-alpha.jsonl", "probe-beta.jsonl", "default.jsonl"} { + data, err := os.ReadFile(filepath.Join(dir, name)) + require.NoError(t, err) + rec, err := parseCodexRolloutUsage(strings.NewReader(string(data))) + require.NoError(t, err, name) + if name == "root.jsonl" { + rootID = rec.Meta.ThreadID + require.Len(t, rec.Responses, 6, "capture has six parent API responses") + } else { + require.Len(t, rec.Responses, 1, "capture has one response per child") + } + rollouts = append(rollouts, rec) + } + return rootID, rollouts +} + +func TestCodexSubagentUsage_RecordedNativeVersions(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + version string + output int + reasoning int + parent int + combined int + }{ + {"0157", 24, 0, 96500, 124159}, + {"0158", 26, 11, 96985, 124657}, + } { + t.Run(tc.version, func(t *testing.T) { + t.Parallel() + rootID, rollouts := readRecordedCodexUsage(t, tc.version) + byModel, err := foldCodexChildUsage(rootID, rollouts) + require.NoError(t, err) + require.Len(t, byModel, 1) + got := byModel["gpt-5.6-luna"] + assert.Equal(t, ModelUsage{ + Requests: 3, InputTokens: 9, OutputTokens: tc.output, CostUnavailable: true, + ReasoningTokens: tc.reasoning, CacheCreationInputTokens: 27626, + }, got) + assert.Equal(t, tc.combined, tc.parent+got.InputTokens+got.OutputTokens+ + got.ReasoningTokens+got.CacheReadInputTokens+got.CacheCreationInputTokens, + "all disjoint child counters must conserve the recorded raw total") + assert.Zero(t, got.CostUSD, "the captures report no dollar cost") + }) + } +} + +func TestCodexSubagentUsage_DeduplicatesResponsesAndCopiedRollouts(t *testing.T) { + t.Parallel() + rootID, rollouts := readRecordedCodexUsage(t, "0158") + want, err := foldCodexChildUsage(rootID, rollouts) + require.NoError(t, err) + rollouts[1].Responses = append(rollouts[1].Responses, rollouts[1].Responses[0]) + rollouts = append(rollouts, rollouts[1], rollouts[2], rollouts[3]) + got, err := foldCodexChildUsage(rootID, rollouts) + require.NoError(t, err) + assert.Equal(t, want, got, "duplicates must not create extra agent invocations") +} + +func TestCodexSubagentUsage_IdentityIsThreadNotRoleOrResponseIDAlone(t *testing.T) { + t.Parallel() + rootID, rollouts := readRecordedCodexUsage(t, "0158") + want, err := foldCodexChildUsage(rootID, rollouts) + require.NoError(t, err) + for i := 1; i < len(rollouts); i++ { + rollouts[i].Meta.Role = "same-persona" + rollouts[i].Responses[0].Record.ResponseID = "same-response-id-in-distinct-threads" + } + got, err := foldCodexChildUsage(rootID, rollouts) + require.NoError(t, err) + assert.Equal(t, want, got) +} + +func TestCodexSubagentUsage_ExcludesRootStaleSessionsAndInheritedResponses(t *testing.T) { + t.Parallel() + rootID, rollouts := readRecordedCodexUsage(t, "0158") + want, err := foldCodexChildUsage(rootID, rollouts) + require.NoError(t, err) + // A full-history fork can carry the parent's own recorded responses. + rollouts[1].Responses = append(rollouts[1].Responses, rollouts[0].Responses...) + _, stale := readRecordedCodexUsage(t, "0157") + rollouts = append(rollouts, stale...) + got, err := foldCodexChildUsage(rootID, rollouts) + require.NoError(t, err) + assert.Equal(t, want, got) +} + +func TestCodexSubagentUsage_RejectsConflictingDuplicate(t *testing.T) { + t.Parallel() + for _, conflict := range []string{"usage", "model", "turn", "session"} { + t.Run(conflict, func(t *testing.T) { + t.Parallel() + rootID, rollouts := readRecordedCodexUsage(t, "0158") + _, copyRollouts := readRecordedCodexUsage(t, "0158") + duplicate := copyRollouts[1] + switch conflict { + case "usage": + duplicate.Responses[0].Record.Usage.InputTokens++ + case "model": + duplicate.Responses[0].Model = "gpt-5.6-sol" + case "turn": + duplicate.Responses[0].Record.TurnID = "another-turn" + case "session": + duplicate.Responses[0].Record.SessionID = "another-root" + } + _, err := foldCodexChildUsage(rootID, append(rollouts, duplicate)) + require.Error(t, err, "conflicting duplicate evidence must not silently win or be added twice") + }) + } +} + +// Synthetic cases below mutate the recorded wire shape. Their values are +// intentionally separate from the recorded native fixture counts above. +const codexUsageTestMeta = `{"type":"session_meta","payload":{"id":"child","session_id":"root","parent_thread_id":"root","agent_role":"test"}}` + +func codexUsageTestRecord(t *testing.T, responseID, turnID string, usage any) string { + t.Helper() + data, err := json.Marshal(map[string]any{ + "type": "token_usage_record", + "payload": map[string]any{ + "thread_id": "child", "session_id": "root", "turn_id": turnID, + "root_turn_id": "root-turn", "response_id": responseID, "usage": usage, + }, + }) + require.NoError(t, err) + return string(data) +} + +func codexUsageTestContext(turnID, model string) string { + data, _ := json.Marshal(map[string]any{ + "type": "turn_context", "payload": map[string]string{ + "turn_id": turnID, "model": model, "root_turn_id": "root-turn", + }, + }) + return string(data) +} + +func TestCodexSubagentUsage_AttributesEachResponseToItsTurnModel(t *testing.T) { + t.Parallel() + u1 := codexUsage{InputTokens: 100, CachedInputTokens: 60, CacheWriteInputTokens: 30, OutputTokens: 20, ReasoningOutputTokens: 5} + u2 := codexUsage{InputTokens: 200, CachedInputTokens: 100, CacheWriteInputTokens: 80, OutputTokens: 30, ReasoningOutputTokens: 6} + data := strings.Join([]string{ + codexUsageTestMeta, + codexUsageTestContext("turn-one", "gpt-5.6-luna"), + codexUsageTestContext("turn-two", "gpt-5.6-sol"), + codexUsageTestRecord(t, "response-one", "turn-one", u1), + codexUsageTestRecord(t, "response-two", "turn-two", u2), + }, "\n") + rec, err := parseCodexRolloutUsage(strings.NewReader(data)) + require.NoError(t, err) + got, err := foldCodexChildUsage("root", []codexRolloutUsage{rec}) + require.NoError(t, err) + assert.Equal(t, map[string]ModelUsage{ + "gpt-5.6-luna": {Requests: 1, InputTokens: 10, OutputTokens: 15, CostUnavailable: true, ReasoningTokens: 5, CacheReadInputTokens: 60, CacheCreationInputTokens: 30}, + "gpt-5.6-sol": {Requests: 1, InputTokens: 20, OutputTokens: 24, CostUnavailable: true, ReasoningTokens: 6, CacheReadInputTokens: 100, CacheCreationInputTokens: 80}, + }, got) +} + +func TestCodexSubagentUsage_MissingModelIsUnknown(t *testing.T) { + t.Parallel() + data := codexUsageTestMeta + "\n" + codexUsageTestRecord(t, "response", "turn", codexUsage{InputTokens: 8, OutputTokens: 3}) + rec, err := parseCodexRolloutUsage(strings.NewReader(data)) + require.NoError(t, err) + got, err := foldCodexChildUsage("root", []codexRolloutUsage{rec}) + require.NoError(t, err) + assert.Equal(t, map[string]ModelUsage{"unknown": {Requests: 1, InputTokens: 8, OutputTokens: 3, CostUnavailable: true}}, got) +} + +func TestCodexSubagentUsage_DoesNotRequireSuccessfulChildCompletion(t *testing.T) { + t.Parallel() + rootID, rollouts := readRecordedCodexUsage(t, "0158") + // The reduced captures deliberately have no terminal lifecycle event. + // Valid incurred response usage still counts when a child later fails. + got, err := foldCodexChildUsage(rootID, rollouts[1:]) + require.NoError(t, err) + assert.Equal(t, 11, got["gpt-5.6-luna"].ReasoningTokens) +} + +func TestCodexSubagentUsage_RejectsMalformedUsage(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + usage any + }{ + {"null usage", nil}, + {"empty usage", map[string]int{}}, + {"missing output", map[string]int{"input_tokens": 1}}, + {"negative input", codexUsage{InputTokens: -1}}, + {"negative output", codexUsage{OutputTokens: -1}}, + {"negative cache read", codexUsage{InputTokens: 10, CachedInputTokens: -1}}, + {"negative cache write", codexUsage{InputTokens: 10, CacheWriteInputTokens: -1}}, + {"negative reasoning", codexUsage{OutputTokens: 10, ReasoningOutputTokens: -1}}, + {"cache exceeds input", codexUsage{InputTokens: 10, CachedInputTokens: 8, CacheWriteInputTokens: 3}}, + {"reasoning exceeds output", codexUsage{OutputTokens: 10, ReasoningOutputTokens: 11}}, + {"numeric overflow", json.RawMessage(`{"input_tokens":9223372036854775808}`)}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + data := codexUsageTestMeta + "\n" + codexUsageTestRecord(t, "response", "turn", tc.usage) + _, err := parseCodexRolloutUsage(strings.NewReader(data)) + require.Error(t, err) + }) + } + require.Error(t, validateCodexResponseUsage(nil), "the fold dereferences validated usage") +} + +func TestCodexSubagentUsage_RejectsIncompleteResponseIdentityAndJSON(t *testing.T) { + t.Parallel() + valid := codexUsageTestMeta + "\n" + codexUsageTestRecord(t, "response", "turn", codexUsage{InputTokens: 1}) + for _, field := range []string{"thread_id", "session_id", "turn_id", "root_turn_id", "response_id"} { + t.Run(field, func(t *testing.T) { + parts := strings.Split(valid, "\n") + var event map[string]any + require.NoError(t, json.Unmarshal([]byte(parts[1]), &event)) + delete(event["payload"].(map[string]any), field) + data, err := json.Marshal(event) + require.NoError(t, err) + _, err = parseCodexRolloutUsage(strings.NewReader(parts[0] + "\n" + string(data))) + require.Error(t, err) + }) + } + _, err := parseCodexRolloutUsage(strings.NewReader(valid + "\n{\"type\":")) + require.Error(t, err, "a truncated tail is not a complete rollout") +} + +func TestCodexSubagentUsage_RejectsAccumulationOverflow(t *testing.T) { + t.Parallel() + maxInt := int(^uint(0) >> 1) + data := strings.Join([]string{ + codexUsageTestMeta, + codexUsageTestRecord(t, "one", "turn", codexUsage{InputTokens: maxInt}), + codexUsageTestRecord(t, "two", "turn", codexUsage{InputTokens: 1}), + }, "\n") + rec, err := parseCodexRolloutUsage(strings.NewReader(data)) + require.NoError(t, err) + _, err = foldCodexChildUsage("root", []codexRolloutUsage{rec}) + require.Error(t, err, "untrusted counters must not wrap negative") +} + +func TestCodexSubagentUsage_AddPreservesParentAndReasoning(t *testing.T) { + t.Parallel() + rootID, rollouts := readRecordedCodexUsage(t, "0158") + byModel, err := foldCodexChildUsage(rootID, rollouts) + require.NoError(t, err) + parent := ModelUsage{Requests: 1, InputTokens: 18, OutputTokens: 624, CostUnavailable: true, + ReasoningTokens: 170, CacheReadInputTokens: 78328, CacheCreationInputTokens: 17845} + m := &RunMetrics{InputTokens: parent.InputTokens, OutputTokens: parent.OutputTokens, + ReasoningTokens: parent.ReasoningTokens, CacheReadInputTokens: parent.CacheReadInputTokens, + CacheCreationInputTokens: parent.CacheCreationInputTokens, + PerModelUsage: map[string]ModelUsage{"gpt-5.6-luna": parent}} + require.NoError(t, addCodexUsage(m, byModel)) + assert.Equal(t, 27, m.InputTokens) + assert.Equal(t, 650, m.OutputTokens) + assert.Equal(t, 181, m.ReasoningTokens) + assert.Equal(t, 45471, m.CacheCreationInputTokens) + assert.Equal(t, 78328, m.CacheReadInputTokens) + assert.Equal(t, ModelUsage{Requests: 4, InputTokens: 27, OutputTokens: 650, CostUnavailable: true, + ReasoningTokens: 181, CacheReadInputTokens: 78328, CacheCreationInputTokens: 45471}, + m.PerModelUsage["gpt-5.6-luna"]) + + var summed ModelUsage + summed.Add(parent) + summed.Add(byModel["gpt-5.6-luna"]) + assert.Equal(t, m.PerModelUsage["gpt-5.6-luna"], summed, "cross-iteration Add retains reasoning") +} + +func TestCodexSubagentUsage_AddOverflowDoesNotPartiallyMutateMetrics(t *testing.T) { + t.Parallel() + maxInt := int(^uint(0) >> 1) + m := &RunMetrics{InputTokens: maxInt, ReasoningTokens: 5, + PerModelUsage: map[string]ModelUsage{"parent": {Requests: 1, InputTokens: maxInt, ReasoningTokens: 5}}} + err := addCodexUsage(m, map[string]ModelUsage{"child": {Requests: 1, InputTokens: 1, ReasoningTokens: 3}}) + require.Error(t, err) + assert.Equal(t, maxInt, m.InputTokens) + assert.Equal(t, 5, m.ReasoningTokens) + assert.Equal(t, map[string]ModelUsage{"parent": {Requests: 1, InputTokens: maxInt, ReasoningTokens: 5}}, m.PerModelUsage) +} + +func TestCodexSubagentUsage_RootFallbackUsesOnlyRecordedRootResponses(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + version string + want ModelUsage + }{ + {"0157", ModelUsage{Requests: 1, InputTokens: 18, OutputTokens: 640, CostUnavailable: true, + ReasoningTokens: 137, CacheReadInputTokens: 77975, CacheCreationInputTokens: 17730}}, + {"0158", ModelUsage{Requests: 1, InputTokens: 18, OutputTokens: 624, CostUnavailable: true, + ReasoningTokens: 170, CacheReadInputTokens: 78328, CacheCreationInputTokens: 17845}}, + } { + t.Run(tc.version, func(t *testing.T) { + t.Parallel() + rootID, rollouts := readRecordedCodexUsage(t, tc.version) + rollouts = append(rollouts, rollouts[0]) // duplicate root artifact + got, err := foldCodexRootUsage(rootID, rollouts) + require.NoError(t, err) + assert.Equal(t, map[string]ModelUsage{"gpt-5.6-luna": tc.want}, got) + }) + } +} + +func TestCodexSubagentUsage_RootFallbackRejectsConflictingEvidence(t *testing.T) { + t.Parallel() + rootID, rollouts := readRecordedCodexUsage(t, "0158") + _, duplicate := readRecordedCodexUsage(t, "0158") + duplicate[0].Responses[0].Record.Usage.OutputTokens++ + _, err := foldCodexRootUsage(rootID, append(rollouts, duplicate[0])) + require.Error(t, err) + got, err := foldCodexRootUsage("unrelated-root", rollouts) + require.NoError(t, err) + assert.Empty(t, got, "missing root evidence must not borrow other sessions' tokens") +} diff --git a/internal/runtime/codex_transcript.go b/internal/runtime/codex_transcript.go index 6a8cd8ba2f..d66d6c10ca 100644 --- a/internal/runtime/codex_transcript.go +++ b/internal/runtime/codex_transcript.go @@ -1,16 +1,243 @@ package runtime import ( + "bytes" + "context" + "crypto/sha256" + "encoding/json" + "errors" "fmt" "io" + "maps" "os" "path/filepath" + "slices" "strings" + "sync" "time" + "github.com/google/uuid" + + "github.com/fullsend-ai/fullsend/internal/config" "github.com/fullsend-ai/fullsend/internal/sandbox" ) +// The exec stream establishes which native threads must have published +// transcripts. Keep these identities outside the sandbox: a second listing +// cannot prove completeness after files disappear between usage and extraction. +var codexExpectedTranscripts sync.Map // sandbox name -> codexTranscriptIdentities + +type codexTranscriptIdentities struct { + RootID string + Threads []string + Digests map[string]string +} + +func rememberCodexTranscriptIdentities(sandboxName, rootID string, children map[string]bool) { + identities := codexTranscriptIdentities{RootID: rootID} + if rootID != "" { + identities.Threads = append(identities.Threads, rootID) + } + for id := range children { + if id != "" && id != rootID { + identities.Threads = append(identities.Threads, id) + } + } + slices.Sort(identities.Threads) + codexExpectedTranscripts.Store(sandboxName, identities) +} + +func clearCodexTranscriptIdentities(sandboxName string) { + codexExpectedTranscripts.Delete(sandboxName) +} + +// Capture only small integrity metadata while accounting reads the private +// files. Root exit and child close precede collection, so extraction must see +// the same complete bytes; matching session metadata alone is insufficient. +func rememberCodexTranscriptFile(sandboxName string, meta codexRolloutMeta, path string) error { + expected, ok := codexExpectedTranscripts.Load(sandboxName) + if !ok { + return nil + } + identities := expected.(codexTranscriptIdentities) + if !slices.Contains(identities.Threads, meta.ThreadID) { + return nil + } + parent := identities.RootID + if meta.ThreadID == identities.RootID { + parent = "" + } + if meta.SessionID != identities.RootID || meta.ParentThreadID != parent { + return fmt.Errorf("codex transcript identity contradicts observed thread %s", meta.ThreadID) + } + digest, err := codexTranscriptDigest(path) + if err != nil { + return err + } + if previous := identities.Digests[meta.ThreadID]; previous != "" && previous != digest { + return fmt.Errorf("conflicting transcripts for observed codex thread %s", meta.ThreadID) + } + identities.Digests = maps.Clone(identities.Digests) + if identities.Digests == nil { + identities.Digests = make(map[string]string) + } + identities.Digests[meta.ThreadID] = digest + codexExpectedTranscripts.Store(sandboxName, identities) + return nil +} + +func codexTranscriptDigest(path string) (string, error) { + f, err := os.Open(path) + if err != nil { + return "", err + } + defer f.Close() + hash := sha256.New() + n, err := io.Copy(hash, io.LimitReader(f, codexMaxArtifactBytes+1)) + if err != nil { + return "", err + } + if n > codexMaxArtifactBytes { + return "", fmt.Errorf("codex transcript exceeds integrity byte limit") + } + return fmt.Sprintf("%x", hash.Sum(nil)), nil +} + +// downloadCodexRollouts streams complete, bounded, regular files to a private +// directory. Never download raw rollouts into the artifact directory: the +// download CLI can write the remote basename before renaming its destination. +func (r CodexRuntime) downloadCodexRollouts(ctx context.Context, sandboxName, privateDir string) ([]string, error) { + remotePaths, err := r.listCodexRollouts(ctx, sandboxName) + if err != nil { + return nil, err + } + slices.Sort(remotePaths) + remaining := int64(codexMaxArtifactBytes) + paths := make([]string, 0, len(remotePaths)) + var failures []error + for i, remote := range remotePaths { + if err := ctx.Err(); err != nil { + failures = append(failures, err) + break + } + if err := codexValidSessionPath(r.codexSessionsDir(), remote); err != nil { + failures = append(failures, err) + continue + } + if remaining <= 0 { + failures = append(failures, fmt.Errorf("codex rollouts exceed the collection byte limit")) + break + } + local := filepath.Join(privateDir, fmt.Sprintf("%03d-%s", i, filepath.Base(remote))) + n, err := codexDownloadRollout(ctx, sandboxName, r.codexSessionsDir(), remote, local, remaining) + if err != nil { + failures = append(failures, err) + continue + } + remaining -= n + paths = append(paths, local) + } + return paths, errors.Join(failures...) +} + +const codexListRolloutsPy = `import json,os,stat,sys +root=sys.argv[1] +if not stat.S_ISDIR(os.lstat(root).st_mode): raise ValueError('invalid sessions root') +paths=[] +size=0 +def fail(error): raise error +for directory,dirs,files in os.walk(root,followlinks=False,onerror=fail): + for name in files: + path=os.path.join(directory,name) + if name.endswith('.jsonl') and stat.S_ISREG(os.lstat(path).st_mode): + paths.append(path) + size+=len(path.encode('utf-8')) + if len(paths)>128 or size>32768: raise ValueError('rollout listing exceeds bounds') +print(json.dumps(paths)) +` + +func (r CodexRuntime) listCodexRollouts(ctx context.Context, sandboxName string) ([]string, error) { + python := "/usr/bin/python3" + if held, ok := lookupRunnerHeldDigests(sandboxName); ok && held.Python != "" { + python = held.Python + } + command := shellQuote(python) + " -I -c " + shellQuote(codexListRolloutsPy) + " " + shellQuote(r.codexSessionsDir()) + " # fullsend-codex-list" + reader, process, cancel, err := sandbox.ExecStreamReader(ctx, sandboxName, command, 10*time.Second, io.Discard) + if err != nil { + return nil, fmt.Errorf("listing codex rollouts: %w", err) + } + defer cancel() + defer reader.Close() + var output bytes.Buffer + const limit = 65536 + n, readErr := io.Copy(&output, io.LimitReader(reader, limit+1)) + if n > limit || readErr != nil { + cancel() + } + waitErr := process.Wait() + if n > limit || readErr != nil || waitErr != nil { + return nil, errors.Join(fmt.Errorf("listing codex rollouts failed or exceeded bounds"), readErr, waitErr) + } + var paths []string + if err := json.Unmarshal(output.Bytes(), &paths); err != nil || len(paths) > 128 { + return nil, fmt.Errorf("invalid or oversized codex rollout listing") + } + return paths, nil +} + +const codexReadRolloutPy = `import os,stat,sys +root,path,limit=sys.argv[1],sys.argv[2],int(sys.argv[3]) +relative=path.removeprefix(root+'/') +if relative==path or any(p in ('','.','..') for p in relative.split('/')): raise ValueError('invalid rollout path') +fd=os.open(root,os.O_PATH|os.O_DIRECTORY|os.O_NOFOLLOW) +parts=relative.split('/') +for part in parts[:-1]: + nextfd=os.open(part,os.O_PATH|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=fd) + os.close(fd); fd=nextfd +source=os.open(parts[-1],os.O_RDONLY|os.O_NONBLOCK|os.O_NOFOLLOW,dir_fd=fd) +os.close(fd) +info=os.fstat(source) +if not stat.S_ISREG(info.st_mode) or info.st_size>limit: raise ValueError('rollout is not a bounded regular file') +with os.fdopen(source,'rb') as stream: + left=limit+1 + while left: + chunk=stream.read(min(left,65536)) + if not chunk: break + sys.stdout.buffer.write(chunk); left-=len(chunk) +` + +// codexDownloadRollout returns the number of bytes written to local. +func codexDownloadRollout(ctx context.Context, sandboxName, root, remote, local string, limit int64) (int64, error) { + python := "/usr/bin/python3" + if held, ok := lookupRunnerHeldDigests(sandboxName); ok && held.Python != "" { + python = held.Python + } + command := shellQuote(python) + " -I -c " + shellQuote(codexReadRolloutPy) + " " + shellQuote(root) + " " + shellQuote(remote) + fmt.Sprintf(" %d # fullsend-codex-rollout", limit) + reader, process, cancel, err := sandbox.ExecStreamReader(ctx, sandboxName, command, 15*time.Second, io.Discard) + if err != nil { + return 0, err + } + defer cancel() + defer reader.Close() + f, err := os.OpenFile(local, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) + if err != nil { + cancel() + process.Wait() + return 0, err + } + n, copyErr := io.Copy(f, io.LimitReader(reader, limit+1)) + closeErr := f.Close() + if n > limit || copyErr != nil { + cancel() + } + waitErr := process.Wait() + if n > limit || copyErr != nil || closeErr != nil || waitErr != nil { + os.Remove(local) + return 0, errors.Join(fmt.Errorf("incomplete codex rollout transfer (%d bytes; limit %d)", n, limit), copyErr, closeErr, waitErr) + } + return n, nil +} + // ExtractTranscripts downloads codex's rollout session files (written under // the runner-owned $CODEX_HOME/sessions/YYYY/MM/DD/, one per thread) into // outputDir as -, with the same path containment as the @@ -28,7 +255,12 @@ import ( // // ClearIterationArtifacts empties the sessions directory between iterations, // so in practice this finds the current run's rollout. -func (r CodexRuntime) ExtractTranscripts(sandboxName, agentLabel, outputDir string) error { +func (r CodexRuntime) ExtractTranscripts(sandboxName, agentLabel, outputDir string) (err error) { + defer func() { + if err != nil { + err = fmt.Errorf("%w: %w", ErrIncompleteEvidence, err) + } + }() if err := os.MkdirAll(outputDir, 0o755); err != nil { return fmt.Errorf("creating output dir: %w", err) } @@ -38,82 +270,107 @@ func (r CodexRuntime) ExtractTranscripts(sandboxName, agentLabel, outputDir stri } defer root.Close() - stdout, _, _, err := sandbox.Exec(sandboxName, - fmt.Sprintf("find %s -type f -name '*.jsonl' 2>/dev/null || true", - shellQuote(r.codexSessionsDir())), - 10*time.Second, - ) + privateDir, err := os.MkdirTemp("", "fullsend-codex-rollouts-") if err != nil { - return fmt.Errorf("finding transcripts: %w", err) + return err } - trimmed := strings.TrimSpace(stdout) - if trimmed == "" { - fmt.Fprintf(os.Stderr, " [%s] No transcripts found\n", agentLabel) - return nil + defer os.RemoveAll(privateDir) + // ponytail: a second transfer of what collectCodexUsage already read, + // reconciled by digest; after a timeout these final bytes can hold usage it + // never counted. Publish its copy instead if transfer cost matters. + paths, collectionErr := r.downloadCodexRollouts(context.Background(), sandboxName, privateDir) + if paths == nil && collectionErr != nil { + return collectionErr + } + if collectionErr != nil { + fmt.Fprintf(os.Stderr, " [%s] Incomplete transcript collection: %s\n", agentLabel, sanitizeOutput(collectionErr.Error())) } - for _, remotePath := range strings.Split(trimmed, "\n") { - remotePath = strings.TrimSpace(remotePath) - if remotePath == "" { + failures := []error{collectionErr} + published := make(map[string]codexRolloutMeta) + var identities codexTranscriptIdentities + if expected, ok := codexExpectedTranscripts.Load(sandboxName); ok { + identities = expected.(codexTranscriptIdentities) + } + for _, path := range paths { + if err := codexIsRolloutFile(path); err != nil { + fmt.Fprintf(os.Stderr, " [%s] Discarded invalid rollout: %s\n", agentLabel, sanitizeOutput(err.Error())) + failures = append(failures, err) continue } - // `find` output is a list of paths from an agent-writable directory, - // and it goes straight to a download. A name is only followed when it - // is plainly inside the sessions directory and free of control - // characters: a newline in a filename splits one entry into two here, - // and without the prefix check a crafted entry could name any path in - // the sandbox for extraction into the run's artifacts. (`find -type f` - // above already skips symlinks — a symlink is -type l — so a link to - // /sandbox/workspace/.env is not listed in the first place.) - if err := codexValidSessionPath(r.codexSessionsDir(), remotePath); err != nil { - fmt.Fprintf(os.Stderr, " [%s] Skipping %s: %v\n", agentLabel, sanitizeOutput(remotePath), err) - continue + _, basename, _ := strings.Cut(filepath.Base(path), "-") + localName := agentLabel + "-" + basename + var head struct { + Payload codexRolloutMeta `json:"payload"` } - localName := fmt.Sprintf("%s-%s", agentLabel, filepath.Base(remotePath)) - f, createErr := root.Create(localName) - if createErr != nil { - fmt.Fprintf(os.Stderr, " [%s] Skipping (path rejected): %s: %v\n", agentLabel, localName, createErr) - continue + // Identity comes from native metadata, never the root's prose or a role + // alone. Preserve legacy filenames when old rollouts lack identities. + if f, openErr := os.Open(path); openErr == nil { + decodeErr := json.NewDecoder(f).Decode(&head) + f.Close() + if _, idErr := uuid.Parse(head.Payload.ThreadID); decodeErr == nil && idErr == nil { + localName = agentLabel + "-" + head.Payload.ThreadID + ".jsonl" + if head.Payload.ParentThreadID != "" { + role := head.Payload.Role + if !config.ValidSubagentKey(role) { + role = "generic" + } + localName = agentLabel + "-child-" + role + "-" + head.Payload.ThreadID + ".jsonl" + } + } } - f.Close() - localPath := filepath.Join(outputDir, localName) - os.Remove(localPath) - - // Downloaded, validated and redacted at a staging name, then renamed - // into place: a crash between the download and the rewrite would - // otherwise leave raw tool output sitting at the path the artifact - // collector picks up. - stagePath := localPath + ".fullsend-staging" - os.Remove(stagePath) - if dlErr := sandbox.DownloadFile(sandboxName, remotePath, stagePath); dlErr != nil { - fmt.Fprintf(os.Stderr, " [%s] Failed to copy transcript: %v\n", agentLabel, dlErr) - os.Remove(stagePath) - continue + if expected := identities.Digests[head.Payload.ThreadID]; expected != "" { + digest, digestErr := codexTranscriptDigest(path) + if digestErr != nil || digest != expected { + failures = append(failures, errors.Join(fmt.Errorf("codex transcript changed after usage collection for thread %s", head.Payload.ThreadID), digestErr)) + continue + } } - // The sessions directory is agent-writable, so a file being there and - // ending in .jsonl proves nothing: anything that is not a codex - // rollout is dropped rather than shipped as this run's transcript. - if err := codexIsRolloutFile(stagePath); err != nil { - fmt.Fprintf(os.Stderr, " [%s] Discarded %s: %v\n", agentLabel, localName, err) - os.Remove(stagePath) - continue + err := codexRedactFile(path) + if err == nil { + err = codexPublishTranscript(root, path, localName) } - // The rollout carries the same raw tool output the stream does, and it - // is uploaded as a run artifact, so it gets the same pattern redaction - // (codex_redact.go). - if redErr := codexRedactFile(stagePath); redErr != nil { - fmt.Fprintf(os.Stderr, " [%s] Discarded %s: could not redact it: %v\n", - agentLabel, localName, redErr) - os.Remove(stagePath) - continue - } - if mvErr := os.Rename(stagePath, localPath); mvErr != nil { - fmt.Fprintf(os.Stderr, " [%s] Discarded %s: %v\n", agentLabel, localName, mvErr) - os.Remove(stagePath) + if err != nil { + fmt.Fprintf(os.Stderr, " [%s] Cannot save transcript: %s\n", agentLabel, sanitizeOutput(err.Error())) + failures = append(failures, err) continue } + published[head.Payload.ThreadID] = head.Payload fmt.Fprintf(os.Stderr, " [%s] Saved transcript: %s\n", agentLabel, localName) } - return nil + for _, id := range identities.Threads { + meta, exists := published[id] + parent := identities.RootID + if id == identities.RootID { + parent = "" + } + if !exists || meta.SessionID != identities.RootID || meta.ParentThreadID != parent { + failures = append(failures, fmt.Errorf("missing transcript for observed codex thread %s", id)) + } + } + return errors.Join(failures...) +} + +// Only already-redacted bytes ever enter the public output directory. A +// temporary file plus root-relative rename makes publication atomic even when +// the private download directory is on a different filesystem. +func codexPublishTranscript(root *os.Root, source, name string) error { + in, err := os.Open(source) + if err != nil { + return err + } + defer in.Close() + stage := name + ".fullsend-staging" + root.Remove(stage) + out, err := root.OpenFile(stage, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600) + if err != nil { + return err + } + defer root.Remove(stage) + _, copyErr := io.Copy(out, in) + if err := errors.Join(copyErr, out.Close()); err != nil { + return err + } + return root.Rename(stage, name) } // ExtractDebugLog downloads the stderr capture Run writes when debug is on. @@ -128,16 +385,26 @@ func (r CodexRuntime) ExtractDebugLog(sandboxName, localPath, debug string) erro if debug == "" { return nil } - if err := sandbox.DownloadFile(sandboxName, r.WorkspaceDir()+"/"+codexDebugLogFile, localPath); err != nil { + privateDir, err := os.MkdirTemp("", "fullsend-codex-debug-") + if err != nil { + return err + } + defer os.RemoveAll(privateDir) + privatePath := filepath.Join(privateDir, codexDebugLogFile) + if _, err := codexDownloadRollout(context.Background(), sandboxName, r.WorkspaceDir(), r.WorkspaceDir()+"/"+codexDebugLogFile, privatePath, codexMaxArtifactBytes); err != nil { return err } - if err := codexRedactTextFile(localPath); err != nil { + if err := codexRedactTextFile(privatePath); err != nil { // Better no debug log than an unredacted one: it is a convenience // artifact, and the run does not depend on it. - os.Remove(localPath) return fmt.Errorf("redacting %s: %w", codexDebugLogFile, err) } - return nil + root, err := os.OpenRoot(filepath.Dir(localPath)) + if err != nil { + return err + } + defer root.Close() + return codexPublishTranscript(root, privatePath, filepath.Base(localPath)) } // codexValidSessionPath reports whether a path `find` returned is safe to diff --git a/internal/runtime/codex_transcript_integrity_test.go b/internal/runtime/codex_transcript_integrity_test.go new file mode 100644 index 0000000000..fb23b7e022 --- /dev/null +++ b/internal/runtime/codex_transcript_integrity_test.go @@ -0,0 +1,223 @@ +package runtime + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCodexTranscriptIntegrity_RejectedCopyPreservesFirstEvidence(t *testing.T) { + // A failed second collection must neither replace nor erase the digest + // that extraction uses to authenticate the first, complete transcript. + const body = `{"type":"session_meta","payload":{"id":"01a0e868-0083-7571-b0e2-de21c3a6c910","session_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","note":"original evidence"}}` + "\n" + for _, problem := range []string{"missing file", "unreadable contents", "conflicting copy"} { + t.Run(problem, func(t *testing.T) { + sandboxName := t.Name() + rememberCodexTranscriptIdentities(sandboxName, recordedRoot0158, nil) + t.Cleanup(func() { clearCodexTranscriptIdentities(sandboxName) }) + meta := codexRolloutMeta{ThreadID: recordedRoot0158, SessionID: recordedRoot0158} + original := filepath.Join(t.TempDir(), "original.jsonl") + require.NoError(t, os.WriteFile(original, []byte(body), 0o600)) + require.NoError(t, rememberCodexTranscriptFile(sandboxName, meta, original)) + + candidate := filepath.Join(t.TempDir(), "candidate.jsonl") + switch problem { + case "unreadable contents": + // Opening a directory succeeds, but hashing its bytes must fail. + require.NoError(t, os.Mkdir(candidate, 0o700)) + case "conflicting copy": + require.NoError(t, os.WriteFile(candidate, []byte(strings.ReplaceAll(body, "original evidence", "substituted evidence")), 0o600)) + } + err := rememberCodexTranscriptFile(sandboxName, meta, candidate) + require.Error(t, err) + if problem == "missing file" { + assert.ErrorIs(t, err, os.ErrNotExist) + } else if problem == "conflicting copy" { + assert.ErrorContains(t, err, "conflicting transcripts") + } else { + var pathErr *os.PathError + assert.ErrorAs(t, err, &pathErr) + } + + fakeOpenshellCodexWithRollouts(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "", map[string]string{"root.jsonl": body}) + out := t.TempDir() + require.NoError(t, (CodexRuntime{}).ExtractTranscripts(sandboxName, "review", out)) + assert.JSONEq(t, body, readFileString(t, filepath.Join(out, "review-01a0e868-0083-7571-b0e2-de21c3a6c910.jsonl"))) + + // Acceptance alone could also mean the digest was forgotten. The + // same native identity with different bytes must still be rejected. + changed := strings.ReplaceAll(body, "original evidence", "changed after collection") + fakeOpenshellCodexWithRollouts(t, filepath.Join(t.TempDir(), "changed.log"), t.TempDir(), "", map[string]string{"root.jsonl": changed}) + changedOut := t.TempDir() + err = (CodexRuntime{}).ExtractTranscripts(sandboxName, "review", changedOut) + require.ErrorIs(t, err, ErrIncompleteEvidence) + entries, err := os.ReadDir(changedOut) + require.NoError(t, err) + assert.Empty(t, entries, "retained authentication must prevent publishing changed evidence") + }) + } +} + +func TestCodexTranscriptIntegrity_RefusesDigestPastArtifactLimit(t *testing.T) { + t.Parallel() + path := filepath.Join(t.TempDir(), "oversized.jsonl") + f, err := os.Create(path) + require.NoError(t, err) + // A sparse file exercises the bounded streaming hash without allocating + // an artifact-sized string or buffer in the test process. + require.NoError(t, f.Truncate(codexMaxArtifactBytes+1)) + require.NoError(t, f.Close()) + digest, err := codexTranscriptDigest(path) + require.ErrorContains(t, err, "integrity byte limit") + assert.Empty(t, digest, "a prefix hash must not authenticate a truncated artifact") +} + +func TestCodexTranscriptIntegrity_DownloadPreservesExistingDestination(t *testing.T) { + for _, linked := range []bool{false, true} { + t.Run(map[bool]string{false: "existing file", true: "symlink"}[linked], func(t *testing.T) { + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "codex-cli 0.158.0") + previous := filepath.Join(t.TempDir(), "existing.jsonl") + require.NoError(t, os.WriteFile(previous, []byte("previous private evidence"), 0o600)) + local := previous + if linked { + local = filepath.Join(t.TempDir(), "download.jsonl") + require.NoError(t, os.Symlink(previous, local)) + } + _, err := codexDownloadRollout(t.Context(), t.Name(), "/sessions", "/sessions/root.jsonl", local, 1024) + require.ErrorIs(t, err, os.ErrExist) + assert.Equal(t, "previous private evidence", readFileString(t, previous)) + if linked { + target, err := os.Readlink(local) + require.NoError(t, err) + assert.Equal(t, previous, target, "failed download must not remove an existing link") + } + }) + } +} + +func TestCodexTranscriptIntegrity_DownloadStartFailureCreatesNoFile(t *testing.T) { + t.Setenv("PATH", t.TempDir()) + local := filepath.Join(t.TempDir(), "download.jsonl") + _, err := codexDownloadRollout(t.Context(), t.Name(), "/sessions", "/sessions/root.jsonl", local, 1024) + require.Error(t, err) + _, err = os.Stat(local) + assert.ErrorIs(t, err, os.ErrNotExist, "an unreachable sandbox must not leave an empty transcript") +} + +func TestCodexTranscriptIntegrity_PrivateStorageFailureIsReported(t *testing.T) { + for _, debug := range []bool{false, true} { + t.Run(map[bool]string{false: "transcripts", true: "debug log"}[debug], func(t *testing.T) { + out := t.TempDir() + blocked := filepath.Join(t.TempDir(), "not-a-directory") + require.NoError(t, os.WriteFile(blocked, []byte("keep"), 0o600)) + t.Setenv("TMPDIR", blocked) + var err error + if debug { + err = (CodexRuntime{}).ExtractDebugLog(t.Name(), filepath.Join(out, "debug.log"), "1") + } else { + err = (CodexRuntime{}).ExtractTranscripts(t.Name(), "review", out) + require.ErrorIs(t, err, ErrIncompleteEvidence) + } + var pathErr *os.PathError + require.ErrorAs(t, err, &pathErr) + assert.Equal(t, "mkdir", pathErr.Op) + assert.True(t, strings.HasPrefix(pathErr.Path, blocked+string(os.PathSeparator))) + entries, err := os.ReadDir(out) + require.NoError(t, err) + assert.Empty(t, entries, "raw bytes must not fall back to public artifact storage") + }) + } +} + +func TestCodexTranscriptIntegrity_PublishFailureRetainsSafeSibling(t *testing.T) { + fakeOpenshellCodexWithRollouts(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "", map[string]string{ + "blocked.jsonl": `{"type":"session_meta","payload":{}}` + "\n", + "safe.jsonl": `{"type":"session_meta","payload":{"note":"kept","token":"` + codexTestSecret + `"}}` + "\n", + }) + out := t.TempDir() + blocked := filepath.Join(out, "review-blocked.jsonl") + require.NoError(t, os.Mkdir(blocked, 0o700)) + marker := filepath.Join(blocked, "previous") + require.NoError(t, os.WriteFile(marker, []byte("retain"), 0o600)) + err := (CodexRuntime{}).ExtractTranscripts(t.Name(), "review", out) + require.ErrorIs(t, err, ErrIncompleteEvidence) + assert.Equal(t, "retain", readFileString(t, marker)) + got := readFileString(t, filepath.Join(out, "review-safe.jsonl")) + assert.NotContains(t, got, codexTestSecret) + assert.JSONEq(t, `{"type":"session_meta","payload":{"note":"kept","token":"ghp_..."}}`, got) + entries, err := os.ReadDir(out) + require.NoError(t, err) + require.Len(t, entries, 2, "failed publication must remove its staging file") +} + +func TestCodexTranscriptIntegrity_PublishFailurePreservesPreviousBytes(t *testing.T) { + for _, problem := range []string{"blocked staging path", "source read failure"} { + t.Run(problem, func(t *testing.T) { + out := t.TempDir() + root, err := os.OpenRoot(out) + require.NoError(t, err) + defer root.Close() + previous := filepath.Join(out, "root.jsonl") + require.NoError(t, os.WriteFile(previous, []byte("previous redacted evidence"), 0o600)) + source := t.TempDir() + stage := filepath.Join(out, "root.jsonl.fullsend-staging") + if problem == "blocked staging path" { + source = filepath.Join(source, "source.jsonl") + require.NoError(t, os.WriteFile(source, []byte("replacement"), 0o600)) + require.NoError(t, os.Mkdir(stage, 0o700)) + require.NoError(t, os.WriteFile(filepath.Join(stage, "marker"), []byte("keep"), 0o600)) + } + require.Error(t, codexPublishTranscript(root, source, "root.jsonl")) + assert.Equal(t, "previous redacted evidence", readFileString(t, previous)) + if problem == "blocked staging path" { + assert.Equal(t, "keep", readFileString(t, filepath.Join(stage, "marker"))) + } else { + _, err := os.Stat(stage) + assert.ErrorIs(t, err, os.ErrNotExist, "a failed copy must not leave a public partial artifact") + } + }) + } +} + +func TestCodexTranscriptIntegrity_DebugPublicationFailureIsReported(t *testing.T) { + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "codex-cli 0.158.0") + t.Setenv("FULLSEND_TEST_DOWNLOAD_BODY", "authorization: Bearer "+codexTestSecret) + out := t.TempDir() + err := (CodexRuntime{}).ExtractDebugLog(t.Name(), filepath.Join(out, "missing", "debug.log"), "1") + require.ErrorIs(t, err, os.ErrNotExist) + entries, err := os.ReadDir(out) + require.NoError(t, err) + assert.Empty(t, entries, "a publication failure must not expose the raw log") +} + +func TestCodexTranscriptIntegrity_CollectionStopsAtAggregateLimit(t *testing.T) { + root := (CodexRuntime{}).codexSessionsDir() + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "codex-cli 0.158.0", "", root+"/a.jsonl\n"+root+"/b.jsonl") + fake, err := exec.LookPath("openshell") + require.NoError(t, err) + require.NoError(t, os.Rename(fake, fake+"-base")) + large := filepath.Join(t.TempDir(), "large.jsonl") + f, err := os.Create(large) + require.NoError(t, err) + require.NoError(t, f.Truncate(codexMaxArtifactBytes)) + require.NoError(t, f.Close()) + secondStarted := filepath.Join(t.TempDir(), "second-transfer-started") + script := "#!/bin/sh\ncase \"$*\" in\n" + + " *'/a.jsonl'*fullsend-codex-rollout*) exec cat " + shellQuote(large) + ";;\n" + + " *'/b.jsonl'*fullsend-codex-rollout*) touch " + shellQuote(secondStarted) + "; printf 'second'; exit 0;;\n" + + "esac\nexec " + shellQuote(fake+"-base") + " \"$@\"\n" + require.NoError(t, os.WriteFile(fake, []byte(script), 0o755)) + paths, err := (CodexRuntime{}).downloadCodexRollouts(t.Context(), t.Name(), t.TempDir()) + require.ErrorContains(t, err, "collection byte limit") + require.Len(t, paths, 1, "keep the complete first file even when collection cannot continue") + info, err := os.Stat(paths[0]) + require.NoError(t, err) + assert.EqualValues(t, codexMaxArtifactBytes, info.Size()) + _, err = os.Stat(secondStarted) + assert.ErrorIs(t, err, os.ErrNotExist, "do not start another remote transfer when no byte budget remains") +} diff --git a/internal/runtime/codex_transcript_test.go b/internal/runtime/codex_transcript_test.go index 1f9856c028..9575976726 100644 --- a/internal/runtime/codex_transcript_test.go +++ b/internal/runtime/codex_transcript_test.go @@ -4,8 +4,10 @@ import ( "bytes" "context" "encoding/json" + "fmt" "os" "path/filepath" + "strings" "testing" "time" @@ -32,9 +34,9 @@ func TestCodexExtractTranscripts_DownloadsRollouts(t *testing.T) { // Only plain .jsonl, and only regular files: the sessions directory is // agent-writable, and a plaintext file named x.jsonl.zst used to ship as // an artifact codexRedactFile then declined to rewrite. - assert.Contains(t, log, "-type f -name '*.jsonl'") + assert.Contains(t, log, "fullsend-codex-list") assert.NotContains(t, log, "*.jsonl.zst") - assert.Contains(t, log, "download") + assert.Contains(t, log, "fullsend-codex-rollout") // The local name is prefixed with the agent label, as for pi and Claude, // so several agents' transcripts can share one directory. _, err := os.Stat(filepath.Join(outDir, "triage-rollout-2026-09-02T10-00-00-abc123.jsonl")) @@ -50,6 +52,141 @@ func TestCodexExtractTranscripts_NoSessionsIsNotAnError(t *testing.T) { assert.NotContains(t, readFileString(t, logPath), "download") } +func TestCodexExtractTranscripts_RequiresEveryObservedThreadAfterCollection(t *testing.T) { + child, err := os.ReadFile("testdata/codex/native-subagents/0158/probe-alpha.jsonl") + require.NoError(t, err) + root := testCodexRootUsage(recordedRoot0158, "gpt-5.6-luna", 20, 10, 2) + stream := fmt.Sprintf(`{"type":"thread.started","thread_id":%q} +{"type":"turn.started"} +{"type":"item.completed","item":{"id":"spawn","type":"collab_tool_call","tool":"spawn_agent","status":"completed","receiver_thread_ids":[%q],"agents_states":{}}} +{"type":"item.completed","item":{"id":"close","type":"collab_tool_call","tool":"close_agent","status":"completed","receiver_thread_ids":[%q],"agents_states":{%q:{"status":"completed","message":"Verified the result."}}}} +{"type":"turn.completed","usage":{"input_tokens":20,"cached_input_tokens":0,"output_tokens":10,"reasoning_output_tokens":2}} +`, recordedRoot0158, recordedAlpha0158, recordedAlpha0158, recordedAlpha0158) + for _, tc := range []struct { + name, removed, missing, reset string + wantFiles int + }{ + {name: "complete", wantFiles: 2}, + {name: "root disappears", removed: "root.jsonl", missing: recordedRoot0158, wantFiles: 1}, + {name: "child disappears", removed: "child.jsonl", missing: recordedAlpha0158, wantFiles: 1}, + {name: "all disappear", removed: "all", missing: recordedRoot0158}, + {name: "child replaced with metadata only", removed: "child-metadata", missing: recordedAlpha0158, wantFiles: 1}, + {name: "next iteration has no session yet", removed: "all", reset: "iteration"}, + {name: "bootstrap has no session yet", removed: "all", reset: "bootstrap"}, + } { + t.Run(tc.name, func(t *testing.T) { + fixture := filepath.Join(t.TempDir(), "stream.ndjson") + require.NoError(t, os.WriteFile(fixture, []byte(stream), 0o600)) + store := t.TempDir() + seedCodexManifest(t, store, CodexRuntime{}, nil) + bodies := map[string]string{"root.jsonl": root, "child.jsonl": string(child)} + fakeOpenshellCodexWithRollouts(t, filepath.Join(t.TempDir(), "run.log"), store, fixture, bodies) + exit, runErr := (CodexRuntime{}).Run(t.Context(), RunParams{ + SandboxName: "sb", RepoDir: "/sandbox/workspace/repo", Model: "gpt-5.6-luna", Timeout: time.Minute, + }, ui.New(&bytes.Buffer{}), time.Now(), &RunMetrics{}) + require.NoError(t, runErr) + require.Zero(t, exit, "usage collection must succeed before files disappear") + switch tc.removed { + case "all": + clear(bodies) + case "child-metadata": + bodies["child.jsonl"] = strings.SplitN(string(child), "\n", 2)[0] + "\n" + default: + delete(bodies, tc.removed) + } + fakeOpenshellCodexWithRollouts(t, filepath.Join(t.TempDir(), "extract.log"), store, "", bodies) + switch tc.reset { + case "iteration": + require.NoError(t, (CodexRuntime{}).ClearIterationArtifacts("sb")) + case "bootstrap": + require.NoError(t, (CodexRuntime{}).Bootstrap(bootstrapInput{ + sandboxName: "sb", agentPath: writeAgentFile(t, codexTestAgentDef), agentName: "triage", + })) + } + out := t.TempDir() + err := (CodexRuntime{}).ExtractTranscripts("sb", "review", out) + if tc.missing == "" { + require.NoError(t, err) + } else { + require.ErrorIs(t, err, ErrIncompleteEvidence) + assert.Contains(t, err.Error(), tc.missing) + if tc.removed == "child-metadata" { + assert.Contains(t, err.Error(), "transcript changed after usage collection") + } + } + files, err := os.ReadDir(out) + require.NoError(t, err) + assert.Len(t, files, tc.wantFiles, "preserve the remaining redacted transcripts") + }) + } +} + +func TestCodexExtractTranscripts_TimedOutRunPublishesFinalBytes(t *testing.T) { + // No terminal event: the exec was killed while Codex kept writing. + stream := fmt.Sprintf("{\"type\":\"thread.started\",\"thread_id\":%q}\n{\"type\":\"turn.started\"}\n", recordedRoot0158) + fixture := filepath.Join(t.TempDir(), "stream.ndjson") + require.NoError(t, os.WriteFile(fixture, []byte(stream), 0o600)) + store := t.TempDir() + seedCodexManifest(t, store, CodexRuntime{}, nil) + root := testCodexRootUsage(recordedRoot0158, "gpt-5.6-luna", 20, 10, 2) + fakeOpenshellCodexWithRollouts(t, filepath.Join(t.TempDir(), "run.log"), store, fixture, map[string]string{"root.jsonl": root}) + _, err := (CodexRuntime{}).Run(t.Context(), RunParams{ + SandboxName: "sb", RepoDir: "/sandbox/workspace/repo", Model: "gpt-5.6-luna", Timeout: time.Minute, + }, ui.New(&bytes.Buffer{}), time.Now(), &RunMetrics{}) + require.NoError(t, err) + final := root + `{"type":"turn_context","payload":{"turn_id":"after-collection","model":"gpt-5.6-luna"}}` + "\n" + fakeOpenshellCodexWithRollouts(t, filepath.Join(t.TempDir(), "extract.log"), store, "", map[string]string{"root.jsonl": final}) + out := t.TempDir() + require.NoError(t, (CodexRuntime{}).ExtractTranscripts("sb", "review", out)) + assert.Contains(t, readFileString(t, filepath.Join(out, "review-"+recordedRoot0158+".jsonl")), "after-collection") +} + +func TestCodexDownloadRolloutBoundAndFailure(t *testing.T) { + for _, tc := range []struct { + name, body, failure string + limit int64 + wantError bool + }{ + {"complete", "complete bytes", "", 64, false}, + {"exact limit", strings.Repeat("x", 63), "", 64, false}, + {"one byte over", strings.Repeat("x", 64), "", 64, true}, + {"process failure", "", "fullsend-codex-rollout", 64, true}, + } { + t.Run(tc.name, func(t *testing.T) { + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "codex-cli 0.157.0") + t.Setenv("FULLSEND_TEST_DOWNLOAD_BODY", tc.body) + t.Setenv("FULLSEND_TEST_FAIL_MATCH", tc.failure) + local := filepath.Join(t.TempDir(), "private.jsonl") + n, err := codexDownloadRollout(t.Context(), "download-test", "/sessions", "/sessions/rollout.jsonl", local, tc.limit) + if tc.wantError { + require.Error(t, err) + _, statErr := os.Stat(local) + assert.ErrorIs(t, statErr, os.ErrNotExist, "partial raw bytes must be removed") + } else { + require.NoError(t, err) + assert.Equal(t, tc.body+"\n", readFileString(t, local)) + assert.EqualValues(t, len(tc.body)+1, n) + info, err := os.Stat(local) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o600), info.Mode().Perm()) + } + }) + } +} + +func TestCodexExtractTranscriptsChildIdentity(t *testing.T) { + role := "../../untrusted" + body := `{"type":"session_meta","payload":{"id":"01a0e868-1019-74d0-a11f-2ad529629759","parent_thread_id":"root","agent_role":"` + role + `"}}` + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "codex-cli 0.157.0", "", CodexRuntime{}.codexSessionsDir()+"/child.jsonl") + t.Setenv("FULLSEND_TEST_DOWNLOAD_BODY", body) + out := t.TempDir() + require.NoError(t, CodexRuntime{}.ExtractTranscripts("child-identity", "review", out)) + entries, err := os.ReadDir(out) + require.NoError(t, err) + require.Len(t, entries, 1) + assert.Equal(t, "review-child-generic-01a0e868-1019-74d0-a11f-2ad529629759.jsonl", entries[0].Name()) +} + func TestCodexExtractDebugLog_OnlyWhenDebugIsOn(t *testing.T) { logPath := filepath.Join(t.TempDir(), "openshell.log") fakeOpenshellCodex(t, logPath, t.TempDir(), "codex-cli 0.152.1") @@ -143,7 +280,7 @@ func TestCodexRun_SuccessfulRunReportsMetrics(t *testing.T) { storeDir := t.TempDir() r := CodexRuntime{} seedCodexManifest(t, storeDir, r, nil) - fakeOpenshellCodex(t, logPath, storeDir, "codex-cli 0.152.1", filepath.Join("testdata", "codex", "basic_run.ndjson")) + fakeOpenshellCodexWithRollouts(t, logPath, storeDir, filepath.Join("testdata", "codex", "basic_run.ndjson"), map[string]string{"root.jsonl": testBasicCodexRootUsage()}) metrics := &RunMetrics{} exit, err := r.Run(context.Background(), RunParams{ @@ -210,7 +347,7 @@ func TestCodexRun_AcceptsManifestHookPlan(t *testing.T) { r := CodexRuntime{} seedCodexManifest(t, storeDir, r, codexHooksManifestFor(r.codexHooksDir(), security.SandboxHookConfigFromHarness(&harness.Harness{}))) - fakeOpenshellCodex(t, logPath, storeDir, "codex-cli 0.152.1", filepath.Join("testdata", "codex", "basic_run.ndjson")) + fakeOpenshellCodexWithRollouts(t, logPath, storeDir, filepath.Join("testdata", "codex", "basic_run.ndjson"), map[string]string{"root.jsonl": testBasicCodexRootUsage()}) exit, err := r.Run(context.Background(), RunParams{ SandboxName: "sb", @@ -231,6 +368,8 @@ func TestCodexRun_AcceptsManifestHookPlan(t *testing.T) { func seedCodexManifest(t *testing.T, storeDir string, r CodexRuntime, hooks *codexHooksManifest) { t.Helper() hashes := codexRunnerHeldDigestSet{ + Python: "/usr/bin/python3", + HooksJSON: "hooks00000000000000000000000000000000000000000000000000000000000", ConfigTOML: "config0000000000000000000000000000000000000000000000000000000000", AgentModel: "openai/gpt-5.6-luna", } @@ -239,7 +378,10 @@ func seedCodexManifest(t *testing.T, storeDir string, r CodexRuntime, hooks *cod hashes.HookScripts = testCodexHookScripts() } recordRunnerHeldDigests("sb", hashes) - t.Cleanup(func() { forgetRunnerHeldDigests("sb") }) + t.Cleanup(func() { + forgetRunnerHeldDigests("sb") + clearCodexTranscriptIdentities("sb") + }) data, err := json.MarshalIndent(codexManifest{ AgentName: "triage", // Deliberately different from the runner-held AgentModel: Run must @@ -277,7 +419,7 @@ func TestCodexRun_FallsBackToTheAgentDefinitionModel(t *testing.T) { // the run params name none. The manifest's own copy is deliberately not // consulted, so it is left saying something else below. seedCodexManifest(t, storeDir, r, nil) - fakeOpenshellCodex(t, logPath, storeDir, "codex-cli 0.152.1", filepath.Join("testdata", "codex", "basic_run.ndjson")) + fakeOpenshellCodexWithRollouts(t, logPath, storeDir, filepath.Join("testdata", "codex", "basic_run.ndjson"), map[string]string{"root.jsonl": testBasicCodexRootUsage()}) metrics := &RunMetrics{} exit, err := r.Run(context.Background(), RunParams{ @@ -289,7 +431,7 @@ func TestCodexRun_FallsBackToTheAgentDefinitionModel(t *testing.T) { require.NoError(t, err) assert.Equal(t, 0, exit) assert.Equal(t, "gpt-5.6-luna", metrics.Model, "the runner-held openai/ spec, prefix stripped") - assert.Contains(t, readFileString(t, logPath), "--model 'gpt-5.6-luna'") + assert.Contains(t, strings.ReplaceAll(readFileString(t, logPath), "'\\''", "'"), "--model 'gpt-5.6-luna'") } func TestCodexRun_RequiresAModelWhenNothingNamesOne(t *testing.T) { @@ -376,7 +518,7 @@ func TestCodexExtractTranscripts_DiscardsSpoofedFiles(t *testing.T) { fakeOpenshellCodex(t, logPath, storeDir, "codex-cli 0.152.1", "", spoof) outDir := filepath.Join(t.TempDir(), "transcripts") - require.NoError(t, r.ExtractTranscripts("sb", "smoke", outDir)) + require.Error(t, r.ExtractTranscripts("sb", "smoke", outDir)) // The fake writes a non-rollout body for a path containing "planted", so // nothing is kept. @@ -499,7 +641,7 @@ func TestCodexExtractTranscripts_FailurePaths(t *testing.T) { err := r.ExtractTranscripts("sb", "smoke", filepath.Join(t.TempDir(), "out")) require.Error(t, err) - assert.Contains(t, err.Error(), "finding transcripts") + assert.Contains(t, err.Error(), "listing codex rollouts") }) t.Run("a path outside the sessions dir is skipped, not downloaded", func(t *testing.T) { @@ -510,7 +652,7 @@ func TestCodexExtractTranscripts_FailurePaths(t *testing.T) { sandbox.SandboxWorkspace+"/.env") outDir := filepath.Join(t.TempDir(), "out") - require.NoError(t, r.ExtractTranscripts("sb", "smoke", outDir)) + require.Error(t, r.ExtractTranscripts("sb", "smoke", outDir)) assert.NotContains(t, readFileString(t, logPath), "download", "a path outside the sessions directory must never reach a download") entries, err := os.ReadDir(outDir) @@ -522,11 +664,11 @@ func TestCodexExtractTranscripts_FailurePaths(t *testing.T) { logPath := filepath.Join(t.TempDir(), "openshell.log") rollout := r.codexSessionsDir() + "/rollout-x.jsonl" fakeOpenshellCodex(t, logPath, t.TempDir(), "codex-cli 0.152.1", "", rollout) - t.Setenv("FULLSEND_TEST_FAIL_MATCH", "download") + t.Setenv("FULLSEND_TEST_FAIL_MATCH", "fullsend-codex-rollout") outDir := filepath.Join(t.TempDir(), "out") - require.NoError(t, r.ExtractTranscripts("sb", "smoke", outDir), - "one failed transcript must not fail the run") + require.Error(t, r.ExtractTranscripts("sb", "smoke", outDir), + "missing transcripts must not be reported as complete") entries, err := os.ReadDir(outDir) require.NoError(t, err) assert.Empty(t, entries) @@ -538,7 +680,7 @@ func TestCodexExtractDebugLog_FailurePaths(t *testing.T) { t.Run("a download that fails is reported", func(t *testing.T) { fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "codex-cli 0.152.1") - t.Setenv("FULLSEND_TEST_FAIL_MATCH", "download") + t.Setenv("FULLSEND_TEST_FAIL_MATCH", "fullsend-codex-rollout") err := r.ExtractDebugLog("sb", filepath.Join(t.TempDir(), "codex-debug.log"), "1") require.Error(t, err) @@ -571,8 +713,8 @@ func TestCodexRun_IgnoresATamperedManifestModel(t *testing.T) { storeDir := t.TempDir() r := CodexRuntime{} seedCodexManifest(t, storeDir, r, nil) // manifest says gpt-9-tampered - fakeOpenshellCodex(t, logPath, storeDir, "codex-cli 0.152.1", - filepath.Join("testdata", "codex", "basic_run.ndjson")) + fakeOpenshellCodexWithRollouts(t, logPath, storeDir, + filepath.Join("testdata", "codex", "basic_run.ndjson"), map[string]string{"root.jsonl": testBasicCodexRootUsage()}) metrics := &RunMetrics{} exit, err := r.Run(t.Context(), RunParams{ @@ -585,6 +727,6 @@ func TestCodexRun_IgnoresATamperedManifestModel(t *testing.T) { assert.Equal(t, 0, exit) assert.Equal(t, "gpt-5.6-luna", metrics.Model, "the runner-held model, not the manifest's") log := readFileString(t, logPath) - assert.Contains(t, log, "--model 'gpt-5.6-luna'") + assert.Contains(t, strings.ReplaceAll(log, "'\\''", "'"), "--model 'gpt-5.6-luna'") assert.NotContains(t, log, "gpt-9-tampered") } diff --git a/internal/runtime/codex_usage.go b/internal/runtime/codex_usage.go new file mode 100644 index 0000000000..09822811fa --- /dev/null +++ b/internal/runtime/codex_usage.go @@ -0,0 +1,283 @@ +package runtime + +import ( + "bufio" + "bytes" + "encoding/json" + "fmt" + "io" + "maps" + "strings" +) + +// Codex 0.157.0 and 0.158.0 persist one token_usage_record for each +// completed response whose provider reported usage. Its usage is a delta; +// the accompanying turn/thread counters may include inherited history. +// The reduced live fixtures in testdata/codex/native-subagents pin this wire. +type codexRolloutMeta struct { + ThreadID string `json:"id"` + SessionID string `json:"session_id"` + ParentThreadID string `json:"parent_thread_id"` + Role string `json:"agent_role"` +} + +type codexResponseUsageRecord struct { + ThreadID string `json:"thread_id"` + SessionID string `json:"session_id"` + TurnID string `json:"turn_id"` + RootTurnID string `json:"root_turn_id"` + ResponseID string `json:"response_id"` + Usage *codexUsage `json:"usage"` +} + +type codexUsageKey struct{ ThreadID, ResponseID string } + +type codexAttributedUsage struct { + Record codexResponseUsageRecord + Model string +} + +type codexRolloutUsage struct { + Meta codexRolloutMeta + Responses []codexAttributedUsage +} + +// parseCodexRolloutUsage reads a complete bounded rollout without retaining +// prompt/tool content. Models are joined by turn ID, not the last context in +// the file. Missing model metadata remains visible as an unknown bucket. +func parseCodexRolloutUsage(r io.Reader) (codexRolloutUsage, error) { + var out codexRolloutUsage + limited := &io.LimitedReader{R: r, N: codexMaxArtifactBytes + 1} + scanner := bufio.NewScanner(limited) + scanner.Buffer(make([]byte, 0, 64*1024), codexMaxArtifactBytes+1) + models := make(map[string]string) + sawMeta := false + lineNumber := 0 + for scanner.Scan() { + lineNumber++ + line := bytes.TrimSpace(scanner.Bytes()) + if len(line) == 0 { + continue + } + var envelope struct { + Type string `json:"type"` + Payload json.RawMessage `json:"payload"` + } + if err := json.Unmarshal(line, &envelope); err != nil { + return out, fmt.Errorf("codex rollout line %d is not JSON", lineNumber) + } + if !codexRolloutEnvelopes[envelope.Type] { + return out, fmt.Errorf("codex rollout line %d has an unknown envelope", lineNumber) + } + switch envelope.Type { + case "session_meta": + if sawMeta { + return out, fmt.Errorf("codex rollout has multiple session identities") + } + if err := json.Unmarshal(envelope.Payload, &out.Meta); err != nil || out.Meta.ThreadID == "" || out.Meta.SessionID == "" { + return out, fmt.Errorf("codex rollout has invalid session identity") + } + sawMeta = true + case "turn_context": + var turn struct { + TurnID string `json:"turn_id"` + Model string `json:"model"` + } + if err := json.Unmarshal(envelope.Payload, &turn); err != nil { + return out, fmt.Errorf("codex rollout line %d has invalid turn context", lineNumber) + } + if turn.TurnID == "" { + continue + } + model := strings.TrimSpace(strings.TrimPrefix(turn.Model, "openai/")) + if previous, ok := models[turn.TurnID]; ok && previous != model { + return out, fmt.Errorf("codex rollout has conflicting models for a turn") + } + models[turn.TurnID] = model + case "token_usage_record": + var rec codexResponseUsageRecord + var presence struct { + Usage map[string]json.RawMessage `json:"usage"` + } + if json.Unmarshal(envelope.Payload, &rec) != nil || json.Unmarshal(envelope.Payload, &presence) != nil { + return out, fmt.Errorf("codex rollout line %d has invalid usage", lineNumber) + } + // Only cache_write_input_tokens is optional in upstream TokenUsage. + // Missing/null required fields are not a reported zero-token response. + for _, key := range []string{"input_tokens", "cached_input_tokens", "output_tokens", "reasoning_output_tokens"} { + value := bytes.TrimSpace(presence.Usage[key]) + if len(value) == 0 || bytes.Equal(value, []byte("null")) { + return out, fmt.Errorf("codex rollout line %d has incomplete usage", lineNumber) + } + } + if rec.ThreadID == "" || rec.SessionID == "" || rec.TurnID == "" || rec.RootTurnID == "" || rec.ResponseID == "" { + return out, fmt.Errorf("codex rollout line %d has incomplete response identity", lineNumber) + } + if err := validateCodexResponseUsage(rec.Usage); err != nil { + return out, fmt.Errorf("codex rollout line %d: %w", lineNumber, err) + } + out.Responses = append(out.Responses, codexAttributedUsage{Record: rec}) + } + } + if limited.N == 0 { + return out, fmt.Errorf("codex rollout exceeds %d-byte artifact limit", codexMaxArtifactBytes) + } + if err := scanner.Err(); err != nil { + return out, fmt.Errorf("reading complete codex rollout: %w", err) + } + if !sawMeta { + return out, fmt.Errorf("codex rollout is missing session identity") + } + for i := range out.Responses { + model := models[out.Responses[i].Record.TurnID] + if model == "" { + model = "unknown" + } + out.Responses[i].Model = model + } + return out, nil +} + +func validateCodexResponseUsage(u *codexUsage) error { + if u == nil { + return fmt.Errorf("missing response usage") + } + if u.InputTokens < 0 || u.OutputTokens < 0 || u.CachedInputTokens < 0 || u.CacheWriteInputTokens < 0 || u.ReasoningOutputTokens < 0 { + return fmt.Errorf("negative response usage") + } + // Subtract only after bounding each subset; adding two hostile counters + // first could overflow and accidentally pass the subset check. + if u.CachedInputTokens > u.InputTokens || u.CacheWriteInputTokens > u.InputTokens-u.CachedInputTokens || u.ReasoningOutputTokens > u.OutputTokens { + return fmt.Errorf("response usage subsets exceed their totals") + } + return nil +} + +// foldCodexChildUsage produces child-only contributions for one depth-one +// run. Deduplication spans files and repeated records; role names are never +// identities. A conflicting duplicate fails rather than depending on the +// order the sandbox happened to enumerate files. +func foldCodexChildUsage(rootID string, rollouts []codexRolloutUsage) (map[string]ModelUsage, error) { + return foldCodexThreadUsage(rootID, rollouts, false) +} + +// foldCodexRootUsage recovers observed parent usage when interruption left +// the exec stream without a completed-turn snapshot. The caller must replace +// that missing parent contribution, never add this to a successful snapshot. +func foldCodexRootUsage(rootID string, rollouts []codexRolloutUsage) (map[string]ModelUsage, error) { + return foldCodexThreadUsage(rootID, rollouts, true) +} + +// foldCodexThreadUsage takes rollouts from parseCodexRolloutUsage, the trust +// boundary that guarantees complete identities, validated non-nil usage and a +// non-empty model. +func foldCodexThreadUsage(rootID string, rollouts []codexRolloutUsage, rootOnly bool) (map[string]ModelUsage, error) { + if rootID == "" { + return nil, fmt.Errorf("codex usage requires the root thread ID") + } + byModel := make(map[string]ModelUsage) + seen := make(map[codexUsageKey]codexAttributedUsage) + invocations := make(map[[2]string]bool) + for _, rollout := range rollouts { + meta := rollout.Meta + matches := meta.ThreadID != "" && meta.ThreadID != rootID && meta.ParentThreadID == rootID && meta.SessionID == rootID + if rootOnly { + matches = meta.ThreadID == rootID && meta.ParentThreadID == "" && meta.SessionID == rootID + } + if !matches { + continue + } + for _, attributed := range rollout.Responses { + rec, model := attributed.Record, attributed.Model + // Forked history can contain parent response records. Their usage + // belongs to that other thread, not to the enclosing child. + if rec.ThreadID != meta.ThreadID { + continue + } + if rec.SessionID != rootID { + return nil, fmt.Errorf("codex response session contradicts its thread identity") + } + key := codexUsageKey{rec.ThreadID, rec.ResponseID} + if previous, ok := seen[key]; ok { + if previous.Model != model || previous.Record.SessionID != rec.SessionID || previous.Record.TurnID != rec.TurnID || previous.Record.RootTurnID != rec.RootTurnID || *previous.Record.Usage != *rec.Usage { + return nil, fmt.Errorf("codex usage has conflicting duplicate response records") + } + continue + } + seen[key] = attributed + c := rec.Usage.counters() + u := ModelUsage{InputTokens: c.Input, OutputTokens: c.Output, + ReasoningTokens: c.Reasoning, CacheReadInputTokens: c.CacheRead, + CacheCreationInputTokens: c.CacheWrite, CostUnavailable: true} + invocation := [2]string{rec.ThreadID, model} + if !invocations[invocation] { + u.Requests = 1 + invocations[invocation] = true + } + total, err := sumCodexModelUsage(byModel[model], u) + if err != nil { + return nil, err + } + byModel[model] = total + } + } + return byModel, nil +} + +// sumCodexModelUsage checks counters originating in agent-writable rollouts +// before adding them. Costs stay unreported for Codex. +func sumCodexModelUsage(a, b ModelUsage) (ModelUsage, error) { + out := a + out.CostUnavailable = a.CostUnavailable || b.CostUnavailable + for _, pair := range []struct { + dst *int + src int + }{ + {&out.Requests, b.Requests}, {&out.InputTokens, b.InputTokens}, + {&out.OutputTokens, b.OutputTokens}, {&out.ReasoningTokens, b.ReasoningTokens}, + {&out.CacheReadInputTokens, b.CacheReadInputTokens}, + {&out.CacheCreationInputTokens, b.CacheCreationInputTokens}, + } { + if *pair.dst < 0 || pair.src < 0 || pair.src > int(^uint(0)>>1)-*pair.dst { + return ModelUsage{}, fmt.Errorf("codex usage counter is negative or overflows") + } + *pair.dst += pair.src + } + return out, nil +} + +// addCodexUsage applies a child-only fold once, after the root stream has +// stopped updating metrics. Validate all additions before changing anything. +// The caller seeds the parent's PerModelUsage entry before calling this. +func addCodexUsage(m *RunMetrics, byModel map[string]ModelUsage) error { + if m == nil { + return fmt.Errorf("codex usage requires run metrics") + } + total := ModelUsage{InputTokens: m.InputTokens, OutputTokens: m.OutputTokens, + ReasoningTokens: m.ReasoningTokens, CacheReadInputTokens: m.CacheReadInputTokens, + CacheCreationInputTokens: m.CacheCreationInputTokens, CostUnavailable: m.CostUnavailable} + perModel := maps.Clone(m.PerModelUsage) + if perModel == nil { + perModel = make(map[string]ModelUsage) + } + for model, usage := range byModel { + var err error + total, err = sumCodexModelUsage(total, usage) + if err != nil { + return err + } + entry, err := sumCodexModelUsage(perModel[model], usage) + if err != nil { + return err + } + perModel[model] = entry + } + m.InputTokens = total.InputTokens + m.OutputTokens = total.OutputTokens + m.ReasoningTokens = total.ReasoningTokens + m.CacheReadInputTokens = total.CacheReadInputTokens + m.CacheCreationInputTokens = total.CacheCreationInputTokens + m.CostUnavailable = total.CostUnavailable + m.PerModelUsage = perModel + return nil +} diff --git a/internal/runtime/codex_usage_boundary_test.go b/internal/runtime/codex_usage_boundary_test.go new file mode 100644 index 0000000000..84eac3565c --- /dev/null +++ b/internal/runtime/codex_usage_boundary_test.go @@ -0,0 +1,126 @@ +package runtime + +import ( + "errors" + "io" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCodexUsageBoundary_RejectsAmbiguousSessionAndModelEvidence(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name, data, problem string + }{ + {"duplicate session", codexUsageTestMeta + "\n" + codexUsageTestMeta, "multiple session identities"}, + {"missing thread", `{"type":"session_meta","payload":{"session_id":"root"}}`, "invalid session identity"}, + {"missing session", `{"type":"session_meta","payload":{"id":"child"}}`, "invalid session identity"}, + {"malformed identity", `{"type":"session_meta","payload":{"id":17,"session_id":"root"}}`, "invalid session identity"}, + {"no identity", `{"type":"turn_context","payload":{"turn_id":"turn","model":"gpt-5.6-luna"}}`, "missing session identity"}, + {"malformed context", codexUsageTestMeta + "\n" + `{"type":"turn_context","payload":{"turn_id":42}}`, "invalid turn context"}, + {"conflicting models", codexUsageTestMeta + "\n" + codexUsageTestContext("turn", "gpt-5.6-luna") + "\n" + codexUsageTestContext("turn", "gpt-5.6-sol"), "conflicting models"}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + _, err := parseCodexRolloutUsage(strings.NewReader(tc.data)) + require.ErrorContains(t, err, tc.problem, "ambiguous evidence must never select a session or model by file order") + }) + } +} + +func TestCodexUsageBoundary_UnidentifiedContextCannotStealAttribution(t *testing.T) { + t.Parallel() + data := strings.Join([]string{ + codexUsageTestMeta, + codexUsageTestContext("turn", "openai/gpt-5.6-luna"), + codexUsageTestContext("turn", "gpt-5.6-luna"), + codexUsageTestContext("", "gpt-5.6-sol"), + codexUsageTestRecord(t, "response", "turn", codexUsage{ + InputTokens: 15, CachedInputTokens: 6, CacheWriteInputTokens: 4, + OutputTokens: 9, ReasoningOutputTokens: 3, + }), + }, "\n") + rollout, err := parseCodexRolloutUsage(strings.NewReader(data)) + require.NoError(t, err) + got, err := foldCodexChildUsage("root", []codexRolloutUsage{rollout}) + require.NoError(t, err) + assert.Equal(t, map[string]ModelUsage{"gpt-5.6-luna": { + Requests: 1, InputTokens: 5, OutputTokens: 6, ReasoningTokens: 3, + CacheReadInputTokens: 6, CacheCreationInputTokens: 4, CostUnavailable: true, + }}, got) +} + +type codexUsageReadFailure struct{ err error } + +func (r codexUsageReadFailure) Read([]byte) (int, error) { return 0, r.err } + +func TestCodexUsageBoundary_ReadFailureCannotBecomeCompleteEvidence(t *testing.T) { + t.Parallel() + brokenRead := errors.New("rollout storage disconnected") + data := codexUsageTestMeta + "\n" + codexUsageTestRecord(t, "response", "turn", codexUsage{InputTokens: 9}) + "\n" + _, err := parseCodexRolloutUsage(io.MultiReader(strings.NewReader(data), codexUsageReadFailure{brokenRead})) + require.ErrorIs(t, err, brokenRead, "a valid prefix must not hide a missing tail") +} + +func TestCodexUsageBoundary_ReducerRequiresRoot(t *testing.T) { + t.Parallel() + // Identity and usage are validated by parseCodexRolloutUsage (see + // TestCodexSubagentUsage_RejectsIncompleteResponseIdentityAndJSON and + // RejectsMalformedUsage); the fold only needs the root. + _, err := foldCodexChildUsage("", nil) + require.Error(t, err, "a missing root must not accept unrelated sessions as zero usage") + _, err = foldCodexRootUsage("", nil) + require.Error(t, err) +} + +func TestCodexUsageBoundary_UnknownModelDeduplicatesAndConservesUsage(t *testing.T) { + t.Parallel() + rollout, err := parseCodexRolloutUsage(strings.NewReader(strings.Join([]string{ + codexUsageTestMeta, + codexUsageTestContext("turn", " "), + codexUsageTestRecord(t, "one", "turn", codexUsage{InputTokens: 15, CachedInputTokens: 6, CacheWriteInputTokens: 4, OutputTokens: 9, ReasoningOutputTokens: 3}), + codexUsageTestRecord(t, "two", "turn", codexUsage{InputTokens: 10, CachedInputTokens: 2, CacheWriteInputTokens: 1, OutputTokens: 4, ReasoningOutputTokens: 1}), + }, "\n"))) + require.NoError(t, err) + got, err := foldCodexChildUsage("root", []codexRolloutUsage{rollout, rollout}) + require.NoError(t, err) + assert.Equal(t, map[string]ModelUsage{"unknown": { + Requests: 1, InputTokens: 12, OutputTokens: 9, ReasoningTokens: 4, + CacheReadInputTokens: 8, CacheCreationInputTokens: 5, CostUnavailable: true, + }}, got, "two responses plus a copied artifact are one invocation and 38 total tokens") +} + +func TestCodexUsageBoundary_PerModelOverflowIsAtomic(t *testing.T) { + t.Parallel() + maxInt := int(^uint(0) >> 1) + metrics := &RunMetrics{InputTokens: 2, TotalCostUSD: 1.25, + PerModelUsage: map[string]ModelUsage{"parent": {Requests: maxInt, InputTokens: 2, CostUSD: 1.25}}} + err := addCodexUsage(metrics, map[string]ModelUsage{"parent": {Requests: 1, InputTokens: 3, CostUnavailable: true}}) + require.Error(t, err, "invocation overflow must be rejected even when the aggregate token counters fit") + assert.Equal(t, 2, metrics.InputTokens) + assert.Equal(t, 1.25, metrics.TotalCostUSD) + assert.False(t, metrics.CostUnavailable, "a failed merge must not change known-cost status") + assert.Equal(t, map[string]ModelUsage{"parent": {Requests: maxInt, InputTokens: 2, CostUSD: 1.25}}, metrics.PerModelUsage) + require.Error(t, addCodexUsage(nil, nil), "missing metrics must return an error instead of panic") +} + +func TestCodexUsageBoundary_UnknownChildCostPreservesKnownContribution(t *testing.T) { + t.Parallel() + metrics := &RunMetrics{InputTokens: 2, TotalCostUSD: 1.25, + PerModelUsage: map[string]ModelUsage{"parent": {Requests: 1, InputTokens: 2, CostUSD: 1.25}}} + require.NoError(t, addCodexUsage(metrics, map[string]ModelUsage{"child": { + Requests: 1, InputTokens: 3, OutputTokens: 4, ReasoningTokens: 2, CostUnavailable: true, + }})) + assert.Equal(t, 5, metrics.InputTokens) + assert.Equal(t, 4, metrics.OutputTokens) + assert.Equal(t, 2, metrics.ReasoningTokens) + assert.Equal(t, 1.25, metrics.TotalCostUSD, "partial known dollars remain useful, but are not the complete price") + assert.True(t, metrics.CostUnavailable) + assert.Equal(t, map[string]ModelUsage{ + "parent": {Requests: 1, InputTokens: 2, CostUSD: 1.25}, + "child": {Requests: 1, InputTokens: 3, OutputTokens: 4, ReasoningTokens: 2, CostUnavailable: true}, + }, metrics.PerModelUsage) +} diff --git a/internal/runtime/cost_availability_test.go b/internal/runtime/cost_availability_test.go new file mode 100644 index 0000000000..db8ee6408d --- /dev/null +++ b/internal/runtime/cost_availability_test.go @@ -0,0 +1,60 @@ +package runtime + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func assertCostUnavailableJSON(t *testing.T, value any, want bool) { + t.Helper() + data, err := json.Marshal(value) + require.NoError(t, err) + var fields map[string]any + require.NoError(t, json.Unmarshal(data, &fields)) + if want { + assert.Equal(t, true, fields["cost_unavailable"]) + } else { + assert.NotContains(t, fields, "cost_unavailable", "preserve existing known-cost JSON") + } +} + +func TestCostAvailability_ModelUsageAdd(t *testing.T) { + var unknown ModelUsage + require.NoError(t, json.Unmarshal([]byte(`{"cost_unavailable":true,"input_tokens":10}`), &unknown)) + for _, unknownFirst := range []bool{false, true} { + var got ModelUsage + known := ModelUsage{CostUSD: 0.25, InputTokens: 5} + if unknownFirst { + got.Add(unknown) + got.Add(known) + } else { + got.Add(known) + got.Add(unknown) + } + assertCostUnavailableJSON(t, got, true) + assert.Equal(t, 0.25, got.CostUSD, "retain the known contribution without calling it a complete total") + assert.Equal(t, 15, got.InputTokens) + } + assertCostUnavailableJSON(t, ModelUsage{}, false) + assertCostUnavailableJSON(t, &RunMetrics{}, false) +} + +func TestCostAvailability_CodexStreamAndChildren(t *testing.T) { + var metrics RunMetrics + applyCodexMetrics(&metrics, ResultEvent{InputTokens: 7, CostUnavailable: true}) + assertCostUnavailableJSON(t, &metrics, true) + rootID, rollouts := readRecordedCodexUsage(t, "0158") + children, err := foldCodexChildUsage(rootID, rollouts) + require.NoError(t, err) + for _, usage := range children { + assertCostUnavailableJSON(t, usage, true) + } + require.NoError(t, addCodexUsage(&metrics, children)) + assertCostUnavailableJSON(t, &metrics, true) + for _, usage := range metrics.PerModelUsage { + assertCostUnavailableJSON(t, usage, true) + } +} diff --git a/internal/runtime/event.go b/internal/runtime/event.go index 0b2faf0235..95afc5f4d6 100644 --- a/internal/runtime/event.go +++ b/internal/runtime/event.go @@ -92,6 +92,7 @@ func (TokensEvent) agentEvent() {} type ResultEvent struct { NumTurns int TotalCostUSD float64 + CostUnavailable bool // The runtime does not report dollar cost. IsError bool ErrorMessage string Subtype string diff --git a/internal/runtime/pi_personas.go b/internal/runtime/pi_personas.go index 0974b1a553..3e22a40a1c 100644 --- a/internal/runtime/pi_personas.go +++ b/internal/runtime/pi_personas.go @@ -15,6 +15,8 @@ import ( // optional model and optional tools restriction. type piPersona struct { Name string + Description string + Body string Model string // frontmatter model (alias or id); empty = inherit parent Tools []string // Claude tool names; nil = parent's set BashAllowlist []string // Bash(a,b) prefixes; nil = unrestricted @@ -129,6 +131,8 @@ func discoverPersonas(skillDirs []string, agentName string) ([]piPersona, []piSk seen[name] = skillName personas = append(personas, piPersona{ Name: name, + Description: def.Description, + Body: def.Body, Model: def.Model, Tools: def.Tools, BashAllowlist: def.BashAllowlist, diff --git a/internal/runtime/pi_subagents.go b/internal/runtime/pi_subagents.go index 4a1fb3f064..7714686757 100644 --- a/internal/runtime/pi_subagents.go +++ b/internal/runtime/pi_subagents.go @@ -18,11 +18,9 @@ import ( // parent's entry is always in the breakdown (see foldPiSubagentUsage). // // The fold covers exactly the fields a per-model entry has: input, -// output, cache-creation and cache-read tokens, and cost. Reasoning -// tokens are not among them — RunMetrics carries a run-level -// ReasoningTokens with no ModelUsage counterpart — so the -// breakdown-sums-to-the-totals invariant is about those five and not -// about every number in metrics.json. +// output, cache-creation and cache-read tokens, and cost. Pi's child usage +// records do not expose a separate reasoning count, so its breakdown invariant +// covers those five fields. Codex records also populate ModelUsage.ReasoningTokens. // piSubagentUnknownModel keys a usage record that carries no model spec: // the line has a seq and a usage object but its "model" is empty or diff --git a/internal/runtime/renderer.go b/internal/runtime/renderer.go index b7b26d709d..36b187888c 100644 --- a/internal/runtime/renderer.go +++ b/internal/runtime/renderer.go @@ -102,7 +102,11 @@ func (r *EventRenderer) Handle(evt AgentEvent) { } r.printer.Header(label) r.printer.KeyValue("Turns", fmt.Sprintf("%d", e.NumTurns)) - r.printer.KeyValue("Cost", fmt.Sprintf("$%.4f", e.TotalCostUSD)) + if e.CostUnavailable { + r.printer.KeyValue("Cost", "unavailable") + } else { + r.printer.KeyValue("Cost", fmt.Sprintf("$%.4f", e.TotalCostUSD)) + } if e.ReasoningTokens > 0 { r.printer.KeyValue("Tokens", fmt.Sprintf( "in=%d out=%d reasoning=%d cache_create=%d cache_read=%d", diff --git a/internal/runtime/renderer_test.go b/internal/runtime/renderer_test.go index e83d23732f..d90d54a593 100644 --- a/internal/runtime/renderer_test.go +++ b/internal/runtime/renderer_test.go @@ -157,6 +157,15 @@ func TestRendererResultEvent(t *testing.T) { } } +func TestRendererResultEventCostUnavailable(t *testing.T) { + var buf bytes.Buffer + r := newTestRenderer(&buf) + r.Handle(ResultEvent{CostUnavailable: true}) + if output := buf.String(); !strings.Contains(output, "unavailable") || strings.Contains(output, "$0.0000") { + t.Errorf("unreported cost must not render as zero dollars: %s", output) + } +} + func TestRendererResultEventWithError(t *testing.T) { var buf bytes.Buffer r := newTestRenderer(&buf) diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index a17af40ef3..50e3a433cd 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -2,6 +2,7 @@ package runtime import ( "context" + "errors" "fmt" "sync/atomic" "time" @@ -9,11 +10,13 @@ import ( "github.com/fullsend-ai/fullsend/internal/ui" ) -// RunMetrics collects execution statistics from stream parsing. +// RunMetrics collects execution statistics from stream parsing. CostUnavailable +// means TotalCostUSD is incomplete because some usage has no reported cost. type RunMetrics struct { ToolCalls atomic.Int32 NumTurns int `json:"num_turns"` TotalCostUSD float64 `json:"total_cost_usd"` + CostUnavailable bool `json:"cost_unavailable,omitempty"` InputTokens int `json:"input_tokens"` OutputTokens int `json:"output_tokens"` ReasoningTokens int `json:"reasoning_tokens"` @@ -21,7 +24,7 @@ type RunMetrics struct { CacheReadInputTokens int `json:"cache_read_input_tokens"` Model string `json:"model"` // PerModelUsage breaks the totals above down by the model spec that - // spent them. Runtimes that dispatch sub-agents (pi's Agent tool) fill + // spent them. Runtimes that dispatch sub-agents (pi and Codex) fill // it with one entry per child model plus the parent's own, so a run // whose cost is dominated by children is legible in metrics.json; // runtimes without sub-agents leave it nil and the totals stand alone. @@ -30,14 +33,18 @@ type RunMetrics struct { // ModelUsage is one model's token and cost contribution to a run. Requests // counts the agent invocations attributed to the model (one for the parent -// iteration, one per sub-agent call). +// iteration, one per sub-agent call). A Codex thread that changes model +// contributes one invocation to each model it actually used. CostUnavailable +// marks CostUSD as incomplete, including when its known contribution is zero. type ModelUsage struct { Requests int `json:"requests"` InputTokens int `json:"input_tokens"` OutputTokens int `json:"output_tokens"` + ReasoningTokens int `json:"reasoning_tokens,omitempty"` CacheCreationInputTokens int `json:"cache_creation_input_tokens"` CacheReadInputTokens int `json:"cache_read_input_tokens"` CostUSD float64 `json:"cost_usd"` + CostUnavailable bool `json:"cost_unavailable,omitempty"` } // Add accumulates other into u. @@ -45,11 +52,18 @@ func (u *ModelUsage) Add(other ModelUsage) { u.Requests += other.Requests u.InputTokens += other.InputTokens u.OutputTokens += other.OutputTokens + u.ReasoningTokens += other.ReasoningTokens u.CacheCreationInputTokens += other.CacheCreationInputTokens u.CacheReadInputTokens += other.CacheReadInputTokens u.CostUSD += other.CostUSD + u.CostUnavailable = u.CostUnavailable || other.CostUnavailable } +// ErrIncompleteEvidence marks a run whose required runtime evidence could not +// be collected or verified. Callers should preserve available artifacts, but +// must not accept output validation as proof that the run completed safely. +var ErrIncompleteEvidence = errors.New("incomplete runtime evidence") + // DefaultAgentPrompt is the prompt handed to the agent CLI when RunParams // does not override it. It is deliberately content-free: the actual task // comes from the agent definition selected with --agent, so every runtime diff --git a/internal/runtime/testdata/codex/native-subagents/0157/default.jsonl b/internal/runtime/testdata/codex/native-subagents/0157/default.jsonl new file mode 100644 index 0000000000..3f712d0160 --- /dev/null +++ b/internal/runtime/testdata/codex/native-subagents/0157/default.jsonl @@ -0,0 +1,3 @@ +{"timestamp":"2026-09-28T14:23:04.352Z","type":"session_meta","payload":{"id":"01a0e865-da84-71d3-95bd-ba0f3444eff2","session_id":"01a0e865-c82b-7991-b075-3ad644e16b31","parent_thread_id":"01a0e865-c82b-7991-b075-3ad644e16b31","source":{"subagent":{"thread_spawn":{"parent_thread_id":"01a0e865-c82b-7991-b075-3ad644e16b31","depth":1,"agent_path":null,"agent_nickname":"Dewey","agent_role":"default"}}},"thread_source":"subagent","agent_role":"default","multi_agent_version":"v1"}} +{"timestamp":"2026-09-28T14:23:05.079Z","type":"turn_context","payload":{"turn_id":"01a0e865-daa0-7290-80b0-107b965c2d4f","model":"gpt-5.6-luna","root_turn_id":"01a0e865-c84b-7112-8277-05918063943f"}} +{"timestamp":"2026-09-28T14:23:06.385Z","type":"token_usage_record","payload":{"thread_id":"01a0e865-da84-71d3-95bd-ba0f3444eff2","turn_id":"01a0e865-daa0-7290-80b0-107b965c2d4f","session_id":"01a0e865-c82b-7991-b075-3ad644e16b31","root_turn_id":"01a0e865-c84b-7112-8277-05918063943f","response_id":"resp_081d0f4f992035d0016aba7849249487d291deab2469fded4e","usage":{"input_tokens":9227,"cached_input_tokens":0,"cache_write_input_tokens":9224,"output_tokens":8,"reasoning_output_tokens":0,"total_tokens":9235},"turn_token_usage":{"input_tokens":9227,"cached_input_tokens":0,"cache_write_input_tokens":9224,"output_tokens":8,"reasoning_output_tokens":0,"total_tokens":9235},"thread_token_usage":{"input_tokens":9227,"cached_input_tokens":0,"cache_write_input_tokens":9224,"output_tokens":8,"reasoning_output_tokens":0,"total_tokens":9235}}} diff --git a/internal/runtime/testdata/codex/native-subagents/0157/probe-alpha.jsonl b/internal/runtime/testdata/codex/native-subagents/0157/probe-alpha.jsonl new file mode 100644 index 0000000000..9bc5810815 --- /dev/null +++ b/internal/runtime/testdata/codex/native-subagents/0157/probe-alpha.jsonl @@ -0,0 +1,3 @@ +{"timestamp":"2026-09-28T14:23:04.319Z","type":"session_meta","payload":{"id":"01a0e865-da5f-7f23-a113-86d7a107c3f7","session_id":"01a0e865-c82b-7991-b075-3ad644e16b31","parent_thread_id":"01a0e865-c82b-7991-b075-3ad644e16b31","source":{"subagent":{"thread_spawn":{"parent_thread_id":"01a0e865-c82b-7991-b075-3ad644e16b31","depth":1,"agent_path":null,"agent_nickname":"Feynman","agent_role":"probe_alpha"}}},"thread_source":"subagent","agent_role":"probe_alpha","multi_agent_version":"v1"}} +{"timestamp":"2026-09-28T14:23:04.886Z","type":"turn_context","payload":{"turn_id":"01a0e865-da7d-7000-b5dd-e650ff08df27","model":"gpt-5.6-luna","root_turn_id":"01a0e865-c84b-7112-8277-05918063943f"}} +{"timestamp":"2026-09-28T14:23:05.757Z","type":"token_usage_record","payload":{"thread_id":"01a0e865-da5f-7f23-a113-86d7a107c3f7","turn_id":"01a0e865-da7d-7000-b5dd-e650ff08df27","session_id":"01a0e865-c82b-7991-b075-3ad644e16b31","root_turn_id":"01a0e865-c84b-7112-8277-05918063943f","response_id":"resp_0aebf76885404806016aba7848f0b087d29740fcdc9fec8c8d","usage":{"input_tokens":9204,"cached_input_tokens":0,"cache_write_input_tokens":9201,"output_tokens":8,"reasoning_output_tokens":0,"total_tokens":9212},"turn_token_usage":{"input_tokens":9204,"cached_input_tokens":0,"cache_write_input_tokens":9201,"output_tokens":8,"reasoning_output_tokens":0,"total_tokens":9212},"thread_token_usage":{"input_tokens":9204,"cached_input_tokens":0,"cache_write_input_tokens":9201,"output_tokens":8,"reasoning_output_tokens":0,"total_tokens":9212}}} diff --git a/internal/runtime/testdata/codex/native-subagents/0157/probe-beta.jsonl b/internal/runtime/testdata/codex/native-subagents/0157/probe-beta.jsonl new file mode 100644 index 0000000000..5037408e6b --- /dev/null +++ b/internal/runtime/testdata/codex/native-subagents/0157/probe-beta.jsonl @@ -0,0 +1,3 @@ +{"timestamp":"2026-09-28T14:23:04.382Z","type":"session_meta","payload":{"id":"01a0e865-daa3-7a71-b355-d76fc45c53f6","session_id":"01a0e865-c82b-7991-b075-3ad644e16b31","parent_thread_id":"01a0e865-c82b-7991-b075-3ad644e16b31","source":{"subagent":{"thread_spawn":{"parent_thread_id":"01a0e865-c82b-7991-b075-3ad644e16b31","depth":1,"agent_path":null,"agent_nickname":"Ohm","agent_role":"probe_beta"}}},"thread_source":"subagent","agent_role":"probe_beta","multi_agent_version":"v1"}} +{"timestamp":"2026-09-28T14:23:04.913Z","type":"turn_context","payload":{"turn_id":"01a0e865-dabd-7490-9d76-d0f6de6b5bab","model":"gpt-5.6-luna","root_turn_id":"01a0e865-c84b-7112-8277-05918063943f"}} +{"timestamp":"2026-09-28T14:23:05.840Z","type":"token_usage_record","payload":{"thread_id":"01a0e865-daa3-7a71-b355-d76fc45c53f6","turn_id":"01a0e865-dabd-7490-9d76-d0f6de6b5bab","session_id":"01a0e865-c82b-7991-b075-3ad644e16b31","root_turn_id":"01a0e865-c84b-7112-8277-05918063943f","response_id":"resp_0279ae726e832f82016aba7848fcb887d2ae2d8c2d9f1b5e8a","usage":{"input_tokens":9204,"cached_input_tokens":0,"cache_write_input_tokens":9201,"output_tokens":8,"reasoning_output_tokens":0,"total_tokens":9212},"turn_token_usage":{"input_tokens":9204,"cached_input_tokens":0,"cache_write_input_tokens":9201,"output_tokens":8,"reasoning_output_tokens":0,"total_tokens":9212},"thread_token_usage":{"input_tokens":9204,"cached_input_tokens":0,"cache_write_input_tokens":9201,"output_tokens":8,"reasoning_output_tokens":0,"total_tokens":9212}}} diff --git a/internal/runtime/testdata/codex/native-subagents/0157/root.jsonl b/internal/runtime/testdata/codex/native-subagents/0157/root.jsonl new file mode 100644 index 0000000000..4fd2cd60a3 --- /dev/null +++ b/internal/runtime/testdata/codex/native-subagents/0157/root.jsonl @@ -0,0 +1,8 @@ +{"timestamp":"2026-09-28T14:22:59.661Z","type":"session_meta","payload":{"id":"01a0e865-c82b-7991-b075-3ad644e16b31","session_id":"01a0e865-c82b-7991-b075-3ad644e16b31","source":"exec","thread_source":"user"}} +{"timestamp":"2026-09-28T14:23:00.168Z","type":"turn_context","payload":{"turn_id":"01a0e865-c84b-7112-8277-05918063943f","model":"gpt-5.6-luna","root_turn_id":"01a0e865-c84b-7112-8277-05918063943f"}} +{"timestamp":"2026-09-28T14:23:01.488Z","type":"token_usage_record","payload":{"thread_id":"01a0e865-c82b-7991-b075-3ad644e16b31","turn_id":"01a0e865-c84b-7112-8277-05918063943f","session_id":"01a0e865-c82b-7991-b075-3ad644e16b31","root_turn_id":"01a0e865-c84b-7112-8277-05918063943f","response_id":"resp_0337ef103d587371016aba784437d487d2b58299f9820ad84f","usage":{"input_tokens":9504,"cached_input_tokens":0,"cache_write_input_tokens":9501,"output_tokens":97,"reasoning_output_tokens":48,"total_tokens":9601},"turn_token_usage":{"input_tokens":9504,"cached_input_tokens":0,"cache_write_input_tokens":9501,"output_tokens":97,"reasoning_output_tokens":48,"total_tokens":9601},"thread_token_usage":{"input_tokens":9504,"cached_input_tokens":0,"cache_write_input_tokens":9501,"output_tokens":97,"reasoning_output_tokens":48,"total_tokens":9601}}} +{"timestamp":"2026-09-28T14:23:04.297Z","type":"token_usage_record","payload":{"thread_id":"01a0e865-c82b-7991-b075-3ad644e16b31","turn_id":"01a0e865-c84b-7112-8277-05918063943f","session_id":"01a0e865-c82b-7991-b075-3ad644e16b31","root_turn_id":"01a0e865-c84b-7112-8277-05918063943f","response_id":"resp_0337ef103d587371016aba784648a887d28222e0d35c26fdf3","usage":{"input_tokens":16646,"cached_input_tokens":9501,"cache_write_input_tokens":7142,"output_tokens":188,"reasoning_output_tokens":42,"total_tokens":16834},"turn_token_usage":{"input_tokens":26150,"cached_input_tokens":9501,"cache_write_input_tokens":16643,"output_tokens":285,"reasoning_output_tokens":90,"total_tokens":26435},"thread_token_usage":{"input_tokens":26150,"cached_input_tokens":9501,"cache_write_input_tokens":16643,"output_tokens":285,"reasoning_output_tokens":90,"total_tokens":26435}}} +{"timestamp":"2026-09-28T14:23:05.505Z","type":"token_usage_record","payload":{"thread_id":"01a0e865-c82b-7991-b075-3ad644e16b31","turn_id":"01a0e865-c84b-7112-8277-05918063943f","session_id":"01a0e865-c82b-7991-b075-3ad644e16b31","root_turn_id":"01a0e865-c84b-7112-8277-05918063943f","response_id":"resp_0337ef103d587371016aba78486b1487d2b1094e9de5cc7857","usage":{"input_tokens":17028,"cached_input_tokens":16643,"cache_write_input_tokens":382,"output_tokens":112,"reasoning_output_tokens":0,"total_tokens":17140},"turn_token_usage":{"input_tokens":43178,"cached_input_tokens":26144,"cache_write_input_tokens":17025,"output_tokens":397,"reasoning_output_tokens":90,"total_tokens":43575},"thread_token_usage":{"input_tokens":43178,"cached_input_tokens":26144,"cache_write_input_tokens":17025,"output_tokens":397,"reasoning_output_tokens":90,"total_tokens":43575}}} +{"timestamp":"2026-09-28T14:23:06.953Z","type":"token_usage_record","payload":{"thread_id":"01a0e865-c82b-7991-b075-3ad644e16b31","turn_id":"01a0e865-c84b-7112-8277-05918063943f","session_id":"01a0e865-c82b-7991-b075-3ad644e16b31","root_turn_id":"01a0e865-c84b-7112-8277-05918063943f","response_id":"resp_0337ef103d587371016aba7849cfa487d2b1c5eb26baf27095","usage":{"input_tokens":17258,"cached_input_tokens":17025,"cache_write_input_tokens":230,"output_tokens":102,"reasoning_output_tokens":13,"total_tokens":17360},"turn_token_usage":{"input_tokens":60436,"cached_input_tokens":43169,"cache_write_input_tokens":17255,"output_tokens":499,"reasoning_output_tokens":103,"total_tokens":60935},"thread_token_usage":{"input_tokens":60436,"cached_input_tokens":43169,"cache_write_input_tokens":17255,"output_tokens":499,"reasoning_output_tokens":103,"total_tokens":60935}}} +{"timestamp":"2026-09-28T14:23:08.304Z","type":"token_usage_record","payload":{"thread_id":"01a0e865-c82b-7991-b075-3ad644e16b31","turn_id":"01a0e865-c84b-7112-8277-05918063943f","session_id":"01a0e865-c82b-7991-b075-3ad644e16b31","root_turn_id":"01a0e865-c84b-7112-8277-05918063943f","response_id":"resp_0337ef103d587371016aba784b010887d2aaf42de9275c51b3","usage":{"input_tokens":17554,"cached_input_tokens":17255,"cache_write_input_tokens":296,"output_tokens":121,"reasoning_output_tokens":9,"total_tokens":17675},"turn_token_usage":{"input_tokens":77990,"cached_input_tokens":60424,"cache_write_input_tokens":17551,"output_tokens":620,"reasoning_output_tokens":112,"total_tokens":78610},"thread_token_usage":{"input_tokens":77990,"cached_input_tokens":60424,"cache_write_input_tokens":17551,"output_tokens":620,"reasoning_output_tokens":112,"total_tokens":78610}}} +{"timestamp":"2026-09-28T14:23:09.715Z","type":"token_usage_record","payload":{"thread_id":"01a0e865-c82b-7991-b075-3ad644e16b31","turn_id":"01a0e865-c84b-7112-8277-05918063943f","session_id":"01a0e865-c82b-7991-b075-3ad644e16b31","root_turn_id":"01a0e865-c84b-7112-8277-05918063943f","response_id":"resp_0337ef103d587371016aba784c621c87d292d76c71f2b378d4","usage":{"input_tokens":17733,"cached_input_tokens":17551,"cache_write_input_tokens":179,"output_tokens":157,"reasoning_output_tokens":25,"total_tokens":17890},"turn_token_usage":{"input_tokens":95723,"cached_input_tokens":77975,"cache_write_input_tokens":17730,"output_tokens":777,"reasoning_output_tokens":137,"total_tokens":96500},"thread_token_usage":{"input_tokens":95723,"cached_input_tokens":77975,"cache_write_input_tokens":17730,"output_tokens":777,"reasoning_output_tokens":137,"total_tokens":96500}}} diff --git a/internal/runtime/testdata/codex/native-subagents/0158/default.jsonl b/internal/runtime/testdata/codex/native-subagents/0158/default.jsonl new file mode 100644 index 0000000000..f204b556cf --- /dev/null +++ b/internal/runtime/testdata/codex/native-subagents/0158/default.jsonl @@ -0,0 +1,3 @@ +{"timestamp":"2026-09-28T14:25:29.170Z","type":"session_meta","payload":{"id":"01a0e868-1037-7123-86da-fdb886715284","session_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","parent_thread_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","source":{"subagent":{"thread_spawn":{"parent_thread_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","depth":1,"agent_path":null,"agent_nickname":"James","agent_role":"default"}}},"thread_source":"subagent","agent_role":"default","multi_agent_version":"v1"}} +{"timestamp":"2026-09-28T14:25:29.686Z","type":"turn_context","payload":{"turn_id":"01a0e868-1051-7110-9170-5565ea3d6747","model":"gpt-5.6-luna","root_turn_id":"01a0e868-00a1-7eb0-b020-9e70e708c274"}} +{"timestamp":"2026-09-28T14:25:30.564Z","type":"token_usage_record","payload":{"thread_id":"01a0e868-1037-7123-86da-fdb886715284","turn_id":"01a0e868-1051-7110-9170-5565ea3d6747","session_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","root_turn_id":"01a0e868-00a1-7eb0-b020-9e70e708c274","response_id":"resp_06f32a58b33b2dbe016aba78d9bbe087d29216ea73d5e3fde1","usage":{"input_tokens":9227,"cached_input_tokens":0,"cache_write_input_tokens":9224,"output_tokens":8,"reasoning_output_tokens":0,"total_tokens":9235},"turn_token_usage":{"input_tokens":9227,"cached_input_tokens":0,"cache_write_input_tokens":9224,"output_tokens":8,"reasoning_output_tokens":0,"total_tokens":9235},"thread_token_usage":{"input_tokens":9227,"cached_input_tokens":0,"cache_write_input_tokens":9224,"output_tokens":8,"reasoning_output_tokens":0,"total_tokens":9235}}} diff --git a/internal/runtime/testdata/codex/native-subagents/0158/probe-alpha.jsonl b/internal/runtime/testdata/codex/native-subagents/0158/probe-alpha.jsonl new file mode 100644 index 0000000000..755823642f --- /dev/null +++ b/internal/runtime/testdata/codex/native-subagents/0158/probe-alpha.jsonl @@ -0,0 +1,3 @@ +{"timestamp":"2026-09-28T14:25:29.106Z","type":"session_meta","payload":{"id":"01a0e868-0ff5-7b90-8852-e23f529ca223","session_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","parent_thread_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","source":{"subagent":{"thread_spawn":{"parent_thread_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","depth":1,"agent_path":null,"agent_nickname":"McClintock","agent_role":"probe_alpha"}}},"thread_source":"subagent","agent_role":"probe_alpha","multi_agent_version":"v1"}} +{"timestamp":"2026-09-28T14:25:29.569Z","type":"turn_context","payload":{"turn_id":"01a0e868-1010-76d3-aef3-4a73d6bc59cf","model":"gpt-5.6-luna","root_turn_id":"01a0e868-00a1-7eb0-b020-9e70e708c274"}} +{"timestamp":"2026-09-28T14:25:30.601Z","type":"token_usage_record","payload":{"thread_id":"01a0e868-0ff5-7b90-8852-e23f529ca223","turn_id":"01a0e868-1010-76d3-aef3-4a73d6bc59cf","session_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","root_turn_id":"01a0e868-00a1-7eb0-b020-9e70e708c274","response_id":"resp_0703a165126aae44016aba78d9a3a487d28784231896b0efd8","usage":{"input_tokens":9204,"cached_input_tokens":0,"cache_write_input_tokens":9201,"output_tokens":8,"reasoning_output_tokens":0,"total_tokens":9212},"turn_token_usage":{"input_tokens":9204,"cached_input_tokens":0,"cache_write_input_tokens":9201,"output_tokens":8,"reasoning_output_tokens":0,"total_tokens":9212},"thread_token_usage":{"input_tokens":9204,"cached_input_tokens":0,"cache_write_input_tokens":9201,"output_tokens":8,"reasoning_output_tokens":0,"total_tokens":9212}}} diff --git a/internal/runtime/testdata/codex/native-subagents/0158/probe-beta.jsonl b/internal/runtime/testdata/codex/native-subagents/0158/probe-beta.jsonl new file mode 100644 index 0000000000..c26ec820d1 --- /dev/null +++ b/internal/runtime/testdata/codex/native-subagents/0158/probe-beta.jsonl @@ -0,0 +1,3 @@ +{"timestamp":"2026-09-28T14:25:29.140Z","type":"session_meta","payload":{"id":"01a0e868-1019-74d0-a11f-2ad529629759","session_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","parent_thread_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","source":{"subagent":{"thread_spawn":{"parent_thread_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","depth":1,"agent_path":null,"agent_nickname":"Zeno","agent_role":"probe_beta"}}},"thread_source":"subagent","agent_role":"probe_beta","multi_agent_version":"v1"}} +{"timestamp":"2026-09-28T14:25:29.620Z","type":"turn_context","payload":{"turn_id":"01a0e868-1033-7fe0-9bff-870ebb2903ba","model":"gpt-5.6-luna","root_turn_id":"01a0e868-00a1-7eb0-b020-9e70e708c274"}} +{"timestamp":"2026-09-28T14:25:30.720Z","type":"token_usage_record","payload":{"thread_id":"01a0e868-1019-74d0-a11f-2ad529629759","turn_id":"01a0e868-1033-7fe0-9bff-870ebb2903ba","session_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","root_turn_id":"01a0e868-00a1-7eb0-b020-9e70e708c274","response_id":"resp_08e493e0c078508b016aba78d9a8c487d28dd755d4fde1ac67","usage":{"input_tokens":9204,"cached_input_tokens":0,"cache_write_input_tokens":9201,"output_tokens":21,"reasoning_output_tokens":11,"total_tokens":9225},"turn_token_usage":{"input_tokens":9204,"cached_input_tokens":0,"cache_write_input_tokens":9201,"output_tokens":21,"reasoning_output_tokens":11,"total_tokens":9225},"thread_token_usage":{"input_tokens":9204,"cached_input_tokens":0,"cache_write_input_tokens":9201,"output_tokens":21,"reasoning_output_tokens":11,"total_tokens":9225}}} diff --git a/internal/runtime/testdata/codex/native-subagents/0158/root.jsonl b/internal/runtime/testdata/codex/native-subagents/0158/root.jsonl new file mode 100644 index 0000000000..3983db8c1d --- /dev/null +++ b/internal/runtime/testdata/codex/native-subagents/0158/root.jsonl @@ -0,0 +1,8 @@ +{"timestamp":"2026-09-28T14:25:25.154Z","type":"session_meta","payload":{"id":"01a0e868-0083-7571-b0e2-de21c3a6c910","session_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","source":"exec","thread_source":"user"}} +{"timestamp":"2026-09-28T14:25:25.806Z","type":"turn_context","payload":{"turn_id":"01a0e868-00a1-7eb0-b020-9e70e708c274","model":"gpt-5.6-luna","root_turn_id":"01a0e868-00a1-7eb0-b020-9e70e708c274"}} +{"timestamp":"2026-09-28T14:25:27.586Z","type":"token_usage_record","payload":{"thread_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","turn_id":"01a0e868-00a1-7eb0-b020-9e70e708c274","session_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","root_turn_id":"01a0e868-00a1-7eb0-b020-9e70e708c274","response_id":"resp_020f9977bc4bfea2016aba78d5d9f087d2844671455fde0d91","usage":{"input_tokens":9626,"cached_input_tokens":0,"cache_write_input_tokens":9623,"output_tokens":124,"reasoning_output_tokens":48,"total_tokens":9750},"turn_token_usage":{"input_tokens":9626,"cached_input_tokens":0,"cache_write_input_tokens":9623,"output_tokens":124,"reasoning_output_tokens":48,"total_tokens":9750},"thread_token_usage":{"input_tokens":9626,"cached_input_tokens":0,"cache_write_input_tokens":9623,"output_tokens":124,"reasoning_output_tokens":48,"total_tokens":9750}}} +{"timestamp":"2026-09-28T14:25:29.098Z","type":"token_usage_record","payload":{"thread_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","turn_id":"01a0e868-00a1-7eb0-b020-9e70e708c274","session_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","root_turn_id":"01a0e868-00a1-7eb0-b020-9e70e708c274","response_id":"resp_020f9977bc4bfea2016aba78d7ac7887d29be304abed265237","usage":{"input_tokens":16795,"cached_input_tokens":9623,"cache_write_input_tokens":7169,"output_tokens":148,"reasoning_output_tokens":41,"total_tokens":16943},"turn_token_usage":{"input_tokens":26421,"cached_input_tokens":9623,"cache_write_input_tokens":16792,"output_tokens":272,"reasoning_output_tokens":89,"total_tokens":26693},"thread_token_usage":{"input_tokens":26421,"cached_input_tokens":9623,"cache_write_input_tokens":16792,"output_tokens":272,"reasoning_output_tokens":89,"total_tokens":26693}}} +{"timestamp":"2026-09-28T14:25:30.490Z","type":"token_usage_record","payload":{"thread_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","turn_id":"01a0e868-00a1-7eb0-b020-9e70e708c274","session_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","root_turn_id":"01a0e868-00a1-7eb0-b020-9e70e708c274","response_id":"resp_020f9977bc4bfea2016aba78d9347487d2bfa6277c58995313","usage":{"input_tokens":17059,"cached_input_tokens":16792,"cache_write_input_tokens":264,"output_tokens":121,"reasoning_output_tokens":17,"total_tokens":17180},"turn_token_usage":{"input_tokens":43480,"cached_input_tokens":26415,"cache_write_input_tokens":17056,"output_tokens":393,"reasoning_output_tokens":106,"total_tokens":43873},"thread_token_usage":{"input_tokens":43480,"cached_input_tokens":26415,"cache_write_input_tokens":17056,"output_tokens":393,"reasoning_output_tokens":106,"total_tokens":43873}}} +{"timestamp":"2026-09-28T14:25:31.825Z","type":"token_usage_record","payload":{"thread_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","turn_id":"01a0e868-00a1-7eb0-b020-9e70e708c274","session_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","root_turn_id":"01a0e868-00a1-7eb0-b020-9e70e708c274","response_id":"resp_020f9977bc4bfea2016aba78da9a8487d2aee13df83b8f4525","usage":{"input_tokens":17288,"cached_input_tokens":17056,"cache_write_input_tokens":229,"output_tokens":93,"reasoning_output_tokens":9,"total_tokens":17381},"turn_token_usage":{"input_tokens":60768,"cached_input_tokens":43471,"cache_write_input_tokens":17285,"output_tokens":486,"reasoning_output_tokens":115,"total_tokens":61254},"thread_token_usage":{"input_tokens":60768,"cached_input_tokens":43471,"cache_write_input_tokens":17285,"output_tokens":486,"reasoning_output_tokens":115,"total_tokens":61254}}} +{"timestamp":"2026-09-28T14:25:33.284Z","type":"token_usage_record","payload":{"thread_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","turn_id":"01a0e868-00a1-7eb0-b020-9e70e708c274","session_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","root_turn_id":"01a0e868-00a1-7eb0-b020-9e70e708c274","response_id":"resp_020f9977bc4bfea2016aba78dbe69c87d286fe88a958fa9a06","usage":{"input_tokens":17575,"cached_input_tokens":17285,"cache_write_input_tokens":287,"output_tokens":138,"reasoning_output_tokens":16,"total_tokens":17713},"turn_token_usage":{"input_tokens":78343,"cached_input_tokens":60756,"cache_write_input_tokens":17572,"output_tokens":624,"reasoning_output_tokens":131,"total_tokens":78967},"thread_token_usage":{"input_tokens":78343,"cached_input_tokens":60756,"cache_write_input_tokens":17572,"output_tokens":624,"reasoning_output_tokens":131,"total_tokens":78967}}} +{"timestamp":"2026-09-28T14:25:35.205Z","type":"token_usage_record","payload":{"thread_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","turn_id":"01a0e868-00a1-7eb0-b020-9e70e708c274","session_id":"01a0e868-0083-7571-b0e2-de21c3a6c910","root_turn_id":"01a0e868-00a1-7eb0-b020-9e70e708c274","response_id":"resp_020f9977bc4bfea2016aba78dd593087d2ae70bdcfe6072f06","usage":{"input_tokens":17848,"cached_input_tokens":17572,"cache_write_input_tokens":273,"output_tokens":170,"reasoning_output_tokens":39,"total_tokens":18018},"turn_token_usage":{"input_tokens":96191,"cached_input_tokens":78328,"cache_write_input_tokens":17845,"output_tokens":794,"reasoning_output_tokens":170,"total_tokens":96985},"thread_token_usage":{"input_tokens":96191,"cached_input_tokens":78328,"cache_write_input_tokens":17845,"output_tokens":794,"reasoning_output_tokens":170,"total_tokens":96985}}} diff --git a/internal/runtime/testdata/codex/native-subagents/README.md b/internal/runtime/testdata/codex/native-subagents/README.md new file mode 100644 index 0000000000..1bf4d73220 --- /dev/null +++ b/internal/runtime/testdata/codex/native-subagents/README.md @@ -0,0 +1,55 @@ +# Recorded native Codex subagent usage + +Reduced from successful local OpenAI API runs captured on 2026-09-28 with +exact stable Codex CLI versions **0.157.0** (`0157`) and **0.158.0** (`0158`), +model `gpt-5.6-luna`, low reasoning effort, native multi-agent V1, and three +fresh-context children (two named roles and one default role). + +These are recorded fixtures, not fabricated event shapes. Reduction retained +all original `token_usage_record` envelopes and payloads, selected session +identity fields, and `turn_context` turn/model/root-turn fields, in original +order. Envelope timestamps, IDs, models and token counts are unchanged. +Prompts, instructions, cwd, local account/host details, tool calls, and all +other event types were omitted. No credentials were retained. Filenames were +renamed for clarity. Root/child association and per-response counters remain +verbatim. The tests supplement these captures with explicitly synthetic +mutation cases. + +The first incomplete 0.158.0 attempt was **not** used: `0158` is the successful +`children-wait-loop` rerun. The private source corpus names are recorded below +with SHA-256 of the original, unreduced files so provenance can be checked +without committing their contents or local paths. + +Official source archive provenance used to verify the wire types: + +- `rust-v0.157.0`: archive SHA-256 + `10d6b3d485440b6b92d46e20398a940f756bb12a6a98a1daa1932df05937eab7`. +- `rust-v0.158.0`: archive SHA-256 + `e0c6f2492a1afad6ace9101b01a85deb58f81c52ee25af351d3b7478425a3558`. + +| Fixture | Original rollout basename | Original SHA-256 | +| --- | --- | --- | +| `0157/root.jsonl` | `rollout-2026-09-28T10-22-59-01a0e865-c82b-7991-b075-3ad644e16b31.jsonl` | `784ee6fecef9ef5f7caf762615a6a27a790d27f652b8eef764f23168b79d85fe` | +| `0157/probe-alpha.jsonl` | `rollout-2026-09-28T10-23-04-01a0e865-da5f-7f23-a113-86d7a107c3f7.jsonl` | `c4b0f0694533e8716336723ef22173b7af7d91ea76f707287489512f755ece4b` | +| `0157/default.jsonl` | `rollout-2026-09-28T10-23-04-01a0e865-da84-71d3-95bd-ba0f3444eff2.jsonl` | `0bd0aef5d46e97e41aa4154869af6eb87ad89cf822ec190eaa93bbf4f6e0ae56` | +| `0157/probe-beta.jsonl` | `rollout-2026-09-28T10-23-04-01a0e865-daa3-7a71-b355-d76fc45c53f6.jsonl` | `43c6cb4b95f4bce3f4d69e04c44c6fefa1b798f36480fbdfb05be40d3731edc2` | +| `0158/root.jsonl` | `rollout-2026-09-28T10-25-25-01a0e868-0083-7571-b0e2-de21c3a6c910.jsonl` | `d8a5d6e760be4ce32420ea6c02017f345e64d68c6b190665a72eac7101daa186` | +| `0158/probe-alpha.jsonl` | `rollout-2026-09-28T10-25-29-01a0e868-0ff5-7b90-8852-e23f529ca223.jsonl` | `3c6269546850a566ece0dd1914d7338cab0e621a6f49c5263b5771ab208e617d` | +| `0158/probe-beta.jsonl` | `rollout-2026-09-28T10-25-29-01a0e868-1019-74d0-a11f-2ad529629759.jsonl` | `959ab32f90c4ddad81b5abe1703fda58042556d413a01687a8350782e322e359` | +| `0158/default.jsonl` | `rollout-2026-09-28T10-25-29-01a0e868-1037-7123-86da-fdb886715284.jsonl` | `8277c9906fe4e818f124763abd6150747787536773db92b735a7e135ba74ec96` | + +Each version has six parent responses and one response from each child. The +parent stream total excludes children. Fullsend uses disjoint counters: +uncached input, nonreasoning output, reasoning, cache-read, cache-write. + +| Version | Contribution | Uncached input | Nonreasoning output | Reasoning | Cache read | Cache write | Total | +| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | +| 0.157.0 | Parent | 18 | 640 | 137 | 77975 | 17730 | 96500 | +| 0.157.0 | Children | 9 | 24 | 0 | 0 | 27626 | 27659 | +| 0.157.0 | Combined | 27 | 664 | 137 | 77975 | 45356 | 124159 | +| 0.158.0 | Parent | 18 | 624 | 170 | 78328 | 17845 | 96985 | +| 0.158.0 | Children | 9 | 26 | 11 | 0 | 27626 | 27672 | +| 0.158.0 | Combined | 27 | 650 | 181 | 78328 | 45471 | 124657 | + +`Requests` means participating agent invocations: three children, not the +number of response records. Costs are unreported by Codex.