Skip to content

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

Python

fix(worktree): never delete a subagent branch that holds commits

Rach Pradhan86951f7c0aae
diff --git a/src/agent_worktree.zig b/src/agent_worktree.zig
index 295b8ff4..daf99034 100644
--- a/src/agent_worktree.zig
+++ b/src/agent_worktree.zig
@@ -7,9 +7,34 @@ const process_runner = @import("process_runner.zig");
const runCapped = process_runner.runCapped;
const ranOk = process_runner.ranOk;
-pub const AgentWorktree = struct { path: []const u8, branch: []const u8 };
+pub const AgentWorktree = struct { path: []const u8, branch: []const u8, base: []const u8 = "" };
pub const AgentWorktreeError = error{ NotAGitRepo, CreateFailed };
-pub const AgentWorktreeOutcome = struct { kept: bool };
+pub const AgentWorktreeOutcome = struct { kept: bool, reason: KeepReason = .removed };
+
+pub const KeepReason = enum { removed, dirty, committed, unverifiable };
+
+/// Pure removal decision. `status_ok`/`porcelain` are the `git status --porcelain`
+/// result in the worktree; `head` is `git rev-parse HEAD` there (empty when it
+/// could not be read); `base` is the commit the worktree was created at (empty
+/// when unknown). Removal requires positive proof on every axis - anything we
+/// could not establish keeps the worktree, because `git branch -D` on a branch
+/// whose commits nothing else references destroys the child's work silently.
+pub fn worktreeKeepReason(status_ok: bool, porcelain: []const u8, base: []const u8, head: []const u8) KeepReason {
+ if (!status_ok) return .unverifiable;
+ if (isWorktreeStatusDirty(porcelain)) return .dirty;
+ if (base.len == 0 or head.len == 0) return .unverifiable;
+ if (!std.mem.eql(u8, base, head)) return .committed;
+ return .removed;
+}
+
+pub fn keepReasonText(reason: KeepReason) []const u8 {
+ return switch (reason) {
+ .dirty => "has changes",
+ .committed => "has commits that exist ONLY on this branch - merge or cherry-pick them, nothing else references them",
+ .unverifiable => "could not verify it is safe to remove",
+ .removed => "",
+ };
+}
pub fn isolationFailureText(err: anyerror) []const u8 {
return switch (err) {
@@ -45,9 +70,18 @@ pub fn agentWorktreeCreate(gpa: Allocator, io: Io, arena: Allocator, sub_id: []c
}
if (!ranOk(add)) return error.CreateFailed;
+ var base: []const u8 = "";
+ if (runCapped(gpa, io, &.{ "git", "-C", names.path, "rev-parse", "HEAD" }, 4096, 4096, 15_000)) |r| {
+ defer {
+ gpa.free(r.stdout);
+ gpa.free(r.stderr);
+ }
+ if (ranOk(r)) base = try arena.dupe(u8, std.mem.trim(u8, r.stdout, " \t\r\n"));
+ } else |_| {}
+
var buf: [4096]u8 = undefined;
- const n = Io.Dir.cwd().realPathFile(io, names.path, &buf) catch return .{ .path = names.path, .branch = names.branch };
- return .{ .path = try arena.dupe(u8, buf[0..n]), .branch = names.branch };
+ const n = Io.Dir.cwd().realPathFile(io, names.path, &buf) catch return .{ .path = names.path, .branch = names.branch, .base = base };
+ return .{ .path = try arena.dupe(u8, buf[0..n]), .branch = names.branch, .base = base };
}
pub fn isWorktreeStatusDirty(porcelain: []const u8) bool {
@@ -55,22 +89,44 @@ pub fn isWorktreeStatusDirty(porcelain: []const u8) bool {
}
pub fn agentWorktreeFinish(gpa: Allocator, io: Io, wt: AgentWorktree) AgentWorktreeOutcome {
- const st = runCapped(gpa, io, &.{ "git", "-C", wt.path, "status", "--porcelain" }, 1 << 16, 8192, 30_000) catch return .{ .kept = true };
+ const st = runCapped(gpa, io, &.{ "git", "-C", wt.path, "status", "--porcelain" }, 1 << 16, 8192, 30_000) catch return .{ .kept = true, .reason = .unverifiable };
defer {
gpa.free(st.stdout);
gpa.free(st.stderr);
}
- if (!ranOk(st) or isWorktreeStatusDirty(st.stdout)) return .{ .kept = true };
- if (runCapped(gpa, io, &.{ "git", "worktree", "remove", "--force", wt.path }, 8192, 8192, 30_000)) |r| {
- gpa.free(r.stdout);
- gpa.free(r.stderr);
+ var head: []const u8 = "";
+ var head_buf: [4096]u8 = undefined;
+ var head_len: usize = 0;
+ if (runCapped(gpa, io, &.{ "git", "-C", wt.path, "rev-parse", "HEAD" }, 4096, 4096, 15_000)) |r| {
+ defer {
+ gpa.free(r.stdout);
+ gpa.free(r.stderr);
+ }
+ if (ranOk(r)) {
+ const trimmed = std.mem.trim(u8, r.stdout, " \t\r\n");
+ head_len = @min(trimmed.len, head_buf.len);
+ @memcpy(head_buf[0..head_len], trimmed[0..head_len]);
+ head = head_buf[0..head_len];
+ }
} else |_| {}
+
+ const reason = worktreeKeepReason(ranOk(st), st.stdout, wt.base, head);
+ if (reason != .removed) return .{ .kept = true, .reason = reason };
+
+ if (runCapped(gpa, io, &.{ "git", "worktree", "remove", wt.path }, 8192, 8192, 30_000)) |r| {
+ defer {
+ gpa.free(r.stdout);
+ gpa.free(r.stderr);
+ }
+ if (!ranOk(r)) return .{ .kept = true, .reason = .unverifiable };
+ } else |_| return .{ .kept = true, .reason = .unverifiable };
+
if (runCapped(gpa, io, &.{ "git", "branch", "-D", wt.branch }, 8192, 8192, 30_000)) |r| {
gpa.free(r.stdout);
gpa.free(r.stderr);
} else |_| {}
- return .{ .kept = false };
+ return .{ .kept = false, .reason = .removed };
}
test "agentWorktreeNames: unique path/branch per nonce, never collide across repeated spawns (#276)" {
@@ -104,3 +160,24 @@ test "isolationFailureText: friendly, distinct messages for the non-git and crea
try std.testing.expect(std.mem.indexOf(u8, create_failed, "isolation_fallback") != null);
try std.testing.expect(!std.mem.eql(u8, not_git, create_failed));
}
+
+test "worktreeKeepReason: committed work is never removable, and every unproven axis keeps the worktree" {
+ try std.testing.expectEqual(KeepReason.removed, worktreeKeepReason(true, "", "abc123", "abc123"));
+ try std.testing.expectEqual(KeepReason.dirty, worktreeKeepReason(true, " M src/foo.zig\n", "abc123", "abc123"));
+ try std.testing.expectEqual(KeepReason.dirty, worktreeKeepReason(true, "?? new.zig\n", "abc123", "abc123"));
+ try std.testing.expectEqual(KeepReason.committed, worktreeKeepReason(true, "", "abc123", "def456"));
+ try std.testing.expectEqual(KeepReason.committed, worktreeKeepReason(true, "\n \n", "abc123", "def456"));
+ try std.testing.expectEqual(KeepReason.unverifiable, worktreeKeepReason(false, "", "abc123", "abc123"));
+ try std.testing.expectEqual(KeepReason.unverifiable, worktreeKeepReason(true, "", "", "def456"));
+ try std.testing.expectEqual(KeepReason.unverifiable, worktreeKeepReason(true, "", "abc123", ""));
+}
+
+test "keepReasonText: each kept reason names its cause, and .dirty keeps its historical wording" {
+ try std.testing.expectEqualStrings("has changes", keepReasonText(.dirty));
+ const committed = keepReasonText(.committed);
+ try std.testing.expect(std.mem.indexOf(u8, committed, "commits") != null);
+ try std.testing.expect(std.mem.indexOf(u8, committed, "cherry-pick") != null);
+ try std.testing.expect(!std.mem.eql(u8, keepReasonText(.committed), keepReasonText(.unverifiable)));
+ try std.testing.expect(!std.mem.eql(u8, keepReasonText(.unverifiable), keepReasonText(.dirty)));
+ try std.testing.expect(!std.mem.eql(u8, keepReasonText(.committed), keepReasonText(.dirty)));
+}
diff --git a/src/jobs.zig b/src/jobs.zig
index 4cfa327d..d691f05d 100644
--- a/src/jobs.zig
+++ b/src/jobs.zig
@@ -46,6 +46,8 @@ pub const agentWorktreeNames = agent_worktree.agentWorktreeNames;
pub const agentWorktreeCreate = agent_worktree.agentWorktreeCreate;
pub const isWorktreeStatusDirty = agent_worktree.isWorktreeStatusDirty;
pub const agentWorktreeFinish = agent_worktree.agentWorktreeFinish;
+pub const KeepReason = agent_worktree.KeepReason;
+pub const keepReasonText = agent_worktree.keepReasonText;
/// True if the current git working tree has uncommitted *tracked* changes
/// (staged or unstaged). Untracked files (`?? …`) don't count — `git reset
diff --git a/src/subagent_run.zig b/src/subagent_run.zig
index baa50b77..b6b4d0f5 100644
--- a/src/subagent_run.zig
+++ b/src/subagent_run.zig
@@ -288,7 +288,7 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const
if (wt) |w| {
const outcome = jobs.agentWorktreeFinish(gpa, ctx.io, w);
if (outcome.kept) {
- extra = std.fmt.allocPrint(gpa, "\n\n[worktree kept (has changes) — path: {s}, branch: {s}]", .{ w.path, w.branch }) catch "";
+ extra = std.fmt.allocPrint(gpa, "\n\n[worktree kept ({s}) — path: {s}, branch: {s}]", .{ jobs.keepReasonText(outcome.reason), w.path, w.branch }) catch "";
extra_owned = extra.len > 0;
}
}