Skip to content

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

Python

fix(serve): treat the ultracode ack as terminal so set_ultracode cannot wedge a session

Rach Pradhanf19ef5df4321
diff --git a/src/schema_protocol.zig b/src/schema_protocol.zig
index b90992a2..9e078764 100644
--- a/src/schema_protocol.zig
+++ b/src/schema_protocol.zig
@@ -30,7 +30,7 @@ pub const flags =
pub const json =
\\{
\\ "transport": "newline-delimited JSON over stdin/stdout (--json)",
- \\ "request": "one JSON object per line: {\"type\":\"user\",\"text\":\"...\"} sends a user turn; {\"type\":\"review\",\"text\":\"target or instructions\"} runs one isolated read-only review turn with fresh model-visible history and no edits, delegation, workflows, or web access; {\"type\":\"answer\",\"text\":\"...\",\"cancelled\":false,\"call_id\":\"optional\"} answers an active ask_user event; {\"type\":\"set_system_prompt\",\"text\":\"...\",\"append\":false} replaces (or with append=true extends) the system prompt between turns and acks with a system_prompt event; {\"type\":\"set_model\",\"model\":\"gpt-5.5\",\"provider\":\"codex\"}, {\"type\":\"compact\"}, {\"type\":\"set_mode\",\"mode\":\"plan|normal\"}, and {\"type\":\"set_agent\",\"id\":\"reviewer\"}, {\"type\":\"set_effort\",\"level\":\"low|medium|high|xhigh|max|ultra\"}, and {\"type\":\"set_fast\",\"on\":true} are live control requests acked by model/compact/mode/agent/effort/fast/ultracode events. For compatibility, set_model also accepts legacy {\"name\":\"provider model|model\"}. NOTE: the system prompt heads the KV-cached prefix, so any mutation invalidates the cache for the whole conversation (per Manus context-engineering lessons) — set it at spawn when possible and mutate only at task boundaries",
+ \\ "request": "one JSON object per line: {\"type\":\"user\",\"text\":\"...\"} sends a user turn; {\"type\":\"review\",\"text\":\"target or instructions\"} runs one isolated read-only review turn with fresh model-visible history and no edits, delegation, workflows, or web access; {\"type\":\"answer\",\"text\":\"...\",\"cancelled\":false,\"call_id\":\"optional\"} answers an active ask_user event; {\"type\":\"set_system_prompt\",\"text\":\"...\",\"append\":false} replaces (or with append=true extends) the system prompt between turns and acks with a system_prompt event; {\"type\":\"set_model\",\"model\":\"gpt-5.5\",\"provider\":\"codex\"}, {\"type\":\"compact\"}, {\"type\":\"set_mode\",\"mode\":\"plan|normal\"}, and {\"type\":\"set_agent\",\"id\":\"reviewer\"}, {\"type\":\"set_effort\",\"level\":\"low|medium|high|xhigh|max|ultra\"}, {\"type\":\"set_fast\",\"on\":true}, and {\"type\":\"set_ultracode\",\"on\":true} are live control requests acked by model/compact/mode/agent/effort/fast/ultracode events. For compatibility, set_model also accepts legacy {\"name\":\"provider model|model\"}. NOTE: the system prompt heads the KV-cached prefix, so any mutation invalidates the cache for the whole conversation (per Manus context-engineering lessons) — set it at spawn when possible and mutate only at task boundaries",
\\ "score_request": "{\"type\":\"score\",\"prompt_sha\":\"<16 hex>\",\"score\":0.7,\"notes\":\"...\",\"parent_sha\":\"<16 hex, optional>\"} appends an evaluation record for an agent/prompt variant to this run's file under .graff/trajectories (the aggregate append-only DGM-style archive; prompt_sha = first 8 bytes of SHA-256 of the system prompt, hex; parent_sha records which prompt this variant was mutated from — the lineage edge DGM parent selection counts children with) and acks with a score event",
\\ "sequencing": "every event object below carries a monotonic per-session \"seq\" as its FIRST field: 1-based, gap-free, one id per emitted line. It survives a resume - the counter is persisted with the conversation as event_seq and restored by --resume, so a REPLACEMENT process continues the numbering instead of reissuing ids a consumer already saw. `graff serve` forwards the child's seq unchanged and uses it for ?from=N replay",
\\ "events": [
@@ -55,6 +55,7 @@ pub const json =
\\ {"type": "agent", "ok": true, "id": "reviewer", "chars": 0},
\\ {"type": "effort", "ok": true, "level": "medium", "applies": true},
\\ {"type": "fast", "ok": true, "on": true, "applies": true},
+ \\ {"type": "ultracode", "ok": true, "on": true},
\\ {"type": "score", "ok": true, "prompt_sha": "..."},
\\ {"type": "error", "message": "..."}
\\ ]
diff --git a/src/schema_serve.zig b/src/schema_serve.zig
index 7b416648..2125aaad 100644
--- a/src/schema_serve.zig
+++ b/src/schema_serve.zig
@@ -11,7 +11,7 @@ pub const json =
\\ {"method": "GET", "path": "/healthz", "description": "liveness + version, no auth"},
\\ {"method": "GET", "path": "/v1/schema", "description": "this schema document"},
\\ {"method": "POST", "path": "/v1/sessions", "description": "create OR resume a session (a graff --json child); optional JSON body {\"session\",\"model\",\"subagentProvider\",\"subagentModel\",\"allowCrossProviderSubagents\",\"noSubagentTier\",\"yolo\",\"system_prompt\",\"append_system_prompt\",\"maxToolCalls\",\"maxModelCalls\",\"dedupeToolCalls\"} overrides serve-level defaults. \"session\" (aliases \"session_id\"/\"resume\") names a durable session: 1-64 chars of [A-Za-z0-9._-], not starting with . or -; omitted means a fresh 16-hex name. Responds {\"session_id\":\"<name>\",\"resumed\":<bool>,\"last_seq\":<N>} - resumed says a session file already existed, last_seq is where the persisted event tape ends (reconnect with ?from=last_seq+1)"},
- \\ {"method": "POST", "path": "/v1/sessions/{id}", "description": "body is ONE stdio-protocol request object (user / review / set_system_prompt / set_model / compact / set_mode / set_agent / set_effort / set_fast / score / answer); non-answer requests stream application/x-ndjson events until the request's terminal event (turn/error, or the request-specific ack); answer requests return a JSON ack while the original user stream continues; one non-answer request in flight per session at a time. ?from=N or {\"resume_from\":N} replays persisted events with seq >= N before the live stream. {\"type\":\"reattach\"} sends nothing to the child and only replays+follows, so it is safe while another connection is mid-turn"},
+ \\ {"method": "POST", "path": "/v1/sessions/{id}", "description": "body is ONE stdio-protocol request object (user / review / set_system_prompt / set_model / compact / set_mode / set_agent / set_effort / set_fast / set_ultracode / score / answer); non-answer requests stream application/x-ndjson events until the request's terminal event (turn/error, or the request-specific ack); answer requests return a JSON ack while the original user stream continues; one non-answer request in flight per session at a time. ?from=N or {\"resume_from\":N} replays persisted events with seq >= N before the live stream. {\"type\":\"reattach\"} sends nothing to the child and only replays+follows, so it is safe while another connection is mid-turn"},
\\ {"method": "GET", "path": "/v1/sessions/{id}/events?from=N", "description": "reconnect: replay persisted events with seq >= N (default 1), then keep following the log live while a request is in flight, ending at that request's terminal event. Takes no protocol lock and never writes to the child, and works for a session this process never spawned as long as its event log is in the workspace"},
\\ {"method": "DELETE", "path": "/v1/sessions/{id}", "description": "graceful close: waits for any in-flight request, then EOFs the child's stdin. The session file and the event log stay on disk, so the id remains resumable"}
\\ ]
diff --git a/src/serve_events.zig b/src/serve_events.zig
index 9abc3c47..f66102c9 100644
--- a/src/serve_events.zig
+++ b/src/serve_events.zig
@@ -167,17 +167,36 @@ pub const Follower = struct {
}
};
-/// Is this child event line the terminal event of a protocol request?
-/// turn/error end user turns; the rest are between-turn acks. Unknown event
-/// types stream through (edge-version durability) — a newer child must still
-/// terminate every request with one of these.
+/// Every event type that ends a protocol request: turn/error close user turns,
+/// the rest are the between-turn acks mainloop.zig emits for control requests.
+/// An ack missing from this list wedges the session PERMANENTLY — serve.zig
+/// streams it and then blocks in takeDelimiter() still holding `busy`, so every
+/// later request on that session waits on a lock nobody will release. The test
+/// below pins this list against the emitter so a new control command cannot
+/// land without one.
+pub const terminal_events = [_][]const u8{
+ "turn",
+ "error",
+ "system_prompt",
+ "score",
+ "model",
+ "compact",
+ "mode",
+ "agent",
+ "effort",
+ "fast",
+ "ultracode",
+};
+
+/// Is this child event line the terminal event of a protocol request? Unknown
+/// event types stream through (edge-version durability) — a newer child must
+/// still terminate every request with one of these.
pub fn terminalEvent(line: []const u8) bool {
const t = stringField(line, "type") orelse "";
- return std.mem.eql(u8, t, "turn") or std.mem.eql(u8, t, "error") or
- std.mem.eql(u8, t, "system_prompt") or std.mem.eql(u8, t, "score") or
- std.mem.eql(u8, t, "model") or std.mem.eql(u8, t, "compact") or
- std.mem.eql(u8, t, "mode") or std.mem.eql(u8, t, "agent") or
- std.mem.eql(u8, t, "effort") or std.mem.eql(u8, t, "fast");
+ for (terminal_events) |name| {
+ if (std.mem.eql(u8, t, name)) return true;
+ }
+ return false;
}
/// Pull a JSON string field out of an event line by scanning, not parsing:
@@ -297,6 +316,9 @@ test "terminalEvent + stringField: envelope reads survive a seq prefix" {
try testing.expect(terminalEvent("{\"seq\":9,\"type\":\"error\",\"message\":\"x\"}"));
try testing.expect(!terminalEvent("{\"seq\":9,\"type\":\"text\",\"text\":\"x\"}"));
try testing.expect(!terminalEvent("{\"seq\":9,\"type\":\"tool_call\",\"name\":\"bash\"}"));
+ // set_ultracode's ack: absent from this list it streams and then blocks,
+ // holding `busy` for the life of the session.
+ try testing.expect(terminalEvent("{\"seq\":9,\"type\":\"ultracode\",\"ok\":true,\"on\":true}"));
try testing.expectEqualStrings("turn", stringField("{\"seq\":1,\"type\":\"turn\"}", "type").?);
try testing.expect(stringField("{\"seq\":1,\"type\":\"turn\"}", "missing") == null);
// escaped quote inside the value is skipped, not treated as the terminator
@@ -345,3 +367,47 @@ test "EventLog + Follower: appended lines tail without gaps or duplicates" {
reopened.append("{\"seq\":4,\"type\":\"started\"}");
try testing.expectEqual(@as(u64, 4), lastSeqOnDisk(io, tmp.dir, testing.allocator, path));
}
+
+test "terminal_events covers every control ack mainloop can emit" {
+ // The list is only correct relative to the emitter, so read the emitter.
+ // mainloop.zig's --json control block answers each between-turn request
+ // with exactly one event; any type of those that is not terminal wedges
+ // the session in serveMessage. Pinned as source text (route_policy_tests
+ // does the same for subagent.zig) because the property is about the emit
+ // sites, not about a value a runtime test could observe here.
+ const src = @embedFile("mainloop.zig");
+ const begin = std.mem.indexOf(u8, src, "json_request = std.json.parseFromSlice") orelse
+ return error.ControlBlockMoved;
+ const end = begin + (std.mem.indexOf(u8, src[begin..], "break :blk text;") orelse
+ return error.ControlBlockMoved);
+ const block = src[begin..end];
+
+ // Every ack in the block is a one-liner, which is what the scan below
+ // reads; a wrapped `.emit(.{` would slip past it entirely unchecked.
+ const emit = ".emit(.{";
+ const typed_emit = emit ++ " .type = \"";
+ try testing.expectEqual(std.mem.count(u8, block, emit), std.mem.count(u8, block, typed_emit));
+
+ var checked: usize = 0;
+ var rest = block;
+ while (std.mem.indexOf(u8, rest, typed_emit)) |at| {
+ const from = at + typed_emit.len;
+ const stop = from + (std.mem.indexOfScalar(u8, rest[from..], '"') orelse return error.ControlBlockMoved);
+ const name = rest[from..stop];
+ rest = rest[stop..];
+ var buf: [128]u8 = undefined;
+ const line = try std.fmt.bufPrint(&buf, "{{\"seq\":1,\"type\":\"{s}\"}}", .{name});
+ if (!terminalEvent(line)) {
+ std.debug.print("\ncontrol ack \"{s}\" is missing from serve_events.terminal_events\n", .{name});
+ return error.ControlAckNotTerminal;
+ }
+ checked += 1;
+ }
+ try testing.expect(checked >= 12); // the scan read acks, not an empty slice
+
+ // score is acked from its own module; answer/reattach never reach the
+ // streaming loop (serve.zig answers both before serveMessage sends).
+ const score_src = @embedFile("mainloop_score.zig");
+ try testing.expect(std.mem.indexOf(u8, score_src, ".emit(.{ .type = \"score\"") != null);
+ try testing.expect(terminalEvent("{\"seq\":1,\"type\":\"score\"}"));
+}