graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat: /edit replaces a past prompt and keeps the cache prefix
justrach07b9e6961806
diff --git a/src/command_catalog.zig b/src/command_catalog.zigindex 2174e6a9..b67d35ef 100644--- a/src/command_catalog.zig+++ b/src/command_catalog.zig@@ -71,6 +71,7 @@ pub const commands = [_]Item{.{ .name = "/btw", .usage = "/btw <question>", .desc = "ask one side question about this conversation — billed, never added, rides the parent cache prefix" },.{ .name = "/compact", .desc = "compact history into a fresh context (OpenAI server-side when available)" },.{ .name = "/rewind", .usage = "/rewind [n|<snapshot>]", .desc = "list past prompts; /rewind <n> drops prompt n+after & reverts its file edits; /rewind <snapshot id> restores a sandbox filesystem instead, never the conversation" },+ .{ .name = "/edit", .usage = "/edit <n> <text>", .desc = "replace prompt n, drop n+after, keep the prefix so the next turn can still hit cache" },.{ .name = "/snapshot", .usage = "/snapshot [attach [image]|detach|list|gc [n]]", .desc = "capture the attached sandbox's filesystem under .graff/sessions/<session>/snapshots; attach puts this session in a Docker sandbox, list shows what it has captured, gc keeps the newest n (default 1)" },.{ .name = "/teleport", .usage = "/teleport <id> [docker|container]", .desc = "restore a docker_image_tar snapshot onto a different CLI backend (Apple Container by default); filesystem only, never the conversation" },.{ .name = "/image", .usage = "/image <path>", .desc = "attach an image to your next message (vision models only)" },diff --git a/src/commands_edit.zig b/src/commands_edit.zignew file mode 100644index 00000000..a3c84092--- /dev/null+++ b/src/commands_edit.zig@@ -0,0 +1,148 @@+//! `/rewind` and `/edit`: drop or replace a past user prompt and everything+//! after it. The prefix before that prompt is unchanged, so a follow-up can+//! still hit the provider cache.++const std = @import("std");+const Io = std.Io;+const Value = std.json.Value;+const Allocator = std.mem.Allocator;++const ansi = @import("ansi.zig");+const style = &ansi.style;+const Agent = @import("agent.zig").Agent;+const messages = @import("messages.zig");+pub fn userPromptIndexes(items: []const Value, gpa: Allocator) ![]usize {+ var turns: std.ArrayList(usize) = .empty;+ errdefer turns.deinit(gpa);+ for (items, 0..) |m, i| {+ if (messages.userPromptText(m) != null) try turns.append(gpa, i);+ }+ return turns.toOwnedSlice(gpa);+}++/// Drop prompt `n` (1-based) and everything after it. Returns the cut index.+pub fn rewindTo(root: *Agent, n: usize) !usize {+ const turns = try userPromptIndexes(root.messages.items, root.gpa);+ defer root.gpa.free(turns);+ if (turns.len == 0) return error.NoPrompts;+ if (n < 1 or n > turns.len) return error.InvalidN;+ const cut = turns[n - 1];+ root.messages.items.len = cut;+ root.last_context_tokens = 0;+ root.context_local_tokens = 0;+ root.compact_transport_failures = 0;+ root.goal_note_fp = 0;+ if (root.snapshots) |snaps| {+ _ = snaps.restore(@intCast(n));+ snaps.turn = @intCast(n - 1);+ }+ return cut;+}++pub fn tryHandle(root: *Agent, line: []const u8, out: *Io.Writer) !bool {+ const is_edit = std.mem.startsWith(u8, line, "/edit");+ const is_rewind = std.mem.startsWith(u8, line, "/rewind");+ if (!is_edit and !is_rewind) return false;+ const cmd = if (is_edit) "/edit" else "/rewind";+ if (line.len > cmd.len and line[cmd.len] != ' ' and line[cmd.len] != '\t') return false;+ const rest = std.mem.trim(u8, line[cmd.len..], " \t");+ const turns = try userPromptIndexes(root.messages.items, root.gpa);+ defer root.gpa.free(turns);+ if (turns.len == 0) {+ try out.writeAll("nothing to edit — no prompts in this conversation yet\n");+ try out.flush();+ return true;+ }+ var n: usize = 0;+ var text: []const u8 = "";+ if (rest.len > 0) {+ const sp = std.mem.indexOfAny(u8, rest, " \t") orelse rest.len;+ n = std.fmt.parseInt(usize, rest[0..sp], 10) catch 0;+ text = std.mem.trim(u8, rest[sp..], " \t");+ }+ if (n == 0) {+ try out.writeAll(if (is_edit) "edit which prompt?\n" else "rewind to before which prompt?\n");+ for (turns, 1..) |idx, i| {+ var snip = messages.userPromptText(root.messages.items[idx]) orelse "";+ if (std.mem.indexOfScalar(u8, snip, '\n')) |nl| snip = snip[0..nl];+ const shown = if (snip.len > 70) snip[0..70] else snip;+ try out.print(" {s}{d}{s}: {s}{s}\n", .{ style.accent, i, style.reset, shown, if (snip.len > 70) "…" else "" });+ }+ if (is_edit)+ try out.print("{s}usage: /edit <n> <text> — replace prompt n, drop n+after, keep the prefix for cache{s}\n", .{ style.dim, style.reset })+ else+ try out.print("{s}usage: /rewind <n> — drops prompt <n>+after and reverts its write_file/edit_file changes{s}\n", .{ style.dim, style.reset });+ try out.flush();+ return true;+ }+ if (n < 1 or n > turns.len) {+ try out.print("invalid — pick 1..{d} (see {s})\n", .{ turns.len, cmd });+ try out.flush();+ return true;+ }+ if (is_edit and text.len == 0) {+ try out.print("usage: /edit {d} <text> — the new prompt that replaces #{d}\n", .{ n, n });+ try out.flush();+ return true;+ }+ const before = root.messages.items.len;+ _ = rewindTo(root, n) catch unreachable;+ const dropped = before - root.messages.items.len;+ if (is_edit) {+ try out.print("edited prompt {d} — dropped {d} message(s); next send continues from here (prefix before {d} is unchanged)\n", .{ n, dropped, n });+ try out.print("{s}replacement: {s}{s}\n", .{ style.dim, text, style.reset });+ } else {+ try out.print("⏪ rewound to before prompt {d} — dropped {d} message(s)\n", .{ n, dropped });+ }+ try out.flush();+ return true;+}++test "userPromptIndexes counts Responses input_text and chat strings" {+ const gpa = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var items = std.json.Array.init(a);+ try items.append(try messages.textMessage(a, "user", "one"));+ try items.append(try messages.textMessage(a, "assistant", "ok"));+ var resp: std.json.ObjectMap = .empty;+ try resp.put(a, "role", .{ .string = "user" });+ var blocks = std.json.Array.init(a);+ var block: std.json.ObjectMap = .empty;+ try block.put(a, "type", .{ .string = "input_text" });+ try block.put(a, "text", .{ .string = "two" });+ try blocks.append(.{ .object = block });+ try resp.put(a, "content", .{ .array = blocks });+ try items.append(.{ .object = resp });+ const idx = try userPromptIndexes(items.items, gpa);+ defer gpa.free(idx);+ try std.testing.expectEqual(@as(usize, 2), idx.len);+ try std.testing.expectEqual(@as(usize, 0), idx[0]);+ try std.testing.expectEqual(@as(usize, 2), idx[1]);+}++test "rewindTo drops prompt n and after, keeps the prefix" {+ const gpa = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var agent: Agent = .{+ .gpa = gpa,+ .arena = a,+ .io = std.testing.io,+ .client = undefined,+ .provider = .{ .id = "xai", .kind = .responses, .auth = .bearer, .url = "", .api_key = "k", .model = "grok-4.6", .context = 100_000 },+ .messages = std.json.Array.init(a),+ .sub = false,+ .label = "test",+ .out = null,+ };+ try agent.messages.append(try messages.textMessage(a, "user", "one"));+ try agent.messages.append(try messages.textMessage(a, "assistant", "a1"));+ try agent.messages.append(try messages.textMessage(a, "user", "two"));+ try agent.messages.append(try messages.textMessage(a, "assistant", "a2"));+ _ = try rewindTo(&agent, 2);+ try std.testing.expectEqual(@as(usize, 2), agent.messages.items.len);+ try std.testing.expectEqualStrings("one", messages.userPromptText(agent.messages.items[0]).?);+}diff --git a/src/commands_model.zig b/src/commands_model.zigindex 53880d8c..c3383d88 100644--- a/src/commands_model.zig+++ b/src/commands_model.zig@@ -20,7 +20,6 @@ const isLocalUrl = keys_cli.isLocalUrl;const openAiModelsUrl = keys_cli.openAiModelsUrl;const fetchOpenAIModels = keys_cli.fetchOpenAIModels;const harness_version = main_mod.harness_version;-const Rewound = @import("tools.zig").Rewound; // what one /rewind restored/skippedconst pricing = @import("pricing.zig");const kimi_catalog = @import("kimi_catalog.zig");@@ -223,66 +222,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,};return true;}- if (std.mem.startsWith(u8, line, "/rewind")) {- // Conversation rewind (à la Claude Code): drop a past prompt and- // everything after it, so you can branch from an earlier point.- // Human turns are user messages whose content is a plain string- // (tool-result user messages carry a content array).- const arg = std.mem.trim(u8, line["/rewind".len..], " \t");- var turns: std.ArrayList(usize) = .empty;- defer turns.deinit(root.gpa);- for (root.messages.items, 0..) |m, i| {- if (m != .object) continue;- const role = if (m.object.get("role")) |r| (if (r == .string) r.string else "") else "";- if (!std.mem.eql(u8, role, "user")) continue;- if (m.object.get("content")) |c| if (c == .string) try turns.append(root.gpa, i);- }- if (turns.items.len == 0) {- try out.writeAll("nothing to rewind — no prompts in this conversation yet\n");- try out.flush();- return true;- }- if (arg.len == 0) {- try out.writeAll("rewind to before which prompt?\n");- for (turns.items, 1..) |idx, n| {- var snip = if (root.messages.items[idx].object.get("content")) |c| (if (c == .string) c.string else "[image]") else "";- if (std.mem.indexOfScalar(u8, snip, '\n')) |nl| snip = snip[0..nl];- const shown = if (snip.len > 70) snip[0..70] else snip;- try out.print(" {s}{d}{s}: {s}{s}\n", .{ style.accent, n, style.reset, shown, if (snip.len > 70) "…" else "" });- }- try out.print("{s}usage: /rewind <n> — drops prompt <n>+after and reverts its write_file/edit_file changes (bash edits aren't tracked){s}\n", .{ style.dim, style.reset });- try out.flush();- return true;- }- const n = std.fmt.parseInt(usize, arg, 10) catch 0;- if (n < 1 or n > turns.items.len) {- try out.print("invalid — pick 1..{d} (see /rewind)\n", .{turns.items.len});- try out.flush();- return true;- }- const cut = turns.items[n - 1];- const dropped = root.messages.items.len - cut;- root.messages.items.len = cut; // truncate (entries are arena-owned)- root.last_context_tokens = 0;- root.context_local_tokens = 0;- root.compact_transport_failures = 0;- 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 rw: Rewound = .{};- if (root.snapshots) |snaps| {- 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 (rw.restored > 0) try out.print(", restored {d} file(s)", .{rw.restored});- // Left alone rather than deleted. State the fact, never a cause: `.unreadable` is every non-FileNotFound read failure, so the reason is not knowable here.- if (rw.skipped > 0) try out.print(", left {d} file(s) as-is (no snapshot was captured)", .{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;- }+ if (try @import("commands_edit.zig").tryHandle(root, line, out)) return true;if (std.mem.eql(u8, line, "/fast") or std.mem.eql(u8, line, "/fast on") or std.mem.eql(u8, line, "/fast off")) {root.fast = if (std.mem.eql(u8, line, "/fast on")) true else if (std.mem.eql(u8, line, "/fast off")) false else !root.fast;_ = saveThinkingSettings(root.io, root.gpa, root.reasoning, root.fast, root.ultracode_mode, root.show_thinking, root.ai_title);@@ -525,3 +465,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,}return false;}++test {+ _ = @import("commands_edit.zig");+}diff --git a/src/json_controls.zig b/src/json_controls.zigindex c20a77de..c4a43754 100644--- a/src/json_controls.zig+++ b/src/json_controls.zig@@ -23,6 +23,27 @@ const remote_images = @import("remote_images.zig");/// event carries `persisted:false` explicitly: a client that logs the stream/// must be able to tell this apart from an ordinary assistant turn, because/// the session it is mirroring does not contain it.+/// `{"type":"edit","n":2,"text":"…"}` — drop prompt n and after, then the+/// caller runs `text` as the replacement. Prefix before n is unchanged.+/// null = not an edit request; false = failed (error already emitted).+pub fn applyEdit(root: *Agent, rtype: []const u8, obj: std.json.ObjectMap) ?bool {+ if (!std.mem.eql(u8, rtype, "edit")) return null;+ const n_v = obj.get("n") orelse {+ root.emit(.{ .type = "error", .message = "edit needs n (1-based prompt index)" });+ return false;+ };+ const n: usize = switch (n_v) {+ .integer => |i| if (i > 0) @intCast(i) else 0,+ else => 0,+ };+ _ = @import("commands_edit.zig").rewindTo(root, n) catch {+ root.emit(.{ .type = "error", .message = "edit: pick an existing prompt (see /edit)" });+ return false;+ };+ root.emit(.{ .type = "edit", .ok = true, .n = n });+ return true;+}+pub fn sideQuestion(root: *Agent, arena: Allocator, rtype: []const u8, text: []const u8) bool {if (!std.mem.eql(u8, rtype, "btw")) return false;if (side_question.ask(root, arena, text)) |answer| {diff --git a/src/mainloop.zig b/src/mainloop.zigindex 4f199368..5018e765 100644--- a/src/mainloop.zig+++ b/src/mainloop.zig@@ -286,9 +286,9 @@ pub fn run(ctx: *Ctx) !void {continue;}if (std.mem.eql(u8, rtype, "review")) review_prompt = text;- // #415: a side question is ANSWERED here and never becomes a turn —- // billed, parent-prefix cached, nothing added to the session.+ // #415: side question is answered here — billed, parent-cached, not persisted.if (json_controls.sideQuestion(ctx.root, ctx.arena, rtype, text)) continue;+ if (json_controls.applyEdit(ctx.root, rtype, parsed.object)) |ok| if (!ok) continue;if (!json_controls.beginTurn(ctx.root, parsed.object)) continue;break :blk text;} else line;diff --git a/src/messages.zig b/src/messages.zigindex d7029b09..7580031f 100644--- a/src/messages.zig+++ b/src/messages.zig@@ -42,7 +42,7 @@ pub fn trailingUserIs(messages: []const Value, text: []const u8) bool {return std.mem.eql(u8, t, text);}-fn userPromptText(msg: Value) ?[]const u8 {+pub fn userPromptText(msg: Value) ?[]const u8 {if (@import("session_wake.zig").isNotice(msg)) return null;if (msg != .object) return null;if (msg.object.get("type")) |kind| {