Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

Sub-agents at parity with the codex route (ADR 0232)

justrachb167a858ea1e
diff --git a/docs/adr/0232-sub-agents-at-parity-with-the-codex-route.md b/docs/adr/0232-sub-agents-at-parity-with-the-codex-route.md
new file mode 100644
index 00000000..c0aae39b
--- /dev/null
+++ b/docs/adr/0232-sub-agents-at-parity-with-the-codex-route.md
@@ -0,0 +1,76 @@
+# 0232. Sub-agents at parity with the codex route, and a suite that measures them
+
+Status: accepted 2026-10-01
+
+## Context
+
+The eval tree had no task that asked for sub-agents, so delegation was never
+measured against another harness. The `subagents` suite now has five: three
+packages fixed in parallel, a census of four services' logs, an API rename
+across three packages, a coverage merge of two inventories, and a docs
+sidecar beside a fix. `subagents-solo` is the same five without the
+delegation wording, so a run can say whether its children paid for
+themselves. Fixtures are git repos with held-out checks. `subagent_split.py`
+splits a run into parent time and child time.
+
+Run against the Codex app server on the same model, graff lost three of the
+five, and the transcripts showed why:
+
+- **A new file in a new directory.** `write_file` refused it, and the docs
+ child generated its whole reference a second time after a `mkdir`.
+- **A checklist nobody reads.** In `-p` and piped sessions the prompt still
+ said to track work with `todo_write`, so the model loaded the folded tool
+ and spent several calls keeping a list no one watched.
+- **A wait per child.** `agent_output` took one id, so collecting three
+ children cost three model calls.
+- **Copying a script's output.** The prompt said to use `write_file` for new
+ files, so a script that computed a report printed it, and the model typed it
+ back into `write_file` in another call.
+
+The codex route's own client starts each child with its parent's
+conversation and runs it at its parent's effort. A graff child started from
+the brief alone, at the worker default effort, so an effort set with
+`/effort` or chosen by Jev never reached it.
+
+## Decision
+
+- `write_file` creates the missing directory of a new file and says so in
+ its result. A path through an existing file still fails.
+- With no human attached (`-p`, or a piped session outside `--json` and ACP)
+ the system prompt leaves out the two `todo_write` nudges. The tool stays
+ loadable, and a standing goal still asks for its checklist.
+ `ask_user.detectNoHuman` decides this before the prompt is composed.
+- `agent_output` takes `ids` in place of `id` and returns every report in one
+ result, waiting for all of them when `wait_ms > 0`. A spawn receipt names
+ every child of the session still running, so the model can copy one call.
+- A fresh child's first message carries the user's prompts from its parent's
+ history, oldest first, newest kept past 8 KiB, ahead of its own task, so
+ siblings share that prefix. Notices and tool results are not prompts. A
+ resumed worker does not get them again.
+- A child without a spawn or persona effort pin runs at its parent's live
+ effort, when the child's model accepts that level. On the codex route an
+ unset effort already means the catalog default (ADR 0226).
+- Each finished child writes one `subagent` trace line with its duration,
+ tool calls, context, cached tokens and effort.
+- The prompt says a script that computes a file's content writes that file
+ itself.
+
+Not adopted: the codex route forks the parent's history under the parent's
+own instructions and tools, which shares the parent's cached prefix. A graff
+child keeps its own smaller prompt and catalog, which its siblings already
+share. Nor resident-thread eviction: graff frees a child's conversation when
+the child finishes and keeps only its report, and a run with four children
+stayed an order of magnitude below the Codex app server process in resident
+memory and CPU time.
+
+## Consequences
+
+An unpinned child of a session at `/effort high` now reasons at high too.
+A child sees the user's request, so a brief can be shorter, and a child can
+also be tempted past its own task; its prompt and the context header both
+say to do only its part. A `-p` run that would have kept a checklist no
+longer does unless a goal asks for one.
+
+Revisit the 8 KiB context cap if long sessions crowd a child's first
+request, and the effort inheritance if children of high-effort sessions cost
+more than the work they save.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 7ea12ffe..ce132db3 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -258,6 +258,7 @@ record only when you need the evidence or the edge cases.
| [0229](0229-every-chatgpt-login-is-chatgpt-new.md) | The Codex client's login no longer works, so every ChatGPT login name (`chatgpt`, `codex`, `openai`, `gpt`, `oai`) and the model picker run the `chatgpt-new` sign-in, and `chatgpt-new` precedes `codex` in the provider table. The `codex` provider stays for an existing Codex CLI `auth.json`. Replaces ADR 0221's "Codex first". |
| [0230](0230-mcp-connects-in-the-background.md) | Every session but `--json` connects MCP servers in the background (interactive after consent, `--yolo`, `-p`, ACP); no request waits for a handshake, finished starts join the next request, and the root request says which server connected or did not. ACP `session/new` waits at most 250 ms; `/mcp` lists without waiting. |
| [0231](0231-no-round-trip-the-model-does-not-need.md) | No call the task did not ask for: a named small MCP server (and subagents, when asked for) loads with the first request, with the slim-shape note; `write_file` refuses to replace an unread file unless `replace: true` and reports created/replaced and JSON validity; inherited child MCP tools are never deferred; a piped bracketed paste is one prompt; unwatched (`-p`, piped) sessions get no `ask_user` and no low-effort reasoning summaries. |
+| [0232](0232-sub-agents-at-parity-with-the-codex-route.md) | Sub-agents measured (`subagents` suite and its `subagents-solo` counterfactual, `subagent_split.py`) and brought to parity: `write_file` creates a new file's directory; unwatched sessions get no `todo_write` nudges; `agent_output` takes `ids` and spawn receipts name the running children; a fresh child starts with the user's prompts and its parent's live effort (`/effort` or Jev) unless pinned; one `subagent` trace line per child; a script that computes a file writes it. |
## When to write one
diff --git a/src/agent_tool_batch.zig b/src/agent_tool_batch.zig
index ebae9f2a..2b12f2b6 100644
--- a/src/agent_tool_batch.zig
+++ b/src/agent_tool_batch.zig
@@ -92,6 +92,8 @@ pub fn context(self: *Agent) ToolCtx {
.agent_cwd = self.agent_cwd,
.subagent_feedback = self.feedback,
.read_miss = &self.read_miss,
+ .parent_effort = self.reasoning,
+ .parent_messages = self.messages.items,
};
}
diff --git a/src/ask_user.zig b/src/ask_user.zig
index aa8c1f9f..3cca8a6f 100644
--- a/src/ask_user.zig
+++ b/src/ask_user.zig
@@ -32,6 +32,14 @@ const style = &@import("ansi.zig").style;
/// "no human is attached".
pub var g_no_human: bool = false;
+/// The g_no_human rule. main.zig settles it before the system prompt is
+/// composed (ADR 0232: the todo nudges stay out when nobody watches), and
+/// session start applies it again. The TUI's terminal shows on stdout.
+pub fn detectNoHuman(io: std.Io, oneshot: bool, json: bool, acp: bool) bool {
+ const terminal = (std.Io.File.stdin().isTty(io) catch false) or (std.Io.File.stdout().isTty(io) catch false);
+ return oneshot or (!json and !acp and !terminal);
+}
+
/// Block the root agent for an ask_user reply; subagents have no stdin.
pub fn askUser(self: *Agent, call: ToolCall) !ExecResult {
// #1308: aliases, a `questions` list, and double-encoded arguments all
@@ -153,3 +161,18 @@ pub fn emitAskUser(self: *Agent, call_id: []const u8, question: []const u8, inpu
try w.writeByte('\n');
try w.flush();
}
+
+test "no human: the prompt leaves the todo nudges out and the tool stays loadable (ADR 0232)" {
+ const prompts = @import("prompts.zig");
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const saved = g_no_human;
+ defer g_no_human = saved;
+ g_no_human = false;
+ try std.testing.expectEqual(prompts.toolAdvertised("todo_write"), prompts.detectCaps().todos);
+ g_no_human = true;
+ try std.testing.expect(!prompts.detectCaps().todos);
+ const base = try prompts.composeBase(arena_state.allocator(), prompts.detectCaps());
+ try std.testing.expect(std.mem.indexOf(u8, base, "todo_write") == null);
+ try std.testing.expect(@import("native_fold.zig").isFolded("todo_write"));
+}
diff --git a/src/edit_verify.zig b/src/edit_verify.zig
index 0ceb7117..384319c6 100644
--- a/src/edit_verify.zig
+++ b/src/edit_verify.zig
@@ -314,7 +314,7 @@ pub fn fsErrorText(gpa: Allocator, op: FileOp, path: []const u8, err: anyerror)
error.FileNotFound, error.NotDir => switch (op) {
.read => std.fmt.allocPrint(gpa, "read_file: {s} does not exist (paths are relative to the cwd) — check the name, or list the directory with codedb list_dir", .{path}),
.edit => std.fmt.allocPrint(gpa, "edit_file: {s} does not exist — edit_file only rewrites an existing file; use write_file to create it", .{path}),
- .write => std.fmt.allocPrint(gpa, "write_file: cannot create {s} — its parent directory does not exist; create it first with bash `mkdir -p`", .{path}),
+ .write => std.fmt.allocPrint(gpa, "write_file: cannot create {s} — part of its directory path is not a directory", .{path}),
},
error.IsDir => std.fmt.allocPrint(gpa, "{s}: {s} is a directory, not a file", .{ op.tool(), path }),
error.AccessDenied, error.PermissionDenied => std.fmt.allocPrint(gpa, "{s}: permission denied for {s}", .{ op.tool(), path }),
diff --git a/src/exec.zig b/src/exec.zig
index 384036f7..0da9800d 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -344,10 +344,11 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
}
if (local_tools.isLocal(call.name)) return local_tools.exec(gpa, io, call.name, input);
if (std.mem.eql(u8, call.name, "agent_output")) {
+ const wait_ms: u64 = @intCast(@max(intField(input, "wait_ms") orelse 0, 0));
+ if (input == .object) if (input.object.get("ids")) |ids| if (ids == .array) return @import("subagent_interactive.zig").outputMany(ctx, ids.array.items, wait_ms);
const id = intField(input, "id") orelse return missingArg(gpa, "id");
- const wait_ms = intField(input, "wait_ms") orelse 0;
if (id < 0 or id > std.math.maxInt(u32)) return .{ .text = try gpa.dupe(u8, "invalid agent id"), .is_error = true };
- return @import("subagent_interactive.zig").output(ctx, @intCast(id), @intCast(@max(wait_ms, 0)));
+ return @import("subagent_interactive.zig").output(ctx, @intCast(id), wait_ms);
}
if (std.mem.eql(u8, call.name, "subagent_resume")) return @import("subagent_resume.zig").exec(ctx, input);
if (std.mem.eql(u8, call.name, "agent_message")) return @import("subagent_messaging.zig").send(ctx, input);
diff --git a/src/main.zig b/src/main.zig
index fb0bc13a..7a65d043 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -397,7 +397,7 @@ pub fn main(init: std.process.Init) !void {
for (approvals.plan_read_roots.items) |p| gpa.free(p);
approvals.plan_read_roots.deinit(gpa);
}
- // buildSystemPrompt layers the base, project instructions, overrides, skills, and MCP notes.
+ @import("ask_user.zig").g_no_human = @import("ask_user.zig").detectNoHuman(io, flags.oneshot_prompt != null, json_mode, @import("mcp_boot.zig").isAcp(flags.positionals.items)); // before the prompt composes (ADR 0232)
const sys_normal = try startup.buildSystemPrompt(io, arena, out, flags.system_prompt_flag, flags.append_system_flag, json_mode or flags.oneshot_prompt != null or init.environ_map.get("GRAFF_REPL_DEBUG") == null, (flags.oneshot_prompt != null or !(Io.File.stdin().isTty(io) catch true)) and !flags.effectiveYolo(), mcp_tools, g_codedbpro_licensed, init.environ_map.get("GRAFF_LEARNED_PROMPT"), init.environ_map);
boot.mark(io, "system prompt");
session_run.learningNotice(io, arena, init.environ_map, out, json_mode or flags.oneshot_prompt != null);
diff --git a/src/prompt_golden.zig b/src/prompt_golden.zig
index 15073a87..2f6902f6 100644
--- a/src/prompt_golden.zig
+++ b/src/prompt_golden.zig
@@ -36,6 +36,8 @@ pub const full_prompt =
\\edit_file for changes to existing files and write_file for new
\\files or full rewrites. write_file will not replace a file you have not
\\read, so write a new file without first checking that its path is free.
+ \\When a script computes a file's content, let that script write the file
+ \\instead of printing it for write_file.
\\For a read-only exact-key lookup in one known file,
\\call read_file once with contains set to the exact key and answer from its
\\output; do not request the whole file first. To navigate code — finding symbols,
diff --git a/src/prompt_text.zig b/src/prompt_text.zig
index 1ed564c6..e3131355 100644
--- a/src/prompt_text.zig
+++ b/src/prompt_text.zig
@@ -41,6 +41,8 @@ pub const local_tools_note =
\\edit_file for changes to existing files and write_file for new
\\files or full rewrites. write_file will not replace a file you have not
\\read, so write a new file without first checking that its path is free.
+ \\When a script computes a file's content, let that script write the file
+ \\instead of printing it for write_file.
\\For a read-only exact-key lookup in one known file,
\\call read_file once with contains set to the exact key and answer from its
\\output; do not request the whole file first. To navigate code — finding symbols,
@@ -374,7 +376,8 @@ pub const lean_local_tools_note =
\\read_file before editing; prefer edit_file for existing files and
\\write_file for new files. write_file never replaces a file you have not
\\read, so skip existence checks; its result is the evidence, so skip
- \\read-backs. Use the smallest unique edit spans and
+ \\read-backs. A file a script computes is written by that script, not
+ \\copied into write_file. Use the smallest unique edit spans and
\\preserve terminal-newline state. Navigate with codedb (context, around,
\\callpath, list_dir, status).
\\Independent reads belong in ONE response, not a chain of turns.
diff --git a/src/prompts.zig b/src/prompts.zig
index 8f3c925b..8c97bc61 100644
--- a/src/prompts.zig
+++ b/src/prompts.zig
@@ -144,7 +144,7 @@ pub fn detectCaps() Caps {
return .{
.local_tools = toolAdvertised("edit_file") and toolAdvertised("bash"),
.subagents = toolAdvertised("subagent") and !no_local_tools.lean, // lean: no fan-out essay
- .todos = toolAdvertised("todo_write") and !no_local_tools.lean,
+ .todos = toolAdvertised("todo_write") and !no_local_tools.lean and !@import("ask_user.zig").g_no_human, // ADR 0232: a checklist nobody watches costs round trips
.constraints = toolAdvertised("note_constraint") and !no_local_tools.lean,
.git_repo = g_git_repo and !no_local_tools.lean, // -p: no commit/PR essay
};
diff --git a/src/schema.zig b/src/schema.zig
index f4e469f6..de139e48 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -69,7 +69,7 @@ pub const base_specs = [_]ToolSpec{
},
.{
.name = "write_file",
- .desc = "Create a file, or replace one you have read, edited or written in this session. It will not replace any other existing file unless replace is true, so there is no need to check whether a path exists first. The result says whether it created or replaced the file and, for a .json path, whether the content parses.",
+ .desc = "Create a file, or replace one you have read, edited or written in this session. It will not replace any other existing file unless replace is true, so there is no need to check whether a path exists first, and a missing directory is created. The result says whether it created or replaced the file and, for a .json path, whether the content parses.",
.schema =
\\{"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}, "replace": {"type": "boolean", "description": "Overwrite an existing file you have not read in this session"}}, "required": ["path", "content"]}
,
diff --git a/src/schema_agents.zig b/src/schema_agents.zig
index e653debf..8ba417a2 100644
--- a/src/schema_agents.zig
+++ b/src/schema_agents.zig
@@ -11,9 +11,9 @@ pub const subagent_spec = ToolSpec{
pub const agent_output_spec = ToolSpec{
.name = "agent_output",
- .desc = "Fetch a background subagent's status/result (one started with subagent run_in_background:true). Running: a brief status line. Completed: the full report — the same text a synchronous subagent call would have returned, including any kept-worktree note — plus a usage summary (duration, tool-call count, context tokens, cache-read tokens). Failed: an is_error result explaining why; failures are always reported, never silent. wait_ms=0 returns an immediate snapshot; in the prompt-based interactive REPL it yields the parent for an automatic completion wake, while ACP/headless callers remain in the turn. wait_ms>0 waits for completion (up to 10h) on every surface; cancellation interrupts the wait. Do not poll. Calling again after completion re-returns the same result — nothing is consumed.",
+ .desc = "Fetch a background subagent's status/result (one started with subagent run_in_background:true). Running: a brief status line. Completed: the full report — the same text a synchronous subagent call would have returned, including any kept-worktree note — plus a usage summary (duration, tool-call count, context tokens, cache-read tokens). Failed: an is_error result explaining why; failures are always reported, never silent. wait_ms=0 returns an immediate snapshot; in the prompt-based interactive REPL it yields the parent for an automatic completion wake, while ACP/headless callers remain in the turn. wait_ms>0 waits for completion (up to 10h) on every surface; cancellation interrupts the wait. ids in place of id waits for several agents in one call and returns every report. Do not poll. Calling again after completion re-returns the same result — nothing is consumed.",
.schema =
- \\{"type": "object", "properties": {"id": {"type": "integer", "description": "Agent id returned by subagent with run_in_background:true"}, "wait_ms": {"type": "integer", "description": "0 = snapshot now. >0 = block until the agent finishes (capped at 10 hours). Do not poll every 30s."}}, "required": ["id"]}
+ \\{"type": "object", "properties": {"id": {"type": "integer", "description": "Agent id returned by subagent with run_in_background:true"}, "ids": {"type": "array", "items": {"type": "integer"}, "description": "Several agent ids, in place of id: one call returns every report, waiting for all of them when wait_ms>0"}, "wait_ms": {"type": "integer", "description": "0 = snapshot now. >0 = block until the agent finishes (capped at 10 hours). Do not poll every 30s."}}}
,
};
diff --git a/src/session_start.zig b/src/session_start.zig
index 805959b7..c47af0e5 100644
--- a/src/session_start.zig
+++ b/src/session_start.zig
@@ -114,9 +114,8 @@ pub fn setupWorktreeAndBanner(
// terminal on either end (piped in and out) outside --json/ACP, so the root
// catalog leaves it out. The TUI takes stdin over before this, so its
// terminal shows on stdout.
- const terminal = (Io.File.stdin().isTty(io) catch false) or (Io.File.stdout().isTty(io) catch false);
- @import("ask_user.zig").g_no_human = flags.oneshot_prompt != null or
- (!main_mod.json_mode and !@import("mcp_boot.zig").isAcp(flags.positionals.items) and !terminal);
+ const ask_user = @import("ask_user.zig");
+ ask_user.g_no_human = ask_user.detectNoHuman(io, flags.oneshot_prompt != null, main_mod.json_mode, @import("mcp_boot.zig").isAcp(flags.positionals.items));
const sink = engine_sink.writerSink(out);
// --add-dir before --worktree chdir so a relative extra root is resolved
// against the launch cwd, not the scratch tree.
diff --git a/src/subagent.zig b/src/subagent.zig
index 9f48060b..828b630e 100644
--- a/src/subagent.zig
+++ b/src/subagent.zig
@@ -73,6 +73,11 @@ pub fn execSubagent(ctx: ToolCtx, input: Value) !ToolOutput {
const ask = vision_ask.seat(ctx, base, obj, cell, label, prompt, sys_override, niche);
if (ask.pin.effort_outcome == .unsupported_effort) return .{ .text = try ctx.gpa.dupe(u8, "subagent: Off is unsupported by this model; choose a supported effort"), .is_error = true };
if (ask.blocked) return .{ .text = try vision_ask.blockMessage(ctx.gpa, ask), .is_error = true };
+ // ADR 0232: the child sees the user's request and runs at its parent's effort unless pinned.
+ const effort = @import("subagent_fork.zig").effort(ctx.parent_effort, ask.pin.effort, ask.pin.provider orelse base);
+ var forked = ctx;
+ forked.parent_task = try @import("subagent_fork.zig").task(ctx.gpa, ctx.parent_messages);
+ defer ctx.gpa.free(forked.parent_task);
const keep = tools.json_args.flag(input, "retained");
// Interactive roots default to detached workers, but an explicit false
// asks for a foreground child that completes within this prompt turn.
@@ -81,15 +86,15 @@ pub fn execSubagent(ctx: ToolCtx, input: Value) !ToolOutput {
else => false,
};
if ((ctx.interactive_children and !explicit_foreground) or tools.json_args.flag(input, "run_in_background")) {
- var child = ctx;
+ var child = forked;
if (keep) child.retained_worker = try @import("subagent_retained.zig").create(ctx, label);
errdefer if (keep) child.retained_worker.?.deinit(ctx.gpa, ctx.io);
- return spawnSubBackground(child, label, prompt, sys_override, niche, isolation, isolation_fallback, ask.pin.provider, ask.pin.effort, ask);
+ return spawnSubBackground(child, label, prompt, sys_override, niche, isolation, isolation_fallback, ask.pin.provider, effort, ask);
}
const run = if (keep)
- try @import("subagent_resume.zig").foreground(ctx, label, prompt, sys_override, niche, isolation, isolation_fallback, ask.pin.provider, ask.pin.effort)
+ try @import("subagent_resume.zig").foreground(forked, label, prompt, sys_override, niche, isolation, isolation_fallback, ask.pin.provider, effort)
else
- try runSub(ctx, "subagent", label, prompt, sys_override, niche, isolation, isolation_fallback, ask.pin.provider, ask.pin.effort);
+ try runSub(forked, "subagent", label, prompt, sys_override, niche, isolation, isolation_fallback, ask.pin.provider, effort);
return vision_ask.flagReport(ctx.gpa, run.output, ask);
}
diff --git a/src/subagent_fork.zig b/src/subagent_fork.zig
new file mode 100644
index 00000000..62a1fb66
--- /dev/null
+++ b/src/subagent_fork.zig
@@ -0,0 +1,104 @@
+//! ADR 0232: what a spawned child inherits from the agent that started it,
+//! the way the codex route's own client forks a child thread. The child keeps
+//! its own prompt, tools and seat; it gains the user's request and its
+//! parent's live reasoning effort.
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+const Value = std.json.Value;
+const ReasoningEffort = @import("main.zig").ReasoningEffort;
+const Provider = @import("provider.zig").Provider;
+
+/// The user's prompts a child sees, newest kept when the history runs over.
+pub const task_cap = 8 * 1024;
+
+/// The user's own prompts in the parent's history, oldest first, joined by a
+/// rule. Harness notices and tool results are not prompts (userPromptText).
+/// Past `task_cap` the oldest prompts drop and the newest one is cut from the
+/// front, so the child always sees the request it was started for.
+pub fn task(gpa: Allocator, messages: []const Value) ![]u8 {
+ const sep = "\n\n---\n\n";
+ var keep: usize = messages.len;
+ var total: usize = 0;
+ var i = messages.len;
+ while (i > 0) {
+ i -= 1;
+ const text = @import("messages.zig").userPromptText(messages[i]) orelse continue;
+ if (total > 0 and total + sep.len + text.len > task_cap) break;
+ total += (if (total > 0) sep.len else 0) + text.len;
+ keep = i;
+ }
+ var out: std.Io.Writer.Allocating = .init(gpa);
+ errdefer out.deinit();
+ var first = true;
+ for (messages[keep..]) |msg| {
+ const text = @import("messages.zig").userPromptText(msg) orelse continue;
+ if (!first) try out.writer.writeAll(sep);
+ first = false;
+ try out.writer.writeAll(if (text.len > task_cap) text[text.len - task_cap ..] else text);
+ }
+ return out.toOwnedSlice();
+}
+
+/// The child's first message: the user's request as context, then its own
+/// task. Siblings share the context block, so it leads and their cached
+/// prefix runs through it.
+pub fn firstMessage(arena: Allocator, parent_task: []const u8, task_prompt: []const u8) ![]const u8 {
+ if (parent_task.len == 0) return task_prompt;
+ return std.fmt.allocPrint(arena, "The user's request to the agent that started you, for context only; do just your task below.\n\n{s}\n\nYour task:\n{s}", .{ parent_task, task_prompt });
+}
+
+/// The child's reasoning effort. A spawn or persona pin wins; otherwise the
+/// child runs at its parent's live effort (the session's, as /effort or Jev
+/// set it), when the child's own model accepts that level. null keeps the
+/// worker default.
+pub fn effort(parent: ?ReasoningEffort, pinned: ?ReasoningEffort, child: Provider) ?ReasoningEffort {
+ if (pinned) |e| return e;
+ const e = parent orelse return null;
+ if (!@import("effort_route.zig").allows(child.id, child.model, @tagName(e))) return null;
+ return e;
+}
+
+test "fork: the child sees the user's prompts, not notices or tool results (ADR 0232)" {
+ const gpa = std.testing.allocator;
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const messages = @import("messages.zig");
+ var notice = try messages.textMessage(a, "user", "Already loaded for this turn: subagent.");
+ try notice.object.put(a, @import("session_wake.zig").origin_key, .{ .string = "notification" });
+ const history = [_]Value{
+ try messages.textMessage(a, "user", "fix the parser"),
+ try messages.textMessage(a, "assistant", "done"),
+ notice,
+ try messages.textMessage(a, "user", "now split the docs across sub-agents"),
+ };
+ const text = try task(gpa, &history);
+ defer gpa.free(text);
+ try std.testing.expectEqualStrings("fix the parser\n\n---\n\nnow split the docs across sub-agents", text);
+
+ const first = try firstMessage(a, text, "write docs/FORMAT.md");
+ try std.testing.expect(std.mem.startsWith(u8, first, "The user's request to the agent that started you"));
+ try std.testing.expect(std.mem.endsWith(u8, first, "Your task:\nwrite docs/FORMAT.md"));
+ try std.testing.expectEqualStrings("write docs/FORMAT.md", try firstMessage(a, "", "write docs/FORMAT.md"));
+}
+
+test "fork: the newest prompt survives the cap" {
+ const gpa = std.testing.allocator;
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const messages = @import("messages.zig");
+ const old = try a.alloc(u8, task_cap);
+ @memset(old, 'o');
+ const history = [_]Value{ try messages.textMessage(a, "user", old), try messages.textMessage(a, "user", "the request") };
+ const text = try task(gpa, &history);
+ defer gpa.free(text);
+ try std.testing.expectEqualStrings("the request", text);
+}
+
+test "fork: a pin wins, else the parent's effort when the child's model takes it" {
+ const sol: Provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "", .model = "gpt-6-sol", .context = 1 };
+ try std.testing.expectEqual(ReasoningEffort.low, effort(.high, .low, sol).?);
+ try std.testing.expectEqual(ReasoningEffort.high, effort(.high, null, sol).?);
+ try std.testing.expect(effort(null, null, sol) == null);
+}
diff --git a/src/subagent_interactive.zig b/src/subagent_interactive.zig
index f1ef5e87..282fd05f 100644
--- a/src/subagent_interactive.zig
+++ b/src/subagent_interactive.zig
@@ -103,6 +103,34 @@ pub fn output(ctx: tools.ToolCtx, id: u32, wait_ms: u64) !tools.ToolOutput {
return result;
}
+/// agent_output with ids: one call returns every listed agent's report,
+/// waiting for all of them when wait_ms>0, where a call per id cost the
+/// parent a model round trip each (ADR 0232). The agents run concurrently,
+/// so the wait is the slowest one's. An error only when every agent failed:
+/// each report already says which one did.
+pub fn outputMany(ctx: tools.ToolCtx, ids: []const std.json.Value, wait_ms: u64) !tools.ToolOutput {
+ if (ids.len == 0) return invalidIds(ctx.gpa);
+ var out: std.Io.Writer.Allocating = .init(ctx.gpa);
+ defer out.deinit();
+ var failed: usize = 0;
+ for (ids, 0..) |value, i| {
+ const id: u32 = switch (value) {
+ .integer => |n| if (n >= 0 and n <= std.math.maxInt(u32)) @intCast(n) else return invalidIds(ctx.gpa),
+ else => return invalidIds(ctx.gpa),
+ };
+ const one = try output(ctx, id, wait_ms);
+ defer ctx.gpa.free(one.text);
+ if (one.is_error) failed += 1;
+ if (i > 0) try out.writer.writeAll("\n\n");
+ try out.writer.writeAll(one.text);
+ }
+ return .{ .text = try out.toOwnedSlice(), .is_error = failed == ids.len };
+}
+
+fn invalidIds(gpa: std.mem.Allocator) !tools.ToolOutput {
+ return .{ .text = try gpa.dupe(u8, "agent_output: ids must be a non-empty list of agent ids"), .is_error = true };
+}
+
test "beforeRequest yields so parked shell jobs free the prompt" {
configure(true);
defer configure(false);
diff --git a/src/subagent_owned.zig b/src/subagent_owned.zig
index 3c92639a..cba314a6 100644
--- a/src/subagent_owned.zig
+++ b/src/subagent_owned.zig
@@ -31,6 +31,8 @@ pub const Owned = struct {
copy.worker_family = try a.dupe(u8, source.worker_family);
copy.session_name = try a.dupe(u8, source.session_name);
copy.parent_tool_call_id = try a.dupe(u8, source.parent_tool_call_id);
+ copy.parent_task = try a.dupe(u8, source.parent_task);
+ copy.parent_messages = &.{}; // the caller's history moves on once this call returns
if (source.worker_id) |id| copy.worker_id = try a.dupe(u8, id);
if (source.approvals) |ap| {
ap.mutex.lockUncancelable(source.io);
diff --git a/src/subagent_run.zig b/src/subagent_run.zig
index 4921a8cc..b82f52db 100644
--- a/src/subagent_run.zig
+++ b/src/subagent_run.zig
@@ -391,7 +391,9 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const
const task_prompt = playbook.rideBrief(ctx.io, arena, try goal_pacing.childTaskPrompt(arena, tasked, ctx.loop_deadline_ms, util.unixMs(ctx.io)));
try @import("subagent_retained.zig").restore(&agent, ctx);
@import("worker_mcp.zig").inherit(&agent); // ADR 0227
- try agent.messages.append(try textMessage(arena, "user", task_prompt));
+ // ADR 0232: a fresh child starts from the user's request; a resumed one already has it.
+ const first = if (agent.messages.items.len == 0) try @import("subagent_fork.zig").firstMessage(arena, ctx.parent_task, task_prompt) else task_prompt;
+ try agent.messages.append(try textMessage(arena, "user", first));
defer agent.tools_used.deinit(gpa);
// Retry transient failures against the same child history.
var attempts: u8 = 0;
@@ -432,6 +434,8 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const
.cache_read_tokens = agent.last_cache_read,
};
guiEmit(ctx.io, agentUsageEvent(sub_id, run_ok, usage));
+ // ADR 0232: one line per child, so a trace splits a run into the parent's time and each child's.
+ if (ctx.tracer) |tr| tr.note("subagent", std.fmt.allocPrint(arena, "{s} {s} label={s} ms={d} tools={d} context={d} cached={d} effort={t}", .{ sub_id, if (run_ok) "ok" else "failed", label, run_ms, usage.tool_calls, usage.context_tokens, usage.cache_read_tokens, agent.reasoning }) catch "");
const fp = promptFingerprint(agent.systemPrompt());
if (trace.g_traj) |tj| {
tj.capturePrompt(fp, agent.systemPrompt());
diff --git a/src/subagent_spawn_job.zig b/src/subagent_spawn_job.zig
index 1792b26d..965e4f2f 100644
--- a/src/subagent_spawn_job.zig
+++ b/src/subagent_spawn_job.zig
@@ -51,11 +51,13 @@ pub fn spawnSubBackground(ctx: ToolCtx, label: []const u8, prompt: []const u8, s
subagent.g_agent_jobs.mutex.lockUncancelable(ctx.io);
job.id = subagent.g_agent_jobs.next_id;
subagent.g_agent_jobs.next_id += 1;
+ var hint_buf: [256]u8 = undefined;
+ const hint = waitHint(&hint_buf, job.id, owner);
const receipt = (if (state) |saved| std.fmt.allocPrint(
gpa,
- "[agent {d} started: {s}] [task_id {s}]\nIt runs in the background and its report reaches you when it finishes: continue with independent work, or end your reply to wait for it. Do not poll; agent_output(id {d}, wait_ms>0) blocks until it finishes. agent_message queues feedback; subagent_resume continues the retained conversation after completion.",
- .{ job.id, job.label, saved.record.id, job.id },
- ) else std.fmt.allocPrint(gpa, "[agent {d} started: {s}]\nIt runs in the background and its report reaches you when it finishes: continue with independent work, or end your reply to wait for it. Do not poll; agent_output(id {d}, wait_ms>0) blocks until it finishes.", .{ job.id, job.label, job.id })) catch |err| {
+ "[agent {d} started: {s}] [task_id {s}]\nIt runs in the background and its report reaches you when it finishes: continue with independent work, or end your reply to wait for it. Do not poll; {s}. agent_message queues feedback; subagent_resume continues the retained conversation after completion.",
+ .{ job.id, job.label, saved.record.id, hint },
+ ) else std.fmt.allocPrint(gpa, "[agent {d} started: {s}]\nIt runs in the background and its report reaches you when it finishes: continue with independent work, or end your reply to wait for it. Do not poll; {s}.", .{ job.id, job.label, hint })) catch |err| {
subagent.g_agent_jobs.mutex.unlock(ctx.io);
gpa.destroy(job);
return err;
@@ -72,3 +74,54 @@ pub fn spawnSubBackground(ctx: ToolCtx, label: []const u8, prompt: []const u8, s
@import("subagent_interactive.zig").request(ctx);
return .{ .text = receipt };
}
+
+/// The receipt's wait sentence, built under the registry lock before this job
+/// joins the list. With other agents of this session still running it names
+/// them all: one agent_output(ids) call waits for every one, where a call per
+/// id cost a round trip each (ADR 0232).
+fn waitHint(buf: []u8, id: u32, owner: ?[]const u8) []const u8 {
+ var w: std.Io.Writer = .fixed(buf);
+ var others: usize = 0;
+ for (subagent.g_agent_jobs.list.items) |other| {
+ if (other.done or !sameOwner(other.owner, owner)) continue;
+ w.print("{s}{d}", .{ if (others == 0) "agent_output(ids [" else ", ", other.id }) catch return singleHint(buf, id);
+ others += 1;
+ }
+ if (others == 0) return singleHint(buf, id);
+ w.print(", {d}], wait_ms>0) blocks until all of them finish", .{id}) catch return singleHint(buf, id);
+ return w.buffered();
+}
+
+fn singleHint(buf: []u8, id: u32) []const u8 {
+ return std.fmt.bufPrint(buf, "agent_output(id {d}, wait_ms>0) blocks until it finishes", .{id}) catch "agent_output(wait_ms>0) blocks until it finishes";
+}
+
+fn sameOwner(a: ?[]const u8, b: ?[]const u8) bool {
+ const x = a orelse return b == null;
+ const y = b orelse return false;
+ return std.mem.eql(u8, x, y);
+}
+
+test "spawn receipt names every running agent for one agent_output(ids) wait (ADR 0232)" {
+ const gpa = std.testing.allocator;
+ const saved = subagent.g_agent_jobs.list;
+ defer subagent.g_agent_jobs.list = saved;
+ subagent.g_agent_jobs.list = .empty;
+ defer subagent.g_agent_jobs.list.deinit(gpa);
+
+ var buf: [256]u8 = undefined;
+ try std.testing.expectEqualStrings("agent_output(id 1, wait_ms>0) blocks until it finishes", waitHint(&buf, 1, null));
+
+ var running: AgentJob = undefined;
+ running.id = 1;
+ running.done = false;
+ running.owner = null;
+ var finished = running;
+ finished.id = 2;
+ finished.done = true;
+ var elsewhere = running;
+ elsewhere.id = 4;
+ elsewhere.owner = "other-session";
+ try subagent.g_agent_jobs.list.appendSlice(gpa, &.{ &running, &finished, &elsewhere });
+ try std.testing.expectEqualStrings("agent_output(ids [1, 3], wait_ms>0) blocks until all of them finish", waitHint(&buf, 3, null));
+}
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index c159d75e..087d5712 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -333,6 +333,9 @@ test {
_ = @import("worker_mcp.zig"); // ADR 0227
_ = @import("mcp_preload.zig"); // ADR 0231
_ = @import("write_file.zig"); // ADR 0231
+ _ = @import("subagent_fork.zig"); // ADR 0232
+ _ = @import("subagent_spawn_job.zig"); // ADR 0232: the spawn receipt's wait hint
+ _ = @import("ask_user.zig"); // ADR 0232: no todo nudges when nobody watches
_ = @import("piped_paste.zig"); // ADR 0231
_ = @import("mcp_connect_notice.zig"); // ADR 0230
_ = @import("oauth_callback.zig");
diff --git a/src/tools.zig b/src/tools.zig
index 4cec9811..f62c15b1 100644
--- a/src/tools.zig
+++ b/src/tools.zig
@@ -140,6 +140,9 @@ pub const ToolCtx = struct {
loop_deadline_ms: ?i64 = null, // the running /goal run's wall-clock deadline, copied from the spawning Agent: a child inherits the parent's ABSOLUTE deadline (minus an integration margin), never a slice of it
agent_cwd: ?[]const u8 = null, // #276 P0-1: per-agent isolated worktree (absolute path); null = shared cwd. Set from Agent.agent_cwd, never a process-wide chdir — safe across parallel sibling subagents on the same pool.
read_miss: ?*@import("read_miss.zig").Tracker = null, // #1116: turn-scoped consecutive read_file miss latch
+ parent_effort: ?main_mod.ReasoningEffort = null, // ADR 0232: the caller's live effort (/effort or Jev); an unpinned child runs at it
+ parent_messages: []const std.json.Value = &.{}, // ADR 0232: the caller's history, read only while its tool batch runs
+ parent_task: []const u8 = "", // ADR 0232: the user's prompts a spawned child sees as context
};
/// Event JSON for a tool lifecycle hook: {"event","tool","input"[,
diff --git a/src/write_file.zig b/src/write_file.zig
index e8c61b98..e58053f6 100644
--- a/src/write_file.zig
+++ b/src/write_file.zig
@@ -81,22 +81,39 @@ pub fn exec(ctx: tools.ToolCtx, input: std.json.Value) !tools.ToolOutput {
defer if (before == .content) gpa.free(before.content);
snaps.record(path, before);
};
- Io.Dir.cwd().writeFile(io, .{ .sub_path = resolved, .data = content }) catch |err| {
+ const made_dir = writeCreating(io, resolved, content, prev_stat == null) catch |err| {
if (edit_verify.fsErrorText(gpa, .write, path, err)) |t| return .{ .text = t, .is_error = true };
return err;
};
edit_verify.preserveMode(io, resolved, prev_stat);
noteKnown(resolved);
- return .{ .text = try resultText(gpa, path, content, if (prev_stat) |st| st.size else null) };
+ const dir = if (made_dir) std.fs.path.dirname(path) else null;
+ return .{ .text = try resultText(gpa, path, content, if (prev_stat) |st| st.size else null, dir) };
}
-fn resultText(gpa: Allocator, path: []const u8, content: []const u8, prev_size: ?u64) ![]u8 {
+/// A new file whose directory is missing gets the directory first, as
+/// `mkdir -p` would. Refusing it cost the model a second generation of the
+/// whole content, which is most of what a large write costs. True when the
+/// directory was made.
+fn writeCreating(io: Io, resolved: []const u8, data: []const u8, new_file: bool) !bool {
+ Io.Dir.cwd().writeFile(io, .{ .sub_path = resolved, .data = data }) catch |err| {
+ if (err != error.FileNotFound or !new_file) return err;
+ const parent = std.fs.path.dirname(resolved) orelse return err;
+ try Io.Dir.cwd().createDirPath(io, parent);
+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = resolved, .data = data });
+ return true;
+ };
+ return false;
+}
+
+fn resultText(gpa: Allocator, path: []const u8, content: []const u8, prev_size: ?u64, made_dir: ?[]const u8) ![]u8 {
var out: std.Io.Writer.Allocating = .init(gpa);
errdefer out.deinit();
const w = &out.writer;
if (prev_size) |was| {
try w.print("replaced {s} ({d} bytes; was {d})", .{ path, content.len, was });
} else try w.print("created {s} ({d} bytes)", .{ path, content.len });
+ if (made_dir) |d| try w.print(" in new directory {s}", .{d});
if (std.ascii.endsWithIgnoreCase(path, ".json")) try jsonNote(gpa, w, content);
return out.toOwnedSlice();
}
@@ -163,4 +180,17 @@ test "write_file creates, refuses to clobber an unread file, and replaces a know
defer gpa.free(again.text);
try std.testing.expect(!again.is_error);
try std.testing.expect(std.mem.startsWith(u8, again.text, try std.fmt.allocPrint(a, "replaced {s} (6 bytes; was 8); NOT valid JSON (", .{out_json})));
+
+ // A new file in a missing directory gets the directory, not a refusal
+ // the model answers by generating the whole content again.
+ const nested = try std.fmt.allocPrint(a, "{s}/docs/deep/FORMAT.md", .{dir});
+ args.getPtr("path").?.* = .{ .string = nested };
+ args.getPtr("content").?.* = .{ .string = "# x\n" };
+ const made = try exec(ctx, .{ .object = args });
+ defer gpa.free(made.text);
+ try std.testing.expect(!made.is_error);
+ try std.testing.expectEqualStrings(try std.fmt.allocPrint(a, "created {s} (4 bytes) in new directory {s}/docs/deep", .{ nested, dir }), made.text);
+ const landed = try tmp.dir.readFileAlloc(io, "docs/deep/FORMAT.md", gpa, .limited(64));
+ defer gpa.free(landed);
+ try std.testing.expectEqualStrings("# x\n", landed);
}