graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(engine): a frontendless agent's wire sink reserves no sequence ids (#330)
Rach Pradhanad622e84a978
diff --git a/src/agent_tool_render.zig b/src/agent_tool_render.zigindex f602d038..1c651876 100644--- a/src/agent_tool_render.zig+++ b/src/agent_tool_render.zig@@ -12,6 +12,11 @@//! - write errors are swallowed rather than propagated, because a sink's emit//! path returns void. A caller that used to abort its batch on a broken//! stdout now continues into the next failing write instead.+//!+//! WHO may announce a moment stays engine policy: the `!self.sub` gates on the+//! batch tallies and the meta notices remain at their emit sites, so nothing+//! here back-reads Agent policy to decide whether to draw. The only Agent+//! reads below are drawing handles — the writer and the allocator.const std = @import("std");const Io = std.Io;@@ -21,7 +26,7 @@ const agent_mod = @import("agent.zig");const Agent = agent_mod.Agent;const agent_output = @import("agent_output.zig");const sayText = agent_output.sayText;-const util = @import("util.zig"); // tests only: repeatBytes for the arg-cap case+const util = @import("util.zig"); // tests only: repeatBytes for the two cap casesconst ansi = @import("ansi.zig");const style = &ansi.style;@@ -92,14 +97,12 @@ pub fn toolResultLine(a: *Agent, r: ToolOutcome) void {const notice_buf_bytes: usize = 192;pub fn parallelBatchStarted(a: *Agent, count: usize) void {- if (a.sub) return; // a child's fan-out is the root's line to draw, not its ownvar buf: [notice_buf_bytes]u8 = undefined;const line = std.fmt.bufPrint(&buf, " {s}↯ running {d} tools in parallel{s}\n", .{ style.dim, count, style.reset }) catch return;sayText(a, line);}pub fn parallelBatchFinished(a: *Agent, o: BatchOutcome) void {- if (a.sub) return;var buf: [notice_buf_bytes]u8 = undefined;const line = std.fmt.bufPrint(&buf, " {s}↯ parallel tools finished: {d} completed, {d} failed, {d} cancelled{s}\n", .{ style.dim, o.done, o.failed, o.cancelled, style.reset }) catch return;sayText(a, line);@@ -108,7 +111,6 @@ pub fn parallelBatchFinished(a: *Agent, o: BatchOutcome) void {/// #318: the checklist isn't settled, so the completion parks. The escapes are/// the literal bytes the old call site spelled out (⏸, 🎯 below).pub fn completionDeferred(a: *Agent) void {- if (a.sub) return;sayText(a, "\xe2\x8f\xb8 completion deferred \xe2\x80\x94 the standing goal's checklist isn't settled\n");}@@ -118,7 +120,6 @@ pub fn goalCompleted(a: *Agent) void {/// A meta tool's own user-facing text, one line, exactly as it came.pub fn toolTextLine(a: *Agent, text: []const u8) void {- if (a.sub) return;var line: Io.Writer.Allocating = .init(a.gpa);defer line.deinit();line.writer.print("{s}\n", .{text}) catch return;@@ -169,7 +170,9 @@ test "the ⚙ line reproduces the old inline announcement, cap and ellipsis inclconst line = aw.writer.buffered();try std.testing.expect(std.mem.startsWith(u8, line, "⚙ codedb {\"q\":\"xxx"));try std.testing.expect(std.mem.endsWith(u8, line, "…\n"));- try std.testing.expectEqual(arg_preview_bytes, line.len - "⚙ codedb ".len - "…\n".len);+ // The literal, not arg_preview_bytes: this asserts the conversion kept the+ // pre-#422 inline cap, and asserting the constant against itself would not.+ try std.testing.expectEqual(@as(usize, 160), line.len - "⚙ codedb ".len - "…\n".len);}test "the result line marks success, failure and cancellation and previews one line" {@@ -199,6 +202,15 @@ test "the result line marks success, failure and cancellation and previews one ltoolResultLine(&a, .{ .name = "todo_write", .text = "todos", .is_error = false, .meta = true });try std.testing.expectEqualStrings("", aw.writer.buffered());+ // Over the cap: exactly 100 bytes of the first line, then the ellipsis —+ // the literal the pre-#422 inline path spelled out, not result_preview_bytes.+ aw.clearRetainingCapacity();+ const long = util.repeatBytes("z", 250);+ toolResultLine(&a, .{ .name = "bash", .text = &long, .is_error = false });+ const rline = aw.writer.buffered();+ try std.testing.expect(std.mem.endsWith(u8, rline, "…\n"));+ try std.testing.expectEqual(@as(usize, 100), rline.len - " ✓ ".len - "…\n".len);+// --timing adds the measured duration between the mark and the preview.aw.clearRetainingCapacity();main_mod.show_timing = true;@@ -236,12 +248,8 @@ test "batch tallies and meta notices render the old wording verbatim" {toolTextLine(&a, "completion recorded");try std.testing.expectEqualStrings("completion recorded\n", aw.writer.buffered());- // A subagent announces none of the root's batch/goal lines.- aw.clearRetainingCapacity();- a.sub = true;- parallelBatchStarted(&a, 3);- parallelBatchFinished(&a, .{ .done = 1, .failed = 0, .cancelled = 0 });- completionDeferred(&a);- toolTextLine(&a, "x");- try std.testing.expectEqualStrings("", aw.writer.buffered());+ // Who may announce these is engine policy, not a drawing decision: the+ // `!self.sub` gates live at the emit sites (agent_tools.runTools /+ // handleMeta), so a subagent never produces the moment at all and this+ // file needs no read into the Agent to suppress it.}diff --git a/src/agent_tools.zig b/src/agent_tools.zigindex d567580a..aa7f07a0 100644--- a/src/agent_tools.zig+++ b/src/agent_tools.zig@@ -132,7 +132,11 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {}if (ext_idx.items.len > 0) {- if (ext_idx.items.len > 1) {+ // A child's fan-out is the root's to announce, so the moment is not+ // produced at all for a subagent: engine policy about who owns the+ // terminal, kept at the emit site rather than re-derived by a sink+ // that would need to back-read the Agent to know (#422 slice-1 rule).+ if (ext_idx.items.len > 1 and !self.sub) {engine_sink.forAgent(self).emit(self.io, .{ .parallel_batch_started = .{ .count = ext_idx.items.len } });}const ctx: ToolCtx = .{@@ -193,7 +197,7 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {brief_diversity.noteSiblingBatch(self.arena, self.tracer, calls, ext_idx.items, results); // #382// #266: a cancelled parallel batch used to just look "running" and then// failed — one terminal line says what completed, failed, and cancelled.- if (ext_idx.items.len > 1) {+ if (ext_idx.items.len > 1 and !self.sub) { // root's line to draw, as abovevar tally: engine_events.BatchOutcome = .{ .done = 0, .failed = 0, .cancelled = 0 };for (ext_idx.items) |i| {const r = results[i];@@ -315,7 +319,7 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {}if (try goal_state.completionGate(self.arena, self)) |refusal| {goal_state.noteCompletionRefused(self); // arm the double-check (across turns) and mark the turn as worked (#318)- engine_sink.forAgent(self).emit(self.io, .completion_deferred);+ if (!self.sub) engine_sink.forAgent(self).emit(self.io, .completion_deferred); // root-only notice, as everreturn .{ .text = refusal, .is_error = true };}const result = if (tools_mod.json_args.object(call.input)) |o| (tools_mod.json_args.str(o, "result") orelse "") else "";@@ -329,7 +333,7 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {if (self.tracer) |t| t.note("goal", "completion; standing goal retained");}// Skip the re-print only when the result streamed live in full.- if (!self.argStreamedFully(call)) engine_sink.forAgent(self).emit(self.io, .{ .completion_text = .{ .text = result } });+ if (!self.sub and !self.argStreamedFully(call)) engine_sink.forAgent(self).emit(self.io, .{ .completion_text = .{ .text = result } });return .{ .text = "completion recorded", .is_error = false };}if (std.mem.eql(u8, call.name, "eval")) {@@ -340,7 +344,7 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {// Epoch-scoped replace, keeping omitted completed items; a write with// no usable items is rejected untouched (#318). goal_todo owns the rule.const r = try goal_todo.applyTodoWrite(self, if (tools_mod.json_args.object(call.input)) |o| o.get("todos") else null);- if (!r.rejected) engine_sink.forAgent(self).emit(self.io, .{ .todo_list_updated = .{ .text = r.text } });+ if (!self.sub and !r.rejected) engine_sink.forAgent(self).emit(self.io, .{ .todo_list_updated = .{ .text = r.text } });return .{ .text = r.text, .is_error = r.rejected };}if (std.mem.eql(u8, call.name, "clock_sleep")) {@@ -437,8 +441,9 @@ pub fn emitAskUser(self: *Agent, call_id: []const u8, question: []const u8, inpu/// --json supervisor times against, and the ⚙ line the terminal draws for the/// first of the two. Which of them a frontend surfaces (the wire skips/// ask_user, the terminal skips prose that already streamed) is the sink's-/// call — engine_events.durable() decides the wire half so no sequence id is-/// ever reserved for a line the wire drops.+/// call — engine_events.durable() decides the wire half, and jsonSink is+/// non-durable for an agent with no writer, so no sequence id is ever+/// reserved for a line the wire drops (#330).pub fn sayToolUse(self: *Agent, call: ToolCall) !void {const ev: engine_events.ToolInvocation = .{.name = call.name,diff --git a/src/engine_sink.zig b/src/engine_sink.zigindex 6ed6131d..da07f6ef 100644--- a/src/engine_sink.zig+++ b/src/engine_sink.zig@@ -14,7 +14,12 @@//! - JsonSink: the existing --json wire lines for these events,//! byte-identical to the old inline emits. The ONE translation point from//! internal type to wire shape: any change here is externally visible and-//! gated behind a schema_version bump.+//! gated behind a schema_version bump. Not yet the ONLY producer of those+//! shapes, though: subagent_run.zig's guiEmit writes `tool_call`/+//! `tool_result` rows with an extra `id` (schema_protocol.zig) straight to+//! stdout, bypassing this sink. Routing them through it needs an optional+//! `id` on ToolInvocation/ToolOutcome — decide that when #429 takes the+//! subagent cluster, while these structs are still cheap to change.//!//! Events are stamped with a {generation, sequence} Cursor at the dispatch//! boundary. In --json mode (the only durable sink today), durable events@@ -61,11 +66,11 @@ pub const EngineSink = struct {/// The emission boundary: stamp, then hand off. `io` backs the stdout/// lock, taken only when a durable sink reserves AND json_mode is on —/// a global, so `io` may be passed undefined only where json_mode is- /// known false (TUI dispatch; the tests here pin it). Durable emitters- /// must not emit durable events a sink will drop (jsonEmit returns on- /// out == null): the reserved id would burn with no wire line, opening- /// a seq gap (#330). Today printDelta guarantees that by returning- /// early when out == null, before any durable emission.+ /// known false (TUI dispatch; the tests here pin it). A durable sink must+ /// never be handed an event it will drop: the reserved id would burn with+ /// no wire line, opening a seq gap (#330). jsonSink enforces that at+ /// construction — an agent with no writer gets a non-durable vtable — so+ /// emitters need no `out == null` guard of their own.pub fn emit(self: EngineSink, io: Io, ev: EngineEvent) void {const reserve = self.vt.durable and engine_events.durable(ev);if (reserve and main_mod.json_mode) {@@ -91,12 +96,21 @@ pub fn tuiSink(a: *Agent) EngineSink {return .{ .ctx = a, .vt = &tui_vtable };}+/// The --json wire, for an agent that HAS one. A frontendless agent — a+/// pool-thread subagent (subagent_run.zig builds every child with+/// `.out = null`) or the ACP root (acp.zig nulls it while json_mode is on) —+/// gets the same emitter but a NON-durable vtable: jsonEmit drops every line+/// for it, and a durable sink would have reserved a sequence id for each of+/// those dropped lines, opening exactly the gap #330 promises cannot exist.+/// Structural, so no emitter has to re-derive the rule per call site.pub fn jsonSink(a: *Agent) EngineSink {- return .{ .ctx = a, .vt = &json_vtable };+ return .{ .ctx = a, .vt = if (a.out == null) &json_dropped_vtable else &json_vtable };}const tui_vtable: VTable = .{ .emit = tuiEmit, .durable = false };const json_vtable: VTable = .{ .emit = jsonEmit, .durable = true };+/// Same writer, nothing to write to: see jsonSink.+const json_dropped_vtable: VTable = .{ .emit = jsonEmit, .durable = false };/// Today's interactive rendering, relocated behind the event contract. Every/// branch is the old inline agent_stream.zig code path, gate for gate.@@ -440,6 +454,37 @@ test "JsonSink drops ask_user's bracket and a meta result without burning ids (s);}+test "a frontendless agent's wire sink burns no ids for the lines it cannot write (#330)" {+ const saved_json = main_mod.json_mode; // pin: see the dispatch-order test+ main_mod.json_mode = false;+ defer main_mod.json_mode = saved_json;+ protocol_seq.resetForTest();+ defer protocol_seq.resetForTest();+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);+ defer aw.deinit();+ var a = testAgent(&aw.writer);+ a.out = null; // a pool-thread subagent, or the ACP root: nowhere to write+ const s = jsonSink(&a);+ try std.testing.expect(!s.vt.durable); // the guarantee is structural, not per-call-site++ const input = try std.json.parseFromSliceLeaky(std.json.Value, arena_state.allocator(), "{\"path\":\"f\"}", .{});+ const call: engine_events.ToolInvocation = .{ .name = "read_file", .input = input };+ const done: engine_events.ToolOutcome = .{ .name = "read_file", .text = "hi", .is_error = false };+ s.emit(undefined, .{ .tool_call_announced = call });+ s.emit(undefined, .{ .tool_call_started = call });+ s.emit(undefined, .{ .tool_result = done });+ s.emit(undefined, .{ .tool_call_finished = done });+ s.emit(undefined, .{ .tool_rejected = .{ .name = "bash", .input = input, .reason = "budget", .message = "no" } });+ s.emit(undefined, .{ .text_delta = .{ .text = "hi" } });+ // Every one of those would have been a wire line for a rooted agent. With+ // no writer there is no line, so there must be no id either: a supervisor+ // reads a gap as lost data.+ try std.testing.expectEqualStrings("", aw.writer.buffered());+ try std.testing.expectEqual(@as(u64, 0), protocol_seq.current());+}+test "TuiSink draws the ⚙ and ✓ lines and nothing for the brackets (slice 1c)" {const saved_color = main_mod.use_color;main_mod.use_color = false;