graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(prompt): Codex sidecar spawn; drop subagent routing essay
Cursor Agent896df36ea550
diff --git a/docs/adr/0023-codex-subagent-is-sidecar-not-v8.md b/docs/adr/0023-codex-subagent-is-sidecar-not-v8.mdnew file mode 100644index 00000000..75f0c3e2--- /dev/null+++ b/docs/adr/0023-codex-subagent-is-sidecar-not-v8.md@@ -0,0 +1,61 @@+# 0023. Codex is a check, not a runtime: sidecar spawn, no V8 Code Mode++Status: accepted 2026-08-25++## Context++[openai/codex](https://github.com/openai/codex) is the closest production+harness to graff's Responses-wire + subagent + "tools as functions" shape.+A double-check against `codex-rs` (2026-08-25 tree) asked whether we should+copy Code Mode, `spawn_agent`, or their prompt-cache keying.++Codex **Code Mode** is an in-process V8 heap+(`codex-rs/code-mode-runtime`): tools become JS functions on `tools.*`,+with `store`/`load` cells and a yield. That is the same *idea* as graff+`rlm` (spec-ptc + persistent binds), implemented as a JavaScript runtime.++Codex **spawn_agent** (`multi_agents_v1`) starts a cold child thread: no+parent history by default, depth-capped, optional `fork_context`. The+always-on tool description hides the model-picker essay+(`hide_spawn_agent_metadata`) and spends its tokens on *when* to delegate:+keep the critical-path next step local; spawn only bounded sidecar work+that can run beside it; disjoint write sets; do not set `model` unless+the user asked. `prompt_cache_key` is the session id; internal/guardian+sessions reuse `{source}:{parent_thread_id}` when they share a prefix.++## Decision++Take Codex's **sidecar vs critical-path** rule into graff's advertised+prompts (`subagent` catalog desc, `rlm` tool desc, `rlm_spec.system_note`).+Drop the routing/tier essay from the always-on `subagent` description —+field schemas still carry pins; Codex was right that the essay does not+belong on every prefix.++Reject the rest:++- **V8 / Code Mode.** graff `rlm` is already the Zig analog. A JS heap+ would raise RSS for no product win (ADR 0022: no IPython, no Python+ kernel; same reason).+- **`spawn_agent` / `wait_agent` / `close_agent` / `send_input`.** graff+ already has `subagent` + `agent_output` + `run_in_background`. Extra+ catalog tools would break the fold and the 64-cell kernel.+- **Inherit or fork parent history.** Codex's default is cold; so is+ `execSubagent` (fresh arena, fresh history). Forking is a token/RSS bomb.+- **Share the root `prompt_cache_key` with children.** Codex does that+ only when the prefix is actually shared (guardian). graff children have+ a different system+tools prefix; they stay on role-lane keys (ADR 0011).+ `/btw` already shares the parent key, same as Codex recap.+- **ExplicitRequestOnly spawn.** Codex has a mode that forbids spawning+ unless AGENTS.md asked. Graff stays proactive (Codex's other mode):+ sidecar parallelism is the product.++## Consequences++- Catalog prefix shrinks (the old `subagent` desc was a routing essay).+ That is a one-time cache miss, then a smaller stable prefix.+- Models are told not to hand the blocker to a child and wait — the+ failure mode Codex's tests pin (`spawn_agent` must not push a smaller+ model by default; wait-by-reflex is called out).+- Cross-harness A/B against the Codex CLI is not runnable here without a+ ChatGPT login. Architecture compare is the evidence; live numbers stay+ graff `--old` vs default RLM (ADR 0022).diff --git a/docs/adr/0024-three-harness-compare-prompt-subagent-rss.md b/docs/adr/0024-three-harness-compare-prompt-subagent-rss.mdnew file mode 100644index 00000000..2d5670c4--- /dev/null+++ b/docs/adr/0024-three-harness-compare-prompt-subagent-rss.md@@ -0,0 +1,78 @@+# 0024. Steal prompt/subagent craft from grok-build, kimi-cli, dsh — not their runtimes++Status: accepted 2026-08-25++## Context++PR 621 made `rlm` the default loop (ADR 0022) and turned prompt-cache+max on (ADR 0011: stable catalog, role-lane child `x-grok-conv-id`).+A follow-up asked whether+[grok-build](https://github.com/xai-org/grok-build),+[kimi-cli](https://github.com/MoonshotAI/kimi-cli), or+[deepseek-harness](https://github.com/deepseek-ai/deepseek-harness)+beat that story on cache, child spawn, prompt tokens, or RSS.++Cloned 2026-08-25 (shallow). None of the three binaries ran here:+grok-build needs Rust + DotSlash (or `x.ai/cli` install + an xAI+account the SuperGrok OAuth file does not unlock as `grok`); kimi-cli+is Python and wants a Moonshot login; dsh is a pnpm/Node plugin host+and wants a DeepSeek key. Architecture is the evidence; live numbers+are graff `--old` vs default RLM (see below, filled after the A/B).++## Decision++**Take (Zig, no IPython, no new catalog tool):**++| Source | What | Why it beats us |+|---|---|---|+| grok-build | Short focused child prompt; "do not broaden"; parallelize independent calls | Their `subagent_prompt.md` is a worker brief, not a copy of the root. Ours was already shorter; we tighten it further. Role-lane conv-id and `/btw` parent-prefix already landed in ADR 0011 — nothing left to steal there. |+| grok-build | Recap/`/btw` share the *parent* `prompt_cache_key` | Already ours. Do not extend that to children. |+| kimi-cli | Persist the child's system prompt on first run; "do not narrate tool calls" | Persist-binds already cover REPL state. Narration tax is real on children — one line on `sub_system_prompt`. Resume-existing-child is a feature, not a cheap win. |+| kimi-cli | Default foreground; `run_in_background` only when the result is not the next step | Same as Codex sidecar (ADR 0023). Already in the shortened `subagent` desc. |+| dsh | PromptContext as a *user-role* snapshot so the system prefix stays byte-stable | Standing goal already does this (ADR 0005). In-process spawn (not fork) is already ours. Child catalog is already `base_specs` comptime JSON — shared bytes, not rebuilt. |+| Codex (ADR 0023) | Sidecar vs critical-path; drop the routing essay from the always-on `subagent` desc | Catalog prefix shrink. Kept. |++**Reject:**++| Source | What | Why |+|---|---|---|+| grok-build | Share the root `x-grok-conv-id` / `prompt_cache_key` with children | Official xAI cache is keyed on conv-id + prefix. Children have a different system+tools array. Role-lane among *siblings* is the win (ADR 0011). Sharing the root id is a forced miss. Do not make the child prompt start with the root prompt to "share prefix" — without a shared key the bytes do not cache. |+| grok-build | `resume_from` a completed child transcript | Token/RSS bomb; we already persist binds on the *root* REPL. |+| grok-build | Memory search / hashline edit workflow | Different product. |+| kimi-cli | `${KIMI_NOW}` and a workdir listing in the system prompt | Cache-bust factory (datetime every minute, tree every file change). We already refuse timestamps on the prefix. |+| kimi-cli | IPython / Python REPL / huge `system.md` | Longer than ours. ADR 0022: no IPython. |+| kimi-cli | Inject AGENTS.md + skill bodies into every system prompt | We load skills on demand. |+| dsh | Harbor / Pier / full DeepSWE | Out of scope. We have DeepSWE-SHAPED local tasks 17–22. |+| dsh | Fork-seed parent history into the child | Codex default is cold; so is `execSubagent`. Seeding is a token/RSS bomb (ADR 0023). |+| dsh | Plugin host, continuable Activation graph, `send_message`/`list_agents` | Extra catalog tools. We have `subagent` + `agent_output`. |+| all three | A Python/Node/Rust fan-out process | Product stays Zig. `graff-evals/run.py` only launches `graff`. |++**Prompt hell-optimize (this revision):**++- `rlm_spec.system_note` stays on the root prefix only (children use+ `sub_system_prompt` — they never see `rlm(code)`). Shorten the note+ without dropping persist / sidecar / print.+- Child brief: do not broaden, do not narrate tool calls (grok + kimi).+- Do not reshuffle messages. Keep `reasoning_content` replay (already+ pinned; grok's official top Chat cache-miss cause).+- `rlm` stays folded; it is not added to `--schema` / `optional_specs` /+ the 64-cell kernel, and it is never the only catalog tool.++**RSS:** children are in-process (`runSub` builds an `Agent` on a+per-spawn arena, comptime `sub_system_prompt`, comptime child tools+JSON). No allocator rewrite. Peak RSS is a column in+`graff-evals/run.py` (`rss_peak_kb` / `tree_rss_kb`). Cheap wins are+fewer prefix bytes, not a new heap.++## Consequences++- First request after the shorter `subagent` desc / `rlm` note is a+ one-time cache miss, then a smaller stable prefix.+- Live A/B after this revision is required (cache-max 92ec3b2 was+ never re-measured with these prompt bytes). Suite: `--suite rlm`+ then `--suite swe`. Harnesses: `graff-dev-old,graff-dev`.++## Live A/B (filled after the run)++_Pending. `graff-evals/run.py --suite rlm --harness graff-dev-old,graff-dev`+then swe. Columns: pass / wall / in / out / calls / RSS / $ / cache-read._diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 6e2aeb6e..d809240b 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -33,6 +33,8 @@ record only when you need the evidence or the edge cases.| [0020](0020-transcript-shows-decisions.md) | Transcript shows decisions: one interpreted tool line, collapsed infra failures, compact WORKING; raw output is `/debug` / TUI-fold. || [0021](0021-transcript-is-the-task-not-the-bus.md) | Transcript is the task, not the event bus: bookkeeping is silent, todos are WORKING, subagents are scouts. || [0022](0022-rlm-is-opt-in-speculative-ptc.md) | `rlm` (Alex Zhang spec-ptc + RLM, Zig) is the default loop. `--old` restores structured-only. Prime persist + `subagent()` only — no IPython. |+| [0023](0023-codex-subagent-is-sidecar-not-v8.md) | Codex check: take sidecar-vs-critical-path spawn prompts; reject V8 Code Mode, extra spawn tools, and parent-history fork. |+| [0024](0024-three-harness-compare-prompt-subagent-rss.md) | Steal short child briefs + sidecar spawn from grok-build/kimi/dsh; reject root conv-id share, datetime/tree prefix, fork-seed, Harbor. |## When to write onediff --git a/src/prompts.zig b/src/prompts.zigindex 14f74ac5..9c3aa679 100644--- a/src/prompts.zig+++ b/src/prompts.zig@@ -458,10 +458,10 @@ pub fn resetSessionCompacted(agent: *Agent, arena: Allocator) void {pub const sub_system_prompt =\\You are a subagent spawned by an orchestrator agent inside a terminal- \\harness. Complete the assigned task using your tools, without asking- \\questions — make reasonable assumptions. Your final message is returned- \\verbatim to the orchestrator as the result of the task: make it a- \\concise, complete report with the concrete facts you found.+ \\harness. Complete only the assigned task; do not broaden scope or ask+ \\questions — make reasonable assumptions. Do not narrate tool calls.+ \\Your final message is returned verbatim to the orchestrator: a concise+ \\report of the concrete facts you found.++ parallel_tools_note;pub const compact_instruction =@@ -495,6 +495,9 @@ test "both prompts ask for parallel tool calls, with the dependency caveat" {}// Composing must not have cost either prompt its own identity.try std.testing.expect(std.mem.indexOf(u8, sub_system_prompt, "subagent spawned by an orchestrator") != null);+ try std.testing.expect(std.mem.indexOf(u8, sub_system_prompt, "do not broaden") != null);+ try std.testing.expect(std.mem.indexOf(u8, sub_system_prompt, "Do not narrate") != null);+ try std.testing.expect(std.mem.indexOf(u8, sub_system_prompt, "rlm(code)") == null);try std.testing.expect(std.mem.indexOf(u8, main_system_prompt, "Be direct and concise") != null);try std.testing.expect(std.mem.indexOf(u8, main_system_prompt_strict, "STRICT MODE") != null);}diff --git a/src/rlm.zig b/src/rlm.zigindex 85f2bc5d..4f203098 100644--- a/src/rlm.zig+++ b/src/rlm.zig@@ -21,7 +21,7 @@ const rlm_query = @import("rlm_query.zig");const rlm_spec = @import("rlm_spec.zig");pub const tool_name = "rlm";-pub const tool_desc = "Programmatic tool calling (RLM + sPTC). Run a short Python-like script whose functions ARE this session's tools. Independent read_file/codedb/bash/webfetch/sleep_ms/llm_query/subagent calls with literal arguments start in parallel as the script streams (speculated), then print() is the answer. Assignments persist across rlm calls in this session. subagent(\"task\") is Prime-style recursion (graff's subagent tool; sync in v1; run_in_background=true returns an id). Semicolons or newlines separate statements. llm_query(prompt) is a tools-off sub-LM call. Example: a = read_file(\"src/main.zig\"); b = codedb(\"status\"); print(a, b). No imports, no control flow — assignments and calls only. Prefer this over N separate tool calls when the work does not depend on itself.";+pub const tool_desc = "Programmatic tool calling (RLM + sPTC). Script whose functions ARE this session's tools. Independent literal read_file/codedb/bash/webfetch/sleep_ms/llm_query/subagent calls start as the script streams. Binds persist across rlm calls. subagent(\"task\") is sidecar-only (keep the critical-path next step local; sync in v1; run_in_background=true returns an id). print() is the answer. Example: a = read_file(\"src/main.zig\"); b = codedb(\"status\"); print(a, b). No imports, no control flow. Prefer one rlm over N tool calls.";pub const tool_schema =\\{"type": "object", "properties": {"code": {"type": "string", "description": "Python-like script: name = read_file(\"path\") / codedb(\"command\") / bash(\"cmd\") / sleep_ms(ms) / llm_query(\"prompt\") / subagent(\"task\"); print(...) is the result. Assignments persist across rlm calls. Semicolons or newlines separate statements."}}, "required": ["code"]};@@ -569,3 +569,11 @@ test "feedLive launches two independent subagent() calls before runScript claimstry std.testing.expect(std.mem.indexOf(u8, e.value_ptr.text, "prompt") != null);}}++test "rlm prompt: subagent() is advertised as sidecar-only, not a critical-path handoff" {+ try std.testing.expect(std.mem.indexOf(u8, tool_desc, "sidecar-only") != null);+ try std.testing.expect(std.mem.indexOf(u8, tool_desc, "critical-path") != null);+ try std.testing.expect(std.mem.indexOf(u8, rlm_spec.system_note, "sidecar-only") != null);+ try std.testing.expect(std.mem.indexOf(u8, rlm_spec.system_note, "critical-path") != null);+ try std.testing.expect(tool_desc.len < 600);+}diff --git a/src/rlm_spec.zig b/src/rlm_spec.zigindex 04801795..03ada0e3 100644--- a/src/rlm_spec.zig+++ b/src/rlm_spec.zig@@ -22,7 +22,7 @@ pub var run_host: ?*const fn (ToolCtx, spec_ptc.Call) ToolOutput = null;/// `subagent("task")` is Prime-style recursion via graff's existing subagent/// tool. v1 is synchronous; speculate() still overlaps independent calls./// Keyword `run_in_background=true` returns an agent id (a handle).-pub const system_note = "\n\nrlm(code) is available: a short script whose functions are this session's tools. Independent read_file/codedb/bash/llm_query/subagent calls with literal args start in parallel as the script streams. Bindings persist across rlm calls until /new or /clear. subagent(\"task\") is Prime-style recursion (graff's subagent tool; sync in v1). Prefer one rlm script over N separate tool calls when the work does not depend on itself. Semicolons or newlines separate statements; print(...) is the answer.";+pub const system_note = "\n\nrlm(code): script of this session's tools. Independent literal read_file/codedb/bash/llm_query/subagent calls start as it streams. Binds persist until /new or /clear. subagent(\"task\") is sidecar-only — keep the critical-path next step local. Prefer one rlm over N tool calls. print(...) is the answer.";/// One REPL assignment. `runScript` seeds these from the process-local store/// so a later `rlm` call can `print(prev)` without re-reading. Owned by the@@ -249,3 +249,22 @@ fn absorbUnlocked(gpa: Allocator, io: Io) void {}live.inflight.clearRetainingCapacity();}++test "system_note stays short and keeps persist / sidecar / print" {+ try std.testing.expect(system_note.len < 360);+ try std.testing.expect(std.mem.indexOf(u8, system_note, "rlm(code)") != null);+ try std.testing.expect(std.mem.indexOf(u8, system_note, "persist") != null);+ try std.testing.expect(std.mem.indexOf(u8, system_note, "/new") != null);+ try std.testing.expect(std.mem.indexOf(u8, system_note, "sidecar-only") != null);+ try std.testing.expect(std.mem.indexOf(u8, system_note, "critical-path") != null);+ try std.testing.expect(std.mem.indexOf(u8, system_note, "print(") != null);+ try std.testing.expect(std.mem.indexOf(u8, system_note, "Prime-style") == null);+}++test "children never see the rlm discovery note (different prefix, different cache key)" {+ const prompts = @import("prompts.zig");+ try std.testing.expect(std.mem.indexOf(u8, prompts.sub_system_prompt, "rlm(code)") == null);+ try std.testing.expect(std.mem.indexOf(u8, prompts.sub_system_prompt, "do not broaden") != null);+ try std.testing.expect(std.mem.indexOf(u8, prompts.sub_system_prompt, "Do not narrate") != null);+ try std.testing.expect(prompts.sub_system_prompt.len < prompts.main_system_prompt.len);+}diff --git a/src/schema.zig b/src/schema.zigindex 2aac1d8a..8a520161 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -172,7 +172,7 @@ const meta_specs = [_]ToolSpec{const subagent_spec = ToolSpec{.name = "subagent",- .desc = "Delegate a self-contained task to a subagent. It has bash, read_file, edit_file, write_file, codedb (code search), and skill (load an installed playbook); it cannot spawn further subagents and does NOT share your context — the prompt must be self-contained. Returns the subagent final report. Call several times in one response to run tasks in parallel. Pick a persona with agent (builtins: reviewer, researcher, implementer, skeptic — plus any in .harness/agents/), or give the child a custom system_prompt; the trajectory log records the lineage either way. Set run_in_background true to launch it asynchronously instead: you get the agent id back immediately and keep working. Do not poll; agent_output(wait_ms>0) blocks until it finishes. Which model this child runs on is decided in this order: model/tier given on THIS call > the chosen persona's own model:/tier: frontmatter > the session default (--subagent-model, else the default tier ladder) > the root model; within one level an exact model wins over tier. The child's reasoning effort is pinned the same way: effort on THIS call > the persona's effort: frontmatter > the worker default (medium) — an independent axis, so an effort-only override keeps the persona's model pin. Exact model pins resolve provider-locally first — a name the child's own provider serves always wins; one it does not serve falls through to a logged-in flat-rate subscription serving that exact name (never a fuzzy match). An explicit tier ask is the portable lever: when the child's own provider has no such rung, sub-first routing checks every logged-in flat-rate subscription and seats the worker on the best sub serving that rung (the login is the standing consent; metered cross-provider routing still needs --subagent-provider + --allow-cross-provider-subagents). A pin that cannot be honored is ignored (the spawn still runs on the session default) rather than failing.",+ .desc = "Delegate a self-contained sidecar task. The child has bash, read_file, edit_file, write_file, codedb, and skill; it cannot spawn further subagents and does NOT share your context — the prompt must be complete. Returns the final report. Call several times in one response for disjoint parallel slices. Keep the critical-path next step local; do not hand off the blocker and wait. Prefer concrete code-change work with disjoint write sets over read-only exploration. Do not set model unless the user asked or a task-specific reason is clear. Personas: agent=reviewer|researcher|implementer|skeptic or a .harness/agents/ name; system_prompt overrides. run_in_background=true returns an id immediately — do not poll; agent_output(wait_ms>0) blocks until done.",.schema =\\{"type": "object", "properties": {"description": {"type": "string", "description": "Short label for logs, 3-5 words"}, "prompt": {"type": "string", "description": "Complete, self-contained task description"}, "agent": {"type": "string", "description": "Optional: a named agent type (reviewer, researcher, implementer, skeptic, or a .harness/agents/ name) whose persona the child runs with"}, "system_prompt": {"type": "string", "description": "Optional: replace the child's system prompt with a custom one (overrides agent)"}, "model": {"type": "string", "description": "Optional: run THIS child on an exact model name available on the current provider (e.g. \"gpt-5.6-luna\"). Highest precedence — beats the persona's own pin and the session default. Ignored (spawn still runs on the session default, with a trace note) if the name is unknown, ambiguous, or not served by this provider — except that a logged-in flat-rate subscription serving the exact name honors it (sub-first routing; the login is the standing consent). For a portable 'cheapest seat' ask, tier is still the better lever."}, "tier": {"type": "string", "enum": ["frontier", "mid", "small"], "description": "Optional: run THIS child on a rung of the current provider's model ladder instead of an exact name — frontier (planner/judge class), mid (reviewers, implementers, researchers), small (mechanical transform/extract/label). Prefer this over model: it stays correct when the root model changes. If the provider has no ladder or no model at that rung, sub-first routing seats the child on a logged-in flat-rate subscription's rung when one exists (no login → the pin is ignored); model wins if both are given."}, "effort": {"type": "string", "enum": ["low", "medium", "high", "xhigh", "max"], "description": "Optional: reasoning effort for THIS child — beats the persona's effort: frontmatter; unpinned children run at medium. An axis independent of model/tier: an effort-only override keeps the persona's model pin. An off-vocabulary value is ignored with a trace note."}, "isolation": {"type": "string", "enum": ["shared_cwd", "worktree"], "description": "Optional: \"worktree\" gives this child its own scratch git worktree (auto-removed if it finishes with no changes, kept + reported if it has any) instead of the shared working tree — use for parallel agents that edit files. Default shared_cwd (today's behavior), unless the chosen agent persona sets its own default."}, "isolation_fallback": {"type": "boolean", "description": "Optional: if isolation:\"worktree\" fails to set up (not a git repo, git error), run in the shared working tree instead of failing the spawn. Default false (fails the spawn on setup failure)."}, "run_in_background": {"type": "boolean", "description": "Optional: start this subagent asynchronously and return its agent id immediately instead of waiting for it to finish (default false). Do not poll; agent_output(wait_ms>0) blocks until it finishes. A spawn beyond the concurrency cap is queued, never failed."}}, "required": ["description", "prompt"]},diff --git a/src/tool_schema_tests.zig b/src/tool_schema_tests.zigindex 8697fa0c..436bc412 100644--- a/src/tool_schema_tests.zig+++ b/src/tool_schema_tests.zig@@ -383,3 +383,18 @@ test "note_constraint (#381): root-only, append-only, and a valid one-property stry std.testing.expect(std.mem.indexOf(u8, schema.tools_openai_sub, "note_constraint") == null);try std.testing.expect(std.mem.indexOf(u8, schema.tools_anthropic_sub, "note_constraint") == null);}++test "subagent desc: Codex sidecar rules, no routing essay on the catalog prefix" {+ var found = false;+ for (schema.root_specs) |t| if (std.mem.eql(u8, t.name, "subagent")) {+ found = true;+ try std.testing.expect(std.mem.indexOf(u8, t.desc, "critical-path") != null);+ try std.testing.expect(std.mem.indexOf(u8, t.desc, "sidecar") != null);+ try std.testing.expect(std.mem.indexOf(u8, t.desc, "disjoint") != null);+ try std.testing.expect(std.mem.indexOf(u8, t.desc, "Do not set model") != null);+ try std.testing.expect(std.mem.indexOf(u8, t.desc, "default tier ladder") == null);+ try std.testing.expect(std.mem.indexOf(u8, t.desc, "sub-first routing") == null);+ try std.testing.expect(t.desc.len < 900);+ };+ try std.testing.expect(found);+}