graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Give subagent children a structured brief
Cursor Agent715df4802dca
diff --git a/docs/adr/0149-subagent-briefs-are-structured.md b/docs/adr/0149-subagent-briefs-are-structured.mdnew file mode 100644index 00000000..f100230f--- /dev/null+++ b/docs/adr/0149-subagent-briefs-are-structured.md@@ -0,0 +1,31 @@+# 0149. Child briefs are structured sections plus a harness environment header++Status: accepted 2026-09-21++## Context++`subagent` composed the child's first user message from a single `prompt`+string. Parents re-typed working directory, instructions file, disabled+tools, and pre-tool hooks — or omitted them — and children re-derived+paths and observed facts the parent already had. Reports came back in+whatever frame each child picked. The system prompt asked only for a+concise report of concrete facts.++## Decision++Optional `context`, `established_facts`, `scope`, and `deliverable` on+the `subagent` tool render as headed sections around `prompt` (empties+omitted; a bare prompt is unchanged). `runSub` prepends a harness-stated+environment header (cwd, instructions file name, disabled-tool line,+pre_tool hooks) on every path except `judge_task`. The child system+prompt asks for Files changed / Verified / Skipped / Open questions.+REPL, TUI, and GUI share this engine path. Workflow task objects stay+`context` + `prompt` only.++## Consequences++Children see one brief shape. A parent that still sends only `prompt`+gets the environment header and the default report headings, nothing+else. Token cost is a few header lines per spawn, not a copy of+AGENTS.md. Revisiting would need a measured brief-quality eval or a+workflow-task field expansion.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 6df2bdcf..bd29ff79 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -168,6 +168,7 @@ record only when you need the evidence or the edge cases.| [0146](0146-concurrent-sessions-auto-isolate.md) | A second live session in the same Git checkout gets its own worktree; concurrent agents never share `index.lock`. || [0147](0147-finish-is-not-cleanup-fanout.md) | Finish is not archive: park peer wakes until idle, paint the tally at the step boundary, refuse cleanup/fix-it children, cap live fan-out. || [0148](0148-read-file-miss-storm-stops.md) | After N same-prefix or incrementing `read_file` misses, refuse further guesses this turn and point at `codedb list_dir`. |+| [0149](0149-subagent-briefs-are-structured.md) | Child briefs are headed sections plus a harness environment header; the judge stays a bare prompt. |## When to write onediff --git a/sdk/ts/orchestrate.test.ts b/sdk/ts/orchestrate.test.tsindex e63f198e..296d2812 100644--- a/sdk/ts/orchestrate.test.ts+++ b/sdk/ts/orchestrate.test.ts@@ -383,6 +383,10 @@ describe("wire-format helpers", () => {const input = subagentToolInput({description: "fix it",prompt: "fix the bug",+ context: "repo is /tmp",+ establishedFacts: "seat() lives in vision_ask.zig",+ scope: "do not retouch workflow",+ deliverable: "files changed, verified",agent: "implementer",systemPrompt: "be terse",isolation: "worktree",@@ -392,6 +396,10 @@ describe("wire-format helpers", () => {expect(input).toEqual({description: "fix it",prompt: "fix the bug",+ context: "repo is /tmp",+ established_facts: "seat() lives in vision_ask.zig",+ scope: "do not retouch workflow",+ deliverable: "files changed, verified",agent: "implementer",system_prompt: "be terse",isolation: "worktree",diff --git a/sdk/ts/orchestrate.ts b/sdk/ts/orchestrate.tsindex f221075c..58f96f1b 100644--- a/sdk/ts/orchestrate.ts+++ b/sdk/ts/orchestrate.ts@@ -71,6 +71,14 @@ export interface SubagentSpec {description?: string;/** Complete, self-contained task description for the child. */prompt: string;+ /** Repo and hard constraints the child must not re-derive. */+ context?: string;+ /** Observed facts, paths, and line numbers the child must treat as given. */+ establishedFacts?: string;+ /** What not to touch or broaden into. */+ scope?: string;+ /** Required report shape; harness default is files changed / verified / skipped / open questions. */+ deliverable?: string;/** Named persona the child runs with. */agent?: string;/** Replace the child's system prompt outright (overrides `agent`). */@@ -150,6 +158,10 @@ export function subagentToolInput(spec: SubagentSpec): Record<string, unknown> {description: spec.description ?? spec.prompt.slice(0, 60),prompt: spec.prompt,};+ if (spec.context) input.context = spec.context;+ if (spec.establishedFacts) input.established_facts = spec.establishedFacts;+ if (spec.scope) input.scope = spec.scope;+ if (spec.deliverable) input.deliverable = spec.deliverable;if (spec.agent) input.agent = spec.agent;if (spec.systemPrompt) input.system_prompt = spec.systemPrompt;if (spec.isolation) input.isolation = spec.isolation;diff --git a/src/no_local_tools.zig b/src/no_local_tools.zigindex 1a55aeaf..613f842b 100644--- a/src/no_local_tools.zig+++ b/src/no_local_tools.zig@@ -134,7 +134,7 @@ pub fn filterLeanSpecs(comptime Spec: type, arena: Allocator, specs: []const Spe/// not claim root bash/edit are approval-denied — that is true only when/// `unattended_note` is appended (`unattended and !yolo`). `-p --yolo`/// (evals) can act locally; the old lie forced extra child turns.-pub const lean_subagent_desc = "Spawn a sidecar for a self-contained task. Child has bash, read_file, edit_file, write_file, codedb; it does NOT share your context — the prompt must say everything. Returns the final report. Keep the critical-path next step local; do not hand off the blocker and wait. Do file and command work yourself this turn; spawn only for independent work.";+pub const lean_subagent_desc = "Spawn a sidecar for a self-contained task. Child has bash, read_file, edit_file, write_file, codedb; it does NOT share your context. Optional context/established_facts/scope/deliverable become headed sections; omit empties. Returns the final report. Keep the critical-path next step local; do not hand off the blocker and wait. Do file and command work yourself this turn; spawn only for independent work.";/// One-shot tool prose (ADR 0046). Same names and JSON schemas; shorter/// descriptions so flash models start and finish instead of rereadingdiff --git a/src/prompts.zig b/src/prompts.zigindex 4bcf787e..b6ae035d 100644--- a/src/prompts.zig+++ b/src/prompts.zig@@ -468,8 +468,8 @@ pub const sub_system_prompt =\\You are a subagent spawned by an orchestrator agent inside a terminal\\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.+ \\Your final message is returned verbatim to the orchestrator. Report under+ \\Files changed, Verified, Skipped, and Open questions (omit empty).++ parallel_tools_note ++ text.public_write_note ++ text.constraint_authority_note ++ text.publication_ready_note;pub const compact_instruction =diff --git a/src/rlm_spec.zig b/src/rlm_spec.zigindex bbfc915f..f6d21a87 100644--- a/src/rlm_spec.zig+++ b/src/rlm_spec.zig@@ -266,5 +266,6 @@ test "children never see the rlm discovery note (different prefix, different cactry 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(std.mem.indexOf(u8, prompts.sub_system_prompt, "Files changed") != null);try std.testing.expect(prompts.sub_system_prompt.len < prompts.main_system_prompt.len);}diff --git a/src/schema_agents.zig b/src/schema_agents.zigindex 1fcd2b95..83121101 100644--- a/src/schema_agents.zig+++ b/src/schema_agents.zig@@ -3,9 +3,9 @@ const ToolSpec = @import("schema.zig").ToolSpec;pub const subagent_spec = ToolSpec{.name = "subagent",- .desc = "Delegate a self-contained sidecar task; children have file, shell, codedb and skill tools, no parent context, and cannot spawn children. Interactive REPL calls return an id and release the prompt; completion wakes the parent. Headless calls return the report unless run_in_background=true. Call several times for disjoint parallel slices. Keep the critical-path next step local. Prefer code changes with disjoint write sets. Do not set model without a user request or task-specific reason. agent selects a persona; system_prompt overrides it. Use agent_message for feedback and agent_output for results. Do not poll; headless agent_output(wait_ms>0) waits for completion.",+ .desc = "Delegate a self-contained sidecar task; children have file, shell, codedb and skill tools, no parent context, and cannot spawn children. Brief once in this order: context (repo and hard constraints), prompt (numbered steps), established_facts, scope, deliverable. Empty fields are omitted; a bare prompt is unchanged. The harness prepends environment (cwd, instructions file, disabled tools, pre_tool hooks). Interactive REPL calls return an id and release the prompt; completion wakes the parent. Headless calls return the report unless run_in_background=true. Call several times for disjoint parallel slices. Keep the critical-path next step local. Prefer code changes with disjoint write sets. Do not set model without a user request or task-specific reason. agent selects a persona; system_prompt overrides it. Use agent_message for feedback and agent_output for results. Do not poll; headless agent_output(wait_ms>0) waits for completion.",.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: independent / fan-out children default to \"worktree\" (own branch + checkout; auto-removed if clean with no unique commits, kept + reported otherwise). Use \"shared_cwd\" only for same-branch collaboration (review + fix, a pipeline). isolation_fallback:true is the only way a failed git worktree add may share the caller tree."}, "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 (headless default false; interactive REPL always backgrounds direct subagents). Do not poll; headless agent_output(wait_ms>0) blocks until it finishes. A spawn at the live concurrency cap is refused; do not spawn a child to clean up a finished worktree."}}, "required": ["description", "prompt"]}+ \\{"type": "object", "properties": {"description": {"type": "string", "description": "Short label for logs, 3-5 words"}, "prompt": {"type": "string", "description": "Numbered steps and search hints; the complete task. Optional context/established_facts/scope/deliverable render as headed sections around this"}, "context": {"type": "string", "description": "Optional: repo and hard constraints the child must not re-derive"}, "established_facts": {"type": "string", "description": "Optional: observed facts, paths, and line numbers the child must treat as given"}, "scope": {"type": "string", "description": "Optional: what not to touch or broaden into"}, "deliverable": {"type": "string", "description": "Optional: required report shape; default is files changed, verified, skipped, open questions"}, "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: independent / fan-out children default to \"worktree\" (own branch + checkout; auto-removed if clean with no unique commits, kept + reported otherwise). Use \"shared_cwd\" only for same-branch collaboration (review + fix, a pipeline). isolation_fallback:true is the only way a failed git worktree add may share the caller tree."}, "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 (headless default false; interactive REPL always backgrounds direct subagents). Do not poll; headless agent_output(wait_ms>0) blocks until it finishes. A spawn at the live concurrency cap is refused; do not spawn a child to clean up a finished worktree."}}, "required": ["description", "prompt"]},};diff --git a/src/subagent.zig b/src/subagent.zigindex 44a6f25a..9fd387f1 100644--- a/src/subagent.zig+++ b/src/subagent.zig@@ -54,7 +54,9 @@ const spawn_gate = @import("subagent_spawn.zig");pub fn execSubagent(ctx: ToolCtx, input: Value) !ToolOutput {const obj = tools.json_args.object(input) orelse return .{ .text = try ctx.gpa.dupe(u8, "subagent: arguments must be a JSON object with a \"prompt\" string"), .is_error = true };const label = tools.json_args.str(obj, "description") orelse "subagent";- const prompt = tools.json_args.str(obj, "prompt") orelse "";+ const briefed = @import("subagent_brief.zig").fromInput(ctx.gpa, obj);+ defer @import("subagent_brief.zig").release(ctx.gpa, briefed);+ const prompt = briefed.text;if (prompt.len == 0) return .{ .text = try ctx.gpa.dupe(u8, "subagent: missing required \"prompt\" (a self-contained task)"), .is_error = true };if (spawn_gate.refuse(ctx.from_sub, label, prompt, g_agent_jobs.active)) |why|return .{ .text = try ctx.gpa.dupe(u8, why), .is_error = true };@@ -65,15 +67,9 @@ pub fn execSubagent(ctx: ToolCtx, input: Value) !ToolOutput {// #292: explicit spawn `model`/`tier` > persona frontmatter > the session// default (--subagent-model / the #291 ladder), resolved provider-locally.const base = childProvider(ctx.provider, ctx.subagent_provider, ctx.subagent_cross_provider);- // #372: a bare spawn instantiates no catalog shape, so its cell is- // (adhoc, <the canonical slot its description or persona niche names>) —- // the same closed vocabulary a workflow phase files fitness under, so- // both feed one policy instead of two disjoint ones.+ // #372: adhoc cell uses the same role vocabulary as a workflow phase.const cell: route_policy.Cell = .{ .role = route_policy.roleOf(label, niche) };- // #380: that chain, its notes and its #372 route line in one call (this- // file is at the cap). A task naming an image is a VISION ASK: a blind- // AUTOMATIC seat is re-routed to one that sees, a human's pin is kept but- // flagged, and no vision model anywhere refuses the spawn outright.+ // #380: vision-aware seat + honesty flag (this file is at the cap).const ask = vision_ask.seat(ctx, base, obj, cell, label, prompt, sys_override, niche);if (ask.blocked) return .{ .text = try vision_ask.blockMessage(ctx.gpa, ask), .is_error = true };if (ctx.interactive_children or tools.json_args.flag(input, "run_in_background")) return spawnSubBackground(ctx, label, prompt, sys_override, niche, isolation, isolation_fallback, ask.pin.provider, ask.pin.effort, ask);diff --git a/src/subagent_brief.zig b/src/subagent_brief.zignew file mode 100644index 00000000..8a635159--- /dev/null+++ b/src/subagent_brief.zig@@ -0,0 +1,273 @@+//! Structured child briefs: optional parent fields render as headed sections+//! around `prompt`, and `runSub` prepends a harness-stated environment+//! header on every path except the judge. Shared engine path — REPL, TUI,+//! and GUI compose the same first user message.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const ObjectMap = std.json.ObjectMap;++const json_args = @import("json_args.zig");+const no_local_tools = @import("no_local_tools.zig");++pub const context_header = "## Context";+pub const environment_header = "## Environment";+pub const facts_header = "## Established facts";+pub const scope_header = "## Scope";+pub const deliverable_header = "## Deliverable";++pub const Fields = struct {+ prompt: []const u8,+ context: []const u8 = "",+ established_facts: []const u8 = "",+ scope: []const u8 = "",+ deliverable: []const u8 = "",+};++pub const Env = struct {+ cwd: []const u8 = "",+ instructions: []const u8 = "",+ disabled: []const u8 = "",+ hooks: []const u8 = "",+};++pub const Owned = struct {+ text: []const u8,+ owned: bool = false,+};++pub fn release(gpa: Allocator, o: Owned) void {+ if (o.owned) gpa.free(o.text);+}++fn trimmed(s: []const u8) []const u8 {+ return std.mem.trim(u8, s, " \t\r\n");+}++pub fn hasExtras(f: Fields) bool {+ return trimmed(f.context).len > 0 or trimmed(f.established_facts).len > 0 or+ trimmed(f.scope).len > 0 or trimmed(f.deliverable).len > 0;+}++/// Headed sections around `prompt`. Empties omitted. A bare prompt is the+/// same bytes — no headings, no trailing newline.+pub fn render(arena: Allocator, f: Fields) ![]const u8 {+ if (trimmed(f.prompt).len == 0 or !hasExtras(f)) return f.prompt;+ var aw: Io.Writer.Allocating = .init(arena);+ errdefer aw.deinit();+ const w = &aw.writer;+ if (trimmed(f.context).len > 0) try w.print("{s}\n{s}\n\n", .{ context_header, trimmed(f.context) });+ try w.writeAll(f.prompt);+ if (trimmed(f.established_facts).len > 0) try w.print("\n\n{s}\n{s}", .{ facts_header, trimmed(f.established_facts) });+ if (trimmed(f.scope).len > 0) try w.print("\n\n{s}\n{s}", .{ scope_header, trimmed(f.scope) });+ if (trimmed(f.deliverable).len > 0) try w.print("\n\n{s}\n{s}", .{ deliverable_header, trimmed(f.deliverable) });+ return aw.toOwnedSlice();+}++pub fn fromInput(gpa: Allocator, obj: ObjectMap) Owned {+ const f = Fields{+ .prompt = json_args.str(obj, "prompt") orelse "",+ .context = json_args.str(obj, "context") orelse "",+ .established_facts = json_args.str(obj, "established_facts") orelse "",+ .scope = json_args.str(obj, "scope") orelse "",+ .deliverable = json_args.str(obj, "deliverable") orelse "",+ };+ if (trimmed(f.prompt).len == 0 or !hasExtras(f)) return .{ .text = f.prompt };+ const text = render(gpa, f) catch return .{ .text = f.prompt };+ return .{ .text = text, .owned = true };+}++pub fn environmentHeader(arena: Allocator, env: Env) ![]const u8 {+ var aw: Io.Writer.Allocating = .init(arena);+ errdefer aw.deinit();+ const w = &aw.writer;+ try w.writeAll(environment_header);+ var lines: usize = 0;+ if (trimmed(env.cwd).len > 0) {+ try w.print("\n- working directory: {s}", .{trimmed(env.cwd)});+ lines += 1;+ }+ if (trimmed(env.instructions).len > 0) {+ try w.print("\n- project instructions: {s}", .{trimmed(env.instructions)});+ lines += 1;+ }+ if (trimmed(env.disabled).len > 0) {+ try w.print("\n- disabled tools: {s}", .{trimmed(env.disabled)});+ lines += 1;+ }+ if (trimmed(env.hooks).len > 0) {+ try w.print("\n- pre_tool hooks: {s}", .{trimmed(env.hooks)});+ lines += 1;+ }+ if (lines == 0) return "";+ return aw.toOwnedSlice();+}++/// Prepend the environment header unless this is the judge (text-only ranker).+pub fn withEnvironment(arena: Allocator, kind: []const u8, prompt: []const u8, env: Env) ![]const u8 {+ if (std.mem.eql(u8, kind, "judge_task")) return prompt;+ const header = try environmentHeader(arena, env);+ if (header.len == 0) return prompt;+ return std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ header, prompt });+}++fn instructionName(io: Io) []const u8 {+ for ([_][]const u8{ "AGENTS.md", "HARNESS.md", "CLAUDE.md" }) |name| {+ _ = Io.Dir.cwd().statFile(io, name, .{}) catch continue;+ return name;+ }+ return "";+}++fn disabledLine(arena: Allocator) []const u8 {+ const child = "child cannot spawn children; no parent transcript";+ if (no_local_tools.enabled)+ return std.fmt.allocPrint(arena, "{s}; --no-local-tools", .{child}) catch child;+ if (no_local_tools.lean)+ return std.fmt.allocPrint(arena, "{s}; --lean catalog", .{child}) catch child;+ return child;+}++fn hookSummary(arena: Allocator, pre_tool: anytype) []const u8 {+ if (pre_tool.len == 0) return "";+ var aw: Io.Writer.Allocating = .init(arena);+ for (pre_tool, 0..) |h, i| {+ if (i > 0) aw.writer.writeAll("; ") catch return "";+ aw.writer.print("{s} -> {s}", .{ h.match, h.command }) catch return "";+ }+ return aw.toOwnedSlice() catch "";+}++/// `runSub` seam: environment header + parent brief. Judge is identity.+pub fn prepare(arena: Allocator, io: Io, kind: []const u8, prompt: []const u8, agent_cwd: ?[]const u8, pre_tool: anytype) ![]const u8 {+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const cwd = agent_cwd orelse blk: {+ const n = Io.Dir.cwd().realPath(io, &buf) catch break :blk "";+ break :blk buf[0..n];+ };+ const env = Env{+ .cwd = cwd,+ .instructions = instructionName(io),+ .disabled = disabledLine(arena),+ .hooks = hookSummary(arena, pre_tool),+ };+ return withEnvironment(arena, kind, prompt, env);+}++test "render: a bare prompt is unchanged; empty extras do not add headings" {+ const gpa = std.testing.allocator;+ const prompt = "1. grep for seat()\n2. report the callers";+ try std.testing.expectEqualStrings(prompt, try render(gpa, .{ .prompt = prompt }));+ try std.testing.expectEqualStrings(prompt, try render(gpa, .{+ .prompt = prompt,+ .context = " \n",+ .established_facts = "",+ .scope = " ",+ .deliverable = "",+ }));+}++test "render: optional fields become headed sections in fixed order around prompt" {+ const gpa = std.testing.allocator;+ const out = try render(gpa, .{+ .context = "repo is /workspace; do not invent paths",+ .prompt = "1. open src/subagent.zig",+ .established_facts = "runSub already injects the playbook block",+ .scope = "do not retouch workflow task fields",+ .deliverable = "files changed, verified, skipped, open questions",+ });+ defer gpa.free(out);+ const ctx_at = std.mem.indexOf(u8, out, context_header) orelse return error.TestExpectedEqual;+ const prompt_at = std.mem.indexOf(u8, out, "1. open src/subagent.zig") orelse return error.TestExpectedEqual;+ const facts_at = std.mem.indexOf(u8, out, facts_header) orelse return error.TestExpectedEqual;+ const scope_at = std.mem.indexOf(u8, out, scope_header) orelse return error.TestExpectedEqual;+ const del_at = std.mem.indexOf(u8, out, deliverable_header) orelse return error.TestExpectedEqual;+ try std.testing.expect(ctx_at < prompt_at);+ try std.testing.expect(prompt_at < facts_at);+ try std.testing.expect(facts_at < scope_at);+ try std.testing.expect(scope_at < del_at);+ try std.testing.expect(std.mem.indexOf(u8, out, environment_header) == null);+}++test "fromInput: JSON extras compose; missing prompt stays empty even with context" {+ const gpa = std.testing.allocator;+ {+ const parsed = try std.json.parseFromSlice(std.json.Value, gpa, "{\"prompt\":\"do it\",\"context\":\"cwd is /tmp\"}", .{});+ defer parsed.deinit();+ const owned = fromInput(gpa, parsed.value.object);+ defer release(gpa, owned);+ try std.testing.expect(owned.owned);+ try std.testing.expect(std.mem.indexOf(u8, owned.text, context_header) != null);+ try std.testing.expect(std.mem.indexOf(u8, owned.text, "do it") != null);+ }+ {+ const parsed = try std.json.parseFromSlice(std.json.Value, gpa, "{\"prompt\":\"do it\"}", .{});+ defer parsed.deinit();+ const owned = fromInput(gpa, parsed.value.object);+ defer release(gpa, owned);+ try std.testing.expect(!owned.owned);+ try std.testing.expectEqualStrings("do it", owned.text);+ }+ {+ const parsed = try std.json.parseFromSlice(std.json.Value, gpa, "{\"context\":\"repo\",\"prompt\":\"\"}", .{});+ defer parsed.deinit();+ const owned = fromInput(gpa, parsed.value.object);+ defer release(gpa, owned);+ try std.testing.expectEqualStrings("", owned.text);+ }+}++test "withEnvironment: workers get the harness header; the judge does not" {+ const gpa = std.testing.allocator;+ const env = Env{+ .cwd = "/tmp/tree",+ .instructions = "AGENTS.md",+ .disabled = "child cannot spawn children; no parent transcript",+ .hooks = "bash -> ./guard.sh",+ };+ const task = "1. list callers of seat()";+ const child = try withEnvironment(gpa, "subagent", task, env);+ defer gpa.free(child);+ try std.testing.expect(std.mem.startsWith(u8, child, environment_header));+ try std.testing.expect(std.mem.indexOf(u8, child, "working directory: /tmp/tree") != null);+ try std.testing.expect(std.mem.indexOf(u8, child, "project instructions: AGENTS.md") != null);+ try std.testing.expect(std.mem.indexOf(u8, child, "disabled tools:") != null);+ try std.testing.expect(std.mem.indexOf(u8, child, "pre_tool hooks: bash -> ./guard.sh") != null);+ try std.testing.expect(std.mem.endsWith(u8, child, task));++ const wf = try withEnvironment(gpa, "workflow_task", task, env);+ defer gpa.free(wf);+ try std.testing.expect(std.mem.indexOf(u8, wf, environment_header) != null);++ const retry = try withEnvironment(gpa, "workflow_retry", task, env);+ defer gpa.free(retry);+ try std.testing.expect(std.mem.indexOf(u8, retry, environment_header) != null);++ try std.testing.expectEqualStrings(task, try withEnvironment(gpa, "judge_task", task, env));+}++test "subagent schema and description ask for one brief in section order" {+ const spec = @import("schema_agents.zig").subagent_spec;+ for ([_][]const u8{ "\"context\"", "\"established_facts\"", "\"scope\"", "\"deliverable\"" }) |field| {+ try std.testing.expect(std.mem.indexOf(u8, spec.schema, field) != null);+ }+ var parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, spec.schema, .{});+ defer parsed.deinit();+ const required = parsed.value.object.get("required").?.array.items;+ for (required) |r| {+ try std.testing.expect(!std.mem.eql(u8, r.string, "context"));+ try std.testing.expect(!std.mem.eql(u8, r.string, "established_facts"));+ try std.testing.expect(!std.mem.eql(u8, r.string, "scope"));+ try std.testing.expect(!std.mem.eql(u8, r.string, "deliverable"));+ }+ try std.testing.expect(std.mem.indexOf(u8, spec.desc, "established_facts") != null);+ try std.testing.expect(std.mem.indexOf(u8, spec.desc, "Brief once") != null);+}++test "child system prompt asks for a default report shape" {+ const prompt = @import("prompts.zig").sub_system_prompt;+ for ([_][]const u8{ "Files changed", "Verified", "Skipped", "Open questions" }) |h| {+ try std.testing.expect(std.mem.indexOf(u8, prompt, h) != null);+ }+}diff --git a/src/subagent_run.zig b/src/subagent_run.zigindex e5596b62..abb85a86 100644--- a/src/subagent_run.zig+++ b/src/subagent_run.zig@@ -351,9 +351,8 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []constconst wf_task = std.mem.eql(u8, kind, "workflow_task");if (wf_task) guiEmit(ctx.io, .{ .type = "tool_call", .name = "subagent", .input = .{ .description = label }, .id = sub_id });- // Loop deadline + playbook.rideBrief: every spawn path (subagent, workflow,- // retry, judge) injects live constraints here from .graff/playbook.jsonl.- const task_prompt = playbook.rideBrief(ctx.io, arena, try goal_pacing.childTaskPrompt(arena, prompt, ctx.loop_deadline_ms, util.unixMs(ctx.io)));+ const tasked = try @import("subagent_brief.zig").prepare(arena, ctx.io, kind, prompt, ctx.agent_cwd, main_mod.g_hooks.pre_tool);+ const task_prompt = playbook.rideBrief(ctx.io, arena, try goal_pacing.childTaskPrompt(arena, tasked, ctx.loop_deadline_ms, util.unixMs(ctx.io)));try agent.messages.append(try textMessage(arena, "user", task_prompt));defer agent.tools_used.deinit(gpa);// Retry transient failures against the same child history.diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 7b3e5df8..100e2332 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -48,6 +48,7 @@ const native_fold = @import("native_fold.zig");const edit_batch = @import("edit_batch.zig");// Moved off subagent.zig, which is at the 600-line cap.const subagent_tests = @import("subagent_tests.zig");+const subagent_brief = @import("subagent_brief.zig");const subagent_ledger = @import("subagent_ledger.zig"); // #753: handle ledger tests// Bench score/cost priors → derived tier ladders (.harness/bench.json).const bench_priors = @import("bench_priors.zig");@@ -251,6 +252,7 @@ test {_ = native_fold;_ = edit_batch;_ = subagent_tests;+ _ = subagent_brief;_ = subagent_ledger;_ = bench_priors;_ = bench_priors_tests;