Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

Claim gate: honor an explicit PR target this session owns

justracha2dfb44a5608
diff --git a/src/artifact_claim.zig b/src/artifact_claim.zig
index 036fe967..a6605be6 100644
--- a/src/artifact_claim.zig
+++ b/src/artifact_claim.zig
@@ -191,7 +191,7 @@ pub fn gateCommandIn(arena: Allocator, io: Io, cmd: []const u8, key: []const u8,
}
// A failed `gh pr view` is unknown identity, not "PR N in no repo" (#1344).
const unresolved = kind == .pull_request and resolved == null and (!builtin.is_test or unresolved_mod.g_force_for_test);
- var target: @import("artifact_claim_target.zig").Target = if (unresolved) unresolved_mod.target(cmd) else if (kind == .pull_request and !builtin.is_test)
+ var target: @import("artifact_claim_target.zig").Target = if (unresolved) unresolved_mod.target(arena, cmd) else if (kind == .pull_request and !builtin.is_test)
resolved.?
else
resolved orelse @import("artifact_claim_target.zig").explicit(cmd, kind) orelse .{ .kind = if (kind == .issue) Kind.issue else Kind.branch, .key = key };
@@ -199,7 +199,7 @@ pub fn gateCommandIn(arena: Allocator, io: Io, cmd: []const u8, key: []const u8,
for (ledger.slice()) |c| {
if (!claimRelevant(c.kind, kind)) continue;
if (unresolved) {
- if (sameOwner(c.owner, me) or !ownerLive(io, c.owner) or unresolved_mod.provablyUnrelated(c, target)) continue;
+ if (sameOwner(c.owner, me) or !ownerLive(io, c.owner) or unresolved_mod.provablyUnrelated(ledger.slice(), me, c, target)) continue;
return unresolved_mod.refuseText(arena, c, target);
}
const branch_claim = c.kind == .publication or c.kind == .branch;
diff --git a/src/artifact_claim_identity.zig b/src/artifact_claim_identity.zig
new file mode 100644
index 00000000..fb2308c9
--- /dev/null
+++ b/src/artifact_claim_identity.zig
@@ -0,0 +1,137 @@
+//! The PR a command names before any run-time text (#1340).
+//!
+//! A body built with `$(...)` makes the whole command unparseable for the
+//! GitHub lookup, but a PR number, `--head`, or `--repo` written ahead of it
+//! is still literal. Words after the first dynamic word or shell separator
+//! are never read: only the shell knows where they begin and end.
+
+const std = @import("std");
+const pr_command = @import("pr_command.zig");
+const target_mod = @import("artifact_claim_target.zig");
+const Target = target_mod.Target;
+
+/// The literal PR number, the `--head` branch of a create, and `--repo`.
+/// Anything not written literally stays unknown (an empty key, a null branch).
+pub fn target(a: std.mem.Allocator, cmd: []const u8) Target {
+ var t: Target = .{ .kind = .pull_request, .key = "" };
+ const w = literalPrefix(a, cmd);
+ if (w.len < 3 or !std.mem.eql(u8, std.fs.path.basename(w[0]), "gh")) return t;
+ var i: usize = 1;
+ while (i < w.len and !std.mem.eql(u8, w[i], "pr")) : (i += 1) {
+ if (std.mem.startsWith(u8, w[i], "--repo=")) {
+ t.repo = w[i][7..];
+ } else if (std.mem.eql(u8, w[i], "-R") or std.mem.eql(u8, w[i], "--repo")) {
+ i += 1;
+ if (i < w.len) t.repo = w[i];
+ } else return t;
+ }
+ if (i + 1 >= w.len) return t;
+ const create = std.mem.eql(u8, w[i + 1], "create");
+ var head: ?[]const u8 = null;
+ var selector: ?[]const u8 = null;
+ // An unknown option may take the next word as its value.
+ var positional = true;
+ i += 2;
+ while (i < w.len) : (i += 1) {
+ const arg = w[i];
+ if (pr_command.takesValue(arg)) {
+ i += 1;
+ if (i >= w.len) break;
+ if (std.mem.eql(u8, arg, "--head") or std.mem.eql(u8, arg, "-H")) head = w[i];
+ if (std.mem.eql(u8, arg, "--repo") or std.mem.eql(u8, arg, "-R")) t.repo = w[i];
+ continue;
+ }
+ if (std.mem.startsWith(u8, arg, "--head=")) {
+ head = arg[7..];
+ } else if (std.mem.startsWith(u8, arg, "--repo=")) {
+ t.repo = arg[7..];
+ } else if (std.mem.startsWith(u8, arg, "-")) {
+ if (!pr_command.isSwitch(arg) and std.mem.indexOfScalar(u8, arg, '=') == null) positional = false;
+ } else if (selector != null or !positional) {
+ selector = null;
+ positional = false;
+ } else selector = arg;
+ }
+ if (create) {
+ const branch = target_mod.unqualifiedHead(head orelse return t);
+ if (branch.len > 0) t.branch = branch;
+ return t;
+ }
+ const number = selector orelse return t;
+ for (number) |c| if (!std.ascii.isDigit(c)) return t;
+ t.key = number;
+ return t;
+}
+
+/// Unquoted words up to the first dynamic word or shell separator. A leading
+/// literal `cd DIR &&` is skipped, as `pr_command.literal` does.
+fn literalPrefix(a: std.mem.Allocator, cmd: []const u8) []const []const u8 {
+ var words: std.ArrayList([]const u8) = .empty;
+ var i: usize = 0;
+ while (true) {
+ while (i < cmd.len) {
+ if (cmd[i] == ' ' or cmd[i] == '\t') {
+ i += 1;
+ } else if (cmd[i] == '\\' and i + 1 < cmd.len and cmd[i + 1] == '\n') {
+ i += 2; // line continuation
+ } else break;
+ }
+ if (i == cmd.len) return words.items;
+ if (std.mem.startsWith(u8, cmd[i..], "&&") and words.items.len == 2 and std.mem.eql(u8, words.items[0], "cd")) {
+ words.clearRetainingCapacity();
+ i += 2;
+ continue;
+ }
+ var word: std.ArrayList(u8) = .empty;
+ var quote: u8 = 0;
+ while (i < cmd.len) : (i += 1) {
+ const c = cmd[i];
+ if (quote == 0 and (c == ' ' or c == '\t')) break;
+ if (quote == 0 and c == '\\' and i + 1 < cmd.len and cmd[i + 1] == '\n') break;
+ if (quote != '\'' and (c == '$' or c == '`')) return words.items;
+ if (quote == 0 and std.mem.indexOfScalar(u8, "|;&<>()#\n\r", c) != null) return words.items;
+ if (c == '\\' and quote != '\'') {
+ i += 1;
+ if (i == cmd.len) return words.items;
+ word.append(a, cmd[i]) catch return words.items;
+ } else if (c == quote) {
+ quote = 0;
+ } else if (quote == 0 and (c == '\'' or c == '"')) {
+ quote = c;
+ } else word.append(a, c) catch return words.items;
+ }
+ if (quote != 0) return words.items;
+ words.append(a, word.items) catch return words.items;
+ }
+}
+
+test "#1340 the PR number, head, and repo before a dynamic body are literal" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const edit = target(a, "cd '../my tree' && gh pr edit 42 --repo owner/repo --body \"$(cat notes.md)\"");
+ try std.testing.expectEqualStrings("42", edit.key);
+ try std.testing.expectEqualStrings("owner/repo", edit.repo.?);
+ const create = target(a, "gh pr create --repo owner/repo --base main --head me:feat/x --title 'Fix (it)' --body \"$(cat <<'EOF'\nbody\nEOF\n)\"");
+ try std.testing.expectEqualStrings("", create.key);
+ try std.testing.expectEqualStrings("feat/x", create.branch.?);
+ try std.testing.expectEqualStrings("7", target(a, "gh -R owner/repo pr ready \\\n 7").key);
+ try std.testing.expectEqualStrings("7", target(a, "gh pr comment 7 --edit-last --body x").key);
+}
+
+test "#1340 run-time or ambiguous words never become the target" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ for ([_][]const u8{
+ "gh pr edit --body \"$(cat notes.md)\" 42",
+ "gh pr edit $PR --body x",
+ "gh pr edit --unknown 42",
+ "gh pr edit 42 43",
+ "gh pr edit feature --body x",
+ "git log && gh pr edit 42",
+ "bash -lc 'gh pr ready 42'",
+ }) |cmd| try std.testing.expectEqualStrings("", target(a, cmd).key);
+ try std.testing.expect(target(a, "gh pr create --body \"$(cat b)\" --head feat/x").branch == null);
+ try std.testing.expect(target(a, "gh pr edit 42 --head feat/x").branch == null);
+}
diff --git a/src/artifact_claim_target.zig b/src/artifact_claim_target.zig
index dfcee45a..03ecbc69 100644
--- a/src/artifact_claim_target.zig
+++ b/src/artifact_claim_target.zig
@@ -4,7 +4,7 @@ const claims = @import("artifact_claim.zig");
pub const Target = struct { kind: claims.Kind, key: []const u8, repo: ?[]const u8 = null, branch: ?[]const u8 = null, head_repo: ?[]const u8 = null };
-fn unqualifiedHead(head: []const u8) []const u8 {
+pub fn unqualifiedHead(head: []const u8) []const u8 {
return if (std.mem.lastIndexOfScalar(u8, head, ':')) |i| head[i + 1 ..] else head;
}
diff --git a/src/artifact_claim_unresolved.zig b/src/artifact_claim_unresolved.zig
index 2e4da637..f6ce67bf 100644
--- a/src/artifact_claim_unresolved.zig
+++ b/src/artifact_claim_unresolved.zig
@@ -15,43 +15,146 @@ const Target = @import("artifact_claim_target.zig").Target;
/// Tests take the unresolved path; production reaches it when the lookup fails.
pub var g_force_for_test = false;
-/// The literal PR number from the command, or an unknown target.
-pub fn target(cmd: []const u8) Target {
- const t = @import("artifact_claim_target.zig").explicit(cmd, .pull_request) orelse return .{ .kind = .pull_request, .key = "" };
- return if (t.kind == .pull_request) t else .{ .kind = .pull_request, .key = "" };
+/// The literal PR number (or a create's `--head`) from the command, or an
+/// unknown target.
+pub fn target(a: std.mem.Allocator, cmd: []const u8) Target {
+ return @import("artifact_claim_identity.zig").target(a, cmd);
}
-/// A different numbered PR is another artifact whatever its branch.
-pub fn provablyUnrelated(c: ledger.Claim, t: Target) bool {
- return c.kind == .pull_request and t.key.len > 0 and c.key.len > 0 and !std.mem.eql(u8, c.key, t.key);
+/// A different numbered PR is another artifact whatever its branch. When
+/// this session holds the explicit target itself (#1340), a foreign claim on
+/// another named PR or branch is another artifact too. A foreign claim on the
+/// same PR or head branch, or a worktree-wide one, still blocks.
+pub fn provablyUnrelated(claims: []const ledger.Claim, me: ledger.Owner, c: ledger.Claim, t: Target) bool {
+ if (c.kind == .pull_request and t.key.len > 0 and c.key.len > 0 and !std.mem.eql(u8, c.key, t.key)) return true;
+ if (c.key.len == 0 or !ownsTarget(claims, me, t)) return false;
+ return switch (c.kind) {
+ .pull_request => !std.mem.eql(u8, c.key, t.key),
+ .branch, .publication, .commit => if (t.branch) |b| !std.mem.eql(u8, c.key, b) else true,
+ .issue => true,
+ };
+}
+
+/// This session's own claim on the PR number, or on the head branch a create
+/// names, in the repository the command names (when both are known).
+pub fn ownsTarget(claims: []const ledger.Claim, me: ledger.Owner, t: Target) bool {
+ for (claims) |c| {
+ if (!ledger.sameOwner(c.owner, me) or c.key.len == 0 or !sameRepository(c.repo, t.repo)) continue;
+ if (c.kind == .pull_request and std.mem.eql(u8, c.key, t.key)) return true;
+ if ((c.kind == .branch or c.kind == .publication) and t.branch != null and std.mem.eql(u8, c.key, t.branch.?)) return true;
+ }
+ return false;
+}
+
+/// A claim's `host/owner/repo` against a command's `[host/]owner/repo`.
+fn sameRepository(claim_repo: ?[]const u8, flag: ?[]const u8) bool {
+ const held = claim_repo orelse return true;
+ const named = flag orelse return true;
+ if (std.ascii.eqlIgnoreCase(held, named)) return true;
+ return held.len > named.len and held[held.len - named.len - 1] == '/' and std.ascii.eqlIgnoreCase(held[held.len - named.len ..], named);
}
pub fn refuseText(a: std.mem.Allocator, c: ledger.Claim, t: Target) []const u8 {
- return std.fmt.allocPrint(a, "artifact claim check: could not resolve which pull request this command targets{s}{s}{s} (the GitHub lookup failed), so another session's live {s} claim {s} blocks it conservatively. NOT performed; no handoff was requested because that claim was not shown to cover this PR. Retry the command, or run it from the PR's own worktree.", .{
- if (t.key.len > 0) " (#" else "",
- t.key,
- if (t.key.len > 0) ")" else "",
+ const what = if (t.key.len > 0)
+ std.fmt.allocPrint(a, " (#{s})", .{t.key}) catch ""
+ else if (t.branch) |b|
+ std.fmt.allocPrint(a, " (head {s})", .{b}) catch ""
+ else
+ "";
+ return std.fmt.allocPrint(a, "artifact claim check: could not resolve which pull request this command targets{s} (the GitHub lookup failed), so another session's live {s} claim {s} blocks it conservatively. NOT performed; no handoff was requested because that claim was not shown to cover this PR. Retry the command, or claim this PR number (or a create's --head branch) for this session and write it literally before any $(...) text.", .{
+ what,
@tagName(c.kind),
if (c.key.len > 0) c.key else "(worktree)",
}) catch "artifact claim check: the pull request target could not be resolved; NOT performed";
}
+test {
+ _ = @import("artifact_claim_identity.zig");
+}
+
test "an unresolved explicit PR skips a different numbered claim only" {
- const t = target("gh pr edit 42 --body-file notes.md");
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const t = target(a, "gh pr edit 42 --body-file notes.md");
try std.testing.expectEqualStrings("42", t.key);
+ const me: ledger.Owner = .{ .session = "me", .pid = 2 };
const other: ledger.Claim = .{ .kind = .pull_request, .key = "7", .owner = .{ .session = "peer", .pid = 1 } };
const same: ledger.Claim = .{ .kind = .pull_request, .key = "42", .owner = .{ .session = "peer", .pid = 1 } };
const branch: ledger.Claim = .{ .kind = .branch, .key = "feature", .owner = .{ .session = "peer", .pid = 1 } };
- try std.testing.expect(provablyUnrelated(other, t));
- try std.testing.expect(!provablyUnrelated(same, t));
- try std.testing.expect(!provablyUnrelated(branch, t));
- try std.testing.expect(!provablyUnrelated(other, target("gh pr edit --body-file notes.md")));
- const text = refuseText(std.testing.allocator, branch, t);
- defer std.testing.allocator.free(text);
+ try std.testing.expect(provablyUnrelated(&.{}, me, other, t));
+ try std.testing.expect(!provablyUnrelated(&.{}, me, same, t));
+ try std.testing.expect(!provablyUnrelated(&.{}, me, branch, t));
+ try std.testing.expect(!provablyUnrelated(&.{}, me, other, target(a, "gh pr edit --body-file notes.md")));
+ const text = refuseText(a, branch, t);
try std.testing.expect(std.mem.indexOf(u8, text, "(#42)") != null);
try std.testing.expect(std.mem.indexOf(u8, text, "no handoff was requested") != null);
}
+test "#1340 owning the explicit PR or head makes only other named claims unrelated" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const me: ledger.Owner = .{ .session = "me", .pid = 2 };
+ const peer: ledger.Owner = .{ .session = "peer", .pid = 1 };
+ const mine = [_]ledger.Claim{
+ .{ .kind = .pull_request, .key = "42", .owner = me, .repo = "github.com/owner/repo" },
+ .{ .kind = .branch, .key = "feat/mine", .owner = me, .repo = "github.com/owner/repo" },
+ };
+ const edit = target(a, "gh pr edit 42 --repo Owner/Repo --body \"$(cat notes.md)\"");
+ const unrelated: ledger.Claim = .{ .kind = .branch, .key = "feature", .owner = peer };
+ const worktree: ledger.Claim = .{ .kind = .publication, .key = "", .owner = peer };
+ try std.testing.expect(ownsTarget(&mine, me, edit));
+ try std.testing.expect(provablyUnrelated(&mine, me, unrelated, edit));
+ try std.testing.expect(!provablyUnrelated(&mine, me, worktree, edit));
+ // Another repository's PR 42 is not the one this session holds.
+ try std.testing.expect(!ownsTarget(&mine, me, target(a, "gh pr edit 42 --repo owner/fork --body x")));
+ // A claim the peer holds is not this session's.
+ try std.testing.expect(!ownsTarget(&mine, peer, edit));
+ // A create's owned head: a peer's claim on that same branch still blocks.
+ const create = target(a, "gh pr create --repo owner/repo --head feat/mine --body \"$(cat b)\"");
+ try std.testing.expect(provablyUnrelated(&mine, me, unrelated, create));
+ try std.testing.expect(!provablyUnrelated(&mine, me, .{ .kind = .publication, .key = "feat/mine", .owner = peer }, create));
+ const text = refuseText(a, worktree, create);
+ try std.testing.expect(std.mem.indexOf(u8, text, "(head feat/mine)") != null);
+}
+
+test "#1340 the gate honors an owned explicit PR and still respects a foreign branch" {
+ const claims = @import("artifact_claim.zig");
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const ar = arena_state.allocator();
+ const io = std.testing.io;
+ claims.resetForTest();
+ defer claims.resetForTest();
+ g_force_for_test = true;
+ defer g_force_for_test = false;
+ claims.setTestOwner(.{ .session = "s-other" });
+ _ = try claims.handleTool(ar, io, "claim", "branch", "feature", "");
+ claims.setTestOwner(.{ .session = "s-me" });
+ claims.setTestOwnerLive(true);
+ const edit = "cd ../my-tree && gh pr edit 42 --repo owner/repo --body \"$(cat notes.md)\"";
+ const ready = "gh pr ready 42 --repo owner/repo";
+ // Unowned, the PR's head is unknown and the foreign branch claim may cover it.
+ try std.testing.expect(claims.gateCommand(ar, io, edit, "") != null);
+ _ = try claims.handleTool(ar, io, "claim", "pull_request", "42", "");
+ try std.testing.expect(claims.gateCommand(ar, io, edit, "") == null);
+ try std.testing.expect(claims.gateCommand(ar, io, ready, "") == null);
+ try std.testing.expect(claims.gateCommand(ar, io, "gh pr ready 43 --repo owner/repo", "") != null);
+ try std.testing.expect(claims.gateCommand(ar, io, "gh pr edit --body \"$(cat notes.md)\" 42", "") != null);
+ // Creating from an owned head; the foreign branch itself stays respected.
+ _ = try claims.handleTool(ar, io, "claim", "branch", "feat/mine", "");
+ const body = " --title 'Fix it' --body \"$(cat <<'EOF'\nbody\nEOF\n)\"";
+ try std.testing.expect(claims.gateCommand(ar, io, try std.fmt.allocPrint(ar, "gh pr create --repo owner/repo --base main --head feat/mine{s}", .{body}), "") == null);
+ const foreign = claims.gateCommand(ar, io, try std.fmt.allocPrint(ar, "gh pr create --repo owner/repo --base main --head feature{s}", .{body}), "") orelse return error.TestUnexpectedResult;
+ try std.testing.expect(std.mem.indexOf(u8, foreign, "branch claim feature") != null);
+ // A foreign worktree-wide claim still blocks even an owned target.
+ claims.setTestOwner(.{ .session = "s-other" });
+ _ = try claims.handleTool(ar, io, "claim", "publication", "", "");
+ claims.setTestOwner(.{ .session = "s-me" });
+ try std.testing.expect(claims.gateCommand(ar, io, ready, "") != null);
+}
+
test "#1344 the gate: another numbered PR claim does not block, a branch claim explains without a handoff" {
const claims = @import("artifact_claim.zig");
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
diff --git a/src/pr_command.zig b/src/pr_command.zig
index 06930726..f59ad4b6 100644
--- a/src/pr_command.zig
+++ b/src/pr_command.zig
@@ -59,12 +59,7 @@ pub const Command = struct {
if (std.mem.indexOfScalar(u8, arg, '=')) |eq| {
if (takesValue(arg[0..eq])) continue;
}
- var known = false;
- for ([_][]const u8{ "--draft", "--draft=true", "--undo", "--help", "--web", "--force", "--delete-branch", "--squash", "--merge", "--rebase", "--auto", "--disable-auto", "--admin", "--remove-milestone", "--edit-last", "--delete-last", "--create-if-none", "--yes" }) |option| if (std.mem.eql(u8, arg, option)) {
- known = true;
- break;
- };
- if (!known) return error.UnsupportedOption;
+ if (!isSwitch(arg)) return error.UnsupportedOption;
continue;
}
if (selected != null) return error.AmbiguousSelector;
@@ -74,7 +69,13 @@ pub const Command = struct {
}
};
-fn takesValue(arg: []const u8) bool {
+/// A known option that takes no value.
+pub fn isSwitch(arg: []const u8) bool {
+ for ([_][]const u8{ "--draft", "--draft=true", "--undo", "--help", "--web", "--force", "--delete-branch", "--squash", "--merge", "--rebase", "--auto", "--disable-auto", "--admin", "--remove-milestone", "--edit-last", "--delete-last", "--create-if-none", "--yes" }) |option| if (std.mem.eql(u8, arg, option)) return true;
+ return false;
+}
+
+pub fn takesValue(arg: []const u8) bool {
for ([_][]const u8{ "--body", "-b", "--body-file", "-F", "--title", "-t", "--head", "-H", "--base", "-B", "--repo", "-R", "--reviewer", "-r", "--assignee", "-a", "--label", "-l", "--milestone", "-m", "--project", "-p", "--template", "-T" }) |flag| if (std.mem.eql(u8, arg, flag)) return true;
// #1344: edit/close/comment/merge options; an unknown one used to make an
// explicit `gh pr edit N` unresolvable, so the claim gate blocked on any