graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: gate non-draft PRs, claims, and verified completion
Rach1a8f72c39934
diff --git a/docs/adr/0100-publication-claims-and-verified-completion.md b/docs/adr/0100-publication-claims-and-verified-completion.mdnew file mode 100644index 00000000..204fd8b8--- /dev/null+++ b/docs/adr/0100-publication-claims-and-verified-completion.md@@ -0,0 +1,42 @@+# 0100. Publication claims and verified completion++Status: accepted 2026-09-10++## Context++Three failures shared one gap: the harness treated awareness, a successful+`gh pr create`, and a rewritten checklist as proof of readiness.++- #847: non-draft publication sanitized outbound text but did not inspect the+ exact head SHA, require a Verification section, or reject an absolute claim+ backed only by a helper/one-separator test. `gh pr checks --watch` after+ create is too late.+- #840: `presence.gateCheck` ACKs a live peer once. An acknowledged handoff+ in prose did not block a later `gh pr create` by the other session.+- #844: `clearEpochForReplace` dropped omitted open verification items;+ `completionGate` then accepted, and `mainloop_trace.record` set+ `Outcome.success` from a normal agent return.++## Decision++Bash GitHub writes go through `publish_gate` before execution: a live foreign+artifact claim blocks, and a non-draft `gh pr create` / `gh pr ready` is+refused unless head evidence, verification text, and claim-vs-test review+pass. Drafts and PR-only workflows (no pre-PR run) remain allowed.++Claims are structured (`peer_message` action=claim|release|handoff|status).+ACK, polling, and a missing PR do not transfer ownership. A gone owner is+stale and may be acquired. The ledger persists in `.graff/artifact-claims.json`.++Verification checklist items survive a replace. `completionGate` will not+accept while they are open, including on the armed second call. Recipe+`success` is verified task success (`executed && taskVerified`), not a+normal return.++## Consequences++A session that has not recorded head CI still publishes when status is+`none` (PR-triggered workflows) if the body has a Verification section.+Live `gh run list` is not required in unit tests; evidence is injected or+parsed from a run-list JSON fixture. Custom personas still receive the+publication-ready note (ADR 0066).diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 6e15d012..af2a22e1 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -109,6 +109,7 @@ record only when you need the evidence or the edge cases.| [0097](0097-isolate-probe-clipboards.md) | Offline PTY probes get private clipboard commands per process; direct probe runs retain OS clipboard integration. || [0098](0098-orphan-listeners-are-not-stop-authority.md) | Legacy listener discovery is read-only; stop authority requires verified ownership, port preflight checks both families, and unknown browser visibility protects listening jobs. || [0099](0099-gui-saved-sessions-are-snapshots.md) | A saved-session GET is a snapshot with unknown live status; the GUI must not infer the REPL finished. |+| [0100](0100-publication-claims-and-verified-completion.md) | Non-draft PRs fail closed on CI/Verification/helper-only claims; artifact presence ACK is not ownership; recipe success is verified task success. |## When to write onediff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.jsonindex fdb86c1f..cf71e72b 100644--- a/scripts/eval/tier1-manifest.json+++ b/scripts/eval/tier1-manifest.json@@ -15,7 +15,7 @@"src/repl.zig","TUI/root.zig"],- "test_count_baseline": 2105,+ "test_count_baseline": 2154,"test_count_slack": 25,"required_invariants": [{diff --git a/src/agent_tool_gate.zig b/src/agent_tool_gate.zigindex 06f8f5f0..7bb38267 100644--- a/src/agent_tool_gate.zig+++ b/src/agent_tool_gate.zig@@ -19,6 +19,7 @@ const fleet = @import("fleet.zig");const telemetry = @import("telemetry.zig");const learning_privacy = @import("learning_privacy.zig");const presence = @import("presence.zig");+const publish_gate = @import("publish_gate.zig");const TemplateCandidates = struct {items: [16][]const u8 = undefined,@@ -154,9 +155,12 @@ pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {.is_error = true,};if (std.mem.eql(u8, call.name, "bash") and call.input == .object) {- if (call.input.object.get("command")) |cv| if (cv == .string and Approvals.isDestructiveGit(cv.string)) return .{- .text = try self.arena.dupe(u8, "destructive git is blocked for subagents (no one to confirm) — leave reset --hard / clean -f / force-push / branch -D to the root session"),- .is_error = true,+ if (call.input.object.get("command")) |cv| if (cv == .string) {+ if (try publish_gate.bash(self, std.mem.trim(u8, cv.string, " \t"))) |blocked| return blocked;+ if (Approvals.isDestructiveGit(cv.string)) return .{+ .text = try self.arena.dupe(u8, "destructive git is blocked for subagents (no one to confirm) — leave reset --hard / clean -f / force-push / branch -D to the root session"),+ .is_error = true,+ };};}return null;@@ -215,6 +219,7 @@ pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {const cmd_val = args.get("command") orelse return null;if (cmd_val != .string) return null;const cmd = std.mem.trim(u8, cmd_val.string, " \t");+ if (try publish_gate.bash(self, cmd)) |blocked| return blocked;// #469: one deliberate checkpoint per live co-owner before this session// touches the shared index/tree — fires under --yolo too, where no// approvals prompt would ever surface the collision. The model seesdiff --git a/src/agent_tools.zig b/src/agent_tools.zigindex ba6d09ff..d6b7701d 100644--- a/src/agent_tools.zig+++ b/src/agent_tools.zig@@ -30,6 +30,7 @@ const schema = @import("schema.zig");const isMetaName = schema.isMetaName;const eval_control = @import("agent_eval_control.zig");const goal_state = @import("goal_state.zig");+const goal_verify = @import("goal_verify.zig");const task_outcome = @import("task_outcome.zig");const goal_todo = @import("goal_todo.zig"); // todo_write's replace path + the omitted-completed preserve ruleconst peer_channel = @import("peer_channel.zig");@@ -344,7 +345,7 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {self.completion_refused = true; // blocked, not silence: attempt_completion skips the tool counter, and /loop must give the model a turn to run eval (#318)return .{ .text = message, .is_error = true };}- if (try goal_state.completionGate(self.arena, self)) |refusal| {+ if (try goal_verify.completionGate(self.arena, self)) |refusal| {goal_state.noteCompletionRefused(self); // arm the double-check (across turns) and mark the turn as worked (#318)if (!self.sub) engine_sink.forAgent(self).emit(self.io, .completion_deferred); // root-only notice, as everreturn .{ .text = refusal, .is_error = true };diff --git a/src/artifact_claim.zig b/src/artifact_claim.zignew file mode 100644index 00000000..f05cfe0c--- /dev/null+++ b/src/artifact_claim.zig@@ -0,0 +1,554 @@+//! Repository-scoped artifact claims (#840). Presence.gateCheck is a one-shot+//! awareness checkpoint; this ledger is the durable owner of branch / issue /+//! commit / pull-request / publication work. Acknowledging a peer, polling for+//! a missing PR, or waiting does not transfer a claim. Only acquire, release,+//! handoff, or a proven-dead owner does.++const std = @import("std");+const builtin = @import("builtin");+const Allocator = std.mem.Allocator;+const Io = std.Io;++const tools_mod = @import("tools.zig");+const ExecResult = tools_mod.ExecResult;+const presence = @import("presence.zig");+const proc_identity = @import("proc_identity.zig");++pub const Kind = enum { branch, issue, commit, pull_request, publication };++pub const Owner = struct {+ session: []const u8 = "",+ pid: i32 = 0,+ start_id: u64 = 0,+};++pub const Claim = struct {+ kind: Kind,+ key: []const u8,+ owner: Owner,+ acquired_ms: i64 = 0,+};++pub const Verdict = enum { free, mine, foreign_live, stale };++pub const max_claims = 32;++pub const Ledger = struct {+ items: [max_claims]Claim = undefined,+ len: usize = 0,++ pub fn slice(self: *const Ledger) []const Claim {+ return self.items[0..self.len];+ }+};++pub fn kindFrom(text: []const u8) ?Kind {+ if (std.mem.eql(u8, text, "branch")) return .branch;+ if (std.mem.eql(u8, text, "issue")) return .issue;+ if (std.mem.eql(u8, text, "commit")) return .commit;+ if (std.mem.eql(u8, text, "pull_request") or std.mem.eql(u8, text, "pr")) return .pull_request;+ if (std.mem.eql(u8, text, "publication")) return .publication;+ return null;+}++pub fn sameOwner(a: Owner, b: Owner) bool {+ if (a.session.len > 0 and b.session.len > 0 and std.mem.eql(u8, a.session, b.session)) return true;+ return a.pid != 0 and a.pid == b.pid and a.start_id == b.start_id;+}++fn sameKey(a: Claim, kind: Kind, key: []const u8) bool {+ if (a.kind != kind) return false;+ if (key.len == 0 or a.key.len == 0) return std.mem.eql(u8, a.key, key);+ return std.mem.eql(u8, a.key, key);+}++/// `owner_live` is the caller's probe of the recorded owner. Time passing and+/// an absent pull request are not inputs — only a gone process is stale.+pub fn verdict(claims: []const Claim, kind: Kind, key: []const u8, me: Owner, owner_live: bool) Verdict {+ for (claims) |c| {+ if (!sameKey(c, kind, key)) continue;+ if (sameOwner(c.owner, me)) return .mine;+ return if (owner_live) .foreign_live else .stale;+ }+ return .free;+}++pub fn find(claims: []const Claim, kind: Kind, key: []const u8) ?Claim {+ for (claims) |c| if (sameKey(c, kind, key)) return c;+ return null;+}++pub fn acquire(ledger: *Ledger, arena: Allocator, kind: Kind, key: []const u8, me: Owner, now_ms: i64, owner_live: bool) ![]const u8 {+ switch (verdict(ledger.slice(), kind, key, me, owner_live)) {+ .mine => return "claim already held by this session",+ .foreign_live => return error.ClaimHeld,+ .stale, .free => {},+ }+ var i: usize = 0;+ while (i < ledger.len) {+ if (sameKey(ledger.items[i], kind, key)) {+ ledger.items[i] = .{+ .kind = kind,+ .key = try arena.dupe(u8, key),+ .owner = .{+ .session = try arena.dupe(u8, me.session),+ .pid = me.pid,+ .start_id = me.start_id,+ },+ .acquired_ms = now_ms,+ };+ return "claim acquired (replaced stale owner)";+ }+ i += 1;+ }+ if (ledger.len >= max_claims) return error.ClaimFull;+ ledger.items[ledger.len] = .{+ .kind = kind,+ .key = try arena.dupe(u8, key),+ .owner = .{+ .session = try arena.dupe(u8, me.session),+ .pid = me.pid,+ .start_id = me.start_id,+ },+ .acquired_ms = now_ms,+ };+ ledger.len += 1;+ return "claim acquired";+}++pub fn release(ledger: *Ledger, kind: Kind, key: []const u8, me: Owner, owner_live: bool) ![]const u8 {+ switch (verdict(ledger.slice(), kind, key, me, owner_live)) {+ .free => return "no claim to release",+ .stale => {}, // a live session may clear a dead owner's claim+ .foreign_live => return error.ClaimHeld,+ .mine => {},+ }+ var i: usize = 0;+ while (i < ledger.len) {+ if (sameKey(ledger.items[i], kind, key)) {+ ledger.items[i] = ledger.items[ledger.len - 1];+ ledger.len -= 1;+ return "claim released";+ }+ i += 1;+ }+ return "no claim to release";+}++pub fn handoff(ledger: *Ledger, arena: Allocator, kind: Kind, key: []const u8, from: Owner, to: Owner, now_ms: i64, owner_live: bool) ![]const u8 {+ if (sameOwner(from, to)) return "handoff to self is a no-op";+ switch (verdict(ledger.slice(), kind, key, from, owner_live)) {+ .mine => {},+ .stale => if (!owner_live) {} else return error.ClaimHeld,+ .foreign_live => return error.ClaimHeld,+ .free => return error.NoClaim,+ }+ var i: usize = 0;+ while (i < ledger.len) : (i += 1) {+ if (!sameKey(ledger.items[i], kind, key)) continue;+ ledger.items[i].owner = .{+ .session = try arena.dupe(u8, to.session),+ .pid = to.pid,+ .start_id = to.start_id,+ };+ ledger.items[i].acquired_ms = now_ms;+ return "claim handed off";+ }+ return error.NoClaim;+}++/// Git / GitHub writes that must not proceed under a foreign live claim.+pub fn isClaimedMutation(cmd: []const u8) bool {+ if (@import("presence_mutate.zig").isSharedTreeGit(cmd)) return true;+ var it = std.mem.tokenizeAny(u8, cmd, " \t\r\n;&|\"'`()");+ var saw_git = false;+ var saw_gh = false;+ var saw_pr = false;+ while (it.next()) |tok| {+ if (std.mem.eql(u8, tok, "git")) {+ saw_git = true;+ continue;+ }+ if (saw_git and (std.mem.eql(u8, tok, "push") or std.mem.eql(u8, tok, "commit") or std.mem.eql(u8, tok, "add"))) return true;+ if (std.mem.eql(u8, tok, "gh")) {+ saw_gh = true;+ continue;+ }+ if (saw_gh and std.mem.eql(u8, tok, "pr")) {+ saw_pr = true;+ continue;+ }+ if (saw_pr and (std.mem.eql(u8, tok, "create") or std.mem.eql(u8, tok, "edit") or std.mem.eql(u8, tok, "ready"))) return true;+ }+ return false;+}++pub fn mutationKind(cmd: []const u8) Kind {+ if (std.mem.indexOf(u8, cmd, "gh pr") != null) return .pull_request;+ if (std.mem.indexOf(u8, cmd, "git push") != null) return .publication;+ if (std.mem.indexOf(u8, cmd, "git commit") != null or std.mem.indexOf(u8, cmd, "git add") != null) return .commit;+ return .publication;+}++pub fn refuseText(arena: Allocator, kind: Kind, key: []const u8, owner: Owner) []const u8 {+ return std.fmt.allocPrint(arena, "artifact claim held: {s} {s} is owned by live session \"{s}\" (pid {d}). The action was NOT performed. Acknowledging the shared-tree checkpoint, polling, or finding no pull request does not transfer ownership. The owner must peer_message action=handoff (or action=release) first.", .{ @tagName(kind), if (key.len > 0) key else "(worktree)", owner.session, owner.pid }) catch "artifact claim held: the action was NOT performed";+}++// --- process-global ledger (one worktree, many tests swap it) ---++var g_ledger: Ledger = .{};+var g_test_owner: Owner = .{};+var g_test_live: bool = true;+var g_persist_path: ?[]const u8 = null;+var g_loaded: bool = false;+var g_store: ?std.heap.ArenaAllocator = null;++pub const persist_rel = ".graff/artifact-claims.json";++fn storeAlloc() Allocator {+ if (g_store == null) g_store = std.heap.ArenaAllocator.init(std.heap.page_allocator);+ return g_store.?.allocator();+}++pub fn resetForTest() void {+ g_ledger.len = 0;+ g_test_owner = .{};+ g_test_live = true;+ g_persist_path = null;+ g_loaded = true; // tests start with an empty in-memory ledger+ if (g_store) |*st| {+ st.deinit();+ g_store = null;+ }+}++pub fn setPersistPath(path: []const u8) void {+ g_persist_path = path;+ g_loaded = false;+}++pub fn setTestOwner(owner: Owner) void {+ g_test_owner = owner;+}++pub fn setTestOwnerLive(live: bool) void {+ g_test_live = live;+}++pub fn testLedger() *Ledger {+ return &g_ledger;+}++pub fn selfOwner() Owner {+ if (g_test_owner.session.len > 0 or g_test_owner.pid != 0) return g_test_owner;+ return .{+ .session = presence.ownSession(),+ .pid = proc_identity.selfPid(),+ .start_id = 0,+ };+}++fn ownerLive(io: Io, owner: Owner) bool {+ if (g_test_owner.session.len > 0 or g_test_owner.pid != 0) {+ if (sameOwner(owner, g_test_owner)) return true;+ return g_test_live;+ }+ if (owner.pid == 0) return true;+ return proc_identity.probe(io, owner.pid) != .gone;+}++fn claimRelevant(held: Kind, mutation: Kind) bool {+ if (held == mutation or held == .publication) return true;+ return switch (mutation) {+ .pull_request => held == .branch or held == .commit,+ .publication => held == .branch or held == .pull_request or held == .commit,+ .commit => held == .branch,+ else => false,+ };+}++pub fn gateCommand(arena: Allocator, io: Io, cmd: []const u8, key: []const u8) ?[]const u8 {+ if (!isClaimedMutation(cmd)) return null;+ ensureLoaded(io);+ const kind = mutationKind(cmd);+ const me = selfOwner();+ if (key.len == 0) {+ for (g_ledger.slice()) |c| {+ if (!claimRelevant(c.kind, kind)) continue;+ const live = ownerLive(io, c.owner);+ if (verdict(g_ledger.slice(), c.kind, c.key, me, live) == .foreign_live)+ return refuseText(arena, c.kind, c.key, c.owner);+ }+ return null;+ }+ const existing = find(g_ledger.slice(), kind, key) orelse find(g_ledger.slice(), .publication, key);+ const check_kind = if (existing) |c| c.kind else kind;+ const check_key = if (existing) |c| c.key else key;+ const held = find(g_ledger.slice(), check_kind, check_key) orelse return null;+ const live = ownerLive(io, held.owner);+ return switch (verdict(g_ledger.slice(), check_kind, check_key, me, live)) {+ .foreign_live => refuseText(arena, check_kind, check_key, held.owner),+ else => null,+ };+}++pub fn handleTool(arena: Allocator, io: Io, action: []const u8, kind_s: []const u8, key: []const u8, to_session: []const u8) !ExecResult {+ ensureLoaded(io);+ const kind = kindFrom(kind_s) orelse return .{+ .text = "kind must be branch, issue, commit, pull_request, or publication",+ .is_error = true,+ };+ const me = selfOwner();+ const now: i64 = 0;+ const existing = find(g_ledger.slice(), kind, key);+ const live = if (existing) |c| ownerLive(io, c.owner) else false;+ if (std.mem.eql(u8, action, "claim") or std.mem.eql(u8, action, "acquire")) {+ const msg = acquire(&g_ledger, storeAlloc(), kind, key, me, now, live) catch |err| switch (err) {+ error.ClaimHeld => return .{ .text = refuseText(arena, kind, key, existing.?.owner), .is_error = true },+ else => return .{ .text = "claim acquire failed", .is_error = true },+ };+ flush(io);+ return .{ .text = msg, .is_error = false };+ }+ if (std.mem.eql(u8, action, "release")) {+ const msg = release(&g_ledger, kind, key, me, live) catch return .{+ .text = "cannot release a live foreign claim",+ .is_error = true,+ };+ flush(io);+ return .{ .text = msg, .is_error = false };+ }+ if (std.mem.eql(u8, action, "handoff")) {+ if (to_session.len == 0) return .{ .text = "handoff needs session (the receiver)", .is_error = true };+ const msg = handoff(&g_ledger, storeAlloc(), kind, key, me, .{ .session = to_session }, now, live) catch |err| switch (err) {+ error.ClaimHeld => return .{ .text = "cannot hand off a claim you do not own", .is_error = true },+ error.NoClaim => return .{ .text = "no claim to hand off", .is_error = true },+ else => return .{ .text = "handoff failed", .is_error = true },+ };+ flush(io);+ return .{ .text = msg, .is_error = false };+ }+ if (std.mem.eql(u8, action, "status")) {+ if (existing) |c| {+ const v = verdict(g_ledger.slice(), kind, key, me, live);+ return .{ .text = try std.fmt.allocPrint(arena, "claim {s} {s}: {s} owner=\"{s}\"", .{ @tagName(kind), key, @tagName(v), c.owner.session }), .is_error = false };+ }+ return .{ .text = "no claim", .is_error = false };+ }+ return .{ .text = "action must be claim, release, handoff, or status", .is_error = true };+}++fn persistPath() ?[]const u8 {+ if (g_persist_path) |p| return p;+ if (builtin.is_test) return null;+ return persist_rel;+}++fn ensureLoaded(io: Io) void {+ if (g_loaded) return;+ g_loaded = true;+ const path = persistPath() orelse return;+ const text = Io.Dir.cwd().readFileAlloc(io, path, storeAlloc(), .limited(64 * 1024)) catch return;+ loadJson(storeAlloc(), &g_ledger, text) catch {+ g_ledger.len = 0;+ };+}++fn flush(io: Io) void {+ const path = persistPath() orelse return;+ const json = persistJson(storeAlloc(), &g_ledger) catch return;+ if (std.fs.path.dirname(path)) |dir| Io.Dir.cwd().createDirPath(io, dir) catch {};+ Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = json }) catch {};+}++pub fn persistJson(arena: Allocator, ledger: *const Ledger) ![]const u8 {+ var aw: Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ try s.beginArray();+ for (ledger.slice()) |c| {+ try s.beginObject();+ try s.objectField("kind");+ try s.write(@tagName(c.kind));+ try s.objectField("key");+ try s.write(c.key);+ try s.objectField("session");+ try s.write(c.owner.session);+ try s.objectField("pid");+ try s.write(c.owner.pid);+ try s.objectField("start_id");+ try s.write(c.owner.start_id);+ try s.endObject();+ }+ try s.endArray();+ return aw.writer.buffered();+}++pub fn loadJson(arena: Allocator, ledger: *Ledger, text: []const u8) !void {+ ledger.len = 0;+ const parsed = std.json.parseFromSliceLeaky(std.json.Value, arena, text, .{}) catch return;+ if (parsed != .array) return;+ for (parsed.array.items) |item| {+ if (item != .object) continue;+ const kind_s = if (item.object.get("kind")) |v| (if (v == .string) v.string else continue) else continue;+ const kind = kindFrom(kind_s) orelse continue;+ const key = if (item.object.get("key")) |v| (if (v == .string) v.string else "") else "";+ const session = if (item.object.get("session")) |v| (if (v == .string) v.string else "") else "";+ const pid: i32 = if (item.object.get("pid")) |v| (if (v == .integer) @intCast(v.integer) else 0) else 0;+ const start_id: u64 = if (item.object.get("start_id")) |v| (if (v == .integer and v.integer >= 0) @intCast(v.integer) else 0) else 0;+ if (ledger.len >= max_claims) break;+ ledger.items[ledger.len] = .{+ .kind = kind,+ .key = try arena.dupe(u8, key),+ .owner = .{ .session = try arena.dupe(u8, session), .pid = pid, .start_id = start_id },+ };+ ledger.len += 1;+ }+}++test "acquire / handoff / release are atomic and session-scoped" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ var ledger: Ledger = .{};+ const a = Owner{ .session = "s-a", .pid = 1, .start_id = 10 };+ const b = Owner{ .session = "s-b", .pid = 2, .start_id = 20 };+ _ = try acquire(&ledger, ar, .publication, "feat/x", a, 1, false);+ try std.testing.expectEqual(Verdict.mine, verdict(ledger.slice(), .publication, "feat/x", a, true));+ try std.testing.expectEqual(Verdict.foreign_live, verdict(ledger.slice(), .publication, "feat/x", b, true));+ try std.testing.expectError(error.ClaimHeld, acquire(&ledger, ar, .publication, "feat/x", b, 2, true));+ _ = try handoff(&ledger, ar, .publication, "feat/x", a, b, 3, true);+ try std.testing.expectEqual(Verdict.mine, verdict(ledger.slice(), .publication, "feat/x", b, true));+ try std.testing.expectEqual(Verdict.foreign_live, verdict(ledger.slice(), .publication, "feat/x", a, true));+ _ = try release(&ledger, .publication, "feat/x", b, true);+ try std.testing.expectEqual(Verdict.free, verdict(ledger.slice(), .publication, "feat/x", a, true));+}++test "stale-owner recovery is only a gone process, never a missing PR" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ var ledger: Ledger = .{};+ const dead = Owner{ .session = "s-dead", .pid = 9, .start_id = 1 };+ const live = Owner{ .session = "s-live", .pid = 8, .start_id = 2 };+ _ = try acquire(&ledger, ar, .pull_request, "none-yet", dead, 1, false);+ try std.testing.expectEqual(Verdict.stale, verdict(ledger.slice(), .pull_request, "none-yet", live, false));+ try std.testing.expectEqual(Verdict.foreign_live, verdict(ledger.slice(), .pull_request, "none-yet", live, true));+ const msg = try acquire(&ledger, ar, .pull_request, "none-yet", live, 2, false);+ try std.testing.expect(std.mem.indexOf(u8, msg, "stale") != null);+ try std.testing.expectEqual(Verdict.mine, verdict(ledger.slice(), .pull_request, "none-yet", live, true));+}++test "a different branch or issue stays independently writable" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ var ledger: Ledger = .{};+ const a = Owner{ .session = "s-a" };+ const b = Owner{ .session = "s-b" };+ _ = try acquire(&ledger, ar, .branch, "feat/a", a, 1, false);+ _ = try acquire(&ledger, ar, .issue, "840", b, 1, false);+ try std.testing.expectEqual(Verdict.free, verdict(ledger.slice(), .branch, "feat/b", b, true));+ try std.testing.expectEqual(Verdict.free, verdict(ledger.slice(), .issue, "841", a, true));+}++test "persist round-trip survives a resume-shaped reload" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ var ledger: Ledger = .{};+ _ = try acquire(&ledger, ar, .publication, "feat/x", .{ .session = "s-a", .pid = 3, .start_id = 7 }, 1, false);+ const json = try persistJson(ar, &ledger);+ var restored: Ledger = .{};+ try loadJson(ar, &restored, json);+ try std.testing.expectEqual(@as(usize, 1), restored.len);+ try std.testing.expectEqualStrings("feat/x", restored.items[0].key);+ try std.testing.expectEqualStrings("s-a", restored.items[0].owner.session);+ try std.testing.expectEqual(@as(i32, 3), restored.items[0].owner.pid);+}++test "claimed mutations include push and gh pr create, not status or checks --watch" {+ try std.testing.expect(isClaimedMutation("git add -A"));+ try std.testing.expect(isClaimedMutation("git commit -m wip"));+ try std.testing.expect(isClaimedMutation("git push origin HEAD"));+ try std.testing.expect(isClaimedMutation("gh pr create --title x --body y"));+ try std.testing.expect(isClaimedMutation("gh pr edit 1 --body z"));+ try std.testing.expect(!isClaimedMutation("git status"));+ try std.testing.expect(!isClaimedMutation("gh pr checks --watch"));+ try std.testing.expect(!isClaimedMutation("gh pr list"));+}++test "#840 acknowledged handoff does not let the other session create the PR" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ resetForTest();+ defer resetForTest();+ setTestOwner(.{ .session = "s-owner", .pid = 11, .start_id = 1 });+ const got = try handleTool(ar, std.testing.io, "claim", "publication", "feat/x", "");+ try std.testing.expect(!got.is_error);+ // Session B acknowledges in prose (peer_message send) — that is not a handoff.+ setTestOwner(.{ .session = "s-other", .pid = 12, .start_id = 2 });+ setTestOwnerLive(true);+ const blocked = gateCommand(ar, std.testing.io, "gh pr create --title x --body y", "feat/x").?;+ try std.testing.expect(std.mem.indexOf(u8, blocked, "NOT performed") != null);+ try std.testing.expect(std.mem.indexOf(u8, blocked, "handoff") != null);+ // Explicit handoff atomically enables the receiver.+ setTestOwner(.{ .session = "s-owner", .pid = 11, .start_id = 1 });+ const ho = try handleTool(ar, std.testing.io, "handoff", "publication", "feat/x", "s-other");+ try std.testing.expect(!ho.is_error);+ setTestOwner(.{ .session = "s-other", .pid = 12, .start_id = 2 });+ try std.testing.expect(gateCommand(ar, std.testing.io, "gh pr create --title x --body y", "feat/x") == null);+ setTestOwner(.{ .session = "s-owner", .pid = 11, .start_id = 1 });+ try std.testing.expect(gateCommand(ar, std.testing.io, "gh pr create --title x --body y", "feat/x") != null);+}++test "empty bash key still blocks a named publication claim" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ resetForTest();+ defer resetForTest();+ setTestOwner(.{ .session = "s-owner" });+ _ = try handleTool(ar, std.testing.io, "claim", "publication", "feat/x", "");+ setTestOwner(.{ .session = "s-other" });+ setTestOwnerLive(true);+ try std.testing.expect(gateCommand(ar, std.testing.io, "gh pr create --title x --body y", "") != null);+ try std.testing.expect(gateCommand(ar, std.testing.io, "git commit -m wip", "") != null);+}++test "file persist reloads after a resume-shaped reset" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ const io = std.testing.io;+ const file = "zig-cache/artifact-claims-persist-test.json";+ Io.Dir.cwd().deleteFile(io, file) catch {};+ defer Io.Dir.cwd().deleteFile(io, file) catch {};+ resetForTest();+ defer resetForTest();+ setPersistPath(file);+ g_loaded = true;+ setTestOwner(.{ .session = "s-persist", .pid = 4, .start_id = 9 });+ _ = try handleTool(ar, io, "claim", "publication", "feat/x", "");+ g_ledger.len = 0;+ g_loaded = false;+ ensureLoaded(io);+ try std.testing.expectEqual(@as(usize, 1), g_ledger.len);+ try std.testing.expectEqualStrings("feat/x", g_ledger.items[0].key);+ try std.testing.expectEqualStrings("s-persist", g_ledger.items[0].owner.session);+}++test "shared-tree ACK is not a claim release" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ resetForTest();+ defer resetForTest();+ setTestOwner(.{ .session = "s-owner" });+ _ = try handleTool(ar, std.testing.io, "claim", "publication", "feat/x", "");+ setTestOwner(.{ .session = "s-other" });+ setTestOwnerLive(true);+ // Re-issuing after presence.gateCheck ACKs the peer — claim still holds.+ try std.testing.expect(gateCommand(ar, std.testing.io, "git commit -m wip", "feat/x") != null);+ try std.testing.expect(gateCommand(ar, std.testing.io, "git push origin HEAD", "feat/x") != null);+}diff --git a/src/goal_todo.zig b/src/goal_todo.zigindex 6a2bf4f7..f0307f8c 100644--- a/src/goal_todo.zig+++ b/src/goal_todo.zig@@ -29,32 +29,34 @@ const agent_mod = @import("agent.zig");const Agent = agent_mod.Agent;const TodoItem = agent_mod.TodoItem;const goal_state = @import("goal_state.zig");+const goal_verify_kind = @import("goal_verify_kind.zig");-/// Make room for a replacement checklist on `epoch`: remove that epoch's items,-/// EXCEPT completed ones whose content the incoming list does not mention.-/// Items from other (parked) epochs are never touched - the authoring goal is-/// rewriting its own list, nobody else's. Returns the number removed.-/// Callers must guarantee `incoming` is nonempty (applyTodoWrite rejects the-/// empty case): an empty replace here would leave only completed survivors,-/// an epoch that reads allDone off a write that did nothing (#318).+pub const ReplaceClear = struct { dropped_open: usize = 0, kept_verify: usize = 0 };++/// Make room for a replacement checklist on `epoch`. Completed omitted items+/// stay (#318). Open verification items also stay (#844). Ordinary omitted+/// open work is still abandoned. Returns the dropped-open count.pub fn clearEpochForReplace(todos: *std.ArrayList(TodoItem), epoch: u64, incoming: []const []const u8) usize {- var dropped_open: usize = 0;+ return clearEpochForReplaceEx(todos, epoch, incoming).dropped_open;+}++pub fn clearEpochForReplaceEx(todos: *std.ArrayList(TodoItem), epoch: u64, incoming: []const []const u8) ReplaceClear {+ var out: ReplaceClear = .{};var i: usize = 0;while (i < todos.items.len) {const t = todos.items[i];const done = std.mem.eql(u8, t.status, "completed");const mentioned = mentions(incoming, t.content);- if (t.epoch != epoch or (done and !mentioned)) {+ const verify = !done and goal_verify_kind.isVerification(t.content);+ if (t.epoch != epoch or (done and !mentioned) or (verify and !mentioned)) {+ if (t.epoch == epoch and verify and !mentioned) out.kept_verify += 1;i += 1;continue;}- // Open work the replacement did not mention is being ABANDONED. Count- // it so the caller can say so: every user-driven drop reports a count- // (/goal clear, /goal <new>), and only the model-driven one was silent.- if (!done and !mentioned) dropped_open += 1;+ if (!done and !mentioned) out.dropped_open += 1;_ = todos.orderedRemove(i);}- return dropped_open;+ return out;}fn mentions(contents: []const []const u8, content: []const u8) bool {@@ -93,7 +95,7 @@ pub fn retireFinishedForNewAsk(root: *Agent) usize {return n;}-pub const WriteResult = struct { text: []const u8, rejected: bool = false, dropped_open: usize = 0 };+pub const WriteResult = struct { text: []const u8, rejected: bool = false, dropped_open: usize = 0, kept_verify: usize = 0 };/// The whole todo_write handler: replace the current epoch's checklist with/// `list` (the tool call's "todos" argument, already parsed), preserving@@ -114,8 +116,8 @@ pub fn applyTodoWrite(root: *Agent, list: ?Value) !WriteResult {}if (incoming.items.len == 0)return .{ .text = "todo_write had no usable items; the list is unchanged. Each item needs a content string and a status. Send your full remaining plan - completed items you omit are kept automatically.", .rejected = true };- const dropped_open = clearEpochForReplace(&root.todos, epoch, incoming.items);- goal_state.noteTodoWrite(root); // fresh evidence for the completion double-check, and this-process evidence for /loop (#318)+ const cleared = clearEpochForReplaceEx(&root.todos, epoch, incoming.items);+ goal_state.noteTodoWrite(root); // list changed; open verification still fails allDone (#844)if (asArray(list)) |items| {for (items) |item| {const content = contentOf(item) orelse continue;@@ -128,12 +130,16 @@ pub fn applyTodoWrite(root: *Agent, list: ?Value) !WriteResult {}}const rendered = goal_state.renderTodos(root, epoch);- if (dropped_open == 0) return .{ .text = rendered };- // Name the abandonment. The model may well have meant it, but the user- // reading the transcript needs the same count they get from /goal clear.+ if (cleared.dropped_open == 0 and cleared.kept_verify == 0) return .{ .text = rendered };+ if (cleared.kept_verify > 0 and cleared.dropped_open == 0)+ return .{+ .text = try std.fmt.allocPrint(root.arena, "{s}\n({d} verification item(s) you left out were kept as unresolved acceptance requirements)", .{ rendered, cleared.kept_verify }),+ .kept_verify = cleared.kept_verify,+ };return .{- .text = try std.fmt.allocPrint(root.arena, "{s}\n({d} open item(s) you left out were dropped; re-list one to keep it)", .{ rendered, dropped_open }),- .dropped_open = dropped_open,+ .text = try std.fmt.allocPrint(root.arena, "{s}\n({d} open item(s) you left out were dropped; re-list one to keep it)", .{ rendered, cleared.dropped_open }),+ .dropped_open = cleared.dropped_open,+ .kept_verify = cleared.kept_verify,};}diff --git a/src/goal_verify.zig b/src/goal_verify.zignew file mode 100644index 00000000..90b8b264--- /dev/null+++ b/src/goal_verify.zig@@ -0,0 +1,152 @@+//! Unresolved verification obligations (#844). A todo_write replace may+//! abandon ordinary open work; acceptance/verification items stay on the+//! checklist until the user changes scope. Dropping them must not satisfy+//! completion, and the armed second attempt_completion cannot waive them.++const std = @import("std");+const Allocator = std.mem.Allocator;++const agent_mod = @import("agent.zig");+const Agent = agent_mod.Agent;+const goal_state = @import("goal_state.zig");+const goal_todo = @import("goal_todo.zig");+const goal_verify_kind = @import("goal_verify_kind.zig");++pub const isVerification = goal_verify_kind.isVerification;++pub fn unresolvedCount(agent: *const Agent) usize {+ const epoch = goal_state.currentEpoch(agent.goal);+ var n: usize = 0;+ for (agent.todos.items) |t| {+ if (t.epoch != epoch or t.retired) continue;+ if (std.mem.eql(u8, t.status, "completed")) continue;+ if (isVerification(t.content)) n += 1;+ }+ return n;+}++pub fn hasUnresolved(agent: *const Agent) bool {+ return unresolvedCount(agent) > 0;+}++pub fn completionGate(arena: Allocator, agent: *Agent) !?[]const u8 {+ if (agent.review_mode or agent.sub) return goal_state.completionGate(arena, agent);+ if (hasUnresolved(agent)) {+ const rendered = goal_state.renderTodos(agent, goal_state.currentEpoch(agent.goal));+ return try std.fmt.allocPrint(arena, "completion deferred: {d} unresolved verification item(s) remain:\n{s}\nDropping or summarizing them does not satisfy completion. Finish the verification, or have the user change scope.", .{ unresolvedCount(agent), rendered });+ }+ return goal_state.completionGate(arena, agent);+}++/// Verified task success, not mere execution. An ordinary return with no+/// goal/eval/verification obligation is vacuously verified so recipe+/// telemetry for chat turns stays usable.+pub fn taskVerified(agent: *const Agent) bool {+ if (hasUnresolved(agent)) return false;+ if (agent.eval_cmd != null) return agent.eval_verified and !agent.eval_repair_pending;+ if (goal_state.goalActive(@constCast(agent))) {+ const epoch = goal_state.currentEpoch(agent.goal);+ if (goal_state.openCount(agent.todos.items, epoch) > 0) return false;+ if (agent.completed == null and !goal_state.checklistFinished(agent)) return false;+ }+ return true;+}++fn todoRoot(arena: Allocator) Agent {+ var root: Agent = undefined;+ root.gpa = std.testing.allocator;+ root.arena = arena;+ root.sub = false;+ root.review_mode = false;+ root.todos = .empty;+ root.goal = null;+ root.todos_dirty = false;+ root.completion_gate_armed = false;+ root.eval_cmd = null;+ root.eval_verified = false;+ root.eval_repair_pending = false;+ root.completed = null;+ return root;+}++fn todosArg(arena: Allocator, json: []const u8) !?std.json.Value {+ const parsed = try std.json.parseFromSliceLeaky(std.json.Value, arena, json, .{ .allocate = .alloc_always });+ return parsed.object.get("todos");+}++test "#844 replacing the last open verification item with a completed summary keeps the obligation" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ var root = todoRoot(ar);+ root.goal = .{ .objective = "ship the fix", .epoch = 1 };+ _ = try goal_todo.applyTodoWrite(&root, try todosArg(ar,+ \\{"todos":[{"content":"land the helper","status":"completed"},+ \\ {"content":"verify the fix","status":"pending"}]}+ ));+ try std.testing.expectEqual(@as(usize, 1), unresolvedCount(&root));+ const rendered = (try goal_todo.applyTodoWrite(&root, try todosArg(ar,+ \\{"todos":[{"content":"shipped: helper landed and looks good","status":"completed"}]}+ ))).text;+ try std.testing.expect(std.mem.indexOf(u8, rendered, "verify the fix") != null);+ try std.testing.expect(std.mem.indexOf(u8, rendered, "kept") != null or std.mem.indexOf(u8, rendered, "verify") != null);+ try std.testing.expectEqual(@as(usize, 1), unresolvedCount(&root));+ try std.testing.expect(!goal_state.checklistFinished(&root));+ try std.testing.expect(!taskVerified(&root));+}++test "#844 completion with unresolved validation is refused even when the gate is armed" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ var root = todoRoot(ar);+ root.goal = .{ .objective = "ship", .epoch = 1 };+ _ = try goal_todo.applyTodoWrite(&root, try todosArg(ar,+ \\{"todos":[{"content":"run the tests","status":"pending"}]}+ ));+ const first = (try completionGate(ar, &root)).?;+ try std.testing.expect(std.mem.indexOf(u8, first, "unresolved verification") != null);+ root.completion_gate_armed = true; // the promised second call must not waive verification+ const second = (try completionGate(ar, &root)).?;+ try std.testing.expect(std.mem.indexOf(u8, second, "unresolved verification") != null);+}++test "#844 ordinary open work can still be abandoned; verification cannot" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ var root = todoRoot(ar);+ root.goal = .{ .objective = "ship", .epoch = 1 };+ _ = try goal_todo.applyTodoWrite(&root, try todosArg(ar,+ \\{"todos":[{"content":"sketch an alternative","status":"pending"},+ \\ {"content":"verify the fix","status":"pending"}]}+ ));+ const rendered = (try goal_todo.applyTodoWrite(&root, try todosArg(ar,+ \\{"todos":[{"content":"verify the fix","status":"in_progress"}]}+ ))).text;+ try std.testing.expect(std.mem.indexOf(u8, rendered, "sketch an alternative") == null);+ try std.testing.expect(std.mem.indexOf(u8, rendered, "verify the fix") != null);+}++test "isVerification matches acceptance language and ignores ordinary chores" {+ try std.testing.expect(isVerification("verify the fix"));+ try std.testing.expect(isVerification("run the tests"));+ try std.testing.expect(isVerification("acceptance: check CI"));+ try std.testing.expect(!isVerification("write the helper"));+ try std.testing.expect(!isVerification("wire it up"));+ try std.testing.expect(!isVerification("sketch an alternative"));+}++test "taskVerified is true for ordinary chat and false with open verification" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ var root = todoRoot(ar);+ try std.testing.expect(taskVerified(&root));+ root.goal = .{ .objective = "ship", .epoch = 1, .status = .active };+ try root.todos.append(ar, .{ .content = "verify the fix", .status = "pending", .epoch = 1 });+ try std.testing.expect(!taskVerified(&root));+ root.eval_cmd = "true";+ root.eval_verified = false;+ try std.testing.expect(!taskVerified(&root));+}diff --git a/src/goal_verify_kind.zig b/src/goal_verify_kind.zignew file mode 100644index 00000000..84abeee0--- /dev/null+++ b/src/goal_verify_kind.zig@@ -0,0 +1,21 @@+//! Content classifier for acceptance/verification checklist items (#844).+//! Kept tiny so goal_todo and goal_verify can share it without a cycle.++const std = @import("std");++const needles = [_][]const u8{+ "verif", "validat", "acceptance",+ "run test", "run the test", "run ci",+ "run eval", "test it", "tests pass",+ "check ci", "prove it", "regression",+};++pub fn isVerification(content: []const u8) bool {+ if (content.len == 0) return false;+ var buf: [256]u8 = undefined;+ const n = @min(content.len, buf.len);+ for (content[0..n], 0..) |c, i| buf[i] = std.ascii.toLower(c);+ const slice = buf[0..n];+ for (needles) |need| if (std.mem.indexOf(u8, slice, need) != null) return true;+ return false;+}diff --git a/src/main.zig b/src/main.zigindex 3afdc814..7b265089 100644--- a/src/main.zig+++ b/src/main.zig@@ -571,6 +571,11 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = @import("agent_empty_completion.zig"); // #745: plain-final reconciliation_ = @import("agent_model_loop.zig");_ = @import("publication_policy_tests.zig");+ _ = @import("artifact_claim.zig");+ _ = @import("pr_publish.zig");+ _ = @import("publish_gate.zig");+ _ = @import("goal_verify.zig");+ _ = @import("goal_verify_kind.zig");_ = @import("jobs_completion_tests.zig");_ = @import("test_hooks.zig"); // unreached modules; their tests were silently skipped_ = @import("list_dir_nearmiss.zig");diff --git a/src/mainloop_trace.zig b/src/mainloop_trace.zigindex f7edaa5b..f017695d 100644--- a/src/mainloop_trace.zig+++ b/src/mainloop_trace.zig@@ -177,6 +177,12 @@ fn countEntry(shape: *ResponseShape, obj: std.json.ObjectMap, kind: []const u8)}}+/// Execution success is not verified-success (#844). A normal return with+/// unresolved verification, an unmet eval, or open goal work stays unsuccessful.+pub fn verifiedSuccess(root: *agent_mod.Agent, executed: bool) bool {+ return executed and @import("goal_verify.zig").taskVerified(root);+}+pub fn record(root: *agent_mod.Agent,io: Io,@@ -198,8 +204,13 @@ pub fn record(const turn_ok = if (result) |_| true else |_| false;const turn_tools = root.tools_used.render(arena);const after = pricing.g_cost.snap(io);+ const verified = @import("goal_verify.zig").taskVerified(root);+ const claimed = root.completed != null;const outcome: recipe.Outcome = .{- .success = turn_ok,+ .success = verifiedSuccess(root, turn_ok),+ .executed = turn_ok,+ .claimed = claimed,+ .verified = verified,.latency_ms = @intCast(@max(0, turn_ms)),.model_calls = (if (root.run_budget) |budget| budget.used() else before.model_calls) -| before.model_calls,.tool_errors = root.tools_used.errorCount(),@@ -223,6 +234,9 @@ pub fn record(.model = root.provider.model,.effort = @tagName(root.reasoning),.success = outcome.success,+ .executed = outcome.executed,+ .claimed = outcome.claimed,+ .verified = outcome.verified,.latency_ms = outcome.latency_ms,.model_calls = outcome.model_calls,.tool_calls = root.tool_calls_this_turn,@@ -412,3 +426,24 @@ test "#270: openai and Responses histories shape the same way" {try std.testing.expectEqual(@as(u32, 3), cut_after_tools.blocks);try std.testing.expectEqualStrings("text+tool_use+reasoning", cut_after_tools.typeSet(&buf));}++test "#844 a normal return is not verified-success telemetry" {+ var root: agent_mod.Agent = undefined;+ root.sub = false;+ root.review_mode = false;+ root.todos = .empty;+ root.goal = .{ .objective = "ship", .epoch = 1, .status = .active };+ root.todos_dirty = false;+ root.eval_cmd = null;+ root.eval_verified = false;+ root.eval_repair_pending = false;+ root.completed = null;+ try root.todos.append(std.testing.allocator, .{ .content = "verify the fix", .status = "pending", .epoch = 1 });+ defer root.todos.deinit(std.testing.allocator);+ try std.testing.expect(verifiedSuccess(&root, true) == false);+ try std.testing.expect(verifiedSuccess(&root, false) == false);+ root.todos.items[0].status = "completed";+ root.todos_dirty = true;+ root.completed = "done";+ try std.testing.expect(verifiedSuccess(&root, true));+}diff --git a/src/peer_channel.zig b/src/peer_channel.zigindex db47d624..9751b5f3 100644--- a/src/peer_channel.zig+++ b/src/peer_channel.zig@@ -7,7 +7,7 @@//! one-line `[peer]` wake and still paints the full lines for the human.//!//! Surfaces:-//! - peer_message: send (default), list, inbox. Queued, one-way.+//! - peer_message: send (default), list, inbox, claim, release, handoff, status.//! - /tell <session> <text>: the user's own line into a peer's inbox.//! - /sessions: the saved-session list gains a "live now" section.//! - deliverInbound: drain + park at every root step boundary.@@ -34,9 +34,9 @@ const ExecResult = tools_mod.ExecResult;const Owner = worktree_lease.Owner;pub const tool_name = "peer_message";-pub const tool_desc = "Ping a co-resident session, list who is live, or read parked inbound. action=list | inbox | send (default). session is a DM (visible title, saved-session base, id/pid/name/goal); omit for this folder's room. Presence is device-local. Not \"all\".";+pub const tool_desc = "Ping a co-resident session, list who is live, read parked inbound, or transfer an artifact claim. action=list | inbox | send (default) | claim | release | handoff | status. session is a DM (visible title, saved-session base, id/pid/name/goal); omit for this folder's room. Presence is device-local. Not \"all\".";pub const tool_schema =- \\{"type": "object", "properties": {"action": {"type": "string", "enum": ["send", "list", "inbox"], "description": "send (default): ping a peer. list: who is live (title, base, id, pid, worktree, goal). inbox: read+clear parked inbound."}, "session": {"type": "string", "description": "who to ping: exact visible title, exact saved-session base, unique normalized title/slug, id, pid, unique name fragment, or unique goal fragment (omit = this folder's room). Named targets are DMs. Presence is device-local. Not \"all\"."}, "text": {"type": "string", "description": "one or two sentences of coordination intent (required for send)"}}}+ \\{"type": "object", "properties": {"action": {"type": "string", "enum": ["send", "list", "inbox", "claim", "release", "handoff", "status"], "description": "send (default): ping a peer. list: who is live. inbox: read+clear parked inbound. claim/release/handoff/status: repository-scoped artifact ownership (kind+key)."}, "session": {"type": "string", "description": "who to ping or hand a claim to: exact visible title, exact saved-session base, unique normalized title/slug, id, pid, unique name fragment, or unique goal fragment (omit = this folder's room). Named targets are DMs. Presence is device-local. Not \"all\"."}, "text": {"type": "string", "description": "one or two sentences of coordination intent (required for send)"}, "kind": {"type": "string", "enum": ["branch", "issue", "commit", "pull_request", "publication"], "description": "artifact kind for claim/release/handoff/status"}, "key": {"type": "string", "description": "artifact key: branch name, issue number, commit SHA, or PR number"}}};/// Whether the named session sits in MY worktree (routes the post: worktree@@ -65,6 +65,16 @@ pub fn handleMessage(self: *Agent, call: ToolCall) !ExecResult {.is_error = true,};const action = tools_mod.json_args.str(obj, "action") orelse "send";+ if (std.mem.eql(u8, action, "claim") or std.mem.eql(u8, action, "release") or std.mem.eql(u8, action, "handoff") or std.mem.eql(u8, action, "status")) {+ return @import("artifact_claim.zig").handleTool(+ self.arena,+ self.io,+ action,+ tools_mod.json_args.str(obj, "kind") orelse "publication",+ tools_mod.json_args.str(obj, "key") orelse "",+ tools_mod.json_args.str(obj, "session") orelse "",+ );+ }if (std.mem.eql(u8, action, "list")) {const everyone = presence.liveAllPeers(self.io, self.arena);return .{ .text = peer_inbox.formatList(self.arena, everyone, presence.ownIdentity()), .is_error = false };@@ -73,7 +83,7 @@ pub fn handleMessage(self: *Agent, call: ToolCall) !ExecResult {return .{ .text = peer_inbox.takeAll(self.arena), .is_error = false };}if (!std.mem.eql(u8, action, "send")) return .{- .text = "peer_message action must be send, list, or inbox",+ .text = "peer_message action must be send, list, inbox, claim, release, handoff, or status",.is_error = true,};const text = tools_mod.json_args.str(obj, "text") orelse "";diff --git a/src/pr_publish.zig b/src/pr_publish.zignew file mode 100644index 00000000..8f284906--- /dev/null+++ b/src/pr_publish.zig@@ -0,0 +1,354 @@+//! Non-draft PR publication preflight (#847). The public-write note is+//! disclosure policy; this module is the readiness gate in front of raw+//! `gh pr create` (and ready/undraft) issued through bash. `gh pr checks+//! --watch` after create is not this gate.++const std = @import("std");+const Allocator = std.mem.Allocator;++pub const HeadStatus = enum { none, pending, failed, passed, unknown };++pub const Coverage = struct {+ helper_only: bool = false,+ one_separator_only: bool = false,+ untested_multi_separator: bool = false,+};++pub const Evidence = struct {+ head_sha: []const u8 = "",+ head_status: HeadStatus = .none,+ base_reproduced: bool = false,+ known_failures_disclosed: bool = false,+ body: []const u8 = "",+ coverage: Coverage = .{},+};++pub const Decision = enum { allow, block, draft_only };++const absolute_words = [_][]const u8{ "atomic", "preserved", "always", "guaranteed", "never fails", "fully preserved" };++pub fn containsToken(cmd: []const u8, needle: []const u8) bool {+ var it = std.mem.tokenizeAny(u8, cmd, " \t\r\n;&|\"'`()");+ while (it.next()) |tok| if (std.mem.eql(u8, tok, needle)) return true;+ return false;+}++fn seqAfter(cmd: []const u8, first: []const u8, second: []const u8, third: []const u8) bool {+ var it = std.mem.tokenizeAny(u8, cmd, " \t\r\n;&|\"'`()");+ var state: u8 = 0;+ while (it.next()) |tok| {+ if (state == 0 and std.mem.eql(u8, tok, first)) {+ state = 1;+ continue;+ }+ if (state == 1) {+ if (tok[0] == '-') continue;+ if (std.mem.eql(u8, tok, second)) {+ state = 2;+ continue;+ }+ state = 0;+ continue;+ }+ if (state == 2) {+ if (tok[0] == '-') continue;+ return std.mem.eql(u8, tok, third);+ }+ }+ return false;+}++pub fn isPrCreate(cmd: []const u8) bool {+ return seqAfter(cmd, "gh", "pr", "create");+}++pub fn isPrReady(cmd: []const u8) bool {+ if (seqAfter(cmd, "gh", "pr", "ready")) return true;+ if (!seqAfter(cmd, "gh", "pr", "edit")) return false;+ return std.mem.indexOf(u8, cmd, "--draft=false") != null or std.mem.indexOf(u8, cmd, "--draft false") != null;+}++pub fn isPrChecksWatch(cmd: []const u8) bool {+ return seqAfter(cmd, "gh", "pr", "checks") and containsToken(cmd, "--watch");+}++pub fn isDraftFlag(cmd: []const u8) bool {+ if (std.mem.indexOf(u8, cmd, "--draft=false") != null) return false;+ var it = std.mem.tokenizeAny(u8, cmd, " \t\r\n;&|\"'`()");+ while (it.next()) |tok| {+ if (std.mem.eql(u8, tok, "--draft") or std.mem.eql(u8, tok, "--draft=true")) return true;+ }+ return false;+}++pub fn isNonDraftPublish(cmd: []const u8) bool {+ if (isPrChecksWatch(cmd)) return false;+ if (isPrCreate(cmd)) return !isDraftFlag(cmd);+ return isPrReady(cmd);+}++fn flagValue(cmd: []const u8, flag: []const u8) []const u8 {+ const idx = std.mem.indexOf(u8, cmd, flag) orelse return "";+ var rest = std.mem.trimStart(u8, cmd[idx + flag.len ..], " \t=");+ if (rest.len == 0) return "";+ if (rest[0] == '"' or rest[0] == '\'') {+ const q = rest[0];+ const end = std.mem.indexOfScalar(u8, rest[1..], q) orelse return rest[1..];+ return rest[1 .. 1 + end];+ }+ const end = std.mem.indexOfAny(u8, rest, " \t") orelse rest.len;+ return rest[0..end];+}++pub fn extractBody(cmd: []const u8) []const u8 {+ const from_body = flagValue(cmd, "--body");+ if (from_body.len > 0) return from_body;+ return flagValue(cmd, "-b");+}++pub fn hasVerificationSection(body: []const u8) bool {+ const lower_needles = [_][]const u8{+ "## verification", "## verify", "verification",+ "commands run", "local:", "remote:",+ "zig build test", "tier 1", "ci:",+ };+ var buf: [2048]u8 = undefined;+ const n = @min(body.len, buf.len);+ for (body[0..n], 0..) |c, i| buf[i] = std.ascii.toLower(c);+ const slice = buf[0..n];+ for (lower_needles) |need| if (std.mem.indexOf(u8, slice, need) != null) return true;+ return false;+}++pub fn hasAbsoluteClaim(body: []const u8) bool {+ var buf: [2048]u8 = undefined;+ const n = @min(body.len, buf.len);+ for (body[0..n], 0..) |c, i| buf[i] = std.ascii.toLower(c);+ const slice = buf[0..n];+ for (absolute_words) |w| if (std.mem.indexOf(u8, slice, w) != null) return true;+ return false;+}++pub fn knownFailuresDisclosed(body: []const u8) bool {+ var buf: [1024]u8 = undefined;+ const n = @min(body.len, buf.len);+ for (body[0..n], 0..) |c, i| buf[i] = std.ascii.toLower(c);+ const slice = buf[0..n];+ return std.mem.indexOf(u8, slice, "known failure") != null or+ std.mem.indexOf(u8, slice, "known-failures") != null or+ std.mem.indexOf(u8, slice, "reproduced on") != null or+ std.mem.indexOf(u8, slice, "reproduces on the base") != null or+ std.mem.indexOf(u8, slice, "pre-existing on") != null;+}++pub fn claimOverreach(body: []const u8, coverage: Coverage) bool {+ if (coverage.helper_only and hasAbsoluteClaim(body)) return true;+ if (coverage.one_separator_only and coverage.untested_multi_separator) return true;+ if (!hasAbsoluteClaim(body)) return false;+ var buf: [2048]u8 = undefined;+ const n = @min(body.len, buf.len);+ for (body[0..n], 0..) |c, i| buf[i] = std.ascii.toLower(c);+ const slice = buf[0..n];+ const helperish = std.mem.indexOf(u8, slice, "helper") != null or+ std.mem.indexOf(u8, slice, "one separator") != null or+ std.mem.indexOf(u8, slice, "one-separator") != null;+ const dispatch = std.mem.indexOf(u8, slice, "dispatch") != null or+ std.mem.indexOf(u8, slice, "multiple separator") != null or+ std.mem.indexOf(u8, slice, "deletion path") != null;+ return helperish and !dispatch;+}++pub fn decide(draft: bool, ev: Evidence) Decision {+ if (draft) return .allow; // draft is the unresolved-readiness fallback+ if (claimOverreach(ev.body, ev.coverage)) return .block;+ if (!hasVerificationSection(ev.body)) return .block;+ return switch (ev.head_status) {+ .pending, .failed => if (ev.base_reproduced and (ev.known_failures_disclosed or knownFailuresDisclosed(ev.body)))+ .draft_only+ else+ .block,+ .unknown => .block,+ .none, .passed => .allow,+ };+}++pub fn reason(decision: Decision, ev: Evidence) []const u8 {+ return switch (decision) {+ .allow => "ready",+ .draft_only => "create as a draft, or disclose the base-reproduced failure in the PR body",+ .block => if (claimOverreach(ev.body, ev.coverage))+ "behavior claim overreaches the committed regression (helper/one-separator coverage is not the changed dispatch path)"+ else if (!hasVerificationSection(ev.body))+ "PR body needs a Verification section listing the commands and results actually run"+ else if (ev.head_status == .pending)+ "non-draft publication blocked: the exact head SHA still has a pending branch run"+ else if (ev.head_status == .failed)+ "non-draft publication blocked: the exact head SHA has an unexplained failed branch run"+ else+ "non-draft publication blocked: head readiness is unresolved",+ };+}++/// Classify `gh run list --json conclusion,status` output. Empty / unreadable+/// JSON is `none` so PR-only workflows stay allowed.+pub fn headStatusFromRunList(json: []const u8) HeadStatus {+ const trimmed = std.mem.trim(u8, json, " \t\r\n");+ if (trimmed.len == 0 or trimmed[0] != '[') return .none;+ const parsed = std.json.parseFromSlice(std.json.Value, std.heap.page_allocator, trimmed, .{}) catch return .none;+ defer parsed.deinit();+ if (parsed.value != .array) return .none;+ if (parsed.value.array.items.len == 0) return .none;+ var pending = false;+ var passed = false;+ for (parsed.value.array.items) |item| {+ if (item != .object) continue;+ const status = if (item.object.get("status")) |v| (if (v == .string) v.string else "") else "";+ const conclusion = if (item.object.get("conclusion")) |v| (if (v == .string) v.string else "") else "";+ if (std.mem.eql(u8, status, "in_progress") or std.mem.eql(u8, status, "queued") or std.mem.eql(u8, status, "waiting") or std.mem.eql(u8, status, "pending"))+ pending = true;+ if (std.mem.eql(u8, conclusion, "failure") or std.mem.eql(u8, conclusion, "cancelled") or std.mem.eql(u8, conclusion, "timed_out") or std.mem.eql(u8, conclusion, "startup_failure"))+ return .failed;+ if (std.mem.eql(u8, conclusion, "success")) passed = true;+ }+ if (pending) return .pending;+ if (passed) return .passed;+ return .unknown;+}++pub fn refuseText(arena: Allocator, cmd: []const u8, ev: Evidence) []const u8 {+ const draft = isDraftFlag(cmd);+ const d = decide(draft, ev);+ const why = reason(d, ev);+ return std.fmt.allocPrint(arena, "PR publication preflight: the GitHub write was NOT performed. {s}. Inspect the exact head SHA before `gh pr create`; `gh pr checks --watch` after create is not this gate. Use --draft when readiness is unresolved.", .{why}) catch why;+}++var g_evidence: ?Evidence = null;++pub fn setTestEvidence(ev: Evidence) void {+ g_evidence = ev;+}++pub fn clearTestEvidence() void {+ g_evidence = null;+}++pub fn testEvidence() ?Evidence {+ return g_evidence;+}++/// Live gatherer: tests inject evidence. Production treats a missing remote+/// run as `none` (PR-only workflows). Recorded failures stay failures.+pub fn evidenceFor(cmd: []const u8) Evidence {+ var ev = g_evidence orelse Evidence{};+ const body = extractBody(cmd);+ if (ev.body.len == 0) ev.body = body;+ if (knownFailuresDisclosed(ev.body)) ev.known_failures_disclosed = true;+ return ev;+}++pub fn gateCommand(arena: Allocator, cmd: []const u8) ?[]const u8 {+ if (isPrChecksWatch(cmd)) return null;+ if (!isPrCreate(cmd) and !isPrReady(cmd)) return null;+ const ev = evidenceFor(cmd);+ const draft = isDraftFlag(cmd) and !isPrReady(cmd);+ return switch (decide(draft, ev)) {+ .allow => null,+ .block, .draft_only => refuseText(arena, cmd, ev),+ };+}++test "classifies create, draft, ready, and checks --watch" {+ try std.testing.expect(isPrCreate("gh pr create --title x --body y"));+ try std.testing.expect(isPrCreate("GH_PAGER=cat gh pr create --fill"));+ try std.testing.expect(isDraftFlag("gh pr create --draft --title x"));+ try std.testing.expect(!isDraftFlag("gh pr create --draft=false"));+ try std.testing.expect(isNonDraftPublish("gh pr create --title x --body y"));+ try std.testing.expect(!isNonDraftPublish("gh pr create --draft --title x"));+ try std.testing.expect(isPrReady("gh pr ready"));+ try std.testing.expect(isPrChecksWatch("gh pr checks --watch"));+ try std.testing.expect(!isNonDraftPublish("gh pr checks --watch"));+}++test "#847 failed or pending head blocks non-draft create" {+ const body = "## Verification\nlocal: zig build test (pass)\nremote: pending";+ try std.testing.expectEqual(Decision.block, decide(false, .{ .head_status = .failed, .body = body }));+ try std.testing.expectEqual(Decision.block, decide(false, .{ .head_status = .pending, .body = body }));+ try std.testing.expectEqual(Decision.allow, decide(true, .{ .head_status = .failed, .body = body }));+ try std.testing.expectEqual(Decision.allow, decide(false, .{ .head_status = .passed, .body = body }));+}++test "#847 base-reproduced failure needs disclosure or a draft" {+ const bare = "## Verification\nzig build test";+ const disclosed = "## Verification\nknown failure reproduced on the base branch\nzig build test";+ try std.testing.expectEqual(Decision.block, decide(false, .{ .head_status = .failed, .base_reproduced = true, .body = bare }));+ try std.testing.expectEqual(Decision.draft_only, decide(false, .{ .head_status = .failed, .base_reproduced = true, .body = disclosed }));+ try std.testing.expectEqual(Decision.allow, decide(true, .{ .head_status = .failed, .base_reproduced = true, .body = disclosed }));+}++test "#847 PR-only workflows with no pre-PR run stay allowed" {+ const body = "## Verification\nlocal: zig build test\nremote: no pre-PR run; CI is PR-triggered";+ try std.testing.expectEqual(Decision.allow, decide(false, .{ .head_status = .none, .body = body }));+}++test "#847 missing verification section blocks non-draft" {+ try std.testing.expectEqual(Decision.block, decide(false, .{ .head_status = .passed, .body = "fixes the bug" }));+ try std.testing.expectEqual(Decision.allow, decide(false, .{ .head_status = .passed, .body = "## Verification\nzig build test: pass" }));+}++test "#847 one-separator helper test cannot publish an atomic claim" {+ const body =+ \\Atomic token deletion is preserved.+ \\## Verification+ \\helper test: one separator boundary+ ;+ const cov = Coverage{ .helper_only = true, .one_separator_only = true, .untested_multi_separator = true };+ try std.testing.expect(claimOverreach(body, cov));+ try std.testing.expectEqual(Decision.block, decide(false, .{ .head_status = .passed, .body = body, .coverage = cov }));+ const wide =+ \\Atomic delete on the dispatch path.+ \\## Verification+ \\exercised multiple separators on the deletion path+ ;+ try std.testing.expect(!claimOverreach(wide, .{}));+}++test "#847 gh pr checks --watch is not the readiness gate" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ try std.testing.expect(gateCommand(arena_state.allocator(), "gh pr checks --watch") == null);+}++test "#847 gateCommand blocks a non-draft create with failed head" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ setTestEvidence(.{+ .head_sha = "abc123",+ .head_status = .failed,+ .body = "## Verification\nzig build test",+ });+ defer clearTestEvidence();+ const msg = gateCommand(arena_state.allocator(), "gh pr create --title t --body '## Verification\nzig build test'").?;+ try std.testing.expect(std.mem.indexOf(u8, msg, "NOT performed") != null);+ try std.testing.expect(std.mem.indexOf(u8, msg, "failed") != null);+ try std.testing.expect(std.mem.indexOf(u8, msg, "checks --watch") != null);+}++test "#847 run-list JSON maps failed, pending, passed, and empty" {+ try std.testing.expectEqual(HeadStatus.failed, headStatusFromRunList(+ \\[{"conclusion":"failure","status":"completed","headSha":"abc"}]+ ));+ try std.testing.expectEqual(HeadStatus.pending, headStatusFromRunList(+ \\[{"conclusion":"","status":"in_progress","headSha":"abc"}]+ ));+ try std.testing.expectEqual(HeadStatus.passed, headStatusFromRunList(+ \\[{"conclusion":"success","status":"completed"}]+ ));+ try std.testing.expectEqual(HeadStatus.none, headStatusFromRunList("[]"));+ try std.testing.expectEqual(HeadStatus.none, headStatusFromRunList(""));+}++test "extractBody reads --body quoted text" {+ try std.testing.expectEqualStrings("hello", extractBody("gh pr create --body \"hello\" --title x"));+ try std.testing.expect(hasVerificationSection("## Verification\nran zig build test"));+ try std.testing.expect(hasAbsoluteClaim("atomic delete is preserved"));+}diff --git a/src/prompt_snapshot_tests.zig b/src/prompt_snapshot_tests.zigindex 95273a03..ea9fb44d 100644--- a/src/prompt_snapshot_tests.zig+++ b/src/prompt_snapshot_tests.zig@@ -100,6 +100,17 @@ const golden_full_prompt =\\A worker unable to ask must return a sanitized draft or request approval\\through its orchestrator, not infer consent. Never disclose secrets.\\+ \\A non-draft GitHub PR (`gh pr create` without --draft, or `gh pr ready`)+ \\is blocked until the exact head SHA is ready: inspect already-running+ \\or completed branch CI, disclose a failure that reproduces on the base+ \\branch or create a draft, and include a Verification section that lists+ \\the commands and results you actually ran. Absolute claims (atomic,+ \\preserved) need a regression on the changed dispatch path, not only a+ \\helper or one-separator boundary. `gh pr checks --watch` after create+ \\is not that gate. Publication work on a claimed branch, issue, commit,+ \\or PR is owned by one live session — acknowledge a handoff with+ \\peer_message action=handoff; polling for a missing PR does not transfer it.+ \\\\When making git commits on behalf of the user, commit as the USER's own git\\identity — do NOT override GIT_AUTHOR_*/GIT_COMMITTER_*; their configured\\name + email (matching their GitHub account) must be the commit Author, justdiff --git a/src/prompt_text.zig b/src/prompt_text.zigindex fd91166e..2cf1b8d8 100644--- a/src/prompt_text.zig+++ b/src/prompt_text.zig@@ -130,6 +130,23 @@ pub const public_write_note =\\through its orchestrator, not infer consent. Never disclose secrets.;+/// Always present (#840, #847): readiness and ownership gates for GitHub writes+/// through bash, not merely disclosure policy.+pub const publication_ready_note =+ \\+ \\+ \\A non-draft GitHub PR (`gh pr create` without --draft, or `gh pr ready`)+ \\is blocked until the exact head SHA is ready: inspect already-running+ \\or completed branch CI, disclose a failure that reproduces on the base+ \\branch or create a draft, and include a Verification section that lists+ \\the commands and results you actually ran. Absolute claims (atomic,+ \\preserved) need a regression on the changed dispatch path, not only a+ \\helper or one-separator boundary. `gh pr checks --watch` after create+ \\is not that gate. Publication work on a claimed branch, issue, commit,+ \\or PR is owned by one live session — acknowledge a handoff with+ \\peer_message action=handoff; polling for a missing PR does not transfer it.+;+/// Gate: `caps.git_repo`. Commit-identity and PR-description discipline only/// earn their tokens where a repository exists to commit to — a scratch-dir/// one-shot or an eval run pays ~250 tokens/call for guidance it can never@@ -264,12 +281,14 @@ pub const constraint_authority_note =pub fn withAuthority(arena: std.mem.Allocator, prompt: []const u8) []const u8 {const publication = std.mem.indexOf(u8, prompt, public_write_note) != null;const constraints = std.mem.indexOf(u8, prompt, constraint_authority_note) != null;- if (publication and constraints) return prompt;- return std.fmt.allocPrint(arena, "{s}{s}{s}", .{+ const ready = std.mem.indexOf(u8, prompt, publication_ready_note) != null;+ if (publication and constraints and ready) return prompt;+ return std.fmt.allocPrint(arena, "{s}{s}{s}{s}", .{prompt,if (publication) "" else public_write_note,if (constraints) "" else constraint_authority_note,- }) catch public_write_note ++ constraint_authority_note;+ if (ready) "" else publication_ready_note,+ }) catch public_write_note ++ constraint_authority_note ++ publication_ready_note;}/// Always present: how to write the final message.diff --git a/src/prompts.zig b/src/prompts.zigindex b0eced20..5d7b75a5 100644--- a/src/prompts.zig+++ b/src/prompts.zig@@ -63,6 +63,7 @@ pub const segments = [_]Segment{.{ .name = "trace", .text = text.trace_note, .gate = .local_tools },.{ .name = "harness_issue", .text = text.harness_issue_note, .gate = .local_tools },.{ .name = "public_write", .text = text.public_write_note, .gate = .always },+ .{ .name = "publication_ready", .text = text.publication_ready_note, .gate = .always },.{ .name = "git_authoring", .text = text.git_authoring_note, .gate = .git_repo },.{ .name = "git_safety", .text = text.git_safety_note, .gate = .always },.{ .name = "work", .text = text.work_note, .gate = .always },@@ -470,7 +471,7 @@ pub const sub_system_prompt =\\questions — make reasonable assumptions. Do not narrate tool calls.\\Your final message is returned verbatim to the orchestrator: a concise\\report of the concrete facts you found.-++ parallel_tools_note ++ text.public_write_note ++ text.constraint_authority_note;+++ parallel_tools_note ++ text.public_write_note ++ text.constraint_authority_note ++ text.publication_ready_note;pub const compact_instruction =\\Summarize this entire conversation for a context handoff. Capture: thediff --git a/src/publication_policy_tests.zig b/src/publication_policy_tests.zigindex 98f3ba2d..15906d02 100644--- a/src/publication_policy_tests.zig+++ b/src/publication_policy_tests.zig@@ -21,6 +21,7 @@ test "#739 publication safety survives capability removal and lean; workers sharfor ([_][]const u8{ floor, prompts.sub_system_prompt, prompts.main_system_prompt_strict }) |policy| {try std.testing.expect(std.mem.indexOf(u8, policy, text.public_write_note) != null);try std.testing.expect(std.mem.indexOf(u8, policy, text.constraint_authority_note) != null);+ try std.testing.expect(std.mem.indexOf(u8, policy, text.publication_ready_note) != null);}}for ([_][]const u8{@@ -54,11 +55,12 @@ test "#739 custom worker and review personas cannot remove standing policy" {try std.testing.expect(std.mem.startsWith(u8, policy, "CUSTOM_PERSONA"));try std.testing.expect(std.mem.indexOf(u8, policy, text.public_write_note) != null);try std.testing.expect(std.mem.indexOf(u8, policy, text.constraint_authority_note) != null);+ try std.testing.expect(std.mem.indexOf(u8, policy, text.publication_ready_note) != null);try std.testing.expectEqual(policy.ptr, text.withAuthority(agent.arena, policy).ptr);}var storage: [0]u8 = .{};var failing = std.heap.FixedBufferAllocator.init(&storage);- try std.testing.expectEqualStrings(text.public_write_note ++ text.constraint_authority_note, text.withAuthority(failing.allocator(), "CUSTOM_PERSONA"));+ try std.testing.expectEqualStrings(text.public_write_note ++ text.constraint_authority_note ++ text.publication_ready_note, text.withAuthority(failing.allocator(), "CUSTOM_PERSONA"));}test "#738 failed prompt allocation never installs only some variants" {diff --git a/src/publish_gate.zig b/src/publish_gate.zignew file mode 100644index 00000000..8297a354--- /dev/null+++ b/src/publish_gate.zig@@ -0,0 +1,90 @@+//! Bash-side publication gate (#840, #847): artifact claims and PR readiness+//! run before the command executes. Presence ACK is a separate one-shot and+//! does not clear either check.++const std = @import("std");+const builtin = @import("builtin");+const agent_mod = @import("agent.zig");+const Agent = agent_mod.Agent;+const tools_mod = @import("tools.zig");+const ExecResult = tools_mod.ExecResult;+const artifact_claim = @import("artifact_claim.zig");+const pr_publish = @import("pr_publish.zig");+const process_runner = @import("process_runner.zig");++fn primeHead(self: *Agent) void {+ if (builtin.is_test or pr_publish.testEvidence() != null) return;+ const sha_run = process_runner.runCapped(self.gpa, self.io, &.{ "git", "rev-parse", "HEAD" }, 128, 256, 5_000) catch return;+ defer self.gpa.free(sha_run.stdout);+ defer self.gpa.free(sha_run.stderr);+ if (!process_runner.ranOk(sha_run)) return;+ const sha = std.mem.trim(u8, sha_run.stdout, " \t\r\n");+ if (sha.len < 7) return;+ const sha_owned = self.arena.dupe(u8, sha) catch return;+ const list_run = process_runner.runCapped(self.gpa, self.io, &.{+ "gh", "run", "list",+ "--commit", sha_owned, "--json",+ "conclusion,status", "--limit", "20",+ }, 16 * 1024, 1024, 15_000) catch {+ pr_publish.setTestEvidence(.{ .head_sha = sha_owned, .head_status = .none });+ return;+ };+ defer self.gpa.free(list_run.stdout);+ defer self.gpa.free(list_run.stderr);+ const status = if (process_runner.ranOk(list_run)) pr_publish.headStatusFromRunList(list_run.stdout) else .none;+ pr_publish.setTestEvidence(.{ .head_sha = sha_owned, .head_status = status });+}++pub fn bash(self: *Agent, cmd: []const u8) !?ExecResult {+ if (artifact_claim.gateCommand(self.arena, self.io, cmd, "")) |blocked| return .{+ .text = blocked,+ .is_error = true,+ };+ if (!builtin.is_test and (pr_publish.isPrCreate(cmd) or pr_publish.isPrReady(cmd))) primeHead(self);+ if (pr_publish.gateCommand(self.arena, cmd)) |blocked| return .{+ .text = blocked,+ .is_error = true,+ };+ return null;+}++test "#840 conflicting gh pr create never reaches execution after an acknowledged handoff" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ artifact_claim.resetForTest();+ defer artifact_claim.resetForTest();+ pr_publish.clearTestEvidence();+ artifact_claim.setTestOwner(.{ .session = "s-owner", .pid = 1, .start_id = 1 });+ _ = try artifact_claim.handleTool(ar, std.testing.io, "claim", "publication", "", "");+ artifact_claim.setTestOwner(.{ .session = "s-other", .pid = 2, .start_id = 2 });+ artifact_claim.setTestOwnerLive(true);+ var agent: Agent = undefined;+ agent.arena = ar;+ agent.io = std.testing.io;+ const denied = (try bash(&agent, "gh pr create --title x --body '## Verification\\nzig build test'")).?;+ try std.testing.expect(denied.is_error);+ try std.testing.expect(std.mem.indexOf(u8, denied.text, "NOT performed") != null);+}++test "#847 non-draft create with failed head is stopped before bash" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ artifact_claim.resetForTest();+ defer artifact_claim.resetForTest();+ pr_publish.setTestEvidence(.{+ .head_sha = "deadbeef",+ .head_status = .failed,+ .body = "## Verification\nzig build test",+ });+ defer pr_publish.clearTestEvidence();+ var agent: Agent = undefined;+ agent.arena = ar;+ agent.io = std.testing.io;+ const denied = (try bash(&agent, "gh pr create --title t --body '## Verification\\nzig build test'")).?;+ try std.testing.expect(denied.is_error);+ try std.testing.expect(std.mem.indexOf(u8, denied.text, "preflight") != null);+ try std.testing.expect(try bash(&agent, "gh pr checks --watch") == null);+ try std.testing.expect(try bash(&agent, "gh pr create --draft --title t --body '## Verification\\nzig build test'") == null);+}diff --git a/src/recipe.zig b/src/recipe.zigindex f152be30..5b2ca34f 100644--- a/src/recipe.zig+++ b/src/recipe.zig@@ -124,6 +124,9 @@ pub fn record(/// scalar that a recipe might game.pub const Outcome = struct {success: bool,+ executed: bool = false,+ claimed: bool = false,+ verified: bool = false,latency_ms: u64,model_calls: u64,tool_errors: u64,