Skip to content

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

Python

fix(rewind): never delete a file whose snapshot could not be read

Rach Pradhan887eb769a162
diff --git a/src/commands_model.zig b/src/commands_model.zig
index 63b4f45c..5fc21c74 100644
--- a/src/commands_model.zig
+++ b/src/commands_model.zig
@@ -24,6 +24,7 @@ const isLocalUrl = keys_cli.isLocalUrl;
const openAiModelsUrl = keys_cli.openAiModelsUrl;
const fetchOpenAIModels = keys_cli.fetchOpenAIModels;
const harness_version = main_mod.harness_version;
+const snapshots_mod = @import("snapshots.zig"); // /rewind's file history (Rewound)
const pricing = @import("pricing.zig");
const kimi_catalog = @import("kimi_catalog.zig");
@@ -285,17 +286,16 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
root.goal_note_fp = 0; // the goal note may have been in the dropped turns (#318)
// Restore files written/edited during the rewound turns, and re-point the
// turn counter so the next prompt re-takes turn n.
- var restored: usize = 0;
+ var rw: snapshots_mod.Rewound = .{};
if (root.snapshots) |snaps| {
- restored = snaps.restore(@intCast(n));
+ rw = snaps.restore(@intCast(n));
snaps.turn = @intCast(n - 1);
}
try out.print("⏪ rewound to before prompt {d} — dropped {d} message(s)", .{ n, dropped });
- if (restored > 0) {
- try out.print(", restored {d} file(s)", .{restored});
- } else {
- try out.print("{s} (no tracked file changes){s}", .{ style.dim, style.reset });
- }
+ if (rw.restored > 0) try out.print(", restored {d} file(s)", .{rw.restored});
+ // Left alone rather than deleted: no snapshot was ever captured for these.
+ if (rw.skipped > 0) try out.print(", left {d} file(s) as-is (unreadable when written, nothing to restore)", .{rw.skipped});
+ if (rw.restored == 0 and rw.skipped == 0) try out.print("{s} (no tracked file changes){s}", .{ style.dim, style.reset });
try out.writeAll("\n");
try out.flush();
return true;
diff --git a/src/edit_verify.zig b/src/edit_verify.zig
index f3979c1a..2ca6c2be 100644
--- a/src/edit_verify.zig
+++ b/src/edit_verify.zig
@@ -235,7 +235,7 @@ pub fn applyEdit(ctx: ToolCtx, path: []const u8, resolved: []const u8, old: []co
// drift falls through to the write, where verification is the backstop.
if (attempt == 0 and drifted(io, resolved, prev_stat)) continue;
- if (ctx.snapshots) |snaps| if (!ctx.from_sub) snaps.record(path, data); // pre-edit content for /rewind
+ if (ctx.snapshots) |snaps| if (!ctx.from_sub) snaps.record(path, .{ .content = data }); // pre-edit content for /rewind
// Premium splice: when the zigrep suite is installed, zigpatch does the
// write — an atomic tmp+rename byte-level --all splice (our count
diff --git a/src/exec.zig b/src/exec.zig
index 2420fb3c..2e59fabb 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -29,6 +29,7 @@ const strField = tools.strField;
const intField = tools.intField;
const missingArg = tools.missingArg;
const outsideCwd = tools.outsideCwd;
+const beforeFromRead = tools.beforeFromRead; // /rewind snapshot classifier (snapshots.zig)
const blankText = tools.blankText;
const rawFetch = tools.rawFetch;
const bash_stdout_cap = tools.bash_stdout_cap;
@@ -445,9 +446,11 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
const lock = edit_verify.lockPath(io, resolved);
defer lock.unlock(io);
if (ctx.snapshots) |snaps| if (!ctx.from_sub) {
- // capture the prior content (or absence) before overwriting, for /rewind
- const before = Io.Dir.cwd().readFileAlloc(io, resolved, gpa, .limited(4 * 1024 * 1024)) catch null;
- defer if (before) |b| gpa.free(b);
+ // capture the prior content (or absence) before overwriting, for /rewind.
+ // beforeFromRead keeps a merely UNREADABLE file (over the cap, permissions)
+ // distinct from a missing one — only the latter is a rewind-deletes-it.
+ const before = beforeFromRead(Io.Dir.cwd().readFileAlloc(io, resolved, gpa, .limited(4 * 1024 * 1024)));
+ defer if (before == .content) gpa.free(before.content);
snaps.record(path, before);
};
// #179: an existing file keeps its mode (e.g. 0755) across the overwrite;
diff --git a/src/imagegen.zig b/src/imagegen.zig
index 0d4a37a8..a3d29dd9 100644
--- a/src/imagegen.zig
+++ b/src/imagegen.zig
@@ -247,8 +247,10 @@ pub fn execImagegen(ctx: ToolCtx, input: Value) !ToolOutput {
// /rewind parity with write_file: capture what we are about to overwrite
// before anything runs, so an imagegen that clobbers a file is undoable.
if (ctx.snapshots) |snaps| if (!ctx.from_sub and before.existed) {
+ // The file IS there, so a read failure (a big image past the cap) means
+ // "no snapshot", never "absent" — /rewind would delete it otherwise.
const prior = Io.Dir.cwd().readFileAlloc(io, resolved, arena, .limited(16 * 1024 * 1024)) catch null;
- snaps.record(out_rel, prior);
+ snaps.record(out_rel, if (prior) |p| .{ .content = p } else .unreadable);
};
// Same stripe as edit_file/write_file, so an imagegen and an edit_file
// landing on one path in the same turn take turns instead of interleaving.
diff --git a/src/snapshots.zig b/src/snapshots.zig
new file mode 100644
index 00000000..5f69ff01
--- /dev/null
+++ b/src/snapshots.zig
@@ -0,0 +1,117 @@
+//! `/rewind`'s file-mutation history: the pre-write snapshot every mutating
+//! tool (write_file/edit_file/imagegen) takes, and the restore that walks the
+//! working tree back to an earlier turn. Split out of tools.zig (600-line cap)
+//! when the snapshot grew its third state.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+/// What a file looked like before the tool that is about to modify it ran.
+/// Three states, not two: "could not read it" is NOT "it was not there", and
+/// folding the first into the second made `/rewind` DELETE a file it had never
+/// captured — a >4 MiB overwrite came back as StreamTooLong, was recorded as
+/// absent, and the rewind removed it.
+pub const Before = union(enum) {
+ absent, // the file did not exist — rewind deletes it
+ content: []const u8, // the bytes rewind writes back
+ unreadable, // it existed but could not be read — rewind leaves it alone
+};
+
+/// Classify the pre-write read of the file a tool is about to clobber. ONLY
+/// FileNotFound may become `.absent`; every other failure (StreamTooLong past
+/// the read cap, AccessDenied, a mid-read I/O error) leaves us with no
+/// snapshot, which must never turn into a delete.
+pub fn beforeFromRead(result: anyerror![]u8) Before {
+ const bytes = result catch |err| return switch (err) {
+ error.FileNotFound => .absent,
+ else => .unreadable,
+ };
+ return .{ .content = bytes };
+}
+
+/// One pre-modification file snapshot, tagged with the turn that's about to
+/// modify it.
+const Snapshot = struct { turn: u32, path: []const u8, before: Before };
+
+/// What one `/rewind` did: files put back (content rewritten, or deleted
+/// because they were new), and files left exactly as they are because no
+/// usable snapshot was ever taken.
+pub const Rewound = struct { restored: usize = 0, skipped: usize = 0 };
+
+/// Per-session record of file mutations (write_file/edit_file), so `/rewind`
+/// can restore the working tree to an earlier turn. Mutex-guarded — tools run
+/// on the pool concurrently. Bash edits are NOT tracked.
+pub const Snapshots = struct {
+ gpa: Allocator,
+ io: Io,
+ mutex: Io.Mutex = .init,
+ list: std.ArrayList(Snapshot) = .empty,
+ turn: u32 = 0, // the turn currently executing (set by the REPL loop)
+
+ /// Record a file's pre-modification state (called before the write).
+ pub fn record(self: *Snapshots, path: []const u8, before: Before) void {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ const p = self.gpa.dupe(u8, path) catch return;
+ const b: Before = switch (before) {
+ .content => |x| .{ .content = self.gpa.dupe(u8, x) catch {
+ self.gpa.free(p);
+ return;
+ } },
+ else => before,
+ };
+ self.list.append(self.gpa, .{ .turn = self.turn, .path = p, .before = b }) catch {
+ self.gpa.free(p);
+ if (b == .content) self.gpa.free(b.content);
+ };
+ }
+
+ /// Restore every file modified at turn ≥ n to its state before turn n, then
+ /// drop those snapshots.
+ pub fn restore(self: *Snapshots, n: u32) Rewound {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ var done: std.ArrayList([]const u8) = .empty;
+ defer done.deinit(self.gpa);
+ var out: Rewound = .{};
+ for (self.list.items) |snap| {
+ if (snap.turn < n) continue;
+ var seen = false;
+ for (done.items) |d| if (std.mem.eql(u8, d, snap.path)) {
+ seen = true;
+ };
+ if (seen) continue; // earliest snapshot per path wins (= state before turn n)
+ done.append(self.gpa, snap.path) catch {};
+ switch (snap.before) {
+ .content => |b| Io.Dir.cwd().writeFile(self.io, .{ .sub_path = snap.path, .data = b }) catch continue,
+ .absent => Io.Dir.cwd().deleteFile(self.io, snap.path) catch {},
+ // Nothing was captured: there is nothing to put back, and
+ // deleting would destroy content /rewind never owned.
+ .unreadable => {
+ out.skipped += 1;
+ continue;
+ },
+ }
+ out.restored += 1;
+ }
+ // Drop (and free) snapshots from the rewound turns.
+ var i: usize = 0;
+ while (i < self.list.items.len) {
+ if (self.list.items[i].turn >= n) {
+ const s = self.list.orderedRemove(i);
+ self.gpa.free(s.path);
+ if (s.before == .content) self.gpa.free(s.before.content);
+ } else i += 1;
+ }
+ return out;
+ }
+
+ pub fn deinit(self: *Snapshots) void {
+ for (self.list.items) |s| {
+ self.gpa.free(s.path);
+ if (s.before == .content) self.gpa.free(s.before.content);
+ }
+ self.list.deinit(self.gpa);
+ }
+};
diff --git a/src/snapshots_tests.zig b/src/snapshots_tests.zig
new file mode 100644
index 00000000..28955448
--- /dev/null
+++ b/src/snapshots_tests.zig
@@ -0,0 +1,105 @@
+//! `/rewind` snapshot tests: the three-state `Before`, and what each state
+//! does to the working tree end-to-end through write_file. Split off
+//! snapshots.zig so the module stays a focused unit; reached from the test
+//! root via test_hooks.zig.
+
+const std = @import("std");
+const builtin = @import("builtin");
+const Value = std.json.Value;
+
+const exec = @import("exec.zig");
+const tools = @import("tools.zig");
+const snapshots = @import("snapshots.zig");
+
+test "beforeFromRead: only FileNotFound is 'absent' — every other failure has NO snapshot" {
+ try std.testing.expect(snapshots.beforeFromRead(error.FileNotFound) == .absent);
+ // A file past readFileAlloc's cap. Recording this as `absent` is what made
+ // /rewind delete the file instead of restoring it.
+ try std.testing.expect(snapshots.beforeFromRead(error.StreamTooLong) == .unreadable);
+ try std.testing.expect(snapshots.beforeFromRead(error.AccessDenied) == .unreadable);
+ var bytes = [_]u8{ 'h', 'i' };
+ try std.testing.expectEqualStrings("hi", snapshots.beforeFromRead(bytes[0..]).content);
+}
+
+fn testCtx(client: *std.http.Client, snaps: *snapshots.Snapshots) tools.ToolCtx {
+ return .{
+ .gpa = std.testing.allocator,
+ .io = std.testing.io,
+ .client = client,
+ .provider = undefined,
+ .registry = null,
+ .from_sub = false,
+ .approvals = null,
+ .tracer = null,
+ .snapshots = snaps,
+ };
+}
+
+/// Run write_file through the real dispatch (guards, snapshotting and all).
+fn writeFile(snaps: *snapshots.Snapshots, a: std.mem.Allocator, path: []const u8, content: []const u8) !void {
+ var obj: std.json.ObjectMap = .empty;
+ try obj.put(a, "path", .{ .string = path });
+ try obj.put(a, "content", .{ .string = content });
+ var client: std.http.Client = undefined;
+ const out = exec.execTool(testCtx(&client, snaps), .{ .id = "call_1", .name = "write_file", .input = .{ .object = obj } });
+ defer std.testing.allocator.free(out.text);
+ try std.testing.expect(!out.is_error);
+}
+
+test "/rewind: a file write_file CREATED is deleted, and an overwritten one is restored" {
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
+ 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();
+ try tmp.dir.writeFile(io, .{ .sub_path = "old.txt", .data = "original\n" });
+ const dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{&tmp.sub_path});
+
+ var snaps: snapshots.Snapshots = .{ .gpa = gpa, .io = io };
+ defer snaps.deinit();
+ snaps.turn = 1;
+ try writeFile(&snaps, a, try std.fmt.allocPrint(a, "{s}/fresh.txt", .{dir}), "brand new\n");
+ try writeFile(&snaps, a, try std.fmt.allocPrint(a, "{s}/old.txt", .{dir}), "clobbered\n");
+
+ const rw = snaps.restore(1);
+ try std.testing.expectEqual(@as(usize, 2), rw.restored);
+ try std.testing.expectEqual(@as(usize, 0), rw.skipped);
+ try std.testing.expectError(error.FileNotFound, tmp.dir.statFile(io, "fresh.txt", .{}));
+ const back = try tmp.dir.readFileAlloc(io, "old.txt", gpa, .limited(4096));
+ defer gpa.free(back);
+ try std.testing.expectEqualStrings("original\n", back);
+}
+
+test "/rewind: a file too big to snapshot survives — it is never mistaken for a new file" {
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
+ 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();
+ // 5 MiB: past write_file's 4 MiB snapshot read cap, so the pre-write read
+ // fails with StreamTooLong and no snapshot can be taken.
+ const big = try a.alloc(u8, 5 * 1024 * 1024);
+ @memset(big, 'x');
+ try tmp.dir.writeFile(io, .{ .sub_path = "big.txt", .data = big });
+
+ var snaps: snapshots.Snapshots = .{ .gpa = gpa, .io = io };
+ defer snaps.deinit();
+ snaps.turn = 1;
+ try writeFile(&snaps, a, try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}/big.txt", .{&tmp.sub_path}), "clobbered\n");
+
+ const rw = snaps.restore(1);
+ try std.testing.expectEqual(@as(usize, 0), rw.restored);
+ try std.testing.expectEqual(@as(usize, 1), rw.skipped);
+ // The file is still there — unrewound, but not destroyed by the rewind.
+ const after = try tmp.dir.readFileAlloc(io, "big.txt", gpa, .limited(4096));
+ defer gpa.free(after);
+ try std.testing.expectEqualStrings("clobbered\n", after);
+}
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index 81575dc3..217ea3a8 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -111,6 +111,11 @@ const workflow_pipeline = @import("workflow_pipeline.zig");
// is contingent on those call sites staying — pinned here instead.
const shutdown_trace = @import("shutdown_trace.zig");
+// `/rewind`'s snapshot store, split off tools.zig (600-line cap). Production
+// reaches it only through a type alias, which analyses nothing.
+const snapshots = @import("snapshots.zig");
+const snapshots_tests = @import("snapshots_tests.zig");
+
test {
_ = learn_holdout;
_ = learn_receipt;
@@ -155,4 +160,6 @@ test {
_ = orchestration_policy_tests;
_ = orchestration_rows;
_ = workflow_pipeline;
+ _ = snapshots;
+ _ = snapshots_tests;
}
diff --git a/src/tools.zig b/src/tools.zig
index 4c842bcc..10d519b6 100644
--- a/src/tools.zig
+++ b/src/tools.zig
@@ -1,6 +1,6 @@
//! Tool execution context, lifecycle-hook dispatch, and the small tool
-//! helpers. Split out of main.zig (600-line goal): `ToolOutput`/`Snapshot(s)`/
-//! `ToolCtx`, pre/post-tool hook dispatch (`hookPayload`/`hookGate`/
+//! helpers. Split out of main.zig (600-line goal): `ToolOutput`/`ToolCtx`,
+//! pre/post-tool hook dispatch (`hookPayload`/`hookGate`/
//! `runPostToolHooks`), the codedb-guard (issue #626: `codedbGuard`/
//! `extractSourceFilePath`/`referencesSourceFile`) and the metered-companion
//! router (`companionRoute`/`companionNativeFallback`), plus the small
@@ -81,78 +81,13 @@ pub const ToolOutput = struct {
ms: i64 = 0, // set by execTool
};
-/// One pre-edit file snapshot, tagged with the turn that's about to modify it.
-/// `before == null` means the file didn't exist (rewind deletes it).
-const Snapshot = struct { turn: u32, path: []const u8, before: ?[]const u8 };
-
-/// Per-session record of file mutations (write_file/edit_file), so `/rewind`
-/// can restore the working tree to an earlier turn. Mutex-guarded — tools run
-/// on the pool concurrently. Bash edits are NOT tracked.
-pub const Snapshots = struct {
- gpa: Allocator,
- io: Io,
- mutex: Io.Mutex = .init,
- list: std.ArrayList(Snapshot) = .empty,
- turn: u32 = 0, // the turn currently executing (set by the REPL loop)
-
- /// Record a file's pre-modification content (called before the write).
- pub fn record(self: *Snapshots, path: []const u8, before: ?[]const u8) void {
- self.mutex.lockUncancelable(self.io);
- defer self.mutex.unlock(self.io);
- const p = self.gpa.dupe(u8, path) catch return;
- const b: ?[]const u8 = if (before) |x| (self.gpa.dupe(u8, x) catch {
- self.gpa.free(p);
- return;
- }) else null;
- self.list.append(self.gpa, .{ .turn = self.turn, .path = p, .before = b }) catch {
- self.gpa.free(p);
- if (b) |bb| self.gpa.free(bb);
- };
- }
-
- /// Restore every file modified at turn ≥ n to its state before turn n, then
- /// drop those snapshots. Returns the number of files restored.
- pub fn restore(self: *Snapshots, n: u32) usize {
- self.mutex.lockUncancelable(self.io);
- defer self.mutex.unlock(self.io);
- var done: std.ArrayList([]const u8) = .empty;
- defer done.deinit(self.gpa);
- var restored: usize = 0;
- for (self.list.items) |snap| {
- if (snap.turn < n) continue;
- var seen = false;
- for (done.items) |d| if (std.mem.eql(u8, d, snap.path)) {
- seen = true;
- };
- if (seen) continue; // earliest snapshot per path wins (= state before turn n)
- done.append(self.gpa, snap.path) catch {};
- if (snap.before) |b| {
- Io.Dir.cwd().writeFile(self.io, .{ .sub_path = snap.path, .data = b }) catch continue;
- } else {
- Io.Dir.cwd().deleteFile(self.io, snap.path) catch {};
- }
- restored += 1;
- }
- // Drop (and free) snapshots from the rewound turns.
- var i: usize = 0;
- while (i < self.list.items.len) {
- if (self.list.items[i].turn >= n) {
- const s = self.list.orderedRemove(i);
- self.gpa.free(s.path);
- if (s.before) |b| self.gpa.free(b);
- } else i += 1;
- }
- return restored;
- }
-
- pub fn deinit(self: *Snapshots) void {
- for (self.list.items) |s| {
- self.gpa.free(s.path);
- if (s.before) |b| self.gpa.free(b);
- }
- self.list.deinit(self.gpa);
- }
-};
+// `/rewind`'s pre-write file history lives in snapshots.zig (this file is at
+// the 600-line cap); re-exported so `tools.Snapshots` keeps resolving for
+// main.zig/agent.zig/exec.zig.
+const snapshots_mod = @import("snapshots.zig");
+pub const Before = snapshots_mod.Before;
+pub const beforeFromRead = snapshots_mod.beforeFromRead;
+pub const Snapshots = snapshots_mod.Snapshots;
/// Everything a tool executor may touch from a pool thread. All fields are
/// thread-safe (gpa, io, shared http client, mutex-guarded registry and