Skip to content

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

Python

Isolate concurrent sessions onto their own Git worktrees

Cursor Agente57e42979fd4
diff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.ts
index 81085afe..ac7acebd 100644
--- a/apps/native/app/api/acp/route.ts
+++ b/apps/native/app/api/acp/route.ts
@@ -265,12 +265,14 @@ async function bootstrapNow(chat: string, opts: BootstrapOpts): Promise<Slot> {
yolo: opts.yolo ?? recovering?.yolo ?? parked?.yolo ?? defaultYolo(),
mcp: opts.mcp ?? recovering?.mcp ?? parked?.mcp ?? true,
});
- slot.sessionId = await initializeWorker(slot.transport, slot.cwd, async () => {
+ const created = await initializeWorker(slot.transport, slot.cwd, async () => {
slot.restart = true;
slot.restartReady = retireWorker(slot.child);
try { await slot.restartReady; }
finally { if (slots.get(chat) === slot) slots.delete(chat); }
}, HANDSHAKE_MS);
+ slot.sessionId = created.sessionId;
+ if (created.cwd) slot.cwd = created.cwd;
if (!slot.resume) registerSessionWriter(sessionFile(slot.cwd, slot.sessionId), slot.child, () => {
if (slots.get(chat) === slot) void killSlot(chat).catch(() => undefined);
});
diff --git a/apps/native/components/site/useHarnessSessions.ts b/apps/native/components/site/useHarnessSessions.ts
index d1b2eea3..9d47ddcb 100644
--- a/apps/native/components/site/useHarnessSessions.ts
+++ b/apps/native/components/site/useHarnessSessions.ts
@@ -97,7 +97,7 @@ export function useHarnessSessions({sessionsRef, sessionNamesRef, chatsRef, work
const cwd = chat?.cwd ?? activePathRef.current ?? undefined;
const ws = findWorkspace(workspacesRef.current, cwd);
const spawnModel = key ?? chat?.model ?? ws?.model ?? model ?? undefined;
- const { sessionId: id, commands } = await ensureSession(handleOf(chatId), {
+ const { sessionId: id, commands, cwd: checkout } = await ensureSession(handleOf(chatId), {
model: spawnModel,
reset,
resume: sessionNamesRef.current.get(chatId),
@@ -105,6 +105,11 @@ export function useHarnessSessions({sessionsRef, sessionNamesRef, chatsRef, work
yolo: ws?.yolo,
mcp: ws?.mcp,
});
+ if (checkout && checkout !== cwd) {
+ const next = chatsRef.current.map((c) => (c.id === chatId ? { ...c, cwd: checkout } : c));
+ chatsRef.current = next;
+ setChats(next);
+ }
sessionsRef.current.set(chatId, id);
bindMcpAppChat(handleOf(chatId));
setSessionIds((current) => ({ ...current, [chatId]: id }));
diff --git a/apps/native/lib/acp-bootstrap.test.ts b/apps/native/lib/acp-bootstrap.test.ts
index 1ffdd3f0..1d290177 100644
--- a/apps/native/lib/acp-bootstrap.test.ts
+++ b/apps/native/lib/acp-bootstrap.test.ts
@@ -12,7 +12,7 @@ async function worker(mode: string) {
require('node:readline').createInterface({input:process.stdin}).on('line', line => {
const req=JSON.parse(line);
if(req.method==='initialize' && mode!=='initialize') send({id:req.id,result:{}});
- if(req.method==='session/new' && mode!=='session/new') send({id:req.id,result:mode==='invalid'?{}:{sessionId:'ready'}});
+ if(req.method==='session/new' && mode!=='session/new') send({id:req.id,result:mode==='invalid'?{}:mode==='isolated'?{sessionId:'ready',cwd:'/isolated/tree'}:{sessionId:'ready'}});
});
console.log('ready');
`], { stdio: ["pipe", "pipe", "inherit"] });
@@ -38,13 +38,22 @@ for (const mode of ["initialize", "session/new", "invalid"]) {
try {
expect(await initializeWorker(fresh.transport, process.cwd(), async () => {
throw new Error('A successful handshake must not retire its child');
- }, 1000)).toBe('ready');
+ }, 1000)).toEqual({ sessionId: 'ready' });
expect(fresh.transport.usable).toBe(true);
} finally { await retireWorker(fresh.child, 50); }
});
}
+test("session/new checkout binds the worker to its isolated worktree", async () => {
+ const isolated = await worker("isolated");
+ try {
+ expect(await initializeWorker(isolated.transport, "/shared/repo", async () => {
+ throw new Error("A successful handshake must not retire its child");
+ }, 1000)).toEqual({ sessionId: "ready", cwd: "/isolated/tree" });
+ } finally { await retireWorker(isolated.child, 50); }
+});
+
test("overlapping startup and first prompt share a completed worker", async () => {
const pending = new Map<string, Promise<string>>();
let live: Awaited<ReturnType<typeof worker>> | undefined;
@@ -54,9 +63,9 @@ test("overlapping startup and first prompt share a completed worker", async () =
if (session) return session;
starts++;
live = await worker("okay");
- session = await initializeWorker(live.transport, process.cwd(), async () => {
+ session = (await initializeWorker(live.transport, process.cwd(), async () => {
await retireWorker(live!.child, 50);
- }, 1000);
+ }, 1000)).sessionId;
return session;
};
try {
diff --git a/apps/native/lib/acp-bootstrap.ts b/apps/native/lib/acp-bootstrap.ts
index 807244f2..49687ab1 100644
--- a/apps/native/lib/acp-bootstrap.ts
+++ b/apps/native/lib/acp-bootstrap.ts
@@ -4,16 +4,17 @@ import type { AcpTransport } from "./acp-transport";
* before reporting failure so a retry starts with a fresh transport. */
export async function initializeWorker(
transport: AcpTransport, cwd: string, retire: () => Promise<void>, timeoutMs: number,
-): Promise<string> {
+): Promise<{ sessionId: string; cwd?: string }> {
let phase = "initialize";
try {
await transport.request(phase, { protocolVersion: 1, clientCapabilities: { fs: {} } }, timeoutMs);
phase = "session/new";
- const created = await transport.request(phase, { cwd }, timeoutMs) as { sessionId?: unknown } | null;
+ const created = await transport.request(phase, { cwd }, timeoutMs) as { sessionId?: unknown; cwd?: unknown } | null;
if (typeof created?.sessionId !== "string" || !created.sessionId) {
throw new Error("session/new returned no sessionId");
}
- return created.sessionId;
+ const checkout = typeof created.cwd === "string" && created.cwd.trim() ? created.cwd.trim() : undefined;
+ return checkout ? { sessionId: created.sessionId, cwd: checkout } : { sessionId: created.sessionId };
} catch (cause) {
const detail = cause instanceof Error ? cause.message : String(cause);
const error = new Error(`ACP startup failed during ${phase}: ${detail}. Retry to start a new worker.`, { cause });
diff --git a/apps/native/lib/acp-client.ts b/apps/native/lib/acp-client.ts
index 1d9e7afa..c20c5d6e 100644
--- a/apps/native/lib/acp-client.ts
+++ b/apps/native/lib/acp-client.ts
@@ -95,11 +95,12 @@ export type SessionOpts = {
export async function ensureSession(
chat: ChatHandle,
opts: SessionOpts = {},
-): Promise<{ sessionId: string; commands: AcpCommand[] }> {
+): Promise<{ sessionId: string; commands: AcpCommand[]; cwd?: string }> {
const res = await rpc(chat, "bootstrap", opts);
- const body = (await res.json()) as { sessionId?: string; error?: string; commands?: AcpCommand[] };
+ const body = (await res.json()) as { sessionId?: string; error?: string; commands?: AcpCommand[]; cwd?: string };
if (!body.sessionId) throw new Error(body.error ?? "ACP session/new failed");
- return { sessionId: body.sessionId, commands: body.commands ?? [] };
+ const checkout = typeof body.cwd === "string" && body.cwd.trim() ? body.cwd.trim() : undefined;
+ return { sessionId: body.sessionId, commands: body.commands ?? [], cwd: checkout };
}
export async function* prompt(
diff --git a/assets/skills/workspace.md b/assets/skills/workspace.md
index ea0f666b..bf145b6e 100644
--- a/assets/skills/workspace.md
+++ b/assets/skills/workspace.md
@@ -13,8 +13,9 @@ for you). This skill is the playbook. Loading it does not move the cwd.
`read_file`, `edit_file`, and `write_file` resolve against the process cwd (or
a subagent's isolated `agent_cwd`). `bash` inherits that cwd too. A `cd` inside
one bash call dies with the shell — the next file tool is still in the old
-tree. `graff -w` only creates a scratch worktree at **startup**. Mid-session
-switch is `workspace action=use`.
+tree. `graff -w` isolates a session at **startup**. A second live session in the
+same checkout auto-isolates. Mid-session switch is `workspace action=use`.
+A new independent task is `workspace action=create`.
## Pull, do not dump
@@ -22,7 +23,9 @@ switch is `workspace action=use`.
2. `workspace action=use path=<folder or unique fragment>` — chdir this
session. Example: `path=cursor-peer-pull-554f` matches a Claude worktree
named that, or `path=cursor/peer-pull-554f` matches the branch.
-3. If the match is ambiguous, name more of the path. Do not guess.
+3. `workspace action=create name=<slug>` — mint a fresh branch and worktree,
+ then enter it. Optional `base` is a branch or commit (default HEAD).
+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 is
enough. Do not `git worktree list` via bash when this tool exists.
diff --git a/docs/adr/0146-concurrent-sessions-auto-isolate.md b/docs/adr/0146-concurrent-sessions-auto-isolate.md
new file mode 100644
index 00000000..34b42149
--- /dev/null
+++ b/docs/adr/0146-concurrent-sessions-auto-isolate.md
@@ -0,0 +1,30 @@
+# 0146. Concurrent sessions auto-isolate into a Git worktree
+
+Status: accepted 2026-09-20
+
+## Context
+
+Two root sessions (REPL, TUI, or `graff acp` desktop chats) in one checkout
+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).
+
+## Decision
+
+- If another live session already owns this Git checkout, the new session
+ mints `.graff/worktrees/<slug>` on `worktree-<slug>` and enters it. Shared
+ object 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.
+- `session/new` reports the checkout `cwd` so GUI chats bind to that tree.
+- Isolation is opt-in (`isolation: worktree`) for dependent child stages.
+
+## Consequences
+
+The 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.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index c44ef9ed..b0aa2e0b 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -165,6 +165,7 @@ record only when you need the evidence or the edge cases.
| [0143](0143-release-desktop-is-com-codegraff-app.md) | Packaged Codegraff.app is `com.codegraff.app`. `dev.*` identities are local rebuilds only. |
| [0144](0144-claim-asks-on-accord.md) | Claim conflicts ping the owner on Accord/JSONL; the model does not broker handoff in chat. |
| [0145](0145-live-claims-are-accord-progress.md) | Claim acquire/release/handoff replicate as replaceable Accord progress; the JSON ledger stays canonical. |
+| [0146](0146-concurrent-sessions-auto-isolate.md) | A second live session in the same Git checkout gets its own worktree; concurrent agents never share `index.lock`. |
## When to write one
diff --git a/src/acp.zig b/src/acp.zig
index 99fe52bb..8f212e27 100644
--- a/src/acp.zig
+++ b/src/acp.zig
@@ -200,6 +200,7 @@ pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_
.bind_session = liveBind,
.meter = liveMeter,
.extra = liveModels,
+ .cwd = main_mod.g_cwd_display,
};
while (true) {
const event = (inbox.wait(arena) catch break) orelse break;
diff --git a/src/acp_engine.zig b/src/acp_engine.zig
index 6448add4..48687f25 100644
--- a/src/acp_engine.zig
+++ b/src/acp_engine.zig
@@ -53,6 +53,8 @@ pub const Dispatch = struct {
meter: ?MeterFn = null,
extra: ?ExtraFn = null,
error_message: ?*const fn (ctx: *anyopaque, err: anyerror) []const u8 = null,
+ /// Isolated checkout after session start (`g_cwd_display`). Empty omits the field.
+ cwd: []const u8 = "",
};
fn respond(w: *Io.Writer, req: proto.Request, result: anytype) !void {
@@ -178,7 +180,10 @@ pub fn handleLine(d: *Dispatch, arena: Allocator, w: *Io.Writer, line: []const u
if (std.mem.eql(u8, req.method, "session/new")) {
d.created += 1;
d.session_id = try std.fmt.allocPrint(arena, "acp-{x}-{d}", .{ d.seed, d.created });
- try respond(w, req, .{ .sessionId = d.session_id.? });
+ if (d.cwd.len > 0)
+ try respond(w, req, .{ .sessionId = d.session_id.?, .cwd = d.cwd })
+ else
+ try respond(w, req, .{ .sessionId = d.session_id.? });
try proto.writeAvailableCommands(w, d.session_id.?, proto.slashCommands());
return;
}
@@ -227,6 +232,17 @@ test "in-process handleLine speaks the same initialize / new / prompt envelopes"
try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "\"stopReason\":\"end_turn\"") != null);
}
+test "session/new reports an isolated checkout when Dispatch.cwd is set" {
+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer state.deinit();
+ var buf: [2048]u8 = undefined;
+ var w: Io.Writer = .fixed(&buf);
+ var d: Dispatch = .{ .turn = echoTurn, .ctx = undefined, .seed = 0x11, .cwd = "/repo/.graff/worktrees/session-1" };
+ try handleLine(&d, state.allocator(), &w, "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"session/new\"}");
+ try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "\"sessionId\":\"acp-11-1\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "\"cwd\":\"/repo/.graff/worktrees/session-1\"") != null);
+}
+
test "authenticate names the out-of-band terminal login" {
var state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer state.deinit();
diff --git a/src/cli.zig b/src/cli.zig
index 7a43f1f1..9f762182 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -333,6 +333,7 @@ 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 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
@@ -368,7 +369,7 @@ pub const usage_text =
\\ --eval <cmd> scoring command for an eval-driven loop (the `eval` tool runs it)
\\ --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
+ \\ -w, --worktree <name> isolate this session in a git worktree (.graff/worktrees/<name>) so parallel agents don't collide on files. A second session in a claimed checkout auto-isolates.
\\ --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
diff --git a/src/main.zig b/src/main.zig
index d0995be5..42b9931a 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -596,5 +596,5 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu
_ = @import("subagent_recovery.zig");
_ = @import("acp_agent_activity.zig");
_ = @import("read_image.zig");
- _ = .{ @import("pr_local_checks.zig"), @import("mcp_names.zig"), @import("workspace_history.zig"), @import("file_worktree.zig"), @import("mcp_turn_context.zig"), @import("review_deadline.zig"), @import("issue_cmd.zig"), @import("shell_tool.zig"), @import("acp_ask.zig"), @import("side_steer.zig") };
+ _ = .{ @import("pr_local_checks.zig"), @import("mcp_names.zig"), @import("workspace_history.zig"), @import("file_worktree.zig"), @import("mcp_turn_context.zig"), @import("review_deadline.zig"), @import("issue_cmd.zig"), @import("shell_tool.zig"), @import("acp_ask.zig"), @import("side_steer.zig"), @import("task_workspace.zig") };
}
diff --git a/src/session_start.zig b/src/session_start.zig
index 1a9adb50..2f103051 100644
--- a/src/session_start.zig
+++ b/src/session_start.zig
@@ -145,10 +145,27 @@ pub fn setupWorktreeAndBanner(
} });
}
}
+ 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;
+ if (isolated) |wt| {
+ if (!main_mod.json_mode) sink.emit(io, .{ .worktree_entered = .{
+ .path = wt.path,
+ .branch = wt.branch,
+ .autocommit = main_mod.g_worktree_autocommit,
+ } });
+ }
var cwd_buf: [4096]u8 = undefined;
main_mod.g_cwd_display = if (flags.worktree_flag) |wt|
// After chdir into the worktree, realPath(AT_FDCWD) is unreliable; derive from the launch dir.
std.fmt.allocPrint(arena, "{s}/.graff/worktrees/{s}", .{ environ_map.get("PWD") orelse ".", wt }) catch try arena.dupe(u8, environ_map.get("PWD") orelse ".")
+ else if (isolated) |wt|
+ try arena.dupe(u8, wt.path)
else if (Io.Dir.cwd().realPath(io, &cwd_buf)) |n|
try arena.dupe(u8, cwd_buf[0..n])
else |_|
diff --git a/src/task_workspace.zig b/src/task_workspace.zig
new file mode 100644
index 00000000..2a00769e
--- /dev/null
+++ b/src/task_workspace.zig
@@ -0,0 +1,335 @@
+//! Task workspace = one Git worktree + one branch + one checkout.
+//! Concurrent root sessions auto-isolate so they never share `index.lock`.
+
+const std = @import("std");
+const builtin = @import("builtin");
+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;
+const lease = @import("worktree_lease.zig");
+const presence = @import("presence.zig");
+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");
+
+pub const CreateError = error{ NotAGitRepo, InvalidName, NameCollision, CreateFailed, Unsupported };
+
+pub const CreateOpts = struct {
+ slug: []const u8,
+ base: []const u8 = "",
+ cwd: []const u8 = ".",
+ unique: bool = false,
+};
+
+pub const Workspace = struct {
+ name: []const u8,
+ path: []const u8,
+ branch: []const u8,
+ base: []const u8 = "",
+};
+
+pub const AutoOpts = struct {
+ already_isolated: bool = false,
+ lean: bool = false,
+ is_git: bool = false,
+ claimed: bool = false,
+ windows: bool = false,
+};
+
+/// Concurrent interactive sessions isolate. Lean/-p oneshots stay put (ADR 0024).
+/// `-w` already isolated. Non-git folders stay plain folders. Windows has no chdir.
+pub fn shouldAutoIsolate(opts: AutoOpts) bool {
+ if (opts.windows or opts.already_isolated or opts.lean or !opts.is_git) return false;
+ return opts.claimed;
+}
+
+pub fn sanitizeSlug(s: []const u8) ?[]const u8 {
+ const t = std.mem.trim(u8, s, " \t\r\n");
+ if (t.len == 0 or t.len > 64) return null;
+ if (std.mem.indexOfScalar(u8, t, '/') != null or std.mem.indexOfScalar(u8, t, '\\') != null) return null;
+ if (std.mem.eql(u8, t, ".") or std.mem.eql(u8, t, "..")) return null;
+ for (t) |c| {
+ const ok = std.ascii.isAlphanumeric(c) or c == '-' or c == '_' or c == '.';
+ if (!ok) return null;
+ }
+ return t;
+}
+
+pub fn names(arena: Allocator, slug: []const u8) !Workspace {
+ const name = sanitizeSlug(slug) orelse return error.InvalidName;
+ return .{
+ .name = name,
+ .path = try std.fmt.allocPrint(arena, ".graff/worktrees/{s}", .{name}),
+ .branch = try std.fmt.allocPrint(arena, "worktree-{s}", .{name}),
+ };
+}
+
+pub fn autoSlug(arena: Allocator, pid: i32, nonce: []const u8) ![]const u8 {
+ return std.fmt.allocPrint(arena, "session-{d}-{s}", .{ pid, nonce });
+}
+
+/// `{git-dir}/index.lock` — distinct per worktree, shared object DB is fine.
+pub fn indexLockPath(arena: Allocator, git_dir: []const u8) ?[]const u8 {
+ const dir = std.mem.trimEnd(u8, git_dir, "/");
+ if (dir.len == 0) return null;
+ return std.fs.path.join(arena, &.{ dir, "index.lock" }) catch null;
+}
+
+pub fn gitDirAt(gpa: Allocator, io: Io, arena: Allocator, checkout: []const u8) []const u8 {
+ return lease.identityAt(gpa, io, arena, checkout).id;
+}
+
+fn isGitAt(gpa: Allocator, io: Io, cwd: []const u8) bool {
+ const r = runCapped(gpa, io, &.{ "git", "-C", cwd, "rev-parse", "--is-inside-work-tree" }, 4096, 4096, 15_000) catch return false;
+ defer {
+ gpa.free(r.stdout);
+ gpa.free(r.stderr);
+ }
+ return ranOk(r);
+}
+
+fn dirExists(io: Io, path: []const u8) bool {
+ return (Io.Dir.cwd().statFile(io, path, .{}) catch null) != null;
+}
+
+fn joinCwd(arena: Allocator, cwd: []const u8, rel: []const u8) ![]const u8 {
+ if (std.fs.path.isAbsolute(rel)) return arena.dupe(u8, rel);
+ if (std.mem.eql(u8, cwd, ".") or cwd.len == 0) return arena.dupe(u8, rel);
+ return std.fs.path.join(arena, &.{ cwd, rel });
+}
+
+fn refExists(gpa: Allocator, io: Io, cwd: []const u8, branch: []const u8) bool {
+ const ref = std.fmt.allocPrint(gpa, "refs/heads/{s}", .{branch}) catch return false;
+ defer gpa.free(ref);
+ const r = runCapped(gpa, io, &.{ "git", "-C", cwd, "show-ref", "--verify", "--quiet", ref }, 4096, 4096, 15_000) catch return false;
+ defer {
+ gpa.free(r.stdout);
+ gpa.free(r.stderr);
+ }
+ return ranOk(r);
+}
+
+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);
+ return arena.dupe(u8, buf[0..n]);
+}
+
+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 mintOnce(gpa: Allocator, io: Io, arena: Allocator, cwd: []const u8, rel: []const u8, branch: []const u8, base: []const u8) !void {
+ const dest = try joinCwd(arena, cwd, rel);
+ const parent = std.fs.path.dirname(dest) orelse dest;
+ Io.Dir.cwd().createDirPath(io, parent) catch {};
+ const add = if (base.len > 0)
+ runCapped(gpa, io, &.{ "git", "-C", cwd, "worktree", "add", dest, "-b", branch, base }, 8192, 8192, 60_000)
+ else
+ runCapped(gpa, io, &.{ "git", "-C", cwd, "worktree", "add", dest, "-b", branch }, 8192, 8192, 60_000);
+ const r = add catch return error.CreateFailed;
+ defer {
+ gpa.free(r.stdout);
+ gpa.free(r.stderr);
+ }
+ if (!ranOk(r)) return error.CreateFailed;
+}
+
+pub fn create(gpa: Allocator, io: Io, arena: Allocator, opts: CreateOpts) (CreateError || Allocator.Error)!Workspace {
+ if (!isGitAt(gpa, io, opts.cwd)) return error.NotAGitRepo;
+ var named = try names(arena, opts.slug);
+ var dest = try joinCwd(arena, opts.cwd, named.path);
+ if (dirExists(io, dest) or refExists(gpa, io, opts.cwd, named.branch)) {
+ if (!opts.unique) return error.NameCollision;
+ var raw: [4]u8 = undefined;
+ io.random(&raw);
+ const nonce = std.fmt.bytesToHex(raw, .lower);
+ const slug = try std.fmt.allocPrint(arena, "{s}-{s}", .{ named.name, nonce[0..8] });
+ named = try names(arena, slug);
+ dest = 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 path = try absPath(io, arena, dest);
+ return .{
+ .name = named.name,
+ .path = path,
+ .branch = named.branch,
+ .base = readHead(gpa, io, arena, path),
+ };
+}
+
+/// 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;
+ const identity = lease.currentIdentity(gpa, io, arena);
+ if (identity.id.len == 0 or identity.kind == .not_git) return false;
+ const dir_path = std.fmt.allocPrint(arena, "{s}/{s}", .{ home, presence.registry_subdir }) catch return false;
+ var dir = Io.Dir.cwd().openDir(io, dir_path, .{ .iterate = true }) catch return false;
+ defer dir.close(io);
+ const peers = presence.listPeers(io, arena, dir);
+ const self = proc_identity.selfPid();
+ return lease.duplicateOwner(peers.records, peers.probes, identity.id, self) != null;
+}
+
+pub fn enter(gpa: Allocator, io: Io, arena: Allocator, wt: Workspace) !void {
+ if (builtin.os.tag == .windows) return error.Unsupported;
+ const z = try arena.dupeSentinel(u8, wt.path, 0);
+ if (std.posix.system.chdir(z.ptr) != 0) return error.ChdirFailed;
+ const owned_path = try gpa.dupe(u8, wt.path);
+ const owned_branch = try gpa.dupe(u8, wt.branch);
+ main_mod.g_cwd_display = owned_path;
+ main_mod.g_worktree_branch = owned_branch;
+ tool_spill.enable(.{ .io = io, .dir = .cwd(), .base_abs = main_mod.g_cwd_display });
+}
+
+/// 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;
+ const is_git = isGitAt(gpa, io, ".");
+ const claimed = checkoutClaimed(gpa, io, arena, home);
+ if (!shouldAutoIsolate(.{
+ .already_isolated = already_isolated,
+ .lean = lean,
+ .is_git = is_git,
+ .claimed = claimed,
+ .windows = false,
+ })) return null;
+ 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;
+}
+
+pub fn createFailureText(err: anyerror) []const u8 {
+ return switch (err) {
+ 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)",
+ else => "could not create a 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 }));
+ try std.testing.expect(!shouldAutoIsolate(.{ .claimed = true, .is_git = true, .windows = true }));
+ try std.testing.expect(!shouldAutoIsolate(.{ .claimed = true, .is_git = false }));
+ try std.testing.expect(!shouldAutoIsolate(.{ .claimed = false, .is_git = true }));
+ try std.testing.expect(shouldAutoIsolate(.{ .claimed = true, .is_git = true }));
+}
+
+test "sanitizeSlug and names: one workspace is one branch and one checkout path" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ try std.testing.expect(sanitizeSlug("") == null);
+ try std.testing.expect(sanitizeSlug("a/b") == null);
+ try std.testing.expect(sanitizeSlug("..") == null);
+ try std.testing.expect(sanitizeSlug("ok_name-1") != null);
+ const first = try names(a, "task-a");
+ try std.testing.expectEqualStrings(".graff/worktrees/task-a", first.path);
+ try std.testing.expectEqualStrings("worktree-task-a", first.branch);
+ const second = try names(a, "task-b");
+ 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 "indexLockPath: two worktree git dirs never share a lock file" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const main_lock = indexLockPath(a, "/repo/.git") orelse return error.TestUnexpectedResult;
+ const wt_lock = indexLockPath(a, "/repo/.git/worktrees/session-1") orelse return error.TestUnexpectedResult;
+ try std.testing.expectEqualStrings("/repo/.git/index.lock", main_lock);
+ try std.testing.expectEqualStrings("/repo/.git/worktrees/session-1/index.lock", wt_lock);
+ try std.testing.expect(!std.mem.eql(u8, main_lock, wt_lock));
+}
+
+test "create: two task workspaces get distinct checkouts and index.lock paths" {
+ 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 one = try create(a, io, ar, .{ .slug = "agent-one", .cwd = root });
+ const two = try create(a, io, ar, .{ .slug = "agent-two", .cwd = root });
+ try std.testing.expect(!std.mem.eql(u8, one.path, two.path));
+ try std.testing.expect(!std.mem.eql(u8, one.branch, two.branch));
+ const git_one = gitDirAt(a, io, ar, one.path);
+ const git_two = gitDirAt(a, io, ar, two.path);
+ try std.testing.expect(git_one.len > 0 and git_two.len > 0);
+ try std.testing.expect(!std.mem.eql(u8, git_one, git_two));
+ const lock_one = indexLockPath(ar, git_one) orelse return error.TestUnexpectedResult;
+ const lock_two = indexLockPath(ar, git_two) orelse return error.TestUnexpectedResult;
+ try std.testing.expect(!std.mem.eql(u8, lock_one, lock_two));
+ try std.testing.expect(std.mem.endsWith(u8, lock_one, "index.lock"));
+ try std.testing.expect(std.mem.endsWith(u8, lock_two, "index.lock"));
+ const claim_a = claim_path.canonicalFile(ar, io, one.path) orelse return error.TestUnexpectedResult;
+ const claim_b = claim_path.canonicalFile(ar, io, two.path) orelse return error.TestUnexpectedResult;
+ try std.testing.expectEqualStrings(claim_a, claim_b);
+ const collide = create(a, io, ar, .{ .slug = "agent-one", .cwd = root });
+ try std.testing.expectError(error.NameCollision, collide);
+}
+
+test "create: non-git folder is not a task workspace" {
+ 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);
+ var arena = std.heap.ArenaAllocator.init(a);
+ defer arena.deinit();
+ try std.testing.expectError(error.NotAGitRepo, create(a, io, arena.allocator(), .{ .slug = "x", .cwd = tmp_root }));
+ try std.testing.expect(std.mem.indexOf(u8, createFailureText(error.NotAGitRepo), "plain folder") != null);
+}
+
+fn git(io: Io, a: Allocator, argv: []const []const u8) !void {
+ var args: std.ArrayList([]const u8) = .empty;
+ defer args.deinit(a);
+ try args.append(a, "git");
+ try args.appendSlice(a, argv);
+ const r = try runCapped(a, io, args.items, 4096, 4096, 15_000);
+ defer {
+ a.free(r.stdout);
+ a.free(r.stderr);
+ }
+ if (!ranOk(r)) return error.TestUnexpectedResult;
+}
diff --git a/src/tui_acp.zig b/src/tui_acp.zig
index 99aface1..5f1a9ba0 100644
--- a/src/tui_acp.zig
+++ b/src/tui_acp.zig
@@ -161,6 +161,7 @@ pub const Session = struct {
.ctx = @ptrCast(self),
.seed = seed,
.bind_session = bindSession,
+ .cwd = main_mod.g_cwd_display,
},
};
}
diff --git a/src/workspace_switch.zig b/src/workspace_switch.zig
index e07b8402..9e05744f 100644
--- a/src/workspace_switch.zig
+++ b/src/workspace_switch.zig
@@ -27,11 +27,12 @@ const tool_spill = @import("tool_spill.zig");
const Agent = agent_mod.Agent;
const ToolCall = tools_mod.ToolCall;
const ExecResult = tools_mod.ExecResult;
+const task_workspace = @import("task_workspace.zig");
pub const tool_name = "workspace";
-pub const tool_desc = "List this repo's git worktrees or switch the session into one. action=list (default) or use. path is a worktree path, its last folder, or a unique name fragment. 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_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"], "description": "list (default): the repo's git worktrees. use: chdir this session into one."}, "path": {"type": "string", "description": "worktree path, last folder, or unique fragment (required for use)"}}}
+ \\{"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)"}}}
;
pub const Entry = struct {
@@ -215,7 +216,27 @@ fn enterPath(gpa: Allocator, io: Io, arena: Allocator, path: []const u8) ![]cons
return abs;
}
-fn run(gpa: Allocator, io: Io, arena: Allocator, from_sub: bool, action: []const u8, path: []const u8) ExecResult {
+fn createAndEnter(gpa: Allocator, io: Io, arena: Allocator, name: []const u8, base: []const u8) ExecResult {
+ if (name.len == 0) return .{
+ .text = "workspace create needs name — a short slug for the branch and checkout",
+ .is_error = true,
+ };
+ const wt = task_workspace.create(gpa, io, arena, .{ .slug = name, .base = base }) catch |err| return .{
+ .text = task_workspace.createFailureText(err),
+ .is_error = true,
+ };
+ const abs = enterPath(gpa, io, arena, wt.path) catch |err| return .{
+ .text = tryText(arena, "created {s} at {s} but could not enter it: {t}", .{ wt.branch, wt.path, err }),
+ .is_error = true,
+ };
+ main_mod.g_worktree_branch = gpa.dupe(u8, wt.branch) catch wt.branch;
+ return .{
+ .text = tryText(arena, "created workspace {s} at {s} (branch {s}) — read_file, edit_file, and bash use this tree", .{ wt.name, abs, wt.branch }),
+ .is_error = false,
+ };
+}
+
+fn run(gpa: Allocator, io: Io, arena: Allocator, from_sub: bool, action: []const u8, path: []const u8, base: []const u8) ExecResult {
if (from_sub) return .{
.text = "workspace switch is root-session only — a subagent stays in its assigned tree",
.is_error = true,
@@ -224,8 +245,11 @@ fn run(gpa: Allocator, io: Io, arena: Allocator, from_sub: bool, action: []const
if (std.mem.eql(u8, action, "list") or action.len == 0) {
return .{ .text = formatList(arena, listEntries(gpa, io, arena), current, io), .is_error = false };
}
+ if (std.mem.eql(u8, action, "create")) {
+ return createAndEnter(gpa, io, arena, path, base);
+ }
if (!std.mem.eql(u8, action, "use")) return .{
- .text = "workspace action must be list or use",
+ .text = "workspace action must be list, use, or create",
.is_error = true,
};
if (path.len == 0) return .{
@@ -267,7 +291,10 @@ pub fn handle(self: *Agent, call: ToolCall) !ExecResult {
const obj = tools_mod.json_args.object(call.input);
const action = if (obj) |o| (tools_mod.json_args.str(o, "action") orelse "list") else "list";
const path = if (obj) |o| (tools_mod.json_args.str(o, "path") orelse "") else "";
- return run(self.gpa, self.io, self.arena, self.sub or self.agent_cwd != null, action, path);
+ const name = if (obj) |o| (tools_mod.json_args.str(o, "name") orelse "") else "";
+ const base = if (obj) |o| (tools_mod.json_args.str(o, "base") orelse "") else "";
+ const dest = if (std.mem.eql(u8, action, "create") and name.len > 0) name else path;
+ return run(self.gpa, self.io, self.arena, self.sub or self.agent_cwd != null, action, dest, base);
}
fn isSlash(line: []const u8) bool {
@@ -284,12 +311,22 @@ pub fn slashCommand(root: *Agent, arena: Allocator, line: []const u8, out: *Io.W
std.mem.trim(u8, line["/ws".len..], " \t");
var action: []const u8 = "list";
var path: []const u8 = "";
+ var base: []const u8 = "";
if (rest.len > 0) {
if (std.mem.startsWith(u8, rest, "use ") or std.mem.startsWith(u8, rest, "cd ")) {
action = "use";
path = std.mem.trim(u8, rest[3..], " \t");
} else if (std.mem.eql(u8, rest, "use") or std.mem.eql(u8, rest, "cd")) {
action = "use";
+ } else if (std.mem.startsWith(u8, rest, "create ")) {
+ action = "create";
+ const spec = std.mem.trim(u8, rest["create ".len..], " \t");
+ if (std.mem.indexOfScalar(u8, spec, ' ')) |i| {
+ path = std.mem.trim(u8, spec[0..i], " \t");
+ base = std.mem.trim(u8, spec[i + 1 ..], " \t");
+ } else path = spec;
+ } else if (std.mem.eql(u8, rest, "create")) {
+ action = "create";
} else if (std.mem.eql(u8, rest, "list") or std.mem.eql(u8, rest, "ls")) {
action = "list";
} else {
@@ -297,7 +334,7 @@ pub fn slashCommand(root: *Agent, arena: Allocator, line: []const u8, out: *Io.W
path = rest;
}
}
- const result = run(root.gpa, root.io, arena, false, action, path);
+ const result = run(root.gpa, root.io, arena, false, action, path, base);
try out.writeAll(result.text);
if (result.text.len == 0 or result.text[result.text.len - 1] != '\n') try out.writeAll("\n");
try out.flush();
@@ -445,14 +482,17 @@ test "run: subagent is refused; bad action and empty use name the fix" {
const a = arena_state.allocator();
const io = std.testing.io;
const gpa = std.testing.allocator;
- const sub = run(gpa, io, a, true, "list", "");
+ const sub = run(gpa, io, a, true, "list", "", "");
try std.testing.expect(sub.is_error);
try std.testing.expect(std.mem.indexOf(u8, sub.text, "root-session only") != null);
- const bad = run(gpa, io, a, false, "send", "");
+ const bad = run(gpa, io, a, false, "send", "", "");
try std.testing.expect(bad.is_error);
- const empty = run(gpa, io, a, false, "use", "");
+ const empty = run(gpa, io, a, false, "use", "", "");
try std.testing.expect(empty.is_error);
try std.testing.expect(std.mem.indexOf(u8, empty.text, "action=list") != null);
+ const no_name = run(gpa, io, a, false, "create", "", "");
+ try std.testing.expect(no_name.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, no_name.text, "name") != null);
}
test "enterPath: chdir then restore; display follows the new tree" {
diff --git a/src/worktree_cmd.zig b/src/worktree_cmd.zig
index 85fde54a..a956f049 100644
--- a/src/worktree_cmd.zig
+++ b/src/worktree_cmd.zig
@@ -165,13 +165,28 @@ pub fn worktreeCommand(gpa: Allocator, io: Io, arena: Allocator, args: []const [
return;
}
+ if (std.mem.eql(u8, action, "create")) {
+ if (args.len < 2) {
+ try out.writeAll("usage: graff worktree create <name> [base]\n");
+ return;
+ }
+ const name = args[1];
+ const base = if (args.len > 2) args[2] else "";
+ const wt = @import("task_workspace.zig").create(gpa, io, arena, .{ .slug = name, .base = base }) catch |err| {
+ try out.print("✗ {s}\n", .{@import("task_workspace.zig").createFailureText(err)});
+ return;
+ };
+ try out.print("✓ workspace {s}\n path {s}\n branch {s}\n", .{ wt.name, wt.path, wt.branch });
+ 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 | merge <name> | remove <name> | prune [older-than <days>]\n", .{action});
+ try out.print("unknown worktree command '{s}' — use: graff worktree list | create <name> [base] | merge <name> | remove <name> | prune [older-than <days>]\n", .{action});
}
test { // split-out module: unreferenced, its tests silently never run