From e28b790b2f18b8ce3c2afef51f2273c0e5bfe97c Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Mon, 12 Oct 2026 16:17:01 -0400 Subject: [PATCH 1/5] refactor(codex): render native role files for skill personas codexRoles turns the personas discoverPersonas registers, plus the built-in default and explore roles, into agents/.toml files with name, description and developer_instructions (#6970). A reserved, duplicate, description-less or body-less persona is skipped with a warning; model, tools, permissionMode, background and maxTurns are reported and never rendered. piAgentDef keeps the raw frontmatter; piPersona gains Description, Body and Frontmatter. Nothing calls this yet. Signed-off-by: Dharit Shah --- internal/runtime/codex_personas.go | 121 +++++++++ internal/runtime/codex_personas_test.go | 328 ++++++++++++++++++++++++ internal/runtime/pi_agent.go | 5 + internal/runtime/pi_personas.go | 8 + 4 files changed, 462 insertions(+) create mode 100644 internal/runtime/codex_personas.go create mode 100644 internal/runtime/codex_personas_test.go diff --git a/internal/runtime/codex_personas.go b/internal/runtime/codex_personas.go new file mode 100644 index 0000000000..2905461136 --- /dev/null +++ b/internal/runtime/codex_personas.go @@ -0,0 +1,121 @@ +package runtime + +import ( + "fmt" + "os" + "slices" + "strings" + + "gopkg.in/yaml.v3" +) + +// codexDelegates is part one of the ADR 0126 gate: an agent gets native +// sub-agent roles when its tools include Agent (an absent tools: includes +// it, as on Claude Code and pi; Task is the alias codexToolMatcher already +// maps to spawn_agent) and the harness has sandbox security enabled, because +// the spawn guard that admits only registered roles is installed with the +// hooks. Part two, codexParentResolvesV1, needs the pinned CLI's catalog and +// is decided in Bootstrap. +func codexDelegates(def *piAgentDef, securityEnabled bool) bool { + return securityEnabled && piAgentToolEnabled(def) +} + +// codexRole is one native Codex sub-agent role, written to +// $CODEX_HOME/agents/.toml. Instructions is the child's +// developer_instructions: the persona body and nothing else (#6970). +type codexRole struct { + Name, Description, Instructions string +} + +// codexReservedRoleNames are persona names Codex treats specially: `enabled` +// is the [agents] table's own key; `explorer` and `worker` are Codex's +// built-in roles, accepted without a role file, which the spawn guard +// 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: the run-level +// default applies to every child (#6970). +func (role codexRole) toml() []byte { + return []byte("name = " + codexTOMLString(role.Name) + "\n" + + "description = " + codexTOMLString(role.Description) + "\n" + + "developer_instructions = " + codexTOMLString(role.Instructions) + "\n") +} + +// Built-in roles. `default` serves a spawn without agent_type, which is how +// retro's unnamed investigation tasks run; `explore` is Claude Code's +// Explore as an instruction to the child, not an enforced sandbox: the +// pinned Codex has no per-child tool restriction (#6970). +const ( + codexDefaultRoleDescription = "Generic sub-agent for a task the parent describes in full in its message." + codexDefaultRoleInstructions = "# Sub-agent\n\nDo the task in the message you were given, and only that task. " + + "Put your findings, with file paths and line numbers where they apply, in your final message: " + + "the parent reads nothing else and owns the synthesis and the final result.\n" + codexExploreRoleDescription = "Investigation of the repository by reading only; reports findings. Instruction-only: nothing enforces read-only on a child." + codexExploreRoleInstructions = "# Explore\n\nAnswer the question in the message you were given by reading the " + + "repository: read files, search, and run commands that change nothing. Do not edit or create files. " + + "Put what you found, with file paths and line numbers, in your final message: the parent reads nothing else.\n" +) + +// codexRoles is the role list for a delegating agent: every skill persona +// 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 { + // discoverPersonas never returns a non-nil error; the value exists for + // the pi call site's shape. + personas, skipped, _ := discoverPersonas(skillDirs, agentName) + for _, sk := range skipped { + fmt.Fprintf(os.Stderr, "Warning: persona %q skipped: %s\n", sk.Path, sk.Reason) + } + roles := []codexRole{ + {Name: "default", Description: codexDefaultRoleDescription, Instructions: codexDefaultRoleInstructions}, + {Name: "explore", Description: codexExploreRoleDescription, Instructions: codexExploreRoleInstructions}, + } + for _, p := range personas { + var reason string + switch { + case slices.Contains(codexReservedRoleNames, p.Name): + reason = "name is reserved on codex (" + strings.Join(codexReservedRoleNames, ", ") + ")" + case p.Description == "": + reason = "frontmatter description: is required; the parent sees it in the spawn tool's role list" + case p.Body == "": + reason = "body is empty, so the role would carry no instructions" + } + if reason != "" { + fmt.Fprintf(os.Stderr, "Warning: persona %q skipped: %s\n", p.Name, reason) + 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", + p.Name, strings.Join(keys, ", ")) + } + roles = append(roles, codexRole{Name: p.Name, Description: p.Description, Instructions: p.Body + "\n"}) + } + slices.SortFunc(roles, func(a, b codexRole) int { return strings.Compare(a.Name, b.Name) }) + return roles +} + +// codexDroppedPersonaKeys are the Claude-specific frontmatter keys a role +// never carries (#6970). piAgentFrontmatter parses only the first two, so +// the raw frontmatter is read for the diagnostic. +var codexDroppedPersonaKeys = []string{"model", "tools", "permissionMode", "background", "maxTurns"} + +// codexDroppedFrontmatterKeys returns which of codexDroppedPersonaKeys the +// frontmatter sets, in that order. A registered persona's frontmatter has +// parsed once already, so a parse failure here reports nothing. +func codexDroppedFrontmatterKeys(frontmatter []byte) []string { + var raw map[string]any + if err := yaml.Unmarshal(frontmatter, &raw); err != nil { + return nil + } + var keys []string + for _, k := range codexDroppedPersonaKeys { + if _, ok := raw[k]; ok { + keys = append(keys, k) + } + } + return keys +} diff --git a/internal/runtime/codex_personas_test.go b/internal/runtime/codex_personas_test.go new file mode 100644 index 0000000000..c6f30faf97 --- /dev/null +++ b/internal/runtime/codex_personas_test.go @@ -0,0 +1,328 @@ +package runtime + +import ( + "encoding/json" + "fmt" + "os/exec" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// codexTestPersona is a correctness persona with the Claude-only keys a +// fleet persona carries, so the tests show them dropped rather than +// rendered. +const codexTestPersona = "---\n" + + "name: correctness\n" + + "description: Evaluates logic correctness, edge cases, nil handling, API contracts, test adequacy/integrity.\n" + + "model: opus\n" + + "tools: Read, Grep, Glob, Bash\n" + + "---\n" + + "# Correctness\n\nYou are a senior software engineer reviewing for correctness.\n" + +// codexTestDelegatingAgentDef has no tools: line, so its tool set includes +// Agent, as review and retro do in fullsend-ai/agents. +const codexTestDelegatingAgentDef = `--- +name: review +description: Review a pull request. +model: openai/gpt-5.6-luna +--- +You are the review agent. Dispatch the roster. +` + +func TestCodexDelegates(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + agent string + security bool + want bool + }{ + {name: "no tools line includes Agent", agent: codexTestDelegatingAgentDef, security: true, want: true}, + {name: "tools naming Agent", agent: "---\nname: review\ntools: Bash,Agent\n---\nbody\n", security: true, want: true}, + {name: "tools naming Task, the alias codex maps to spawn_agent", agent: "---\nname: review\ntools: Bash,Task\n---\nbody\n", security: true, want: true}, + {name: "tools without Agent", agent: codexTestAgentDef, security: true, want: false}, + {name: "security disabled", agent: codexTestDelegatingAgentDef, security: false, want: false}, + {name: "empty tools list", agent: "---\nname: review\ntools: []\n---\nbody\n", security: true, want: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + def, err := parsePiAgent([]byte(tt.agent)) + require.NoError(t, err) + assert.Equal(t, tt.want, codexDelegates(def, tt.security)) + }) + } +} + +// Codex needs the two values the pi manifest never carried. They are filled +// by the shared discovery so the two runtimes cannot drift (#6970). +func TestDiscoverPersonas_CarriesDescriptionAndBody(t *testing.T) { + t.Parallel() + skill := t.TempDir() + writePersonaFile(t, skill, "correctness", codexTestPersona) + + personas, skipped, err := discoverPersonas([]string{skill}, "review") + require.NoError(t, err) + require.Empty(t, skipped) + require.Len(t, personas, 1) + assert.Equal(t, "Evaluates logic correctness, edge cases, nil handling, API contracts, test adequacy/integrity.", personas[0].Description) + assert.Equal(t, "# Correctness\n\nYou are a senior software engineer reviewing for correctness.", personas[0].Body, + "the body is trimmed by parsePiAgent; the role renderer adds the final newline") + assert.Equal(t, "name: correctness\n"+ + "description: Evaluates logic correctness, edge cases, nil handling, API contracts, test adequacy/integrity.\n"+ + "model: opus\ntools: Read, Grep, Glob, Bash\n", string(personas[0].Frontmatter), + "the raw frontmatter, for the dropped-keys diagnostic") + // The pi fields are untouched. + assert.Equal(t, "opus", personas[0].Model) + assert.Equal(t, []string{"Read", "Grep", "Glob", "Bash"}, personas[0].Tools) +} + +// 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, and no dropped +// frontmatter turned into text (#6970). +func TestCodexRole_TOML(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", + } + want := "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, want, string(role.toml())) +} + +func TestCodexRole_TOMLEscapesTheBody(t *testing.T) { + t.Parallel() + + 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", "a role never carries a model line") +} + +func codexRoleNames(roles []codexRole) []string { + names := make([]string, 0, len(roles)) + for _, r := range roles { + names = append(names, r.Name) + } + return names +} + +// A delegating agent always has default and explore registered (ADR 0126): +// retro dispatches unnamed children through default, and Explore maps to +// explore (#6970). +func TestCodexRoles_BuiltinsAlwaysPresent(t *testing.T) { + t.Parallel() + + for name, dirs := range map[string][]string{ + "no skill dirs": nil, + "an empty entry": {""}, + "a skill without sub-agents": {t.TempDir()}, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + 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) + assert.NotEmpty(t, r.Instructions, "%s", r.Name) + assert.True(t, strings.HasSuffix(r.Instructions, "\n"), "%s: instructions end with one newline like a file", r.Name) + } + }) + } +} + +func TestCodexRoles_SkillPersonasSorted(t *testing.T) { + t.Parallel() + skill := t.TempDir() + writePersonaFile(t, skill, "style", "---\nname: style\ndescription: Style review.\n---\nReview for style.\n") + writePersonaFile(t, skill, "correctness", codexTestPersona) + + 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{ + 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", + }, roles[0]) + assert.Equal(t, "Review for style.\n", roles[3].Instructions) +} + +// A file discoverPersonas skips (reserved name, bad shape) is a warning here +// too: Bootstrap never fails over a stray sub-agents/*.md. +func TestCodexRoles_DiscoverySkipIsAWarning(t *testing.T) { + skill := t.TempDir() + writePersonaFile(t, skill, "default", "---\nname: default\ndescription: Not allowed.\n---\nbody\n") + writePersonaFile(t, skill, "Bad", "---\nname: Bad\ndescription: Bad shape.\n---\nbody\n") + + var roles []codexRole + out := captureStderr(t, func() { roles = codexRoles([]string{skill}, "review") }) + + assert.Equal(t, []string{"default", "explore"}, codexRoleNames(roles)) + assert.Contains(t, out, fmt.Sprintf("Warning: persona %q skipped: name is reserved", skill+"/sub-agents/default.md")) + assert.Contains(t, out, fmt.Sprintf("Warning: persona %q skipped: name must be lowercase alphanumeric", skill+"/sub-agents/Bad.md")) +} + +// One row per rule a persona can break on Codex. Every row is a warning, +// never an error, and the built-ins are always left standing. +func TestCodexRoles_SkipsInvalidPersonas(t *testing.T) { + tests := []struct { + name string + file string // persona basename + content string + wantWarn string + wantRoles []string + }{ + {name: "reserved: enabled is the [agents] table key", file: "enabled", + content: "---\nname: enabled\ndescription: d\n---\nbody\n", + wantWarn: `persona "enabled" skipped: name is reserved on codex (enabled, explorer, worker)`}, + {name: "reserved: explorer is a codex built-in", file: "explorer", + content: "---\nname: explorer\ndescription: d\n---\nbody\n", + wantWarn: `persona "explorer" skipped: name is reserved on codex`}, + {name: "reserved: worker is a codex built-in", file: "worker", + content: "---\nname: worker\ndescription: d\n---\nbody\n", + wantWarn: `persona "worker" skipped: name is reserved on codex`}, + {name: "empty description", file: "quiet", + content: "---\nname: quiet\n---\nbody\n", + wantWarn: `persona "quiet" skipped: frontmatter description: is required`}, + {name: "empty body", file: "hollow", + content: "---\nname: hollow\ndescription: d\n---\n", + wantWarn: `persona "hollow" skipped: body is empty`}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + skill := t.TempDir() + writePersonaFile(t, skill, tt.file, tt.content) + + var roles []codexRole + out := captureStderr(t, func() { roles = codexRoles([]string{skill}, "review") }) + + assert.Equal(t, []string{"default", "explore"}, codexRoleNames(roles)) + assert.Contains(t, out, tt.wantWarn) + }) + } +} + +// Two skills declaring one name: the first wins (discoverPersonas), the +// second is a warning, and exactly one role file is rendered (#6970). +func TestCodexRoles_DuplicateAcrossSkillsKeepsTheFirst(t *testing.T) { + first := t.TempDir() + second := t.TempDir() + writePersonaFile(t, first, "correctness", codexTestPersona) + 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") }) + + assert.Equal(t, []string{"correctness", "default", "explore"}, codexRoleNames(roles)) + assert.Equal(t, "# Correctness\n\nYou are a senior software engineer reviewing for correctness.\n", roles[0].Instructions) + assert.Contains(t, out, "skipped: name already declared by skill") +} + +// Claude-specific frontmatter is reported, never applied and never turned +// into prompt text (#6970): one line per persona, naming the keys +// present among the five, and no line for a persona that sets none. +func TestCodexRoles_ReportsDroppedFrontmatter(t *testing.T) { + skill := t.TempDir() + writePersonaFile(t, skill, "all-five", "---\nname: all-five\ndescription: d\nmodel: opus\ntools: Read, Grep\n"+ + "permissionMode: bypassPermissions\nbackground: true\nmaxTurns: 20\n---\nbody\n") + writePersonaFile(t, skill, "two", "---\nname: two\ndescription: d\nmaxTurns: 3\nmodel: haiku\n---\nbody\n") + writePersonaFile(t, skill, "clean", "---\nname: clean\ndescription: d\n---\nbody\n") + + var roles []codexRole + 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") + assert.NotContains(t, out, `Codex persona "clean"`) + assert.Equal(t, 2, strings.Count(out, "dropped"), "one line per persona that sets any of the five keys") + for _, r := range roles { + assert.NotContains(t, r.Instructions, "opus", "%s: a dropped value never becomes prompt text", r.Name) + assert.NotContains(t, r.Instructions, "permissionMode", "%s", r.Name) + } +} + +// The keys reported are the registered file's: a same-named file an earlier +// skill holds that discovery skipped is not the one described. +func TestCodexRoles_DroppedFrontmatterIsTheRegisteredFile(t *testing.T) { + withModel := "---\nname: %s\ndescription: d\nmodel: opus\n---\nbody\n" + plain := "---\nname: %s\ndescription: d\n---\nbody\n" + for name, tc := range map[string]struct{ skipped, registered, want string }{ + "the skipped file sets a key": {fmt.Sprintf(withModel, "other"), fmt.Sprintf(plain, "correctness"), ""}, + "the registered file sets a key": {fmt.Sprintf(plain, "other"), fmt.Sprintf(withModel, "correctness"), `Codex persona "correctness": frontmatter model dropped`}, + } { + t.Run(name, func(t *testing.T) { + skipped := t.TempDir() + writePersonaFile(t, skipped, "correctness", tc.skipped) + registered := t.TempDir() + writePersonaFile(t, registered, "correctness", tc.registered) + + out := captureStderr(t, func() { codexRoles([]string{skipped, registered}, "review") }) + + assert.Contains(t, out, "skipped: frontmatter name") + if tc.want == "" { + assert.NotContains(t, out, `Codex persona "correctness"`) + } else { + assert.Contains(t, out, tc.want) + } + }) + } +} + +func TestCodexDroppedFrontmatterKeys(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + data string + want []string + }{ + {name: "no frontmatter"}, + {name: "keys in fixed order", data: "maxTurns: 1\nmodel: opus\n", want: []string{"model", "maxTurns"}}, + {name: "a null value still counts as present", data: "model:\n", want: []string{"model"}}, + {name: "unrelated keys are ignored", data: "name: x\ndescription: y\n"}, + {name: "scalar yaml reports nothing", data: "scalar\n"}, + {name: "malformed yaml reports nothing", data: "model: [\n"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, tt.want, codexDroppedFrontmatterKeys([]byte(tt.data))) + }) + } +} + +// codexDecodeTOML parses data with the stdlib tomllib, the parser codex's own +// loader has to agree with (as TestRenderCodexConfig_ParsesAsTOML does). +func codexDecodeTOML(t *testing.T, data []byte) map[string]any { + t.Helper() + cmd := exec.Command(pythonWithTomllib(t), "-c", "import json, sys, tomllib; print(json.dumps(tomllib.loads(sys.stdin.read())))") + cmd.Stdin = strings.NewReader(string(data)) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "%s", out) + var doc map[string]any + require.NoError(t, json.Unmarshal(out, &doc)) + return doc +} + +func TestCodexRole_TOMLParsesWithTheThreeKeys(t *testing.T) { + skill := t.TempDir() + writePersonaFile(t, skill, "correctness", codexTestPersona) + + for _, role := range codexRoles([]string{skill}, "review") { + 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"]) + assert.Equal(t, role.Description, doc["description"]) + assert.Equal(t, role.Instructions, doc["developer_instructions"], "%s: the body round-trips", role.Name) + } +} diff --git a/internal/runtime/pi_agent.go b/internal/runtime/pi_agent.go index 27443532f5..e0c2687ead 100644 --- a/internal/runtime/pi_agent.go +++ b/internal/runtime/pi_agent.go @@ -26,6 +26,9 @@ type piAgentDef struct { // unrestricted or absent. BashAllowlist []string Body string + // Frontmatter is the raw YAML between the fences, for a caller that + // reports keys piAgentFrontmatter does not parse. + Frontmatter []byte } type piAgentFrontmatter struct { @@ -76,6 +79,8 @@ func parsePiAgent(data []byte) (*piAgentDef, error) { def.Description = strings.TrimSpace(fm.Description) def.Model = strings.TrimSpace(fm.Model) def.Body = strings.TrimSpace(string(body)) + def.Frontmatter = front + def.Frontmatter = front specs, err := piToolSpecs(fm.Tools) if err != nil { diff --git a/internal/runtime/pi_personas.go b/internal/runtime/pi_personas.go index d8524d6441..7df4f8f3b1 100644 --- a/internal/runtime/pi_personas.go +++ b/internal/runtime/pi_personas.go @@ -18,6 +18,11 @@ type piPersona struct { Model string // frontmatter model (alias or id); empty = inherit parent Tools []string // Claude tool names; nil = parent's set BashAllowlist []string // Bash(a,b) prefixes; nil = unrestricted + // Description, Body and Frontmatter are what a Codex role file and its + // diagnostics need (#6970). They are not serialized into the pi manifest. + Description string + Body string + Frontmatter []byte } // piPersonaManifestEntry is one entry in the manifest's personas table, @@ -132,6 +137,9 @@ func discoverPersonas(skillDirs []string, agentName string) ([]piPersona, []piSk Model: def.Model, Tools: def.Tools, BashAllowlist: def.BashAllowlist, + Description: def.Description, + Body: def.Body, + Frontmatter: def.Frontmatter, }) } } From 049279a68d4ae31a6d25b19d5d5697b32fd8c4a0 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Mon, 12 Oct 2026 16:18:47 -0400 Subject: [PATCH 2/5] refactor(codex): write role files at bootstrap for delegating agents For an agent whose tools include Agent, with harness security on and a parent model Codex resolves to collaboration V1 (its entry in the pinned CLI's bundled catalog says v1 or carries no version; codex debug models --bundled, read at Bootstrap), Bootstrap creates $CODEX_HOME/agents/, uploads one regular file per role and records each digest in the runner-held set, so the spawn guard admits the registered roles and denies a planted or edited file. Every other agent, and every run with security off, gets today's files. config.toml keeps [agents] enabled = false until the dispatch note lands (#6970). Signed-off-by: Dharit Shah --- docs/contributing/runtime-implementation.md | 12 +- internal/runtime/codex_bootstrap.go | 59 +++++ internal/runtime/codex_bootstrap_test.go | 237 ++++++++++++++++++ internal/runtime/codex_golden_test.go | 54 ++++ internal/runtime/codex_personas.go | 70 ++++++ internal/runtime/codex_personas_test.go | 80 ++++++ .../codex/golden/launch-delegating.txt | 93 +++++++ .../codex/golden/roles/correctness.toml | 7 + .../testdata/codex/golden/roles/default.toml | 7 + .../testdata/codex/golden/roles/explore.toml | 7 + .../codex/models-bundled-0.159.3.json | 48 ++++ 11 files changed, 671 insertions(+), 3 deletions(-) create mode 100644 internal/runtime/testdata/codex/golden/launch-delegating.txt create mode 100644 internal/runtime/testdata/codex/golden/roles/correctness.toml create mode 100644 internal/runtime/testdata/codex/golden/roles/default.toml create mode 100644 internal/runtime/testdata/codex/golden/roles/explore.toml create mode 100644 internal/runtime/testdata/codex/models-bundled-0.159.3.json diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index af2467d627..a0ea815938 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -449,6 +449,8 @@ The sandbox has two key directories that map to Claude Code's config levels (plu ├── codex-config/ ← CODEX_HOME (codex runtime) │ Created by the sandbox image (codex will not start without it); │ populated by CodexRuntime.Bootstrap (#6920, follow-up PR) +│ └── agents/.toml Native sub-agent roles (skill personas plus default and explore), written only +│ when the ADR 0126 gate holds; runner-held digests, checked by the spawn guard (#6970) │ ├── claude-config/ ← CLAUDE_CONFIG_DIR (personal level) │ ├── agents/ @@ -1258,7 +1260,7 @@ as the place its expected value comes from. There are two trustworthy places — | hook adapter, auth script | **compile-time** — `go:embed`ed, so the digest is a literal in the run command | SHA-256, exit 97 | | the shared hook scripts | **compile-time** for the bytes, **runner-held** for which names — Bootstrap records the name → digest map for the set the harness enabled | SHA-256 per filename, plus an exhaustive directory check, exit 97 | | `config.toml`, `hooks.json` | **runner-held** — rendered per run, so Bootstrap records what it uploaded outside the sandbox and Run injects it into the launch command (`codex_integrity.go`) | whole-file SHA-256, exit 98 | -| `agents/.toml` (role files; none written yet) | **runner-held** — Bootstrap records name → digest in `RoleFiles`; Run exports it with `hooks.json`'s digest as `FULLSEND_CODEX_SPAWN_DIGESTS` | SHA-256 per filename plus an exhaustive `agents/` check, by the spawn guard before every spawn; exit 2 | +| `agents/.toml` | **runner-held** — rendered per run from the skills' `sub-agents/*.md` plus the built-in `default` and `explore`; Bootstrap records one digest per role name (`RoleFiles`) and the run command exports them as `FULLSEND_CODEX_SPAWN_DIGESTS` | SHA-256 per file name plus an exhaustive directory check by the spawn guard before every spawn: a changed, missing or extra file denies the spawn (exit 2 with a reason) | | `fullsend-manifest.json` | none — it is a file in the same agent-writable directory | information only; never authority | The hook-script check makes codex **stricter than Claude Code and pi**, where the scripts stay @@ -1422,8 +1424,11 @@ Two artefacts of the run are worth knowing about: and local smoke runs. - The rollout session files are archived as transcripts but not error-classified: only the tee'd `exec --json` capture yields a verdict, which is what the runner's exit-code override reads. -- Sub-agent rosters are not wired, so `review`/`retro` are unsupported; `Bootstrap` appends a runtime - note telling the agent to execute sub-agent definitions itself, in order, as it does for pi. +- 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. ### Re-check on a `CODEX_VERSION` bump @@ -1445,3 +1450,4 @@ 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'` | diff --git a/internal/runtime/codex_bootstrap.go b/internal/runtime/codex_bootstrap.go index bd5fc7e9a5..1f377382e4 100644 --- a/internal/runtime/codex_bootstrap.go +++ b/internal/runtime/codex_bootstrap.go @@ -70,6 +70,9 @@ var claudeToolForCodex = map[string]string{ func (r CodexRuntime) codexHooksDir() string { return r.ConfigDir() + "/hooks" } +// codexRolesDir is where codex discovers sub-agent roles at launch (#6970). +func (r CodexRuntime) codexRolesDir() string { return r.ConfigDir() + "/agents" } + func (r CodexRuntime) codexManifestPath() string { return r.ConfigDir() + "/" + codexManifestFile } func (r CodexRuntime) codexSessionsDir() string { return r.ConfigDir() + "/sessions" } @@ -151,6 +154,25 @@ func (r CodexRuntime) Bootstrap(input BootstrapInput) error { if !ok || repoInput.RepoDir() == "" { return fmt.Errorf("codex bootstrap: the target repository's sandbox path is required") } + // ADR 0126 gate. Part one: tools include Agent and harness security is + // 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. + _, securityOn := input.(SandboxHooksBootstrap) + var catalog codexCatalog + delegating := false + if codexDelegates(def, securityOn) { + if catalog, err = codexPreflightCatalog(sandboxName); err != nil { + return err + } + 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) + } + } // The gateway provider is rendered only when the runner registered an // inference.gateway block for this sandbox (PrepareGatewayRun). gatewayBaseURL := codexGatewayRunFor(sandboxName) @@ -273,6 +295,23 @@ func (r CodexRuntime) Bootstrap(input BootstrapInput) error { return fmt.Errorf("writing %s: %w", codexHooksFile, err) } 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 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) { + 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) + } + digests.RoleFiles[role.Name] = codexAssetSHA256(data) + } + } manifest.Hooks = codexHooksManifestFor(r.codexHooksDir(), hooks) } @@ -433,6 +472,26 @@ func codexPreflightVersion(sandboxName string) (string, error) { return sanitizeOutput(number), nil } +// codexPreflightCatalog dumps the catalog compiled into the pinned binary +// (offline, no CODEX_HOME needed) and parses it. Failure here is a broken +// image, reported before any iteration. +func codexPreflightCatalog(sandboxName string) (codexCatalog, error) { + const cmd = "codex debug models --bundled" + stdout, stderr, exitCode, err := sandbox.Exec(sandboxName, cmd, 30*time.Second) + if err != nil { + return nil, fmt.Errorf("codex preflight: %w", err) + } + if exitCode != 0 { + return nil, fmt.Errorf("codex preflight: `%s` exited %d: %s", + cmd, exitCode, strings.TrimSpace(sanitizeOutput(stderr))) + } + catalog, err := parseCodexCatalog([]byte(stdout)) + if err != nil { + return nil, fmt.Errorf("codex preflight: `%s` printed no model catalog: %w", cmd, err) + } + return catalog, nil +} + // codexVersionPrefix is what `codex --version` puts before the number. // Asserted at image build time too (images/sandbox/Containerfile compares the // whole "codex-cli " string), so a change here shows up as a build diff --git a/internal/runtime/codex_bootstrap_test.go b/internal/runtime/codex_bootstrap_test.go index a103abc2a2..dadffa5169 100644 --- a/internal/runtime/codex_bootstrap_test.go +++ b/internal/runtime/codex_bootstrap_test.go @@ -67,6 +67,7 @@ if [ "$2" = "exec" ]; then sh -c 'mkdir() { :; }; mv() { shift; shift; cp -- "$1" '\''` + storeDir + `/'\''"$(printf "%s" "$2" | tr / _)"; }; '"$last" exit $? ;; "codex --version") echo "` + versionOutput + `"; exit 0 ;; + "codex debug models --bundled") cat "${FULLSEND_TEST_CATALOG:-testdata/codex/models-bundled-0.159.3.json}"; exit 0 ;; "command -v python3") echo "/usr/bin/python3"; exit 0 ;; *"sys.version_info"*) echo "${FULLSEND_TEST_PYVER:-3.12}"; exit 0 ;; *fullsend-env-sep*) printf '%s' "${FULLSEND_TEST_ENV_READ-|fullsend-env-sep|}"; exit 0 ;; @@ -680,3 +681,239 @@ func TestHomeAgentsMDPath(t *testing.T) { assert.Equal(t, sandbox.SandboxCodexConfig+"/AGENTS.md", HomeAgentsMDPath(CodexRuntime{})) assert.Empty(t, HomeAgentsMDPath(ClaudeRuntime{}), "Claude reads the repo's own context files") } + +// The catalog preflight is a sandbox exec like codexPreflightVersion: a +// failed command, unparsable output and an empty catalog each fail +// Bootstrap with their own message rather than leaving the gate half decided. +func TestCodexPreflightCatalog(t *testing.T) { + t.Run("reads the fixture", func(t *testing.T) { + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "codex-cli 0.152.1") + catalog, err := codexPreflightCatalog("sb") + require.NoError(t, err) + assert.True(t, catalog.resolvesV1("gpt-5.6-luna")) + }) + t.Run("command fails", func(t *testing.T) { + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "codex-cli 0.152.1") + t.Setenv("FULLSEND_TEST_FAIL_MATCH", "codex debug models --bundled") + _, err := codexPreflightCatalog("sb") + require.Error(t, err) + assert.Contains(t, err.Error(), "codex preflight: `codex debug models --bundled` exited 1") + }) + t.Run("output is not a catalog", func(t *testing.T) { + bad := filepath.Join(t.TempDir(), "catalog.json") + require.NoError(t, os.WriteFile(bad, []byte("codex-cli 0.152.1\n"), 0o644)) + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "codex-cli 0.152.1") + t.Setenv("FULLSEND_TEST_CATALOG", bad) + _, err := codexPreflightCatalog("sb") + require.Error(t, err) + assert.Contains(t, err.Error(), "codex preflight: `codex debug models --bundled` printed no model catalog") + }) +} + +// codexDelegatingHooksInput is the ADR 0126 gate met: an agent whose tools +// include Agent, with harness security on, whose definition model (the +// run-level model of the double is "") is the listed V1 model of the fixture. +func codexDelegatingHooksInput(t *testing.T, skillDirs ...string) codexHooksBootstrapInput { + t.Helper() + return codexHooksBootstrapInput{ + bootstrapInput: bootstrapInput{ + sandboxName: "sb", + agentPath: writeAgentFile(t, codexTestDelegatingAgentDef), + agentName: "review", + skillDirs: skillDirs, + }, + hooks: security.SandboxHookConfigFromHarness(&harness.Harness{}), + } +} + +func TestCodexRolesDir(t *testing.T) { + t.Parallel() + assert.Equal(t, sandbox.SandboxCodexConfig+"/agents", CodexRuntime{}.codexRolesDir(), + "the directory codex scans for roles at launch") +} + +// 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. +func TestCodexRuntimeBootstrap_WritesRoleFilesForADelegatingAgent(t *testing.T) { + logPath := filepath.Join(t.TempDir(), "openshell.log") + storeDir := t.TempDir() + fakeOpenshellCodex(t, logPath, storeDir, "codex-cli 0.152.1") + forgetRunnerHeldDigests("sb") + t.Cleanup(func() { forgetRunnerHeldDigests("sb") }) + skill := t.TempDir() + writePersonaFile(t, skill, "correctness", codexTestPersona) + + r := CodexRuntime{} + require.NoError(t, r.Bootstrap(codexDelegatingHooksInput(t, skill))) + + log := readFileString(t, logPath) + assert.Contains(t, log, "mkdir -p "+shellQuote(r.codexRolesDir()), "the roles directory is created only when the gate passes") + assert.Contains(t, log, "codex debug models --bundled", "the catalog preflight runs for a delegating agent") + + held, ok := lookupRunnerHeldDigests("sb") + require.True(t, ok) + want := codexRoles([]string{skill}, "review") + require.Len(t, held.RoleFiles, len(want)) + var names []string + for name := range held.RoleFiles { + names = append(names, name) + } + assert.ElementsMatch(t, []string{"correctness", "default", "explore"}, names) + for _, role := range want { + path := r.codexRolesDir() + "/" + role.Name + ".toml" + got := storedUpload(t, storeDir, path) + 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 +// (security on, tools include Agent) and part two (codex resolves the parent +// model to V1: its entry selects V1 or carries no version). With part one +// failed, no catalog is read; with part two failed, the catalog was read and +// nothing else happens: no directory is created, nothing is uploaded and the +// digest set has no role entry. The gpt-5.5 case is the boundary: an entry +// without a version delegates (ADR 0126), so its files are present. +func TestCodexRuntimeBootstrap_NoRoleFilesWhenTheGateFails(t *testing.T) { + skill := t.TempDir() + writePersonaFile(t, skill, "correctness", codexTestPersona) + hooks := security.SandboxHookConfigFromHarness(&harness.Harness{}) + delegating := func(agentDef, parentModel string) codexHooksBootstrapInput { + return codexHooksBootstrapInput{ + bootstrapInput: bootstrapInput{sandboxName: "sb", agentPath: writeAgentFile(t, agentDef), agentName: "review", skillDirs: []string{skill}, parentModel: parentModel}, + hooks: hooks, + } + } + v2Def := strings.Replace(codexTestDelegatingAgentDef, "gpt-5.6-luna", "gpt-5.6-sol", 1) + unlistedDef := strings.Replace(codexTestDelegatingAgentDef, "gpt-5.6-luna", "gpt-5.6-nova", 1) + noVersionDef := strings.Replace(codexTestDelegatingAgentDef, "gpt-5.6-luna", "gpt-5.5", 1) + for name, tc := range map[string]struct { + input BootstrapInput + preflight bool + delegating bool + reason string // the one stderr line of a declined parent + }{ + "security on, agent without the Agent tool": {codexHooksBootstrapInput{ + bootstrapInput: bootstrapInput{sandboxName: "sb", agentPath: writeAgentFile(t, codexTestAgentDef), agentName: "triage", skillDirs: []string{skill}}, + hooks: hooks, + }, false, false, ""}, + "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 has no version (gpt-5.5)": {delegating(noVersionDef, ""), true, true, ""}, + } { + t.Run(name, func(t *testing.T) { + logPath := filepath.Join(t.TempDir(), "openshell.log") + fakeOpenshellCodex(t, logPath, t.TempDir(), "codex-cli 0.152.1") + forgetRunnerHeldDigests("sb") + t.Cleanup(func() { forgetRunnerHeldDigests("sb") }) + + r := CodexRuntime{} + var err error + out := captureStderr(t, func() { err = r.Bootstrap(tc.input) }) + require.NoError(t, err) + 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.Equal(t, wantLines, strings.Count(out, "sub-agents: "), "one stderr line exactly when part two of the gate declines") + + log := readFileString(t, logPath) + assert.Equal(t, tc.delegating, strings.Contains(log, r.codexRolesDir()), "the roles directory exists exactly when the gate holds") + assert.Equal(t, tc.preflight, strings.Contains(log, "codex debug models --bundled"), + "the catalog is read only once part one of the gate passed") + held, ok := lookupRunnerHeldDigests("sb") + require.True(t, ok) + assert.Equal(t, tc.delegating, held.RoleFiles != nil, "role digests are recorded exactly when the gate holds") + }) + } +} + +// The three new infrastructure failures are reported with their own message, +// like the rows of TestCodexRuntimeBootstrap_ReportsInfrastructureFailures. +func TestCodexRuntimeBootstrap_ReportsRoleFileFailures(t *testing.T) { + r := CodexRuntime{} + for name, tc := range map[string]struct{ match, want string }{ + "roles dir": {"mkdir -p " + shellQuote(r.codexRolesDir()), "creating codex roles dir"}, + "role file": {r.codexRolesDir() + "/default.toml", `writing role "default"`}, + "catalog preflight": {"codex debug models --bundled", "codex preflight: `codex debug models --bundled` exited 1"}, + } { + t.Run(name, func(t *testing.T) { + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), t.TempDir(), "codex-cli 0.152.1") + t.Setenv("FULLSEND_TEST_FAIL_MATCH", tc.match) + + err := r.Bootstrap(codexDelegatingHooksInput(t)) + require.Error(t, err) + assert.Contains(t, err.Error(), tc.want) + }) + } +} + +// TestCodexBootstrap_PlantedRoleFileDeniesSpawn checks the runner-held role +// 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. +func TestCodexBootstrap_PlantedRoleFileDeniesSpawn(t *testing.T) { + h := newCodexAdapterHarness(t) + storeDir := t.TempDir() + fakeOpenshellCodex(t, filepath.Join(t.TempDir(), "log"), storeDir, "codex-cli 0.152.1") + forgetRunnerHeldDigests("sb") + t.Cleanup(func() { forgetRunnerHeldDigests("sb") }) + skill := t.TempDir() + writePersonaFile(t, skill, "correctness", codexTestPersona) + + r := CodexRuntime{} + require.NoError(t, r.Bootstrap(codexDelegatingHooksInput(t, skill))) + held, ok := lookupRunnerHeldDigests("sb") + require.True(t, ok) + require.NotEmpty(t, held.RoleFiles) + + // CODEX_HOME on the host, exactly the bytes Bootstrap uploaded: the + // adapter resolves hooks.json and agents/ relative to its own directory. + h.write(codexHooksFile, string(storedUpload(t, storeDir, r.codexHooksPath()))) + for name := range held.RoleFiles { + h.write("agents/"+name+".toml", string(storedUpload(t, storeDir, r.codexRolesDir()+"/"+name+".toml"))) + } + spawn := func(role string) codexAdapterResult { + return h.spawnGuardWith(codexSpawnInput(role), codexSpawnDigestsValue(held)) + } + + t.Run("admits a registered role from the files Bootstrap wrote", func(t *testing.T) { + got := spawn("correctness") + assert.Equal(t, 0, got.exitCode, "stderr: %s", got.stderr) + }) + t.Run("denies a role that was never registered", func(t *testing.T) { + got := spawn("planted") + assert.Equal(t, 2, got.exitCode) + assert.NotEmpty(t, got.stderr, "a block is exit 2 with a non-empty reason, or codex lets the spawn through") + }) + t.Run("denies every spawn once a file is planted in agents/", func(t *testing.T) { + h.write("agents/planted.toml", "name = \"planted\"\ndescription = \"x\"\ndeveloper_instructions = \"x\"\n") + t.Cleanup(func() { require.NoError(t, os.Remove(filepath.Join(h.dir, "agents", "planted.toml"))) }) + got := spawn("correctness") + assert.Equal(t, 2, got.exitCode, "an entry that is not a runner-held key denies the spawn (exhaustive check)") + assert.NotEmpty(t, got.stderr) + }) + t.Run("denies a registered role whose file was edited", func(t *testing.T) { + h.write("agents/correctness.toml", "name = \"correctness\"\ndescription = \"x\"\ndeveloper_instructions = \"changed\"\n") + got := spawn("correctness") + assert.Equal(t, 2, got.exitCode) + assert.NotEmpty(t, got.stderr) + }) +} diff --git a/internal/runtime/codex_golden_test.go b/internal/runtime/codex_golden_test.go index 30bcb10bcb..02806a0027 100644 --- a/internal/runtime/codex_golden_test.go +++ b/internal/runtime/codex_golden_test.go @@ -105,6 +105,15 @@ func TestCodexGolden(t *testing.T) { {"launch-nohooks.txt", func(t *testing.T) string { return codexGoldenLaunch(buildCodexRunCommand(RunParams{RepoDir: repo}, codexModel{ID: "gpt-5.6-luna"}, "", false, noHooks)) }}, + // The role files of a delegating agent and its launch command. + // codexRoles sorts by name (TestCodexRoles_SkillPersonasSorted), so the + // indexes are correctness, default, explore. + {"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()) }}, + {"launch-delegating.txt", func(t *testing.T) string { + return codexGoldenLaunch(buildCodexRunCommand(hooksOn, codexModel{ID: "gpt-5.6-luna"}, "high", true, codexGoldenDelegatingDigests(t))) + }}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -128,3 +137,48 @@ func TestCodexGolden(t *testing.T) { }) } } + +// codexGoldenRoles renders the roles of a review agent with the test +// correctness persona (codexTestPersona): three files, no model line. +func codexGoldenRoles(t *testing.T) []codexRole { + t.Helper() + skill := t.TempDir() + writePersonaFile(t, skill, "correctness", codexTestPersona) + return codexRoles([]string{skill}, "review") +} + +// codexGoldenDelegatingDigests is testRunnerHeldDigests plus the role +// entries a delegating agent's Bootstrap records. +func codexGoldenDelegatingDigests(t *testing.T) codexRunnerHeldDigestSet { + t.Helper() + d := testRunnerHeldDigests + d.RoleFiles = map[string]string{} + for _, role := range codexGoldenRoles(t) { + d.RoleFiles[role.Name] = codexAssetSHA256(role.toml()) + } + return d +} + +// The invariant of the role files: a delegating agent's launch command +// differs from a non-delegating one in the FULLSEND_CODEX_SPAWN_DIGESTS +// value and in nothing else. Rendered here from both digest sets with the +// golden inputs, so it holds independently of the files. +func TestCodexGolden_DelegatingLaunchDiffersOnlyInSpawnDigests(t *testing.T) { + t.Parallel() + + plain := strings.Split(codexGoldenLaunch(buildCodexRunCommand(hooksOn, codexModel{ID: "gpt-5.6-luna"}, "high", true, testRunnerHeldDigests)), "\n") + delegating := strings.Split(codexGoldenLaunch(buildCodexRunCommand(hooksOn, codexModel{ID: "gpt-5.6-luna"}, "high", true, codexGoldenDelegatingDigests(t))), "\n") + require.Len(t, delegating, len(plain), "no fragment added or removed") + + var changed []int + for i := range plain { + if plain[i] != delegating[i] { + changed = append(changed, i) + } + } + require.Len(t, changed, 1, "exactly one fragment differs") + assert.Equal(t, "export "+codexSpawnDigestsEnv+"='hooks.json:'", strings.TrimSuffix(plain[changed[0]], " &&")) + assert.Equal(t, "export "+codexSpawnDigestsEnv+ + "='agents/correctness.toml: agents/default.toml: agents/explore.toml: hooks.json:'", + strings.TrimSuffix(delegating[changed[0]], " &&"), "one entry per role, ascending, file-name bound") +} diff --git a/internal/runtime/codex_personas.go b/internal/runtime/codex_personas.go index 2905461136..1ed273df91 100644 --- a/internal/runtime/codex_personas.go +++ b/internal/runtime/codex_personas.go @@ -1,6 +1,7 @@ package runtime import ( + "encoding/json" "fmt" "os" "slices" @@ -119,3 +120,72 @@ func codexDroppedFrontmatterKeys(frontmatter []byte) []string { } return keys } + +// 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 +// dumps the catalog compiled into the binary and makes no request. +type codexCatalog map[string]string + +// has reports whether the catalog lists the model. +func (c codexCatalog) has(slug string) bool { _, ok := c[slug]; return ok } + +// resolvesV1 reports whether codex resolves the model to collaboration V1, +// the only version whose spawn tool the guard admits (ADR 0126): the entry +// 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 == "") +} + +// 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. +func parseCodexCatalog(data []byte) (codexCatalog, error) { + var dump struct { + Models []struct { + Slug string `json:"slug"` + MultiAgentVersion string `json:"multi_agent_version"` + } `json:"models"` + } + if err := json.Unmarshal(data, &dump); err != nil { + return nil, fmt.Errorf("decoding the model catalog: %w", err) + } + if len(dump.Models) == 0 { + return nil, fmt.Errorf("the model catalog lists no model") + } + catalog := make(codexCatalog, len(dump.Models)) + for _, m := range dump.Models { + catalog[m.Slug] = m.MultiAgentVersion + } + return catalog, nil +} + +// codexParentResolvesV1 is part two of the ADR 0126 gate. The parent is the +// model Run will launch — EffectiveModel(parentModel, agentModel), the +// expression Run launches with, translated by translateCodexModel — and +// 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 +// 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. +func codexParentResolvesV1(catalog codexCatalog, parentModel, agentModel string) (bool, string) { + model, err := translateCodexModel(EffectiveModel(parentModel, agentModel), true) + if err != nil { + return false, err.Error() + } + id := model.ID + switch { + case !catalog.has(id): + return false, fmt.Sprintf("parent model %q is not in the bundled catalog of the pinned codex", id) + case catalog.resolvesV1(id): + return true, "" + default: + return false, fmt.Sprintf("parent model %q selects collaboration %q", id, catalog[id]) + } +} diff --git a/internal/runtime/codex_personas_test.go b/internal/runtime/codex_personas_test.go index c6f30faf97..32a6b8f4fa 100644 --- a/internal/runtime/codex_personas_test.go +++ b/internal/runtime/codex_personas_test.go @@ -3,7 +3,10 @@ package runtime import ( "encoding/json" "fmt" + "os" "os/exec" + "path/filepath" + "regexp" "strings" "testing" @@ -326,3 +329,80 @@ func TestCodexRole_TOMLParsesWithTheThreeKeys(t *testing.T) { assert.Equal(t, role.Instructions, doc["developer_instructions"], "%s: the body round-trips", role.Name) } } + +// 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): +// +// 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 +func TestCodexCatalog(t *testing.T) { + t.Parallel() + containerfile, err := os.ReadFile(filepath.Join("..", "..", "images", "sandbox", "Containerfile")) + require.NoError(t, err) + pin := regexp.MustCompile(`(?m)^ARG CODEX_VERSION=(\S+)$`).FindStringSubmatch(string(containerfile)) + require.Len(t, pin, 2) + data, err := os.ReadFile("testdata/codex/models-bundled-" + pin[1] + ".json") + require.NoError(t, err, "the fixture is named after the pin: regenerate it for %s", pin[1]) + 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("gpt-5.6-sol")) + assert.False(t, catalog.resolvesV1("gpt-5.6-sol"), "sol selects V2") + assert.True(t, catalog.has("gpt-5.5")) + assert.True(t, catalog.resolvesV1("gpt-5.5"), "an entry without a version takes V1 from the multi_agent feature") + assert.False(t, catalog.has("gpt-5.6-nova")) + assert.False(t, catalog.resolvesV1("gpt-5.6-nova")) + // Hidden entries count: the fixture keeps no `visibility`, so the hidden + // V1 entry resolves to V1 like a listed one and a hidden model is listed. + assert.True(t, catalog.has("codex-auto-review")) + assert.True(t, catalog.resolvesV1("codex-auto-review"), "a hidden entry that selects V1 resolves to V1") + assert.True(t, catalog.has("gpt-daybreak-blue-latest"), "a hidden model passes the membership check") + assert.False(t, catalog.resolvesV1("gpt-daybreak-blue-latest"), "hidden and V2") + + _, err = parseCodexCatalog([]byte("not json")) + require.Error(t, err) + _, err = parseCodexCatalog([]byte(`{"models": []}`)) + require.Error(t, err, "an empty catalog is a broken binary, not a catalog") +} + +// TestCodexParentResolvesV1 is part two of the ADR 0126 gate: the parent model +// 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. +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"} + tests := []struct { + name string + parentModel string + agentModel string + want bool + wantReason string + }{ + {"definition model, V1", "", "openai/gpt-5.6-luna", true, ""}, + {"run-level model wins", "openai/gpt-5.6-luna", "openai/gpt-5.6-sol", true, ""}, + {"run-level V2 beats a V1 definition", "openai/gpt-5.6-sol", "openai/gpt-5.6-luna", false, `parent model "gpt-5.6-sol" selects collaboration "v2"`}, + {"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`}, + {"claude alias does not translate", "", "opus", false, "codex takes OpenAI model ids or gateway/ only"}, + {"no model at all", "", "", false, "no model was named"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got, reason := codexParentResolvesV1(catalog, tt.parentModel, tt.agentModel) + assert.Equal(t, tt.want, got) + if tt.want { + assert.Empty(t, reason) + } else { + assert.Contains(t, reason, tt.wantReason) + } + }) + } +} diff --git a/internal/runtime/testdata/codex/golden/launch-delegating.txt b/internal/runtime/testdata/codex/golden/launch-delegating.txt new file mode 100644 index 0000000000..5fa6ae3fe4 --- /dev/null +++ b/internal/runtime/testdata/codex/golden/launch-delegating.txt @@ -0,0 +1,93 @@ +cd '/sandbox/workspace/repo' && +{ readonly FULLSEND_CODEX_BIN="$(command -v codex)" && +case "$FULLSEND_CODEX_BIN" in /*) ;; *) false ;; esac || { echo 'fullsend: codex not found on PATH' >&2; exit 127; }; } && +readonly FULLSEND_CODEX_PATH="$PATH" && +{ test -f '/sandbox/codex-config/config.toml' && +test -f '/sandbox/codex-config/openai-token.sh' && +[ "$(command -p sha256sum '/sandbox/codex-config/openai-token.sh' | command -p cut -d' ' -f1)" = '' ] && +test -f '/sandbox/codex-config/hooks.json' && +test -f '/sandbox/codex-config/fullsend-manifest.json' && +test -f '/sandbox/codex-config/fullsend-codex-hook.py' && +[ "$(command -p sha256sum '/sandbox/codex-config/fullsend-codex-hook.py' | command -p cut -d' ' -f1)" = '' ] && +[ "$(command -p grep -o '"command":' '/sandbox/codex-config/hooks.json' | command -p wc -l)" = "$(command -p grep -o '/sandbox/codex-config/fullsend-codex-hook.py' '/sandbox/codex-config/hooks.json' | command -p wc -l)" ] && +{ test -f '/sandbox/codex-config/hooks/canary_posttool.py' && +[ "$(command -p sha256sum '/sandbox/codex-config/hooks/canary_posttool.py' | command -p cut -d' ' -f1)" = '' ] && +test -f '/sandbox/codex-config/hooks/canary_pretool.py' && +[ "$(command -p sha256sum '/sandbox/codex-config/hooks/canary_pretool.py' | command -p cut -d' ' -f1)" = '' ] && +test -f '/sandbox/codex-config/hooks/context_suppress_posttool.py' && +[ "$(command -p sha256sum '/sandbox/codex-config/hooks/context_suppress_posttool.py' | command -p cut -d' ' -f1)" = '' ] && +test -f '/sandbox/codex-config/hooks/hook_io.py' && +[ "$(command -p sha256sum '/sandbox/codex-config/hooks/hook_io.py' | command -p cut -d' ' -f1)" = '' ] && +test -f '/sandbox/codex-config/hooks/posttool_chain.py' && +[ "$(command -p sha256sum '/sandbox/codex-config/hooks/posttool_chain.py' | command -p cut -d' ' -f1)" = '' ] && +test -f '/sandbox/codex-config/hooks/secret_redact_posttool.py' && +[ "$(command -p sha256sum '/sandbox/codex-config/hooks/secret_redact_posttool.py' | command -p cut -d' ' -f1)" = '' ] && +test -f '/sandbox/codex-config/hooks/ssrf_pretool.py' && +[ "$(command -p sha256sum '/sandbox/codex-config/hooks/ssrf_pretool.py' | command -p cut -d' ' -f1)" = '' ] && +test -f '/sandbox/codex-config/hooks/tirith_check.py' && +[ "$(command -p sha256sum '/sandbox/codex-config/hooks/tirith_check.py' | command -p cut -d' ' -f1)" = '' ] && +test -f '/sandbox/codex-config/hooks/unicode_posttool.py' && +[ "$(command -p sha256sum '/sandbox/codex-config/hooks/unicode_posttool.py' | command -p cut -d' ' -f1)" = '' ] && +[ "$(command -p find '/sandbox/codex-config/hooks' -mindepth 1 | command -p wc -l)" -eq 9 ] && +[ -z "$(command -p find '/sandbox/codex-config/hooks' -mindepth 1 ! -type f -print)" ] || { echo 'fullsend: the sandbox hook scripts are not the set fullsend installed (a file was changed, replaced with another allowed file, or something was added); refusing to run' >&2; exit 97; }; } || { echo 'fullsend: codex config, hook adapter or auth script missing or modified; refusing to run' >&2; exit 97; }; } && +{ [ "$(command -p sha256sum '/sandbox/codex-config/config.toml' | command -p cut -d' ' -f1)" = '' ] && +[ "$(command -p sha256sum '/sandbox/codex-config/hooks.json' | command -p cut -d' ' -f1)" = '' ] || { echo 'fullsend: codex config.toml or hooks.json is not the file fullsend wrote; refusing to run (a rewritten config can trust the target repo, which loads its .codex/ layer and its hooks)' >&2; exit 98; }; } && +command -p rm -f '/sandbox/codex-config/models_cache.json' && +case "${OPENAI_API_KEY:-}" in openshell:resolve:env:*OPENAI_API_KEY) ;; *) echo 'fullsend: OPENAI_API_KEY in the sandbox is not a gateway placeholder (openai provider not attached, or a real key reached the sandbox); refusing to run codex' >&2; exit 1 ;; esac && +case "$OPENAI_API_KEY" in *[!A-Za-z0-9_:]*) echo 'fullsend: OPENAI_API_KEY placeholder has unexpected characters; refusing to run codex' >&2; exit 1 ;; esac && +{ case "${FULLSEND_SEED_PREVIOUS:-}" in *[!A-Za-z0-9_:\ ]*) echo 'fullsend: FULLSEND_SEED_PREVIOUS has unexpected characters; refusing to seed' >&2; exit 1 ;; esac && +command -p mkdir -p '/sandbox/codex-config' && +{ command -p flock -w 10 9 && +{ test -z "${FULLSEND_SEED_PREVIOUS:-}" || { { for fullsend_g in $FULLSEND_SEED_PREVIOUS; do command -p grep -qxF -e "$fullsend_g" '/sandbox/codex-config/openai-token.generations' 2>/dev/null || printf '%s\n' "$fullsend_g"; done; command -p cat '/sandbox/codex-config/openai-token.generations' 2>/dev/null || :; } > '/sandbox/codex-config/openai-token.generations'.$$ && +command -p mv -f '/sandbox/codex-config/openai-token.generations'.$$ '/sandbox/codex-config/openai-token.generations'; }; } && +{ fullsend_last=$(command -p tail -n 1 '/sandbox/codex-config/openai-token.generations' 2>/dev/null) || :; } && +if test "$fullsend_last" != "$OPENAI_API_KEY" && +command -p grep -qxF -e "$OPENAI_API_KEY" '/sandbox/codex-config/openai-token.generations' 2>/dev/null; then if { case "$fullsend_last" in ''|*[!A-Za-z0-9_:]*) command -p false ;; openshell:resolve:env:*OPENAI_API_KEY) fullsend_want=$( OPENAI_API_KEY="$fullsend_last"; printf '%s' "$OPENAI_API_KEY" ) && +test -n "$fullsend_want" && +fullsend_have=$(command -p cat '/sandbox/codex-config/openai-token' 2>/dev/null) && +test "$fullsend_have" = "$fullsend_want" ;; *) command -p false ;; esac; }; then echo 'fullsend: OPENAI_API_KEY is an older generation than the credential file holds; leaving the file as it is' >&2; else echo 'fullsend: OPENAI_API_KEY is older than the newest generation in the history, but the credential file does not hold that one; not treating the skipped write as done' >&2; command -p false; fi; else { test "$fullsend_last" = "$OPENAI_API_KEY" || printf '%s\n' "$OPENAI_API_KEY" >> '/sandbox/codex-config/openai-token.generations'; } && +printf '%s' "$OPENAI_API_KEY" > '/sandbox/codex-config/openai-token.fullsend'.$$ && +command -p mv -f '/sandbox/codex-config/openai-token.fullsend'.$$ '/sandbox/codex-config/openai-token'; fi; } 9>>'/sandbox/codex-config/openai-token.fullsend-seed.lock' || { command -p rm -f '/sandbox/codex-config/openai-token.fullsend'.$$ '/sandbox/codex-config/openai-token.generations'.$$; echo 'fullsend: writing the codex token file failed' >&2; exit 1; }; } && +. '/sandbox/workspace/.env' && +export CODEX_HOME=/sandbox/codex-config && +export PATH="$FULLSEND_CODEX_PATH" && +export FULLSEND_CODEX_PATH && +export FULLSEND_RUNTIME=codex && +unset OPENAI_BASE_URL OPENAI_API_KEY CODEX_API_KEY NODE_OPTIONS NODE_PATH PYTHONPATH PYTHONHOME PYTHONSTARTUP LD_PRELOAD LD_LIBRARY_PATH LD_AUDIT && +unset -f test command grep cut wc sha256sum printf codex && +{ test -f '/sandbox/codex-config/config.toml' && +test -f '/sandbox/codex-config/openai-token.sh' && +[ "$(command -p sha256sum '/sandbox/codex-config/openai-token.sh' | command -p cut -d' ' -f1)" = '' ] && +test -f '/sandbox/codex-config/hooks.json' && +test -f '/sandbox/codex-config/fullsend-manifest.json' && +test -f '/sandbox/codex-config/fullsend-codex-hook.py' && +[ "$(command -p sha256sum '/sandbox/codex-config/fullsend-codex-hook.py' | command -p cut -d' ' -f1)" = '' ] && +[ "$(command -p grep -o '"command":' '/sandbox/codex-config/hooks.json' | command -p wc -l)" = "$(command -p grep -o '/sandbox/codex-config/fullsend-codex-hook.py' '/sandbox/codex-config/hooks.json' | command -p wc -l)" ] && +{ test -f '/sandbox/codex-config/hooks/canary_posttool.py' && +[ "$(command -p sha256sum '/sandbox/codex-config/hooks/canary_posttool.py' | command -p cut -d' ' -f1)" = '' ] && +test -f '/sandbox/codex-config/hooks/canary_pretool.py' && +[ "$(command -p sha256sum '/sandbox/codex-config/hooks/canary_pretool.py' | command -p cut -d' ' -f1)" = '' ] && +test -f '/sandbox/codex-config/hooks/context_suppress_posttool.py' && +[ "$(command -p sha256sum '/sandbox/codex-config/hooks/context_suppress_posttool.py' | command -p cut -d' ' -f1)" = '' ] && +test -f '/sandbox/codex-config/hooks/hook_io.py' && +[ "$(command -p sha256sum '/sandbox/codex-config/hooks/hook_io.py' | command -p cut -d' ' -f1)" = '' ] && +test -f '/sandbox/codex-config/hooks/posttool_chain.py' && +[ "$(command -p sha256sum '/sandbox/codex-config/hooks/posttool_chain.py' | command -p cut -d' ' -f1)" = '' ] && +test -f '/sandbox/codex-config/hooks/secret_redact_posttool.py' && +[ "$(command -p sha256sum '/sandbox/codex-config/hooks/secret_redact_posttool.py' | command -p cut -d' ' -f1)" = '' ] && +test -f '/sandbox/codex-config/hooks/ssrf_pretool.py' && +[ "$(command -p sha256sum '/sandbox/codex-config/hooks/ssrf_pretool.py' | command -p cut -d' ' -f1)" = '' ] && +test -f '/sandbox/codex-config/hooks/tirith_check.py' && +[ "$(command -p sha256sum '/sandbox/codex-config/hooks/tirith_check.py' | command -p cut -d' ' -f1)" = '' ] && +test -f '/sandbox/codex-config/hooks/unicode_posttool.py' && +[ "$(command -p sha256sum '/sandbox/codex-config/hooks/unicode_posttool.py' | command -p cut -d' ' -f1)" = '' ] && +[ "$(command -p find '/sandbox/codex-config/hooks' -mindepth 1 | command -p wc -l)" -eq 9 ] && +[ -z "$(command -p find '/sandbox/codex-config/hooks' -mindepth 1 ! -type f -print)" ] || { echo 'fullsend: the sandbox hook scripts are not the set fullsend installed (a file was changed, replaced with another allowed file, or something was added); refusing to run' >&2; exit 97; }; } || { echo 'fullsend: codex config, hook adapter or auth script missing or modified; refusing to run' >&2; exit 97; }; } && +{ [ "$(command -p sha256sum '/sandbox/codex-config/config.toml' | command -p cut -d' ' -f1)" = '' ] && +[ "$(command -p sha256sum '/sandbox/codex-config/hooks.json' | command -p cut -d' ' -f1)" = '' ] || { echo 'fullsend: codex config.toml or hooks.json is not the file fullsend wrote; refusing to run (a rewritten config can trust the target repo, which loads its .codex/ layer and its hooks)' >&2; exit 98; }; } && +command -p rm -f '/sandbox/codex-config/models_cache.json' && +export FULLSEND_CODEX_HOOK_DIGESTS='canary_posttool.py: canary_pretool.py: context_suppress_posttool.py: hook_io.py: posttool_chain.py: secret_redact_posttool.py: ssrf_pretool.py: tirith_check.py: unicode_posttool.py:' && +export FULLSEND_CODEX_SPAWN_DIGESTS='agents/correctness.toml: agents/default.toml: agents/explore.toml: hooks.json:' && +export TIRITH_REQUIRED='1' && +export FULLSEND_EGRESS_ALLOWLIST='api.github.com:443' && +printf '%s' 'Run the agent task' | "$FULLSEND_CODEX_BIN" exec --json --skip-git-repo-check --dangerously-bypass-approvals-and-sandbox --dangerously-bypass-hook-trust -C '/sandbox/workspace/repo' --model 'gpt-5.6-luna' -c 'model_provider=fullsend-openai' -c 'approval_policy=never' -c 'sandbox_mode=danger-full-access' -c 'model_providers.fullsend-openai.base_url="https://api.openai.com/v1"' -c 'model_providers.fullsend-openai.auth.command="/sandbox/codex-config/openai-token.sh"' -c 'model_reasoning_effort=high' -o '/sandbox/codex-config/last-message.txt' - diff --git a/internal/runtime/testdata/codex/golden/roles/correctness.toml b/internal/runtime/testdata/codex/golden/roles/correctness.toml new file mode 100644 index 0000000000..5832670056 --- /dev/null +++ b/internal/runtime/testdata/codex/golden/roles/correctness.toml @@ -0,0 +1,7 @@ +name = "correctness" +description = "Evaluates logic correctness, edge cases, nil handling, API contracts, test adequacy/integrity." +developer_instructions = """ +# Correctness + +You are a senior software engineer reviewing for correctness. +""" diff --git a/internal/runtime/testdata/codex/golden/roles/default.toml b/internal/runtime/testdata/codex/golden/roles/default.toml new file mode 100644 index 0000000000..a35455e439 --- /dev/null +++ b/internal/runtime/testdata/codex/golden/roles/default.toml @@ -0,0 +1,7 @@ +name = "default" +description = "Generic sub-agent for a task the parent describes in full in its message." +developer_instructions = """ +# Sub-agent + +Do the task in the message you were given, and only that task. Put your findings, with file paths and line numbers where they apply, in your final message: the parent reads nothing else and owns the synthesis and the final result. +""" diff --git a/internal/runtime/testdata/codex/golden/roles/explore.toml b/internal/runtime/testdata/codex/golden/roles/explore.toml new file mode 100644 index 0000000000..8c22aabd7f --- /dev/null +++ b/internal/runtime/testdata/codex/golden/roles/explore.toml @@ -0,0 +1,7 @@ +name = "explore" +description = "Investigation of the repository by reading only; reports findings. Instruction-only: nothing enforces read-only on a child." +developer_instructions = """ +# Explore + +Answer the question in the message you were given by reading the repository: read files, search, and run commands that change nothing. Do not edit or create files. Put what you found, with file paths and line numbers, in your final message: the parent reads nothing else. +""" diff --git a/internal/runtime/testdata/codex/models-bundled-0.159.3.json b/internal/runtime/testdata/codex/models-bundled-0.159.3.json new file mode 100644 index 0000000000..4ccc3e3f0d --- /dev/null +++ b/internal/runtime/testdata/codex/models-bundled-0.159.3.json @@ -0,0 +1,48 @@ +{ + "models": [ + { + "slug": "gpt-6-astra", + "multi_agent_version": "v2" + }, + { + "slug": "gpt-6.1-sol", + "multi_agent_version": "v2" + }, + { + "slug": "gpt-6-sol", + "multi_agent_version": "v2" + }, + { + "slug": "gpt-6-luna", + "multi_agent_version": "v2" + }, + { + "slug": "gpt-5.6-sol", + "multi_agent_version": "v2" + }, + { + "slug": "gpt-5.6-terra", + "multi_agent_version": "v2" + }, + { + "slug": "gpt-5.6-luna", + "multi_agent_version": "v1" + }, + { + "slug": "gpt-daybreak-blue-latest", + "multi_agent_version": "v2" + }, + { + "slug": "gpt-daybreak-red-latest", + "multi_agent_version": "v2" + }, + { + "slug": "gpt-5.5", + "multi_agent_version": null + }, + { + "slug": "codex-auto-review", + "multi_agent_version": "v1" + } + ] +} From 6094f8b819b0cd1814c339871c5be93c1f504853 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Mon, 12 Oct 2026 21:49:59 -0400 Subject: [PATCH 3/5] refactor(codex): drop a duplicated frontmatter assignment parsePiAgent assigned def.Frontmatter twice on consecutive lines. Signed-off-by: Dharit Shah --- internal/runtime/pi_agent.go | 1 - 1 file changed, 1 deletion(-) diff --git a/internal/runtime/pi_agent.go b/internal/runtime/pi_agent.go index e0c2687ead..deeb95974e 100644 --- a/internal/runtime/pi_agent.go +++ b/internal/runtime/pi_agent.go @@ -80,7 +80,6 @@ func parsePiAgent(data []byte) (*piAgentDef, error) { def.Model = strings.TrimSpace(fm.Model) def.Body = strings.TrimSpace(string(body)) def.Frontmatter = front - def.Frontmatter = front specs, err := piToolSpecs(fm.Tools) if err != nil { From 8d8dd6a176d345d32ca3c3862bee996d005b2102 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Mon, 12 Oct 2026 22:08:48 -0400 Subject: [PATCH 4/5] refactor(codex): scope the role-file model wording to this PR The toml comment and the TOML test read as if a role file never carries a model line. ADR 0126's per-persona model arrives with the PR of #6970 that makes delegation reachable; default and explore never carry one. The expected persona paths in TestCodexRoles_DiscoverySkipIsAWarning are joined with filepath, as discoverPersonas builds them. Signed-off-by: Dharit Shah --- internal/runtime/codex_personas.go | 5 +++-- internal/runtime/codex_personas_test.go | 11 ++++++----- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/internal/runtime/codex_personas.go b/internal/runtime/codex_personas.go index 1ed273df91..1621104141 100644 --- a/internal/runtime/codex_personas.go +++ b/internal/runtime/codex_personas.go @@ -35,8 +35,9 @@ type codexRole struct { var codexReservedRoleNames = []string{"enabled", "explorer", "worker"} // toml renders the role file: name, description and developer_instructions, -// each through codexTOMLString, nothing else. No model line: the run-level -// default applies to every child (#6970). +// 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. func (role codexRole) toml() []byte { return []byte("name = " + codexTOMLString(role.Name) + "\n" + "description = " + codexTOMLString(role.Description) + "\n" + diff --git a/internal/runtime/codex_personas_test.go b/internal/runtime/codex_personas_test.go index 32a6b8f4fa..4b664134ea 100644 --- a/internal/runtime/codex_personas_test.go +++ b/internal/runtime/codex_personas_test.go @@ -86,8 +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, and no dropped -// frontmatter turned into text (#6970). +// 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. func TestCodexRole_TOML(t *testing.T) { t.Parallel() @@ -108,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", "a role never carries a model line") + assert.NotContains(t, got, "model", "no model line in this PR: ADR 0126's per-persona model arrives with delegation (#6970)") } func codexRoleNames(roles []codexRole) []string { @@ -171,8 +172,8 @@ func TestCodexRoles_DiscoverySkipIsAWarning(t *testing.T) { out := captureStderr(t, func() { roles = codexRoles([]string{skill}, "review") }) assert.Equal(t, []string{"default", "explore"}, codexRoleNames(roles)) - assert.Contains(t, out, fmt.Sprintf("Warning: persona %q skipped: name is reserved", skill+"/sub-agents/default.md")) - assert.Contains(t, out, fmt.Sprintf("Warning: persona %q skipped: name must be lowercase alphanumeric", skill+"/sub-agents/Bad.md")) + 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"))) } // One row per rule a persona can break on Codex. Every row is a warning, From 683c8727200e873779d9c706bab16be14f437819 Mon Sep 17 00:00:00 2001 From: Dharit Shah Date: Wed, 14 Oct 2026 10:22:09 -0400 Subject: [PATCH 5/5] refactor(codex): open every role with the child runtime note A native child runs with its role's developer_instructions in place of the parent's, so nothing of codexNoSubagentNote reached it, including the chunked-read rule for exec truncation (#7831), and only the built-in roles stated the child contract. Every role, persona or built-in, now opens with codexChildNote: pi's CHILD_SYSTEM_NOTE word for word, then codexChunkedReadNote, the paragraph factored out of codexNoSubagentNote. The parent's note and config.toml are byte-equal. The built-ins drop their own contract clause. Signed-off-by: Dharit Shah --- docs/contributing/runtime-implementation.md | 4 +++- internal/runtime/codex_bootstrap.go | 18 +++++++------- internal/runtime/codex_personas.go | 24 ++++++++++++++----- internal/runtime/codex_personas_test.go | 6 ++--- .../codex/golden/roles/correctness.toml | 6 +++++ .../testdata/codex/golden/roles/default.toml | 8 ++++++- .../testdata/codex/golden/roles/explore.toml | 8 ++++++- 7 files changed, 54 insertions(+), 20 deletions(-) diff --git a/docs/contributing/runtime-implementation.md b/docs/contributing/runtime-implementation.md index a0ea815938..efe7f82b2a 100644 --- a/docs/contributing/runtime-implementation.md +++ b/docs/contributing/runtime-implementation.md @@ -1101,7 +1101,9 @@ flowchart TB 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` 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). + 200-line ranges, one per tool call (#7831). A native child runs with its role's + `developer_instructions` in place of the parent's, so every role file opens with + `codexChildNote`: the child contract pi gives every child, and the same rule. - **AGENTS.md** — codex skips a project's own `AGENTS.md` while the project is untrusted (`codex-rs/core/src/agents_md.rs`), but always loads `$CODEX_HOME/AGENTS.md` as user instructions. The runner copies the repo's root `AGENTS.md` (or the injected org-level one) there diff --git a/internal/runtime/codex_bootstrap.go b/internal/runtime/codex_bootstrap.go index 1f377382e4..5c18ec6f04 100644 --- a/internal/runtime/codex_bootstrap.go +++ b/internal/runtime/codex_bootstrap.go @@ -373,19 +373,21 @@ func codexDeveloperInstructions(agentName string, def *piAgentDef) string { // 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). -// -// The second paragraph is the chunked-read rule for Codex's exec truncation -// (10,000 tokens, head and tail, at 0.157.0). A single cat of a long SKILL.md -// drops the middle with no retry (#7831). Lines are counted with awk's NR, not -// `wc -l`: `wc -l` counts newline characters, so a file whose last line has no -// trailing newline reports one line too few and the last range would stop -// short of it. 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 " + "definition yourself, in the listed order, with the same context package, and treat each " + "output as that sub-agent's result.\n\n" + - "When reading a SKILL.md or other instruction file, do not cat it in one call: Codex " + + codexChunkedReadNote + +// codexChunkedReadNote is the chunked-read rule for Codex's exec truncation +// (10,000 tokens, head and tail, at 0.157.0). A single cat of a long SKILL.md +// drops the middle with no retry (#7831). Lines are counted with awk's NR, not +// `wc -l`: `wc -l` counts newline characters, so a file whose last line has no +// trailing newline reports one line too few and the last range would stop +// short of it. codexNoSubagentNote and every role file (codexChildNote) end +// their runtime note with it. +const codexChunkedReadNote = "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 " + diff --git a/internal/runtime/codex_personas.go b/internal/runtime/codex_personas.go index 1621104141..b9c85f1817 100644 --- a/internal/runtime/codex_personas.go +++ b/internal/runtime/codex_personas.go @@ -23,7 +23,8 @@ func codexDelegates(def *piAgentDef, securityEnabled bool) bool { // codexRole is one native Codex sub-agent role, written to // $CODEX_HOME/agents/.toml. Instructions is the child's -// developer_instructions: the persona body and nothing else (#6970). +// developer_instructions: codexChildNote, then the persona body; nothing of +// the dropped frontmatter (#6970). type codexRole struct { Name, Description, Instructions string } @@ -44,6 +45,17 @@ func (role codexRole) toml() []byte { "developer_instructions = " + codexTOMLString(role.Instructions) + "\n") } +// codexChildNote opens every role's developer_instructions. A native child +// runs with its role's developer_instructions in place of the parent's, so +// nothing of codexNoSubagentNote reaches it: the note carries the child +// contract (pi's CHILD_SYSTEM_NOTE, word for word) and the chunked-read rule. +const codexChildNote = "## Runtime note\n\n" + + "You are a sub-agent dispatched by another agent. Carry out the single task in the message you " + + "were given and then stop. You have no sub-agent tool of your own and cannot dispatch further " + + "work. Your final assistant message is the entire result handed back to the agent that " + + "dispatched you, so make it self-contained.\n\n" + + codexChunkedReadNote + "\n" + // Built-in roles. `default` serves a spawn without agent_type, which is how // retro's unnamed investigation tasks run; `explore` is Claude Code's // Explore as an instruction to the child, not an enforced sandbox: the @@ -52,11 +64,11 @@ const ( codexDefaultRoleDescription = "Generic sub-agent for a task the parent describes in full in its message." codexDefaultRoleInstructions = "# Sub-agent\n\nDo the task in the message you were given, and only that task. " + "Put your findings, with file paths and line numbers where they apply, in your final message: " + - "the parent reads nothing else and owns the synthesis and the final result.\n" + "the parent owns the synthesis and the final result.\n" codexExploreRoleDescription = "Investigation of the repository by reading only; reports findings. Instruction-only: nothing enforces read-only on a child." codexExploreRoleInstructions = "# Explore\n\nAnswer the question in the message you were given by reading the " + "repository: read files, search, and run commands that change nothing. Do not edit or create files. " + - "Put what you found, with file paths and line numbers, in your final message: the parent reads nothing else.\n" + "Put what you found, with file paths and line numbers, in your final message.\n" ) // codexRoles is the role list for a delegating agent: every skill persona @@ -72,8 +84,8 @@ func codexRoles(skillDirs []string, agentName string) []codexRole { fmt.Fprintf(os.Stderr, "Warning: persona %q skipped: %s\n", sk.Path, sk.Reason) } roles := []codexRole{ - {Name: "default", Description: codexDefaultRoleDescription, Instructions: codexDefaultRoleInstructions}, - {Name: "explore", Description: codexExploreRoleDescription, Instructions: codexExploreRoleInstructions}, + {Name: "default", Description: codexDefaultRoleDescription, Instructions: codexChildNote + codexDefaultRoleInstructions}, + {Name: "explore", Description: codexExploreRoleDescription, Instructions: codexChildNote + codexExploreRoleInstructions}, } for _, p := range personas { var reason string @@ -94,7 +106,7 @@ func codexRoles(skillDirs []string, agentName string) []codexRole { "restriction, so 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: p.Body + "\n"}) + 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 diff --git a/internal/runtime/codex_personas_test.go b/internal/runtime/codex_personas_test.go index 4b664134ea..fe9b8e8872 100644 --- a/internal/runtime/codex_personas_test.go +++ b/internal/runtime/codex_personas_test.go @@ -156,9 +156,9 @@ func TestCodexRoles_SkillPersonasSorted(t *testing.T) { assert.Equal(t, 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", + Instructions: codexChildNote + "# Correctness\n\nYou are a senior software engineer reviewing for correctness.\n", }, roles[0]) - assert.Equal(t, "Review for style.\n", roles[3].Instructions) + assert.Equal(t, codexChildNote+"Review for style.\n", roles[3].Instructions) } // A file discoverPersonas skips (reserved name, bad shape) is a warning here @@ -228,7 +228,7 @@ func TestCodexRoles_DuplicateAcrossSkillsKeepsTheFirst(t *testing.T) { out := captureStderr(t, func() { roles = codexRoles([]string{first, second}, "review") }) assert.Equal(t, []string{"correctness", "default", "explore"}, codexRoleNames(roles)) - assert.Equal(t, "# Correctness\n\nYou are a senior software engineer reviewing for correctness.\n", roles[0].Instructions) + assert.Equal(t, codexChildNote+"# Correctness\n\nYou are a senior software engineer reviewing for correctness.\n", roles[0].Instructions) assert.Contains(t, out, "skipped: name already declared by skill") } diff --git a/internal/runtime/testdata/codex/golden/roles/correctness.toml b/internal/runtime/testdata/codex/golden/roles/correctness.toml index 5832670056..1c801221d7 100644 --- a/internal/runtime/testdata/codex/golden/roles/correctness.toml +++ b/internal/runtime/testdata/codex/golden/roles/correctness.toml @@ -1,6 +1,12 @@ name = "correctness" description = "Evaluates logic correctness, edge cases, nil handling, API contracts, test adequacy/integrity." 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. diff --git a/internal/runtime/testdata/codex/golden/roles/default.toml b/internal/runtime/testdata/codex/golden/roles/default.toml index a35455e439..7f23ee4a07 100644 --- a/internal/runtime/testdata/codex/golden/roles/default.toml +++ b/internal/runtime/testdata/codex/golden/roles/default.toml @@ -1,7 +1,13 @@ name = "default" description = "Generic sub-agent for a task the parent describes in full in its message." 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. + # Sub-agent -Do the task in the message you were given, and only that task. Put your findings, with file paths and line numbers where they apply, in your final message: the parent reads nothing else and owns the synthesis and the final result. +Do the task in the message you were given, and only that task. Put your findings, with file paths and line numbers where they apply, in your final message: the parent owns the synthesis and the final result. """ diff --git a/internal/runtime/testdata/codex/golden/roles/explore.toml b/internal/runtime/testdata/codex/golden/roles/explore.toml index 8c22aabd7f..3e89766c8a 100644 --- a/internal/runtime/testdata/codex/golden/roles/explore.toml +++ b/internal/runtime/testdata/codex/golden/roles/explore.toml @@ -1,7 +1,13 @@ name = "explore" description = "Investigation of the repository by reading only; reports findings. Instruction-only: nothing enforces read-only on a child." 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. + # Explore -Answer the question in the message you were given by reading the repository: read files, search, and run commands that change nothing. Do not edit or create files. Put what you found, with file paths and line numbers, in your final message: the parent reads nothing else. +Answer the question in the message you were given by reading the repository: read files, search, and run commands that change nothing. Do not edit or create files. Put what you found, with file paths and line numbers, in your final message. """