graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Default fan-out agents onto their own Git worktrees
Cursor Agent8b85cb9d3bfe
diff --git a/assets/skills/workspace.md b/assets/skills/workspace.mdindex bf145b6e..c3fc72c0 100644--- a/assets/skills/workspace.md+++ b/assets/skills/workspace.md@@ -23,8 +23,10 @@ A new independent task is `workspace action=create`.2. `workspace action=use path=<folder or unique fragment>` — chdir thissession. Example: `path=cursor-peer-pull-554f` matches a Claude worktreenamed that, or `path=cursor/peer-pull-554f` matches the branch.-3. `workspace action=create name=<slug>` — mint a fresh branch and worktree,- then enter it. Optional `base` is a branch or commit (default HEAD).+3. `workspace action=create name=<slug>` — mint a fresh branch and worktree+ from the remote base, then enter it. Optional `base` is a branch or commit+ (default `origin/main` after fetch). Independent work gets its own tree;+ same-branch collaboration stays in one workspace (`isolation: shared_cwd`).4. If the match is ambiguous, name more of the path. Do not guess.Do not paste every worktree path into the next user turn. The list result isdiff --git a/docs/adr/0146-concurrent-sessions-auto-isolate.md b/docs/adr/0146-concurrent-sessions-auto-isolate.mdindex 34b42149..2b489c7a 100644--- a/docs/adr/0146-concurrent-sessions-auto-isolate.md+++ b/docs/adr/0146-concurrent-sessions-auto-isolate.md@@ -9,22 +9,32 @@ share `.git/index`. Parallel `git add` / `commit` / `status` then fail on`index.lock`. `-w` already isolated a session, but only when the user asked.Presence warned and gated; it did not move the second session.-Task workspaces are one branch and one checkout (#1119). Agents that share a-branch stay in one workspace; independent work gets a new tree. Finish is not-archive (#1124).+Task workspaces are one branch and one checkout. Independent / fan-out work+must not share a tree; same-branch collaboration stays in one workspace.+Finish is not archive.## Decision+- One workspace ↔ one branch ↔ one Git worktree. Trees share the object DB+ (`git worktree add`); they are never a second clone.- If another live session already owns this Git checkout, the new sessionmints `.graff/worktrees/<slug>` on `worktree-<slug>` and enters it. Sharedobject DB and the one claim ledger per common dir stay as they are.- `-w`, lean/`-p` oneshots (ADR 0024), and non-git folders do not auto-isolate.-- `workspace` `create` and `graff worktree create` are the explicit mint.+- `workspace` `create` and `graff worktree create` mint from the remote base+ (`origin/HEAD` / `origin/main` after fetch; an explicit `base` wins).+- Independent / fan-out children default to `isolation: worktree` and bind+ tools to `agent_cwd` (no process-wide chdir). `shared_cwd` is only for+ same-branch collaboration (review + fix, pipeline stages, an explicit field).+- `git worktree add` failure is an isolation failure unless+ `isolation_fallback` / `GRAFF_ISOLATION_FALLBACK=1`.+- Finish / `graff worktree archive` keep dirty or unique-commit trees. Archive+ removes only a clean checkout whose commits exist elsewhere.- `session/new` reports the checkout `cwd` so GUI chats bind to that tree.-- Isolation is opt-in (`isolation: worktree`) for dependent child stages.## ConsequencesThe second concurrent agent never contends on the first agent's `index.lock`.-A first session still owns the folder it started in. Archive, merge-back, and-setup scripts stay #1124 / #1123.+A first session still owns the folder it started in. Experiment-pool pre-mint+(ADR 0037) still skips mid-turn `worktree add` when seats are reserved.+Setup scripts stay #1123. Stale-tree reaping stays #1118.diff --git a/src/cli.zig b/src/cli.zigindex 9f762182..a54a2063 100644--- a/src/cli.zig+++ b/src/cli.zig@@ -333,7 +333,8 @@ pub const usage_text =\\ 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 -w tabs and experiment-pool trees (tagged)- \\ graff worktree create <name> [base] mint a task workspace (branch + worktree) so concurrent agents do not share a checkout+ \\ graff worktree create <name> [base] mint a task workspace from the remote base (origin/main after fetch; optional base)+ \\ graff worktree archive <name> remove a clean duplicate checkout; dirty or unique-commit trees stay\\ 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 deleteddiff --git a/src/fleet.zig b/src/fleet.zigindex 50c63672..bf9b0598 100644--- a/src/fleet.zig+++ b/src/fleet.zig@@ -32,12 +32,10 @@ const agent_file = @import("agent_file.zig");/// elite prompt; builtins ship compiled in, and `.harness/agents/<name>.md`/// or `.toml` files override or extend them — that's where an evolution driver/// promotes archive winners (still as `.md`). Spawn with `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.+/// #276 P0-1: per-agent git-worktree isolation. Independent / fan-out+/// children default to `.worktree` (own branch + checkout, `agent_cwd`, no+/// process-wide chdir). `.shared_cwd` is same-branch collaboration only+/// (review + fix, pipeline stages, an explicit isolation field).pub const Isolation = enum {shared_cwd,worktree,@@ -61,7 +59,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+ isolation: ?Isolation = null, // persona default; null = no opinion, falls through to the caller default (worktree for fan-out)// #292 persona model pin. Both null = no opinion; the spawn keeps the// session default (--subagent-model or the #291 ladder). `model` is an// exact name and wins over `tier` when a persona sets both; neither is@@ -82,12 +80,14 @@ const builtin_agent_types = [_]AgentType{.desc = "adversarial code reviewer — hunts defects, assumes guilt",.prompt = "You are an adversarial code reviewer. Read the code you are pointed at and hunt for genuine defects: logic errors, unhandled edge cases, races, leaks, security holes. Assume the code is guilty until proven correct. Report only findings you can defend with a concrete failure scenario, each with file:line and the exact sequence that breaks. No style nits. End with a verdict: the single most dangerous defect, or 'no defensible defects found'.",.builtin = true,+ .isolation = .shared_cwd, // same-branch review},.{.name = "researcher",.desc = "evidence gatherer — reads widely, cites precisely, never edits",.prompt = "You are a research agent. Your job is to READ and REPORT, never to modify anything. Explore the files or sources you are pointed at, follow the references that matter, and produce a tight evidence-backed summary: every claim cites its file:line or source. Separate what you verified from what you infer. End with the 3 facts most load-bearing for the task and 1 open question.",.builtin = true,+ .isolation = .shared_cwd,.tier = .small, // luna / flash / sonnet — cheap search seat, same as sol+luna},.{@@ -101,6 +101,7 @@ const builtin_agent_types = [_]AgentType{.desc = "claim refuter — tries to prove the premise wrong",.prompt = "You are a skeptic. You receive a claim or finding; your only goal is to REFUTE it. Search for counterexamples, missing context, and alternative explanations. Default to 'refuted' unless the claim survives your strongest attack. Report the attack you ran, what you found, and a final verdict: refuted (with the counterexample) or survives (with what would have broken it).",.builtin = true,+ .isolation = .shared_cwd,},};@@ -425,18 +426,20 @@ 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 {+/// Effective isolation for a subagent / workflow-task input.+/// Precedence: explicit `isolation` wins; else a named persona's default;+/// else `default` (fan-out uses `.worktree`; pipeline stages pass `.shared_cwd`).+/// An unrecognized `isolation` string is treated as omitted.+pub fn resolveIsolationWithDefault(obj: std.json.ObjectMap, default: Isolation) 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;+ if (std.mem.eql(u8, t.name, v.string)) return t.isolation orelse default;};- return .shared_cwd;+ return default;+}++pub fn resolveIsolation(obj: std.json.ObjectMap) Isolation {+ return resolveIsolationWithDefault(obj, .worktree);}/// #276 design point 4: worktree creation failure fails the spawn unless the@@ -458,7 +461,7 @@ test "builtin researcher is the small search seat (luna on Codex)" {try std.testing.expect(false);}-test "resolveIsolation: explicit field wins, then the named persona's default, then shared_cwd" {+test "resolveIsolation: fan-out defaults to worktree; pipeline default stays shared_cwd" {_ = agent_file;var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();@@ -477,16 +480,14 @@ test "resolveIsolation: explicit field wins, then the named persona's default, t.{ .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, "{\"description\":\"x\",\"prompt\":\"y\"}")));+ try std.testing.expectEqual(Isolation.shared_cwd, resolveIsolationWithDefault(obj(a, "{\"description\":\"x\",\"prompt\":\"y\"}"), .shared_cwd));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.worktree, resolveIsolation(obj(a, "{\"agent\":\"reviewer\"}")));+ try std.testing.expectEqual(Isolation.shared_cwd, resolveIsolationWithDefault(obj(a, "{\"agent\":\"reviewer\"}"), .shared_cwd));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\"}")));}diff --git a/src/schema_agents.zig b/src/schema_agents.zigindex 398b2034..169d44bf 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: independent / fan-out children default to \"worktree\" (own branch + checkout; auto-removed if clean with no unique commits, kept + reported otherwise). Use \"shared_cwd\" only for same-branch collaboration (review + fix, a pipeline). isolation_fallback:true is the only way a failed git worktree add may share the caller tree."}, "isolation_fallback": {"type": "boolean", "description": "Optional: if isolation:\"worktree\" fails to set up (not a git repo, git error), run in the shared working tree instead of failing the spawn. Default false (fails the spawn on setup failure)."}, "run_in_background": {"type": "boolean", "description": "Optional: start this subagent asynchronously and return its agent id immediately instead of waiting for it to finish (headless default false; interactive REPL always backgrounds direct subagents). Do not poll; headless agent_output(wait_ms>0) blocks until it finishes. A spawn beyond the concurrency cap is queued, never failed."}}, "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: fan-out tasks default to \"worktree\" (own branch + checkout). Use \"shared_cwd\" only when this task must share the same branch and files. isolation_fallback:true is the only way a failed git worktree add may share the caller tree."}, "isolation_fallback": {"type": "boolean", "description": "Optional: if isolation:\"worktree\" fails to set up, 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: pipeline stages default to \"shared_cwd\" so later stages see earlier edits. Stage 0 may set \"worktree\". isolation_fallback:true is the only way a failed git worktree add may share the caller tree."}, "isolation_fallback": {"type": "boolean", "description": "Optional: if isolation:\"worktree\" fails to set up, 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/session_start.zig b/src/session_start.zigindex 2f103051..5a31bf57 100644--- a/src/session_start.zig+++ b/src/session_start.zig@@ -44,7 +44,6 @@ const mcp_config = @import("mcp_config.zig");const plugin_scan = @import("plugin_scan.zig");const adopt = @import("adopt.zig");const mcp_schema_gate = @import("mcp_schema_gate.zig"); // #416: the eager-vs-deferred policy for MCP tool schemas-const jobs = @import("jobs.zig");const tool_spill = @import("tool_spill.zig"); // #409: where an over-cap tool output's full bytes goconst trace = @import("trace.zig");const scoring = @import("scoring.zig");@@ -119,7 +118,8 @@ pub fn setupWorktreeAndBanner(}// --worktree/-w: run this session in an isolated git worktree so parallel// agents don't collide on files. Creates .graff/worktrees/<name> on branch- // worktree-<name> (from HEAD) and enters it; reuses it if it already exists.+ // worktree-<name> from the remote base and enters it; reuses it if it exists.+ const task_workspace = @import("task_workspace.zig");if (flags.worktree_flag) |wt| {// POSIX-only: the chdir below goes through libc's `chdir`, which Windows// builds don't link. -w is a parallel-agent dev workflow (mac/linux); on@@ -128,31 +128,35 @@ pub fn setupWorktreeAndBanner(if (builtin.os.tag == .windows) {std.process.fatal("--worktree is not yet supported on Windows (POSIX-only chdir) — run without -w", .{});} else {- const wt_path = try std.fmt.allocPrint(arena, ".graff/worktrees/{s}", .{wt});- const wt_branch = try std.fmt.allocPrint(arena, "worktree-{s}", .{wt});- if (jobs.runCapped(gpa, io, &.{ "git", "worktree", "add", wt_path, "-b", wt_branch }, 8192, 8192, 60_000)) |r| {- gpa.free(r.stdout);- gpa.free(r.stderr);- } else |_| {}- const wt_z = arena.dupeSentinel(u8, wt_path, 0) catch std.process.fatal("--worktree: out of memory", .{});- if (std.posix.system.chdir(wt_z.ptr) != 0)- std.process.fatal("--worktree '{s}': could not enter {s} (is this a git repository?)", .{ wt, wt_path });- main_mod.g_worktree_branch = wt_branch; // non-null = auto-commit each turn to this scratch branch+ const created = task_workspace.ensure(gpa, io, arena, .{ .slug = wt }) catch |err|+ std.process.fatal("--worktree '{s}': {s}", .{ wt, task_workspace.createFailureText(err) });+ task_workspace.enter(gpa, io, arena, created) catch+ std.process.fatal("--worktree '{s}': could not enter {s} (is this a git repository?)", .{ wt, created.path });if (!main_mod.json_mode) sink.emit(io, .{ .worktree_entered = .{- .path = wt_path,- .branch = wt_branch,+ .path = created.path,+ .branch = created.branch,.autocommit = main_mod.g_worktree_autocommit,} });}}- const isolated = if (flags.worktree_flag == null) @import("task_workspace.zig").maybeAutoIsolate(- gpa,- io,- arena,- environ_map.get("HOME") orelse "",- false,- flags.effectiveLean(),- ) else null;+ var isolated: ?task_workspace.Workspace = null;+ if (flags.worktree_flag == null) {+ switch (task_workspace.maybeAutoIsolate(+ gpa,+ io,+ arena,+ environ_map.get("HOME") orelse "",+ false,+ flags.effectiveLean(),+ )) {+ .skip => {},+ .isolated => |wt| isolated = wt,+ .failed => |err| {+ if (!task_workspace.envIsolationFallback(environ_map.get("GRAFF_ISOLATION_FALLBACK")))+ std.process.fatal("concurrent session isolation failed: {s}", .{task_workspace.createFailureText(err)});+ },+ }+ }if (isolated) |wt| {if (!main_mod.json_mode) sink.emit(io, .{ .worktree_entered = .{.path = wt.path,diff --git a/src/shapes.zig b/src/shapes.zigindex 7fb45556..306e358a 100644--- a/src/shapes.zig+++ b/src/shapes.zig@@ -148,12 +148,11 @@ pub const shape_catalog_note =\\Use phases only when a phase genuinely needs ALL of the previous one;\\per-item work belongs in pipeline.\\- \\isolation:"worktree" ONLY for tasks that edit files IN PARALLEL within one- \\phase and whose edits nothing downstream has to read. Every task gets its- \\OWN worktree branched from HEAD, so a later stage cannot see an earlier- \\stage's edits. Never set it on a dependent chain (transform then verify,- \\implement then review) — those stages must share the working tree or the- \\reviewer inspects the original file and the edits are stranded.+ \\Independent / fan-out tasks default to isolation:"worktree" (own branch ++ \\checkout, tools bound to agent_cwd, no process-wide chdir). Use+ \\isolation:"shared_cwd" only for same-branch collaboration — review + fix,+ \\pipeline stages, agents that must see each other's uncommitted files.+ \\A failed git worktree add fails the spawn unless isolation_fallback:true.;test "canonicalSlot: exact, first-word, and miss" {diff --git a/src/task_workspace.zig b/src/task_workspace.zigindex 2a00769e..51d9ea10 100644--- a/src/task_workspace.zig+++ b/src/task_workspace.zig@@ -15,8 +15,24 @@ const proc_identity = @import("proc_identity.zig");const main_mod = @import("main.zig");const tool_spill = @import("tool_spill.zig");const claim_path = @import("artifact_claim_path.zig");+const agent_worktree = @import("agent_worktree.zig");+const worktree_prune = @import("worktree_prune.zig");pub const CreateError = error{ NotAGitRepo, InvalidName, NameCollision, CreateFailed, Unsupported };+pub const ArchiveError = error{ InvalidName, NotFound, ArchiveFailed };++pub const AutoIsolate = union(enum) {+ skip,+ isolated: Workspace,+ failed: anyerror,+};++pub const ArchiveResult = struct {+ removed: bool,+ reason: agent_worktree.KeepReason,+ path: []const u8,+ branch: []const u8,+};pub const CreateOpts = struct {slug: []const u8,@@ -113,6 +129,56 @@ fn refExists(gpa: Allocator, io: Io, cwd: []const u8, branch: []const u8) bool {return ranOk(r);}+fn revExists(gpa: Allocator, io: Io, cwd: []const u8, rev: []const u8) bool {+ const r = runCapped(gpa, io, &.{ "git", "-C", cwd, "rev-parse", "--verify", "--quiet", rev }, 4096, 4096, 15_000) catch return false;+ defer {+ gpa.free(r.stdout);+ gpa.free(r.stderr);+ }+ return ranOk(r);+}++fn remoteHead(gpa: Allocator, io: Io, arena: Allocator, cwd: []const u8) []const u8 {+ const r = runCapped(gpa, io, &.{ "git", "-C", cwd, "symbolic-ref", "--quiet", "refs/remotes/origin/HEAD" }, 4096, 4096, 15_000) catch return "";+ defer {+ gpa.free(r.stdout);+ gpa.free(r.stderr);+ }+ if (!ranOk(r)) return "";+ const ref = std.mem.trim(u8, r.stdout, " \t\r\n");+ const prefix = "refs/remotes/";+ const short = if (std.mem.startsWith(u8, ref, prefix)) ref[prefix.len..] else ref;+ return arena.dupe(u8, short) catch "";+}++/// Conductor create: an explicit base wins; else origin/HEAD, origin/main, origin/master; else local HEAD.+pub fn preferRemoteBase(requested: []const u8, origin_head: []const u8, has_origin_main: bool, has_origin_master: bool) []const u8 {+ if (requested.len > 0) return requested;+ if (origin_head.len > 0) return origin_head;+ if (has_origin_main) return "origin/main";+ if (has_origin_master) return "origin/master";+ return "";+}++pub fn resolveCreateBase(gpa: Allocator, io: Io, arena: Allocator, cwd: []const u8, requested: []const u8) []const u8 {+ if (requested.len > 0) return requested;+ if (runCapped(gpa, io, &.{ "git", "-C", cwd, "fetch", "--quiet", "origin" }, 4096, 4096, 60_000)) |r| {+ gpa.free(r.stdout);+ gpa.free(r.stderr);+ } else |_| {}+ return preferRemoteBase(+ requested,+ remoteHead(gpa, io, arena, cwd),+ revExists(gpa, io, cwd, "origin/main"),+ revExists(gpa, io, cwd, "origin/master"),+ );+}++pub fn envIsolationFallback(val: ?[]const u8) bool {+ const v = val orelse return false;+ return std.mem.eql(u8, v, "1") or std.mem.eql(u8, v, "true") or std.mem.eql(u8, v, "yes");+}+fn absPath(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);@@ -159,7 +225,8 @@ pub fn create(gpa: Allocator, io: Io, arena: Allocator, opts: CreateOpts) (Creatdest = try joinCwd(arena, opts.cwd, named.path);if (dirExists(io, dest) or refExists(gpa, io, opts.cwd, named.branch)) return error.NameCollision;}- try mintOnce(gpa, io, arena, opts.cwd, named.path, named.branch, opts.base);+ const base = resolveCreateBase(gpa, io, arena, opts.cwd, opts.base);+ try mintOnce(gpa, io, arena, opts.cwd, named.path, named.branch, base);const path = try absPath(io, arena, dest);return .{.name = named.name,@@ -169,6 +236,59 @@ pub fn create(gpa: Allocator, io: Io, arena: Allocator, opts: CreateOpts) (Creat};}+/// Reuse an existing checkout, or mint one. `-w` tabs come through here.+pub fn ensure(gpa: Allocator, io: Io, arena: Allocator, opts: CreateOpts) (CreateError || Allocator.Error)!Workspace {+ if (!isGitAt(gpa, io, opts.cwd)) return error.NotAGitRepo;+ const named = try names(arena, opts.slug);+ const dest = try joinCwd(arena, opts.cwd, named.path);+ if (dirExists(io, dest)) {+ const path = try absPath(io, arena, dest);+ return .{+ .name = named.name,+ .path = path,+ .branch = named.branch,+ .base = readHead(gpa, io, arena, path),+ };+ }+ return create(gpa, io, arena, opts);+}++/// Archive removes a clean tree whose commits exist elsewhere. Dirty or unique-commit trees stay.+pub fn archive(gpa: Allocator, io: Io, arena: Allocator, cwd: []const u8, slug: []const u8) (ArchiveError || Allocator.Error)!ArchiveResult {+ const named = try names(arena, slug);+ const dest = try joinCwd(arena, cwd, named.path);+ if (!dirExists(io, dest)) return error.NotFound;+ const path = try absPath(io, arena, dest);+ const kept = ArchiveResult{ .removed = false, .reason = .unverifiable, .path = path, .branch = named.branch };+ const st = runCapped(gpa, io, &.{ "git", "-C", dest, "status", "--porcelain" }, 1 << 16, 8192, 30_000) catch return kept;+ defer {+ gpa.free(st.stdout);+ gpa.free(st.stderr);+ }+ const head = readHead(gpa, io, arena, dest);+ const own = try std.fmt.allocPrint(arena, "refs/heads/{s}", .{named.branch});+ const refs = runCapped(gpa, io, &.{ "git", "-C", cwd, "branch", "--all", "--contains", head, "--format=%(refname)" }, 1 << 16, 8192, 30_000) catch return kept;+ defer {+ gpa.free(refs.stdout);+ gpa.free(refs.stderr);+ }+ const contained = ranOk(refs) and worktree_prune.containedElsewhere(refs.stdout, own);+ const reason = agent_worktree.worktreeKeepReason(ranOk(st), st.stdout, worktree_prune.containmentBase(head, contained), head);+ if (reason != .removed) return .{ .removed = false, .reason = reason, .path = path, .branch = named.branch };+ if (runCapped(gpa, io, &.{ "git", "-C", cwd, "worktree", "remove", dest }, 8192, 8192, 30_000)) |r| {+ defer {+ gpa.free(r.stdout);+ gpa.free(r.stderr);+ }+ if (!ranOk(r)) return error.ArchiveFailed;+ } else |_| return error.ArchiveFailed;+ if (runCapped(gpa, io, &.{ "git", "-C", cwd, "branch", "-D", named.branch }, 8192, 8192, 30_000)) |r| {+ gpa.free(r.stdout);+ gpa.free(r.stderr);+ } else |_| {}+ return .{ .removed = true, .reason = .removed, .path = path, .branch = named.branch };+}+/// Live foreign owner of THIS checkout, if any. Read-only: does not announce.pub fn checkoutClaimed(gpa: Allocator, io: Io, arena: Allocator, home: []const u8) bool {if (home.len == 0) return false;@@ -194,8 +314,9 @@ pub fn enter(gpa: Allocator, io: Io, arena: Allocator, wt: Workspace) !void {}/// Session-start hook: if another live session owns this checkout, mint and enter a tree.-pub fn maybeAutoIsolate(gpa: Allocator, io: Io, arena: Allocator, home: []const u8, already_isolated: bool, lean: bool) ?Workspace {- if (builtin.os.tag == .windows) return null;+/// A failed `git worktree add` is an isolation failure — do not stay on the claimed tree.+pub fn maybeAutoIsolate(gpa: Allocator, io: Io, arena: Allocator, home: []const u8, already_isolated: bool, lean: bool) AutoIsolate {+ if (builtin.os.tag == .windows) return .skip;const is_git = isGitAt(gpa, io, ".");const claimed = checkoutClaimed(gpa, io, arena, home);if (!shouldAutoIsolate(.{@@ -204,14 +325,14 @@ pub fn maybeAutoIsolate(gpa: Allocator, io: Io, arena: Allocator, home: []const.is_git = is_git,.claimed = claimed,.windows = false,- })) return null;+ })) return .skip;var raw: [4]u8 = undefined;io.random(&raw);const nonce = std.fmt.bytesToHex(raw, .lower);- const slug = autoSlug(arena, proc_identity.selfPid(), nonce[0..8]) catch return null;- const wt = create(gpa, io, arena, .{ .slug = slug, .unique = true }) catch return null;- enter(gpa, io, arena, wt) catch return null;- return wt;+ const slug = autoSlug(arena, proc_identity.selfPid(), nonce[0..8]) catch return .{ .failed = error.CreateFailed };+ const wt = create(gpa, io, arena, .{ .slug = slug, .unique = true }) catch |err| return .{ .failed = err };+ enter(gpa, io, arena, wt) catch |err| return .{ .failed = err };+ return .{ .isolated = wt };}pub fn createFailureText(err: anyerror) []const u8 {@@ -219,11 +340,20 @@ pub fn createFailureText(err: anyerror) []const u8 {error.NotAGitRepo => "not a git repository — a task workspace needs a git repo; a plain folder stays a plain folder",error.InvalidName => "workspace name must be 1-64 letters, digits, '.', '_' or '-' (no slashes)",error.NameCollision => "that workspace name is already a worktree or branch — pick another name",- error.CreateFailed => "git worktree add failed (dirty HEAD, a name collision, or a git error)",+ error.CreateFailed => "git worktree add failed (dirty HEAD, a name collision, or a git error) — isolation failed; set GRAFF_ISOLATION_FALLBACK=1 only to stay on the shared checkout",else => "could not create a task workspace",};}+pub fn archiveFailureText(err: anyerror) []const u8 {+ return switch (err) {+ error.InvalidName => createFailureText(error.InvalidName),+ error.NotFound => "no such task workspace — `graff worktree list` to see them",+ error.ArchiveFailed => "git worktree remove failed — the checkout was kept",+ else => "could not archive the task workspace",+ };+}+test "shouldAutoIsolate: only a claimed interactive git checkout isolates" {try std.testing.expect(!shouldAutoIsolate(.{ .claimed = true, .is_git = true, .already_isolated = true }));try std.testing.expect(!shouldAutoIsolate(.{ .claimed = true, .is_git = true, .lean = true }));@@ -321,6 +451,128 @@ test "create: non-git folder is not a task workspace" {try std.testing.expect(std.mem.indexOf(u8, createFailureText(error.NotAGitRepo), "plain folder") != null);}+test "preferRemoteBase: explicit wins, then origin, then empty (local HEAD)" {+ try std.testing.expectEqualStrings("feature", preferRemoteBase("feature", "origin/main", true, true));+ try std.testing.expectEqualStrings("origin/develop", preferRemoteBase("", "origin/develop", true, true));+ try std.testing.expectEqualStrings("origin/main", preferRemoteBase("", "", true, true));+ try std.testing.expectEqualStrings("origin/master", preferRemoteBase("", "", false, true));+ try std.testing.expectEqualStrings("", preferRemoteBase("", "", false, false));+ try std.testing.expect(envIsolationFallback("1"));+ try std.testing.expect(envIsolationFallback("true"));+ try std.testing.expect(!envIsolationFallback(null));+ try std.testing.expect(!envIsolationFallback("0"));+}++test "create: worktree starts from the remote base, not a stale local HEAD" {+ if (builtin.os.tag == .windows) return error.SkipZigTest;+ const a = std.testing.allocator;+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ const tmp_root = try tmp.dir.realPathFileAlloc(io, ".", a);+ defer a.free(tmp_root);+ const remote = try std.fmt.allocPrint(a, "{s}/remote.git", .{tmp_root});+ defer a.free(remote);+ const seed = try std.fmt.allocPrint(a, "{s}/seed", .{tmp_root});+ defer a.free(seed);+ const clone = try std.fmt.allocPrint(a, "{s}/clone", .{tmp_root});+ defer a.free(clone);+ try git(io, a, &.{ "init", "-q", "-b", "main", "--bare", remote });+ try git(io, a, &.{ "clone", "-q", remote, seed });+ try git(io, a, &.{ "-C", seed, "config", "user.email", "t@t" });+ try git(io, a, &.{ "-C", seed, "config", "user.name", "t" });+ const first = try std.fs.path.join(a, &.{ seed, "f" });+ defer a.free(first);+ {+ const f = try Io.Dir.cwd().createFile(io, first, .{});+ defer f.close(io);+ try f.writePositionalAll(io, "old\n", 0);+ }+ try git(io, a, &.{ "-C", seed, "add", "f" });+ try git(io, a, &.{ "-C", seed, "commit", "-m", "old" });+ try git(io, a, &.{ "-C", seed, "push", "-q", "origin", "main" });+ try git(io, a, &.{ "clone", "-q", remote, clone });+ {+ const f = try Io.Dir.cwd().openFile(io, first, .{ .mode = .write_only });+ defer f.close(io);+ try f.writePositionalAll(io, "new\n", 0);+ }+ try git(io, a, &.{ "-C", seed, "add", "f" });+ try git(io, a, &.{ "-C", seed, "commit", "-m", "new" });+ try git(io, a, &.{ "-C", seed, "push", "-q", "origin", "main" });++ var arena = std.heap.ArenaAllocator.init(a);+ defer arena.deinit();+ const ar = arena.allocator();+ const stale = readHead(a, io, ar, clone);+ const remote_head = readHead(a, io, ar, seed);+ try std.testing.expect(!std.mem.eql(u8, stale, remote_head));+ const wt = try create(a, io, ar, .{ .slug = "from-origin", .cwd = clone });+ try std.testing.expectEqualStrings(remote_head, readHead(a, io, ar, wt.path));+ try std.testing.expectEqualStrings(remote_head, wt.base);+ const reused = try ensure(a, io, ar, .{ .slug = "from-origin", .cwd = clone });+ try std.testing.expectEqualStrings(wt.path, reused.path);+}++test "archive: keeps dirty and unique-commit trees, removes a clean duplicate" {+ if (builtin.os.tag == .windows) return error.SkipZigTest;+ const a = std.testing.allocator;+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ const tmp_root = try tmp.dir.realPathFileAlloc(io, ".", a);+ defer a.free(tmp_root);+ const root = try std.fmt.allocPrint(a, "{s}/repo", .{tmp_root});+ defer a.free(root);+ try Io.Dir.cwd().createDirPath(io, root);+ try git(io, a, &.{ "init", "-q", "-b", "main", root });+ try git(io, a, &.{ "-C", root, "config", "user.email", "t@t" });+ try git(io, a, &.{ "-C", root, "config", "user.name", "t" });+ const tracked = try std.fs.path.join(a, &.{ root, "f" });+ defer a.free(tracked);+ {+ const f = try Io.Dir.cwd().createFile(io, tracked, .{});+ defer f.close(io);+ try f.writePositionalAll(io, "x\n", 0);+ }+ try git(io, a, &.{ "-C", root, "add", "f" });+ try git(io, a, &.{ "-C", root, "commit", "-m", "i" });++ var arena = std.heap.ArenaAllocator.init(a);+ defer arena.deinit();+ const ar = arena.allocator();+ const dirty = try create(a, io, ar, .{ .slug = "dirty", .cwd = root });+ const extra = try std.fs.path.join(a, &.{ dirty.path, "extra" });+ defer a.free(extra);+ {+ const f = try Io.Dir.cwd().createFile(io, extra, .{});+ defer f.close(io);+ try f.writePositionalAll(io, "y\n", 0);+ }+ const kept_dirty = try archive(a, io, ar, root, "dirty");+ try std.testing.expect(!kept_dirty.removed);+ try std.testing.expectEqual(agent_worktree.KeepReason.dirty, kept_dirty.reason);++ const unique = try create(a, io, ar, .{ .slug = "unique", .cwd = root });+ const extra2 = try std.fs.path.join(a, &.{ unique.path, "g" });+ defer a.free(extra2);+ {+ const f = try Io.Dir.cwd().createFile(io, extra2, .{});+ defer f.close(io);+ try f.writePositionalAll(io, "z\n", 0);+ }+ try git(io, a, &.{ "-C", unique.path, "add", "g" });+ try git(io, a, &.{ "-C", unique.path, "commit", "-m", "only-here" });+ const kept_unique = try archive(a, io, ar, root, "unique");+ try std.testing.expect(!kept_unique.removed);+ try std.testing.expectEqual(agent_worktree.KeepReason.committed, kept_unique.reason);++ _ = try create(a, io, ar, .{ .slug = "clean", .cwd = root });+ const dropped = try archive(a, io, ar, root, "clean");+ try std.testing.expect(dropped.removed);+ try std.testing.expectEqual(agent_worktree.KeepReason.removed, dropped.reason);+}+fn git(io: Io, a: Allocator, argv: []const []const u8) !void {var args: std.ArrayList([]const u8) = .empty;defer args.deinit(a);diff --git a/src/workflow_pipeline.zig b/src/workflow_pipeline.zigindex ccf2db13..8a497420 100644--- a/src/workflow_pipeline.zig+++ b/src/workflow_pipeline.zig@@ -237,7 +237,7 @@ pub fn run(ctx: ToolCtx, pv: Value, outer_context: []const u8) !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 = fleet.resolveIsolationWithDefault(so, .shared_cwd);// A pipeline is a dependent chain over one item: stage 2+ must see// what earlier stages did, which worktree isolation would silently// hide (#295 territory). Reject rather than run the chain wrong.diff --git a/src/workspace_switch.zig b/src/workspace_switch.zigindex 9e05744f..e3517e00 100644--- a/src/workspace_switch.zig+++ b/src/workspace_switch.zig@@ -32,7 +32,7 @@ const task_workspace = @import("task_workspace.zig");pub const tool_name = "workspace";pub const tool_desc = "List this repo's git worktrees, switch into one, or create a task workspace (fresh branch + worktree). action=list (default), use, or create. path is a worktree path, its last folder, or a unique name fragment. create needs name and optional base. File tools and bash follow the new cwd. Root session only — a subagent stays in its assigned tree. Do not bash-cd to switch.";pub const tool_schema =- \\{"type": "object", "properties": {"action": {"type": "string", "enum": ["list", "use", "create"], "description": "list (default): the repo's git worktrees. use: chdir this session into one. create: mint a fresh branch and worktree, then enter it."}, "path": {"type": "string", "description": "worktree path, last folder, or unique fragment (required for use)"}, "name": {"type": "string", "description": "task workspace name (required for create)"}, "base": {"type": "string", "description": "base branch or commit for create (default HEAD)"}}}+ \\{"type": "object", "properties": {"action": {"type": "string", "enum": ["list", "use", "create"], "description": "list (default): the repo's git worktrees. use: chdir this session into one. create: mint a fresh branch and worktree from the remote base, then enter it."}, "path": {"type": "string", "description": "worktree path, last folder, or unique fragment (required for use)"}, "name": {"type": "string", "description": "task workspace name (required for create)"}, "base": {"type": "string", "description": "base branch or commit for create (default origin/main after fetch)"}}};pub const Entry = struct {diff --git a/src/worktree_cmd.zig b/src/worktree_cmd.zigindex a956f049..16a698ee 100644--- a/src/worktree_cmd.zig+++ b/src/worktree_cmd.zig@@ -180,13 +180,31 @@ pub fn worktreeCommand(gpa: Allocator, io: Io, arena: Allocator, args: []const [return;}+ if (std.mem.eql(u8, action, "archive")) {+ if (args.len < 2) {+ try out.writeAll("usage: graff worktree archive <name>\n");+ return;+ }+ const tw = @import("task_workspace.zig");+ const result = tw.archive(gpa, io, arena, ".", args[1]) catch |err| {+ try out.print("✗ {s}\n", .{tw.archiveFailureText(err)});+ return;+ };+ if (result.removed) {+ try out.print("✓ archived {s} (removed checkout and branch {s})\n", .{ result.path, result.branch });+ } else {+ try out.print("kept {s} — {s}\n", .{ result.path, @import("agent_worktree.zig").keepReasonText(result.reason) });+ }+ return;+ }+if (std.mem.eql(u8, action, "prune")) {// Drops git's registrations for worktrees whose dirs were deleted out of// band, and with `older-than <days>` the stale DIRECTORIES too (#112).return worktree_prune.pruneCommand(gpa, io, arena, out, args[1..]);}- try out.print("unknown worktree command '{s}' — use: graff worktree list | create <name> [base] | merge <name> | remove <name> | prune [older-than <days>]\n", .{action});+ try out.print("unknown worktree command '{s}' — use: graff worktree list | create <name> [base] | archive <name> | merge <name> | remove <name> | prune [older-than <days>]\n", .{action});}test { // split-out module: unreferenced, its tests silently never run