graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: start ACP goals in the submitting request
yxlyx5d0673b7b108
diff --git a/build.zig b/build.zigindex 984b7e41..9c57f9bd 100644--- a/build.zig+++ b/build.zig@@ -137,6 +137,9 @@ pub fn build(b: *std.Build) void {const acp_preauth_test = b.addSystemCommand(&.{ "python3", "scripts/test-acp-preauth.py" });acp_preauth_test.addArtifactArg(exe);test_step.dependOn(&acp_preauth_test.step);+ const acp_goal_test = b.addSystemCommand(&.{ "python3", "scripts/test-acp-goal.py" });+ acp_goal_test.addArtifactArg(exe);+ test_step.dependOn(&acp_goal_test.step);const acp_startup_test = b.addSystemCommand(&.{ "python3", "scripts/test-acp-startup.py" });acp_startup_test.addArtifactArg(exe);test_step.dependOn(&acp_startup_test.step);diff --git a/scripts/test-acp-goal.py b/scripts/test-acp-goal.pynew file mode 100644index 00000000..3bcc02c5--- /dev/null+++ b/scripts/test-acp-goal.py@@ -0,0 +1,136 @@+#!/usr/bin/env python3+"""#1528: ACP /goal must execute before any follow-up input or stdin EOF.++Offline: uses the tier-2 scripted model, an isolated workspace and no credentials.+Also checks duration parsing, replacement, and command-only lifecycle verbs.+"""+from __future__ import annotations++import json+import os+from pathlib import Path+import queue+import subprocess+import sys+import tempfile+import threading++REPO = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(REPO / "scripts" / "eval"))+from mock_model import ScriptedModel+++def main() -> None:+ binary = str(Path(sys.argv[1] if len(sys.argv) > 1 else REPO / "zig-out/bin/graff").resolve())+ script = []+ for name in ("first", "replacement"):+ script.extend([+ {"tool": "todo_write", "arguments": {"todos": [{"content": "write marker", "status": "in_progress"}]}},+ {"tool": "bash", "arguments": {"command": "printf started > " + name + ".txt"}},+ {"tool": "todo_write", "arguments": {"todos": [{"content": "write marker", "status": "completed"}]}},+ {"text": "GOAL_DONE_" + name},+ ])+ model = ScriptedModel(script)+ port = model.start(0)+ try:+ with tempfile.TemporaryDirectory(prefix="graff-acp-goal-") as temp:+ workspace = Path(temp)+ env = {key: os.environ[key] for key in ("PATH", "TMPDIR", "SystemRoot") if key in os.environ}+ config = workspace / "mcp.json"+ config.write_text('{"mcpServers":{}}')+ env.update({+ "HOME": temp,+ "AI_GATEWAY_API_KEY": "local",+ "GRAFF_VERCEL_URL": "http://127.0.0.1:%d/v1/chat/completions" % port,+ "GRAFF_MCP_CONFIG": str(config),+ "GRAFF_NO_TELEMETRY": "1",+ "GRAFF_FLEET": "off",+ "GRAFF_NO_SMOLIFY": "1",+ "GRAFF_LEARN_AUTO": "0",+ "GRAFF_BEHAVIOR_UPLOAD": "0",+ "GRAFF_NO_BROWSER": "1",+ "NO_COLOR": "1",+ })+ settings = workspace / ".harness/settings.json"+ settings.parent.mkdir()+ settings.write_text('{"ai_title":false}')+ proc = subprocess.Popen(+ [binary, "--yolo", "--no-telemetry", "--model", "vercel", "--old", "--no-lean", "acp"],+ cwd=temp, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,+ stderr=subprocess.PIPE, text=True,+ )+ responses = queue.Queue()++ def read_stdout() -> None:+ for line in proc.stdout:+ try:+ responses.put(json.loads(line))+ except ValueError:+ responses.put({"invalid_stdout": line})+ responses.put({"eof": True})++ reader = threading.Thread(target=read_stdout, daemon=True)+ reader.start()++ def request(rpc_id: int, method: str, params: dict) -> list:+ proc.stdin.write(json.dumps({"jsonrpc": "2.0", "id": rpc_id, "method": method, "params": params}) + "\n")+ proc.stdin.flush()+ events = []+ while True:+ event = responses.get(timeout=45)+ assert "invalid_stdout" not in event and "eof" not in event, event+ events.append(event)+ if event.get("id") == rpc_id:+ assert "error" not in event, event+ return events++ try:+ request(1, "initialize", {"protocolVersion": 1})+ events = request(2, "session/new", {"cwd": temp, "mcpServers": []})+ sid = events[-1]["result"]["sessionId"]+ rpc_id = 3++ def prompt(text: str) -> list:+ nonlocal rpc_id+ events = request(rpc_id, "session/prompt", {"sessionId": sid, "prompt": [{"type": "text", "text": text}]})+ rpc_id += 1+ assert events[-1]["result"]["stopReason"] == "end_turn", events[-1]+ return events++ for name, text in (("first", "/goal 30m write first marker"), ("replacement", "/goal write replacement marker")):+ before = len(model.requests)+ events = prompt(text)+ # stdin is still open and no further prompt has been sent.+ assert len(model.requests) > before, "/goal acknowledged without starting work"+ assert (workspace / (name + ".txt")).read_text() == "started"+ chunks = [e["params"]["update"]["content"]["text"] for e in events+ if e.get("method") == "session/update"+ and e["params"]["update"].get("sessionUpdate") == "agent_message_chunk"]+ answer = "".join(chunks)+ assert "starting now" in answer and "GOAL_DONE_" + name in answer, answer+ sent = json.dumps(model.requests[before])+ assert "write " + name + " marker" in sent and "30m write" not in sent, sent+ commands = ["/goal", "/goal status", "/goal pause", "/goal resume"]+ if name == "replacement":+ commands.append("/goal clear")+ for command in commands:+ count = len(model.requests)+ prompt(command)+ assert len(model.requests) == count, command + " unexpectedly started work"+ proc.stdin.close()+ assert proc.wait(timeout=15) == 0, proc.stderr.read()+ finally:+ if proc.poll() is None:+ proc.kill()+ proc.wait()+ reader.join(timeout=5)+ for pipe in (proc.stdin, proc.stdout, proc.stderr):+ if pipe and not pipe.closed:+ pipe.close()+ finally:+ model.stop()+ print("ACP /goal immediate execution: passed (initial, replacement, budget, lifecycle)")+++if __name__ == "__main__":+ main()diff --git a/src/acp.zig b/src/acp.zigindex f375d0e7..c50b17cf 100644--- a/src/acp.zig+++ b/src/acp.zig@@ -70,7 +70,7 @@ fn liveCancelled() bool {/// turn; paths and prose return null and stay ordinary prompts. Pickers here/// find no TTY and fall back to printing their list.fn liveSlash(ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror!?[]const u8 {- if (@import("review.zig").promptFromLine(text) != null) return null;+ if (@import("review.zig").promptFromLine(text) != null or @import("repl_glue.zig").goalPromptFromLine(std.mem.trim(u8, text, " \t\r\n")) != null) return null;if (@import("issue_cmd.zig").promptFromLine(text) != null) return null;const live: *LiveTurn = @ptrCast(@alignCast(ctx));var aw: Io.Writer.Allocating = .init(arena);diff --git a/src/acp_live_turn.zig b/src/acp_live_turn.zigindex 8db79ae5..711a4120 100644--- a/src/acp_live_turn.zig+++ b/src/acp_live_turn.zig@@ -65,6 +65,23 @@ pub const LiveTurn = struct {if (inbox.permission) |bridge| bridge.cancel();inbox.end();};+ // 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);+ var clock: goal_pacing.LoopClock = .{};+ defer clock.clear(self.root);+ if (auto) |invocation| {+ var aw: Io.Writer.Allocating = .init(arena);+ try goal_pacing.armAndAnnounce(&clock, self.root, &aw.writer, arena, @import("util.zig").unixMs(self.root.io), invocation.budget());+ try main_mod.handleCommand(self.root, self.keys, arena, invocation.goal_line.?, &aw.writer);+ const notice = try @import("acp_engine.zig").stripSgr(arena, aw.writer.buffered());+ output_lock.lockUncancelable(self.root.io);+ defer output_lock.unlock(self.root.io);+ 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 parent_override = self.root.sys_override;const parent_review_mode = self.root.review_mode;@@ -79,7 +96,8 @@ pub const LiveTurn = struct {defer if (context.restore(self.root)) self.root.rebaseContextMeter();if (@import("side_steer.zig").isSideRequest(text))return @import("side_steer.zig").spawnSide(self.root, arena, null, text);- switch (try @import("turn_dedup.zig").enqueue(self.root, arena, self.out, review_prompt orelse text)) {+ const prompt = try @import("goal_state.zig").applyGoalSteering(arena, self.root, review_prompt orelse if (auto) |invocation| invocation.prompt else text);+ switch (try @import("turn_dedup.zig").enqueue(self.root, arena, self.out, prompt)) {.started => {},.skipped => return "",.stuck => return @import("turn_dedup.zig").stuck_text,