graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat: per-agent worktree isolation for subagents (#276)
Rach Pradhanf65790792071
diff --git a/src/agent.zig b/src/agent.zigindex 05242385..3ede5a5f 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -97,6 +97,7 @@ pub const Agent = struct {last_cache_read: u64 = 0, // KV-cache read tokens from the latest responsesys_normal: []const u8 = prompts.main_system_prompt, // root system prompt (+ project instructions)sys_override: ?[]const u8 = null, // subagent-only: per-child system prompt (swarm prompt variants)+ agent_cwd: ?[]const u8 = null, // subagent-only (#276 P0-1): absolute path of this agent's isolated git worktree, threaded through ToolCtx per tool call instead of a process-wide chdir — parallel siblings each keep their owntools_used: trace.ToolSink = .{}, // external tool calls this agent made (per turn for the root)tool_calls_this_turn: u64 = 0, // root-only hard budget counter (--max-tool-calls)seen_tool_keys: std.ArrayList([]const u8) = .empty, // root-only per-turn dedupe keysdiff --git a/src/agent_tools.zig b/src/agent_tools.zigindex d20d1fe9..fb4c9639 100644--- a/src/agent_tools.zig+++ b/src/agent_tools.zig@@ -144,6 +144,7 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {.depth = self.depth,.snapshots = self.snapshots,.tools_used = &self.tools_used,+ .agent_cwd = self.agent_cwd,};// Esc while tools run: spawn a stdin watcher for the duration of// the join (see esc_cancel). Subagents notice the flag mid-flight;diff --git a/src/approvals.zig b/src/approvals.zigindex 0a6a5c01..10f16eb4 100644--- a/src/approvals.zig+++ b/src/approvals.zig@@ -334,14 +334,25 @@ pub fn confinedPath(path: []const u8) bool {/// reject if any component is a symlink (readLink succeeds). Conservative — a/// symlink inside the repo becomes unreadable via the file tools — but it makes/// confinement structural rather than lexical. bash (gated) is unaffected.-pub fn noSymlinkEscape(io: Io, path: []const u8) bool {+/// `base` is the agent's isolated worktree root (#276 P0-1) when its tool+/// calls are pinned there instead of the shared cwd — each checked prefix is+/// then resolved under `base` (an absolute path, so `Io.Dir.cwd()` below is+/// just the dir-fd the readLink call ignores for an absolute sub_path) rather+/// than the process's real cwd, which a worktree-isolated agent never enters.+/// `base == null` (the shared-cwd default) keeps the original behavior exactly.+pub fn noSymlinkEscape(io: Io, path: []const u8, base: ?[]const u8) bool {var buf: [std.fs.max_path_bytes]u8 = undefined;+ var join_buf: [std.fs.max_path_bytes]u8 = undefined;var i: usize = 0;while (i <= path.len) {const slash = std.mem.indexOfScalarPos(u8, path, i, '/') orelse path.len;const prefix = path[0..slash];if (prefix.len > 0) {- if (Io.Dir.cwd().readLink(io, prefix, &buf)) |_| {+ const check_path = if (base) |b|+ std.fmt.bufPrint(&join_buf, "{s}/{s}", .{ b, prefix }) catch return false+ else+ prefix;+ if (Io.Dir.cwd().readLink(io, check_path, &buf)) |_| {return false; // this component is a symlink → refuse} else |_| {} // not a symlink (or doesn't exist yet) → fine}diff --git a/src/exec.zig b/src/exec.zigindex 056dd095..161553d2 100644--- a/src/exec.zig+++ b/src/exec.zig@@ -47,6 +47,7 @@ const confinedPath = approvals_mod.confinedPath;const noSymlinkEscape = approvals_mod.noSymlinkEscape;const jobs = @import("jobs.zig");const runCapped = jobs.runCapped;+const runCappedCwd = jobs.runCappedCwd; // #276 P0-1: bash cwd for a worktree-isolated agentconst spawnJob = jobs.spawnJob;const jobOutput = jobs.jobOutput;const jobKill = jobs.jobKill;@@ -208,7 +209,14 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {return .{ .text = try std.fmt.allocPrint(gpa, "[job {d} started: {s}]\nIt keeps running across turns. Poll new output with bash_output (id {d}, optional wait_ms), stop it with bash_kill.", .{ job.id, job.cmd, job.id }) };}const sh = shellArgv(cmd);- const run = try runCapped(gpa, io, &sh, bash_stdout_cap, bash_stderr_cap, if (ctx.from_sub) subagent_bash_deadline_ms else 0);+ const deadline: u64 = if (ctx.from_sub) subagent_bash_deadline_ms else 0;+ // #276 P0-1: a worktree-isolated agent's bash calls run pinned to its+ // own worktree — via std.process.Child.Cwd, per spawn, never a+ // process-wide chdir — so parallel siblings never share a cwd.+ const run = if (ctx.agent_cwd) |cw|+ try runCappedCwd(gpa, io, &sh, bash_stdout_cap, bash_stderr_cap, deadline, .{ .path = cw })+ else+ try runCapped(gpa, io, &sh, bash_stdout_cap, bash_stderr_cap, deadline);defer gpa.free(run.stdout);defer gpa.free(run.stderr);@@ -270,7 +278,7 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {}if (std.mem.eql(u8, call.name, "read_file")) {const path = strField(input, "path") orelse return missingArg(gpa, "path");- if (!confinedPath(path) or !noSymlinkEscape(io, path)) return outsideCwd(gpa, path);+ if (!confinedPath(path) or !noSymlinkEscape(io, path, ctx.agent_cwd)) return outsideCwd(gpa, path);const start_line = intField(input, "start_line");const end_line = intField(input, "end_line");const want_compact = if (input == .object) (if (input.object.get("compact")) |v| v == .bool and v.bool else false) else false;@@ -278,13 +286,22 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {// when codedb is present and this file is indexed. Lossy (strips comments/// blanks, shows line numbers) so it is NEVER the default and is labeled// not-for-editing; any failure falls through to the native byte-exact read.- if (want_compact) {+ // #276: skipped entirely for a worktree-isolated agent — codedb's index is+ // built over the main checkout, not the scratch worktree, so a compact+ // read there could show stale or altogether wrong content.+ if (want_compact and ctx.agent_cwd == null) {if (main_mod.g_codedb_present == null) main_mod.g_codedb_present = skills.binOnPath(io, "codedb");if (main_mod.g_codedb_present == true and hooks.codedbFileIndexed(io, gpa, path)) {if (try codedbCompactRead(gpa, io, path, start_line, end_line)) |out| return out;}}- const outcome = read_file.read(io, gpa, .cwd(), path, start_line, end_line) catch |err| {+ // #276 P0-1: resolve under the agent's isolated worktree when set —+ // path itself stays relative (that's the agent's own view, used in+ // every message below); only the actual syscall targets the resolved+ // absolute path.+ const resolved: []const u8 = if (ctx.agent_cwd) |base| try std.fmt.allocPrint(gpa, "{s}/{s}", .{ base, path }) else path;+ defer if (ctx.agent_cwd != null) gpa.free(resolved);+ const outcome = read_file.read(io, gpa, .cwd(), resolved, start_line, end_line) catch |err| {if (fsErrorText(gpa, .read, path, err)) |t| return .{ .text = t, .is_error = true };return err;};@@ -349,11 +366,15 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {const path = strField(input, "path") orelse return missingArg(gpa, "path");const old = strField(input, "old_string") orelse return missingArg(gpa, "old_string");const new = strField(input, "new_string") orelse return missingArg(gpa, "new_string");- if (!confinedPath(path) or !noSymlinkEscape(io, path)) return outsideCwd(gpa, path);+ if (!confinedPath(path) or !noSymlinkEscape(io, path, ctx.agent_cwd)) return outsideCwd(gpa, path);const all = if (input.object.get("replace_all")) |v| v == .bool and v.bool else false;if (old.len == 0) return .{ .text = try gpa.dupe(u8, "old_string must not be empty"), .is_error = true };- const data = Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1024 * 1024)) catch |err| {+ // #276 P0-1: resolve under the agent's isolated worktree when set.+ const resolved: []const u8 = if (ctx.agent_cwd) |base| try std.fmt.allocPrint(gpa, "{s}/{s}", .{ base, path }) else path;+ defer if (ctx.agent_cwd != null) gpa.free(resolved);++ const data = Io.Dir.cwd().readFileAlloc(io, resolved, gpa, .limited(1024 * 1024)) catch |err| {if (fsErrorText(gpa, .edit, path, err)) |t| return .{ .text = t, .is_error = true };return err;};@@ -374,14 +395,16 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {if (ctx.snapshots) |snaps| if (!ctx.from_sub) snaps.record(path, data); // pre-edit content for /rewind// #179: capture the file's mode now so the atomic rewrite below can't drop// a 0755 executable bit down to the default 0644.- const prev_stat = Io.Dir.cwd().statFile(io, path, .{}) catch null;+ const prev_stat = Io.Dir.cwd().statFile(io, resolved, .{}) catch null;// Premium splice: when the zigrep suite is installed, zigpatch does// the write — an atomic tmp+rename byte-level --all splice (our count// checks above already enforce the uniqueness semantics). Any// failure, including the tool simply not being on PATH, falls back- // to the native in-place write below.+ // to the native in-place write below. zigpatch is a separate process+ // (`.inherit` cwd, #276) so it's handed `resolved` — an absolute path+ // when isolated — directly, rather than relying on its own cwd.zp: {- const run = runCapped(gpa, io, &.{ "zigpatch", path, "-p", old, "--all", "--content", new }, 4096, 4096, 0) catch break :zp;+ const run = runCapped(gpa, io, &.{ "zigpatch", resolved, "-p", old, "--all", "--content", new }, 4096, 4096, 0) catch break :zp;defer {gpa.free(run.stdout);gpa.free(run.stderr);@@ -391,32 +414,37 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {else => false,};if (ok and std.mem.indexOf(u8, run.stdout, "\"ok\":true") != null) {- preserveMode(io, path, prev_stat); // #179: zigpatch renamed a fresh inode into place+ preserveMode(io, resolved, prev_stat); // #179: zigpatch renamed a fresh inode into placereturn .{ .text = try std.fmt.allocPrint(gpa, "replaced {d} occurrence(s) in {s} (zigpatch)", .{ count, path }) };}}- try Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = replaced });- preserveMode(io, path, prev_stat); // #179: keep the pre-edit mode+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = resolved, .data = replaced });+ preserveMode(io, resolved, prev_stat); // #179: keep the pre-edit modereturn .{ .text = try std.fmt.allocPrint(gpa, "replaced {d} occurrence(s) in {s}", .{ count, path }) };}if (std.mem.eql(u8, call.name, "write_file")) {const path = strField(input, "path") orelse return missingArg(gpa, "path");const content = strField(input, "content") orelse return missingArg(gpa, "content");- if (!confinedPath(path) or !noSymlinkEscape(io, path)) return outsideCwd(gpa, path);+ if (!confinedPath(path) or !noSymlinkEscape(io, path, ctx.agent_cwd)) return outsideCwd(gpa, path);+ // #276 P0-1: resolve under the agent's isolated worktree when set.+ // (snapshots are root-only — `ctx.agent_cwd` is only ever set for a+ // subagent, so the branch below never runs together with isolation.)+ const resolved: []const u8 = if (ctx.agent_cwd) |base| try std.fmt.allocPrint(gpa, "{s}/{s}", .{ base, path }) else path;+ defer if (ctx.agent_cwd != null) gpa.free(resolved);if (ctx.snapshots) |snaps| if (!ctx.from_sub) {// capture the prior content (or absence) before overwriting, for /rewind- const before = Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(4 * 1024 * 1024)) catch null;+ const before = Io.Dir.cwd().readFileAlloc(io, resolved, gpa, .limited(4 * 1024 * 1024)) catch null;defer if (before) |b| gpa.free(b);snaps.record(path, before);};// #179: an existing file keeps its mode (e.g. 0755) across the overwrite;// a brand-new file (prev_stat == null) keeps the default.- const prev_stat = Io.Dir.cwd().statFile(io, path, .{}) catch null;- Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = content }) catch |err| {+ const prev_stat = Io.Dir.cwd().statFile(io, resolved, .{}) catch null;+ Io.Dir.cwd().writeFile(io, .{ .sub_path = resolved, .data = content }) catch |err| {if (fsErrorText(gpa, .write, path, err)) |t| return .{ .text = t, .is_error = true };return err;};- preserveMode(io, path, prev_stat);+ preserveMode(io, resolved, prev_stat);return .{ .text = try std.fmt.allocPrint(gpa, "wrote {d} bytes to {s}", .{ content.len, path }) };}if (std.mem.eql(u8, call.name, "subagent")) return execSubagent(ctx, input);diff --git a/src/fleet.zig b/src/fleet.zigindex 807e2daa..bdd3a026 100644--- a/src/fleet.zig+++ b/src/fleet.zig@@ -32,6 +32,23 @@ const http = @import("http.zig");/// files (frontmatter: name/description/score, body: the system prompt)/// override or extend them — that's where an evolution driver promotes/// archive winners. Spawn one with subagent/workflow `agent: "<name>"`.+/// #276 P0-1: per-agent git-worktree isolation. `.shared_cwd` (default) is+/// today's behavior — every fanned-out subagent shares the caller's working+/// tree. `.worktree` gives the child its own scratch `git worktree`, threaded+/// through as its `Agent.agent_cwd` (never a process-wide chdir — see+/// jobs.zig's "Per-agent worktree isolation" section and subagent.zig's+/// runSub) so parallel siblings never race on the same files.+pub const Isolation = enum {+ shared_cwd,+ worktree,++ fn parse(s: []const u8) ?Isolation {+ if (std.mem.eql(u8, s, "worktree")) return .worktree;+ if (std.mem.eql(u8, s, "shared_cwd")) return .shared_cwd;+ return null;+ }+};+pub const AgentType = struct {name: []const u8,desc: []const u8,@@ -39,6 +56,7 @@ pub const AgentType = struct {score: ?f64 = null, // written by the evolution driver, shown in /agentsbuiltin: bool = false,learned: bool = false,+ isolation: ?Isolation = null, // persona default (frontmatter `isolation: worktree`); null = no opinion, falls through to shared_cwd};/// Preloaded niches: deliberately orthogonal *behavioral* dimensions (what@@ -146,6 +164,7 @@ fn loadAgentDir(io: Io, arena: Allocator, list: *std.ArrayList(AgentType), dir_pif (std.mem.eql(u8, key, "name") and val.len > 0) at.name = val;if (std.mem.eql(u8, key, "description")) at.desc = val;if (std.mem.eql(u8, key, "score")) at.score = std.fmt.parseFloat(f64, val) catch null;+ if (std.mem.eql(u8, key, "isolation")) at.isolation = Isolation.parse(val); // #276: e.g. an "implementer" persona opting into worktree isolation by default}const body_start = fm_end + "\n---".len;at.prompt = std.mem.trim(u8, data[@min(body_start + 1, data.len)..], " \t\r\n");@@ -424,6 +443,74 @@ pub fn resolveNiche(obj: std.json.ObjectMap) []const u8 {if (obj.get("agent")) |v| if (v == .string) return v.string;return "";}+/// #276 P0-1: effective isolation mode for a subagent/workflow-task input.+/// Precedence: an explicit `isolation` field on the call wins; else a named+/// agent type's persona default (`isolation:` frontmatter); else `.shared_cwd`+/// (today's behavior, unchanged for every call that never mentions isolation).+/// An unrecognized `isolation` string is treated the same as omitted — falls+/// through to the persona/default rather than failing the spawn outright.+pub fn resolveIsolation(obj: std.json.ObjectMap) Isolation {+ if (obj.get("isolation")) |v| if (v == .string) if (Isolation.parse(v.string)) |iso| return iso;+ if (obj.get("agent")) |v| if (v == .string) for (g_agent_types) |t| {+ if (std.mem.eql(u8, t.name, v.string)) return t.isolation orelse .shared_cwd;+ };+ return .shared_cwd;+}++/// #276 design point 4: worktree creation failure fails the spawn unless the+/// caller explicitly allowed falling back to the shared cwd. Strict-by-default+/// on purpose — a silent fallback would reintroduce exactly the race isolation+/// exists to prevent.+pub fn resolveIsolationFallback(obj: std.json.ObjectMap) bool {+ if (obj.get("isolation_fallback")) |v| return v == .bool and v.bool;+ return false;+}++test "resolveIsolation: explicit field wins, then the named persona's default, then shared_cwd" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const obj = struct {+ fn p(al: Allocator, s: []const u8) std.json.ObjectMap {+ return (std.json.parseFromSliceLeaky(Value, al, s, .{}) catch unreachable).object;+ }+ }.p;++ const saved_types = g_agent_types;+ defer g_agent_types = saved_types;+ g_agent_types = &.{+ .{ .name = "implementer", .desc = "", .prompt = "x", .isolation = .worktree },+ .{ .name = "researcher", .desc = "", .prompt = "x", .isolation = .shared_cwd },+ .{ .name = "reviewer", .desc = "", .prompt = "x" }, // no opinion+ };++ // A plain task with no isolation/agent field defaults to shared_cwd.+ try std.testing.expectEqual(Isolation.shared_cwd, resolveIsolation(obj(a, "{\"description\":\"x\",\"prompt\":\"y\"}")));+ // A named persona's own default applies when the call doesn't override it.+ try std.testing.expectEqual(Isolation.worktree, resolveIsolation(obj(a, "{\"agent\":\"implementer\"}")));+ try std.testing.expectEqual(Isolation.shared_cwd, resolveIsolation(obj(a, "{\"agent\":\"researcher\"}")));+ try std.testing.expectEqual(Isolation.shared_cwd, resolveIsolation(obj(a, "{\"agent\":\"reviewer\"}"))); // no opinion → default+ // An explicit isolation field overrides the persona's default either way.+ try std.testing.expectEqual(Isolation.shared_cwd, resolveIsolation(obj(a, "{\"agent\":\"implementer\",\"isolation\":\"shared_cwd\"}")));+ try std.testing.expectEqual(Isolation.worktree, resolveIsolation(obj(a, "{\"agent\":\"researcher\",\"isolation\":\"worktree\"}")));+ // An unrecognized isolation string falls through rather than erroring.+ try std.testing.expectEqual(Isolation.worktree, resolveIsolation(obj(a, "{\"agent\":\"implementer\",\"isolation\":\"bogus\"}")));+}++test "resolveIsolationFallback: defaults to strict (false), true only when the caller explicitly opts in" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const obj = struct {+ fn p(al: Allocator, s: []const u8) std.json.ObjectMap {+ return (std.json.parseFromSliceLeaky(Value, al, s, .{}) catch unreachable).object;+ }+ }.p;+ try std.testing.expect(!resolveIsolationFallback(obj(a, "{}")));+ try std.testing.expect(!resolveIsolationFallback(obj(a, "{\"isolation_fallback\":false}")));+ try std.testing.expect(resolveIsolationFallback(obj(a, "{\"isolation_fallback\":true}")));+}+test "resolveNiche: agent name is the fleet cell, inline variant is uncelled" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();diff --git a/src/jobs.zig b/src/jobs.zigindex e8c7be60..c6b6ee0f 100644--- a/src/jobs.zig+++ b/src/jobs.zig@@ -28,6 +28,14 @@ const ranOk = process_runner.ranOk;const codegraff_coauthor = "Co-Authored-By: Codegraff <[email protected]>";const Agent = agent_mod.Agent;+/// Same as `runCapped`, but spawns the child with an explicit working+/// directory instead of inheriting the process's (#276 P0-1: a worktree-+/// isolated subagent's `bash` calls need their own cwd — per-spawn, via+/// `std.process.Child.Cwd`, never a process-wide chdir, so parallel sibling+/// agents on the same pool each keep their own).+pub fn runCappedCwd(gpa: Allocator, io: Io, argv: []const []const u8, stdout_cap: usize, stderr_cap: usize, deadline_ms: u64, cwd: std.process.Child.Cwd) !CappedRun {+ return runCappedWithOptions(gpa, io, argv, stdout_cap, stderr_cap, deadline_ms, .{ .cwd = cwd });+}/// True if the current git working tree has uncommitted *tracked* changes/// (staged or unstaged). Untracked files (`?? …`) don't count — `git reset/// --hard` leaves them alone, so they're safe around a worktree land.@@ -45,6 +53,151 @@ fn gitTreeDirty(gpa: Allocator, io: Io) bool {return false;}+// ── Per-agent worktree isolation (#276 P0-1) ────────────────────────────────+// Extends the session-level `-w`/`graff worktree` mechanism (above) down to+// one worktree per fanned-out subagent, opt-in via `isolation:"worktree"` on+// a subagent/workflow-task spawn (see subagent.zig's `runSub`, fleet.zig's+// `resolveIsolation`). The critical difference from `-w`: nothing here ever+// chdirs the process. `agentWorktreeCreate` returns an absolute path that the+// caller threads through as the child `Agent`'s `agent_cwd` → `ToolCtx.agent_cwd`+// → per-tool-call `bash` cwd / file-op path prefix, so parallel siblings on the+// same pool each keep their own working tree with no shared-state race.++/// One agent's scratch worktree: an absolute path (resolved once at creation,+/// since every later use — bash cwd, file-op path join, `git -C` for status/+/// removal — runs from a pool thread that never chdirs) and its branch name.+pub const AgentWorktree = struct { path: []const u8, branch: []const u8 };++pub const AgentWorktreeError = error{ NotAGitRepo, CreateFailed };++/// User-facing explanation for a failed `isolation:"worktree"` request (#276+/// design point 5: "non-git repo → explicit, friendly error"). Takes `anyerror`+/// (not `AgentWorktreeError`) so the caller — catching the wider error set+/// `agentWorktreeCreate` actually returns (it's `Allocator.Error`-fallible too)+/// — never has to narrow the value first; unrecognized errors still get a+/// sensible fallback message instead of failing to compile/format.+pub fn isolationFailureText(err: anyerror) []const u8 {+ return switch (err) {+ error.NotAGitRepo => "isolation:\"worktree\" requested but this isn't a git repository (or `git` isn't on PATH) — worktrees need a git repo; drop isolation, or set isolation_fallback:true to run in the shared working tree instead",+ error.CreateFailed => "isolation:\"worktree\" requested but `git worktree add` failed (dirty HEAD, a name collision, or a git error) — set isolation_fallback:true to run in the shared working tree instead, or retry",+ else => "isolation:\"worktree\" requested but setup failed — set isolation_fallback:true to run in the shared working tree instead, or retry",+ };+}++/// Deterministic name generator, kept separate from the git calls below so+/// it's unit-testable without a real `Io`: `.graff/worktrees/agent-<id>` on+/// branch `graff/agents/<id>`, `id = "<sub_id>-<nonce>"`. `sub_id` is already+/// unique within one `graff` process (subagentId's monotonic ordinal); the+/// caller-supplied `nonce` (fresh randomness from `io.random`, hex-encoded)+/// covers the cross-process case too — two concurrent `graff` invocations in+/// the same repo whose own per-process counters happen to line up still never+/// collide on a path or branch name.+pub fn agentWorktreeNames(arena: Allocator, sub_id: []const u8, nonce: []const u8) !AgentWorktree {+ return .{+ .path = try std.fmt.allocPrint(arena, ".graff/worktrees/agent-{s}-{s}", .{ sub_id, nonce }),+ .branch = try std.fmt.allocPrint(arena, "graff/agents/{s}-{s}", .{ sub_id, nonce }),+ };+}++/// Create a scratch git worktree, branched from HEAD, for one fanned-out+/// subagent. `error.NotAGitRepo` when the target isn't a git repository at+/// all (or `git` isn't on PATH); `error.CreateFailed` for anything else+/// `git worktree add` rejects.+pub fn agentWorktreeCreate(gpa: Allocator, io: Io, arena: Allocator, sub_id: []const u8) (AgentWorktreeError || Allocator.Error)!AgentWorktree {+ const probe = runCapped(gpa, io, &.{ "git", "rev-parse", "--is-inside-work-tree" }, 4096, 4096, 15_000) catch return error.NotAGitRepo;+ defer {+ gpa.free(probe.stdout);+ gpa.free(probe.stderr);+ }+ if (!ranOk(probe)) return error.NotAGitRepo;++ var raw: [4]u8 = undefined;+ io.random(&raw);+ const nonce = std.fmt.bytesToHex(raw, .lower);+ const names = try agentWorktreeNames(arena, sub_id, &nonce);+ const add = runCapped(gpa, io, &.{ "git", "worktree", "add", names.path, "-b", names.branch }, 8192, 8192, 60_000) catch return error.CreateFailed;+ defer {+ gpa.free(add.stdout);+ gpa.free(add.stderr);+ }+ if (!ranOk(add)) return error.CreateFailed;++ var buf: [4096]u8 = undefined;+ const n = Io.Dir.cwd().realPathFile(io, names.path, &buf) catch return .{ .path = names.path, .branch = names.branch };+ return .{ .path = try arena.dupe(u8, buf[0..n]), .branch = names.branch };+}++/// Pure decision extracted from `agentWorktreeFinish`: any `git status+/// --porcelain` output (tracked OR untracked — unlike the session-level+/// `gitTreeDirty` above, a subagent's brand-new untracked file is real work+/// worth keeping, not noise to auto-discard) means the worktree is dirty.+pub fn isWorktreeStatusDirty(porcelain: []const u8) bool {+ return std.mem.trim(u8, porcelain, " \t\r\n").len > 0;+}++pub const AgentWorktreeOutcome = struct { kept: bool };++/// Called when a worktree-isolated subagent finishes normally (#276 design+/// point 3): an unchanged worktree is removed with its branch — no trace left+/// in `git worktree list` — a changed one is kept for the orchestrator to+/// inspect/land. Never called on a crash (see subagent.zig's runSub): a+/// worktree this function didn't get to run against is left in place,+/// unconditionally, so a crash never silently discards changes. If the status+/// check itself fails to run, this also keeps the worktree rather than guess.+pub fn agentWorktreeFinish(gpa: Allocator, io: Io, wt: AgentWorktree) AgentWorktreeOutcome {+ const st = runCapped(gpa, io, &.{ "git", "-C", wt.path, "status", "--porcelain" }, 1 << 16, 8192, 30_000) catch return .{ .kept = true };+ defer {+ gpa.free(st.stdout);+ gpa.free(st.stderr);+ }+ if (!ranOk(st) or isWorktreeStatusDirty(st.stdout)) return .{ .kept = true };++ if (runCapped(gpa, io, &.{ "git", "worktree", "remove", "--force", wt.path }, 8192, 8192, 30_000)) |r| {+ gpa.free(r.stdout);+ gpa.free(r.stderr);+ } else |_| {}+ if (runCapped(gpa, io, &.{ "git", "branch", "-D", wt.branch }, 8192, 8192, 30_000)) |r| {+ gpa.free(r.stdout);+ gpa.free(r.stderr);+ } else |_| {}+ return .{ .kept = false };+}++test "agentWorktreeNames: unique path/branch per nonce, never collide across repeated spawns (#276)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ const first = try agentWorktreeNames(a, "sa-001-dead", "aa11bb22");+ try std.testing.expectEqualStrings(".graff/worktrees/agent-sa-001-dead-aa11bb22", first.path);+ try std.testing.expectEqualStrings("graff/agents/sa-001-dead-aa11bb22", first.branch);++ // Same sub_id (e.g. two processes whose own counters line up) but a+ // different nonce — the collision case the nonce exists to prevent —+ // still produces distinct names.+ const second = try agentWorktreeNames(a, "sa-001-dead", "cc33dd44");+ try std.testing.expect(!std.mem.eql(u8, first.path, second.path));+ try std.testing.expect(!std.mem.eql(u8, first.branch, second.branch));+}++test "isWorktreeStatusDirty: clean drives auto-cleanup, tracked or untracked changes drive retention (#276)" {+ try std.testing.expect(!isWorktreeStatusDirty("")); // clean → agentWorktreeFinish removes it+ try std.testing.expect(!isWorktreeStatusDirty("\n \n")); // whitespace-only porcelain output is still clean+ try std.testing.expect(isWorktreeStatusDirty(" M src/foo.zig\n")); // tracked edit → kept+ try std.testing.expect(isWorktreeStatusDirty("?? new_file.zig\n")); // untracked-only still counts as changes → kept+}++test "isolationFailureText: friendly, distinct messages for the non-git and create-failed error paths (#276)" {+ const not_git = isolationFailureText(error.NotAGitRepo);+ try std.testing.expect(std.mem.indexOf(u8, not_git, "isn't a git repository") != null);+ try std.testing.expect(std.mem.indexOf(u8, not_git, "isolation_fallback") != null);++ const create_failed = isolationFailureText(error.CreateFailed);+ try std.testing.expect(std.mem.indexOf(u8, create_failed, "git worktree add") != null);+ try std.testing.expect(std.mem.indexOf(u8, create_failed, "isolation_fallback") != null);+ try std.testing.expect(!std.mem.eql(u8, not_git, create_failed));+}+/// Per-turn checkpoint commit for `-w` sessions. The worktree branch is a/// throwaway scratch branch, so committing every turn is free and gives durable/// rewind points across restarts; `graff worktree merge` later --squashes thediff --git a/src/schema.zig b/src/schema.zigindex 71d8e420..7039ba4e 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -206,7 +206,7 @@ const subagent_spec = ToolSpec{.name = "subagent",.desc = "Delegate a self-contained task to a subagent. It has bash, read_file, edit_file, write_file, and codedb (code search); it cannot spawn further subagents and does NOT share your context — the prompt must be self-contained. Returns the subagent final report. Call several times in one response to run tasks in parallel. Pick a persona with agent (builtins: reviewer, researcher, implementer, skeptic — plus any in .harness/agents/), or give the child a custom system_prompt; the trajectory log records the lineage either way.",.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)"}}, "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)"}, "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)."}}, "required": ["description", "prompt"]},};@@ -214,7 +214,7 @@ 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.",.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)"}}, "required": ["description", "prompt"]}}}, "required": ["tasks"]}}, "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"}}, "required": ["description", "prompt"]}}}, "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 (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"]}}, "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"]}}}, "required": ["items", "stages"]}}},};@@ -403,7 +403,7 @@ fn writeToolEntry(s: *std.json.Stringify, kind: Provider.Kind, name: []const u8,/// a per-commit git describe) — bump this only when the schema or JSONL/// protocol changes shape, so SDK regeneration stays byte-stable across/// commits.-pub const schema_version = "0.6";+pub const schema_version = "0.7"; // #276 P0-1: subagent/workflow-task schemas gained isolation/isolation_fallback/// Emit the machine-readable interface description for `harness --schema`:/// providers, models, built-in tools (name/description/parameters), and thediff --git a/src/subagent.zig b/src/subagent.zigindex 614e4af9..0e72832d 100644--- a/src/subagent.zig+++ b/src/subagent.zig@@ -34,6 +34,8 @@ const signScore = scoring.signScore;const fleet = @import("fleet.zig");const learning_privacy = @import("learning_privacy.zig");const agentTypePrompt = fleet.agentTypePrompt;+const Isolation = fleet.Isolation;+const jobs = @import("jobs.zig"); // #276 P0-1: agentWorktreeCreate/agentWorktreeFinish/isolationFailureTextconst cards = @import("cards.zig");const trace = @import("trace.zig");const messages_mod = @import("messages.zig");@@ -51,7 +53,7 @@ pub fn execSubagent(ctx: ToolCtx, input: Value) !ToolOutput {const prompt = if (input.object.get("prompt")) |p| (if (p == .string) p.string else "") else "";if (prompt.len == 0) return .{ .text = try ctx.gpa.dupe(u8, "subagent: missing required \"prompt\" (a self-contained task)"), .is_error = true };const sys_override = fleet.resolveOverride(input.object);- return runSub(ctx, "subagent", label, prompt, sys_override, fleet.resolveNiche(input.object));+ return runSub(ctx, "subagent", label, prompt, sys_override, fleet.resolveNiche(input.object), fleet.resolveIsolation(input.object), fleet.resolveIsolationFallback(input.object));}/// Surface a workflow subagent as a synthetic `tool_call` / `tool_result` on the@@ -170,7 +172,7 @@ test "child model pin crosses the current root provider only with consent" {/// lean default system prompt for a per-child variant (swarm prompt/// evolution); either way the run is recorded as a trajectory node under/// the turn that spawned it, with the prompt's fingerprint.-pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const u8, sys_override: ?[]const u8, niche: []const u8) !ToolOutput {+pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const u8, sys_override: ?[]const u8, niche: []const u8, isolation: Isolation, isolation_fallback: bool) !ToolOutput {const gpa = ctx.gpa;if (ctx.run_budget) |budget| if (ctx.depth >= budget.max_depth) return .{.text = try gpa.dupe(u8, "agent depth limit reached (max depth 1) — do this work in the current agent"),@@ -229,6 +231,26 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []constconst sub_id = cards.subagentId(&id_buf, ordinal, label, prompt);const sprite = cards.subagentSprite(ordinal);cards.subagentLaunchCard(arena, sub_id, sprite, label, kind, prompt);++ // #276 P0-1: opt-in per-agent git-worktree isolation, threaded through as+ // this child's own `agent.agent_cwd` (never a process-wide chdir), so+ // parallel siblings fanned out from the same turn each keep their own+ // working tree — see jobs.zig's "Per-agent worktree isolation" section.+ // Creation failure fails the spawn outright unless the caller explicitly+ // allowed falling back to the shared cwd (design point 4 — a silent+ // fallback would reintroduce the very race isolation exists to prevent).+ var wt: ?jobs.AgentWorktree = null;+ var isolation_note: []const u8 = "";+ if (isolation == .worktree) {+ if (jobs.agentWorktreeCreate(gpa, ctx.io, arena, sub_id)) |created| {+ wt = created;+ } else |err| {+ if (!isolation_fallback) return .{ .text = try gpa.dupe(u8, jobs.isolationFailureText(err)), .is_error = true };+ isolation_note = "\n\n[note: isolation:\"worktree\" failed and fell back to the shared working tree — isolation_fallback:true allowed it]";+ }+ }+ agent.agent_cwd = if (wt) |w| w.path else null;+// Live agent tree: surface workflow_task children as their own GUI rows.const wf_task = std.mem.eql(u8, kind, "workflow_task");if (wf_task) guiEmit(ctx.io, .{ .type = "tool_call", .name = "subagent", .input = .{ .description = label } });@@ -266,40 +288,67 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const// surface the child's own diagnostic (provider status/message + a coarse// category + retry guidance) as an is_error result, duped into gpa before// the child arena that owns last_api_error is freed on return.- const text = report catch |err|- return subagentFailure(gpa, sub_id, err, agent.last_api_error);+ const text = report catch |err| {+ // #276 P0-1: a crashed child leaves its worktree exactly as-is — never+ // silently cleaned up, since we can't safely tell "no changes yet"+ // from "changes we're about to lose" once the run failed abnormally.+ var out = subagentFailure(gpa, sub_id, err, agent.last_api_error);+ if (wt) |w| {+ const combined = std.fmt.allocPrint(gpa, "{s}\n\n[worktree left in place after failure — path: {s}, branch: {s}]", .{ out.text, w.path, w.branch }) catch return out;+ gpa.free(out.text);+ out.text = combined;+ }+ return out;+ };const empty = text.len == 0;const report_body = if (empty) "subagent finished without a report" else text;// Persist the full report + metadata so it can be inspected from the// terminal, then render the completion card with the inspect: path.const detail = cards.writeSubagentDetail(ctx.io, arena, sub_id, label, kind, prompt, report_body, !empty, run_ms, used_tools);cards.subagentDoneCard(arena, sub_id, sprite, label, !empty, run_ms, used_tools, detail);- if (empty) return .{ .text = try gpa.dupe(u8, report_body), .is_error = true };++ // #276 P0-1: the child completed normally — finish an isolated worktree+ // now (an unchanged one is removed with its branch, silently; a changed+ // one is kept and its path/branch ride along in the result so the+ // orchestrator can inspect/land it), or carry the isolation_fallback note.+ var extra: []const u8 = isolation_note;+ var extra_owned = false;+ if (wt) |w| {+ const outcome = jobs.agentWorktreeFinish(gpa, ctx.io, w);+ if (outcome.kept) {+ extra = std.fmt.allocPrint(gpa, "\n\n[worktree kept (has changes) — path: {s}, branch: {s}]", .{ w.path, w.branch }) catch "";+ extra_owned = extra.len > 0;+ }+ }+ defer if (extra_owned) gpa.free(extra);++ if (empty) return .{ .text = try std.fmt.allocPrint(gpa, "{s}{s}", .{ report_body, extra }), .is_error = true };// Append the inspect: path so the orchestrator can cite the detail file.if (detail) |p|- return .{ .text = try std.fmt.allocPrint(gpa, "{s}\n\n[subagent {s} · inspect: {s}]", .{ text, sub_id, p }) };- return .{ .text = try gpa.dupe(u8, text) };+ return .{ .text = try std.fmt.allocPrint(gpa, "{s}\n\n[subagent {s} · inspect: {s}]{s}", .{ text, sub_id, p, extra }) };+ return .{ .text = try std.fmt.allocPrint(gpa, "{s}{s}", .{ text, extra }) };}/// One task inside a workflow phase; never throws, suitable for io.async./// `niche` is the task's MAP-Elites cell, threaded through so runSub's/// fleet:propose — and scoreVariants' submit — tag the variant's genome.-pub fn workflowTask(ctx: ToolCtx, label: []const u8, prompt: []const u8, sys_override: ?[]const u8, niche: []const u8) ToolOutput {- return runSub(ctx, "workflow_task", label, prompt, sys_override, niche) catch |err| failure(ctx.gpa, err);+pub fn workflowTask(ctx: ToolCtx, label: []const u8, prompt: []const u8, sys_override: ?[]const u8, niche: []const u8, isolation: Isolation, isolation_fallback: bool) ToolOutput {+ return runSub(ctx, "workflow_task", label, prompt, sys_override, niche, isolation, isolation_fallback) catch |err| failure(ctx.gpa, err);}/// A second workflow attempt has its own explicit budget kind. It still shares/// the same invocation-wide atomic ceiling and concurrency limiter.-pub fn workflowRetryTask(ctx: ToolCtx, label: []const u8, prompt: []const u8, sys_override: ?[]const u8, niche: []const u8) ToolOutput {- return runSub(ctx, "workflow_retry", label, prompt, sys_override, niche) catch |err| failure(ctx.gpa, err);+pub fn workflowRetryTask(ctx: ToolCtx, label: []const u8, prompt: []const u8, sys_override: ?[]const u8, niche: []const u8, isolation: Isolation, isolation_fallback: bool) ToolOutput {+ return runSub(ctx, "workflow_retry", label, prompt, sys_override, niche, isolation, isolation_fallback) catch |err| failure(ctx.gpa, err);}/// The --judge LLM-as-judge run (see runEval in main): an isolated subagent/// scores the work against the rubric and ends with a `score:` line. Mirrors/// workflowTask — a thin runSub wrapper — so the eval handler can io.async it-/// on a pool thread.+/// on a pool thread. Never worktree-isolated: a judge only reads/reasons over+/// text handed to it, never the filesystem, so there's nothing to isolate.pub fn judgeTask(ctx: ToolCtx, prompt: []const u8) ToolOutput {- return runSub(ctx, "judge_task", "judge", prompt, null, "") catch |err| failure(ctx.gpa, err);+ return runSub(ctx, "judge_task", "judge", prompt, null, "", .shared_cwd, false) catch |err| failure(ctx.gpa, err);}/// Build the judge prompt that scores one workflow variant's output against itsdiff --git a/src/tools.zig b/src/tools.zigindex 49573435..354720ab 100644--- a/src/tools.zig+++ b/src/tools.zig@@ -169,6 +169,7 @@ pub const ToolCtx = struct {depth: u8 = 0,snapshots: ?*Snapshots = null,tools_used: ?*ToolSink = null, // the calling agent's tool log (trajectory/process mining)+ 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.};/// Event JSON for a tool lifecycle hook: {"event","tool","input"[,diff --git a/src/workflow.zig b/src/workflow.zigindex 322fc861..ee41b701 100644--- a/src/workflow.zig+++ b/src/workflow.zig@@ -28,6 +28,7 @@ const scoreVariants = subagent.scoreVariants;const max_workflow_tasks = subagent.max_workflow_tasks;const fleet = @import("fleet.zig");+const Isolation = fleet.Isolation; // #276 P0-1const telemetry = @import("telemetry.zig");const max_workflow_phases = 5;@@ -74,6 +75,8 @@ const StageSpec = struct {prompt: []const u8, // raw; may contain {{item}} / {{prev}}override: ?[]const u8,niche: []const u8,+ isolation: Isolation = .shared_cwd, // #276 P0-1+ isolation_fallback: bool = false,};/// Replace every `needle` in `hay` with `repl` (arena-allocated); returns `hay`@@ -116,10 +119,10 @@ fn pipelineChain(ctx: ToolCtx, item: []const u8, stages: []const StageSpec) Toolvar prev: []const u8 = "";for (stages, 1..) |st, stage_no| {const prompt = pipelinePrompt(arena, st.prompt, item, prev, stage_no) catch |e| return failure(gpa, e);- var out = runSub(ctx, "workflow_task", st.label, prompt, st.override, st.niche) catch |e| failure(gpa, e);+ var out = runSub(ctx, "workflow_task", st.label, prompt, st.override, st.niche, st.isolation, st.isolation_fallback) catch |e| failure(gpa, e);if (out.is_error) {gpa.free(out.text);- out = runSub(ctx, "workflow_retry", st.label, prompt, st.override, st.niche) catch |e| failure(gpa, e);+ out = runSub(ctx, "workflow_retry", st.label, prompt, st.override, st.niche, st.isolation, st.isolation_fallback) catch |e| failure(gpa, e);if (out.is_error) {gpa.free(out.text);return .{@@ -168,6 +171,8 @@ fn runPipeline(ctx: ToolCtx, pv: Value) !ToolOutput {sp.override = fleet.resolveOverride(so);const an = fleet.resolveNiche(so);sp.niche = if (an.len > 0) an else sp.label;+ sp.isolation = fleet.resolveIsolation(so);+ sp.isolation_fallback = fleet.resolveIsolationFallback(so);}const item_strs = try arena.alloc([]const u8, items.len);@@ -275,13 +280,17 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {const overrides = try arena.alloc(?[]const u8, tasks.len);const raws = try arena.alloc([]const u8, tasks.len);const niches = try arena.alloc([]const u8, tasks.len);- for (tasks, prompts, labels, overrides, raws, niches) |task_val, *prompt, *label, *override, *rawp, *niche| {+ const isolations = try arena.alloc(Isolation, tasks.len); // #276 P0-1+ const isolation_fallbacks = try arena.alloc(bool, tasks.len);+ for (tasks, prompts, labels, overrides, raws, niches, isolations, isolation_fallbacks) |task_val, *prompt, *label, *override, *rawp, *niche, *isolation, *isolation_fallback| {if (task_val != .object) return .{ .text = try gpa.dupe(u8, "each task must be an object"), .is_error = true };const task = task_val.object;label.* = if (task.get("description")) |d| (if (d == .string) d.string else "task") else "task";override.* = fleet.resolveOverride(task);const agent_niche = fleet.resolveNiche(task);niche.* = if (agent_niche.len > 0) agent_niche else title;+ isolation.* = fleet.resolveIsolation(task);+ isolation_fallback.* = fleet.resolveIsolationFallback(task);const raw = if (task.get("prompt")) |p| (if (p == .string) p.string else "") else "";if (raw.len == 0) return .{ .text = try gpa.dupe(u8, "each task needs a non-empty \"prompt\""), .is_error = true };rawp.* = raw;@@ -301,8 +310,8 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {// can never abandon running subagents or free their result slots.const futures = try arena.alloc(Io.Future(ToolOutput), tasks.len);const outputs = try arena.alloc(ToolOutput, tasks.len);- for (labels, prompts, overrides, niches, futures) |label, prompt, override, niche, *fut| {- fut.* = ctx.io.async(workflowTask, .{ ctx, label, prompt, override, niche });+ for (labels, prompts, overrides, niches, isolations, isolation_fallbacks, futures) |label, prompt, override, niche, isolation, isolation_fallback, *fut| {+ fut.* = ctx.io.async(workflowTask, .{ ctx, label, prompt, override, niche, isolation, isolation_fallback });}for (futures, outputs) |*fut, *out| out.* = fut.await(ctx.io);defer for (outputs) |out| gpa.free(out.text);@@ -323,7 +332,7 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {const refut = try arena.alloc(Io.Future(ToolOutput), nf);for (refut, 0..) |*rf, k| {const i = fidx[k];- rf.* = ctx.io.async(workflowRetryTask, .{ ctx, labels[i], prompts[i], overrides[i], niches[i] });+ rf.* = ctx.io.async(workflowRetryTask, .{ ctx, labels[i], prompts[i], overrides[i], niches[i], isolations[i], isolation_fallbacks[i] });}for (refut, 0..) |*rf, k| {const retry = rf.await(ctx.io);