Skip to content

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

Python

Reap dead auto-isolate session worktrees on startup

justrach56819c74b937
diff --git a/src/main.zig b/src/main.zig
index ab01050a..202f74f1 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("task_workspace_tests.zig"), @import("workspace_prepare_tests.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_tests.zig"), @import("workspace_prepare_tests.zig"), @import("worktree_reap.zig") };
}
diff --git a/src/session_start.zig b/src/session_start.zig
index f7767a0b..32e177fd 100644
--- a/src/session_start.zig
+++ b/src/session_start.zig
@@ -120,6 +120,7 @@ pub fn setupWorktreeAndBanner(
// agents don't collide on files. Creates .graff/worktrees/<name> on branch
// worktree-<name> from the remote base and enters it; reuses it if it exists.
const task_workspace = @import("task_workspace.zig");
+ _ = @import("worktree_reap.zig").orphans(gpa, io, arena, ".");
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
diff --git a/src/worktree_prune.zig b/src/worktree_prune.zig
index a74669c4..3a691088 100644
--- a/src/worktree_prune.zig
+++ b/src/worktree_prune.zig
@@ -191,7 +191,7 @@ fn worktreeAgeMs(io: Io, now_ms: i64, path: []const u8) i64 {
/// `worktreeKeepReason` for a listed worktree, gathering the two facts it needs
/// from git. Any failed probe stays `.unverifiable`, i.e. keeps the worktree.
-fn keepReasonFor(gpa: Allocator, io: Io, e: Entry) KeepReason {
+pub fn keepReasonFor(gpa: Allocator, io: Io, e: Entry) KeepReason {
const st = runCapped(gpa, io, &.{ "git", "-C", e.path, "status", "--porcelain" }, 1 << 16, 8192, 30_000) catch return .unverifiable;
defer {
gpa.free(st.stdout);
@@ -199,7 +199,7 @@ fn keepReasonFor(gpa: Allocator, io: Io, e: Entry) KeepReason {
}
if (!ranOk(st)) return .unverifiable;
if (e.head.len == 0) return .unverifiable;
- const refs = runCapped(gpa, io, &.{ "git", "branch", "--all", "--contains", e.head, "--format=%(refname)" }, 1 << 16, 8192, 30_000) catch return .unverifiable;
+ const refs = runCapped(gpa, io, &.{ "git", "-C", e.path, "branch", "--all", "--contains", e.head, "--format=%(refname)" }, 1 << 16, 8192, 30_000) catch return .unverifiable;
defer {
gpa.free(refs.stdout);
gpa.free(refs.stderr);
@@ -212,15 +212,15 @@ fn keepReasonFor(gpa: Allocator, io: Io, e: Entry) KeepReason {
/// Remove the directory git registered for `e`. No `--force`: we already proved
/// the tree is clean, so git's own refusal is a second belt — #112 must not
/// turn `prune` into a data-loss command.
-fn removeWorktree(gpa: Allocator, io: Io, e: Entry) bool {
- const rm = runCapped(gpa, io, &.{ "git", "worktree", "remove", e.path }, 8192, 8192, 60_000) catch return false;
+pub fn removeWorktree(gpa: Allocator, io: Io, e: Entry) bool {
+ const rm = runCapped(gpa, io, &.{ "git", "-C", e.path, "worktree", "remove", e.path }, 8192, 8192, 60_000) catch return false;
defer {
gpa.free(rm.stdout);
gpa.free(rm.stderr);
}
if (!ranOk(rm)) return false;
if (isGraffScratchBranch(e.branch)) {
- if (runCapped(gpa, io, &.{ "git", "branch", "-D", shortBranch(e.branch) }, 8192, 8192, 30_000)) |b| {
+ if (runCapped(gpa, io, &.{ "git", "-C", e.path, "branch", "-D", shortBranch(e.branch) }, 8192, 8192, 30_000)) |b| {
gpa.free(b.stdout);
gpa.free(b.stderr);
} else |_| {}
diff --git a/src/worktree_reap.zig b/src/worktree_reap.zig
new file mode 100644
index 00000000..43f552b8
--- /dev/null
+++ b/src/worktree_reap.zig
@@ -0,0 +1,112 @@
+//! Reap auto-isolate session worktrees whose process is gone (#1118).
+//! Named task workspaces and dirty/unique-commit trees stay (ADR 0147).
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const process_runner = @import("process_runner.zig");
+const runCapped = process_runner.runCapped;
+const proc_identity = @import("proc_identity.zig");
+const prune = @import("worktree_prune.zig");
+
+const session_prefix = "worktree-session-";
+
+/// Pid encoded in `worktree-session-<pid>-<nonce>`, or null if this is not
+/// an auto-isolate session tree.
+pub fn sessionPid(branch: []const u8) ?i32 {
+ const name = prune.shortBranch(branch);
+ if (!std.mem.startsWith(u8, name, session_prefix)) return null;
+ const rest = name[session_prefix.len..];
+ const dash = std.mem.indexOfScalar(u8, rest, '-') orelse return null;
+ if (dash == 0) return null;
+ return std.fmt.parseInt(i32, rest[0..dash], 10) catch null;
+}
+
+fn pidGone(io: Io, pid: i32) bool {
+ return proc_identity.probe(io, pid) == .gone;
+}
+
+/// Drop registrations whose dirs are already gone, then remove clean
+/// auto-isolate trees whose pid is dead. Returns how many directories went.
+pub fn orphans(gpa: Allocator, io: Io, arena: Allocator, cwd: []const u8) usize {
+ const dir = if (cwd.len > 0) cwd else ".";
+ if (runCapped(gpa, io, &.{ "git", "-C", dir, "worktree", "prune" }, 4096, 4096, 15_000)) |r| {
+ gpa.free(r.stdout);
+ gpa.free(r.stderr);
+ } else |_| {}
+ const listed = runCapped(gpa, io, &.{ "git", "-C", dir, "worktree", "list", "--porcelain" }, 1 << 18, 8192, 15_000) catch return 0;
+ defer {
+ gpa.free(listed.stdout);
+ gpa.free(listed.stderr);
+ }
+ const entries = prune.parseEntries(arena, listed.stdout) catch return 0;
+ var buf: [std.fs.max_path_bytes]u8 = undefined;
+ const here_n = Io.Dir.cwd().realPathFile(io, ".", &buf) catch 0;
+ const here = if (here_n > 0) buf[0..here_n] else "";
+ var removed: usize = 0;
+ for (entries) |e| {
+ const pid = sessionPid(e.branch) orelse continue;
+ if (!pidGone(io, pid)) continue;
+ if (here.len > 0 and std.mem.eql(u8, e.path, here)) continue;
+ if (prune.keepReasonFor(gpa, io, e) != .removed) continue;
+ if (prune.removeWorktree(gpa, io, e)) removed += 1;
+ }
+ return removed;
+}
+
+test "sessionPid: only auto-isolate session branches" {
+ try std.testing.expectEqual(@as(?i32, 65043), sessionPid("refs/heads/worktree-session-65043-e9cc718d"));
+ try std.testing.expectEqual(@as(?i32, 65043), sessionPid("worktree-session-65043-e9cc718d"));
+ try std.testing.expectEqual(@as(?i32, null), sessionPid("worktree-task-a"));
+ try std.testing.expectEqual(@as(?i32, null), sessionPid("graff/agents/sa-1-aa"));
+ try std.testing.expectEqual(@as(?i32, null), sessionPid("feat/side-agent-steer"));
+}
+
+test "orphans: a dead-pid clean session tree is removed; a named workspace is not" {
+ const builtin = @import("builtin");
+ 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);
+ const ws = @import("task_workspace.zig");
+ const runner = @import("process_runner.zig");
+ const git = struct {
+ fn run(gpa: Allocator, git_io: Io, argv: []const []const u8) !void {
+ var args: std.ArrayList([]const u8) = .empty;
+ defer args.deinit(gpa);
+ try args.append(gpa, "git");
+ try args.appendSlice(gpa, argv);
+ const r = try runner.runCapped(gpa, git_io, args.items, 4096, 4096, 15_000);
+ defer gpa.free(r.stdout);
+ defer gpa.free(r.stderr);
+ try std.testing.expect(runner.ranOk(r));
+ }
+ };
+ try git.run(a, io, &.{ "init", "-q", "-b", "main", root });
+ try git.run(a, io, &.{ "-C", root, "config", "user.email", "t@t" });
+ try git.run(a, io, &.{ "-C", root, "config", "user.name", "t" });
+ const tracked = try std.fs.path.join(a, &.{ root, "f" });
+ defer a.free(tracked);
+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = tracked, .data = "x\n" });
+ try git.run(a, io, &.{ "-C", root, "add", "f" });
+ try git.run(a, io, &.{ "-C", root, "commit", "-m", "i" });
+
+ var arena = std.heap.ArenaAllocator.init(a);
+ defer arena.deinit();
+ const ar = arena.allocator();
+ const live = try ws.create(a, io, ar, .{ .slug = "session-1-deadbeef", .cwd = root });
+ const named = try ws.create(a, io, ar, .{ .slug = "task-keep", .cwd = root });
+ const gone = try ws.create(a, io, ar, .{ .slug = "session-0-deadbeef", .cwd = root });
+ const n = orphans(a, io, ar, root);
+ try std.testing.expect(n >= 1);
+ try std.testing.expect((Io.Dir.cwd().statFile(io, gone.path, .{}) catch null) == null);
+ try std.testing.expect((Io.Dir.cwd().statFile(io, named.path, .{}) catch null) != null);
+ try std.testing.expect((Io.Dir.cwd().statFile(io, live.path, .{}) catch null) != null);
+}