diff --git a/docs/architecture.md b/docs/architecture.md index af834fdd77..6c2d4cefef 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -367,20 +367,27 @@ flowchart TB ([ADR 0158](ADRs/0158-overlays-may-grant-runtime-fetch-within-the-config-allowlist.md)). Decided, not yet implemented. - 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)). -- Decided, not yet implemented: extend the runner-owned native Codex child - policy to V2. Bootstrap requires the `Agent` tool, - harness security and a direct-route parent selecting V1 or V2 in the bundled - model catalog (absent means V1); other parents keep delegation off. The - runner binds child models and effort, registers roles and admits only - fresh-context spawns after checking runner-held digests. V2 configuration - removes direct messaging and model overrides, with hook denial as a - backstop; spawn and permitted control calls map to `Agent`. Every child of - a V2 parent inherits V2 tools, so depth one relies on hook enforcement and - its documented fail-open limits. V2 child results must pass the ADR 0100 - PostToolUse chain before entering the parent's context; V2 delegation stays - experimental until this path is implemented and verified live. Aggregate - spawn/admission reconciliation remains after-the-fact detection: unused - admissions or missing/altered child session logs can hide unauthorized spawns +- The runner-owned native Codex child policy covers collaboration V1 and V2. + Bootstrap requires the `Agent` tool, harness security and a direct-route + parent selecting V1 or V2 in the bundled model catalog (absent means V1); + other parents keep delegation off. The runner binds child models and effort, + registers roles and admits only fresh-context spawns after checking + runner-held digests. V2 configuration removes direct messaging, with hook + denial as a backstop, and hides model overrides from the spawn schema, which + only the hook enforces; spawn and permitted control calls map to `Agent`. + Codex gives a child of a V2 parent the V2 tools only when the child's own + model selects V2, so a V2 parent delegates only when no child model does; a + spawn the hook did not screen can still name a model or use a rewritten role + file, and for it depth one rests on the hook. A V2 child's final message + passes the ADR 0100 PostToolUse chain at `SubagentStop`, before Codex + delivers it; a block makes the child continue, told only to reply with a + fixed withheld notice, and nothing else passes for the rest of its turn. + That gate fails open when its hook process fails, an errored child's error + text is not screened, and a child that never replies with the notice runs, + and spends tokens, until the parent interrupts it or the run ends. + Aggregate spawn/admission reconciliation remains after-the-fact + detection: unused admissions or missing/altered child session logs can hide + unauthorized spawns ([ADR 0126](ADRs/0126-fullsend-owned-codex-subagents.md), [ADR 0159](ADRs/0159-codex-subagents-on-collaboration-v2.md), [#6970](https://github.com/fullsend-ai/fullsend/issues/6970)). diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 805d9242dd..49e21ade2e 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -1227,7 +1227,8 @@ flowchart TB misses a last line with no trailing newline) then `sed -n` a long `SKILL.md` in at most 200-line ranges, one per tool call (#7831). A native child runs with its role's `developer_instructions` in place of the parent's, so every role file opens with - `codexChildNote`: the child contract pi gives every child, and the same rule. + `codexChildNote` (`codexChildNoteV2` under a V2 parent): the child contract pi gives every + child, and the same rule. - **AGENTS.md** — codex skips a project's own `AGENTS.md` while the project is untrusted (`codex-rs/core/src/agents_md.rs`), but always loads `$CODEX_HOME/AGENTS.md` as user instructions. The runner copies the repo's root `AGENTS.md` (or the injected org-level one) there @@ -1328,7 +1329,8 @@ Matcher translation, per group: | `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 | -| *(the spawn guard, not a plan group)* | `^(multi_agent_v1\|collaboration)\|(spawn\|resume)_agent$` — a regex (a character outside `[A-Za-z0-9_\|]` makes it one) that reaches both multi-agent namespaces plus the bare V1 `spawn_agent` | `PreToolUse` element 0; admits a V1 `spawn_agent` from the root thread of a registered role, with `fork_context: false` and no `model` or `reasoning_effort`, after re-checking the files in `FULLSEND_CODEX_SPAWN_DIGESTS`; passes the parent's wait, close and send-input calls through and denies them from a child (a payload carrying `agent_id` or `agent_type`); the V2 spawn, `wait_agent`, `list_agents` and `interrupt_agent` stay denied by name, and today Bootstrap declines a V2 parent, so no `collaboration*` call reaches the hook; everything else, its own errors included, exits 2 with a reason. Every admit and deny is logged to `security/findings.jsonl` | +| *(the spawn guard, not a plan group)* | `^(multi_agent_v1\|collaboration)\|(spawn\|resume)_agent$` — a regex (a character outside `[A-Za-z0-9_\|]` makes it one) that reaches both multi-agent namespaces plus the bare V1 `spawn_agent` | `PreToolUse` element 0; admits a V1 `spawn_agent` from the root thread with `fork_context: false`, and a V2 `collaborationspawn_agent` from the root thread with `fork_turns: "none"` and no `fork_context` key, either one with no `model` or `reasoning_effort` key and a registered or absent `agent_type`, after re-checking the files in `FULLSEND_CODEX_SPAWN_DIGESTS`; passes the parent's V1 wait, close and send-input calls and V2 wait, list and interrupt calls through and denies them from a child (a payload carrying `agent_id` or `agent_type`); denies `send_message`, `followup_task`, the resume and every other name; everything else, its own errors included, exits 2 with a reason. Every admit and deny is logged to `security/findings.jsonl` | +| *(the child-result gate, not a plan group)* | *matcher key omitted* (codex matches `SubagentStop` on `agent_type`) | on a run that delegates from a V2 parent, a `SubagentStop` handler for every `PostToolUse` group that covers `Agent` (`*`, `Agent` or `Task`), with that group's scripts. Codex runs it in a thread-spawned child on `last_assistant_message`, the text that becomes the child's result, before the parent is notified; the adapter presents it to the scripts as an `Agent` result. Every block on this phase, a failing script or the adapter's own error included, exits 2 with a fixed prompt to reply with exactly `RESULT WITHHELD BY FULLSEND` (`codexWithheldNotice`) in place of the reason, which goes to `findings.jsonl`, so the child continues instead of finishing; `continue: false` is never emitted, because codex would end the child and deliver the message. Once a block has set `stop_hook_active`, only that exact notice passes for the rest of the child's turn and the chain does not run. Before a block, an empty or null message passes and a missing one blocks | Tokens are joined with `|` and stay within `[A-Za-z0-9_|]`, which is the character set codex treats as an **exact alternation** rather than a regex, so there is no anchoring question and no substring @@ -1434,8 +1436,9 @@ at `reserve_spawn_slot` after the guard admitted it and names no child), counted ids plus the items that name none; and the rollouts under the sessions directory whose `session_meta` parent is the primary thread or a counted child, plus any file whose first line is empty, cut before it names a parent, or not a `session_meta` record, under the thread id in its -name, the run's own excepted; such a file is a parent only when the stream names it. A child writes -its rollout at its first recorded item, so a spawn the stream lost is still counted; a previous +name, the run's own excepted; such a file is a parent only when the stream names it. A V2 spawn +emits no stream item (ADR 0159), so a V2 parent's children are counted from their rollouts alone. A +child writes its rollout at its first recorded item, so a spawn the stream lost is still counted; a previous iteration's files and a root the agent's own `codex exec` writes under `CODEX_HOME` are not, unless their first line is empty, cut or 1 MiB or longer. The run fails (`codex_spawn_without_admission`) on a shortfall, a spawn not sent by the primary thread, a spawn item too long to read, an unknown @@ -1623,9 +1626,9 @@ Two artefacts of the run are worth knowing about: | Project trust and `AGENTS.md` | the pinned untrusted entry must still stop codex recording its own trust level, the repo's `.codex/` layer must stay unloaded, and `$CODEX_HOME/AGENTS.md` must still load while the project is untrusted, or the bridge stops reaching the agent | `codex-rs/app-server/src/request_processors/thread_processor.rs` (trust write), `codex-rs/config/src/loader/mod.rs`, `codex-rs/core/src/agents_md.rs`, `codex-rs/codex-home/src/instructions/mod.rs` | | JSONL event structs, rollout line types and rollout file naming | the stream parser and transcript extraction; a rollout line type missing from `codexRolloutEnvelopes` discards the whole transcript | `codex-rs/exec/src/exec_events.rs`, `codex-rs/history/src/rollout_payload.rs` (`RolloutItemWire`), `codex-rs/thread-store/src/local/helpers.rs` | | Stderr warning markers (`dropping in-process server notification (queue full)`, `thread/items/list failed during turn completion`, `thread/items/list returned a repeated cursor during turn completion`, and the prefix `thread/read failed while backfilling turn items`), their log targets and levels, and the `RUST_LOG` filter (`error,opentelemetry_sdk=off,opentelemetry_otlp=off,codex_exec=warn,codex_app_server::in_process=warn`; `info` with debug) | `codexStderrDrops` and the debug-log counts match these literals; changed text, targets, levels or filter semantics can silently stop the dropped-notification and failed-backfill warnings | `codex-rs/exec/src/lib.rs` (backfill `warn!` calls, `EXEC_DEFAULT_LOG_FILTER`), `codex-rs/app-server/src/in_process.rs` (drop `warn!` call) | -| The multi-agent tool names (`multi_agent_v1*`, `collaboration*`, the bare V1 `spawn_agent`), the block contract (exit 2 with non-empty stderr blocks; a timeout kills the handler and lets the call through), `agent_id` and `agent_type` in a child's payload, the spawn arguments, and what a child start rereads (`hooks.json` and the role file) | the spawn guard's matcher, pass-through set, policy, digest set and deadline rest on them; a renamed tool is denied (loud), but a payload without `agent_id` or `agent_type`, a new model or effort argument, a changed block contract or a child that rereads another file turns a deny into a pass | `codex-rs/core/src/tools/handlers/multi_agents_spec.rs`, `codex-rs/core/src/tools/registry.rs` (`function_hook_tool_name`), `codex-rs/hooks/src/engine/command_runner.rs` (the timeout branch), `codex-rs/core/src/agent/role.rs` (the role file, read at spawn) | -| The bundled catalog's `multi_agent_version`, `default_reasoning_level` and `supported_reasoning_levels` entries, the version codex supplies to an entry that carries none, and the floor model (`codex debug models --bundled`; at 0.166.0 `gpt-5.6-luna` is the listed model that selects `v1` and defaults to `medium`, and `gpt-5.5` carries no version, which the `multi_agent` feature, on by default, resolves to V1, and lists `low` to `xhigh`) | part two of the delegation gate, the child-model floor and the child-effort check rest on them: the floor must stay listed, or every delegating agent without `subagents.default` or `FULLSEND_CODEX_SUBAGENT_MODEL` fails Bootstrap, while the floor's own collaboration version does not matter for children (a child runs under its parent's; moving luna to V2 only stops luna parents from delegating); a bump that turns `multi_agent` off by default, or gives the null entry a version, changes which parents delegate; a changed level set changes which run efforts Bootstrap accepts; and the fixture `internal/runtime/testdata/codex/models-bundled-0.166.0.json` must be regenerated, never edited | `codex-rs/models-manager/models.json` in the bumped tag; regenerate the fixture with the one-liner in `codex_personas_test.go`'s `TestCodexCatalog` comment and run `go test ./internal/runtime/ -run 'TestCodexCatalog\|TestCodexParentCollabVersion\|TestResolveCodexChildModels_Effort'` | +| The multi-agent tool names (`multi_agent_v1*`, `collaboration*`, the bare V1 `spawn_agent`), the block contract (exit 2 with non-empty stderr blocks; a timeout kills the handler and lets the call through), `agent_id` and `agent_type` in a child's payload, the spawn arguments, and what a child start rereads (`hooks.json` and the role file) | the spawn guard's matcher, pass-through set, policy, digest set and deadline rest on them; a renamed tool is denied (loud), but a payload without `agent_id` or `agent_type`, a new model or effort argument, a changed `fork_turns` reading, a changed block contract or a child that rereads another file turns a deny into a pass | `codex-rs/core/src/tools/handlers/multi_agents_spec.rs`, `codex-rs/core/src/tools/handlers/multi_agents_v2/spawn.rs` (`SpawnAgentArgs::fork_mode`, which the hook's `_is_none_fork` mirrors), `codex-rs/core/src/tools/registry.rs` (`function_hook_tool_name`), `codex-rs/hooks/src/engine/command_runner.rs` (the timeout branch), `codex-rs/core/src/agent/role.rs` (the role file, read at spawn) | +| The bundled catalog's `multi_agent_version`, `default_reasoning_level` and `supported_reasoning_levels` entries, the version codex supplies to an entry that carries none, and the floor model (`codex debug models --bundled`; at 0.166.0 `gpt-5.6-luna` is the listed model that selects `v1` and defaults to `medium`, and `gpt-5.5` carries no version, which the `multi_agent` feature, on by default, resolves to V1, and lists `low` to `xhigh`) | part two of the delegation gate, the child-model floor and the child-effort check rest on them: the floor must stay listed, or every delegating agent without `subagents.default` or `FULLSEND_CODEX_SUBAGENT_MODEL` fails Bootstrap, while the floor's own collaboration version matters only under a V2 parent, which delegates only while no child model selects V2 (moving luna to V2 would stop every V2 parent on the default child model from delegating); a bump that turns `multi_agent` off by default, or gives the null entry a version, changes which parents delegate; a changed level set changes which run efforts Bootstrap accepts; and the fixture `internal/runtime/testdata/codex/models-bundled-0.166.0.json` must be regenerated, never edited | `codex-rs/models-manager/models.json` in the bumped tag; regenerate the fixture with the one-liner in `codex_personas_test.go`'s `TestCodexCatalog` comment and run `go test ./internal/runtime/ -run 'TestCodexCatalog\|TestCodexParentCollabVersion\|TestCodexV2ChildModelReason\|TestResolveCodexChildModels_Effort'` | | The `[agents]` keys codex reads (`enabled`, `max_concurrent_threads_per_session`, `max_depth`, `default_subagent_model`, `default_subagent_reasoning_effort`, and `[agents.]` `description` and `config_file`) and the order of the child path: with no model argument a child takes `default_subagent_model` and, with no effort argument, `default_subagent_reasoning_effort`, else that model's catalog default; a role file applies after and its effort is checked against its own model | `codexAgentsBlock` writes the keys and Bootstrap checks the child efforts on that order; a renamed key or a changed order silently changes every child's model or effort | `codex-rs/config/src/config_toml.rs` (`AgentsToml`), `codex-rs/core/src/config/mod.rs`, `codex-rs/core/src/agent/child_config.rs` (`apply_requested_spawn_agent_model_overrides`, `apply_spawn_agent_role`), `codex-rs/core/src/agent/role.rs` | | What writes a rollout under the sessions directory in an exec run, rollout naming and the date layout, creation at a child's first recorded item, a PreToolUse block returning before the tool handler, and spawn-slot reservation before thread creation | the disk side of the admission cross-check (the four facts are in `internal/runtime/testdata/codex/README.md`) | `codex-rs/core/src/tools/registry.rs`, `codex-rs/core/src/agent/control/spawn.rs`, `codex-rs/rollout/src/rollout_file_name.rs`, `codex-rs/features/src/lib.rs` (the memories default) | -| The `enabled`, `disable_direct_message`, `expose_spawn_agent_model_overrides` and `max_concurrent_threads_per_session` keys of the `[features.multi_agent_v2]` table (codex parses it with `deny_unknown_fields`) and how codex derives the V2 child cap: the table's own key, else `[agents] max_concurrent_threads_per_session + 1`, else 4, minus one at reservation | ADR 0159 keeps the four-child cap under `[agents]`; once V2 parents delegate, a changed derivation silently gives a V2 parent three or five children, and once the runner renders the table, a renamed table key fails every run's config | `codex-rs/core/src/config/mod.rs` (`resolve_multi_agent_v2_config`, `effective_agent_max_threads`), `codex-rs/features/src/feature_configs.rs` (`MultiAgentV2ConfigToml`), codex's test `multi_agent_v2_uses_agents_max_concurrent_threads_per_session` in `codex-rs/core/src/config/config_tests.rs` | -| The V2 child-result delivery path: `notify_parent_of_terminal_turn` queues a terminal result to the parent, `record_inter_agent_communication` records it, and it reaches the parent's next model request as an `agent_message` item; at 0.166.0 no hook event, config key or app-server method reachable from `codex exec` withholds it before codex records it, and `SubagentStop` treats a deny as a request for the child to continue | ADR 0159 decision 4 requires every V2 child result to pass the ADR 0100 PostToolUse chain before it enters the parent's context, and Bootstrap declines V2 parents until a checked delivery path for those results is implemented and verified live; re-check on every bump whether codex offers a synchronous, fail-closed gate on this path | `codex-rs/core/src/agent/control/completion.rs`, `codex-rs/core/src/session/handlers.rs`, `codex-rs/core/src/hook_runtime.rs` (`inspect_pending_input`), `codex-rs/core/src/session/mod.rs` (`record_inter_agent_communication`), `codex-rs/hooks/src/events/stop.rs` | +| The `enabled`, `disable_direct_message`, `expose_spawn_agent_model_overrides` and `max_concurrent_threads_per_session` keys of the `[features.multi_agent_v2]` table (codex parses it with `deny_unknown_fields`) and how codex derives the V2 child cap: the table's own key, else `[agents] max_concurrent_threads_per_session + 1`, else 4, minus one at reservation | ADR 0159 keeps the four-child cap under `[agents]`; a changed derivation silently gives a V2 parent three or five children, and the runner renders the table on every run (`enabled`, plus `disable_direct_message` and `expose_spawn_agent_model_overrides` for an admitted V2 parent), so a renamed key fails the config of every run that renders it; a changed `collab_tools_enabled` changes which children of a V2 parent get the multi-agent tools (at 0.166.0 only a child whose own model selects V2), and the V2 spawn's backstop, a V2 parent delegating only while no child model selects V2 (`codexV2ChildModelReason`), rests on it | `codex-rs/core/src/config/mod.rs` (`resolve_multi_agent_v2_config`, `effective_agent_max_threads`), `codex-rs/features/src/feature_configs.rs` (`MultiAgentV2ConfigToml`), `codex-rs/core/src/tools/spec_plan.rs` (`collab_tools_enabled`), codex's test `multi_agent_v2_uses_agents_max_concurrent_threads_per_session` in `codex-rs/core/src/config/config_tests.rs` | +| The V2 child-result path: `SubagentStop` runs in a thread-spawned child with `last_assistant_message`, the text that becomes its result, before the turn completes and `notify_parent_of_terminal_turn` queues the result to the parent; exit 2 with a non-empty stderr makes the child continue with that stderr as its prompt (an empty one is ignored and the message delivered), `continue: false` ends the child and delivers the message, and the result reaches the parent's next model request as an `agent_message` item, which codex sends only from a thread on V2: the feature table must keep putting every thread of the run on V2, whatever the child's model | the child-result gate (ADR 0159 decision 4) rests on it: re-check on every bump that `SubagentStop` still runs before the result is delivered, that a block still continues the child, and that the hook runs after a block still carry `stop_hook_active: true` for the rest of the turn; if either of the first two changes, a flagged result reaches the parent unchecked, and if the third does, a blocked child can retry through the chain | `codex-rs/core/src/session/turn.rs` (the stop-hook block), `codex-rs/core/src/hook_runtime.rs` (`run_turn_stop_hooks`), `codex-rs/hooks/src/events/stop.rs`, `codex-rs/core/src/agent/control/completion.rs`, `codex-rs/core/src/session/mod.rs` (`record_inter_agent_communication`); run `go test ./internal/runtime/ -run 'TestCodexAdapter_SubagentStopGate'` | diff --git a/docs/runtimes.md b/docs/runtimes.md index df2e64d728..82f6703fff 100644 --- a/docs/runtimes.md +++ b/docs/runtimes.md @@ -55,7 +55,7 @@ sequenceDiagram | | Claude Code | pi | codex | |---|---|---|---| | Models | Anthropic on Vertex; any Messages-capable model through an [inference gateway](runtimes/claude.md#inference-gateway-route) (`gateway/`) | Claude, **Grok** and **Gemini** on Vertex; **GPT** via OpenAI WIF (opt-in, [not yet exercised live](runtimes/pi.md#models-and-providers)) | **GPT**, via OpenAI WIF ([not yet exercised live](runtimes/codex.md#not-yet-exercised)); any Responses-capable model through an [inference gateway](runtimes/codex.md#models-through-an-inference-gateway-experimental) (`gateway/`, experimental) | -| Sub-agents | Native (`Agent` tool) | `Agent`/`Task` via a fullsend extension | Native Codex children under a runner-owned policy, for an agent whose tools include `Agent` (or that declares no `tools:`), with harness security on, on a parent model Codex resolves to collaboration V1 on the direct route ([Sub-agents](runtimes/codex.md#sub-agents)) | +| Sub-agents | Native (`Agent` tool) | `Agent`/`Task` via a fullsend extension | Native Codex children under a runner-owned policy, for an agent whose tools include `Agent` (or that declares no `tools:`), with harness security on, on a parent model Codex resolves to collaboration V1 or V2 on the direct route ([Sub-agents](runtimes/codex.md#sub-agents)) | | Default alias models | `opus`/`sonnet`/`haiku` → `claude-*-5-5`, passed as the id; `fable` by Claude Code's own table; sub-agent frontmatter resolved by Claude Code | `opus`/`sonnet`/`haiku` → `claude-*-5-5`, `fable` → `claude-fable-5-1`, children included | Not applicable — OpenAI models only | | Fallback model chain | Alias requests retried by the runner when Vertex does not serve the model (Claude Code's own "model not available" result naming the model, or Vertex's [two 404/403 messages](runtimes/claude.md#models)): `FULLSEND_FALLBACK_MODELS`, else the alias's built-in chain (`opus` → `claude-opus-4-6`, `sonnet` → `claude-sonnet-4-6`, `haiku` → `claude-haiku-4-5`); only an explicit `FULLSEND_FALLBACK_MODELS` is also passed as `--fallback-model`, never the built-in chain; pinned ids, retargets and sub-agents fail loudly | The same chain, same provider only; sub-agent children asking for an alias use its built-in chain; pinned ids and retargets fail loudly | Ignored with a warning | | Roles | All | All; `review`/`retro` at `--thinking medium` by default | Same recommendation as before until a fleet-shaped run completes ([Sub-agents](runtimes/codex.md#sub-agents)) | diff --git a/docs/runtimes/codex.md b/docs/runtimes/codex.md index fa1eb3e6ef..9b9f6a12ac 100644 --- a/docs/runtimes/codex.md +++ b/docs/runtimes/codex.md @@ -162,8 +162,10 @@ in the sandbox) and fails naming the position that supplied an unlisted id: Code run-level default only at each spawn and a role-file model not at all. A listed model the provider does not serve still fails that child at its first request: it ends `errored`, no other model is substituted, and the parent treats that role as failed. The floor is `gpt-5.6-luna`, the cheap -gpt-5.6 tier #6970 chose; it must be listed in the bundled catalog, and its collaboration version -does not matter, because a child runs under its parent's. The runner reads `FULLSEND_CODEX_SUBAGENT_MODEL` from its own +gpt-5.6 tier #6970 chose; it must be listed in the bundled catalog. Under a V1 parent a child +model's collaboration version does not matter, because a child runs under its parent's; under a V2 +parent, a child model that selects V2 makes the parent run in one context (see +[Sub-agents](#sub-agents)). The runner reads `FULLSEND_CODEX_SUBAGENT_MODEL` from its own environment: you set it for a local `fullsend run`, and on GitLab a project or group CI/CD variable reaches it, since the job runs `fullsend run` in its own environment. The GitHub fleet workflows do not pass it, and unlike `FULLSEND_CODEX_MODEL` it is not read from repository variables, so on that @@ -189,8 +191,9 @@ subagents: effort → high (from the run's effort; every child) An agent whose `tools:` frontmatter includes `Agent` (or its alias `Task`), or declares no `tools:` at all, runs its sub-agents as native Codex children when harness security is enabled and Codex -resolves its parent model to collaboration V1 on the direct route (see the end of this section). Bootstrap registers -one role per persona it discovers under the uploaded skills' `sub-agents/*.md`, plus a generic +resolves its parent model to collaboration V1 or V2 on the direct route (see the end of this +section). Bootstrap registers one role per persona it discovers under the uploaded skills' +`sub-agents/*.md`, plus a generic `default` role for a task that names no persona and an instruction-only `explore` role for a skill's `Explore` pass (nothing enforces read-only on a child). The roster is not a fixed list: the runtime note at the end of the agent's instructions names it (`Registered sub-agent roles: @@ -198,28 +201,59 @@ the runtime note at the end of the agent's instructions names it (`Registered su `Agent` out, and any run with harness security disabled, keeps Codex's multi-agent tools off and runs in one context, as before. -A child gets no copy of the parent's conversation (`fork_context: false`): it starts from its -role's instructions and the message its parent sends. At most four are open at once, and the depth -is one. A runner-owned hook admits a spawn only for a registered role with `fork_context: -false` and no model or effort override; it denies resume, Codex's built-in `explorer` and -`worker`, and any spawn from a child. A denied spawn is final for that role: the parent runs that +A child gets no copy of the parent's conversation (`fork_context: false` on V1, `fork_turns: +"none"` on V2): it starts from its role's instructions and the message its parent sends. At most +four are open at once on V1, where a finished child holds its slot until it is closed, and four +run at once on V2; the depth is one. A runner-owned hook admits a spawn only for a registered +role with that fresh context and no model or effort override; it denies resume, V2's message and +follow-up calls, Codex's built-in `explorer` and `worker`, and any spawn from a child. A denied +spawn is final for that role: the parent runs that sub-agent definition itself. A spawn the hook did not admit fails the run after the fact, within the limits named in [Troubleshooting](#troubleshooting): per iteration the runner counts the spawns seen in the event stream or in the children's rollouts on disk, each child once, and compares the run's total with the admissions the hook recorded. Every child's rollout is saved and redacted like the parent's, and its tokens are in `metrics.json` (see [At a glance](#at-a-glance)). -Delegation needs a parent model Codex resolves to collaboration V1: its entry in -the pinned CLI's bundled catalog selects V1, or carries no version and Codex's -`multi_agent` feature, on by default, supplies V1 (on the current pin -`gpt-5.6-luna`, `gpt-5.5` and a hidden catalog entry). Bootstrap reads that -catalog. [ADR 0159](../ADRs/0159-codex-subagents-on-collaboration-v2.md) admits -a parent that selects V2 (`gpt-5.6-sol`, `gpt-6.1-sol` and most of the current -catalog). Such a parent still runs in one context, because its child results -would reach it outside the PostToolUse chain. Bootstrap prints one line saying -so (`sub-agents: parent model "gpt-5.6-sol" selects collaboration "v2"; V2 -delegation is off until its child-result delivery path is verified live -(ADR 0159), running in one context`). A model the catalog does not list runs +Delegation needs a parent model Codex resolves to collaboration V1 or V2: its +entry in the pinned CLI's bundled catalog selects V1 or V2, or carries no +version and Codex's `multi_agent` feature, on by default, supplies V1. On the +current pin `gpt-5.6-luna`, `gpt-5.5` and a hidden catalog entry are V1, and +`gpt-5.6-sol`, `gpt-6.1-sol` and the rest are V2. Bootstrap reads that +catalog ([ADR 0159](../ADRs/0159-codex-subagents-on-collaboration-v2.md)). + +On V2 a child's result reaches the parent as a message rather than as a tool +result, so a `SubagentStop` hook runs the PostToolUse chain on the child's +final message, as an `Agent` result, before Codex delivers it. When the chain +blocks, the child does not finish: it continues with a fixed prompt to reply +with exactly `RESULT WITHHELD BY FULLSEND`, which does not say what was +flagged (the reason goes to the findings log), and for the rest of that turn +only that exact notice passes, so the child cannot reword a flagged result +until one gets through. The V2 parent's runtime note treats that notice as a +coverage gap for that role. Three limits remain: + +- The gate fails open when the hook process itself fails (an exit other than 0 + or 2, a timeout, or a failure to start), like every Codex hook, and a child + started by a spawn the spawn hook did not screen may run without it. A + script that fails inside the gate is a block, not a pass. +- An errored child's result is the provider's error text, and no hook runs on + it. +- A child that never replies with the notice keeps running, and spending + tokens, until the parent interrupts it or the run ends. + +Codex applies no `agents.max_depth` on V2, and gives a child of a V2 parent +the multi-agent tools only when the child's own model selects V2. So a V2 +parent delegates only when neither the run-level child model nor any persona +model selects V2; otherwise it runs in one context with a line that names the +model (`sub-agents: child model "gpt-6.1-terra" (the run-level child model) +selects collaboration "v2", so under a V2 parent its children would keep +codex's spawn tool, running in one context`). The floor, `gpt-5.6-luna`, +selects V1. A child the runner starts on a model off V2 holds no +`spawn_agent`. A spawn the hook did not screen could still name a V2 model or +use a rewritten role file; for such a spawn, depth one rests on the hook, as +ADR 0159 accepts, and the admission check above finds a breach only after the +fact. + +A parent model the catalog does not list runs in one context the same way (`sub-agents: parent model "gpt-5.6-nova" is not in the bundled catalog of the pinned codex, running in one context`), and so does an entry whose `multi_agent_version` is `disabled`, with a line that says @@ -238,9 +272,9 @@ serve, and native children have not been run on that route. | 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)). A `gateway/` model uses the inference gateway's credential the same way ([Models through an inference gateway](#models-through-an-inference-gateway-experimental)) | | 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` for the root thread and `transcripts/-sub-.jsonl` for each native child (`generic` for the `default` role, which codex records as no role when the spawn names no `agent_type`; `explore` keeps its name), `metrics.json` with `runtime: codex` (and `per_model_usage` for a delegating agent), 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 | -| Sub-agents | Native Codex children for an agent whose tools include `Agent` (or that declares no `tools:`), with harness security on, on a parent model Codex resolves to collaboration V1 on the direct route, under a runner-owned policy: registered roles only, fresh context, depth one, four open; see [Sub-agents](#sub-agents) | +| Sub-agents | Native Codex children for an agent whose tools include `Agent` (or that declares no `tools:`), with harness security on, on a parent model Codex resolves to collaboration V1 or V2 on the direct route, under a runner-owned policy: registered roles only, fresh context, depth one, four at once, and on V2 each child's result checked before the parent receives it; see [Sub-agents](#sub-agents) | | Extra knobs | `FULLSEND_CODEX_MODEL` (the runner-side model default for codex runs; see [Models](#models)), `FULLSEND_CODEX_SUBAGENT_MODEL` (the run-level child model; the GitHub fleet workflows do not pass it; see [Child models](#child-models)) | -| Not supported | `plugins:`, fallback chains, non-OpenAI providers (other than through a Responses-capable inference gateway), Chat Completions or Messages on a gateway, delegation from a parent model on collaboration V2 (ADR 0159 admits it; off until its child-result delivery path is implemented and verified live) or from a `gateway/` parent (see [Sub-agents](#sub-agents)) | +| Not supported | `plugins:`, fallback chains, non-OpenAI providers (other than through a Responses-capable inference gateway), Chat Completions or Messages on a gateway, delegation from a `gateway/` parent, or from a V2 parent with a V2 child model (see [Sub-agents](#sub-agents)) | Cost is recorded as **zero** in `metrics.json` on codex: the `codex exec --json` stream carries no cost field, so the value stays `0`. @@ -416,8 +450,8 @@ agents: runtime: claude ``` -**`code` and `fix` delegate too.** They declare no `tools:`, so on a V1 parent on the direct route with harness security -on they get the `default` and `explore` roles, children with the parent's shell and `apply_patch`, +**`code` and `fix` delegate too.** They declare no `tools:`, so on a V1 or V2 parent on the +direct route with harness security on they get the `default` and `explore` roles, children with the parent's shell and `apply_patch`, the spawn guard and the dispatch note, as `review` does. Both have run end to end that way on `gpt-5.6-luna` and chose not to spawn, so neither has run a native child yet. diff --git a/internal/runtime/codex_bootstrap.go b/internal/runtime/codex_bootstrap.go index 3486f32ae0..fb68980ad1 100644 --- a/internal/runtime/codex_bootstrap.go +++ b/internal/runtime/codex_bootstrap.go @@ -66,8 +66,9 @@ type codexHookGroup struct { // guard cannot run. No mapped call has that backstop: an allowlist that // permits Agent passes them all and the spawn guard is their only name-level // check. The V1 spawn still sits under codex's agents.max_depth; the V2 spawn -// does not (#9085), so V2 admission needs a backstop of its own before -// Bootstrap accepts a V2 parent. codex joins namespace and name with no +// does not (#9085); its backstop is that the runner starts a V2 parent's +// children only on models off V2, which get no multi-agent tools +// (codexV2ChildModelReason). codex joins namespace and name with no // separator (codex-rs/core/src/tools/registry.rs function_hook_tool_name); // only the default and multi_agent_v1 namespaces keep the bare spawn_agent. var codexAgentToolNames = []string{ @@ -178,22 +179,26 @@ func (r CodexRuntime) Bootstrap(input BootstrapInput) error { // CLI's catalog: the gate takes the collaboration version from the entry // of the model Run will launch, V1 when the entry selects V1 or carries // no version (codex's multi_agent feature, on by default, supplies V1) - // and V2 when it selects V2. Only a V1 parent delegates: the gate reads - // the version, not the reason. Only the change that renders the V2 - // config and the checked child-result delivery path widens the gate to V2, - // once that path is verified live (ADR 0159 decision 4). A V2, disabled, - // unknown-version, unlisted or gateway/ parent is declined with its own + // and V2 when it selects V2. A V1 or V2 parent delegates: the gate reads + // the version, not the reason. A V2 child's result passes the PostToolUse + // chain at SubagentStop before codex delivers it (codexHooksJSON, ADR 0159 + // decision 4), and a V2 parent delegates only while no child model selects + // V2 (codexV2ChildModelReason). Bootstrap passes the version on to the + // roles, the developer instructions and the config, which take their V2 + // forms for a V2 parent. A disabled, unknown-version, unlisted or gateway/ + // parent, and a V2 parent with a V2 child model, is declined with its own // explanation, keeps the multi-agent tools off and runs in one context, // as an agent that does not delegate does. _, securityOn := input.(SandboxHooksBootstrap) var catalog codexCatalog - delegating := false + delegating, collab := false, "" if codexDelegates(def, securityOn) { if catalog, err = codexPreflightCatalog(sandboxName); err != nil { return err } - version, reason := codexParentCollabVersion(catalog, input.ParentModel(), def.Model) - if delegating = version == "v1"; !delegating { + var reason string + collab, reason = codexParentCollabVersion(catalog, input.ParentModel(), def.Model) + if delegating = collab == "v1" || collab == "v2"; !delegating { fmt.Fprintf(os.Stderr, "sub-agents: %s, running in one context\n", reason) } } @@ -201,18 +206,24 @@ func (r CodexRuntime) Bootstrap(input BootstrapInput) error { var roles []codexRole defaultSubagentModel, childEffort := "", "" if delegating { - discovered, skipped := codexRoles(input.SkillDirs(), agentName) + discovered, skipped := codexRoles(input.SkillDirs(), agentName, collab) roles, defaultSubagentModel, childEffort, err = resolveCodexChildModels( discovered, skipped, input.AgentSubagents(), os.Getenv(codexSubagentModelEnv), input.Effort(), catalog) if err != nil { return err } + if reason := codexV2ChildModelReason(catalog, roles, defaultSubagentModel); collab == "v2" && reason != "" { + fmt.Fprintf(os.Stderr, "sub-agents: %s, running in one context\n", reason) + delegating, roles = false, nil + } } // The gateway provider is rendered only when the runner registered an // inference.gateway block for this sandbox (PrepareGatewayRun). gatewayBaseURL := codexGatewayRunFor(sandboxName) + multiAgentV2 := delegating && collab == "v2" configTOML, err := renderCodexConfig(cfg, repoInput.RepoDir(), - codexDeveloperInstructions(agentName, def, roles), gatewayBaseURL, roles, defaultSubagentModel, childEffort) + codexDeveloperInstructions(agentName, def, roles, collab), gatewayBaseURL, roles, defaultSubagentModel, childEffort, + multiAgentV2) if err != nil { return err } @@ -308,7 +319,7 @@ func (r CodexRuntime) Bootstrap(input BootstrapInput) error { if err != nil { return err } - hooksJSON, notes, err := codexHooksJSON(cfg, python, hooks) + hooksJSON, notes, err := codexHooksJSON(cfg, python, hooks, multiAgentV2) if err != nil { return err } @@ -377,8 +388,10 @@ func codexExecOK(sandboxName, cmd, what string) error { // prompt and tool guidance — the same relationship pi's APPEND_SYSTEM.md has, // and a deliberate difference from Claude Code, where the body *is* the system // prompt. roles is the registered roster of a delegating agent; empty means -// the agent runs in one context and gets codexNoSubagentNote. -func codexDeveloperInstructions(agentName string, def *piAgentDef, roles []codexRole) string { +// the agent runs in one context and gets codexNoSubagentNote. version is +// the collaboration version the gate admitted, which picks the dispatch +// note. +func codexDeveloperInstructions(agentName string, def *piAgentDef, roles []codexRole, version string) string { var b strings.Builder fmt.Fprintf(&b, "# Agent: %s\n\n", agentName) if def.Description != "" { @@ -390,7 +403,7 @@ func codexDeveloperInstructions(agentName string, def *piAgentDef, roles []codex if len(roles) == 0 { b.WriteString(codexNoSubagentNote) } else { - b.WriteString(codexSubagentNote(roles)) + b.WriteString(codexSubagentNote(roles, version)) } return b.String() } @@ -399,8 +412,9 @@ func codexDeveloperInstructions(agentName string, def *piAgentDef, roles []codex // skills written for Claude Code's Agent tool (pr-review, retro) take their // single-context path deliberately instead of recording a failed dispatch. // Every agent the delegation gate declines gets it (tools without Agent, -// security off, or a V2, disabled, unknown-version, unlisted or gateway/ -// parent); a delegating agent gets codexSubagentNote. +// security off, a disabled, unknown-version, unlisted or gateway/ parent, or +// a V2 parent with a V2 child model); a delegating agent gets +// codexSubagentNote. 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 " + @@ -428,24 +442,67 @@ const codexChunkedReadNote = "When reading a SKILL.md or other instruction file, "smaller contiguous windows that together still cover its start through end — never skip " + "the back half — and read those windows before moving on to the next range.\n" +// codexV2DispatchMarker is the sentence that marks a V2 note: it comes right +// after "Sub-agents are native Codex children.", the sentence after the +// roster sentence, so the agents repository's skills can tell the two +// dispatch contracts apart on the sentences they key on. +const codexV2DispatchMarker = "Dispatch follows collaboration V2." + // codexSubagentNote is the dispatch bridge for a delegating agent (#6970, -// ADR 0126): it maps the skills' "dispatch a sub-agent" onto codex's native -// tools and states the policy the spawn guard enforces, so the parent passes -// the arguments the guard admits and handles a denial without retrying. The -// first two sentences and the denied-spawn sentence are what the agents -// repository's pr-review skill will key on once its codex wording lands; -// change them only together with that skill. roles is the registered -// roster, sorted by name (codexRoles). The child contract is in every role -// file (codexChildNote), not here. -func codexSubagentNote(roles []codexRole) string { +// ADR 0126, ADR 0159): it maps the skills' "dispatch a sub-agent" onto +// codex's native tools and states the policy the spawn guard enforces, so +// the parent passes the arguments the guard admits and handles a denial +// without retrying. The first two sentences and the denied-spawn sentence +// are what the agents repository's pr-review skill keys on; change them +// only together with that skill. roles is +// the registered roster, sorted by name (codexRoles); version is the +// collaboration version the gate admitted. The V2 note keeps the keyed +// sentences, puts codexV2DispatchMarker right after its third sentence, +// before the dispatch text, and carries V2's spawn arguments and control +// calls (ADR 0159 decision 5). It quotes codexWithheldNotice, the result a +// child whose final message the chain blocked is told to give instead. The +// child contract is in every role file (codexChildNote, codexChildNoteV2), +// not here. +func codexSubagentNote(roles []codexRole, version string) string { names := make([]string, len(roles)) for i, role := range roles { names[i] = role.Name } - return "\n## Runtime note\n\n" + + head := "\n## Runtime note\n\n" + "This agent runs on the codex runtime (FULLSEND_RUNTIME=codex). " + "Registered sub-agent roles: " + strings.Join(names, ", ") + ". " + - "Sub-agents are native Codex children. When a skill says to dispatch a sub-agent, call " + + "Sub-agents are native Codex children. " + const denied = "A denied spawn is final for that role: do not retry it, execute that sub-agent " + + "definition yourself with the same context package, and treat the output as that " + + "sub-agent's result.\n\n" + if version == "v2" { + return head + codexV2DispatchMarker + " " + + "When a skill says to dispatch a sub-agent, call `spawn_agent` with `task_name` set to a short " + + "name for the task, unique among the children you spawn (lowercase letters, digits and `_` " + + "only; `root` is reserved), " + + "`agent_type` set to a role listed above — the persona's name, or `explore` " + + "where the skill asks for an `Explore` pass (instruction-only; nothing enforces read-only on " + + "a child); for a task that names no persona, omit `agent_type` — and `message` carrying that " + + "sub-agent's whole context package: a child starts with nothing but that message. Pass " + + "`fork_turns: \"none\"` explicitly on every spawn, and never pass a `model`, `reasoning_effort` " + + "or `fork_context` argument: the runner has bound each role's model. Use only the roles " + + "listed above; `explorer` and `worker` are not registered and are denied. Spawn only the " + + "sub-agents the skill selected; a role being registered is not a reason to spawn it.\n\n" + + "`wait_agent` takes only `timeout_ms` and never a target. A child's result arrives as a " + + "message in your conversation, one per finished child, through the runner's checked delivery " + + "path, not in the wait's result. At most four children can run at once: a fifth spawn is " + + "refused while four are running, and Codex evicts an idle finished child when a new spawn " + + "needs its slot. There is no close or follow-up call: never resume, message or follow up a " + + "child. Interrupt a child that is over its budget with `interrupt_agent`. An interrupted " + + "child sends no result: report a coverage gap for that role. A child whose result reports " + + "an error is final for that role. A message whose payload is `" + codexWithheldNotice + + "`, ignoring whitespace around it, is a withheld result: report a coverage gap for " + + "that role, and never retry the spawn or read the child's raw rollout. " + + denied + + codexChunkedReadNote + } + return head + + "When a skill says to dispatch a sub-agent, call " + "`spawn_agent` with `agent_type` set to a role listed above — the persona's name, or `explore` " + "where the skill asks for an `Explore` pass (instruction-only; nothing enforces read-only on " + "a child); for a task that names no persona, omit `agent_type` — and `message` carrying that " + @@ -460,9 +517,7 @@ func codexSubagentNote(roles []codexRole) string { "child you spawned and never resume one. A `wait_agent` that returns `timed_out: true` and " + "no status has timed out, not failed: call it again. A child whose status is `errored` is " + "final for that role. " + - "A denied spawn is final for that role: do not retry it, execute that sub-agent " + - "definition yourself with the same context package, and treat the output as that " + - "sub-agent's result.\n\n" + + denied + codexChunkedReadNote } diff --git a/internal/runtime/codex_bootstrap_test.go b/internal/runtime/codex_bootstrap_test.go index 97336dfe42..3df29520cf 100644 --- a/internal/runtime/codex_bootstrap_test.go +++ b/internal/runtime/codex_bootstrap_test.go @@ -333,7 +333,7 @@ func TestCodexDeveloperInstructions(t *testing.T) { def, err := parsePiAgent([]byte(codexTestAgentDef)) require.NoError(t, err) - got := codexDeveloperInstructions("triage", def, nil) + got := codexDeveloperInstructions("triage", def, nil, "v1") assert.Contains(t, got, "# Agent: triage") assert.Contains(t, got, "Inspect an issue.") @@ -927,7 +927,7 @@ func TestCodexRuntimeBootstrap_WritesRoleFilesForADelegatingAgent(t *testing.T) held, ok := lookupRunnerHeldDigests("sb") require.True(t, ok) - want, _ := codexRoles([]string{skill}, "review") + want, _ := codexRoles([]string{skill}, "review", "v1") require.Len(t, held.RoleFiles, len(want)) var names []string for name := range held.RoleFiles { @@ -943,13 +943,13 @@ func TestCodexRuntimeBootstrap_WritesRoleFilesForADelegatingAgent(t *testing.T) } // len(RoleFiles) > 0 exactly when the delegation gate holds: part one -// (security on, tools include Agent) and part two (the gate takes V1 from the -// parent model's entry: it selects V1 or carries no version; a V2 parent is -// declined until ADR 0159 decision 4 is met). With part one failed, no -// catalog is read; with part two failed, the catalog was read and nothing -// else happens: no directory is created, nothing is uploaded and the digest -// set has no role entry. The gpt-5.5 case is the boundary: an entry without -// a version delegates (ADR 0126), so its files are present. +// (security on, tools include Agent) and part two (the gate takes V1 or V2 +// from the parent model's entry: V1 when it selects V1 or carries no +// version; a V2 parent only while no child model selects V2). With part one +// failed, no catalog is read; with part two failed, the catalog was read and +// nothing else happens: no directory is created, nothing is uploaded and the +// digest set has no role entry. The gpt-5.5 case is the boundary: an entry +// without a version delegates (ADR 0126), so its files are present. func TestCodexRuntimeBootstrap_NoRoleFilesWhenTheGateFails(t *testing.T) { t.Setenv(codexSubagentModelEnv, "") skill := t.TempDir() @@ -964,6 +964,10 @@ func TestCodexRuntimeBootstrap_NoRoleFilesWhenTheGateFails(t *testing.T) { v2Def := strings.Replace(codexTestDelegatingAgentDef, "gpt-5.6-luna", "gpt-5.6-sol", 1) unlistedDef := strings.Replace(codexTestDelegatingAgentDef, "gpt-5.6-luna", "gpt-5.6-nova", 1) noVersionDef := strings.Replace(codexTestDelegatingAgentDef, "gpt-5.6-luna", "gpt-5.5", 1) + v2ChildModel := delegating(v2Def, "") + v2ChildModel.agentSubagents = map[string]*string{"default": strp("openai/gpt-6.1-terra")} + v2PersonaModel := delegating(v2Def, "") + v2PersonaModel.agentSubagents = map[string]*string{"correctness": strp("openai/gpt-6.1-terra")} for name, tc := range map[string]struct { input BootstrapInput preflight bool @@ -977,9 +981,11 @@ func TestCodexRuntimeBootstrap_NoRoleFilesWhenTheGateFails(t *testing.T) { "security off, delegating agent": {bootstrapInput{ sandboxName: "sb", agentPath: writeAgentFile(t, codexTestDelegatingAgentDef), agentName: "review", skillDirs: []string{skill}, }, false, false, ""}, - "security on, definition model selects V2": {delegating(v2Def, ""), true, false, `parent model "gpt-5.6-sol" selects collaboration "v2"; V2 delegation is off until its child-result delivery path is verified live (ADR 0159)`}, + "security on, definition model selects V2": {delegating(v2Def, ""), true, true, ""}, + "security on, V2 parent with a V2 child model": {v2ChildModel, true, false, `child model "gpt-6.1-terra" (the run-level child model) selects collaboration "v2", so under a V2 parent its children would keep codex's spawn tool`}, + "security on, V2 parent with a persona's own V2 model": {v2PersonaModel, true, false, `child model "gpt-6.1-terra" (subagents.correctness) selects collaboration "v2", so under a V2 parent that child would keep codex's spawn tool`}, "security on, definition model not in the catalog": {delegating(unlistedDef, ""), true, false, `parent model "gpt-5.6-nova" is not in the bundled catalog of the pinned codex`}, - "security on, run-level V2 model beats a V1 definition": {delegating(codexTestDelegatingAgentDef, "openai/gpt-5.6-sol"), true, false, `parent model "gpt-5.6-sol" selects collaboration "v2"; V2 delegation is off until its child-result delivery path is verified live (ADR 0159)`}, + "security on, run-level V2 model beats a V1 definition": {delegating(codexTestDelegatingAgentDef, "openai/gpt-5.6-sol"), true, true, ""}, "security on, run-level gateway route to a V1 id": {delegating(codexTestDelegatingAgentDef, "gateway/gpt-5.6-luna"), true, false, `parent model "gateway/gpt-5.6-luna" takes the inference gateway route, where native sub-agents are not supported`}, "security on, definition model has no version (gpt-5.5)": {delegating(noVersionDef, ""), true, true, ""}, } { @@ -1145,7 +1151,7 @@ func TestCodexRuntimeBootstrap_RejectsNonOpenAISubagentModel(t *testing.T) { // The check applies to a delegating agent only. An agent without the Agent // tool, any agent with harness security off, and a delegating agent whose -// parent the gate declines (a V2, disabled, unknown-version, unlisted or +// parent the gate declines (a disabled, unknown-version, unlisted or // gateway/ parent) keep codex's multi-agent tools off and ignore subagents // (ADR 0126: "Every other agent runs with Codex's multi-agent tools off"). func TestCodexRuntimeBootstrap_NonDelegatingAgentIgnoresSubagents(t *testing.T) { @@ -1166,9 +1172,9 @@ func TestCodexRuntimeBootstrap_NonDelegatingAgentIgnoresSubagents(t *testing.T) "Agent tool, security off": {bootstrapInput{ sandboxName: "sb", agentPath: writeAgentFile(t, codexTestDelegatingAgentDef), agentName: "review", skillDirs: []string{skill}, agentSubagents: bad, }, false}, - "Agent tool, security on, run-level parent selects V2": {codexHooksBootstrapInput{ + "Agent tool, security on, run-level parent takes the gateway route": {codexHooksBootstrapInput{ bootstrapInput: bootstrapInput{sandboxName: "sb", agentPath: writeAgentFile(t, codexTestDelegatingAgentDef), agentName: "review", - skillDirs: []string{skill}, parentModel: "openai/gpt-5.6-sol", agentSubagents: bad}, + skillDirs: []string{skill}, parentModel: "gateway/gpt-5.6-luna", agentSubagents: bad}, hooks: hooks, }, true}, } { @@ -1200,7 +1206,7 @@ func TestCodexSubagentNote_CarriesTheDispatchContract(t *testing.T) { t.Parallel() roles := []codexRole{{Name: "challenger"}, {Name: "correctness"}, {Name: "default"}, {Name: "explore"}, {Name: "security"}} - got := codexSubagentNote(roles) + got := codexSubagentNote(roles, "v1") assert.True(t, strings.HasPrefix(got, "\n## Runtime note\n\n"), "the heading the pr-review skill looks for") // The first sentence. @@ -1231,6 +1237,89 @@ func TestCodexSubagentNote_CarriesTheDispatchContract(t *testing.T) { assert.NotContains(t, got, "You are a sub-agent", "the child contract is the role file's (codexChildNote), not the parent's") } +// TestCodexSubagentNote_V1IsUnchanged pins the V1 note byte for byte: the +// V2 note changes nothing a V1 parent reads. +func TestCodexSubagentNote_V1IsUnchanged(t *testing.T) { + t.Parallel() + + roles := []codexRole{{Name: "correctness"}, {Name: "default"}, {Name: "explore"}} + want := "\n## Runtime note\n\n" + + "This agent runs on the codex runtime (FULLSEND_RUNTIME=codex). " + + "Registered sub-agent roles: correctness, default, explore. " + + "Sub-agents are native Codex children. When a skill says to dispatch a sub-agent, call " + + "`spawn_agent` with `agent_type` set to a role listed above — the persona's name, or `explore` " + + "where the skill asks for an `Explore` pass (instruction-only; nothing enforces read-only on " + + "a child); for a task that names no persona, omit `agent_type` — and `message` carrying that " + + "sub-agent's whole context package: a child starts with nothing but that message. Pass " + + "`fork_context: false` explicitly on every spawn, and never pass a `model` or " + + "`reasoning_effort` argument: the runner has bound each role's model. Use only the roles " + + "listed above; `explorer` and `worker` are not registered and are denied. Spawn only the " + + "sub-agents the skill selected; a role being registered is not a reason to spawn it.\n\n" + + "At most four children can be open at once, and a finished child keeps its slot until it " + + "is closed. Start up to four, `wait_agent` on one child at a time (one target id per call), " + + "`close_agent` each child once it has reported, then start the remaining ones. Close every " + + "child you spawned and never resume one. A `wait_agent` that returns `timed_out: true` and " + + "no status has timed out, not failed: call it again. A child whose status is `errored` is " + + "final for that role. " + + "A denied spawn is final for that role: do not retry it, execute that sub-agent " + + "definition yourself with the same context package, and treat the output as that " + + "sub-agent's result.\n\n" + + codexChunkedReadNote + assert.Equal(t, want, codexSubagentNote(roles, "v1")) + assert.NotContains(t, want, codexV2DispatchMarker) +} + +// TestCodexSubagentNote_V2CarriesTheDispatchContract pins the V2 note (ADR +// 0159 decision 5): the sentences the agents repository keys on unchanged, +// the marker right after "Sub-agents are native Codex children.", V2's +// spawn arguments, a wait with no target, results as messages, the +// four-slot rule without a close, the interrupt and what an interrupted or +// errored child means, the withheld result quoting codexWithheldNotice, +// codex's task_name rule, and nothing of V1's close-per-child dispatch. +func TestCodexSubagentNote_V2CarriesTheDispatchContract(t *testing.T) { + t.Parallel() + + roles := []codexRole{{Name: "challenger"}, {Name: "correctness"}, {Name: "default"}, {Name: "explore"}, {Name: "security"}} + got := codexSubagentNote(roles, "v2") + + assert.True(t, strings.HasPrefix(got, "\n## Runtime note\n\n"+ + "This agent runs on the codex runtime (FULLSEND_RUNTIME=codex). "+ + "Registered sub-agent roles: challenger, correctness, default, explore, security. "+ + "Sub-agents are native Codex children. "+codexV2DispatchMarker+" "), "the first three sentences, then the marker") + assert.Contains(t, got, "A denied spawn is final for that role: do not retry it, execute that sub-agent "+ + "definition yourself with the same context package, and treat the output as that sub-agent's result.") + assert.NotContains(t, got, "No fullsend sub-agent roster") + + for _, want := range []string{ + "`spawn_agent`", "`task_name`", "`agent_type`", "`message`", + "`explore`", "for a task that names no persona, omit `agent_type`", + "`fork_turns: \"none\"` explicitly on every spawn", + "never pass a `model`, `reasoning_effort` or `fork_context` argument", + "`explorer` and `worker`", + "Spawn only the sub-agents the skill selected", + "`wait_agent` takes only `timeout_ms` and never a target", + "one per finished child", "checked delivery path", + "At most four children can run at once", "a fifth spawn is refused while four are running", + "evicts an idle finished child", "no close or follow-up call", + "Interrupt a child that is over its budget with `interrupt_agent`", + "An interrupted child sends no result: report a coverage gap for that role", + "A child whose result reports an error is final for that role", + "A message whose payload is `" + codexWithheldNotice + "`, ignoring whitespace around it, is a withheld result: report a " + + "coverage gap for that role, and never retry the spawn or read the child's raw rollout.", + "`task_name` set to a short name for the task, unique among the children you spawn (lowercase letters, digits and `_` only; `root` is reserved)", + } { + assert.Contains(t, got, want) + } + for _, unwanted := range []string{ + "`close_agent`", "`fork_context: false`", "keeps its slot until it is closed", "one target id per call", + } { + assert.NotContains(t, got, unwanted) + } + assert.True(t, strings.HasSuffix(got, codexChunkedReadNote), "the chunked-read paragraph, byte-equal") + assert.Equal(t, 1, strings.Count(got, "contiguous ranges of at most 200 lines"), "the chunked-read rule appears once") + assert.NotContains(t, got, "You are a sub-agent", "the child contract is the role file's, not the parent's") +} + func TestCodexDeveloperInstructions_DelegatingAgentGetsTheDispatchNote(t *testing.T) { t.Parallel() @@ -1238,7 +1327,7 @@ func TestCodexDeveloperInstructions_DelegatingAgentGetsTheDispatchNote(t *testin require.NoError(t, err) roles := []codexRole{{Name: "correctness"}, {Name: "default"}, {Name: "explore"}} - got := codexDeveloperInstructions("review", def, roles) + got := codexDeveloperInstructions("review", def, roles, "v1") assert.Contains(t, got, "# Agent: review") assert.Contains(t, got, "Review a pull request.") assert.Contains(t, got, "You are the review agent.") @@ -1246,19 +1335,28 @@ func TestCodexDeveloperInstructions_DelegatingAgentGetsTheDispatchNote(t *testin assert.Contains(t, got, "A denied spawn is final for that role") assert.Contains(t, got, "at most 200 lines") assert.NotContains(t, got, "No fullsend sub-agent roster") + assert.NotContains(t, got, codexV2DispatchMarker) - single := codexDeveloperInstructions("review", def, nil) + single := codexDeveloperInstructions("review", def, nil, "v1") assert.Contains(t, single, "No fullsend sub-agent roster is available") assert.NotContains(t, single, "Registered sub-agent roles") - assert.Equal(t, strings.TrimSuffix(single, codexNoSubagentNote), strings.TrimSuffix(got, codexSubagentNote(roles)), + assert.Equal(t, strings.TrimSuffix(single, codexNoSubagentNote), strings.TrimSuffix(got, codexSubagentNote(roles, "v1")), "the two notes are the only difference") + + // The version picks the dispatch note and nothing else; without a + // roster there is no dispatch note to pick. + v2 := codexDeveloperInstructions("review", def, roles, "v2") + assert.Contains(t, v2, codexV2DispatchMarker) + assert.Equal(t, strings.TrimSuffix(got, codexSubagentNote(roles, "v1")), strings.TrimSuffix(v2, codexSubagentNote(roles, "v2"))) + assert.Equal(t, single, codexDeveloperInstructions("review", def, nil, "v2")) } // TestCodexRuntimeBootstrap_DelegatingAgentRunsNativeChildren is the switch: // with the Agent tool, harness security on and a V1 parent (the ADR 0126 -// gate), config.toml turns the multi-agent tools on with the roster, the -// persona's own model lands in its role file and in the runner-held digest, -// and the dispatch note replaces the single-context note. +// gate), config.toml keeps the V2 feature table off and turns the +// multi-agent tools on with the roster, the persona's own model lands in its +// role file and in the runner-held digest, and the V1 dispatch note replaces +// the single-context note. func TestCodexRuntimeBootstrap_DelegatingAgentRunsNativeChildren(t *testing.T) { t.Setenv(codexSubagentModelEnv, "") storeDir := t.TempDir() @@ -1267,6 +1365,8 @@ func TestCodexRuntimeBootstrap_DelegatingAgentRunsNativeChildren(t *testing.T) { cfg := string(storedUpload(t, storeDir, r.codexConfigPath())) assert.Contains(t, cfg, "[agents]\nenabled = true\nmax_concurrent_threads_per_session = 4\nmax_depth = 1\ndefault_subagent_model = \"gpt-5.6-luna\"\n") + assert.Contains(t, cfg, "[features.multi_agent_v2]\nenabled = false\n\n[agents]\nenabled = true\n", "a V1 parent's config keeps the V2 feature off") + assert.NotContains(t, cfg, codexV2DispatchMarker, "a V1 parent reads the V1 dispatch note") for _, role := range []string{"correctness", "default", "explore"} { assert.Contains(t, cfg, "[agents.\""+role+"\"]\n") assert.Contains(t, cfg, "config_file = \""+r.codexRolesDir()+"/"+role+".toml\"\n") @@ -1288,6 +1388,43 @@ func TestCodexRuntimeBootstrap_DelegatingAgentRunsNativeChildren(t *testing.T) { assert.Equal(t, codexAssetSHA256(correctness), held.RoleFiles["correctness"], "the digest covers the model line") assert.Equal(t, codexAssetSHA256([]byte(cfg)), held.ConfigTOML) assert.Contains(t, readFileString(t, logPath), r.codexHooksPath(), "hooks.json is still written: the guard is installed") + assert.NotContains(t, string(storedUpload(t, storeDir, r.codexHooksPath())), codexSubagentStopEvent, + "the child-result gate is part of V2 delegation only") +} + +// TestCodexRuntimeBootstrap_V2ParentRunsNativeChildren is the V2 switch +// (ADR 0159): a V2 parent with security on and V1 child models turns the +// feature table on, gets the V2 dispatch note quoting the withheld notice, +// role files with the V2 child note, and a hooks.json whose SubagentStop +// handler screens every child's result. +func TestCodexRuntimeBootstrap_V2ParentRunsNativeChildren(t *testing.T) { + t.Setenv(codexSubagentModelEnv, "") + storeDir := t.TempDir() + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "openshell.log"), storeDir, "codex-cli 0.152.1") + forgetRunnerHeldDigests("sb") + t.Cleanup(func() { forgetRunnerHeldDigests("sb") }) + skill := t.TempDir() + writePersonaFile(t, skill, "correctness", codexTestPersona) + input := codexDelegatingHooksInput(t, skill) + input.parentModel = "openai/gpt-6.1-sol" + + r := CodexRuntime{} + var err error + out := captureStderr(t, func() { err = r.Bootstrap(input) }) + require.NoError(t, err) + assert.NotContains(t, out, "running in one context") + + cfg := string(storedUpload(t, storeDir, r.codexConfigPath())) + assert.Contains(t, cfg, "[features.multi_agent_v2]\nenabled = true\n") + assert.Contains(t, cfg, "[agents]\nenabled = true\nmax_concurrent_threads_per_session = 4\n") + assert.Contains(t, cfg, codexV2DispatchMarker) + assert.Contains(t, cfg, "A message whose payload is `"+codexWithheldNotice+"`, ignoring whitespace around it, is a withheld result") + assert.Contains(t, cfg, "`task_name` set to a short name for the task, unique among the children you spawn (lowercase letters, digits and `_` only; `root` is reserved)") + assert.Contains(t, string(storedUpload(t, storeDir, r.codexRolesDir()+"/correctness.toml")), "any such call is denied", + "a V2 child reads the V2 child note") + hooks := string(storedUpload(t, storeDir, r.codexHooksPath())) + assert.Contains(t, hooks, `"SubagentStop"`) + assert.Contains(t, hooks, codexAdapterFile+" SubagentStop posttool_chain.py") } // The run's effort reaches config.toml as every child's effort, and an diff --git a/internal/runtime/codex_config.go b/internal/runtime/codex_config.go index 943bbd0543..231a925b1a 100644 --- a/internal/runtime/codex_config.go +++ b/internal/runtime/codex_config.go @@ -121,10 +121,23 @@ const codexAuthTimeoutMS = 5000 // it (verified on 0.157.0, 0.158.0 and 0.159.3; the resolution order is // unchanged at 0.166.0). // -// `[features] multi_agent_v2 = false` states codex's default so that the -// `[agents]` table decides: codex checks this feature first, and when it is -// on the V2 collaboration tools come back for every model (verified on -// 0.159.3, unchanged at 0.166.0). On its own the key removes nothing. +// The `[features.multi_agent_v2]` table decides the collaboration protocol +// of the run and of every child, whatever its model: codex checks this +// feature before `[agents] enabled`. When it is on, the root gets the V2 +// tools whatever its model (verified on 0.159.3, unchanged at 0.166.0) and +// a child gets them only when its own model selects V2 in the catalog +// (collab_tools_enabled, 0.166.0). `enabled = false` is codex's default, +// the same as the scalar `[features] multi_agent_v2 = false`, stated so +// that the `[agents]` table decides. `enabled = true`, for an admitted V2 +// parent with a roster (ADR 0159 decision 1), brings +// `disable_direct_message = true` (no send_message or followup_task) and +// `expose_spawn_agent_model_overrides = false` (no model or +// reasoning_effort in the spawn schema) with it, and only then: the table +// is `deny_unknown_fields` (MultiAgentV2ConfigToml), so a bump that drops +// either key would otherwise refuse every run's config, V1 and +// single-context ones included. `max_concurrent_threads_per_session` is +// never rendered here: codex derives the V2 cap from the `[agents]` key +// plus one for the root, so `[agents]` at 4 already yields four children. // // `[model_providers.fullsend-gateway]` is rendered only when an // inference.gateway block applies (codex_gateway.go): a second runner-owned @@ -161,7 +174,11 @@ enabled = false [features] plugins = false -multi_agent_v2 = false + +[features.multi_agent_v2] +enabled = {{ .MultiAgentV2 }}{{ if .MultiAgentV2 }} +disable_direct_message = true +expose_spawn_agent_model_overrides = false{{ end }} {{ .AgentsBlock }} @@ -204,7 +221,10 @@ type codexConfigData struct { AuthCommand string ProjectKey string // AgentsBlock arrives rendered by codexAgentsBlock, its strings quoted. - AgentsBlock string + AgentsBlock string + // MultiAgentV2 turns the collaboration V2 table on, with its two + // restriction keys; false renders the table at codex's default. + MultiAgentV2 bool RefreshIntervalMS int TimeoutMS int // GatewayProviderID, GatewayBaseURL and GatewayAuthCommand render the @@ -222,11 +242,17 @@ type codexConfigData struct { // fullsend-gateway provider's base_url (codexGatewayBaseURL), or "" when no // inference.gateway block applies. roles is the roster Bootstrap registers // for a delegating agent (empty otherwise) and defaultSubagentModel the -// run-level child model it resolved with them. -func renderCodexConfig(configDir, repoDir, developerInstructions, gatewayBaseURL string, roles []codexRole, defaultSubagentModel, childEffort string) ([]byte, error) { +// run-level child model it resolved with them. multiAgentV2 is true for a +// parent admitted on collaboration V2, which needs the roster: the table +// overrides `[agents] enabled = false`, so V2 without a roster would give +// the multi-agent tools to an agent that runs in one context. +func renderCodexConfig(configDir, repoDir, developerInstructions, gatewayBaseURL string, roles []codexRole, defaultSubagentModel, childEffort string, multiAgentV2 bool) ([]byte, error) { if repoDir == "" { return nil, fmt.Errorf("rendering codex %s: the target repository path is required", codexConfigFile) } + if multiAgentV2 && len(roles) == 0 { + return nil, fmt.Errorf("rendering codex %s: collaboration V2 needs a registered roster", codexConfigFile) + } data := codexConfigData{ DefaultProviderID: codexProviderID, ProviderID: codexProviderID, @@ -235,6 +261,7 @@ func renderCodexConfig(configDir, repoDir, developerInstructions, gatewayBaseURL AuthCommand: codexTOMLString(configDir + "/" + codexAuthScriptFile), ProjectKey: codexTOMLKey(repoDir), AgentsBlock: codexAgentsBlock(configDir, roles, defaultSubagentModel, childEffort), + MultiAgentV2: multiAgentV2, RefreshIntervalMS: codexAuthRefreshIntervalMS, TimeoutMS: codexAuthTimeoutMS, } @@ -469,13 +496,45 @@ const codexSpawnGuardMatcher = "^(multi_agent_v1|collaboration)|(spawn|resume)_a // in place of a hook-script phase. const codexSpawnGuardMode = "SpawnGuard" +// codexSubagentStopEvent is the codex hook event and adapter phase of the +// child-result gate (ADR 0159 decision 4), which codexHooksJSON renders for +// a run that delegates from a V2 parent. Codex runs it in a thread-spawned +// child with last_assistant_message, the text that becomes the child's +// result, before the parent is notified; a block (exit 2 with a reason) +// makes the child continue with the reason as its prompt instead of +// finishing (codex-rs/hooks/src/events/stop.rs, core/src/session/turn.rs, +// rust-v0.166.0). +const codexSubagentStopEvent = "SubagentStop" + +// codexWithheldNotice is the adapter's WITHHELD_NOTICE: a SubagentStop block +// tells the child to reply with exactly this, so it is the result the parent +// receives in place of a flagged one. The V2 runtime note quotes it, and the +// V2 review and retro rules in the agents repository must list this exact +// text as a final result with no content: a change here needs the same +// change there. +const codexWithheldNotice = "RESULT WITHHELD BY FULLSEND" + +// codexGroupCoversAgent reports whether a hook group's tools include a +// sub-agent's result on the other runtimes: every tool, or Agent/Task. +func codexGroupCoversAgent(tools []string) bool { + for _, t := range tools { + if t == security.AllTools || t == "Agent" || t == "Task" { + return true + } + } + return false +} + // codexHooksJSON renders $CODEX_HOME/hooks.json from the runtime-neutral // security.HookPlan, and returns the notes Bootstrap prints for tools that // have no codex counterpart. // // The spawn guard first, then one handler per plan group, so the group's // scripts still run in plan order inside one process — the ordering the -// PostToolUse chain depends on. +// PostToolUse chain depends on. multiAgentV2 is true for a run that +// delegates from a V2 parent: a PostToolUse group that covers Agent then +// also gets a SubagentStop handler with the same scripts +// (codexSubagentStopEvent). // // python is the absolute interpreter path Bootstrap resolved, rendered with // `-I`: codex spawns a hook through the shell it inherits, *after* the @@ -491,7 +550,7 @@ const codexSpawnGuardMode = "SpawnGuard" // well — a shell tool result is `success` regardless of exit code // (codex-rs/core/src/tools/context.rs ExecCommandToolOutput). pi maps the // phase onto nothing for the same reason. -func codexHooksJSON(configDir, python string, hooks security.SandboxHookConfig) ([]byte, []string, error) { +func codexHooksJSON(configDir, python string, hooks security.SandboxHookConfig, multiAgentV2 bool) ([]byte, []string, error) { cfg := codexHooksConfig{ Description: "fullsend sandbox tool hooks (generated; see docs/contributing/runtime-implementation.md)", Hooks: map[string][]codexHookMatcherSet{}, @@ -539,6 +598,19 @@ func codexHooksJSON(configDir, python string, hooks security.SandboxHookConfig) Timeout: security.HookTimeoutSeconds, }}, }) + // The child-result gate: the PostToolUse scripts that cover Agent + // also run on SubagentStop, in the child, on the final message that + // would become the child's result. + if multiAgentV2 && g.Phase == security.HookPhasePostToolUse && codexGroupCoversAgent(g.Tools) { + cfg.Hooks[codexSubagentStopEvent] = append(cfg.Hooks[codexSubagentStopEvent], codexHookMatcherSet{ + Hooks: []codexHookEntry{{ + Type: "command", + Command: strings.Join(append( + []string{python, "-I", adapter, codexSubagentStopEvent}, g.Scripts...), " "), + Timeout: security.HookTimeoutSeconds, + }}, + }) + } } data, err := json.MarshalIndent(cfg, "", " ") diff --git a/internal/runtime/codex_config_test.go b/internal/runtime/codex_config_test.go index db7a548ce5..0af5b6f6c7 100644 --- a/internal/runtime/codex_config_test.go +++ b/internal/runtime/codex_config_test.go @@ -65,7 +65,7 @@ func TestRenderCodexConfig_ParsesAsTOML(t *testing.T) { // A directory name can carry quotes, backslashes and a newline too. nastyRepo := sandbox.SandboxWorkspace + "/re\"po\\\\x]\ntrust_level = \"trusted\"" - data, err := renderCodexConfig(sandbox.SandboxCodexConfig, nastyRepo, nasty, "", nil, "", "") + data, err := renderCodexConfig(sandbox.SandboxCodexConfig, nastyRepo, nasty, "", nil, "", "", false) require.NoError(t, err) path := filepath.Join(t.TempDir(), "config.toml") @@ -113,7 +113,7 @@ print(json.dumps({ } func TestRenderCodexConfig_PinsProviderAndHygieneKeys(t *testing.T) { - data, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", "", nil, "", "") + data, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", "", nil, "", "", false) require.NoError(t, err) rendered := string(data) @@ -135,7 +135,7 @@ func TestRenderCodexConfig_PinsProviderAndHygieneKeys(t *testing.T) { "[agents]\nenabled = false", // codex checks this feature before agents.enabled; when it is on the // V2 collaboration tools come back. - "plugins = false\nmulti_agent_v2 = false", + "[features]\nplugins = false\n\n[features.multi_agent_v2]\nenabled = false", `wire_api = "responses"`, `base_url = "` + codexBaseURL + `"`, `refresh_interval_ms = 30000`, @@ -168,7 +168,7 @@ func TestRenderCodexConfig_PinsProviderAndHygieneKeys(t *testing.T) { // codex reads; the gateway provider is the default. func TestRenderCodexConfig_GatewayProvider(t *testing.T) { python := pythonWithTomllib(t) - data, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", testCodexGatewayBaseURL, nil, "", "") + data, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", testCodexGatewayBaseURL, nil, "", "", false) require.NoError(t, err) rendered := string(data) assert.NotContains(t, rendered, "env_key", "the gateway credential comes from the auth script, never the environment") @@ -214,12 +214,12 @@ print(json.dumps({"default": cfg["model_provider"], "providers": cfg["model_prov // refuses the openai-only config in its place and vice versa: rendering a // second provider does not loosen it. func TestCodexConfigGuard_GatewayConfig(t *testing.T) { - plain, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", "", nil, "", "") + plain, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", "", nil, "", "", false) require.NoError(t, err) - withGateway, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", testCodexGatewayBaseURL, nil, "", "") + withGateway, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", testCodexGatewayBaseURL, nil, "", "", false) require.NoError(t, err) assert.NotEqual(t, codexAssetSHA256(plain), codexAssetSHA256(withGateway)) - other, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", "https://evil.example.com/v1", nil, "", "") + other, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", "https://evil.example.com/v1", nil, "", "", false) require.NoError(t, err) assert.NotEqual(t, codexAssetSHA256(withGateway), codexAssetSHA256(other), "the gateway base_url is covered by the digest") } @@ -283,7 +283,7 @@ func TestCodexMatcherFor_ExactAlternationForm(t *testing.T) { func TestCodexHooksJSON_DefaultPlan(t *testing.T) { cfg := security.SandboxHookConfigFromHarness(&harness.Harness{}) - data, notes, err := codexHooksJSON(sandbox.SandboxCodexConfig, testCodexPython, cfg) + data, notes, err := codexHooksJSON(sandbox.SandboxCodexConfig, testCodexPython, cfg, false) require.NoError(t, err) var parsed codexHooksConfig @@ -332,6 +332,52 @@ func TestCodexHooksJSON_DefaultPlan(t *testing.T) { } assert.True(t, sawBashMatcher, "the Bash-scoped groups keep a matcher") assert.True(t, sawNoMatcher, "the all-tools group omits the matcher key") + + assert.NotContains(t, parsed.Hooks, codexSubagentStopEvent, "the child-result gate is part of V2 delegation only") +} + +// TestCodexHooksJSON_V2DelegationAddsTheChildResultGate: for a run that +// delegates from a V2 parent (ADR 0159 decision 4), one SubagentStop +// handler with the scripts of the PostToolUse group, which covers Agent, +// and no matcher (codex matches SubagentStop on agent_type), so every +// role's final message is screened. Everything else is the default plan's. +func TestCodexHooksJSON_V2DelegationAddsTheChildResultGate(t *testing.T) { + cfg := security.SandboxHookConfigFromHarness(&harness.Harness{}) + plain, _, err := codexHooksJSON(sandbox.SandboxCodexConfig, testCodexPython, cfg, false) + require.NoError(t, err) + data, _, err := codexHooksJSON(sandbox.SandboxCodexConfig, testCodexPython, cfg, true) + require.NoError(t, err) + + var parsed, base codexHooksConfig + require.NoError(t, json.Unmarshal(data, &parsed)) + require.NoError(t, json.Unmarshal(plain, &base)) + post := parsed.Hooks[string(security.HookPhasePostToolUse)] + stop := parsed.Hooks[codexSubagentStopEvent] + require.Len(t, post, 1) + require.Len(t, stop, 1) + assert.Empty(t, stop[0].Matcher) + assert.Equal(t, strings.Replace(post[0].Hooks[0].Command, " PostToolUse ", " SubagentStop ", 1), stop[0].Hooks[0].Command) + assert.Equal(t, post[0].Hooks[0].Timeout, stop[0].Hooks[0].Timeout) + delete(parsed.Hooks, codexSubagentStopEvent) + assert.Equal(t, base, parsed, "the handler is the only difference") +} + +// TestCodexGroupCoversAgent: a group reaches a sub-agent's result when it +// names every tool, Agent or its alias Task. +func TestCodexGroupCoversAgent(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + tools []string + want bool + }{ + {[]string{security.AllTools}, true}, + {[]string{"Bash", "Agent"}, true}, + {[]string{"Task"}, true}, + {[]string{"Bash", "Edit"}, false}, + {nil, false}, + } { + assert.Equal(t, tc.want, codexGroupCoversAgent(tc.tools), "%v", tc.tools) + } } // TestCodexHooksJSON_NeverAsync is the load-bearing one. codex only lets a @@ -342,7 +388,7 @@ func TestCodexHooksJSON_DefaultPlan(t *testing.T) { // with no signal that they had. func TestCodexHooksJSON_NeverAsync(t *testing.T) { cfg := security.SandboxHookConfigFromHarness(&harness.Harness{}) - data, _, err := codexHooksJSON(sandbox.SandboxCodexConfig, testCodexPython, cfg) + data, _, err := codexHooksJSON(sandbox.SandboxCodexConfig, testCodexPython, cfg, true) require.NoError(t, err) assert.NotContains(t, string(data), "async") @@ -366,7 +412,7 @@ func TestCodexHooksJSON_NeverAsync(t *testing.T) { // hooks at all. func TestCodexHooksJSON_ParsesAsCodexHooksFile(t *testing.T) { cfg := security.SandboxHookConfigFromHarness(&harness.Harness{}) - data, _, err := codexHooksJSON(sandbox.SandboxCodexConfig, testCodexPython, cfg) + data, _, err := codexHooksJSON(sandbox.SandboxCodexConfig, testCodexPython, cfg, true) require.NoError(t, err) var raw map[string]any @@ -391,7 +437,7 @@ func TestCodexHooksJSON_ParsesAsCodexHooksFile(t *testing.T) { // spawn guard as its first PreToolUse group. func TestCodexHooksJSON_AllHooksOffKeepsSpawnGuard(t *testing.T) { cfg := codexAllHooksOff() - data, _, err := codexHooksJSON(sandbox.SandboxCodexConfig, testCodexPython, cfg) + data, _, err := codexHooksJSON(sandbox.SandboxCodexConfig, testCodexPython, cfg, true) require.NoError(t, err) var parsed codexHooksConfig @@ -446,7 +492,7 @@ func writeFileForTest(path string, data []byte) error { } func TestRenderCodexConfig_RequiresRepoDir(t *testing.T) { - _, err := renderCodexConfig(sandbox.SandboxCodexConfig, "", "body", "", nil, "", "") + _, err := renderCodexConfig(sandbox.SandboxCodexConfig, "", "body", "", nil, "", "", false) require.Error(t, err, "an empty path would leave the project's trust unset") } @@ -454,7 +500,7 @@ func TestRenderCodexConfig_RequiresRepoDir(t *testing.T) { // PreToolUse group, and its matcher's reach. func TestCodexHooksJSON_SpawnGuardIsFirst(t *testing.T) { cfg := security.SandboxHookConfigFromHarness(&harness.Harness{}) - data, _, err := codexHooksJSON(sandbox.SandboxCodexConfig, testCodexPython, cfg) + data, _, err := codexHooksJSON(sandbox.SandboxCodexConfig, testCodexPython, cfg, false) require.NoError(t, err) var parsed codexHooksConfig @@ -481,7 +527,7 @@ func TestCodexHooksJSON_SpawnGuardIsFirst(t *testing.T) { for _, name := range []string{ "spawn_agent", "multi_agent_v1resume_agent", "collaborationspawn_agent", // codex's spawn and resume tools "multi_agent_v1wait_agent", "multi_agent_v1close_agent", "multi_agent_v1send_input", // passed through by the handler - "collaborationwait_agent", "collaborationlist_agents", "collaborationinterrupt_agent", // V2 control calls: denied by the handler + "collaborationwait_agent", "collaborationlist_agents", "collaborationinterrupt_agent", // V2 control calls: passed through by the handler "multi_agent_v1fork_agent", "resume_agent", // unknown names: denied by the handler } { assert.True(t, pattern.MatchString(name), "the guard must run for %s", name) @@ -521,11 +567,11 @@ func TestCodexAgentsBlock_ChildEffort(t *testing.T) { // the untrusted project pin stays. func TestRenderCodexConfig_DelegatingAgentsBlock(t *testing.T) { data, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", "", - codexTestDelegatingRoles(), "gpt-5.6-luna", "") + codexTestDelegatingRoles(), "gpt-5.6-luna", "", false) require.NoError(t, err) rendered := string(data) - want := "[features]\nplugins = false\nmulti_agent_v2 = false\n\n" + + want := "[features]\nplugins = false\n\n[features.multi_agent_v2]\nenabled = false\n\n" + "[agents]\n" + "enabled = true\n" + "max_concurrent_threads_per_session = 4\n" + @@ -553,27 +599,69 @@ func TestRenderCodexConfig_DelegatingAgentsBlock(t *testing.T) { assert.Equal(t, 1, strings.Count(rendered, "\ncommand ")) // No roles: the same bytes as before, whatever the default model argument. - none, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", "", nil, "", "") + none, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", "", nil, "", "", false) require.NoError(t, err) - empty, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", "", []codexRole{}, "gpt-5.6-luna", "") + empty, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", "", []codexRole{}, "gpt-5.6-luna", "", false) require.NoError(t, err) assert.Equal(t, none, empty) - assert.Contains(t, string(none), "[features]\nplugins = false\nmulti_agent_v2 = false\n\n[agents]\nenabled = false\n\n[projects.") + assert.Contains(t, string(none), "[features]\nplugins = false\n\n[features.multi_agent_v2]\nenabled = false\n\n[agents]\nenabled = false\n\n[projects.") +} + +// TestRenderCodexConfig_MultiAgentV2Table pins the table of a V2 parent +// (ADR 0159 decisions 1 and 3): enabled, the two restriction keys, no thread +// cap of its own, and nothing else different from the V1 config; and that +// V2 with no roster is refused: the table would override the single-context +// `[agents] enabled = false`. +func TestRenderCodexConfig_MultiAgentV2Table(t *testing.T) { + t.Parallel() + v1, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", "", + codexTestDelegatingRoles(), "gpt-5.6-luna", "", false) + require.NoError(t, err) + v2, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", "", + codexTestDelegatingRoles(), "gpt-5.6-luna", "", true) + require.NoError(t, err) + rendered := string(v2) + + const table = "[features]\nplugins = false\n\n[features.multi_agent_v2]\nenabled = true\n" + + "disable_direct_message = true\nexpose_spawn_agent_model_overrides = false\n\n" + + "[agents]\nenabled = true\nmax_concurrent_threads_per_session = 4\n" + assert.Contains(t, rendered, table) + _, fromTable, _ := strings.Cut(rendered, "[features.multi_agent_v2]") + tableOnly, _, _ := strings.Cut(fromTable, "[agents]") + assert.NotContains(t, tableOnly, "max_concurrent_threads_per_session", + "codex derives the V2 cap from the [agents] key plus the root; a cap here would count the root too") + assert.Equal(t, strings.Replace(string(v1), "enabled = false\n\n[agents]", + "enabled = true\ndisable_direct_message = true\nexpose_spawn_agent_model_overrides = false\n\n[agents]", 1), + rendered, "the table is the only difference from the V1 config") + + _, err = renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", "", nil, "", "", true) + assert.EqualError(t, err, "rendering codex config.toml: collaboration V2 needs a registered roster") } // TestRenderCodexConfig_DelegatingParsesAsTOML round-trips the block through // tomllib, with a description that carries quotes and a backslash: the // escaper, not the block, keeps a persona description from breaking out. +// Both feature tables parse, each as the one multi_agent_v2 value under +// [features], with the V2 keys present only when enabled. func TestRenderCodexConfig_DelegatingParsesAsTOML(t *testing.T) { python := pythonWithTomllib(t) - roles := codexTestDelegatingRoles() - roles[0].Description = `Checks "edge" cases \ and [agents."evil"] config_file = "x"` - data, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", "", roles, "gpt-6-astra", "") - require.NoError(t, err) - - path := filepath.Join(t.TempDir(), "config.toml") - require.NoError(t, writeFileForTest(path, data)) - script := ` + for name, tc := range map[string]struct { + multiAgentV2 bool + features map[string]any + }{ + "v1": {false, map[string]any{"plugins": false, "multi_agent_v2": map[string]any{"enabled": false}}}, + "v2": {true, map[string]any{"plugins": false, "multi_agent_v2": map[string]any{ + "enabled": true, "disable_direct_message": true, "expose_spawn_agent_model_overrides": false}}}, + } { + t.Run(name, func(t *testing.T) { + roles := codexTestDelegatingRoles() + roles[0].Description = `Checks "edge" cases \ and [agents."evil"] config_file = "x"` + data, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", "", roles, "gpt-6-astra", "", tc.multiAgentV2) + require.NoError(t, err) + + path := filepath.Join(t.TempDir(), "config.toml") + require.NoError(t, writeFileForTest(path, data)) + script := ` import json, sys, tomllib with open(sys.argv[1], "rb") as fh: cfg = tomllib.load(fh) @@ -586,29 +674,34 @@ print(json.dumps({ "roles": sorted(k for k in a if isinstance(a[k], dict)), "correctness": a["correctness"], "projects": cfg["projects"], + "features": cfg["features"], })) ` - out, err := exec.Command(python, "-c", script, path).CombinedOutput() - require.NoError(t, err, "rendered config.toml did not parse: %s", out) - - var got struct { - Enabled bool `json:"enabled"` - Open int `json:"open"` - Depth int `json:"depth"` - Default string `json:"default"` - Roles []string `json:"roles"` - Correctness map[string]string `json:"correctness"` - Projects map[string]map[string]string `json:"projects"` + out, err := exec.Command(python, "-c", script, path).CombinedOutput() + require.NoError(t, err, "rendered config.toml did not parse: %s", out) + + var got struct { + Enabled bool `json:"enabled"` + Open int `json:"open"` + Depth int `json:"depth"` + Default string `json:"default"` + Roles []string `json:"roles"` + Correctness map[string]string `json:"correctness"` + Projects map[string]map[string]string `json:"projects"` + Features map[string]any `json:"features"` + } + require.NoError(t, json.Unmarshal(out, &got)) + assert.True(t, got.Enabled) + assert.Equal(t, 4, got.Open) + assert.Equal(t, 1, got.Depth) + assert.Equal(t, "gpt-6-astra", got.Default) + assert.Equal(t, []string{"correctness", "default", "explore"}, got.Roles, "exactly the roster, no table smuggled in by a description") + assert.Equal(t, map[string]string{ + "description": roles[0].Description, + "config_file": "/sandbox/codex-config/agents/correctness.toml", + }, got.Correctness) + assert.Equal(t, map[string]map[string]string{"/sandbox/workspace/repo": {"trust_level": "untrusted"}}, got.Projects) + assert.Equal(t, tc.features, got.Features) + }) } - require.NoError(t, json.Unmarshal(out, &got)) - assert.True(t, got.Enabled) - assert.Equal(t, 4, got.Open) - assert.Equal(t, 1, got.Depth) - assert.Equal(t, "gpt-6-astra", got.Default) - assert.Equal(t, []string{"correctness", "default", "explore"}, got.Roles, "exactly the roster, no table smuggled in by a description") - assert.Equal(t, map[string]string{ - "description": roles[0].Description, - "config_file": "/sandbox/codex-config/agents/correctness.toml", - }, got.Correctness) - assert.Equal(t, map[string]map[string]string{"/sandbox/workspace/repo": {"trust_level": "untrusted"}}, got.Projects) } diff --git a/internal/runtime/codex_golden_test.go b/internal/runtime/codex_golden_test.go index 38a3912695..3ebbc71040 100644 --- a/internal/runtime/codex_golden_test.go +++ b/internal/runtime/codex_golden_test.go @@ -75,37 +75,35 @@ func TestCodexGolden(t *testing.T) { }{ {"config.toml", func(t *testing.T) string { data, err := renderCodexConfig(sandbox.SandboxCodexConfig, repo, - codexDeveloperInstructions("triage", def, nil), "", nil, "", "") + codexDeveloperInstructions("triage", def, nil, "v1"), "", nil, "", "", false) require.NoError(t, err) return string(data) }}, {"config-gateway.toml", func(t *testing.T) string { data, err := renderCodexConfig(sandbox.SandboxCodexConfig, repo, - codexDeveloperInstructions("triage", def, nil), testCodexGatewayBaseURL, nil, "", "") - require.NoError(t, err) - return string(data) - }}, - {"config-delegating.toml", func(t *testing.T) string { - review, err := parsePiAgent([]byte(codexTestDelegatingAgentDef)) - require.NoError(t, err) - roles, defaultModel, _, err := resolveCodexChildModels(codexGoldenRoles(t), nil, nil, "", "", codexTestCatalog()) - require.NoError(t, err) - data, err := renderCodexConfig(sandbox.SandboxCodexConfig, repo, - codexDeveloperInstructions("review", review, roles), "", roles, defaultModel, "") + codexDeveloperInstructions("triage", def, nil, "v1"), testCodexGatewayBaseURL, nil, "", "", false) require.NoError(t, err) return string(data) }}, + {"config-delegating.toml", func(t *testing.T) string { return codexGoldenDelegatingConfig(t, "v1") }}, + {"config-delegating-v2.toml", func(t *testing.T) string { return codexGoldenDelegatingConfig(t, "v2") }}, {"launch-gateway.txt", func(t *testing.T) string { return codexGoldenLaunch(buildCodexRunCommand(hooksOn, codexModel{ID: "vendor/org/model", Gateway: true}, "high", true, gatewayHooks)) }}, {"hooks-default.json", func(t *testing.T) string { data, _, err := codexHooksJSON(sandbox.SandboxCodexConfig, testCodexPython, - security.SandboxHookConfigFromHarness(&harness.Harness{})) + security.SandboxHookConfigFromHarness(&harness.Harness{}), false) + require.NoError(t, err) + return string(data) + }}, + {"hooks-delegating-v2.json", func(t *testing.T) string { + data, _, err := codexHooksJSON(sandbox.SandboxCodexConfig, testCodexPython, + security.SandboxHookConfigFromHarness(&harness.Harness{}), true) require.NoError(t, err) return string(data) }}, {"hooks-all-off.json", func(t *testing.T) string { - data, _, err := codexHooksJSON(sandbox.SandboxCodexConfig, testCodexPython, codexAllHooksOff()) + data, _, err := codexHooksJSON(sandbox.SandboxCodexConfig, testCodexPython, codexAllHooksOff(), false) require.NoError(t, err) return string(data) }}, @@ -155,13 +153,28 @@ func TestCodexGolden(t *testing.T) { } } +// codexGoldenDelegatingConfig renders config.toml as Bootstrap does for the +// review agent with the golden roles on collaboration version: the +// version's dispatch note and, for V2, the feature table on. +func codexGoldenDelegatingConfig(t *testing.T, version string) string { + t.Helper() + review, err := parsePiAgent([]byte(codexTestDelegatingAgentDef)) + require.NoError(t, err) + roles, defaultModel, _, err := resolveCodexChildModels(codexGoldenRoles(t), nil, nil, "", "", codexTestCatalog()) + require.NoError(t, err) + data, err := renderCodexConfig(sandbox.SandboxCodexConfig, sandbox.SandboxWorkspace+"/repo", + codexDeveloperInstructions("review", review, roles, version), "", roles, defaultModel, "", version == "v2") + require.NoError(t, err) + return string(data) +} + // codexGoldenRoles renders the roles of a review agent with the test // correctness persona (codexTestPersona): three files, no model line. func codexGoldenRoles(t *testing.T) []codexRole { t.Helper() skill := t.TempDir() writePersonaFile(t, skill, "correctness", codexTestPersona) - roles, _ := codexRoles([]string{skill}, "review") + roles, _ := codexRoles([]string{skill}, "review", "v1") return roles } diff --git a/internal/runtime/codex_hook/fullsend-codex-hook.py b/internal/runtime/codex_hook/fullsend-codex-hook.py index ce73d060a1..8cc081d6b8 100644 --- a/internal/runtime/codex_hook/fullsend-codex-hook.py +++ b/internal/runtime/codex_hook/fullsend-codex-hook.py @@ -4,10 +4,13 @@ docs/contributing/runtime-implementation.md "Sandbox hook contract"). Invoked by codex from `$CODEX_HOME/hooks.json`, one handler per -`security.HookPlan` group, plus one for the spawn policy of ADR 0126: +`security.HookPlan` group, plus one for the spawn policy of ADR 0126 and, on +a run that delegates from a V2 parent, one per PostToolUse group that covers +Agent, on a child's final message (ADR 0159 decision 4): python3 [ ...] python3 SpawnGuard + python3 SubagentStop [ ...] The hook payload arrives as JSON on stdin. Everything else is derived from this file's own location, so nothing in the agent-writable environment can @@ -128,19 +131,43 @@ PHASE_PRE = "PreToolUse" PHASE_POST = "PostToolUse" +# The child-result gate (ADR 0159 decision 4). codex runs SubagentStop in a +# thread-spawned child with the final message that would become the child's +# result, before the parent is notified. A block (exit 2 + reason) makes the +# child continue with the reason as its prompt instead of finishing. On this +# phase that reason is always SUBAGENT_STOP_PROMPT, which asks for +# WITHHELD_NOTICE and does not say what was flagged, and after a block only +# the notice passes, so a flagged result is never delivered: the parent +# receives the notice instead. WITHHELD_NOTICE is the Go side's +# codexWithheldNotice, which the V2 runtime note quotes. +PHASE_SUBAGENT_STOP = "SubagentStop" +WITHHELD_NOTICE = "RESULT WITHHELD BY FULLSEND" +SUBAGENT_STOP_PROMPT = ( + "fullsend: your final message was withheld by the security chain and was " + "not delivered. Reply with exactly: " + WITHHELD_NOTICE +) # argv[1] of the spawn guard handler, which takes no script. MODE_SPAWN_GUARD = "SpawnGuard" -# The only multi-agent tool the guard admits. +# The spawns the guard admits under policy: the V1 spawn, which codex +# reports under its bare name, and the V2 spawn, reported as its +# `collaboration` namespace joined with the name (ADR 0126, ADR 0159). SPAWN_TOOL_V1 = "spawn_agent" +SPAWN_TOOL_V2 = "collaborationspawn_agent" +SPAWN_TOOLS = frozenset({SPAWN_TOOL_V1, SPAWN_TOOL_V2}) # Passed through from the root thread: each acts on an admitted child and # none can start or reopen one. Denied from a child, whose payload carries -# agent_id or agent_type. Every other multi-agent tool is denied by name. +# agent_id or agent_type. Every other multi-agent tool is denied by name: +# the V1 resume, and the V2 send_message and followup_task, which reach a +# child again. SPAWN_GUARD_PASS = frozenset( { "multi_agent_v1wait_agent", "multi_agent_v1close_agent", "multi_agent_v1send_input", + "collaborationwait_agent", + "collaborationlist_agents", + "collaborationinterrupt_agent", } ) # A spawn without agent_type asks codex for its `default` role. @@ -175,13 +202,14 @@ "multi_agent_v1close_agent": "Agent", "multi_agent_v1send_input": "Agent", # The V2 spawn and the control calls ADR 0159 decision 3 maps the same - # way are Agent too; the guard still denies them by name. No mapped call - # has the allowlist as a backstop: an allowlist that permits Agent passes - # them all and the spawn guard is their only name-level check. The V1 - # spawn still sits under codex's agents.max_depth; the V2 spawn does not - # (#9085), so V2 admission needs a backstop of its own before - # CodexRuntime.Bootstrap accepts a V2 parent. send_message and - # followup_task stay unmapped like the resume. + # way are Agent too, admitted and passed through under the same policy. + # No mapped call has the allowlist as a backstop: an allowlist that + # permits Agent passes them all and the spawn guard is their only + # name-level check. The V1 spawn still sits under codex's + # agents.max_depth; the V2 spawn does not (#9085). Its backstop is that + # CodexRuntime.Bootstrap admits a V2 parent only when no child model + # selects V2, so a child the runner starts holds no spawn tool. + # send_message and followup_task stay unmapped like the resume. "collaborationspawn_agent": "Agent", "collaborationwait_agent": "Agent", "collaborationlist_agents": "Agent", @@ -436,6 +464,13 @@ def log_finding(name: str, severity: str, detail: str, action: str) -> None: os.close(fd) +# Sent in place of every block reason on SubagentStop (set in main()), where +# stderr is the continuation prompt the child reads: a child told which stage +# fired could reword its result until one passed. Every call site records +# the reason in the findings log first. +_BLOCK_PROMPT = "" + + def block(reason: str) -> None: """Exit 2 with a non-empty reason on stderr — codex's blocking contract. @@ -481,7 +516,7 @@ def block(reason: str) -> None: # by signal, which codex does not treat as a block. signal.setitimer(signal.ITIMER_REAL, 0) text = (reason or "").strip() or "fullsend hook blocked this tool call" - truncated = text[:MAX_TEXT] + truncated = _BLOCK_PROMPT or text[:MAX_TEXT] with contextlib.suppress(BaseException): data = truncated.encode("utf-8", "replace") while data: @@ -756,15 +791,24 @@ def verify_spawn_files(digests: dict[str, str]) -> str | None: return None +def _is_none_fork(value: Any) -> bool: + """True for the fork_turns codex reads as no fork: a string that is "none" + once trimmed, compared case-insensitively. Python's strip() trims a + superset of Rust's trim() (U+001C to U+001F); a value the hook admits on + that difference is still rejected by codex, never forked.""" + return isinstance(value, str) and value.strip().casefold() == "none" + + def spawn_policy(hook_input: dict[str, Any], registered: dict[str, str]) -> str | None: - """The reason a multi-agent call is outside policy, or None for a V1 spawn - from the root thread of a registered role with fork_context false and no - model or effort argument. Reads no file: agent_type is never a path.""" + """The reason a multi-agent call is outside policy, or None for a spawn + from the root thread of a registered role that starts a fresh context + (V1: fork_context false; V2: fork_turns "none") with no model or effort + argument. Reads no file: agent_type is never a path.""" tool = hook_input.get("tool_name") - if tool != SPAWN_TOOL_V1: + if tool not in SPAWN_TOOLS: return ( - f"fullsend: {tool!r} is not the V1 spawn tool; resuming a child, V2 " - "tools and unknown multi-agent tools are not allowed" + f"fullsend: {tool!r} is not a spawn tool the runner admits; resuming " + "or messaging a child and unknown multi-agent tools are not allowed" ) # Only a child's payload carries agent_id or agent_type. if "agent_id" in hook_input or "agent_type" in hook_input: @@ -772,11 +816,21 @@ def spawn_policy(hook_input: dict[str, Any], registered: dict[str, str]) -> str args = hook_input.get("tool_input") if not isinstance(args, dict): return "fullsend: spawn_agent arguments are not an object (fail closed)" - if args.get("fork_context") is not False: + if tool == SPAWN_TOOL_V1 and args.get("fork_context") is not False: return ( "fullsend: spawn_agent must pass fork_context: false; a child starts " "without the parent's context" ) + # Under V2 an absent fork_turns forks the parent's whole history and "0" + # is invalid, so only "none" as codex reads it is a fresh context; + # fork_context is V1's key. + if tool == SPAWN_TOOL_V2 and ( + "fork_context" in args or not _is_none_fork(args.get("fork_turns")) + ): + return ( + 'fullsend: spawn_agent must pass fork_turns: "none" and no fork_context; ' + "a child starts without the parent's context" + ) for key in ("model", "reasoning_effort"): if key in args: return ( @@ -930,8 +984,68 @@ def run_post_tool_use(scripts: list[str], hook_input: dict[str, Any], tool_name: sys.exit(0) +def run_subagent_stop(scripts: list[str], hook_input: dict[str, Any]) -> None: + """Run the PostToolUse chain on a child's final message. + + The message is presented to the scripts as an Agent tool result, the shape + the other runtimes give a sub-agent's answer. Every block in the chain + leaves through block() (exit 2 with SUBAGENT_STOP_PROMPT in place of the + reason, which goes to the findings log), which SubagentStop reads as + "continue the child" (codex-rs/hooks/src/events/stop.rs), so the flagged + text is not delivered. `continue: false` is never emitted: codex would end + the child and deliver the flagged message. + + After a block codex sets stop_hook_active for the rest of the child's + turn (core/src/session/turn.rs), and only fullsend renders stop handlers, + so the flag means this gate already blocked: from then on only the exact + withheld notice passes and the chain does not run, so a child cannot + reword a flagged result until one gets through. + + codex always sends last_assistant_message, a string or null + (hooks/src/schema.rs SubagentStopCommandInput): null or "" has nothing + to screen, and a missing key or another type means the payload changed + shape, so it blocks. The exact withheld notice, with only ASCII + whitespace around it, carries no content and passes before the chain + runs, so a child that complies can always finish, even when the chain + blocks for a reason that is not the message. Any other padding goes + through the chain, whose unicode stage screens hidden characters. + """ + message = hook_input.get("last_assistant_message") + if hook_input.get("stop_hook_active") is True: + if isinstance(message, str) and message.strip(" \t\r\n") == WITHHELD_NOTICE: + sys.exit(0) + reason = ( + "fullsend: after a SubagentStop block the child's next final message " + "was not the withheld notice, so it was withheld" + ) + log_finding("codex_subagent_stop_retry_block", "critical", reason, "block") + block(reason) + if "last_assistant_message" in hook_input and message in (None, ""): + sys.exit(0) + if not isinstance(message, str): + reason = ( + "fullsend: the SubagentStop payload has no last_assistant_message string, " + "so the result cannot be scanned (fail closed)" + ) + log_finding("codex_adapter_bad_payload", "critical", reason, "block") + block(reason) + if message.strip(" \t\r\n") == WITHHELD_NOTICE: + sys.exit(0) + synthetic = { + "tool_input": {}, + "tool_response": message, + **_cwd(hook_input), + } + run_post_tool_use(scripts, synthetic, "Agent") + + def main() -> None: phase = sys.argv[1] if len(sys.argv) > 1 else "" + if phase == PHASE_SUBAGENT_STOP: + # Every block on this phase, a misconfiguration, a bad payload or a + # crash included, continues the child with the withheld-notice prompt. + global _BLOCK_PROMPT + _BLOCK_PROMPT = SUBAGENT_STOP_PROMPT if phase != MODE_SPAWN_GUARD and len(sys.argv) < 3: # Misconfiguration, not a tool decision. Fail closed on the phase that # can block and stay quiet on the one that cannot. @@ -954,13 +1068,14 @@ def main() -> None: # about to happen, so an empty payload means the call cannot be # scanned, not that there is nothing to scan. On PostToolUse the call # has already run and there is nothing left to prevent, so the no-op - # stands there. + # stands there. On SubagentStop an empty payload leaves the child's + # result unscanned, so it blocks. empty = raw.strip() == "" if phase == PHASE_POST and empty: sys.exit(0) + event = PHASE_SUBAGENT_STOP if phase == PHASE_SUBAGENT_STOP else PHASE_PRE message = ( - "fullsend: codex sent an empty PreToolUse payload, so the tool " - "call cannot be scanned (fail closed)" + f"fullsend: codex sent an empty {event} payload, so it cannot be scanned (fail closed)" if empty else "fullsend: codex hook payload was not a JSON object (fail closed)" ) @@ -972,6 +1087,9 @@ def main() -> None: # names and a child's payload is told apart by untranslated fields. run_spawn_guard(hook_input) + if phase == PHASE_SUBAGENT_STOP: + run_subagent_stop(scripts, hook_input) + codex_tool = hook_input.get("tool_name") codex_tool = codex_tool if isinstance(codex_tool, str) else "" tool_name = claude_tool_name(codex_tool) diff --git a/internal/runtime/codex_hook_test.go b/internal/runtime/codex_hook_test.go index 7627e8638d..bad47fe0e9 100644 --- a/internal/runtime/codex_hook_test.go +++ b/internal/runtime/codex_hook_test.go @@ -94,11 +94,16 @@ func (h *codexAdapterHarness) run(phase string, input map[string]any, scripts .. h.t.Helper() payload, err := json.Marshal(input) require.NoError(h.t, err) + return h.runRaw(phase, string(payload), scripts...) +} +// runRaw is run with stdin passed as is, for payloads that are not an object. +func (h *codexAdapterHarness) runRaw(phase, stdin string, scripts ...string) codexAdapterResult { + h.t.Helper() args := append([]string{h.adapter, phase}, scripts...) cmd := exec.Command(h.python, args...) cmd.Env = append(codexAdapterBaseEnv(), codexHookDigestsEnv+"="+codexHookDigestsValue(h.digests)) - cmd.Stdin = strings.NewReader(string(payload)) + cmd.Stdin = strings.NewReader(stdin) var stdout, stderr strings.Builder cmd.Stdout = &stdout cmd.Stderr = &stderr @@ -705,6 +710,9 @@ func TestCodexAdapterPhasesMatchHookPlan(t *testing.T) { src := string(codexHookAdapterPy) assert.Contains(t, src, `PHASE_PRE = "`+string(security.HookPhasePreToolUse)+`"`) assert.Contains(t, src, `PHASE_POST = "`+string(security.HookPhasePostToolUse)+`"`) + assert.Contains(t, src, `PHASE_SUBAGENT_STOP = "`+codexSubagentStopEvent+`"`) + assert.Contains(t, src, `WITHHELD_NOTICE = "`+codexWithheldNotice+`"`, + "the notice the V2 runtime note quotes is the one a blocked child is told to reply with") } func sortedKeys(m map[string]any) []string { @@ -1260,7 +1268,10 @@ func TestCodexAdapterSpawnGuardConstantsMatchGo(t *testing.T) { assert.Contains(t, src, `MODE_SPAWN_GUARD = "`+codexSpawnGuardMode+`"`) assert.Contains(t, src, `SPAWN_DIGESTS_ENV = "`+codexSpawnDigestsEnv+`"`) assert.Contains(t, src, `SPAWN_TOOL_V1 = "spawn_agent"`, - "the guard admits the V1 spawn under policy; every other matched name is passed through or denied by the handler") + "the guard admits the V1 spawn under policy") + assert.Contains(t, src, `SPAWN_TOOL_V2 = "collaborationspawn_agent"`, + "the guard admits the V2 spawn under policy, reached as its namespace joined with its name (ADR 0159); "+ + "every other matched name is passed through or denied by the handler") assert.Contains(t, src, `SPAWN_GUARD_DEADLINE_S = HANDLER_TIMEOUT_S - BUDGET_MARGIN_S`, "the guard's own deadline is derived from the adapter's handler budget, so it stays below codex's timeout") assert.Contains(t, src, `SPAWN_ADMIT_FINDING = "`+codexSpawnAdmitFinding+`"`, @@ -1308,6 +1319,26 @@ func codexChildSpawnInput() map[string]any { return in } +// codexSpawnInputV2 is the PreToolUse payload codex sends for a V2 spawn of +// role from the root thread: the `collaboration` namespace joined with the +// tool name, and task_name and fork_turns in place of fork_context. An empty +// role omits agent_type, which asks codex for the default role. +func codexSpawnInputV2(role string) map[string]any { + in := codexSpawnInput("") + in["model"] = "gpt-5.6-sol" + in["tool_name"] = "collaborationspawn_agent" + args := map[string]any{ + "fork_turns": "none", + "message": "Review the diff for correctness.", + "task_name": "correctness", + } + if role != "" { + args["agent_type"] = role + } + in["tool_input"] = args + return in +} + // codexSpawnArgs is the spawn's tool_input, for a test that edits it. func codexSpawnArgs(in map[string]any) map[string]any { return in["tool_input"].(map[string]any) @@ -1400,9 +1431,10 @@ func (h *codexAdapterHarness) findingsLog() string { } // TestCodexAdapter_SpawnGuardAdmits covers what the guard lets through: a -// root-thread V1 spawn of a registered role, and the V1 tools that act on a -// child already admitted. An allow writes nothing, since stdout codex cannot -// parse fails the hook; an admitted spawn is recorded in the findings log. +// root-thread spawn of a registered role, V1 or V2, and the tools of either +// version that act on a child already admitted. An allow writes nothing, +// since stdout codex cannot parse fails the hook; an admitted spawn is +// recorded in the findings log. func TestCodexAdapter_SpawnGuardAdmits(t *testing.T) { unnamed := codexSpawnInput("") delete(codexSpawnArgs(unnamed), "agent_type") @@ -1412,6 +1444,17 @@ func TestCodexAdapter_SpawnGuardAdmits(t *testing.T) { in["tool_input"] = map[string]any{"target": "01a0ee84-2a04-7d03-b84f-ad297f46b50e"} return in } + spacedNone := codexSpawnInputV2("correctness") + codexSpawnArgs(spacedNone)["fork_turns"] = " None " + upperNone := codexSpawnInputV2("correctness") + codexSpawnArgs(upperNone)["fork_turns"] = "NONE" + // The guard reads nothing of a pass-through's arguments. + passThroughV2 := func(tool string, input map[string]any) map[string]any { + in := codexSpawnInputV2("correctness") + in["tool_name"] = tool + in["tool_input"] = input + return in + } cases := []struct { name string @@ -1424,6 +1467,13 @@ func TestCodexAdapter_SpawnGuardAdmits(t *testing.T) { {"V1 wait_agent passes through, no role registered", passThrough("multi_agent_v1wait_agent"), nil, ""}, {"V1 close_agent passes through", passThrough("multi_agent_v1close_agent"), []string{"correctness"}, ""}, {"V1 send_input passes through", passThrough("multi_agent_v1send_input"), []string{"correctness"}, ""}, + {"V2 spawn of a registered role, fork_turns none, no override", codexSpawnInputV2("correctness"), []string{"correctness", "default"}, "admitted spawn tool_use_id=call_1_0 agent_type=correctness"}, + {"V2 agent_type absent maps to default", codexSpawnInputV2(""), []string{"default"}, "admitted spawn tool_use_id=call_1_0 agent_type=default"}, + {"V2 fork_turns trimmed as codex trims it", spacedNone, []string{"correctness"}, "admitted spawn tool_use_id=call_1_0 agent_type=correctness"}, + {"V2 fork_turns compared case-insensitively", upperNone, []string{"correctness"}, "admitted spawn tool_use_id=call_1_0 agent_type=correctness"}, + {"V2 wait_agent passes through, no role registered", passThroughV2("collaborationwait_agent", map[string]any{"timeout_ms": 60000}), nil, ""}, + {"V2 list_agents passes through", passThroughV2("collaborationlist_agents", map[string]any{}), []string{"correctness"}, ""}, + {"V2 interrupt_agent passes through", passThroughV2("collaborationinterrupt_agent", map[string]any{}), []string{"correctness"}, ""}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -1462,6 +1512,17 @@ func TestCodexAdapter_SpawnGuardDenies(t *testing.T) { edit(codexSpawnArgs(in)) return in } + withArgsV2 := func(edit func(args map[string]any)) map[string]any { + in := codexSpawnInputV2("correctness") + edit(codexSpawnArgs(in)) + return in + } + namedV2 := func(tool string, input map[string]any) map[string]any { + in := codexSpawnInputV2("correctness") + in["tool_name"] = tool + in["tool_input"] = input + return in + } rules := []struct { name string run func(t *testing.T, h *codexAdapterHarness) codexAdapterResult @@ -1486,13 +1547,54 @@ func TestCodexAdapter_SpawnGuardDenies(t *testing.T) { in["tool_name"] = "multi_agent_v1resume_agent" in["tool_input"] = map[string]any{"target": "01a0ee84-2a04-7d03-b84f-ad297f46b50e"} return h.spawnGuard(in, "correctness") - }, "is not the V1 spawn tool"}, - {"tool collaborationspawn_agent", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { - in := codexSpawnInput("correctness") - in["tool_name"] = "collaborationspawn_agent" - in["model"] = "gpt-5.6-sol" + }, "is not a spawn tool the runner admits"}, + {"V2 send_message reaches a child again", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { + return h.spawnGuard(namedV2("collaborationsend_message", map[string]any{"target": "correctness", "message": "more"}), "correctness") + }, "is not a spawn tool the runner admits"}, + {"V2 followup_task is the V2 resume", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { + return h.spawnGuard(namedV2("collaborationfollowup_task", map[string]any{"target": "correctness", "message": "again"}), "correctness") + }, "is not a spawn tool the runner admits"}, + {"V2 fork_turns absent forks the parent's whole history", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { + return h.spawnGuard(withArgsV2(func(a map[string]any) { delete(a, "fork_turns") }), "correctness") + }, `fork_turns: "none"`}, + {"V2 fork_turns 0 is not none", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { + return h.spawnGuard(withArgsV2(func(a map[string]any) { a["fork_turns"] = "0" }), "correctness") + }, `fork_turns: "none"`}, + {"V2 fork_turns all", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { + return h.spawnGuard(withArgsV2(func(a map[string]any) { a["fork_turns"] = "all" }), "correctness") + }, `fork_turns: "none"`}, + {"V2 fork_turns a number", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { + return h.spawnGuard(withArgsV2(func(a map[string]any) { a["fork_turns"] = 3 }), "correctness") + }, `fork_turns: "none"`}, + {"V2 fork_turns null", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { + return h.spawnGuard(withArgsV2(func(a map[string]any) { a["fork_turns"] = nil }), "correctness") + }, `fork_turns: "none"`}, + {"V2 fork_turns whitespace only (codex maps it to all)", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { + return h.spawnGuard(withArgsV2(func(a map[string]any) { a["fork_turns"] = " " }), "correctness") + }, `fork_turns: "none"`}, + {"V2 fork_context present", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { + return h.spawnGuard(withArgsV2(func(a map[string]any) { a["fork_context"] = false }), "correctness") + }, "no fork_context"}, + {"V2 model argument present", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { + return h.spawnGuard(withArgsV2(func(a map[string]any) { a["model"] = "gpt-5.6-sol" }), "correctness") + }, "must not pass model"}, + {"V2 reasoning_effort argument null", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { + return h.spawnGuard(withArgsV2(func(a map[string]any) { a["reasoning_effort"] = nil }), "correctness") + }, "must not pass reasoning_effort"}, + {"V2 built-in explorer", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { + return h.spawnGuard(codexSpawnInputV2("explorer"), "correctness", "default") + }, "'explorer' is not one the runner registered"}, + {"V2 spawn from a child", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { + in := codexSpawnInputV2("correctness") + in["agent_id"] = "01a0ee89-1b2e-7c60-8812-87a59542808f" + in["agent_type"] = "correctness" + return h.spawnGuard(in, "correctness") + }, "a child may not spawn"}, + {"V2 pass-through name from a child, agent_type only", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { + in := namedV2("collaborationwait_agent", map[string]any{"timeout_ms": 60000}) + in["agent_type"] = "correctness" return h.spawnGuard(in, "correctness") - }, "is not the V1 spawn tool"}, + }, "is not allowed from a child"}, {"spawn from a child (agent_id and agent_type present)", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { return h.spawnGuard(codexChildSpawnInput(), "correctness") }, "a child may not spawn"}, @@ -1599,16 +1701,13 @@ func TestCodexAdapter_SpawnGuardDenies(t *testing.T) { return h.spawnGuardRaw(" ", h.spawnEnv(h.spawnDigests("correctness"))) }, "cannot be scanned"}, {"unknown tool in the V2 namespace (deny-by-default)", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { - in := codexSpawnInput("correctness") - in["tool_name"] = "collaborationwait_agent" - in["tool_input"] = map[string]any{"target": "01a0ee84-2a04-7d03-b84f-ad297f46b50e"} - return h.spawnGuard(in, "correctness") - }, "is not the V1 spawn tool"}, + return h.spawnGuard(namedV2("collaborationresume_agent", map[string]any{"target": "correctness"}), "correctness") + }, "is not a spawn tool the runner admits"}, {"unknown tool in the V1 namespace (deny-by-default)", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { in := codexSpawnInput("correctness") in["tool_name"] = "multi_agent_v1fork_agent" return h.spawnGuard(in, "correctness") - }, "is not the V1 spawn tool"}, + }, "is not a spawn tool the runner admits"}, {"role file swapped for a FIFO", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { // A plain open() of a FIFO would block until codex's timeout, which // does not block the spawn; the guard must refuse it at once. @@ -1678,3 +1777,224 @@ func TestCodexAdapter_SpawnGuardDenies(t *testing.T) { }) } } + +// codexSubagentStopInput is the SubagentStop payload codex sends from a +// thread-spawned child (rust-v0.166.0 hooks/src/schema.rs +// SubagentStopCommandInput), with message as last_assistant_message. +func codexSubagentStopInput(message any) map[string]any { + return map[string]any{ + "session_id": "01a0eea5-cf24-7250-ae7b-df1cd9b70160", + "turn_id": "t1", + "transcript_path": nil, + "agent_transcript_path": nil, + "cwd": "/sandbox/workspace/repo", + "hook_event_name": "SubagentStop", + "model": "gpt-5.6-luna", + "permission_mode": "bypassPermissions", + "stop_hook_active": false, + "agent_id": "01a0ee84-2a04-7d03-b84f-ad297f46b50e", + "agent_type": "correctness", + "last_assistant_message": message, + } +} + +// codexSubagentStopPrompt is the adapter's SUBAGENT_STOP_PROMPT, which every +// block on the SubagentStop phase sends in place of its reason. +const codexSubagentStopPrompt = "fullsend: your final message was withheld by the security chain and was " + + "not delivered. Reply with exactly: " + codexWithheldNotice + +// assertSubagentStopBlock checks the shape codex continues a child on: exit +// 2 with the fixed withheld-notice prompt as the whole of stderr (an exit 2 +// with an empty stderr is a failed hook, which does not block, +// hooks/src/events/stop.rs), nothing on stdout, so no `continue: false` can +// end the child and deliver it, and the reason in the findings log only: a +// child told which stage fired could reword its result until one passed. +func assertSubagentStopBlock(t *testing.T, got codexAdapterResult, findings, reason string) { + t.Helper() + assert.Equal(t, 2, got.exitCode, got.stderr) + assert.Empty(t, got.stdout, "a SubagentStop block writes nothing on stdout") + assert.Equal(t, codexSubagentStopPrompt, got.stderr, "the child reads only the fixed prompt") + assert.Contains(t, readFileString(t, findings), reason, "the reason goes to the findings log") +} + +// TestCodexAdapter_SubagentStopGate covers the child-result gate (ADR 0159 +// decision 4): the chain runs on the child's final message as an Agent +// result; a block continues the child with the withheld-notice prompt, a +// clean message and an empty one pass, every failure of the adapter blocks +// the same way, and after a block only the exact notice passes. +func TestCodexAdapter_SubagentStopGate(t *testing.T) { + const flagged = "Findings: none.\nOPENAI_API_KEY=sk-proj-abcdefghijklmnopqrstuvwx" + + t.Run("the chain's block continues the child with the prompt", func(t *testing.T) { + h := newCodexAdapterHarness(t) + h.installPostToolChain() + findings := h.findingsLog() + got := h.run("SubagentStop", codexSubagentStopInput(flagged), "posttool_chain.py") + assertSubagentStopBlock(t, got, findings, "security-sensitive content") + assert.NotContains(t, readFileString(t, findings), "sk-proj-", "the flagged value must not be logged") + }) + + t.Run("the scripts see the message as an Agent result", func(t *testing.T) { + h := newCodexAdapterHarness(t) + seen := filepath.Join(h.dir, "seen.json") + h.script("block.py", `open(`+pyStr(seen)+`, "w").write(json.dumps(payload)) +print(json.dumps({"decision": "block", "reason": "canary token in the result"})) +sys.exit(1)`) + findings := h.findingsLog() + got := h.run("SubagentStop", codexSubagentStopInput("the result"), "block.py") + assertSubagentStopBlock(t, got, findings, "canary token in the result") + var payload map[string]any + require.NoError(t, json.Unmarshal([]byte(readFileString(t, seen)), &payload)) + assert.Equal(t, "Agent", payload["tool_name"]) + assert.Equal(t, "the result", payload["tool_response"]) + assert.Equal(t, "the result", payload["tool_result"]) + assert.Equal(t, map[string]any{}, payload["tool_input"]) + assert.Equal(t, "/sandbox/workspace/repo", payload["cwd"]) + }) + + t.Run("a clean message passes", func(t *testing.T) { + h := newCodexAdapterHarness(t) + h.installPostToolChain() + got := h.run("SubagentStop", codexSubagentStopInput("Correctness: no findings in the diff."), "posttool_chain.py") + assert.Equal(t, codexAdapterResult{}, got, "exit 0 with nothing on either stream") + }) + + t.Run("the withheld notice passes, even when the chain would block", func(t *testing.T) { + // The child's reply to the prompt reaches the gate again. The notice + // carries no content, so it passes before the chain runs: a + // compliant child can finish even when the chain blocks for a + // reason that is not the message (here, a script changed on disk). + h := newCodexAdapterHarness(t) + findings := h.findingsLog() + h.script("allow.py", "sys.exit(0)") + require.NoError(t, os.WriteFile(filepath.Join(h.hooksDir, "allow.py"), []byte("import sys\nsys.exit(0)\n"), 0o755)) + for _, message := range []string{codexWithheldNotice, "\n" + codexWithheldNotice + "\n"} { + assert.Equal(t, codexAdapterResult{}, h.run("SubagentStop", codexSubagentStopInput(message), "allow.py")) + } + // Only ASCII whitespace may pad it: anything else, such as a hidden + // separator, goes through the chain, which here blocks. + for _, message := range []string{codexWithheldNotice + " and the result", codexWithheldNotice + "\u2028", "\x1c" + codexWithheldNotice} { + assertSubagentStopBlock(t, h.run("SubagentStop", codexSubagentStopInput(message), "allow.py"), findings, "changed since the run started") + } + }) + + t.Run("an empty or null message has nothing to screen", func(t *testing.T) { + h := newCodexAdapterHarness(t) + ran := filepath.Join(h.dir, "ran") + h.script("record.py", `open(`+pyStr(ran)+`, "w").close() +sys.exit(1)`) + for name, input := range map[string]map[string]any{ + "empty": codexSubagentStopInput(""), + "null": codexSubagentStopInput(nil), + } { + t.Run(name, func(t *testing.T) { + got := h.run("SubagentStop", input, "record.py") + assert.Equal(t, codexAdapterResult{}, got) + assert.NoFileExists(t, ran, "no script runs on an empty message") + }) + } + }) + + t.Run("an adapter failure blocks with the prompt", func(t *testing.T) { + for _, tc := range []struct { + name string + run func(t *testing.T, h *codexAdapterHarness) codexAdapterResult + want string + }{ + {"a script that crashes", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { + h.script("crash.py", `raise RuntimeError("boom")`) + return h.run("SubagentStop", codexSubagentStopInput("the result"), "crash.py") + }, "fullsend: hook crash.py exited 1"}, + {"a script changed since the run started", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { + h.script("allow.py", "sys.exit(0)") + require.NoError(t, os.WriteFile(filepath.Join(h.hooksDir, "allow.py"), []byte("import sys\nsys.exit(0)\n"), 0o755)) + return h.run("SubagentStop", codexSubagentStopInput("the result"), "allow.py") + }, "changed since the run started"}, + {"no script on the command line", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { + return h.run("SubagentStop", codexSubagentStopInput("the result")) + }, "needs and at least one script"}, + {"a payload that is not a JSON object", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { + h.script("allow.py", "sys.exit(0)") + return h.runRaw("SubagentStop", "[]", "allow.py") + }, "not a JSON object"}, + {"an empty payload", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { + h.script("allow.py", "sys.exit(0)") + return h.runRaw("SubagentStop", " ", "allow.py") + }, "codex sent an empty SubagentStop payload"}, + {"a payload without last_assistant_message", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { + h.script("allow.py", "sys.exit(0)") + in := codexSubagentStopInput(nil) + delete(in, "last_assistant_message") + return h.run("SubagentStop", in, "allow.py") + }, "no last_assistant_message string"}, + {"a last_assistant_message that is not a string", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { + h.script("allow.py", "sys.exit(0)") + return h.run("SubagentStop", codexSubagentStopInput(map[string]any{"text": "the result"}), "allow.py") + }, "no last_assistant_message string"}, + {"the adapter itself crashing", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { + // json.loads raises RecursionError on deep nesting, which + // parse_json does not catch: the __main__ handler blocks. + h.script("allow.py", "sys.exit(0)") + return h.runRaw("SubagentStop", strings.Repeat("[", 200000)+strings.Repeat("]", 200000), "allow.py") + }, "RecursionError"}, + {"a reason longer than the adapter's cap", func(t *testing.T, h *codexAdapterHarness) codexAdapterResult { + h.script("block.py", `print(json.dumps({"decision": "block", "reason": "x" * 20000})) +sys.exit(1)`) + return h.run("SubagentStop", codexSubagentStopInput("the result"), "block.py") + }, "xxx"}, + } { + t.Run(tc.name, func(t *testing.T) { + h := newCodexAdapterHarness(t) + findings := h.findingsLog() + assertSubagentStopBlock(t, tc.run(t, h), findings, tc.want) + }) + } + }) + + t.Run("after a block only the exact notice passes", func(t *testing.T) { + // codex sets stop_hook_active once a stop hook has blocked in the + // child's turn (core/src/session/turn.rs). The child must not get + // another try through the chain: anything but the notice blocks, even + // a clean message, and the chain does not run. + h := newCodexAdapterHarness(t) + ran := filepath.Join(h.dir, "ran") + h.script("record.py", `open(`+pyStr(ran)+`, "w").close() +sys.exit(0)`) + findings := h.findingsLog() + retry := func(message any) map[string]any { + in := codexSubagentStopInput(message) + in["stop_hook_active"] = true + return in + } + for _, message := range []string{codexWithheldNotice, " \t" + codexWithheldNotice + "\r\n"} { + assert.Equal(t, codexAdapterResult{}, h.run("SubagentStop", retry(message), "record.py")) + } + missing := retry(nil) + delete(missing, "last_assistant_message") + for name, input := range map[string]map[string]any{ + "a clean but different message": retry("Correctness: no findings in the diff."), + "the notice with more text": retry(codexWithheldNotice + " and the result"), + "the notice and a hidden separator": retry(codexWithheldNotice + "\u2028"), + "an empty message": retry(""), + "a null message": retry(nil), + "no message": missing, + "a message that is not a string": retry(map[string]any{"text": "the result"}), + } { + t.Run(name, func(t *testing.T) { + assertSubagentStopBlock(t, h.run("SubagentStop", input, "record.py"), findings, "was not the withheld notice") + }) + } + assert.NoFileExists(t, ran, "the chain does not run after a block") + }) + + t.Run("other phases carry no prompt", func(t *testing.T) { + h := newCodexAdapterHarness(t) + h.installPostToolChain() + input := codexBashInput("cat .env") + input["hook_event_name"] = "PostToolUse" + input["tool_response"] = flagged + got := h.run("PostToolUse", input, "posttool_chain.py") + assert.Equal(t, 2, got.exitCode) + assert.NotContains(t, got.stderr, codexWithheldNotice, "the prompt is the SubagentStop phase's only") + }) +} diff --git a/internal/runtime/codex_personas.go b/internal/runtime/codex_personas.go index ddbeb6d9e8..0a566b3074 100644 --- a/internal/runtime/codex_personas.go +++ b/internal/runtime/codex_personas.go @@ -26,8 +26,9 @@ func codexDelegates(def *piAgentDef, securityEnabled bool) bool { // codexRole is one native Codex sub-agent role, written to // $CODEX_HOME/agents/.toml. Instructions is the child's -// developer_instructions: codexChildNote, then the persona body; nothing of -// the dropped frontmatter (#6970). +// developer_instructions: the collaboration version's child note +// (codexChildNote, codexChildNoteV2), then the persona body; nothing of the +// dropped frontmatter (#6970). type codexRole struct { Name, Description, Instructions string // Model is the child's model, set only for a skill persona with its own @@ -224,10 +225,11 @@ func (role codexRole) toml() []byte { "developer_instructions = " + codexTOMLString(role.Instructions) + "\n") } -// codexChildNote opens every role's developer_instructions. A native child -// runs with its role's developer_instructions in place of the parent's, so -// nothing of codexNoSubagentNote reaches it: the note carries the child -// contract (pi's CHILD_SYSTEM_NOTE, word for word) and the chunked-read rule. +// codexChildNote opens every V1 role's developer_instructions. A native +// child runs with its role's developer_instructions in place of the +// parent's, so nothing of codexNoSubagentNote reaches it: the note carries +// the child contract (pi's CHILD_SYSTEM_NOTE, word for word) and the +// chunked-read rule. const codexChildNote = "## Runtime note\n\n" + "You are a sub-agent dispatched by another agent. Carry out the single task in the message you " + "were given and then stop. You have no sub-agent tool of your own and cannot dispatch further " + @@ -235,6 +237,19 @@ const codexChildNote = "## Runtime note\n\n" + "dispatched you, so make it self-contained.\n\n" + codexChunkedReadNote + "\n" +// codexChildNoteV2 is codexChildNote for a V2 child. The child inherits the +// feature table (ADR 0159 decision 1), and codex gives it the multi-agent +// tools only when its own model selects V2 in the catalog +// (collab_tools_enabled, codex-rs/core/src/tools/spec_plan.rs). Either way +// the hook denies every such call from a child (ADR 0159 decision 3), and +// the note says so where V1's says the child has no tool. +const codexChildNoteV2 = "## Runtime note\n\n" + + "You are a sub-agent dispatched by another agent. Carry out the single task in the message you " + + "were given and then stop. Do not spawn, wait on, list, message or interrupt agents; any such call " + + "is denied. Your final assistant message is the entire result handed back to the agent that " + + "dispatched you, so make it self-contained.\n\n" + + codexChunkedReadNote + "\n" + // Built-in roles. `default` serves a spawn without agent_type, which is how // retro's unnamed investigation tasks run; `explore` is Claude Code's // Explore as an instruction to the child, not an enforced sandbox: the @@ -256,8 +271,9 @@ const ( // fails Bootstrap: a stray sub-agents/*.md must not stop a run that never // dispatches it, the rule discoverPersonas already applies. The second // value maps each skipped name to its reason, so a subagents key naming one -// fails with that reason, as on pi (resolveCodexChildModels). -func codexRoles(skillDirs []string, agentName string) ([]codexRole, map[string]string) { +// fails with that reason, as on pi (resolveCodexChildModels). version is +// the collaboration version the gate admitted, which picks the child note. +func codexRoles(skillDirs []string, agentName, version string) ([]codexRole, map[string]string) { // discoverPersonas never returns a non-nil error; the value exists for // the pi call site's shape. personas, skipped, _ := discoverPersonas(skillDirs, agentName) @@ -266,9 +282,13 @@ func codexRoles(skillDirs []string, agentName string) ([]codexRole, map[string]s fmt.Fprintf(os.Stderr, "Warning: persona %q skipped: %s\n", sk.Path, sk.Reason) reasons[sk.Name] = sk.Path + ": " + sk.Reason } + note := codexChildNote + if version == "v2" { + note = codexChildNoteV2 + } roles := []codexRole{ - {Name: "default", Description: codexDefaultRoleDescription, Instructions: codexChildNote + codexDefaultRoleInstructions}, - {Name: "explore", Description: codexExploreRoleDescription, Instructions: codexChildNote + codexExploreRoleInstructions}, + {Name: "default", Description: codexDefaultRoleDescription, Instructions: note + codexDefaultRoleInstructions}, + {Name: "explore", Description: codexExploreRoleDescription, Instructions: note + codexExploreRoleInstructions}, } for _, p := range personas { var reason string @@ -290,7 +310,7 @@ func codexRoles(skillDirs []string, agentName string) ([]codexRole, map[string]s "(the role's model is its subagents entry, else the run-level child model) and the parent's tools apply\n", p.Name, strings.Join(keys, ", ")) } - roles = append(roles, codexRole{Name: p.Name, Description: p.Description, Instructions: codexChildNote + p.Body + "\n"}) + roles = append(roles, codexRole{Name: p.Name, Description: p.Description, Instructions: note + p.Body + "\n"}) } slices.SortFunc(roles, func(a, b codexRole) int { return strings.Compare(a.Name, b.Name) }) return roles, reasons @@ -392,14 +412,12 @@ func parseCodexCatalog(data []byte) (codexCatalog, error) { // extended by ADR 0159): the collaboration version the gate takes for the // parent Run will launch ("v1" or "v2", else ""), and the one-line reason // Bootstrap prints when the parent runs in one context. Bootstrap delegates -// only a "v1" parent: the reason explains a decline and never decides one. A -// V2 parent is returned as "v2" with the ADR 0159 reason, and Bootstrap -// declines it until its child-result delivery path is implemented and -// verified live (ADR 0159 decision 4). A parent that does not translate is -// reported by Run with the same error; the gate only declines here. A -// gateway/ parent is declined whatever its id: children would inherit the -// gateway provider with bare OpenAI ids it may not serve, and native children -// have not run on that route. +// a "v1" or "v2" parent, the latter subject to codexV2ChildModelReason: the +// reason explains a decline and never decides one. A parent that does not +// translate is reported by Run with the same error; the gate only declines +// here. A gateway/ parent is declined whatever its id: children would +// inherit the gateway provider with bare OpenAI ids it may not serve, and +// native children have not run on that route. func codexParentCollabVersion(catalog codexCatalog, parentModel, agentModel string) (version, reason string) { model, err := translateCodexModel(EffectiveModel(parentModel, agentModel), true) if err != nil { @@ -412,14 +430,33 @@ func codexParentCollabVersion(catalog codexCatalog, parentModel, agentModel stri if !catalog.has(id) { return "", fmt.Sprintf("parent model %q is not in the bundled catalog of the pinned codex", id) } - switch catalog.collabVersion(id) { - case "v1": - return "v1", "" - case "v2": - return "v2", fmt.Sprintf("parent model %q selects collaboration \"v2\"; V2 delegation is off until its child-result delivery path is verified live (ADR 0159)", id) + if version := catalog.collabVersion(id); version != "" { + return version, "" } if catalog[id].Version == "disabled" { return "", fmt.Sprintf("parent model %q has native sub-agents disabled in the bundled catalog", id) } return "", fmt.Sprintf("parent model %q selects collaboration %q, which the runner does not support", id, catalog[id].Version) } + +// codexV2ChildModelReason is the V2 spawn's backstop (#9085). Codex applies +// no agents.max_depth under V2 and gives a child of a V2 parent the +// multi-agent tools only when the child's own model selects V2 +// (collab_tools_enabled, codex-rs/core/src/tools/spec_plan.rs, +// rust-v0.166.0). With every model the runner binds off V2, a child it +// starts holds no spawn_agent. A spawn the guard did not screen can still +// name a model (the schema hides the argument; the handler accepts it) or +// use a rewritten role file, so for such a spawn depth one still rests on +// the guard (ADR 0159). It returns the reason Bootstrap prints when the +// run-level child model or a persona's own model selects V2, else "". +func codexV2ChildModelReason(catalog codexCatalog, roles []codexRole, defaultModel string) string { + if catalog.collabVersion(defaultModel) == "v2" { + return fmt.Sprintf("child model %q (the run-level child model) selects collaboration \"v2\", so under a V2 parent its children would keep codex's spawn tool", defaultModel) + } + for _, role := range roles { + if role.Model != "" && catalog.collabVersion(role.Model) == "v2" { + return fmt.Sprintf("child model %q (subagents.%s) selects collaboration \"v2\", so under a V2 parent that child would keep codex's spawn tool", role.Model, role.Name) + } + } + return "" +} diff --git a/internal/runtime/codex_personas_test.go b/internal/runtime/codex_personas_test.go index bd43db0688..90ff887b6b 100644 --- a/internal/runtime/codex_personas_test.go +++ b/internal/runtime/codex_personas_test.go @@ -133,7 +133,7 @@ func TestCodexRoles_BuiltinsAlwaysPresent(t *testing.T) { } { t.Run(name, func(t *testing.T) { t.Parallel() - roles, _ := codexRoles(dirs, "retro") + roles, _ := codexRoles(dirs, "retro", "v1") assert.Equal(t, []string{"default", "explore"}, codexRoleNames(roles)) for _, r := range roles { assert.NotEmpty(t, r.Description, "%s: the parent sees the description in the spawn tool's role list", r.Name) @@ -150,7 +150,7 @@ func TestCodexRoles_SkillPersonasSorted(t *testing.T) { writePersonaFile(t, skill, "style", "---\nname: style\ndescription: Style review.\n---\nReview for style.\n") writePersonaFile(t, skill, "correctness", codexTestPersona) - roles, _ := codexRoles([]string{skill}, "review") + roles, _ := codexRoles([]string{skill}, "review", "v1") assert.Equal(t, []string{"correctness", "default", "explore", "style"}, codexRoleNames(roles), "ascending by name, built-ins included; the spawn digest env lists roles in this order") assert.Equal(t, codexRole{ @@ -170,7 +170,7 @@ func TestCodexRoles_DiscoverySkipIsAWarning(t *testing.T) { var roles []codexRole var skipped map[string]string - out := captureStderr(t, func() { roles, skipped = codexRoles([]string{skill}, "review") }) + out := captureStderr(t, func() { roles, skipped = codexRoles([]string{skill}, "review", "v1") }) assert.Equal(t, []string{"default", "explore"}, codexRoleNames(roles)) assert.Equal(t, filepath.Join(skill, "sub-agents", "default.md")+": name is reserved", skipped["default"], @@ -212,7 +212,7 @@ func TestCodexRoles_SkipsInvalidPersonas(t *testing.T) { var roles []codexRole var skipped map[string]string - out := captureStderr(t, func() { roles, skipped = codexRoles([]string{skill}, "review") }) + out := captureStderr(t, func() { roles, skipped = codexRoles([]string{skill}, "review", "v1") }) assert.Equal(t, []string{"default", "explore"}, codexRoleNames(roles)) assert.Contains(t, out, tt.wantWarn) @@ -231,7 +231,7 @@ func TestCodexRoles_DuplicateAcrossSkillsKeepsTheFirst(t *testing.T) { writePersonaFile(t, second, "correctness", "---\nname: correctness\ndescription: Other.\n---\nOther body.\n") var roles []codexRole - out := captureStderr(t, func() { roles, _ = codexRoles([]string{first, second}, "review") }) + out := captureStderr(t, func() { roles, _ = codexRoles([]string{first, second}, "review", "v1") }) assert.Equal(t, []string{"correctness", "default", "explore"}, codexRoleNames(roles)) assert.Equal(t, codexChildNote+"# Correctness\n\nYou are a senior software engineer reviewing for correctness.\n", roles[0].Instructions) @@ -249,7 +249,7 @@ func TestCodexRoles_ReportsDroppedFrontmatter(t *testing.T) { writePersonaFile(t, skill, "clean", "---\nname: clean\ndescription: d\n---\nbody\n") var roles []codexRole - out := captureStderr(t, func() { roles, _ = codexRoles([]string{skill}, "review") }) + out := captureStderr(t, func() { roles, _ = codexRoles([]string{skill}, "review", "v1") }) assert.Contains(t, out, `Codex persona "all-five": frontmatter model, tools, permissionMode, background, maxTurns dropped`) assert.Contains(t, out, `Codex persona "two": frontmatter model, maxTurns dropped`, "fixed order, not file order") @@ -276,7 +276,7 @@ func TestCodexRoles_DroppedFrontmatterIsTheRegisteredFile(t *testing.T) { registered := t.TempDir() writePersonaFile(t, registered, "correctness", tc.registered) - out := captureStderr(t, func() { codexRoles([]string{skipped, registered}, "review") }) + out := captureStderr(t, func() { codexRoles([]string{skipped, registered}, "review", "v1") }) assert.Contains(t, out, "skipped: frontmatter name") if tc.want == "" { @@ -324,11 +324,36 @@ func codexDecodeTOML(t *testing.T, data []byte) map[string]any { return doc } +// TestCodexRoles_V2ChildNote: on V2 every role opens with codexChildNoteV2, +// the V1 note with its no-tool sentence replaced by the denial of every +// multi-agent call (ADR 0159 decision 3), and differs from its V1 role in +// nothing else. +func TestCodexRoles_V2ChildNote(t *testing.T) { + t.Parallel() + skill := t.TempDir() + writePersonaFile(t, skill, "correctness", codexTestPersona) + + v1, _ := codexRoles([]string{skill}, "review", "v1") + v2, _ := codexRoles([]string{skill}, "review", "v2") + require.Len(t, v2, len(v1)) + for i := range v1 { + assert.True(t, strings.HasPrefix(v1[i].Instructions, codexChildNote), v1[i].Name) + assert.True(t, strings.HasPrefix(v2[i].Instructions, codexChildNoteV2), v2[i].Name) + assert.Equal(t, v1[i], codexRole{Name: v2[i].Name, Description: v2[i].Description, + Instructions: codexChildNote + strings.TrimPrefix(v2[i].Instructions, codexChildNoteV2), Model: v2[i].Model}, + "%s: the note is the only difference", v2[i].Name) + } + assert.Equal(t, strings.Replace(codexChildNote, + "You have no sub-agent tool of your own and cannot dispatch further work.", + "Do not spawn, wait on, list, message or interrupt agents; any such call is denied.", 1), codexChildNoteV2) + assert.NotEqual(t, codexChildNote, codexChildNoteV2) +} + func TestCodexRole_TOMLParsesWithTheThreeKeys(t *testing.T) { skill := t.TempDir() writePersonaFile(t, skill, "correctness", codexTestPersona) - roles, _ := codexRoles([]string{skill}, "review") + roles, _ := codexRoles([]string{skill}, "review", "v1") for _, role := range roles { doc := codexDecodeTOML(t, role.toml()) assert.Len(t, doc, 3, "%s: name, description, developer_instructions and nothing else", role.Name) @@ -388,12 +413,10 @@ func TestCodexCatalog(t *testing.T) { // extended by ADR 0159): the parent model Run will use (the run-level model, // else the definition's) must translate to an OpenAI id, whose catalog entry // gives a version: V1 when it selects V1 or carries none (codex's multi_agent -// feature, on by default, supplies V1), V2 when it selects V2. Only a "v1" -// result delegates; a V2 parent gets "v2" and the ADR 0159 reason, and -// Bootstrap declines it until its child-result delivery path is implemented -// and verified live. A disabled, unknown-version or unlisted parent gets no -// version from the gate and says why in one line, and so does a gateway/ -// parent whatever its id. +// feature, on by default, supplies V1), V2 when it selects V2, either with +// no reason. A disabled, unknown-version or unlisted parent gets no version +// from the gate and says why in one line, and so does a gateway/ parent +// whatever its id. func TestCodexParentCollabVersion(t *testing.T) { t.Parallel() catalog := codexVersionsCatalog(map[string]string{"gpt-5.6-luna": "v1", "gpt-5.6-sol": "v2", "gpt-5.5": "", "gpt-x": "v3", "gpt-d": "disabled"}) @@ -406,7 +429,8 @@ func TestCodexParentCollabVersion(t *testing.T) { }{ {"definition model, V1", "", "openai/gpt-5.6-luna", "v1", ""}, {"run-level model wins", "openai/gpt-5.6-luna", "openai/gpt-5.6-sol", "v1", ""}, - {"run-level V2 beats a V1 definition", "openai/gpt-5.6-sol", "openai/gpt-5.6-luna", "v2", `parent model "gpt-5.6-sol" selects collaboration "v2"; V2 delegation is off until its child-result delivery path is verified live (ADR 0159)`}, + {"run-level V2 beats a V1 definition", "openai/gpt-5.6-sol", "openai/gpt-5.6-luna", "v2", ""}, + {"definition model, V2", "", "openai/gpt-5.6-sol", "v2", ""}, {"no multi-agent version (multi_agent supplies V1)", "", "gpt-5.5", "v1", ""}, {"catalog says disabled", "", "openai/gpt-d", "", `parent model "gpt-d" has native sub-agents disabled in the bundled catalog`}, {"unknown collaboration version", "", "openai/gpt-x", "", `parent model "gpt-x" selects collaboration "v3", which the runner does not support`}, @@ -433,6 +457,41 @@ func TestCodexParentCollabVersion(t *testing.T) { } } +// TestCodexV2ChildModelReason is the V2 spawn's backstop: a V2 parent +// delegates only while no child model selects V2, since codex gives a V2 +// child the multi-agent tools exactly when its own model does. The +// run-level child model serves the default and explore roles and every +// persona without a model of its own, so it is checked first. +func TestCodexV2ChildModelReason(t *testing.T) { + t.Parallel() + catalog := codexVersionsCatalog(map[string]string{"gpt-5.6-luna": "v1", "gpt-5.6-sol": "v2", "gpt-5.5": "", "gpt-d": "disabled"}) + personas := func(models ...string) []codexRole { + roles := []codexRole{{Name: "default"}, {Name: "explore"}} + for i, model := range models { + roles = append(roles, codexRole{Name: fmt.Sprintf("persona%d", i), Model: model}) + } + return roles + } + for _, tc := range []struct { + name string + roles []codexRole + defaultModel string + want string + }{ + {"V1 run-level model, no persona model", personas(), "gpt-5.6-luna", ""}, + {"persona models without V2", personas("gpt-5.5", "gpt-5.6-luna", "gpt-d"), "gpt-5.5", ""}, + {"V2 run-level model", personas(), "gpt-5.6-sol", + `child model "gpt-5.6-sol" (the run-level child model) selects collaboration "v2", so under a V2 parent its children would keep codex's spawn tool`}, + {"a persona's own V2 model", personas("gpt-5.6-luna", "gpt-5.6-sol"), "gpt-5.6-luna", + `child model "gpt-5.6-sol" (subagents.persona1) selects collaboration "v2", so under a V2 parent that child would keep codex's spawn tool`}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tc.want, codexV2ChildModelReason(catalog, tc.roles, tc.defaultModel)) + }) + } +} + // TestCodexChildModel pins the check a configured child model gets: an // OpenAI id, bare or prefixed; everything else, a gateway/ spec and // `inherit` included, fails naming the key and the entry's own fix. diff --git a/internal/runtime/codex_run_test.go b/internal/runtime/codex_run_test.go index 015c58a952..427f1f6554 100644 --- a/internal/runtime/codex_run_test.go +++ b/internal/runtime/codex_run_test.go @@ -497,7 +497,7 @@ func TestCodexConfigGuard_Executes(t *testing.T) { dir := t.TempDir() r := CodexRuntime{} - good, err := renderCodexConfig(dir, "/sandbox/workspace/repo", "body", "", nil, "", "") + good, err := renderCodexConfig(dir, "/sandbox/workspace/repo", "body", "", nil, "", "", false) require.NoError(t, err) digests := codexRunnerHeldDigestSet{ConfigTOML: codexAssetSHA256(good)} guard := strings.ReplaceAll(codexConfigGuard(r, digests), sandbox.SandboxCodexConfig, dir) diff --git a/internal/runtime/codex_subagents_test.go b/internal/runtime/codex_subagents_test.go index aed22c8987..e37b90cbd2 100644 --- a/internal/runtime/codex_subagents_test.go +++ b/internal/runtime/codex_subagents_test.go @@ -1315,6 +1315,18 @@ func codexRolloutLine(id, parent string) string { return `{"timestamp":"2026-09-29T15:46:31.000Z","type":"session_meta","payload":{"id":"` + id + `","cwd":"/sandbox/workspace/repo"` + extra + `,"base_instructions":{"text":"quoted \"parent_thread_id\":\"` + codexRootThreadID + `\" stays inert"}}}` + "\n" } +// codexV2RolloutLine is the session_meta first line of a collaboration V2 +// child at 0.166.0, modelled on a harness capture with synthetic ids: the +// parent is named at the top level and again under +// source.subagent.thread_spawn, beside the spawn's depth and agent_path. +func codexV2RolloutLine(id, parent string) string { + return `{"timestamp":"2026-11-03T10:00:00.000Z","type":"session_meta","payload":{"session_id":"` + parent + `","id":"` + id + `",` + + `"parent_thread_id":"` + parent + `","timestamp":"2026-11-03T10:00:00.000Z","cwd":"/sandbox/workspace/repo",` + + `"originator":"codex_exec","cli_version":"0.166.0","source":{"subagent":{"thread_spawn":{"parent_thread_id":"` + parent + `",` + + `"depth":1,"agent_path":"/root/child","agent_role":"default"}}},"thread_source":"subagent","agent_role":"default",` + + `"multi_agent_version":"v2"}}` + "\n" +} + // writeCodexRollout writes one more rollout under sessions/. func writeCodexRollout(t *testing.T, sessions, day, id, content string) { t.Helper() @@ -1449,7 +1461,8 @@ func TestCountCodexChildRollouts_NameKnownParentNeedsTheStream(t *testing.T) { // per file, a quoted key inside a string inert, an empty, undecodable or // unreadable first line, or a session_meta line cut before its parent, known // by its file name's thread id, an unclosed line that names its parent read -// by content, a revert's second +// by content, a V2 child's head, which names its parent twice, counted +// once, a revert's second // file of a thread counted once, a name that carries no thread id read by // content, a missing directory empty, and a find that cannot read a directory // exits 3. @@ -1459,17 +1472,19 @@ func TestCodexChildRolloutsReadCommand_UnderSh(t *testing.T) { torn, empty, spaced = "01a06300-0000-7000-8000-0000000000ee", "01a06300-0000-7000-8000-0000000000e1", "01a06300-0000-7000-8000-0000000000e2" locked, revert = "01a06300-0000-7000-8000-0000000000e3", "01a06300-0000-7000-8000-0000000000e4" cutMeta, unclosed = "01a06300-0000-7000-8000-0000000000e5", "01a06300-0000-7000-8000-0000000000e6" + v2Child = "01a06300-0000-7000-8000-0000000000e7" ) sessions := writeCodexChildRollouts(t) writeCodexRollout(t, sessions, "2026/09/29", codexChildSameModelID, codexRolloutLine(codexChildSameModelID, codexRootThreadID)) writeCodexRollout(t, sessions, "2026/09/30", codexChildOtherModelID, codexRolloutLine(codexChildOtherModelID, codexRootThreadID)) + writeCodexRollout(t, sessions, "2026/11/03", v2Child, codexV2RolloutLine(v2Child, codexRootThreadID)) writeCodexRollout(t, sessions, "2026/09/30", torn, "not json\n") writeCodexRollout(t, sessions, "2026/09/30", empty, "") writeCodexRollout(t, sessions, "2026/09/30", codexChildSameModelID+"_"+revert, "") writeCodexRollout(t, sessions, "2026/09/30", spaced+" copy", codexRolloutLine(spaced, codexRootThreadID)) writeCodexRollout(t, sessions, "2026/09/30", cutMeta, `{"timestamp":"2026-09-29T15:46:31.000Z","type":"session_meta","payload":{"id":"`+cutMeta+`"`) writeCodexRollout(t, sessions, "2026/09/30", unclosed, strings.TrimSuffix(codexRolloutLine(unclosed, codexRootThreadID), "\n")) - want := []string{codexChildSameModelID, codexChildOtherModelID, torn, empty, spaced, cutMeta, unclosed} + want := []string{codexChildSameModelID, codexChildOtherModelID, v2Child, torn, empty, spaced, cutMeta, unclosed} if os.Geteuid() != 0 { writeCodexRollout(t, sessions, "2026/09/30", locked, codexRolloutLine(locked, "")) lockedPath := filepath.Join(sessions, "2026/09/30", "rollout-2026-09-29T15-46-40-"+locked+".jsonl") @@ -1481,7 +1496,7 @@ func TestCodexChildRolloutsReadCommand_UnderSh(t *testing.T) { require.NoError(t, err) n, ids, err := countCodexChildRollouts(parseCodexRolloutHeads(out), codexRootThreadID, nil) require.NoError(t, err) - assert.Equal(t, len(want), n, "two children across two date directories, the cut, empty and unreadable files by name, the spaced name by content, the revert's file once; the root is not counted") + assert.Equal(t, len(want), n, "three children across three date directories, the V2 one once, though its head names its parent twice, the cut, empty and unreadable files by name, the spaced name by content, the revert's file once; the root is not counted") assert.ElementsMatch(t, want, ids) out, err = exec.Command("/bin/sh", "-c", codexChildRolloutsReadCommand(filepath.Join(t.TempDir(), "missing"))).Output() diff --git a/internal/runtime/testdata/codex/README.md b/internal/runtime/testdata/codex/README.md index f8e169e133..156effd275 100644 --- a/internal/runtime/testdata/codex/README.md +++ b/internal/runtime/testdata/codex/README.md @@ -54,7 +54,10 @@ The tests lay the rollouts out under a temporary sessions tree as and the findings log beside the tree as `.security/findings.jsonl`. `spawn_admissions.jsonl` is that log for a run whose spawn guard admitted three spawns and denied one, in the adapter's `log_finding` shape, plus one `secret_redact_posttool` finding; `countCodexSpawnAdmissions` -counts the three `codex_spawn_guard_admit` lines by name. +counts the three `codex_spawn_guard_admit` lines by name. The V2 child head the +read-command test writes (`codexV2RolloutLine`) is modelled on a 0.166.0 harness +capture, with synthetic ids: `parent_thread_id` at the top level and again under +`source.subagent.thread_spawn`, beside the spawn's `depth` and `agent_path`. ## Event structs diff --git a/internal/runtime/testdata/codex/golden/config-delegating-v2.toml b/internal/runtime/testdata/codex/golden/config-delegating-v2.toml new file mode 100644 index 0000000000..a250a1d3b6 --- /dev/null +++ b/internal/runtime/testdata/codex/golden/config-delegating-v2.toml @@ -0,0 +1,74 @@ +# Written by fullsend (CodexRuntime.Bootstrap); do not edit. +# Integrity-checked before every iteration — see buildCodexRunCommand. +model_provider = "fullsend-openai" +approval_policy = "never" +sandbox_mode = "danger-full-access" +web_search = "disabled" +check_for_update_on_startup = false +hide_agent_reasoning = false +developer_instructions = """ +# Agent: review + +Review a pull request. + +You are the review agent. Dispatch the roster. + +## Runtime note + +This agent runs on the codex runtime (FULLSEND_RUNTIME=codex). Registered sub-agent roles: correctness, default, explore. Sub-agents are native Codex children. Dispatch follows collaboration V2. When a skill says to dispatch a sub-agent, call `spawn_agent` with `task_name` set to a short name for the task, unique among the children you spawn (lowercase letters, digits and `_` only; `root` is reserved), `agent_type` set to a role listed above — the persona's name, or `explore` where the skill asks for an `Explore` pass (instruction-only; nothing enforces read-only on a child); for a task that names no persona, omit `agent_type` — and `message` carrying that sub-agent's whole context package: a child starts with nothing but that message. Pass `fork_turns: \"none\"` explicitly on every spawn, and never pass a `model`, `reasoning_effort` or `fork_context` argument: the runner has bound each role's model. Use only the roles listed above; `explorer` and `worker` are not registered and are denied. Spawn only the sub-agents the skill selected; a role being registered is not a reason to spawn it. + +`wait_agent` takes only `timeout_ms` and never a target. A child's result arrives as a message in your conversation, one per finished child, through the runner's checked delivery path, not in the wait's result. At most four children can run at once: a fifth spawn is refused while four are running, and Codex evicts an idle finished child when a new spawn needs its slot. There is no close or follow-up call: never resume, message or follow up a child. Interrupt a child that is over its budget with `interrupt_agent`. An interrupted child sends no result: report a coverage gap for that role. A child whose result reports an error is final for that role. A message whose payload is `RESULT WITHHELD BY FULLSEND`, ignoring whitespace around it, is a withheld result: report a coverage gap for that role, and never retry the spawn or read the child's raw rollout. A denied spawn is final for that role: do not retry it, execute that sub-agent definition yourself with the same context package, and treat the output as that sub-agent's result. + +When reading a SKILL.md or other instruction file, do not cat it in one call: Codex truncates exec output (head and tail, dropping the middle). For each file, count its lines with `awk 'END { print NR }' ` (`wc -l` misses a last line with no newline), then `sed -n ',p'` in contiguous ranges of at most 200 lines, one range per tool call, including a short final chunk so the last line is covered — do not round the line count down to a multiple of 200 (a 425-line file is three ranges: `1,200p`, `201,400p`, `401,425p`). Never combine files or ranges in one exec. Inspect the returned output for a truncation warning before advancing; if a range is truncated, split it into smaller contiguous windows that together still cover its start through end — never skip the back half — and read those windows before moving on to the next range. +""" + +[analytics] +enabled = false + +[feedback] +enabled = false + +[history] +persistence = "none" + +[skills.bundled] +enabled = false + +[features] +plugins = false + +[features.multi_agent_v2] +enabled = true +disable_direct_message = true +expose_spawn_agent_model_overrides = false + +[agents] +enabled = true +max_concurrent_threads_per_session = 4 +max_depth = 1 +default_subagent_model = "gpt-5.6-luna" + +[agents."correctness"] +description = "Evaluates logic correctness, edge cases, nil handling, API contracts, test adequacy/integrity." +config_file = "/sandbox/codex-config/agents/correctness.toml" + +[agents."default"] +description = "Generic sub-agent for a task the parent describes in full in its message." +config_file = "/sandbox/codex-config/agents/default.toml" + +[agents."explore"] +description = "Investigation of the repository by reading only; reports findings. Instruction-only: nothing enforces read-only on a child." +config_file = "/sandbox/codex-config/agents/explore.toml" + +[projects."/sandbox/workspace/repo"] +trust_level = "untrusted" + +[model_providers.fullsend-openai] +name = "OpenAI via the fullsend run-scoped provider" +base_url = "https://api.openai.com/v1" +wire_api = "responses" + +[model_providers.fullsend-openai.auth] +command = "/sandbox/codex-config/openai-token.sh" +refresh_interval_ms = 30000 +timeout_ms = 5000 diff --git a/internal/runtime/testdata/codex/golden/config-delegating.toml b/internal/runtime/testdata/codex/golden/config-delegating.toml index e439a2a518..e65d54a0dd 100644 --- a/internal/runtime/testdata/codex/golden/config-delegating.toml +++ b/internal/runtime/testdata/codex/golden/config-delegating.toml @@ -36,7 +36,9 @@ enabled = false [features] plugins = false -multi_agent_v2 = false + +[features.multi_agent_v2] +enabled = false [agents] enabled = true diff --git a/internal/runtime/testdata/codex/golden/config-gateway.toml b/internal/runtime/testdata/codex/golden/config-gateway.toml index 21460d38fd..548968619c 100644 --- a/internal/runtime/testdata/codex/golden/config-gateway.toml +++ b/internal/runtime/testdata/codex/golden/config-gateway.toml @@ -34,7 +34,9 @@ enabled = false [features] plugins = false -multi_agent_v2 = false + +[features.multi_agent_v2] +enabled = false [agents] enabled = false diff --git a/internal/runtime/testdata/codex/golden/config.toml b/internal/runtime/testdata/codex/golden/config.toml index 0560e8a86f..e9f32d961e 100644 --- a/internal/runtime/testdata/codex/golden/config.toml +++ b/internal/runtime/testdata/codex/golden/config.toml @@ -34,7 +34,9 @@ enabled = false [features] plugins = false -multi_agent_v2 = false + +[features.multi_agent_v2] +enabled = false [agents] enabled = false diff --git a/internal/runtime/testdata/codex/golden/hooks-delegating-v2.json b/internal/runtime/testdata/codex/golden/hooks-delegating-v2.json new file mode 100644 index 0000000000..79c4aae78f --- /dev/null +++ b/internal/runtime/testdata/codex/golden/hooks-delegating-v2.json @@ -0,0 +1,68 @@ +{ + "description": "fullsend sandbox tool hooks (generated; see docs/contributing/runtime-implementation.md)", + "hooks": { + "PostToolUse": [ + { + "hooks": [ + { + "type": "command", + "command": "/usr/bin/python3 -I /sandbox/codex-config/fullsend-codex-hook.py PostToolUse posttool_chain.py", + "timeout": 30 + } + ] + } + ], + "PreToolUse": [ + { + "matcher": "^(multi_agent_v1|collaboration)|(spawn|resume)_agent$", + "hooks": [ + { + "type": "command", + "command": "/usr/bin/python3 -I /sandbox/codex-config/fullsend-codex-hook.py SpawnGuard", + "timeout": 30 + } + ] + }, + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "command": "/usr/bin/python3 -I /sandbox/codex-config/fullsend-codex-hook.py PreToolUse tirith_check.py", + "timeout": 30 + } + ] + }, + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "command": "/usr/bin/python3 -I /sandbox/codex-config/fullsend-codex-hook.py PreToolUse ssrf_pretool.py", + "timeout": 30 + } + ] + }, + { + "hooks": [ + { + "type": "command", + "command": "/usr/bin/python3 -I /sandbox/codex-config/fullsend-codex-hook.py PreToolUse canary_pretool.py", + "timeout": 30 + } + ] + } + ], + "SubagentStop": [ + { + "hooks": [ + { + "type": "command", + "command": "/usr/bin/python3 -I /sandbox/codex-config/fullsend-codex-hook.py SubagentStop posttool_chain.py", + "timeout": 30 + } + ] + } + ] + } +}