graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
acp: sessions adopt the client cwd and report worktrees in _meta
Rach Pradhanc80814937e60
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e9ae5ce4..0b92204a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,14 @@ current is part of cutting a release.- ACP clients can pass MCP servers in `session/new` and `session/load`, and `GRAFF_NO_PLUGINS` now applies before those servers connect.- Opted-in ACP clients can preview child-agent activity live, and background workers stream through a Graff extension across turns. Session teardown waits for background agents, and deferred MCP startup joins run under the registry lock.+### Workspaces over ACP++- ACP sessions now use the folder the client asks for on `session/new` and `session/load`, as the protocol requires, instead of the folder graff was launched in. A relative or missing folder is rejected.+- The worktree a session runs in is reported as `_meta["graff/worktree"]` (name, path, branch, base, owning checkout, and whether graff generated it), or `null` in a main checkout. The non-standard top-level `cwd` in the `session/new` reply is gone; the desktop app reads the new field and still accepts older builds.+- Reopening a session works from the repository root when the process runs in a `-w` tree, and from a main checkout when the save lives in one of its worktrees. Switching workspace mid-session sends `session_info_update`.+- `-w` sessions record their real worktree path. They used `$PWD`, which names the host's own folder when an app launches graff, so their saves pointed at a path that did not exist.+- `graff worktree` exits 1 when it refuses or fails and 2 when it does nothing, instead of always 0. Merging a workspace that does not exist now says so.+### Optional formal evidence for local learning- Bounded lifecycle models cover effort changes, asynchronous tools, permission ownership, and connection leases. Deliberately weakened configurations provide counterexamples for the invariants those models are meant to guard.diff --git a/apps/native/lib/acp-bootstrap.test.ts b/apps/native/lib/acp-bootstrap.test.tsindex 8171c582..e0e419c4 100644--- a/apps/native/lib/acp-bootstrap.test.ts+++ b/apps/native/lib/acp-bootstrap.test.ts@@ -15,7 +15,8 @@ async function worker(mode: string) {require('node:readline').createInterface({input:process.stdin}).on('line', line => {const req=JSON.parse(line);if(req.method==='initialize' && mode!=='initialize') send({id:req.id,result:{protocolVersion:1}});- if(req.method==='session/new' && mode!=='session/new') send({id:req.id,result:mode==='invalid'?{}:mode==='isolated'?{sessionId:'ready',cwd:'/isolated/tree'}:{sessionId:'ready'}});+ const results={invalid:{},isolated:{sessionId:'ready',cwd:'/isolated/tree'},worktree:{sessionId:'ready',_meta:{'graff/worktree':{name:'harness-1',path:'/repo/.graff/worktrees/harness-1',branch:'worktree-harness-1',base:'main',baseSha:null,root:'/repo',generated:false}}},main:{sessionId:'ready',cwd:'/stale',_meta:{'graff/worktree':null}}};+ if(req.method==='session/new' && mode!=='session/new') send({id:req.id,result:results[mode]??{sessionId:'ready'}});});console.log('ready');`], { stdio: ["pipe", "pipe", "inherit"] });@@ -121,6 +122,20 @@ test("session/new checkout binds the worker to its isolated worktree", async ()} finally { await retireWorker(isolated.child, 50); }});+test("session/new binds to the worktree graff reports in _meta; null means the requested folder", async () => {+ const noRetire = async () => { throw new Error("A successful handshake must not retire its child"); };+ const tree = await worker("worktree");+ try {+ expect(await initializeWorker(tree.transport, "/repo", noRetire, 1000))+ .toEqual({ sessionId: "ready", cwd: "/repo/.graff/worktrees/harness-1" });+ } finally { await retireWorker(tree.child, 50); }+ const main = await worker("main");+ try {+ // An explicit null wins over a stray legacy field.+ expect(await initializeWorker(main.transport, "/repo", noRetire, 1000)).toEqual({ sessionId: "ready" });+ } finally { await retireWorker(main.child, 50); }+});+test("overlapping startup and first prompt share a completed worker", async () => {const pending = new Map<string, Promise<string>>();let live: Awaited<ReturnType<typeof worker>> | undefined;diff --git a/apps/native/lib/acp-bootstrap.ts b/apps/native/lib/acp-bootstrap.tsindex 8ab2d8b0..dc27c79e 100644--- a/apps/native/lib/acp-bootstrap.ts+++ b/apps/native/lib/acp-bootstrap.ts@@ -23,6 +23,19 @@ export function bindSessionCwd(requested: string, reported?: string, hostCwd = preturn resolved;}+/** The worker's checkout from a session/new or session/load result. Graff+ * reports its worktree as `_meta["graff/worktree"]` (null: the requested+ * folder itself); older builds sent a non-standard top-level `cwd`. */+export function sessionCheckout(result: { cwd?: unknown; _meta?: unknown } | null | undefined): string | undefined {+ const meta = result?._meta;+ if (meta && typeof meta === "object" && "graff/worktree" in meta) {+ const tree = (meta as Record<string, unknown>)["graff/worktree"];+ const at = tree && typeof tree === "object" ? (tree as { path?: unknown }).path : undefined;+ return typeof at === "string" && at.trim() ? at.trim() : undefined;+ }+ return typeof result?.cwd === "string" && result.cwd.trim() ? result.cwd.trim() : undefined;+}+/** A failed handshake cannot recover from a late reply. Retire its worker* before reporting failure so a retry starts with a fresh transport. */export async function initializeWorker(@@ -35,11 +48,11 @@ export async function initializeWorker(throw new Error("initialize returned an unsupported or missing protocolVersion; expected 1");}phase = "session/new";- const created = await transport.request(phase, { cwd, mcpServers: [] }, timeoutMs) as { sessionId?: unknown; cwd?: unknown } | null;+ const created = await transport.request(phase, { cwd, mcpServers: [] }, timeoutMs) as { sessionId?: unknown; cwd?: unknown; _meta?: unknown } | null;if (typeof created?.sessionId !== "string" || !created.sessionId) {throw new Error("session/new returned no sessionId");}- const checkout = typeof created.cwd === "string" && created.cwd.trim() ? created.cwd.trim() : undefined;+ const checkout = sessionCheckout(created);return checkout ? { sessionId: created.sessionId, cwd: checkout } : { sessionId: created.sessionId };} catch (cause) {const detail = cause instanceof Error ? cause.message : String(cause);diff --git a/build.zig b/build.zigindex 84e05193..02585754 100644--- a/build.zig+++ b/build.zig@@ -155,6 +155,9 @@ pub fn build(b: *std.Build) void {const workspace_lifecycle_test = b.addSystemCommand(&.{ "python3", "scripts/test-workspace-lifecycle.py" });workspace_lifecycle_test.addArtifactArg(exe);test_step.dependOn(&workspace_lifecycle_test.step);+ const acp_workspace_test = b.addSystemCommand(&.{ "python3", "scripts/test-acp-workspace.py" });+ acp_workspace_test.addArtifactArg(exe);+ test_step.dependOn(&acp_workspace_test.step);const run_tool_budget_test = b.addSystemCommand(&.{ "python3", "scripts/test-run-tool-budget.py" });run_tool_budget_test.addArtifactArg(exe);test_step.dependOn(&run_tool_budget_test.step);diff --git a/docs/acp-compatibility.md b/docs/acp-compatibility.mdindex 5136220f..f99b33e7 100644--- a/docs/acp-compatibility.md+++ b/docs/acp-compatibility.md@@ -23,6 +23,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 || 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` || Permissions | Send the advertised choices to the active client and await its response. Clients must honor an explicit rejection or cancellation; automatic approval is a separate user setting. | `scripts/test-acp-permissions.py` |diff --git a/docs/adr/0146-concurrent-sessions-auto-isolate.md b/docs/adr/0146-concurrent-sessions-auto-isolate.mdindex e6393222..049c4689 100644--- a/docs/adr/0146-concurrent-sessions-auto-isolate.md+++ b/docs/adr/0146-concurrent-sessions-auto-isolate.md@@ -30,7 +30,7 @@ Finish is not archive.`isolation_fallback` / `GRAFF_ISOLATION_FALLBACK=1`.- Finish / `graff worktree archive` keep dirty or unique-commit trees. Archiveremoves only a clean checkout whose commits exist elsewhere.-- `session/new` reports the checkout `cwd` so GUI chats bind to that tree.+- `session/new` reports the checkout so GUI chats bind to that tree. Superseded in form by ADR 0202: it is `_meta["graff/worktree"]`, not a top-level `cwd`.## Consequencesdiff --git a/docs/adr/0202-acp-sessions-adopt-client-cwd.md b/docs/adr/0202-acp-sessions-adopt-client-cwd.mdnew file mode 100644index 00000000..7c7db101--- /dev/null+++ b/docs/adr/0202-acp-sessions-adopt-client-cwd.md@@ -0,0 +1,50 @@+# 0202. ACP sessions adopt the client cwd and report worktrees in `_meta`++Status: accepted 2026-09-25++## Context++ACP requires an absolute `cwd` on `session/new` and `session/load`, and the+agent must use it regardless of where it was spawned. Graff ignored it on+`session/new` and ran in its launch folder. It reported an isolated checkout+as a top-level `cwd` in the reply, which ACP does not allow: extensions belong+in `_meta`. `session/load` accepted only the exact folder the process was+running in, so a host that relaunches `graff acp -w <name>` for every turn and+names the repository root was refused, and a save made inside a linked tree+could not be reopened from the main checkout.++## Decision++`session/new` and `session/load` make the client's `cwd` the session's+working directory: tools, relative paths, `.graff/` storage and path+confinement follow it. A relative or missing directory is an invalid-params+error. When the client names the checkout that owns the process's `-w` or+auto-isolated tree, the process keeps that tree.++Both replies carry `_meta["graff/worktree"]`. It is an object with `name`+(the `-w` name: branch minus `worktree-`, else the folder name), `path`,+`branch`, `base` (the recorded landing branch or null), `baseSha`, `root`+(the owning main checkout) and `generated` (an auto-isolated `session-*`+tree), or an explicit `null` in a main checkout. A missing key means an older+build. The top-level `cwd` field is removed.++`session/load` from a main checkout also finds a save inside one of its own+`.graff/worktrees/*` trees and re-enters it, matching CLI resume (ADR 0155).+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.++`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.++## Consequences++Hosts learn the worktree and branch from the protocol and can pin a chat to a+named tree (`-w`). Auto-isolated `session-*` trees are reaped once their+process is gone (ADR 0147), so hosts that relaunch per turn should pin named+trees, not generated ones. The system prompt's project instructions and repo+map are still read from the launch folder; a `session/new` in an unrelated+folder keeps them until that is rebuilt per session. This supersedes the+ADR 0146 line about reporting the checkout as `cwd`.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex c46d6ea0..efe08cbb 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -228,6 +228,7 @@ record only when you need the evidence or the edge cases.| [0199](0199-generated-checkouts-belong-to-project-history.md) | Generated worktree activity rolls up to the owning project in automatic suggestions; explicitly saved checkouts stay selectable. || [0200](0200-desktop-page-transitions-preserve-tabs.md) | Desktop restart/reload confirms active-turn interruption and restores tab references from saved sessions in their workspaces. || [0201](0201-cli-beta-channel-is-explicit.md) | CLI beta updates require explicit opt-in, select the newest numeric release branch, verify pinned assets, and activate on next launch. |+| [0202](0202-acp-sessions-adopt-client-cwd.md) | ACP sessions adopt the client `cwd`, report the worktree as `_meta["graff/worktree"]` (null in a main checkout), and `graff worktree` exits non-zero when it refuses or does nothing. |## When to write onediff --git a/scripts/eval-tier1.sh b/scripts/eval-tier1.shindex c21b7eb9..d2440318 100755--- a/scripts/eval-tier1.sh+++ b/scripts/eval-tier1.sh@@ -188,7 +188,8 @@ if wanted shell; thenpython3 scripts/eval/process_guard.py --timeout 90 python3 scripts/test-shell-restart.py zig-out/bin/graff &&python3 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-load.py zig-out/bin/graff &&+ python3 scripts/eval/process_guard.py --timeout 120 python3 scripts/test-acp-workspace.py zig-out/bin/graff); then :; elserecord_fail shellfidiff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.jsonindex 857b45e2..510a5812 100644--- a/scripts/eval/tier1-manifest.json+++ b/scripts/eval/tier1-manifest.json@@ -15,7 +15,7 @@"src/repl.zig","TUI/root.zig"],- "test_count_baseline": 2813,+ "test_count_baseline": 2818,"test_count_slack": 25,"required_invariants": [{diff --git a/scripts/test-acp-workspace.py b/scripts/test-acp-workspace.pynew file mode 100755index 00000000..e82a9084--- /dev/null+++ b/scripts/test-acp-workspace.py@@ -0,0 +1,149 @@+#!/usr/bin/env python3+"""Offline ACP workspace contract (ADR 0202): the client cwd wins, worktrees ride+`_meta["graff/worktree"]`, loads accept the owning checkout, switches notify."""+import importlib.util+import json+import os+import subprocess+import sys+import tempfile+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_session_load_fixture", REPO / "scripts/test-acp-session-load.py")+_fixture = importlib.util.module_from_spec(_spec)+_spec.loader.exec_module(_fixture)+Acp, tool_text = _fixture.Acp, _fixture.tool_text+++def repo(parent, name):+ path = parent / name+ path.mkdir()+ for args in (["init", "-q", "-b", "main"], ["config", "user.email", "[email protected]"],+ ["config", "user.name", "T"], ["commit", "-q", "--allow-empty", "-m", "init"]):+ subprocess.run(["git", "-C", str(path), *args], check=True, capture_output=True)+ return path.resolve()+++def worktree(result):+ return (result.get("_meta") or {}).get("graff/worktree", "MISSING")+++def run(binary):+ if os.name == "nt":+ print("ACP workspace contract: skipped (worktrees need POSIX chdir)")+ return+ with tempfile.TemporaryDirectory(prefix="graff-acp-workspace-") as temporary:+ base = Path(temporary).resolve()+ home = base / "home"+ home.mkdir()+ launch, client = repo(base, "launch"), repo(base, "client")+ isolation_off = {"GRAFF_AUTO_ISOLATE": "0"}++ # The client's cwd wins over the launch folder; tools run there.+ model = ScriptedModel([{"tool": "shell", "arguments": {"action": "run", "command": "pwd"}}, {"text": "done"}])+ port = model.start(0)+ a = Acp(binary, launch, home, port, isolation_off)+ try:+ a.request("initialize", {"protocolVersion": 1})+ created = a.request("session/new", {"cwd": str(client), "mcpServers": []})["result"]+ assert "cwd" not in created, created+ assert worktree(created) is None, created+ turn = a.request("session/prompt", {"sessionId": created["sessionId"],+ "prompt": [{"type": "text", "text": "where am I"}]}, 35)+ assert turn["result"]["stopReason"] == "end_turn", turn+ assert any(str(client) in text for text in tool_text(model.requests[1])), tool_text(model.requests[1])+ finally:+ a.close()+ model.stop()++ # A relative cwd is invalid params, not a silent fallback.+ model = ScriptedModel([])+ port = model.start(0)+ a = Acp(binary, launch, home, port, isolation_off)+ try:+ a.request("initialize", {"protocolVersion": 1})+ rejected = a.request("session/new", {"cwd": "relative/dir", "mcpServers": []})+ assert rejected["error"]["code"] == -32602 and "absolute" in rejected["error"]["message"], rejected+ finally:+ a.close()+ model.stop()++ # `-w <name>`: naming the owning checkout keeps the tree, reported in _meta.+ tree = launch / ".graff" / "worktrees" / "harness-x"+ model = ScriptedModel([{"text": "remembered"}])+ port = model.start(0)+ a = Acp(binary, launch, home, port, isolation_off, ("-w", "harness-x"))+ try:+ a.request("initialize", {"protocolVersion": 1})+ created = a.request("session/new", {"cwd": str(launch), "mcpServers": []})["result"]+ info = worktree(created)+ assert isinstance(info, dict), created+ assert info["name"] == "harness-x" and info["branch"] == "worktree-harness-x", info+ assert Path(info["path"]).resolve() == tree.resolve() and Path(info["root"]).resolve() == launch, info+ assert info["generated"] is False and info["base"] == "main" and info["baseSha"], info+ sid = created["sessionId"]+ turn = a.request("session/prompt", {"sessionId": sid, "prompt": [{"type": "text", "text": "remember PLUM"}]}, 35)+ assert turn["result"]["stopReason"] == "end_turn", turn+ finally:+ a.close()+ model.stop()+ saved = tree / ".graff" / "sessions" / f"{sid}.session.json"+ assert saved.exists(), "a -w session saves inside its tree"+ assert Path(json.loads(saved.read_text())["workspace"]).resolve() == tree.resolve()++ # A relaunched `-w` process naming the repository root reopens it.+ model = ScriptedModel([])+ port = model.start(0)+ a = Acp(binary, launch, home, port, isolation_off, ("-w", "harness-x"))+ try:+ a.request("initialize", {"protocolVersion": 1})+ loaded = a.request("session/load", {"sessionId": sid, "cwd": str(launch), "mcpServers": []})+ assert "error" not in loaded, loaded+ assert worktree(loaded["result"])["name"] == "harness-x", loaded+ finally:+ a.close()+ model.stop()++ # A plain process in the main checkout re-enters the tree holding the save.+ model = ScriptedModel([{"text": "PLUM"}])+ port = model.start(0)+ a = Acp(binary, launch, home, port, isolation_off)+ try:+ a.request("initialize", {"protocolVersion": 1})+ loaded = a.request("session/load", {"sessionId": sid, "cwd": str(launch), "mcpServers": []})+ assert "error" not in loaded, loaded+ assert worktree(loaded["result"])["name"] == "harness-x", loaded+ turn = a.request("session/prompt", {"sessionId": sid, "prompt": [{"type": "text", "text": "which word?"}]}, 35)+ assert turn["result"]["stopReason"] == "end_turn", turn+ assert "remember PLUM" in str(model.requests[0]), "the reopened session kept its history"+ finally:+ a.close()+ model.stop()++ # Switching workspace mid-session notifies the client before the reply.+ created_tree = subprocess.run([str(binary), "worktree", "create", "other"], cwd=launch, capture_output=True, text=True)+ assert created_tree.returncode == 0, created_tree.stdout + created_tree.stderr+ model = ScriptedModel([])+ port = model.start(0)+ a = Acp(binary, launch, home, port, isolation_off)+ try:+ a.request("initialize", {"protocolVersion": 1})+ sid2 = a.request("session/new", {"cwd": str(launch), "mcpServers": []})["result"]["sessionId"]+ before = len(a.events)+ switched = a.request("session/prompt", {"sessionId": sid2, "prompt": [{"type": "text", "text": "/workspace use other"}]}, 35)+ assert switched["result"]["stopReason"] == "end_turn", switched+ updates = [e["params"]["update"] for e in a.events[before:]+ if e.get("method") == "session/update" and e["params"]["update"].get("sessionUpdate") == "session_info_update"]+ assert updates and updates[-1]["_meta"]["graff/worktree"]["name"] == "other", a.events[before:]+ finally:+ a.close()+ model.stop()+ print("ACP workspace contract: client cwd, relative cwd rejected, -w tree in _meta, load from root and from main checkout, switch notice: ok")+++if __name__ == "__main__":+ run(Path(sys.argv[1] if len(sys.argv) > 1 else REPO / "zig-out/bin/graff").resolve())diff --git a/scripts/test-workspace-lifecycle.py b/scripts/test-workspace-lifecycle.pyindex 1bf277ea..0f9fc0e5 100644--- a/scripts/test-workspace-lifecycle.py+++ b/scripts/test-workspace-lifecycle.py@@ -27,9 +27,10 @@ with tempfile.TemporaryDirectory(prefix="graff-workspace-lifecycle-") as temporadef git(*args, cwd=root):return subprocess.check_output(["git", "-C", str(cwd), *args], text=True, stderr=subprocess.STDOUT).strip()- def graff(*args):+ def graff(*args, code=0):+ # Exit status contract: 0 done, 1 refused or failed, 2 nothing done (kept).result = subprocess.run([binary, "worktree", *args], cwd=root, env=env, text=True, capture_output=True, timeout=30)- assert result.returncode == 0, result.stderr+ assert result.returncode == code, (result.returncode, result.stdout, result.stderr)return result.stdoutgit("init", "-q", "-b", "main")@@ -60,11 +61,12 @@ with tempfile.TemporaryDirectory(prefix="graff-workspace-lifecycle-") as temporagit("commit", "-qm", "task", cwd=tree)head = git("rev-parse", "HEAD", cwd=tree)proof.write_text(json.dumps({"state": "MERGED", "headRefOid": "old"}))- assert "kept" in graff("archive-merged", "task") and tree.exists()+ assert "kept" in graff("archive-merged", "task", code=2) and tree.exists()proof.write_text(json.dumps({"state": "MERGED", "headRefOid": head}))(tree / "untracked").write_text("keep")- assert "kept" in graff("archive-merged", "task") and tree.exists()- assert "confirm" in graff("remove", "task") and tree.exists()+ assert "kept" in graff("archive-merged", "task", code=2) and tree.exists()+ assert "confirm" in graff("remove", "task", code=1) and tree.exists()+ assert "no such task workspace" in graff("merge", "missing", code=1)(tree / "untracked").unlink()assert "archived" in graff("archive-merged", "task") and not tree.exists()assert not git("branch", "--list", "worktree-task")diff --git a/src/acp.zig b/src/acp.zigindex 973955b6..a395e197 100644--- a/src/acp.zig+++ b/src/acp.zig@@ -243,7 +243,7 @@ pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_.meter = liveMeter,.extra = liveModels,.mcp_servers = @import("acp_mcp_servers.zig").attach,- .cwd = if (std.fs.path.isAbsolute(main_mod.g_cwd_display)) main_mod.g_cwd_display else "",+ .workspace = .{ .gpa = gpa, .io = io },.draft_subagents_enabled = std.mem.eql(u8, environ_map.get("GRAFF_ACP_DRAFT_SUBAGENTS") orelse "", "1"),};@import("acp_session_load.zig").configure(&d, &live);diff --git a/src/acp_engine.zig b/src/acp_engine.zigindex d68c7309..9519df47 100644--- a/src/acp_engine.zig+++ b/src/acp_engine.zig@@ -7,6 +7,7 @@ const Io = std.Io;const Allocator = std.mem.Allocator;const proto = @import("acp_protocol.zig");+const acp_workspace = @import("acp_workspace.zig");const util = @import("util.zig");const acp_auth = @import("acp_auth.zig");@@ -73,8 +74,8 @@ pub const Dispatch = struct {set_config: ?SetConfigFn = null,mcp_servers: ?McpServersFn = null,error_message: ?*const fn (ctx: *anyopaque, err: anyerror) []const u8 = null,- /// Isolated checkout after session start (`g_cwd_display`). Empty omits the field.- cwd: []const u8 = "",+ /// Live CLI: adopt the client's cwd, report `_meta["graff/worktree"]` (acp_workspace.zig).+ workspace: ?acp_workspace.Env = null,/// ACP v1 draft subagent updates are opt-in at initialize.subagents: bool = false,/// Graff extension: detached children may outlive a prompt. The client@@ -174,6 +175,7 @@ fn promptTurn(d: *Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request)};if (d.bind_session) |bind| bind(d.ctx, sid);const config_before = configOptions(d, arena) catch |err| return turnError(d, w, req, err);+ const workspace_before = acp_workspace.snapshot(d.workspace, arena);const text = try flattenPrompt(arena, if (obj) |o| o.get("prompt") else null);if (d.slash) |slash| {const reply = slash(d.ctx, arena, text) catch |err| {@@ -183,6 +185,7 @@ fn promptTurn(d: *Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request)if (reply) |plain| {if (plain.len > 0) try writeSessionUpdate(w, sid, 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 emitMeter(d, w, sid);return respond(w, req, .{ .stopReason = "end_turn" });}@@ -194,6 +197,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 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";@@ -301,17 +305,19 @@ pub fn handleLine(d: *Dispatch, arena: Allocator, w: *Io.Writer, line: []const ureturn respondError(w, req, -32000, "This ACP process already owns a session");// The client's MCP servers join before the reply: its first prompt// must already see their tools. A bad entry never fails the session.+ if (d.workspace) |env| acp_workspace.adopt(env, arena, req.params) catch |err|+ return respondError(w, req, -32602, acp_workspace.errorText(err));if (d.mcp_servers) |attach| attach(d.ctx, arena, req.params) catch {};d.created += 1;d.session_id = d.durable_session_id orelse try std.fmt.allocPrint(arena, "acp-{x}-{d}", .{ d.seed, d.created });if (d.config != null) {const options = configOptions(d, arena) catch |err| return respondError(w, req, err_internal, @errorName(err));- if (d.cwd.len > 0)- try respond(w, req, .{ .sessionId = d.session_id.?, .cwd = d.cwd, .configOptions = options })+ if (d.workspace) |env|+ try respond(w, req, .{ .sessionId = d.session_id.?, .configOptions = options, ._meta = acp_workspace.meta(env, arena) })elsetry respond(w, req, .{ .sessionId = d.session_id.?, .configOptions = options });- } else if (d.cwd.len > 0)- try respond(w, req, .{ .sessionId = d.session_id.?, .cwd = d.cwd })+ } else if (d.workspace) |env|+ try respond(w, req, .{ .sessionId = d.session_id.?, ._meta = acp_workspace.meta(env, arena) })elsetry respond(w, req, .{ .sessionId = d.session_id.? });try proto.writeAvailableCommands(w, d.session_id.?, proto.slashCommands());@@ -420,15 +426,21 @@ test "background child extension negotiates independently of draft sessions" {try std.testing.expect(!dispatch.background_subagents);}-test "session/new reports an isolated checkout when Dispatch.cwd is set" {+test "session/new: embeds send no root cwd; a relative client cwd is rejected" {var state = std.heap.ArenaAllocator.init(std.testing.allocator);defer state.deinit();var buf: [32768]u8 = undefined;var w: Io.Writer = .fixed(&buf);- var d: Dispatch = .{ .turn = echoTurn, .ctx = undefined, .seed = 0x11, .cwd = "/repo/.graff/worktrees/session-1" };+ var d: Dispatch = .{ .turn = echoTurn, .ctx = undefined, .seed = 0x11 };try handleLine(&d, state.allocator(), &w, "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"session/new\"}");try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "\"sessionId\":\"acp-11-1\"") != null);- try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "\"cwd\":\"/repo/.graff/worktrees/session-1\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "\"cwd\"") == null);+ try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "graff/worktree") == null);+ w = .fixed(&buf);+ var live: Dispatch = .{ .turn = echoTurn, .ctx = undefined, .seed = 0x12, .workspace = .{ .gpa = std.testing.allocator, .io = std.testing.io } };+ try handleLine(&live, state.allocator(), &w, "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"session/new\",\"params\":{\"cwd\":\"relative/dir\"}}");+ try std.testing.expect(std.mem.indexOf(u8, w.buffered(), "Session cwd must be an absolute path") != null);+ try std.testing.expect(live.session_id == null);}test "in-process embed can still create a second session" {diff --git a/src/acp_session_load.zig b/src/acp_session_load.zigindex 8358f41b..a35b07c0 100644--- a/src/acp_session_load.zig+++ b/src/acp_session_load.zig@@ -11,6 +11,8 @@ const replay = @import("acp_replay.zig");const transcript = @import("session_transcript.zig");const LiveTurn = @import("acp_live_turn.zig").LiveTurn;const util = @import("util.zig");+const acp_workspace = @import("acp_workspace.zig");+const workspace_switch = @import("workspace_switch.zig");const invalid_params: i32 = -32602;@@ -51,19 +53,22 @@ pub fn load(ctx: *anyopaque, arena: Allocator, w: *Io.Writer, req: proto.Requestconst params = req.params orelse return reject(w, req, "Invalid session/load parameters");if (params != .object) return reject(w, req, "Invalid session/load parameters");const sid = util.strFieldObj(params.object, "sessionId") orelse return reject(w, req, "Invalid session ID");- const cwd = util.strFieldObj(params.object, "cwd") orelse return reject(w, req, "Invalid session workspace");+ 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");- if (!std.fs.path.isAbsolute(cwd))- return reject(w, req, "Session workspace does not match the selected workspace");- const canonical_cwd = Io.Dir.cwd().realPathFileAlloc(live.root.io, cwd, arena) catch cwd;- const canonical_active = Io.Dir.cwd().realPathFileAlloc(live.root.io, d.cwd, arena) catch d.cwd;- if (!session_index.sameWorkspace(canonical_cwd, canonical_active))- return reject(w, req, "Session workspace does not match the selected workspace");+ const env = d.workspace orelse return reject(w, req, "Session loading is unavailable");+ // 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- return reject(w, req, "Unknown session ID in the selected workspace");+ 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 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(8 * 1024 * 1024)) catchreturn reject(w, req, "Saved session could not be loaded");@@ -95,6 +100,6 @@ pub fn load(ctx: *anyopaque, arena: Allocator, w: *Io.Writer, req: proto.Requestd.durable_session_id = live.session_id;try replayHistory(arena, live.root, w, live.session_id);const options = engine.configOptions(d, arena) catch |err| return proto.writeError(w, req.id, engine.err_internal, @errorName(err));- try proto.writeResult(w, req.id, .{ .configOptions = options });+ try proto.writeResult(w, req.id, .{ .configOptions = options, ._meta = acp_workspace.meta(env, arena) });try proto.writeAvailableCommands(w, live.session_id, proto.slashCommands());}diff --git a/src/acp_workspace.zig b/src/acp_workspace.zignew file mode 100644index 00000000..01771c9f--- /dev/null+++ b/src/acp_workspace.zig@@ -0,0 +1,195 @@+//! ACP session workspace: adopt the client's `cwd` and report the Git+//! worktree the session runs in as `_meta["graff/worktree"]` (ADR 0202).+//!+//! ACP requires an absolute `cwd` on session/new and session/load and the+//! agent must use it regardless of where it was spawned. A process launched+//! with `-w <name>` or auto-isolated keeps its tree when the client names the+//! checkout that owns it; any other folder becomes the session's cwd.+//! Extensions ride `_meta` because ACP forbids custom top-level fields.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const Value = std.json.Value;++const main_mod = @import("main.zig");+const proto = @import("acp_protocol.zig");+const runner = @import("process_runner.zig");+const session_index = @import("session_index.zig");+const util = @import("util.zig");+const workspace_switch = @import("workspace_switch.zig");+const worktree_base = @import("worktree_base.zig");++/// Present on the live CLI dispatch; embeds leave it null and report nothing.+pub const Env = struct { gpa: Allocator, io: Io };++pub const Info = struct {+ /// The `-w` / `graff worktree` name: branch minus `worktree-`, else the folder name.+ name: []const u8,+ path: []const u8,+ branch: []const u8,+ /// Landing branch recorded when graff created the tree; null when unknown.+ base: ?[]const u8 = null,+ baseSha: ?[]const u8 = null,+ /// The main checkout that owns this linked worktree.+ root: []const u8,+ /// Auto-isolated `session-*` tree; these are reaped once their process is gone.+ generated: bool,+};++/// Explicit null means "main checkout"; clients clear their worktree state on it.+pub const Meta = struct { @"graff/worktree": ?Info };++pub const AdoptError = error{ RelativeCwd, MissingCwd, ChdirFailed } || Allocator.Error;++pub fn errorText(err: anyerror) []const u8 {+ return switch (err) {+ error.RelativeCwd => "Session cwd must be an absolute path",+ error.MissingCwd => "Session cwd does not exist or is not a directory",+ else => "Session cwd could not be entered",+ };+}++fn git(env: Env, arena: Allocator, argv: []const []const u8) ?[]const u8 {+ const r = runner.runCapped(env.gpa, env.io, argv, 16 * 1024, 4096, 15_000) catch return null;+ defer env.gpa.free(r.stdout);+ defer env.gpa.free(r.stderr);+ if (!runner.ranOk(r)) return null;+ return arena.dupe(u8, std.mem.trim(u8, r.stdout, " \t\r\n")) catch null;+}++/// Pure half of `info`: `git rev-parse --path-format=absolute --show-toplevel+/// --git-dir --git-common-dir` output plus the short branch.+pub fn fromRevParse(arena: Allocator, rev_parse: []const u8, branch: []const u8) ?Info {+ var it = std.mem.tokenizeAny(u8, rev_parse, "\r\n");+ const top = it.next() orelse return null;+ const git_dir = std.mem.trimEnd(u8, it.next() orelse return null, "/");+ const common = std.mem.trimEnd(u8, it.next() orelse return null, "/");+ // The main checkout's git dir IS the common dir; only linked trees differ.+ if (std.mem.eql(u8, git_dir, common)) return null;+ if (!std.mem.endsWith(u8, common, "/.git")) return null; // bare repos have no checkout root+ const name = if (std.mem.startsWith(u8, branch, "worktree-") and branch.len > "worktree-".len)+ branch["worktree-".len..]+ else+ std.fs.path.basename(top);+ return .{+ .name = arena.dupe(u8, name) catch return null,+ .path = arena.dupe(u8, top) catch return null,+ .branch = arena.dupe(u8, branch) catch return null,+ .root = arena.dupe(u8, common[0 .. common.len - "/.git".len]) catch return null,+ .generated = std.mem.startsWith(u8, branch, "worktree-session-"),+ };+}++/// The linked worktree the process runs in, or null in a main checkout or outside Git.+pub fn info(env: Env, arena: Allocator) ?Info {+ const rev = git(env, arena, &.{ "git", "rev-parse", "--path-format=absolute", "--show-toplevel", "--git-dir", "--git-common-dir" }) orelse return null;+ const branch = git(env, arena, &.{ "git", "symbolic-ref", "--short", "HEAD" }) orelse "";+ var out = fromRevParse(arena, rev, branch) orelse return null;+ const base = worktree_base.read(env.gpa, env.io, arena, out.root, branch);+ if (base.len > 0) {+ out.base = base;+ out.baseSha = git(env, arena, &.{ "git", "merge-base", "HEAD", base });+ }+ return out;+}++pub fn meta(env: Env, arena: Allocator) Meta {+ return .{ .@"graff/worktree" = info(env, arena) };+}++fn cwdParam(params: ?Value) ?[]const u8 {+ const p = params orelse return null;+ if (p != .object) return null;+ return util.strFieldObj(p.object, "cwd");+}++/// Make the client's `cwd` the session's working directory. Keeps the current+/// tree when the client names it or the checkout that owns it (`-w`, auto-isolate).+pub fn adopt(env: Env, arena: Allocator, params: ?Value) AdoptError!void {+ const want = cwdParam(params) orelse return; // pre-v1 clients omit it+ if (!std.fs.path.isAbsolute(want)) return error.RelativeCwd;+ var dir = Io.Dir.cwd().openDir(env.io, want, .{}) catch return error.MissingCwd;+ dir.close(env.io);+ const active = workspace_switch.currentAbs(env.io, arena);+ if (workspace_switch.samePath(env.io, want, active)) return;+ if (info(env, arena)) |tree| if (workspace_switch.samePath(env.io, want, tree.root)) return;+ _ = workspace_switch.enterPath(env.gpa, env.io, arena, want) catch |err|+ return if (err == error.OutOfMemory) error.OutOfMemory else error.ChdirFailed;+}++/// session/load from a main checkout: a save made inside one of its+/// `.graff/worktrees/<name>` trees. Enters that tree and returns true.+pub fn enterSavedTree(env: Env, arena: Allocator, session_id: []const u8) bool {+ if (info(env, arena) != null) return false; // already inside a linked tree+ const rel = session_index.sessionPath(arena, session_id) catch return false;+ var trees = Io.Dir.cwd().openDir(env.io, ".graff/worktrees", .{ .iterate = true }) catch return false;+ defer trees.close(env.io);+ var it = trees.iterate();+ while (it.next(env.io) catch return false) |entry| {+ if (entry.kind != .directory) continue;+ const candidate = std.fmt.allocPrint(arena, ".graff/worktrees/{s}/{s}", .{ entry.name, rel }) catch return false;+ const stat = Io.Dir.cwd().statFile(env.io, candidate, .{}) catch continue;+ if (stat.kind != .file) continue;+ // enterPath verifies the chdir by resolving its argument afterwards,+ // so it must be absolute.+ const tree = std.fs.path.join(arena, &.{ workspace_switch.currentAbs(env.io, arena), ".graff/worktrees", entry.name }) catch return false;+ _ = workspace_switch.enterPath(env.gpa, env.io, arena, tree) catch return false;+ return true;+ }+ 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 "";+}++/// `/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;+ try proto.writeNotification(w, "session/update", .{+ .sessionId = session_id,+ .update = .{ .sessionUpdate = "session_info_update", ._meta = meta(e, arena) },+ });+}++test "fromRevParse: a linked tree reports its name, branch, and owning checkout" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ const rev = "/repo/.graff/worktrees/harness-abc\n/repo/.git/worktrees/harness-abc\n/repo/.git\n";+ const got = fromRevParse(a, rev, "worktree-harness-abc").?;+ try std.testing.expectEqualStrings("harness-abc", got.name);+ try std.testing.expectEqualStrings("/repo/.graff/worktrees/harness-abc", got.path);+ try std.testing.expectEqualStrings("/repo", got.root);+ try std.testing.expect(!got.generated);+ try std.testing.expect(fromRevParse(a, rev, "worktree-session-42-deadbeef").?.generated);+ // A hand-made tree on another branch is named after its folder.+ try std.testing.expectEqualStrings("harness-abc", fromRevParse(a, rev, "feature/x").?.name);+}++test "fromRevParse: the main checkout and bare repos report no worktree" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ try std.testing.expect(fromRevParse(a, "/repo\n/repo/.git\n/repo/.git\n", "main") == null);+ try std.testing.expect(fromRevParse(a, "/srv/x\n/srv/x.git/worktrees/y\n/srv/x.git\n", "main") == null);+ try std.testing.expect(fromRevParse(a, "", "main") == null);+}++test "Meta serializes an explicit null for the main checkout" {+ var buf: [256]u8 = undefined;+ var w: Io.Writer = .fixed(&buf);+ var s: std.json.Stringify = .{ .writer = &w };+ try s.write(Meta{ .@"graff/worktree" = null });+ try std.testing.expectEqualStrings("{\"graff/worktree\":null}", w.buffered());+}++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/session_start.zig b/src/session_start.zigindex becb047d..30eef1a5 100644--- a/src/session_start.zig+++ b/src/session_start.zig@@ -166,9 +166,11 @@ pub fn setupWorktreeAndBanner(} });}var cwd_buf: [std.fs.max_path_bytes]u8 = undefined;- main_mod.g_cwd_display = if (flags.worktree_flag) |wt|- // After chdir into the worktree, realPath(AT_FDCWD) is unreliable; derive from the launch dir.- std.fmt.allocPrint(arena, "{s}/.graff/worktrees/{s}", .{ environ_map.get("PWD") orelse ".", wt }) catch try arena.dupe(u8, environ_map.get("PWD") orelse ".")+ main_mod.g_cwd_display = if (flags.worktree_flag != null)+ // task_workspace.enter already set the tree's resolved absolute path.+ // Not $PWD: hosts that spawn with a working directory (ACP clients)+ // leave it naming their own folder, so saves recorded the wrong tree.+ main_mod.g_cwd_displayelse if (isolated) |wt|try arena.dupe(u8, wt.path)else if (std.process.currentPath(io, &cwd_buf)) |n|diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex b692093c..795dfe1a 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -350,6 +350,7 @@ test {_ = @import("acp_config.zig");_ = @import("session_start_plugins_test.zig");_ = @import("acp_mcp_servers.zig");+ _ = @import("acp_workspace.zig");_ = @import("libgraff.zig");_ = @import("tui_peer.zig");_ = @import("acp_auth.zig");diff --git a/src/tui_acp.zig b/src/tui_acp.zigindex 90db387d..b0695262 100644--- a/src/tui_acp.zig+++ b/src/tui_acp.zig@@ -177,7 +177,6 @@ pub const Session = struct {.ctx = @ptrCast(self),.seed = seed,.bind_session = bindSession,- .cwd = if (std.fs.path.isAbsolute(main_mod.g_cwd_display)) main_mod.g_cwd_display else "",},};}diff --git a/src/workspace_switch.zig b/src/workspace_switch.zigindex 2d82c6b7..3a9331fa 100644--- a/src/workspace_switch.zig+++ b/src/workspace_switch.zig@@ -121,7 +121,7 @@ fn realpathOs(io: Io, path: []const u8, out: []u8) ?[]const u8 {return out[0..n];}-fn samePath(io: Io, a: []const u8, b: []const u8) bool {+pub fn samePath(io: Io, a: []const u8, b: []const u8) bool {const left = std.mem.trimEnd(u8, a, "/");const right = std.mem.trimEnd(u8, b, "/");if (std.mem.eql(u8, left, right)) return true;@@ -183,7 +183,7 @@ pub fn formatList(arena: Allocator, entries: []const Entry, current: []const u8,return buf.items;}-fn currentAbs(io: Io, arena: Allocator) []const u8 {+pub fn currentAbs(io: Io, arena: Allocator) []const u8 {// Process cwd via Io's processCurrentPath (linux getcwd syscall /// RtlGetCurrentDirectory_U) — not Io.Dir.cwd().realPath, which Threaded// Io can keep stale across posix.chdir, and not std.c.getcwd, whichdiff --git a/src/worktree_cmd.zig b/src/worktree_cmd.zigindex 30e3f114..938a5be2 100644--- a/src/worktree_cmd.zig+++ b/src/worktree_cmd.zig@@ -70,11 +70,27 @@ pub fn worktreeAutoCommit(gpa: Allocator, io: Io, msg: []const u8) void {/// worktree-<name> into the current branch as one clean commit, then removes the/// worktree and deletes its branch. Run from the main checkout.pub fn worktreeCommand(gpa: Allocator, io: Io, arena: Allocator, args: []const []const u8) !void {+ var captured: Io.Writer.Allocating = .init(arena);+ try runTo(gpa, io, arena, args, &captured.writer);+ const text = captured.written();var buf: [4096]u8 = undefined;var w = Io.File.stdout().writer(io, &buf);- const out = &w.interface;- defer out.flush() catch {};+ try w.interface.writeAll(text);+ try w.interface.flush();+ const code = exitCode(text);+ if (code != 0) std.process.exit(code);+}++/// Scripted callers (Harness, CI) branch on the status, not the prose:+/// 1 = refused or failed (`✗`, usage), 2 = nothing done (`kept`, `⚠`), else 0.+pub fn exitCode(text: []const u8) u8 {+ const first = std.mem.trimStart(u8, text, " \t\r\n");+ if (std.mem.startsWith(u8, first, "✗") or std.mem.startsWith(u8, first, "usage:")) return 1;+ if (std.mem.startsWith(u8, first, "kept ") or std.mem.startsWith(u8, first, "⚠")) return 2;+ return 0;+}+fn runTo(gpa: Allocator, io: Io, arena: Allocator, args: []const []const u8, out: *Io.Writer) !void {const action = if (args.len > 0) args[0] else "list";if (std.mem.eql(u8, action, "list") or std.mem.eql(u8, action, "ls")) {@@ -89,6 +105,10 @@ pub fn worktreeCommand(gpa: Allocator, io: Io, arena: Allocator, args: []const [const name = args[1];const wt_path = try std.fmt.allocPrint(arena, ".graff/worktrees/{s}", .{name});const wt_branch = try std.fmt.allocPrint(arena, "worktree-{s}", .{name});+ Io.Dir.cwd().access(io, wt_path, .{}) catch {+ try out.print("✗ no such task workspace {s} — `graff worktree list`\n", .{name});+ return;+ };const metadata = @import("worktree_base.zig");const base = metadata.read(gpa, io, arena, ".", wt_branch);@@ -354,3 +374,12 @@ test { // split-out module: unreferenced, its tests silently never run_ = worktree_prune;_ = @import("worktree_reap.zig");}++test "exitCode: refusals and usage fail, kept is a no-op, success is zero" {+ try std.testing.expectEqual(@as(u8, 1), exitCode("✗ no such task workspace x — `graff worktree list`\n"));+ try std.testing.expectEqual(@as(u8, 1), exitCode("usage: graff worktree merge <name>\n"));+ try std.testing.expectEqual(@as(u8, 2), exitCode("kept /r/.graff/worktrees/x — has uncommitted changes\n"));+ try std.testing.expectEqual(@as(u8, 2), exitCode("⚠ nothing to land from worktree-x (empty or already merged) — worktree left intact\n"));+ try std.testing.expectEqual(@as(u8, 0), exitCode("✓ landed worktree-x → current branch as one commit, removed the worktree\n"));+ try std.testing.expectEqual(@as(u8, 0), exitCode("identity: /r/.git (main checkout)\n"));+}