graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(edit): resolve writes against the selected worktree (#747)
Rach0889701ab6b7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 058873e3..39b9f5c6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -58,6 +58,9 @@ current is part of cutting a release.width change instead of asserting on the first (possibly stale) repaint.- `#748`: an error-only SSE event is reported as that error, not retriedas a truncated gateway body.+- `#747`: `edit_file` / `write_file` / `read_file` share one absolute path+ from the posix session cwd (not a stale Io cwd or a disagreeing display+ cwd), so a worktree switch cannot report success on the previous tree.- `#761`: `read_file` optional fields stay out of `required[]` (path only).Null or empty `contains` / null bounds / null `compact` are a whole-fileread, so strict tool calling can omit unused mutually exclusive fields.diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.jsonindex b90abef6..7c8d2f91 100644--- a/scripts/eval/tier1-manifest.json+++ b/scripts/eval/tier1-manifest.json@@ -72,6 +72,11 @@"id": "sse-error-not-truncated","test": "#748: error-only OpenAI SSE is an error envelope, not a missing stream","why": "#748: an explicit streamed error was retried as a truncated gateway body."+ },+ {+ "id": "edit-selected-worktree",+ "test": "#747: editing the same relative name after a tree switch lands on the selected root",+ "why": "#747: an edit could report success while the selected worktree stayed unchanged."}],"docs_only_paths": [diff --git a/src/cli.zig b/src/cli.zigindex dd460608..647bd5b1 100644--- a/src/cli.zig+++ b/src/cli.zig@@ -30,6 +30,7 @@ pub const changelog_text =\\ • background-agent handles survive an interrupted API turn (#753)\\ • prompt-cache affinity is the git root, not the leaf cwd\\ • Meta tool_choice is auto-only; error-only SSE is not a truncate-retry (#751 #748)+ \\ • worktree edits land on the selected root (#747)\\\\0.0.288\\ • GPT-6 Astra is the default Codex model: mid-turn steer, vision, hosted search, OpenAI compactdiff --git a/src/codedbpro_paths.zig b/src/codedbpro_paths.zigindex 585ccdd3..de0d62be 100644--- a/src/codedbpro_paths.zig+++ b/src/codedbpro_paths.zig@@ -67,6 +67,27 @@ pub fn callerError(text: []const u8) bool {return false;}+/// Absolute path for a model-supplied relative file, against the selected+/// worktree. Prefer `agent_cwd`, then the posix process cwd (`/workspace use`+/// chdirs this), then the session display cwd. Never `Io.Dir.cwd()`:+/// Threaded Io can stay on the previous tree after `chdir` (#721 / #747).+/// Prefer posix over `g_cwd_display`: display can be a stale `realPath` of+/// Io cwd while the child was launched with a different posix cwd (tier-2+/// `cwd=` vs inherited `PWD`).+pub fn sessionAbs(gpa: Allocator, io: Io, agent_cwd: ?[]const u8, path: []const u8) ![]u8 {+ if (std.fs.path.isAbsolute(path)) return gpa.dupe(u8, path);+ if (agent_cwd) |worktree| return std.fs.path.resolve(gpa, &.{ worktree, path });+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ if (std.process.currentPath(io, &buf)) |n| {+ return std.fs.path.resolve(gpa, &.{ buf[0..n], path });+ } else |_| {+ const display = @import("main.zig").g_cwd_display;+ if (display.len > 0 and std.fs.path.isAbsolute(display))+ return std.fs.path.resolve(gpa, &.{ display, path });+ return std.fs.path.resolve(gpa, &.{path});+ }+}+/// CodeDB Pro's resident daemon has one launch cwd that can outlive and differ/// from the Graff session using it. Normalize path-bearing calls at the client/// boundary so relative model arguments keep their documented session-cwd@@ -101,14 +122,7 @@ pub fn prepareInput(gpa: Allocator, io: Io, agent_cwd: ?[]const u8, tool: []consreturn .{ .value = working, .owned_object = owned_object };}- var cwd_buf: [4096]u8 = undefined;- const base = if (agent_cwd) |worktree|- worktree- else blk: {- const n = try Io.Dir.cwd().realPathFile(io, ".", &cwd_buf);- break :blk cwd_buf[0..n];- };- const absolute = try std.fs.path.resolve(gpa, &.{ base, path_value.string });+ const absolute = try sessionAbs(gpa, io, agent_cwd, path_value.string);errdefer gpa.free(absolute);var object: std.json.ObjectMap = .empty;diff --git a/src/edit_batch.zig b/src/edit_batch.zigindex 2c563f86..5f0ea651 100644--- a/src/edit_batch.zig+++ b/src/edit_batch.zig@@ -30,9 +30,9 @@ pub fn execBatch(ctx: ToolCtx, input: Value) !ToolOutput {const list = input.object.get("edits").?.array;if (list.items.len == 0) return .{ .text = try gpa.dupe(u8, "edits must contain at least one span"), .is_error = true };- // #276 P0-1, same as execEdit: resolve under the agent's worktree.- const resolved: []const u8 = if (ctx.agent_cwd) |base| try std.fmt.allocPrint(gpa, "{s}/{s}", .{ base, path }) else path;- defer if (ctx.agent_cwd != null) gpa.free(resolved);+ // #747: same absolute selected-tree path as execEdit (write + verify).+ const resolved = try @import("codedbpro_paths.zig").sessionAbs(gpa, ctx.io, ctx.agent_cwd, path);+ defer gpa.free(resolved);var applied: usize = 0;for (list.items, 0..) |item, i| {diff --git a/src/edit_verify.zig b/src/edit_verify.zigindex 5cd2e9f9..3d3644b1 100644--- a/src/edit_verify.zig+++ b/src/edit_verify.zig@@ -187,9 +187,9 @@ pub fn execEdit(ctx: ToolCtx, input: Value) !ToolOutput {const all = tools.json_args.flag(input, "replace_all");if (old.len == 0) return .{ .text = try gpa.dupe(u8, "old_string must not be empty"), .is_error = true };- // #276 P0-1: resolve under the agent's isolated worktree when set.- const resolved: []const u8 = if (ctx.agent_cwd) |base| try std.fmt.allocPrint(gpa, "{s}/{s}", .{ base, path }) else path;- defer if (ctx.agent_cwd != null) gpa.free(resolved);+ // #747: write and verify share one absolute path (selected tree).+ const resolved = try @import("codedbpro_paths.zig").sessionAbs(gpa, ctx.io, ctx.agent_cwd, path);+ defer gpa.free(resolved);return applyEdit(ctx, path, resolved, old, new, all);}diff --git a/src/edit_worktree_tests.zig b/src/edit_worktree_tests.zignew file mode 100644index 00000000..e220c122--- /dev/null+++ b/src/edit_worktree_tests.zig@@ -0,0 +1,143 @@+//! #747: after a workspace switch, edit_file must write the selected tree.+//!+//! `/workspace use` posix-chdirs. Write and verify must share one absolute+//! path from that cwd (`sessionAbs`), not a stale Threaded-Io cwd (#721)+//! and not a `g_cwd_display` that can disagree with posix (tier-2 `cwd=`).++const std = @import("std");+const builtin = @import("builtin");+const Io = std.Io;++const edit_verify = @import("edit_verify.zig");+const codedbpro_paths = @import("codedbpro_paths.zig");+const main_mod = @import("main.zig");++fn tmpAbs(io: Io, dir: anytype) ![]u8 {+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const n = dir.dir.realPath(io, &buf) catch return error.SkipZigTest;+ return std.testing.allocator.dupe(u8, buf[0..n]);+}++fn chdirAbs(path: []const u8) !void {+ const z = try std.testing.allocator.dupeSentinel(u8, path, 0);+ defer std.testing.allocator.free(z);+ if (std.posix.system.chdir(z.ptr) != 0) return error.ChdirFailed;+}++test "#747: editing the same relative name after a tree switch lands on the selected root" {+ if (builtin.os.tag == .windows) return error.SkipZigTest;+ const gpa = std.testing.allocator;+ const io = std.testing.io;++ var here_buf: [std.fs.max_path_bytes]u8 = undefined;+ const here_n = std.process.currentPath(io, &here_buf) catch return error.SkipZigTest;+ const here = try gpa.dupe(u8, here_buf[0..here_n]);+ defer gpa.free(here);+ defer chdirAbs(here) catch {};++ var dir_a = std.testing.tmpDir(.{});+ defer dir_a.cleanup();+ var dir_b = std.testing.tmpDir(.{});+ defer dir_b.cleanup();+ try dir_a.dir.writeFile(io, .{ .sub_path = "note.txt", .data = "alpha\n" });+ try dir_b.dir.writeFile(io, .{ .sub_path = "note.txt", .data = "beta\n" });+ const path_a = try tmpAbs(io, &dir_a);+ defer gpa.free(path_a);+ const path_b = try tmpAbs(io, &dir_b);+ defer gpa.free(path_b);++ var client: std.http.Client = undefined;+ const ctx = edit_verify.testCtx(&client);++ var a_obj: std.json.ObjectMap = .empty;+ defer a_obj.deinit(gpa);+ try a_obj.put(gpa, "path", .{ .string = "note.txt" });+ try a_obj.put(gpa, "old_string", .{ .string = "alpha\n" });+ try a_obj.put(gpa, "new_string", .{ .string = "ALPHA\n" });++ try chdirAbs(path_a);+ const out_a = try edit_verify.execEdit(ctx, .{ .object = a_obj });+ defer gpa.free(out_a.text);+ try std.testing.expect(!out_a.is_error);++ var b_obj: std.json.ObjectMap = .empty;+ defer b_obj.deinit(gpa);+ try b_obj.put(gpa, "path", .{ .string = "note.txt" });+ try b_obj.put(gpa, "old_string", .{ .string = "beta\n" });+ try b_obj.put(gpa, "new_string", .{ .string = "BETA\n" });++ try chdirAbs(path_b);+ const out_b = try edit_verify.execEdit(ctx, .{ .object = b_obj });+ defer gpa.free(out_b.text);+ try std.testing.expect(!out_b.is_error);++ try chdirAbs(here);+ const on_a = try dir_a.dir.readFileAlloc(io, "note.txt", gpa, .limited(64));+ defer gpa.free(on_a);+ const on_b = try dir_b.dir.readFileAlloc(io, "note.txt", gpa, .limited(64));+ defer gpa.free(on_b);+ try std.testing.expectEqualStrings("ALPHA\n", on_a);+ try std.testing.expectEqualStrings("BETA\n", on_b);+}++test "#747: writeFile+readFileAlloc of sessionAbs agree after a posix chdir" {+ if (builtin.os.tag == .windows) return error.SkipZigTest;+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ var here_buf: [std.fs.max_path_bytes]u8 = undefined;+ const here_n = std.process.currentPath(io, &here_buf) catch return error.SkipZigTest;+ const here = try gpa.dupe(u8, here_buf[0..here_n]);+ defer gpa.free(here);+ defer chdirAbs(here) catch {};++ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ const root = try tmpAbs(io, &tmp);+ defer gpa.free(root);+ try chdirAbs(root);++ const abs = try codedbpro_paths.sessionAbs(gpa, io, null, "settings.py");+ defer gpa.free(abs);+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = abs, .data = "TIMEOUT = 30\n" });+ const via_abs = Io.Dir.cwd().readFileAlloc(io, abs, gpa, .limited(64)) catch |err| {+ std.debug.print("readFileAlloc({s}) failed: {t}\n", .{ abs, err });+ return err;+ };+ defer gpa.free(via_abs);+ try std.testing.expectEqualStrings("TIMEOUT = 30\n", via_abs);+ const via_rel = try Io.Dir.cwd().readFileAlloc(io, "settings.py", gpa, .limited(64));+ defer gpa.free(via_rel);+ try std.testing.expectEqualStrings("TIMEOUT = 30\n", via_rel);++ var client: std.http.Client = undefined;+ const ctx = edit_verify.testCtx(&client);+ var obj: std.json.ObjectMap = .empty;+ defer obj.deinit(gpa);+ try obj.put(gpa, "path", .{ .string = "settings.py" });+ try obj.put(gpa, "old_string", .{ .string = "TIMEOUT = 30" });+ try obj.put(gpa, "new_string", .{ .string = "TIMEOUT = 60" });+ const out = try edit_verify.execEdit(ctx, .{ .object = obj });+ defer gpa.free(out.text);+ try std.testing.expect(!out.is_error);+}++test "#747: sessionAbs of a relative name follows the selected cwd, not a sibling tree" {+ if (builtin.os.tag == .windows) return error.SkipZigTest;+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ const a = try codedbpro_paths.sessionAbs(gpa, io, "/tmp/graff-747-tree-a", "note.txt");+ defer gpa.free(a);+ const b = try codedbpro_paths.sessionAbs(gpa, io, "/tmp/graff-747-tree-b", "note.txt");+ defer gpa.free(b);+ try std.testing.expect(!std.mem.eql(u8, a, b));+ try std.testing.expect(std.mem.endsWith(u8, a, "note.txt"));+ try std.testing.expect(std.mem.endsWith(u8, b, "note.txt"));++ // A stale display cwd must not beat posix cwd (tier-2 HOME/PWD split).+ const saved = main_mod.g_cwd_display;+ defer main_mod.g_cwd_display = saved;+ main_mod.g_cwd_display = "/tmp/graff-747-tree-a";+ const via_posix = try codedbpro_paths.sessionAbs(gpa, io, null, "note.txt");+ defer gpa.free(via_posix);+ try std.testing.expect(std.mem.indexOf(u8, via_posix, "graff-747-tree-a") == null);+}diff --git a/src/exec.zig b/src/exec.zigindex 478187a2..a8d6c4b7 100644--- a/src/exec.zig+++ b/src/exec.zig@@ -291,12 +291,9 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {if (want_compact) {if (try codedb_exec.maybeCompactRead(ctx, path, start_line, end_line)) |out| return out;}- // #276 P0-1: resolve under the agent's isolated worktree when set —- // path itself stays relative (that's the agent's own view, used in- // every message below); only the actual syscall targets the resolved- // absolute path.- const resolved: []const u8 = if (ctx.agent_cwd) |base| try std.fmt.allocPrint(gpa, "{s}/{s}", .{ base, path }) else path;- defer if (ctx.agent_cwd != null) gpa.free(resolved);+ // #747: same selected-tree absolute path as edit_file (sessionAbs).+ const resolved = try codedbpro_paths.sessionAbs(gpa, io, ctx.agent_cwd, path);+ defer gpa.free(resolved);const outcome = read_file.read(io, gpa, .cwd(), resolved, start_line, end_line, contains) catch |err| {if (fsErrorText(gpa, .read, path, err)) |t| return .{ .text = t, .is_error = true };return err;@@ -342,11 +339,10 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {const path = strField(input, "path") orelse return missingArg(gpa, "path");const content = strField(input, "content") orelse return missingArg(gpa, "content");if (!confinedPath(path) or !noSymlinkEscape(io, path, ctx.agent_cwd)) return outsideCwd(gpa, path);- // #276 P0-1: resolve under the agent's isolated worktree when set.- // (snapshots are root-only — `ctx.agent_cwd` is only ever set for a- // subagent, so the branch below never runs together with isolation.)- const resolved: []const u8 = if (ctx.agent_cwd) |base| try std.fmt.allocPrint(gpa, "{s}/{s}", .{ base, path }) else path;- defer if (ctx.agent_cwd != null) gpa.free(resolved);+ // #747: share sessionAbs with edit_file so a write cannot land in+ // posix cwd while the next edit looks at a stale display cwd.+ const resolved = try codedbpro_paths.sessionAbs(gpa, io, ctx.agent_cwd, path);+ defer gpa.free(resolved);// #337: a write_file racing an edit_file on the same path in the same// assistant turn (agent_tools.zig runs them concurrently) would drop// one of the two. Same stripe as edit_file, so they take turns.diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 61f4878e..1b0015df 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -370,4 +370,5 @@ test {_ = @import("update_tests.zig");_ = @import("mcp_elicitation.zig"); // #768: Computer Use form elicitation_ = @import("skill_runtime_adapter.zig"); // #768: read-only get_app_state adapter+ _ = @import("edit_worktree_tests.zig"); // #747: edit lands on the selected worktree}