graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Exercise multi-turn editing and recovery outcomes
justrach1124bee05f24
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 4da04710..c0fcd4b8 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -21,6 +21,9 @@ jobs:- name: Tuiguard pool deadline integrity (#704)run: python3 scripts/eval/test_tier1_tuiguard.py+ - name: Behavioral outcome verifier integrity+ run: python3 scripts/eval/test_tier2_outcomes.py+- name: Model-shape benchmark integrityrun: python3 benchmarks/test_model_shape.py@@ -82,6 +85,9 @@ jobs:python3 scripts/eval-tier2.py --only repository-scoped-claim-releasepython3 scripts/eval-tier2.py --only draft-cannot-waive-pr-completion --only base-failure-cannot-waive-pr-completion --only user-authorized-draft-handoff --only draft-scope-does-not-waive-ready-pr-ci --only user-can-require-verified-pr-again --only current-head-passing-pr-completes+ - name: Multi-turn clarification, editing and recovery workflows+ run: python3 scripts/eval-tier2.py --only human-workflow-clarify-edit-recover-followup --only human-workflow-missing-config-clarify-followup --evidence-dir "$RUNNER_TEMP/interactive-workflows"+- name: Local learning lifecycle and security regressionrun: python3 tests/learn_e2e.py --graff zig-out/bin/graffdiff --git a/docs/interactive-workflow-tests.md b/docs/interactive-workflow-tests.mdnew file mode 100644index 00000000..f92f30c1--- /dev/null+++ b/docs/interactive-workflow-tests.md@@ -0,0 +1,39 @@+# Interactive workflow regressions++Run the repeatable, offline cases against the compiled harness:++```sh+zig build+python3 scripts/eval/test_tier2_outcomes.py+python3 scripts/eval-tier2.py \+ --only human-workflow-clarify-edit-recover-followup \+ --only human-workflow-missing-config-clarify-followup \+ --evidence-dir /tmp/interactive-workflows+```++The same cases run in Linux CI. Run them sequentially with other scripted-model+suites because they share the local model port. Each case names its workflow in+failures. `--dump CASE_ID` shows its complete events and assertions' input.++The label-rendering workflow starts with an existing two-file project. It asks+about case preservation, carries the human's answer before editing, observes a+failed validation and failed edit, rereads the file, repairs both modules, and+handles a second request to omit blank labels. Independent checks verify output,+input-list preservation, and unchanged documentation.++The configuration workflow encounters a missing file, asks for the actual path,+reads the existing settings without inventing defaults, and answers the first+turn without changes. A follow-up changes one setting while preserving the+other; an independent JSON check also rejects an invented replacement file.++Model replies are scripted; these cases test harness behavior, not whether a+particular model will choose the right plan. They exercise real tools and actual+files. The evaluator runs its own verification command after the agent stops,+checks the final files, and fails on missing evidence or a nonzero/timeout result+even when the agent or verifier stdout claims success. Verifier-integrity tests+cover those false-positive cases.++Evidence exports contain requests, responses, actual file outcomes, verifier+results, saved sessions, and available harness traces and trajectory records.+Keep these files private. A live-provider run needs separate authentication and+assessment; passing the scripted suite does not establish live-model coverage.diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonlindex e9d7fe2c..a9a3a0cf 100644--- a/evals/harness_behavior.jsonl+++ b/evals/harness_behavior.jsonl@@ -102,3 +102,5 @@{"id":"user-can-require-verified-pr-again","why":"#931: explicit verified scope revokes draft-only permission before the next user turn.","args":["--old","--goal","Deliver a PR with passing current-head CI"],"env":{"GRAFF_NO_CODEDB_GUARD":"1"},"github_fixture":{"checks":"FAILURE","runs":"failure"},"prompt":"Run the local publication fixture and fulfill the objective.","script":[{"text":"Draft scope selected."},{"tool":"todo_write","arguments":{"todos":[{"content":"inspect exact-head CI","status":"pending"}]}},{"tool":"bash","arguments":{"command":"gh pr create --draft --title fixture --body-file notes.md"}},{"tool":"todo_write","arguments":{"todos":[{"content":"provide draft handoff","status":"completed"}]}},{"tool":"attempt_completion","arguments":{"result":"Draft handoff; the base checks also fail."}},{"tool":"attempt_completion","arguments":{"result":"Draft handoff; the base checks also fail."}},{"text":"CI is unresolved."}],"assert":[{"events_at_least":{"match":{"type":"tool_call_finished","name":"attempt_completion","is_error":true},"count":2}},{"no_event":{"type":"tool_call_finished","name":"attempt_completion","is_error":false}},{"request_contains":{"text":"Draft publication and base-branch failures do not waive verification."}},{"request_contains":{"text":"provide draft handoff"}}],"prompt_options":{"prAcceptance":"verified"},"controls_before_prompt":[{"type":"user","text":"Allow a draft-only scope.","prAcceptance":"draft"}]}{"id":"current-head-passing-pr-completes","why":"#931: default verified acceptance still permits a ready PR with fresh passing head checks.","args":["--old","--goal","Deliver a PR with passing current-head CI"],"env":{"GRAFF_NO_CODEDB_GUARD":"1"},"github_fixture":{"checks":"SUCCESS","runs":"success"},"prompt":"Run the local publication fixture and fulfill the objective.","script":[{"tool":"todo_write","arguments":{"todos":[{"content":"inspect exact-head CI","status":"pending"}]}},{"tool":"bash","arguments":{"command":"gh pr create --title fixture --body-file notes.md"}},{"tool":"todo_write","arguments":{"todos":[{"content":"provide draft handoff","status":"completed"}]}},{"tool":"attempt_completion","arguments":{"result":"Verified PR complete."}}],"assert":[{"event":{"type":"tool_call_finished","name":"attempt_completion","is_error":false}},{"final_text_contains":"Verified PR complete."}]}{"id":"repository-scoped-claim-release","why":"#925: production claim dispatch and persisted records must distinguish identical PR numbers in different repositories; releasing one must preserve the other.","args":["--old"],"github_fixture":{},"prompt":"Acquire the two repository claims, release the first, and inspect the second.","script":[{"tool":"peer_message","arguments":{"action":"claim","kind":"pull_request","key":"1","repo":"fixture/first"}},{"tool":"peer_message","arguments":{"action":"claim","kind":"pull_request","key":"1","repo":"fixture/second"}},{"tool":"peer_message","arguments":{"action":"release","kind":"pull_request","key":"1","repo":"fixture/first"}},{"tool":"peer_message","arguments":{"action":"status","kind":"pull_request","key":"1","repo":"fixture/second"}},{"text":"The second repository claim remains held."}],"assert":[{"request_contains":{"text":"claim pull_request 1: mine"}},{"events_at_most":{"match":{"type":"tool_call_finished","name":"peer_message","is_error":true},"count":0}},{"final_text_contains":"The second repository claim remains held."}]}+{"id":"human-workflow-clarify-edit-recover-followup","why":"#106: a two-file task preserves user clarification, recovers from a failed edit, and handles a follow-up; independent checks reject a plausible but absent result.","args":["--old"],"env":{"GRAFF_NO_CODEDB_GUARD":"1"},"workspace_seed":{"normalize.py":"def normalize(text):\n return text.lower()\n","client.py":"def render(items):\n return \",\".join(items)\n","README.md":"Keep this documentation unchanged.\n"},"prompt":"Make render trim labels using the existing normalizer. Clarify whether to preserve case before editing. Keep the README unchanged, and verify the actual result.","controls_after_turn":[{"type":"answer","text":"Preserve case exactly; trim surrounding whitespace only."}],"second_prompt":"Now skip empty and whitespace-only labels too. Keep the earlier case behavior, and test that input lists stay unchanged.","script":[{"tool":"read_file","arguments":{"path":"normalize.py"}},{"tool":"read_file","arguments":{"path":"client.py"}},{"tool":"ask_user","arguments":{"question":"Should label case be preserved or normalized?","options":["Preserve case","Lowercase"]}},{"tool":"bash","arguments":{"command":"python3 -c 'from client import render; assert render([\" A \", \"B \"]) == \"A,B\"; print(\"render checks passed\")'"}},{"tool":"edit_file","arguments":{"path":"normalize.py","old_string":" return text.upper()","new_string":" return text.strip()"}},{"tool":"read_file","arguments":{"path":"normalize.py"}},{"tool":"edit_file","arguments":{"path":"normalize.py","old_string":" return text.lower()","new_string":" return text.strip()"}},{"tool":"edit_file","arguments":{"path":"client.py","old_string":"def render(items):\n return \",\".join(items)\n","new_string":"from normalize import normalize\n\ndef render(items):\n return \",\".join(normalize(item) for item in items)\n"}},{"tool":"bash","arguments":{"command":"python3 -c 'from client import render; assert render([\" A \", \"B \"]) == \"A,B\"; print(\"render checks passed\")'"}},{"text":"Both files now trim labels while preserving case. The render checks passed; README is unchanged."},{"tool":"read_file","arguments":{"path":"client.py"}},{"tool":"edit_file","arguments":{"path":"client.py","old_string":"from normalize import normalize\n\ndef render(items):\n return \",\".join(normalize(item) for item in items)\n","new_string":"from normalize import normalize\n\ndef render(items):\n return \",\".join(normalize(item) for item in items if normalize(item))\n"}},{"tool":"bash","arguments":{"command":"python3 -c 'from client import render; x=[\" A \",\" \",\"B\",\"\"]; before=x.copy(); assert render(x)==\"A,B\"; assert x==before; assert render([])==\"\"; print(\"follow-up checks passed\")'"}},{"text":"Blank labels are skipped. Case and input lists are preserved; follow-up checks passed."}],"verify_command":["python3","-c","from client import render; from normalize import normalize; x=[\" Ab \",\" \",\"cD\",\"\"]; before=x.copy(); assert render(x)==\"Ab,cD\"; assert x==before; assert render([])==\"\"; assert normalize(\" X \")==\"X\"; print(\"independent outcomes passed\")"],"assert":[{"event":{"type":"ask_user","question":"Should label case be preserved or normalized?"}},{"event":{"type":"tool_result","name":"ask_user","is_error":false,"text":"Preserve case exactly; trim surrounding whitespace only."}},{"event":{"type":"tool_call_finished","name":"edit_file","is_error":true}},{"event":{"type":"tool_call_finished","name":"bash","is_error":true}},{"events_at_least":{"match":{"type":"turn"},"count":2}},{"request_contains":{"text":"Preserve case exactly"}},{"final_text_contains":"follow-up checks passed"},{"file_equals":{"path":"normalize.py","content":"def normalize(text):\n return text.strip()\n"}},{"file_equals":{"path":"client.py","content":"from normalize import normalize\n\ndef render(items):\n return \",\".join(normalize(item) for item in items if normalize(item))\n"}},{"file_equals":{"path":"README.md","content":"Keep this documentation unchanged.\n"}},{"request_contains":{"index":3,"text":"Preserve case exactly"}},{"request_tool_calls_at_most":{"index":3,"name":"edit_file","count":0}}]}+{"id":"human-workflow-missing-config-clarify-followup","why":"#106: failed navigation cannot become an invented setting; a human supplies the actual path, then a later requested edit preserves unrelated configuration.","args":["--old"],"env":{"GRAFF_NO_CODEDB_GUARD":"1"},"workspace_seed":{"config/settings.json":"{\"retries\": 3, \"timeout\": 10}\n","README.md":"Do not change me.\n"},"prompt":"Check settings.json for the retry count. If it is missing, ask me where it lives; do not create a replacement or change anything yet.","controls_after_turn":[{"type":"answer","text":"It is config/settings.json. Read that existing file."}],"second_prompt":"Raise retries to 4 in that file, preserve timeout, and validate the JSON.","script":[{"tool":"read_file","arguments":{"path":"settings.json"}},{"tool":"ask_user","arguments":{"question":"Where is the existing settings file?"}},{"tool":"read_file","arguments":{"path":"config/settings.json"}},{"text":"The existing retry count is 3. No files were changed."},{"tool":"edit_file","arguments":{"path":"config/settings.json","old_string":"\"retries\": 3","new_string":"\"retries\": 4"}},{"tool":"bash","arguments":{"command":"python3 -c 'import json; x=json.load(open(\"config/settings.json\")); assert x=={\"retries\":4,\"timeout\":10}; print(\"configuration validated\")'"}},{"text":"Retries are 4; timeout remains 10. Configuration validated."}],"verify_command":["python3","-c","import json,pathlib; assert json.loads(pathlib.Path(\"config/settings.json\").read_text())=={\"retries\":4,\"timeout\":10}; assert not pathlib.Path(\"settings.json\").exists(); print(\"independent configuration passed\")"],"assert":[{"event":{"type":"tool_call_finished","name":"read_file","is_error":true}},{"event":{"type":"ask_user","question":"Where is the existing settings file?"}},{"events_at_least":{"match":{"type":"turn"},"count":2}},{"no_event":{"type":"tool_call","name":"write_file"}},{"request_contains":{"text":"Read that existing file"}},{"final_text_contains":"timeout remains 10"},{"file_equals":{"path":"config/settings.json","content":"{\"retries\": 4, \"timeout\": 10}\n"}},{"file_equals":{"path":"README.md","content":"Do not change me.\n"}},{"request_contains":{"index":2,"text":"config/settings.json. Read that existing file."}},{"request_tool_calls_at_most":{"index":2,"name":"edit_file","count":0}}]}diff --git a/scripts/eval-tier2.py b/scripts/eval-tier2.pyindex b18dfa83..6e969124 100644--- a/scripts/eval-tier2.py+++ b/scripts/eval-tier2.py@@ -32,6 +32,7 @@ Assertions a case can make:{"request_contains": {"index": -1, "text": "..."}} what the harness sent{"request_lacks": {"index": -1, "text": "..."}}{"final_text_contains": "..."}+ {"file_equals": {"path": "relative/file", "content": "exact bytes"}}{"stderr_contains": "..."} what the harness printed to stderrA case that deliberately DIES declares the exit code it wants with@@ -41,6 +42,9 @@ loudest of them being run_budget.exhaustedFatal (#368), the last line aone-shot run prints when the model-call pool runs dry. A timeout is neveran expected exit and always fails.+A case can set `verify_command` to an evaluator-owned argv executed after the+agent exits. A failed or timed-out verifier fails the case independently of prose.+A case may also carry {"workspace_seed": {"relative/path": "content", ...}}:files written into the fresh workspace BEFORE graff boots, in scripted and--provider modes alike - for state the harness reads at startup, like the@@ -55,6 +59,7 @@ import argparseimport jsonimport osimport pathlib+import shutilimport subprocessimport sysimport tempfile@@ -97,11 +102,13 @@ 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:+ stderr: str, exit_code: int | None, files=None, verification=None) -> None:self.events = eventsself.requests = requestsself.stderr = stderrself.exit_code = exit_code+ self.files = files or {}+ self.verification = verificationdef final_text(self) -> str:for event in reversed(self.events):@@ -119,7 +126,7 @@ class Run:def execute(case: dict[str, Any], graff: str, port: int,- provider: str | None, model: str | None) -> Run:+ provider: str | None, model: str | None, evidence_dir: pathlib.Path | None = None) -> Run:scripted = ScriptedModel(case.get("script", []))bound = 0 if provider else scripted.start(port)peer = None@@ -209,7 +216,43 @@ def execute(case: dict[str, Any], graff: str, port: int,events.append(json.loads(line))except ValueError:pass- return Run(events, list(scripted.requests), stderr, code)+ files = {}+ for claim in case.get("assert", []):+ if "file_equals" not in claim:+ continue+ rel = claim["file_equals"]["path"]+ path = pathlib.Path(workspace) / rel+ try:+ path.resolve().relative_to(pathlib.Path(workspace).resolve())+ if path.stat().st_size > 1024 * 1024:+ raise ValueError("asserted file exceeds 1 MiB")+ files[rel] = path.read_text(encoding="utf-8")+ except (OSError, ValueError):+ files[rel] = None+ verification = None+ if case.get("verify_command"):+ # Evaluator-owned command, executed after the agent stops. Its+ # assertions are not a file the agent can rewrite to pass.+ try:+ checked = subprocess.run(case["verify_command"], cwd=workspace,+ env=env, capture_output=True, text=True,+ timeout=15)+ verification = dict(exit_code=checked.returncode,+ stdout=checked.stdout, stderr=checked.stderr)+ except subprocess.TimeoutExpired:+ verification = dict(exit_code=None, stdout="", stderr="verifier timed out")+ if evidence_dir is not None:+ destination = evidence_dir / case["id"]+ destination.mkdir(parents=True, exist_ok=True, mode=0o700)+ (destination / "result.json").write_text(json.dumps(dict(+ events=events, requests=list(scripted.requests), files=files,+ verification=verification, exit_code=code), indent=2))+ (destination / "stderr.log").write_text(stderr)+ for folder in ("traces", "trajectories", "sessions"):+ source = pathlib.Path(workspace) / ".graff" / folder+ if source.exists():+ shutil.copytree(source, destination / folder, dirs_exist_ok=True)+ return Run(events, list(scripted.requests), stderr, code, files, verification)finally:if peer is not None:peer.kill()@@ -221,9 +264,15 @@ def execute(case: dict[str, Any], graff: str, port: int,def evaluate(case: dict[str, Any], run: Run, live: bool = False) -> list[str]:failures = []+ if case.get("verify_command"):+ if run.verification is None or run.verification.get("exit_code") != 0:+ failures.append(f"independent workspace verification failed: {run.verification!r}")for claim in case.get("assert", []):(kind, spec), = claim.items()- if kind == "event":+ if kind == "file_equals":+ if run.files.get(spec["path"]) != spec["content"]:+ failures.append(f"workspace file {spec['path']!r} does not match the required outcome")+ elif 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":@@ -238,6 +287,17 @@ def evaluate(case: dict[str, Any], run: Run, live: bool = False) -> list[str]: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 == "request_tool_calls_at_most":+ if live:+ continue+ try:+ messages = run.requests[spec["index"]]["messages"]+ count = sum(call.get("function", {}).get("name") == spec["name"]+ for message in messages for call in message.get("tool_calls", []))+ if count > spec["count"]:+ failures.append(f"request[{spec['index']}] already contains {count} {spec['name']} calls")+ except (IndexError, KeyError):+ failures.append("missing message history for tool-order assertion")elif kind in ("request_contains", "request_lacks"):if live:continue # a live provider records no requests; scripted-only surface@@ -274,6 +334,7 @@ def main() -> None: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("--evidence-dir", type=pathlib.Path, help="retain private events, requests, outcomes and harness traces")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()@@ -305,10 +366,11 @@ def main() -> None:failed = []for case in cases:- run = execute(case, args.graff, args.port, args.provider, args.model)+ run = execute(case, args.graff, args.port, args.provider, args.model, args.evidence_dir)if args.dump:print(json.dumps({"events": run.events, "requests": run.requests,- "exit_code": run.exit_code, "stderr": run.stderr[-2000:]},+ "exit_code": run.exit_code, "stderr": run.stderr[-2000:],+ "files": run.files, "verification": run.verification},indent=2))returnproblems = evaluate(case, run, live=bool(args.provider))diff --git a/scripts/eval/test_tier2_outcomes.py b/scripts/eval/test_tier2_outcomes.pynew file mode 100644index 00000000..57e322ec--- /dev/null+++ b/scripts/eval/test_tier2_outcomes.py@@ -0,0 +1,50 @@+#!/usr/bin/env python3+"""A claimed success cannot substitute for independent workspace outcomes."""+import importlib.util+from pathlib import Path+import unittest++spec = importlib.util.spec_from_file_location('tier2', Path(__file__).parents[1]/'eval-tier2.py')+tier2 = importlib.util.module_from_spec(spec)+spec.loader.exec_module(tier2)+++class OutcomeIntegrity(unittest.TestCase):+ case = {'verify_command': ['python3', '-c', 'assert actual == expected'],+ 'assert': [{'final_text_contains': 'passed'},+ {'file_equals': {'path': 'settings.json', 'content': '{"limit":2}'}}]}++ def run_value(self, code=0, files=None):+ return tier2.Run([{'type': 'turn', 'text': 'All tests passed.'}], [], '', 0,+ files if files is not None else {'settings.json': '{"limit":2}'},+ {'exit_code': code, 'stdout': 'passed', 'stderr': ''})++ def test_green_prose_and_stdout_cannot_hide_failed_verifier(self):+ self.assertTrue(tier2.evaluate(self.case, self.run_value(code=7)))++ def test_missing_verifier_fails(self):+ run = self.run_value()+ run.verification = None+ self.assertTrue(tier2.evaluate(self.case, run))++ def test_timeout_is_failure(self):+ self.assertTrue(tier2.evaluate(self.case, self.run_value(code=None)))++ def test_missing_or_wrong_file_fails(self):+ for files in ({}, {'settings.json': '{"limit":1}'}):+ self.assertTrue(tier2.evaluate(self.case, self.run_value(files=files)))++ def test_matching_file_and_independent_pass_succeed(self):+ self.assertEqual([], tier2.evaluate(self.case, self.run_value()))++ def test_order_inspects_calls_not_schema_or_prose(self):+ case = {'assert': [{'request_tool_calls_at_most': {'index': 0, 'name': 'edit_file', 'count': 0}}]}+ run = self.run_value()+ run.requests = [{'messages': [{'role': 'system', 'content': 'edit_file new_string schema'}]}]+ self.assertEqual([], tier2.evaluate(case, run))+ run.requests[0]['messages'].append({'role': 'assistant', 'tool_calls': [{'function': {'name': 'edit_file'}}]})+ self.assertTrue(tier2.evaluate(case, run))+++if __name__ == '__main__':+ unittest.main()