Skip to content

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

Python

acp: report the save a /resume moves the session onto

justrach132afb3fa8cf
diff --git a/docs/acp-compatibility.md b/docs/acp-compatibility.md
index c4aee2b5..e1ddcf2d 100644
--- a/docs/acp-compatibility.md
+++ b/docs/acp-compatibility.md
@@ -37,6 +37,7 @@ optional feature or draft extension is enabled.
| Context meter | Standard `usage_update` (stable in ACP v1): `used` tokens in context and the model's `size`, plus `cost` `{amount, currency: "USD"}` only when every call so far was priced. Sent after tool steps whenever the count moved (so it drops visibly after compaction) and at the end of each prompt turn. | `src/acp_context_meter.zig`, `src/acp_engine_test.zig` |
| Usage | Connection usage is a namespaced extension. It preserves unknown totals and is not a standard ACP v1 billing contract. | `scripts/test-acp-usage.py`, ADR 0182 |
| Subagents | Default: a top-level subagent streams its work onto the parent tool call as standard `tool_call_update` content (a rolling log of its tool calls, failures and message tail), with no `status` change and `_meta["graff/subagent"]` = `{sessionId, name, state}`; `GRAFF_ACP_SUBAGENT_PROGRESS=0` disables it. Opt-in preview: the proposed child-session stream (client `subagents` capability plus `GRAFF_ACP_DRAFT_SUBAGENTS=1`) replaces it for foreground children. Detached workers also keep `graff/agents` inspection. Child history is not yet replayed on `session/load`. | `scripts/test-acp-subagent-update.py`, ADR 0194, ADR 0205 |
+| Session-changing commands | `/resume SOURCE` (and `--branch DEST`) moves the live session onto another save while the connection keeps its session ID. The `session/prompt` result then carries `_meta["graff/durableSessionId"]`: the save the session now writes. A host that restores sessions should keep that ID and pass it to `session/load` after a restart; the old ID may name no save, or a save from before the switch. v1 only. | `scripts/test-acp-resume-identity.py`, `src/acp_engine.zig` (#1529) |
| Resent prompts | `session/prompt` may carry a client message id as `messageId` or `_meta["graff/messageId"]`. Resending a prompt this process already finished for that session answers with the first turn's `stopReason` instead of starting another turn; a failed turn is not recorded, so its resend runs. The last 32 ids are kept in memory. `graff serve` and remote control take the same id as `message_id` on the request body and replay the first request's events. | `src/resend.zig`, `scripts/test-serve-resume.py` |
| Saved views | A completed `tool_call_update` whose result saved a `render_html` page or an MCP Apps result also carries `_meta["graff/view"]` = `{kind: "html" \| "mcp_app", id, path}`. `id` is the 32-hex snapshot name under `.graff/views` or `.graff/mcp-apps`; resolve by id and treat `path` as informational. The `[Rendered view](…)` / `[MCP app](…)` text link stays in the content. Replayed on `session/load`. | `scripts/test-acp-view-meta.py`, `src/acp_view_meta.zig` |
| Compaction | When the root agent compacts (automatically, `/compact`, or server-side), graff sends `compaction_update` `{compactionId, status}`: `in_progress`, then one of `completed` (a local summary rides `summary` as a text block), `failed` (with `error`) or `cancelled`. A provider that compacted in-stream gets one `completed`. ACP v1 marks this unstable, so it is sent only to clients that advertise `clientCapabilities.session.compaction`; ACP v2 clients always get it. | `src/acp_compaction.zig`, `scripts/test-acp-compaction.py` |
diff --git a/scripts/eval-tier1.sh b/scripts/eval-tier1.sh
index 4bc44e0a..0f6fd880 100755
--- a/scripts/eval-tier1.sh
+++ b/scripts/eval-tier1.sh
@@ -187,6 +187,7 @@ if wanted shell; then
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-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/graff
); then :; else
diff --git a/scripts/test-acp-resume-identity.py b/scripts/test-acp-resume-identity.py
new file mode 100755
index 00000000..6085d33b
--- /dev/null
+++ b/scripts/test-acp-resume-identity.py
@@ -0,0 +1,125 @@
+#!/usr/bin/env python3
+"""Offline ACP lifecycle for #1529: `/resume` moves a live session onto another
+save. The prompt result names that save (`_meta["graff/durableSessionId"]`), a
+restarted worker loads it, and the continued history comes back. Covers a plain
+`/resume SOURCE` and an explicit `--branch DEST`."""
+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_session_load_fixture", REPO / "scripts/test-acp-session-load.py")
+_fixture = importlib.util.module_from_spec(_spec)
+_spec.loader.exec_module(_fixture)
+Acp = _fixture.Acp
+
+
+def prompt(client, sid, text):
+ reply = client.request("session/prompt", {"sessionId": sid, "prompt": [{"type": "text", "text": text}]})
+ assert "result" in reply, reply
+ return reply["result"]
+
+
+def saved_text(cwd, name):
+ path = cwd / ".graff/sessions" / f"{name}.session.json"
+ deadline = time.monotonic() + 5
+ while not path.exists() and time.monotonic() < deadline:
+ time.sleep(.05)
+ return path.read_text()
+
+
+def replayed(client, start):
+ out = []
+ for event in client.events[start:]:
+ update = event.get("params", {}).get("update", {})
+ content = update.get("content", {})
+ if isinstance(content, dict):
+ out.append(content.get("text", ""))
+ return "".join(out)
+
+
+def run(binary):
+ with tempfile.TemporaryDirectory(prefix="graff-acp-resume-identity-") as temporary:
+ base = Path(temporary).resolve()
+ cwd, home = base / "work", base / "home"
+ cwd.mkdir()
+ home.mkdir()
+ model = ScriptedModel([
+ {"text": "Baseline answer."},
+ {"text": "Continued answer."},
+ {"text": "Branch answer."},
+ {"text": "After restart."},
+ ])
+ port = model.start(0)
+ new = {"cwd": str(cwd), "mcpServers": []}
+
+ # 1. A saved conversation to resume later.
+ first = Acp(binary, cwd, home, port)
+ try:
+ first.request("initialize", {"protocolVersion": 1})
+ baseline = first.request("session/new", new)["result"]["sessionId"]
+ result = prompt(first, baseline, "Baseline question.")
+ assert "_meta" not in result or "graff/durableSessionId" not in result["_meta"], result
+ finally:
+ first.close()
+ assert "Baseline answer." in saved_text(cwd, baseline)
+
+ # 2. A fresh session resumes it: the result names the save it now writes.
+ second = Acp(binary, cwd, home, port)
+ try:
+ second.request("initialize", {"protocolVersion": 1})
+ transport = second.request("session/new", new)["result"]["sessionId"]
+ assert transport != baseline
+ moved = prompt(second, transport, f"/resume {baseline}")
+ assert moved.get("_meta", {}).get("graff/durableSessionId") == baseline, moved
+ # The transport ID keeps routing this connection.
+ continued = prompt(second, transport, "Continued question.")
+ assert continued.get("_meta", {}).get("graff/durableSessionId") == baseline, continued
+ finally:
+ second.close()
+ text = saved_text(cwd, baseline)
+ assert "Continued question." in text and "Continued answer." in text
+
+ # 3. A restarted worker loads the reported save and has the continued history.
+ third = Acp(binary, cwd, home, port)
+ try:
+ third.request("initialize", {"protocolVersion": 1})
+ third.request("session/new", new)
+ start = len(third.events)
+ loaded = third.request("session/load", {"sessionId": baseline, **new})
+ assert "result" in loaded, loaded
+ history = replayed(third, start)
+ assert "Baseline question." in history and "Continued answer." in history, history
+
+ # 4. An explicit branch destination is reported the same way.
+ branched = prompt(third, baseline, f"/resume {baseline} --branch fork-1529")
+ assert branched.get("_meta", {}).get("graff/durableSessionId") == "fork-1529", branched
+ prompt(third, baseline, "Branch question.")
+ finally:
+ third.close()
+ assert "Branch question." in saved_text(cwd, "fork-1529")
+ assert "Branch question." not in saved_text(cwd, baseline), "a branch must not write its source"
+
+ fourth = Acp(binary, cwd, home, port)
+ try:
+ fourth.request("initialize", {"protocolVersion": 1})
+ fourth.request("session/new", new)
+ loaded = fourth.request("session/load", {"sessionId": "fork-1529", **new})
+ assert "result" in loaded, loaded
+ after = prompt(fourth, "fork-1529", "One more.")
+ assert "graff/durableSessionId" not in after.get("_meta", {}), "loaded save is the transport ID"
+ finally:
+ fourth.close()
+ body = json.dumps(model.requests[-1])
+ assert "Branch question." in body and "Continued answer." in body, "branch keeps the resumed history"
+ print("ok: /resume reports its save; a restart restores the continued history (plain and --branch)")
+
+
+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_engine.zig b/src/acp_engine.zig
index 29cebe27..3e30e684 100644
--- a/src/acp_engine.zig
+++ b/src/acp_engine.zig
@@ -75,6 +75,11 @@ pub const Dispatch = struct {
load_session: ?LoadSessionFn = null,
/// Live CLI saves under this stable name; embeds retain generated IDs.
durable_session_id: ?[]const u8 = null,
+ /// #1529: the save the live session writes now. A slash command such as
+ /// `/resume` can move it off the transport ID; the prompt result then
+ /// names it (`_meta["graff/durableSessionId"]`) so the host loads that
+ /// save after a restart instead of the one it was handed at session/new.
+ durable_name: ?*const fn (ctx: *anyopaque) ?[]const u8 = null,
meter: ?MeterFn = null,
extra: ?ExtraFn = null,
config: ?ConfigFn = null,
@@ -211,7 +216,7 @@ fn promptTurn(d: *Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request)
try acp_workspace.emitChange(d.workspace, arena, w, sid, workspace_before);
try emitMeter(d, w, sid);
if (resend_key) |key| resent.finish(key, 0, "end_turn");
- return respond(w, req, .{ .stopReason = "end_turn" });
+ return respondStop(d, w, req, sid, "end_turn");
}
}
if (d.after_user) |after| after(d.ctx, arena, text, if (obj) |o| o.get("prompt") else null);
@@ -226,7 +231,26 @@ fn promptTurn(d: *Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request)
const extra = if (extra_cancelled) |f| f() else false;
const stop: []const u8 = if (cancel_flag.load(.acquire) or extra) "cancelled" else "end_turn";
if (resend_key) |key| resent.finish(key, 0, stop);
- try respond(w, req, .{ .stopReason = stop });
+ try respondStop(d, w, req, sid, stop);
+}
+
+/// The save the session writes, when it is no longer the transport ID `sid`.
+pub fn movedDurableName(d: *const Dispatch, sid: []const u8) ?[]const u8 {
+ const current = d.durable_name orelse return null;
+ const name = current(d.ctx) orelse return null;
+ if (std.mem.eql(u8, name, sid)) return null;
+ return name;
+}
+
+/// A prompt's result. When a command moved the session onto another save, the
+/// result names it and the dispatch's durable identity follows (#1529); the
+/// transport ID keeps routing this connection.
+fn respondStop(d: *Dispatch, w: *Io.Writer, req: proto.Request, sid: []const u8, stop: []const u8) !void {
+ if (movedDurableName(d, sid)) |name| {
+ d.durable_session_id = name;
+ return respond(w, req, .{ .stopReason = stop, ._meta = .{ .@"graff/durableSessionId" = name } });
+ }
+ return respond(w, req, .{ .stopReason = stop });
}
pub fn emitMeter(d: *Dispatch, w: *Io.Writer, sid: []const u8) !void {
diff --git a/src/acp_session_load.zig b/src/acp_session_load.zig
index 991f51c3..ef2f214b 100644
--- a/src/acp_session_load.zig
+++ b/src/acp_session_load.zig
@@ -22,9 +22,17 @@ pub fn configure(d: *engine.Dispatch, live: *LiveTurn) void {
d.config = @import("acp_config.zig").option;
d.set_config = @import("acp_config.zig").set;
d.durable_session_id = if (session.validSessionName(live.root.session_name)) live.root.session_name else null;
+ d.durable_name = durableName;
live.dispatch = d;
}
+/// The save turns are written to (`acp_live_turn` saves under `session_name`).
+fn durableName(ctx: *anyopaque) ?[]const u8 {
+ const live: *LiveTurn = @ptrCast(@alignCast(ctx));
+ const name = live.root.session_name;
+ return if (session.validSessionName(name)) name else null;
+}
+
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);
}