Skip to content

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

Python

feat(edit): batched edit_file — many spans, one call

Rach Pradhandc453bffa87f
diff --git a/src/edit_batch.zig b/src/edit_batch.zig
new file mode 100644
index 00000000..2c563f86
--- /dev/null
+++ b/src/edit_batch.zig
@@ -0,0 +1,92 @@
+//! Batched edit_file: several spans, one call (#476 — the apply_patch
+//! mechanic from the opencode session anatomy: their feature run paid 2
+//! patch calls where graff paid 8-10 single-span edit_file calls; one
+//! batched call per file is the 1:1). Spans apply SEQUENTIALLY through
+//! edit_verify.applyEdit, so each one gets the same lock, drift check,
+//! mode preservation and post-write verify as a single edit. A failing
+//! span stops the batch and the result says how many earlier spans DID
+//! apply — no silent partial state.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const tools = @import("tools.zig");
+const approvals = @import("approvals.zig");
+const edit_verify = @import("edit_verify.zig");
+
+const ToolCtx = tools.ToolCtx;
+const ToolOutput = tools.ToolOutput;
+const Value = std.json.Value;
+
+/// The `edits`-array arm of edit_file; exec.zig routes here when the input
+/// carries a non-null `edits` field. Same confinement and worktree
+/// resolution as edit_verify.execEdit.
+pub fn execBatch(ctx: ToolCtx, input: Value) !ToolOutput {
+ const gpa = ctx.gpa;
+ const path = tools.strField(input, "path") orelse return tools.missingArg(gpa, "path");
+ if (!approvals.confinedPath(path) or !approvals.noSymlinkEscape(ctx.io, path, ctx.agent_cwd))
+ return .{ .text = try std.fmt.allocPrint(gpa, "{s} is outside the working directory — edit_file stays inside it", .{path}), .is_error = true };
+ 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);
+
+ var applied: usize = 0;
+ for (list.items, 0..) |item, i| {
+ if (item != .object) return spanErr(gpa, i, list.items.len, "span is not an object", applied, path);
+ const old = tools.strField(item, "old_string") orelse return spanErr(gpa, i, list.items.len, "missing old_string", applied, path);
+ const new = tools.strField(item, "new_string") orelse return spanErr(gpa, i, list.items.len, "missing new_string", applied, path);
+ if (old.len == 0) return spanErr(gpa, i, list.items.len, "old_string must not be empty", applied, path);
+ const all = tools.json_args.flag(item, "replace_all");
+ const r = try edit_verify.applyEdit(ctx, path, resolved, old, new, all);
+ if (r.is_error) return spanErr(gpa, i, list.items.len, r.text, applied, path);
+ applied += 1;
+ }
+ return .{ .text = try std.fmt.allocPrint(gpa, "applied {d} edit span(s) to {s} (each verified)", .{ applied, path }), .is_error = false };
+}
+
+fn spanErr(gpa: Allocator, idx: usize, total: usize, why: []const u8, applied: usize, path: []const u8) !ToolOutput {
+ const suffix: []const u8 = if (applied > 0)
+ try std.fmt.allocPrint(gpa, " ({d} earlier span(s) DID apply to {s} — read it before retrying)", .{ applied, path })
+ else
+ "";
+ return .{ .text = try std.fmt.allocPrint(gpa, "edit span {d}/{d} failed: {s}{s}", .{ idx + 1, total, why, suffix }), .is_error = true };
+}
+
+test "execBatch: two spans apply in one call; a bad span reports its index and prior applies" {
+ if (@import("builtin").os.tag == .windows) return error.SkipZigTest;
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(io, .{ .sub_path = "f.txt", .data = "alpha one\nbeta two\ngamma three\n" });
+ const rel = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}/f.txt", .{&tmp.sub_path});
+ var client: std.http.Client = undefined;
+ const ctx: tools.ToolCtx = .{ .gpa = a, .io = io, .client = &client, .provider = undefined, .registry = null, .from_sub = false, .approvals = null, .tracer = null };
+
+ var good = try std.json.parseFromSliceLeaky(Value, a,
+ \\{"path":"P","edits":[{"old_string":"one","new_string":"1"},{"old_string":"two","new_string":"2"}]}
+ , .{ .allocate = .alloc_always });
+ good.object.put(a, "path", .{ .string = rel }) catch unreachable;
+ const ok = try execBatch(ctx, good);
+ try std.testing.expect(!ok.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, ok.text, "2 edit span(s)") != null);
+ const data = try tmp.dir.readFileAlloc(io, "f.txt", a, .limited(4096));
+ try std.testing.expect(std.mem.indexOf(u8, data, "alpha 1\nbeta 2") != null);
+
+ var bad = try std.json.parseFromSliceLeaky(Value, a,
+ \\{"path":"P","edits":[{"old_string":"gamma","new_string":"3"},{"old_string":"NOT PRESENT","new_string":"x"}]}
+ , .{ .allocate = .alloc_always });
+ bad.object.put(a, "path", .{ .string = rel }) catch unreachable;
+ const err = try execBatch(ctx, bad);
+ try std.testing.expect(err.is_error);
+ try std.testing.expect(std.mem.indexOf(u8, err.text, "span 2/2") != null);
+ try std.testing.expect(std.mem.indexOf(u8, err.text, "1 earlier span(s) DID apply") != null);
+ const after = try tmp.dir.readFileAlloc(io, "f.txt", a, .limited(4096));
+ try std.testing.expect(std.mem.indexOf(u8, after, "3 three") != null); // span 1 landed
+}
diff --git a/src/edit_verify.zig b/src/edit_verify.zig
index 8026d80e..f7845844 100644
--- a/src/edit_verify.zig
+++ b/src/edit_verify.zig
@@ -426,7 +426,7 @@ test "verdictText names the file, refuses the success wording, and demands a re-
/// Minimal ToolCtx for the file-tool tests: no client, no registry, no
/// approvals — applyEdit touches none of them.
-fn testCtx(client: *std.http.Client) ToolCtx {
+pub fn testCtx(client: *std.http.Client) ToolCtx {
return .{
.gpa = std.testing.allocator,
.io = std.testing.io,
diff --git a/src/exec.zig b/src/exec.zig
index b945ae25..d57dd728 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -65,6 +65,7 @@ const read_file = @import("read_file.zig");
// #337: edit_file's verified write path, plus the file-tool helpers that moved
// out with it (this file is at the 600-line ceiling).
const edit_verify = @import("edit_verify.zig");
+const edit_batch = @import("edit_batch.zig"); // batched edit_file spans (#476)
const fsErrorText = edit_verify.fsErrorText;
const preserveMode = edit_verify.preserveMode;
const hooks = @import("hooks.zig");
@@ -508,7 +509,7 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
// #337: the read/splice/write/VERIFY path lives in edit_verify.zig, where
// the post-edit check sits ON the success path — a write that did not land
// can no longer be reported as `replaced N occurrence(s)`.
- if (std.mem.eql(u8, call.name, "edit_file")) return edit_verify.execEdit(ctx, input);
+ if (std.mem.eql(u8, call.name, "edit_file")) return if (input == .object and input.object.get("edits") != null) edit_batch.execBatch(ctx, input) else edit_verify.execEdit(ctx, input);
if (std.mem.eql(u8, call.name, "write_file")) {
const path = strField(input, "path") orelse return missingArg(gpa, "path");
const content = strField(input, "content") orelse return missingArg(gpa, "content");
diff --git a/src/schema.zig b/src/schema.zig
index 7be01d4b..72e5d202 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -82,9 +82,9 @@ const base_specs = [_]ToolSpec{
},
.{
.name = "edit_file",
- .desc = "Replace an exact string in a file. old_string must match exactly one spot unless replace_all is set. Prefer this over write_file when changing an existing file.",
+ .desc = "Replace exact strings in a file. One span: old_string + new_string (old_string must match exactly one spot unless replace_all is set). Many spans: pass edits, an array of {old_string, new_string, replace_all?} applied in order — PREFER one batched call over several edit_file calls to the same file. Prefer this over write_file when changing an existing file.",
.schema =
- \\{"type": "object", "properties": {"path": {"type": "string"}, "old_string": {"type": "string", "description": "Exact existing text to find"}, "new_string": {"type": "string", "description": "Replacement text"}, "replace_all": {"type": "boolean", "description": "Replace every occurrence (default: require a unique match)"}}, "required": ["path", "old_string", "new_string"]}
+ \\{"type": "object", "properties": {"path": {"type": "string"}, "old_string": {"type": "string", "description": "Exact existing text to find (single-span form)"}, "new_string": {"type": "string", "description": "Replacement text (single-span form)"}, "replace_all": {"type": "boolean", "description": "Replace every occurrence (default: require a unique match)"}, "edits": {"type": "array", "items": {"type": "object", "properties": {"old_string": {"type": "string"}, "new_string": {"type": "string"}, "replace_all": {"type": "boolean"}}, "required": ["old_string", "new_string"]}, "description": "Batch form: several spans applied in order in one call"}}}
,
},
.{
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index 77b2e3f3..4efaa739 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -44,6 +44,7 @@ const subagent_pin_tests = @import("subagent_pin_tests.zig");
// Folded native tools (#416's two-phase pattern for the harness's own power
// tools): reached in production via schema.zig/exec.zig/agent_tools.zig.
const native_fold = @import("native_fold.zig");
+const edit_batch = @import("edit_batch.zig");
// Moved off subagent.zig, which is at the 600-line cap.
const subagent_tests = @import("subagent_tests.zig");
// Bench score/cost priors → derived tier ladders (.harness/bench.json).
@@ -207,6 +208,7 @@ test {
_ = subagent_selection;
_ = subagent_pin_tests;
_ = native_fold;
+ _ = edit_batch;
_ = subagent_tests;
_ = bench_priors;
_ = bench_priors_tests;