graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(#629): opt-in experiment worktree pool on 279 continuation
Cursor Agent6ec7c6c2f99e
diff --git a/docs/adr/0037-experiment-pool-is-opt-in.md b/docs/adr/0037-experiment-pool-is-opt-in.mdnew file mode 100644index 00000000..ea28ca79--- /dev/null+++ b/docs/adr/0037-experiment-pool-is-opt-in.md@@ -0,0 +1,23 @@+# 0037. Experiment worktree pool is opt-in++Status: accepted 2026-08-26++## Context++#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.++## 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.++## Consequences++Seats are FIFO. A fourth child after `--experiment 3` uses normal isolation.+Dependent pipeline stages still need #295. Docker snapshots stay #554.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 97853e7f..bb00a849 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -47,6 +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. |## When to write onediff --git a/docs/releases/v0.0.279-continuation.md b/docs/releases/v0.0.279-continuation.mdnew file mode 100644index 00000000..8df2dbc7--- /dev/null+++ b/docs/releases/v0.0.279-continuation.md@@ -0,0 +1,11 @@+# v0.0.279 continuation (not on main)++The tagged cut is `v0.0.279` on `main` (`70a5228`). Further work on+`release/v0.0.279` stays **off main** until you ask to cut again.++| Item | Status on this branch |+| --- | --- |+| #629 experiment worktree pool | First slice compiling: `--experiment N`, `/experiment [N\|off\|status]`, children `claim()` a seat and set `agent_cwd` before `git worktree add` (ADR 0037). Mint/reuse of real trees and forced fan-out are still open. |+| #613 ACP Registry | Listing lives in [agentclientprotocol/registry](https://github.com/agentclientprotocol/registry), not this repo. Not started. |+| yxlyx doctor / cube / governed / localhost | Still open (#321 / #306 / #283 / #220–217 / #199 / #106). Not started. |+| WASM / libgraff / in-process embed | Host recipe stays subprocess (`docs/embedding.md`). No `fx-core.wasm`. Not started. |diff --git a/src/args.zig b/src/args.zigindex e28ec22d..ffd5c496 100644--- a/src/args.zig+++ b/src/args.zig@@ -64,6 +64,7 @@ pub const Flags = struct {goal_flag: ?[]const u8 = null, // --goal: standing objective (todos) every turn gets, incl. --json/-peval_cmd_flag: ?[]const u8 = null, // --eval: scoring command for the eval-driven loopworktree_flag: ?[]const u8 = null, // --worktree/-w: isolate this session in a git worktree (parallel agents, no file collisions)+ experiment_n: u8 = 0, // --experiment N: #629 pre-mint N child worktrees (279 continuation)add_dirs: std.ArrayList([]const u8) = .empty, // --add-dir: extra file-tool roots, max 16context_limits: std.ArrayList([]const u8) = .empty, // --context-limit name=Neval_target_flag: ?u8 = null, // --until: target score 0-100 for the eval loop@@ -133,6 +134,10 @@ pub fn parse(init: std.process.Init) !Flags {flags.lean_flag = true;} else if (std.mem.eql(u8, arg, "--worktree") or std.mem.eql(u8, arg, "-w")) {flags.worktree_flag = it.next() orelse std.process.fatal("--worktree needs a name (e.g. --worktree agent1)", .{});+ } else if (std.mem.eql(u8, arg, "--experiment")) {+ const ev = it.next() orelse std.process.fatal("--experiment needs N (1-16)", .{});+ flags.experiment_n = std.fmt.parseInt(u8, ev, 10) catch std.process.fatal("--experiment needs N 1-16, got '{s}'", .{ev});+ if (flags.experiment_n == 0 or flags.experiment_n > 16) std.process.fatal("--experiment N must be 1-16", .{});} else if (std.mem.eql(u8, arg, "--add-dir")) {const dir = it.next() orelse std.process.fatal("--add-dir needs a directory (repeatable, max 16)", .{});flags.add_dirs.append(arena, try arena.dupe(u8, dir)) catch std.process.fatal("--add-dir: out of memory", .{});diff --git a/src/cli.zig b/src/cli.zigindex 02259ddb..c65e2dcb 100644--- a/src/cli.zig+++ b/src/cli.zig@@ -271,6 +271,7 @@ pub const usage_text =\\ --until <0-100> eval-loop target score; stop when reached (default 90)\\ --niche <name> fleet niche this eval optimizes (reviewer/researcher/implementer/skeptic or a custom agent); tags submitted scores so the DGM can promote a champion for that role\\ -w, --worktree <name> isolate this session in a git worktree (.graff/worktrees/<name>) so parallel agents don't collide on files+ \\ --experiment N pre-mint N child worktrees (1-16) under .graff/worktrees/exp-<id>/; next spawns claim a seat\\ --add-dir <path> extra file-tool root (repeatable, max 16). Not a cwd switch; no skills/sessions from it\\ --context-limit name=N cap a named prefix: skill_catalog_bytes|mcp_schema_bytes|agents_md_bytes\\ --no-autocommit with -w, don't auto-commit each turn (default on; land work with `graff worktree merge`)diff --git a/src/command_catalog.zig b/src/command_catalog.zigindex fe794248..2d894fc4 100644--- a/src/command_catalog.zig+++ b/src/command_catalog.zig@@ -66,6 +66,7 @@ pub const commands = [_]Item{.{ .name = "/resume", .usage = "/resume [name]", .desc = "restore a saved conversation (no arg → interactive picker)" },.{ .name = "/sessions", .desc = "list saved sessions in the cwd" },.{ .name = "/workspace", .usage = "/workspace [list|use <name>]", .desc = "list git worktrees or switch this session into one (file tools follow)" },+ .{ .name = "/experiment", .usage = "/experiment [N|off|status]", .desc = "pre-mint N child worktrees (1-16) and seat the next spawns in them; off clears the pool" },.{ .name = "/todo", .desc = "show the current task list" },.{ .name = "/jobs", .desc = "list background jobs" },.{ .name = "/cost", .desc = "session token usage and cost" },diff --git a/src/commands_experiment.zig b/src/commands_experiment.zignew file mode 100644index 00000000..27c77822--- /dev/null+++ b/src/commands_experiment.zig@@ -0,0 +1,96 @@+//! `/experiment` — arm or inspect the #629 worktree pool (279 continuation).++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const Agent = @import("agent.zig").Agent;+const pool = @import("experiment_pool.zig");+const style = &@import("ansi.zig").style;++pub fn tryHandle(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {+ if (!std.mem.eql(u8, line, "/experiment") and !std.mem.startsWith(u8, line, "/experiment "))+ return false;+ const rest = std.mem.trim(u8, line["/experiment".len..], " \t");+ if (rest.len == 0 or std.mem.eql(u8, rest, "status")) {+ var buf: [80]u8 = undefined;+ try out.print(" {s}{s}{s}\n", .{ style.dim, pool.statusLine(&buf), style.reset });+ try out.flush();+ return true;+ }+ if (std.mem.eql(u8, rest, "off") or std.mem.eql(u8, rest, "clear")) {+ pool.reset();+ try out.print(" {s}experiment pool off{s}\n", .{ style.dim, style.reset });+ try out.flush();+ return true;+ }+ const n = std.fmt.parseInt(u8, rest, 10) catch 0;+ if (n == 0 or n > pool.cap) {+ try out.print(" {s}usage: /experiment [N|off|status] (N is 1-{d}){s}\n", .{ style.dim, pool.cap, style.reset });+ try out.flush();+ return true;+ }+ const raw = if (root.session_name.len > 0) root.session_name else "live";+ var idbuf: [64]u8 = undefined;+ const id = pool.sanitizeId(&idbuf, raw);+ const minted = pool.arm(root.gpa, root.io, arena, id, n) catch |err| {+ try out.print(" {s}experiment: {t}{s}\n", .{ style.red, err, style.reset });+ try out.flush();+ return true;+ };+ 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,+ });+ try out.flush();+ return true;+}++fn stubRoot(out: *Io.Writer) Agent {+ return .{+ .gpa = std.testing.allocator,+ .arena = std.testing.allocator,+ .io = std.testing.io,+ .client = undefined,+ .provider = undefined,+ .messages = undefined,+ .sub = false,+ .label = "test",+ .out = out,+ .session_name = "live",+ };+}++test "tryHandle: status/off/usage, unrelated lines fall through" {+ pool.reset();+ defer pool.reset();+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);+ defer aw.deinit();+ var root = stubRoot(&aw.writer);+ const a = std.testing.allocator;++ try std.testing.expect(!try tryHandle(&root, a, "/help", &aw.writer));+ try std.testing.expect(!try tryHandle(&root, a, "/experimental", &aw.writer));++ try std.testing.expect(try tryHandle(&root, a, "/experiment", &aw.writer));+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "experiment pool off") != null);++ aw.clearRetainingCapacity();+ try std.testing.expect(try tryHandle(&root, a, "/experiment status", &aw.writer));+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "experiment pool off") != null);++ aw.clearRetainingCapacity();+ try std.testing.expect(try tryHandle(&root, a, "/experiment off", &aw.writer));+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "experiment pool off") != null);++ aw.clearRetainingCapacity();+ try std.testing.expect(try tryHandle(&root, a, "/experiment 0", &aw.writer));+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "usage:") != null);++ aw.clearRetainingCapacity();+ try std.testing.expect(try tryHandle(&root, a, "/experiment 17", &aw.writer));+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "usage:") != null);++ aw.clearRetainingCapacity();+ try std.testing.expect(try tryHandle(&root, a, "/experiment no", &aw.writer));+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "usage:") != null);+}diff --git a/src/commands_session.zig b/src/commands_session.zigindex 90a25e93..46ea6884 100644--- a/src/commands_session.zig+++ b/src/commands_session.zig@@ -91,6 +91,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,// id — a numeric /rewind falls through to the conversation rewind below.if (try commands_sandbox.tryHandle(root, arena, line, out)) return true;if (try commands_trajectory.tryHandle(root, arena, line, out)) return true;+ if (try @import("commands_experiment.zig").tryHandle(root, arena, line, out)) return true;if (try workspace_switch.slashCommand(root, arena, line, out)) return true;if (try plugins.slashCommand(root.io, arena, root.home, line, out)) return true;if (std.mem.eql(u8, line, "/clear")) {diff --git a/src/experiment_pool.zig b/src/experiment_pool.zignew file mode 100644index 00000000..44621aa1--- /dev/null+++ b/src/experiment_pool.zig@@ -0,0 +1,155 @@+//! #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`.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const process_runner = @import("process_runner.zig");+const runCapped = process_runner.runCapped;+const ranOk = process_runner.ranOk;++pub const cap: u8 = 16;++const Slot = struct { path: []const u8, branch: []const u8 };++var g_n: u8 = 0;+var g_next: u8 = 0;+var g_id: []const u8 = "";+var g_slots: [cap]Slot = @splat(.{ .path = "", .branch = "" });++pub fn enabled() bool {+ return g_n > 0;+}++pub fn size() u8 {+ return g_n;+}++pub fn remaining() u8 {+ if (g_next >= g_n) return 0;+ return g_n - g_next;+}++pub fn reset() void {+ g_n = 0;+ g_next = 0;+ g_id = "";+ g_slots = @splat(.{ .path = "", .branch = "" });+}++pub fn sanitizeId(buf: []u8, id: []const u8) []const u8 {+ const n = @min(id.len, buf.len);+ for (id[0..n], 0..) |c, i| {+ buf[i] = if (c == '/' or c == '\\' or c == ' ') '-' else c;+ }+ return buf[0..n];+}++pub fn slotPath(buf: []u8, id: []const u8, i: u8) []const u8 {+ return std.fmt.bufPrint(buf, ".graff/worktrees/exp-{s}/{d}", .{ id, i }) catch buf[0..0];+}++pub fn slotBranch(buf: []u8, id: []const u8, i: u8) []const u8 {+ return std.fmt.bufPrint(buf, "graff/exp/{s}/{d}", .{ id, i }) catch buf[0..0];+}++/// Next unused seat, or null when the pool is empty/exhausted.+pub fn claim() ?[]const u8 {+ if (g_next >= g_n) return null;+ const i = g_next;+ g_next += 1;+ return g_slots[i].path;+}++pub fn statusLine(buf: []u8) []const u8 {+ if (g_n == 0) return "experiment pool off";+ return std.fmt.bufPrint(buf, "experiment {s}: {d}/{d} seats left", .{ g_id, remaining(), g_n }) catch "experiment pool";+}++fn dirExists(io: Io, path: []const u8) bool {+ return (Io.Dir.cwd().statFile(io, path, .{}) catch null) != null;+}++fn absOrRel(io: Io, arena: Allocator, path: []const u8) ![]const u8 {+ var buf: [4096]u8 = undefined;+ const n = Io.Dir.cwd().realPathFile(io, path, &buf) catch return arena.dupe(u8, path);+ return arena.dupe(u8, buf[0..n]);+}++fn mintOne(gpa: Allocator, io: Io, arena: Allocator, id: []const u8, i: u8) !Slot {+ 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 (!ranOk(add) and !dirExists(io, rel)) return error.CreateFailed;+ return .{ .path = try absOrRel(io, arena, rel), .branch = branch };+}++/// Create or reuse N trees under `.graff/worktrees/exp-{id}/`. Idempotent+/// on an already-armed pool of the same size.+pub fn arm(gpa: Allocator, io: Io, arena: Allocator, id: []const u8, n: u8) !u8 {+ if (n == 0 or n > cap) return error.BadPoolSize;+ 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;++ reset();+ var idbuf: [64]u8 = undefined;+ g_id = try arena.dupe(u8, sanitizeId(&idbuf, id));+ var i: u8 = 0;+ while (i < n) : (i += 1) {+ g_slots[i] = try mintOne(gpa, io, arena, g_id, i);+ }+ g_n = n;+ g_next = 0;+ return n;+}++test "slot names are stable and claim walks the pool" {+ var pbuf: [64]u8 = undefined;+ var bbuf: [64]u8 = undefined;+ try std.testing.expectEqualStrings(".graff/worktrees/exp-live/0", slotPath(&pbuf, "live", 0));+ try std.testing.expectEqualStrings("graff/exp/live/2", slotBranch(&bbuf, "live", 2));+ var sbuf: [16]u8 = undefined;+ try std.testing.expectEqualStrings("a-b", sanitizeId(&sbuf, "a/b"));++ reset();+ g_id = "live";+ g_n = 2;+ g_slots[0] = .{ .path = "a", .branch = "ba" };+ g_slots[1] = .{ .path = "b", .branch = "bb" };+ try std.testing.expectEqualStrings("a", claim().?);+ try std.testing.expectEqual(@as(u8, 1), remaining());+ try std.testing.expectEqualStrings("b", claim().?);+ try std.testing.expect(claim() == null);+ try std.testing.expectEqual(@as(u8, 0), remaining());+}++test "statusLine names the id and remaining seats" {+ reset();+ var buf: [80]u8 = undefined;+ try std.testing.expectEqualStrings("experiment pool off", statusLine(&buf));+ g_id = "q";+ g_n = 3;+ g_next = 1;+ try std.testing.expectEqualStrings("experiment q: 2/3 seats left", statusLine(&buf));+}++test "arm rejects empty and oversized pools before git" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ 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));+}diff --git a/src/help.zig b/src/help.zigindex 7dce5330..af61f8f7 100644--- a/src/help.zig+++ b/src/help.zig@@ -28,7 +28,7 @@ const peers_blurb =;pub const sections = [_]Section{- .{ .title = "getting around", .names = &.{ "/new", "/clear", "/resume", "/save", "/sessions", "/workspace", "/rename", "/rewind", "/snapshot" } },+ .{ .title = "getting around", .names = &.{ "/new", "/clear", "/resume", "/save", "/sessions", "/workspace", "/experiment", "/rename", "/rewind", "/snapshot" } },.{ .title = "the model", .names = &.{ "/model", "/models", "/effort", "/reasoning", "/fast", "/thinking", "/keepcontext", "/fallback", "/routes" } },.{ .title = "working autonomously", .names = &.{ "/goal", "/loop", "/review", "/plan", "/todo", "/jobs", "/ultracode", "/strict", "/yolo", "/never" } },.{ .title = "talking to other graffs", .names = &.{ "/tell", "/peek" }, .blurb = peers_blurb },diff --git a/src/session_start.zig b/src/session_start.zigindex b4354a3d..ed194136 100644--- a/src/session_start.zig+++ b/src/session_start.zig@@ -150,6 +150,15 @@ pub fn setupWorktreeAndBanner(// model an ABSOLUTE path. Left unwired in tests, where the cap stays the// pre-#409 plain truncation.tool_spill.enable(.{ .io = io, .dir = .cwd(), .base_abs = main_mod.g_cwd_display });+ if (flags.experiment_n > 0) {+ const exp_id = flags.resume_flag orelse "live";+ const n = @import("experiment_pool.zig").arm(gpa, io, arena, exp_id, flags.experiment_n) catch |err|+ std.process.fatal("--experiment: {t}", .{err});+ if (!main_mod.json_mode) sink.emit(io, .{ .session_notice = .{+ .text = try std.fmt.allocPrint(arena, "experiment {s}: {d} trees — spawn into them, do not edit the caller tree", .{ exp_id, n }),+ .tone = .dim,+ } });+ }// The pager owns the screen. Dumping the line-REPL banner first makes// `graff tui --yolo` look like bare `graff` never left.diff --git a/src/subagent_run.zig b/src/subagent_run.zigindex 49e7b6c2..1850df6b 100644--- a/src/subagent_run.zig+++ b/src/subagent_run.zig@@ -319,7 +319,9 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []constvar wt: ?jobs.AgentWorktree = null;var isolation_note: []const u8 = "";- if (isolation == .worktree) {+ if (@import("experiment_pool.zig").claim()) |seat| {+ agent.agent_cwd = seat;+ } else if (isolation == .worktree) {if (jobs.agentWorktreeCreate(gpa, ctx.io, arena, sub_id)) |created| {wt = created;} else |err| {@@ -329,8 +331,10 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const};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;+ } else {+ agent.agent_cwd = null;}- agent.agent_cwd = if (wt) |w| w.path else null;const wf_task = std.mem.eql(u8, kind, "workflow_task");if (wf_task) guiEmit(ctx.io, .{ .type = "tool_call", .name = "subagent", .input = .{ .description = label }, .id = sub_id });diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex a0f03d98..23437453 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -330,4 +330,6 @@ test {_ = tool_surface;_ = agent_catalog;_ = session_connect_tests;+ _ = @import("experiment_pool.zig");+ _ = @import("commands_experiment.zig");}