Skip to content

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

Python

Route ACP reviews through isolated guarded turns

justrachc09f00b498b4
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index b1afeed7..4fc687e3 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -121,6 +121,7 @@ jobs:
run: |
python3 scripts/test-review-mode.py zig-out/bin/graff
python3 scripts/test-review-deadline.py zig-out/bin/graff
+ python3 scripts/test-review-acp.py zig-out/bin/graff
- name: Automatic learning bootstrap and its idle-workspace guard
run: python3 scripts/test-learn-auto-init.py zig-out/bin/graff
diff --git a/docs/review-guardrails.md b/docs/review-guardrails.md
index 4041aeba..f1a09a89 100644
--- a/docs/review-guardrails.md
+++ b/docs/review-guardrails.md
@@ -1,6 +1,6 @@
# Review guardrails
-Use `/review <target>` in a supported interactive client or the JSON request
+Use `/review <target>` in ACP clients or the interactive REPL or the JSON request
`{"type":"review","text":"Review the current diff"}` for the dedicated read-only
review mode. Ordinary chat text is not a request to enter this mode automatically.
Review mode rejects mutation, workflow expansion and delegation. A later user
@@ -24,10 +24,11 @@ Run the offline production regressions locally:
zig build
python3 scripts/test-review-mode.py zig-out/bin/graff
python3 scripts/test-review-deadline.py zig-out/bin/graff
+python3 scripts/test-review-acp.py zig-out/bin/graff
python3 scripts/eval-tier2.py --only review-checkpoint-preserves-unfinished-scope
```
-The first two also run in CI. Set `GRAFF_REVIEW_EVIDENCE` to a private directory
+The three process regressions also run in CI. Set `GRAFF_REVIEW_EVIDENCE` to a private directory
when running the deadline test to retain its protocol events and harness traces.
These are scripted-model regressions of the actual harness, not a claim about
an unscripted model's review quality.
diff --git a/scripts/test-review-acp.py b/scripts/test-review-acp.py
new file mode 100644
index 00000000..23c142df
--- /dev/null
+++ b/scripts/test-review-acp.py
@@ -0,0 +1,196 @@
+#!/usr/bin/env python3
+"""Exercise explicit review routing through the actual ACP process."""
+
+import importlib.util, json, os, pathlib, queue, shutil, signal, subprocess, sys, tempfile, threading, time
+
+root = pathlib.Path(__file__).resolve().parents[1]
+binary = (
+ pathlib.Path(sys.argv[1]).resolve()
+ if len(sys.argv) > 1
+ else root / "zig-out/bin/graff"
+)
+out = (
+ pathlib.Path(os.environ["GRAFF_REVIEW_EVIDENCE"])
+ if os.environ.get("GRAFF_REVIEW_EVIDENCE")
+ else None
+)
+if out:
+ out.mkdir(parents=True, exist_ok=True)
+sys.path.insert(0, str(root / "scripts"))
+sys.argv = [str(root / "scripts/test-review-mode.py"), str(binary)]
+spec = importlib.util.spec_from_file_location(
+ "review_fixture", root / "scripts/test-review-mode.py"
+)
+f = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(f)
+
+
+release_stall = threading.Event()
+
+
+def reply(r):
+ if r.ordinal == 1:
+ return f.message("Parent context retained.", 1)
+ if r.ordinal == 2:
+ return f.tool(
+ "edit_file",
+ {"path": "target.txt", "old_string": "original", "new_string": "changed"},
+ 1,
+ )
+ if r.ordinal == 3:
+ return f.message("Review result.", r.ordinal)
+ if r.ordinal == 4:
+ return f.tool(
+ "edit_file",
+ {"path": "target.txt", "old_string": "original", "new_string": "changed"},
+ 4,
+ )
+ if r.ordinal == 6:
+ release_stall.wait(8)
+ return f.message("Late review result must not complete the turn.", r.ordinal)
+ if r.ordinal == 7:
+ time.sleep(1.2)
+ return f.message("Normal follow-up complete.", r.ordinal)
+
+
+with tempfile.TemporaryDirectory(prefix="graff-review-acp-probe-") as tmp:
+ pathlib.Path(tmp, "target.txt").write_text("original")
+ mock = f.CodexMock(events_for_request=reply)
+ port = mock.start()
+ proc = subprocess.Popen(
+ [
+ str(binary),
+ "acp",
+ "--model",
+ "codex",
+ "--old",
+ "--yolo",
+ "--max-model-calls",
+ "8",
+ ],
+ cwd=tmp,
+ env={**f.environment(tmp, port), "GRAFF_REVIEW_MAX_SECONDS": "1"},
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL,
+ text=True,
+ start_new_session=True,
+ )
+ q = queue.Queue()
+ events = []
+ counter = 0
+
+ def read():
+ for l in proc.stdout:
+ try:
+ q.put(json.loads(l))
+ except ValueError:
+ pass
+ q.put(None)
+
+ threading.Thread(target=read, daemon=True).start()
+
+ def call(method, params):
+ global counter
+ counter += 1
+ proc.stdin.write(
+ json.dumps(dict(jsonrpc="2.0", id=counter, method=method, params=params))
+ + "\n"
+ )
+ proc.stdin.flush()
+ end = time.monotonic() + 20
+ while True:
+ v = q.get(timeout=max(0.01, end - time.monotonic()))
+ assert v is not None, "ACP stopped"
+ events.append(v)
+ if v.get("id") == counter:
+ return v
+
+ try:
+ call("initialize", {"protocolVersion": 1})
+ res = call("session/new", {})
+ sid = res["result"]["sessionId"]
+
+ def prompt(text):
+ return call(
+ "session/prompt",
+ {"sessionId": sid, "prompt": [{"type": "text", "text": text}]},
+ )
+
+ assert (
+ prompt("Remember parent-only-context")["result"]["stopReason"] == "end_turn"
+ )
+ response = call(
+ "session/prompt",
+ {
+ "sessionId": sid,
+ "prompt": [{"type": "text", "text": "/review target.txt"}],
+ },
+ )
+ assert response["result"]["stopReason"] == "end_turn", response
+ assert pathlib.Path(tmp, "target.txt").read_text() == "original", (
+ "Review changed the file"
+ )
+ requests = [r.body for r in mock.recorded_requests()]
+ assert len(requests) == 3, len(requests)
+ assert "parent-only-context" not in json.dumps(requests[1]), (
+ "Review inherited parent history"
+ )
+ assert "review mode is read-only" in json.dumps(requests[2]), (
+ "Mutation was not rejected"
+ )
+ assert prompt("Now implement the change")["result"]["stopReason"] == "end_turn"
+ assert pathlib.Path(tmp, "target.txt").read_text() == "changed", (
+ "Review restrictions leaked into follow-up"
+ )
+ requests = [r.body for r in mock.recorded_requests()]
+ assert len(requests) == 5, len(requests)
+ followup = json.dumps(requests[3])
+ assert "parent-only-context" in followup, "Parent history lost"
+ assert "Review result." in followup, "Review report lost"
+ assert "review mode is read-only" not in followup, (
+ "Review tool internals leaked into parent"
+ )
+ before_timeout = len(events)
+ started = time.monotonic()
+ expired = prompt("/review inspect target.txt again")
+ assert expired["result"]["stopReason"] == "cancelled", expired
+ assert time.monotonic() - started < 4, (
+ "Deadline failed to interrupt the request"
+ )
+ assert "wall-time limit reached; findings are incomplete" in json.dumps(
+ events[before_timeout:]
+ )
+ release_stall.set()
+ assert (
+ prompt("Remember the parent and summarize the incomplete review")["result"][
+ "stopReason"
+ ]
+ == "end_turn"
+ )
+ requests = [r.body for r in mock.recorded_requests()]
+ assert len(requests) == 7, len(requests)
+ assert "parent-only-context" in json.dumps(requests[6])
+ assert "findings are incomplete" in json.dumps(requests[6])
+ result = dict(
+ response=response,
+ model_calls=len(requests),
+ file=pathlib.Path(tmp, "target.txt").read_text(),
+ events=events,
+ )
+ if out:
+ (out / "result.json").write_text(json.dumps(result, indent=2))
+ (out / "requests.json").write_text(json.dumps(requests, indent=2))
+ for name in ("traces", "trajectories", "sessions"):
+ source = pathlib.Path(tmp, ".graff", name)
+ if source.exists():
+ shutil.copytree(source, out / name, dirs_exist_ok=True)
+ print(
+ "PASS: ACP review rejects edits, isolates parent context, retains report, reports deadlines and preserves later turns"
+ )
+
+ finally:
+ release_stall.set()
+ os.killpg(proc.pid, signal.SIGTERM)
+ proc.wait(timeout=5)
+ mock.stop()
diff --git a/src/acp.zig b/src/acp.zig
index d5bce15b..13ff1109 100644
--- a/src/acp.zig
+++ b/src/acp.zig
@@ -71,6 +71,7 @@ fn liveCancelled() bool {
/// and stays an ordinary prompt. Pickers here find no TTY and fall back to
/// printing their list, so nothing waits on a keypress that cannot come.
fn liveSlash(ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror!?[]const u8 {
+ if (@import("review.zig").promptFromLine(text) != null) return null;
const live: *LiveTurn = @ptrCast(@alignCast(ctx));
var aw: Io.Writer.Allocating = .init(arena);
// /never is the playbook's own, and handleCommand does not know it.
@@ -168,66 +169,7 @@ pub fn handleLine(d: *Dispatch, arena: Allocator, w: *Io.Writer, line: []const u
return engine.handleLine(d, arena, w, line);
}
-const LiveTurn = struct {
- root: *agent_mod.Agent,
- keys: *provider_mod.Keys,
- out: *Io.Writer,
- session_id: []const u8 = "",
- saw_text: bool = false,
- inbox: ?*@import("acp_inbox.zig").Inbox = null,
-
- fn errorMessage(ctx: *anyopaque, err: anyerror) []const u8 {
- const self: *LiveTurn = @ptrCast(@alignCast(ctx));
- return if (err == error.ApiError) self.root.last_api_error orelse "Provider request failed" else @errorName(err);
- }
-
- fn run(ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror![]const u8 {
- const self: *LiveTurn = @ptrCast(@alignCast(ctx));
- agent_mod.Agent.prepareRootTurn(); // #753: a prior stream cancel must not steal the continuation
- if (self.inbox) |inbox| inbox.begin();
- defer if (self.inbox) |inbox| inbox.end();
- switch (try @import("turn_dedup.zig").enqueue(self.root, arena, self.out, text)) {
- .started => {},
- .skipped => return "",
- .stuck => return @import("turn_dedup.zig").stuck_text,
- }
- if (telemetry.g_telem) |t| t.beginTurn(@intCast(@min(text.len, std.math.maxInt(u32))), self.root.provider.model);
- self.saw_text = false;
- var sink: stream.EventSink = undefined;
- sink.init(self.root.gpa, self.out, &self.session_id, &self.saw_text);
- defer sink.deinit();
- self.root.out = &sink.writer;
- main_mod.g_out = &sink.writer;
- defer {
- sink.writer.flush() catch {};
- self.root.out = null;
- main_mod.g_out = null;
- }
- const final = providers.runTurnWithFallback(self.root, self.keys, arena, null) catch |err| {
- // #753: an API interruption is a failed turn, not a dead ACP
- // process. Save so the next prompt (and a respawn --resume) still
- // sees the tool results and the background-agent ledger.
- session.saveSession(self.root, self.root.arena, self.root.session_name) catch {};
- return err;
- };
- // The REPL checkpoints after every turn (mainloop); an ACP host's
- // conversation deserves the same durability. Without this a text-only
- // turn reached .graff/sessions only at stdin EOF, and a tab the host
- // killed never did. The root arena, not this turn's: the queued write
- // outlives the turn.
- session.saveSessionAsync(self.root, self.root.arena, self.root.session_name) catch {};
- // saw_text is "the LAST streamed event was answer text" (tool events
- // reset it in the sink): a turn that ended mid-text already delivered
- // the answer; one that ended on tools (attempt_completion flows) has
- // its answer only in `final`, so that must still go on the wire.
- if (self.saw_text) return "";
- // A streamed preamble and the final answer are separate paragraphs;
- // without the break the client renders "…answering.The three files…".
- if (final.len > 0 and sink.streamed_any)
- return try std.fmt.allocPrint(arena, "\n\n{s}", .{final});
- return final;
- }
-};
+const LiveTurn = @import("acp_live_turn.zig").LiveTurn;
pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_mod.Agent, keys: *provider_mod.Keys, client: *std.http.Client, in: *Io.Reader, out: *Io.Writer, arena: Allocator, flags: args.Flags) !bool {
if (!(flags.positionals.items.len > 0 and std.mem.eql(u8, flags.positionals.items[0], "acp"))) return false;
diff --git a/src/acp_live_turn.zig b/src/acp_live_turn.zig
new file mode 100644
index 00000000..ca32c0e8
--- /dev/null
+++ b/src/acp_live_turn.zig
@@ -0,0 +1,108 @@
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const agent_mod = @import("agent.zig");
+const provider_mod = @import("provider.zig");
+const main_mod = @import("main.zig");
+const providers = @import("providers.zig");
+const telemetry = @import("telemetry.zig");
+const session = @import("session.zig");
+const stream = @import("acp_stream.zig");
+const review = @import("review.zig");
+const messages = @import("messages.zig");
+const cancel_source = @import("cancel_source.zig");
+const proto = @import("acp_protocol.zig");
+
+pub const LiveTurn = struct {
+ root: *agent_mod.Agent,
+ keys: *provider_mod.Keys,
+ out: *Io.Writer,
+ session_id: []const u8 = "",
+ saw_text: bool = false,
+ inbox: ?*@import("acp_inbox.zig").Inbox = null,
+
+ pub fn errorMessage(ctx: *anyopaque, err: anyerror) []const u8 {
+ const self: *LiveTurn = @ptrCast(@alignCast(ctx));
+ return if (err == error.ApiError) self.root.last_api_error orelse "Provider request failed" else @errorName(err);
+ }
+
+ pub fn run(ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror![]const u8 {
+ const self: *LiveTurn = @ptrCast(@alignCast(ctx));
+ agent_mod.Agent.prepareRootTurn(); // #753: a prior stream cancel must not steal the continuation
+ if (self.inbox) |inbox| inbox.begin();
+ defer if (self.inbox) |inbox| inbox.end();
+ const review_prompt = review.promptFromLine(text);
+ const parent_override = self.root.sys_override;
+ const parent_review_mode = self.root.review_mode;
+ self.root.review_mode = review_prompt != null;
+ defer {
+ self.root.review_mode = parent_review_mode;
+ self.root.sys_override = parent_override;
+ }
+ if (review_prompt != null)
+ self.root.sys_override = try review.systemPrompt(arena, self.root.sys_normal);
+ var context = review.Context.begin(arena, self.root, review_prompt != null);
+ defer if (context.restore(self.root)) self.root.rebaseContextMeter();
+ switch (try @import("turn_dedup.zig").enqueue(self.root, arena, self.out, review_prompt orelse text)) {
+ .started => {},
+ .skipped => return "",
+ .stuck => return @import("turn_dedup.zig").stuck_text,
+ }
+ if (telemetry.g_telem) |t| t.beginTurn(@intCast(@min(text.len, std.math.maxInt(u32))), self.root.provider.model);
+ self.saw_text = false;
+ var sink: stream.EventSink = undefined;
+ sink.init(self.root.gpa, self.out, &self.session_id, &self.saw_text);
+ defer sink.deinit();
+ self.root.out = &sink.writer;
+ main_mod.g_out = &sink.writer;
+ defer {
+ sink.writer.flush() catch {};
+ self.root.out = null;
+ main_mod.g_out = null;
+ }
+ const result = providers.runTurnWithFallback(self.root, self.keys, arena, null);
+ const isolated = context.restore(self.root);
+ if (isolated) {
+ self.root.review_mode = parent_review_mode;
+ self.root.sys_override = parent_override;
+ try self.root.messages.append(try messages.textMessage(arena, "user", text));
+ self.root.rebaseContextMeter();
+ }
+ const final = result catch |err| {
+ if (isolated) {
+ const marker = if (err == error.Interrupted or err == error.Canceled)
+ cancel_source.marker(cancel_source.take(self.root.tracer))
+ else
+ try std.fmt.allocPrint(arena, "[review ended early: {s}; findings are incomplete]", .{@errorName(err)});
+ const partial = std.mem.trim(u8, self.root.partial_text.items, " \t\r\n");
+ const report = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ partial, marker });
+ try self.root.messages.append(try messages.textMessage(arena, "assistant", report));
+ try sink.writer.flush();
+ try proto.writeSessionUpdate(self.out, self.session_id, marker);
+ }
+ // #753: an API interruption is a failed turn, not a dead ACP
+ // process. Save so the next prompt (and a respawn --resume) still
+ // sees the tool results and the background-agent ledger.
+ session.saveSession(self.root, self.root.arena, self.root.session_name) catch {};
+ return err;
+ };
+ // The REPL checkpoints after every turn (mainloop); an ACP host's
+ // conversation deserves the same durability. Without this a text-only
+ // turn reached .graff/sessions only at stdin EOF, and a tab the host
+ // killed never did. The root arena, not this turn's: the queued write
+ // outlives the turn.
+ if (isolated)
+ try self.root.messages.append(try messages.textMessage(arena, "assistant", final));
+ session.saveSessionAsync(self.root, self.root.arena, self.root.session_name) catch {};
+ // saw_text is "the LAST streamed event was answer text" (tool events
+ // reset it in the sink): a turn that ended mid-text already delivered
+ // the answer; one that ended on tools (attempt_completion flows) has
+ // its answer only in `final`, so that must still go on the wire.
+ if (self.saw_text) return "";
+ // A streamed preamble and the final answer are separate paragraphs;
+ // without the break the client renders "…answering.The three files…".
+ if (final.len > 0 and sink.streamed_any)
+ return try std.fmt.allocPrint(arena, "\n\n{s}", .{final});
+ return final;
+ }
+};