graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(eval): a tier-2 eval set that asserts what a run actually does
Rach Pradhan1ddd62bb71bb
diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonlnew file mode 100644index 00000000..e9df36d4--- /dev/null+++ b/evals/harness_behavior.jsonl@@ -0,0 +1,6 @@+{"id": "goal-checklist-completes", "why": "#318: a standing goal must produce a checklist and be able to finish it. The regression was a goal born done, or one that could never be closed.", "args": ["--goal", "add a health endpoint and a test for it"], "prompt": "get the objective done", "script": [{"tool": "todo_write", "arguments": {"todos": [{"content": "add the health endpoint", "status": "in_progress"}, {"content": "add a test for it", "status": "pending"}]}}, {"tool": "todo_write", "arguments": {"todos": [{"content": "add the health endpoint", "status": "completed"}, {"content": "add a test for it", "status": "completed"}]}}, {"text": "the endpoint and its test are in"}], "assert": [{"events_at_least": {"match": {"type": "tool_call", "name": "todo_write"}, "count": 2}}, {"request_contains": {"index": -1, "text": "add the health endpoint"}}, {"request_contains": {"index": -1, "text": "completed"}}, {"final_text_contains": "the endpoint and its test are in"}]}+{"id": "standing-goal-restated", "why": "#318: --goal is a standing objective, so it has to reach the model on every call, not only the first.", "args": ["--goal", "keep the build green"], "prompt": "what should I do next", "script": [{"text": "checking"}, {"text": "still checking"}], "assert": [{"request_contains": {"index": 0, "text": "keep the build green"}}, {"request_contains": {"index": -1, "text": "keep the build green"}}]}+{"id": "todo-empty-write-noop", "why": "6300514: a todo_write with no usable items must leave the list untouched. It used to wipe the checklist, and an empty list read as completion.", "args": [], "prompt": "plan two steps, then send an empty checklist", "script": [{"tool": "todo_write", "arguments": {"todos": [{"content": "survey the call sites", "status": "pending"}, {"content": "land the fix", "status": "pending"}]}}, {"tool": "todo_write", "arguments": {"todos": []}}, {"tool": "todo_read", "arguments": {}}, {"text": "the plan is unchanged"}], "assert": [{"events_at_least": {"match": {"type": "tool_call", "name": "todo_read"}, "count": 1}}, {"request_contains": {"index": -1, "text": "survey the call sites"}}, {"request_contains": {"index": -1, "text": "land the fix"}}]}+{"id": "todo-preserves-completed", "why": "2896b32: a replace that omits an already-completed item must keep it. Omitting finished work used to delete it, erasing the record of what was done.", "args": [], "prompt": "finish one step then replace the list without it", "script": [{"tool": "todo_write", "arguments": {"todos": [{"content": "migrate the schema", "status": "completed"}, {"content": "backfill the rows", "status": "pending"}]}}, {"tool": "todo_write", "arguments": {"todos": [{"content": "backfill the rows", "status": "in_progress"}]}}, {"tool": "todo_read", "arguments": {}}, {"text": "still on the backfill"}], "assert": [{"request_contains": {"index": -1, "text": "migrate the schema"}}, {"request_contains": {"index": -1, "text": "backfill the rows"}}]}+{"id": "compaction-keeps-completed", "why": "#318: compaction mid-run must not lose the goal or the items already completed under it. The summary used to drop them and the run restarted work it had finished.", "args": ["--goal", "ship the migration"], "prompt": "start the work", "controls_after_turn": [{"type": "compact"}], "second_prompt": "keep going", "script": [{"tool": "todo_write", "arguments": {"todos": [{"content": "write the migration", "status": "completed"}, {"content": "run it against staging", "status": "pending"}]}}, {"text": "migration written"}, {"text": "summary of the session so far: the migration is written"}, {"text": "running it against staging now"}], "assert": [{"event": {"type": "compact", "ok": true}}, {"request_contains": {"index": -1, "text": "write the migration"}}, {"request_contains": {"index": -1, "text": "ship the migration"}}]}+{"id": "tool-budget-stops-the-run", "why": "A run that will not stop is worse than one that stops early. --max-tool-calls has to be enforced against the root agent, not just advertised.", "args": ["--max-tool-calls", "2"], "prompt": "keep calling the todo tool", "script": [{"tool": "todo_read", "arguments": {}}, {"tool": "todo_read", "arguments": {}}, {"tool": "todo_read", "arguments": {}}, {"tool": "todo_read", "arguments": {}}, {"text": "stopping"}], "assert": [{"events_at_most": {"match": {"type": "tool_call_started"}, "count": 2}}]}diff --git a/scripts/eval-tier2.py b/scripts/eval-tier2.pynew file mode 100755index 00000000..b51d336b--- /dev/null+++ b/scripts/eval-tier2.py@@ -0,0 +1,263 @@+#!/usr/bin/env python3+"""Tier 2 of the internal eval set: model-backed harness behavior.++Tier 1 (scripts/eval-tier1.sh) proves the code compiles, the tests run, and the+generated artifacts match. It cannot tell you whether a real run *behaves*: that+a goal produces a checklist and can finish it, that an empty todo_write leaves+the list alone, that compaction does not lose completed work. Those need a model+in the loop, which is why this tier is not in the pre-push hook.++The cases are data - evals/harness_behavior.jsonl - and each one carries the+regression it guards. A case scripts the model's replies, so the default run is+offline and free: scripts/eval/mock_model.py replays the script on the fixed+lmstudio port and records what the harness sent back. Point --provider/--model+at a real provider to run the same cases against one.++ python3 scripts/eval-tier2.py every case, scripted model+ python3 scripts/eval-tier2.py --only todo-empty-write-noop+ python3 scripts/eval-tier2.py --list+ python3 scripts/eval-tier2.py --dump goal-checklist-completes++Assertions a case can make:++ {"event": {...}} some emitted event matches this subset+ {"no_event": {...}} none does+ {"events_at_least": {"match": {...}, "count": N}}+ {"events_at_most": {"match": {...}, "count": N}}+ {"request_contains": {"index": -1, "text": "..."}} what the harness sent+ {"request_lacks": {"index": -1, "text": "..."}}+ {"final_text_contains": "..."}+"""++from __future__ import annotations++import argparse+import json+import os+import pathlib+import subprocess+import sys+import tempfile+import time+from typing import Any++REPO = pathlib.Path(__file__).resolve().parents[1]+CASES = REPO / "evals" / "harness_behavior.jsonl"+sys.path.insert(0, str(REPO / "scripts" / "eval"))+from mock_model import ScriptedModel # noqa: E402+++def load_cases() -> list[dict[str, Any]]:+ cases = []+ for number, line in enumerate(CASES.read_text(encoding="utf-8").splitlines(), 1):+ line = line.strip()+ if not line or line.startswith("//"):+ continue+ try:+ cases.append(json.loads(line))+ except ValueError as exc:+ sys.exit(f"eval-tier2: {CASES}:{number} is not valid JSON: {exc}")+ return cases+++def subset_matches(event: dict[str, Any], wanted: dict[str, Any]) -> bool:+ for key, value in wanted.items():+ if key not in event:+ return False+ if isinstance(value, dict):+ if not isinstance(event[key], dict) or not subset_matches(event[key], value):+ return False+ elif event[key] != value:+ return False+ return True+++class Run:+ """One harness run: the events it emitted and the requests it sent."""++ def __init__(self, events: list[dict[str, Any]], requests: list[dict[str, Any]],+ stderr: str, exit_code: int | None) -> None:+ self.events = events+ self.requests = requests+ self.stderr = stderr+ self.exit_code = exit_code++ def final_text(self) -> str:+ for event in reversed(self.events):+ if event.get("type") == "turn":+ return str(event.get("text", ""))+ return ""++ def request_text(self, index: int) -> str | None:+ if not self.requests:+ return None+ try:+ return json.dumps(self.requests[index])+ except IndexError:+ return None+++def execute(case: dict[str, Any], graff: str, port: int,+ provider: str | None, model: str | None) -> Run:+ scripted = ScriptedModel(case.get("script", []))+ bound = 0 if provider else scripted.start(port)+ try:+ with tempfile.TemporaryDirectory(prefix="graff-tier2-") as workspace:+ env = {+ key: value for key, value in os.environ.items()+ if not key.endswith("_API_KEY")+ }+ env.update({+ "HOME": workspace,+ "LMSTUDIO_API_KEY": "local",+ "GRAFF_NO_TELEMETRY": "1",+ "GRAFF_FLEET": "off",+ "GRAFF_NO_SMOLIFY": "1",+ "NO_COLOR": "1",+ })+ argv = [graff, "--json", "--yolo", "--model", model or "lmstudio"]+ if provider:+ argv += ["--subagent-provider", provider]+ argv += list(case.get("args", []))++ stdin_lines = [json.dumps({"type": "user", "text": case["prompt"]})]+ for control in case.get("controls_after_turn", []):+ stdin_lines.append(json.dumps(control))+ if case.get("second_prompt"):+ stdin_lines.append(json.dumps({"type": "user", "text": case["second_prompt"]}))++ try:+ done = subprocess.run(+ argv, cwd=workspace, env=env, text=True, capture_output=True,+ input="\n".join(stdin_lines) + "\n",+ timeout=case.get("timeout_s", 60),+ )+ stdout, stderr, code = done.stdout, done.stderr, done.returncode+ except subprocess.TimeoutExpired as exc:+ stdout = exc.stdout if isinstance(exc.stdout, str) else (exc.stdout or b"").decode("utf-8", "ignore")+ stderr = exc.stderr if isinstance(exc.stderr, str) else (exc.stderr or b"").decode("utf-8", "ignore")+ code = None++ events = []+ for line in stdout.splitlines():+ line = line.strip()+ if line.startswith("{"):+ try:+ events.append(json.loads(line))+ except ValueError:+ pass+ return Run(events, list(scripted.requests), stderr, code)+ finally:+ if bound:+ scripted.stop()+ # The port is fixed, so let the socket clear before the next case.+ time.sleep(0.05)+++def evaluate(case: dict[str, Any], run: Run) -> list[str]:+ failures = []+ for claim in case.get("assert", []):+ (kind, spec), = claim.items()+ if kind == "event":+ if not any(subset_matches(e, spec) for e in run.events):+ failures.append(f"no event matched {json.dumps(spec)}")+ elif kind == "no_event":+ if any(subset_matches(e, spec) for e in run.events):+ failures.append(f"an event matched {json.dumps(spec)} and none should have")+ elif kind in ("events_at_least", "events_at_most"):+ seen = sum(1 for e in run.events if subset_matches(e, spec["match"]))+ want = spec["count"]+ if kind == "events_at_least" and seen < want:+ failures.append(+ f"{seen} event(s) matched {json.dumps(spec['match'])}, wanted at least {want}")+ if kind == "events_at_most" and seen > want:+ failures.append(+ f"{seen} event(s) matched {json.dumps(spec['match'])}, wanted at most {want}")+ elif kind in ("request_contains", "request_lacks"):+ body = run.request_text(spec.get("index", -1))+ if body is None:+ failures.append(f"the harness sent no request at index {spec.get('index', -1)}")+ continue+ present = spec["text"] in body+ if kind == "request_contains" and not present:+ failures.append(+ f"request[{spec.get('index', -1)}] never mentioned {spec['text']!r}")+ if kind == "request_lacks" and present:+ failures.append(+ f"request[{spec.get('index', -1)}] mentioned {spec['text']!r} and should not have")+ elif kind == "final_text_contains":+ if spec not in run.final_text():+ failures.append(f"the final answer was {run.final_text()!r}, wanted {spec!r}")+ else:+ failures.append(f"unknown assertion {kind!r}")+ return failures+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__,+ formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--graff", default=str(REPO / "zig-out" / "bin" / "graff"))+ parser.add_argument("--only", action="append", default=[], help="case id (repeatable)")+ parser.add_argument("--list", action="store_true")+ parser.add_argument("--dump", help="run one case and print its events and requests")+ parser.add_argument("--port", type=int, default=1234, help="scripted-model port")+ parser.add_argument("--provider", help="run against a real provider instead of the script")+ parser.add_argument("--model", help="model name for --provider")+ args = parser.parse_args()++ cases = load_cases()+ if args.list:+ for case in cases:+ print(f"{case['id']}\n {case['why']}")+ return++ wanted = set(args.only) | ({args.dump} if args.dump else set())+ if wanted:+ known = {case["id"] for case in cases}+ missing = wanted - known+ if missing:+ sys.exit(f"eval-tier2: no case named {', '.join(sorted(missing))} (try --list)")+ cases = [case for case in cases if case["id"] in wanted]++ if not pathlib.Path(args.graff).exists():+ sys.exit(f"eval-tier2: {args.graff} does not exist - run `zig build` first")++ if args.provider:+ print(f"tier 2: {len(cases)} case(s) against {args.provider}"+ f"/{args.model or 'default'} - this spends real calls\n")+ else:+ print(f"tier 2: {len(cases)} case(s) against the scripted model"+ f" on 127.0.0.1:{args.port} - offline, no spend\n")++ failed = []+ for case in cases:+ run = execute(case, args.graff, args.port, args.provider, args.model)+ if args.dump:+ print(json.dumps({"events": run.events, "requests": run.requests,+ "exit_code": run.exit_code, "stderr": run.stderr[-2000:]},+ indent=2))+ return+ problems = evaluate(case, run)+ if problems:+ failed.append(case["id"])+ print(f" FAIL {case['id']}")+ print(f" guards: {case['why']}")+ for problem in problems:+ print(f" - {problem}")+ if run.exit_code not in (0, None):+ print(f" graff exited {run.exit_code}; stderr tail:")+ print(" " + run.stderr.strip().splitlines()[-1] if run.stderr.strip() else "")+ else:+ print(f" pass {case['id']}")++ print()+ if failed:+ print(f"tier 2 red - {len(failed)} of {len(cases)} case(s) failed: {', '.join(failed)}")+ print("rerun one with: python3 scripts/eval-tier2.py --only <id>")+ print("see everything it did: python3 scripts/eval-tier2.py --dump <id>")+ sys.exit(1)+ print(f"tier 2 green - {len(cases)} case(s)")+++if __name__ == "__main__":+ main()diff --git a/scripts/eval/mock_model.py b/scripts/eval/mock_model.pynew file mode 100755index 00000000..befbb924--- /dev/null+++ b/scripts/eval/mock_model.py@@ -0,0 +1,167 @@+#!/usr/bin/env python3+"""A scripted OpenAI-compatible model, for tier-2 behavioral evals.++scripts/openai_mock.py answers everything with "done", which is enough to prove+plumbing but cannot drive the harness through a checklist. This one replays a+script: each entry is the reply to the next model call in the run, in order, so+a case can say "call todo_write with these three items, then finish them, then+claim completion" and the assertions can check what the harness did with it.++A reply is either:++ {"text": "..."}+ {"tool": "todo_write", "arguments": {...}}+ {"tool": "todo_write", "arguments": {...}, "text": "..."}++Past the end of the script every call answers with `exhausted_text` (default+"done"), so a run that takes more turns than the case scripted still ends+instead of hanging.++Requests are recorded in order so an assertion can look at what the harness+actually sent - that is how "compaction restated the checklist" is checked.+"""++from __future__ import annotations++import http.server+import json+import threading+from typing import Any+++class ScriptedModel:+ def __init__(self, script: list[dict[str, Any]], exhausted_text: str = "done") -> None:+ self.script = script+ self.exhausted_text = exhausted_text+ self.requests: list[dict[str, Any]] = []+ self._lock = threading.Lock()+ self._server: http.server.ThreadingHTTPServer | None = None++ def next_reply(self, body: dict[str, Any]) -> dict[str, Any]:+ with self._lock:+ self.requests.append(body)+ index = len(self.requests) - 1+ if index < len(self.script):+ return self.script[index]+ return {"text": self.exhausted_text}++ def start(self, port: int = 1234) -> int:+ model = self++ class Handler(http.server.BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.1"++ def _body(self) -> dict[str, Any]:+ length = int(self.headers.get("content-length", 0))+ if not length:+ return {}+ try:+ return json.loads(self.rfile.read(length))+ except (ValueError, UnicodeDecodeError):+ return {}++ 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+ body = self._body()+ reply = model.next_reply(body)+ if body.get("stream"):+ self._stream(reply)+ else:+ self._whole(reply)++ def _message(self, reply: dict[str, Any]) -> dict[str, Any]:+ message: dict[str, Any] = {"role": "assistant", "content": reply.get("text", "")}+ if reply.get("tool"):+ message["tool_calls"] = [{+ "id": f"call_{len(model.requests)}",+ "type": "function",+ "function": {+ "name": reply["tool"],+ "arguments": json.dumps(reply.get("arguments", {})),+ },+ }]+ return message++ def _whole(self, reply: dict[str, Any]) -> None:+ message = self._message(reply)+ finish = "tool_calls" if "tool_calls" in message else "stop"+ self._send(json.dumps({+ "id": "mock", "object": "chat.completion", "model": "mock",+ "choices": [{"index": 0, "message": message, "finish_reason": finish}],+ "usage": {"prompt_tokens": 8, "completion_tokens": 4, "total_tokens": 12},+ }).encode(), "application/json")++ def _stream(self, reply: dict[str, Any]) -> 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()+ message = self._message(reply)+ deltas: list[dict[str, Any]] = []+ if message["content"]:+ deltas.append({"role": "assistant", "content": message["content"]})+ for position, call in enumerate(message.get("tool_calls", [])):+ deltas.append({"tool_calls": [{+ "index": position,+ "id": call["id"],+ "type": "function",+ "function": call["function"],+ }]})+ finish = "tool_calls" if "tool_calls" in message else "stop"+ for delta in deltas or [{"role": "assistant", "content": ""}]:+ self._chunk({"choices": [{"index": 0, "delta": delta, "finish_reason": None}]})+ self._chunk({+ "choices": [{"index": 0, "delta": {}, "finish_reason": finish}],+ "usage": {"prompt_tokens": 8, "completion_tokens": 4, "total_tokens": 12},+ })+ 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()+ return self._server.server_address[1]++ def stop(self) -> None:+ if self._server is not None:+ self._server.shutdown()+ self._server.server_close()+ self._server = None+++def main() -> None:+ import argparse++ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--port", type=int, default=1234)+ parser.add_argument("--script", help="JSON file holding the reply list")+ args = parser.parse_args()+ script = json.load(open(args.script, encoding="utf-8")) if args.script else []+ model = ScriptedModel(script)+ port = model.start(args.port)+ print(f"scripted model on 127.0.0.1:{port} ({len(script)} scripted replies)", flush=True)+ try:+ threading.Event().wait()+ except KeyboardInterrupt:+ model.stop()+++if __name__ == "__main__":+ main()