graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(eval): a tier-1 eval set the harness can run before every push
Rach Pradhan9d71a983ac44
diff --git a/build.zig b/build.zigindex 0f7c2020..d3e67e8d 100644--- a/build.zig+++ b/build.zig@@ -65,12 +65,22 @@ pub fn build(b: *std.Build) void {run_step.dependOn(&run_cmd.step);// `zig build test` — unit tests live in src/main.zig `test "..." {}` blocks.+ // `-Dtest-filter="<text>"` (repeatable) narrows the run to the tests whose+ // name contains that text. scripts/eval-tier1.sh uses it to prove the named+ // goal/loop/todo invariants still run — a test whose module fell out of the+ // test root exists in the source but never executes.+ const test_filters = b.option(+ []const []const u8,+ "test-filter",+ "Only run tests whose name contains this text (repeatable)",+ ) orelse &[_][]const u8{};const unit_tests = b.addTest(.{.root_module = b.createModule(.{.root_source_file = b.path("src/main.zig"),.target = target,.optimize = optimize,}),+ .filters = test_filters,});unit_tests.root_module.addOptions("build_options", opts);unit_tests.root_module.addImport("zigzag", zigzag.module("zigzag"));diff --git a/scripts/eval-tier1.sh b/scripts/eval-tier1.shnew file mode 100755index 00000000..ca8a1077--- /dev/null+++ b/scripts/eval-tier1.sh@@ -0,0 +1,209 @@+#!/usr/bin/env bash+# Tier 1 of the internal eval set: every check here is deterministic, offline,+# and free. No provider calls, no network, no model in the loop. This is what+# the pre-push hook runs, so it has to stay honest and it has to stay fast+# (~30s warm on an M-series laptop).+#+# Tier 2 is the model-backed behavioral eval set (scripts/eval-tier2.py). It is+# deliberately NOT in the hook: it spends turns and it is slower.+#+# scripts/eval-tier1.sh run every check+# scripts/eval-tier1.sh --list show the check names+# scripts/eval-tier1.sh --only sdk run one check+#+set -uo pipefail++repo_root=$(git -C "$(dirname "${BASH_SOURCE[0]}")/.." rev-parse --show-toplevel)+cd "$repo_root"++CHECKS=(fmt lines reach build tests invariants sdk)++usage() {+ cat <<'EOF'+usage: scripts/eval-tier1.sh [--only <check>] [--list]++checks, in order:+ fmt zig fmt --check src build.zig+ lines scripts/check-zig-lines.sh (600-line ceiling, AGENTS.md)+ reach every file that declares tests is reachable from the test root+ build zig build+ tests zig build test, and the suite count never shrinks+ invariants the named goal/loop/todo tests actually ran, not just compiled+ sdk the committed SDKs match `graff --schema`+EOF+}++only=""+while (($#)); do+ case "$1" in+ --list) printf '%s\n' "${CHECKS[@]}"; exit 0 ;;+ --only) only=${2:-}; shift 2 || true ;;+ --only=*) only=${1#--only=}; shift ;;+ -h|--help) usage; exit 0 ;;+ *) printf 'eval-tier1: unknown argument %s\n\n' "$1" >&2; usage >&2; exit 2 ;;+ esac+done++if [[ -n "$only" ]]; then+ found=0+ for name in "${CHECKS[@]}"; do [[ $name == "$only" ]] && found=1; done+ if ((!found)); then+ printf 'eval-tier1: no check named %s (try --list)\n' "$only" >&2+ exit 2+ fi+fi++wanted() { [[ -z "$only" || "$only" == "$1" ]]; }++failed=()+started=$SECONDS++announce() { printf '\n\033[1m==> %s\033[0m %s\n' "$1" "$2"; }+record_fail() {+ failed+=("$1")+ printf '\n \033[31mFAILED\033[0m %s\n rerun just this check: scripts/eval-tier1.sh --only %s\n' "$1" "$1"+}++# --- fmt ---------------------------------------------------------------+if wanted fmt; then+ announce fmt "zig fmt --check src build.zig"+ if zig fmt --check src build.zig; then+ printf ' formatting is clean\n'+ else+ printf ' the files above are unformatted.\n fix: zig fmt src build.zig\n'+ record_fail fmt+ fi+fi++# --- lines -------------------------------------------------------------+if wanted lines; then+ announce lines "600-line ceiling on hand-written Zig (AGENTS.md)"+ if bash scripts/check-zig-lines.sh; then :; else+ printf ' fix: split the file above into focused sibling modules.\n'+ record_fail lines+ fi+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+ record_fail reach+ fi+fi++# --- build -------------------------------------------------------------+build_ok=1+if wanted build; then+ announce build "zig build"+ if zig build; then+ printf ' zig-out/bin/graff is current\n'+ else+ build_ok=0+ record_fail build+ fi+fi++# The suite count and the SDK gate both need a working compile; skip rather+# than report a second, derived failure.+skip_dependent() {+ printf '\n \033[33mskipped\033[0m %s (zig build failed above)\n' "$1"+}++# --- tests -------------------------------------------------------------+suite_count() {+ # `--summary all` prints "N/N tests passed" even on a fully cached run.+ sed -n 's/.*Build Summary:.*; \([0-9][0-9]*\)\/[0-9][0-9]* tests passed.*/\1/p' <<<"$1" | tail -1+}++if wanted tests; then+ if ((!build_ok)); then+ skip_dependent tests+ else+ announce tests "zig build test, and the suite count never shrinks"+ out=$(zig build test --summary all 2>&1)+ status=$?+ printf '%s\n' "$out" | tail -4+ if ((status != 0)); then+ printf ' fix: the failing test names are above; rerun one with\n'+ printf ' zig build test -Dtest-filter="<part of the name>"\n'+ record_fail tests+ else+ count=$(suite_count "$out")+ if [[ -z "$count" ]]; then+ printf ' FAIL could not read the test count out of the build summary\n'+ record_fail tests+ elif python3 scripts/eval/tier1_invariants.py count --observed "$count"; then :; else+ record_fail tests+ fi+ fi+ fi+fi++# --- invariants --------------------------------------------------------+if wanted invariants; then+ if ((!build_ok)); then+ skip_dependent invariants+ else+ announce invariants "the named goal/loop/todo tests actually ran"+ filters=()+ while IFS= read -r line; do [[ -n "$line" ]] && filters+=(-Dtest-filter="$line"); done \+ < <(python3 scripts/eval/tier1_invariants.py filters)+ # Anonymous `test {}` blocks ignore -Dtest-filter and always run, so measure+ # that floor with a filter that matches nothing and subtract it.+ floor_out=$(zig build test --summary all -Dtest-filter="__tier1_matches_nothing__" 2>&1)+ floor=$(suite_count "$floor_out")+ named_out=$(zig build test --summary all "${filters[@]}" 2>&1)+ status=$?+ named=$(suite_count "$named_out")+ if ((status != 0)); then+ printf '%s\n' "$named_out" | tail -6+ printf ' one of the named invariants is failing.\n'+ record_fail invariants+ elif [[ -z "$floor" || -z "$named" ]]; then+ printf ' FAIL could not read the filtered test counts\n'+ record_fail invariants+ else+ printf ' filtered run: %s tests, floor %s\n' "$named" "$floor"+ if python3 scripts/eval/tier1_invariants.py invariants --observed "$((named - floor))"; then :; else+ printf ' the required set is listed in scripts/eval/tier1-manifest.json:\n'+ python3 -c 'import json,sys; m=json.load(open("scripts/eval/tier1-manifest.json")); [print(f" {e[\"id\"]}: {e[\"test\"]}") for e in m["required_invariants"]]'+ record_fail invariants+ fi+ fi+ fi+fi++# --- sdk ---------------------------------------------------------------+if wanted sdk; then+ if ((!build_ok)); then+ skip_dependent sdk+ else+ announce sdk "the committed SDKs match \`graff --schema\`"+ if python3 sdk/generate.py --harness ./zig-out/bin/graff >/dev/null; then+ if git diff --exit-code --stat -- sdk/; then+ printf ' sdk/ is in sync with the schema\n'+ else+ printf '\n The generator just rewrote the files above, so the committed SDKs were\n'+ printf ' stale. They are regenerated in your working tree right now - review and\n'+ printf ' commit them:\n'+ printf ' git add sdk/ && git commit -m "chore(sdk): regenerate from the schema"\n'+ record_fail sdk+ fi+ else+ printf ' sdk/generate.py failed\n'+ record_fail sdk+ fi+ fi+fi++# --- verdict -----------------------------------------------------------+elapsed=$((SECONDS - started))+if ((${#failed[@]} == 0)); then+ printf '\n\033[32mtier 1 green\033[0m in %ss\n' "$elapsed"+ exit 0+fi+printf '\n\033[31mtier 1 red\033[0m in %ss - %d check(s) failed: %s\n' \+ "$elapsed" "${#failed[@]}" "${failed[*]}"+printf 'rerun one with: scripts/eval-tier1.sh --only <check>\n'+exit 1diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.jsonnew file mode 100644index 00000000..2f9e263b--- /dev/null+++ b/scripts/eval/tier1-manifest.json@@ -0,0 +1,69 @@+{+ "schema": "codegraff.eval.tier1.manifest.v1",+ "comment": [+ "Tier 1 of the internal eval set: the deterministic invariants the pre-push hook enforces.",+ "No network, no model calls. Tier 2 (model-backed behavior) lives in evals/ and is opt-in.",+ "test_count_baseline is a ratchet: the suite may grow, it may never shrink. A drop means a",+ "module stopped being referenced from the test root and its tests silently vanished."+ ],+ "test_roots": ["src/main.zig", "src/repl.zig"],+ "test_count_baseline": 449,+ "required_invariants": [+ {+ "id": "goal-epochs",+ "test": "epochs: nextEpoch clears the live goal AND every parked epoch; currentEpoch 0 without a goal",+ "why": "#318: a new goal inherited the previous goal's checklist and was born done."+ },+ {+ "id": "todo-preserve",+ "test": "a replace keeps omitted completed items and still drops omitted open ones",+ "why": "2896b32: a replace deleted completed items the model omitted, erasing finished work."+ },+ {+ "id": "todo-empty-write",+ "test": "a write with zero usable items is rejected untouched, never completion evidence (#318)",+ "why": "6300514: an empty todo_write wiped the checklist and read as completion."+ },+ {+ "id": "loop-expired",+ "test": "/loop: a passed wall-clock deadline stops as expired and flips nothing",+ "why": "6300514: a timed run past its deadline must stop as expired, not as accepted."+ },+ {+ "id": "loop-idle",+ "test": "/loop: a restored all-[x] list is idle, not accepted (#318)",+ "why": "#318: a leftover finished checklist ended a fresh /loop at iteration 1."+ },+ {+ "id": "goal-loop-one-run",+ "test": "/goal and /loop produce the same run; only /goal adopts the objective",+ "why": "010b9ad: /goal and /loop are one autonomous run; they must not drift apart."+ },+ {+ "id": "compaction-keeps-goal",+ "test": "compactionSnapshot: no live goal, no checklist, and a capped render (#318)",+ "why": "#318: compaction dropped the goal and its completed items mid-run."+ },+ {+ "id": "completion-gate",+ "test": "completionGate: open list refused once, no-checklist needs confirm, done list accepts, review exempt (#318)",+ "why": "#318: the model could claim completion over an unfinished checklist."+ },+ {+ "id": "child-deadline",+ "test": "childTaskPrompt: the same absolute deadline reaches every child, minus a margin",+ "why": "d33c4a4: a timed /loop must hand its deadline down, or children outlive the run."+ }+ ],+ "docs_only_paths": [+ "*.md",+ "docs/*",+ "plans/*",+ "social/*",+ "socials/*",+ "assets/*",+ "benchmarks/*.png",+ "*.png",+ "LICENSE"+ ]+}diff --git a/scripts/eval/tier1_invariants.py b/scripts/eval/tier1_invariants.pynew file mode 100755index 00000000..a7f002b0--- /dev/null+++ b/scripts/eval/tier1_invariants.py@@ -0,0 +1,205 @@+#!/usr/bin/env python3+"""Static and count-based halves of the tier-1 eval set.++Two things `zig build test` alone cannot tell you:++ 1. Whether a module's tests are *reachable* from the test root. Zig only runs+ the tests in files the root pulls in; a split-out module that nobody+ references compiles to nothing and the suite still reports green. That is+ how src/main_tests.zig sat dead for months.+ 2. Whether the invariants this repo actually regressed on are still covered.+ A named test can be deleted, renamed, or orphaned and the total barely+ moves.++Subcommands (all offline, all under a second):++ static import-graph reachability + required-invariant presence+ filters print one -Dtest-filter value per line, for the shell+ count --observed N the total suite count may grow, never shrink+ invariants --observed N the filtered run must have run exactly the required set+"""++from __future__ import annotations++import argparse+import fnmatch+import json+import pathlib+import re+import sys++REPO = pathlib.Path(__file__).resolve().parents[2]+MANIFEST = REPO / "scripts" / "eval" / "tier1-manifest.json"+IMPORT = re.compile(r'@import\("([^"]+\.zig)"\)')+TEST_DECL = re.compile(r'(?m)^test[ {]')+TEST_NAME = re.compile(r'(?m)^test "((?:[^"\\]|\\.)*)"')+++def load_manifest() -> dict:+ try:+ return json.loads(MANIFEST.read_text(encoding="utf-8"))+ except (OSError, ValueError) as exc:+ sys.exit(f"tier1: cannot read {MANIFEST}: {exc}")+++def reachable_files(roots: list[str]) -> set[pathlib.Path]:+ """Every .zig file the test roots pull in, transitively."""+ seen: set[pathlib.Path] = set()+ stack = [REPO / root for root in roots]+ while stack:+ current = stack.pop().resolve()+ if current in seen or not current.is_file():+ continue+ seen.add(current)+ text = current.read_text(encoding="utf-8", errors="replace")+ for target in IMPORT.findall(text):+ stack.append(current.parent / target)+ return seen+++def files_with_tests() -> list[pathlib.Path]:+ found = []+ for path in sorted((REPO / "src").rglob("*.zig")):+ if TEST_DECL.search(path.read_text(encoding="utf-8", errors="replace")):+ found.append(path.resolve())+ return found+++def all_test_names() -> dict[str, list[pathlib.Path]]:+ names: dict[str, list[pathlib.Path]] = {}+ for path in sorted((REPO / "src").rglob("*.zig")):+ text = path.read_text(encoding="utf-8", errors="replace")+ for name in TEST_NAME.findall(text):+ names.setdefault(name, []).append(path)+ return names+++def check_static(manifest: dict) -> list[str]:+ failures: list[str] = []+ reachable = reachable_files(manifest["test_roots"])++ orphans = [p for p in files_with_tests() if p not in reachable]+ if orphans:+ listing = "\n".join(f" src/{p.relative_to(REPO / 'src')}" for p in orphans)+ failures.append(+ "reachability: these files declare tests that never run - nothing in\n"+ f" {', '.join(manifest['test_roots'])} imports them:\n{listing}\n"+ " fix: reference the module from src/main.zig's `test {}` block\n"+ " (`_ = @import(\"x.zig\");`), or delete the dead file."+ )++ known = all_test_names()+ required = manifest["required_invariants"]+ for entry in required:+ name = entry["test"]+ where = known.get(name, [])+ if not where:+ failures.append(+ f"invariant {entry['id']}: no test named\n \"{name}\"\n"+ f" it guards: {entry['why']}\n"+ " fix: restore the test, or drop the entry from"+ " scripts/eval/tier1-manifest.json with a reason."+ )+ elif len(where) > 1:+ listing = ", ".join(str(p.relative_to(REPO)) for p in where)+ failures.append(+ f"invariant {entry['id']}: the name is declared {len(where)} times"+ f" ({listing});\n tier 1 counts filter hits, so the name must be unique."+ )++ # The filtered run below counts hits, so no required name may be a prefix or+ # substring of another test's name - that would inflate the count and hide a+ # genuinely missing invariant.+ for entry in required:+ name = entry["test"]+ collisions = [other for other in known if other != name and name in other]+ if collisions:+ failures.append(+ f"invariant {entry['id']}: its name is a substring of"+ f" {len(collisions)} other test name(s), e.g.\n \"{collisions[0]}\"\n"+ " pick a distinct name so the -Dtest-filter hit count stays exact."+ )+ return failures+++def docs_only(paths: list[str], manifest: dict) -> bool:+ patterns = manifest.get("docs_only_paths", [])+ if not paths:+ return True+ return all(any(fnmatch.fnmatch(p, pat) for pat in patterns) for p in paths)+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ sub = parser.add_subparsers(dest="cmd", required=True)+ sub.add_parser("static")+ sub.add_parser("filters")+ count = sub.add_parser("count")+ count.add_argument("--observed", type=int, required=True)+ inv = sub.add_parser("invariants")+ inv.add_argument("--observed", type=int, required=True)+ skip = sub.add_parser("docs-only")+ skip.add_argument("paths", nargs="*")+ args = parser.parse_args()+ manifest = load_manifest()++ if args.cmd == "filters":+ for entry in manifest["required_invariants"]:+ print(entry["test"])+ return++ if args.cmd == "docs-only":+ sys.exit(0 if docs_only(args.paths, manifest) else 1)++ if args.cmd == "static":+ failures = check_static(manifest)+ for failure in failures:+ print(f" FAIL {failure}", file=sys.stderr)+ if failures:+ sys.exit(1)+ print(+ f" every test file is reachable from the test root;"+ f" all {len(manifest['required_invariants'])} named invariants present"+ )+ return++ if args.cmd == "count":+ baseline = int(manifest["test_count_baseline"])+ if args.observed < baseline:+ print(+ f" FAIL test count dropped: {args.observed} ran, baseline is {baseline}.\n"+ " Tests do not disappear on their own. Either a module stopped being\n"+ " referenced from src/main.zig's `test {}` block (its tests now compile\n"+ " to nothing and the suite still reports green), or tests were removed.\n"+ " fix: restore them, or lower test_count_baseline in\n"+ " scripts/eval/tier1-manifest.json in the same commit, with a reason.",+ file=sys.stderr,+ )+ sys.exit(1)+ if args.observed > baseline:+ print(+ f" {args.observed} tests ran (baseline {baseline}) - "+ "bump test_count_baseline in scripts/eval/tier1-manifest.json to ratchet it up"+ )+ else:+ print(f" {args.observed} tests ran, matching the baseline")+ return++ if args.cmd == "invariants":+ expected = len(manifest["required_invariants"])+ if args.observed != expected:+ print(+ f" FAIL {args.observed} of {expected} named invariants ran under"+ " -Dtest-filter.\n"+ " A named test exists in the source but did not run, which means the\n"+ " module holding it is no longer pulled into the test root.\n"+ " fix: `scripts/eval-tier1.sh --only invariants` names the set;\n"+ " reference the module from src/main.zig's `test {}` block.",+ file=sys.stderr,+ )+ sys.exit(1)+ print(f" all {expected} named goal/loop/todo invariants ran")+++if __name__ == "__main__":+ main()