Skip to content

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

Python

fix: scope artifact ownership to repository and PR target

justrach38a8ba242a60
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index b770d5bc..24f67b74 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -77,6 +77,8 @@ jobs:
python3 scripts/test-acp-failure.py
python3 scripts/regression-release-297.py
python3 scripts/test-pr-completion-acp.py
+ python3 scripts/test-claim-repository.py
+ python3 scripts/eval-tier2.py --only repository-scoped-claim-release
python3 scripts/eval-tier2.py --only draft-cannot-waive-pr-completion --only base-failure-cannot-waive-pr-completion --only user-authorized-draft-handoff --only draft-scope-does-not-waive-ready-pr-ci --only user-can-require-verified-pr-again --only current-head-passing-pr-completes
- name: Local learning lifecycle and security regression
diff --git a/docs/adr/0121-claims-include-repository-identity.md b/docs/adr/0121-claims-include-repository-identity.md
new file mode 100644
index 00000000..db80bc27
--- /dev/null
+++ b/docs/adr/0121-claims-include-repository-identity.md
@@ -0,0 +1,45 @@
+# 0121. Artifact claims include repository identity
+
+Status: accepted 2026-09-15
+
+## Context
+
+A live publication claim could block edits to a separately owned PR in another
+repository. The ledger stored only artifact kind and key, so matching names or
+numbers collided across repositories. Publication claims also could not be
+compared with a numbered PR's branch (#925).
+
+## Decision
+
+Claims persist a canonical host/owner/repository identity. Claim, release,
+handoff and status accept an optional `repo`, defaulting to the workspace
+repository resolved by GitHub CLI. The same artifact key may exist in distinct
+known repositories. Unknown scope remains conservative; ambiguous operations
+must specify a repository rather than choose the first matching record.
+
+Before a literal PR mutation, observe its repository URL, number and head
+branch through GitHub CLI. Compare publication/branch claims with that branch
+and PR claims with its number. A fork head repository also participates in
+branch/publication ownership; unknown head identity stays conservative. PR URLs and
+options before the selector retain the same identity. Unknown shell forms and
+unavailable evidence cannot release a live claim. Git mutations retain their
+existing conservative checks; this is not a universal shell sandbox.
+
+Legacy records have unknown repository scope. Their live owner can re-claim
+the artifact with a resolved repository to bind it without a release window.
+Other sessions cannot rebind a live owner's claim. Scope is retained through
+handoff and serialization; repository lookup failure is never proof of freedom.
+
+## Verification and costs
+
+Two live harness processes exercise edit and ready across repositories,
+branches and hosts, PR URLs, flag order, unavailable evidence and legacy
+migration. The old release blocks the independent-repository case. A JSON
+behavior case proves releasing one repository's PR claim preserves another
+with the same number. Pure tests cover persistence and ownership transitions.
+
+Claim operations may perform a bounded read-only repository lookup. PR target
+lookups occur only when foreign claims exist. Remote lookups run outside the
+ledger lock; mutation gating reloads the ledger afterward so a peer can release
+its claim during a slow lookup and the decision sees that release. No ownership database outside
+the existing workspace ledger is introduced.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 5c126f77..76880455 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -129,6 +129,7 @@ record only when you need the evidence or the edge cases.
| [0118](0118-file-edits-check-target-worktree.md) | File edits checkpoint the target Git worktree; unresolved paths retain the caller checkpoint. |
| [0119](0119-computer-tools-receive-caller-context.md) | Computer-use MCP requests receive opaque caller-owned session and turn context. |
| [0120](0120-draft-publication-does-not-complete-verification.md) | Draft PRs cannot satisfy verified completion; only a user control scoped to this conversation and goal permits an unverified draft handoff. |
+| [0121](0121-claims-include-repository-identity.md) | Claims include repository identity; literal PR mutations compare the observed repository, PR number and branch, while unknown scopes stay conservative. |
## When to write one
diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonl
index 5a4afc0a..e9d7fe2c 100644
--- a/evals/harness_behavior.jsonl
+++ b/evals/harness_behavior.jsonl
@@ -101,3 +101,4 @@
{"id":"draft-scope-does-not-waive-ready-pr-ci","why":"#931: draft-only permission does not turn failed ready-PR checks into verified completion.","args":["--old","--goal","Deliver a PR with passing current-head CI"],"env":{"GRAFF_NO_CODEDB_GUARD":"1"},"github_fixture":{"checks":"FAILURE","runs":"none"},"prompt":"Run the local publication fixture and fulfill the objective.","script":[{"tool":"todo_write","arguments":{"todos":[{"content":"inspect exact-head CI","status":"pending"}]}},{"tool":"bash","arguments":{"command":"gh pr create --title fixture --body-file notes.md"}},{"tool":"todo_write","arguments":{"todos":[{"content":"provide draft handoff","status":"completed"}]}},{"tool":"attempt_completion","arguments":{"result":"Draft handoff; the base checks also fail."}},{"tool":"attempt_completion","arguments":{"result":"Draft handoff; the base checks also fail."}},{"text":"CI is unresolved."}],"assert":[{"events_at_least":{"match":{"type":"tool_call_finished","name":"attempt_completion","is_error":true},"count":2}},{"no_event":{"type":"tool_call_finished","name":"attempt_completion","is_error":false}},{"request_contains":{"text":"Draft publication and base-branch failures do not waive verification."}},{"request_contains":{"text":"provide draft handoff"}}],"prompt_options":{"prAcceptance":"draft"}}
{"id":"user-can-require-verified-pr-again","why":"#931: explicit verified scope revokes draft-only permission before the next user turn.","args":["--old","--goal","Deliver a PR with passing current-head CI"],"env":{"GRAFF_NO_CODEDB_GUARD":"1"},"github_fixture":{"checks":"FAILURE","runs":"failure"},"prompt":"Run the local publication fixture and fulfill the objective.","script":[{"text":"Draft scope selected."},{"tool":"todo_write","arguments":{"todos":[{"content":"inspect exact-head CI","status":"pending"}]}},{"tool":"bash","arguments":{"command":"gh pr create --draft --title fixture --body-file notes.md"}},{"tool":"todo_write","arguments":{"todos":[{"content":"provide draft handoff","status":"completed"}]}},{"tool":"attempt_completion","arguments":{"result":"Draft handoff; the base checks also fail."}},{"tool":"attempt_completion","arguments":{"result":"Draft handoff; the base checks also fail."}},{"text":"CI is unresolved."}],"assert":[{"events_at_least":{"match":{"type":"tool_call_finished","name":"attempt_completion","is_error":true},"count":2}},{"no_event":{"type":"tool_call_finished","name":"attempt_completion","is_error":false}},{"request_contains":{"text":"Draft publication and base-branch failures do not waive verification."}},{"request_contains":{"text":"provide draft handoff"}}],"prompt_options":{"prAcceptance":"verified"},"controls_before_prompt":[{"type":"user","text":"Allow a draft-only scope.","prAcceptance":"draft"}]}
{"id":"current-head-passing-pr-completes","why":"#931: default verified acceptance still permits a ready PR with fresh passing head checks.","args":["--old","--goal","Deliver a PR with passing current-head CI"],"env":{"GRAFF_NO_CODEDB_GUARD":"1"},"github_fixture":{"checks":"SUCCESS","runs":"success"},"prompt":"Run the local publication fixture and fulfill the objective.","script":[{"tool":"todo_write","arguments":{"todos":[{"content":"inspect exact-head CI","status":"pending"}]}},{"tool":"bash","arguments":{"command":"gh pr create --title fixture --body-file notes.md"}},{"tool":"todo_write","arguments":{"todos":[{"content":"provide draft handoff","status":"completed"}]}},{"tool":"attempt_completion","arguments":{"result":"Verified PR complete."}}],"assert":[{"event":{"type":"tool_call_finished","name":"attempt_completion","is_error":false}},{"final_text_contains":"Verified PR complete."}]}
+{"id":"repository-scoped-claim-release","why":"#925: production claim dispatch and persisted records must distinguish identical PR numbers in different repositories; releasing one must preserve the other.","args":["--old"],"github_fixture":{},"prompt":"Acquire the two repository claims, release the first, and inspect the second.","script":[{"tool":"peer_message","arguments":{"action":"claim","kind":"pull_request","key":"1","repo":"fixture/first"}},{"tool":"peer_message","arguments":{"action":"claim","kind":"pull_request","key":"1","repo":"fixture/second"}},{"tool":"peer_message","arguments":{"action":"release","kind":"pull_request","key":"1","repo":"fixture/first"}},{"tool":"peer_message","arguments":{"action":"status","kind":"pull_request","key":"1","repo":"fixture/second"}},{"text":"The second repository claim remains held."}],"assert":[{"request_contains":{"text":"claim pull_request 1: mine"}},{"events_at_most":{"match":{"type":"tool_call_finished","name":"peer_message","is_error":true},"count":0}},{"final_text_contains":"The second repository claim remains held."}]}
diff --git a/scripts/eval/github_fixture.py b/scripts/eval/github_fixture.py
index 5d586c39..a5001f4c 100644
--- a/scripts/eval/github_fixture.py
+++ b/scripts/eval/github_fixture.py
@@ -6,13 +6,19 @@ import subprocess
import sys
GH = r'''
-import json, pathlib, subprocess, sys
+import json, pathlib, subprocess, sys, time
root=pathlib.Path(__file__).resolve().parent.parent
state=json.loads((root/'gh-state.json').read_text())
args=sys.argv[1:]
with (root/'gh-argv.jsonl').open('a') as f:f.write(json.dumps(args)+'\n')
+if len(args)>2 and args[0] in ('--repo','-R'): args=args[2:]+['--repo',args[1]]
head=subprocess.check_output(['GIT_EXE','rev-parse','HEAD'],cwd=root,text=True).strip()
-if args[:2]==['run','list']:
+if args[:2]==['repo','view']:
+ if state.get('repo_unavailable'): sys.exit(1)
+ selected=args[-1] if '--' in args else state.get('repo','fixture/primary')
+ url=selected if selected.startswith('https://') else 'https://github.com/'+selected
+ print(json.dumps({'url':url}))
+elif args[:2]==['run','list']:
if state.get('unavailable'):sys.exit(1)
sha=args[args.index('--commit')+1]
status=state.get('runs','success') if sha==state['initial_head'] else state.get('new_runs','failure')
@@ -22,11 +28,22 @@ if args[:2]==['run','list']:
elif args[:1]==['api']:
print(state.get('remote_head', head))
elif args[:2]==['pr','view']:
+ if state.get('wait_release') and '--json' in args and args[args.index('--json')+1].startswith('number,'):
+ (root/'lookup-start').touch()
+ deadline=time.monotonic()+12
+ while not (root/'release-done').exists():
+ if time.monotonic()>deadline: sys.exit(89)
+ time.sleep(.02)
+ if state.get('pr_unavailable'): sys.exit(1)
+ selected=args[args.index('--repo')+1] if '--repo' in args else state.get('repo','fixture/primary')
+ url=selected if selected.startswith('https://') else 'https://github.com/'+selected
+ selector=args[2] if len(args)>2 and not args[2].startswith('-') else '1'
+ if selector.startswith('https://') and '/pull/' in selector: url=selector.rsplit('/pull/',1)[0]
remote=state.get('remote_head',head)
status=state.get('checks','PENDING')
checks=[] if status=='NONE' else [{'state':status}]
- print(json.dumps({'headRefOid':remote,'isDraft':state.get('draft',False),'body':'## Verification\nLocal tests passed.','statusCheckRollup':checks}))
-elif args[:2] in (['pr','create'],['pr','ready']):
+ print(json.dumps({'headRefOid':remote,'isDraft':state.get('draft',False),'body':'## Verification\nLocal tests passed.','statusCheckRollup':checks,'headRefName':state.get('head_branch','fixture'),'number':1,'url':url+'/pull/1','headRepository':{'nameWithOwner':state.get('head_repo',url.split('://',1)[-1].split('/',1)[1])}}))
+elif args[:2] in (['pr','create'],['pr','ready'],['pr','edit']):
with (root/'mutations.jsonl').open('a') as f:f.write(json.dumps(args)+'\n')
if '--draft' in args:state['draft']=True
if args[:2]==['pr','ready']:state['draft']=False
diff --git a/scripts/test-claim-repository.py b/scripts/test-claim-repository.py
new file mode 100644
index 00000000..41a1d0d4
--- /dev/null
+++ b/scripts/test-claim-repository.py
@@ -0,0 +1,169 @@
+#!/usr/bin/env python3
+"""Two live harness processes verify repository and PR artifact ownership.
+All GitHub calls use a local fixture; no remote mutation is possible.
+"""
+import argparse
+import json
+import os
+from pathlib import Path
+import signal
+import subprocess
+import sys
+import tempfile
+import threading
+sys.path.insert(0, str(Path(__file__).resolve().parent / 'eval'))
+from github_fixture import prepare
+from mock_model import ScriptedModel
+
+
+def tool(name, **arguments):
+ return {'tool': name, 'arguments': arguments}
+
+
+CASES = {
+ 'release-during-lookup': dict(owner='fixture/primary', caller='fixture/primary', held='feature', allow=True, wait_release=True),
+ 'different-repositories': dict(owner='fixture/primary', caller='fixture/other', held='feature', allow=True),
+ 'same-artifact': dict(owner='fixture/primary', caller='fixture/primary', held='feature', allow=False),
+ 'different-branches': dict(owner='fixture/primary', caller='fixture/primary', held='unrelated', allow=True),
+ 'different-hosts': dict(owner='https://git.example/fixture/primary', caller='fixture/primary', held='feature', allow=True),
+ 'pr-url': dict(owner='fixture/primary', caller='fixture/other', held='feature', allow=True, url=True),
+ 'flags-first': dict(owner='fixture/primary', caller='fixture/primary', held='unrelated', allow=True, flags_first=True),
+ 'unknown-pr': dict(owner='fixture/primary', caller='fixture/other', held='feature', allow=False, pr_unavailable=True),
+ 'legacy-unknown': dict(owner='fixture/primary', caller='fixture/other', held='feature', allow=False, legacy=True),
+ 'legacy-rebound': dict(owner='fixture/primary', caller='fixture/other', held='feature', allow=True, legacy=True, rebind=True),
+ 'fork-owner': dict(owner='fork/primary', caller='fixture/primary', held='feature', allow=False, head_repo='fork/primary'),
+ 'unrelated-fork': dict(owner='unrelated/primary', caller='fixture/primary', held='feature', allow=True, head_repo='fork/primary'),
+ 'unrelated-base-branch': dict(owner='fixture/primary', caller='fixture/primary', held='feature', allow=True, head_repo='fork/primary', owner_kind='branch'),
+}
+
+
+class Model(ScriptedModel):
+ def __init__(self, case):
+ super().__init__([])
+ self.case = case
+ self.counts = {}
+ self.owner_ready = threading.Event()
+ self.work = None
+
+ def next_reply(self, body):
+ actor = 'owner' if 'fixture-owner-only' in json.dumps(body) else 'caller'
+ with self._lock:
+ self.requests.append(body)
+ step = self.counts.get(actor, 0)
+ self.counts[actor] = step + 1
+ c = self.case
+ if actor == 'owner':
+ if step == 0:
+ return tool('peer_message', action='claim', kind=c.get('owner_kind','publication'), key=c['held'], repo=c['owner'])
+ if c.get('wait_release') and step == 2:
+ return tool('peer_message', action='release', kind='publication', key=c['held'], repo=c['owner'])
+ if c.get('wait_release') and step == 3:
+ assert 'claim released' in json.dumps(body), body
+ (self.work/'release-done').touch()
+ if c.get('legacy') and step == 1:
+ command = "python3 - <<'PYCLAIM'\nimport json\nfrom pathlib import Path\np=Path('.graff/artifact-claims.json')\nrows=json.loads(p.read_text())\nfor row in rows: row.pop('repo',None)\np.write_text(json.dumps(rows))\nPYCLAIM"
+ return tool('bash', command=command)
+ if c.get('rebind') and step == 2:
+ return tool('peer_message', action='claim', kind=c.get('owner_kind','publication'), key=c['held'], repo=c['owner'])
+ self.owner_ready.set()
+ return {'text': 'Claim remains held.'}
+ selector = f'https://github.com/{c["caller"]}/pull/1' if c.get('url') else '1'
+ option = '' if c.get('url') else f' --repo {c["caller"]}'
+ edit = f'gh pr edit {selector}{option} --title fixture'
+ ready = f'gh pr ready {selector}{option}'
+ if c.get('flags_first'):
+ edit = f'gh --repo {c["caller"]} pr edit --title fixture 1'
+ ready = f'gh --repo {c["caller"]} pr ready 1'
+ steps = [
+ tool('peer_message', action='claim', kind='branch', key='feature', repo=c.get('head_repo',c['caller'])),
+ tool('peer_message', action='claim', kind='pull_request', key='1', repo=c['caller']),
+ tool('bash', command=edit), tool('bash', command=ready),
+ {'text': 'Ownership result observed.'},
+ ]
+ return steps[min(step, len(steps)-1)]
+
+
+def run_case(binary, name, case, evidence):
+ model = Model(case)
+ with tempfile.TemporaryDirectory(prefix='graff-claim-repo-') as temp:
+ work = Path(temp)
+ model.work = work
+ env = {k: v for k, v in os.environ.items() if not k.endswith('_API_KEY')}
+ env.update(HOME=temp, LMSTUDIO_API_KEY='local', GRAFF_NO_TELEMETRY='1',
+ GRAFF_FLEET='off', GRAFF_NO_SMOLIFY='1', GRAFF_NO_CODEDB_GUARD='1')
+ state = dict(checks='SUCCESS', head_branch='feature', pr_unavailable=case.get('pr_unavailable', False))
+ state['wait_release'] = case.get('wait_release', False)
+ if 'head_repo' in case: state['head_repo'] = case['head_repo']
+ prepare(work, env, state)
+ model.start(1234)
+ owner = None
+ release_thread = None
+ stop_release = threading.Event()
+ try:
+ argv = [binary, '--json', '--yolo', '--old', '--model', 'lmstudio']
+ owner = subprocess.Popen(argv, cwd=work, env=env, stdin=subprocess.PIPE,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ text=True, start_new_session=True)
+ owner.stdin.write(json.dumps({'type': 'user', 'text': 'fixture-owner-only: acquire publication ownership and hold it.'})+'\n')
+ owner.stdin.flush()
+ assert model.owner_ready.wait(30), 'owner did not claim'
+ assert owner.poll() is None, 'owner exited'
+ if case.get('wait_release'):
+ def release_when_lookup_starts():
+ while not stop_release.wait(.02):
+ if (work/'lookup-start').exists():
+ owner.stdin.write(json.dumps({'type':'user','text':'fixture-owner-only: release the claim now.'})+'\n')
+ owner.stdin.flush()
+ return
+ release_thread = threading.Thread(target=release_when_lookup_starts)
+ release_thread.start()
+ done = subprocess.run(argv, cwd=work, env=env, input=json.dumps({'type': 'user', 'text': 'Claim the target branch and PR, then edit and mark it ready.'})+'\n', capture_output=True, text=True, timeout=45)
+ events = [json.loads(line) for line in done.stdout.splitlines() if line.startswith('{')]
+ claims = json.loads((work/'.graff/artifact-claims.json').read_text())
+ mutations = (work/'mutations.jsonl').read_text().splitlines() if (work/'mutations.jsonl').exists() else []
+ if evidence:
+ dest = evidence/name
+ dest.mkdir(parents=True, exist_ok=True)
+ (dest/'events.jsonl').write_text(done.stdout)
+ (dest/'stderr.log').write_text(done.stderr)
+ (dest/'requests.json').write_text(json.dumps(model.requests, indent=2))
+ (dest/'claims.json').write_text(json.dumps(claims, indent=2))
+ (dest/'mutations.json').write_text(json.dumps(mutations, indent=2))
+ assert done.returncode == 0, done.stderr[-1500:]
+ assert owner.poll() is None, 'owner must remain live through both mutations'
+ owner_held = any(c['kind']==case.get('owner_kind','publication') and c['pid']==owner.pid for c in claims)
+ assert owner_held != case.get('wait_release', False), claims
+ assert any(c['kind']=='pull_request' and c['key']=='1' and c['pid']!=owner.pid for c in claims), claims
+ results = [e for e in events if e.get('type')=='tool_result' and e.get('name')=='bash']
+ assert len(results)==2, results
+ assert all(e.get('is_error') != case['allow'] for e in results), results
+ assert len(mutations)==(2 if case['allow'] else 0), mutations
+ if not case['allow']:
+ assert all('artifact claim held' in e['text'] for e in results), results
+ print(f'PASS {name}: both mutations {"allowed" if case["allow"] else "blocked"} with owner still live', flush=True)
+ finally:
+ stop_release.set()
+ if release_thread: release_thread.join(timeout=2)
+ if owner:
+ try: os.killpg(owner.pid, signal.SIGKILL)
+ except ProcessLookupError: pass
+ owner.wait(timeout=3)
+ owner.stdin.close()
+ model.stop()
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--graff', default='zig-out/bin/graff')
+ parser.add_argument('--only', choices=CASES)
+ parser.add_argument('--evidence', type=Path)
+ args = parser.parse_args()
+ binary = str(Path(args.graff).resolve())
+ for name, case in CASES.items():
+ if args.only and name != args.only:
+ continue
+ run_case(binary, name, case, args.evidence)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/src/artifact_claim.zig b/src/artifact_claim.zig
index 61f5c673..0e599dfe 100644
--- a/src/artifact_claim.zig
+++ b/src/artifact_claim.zig
@@ -14,148 +14,20 @@ 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.pid == 0 and b.pid == 0) return a.session.len > 0 and std.mem.eql(u8, a.session, b.session);
- return a.pid != 0 and a.pid == b.pid and a.start_id == b.start_id and std.mem.eql(u8, a.session, b.session);
-}
-
-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;
-}
+const claim_ledger = @import("artifact_claim_ledger.zig");
+pub const Kind = claim_ledger.Kind;
+pub const Owner = claim_ledger.Owner;
+pub const Claim = claim_ledger.Claim;
+pub const Verdict = claim_ledger.Verdict;
+pub const max_claims = claim_ledger.max_claims;
+pub const Ledger = claim_ledger.Ledger;
+pub const kindFrom = claim_ledger.kindFrom;
+pub const sameOwner = claim_ledger.sameOwner;
+pub const verdict = claim_ledger.verdict;
+pub const find = claim_ledger.find;
+pub const acquire = claim_ledger.acquire;
+pub const release = claim_ledger.release;
+pub const handoff = claim_ledger.handoff;
/// Git / GitHub writes that must not proceed under a foreign live claim.
pub fn isClaimedMutation(cmd: []const u8) bool {
@@ -248,31 +120,63 @@ fn claimRelevant(held: Kind, mutation: Kind) bool {
}
pub fn gateCommand(arena: Allocator, io: Io, cmd: []const u8, key: []const u8) ?[]const u8 {
+ return gateCommandIn(arena, io, cmd, key, ".");
+}
+
+pub fn gateCommandIn(arena: Allocator, io: Io, cmd: []const u8, key: []const u8, cwd: []const u8) ?[]const u8 {
if (!isClaimedMutation(cmd)) return null;
var scratch = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer scratch.deinit();
- const tx = begin(io, scratch.allocator()) catch return "artifact claim ledger unavailable or busy: action NOT performed";
- defer if (tx) |transaction| transaction.end();
- var local: Ledger = .{};
- const ledger = if (tx != null) &local else &g_ledger;
- if (tx) |transaction| loadTransaction(transaction, ledger) catch return "artifact claim ledger unreadable: action NOT performed";
+ var local = readSnapshot(io, scratch.allocator()) catch return "artifact claim ledger unreadable or busy: action NOT performed";
+ const ledger = &local;
+ if (ledger.len == 0) return null;
const kind = mutationKind(cmd);
- const compound = std.mem.indexOfAny(u8, cmd, ";|&`$\n") != null;
const me = selfOwner(io);
- const target: @import("artifact_claim_target.zig").Target = @import("artifact_claim_target.zig").explicit(cmd, kind) orelse .{ .kind = if (kind == .issue) Kind.issue else Kind.branch, .key = key };
+ // Avoid remote lookups when every potentially relevant claim is ours.
+ var foreign = false;
+ for (ledger.slice()) |c| if (!sameOwner(c.owner, me)) {
+ foreign = true;
+ break;
+ };
+ if (!foreign) return null;
+ const resolved = if (builtin.is_test) null else @import("artifact_claim_target.zig").resolve(arena, io, cmd, kind, cwd);
+ // The remote read does not hold the ledger lock. A handoff/release during
+ // that read must be observed before deciding whether this action may run.
+ const tx = begin(io, scratch.allocator()) catch return "artifact claim ledger unavailable or busy: action NOT performed";
+ defer if (tx) |transaction| transaction.end();
+ local = .{};
+ if (tx) |transaction| {
+ loadTransaction(transaction, ledger) catch return "artifact claim ledger unreadable: action NOT performed";
+ } else local = g_ledger;
+ const compound = resolved == null and std.mem.indexOfAny(u8, cmd, ";|&`$\n") != null;
+ var target: @import("artifact_claim_target.zig").Target = resolved orelse @import("artifact_claim_target.zig").explicit(cmd, kind) orelse .{ .kind = if (kind == .issue) Kind.issue else Kind.branch, .key = key };
+ if (target.kind == .branch and target.key.len == 0) target.key = key;
for (ledger.slice()) |c| {
if (!compound and !claimRelevant(c.kind, kind)) continue;
- const comparable = c.kind == target.kind or (c.kind == .publication and target.kind == .branch);
- if (!compound and comparable and target.key.len > 0 and c.key.len > 0 and !std.mem.eql(u8, c.key, target.key)) continue;
- if (verdict(ledger.slice(), c.kind, c.key, me, ownerLive(io, c.owner)) == .foreign_live)
- return refuseText(arena, c.kind, c.key, c.owner);
+ const branch_claim = c.kind == .publication or c.kind == .branch;
+ if (!compound and c.kind == .branch and claim_ledger.differentRepository(c.repo, target.head_repo)) continue;
+ if (!compound and claim_ledger.differentRepository(c.repo, target.repo)) {
+ // A fork's branch can own the same PR's publication work. Unknown
+ // head repository evidence must not silently release that claim.
+ if (!branch_claim or claim_ledger.differentRepository(c.repo, target.head_repo)) continue;
+ }
+ const compare_key = if (branch_claim and target.branch != null) target.branch.? else target.key;
+ const comparable = c.kind == target.kind or (branch_claim and (target.kind == .branch or target.branch != null));
+ if (!compound and comparable and compare_key.len > 0 and c.key.len > 0 and !std.mem.eql(u8, c.key, compare_key)) continue;
+ if (!sameOwner(c.owner, me) and ownerLive(io, c.owner)) return refuseText(arena, c.kind, c.key, c.owner);
}
return null;
}
pub fn handleTool(arena: Allocator, io: Io, action: []const u8, kind_s: []const u8, key: []const u8, to_session: []const u8) !ExecResult {
+ return handleToolIn(arena, io, action, kind_s, key, to_session, ".", null);
+}
+
+pub fn handleToolIn(arena: Allocator, io: Io, action: []const u8, kind_s: []const u8, key: []const u8, to_session: []const u8, cwd: []const u8, requested_repo: ?[]const u8) !ExecResult {
var scratch = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer scratch.deinit();
+ const repo = if (builtin.is_test and requested_repo == null) null else @import("artifact_repository.zig").resolve(arena, io, cwd, requested_repo);
+ if (requested_repo != null and repo == null) return .{ .text = "claim repository could not be resolved; no claim changed", .is_error = true };
const tx = begin(io, scratch.allocator()) catch return .{ .text = "claim ledger unavailable or busy", .is_error = true };
defer if (tx) |transaction| transaction.end();
var local: Ledger = .{};
@@ -285,10 +189,11 @@ pub fn handleTool(arena: Allocator, io: Io, action: []const u8, kind_s: []const
};
const me = selfOwner(io);
const now: i64 = 0;
- const existing = find(ledger.slice(), kind, key);
+ if (claim_ledger.ambiguous(ledger.slice(), kind, key, repo)) return .{ .text = "claim repository is ambiguous; specify repo explicitly", .is_error = true };
+ const existing = claim_ledger.findIn(ledger.slice(), kind, key, repo);
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(ledger, storage, kind, key, me, now, live) catch |err| switch (err) {
+ const msg = claim_ledger.acquireIn(ledger, storage, kind, key, me, now, live, repo) 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 },
};
@@ -296,7 +201,7 @@ pub fn handleTool(arena: Allocator, io: Io, action: []const u8, kind_s: []const
return .{ .text = msg, .is_error = false };
}
if (std.mem.eql(u8, action, "release")) {
- const msg = release(ledger, kind, key, me, live) catch return .{
+ const msg = claim_ledger.releaseIn(ledger, kind, key, me, live, repo) catch return .{
.text = "cannot release a live foreign claim",
.is_error = true,
};
@@ -319,7 +224,7 @@ pub fn handleTool(arena: Allocator, io: Io, action: []const u8, kind_s: []const
.id => |id| id,
else => receiver.start_id,
};
- const msg = handoff(ledger, storage, kind, key, me, .{ .session = receiver.session_id, .pid = receiver.pid, .start_id = start_id }, now, live) catch |err| switch (err) {
+ const msg = claim_ledger.handoffIn(ledger, storage, kind, key, me, .{ .session = receiver.session_id, .pid = receiver.pid, .start_id = start_id }, now, live, repo) 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 },
@@ -329,7 +234,7 @@ pub fn handleTool(arena: Allocator, io: Io, action: []const u8, kind_s: []const
}
if (std.mem.eql(u8, action, "status")) {
if (existing) |c| {
- const v = verdict(ledger.slice(), kind, key, me, live);
+ const v = claim_ledger.verdictIn(ledger.slice(), kind, key, me, live, repo);
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 };
@@ -348,6 +253,14 @@ fn begin(io: Io, arena: Allocator) !?@import("repo_transaction.zig").Transaction
return try @import("repo_transaction.zig").Transaction.begin(io, arena, path);
}
+fn readSnapshot(io: Io, arena: Allocator) !Ledger {
+ const tx = try begin(io, arena);
+ defer if (tx) |transaction| transaction.end();
+ var ledger: Ledger = .{};
+ if (tx) |transaction| try loadTransaction(transaction, &ledger) else return g_ledger;
+ return ledger;
+}
+
fn loadTransaction(tx: @import("repo_transaction.zig").Transaction, ledger: *Ledger) !void {
const text = try tx.read() orelse return;
try loadJson(tx.arena, ledger, text);
diff --git a/src/artifact_claim_ledger.zig b/src/artifact_claim_ledger.zig
new file mode 100644
index 00000000..afc8ad9d
--- /dev/null
+++ b/src/artifact_claim_ledger.zig
@@ -0,0 +1,222 @@
+//! Pure artifact ownership transitions, including repository identity.
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+
+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,
+ repo: ?[]const u8 = null, // legacy/unknown claims stay conservative
+};
+
+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.pid == 0 and b.pid == 0) return a.session.len > 0 and std.mem.eql(u8, a.session, b.session);
+ return a.pid != 0 and a.pid == b.pid and a.start_id == b.start_id and std.mem.eql(u8, a.session, b.session);
+}
+
+fn sameKey(a: Claim, kind: Kind, key: []const u8, repo: ?[]const u8) bool {
+ if (differentRepository(a.repo, repo)) return false;
+ 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 verdictIn(claims: []const Claim, kind: Kind, key: []const u8, me: Owner, owner_live: bool, repo: ?[]const u8) Verdict {
+ for (claims) |c| {
+ if (!sameKey(c, kind, key, repo)) continue;
+ if (sameOwner(c.owner, me)) return .mine;
+ return if (owner_live) .foreign_live else .stale;
+ }
+ return .free;
+}
+
+pub fn findIn(claims: []const Claim, kind: Kind, key: []const u8, repo: ?[]const u8) ?Claim {
+ for (claims) |c| if (sameKey(c, kind, key, repo)) return c;
+ return null;
+}
+
+pub fn acquireIn(ledger: *Ledger, arena: Allocator, kind: Kind, key: []const u8, me: Owner, now_ms: i64, owner_live: bool, repo: ?[]const u8) ![]const u8 {
+ if (ambiguous(ledger.slice(), kind, key, repo)) return error.AmbiguousClaim;
+ switch (verdictIn(ledger.slice(), kind, key, me, owner_live, repo)) {
+ .mine => {
+ if (repo) |r| for (ledger.items[0..ledger.len]) |*c| {
+ if (sameKey(c.*, kind, key, repo) and c.repo == null) c.repo = try arena.dupe(u8, r);
+ };
+ 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, repo)) {
+ 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,
+ .repo = if (repo) |r| try arena.dupe(u8, r) else null,
+ };
+ 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,
+ .repo = if (repo) |r| try arena.dupe(u8, r) else null,
+ };
+ ledger.len += 1;
+ return "claim acquired";
+}
+
+pub fn releaseIn(ledger: *Ledger, kind: Kind, key: []const u8, me: Owner, owner_live: bool, repo: ?[]const u8) ![]const u8 {
+ if (ambiguous(ledger.slice(), kind, key, repo)) return error.AmbiguousClaim;
+ switch (verdictIn(ledger.slice(), kind, key, me, owner_live, repo)) {
+ .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, repo)) {
+ ledger.items[i] = ledger.items[ledger.len - 1];
+ ledger.len -= 1;
+ return "claim released";
+ }
+ i += 1;
+ }
+ return "no claim to release";
+}
+
+pub fn handoffIn(ledger: *Ledger, arena: Allocator, kind: Kind, key: []const u8, from: Owner, to: Owner, now_ms: i64, owner_live: bool, repo: ?[]const u8) ![]const u8 {
+ if (ambiguous(ledger.slice(), kind, key, repo)) return error.AmbiguousClaim;
+ if (sameOwner(from, to)) return "handoff to self is a no-op";
+ switch (verdictIn(ledger.slice(), kind, key, from, owner_live, repo)) {
+ .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, repo)) 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;
+}
+
+pub fn differentRepository(a: ?[]const u8, b: ?[]const u8) bool {
+ return a != null and b != null and !std.mem.eql(u8, a.?, b.?);
+}
+
+pub fn ambiguous(claims: []const Claim, kind: Kind, key: []const u8, repo: ?[]const u8) bool {
+ var count: usize = 0;
+ for (claims) |c| if (sameKey(c, kind, key, repo)) {
+ count += 1;
+ };
+ return count > 1;
+}
+
+pub fn verdict(claims: []const Claim, kind: Kind, key: []const u8, me: Owner, owner_live: bool) Verdict {
+ return verdictIn(claims, kind, key, me, owner_live, null);
+}
+
+pub fn find(claims: []const Claim, kind: Kind, key: []const u8) ?Claim {
+ return findIn(claims, kind, key, null);
+}
+
+pub fn acquire(ledger: *Ledger, arena: Allocator, kind: Kind, key: []const u8, me: Owner, now_ms: i64, owner_live: bool) ![]const u8 {
+ return acquireIn(ledger, arena, kind, key, me, now_ms, owner_live, null);
+}
+
+pub fn release(ledger: *Ledger, kind: Kind, key: []const u8, me: Owner, owner_live: bool) ![]const u8 {
+ return releaseIn(ledger, kind, key, me, owner_live, null);
+}
+
+pub fn handoff(ledger: *Ledger, arena: Allocator, kind: Kind, key: []const u8, from: Owner, to: Owner, now_ms: i64, owner_live: bool) ![]const u8 {
+ return handoffIn(ledger, arena, kind, key, from, to, now_ms, owner_live, null);
+}
+
+test "repository scopes separate identical artifacts and keep handoffs local" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var ledger: Ledger = .{};
+ const first = Owner{ .session = "first" };
+ const second = Owner{ .session = "second" };
+ const receiver = Owner{ .session = "receiver" };
+ _ = try acquireIn(&ledger, a, .pull_request, "1", first, 0, false, "github.com/org/first");
+ _ = try acquireIn(&ledger, a, .pull_request, "1", second, 0, false, "github.com/org/second");
+ try std.testing.expectEqual(@as(usize, 2), ledger.len);
+ try std.testing.expect(sameOwner(findIn(ledger.slice(), .pull_request, "1", "github.com/org/first").?.owner, first));
+ try std.testing.expect(ambiguous(ledger.slice(), .pull_request, "1", null));
+ try std.testing.expect(!ambiguous(ledger.slice(), .pull_request, "1", "github.com/org/second"));
+ _ = try handoffIn(&ledger, a, .pull_request, "1", second, receiver, 1, true, "github.com/org/second");
+ _ = try releaseIn(&ledger, .pull_request, "1", first, true, "github.com/org/first");
+ try std.testing.expectEqual(@as(usize, 1), ledger.len);
+ try std.testing.expect(sameOwner(ledger.items[0].owner, receiver));
+ try std.testing.expectEqualStrings("github.com/org/second", ledger.items[0].repo.?);
+}
+
+test "legacy unknown repository claims cannot be bypassed by a new scoped claim" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ var ledger: Ledger = .{};
+ _ = try acquire(&ledger, arena.allocator(), .branch, "feature", .{ .session = "first" }, 0, false);
+ try std.testing.expectError(error.ClaimHeld, acquireIn(&ledger, arena.allocator(), .branch, "feature", .{ .session = "second" }, 1, true, "github.com/org/other"));
+ try std.testing.expect(!differentRepository(null, "github.com/org/other"));
+ _ = try acquireIn(&ledger, arena.allocator(), .branch, "feature", .{ .session = "first" }, 1, true, "github.com/org/first");
+ try std.testing.expectEqualStrings("github.com/org/first", ledger.items[0].repo.?);
+}
diff --git a/src/artifact_claim_store.zig b/src/artifact_claim_store.zig
index 0854ff6c..891cfed9 100644
--- a/src/artifact_claim_store.zig
+++ b/src/artifact_claim_store.zig
@@ -16,6 +16,8 @@ pub fn persistJson(arena: Allocator, ledger: *const Ledger) ![]const u8 {
try s.write(@tagName(c.kind));
try s.objectField("key");
try s.write(c.key);
+ try s.objectField("repo");
+ try s.write(c.repo);
try s.objectField("session");
try s.write(c.owner.session);
try s.objectField("pid");
@@ -37,18 +39,40 @@ pub fn loadJson(arena: Allocator, ledger: *Ledger, text: []const u8) !void {
const kind_s = if (item.object.get("kind")) |v| (if (v == .string) v.string else return error.InvalidClaimLedger) else return error.InvalidClaimLedger;
const kind = kindFrom(kind_s) orelse return error.InvalidClaimLedger;
const key = if (item.object.get("key")) |v| (if (v == .string) v.string else return error.InvalidClaimLedger) else return error.InvalidClaimLedger;
+ const repo: ?[]const u8 = if (item.object.get("repo")) |v| switch (v) {
+ .null => null,
+ .string => if (@import("artifact_repository.zig").valid(v.string)) try std.ascii.allocLowerString(arena, v.string) else return error.InvalidClaimLedger,
+ else => return error.InvalidClaimLedger,
+ } else null;
const session = if (item.object.get("session")) |v| (if (v == .string) v.string else return error.InvalidClaimLedger) else return error.InvalidClaimLedger;
const pid: i32 = if (item.object.get("pid")) |v| (if (v == .integer and v.integer >= 0 and v.integer <= std.math.maxInt(i32)) @intCast(v.integer) else return error.InvalidClaimLedger) else 0;
const start_id: u64 = if (item.object.get("start_id")) |v| (if (v == .integer and v.integer >= 0) @intCast(v.integer) else return error.InvalidClaimLedger) else 0;
if (ledger.len >= max_claims) return error.InvalidClaimLedger;
for (ledger.slice()) |c| {
- if (c.kind == kind and std.mem.eql(u8, c.key, key)) return error.InvalidClaimLedger;
+ if (c.kind == kind and std.mem.eql(u8, c.key, key) and !@import("artifact_claim_ledger.zig").differentRepository(c.repo, repo)) return error.InvalidClaimLedger;
}
ledger.items[ledger.len] = .{
.kind = kind,
+ .repo = repo,
.key = try arena.dupe(u8, key),
.owner = .{ .session = try arena.dupe(u8, session), .pid = pid, .start_id = start_id },
};
ledger.len += 1;
}
}
+
+test "repository scopes survive persistence while legacy records stay unknown" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const scoped = "[{\"kind\":\"issue\",\"key\":\"1\",\"session\":\"a\",\"repo\":\"github.com/org/first\"},{\"kind\":\"issue\",\"key\":\"1\",\"session\":\"b\",\"repo\":\"github.com/org/second\"}]";
+ var ledger: Ledger = .{};
+ try loadJson(a, &ledger, scoped);
+ var restored: Ledger = .{};
+ try loadJson(a, &restored, try persistJson(a, &ledger));
+ try std.testing.expectEqual(@as(usize, 2), restored.len);
+ try std.testing.expectEqualStrings("github.com/org/second", restored.items[1].repo.?);
+ try loadJson(a, &ledger, "[{\"kind\":\"issue\",\"key\":\"1\",\"session\":\"a\"}]");
+ try std.testing.expect(ledger.items[0].repo == null);
+ try std.testing.expectError(error.InvalidClaimLedger, loadJson(a, &ledger, "[{\"kind\":\"issue\",\"key\":\"1\",\"session\":\"a\",\"repo\":\"invalid\"}]"));
+}
diff --git a/src/artifact_claim_target.zig b/src/artifact_claim_target.zig
index eb07363e..dfcee45a 100644
--- a/src/artifact_claim_target.zig
+++ b/src/artifact_claim_target.zig
@@ -2,7 +2,11 @@
const std = @import("std");
const claims = @import("artifact_claim.zig");
-pub const Target = struct { kind: claims.Kind, key: []const u8 };
+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 {
+ return if (std.mem.lastIndexOfScalar(u8, head, ':')) |i| head[i + 1 ..] else head;
+}
pub fn explicit(cmd: []const u8, kind: claims.Kind) ?Target {
// Do not infer one target for a compound command.
@@ -13,12 +17,41 @@ pub fn explicit(cmd: []const u8, kind: claims.Kind) ?Target {
var object = false;
var action = false;
while (words.next()) |word| {
- if (std.mem.eql(u8, previous, "--head") or std.mem.eql(u8, previous, "-H")) return .{ .kind = .branch, .key = word };
- if (std.mem.startsWith(u8, word, "--head=")) return .{ .kind = .branch, .key = word[7..] };
- if (action) return if (!std.mem.startsWith(u8, word, "-")) .{ .kind = kind, .key = word } else null;
+ if (std.mem.eql(u8, previous, "--head") or std.mem.eql(u8, previous, "-H")) return .{ .kind = .branch, .key = unqualifiedHead(word) };
+ if (std.mem.startsWith(u8, word, "--head=")) return .{ .kind = .branch, .key = unqualifiedHead(word[7..]) };
+ if (action) {
+ // Branch names and URLs need a fresh PR lookup before comparing
+ // them with a numeric claim. Unknown evidence stays conservative.
+ if (word.len == 0) return null;
+ for (word) |c| if (!std.ascii.isDigit(c)) return null;
+ return .{ .kind = kind, .key = word };
+ }
if (object and (std.mem.eql(u8, word, "edit") or std.mem.eql(u8, word, "ready") or std.mem.eql(u8, word, "close") or std.mem.eql(u8, word, "reopen") or std.mem.eql(u8, word, "comment"))) action = true;
if ((kind == .issue and std.mem.eql(u8, word, "issue")) or (kind == .pull_request and std.mem.eql(u8, word, "pr"))) object = true;
previous = word;
}
return null;
}
+
+/// Only a fully parsed literal PR command may narrow repository ownership.
+/// A branch lookup lets publication/branch claims match a numbered PR.
+pub fn resolve(a: std.mem.Allocator, io: std.Io, cmd: []const u8, kind: claims.Kind, cwd: []const u8) ?Target {
+ const parsed = @import("pr_command.zig").parse(a, cmd) catch return null;
+ const work = if (parsed.cwd) |path| std.fs.path.resolve(a, &.{ cwd, path }) catch return null else cwd;
+ const selector = parsed.selectorChecked() catch return null;
+ if (!std.mem.eql(u8, parsed.verb, "create")) {
+ const pr = @import("artifact_repository.zig").pullRequest(a, io, .{
+ .cwd = work,
+ .repo = parsed.flag("--repo", "-R"),
+ .selector = selector orelse "",
+ }) orelse return null;
+ return .{ .kind = kind, .key = pr.number, .repo = pr.repo, .branch = pr.branch, .head_repo = pr.head_repo };
+ }
+ const repo = @import("artifact_repository.zig").resolve(a, io, work, parsed.flag("--repo", "-R"));
+ if (parsed.flag("--head", "-H")) |head| {
+ const branch = unqualifiedHead(head);
+ // Fork-qualified create has no observed head repository yet.
+ return .{ .kind = .branch, .key = branch, .branch = branch, .repo = if (std.mem.indexOfScalar(u8, head, ':') == null) repo else null };
+ }
+ return .{ .kind = .branch, .key = "", .repo = repo };
+}
diff --git a/src/artifact_repository.zig b/src/artifact_repository.zig
new file mode 100644
index 00000000..936ec2b3
--- /dev/null
+++ b/src/artifact_repository.zig
@@ -0,0 +1,73 @@
+//! Repository identity comes from the CLI that will perform the mutation.
+//! Missing evidence stays unknown; it never releases an ownership claim.
+const std = @import("std");
+const evidence = @import("pr_evidence.zig");
+const A = std.mem.Allocator;
+
+pub fn valid(identity: []const u8) bool {
+ if (identity.len == 0 or identity.len > 2048) return false;
+ var parts = std.mem.splitScalar(u8, identity, '/');
+ var count: usize = 0;
+ while (parts.next()) |part| {
+ if (part.len == 0 or std.mem.eql(u8, part, ".") or std.mem.eql(u8, part, "..")) return false;
+ for (part) |c| if (!std.ascii.isAlphanumeric(c) and c != '.' and c != '-' and c != '_' and (count != 0 or c != ':')) return false;
+ count += 1;
+ }
+ return count == 3;
+}
+
+pub fn fromUrl(a: A, url: []const u8) !?[]const u8 {
+ const raw = if (std.mem.startsWith(u8, url, "https://")) url[8..] else if (std.mem.startsWith(u8, url, "http://")) url[7..] else return null;
+ const trimmed = std.mem.trimEnd(u8, raw, "/");
+ if (!valid(trimmed)) return null;
+ return try std.ascii.allocLowerString(a, trimmed);
+}
+
+pub fn resolve(a: A, io: std.Io, cwd: []const u8, repo: ?[]const u8) ?[]const u8 {
+ if (repo) |r| if (r.len == 0 or r.len > 2048) return null;
+ const target = evidence.Target{ .cwd = cwd, .selector = "" };
+ const argv: []const []const u8 = if (repo) |r| &.{ "gh", "repo", "view", "--json", "url", "--", r } else &.{ "gh", "repo", "view", "--json", "url" };
+ const json = evidence.capture(std.heap.page_allocator, io, a, target, argv) catch return null;
+ const value = std.json.parseFromSliceLeaky(std.json.Value, a, json, .{}) catch return null;
+ if (value != .object) return null;
+ const url = value.object.get("url") orelse return null;
+ if (url != .string) return null;
+ return fromUrl(a, url.string) catch null;
+}
+
+pub const PullRequest = struct { repo: []const u8, number: []const u8, branch: []const u8, head_repo: ?[]const u8 };
+
+pub fn pullRequest(a: A, io: std.Io, target: evidence.Target) ?PullRequest {
+ const fields = "number,url,headRefName,headRepository";
+ const argv: []const []const u8 = if (target.selector.len > 0) &.{ "gh", "pr", "view", target.selector, "--json", fields } else &.{ "gh", "pr", "view", "--json", fields };
+ const json = evidence.capture(std.heap.page_allocator, io, a, target, argv) catch return null;
+ const value = std.json.parseFromSliceLeaky(std.json.Value, a, json, .{}) catch return null;
+ if (value != .object) return null;
+ const name = value.object.get("headRefName") orelse return null;
+ const number = value.object.get("number") orelse return null;
+ const url = value.object.get("url") orelse return null;
+ if (name != .string or name.string.len == 0 or number != .integer or number.integer <= 0 or url != .string) return null;
+ const id = std.fmt.allocPrint(a, "{d}", .{number.integer}) catch return null;
+ const split = std.mem.lastIndexOf(u8, url.string, "/pull/") orelse return null;
+ if (!std.mem.eql(u8, url.string[split + 6 ..], id)) return null;
+ const repo = (fromUrl(a, url.string[0..split]) catch null) orelse return null;
+ var head_repo: ?[]const u8 = null;
+ if (value.object.get("headRepository")) |head| if (head == .object) {
+ if (head.object.get("nameWithOwner")) |full| if (full == .string) {
+ const host_end = std.mem.indexOfScalar(u8, repo, '/').?;
+ const identity = std.fmt.allocPrint(a, "{s}/{s}", .{ repo[0..host_end], full.string }) catch return null;
+ if (valid(identity)) head_repo = std.ascii.allocLowerString(a, identity) catch return null;
+ };
+ };
+ return .{ .repo = repo, .number = id, .branch = name.string, .head_repo = head_repo };
+}
+
+test "repository identity includes host and normalizes only observed URLs" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ try std.testing.expectEqualStrings("github.com/owner/repo", (try fromUrl(a, "https://GitHub.com/Owner/Repo/")).?);
+ try std.testing.expectEqualStrings("git.example:8443/owner/repo", (try fromUrl(a, "https://git.example:8443/owner/repo")).?);
+ for ([_][]const u8{ "owner/repo", "https://github.com/owner", "https://github.com/owner/repo/pull/1", "https://[email protected]/owner/repo", "https://github.com/owner/repo?x=1" }) |url|
+ try std.testing.expect(try fromUrl(a, url) == null);
+}
diff --git a/src/main.zig b/src/main.zig
index 0a6af542..d874e555 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -52,7 +52,7 @@ test {
_ = .{ @import("clipboard_native.zig"), @import("clipboard_edge_tests.zig"), @import("clipboard_failure_tests.zig"), @import("process_runner_clipboard_tests.zig") };
_ = @import("server_orphan.zig");
_ = @import("repo_transaction.zig");
- _ = .{ @import("pr_command.zig"), @import("pr_evidence.zig"), @import("pr_verify.zig"), @import("pr_acceptance.zig") };
+ _ = .{ @import("pr_command.zig"), @import("pr_evidence.zig"), @import("pr_verify.zig"), @import("pr_acceptance.zig"), @import("artifact_repository.zig"), @import("artifact_claim_ledger.zig"), @import("artifact_claim_store.zig") };
_ = @import("argstream_citation_tests.zig"); // unit_tests' root is main.zig only, so reference every split-out module or its tests silently never run
_ = @import("codex_node_repl.zig");
_ = pricing;
diff --git a/src/peer_channel.zig b/src/peer_channel.zig
index d6b0ce0c..bcbfc2cc 100644
--- a/src/peer_channel.zig
+++ b/src/peer_channel.zig
@@ -36,7 +36,7 @@ const Owner = worktree_lease.Owner;
pub const tool_name = "peer_message";
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", "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"}}}
+ \\{"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"}, "repo": {"type": "string", "description": "GitHub repository for claim/release/handoff/status, as owner/name or host/owner/name; defaults to the workspace CLI repository. Use the same repository for release or handoff."}}}
;
/// Whether the named session sits in MY worktree (routes the post: worktree
@@ -66,13 +66,16 @@ pub fn handleMessage(self: *Agent, call: ToolCall) !ExecResult {
};
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(
+ if (obj.get("repo")) |repo| if (repo != .string) return .{ .text = "claim repo must be a repository name", .is_error = true };
+ return @import("artifact_claim.zig").handleToolIn(
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 "",
+ self.agent_cwd orelse ".",
+ tools_mod.json_args.str(obj, "repo"),
);
}
if (std.mem.eql(u8, action, "list")) {
diff --git a/src/pr_command.zig b/src/pr_command.zig
index d054cf59..b220205f 100644
--- a/src/pr_command.zig
+++ b/src/pr_command.zig
@@ -39,10 +39,38 @@ pub const Command = struct {
return false;
}
pub fn selector(self: Command) ?[]const u8 {
- for (self.argv, 0..) |arg, i| {
- if (std.mem.eql(u8, arg, self.verb) and i + 1 < self.argv.len and !std.mem.startsWith(u8, self.argv[i + 1], "-")) return self.argv[i + 1];
+ return self.selectorChecked() catch null;
+ }
+ pub fn selectorChecked(self: Command) !?[]const u8 {
+ var i: usize = 1;
+ while (i < self.argv.len and !std.mem.eql(u8, self.argv[i], "pr")) : (i += 1) {
+ if (takesValue(self.argv[i])) i += 1;
}
- return null;
+ i += 2; // family and verb
+ var selected: ?[]const u8 = null;
+ while (i < self.argv.len) : (i += 1) {
+ const arg = self.argv[i];
+ if (takesValue(arg)) {
+ i += 1;
+ if (i >= self.argv.len) return error.MissingOptionValue;
+ continue;
+ }
+ if (std.mem.startsWith(u8, arg, "-")) {
+ 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" }) |option| if (std.mem.eql(u8, arg, option)) {
+ known = true;
+ break;
+ };
+ if (!known) return error.UnsupportedOption;
+ continue;
+ }
+ if (selected != null) return error.AmbiguousSelector;
+ selected = arg;
+ }
+ return selected;
}
};
@@ -119,3 +147,15 @@ test "PR arguments keep body flags opaque and resolve repository and target" {
try std.testing.expectError(error.CompoundCommand, parse(arena.allocator(), "gh pr create --body x\necho other"));
try std.testing.expectError(error.CompoundCommand, parse(arena.allocator(), "gh pr create --body x&echo other"));
}
+
+test "PR selectors skip known option values and refuse ambiguous options" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const flags_first = try parse(a, "gh --repo org/repo pr edit --title title 12");
+ try std.testing.expectEqualStrings("12", (try flags_first.selectorChecked()).?);
+ const body_only = try parse(a, "gh pr edit --body '12'");
+ try std.testing.expect(try body_only.selectorChecked() == null);
+ const unknown = try parse(a, "gh pr edit --unknown 12");
+ try std.testing.expectError(error.UnsupportedOption, unknown.selectorChecked());
+}
diff --git a/src/publish_gate.zig b/src/publish_gate.zig
index c0d4891b..9d343c41 100644
--- a/src/publish_gate.zig
+++ b/src/publish_gate.zig
@@ -57,7 +57,7 @@ fn observe(self: *Agent, cmd: []const u8) !?ExecResult {
pub fn bash(self: *Agent, cmd: []const u8) !?ExecResult {
const key = if (builtin.is_test) "" else mutationKey(self, cmd);
- if (artifact_claim.gateCommand(self.arena, self.io, cmd, key)) |blocked| return .{ .text = blocked, .is_error = true };
+ if (artifact_claim.gateCommandIn(self.arena, self.io, cmd, key, self.agent_cwd orelse ".")) |blocked| return .{ .text = blocked, .is_error = true };
if (!pr_publish.isPrCreate(cmd) and !pr_publish.isPrReady(cmd)) return null;
if (!builtin.is_test) return observe(self, cmd);
if (pr_publish.gateCommand(self.arena, cmd)) |blocked| return .{ .text = blocked, .is_error = true };