graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Preserve observed check failures before publication
justrach5b1e3e435470
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex c0fcd4b8..2e7cc3b2 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -85,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: Observed local checks before publication+ run: python3 scripts/test-pr-local-checks.py --graff zig-out/bin/graff --evidence /tmp/pr-local-checks+- name: Multi-turn clarification, editing and recovery workflowsrun: 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"diff --git a/docs/adr/0126-publication-retains-observed-check-failures.md b/docs/adr/0126-publication-retains-observed-check-failures.mdnew file mode 100644index 00000000..78fe3917--- /dev/null+++ b/docs/adr/0126-publication-retains-observed-check-failures.md@@ -0,0 +1,32 @@+# 0126. Publication retains observed check failures++Status: accepted 2026-09-15++## Context++A failing local check followed by a green remote observation and optimistic PR+prose could still publish a non-draft PR. Tests that injected coverage flags did+not establish that runtime publication consumed actual local results.++## Decision++The root records failures and incomplete background starts from recognized test+commands after tool execution. Records use canonical workspace paths and survive+session saves and resumes. Only a successful foreground rerun of the same command+clears its record; unrelated successful commands and rewritten prose do not.+Non-draft publication is refused while an applicable record remains unresolved.+Draft creation remains available.++A non-draft publication must occupy its own tool batch. It cannot race a check+or edit requested in the same model response.++## Consequences++This is observed-check bookkeeping, not proof that a regression test covers the+claimed behavior. The command recognizer has explicit supported forms; arbitrary+shell programs cannot be classified reliably from their names. Broader coverage+and claim validation remain separate requirements. A missing field in an older+session supplies no historical observations; malformed new state fails restore.++The production regression exercises failing checks, successful reruns, drafts,+resumes and batched publication with local-only external-service fixtures.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 3ed01fbf..09369985 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -135,6 +135,8 @@ record only when you need the evidence or the edge cases.| [0123](0123-pr-check-observations-retain-the-rollup.md) | PR completion retains named current-head check observations locally; diagnostic receipts never replace fresh verification. |+| [0126](0126-publication-retains-observed-check-failures.md) | Observed failed checks survive resumes; non-draft publication waits for successful reruns and occupies its own tool batch. |+## When to write oneWrite an ADR when a decision is load-bearing and non-obvious: it was reacheddiff --git a/scripts/eval/mock_model.py b/scripts/eval/mock_model.pyindex d2522ff8..a1064075 100644--- a/scripts/eval/mock_model.py+++ b/scripts/eval/mock_model.py@@ -99,15 +99,16 @@ class ScriptedModel:def _message(self, reply: dict[str, Any]) -> dict[str, Any]:message: dict[str, Any] = {"role": "assistant", "content": reply.get("text", "")}- if reply.get("tool"):+ calls = reply.get("tools") or ([reply] if reply.get("tool") else [])+ if calls:message["tool_calls"] = [{- "id": f"call_{len(model.requests)}",+ "id": f"call_{len(model.requests)}" + (f"_{index}" if len(calls) > 1 else ""),"type": "function","function": {- "name": reply["tool"],- "arguments": json.dumps(reply.get("arguments", {})),+ "name": call["tool"],+ "arguments": json.dumps(call.get("arguments", {})),},- }]+ } for index, call in enumerate(calls)]return messagedef _whole(self, reply: dict[str, Any]) -> None:diff --git a/scripts/test-pr-local-checks.py b/scripts/test-pr-local-checks.pynew file mode 100644index 00000000..2ffadb2d--- /dev/null+++ b/scripts/test-pr-local-checks.py@@ -0,0 +1,157 @@+#!/usr/bin/env python3+"""Production publication dispatch with local-only model and GitHub fixtures."""++import argparse+import json+import os+from pathlib import Path+import shutil+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 bash(command):+ return {"tool": "bash", "arguments": {"command": command}}+++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())+ failing = "import unittest\nclass Check(unittest.TestCase):\n def test_observed_failure(self):\n self.assertEqual(1, 2)\n"+ check = bash("python3 -m unittest test_observed -v")+ publish = bash("gh pr create --title fixture --body-file notes.md")+ final = {"text": "Fixture finished."}+ for case in ("failed", "rerun", "draft", "resume", "batch"):+ with tempfile.TemporaryDirectory(prefix="graff-pr-local-checks-") 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,+ PYTHONDONTWRITEBYTECODE="1",+ LMSTUDIO_API_KEY="local",+ GRAFF_FLEET="off",+ GRAFF_NO_TELEMETRY="1",+ GRAFF_NO_SMOLIFY="1",+ GRAFF_NO_CODEDB_GUARD="1",+ )+ prepare(work, env, {"checks": "SUCCESS"})+ (work / "test_observed.py").write_text(failing)+ (work / "notes.md").write_text(+ "Verification: local checks passed. Dispatch is covered."+ )+ if case == "rerun":+ script = [+ check,+ {+ "tool": "write_file",+ "arguments": {+ "path": "test_observed.py",+ "content": failing.replace("1, 2", "2, 2"),+ },+ },+ check,+ publish,+ final,+ ]+ elif case == "draft":+ script = [+ check,+ bash("gh pr create --draft --title fixture --body-file notes.md"),+ final,+ ]+ elif case == "resume":+ script = [check, final, publish, final]+ elif case == "batch":+ script = [{"tools": [check, publish]}, final]+ else:+ script = [check, bash("git diff"), publish, final]+ model = ScriptedModel(script)+ model.start(1234)+ try:+ events = []+ runs = 2 if case == "resume" else 1+ for phase in range(runs):+ command = [+ binary,+ "--json",+ "--old",+ "--yolo",+ "--model",+ "lmstudio",+ ]+ if phase:+ files = list((work / ".graff/sessions").glob("*.session.json"))+ assert len(files) == 1, files+ saved = json.loads(files[0].read_text())+ assert len(saved["publication_failed_checks"]) == 1, saved+ command += [+ "--resume",+ files[0].name.removesuffix(".session.json"),+ ]+ result = run(+ command,+ cwd=work,+ env=env,+ text=True,+ capture_output=True,+ timeout=90,+ input=json.dumps(+ {+ "type": "user",+ "text": "Exercise the local-only publication fixture.",+ }+ )+ + "\n",+ )+ assert result.returncode == 0, result.stderr[-3000:]+ events += [+ json.loads(line)+ for line in result.stdout.splitlines()+ if line.startswith("{")+ ]+ mutations = (+ (work / "mutations.jsonl").read_text()+ if (work / "mutations.jsonl").exists()+ else ""+ )+ assert bool(mutations) == (case in ("rerun", "draft")), (+ case,+ mutations,+ events,+ )+ if case in ("failed", "resume"):+ assert (+ "observed local check has no successful completion"+ in json.dumps(events)+ )+ if case == "batch":+ assert "separate tool call" in json.dumps(events)+ target = args.evidence / case+ target.mkdir(parents=True, exist_ok=True)+ (target / "events.json").write_text(json.dumps(events, indent=2))+ (target / "requests.json").write_text(+ json.dumps(model.requests, indent=2)+ )+ (target / "mutations.jsonl").write_text(mutations)+ for folder in ("sessions", "traces", "trajectories"):+ source = work / ".graff" / folder+ if source.exists():+ shutil.copytree(source, target / folder, dirs_exist_ok=True)+ print(+ f"PASS {case}: observed checks and publication outcome agree",+ flush=True,+ )+ finally:+ model.stop()+++if __name__ == "__main__":+ main()diff --git a/src/agent.zig b/src/agent.zigindex 45a149cd..b0003ef8 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -71,6 +71,7 @@ pub const Goal = struct {/// agent prints to stdout; subagents (sub = true) run on pool threads and/// log through std.debug.print, which locks stderr and is thread-safe.pub const Agent = struct {+ publication_checks: @import("pr_local_checks.zig").State = .{},gpa: Allocator,arena: Allocator,/// #124: per-turn parse garbage (SSE envelopes, isStreamEnd) lives here anddiff --git a/src/agent_tools.zig b/src/agent_tools.zigindex dd236b97..e8bbe3fb 100644--- a/src/agent_tools.zig+++ b/src/agent_tools.zig@@ -106,7 +106,7 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {if (std.mem.eql(u8, call.name, "attempt_completion") and defer_completion) {continue;}- if (try self.rejectToolCall(call)) |denied| {+ if (try @import("pr_local_checks.zig").batchGate(self, calls, call) orelse try self.rejectToolCall(call)) |denied| {results[i] = denied;continue;}@@ -186,6 +186,7 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {.run_id = if (self.tracer) |tr| tr.identity.run_id else "untraced",};for (ext_idx.items, outputs) |i, output| {+ try @import("pr_local_checks.zig").record(self, calls[i], .{ .text = output.text, .is_error = output.is_error, .cancelled = output.cancelled });// Over the threshold, the bytes go to a durable handle; the model// gets a bounded preview + path + byte count + shape hint.const handled = try tool_handle.forResult(self.gpa, self.arena, handle_target, output.text, handle_threshold);diff --git a/src/main.zig b/src/main.zigindex d874e555..d9208ab7 100644--- a/src/main.zig+++ b/src/main.zig@@ -596,5 +596,5 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = @import("subagent_recovery.zig");_ = @import("acp_agent_activity.zig");_ = @import("read_image.zig");- _ = .{ @import("mcp_names.zig"), @import("workspace_history.zig"), @import("file_worktree.zig"), @import("mcp_turn_context.zig") };+ _ = .{ @import("pr_local_checks.zig"), @import("mcp_names.zig"), @import("workspace_history.zig"), @import("file_worktree.zig"), @import("mcp_turn_context.zig") };}diff --git a/src/pr_local_checks.zig b/src/pr_local_checks.zignew file mode 100644index 00000000..d50cc19c--- /dev/null+++ b/src/pr_local_checks.zig@@ -0,0 +1,152 @@+//! Session-observed failing checks cannot be replaced by publication prose.+const std = @import("std");+const Allocator = std.mem.Allocator;+const ToolCall = @import("tools.zig").ToolCall;+const ExecResult = @import("tools.zig").ExecResult;++pub fn isCheck(command: []const u8) bool {+ var words = std.mem.tokenizeAny(u8, command, " \t\r\n");+ const executable = std.fs.path.basename(words.next() orelse return false);+ if (std.mem.eql(u8, executable, "pytest")) return true;+ const first = words.next() orelse return false;+ if (std.mem.eql(u8, executable, "python") or std.mem.eql(u8, executable, "python3")) {+ if (std.mem.eql(u8, first, "-m")) {+ const module = words.next() orelse return false;+ return std.mem.eql(u8, module, "unittest") or std.mem.eql(u8, module, "pytest");+ }+ const script = std.fs.path.basename(first);+ return std.mem.startsWith(u8, script, "test-") or std.mem.startsWith(u8, script, "test_") or std.mem.startsWith(u8, script, "eval-tier");+ }+ if (std.mem.eql(u8, executable, "zig"))+ return std.mem.eql(u8, first, "test") or (std.mem.eql(u8, first, "build") and std.mem.startsWith(u8, words.next() orelse "", "test"));+ for ([_][]const u8{ "cargo", "go", "bun", "npm", "pnpm", "yarn", "make" }) |runner| {+ if (!std.mem.eql(u8, executable, runner)) continue;+ return std.mem.eql(u8, first, "test") or (std.mem.eql(u8, first, "run") and std.mem.startsWith(u8, words.next() orelse "", "test"));+ }+ return false;+}++pub fn record(root: anytype, call: ToolCall, result: ExecResult) !void {+ if (root.sub or !std.mem.eql(u8, call.name, "bash") or call.input != .object) return;+ const command = call.input.object.get("command") orelse return;+ if (command != .string or !isCheck(command.string)) return;+ var dir = try std.Io.Dir.cwd().openDir(root.io, root.agent_cwd orelse ".", .{});+ defer dir.close(root.io);+ var buffer: [std.fs.max_path_bytes]u8 = undefined;+ const cwd = buffer[0..try dir.realPath(root.io, &buffer)];+ try root.publication_checks.observe(root.arena, cwd, call, result);+}++pub fn batchGate(root: anytype, calls: []const ToolCall, call: ToolCall) !?ExecResult {+ if (calls.len <= 1 or !std.mem.eql(u8, call.name, "bash") or call.input != .object) return null;+ const raw = call.input.object.get("command") orelse return null;+ if (raw != .string) return null;+ const command = @import("pr_command.zig").parse(root.arena, raw.string) catch return null;+ if (!std.mem.eql(u8, command.verb, "create") and !std.mem.eql(u8, command.verb, "ready")) return null;+ if (std.mem.eql(u8, command.verb, "create") and command.draft()) return null;+ const text = "PR publication preflight: run non-draft publication in a separate tool call after other work finishes; write NOT performed.";+ root.emitToolRejected(call, "publication_batch", text);+ return .{ .text = text, .is_error = true };+}++pub const State = struct {+ const Entry = struct { cwd: []const u8, command: []const u8 };+ failed: std.ArrayList(Entry) = .empty,++ pub fn observe(self: *State, arena: Allocator, cwd: []const u8, call: ToolCall, result: ExecResult) !void {+ if (!std.mem.eql(u8, call.name, "bash") or call.input != .object) return;+ const raw = call.input.object.get("command") orelse return;+ if (raw != .string or !isCheck(raw.string)) return;+ const command = std.mem.trim(u8, raw.string, " \t\r\n");+ for (self.failed.items, 0..) |entry, i| {+ if (!std.mem.eql(u8, entry.cwd, cwd) or !std.mem.eql(u8, entry.command, command)) continue;+ if (!result.is_error and !result.cancelled and std.mem.indexOf(u8, result.text, "[job ") == null)+ _ = self.failed.orderedRemove(i);+ return;+ }+ if (!result.is_error and !result.cancelled and std.mem.indexOf(u8, result.text, "[job ") == null) return;+ try self.failed.append(arena, .{ .cwd = try arena.dupe(u8, cwd), .command = try arena.dupe(u8, command) });+ }++ pub fn write(self: *const State, writer: anytype) !void {+ try writer.objectField("publication_failed_checks");+ try writer.write(self.failed.items);+ }++ pub fn mixFingerprint(self: *const State, fingerprint: anytype) void {+ fingerprint.num(self.failed.items.len);+ for (self.failed.items) |entry| {+ fingerprint.text(entry.cwd);+ fingerprint.text(entry.command);+ }+ }++ pub fn restore(self: *State, arena: Allocator, object: std.json.ObjectMap) !void {+ var restored: State = .{};+ const saved = object.get("publication_failed_checks") orelse {+ self.* = restored;+ return;+ };+ if (saved != .array) return error.InvalidPublicationChecks;+ for (saved.array.items) |item| {+ if (item != .object) return error.InvalidPublicationChecks;+ const cwd = item.object.get("cwd") orelse return error.InvalidPublicationChecks;+ const command = item.object.get("command") orelse return error.InvalidPublicationChecks;+ if (cwd != .string or command != .string or !std.fs.path.isAbsolute(cwd.string) or command.string.len == 0)+ return error.InvalidPublicationChecks;+ try restored.failed.append(arena, .{ .cwd = try arena.dupe(u8, cwd.string), .command = try arena.dupe(u8, command.string) });+ }+ self.* = restored;+ }++ pub fn unresolved(self: *const State, cwd: []const u8) ?[]const u8 {+ for (self.failed.items) |entry| if (std.mem.eql(u8, entry.cwd, cwd)) return entry.command;+ return null;+ }+};++test "observed failed check survives unrelated success and clears only on its successful rerun" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ var state: State = .{};+ const input = try std.json.parseFromSliceLeaky(std.json.Value, a, "{\"command\":\"python3 -m unittest test_delete -v\"}", .{});+ const call: ToolCall = .{ .id = "test", .name = "bash", .input = input };+ try state.observe(a, "/fixture", call, .{ .text = "FAIL", .is_error = true });+ try std.testing.expect(state.unresolved("/fixture") != null);+ try std.testing.expect(state.unresolved("/other") == null);+ const unrelated = try std.json.parseFromSliceLeaky(std.json.Value, a, "{\"command\":\"git diff\"}", .{});+ try state.observe(a, "/fixture", .{ .id = "inspect", .name = "bash", .input = unrelated }, .{ .text = "", .is_error = false });+ try std.testing.expect(state.unresolved("/fixture") != null);+ try state.observe(a, "/fixture", call, .{ .text = "[job 1 started]", .is_error = false });+ try std.testing.expect(state.unresolved("/fixture") != null);+ try state.observe(a, "/fixture", call, .{ .text = "OK", .is_error = false });+ try std.testing.expect(state.unresolved("/fixture") == null);+}++test "check classification excludes prose and ordinary inspection" {+ try std.testing.expect(isCheck("python3 -m unittest test_delete -v"));+ try std.testing.expect(isCheck("zig build test"));+ try std.testing.expect(!isCheck("echo pytest failed"));+ try std.testing.expect(!isCheck("git diff"));+}++test "failed checks survive serialization and malformed state is not a clean resume" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ var original: State = .{};+ try original.failed.append(a, .{ .cwd = "/fixture", .command = "zig build test" });+ var output: std.Io.Writer.Allocating = .init(a);+ var writer: std.json.Stringify = .{ .writer = &output.writer };+ try writer.beginObject();+ try original.write(&writer);+ try writer.endObject();+ const saved = try std.json.parseFromSliceLeaky(std.json.Value, a, output.writer.buffered(), .{});+ var resumed: State = .{};+ try resumed.restore(a, saved.object);+ try std.testing.expectEqualStrings("zig build test", resumed.unresolved("/fixture").?);+ const malformed = try std.json.parseFromSliceLeaky(std.json.Value, a, "{\"publication_failed_checks\":false}", .{});+ try std.testing.expectError(error.InvalidPublicationChecks, resumed.restore(a, malformed.object));+ try std.testing.expect(resumed.unresolved("/fixture") != null);+}diff --git a/src/publish_gate.zig b/src/publish_gate.zigindex 9d343c41..209060e1 100644--- a/src/publish_gate.zig+++ b/src/publish_gate.zig@@ -27,6 +27,8 @@ fn observe(self: *Agent, cmd: []const u8) !?ExecResult {var ev: pr_publish.Evidence = .{};const draft = creating and command.draft();if (!draft) {+ if (self.publication_checks.unresolved(target.cwd)) |command_text|+ return .{ .text = try std.fmt.allocPrint(self.arena, "PR publication preflight: observed local check has no successful completion: {s}. Rerun it successfully or publish a draft; write NOT performed.", .{command_text}), .is_error = true };if (creating) {ev.head_sha = evmod.localHead(self.gpa, self.io, self.arena, target) catch "";// An explicit alternate head must be resolved independently of HEAD.diff --git a/src/session.zig b/src/session.zigindex cfa3094f..c3175282 100644--- a/src/session.zig+++ b/src/session.zig@@ -185,6 +185,7 @@ fn fingerprint(root: *Agent, name: []const u8) u64 {f.json(Value{ .array = root.messages });@import("session_catalog.zig").mixFingerprint(root, &f);f.text(@import("session_prompt.zig").snapshot(root) orelse "");+ root.publication_checks.mixFingerprint(&f);session_peer.mixFingerprint(&f);subagent_ledger.mixFingerprint(&f);return f.final();@@ -266,6 +267,7 @@ fn queueSave(root: *Agent, arena: Allocator, dir: Io.Dir, name: []const u8) !u64defer aw.deinit();var s: std.json.Stringify = .{ .writer = &aw.writer };try s.beginObject();+ try root.publication_checks.write(&s);try @import("session_catalog.zig").write(root, &s);try @import("session_prompt.zig").write(root, &s);try s.objectField("provider");@@ -492,6 +494,7 @@ pub fn loadSession(root: *Agent, keys: *Keys, arena: Allocator, name: []const u8// meter, and keep every still-unused format lazy.try @import("session_prompt.zig").restore(root, obj);try @import("session_catalog.zig").restore(root, obj);+ try root.publication_checks.restore(arena, 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 resume