graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Resolve file edit checkpoints against the target worktree
justrachcc46a0d507df
diff --git a/docs/adr/0118-file-edits-check-target-worktree.md b/docs/adr/0118-file-edits-check-target-worktree.mdnew file mode 100644index 00000000..843b4128--- /dev/null+++ b/docs/adr/0118-file-edits-check-target-worktree.md@@ -0,0 +1,26 @@+# 0118. File edits checkpoint the target worktree++Status: accepted 2026-09-15++## Context++A file tool can run from one checkout while editing a nested linked worktree.+Using only the caller's presence identity incorrectly warns about parent peers+and misses peers that actually share the target tree.++## Decision++Resolve file-tool paths using the same session-relative rules as the write.+Find the nearest existing parent directory for new files and resolve its Git+worktree identity. For a different Git worktree, checkpoint that identity's+live peers. For the caller's tree, preserve its announced identity, including+when Git was initialized after startup. Unresolved and non-Git targets retain+the conservative caller checkpoint. Approval and path-confinement checks stay+in place.++## Consequences++Disjoint nested worktrees no longer consume parent-peer acknowledgments.+A target with its own live peer still warns before the first write. The two+`peer-checkpoint-file-target-*` behavior cases use real linked worktrees and+live harness peers to verify both directions; both fail on the former path.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 429735ae..bb8dc8d6 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -126,6 +126,7 @@ record only when you need the evidence or the edge cases.| [0113](0113-clipboard-errors-need-evidence.md) | Direct AppKit clipboard failures need typed evidence; generic helper failures never imply Automation permission. || [0114](0114-live-citations-are-terminal-presentation.md) | Live terminal citations use per-stream display filters with independent reasoning state; structured JSON/ACP output stays unchanged. || [0116](0116-informational-turns-have-bounded-scope.md) | Summary turns gather bounded evidence; coding completion requirements apply to requested changes. |+| [0118](0118-file-edits-check-target-worktree.md) | File edits checkpoint the target Git worktree; unresolved paths retain the caller checkpoint. |## When to write onediff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonlindex b10aab47..cbdd0ccb 100644--- a/evals/harness_behavior.jsonl+++ b/evals/harness_behavior.jsonl@@ -92,3 +92,5 @@{"id": "informational-mixed-request-keeps-mutation", "why": "#884: a mixed fix-and-summary request must still read, apply the root-cause change, and verify in the fixture project.", "prompt": "Fix slug.py so whitespace-only labels return an empty string, add a regression test, run the project tests, and summarize the change.", "workspace_seed": {"slug.py": "def slug(label):\n result = \"-\".join(label.strip().lower().split())\n if not result:\n raise ValueError(\"empty label\")\n return result\n", "test_slug.py": "import unittest\nfrom slug import slug\n\nclass SlugTests(unittest.TestCase):\n def test_words(self):\n self.assertEqual(slug(\"Hello World\"), \"hello-world\")\n", "README.md": "Run tests with python3 -m unittest discover.\n"}, "script": [{"tool": "read_file", "arguments": {"path": "slug.py"}}, {"tool": "read_file", "arguments": {"path": "test_slug.py"}}, {"tool": "read_file", "arguments": {"path": "README.md"}}, {"tool": "edit_file", "arguments": {"path": "slug.py", "old_string": " if not result:\n raise ValueError(\"empty label\")\n", "new_string": ""}}, {"tool": "edit_file", "arguments": {"path": "test_slug.py", "old_string": "import unittest\nfrom slug import slug\n\nclass SlugTests(unittest.TestCase):\n def test_words(self):\n self.assertEqual(slug(\"Hello World\"), \"hello-world\")\n", "new_string": "import unittest\nfrom slug import slug\n\nclass SlugTests(unittest.TestCase):\n def test_words(self):\n self.assertEqual(slug(\"Hello World\"), \"hello-world\")\n\n def test_whitespace_only(self):\n self.assertEqual(slug(\" \\t\\n \"), \"\")\n"}}, {"tool": "bash", "arguments": {"command": "python3 -m unittest discover"}}, {"text": "Whitespace-only labels now return an empty string. Both project tests passed."}], "assert": [{"events_at_least": {"match": {"type": "tool_call", "name": "read_file"}, "count": 3}}, {"events_at_least": {"match": {"type": "tool_call", "name": "edit_file"}, "count": 2}}, {"events_at_most": {"match": {"type": "tool_call_finished", "is_error": true}, "count": 0}}, {"request_contains": {"index": -1, "text": "Ran 2 tests"}}, {"request_contains": {"index": -1, "text": "OK"}}, {"request_lacks": {"index": -1, "text": "Summary scope checkpoint:"}}, {"final_text_contains": "Both project tests passed."}]}{"id": "internal-budget-note-keeps-wire-clean", "why": "#912: internal budget reminders must remain effective without exposing saved notification metadata on the model wire.", "args": ["--max-model-calls", "2"], "prompt": "Read the checklist and summarize its current state.", "script": [{"tool": "todo_read", "arguments": {}}, {"text": "The checklist is empty."}], "assert": [{"request_contains": {"index": -1, "text": "[budget landing]"}}, {"request_contains": {"index": -1, "text": "Read the checklist and summarize its current state."}}, {"request_lacks": {"index": -1, "text": "_graff_origin"}}, {"final_text_contains": "The checklist is empty."}]}{"id": "cli-outside-path-recovers-through-shell", "why": "#902/#903: a missing PATH lookup must prompt executable discovery instead of declaring the CLI absent or abandoning the shell workflow.", "env": {"PATH": "/usr/bin:/bin"}, "prompt": "Use the installed fixture CLI to file the local test issue and verify its receipt.", "workspace_seed": {"bin/graff_fixture_cli": "#!/bin/sh\n[ \"$1 $2\" = \"issue create\" ] || exit 2\nprintf \"FILED_LOCALLY\\n\" > \"$HOME/issue-receipt.txt\"\nprintf \"CLI_OPERATION_COMPLETE\\n\"\n"}, "script": [{"tool": "bash", "arguments": {"command": "chmod +x \"$HOME/bin/graff_fixture_cli\""}}, {"tool": "bash", "arguments": {"command": "graff_fixture_cli issue create --title \"Fixture issue\""}}, {"tool": "bash", "arguments": {"command": "if [ -x \"$HOME/bin/graff_fixture_cli\" ]; then \"$HOME/bin/graff_fixture_cli\" issue create --title \"Fixture issue\"; fi"}}, {"tool": "bash", "arguments": {"command": "test -s \"$HOME/issue-receipt.txt\" && cat \"$HOME/issue-receipt.txt\""}}, {"text": "The CLI operation completed."}], "assert": [{"request_contains": {"index": 2, "text": "[CLI lookup]"}}, {"request_contains": {"index": 2, "text": "does not prove the executable is absent"}}, {"request_contains": {"index": -1, "text": "CLI_OPERATION_COMPLETE"}}, {"events_at_least": {"match": {"type": "tool_call", "name": "bash"}, "count": 4}}, {"events_at_most": {"match": {"type": "tool_call"}, "count": 4}}, {"final_text_contains": "The CLI operation completed."}, {"request_contains": {"index": -1, "text": "FILED_LOCALLY"}}]}+{"id": "peer-checkpoint-file-target-worktree", "why": "File edits in a nested linked worktree must not inherit parent-checkout peer warnings; actual file changes still land.", "live_peer": true, "args": [], "prompt": "Create an isolated nested worktree, write its notes.txt, and change hello to updated.", "script": [{"tool": "write_file", "arguments": {"path": "nested/notes.txt", "content": "hello"}}, {"tool": "edit_file", "arguments": {"path": "nested/notes.txt", "old_string": "hello", "new_string": "updated"}}, {"tool": "read_file", "arguments": {"path": "nested/notes.txt"}}, {"text": "Updated the isolated worktree file."}], "assert": [{"event": {"type": "tool_call_finished", "name": "write_file", "is_error": false}}, {"event": {"type": "tool_call_finished", "name": "edit_file", "is_error": false}}, {"events_at_most": {"match": {"type": "tool_call_finished", "name": "write_file", "is_error": true}, "count": 0}}, {"events_at_most": {"match": {"type": "tool_call_finished", "name": "edit_file", "is_error": true}, "count": 0}}, {"request_contains": {"index": 3, "text": "updated"}}], "nested_worktree": true}+{"id": "peer-checkpoint-file-target-owner", "why": "An edit targeting a nested linked worktree must checkpoint that target worktree owner even when the caller uses the parent checkout.", "nested_worktree": true, "live_peer": true, "peer_in_nested_worktree": true, "args": [], "prompt": "Write hello to nested/notes.txt; acknowledge any shared-tree checkpoint before retrying.", "script": [{"tool": "write_file", "arguments": {"path": "nested/notes.txt", "content": "hello"}}, {"tool": "write_file", "arguments": {"path": "nested/notes.txt", "content": "hello"}}, {"text": "Created after the target-owner checkpoint."}], "assert": [{"events_at_least": {"match": {"type": "tool_call_finished", "name": "write_file", "is_error": true}, "count": 1}}, {"events_at_most": {"match": {"type": "tool_call_finished", "name": "write_file", "is_error": true}, "count": 1}}, {"event": {"type": "tool_call_finished", "name": "write_file", "is_error": false}}, {"request_contains": {"index": 1, "text": "shared-tree checkpoint"}}]}diff --git a/scripts/eval-tier2.py b/scripts/eval-tier2.pyindex b4bf5e2c..a50fbf00 100644--- a/scripts/eval-tier2.py+++ b/scripts/eval-tier2.py@@ -145,6 +145,14 @@ def execute(case: dict[str, Any], graff: str, port: int,dest = pathlib.Path(workspace) / reldest.parent.mkdir(parents=True, exist_ok=True)dest.write_text(content, encoding="utf-8")+ # Real linked-worktree topology for ownership/checkpoint cases.+ if case.get("nested_worktree"):+ for command in [+ ["git", "init", "-q"],+ ["git", "-c", "user.name=Fixture", "-c", "[email protected]", "commit", "--allow-empty", "-qm", "fixture"],+ ["git", "worktree", "add", "--detach", "nested"],+ ]:+ subprocess.run(command, cwd=workspace, env=env, check=True, capture_output=True)# A genuinely live second graff in the same workspace, for #469# presence cases: the checkpoint only exists while a co-resident# session does, and a real peer announces (and probes) better than@@ -152,7 +160,7 @@ def execute(case: dict[str, Any], graff: str, port: int,if case.get("live_peer"):peer = subprocess.Popen([graff, "--json", "--yolo", "--model", model or "lmstudio"],- cwd=workspace, env=env, stdin=subprocess.PIPE,+ cwd=str(pathlib.Path(workspace) / "nested") if case.get("peer_in_nested_worktree") else workspace, env=env, stdin=subprocess.PIPE,stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, text=True)live_dir = pathlib.Path(workspace) / ".graff" / "live"deadline = time.time() + 30@@ -162,6 +170,8 @@ def execute(case: dict[str, Any], graff: str, port: int,if peer.poll() is not None:breaktime.sleep(0.1)+ if peer.poll() is not None or not live_dir.is_dir() or not any(live_dir.glob("*.json")):+ raise RuntimeError("Live-peer fixture did not announce before the deadline")argv = [graff, "--json", "--yolo", "--model", model or "lmstudio"]if provider:argv += ["--subagent-provider", provider]diff --git a/src/agent_tool_gate.zig b/src/agent_tool_gate.zigindex 4e825c9e..e40281fc 100644--- a/src/agent_tool_gate.zig+++ b/src/agent_tool_gate.zig@@ -243,16 +243,15 @@ pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {} else if (std.mem.eql(u8, call.name, "write_file") or std.mem.eql(u8, call.name, "edit_file")) {// #469: the same once-per-peer checkpoint guards the files themselves —// the incident's other vector was editing a file a live peer had open.- if (presence.gateCheck(self.io, self.arena)) |checkpoint| return .{- .text = checkpoint,- .is_error = true,- };- if (approvals.allowedExact(self.io, call.name)) return null;- key = call.name;const path = if (call.input == .object)(if (call.input.object.get("path")) |p| (if (p == .string) p.string else "?") else "?")else"?";+ const target = if (presence.hasCheckpointContext()) @import("file_worktree.zig").identity(self.gpa, self.io, self.arena, self.agent_cwd, path) else null;+ const checkpoint = if (target) |id| presence.gateCheckIdentity(self.io, self.arena, id) else presence.gateCheck(self.io, self.arena);+ if (checkpoint) |text| return .{ .text = text, .is_error = true };+ if (approvals.allowedExact(self.io, call.name)) return null;+ key = call.name;prompt_line = std.fmt.bufPrint(&line_buf, "{s} {s}", .{ call.name, path }) catch call.name;} else if (std.mem.eql(u8, call.name, "learn_candidate")) {if (!learning_privacy.allowsAggregate()) {diff --git a/src/file_worktree.zig b/src/file_worktree.zignew file mode 100644index 00000000..e87fad36--- /dev/null+++ b/src/file_worktree.zig@@ -0,0 +1,66 @@+//! Resolve file-edit ownership from the target directory, including new files.+const std = @import("std");+const lease = @import("worktree_lease.zig");++/// Unknown/non-Git targets retain the caller's conservative checkpoint.+/// Use the same session-relative path resolution as the actual file tools.+pub fn identity(gpa: std.mem.Allocator, io: std.Io, arena: std.mem.Allocator, cwd: ?[]const u8, file: []const u8) ?[]const u8 {+ if (file.len == 0 or std.mem.eql(u8, file, "?")) return null;+ const absolute = @import("codedbpro_paths.zig").sessionAbs(arena, io, cwd, file) catch return null;+ var parent = std.fs.path.dirname(absolute) orelse return null;+ // New files can have not-yet-created parent directories. Stop at the+ // nearest existing directory; permission errors must not skip boundaries.+ while (true) {+ var dir = std.Io.Dir.cwd().openDir(io, parent, .{}) catch |err| switch (err) {+ error.FileNotFound => {+ const next = std.fs.path.dirname(parent) orelse return null;+ if (std.mem.eql(u8, next, parent)) return null;+ parent = next;+ continue;+ },+ else => return null,+ };+ dir.close(io);+ const at = lease.identityAt(gpa, io, arena, parent);+ if (at.kind == .not_git or at.id.len == 0) return null;+ const source = @import("codedbpro_paths.zig").sessionAbs(arena, io, cwd, ".") catch return null;+ const mine = lease.identityAt(gpa, io, arena, source);+ // Preserve the announced identity when git init occurred after startup.+ if (std.mem.eql(u8, at.id, mine.id)) return null;+ return at.id;+ }+}++test "file checkpoints distinguish nested linked worktrees from ordinary directories" {+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ 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 linked = try std.fs.path.join(a, &.{ root, "nested" });+ const runner = @import("process_runner.zig");+ const commands = [_][]const []const u8{+ &.{ "git", "init", "-q", root },+ &.{ "git", "-C", root, "-c", "user.name=Fixture", "-c", "[email protected]", "commit", "--allow-empty", "-qm", "fixture" },+ &.{ "git", "-C", root, "worktree", "add", "--detach", linked },+ };+ for (commands) |argv| {+ const result = try runner.runCapped(gpa, io, argv, 4096, 4096, 15_000);+ defer gpa.free(result.stdout);+ defer gpa.free(result.stderr);+ try std.testing.expect(runner.ranOk(result));+ }+ const linked_id = lease.identityAt(gpa, io, a, linked);+ try std.testing.expectEqual(lease.Identity.Kind.linked_worktree, linked_id.kind);+ const existing = try std.fs.path.join(a, &.{ linked, "existing.txt" });+ try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = existing, .data = "before" });+ try std.testing.expectEqualStrings(linked_id.id, identity(gpa, io, a, root, existing).?);+ try std.testing.expectEqualStrings(linked_id.id, identity(gpa, io, a, root, "nested/new/deep/file.txt").?);+ try std.testing.expect(identity(gpa, io, a, root, "ordinary/new/file.txt") == null);+ try std.testing.expect(identity(gpa, io, a, linked, "new/file.txt") == null);+ // Unknown input keeps the conservative original checkpoint.+ try std.testing.expect(identity(gpa, io, a, root, "") == null);+}diff --git a/src/main.zig b/src/main.zigindex 34c349fb..364a1b85 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("mcp_names.zig"), @import("workspace_history.zig") };+ _ = .{ @import("mcp_names.zig"), @import("workspace_history.zig"), @import("file_worktree.zig") };}diff --git a/src/presence.zig b/src/presence.zigindex 9ddd2b02..8ccd2522 100644--- a/src/presence.zig+++ b/src/presence.zig@@ -302,13 +302,20 @@ pub fn noteLabelsFrom(io: Io, gpa: Allocator, arena: Allocator, title: ?[]const/// peer ACKs it, so the re-issued command runs and one process checkpoints at/// most once per peer — awareness is the goal, not a tollbooth.pub fn gateCheck(io: Io, arena: Allocator) ?[]const u8 {- if (no_local_tools.lean) return null;- const dir_path = g_dir orelse return null;- if (g_identity.len == 0) return null;+ return gateCheckIdentity(io, arena, g_identity);+}++pub fn hasCheckpointContext() bool {+ return !no_local_tools.lean and g_dir != null and g_identity.len > 0;+}++pub fn gateCheckIdentity(io: Io, arena: Allocator, identity: []const u8) ?[]const u8 {+ if (!hasCheckpointContext()) return null;+ const dir_path = g_dir.?;var dir = Io.Dir.cwd().openDir(io, dir_path, .{ .iterate = true }) catch return null;defer dir.close(io);const peers = listPeers(io, arena, dir);- const peer = unackedPeer(peers, g_identity, proc_identity.selfPid(), g_acked[0..g_acked_len]) orelse return null;+ const peer = unackedPeer(peers, identity, proc_identity.selfPid(), g_acked[0..g_acked_len]) orelse return null;if (g_acked_len < g_acked.len) {g_acked[g_acked_len] = ackKey(peer);g_acked_len += 1;