graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Fork a conversation: /fork and ACP session/fork
Rach Pradhan681d686cab28
diff --git a/scripts/eval-tier1.sh b/scripts/eval-tier1.shindex 0f6fd880..37a679c1 100755--- a/scripts/eval-tier1.sh+++ b/scripts/eval-tier1.sh@@ -187,6 +187,7 @@ if wanted shell; thenpython3 scripts/eval/process_guard.py --timeout 90 python3 scripts/test-acp-released-fixes.py zig-out/bin/graff &&python3 scripts/eval/process_guard.py --timeout 120 python3 scripts/test-acp-permissions.py zig-out/bin/graff &&python3 scripts/eval/process_guard.py --timeout 90 python3 scripts/test-acp-session-load.py zig-out/bin/graff &&+ python3 scripts/eval/process_guard.py --timeout 90 python3 scripts/test-acp-session-fork.py zig-out/bin/graff &&python3 scripts/eval/process_guard.py --timeout 90 python3 scripts/test-acp-resume-identity.py zig-out/bin/graff &&python3 scripts/eval/process_guard.py --timeout 120 python3 scripts/test-acp-workspace.py zig-out/bin/graff &&python3 scripts/eval/process_guard.py --timeout 90 python3 scripts/test-acp-images.py zig-out/bin/graffdiff --git a/scripts/test-acp-session-fork.py b/scripts/test-acp-session-fork.pynew file mode 100755index 00000000..b0c9f383--- /dev/null+++ b/scripts/test-acp-session-fork.py@@ -0,0 +1,108 @@+#!/usr/bin/env python3+"""Offline ACP session/fork: the branch carries the history, the source save+stays as it was, and a fresh process can fork a saved session."""+import importlib.util+import json+import sys+import tempfile+import time+from pathlib import Path++REPO = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(REPO / "scripts/eval"))+from mock_model import ScriptedModel++spec = importlib.util.spec_from_file_location("acp_load", REPO / "scripts/test-acp-session-load.py")+acp_load = importlib.util.module_from_spec(spec)+spec.loader.exec_module(acp_load)+Acp = acp_load.Acp+++def wait_for(path, needle, timeout=5):+ end = time.monotonic() + timeout+ while time.monotonic() < end:+ if path.exists() and needle in path.read_text():+ return+ time.sleep(.05)+ raise AssertionError(f"{path.name} never contained {needle!r}")+++def updates(events):+ return [e["params"]["update"] for e in events if e.get("method") == "session/update"]+++def run(binary):+ with tempfile.TemporaryDirectory(prefix="graff-acp-fork-") as temporary:+ cwd = Path(temporary).resolve()+ home = cwd / "home"+ home.mkdir()+ sessions = cwd / ".graff" / "sessions"++ model = ScriptedModel([{"text": "Original answer."}, {"text": "Branch answer."}])+ port = model.start(0)+ a = Acp(binary, cwd, home, port)+ try:+ init = a.request("initialize", {"protocolVersion": 1})+ assert init["result"]["agentCapabilities"]["sessionCapabilities"] == {"fork": {}}, init+ sid = a.request("session/new", {"cwd": str(cwd), "mcpServers": []})["result"]["sessionId"]+ empty = a.request("session/fork", {"sessionId": sid, "cwd": str(cwd), "mcpServers": []})+ assert empty["error"]["code"] == -32602, empty+ turn = a.request("session/prompt", {"sessionId": sid, "prompt": [{"type": "text", "text": "Original request."}]}, 35)+ assert turn["result"]["stopReason"] == "end_turn", turn+ source = sessions / f"{sid}.session.json"+ wait_for(source, "Original answer.")++ # Same process: fork the live session and continue on the branch.+ forked = a.request("session/fork", {"sessionId": sid, "cwd": str(cwd), "mcpServers": []})+ branch = forked["result"]["sessionId"]+ assert branch == f"{sid}-fork-1", forked+ assert forked["result"]["configOptions"], forked+ before = source.read_text()+ stale = a.request("session/prompt", {"sessionId": sid, "prompt": [{"type": "text", "text": "x"}]})+ assert stale["error"]["code"] == -32602, stale+ turn = a.request("session/prompt", {"sessionId": branch, "prompt": [{"type": "text", "text": "Branch request."}]}, 35)+ assert turn["result"]["stopReason"] == "end_turn", turn+ sent = json.dumps(model.requests[-1])+ assert "Original request." in sent and "Original answer." in sent, "branch lost the history"+ branch_save = sessions / f"{branch}.session.json"+ wait_for(branch_save, "Branch answer.")+ saved = json.loads(branch_save.read_text())+ assert saved.get("parent") == sid, saved.get("parent")+ assert source.read_text() == before, "a branch turn rewrote the source"+ assert "Branch request." not in source.read_text()+ finally:+ a.close()+ model.stop()++ # A fresh process forks the saved source and replays it on request.+ model = ScriptedModel([{"text": "Second branch answer."}])+ port = model.start(0)+ b = Acp(binary, cwd, home, port)+ try:+ b.request("initialize", {"protocolVersion": 1})+ missing = b.request("session/fork", {"sessionId": "missing", "cwd": str(cwd), "mcpServers": []})+ assert missing["error"]["code"] == -32602, missing+ escape = b.request("session/fork", {"sessionId": "../escape", "cwd": str(cwd), "mcpServers": []})+ assert escape["error"]["code"] == -32602, escape+ mark = len(b.events)+ forked = b.request("session/fork", {"sessionId": sid, "cwd": str(cwd), "mcpServers": [],+ "replayFrom": {"type": "start"}})+ second = forked["result"]["sessionId"]+ assert second == f"{sid}-fork-2", forked+ replayed = updates(b.events[mark:])+ assert any(u.get("sessionUpdate") == "user_message_chunk" and u["content"].get("text") == "Original request." for u in replayed)+ assert not any(u.get("sessionUpdate") == "user_message_chunk" and u["content"].get("text") == "Branch request." for u in replayed)+ turn = b.request("session/prompt", {"sessionId": second, "prompt": [{"type": "text", "text": "Second branch request."}]}, 35)+ assert turn["result"]["stopReason"] == "end_turn", turn+ sent = json.dumps(model.requests[-1])+ assert "Original answer." in sent and "Branch request." not in sent, "second branch saw the wrong history"+ wait_for(sessions / f"{second}.session.json", "Second branch answer.")+ assert source.read_text() == before, "forking from disk rewrote the source"+ finally:+ b.close()+ model.stop()+ print("ACP session/fork: live and saved forks keep history and leave the source untouched: ok")+++if __name__ == "__main__":+ run(Path(sys.argv[1] if len(sys.argv) > 1 else REPO / "zig-out/bin/graff").resolve())diff --git a/src/acp.zig b/src/acp.zigindex 76aad0de..5c2637c8 100644--- a/src/acp.zig+++ b/src/acp.zig@@ -117,6 +117,7 @@ fn liveModels(ctx: *anyopaque, arena: Allocator, w: *Io.Writer, req: proto.Requeconst live: *LiveTurn = @ptrCast(@alignCast(ctx));if (try @import("acp_agents.zig").handle(arena, live.root.io, live.root.home, w, req)) return true;if (try @import("acp_changes.zig").handle(arena, live.root.io, w, req)) return true;+ if (try @import("acp_session_fork.zig").handle(live, arena, w, req)) return true;if (try @import("acp_mcp_app.zig").handle(arena, w, req, live.root)) return true;if (!std.mem.eql(u8, req.method, "graff/models")) return false;if (req.id == null) return true;diff --git a/src/acp_engine.zig b/src/acp_engine.zigindex 395d7577..4f373739 100644--- a/src/acp_engine.zig+++ b/src/acp_engine.zig@@ -265,6 +265,7 @@ fn respondInitialize(w: *Io.Writer, req: proto.Request, can_load: bool) !void {.protocolVersion = negotiateVersion(req.params),.agentCapabilities = .{.loadSession = can_load,+ .sessionCapabilities = proto.SessionCapabilities{ .fork = can_load },._meta = .{ .@"codegraff/usage" = can_load, .@"graff/backgroundSubagents" = true },.promptCapabilities = proto.PromptCapabilities{ .image = can_load },// session/new and session/load connect a client's MCP servers@@ -339,8 +340,7 @@ pub fn handleLine(d: *Dispatch, arena: Allocator, w: *Io.Writer, line: []const ucancel_flag.store(true, .release);@import("cancel_source.zig").noteAcp(req.params);if (on_cancel) |hook| hook();- if (req.id != null) return respond(w, req, struct {}{});- return;+ return respond(w, req, struct {}{});}if (v2.on() and std.mem.eql(u8, req.method, "session/close")) return respond(w, req, struct {}{});if (std.mem.eql(u8, req.method, if (v2.on()) "session/resume" else "session/load")) {diff --git a/src/acp_protocol.zig b/src/acp_protocol.zigindex 48547666..6ec62598 100644--- a/src/acp_protocol.zig+++ b/src/acp_protocol.zig@@ -26,6 +26,21 @@ pub const PromptCapabilities = struct {embeddedContext: bool = true,};+/// `agentCapabilities.sessionCapabilities`: `{"fork":{}}` when the live CLI can+/// branch a session (acp_session_fork.zig), `{}` for an embed without saves.+pub const SessionCapabilities = struct {+ fork: bool = false,++ pub fn jsonStringify(self: @This(), s: anytype) !void {+ try s.beginObject();+ if (self.fork) {+ try s.objectField("fork");+ try s.write(struct {}{});+ }+ try s.endObject();+ }+};+pub const AgentImplementation = struct {name: []const u8 = "graff",title: []const u8 = "graff",diff --git a/src/acp_session_fork.zig b/src/acp_session_fork.zignew file mode 100644index 00000000..f63373f6--- /dev/null+++ b/src/acp_session_fork.zig@@ -0,0 +1,92 @@+//! ACP `session/fork` (draft RFD) for the live CLI Agent: branch a saved+//! session into a new one and make the branch this process's session. The+//! source keeps its save, so the client can still load it in another process.+//! Forking this process's own session saves it first (session_fork.zig); any+//! other session must be a save in the selected workspace, as for session/load.+//! The result has session/new's shape; `replayFrom: {type: start}` also+//! replays the branch's history, the same opt-in v2 session/resume takes.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const proto = @import("acp_protocol.zig");+const engine = @import("acp_engine.zig");+const session = @import("session.zig");+const session_fork = @import("session_fork.zig");+const load = @import("acp_session_load.zig");+const acp_workspace = @import("acp_workspace.zig");+const LiveTurn = @import("acp_live_turn.zig").LiveTurn;+const util = @import("util.zig");++const invalid_params: i32 = -32602;++fn reject(w: *Io.Writer, req: proto.Request, message: []const u8) !bool {+ if (req.id != null) try proto.writeError(w, req.id, invalid_params, message);+ return true;+}++fn failText(err: anyerror) []const u8 {+ return switch (err) {+ error.NothingToFork => "Session has nothing to fork yet",+ error.InvalidSessionName => "Invalid session ID",+ error.BranchAlreadyExists => "A session with the fork's name already exists",+ else => @errorName(err),+ };+}++/// True when `req` was session/fork (answered here either way).+pub fn handle(live: *LiveTurn, arena: Allocator, w: *Io.Writer, req: proto.Request) !bool {+ if (!std.mem.eql(u8, req.method, "session/fork")) return false;+ const d = live.dispatch orelse return reject(w, req, "Session forking is unavailable");+ const env = d.workspace orelse return reject(w, req, "Session forking is unavailable");+ const params = req.params orelse return reject(w, req, "Invalid session/fork parameters");+ if (params != .object) return reject(w, req, "Invalid session/fork parameters");+ const sid = util.strFieldObj(params.object, "sessionId") orelse return reject(w, req, "Invalid session ID");+ if (util.strFieldObj(params.object, "cwd") == null) return reject(w, req, "Invalid session workspace");+ if (!session.validSessionName(sid)) return reject(w, req, "Invalid session ID");+ acp_workspace.adopt(env, arena, params) catch |err| return reject(w, req, acp_workspace.errorText(err));+ if (d.mcp_servers) |attach| attach(d.ctx, arena, req.params) catch {};+ const root = live.root;+ const own = std.mem.eql(u8, sid, root.session_name) or (d.session_id != null and std.mem.eql(u8, sid, d.session_id.?));+ if (own) {+ _ = session_fork.forkCurrent(root, live.keys, arena, null, null) catch |err| return reject(w, req, failText(err));+ } else {+ switch (load.savedHere(live, env, arena, sid)) {+ .provider => {},+ .rejected => |message| return reject(w, req, message),+ }+ // Flush the outgoing conversation before the branch replaces it.+ session.saveSession(root, arena, root.session_name) catch |err| {+ try proto.writeError(w, req.id, engine.err_internal, @errorName(err));+ return true;+ };+ const target = try session_fork.autoName(root, arena, sid);+ _ = @import("session_branch.zig").restore(root, live.keys, arena, sid, target, live.model_override) catch |err|+ return reject(w, req, failText(err));+ }+ live.session_id = root.session_name;+ d.session_id = live.session_id;+ d.durable_session_id = live.session_id;+ if (load.replayFromStart(params)) try load.replayHistory(arena, root, w, live.session_id);+ const options = engine.configOptions(d, arena) catch |err| {+ try proto.writeError(w, req.id, engine.err_internal, @errorName(err));+ return true;+ };+ try proto.writeResult(w, req.id, .{ .sessionId = live.session_id, .configOptions = options, ._meta = acp_workspace.meta(env, arena) });+ try proto.writeAvailableCommands(w, live.session_id, try @import("acp_t3.zig").commands(arena, proto.slashCommands()));+ return true;+}++test "session/fork without a live workspace or a session ID is refused, not dropped" {+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ const a = state.allocator();+ var out: Io.Writer.Allocating = .init(a);+ var live: LiveTurn = undefined;+ live.dispatch = null;+ const other = proto.parseRequest(a, "{\"id\":1,\"method\":\"session/load\"}").?;+ try std.testing.expect(!try handle(&live, a, &out.writer, other));+ const fork = proto.parseRequest(a, "{\"id\":2,\"method\":\"session/fork\",\"params\":{\"cwd\":\"/tmp\"}}").?;+ try std.testing.expect(try handle(&live, a, &out.writer, fork));+ try std.testing.expect(std.mem.indexOf(u8, out.writer.buffered(), "\"id\":2,\"error\"") != null);+}diff --git a/src/acp_session_load.zig b/src/acp_session_load.zigindex aae9c416..36e17f42 100644--- a/src/acp_session_load.zig+++ b/src/acp_session_load.zig@@ -39,7 +39,7 @@ fn reject(w: *Io.Writer, req: proto.Request, message: []const u8) !void {if (req.id != null) try proto.writeError(w, req.id, invalid_params, message);}-fn replayHistory(arena: Allocator, root: *@import("agent.zig").Agent, w: *Io.Writer, sid: []const u8) !void {+pub fn replayHistory(arena: Allocator, root: *@import("agent.zig").Agent, w: *Io.Writer, sid: []const u8) !void {// The provider context can be compacted. The append-only transcript keeps// earlier visible turns; a legacy save without one uses current history.var retained: std.ArrayList(std.json.Value) = .empty;@@ -70,38 +70,16 @@ pub fn load(ctx: *anyopaque, arena: Allocator, w: *Io.Writer, req: proto.Request// The client's cwd becomes the session's; naming the checkout that owns a// `-w` or auto-isolated tree keeps that tree (acp_workspace.adopt).acp_workspace.adopt(env, arena, params) catch |err| return reject(w, req, acp_workspace.errorText(err));- // No discovery fallback to the user's home or a sibling checkout. A save- // with this basename in another workspace is a different conversation.- // The one exception is this checkout's own `.graff/worktrees/*` (ADR 0202).- const path = try session.sessionPath(arena, sid);- const stat = Io.Dir.cwd().statFile(live.root.io, path, .{}) catch blk: {- if (!acp_workspace.enterSavedTree(env, arena, sid)) return reject(w, req, "Unknown session ID in the selected workspace");- break :blk Io.Dir.cwd().statFile(live.root.io, path, .{}) catch- return reject(w, req, "Unknown session ID in the selected workspace");+ const provider = switch (savedHere(live, env, arena, sid)) {+ .provider => |id| id,+ .rejected => |message| return reject(w, req, message),};- const canonical_active = workspace_switch.currentAbs(live.root.io, arena);- if (stat.kind != .file) return reject(w, req, "Unknown session ID in the selected workspace");- const bytes = Io.Dir.cwd().readFileAlloc(live.root.io, path, arena, .limited(session_index.max_session_bytes)) catch |err|- return reject(w, req, loadErrorText(arena, if (err == error.StreamTooLong) error.SessionTooLarge else err, ""));- const parsed = std.json.parseFromSliceLeaky(std.json.Value, arena, bytes, .{ .allocate = .alloc_always }) catch- return reject(w, req, "Saved session could not be loaded");- if (parsed != .object) return reject(w, req, "Saved session could not be loaded");- const provider = parsed.object.get("provider") orelse return reject(w, req, "Saved session could not be loaded");- const model = parsed.object.get("model") orelse return reject(w, req, "Saved session could not be loaded");- const messages = parsed.object.get("messages") orelse return reject(w, req, "Saved session could not be loaded");- if (provider != .string or model != .string or messages != .array)- return reject(w, req, "Saved session could not be loaded");- if (util.strFieldObj(parsed.object, "workspace")) |saved_workspace| {- const canonical_saved = Io.Dir.cwd().realPathFileAlloc(live.root.io, saved_workspace, arena) catch saved_workspace;- if (!session_index.sameWorkspace(canonical_saved, canonical_active))- return reject(w, req, "Saved session belongs to another workspace");- }// Flush the outgoing conversation before replacing provider-native state.session.saveSession(live.root, arena, live.root.session_name) catch |err| {return proto.writeError(w, req.id, engine.err_internal, @errorName(err));};session.loadSession(live.root, live.keys, arena, sid) catch |err| {- return proto.writeError(w, req.id, invalid_params, loadErrorText(arena, err, if (provider == .string) provider.string else ""));+ return proto.writeError(w, req.id, invalid_params, loadErrorText(arena, err, provider));};// Same precedence as CLI resume: the host respawns with --model to switch.if (live.model_override) |p| @import("session_branch.zig").applyModelOverride(live.root, arena, p);@@ -116,6 +94,39 @@ pub fn load(ctx: *anyopaque, arena: Allocator, w: *Io.Writer, req: proto.Requesttry proto.writeAvailableCommands(w, live.session_id, try @import("acp_t3.zig").commands(arena, proto.slashCommands()));}+pub const Saved = union(enum) { provider: []const u8, rejected: []const u8 };++/// A save `sid` in the selected workspace that session/load (and session/fork)+/// may restore, or why not. Names its provider for a credential error.+pub fn savedHere(live: *LiveTurn, env: acp_workspace.Env, arena: Allocator, sid: []const u8) Saved {+ // No discovery fallback to the user's home or a sibling checkout. A save+ // with this basename in another workspace is a different conversation.+ // The one exception is this checkout's own `.graff/worktrees/*` (ADR 0202).+ const path = session.sessionPath(arena, sid) catch return .{ .rejected = "Invalid session ID" };+ const stat = Io.Dir.cwd().statFile(live.root.io, path, .{}) catch blk: {+ if (!acp_workspace.enterSavedTree(env, arena, sid)) return .{ .rejected = "Unknown session ID in the selected workspace" };+ break :blk Io.Dir.cwd().statFile(live.root.io, path, .{}) catch+ return .{ .rejected = "Unknown session ID in the selected workspace" };+ };+ const canonical_active = workspace_switch.currentAbs(live.root.io, arena);+ if (stat.kind != .file) return .{ .rejected = "Unknown session ID in the selected workspace" };+ const bytes = Io.Dir.cwd().readFileAlloc(live.root.io, path, arena, .limited(session_index.max_session_bytes)) catch |err|+ return .{ .rejected = loadErrorText(arena, if (err == error.StreamTooLong) error.SessionTooLarge else err, "") };+ const unloadable: Saved = .{ .rejected = "Saved session could not be loaded" };+ const parsed = std.json.parseFromSliceLeaky(std.json.Value, arena, bytes, .{ .allocate = .alloc_always }) catch return unloadable;+ if (parsed != .object) return unloadable;+ const provider = parsed.object.get("provider") orelse return unloadable;+ const model = parsed.object.get("model") orelse return unloadable;+ const messages = parsed.object.get("messages") orelse return unloadable;+ if (provider != .string or model != .string or messages != .array) return unloadable;+ if (util.strFieldObj(parsed.object, "workspace")) |saved_workspace| {+ const canonical_saved = Io.Dir.cwd().realPathFileAlloc(live.root.io, saved_workspace, arena) catch saved_workspace;+ if (!session_index.sameWorkspace(canonical_saved, canonical_active))+ return .{ .rejected = "Saved session belongs to another workspace" };+ }+ return .{ .provider = provider.string };+}+/// #1557: the save parsed and its fields are present, so a failure here is/// rarely an unreadable file. Name the real cause — a missing credential most/// of all, which the host would otherwise present as lost context.@@ -140,7 +151,7 @@ test "loadErrorText names a missing credential instead of blaming the save (#155try std.testing.expect(std.mem.indexOf(u8, loadErrorText(a, error.SessionTooLarge, "x"), "read limit") != null);}-fn replayFromStart(params: std.json.Value) bool {+pub fn replayFromStart(params: std.json.Value) bool {const from = params.object.get("replayFrom") orelse return false;if (from != .object) return false;return std.mem.eql(u8, util.strFieldObj(from.object, "type") orelse "", "start");diff --git a/src/acp_v2.zig b/src/acp_v2.zigindex 572fdb5c..076d7b69 100644--- a/src/acp_v2.zig+++ b/src/acp_v2.zig@@ -206,6 +206,10 @@ const InitializeResult = struct {try s.endObject();try s.objectField("mcp");try s.write(.{ .stdio = Empty{}, .http = Empty{} });+ if (self.can_load) {+ try s.objectField("fork");+ try s.write(Empty{});+ }try s.endObject();try s.objectField("_meta");try s.write(.{ .@"codegraff/usage" = self.can_load, .@"graff/backgroundSubagents" = true });diff --git a/src/command_catalog.zig b/src/command_catalog.zigindex 0ecf5e63..f5c106d7 100644--- a/src/command_catalog.zig+++ b/src/command_catalog.zig@@ -110,6 +110,7 @@ pub const commands = [_]Item{.{ .name = "/bash", .usage = "/bash <command>", .desc = "run a shell command directly" },.{ .name = "/save", .usage = "/save [name]", .desc = "write the conversation to <name>.session.json (default: current)" },.{ .name = "/resume", .usage = "/resume [source] [--branch destination]", .desc = "restore a saved conversation, optionally cloning it into an independent branch" },+ .{ .name = "/fork", .usage = "/fork [name]", .desc = "branch this conversation into a new session and continue there; the original stays saved for /resume" },.{ .name = "/sessions", .desc = "list saved sessions here and under ~/.graff/sessions" },.{ .name = "/workspace", .usage = "/workspace [list|use <name>|create <name>|gc]", .desc = "list git worktrees, switch, create a task workspace, or gc unused trees (free space)" },.{ .name = "/experiment", .usage = "/experiment [N|off|status]", .desc = "pre-mint N child worktrees (1-16) and seat the next spawns in them; off clears the pool" },diff --git a/src/commands_resume.zig b/src/commands_resume.zigindex 7cd8a9cb..8efac91d 100644--- a/src/commands_resume.zig+++ b/src/commands_resume.zig@@ -1,4 +1,4 @@-//! `/resume` and clone-on-write `/resume SOURCE --branch DEST`.+//! `/resume`, clone-on-write `/resume SOURCE --branch DEST`, and `/fork`.const std = @import("std");const Io = std.Io;@@ -50,7 +50,26 @@ fn reject(out: *Io.Writer, comptime fmt: []const u8, args: anytype) !bool {return true;}+/// `/fork [NAME]`: branch the current conversation and continue in the branch.+fn tryFork(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {+ if (!std.mem.startsWith(u8, line, "/fork") or (line.len > 5 and line[5] != ' ' and line[5] != '\t')) return false;+ const arg = std.mem.trim(u8, line["/fork".len..], " \t");+ if (std.mem.indexOfAny(u8, arg, " \t") != null) return reject(out, "usage: /fork [NAME]\n", .{});+ const forked = @import("session_fork.zig").forkCurrent(root, keys, arena, if (arg.len == 0) null else arg, null) catch |err| return switch (err) {+ error.NothingToFork => reject(out, "fork failed: this conversation has nothing to fork yet\n", .{}),+ error.InvalidSessionName => reject(out, "fork failed: invalid session or branch name\n", .{}),+ error.BranchMatchesSource => reject(out, "fork failed: the branch name must differ from the current session\n", .{}),+ error.BranchAlreadyExists => reject(out, "fork failed: a session named {s} already exists\n", .{arg}),+ else => reject(out, "fork failed: {t}\n", .{err}),+ };+ presence.noteLabelsFrom(root.io, root.gpa, arena, root.session_title, root.session_name);+ try out.print("forked {s} into {s} ({d} messages); you are on the branch, /resume {s} returns to the original\n", .{ forked.source, forked.target, root.messages.items.len, forked.source });+ try out.flush();+ return true;+}+pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {+ if (try tryFork(root, keys, arena, line, out)) return true;if (!std.mem.startsWith(u8, line, "/resume") or (line.len > 7 and line[7] != ' ' and line[7] != '\t')) return false;const parsed = session_branch.parseSpec(line["/resume".len..]) orelse return reject(out, "usage: /resume SOURCE [--branch DEST]\n", .{});var source = parsed.source;diff --git a/src/help.zig b/src/help.zigindex 5017362e..3c0de4c6 100644--- a/src/help.zig+++ b/src/help.zig@@ -28,7 +28,7 @@ const peers_blurb =;pub const sections = [_]Section{- .{ .title = "getting around", .names = &.{ "/new", "/clear", "/resume", "/save", "/sessions", "/workspace", "/experiment", "/rename", "/rewind", "/edit", "/snapshot", "/teleport" } },+ .{ .title = "getting around", .names = &.{ "/new", "/clear", "/resume", "/fork", "/save", "/sessions", "/workspace", "/experiment", "/rename", "/rewind", "/edit", "/snapshot", "/teleport" } },.{ .title = "the model", .names = &.{ "/model", "/models", "/effort", "/reasoning", "/fast", "/thinking", "/keepcontext", "/fallback", "/routes" } },.{ .title = "working autonomously", .names = &.{ "/goal", "/goals", "/schedule", "/review", "/issue", "/plan", "/todo", "/jobs", "/ultracode", "/strict", "/yolo", "/never" } },.{ .title = "talking to other graffs", .names = &.{ "/tell", "/daddy", "/peek", "/adapter" }, .blurb = peers_blurb },diff --git a/src/main.zig b/src/main.zigindex 97956e4e..a1c7d159 100644--- a/src/main.zig+++ b/src/main.zig@@ -579,7 +579,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = .{ @import("agent_ws_prewarm.zig"), @import("agent_ws_headers.zig") };_ = .{ @import("http2_pool.zig"), @import("agent_stream_h2.zig"), @import("agent_stream_h2_transport_test.zig") }; // h2 stream path, and graff's request/response contract over the pinned http-zig_ = @import("acp_preauth.zig"); // credential-free ACP loop must stay in the test root- _ = .{ @import("acp_protocol.zig"), @import("acp_v2.zig"), @import("acp_v2_prompt.zig"), @import("acp_session_load.zig"), @import("acp_elicit.zig"), @import("hot_context.zig"), @import("history_translate.zig"), @import("mcp_notify.zig"), @import("mcp_wait.zig"), @import("mcp_pages.zig"), @import("mcp_mrtr.zig"), @import("ask_user_args.zig"), @import("mcp_add.zig"), @import("mcp_lazy.zig"), @import("mcp_share.zig"), @import("acp_room.zig"), @import("mcp_catalog.zig"), @import("mcp_watch.zig"), @import("acp_engine_test.zig"), @import("subagent_mimo_tests.zig"), @import("mimo_effort_tests.zig"), @import("gateway_picker_catalog.zig"), @import("ask_user_answers.zig"), @import("job_class.zig"), @import("startup_claim.zig") };+ _ = .{ @import("acp_protocol.zig"), @import("acp_v2.zig"), @import("acp_v2_prompt.zig"), @import("acp_session_load.zig"), @import("acp_session_fork.zig"), @import("session_fork.zig"), @import("acp_elicit.zig"), @import("hot_context.zig"), @import("history_translate.zig"), @import("mcp_notify.zig"), @import("mcp_wait.zig"), @import("mcp_pages.zig"), @import("mcp_mrtr.zig"), @import("ask_user_args.zig"), @import("mcp_add.zig"), @import("mcp_lazy.zig"), @import("mcp_share.zig"), @import("acp_room.zig"), @import("mcp_catalog.zig"), @import("mcp_watch.zig"), @import("acp_engine_test.zig"), @import("subagent_mimo_tests.zig"), @import("mimo_effort_tests.zig"), @import("gateway_picker_catalog.zig"), @import("ask_user_answers.zig"), @import("job_class.zig"), @import("startup_claim.zig") };_ = @import("task_outcome.zig"); // goal-outcome telemetry events_ = @import("learn_delete.zig"); // #303: its tests were dead until listed here_ = .{ @import("additional_tests.zig"), @import("req_stats.zig"), @import("exact_reply.zig"), @import("rlm_order_tests.zig"), @import("async_tool_policy.zig"), @import("agent_async_tools.zig"), @import("request_usage_attempts.zig"), @import("learn_formal.zig") };diff --git a/src/repl_model_commands.zig b/src/repl_model_commands.zigindex 26bfe1ad..8cfd0adb 100644--- a/src/repl_model_commands.zig+++ b/src/repl_model_commands.zig@@ -119,7 +119,7 @@ pub fn runCommand(self: *Model, line: []const u8) void {self.push(.info, "hooks run around the agent loop, not the chat repl") catch {};} else if (eqlAny(cmd, &.{ "/trace", "/trajectory", "/cache" })) {self.push(.info, "trace/trajectory/cache logging is a main-session feature") catch {};- } else if (eqlAny(cmd, &.{ "/save", "/resume", "/sessions", "/workspace", "/ws", "/plugins" })) {+ } else if (eqlAny(cmd, &.{ "/save", "/resume", "/fork", "/sessions", "/workspace", "/ws", "/plugins" })) {self.push(.info, "the chat repl is ephemeral — session save/resume/list/workspace/plugins lives in the main `graff` session") catch {};} else if (std.mem.eql(u8, cmd, "/images")) {self.push(.info, "/images opens image URLs from tool output (e.g. a `gh issue view` result); the chat repl runs no tools — use the main `graff` session for it") catch {};diff --git a/src/session_fork.zig b/src/session_fork.zignew file mode 100644index 00000000..a008ed1e--- /dev/null+++ b/src/session_fork.zig@@ -0,0 +1,171 @@+//! Fork the CURRENT conversation in one step: save it, clone-on-write it into+//! a new session identity, and continue in the branch. Shared by the `/fork`+//! slash command (line REPL, and ACP clients through the same handler) and+//! ACP `session/fork`. The copy itself is session_branch.restore (#689/#697);+//! this module only chooses the names and makes sure the source is on disk.++const std = @import("std");+const builtin = @import("builtin");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const agent_mod = @import("agent.zig");+const provider_mod = @import("provider.zig");+const session = @import("session.zig");+const session_branch = @import("session_branch.zig");++pub const Error = error{NothingToFork};++const marker = "-fork-";++/// The first `<base>-fork-<n>` (n from 1) that `exists` does not claim. A+/// source that is itself an auto-named fork keeps one flat suffix, so forking+/// `chat-fork-1` offers `chat-fork-2` rather than `chat-fork-1-fork-1`; the+/// session file's `parent` still records the real lineage.+pub fn nextName(arena: Allocator, source: []const u8, ctx: anytype, comptime exists: fn (@TypeOf(ctx), []const u8) bool) ![]const u8 {+ var base = stem(source);+ // Leave room for the suffix inside the 128-byte session-name limit.+ const room = 128 - marker.len - 10;+ if (base.len > room) base = base[0..room];+ var n: u32 = 1;+ while (n < std.math.maxInt(u32)) : (n += 1) {+ const candidate = try std.fmt.allocPrint(arena, "{s}{s}{d}", .{ base, marker, n });+ if (!exists(ctx, candidate)) return candidate;+ }+ return error.BranchAlreadyExists;+}++fn stem(source: []const u8) []const u8 {+ const at = std.mem.lastIndexOf(u8, source, marker) orelse return source;+ const digits = source[at + marker.len ..];+ if (at == 0 or digits.len == 0) return source;+ for (digits) |c| if (!std.ascii.isDigit(c)) return source;+ return source[0..at];+}++fn savedHere(root: *agent_mod.Agent, name: []const u8) bool {+ var scratch: [256]u8 = undefined;+ var fba = std.heap.FixedBufferAllocator.init(&scratch);+ return session.sessionExists(root, fba.allocator(), name);+}++/// A fork name for `source` that no save in this workspace uses yet.+pub fn autoName(root: *agent_mod.Agent, arena: Allocator, source: []const u8) ![]const u8 {+ return nextName(arena, source, root, savedHere);+}++/// Save the live conversation under its own name (so a never-saved one lands+/// where its autosave would), then branch it to `dest` or an automatic name.+/// The source file is not rewritten after this save: every later turn writes+/// the branch. `model_override` follows session_branch.restore.+pub fn forkCurrent(root: *agent_mod.Agent, keys: *provider_mod.Keys, arena: Allocator, dest: ?[]const u8, model_override: ?provider_mod.Provider) !session_branch.Result {+ const source = try arena.dupe(u8, root.session_name);+ if (!session.validSessionName(source)) return error.InvalidSessionName;+ try session.saveSession(root, arena, source);+ // #184: a conversation with nothing in it is never written, so there is+ // nothing durable to branch from.+ if (!session.sessionExists(root, arena, source)) return Error.NothingToFork;+ const target = dest orelse try autoName(root, arena, source);+ return session_branch.restore(root, keys, arena, source, target, model_override);+}++fn takenIn(set: []const []const u8, name: []const u8) bool {+ for (set) |taken| if (std.mem.eql(u8, taken, name)) return true;+ return false;+}++test "fork auto-names count up past existing saves and stay flat for forks of forks" {+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ const a = state.allocator();+ const none: []const []const u8 = &.{};+ try std.testing.expectEqualStrings("chat-fork-1", try nextName(a, "chat", none, takenIn));+ const some: []const []const u8 = &.{ "chat-fork-1", "chat-fork-2" };+ try std.testing.expectEqualStrings("chat-fork-3", try nextName(a, "chat", some, takenIn));+ try std.testing.expectEqualStrings("chat-fork-3", try nextName(a, "chat-fork-2", some, takenIn));+ // Only a numeric suffix is ours to strip.+ try std.testing.expectEqualStrings("my-fork-x-fork-1", try nextName(a, "my-fork-x", none, takenIn));+ try std.testing.expectEqualStrings("-fork-3-fork-1", try nextName(a, "-fork-3", none, takenIn));+ const long = &@import("util.zig").repeatBytes("x", 128);+ const named = try nextName(a, long, none, takenIn);+ try std.testing.expect(session.validSessionName(named));+ try std.testing.expect(std.mem.endsWith(u8, named, "-fork-1"));+}++test "/fork branches the current conversation and leaves the source save untouched" {+ if (builtin.os.tag == .windows) return error.SkipZigTest; // fchdir isolation is POSIX-only+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var orig_dir = try Io.Dir.cwd().openDir(io, ".", .{});+ defer orig_dir.close(io);+ defer _ = std.posix.system.fchdir(orig_dir.handle);+ if (std.posix.system.fchdir(tmp.dir.handle) != 0) return error.ChdirFailed;+ const writer = @import("session_writer.zig");+ const transcript = @import("session_transcript.zig");+ writer.resetForTest();+ defer writer.resetForTest();+ transcript.resetForTest();+ defer transcript.resetForTest();++ var client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer client.deinit();+ var keys: provider_mod.Keys = .{ .values = @splat("k") };+ var root: agent_mod.Agent = .{+ .gpa = gpa,+ .arena = arena,+ .io = io,+ .client = &client,+ .provider = try keys.providerById("anthropic", "sonnet"),+ .messages = (try std.json.parseFromSliceLeaky(std.json.Value, arena, "[{\"role\":\"user\",\"content\":\"fork me\"},{\"role\":\"assistant\",\"content\":\"forked answer\"}]", .{})).array,+ .sub = false,+ .label = "root",+ .out = null,+ .home = "home", // relative to the tmp cwd; no saves there+ .stored_keys_loaded = true,+ };+ defer root.tools_used.deinit(gpa);+ root.session_name = "chat"; // never saved yet: /fork saves it first+ var aw: Io.Writer.Allocating = .init(gpa);+ defer aw.deinit();++ try @import("main.zig").handleCommand(&root, &keys, arena, "/fork", &aw.writer);+ const said = aw.writer.buffered();+ try std.testing.expect(std.mem.indexOf(u8, said, "forked chat into chat-fork-1") != null);+ try std.testing.expect(std.mem.indexOf(u8, said, "/resume chat") != null);+ try std.testing.expectEqualStrings("chat-fork-1", root.session_name);+ try std.testing.expectEqualStrings("chat", root.session_parent.?);+ try std.testing.expectEqual(@as(usize, 2), root.messages.items.len);+ session.flushSaves();+ const source_before = try tmp.dir.readFileAlloc(io, ".graff/sessions/chat.session.json", arena, .unlimited);+ try std.testing.expect(std.mem.indexOf(u8, source_before, "forked answer") != null);+ const branch = try tmp.dir.readFileAlloc(io, ".graff/sessions/chat-fork-1.session.json", arena, .unlimited);+ try std.testing.expect(std.mem.indexOf(u8, branch, "\"parent\":\"chat\"") != null);++ // A turn on the branch writes the branch, never the source.+ var turn: std.json.ObjectMap = .empty;+ try turn.put(arena, "role", .{ .string = "user" });+ try turn.put(arena, "content", .{ .string = "only on the branch" });+ try root.messages.append(.{ .object = turn });+ try session.saveSession(&root, arena, root.session_name);+ const source_after = try tmp.dir.readFileAlloc(io, ".graff/sessions/chat.session.json", arena, .unlimited);+ try std.testing.expectEqualStrings(source_before, source_after);+ const branch_after = try tmp.dir.readFileAlloc(io, ".graff/sessions/chat-fork-1.session.json", arena, .unlimited);+ try std.testing.expect(std.mem.indexOf(u8, branch_after, "only on the branch") != null);++ // Forking the branch picks the next free flat name; an explicit name that+ // is taken is refused without moving the session.+ aw.clearRetainingCapacity();+ try @import("main.zig").handleCommand(&root, &keys, arena, "/fork", &aw.writer);+ try std.testing.expectEqualStrings("chat-fork-2", root.session_name);+ try std.testing.expectEqualStrings("chat-fork-1", root.session_parent.?);+ try std.testing.expectEqualStrings(source_before, try tmp.dir.readFileAlloc(io, ".graff/sessions/chat.session.json", arena, .unlimited));+ aw.clearRetainingCapacity();+ try @import("main.zig").handleCommand(&root, &keys, arena, "/fork chat-fork-1", &aw.writer);+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "already exists") != null);+ try std.testing.expectEqualStrings("chat-fork-2", root.session_name);+}