graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Keep ACP startup responsive and retire failed handshake workers
justrach9c4d5fc90681
diff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.tsindex fd6ad641..ee97d5e4 100644--- a/apps/native/app/api/acp/route.ts+++ b/apps/native/app/api/acp/route.ts@@ -11,6 +11,7 @@ import { defaultRoot, resolveRoot } from "@/lib/server-root";import { prepareGuiPrompt } from "@/lib/gui-skill-context";import { retireWorker } from "@/lib/acp-retire";+import { initializeWorker } from "@/lib/acp-bootstrap";import { finishCancelledPrompt } from "@/lib/acp-cancel";export const runtime = "nodejs";@@ -222,12 +223,12 @@ async function bootstrap(chat: string, opts: BootstrapOpts): Promise<Slot> {yolo: opts.yolo ?? recovering?.yolo ?? defaultYolo(),mcp: opts.mcp ?? recovering?.mcp ?? true,});- await rpc(slot, "initialize", { protocolVersion: 1, clientCapabilities: { fs: {} } }, HANDSHAKE_MS);- const created = (await rpc(slot, "session/new", { cwd: slot.cwd }, HANDSHAKE_MS)) as {- sessionId?: string;- };- if (!created?.sessionId) throw new Error("session/new returned no sessionId");- slot.sessionId = created.sessionId;+ slot.sessionId = await initializeWorker(slot.transport, slot.cwd, async () => {+ slot.restart = true;+ slot.restartReady = retireWorker(slot.child);+ try { await slot.restartReady; }+ finally { if (slots.get(chat) === slot) slots.delete(chat); }+ }, HANDSHAKE_MS);await drainCommands(slot);return slot;}diff --git a/apps/native/lib/acp-bootstrap.test.ts b/apps/native/lib/acp-bootstrap.test.tsnew file mode 100644index 00000000..068a926c--- /dev/null+++ b/apps/native/lib/acp-bootstrap.test.ts@@ -0,0 +1,45 @@+import { test, expect } from "bun:test";+import { spawn } from "node:child_process";+import { once } from "node:events";+import { AcpTransport } from "./acp-transport";+import { initializeWorker } from "./acp-bootstrap";+import { retireWorker } from "./acp-retire";++async function worker(mode: string) {+ const child = spawn(process.execPath, ["-e", `+ const mode = ${JSON.stringify(mode)};+ const send = value => console.log(JSON.stringify(value));+ 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:{}});+ if(req.method==='session/new' && mode!=='session/new') send({id:req.id,result:mode==='invalid'?{}:{sessionId:'ready'}});+ });+ console.log('ready');+ `], { stdio: ["pipe", "pipe", "inherit"] });+ const transport = new AcpTransport(child);+ await once(child.stdout, "data");+ return { child, transport };+}++for (const mode of ["initialize", "session/new", "invalid"]) {+ test(`failed ACP ${mode} retires its child and a fresh worker succeeds`, async () => {+ const failed = await worker(mode);+ let retired = false;+ try {+ await expect(initializeWorker(failed.transport, process.cwd(), async () => {+ await retireWorker(failed.child, 50); retired = true;+ }, 50)).rejects.toThrow(`ACP startup failed during ${mode==='invalid'?'session/new':mode}`);+ expect(retired).toBe(true);+ expect(failed.transport.usable).toBe(false);+ expect(failed.child.exitCode !== null || failed.child.signalCode !== null).toBe(true);+ await expect(failed.transport.request('initialize')).rejects.toThrow('ACP startup failed');+ } finally { failed.child.kill('SIGKILL'); }+ const fresh = await worker('okay');+ try {+ expect(await initializeWorker(fresh.transport, process.cwd(), async () => {+ throw new Error('A successful handshake must not retire its child');+ }, 1000)).toBe('ready');+ expect(fresh.transport.usable).toBe(true);+ } finally { await retireWorker(fresh.child, 50); }+ });+}diff --git a/apps/native/lib/acp-bootstrap.ts b/apps/native/lib/acp-bootstrap.tsnew file mode 100644index 00000000..4d5158fb--- /dev/null+++ b/apps/native/lib/acp-bootstrap.ts@@ -0,0 +1,25 @@+import type { AcpTransport } from "./acp-transport";++/** 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(+ transport: AcpTransport, cwd: string, retire: () => Promise<void>, timeoutMs: number,+): Promise<string> {+ let phase = "initialize";+ try {+ await transport.request(phase, { protocolVersion: 1, clientCapabilities: { fs: {} } }, timeoutMs);+ phase = "session/new";+ const created = await transport.request(phase, { cwd }, timeoutMs) as { sessionId?: unknown } | null;+ if (typeof created?.sessionId !== "string" || !created.sessionId) {+ throw new Error("session/new returned no sessionId");+ }+ return created.sessionId;+ } catch (cause) {+ const detail = cause instanceof Error ? cause.message : String(cause);+ const error = new Error(`ACP startup failed during ${phase}: ${detail}. Retry to start a new worker.`, { cause });+ transport.abort(error);+ try { await retire(); }+ catch (cleanup) { throw new Error(`${error.message} Worker cleanup failed: ${cleanup instanceof Error ? cleanup.message : String(cleanup)}`, { cause: error }); }+ throw error;+ }+}diff --git a/apps/native/lib/acp-route.test.ts b/apps/native/lib/acp-route.test.tsindex b4a8e866..3d933cf0 100644--- a/apps/native/lib/acp-route.test.ts+++ b/apps/native/lib/acp-route.test.ts@@ -131,3 +131,57 @@ readline.createInterface({input:process.stdin}).on('line', line => {rmSync(temp, { recursive: true, force: true });}}, 10000);++test("an older failed bootstrap cannot retire a newer chat worker", async () => {+ const temp = mkdtempSync(path.join(os.tmpdir(), "graff-acp-replacement-"));+ const binary = path.join(temp, "agent.cjs");+ const oldBin = process.env.GRAFF_BIN;+ writeFileSync(binary, `#!/usr/bin/env node+const fs=require('node:fs');+const stalled=process.argv.includes('stalled');+fs.appendFileSync('starts',String(process.pid)+'\\n');+const send=value=>console.log(JSON.stringify(value));+require('node:readline').createInterface({input:process.stdin}).on('line',line=>{+ const req=JSON.parse(line);+ if(req.method==='initialize') {+ if(stalled) fs.writeFileSync('stalled',String(process.pid));+ else send({id:req.id,result:{}});+ }+ if(req.method==='session/new') {+ send({id:req.id,result:{sessionId:'replacement'}});+ send({method:'session/update',params:{update:{sessionUpdate:'available_commands_update',availableCommands:[{name:'help'}]}}});+ }+}).on('close',()=>process.exit(0));+`, {mode:0o700});+ const chat = `replacement-test-${path.basename(temp)}`;+ const call = (method: string, params = {}) => deadline(POST(new NextRequest("http://localhost/api/acp", {+ method:"POST",body:JSON.stringify({chat,method,params}),+ })), method);+ try {+ process.env.GRAFF_BIN = binary;+ const older = call("bootstrap", {cwd:temp,model:"stalled",mcp:true});+ await deadline((async()=>{+ for(;;) {+ try { readFileSync(path.join(temp,"stalled")); return; } catch {}+ await new Promise(resolve=>setTimeout(resolve,10));+ }+ })(),"stalled child ready");+ const newer = await call("bootstrap", {cwd:temp,model:"replacement",mcp:true});+ expect(newer.status).toBe(200);+ const failed = await older;+ expect(failed.status).toBe(502);+ expect((await failed.json()).error).toContain("ACP startup failed during initialize");+ const reused = await call("bootstrap", {cwd:temp,model:"replacement",mcp:true});+ expect(reused.status).toBe(200);+ expect((await reused.json()).sessionId).toBe("replacement");+ expect((await call("initialize")).status).toBe(200);+ const started = readFileSync(path.join(temp,"starts"),"utf8").trim().split("\n").map(Number);+ expect(started.length).toBe(2);+ expect(()=>process.kill(started[0],0)).toThrow();+ expect(()=>process.kill(started[1],0)).not.toThrow();+ } finally {+ await call("dispose");+ if(oldBin===undefined)delete process.env.GRAFF_BIN;else process.env.GRAFF_BIN=oldBin;+ rmSync(temp,{recursive:true,force:true});+ }+},10000);diff --git a/build.zig b/build.zigindex 4c259450..2486302e 100644--- a/build.zig+++ b/build.zig@@ -125,6 +125,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_startup_test = b.addSystemCommand(&.{ "python3", "scripts/test-acp-startup.py" });+ acp_startup_test.addArtifactArg(exe);+ test_step.dependOn(&acp_startup_test.step);// Learning kit: the adapter/suite files `graff learn init` materializes// into a workspace so zero-configuration learning needs no repo checkout.diff --git a/docs/adr/0035-first-turn-skips-deferred-mcp-join.md b/docs/adr/0035-first-turn-skips-deferred-mcp-join.mdindex 3752d304..334db0cb 100644--- a/docs/adr/0035-first-turn-skips-deferred-mcp-join.md+++ b/docs/adr/0035-first-turn-skips-deferred-mcp-join.md@@ -7,7 +7,9 @@ Later-request joining is updated by [ADR 0104](0104-live-publication-and-deferre## ContextInteractive `--yolo` (including `graff acp`) starts MCP handshakes in the-background so the prompt can paint. The first `request()` still called+background so the prompt can paint. ACP’s JSON stdout discipline does not+select the blocking CLI `--json` startup path; the explicit subcommand+distinguishes them. Both configured MCP servers and companions use this gate. The first `request()` still called`joinPending`, so a silent stdio probe (default 5s) or a 15s handshake capblocked every native tool on the first turn. The chips looked late; themodel had not even been called.diff --git a/scripts/test-acp-startup.py b/scripts/test-acp-startup.pynew file mode 100644index 00000000..ad94671b--- /dev/null+++ b/scripts/test-acp-startup.py@@ -0,0 +1,78 @@+#!/usr/bin/env python3+"""ACP initializes while an optional MCP child never answers its handshake."""+import json+import os+import selectors+import signal+import subprocess+import sys+import tempfile+import time+from pathlib import Path+++def main():+ if os.name != "posix":+ print("ACP startup process-group regression: POSIX only")+ return+ binary = Path(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff").resolve()+ with tempfile.TemporaryDirectory(prefix="graff-acp-startup-") as temporary:+ root = Path(temporary)+ shim = root / "bin"+ shim.mkdir()+ security = shim / "security"+ security.write_text("#!/bin/sh\nexit 44\n")+ security.chmod(0o700)+ slow = root / "slow.py"+ slow.write_text("import os,pathlib,sys,time\npathlib.Path('started').write_text(str(os.getpid()))\nfor line in sys.stdin: time.sleep(30)\n")+ config = root / "mcp.json"+ config.write_text(json.dumps({"mcpServers": {"slow-fixture": {"command": sys.executable, "args": [str(slow)]}}}))+ env = {"HOME": str(root), "PATH": str(shim) + ":/usr/bin:/bin", "TERM": "dumb",+ "LMSTUDIO_API_KEY": "fixture", "GRAFF_MCP_CONFIG": str(config),+ "GRAFF_NO_ADOPT": "1", "GRAFF_NO_TELEMETRY": "1", "GRAFF_FLEET": "off"}+ with (root / "stderr").open("w") as stderr:+ child = subprocess.Popen([str(binary), "acp", "--yolo", "--model", "lmstudio"],+ cwd=root, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,+ stderr=stderr, start_new_session=True)+ poll = selectors.DefaultSelector()+ poll.register(child.stdout, selectors.EVENT_READ)+ try:+ deadline = time.monotonic() + 5+ while not (root / "started").exists() and time.monotonic() < deadline:+ if child.poll() is not None:+ raise AssertionError("ACP exited before the optional server started")+ time.sleep(.01)+ assert (root / "started").exists(), "optional server did not start"+ child.stdin.write(b'{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":1}}\n')+ child.stdin.flush()+ deadline = time.monotonic() + 5+ buffer = b""+ ready = False+ while time.monotonic() < deadline and not ready:+ if not poll.select(.1):+ continue+ chunk = os.read(child.stdout.fileno(), 65536)+ assert chunk, "ACP exited before initialize"+ buffer += chunk+ while b"\n" in buffer:+ line, buffer = buffer.split(b"\n", 1)+ message = json.loads(line) # stdout must stay protocol-clean.+ ready |= message.get("id") == 1 and "result" in message+ assert ready, "ACP initialize blocked on the optional MCP handshake"+ os.kill(int((root / "started").read_text()), 0)+ finally:+ poll.close()+ try:+ os.killpg(child.pid, signal.SIGTERM)+ except ProcessLookupError:+ pass+ try:+ child.wait(timeout=3)+ except subprocess.TimeoutExpired:+ os.killpg(child.pid, signal.SIGKILL)+ child.wait()+ print("ACP deferred startup integration: ok")+++if __name__ == "__main__":+ main()diff --git a/src/companion_boot.zig b/src/companion_boot.zigindex 824e0f36..b9519ac5 100644--- a/src/companion_boot.zig+++ b/src/companion_boot.zig@@ -19,9 +19,9 @@ const mcp_boot = @import("mcp_boot.zig");const mcp_schema_gate = @import("mcp_schema_gate.zig");const skills = @import("skills.zig");-/// Same gate as MCP `defer_join`: interactive yolo, not `--json` / `-p`.+/// Same gate as MCP `defer_join`: interactive yolo, including ACP, not CLI `--json` / `-p`.pub fn deferCompanion(flags: args.Flags, json_mode: bool) bool {- return flags.effectiveYolo() and flags.oneshot_prompt == null and !json_mode;+ return flags.oneshot_prompt == null and mcp_boot.deferMcpJoin(flags.effectiveYolo(), json_mode, mcp_boot.isAcp(flags.positionals.items));}pub fn probeLicensed(gpa: Allocator, io: Io) bool {@@ -106,3 +106,9 @@ test "a licensed companion is pinned eager, once, so no discovery round-trip ispinCompanionEager(arena);try std.testing.expectEqual(@as(usize, 1), mcp_schema_gate.g_policy.eager.len);}++test "ACP companion startup stays deferred despite JSON stdout discipline" {+ const positionals = [_][]const u8{"acp"};+ const flags: args.Flags = .{ .yolo_flag = true, .positionals = .{ .items = @constCast(&positionals), .capacity = 0 } };+ try std.testing.expect(deferCompanion(flags, true));+}diff --git a/src/mcp_boot.zig b/src/mcp_boot.zigindex e8d57ce6..1a1381ec 100644--- a/src/mcp_boot.zig+++ b/src/mcp_boot.zig@@ -268,11 +268,16 @@ pub fn firstRequestJoin(pending_len: usize, already_skipped: *bool) enum { none,return .join;}+pub fn isAcp(positionals: []const []const u8) bool {+ return positionals.len > 0 and std.mem.eql(u8, positionals[0], "acp");+}+/// ADR 0035: `--yolo` (including `-p`, which implies yolo) starts MCP in the/// background. `--json` keeps a blocking connect so the protocol stream does-/// not race a late catalog merge.-pub fn deferMcpJoin(yolo: bool, json_mode: bool) bool {- return yolo and !json_mode;+/// not race a late catalog merge. ACP shares stdout discipline, but its+/// interactive protocol must remain responsive while optional servers connect.+pub fn deferMcpJoin(yolo: bool, json_mode: bool, acp: bool) bool {+ return yolo and (!json_mode or acp);}/// Lean `-p` connects workspace `.mcp.json` (ADR 0029). It does not handshake@@ -396,9 +401,9 @@ test "firstRequestJoin skips once, then joins" {}test "deferMcpJoin covers -p yolo and leaves --json blocking" {- try std.testing.expect(deferMcpJoin(true, false));- try std.testing.expect(!deferMcpJoin(true, true));- try std.testing.expect(!deferMcpJoin(false, false));+ try std.testing.expect(deferMcpJoin(true, false, false));+ try std.testing.expect(!deferMcpJoin(true, true, false));+ try std.testing.expect(!deferMcpJoin(false, false, false));}test "oneshotSkipsImportedMcp is lean -p with no project .mcp.json" {@@ -441,3 +446,12 @@ test "#860 later requests leave unfinished handshakes queued and consume ready ttry std.testing.expect(joinPending(®));try std.testing.expectEqual(@as(usize, 0), reg.pending_starts.len);}++test "ACP stdout discipline does not block optional startup handshakes" {+ try std.testing.expect(isAcp(&.{"acp"}));+ try std.testing.expect(!isAcp(&.{}));+ try std.testing.expect(!isAcp(&.{ "repl", "acp" }));+ try std.testing.expect(deferMcpJoin(true, true, isAcp(&.{"acp"})));+ try std.testing.expect(!deferMcpJoin(false, true, true));+ try std.testing.expect(!deferMcpJoin(true, true, isAcp(&.{"repl"})));+}diff --git a/src/session_start.zig b/src/session_start.zigindex 49de5c9f..0334d750 100644--- a/src/session_start.zig+++ b/src/session_start.zig@@ -452,7 +452,7 @@ pub fn initRegistryConsent(io: Io, gpa: Allocator, arena: Allocator, out: *Io.Wrsink.emit(io, dimNotice(try std.fmt.allocPrint(arena, "ignoring ~/" ++ mcp_config.unsupported_rel_path ++ ": unsupported path — use ~/" ++ mcp_config.global_rel_path ++ " (global) or {s} (project)", .{mcp_config_path})));}const mcp_count = mcp_cli.countMcpServers(merged);- const defer_join = mcp_boot.deferMcpJoin(flags.effectiveYolo(), json_mode);+ const defer_join = mcp_boot.deferMcpJoin(flags.effectiveYolo(), json_mode, mcp_boot.isAcp(flags.positionals.items));const skip_imported = mcp_boot.oneshotSkipsImportedMcp(flags.oneshot_prompt != null,leanMode(flags.effectiveLean(), environ_map),