graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Require explicit draft-only scope for PR task completion
justrach43d36e0feeab
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 445193ff..b770d5bc 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -76,6 +76,8 @@ jobs:python3 scripts/eval/test_process_guard.pypython3 scripts/test-acp-failure.pypython3 scripts/regression-release-297.py+ python3 scripts/test-pr-completion-acp.py+ python3 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: Local learning lifecycle and security regressionrun: python3 tests/learn_e2e.py --graff zig-out/bin/graffdiff --git a/docs/adr/0120-draft-publication-does-not-complete-verification.md b/docs/adr/0120-draft-publication-does-not-complete-verification.mdnew file mode 100644index 00000000..0de5aa3c--- /dev/null+++ b/docs/adr/0120-draft-publication-does-not-complete-verification.md@@ -0,0 +1,35 @@+# 0120. Draft publication does not complete verification++Status: accepted 2026-09-15++## Context++A draft PR could bypass the persisted verification obligation even when its+checks failed. Replacing the checklist with a completed handoff item and+calling `attempt_completion` then recorded completion of a verified-PR task.+The unverified label did not protect the acceptance contract (#931).++## Decision++A publication still arms an obligation independently of checklist wording.+Every completion attempt reads fresh head evidence. A draft is insufficient+by default, even if its checks pass; failing base-branch checks explain a+blocker but do not waive the task's requirements.++The user may explicitly choose `/pr-acceptance draft` in the terminal or ACP+client, or `prAcceptance: "draft"` on a JSON user request. This permits only an+unverified draft handoff. `/pr-acceptance verified` or the matching JSON value+revokes it. The choice belongs to the current conversation and goal epoch;+it is not saved, inherited by workers, or reconstructed from model prose.+Resume and new conversations clear it. A new goal cannot reuse it.++Authorized draft handoffs remain labelled unverified and cannot count as+verified recipe success. Ready PRs still require passing checks. This tightens+ADR 0104's distinction between a draft handoff and verified task completion.++## Verification++Offline production-dispatch cases publish through a local GitHub CLI fixture,+replace todos, and repeat completion attempts. They cover failing head/base+checks, user authorization and revocation, and successful verified completion.+The failure cases reproduce on the preceding release build.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 3cda6a8c..5c126f77 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -128,6 +128,7 @@ record only when you need the evidence or the edge cases.| [0116](0116-informational-turns-have-bounded-scope.md) | Summary turns gather bounded evidence; coding completion requirements apply to requested changes. || [0118](0118-file-edits-check-target-worktree.md) | File edits checkpoint the target Git worktree; unresolved paths retain the caller checkpoint. || [0119](0119-computer-tools-receive-caller-context.md) | Computer-use MCP requests receive opaque caller-owned session and turn context. |+| [0120](0120-draft-publication-does-not-complete-verification.md) | Draft PRs cannot satisfy verified completion; only a user control scoped to this conversation and goal permits an unverified draft handoff. |## When to write onediff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonlindex d661e6eb..5a4afc0a 100644--- a/evals/harness_behavior.jsonl+++ b/evals/harness_behavior.jsonl@@ -95,3 +95,9 @@{"id": "peer-checkpoint-file-target-worktree", "why": "File edits in a nested linked worktree must not inherit parent-checkout peer warnings; actual file changes still land.", "live_peer": true, "args": [], "prompt": "Create an isolated nested worktree, write its notes.txt, and change hello to updated.", "script": [{"tool": "write_file", "arguments": {"path": "nested/notes.txt", "content": "hello"}}, {"tool": "edit_file", "arguments": {"path": "nested/notes.txt", "old_string": "hello", "new_string": "updated"}}, {"tool": "read_file", "arguments": {"path": "nested/notes.txt"}}, {"text": "Updated the isolated worktree file."}], "assert": [{"event": {"type": "tool_call_finished", "name": "write_file", "is_error": false}}, {"event": {"type": "tool_call_finished", "name": "edit_file", "is_error": false}}, {"events_at_most": {"match": {"type": "tool_call_finished", "name": "write_file", "is_error": true}, "count": 0}}, {"events_at_most": {"match": {"type": "tool_call_finished", "name": "edit_file", "is_error": true}, "count": 0}}, {"request_contains": {"index": 3, "text": "updated"}}], "nested_worktree": true}{"id": "peer-checkpoint-file-target-owner", "why": "An edit targeting a nested linked worktree must checkpoint that target worktree owner even when the caller uses the parent checkout.", "nested_worktree": true, "live_peer": true, "peer_in_nested_worktree": true, "args": [], "prompt": "Write hello to nested/notes.txt; acknowledge any shared-tree checkpoint before retrying.", "script": [{"tool": "write_file", "arguments": {"path": "nested/notes.txt", "content": "hello"}}, {"tool": "write_file", "arguments": {"path": "nested/notes.txt", "content": "hello"}}, {"text": "Created after the target-owner checkpoint."}], "assert": [{"events_at_least": {"match": {"type": "tool_call_finished", "name": "write_file", "is_error": true}, "count": 1}}, {"events_at_most": {"match": {"type": "tool_call_finished", "name": "write_file", "is_error": true}, "count": 1}}, {"event": {"type": "tool_call_finished", "name": "write_file", "is_error": false}}, {"request_contains": {"index": 1, "text": "shared-tree checkpoint"}}]}{"id": "computer-tool-turn-context", "why": "Computer-use MCP calls require stable caller session and turn context, with a new turn identifier on the next user turn.", "env": {"GRAFF_MCP_SCHEMA_BUDGET": "0", "GRAFF_MCP_PROBE": "0", "GRAFF_LEARN_AUTO": "off"}, "workspace_seed": {".mcp.json": "{\"mcpServers\": {\"cua_repl\": {\"command\": \"python3\", \"args\": [\"context_mcp.py\"]}}}", "context_mcp.py": "import json, sys\nfirst = None\ncalls = 0\nfor line in sys.stdin:\n r = json.loads(line)\n if 'id' not in r: continue\n method = r.get('method')\n if method == 'initialize':\n result = {'protocolVersion':'2025-06-18','capabilities':{'tools':{}},'serverInfo':{'name':'fixture','version':'1'}}\n elif method == 'tools/list':\n result = {'tools':[{'name':'js','description':'Check caller context','inputSchema':{'type':'object','properties':{'code':{'type':'string'}}}}]}\n elif method == 'tools/call':\n calls += 1\n meta = r['params'].get('_meta', {}).get('x-codex-turn-metadata', {})\n if isinstance(meta, str): meta = json.loads(meta)\n valid = all(isinstance(meta.get(key), str) and meta[key] for key in ('session_id','turn_id'))\n if calls == 1:\n first = meta\n valid = valid\n elif calls == 2: valid = valid and meta == first\n else: valid = valid and meta['session_id'] == first.get('session_id') and meta['turn_id'] != first.get('turn_id')\n text = ('initial context received' if calls == 1 else 'same-turn context preserved' if calls == 2 else 'next-turn context rotated') if valid else 'context missing or incorrectly scoped'\n result = {'content':[{'type':'text','text':text}], 'isError':not valid}\n else: result = {}\n print(json.dumps({'jsonrpc':'2.0','id':r['id'],'result':result}),flush=True)\n"}, "prompt": "Load the context-check tool and call it twice.", "second_prompt": "Call the context-check tool once more.", "script": [{"tool": "load_tool_schemas", "arguments": {"server": "cua_repl"}}, {"tool": "mcp__cua_repl__js", "arguments": {"code": "first"}}, {"tool": "mcp__cua_repl__js", "arguments": {"code": "same"}}, {"text": "Both calls completed."}, {"tool": "mcp__cua_repl__js", "arguments": {"code": "next"}}, {"text": "Context verified."}], "assert": [{"request_contains": {"index": 2, "text": "initial context received"}}, {"request_contains": {"index": 3, "text": "same-turn context preserved"}}, {"request_contains": {"index": 5, "text": "next-turn context rotated"}}, {"events_at_most": {"match": {"type": "tool_call_finished", "name": "mcp__cua_repl__js", "is_error": true}, "count": 0}}]}+{"id":"draft-cannot-waive-pr-completion","why":"#931: real publication arms an obligation that survives draft status, rewritten todos and repeated completion attempts.","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":[{"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"}}]}+{"id":"base-failure-cannot-waive-pr-completion","why":"#931: observing failing CI on the base explains a blocker but cannot authorize task completion.","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":[{"tool":"todo_write","arguments":{"todos":[{"content":"inspect exact-head CI","status":"pending"}]}},{"tool":"bash","arguments":{"command":"git -c user.name=Fixture -c [email protected] commit --allow-empty -m change"}},{"tool":"bash","arguments":{"command":"gh run list --commit \"$(git rev-parse HEAD^)\" --json status,conclusion"}},{"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"}},{"request_contains":{"text":"failure"}}]}+{"id":"user-authorized-draft-handoff","why":"#931: the user-owned JSON control permits a draft-only outcome without claiming verified CI.","args":["--old","--goal","Create an unverified draft handoff"],"env":{"GRAFF_NO_CODEDB_GUARD":"1"},"github_fixture":{"checks":"FAILURE","runs":"failure"},"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 --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."}}],"assert":[{"event":{"type":"tool_call_finished","name":"attempt_completion","is_error":false}},{"final_text_contains":"Draft handoff \u2014 CI is not verified."}],"prompt_options":{"prAcceptance":"draft"}}+{"id":"draft-scope-does-not-waive-ready-pr-ci","why":"#931: draft-only permission does not turn failed ready-PR checks into verified completion.","args":["--old","--goal","Deliver a PR with passing current-head CI"],"env":{"GRAFF_NO_CODEDB_GUARD":"1"},"github_fixture":{"checks":"FAILURE","runs":"none"},"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":"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":"draft"}}+{"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."}]}diff --git a/scripts/eval-tier2.py b/scripts/eval-tier2.pyindex a50fbf00..b18dfa83 100644--- a/scripts/eval-tier2.py+++ b/scripts/eval-tier2.py@@ -20,6 +20,8 @@ at a real provider to run the same cases against one.A case can send structured setup controls with `controls_before_prompt`, suchas selecting a local vision model before its first user message.+`prompt_options` supplies explicit user-request fields; `github_fixture` installs+a local-only GitHub CLI with scripted head/check evidence.Assertions a case can make:@@ -63,6 +65,7 @@ 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+from github_fixture import prepare as prepare_githubdef load_cases() -> list[dict[str, Any]]:@@ -153,6 +156,8 @@ def execute(case: dict[str, Any], graff: str, port: int,["git", "worktree", "add", "--detach", "nested"],]:subprocess.run(command, cwd=workspace, env=env, check=True, capture_output=True)+ if "github_fixture" in case:+ prepare_github(pathlib.Path(workspace), env, case["github_fixture"])# A genuinely live second graff in the same workspace, for #469# presence cases: the checkpoint only exists while a co-resident# session does, and a real peer announces (and probes) better than@@ -178,7 +183,7 @@ def execute(case: dict[str, Any], graff: str, port: int,argv += list(case.get("args", []))stdin_lines = [json.dumps(control) for control in case.get("controls_before_prompt", [])]- stdin_lines.append(json.dumps({"type": "user", "text": case["prompt"]}))+ stdin_lines.append(json.dumps({"type": "user", "text": case["prompt"], **case.get("prompt_options", {})}))for control in case.get("controls_after_turn", []):stdin_lines.append(json.dumps(control))if case.get("second_prompt"):diff --git a/scripts/eval/github_fixture.py b/scripts/eval/github_fixture.pynew file mode 100644index 00000000..5d586c39--- /dev/null+++ b/scripts/eval/github_fixture.py@@ -0,0 +1,54 @@+"""Local-only GitHub CLI fixture for production dispatch regressions."""+import json+import os+import shutil+import subprocess+import sys++GH = r'''+import json, pathlib, subprocess, sys+root=pathlib.Path(__file__).resolve().parent.parent+state=json.loads((root/'gh-state.json').read_text())+args=sys.argv[1:]+with (root/'gh-argv.jsonl').open('a') as f:f.write(json.dumps(args)+'\n')+head=subprocess.check_output(['GIT_EXE','rev-parse','HEAD'],cwd=root,text=True).strip()+if args[:2]==['run','list']:+ if state.get('unavailable'):sys.exit(1)+ sha=args[args.index('--commit')+1]+ status=state.get('runs','success') if sha==state['initial_head'] else state.get('new_runs','failure')+ if status=='malformed': print('invalid');sys.exit()+ if status=='none': print('[]');sys.exit()+ print(json.dumps([{'status':'queued' if status=='pending' else 'completed','conclusion':None if status=='pending' else status}]))+elif args[:1]==['api']:+ print(state.get('remote_head', head))+elif args[:2]==['pr','view']:+ remote=state.get('remote_head',head)+ status=state.get('checks','PENDING')+ checks=[] if status=='NONE' else [{'state':status}]+ print(json.dumps({'headRefOid':remote,'isDraft':state.get('draft',False),'body':'## Verification\nLocal tests passed.','statusCheckRollup':checks}))+elif args[:2] in (['pr','create'],['pr','ready']):+ with (root/'mutations.jsonl').open('a') as f:f.write(json.dumps(args)+'\n')+ if '--draft' in args:state['draft']=True+ if args[:2]==['pr','ready']:state['draft']=False+ (root/'gh-state.json').write_text(json.dumps(state))+ print('https://example.invalid/pull/1')+else: sys.exit(88)+'''+++def prepare(work, env, state):+ bindir = work / "bin"+ bindir.mkdir(exist_ok=True)+ gh = bindir / "gh"+ gh.write_text(f"#!{sys.executable}\n" + GH.replace("GIT_EXE", shutil.which("git")))+ gh.chmod(0o755)+ subprocess.run(["git", "init", "-q", "-b", "fixture"], cwd=work, check=True, timeout=10)+ subprocess.run(["git", "-c", "user.name=Fixture", "-c", "[email protected]",+ "commit", "-q", "--allow-empty", "-m", "fixture"], cwd=work, check=True, timeout=10)+ head = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=work, text=True, timeout=10).strip()+ fixture = dict(initial_head=head, **state)+ if fixture.get("remote_head") == "initial":+ fixture["remote_head"] = head+ (work / "gh-state.json").write_text(json.dumps(fixture))+ (work / "notes.md").write_text("## Verification\nLocal regression passed.\n")+ env["PATH"] = str(bindir) + os.pathsep + env["PATH"]diff --git a/scripts/regression-release-297.py b/scripts/regression-release-297.pyindex d656a52c..f3b64f37 100644--- a/scripts/regression-release-297.py+++ b/scripts/regression-release-297.py@@ -21,35 +21,7 @@ sys.path.insert(0, str(ROOT / "scripts" / "eval"))from mock_model import ScriptedModelfrom process_guard import run as bounded_run-GH = r'''-import json, pathlib, subprocess, sys-root=pathlib.Path(__file__).resolve().parent.parent-state=json.loads((root/'gh-state.json').read_text())-args=sys.argv[1:]-with (root/'gh-argv.jsonl').open('a') as f:f.write(json.dumps(args)+'\n')-head=subprocess.check_output(['GIT_EXE','rev-parse','HEAD'],cwd=root,text=True).strip()-if args[:2]==['run','list']:- if state.get('unavailable'):sys.exit(1)- sha=args[args.index('--commit')+1]- status=state.get('runs','success') if sha==state['initial_head'] else state.get('new_runs','failure')- if status=='malformed': print('invalid');sys.exit()- if status=='none': print('[]');sys.exit()- print(json.dumps([{'status':'queued' if status=='pending' else 'completed','conclusion':None if status=='pending' else status}]))-elif args[:1]==['api']:- print(state.get('remote_head', head))-elif args[:2]==['pr','view']:- remote=state.get('remote_head',head)- status=state.get('checks','PENDING')- checks=[] if status=='NONE' else [{'state':status}]- print(json.dumps({'headRefOid':remote,'isDraft':state.get('draft',False),'body':'## Verification\nLocal tests passed.','statusCheckRollup':checks}))-elif args[:2] in (['pr','create'],['pr','ready']):- with (root/'mutations.jsonl').open('a') as f:f.write(json.dumps(args)+'\n')- if '--draft' in args:state['draft']=True- if args[:2]==['pr','ready']:state['draft']=False- (root/'gh-state.json').write_text(json.dumps(state))- print('https://example.invalid/pull/1')-else: sys.exit(88)-'''+from github_fixture import GHdef tool(command):@@ -272,7 +244,7 @@ def main():run_case(args.graff, "body flag cannot turn non-draft into draft", [tool("gh pr create --title fixture --body '--draft'"), {"text": "Blocked."}], {"runs": "failure"})run_case(args.graff, "local-only and repeated completion cannot pass PR CI", [tool(create), completion(), completion(), {"text": "CI remains unverified."}], {"runs": "none"}, expected_mutations=1, refused=2, resume_check=True)run_case(args.graff, "fresh passing remote head completes", [tool(create), completion()], {"checks": "SUCCESS"}, expected_mutations=1, expected_final="Verification complete.")- run_case(args.graff, "draft handoff is explicitly unverified", [tool(create + " --draft"), completion("Handing off the draft.")], {"runs": "failure"}, expected_mutations=1, expected_final="Draft handoff")+ run_case(args.graff, "draft handoff needs explicit scope", [tool(create + " --draft"), completion("Handing off the draft."), {"text": "Draft remains unverified."}], {"runs": "failure"}, expected_mutations=1, refused=1)commit = "git -c user.name=Fixture -c [email protected] commit --allow-empty -m next"run_case(args.graff, "ready refreshes changed head", [tool(create), tool(commit), tool("gh pr ready"), {"text": "New head needs CI."}], {"checks": "FAILURE"}, expected_mutations=1)run_case(args.graff, "passing old remote head is not local new head", [tool(create), tool(commit), completion(), {"text": "Push and verify the new head."}], {"checks": "SUCCESS", "remote_head": "initial"}, expected_mutations=1, refused=1)diff --git a/scripts/test-pr-completion-acp.py b/scripts/test-pr-completion-acp.pynew file mode 100644index 00000000..58bef4ab--- /dev/null+++ b/scripts/test-pr-completion-acp.py@@ -0,0 +1,137 @@+#!/usr/bin/env python3+"""Real ACP user controls, publication and goal state against local-only fixtures."""+import argparse+import json+import os+from pathlib import Path+import queue+import signal+import subprocess+import sys+import tempfile+import threading+import time+sys.path.insert(0, str(Path(__file__).resolve().parent / 'eval'))+from github_fixture import prepare+from mock_model import ScriptedModel+++def tool(name, **arguments):+ return {'tool': name, 'arguments': arguments}+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--graff', default='zig-out/bin/graff')+ parser.add_argument('--only-default', action='store_true')+ parser.add_argument('--evidence', type=Path)+ args = parser.parse_args()+ binary = str(Path(args.graff).resolve())+ attempt = tool('attempt_completion', result='Draft handoff.')+ model = ScriptedModel([+ tool('todo_write', todos=[{'content': 'inspect exact-head CI', 'status': 'pending'}]),+ tool('bash', command='gh pr create --draft --title fixture --body-file notes.md'),+ tool('todo_write', todos=[{'content': 'provide draft handoff', 'status': 'completed'}]),+ attempt, attempt, {'text': 'CI remains unresolved.'},+ attempt,+ tool('todo_write', todos=[{'content': 'provide another handoff', 'status': 'completed'}]),+ attempt, {'text': 'New goal still requires verified CI.'},+ ])+ with tempfile.TemporaryDirectory(prefix='graff-pr-acp-') as temp:+ work = Path(temp)+ env = {k: v for k, v in os.environ.items() if not k.endswith('_API_KEY')}+ env.update(HOME=temp, LMSTUDIO_API_KEY='local', GRAFF_NO_TELEMETRY='1',+ GRAFF_FLEET='off', GRAFF_NO_SMOLIFY='1', GRAFF_NO_CODEDB_GUARD='1')+ prepare(work, env, {'checks': 'FAILURE', 'runs': 'failure'})+ model.start(1234)+ proc = None+ all_events = []+ try:+ proc = subprocess.Popen([binary, 'acp', '--model', 'lmstudio', '--old', '--yolo'],+ cwd=temp, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL, text=True, start_new_session=True)+ events = queue.Queue()+ def reader():+ for line in proc.stdout:+ try: events.put(json.loads(line))+ except ValueError: pass+ events.put(None)+ threading.Thread(target=reader, daemon=True).start()+ next_id = 0+ def call(method, params):+ nonlocal next_id+ next_id += 1+ proc.stdin.write(json.dumps(dict(jsonrpc='2.0', method=method, params=params, id=next_id))+'\n')+ proc.stdin.flush()+ deadline = time.monotonic()+40+ updates = []+ while True:+ value = events.get(timeout=max(.01, deadline-time.monotonic()))+ assert value is not None, 'ACP worker exited before replying'+ all_events.append(value)+ if value.get('id') == next_id:+ assert 'error' not in value, value+ return value, updates+ updates.append(value)+ call('initialize', {'protocolVersion': 1})+ session, _ = call('session/new', {})+ sid = session['result']['sessionId']+ def prompt(text):+ return call('session/prompt', {'sessionId': sid, 'prompt': [{'type': 'text', 'text': text}]})+ def saved_goal():+ saves = list((work/'.graff/sessions').glob('*.session.json'))+ assert saves, 'ACP did not save its session'+ current = max(saves, key=lambda p: p.stat().st_mtime_ns)+ return json.loads(current.read_text())['goal']+ prompt('/goal Deliver a PR with passing current-head CI')+ assert not model.requests, 'Slash goal command was sent to the model'+ prompt('Run the publication fixture and complete the task.')+ assert saved_goal()['status'] == 'active', saved_goal()+ assert 'completion deferred: current-head PR verification' in json.dumps(model.requests[-1])+ print('PASS ACP default: failed draft, replaced checklist, repeated completion leave the goal active', flush=True)+ if args.only_default:+ return+ before = len(model.requests)+ _, updates = prompt('/pr-acceptance draft')+ assert len(model.requests) == before, 'Scope command was sent to the model'+ assert 'draft handoff authorized' in json.dumps(updates), updates+ prompt('Complete the explicitly authorized draft-only handoff.')+ assert saved_goal()['status'] == 'complete', saved_goal()+ print('PASS ACP explicit draft scope permits only the authorized goal to complete', flush=True)+ prompt('/goal Deliver another verified PR')+ prompt('Complete this new task.')+ assert saved_goal()['status'] == 'active', saved_goal()+ _, updates = prompt('/pr-acceptance')+ assert 'PR acceptance: verified.' in json.dumps(updates), updates+ print('PASS ACP new goal cannot reuse the prior draft scope', flush=True)+ prompt('/save acceptance-fixture')+ prompt('/pr-acceptance draft')+ prompt('/resume acceptance-fixture')+ _, updates = prompt('/pr-acceptance')+ assert 'PR acceptance: verified.' in json.dumps(updates), updates+ prompt('/pr-acceptance draft')+ prompt('/new')+ _, updates = prompt('/pr-acceptance')+ assert 'PR acceptance: verified.' in json.dumps(updates), updates+ print('PASS ACP resume and new conversation reset draft-only scope', flush=True)+ finally:+ if args.evidence:+ args.evidence.mkdir(parents=True, exist_ok=True)+ (args.evidence/'acp-events.json').write_text(json.dumps(all_events, indent=2))+ (args.evidence/'model-requests.json').write_text(json.dumps(model.requests, indent=2))+ for name in ('traces', 'trajectories'):+ source = work/'.graff'/name+ if source.exists():+ import shutil+ shutil.copytree(source, args.evidence/name, dirs_exist_ok=True)+ if proc:+ try: os.killpg(proc.pid, signal.SIGKILL)+ except ProcessLookupError: pass+ proc.wait(timeout=3)+ for pipe in (proc.stdin, proc.stdout):+ if pipe: pipe.close()+ model.stop()+++if __name__ == '__main__':+ main()diff --git a/src/agent.zig b/src/agent.zigindex a96517e2..45a149cd 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -126,6 +126,7 @@ pub const Agent = struct {sys_override: ?[]const u8 = null, // per-child custom prompt or transient isolated-review basetask_prompt: ?[]const u8 = null, // a subagent's mandate, pinned once before the first history rewrite so compaction can restate it verbatim (recentContextStart can keep no verbatim suffix for a child - its only clean user turn is index 0)pr_verification: @import("pr_verify.zig").State = .unused,+ pr_draft_scope: ?@import("pr_acceptance.zig").Scope = null,agent_cwd: ?[]const u8 = null, // subagent-only (#276 P0-1): absolute path of this agent's isolated git worktree, threaded through ToolCtx per tool call instead of a process-wide chdir — parallel siblings each keep their owntools_used: trace.ToolSink = .{}, // external tool calls this agent made (per turn for the root)tool_calls_this_turn: u64 = 0,diff --git a/src/command_catalog.zig b/src/command_catalog.zigindex b38ce23a..c9cc76e4 100644--- a/src/command_catalog.zig+++ b/src/command_catalog.zig@@ -37,6 +37,7 @@ pub const commands = [_]Item{.{ .name = "/new", .desc = "start a fresh autosaved session" },.{ .name = "/rename", .usage = "/rename <title>", .desc = "set the current session title" },.{ .name = "/goal", .usage = "/goal [30m] [text|pause|resume|status|clear]", .desc = "set a standing objective and work it autonomously; an optional 30s/30m/2h budget paces the run; pause/resume steering, status shows state, clear removes it" },+ .{ .name = "/pr-acceptance", .usage = "/pr-acceptance [verified|draft]", .desc = "choose whether this conversation and goal requires verified PR checks or permits an unverified draft handoff" },.{ .name = "/loop", .usage = "/loop [30m] <prompt>", .desc = "the same autonomous run as /goal, without adopting a standing objective" },.{ .name = "/schedule", .usage = "/schedule <30s|5m|2h> <prompt>", .desc = "fire a prompt later; delay tokens match /loop (not a standing goal)" },.{ .name = "/adapter", .usage = "/adapter send <text>|inbox", .desc = "channel-worker outbox / inbox (JSONL protocol; Discord/Slack fronts later)" },diff --git a/src/commands_session.zig b/src/commands_session.zigindex dd56afe9..fa022ad6 100644--- a/src/commands_session.zig+++ b/src/commands_session.zig@@ -67,6 +67,7 @@ const setTerminalTitle = title_mod.setTerminalTitle;/// after "context cleared" (#178).pub fn resetConversationSteering(root: *Agent) void {root.goal = null;+ root.pr_draft_scope = null;root.completion_gate_armed = false; // a dropped goal re-arms the completion double-check (#318)root.todos_dirty = false; // the conversation's checklist dies with it; nothing survives as /loop evidence (#318)root.ultracode_mode = false;@@ -91,6 +92,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,_ = keys; // unused in this file's command set; kept for a uniform tryHandle signature// #554: claims /snapshot, and /rewind ONLY when its argument is a snapshot// id — a numeric /rewind falls through to the conversation rewind below.+ if (try @import("pr_acceptance.zig").slash(root, line, out)) return true;if (try commands_sandbox.tryHandle(root, arena, line, out)) return true;if (try commands_trajectory.tryHandle(root, arena, line, out)) return true;if (try @import("commands_experiment.zig").tryHandle(root, arena, line, out)) return true;@@ -180,7 +182,8 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,return true;}const open = goal_state.openCount(root.todos.items, goal_state.currentEpoch(root.goal));- root.goal = null; // the checklist PARKS with the goal (#318): items keep their epoch and stay in the session, they just stop being current+ root.goal = null; // the checklist parks with its old epoch+ root.pr_draft_scope = null;goal_state.resetCompletionGate(root);root.goal_note_fp = 0;prompts.pinStandingGoal(root, arena);diff --git a/src/help.zig b/src/help.zigindex 2c947e8e..d8150d2f 100644--- a/src/help.zig+++ b/src/help.zig@@ -30,7 +30,7 @@ const peers_blurb =pub const sections = [_]Section{.{ .title = "getting around", .names = &.{ "/new", "/clear", "/resume", "/save", "/sessions", "/workspace", "/experiment", "/rename", "/rewind", "/snapshot", "/teleport" } },.{ .title = "the model", .names = &.{ "/model", "/models", "/effort", "/reasoning", "/fast", "/thinking", "/keepcontext", "/fallback", "/routes" } },- .{ .title = "working autonomously", .names = &.{ "/goal", "/loop", "/schedule", "/review", "/plan", "/todo", "/jobs", "/ultracode", "/strict", "/yolo", "/never" } },+ .{ .title = "working autonomously", .names = &.{ "/goal", "/pr-acceptance", "/loop", "/schedule", "/review", "/plan", "/todo", "/jobs", "/ultracode", "/strict", "/yolo", "/never" } },.{ .title = "talking to other graffs", .names = &.{ "/tell", "/peek", "/adapter" }, .blurb = peers_blurb },.{ .title = "your setup", .names = &.{ "/login", "/key", "/cost", "/usage", "/version", "/update", "/privacy", "/mcp", "/import-claude", "/skills", "/plugins", "/agents", "/hooks", "/tools", "/fleet" } },.{ .title = "context & history", .names = &.{ "/compact", "/btw", "/doctor", "/debug", "/cache", "/trace", "/trajectory" } },diff --git a/src/json_controls.zig b/src/json_controls.zigindex 3e13205c..c20a77de 100644--- a/src/json_controls.zig+++ b/src/json_controls.zig@@ -47,10 +47,20 @@ pub fn applyToolKnobs(obj: std.json.ObjectMap) void {}}-/// Turn-scoped JSON options: tool ceilings plus native image parts. False-/// means image validation already emitted the request error.+/// User-request options: tool ceilings, native images, and explicit PR scope.+/// False means validation already emitted the request error.pub fn applyTurnOptions(root: *Agent, obj: std.json.ObjectMap) bool {if (!remote_images.stage(root, obj)) return false;+ if (obj.get("prAcceptance")) |value| {+ if (value != .string) {+ root.emit(.{ .type = "error", .message = "prAcceptance must be verified or draft" });+ return false;+ }+ @import("pr_acceptance.zig").set(root, value.string) catch {+ root.emit(.{ .type = "error", .message = "prAcceptance must be verified or draft" });+ return false;+ };+ }applyToolKnobs(obj);return true;}diff --git a/src/main.zig b/src/main.zigindex 711be041..0a6af542 100644--- a/src/main.zig+++ b/src/main.zig@@ -52,7 +52,7 @@ test {_ = .{ @import("clipboard_native.zig"), @import("clipboard_edge_tests.zig"), @import("clipboard_failure_tests.zig"), @import("process_runner_clipboard_tests.zig") };_ = @import("server_orphan.zig");_ = @import("repo_transaction.zig");- _ = .{ @import("pr_command.zig"), @import("pr_evidence.zig"), @import("pr_verify.zig") };+ _ = .{ @import("pr_command.zig"), @import("pr_evidence.zig"), @import("pr_verify.zig"), @import("pr_acceptance.zig") };_ = @import("argstream_citation_tests.zig"); // unit_tests' root is main.zig only, so reference every split-out module or its tests silently never run_ = @import("codex_node_repl.zig");_ = pricing;diff --git a/src/pr_acceptance.zig b/src/pr_acceptance.zignew file mode 100644index 00000000..5097a2f8--- /dev/null+++ b/src/pr_acceptance.zig@@ -0,0 +1,58 @@+//! Draft-only completion is an explicit user control, never a model claim.+//! Permission belongs to this conversation and goal; it is not persisted.+const std = @import("std");+const Agent = @import("agent.zig").Agent;+const goals = @import("goal_state.zig");+const headers = @import("http_headers.zig");++pub const Scope = struct {+ session: []const u8,+ epoch: u64,++ pub fn matches(self: Scope, session: []const u8, epoch: u64) bool {+ return self.epoch == epoch and std.mem.eql(u8, self.session, session);+ }+};++pub fn allowsDraft(root: *const Agent) bool {+ const scope = root.pr_draft_scope orelse return false;+ return scope.matches(headers.sessionId(root.io), goals.currentEpoch(root.goal));+}++/// Called only by the user-facing slash / JSON input paths, not tool dispatch.+pub fn set(root: *Agent, mode: []const u8) !void {+ if (std.mem.eql(u8, mode, "verified")) {+ root.pr_draft_scope = null;+ } else if (std.mem.eql(u8, mode, "draft")) {+ root.pr_draft_scope = .{+ .session = try root.arena.dupe(u8, headers.sessionId(root.io)),+ .epoch = goals.currentEpoch(root.goal),+ };+ } else return error.InvalidPrAcceptance;+ goals.resetCompletionGate(root);+}++pub fn slash(root: *Agent, line: []const u8, out: *std.Io.Writer) !bool {+ const prefix = "/pr-acceptance";+ if (!std.mem.startsWith(u8, line, prefix) or (line.len > prefix.len and line[prefix.len] != ' ' and line[prefix.len] != '\t')) return false;+ const mode = std.mem.trim(u8, line[prefix.len..], " \t");+ if (mode.len != 0) set(root, mode) catch {+ try out.writeAll("usage: /pr-acceptance [verified|draft]\n");+ try out.flush();+ return true;+ };+ try out.writeAll(if (allowsDraft(root))+ "PR acceptance: draft handoff authorized for this conversation and goal. CI remains unverified. This choice resets on resume, a new conversation, or a new goal.\n"+ else+ "PR acceptance: verified. Draft publication does not fulfill the task; current-head checks must pass.\n");+ try out.flush();+ return true;+}++test "draft acceptance cannot transfer to another conversation or goal" {+ const scope = Scope{ .session = "first", .epoch = 7 };+ try std.testing.expect(scope.matches("first", 7));+ try std.testing.expect(!scope.matches("second", 7));+ try std.testing.expect(!scope.matches("first", 8));+ try std.testing.expect(!scope.matches("first", 0));+}diff --git a/src/pr_verify.zig b/src/pr_verify.zigindex 7fc6ad4d..959182c9 100644--- a/src/pr_verify.zig+++ b/src/pr_verify.zig@@ -43,9 +43,9 @@ pub fn arm(agent: *Agent, target: evidence.Target, match_local: bool) !void {agent.pr_verification = .pending;}-pub fn decision(receipt: evidence.Receipt, local: ?[]const u8) State {+pub fn decision(receipt: evidence.Receipt, local: ?[]const u8, draft_authorized: bool) State {if (local) |sha| if (!std.mem.eql(u8, sha, receipt.head)) return .pending;- if (receipt.draft) return .draft;+ if (receipt.draft) return if (draft_authorized) .draft else .pending;return if (receipt.status == .passed) .passed else .pending;}@@ -62,10 +62,10 @@ pub fn completionGate(agent: *Agent) ?[]const u8 {var result: State = .passed;for (records) |record| {if (!std.mem.eql(u8, record.session, @import("http_headers.zig").sessionId(agent.io))) continue;- const receipt = evidence.pr(agent.gpa, agent.io, agent.arena, record.target) catch return "completion deferred: current-head PR checks could not be observed. Local tests and completed todos are not remote CI evidence; retry the lookup or leave an explicit draft handoff.";+ const receipt = evidence.pr(agent.gpa, agent.io, agent.arena, record.target) catch return "completion deferred: current-head PR checks could not be observed. Local tests and completed todos are not remote CI evidence; retry the lookup. Draft-only completion requires explicit user authorization.";const local = if (record.match_local) evidence.localHead(agent.gpa, agent.io, agent.arena, record.target) catch return "completion deferred: local publication head could not be resolved" else null;- switch (decision(receipt, local)) {- .pending, .unused => return "completion deferred: current-head PR verification is pending, failed, missing, or stale. Inspect the PR checks and finish CI verification; repeating attempt_completion cannot waive it. An explicit draft PR can be handed off as unverified.",+ switch (decision(receipt, local, @import("pr_acceptance.zig").allowsDraft(agent))) {+ .pending, .unused => return "completion deferred: current-head PR verification is pending, failed, missing, or stale. Inspect the PR checks and finish CI verification; repeating attempt_completion cannot waive it. Draft publication and base-branch failures do not waive verification. Only the user can authorize a draft-only scope with /pr-acceptance draft.",.draft => result = .draft,.passed => {},}@@ -76,10 +76,10 @@ pub fn completionGate(agent: *Agent) ?[]const u8 {test "#853 a changed head or a second completion attempt cannot reuse a passing receipt" {const receipt = evidence.Receipt{ .head = "new", .status = .passed };- try std.testing.expectEqual(State.pending, decision(receipt, "old"));- try std.testing.expectEqual(State.passed, decision(receipt, "new"));- for (0..2) |_| try std.testing.expectEqual(State.pending, decision(.{ .head = "new", .status = .pending }, "new"));- try std.testing.expectEqual(State.draft, decision(.{ .head = "new", .status = .failed, .draft = true }, "new"));+ try std.testing.expectEqual(State.pending, decision(receipt, "old", false));+ try std.testing.expectEqual(State.passed, decision(receipt, "new", false));+ for (0..2) |_| try std.testing.expectEqual(State.pending, decision(.{ .head = "new", .status = .pending }, "new", false));+ try std.testing.expectEqual(State.draft, decision(.{ .head = "new", .status = .failed, .draft = true }, "new", true));}pub fn hasObligation(agent: *const Agent) bool {@@ -108,3 +108,13 @@ test "PR obligations isolate conversations and cannot use restored IDs as paths"try std.testing.expect(std.mem.indexOf(u8, hostile, "..") == null);try std.testing.expectEqualStrings(std.fs.path.dirname(first).?, std.fs.path.dirname(hostile).?);}++test "draft PRs require user-authorized scope even with passing or base-failing checks" {+ for ([_]@import("pr_publish.zig").HeadStatus{ .passed, .failed, .pending, .none, .unknown }) |status| {+ const receipt = evidence.Receipt{ .head = "new", .status = status, .draft = true };+ try std.testing.expectEqual(State.pending, decision(receipt, "new", false));+ try std.testing.expectEqual(State.draft, decision(receipt, "new", true));+ try std.testing.expectEqual(State.pending, decision(receipt, "old", true));+ }+ try std.testing.expectEqual(State.pending, decision(.{ .head = "new", .status = .failed }, "new", true));+}diff --git a/src/schema_protocol.zig b/src/schema_protocol.zigindex fab95cdb..f77764a4 100644--- a/src/schema_protocol.zig+++ b/src/schema_protocol.zig@@ -36,7 +36,7 @@ pub const flags =pub const json =\\{\\ "transport": "newline-delimited JSON over stdin/stdout (--json)",- \\ "request": "one JSON object per line: {\"type\":\"user\",\"text\":\"...\",\"images\":[{\"type\":\"image_url\",\"url\":\"https://...\"},{\"type\":\"image_base64\",\"media_type\":\"image/png\",\"data\":\"...\"}]} sends a native multimodal user turn (images optional, max 16); {\"type\":\"review\",\"text\":\"target or instructions\"} runs one isolated read-only review turn with fresh model-visible history and no edits, delegation, workflows, or web access; {\"type\":\"answer\",\"text\":\"...\",\"cancelled\":false,\"call_id\":\"optional\"} answers an active ask_user event; {\"type\":\"cancel\"} interrupts an active turn; {\"type\":\"set_system_prompt\",\"text\":\"...\",\"append\":false} replaces (or with append=true extends) the system prompt between turns and acks with a system_prompt event; {\"type\":\"set_model\",\"model\":\"gpt-5.5\",\"provider\":\"codex\"}, {\"type\":\"compact\"}, {\"type\":\"set_mode\",\"mode\":\"plan|normal\"}, and {\"type\":\"set_agent\",\"id\":\"reviewer\"}, {\"type\":\"set_effort\",\"level\":\"low|medium|high|xhigh|max|ultra\"}, {\"type\":\"set_fast\",\"on\":true}, and {\"type\":\"set_ultracode\",\"on\":true} are live control requests acked by model/compact/mode/agent/effort/fast/ultracode events. For compatibility, set_model also accepts legacy {\"name\":\"provider model|model\"}. NOTE: the system prompt heads the KV-cached prefix, so any mutation invalidates the cache for the whole conversation (per Manus context-engineering lessons) — set it at spawn when possible and mutate only at task boundaries",+ \\ "request": "one JSON object per line: {\"type\":\"user\",\"text\":\"...\",\"images\":[{\"type\":\"image_url\",\"url\":\"https://...\"},{\"type\":\"image_base64\",\"media_type\":\"image/png\",\"data\":\"...\"}]} sends a native multimodal user turn (images optional, max 16). Optional prAcceptance is verified (default) or draft: an explicit user choice for the current conversation and goal, reset by resume/new conversation/new goal; draft permits an unverified handoff, never passing CI. Only user input may set this field; {\"type\":\"review\",\"text\":\"target or instructions\"} runs one isolated read-only review turn with fresh model-visible history and no edits, delegation, workflows, or web access; {\"type\":\"answer\",\"text\":\"...\",\"cancelled\":false,\"call_id\":\"optional\"} answers an active ask_user event; {\"type\":\"cancel\"} interrupts an active turn; {\"type\":\"set_system_prompt\",\"text\":\"...\",\"append\":false} replaces (or with append=true extends) the system prompt between turns and acks with a system_prompt event; {\"type\":\"set_model\",\"model\":\"gpt-5.5\",\"provider\":\"codex\"}, {\"type\":\"compact\"}, {\"type\":\"set_mode\",\"mode\":\"plan|normal\"}, and {\"type\":\"set_agent\",\"id\":\"reviewer\"}, {\"type\":\"set_effort\",\"level\":\"low|medium|high|xhigh|max|ultra\"}, {\"type\":\"set_fast\",\"on\":true}, and {\"type\":\"set_ultracode\",\"on\":true} are live control requests acked by model/compact/mode/agent/effort/fast/ultracode events. For compatibility, set_model also accepts legacy {\"name\":\"provider model|model\"}. NOTE: the system prompt heads the KV-cached prefix, so any mutation invalidates the cache for the whole conversation (per Manus context-engineering lessons) — set it at spawn when possible and mutate only at task boundaries",\\ "score_request": "{\"type\":\"score\",\"prompt_sha\":\"<16 hex>\",\"score\":0.7,\"notes\":\"...\",\"parent_sha\":\"<16 hex, optional>\"} appends an evaluation record for an agent/prompt variant to this run's file under .graff/trajectories (the aggregate append-only DGM-style archive; prompt_sha = first 8 bytes of SHA-256 of the system prompt, hex; parent_sha records which prompt this variant was mutated from — the lineage edge DGM parent selection counts children with) and acks with a score event",\\ "sequencing": "every event object below carries a monotonic per-session \"seq\" as its FIRST field: 1-based, gap-free, one id per emitted line. It survives a resume - the counter is persisted with the conversation as event_seq and restored by --resume, so a REPLACEMENT process continues the numbering instead of reissuing ids a consumer already saw. `graff serve` forwards the child's seq unchanged and uses it for ?from=N replay",\\ "events": [diff --git a/src/session.zig b/src/session.zigindex 17962533..cfa3094f 100644--- a/src/session.zig+++ b/src/session.zig@@ -494,6 +494,7 @@ pub fn loadSession(root: *Agent, keys: *Keys, arena: Allocator, name: []const u8try @import("session_catalog.zig").restore(root, obj);try root.ensureRootTools(root.provider.kind);const compaction_window = try @import("compaction_window.zig").State.restore(arena, obj, msgs.items);+ root.pr_draft_scope = null; // draft-only scope must be authorized again after resumeroot.messages = msgs;root.compaction_window = compaction_window;// Repair histories written by older builds where a Responses