Skip to content

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

Python

fix(test): a green `zig build test` no longer prints a step failure

Rach Pradhan39396eaf0ff0
diff --git a/src/brief_diversity.zig b/src/brief_diversity.zig
index f67278cd..a8bb5535 100644
--- a/src/brief_diversity.zig
+++ b/src/brief_diversity.zig
@@ -56,6 +56,7 @@ const Allocator = std.mem.Allocator;
const trace = @import("trace.zig");
const util = @import("util.zig");
const fleet = @import("fleet.zig"); // resolveOverride: the shared system_prompt/agent resolution
+const tick_gate = @import("tick_gate.zig"); // #tui-tick/#444: activity lines land at a line boundary, and never in a test binary
/// Shingle width. 3 is the standard near-duplicate-detection default and it
/// is what the fixtures below were tuned against; 2 drifts toward unigram
@@ -455,7 +456,7 @@ pub fn check(arena: Allocator, tracer: ?*trace.Tracer, phase: []const u8, briefs
// Its own prefix rather than the caller's: this fires from the workflow
// phase loop AND from a bare sibling-spawn batch, where "[workflow]"
// would name a workflow that never ran.
- std.debug.print(" [diversity] {s}\n", .{text});
+ tick_gate.workerPrint(" [diversity] {s}\n", .{text});
return text;
}
diff --git a/src/tick_gate.zig b/src/tick_gate.zig
index b5d97b30..28e69eea 100644
--- a/src/tick_gate.zig
+++ b/src/tick_gate.zig
@@ -30,8 +30,28 @@
//! direct stderr write and the gate stays out of the way.
const std = @import("std");
+const builtin = @import("builtin");
const root = @import("main.zig"); // live json_mode toggle
+/// #444. A test binary has no terminal for a worker line to reach, and stderr
+/// there is not free: zig's build runner routes a Run step through its ERROR
+/// printer whenever `result_stderr` is non-empty — even on a green exit 0 — so
+/// a passing suite that says anything renders a step-failure tree and a red
+/// `failed command: …/test --listen=-`. That output read as a failure for
+/// months (the line people latched onto was an unrelated negative control's
+/// expected diagnostic, which merely sat in the same stderr buffer).
+///
+/// So: the gate's accounting still runs under test — offers are held, drops are
+/// counted, released lines are still counted — only the physical write is
+/// elided, and elided at comptime, so no test build can reach a stderr write
+/// through this module.
+const emit_to_stderr = !builtin.is_test;
+
+fn writeLine(text: []const u8) void {
+ if (!emit_to_stderr) return;
+ std.debug.print("{s}", .{text});
+}
+
/// Held lines. Small on purpose: a fleet that outruns the stream should show
/// its newest activity, not replay a backlog once the line finally ends.
pub const max_pending = 6;
@@ -116,11 +136,30 @@ fn unlock() void {
/// A pool-thread worker wants `text` (whole, newline-terminated lines) on the
/// terminal: printed now at a foreground line boundary, held otherwise.
pub fn workerLine(text: []const u8) void {
- if (root.json_mode) return std.debug.print("{s}", .{text});
+ if (root.json_mode) return writeLine(text);
lock();
const held = g_gate.offer(text);
unlock();
- if (!held) std.debug.print("{s}", .{text});
+ if (!held) writeLine(text);
+}
+
+/// workerLine for a format string. The activity lines subsystems print
+/// directly (" [workflow] phase 1/2: …", " [diversity] …") are exactly the
+/// class this module exists for — see the module doc — but they reached stderr
+/// through a raw std.debug.print, so they neither honoured the line-boundary
+/// gate nor could be elided in a test binary (#444). Same fixed slot and same
+/// "a cut line still ends its row" repair as agent_output.say.
+pub fn workerPrint(comptime fmt: []const u8, args: anytype) void {
+ var buf: [slot_bytes]u8 = undefined;
+ var sink = std.Io.Writer.fixed(&buf);
+ const fit = if (sink.print(fmt, args)) |_| true else |_| false;
+ var line = sink.buffered();
+ if (!fit or line.len == 0 or line[line.len - 1] != '\n') {
+ const at: usize = @min(line.len, buf.len - 1);
+ buf[at] = '\n';
+ line = buf[0 .. at + 1];
+ }
+ workerLine(line);
}
/// Publish the foreground stream's position and release everything held once it
@@ -155,20 +194,41 @@ fn release() usize {
const dropped = if (took == null) g_gate.takeDropped() else 0;
unlock();
if (took) |n| {
- std.debug.print("{s}", .{buf[0..n]});
+ writeLine(buf[0..n]);
for (buf[0..n]) |c| {
if (c == '\n') lines += 1;
}
continue;
}
if (dropped > 0) {
- std.debug.print(" [·] {d} subagent line(s) dropped while the answer streamed\n", .{dropped});
+ var note: [64]u8 = undefined;
+ writeLine(std.fmt.bufPrint(&note, " [·] {d} subagent line(s) dropped while the answer streamed\n", .{dropped}) catch " [·] subagent line(s) dropped while the answer streamed\n");
lines += 1;
}
return lines;
}
}
+test "#444: the worker-line write is elided at comptime in a test binary" {
+ // The whole point of the gate under test is the accounting, not the write.
+ // If this ever flips true, a passing `zig build test` starts printing a
+ // step-failure tree and `failed command: …` on a green exit 0 again,
+ // because zig's build runner error-prints any Run step with stderr.
+ try std.testing.expect(!emit_to_stderr);
+ comptime std.debug.assert(!emit_to_stderr);
+ // The bookkeeping is untouched: an offer at a line boundary is still
+ // refused (the caller "prints"), and a held one is still retrievable.
+ hold();
+ defer _ = setLineStart(true);
+ workerLine(" [w] held under test\n");
+ var buf: [slot_bytes]u8 = undefined;
+ lock();
+ const n = g_gate.take(&buf);
+ unlock();
+ try std.testing.expect(n != null);
+ try std.testing.expectEqualStrings(" [w] held under test\n", buf[0..n.?]);
+}
+
test "tick gate: a tick offered mid-line waits for the newline (#tui-tick)" {
var gate: Gate = .{};
var buf: [slot_bytes]u8 = undefined;
diff --git a/src/tool_schema_tests.zig b/src/tool_schema_tests.zig
index 8decadc1..30ebea0a 100644
--- a/src/tool_schema_tests.zig
+++ b/src/tool_schema_tests.zig
@@ -64,9 +64,19 @@ fn forEachServedSchema(arena: Allocator, catalog: []const u8, check: *const fn (
}
}
+/// #444: the diagnostic below is for a REAL offender, where stderr is exactly
+/// what you want. The negative control at the bottom of the next test deals in
+/// a deliberately bad schema, and its print landed on every green run — where
+/// zig's build runner error-prints any Run step whose stderr is non-empty, so a
+/// passing suite rendered a step-failure tree and `failed command: …/test`.
+/// Reading that as a failure cost real time. Muted for the control only; the
+/// assertion it makes is unchanged.
+var report_offenders: bool = true;
+
fn assertClean(name: []const u8, sch: Value) anyerror!void {
if (combinatorAnywhere(sch)) |key| {
- std.debug.print("\ntool '{s}' has a JSON Schema '{s}' — Anthropic rejects the whole request over a top-level one\n", .{ name, key });
+ if (report_offenders)
+ std.debug.print("\ntool '{s}' has a JSON Schema '{s}' — Anthropic rejects the whole request over a top-level one\n", .{ name, key });
return error.ToolSchemaHasCombinator;
}
}
@@ -100,10 +110,15 @@ test "no built-in tool schema carries oneOf/allOf/anyOf — the wire rejection t
}
}
- // The guard has to be able to fail, or it proves nothing.
+ // The guard has to be able to fail, or it proves nothing. Silently (#444):
+ // this is the ONE call to assertClean that is meant to fail, so its
+ // diagnostic is noise on a green run — and a green run's stderr is what
+ // zig's build runner error-prints.
const bad = try std.json.parseFromSliceLeaky(Value, arena,
\\{"type":"object","properties":{},"anyOf":[{"required":["a"]},{"required":["b"]}]}
, .{});
+ report_offenders = false;
+ defer report_offenders = true;
try testing.expectError(error.ToolSchemaHasCombinator, assertClean("fake", bad));
}
diff --git a/src/workflow.zig b/src/workflow.zig
index 1df97948..beb3d9f0 100644
--- a/src/workflow.zig
+++ b/src/workflow.zig
@@ -61,6 +61,7 @@ const report_anchors = @import("report_anchors.zig");
const phase_budget = @import("phase_budget.zig");
const shapes = @import("shapes.zig");
const pipeline_mode = @import("workflow_pipeline.zig");
+const tick_gate = @import("tick_gate.zig"); // #tui-tick/#444: activity lines land at a line boundary, and never in a test binary
// Pipeline mode moved to workflow_pipeline.zig (600-line cap); aliased back so
// workflow_test.zig and every other caller still reach it here.
@@ -295,13 +296,13 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {
// its `when` never gates; a skipped phase leaves {{prev}} untouched, so a
// skipped final phase just returns the prior phase's results (early-exit).
if (phase_no > 1) if (phase.get("when")) |wv| if (wv == .string and !gateAllows(prev_results, wv.string)) {
- std.debug.print(" [workflow] phase {d}/{d}: {s} — SKIPPED (when \"{s}\" absent)\n", .{ phase_no, phases.len, title, wv.string });
+ tick_gate.workerPrint(" [workflow] phase {d}/{d}: {s} — SKIPPED (when \"{s}\" absent)\n", .{ phase_no, phases.len, title, wv.string });
wfp.phase(ctx.io, arena, run_id, phase_no, phases.len, title, "skipped", tasks.len); // #63
tallies[phase_no - 1] = .{ .phase_no = phase_no, .total_phases = phases.len, .title = title, .ok = 0, .total = tasks.len, .retried = 0, .skipped_when = wv.string };
phases_ran = phase_no;
continue;
};
- std.debug.print(" [workflow] phase {d}/{d}: {s} ({d} task(s))\n", .{ phase_no, phases.len, title, tasks.len });
+ tick_gate.workerPrint(" [workflow] phase {d}/{d}: {s} ({d} task(s))\n", .{ phase_no, phases.len, title, tasks.len });
wfp.phase(ctx.io, arena, run_id, phase_no, phases.len, title, "started", tasks.len); // #63
// Resolve prompts: substitute or append the previous phase results.
diff --git a/src/workflow_pipeline.zig b/src/workflow_pipeline.zig
index c6fe4c6a..8eb925e9 100644
--- a/src/workflow_pipeline.zig
+++ b/src/workflow_pipeline.zig
@@ -43,6 +43,7 @@ const wfp = @import("workflow_progress.zig");
const escalation = @import("escalation.zig");
const phase_budget = @import("phase_budget.zig");
const workflow = @import("workflow.zig");
+const tick_gate = @import("tick_gate.zig"); // #tui-tick/#444: activity lines land at a line boundary, and never in a test binary
const max_pipeline_items = 8;
const max_pipeline_stages = 5;
@@ -271,7 +272,7 @@ pub fn run(ctx: ToolCtx, pv: Value, outer_context: []const u8) !ToolOutput {
}
const wf_start = Io.Timestamp.now(ctx.io, .awake);
- std.debug.print(" [workflow] pipeline: {d} item(s) × {d} stage(s), no barrier\n", .{ items.len, stages.len });
+ tick_gate.workerPrint(" [workflow] pipeline: {d} item(s) × {d} stage(s), no barrier\n", .{ items.len, stages.len });
// #63 — same fact, as state: phase_index 0 is the run-level event, since a
// pipeline has stages rather than phases. Per-stage events would have to be
// threaded into pipelineChain (one chain per item, on its own pool thread);