graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Retain current-head PR check observations
justrach70c74d256849
diff --git a/docs/adr/0123-pr-check-observations-retain-the-rollup.md b/docs/adr/0123-pr-check-observations-retain-the-rollup.mdnew file mode 100644index 00000000..8877596f--- /dev/null+++ b/docs/adr/0123-pr-check-observations-retain-the-rollup.md@@ -0,0 +1,30 @@+# 0123. PR check observations retain the rollup++Status: accepted 2026-09-15++## Context++Current-head verification rejected failed checks, but retained only an aggregate+state. It discarded the check identities and gave the same explanation for+pending, failed, missing and stale evidence (#853). A local schema check could+therefore be mistaken for evidence about a different CI job.++## Decision++Keep the complete bounded remote check rollup with its head in a private local+receipt for each conversation's publication target. Retire the previous receipt+before observing again, including when the lookup fails or exits nonzero after+printing apparently valid output. Failure to retain evidence defers completion.+The receipt is diagnostic, never cached acceptance authority: each completion+attempt still fetches fresh remote evidence and compares the local head where+required. Check names and outcomes appear in deferred completion results, with+bounded display and the full rollup retained locally. Distinguish pending,+failed, missing, unknown, draft and stale-head reasons.++## Verification++`scripts/test-pr-check-receipts.py` drives production publication and completion+through an offline model and GitHub fixture. It covers named mixed check results,+repeated completion with completed todos, pending/missing/unknown observations,+a different remote head, unavailable lookups, failed exit with green output,+and passing evidence. It checks actual tool events against the retained receipt.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 6969e6b4..3ed01fbf 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -133,6 +133,8 @@ record only when you need the evidence or the edge cases.| [0122](0122-one-session-navigation-surface.md) | Open chats use the expanded sidebar or collapsed top tabs, preserving drafts and groups; focused mode keeps a compact composer and accessible settings. |+| [0123](0123-pr-check-observations-retain-the-rollup.md) | PR completion retains named current-head check observations locally; diagnostic receipts never replace fresh verification. |+## When to write oneWrite an ADR when a decision is load-bearing and non-obvious: it was reacheddiff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonlindex e9d7fe2c..19658e25 100644--- a/evals/harness_behavior.jsonl+++ b/evals/harness_behavior.jsonl@@ -102,3 +102,4 @@{"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":"current-head-receipt-names-actual-checks","why":"#853: preserve the actual named CI outcomes; local schema success cannot replace failing packed SDK evidence.","args":["--old","--goal","Deliver a PR with passing current-head CI"],"env":{"GRAFF_NO_CODEDB_GUARD":"1"},"github_fixture":{"runs":"none","check_rollup":[{"name":"schema drift","status":"COMPLETED","conclusion":"SUCCESS"},{"name":"packed SDK","status":"COMPLETED","conclusion":"FAILURE"},{"context":"platform contract","state":"PENDING"}]},"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":"failed: CI reported a failure"}},{"request_contains":{"text":"schema drift"}},{"request_contains":{"text":"packed SDK"}},{"request_contains":{"text":"platform contract"}}]}diff --git a/scripts/eval/github_fixture.py b/scripts/eval/github_fixture.pyindex d7f5c239..fe558b77 100644--- a/scripts/eval/github_fixture.py+++ b/scripts/eval/github_fixture.py@@ -43,8 +43,9 @@ elif args[:2]==['pr','view']:if selector.startswith('https://') and '/pull/' in selector: url=selector.rsplit('/pull/',1)[0]remote=state.get('remote_head',head)status=state.get('checks','PENDING')- checks=[] if status=='NONE' else [{'state':status}]+ checks=state.get('check_rollup', [] if status=='NONE' else [{'context':'fixture CI','state':status}])print(json.dumps({'headRefOid':remote,'isDraft':state.get('draft',False),'body':'## Verification\nLocal tests passed.','statusCheckRollup':checks,'headRefName':state.get('head_branch','fixture'),'number':1,'url':url+'/pull/1','headRepository':{'nameWithOwner':state.get('head_repo',url.split('://',1)[-1].split('/',1)[1])}}))+ sys.exit(state.get('pr_exit',0))elif args[:2] in (['pr','create'],['pr','ready'],['pr','edit'],['issue','edit']):with (root/'mutations.jsonl').open('a') as f:f.write(json.dumps(args)+'\n')if '--draft' in args:state['draft']=Truediff --git a/scripts/test-pr-check-receipts.py b/scripts/test-pr-check-receipts.pynew file mode 100644index 00000000..1e304eb4--- /dev/null+++ b/scripts/test-pr-check-receipts.py@@ -0,0 +1,98 @@+#!/usr/bin/env python3+"""Exercise actual completion dispatch with bounded local GitHub/model fixtures."""+import argparse+import json+import os+from pathlib import Path+import shutil+import subprocess+import sys+import tempfile+sys.path.insert(0, str(Path(__file__).resolve().parent / 'eval'))+from github_fixture import prepare+from mock_model import ScriptedModel+from process_guard import run+++def tool(name, **arguments):+ return dict(tool=name, arguments=arguments)+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--graff', default='zig-out/bin/graff')+ parser.add_argument('--evidence', type=Path, required=True)+ args = parser.parse_args()+ binary = str(Path(args.graff).resolve())+ checks = [dict(name='schema drift', status='COMPLETED', conclusion='SUCCESS'),+ dict(name='packed SDK', status='COMPLETED', conclusion='FAILURE'),+ dict(context='platform contract', state='PENDING')]+ cases = [+ ('failed', dict(check_rollup=checks), 'failed: CI reported a failure'),+ ('pending', dict(checks='PENDING'), 'pending: CI has not finished'),+ ('missing', dict(checks='NONE'), 'missing: no CI checks were reported'),+ ('unknown', dict(check_rollup=None), 'unknown: CI evidence is incomplete'),+ ('stale', dict(checks='SUCCESS', remote_head='a'*40), 'stale: local and remote heads differ'),+ ('unavailable', dict(pr_unavailable=True), 'checks could not be observed'),+ ('failed-exit-green-output', dict(checks='SUCCESS', pr_exit=7), 'checks could not be observed'),+ ('passed', dict(checks='SUCCESS'), None),+ ]+ for name, state, expected in cases:+ with tempfile.TemporaryDirectory(prefix='graff-check-receipt-') 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_FLEET='off',+ GRAFF_NO_TELEMETRY='1', GRAFF_NO_SMOLIFY='1', GRAFF_NO_CODEDB_GUARD='1')+ prepare(work, env, dict(checks='SUCCESS'))+ # Publish while evidence is green, then change the current observation.+ (work/'next-state.json').write_text(json.dumps(state))+ (work/'change.py').write_text("import json,pathlib\np=pathlib.Path('gh-state.json')\ns=json.loads(p.read_text());s.update(json.loads(pathlib.Path('next-state.json').read_text()));p.write_text(json.dumps(s))\n")+ attempt = tool('attempt_completion', result='Verification complete.')+ model = ScriptedModel([+ tool('bash', command='gh pr create --title fixture --body-file notes.md'),+ tool('bash', command=f'{sys.executable} change.py'),+ tool('todo_write', todos=[dict(content='verify CI', status='completed')]),+ attempt, attempt, dict(text='Verification remains unresolved.'),+ ])+ model.start(1234)+ try:+ result = run([binary, '--json', '--old', '--yolo', '--model', 'lmstudio'],+ cwd=work, env=env, text=True, capture_output=True, timeout=90,+ input=json.dumps(dict(type='user', text='Run the publication verification fixture.'))+'\n')+ assert result.returncode == 0, result.stderr[-3000:]+ events = [json.loads(line) for line in result.stdout.splitlines() if line.startswith('{')]+ completions = [e for e in events if e.get('type') == 'tool_call_finished' and e.get('name') == 'attempt_completion']+ assert completions, events+ requests = json.dumps(model.requests)+ if expected:+ assert expected in requests, requests[-5000:]+ assert all(e.get('is_error') for e in completions), completions+ assert len(completions) >= 2, completions+ else:+ assert any(not e.get('is_error') for e in completions), completions+ files = list((work/'.graff/pr-verification').glob('*.receipt.json'))+ assert len(files) == 1, files+ receipt = json.loads(files[0].read_text())+ if state.get('pr_unavailable') or state.get('pr_exit'):+ assert receipt['observation'] == 'unavailable' and receipt['receipt'] is None, receipt+ else:+ assert receipt['receipt']['head'] == state.get('remote_head', receipt['local_head']), receipt+ if name == 'failed':+ assert json.loads(receipt['receipt']['checks_json']) == checks, receipt+ for check in ('schema drift', 'packed SDK', 'platform contract'):+ assert check in requests, check+ output = args.evidence/name+ output.mkdir(parents=True, exist_ok=True)+ (output/'events.json').write_text(json.dumps(events, indent=2))+ (output/'requests.json').write_text(json.dumps(model.requests, indent=2))+ (output/'receipt.json').write_text(json.dumps(receipt, indent=2))+ (output/'stderr.log').write_text(result.stderr)+ if (work/'.graff/traces').exists():+ shutil.copytree(work/'.graff/traces', output/'traces', dirs_exist_ok=True)+ print(f'PASS {name}: actual completion results and persisted receipt agree', flush=True)+ finally:+ model.stop()+++if __name__ == '__main__':+ main()diff --git a/src/pr_evidence.zig b/src/pr_evidence.zigindex 1cf84ac8..c174f71e 100644--- a/src/pr_evidence.zig+++ b/src/pr_evidence.zig@@ -5,7 +5,7 @@ const runner = @import("process_runner.zig");const publish = @import("pr_publish.zig");const A = std.mem.Allocator;pub const Target = struct { cwd: []const u8 = ".", repo: ?[]const u8 = null, selector: []const u8 };-pub const Receipt = struct { head: []const u8 = "", status: publish.HeadStatus = .unknown, draft: bool = false, body: []const u8 = "" };+pub const Receipt = struct { head: []const u8 = "", status: publish.HeadStatus = .unknown, draft: bool = false, body: []const u8 = "", checks_json: []const u8 = "null" };pub fn capture(gpa: A, io: std.Io, a: A, target: Target, argv: []const []const u8) ![]const u8 {var args: std.ArrayList([]const u8) = .empty;@@ -54,7 +54,7 @@ pub fn parsePr(a: A, json: []const u8) !Receipt {const body = v.object.get("body") orelse return error.InvalidReceipt;const checks = v.object.get("statusCheckRollup") orelse return error.InvalidReceipt;if (head != .string or !validSha(head.string) or draft != .bool or body != .string) return error.InvalidReceipt;- return .{ .head = head.string, .draft = draft.bool, .body = body.string, .status = checkStatus(checks) };+ return .{ .head = head.string, .draft = draft.bool, .body = body.string, .status = checkStatus(checks), .checks_json = try std.json.Stringify.valueAlloc(a, checks, .{}) };}pub fn checkStatus(checks: std.json.Value) publish.HeadStatus {@@ -111,3 +111,13 @@ test "#853 remote receipt cannot turn missing, pending, failed or partial checkstry std.testing.expectEqual(c[1], checkStatus(v));}}++test "PR receipt preserves check identities and outcomes instead of substituting aggregate green" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const checks = "[{\"name\":\"schema drift\",\"status\":\"COMPLETED\",\"conclusion\":\"SUCCESS\"},{\"name\":\"packed SDK\",\"status\":\"COMPLETED\",\"conclusion\":\"FAILURE\"},{\"context\":\"platform contract\",\"state\":\"PENDING\"}]";+ const json = try std.fmt.allocPrint(arena.allocator(), "{{\"headRefOid\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"isDraft\":false,\"body\":\"\",\"statusCheckRollup\":{s}}}", .{checks});+ const receipt = try parsePr(arena.allocator(), json);+ try std.testing.expectEqual(publish.HeadStatus.failed, receipt.status);+ try std.testing.expectEqualStrings(checks, receipt.checks_json);+}diff --git a/src/pr_verify.zig b/src/pr_verify.zigindex 959182c9..6f980ce7 100644--- a/src/pr_verify.zig+++ b/src/pr_verify.zig@@ -49,6 +49,43 @@ pub fn decision(receipt: evidence.Receipt, local: ?[]const u8, draft_authorized:return if (receipt.status == .passed) .passed else .pending;}+/// Diagnostic receipts are never read as acceptance authority. Write an+/// unavailable observation before the lookup so old green evidence is retired.+fn observe(agent: *Agent, record: Record, receipt: ?evidence.Receipt, local: ?[]const u8) !void {+ const key = try std.json.Stringify.valueAlloc(agent.arena, record.target, .{});+ var digest: [32]u8 = undefined;+ std.crypto.hash.sha2.Sha256.hash(key, &digest, .{});+ const file = try std.fmt.allocPrint(agent.arena, "{s}.{s}.receipt.json", .{ try path(agent), std.fmt.bytesToHex(digest, .lower) });+ const tx = try @import("repo_transaction.zig").Transaction.begin(agent.io, agent.arena, file);+ defer tx.end();+ const json = try std.json.Stringify.valueAlloc(agent.arena, .{+ .target = record.target,+ .observation = if (receipt != null) "observed" else "unavailable",+ .receipt = receipt,+ .local_head = local,+ }, .{});+ try tx.write(json);+}++fn deferred(a: A, receipt: evidence.Receipt, local: ?[]const u8) ![]const u8 {+ const reason = if (local != null and !std.mem.eql(u8, local.?, receipt.head))+ "stale: local and remote heads differ"+ else if (receipt.draft)+ "draft: verified readiness requires a ready PR"+ else switch (receipt.status) {+ .pending => "pending: CI has not finished",+ .failed => "failed: CI reported a failure",+ .none => "missing: no CI checks were reported",+ .unknown => "unknown: CI evidence is incomplete",+ .passed => "unresolved",+ };+ // The complete bounded rollup is retained in the local receipt; avoid+ // flooding the model context when repositories have hundreds of checks.+ var limit = @min(receipt.checks_json.len, 16 * 1024);+ while (limit < receipt.checks_json.len and limit > 0 and receipt.checks_json[limit] & 0xc0 == 0x80) limit -= 1;+ return std.fmt.allocPrint(a, "completion deferred: current-head PR verification is {s}. Remote head: {s}. Observed checks: {s}{s}. Repeating attempt_completion or completing todos cannot waive verification. Draft publication and base-branch failures do not waive verification. Only the user can authorize a draft-only scope with /pr-acceptance draft.", .{ reason, receipt.head, receipt.checks_json[0..limit], if (limit < receipt.checks_json.len) " [truncated; full checks retained in local receipt]" else "" });+}+pub fn completionGate(agent: *Agent) ?[]const u8 {if (agent.review_mode) return null;const file = path(agent) catch return "completion deferred: unable to read PR verification obligation";@@ -62,10 +99,12 @@ 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;+ observe(agent, record, null, null) catch return "completion deferred: unable to retire previous PR observation";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;+ observe(agent, record, receipt, local) catch return "completion deferred: unable to retain current PR observation";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.",+ .pending, .unused => return deferred(agent.arena, receipt, local) catch "completion deferred: unable to describe PR verification evidence",.draft => result = .draft,.passed => {},}