graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Defer parked peer wakes until idle; refuse cleanup fan-out
Cursor Agent5b8deb36e558
diff --git a/TUI/turn_spawn_tests.zig b/TUI/turn_spawn_tests.zigindex ffd57e58..700d06fd 100644--- a/TUI/turn_spawn_tests.zig+++ b/TUI/turn_spawn_tests.zig@@ -143,6 +143,21 @@ test "idle wake spawn failure is reapable without a thread or model work (#537)"try std.testing.expectEqual(@as(usize, 0), Fake.join_calls);}+test "#1136 idle wake does not start a turn while one is already in flight" {+ install();+ defer uninstall();+ engine.g_idle_wake_fn = Fake.wake;+ var term: Term = undefined;+ term.init(std.testing.allocator, 80, 24);+ defer term.deinit();+ _ = term.typeText("in flight");+ _ = term.enter();+ try expectFailedStart(&term);+ turn.maybeJobWake(&term.model);+ try std.testing.expectEqual(@as(usize, 0), Fake.wake_calls);+ try finishFailedStart(&term);+}+test "completion wake waits for drafts and queued user input" {install();defer uninstall();diff --git a/assets/skills/workspace.md b/assets/skills/workspace.mdindex ea0f666b..692bf723 100644--- a/assets/skills/workspace.md+++ b/assets/skills/workspace.md@@ -43,3 +43,5 @@ subagents already running (they keep their assigned tree). Project files- Process-wide chdir from a subagent (the tool refuses).- Treat this as `graff worktree merge` — that lands a `-w` scratch tab.- Invent a font or OSC sequence; the tree is a directory, not a theme.+- Spawn a child to clean up a finished tree. Finish is not archive.+ Keep dirty or unique-commit trees; an empty clean tree may be removed.diff --git a/docs/adr/0147-finish-is-not-cleanup-fanout.md b/docs/adr/0147-finish-is-not-cleanup-fanout.mdnew file mode 100644index 00000000..eec0d17b--- /dev/null+++ b/docs/adr/0147-finish-is-not-cleanup-fanout.md@@ -0,0 +1,29 @@+# 0147. Finish is not cleanup fan-out; parked peer mail waits for idle++Status: accepted 2026-09-21++## Context++A child that finished a worktree could keep running to "clean up", and+other agents then spawned to fix what that cleanup created (#1135).+Parked peer mail also injected a user-role wake at every root step+boundary, which aborted tools on an in-flight REPL/TUI/ACP turn (#1136).+Idle auto-turn (#1001, #1007) was meant for idle sessions; mid-turn+preemption was already out of scope (#430, ADR 0134).++## Decision++- Isolation is one workspace, one branch, one worktree.+- Finish is not archive. Dirty or unique-commit trees stay; an empty+ clean tree may be removed. Do not spawn a child to clean up a finished+ tree, and do not delete a tree and recreate the work with a fix-it child.+- Live background fan-out is refused at the concurrency cap, not queued+ without bound.+- `deliverInbound` parks inbound during a root turn. Paint and the+ one-line `[peer]` wake wait until idle. Same latch on REPL, TUI, and+ `graff acp`.++## Consequences++A kept-tree note must not read as an invitation to spawn. Peer mail still+starts an idle turn. In-flight tools are not preempted by a parked wake.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex c44ef9ed..ea927bc6 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -165,6 +165,7 @@ record only when you need the evidence or the edge cases.| [0143](0143-release-desktop-is-com-codegraff-app.md) | Packaged Codegraff.app is `com.codegraff.app`. `dev.*` identities are local rebuilds only. || [0144](0144-claim-asks-on-accord.md) | Claim conflicts ping the owner on Accord/JSONL; the model does not broker handoff in chat. || [0145](0145-live-claims-are-accord-progress.md) | Claim acquire/release/handoff replicate as replaceable Accord progress; the JSON ledger stays canonical. |+| [0147](0147-finish-is-not-cleanup-fanout.md) | Finish is not archive: park peer mail until idle, refuse cleanup/fix-it children, cap live fan-out. |## When to write onediff --git a/src/acp_idle.zig b/src/acp_idle.zigindex d870562a..e4989f1f 100644--- a/src/acp_idle.zig+++ b/src/acp_idle.zig@@ -14,6 +14,7 @@ const peer_inbox = @import("peer_inbox.zig");pub fn maybeWake(d: *engine.Dispatch, arena: Allocator, w: *Io.Writer, io: Io) !void {const sid = d.session_id orelse return;if (sid.len == 0) return;+ if (peer_idle.isBusy()) return; // in-flight prompt is not preempted (#1136)var buf: [512]u8 = undefined;const wake = peer_idle.takeIdleWake(io, &buf) orelse return;try promptWake(d, arena, w, wake);@@ -66,6 +67,24 @@ test "#1007 idle wake without a request id streams the turn and no RPC result" {try std.testing.expect(std.mem.indexOf(u8, out, "\"id\"") == null);}+test "#1136 maybeWake is silent while a root turn is in flight" {+ peer_inbox.resetForTest();+ peer_idle.resetForTest();+ defer {+ peer_inbox.resetForTest();+ peer_idle.resetForTest();+ }+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ var buf: [256]u8 = undefined;+ var w: Io.Writer = .fixed(&buf);+ var d: engine.Dispatch = .{ .turn = echoTurn, .ctx = undefined, .session_id = "s1" };+ peer_idle.noteTurnStart();+ try maybeWake(&d, arena.allocator(), &w, std.testing.io);+ try std.testing.expectEqual(@as(usize, 0), w.buffered().len);+ peer_idle.noteTurnEnd();+}+test "#1007 maybeWake is silent without a session or mail" {peer_inbox.resetForTest();peer_idle.resetForTest();diff --git a/src/agent.zig b/src/agent.zigindex 33d74e4f..a6828fd6 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -326,6 +326,8 @@ pub const Agent = struct {}pub fn runTurn(self: *Agent) anyerror![]const u8 {+ if (!self.sub) @import("peer_idle.zig").noteTurnStart();+ defer if (!self.sub) @import("peer_idle.zig").noteTurnEnd();var pending_work: empty_completion.PendingWork = .{};var bounced_answer: empty_completion.BounceAnswer = .{};self.completed = null;diff --git a/src/agent_worktree.zig b/src/agent_worktree.zigindex daf99034..b7127716 100644--- a/src/agent_worktree.zig+++ b/src/agent_worktree.zig@@ -30,7 +30,7 @@ pub fn worktreeKeepReason(status_ok: bool, porcelain: []const u8, base: []constpub fn keepReasonText(reason: KeepReason) []const u8 {return switch (reason) {.dirty => "has changes",- .committed => "has commits that exist ONLY on this branch - merge or cherry-pick them, nothing else references them",+ .committed => "has commits that exist ONLY on this branch — keep this tree; merge or cherry-pick later, do not spawn a cleanup child",.unverifiable => "could not verify it is safe to remove",.removed => "",};diff --git a/src/peer_channel.zig b/src/peer_channel.zigindex 67926528..63d35ac5 100644--- a/src/peer_channel.zig+++ b/src/peer_channel.zig@@ -10,7 +10,8 @@//! - peer_message: send (default), list, inbox, claim, release, handoff, status.//! - /tell <session> <text>: the user's own line into a peer's inbox.//! - /sessions: the saved-session list gains a "live now" section.-//! - deliverInbound: drain + park at every root step boundary.+//! - deliverInbound: drain + park at every root step boundary; paint and+//! the history wake wait until the root is idle (#1136).const std = @import("std");@@ -141,9 +142,10 @@ pub fn handleMessage(self: *Agent, call: ToolCall) !ExecResult {}/// The receiving half, called at every step boundary of a root agent's turn:-/// drain the rooms, park heard bodies, paint them for the human, and inject-/// at most a one-line `[peer]` wake. Never fails a turn — delivery trouble-/// is silence, not an error, because a peer must never break our session.+/// drain the rooms and park heard bodies. Paint and the one-line `[peer]`+/// wake wait until idle — a mid-turn inject aborts tools (#1136). Never+/// fails a turn — delivery trouble is silence, not an error, because a+/// peer must never break our session./// The room tail a late joiner parks; anything older is seek-skipped.pub const backlog_tail_max = 10;var g_backlog_tail_cut = false;@@ -196,6 +198,10 @@ pub fn deliverInbound(root: *Agent) void {}device_msgs = heard.items;if (local_msgs.len == 0 and device_msgs.len == 0 and omitted == 0 and skipped == 0) return;+ const newly = peer_inbox.parkHeard(local_msgs, device_msgs);+ // Park always. Paint and history inject wait until the root is idle+ // (#1136): a mid-turn user-role wake aborts tools. ADR 0134 / #430.+ if (!shouldAnnounce(peer_idle.isBusy(), newly)) return;const sink = engine_sink.forAgent(root);// The visible block gets one blank line of air on either side: peer lines// land mid-stream at a step boundary and used to butt straight against@@ -239,11 +245,15 @@ pub fn deliverInbound(root: *Agent) void {if (summary.len > 0)renderPeerBlock(sink, root.io, true, &.{}, &.{summary});}- if (peer_inbox.parkHeard(local_msgs, device_msgs) == 0) return;// History gets the wake only (ADR 0004). Bodies wait in the ring.root.messages.append(@import("session_wake.zig").message(root.arena, peer_context.capInject(peer_inbox.formatWake(root.arena))) catch return) catch {};}+/// Mid-turn mail stays parked. Announce only when idle and something new landed.+pub fn shouldAnnounce(busy: bool, newly_parked: usize) bool {+ return !busy and newly_parked > 0;+}+/// Emit the drain's visible half as one bracketed unit: a blank notice, the/// debug markers and peer lines in drain order, a closing blank. Nothing at/// all when nothing is visible — a drain that only refreshed history must not@@ -488,6 +498,13 @@ test "summarizeTranscript: last prompt, last words, last tool, from complete lintry std.testing.expectEqual(5, sum.messages); // the torn tail is skipped}+test "#1136 shouldAnnounce: park during a turn, announce only when idle" {+ try std.testing.expect(!shouldAnnounce(true, 3));+ try std.testing.expect(!shouldAnnounce(true, 0));+ try std.testing.expect(!shouldAnnounce(false, 0));+ try std.testing.expect(shouldAnnounce(false, 1));+}+test "displayWindow: only a backlog drain is windowed, to its trailing lines" {// Live incremental drains render every line, however many.try std.testing.expectEqualDeep(DisplayWindow{ .start = 0, .hidden = 0 }, displayWindow(false, 25));diff --git a/src/peer_idle.zig b/src/peer_idle.zigindex 10450c5d..d56d499e 100644--- a/src/peer_idle.zig+++ b/src/peer_idle.zig@@ -13,9 +13,25 @@ const presence = @import("presence.zig");const presence_chan = @import("presence_chan.zig");var last_woken_unread: usize = 0;+var turn_busy: std.atomic.Value(bool) = .init(false);pub fn resetForTest() void {last_woken_unread = 0;+ turn_busy.store(false, .release);+}++/// Root `runTurn` latch. Idle auto-turn (#1001 / #1007) and mid-turn+/// `deliverInbound` injects stay off while a prompt is in flight (#1136).+pub fn noteTurnStart() void {+ turn_busy.store(true, .release);+}++pub fn noteTurnEnd() void {+ turn_busy.store(false, .release);+}++pub fn isBusy() bool {+ return turn_busy.load(.acquire);}fn ingest(io: Io, arena: Allocator) void {@@ -37,6 +53,7 @@ fn ingest(io: Io, arena: Allocator) void {/// buffer so a spent Agent arena cannot hide new JSONL. Does not inject/// history — `runTurn`'s deliverInbound handles leftover room bytes.pub fn takeIdleWake(io: Io, buf: []u8) ?[]const u8 {+ if (isBusy()) return null;var scratch: [64 * 1024]u8 = undefined;var fba = std.heap.FixedBufferAllocator.init(&scratch);const arena = fba.allocator();@@ -89,6 +106,30 @@ test "#1001 idle wake fires once per new unread batch" {try std.testing.expect(takeIdleWake(io, &buf) == null);}+test "#1136 idle wake is silent while a root turn is in flight" {+ peer_inbox.resetForTest();+ resetForTest();+ defer {+ peer_inbox.resetForTest();+ resetForTest();+ }+ var buf: [256]u8 = undefined;+ const msg: presence_chan.Message = .{+ .from_pid = 2,+ .from_start = 1,+ .from_session = "s-peer",+ .text = "hold the tree",+ .to = "s-me",+ };+ _ = peer_inbox.parkHeard(&.{msg}, &.{});+ noteTurnStart();+ try std.testing.expect(isBusy());+ try std.testing.expect(takeIdleWake(std.testing.io, &buf) == null);+ noteTurnEnd();+ const wake = takeIdleWake(std.testing.io, &buf) orelse return error.ExpectedWakeAfterIdle;+ try std.testing.expect(std.mem.indexOf(u8, wake, "[peer]") != null);+}+test "#1001 more mail after a wake can fire again" {peer_inbox.resetForTest();resetForTest();diff --git a/src/prompt_golden.zig b/src/prompt_golden.zigindex 7405e5a7..08b06627 100644--- a/src/prompt_golden.zig+++ b/src/prompt_golden.zig@@ -129,6 +129,10 @@ pub const full_prompt =\\`checkout --`/`restore`, force-push, or `branch -D` — unless the user\\explicitly asks. Their existing commits and any -w worktree\\auto-checkpoints are the user's safety net; do not blow them away.+ \\Finish is not archive: do not spawn a child to clean up a worktree.+ \\Keep dirty or unique-commit trees; an empty clean tree may be removed.+ \\Isolation is one workspace, one branch, one worktree — do not delete+ \\a tree and recreate the work with a fix-it child.\\\\For requested changes, assume the user wants the work done, not described.\\Keep going until thediff --git a/src/prompt_text.zig b/src/prompt_text.zigindex 9a6da034..27c2e8c4 100644--- a/src/prompt_text.zig+++ b/src/prompt_text.zig@@ -187,6 +187,10 @@ pub const git_safety_note =\\`checkout --`/`restore`, force-push, or `branch -D` — unless the user\\explicitly asks. Their existing commits and any -w worktree\\auto-checkpoints are the user's safety net; do not blow them away.+ \\Finish is not archive: do not spawn a child to clean up a worktree.+ \\Keep dirty or unique-commit trees; an empty clean tree may be removed.+ \\Isolation is one workspace, one branch, one worktree — do not delete+ \\a tree and recreate the work with a fix-it child.;/// Always present. The closing sentence is the second prompt-doctrine linediff --git a/src/schema_agents.zig b/src/schema_agents.zigindex 398b2034..0174daa3 100644--- a/src/schema_agents.zig+++ b/src/schema_agents.zig@@ -5,7 +5,7 @@ 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.",.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 (headless default false; interactive REPL always backgrounds direct subagents). Do not poll; headless agent_output(wait_ms>0) blocks until it finishes. A spawn beyond the concurrency cap is queued, never failed."}}, "required": ["description", "prompt"]}+ \\{"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 (removed only if it finishes clean with no unique commits; dirty or unique-commit trees are kept — do not spawn a cleanup child) 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 (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"]},};@@ -21,7 +21,7 @@ pub const workflow_spec = ToolSpec{.name = "workflow",.desc = "Run a workflow of parallel subagents (dynamic workflows as data). Two shapes. PHASES (fan-out + synthesis): phases run sequentially; tasks inside a phase run in parallel as isolated subagents with no shared context, so every prompt must be self-contained; from phase 2 on, {{prev}} in a task prompt is replaced with the labeled results of the previous phase (appended if omitted); a phase may carry `when` to run only if a substring appears in {{prev}} (conditional / early-exit). Returns the final phase results. Use for audits, multi-perspective review, parallel research. Tasks may carry their own system_prompt to run prompt variants side by side; when the fleet is on, a phase with 2+ variants is auto-scored by an LLM judge and each variant's fitness feeds back to the fleet (a tournament doubles as a DGM scoring round). PIPELINE (no barrier): pass {pipeline:{items,stages}} instead to map each item through the stages independently — item A can reach stage 3 while item B is still on stage 1; {{item}} is the item and {{prev}} is this item's previous-stage result. Use for per-item work like transform/verify each file. Optional top-level \"context\" (also settable on the pipeline object): one shared string prepended once, plus a blank line, to every task/stage prompt before {{prev}} substitution, so repo/task boilerplate is stated once instead of repeated in every task.",.schema =- \\{"type": "object", "properties": {"phases": {"type": "array", "description": "Fan-out + synthesis mode (barrier between phases).", "items": {"type": "object", "properties": {"title": {"type": "string", "description": "Short phase label for logs"}, "when": {"type": "string", "description": "Optional (phase 2+): run this phase only if this substring appears (case-insensitive) in the previous phase's results — gate a synthesis/exit phase on a sentinel"}, "tasks": {"type": "array", "items": {"type": "object", "properties": {"description": {"type": "string", "description": "Short label, 3-5 words"}, "prompt": {"type": "string", "description": "Complete, self-contained task; may contain {{prev}}"}, "agent": {"type": "string", "description": "Optional: a named agent type (reviewer, researcher, implementer, skeptic, or a .harness/agents/ name)"}, "system_prompt": {"type": "string", "description": "Optional: replace this task's system prompt (overrides agent)"}, "isolation": {"type": "string", "enum": ["shared_cwd", "worktree"], "description": "Optional: \"worktree\" gives this task 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. Default shared_cwd, unless the chosen agent persona sets its own default."}, "isolation_fallback": {"type": "boolean", "description": "Optional: if isolation:\"worktree\" fails to set up, run in the shared working tree instead of failing this task. Default false."}}, "required": ["description", "prompt"]}}}, "required": ["tasks"]}}, "context": {"type": "string", "description": "Optional: prepended once, plus a blank line, to every task prompt before {{prev}} substitution."}, "pipeline": {"type": "object", "description": "No-barrier mode: map each item through the stages independently.", "properties": {"items": {"type": "array", "items": {"type": "string"}, "description": "Things to process, one independent chain each (e.g. file paths)"}, "stages": {"type": "array", "items": {"type": "object", "properties": {"description": {"type": "string", "description": "Short stage label"}, "prompt": {"type": "string", "description": "Self-contained; {{item}} = the item, {{prev}} = this item's previous-stage result"}, "agent": {"type": "string", "description": "Optional named agent type"}, "system_prompt": {"type": "string", "description": "Optional: replace this stage's system prompt"}, "isolation": {"type": "string", "enum": ["shared_cwd", "worktree"], "description": "Optional: \"worktree\" gives this stage 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. Default shared_cwd, unless the chosen agent persona sets its own default."}, "isolation_fallback": {"type": "boolean", "description": "Optional: if isolation:\"worktree\" fails to set up, run in the shared working tree instead of failing this stage. Default false."}}, "required": ["description", "prompt"]}}, "context": {"type": "string", "description": "Optional: prepended once, plus a blank line, to every stage prompt before {{item}}/{{prev}} substitution."}}, "required": ["items", "stages"]}}}+ \\{"type": "object", "properties": {"phases": {"type": "array", "description": "Fan-out + synthesis mode (barrier between phases).", "items": {"type": "object", "properties": {"title": {"type": "string", "description": "Short phase label for logs"}, "when": {"type": "string", "description": "Optional (phase 2+): run this phase only if this substring appears (case-insensitive) in the previous phase's results — gate a synthesis/exit phase on a sentinel"}, "tasks": {"type": "array", "items": {"type": "object", "properties": {"description": {"type": "string", "description": "Short label, 3-5 words"}, "prompt": {"type": "string", "description": "Complete, self-contained task; may contain {{prev}}"}, "agent": {"type": "string", "description": "Optional: a named agent type (reviewer, researcher, implementer, skeptic, or a .harness/agents/ name)"}, "system_prompt": {"type": "string", "description": "Optional: replace this task's system prompt (overrides agent)"}, "isolation": {"type": "string", "enum": ["shared_cwd", "worktree"], "description": "Optional: \"worktree\" gives this task its own scratch git worktree (removed only if it finishes clean with no unique commits; dirty or unique-commit trees are kept — do not spawn a cleanup child) instead of the shared working tree. Default shared_cwd, unless the chosen agent persona sets its own default."}, "isolation_fallback": {"type": "boolean", "description": "Optional: if isolation:\"worktree\" fails to set up, run in the shared working tree instead of failing this task. Default false."}}, "required": ["description", "prompt"]}}}, "required": ["tasks"]}}, "context": {"type": "string", "description": "Optional: prepended once, plus a blank line, to every task prompt before {{prev}} substitution."}, "pipeline": {"type": "object", "description": "No-barrier mode: map each item through the stages independently.", "properties": {"items": {"type": "array", "items": {"type": "string"}, "description": "Things to process, one independent chain each (e.g. file paths)"}, "stages": {"type": "array", "items": {"type": "object", "properties": {"description": {"type": "string", "description": "Short stage label"}, "prompt": {"type": "string", "description": "Self-contained; {{item}} = the item, {{prev}} = this item's previous-stage result"}, "agent": {"type": "string", "description": "Optional named agent type"}, "system_prompt": {"type": "string", "description": "Optional: replace this stage's system prompt"}, "isolation": {"type": "string", "enum": ["shared_cwd", "worktree"], "description": "Optional: \"worktree\" gives this stage its own scratch git worktree (removed only if it finishes clean with no unique commits; dirty or unique-commit trees are kept — do not spawn a cleanup child) instead of the shared working tree. Default shared_cwd, unless the chosen agent persona sets its own default."}, "isolation_fallback": {"type": "boolean", "description": "Optional: if isolation:\"worktree\" fails to set up, run in the shared working tree instead of failing this stage. Default false."}}, "required": ["description", "prompt"]}}, "context": {"type": "string", "description": "Optional: prepended once, plus a blank line, to every stage prompt before {{item}}/{{prev}} substitution."}}, "required": ["items", "stages"]}}},};diff --git a/src/subagent.zig b/src/subagent.zigindex a607f16a..44a6f25a 100644--- a/src/subagent.zig+++ b/src/subagent.zig@@ -52,14 +52,12 @@ const orch_rows = @import("orchestration_rows.zig"); // #290: a scored tournamenconst spawn_gate = @import("subagent_spawn.zig");pub fn execSubagent(ctx: ToolCtx, input: Value) !ToolOutput {- if (!spawn_gate.allowed(ctx.from_sub)) return .{- .text = try ctx.gpa.dupe(u8, "subagents cannot spawn subagents — do this work yourself"),- .is_error = true,- };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 "";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 };const sys_override = fleet.resolveOverride(obj);const niche = fleet.resolveNiche(obj);const isolation = fleet.resolveIsolation(obj);diff --git a/src/subagent_run.zig b/src/subagent_run.zigindex d16b1fcf..e5596b62 100644--- a/src/subagent_run.zig+++ b/src/subagent_run.zig@@ -453,7 +453,7 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const} else {const outcome = jobs.agentWorktreeFinish(gpa, ctx.io, w);if (outcome.kept) {- extra = std.fmt.allocPrint(gpa, "\n\n[worktree kept ({s}) — path: {s}, branch: {s}]", .{ jobs.keepReasonText(outcome.reason), w.path, w.branch }) catch "";+ extra = std.fmt.allocPrint(gpa, "\n\n[worktree kept ({s}) — path: {s}, branch: {s}; finish is not archive — do not spawn a cleanup child]", .{ jobs.keepReasonText(outcome.reason), w.path, w.branch }) catch "";extra_owned = extra.len > 0;}}diff --git a/src/subagent_spawn.zig b/src/subagent_spawn.zigindex 9d93c25b..f0a968f9 100644--- a/src/subagent_spawn.zig+++ b/src/subagent_spawn.zig@@ -1,11 +1,74 @@-//! One-level spawn gate. Children cannot spawn children.+//! Spawn admission: children cannot spawn children, cleanup is not a+//! child task, and live fan-out is capped (#1135).const std = @import("std");+pub const max_live: u32 = 8;+pub fn allowed(from_sub: bool) bool {return !from_sub;}+/// Description/prompt looks like "clean up the tree" or "fix what that+/// agent created" — finish is not archive; do not launch a fix-it child.+/// Bare "cleanup" in a prompt is not enough (a helper named cleanup() is work).+pub fn isCleanupTask(description: []const u8, prompt: []const u8) bool {+ return hasAny(description, &.{ "clean up", "cleanup", "cleaning up" }) or+ hasAny(prompt, &.{+ "clean up the worktree",+ "cleanup the worktree",+ "cleaning up the worktree",+ "archive the worktree",+ "remove the worktree",+ "delete the worktree",+ "fix the issue that",+ "fix what the other",+ "clean up after",+ "fix the issue created",+ });+}++pub fn refuse(from_sub: bool, description: []const u8, prompt: []const u8, live: u32) ?[]const u8 {+ if (!allowed(from_sub)) return "subagents cannot spawn subagents — do this work yourself";+ if (isCleanupTask(description, prompt))+ return "finish is not archive — do not spawn a child to clean up a worktree; keep dirty or unique-commit trees, and only remove an empty clean tree";+ if (live >= max_live)+ return "too many agents already running — finish or collect existing children before spawning more";+ return null;+}++fn hasAny(text: []const u8, needles: []const []const u8) bool {+ for (needles) |n| {+ if (indexOfIgnoreCase(text, n) != null) return true;+ }+ return false;+}++fn indexOfIgnoreCase(hay: []const u8, needle: []const u8) ?usize {+ if (needle.len == 0 or hay.len < needle.len) return null;+ var i: usize = 0;+ while (i + needle.len <= hay.len) : (i += 1) {+ if (std.ascii.eqlIgnoreCase(hay[i .. i + needle.len], needle)) return i;+ }+ return null;+}+test "spec/prompt_cache: sub never spawns" {try std.testing.expect(allowed(false));try std.testing.expect(!allowed(true));}++test "#1135 refuse: nested spawn, cleanup phrase, and live cap" {+ try std.testing.expect(refuse(true, "review", "read src/main.zig", 0) != null);+ try std.testing.expect(refuse(false, "clean up", "remove leftover files", 0) != null);+ try std.testing.expect(refuse(false, "fix leftover", "clean up the worktree after the child", 1) != null);+ try std.testing.expect(refuse(false, "fix issue", "fix the issue that the other agent created", 0) != null);+ try std.testing.expect(refuse(false, "review", "read the diff", max_live) != null);+ try std.testing.expect(refuse(false, "review", "read the diff", max_live - 1) == null);+ try std.testing.expect(!isCleanupTask("review patch", "read src/foo.zig and report defects"));+}++test "#1135 cleanup detector is case-insensitive and ignores ordinary review" {+ try std.testing.expect(isCleanupTask("Cleaning Up", "archive leftovers"));+ try std.testing.expect(isCleanupTask("worker", "CLEANUP the worktree after the child"));+ try std.testing.expect(!isCleanupTask("implementer", "add a cleanup() helper on the test tmpDir"));+}