Skip to content

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

Python

feat(#629): force experiment fan-out, list the pool, deliver back

Cursor Agente755c17cf9f6
diff --git a/docs/adr/0037-experiment-pool-is-opt-in.md b/docs/adr/0037-experiment-pool-is-opt-in.md
index ea28ca79..b1641137 100644
--- a/docs/adr/0037-experiment-pool-is-opt-in.md
+++ b/docs/adr/0037-experiment-pool-is-opt-in.md
@@ -7,15 +7,17 @@ Status: accepted 2026-08-26
#629: default isolation is `shared_cwd`, so "run 3 approaches" stays on one
agent. Per-spawn `isolation: worktree` pays `git worktree add` mid-turn.
-This record lives on `release/v0.0.279` after the v0.0.279 tag. It is **not**
-on `main` until a later cut.
+On `main` as of the 279 continuation.
## Decision
`--experiment N` / `/experiment N` mints N trees under
`.graff/worktrees/exp-{id}/` **before** the first child. Each spawn claims
-the next seat and sets `agent_cwd`. The root stays on the caller tree.
-Default sessions are unchanged. Pool trees are not auto-deleted.
+the next seat and sets `agent_cwd`. The root stays on the caller tree and
+is told it **must** spawn (system-prompt mandate), not edit. Default
+sessions are unchanged. Pool trees are not auto-deleted: finish reports
+path, branch, keep-reason, and diffstat. `graff worktree list` tags them
+`(experiment pool)`.
## Consequences
diff --git a/docs/adr/README.md b/docs/adr/README.md
index fcc12358..e9ef9c46 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -47,7 +47,7 @@ record only when you need the evidence or the edge cases.
| [0034](0034-remote-images-stay-native.md) | JSON/serve image inputs are a typed URL/base64 union, validated atomically and preserved as native provider vision blocks; never flatten pixels into prompt text. |
| [0035](0035-first-turn-skips-deferred-mcp-join.md) | First model call after a deferred MCP boot does not wait for the handshake; native tools run now, MCP catalogs merge on the next request. |
| [0036](0036-computer-use-keeps-the-signed-codex-bridge.md) | Codex Computer Use keeps its authenticated node_repl process chain: Graff launches it through the signed Codex sandbox wrapper, never embeds V8 or spoofs the service. |
-| [0037](0037-experiment-pool-is-opt-in.md) | `--experiment N` / `/experiment N` pre-mints a child worktree pool; default isolation stays `shared_cwd`. 279 continuation — not on main until a later cut. |
+| [0037](0037-experiment-pool-is-opt-in.md) | `--experiment N` / `/experiment N` pre-mints a child worktree pool; the root must spawn; pool trees are listed and delivered back, never auto-deleted. |
| [0038](0038-in-process-acp-core.md) | Same-process embed is `libgraff` + `graff-core.wasm` + `createGraffAgent()` (ACP core, echo turn). Live coding stays `graff acp`. 279 continuation — not on main until a later cut. |
## When to write one
diff --git a/src/cli.zig b/src/cli.zig
index c65e2dcb..0a36e2ca 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -240,7 +240,7 @@ pub const usage_text =
\\ graff mcp list configured MCP servers
\\ graff plugins [load <name>] list Claude/Cursor/Grok/Codex plugin trees (in place)
\\ graff learn [help] local mutate/evaluate/promote/rollback engine
- \\ graff worktree list list the per-tab worktrees created by -w
+ \\ graff worktree list list -w tabs and experiment-pool trees (tagged)
\\ graff worktree merge <name> squash-land worktree-<name> onto the current branch + clean up
\\ graff worktree remove <name> discard worktree-<name> (drops its scratch work) + delete the branch
\\ graff worktree prune drop git registrations for worktrees whose dirs were deleted
diff --git a/src/commands_experiment.zig b/src/commands_experiment.zig
index 27c77822..a15e7397 100644
--- a/src/commands_experiment.zig
+++ b/src/commands_experiment.zig
@@ -38,6 +38,12 @@ pub fn tryHandle(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Writ
try out.flush();
return true;
};
+ if (pool.directive()) |d| {
+ if (root.sys_base.len > 0 and std.mem.indexOf(u8, root.sys_base, pool.directive_marker) == null) {
+ const next = std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ root.sys_base, d }) catch root.sys_base;
+ @import("prompts.zig").setSystemPrompts(root, next, arena) catch {};
+ }
+ }
try out.print(" {s}experiment {s}: {d} trees under .graff/worktrees/exp-{s}/ — spawn, do not edit here{s}\n", .{
style.dim, id, minted, id, style.reset,
});
diff --git a/src/experiment_pool.zig b/src/experiment_pool.zig
index 44621aa1..cf968fea 100644
--- a/src/experiment_pool.zig
+++ b/src/experiment_pool.zig
@@ -1,8 +1,8 @@
-//! #629 first slice: a pre-minted worktree pool for one experiment.
-//! Lives on `release/v0.0.279` only (not merged to main). Fan-out seats
-//! children in already-created trees so the first tool is not `git worktree add`.
+//! #629 experiment worktree pool: mint N trees first, seat children in them,
+//! force the root to spawn, list/deliver-back without deleting the pool.
const std = @import("std");
+const builtin = @import("builtin");
const Io = std.Io;
const Allocator = std.mem.Allocator;
@@ -12,12 +12,16 @@ const ranOk = process_runner.ranOk;
pub const cap: u8 = 16;
-const Slot = struct { path: []const u8, branch: []const u8 };
+pub const Seat = struct { path: []const u8 = "", branch: []const u8 = "", base: []const u8 = "" };
+
+/// Standing line injected into the root system prompt while a pool is armed.
+pub const directive_marker = "Experiment pool `";
var g_n: u8 = 0;
var g_next: u8 = 0;
var g_id: []const u8 = "";
-var g_slots: [cap]Slot = @splat(.{ .path = "", .branch = "" });
+var g_directive: []const u8 = "";
+var g_slots: [cap]Seat = @splat(.{});
pub fn enabled() bool {
return g_n > 0;
@@ -36,7 +40,8 @@ pub fn reset() void {
g_n = 0;
g_next = 0;
g_id = "";
- g_slots = @splat(.{ .path = "", .branch = "" });
+ g_directive = "";
+ g_slots = @splat(.{});
}
pub fn sanitizeId(buf: []u8, id: []const u8) []const u8 {
@@ -57,10 +62,30 @@ pub fn slotBranch(buf: []u8, id: []const u8, i: u8) []const u8 {
/// Next unused seat, or null when the pool is empty/exhausted.
pub fn claim() ?[]const u8 {
+ const seat = claimSeat() orelse return null;
+ return seat.path;
+}
+
+/// Path + branch + creation HEAD so finish can report keep-reason without
+/// deleting the tree (ADR 0037: pool trees are not auto-deleted).
+pub fn claimSeat() ?Seat {
if (g_next >= g_n) return null;
const i = g_next;
g_next += 1;
- return g_slots[i].path;
+ return g_slots[i];
+}
+
+/// Root must spawn, not edit. Null when the pool is off.
+pub fn directive() ?[]const u8 {
+ if (g_n == 0 or g_directive.len == 0) return null;
+ return g_directive;
+}
+
+/// `graff worktree list` tag: minted pool trees, even after this process resets.
+pub fn isExperimentTree(path: []const u8, branch: []const u8) bool {
+ if (std.mem.indexOf(u8, path, ".graff/worktrees/exp-") != null) return true;
+ const b = if (std.mem.startsWith(u8, branch, "refs/heads/")) branch["refs/heads/".len..] else branch;
+ return std.mem.startsWith(u8, b, "graff/exp/");
}
pub fn statusLine(buf: []u8) []const u8 {
@@ -78,19 +103,31 @@ fn absOrRel(io: Io, arena: Allocator, path: []const u8) ![]const u8 {
return arena.dupe(u8, buf[0..n]);
}
-fn mintOne(gpa: Allocator, io: Io, arena: Allocator, id: []const u8, i: u8) !Slot {
+fn readHead(gpa: Allocator, io: Io, arena: Allocator, path: []const u8) []const u8 {
+ const r = runCapped(gpa, io, &.{ "git", "-C", path, "rev-parse", "HEAD" }, 4096, 4096, 15_000) catch return "";
+ defer {
+ gpa.free(r.stdout);
+ gpa.free(r.stderr);
+ }
+ if (!ranOk(r)) return "";
+ return arena.dupe(u8, std.mem.trim(u8, r.stdout, " \t\r\n")) catch "";
+}
+
+fn mintOne(gpa: Allocator, io: Io, arena: Allocator, id: []const u8, i: u8) !Seat {
var pbuf: [256]u8 = undefined;
var bbuf: [256]u8 = undefined;
const rel = slotPath(&pbuf, id, i);
const branch = try arena.dupe(u8, slotBranch(&bbuf, id, i));
- if (dirExists(io, rel)) return .{ .path = try absOrRel(io, arena, rel), .branch = branch };
- const add = runCapped(gpa, io, &.{ "git", "worktree", "add", rel, "-b", branch }, 8192, 8192, 60_000) catch return error.CreateFailed;
- defer {
- gpa.free(add.stdout);
- gpa.free(add.stderr);
+ if (!dirExists(io, rel)) {
+ const add = runCapped(gpa, io, &.{ "git", "worktree", "add", rel, "-b", branch }, 8192, 8192, 60_000) catch return error.CreateFailed;
+ defer {
+ gpa.free(add.stdout);
+ gpa.free(add.stderr);
+ }
+ if (!ranOk(add) and !dirExists(io, rel)) return error.CreateFailed;
}
- if (!ranOk(add) and !dirExists(io, rel)) return error.CreateFailed;
- return .{ .path = try absOrRel(io, arena, rel), .branch = branch };
+ const path = try absOrRel(io, arena, rel);
+ return .{ .path = path, .branch = branch, .base = readHead(gpa, io, arena, path) };
}
/// Create or reuse N trees under `.graff/worktrees/exp-{id}/`. Idempotent
@@ -113,9 +150,55 @@ pub fn arm(gpa: Allocator, io: Io, arena: Allocator, id: []const u8, n: u8) !u8
}
g_n = n;
g_next = 0;
+ g_directive = try std.fmt.allocPrint(arena, "{s}{s}` is armed with {d} pre-minted worktrees under `.graff/worktrees/exp-{s}/` (branches `graff/exp/{s}/0` …). You MUST call the subagent tool once per independent task or A/B arm so each child claims a seat. Do not edit files in this caller tree. After children return, synthesize — do not redo their work here.", .{
+ directive_marker, g_id, n, g_id, g_id,
+ });
return n;
}
+/// Report path / branch / keep-reason / diffstat. Never removes the tree.
+pub fn deliverNote(gpa: Allocator, io: Io, seat: Seat) []const u8 {
+ const keep = @import("agent_worktree.zig");
+ const st = runCapped(gpa, io, &.{ "git", "-C", seat.path, "status", "--porcelain" }, 1 << 16, 8192, 30_000) catch
+ return std.fmt.allocPrint(gpa, "\n\n[experiment seat kept (could not verify) — path: {s}, branch: {s}]", .{ seat.path, seat.branch }) catch "";
+ defer {
+ gpa.free(st.stdout);
+ gpa.free(st.stderr);
+ }
+ var head_buf: [64]u8 = undefined;
+ const head = blk: {
+ const r = runCapped(gpa, io, &.{ "git", "-C", seat.path, "rev-parse", "HEAD" }, 4096, 4096, 15_000) catch break :blk "";
+ defer {
+ gpa.free(r.stdout);
+ gpa.free(r.stderr);
+ }
+ if (!ranOk(r)) break :blk "";
+ const trimmed = std.mem.trim(u8, r.stdout, " \t\r\n");
+ const n = @min(trimmed.len, head_buf.len);
+ @memcpy(head_buf[0..n], trimmed[0..n]);
+ break :blk head_buf[0..n];
+ };
+ const reason = keep.worktreeKeepReason(ranOk(st), st.stdout, seat.base, head);
+ const why: []const u8 = if (reason == .removed) "clean, left in the pool" else keep.keepReasonText(reason);
+ var stat: []const u8 = "";
+ if (seat.base.len > 0) {
+ if (runCapped(gpa, io, &.{ "git", "-C", seat.path, "diff", "--stat", seat.base }, 4096, 2048, 15_000)) |r| {
+ defer {
+ gpa.free(r.stdout);
+ gpa.free(r.stderr);
+ }
+ if (ranOk(r)) {
+ const trimmed = std.mem.trim(u8, r.stdout, " \t\r\n");
+ if (trimmed.len > 0) stat = std.fmt.allocPrint(gpa, "; {s}", .{trimmed}) catch "";
+ }
+ } else |_| {}
+ }
+ defer if (stat.len > 0) gpa.free(stat);
+ return std.fmt.allocPrint(gpa, "\n\n[experiment seat kept ({s}) — path: {s}, branch: {s}{s}]", .{
+ why, seat.path, seat.branch, stat,
+ }) catch "";
+}
+
test "slot names are stable and claim walks the pool" {
var pbuf: [64]u8 = undefined;
var bbuf: [64]u8 = undefined;
@@ -153,3 +236,67 @@ test "arm rejects empty and oversized pools before git" {
try std.testing.expectError(error.BadPoolSize, arm(std.testing.allocator, std.testing.io, a, "live", 0));
try std.testing.expectError(error.BadPoolSize, arm(std.testing.allocator, std.testing.io, a, "live", 17));
}
+
+test "isExperimentTree matches pool paths and graff/exp branches" {
+ try std.testing.expect(isExperimentTree("/tmp/repo/.graff/worktrees/exp-live/0", "refs/heads/graff/exp/live/0"));
+ try std.testing.expect(isExperimentTree("/other", "graff/exp/q/1"));
+ try std.testing.expect(!isExperimentTree("/tmp/repo/.graff/worktrees/agent-sa-1", "refs/heads/graff/agents/sa-1"));
+ try std.testing.expect(!isExperimentTree("/tmp/repo", "main"));
+}
+
+test "directive is off until arm writes the spawn mandate" {
+ reset();
+ defer reset();
+ try std.testing.expect(directive() == null);
+}
+
+fn fixtureGit(gpa: Allocator, io: Io, argv: []const []const u8) !void {
+ const r = runCapped(gpa, io, argv, 1 << 16, 1 << 16, 60_000) catch return error.SkipZigTest;
+ defer gpa.free(r.stdout);
+ defer gpa.free(r.stderr);
+ if (!ranOk(r)) return error.FixtureCommandFailed;
+}
+
+test "arm mints then reuses real git worktrees; deliver-back never deletes (#629)" {
+ if (builtin.os.tag == .windows) return;
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var orig_dir = try Io.Dir.cwd().openDir(io, ".", .{});
+ defer orig_dir.close(io);
+ defer _ = std.posix.system.fchdir(orig_dir.handle);
+ if (std.posix.system.fchdir(tmp.dir.handle) != 0) return error.ChdirFailed;
+
+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = "work.txt", .data = "one\n" });
+ try fixtureGit(gpa, io, &.{ "git", "init", "-q" });
+ try fixtureGit(gpa, io, &.{ "git", "add", "-A" });
+ try fixtureGit(gpa, io, &.{ "git", "-c", "[email protected]", "-c", "user.name=t", "-c", "commit.gpgsign=false", "commit", "-q", "--no-verify", "-m", "fixture" });
+
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ reset();
+ defer reset();
+
+ try std.testing.expectEqual(@as(u8, 2), try arm(gpa, io, arena, "live", 2));
+ try std.testing.expect(dirExists(io, ".graff/worktrees/exp-live/0"));
+ try std.testing.expect(dirExists(io, ".graff/worktrees/exp-live/1"));
+ try std.testing.expect(std.mem.indexOf(u8, directive().?, "MUST") != null);
+ try std.testing.expect(std.mem.indexOf(u8, directive().?, "Do not edit files in this caller tree") != null);
+
+ const first0 = g_slots[0].path;
+ try std.testing.expectEqual(@as(u8, 2), try arm(gpa, io, arena, "live", 2));
+ try std.testing.expectEqualStrings(first0, g_slots[0].path);
+ try std.testing.expect(g_slots[0].base.len > 0);
+
+ const seat = claimSeat().?;
+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = ".graff/worktrees/exp-live/0/dirty.txt", .data = "edit\n" });
+
+ const note = deliverNote(gpa, io, seat);
+ defer if (note.len > 0) gpa.free(note);
+ try std.testing.expect(std.mem.indexOf(u8, note, "experiment seat kept") != null);
+ try std.testing.expect(std.mem.indexOf(u8, note, seat.branch) != null);
+ try std.testing.expect(std.mem.indexOf(u8, note, "has changes") != null);
+ try std.testing.expect(dirExists(io, ".graff/worktrees/exp-live/0"));
+}
diff --git a/src/startup.zig b/src/startup.zig
index 1e425e06..f851ae2d 100644
--- a/src/startup.zig
+++ b/src/startup.zig
@@ -173,6 +173,10 @@ pub fn buildSystemPrompt(
// sys_normal/sys_strict/sys_ultra/sys_ultra_strict from it — the single
// funnel every later mutation (repl, set_agent, set_system_prompt) must
// also go through, so none of the four ever go stale independently.
+ // #629: --experiment is armed before this runs; the spawn mandate rides
+ // sys_base so a later playbook refresh cannot drop it.
+ if (@import("experiment_pool.zig").directive()) |d|
+ sys_normal = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ sys_normal, d });
return sys_normal;
}
diff --git a/src/subagent_run.zig b/src/subagent_run.zig
index 1850df6b..60ba8976 100644
--- a/src/subagent_run.zig
+++ b/src/subagent_run.zig
@@ -319,8 +319,11 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const
var wt: ?jobs.AgentWorktree = null;
var isolation_note: []const u8 = "";
- if (@import("experiment_pool.zig").claim()) |seat| {
- agent.agent_cwd = seat;
+ var pool_seat = false;
+ if (@import("experiment_pool.zig").claimSeat()) |seat| {
+ agent.agent_cwd = seat.path;
+ wt = .{ .path = seat.path, .branch = seat.branch, .base = seat.base };
+ pool_seat = true;
} else if (isolation == .worktree) {
if (jobs.agentWorktreeCreate(gpa, ctx.io, arena, sub_id)) |created| {
wt = created;
@@ -419,9 +422,16 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const
const text = report catch |err| {
var out = subagentFailure(gpa, sub_id, err, agent.last_api_error, attempts);
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 .{ .output = out, .usage = usage };
- gpa.free(out.text);
- out.text = combined;
+ const tail = if (pool_seat)
+ @import("experiment_pool.zig").deliverNote(gpa, ctx.io, .{ .path = w.path, .branch = w.branch, .base = w.base })
+ else
+ (std.fmt.allocPrint(gpa, "\n\n[worktree left in place after failure — path: {s}, branch: {s}]", .{ w.path, w.branch }) catch "");
+ if (tail.len > 0) {
+ const combined = std.fmt.allocPrint(gpa, "{s}{s}", .{ out.text, tail }) catch return .{ .output = out, .usage = usage };
+ gpa.free(out.text);
+ gpa.free(tail);
+ out.text = combined;
+ }
}
return .{ .output = out, .usage = usage };
};
@@ -437,10 +447,15 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const
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 ({s}) — path: {s}, branch: {s}]", .{ jobs.keepReasonText(outcome.reason), w.path, w.branch }) catch "";
+ if (pool_seat) {
+ extra = @import("experiment_pool.zig").deliverNote(gpa, ctx.io, .{ .path = w.path, .branch = w.branch, .base = w.base });
extra_owned = extra.len > 0;
+ } 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_owned = extra.len > 0;
+ }
}
}
defer if (extra_owned) gpa.free(extra);
diff --git a/src/worktree_prune.zig b/src/worktree_prune.zig
index 9757c5df..a74669c4 100644
--- a/src/worktree_prune.zig
+++ b/src/worktree_prune.zig
@@ -258,7 +258,13 @@ pub fn listWithAge(gpa: Allocator, io: Io, arena: Allocator, out: *Io.Writer) !v
const age = formatAge(&abuf, worktreeAgeMs(io, now_ms, e.path));
const label = if (e.branch.len > 0) shortBranch(e.branch) else if (e.detached) "(detached)" else if (e.bare) "(bare)" else "";
const is_main = i == 0 or (main_path.len > 0 and std.mem.eql(u8, e.path, main_path));
- try out.print("{s: <5} {s} [{s}]{s}\n", .{ age, e.path, label, if (is_main) " (main checkout)" else "" });
+ const tag: []const u8 = if (is_main)
+ " (main checkout)"
+ else if (@import("experiment_pool.zig").isExperimentTree(e.path, e.branch))
+ " (experiment pool)"
+ else
+ "";
+ try out.print("{s: <5} {s} [{s}]{s}\n", .{ age, e.path, label, tag });
}
}