graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Report a workspace switch to the ACP client when it happens
Rach Pradhan6b00c4b8fcfe
diff --git a/docs/acp-compatibility.md b/docs/acp-compatibility.mdindex d855b220..bd7399b4 100644--- a/docs/acp-compatibility.md+++ b/docs/acp-compatibility.md@@ -25,7 +25,7 @@ optional feature or draft extension is enabled.| Initialization | Return protocol version 1 and explicit capabilities. Clients must reject a version they cannot speak. | `src/acp_protocol.zig`, `scripts/test-acp-startup.py`, `sdk/ts/acp.test.ts` || Authentication | Credential-free initialization is available. Operations requiring a live agent remain authentication-gated. | `scripts/test-acp-preauth.py` || Sessions | Create a session in its selected workspace. A live process owns one session; duplicate creation cannot replace its history. Load is advertised only when the live implementation can replay saved history. | `scripts/test-acp-session-load.py`, `scripts/test-acp-released-fixes.py` |-| Workspace and worktrees | `session/new` and `session/load` adopt the client's absolute `cwd`; naming the checkout that owns a `-w` or auto-isolated tree keeps that tree. Replies carry `_meta["graff/worktree"]` (`name`, `path`, `branch`, `base`, `baseSha`, `root`, `generated`, or `null` in a main checkout). A workspace switch emits `session_info_update` with the same `_meta`. | `scripts/test-acp-workspace.py`, `src/acp_workspace.zig`, ADR 0202 |+| Workspace and worktrees | `session/new` and `session/load` adopt the client's absolute `cwd`; naming the checkout that owns a `-w` or auto-isolated tree keeps that tree. Replies carry `_meta["graff/worktree"]` (`name`, `path`, `branch`, `base`, `baseSha`, `root`, `generated`, or `null` in a main checkout). A workspace switch emits `session_info_update` with the same `_meta` plus `graff/cwd`, right after the `workspace` tool result (before the next call), or before the reply for `/workspace use`. | `scripts/test-acp-workspace.py`, `src/acp_workspace.zig`, ADR 0202 || Prompt lifecycle | Stream session-scoped updates and return the terminal stop reason. Cancellation interrupts the active turn and cannot grant a pending permission. | `scripts/test-acp-failure.py`, `scripts/test-acp-permissions.py` || Tool calls | Preserve call identity, status and terminal results. Tool-like prose is not execution evidence. | `src/acp_stream.zig`, `src/agent_steps_tests.zig` || Questions (`ask_user`) | A client that advertises `clientCapabilities.elicitation.form` gets a standard `elicitation/create` form request (one required `answer` string, an `enum` when the model offered choices); `accept` returns the answer, `decline`/`cancel` end the question. A client that opts in with `_meta["graff/askUser"]` gets graff's `gui_ask_user` and answers with `session/answer`. Any other client cannot show the question, so `ask_user` returns at once and tells the model to assume or ask in its reply; it never waits on a client that cannot answer. | `scripts/test-acp-ask-user.py`, `src/acp_elicit.zig` |diff --git a/docs/adr/0202-acp-sessions-adopt-client-cwd.md b/docs/adr/0202-acp-sessions-adopt-client-cwd.mdindex 7c7db101..6b9105d2 100644--- a/docs/adr/0202-acp-sessions-adopt-client-cwd.md+++ b/docs/adr/0202-acp-sessions-adopt-client-cwd.md@@ -33,8 +33,14 @@ build. The top-level `cwd` field is removed.No other folder is searched.When `/workspace use` or the `workspace` tool moves the root session, the-prompt reply is preceded by `session_info_update` whose `_meta` carries the-new value.+client gets `session_info_update` whose `_meta` carries the new+`graff/worktree` value and `graff/cwd`, the session's absolute working+directory (so a switch into a main checkout or a non-graff tree is still+addressable). The tool's switch is reported right after its tool result,+before the model's next call, not at turn end: a client that serves tools+resolving paths against the session's folder (image attachment) must follow+it within the turn (#1737). A slash switch is reported before the prompt+reply. Each switch is reported once.`graff worktree` exits 1 when it refuses or fails and 2 when it does nothing(`kept`), so hosts can branch on the status instead of the text.diff --git a/src/acp_engine.zig b/src/acp_engine.zigindex 4f373739..3771b87d 100644--- a/src/acp_engine.zig+++ b/src/acp_engine.zig@@ -199,7 +199,7 @@ fn promptTurn(d: *Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request)if (d.bind_session) |bind| bind(d.ctx, sid);@import("acp_citations.zig").endTurn(sid); // a failed turn must not leave a marker openconst config_before = configOptions(d, arena) catch |err| return turnError(d, w, req, err);- const workspace_before = acp_workspace.snapshot(d.workspace, arena);+ acp_workspace.snapshot(d.workspace);// Before slash handling: an agent's room line must not run as a command.const flat = try flattenPrompt(arena, if (obj) |o| o.get("prompt") else null);const text = try @import("acp_room.zig").frame(arena, req.params, flat);@@ -211,7 +211,7 @@ fn promptTurn(d: *Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request)if (reply) |plain| {if (plain.len > 0) try writeSessionUpdate(w, sid, try @import("acp_t3.zig").slashReply(arena, plain));emitConfigChange(d, arena, w, sid, config_before) catch |config_err| return turnError(d, w, req, config_err);- try acp_workspace.emitChange(d.workspace, arena, w, sid, workspace_before);+ try acp_workspace.emitChange(d.workspace, arena, w, sid);try emitMeter(d, w, sid);if (resend_key) |key| resent.finish(key, 0, "end_turn");return respondStop(d, w, req, sid, "end_turn");@@ -224,7 +224,7 @@ fn promptTurn(d: *Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request)};if (final.len > 0) try writeSessionUpdate(w, sid, final);emitConfigChange(d, arena, w, sid, config_before) catch |config_err| return turnError(d, w, req, config_err);- try acp_workspace.emitChange(d.workspace, arena, w, sid, workspace_before);+ try acp_workspace.emitChange(d.workspace, arena, w, sid);try emitMeter(d, w, sid);const extra = if (extra_cancelled) |f| f() else false;const stop: []const u8 = if (cancel_flag.load(.acquire) or extra) "cancelled" else "end_turn";diff --git a/src/acp_stream.zig b/src/acp_stream.zigindex b1ee1dff..ca222775 100644--- a/src/acp_stream.zig+++ b/src/acp_stream.zig@@ -221,6 +221,7 @@ pub fn translateTracked(return .tool_end;}try writeToolDone(w, session_id, use_id, is_error, text, @import("run_task_meta.zig").fromEvent(ev));+ try @import("acp_workspace.zig").emitMoved(w, session_id); // #1737: `workspace use` mid-turnreturn .tool_end;}if (std.mem.eql(u8, typ, "ask_user")) {diff --git a/src/acp_v2_prompt.zig b/src/acp_v2_prompt.zigindex 53a89e48..2e08aba0 100644--- a/src/acp_v2_prompt.zig+++ b/src/acp_v2_prompt.zig@@ -23,7 +23,7 @@ pub fn promptTurn(d: *engine.Dispatch, arena: Allocator, w: *Io.Writer, req: pro// JSON-RPC error is still the right answer.const config_before = engine.configOptions(d, arena) catch |err|return engine.respondError(w, req, proto.err_internal, @errorName(err));- const workspace_before = acp_workspace.snapshot(d.workspace, arena);+ acp_workspace.snapshot(d.workspace);// Before slash handling: an agent's room line must not run as a command.const text = try @import("acp_room.zig").frame(arena, req.params, try proto.flattenPrompt(arena, prompt));var id_buf: [48]u8 = undefined;@@ -35,7 +35,7 @@ pub fn promptTurn(d: *engine.Dispatch, arena: Allocator, w: *Io.Writer, req: proconst outcome = run(d, arena, w, sid, text, prompt);engine.emitConfigChange(d, arena, w, sid, config_before) catch {};- acp_workspace.emitChange(d.workspace, arena, w, sid, workspace_before) catch {};+ acp_workspace.emitChange(d.workspace, arena, w, sid) catch {};try engine.emitMeter(d, w, sid);switch (outcome) {.stop => |stop| try v2.writeIdle(w, sid, stop),diff --git a/src/acp_workspace.zig b/src/acp_workspace.zigindex fff6f8b4..387abe96 100644--- a/src/acp_workspace.zig+++ b/src/acp_workspace.zig@@ -140,21 +140,63 @@ pub fn enterSavedTree(env: Env, arena: Allocator, session_id: []const u8) bool {return false;}-/// Taken before a prompt turn; compared by `emitChange` after it.-pub fn snapshot(env: ?Env, arena: Allocator) []const u8 {- if (env == null) return "";- return arena.dupe(u8, main_mod.g_cwd_display) catch "";+/// `session_info_update` meta: the tree plus the session's absolute cwd, so a+/// client can re-root cwd-relative work (image attachment, files panel) even+/// when the new folder is a main checkout or a non-graff worktree (#1737).+pub const ChangeMeta = struct { @"graff/worktree": ?Info, @"graff/cwd": []const u8 };++/// The live session's env and the cwd the client was last told about. The+/// event stream reads them to report a mid-turn switch (`emitMoved`) without+/// threading the dispatch through it. Embeds and the REPL leave env null.+var live_env: ?Env = null;+var reported_buf: [std.fs.max_path_bytes]u8 = undefined;+var reported_len: usize = 0;++fn remember(cwd: []const u8) void {+ reported_len = @min(cwd.len, reported_buf.len);+ @memcpy(reported_buf[0..reported_len], cwd[0..reported_len]);}-/// `/workspace use` and the `workspace` tool move the root session. Tell the-/// client with `session_info_update` so it can re-record the chat's tree.-pub fn emitChange(env: ?Env, arena: Allocator, w: *Io.Writer, session_id: []const u8, before: []const u8) !void {- const e = env orelse return;- if (std.mem.eql(u8, before, main_mod.g_cwd_display)) return;+/// Taken before a prompt turn: the client already knows this cwd.+pub fn snapshot(env: ?Env) void {+ live_env = env orelse return;+ remember(main_mod.g_cwd_display);+}++fn emitIfMoved(e: Env, arena: Allocator, w: *Io.Writer, session_id: []const u8) !void {+ const cwd = main_mod.g_cwd_display;+ if (std.mem.eql(u8, reported_buf[0..reported_len], cwd)) return;try proto.writeNotification(w, "session/update", .{.sessionId = session_id,- .update = .{ .sessionUpdate = "session_info_update", ._meta = meta(e, arena) },+ .update = .{ .sessionUpdate = "session_info_update", ._meta = ChangeMeta{+ .@"graff/worktree" = info(e, arena),+ .@"graff/cwd" = cwd,+ } },});+ remember(cwd);+}++/// `/workspace use` and the `workspace` tool move the root session. Tell the+/// client with `session_info_update` so it can re-record the chat's tree.+/// Silent when `emitMoved` already reported the switch during the turn.+pub fn emitChange(env: ?Env, arena: Allocator, w: *Io.Writer, session_id: []const u8) !void {+ try emitIfMoved(env orelse return, arena, w, session_id);+}++/// After a root tool result: report a switch the moment it happens, before+/// the model's next call. Waiting for the turn to end left the client+/// resolving tools it serves (show_image) against the old tree (#1737).+pub fn emitMoved(w: *Io.Writer, session_id: []const u8) !void {+ const e = live_env orelse return;+ if (std.mem.eql(u8, reported_buf[0..reported_len], main_mod.g_cwd_display)) return;+ var arena_state = std.heap.ArenaAllocator.init(e.gpa);+ defer arena_state.deinit();+ try emitIfMoved(e, arena_state.allocator(), w, session_id);+}++pub fn resetForTest() void {+ live_env = null;+ reported_len = 0;}test "fromRevParse: a linked tree reports its name, branch, and owning checkout" {@@ -189,6 +231,51 @@ test "Meta serializes an explicit null for the main checkout" {try std.testing.expectEqualStrings("{\"graff/worktree\":null}", w.buffered());}+test "#1737: a mid-turn workspace switch reaches the client with the tool result, once" {+ const a = std.testing.allocator;+ var arena = std.heap.ArenaAllocator.init(a);+ defer arena.deinit();+ const saved = main_mod.g_cwd_display;+ defer main_mod.g_cwd_display = saved;+ defer resetForTest();+ const stream = @import("acp_stream.zig");+ const ev = try std.json.parseFromSliceLeaky(Value, arena.allocator(),+ \\{"type":"tool_result","id":"call-7","name":"workspace","text":"now at /trees/other","is_error":false}+ , .{});+ var id_buf: [64]u8 = @splat(0);+ var next: u32 = 0;+ var buf: [8192]u8 = undefined;++ // Without a live ACP session (REPL, embeds) nothing extra is written.+ main_mod.g_cwd_display = "/trees/launch";+ var quiet: Io.Writer = .fixed(&buf);+ _ = try stream.translateEvent(&quiet, "s1", ev, &id_buf, &next);+ try std.testing.expect(std.mem.indexOf(u8, quiet.buffered(), "session_info_update") == null);++ // Live session: the switch is reported right after the tool's own update.+ snapshot(.{ .gpa = a, .io = std.testing.io });+ main_mod.g_cwd_display = "/trees/other";+ var w: Io.Writer = .fixed(&buf);+ _ = try stream.translateEvent(&w, "s1", ev, &id_buf, &next);+ const out = w.buffered();+ const done = std.mem.indexOf(u8, out, "call-7") orelse return error.TestExpectedToolUpdate;+ const info_at = std.mem.indexOf(u8, out, "\"session_info_update\"") orelse return error.TestExpectedInfoUpdate;+ try std.testing.expect(done < info_at);+ try std.testing.expect(std.mem.indexOf(u8, out, "\"graff/cwd\":\"/trees/other\"") != null);++ // Already told: neither the next tool result nor turn end repeats it.+ var again: Io.Writer = .fixed(&buf);+ _ = try stream.translateEvent(&again, "s1", ev, &id_buf, &next);+ try emitChange(.{ .gpa = a, .io = std.testing.io }, arena.allocator(), &again, "s1");+ try std.testing.expect(std.mem.indexOf(u8, again.buffered(), "session_info_update") == null);++ // A slash switch (no tool result) is still reported at turn end.+ main_mod.g_cwd_display = "/trees/third";+ var end: Io.Writer = .fixed(&buf);+ try emitChange(.{ .gpa = a, .io = std.testing.io }, arena.allocator(), &end, "s1");+ try std.testing.expect(std.mem.indexOf(u8, end.buffered(), "\"graff/cwd\":\"/trees/third\"") != null);+}+test "errorText names the cwd problem" {try std.testing.expectEqualStrings("Session cwd must be an absolute path", errorText(error.RelativeCwd));try std.testing.expectEqualStrings("Session cwd does not exist or is not a directory", errorText(error.MissingCwd));diff --git a/src/read_image.zig b/src/read_image.zigindex a1adff14..2335641e 100644--- a/src/read_image.zig+++ b/src/read_image.zig@@ -135,6 +135,60 @@ test "native image read stages pixels and tool checkpoint sends them without a utry std.testing.expect(reg.pending_image == null);}+test "#1737: after workspace use, an image in the new tree attaches; one outside both trees is refused" {+ if (builtin.os.tag == .windows) return error.SkipZigTest; // enterPath is POSIX-only+ const a = std.testing.allocator;+ const io = std.testing.io;+ const policy = @import("harness_policy.zig");+ const switcher = @import("workspace_switch.zig");+ const main_mod = @import("main.zig");+ var launch = std.testing.tmpDir(.{});+ defer launch.cleanup();+ var other = std.testing.tmpDir(.{});+ defer other.cleanup();+ var outside = std.testing.tmpDir(.{});+ defer outside.cleanup();+ try other.dir.writeFile(io, .{ .sub_path = "shot.png", .data = tiny_png });+ try outside.dir.writeFile(io, .{ .sub_path = "shot.png", .data = tiny_png });+ var orig = try Io.Dir.cwd().openDir(io, ".", .{});+ defer orig.close(io);+ defer _ = std.posix.system.fchdir(orig.handle);+ const saved = .{ main_mod.g_cwd_display, main_mod.g_worktree_branch };+ defer {+ main_mod.g_cwd_display = saved[0];+ main_mod.g_worktree_branch = saved[1];+ switcher.deinitDisplay(a);+ @import("tool_spill.zig").resetForTest();+ }+ var arena = std.heap.ArenaAllocator.init(a);+ defer arena.deinit();+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const other_abs = try arena.allocator().dupe(u8, buf[0..try other.dir.realPath(io, &buf)]);+ const outside_abs = try arena.allocator().dupe(u8, buf[0..try outside.dir.realPath(io, &buf)]);+ if (std.posix.system.fchdir(launch.dir.handle) != 0) return error.ChdirFailed;+ _ = try switcher.enterPath(a, io, arena.allocator(), other_abs);++ // The native tools' own confinement now roots at the switched tree.+ try std.testing.expect(policy.confinedPath("shot.png") and policy.noSymlinkEscape(io, "shot.png", null));+ const resolved = try @import("codedbpro_paths.zig").sessionAbs(a, io, null, "shot.png");+ defer a.free(resolved);+ try std.testing.expect(std.mem.startsWith(u8, resolved, other_abs));+ var reg = @import("mcp.zig").Registry.empty(a, io);+ defer reg.deinit();+ var ctx: ToolCtx = undefined;+ ctx.registry = ®+ ctx.provider = .{ .id = "test", .kind = .responses, .auth = .bearer, .url = "", .api_key = "", .model = "gpt-5", .context = 100000 };+ const out = (try stage(a, io, ctx, resolved, "shot.png", tiny_png.len)).?;+ defer a.free(out.text);+ try std.testing.expect(!out.is_error);+ try std.testing.expect(reg.pending_image != null);++ // Outside both the launch tree and the switched tree: still refused.+ const escaped = try std.fmt.allocPrint(arena.allocator(), "{s}/shot.png", .{outside_abs});+ try std.testing.expect(!policy.confinedPath(escaped) and !policy.noSymlinkEscape(io, escaped, null));+ try std.testing.expect(!policy.confinedPath("../outside/shot.png"));+}+/// 1x1 PNG a fake resizer "downscales" to.const tiny_png = "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\x00\x00\x01\x00\x00\x00\x01\x08\x04\x00\x00\x00\xb5\x1c\x0c\x02\x00\x00\x00\x0b\x49\x44\x41\x54\x78\xda\x63\xfc\xff\x1f\x00\x03\x03\x02\x00\xef\x9a\x0f\x5b\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82";