graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Respect explicit ACP command intent without consuming literal slash prose
yxlyx78af54ed4fac
diff --git a/docs/adr/0313-acp-explicit-command-intent.md b/docs/adr/0313-acp-explicit-command-intent.mdnew file mode 100644index 00000000..a21e08c6--- /dev/null+++ b/docs/adr/0313-acp-explicit-command-intent.md@@ -0,0 +1,19 @@+# 0313 — ACP command selection is separate from prompt text++## Context++A Harness prompt beginning with ordinary slash prose was rejected as an unknown command before the agent saw it (#1814). A subsequent retry could refer to a session with no saved model history. Known slash names used as prose can also accidentally change goal, review or issue state.++## Decision++Harness preserves canonical completion selections until the ACP adapter builds `session/prompt`. It sends readable prompt content and a boolean `_meta["harness/command"]`: true only for a leading, explicitly accepted native command or native skill command; false for ordinary text, including known slash names. This marker gates both local slash dispatch and live-turn command expansion (goal/loop, review, issue, side requests and playbook overrides), in ACP v1 and v2.++Clients that omit the marker retain existing ACP command syntax. The terminal REPL is unchanged. Literal text is not escaped, prefixed with invisible characters, or rewritten to evade parsing.++## Consequences++Both Harness and graff must carry this intent end to end. User-visible command labels alone cannot recover completion acceptance after it has been discarded. A missing native save must not be treated as a successfully restored conversation; Harness stops failed Graff restores instead of silently sending the retry into an empty session.++## Evidence++`acp_engine_test` covers explicit selection and legacy behavior in both protocol versions. `scripts/test-acp-slash-typo.py` checks literal prompt delivery, command expansion, selected commands, and a worker restart followed by a retry retaining the original synthetic task.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 61e3e229..ea5818ed 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -337,6 +337,7 @@ record only when you need the evidence or the edge cases.| [0310](0310-auth-failures-name-the-rejected-credential.md) | A terminal auth rejection names the seat that failed: sign-in text keeps "sign in again"; key and promoted-key texts say "API key was rejected" and never the signed-out phrases. Key seats carry `{"kind":"api_key_rejected","provider":…}` (v1 `-32603` data, v2 `_meta["graff/recovery"]`); `reauth_required` is unchanged. || [0311](0311-tool-refresh-and-addressed-wakes.md) | Claude Agent refreshes a changed tool list with MCP `tools/list_changed` (served before anything else; fresh session if not re-read in 15 s) instead of removing and re-adding its server, which failed held calls. `attempt_completion` settles a task like a final answer: room mail waits for the next human prompt, addressed mail can still start a turn; `yield_turn` stays strict. A peer wake preloads `peer_message`. || [0312](0312-openai-12h-prompt-cache-is-opt-in.md) | OpenAI Responses GPT-5.6+ can put a 12h explicit breakpoint on the stable prefix (`GRAFF_OPENAI_CACHE_TTL=12h` or `openai_cache_ttl`); the default stays 30m (ADR 0009 bytes) until a live probe confirms OpenAI accepts the field and keeps the entry. Usage parses cache writes by TTL. |+| [0313](0313-acp-explicit-command-intent.md) | Harness carries explicit command completion intent in ACP `_meta["harness/command"]`; literal slash prose bypasses dispatch and expansion, while legacy clients retain their syntax. || [0302](0302-sse-idle-watchdogs-follow-body-byte-progress.md) | SSE idle watchdogs observe partial body-byte progress, while separate unfinished-event time and size bounds preserve recovery. |diff --git a/scripts/test-acp-slash-typo.py b/scripts/test-acp-slash-typo.pyindex 50d6739c..0509be10 100755--- a/scripts/test-acp-slash-typo.py+++ b/scripts/test-acp-slash-typo.py@@ -6,6 +6,7 @@ import importlib.utilimport jsonimport sysimport tempfile+import timefrom pathlib import PathREPO = Path(__file__).resolve().parents[1]@@ -63,5 +64,80 @@ def run(binary):print("ACP slash typo: answered locally with a suggestion, no model call; paths still reach the model: ok")+def run_explicit(binary):+ """Literal Harness prompts reach the model and remain resumable (#1814)."""+ with tempfile.TemporaryDirectory(prefix="graff-acp-command-intent-") as temporary:+ base = Path(temporary).resolve()+ cwd, home = base / "work", base / "home"+ cwd.mkdir()+ home.mkdir()+ model = ScriptedModel([], exhausted_text="synthetic prompt answered")+ port = model.start(0)+ a = Acp(binary, cwd, home, port)+ original = "/ widgets are ordinary text; synthetic parser task."+ try:+ a.request("initialize", {"protocolVersion": 1})+ sid = a.request("session/new", {"cwd": str(cwd), "mcpServers": []})["result"]["sessionId"]++ def prompt(text, selected=False):+ start = len(a.events)+ turn = a.request("session/prompt", {+ "sessionId": sid,+ "prompt": [{"type": "text", "text": text}],+ "_meta": {"harness/command": selected},+ }, 35)+ assert turn["result"]["stopReason"] == "end_turn", turn+ return reply_text(a, start)++ for text in [original, "/", "/help", "/unknown prose", "/goal discuss this literally",+ "/review discuss this literally", "/issue discuss this literally",+ "/btw discuss this literally", "/loop discuss this literally", "intro\n/help"]:+ count = len(model.requests)+ reply = prompt(text)+ assert "synthetic prompt answered" in reply, (text, reply)+ assert len(model.requests) == count + 1, text+ encoded = json.dumps(text)[1:-1]+ assert encoded in json.dumps(model.requests[-1]["messages"]), text+ count = len(model.requests)+ reply = prompt("/help", selected=True)+ assert "synthetic prompt answered" not in reply and reply.strip(), reply+ assert len(model.requests) == count, "selected /help was sent to model"+ reply = prompt("/resuem", selected=True)+ assert "unknown command '/resuem'" in reply, reply+ assert len(model.requests) == count, "selected typo was sent to model"+ # A literal /goal must not have installed an autonomous objective.+ reply = prompt("/goal", selected=True)+ assert "discuss this literally" not in reply, reply+ saved = cwd / ".graff" / "sessions" / f"{sid}.session.json"+ deadline = time.monotonic() + 5+ while not saved.exists() and time.monotonic() < deadline:+ time.sleep(.02)+ assert saved.exists(), "the literal first prompt left no durable session"+ finally:+ a.close()+ model.stop()++ resumed_model = ScriptedModel([], exhausted_text="synthetic retry answered")+ port = resumed_model.start(0)+ b = Acp(binary, cwd, home, port)+ try:+ b.request("initialize", {"protocolVersion": 1})+ loaded = b.request("session/load", {"sessionId": sid, "cwd": str(cwd), "mcpServers": []})+ assert "error" not in loaded, loaded+ turn = b.request("session/prompt", {+ "sessionId": sid,+ "prompt": [{"type": "text", "text": "retry the synthetic task"}],+ "_meta": {"harness/command": False},+ }, 35)+ assert turn["result"]["stopReason"] == "end_turn", turn+ assert original in json.dumps(resumed_model.requests[-1]["messages"]), "retry lost the original task"+ finally:+ b.close()+ resumed_model.stop()+ print("ACP explicit command intent: literal slash/goal/review/issue/side/loop prompts reach model; selected commands stay local; restart preserves original task: ok")++if __name__ == "__main__":- run(Path(sys.argv[1] if len(sys.argv) > 1 else REPO / "zig-out/bin/graff").resolve())+ binary = Path(sys.argv[1] if len(sys.argv) > 1 else REPO / "zig-out/bin/graff").resolve()+ run(binary)+ run_explicit(binary)diff --git a/src/acp.zig b/src/acp.zigindex ba3262f4..b64c886a 100644--- a/src/acp.zig+++ b/src/acp.zig@@ -83,7 +83,8 @@ fn liveSlash(ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror!?[]cofn liveAfter(ctx: *anyopaque, arena: Allocator, text: []const u8, prompt: ?std.json.Value) void {const live: *LiveTurn = @ptrCast(@alignCast(ctx));- _ = playbook_glue.applyUserOverride(live.root, arena, text);+ if (if (live.dispatch) |d| d.commands else true)+ _ = playbook_glue.applyUserOverride(live.root, arena, text);// ACP image blocks join the next model request (promptCapabilities.image)._ = @import("acp_images.zig").stage(live.root, prompt);}diff --git a/src/acp_command_intent.zig b/src/acp_command_intent.zignew file mode 100644index 00000000..b41185d6--- /dev/null+++ b/src/acp_command_intent.zig@@ -0,0 +1,12 @@+//! Harness carries completion acceptance separately from prompt text. Legacy+//! ACP clients retain their command syntax; explicit false means literal prose.+const std = @import("std");++pub fn selected(params: ?std.json.Value) bool {+ const root = params orelse return true;+ if (root != .object) return true;+ const meta = root.object.get("_meta") orelse return true;+ if (meta != .object) return true;+ const value = meta.object.get("harness/command") orelse return true;+ return value == .bool and value.bool;+}diff --git a/src/acp_engine.zig b/src/acp_engine.zigindex e41e9c14..1008b04a 100644--- a/src/acp_engine.zig+++ b/src/acp_engine.zig@@ -70,6 +70,8 @@ pub const Dispatch = struct {seed: u64 = 0,created: u32 = 0,slash: ?SlashFn = null,+ /// Per-prompt completion intent; also gates goal/review expansion in live turns.+ commands: bool = true,after_user: ?AfterUserFn = null,bind_session: ?BindSessionFn = null,load_session: ?LoadSessionFn = null,@@ -185,6 +187,7 @@ fn turnError(d: *Dispatch, w: *Io.Writer, req: proto.Request, err: anyerror) !vofn promptTurn(d: *Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request) !void {if (v2.on()) return v2_prompt.promptTurn(d, arena, w, req);+ d.commands = @import("acp_command_intent.zig").selected(req.params);const obj: ?std.json.ObjectMap = if (req.params) |p| (if (p == .object) p.object else null) else null;const sid = blk: {if (obj) |o| if (util.strFieldObj(o, "sessionId")) |s| break :blk s;@@ -203,7 +206,7 @@ fn promptTurn(d: *Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request)// 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);- if (d.slash) |slash| {+ if (if (d.commands) d.slash else null) |slash| {const reply = slash(d.ctx, arena, @import("acp_t3.zig").slashText(if (obj) |o| o.get("prompt") else null, flat, text)) catch |err| {emitConfigChange(d, arena, w, sid, config_before) catch |config_err| return turnError(d, w, req, config_err);return turnError(d, w, req, err);@@ -582,19 +585,3 @@ test "ACP failure carries its reason without claiming completion and the next prtry handleLine(&dispatch, arena.allocator(), &writer, request);try std.testing.expect(std.mem.indexOf(u8, writer.buffered(), "end_turn") != null);}--test "failed slash command returns an ACP error instead of killing the worker loop" {- const Fixture = struct {- fn slash(_: *anyopaque, _: Allocator, _: []const u8) anyerror!?[]const u8 {- return error.ApiError;- }- };- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- var buf: [2048]u8 = undefined;- var writer: Io.Writer = .fixed(&buf);- var dispatch: Dispatch = .{ .turn = echoTurn, .ctx = undefined, .slash = Fixture.slash };- try handleLine(&dispatch, arena.allocator(), &writer, "{\"id\":1,\"method\":\"session/prompt\",\"params\":{\"prompt\":[{\"type\":\"text\",\"text\":\"/compact\"}]}}");- try std.testing.expect(std.mem.indexOf(u8, writer.buffered(), "ApiError") != null);- try std.testing.expect(std.mem.indexOf(u8, writer.buffered(), "end_turn") == null);-}diff --git a/src/acp_engine_test.zig b/src/acp_engine_test.zigindex c7268d84..e45452f6 100644--- a/src/acp_engine_test.zig+++ b/src/acp_engine_test.zig@@ -11,6 +11,38 @@ fn echoTurn(_: *anyopaque, arena: Allocator, text: []const u8) anyerror![]constreturn std.fmt.allocPrint(arena, "echo:{s}", .{text});}+test "explicit command intent keeps literal slash prompts out of command dispatch in v1 and v2" {+ const v2 = @import("acp_v2.zig");+ defer v2.resetForTest();+ const Fixture = struct {+ fn slash(_: *anyopaque, _: Allocator, _: []const u8) anyerror!?[]const u8 {+ return "command executed";+ }+ };+ for ([_]bool{ false, true }) |draft| {+ v2.resetForTest();+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ const a = state.allocator();+ var out: Io.Writer.Allocating = .init(a);+ var d: Dispatch = .{ .turn = echoTurn, .ctx = undefined, .slash = Fixture.slash };+ if (draft) {+ v2.gate = true;+ try handleLine(&d, a, &out.writer, "{\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":2,\"capabilities\":{},\"info\":{\"name\":\"test\",\"version\":\"1\"}}}");+ }+ out.clearRetainingCapacity();+ try handleLine(&d, a, &out.writer, "{\"id\":2,\"method\":\"session/prompt\",\"params\":{\"prompt\":[{\"type\":\"text\",\"text\":\"/ widgets are prose\"}],\"_meta\":{\"harness/command\":false}}}");+ try std.testing.expect(std.mem.indexOf(u8, out.writer.buffered(), "echo:/ widgets are prose") != null);+ try std.testing.expect(std.mem.indexOf(u8, out.writer.buffered(), "command executed") == null);+ out.clearRetainingCapacity();+ try handleLine(&d, a, &out.writer, "{\"id\":3,\"method\":\"session/prompt\",\"params\":{\"prompt\":[{\"type\":\"text\",\"text\":\"/help\"}],\"_meta\":{\"harness/command\":true}}}");+ try std.testing.expect(std.mem.indexOf(u8, out.writer.buffered(), "command executed") != null);+ out.clearRetainingCapacity();+ try handleLine(&d, a, &out.writer, "{\"id\":4,\"method\":\"session/prompt\",\"params\":{\"prompt\":[{\"type\":\"text\",\"text\":\"/help\"}]}}");+ try std.testing.expect(std.mem.indexOf(u8, out.writer.buffered(), "command executed") != null);+ }+}+test "slash commands refresh occupancy before their terminal response" {const Fixture = struct {fn slash(_: *anyopaque, _: Allocator, _: []const u8) anyerror!?[]const u8 {@@ -78,3 +110,19 @@ test "interrupted ACP prompt preserves cancellation provenance in its terminal rtry std.testing.expect(std.mem.indexOf(u8, output, "\"graff/cancelSource\":\"none\"") != null);try std.testing.expect(std.mem.indexOf(u8, output, "harness cancelled the turn") != null);}++test "failed slash command returns an ACP error instead of killing the worker loop" {+ const Fixture = struct {+ fn slash(_: *anyopaque, _: Allocator, _: []const u8) anyerror!?[]const u8 {+ return error.ApiError;+ }+ };+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ var buf: [2048]u8 = undefined;+ var writer: Io.Writer = .fixed(&buf);+ var dispatch: Dispatch = .{ .turn = echoTurn, .ctx = undefined, .slash = Fixture.slash };+ try handleLine(&dispatch, arena.allocator(), &writer, "{\"id\":1,\"method\":\"session/prompt\",\"params\":{\"prompt\":[{\"type\":\"text\",\"text\":\"/compact\"}]}}");+ try std.testing.expect(std.mem.indexOf(u8, writer.buffered(), "ApiError") != null);+ try std.testing.expect(std.mem.indexOf(u8, writer.buffered(), "end_turn") == null);+}diff --git a/src/acp_live_turn.zig b/src/acp_live_turn.zigindex a6dd89cc..1962ce3e 100644--- a/src/acp_live_turn.zig+++ b/src/acp_live_turn.zig@@ -98,8 +98,9 @@ pub const LiveTurn = struct {// An objective sets state AND starts this turn, unlike lifecycle verbs (#1528).const goal_pacing = @import("goal_pacing.zig");const line = std.mem.trim(u8, text, " \t\r\n");- const objective = @import("repl_glue.zig").goalPromptFromLine(line);- const auto = try goal_pacing.autonomousFromLine(arena, line, objective, false);+ const commands = if (self.dispatch) |d| d.commands else true;+ const objective = if (commands) @import("repl_glue.zig").goalPromptFromLine(line) else null;+ const auto = if (commands) try goal_pacing.autonomousFromLine(arena, line, objective, false) else null;var clock: goal_pacing.LoopClock = .{};defer clock.clear(self.root);if (auto) |invocation| {@@ -112,8 +113,8 @@ pub const LiveTurn = struct {try proto.writeSessionUpdate(self.out, self.session_id, try std.fmt.allocPrint(arena, "{s}\n", .{notice}));try self.out.flush();}- const review_prompt = review.promptFromLine(text);- const issue_report = @import("issue_cmd.zig").promptFromLine(text);+ const review_prompt = if (commands) review.promptFromLine(text) else null;+ const issue_report = if (commands) @import("issue_cmd.zig").promptFromLine(text) else null;const parent_override = self.root.sys_override;const parent_review_mode = self.root.review_mode;self.root.review_mode = review_prompt != null;@@ -125,7 +126,7 @@ pub const LiveTurn = struct {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();- if (@import("side_steer.zig").isSideRequest(text))+ if (commands and @import("side_steer.zig").isSideRequest(text))return @import("side_steer.zig").spawnSide(self.root, arena, null, text);// Match REPL expansion order: review, issue brief, then goal pacing.const base_prompt = review_prompt orelse if (issue_report) |report| try @import("issue_cmd.zig").userText(arena, report) else if (auto) |invocation| invocation.prompt else text;diff --git a/src/acp_v2_prompt.zig b/src/acp_v2_prompt.zigindex 2e08aba0..df66e724 100644--- a/src/acp_v2_prompt.zig+++ b/src/acp_v2_prompt.zig@@ -12,6 +12,7 @@ const util = @import("util.zig");const v2 = @import("acp_v2.zig");pub fn promptTurn(d: *engine.Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request) !void {+ d.commands = @import("acp_command_intent.zig").selected(req.params);const obj: ?std.json.ObjectMap = if (req.params) |p| (if (p == .object) p.object else null) else null;const sid = blk: {if (obj) |o| if (util.strFieldObj(o, "sessionId")) |s| break :blk s;@@ -50,7 +51,7 @@ const Outcome = union(enum) {fn run(d: *engine.Dispatch, arena: Allocator, w: *Io.Writer, sid: []const u8, text: []const u8, prompt: ?std.json.Value) Outcome {@import("acp_citations.zig").endTurn(sid); // a failed turn must not leave a marker open- if (d.slash) |slash| {+ if (if (d.commands) d.slash else null) |slash| {const reply = slash(d.ctx, arena, text) catch |err| return failure(d, err);if (reply) |plain| {if (plain.len > 0) proto.writeSessionUpdate(w, sid, plain) catch |err| return failure(d, err);