Skip to content

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

Python

fix: shared-tree gate uses the git -C / cd target

Rachc8afe75118d1
diff --git a/src/agent_tool_gate.zig b/src/agent_tool_gate.zig
index 06f8f5f0..690edb5d 100644
--- a/src/agent_tool_gate.zig
+++ b/src/agent_tool_gate.zig
@@ -220,10 +220,12 @@ pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {
// approvals prompt would ever surface the collision. The model sees
// the peer's identity + goal and re-issues the command to proceed.
if (presence.isSharedTreeGit(cmd) or presence.isSharedTreeShell(cmd)) {
- if (presence.gateCheck(self.io, self.arena)) |checkpoint| return .{
- .text = checkpoint,
- .is_error = true,
- };
+ if (presence.sharedTreeGateApplies(self.gpa, self.io, self.arena, cmd)) {
+ if (presence.gateCheck(self.io, self.arena)) |checkpoint| return .{
+ .text = checkpoint,
+ .is_error = true,
+ };
+ }
}
const destructive_git = Approvals.isDestructiveGit(cmd);
const gate_ok = !destructive_git or Approvals.destructiveGitAllowed(approvals.yolo, self.sub);
@@ -386,3 +388,45 @@ test "private template collector covers subagents and workflow stages" {
const wf = collectPrivateTemplates(io, .{ .id = "2", .name = "workflow", .input = wf_value });
try std.testing.expectEqual(@as(usize, 2), wf.len);
}
+
+test "#851 bash gate resolves the git target before gateCheck" {
+ const src = @embedFile("agent_tool_gate.zig");
+ const applies = std.mem.indexOf(u8, src, "sharedTreeGateApplies").?;
+ const check = std.mem.indexOfPos(u8, src, applies, "gateCheck(").?;
+ try std.testing.expect(applies < check);
+}
+
+test "#851 isolated git -C target does not use the caller worktree identity" {
+ const gpa = std.testing.allocator;
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const root = try tmp.dir.realPathFileAlloc(std.testing.io, ".", a);
+ const path_a = try std.fmt.allocPrint(a, "{s}/a", .{root});
+ const path_b = try std.fmt.allocPrint(a, "{s}/b", .{root});
+ try tmp.dir.createDirPath(std.testing.io, "a");
+ try tmp.dir.createDirPath(std.testing.io, "b");
+ const runner = @import("process_runner.zig");
+ for ([_][]const u8{ path_a, path_b }) |p| {
+ const r = try runner.runCapped(gpa, std.testing.io, &.{ "git", "init", "-q", p }, 4096, 4096, 15_000);
+ defer {
+ gpa.free(r.stdout);
+ gpa.free(r.stderr);
+ }
+ try std.testing.expect(runner.ranOk(r));
+ }
+ const worktree_lease = @import("worktree_lease.zig");
+ const id_a = worktree_lease.identityAt(gpa, std.testing.io, a, path_a);
+ try std.testing.expect(id_a.id.len > 0);
+ presence.bindForTest(root, id_a.id, "s-caller", .{});
+ defer presence.unbindForTest();
+ const cmd_b = try std.fmt.allocPrint(a, "git -C {s} cherry-pick abc", .{path_b});
+ const cmd_a = try std.fmt.allocPrint(a, "git -C {s} cherry-pick abc", .{path_a});
+ const cmd_sub = try std.fmt.allocPrint(a, "cd {s}/. && git stash", .{path_a});
+ try std.testing.expect(!presence.sharedTreeGateApplies(gpa, std.testing.io, a, cmd_b));
+ try std.testing.expect(presence.sharedTreeGateApplies(gpa, std.testing.io, a, cmd_a));
+ try std.testing.expect(presence.sharedTreeGateApplies(gpa, std.testing.io, a, cmd_sub));
+ try std.testing.expect(presence.sharedTreeGateApplies(gpa, std.testing.io, a, "git cherry-pick abc"));
+}
diff --git a/src/presence.zig b/src/presence.zig
index f2efc464..9ddd2b02 100644
--- a/src/presence.zig
+++ b/src/presence.zig
@@ -26,6 +26,19 @@ pub const parseRecord = presence_record.parseRecord;
pub const isSharedTreeGit = presence_mutate.isSharedTreeGit;
pub const isSharedTreeShell = presence_mutate.isSharedTreeShell;
+pub const mutationTarget = presence_mutate.mutationTarget;
+
+/// #851: checkpoint the worktree the command mutates. An isolated `git -C`
+/// / leading `cd` target that resolves to a different identity is not the
+/// caller's shared tree. Unresolved or in-tree paths stay gated.
+pub fn sharedTreeGateApplies(gpa: Allocator, io: Io, arena: Allocator, cmd: []const u8) bool {
+ const mine = g_identity;
+ if (mine.len == 0) return true;
+ const target = presence_mutate.mutationTarget(cmd) orelse return true;
+ const at = worktree_lease.identityAt(gpa, io, arena, target);
+ if (at.id.len == 0) return true;
+ return std.mem.eql(u8, mine, at.id);
+}
/// Per-user registry: <home>/.graff/live. Deliberately NOT the per-project .graff/sessions of session_index.zig — presence is device-local and keyed by worktree identity so two checkouts of one repo stay distinct (#320).
pub const registry_subdir = ".graff/live";
diff --git a/src/presence_mutate.zig b/src/presence_mutate.zig
index d1486615..3bdb4d03 100644
--- a/src/presence_mutate.zig
+++ b/src/presence_mutate.zig
@@ -70,6 +70,48 @@ pub fn isSharedTreeShell(cmd: []const u8) bool {
return false;
}
+/// Directory a mutating command actually touches, when we can resolve it
+/// without a shell. `git -C PATH` wins; a leading `cd PATH` is next.
+/// Quoted, globbed, or otherwise ambiguous forms return null so the caller
+/// stays conservative and still checkpoints the session worktree (#851).
+pub fn mutationTarget(cmd: []const u8) ?[]const u8 {
+ if (gitDashC(cmd)) |p| return p;
+ return leadingCd(cmd);
+}
+
+fn gitDashC(cmd: []const u8) ?[]const u8 {
+ var it = std.mem.tokenizeAny(u8, cmd, " \t\r\n;&|\"'`()");
+ while (it.next()) |tok| {
+ if (!std.mem.eql(u8, tok, "git")) continue;
+ while (it.next()) |arg| {
+ if (std.mem.eql(u8, arg, "-C")) return nonemptyPath(it.next() orelse return null);
+ if (std.mem.startsWith(u8, arg, "-C") and arg.len > 2) return nonemptyPath(arg[2..]);
+ if (arg[0] == '-') {
+ if (std.mem.eql(u8, arg, "-c")) _ = it.next();
+ continue;
+ }
+ break;
+ }
+ }
+ return null;
+}
+
+fn leadingCd(cmd: []const u8) ?[]const u8 {
+ const t = std.mem.trim(u8, cmd, " \t");
+ if (!std.mem.startsWith(u8, t, "cd")) return null;
+ if (t.len < 4 or (t[2] != ' ' and t[2] != '\t')) return null;
+ const rest = std.mem.trimStart(u8, t[2..], " \t");
+ if (rest.len == 0 or std.mem.indexOfScalar(u8, "-$\"'`", rest[0]) != null) return null;
+ var i: usize = 0;
+ while (i < rest.len and std.mem.indexOfScalar(u8, " \t;&|", rest[i]) == null) : (i += 1) {}
+ return nonemptyPath(rest[0..i]);
+}
+
+fn nonemptyPath(p: []const u8) ?[]const u8 {
+ if (p.len == 0 or std.mem.indexOfAny(u8, p, "*?{}") != null) return null;
+ return p;
+}
+
test "isSharedTreeGit: flags index/tree-mutating git, ignores read-only git" {
try std.testing.expect(isSharedTreeGit("git add -A"));
try std.testing.expect(isSharedTreeGit("git commit -m \"wip\""));
@@ -102,3 +144,14 @@ test "isSharedTreeShell: flags mv and recursive rm, leaves everyday commands alo
try std.testing.expect(!isSharedTreeShell("ls -la"));
try std.testing.expect(!isSharedTreeShell("echo moved"));
}
+
+test "#851 mutationTarget reads git -C and a leading cd, ignores ambiguous forms" {
+ try std.testing.expectEqualStrings("/tmp/wt", mutationTarget("git -C /tmp/wt cherry-pick abc").?);
+ try std.testing.expectEqualStrings("/tmp/wt", mutationTarget("git -C/tmp/wt reset HEAD~1").?);
+ try std.testing.expectEqualStrings("/tmp/wt", mutationTarget("cd /tmp/wt && git stash").?);
+ try std.testing.expectEqualStrings("sub", mutationTarget("cd sub && git commit -m x").?);
+ try std.testing.expect(mutationTarget("git cherry-pick abc") == null);
+ try std.testing.expect(mutationTarget("git -c user.name=x commit") == null);
+ try std.testing.expect(mutationTarget("cd \"$wt\" && git stash") == null);
+ try std.testing.expect(mutationTarget("cd /tmp/wt*") == null);
+}
diff --git a/src/worktree_lease.zig b/src/worktree_lease.zig
index aedec970..1fa5c9a7 100644
--- a/src/worktree_lease.zig
+++ b/src/worktree_lease.zig
@@ -179,6 +179,16 @@ pub fn gitCommonDir(gpa: Allocator, io: Io, arena: Allocator) []const u8 {
return revParse(gpa, io, arena, "--git-common-dir");
}
+fn revParseAt(gpa: Allocator, io: Io, arena: Allocator, dir: []const u8, flag: []const u8) []const u8 {
+ const r = runCapped(gpa, io, &.{ "git", "-C", dir, "rev-parse", "--path-format=absolute", flag }, 8192, 8192, 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 "";
+}
+
/// Live canonical identity for this process's working directory.
pub fn currentIdentity(gpa: Allocator, io: Io, arena: Allocator) Identity {
const git_dir = revParse(gpa, io, arena, "--git-dir");
@@ -191,6 +201,19 @@ pub fn currentIdentity(gpa: Allocator, io: Io, arena: Allocator) Identity {
return canonicalIdentity(git_dir, common, cwd);
}
+/// Identity of an explicit path (`git -C` / `cd` target), not the caller cwd.
+pub fn identityAt(gpa: Allocator, io: Io, arena: Allocator, path: []const u8) Identity {
+ if (path.len == 0) return .{};
+ const git_dir = revParseAt(gpa, io, arena, path, "--git-dir");
+ const common = revParseAt(gpa, io, arena, path, "--git-common-dir");
+ var buf: [4096]u8 = undefined;
+ const cwd = blk: {
+ const n = Io.Dir.cwd().realPathFile(io, path, &buf) catch break :blk path;
+ break :blk arena.dupe(u8, buf[0..n]) catch path;
+ };
+ return canonicalIdentity(git_dir, common, cwd);
+}
+
pub fn identityLine(arena: Allocator, id: Identity) []const u8 {
const kind = switch (id.kind) {
.main_checkout => "main checkout",
@@ -310,3 +333,37 @@ test "identityLine: says which kind of checkout, and stays honest when unknown"
try std.testing.expect(std.mem.indexOf(u8, identityLine(a, .{ .id = "/repo/.git/worktrees/w", .kind = .linked_worktree }), "linked worktree") != null);
try std.testing.expect(std.mem.indexOf(u8, identityLine(a, .{}), "unknown") != null);
}
+
+fn initBareRepo(gpa: Allocator, io: Io, path: []const u8) !void {
+ const r = try runCapped(gpa, io, &.{ "git", "init", "-q", path }, 4096, 4096, 15_000);
+ defer {
+ gpa.free(r.stdout);
+ gpa.free(r.stderr);
+ }
+ if (!ranOk(r)) return error.GitInitFailed;
+}
+
+test "#851 identityAt distinguishes isolated checkouts and matches a subdirectory" {
+ const io = std.testing.io;
+ const gpa = std.testing.allocator;
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const root = try tmp.dir.realPathFileAlloc(io, ".", a);
+ const path_a = try std.fmt.allocPrint(a, "{s}/a", .{root});
+ const path_b = try std.fmt.allocPrint(a, "{s}/b", .{root});
+ const path_sub = try std.fmt.allocPrint(a, "{s}/a/src", .{root});
+ try tmp.dir.createDirPath(io, "a/src");
+ try tmp.dir.createDirPath(io, "b");
+ try initBareRepo(gpa, io, path_a);
+ try initBareRepo(gpa, io, path_b);
+ const id_a = identityAt(gpa, io, a, path_a);
+ const id_b = identityAt(gpa, io, a, path_b);
+ const id_sub = identityAt(gpa, io, a, path_sub);
+ try std.testing.expect(id_a.id.len > 0);
+ try std.testing.expect(id_b.id.len > 0);
+ try std.testing.expect(!std.mem.eql(u8, id_a.id, id_b.id));
+ try std.testing.expectEqualStrings(id_a.id, id_sub.id);
+}