graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
chore(eval): promote the golden byte-identity harness into the repo
Rach Pradhan7fa1cb0264c7
diff --git a/scripts/eval/golden/.gitignore b/scripts/eval/golden/.gitignorenew file mode 100644index 00000000..2fcb51f7--- /dev/null+++ b/scripts/eval/golden/.gitignore@@ -0,0 +1,2 @@+runs/+__pycache__/diff --git a/scripts/eval/golden/README.md b/scripts/eval/golden/README.mdnew file mode 100644index 00000000..7e36b3b2--- /dev/null+++ b/scripts/eval/golden/README.md@@ -0,0 +1,144 @@+# Golden byte-identity harness++Proves that a refactor changed no rendered output. Two graff binaries drive the+same real-PTY session against the same scripted model at three pane widths, and+the exact bytes the terminal received are compared. A change that claims to be+behavior-preserving has to produce an empty diff.++This exists because "I only moved code" is the easiest claim in a refactor to+make and the hardest to check by reading. It was built for #429's engine output+inversion, where rendering moved out of engine files and behind a sink, and the+only acceptance bar that meant anything was "the terminal sees the same bytes".++## Running it++Build both binaries, then:++```sh+export GRAFF_EVAL_BEFORE=/path/to/base-worktree/zig-out/bin/graff+export GRAFF_EVAL_AFTER=/path/to/change-worktree/zig-out/bin/graff++python3 run_golden.py # self-check, capture both arms, diff+python3 run_golden.py --arm before # capture one arm only+python3 run_golden.py --diff-only # re-compare existing captures+python3 run_golden.py --skip-self-check # not recommended; see below+```++Exit status is 0 only when the self-check passed *and* the two arms are+byte-identical, so it works as a gate. Optional: `GRAFF_EVAL_MODEL` (default+`lmstudio`), `GRAFF_EVAL_PORT` (default 1234, the scripted model's port).++Captures land in `runs/<arm>/` and are gitignored: they are outputs, not+instrument. Only `run_golden.py` and this file are committed.++## The determinism self-check is not optional++Before comparing the arms, the harness captures the **same** binary twice and+requires those two runs to agree. If they do not, a before/after diff proves+nothing — you cannot tell a real regression from a flaky capture — so the run+stops there rather than reporting a difference it cannot attribute.++`--skip-self-check` exists for iterating on the instrument itself. Do not use+it to produce evidence.++## The capture-window race (read this before adding a window)++Each window is `raw[cursor:]`, with `cursor` taken just before sending input.+The obvious way to write that is:++```python+s.wait_for_literal("] ›")+cursor = len(s.raw) # WRONG+```++`wait_for_literal` returns as soon as the pattern is *visible*, which is not+the same moment as "the terminal has gone quiet". readline emits its setup+bytes — `ESC[?2004h` (bracketed paste on) and `ESC[6n` (cursor-position probe),+12 bytes — immediately after the prompt. Whether those bytes have been pumped+into `raw` when `cursor` is read is a race with the child process.++The failure mode is nasty because it is *stable per run*: two captures of one+binary can agree, and then the other arm lands on the other side of the race+and the diff shows a 12-byte prefix with byte-identical content after it. That+looks exactly like a real difference until you diff the remainder.++The fix, applied at every window here: **settle before opening a window.**++```python+s.wait_for_literal("] ›")+s.pump_for(1.0) # let the terminal go quiet+cursor = len(s.raw) # now the boundary is deterministic+```++Every step in `STEPS` carries a `settle` for this reason. If you add a window,+give it one; if a new golden shows a leading- or trailing-byte diff with an+identical middle, suspect this before suspecting the code.++## What is captured++Three pane widths, chosen to straddle the #209 status-line width budget, and+seven steps each — six of which capture a window:++| width | what it forces |+|---|---|+| `wide` (160) | every status-line segment survives the budget |+| `narrow` (60) | low-priority metadata (cwd, context meter) is dropped |+| `tiny` (34) | the pathological pane: only the badges that disambiguate the cursor |++| window | surface |+|---|---|+| `01-prompt-clean` | the status line before any usage exists (no meter, no cache badge) |+| *(uncaptured turn)* | one real model turn, to populate the meters |+| `02-skills-list` | the `/skills` catalog, plus a status line **with** context meter and cache badge |+| `03-skills-remove` | `/skills remove` success line |+| `04-skills-after-remove` | the catalog with the skill gone |+| `05-skills-add` | `/skills add` success line |+| `06-skills-unknown` | an unknown name, which neither handler claims |++Plus two non-PTY captures, `static-help` and `static-schema`, as cheap+insurance that the argument surface did not move.++Each window is written twice: `.raw` (exact bytes, ANSI included — this is the+comparison that matters) and `.txt` (`pty_harness.terminal_text` rendering,+which is what you read when a diff fires). 3 widths x 6 windows + 2 static = 20+captures, 40 files.++## Why the model turn is run but not captured++A live turn spins the thinking spinner, and its frame count depends on wall+clock — capture it and every run differs. So the turn happens first, outside+any window, and every window after it shows a status line whose context meter+and cache badge are populated, with no spinner byte inside. That is also why+the scripted model here is not `scripts/eval/mock_model.py`: this one reports a+large prompt count **and** a cached count, so both of those segments actually+render. A mock reporting 8 tokens and no cache leaves them blank, and the+goldens would silently cover nothing.++## Measurement validity++Four things have to hold or the diff says nothing:++1. **Fixed workspace path.** The cwd string is rendered into the status line+ and its *length* feeds the width budget, so `workspace()` uses a fixed path+ under `runs/`, never `mkdtemp`. A per-run temp name moves the layout between+ arms and produces diffs that are pure harness noise.+2. **Pinned environment.** `HOME`, `TERM`, `GRAFF_LEARNING_PRIVACY`, fleet and+ telemetry are all set explicitly. The privacy badge is a status-line+ segment, so an inherited setting would move the layout.+3. **Fresh workspace per scenario.** Each width starts from an empty HOME, so+ the `.harness/settings.json` written by `/skills remove` in one scenario+ never leaks into the next.+4. **Settle before every window.** See the race above.++## Known gaps++- **No NO_COLOR scenario.** With `NO_COLOR=1` this build never draws the+ interactive prompt over a PTY at all, so there is nothing to capture. The+ no-color rendering is covered instead by unit tests that zero `ansi.style`+ and assert the line byte-for-byte.+- **No `--json` scenario.** The surfaces covered here have no wire shape, so+ the wire is untouched by construction rather than by observation. A batch+ that converts a *durable* event needs a `--json` arm added here.+- **No approval prompt.** #430's acceptance calls for a scripted PTY approval+ flow; these goldens never exercise a permission prompt. That is tracked+ there, not here.diff --git a/scripts/eval/golden/run_golden.py b/scripts/eval/golden/run_golden.pynew file mode 100755index 00000000..a751d16e--- /dev/null+++ b/scripts/eval/golden/run_golden.py@@ -0,0 +1,338 @@+#!/usr/bin/env python3+"""Golden byte-identity harness: prove a refactor changed no rendered output.++Drives a real PTY session against a scripted model at several pane widths and+captures the exact bytes the terminal received, for two graff binaries. A+refactor that claims to be behavior-preserving has to produce an empty diff.++Every capture window is deterministic by construction (see the settle rule in+README.md), and `--self-check` proves that before any comparison is believed:+if the same binary twice does not agree, a before/after diff means nothing.++ export GRAFF_EVAL_BEFORE=/path/to/base-worktree/zig-out/bin/graff+ export GRAFF_EVAL_AFTER=/path/to/change-worktree/zig-out/bin/graff+ python3 run_golden.py++Exit status is 0 only when the self-check passed and the two arms are+byte-identical, so this is usable as a gate.+"""+from __future__ import annotations++import argparse+import filecmp+import http.server+import json+import os+import pathlib+import shutil+import subprocess+import sys+import threading+from typing import Any++ROOT = pathlib.Path(__file__).resolve().parent+RUNS = ROOT / "runs"+# scripts/eval/golden -> scripts, where the shared PTY driver lives.+sys.path.insert(0, str(ROOT.parents[1]))++from pty_harness import PtySession, terminal_text # noqa: E402++# Same variable names the live-ab harness uses, so the two instruments share+# one convention. Resolution is lazy: capturing a single arm needs only that+# arm's variable set.+BIN_ENV = {"before": "GRAFF_EVAL_BEFORE", "after": "GRAFF_EVAL_AFTER"}++PORT = int(os.environ.get("GRAFF_EVAL_PORT", "1234"))+MODEL = os.environ.get("GRAFF_EVAL_MODEL", "lmstudio")+++def binary_path(arm: str) -> str:+ env_name = BIN_ENV[arm]+ path = os.environ.get(env_name)+ if not path:+ sys.exit(+ "%s is unset. Point it at the %r arm's graff binary, e.g.\n"+ " %s=/path/to/worktree/zig-out/bin/graff" % (env_name, arm, env_name)+ )+ if not os.path.isfile(path):+ sys.exit("%s=%s is not a file" % (env_name, path))+ return path+++# ── the scripted model ───────────────────────────────────────────────────────+# Deliberately not scripts/eval/mock_model.py: this one reports a large prompt+# count AND a cached count, so the status line's context meter and its cache+# badge both render and are covered. A mock that reports 8 tokens and no cache+# leaves both segments blank and the goldens prove nothing about them.++USAGE = {+ "prompt_tokens": 12345,+ "completion_tokens": 4,+ "total_tokens": 12349,+ "prompt_tokens_details": {"cached_tokens": 2048},+}+ANSWER = "golden answer"+++class MockModel:+ def __init__(self) -> None:+ self._server: http.server.ThreadingHTTPServer | None = None++ def start(self) -> None:+ class Handler(http.server.BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def _send(self, payload: bytes, content_type: str) -> None:+ self.send_response(200)+ self.send_header("content-type", content_type)+ self.send_header("content-length", str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)++ def do_GET(self) -> None: # noqa: N802 (/v1/models probes)+ self._send(json.dumps({"data": [{"id": "mock"}]}).encode(), "application/json")++ def do_POST(self) -> None: # noqa: N802+ length = int(self.headers.get("content-length", 0))+ body: dict[str, Any] = {}+ if length:+ try:+ body = json.loads(self.rfile.read(length))+ except (ValueError, UnicodeDecodeError):+ body = {}+ if body.get("stream"):+ self._stream()+ else:+ self._send(json.dumps({+ "id": "mock", "object": "chat.completion", "model": "mock",+ "choices": [{+ "index": 0,+ "message": {"role": "assistant", "content": ANSWER},+ "finish_reason": "stop",+ }],+ "usage": USAGE,+ }).encode(), "application/json")++ def _stream(self) -> None:+ self.send_response(200)+ self.send_header("content-type", "text/event-stream")+ self.send_header("cache-control", "no-cache")+ self.send_header("connection", "close")+ self.end_headers()+ self._chunk({"choices": [{+ "index": 0,+ "delta": {"role": "assistant", "content": ANSWER},+ "finish_reason": None,+ }]})+ self._chunk({+ "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],+ "usage": USAGE,+ })+ self.wfile.write(b"data: [DONE]\n\n")+ self.wfile.flush()+ self.close_connection = True++ def _chunk(self, payload: dict[str, Any]) -> None:+ framed = dict(payload, id="mock", object="chat.completion.chunk", model="mock")+ self.wfile.write(b"data: " + json.dumps(framed).encode() + b"\n\n")++ def log_message(self, *_args) -> None:+ pass++ self._server = http.server.ThreadingHTTPServer(("127.0.0.1", PORT), Handler)+ threading.Thread(target=self._server.serve_forever, daemon=True).start()++ def stop(self) -> None:+ if self._server is not None:+ self._server.shutdown()+ self._server.server_close()+ self._server = None+++# ── the session script ───────────────────────────────────────────────────────+# A step either captures a window or does not. `wait` is a literal to wait for+# before settling; `settle` is the quiet period that must elapse BEFORE the+# next window opens (see README: the capture-window race).+#+# The model turn is deliberately NOT captured: a live turn spins the thinking+# spinner, whose frame count is wall-clock dependent. Running it first and+# capturing afterwards means every window below shows a status line with the+# context meter and cache badge populated, with no spinner byte inside it.++STEPS = [+ {"name": "01-prompt-clean", "send": "/thinking off", "settle": 1.0},+ {"name": None, "send": "say hello", "wait": ANSWER, "settle": 1.5},+ {"name": "02-skills-list", "send": "/skills", "wait": "re-enable", "settle": 0.8},+ {"name": "03-skills-remove", "send": "/skills remove skill-creator", "settle": 1.0},+ {"name": "04-skills-after-remove", "send": "/skills", "wait": "re-enable", "settle": 0.8},+ {"name": "05-skills-add", "send": "/skills add skill-creator", "settle": 1.0},+ {"name": "06-skills-unknown", "send": "/skills remove no-such-skill", "settle": 1.0},+]++# Widths chosen to straddle the #209 status-line budget: 160 keeps every+# segment, 60 forces low-priority metadata out, 34 is the pathological pane.+WIDTHS = [("wide", 160), ("narrow", 60), ("tiny", 34)]+++def workspace() -> str:+ """A FIXED path, never mkdtemp.++ The cwd string is rendered into the status line and its LENGTH feeds the+ width budget, so a per-run temp name would move the layout between arms and+ produce diffs that are pure harness noise.+ """+ ws = RUNS / "_ws"+ shutil.rmtree(ws, ignore_errors=True)+ ws.mkdir(parents=True)+ return str(ws)+++def env_for(ws: str) -> dict[str, str]:+ return {+ "HOME": ws,+ "LMSTUDIO_API_KEY": "local",+ "GRAFF_FLEET": "off",+ "GRAFF_NO_TELEMETRY": "1",+ "GRAFF_NO_SMOLIFY": "1",+ # Pinned: the privacy badge is one of the status-line segments, so an+ # inherited setting would move the layout.+ "GRAFF_LEARNING_PRIVACY": "aggregate",+ "TERM": "xterm-256color",+ }+++def dump(outdir: pathlib.Path, name: str, raw: bytes) -> None:+ outdir.mkdir(parents=True, exist_ok=True)+ (outdir / (name + ".raw")).write_bytes(raw)+ (outdir / (name + ".txt")).write_text(terminal_text(raw), encoding="utf-8")+++def scenario(graff: str, outdir: pathlib.Path, label: str, cols: int) -> None:+ ws = workspace()+ with PtySession(+ graff,+ ["--model", MODEL, "--no-telemetry"],+ cwd=ws,+ env=env_for(ws),+ unset_env=("CODEX_HOME",),+ color=True,+ timeout=30.0,+ rows=40,+ cols=cols,+ ) as s:+ s.wait_for_literal("] ›")+ # Let readline's terminal setup (bracketed paste, the DSR cursor probe)+ # land BEFORE the first window opens. Without this those 12 bytes fall+ # on one side or the other of the cursor by luck. See README.+ s.pump_for(1.0)++ for step in STEPS:+ cursor = len(s.raw)+ s.send_line(step["send"])+ if step.get("wait"):+ s.wait_for_literal(step["wait"], start=cursor)+ s.pump_for(step["settle"])+ if step["name"]:+ dump(outdir, "%s-%s" % (label, step["name"]), bytes(s.raw[cursor:]))++ s.send_key("ctrl-d")+ result = s.read_until_exit(8.0)+ if result.exit_code != 0:+ sys.exit("%s: unclean exit %s timed_out=%s"+ % (label, result.exit_code, result.timed_out))+++def static_captures(graff: str, outdir: pathlib.Path) -> None:+ """Non-PTY surfaces that must not move either."""+ ws = workspace()+ for name, argv in (("static-help", ["--help"]), ("static-schema", ["--schema"])):+ proc = subprocess.run([graff, *argv], cwd=ws,+ env={**os.environ, **env_for(ws)},+ capture_output=True, timeout=60)+ dump(outdir, name, proc.stdout)+++def capture(graff: str, outdir: pathlib.Path, quiet: bool = False) -> pathlib.Path:+ shutil.rmtree(outdir, ignore_errors=True)+ model = MockModel()+ model.start()+ try:+ static_captures(graff, outdir)+ for label, cols in WIDTHS:+ scenario(graff, outdir, label, cols)+ if not quiet:+ print(" captured %s (%d cols)" % (label, cols), flush=True)+ finally:+ model.stop()+ return outdir+++def compare(a: pathlib.Path, b: pathlib.Path, a_name: str, b_name: str) -> bool:+ names = sorted({p.name for p in a.iterdir()} | {p.name for p in b.iterdir()})+ match, mismatch, errors = filecmp.cmpfiles(a, b, names, shallow=False)+ if not mismatch and not errors:+ print(" %d artifacts identical (%s vs %s)" % (len(match), a_name, b_name))+ return True+ for name in mismatch:+ ra, rb = (a / name).read_bytes(), (b / name).read_bytes()+ print(" DIFFER %s (%s: %d bytes, %s: %d bytes)"+ % (name, a_name, len(ra), b_name, len(rb)))+ for name in errors:+ print(" MISSING %s in one arm" % name)+ return False+++def main() -> int:+ ap = argparse.ArgumentParser(description=__doc__,+ formatter_class=argparse.RawDescriptionHelpFormatter)+ ap.add_argument("--arm", choices=sorted(BIN_ENV), action="append",+ help="capture only this arm (repeatable); default is both")+ ap.add_argument("--skip-self-check", action="store_true",+ help="skip the same-binary-twice determinism proof (not recommended)")+ ap.add_argument("--diff-only", action="store_true",+ help="compare existing captures under runs/ without re-capturing")+ args = ap.parse_args()++ arms = args.arm or ["before", "after"]+ RUNS.mkdir(parents=True, exist_ok=True)++ if args.diff_only:+ a, b = RUNS / "before", RUNS / "after"+ if not a.is_dir() or not b.is_dir():+ sys.exit("no captures under %s -- run without --diff-only first" % RUNS)+ print("== diff ==")+ return 0 if compare(a, b, "before", "after") else 1++ # The determinism proof comes FIRST and gates everything after it. A+ # before/after diff is only evidence if the instrument itself is stable,+ # and PTY capture has several ways not to be.+ if not args.skip_self_check:+ probe = arms[0]+ print("== self-check: %s binary captured twice ==" % probe)+ graff = binary_path(probe)+ capture(graff, RUNS / "_selfcheck-a", quiet=True)+ capture(graff, RUNS / "_selfcheck-b", quiet=True)+ if not compare(RUNS / "_selfcheck-a", RUNS / "_selfcheck-b", "run 1", "run 2"):+ print("\nthe harness is NOT deterministic on this machine; a "+ "before/after diff would be meaningless. Fix this first.")+ return 1++ for arm in arms:+ print("== capture: %s ==" % arm)+ capture(binary_path(arm), RUNS / arm)++ if len(arms) < 2:+ print("\ncaptured %s only; re-run with both arms to compare." % arms[0])+ return 0++ print("== diff ==")+ if not compare(RUNS / "before", RUNS / "after", "before", "after"):+ print("\nrendered output CHANGED. If that was intended, say so "+ "explicitly; otherwise the refactor is not behavior-preserving.")+ return 1+ print("\nbyte-identical: the change is behavior-preserving for these surfaces.")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())