From 75d0b4b8f78cdfd2052e4f072103e3469506ba90 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Mon, 26 Oct 2026 15:57:40 -0400 Subject: [PATCH 01/15] feat(codex)!: bind native child models from subagents and FULLSEND_CODEX_SUBAGENT_MODEL For a delegating agent (tools include Agent, harness security on, parent model on collaboration V1 by the ADR 0126 gate) Bootstrap resolves each child's model in the order decided on #6970: subagents., then FULLSEND_CODEX_SUBAGENT_MODEL, then subagents.default, then gpt-5.6-luna. A persona with its own entry carries the validated bare OpenAI id in its role file; default and explore never carry one. The run-level default is returned and not yet bound. Values are checked for form (translateCodexModel's rules, less a gateway/ spec and inherit) and for presence in the pinned CLI's bundled catalog (codex debug models --bundled, read by Bootstrap); whether the provider serves a listed model is only known at the child's first request. A key naming no persona, explore included, fails as on pi. BREAKING CHANGE: a delegating agent on runtime codex now fails Bootstrap when an agents[].subagents value is not an OpenAI id or is not in the pinned CLI's bundled catalog, naming the key. Case: a review entry carrying xai-vertex/... and google-vertex/... subagents values written for pi, run with runtime: codex and an OpenAI model override; before, the values were ignored and the agent ran in one context. Fix: set openai/ on those entries, or tombstone them (: ~) in the repository's .fullsend/config.yaml so the run-level default applies. Signed-off-by: Dharit Shah --- internal/runtime/codex_bootstrap.go | 15 +- internal/runtime/codex_bootstrap_test.go | 102 +++++++ internal/runtime/codex_golden_test.go | 7 + internal/runtime/codex_personas.go | 132 ++++++++- internal/runtime/codex_personas_test.go | 264 +++++++++++++++++- .../codex/golden/roles/correctness-model.toml | 14 + 6 files changed, 520 insertions(+), 14 deletions(-) create mode 100644 internal/runtime/testdata/codex/golden/roles/correctness-model.toml diff --git a/internal/runtime/codex_bootstrap.go b/internal/runtime/codex_bootstrap.go index 5cbee30bb1..80bb098a9f 100644 --- a/internal/runtime/codex_bootstrap.go +++ b/internal/runtime/codex_bootstrap.go @@ -173,6 +173,15 @@ func (r CodexRuntime) Bootstrap(input BootstrapInput) error { fmt.Fprintf(os.Stderr, "sub-agents: %s; native sub-agents need a parent Codex resolves to collaboration V1, running in one context\n", reason) } } + // Resolved before config.toml is written: a bad subagents value fails here. + var roles []codexRole + if delegating { + roles, _, err = resolveCodexChildModels( + codexRoles(input.SkillDirs(), agentName), input.AgentSubagents(), os.Getenv(codexSubagentModelEnv), catalog) + if err != nil { + return err + } + } // The gateway provider is rendered only when the runner registered an // inference.gateway block for this sandbox (PrepareGatewayRun). gatewayBaseURL := codexGatewayRunFor(sandboxName) @@ -285,14 +294,12 @@ func (r CodexRuntime) Bootstrap(input BootstrapInput) error { digests.HooksJSON = codexAssetSHA256(hooksJSON) // The role files are agent-writable, so their digests join the // runner-held set the spawn guard re-checks before every spawn. - // Codex's multi-agent tools stay off in config.toml until the - // dispatch note lands (#6970). - if delegating { + if len(roles) > 0 { if err := codexExecOK(sandboxName, "mkdir -p "+shellQuote(r.codexRolesDir()), "creating codex roles dir"); err != nil { return err } digests.RoleFiles = map[string]string{} - for _, role := range codexRoles(input.SkillDirs(), agentName) { + for _, role := range roles { data := role.toml() if err := uploadBytes(sandboxName, r.codexRolesDir()+"/"+role.Name+".toml", data); err != nil { return fmt.Errorf("writing role %q: %w", role.Name, err) diff --git a/internal/runtime/codex_bootstrap_test.go b/internal/runtime/codex_bootstrap_test.go index 71c7f99884..90a64749d0 100644 --- a/internal/runtime/codex_bootstrap_test.go +++ b/internal/runtime/codex_bootstrap_test.go @@ -909,6 +909,7 @@ func TestCodexRolesDir(t *testing.T) { // gate passing: one regular file per role under agents/, digests recorded // for the spawn guard, and everything else byte-equal to today. func TestCodexRuntimeBootstrap_WritesRoleFilesForADelegatingAgent(t *testing.T) { + t.Setenv(codexSubagentModelEnv, "") logPath := filepath.Join(t.TempDir(), "openshell.log") storeDir := t.TempDir() fakeOpenshellCodex(t, logPath, storeDir, "codex-cli 0.152.1") @@ -959,6 +960,7 @@ func TestCodexRuntimeBootstrap_WritesRoleFilesForADelegatingAgent(t *testing.T) // 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() writePersonaFile(t, skill, "correctness", codexTestPersona) hooks := security.SandboxHookConfigFromHarness(&harness.Harness{}) @@ -1020,6 +1022,7 @@ func TestCodexRuntimeBootstrap_NoRoleFilesWhenTheGateFails(t *testing.T) { // The three new infrastructure failures are reported with their own message, // like the rows of TestCodexRuntimeBootstrap_ReportsInfrastructureFailures. func TestCodexRuntimeBootstrap_ReportsRoleFileFailures(t *testing.T) { + t.Setenv(codexSubagentModelEnv, "") r := CodexRuntime{} for name, tc := range map[string]struct{ match, want string }{ "roles dir": {"mkdir -p " + shellQuote(r.codexRolesDir()), "creating codex roles dir"}, @@ -1043,6 +1046,7 @@ func TestCodexRuntimeBootstrap_ReportsRoleFileFailures(t *testing.T) { // exit 2 and a reason, through the installed hook adapter. Driven directly: // the multi-agent tools are still off, so no Codex process reaches the hook. func TestCodexBootstrap_PlantedRoleFileDeniesSpawn(t *testing.T) { + t.Setenv(codexSubagentModelEnv, "") h := newCodexAdapterHarness(t) storeDir := t.TempDir() fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), storeDir, "codex-cli 0.152.1") @@ -1090,3 +1094,101 @@ func TestCodexBootstrap_PlantedRoleFileDeniesSpawn(t *testing.T) { assert.NotEmpty(t, got.stderr) }) } + +// codexDelegatingBootstrap runs Bootstrap for the delegating review agent +// with one correctness persona, harness security on and the given subagents +// map. It returns the runtime, the fake's argv log and Bootstrap's error. +func codexDelegatingBootstrap(t *testing.T, storeDir string, subagents map[string]*string) (CodexRuntime, string, error) { + t.Helper() + logPath := filepath.Join(t.TempDir(), "openshell.log") + fakeOpenshellCodex(t, logPath, 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.agentSubagents = subagents + r := CodexRuntime{} + return r, logPath, r.Bootstrap(input) +} + +// TestCodexRuntimeBootstrap_RejectsNonOpenAISubagentModel pins the wiring: +// the subagents map, the catalog and the runner variable reach the resolver, +// and a bad value fails Bootstrap naming the key before config.toml is +// written. The breaking case is a pi-shaped review entry (xai and +// google-vertex values) run with runtime codex. +func TestCodexRuntimeBootstrap_RejectsNonOpenAISubagentModel(t *testing.T) { + for name, tc := range map[string]struct { + env string + subagents map[string]*string + want []string + }{ + "a persona entry from another provider": { + subagents: map[string]*string{"correctness": strp("xai-vertex/xai/grok-4.6")}, + want: []string{"subagents.correctness", `"xai-vertex/xai/grok-4.6"`, "correctness: ~"}}, + "a model the pinned catalog does not list": { + subagents: map[string]*string{"correctness": strp("openai/gpt-5.6-nova")}, + want: []string{`subagents.correctness: model "gpt-5.6-nova" is not in the bundled catalog`}}, + "the runner variable": {env: "opus", want: []string{codexSubagentModelEnv, `"opus"`, "unset"}}, + } { + t.Run(name, func(t *testing.T) { + t.Setenv(codexSubagentModelEnv, tc.env) + r, logPath, err := codexDelegatingBootstrap(t, t.TempDir(), tc.subagents) + require.Error(t, err) + for _, w := range tc.want { + assert.Contains(t, err.Error(), w) + } + assert.NotContains(t, readFileString(t, logPath), r.codexConfigPath(), + "the model check runs before config.toml is written") + }) + } +} + +// 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 model codex does not resolve to collaboration V1 (a V2 or unlisted +// 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) { + t.Setenv(codexSubagentModelEnv, "") + bad := map[string]*string{"correctness": strp("xai-vertex/xai/grok-4.6")} + hooks := security.SandboxHookConfigFromHarness(&harness.Harness{}) + skill := t.TempDir() + writePersonaFile(t, skill, "correctness", codexTestPersona) + + for name, tc := range map[string]struct { + input BootstrapInput + preflight bool // part two of the gate read the catalog + }{ + "no Agent tool, security on": {codexHooksBootstrapInput{ + bootstrapInput: bootstrapInput{sandboxName: "sb", agentPath: writeAgentFile(t, codexTestAgentDef), agentName: "triage", agentSubagents: bad}, + hooks: hooks, + }, false}, + "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{ + bootstrapInput: bootstrapInput{sandboxName: "sb", agentPath: writeAgentFile(t, codexTestDelegatingAgentDef), agentName: "review", + skillDirs: []string{skill}, parentModel: "openai/gpt-5.6-sol", agentSubagents: bad}, + hooks: hooks, + }, true}, + } { + t.Run(name, func(t *testing.T) { + storeDir := t.TempDir() + logPath := filepath.Join(t.TempDir(), "openshell.log") + fakeOpenshellCodex(t, logPath, storeDir, "codex-cli 0.152.1") + forgetRunnerHeldDigests("sb") + t.Cleanup(func() { forgetRunnerHeldDigests("sb") }) + + r := CodexRuntime{} + require.NoError(t, r.Bootstrap(tc.input), "a bad subagents value is ignored: the chain is never resolved") + log := readFileString(t, logPath) + assert.Equal(t, tc.preflight, strings.Contains(log, "codex debug models --bundled")) + assert.NotContains(t, log, r.codexRolesDir(), "no role directory, no role file") + cfg := string(storedUpload(t, storeDir, r.codexConfigPath())) + assert.Contains(t, cfg, "[agents]\nenabled = false") + assert.Contains(t, cfg, "No fullsend sub-agent roster is available") + }) + } +} diff --git a/internal/runtime/codex_golden_test.go b/internal/runtime/codex_golden_test.go index 02806a0027..984b386779 100644 --- a/internal/runtime/codex_golden_test.go +++ b/internal/runtime/codex_golden_test.go @@ -111,6 +111,13 @@ func TestCodexGolden(t *testing.T) { {"roles/correctness.toml", func(t *testing.T) string { return string(codexGoldenRoles(t)[0].toml()) }}, {"roles/default.toml", func(t *testing.T) string { return string(codexGoldenRoles(t)[1].toml()) }}, {"roles/explore.toml", func(t *testing.T) string { return string(codexGoldenRoles(t)[2].toml()) }}, + {"roles/correctness-model.toml", func(t *testing.T) string { + resolved, _, err := resolveCodexChildModels(codexGoldenRoles(t), + map[string]*string{"correctness": strp("openai/gpt-5.6-sol")}, "", codexTestCatalog()) + require.NoError(t, err) + require.Equal(t, "correctness", resolved[0].Name, "codexRoles sorts by name") + return string(resolved[0].toml()) + }}, {"launch-delegating.txt", func(t *testing.T) string { return codexGoldenLaunch(buildCodexRunCommand(hooksOn, codexModel{ID: "gpt-5.6-luna"}, "high", true, codexGoldenDelegatingDigests(t))) }}, diff --git a/internal/runtime/codex_personas.go b/internal/runtime/codex_personas.go index b9c85f1817..2d70debb2e 100644 --- a/internal/runtime/codex_personas.go +++ b/internal/runtime/codex_personas.go @@ -3,11 +3,14 @@ package runtime import ( "encoding/json" "fmt" + "maps" "os" "slices" "strings" "gopkg.in/yaml.v3" + + "github.com/fullsend-ai/fullsend/internal/config" ) // codexDelegates is part one of the ADR 0126 gate: an agent gets native @@ -27,6 +30,10 @@ func codexDelegates(def *piAgentDef, securityEnabled bool) bool { // 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 + // subagents entry (the validated bare OpenAI id). Empty means no `model` + // line: the child takes agents.default_subagent_model. + Model string } // codexReservedRoleNames are persona names Codex treats specially: `enabled` @@ -35,13 +42,126 @@ type codexRole struct { // therefore denies. The runtime-neutral reserved list is discoverPersonas's. var codexReservedRoleNames = []string{"enabled", "explorer", "worker"} -// toml renders the role file: name, description and developer_instructions, -// each through codexTOMLString, nothing else. No model line in this PR: ADR -// 0126's per-persona model arrives with the PR of #6970 that makes delegation -// reachable; default and explore never carry one. +// codexDefaultSubagentModel is the last position of the child model chain +// (#6970): children run the cheap tier by default. +const codexDefaultSubagentModel = "gpt-5.6-luna" + +// codexSubagentModelEnv is the runner-side run-level child model (#6970), read +// from the runner's own environment like FULLSEND_PI_SUBAGENT_THINKING. +const codexSubagentModelEnv = "FULLSEND_CODEX_SUBAGENT_MODEL" + +// codexChildModel validates one configured child model and returns the bare +// OpenAI id: translateCodexModel's rules, less a gateway/ spec (the route is +// the run's own model's) and `inherit`, which codex does not resolve for a +// child. key names the entry so the error says what to fix. +func codexChildModel(key, value string) (string, error) { + fix := "unset it so subagents.default or " + codexDefaultSubagentModel + " applies" + if name, ok := strings.CutPrefix(key, "subagents."); ok { + fix = fmt.Sprintf("set an OpenAI id (%s/) or tombstone the entry (`%s: ~` under subagents:) so the run-level default applies", + codexOpenAIProvider, name) + } + model, err := translateCodexModel(value, true) + if err != nil || model.Gateway || strings.EqualFold(model.ID, "inherit") { + return "", fmt.Errorf("%s: %q is not an OpenAI model id (%s/ or the bare id); %s", key, value, codexOpenAIProvider, fix) + } + return model.ID, nil +} + +// codexListedModel is Bootstrap's catalog check: codex itself checks a +// run-level default only at each spawn and a role-file model not at all (the +// child fails on the provider's 404 instead), so every chain position is +// checked here, naming the position. +func codexListedModel(catalog codexCatalog, key, model string) error { + if catalog.has(model) { + return nil + } + return fmt.Errorf("%s: model %q is not in the bundled catalog of the pinned codex (`codex debug models --bundled`)", key, model) +} + +// resolveCodexChildModels binds a persona's own subagents entry to its role +// and resolves the run-level default (FULLSEND_CODEX_SUBAGENT_MODEL, then +// subagents.default, then codexDefaultSubagentModel), which Bootstrap sets as +// agents.default_subagent_model. A nil entry is a tombstone and reads as +// absent; a key naming neither default nor a persona is an error, as on pi; +// every configured value is validated whichever position wins, and every +// resolved model must be in catalog (ADR 0126). The returned slice is a copy. +func resolveCodexChildModels(roles []codexRole, subagents map[string]*string, envValue string, catalog codexCatalog) ([]codexRole, string, error) { + persona := make(map[string]bool, len(roles)) + for _, role := range roles { + if !slices.Contains(config.ReservedSubagentKeys(), role.Name) { + persona[role.Name] = true + } + } + // Sorted, so a config with two bad keys names the same one every run. + for _, key := range slices.Sorted(maps.Keys(subagents)) { + if key == "default" || subagents[key] == nil || persona[key] { + continue + } + discovered := "none" + if len(persona) > 0 { + discovered = strings.Join(slices.Sorted(maps.Keys(persona)), ", ") + } + return nil, "", fmt.Errorf("subagents.%s: %q is not a registered codex role (a discovered persona that was skipped is reported above); registered personas: %s", + key, key, discovered) + } + + out := slices.Clone(roles) + for i, role := range out { + value := subagents[role.Name] + if value == nil || !persona[role.Name] { + continue + } + model, err := codexChildModel("subagents."+role.Name, *value) + if err != nil { + return nil, "", err + } + if err := codexListedModel(catalog, "subagents."+role.Name, model); err != nil { + return nil, "", err + } + out[i].Model = model + } + + defaultModel, source := codexDefaultSubagentModel, "built-in default" + if value := subagents["default"]; value != nil { + model, err := codexChildModel("subagents.default", *value) + if err != nil { + return nil, "", err + } + defaultModel, source = model, "subagents.default" + } + if strings.TrimSpace(envValue) != "" { + model, err := codexChildModel(codexSubagentModelEnv, envValue) + if err != nil { + return nil, "", err + } + defaultModel, source = model, codexSubagentModelEnv + } + if err := codexListedModel(catalog, source, defaultModel); err != nil { + return nil, "", err + } + + // Echoed as pi does, so a user sees why a child resolved as it did. + fmt.Fprintf(os.Stderr, "subagents: default → %s (from %s; children that name no persona and personas without an entry)\n", + defaultModel, source) + for _, role := range out { + if role.Model != "" { + fmt.Fprintf(os.Stderr, "subagents: %s → %s (from subagents.%s)\n", role.Name, role.Model, role.Name) + } + } + return out, defaultModel, nil +} + +// toml renders the role file: name, description, model for a persona with +// its own subagents entry (#6970) and developer_instructions, each through +// codexTOMLString, nothing else. func (role codexRole) toml() []byte { + model := "" + if role.Model != "" { + model = "model = " + codexTOMLString(role.Model) + "\n" + } return []byte("name = " + codexTOMLString(role.Name) + "\n" + "description = " + codexTOMLString(role.Description) + "\n" + + model + "developer_instructions = " + codexTOMLString(role.Instructions) + "\n") } @@ -102,8 +222,8 @@ func codexRoles(skillDirs []string, agentName string) []codexRole { continue } if keys := codexDroppedFrontmatterKeys(p.Frontmatter); len(keys) > 0 { - fmt.Fprintf(os.Stderr, "Codex persona %q: frontmatter %s dropped; a role carries no model or tool "+ - "restriction, so the run-level child model and the parent's tools apply\n", + fmt.Fprintf(os.Stderr, "Codex persona %q: frontmatter %s dropped; the frontmatter model is not applied on codex "+ + "(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"}) diff --git a/internal/runtime/codex_personas_test.go b/internal/runtime/codex_personas_test.go index fe9b8e8872..6cd25f603d 100644 --- a/internal/runtime/codex_personas_test.go +++ b/internal/runtime/codex_personas_test.go @@ -86,9 +86,9 @@ func TestDiscoverPersonas_CarriesDescriptionAndBody(t *testing.T) { // The role shape the pinned CLI reads: three keys, each a basic string // (multi-line when the value holds a newline, as config.toml's -// developer_instructions), nothing else. No model line in this PR (ADR 0126's -// per-persona model arrives with delegation, #6970), and no dropped -// frontmatter turned into text. +// developer_instructions), nothing else. No model line without a subagents +// entry (TestCodexRole_TOMLModelLine), and no dropped frontmatter turned into +// text. func TestCodexRole_TOML(t *testing.T) { t.Parallel() @@ -109,7 +109,7 @@ func TestCodexRole_TOMLEscapesTheBody(t *testing.T) { got := string(codexRole{Name: "x", Description: `say "hi"`, Instructions: "line\n\"\"\"\\end"}.toml()) assert.Equal(t, "name = \"x\"\ndescription = \"say \\\"hi\\\"\"\ndeveloper_instructions = \"\"\"\nline\n\\\"\\\"\\\"\\\\end\"\"\"\n", got, "a persona body is arbitrary markdown; codexTOMLString keeps it inside one basic string, multi-line when it holds a newline") - assert.NotContains(t, got, "model", "no model line in this PR: ADR 0126's per-persona model arrives with delegation (#6970)") + assert.NotContains(t, got, "model", "no model line without a subagents entry") } func codexRoleNames(roles []codexRole) []string { @@ -407,3 +407,259 @@ func TestCodexParentResolvesV1(t *testing.T) { }) } } + +// 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. +func TestCodexChildModel(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + key string + in string + want string + wantErr []string + }{ + {name: "bare id", key: "subagents.correctness", in: "gpt-5.6-sol", want: "gpt-5.6-sol"}, + {name: "openai prefix stripped", key: "subagents.correctness", in: "openai/gpt-5.6-sol", want: "gpt-5.6-sol"}, + {name: "whitespace trimmed", key: "subagents.default", in: " openai/gpt-6-astra ", want: "gpt-6-astra"}, + {name: "another provider names the key and the tombstone", key: "subagents.correctness", + in: "xai-vertex/xai/grok-4.6", wantErr: []string{"subagents.correctness", `"xai-vertex/xai/grok-4.6"`, "correctness: ~"}}, + {name: "google vertex on default", key: "subagents.default", + in: "google-vertex/gemini-3.8-flash", wantErr: []string{"subagents.default", `"google-vertex/gemini-3.8-flash"`, "default: ~"}}, + {name: "claude alias", key: "subagents.security", in: "opus", + wantErr: []string{"subagents.security", `"opus"`, "security: ~"}}, + {name: "gateway route names the key", key: "subagents.correctness", in: "gateway/vendor/org/model", + wantErr: []string{"subagents.correctness", `"gateway/vendor/org/model"`, "correctness: ~"}}, + {name: "gateway route with an empty id", key: "subagents.correctness", in: "gateway/", + wantErr: []string{"subagents.correctness", `"gateway/"`, "correctness: ~"}}, + {name: "inherit is refused", key: "subagents.correctness", in: "inherit", + wantErr: []string{"subagents.correctness", `"inherit"`, "correctness: ~"}}, + {name: "inherit behind the prefix, any case", key: "subagents.correctness", in: "openai/Inherit", + wantErr: []string{`"openai/Inherit"`}}, + {name: "empty value", key: "subagents.correctness", in: "", wantErr: []string{"subagents.correctness", `""`, "correctness: ~"}}, + {name: "the runner variable says unset, not tombstone", key: codexSubagentModelEnv, in: "haiku", + wantErr: []string{"FULLSEND_CODEX_SUBAGENT_MODEL", `"haiku"`, "unset"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got, err := codexChildModel(tt.key, tt.in) + if len(tt.wantErr) > 0 { + require.Error(t, err) + for _, w := range tt.wantErr { + assert.Contains(t, err.Error(), w) + } + assert.NotContains(t, err.Error(), "FULLSEND_CODEX_MODEL=", "the fix names the entry, not the run's own model") + return + } + require.NoError(t, err) + assert.Equal(t, tt.want, got) + }) + } +} + +// Every env × subagents.default × persona-entry combination of the chain: +// only a persona with its own entry gets a role-file model; the second value +// is the run-level default every other child takes. +func TestResolveCodexChildModels_Precedence(t *testing.T) { + t.Parallel() + + const ( + absent = "absent" + set = "set" + tombstone = "tombstone" + ) + tests := []struct { + name string + env string + defaultSet bool + persona string + wantModel string // correctness's role-file model; "" = no model line + wantDefault string + }{ + {"nothing configured", "", false, absent, "", "gpt-5.6-luna"}, + {"persona entry only", "", false, set, "gpt-5.6-sol", "gpt-5.6-luna"}, + {"persona tombstone only", "", false, tombstone, "", "gpt-5.6-luna"}, + {"default only", "", true, absent, "", "gpt-6-astra"}, + {"default and persona entry", "", true, set, "gpt-5.6-sol", "gpt-6-astra"}, + {"default and persona tombstone", "", true, tombstone, "", "gpt-6-astra"}, + {"env only", "openai/gpt-5.6-terra", false, absent, "", "gpt-5.6-terra"}, + {"env and persona entry", "openai/gpt-5.6-terra", false, set, "gpt-5.6-sol", "gpt-5.6-terra"}, + {"env and persona tombstone", "openai/gpt-5.6-terra", false, tombstone, "", "gpt-5.6-terra"}, + {"env beats default", "openai/gpt-5.6-terra", true, absent, "", "gpt-5.6-terra"}, + {"env, default and persona entry", "openai/gpt-5.6-terra", true, set, "gpt-5.6-sol", "gpt-5.6-terra"}, + {"env, default and persona tombstone", "openai/gpt-5.6-terra", true, tombstone, "", "gpt-5.6-terra"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + roles := []codexRole{ + {Name: "correctness", Description: "d", Instructions: "i"}, + {Name: "default", Description: "d", Instructions: "i"}, + {Name: "explore", Description: codexExploreRoleDescription, Instructions: "i"}, + } + cfg := map[string]*string{} + if tt.defaultSet { + cfg["default"] = strp("gpt-6-astra") + } + switch tt.persona { + case set: + cfg["correctness"] = strp("openai/gpt-5.6-sol") + case tombstone: + cfg["correctness"] = nil + } + + got, gotDefault, err := resolveCodexChildModels(roles, cfg, tt.env, codexTestCatalog()) + require.NoError(t, err) + require.Len(t, got, 3) + assert.Equal(t, tt.wantModel, got[0].Model, "correctness") + assert.Empty(t, got[1].Model, "default never carries a model line: it takes agents.default_subagent_model") + assert.Empty(t, got[2].Model, "explore never carries a model line") + assert.Equal(t, tt.wantDefault, gotDefault) + assert.Empty(t, roles[0].Model, "the input slice is not mutated") + for i := range got { + assert.Equal(t, roles[i].Name, got[i].Name, "order and names are kept") + } + }) + } +} + +// A subagents key must name a discovered persona or `default`; anything else, +// `explore` included (a reserved key), fails Bootstrap and names the key, as +// pi does. A tombstoned unknown key is skipped, as on pi, because a tombstone +// only removes an inherited entry. +func TestResolveCodexChildModels_RejectsUnknownKeys(t *testing.T) { + t.Parallel() + + roles := []codexRole{{Name: "correctness"}, {Name: "default"}, {Name: "explore"}} + tests := []struct { + name string + roles []codexRole + cfg map[string]*string + wantErr []string + }{ + {name: "explore is reserved", roles: roles, cfg: map[string]*string{"explore": strp("openai/gpt-5.6-sol")}, + wantErr: []string{"subagents.explore", "correctness"}}, + {name: "a typo", roles: roles, cfg: map[string]*string{"correctnes": strp("openai/gpt-5.6-sol")}, + wantErr: []string{"subagents.correctnes", `"correctnes"`, "correctness"}}, + {name: "no persona at all", roles: nil, cfg: map[string]*string{"correctness": strp("openai/gpt-5.6-sol")}, + wantErr: []string{"subagents.correctness", "none"}}, + {name: "a tombstoned unknown key is skipped", roles: roles, cfg: map[string]*string{"correctnes": nil}}, + {name: "default is not a persona key error", roles: nil, cfg: map[string]*string{"default": strp("openai/gpt-5.6-sol")}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + _, _, err := resolveCodexChildModels(tt.roles, tt.cfg, "", codexTestCatalog()) + if len(tt.wantErr) == 0 { + assert.NoError(t, err) + return + } + require.Error(t, err) + for _, w := range tt.wantErr { + assert.Contains(t, err.Error(), w) + } + }) + } +} + +// Every configured value is checked, whichever position of the chain wins: +// a non-OpenAI value fails Bootstrap and names the key (#6970). +func TestResolveCodexChildModels_NonOpenAIValueNamesTheKey(t *testing.T) { + t.Parallel() + + roles := []codexRole{{Name: "correctness"}, {Name: "default"}, {Name: "explore"}} + tests := []struct { + name string + env string + cfg map[string]*string + wantErr []string + }{ + {name: "persona from xai vertex", cfg: map[string]*string{"correctness": strp("xai-vertex/xai/grok-4.6")}, + wantErr: []string{"subagents.correctness", `"xai-vertex/xai/grok-4.6"`, "correctness: ~"}}, + {name: "default from google vertex", cfg: map[string]*string{"default": strp("google-vertex/gemini-3.8-flash")}, + wantErr: []string{"subagents.default", `"google-vertex/gemini-3.8-flash"`}}, + {name: "default is checked even when env wins", env: "openai/gpt-5.6-terra", + cfg: map[string]*string{"default": strp("google-vertex/gemini-3.8-flash")}, wantErr: []string{"subagents.default"}}, + {name: "runner variable", env: "opus", wantErr: []string{"FULLSEND_CODEX_SUBAGENT_MODEL", `"opus"`, "unset"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + _, _, err := resolveCodexChildModels(roles, tt.cfg, tt.env, codexTestCatalog()) + require.Error(t, err) + for _, w := range tt.wantErr { + assert.Contains(t, err.Error(), w) + } + }) + } +} + +// codexTestCatalog lists every model the tables above use, with the versions +// of testdata/codex/models-bundled-0.159.3.json; add any id a new row introduces. +func codexTestCatalog() codexCatalog { + return codexCatalog{"gpt-5.6-luna": "v1", "gpt-5.6-sol": "v2", "gpt-5.6-terra": "v2", "gpt-6-astra": "v2"} +} + +// Every chain position is checked against the catalog, the floor included; +// the error names the position that supplied the id. +func TestResolveCodexChildModels_CatalogMembership(t *testing.T) { + t.Parallel() + catalog := codexCatalog{"gpt-5.6-luna": "v1", "gpt-5.6-sol": "v2", "gpt-6-astra": "v2"} + sol, nova := "openai/gpt-5.6-sol", "openai/gpt-5.6-nova" + roles := []codexRole{{Name: "correctness"}, {Name: "default"}, {Name: "explore"}} + tests := []struct { + name string + subagents map[string]*string + env string + catalog codexCatalog + wantErr string + }{ + {"listed everywhere", map[string]*string{"correctness": &sol, "default": &sol}, "gpt-6-astra", catalog, ""}, + {"persona entry unlisted", map[string]*string{"correctness": &nova}, "", catalog, `subagents.correctness: model "gpt-5.6-nova" is not in the bundled catalog of the pinned codex`}, + {"default unlisted", map[string]*string{"default": &nova}, "", catalog, `subagents.default: model "gpt-5.6-nova" is not in the bundled catalog of the pinned codex`}, + {"runner variable unlisted", nil, "gpt-5.6-nova", catalog, `FULLSEND_CODEX_SUBAGENT_MODEL: model "gpt-5.6-nova" is not in the bundled catalog of the pinned codex`}, + {"floor unlisted after a CLI bump", nil, "", codexCatalog{"gpt-5.6-sol": "v2"}, `built-in default: model "gpt-5.6-luna" is not in the bundled catalog of the pinned codex`}, + {"floor unlisted but overridden", map[string]*string{"default": &sol}, "", codexCatalog{"gpt-5.6-sol": "v2"}, ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + _, _, err := resolveCodexChildModels(roles, tt.subagents, tt.env, tt.catalog) + if tt.wantErr == "" { + require.NoError(t, err) + return + } + require.ErrorContains(t, err, tt.wantErr) + }) + } +} + +// TestCodexRole_TOMLModelLine pins the role file with and without a model: +// keys name, description, [model], developer_instructions, nothing else. The +// bytes without a model are unchanged; the model line is the only difference. +func TestCodexRole_TOMLModelLine(t *testing.T) { + t.Parallel() + + role := codexRole{ + Name: "correctness", + Description: "Evaluates logic correctness, edge cases, nil handling, API contracts, test adequacy/integrity.", + Instructions: "# Correctness\n\nYou are a senior software engineer reviewing for correctness.\n", + } + without := "name = \"correctness\"\n" + + "description = \"Evaluates logic correctness, edge cases, nil handling, API contracts, test adequacy/integrity.\"\n" + + "developer_instructions = \"\"\"\n# Correctness\n\nYou are a senior software engineer reviewing for correctness.\n\"\"\"\n" + assert.Equal(t, without, string(role.toml())) + + role.Model = "gpt-5.6-sol" + with := "name = \"correctness\"\n" + + "description = \"Evaluates logic correctness, edge cases, nil handling, API contracts, test adequacy/integrity.\"\n" + + "model = \"gpt-5.6-sol\"\n" + + "developer_instructions = \"\"\"\n# Correctness\n\nYou are a senior software engineer reviewing for correctness.\n\"\"\"\n" + assert.Equal(t, with, string(role.toml()), "the model line sits between description and developer_instructions") + + role.Model = "gpt-5.6-\"sol\"" + assert.Contains(t, string(role.toml()), "model = \"gpt-5.6-\\\"sol\\\"\"\n", "quoted like every other value") +} diff --git a/internal/runtime/testdata/codex/golden/roles/correctness-model.toml b/internal/runtime/testdata/codex/golden/roles/correctness-model.toml new file mode 100644 index 0000000000..1c9a9f5784 --- /dev/null +++ b/internal/runtime/testdata/codex/golden/roles/correctness-model.toml @@ -0,0 +1,14 @@ +name = "correctness" +description = "Evaluates logic correctness, edge cases, nil handling, API contracts, test adequacy/integrity." +model = "gpt-5.6-sol" +developer_instructions = """ +## Runtime note + +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 work. Your final assistant message is the entire result handed back to the agent that dispatched you, so make it self-contained. + +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. + +# Correctness + +You are a senior software engineer reviewing for correctness. +""" From 4b80950929546abcb465f0190f2e4a96a1cc9210 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Mon, 26 Oct 2026 16:09:08 -0400 Subject: [PATCH 02/15] feat(codex): run sub-agents as native Codex children For a delegating agent config.toml replaces [agents] enabled = false (#7829) with the ADR 0126 block: enabled, four open children, depth one, the run-level child model, and one [agents.] table per registered role file. The runtime note becomes the dispatch bridge: the roster, the spawn arguments the guard admits (fork_context: false, no model or effort), the four-slot rule with close, no resume, an errored child final, a denied spawn final, and the chunked-read rule of #7832 unchanged. Every other agent, and every run with harness security off, gets the same config.toml and note as before; the goldens prove it. Two Run comments are corrected while children become reachable: the backpressure warning no longer says nothing can spawn, and the doc comment no longer says codex exits 0 on a failed turn (a failed or interrupted primary turn exits 1 on the pinned codex). Signed-off-by: Dharit Shah --- internal/runtime/codex_bootstrap.go | 64 +++++++-- internal/runtime/codex_bootstrap_test.go | 131 ++++++++++++++++-- internal/runtime/codex_config.go | 61 ++++++-- internal/runtime/codex_config_test.go | 127 +++++++++++++++-- internal/runtime/codex_golden_test.go | 14 +- internal/runtime/codex_run.go | 9 +- internal/runtime/codex_run_test.go | 2 +- .../codex/golden/config-delegating.toml | 70 ++++++++++ 8 files changed, 426 insertions(+), 52 deletions(-) create mode 100644 internal/runtime/testdata/codex/golden/config-delegating.toml diff --git a/internal/runtime/codex_bootstrap.go b/internal/runtime/codex_bootstrap.go index 80bb098a9f..d139dee35c 100644 --- a/internal/runtime/codex_bootstrap.go +++ b/internal/runtime/codex_bootstrap.go @@ -175,8 +175,9 @@ func (r CodexRuntime) Bootstrap(input BootstrapInput) error { } // Resolved before config.toml is written: a bad subagents value fails here. var roles []codexRole + defaultSubagentModel := "" if delegating { - roles, _, err = resolveCodexChildModels( + roles, defaultSubagentModel, err = resolveCodexChildModels( codexRoles(input.SkillDirs(), agentName), input.AgentSubagents(), os.Getenv(codexSubagentModelEnv), catalog) if err != nil { return err @@ -185,7 +186,8 @@ func (r CodexRuntime) Bootstrap(input BootstrapInput) error { // The gateway provider is rendered only when the runner registered an // inference.gateway block for this sandbox (PrepareGatewayRun). gatewayBaseURL := codexGatewayRunFor(sandboxName) - configTOML, err := renderCodexConfig(cfg, repoInput.RepoDir(), codexDeveloperInstructions(agentName, def), gatewayBaseURL) + configTOML, err := renderCodexConfig(cfg, repoInput.RepoDir(), + codexDeveloperInstructions(agentName, def, roles), gatewayBaseURL, roles, defaultSubagentModel) if err != nil { return err } @@ -349,8 +351,9 @@ func codexExecOK(sandboxName, cmd, what string) error { // slot for caller-supplied instructions, which it composes with its own base // 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. -func codexDeveloperInstructions(agentName string, def *piAgentDef) string { +// 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 { var b strings.Builder fmt.Fprintf(&b, "# Agent: %s\n\n", agentName) if def.Description != "" { @@ -359,15 +362,20 @@ func codexDeveloperInstructions(agentName string, def *piAgentDef) string { } b.WriteString(def.Body) b.WriteString("\n") - b.WriteString(codexNoSubagentNote) + if len(roles) == 0 { + b.WriteString(codexNoSubagentNote) + } else { + b.WriteString(codexSubagentNote(roles)) + } return b.String() } -// codexNoSubagentNote makes the absence of a sub-agent tool explicit so skills -// written for Claude Code's Agent tool (pr-review, retro) take their +// codexNoSubagentNote makes the absence of a sub-agent roster explicit so +// skills written for Claude Code's Agent tool (pr-review, retro) take their // single-context path deliberately instead of recording a failed dispatch. -// codex does have a spawn_agent tool, but fullsend wires no sub-agent roster -// for it in v1, the same position pi was in (#6527). +// Every agent the ADR 0126 gate declines gets it (tools without Agent, +// security off, a V2 or unlisted parent); 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 " + @@ -393,6 +401,44 @@ 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" +// 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 { + names := make([]string, len(roles)) + for i, role := range roles { + names[i] = role.Name + } + return "\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 " + + "`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 +} + // codexUnsupportedTools returns the Claude tool names from an agent // definition that have no codex tool. Unlike pi, nothing is dropped from an // allowlist as a result: codex has no native tool restriction, so the names diff --git a/internal/runtime/codex_bootstrap_test.go b/internal/runtime/codex_bootstrap_test.go index 90a64749d0..5dc74231fc 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) + got := codexDeveloperInstructions("triage", def, nil) assert.Contains(t, got, "# Agent: triage") assert.Contains(t, got, "Inspect an issue.") @@ -907,7 +907,7 @@ func TestCodexRolesDir(t *testing.T) { // TestCodexRuntimeBootstrap_WritesRoleFilesForADelegatingAgent covers the // gate passing: one regular file per role under agents/, digests recorded -// for the spawn guard, and everything else byte-equal to today. +// for the spawn guard. func TestCodexRuntimeBootstrap_WritesRoleFilesForADelegatingAgent(t *testing.T) { t.Setenv(codexSubagentModelEnv, "") logPath := filepath.Join(t.TempDir(), "openshell.log") @@ -940,16 +940,6 @@ func TestCodexRuntimeBootstrap_WritesRoleFilesForADelegatingAgent(t *testing.T) assert.Equal(t, role.toml(), got, "role file %s", path) assert.Equal(t, codexAssetSHA256(got), held.RoleFiles[role.Name], "the spawn guard's digest for %s is bound to the file name", role.Name) } - - // Nothing else changes until delegation is turned on: the multi-agent - // tools stay off and the runtime note still says there is no roster. - def, err := parsePiAgent([]byte(codexTestDelegatingAgentDef)) - require.NoError(t, err) - wantConfig, err := renderCodexConfig(r.ConfigDir(), "/sandbox/workspace/repo", codexDeveloperInstructions("review", def), "") - require.NoError(t, err) - assert.Equal(t, wantConfig, storedUpload(t, storeDir, r.codexConfigPath()), "config.toml is byte-equal to a non-delegating render") - assert.Contains(t, string(wantConfig), "[agents]\nenabled = false") - assert.Contains(t, string(wantConfig), "No fullsend sub-agent roster is available") } // len(RoleFiles) > 0 exactly when the ADR 0126 gate holds: part one @@ -1044,7 +1034,8 @@ func TestCodexRuntimeBootstrap_ReportsRoleFileFailures(t *testing.T) { // digests (#6970): the files Bootstrap wrote admit a registered role; one // extra file in agents/, which is agent-writable, denies every spawn with // exit 2 and a reason, through the installed hook adapter. Driven directly: -// the multi-agent tools are still off, so no Codex process reaches the hook. +// no Codex process runs here; the hook is invoked with the spawn input the +// test builds. func TestCodexBootstrap_PlantedRoleFileDeniesSpawn(t *testing.T) { t.Setenv(codexSubagentModelEnv, "") h := newCodexAdapterHarness(t) @@ -1192,3 +1183,117 @@ func TestCodexRuntimeBootstrap_NonDelegatingAgentIgnoresSubagents(t *testing.T) }) } } + +// TestCodexSubagentNote_CarriesTheDispatchContract pins the sentences the +// agents repository's pr-review skill keys on and the content the note must +// carry: the spawn arguments, the four-slot rule with close, no resume, only +// the registered roles, an errored child final, and the chunked-read +// paragraph byte-equal to the single-context note's. +func TestCodexSubagentNote_CarriesTheDispatchContract(t *testing.T) { + t.Parallel() + + roles := []codexRole{{Name: "challenger"}, {Name: "correctness"}, {Name: "default"}, {Name: "explore"}, {Name: "security"}} + got := codexSubagentNote(roles) + + assert.True(t, strings.HasPrefix(got, "\n## Runtime note\n\n"), "the heading the pr-review skill looks for") + // The first sentence. + assert.Contains(t, got, "This agent runs on the codex runtime (FULLSEND_RUNTIME=codex).") + // The roster sentence, in roster order (codexRoles sorts). + assert.Contains(t, got, "Registered sub-agent roles: challenger, correctness, default, explore, security.") + // The denied-spawn sentence, verbatim. + 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`", "`agent_type`", "`message`", + "`explore`", "for a task that names no persona, omit `agent_type`", + "`fork_context: false`", "never pass a `model` or `reasoning_effort` argument", + "`explorer` and `worker`", + "Spawn only the sub-agents the skill selected", + "At most four children can be open at once", "keeps its slot until it is closed", + "`wait_agent` on one child at a time", "`close_agent`", + "Close every child you spawned and never resume one", + "`timed_out: true` and no status has timed out, not failed: call it again", + "`errored` is final for that role", + } { + assert.Contains(t, got, want) + } + 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 (codexChildNote), not the parent's") +} + +func TestCodexDeveloperInstructions_DelegatingAgentGetsTheDispatchNote(t *testing.T) { + t.Parallel() + + def, err := parsePiAgent([]byte(codexTestDelegatingAgentDef)) + require.NoError(t, err) + roles := []codexRole{{Name: "correctness"}, {Name: "default"}, {Name: "explore"}} + + got := codexDeveloperInstructions("review", def, roles) + assert.Contains(t, got, "# Agent: review") + assert.Contains(t, got, "Review a pull request.") + assert.Contains(t, got, "You are the review agent.") + assert.Contains(t, got, "Registered sub-agent roles: correctness, default, explore.") + 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") + + single := codexDeveloperInstructions("review", def, nil) + 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)), + "the two notes are the only difference") +} + +// 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. +func TestCodexRuntimeBootstrap_DelegatingAgentRunsNativeChildren(t *testing.T) { + t.Setenv(codexSubagentModelEnv, "") + storeDir := t.TempDir() + r, logPath, err := codexDelegatingBootstrap(t, storeDir, map[string]*string{"correctness": strp("openai/gpt-5.6-sol")}) + require.NoError(t, err) + + 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") + 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") + } + assert.NotContains(t, cfg, "[agents]\nenabled = false") + assert.Contains(t, cfg, "trust_level = \"untrusted\"", "the project pin stays") + assert.Contains(t, cfg, "Registered sub-agent roles: correctness, default, explore.") + assert.Contains(t, cfg, "A denied spawn is final for that role") + assert.Contains(t, cfg, "at most 200 lines", "the chunked-read rule stays (#7832)") + assert.NotContains(t, cfg, "No fullsend sub-agent roster") + + correctness := storedUpload(t, storeDir, r.codexRolesDir()+"/correctness.toml") + assert.Contains(t, string(correctness), "\nmodel = \"gpt-5.6-sol\"\n") + assert.NotContains(t, string(storedUpload(t, storeDir, r.codexRolesDir()+"/default.toml")), "model = ") + assert.NotContains(t, string(storedUpload(t, storeDir, r.codexRolesDir()+"/explore.toml")), "model = ") + + held, ok := lookupRunnerHeldDigests("sb") + require.True(t, ok) + 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") +} + +// FULLSEND_CODEX_SUBAGENT_MODEL beats subagents.default for the run-level +// default; a persona without its own entry still gets no model line. +func TestCodexRuntimeBootstrap_SubagentModelEnvBeatsTheConfigDefault(t *testing.T) { + t.Setenv(codexSubagentModelEnv, "openai/gpt-5.6-terra") + storeDir := t.TempDir() + r, _, err := codexDelegatingBootstrap(t, storeDir, map[string]*string{"default": strp("openai/gpt-5.6-sol")}) + require.NoError(t, err) + + cfg := string(storedUpload(t, storeDir, r.codexConfigPath())) + assert.Contains(t, cfg, "default_subagent_model = \"gpt-5.6-terra\"\n") + assert.NotContains(t, cfg, "gpt-5.6-sol") + assert.NotContains(t, string(storedUpload(t, storeDir, r.codexRolesDir()+"/correctness.toml")), "model = ", + "the run-level default is bound in config.toml, not copied into role files") +} diff --git a/internal/runtime/codex_config.go b/internal/runtime/codex_config.go index 83b130f97f..c4ab02bdb5 100644 --- a/internal/runtime/codex_config.go +++ b/internal/runtime/codex_config.go @@ -112,15 +112,17 @@ const codexAuthTimeoutMS = 5000 // on roles whose GitHub profile allows git fetches, it would pull content // fullsend does not control into the sandbox. // -// `[agents] enabled = false` removes codex's multi-agent tools (spawn_agent, -// wait_agent, ...), which are on by default. fullsend wires no sub-agent -// roster on codex, and a child's token usage is not in the parent's -// turn.completed. `[features] multi_agent = false` is not enough: the model's -// catalog entry overrides it (verified on 0.157.0, 0.158.0 and 0.159.3). +// The `[agents]` table is codexAgentsBlock: `enabled = false` for an agent +// that does not delegate, which removes codex's multi-agent tools +// (spawn_agent, wait_agent, ...) that are on by default; for a delegating +// agent (ADR 0126) `enabled = true` with the roster, depth one, four open +// children and the run-level child model. `[features] multi_agent = false` +// is not enough to turn the tools off: the model's catalog entry overrides +// it (verified on 0.157.0, 0.158.0 and 0.159.3). // -// `[features] multi_agent_v2 = false` states codex's default so that -// `[agents] enabled = false` holds: codex checks this feature first, and when -// it is on the V2 collaboration tools come back for every model (verified on +// `[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). On its own the key removes nothing. // // `[model_providers.fullsend-gateway]` is rendered only when an @@ -160,8 +162,7 @@ enabled = false plugins = false multi_agent_v2 = false -[agents] -enabled = false +{{ .AgentsBlock }} [projects.{{ .ProjectKey }}] trust_level = "untrusted" @@ -201,8 +202,10 @@ type codexConfigData struct { DeveloperInstructions string AuthCommand string ProjectKey string - RefreshIntervalMS int - TimeoutMS int + // AgentsBlock arrives rendered by codexAgentsBlock, its strings quoted. + AgentsBlock string + RefreshIntervalMS int + TimeoutMS int // GatewayProviderID, GatewayBaseURL and GatewayAuthCommand render the // fullsend-gateway provider; GatewayBaseURL (quoted) is empty when no // inference.gateway block applies, and then nothing of it is rendered. @@ -216,8 +219,10 @@ type codexConfigData struct { // codex runs in. developerInstructions is the agent definition's body, which // is arbitrary markdown from the harness. gatewayBaseURL is the // fullsend-gateway provider's base_url (codexGatewayBaseURL), or "" when no -// inference.gateway block applies. -func renderCodexConfig(configDir, repoDir, developerInstructions, gatewayBaseURL string) ([]byte, error) { +// 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 string) ([]byte, error) { if repoDir == "" { return nil, fmt.Errorf("rendering codex %s: the target repository path is required", codexConfigFile) } @@ -228,6 +233,7 @@ func renderCodexConfig(configDir, repoDir, developerInstructions, gatewayBaseURL DeveloperInstructions: codexTOMLString(developerInstructions), AuthCommand: codexTOMLString(configDir + "/" + codexAuthScriptFile), ProjectKey: codexTOMLKey(repoDir), + AgentsBlock: codexAgentsBlock(configDir, roles, defaultSubagentModel), RefreshIntervalMS: codexAuthRefreshIntervalMS, TimeoutMS: codexAuthTimeoutMS, } @@ -245,6 +251,33 @@ func renderCodexConfig(configDir, repoDir, developerInstructions, gatewayBaseURL return []byte(buf.String()), nil } +// ADR 0126: one level of children, four open at once. +const ( + codexMaxOpenChildren = 4 + codexMaxChildDepth = 1 +) + +// codexAgentsBlock renders the [agents] table: off without roles; with +// roles, on under the ADR 0126 limits, with the run-level child model and +// one table per role file Bootstrap writes under /agents. +// Strings go through codexTOMLString and table keys through codexTOMLKey; +// the boolean and the two limits are bare. No trailing newline: the +// template supplies the blank line that follows. +func codexAgentsBlock(configDir string, roles []codexRole, defaultSubagentModel string) string { + if len(roles) == 0 { + return "[agents]\nenabled = false" + } + var b strings.Builder + fmt.Fprintf(&b, "[agents]\nenabled = true\nmax_concurrent_threads_per_session = %d\nmax_depth = %d\ndefault_subagent_model = %s\n", + codexMaxOpenChildren, codexMaxChildDepth, codexTOMLString(defaultSubagentModel)) + for _, role := range roles { + fmt.Fprintf(&b, "\n[agents.%s]\ndescription = %s\nconfig_file = %s\n", + codexTOMLKey(role.Name), codexTOMLString(role.Description), + codexTOMLString(configDir+"/agents/"+role.Name+".toml")) + } + return strings.TrimSuffix(b.String(), "\n") +} + // codexTOMLString renders s as a TOML basic string, quotes included. A value // with a newline becomes a multi-line basic string, so it reads as written. // Backslashes, quotes and control characters are escaped in both forms, so a diff --git a/internal/runtime/codex_config_test.go b/internal/runtime/codex_config_test.go index d286280a91..83abba3743 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, "") + data, err := renderCodexConfig(sandbox.SandboxCodexConfig, nastyRepo, nasty, "", nil, "") 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", "") + data, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", "", nil, "") require.NoError(t, err) rendered := string(data) @@ -130,8 +130,8 @@ func TestRenderCodexConfig_PinsProviderAndHygieneKeys(t *testing.T) { "[skills.bundled]", // The curated plugin marketplace is fetched from GitHub at startup. "[features]\nplugins = false", - // codex turns its multi-agent tools on by default; no sub-agent - // roster is wired on codex. + // codex turns its multi-agent tools on by default; an agent without + // a roster keeps them off. "[agents]\nenabled = false", // codex checks this feature before agents.enabled; when it is on the // V2 collaboration tools come back. @@ -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) + data, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", testCodexGatewayBaseURL, nil, "") 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", "") + plain, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", "", nil, "") require.NoError(t, err) - withGateway, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", testCodexGatewayBaseURL) + withGateway, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", testCodexGatewayBaseURL, nil, "") 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") + other, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", "https://evil.example.com/v1", nil, "") require.NoError(t, err) assert.NotEqual(t, codexAssetSHA256(withGateway), codexAssetSHA256(other), "the gateway base_url is covered by the digest") } @@ -435,7 +435,7 @@ func writeFileForTest(path string, data []byte) error { } func TestRenderCodexConfig_RequiresRepoDir(t *testing.T) { - _, err := renderCodexConfig(sandbox.SandboxCodexConfig, "", "body", "") + _, err := renderCodexConfig(sandbox.SandboxCodexConfig, "", "body", "", nil, "") require.Error(t, err, "an empty path would leave the project's trust unset") } @@ -478,3 +478,112 @@ func TestCodexHooksJSON_SpawnGuardIsFirst(t *testing.T) { assert.False(t, pattern.MatchString(name), "the guard must not run for %s", name) } } + +// codexTestDelegatingRoles is a sorted roster of three roles for the +// config.toml tests; explore carries codexExploreRoleDescription. +func codexTestDelegatingRoles() []codexRole { + return []codexRole{ + {Name: "correctness", Description: "Evaluates logic correctness, edge cases, nil handling, API contracts, test adequacy/integrity.", Instructions: "i"}, + {Name: "default", Description: "A generic child for a task that names no persona.", Instructions: "i"}, + {Name: "explore", Description: codexExploreRoleDescription, Instructions: "i"}, + } +} + +// TestRenderCodexConfig_DelegatingAgentsBlock pins the [agents] block of a +// delegating agent: enabled = true, the two limits ADR 0126 fixes, the +// run-level child model, one [agents.""] table per role with its +// description and the absolute path of its role file, in the roster's order; +// 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") + require.NoError(t, err) + rendered := string(data) + + want := "[features]\nplugins = false\nmulti_agent_v2 = false\n\n" + + "[agents]\n" + + "enabled = true\n" + + "max_concurrent_threads_per_session = 4\n" + + "max_depth = 1\n" + + "default_subagent_model = \"gpt-5.6-luna\"\n" + + "\n" + + "[agents.\"correctness\"]\n" + + "description = \"Evaluates logic correctness, edge cases, nil handling, API contracts, test adequacy/integrity.\"\n" + + "config_file = \"/sandbox/codex-config/agents/correctness.toml\"\n" + + "\n" + + "[agents.\"default\"]\n" + + "description = \"A generic child for a task that names no persona.\"\n" + + "config_file = \"/sandbox/codex-config/agents/default.toml\"\n" + + "\n" + + "[agents.\"explore\"]\n" + + "description = \"Investigation of the repository by reading only; reports findings. Instruction-only: nothing enforces read-only on a child.\"\n" + + "config_file = \"/sandbox/codex-config/agents/explore.toml\"\n" + + "\n" + + "[projects.\"/sandbox/workspace/repo\"]\ntrust_level = \"untrusted\"\n" + assert.Contains(t, rendered, want) + assert.NotContains(t, rendered, "enabled = false\n\n[projects", "the one [agents] table is the delegating one") + assert.Equal(t, 1, strings.Count(rendered, "\n[agents]\n")) + // The shapes codexConfigGuard pins are unchanged by the block. + assert.Equal(t, 1, strings.Count(rendered, "\nbase_url ")) + 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, "") + require.NoError(t, err) + empty, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", "", []codexRole{}, "gpt-5.6-luna") + 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.") +} + +// 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. +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 := ` +import json, sys, tomllib +with open(sys.argv[1], "rb") as fh: + cfg = tomllib.load(fh) +a = cfg["agents"] +print(json.dumps({ + "enabled": a["enabled"], + "open": a["max_concurrent_threads_per_session"], + "depth": a["max_depth"], + "default": a["default_subagent_model"], + "roles": sorted(k for k in a if isinstance(a[k], dict)), + "correctness": a["correctness"], + "projects": cfg["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"` + } + 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 984b386779..84b89844cf 100644 --- a/internal/runtime/codex_golden_test.go +++ b/internal/runtime/codex_golden_test.go @@ -75,13 +75,23 @@ func TestCodexGolden(t *testing.T) { }{ {"config.toml", func(t *testing.T) string { data, err := renderCodexConfig(sandbox.SandboxCodexConfig, repo, - codexDeveloperInstructions("triage", def), "") + codexDeveloperInstructions("triage", def, nil), "", nil, "") require.NoError(t, err) return string(data) }}, {"config-gateway.toml", func(t *testing.T) string { data, err := renderCodexConfig(sandbox.SandboxCodexConfig, repo, - codexDeveloperInstructions("triage", def), testCodexGatewayBaseURL) + 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, "", codexTestCatalog()) + require.NoError(t, err) + data, err := renderCodexConfig(sandbox.SandboxCodexConfig, repo, + codexDeveloperInstructions("review", review, roles), "", roles, defaultModel) require.NoError(t, err) return string(data) }}, diff --git a/internal/runtime/codex_run.go b/internal/runtime/codex_run.go index 62dfdfff08..7a63a3d792 100644 --- a/internal/runtime/codex_run.go +++ b/internal/runtime/codex_run.go @@ -513,8 +513,8 @@ func buildCodexRunCommand(params RunParams, model codexModel, effort string, hoo } // Run executes one agent iteration and normalizes codex's `exec --json` stream -// into AgentEvents. codex exits 0 on a failed turn and on an interrupted one, -// so the stream's verdict overrides the exit code, as it does for pi. +// into AgentEvents. The stream's verdict overrides a zero exit code, as it +// does for pi, so a failed turn fails the run whatever codex exits. func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Printer, start time.Time, metrics *RunMetrics) (int, error) { m, err := readCodexManifest(params.SandboxName, r.codexManifestPath()) if err != nil { @@ -702,8 +702,9 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri // non-zero exit does not fail the run; an error from Run does, and a // failed read or an unread spawn item is one too, unlike the usage read // above. A dropped stream notification can hide a completed spawn, but - // nothing can spawn until the multi-agent tools are switched on, so it - // is a warning until then. + // the count cannot tell one from a harmless drop (exec re-reads the + // turn's persisted items from the thread at turn/completed), so it stays + // a warning. if stderr.Dropped > 0 { msg := fmt.Sprintf("codex dropped %d stream notification(s) under backpressure", stderr.Dropped) if stderr.BackfillFailed > 0 { diff --git a/internal/runtime/codex_run_test.go b/internal/runtime/codex_run_test.go index 3d3c4eef0e..868b5ec3d1 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", "") + good, err := renderCodexConfig(dir, "/sandbox/workspace/repo", "body", "", nil, "") require.NoError(t, err) digests := codexRunnerHeldDigestSet{ConfigTOML: codexAssetSHA256(good)} guard := strings.ReplaceAll(codexConfigGuard(r, digests), sandbox.SandboxCodexConfig, dir) diff --git a/internal/runtime/testdata/codex/golden/config-delegating.toml b/internal/runtime/testdata/codex/golden/config-delegating.toml new file mode 100644 index 0000000000..e439a2a518 --- /dev/null +++ b/internal/runtime/testdata/codex/golden/config-delegating.toml @@ -0,0 +1,70 @@ +# 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. 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. + +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. + +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 +multi_agent_v2 = 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 From 2762f3803ced86c2c5ab862025f4083e3dcab358 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Mon, 26 Oct 2026 16:11:20 -0400 Subject: [PATCH 03/15] docs(codex): document native sub-agents, child models and child transcripts The discovery rule for the roster, the child model chain with FULLSEND_CODEX_SUBAGENT_MODEL, the transcript name of a child, the At-a-glance entry and the V1-parent limit on the codex page; the Sub-agents row of the runtime matrix; subagents on codex in the config reference; the transcript pointer of fullsend run; the architecture line without its not-yet clause; the two contributor statements that said the roster was not wired. The keep-review-and-retro-on-Claude recommendation stays until a fleet-shaped run completes; its reason no longer says there is no roster. Signed-off-by: Dharit Shah --- docs/architecture.md | 2 +- docs/cli/run.md | 6 +- docs/contributing/runtime-implementation.md | 11 +-- .../getting-started/choosing-a-runtime.md | 4 +- docs/reference/config-reference.md | 6 +- docs/runtimes.md | 4 +- docs/runtimes/codex.md | 93 ++++++++++++++++--- 7 files changed, 99 insertions(+), 27 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 711b1ab91e..1bf849e998 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -308,7 +308,7 @@ flowchart TB - The `fullsend run` runner delegates in-sandbox agent execution to a `runtime.Runtime` interface; production orgs default to Claude Code, with [pi](https://github.com/earendil-works/pi) available as an opt-in second runtime (`runtime: pi`, Claude-on-Vertex through the same WIF credential path), [codex](https://github.com/openai/codex) as a third (`runtime: codex`, OpenAI models through a custom model provider whose bearer token comes from a runner-seeded file, or `gateway/` models through a runner-owned gateway provider ([ADR 0137](ADRs/0137-inference-gateway-credential-route.md)), with the sandbox tool hooks behind a translating adapter — [ADR 0099](ADRs/0099-codex-agent-runtime.md) and [ADR 0100](ADRs/0100-codex-sandbox-hooks.md)), and [OpenCode](https://github.com/anomalyco/opencode) as a fourth (`runtime: opencode`, Claude-on-Vertex through the same WIF credential path; read-only agents only until the security-hook plugin adapter in [unbound-force#515](https://github.com/unbound-force/unbound-force/issues/515) lands). Runtime selection is configured per repo with `runtime:` in `.fullsend/config.yaml` (per-agent `runtime`/`model`/`effort`/`subagents` on the agent's `agents:` entry sit above it and below the `--runtime`/`--model`/`--effort` flags and `FULLSEND_*` variables, [ADR 0091](ADRs/0091-per-agent-runtime-model-effort.md)) and resolved via `runtime.ResolveForAgent()`. Test-only runtimes — **dummy** (scripted operations) and **dummy-playback** (playlist-based replay of canned results) — execute in the real OpenShell sandbox for behaviour tests without inference. Bootstrap uses a portable `BootstrapInput` interface with optional extensions such as `SandboxHooksBootstrap` for the runtime-neutral sandbox tool hooks ([ADR 0090](ADRs/0090-runtime-neutral-sandbox-hooks-contract.md)); runtimes declare further capabilities through small optional interfaces (`DebugLogNamer`, `ContextBridger`) rather than `Name()` checks in the runner. Transcript and debug artifact handling use a separate `TranscriptHandler` interface. See [runtimes.md](runtimes.md) for the per-runtime security feature matrix required when adding a new backend. - Harness `overlays:` ([ADR 0088](ADRs/0088-cel-guarded-overlays.md)) will be able to set any harness field except `base`, `trigger`, `overlays`, `slug`, `role` and `forge`; an overlay that sets a guarded field (any field except `model`, `effort`, `description` and `doc`) may read only trusted event and entity fields, `runtime.forge` and `config`, and every run will record an overlay resolution trace in the plan output and a dedicated span ([ADR 0112](ADRs/0112-overlays-may-set-any-harness-field.md)). Per-task model routing is overlays setting `model` and `effort`, and when a routed model isn't served the runner retries once with the model and effort the run would use without overlays, and `FULLSEND_FALLBACK_MODELS` applies as each runtime allows. 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)). -- Native Codex children run under a runner-owned policy: Bootstrap registers roles for an agent with the `Agent` tool, under harness security, whose parent model Codex resolves to collaboration V1 (a V2 or unlisted parent keeps the multi-agent tools off), and binds each child's model (a persona's own entry in its role file, the run-level default otherwise), and a mandatory dispatch hook admits only fresh-context V1 spawns of registered roles after checking `hooks.json` and the role files against runner-held digests ([ADR 0126](ADRs/0126-fullsend-owned-codex-subagents.md)); not yet implemented, so review and retro still run in one context on Codex ([#6970](https://github.com/fullsend-ai/fullsend/issues/6970)). +- Native Codex children run under a runner-owned policy: Bootstrap registers roles for an agent with the `Agent` tool, under harness security, whose parent model Codex resolves to collaboration V1 (a V2 or unlisted parent keeps the multi-agent tools off), and binds each child's model (a persona's own entry in its role file, the run-level default otherwise), and a mandatory dispatch hook admits only fresh-context V1 spawns of registered roles after checking `hooks.json` and the role files against runner-held digests ([ADR 0126](ADRs/0126-fullsend-owned-codex-subagents.md), [#6970](https://github.com/fullsend-ai/fullsend/issues/6970)). ### Behaviour testing diff --git a/docs/cli/run.md b/docs/cli/run.md index cad12cce4c..72030cb18e 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -91,6 +91,9 @@ subagents: correctness → anthropic-vertex/claude-opus-4-6 (from frontmatter) subagents: docs-currency → google-vertex/gemini-3.8-flash (from subagents.docs-currency) ``` +On codex a delegating agent prints the run-level default and one line per persona with its own +`subagents` entry; see [Codex › Child models](../runtimes/codex.md#child-models). + A malformed `subagents` key or model reference is rejected by config validation, before the sandbox is created, like the other invalid overrides above. A key that names no discovered persona, or a model this run cannot serve, is caught slightly later — at Bootstrap, once the @@ -173,7 +176,8 @@ differences in the last bullet. sub-agent, which is what keeps the invariant true across a retry. - **What stays parent-only.** `num_turns` and `tool_calls` are read from the parent's stream and are not broken down or added to per model — a child's turns and tool calls are recorded in its own - session transcript (`transcripts/-sub-*.jsonl`) instead. + session transcript (`transcripts/-sub-*.jsonl`; on codex + `transcripts/-sub-.jsonl`, see [Codex › At a glance](../runtimes/codex.md#at-a-glance)) instead. - A model spec of `unknown` is a pi usage record, or a codex child rollout, that carries no model at all; its usage is bucketed there rather than dropped. A dispatch rejected *before* a model was resolved writes no record, so it never reaches the breakdown. diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index e89aa59a13..11124c348c 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -1144,7 +1144,7 @@ flowchart TB 0.159.3) its `.codex/skills` even with the project untrusted; both are covered by the host-side and in-sandbox context scans, which match `SKILL.md` anywhere in the repo. The agent reads those files through the shell, and Codex 0.157.0 truncates a single exec at 10,000 tokens (head and - tail), so `codexNoSubagentNote` tells it to count lines with `awk 'END { print NR }'` (`wc -l` + tail), so both runtime notes (`codexChunkedReadNote`) tell it to count lines with `awk 'END { print NR }'` (`wc -l` 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 @@ -1245,7 +1245,7 @@ Matcher translation, per group: |---|---|---| | `Bash` | `Bash` | codex's shell tool has the same name | | `Write`, `Edit`, `MultiEdit` | `apply_patch` | the canonical name; `Write`/`Edit` would also match as aliases | -| `Agent`, `Task` | `spawn_agent` | not reachable in v1 — no sub-agent roster is wired | +| `Agent`, `Task` | `spawn_agent` | reached by a delegating agent's spawns (ADR 0126); the spawn guard is the last row | | `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 | @@ -1505,11 +1505,8 @@ Two artefacts of the run are worth knowing about: and local smoke runs. - The rollout session files are archived as transcripts but not error-classified: only the tee'd `exec --json` capture yields a verdict, which is what the runner's exit-code override reads. -- Sub-agent roles are generated (`agents/.toml`, digest-guarded) for an agent with the `Agent` - tool under harness security whose parent model Codex resolves to collaboration V1 (ADR 0126), but - codex's multi-agent tools stay off (`[agents] enabled = false`), so `review`/`retro` are unsupported; - `Bootstrap` appends a runtime note telling the agent to execute sub-agent definitions itself, in - order, as it does for pi. +- Native sub-agents (ADR 0126) have not completed a fleet-shaped run; `review`/`retro` stay on + Claude Code in the docs until one does. ### Re-check on a `CODEX_VERSION` bump diff --git a/docs/guides/getting-started/choosing-a-runtime.md b/docs/guides/getting-started/choosing-a-runtime.md index cfdd4831f5..0863acfacb 100644 --- a/docs/guides/getting-started/choosing-a-runtime.md +++ b/docs/guides/getting-started/choosing-a-runtime.md @@ -4,7 +4,7 @@ sidebar_label: Choose a Runtime # Choose an agent runtime -> **Claude Code is the stable default.** The fleet agents have run on Claude Code in production for a long time; it is what a new installation gets unless you ask for something else. **pi and codex are experimental** — pi works end to end for `triage`, `prioritize`, `code`, `fix` and `review`/`retro`; codex runs OpenAI models through the same secretless credential path but has no sub-agent roster yet, so `review`/`retro` are best left on Claude Code there. Neither runtime has completed a fleet pilot. Unless you are taking part in one, keep the default. +> **Claude Code is the stable default.** The fleet agents have run on Claude Code in production for a long time; it is what a new installation gets unless you ask for something else. **pi and codex are experimental** — pi works end to end for `triage`, `prioritize`, `code`, `fix` and `review`/`retro`; codex runs OpenAI models through the same secretless credential path; `review`/`retro` are best left on Claude Code there. Neither runtime has completed a fleet pilot. Unless you are taking part in one, keep the default. This page explains what the choice means and where it is made. **You do not select anything on this page** — the selection happens in the next step. On GitHub, [Configuring GitHub](configuring-github.md) asks when you run `fullsend github setup` (press Enter for `claude`) or you pass `--runtime`. On GitLab, set `runtime:` in `defaults.config`, `gitlab.config`, or the repository entry's `config` in `repos.yaml` before running `fullsend repos install` (there is no install flag) — see [Configuring GitLab](configuring-gitlab.md). @@ -16,7 +16,7 @@ Fullsend supports multiple agent runtimes. A runtime is the program that runs in |---------|--------|-------------|-------------| | `claude` | **Stable (default)** | Claude Code on Vertex AI | Every production deployment — mature, full sub-agent support for `review`/`retro` | | `pi` | Experimental (enablement phase) | [Pi](https://github.com/earendil-works/pi) — Claude on Vertex by default; any provider pi supports by model name (e.g. Gemini on Vertex with the same credentials) | Opt-in pilots only; see [Runtimes](../../runtimes.md) for known constraints | -| `codex` | Experimental | [Codex](https://github.com/openai/codex) — OpenAI models through the same secretless credential path, or any Responses-capable model through an inference gateway (`gateway/`) | Opt-in pilots only, when you want GPT specifically. No sub-agent roster, so keeping `review`/`retro` on Claude Code is recommended; needs an OpenAI or `gateway/` model named (`FULLSEND_CODEX_MODEL`) because the fleet harnesses ask for `opus`; see [Codex](../../runtimes/codex.md) | +| `codex` | Experimental | [Codex](https://github.com/openai/codex) — OpenAI models through the same secretless credential path, or any Responses-capable model through an inference gateway (`gateway/`) | Opt-in pilots only, when you want GPT specifically. Sub-agents run as native Codex children, not yet verified fleet-wide, so keeping `review`/`retro` on Claude Code is recommended; needs an OpenAI or `gateway/` model named (`FULLSEND_CODEX_MODEL`) because the fleet harnesses ask for `opus`; see [Codex](../../runtimes/codex.md) | | `opencode` | Experimental | [OpenCode](https://opencode.ai/) — reads `AGENTS.md` natively | Opt-in read-only agents (`triage`, `prioritize`) until the security-hook adapter lands; see [OpenCode](../../runtimes/opencode.md) | ## When and how the runtime is selected diff --git a/docs/reference/config-reference.md b/docs/reference/config-reference.md index 0bf1e5fd0a..e49ac16ff5 100644 --- a/docs/reference/config-reference.md +++ b/docs/reference/config-reference.md @@ -47,7 +47,7 @@ agents: # Registered agent sources and per-agent tu runtime: claude # Per-agent runtime override model: opus # Per-agent model override (model id or provider/id) effort: high # Per-agent reasoning effort: low, medium, high, xhigh, max - subagents: # Per-agent sub-agent model map + subagents: # Per-agent sub-agent model map (pi and codex) default: sonnet # Fallback model for personas without an explicit entry code-reviewer: opus # Model for a specific persona # trigger: # When the built-in review agent runs (review entry only) @@ -194,7 +194,9 @@ effort, sub-agent models and the trigger. - **`subagents`** — Map of persona names to model references. The `default` key sets the fallback for personas without an explicit entry. A `~` (null) value tombstones an inherited entry. Keys must be lowercase alphanumeric - segments joined by hyphens (max 64 chars). + segments joined by hyphens (max 64 chars). On codex the values must be + OpenAI ids and a key must name a discovered persona or `default`; see + [Codex › Child models](../runtimes/codex.md#child-models). - **`trigger`** — A [CEL trigger](../guides/user/cel-triggers-reference.md) (a boolean over the normalized `event`). It decides routing for the built-in review, retro, triage and prioritize agents only: on one of those diff --git a/docs/runtimes.md b/docs/runtimes.md index b06b4c0f49..63a175a068 100644 --- a/docs/runtimes.md +++ b/docs/runtimes.md @@ -55,10 +55,10 @@ 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 | Not available | +| 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`, on a parent model Codex resolves to collaboration V1 ([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 — no sub-agent roster on codex | +| 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)) | | Effort | `--effort low..max` | `--thinking`, same levels (`high` when unset) | `model_reasoning_effort`, same levels | | Tools | Native Claude permission syntax | `--tools` (strict) + a first-token Bash allowlist | Shell + `apply_patch` only; `tools:` is recorded, not enforced (the allowlist hook is opt-in) | | Security controls | Full matrix | Full matrix; stricter on failed-call sanitizing | Full matrix; post-tool hooks detect and block but cannot rewrite output | diff --git a/docs/runtimes/codex.md b/docs/runtimes/codex.md index 1964082422..5a76caab90 100644 --- a/docs/runtimes/codex.md +++ b/docs/runtimes/codex.md @@ -130,19 +130,90 @@ own log. **Check the effort level against the model.** Effort is passed to the gateway as is, and some models refuse some levels with an upstream 400. Check the levels your model accepts before you set `effort`. +### Child models + +A native child (see [Sub-agents](#sub-agents)) runs on the first of these that is set: + +1. `subagents.` on the agent's `agents:` entry — that persona's role file carries the model; +2. `FULLSEND_CODEX_SUBAGENT_MODEL` on the runner — the run-level default for every other child; +3. `subagents.default` on the agent's `agents:` entry; +4. `gpt-5.6-luna`. + +Positions 2 to 4 set Codex's `agents.default_subagent_model`, which every child without its own +entry takes — the personas without an entry and the unnamed children of `retro` alike. A +persona's frontmatter `model:` is never applied on codex. Only OpenAI ids are accepted +(`openai/` or the bare id): a Claude alias, another provider's prefix, a `gateway/` spec (the +route is selected by the run's own model) or `inherit` fails Bootstrap and names the key: + +``` +subagents.correctness: "xai-vertex/xai/grok-4.6" is not an OpenAI model id (openai/ or the bare +id); set an OpenAI id (openai/) or tombstone the entry (`correctness: ~` under subagents:) so the +run-level default applies +``` + +A tombstone (`correctness: ~`) removes an inherited entry, as on pi, so a `subagents` map written +for pi can stay in a parent layer. Bootstrap also checks every resolved model, the floor included, +against the catalog bundled with the pinned Codex CLI (`codex debug models --bundled`, read offline +in the sandbox) and fails naming the position that supplied an unlisted id: Codex itself checks a +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 tier +of the current family, whose catalog entry selects collaboration V1 on the pinned CLI (see +[Sub-agents](#sub-agents)). The runner reads `FULLSEND_CODEX_SUBAGENT_MODEL` from its own +environment: a fleet workflow sets it in the job environment (plain or `_`-prefixed); unlike +`FULLSEND_CODEX_MODEL` it is not read from repository variables. A child's reasoning effort follows +the run-level default model's standard effort. Bootstrap prints what it resolved: + +``` +subagents: default → gpt-5.6-luna (from built-in default; children that name no persona and personas without an entry) +subagents: correctness → gpt-5.6-sol (from subagents.correctness) +``` + +## Sub-agents + +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 (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: +...`), and `config.toml` in a kept sandbox declares it. An agent whose `tools:` list leaves +`Agent` out, and any run with harness security disabled, keeps Codex's multi-agent tools off and +runs in one context, as before. + +Each child starts with only 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 +sub-agent definition itself. A spawn the hook did not admit fails the run after the fact: the +runner compares the spawns in the run's event stream with the admissions the hook recorded (see +[Troubleshooting](#troubleshooting)). 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; for any +other parent, a V2 model such as `gpt-5.6-sol` or a model the catalog does not list included, it +keeps Codex's multi-agent tools off, prints one line saying why (`sub-agents: parent model +"gpt-5.6-sol" selects collaboration "v2"; native sub-agents need a parent Codex resolves to +collaboration V1, running in one context`), and the agent runs in one context. + ## At a glance | | | |---|---| | 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`, `metrics.json` with `runtime: codex`, plus `codex-debug.log` with `--debug`. Only uncompressed rollouts are extracted — codex compresses older sessions, so a `.jsonl.zst` is never the run's own transcript. The agent's final message is in the stream; `--output-last-message` also drops it in the runner-owned config directory inside the sandbox, which is a convenience when inspecting a kept sandbox rather than a downloaded artifact | -| Extra knobs | `FULLSEND_CODEX_MODEL` (the runner-side model default for codex runs; see [Models](#models)) | -| Not supported | Sub-agents, `plugins:`, fallback chains, non-OpenAI providers (other than through a Responses-capable inference gateway), Chat Completions or Messages on a gateway | +| Artifacts | `output.jsonl` (the `codex exec --json` stream), `transcripts/-.jsonl` for the root thread and `transcripts/-sub-.jsonl` for each native child (`generic` for a spawn that named no `agent_type`: the `default` role, which codex records as no role), `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`, on a parent model Codex resolves to collaboration V1, under a runner-owned policy: registered roles only, fresh context, depth one, four open; 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; 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 (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`. -Token counts are recorded normally on the direct route; through a gateway +Token counts are recorded normally on the direct route and include native children; through a gateway they can read 0 (see [Models through an inference gateway](#models-through-an-inference-gateway-experimental)). See [Computing dollar cost from token telemetry](../guides/infrastructure/distributed-tracing.md#computing-dollar-cost-from-token-telemetry) for a list-price estimate from `run-telemetry.jsonl`, including Codex reasoning tokens. @@ -303,12 +374,10 @@ has no default behaviour-test coverage; its scenario is gated. What was run, and is recorded in [codex runtime internals](../contributing/runtime-implementation.md#codex-runtime-internals-6920). -**Keep `review` and `retro` on Claude Code.** fullsend turns off Codex's native delegation -(`agents.enabled = false` and `features.multi_agent_v2 = false` in the config it writes) because it -does not yet support persona wiring or child token accounting, so those two agents run in a single -context instead of with their reviewer personas. Nothing prevents a repo-wide `runtime: codex` from -applying to them — they will run — so pin them with `runtime: claude` on their `agents:` entries if -you want the roster: +**Keep `review` and `retro` on Claude Code.** Their sub-agents run as native Codex children +([Sub-agents](#sub-agents)), but that path has not completed a fleet-shaped run yet. Nothing +prevents a repo-wide `runtime: codex` from applying to them — they will run — so pin them with +`runtime: claude` on their `agents:` entries until it has: ```yaml agents: @@ -432,8 +501,8 @@ under `--debug`), replacing any value from the environment or `.env`. **The model answers, then the run fails anyway.** A model your account cannot serve on the Responses API surfaces as several `error` reconnect events and a `turn.failed` carrying the 404 — not as a -startup error. `codex exec` can still exit 0 there, so fullsend takes the verdict from the stream -rather than the exit code, and the run fails as it should. +startup error. Whatever `codex exec` exits there, fullsend takes the verdict from the stream too, +so the run fails as it should. **`Run-scoped provider ... expired in place instead of deleted`.** The run finished and deleted its sandbox, but OpenShell still reported the provider attached to it, so fullsend expired the From 144ad6460a9977f143a3ee0c4deb479c228153a4 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Mon, 26 Oct 2026 20:28:11 -0400 Subject: [PATCH 04/15] fix(codex): name a reserved or unregistered subagents key plainly A subagents key that names no persona failed Bootstrap with "is not a registered codex role" and a note about a skipped persona, printed even when none was skipped; explore, a built-in role, read as unknown. The reserved key now says it is a built-in role on the run-level child model; any other key says no persona of that name is registered, as pi does. Discovery still prints a skipped persona's warning above it. Signed-off-by: Dharit Shah --- internal/runtime/codex_personas.go | 7 +++++-- internal/runtime/codex_personas_test.go | 4 ++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/internal/runtime/codex_personas.go b/internal/runtime/codex_personas.go index 2d70debb2e..7b43f102f1 100644 --- a/internal/runtime/codex_personas.go +++ b/internal/runtime/codex_personas.go @@ -101,8 +101,11 @@ func resolveCodexChildModels(roles []codexRole, subagents map[string]*string, en if len(persona) > 0 { discovered = strings.Join(slices.Sorted(maps.Keys(persona)), ", ") } - return nil, "", fmt.Errorf("subagents.%s: %q is not a registered codex role (a discovered persona that was skipped is reported above); registered personas: %s", - key, key, discovered) + if slices.Contains(config.ReservedSubagentKeys(), key) { + return nil, "", fmt.Errorf("subagents.%s: %q is a built-in role, not a persona; it runs on the run-level child model; registered personas: %s", + key, key, discovered) + } + return nil, "", fmt.Errorf("subagents.%s: no persona %q is registered; registered personas: %s", key, key, discovered) } out := slices.Clone(roles) diff --git a/internal/runtime/codex_personas_test.go b/internal/runtime/codex_personas_test.go index 6cd25f603d..8bbe08ab5f 100644 --- a/internal/runtime/codex_personas_test.go +++ b/internal/runtime/codex_personas_test.go @@ -541,9 +541,9 @@ func TestResolveCodexChildModels_RejectsUnknownKeys(t *testing.T) { wantErr []string }{ {name: "explore is reserved", roles: roles, cfg: map[string]*string{"explore": strp("openai/gpt-5.6-sol")}, - wantErr: []string{"subagents.explore", "correctness"}}, + wantErr: []string{"subagents.explore", "built-in role", "correctness"}}, {name: "a typo", roles: roles, cfg: map[string]*string{"correctnes": strp("openai/gpt-5.6-sol")}, - wantErr: []string{"subagents.correctnes", `"correctnes"`, "correctness"}}, + wantErr: []string{"subagents.correctnes", `no persona "correctnes" is registered`, "correctness"}}, {name: "no persona at all", roles: nil, cfg: map[string]*string{"correctness": strp("openai/gpt-5.6-sol")}, wantErr: []string{"subagents.correctness", "none"}}, {name: "a tombstoned unknown key is skipped", roles: roles, cfg: map[string]*string{"correctnes": nil}}, From 3c34754f8a874ccf7117a8cdc3228383c19d4e2e Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Mon, 26 Oct 2026 20:28:17 -0400 Subject: [PATCH 05/15] docs(codex): give codex's fallback for a cleared --subagent entry MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The agent --subagent row described only pi's fallback for a cleared entry and linked only the pi page. It now names codex's (the run-level child model, OpenAI ids from the pinned catalog) and links Codex › Child models. The Sub-agents paragraph on the codex page is rewrapped at about 80 columns. Signed-off-by: Dharit Shah --- docs/cli/agent.md | 7 ++++--- docs/runtimes/codex.md | 15 ++++++++------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/docs/cli/agent.md b/docs/cli/agent.md index e1647dfe61..1ff12c1345 100644 --- a/docs/cli/agent.md +++ b/docs/cli/agent.md @@ -432,11 +432,12 @@ fullsend agent set review --subagent correctness=opus --subagent default=haiku | `--runtime` | Agent runtime for this agent (`claude`, `pi`, `codex` or `opencode`) | | `--model` | Model for this agent — an alias, a model id, or `provider/id` on pi, codex, and opencode (codex takes OpenAI ids and `gateway/` only) | | `--effort` | Effort level for this agent (`low`, `medium`, `high`, `xhigh`, `max`) | -| `--subagent` | Per-persona model override as `key=value` (repeatable). Key is a persona name or `default`; value is a model reference. Pass an empty value (`--subagent key=`) to clear an inherited entry — that writes `key: ~` in the config, after which the persona resolves the way an unmentioned one does (its frontmatter model, then `subagents.default`). On pi, a value that resolves to `openai/` prints a warning when the agent's local harness declares no `openai` provider; see [pi § Route a persona to OpenAI](../runtimes/pi.md#route-a-persona-to-openai) | +| `--subagent` | Per-persona model override as `key=value` (repeatable). Key is a persona name or `default`; value is a model reference (on codex, an OpenAI id the pinned CLI's catalog lists). Pass an empty value (`--subagent key=`) to clear an inherited entry — that writes `key: ~` in the config, after which the persona resolves the way an unmentioned one does (on pi, its frontmatter model, then `subagents.default`; on codex, the run-level child model, see [Codex § Child models](../runtimes/codex.md#child-models)). On pi, a value that resolves to `openai/` prints a warning when the agent's local harness declares no `openai` provider; see [pi § Route a persona to OpenAI](../runtimes/pi.md#route-a-persona-to-openai) | See [Runtimes — per-agent settings](../runtimes.md#per-agent-runtime-model-and-effort) for precedence. -See [pi § Per-persona model configuration](../runtimes/pi.md#per-persona-model-configuration) for -how `subagents` map to persona dispatch. +See [pi § Per-persona model configuration](../runtimes/pi.md#per-persona-model-configuration) and +[Codex § Child models](../runtimes/codex.md#child-models) for how `subagents` map to persona +dispatch on each runtime. ## `agent remove` diff --git a/docs/runtimes/codex.md b/docs/runtimes/codex.md index 5a76caab90..dd7884221f 100644 --- a/docs/runtimes/codex.md +++ b/docs/runtimes/codex.md @@ -191,13 +191,14 @@ runner compares the spawns in the run's event stream with the admissions the hoo [Troubleshooting](#troubleshooting)). 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; for any -other parent, a V2 model such as `gpt-5.6-sol` or a model the catalog does not list included, it -keeps Codex's multi-agent tools off, prints one line saying why (`sub-agents: parent model -"gpt-5.6-sol" selects collaboration "v2"; native sub-agents need a parent Codex resolves to +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; for any other parent, a V2 model such as `gpt-5.6-sol` or a model the +catalog does not list included, it keeps Codex's multi-agent tools off, prints +one line saying why (`sub-agents: parent model "gpt-5.6-sol" selects +collaboration "v2"; native sub-agents need a parent Codex resolves to collaboration V1, running in one context`), and the agent runs in one context. ## At a glance From 6a26a79f36ddf1afe8a69b36e25fe695aa5c103b Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 27 Oct 2026 09:44:22 -0400 Subject: [PATCH 06/15] fix(codex): give the skip reason for a subagents key a skipped persona owns A subagents key naming a persona that codexRoles skipped (a name reserved on codex, no description, an empty body, or a discovery skip) failed Bootstrap with "no persona ... is registered", leaving only the earlier warning to explain why. codexRoles now returns each skipped name with its reason, and the key error carries the matching one, as pi does. A reserved key keeps its built-in-role message, and a key naming no persona is unchanged. Signed-off-by: Dharit Shah --- internal/runtime/codex_bootstrap.go | 3 +- internal/runtime/codex_bootstrap_test.go | 19 +++++---- internal/runtime/codex_golden_test.go | 7 ++-- internal/runtime/codex_personas.go | 21 +++++++--- internal/runtime/codex_personas_test.go | 50 ++++++++++++++++++------ 5 files changed, 72 insertions(+), 28 deletions(-) diff --git a/internal/runtime/codex_bootstrap.go b/internal/runtime/codex_bootstrap.go index d139dee35c..e319f7bac5 100644 --- a/internal/runtime/codex_bootstrap.go +++ b/internal/runtime/codex_bootstrap.go @@ -177,8 +177,9 @@ func (r CodexRuntime) Bootstrap(input BootstrapInput) error { var roles []codexRole defaultSubagentModel := "" if delegating { + discovered, skipped := codexRoles(input.SkillDirs(), agentName) roles, defaultSubagentModel, err = resolveCodexChildModels( - codexRoles(input.SkillDirs(), agentName), input.AgentSubagents(), os.Getenv(codexSubagentModelEnv), catalog) + discovered, skipped, input.AgentSubagents(), os.Getenv(codexSubagentModelEnv), catalog) if err != nil { return err } diff --git a/internal/runtime/codex_bootstrap_test.go b/internal/runtime/codex_bootstrap_test.go index 5dc74231fc..bac0d289a9 100644 --- a/internal/runtime/codex_bootstrap_test.go +++ b/internal/runtime/codex_bootstrap_test.go @@ -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") require.Len(t, held.RoleFiles, len(want)) var names []string for name := range held.RoleFiles { @@ -1087,8 +1087,9 @@ func TestCodexBootstrap_PlantedRoleFileDeniesSpawn(t *testing.T) { } // codexDelegatingBootstrap runs Bootstrap for the delegating review agent -// with one correctness persona, harness security on and the given subagents -// map. It returns the runtime, the fake's argv log and Bootstrap's error. +// with one correctness persona (and a worker persona codex skips), harness +// security on and the given subagents map. It returns the runtime, the +// fake's argv log and Bootstrap's error. func codexDelegatingBootstrap(t *testing.T, storeDir string, subagents map[string]*string) (CodexRuntime, string, error) { t.Helper() logPath := filepath.Join(t.TempDir(), "openshell.log") @@ -1097,6 +1098,7 @@ func codexDelegatingBootstrap(t *testing.T, storeDir string, subagents map[strin t.Cleanup(func() { forgetRunnerHeldDigests("sb") }) skill := t.TempDir() writePersonaFile(t, skill, "correctness", codexTestPersona) + writePersonaFile(t, skill, "worker", "---\nname: worker\ndescription: d\n---\nbody\n") input := codexDelegatingHooksInput(t, skill) input.agentSubagents = subagents @@ -1105,10 +1107,10 @@ func codexDelegatingBootstrap(t *testing.T, storeDir string, subagents map[strin } // TestCodexRuntimeBootstrap_RejectsNonOpenAISubagentModel pins the wiring: -// the subagents map, the catalog and the runner variable reach the resolver, -// and a bad value fails Bootstrap naming the key before config.toml is -// written. The breaking case is a pi-shaped review entry (xai and -// google-vertex values) run with runtime codex. +// the subagents map, the skipped personas, the catalog and the runner +// variable reach the resolver, and a bad value fails Bootstrap naming the +// key before config.toml is written. The breaking case is a pi-shaped +// review entry (xai and google-vertex values) run with runtime codex. func TestCodexRuntimeBootstrap_RejectsNonOpenAISubagentModel(t *testing.T) { for name, tc := range map[string]struct { env string @@ -1122,6 +1124,9 @@ func TestCodexRuntimeBootstrap_RejectsNonOpenAISubagentModel(t *testing.T) { subagents: map[string]*string{"correctness": strp("openai/gpt-5.6-nova")}, want: []string{`subagents.correctness: model "gpt-5.6-nova" is not in the bundled catalog`}}, "the runner variable": {env: "opus", want: []string{codexSubagentModelEnv, `"opus"`, "unset"}}, + "a persona codex skipped": { + subagents: map[string]*string{"worker": strp("openai/gpt-5.6-sol")}, + want: []string{`subagents.worker: persona "worker" was not registered: name is reserved on codex`}}, } { t.Run(name, func(t *testing.T) { t.Setenv(codexSubagentModelEnv, tc.env) diff --git a/internal/runtime/codex_golden_test.go b/internal/runtime/codex_golden_test.go index 84b89844cf..4dd56e0031 100644 --- a/internal/runtime/codex_golden_test.go +++ b/internal/runtime/codex_golden_test.go @@ -88,7 +88,7 @@ func TestCodexGolden(t *testing.T) { {"config-delegating.toml", func(t *testing.T) string { review, err := parsePiAgent([]byte(codexTestDelegatingAgentDef)) require.NoError(t, err) - roles, defaultModel, err := resolveCodexChildModels(codexGoldenRoles(t), nil, "", codexTestCatalog()) + 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) @@ -122,7 +122,7 @@ func TestCodexGolden(t *testing.T) { {"roles/default.toml", func(t *testing.T) string { return string(codexGoldenRoles(t)[1].toml()) }}, {"roles/explore.toml", func(t *testing.T) string { return string(codexGoldenRoles(t)[2].toml()) }}, {"roles/correctness-model.toml", func(t *testing.T) string { - resolved, _, err := resolveCodexChildModels(codexGoldenRoles(t), + resolved, _, err := resolveCodexChildModels(codexGoldenRoles(t), nil, map[string]*string{"correctness": strp("openai/gpt-5.6-sol")}, "", codexTestCatalog()) require.NoError(t, err) require.Equal(t, "correctness", resolved[0].Name, "codexRoles sorts by name") @@ -161,7 +161,8 @@ func codexGoldenRoles(t *testing.T) []codexRole { t.Helper() skill := t.TempDir() writePersonaFile(t, skill, "correctness", codexTestPersona) - return codexRoles([]string{skill}, "review") + roles, _ := codexRoles([]string{skill}, "review") + return roles } // codexGoldenDelegatingDigests is testRunnerHeldDigests plus the role diff --git a/internal/runtime/codex_personas.go b/internal/runtime/codex_personas.go index 7b43f102f1..4dcc860b24 100644 --- a/internal/runtime/codex_personas.go +++ b/internal/runtime/codex_personas.go @@ -82,10 +82,11 @@ func codexListedModel(catalog codexCatalog, key, model string) error { // and resolves the run-level default (FULLSEND_CODEX_SUBAGENT_MODEL, then // subagents.default, then codexDefaultSubagentModel), which Bootstrap sets as // agents.default_subagent_model. A nil entry is a tombstone and reads as -// absent; a key naming neither default nor a persona is an error, as on pi; -// every configured value is validated whichever position wins, and every +// absent; a key naming neither default nor a persona is an error, as on pi, +// carrying codexRoles's reason when the key names a skipped persona; every +// configured value is validated whichever position wins, and every // resolved model must be in catalog (ADR 0126). The returned slice is a copy. -func resolveCodexChildModels(roles []codexRole, subagents map[string]*string, envValue string, catalog codexCatalog) ([]codexRole, string, error) { +func resolveCodexChildModels(roles []codexRole, skipped map[string]string, subagents map[string]*string, envValue string, catalog codexCatalog) ([]codexRole, string, error) { persona := make(map[string]bool, len(roles)) for _, role := range roles { if !slices.Contains(config.ReservedSubagentKeys(), role.Name) { @@ -105,6 +106,9 @@ func resolveCodexChildModels(roles []codexRole, subagents map[string]*string, en return nil, "", fmt.Errorf("subagents.%s: %q is a built-in role, not a persona; it runs on the run-level child model; registered personas: %s", key, key, discovered) } + if reason, ok := skipped[key]; ok { + return nil, "", fmt.Errorf("subagents.%s: persona %q was not registered: %s", key, key, reason) + } return nil, "", fmt.Errorf("subagents.%s: no persona %q is registered; registered personas: %s", key, key, discovered) } @@ -198,13 +202,17 @@ const ( // discoverPersonas registered, plus the two built-ins, sorted by name. A // persona that cannot become a role is skipped with a warning and never // fails Bootstrap: a stray sub-agents/*.md must not stop a run that never -// dispatches it, the rule discoverPersonas already applies. -func codexRoles(skillDirs []string, agentName string) []codexRole { +// 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) { // discoverPersonas never returns a non-nil error; the value exists for // the pi call site's shape. personas, skipped, _ := discoverPersonas(skillDirs, agentName) + reasons := make(map[string]string, len(skipped)) for _, sk := range skipped { fmt.Fprintf(os.Stderr, "Warning: persona %q skipped: %s\n", sk.Path, sk.Reason) + reasons[sk.Name] = sk.Path + ": " + sk.Reason } roles := []codexRole{ {Name: "default", Description: codexDefaultRoleDescription, Instructions: codexChildNote + codexDefaultRoleInstructions}, @@ -222,6 +230,7 @@ func codexRoles(skillDirs []string, agentName string) []codexRole { } if reason != "" { fmt.Fprintf(os.Stderr, "Warning: persona %q skipped: %s\n", p.Name, reason) + reasons[p.Name] = reason continue } if keys := codexDroppedFrontmatterKeys(p.Frontmatter); len(keys) > 0 { @@ -232,7 +241,7 @@ func codexRoles(skillDirs []string, agentName string) []codexRole { roles = append(roles, codexRole{Name: p.Name, Description: p.Description, Instructions: codexChildNote + p.Body + "\n"}) } slices.SortFunc(roles, func(a, b codexRole) int { return strings.Compare(a.Name, b.Name) }) - return roles + return roles, reasons } // codexDroppedPersonaKeys are the Claude-specific frontmatter keys a role diff --git a/internal/runtime/codex_personas_test.go b/internal/runtime/codex_personas_test.go index 8bbe08ab5f..0f185ecef3 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") 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") 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{ @@ -169,9 +169,12 @@ func TestCodexRoles_DiscoverySkipIsAWarning(t *testing.T) { writePersonaFile(t, skill, "Bad", "---\nname: Bad\ndescription: Bad shape.\n---\nbody\n") var roles []codexRole - out := captureStderr(t, func() { roles = codexRoles([]string{skill}, "review") }) + var skipped map[string]string + out := captureStderr(t, func() { roles, skipped = codexRoles([]string{skill}, "review") }) assert.Equal(t, []string{"default", "explore"}, codexRoleNames(roles)) + assert.Equal(t, filepath.Join(skill, "sub-agents", "default.md")+": name is reserved", skipped["default"], + "a discovery skip is recorded with its file, for the subagents key error") assert.Contains(t, out, fmt.Sprintf("Warning: persona %q skipped: name is reserved", filepath.Join(skill, "sub-agents", "default.md"))) assert.Contains(t, out, fmt.Sprintf("Warning: persona %q skipped: name must be lowercase alphanumeric", filepath.Join(skill, "sub-agents", "Bad.md"))) } @@ -208,10 +211,13 @@ func TestCodexRoles_SkipsInvalidPersonas(t *testing.T) { writePersonaFile(t, skill, tt.file, tt.content) var roles []codexRole - out := captureStderr(t, func() { roles = codexRoles([]string{skill}, "review") }) + var skipped map[string]string + out := captureStderr(t, func() { roles, skipped = codexRoles([]string{skill}, "review") }) assert.Equal(t, []string{"default", "explore"}, codexRoleNames(roles)) assert.Contains(t, out, tt.wantWarn) + require.Contains(t, skipped, tt.file) + assert.Contains(t, out, fmt.Sprintf("persona %q skipped: %s\n", tt.file, skipped[tt.file]), "the recorded reason is the warned one") }) } } @@ -225,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") }) 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) @@ -243,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") }) 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") @@ -322,7 +328,8 @@ func TestCodexRole_TOMLParsesWithTheThreeKeys(t *testing.T) { skill := t.TempDir() writePersonaFile(t, skill, "correctness", codexTestPersona) - for _, role := range codexRoles([]string{skill}, "review") { + roles, _ := codexRoles([]string{skill}, "review") + for _, role := range roles { doc := codexDecodeTOML(t, role.toml()) assert.Len(t, doc, 3, "%s: name, description, developer_instructions and nothing else", role.Name) assert.Equal(t, role.Name, doc["name"]) @@ -511,7 +518,7 @@ func TestResolveCodexChildModels_Precedence(t *testing.T) { cfg["correctness"] = nil } - got, gotDefault, err := resolveCodexChildModels(roles, cfg, tt.env, codexTestCatalog()) + got, gotDefault, err := resolveCodexChildModels(roles, nil, cfg, tt.env, codexTestCatalog()) require.NoError(t, err) require.Len(t, got, 3) assert.Equal(t, tt.wantModel, got[0].Model, "correctness") @@ -534,11 +541,14 @@ func TestResolveCodexChildModels_RejectsUnknownKeys(t *testing.T) { t.Parallel() roles := []codexRole{{Name: "correctness"}, {Name: "default"}, {Name: "explore"}} + worker := map[string]string{"worker": "name is reserved on codex (enabled, explorer, worker)"} tests := []struct { name string roles []codexRole + skipped map[string]string cfg map[string]*string wantErr []string + notErr string }{ {name: "explore is reserved", roles: roles, cfg: map[string]*string{"explore": strp("openai/gpt-5.6-sol")}, wantErr: []string{"subagents.explore", "built-in role", "correctness"}}, @@ -548,11 +558,26 @@ func TestResolveCodexChildModels_RejectsUnknownKeys(t *testing.T) { wantErr: []string{"subagents.correctness", "none"}}, {name: "a tombstoned unknown key is skipped", roles: roles, cfg: map[string]*string{"correctnes": nil}}, {name: "default is not a persona key error", roles: nil, cfg: map[string]*string{"default": strp("openai/gpt-5.6-sol")}}, + {name: "a skipped persona's key carries the reason", roles: roles, skipped: worker, + cfg: map[string]*string{"worker": strp("openai/gpt-5.6-sol")}, + wantErr: []string{`subagents.worker: persona "worker" was not registered: name is reserved on codex (enabled, explorer, worker)`}, + notErr: "registered personas"}, + {name: "a skipped persona is named only when the key matches it", roles: roles, skipped: worker, + cfg: map[string]*string{"correctnes": strp("openai/gpt-5.6-sol")}, + wantErr: []string{`no persona "correctnes" is registered`}, notErr: "worker"}, + {name: "explore stays a built-in role over a skipped explore.md", roles: roles, + skipped: map[string]string{"explore": "/s/sub-agents/explore.md: name is reserved"}, + cfg: map[string]*string{"explore": strp("openai/gpt-5.6-sol")}, + wantErr: []string{"subagents.explore", "built-in role"}, notErr: "was not registered"}, + {name: "a tombstoned skipped key is skipped", roles: roles, skipped: worker, cfg: map[string]*string{"worker": nil}}, + {name: "a duplicate skipped in a later skill does not hide the registered persona", roles: roles, + skipped: map[string]string{"correctness": `/b/sub-agents/correctness.md: name already declared by skill "a"`}, + cfg: map[string]*string{"correctness": strp("openai/gpt-5.6-sol")}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - _, _, err := resolveCodexChildModels(tt.roles, tt.cfg, "", codexTestCatalog()) + _, _, err := resolveCodexChildModels(tt.roles, tt.skipped, tt.cfg, "", codexTestCatalog()) if len(tt.wantErr) == 0 { assert.NoError(t, err) return @@ -561,6 +586,9 @@ func TestResolveCodexChildModels_RejectsUnknownKeys(t *testing.T) { for _, w := range tt.wantErr { assert.Contains(t, err.Error(), w) } + if tt.notErr != "" { + assert.NotContains(t, err.Error(), tt.notErr) + } }) } } @@ -588,7 +616,7 @@ func TestResolveCodexChildModels_NonOpenAIValueNamesTheKey(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - _, _, err := resolveCodexChildModels(roles, tt.cfg, tt.env, codexTestCatalog()) + _, _, err := resolveCodexChildModels(roles, nil, tt.cfg, tt.env, codexTestCatalog()) require.Error(t, err) for _, w := range tt.wantErr { assert.Contains(t, err.Error(), w) @@ -627,7 +655,7 @@ func TestResolveCodexChildModels_CatalogMembership(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - _, _, err := resolveCodexChildModels(roles, tt.subagents, tt.env, tt.catalog) + _, _, err := resolveCodexChildModels(roles, nil, tt.subagents, tt.env, tt.catalog) if tt.wantErr == "" { require.NoError(t, err) return From adffa7d6ffedb6dd85ff1debc0332917d20dfcd6 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 27 Oct 2026 09:44:27 -0400 Subject: [PATCH 07/15] docs(codex): link native Codex children from the runtime guide The codex row now links the term to the Sub-agents section, as the runtimes page already does. Signed-off-by: Dharit Shah --- docs/guides/getting-started/choosing-a-runtime.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/guides/getting-started/choosing-a-runtime.md b/docs/guides/getting-started/choosing-a-runtime.md index 0863acfacb..8b1a94c3a9 100644 --- a/docs/guides/getting-started/choosing-a-runtime.md +++ b/docs/guides/getting-started/choosing-a-runtime.md @@ -16,7 +16,7 @@ Fullsend supports multiple agent runtimes. A runtime is the program that runs in |---------|--------|-------------|-------------| | `claude` | **Stable (default)** | Claude Code on Vertex AI | Every production deployment — mature, full sub-agent support for `review`/`retro` | | `pi` | Experimental (enablement phase) | [Pi](https://github.com/earendil-works/pi) — Claude on Vertex by default; any provider pi supports by model name (e.g. Gemini on Vertex with the same credentials) | Opt-in pilots only; see [Runtimes](../../runtimes.md) for known constraints | -| `codex` | Experimental | [Codex](https://github.com/openai/codex) — OpenAI models through the same secretless credential path, or any Responses-capable model through an inference gateway (`gateway/`) | Opt-in pilots only, when you want GPT specifically. Sub-agents run as native Codex children, not yet verified fleet-wide, so keeping `review`/`retro` on Claude Code is recommended; needs an OpenAI or `gateway/` model named (`FULLSEND_CODEX_MODEL`) because the fleet harnesses ask for `opus`; see [Codex](../../runtimes/codex.md) | +| `codex` | Experimental | [Codex](https://github.com/openai/codex) — OpenAI models through the same secretless credential path, or any Responses-capable model through an inference gateway (`gateway/`) | Opt-in pilots only, when you want GPT specifically. Sub-agents run as [native Codex children](../../runtimes/codex.md#sub-agents), not yet verified fleet-wide, so keeping `review`/`retro` on Claude Code is recommended; needs an OpenAI or `gateway/` model named (`FULLSEND_CODEX_MODEL`) because the fleet harnesses ask for `opus`; see [Codex](../../runtimes/codex.md) | | `opencode` | Experimental | [OpenCode](https://opencode.ai/) — reads `AGENTS.md` natively | Opt-in read-only agents (`triage`, `prioritize`) until the security-hook adapter lands; see [OpenCode](../../runtimes/opencode.md) | ## When and how the runtime is selected From 44d182ce56a0422b1360afd7e16972047b290670 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 27 Oct 2026 11:10:15 -0400 Subject: [PATCH 08/15] fix(codex): keep explore children apart from default in transcript names Child transcripts mapped every reserved role to generic, so an explore child, which the dispatch note now offers, was saved like an unnamed default child, and the codex page said generic means default only. Only default now maps to generic; explore keeps its name. The naming test covers an explore child, and the Artifacts row says so. Signed-off-by: Dharit Shah --- docs/runtimes/codex.md | 2 +- internal/runtime/codex_transcript.go | 13 +++++++------ internal/runtime/codex_transcript_test.go | 4 +++- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/docs/runtimes/codex.md b/docs/runtimes/codex.md index dd7884221f..014c9005c5 100644 --- a/docs/runtimes/codex.md +++ b/docs/runtimes/codex.md @@ -207,7 +207,7 @@ collaboration V1, running in one context`), and the agent runs in one context. |---|---| | 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 a spawn that named no `agent_type`: the `default` role, which codex records as no role), `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 | +| 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`, on a parent model Codex resolves to collaboration V1, under a runner-owned policy: registered roles only, fresh context, depth one, four open; 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; 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 (see [Sub-agents](#sub-agents)) | diff --git a/internal/runtime/codex_transcript.go b/internal/runtime/codex_transcript.go index c2bcde47c9..4ca4b300d5 100644 --- a/internal/runtime/codex_transcript.go +++ b/internal/runtime/codex_transcript.go @@ -23,7 +23,7 @@ import ( // thread's (its session_meta names a parent_thread_id) as // -sub-.jsonl, where seq counts the kept child // rollouts in ascending basename order and role is the child's agent_role -// when it is a legal persona name, else codexGenericRole. +// when it is a legal persona name or explore, else codexGenericRole. // // Only `.jsonl` is collected. codex writes the running session's rollout // uncompressed and compresses older ones in place @@ -121,13 +121,14 @@ func (r CodexRuntime) ExtractTranscripts(sandboxName, agentLabel, outputDir stri continue } // A rollout whose first line names a parent thread is a child's. Its - // role enters the file name only as a legal persona name that the - // redactor leaves alone; anything else is codexGenericRole. The child - // name gets the same os.Root check as the root's. + // role enters the file name only as a legal persona name or explore + // that the redactor leaves alone; default and anything else is + // codexGenericRole. The child name gets the same os.Root check as + // the root's. isChild := false if meta, metaErr := codexReadSessionMeta(stagePath); metaErr == nil && meta.ParentThreadID != "" { role := meta.AgentRole - if !config.ValidSubagentKey(role) || slices.Contains(config.ReservedSubagentKeys(), role) || redactSummary(role) != role { + if role == "default" || !config.ValidSubagentKey(role) || redactSummary(role) != role { role = codexGenericRole } childName := codexChildTranscriptName(agentLabel, children+1, role) @@ -214,7 +215,7 @@ func codexValidSessionPath(sessionsDir, path string) error { } // codexGenericRole names a child transcript whose rollout carries no usable -// role: null, reserved, not a legal persona name, or credential-shaped. +// role: null, default, not a legal persona name, or credential-shaped. const codexGenericRole = "generic" // codexChildTranscriptName renders -sub-.jsonl, the diff --git a/internal/runtime/codex_transcript_test.go b/internal/runtime/codex_transcript_test.go index f77e91e606..d780147421 100644 --- a/internal/runtime/codex_transcript_test.go +++ b/internal/runtime/codex_transcript_test.go @@ -743,6 +743,7 @@ func TestCodexExtractTranscripts_NamesChildrenByRole(t *testing.T) { {day + "rollout-2026-09-29T15-46-48-0006.jsonl", "not a rollout\n"}, {day + "rollout-2026-09-29T15-46-50-0007.jsonl", child("0007", `"default"`)}, // reserved name {day + "rollout-2026-09-29T15-46-52-0008.jsonl", child("0008", `"sk-abcdefghijklmnopqrstuvwxyz"`)}, // credential-shaped + {day + "rollout-2026-09-29T15-46-54-0009.jsonl", child("0009", `"explore"`)}, // built-in, kept apart from default // A crafted basename equal to a child name, listed after that child // was saved: skipped, so the saved transcript is not truncated. {day + "sub1-correctness.jsonl", meta(`"id":"planted"`)}, @@ -766,8 +767,9 @@ func TestCodexExtractTranscripts_NamesChildrenByRole(t *testing.T) { "review-rollout-2026-09-29T15-46-46-0005.jsonl", "review-sub5-generic.jsonl", "review-sub6-generic.jsonl", + "review-sub7-explore.jsonl", }, names, "the root keeps its basename; children are numbered in basename order and named by their validated role, generic otherwise") - assert.Equal(t, 9, strings.Count(readFileString(t, logPath), " download "), + assert.Equal(t, 10, strings.Count(readFileString(t, logPath), " download "), "every listed rollout is fetched, except one whose name was already saved; naming happens after validation, not before the download") got, err := os.ReadFile(filepath.Join(outDir, "review-sub1-correctness.jsonl")) From 8a079a02705155eb205f252924cf49b815a78fc8 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 27 Oct 2026 16:00:30 -0400 Subject: [PATCH 09/15] fix(codex): keep children off a gateway parent and fail on a lost spawn A gateway/ parent whose id the catalog lists as V1 delegated, though children would inherit the gateway provider with bare OpenAI ids it may not serve, and native children have never run on that route. The gate now declines any gateway/ parent before the catalog lookup and says so on one stderr line; the V2 line is unchanged. A dropped stream notification only warned, so a spawn_agent item it lost stayed out of the admission count and an unadmitted spawn could balance it: exec's backfill re-emits only items it saw start. A delegating run now fails on any drop, a failed backfill, or a --debug log the runner could not read, which no longer reads as a zero count. A run without roles still warns. The codex page says the GitHub fleet workflows do not pass FULLSEND_CODEX_SUBAGENT_MODEL (subagents.default is the fleet knob), that code and fix delegate, and that the gateway route has no native children. Signed-off-by: Dharit Shah --- docs/architecture.md | 2 +- docs/contributing/runtime-implementation.md | 11 ++-- docs/runtimes.md | 2 +- docs/runtimes/codex.md | 51 ++++++++++++---- internal/runtime/codex_bootstrap.go | 8 +-- internal/runtime/codex_bootstrap_test.go | 9 +-- internal/runtime/codex_personas.go | 24 +++++--- internal/runtime/codex_personas_test.go | 8 ++- internal/runtime/codex_run.go | 16 +++-- internal/runtime/codex_subagents.go | 26 ++++---- internal/runtime/codex_subagents_test.go | 68 ++++++++++++++++++--- 11 files changed, 163 insertions(+), 62 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 1bf849e998..27e5e8da91 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -308,7 +308,7 @@ flowchart TB - The `fullsend run` runner delegates in-sandbox agent execution to a `runtime.Runtime` interface; production orgs default to Claude Code, with [pi](https://github.com/earendil-works/pi) available as an opt-in second runtime (`runtime: pi`, Claude-on-Vertex through the same WIF credential path), [codex](https://github.com/openai/codex) as a third (`runtime: codex`, OpenAI models through a custom model provider whose bearer token comes from a runner-seeded file, or `gateway/` models through a runner-owned gateway provider ([ADR 0137](ADRs/0137-inference-gateway-credential-route.md)), with the sandbox tool hooks behind a translating adapter — [ADR 0099](ADRs/0099-codex-agent-runtime.md) and [ADR 0100](ADRs/0100-codex-sandbox-hooks.md)), and [OpenCode](https://github.com/anomalyco/opencode) as a fourth (`runtime: opencode`, Claude-on-Vertex through the same WIF credential path; read-only agents only until the security-hook plugin adapter in [unbound-force#515](https://github.com/unbound-force/unbound-force/issues/515) lands). Runtime selection is configured per repo with `runtime:` in `.fullsend/config.yaml` (per-agent `runtime`/`model`/`effort`/`subagents` on the agent's `agents:` entry sit above it and below the `--runtime`/`--model`/`--effort` flags and `FULLSEND_*` variables, [ADR 0091](ADRs/0091-per-agent-runtime-model-effort.md)) and resolved via `runtime.ResolveForAgent()`. Test-only runtimes — **dummy** (scripted operations) and **dummy-playback** (playlist-based replay of canned results) — execute in the real OpenShell sandbox for behaviour tests without inference. Bootstrap uses a portable `BootstrapInput` interface with optional extensions such as `SandboxHooksBootstrap` for the runtime-neutral sandbox tool hooks ([ADR 0090](ADRs/0090-runtime-neutral-sandbox-hooks-contract.md)); runtimes declare further capabilities through small optional interfaces (`DebugLogNamer`, `ContextBridger`) rather than `Name()` checks in the runner. Transcript and debug artifact handling use a separate `TranscriptHandler` interface. See [runtimes.md](runtimes.md) for the per-runtime security feature matrix required when adding a new backend. - Harness `overlays:` ([ADR 0088](ADRs/0088-cel-guarded-overlays.md)) will be able to set any harness field except `base`, `trigger`, `overlays`, `slug`, `role` and `forge`; an overlay that sets a guarded field (any field except `model`, `effort`, `description` and `doc`) may read only trusted event and entity fields, `runtime.forge` and `config`, and every run will record an overlay resolution trace in the plan output and a dedicated span ([ADR 0112](ADRs/0112-overlays-may-set-any-harness-field.md)). Per-task model routing is overlays setting `model` and `effort`, and when a routed model isn't served the runner retries once with the model and effort the run would use without overlays, and `FULLSEND_FALLBACK_MODELS` applies as each runtime allows. 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)). -- Native Codex children run under a runner-owned policy: Bootstrap registers roles for an agent with the `Agent` tool, under harness security, whose parent model Codex resolves to collaboration V1 (a V2 or unlisted parent keeps the multi-agent tools off), and binds each child's model (a persona's own entry in its role file, the run-level default otherwise), and a mandatory dispatch hook admits only fresh-context V1 spawns of registered roles after checking `hooks.json` and the role files against runner-held digests ([ADR 0126](ADRs/0126-fullsend-owned-codex-subagents.md), [#6970](https://github.com/fullsend-ai/fullsend/issues/6970)). +- Native Codex children run under a runner-owned policy: Bootstrap registers roles for an agent with the `Agent` tool, under harness security, whose parent model Codex resolves to collaboration V1 on the direct route (a V2, unlisted or `gateway/` parent keeps the multi-agent tools off), and binds each child's model (a persona's own entry in its role file, the run-level default otherwise), and a mandatory dispatch hook admits only fresh-context V1 spawns of registered roles after checking `hooks.json` and the role files against runner-held digests ([ADR 0126](ADRs/0126-fullsend-owned-codex-subagents.md), [#6970](https://github.com/fullsend-ai/fullsend/issues/6970)). ### Behaviour testing diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 11124c348c..842d0d3829 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -1356,11 +1356,12 @@ notification under backpressure and says so on stderr: the launch sets `RUST_LOG `.env` (codex's default filter with `codex_exec` and `codex_app_server::in_process` at warn; codex's commands inherit it), the runner scans that stderr on the host (the sandbox log under `--debug`) and warns on the line, and on exec's warning that its `thread/read` backfill of the turn's items -failed. The check cannot catch a forged admission (the log is agent-writable), a surplus admission -covering a later spawn (counts, not ids), a resume (a `wait` item in the stream), or a spawn both -of whose notifications codex dropped, or whose dropped completed item the backfill did not bring -back (it runs only for a completed turn on a non-ephemeral thread, and only when `thread/read` -succeeds). +failed. The backfill at turn completion re-emits only items exec saw start, so a spawn both of whose +notifications codex dropped never reaches the count: a delegating run therefore fails on any drop, +on that backfill warning, or under `--debug` on a log read that did not finish; a run without roles +warns. The check cannot catch a forged admission (the log is agent-writable), a surplus admission +covering a later spawn (counts, not ids), a resume (a `wait` item in the stream), or, under +`--debug`, a drop whose line the agent removed from `codex-debug.log` (it sits in the workspace). **PATH is pinned across `.env` for the same reason the interpreter is.** The hook scripts resolve their tools by name — `tirith_check.py` runs a bare `tirith` — so a `.env` that prepends a directory diff --git a/docs/runtimes.md b/docs/runtimes.md index 63a175a068..e9e239fb9f 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`, on a parent model Codex resolves to collaboration V1 ([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`, on a parent model Codex resolves to collaboration V1 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 014c9005c5..faf8a218cf 100644 --- a/docs/runtimes/codex.md +++ b/docs/runtimes/codex.md @@ -130,6 +130,9 @@ own log. **Check the effort level against the model.** Effort is passed to the gateway as is, and some models refuse some levels with an upstream 400. Check the levels your model accepts before you set `effort`. +**No native sub-agents.** A `gateway/` parent keeps Codex's multi-agent tools off and runs in one +context, whatever its id (see [Sub-agents](#sub-agents)). + ### Child models A native child (see [Sub-agents](#sub-agents)) runs on the first of these that is set: @@ -142,8 +145,9 @@ A native child (see [Sub-agents](#sub-agents)) runs on the first of these that i Positions 2 to 4 set Codex's `agents.default_subagent_model`, which every child without its own entry takes — the personas without an entry and the unnamed children of `retro` alike. A persona's frontmatter `model:` is never applied on codex. Only OpenAI ids are accepted -(`openai/` or the bare id): a Claude alias, another provider's prefix, a `gateway/` spec (the -route is selected by the run's own model) or `inherit` fails Bootstrap and names the key: +(`openai/` or the bare id): a Claude alias, another provider's prefix, a `gateway/` spec (a +delegating run is always on the direct route; see [Sub-agents](#sub-agents)) or `inherit` fails +Bootstrap and names the key: ``` subagents.correctness: "xai-vertex/xai/grok-4.6" is not an OpenAI model id (openai/ or the bare @@ -160,8 +164,10 @@ does not serve still fails that child at its first request: it ends `errored`, n substituted, and the parent treats that role as failed. The floor is `gpt-5.6-luna`, the cheap tier of the current family, whose catalog entry selects collaboration V1 on the pinned CLI (see [Sub-agents](#sub-agents)). The runner reads `FULLSEND_CODEX_SUBAGENT_MODEL` from its own -environment: a fleet workflow sets it in the job environment (plain or `_`-prefixed); unlike -`FULLSEND_CODEX_MODEL` it is not read from repository variables. A child's reasoning effort follows +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 +path set `subagents.default` instead. A child's reasoning effort follows the run-level default model's standard effort. Bootstrap prints what it resolved: ``` @@ -173,7 +179,7 @@ subagents: correctness → gpt-5.6-sol (from subagents.correctness) 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 (see the end of this section). Bootstrap registers +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 `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: @@ -200,6 +206,11 @@ catalog does not list included, it keeps Codex's multi-agent tools off, prints one line saying why (`sub-agents: parent model "gpt-5.6-sol" selects collaboration "v2"; native sub-agents need a parent Codex resolves to collaboration V1, running in one context`), and the agent runs in one context. +A `gateway/` parent runs in one context the same way, whatever its id +(`sub-agents: parent model "gateway/gpt-5.6-luna" takes the inference gateway +route, where native sub-agents are not supported, running in one context`): +children would inherit the gateway provider with bare OpenAI ids it may not +serve, and native children have not been run on that route. ## At a glance @@ -208,9 +219,9 @@ collaboration V1, running in one context`), and the agent runs in one context. | 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`, on a parent model Codex resolves to collaboration V1, under a runner-owned policy: registered roles only, fresh context, depth one, four open; 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; 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 (see [Sub-agents](#sub-agents)) | +| Sub-agents | Native Codex children for an agent whose tools include `Agent`, 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) | +| 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 or from a `gateway/` parent (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`. @@ -386,6 +397,11 @@ agents: runtime: claude ``` +**`code` and `fix` delegate too.** They declare no `tools:`, so on a V1 parent 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. Neither has been run with native children +yet. + ## Troubleshooting **``codex preflight: `codex --version` exited 127``, or @@ -461,7 +477,8 @@ as the same user as those files, so "did the agent write there?" is the question **A spawn failed the admission check.** After an iteration whose `exec --json` stream reported a completed `spawn_agent`, the runner compares the run's completed spawns with the spawn guard's `codex_spawn_guard_admit` lines in `/sandbox/workspace/.security/findings.jsonl`, and the run fails -whatever codex's exit code. Each message says why: +whatever codex's exit code. The overlong-item and dropped-notification messages below come before +that comparison, whether or not the stream shows a spawn. Each message says why: ``` codex_spawn_without_admission: 3 completed spawn(s) in this run's stream(s) but 2 recorded admission(s) @@ -486,14 +503,24 @@ reading the spawn admissions: ... ``` The findings log could not be read (the command failed or timed out), so the check could not be made. +``` +codex_spawn_without_admission: codex dropped a stream notification, or its backfill of the turn's items failed or could not be checked, so a lost spawn_agent item cannot be ruled out +``` +A delegating agent's run in which codex dropped an item notification under backpressure, its +re-read of the turn's items failed (`thread/read failed while backfilling turn items` on stderr), +or, under `--debug`, the runner could not read codex's log to find out. The re-read brings back only +items codex saw start, so a spawn that lost both its notifications stays out of the stream's count, +and an unadmitted spawn could balance it; the run fails rather than pass the check on a short +count. Re-run. **`codex dropped N stream notification(s) under backpressure; the progress log is incomplete`.** -A warning: codex's in-process channel filled and it dropped an item notification, which it says on +A warning, and for a delegating agent the run then fails: codex's in-process channel filled and it dropped an item notification, which it says on stderr; the runner reads codex's stderr for that line on every run (under `--debug` the sandbox log instead). A dropped completed item comes back when the turn completes, if exec's read of the turn's items succeeds; when that read fails codex says so too, and the warning adds `and its backfill of -the turn's items failed`. A spawn that lost both its notifications, or whose backfill failed, is -not counted, and the count cannot tell those from a harmless drop. The launch sets `RUST_LOG` +the turn's items failed`. A spawn that lost both its notifications does not come back, so a +delegating agent's run fails on any drop (above); an agent without roles only gets the warning. The +launch sets `RUST_LOG` itself, codex's default filter with `codex_exec` and `codex_app_server::in_process` at warn (`info` under `--debug`), replacing any value from the environment or `.env`. diff --git a/internal/runtime/codex_bootstrap.go b/internal/runtime/codex_bootstrap.go index e319f7bac5..f6677cb0f2 100644 --- a/internal/runtime/codex_bootstrap.go +++ b/internal/runtime/codex_bootstrap.go @@ -158,9 +158,9 @@ func (r CodexRuntime) Bootstrap(input BootstrapInput) error { // on. Part two needs the pinned CLI's catalog: codex must resolve the // model Run will launch to collaboration V1, the only version whose spawn // tool the guard admits (its entry selects V1, or carries no version and - // codex's multi_agent feature, on by default, supplies V1). A V2 or - // unlisted parent keeps the multi-agent tools off and runs in one context, - // as every agent does today. + // codex's multi_agent feature, on by default, supplies V1). A V2, + // unlisted or gateway/ parent keeps the multi-agent tools off and runs in + // one context, as every agent does today. _, securityOn := input.(SandboxHooksBootstrap) var catalog codexCatalog delegating := false @@ -170,7 +170,7 @@ func (r CodexRuntime) Bootstrap(input BootstrapInput) error { } var reason string if delegating, reason = codexParentResolvesV1(catalog, input.ParentModel(), def.Model); !delegating { - fmt.Fprintf(os.Stderr, "sub-agents: %s; native sub-agents need a parent Codex resolves to collaboration V1, running in one context\n", reason) + fmt.Fprintf(os.Stderr, "sub-agents: %s, running in one context\n", reason) } } // Resolved before config.toml is written: a bad subagents value fails here. diff --git a/internal/runtime/codex_bootstrap_test.go b/internal/runtime/codex_bootstrap_test.go index bac0d289a9..232717978e 100644 --- a/internal/runtime/codex_bootstrap_test.go +++ b/internal/runtime/codex_bootstrap_test.go @@ -976,9 +976,10 @@ 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"`}, - "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"`}, + "security on, definition model selects V2": {delegating(v2Def, ""), true, false, `parent model "gpt-5.6-sol" selects collaboration "v2"; native sub-agents need a parent Codex resolves to collaboration V1`}, + "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; native sub-agents need a parent Codex resolves to collaboration V1`}, + "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"; native sub-agents need a parent Codex resolves to collaboration V1`}, + "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, ""}, } { t.Run(name, func(t *testing.T) { @@ -994,7 +995,7 @@ func TestCodexRuntimeBootstrap_NoRoleFilesWhenTheGateFails(t *testing.T) { wantLines := 0 if tc.reason != "" { wantLines = 1 - assert.Contains(t, out, "sub-agents: "+tc.reason+"; native sub-agents need a parent Codex resolves to collaboration V1") + assert.Contains(t, out, "sub-agents: "+tc.reason+", running in one context\n") } assert.Equal(t, wantLines, strings.Count(out, "sub-agents: "), "one stderr line exactly when part two of the gate declines") diff --git a/internal/runtime/codex_personas.go b/internal/runtime/codex_personas.go index 4dcc860b24..5c08849cdd 100644 --- a/internal/runtime/codex_personas.go +++ b/internal/runtime/codex_personas.go @@ -51,9 +51,10 @@ const codexDefaultSubagentModel = "gpt-5.6-luna" const codexSubagentModelEnv = "FULLSEND_CODEX_SUBAGENT_MODEL" // codexChildModel validates one configured child model and returns the bare -// OpenAI id: translateCodexModel's rules, less a gateway/ spec (the route is -// the run's own model's) and `inherit`, which codex does not resolve for a -// child. key names the entry so the error says what to fix. +// OpenAI id: translateCodexModel's rules, less a gateway/ spec (a delegating +// run is on the direct route: codexParentResolvesV1 declines a gateway/ +// parent) and `inherit`, which codex does not resolve for a child. key names +// the entry so the error says what to fix. func codexChildModel(key, value string) (string, error) { fix := "unset it so subagents.default or " + codexDefaultSubagentModel + " applies" if name, ok := strings.CutPrefix(key, "subagents."); ok { @@ -315,22 +316,25 @@ func parseCodexCatalog(data []byte) (codexCatalog, error) { // a V2 or unlisted parent, the reason is returned for one stderr line and // Bootstrap keeps codex's multi-agent tools off: the agent runs in one // context, as every agent does today. A parent that does not translate is -// reported by Run with the same error; the gate only declines here. The -// route is Run's concern too: the catalog is asked about the id whichever -// provider serves it, so a gateway/ parent is accepted here and declined -// by the catalog. +// 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 codexParentResolvesV1(catalog codexCatalog, parentModel, agentModel string) (bool, string) { + const needV1 = "; native sub-agents need a parent Codex resolves to collaboration V1" model, err := translateCodexModel(EffectiveModel(parentModel, agentModel), true) if err != nil { - return false, err.Error() + return false, err.Error() + needV1 } id := model.ID switch { + case model.Gateway: + return false, fmt.Sprintf("parent model %q takes the inference gateway route, where native sub-agents are not supported", "gateway/"+id) case !catalog.has(id): - return false, fmt.Sprintf("parent model %q is not in the bundled catalog of the pinned codex", id) + return false, fmt.Sprintf("parent model %q is not in the bundled catalog of the pinned codex", id) + needV1 case catalog.resolvesV1(id): return true, "" default: - return false, fmt.Sprintf("parent model %q selects collaboration %q", id, catalog[id]) + return false, fmt.Sprintf("parent model %q selects collaboration %q", id, catalog[id]) + needV1 } } diff --git a/internal/runtime/codex_personas_test.go b/internal/runtime/codex_personas_test.go index 0f185ecef3..bb58a83b97 100644 --- a/internal/runtime/codex_personas_test.go +++ b/internal/runtime/codex_personas_test.go @@ -380,7 +380,8 @@ func TestCodexCatalog(t *testing.T) { // Run will use (the run-level model, else the definition's) must translate to // an OpenAI id codex resolves to V1: its entry selects V1 or carries no // version (codex's multi_agent feature, on by default, supplies V1). A V2 or -// unlisted parent keeps the multi-agent tools off and says why in one line. +// unlisted parent keeps the multi-agent tools off and says why in one line, +// and so does a gateway/ parent whatever its id. func TestCodexParentResolvesV1(t *testing.T) { t.Parallel() catalog := codexCatalog{"gpt-5.6-luna": "v1", "gpt-5.6-sol": "v2", "gpt-5.5": "", "gpt-x": "v3"} @@ -397,7 +398,10 @@ func TestCodexParentResolvesV1(t *testing.T) { {"no multi-agent version (multi_agent supplies V1)", "", "gpt-5.5", true, ""}, {"unknown collaboration version", "", "openai/gpt-x", false, `parent model "gpt-x" selects collaboration "v3"`}, {"not in the catalog", "", "openai/gpt-5.6-nova", false, `parent model "gpt-5.6-nova" is not in the bundled catalog`}, - {"gateway route, the id is asked of the catalog", "", "gateway/vendor/org/model", false, `parent model "vendor/org/model" is not in the bundled catalog`}, + {"gateway route declines a listed V1 id", "", "gateway/gpt-5.6-luna", false, `parent model "gateway/gpt-5.6-luna" takes the inference gateway route`}, + {"gateway route declines before the catalog", "", "gateway/vendor/org/model", false, `parent model "gateway/vendor/org/model" takes the inference gateway route`}, + {"run-level OpenAI model beats a gateway definition", "openai/gpt-5.6-luna", "gateway/vendor/org/model", true, ""}, + {"run-level gateway route beats a V1 definition", "gateway/vendor/org/model", "openai/gpt-5.6-luna", false, `parent model "gateway/vendor/org/model" takes the inference gateway route`}, {"claude alias does not translate", "", "opus", false, "codex takes OpenAI model ids or gateway/ only"}, {"no model at all", "", "", false, "no model was named"}, } diff --git a/internal/runtime/codex_run.go b/internal/runtime/codex_run.go index 7a63a3d792..a19a85ea6d 100644 --- a/internal/runtime/codex_run.go +++ b/internal/runtime/codex_run.go @@ -657,10 +657,12 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri } childIDs.flush() stderr.flush() + dropsUnread := false if params.Debug != "" { // Under --debug codex's stderr went to the sandbox log instead. dropped, backfillFailed, derr := codexCountDroppedInLog(params.SandboxName) if derr != nil { + dropsUnread = true printer.StepWarn("Could not read codex's log for dropped stream notifications: " + redactSummary(sanitizeOutput(derr.Error()))) } stderr.Dropped += dropped @@ -701,10 +703,13 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri // Checked whatever the exit code: with a validation loop an iteration's // non-zero exit does not fail the run; an error from Run does, and a // failed read or an unread spawn item is one too, unlike the usage read - // above. A dropped stream notification can hide a completed spawn, but - // the count cannot tell one from a harmless drop (exec re-reads the - // turn's persisted items from the thread at turn/completed), so it stays - // a warning. + // above. A dropped stream notification can hide a completed spawn: exec's + // backfill at turn completion re-emits only items it saw start, so a + // spawn that lost both notifications, or whose backfill failed, stays out + // of the stream's count, and an unadmitted spawn could balance it. A + // delegating run therefore fails on any drop, a failed backfill, or a + // debug log the runner could not read; a run without roles has the + // multi-agent tools off and only warns. if stderr.Dropped > 0 { msg := fmt.Sprintf("codex dropped %d stream notification(s) under backpressure", stderr.Dropped) if stderr.BackfillFailed > 0 { @@ -712,6 +717,9 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri } printer.StepWarn(msg + "; the progress log is incomplete") } + if digests.delegating() && (stderr.Dropped > 0 || stderr.BackfillFailed > 0 || dropsUnread) { + return exitCode, fmt.Errorf("%s: codex dropped a stream notification, or its backfill of the turn's items failed or could not be checked, so a lost spawn_agent item cannot be ruled out", codexSpawnWithoutAdmission) + } if childIDs.UnreadSpawn { return exitCode, fmt.Errorf("%s: a spawn_agent item longer than %d bytes could not be read", codexSpawnWithoutAdmission, streamBufSize) } diff --git a/internal/runtime/codex_subagents.go b/internal/runtime/codex_subagents.go index 10ce774351..1110ddb545 100644 --- a/internal/runtime/codex_subagents.go +++ b/internal/runtime/codex_subagents.go @@ -243,15 +243,19 @@ func (c *codexStderrDrops) flush() { // codexCountDroppedInLog counts codexDroppedNotification and // codexBackfillFailed in the sandbox debug log, where codex's stderr goes // under --debug instead of the host. A log that is missing or has no such -// line counts zero. +// line counts zero; a command that did not finish (the script itself always +// exits 0) is an error, not a zero count. func codexCountDroppedInLog(sandboxName string) (dropped, backfillFailed int, err error) { log := shellQuote(sandbox.SandboxWorkspace + "/" + codexDebugLogFile) cmd := fmt.Sprintf(`command -p grep -a -c -F -e %s -- %s 2>/dev/null; command -p grep -a -c -F -e %s -- %s 2>/dev/null; true`, shellQuote(codexDroppedNotification), log, shellQuote(codexBackfillFailed), log) - stdout, _, _, err := sandbox.Exec(sandboxName, cmd, 10*time.Second) + stdout, stderr, exitCode, err := sandbox.Exec(sandboxName, cmd, 10*time.Second) if err != nil { return 0, 0, err } + if exitCode != 0 { + return 0, 0, fmt.Errorf("exited %d: %s", exitCode, redactSummary(strings.TrimSpace(sanitizeOutput(stderr)))) + } counts := strings.Fields(stdout) if len(counts) > 0 { dropped, _ = strconv.Atoi(counts[0]) @@ -404,16 +408,14 @@ func (r CodexRuntime) foldCodexChildUsage(sandboxName string, childIDs []string, // would have passed, never pass one that would have failed. The stream side // is not that strict: codex can drop an item notification under // backpressure, and the completed count is then too low; it says so on its -// stderr, which Run scans (codexStderrDrops) and warns on. A completed item -// codex saw start comes back when the turn completes, if exec's read of the -// turn's items succeeds; exec warns when it does not, and Run counts that -// line too. A spawn that lost both notifications, or whose dropped -// completed item that read did not bring back, is not counted, and the -// count cannot tell it from a harmless drop. A resume -// that got through appears in the stream -// as a wait item, so it is not caught either, nor is an overlong spawn line -// whose first bytes do not show its type and tool. Counts are compared, not -// ids: a stream item carries no tool_use_id. +// stderr, which Run scans (codexStderrDrops). exec's backfill at turn +// completion re-emits only items it saw start, and exec warns when that +// read fails, so a count after any drop or failed backfill cannot be +// trusted: a delegating run fails on either, and a run without roles warns. +// A resume that got through appears in the stream as a wait item, so it is +// not caught, nor is an overlong spawn line whose first bytes do not show +// its type and tool. Counts are compared, not ids: a stream item carries no +// tool_use_id. // codexSpawnAdmitFinding is the adapter's SPAWN_ADMIT_FINDING. const codexSpawnAdmitFinding = "codex_spawn_guard_admit" diff --git a/internal/runtime/codex_subagents_test.go b/internal/runtime/codex_subagents_test.go index 7a2e58b1ad..6bde902a62 100644 --- a/internal/runtime/codex_subagents_test.go +++ b/internal/runtime/codex_subagents_test.go @@ -367,7 +367,8 @@ func TestParseCodexStream_FailedCollabItem(t *testing.T) { // admissions read; FULLSEND_TEST_CODEX_EXIT sets the launch's exit status (killed: // SIGKILL, as the budget's context kill ends it); FULLSEND_TEST_CODEX_DROP=1 // prints codex's dropped-notification warning on stderr before the stream, -// FULLSEND_TEST_CODEX_BACKFILL_FAIL=1 exec's failed-backfill warning. +// FULLSEND_TEST_CODEX_BACKFILL_FAIL=1 exec's failed-backfill warning; +// FULLSEND_TEST_DEBUG_LOG_READ_FAIL=1 makes the debug-log read exit 1. func fakeOpenshellCodexChildren(t *testing.T, logPath, storeDir, streamFixture, sessionsDir string) { t.Helper() binDir := t.TempDir() @@ -389,6 +390,7 @@ if [ "$2" = "exec" ]; then if [ "${FULLSEND_TEST_ADMISSIONS_READ_FAIL:-}" = after ]; then exit 124; fi exit $rc ;; *` + codexDebugLogFile + `*) + if [ "${FULLSEND_TEST_DEBUG_LOG_READ_FAIL:-}" = 1 ]; then echo "fake openshell: refusing the log read" >&2; exit 1; fi sh -c "$(printf '%s' "$last" | sed 's#` + sandbox.SandboxWorkspace + "/" + codexDebugLogFile + `#` + filepath.Join(filepath.Dir(sessionsDir), codexDebugLogFile) + `#g')"; exit $? ;; esac exit 0 @@ -1171,19 +1173,43 @@ func TestCodexStderrDrops_CountsAcrossChunks(t *testing.T) { assert.Equal(t, 1, last.Dropped, "the last line is scanned once the stream has ended") } -// A dropped stream notification can hide a completed spawn. Nothing can -// spawn until the multi-agent tools are switched on, so the run warns and -// the cross-check runs on what the stream did carry. -func TestCodexRun_DroppedNotificationWarns(t *testing.T) { +// A dropped stream notification can hide a spawn exec's backfill does not +// bring back (one that lost both notifications): a run without roles warns +// and the cross-check runs on what the stream carried; a delegating run +// fails before it. +func TestCodexRun_DroppedNotificationFailsADelegatingRun(t *testing.T) { t.Setenv("FULLSEND_TEST_CODEX_DROP", "1") - _, exit, out, log := runCodexWithChildren(t, "collab_spawn.ndjson", true, 3) + _, exit, out, log := runCodexWithChildren(t, "collab_spawn.ndjson", false, 3) assert.Equal(t, 0, exit) assert.Contains(t, out, "! codex dropped 1 stream notification(s) under backpressure; the progress log is incomplete") assert.Equal(t, 1, strings.Count(log, codexSpawnAdmitFinding)) + _, _, out, log, err := tryCodexRunWithChildren(t, "collab_spawn.ndjson", true, 3) + require.Error(t, err) + assert.Contains(t, err.Error(), codexSpawnWithoutAdmission+": codex dropped a stream notification") + assert.Contains(t, out, "! codex dropped 1 stream notification(s) under backpressure", "the warning still says what codex reported") + assert.Zero(t, strings.Count(log, codexSpawnAdmitFinding), "the cross-check is not run on a count it cannot trust") +} + +// A failed backfill leaves a dropped spawn item lost, so the stream's count +// can be short and an unadmitted spawn balance it: a delegating run fails, +// with or without a drop line, and a run with no roles only warns. +func TestCodexRun_FailedBackfillFailsADelegatingRun(t *testing.T) { + t.Setenv("FULLSEND_TEST_CODEX_DROP", "1") t.Setenv("FULLSEND_TEST_CODEX_BACKFILL_FAIL", "1") - _, _, out, _ = runCodexWithChildren(t, "collab_spawn.ndjson", true, 3) + _, exit, out, _ := runCodexWithChildren(t, "collab_spawn.ndjson", false, 3) + assert.Equal(t, 0, exit) assert.Contains(t, out, "! codex dropped 1 stream notification(s) under backpressure, and its backfill of the turn's items failed, so a dropped completed item stayed lost; the progress log is incomplete") + + _, _, out, _, err := tryCodexRunWithChildren(t, "collab_spawn.ndjson", true, 3) + require.Error(t, err) + assert.Contains(t, err.Error(), codexSpawnWithoutAdmission+": codex dropped a stream notification, or its backfill of the turn's items failed or could not be checked") + assert.Contains(t, out, "and its backfill of the turn's items failed", "the warning still says what codex reported") + + t.Setenv("FULLSEND_TEST_CODEX_DROP", "") + _, _, _, _, err = tryCodexRunWithChildren(t, "collab_spawn.ndjson", true, 3) + require.Error(t, err, "a failed backfill alone fails it too") + assert.Contains(t, err.Error(), codexSpawnWithoutAdmission) } // Under --debug codex's stderr goes to the sandbox log, which is read back. @@ -1206,3 +1232,31 @@ func TestCodexRun_DroppedNotificationInTheDebugLog(t *testing.T) { assert.Contains(t, out.String(), "! codex dropped 1 stream notification(s) under backpressure, and its backfill of the turn's items failed") assert.Contains(t, readFileString(t, logPath), "grep -a -c -F", "the counts came from the sandbox log") } + +// Under --debug a log read that did not finish is no zero count: a run with +// no roles warns, and a delegating run fails, since a failed backfill cannot +// be ruled out. +func TestCodexRun_UnreadDebugLogFailsADelegatingRun(t *testing.T) { + t.Setenv("FULLSEND_TEST_DEBUG_LOG_READ_FAIL", "1") + storeDir := t.TempDir() + r := CodexRuntime{} + seedCodexManifest(t, storeDir, r, nil) + sessions := writeCodexChildRollouts(t) + fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), storeDir, filepath.Join("testdata", "codex", "basic_run.ndjson"), sessions) + params := codexChildrenRunParams + params.Debug = "1" + + var out bytes.Buffer + exit, err := r.Run(context.Background(), params, ui.New(&out), time.Now(), &RunMetrics{}) + require.NoError(t, err) + assert.Equal(t, 0, exit) + assert.Contains(t, out.String(), "! Could not read codex's log for dropped stream notifications: exited 1: fake openshell: refusing the log read") + + d, ok := lookupRunnerHeldDigests("sb") + require.True(t, ok) + d.RoleFiles = map[string]string{"default": "d0d0", "explore": "e0e0"} + recordRunnerHeldDigests("sb", d) + _, err = r.Run(context.Background(), params, ui.New(&out), time.Now(), &RunMetrics{}) + require.Error(t, err) + assert.Contains(t, err.Error(), codexSpawnWithoutAdmission+": codex dropped a stream notification, or its backfill of the turn's items failed or could not be checked") +} From b687fc579605bdb0fd1ad540dadf71f20bee7c53 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 27 Oct 2026 16:13:57 -0400 Subject: [PATCH 10/15] docs(codex): say code and fix ran with the roles registered Both ran end to end on gpt-5.6-luna with the default and explore roles, the spawn guard and the dispatch note, and spawned no child. Signed-off-by: Dharit Shah --- docs/runtimes/codex.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/runtimes/codex.md b/docs/runtimes/codex.md index faf8a218cf..c8889f2c39 100644 --- a/docs/runtimes/codex.md +++ b/docs/runtimes/codex.md @@ -399,8 +399,8 @@ agents: **`code` and `fix` delegate too.** They declare no `tools:`, so on a V1 parent 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. Neither has been run with native children -yet. +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. ## Troubleshooting From 4c0c0560d818a35512b32066ef7672a3fde95bc6 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Tue, 27 Oct 2026 21:49:40 -0400 Subject: [PATCH 11/15] fix(codex)!: bind the run's effort for children and count spawns on disk Children ran at the run-level child model's catalog default: codex resets a child's effort to it unless default_subagent_reasoning_effort is set, so the agent's effort was ignored for every child. Bootstrap now writes the run's effort there and checks it, as codex does at each spawn, against the run-level child model and every persona model in the bundled catalog, naming the position; with no run effort it checks the catalog default against the persona models. The admission check failed a delegating run on any dropped notification, which #8712 ruled out. It now counts, per iteration, the spawns seen in the stream (completed or failed items) or in the children's rollouts on disk, each child once by thread id, and folds usage for both, so a spawn the stream lost still counts. Drops, a failed backfill and an unread debug log are warnings again; the debug-log read keeps grep's status. The docs say the floor need only be listed, that the drop line covers any thread, and what the check cannot catch. BREAKING CHANGE: a delegating agent on runtime codex now fails Bootstrap when its effort is one a resolved child model does not support, naming the position that chose the model. At the pinned CLI the only case is effort max with gpt-5.5 as the run-level child model (subagents.default or FULLSEND_CODEX_SUBAGENT_MODEL) or as a persona's subagents entry; before, the run started and the agent did that work in one context. Set an effort every child model supports, or a child model that supports it. Signed-off-by: Dharit Shah --- docs/architecture.md | 2 +- docs/contributing/runtime-implementation.md | 50 +- docs/reference/config-reference.md | 5 +- docs/runtimes.md | 2 +- docs/runtimes/codex.md | 100 ++-- internal/cli/bootstrap_input.go | 3 + internal/cli/bootstrap_input_test.go | 14 + internal/cli/bootstrap_scan_test.go | 1 + internal/runtime/bootstrap.go | 5 + internal/runtime/claude_test.go | 2 + internal/runtime/codex_bootstrap.go | 10 +- internal/runtime/codex_bootstrap_test.go | 54 +++ internal/runtime/codex_config.go | 14 +- internal/runtime/codex_config_test.go | 35 +- internal/runtime/codex_golden_test.go | 12 +- internal/runtime/codex_integrity.go | 8 +- internal/runtime/codex_personas.go | 113 ++++- internal/runtime/codex_personas_test.go | 111 ++++- internal/runtime/codex_run.go | 45 +- internal/runtime/codex_run_test.go | 2 +- internal/runtime/codex_subagents.go | 209 +++++++-- internal/runtime/codex_subagents_test.go | 443 +++++++++++++++--- internal/runtime/dummy_test.go | 1 + internal/runtime/testdata/codex/README.md | 9 +- .../codex/models-bundled-0.159.3.json | 238 +++++++++- 25 files changed, 1233 insertions(+), 255 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 27e5e8da91..a023b8e1b4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -308,7 +308,7 @@ flowchart TB - The `fullsend run` runner delegates in-sandbox agent execution to a `runtime.Runtime` interface; production orgs default to Claude Code, with [pi](https://github.com/earendil-works/pi) available as an opt-in second runtime (`runtime: pi`, Claude-on-Vertex through the same WIF credential path), [codex](https://github.com/openai/codex) as a third (`runtime: codex`, OpenAI models through a custom model provider whose bearer token comes from a runner-seeded file, or `gateway/` models through a runner-owned gateway provider ([ADR 0137](ADRs/0137-inference-gateway-credential-route.md)), with the sandbox tool hooks behind a translating adapter — [ADR 0099](ADRs/0099-codex-agent-runtime.md) and [ADR 0100](ADRs/0100-codex-sandbox-hooks.md)), and [OpenCode](https://github.com/anomalyco/opencode) as a fourth (`runtime: opencode`, Claude-on-Vertex through the same WIF credential path; read-only agents only until the security-hook plugin adapter in [unbound-force#515](https://github.com/unbound-force/unbound-force/issues/515) lands). Runtime selection is configured per repo with `runtime:` in `.fullsend/config.yaml` (per-agent `runtime`/`model`/`effort`/`subagents` on the agent's `agents:` entry sit above it and below the `--runtime`/`--model`/`--effort` flags and `FULLSEND_*` variables, [ADR 0091](ADRs/0091-per-agent-runtime-model-effort.md)) and resolved via `runtime.ResolveForAgent()`. Test-only runtimes — **dummy** (scripted operations) and **dummy-playback** (playlist-based replay of canned results) — execute in the real OpenShell sandbox for behaviour tests without inference. Bootstrap uses a portable `BootstrapInput` interface with optional extensions such as `SandboxHooksBootstrap` for the runtime-neutral sandbox tool hooks ([ADR 0090](ADRs/0090-runtime-neutral-sandbox-hooks-contract.md)); runtimes declare further capabilities through small optional interfaces (`DebugLogNamer`, `ContextBridger`) rather than `Name()` checks in the runner. Transcript and debug artifact handling use a separate `TranscriptHandler` interface. See [runtimes.md](runtimes.md) for the per-runtime security feature matrix required when adding a new backend. - Harness `overlays:` ([ADR 0088](ADRs/0088-cel-guarded-overlays.md)) will be able to set any harness field except `base`, `trigger`, `overlays`, `slug`, `role` and `forge`; an overlay that sets a guarded field (any field except `model`, `effort`, `description` and `doc`) may read only trusted event and entity fields, `runtime.forge` and `config`, and every run will record an overlay resolution trace in the plan output and a dedicated span ([ADR 0112](ADRs/0112-overlays-may-set-any-harness-field.md)). Per-task model routing is overlays setting `model` and `effort`, and when a routed model isn't served the runner retries once with the model and effort the run would use without overlays, and `FULLSEND_FALLBACK_MODELS` applies as each runtime allows. 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)). -- Native Codex children run under a runner-owned policy: Bootstrap registers roles for an agent with the `Agent` tool, under harness security, whose parent model Codex resolves to collaboration V1 on the direct route (a V2, unlisted or `gateway/` parent keeps the multi-agent tools off), and binds each child's model (a persona's own entry in its role file, the run-level default otherwise), and a mandatory dispatch hook admits only fresh-context V1 spawns of registered roles after checking `hooks.json` and the role files against runner-held digests ([ADR 0126](ADRs/0126-fullsend-owned-codex-subagents.md), [#6970](https://github.com/fullsend-ai/fullsend/issues/6970)). +- Native Codex children run under a runner-owned policy: Bootstrap registers roles for an agent with the `Agent` tool, under harness security, whose parent model Codex resolves to collaboration V1 on the direct route (a V2, unlisted or `gateway/` parent keeps the multi-agent tools off), and binds each child's model (a persona's own entry in its role file, the run-level default otherwise) and the run's effort, and a mandatory dispatch hook admits only fresh-context V1 spawns of registered roles after checking `hooks.json` and the role files against runner-held digests; after each iteration the runner checks the spawns seen in the stream or in the children's rollouts on disk, each child once, against the hook's admissions ([ADR 0126](ADRs/0126-fullsend-owned-codex-subagents.md), [#6970](https://github.com/fullsend-ai/fullsend/issues/6970)). ### Behaviour testing diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 842d0d3829..1ba7177aca 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -1345,23 +1345,35 @@ file when a child starts, so Run exports their digests as `FULLSEND_CODEX_SPAWN_ handler re-hashes them, and lists `agents/`, before applying the policy, on its own deadline below the hook timeout at which codex kills a handler and lets the call through. No role, no spawn. -A handler codex kills at that timeout still lets the call through, so after each iteration the -runner cross-checks the stream's completed `spawn_agent` items, read on the host, against the -guard's `codex_spawn_guard_admit` lines in `/sandbox/workspace/.security/findings.jsonl` and fails -the run (`codex_spawn_without_admission`) on a shortfall, a spawn not sent by the primary thread, -a spawn item too long to read, or a failed read. The count spans the run's iterations, so -`ClearIterationArtifacts` must leave `.security/` in place (it clears `output/`, the sessions -directory and the debug log, nothing else under the workspace). Codex can drop a stream -notification under backpressure and says so on stderr: the launch sets `RUST_LOG` outright after -`.env` (codex's default filter with `codex_exec` and `codex_app_server::in_process` at warn; codex's -commands inherit it), the runner scans that stderr on the host (the sandbox log under `--debug`) -and warns on the line, and on exec's warning that its `thread/read` backfill of the turn's items -failed. The backfill at turn completion re-emits only items exec saw start, so a spawn both of whose -notifications codex dropped never reaches the count: a delegating run therefore fails on any drop, -on that backfill warning, or under `--debug` on a log read that did not finish; a run without roles -warns. The check cannot catch a forged admission (the log is agent-writable), a surplus admission -covering a later spawn (counts, not ids), a resume (a `wait` item in the stream), or, under -`--debug`, a drop whose line the agent removed from `codex-debug.log` (it sits in the workspace). +A handler codex kills at that timeout still lets the call through, so after each iteration of a +delegating agent (and any iteration whose stream shows a spawn) the runner counts the iteration's +spawns from two sources, each child once by thread id, and cross-checks the run's total against the +guard's `codex_spawn_guard_admit` lines in `/sandbox/workspace/.security/findings.jsonl`: the +stream's `spawn_agent` items, read on the host, completed or failed (a blocked spawn returns before +the handler and emits none, `core/src/tools/registry.rs`; a spawn refused at the thread limit fails +at `reserve_spawn_slot` after the guard admitted it and names no child), counted by their receiver +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 +not a `session_meta` record. 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. 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 +primary thread id with a child-shaped rollout present, or a failed read of either side. The count +spans the run's iterations, so `ClearIterationArtifacts` must leave `.security/` in place (it +clears `output/`, the sessions directory and the debug log, nothing else under the workspace). The +usage fold reads the union of the stream's children and the children on disk. Codex can drop a +stream notification under backpressure, of any thread, and says so on stderr: the launch sets +`RUST_LOG` outright after `.env` (codex's default filter with `codex_exec` and +`codex_app_server::in_process` at warn; codex's commands inherit it), and the runner scans that +stderr on the host (the sandbox log under `--debug`) and warns on the line and on exec's warning +that its `thread/read` backfill of the turn's items failed. Drops stay warnings (#8712): the +rollouts do not depend on the stream. The check cannot catch a forged admission (the log is +agent-writable), a resume (a `wait` item in the stream), a spawn hidden from both sides (stream +items lost and the rollout deleted or its `session_meta` edited), a child that never recorded an +item, or a surplus admission covering a later spawn (counts, not ids): codex can reject an admitted +call before it emits an item (`parse_collab_input` on a spawn with no message, or +`prepare_agent_spawn_config` after `item.started`), and another PreToolUse hook running beside the +guard can block a call the guard admitted. **PATH is pinned across `.env` for the same reason the interpreter is.** The hook scripts resolve their tools by name — `tirith_check.py` runs a bare `tirith` — so a `.env` that prepends a directory @@ -1529,4 +1541,6 @@ 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` | | 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`, 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` entries, the version codex supplies to an entry that carries none, and the floor model (`codex debug models --bundled`; at 0.159.3 `gpt-5.6-luna` is the listed model that selects `v1`, and `gpt-5.5` carries no version, which the `multi_agent` feature, on by default, resolves to V1) | part two of the delegation gate and the child-model floor rest on them: a bump that moves the floor to V2, or drops it, turns native sub-agents off for every agent; a bump that turns `multi_agent` off by default, or gives the null entry a version, changes which parents delegate; and the fixture `internal/runtime/testdata/codex/models-bundled-0.159.3.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\|TestCodexParentResolvesV1'` | +| 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.159.3 `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.159.3.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\|TestCodexParentResolvesV1\|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) | diff --git a/docs/reference/config-reference.md b/docs/reference/config-reference.md index e49ac16ff5..8fa3d58b77 100644 --- a/docs/reference/config-reference.md +++ b/docs/reference/config-reference.md @@ -194,8 +194,9 @@ effort, sub-agent models and the trigger. - **`subagents`** — Map of persona names to model references. The `default` key sets the fallback for personas without an explicit entry. A `~` (null) value tombstones an inherited entry. Keys must be lowercase alphanumeric - segments joined by hyphens (max 64 chars). On codex the values must be - OpenAI ids and a key must name a discovered persona or `default`; see + segments joined by hyphens (max 64 chars). On codex, for an agent that + delegates, the values must be OpenAI ids and a key must name a registered + persona or `default`; see [Codex › Child models](../runtimes/codex.md#child-models). - **`trigger`** — A [CEL trigger](../guides/user/cel-triggers-reference.md) (a boolean over the normalized `event`). It decides routing for the diff --git a/docs/runtimes.md b/docs/runtimes.md index e9e239fb9f..5236117037 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`, 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 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 c8889f2c39..b180ab66de 100644 --- a/docs/runtimes/codex.md +++ b/docs/runtimes/codex.md @@ -161,18 +161,28 @@ against the catalog bundled with the pinned Codex CLI (`codex debug models --bun in the sandbox) and fails naming the position that supplied an unlisted id: Codex itself checks a 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 tier -of the current family, whose catalog entry selects collaboration V1 on the pinned CLI (see -[Sub-agents](#sub-agents)). The runner reads `FULLSEND_CODEX_SUBAGENT_MODEL` from its own +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 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 -path set `subagents.default` instead. A child's reasoning effort follows -the run-level default model's standard effort. Bootstrap prints what it resolved: +path set `subagents.default` instead. + +Every child runs at the run's effort (`effort:`, an `agents:` entry or `--effort`) when one is set: +Bootstrap writes it as `agents.default_subagent_reasoning_effort`. Codex checks a child's effort +against its model at every spawn and refuses the spawn when the model lacks it, so Bootstrap checks +the effort against the run-level child model and every persona model in the bundled catalog and +fails naming the effort, the model and the position that chose it; at the pin only `max` on +`gpt-5.5` fails. With no run effort, codex resets every child to the run-level child model's +catalog default (`medium` for `gpt-5.6-luna`, `low` for `gpt-5.6-sol`), a persona with its own +model included, and Bootstrap checks that level against the persona models. pi children run at +`medium` unless `FULLSEND_PI_SUBAGENT_THINKING` says otherwise. Bootstrap prints what it resolved: ``` subagents: default → gpt-5.6-luna (from built-in default; children that name no persona and personas without an entry) subagents: correctness → gpt-5.6-sol (from subagents.correctness) +subagents: effort → high (from the run's effort; every child) ``` ## Sub-agents @@ -188,13 +198,15 @@ 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. -Each child starts with only 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: +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 -sub-agent definition itself. A spawn the hook did not admit fails the run after the fact: the -runner compares the spawns in the run's event stream with the admissions the hook recorded (see -[Troubleshooting](#troubleshooting)). Every child's rollout is saved and redacted like the +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 @@ -219,7 +231,7 @@ 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`, 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 on the direct route, under a runner-owned policy: registered roles only, fresh context, depth one, four open; 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 or from a `gateway/` parent (see [Sub-agents](#sub-agents)) | @@ -397,7 +409,7 @@ agents: runtime: claude ``` -**`code` and `fix` delegate too.** They declare no `tools:`, so on a V1 parent with harness security +**`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`, 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. @@ -474,19 +486,24 @@ The first two exit 97 and mean the hook wiring cannot be trusted; the third exit credential-and-trust guard. All three are fail-closed by design. Between iterations the agent runs as the same user as those files, so "did the agent write there?" is the question to ask first. -**A spawn failed the admission check.** After an iteration whose `exec --json` stream reported a -completed `spawn_agent`, the runner compares the run's completed spawns with the spawn guard's -`codex_spawn_guard_admit` lines in `/sandbox/workspace/.security/findings.jsonl`, and the run fails -whatever codex's exit code. The overlong-item and dropped-notification messages below come before -that comparison, whether or not the stream shows a spawn. Each message says why: +**A spawn failed the admission check.** After every iteration of a delegating agent, and any +iteration whose stream shows a spawn, the runner counts that iteration's spawns from two sources, +each child once by its thread id: the `spawn_agent` items in the `exec --json` stream, completed or +failed (each passed the guard; a spawn the guard blocks emits none, and one codex refused before a +thread existed names no child), and the rollouts under `$CODEX_HOME/sessions` whose parent is the +run's thread or one of its children (a file whose first line is not a `session_meta` record counts +too). It compares the run's total with the spawn guard's `codex_spawn_guard_admit` +lines in `/sandbox/workspace/.security/findings.jsonl`, and the run fails whatever codex's exit +code. Each message says why: ``` -codex_spawn_without_admission: 3 completed spawn(s) in this run's stream(s) but 2 recorded admission(s) +codex_spawn_without_admission: 4 spawn(s) in this run (the stream's spawn items and the child rollouts on disk, each child counted once) but 3 recorded admission(s) ``` -The guard admitted fewer spawns than completed: a hook handler that timed out or failed let a spawn -through, or the findings log lost lines. The count spans every iteration of the run, so a retry's -spawns need admissions of their own. Ask first whether the agent wrote to the findings log; a log -over 1 MiB is read cut, and the message then ends with `the admissions read was cut at 1048576 +The guard admitted fewer spawns than codex handled or started: a hook handler that timed out or +failed let a spawn through, the findings log lost lines, or the sessions directory holds a file that +reads as a child. The count spans every iteration of the run, so a retry's spawns need admissions of +their own. Ask first whether the agent wrote to the findings log or under `$CODEX_HOME/sessions`; a +log over 1 MiB is read cut, and the message then ends with `the admissions read was cut at 1048576 bytes`. ``` codex_spawn_without_admission: a completed spawn was not sent by the primary thread @@ -499,29 +516,34 @@ codex_spawn_without_admission: a spawn_agent item longer than 1048576 bytes coul The parent spawned with a prompt over 1 MiB, so the runner cannot tell whether that spawn completed. Shorten the prompt. ``` +codex_spawn_without_admission: counting the child rollouts: ... +``` +The sessions directory could not be read (the command failed, timed out, or listed over 1 MiB), or +the run's thread id is unknown while a rollout that could be a child exists, so the check could not +be made. +``` reading the spawn admissions: ... ``` The findings log could not be read (the command failed or timed out), so the check could not be made. -``` -codex_spawn_without_admission: codex dropped a stream notification, or its backfill of the turn's items failed or could not be checked, so a lost spawn_agent item cannot be ruled out -``` -A delegating agent's run in which codex dropped an item notification under backpressure, its -re-read of the turn's items failed (`thread/read failed while backfilling turn items` on stderr), -or, under `--debug`, the runner could not read codex's log to find out. The re-read brings back only -items codex saw start, so a spawn that lost both its notifications stays out of the stream's count, -and an unadmitted spawn could balance it; the run fails rather than pass the check on a short -count. Re-run. + +The check cannot catch a forged admission (the findings log is agent-writable), a resume (it shows +as a wait item), a spawn hidden from both sides (its stream items lost and its rollout deleted or +its `session_meta` edited), a child that never started a turn (codex writes the rollout at the +child's first recorded item), or an admission no spawn used covering a later unadmitted spawn: +admissions are compared by count, not id, and codex can reject an admitted call before it emits an +item (a spawn with no message, for one), or another hook can block it after the guard admitted it. **`codex dropped N stream notification(s) under backpressure; the progress log is incomplete`.** -A warning, and for a delegating agent the run then fails: codex's in-process channel filled and it dropped an item notification, which it says on -stderr; the runner reads codex's stderr for that line on every run (under `--debug` the sandbox log -instead). A dropped completed item comes back when the turn completes, if exec's read of the turn's -items succeeds; when that read fails codex says so too, and the warning adds `and its backfill of -the turn's items failed`. A spawn that lost both its notifications does not come back, so a -delegating agent's run fails on any drop (above); an agent without roles only gets the warning. The -launch sets `RUST_LOG` -itself, codex's default filter with `codex_exec` and `codex_app_server::in_process` at warn (`info` +A warning: codex's in-process channel filled and it dropped a notification, of any thread, children +included, and the line does not say which; it says so on stderr, and the runner reads codex's stderr +for that line on every run (under `--debug` the sandbox log instead, where a log it cannot read is +its own warning and a missing one counts zero). A dropped completed item comes back when the turn +completes if exec saw it start and its read of the turn's items succeeds; when that read fails codex +says so too, and the warning adds `and its backfill of the turn's items failed`. The admission check +does not rest on the stream alone: a child's rollout counts it even when its spawn item was lost. +The lines are matched as text, so a tool line that quotes them also counts. The launch sets +`RUST_LOG` itself, codex's default filter with `codex_exec` and `codex_app_server::in_process` at warn (`info` under `--debug`), replacing any value from the environment or `.env`. **`--debug "..."` fails with `accepts 1 arg(s)`.** `--debug` takes an optional value: write diff --git a/internal/cli/bootstrap_input.go b/internal/cli/bootstrap_input.go index 1079b724a0..30ad8b8beb 100644 --- a/internal/cli/bootstrap_input.go +++ b/internal/cli/bootstrap_input.go @@ -18,6 +18,7 @@ type harnessBootstrap struct { modelAliases map[string]string agentSubagents map[string]*string parentModel string + effort string repoDir string // openAIProviderAttached is whether the run-scoped OpenAI provider was // created for this run; see runtime.BootstrapInput.OpenAIProviderAttached. @@ -37,6 +38,7 @@ func (b *harnessBootstrap) Plugins() []runtime.PluginInput { return b.plugin func (b *harnessBootstrap) ModelAliases() map[string]string { return b.modelAliases } func (b *harnessBootstrap) AgentSubagents() map[string]*string { return b.agentSubagents } func (b *harnessBootstrap) ParentModel() string { return b.parentModel } +func (b *harnessBootstrap) Effort() string { return b.effort } func (b *harnessBootstrap) RepoDir() string { return b.repoDir } func (b *harnessBootstrap) OpenAIProviderAttached() bool { return b.openAIProviderAttached } @@ -93,6 +95,7 @@ func newHarnessBootstrap(h *harness.Harness, sandboxName, agentName, forgeEgress modelAliases: modelAliases, agentSubagents: agentSubagents, parentModel: parentModel, + effort: h.Effort, repoDir: repoDir, openAIProviderAttached: openAIProviderAttached, } diff --git a/internal/cli/bootstrap_input_test.go b/internal/cli/bootstrap_input_test.go index 4ef4f2a00c..4f0b52d517 100644 --- a/internal/cli/bootstrap_input_test.go +++ b/internal/cli/bootstrap_input_test.go @@ -50,6 +50,20 @@ func TestNewHarnessBootstrap_WithoutSecurity(t *testing.T) { assert.Nil(t, boot.ModelAliases(), "no per-repo overrides means no alias map") } +// The run's effort reaches the runtime through BootstrapInput, with the +// security hooks on or off: codex binds it as every native child's effort. +func TestNewHarnessBootstrap_CarriesTheEffort(t *testing.T) { + for _, enabled := range []bool{false, true} { + h := &harness.Harness{Agent: "agents/test.md", Effort: "high", Security: &harness.SecurityConfig{Enabled: &enabled}} + boot, err := newHarnessBootstrap(h, "sandbox-1", "test", "", nil, nil, "", "/sandbox/workspace/repo", false) + require.NoError(t, err) + assert.Equal(t, "high", boot.Effort()) + } + boot, err := newHarnessBootstrap(&harness.Harness{Agent: "a.md"}, "sb", "code", "", nil, nil, "", "/sandbox/workspace/repo", false) + require.NoError(t, err) + assert.Empty(t, boot.Effort()) +} + // The per-repo models.aliases map reaches the runtime through // BootstrapInput, which is how it lands in pi's sub-agent model table // (#7020); a run with overrides must carry them here, not just on diff --git a/internal/cli/bootstrap_scan_test.go b/internal/cli/bootstrap_scan_test.go index 7bef8df883..ca4aba6297 100644 --- a/internal/cli/bootstrap_scan_test.go +++ b/internal/cli/bootstrap_scan_test.go @@ -50,6 +50,7 @@ func (b scanBootstrap) Plugins() []runtime.PluginInput { return b.plugins } func (b scanBootstrap) ModelAliases() map[string]string { return nil } func (b scanBootstrap) AgentSubagents() map[string]*string { return nil } func (b scanBootstrap) ParentModel() string { return "" } +func (b scanBootstrap) Effort() string { return "" } func (b scanBootstrap) OpenAIProviderAttached() bool { return false } // scanPiPlugin is one pi-format entry: those are scanned tree-wide, diff --git a/internal/runtime/bootstrap.go b/internal/runtime/bootstrap.go index 2fcb08aa8a..3e3869b078 100644 --- a/internal/runtime/bootstrap.go +++ b/internal/runtime/bootstrap.go @@ -49,6 +49,11 @@ type BootstrapInput interface { // parent's own model is accepted even when that model is outside the // alias table (#7031). ParentModel() string + // Effort returns the reasoning effort the run's agent runs at (the + // harness effort after the agents: entry and --effort, the value Run + // receives as RunParams.Effort), or "" when none is set. The codex + // runtime binds it as every native child's effort (#8836). + Effort() string // OpenAIProviderAttached reports whether the run-scoped OpenAI // provider was created for this run (the harness declares an // openai-type provider and the run needs it, parent or child — see diff --git a/internal/runtime/claude_test.go b/internal/runtime/claude_test.go index 8b0f53295e..41be02e9a1 100644 --- a/internal/runtime/claude_test.go +++ b/internal/runtime/claude_test.go @@ -32,6 +32,7 @@ type bootstrapInput struct { repoDir string agentSubagents map[string]*string parentModel string + effort string openAIProviderAttached bool } @@ -43,6 +44,7 @@ func (b bootstrapInput) Plugins() []PluginInput { return b.plugins } func (b bootstrapInput) ModelAliases() map[string]string { return b.modelAliases } func (b bootstrapInput) AgentSubagents() map[string]*string { return b.agentSubagents } func (b bootstrapInput) ParentModel() string { return b.parentModel } +func (b bootstrapInput) Effort() string { return b.effort } func (b bootstrapInput) OpenAIProviderAttached() bool { return b.openAIProviderAttached } func (b bootstrapInput) RepoDir() string { if b.repoDir == "" { diff --git a/internal/runtime/codex_bootstrap.go b/internal/runtime/codex_bootstrap.go index f6677cb0f2..78cb178ac4 100644 --- a/internal/runtime/codex_bootstrap.go +++ b/internal/runtime/codex_bootstrap.go @@ -160,7 +160,7 @@ func (r CodexRuntime) Bootstrap(input BootstrapInput) error { // tool the guard admits (its entry selects V1, or carries no version and // codex's multi_agent feature, on by default, supplies V1). A V2, // unlisted or gateway/ parent keeps the multi-agent tools off and runs in - // one context, as every agent does today. + // one context, as an agent that does not delegate does. _, securityOn := input.(SandboxHooksBootstrap) var catalog codexCatalog delegating := false @@ -175,11 +175,11 @@ func (r CodexRuntime) Bootstrap(input BootstrapInput) error { } // Resolved before config.toml is written: a bad subagents value fails here. var roles []codexRole - defaultSubagentModel := "" + defaultSubagentModel, childEffort := "", "" if delegating { discovered, skipped := codexRoles(input.SkillDirs(), agentName) - roles, defaultSubagentModel, err = resolveCodexChildModels( - discovered, skipped, input.AgentSubagents(), os.Getenv(codexSubagentModelEnv), catalog) + roles, defaultSubagentModel, childEffort, err = resolveCodexChildModels( + discovered, skipped, input.AgentSubagents(), os.Getenv(codexSubagentModelEnv), input.Effort(), catalog) if err != nil { return err } @@ -188,7 +188,7 @@ func (r CodexRuntime) Bootstrap(input BootstrapInput) error { // inference.gateway block for this sandbox (PrepareGatewayRun). gatewayBaseURL := codexGatewayRunFor(sandboxName) configTOML, err := renderCodexConfig(cfg, repoInput.RepoDir(), - codexDeveloperInstructions(agentName, def, roles), gatewayBaseURL, roles, defaultSubagentModel) + codexDeveloperInstructions(agentName, def, roles), gatewayBaseURL, roles, defaultSubagentModel, childEffort) if err != nil { return err } diff --git a/internal/runtime/codex_bootstrap_test.go b/internal/runtime/codex_bootstrap_test.go index 232717978e..4bba5f800b 100644 --- a/internal/runtime/codex_bootstrap_test.go +++ b/internal/runtime/codex_bootstrap_test.go @@ -1289,6 +1289,60 @@ func TestCodexRuntimeBootstrap_DelegatingAgentRunsNativeChildren(t *testing.T) { assert.Contains(t, readFileString(t, logPath), r.codexHooksPath(), "hooks.json is still written: the guard is installed") } +// The run's effort reaches config.toml as every child's effort, and an +// effort a child model lacks fails Bootstrap before config.toml is written; +// an agent that does not delegate gets neither, whatever its effort. +func TestCodexRuntimeBootstrap_BindsTheRunEffort(t *testing.T) { + t.Setenv(codexSubagentModelEnv, "") + skill := t.TempDir() + writePersonaFile(t, skill, "correctness", codexTestPersona) + run := func(t *testing.T, input codexHooksBootstrapInput) (CodexRuntime, string, string, error) { + storeDir := t.TempDir() + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "openshell.log"), storeDir, "codex-cli 0.152.1") + forgetRunnerHeldDigests("sb") + t.Cleanup(func() { forgetRunnerHeldDigests("sb") }) + r := CodexRuntime{} + var err error + out := captureStderr(t, func() { err = r.Bootstrap(input) }) + return r, storeDir, out, err + } + + t.Run("delegating, effort high", func(t *testing.T) { + input := codexDelegatingHooksInput(t, skill) + input.effort = "high" + r, storeDir, out, err := run(t, input) + require.NoError(t, err) + assert.Contains(t, string(storedUpload(t, storeDir, r.codexConfigPath())), "default_subagent_reasoning_effort = \"high\"\n") + assert.Contains(t, out, "subagents: effort → high (from the run's effort; every child)") + }) + t.Run("delegating, no effort", func(t *testing.T) { + r, storeDir, out, err := run(t, codexDelegatingHooksInput(t, skill)) + require.NoError(t, err) + assert.NotContains(t, string(storedUpload(t, storeDir, r.codexConfigPath())), "default_subagent_reasoning_effort") + assert.Contains(t, out, "subagents: effort → medium (from the catalog default of gpt-5.6-luna; every child)") + }) + t.Run("delegating, effort max with a gpt-5.5 default", func(t *testing.T) { + input := codexDelegatingHooksInput(t, skill) + input.effort = "max" + input.agentSubagents = map[string]*string{"default": strp("openai/gpt-5.5")} + r, storeDir, _, err := run(t, input) + require.ErrorContains(t, err, `subagents.default: model "gpt-5.5" does not support reasoning effort "max"`) + _, statErr := os.Stat(filepath.Join(storeDir, strings.ReplaceAll(r.codexConfigPath(), "/", "_"))) + assert.True(t, os.IsNotExist(statErr), "config.toml is not written") + }) + t.Run("not delegating, effort max", func(t *testing.T) { + input := codexHooksBootstrapInput{ + bootstrapInput: bootstrapInput{sandboxName: "sb", agentPath: writeAgentFile(t, codexTestAgentDef), agentName: "triage", skillDirs: []string{skill}, effort: "max", + agentSubagents: map[string]*string{"default": strp("openai/gpt-5.5")}}, + hooks: security.SandboxHookConfigFromHarness(&harness.Harness{}), + } + r, storeDir, out, err := run(t, input) + require.NoError(t, err) + assert.NotContains(t, string(storedUpload(t, storeDir, r.codexConfigPath())), "default_subagent_reasoning_effort") + assert.NotContains(t, out, "subagents:") + }) +} + // FULLSEND_CODEX_SUBAGENT_MODEL beats subagents.default for the run-level // default; a persona without its own entry still gets no model line. func TestCodexRuntimeBootstrap_SubagentModelEnvBeatsTheConfigDefault(t *testing.T) { diff --git a/internal/runtime/codex_config.go b/internal/runtime/codex_config.go index c4ab02bdb5..f2e8419ffe 100644 --- a/internal/runtime/codex_config.go +++ b/internal/runtime/codex_config.go @@ -222,7 +222,7 @@ type codexConfigData struct { // 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 string) ([]byte, error) { +func renderCodexConfig(configDir, repoDir, developerInstructions, gatewayBaseURL string, roles []codexRole, defaultSubagentModel, childEffort string) ([]byte, error) { if repoDir == "" { return nil, fmt.Errorf("rendering codex %s: the target repository path is required", codexConfigFile) } @@ -233,7 +233,7 @@ func renderCodexConfig(configDir, repoDir, developerInstructions, gatewayBaseURL DeveloperInstructions: codexTOMLString(developerInstructions), AuthCommand: codexTOMLString(configDir + "/" + codexAuthScriptFile), ProjectKey: codexTOMLKey(repoDir), - AgentsBlock: codexAgentsBlock(configDir, roles, defaultSubagentModel), + AgentsBlock: codexAgentsBlock(configDir, roles, defaultSubagentModel, childEffort), RefreshIntervalMS: codexAuthRefreshIntervalMS, TimeoutMS: codexAuthTimeoutMS, } @@ -258,18 +258,22 @@ const ( ) // codexAgentsBlock renders the [agents] table: off without roles; with -// roles, on under the ADR 0126 limits, with the run-level child model and -// one table per role file Bootstrap writes under /agents. +// roles, on under the ADR 0126 limits, with the run-level child model, the +// run's effort for every child when the run has one, and one table per +// role file Bootstrap writes under /agents. // Strings go through codexTOMLString and table keys through codexTOMLKey; // the boolean and the two limits are bare. No trailing newline: the // template supplies the blank line that follows. -func codexAgentsBlock(configDir string, roles []codexRole, defaultSubagentModel string) string { +func codexAgentsBlock(configDir string, roles []codexRole, defaultSubagentModel, childEffort string) string { if len(roles) == 0 { return "[agents]\nenabled = false" } var b strings.Builder fmt.Fprintf(&b, "[agents]\nenabled = true\nmax_concurrent_threads_per_session = %d\nmax_depth = %d\ndefault_subagent_model = %s\n", codexMaxOpenChildren, codexMaxChildDepth, codexTOMLString(defaultSubagentModel)) + if childEffort != "" { + fmt.Fprintf(&b, "default_subagent_reasoning_effort = %s\n", codexTOMLString(childEffort)) + } for _, role := range roles { fmt.Fprintf(&b, "\n[agents.%s]\ndescription = %s\nconfig_file = %s\n", codexTOMLKey(role.Name), codexTOMLString(role.Description), diff --git a/internal/runtime/codex_config_test.go b/internal/runtime/codex_config_test.go index 83abba3743..1f8868aa12 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, "", "") 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, "", "") require.NoError(t, err) rendered := string(data) @@ -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, "", "") 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, "", "") 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, "", "") 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, "", "") require.NoError(t, err) assert.NotEqual(t, codexAssetSHA256(withGateway), codexAssetSHA256(other), "the gateway base_url is covered by the digest") } @@ -435,7 +435,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, "", "") require.Error(t, err, "an empty path would leave the project's trust unset") } @@ -489,6 +489,19 @@ func codexTestDelegatingRoles() []codexRole { } } +// The run's effort is bound for every child right after the run-level child +// model; with no effort the key is absent, so the bytes are unchanged. +func TestCodexAgentsBlock_ChildEffort(t *testing.T) { + t.Parallel() + with := codexAgentsBlock(sandbox.SandboxCodexConfig, codexTestDelegatingRoles(), "gpt-5.6-luna", "high") + assert.Contains(t, with, "default_subagent_model = \"gpt-5.6-luna\"\ndefault_subagent_reasoning_effort = \"high\"\n") + without := codexAgentsBlock(sandbox.SandboxCodexConfig, codexTestDelegatingRoles(), "gpt-5.6-luna", "") + assert.NotContains(t, without, "reasoning_effort") + assert.Equal(t, strings.Replace(with, "default_subagent_reasoning_effort = \"high\"\n", "", 1), without) + assert.Equal(t, "[agents]\nenabled = false", codexAgentsBlock(sandbox.SandboxCodexConfig, nil, "", "high"), + "an agent that does not delegate gets no child settings") +} + // TestRenderCodexConfig_DelegatingAgentsBlock pins the [agents] block of a // delegating agent: enabled = true, the two limits ADR 0126 fixes, the // run-level child model, one [agents.""] table per role with its @@ -496,7 +509,7 @@ func codexTestDelegatingRoles() []codexRole { // 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", "") require.NoError(t, err) rendered := string(data) @@ -528,9 +541,9 @@ 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, "", "") 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", "") 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.") @@ -543,7 +556,7 @@ 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") + data, err := renderCodexConfig(sandbox.SandboxCodexConfig, "/sandbox/workspace/repo", "body", "", roles, "gpt-6-astra", "") require.NoError(t, err) path := filepath.Join(t.TempDir(), "config.toml") diff --git a/internal/runtime/codex_golden_test.go b/internal/runtime/codex_golden_test.go index 4dd56e0031..38a3912695 100644 --- a/internal/runtime/codex_golden_test.go +++ b/internal/runtime/codex_golden_test.go @@ -75,23 +75,23 @@ 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), "", nil, "", "") 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, "") + 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()) + 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("review", review, roles), "", roles, defaultModel, "") require.NoError(t, err) return string(data) }}, @@ -122,8 +122,8 @@ func TestCodexGolden(t *testing.T) { {"roles/default.toml", func(t *testing.T) string { return string(codexGoldenRoles(t)[1].toml()) }}, {"roles/explore.toml", func(t *testing.T) string { return string(codexGoldenRoles(t)[2].toml()) }}, {"roles/correctness-model.toml", func(t *testing.T) string { - resolved, _, err := resolveCodexChildModels(codexGoldenRoles(t), nil, - map[string]*string{"correctness": strp("openai/gpt-5.6-sol")}, "", codexTestCatalog()) + resolved, _, _, err := resolveCodexChildModels(codexGoldenRoles(t), nil, + map[string]*string{"correctness": strp("openai/gpt-5.6-sol")}, "", "", codexTestCatalog()) require.NoError(t, err) require.Equal(t, "correctness", resolved[0].Name, "codexRoles sorts by name") return string(resolved[0].toml()) diff --git a/internal/runtime/codex_integrity.go b/internal/runtime/codex_integrity.go index b3b26d4249..1891c86d91 100644 --- a/internal/runtime/codex_integrity.go +++ b/internal/runtime/codex_integrity.go @@ -71,9 +71,11 @@ type codexRunnerHeldDigestSet struct { // Bootstrap registers roles; the spawn guard admits only these. RoleFiles map[string]string - // CompletedSpawns is the number of completed spawns the `exec --json` - // streams reported, summed over the run's iterations: the findings log - // the admission cross-check compares it with persists across them too. + // CompletedSpawns is the run's spawn count, summed over its iterations: + // per iteration the spawns the `exec --json` stream (completed or failed + // items) and the children on disk show, each counted once per thread. + // The findings log the admission cross-check compares it with persists + // across them too. CompletedSpawns int } diff --git a/internal/runtime/codex_personas.go b/internal/runtime/codex_personas.go index 5c08849cdd..a7cca19df9 100644 --- a/internal/runtime/codex_personas.go +++ b/internal/runtime/codex_personas.go @@ -68,6 +68,24 @@ func codexChildModel(key, value string) (string, error) { return model.ID, nil } +// codexSupportedEffort checks a child effort against a child model's +// supported reasoning levels in the bundled catalog: codex compares them +// exactly and refuses the spawn otherwise, with no clamping +// (validate_spawn_agent_reasoning_effort). key names the position that chose +// the model, effortSource where the effort came from. +func codexSupportedEffort(catalog codexCatalog, key, model, effort, effortSource string) error { + efforts := catalog[model].Efforts + if slices.Contains(efforts, effort) { + return nil + } + supported := "none" + if len(efforts) > 0 { + supported = strings.Join(efforts, ", ") + } + return fmt.Errorf("%s: model %q does not support reasoning effort %q (%s), which codex would refuse at every spawn; it supports %s: set an effort every child model supports, or a child model that supports it", + key, model, effort, effortSource, supported) +} + // codexListedModel is Bootstrap's catalog check: codex itself checks a // run-level default only at each spawn and a role-file model not at all (the // child fails on the provider's 404 instead), so every chain position is @@ -87,7 +105,7 @@ func codexListedModel(catalog codexCatalog, key, model string) error { // carrying codexRoles's reason when the key names a skipped persona; every // configured value is validated whichever position wins, and every // resolved model must be in catalog (ADR 0126). The returned slice is a copy. -func resolveCodexChildModels(roles []codexRole, skipped map[string]string, subagents map[string]*string, envValue string, catalog codexCatalog) ([]codexRole, string, error) { +func resolveCodexChildModels(roles []codexRole, skipped map[string]string, subagents map[string]*string, envValue, runEffort string, catalog codexCatalog) ([]codexRole, string, string, error) { persona := make(map[string]bool, len(roles)) for _, role := range roles { if !slices.Contains(config.ReservedSubagentKeys(), role.Name) { @@ -104,13 +122,13 @@ func resolveCodexChildModels(roles []codexRole, skipped map[string]string, subag discovered = strings.Join(slices.Sorted(maps.Keys(persona)), ", ") } if slices.Contains(config.ReservedSubagentKeys(), key) { - return nil, "", fmt.Errorf("subagents.%s: %q is a built-in role, not a persona; it runs on the run-level child model; registered personas: %s", + return nil, "", "", fmt.Errorf("subagents.%s: %q is a built-in role, not a persona; it runs on the run-level child model; registered personas: %s", key, key, discovered) } if reason, ok := skipped[key]; ok { - return nil, "", fmt.Errorf("subagents.%s: persona %q was not registered: %s", key, key, reason) + return nil, "", "", fmt.Errorf("subagents.%s: persona %q was not registered: %s", key, key, reason) } - return nil, "", fmt.Errorf("subagents.%s: no persona %q is registered; registered personas: %s", key, key, discovered) + return nil, "", "", fmt.Errorf("subagents.%s: no persona %q is registered; registered personas: %s", key, key, discovered) } out := slices.Clone(roles) @@ -121,10 +139,10 @@ func resolveCodexChildModels(roles []codexRole, skipped map[string]string, subag } model, err := codexChildModel("subagents."+role.Name, *value) if err != nil { - return nil, "", err + return nil, "", "", err } if err := codexListedModel(catalog, "subagents."+role.Name, model); err != nil { - return nil, "", err + return nil, "", "", err } out[i].Model = model } @@ -133,19 +151,49 @@ func resolveCodexChildModels(roles []codexRole, skipped map[string]string, subag if value := subagents["default"]; value != nil { model, err := codexChildModel("subagents.default", *value) if err != nil { - return nil, "", err + return nil, "", "", err } defaultModel, source = model, "subagents.default" } if strings.TrimSpace(envValue) != "" { model, err := codexChildModel(codexSubagentModelEnv, envValue) if err != nil { - return nil, "", err + return nil, "", "", err } defaultModel, source = model, codexSubagentModelEnv } if err := codexListedModel(catalog, source, defaultModel); err != nil { - return nil, "", err + return nil, "", "", err + } + + // The child effort. Codex resets a child to the run-level child model's + // catalog default unless agents.default_subagent_reasoning_effort is set + // (child_config.rs, rust-v0.159.3), so the run's effort is written there + // when the run has one. Either way codex checks the effort against the + // run-level child model and against a persona's own model at spawn and + // refuses the spawn when the model lacks it: each is checked here. + effort, effortSource := "", "" + if mapped, ok := codexEffortFor(runEffort); ok && mapped != "" { + effort, effortSource = mapped, "the run's effort" + } + effective := effort + if effective == "" { + effective, effortSource = catalog[defaultModel].DefaultEffort, "the catalog default of "+defaultModel + } + if effort != "" { + if err := codexSupportedEffort(catalog, source, defaultModel, effort, effortSource); err != nil { + return nil, "", "", err + } + } + if effective != "" { + for _, role := range out { + if role.Model == "" { + continue + } + if err := codexSupportedEffort(catalog, "subagents."+role.Name, role.Model, effective, effortSource); err != nil { + return nil, "", "", err + } + } } // Echoed as pi does, so a user sees why a child resolved as it did. @@ -156,7 +204,10 @@ func resolveCodexChildModels(roles []codexRole, skipped map[string]string, subag fmt.Fprintf(os.Stderr, "subagents: %s → %s (from subagents.%s)\n", role.Name, role.Model, role.Name) } } - return out, defaultModel, nil + if effective != "" { + fmt.Fprintf(os.Stderr, "subagents: effort → %s (from %s; every child)\n", effective, effortSource) + } + return out, defaultModel, effort, nil } // toml renders the role file: name, description, model for a persona with @@ -268,10 +319,19 @@ func codexDroppedFrontmatterKeys(frontmatter []byte) []string { } // codexCatalog is the pinned CLI's bundled model catalog reduced to what -// Bootstrap asks of it: slug → multi_agent_version ("v1", "v2", or "" when -// the entry sets none), read from `codex debug models --bundled`, which +// Bootstrap asks of it, read from `codex debug models --bundled`, which // dumps the catalog compiled into the binary and makes no request. -type codexCatalog map[string]string +type codexCatalog map[string]codexCatalogModel + +// codexCatalogModel is one catalog entry: its multi_agent_version ("v1", +// "v2", or "" when the entry sets none), its default_reasoning_level ("" for +// none) and the efforts of its supported_reasoning_levels, the set codex +// checks a child's effort against at spawn (validate_spawn_agent_reasoning_effort). +type codexCatalogModel struct { + Version string + DefaultEffort string + Efforts []string +} // has reports whether the catalog lists the model. func (c codexCatalog) has(slug string) bool { _, ok := c[slug]; return ok } @@ -281,19 +341,24 @@ func (c codexCatalog) has(slug string) bool { _, ok := c[slug]; return ok } // selects V1, or carries no version and codex's multi_agent feature, on by // default, supplies V1. func (c codexCatalog) resolvesV1(slug string) bool { - v, ok := c[slug] - return ok && (v == "v1" || v == "") + m, ok := c[slug] + return ok && (m.Version == "v1" || m.Version == "") } // parseCodexCatalog decodes the dump. Unknown keys are ignored; an empty // model list is an error, because a binary with no catalog cannot run at all. -// A null multi_agent_version is stored as "": encoding/json decodes null -// into a zero string, which is the "no version" resolvesV1 counts as V1. +// A null multi_agent_version or default_reasoning_level is stored as "": +// encoding/json decodes null into a zero string, which is the "no version" +// resolvesV1 counts as V1. func parseCodexCatalog(data []byte) (codexCatalog, error) { var dump struct { Models []struct { - Slug string `json:"slug"` - MultiAgentVersion string `json:"multi_agent_version"` + Slug string `json:"slug"` + MultiAgentVersion string `json:"multi_agent_version"` + DefaultReasoningLevel string `json:"default_reasoning_level"` + SupportedLevels []struct { + Effort string `json:"effort"` + } `json:"supported_reasoning_levels"` } `json:"models"` } if err := json.Unmarshal(data, &dump); err != nil { @@ -304,7 +369,11 @@ func parseCodexCatalog(data []byte) (codexCatalog, error) { } catalog := make(codexCatalog, len(dump.Models)) for _, m := range dump.Models { - catalog[m.Slug] = m.MultiAgentVersion + efforts := make([]string, 0, len(m.SupportedLevels)) + for _, level := range m.SupportedLevels { + efforts = append(efforts, level.Effort) + } + catalog[m.Slug] = codexCatalogModel{Version: m.MultiAgentVersion, DefaultEffort: m.DefaultReasoningLevel, Efforts: efforts} } return catalog, nil } @@ -315,7 +384,7 @@ func parseCodexCatalog(data []byte) (codexCatalog, error) { // codex must resolve it to collaboration V1 (resolvesV1). When it does not, // a V2 or unlisted parent, the reason is returned for one stderr line and // Bootstrap keeps codex's multi-agent tools off: the agent runs in one -// context, as every agent does today. A parent that does not translate is +// context, as an agent that does not delegate does. 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 @@ -335,6 +404,6 @@ func codexParentResolvesV1(catalog codexCatalog, parentModel, agentModel string) case catalog.resolvesV1(id): return true, "" default: - return false, fmt.Sprintf("parent model %q selects collaboration %q", id, catalog[id]) + needV1 + return false, fmt.Sprintf("parent model %q selects collaboration %q", id, catalog[id].Version) + needV1 } } diff --git a/internal/runtime/codex_personas_test.go b/internal/runtime/codex_personas_test.go index bb58a83b97..d86658adf3 100644 --- a/internal/runtime/codex_personas_test.go +++ b/internal/runtime/codex_personas_test.go @@ -339,11 +339,12 @@ func TestCodexRole_TOMLParsesWithTheThreeKeys(t *testing.T) { } // TestCodexCatalog reads the fixture reduced from the pinned CLI's dump and -// pins the two questions Bootstrap asks it: is a model listed, and does -// codex resolve it to collaboration V1. On a CODEX_VERSION bump regenerate -// it, never edit it (the file name carries the pin): +// pins the questions Bootstrap asks it: is a model listed, does codex +// resolve it to collaboration V1, and which efforts a child on it may run +// at. On a CODEX_VERSION bump regenerate it, never edit it (the file name +// carries the pin): // -// codex debug models --bundled | python3 -c 'import json,sys; d=json.load(sys.stdin); json.dump({"models":[{"slug":m["slug"],"multi_agent_version":m.get("multi_agent_version")} for m in d["models"]]}, sys.stdout, indent=2); print()' > testdata/codex/models-bundled-.json +// codex debug models --bundled | python3 -c 'import json,sys; d=json.load(sys.stdin); json.dump({"models":[{"slug":m["slug"],"multi_agent_version":m.get("multi_agent_version"),"default_reasoning_level":m.get("default_reasoning_level"),"supported_reasoning_levels":[{"effort":l["effort"]} for l in m.get("supported_reasoning_levels") or []]} for m in d["models"]]}, sys.stdout, indent=2); print()' > testdata/codex/models-bundled-.json func TestCodexCatalog(t *testing.T) { t.Parallel() containerfile, err := os.ReadFile(filepath.Join("..", "..", "images", "sandbox", "Containerfile")) @@ -355,8 +356,12 @@ func TestCodexCatalog(t *testing.T) { catalog, err := parseCodexCatalog(data) require.NoError(t, err) - assert.True(t, catalog.has("gpt-5.6-luna")) - assert.True(t, catalog.resolvesV1("gpt-5.6-luna"), "the floor model is the listed V1 model on 0.159.3") + assert.True(t, catalog.has(codexDefaultSubagentModel), "the floor must be listed; a child takes its parent's collaboration version, so the floor's own does not matter") + assert.True(t, catalog.resolvesV1("gpt-5.6-luna"), "a luna parent delegates on 0.159.3") + assert.Equal(t, "medium", catalog["gpt-5.6-luna"].DefaultEffort, "children on the floor run at medium when the run sets no effort") + assert.Equal(t, []string{"low", "medium", "high", "xhigh", "max"}, catalog["gpt-5.6-luna"].Efforts) + assert.Equal(t, "low", catalog["gpt-5.6-sol"].DefaultEffort) + assert.NotContains(t, catalog["gpt-5.5"].Efforts, "max", "the one fullsend effort a listed model lacks at the pin") assert.True(t, catalog.has("gpt-5.6-sol")) assert.False(t, catalog.resolvesV1("gpt-5.6-sol"), "sol selects V2") assert.True(t, catalog.has("gpt-5.5")) @@ -384,7 +389,7 @@ func TestCodexCatalog(t *testing.T) { // and so does a gateway/ parent whatever its id. func TestCodexParentResolvesV1(t *testing.T) { t.Parallel() - catalog := codexCatalog{"gpt-5.6-luna": "v1", "gpt-5.6-sol": "v2", "gpt-5.5": "", "gpt-x": "v3"} + catalog := codexVersionsCatalog(map[string]string{"gpt-5.6-luna": "v1", "gpt-5.6-sol": "v2", "gpt-5.5": "", "gpt-x": "v3"}) tests := []struct { name string parentModel string @@ -522,7 +527,7 @@ func TestResolveCodexChildModels_Precedence(t *testing.T) { cfg["correctness"] = nil } - got, gotDefault, err := resolveCodexChildModels(roles, nil, cfg, tt.env, codexTestCatalog()) + got, gotDefault, _, err := resolveCodexChildModels(roles, nil, cfg, tt.env, "", codexTestCatalog()) require.NoError(t, err) require.Len(t, got, 3) assert.Equal(t, tt.wantModel, got[0].Model, "correctness") @@ -581,7 +586,7 @@ func TestResolveCodexChildModels_RejectsUnknownKeys(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - _, _, err := resolveCodexChildModels(tt.roles, tt.skipped, tt.cfg, "", codexTestCatalog()) + _, _, _, err := resolveCodexChildModels(tt.roles, tt.skipped, tt.cfg, "", "", codexTestCatalog()) if len(tt.wantErr) == 0 { assert.NoError(t, err) return @@ -620,7 +625,7 @@ func TestResolveCodexChildModels_NonOpenAIValueNamesTheKey(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - _, _, err := resolveCodexChildModels(roles, nil, tt.cfg, tt.env, codexTestCatalog()) + _, _, _, err := resolveCodexChildModels(roles, nil, tt.cfg, tt.env, "", codexTestCatalog()) require.Error(t, err) for _, w := range tt.wantErr { assert.Contains(t, err.Error(), w) @@ -629,17 +634,35 @@ func TestResolveCodexChildModels_NonOpenAIValueNamesTheKey(t *testing.T) { } } -// codexTestCatalog lists every model the tables above use, with the versions -// of testdata/codex/models-bundled-0.159.3.json; add any id a new row introduces. +// codexTestCatalog lists every model the tables above use, with the versions, +// default efforts and supported efforts of +// testdata/codex/models-bundled-0.159.3.json; add any id a new row introduces. func codexTestCatalog() codexCatalog { - return codexCatalog{"gpt-5.6-luna": "v1", "gpt-5.6-sol": "v2", "gpt-5.6-terra": "v2", "gpt-6-astra": "v2"} + upToMax := []string{"low", "medium", "high", "xhigh", "max"} + upToUltra := []string{"low", "medium", "high", "xhigh", "max", "ultra"} + return codexCatalog{ + "gpt-5.6-luna": {Version: "v1", DefaultEffort: "medium", Efforts: upToMax}, + "gpt-5.6-sol": {Version: "v2", DefaultEffort: "low", Efforts: upToUltra}, + "gpt-5.6-terra": {Version: "v2", DefaultEffort: "medium", Efforts: upToUltra}, + "gpt-6-astra": {Version: "v2", DefaultEffort: "low", Efforts: upToUltra}, + "gpt-5.5": {Version: "", DefaultEffort: "medium", Efforts: []string{"low", "medium", "high", "xhigh"}}, + } +} + +// codexVersionsCatalog is a catalog with versions only, for the gate's tests. +func codexVersionsCatalog(versions map[string]string) codexCatalog { + c := make(codexCatalog, len(versions)) + for slug, v := range versions { + c[slug] = codexCatalogModel{Version: v} + } + return c } // Every chain position is checked against the catalog, the floor included; // the error names the position that supplied the id. func TestResolveCodexChildModels_CatalogMembership(t *testing.T) { t.Parallel() - catalog := codexCatalog{"gpt-5.6-luna": "v1", "gpt-5.6-sol": "v2", "gpt-6-astra": "v2"} + catalog := codexVersionsCatalog(map[string]string{"gpt-5.6-luna": "v1", "gpt-5.6-sol": "v2", "gpt-6-astra": "v2"}) sol, nova := "openai/gpt-5.6-sol", "openai/gpt-5.6-nova" roles := []codexRole{{Name: "correctness"}, {Name: "default"}, {Name: "explore"}} tests := []struct { @@ -653,13 +676,13 @@ func TestResolveCodexChildModels_CatalogMembership(t *testing.T) { {"persona entry unlisted", map[string]*string{"correctness": &nova}, "", catalog, `subagents.correctness: model "gpt-5.6-nova" is not in the bundled catalog of the pinned codex`}, {"default unlisted", map[string]*string{"default": &nova}, "", catalog, `subagents.default: model "gpt-5.6-nova" is not in the bundled catalog of the pinned codex`}, {"runner variable unlisted", nil, "gpt-5.6-nova", catalog, `FULLSEND_CODEX_SUBAGENT_MODEL: model "gpt-5.6-nova" is not in the bundled catalog of the pinned codex`}, - {"floor unlisted after a CLI bump", nil, "", codexCatalog{"gpt-5.6-sol": "v2"}, `built-in default: model "gpt-5.6-luna" is not in the bundled catalog of the pinned codex`}, - {"floor unlisted but overridden", map[string]*string{"default": &sol}, "", codexCatalog{"gpt-5.6-sol": "v2"}, ""}, + {"floor unlisted after a CLI bump", nil, "", codexVersionsCatalog(map[string]string{"gpt-5.6-sol": "v2"}), `built-in default: model "gpt-5.6-luna" is not in the bundled catalog of the pinned codex`}, + {"floor unlisted but overridden", map[string]*string{"default": &sol}, "", codexVersionsCatalog(map[string]string{"gpt-5.6-sol": "v2"}), ""}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - _, _, err := resolveCodexChildModels(roles, nil, tt.subagents, tt.env, tt.catalog) + _, _, _, err := resolveCodexChildModels(roles, nil, tt.subagents, tt.env, "", tt.catalog) if tt.wantErr == "" { require.NoError(t, err) return @@ -669,6 +692,60 @@ func TestResolveCodexChildModels_CatalogMembership(t *testing.T) { } } +// TestResolveCodexChildModels_Effort pins the child effort: the run's effort +// when set, else the run-level child model's catalog default (codex resets a +// child to it); either is checked against the run-level child model (the +// run's effort only) and every persona model, as codex checks them at +// spawn, and the error names the position that chose the model. +func TestResolveCodexChildModels_Effort(t *testing.T) { + t.Parallel() + gpt55, luna, sol := "openai/gpt-5.5", "openai/gpt-5.6-luna", "openai/gpt-5.6-sol" + roles := []codexRole{{Name: "correctness"}, {Name: "default"}, {Name: "explore"}} + ultraDefault := codexTestCatalog() + ultraDefault["gpt-x-ultra"] = codexCatalogModel{Version: "v2", DefaultEffort: "ultra", Efforts: []string{"ultra"}} + noLevels := codexTestCatalog() + noLevels["gpt-5.6-luna"] = codexCatalogModel{Version: "v1", DefaultEffort: "medium"} + tests := []struct { + name string + subagents map[string]*string + env string + runEffort string + catalog codexCatalog + wantEffort string + wantErr string + }{ + {name: "no run effort: no key", catalog: codexTestCatalog()}, + {name: "run effort high on luna", runEffort: "high", catalog: codexTestCatalog(), wantEffort: "high"}, + {name: "run effort trimmed and lower-cased", runEffort: " High ", catalog: codexTestCatalog(), wantEffort: "high"}, + {name: "max with subagents.default gpt-5.5", subagents: map[string]*string{"default": &gpt55}, runEffort: "max", catalog: codexTestCatalog(), + wantErr: `subagents.default: model "gpt-5.5" does not support reasoning effort "max" (the run's effort)`}, + {name: "max with the runner variable gpt-5.5", env: gpt55, runEffort: "max", catalog: codexTestCatalog(), + wantErr: `FULLSEND_CODEX_SUBAGENT_MODEL: model "gpt-5.5" does not support reasoning effort "max"`}, + {name: "max with a beaten subagents.default gpt-5.5", subagents: map[string]*string{"default": &gpt55}, env: luna, runEffort: "max", + catalog: codexTestCatalog(), wantEffort: "max"}, + {name: "max with a persona on gpt-5.5", subagents: map[string]*string{"correctness": &gpt55}, runEffort: "max", catalog: codexTestCatalog(), + wantErr: `subagents.correctness: model "gpt-5.5" does not support reasoning effort "max" (the run's effort)`}, + {name: "low with a persona on sol", subagents: map[string]*string{"correctness": &sol}, runEffort: "low", catalog: codexTestCatalog(), wantEffort: "low"}, + {name: "no run effort: a persona model lacks the default model's default", subagents: map[string]*string{"default": strp("openai/gpt-x-ultra"), "correctness": &luna}, + catalog: ultraDefault, wantErr: `subagents.correctness: model "gpt-5.6-luna" does not support reasoning effort "ultra" (the catalog default of gpt-x-ultra)`}, + {name: "an entry without supported levels", runEffort: "medium", catalog: noLevels, + wantErr: `built-in default: model "gpt-5.6-luna" does not support reasoning effort "medium" (the run's effort), which codex would refuse at every spawn; it supports none`}, + {name: "a tombstoned subagents.default falls to the floor", subagents: map[string]*string{"default": nil}, runEffort: "high", catalog: codexTestCatalog(), wantEffort: "high"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + _, _, effort, err := resolveCodexChildModels(roles, nil, tt.subagents, tt.env, tt.runEffort, tt.catalog) + if tt.wantErr != "" { + require.ErrorContains(t, err, tt.wantErr) + return + } + require.NoError(t, err) + assert.Equal(t, tt.wantEffort, effort) + }) + } +} + // TestCodexRole_TOMLModelLine pins the role file with and without a model: // keys name, description, [model], developer_instructions, nothing else. The // bytes without a model are unchanged; the model line is the only difference. diff --git a/internal/runtime/codex_run.go b/internal/runtime/codex_run.go index a19a85ea6d..76b5c21259 100644 --- a/internal/runtime/codex_run.go +++ b/internal/runtime/codex_run.go @@ -5,6 +5,7 @@ import ( "fmt" "io" "os" + "slices" "sort" "strings" "time" @@ -657,12 +658,10 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri } childIDs.flush() stderr.flush() - dropsUnread := false if params.Debug != "" { // Under --debug codex's stderr went to the sandbox log instead. dropped, backfillFailed, derr := codexCountDroppedInLog(params.SandboxName) if derr != nil { - dropsUnread = true printer.StepWarn("Could not read codex's log for dropped stream notifications: " + redactSummary(sanitizeOutput(derr.Error()))) } stderr.Dropped += dropped @@ -682,11 +681,23 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri r.ConfigDir()) } + // The children on disk are read whatever the exit code, for a delegating + // agent and whenever the stream shows a spawn: a child that started a turn + // leaves a rollout even when the stream lost its spawn item, which is how + // the admission check below and the usage fold see it. + checkSpawns := digests.delegating() || len(childIDs.Senders) > 0 + diskChildren, diskIDs := 0, []string(nil) + var rolloutsErr error + if checkSpawns { + diskChildren, diskIDs, rolloutsErr = r.readCodexChildRollouts(params.SandboxName, primaryThreadID) + } + foldIDs := slices.Compact(slices.Sorted(slices.Values(slices.Concat(childIDs.IDs, diskIDs)))) + // The fold runs whatever the exit code: codex writes a child's usage as // each response completes, and the parent's entry keeps per_model_usage // summing to the totals across a retry. A read failure is a warning. - if digests.delegating() || len(childIDs.IDs) > 0 { - n, ferr := r.foldCodexChildUsage(params.SandboxName, childIDs.IDs, metrics) + if digests.delegating() || len(foldIDs) > 0 { + n, ferr := r.foldCodexChildUsage(params.SandboxName, foldIDs, metrics) if ferr != nil { printer.StepWarn("Sub-agent usage not fully counted: " + redactSummary(sanitizeOutput(ferr.Error()))) } @@ -695,7 +706,7 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri } // At the budget or on a cancel OpenShell kills nothing, so codex's // children can record more after the read. - if len(childIDs.IDs) > 0 && (ctx.Err() != nil || exitCode == 124 || exitCode == -1) { + if len(foldIDs) > 0 && (ctx.Err() != nil || exitCode == 124 || exitCode == -1) { printer.StepWarn("Sub-agent usage may be undercounted: codex was stopped, and its children can record more after the read") } } @@ -703,13 +714,11 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri // Checked whatever the exit code: with a validation loop an iteration's // non-zero exit does not fail the run; an error from Run does, and a // failed read or an unread spawn item is one too, unlike the usage read - // above. A dropped stream notification can hide a completed spawn: exec's - // backfill at turn completion re-emits only items it saw start, so a - // spawn that lost both notifications, or whose backfill failed, stays out - // of the stream's count, and an unadmitted spawn could balance it. A - // delegating run therefore fails on any drop, a failed backfill, or a - // debug log the runner could not read; a run without roles has the - // multi-agent tools off and only warns. + // above. Each iteration adds its spawns seen on either side, each counted + // once per thread: the stream's spawn items (completed or failed: each + // passed the guard) and the children on disk. A dropped stream + // notification is a warning: it can hide a spawn item, but not the + // child's rollout. if stderr.Dropped > 0 { msg := fmt.Sprintf("codex dropped %d stream notification(s) under backpressure", stderr.Dropped) if stderr.BackfillFailed > 0 { @@ -717,14 +726,16 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri } printer.StepWarn(msg + "; the progress log is incomplete") } - if digests.delegating() && (stderr.Dropped > 0 || stderr.BackfillFailed > 0 || dropsUnread) { - return exitCode, fmt.Errorf("%s: codex dropped a stream notification, or its backfill of the turn's items failed or could not be checked, so a lost spawn_agent item cannot be ruled out", codexSpawnWithoutAdmission) - } if childIDs.UnreadSpawn { return exitCode, fmt.Errorf("%s: a spawn_agent item longer than %d bytes could not be read", codexSpawnWithoutAdmission, streamBufSize) } - if len(childIDs.Senders) > 0 { - digests.CompletedSpawns += len(childIDs.Senders) + if rolloutsErr != nil { + return exitCode, fmt.Errorf("%s: counting the child rollouts: %w", codexSpawnWithoutAdmission, rolloutsErr) + } + spawned := slices.Compact(slices.Sorted(slices.Values(slices.Concat(childIDs.Receivers, diskIDs)))) + union := len(spawned) + childIDs.NoReceiver + (diskChildren - len(diskIDs)) + if children := max(len(childIDs.Senders), diskChildren, union); checkSpawns && children > 0 { + digests.CompletedSpawns += children recordRunnerHeldDigests(params.SandboxName, digests) if err := checkCodexSpawnAdmissions(params.SandboxName, primaryThreadID, childIDs.Senders, digests.CompletedSpawns); err != nil { return exitCode, err diff --git a/internal/runtime/codex_run_test.go b/internal/runtime/codex_run_test.go index 868b5ec3d1..015c58a952 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, "", "") 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.go b/internal/runtime/codex_subagents.go index 1110ddb545..af8635c9b4 100644 --- a/internal/runtime/codex_subagents.go +++ b/internal/runtime/codex_subagents.go @@ -141,8 +141,17 @@ func parseCodexChildUsage(data []byte) []codexChildUsage { // A final line without a newline waits for flush, once the stream has ended: // codex killed mid-write can leave a completed spawn there. type codexChildIDs struct { - IDs []string + // IDs are the receivers of completed spawn items, for the usage fold. + IDs []string + // Senders has one entry per spawn item the handler finished, completed + // or failed: the stream side of the admission count. Senders []string + // Receivers are the receivers of every finished spawn item, completed or + // failed, and NoReceiver counts the finished items that name none (a + // spawn codex refused before a thread existed): with the children on + // disk they count each spawn once, whichever side saw it. + Receivers []string + NoReceiver int // UnreadSpawn marks a line too long to scan that opened as a spawn_agent // item: whether that spawn completed is unknown, so the run fails. UnreadSpawn bool @@ -192,8 +201,9 @@ func (c *codexChildIDs) take(b []byte) { const codexStderrDefaultFilter = "error,opentelemetry_sdk=off,opentelemetry_otlp=off" // codexDroppedNotification is the line codex logs, at warn, when its -// in-process channel is full and it drops a stream notification: an item -// then never reaches `exec --json`, and a completed spawn may be among them. +// in-process channel is full and it drops a notification, of any thread +// (children included); the line does not say which. A completed spawn may be +// among them. const codexDroppedNotification = "dropping in-process server notification (queue full)" // codexBackfillFailed starts the line exec logs, at warn, when the read of @@ -242,13 +252,16 @@ func (c *codexStderrDrops) flush() { // codexCountDroppedInLog counts codexDroppedNotification and // codexBackfillFailed in the sandbox debug log, where codex's stderr goes -// under --debug instead of the host. A log that is missing or has no such -// line counts zero; a command that did not finish (the script itself always -// exits 0) is an error, not a zero count. +// under --debug instead of the host. A missing log counts zero, as does a +// log with no such line; a log grep cannot read (unreadable, a directory), a +// command that did not finish, or output that is not two counts is an +// error, not a zero count. func codexCountDroppedInLog(sandboxName string) (dropped, backfillFailed int, err error) { - log := shellQuote(sandbox.SandboxWorkspace + "/" + codexDebugLogFile) - cmd := fmt.Sprintf(`command -p grep -a -c -F -e %s -- %s 2>/dev/null; command -p grep -a -c -F -e %s -- %s 2>/dev/null; true`, - shellQuote(codexDroppedNotification), log, shellQuote(codexBackfillFailed), log) + cmd := fmt.Sprintf(`log=%s; [ -e "$log" ] || { echo 0 0; exit 0; }; `+ + `d=$(command -p grep -a -c -F -e %s -- "$log"); rd=$?; `+ + `b=$(command -p grep -a -c -F -e %s -- "$log"); rb=$?; `+ + `[ "$rd" -le 1 ] && [ "$rb" -le 1 ] || exit 3; echo "$d $b"`, + shellQuote(sandbox.SandboxWorkspace+"/"+codexDebugLogFile), shellQuote(codexDroppedNotification), shellQuote(codexBackfillFailed)) stdout, stderr, exitCode, err := sandbox.Exec(sandboxName, cmd, 10*time.Second) if err != nil { return 0, 0, err @@ -257,11 +270,14 @@ func codexCountDroppedInLog(sandboxName string) (dropped, backfillFailed int, er return 0, 0, fmt.Errorf("exited %d: %s", exitCode, redactSummary(strings.TrimSpace(sanitizeOutput(stderr)))) } counts := strings.Fields(stdout) - if len(counts) > 0 { - dropped, _ = strconv.Atoi(counts[0]) + if len(counts) != 2 { + return 0, 0, fmt.Errorf("read %d counts, want 2", len(counts)) } - if len(counts) > 1 { - backfillFailed, _ = strconv.Atoi(counts[1]) + if dropped, err = strconv.Atoi(counts[0]); err == nil { + backfillFailed, err = strconv.Atoi(counts[1]) + } + if err != nil { + return 0, 0, fmt.Errorf("reading the counts: %w", err) } return dropped, backfillFailed, nil } @@ -288,11 +304,21 @@ func (c *codexChildIDs) scan(line []byte) { } `json:"item"` } if json.Unmarshal(line, &evt) != nil || evt.Type != "item.completed" || evt.Item.Type != "collab_tool_call" || - evt.Item.Tool != "spawn_agent" || evt.Item.Status != "completed" { + evt.Item.Tool != "spawn_agent" || (evt.Item.Status != "completed" && evt.Item.Status != "failed") { return } - c.IDs = append(c.IDs, evt.Item.ReceiverThreadIDs...) + // A failed item is a spawn the handler refused (at the thread limit, for + // one) after the guard admitted it, so it counts against the admissions; + // a spawn the guard blocked never reaches the handler and emits no item. + // Only a completed spawn has a child to fold. + if evt.Item.Status == "completed" { + c.IDs = append(c.IDs, evt.Item.ReceiverThreadIDs...) + } c.Senders = append(c.Senders, evt.Item.SenderThreadID) + c.Receivers = append(c.Receivers, evt.Item.ReceiverThreadIDs...) + if len(evt.Item.ReceiverThreadIDs) == 0 { + c.NoReceiver++ + } } // foldCodexChildUsage adds the parent's entry to m.PerModelUsage, always, so @@ -400,22 +426,24 @@ func (r CodexRuntime) foldCodexChildUsage(sandboxName string, childIDs []string, // The admission cross-check. Codex records no hook outcome in `exec --json` // or the rollout, so a spawn the guard never decided (a starved or failed -// handler lets the call through) is found by comparing two records: the -// completed spawns of the stream, read on the host, and the guard's admission -// lines in the sandbox findings log. The log is agent-writable: a planted or -// duplicated admission only raises the count, so a forged one is not caught, -// while a torn, cut or missing log can only lower it: it can fail a run that -// would have passed, never pass one that would have failed. The stream side -// is not that strict: codex can drop an item notification under -// backpressure, and the completed count is then too low; it says so on its -// stderr, which Run scans (codexStderrDrops). exec's backfill at turn -// completion re-emits only items it saw start, and exec warns when that -// read fails, so a count after any drop or failed backfill cannot be -// trusted: a delegating run fails on either, and a run without roles warns. -// A resume that got through appears in the stream as a wait item, so it is -// not caught, nor is an overlong spawn line whose first bytes do not show -// its type and tool. Counts are compared, not ids: a stream item carries no -// tool_use_id. +// handler lets the call through) is found by comparing the guard's admission +// lines in the sandbox findings log with the spawns seen on either side, +// each counted once per thread: the stream's spawn items, read on the host, +// completed or failed (a blocked spawn emits none; a refused one used its +// admission), and the children's rollouts on disk (countCodexChildRollouts). The log is +// agent-writable: a planted or duplicated admission only raises the count, so +// a forged one is not caught, while a torn, cut or missing log can only lower +// it: it can fail a run that would have passed, never pass one that would +// have failed. Codex can drop a stream notification under backpressure and +// says so on stderr, which Run scans (codexStderrDrops) and warns on: a lost +// spawn item lowers the stream's count but not the rollouts'. A resume that +// got through appears in the stream as a wait item, so it is not caught, nor +// is a spawn hidden from both sides (its stream items lost and its rollout +// deleted or edited), nor an overlong spawn line whose first bytes do not +// show its type and tool. Admissions are compared by count, not id (a stream +// item carries no tool_use_id), so an admission no spawn used (codex rejected +// the call before it emitted an item, or another PreToolUse hook blocked it) +// can cover a later unadmitted spawn. // codexSpawnAdmitFinding is the adapter's SPAWN_ADMIT_FINDING. const codexSpawnAdmitFinding = "codex_spawn_guard_admit" @@ -426,6 +454,123 @@ const codexFindingsLogPath = sandbox.SandboxWorkspace + "/.security/findings.jso // codexSpawnWithoutAdmission starts the cross-check's error. const codexSpawnWithoutAdmission = "codex_spawn_without_admission" +// codexChildRolloutsMarker opens the child-rollout read, so a test double +// can route it; it is a shell no-op. +const codexChildRolloutsMarker = "fullsend-rollout-heads" + +// codexChildRolloutsReadCommand prints, for each *.jsonl under the sessions +// directory (recursively: codex files rollouts under YYYY/MM/DD), one line: +// 1 or 0 for a first line that is or is not a session_meta record, then the +// first `"id":"..."` and `"parent_thread_id":"..."` on that line, or none. +// A child that started a turn writes rollout--.jsonl whose +// first line is its session_meta, carrying parent_thread_id; a root carries +// none (codex rust-v0.159.3). A key quoted inside a string is escaped there, +// so it cannot match. A missing directory prints nothing; a find that fails +// exits 3; head -c bounds each line read and the output. +func codexChildRolloutsReadCommand(sessionsDir string) string { + return fmt.Sprintf(`: %s; d=%s; [ -d "$d" ] || exit 0; files=$(command -p find "$d" -type f -name '*.jsonl') || exit 3; `+ + `printf '%%s\n' "$files" | while IFS= read -r f; do [ -n "$f" ] || continue; `+ + `l=$(command -p head -n 1 -- "$f" 2>/dev/null | command -p head -c %d); `+ + `case $l in *'"type":"session_meta"'*) m=1 ;; *) m=0 ;; esac; `+ + `i=$(printf '%%s' "$l" | command -p grep -o -e '"id":"[0-9a-f-]*"' | command -p head -n 1); `+ + `p=$(printf '%%s' "$l" | command -p grep -o -e '"parent_thread_id":"[0-9a-f-]*"' | command -p head -n 1); `+ + `printf '%%s %%s %%s\n' "$m" "${i:-none}" "${p:-none}"; done | command -p head -c %d`, + codexChildRolloutsMarker, shellQuote(sessionsDir), codexChildUsageMaxBytes, codexChildUsageMaxBytes) +} + +// codexRolloutHead is what the read printed for one rollout file. +type codexRolloutHead struct { + Meta bool + ID, Parent string +} + +// parseCodexRolloutHeads decodes the read's output. A line that is not three +// fields (a cut, a planted file name) counts as a head that is not a +// session_meta record. +func parseCodexRolloutHeads(data []byte) []codexRolloutHead { + value := func(field, key string) string { + v, ok := strings.CutPrefix(field, `"`+key+`":"`) + if !ok { + return "" + } + return strings.TrimSuffix(v, `"`) + } + var heads []codexRolloutHead + for line := range bytes.Lines(data) { + fields := strings.Fields(string(line)) + if len(fields) == 0 { + continue + } + if len(fields) != 3 { + heads = append(heads, codexRolloutHead{}) + continue + } + heads = append(heads, codexRolloutHead{Meta: fields[0] == "1", ID: value(fields[1], "id"), Parent: value(fields[2], "parent_thread_id")}) + } + return heads +} + +// countCodexChildRollouts counts the iteration's children on disk: a file +// whose parent is the primary thread, or a child already counted (a +// grandchild that got past the guard), and a file whose first line is not a +// session_meta record. A root (no parent) and a file of another parent are +// not counted: a previous iteration's files left by a failed clear, or a +// root the agent's own codex exec wrote under the exported CODEX_HOME. The +// ids returned are the counted children's, for the usage fold. With a +// primary id that is not a thread id, any file that could be a child is an +// error rather than a count of zero. +func countCodexChildRollouts(heads []codexRolloutHead, primary string) (int, []string, error) { + if !codexChildUsageThreadID.MatchString(primary) { + for _, h := range heads { + if !h.Meta || h.Parent != "" { + return 0, nil, fmt.Errorf("the run's primary thread id is unknown, so its child rollouts cannot be told apart") + } + } + return 0, nil, nil + } + parents := map[string]bool{primary: true} + counted := make([]bool, len(heads)) + n := 0 + var ids []string + for i, h := range heads { + if !h.Meta { + counted[i] = true + n++ + } + } + for changed := true; changed; { + changed = false + for i, h := range heads { + if counted[i] || h.Parent == "" || !parents[h.Parent] { + continue + } + counted[i], changed = true, true + n++ + if codexChildUsageThreadID.MatchString(h.ID) && !parents[h.ID] { + parents[h.ID] = true + ids = append(ids, h.ID) + } + } + } + return n, ids, nil +} + +// readCodexChildRollouts runs the read and counts. Unlike the usage read, a +// read that fails, times out or is cut is an error: this is a policy check. +func (r CodexRuntime) readCodexChildRollouts(sandboxName, primary string) (int, []string, error) { + stdout, stderr, exitCode, err := sandbox.Exec(sandboxName, codexChildRolloutsReadCommand(r.codexSessionsDir()), 10*time.Second) + if err != nil { + return 0, nil, err + } + if exitCode != 0 { + return 0, nil, fmt.Errorf("exited %d: %s", exitCode, redactSummary(strings.TrimSpace(sanitizeOutput(stderr)))) + } + if len(stdout) >= codexChildUsageMaxBytes { + return 0, nil, fmt.Errorf("the read was cut at %d bytes", codexChildUsageMaxBytes) + } + return countCodexChildRollouts(parseCodexRolloutHeads([]byte(stdout)), primary) +} + // codexSpawnAdmissionsReadCommand prints the findings log's lines that name // an admission, bounded like the usage read. A log grep cannot open prints // nothing and exits 0: the pipeline's status is head's. @@ -465,7 +610,7 @@ func compareCodexSpawnAdmissions(primary string, senders []string, completed, ad } } if completed > admitted { - return fmt.Errorf("%s: %d completed spawn(s) in this run's stream(s) but %d recorded admission(s)", + return fmt.Errorf("%s: %d spawn(s) in this run (the stream's spawn items and the child rollouts on disk, each child counted once) but %d recorded admission(s)", codexSpawnWithoutAdmission, completed, admitted) } return nil diff --git a/internal/runtime/codex_subagents_test.go b/internal/runtime/codex_subagents_test.go index 6bde902a62..deada9a4cd 100644 --- a/internal/runtime/codex_subagents_test.go +++ b/internal/runtime/codex_subagents_test.go @@ -62,14 +62,19 @@ var codexChildFixtures = map[string]string{ codexChildForkedID: "child_usage_forked.jsonl", } +// codexRootRolloutHead is the first line of collab_spawn.ndjson's root +// rollout: a session_meta record with no parent. +const codexRootRolloutHead = `{"timestamp":"2026-09-29T15:46:30.000Z","type":"session_meta","payload":{"id":"` + codexRootThreadID + `","cwd":"/sandbox/workspace/repo","originator":"codex_exec","cli_version":"0.159.3"}}` + "\n" + // writeCodexChildRollouts lays the child fixtures out as codex would under a -// sessions directory (YYYY/MM/DD/rollout--.jsonl) and -// returns that directory. +// sessions directory (YYYY/MM/DD/rollout--.jsonl), beside +// the root thread's own rollout, and returns that directory. func writeCodexChildRollouts(t *testing.T, ids ...string) string { t.Helper() sessions := filepath.Join(t.TempDir(), "sessions") day := filepath.Join(sessions, "2026", "09", "29") require.NoError(t, os.MkdirAll(day, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(day, "rollout-2026-09-29T15-46-30-"+codexRootThreadID+".jsonl"), []byte(codexRootRolloutHead), 0o644)) for _, id := range ids { name := "rollout-2026-09-29T15-46-38-" + id + ".jsonl" require.NoError(t, os.WriteFile(filepath.Join(day, name), readCodexFixture(t, codexChildFixtures[id]), 0o644)) @@ -275,8 +280,10 @@ func TestCodexChildIDs_CollectsCompletedSpawns(t *testing.T) { assert.Equal(t, want, whole.IDs, "the three completed spawns in stream order; the failed spawn's receiver is not a child; wait and close items name no new thread") assert.NotContains(t, whole.IDs, codexChildFailedSpawnID) - assert.Equal(t, []string{codexRootThreadID, codexRootThreadID, codexRootThreadID}, whole.Senders, - "one sender per completed spawn; the failed spawn is not counted") + assert.Equal(t, []string{codexRootThreadID, codexRootThreadID, codexRootThreadID, codexRootThreadID}, whole.Senders, + "one sender per handled spawn item: the three completed and the failed one, which passed the guard") + assert.Equal(t, []string{codexChildSameModelID, codexChildOtherModelID, codexChildFailedID, codexChildFailedSpawnID}, whole.Receivers, "every handled item's receivers, for counting") + assert.Zero(t, whole.NoReceiver) chunked := &codexChildIDs{} for i := 0; i < len(stream); i += 7 { @@ -284,7 +291,7 @@ func TestCodexChildIDs_CollectsCompletedSpawns(t *testing.T) { require.NoError(t, err) } assert.Equal(t, want, chunked.IDs, "lines are reassembled across Write calls, as a TeeReader delivers them") - assert.Len(t, chunked.Senders, 3) + assert.Len(t, chunked.Senders, 4) } func TestCodexChildIDs_SkipsOverlongLine(t *testing.T) { @@ -368,7 +375,10 @@ func TestParseCodexStream_FailedCollabItem(t *testing.T) { // SIGKILL, as the budget's context kill ends it); FULLSEND_TEST_CODEX_DROP=1 // prints codex's dropped-notification warning on stderr before the stream, // FULLSEND_TEST_CODEX_BACKFILL_FAIL=1 exec's failed-backfill warning; -// FULLSEND_TEST_DEBUG_LOG_READ_FAIL=1 makes the debug-log read exit 1. +// FULLSEND_TEST_DEBUG_LOG_READ_FAIL=1 makes the debug-log read exit 1, and +// =garbled print one count instead of two; FULLSEND_TEST_ROLLOUTS_READ_FAIL=1 +// makes the child-rollout read exit 1. The child-rollout read runs under sh +// against sessionsDir. func fakeOpenshellCodexChildren(t *testing.T, logPath, storeDir, streamFixture, sessionsDir string) { t.Helper() binDir := t.TempDir() @@ -379,6 +389,9 @@ if [ "$2" = "exec" ]; then case "$last" in cat\ *) f=$(printf '%s' "${last#cat }" | tr -d "'" | tr '/' '_'); cat '` + storeDir + `'/"$f"; exit $? ;; *"exec --json"*) [ "${FULLSEND_TEST_CODEX_DROP:-}" = 1 ] && echo "2026-10-22T16:00:00Z WARN codex_app_server::in_process: ` + codexDroppedNotification + `" >&2; [ "${FULLSEND_TEST_CODEX_BACKFILL_FAIL:-}" = 1 ] && echo "2026-10-22T16:00:01Z WARN codex_exec: ` + codexBackfillFailed + ` for turn completion: boom" >&2; cat '` + streamFixture + `'; [ "${FULLSEND_TEST_CODEX_EXIT:-}" = killed ] && kill -9 $$; exit "${FULLSEND_TEST_CODEX_EXIT:-0}" ;; + *` + codexChildRolloutsMarker + `*) + if [ "${FULLSEND_TEST_ROLLOUTS_READ_FAIL:-}" = 1 ]; then echo "fake openshell: refusing the rollouts read" >&2; exit 1; fi + sh -c "$(printf '%s' "$last" | sed 's#` + CodexRuntime{}.codexSessionsDir() + `#` + sessionsDir + `#g')"; exit $? ;; *` + codexChildUsageMarker + `*) if [ "${FULLSEND_TEST_CHILD_READ_FAIL:-}" = 1 ]; then echo "fake openshell: refusing the rollout read${FULLSEND_TEST_CHILD_READ_STDERR:+ $FULLSEND_TEST_CHILD_READ_STDERR}" >&2; exit 1; fi sh -c "$(printf '%s' "$last" | sed 's#` + CodexRuntime{}.codexSessionsDir() + `#` + sessionsDir + `#g')"; rc=$? @@ -391,6 +404,7 @@ if [ "$2" = "exec" ]; then exit $rc ;; *` + codexDebugLogFile + `*) if [ "${FULLSEND_TEST_DEBUG_LOG_READ_FAIL:-}" = 1 ]; then echo "fake openshell: refusing the log read" >&2; exit 1; fi + if [ "${FULLSEND_TEST_DEBUG_LOG_READ_FAIL:-}" = garbled ]; then echo 7; exit 0; fi sh -c "$(printf '%s' "$last" | sed 's#` + sandbox.SandboxWorkspace + "/" + codexDebugLogFile + `#` + filepath.Join(filepath.Dir(sessionsDir), codexDebugLogFile) + `#g')"; exit $? ;; esac exit 0 @@ -792,7 +806,7 @@ func runCodexWithChildren(t *testing.T, streamFixture string, delegating bool, a // A spawn in the stream alone (no RoleFiles) triggers the read. func TestCodexRun_FoldsChildUsage(t *testing.T) { - metrics, exit, out, log := runCodexWithChildren(t, "collab_spawn.ndjson", false, 3) + metrics, exit, out, log := runCodexWithChildren(t, "collab_spawn.ndjson", false, 4) assert.Equal(t, 0, exit) assert.Equal(t, "gpt-5.6-luna", metrics.Model) @@ -808,9 +822,10 @@ func TestCodexRun_FoldsChildUsage(t *testing.T) { assert.Contains(t, out, "2 sub-agent thread(s) folded into the run metrics") assert.Equal(t, 1, strings.Count(log, codexChildUsageMarker), "one read command, after the run") assert.Equal(t, 1, strings.Count(log, codexSpawnAdmitFinding), "and one admissions read") + assert.Equal(t, 1, strings.Count(log, codexChildRolloutsMarker), "and one read of the children on disk") d, ok := lookupRunnerHeldDigests("sb") require.True(t, ok) - assert.Equal(t, 3, d.CompletedSpawns, "the run's count, kept for a retry") + assert.Equal(t, 4, d.CompletedSpawns, "the run's count, kept for a retry: four handled spawn items (one failed) beat three child rollouts") assert.Contains(t, log, shellQuote(codexChildFailedID), "the failed child's rollout is read too; it is its content that contributes nothing") assert.NotContains(t, log, codexChildFailedSpawnID, "the failed spawn's receiver is never looked up") } @@ -848,7 +863,7 @@ func TestCodexRun_ChildReadFailureIsAWarning(t *testing.T) { token := "ghp_" + strings.Repeat("B", 36) t.Setenv("FULLSEND_TEST_CHILD_READ_FAIL", "1") t.Setenv("FULLSEND_TEST_CHILD_READ_STDERR", token) - metrics, exit, out, _ := runCodexWithChildren(t, "collab_spawn.ndjson", false, 3) + metrics, exit, out, _ := runCodexWithChildren(t, "collab_spawn.ndjson", false, 4) assert.Equal(t, 0, exit, "losing the children's tokens must not fail an iteration that succeeded") assert.Contains(t, out, "! Sub-agent usage not fully counted: reading the child rollouts: exited 1: fake openshell: refusing the rollout read") @@ -865,7 +880,7 @@ func TestCodexRun_ChildReadFailureIsAWarning(t *testing.T) { // breakdown still sums to the totals. func TestCodexRun_NonZeroExitStillReadsTheChildren(t *testing.T) { t.Setenv("FULLSEND_TEST_CODEX_EXIT", "137") - failed, exit, out, log := runCodexWithChildren(t, "collab_spawn.ndjson", true, 3) + failed, exit, out, log := runCodexWithChildren(t, "collab_spawn.ndjson", true, 4) assert.Equal(t, 137, exit) assert.Equal(t, map[string]ModelUsage{ @@ -878,7 +893,7 @@ func TestCodexRun_NonZeroExitStillReadsTheChildren(t *testing.T) { assertCodexUsageSumsToTotals(t, failed) t.Setenv("FULLSEND_TEST_CODEX_EXIT", "0") - retry, exit, _, _ := runCodexWithChildren(t, "collab_spawn.ndjson", true, 3) + retry, exit, _, _ := runCodexWithChildren(t, "collab_spawn.ndjson", true, 4) require.Equal(t, 0, exit) assertCodexUsageSumsToTotals(t, sumCodexIterations(failed, retry)) assert.NotContains(t, out, "may be undercounted", "codex exited on its own; its children were done") @@ -891,7 +906,7 @@ func TestCodexRun_BudgetStopWarnsOfLaterChildUsage(t *testing.T) { for exitEnv, want := range map[string]int{"killed": -1, "124": 124} { t.Run(exitEnv, func(t *testing.T) { t.Setenv("FULLSEND_TEST_CODEX_EXIT", exitEnv) - _, exit, out, _ := runCodexWithChildren(t, "collab_spawn.ndjson", false, 3) + _, exit, out, _ := runCodexWithChildren(t, "collab_spawn.ndjson", false, 4) assert.Equal(t, want, exit) assert.Contains(t, out, "2 sub-agent thread(s) folded into the run metrics") @@ -941,9 +956,9 @@ func TestCompareCodexSpawnAdmissions(t *testing.T) { {"equal counts", root, []string{root, root, root}, 3, 3, ""}, {"more admissions: an admitted spawn codex then refused", root, []string{root, root}, 2, 3, ""}, {"one completed spawn more than admissions", root, []string{root, root, root}, 3, 2, - "codex_spawn_without_admission: 3 completed spawn(s) in this run's stream(s) but 2 recorded admission(s)"}, + "codex_spawn_without_admission: 3 spawn(s) in this run (the stream's spawn items and the child rollouts on disk, each child counted once) but 2 recorded admission(s)"}, {"an earlier iteration's spawns count", root, []string{root}, 4, 3, - "codex_spawn_without_admission: 4 completed spawn(s) in this run's stream(s) but 3 recorded admission(s)"}, + "codex_spawn_without_admission: 4 spawn(s) in this run (the stream's spawn items and the child rollouts on disk, each child counted once) but 3 recorded admission(s)"}, {"a sender that is not the primary thread", root, []string{root, codexChildSameModelID}, 2, 3, "codex_spawn_without_admission: a completed spawn was not sent by the primary thread"}, {"a spawn item without a sender", root, []string{""}, 1, 3, @@ -991,7 +1006,7 @@ func TestCheckCodexSpawnAdmissions_ThroughTheSandbox(t *testing.T) { want string }{ "every completed spawn admitted": {three, 3, ""}, - "spawns, no findings log": {three[:1], 0, "1 completed spawn(s) in this run's stream(s) but 0 recorded admission(s)"}, + "spawns, no findings log": {three[:1], 0, "1 spawn(s) in this run (the stream's spawn items and the child rollouts on disk, each child counted once) but 0 recorded admission(s)"}, } { t.Run(name, func(t *testing.T) { sessions := writeCodexChildRollouts(t) @@ -1051,8 +1066,8 @@ func TestCodexRun_SpawnWithoutAdmissionFailsTheRun(t *testing.T) { t.Setenv("FULLSEND_TEST_CODEX_EXIT", exitEnv) metrics, exit, out, log, err := tryCodexRunWithChildren(t, "collab_spawn.ndjson", true, 2) - assert.EqualError(t, err, "codex_spawn_without_admission: 3 completed spawn(s) in this run's stream(s) but 2 recorded admission(s)", - "the failed spawn of the fixture is not counted") + assert.EqualError(t, err, "codex_spawn_without_admission: 4 spawn(s) in this run (the stream's spawn items and the child rollouts on disk, each child counted once) but 2 recorded admission(s)", + "the fixture's failed spawn is counted: codex refused it after the guard admitted it") assert.Equal(t, want, exit) assert.Contains(t, out, "2 sub-agent thread(s) folded into the run metrics", "the fold ran first") assert.Equal(t, 1, strings.Count(log, codexSpawnAdmitFinding)) @@ -1064,11 +1079,11 @@ func TestCodexRun_SpawnWithoutAdmissionFailsTheRun(t *testing.T) { // The count spans the run: the findings log keeps the earlier iterations' // admissions, so a retry's spawns need admissions of their own. func TestCodexRun_RetrySpawnsNeedTheirOwnAdmissions(t *testing.T) { - runCodexWithChildren(t, "collab_spawn.ndjson", false, 3) + runCodexWithChildren(t, "collab_spawn.ndjson", false, 4) var out bytes.Buffer _, err := CodexRuntime{}.Run(context.Background(), codexChildrenRunParams, ui.New(&out), time.Now(), &RunMetrics{}) - assert.EqualError(t, err, "codex_spawn_without_admission: 6 completed spawn(s) in this run's stream(s) but 3 recorded admission(s)") + assert.EqualError(t, err, "codex_spawn_without_admission: 8 spawn(s) in this run (the stream's spawn items and the child rollouts on disk, each child counted once) but 4 recorded admission(s)") } func TestCodexChildIDs_FlushScansTheTornLastLine(t *testing.T) { @@ -1173,43 +1188,27 @@ func TestCodexStderrDrops_CountsAcrossChunks(t *testing.T) { assert.Equal(t, 1, last.Dropped, "the last line is scanned once the stream has ended") } -// A dropped stream notification can hide a spawn exec's backfill does not -// bring back (one that lost both notifications): a run without roles warns -// and the cross-check runs on what the stream carried; a delegating run -// fails before it. -func TestCodexRun_DroppedNotificationFailsADelegatingRun(t *testing.T) { +// A dropped stream notification is a warning, for a delegating run too: it +// can hide a spawn item, not the child's rollout, which the admission check +// counts as well (#8712: most drops lose nothing the count needs). +func TestCodexRun_DroppedNotificationWarns(t *testing.T) { t.Setenv("FULLSEND_TEST_CODEX_DROP", "1") - _, exit, out, log := runCodexWithChildren(t, "collab_spawn.ndjson", false, 3) - assert.Equal(t, 0, exit) - assert.Contains(t, out, "! codex dropped 1 stream notification(s) under backpressure; the progress log is incomplete") - assert.Equal(t, 1, strings.Count(log, codexSpawnAdmitFinding)) - - _, _, out, log, err := tryCodexRunWithChildren(t, "collab_spawn.ndjson", true, 3) - require.Error(t, err) - assert.Contains(t, err.Error(), codexSpawnWithoutAdmission+": codex dropped a stream notification") - assert.Contains(t, out, "! codex dropped 1 stream notification(s) under backpressure", "the warning still says what codex reported") - assert.Zero(t, strings.Count(log, codexSpawnAdmitFinding), "the cross-check is not run on a count it cannot trust") + for _, delegating := range []bool{false, true} { + _, exit, out, log := runCodexWithChildren(t, "collab_spawn.ndjson", delegating, 4) + assert.Equal(t, 0, exit) + assert.Contains(t, out, "! codex dropped 1 stream notification(s) under backpressure; the progress log is incomplete") + assert.Equal(t, 1, strings.Count(log, codexSpawnAdmitFinding), "the cross-check still runs") + } } -// A failed backfill leaves a dropped spawn item lost, so the stream's count -// can be short and an unadmitted spawn balance it: a delegating run fails, -// with or without a drop line, and a run with no roles only warns. -func TestCodexRun_FailedBackfillFailsADelegatingRun(t *testing.T) { +// A failed backfill leaves a dropped completed item lost from the stream; +// the warning says so, and the child's rollout still counts it. +func TestCodexRun_FailedBackfillWarns(t *testing.T) { t.Setenv("FULLSEND_TEST_CODEX_DROP", "1") t.Setenv("FULLSEND_TEST_CODEX_BACKFILL_FAIL", "1") - _, exit, out, _ := runCodexWithChildren(t, "collab_spawn.ndjson", false, 3) + _, exit, out, _ := runCodexWithChildren(t, "collab_spawn.ndjson", true, 4) assert.Equal(t, 0, exit) assert.Contains(t, out, "! codex dropped 1 stream notification(s) under backpressure, and its backfill of the turn's items failed, so a dropped completed item stayed lost; the progress log is incomplete") - - _, _, out, _, err := tryCodexRunWithChildren(t, "collab_spawn.ndjson", true, 3) - require.Error(t, err) - assert.Contains(t, err.Error(), codexSpawnWithoutAdmission+": codex dropped a stream notification, or its backfill of the turn's items failed or could not be checked") - assert.Contains(t, out, "and its backfill of the turn's items failed", "the warning still says what codex reported") - - t.Setenv("FULLSEND_TEST_CODEX_DROP", "") - _, _, _, _, err = tryCodexRunWithChildren(t, "collab_spawn.ndjson", true, 3) - require.Error(t, err, "a failed backfill alone fails it too") - assert.Contains(t, err.Error(), codexSpawnWithoutAdmission) } // Under --debug codex's stderr goes to the sandbox log, which is read back. @@ -1233,16 +1232,62 @@ func TestCodexRun_DroppedNotificationInTheDebugLog(t *testing.T) { assert.Contains(t, readFileString(t, logPath), "grep -a -c -F", "the counts came from the sandbox log") } -// Under --debug a log read that did not finish is no zero count: a run with -// no roles warns, and a delegating run fails, since a failed backfill cannot -// be ruled out. -func TestCodexRun_UnreadDebugLogFailsADelegatingRun(t *testing.T) { - t.Setenv("FULLSEND_TEST_DEBUG_LOG_READ_FAIL", "1") +// Under --debug a log the runner could not read is no zero count: the run +// says so, for a delegating agent too, whose admission check rests on the +// children on disk. The directory case runs the real script under sh: grep +// cannot read a directory, and its status is kept. +func TestCodexRun_UnreadDebugLogWarns(t *testing.T) { + for name, tc := range map[string]struct { + env, warn string + dirAtLog bool + }{ + "openshell exits 1": {env: "1", warn: "exited 1: fake openshell: refusing the log read"}, + "a directory at the log": {dirAtLog: true, warn: "exited 3: "}, + "output that is no counts": {env: "garbled", warn: "read 1 counts, want 2"}, + } { + t.Run(name, func(t *testing.T) { + t.Setenv("FULLSEND_TEST_DEBUG_LOG_READ_FAIL", tc.env) + storeDir := t.TempDir() + r := CodexRuntime{} + seedCodexManifest(t, storeDir, r, nil) + sessions := writeCodexChildRollouts(t) + if tc.dirAtLog { + require.NoError(t, os.Mkdir(filepath.Join(filepath.Dir(sessions), codexDebugLogFile), 0o755)) + } + fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), storeDir, filepath.Join("testdata", "codex", "basic_run.ndjson"), sessions) + params := codexChildrenRunParams + params.Debug = "1" + + for _, delegating := range []bool{false, true} { + if delegating { + d, ok := lookupRunnerHeldDigests("sb") + require.True(t, ok) + d.RoleFiles = map[string]string{"default": "d0d0", "explore": "e0e0"} + recordRunnerHeldDigests("sb", d) + } + var out bytes.Buffer + exit, err := r.Run(context.Background(), params, ui.New(&out), time.Now(), &RunMetrics{}) + require.NoError(t, err) + assert.Equal(t, 0, exit) + assert.Contains(t, out.String(), "! Could not read codex's log for dropped stream notifications: "+tc.warn) + } + }) + } +} + +// A missing debug log (the agent may delete it) counts zero, as before: a +// delegating run passes, with no warning about the read. +func TestCodexRun_MissingDebugLogCountsZero(t *testing.T) { storeDir := t.TempDir() r := CodexRuntime{} seedCodexManifest(t, storeDir, r, nil) + d, ok := lookupRunnerHeldDigests("sb") + require.True(t, ok) + d.RoleFiles = map[string]string{"default": "d0d0", "explore": "e0e0"} + recordRunnerHeldDigests("sb", d) sessions := writeCodexChildRollouts(t) - fakeOpenshellCodexChildren(t, filepath.Join(t.TempDir(), "openshell.log"), storeDir, filepath.Join("testdata", "codex", "basic_run.ndjson"), sessions) + logPath := filepath.Join(t.TempDir(), "openshell.log") + fakeOpenshellCodexChildren(t, logPath, storeDir, filepath.Join("testdata", "codex", "basic_run.ndjson"), sessions) params := codexChildrenRunParams params.Debug = "1" @@ -1250,13 +1295,285 @@ func TestCodexRun_UnreadDebugLogFailsADelegatingRun(t *testing.T) { exit, err := r.Run(context.Background(), params, ui.New(&out), time.Now(), &RunMetrics{}) require.NoError(t, err) assert.Equal(t, 0, exit) - assert.Contains(t, out.String(), "! Could not read codex's log for dropped stream notifications: exited 1: fake openshell: refusing the log read") + assert.NotContains(t, out.String(), "Could not read codex's log") + assert.Contains(t, readFileString(t, logPath), codexDebugLogFile, "the log read ran") +} - d, ok := lookupRunnerHeldDigests("sb") - require.True(t, ok) - d.RoleFiles = map[string]string{"default": "d0d0", "explore": "e0e0"} - recordRunnerHeldDigests("sb", d) - _, err = r.Run(context.Background(), params, ui.New(&out), time.Now(), &RunMetrics{}) - require.Error(t, err) - assert.Contains(t, err.Error(), codexSpawnWithoutAdmission+": codex dropped a stream notification, or its backfill of the turn's items failed or could not be checked") +// codexRolloutLine is a rollout's first line: a session_meta record for id, +// with parent_thread_id when parent is set. +func codexRolloutLine(id, parent string) string { + extra := "" + if parent != "" { + extra = `,"parent_thread_id":"` + parent + `","agent_role":"default"` + } + 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" +} + +// writeCodexRollout writes one more rollout under sessions/. +func writeCodexRollout(t *testing.T, sessions, day, id, content string) { + t.Helper() + dir := filepath.Join(sessions, day) + require.NoError(t, os.MkdirAll(dir, 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "rollout-2026-09-29T15-46-40-"+id+".jsonl"), []byte(content), 0o644)) +} + +// codexStreamWithout returns collab_spawn.ndjson without the lines that +// contain drop, written to a temp file: a stream that lost those items. +func codexStreamWithout(t *testing.T, drop string) string { + t.Helper() + var kept [][]byte + for _, line := range bytes.Split(readCodexFixture(t, "collab_spawn.ndjson"), []byte("\n")) { + if !bytes.Contains(line, []byte(drop)) { + kept = append(kept, line) + } + } + path := filepath.Join(t.TempDir(), "stream.ndjson") + require.NoError(t, os.WriteFile(path, bytes.Join(kept, []byte("\n")), 0o600)) + return path +} + +// runCodexChildrenCase runs Run against the fake with stream, the given +// child rollouts and admissions, after setup has added files under the +// sessions directory. +func runCodexChildrenCase(t *testing.T, stream string, delegating bool, admitted int, children []string, setup func(sessions string)) (*RunMetrics, string, string, error) { + t.Helper() + logPath := filepath.Join(t.TempDir(), "openshell.log") + storeDir := t.TempDir() + r := CodexRuntime{} + seedCodexManifest(t, storeDir, r, nil) + if delegating { + d, ok := lookupRunnerHeldDigests("sb") + require.True(t, ok) + d.RoleFiles = map[string]string{"default": "d0d0", "explore": "e0e0"} + recordRunnerHeldDigests("sb", d) + } + sessions := writeCodexChildRollouts(t, children...) + writeCodexSpawnAdmissions(t, sessions, admitted) + if setup != nil { + setup(sessions) + } + if !filepath.IsAbs(stream) { + stream = filepath.Join("testdata", "codex", stream) + } + fakeOpenshellCodexChildren(t, logPath, storeDir, stream, sessions) + var out bytes.Buffer + metrics := &RunMetrics{} + _, err := r.Run(context.Background(), codexChildrenRunParams, ui.New(&out), time.Now(), metrics) + return metrics, out.String(), readFileString(t, logPath), err +} + +// countCodexChildRollouts counts children of the primary thread and of +// counted children, and files whose first line is not a session_meta record; +// roots and other parents are not children of this iteration. +func TestCountCodexChildRollouts(t *testing.T) { + t.Parallel() + const ( + root, other = codexRootThreadID, "01a06300-0000-7000-8000-0000000000ff" + a1, a2, g1 = codexChildSameModelID, codexChildOtherModelID, "01a06300-0000-7000-8000-0000000000b1" + o1 = "01a06300-0000-7000-8000-0000000000c1" + ) + tests := []struct { + name string + heads []codexRolloutHead + primary string + want int + wantIDs []string + wantErr string + }{ + {"root and two children", []codexRolloutHead{{Meta: true, ID: root}, {Meta: true, ID: a1, Parent: root}, {Meta: true, ID: a2, Parent: root}}, root, 2, []string{a1, a2}, ""}, + {"a previous iteration's root and child are not counted", []codexRolloutHead{{Meta: true, ID: root}, {Meta: true, ID: other}, {Meta: true, ID: o1, Parent: other}}, root, 0, nil, ""}, + {"a root with no parent is not counted", []codexRolloutHead{{Meta: true, ID: root}, {Meta: true, ID: other}}, root, 0, nil, ""}, + {"a grandchild of a counted child is counted", []codexRolloutHead{{Meta: true, ID: g1, Parent: a1}, {Meta: true, ID: a1, Parent: root}}, root, 2, []string{a1, g1}, ""}, + {"a first line that is not session_meta is counted", []codexRolloutHead{{Meta: true, ID: root}, {}}, root, 1, nil, ""}, + {"empty primary with a child-shaped file", []codexRolloutHead{{Meta: true, ID: a1, Parent: root}}, "", 0, nil, "the run's primary thread id is unknown"}, + {"empty primary with an undecodable file", []codexRolloutHead{{}}, "", 0, nil, "the run's primary thread id is unknown"}, + {"empty primary with roots only", []codexRolloutHead{{Meta: true, ID: root}}, "", 0, nil, ""}, + {"a primary that is not a thread id", []codexRolloutHead{{Meta: true, ID: a1, Parent: "x"}}, "x", 0, nil, "the run's primary thread id is unknown"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got, ids, err := countCodexChildRollouts(tt.heads, tt.primary) + if tt.wantErr != "" { + require.ErrorContains(t, err, tt.wantErr) + return + } + require.NoError(t, err) + assert.Equal(t, tt.want, got) + assert.ElementsMatch(t, tt.wantIDs, ids) + }) + } +} + +// The read command under /bin/sh: recursive over date directories, one line +// per file, a quoted key inside a string inert, an undecodable first line +// marked, a missing directory empty, and a find that cannot read a directory +// exits 3. +func TestCodexChildRolloutsReadCommand_UnderSh(t *testing.T) { + t.Parallel() + 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/09/30", "01a06300-0000-7000-8000-0000000000ee", "not json\n") + out, err := exec.Command("/bin/sh", "-c", codexChildRolloutsReadCommand(sessions)).Output() + require.NoError(t, err) + n, ids, err := countCodexChildRollouts(parseCodexRolloutHeads(out), codexRootThreadID) + require.NoError(t, err) + assert.Equal(t, 3, n, "two children across two date directories and one undecodable file; the root is not counted") + assert.ElementsMatch(t, []string{codexChildSameModelID, codexChildOtherModelID}, ids) + + out, err = exec.Command("/bin/sh", "-c", codexChildRolloutsReadCommand(filepath.Join(t.TempDir(), "missing"))).Output() + require.NoError(t, err) + assert.Empty(t, out) + + if os.Geteuid() != 0 { + locked := filepath.Join(sessions, "locked") + require.NoError(t, os.Mkdir(locked, 0o000)) + t.Cleanup(func() { _ = os.Chmod(locked, 0o755) }) + cmd := exec.Command("/bin/sh", "-c", codexChildRolloutsReadCommand(sessions)) + err = cmd.Run() + var exitErr *exec.ExitError + require.ErrorAs(t, err, &exitErr) + assert.Equal(t, 3, exitErr.ExitCode(), "a find that fails is not a count") + } +} + +// The admission check counts per iteration the spawns seen in the stream +// (handled items) or on disk, each child once, for a delegating run even +// when the stream shows no spawn. +func TestCodexRun_AdmissionCheckCountsTheChildrenOnDisk(t *testing.T) { + children := []string{codexChildSameModelID, codexChildOtherModelID, codexChildFailedID} + lostSpawns := func(t *testing.T) string { return codexStreamWithout(t, `"tool":"spawn_agent"`) } + msg := func(n, admitted int) string { + return fmt.Sprintf("codex_spawn_without_admission: %d spawn(s) in this run (the stream's spawn items and the child rollouts on disk, each child counted once) but %d recorded admission(s)", n, admitted) + } + + t.Run("the stream lost every spawn: the files count", func(t *testing.T) { + metrics, _, log, err := runCodexChildrenCase(t, lostSpawns(t), true, 0, children, nil) + assert.EqualError(t, err, msg(3, 0)) + assert.Equal(t, 1, strings.Count(log, codexChildRolloutsMarker)) + assert.Contains(t, metrics.PerModelUsage, "gpt-5.6-terra", "the lost spawn's child is folded from its rollout") + }) + t.Run("the stream lost every spawn, admitted", func(t *testing.T) { + metrics, out, _, err := runCodexChildrenCase(t, lostSpawns(t), true, 3, children, nil) + require.NoError(t, err) + assert.Contains(t, out, "2 sub-agent thread(s) folded into the run metrics", "usage of the children the stream lost is folded") + assertCodexUsageSumsToTotals(t, metrics) + }) + t.Run("a deleted rollout: the stream counts", func(t *testing.T) { + _, _, _, err := runCodexChildrenCase(t, "collab_spawn.ndjson", true, 3, children[:2], nil) + assert.EqualError(t, err, msg(4, 3), "four handled items beat two files") + }) + t.Run("a refused spawn used its admission", func(t *testing.T) { + _, _, _, err := runCodexChildrenCase(t, "collab_spawn.ndjson", true, 3, children, nil) + assert.EqualError(t, err, msg(4, 3)) + }) + t.Run("a child only on disk is not covered by a spawn only in the stream", func(t *testing.T) { + const lost = "01a06300-0000-7000-8000-0000000000d1" + _, _, _, err := runCodexChildrenCase(t, "collab_spawn.ndjson", true, 4, children, func(sessions string) { + writeCodexRollout(t, sessions, "2026/09/29", lost, codexRolloutLine(lost, codexRootThreadID)) + }) + assert.EqualError(t, err, msg(5, 4), "a1-a3 and a9 in the stream, the lost child on disk: five spawns") + }) + t.Run("a refused spawn does not cover a lost child", func(t *testing.T) { + const lost = "01a06300-0000-7000-8000-0000000000d1" + item := func(id, receivers, status string) string { + return `{"type":"item.completed","item":{"id":"` + id + `","type":"collab_tool_call","tool":"spawn_agent","sender_thread_id":"` + codexRootThreadID + `","receiver_thread_ids":[` + receivers + `],"prompt":"p","agents_states":{},"status":"` + status + `"}}` + } + stream := filepath.Join(t.TempDir(), "refused.ndjson") + require.NoError(t, os.WriteFile(stream, []byte(strings.Join([]string{ + `{"type":"thread.started","thread_id":"` + codexRootThreadID + `"}`, `{"type":"turn.started"}`, + item("item_0", `"`+codexChildSameModelID+`"`, "completed"), item("item_1", "", "failed"), + `{"type":"turn.completed","usage":{"input_tokens":1,"cached_input_tokens":0,"cache_write_input_tokens":0,"output_tokens":1,"reasoning_output_tokens":0}}`, + }, "\n")+"\n"), 0o600)) + addLost := func(sessions string) { + writeCodexRollout(t, sessions, "2026/09/29", lost, codexRolloutLine(lost, codexRootThreadID)) + } + _, _, _, err := runCodexChildrenCase(t, stream, true, 2, []string{codexChildSameModelID}, addLost) + assert.EqualError(t, err, msg(3, 2), "the completed spawn, the refused one and the lost child") + _, _, _, err = runCodexChildrenCase(t, stream, true, 3, []string{codexChildSameModelID}, addLost) + require.NoError(t, err) + }) + t.Run("leftovers and another root are not counted", func(t *testing.T) { + _, _, _, err := runCodexChildrenCase(t, lostSpawns(t), true, 3, children, func(sessions string) { + const prev = "01a06300-0000-7000-8000-0000000000ff" + writeCodexRollout(t, sessions, "2026/09/28", prev, codexRolloutLine(prev, "")) + writeCodexRollout(t, sessions, "2026/09/28", "01a06300-0000-7000-8000-0000000000c1", codexRolloutLine("01a06300-0000-7000-8000-0000000000c1", prev)) + writeCodexRollout(t, sessions, "2026/09/29", "01a06300-0000-7000-8000-0000000000c2", codexRolloutLine("01a06300-0000-7000-8000-0000000000c2", "")) + }) + require.NoError(t, err) + }) + t.Run("a grandchild and an undecodable file are counted", func(t *testing.T) { + _, _, _, err := runCodexChildrenCase(t, lostSpawns(t), true, 3, children, func(sessions string) { + writeCodexRollout(t, sessions, "2026/09/29", "01a06300-0000-7000-8000-0000000000b1", codexRolloutLine("01a06300-0000-7000-8000-0000000000b1", codexChildSameModelID)) + writeCodexRollout(t, sessions, "2026/09/30", "01a06300-0000-7000-8000-0000000000ee", "torn\n") + }) + assert.EqualError(t, err, msg(5, 3)) + }) + t.Run("an unknown primary thread with a child on disk", func(t *testing.T) { + _, _, _, err := runCodexChildrenCase(t, codexStreamWithout(t, `"type":"thread.started"`), true, 4, children, nil) + require.Error(t, err) + assert.Contains(t, err.Error(), "codex_spawn_without_admission: counting the child rollouts: the run's primary thread id is unknown") + }) + t.Run("the read fails", func(t *testing.T) { + t.Setenv("FULLSEND_TEST_ROLLOUTS_READ_FAIL", "1") + _, _, _, err := runCodexChildrenCase(t, "collab_spawn.ndjson", true, 4, children, nil) + require.Error(t, err) + assert.Contains(t, err.Error(), "codex_spawn_without_admission: counting the child rollouts: exited 1: fake openshell: refusing the rollouts read") + }) + t.Run("no sessions directory, no spawn", func(t *testing.T) { + _, _, _, err := runCodexChildrenCase(t, "basic_run.ndjson", true, 0, nil, func(sessions string) { require.NoError(t, os.RemoveAll(sessions)) }) + require.NoError(t, err) + }) + t.Run("not delegating, no spawn: no read", func(t *testing.T) { + _, _, log, err := runCodexChildrenCase(t, "basic_run.ndjson", false, 0, nil, nil) + require.NoError(t, err) + assert.NotContains(t, log, codexChildRolloutsMarker) + }) + t.Run("not delegating, a spawn in the stream, no admission", func(t *testing.T) { + _, _, _, err := runCodexChildrenCase(t, "collab_spawn.ndjson", false, 0, children, nil) + assert.EqualError(t, err, msg(4, 0)) + }) +} + +// Two iterations: each adds its spawns from both sides, so a spawn the first +// iteration's stream lost still needs its admission. +func TestCodexRun_AdmissionCountSpansIterations(t *testing.T) { + for admitted, wantErr := range map[int]bool{6: false, 5: true} { + t.Run(fmt.Sprint(admitted), func(t *testing.T) { + children := []string{codexChildSameModelID, codexChildOtherModelID, codexChildFailedID} + _, _, _, err := runCodexChildrenCase(t, codexStreamWithout(t, `"tool":"spawn_agent"`), true, admitted, children, nil) + require.NoError(t, err, "iteration 1: three children on disk, admitted") + var out bytes.Buffer + _, err = CodexRuntime{}.Run(context.Background(), codexChildrenRunParams, ui.New(&out), time.Now(), &RunMetrics{}) + if wantErr { + assert.EqualError(t, err, "codex_spawn_without_admission: 6 spawn(s) in this run (the stream's spawn items and the child rollouts on disk, each child counted once) but 5 recorded admission(s)") + } else { + require.NoError(t, err) + } + }) + } +} + +// A line that is not three fields (a cut, a planted file name split on a +// newline) is a head that is not a session_meta record, so it counts; a +// blank line is no file. +func TestParseCodexRolloutHeads(t *testing.T) { + t.Parallel() + out := "1 \"id\":\"" + codexChildSameModelID + "\" \"parent_thread_id\":\"" + codexRootThreadID + "\"\n" + + "1 none none\n" + + "\n" + + "0 none\n" + + "/sandbox/weird name\n" + heads := parseCodexRolloutHeads([]byte(out)) + assert.Equal(t, []codexRolloutHead{ + {Meta: true, ID: codexChildSameModelID, Parent: codexRootThreadID}, + {Meta: true}, + {}, + {}, + }, heads) + n, ids, err := countCodexChildRollouts(heads, codexRootThreadID) + require.NoError(t, err) + assert.Equal(t, 3, n, "the child and the two malformed lines; the root-shaped head is not counted") + assert.Equal(t, []string{codexChildSameModelID}, ids) } diff --git a/internal/runtime/dummy_test.go b/internal/runtime/dummy_test.go index 4915943325..5385788617 100644 --- a/internal/runtime/dummy_test.go +++ b/internal/runtime/dummy_test.go @@ -245,6 +245,7 @@ func (s stubBootstrapInput) Plugins() []PluginInput { return nil } func (s stubBootstrapInput) ModelAliases() map[string]string { return nil } func (s stubBootstrapInput) AgentSubagents() map[string]*string { return nil } func (s stubBootstrapInput) ParentModel() string { return "" } +func (s stubBootstrapInput) Effort() string { return "" } func (s stubBootstrapInput) OpenAIProviderAttached() bool { return false } func TestDummyRuntime_Bootstrap(t *testing.T) { diff --git a/internal/runtime/testdata/codex/README.md b/internal/runtime/testdata/codex/README.md index 9654503507..3bf27224d9 100644 --- a/internal/runtime/testdata/codex/README.md +++ b/internal/runtime/testdata/codex/README.md @@ -69,7 +69,14 @@ a failed read logs `thread/read failed while backfilling turn items for turn com from `codex_exec`, which the runner counts too), so a spawn that lost both notifications or whose backfill failed is missing; and exec's default stderr filter is `error,opentelemetry_sdk=off,opentelemetry_otlp=off` (`codex-rs/exec/src/lib.rs`, `EXEC_DEFAULT_LOG_FILTER`), which the launch command keeps as its -base. +base. The disk side of the cross-check rests on four more: a PreToolUse block returns before the +tool handler runs, so a blocked spawn creates no thread and emits no item +(`codex-rs/core/src/tools/registry.rs`); a spawn refused at the thread limit fails at +`reserve_spawn_slot` before any thread exists (`codex-rs/core/src/agent/control/spawn.rs`); a +child's rollout is `sessions/YYYY/MM/DD/rollout--.jsonl`, created at its first +recorded item, with a first line that is its `session_meta` carrying `parent_thread_id` +(`codex-rs/rollout/src/rollout_file_name.rs`); and in an exec run with approvals off and memories +off by default only the root and its spawned children write rollouts there. Top-level `ThreadEvent` — serde `tag = "type"`, the variant payload flattened next to it: diff --git a/internal/runtime/testdata/codex/models-bundled-0.159.3.json b/internal/runtime/testdata/codex/models-bundled-0.159.3.json index 4ccc3e3f0d..64b15a9db3 100644 --- a/internal/runtime/testdata/codex/models-bundled-0.159.3.json +++ b/internal/runtime/testdata/codex/models-bundled-0.159.3.json @@ -2,47 +2,263 @@ "models": [ { "slug": "gpt-6-astra", - "multi_agent_version": "v2" + "multi_agent_version": "v2", + "default_reasoning_level": "low", + "supported_reasoning_levels": [ + { + "effort": "low" + }, + { + "effort": "medium" + }, + { + "effort": "high" + }, + { + "effort": "xhigh" + }, + { + "effort": "max" + }, + { + "effort": "ultra" + } + ] }, { "slug": "gpt-6.1-sol", - "multi_agent_version": "v2" + "multi_agent_version": "v2", + "default_reasoning_level": "low", + "supported_reasoning_levels": [ + { + "effort": "low" + }, + { + "effort": "medium" + }, + { + "effort": "high" + }, + { + "effort": "xhigh" + }, + { + "effort": "max" + }, + { + "effort": "ultra" + } + ] }, { "slug": "gpt-6-sol", - "multi_agent_version": "v2" + "multi_agent_version": "v2", + "default_reasoning_level": "medium", + "supported_reasoning_levels": [ + { + "effort": "low" + }, + { + "effort": "medium" + }, + { + "effort": "high" + }, + { + "effort": "xhigh" + }, + { + "effort": "max" + }, + { + "effort": "ultra" + } + ] }, { "slug": "gpt-6-luna", - "multi_agent_version": "v2" + "multi_agent_version": "v2", + "default_reasoning_level": "medium", + "supported_reasoning_levels": [ + { + "effort": "low" + }, + { + "effort": "medium" + }, + { + "effort": "high" + }, + { + "effort": "xhigh" + }, + { + "effort": "max" + } + ] }, { "slug": "gpt-5.6-sol", - "multi_agent_version": "v2" + "multi_agent_version": "v2", + "default_reasoning_level": "low", + "supported_reasoning_levels": [ + { + "effort": "low" + }, + { + "effort": "medium" + }, + { + "effort": "high" + }, + { + "effort": "xhigh" + }, + { + "effort": "max" + }, + { + "effort": "ultra" + } + ] }, { "slug": "gpt-5.6-terra", - "multi_agent_version": "v2" + "multi_agent_version": "v2", + "default_reasoning_level": "medium", + "supported_reasoning_levels": [ + { + "effort": "low" + }, + { + "effort": "medium" + }, + { + "effort": "high" + }, + { + "effort": "xhigh" + }, + { + "effort": "max" + }, + { + "effort": "ultra" + } + ] }, { "slug": "gpt-5.6-luna", - "multi_agent_version": "v1" + "multi_agent_version": "v1", + "default_reasoning_level": "medium", + "supported_reasoning_levels": [ + { + "effort": "low" + }, + { + "effort": "medium" + }, + { + "effort": "high" + }, + { + "effort": "xhigh" + }, + { + "effort": "max" + } + ] }, { "slug": "gpt-daybreak-blue-latest", - "multi_agent_version": "v2" + "multi_agent_version": "v2", + "default_reasoning_level": "low", + "supported_reasoning_levels": [ + { + "effort": "low" + }, + { + "effort": "medium" + }, + { + "effort": "high" + }, + { + "effort": "xhigh" + }, + { + "effort": "max" + }, + { + "effort": "ultra" + } + ] }, { "slug": "gpt-daybreak-red-latest", - "multi_agent_version": "v2" + "multi_agent_version": "v2", + "default_reasoning_level": "medium", + "supported_reasoning_levels": [ + { + "effort": "low" + }, + { + "effort": "medium" + }, + { + "effort": "high" + }, + { + "effort": "xhigh" + }, + { + "effort": "max" + }, + { + "effort": "ultra" + } + ] }, { "slug": "gpt-5.5", - "multi_agent_version": null + "multi_agent_version": null, + "default_reasoning_level": "medium", + "supported_reasoning_levels": [ + { + "effort": "low" + }, + { + "effort": "medium" + }, + { + "effort": "high" + }, + { + "effort": "xhigh" + } + ] }, { "slug": "codex-auto-review", - "multi_agent_version": "v1" + "multi_agent_version": "v1", + "default_reasoning_level": "medium", + "supported_reasoning_levels": [ + { + "effort": "low" + }, + { + "effort": "medium" + }, + { + "effort": "high" + }, + { + "effort": "xhigh" + }, + { + "effort": "max" + } + ] } ] } From b845a4cd034b13c99b21e9e077e0e608c8e7a1ff Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Wed, 28 Oct 2026 13:04:23 -0400 Subject: [PATCH 12/15] fix(codex): say spawn where failed spawn items count The admission check counts failed spawn_agent items too, but the error for a spawn not sent by the primary thread, the codexChildIDs and compareCodexSpawnAdmissions comments and the codex page still said "completed spawn", and the spare-admission example (a spawn codex refused at the thread limit) now uses up its admission. The error says "a spawn", and the example is a call codex rejects before its item or another hook blocks. Drops warn for #8712's reason, that most drops hide no spawn. The code comment, the test comment and the runtime guide gave the child's rollout instead, which the agent can delete. Signed-off-by: Dharit Shah --- docs/contributing/runtime-implementation.md | 4 ++-- docs/runtimes/codex.md | 2 +- internal/runtime/codex_run.go | 4 ++-- internal/runtime/codex_subagents.go | 24 ++++++++++----------- internal/runtime/codex_subagents_test.go | 19 ++++++++-------- 5 files changed, 26 insertions(+), 27 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index 1ba7177aca..c0da7a3c9d 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -1366,8 +1366,8 @@ stream notification under backpressure, of any thread, and says so on stderr: th `RUST_LOG` outright after `.env` (codex's default filter with `codex_exec` and `codex_app_server::in_process` at warn; codex's commands inherit it), and the runner scans that stderr on the host (the sandbox log under `--debug`) and warns on the line and on exec's warning -that its `thread/read` backfill of the turn's items failed. Drops stay warnings (#8712): the -rollouts do not depend on the stream. The check cannot catch a forged admission (the log is +that its `thread/read` backfill of the turn's items failed. Drops stay warnings, as #8712 settled: +most drops hide no spawn. The check cannot catch a forged admission (the log is agent-writable), a resume (a `wait` item in the stream), a spawn hidden from both sides (stream items lost and the rollout deleted or its `session_meta` edited), a child that never recorded an item, or a surplus admission covering a later spawn (counts, not ids): codex can reject an admitted diff --git a/docs/runtimes/codex.md b/docs/runtimes/codex.md index b180ab66de..70976cda31 100644 --- a/docs/runtimes/codex.md +++ b/docs/runtimes/codex.md @@ -506,7 +506,7 @@ their own. Ask first whether the agent wrote to the findings log or under `$CODE log over 1 MiB is read cut, and the message then ends with `the admissions read was cut at 1048576 bytes`. ``` -codex_spawn_without_admission: a completed spawn was not sent by the primary thread +codex_spawn_without_admission: a spawn was not sent by the primary thread ``` A spawn item without a sender, or sent by a thread other than the run's own. Codex 0.159.3 emits neither; look for a malformed or planted stream line. diff --git a/internal/runtime/codex_run.go b/internal/runtime/codex_run.go index 76b5c21259..fc668422d9 100644 --- a/internal/runtime/codex_run.go +++ b/internal/runtime/codex_run.go @@ -717,8 +717,8 @@ func (r CodexRuntime) Run(ctx context.Context, params RunParams, printer *ui.Pri // above. Each iteration adds its spawns seen on either side, each counted // once per thread: the stream's spawn items (completed or failed: each // passed the guard) and the children on disk. A dropped stream - // notification is a warning: it can hide a spawn item, but not the - // child's rollout. + // notification is a warning, as settled on #8712: most drops hide no + // spawn. if stderr.Dropped > 0 { msg := fmt.Sprintf("codex dropped %d stream notification(s) under backpressure", stderr.Dropped) if stderr.BackfillFailed > 0 { diff --git a/internal/runtime/codex_subagents.go b/internal/runtime/codex_subagents.go index af8635c9b4..aa2fc0bd94 100644 --- a/internal/runtime/codex_subagents.go +++ b/internal/runtime/codex_subagents.go @@ -134,10 +134,10 @@ func parseCodexChildUsage(data []byte) []codexChildUsage { return out } -// codexChildIDs collects the thread ids of completed spawn_agent items from -// a tee of the `exec --json` stream: the parser's events carry no thread id. -// Senders holds each completed spawn's sender_thread_id, in stream order, for -// the admission cross-check. +// codexChildIDs collects the thread ids of the spawn_agent items codex +// finished, completed or failed, from a tee of the `exec --json` stream: the +// parser's events carry no thread id. Senders holds each one's +// sender_thread_id, in stream order, for the admission cross-check. // A final line without a newline waits for flush, once the stream has ended: // codex killed mid-write can leave a completed spawn there. type codexChildIDs struct { @@ -597,16 +597,16 @@ func countCodexSpawnAdmissions(data []byte) int { // compareCodexSpawnAdmissions returns an error for a spawn without a sender // or sent by any thread but the primary one (two unknown ids are not the -// same thread), and for more completed spawns in the run than admissions. -// More admissions is not an error: an admitted spawn codex then refused (at -// the thread limit) completed nothing. No id is in the error: the stream -// comes out of the sandbox. At the pinned codex the stream carries the -// primary thread's items only, so the sender rule is defence in depth; a -// child's spawn is the guard's deny. +// same thread), and for more spawns in the run than admissions. More +// admissions is not an error: codex can reject an admitted call before it +// emits an item, and another hook can block a call the guard admitted. No id +// is in the error: the stream comes out of the sandbox. At the pinned codex +// the stream carries the primary thread's items only, so the sender rule is +// defence in depth; a child's spawn is the guard's deny. func compareCodexSpawnAdmissions(primary string, senders []string, completed, admitted int) error { for _, sender := range senders { if sender == "" || sender != primary { - return fmt.Errorf("%s: a completed spawn was not sent by the primary thread", codexSpawnWithoutAdmission) + return fmt.Errorf("%s: a spawn was not sent by the primary thread", codexSpawnWithoutAdmission) } } if completed > admitted { @@ -617,7 +617,7 @@ func compareCodexSpawnAdmissions(primary string, senders []string, completed, ad } // checkCodexSpawnAdmissions reads the admissions and compares them with an -// iteration's completed spawns (senders) and the run's (completed). Unlike +// iteration's spawn senders and the run's spawn count (completed). Unlike // the usage read, a read that fails or times out fails the run: this is a // policy check, not a metric. func checkCodexSpawnAdmissions(sandboxName, primary string, senders []string, completed int) error { diff --git a/internal/runtime/codex_subagents_test.go b/internal/runtime/codex_subagents_test.go index deada9a4cd..8906d61b46 100644 --- a/internal/runtime/codex_subagents_test.go +++ b/internal/runtime/codex_subagents_test.go @@ -949,24 +949,24 @@ func TestCompareCodexSpawnAdmissions(t *testing.T) { tests := []struct { name string primary string - senders []string // this iteration's completed spawns + senders []string // this iteration's spawn items completed, admitted int // the whole run's want string // "" = no error }{ {"equal counts", root, []string{root, root, root}, 3, 3, ""}, - {"more admissions: an admitted spawn codex then refused", root, []string{root, root}, 2, 3, ""}, - {"one completed spawn more than admissions", root, []string{root, root, root}, 3, 2, + {"more admissions: an admitted call codex rejected before its item", root, []string{root, root}, 2, 3, ""}, + {"one spawn more than admissions", root, []string{root, root, root}, 3, 2, "codex_spawn_without_admission: 3 spawn(s) in this run (the stream's spawn items and the child rollouts on disk, each child counted once) but 2 recorded admission(s)"}, {"an earlier iteration's spawns count", root, []string{root}, 4, 3, "codex_spawn_without_admission: 4 spawn(s) in this run (the stream's spawn items and the child rollouts on disk, each child counted once) but 3 recorded admission(s)"}, {"a sender that is not the primary thread", root, []string{root, codexChildSameModelID}, 2, 3, - "codex_spawn_without_admission: a completed spawn was not sent by the primary thread"}, + "codex_spawn_without_admission: a spawn was not sent by the primary thread"}, {"a spawn item without a sender", root, []string{""}, 1, 3, - "codex_spawn_without_admission: a completed spawn was not sent by the primary thread"}, + "codex_spawn_without_admission: a spawn was not sent by the primary thread"}, {"the stream named no primary thread", "", []string{root}, 1, 3, - "codex_spawn_without_admission: a completed spawn was not sent by the primary thread"}, + "codex_spawn_without_admission: a spawn was not sent by the primary thread"}, {"no sender and no primary thread", "", []string{""}, 1, 3, - "codex_spawn_without_admission: a completed spawn was not sent by the primary thread"}, + "codex_spawn_without_admission: a spawn was not sent by the primary thread"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -1188,9 +1188,8 @@ func TestCodexStderrDrops_CountsAcrossChunks(t *testing.T) { assert.Equal(t, 1, last.Dropped, "the last line is scanned once the stream has ended") } -// A dropped stream notification is a warning, for a delegating run too: it -// can hide a spawn item, not the child's rollout, which the admission check -// counts as well (#8712: most drops lose nothing the count needs). +// A dropped stream notification is a warning, for a delegating run too, as +// settled on #8712: most drops hide no spawn. func TestCodexRun_DroppedNotificationWarns(t *testing.T) { t.Setenv("FULLSEND_TEST_CODEX_DROP", "1") for _, delegating := range []bool{false, true} { From a58293173348798889d3bba3c25d4b60e122bd80 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Wed, 28 Oct 2026 18:13:04 -0400 Subject: [PATCH 13/15] fix(codex): count a child whose rollout head is empty or cut once A rollout whose first line is empty or not a session_meta record counted as a child with no id, so a child the stream also showed counted twice and one admission failed the run. Codex creates the file before it writes session_meta: the write waits on git info, and a failed write leaves the file empty, or with a cut first line for good. Such a head now takes the thread id in its file name (rollout--.jsonl), so it dedupes against the stream's receivers and the run's own file is not a child; two files of one thread count once. A name says which thread a file is, not whose child, so such a file is a parent in the grandchild walk only when the stream's receivers name it. A session_meta head with no parent stays a root whatever its name. The limits name an ancestor's rollout and a rename too. Signed-off-by: Dharit Shah --- docs/contributing/runtime-implementation.md | 42 ++++--- docs/runtimes/codex.md | 20 +-- internal/runtime/codex_run.go | 2 +- internal/runtime/codex_subagents.go | 128 +++++++++++++------- internal/runtime/codex_subagents_test.go | 117 +++++++++++++++--- internal/runtime/testdata/codex/README.md | 13 +- 6 files changed, 223 insertions(+), 99 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index c0da7a3c9d..1648eaf163 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -1354,26 +1354,28 @@ the handler and emits none, `core/src/tools/registry.rs`; a spawn refused at the at `reserve_spawn_slot` after the guard admitted it and names no child), counted by their receiver 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 -not a `session_meta` record. 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. 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 -primary thread id with a child-shaped rollout present, or a failed read of either side. The count -spans the run's iterations, so `ClearIterationArtifacts` must leave `.security/` in place (it -clears `output/`, the sessions directory and the debug log, nothing else under the workspace). The -usage fold reads the union of the stream's children and the children on disk. Codex can drop a -stream notification under backpressure, of any thread, and says so on stderr: the launch sets -`RUST_LOG` outright after `.env` (codex's default filter with `codex_exec` and -`codex_app_server::in_process` at warn; codex's commands inherit it), and the runner scans that -stderr on the host (the sandbox log under `--debug`) and warns on the line and on exec's warning -that its `thread/read` backfill of the turn's items failed. Drops stay warnings, as #8712 settled: -most drops hide no spawn. The check cannot catch a forged admission (the log is -agent-writable), a resume (a `wait` item in the stream), a spawn hidden from both sides (stream -items lost and the rollout deleted or its `session_meta` edited), a child that never recorded an -item, or a surplus admission covering a later spawn (counts, not ids): codex can reject an admitted -call before it emits an item (`parse_collab_input` on a spawn with no message, or -`prepare_agent_spawn_config` after `item.started`), and another PreToolUse hook running beside the -guard can block a call the guard admitted. +empty 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 iteration's files and a root the +agent's own `codex exec` writes under `CODEX_HOME` are not, unless their first line is empty or +cut. 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 primary thread id with a child-shaped +rollout present, or a failed read of either side. The count spans the run's iterations, so +`ClearIterationArtifacts` must leave `.security/` in place (it clears `output/`, the sessions +directory and the debug log, nothing else under the workspace). The usage fold reads the union of +the stream's children and the children on disk. Codex can drop a stream notification under +backpressure, of any thread, and says so on stderr: the launch sets `RUST_LOG` outright after +`.env` (codex's default filter with `codex_exec` and `codex_app_server::in_process` at warn; +codex's commands inherit it), and the runner scans that stderr on the host (the sandbox log under +`--debug`) and warns on the line and on exec's warning that its `thread/read` backfill of the +turn's items failed. Drops stay warnings, as #8712 settled: most drops hide no spawn. The check +cannot catch a forged admission (the log is agent-writable), a resume (a `wait` item in the +stream), a spawn hidden from both sides (stream items lost and the rollout, or an ancestor's, +deleted, renamed or its `session_meta` edited), a child that never recorded an item, or a surplus +admission covering a later spawn (counts, not ids): codex can reject an admitted call before it +emits an item (`parse_collab_input` on a spawn with no message, or `prepare_agent_spawn_config` +after `item.started`), and another PreToolUse hook running beside the guard can block a call the +guard admitted. **PATH is pinned across `.env` for the same reason the interpreter is.** The hook scripts resolve their tools by name — `tirith_check.py` runs a bare `tirith` — so a `.env` that prepends a directory diff --git a/docs/runtimes/codex.md b/docs/runtimes/codex.md index 70976cda31..496a2edcd8 100644 --- a/docs/runtimes/codex.md +++ b/docs/runtimes/codex.md @@ -491,10 +491,11 @@ iteration whose stream shows a spawn, the runner counts that iteration's spawns each child once by its thread id: the `spawn_agent` items in the `exec --json` stream, completed or failed (each passed the guard; a spawn the guard blocks emits none, and one codex refused before a thread existed names no child), and the rollouts under `$CODEX_HOME/sessions` whose parent is the -run's thread or one of its children (a file whose first line is not a `session_meta` record counts -too). It compares the run's total with the spawn guard's `codex_spawn_guard_admit` -lines in `/sandbox/workspace/.security/findings.jsonl`, and the run fails whatever codex's exit -code. Each message says why: +run's thread or one of its children (a file whose first line is empty or not a `session_meta` +record counts too, under the thread id in its name, `rollout-