graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: restore /image and /doctor, and wake 37 tests that never ran
justrach4d958c6bd248
diff --git a/scripts/eval-tier1.sh b/scripts/eval-tier1.shindex 770f0dc7..1aea759d 100644--- a/scripts/eval-tier1.sh+++ b/scripts/eval-tier1.sh@@ -86,8 +86,13 @@ fi# --- reach -------------------------------------------------------------if wanted reach; then- announce reach "tests declared in src/ are reachable from the test root"- if python3 scripts/eval/tier1_invariants.py static; then :; else+ announce reach "every declared test is actually COMPILED IN, not just imported"+ # tier1_invariants.py static modelled reachability as a textual @import graph,+ # which over-approximates what Zig analyses: it printed "every test file is+ # reachable" and exited 0 while 37 tests in 12 files were silently skipped.+ # test_reachability.py diffs declared names against the compiled binary+ # instead, so it cannot be fooled by an import Zig never follows.+ if python3 scripts/eval/test_reachability.py; then :; elserecord_fail reachfifidiff --git a/scripts/eval/test_reachability.py b/scripts/eval/test_reachability.pynew file mode 100644index 00000000..036a7d0b--- /dev/null+++ b/scripts/eval/test_reachability.py@@ -0,0 +1,99 @@+#!/usr/bin/env python3+"""Fail if any declared Zig test is not actually compiled into the test binary.++Zig only compiles a `test` block when its file is reachable from the test root.+A module nothing imports has its tests SILENTLY SKIPPED: they sit in the source+reading as coverage and never run. That is not hypothetical - 12 files and 37+tests were in exactly that state, including the whole promotion ladder in+learn_tournament.zig, and one of them was already stale and failing the moment+it was wired back in.++Why this check and not the previous one: tier1_invariants.py modelled+reachability as a TEXTUAL `@import` graph over the source. That over-approximates+what Zig actually analyses, so it printed "every test file is reachable from the+test root" and exited 0 while 37 tests were dead. This compares two ground+truths instead - the names declared in src/*.zig, and the names present in the+compiled binary - so it cannot be fooled by an import Zig never follows.++Usage: python3 scripts/eval/test_reachability.py [--verbose]+Exit 0 when every declared test is compiled in; 1 otherwise.+"""++from __future__ import annotations++import pathlib+import re+import subprocess+import sys++ROOT = pathlib.Path(__file__).resolve().parents[2]+SRC = ROOT / "src"+CACHE = ROOT / ".zig-cache" / "o"++TEST_NAME = re.compile(r'^test "((?:[^"\\]|\\.)*)"', re.M)+++def declared_tests() -> dict[str, str]:+ """Every `test "name"` in src/*.zig, mapped to its file."""+ out: dict[str, str] = {}+ for path in sorted(SRC.glob("*.zig")):+ for match in TEST_NAME.finditer(path.read_text(encoding="utf-8")):+ # The source carries Zig escapes; the binary carries the resolved+ # bytes. Unescape so a name containing a quote still matches.+ name = match.group(1).replace('\\"', '"').replace("\\\\", "\\")+ out[name] = path.name+ return out+++def newest_test_binary() -> pathlib.Path | None:+ candidates = [p for p in CACHE.glob("*/test") if p.is_file()]+ return max(candidates, key=lambda p: p.stat().st_mtime) if candidates else None+++def main() -> int:+ verbose = "--verbose" in sys.argv++ # A stale binary would give a false verdict in either direction, so build+ # first and let a compile failure surface as a compile failure.+ build = subprocess.run(+ ["zig", "build", "test"], cwd=ROOT, capture_output=True, text=True+ )+ if build.returncode != 0:+ sys.stderr.write("zig build test failed; reachability not checked\n")+ sys.stderr.write(build.stderr[-2000:])+ return 1++ binary = newest_test_binary()+ if binary is None:+ sys.stderr.write("no compiled test binary found under .zig-cache/o\n")+ return 1++ # Raw bytes, NOT `strings`: that tool only extracts ASCII runs, so every+ # test name containing an em dash, an arrow or a quote read as missing and+ # the guard cried wolf on six perfectly live tests. Searching the bytes for+ # the UTF-8 encoding of each name has no such blind spot.+ blob = binary.read_bytes()++ declared = declared_tests()+ missing: dict[str, list[str]] = {}+ for name, file in declared.items():+ if name.encode("utf-8") not in blob:+ missing.setdefault(file, []).append(name)++ if not missing:+ print(f" all {len(declared)} declared tests are compiled in ({binary.parent.name})")+ return 0++ total = sum(len(v) for v in missing.values())+ print(f" {total} declared test(s) in {len(missing)} file(s) are NOT compiled in:")+ for file in sorted(missing):+ print(f" {file} ({len(missing[file])})")+ if verbose:+ for name in missing[file]:+ print(f" {name}")+ print(" add a reference in src/test_hooks.zig so Zig analyses the module")+ return 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.jsonindex 67292fae..fd6f7953 100644--- a/scripts/eval/tier1-manifest.json+++ b/scripts/eval/tier1-manifest.json@@ -10,7 +10,7 @@"src/main.zig","src/repl.zig"],- "test_count_baseline": 576,+ "test_count_baseline": 615,"required_invariants": [{"id": "goal-epochs",diff --git a/src/command_catalog.zig b/src/command_catalog.zigindex 235e286b..795eaa42 100644--- a/src/command_catalog.zig+++ b/src/command_catalog.zig@@ -76,12 +76,8 @@ pub const names = blk: {break :blk arr;};-test { // #321: /doctor's rules live in doctor.zig, which nothing else references- // yet - and a module with no test-root reference has its tests silently- // skipped. Hung here beside the catalog entry that introduces the command;- // it belongs in main.zig's test block once /doctor is dispatched.- _ = @import("doctor.zig");-}+// /doctor is dispatched from commands_misc.tryHandle now, so doctor.zig is+// reached through the production import graph and needs no hook here.test "catalog is well-formed and names track commands" {try std.testing.expectEqual(commands.len, names.len);diff --git a/src/commands_misc.zig b/src/commands_misc.zigindex eb1e0dcb..6cee17ee 100644--- a/src/commands_misc.zig+++ b/src/commands_misc.zig@@ -12,6 +12,7 @@ const main_mod = @import("main.zig");const provider_mod = @import("provider.zig");const agent_mod = @import("agent.zig");const util = @import("util.zig");+const doctor = @import("doctor.zig");const Agent = agent_mod.Agent;const Keys = provider_mod.Keys;const utf8Prefix = util.utf8Prefix;@@ -134,6 +135,14 @@ fn showModelsHealth(root: *Agent, keys: *Keys, arena: Allocator, out: *Io.Writer/// to handleRest() for the unknown-command/help terminal stage.pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {if (try commands_privacy.tryHandle(root, line, out)) return true;+ // #321: doctor.zig shipped with a catalog entry but no dispatch, so /doctor+ // was advertised in /help and the `/` menu while answering "unknown command".+ if (std.mem.eql(u8, line, "/doctor")) {+ const checks = try doctor.run(arena, doctor.snapshot(root, util.unixMs(root.io)));+ try out.writeAll(try doctor.render(arena, checks));+ try out.flush();+ return true;+ }if (std.mem.eql(u8, line, "/todo")) {const epoch = goal_state.currentEpoch(root.goal);try out.print("{s}\n", .{root.renderTodos(epoch)});diff --git a/src/commands_model.zig b/src/commands_model.zigindex bd16f944..6227b5df 100644--- a/src/commands_model.zig+++ b/src/commands_model.zig@@ -522,7 +522,12 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,try out.flush();return true;}- if (std.mem.eql(u8, line, "/images")) {+ // startsWith, NOT eql: this branch owns BOTH `/images` (the URL opener,+ // dispatched on the exact match just below) and `/image <path>` (staging an+ // attachment). The #103 extraction overwrote this outer guard with a copy of+ // the inner exact-match, which made every `/image` line below unreachable -+ // the command stayed in the catalog and /help while answering "unknown".+ if (std.mem.startsWith(u8, line, "/image")) {if (std.mem.eql(u8, line, "/images")) return images_command.run(root, out);const path = std.mem.trim(u8, line["/image".len..], " \t");if (path.len == 0) {diff --git a/src/learn_tournament.zig b/src/learn_tournament.zigindex 37f7dd9e..093636ab 100644--- a/src/learn_tournament.zig+++ b/src/learn_tournament.zig@@ -251,9 +251,16 @@ test "null, parent-identical, and duplicate candidates do not contend" {test "only the primary winner can become finally eligible" {const parent = "1111111111111111111111111111111111111111111111111111111111111111";+ // Index 1 must win on a signal primaryOutranks actually reads. This test+ // was dead (learn_tournament.zig had no test-root reference) and had gone+ // stale: it gave index 1 the larger parent-relative DELTA, which stopped+ // choosing winners when the ranking became correctness-then-cost - see the+ // rationale at the top of primaryOutranks and the tie case in "primary+ // winner is correctness-first...". Cost is what separates them now, so+ // index 1 is the cheaper one.var candidates = [_]eval.CandidateRecord{- fakeCandidate("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", fakeComparison(20, 10, 5, 10, true, "eligible")),- fakeCandidate("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", fakeComparison(30, 10, 5, 20, true, "eligible")),+ fakeCandidate("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", fakeComparison(20, 10, 5, 20, true, "eligible")),+ fakeCandidate("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", fakeComparison(30, 10, 5, 10, true, "eligible")),};candidates[0].eligible = true;candidates[1].holdout = fakeComparison(5, 5, 10, 5, true, "eligible");diff --git a/src/main.zig b/src/main.zigindex 80d8df31..95724917 100644--- a/src/main.zig+++ b/src/main.zig@@ -588,7 +588,7 @@ test { // pull in tests from imported modules (mcp.zig)// A module whose tests must run needs an explicit reference here: a// plain @import elsewhere (or a type-only alias) is NOT enough — it// compiles to nothing; scripts/eval-tier1.sh --only reach catches one.- _ = @import("scoring_slot_test.zig");+ _ = @import("test_hooks.zig"); // unreached modules; their tests were silently skipped_ = @import("learn_delete.zig"); // #303: its tests were dead until listed here_ = @import("readline_history.zig");_ = @import("goal_pacing_autonomous_test.zig");diff --git a/src/test_hooks.zig b/src/test_hooks.zignew file mode 100644index 00000000..2e1a7a03--- /dev/null+++ b/src/test_hooks.zig@@ -0,0 +1,59 @@+//! Test-root references for modules the production import graph does not reach+//! from main.zig.+//!+//! Zig only compiles a `test` block if its file is reachable from the test+//! root. A module that nothing imports has its tests SILENTLY SKIPPED - they+//! still appear in the source, still read as coverage, and never run. That is+//! not hypothetical here: 12 files (37 tests) were in exactly that state,+//! including the whole of learn_tournament.zig - the ranking ladder that+//! decides which learned genome is promoted into the ROOT system prompt, with+//! cases like "critical child safety outranks higher pass rate" and "holdout+//! cannot rescue a primary rejection". Every one could have been broken with+//! the suite, the tier-1 gate and CI all green.+//!+//! Hooks live here rather than in main.zig's `test {}` block because that file+//! sits at the 600-line cap, so the natural home for a one-line fix has no room+//! for one - which is part of how the gap opened.+//!+//! scripts/eval/test_reachability.py is the guard: it diffs declared test names+//! against the names actually present in the compiled test binary, so a file+//! that drops out of the graph fails the build instead of going quiet. Adding a+//! module here is what makes that guard pass; do not delete a line without+//! checking the guard still does.++// Learning / DGM promotion pipeline.+const learn_holdout = @import("learn_holdout.zig");+const learn_receipt = @import("learn_receipt.zig");+const learn_report = @import("learn_report.zig");+const learn_run = @import("learn_run.zig");+const learn_submit = @import("learn_submit.zig");+const learn_tournament = @import("learn_tournament.zig");+const recipe = @import("recipe.zig");++// `graff repl` (zigzag TUI chat).+const repl = @import("repl.zig");+const repl_markdown = @import("repl_markdown.zig");+const repl_parser = @import("repl_parser.zig");++// Routing + worker selection.+const router_config = @import("router_config.zig");+const subagent_selection = @import("subagent_selection.zig");++// Moved off main.zig, which is at the 600-line cap.+const scoring_slot_test = @import("scoring_slot_test.zig");++test {+ _ = learn_holdout;+ _ = learn_receipt;+ _ = learn_report;+ _ = learn_run;+ _ = learn_submit;+ _ = learn_tournament;+ _ = recipe;+ _ = repl;+ _ = repl_markdown;+ _ = repl_parser;+ _ = router_config;+ _ = subagent_selection;+ _ = scoring_slot_test;+}