@jesdi/skills 0.0.63 → 0.0.65
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -0
- package/package.json +2 -2
- package/skills/babysit-pr/SKILL.md +54 -0
- package/skills/babysit-pr/babysit.py +998 -0
- package/skills/babysit-pr/fixtures/gh +310 -0
- package/skills/babysit-pr/hooks/post-pr-create.sh +56 -0
- package/skills/babysit-pr/hooks.json +10 -0
- package/skills/babysit-pr/judge-prompt.md +9 -0
- package/skills/babysit-pr/test_babysit.py +242 -0
- package/skills/babysit-pr/test_babysit_judge.py +286 -0
- package/skills/babysit-pr/test_babysit_judge_diff.py +25 -0
- package/skills/babysit-pr/test_babysit_judge_isolation.py +61 -0
- package/skills/babysit-pr/test_checks_regressions.py +210 -0
- package/skills/babysit-pr/test_comment_fidelity.py +88 -0
- package/skills/babysit-pr/test_comment_identity.py +70 -0
- package/skills/babysit-pr/test_e2e_setup.py +74 -0
- package/skills/babysit-pr/test_handoff_takeover.py +141 -0
- package/skills/babysit-pr/test_handoff_terminal.py +29 -0
- package/skills/babysit-pr/test_hook_quoting.py +25 -0
- package/skills/babysit-pr/test_hooks.py +62 -0
- package/skills/babysit-pr/test_lease_regressions.py +198 -0
- package/skills/babysit-pr/test_merge_and_handoff.py +260 -0
- package/skills/babysit-pr/test_merge_base_pin.py +10 -0
- package/skills/babysit-pr/test_merge_gate.py +124 -0
- package/skills/babysit-pr/test_merge_session_safety.py +117 -0
- package/skills/babysit-pr/test_merged_pr_labels.py +144 -0
- package/skills/babysit-pr/test_owner_comment_edits.py +26 -0
- package/skills/babysit-pr/test_owner_comments.py +316 -0
- package/skills/babysit-pr/test_retry_and_stall_hardening.py +143 -0
- package/skills/babysit-pr/test_rounds_and_checks.py +305 -0
- package/skills/babysit-pr/test_terminal_label_regressions.py +117 -0
- package/skills/babysit-pr/test_trusted_merge_risk.py +184 -0
- package/skills/babysit-pr/test_update_plan.py +157 -0
- package/skills/implement-spec/README.md +3 -3
- package/skills/implement-spec/SKILL.md +1 -1
- package/skills/implement-spec/driver.py +27 -4
- package/skills/implement-spec/driver_final.py +49 -10
- package/skills/implement-spec/prompts/overruled.md +3 -1
- package/skills/implement-spec/prompts/pr-writer.md +3 -2
- package/skills/implement-spec/tests/test_decisions.py +36 -2
- package/skills/implement-spec/tests/test_final.py +112 -1
- package/skills/implement-spec/tests/test_tidy.py +2 -2
- package/skills/implement-spec/tests/test_walk.py +2 -2
- package/skills/pr-risk/SKILL.md +33 -0
- package/skills/pr-risk/hooks/pre-pr-create.sh +274 -0
- package/skills/pr-risk/hooks.json +10 -0
- package/skills/pr-risk/merge_policy.py +81 -0
- package/skills/pr-risk/merge_risk.py +314 -0
- package/skills/pr-risk/test_hook_commands.py +47 -0
- package/skills/pr-risk/test_hook_heredoc.py +16 -0
- package/skills/pr-risk/test_hook_substitution.py +40 -0
- package/skills/pr-risk/test_hooks.py +175 -0
- package/skills/pr-risk/test_merge_risk.py +97 -0
- package/skills/pr-risk/test_merge_risk_gate.py +217 -0
- package/skills/pr-risk/test_merge_risk_regressions.py +37 -0
- package/skills/pr-risk/test_merge_risk_structure.py +101 -0
- package/skills-manifest.json +15 -3
|
@@ -0,0 +1,998 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""babysit-pr: `babysit.py lease acquire|renew|check|release --repo R --pr N --session S --host H`.
|
|
3
|
+
|
|
4
|
+
The lease is a PR comment `<!-- babysit-pr lease: <session> <host> <expires-at> -->` written by the
|
|
5
|
+
gh user. Expiry is judged against GitHub's clock (the `Date` header of `gh api -i`), never the host
|
|
6
|
+
clock. Among valid lease comments the lowest comment id holds the lease; the label is not the lock.
|
|
7
|
+
"""
|
|
8
|
+
import argparse
|
|
9
|
+
import fcntl
|
|
10
|
+
import hashlib
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import shlex
|
|
15
|
+
import shutil
|
|
16
|
+
import subprocess
|
|
17
|
+
import tempfile
|
|
18
|
+
import time
|
|
19
|
+
import sys
|
|
20
|
+
from contextlib import contextmanager
|
|
21
|
+
from datetime import datetime, timedelta, timezone
|
|
22
|
+
from email.utils import parsedate_to_datetime
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
LEASE = re.compile(r"\A<!-- babysit-pr lease: (\S+) (\S+) (\S+) -->")
|
|
26
|
+
TTL = timedelta(minutes=90)
|
|
27
|
+
INSTALL = "npx @jesdi/skills-cli install pr-risk"
|
|
28
|
+
PR_RISK_DIRS = (".my-skills/pr-risk", ".agents/skills/pr-risk", ".claude/skills/pr-risk")
|
|
29
|
+
CLAIM_PENDING = "<!-- babysit-pr claim: pending -->\n"
|
|
30
|
+
CLAIM_HELD = "<!-- babysit-pr claim: held -->\n"
|
|
31
|
+
MAX_ROUNDS = 5
|
|
32
|
+
HANDOFF = re.compile(r"\A## 🧑 Needs human: (.*)")
|
|
33
|
+
NEW_BUDGET = ("5 fix rounds", "same failure twice")
|
|
34
|
+
SEEN = "<!-- babysit-pr seen -->\n"
|
|
35
|
+
PASS = {"success"} # requirement 19: every check passed; skipped or neutral is not a pass
|
|
36
|
+
MENTION = "@babysitter"
|
|
37
|
+
MERGE = re.compile(rf"\A{MENTION} merge(?:\s+(\S+))?\s*\Z")
|
|
38
|
+
CONNECTIONS = {
|
|
39
|
+
"comments": "databaseId author { login } editor { login } lastEditedAt createdAt body",
|
|
40
|
+
"reviews": "author { login } state body submittedAt",
|
|
41
|
+
"reviewThreads": "isResolved comments(first: 100) { nodes { author { login } createdAt } pageInfo { hasNextPage } }",
|
|
42
|
+
"commits": "commit { oid }",
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def fail(msg):
|
|
47
|
+
print(msg, file=sys.stderr)
|
|
48
|
+
sys.exit(1)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def gh(*args, check=True):
|
|
52
|
+
p = subprocess.run(["gh", *args], text=True, capture_output=True)
|
|
53
|
+
if check and p.returncode:
|
|
54
|
+
fail(f"gh {' '.join(args)} failed: {p.stderr.strip()}")
|
|
55
|
+
return p.stdout
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def iso(dt):
|
|
59
|
+
return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def parse(s):
|
|
63
|
+
try:
|
|
64
|
+
return datetime.fromisoformat(s.replace("Z", "+00:00"))
|
|
65
|
+
except ValueError:
|
|
66
|
+
return parsedate_to_datetime(s)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class Pr:
|
|
70
|
+
def __init__(self, repo, number):
|
|
71
|
+
self.identity_scope = (repo, number)
|
|
72
|
+
self.repo = f"repos/{repo}"
|
|
73
|
+
self.base = f"{self.repo}/issues/{number}"
|
|
74
|
+
|
|
75
|
+
def now(self):
|
|
76
|
+
out = gh("api", "-i", "user")
|
|
77
|
+
return parse(re.search(r"^Date: (.+)$", out, re.M).group(1).strip())
|
|
78
|
+
|
|
79
|
+
def user(self):
|
|
80
|
+
return gh("api", "user", "--jq", ".login").strip()
|
|
81
|
+
|
|
82
|
+
def comments(self):
|
|
83
|
+
out = gh("api", "--paginate", f"{self.base}/comments", "--jq", ".[] | tojson")
|
|
84
|
+
return [json.loads(l) for l in out.splitlines() if l]
|
|
85
|
+
|
|
86
|
+
def write_comment(self, cid, body):
|
|
87
|
+
return json.loads(gh("api", "-X", "PATCH", f"{self.repo}/issues/comments/{cid}", "-f", f"body={body}"))
|
|
88
|
+
|
|
89
|
+
def post(self, body):
|
|
90
|
+
c = json.loads(gh("api", "-X", "POST", f"{self.base}/comments", "-f", f"body={body}"))
|
|
91
|
+
CommentIdentities(*self.identity_scope, c["user"]["login"]).remember(c["id"], body)
|
|
92
|
+
return c
|
|
93
|
+
|
|
94
|
+
def label(self, add=(), remove=()):
|
|
95
|
+
for name in add:
|
|
96
|
+
gh("api", "-X", "POST", f"{self.base}/labels", "-f", f"labels[]={name}")
|
|
97
|
+
for name in remove:
|
|
98
|
+
self.remove_label(name)
|
|
99
|
+
|
|
100
|
+
def remove_label(self, name):
|
|
101
|
+
# DELETE may return 404 for an absent label or fail transiently. Read
|
|
102
|
+
# back the labels before accepting either response as a completed write.
|
|
103
|
+
for _ in range(2):
|
|
104
|
+
gh("api", "-X", "DELETE", f"{self.base}/labels/{name}", check=False)
|
|
105
|
+
labels = json.loads(gh("api", f"{self.base}/labels"))
|
|
106
|
+
if not any(label["name"] == name for label in labels):
|
|
107
|
+
return
|
|
108
|
+
fail(f"could not remove label {name}: label reconciliation incomplete")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class CommentIdentities:
|
|
112
|
+
"""Local creation receipts: mutable GitHub bodies cannot change a known identity.
|
|
113
|
+
|
|
114
|
+
Scope by repository, PR and authenticated login. Separate immutable files per
|
|
115
|
+
comment survive process restarts and concurrent sessions without lost updates.
|
|
116
|
+
Missing receipts never establish trust from an edited body.
|
|
117
|
+
"""
|
|
118
|
+
def __init__(self, repo, number, owner):
|
|
119
|
+
scope = hashlib.sha256(json.dumps([repo, str(number), owner]).encode()).hexdigest()
|
|
120
|
+
self.root = Path.home() / ".local/state/babysit-pr/comments" / scope
|
|
121
|
+
|
|
122
|
+
def kind(self, cid):
|
|
123
|
+
path = self.root / str(cid)
|
|
124
|
+
return path.read_text() if path.exists() else None
|
|
125
|
+
|
|
126
|
+
def remember(self, cid, body):
|
|
127
|
+
kind = "lease" if LEASE.match(body) else "handoff" if HANDOFF.match(body) else None
|
|
128
|
+
if kind:
|
|
129
|
+
self.root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
130
|
+
try:
|
|
131
|
+
with (self.root / str(cid)).open("x") as f:
|
|
132
|
+
f.write(kind)
|
|
133
|
+
except FileExistsError:
|
|
134
|
+
pass # the original identity wins, even if the body has changed
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def marker(session, host, expires):
|
|
138
|
+
return f"<!-- babysit-pr lease: {session} {host} {iso(expires)} -->"
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def leases(comments, user, include_ended=False):
|
|
142
|
+
"""Lease comments by `user`: (id, session, host, expires, comment)."""
|
|
143
|
+
out = []
|
|
144
|
+
for c in comments:
|
|
145
|
+
m = LEASE.match(c["body"])
|
|
146
|
+
if m and c["user"]["login"] == user and (include_ended or not is_ended(c)):
|
|
147
|
+
out.append((c["id"], m[1], m[2], parse(m[3]), c))
|
|
148
|
+
return sorted(out, key=lambda l: l[0])
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def holder(found, now):
|
|
152
|
+
return next((l for l in found if l[3] > now), None)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def is_ended(comment):
|
|
156
|
+
lines = comment["body"].split("\n")
|
|
157
|
+
return len(lines) > 1 and lines[1] == "ended"
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def rest_of(comment):
|
|
161
|
+
rest = comment["body"].partition("\n")[2]
|
|
162
|
+
while rest.startswith("ended\n") or rest == "ended":
|
|
163
|
+
rest = rest.partition("\n")[2]
|
|
164
|
+
return rest
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def end(pr, comment):
|
|
168
|
+
pr.write_comment(comment["id"], comment["body"].split("\n", 1)[0] + "\nended\n" + rest_of(comment))
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def inherited_state(comments, user):
|
|
172
|
+
# Unmarked comments are leases from before claim confirmation was introduced.
|
|
173
|
+
# Pending claims (including ended losers and crashed attempts) never own history.
|
|
174
|
+
history = [l for l in leases(comments, user, include_ended=True)
|
|
175
|
+
if CLAIM_PENDING not in l[4]["body"]]
|
|
176
|
+
if not history or budget_spent(comments, user, history[-1][0]):
|
|
177
|
+
return "rounds: 0\n"
|
|
178
|
+
return rest_of(history[-1][4]).replace(CLAIM_HELD, "")
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def budget_spent(comments, user, after_id):
|
|
182
|
+
"""The owner's latest handoff newer than the last lease ended the budget (rounds or repeat)."""
|
|
183
|
+
handoffs = [(c["id"], m[1].strip()) for c in comments if c["user"]["login"] == user
|
|
184
|
+
and (m := HANDOFF.match(c["body"]))]
|
|
185
|
+
return bool(handoffs) and max(handoffs)[0] > after_id and max(handoffs)[1] in NEW_BUDGET
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def signature(check, error):
|
|
189
|
+
error = re.sub(r"/tmp/\S+", "<tmp>", error)
|
|
190
|
+
error = re.sub(r"\b0x[0-9a-f]+\b|\b[0-9a-f]{7,}\b|\d+", "<n>", error, flags=re.I)
|
|
191
|
+
return f"{check}: {' '.join(error.split())}"
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def round_state(comment):
|
|
195
|
+
"""(rounds, [(round, signature)], halt reason) kept after the marker line of a lease comment."""
|
|
196
|
+
rest = rest_of(comment)
|
|
197
|
+
rounds = int(re.search(r"^rounds: (\d+)", rest, re.M)[1])
|
|
198
|
+
sigs = [(int(m[1] or 0), m[2]) for m in re.finditer(r"^signature: (?:r(\d+) )?(.*)$", rest, re.M)]
|
|
199
|
+
halt = re.search(r"^halt: (.*)$", rest, re.M)
|
|
200
|
+
return rounds, sigs, halt[1] if halt else None
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def save_round_state(pr, comment, rounds, sigs, halt, ops=()):
|
|
204
|
+
body = comment["body"].split("\n", 1)[0] + "\n" + ("ended\n" if is_ended(comment) else "")
|
|
205
|
+
held = CLAIM_HELD if CLAIM_HELD in comment["body"] else ""
|
|
206
|
+
lines = [f"rounds: {rounds}"] + [f"op: {n} {o}" for n, o in ops] + [f"signature: r{n} {s}" for n, s in sigs]
|
|
207
|
+
return pr.write_comment(comment["id"], body + held + "\n".join(lines + ([f"halt: {halt}"] if halt else [])) + "\n")
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def round_ops(comment):
|
|
211
|
+
"""[(round, op)]: every start operation of this budget, so a late retry of an old one is recognised."""
|
|
212
|
+
return [(int(m[1]), m[2]) for m in re.finditer(r"^op: (\d+) (.+)$", rest_of(comment), re.M)]
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def own_lease(repo, number, session):
|
|
216
|
+
require_pr_risk(repo, number)
|
|
217
|
+
pr = Pr(repo, number)
|
|
218
|
+
top = holder(leases(pr.comments(), pr.user()), pr.now())
|
|
219
|
+
if top is None or top[1] != session:
|
|
220
|
+
fail(f"{session} does not hold the lease")
|
|
221
|
+
return pr, top[4]
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
@contextmanager
|
|
225
|
+
def locked():
|
|
226
|
+
"""Serialize read-modify-write of babysit state on this host."""
|
|
227
|
+
with open(Path.home() / ".babysit-pr.lock", "a") as f:
|
|
228
|
+
fcntl.flock(f, fcntl.LOCK_EX)
|
|
229
|
+
yield
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def round_cmd(*args, **kw):
|
|
233
|
+
with locked():
|
|
234
|
+
round_locked(*args, **kw)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def round_locked(verb, repo, number, session, check, error, op=None):
|
|
238
|
+
if not op:
|
|
239
|
+
fail(f"round {verb} needs --op (reuse the same ID on retries)")
|
|
240
|
+
pr, c = own_lease(repo, number, session)
|
|
241
|
+
user = pr.user()
|
|
242
|
+
rounds, sigs, halt = round_state(c)
|
|
243
|
+
if verb == "start":
|
|
244
|
+
op = f"{session} {op}" # ops are scoped to their session
|
|
245
|
+
done = dict((o, n) for n, o in round_ops(c))
|
|
246
|
+
if op in done: # retry of a start whose answer was lost: finish its renewal, spend nothing
|
|
247
|
+
extend(pr, c, session, LEASE.match(c["body"])[2], pr.now() + TTL, user)
|
|
248
|
+
print(f"round {done[op]}")
|
|
249
|
+
return
|
|
250
|
+
if halt:
|
|
251
|
+
fail(halt)
|
|
252
|
+
if rounds >= MAX_ROUNDS:
|
|
253
|
+
fail("5 fix rounds")
|
|
254
|
+
c = save_round_state(pr, c, rounds + 1, sigs, halt, round_ops(c) + [(rounds + 1, op)])
|
|
255
|
+
extend(pr, c, session, LEASE.match(c["body"])[2], pr.now() + TTL, user)
|
|
256
|
+
print(f"round {rounds + 1}")
|
|
257
|
+
return
|
|
258
|
+
sig = signature(check, error)
|
|
259
|
+
failure_round = dict((o, n) for n, o in round_ops(c)).get(f"{session} {op}")
|
|
260
|
+
if failure_round is None:
|
|
261
|
+
fail("record-failure --op must name its originating round start")
|
|
262
|
+
if (failure_round, sig) in sigs:
|
|
263
|
+
return # response lost, including a retry after a later round started
|
|
264
|
+
if any(s == sig and n != failure_round for n, s in sigs):
|
|
265
|
+
save_round_state(pr, c, rounds, sigs, "same failure twice", round_ops(c))
|
|
266
|
+
own_lease(repo, number, session)
|
|
267
|
+
fail("same failure twice")
|
|
268
|
+
sigs.append((failure_round, sig))
|
|
269
|
+
save_round_state(pr, c, rounds, sigs, halt, round_ops(c))
|
|
270
|
+
# A PATCH can cross expiry on another host. Never acknowledge that write
|
|
271
|
+
# from the pre-PATCH lease snapshot: the new holder may already own history.
|
|
272
|
+
own_lease(repo, number, session)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def seen_comment(pr):
|
|
276
|
+
"""The owner's shared comment of first sightings, so the stall bound survives host changes."""
|
|
277
|
+
user = pr.user()
|
|
278
|
+
return next((c for c in pr.comments() if c["user"]["login"] == user and c["body"].startswith(SEEN)), None)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def load_seen(pr):
|
|
282
|
+
c = seen_comment(pr)
|
|
283
|
+
try:
|
|
284
|
+
return json.loads(c["body"][len(SEEN):]) if c else {}
|
|
285
|
+
except ValueError: # damaged: start over
|
|
286
|
+
return {}
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def first_seen(pr, key, now, since=None):
|
|
290
|
+
"""Earliest pending time of a check: when we first saw it (GitHub time), or its created_at if earlier."""
|
|
291
|
+
with locked():
|
|
292
|
+
seen = load_seen(pr)
|
|
293
|
+
earliest = iso(min(now, since) if since else now)
|
|
294
|
+
if key not in seen or earliest < seen[key]: # an earlier created_at learned later still counts
|
|
295
|
+
prefix = key.rsplit("#", 1)[0] + "#" # only the current head commit's entries matter
|
|
296
|
+
seen = {k: v for k, v in seen.items() if k.startswith(prefix)}
|
|
297
|
+
seen[key] = earliest if key not in seen else min(earliest, seen[key])
|
|
298
|
+
body = SEEN + json.dumps(seen)
|
|
299
|
+
c = seen_comment(pr)
|
|
300
|
+
pr.write_comment(c["id"], body) if c else pr.post(body)
|
|
301
|
+
return parse(seen[key])
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def checks_cmd(repo, number, wait):
|
|
305
|
+
print(ci_state(repo, number, wait))
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def ci_state(repo, number, wait):
|
|
309
|
+
pr = Pr(repo, number)
|
|
310
|
+
sha = json.loads(gh("api", f"{pr.repo}/pulls/{number}"))["head"]["sha"]
|
|
311
|
+
out = gh("api", "--paginate", f"{pr.repo}/commits/{sha}/check-runs", "--jq", ".check_runs[] | tojson")
|
|
312
|
+
runs = [json.loads(l) for l in out.splitlines() if l]
|
|
313
|
+
now = pr.now()
|
|
314
|
+
red = any(r["status"] == "completed" and r["conclusion"] not in PASS for r in runs)
|
|
315
|
+
# Commit statuses are separate from check runs. Newest first, so the first per context is current.
|
|
316
|
+
latest = {}
|
|
317
|
+
out = gh("api", "--paginate", f"{pr.repo}/commits/{sha}/statuses", "--jq", ".[] | tojson")
|
|
318
|
+
for line in out.splitlines():
|
|
319
|
+
if line:
|
|
320
|
+
status = json.loads(line)
|
|
321
|
+
latest.setdefault(status["context"], status)
|
|
322
|
+
reset_terminal_statuses(pr, f"{repo}#{sha}#status:", latest)
|
|
323
|
+
red = red or any(s["state"] in ("failure", "error") for s in latest.values())
|
|
324
|
+
pending_runs = [r for r in runs if r["status"] != "completed"]
|
|
325
|
+
pending_statuses = [s for s in latest.values() if s["state"] == "pending"]
|
|
326
|
+
if not runs and not latest:
|
|
327
|
+
return "no checks"
|
|
328
|
+
elif red:
|
|
329
|
+
return "red"
|
|
330
|
+
elif pending_runs or pending_statuses:
|
|
331
|
+
# Observe every pending item, even when an earlier one is already stalled.
|
|
332
|
+
times = [pending_since(pr, f"{repo}#{sha}#run:{r.get('id', r['name'])}",
|
|
333
|
+
min(filter(None, (r.get("started_at"), r.get("created_at"))), default=None), now) for r in pending_runs]
|
|
334
|
+
times += [pending_since(pr, f"{repo}#{sha}#status:{s['context']}",
|
|
335
|
+
s.get("created_at"), now) for s in pending_statuses]
|
|
336
|
+
return "CI stalled" if now - min(times) >= timedelta(minutes=wait) else "pending"
|
|
337
|
+
else:
|
|
338
|
+
return "green"
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def reset_terminal_statuses(pr, prefix, statuses):
|
|
342
|
+
"""Only a terminal observation ends a context's continuous pending interval."""
|
|
343
|
+
terminal = {prefix + name for name, s in statuses.items() if s["state"] != "pending"}
|
|
344
|
+
with locked():
|
|
345
|
+
seen = load_seen(pr)
|
|
346
|
+
if terminal.intersection(seen):
|
|
347
|
+
c = seen_comment(pr)
|
|
348
|
+
pr.write_comment(c["id"], SEEN + json.dumps({k: v for k, v in seen.items() if k not in terminal}))
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def pending_since(pr, key, timestamp, now):
|
|
352
|
+
"""Keep queued time through a running transition, without sharing it across runs."""
|
|
353
|
+
return first_seen(pr, key, now, parse(timestamp) if timestamp else None)
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def confirm(pr, comment):
|
|
357
|
+
if CLAIM_PENDING in comment["body"]:
|
|
358
|
+
pr.write_comment(comment["id"], comment["body"].replace(CLAIM_PENDING, CLAIM_HELD))
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def extend(pr, c, session, host, expires, user):
|
|
362
|
+
"""Renew, then verify election and whether a takeover crossed our old expiry.
|
|
363
|
+
|
|
364
|
+
A contender posted after our previous expiry may already be cleaning up our
|
|
365
|
+
comment. Yield even if this PATCH temporarily resurrected the lower id.
|
|
366
|
+
A contender posted while we were valid remains subject to lowest-id election.
|
|
367
|
+
"""
|
|
368
|
+
previous_expiry = parse(LEASE.match(c["body"])[3])
|
|
369
|
+
c = pr.write_comment(c["id"], marker(session, host, expires) + "\n" + rest_of(c))
|
|
370
|
+
found = leases(pr.comments(), user)
|
|
371
|
+
now = pr.now()
|
|
372
|
+
takeover = next((l for l in found if l[0] != c["id"] and l[3] > now
|
|
373
|
+
and parse(l[4]["created_at"]) >= previous_expiry), None)
|
|
374
|
+
winner = takeover or holder(found, now)
|
|
375
|
+
if winner is None or winner[0] != c["id"]:
|
|
376
|
+
end(pr, c)
|
|
377
|
+
fail(f"lost the lease to {winner[1] if winner else 'another session'}")
|
|
378
|
+
confirm(pr, c)
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def require_pr_risk(repo, number):
|
|
382
|
+
if trusted_pr_risk_dirs():
|
|
383
|
+
return
|
|
384
|
+
if subprocess.run(["git", "rev-parse", "--git-dir"], capture_output=True).returncode == 0:
|
|
385
|
+
base = gh("api", f"repos/{repo}/pulls/{number}", "--jq", ".base.ref", check=False).strip()
|
|
386
|
+
if base and base_install(base):
|
|
387
|
+
return
|
|
388
|
+
fail(f"pr-risk is not installed. Run: {INSTALL}")
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def renew(repo, number, session):
|
|
392
|
+
pr, c = own_lease(repo, number, session)
|
|
393
|
+
extend(pr, c, session, LEASE.match(c["body"])[2], pr.now() + TTL, pr.user())
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def lease(verb, repo, number, session, host):
|
|
397
|
+
# Every lease-body writer reads its snapshot inside the same lock as rounds.
|
|
398
|
+
with locked():
|
|
399
|
+
return lease_locked(verb, repo, number, session, host)
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def confirmed_leases(comments, user):
|
|
403
|
+
"""Include completed holders, but never treat a pending claim as ownership."""
|
|
404
|
+
return [l for l in leases(comments, user, include_ended=True)
|
|
405
|
+
if CLAIM_PENDING not in l[4]["body"]]
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def repair_if_taken_over(pr, session, after_id=None):
|
|
409
|
+
"""Labels have no compare-and-swap: after a terminal write, re-read the lease and give a new holder its labels back.
|
|
410
|
+
|
|
411
|
+
The repair write can itself race the new holder finishing its own handoff, so
|
|
412
|
+
re-read after each write and follow the durable state until it stops moving.
|
|
413
|
+
"""
|
|
414
|
+
comments, user = pr.comments(), pr.user()
|
|
415
|
+
history = confirmed_leases(comments, user)
|
|
416
|
+
if after_id is None:
|
|
417
|
+
after_id = max((l[0] for l in history if l[1] == session), default=0)
|
|
418
|
+
# A successor can merge and release before our first read. Its confirmed
|
|
419
|
+
# lease remains evidence of takeover after it stops being the active holder.
|
|
420
|
+
successor = next((l for l in reversed(history) if l[0] > after_id), None)
|
|
421
|
+
top = holder(leases(comments, user), pr.now()) or successor
|
|
422
|
+
if not top or top[1] == session:
|
|
423
|
+
# No takeover, but the owner may have merged while our terminal write was in flight.
|
|
424
|
+
if json.loads(gh("api", f"{pr.repo}/pulls/{pr.identity_scope[1]}")).get("merged"):
|
|
425
|
+
pr.label(remove=["babysitting", "needs-human"])
|
|
426
|
+
return
|
|
427
|
+
taker = top[1]
|
|
428
|
+
applied = None
|
|
429
|
+
while True:
|
|
430
|
+
comments, user = pr.comments(), pr.user()
|
|
431
|
+
active = holder(leases(comments, user), pr.now())
|
|
432
|
+
# Compare the handoff to the actual holder, even before it releases.
|
|
433
|
+
# Ended pending claims never held the PR and cannot supersede a handoff.
|
|
434
|
+
history = confirmed_leases(comments, user)
|
|
435
|
+
lease_id = active[0] if active else max((l[0] for l in history), default=0)
|
|
436
|
+
handoff_id = max((c["id"] for c in comments if c["user"]["login"] == user
|
|
437
|
+
and HANDOFF.match(c["body"])), default=0)
|
|
438
|
+
merge_id = max((c["id"] for c in comments if c["user"]["login"] == user
|
|
439
|
+
and c["body"].startswith("🤖 Merged by babysit-pr:")), default=0)
|
|
440
|
+
merged = json.loads(gh("api", f"{pr.repo}/pulls/{pr.identity_scope[1]}")).get("merged")
|
|
441
|
+
if merged or merge_id > max(lease_id, handoff_id):
|
|
442
|
+
want = ([], ["babysitting", "needs-human"])
|
|
443
|
+
elif handoff_id > lease_id:
|
|
444
|
+
want = (["needs-human"], ["babysitting"])
|
|
445
|
+
elif active:
|
|
446
|
+
want = (["babysitting"], ["needs-human"])
|
|
447
|
+
else:
|
|
448
|
+
want = ([], ["babysitting"])
|
|
449
|
+
if want == applied:
|
|
450
|
+
break
|
|
451
|
+
pr.label(add=want[0], remove=want[1])
|
|
452
|
+
applied = want
|
|
453
|
+
fail(f"{session} was taken over by {taker}: labels restored to the new holder")
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def release(pr, session):
|
|
457
|
+
"""End `session`'s leases; drop `babysitting` unless another session holds the PR."""
|
|
458
|
+
comments = pr.comments()
|
|
459
|
+
found = leases(comments, pr.user())
|
|
460
|
+
top = holder(found, pr.now())
|
|
461
|
+
# Finish label cleanup while our lease still prevents a resume from winning.
|
|
462
|
+
if not top or top[1] == session:
|
|
463
|
+
pr.label(remove=["babysitting"])
|
|
464
|
+
repair_if_taken_over(pr, session)
|
|
465
|
+
for l in found:
|
|
466
|
+
if l[1] == session:
|
|
467
|
+
end(pr, l[4])
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
def lease_locked(verb, repo, number, session, host):
|
|
471
|
+
require_pr_risk(repo, number)
|
|
472
|
+
pr = Pr(repo, number)
|
|
473
|
+
user = pr.user()
|
|
474
|
+
comments = pr.comments()
|
|
475
|
+
now = pr.now()
|
|
476
|
+
found = leases(comments, user)
|
|
477
|
+
top = holder(found, now)
|
|
478
|
+
mine = top is not None and top[1] == session
|
|
479
|
+
|
|
480
|
+
if verb == "check":
|
|
481
|
+
if not mine:
|
|
482
|
+
fail(f"{session} does not hold the lease" + (f" (babysat by {top[2]})" if top else ""))
|
|
483
|
+
elif verb == "renew":
|
|
484
|
+
return renew(repo, number, session)
|
|
485
|
+
elif verb == "release":
|
|
486
|
+
release(pr, session)
|
|
487
|
+
else: # acquire
|
|
488
|
+
if top and not mine:
|
|
489
|
+
fail(f"already babysat by {top[2]}")
|
|
490
|
+
carried = inherited_state(comments, user)
|
|
491
|
+
if mine:
|
|
492
|
+
c = top[4]
|
|
493
|
+
extend(pr, c, session, host, now + TTL, user)
|
|
494
|
+
else:
|
|
495
|
+
claim = CLAIM_PENDING + carried
|
|
496
|
+
c = pr.post(marker(session, host, now + TTL) + "\n" + claim)
|
|
497
|
+
c = pr.write_comment(c["id"], marker(session, host, parse(c["updated_at"]) + TTL) + "\n" + claim)
|
|
498
|
+
# Re-read: a session that posted within the same second may have the lower id.
|
|
499
|
+
found = leases(pr.comments(), user)
|
|
500
|
+
now = pr.now()
|
|
501
|
+
winner = holder(found, now)
|
|
502
|
+
if winner is None or winner[0] != c["id"]:
|
|
503
|
+
end(pr, c)
|
|
504
|
+
fail(f"already babysat by {winner[2] if winner else 'another session'}")
|
|
505
|
+
# The initial read can predate a final write by the old holder.
|
|
506
|
+
# Inherit after publishing our claim, which fences successful old
|
|
507
|
+
# writers via their post-write lease check, before confirming ours.
|
|
508
|
+
carried = inherited_state(pr.comments(), user)
|
|
509
|
+
c = pr.write_comment(c["id"], c["body"].split("\n", 1)[0] + "\n" + CLAIM_PENDING + carried)
|
|
510
|
+
confirm(pr, c)
|
|
511
|
+
# Publish and elect our claim before touching expired comments. A
|
|
512
|
+
# renewal that completed before our post wins the fresh election;
|
|
513
|
+
# one racing this cleanup sees our claim in its own post-write check.
|
|
514
|
+
for l in leases(pr.comments(), user):
|
|
515
|
+
if l[0] != c["id"] and l[3] <= now:
|
|
516
|
+
end(pr, l[4])
|
|
517
|
+
pr.label(add=["babysitting"], remove=["needs-human"])
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def connection(repo, number, name):
|
|
521
|
+
"""All nodes of one PR connection over GraphQL (REST has no comment `editor`)."""
|
|
522
|
+
owner, _, repo_name = repo.partition("/")
|
|
523
|
+
query = ("query($o: String!, $r: String!, $n: Int!, $after: String) { repository(owner: $o, name: $r) "
|
|
524
|
+
f"{{ pullRequest(number: $n) {{ {name}(first: 100, after: $after) "
|
|
525
|
+
f"{{ nodes {{ {CONNECTIONS[name]} }} pageInfo {{ hasNextPage endCursor }} }} }} }} }}")
|
|
526
|
+
nodes, after = [], []
|
|
527
|
+
while True:
|
|
528
|
+
out = json.loads(gh("api", "graphql", "-f", f"query={query}", "-f", f"o={owner}",
|
|
529
|
+
"-f", f"r={repo_name}", "-F", f"n={number}", *after))
|
|
530
|
+
page = out["data"]["repository"]["pullRequest"][name]
|
|
531
|
+
nodes += page["nodes"]
|
|
532
|
+
if not page.get("pageInfo", {}).get("hasNextPage"):
|
|
533
|
+
return nodes
|
|
534
|
+
after = ["-f", f"after={page['pageInfo']['endCursor']}"]
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def login_of(node):
|
|
538
|
+
return (node.get("author") or {}).get("login") or "ghost"
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def owner_comments(repo, number):
|
|
542
|
+
"""Hand off for any review or non-owner comment; else the owner's `@babysitter` instructions."""
|
|
543
|
+
owner = Pr(repo, number).user()
|
|
544
|
+
identities = CommentIdentities(repo, number, owner)
|
|
545
|
+
comments = sorted(connection(repo, number, "comments"), key=lambda c: c["databaseId"])
|
|
546
|
+
for c in comments:
|
|
547
|
+
if login_of(c) == owner and not c.get("lastEditedAt"):
|
|
548
|
+
identities.remember(c["databaseId"], c["body"])
|
|
549
|
+
kinds = {c["databaseId"]: identities.kind(c["databaseId"]) for c in comments}
|
|
550
|
+
last = max((i for i, c in enumerate(comments)
|
|
551
|
+
if login_of(c) == owner and kinds[c["databaseId"]] != "lease"
|
|
552
|
+
and HANDOFF.match(c["body"]) and not c.get("lastEditedAt")), default=-1) # an edited handoff may be forged
|
|
553
|
+
since = parse(comments[last]["createdAt"]) if last >= 0 else None
|
|
554
|
+
handoff, instructions = None, []
|
|
555
|
+
for c in comments[last + 1:]:
|
|
556
|
+
author = login_of(c)
|
|
557
|
+
editor = (c.get("editor") or {}).get("login")
|
|
558
|
+
kind = kinds[c["databaseId"]]
|
|
559
|
+
if author == owner and kind == "lease":
|
|
560
|
+
continue # creation receipt, independent of the lease's current body
|
|
561
|
+
if author == owner and not c["body"].startswith(MENTION):
|
|
562
|
+
# An unknown edited lease may be a handoff with its heading removed.
|
|
563
|
+
# Without a receipt it is safe to ignore only if no earlier instruction
|
|
564
|
+
# could be replayed. This also supports leases from another host.
|
|
565
|
+
if c.get("lastEditedAt") and (kind == "handoff" or not LEASE.match(c["body"])
|
|
566
|
+
or editor != owner or instructions):
|
|
567
|
+
handoff = handoff or "handoff comment edited, boundary unverifiable"
|
|
568
|
+
continue # the babysitter's own lease comments and the owner's plain chatter
|
|
569
|
+
if author != owner:
|
|
570
|
+
handoff = handoff or f"review comment from {author}"
|
|
571
|
+
elif editor not in (None, owner):
|
|
572
|
+
handoff = handoff or f"owner comment edited by {editor}"
|
|
573
|
+
elif c.get("lastEditedAt"): # the last editor alone cannot rule out an earlier edit by another account
|
|
574
|
+
handoff = handoff or "owner comment edited, edit history unverifiable"
|
|
575
|
+
else:
|
|
576
|
+
instructions.append({"id": c["databaseId"], "text": c["body"], "approved_sha": None})
|
|
577
|
+
m = MERGE.match(c["body"])
|
|
578
|
+
if m:
|
|
579
|
+
oids = [k["commit"]["oid"] for k in connection(repo, number, "commits")]
|
|
580
|
+
hits = {o for o in oids if re.fullmatch(r"[0-9a-f]{7,40}", m[1] or "") and o.startswith(m[1])}
|
|
581
|
+
sha = hits.pop() if len(hits) == 1 else None # an ambiguous prefix approves nothing
|
|
582
|
+
if sha: # the approval names its commit; the head is never inferred from dates
|
|
583
|
+
instructions[-1]["approved_sha"] = sha
|
|
584
|
+
else:
|
|
585
|
+
handoff = handoff or "merge approval must name a commit: @babysitter merge <sha>"
|
|
586
|
+
for r in connection(repo, number, "reviews"):
|
|
587
|
+
author = login_of(r)
|
|
588
|
+
if r["state"] == "CHANGES_REQUESTED":
|
|
589
|
+
handoff = handoff or f"changes requested by {author}"
|
|
590
|
+
elif author != owner and r["body"].strip() and (since is None or parse(r["submittedAt"]) >= since):
|
|
591
|
+
handoff = handoff or f"review comment from {author}"
|
|
592
|
+
for t in connection(repo, number, "reviewThreads"):
|
|
593
|
+
if not t["isResolved"]:
|
|
594
|
+
handoff = handoff or f"review comment from {login_of(t['comments']['nodes'][0])}"
|
|
595
|
+
for c in t["comments"]["nodes"]:
|
|
596
|
+
stamp = c.get("createdAt") # resolving a thread must not hide its comments
|
|
597
|
+
if login_of(c) != owner and (since is None or not stamp or parse(stamp) >= since): # equal stamps: order unknown, hand off
|
|
598
|
+
handoff = handoff or f"review comment from {login_of(c)}"
|
|
599
|
+
if t["comments"].get("pageInfo", {}).get("hasNextPage"): # unread comments: fail closed
|
|
600
|
+
handoff = handoff or "review thread too long to read"
|
|
601
|
+
return {"handoff": handoff, "instructions": [] if handoff else instructions}
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
def checkout_root():
|
|
605
|
+
p = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True)
|
|
606
|
+
return Path(p.stdout.strip() if p.returncode == 0 else ".").resolve()
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
def trusted_pr_risk_dirs():
|
|
610
|
+
"""Installs a PR cannot change: next to this skill, and under $HOME. Never inside the checkout.
|
|
611
|
+
|
|
612
|
+
A path counts only if it, and the module files in it, resolve outside the checkout:
|
|
613
|
+
HOME may be the checkout, and a symlink may point into it. A project install is
|
|
614
|
+
read from origin/<base> instead.
|
|
615
|
+
"""
|
|
616
|
+
root = checkout_root()
|
|
617
|
+
home = Path.home()
|
|
618
|
+
outside = lambda p: not p.resolve().is_relative_to(root)
|
|
619
|
+
return [d.resolve() for d in [Path(__file__).resolve().parent.parent / "pr-risk",
|
|
620
|
+
*(home / n for n in PR_RISK_DIRS)]
|
|
621
|
+
if d.is_dir() and outside(d)
|
|
622
|
+
and all((d / n).is_file() and outside(d / n) for n in ("merge_risk.py", "merge_policy.py"))]
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
def base_install(base):
|
|
626
|
+
"""[(file name, bytes)] of a pr-risk install committed on origin/<base>, else None."""
|
|
627
|
+
names = ("merge_risk.py", "merge_policy.py")
|
|
628
|
+
for d in PR_RISK_DIRS: # a project install counts only as committed on origin/<base>
|
|
629
|
+
shown = [subprocess.run(["git", "show", f"origin/{base}:{d}/{n}"], capture_output=True)
|
|
630
|
+
for n in names]
|
|
631
|
+
if all(p.returncode == 0 for p in shown):
|
|
632
|
+
return [(n, p.stdout) for n, p in zip(names, shown)]
|
|
633
|
+
|
|
634
|
+
|
|
635
|
+
def import_merge_risk(folder):
|
|
636
|
+
sys.modules.pop("merge_risk", None)
|
|
637
|
+
sys.modules.pop("merge_policy", None)
|
|
638
|
+
saved = sys.path[:]
|
|
639
|
+
root = checkout_root() # PYTHONPATH or "" may name the checkout: the trusted import must not see it
|
|
640
|
+
sys.path[:] = [str(folder)] + [p for p in saved if p and not Path(p).resolve().is_relative_to(root)]
|
|
641
|
+
try:
|
|
642
|
+
import merge_risk
|
|
643
|
+
finally:
|
|
644
|
+
sys.path[:] = saved
|
|
645
|
+
return merge_risk
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
def load_merge_risk(base=None):
|
|
649
|
+
for d in trusted_pr_risk_dirs():
|
|
650
|
+
if (d / "merge_risk.py").is_file():
|
|
651
|
+
return import_merge_risk(d)
|
|
652
|
+
files = base_install(base) if base else None
|
|
653
|
+
if files:
|
|
654
|
+
with tempfile.TemporaryDirectory(prefix="babysit-pr-risk-", dir="/tmp") as tmp:
|
|
655
|
+
for n, data in files:
|
|
656
|
+
(Path(tmp) / n).write_bytes(data)
|
|
657
|
+
return import_merge_risk(tmp)
|
|
658
|
+
fail(f"pr-risk is not installed. Run: {INSTALL}")
|
|
659
|
+
|
|
660
|
+
|
|
661
|
+
JUDGE_NEEDS = ("base_policy", "classify_diff", "diff_stats", "FENCE")
|
|
662
|
+
GATE_NEEDS = ("gate", "base_policy", "classify_diff", "diff_stats", "parse")
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
def missing_functions(mr, *names):
|
|
666
|
+
return [n for n in names if not hasattr(mr, n)]
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
def judge_input(mr, body, base, head):
|
|
670
|
+
"""Counted-file diffs, other files by name and count, the block, the categories. Nothing else."""
|
|
671
|
+
base, policy, _ = mr.base_policy(base)
|
|
672
|
+
diff_base, files = mr.classify_diff(base, head, policy)
|
|
673
|
+
diffs, others = [], []
|
|
674
|
+
for path, _, lines, counted in files:
|
|
675
|
+
if counted:
|
|
676
|
+
diffs.append(git("diff", "--no-renames", "--no-textconv", "--no-ext-diff",
|
|
677
|
+
diff_base, head, "--", f":(literal){path}").stdout)
|
|
678
|
+
else:
|
|
679
|
+
others.append(f"{path}: {lines or 0} lines")
|
|
680
|
+
cats = mr.diff_stats(files)[0]
|
|
681
|
+
block = mr.FENCE.search(body)
|
|
682
|
+
return (f"## Diff of counted files\n\n{''.join(diffs)}\n## Other files\n\n"
|
|
683
|
+
+ "\n".join(others) + f"\n\n## Merge-risk block\n\n{block[0] if block else '(none)'}\n"
|
|
684
|
+
f"\n## Categories of the diff\n\n{', '.join(sorted(cats))}\n")
|
|
685
|
+
|
|
686
|
+
|
|
687
|
+
def ask(cli, prompt, timeout):
|
|
688
|
+
"""Run one judge CLI. Returns its answer text; None when it fails; raises TimeoutExpired."""
|
|
689
|
+
if timeout <= 0:
|
|
690
|
+
raise subprocess.TimeoutExpired(cli, 0)
|
|
691
|
+
try:
|
|
692
|
+
# Use /tmp explicitly: TMPDIR may point into the untrusted PR checkout.
|
|
693
|
+
# Read-only alone still permits reading author-controlled instructions.
|
|
694
|
+
with tempfile.TemporaryDirectory(prefix="babysit-judge-", dir="/tmp") as d:
|
|
695
|
+
env = {k: v for k, v in os.environ.items()
|
|
696
|
+
if not k.startswith("GIT_") and k not in
|
|
697
|
+
{"CLAUDECODE", "CLAUDE_PROJECT_DIR", "CODEX_THREAD_ID"}}
|
|
698
|
+
env["PWD"] = d
|
|
699
|
+
if cli == "codex":
|
|
700
|
+
out = Path(d) / "answer"
|
|
701
|
+
cmd = ["codex", "exec", "--skip-git-repo-check", "--ephemeral",
|
|
702
|
+
"--ignore-user-config", "--ignore-rules", "--sandbox", "read-only",
|
|
703
|
+
"-c", "project_doc_max_bytes=0", "-c", 'web_search="disabled"',
|
|
704
|
+
"-c", "mcp_servers={}"]
|
|
705
|
+
for feature in ("shell_tool", "unified_exec", "multi_agent", "view_image",
|
|
706
|
+
"apps", "plugins", "hooks", "skill_search"):
|
|
707
|
+
cmd.extend(["-c", f"features.{feature}=false"])
|
|
708
|
+
cmd.extend(["-o", str(out), "-"])
|
|
709
|
+
p = subprocess.run(cmd, input=prompt, text=True, cwd=d, env=env,
|
|
710
|
+
capture_output=True, timeout=timeout)
|
|
711
|
+
return (out.read_text() if out.is_file() else p.stdout) if p.returncode == 0 else None
|
|
712
|
+
p = subprocess.run(["claude", "-p", "--safe-mode", "--tools", "",
|
|
713
|
+
"--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}',
|
|
714
|
+
"--no-session-persistence"], input=prompt, text=True,
|
|
715
|
+
cwd=d, env=env, capture_output=True, timeout=timeout)
|
|
716
|
+
return p.stdout if p.returncode == 0 else None
|
|
717
|
+
except OSError: # the CLI could not start: same as a failed run, so the fallback runs
|
|
718
|
+
return None
|
|
719
|
+
|
|
720
|
+
|
|
721
|
+
def judge(base, head, body_file, agent):
|
|
722
|
+
mr = load_merge_risk(base)
|
|
723
|
+
if old := missing_functions(mr, *JUDGE_NEEDS):
|
|
724
|
+
fail(f"pr-risk is too old: {', '.join(old)}")
|
|
725
|
+
prompt = (Path(__file__).with_name("judge-prompt.md").read_text()
|
|
726
|
+
+ judge_input(mr, Path(body_file).read_text(), base, head))
|
|
727
|
+
deadline = time.monotonic() + float(os.environ.get("BABYSIT_JUDGE_TIMEOUT", 600))
|
|
728
|
+
other, same = ("codex", "claude") if agent == "claude-code" else ("claude", "codex")
|
|
729
|
+
same_model = False
|
|
730
|
+
try:
|
|
731
|
+
answer = ask(other, prompt, deadline - time.monotonic()) if shutil.which(other) else None
|
|
732
|
+
if answer is None:
|
|
733
|
+
same_model = True
|
|
734
|
+
answer = ask(same, prompt, deadline - time.monotonic()) if shutil.which(same) else None
|
|
735
|
+
except subprocess.TimeoutExpired:
|
|
736
|
+
return {"verdict": "disagree", "reason": "judge timeout", "sameModel": same_model}
|
|
737
|
+
try:
|
|
738
|
+
data = json.loads(answer)
|
|
739
|
+
verdict, reason = data["verdict"], data.get("reason")
|
|
740
|
+
except (TypeError, ValueError, KeyError, AttributeError):
|
|
741
|
+
verdict, reason = None, None
|
|
742
|
+
if verdict == "agree" and not (isinstance(reason, str) and reason.strip()):
|
|
743
|
+
verdict = None
|
|
744
|
+
if verdict == "agree":
|
|
745
|
+
return {"verdict": "agree", "sameModel": same_model,
|
|
746
|
+
"label": "same-model agree" if same_model else "agree"}
|
|
747
|
+
if verdict != "disagree":
|
|
748
|
+
reason = "invalid answer"
|
|
749
|
+
return {"verdict": "disagree", "reason": f"judge: {reason or 'disagree'}", "sameModel": same_model}
|
|
750
|
+
|
|
751
|
+
|
|
752
|
+
def git(*args, ok=(0,)):
|
|
753
|
+
p = subprocess.run(["git", *args], text=True, capture_output=True)
|
|
754
|
+
if p.returncode not in ok:
|
|
755
|
+
fail(f"git {' '.join(args)} failed: {p.stderr.strip()}")
|
|
756
|
+
return p
|
|
757
|
+
|
|
758
|
+
|
|
759
|
+
def update_plan(base):
|
|
760
|
+
"""Dry-run a base update with merge-tree: no worktree, index, HEAD or ref change."""
|
|
761
|
+
compare = f"origin/{base}"
|
|
762
|
+
branch = git("rev-parse", "--abbrev-ref", "HEAD").stdout.strip()
|
|
763
|
+
head = git("rev-parse", "HEAD").stdout.strip()
|
|
764
|
+
out = {"compare": compare, "branch": branch}
|
|
765
|
+
if git("merge-base", "--is-ancestor", compare, "HEAD", ok=(0, 1)).returncode == 0:
|
|
766
|
+
return {**out, "plan": "none"}
|
|
767
|
+
force = shlex.join(["git", "push", f"--force-with-lease={branch}:{head}", "origin", branch])
|
|
768
|
+
mt = git("merge-tree", "--write-tree", "--name-only", "-z", "--no-messages", "HEAD", compare, ok=(0, 1))
|
|
769
|
+
files = [f for f in mt.stdout.split("\0")[1:] if f] if mt.returncode else []
|
|
770
|
+
if not files:
|
|
771
|
+
return {**out, "plan": "rebase", "push": force}
|
|
772
|
+
mb = git("merge-base", "HEAD", compare).stdout.strip()
|
|
773
|
+
# Rebase replays each branch commit that touches a conflicting file: one conflict stop per commit.
|
|
774
|
+
touching = git("--literal-pathspecs", "rev-list", f"{mb}..HEAD", "--", *files).stdout.split()
|
|
775
|
+
if len(touching) >= 3:
|
|
776
|
+
return {**out, "plan": "merge", "push": shlex.join(["git", "push", "origin", branch])}
|
|
777
|
+
return {**out, "plan": "rebase-with-conflict", "files": files, "push": force}
|
|
778
|
+
|
|
779
|
+
|
|
780
|
+
def pr_commits(repo, number):
|
|
781
|
+
return [json.loads(l) for l in gh("api", "--paginate", f"repos/{repo}/pulls/{number}/commits",
|
|
782
|
+
"--jq", ".[] | tojson").splitlines() if l]
|
|
783
|
+
|
|
784
|
+
|
|
785
|
+
def merge_method(repo, number, policy=None):
|
|
786
|
+
"""Policy wins; a branch with a merge commit needs "merge"; else rebase when the repo allows it."""
|
|
787
|
+
configured = (json.loads(Path(policy).read_text()) if policy else {}).get("mergeMethod")
|
|
788
|
+
if configured:
|
|
789
|
+
return configured
|
|
790
|
+
if any(len(c["parents"]) > 1 for c in pr_commits(repo, number)):
|
|
791
|
+
return "merge"
|
|
792
|
+
allowed = json.loads(gh("api", f"repos/{repo}"))
|
|
793
|
+
flags = {"rebase": "allow_rebase_merge", "merge": "allow_merge_commit", "squash": "allow_squash_merge"}
|
|
794
|
+
return next((m for m, f in flags.items() if allowed.get(f)), "rebase")
|
|
795
|
+
|
|
796
|
+
|
|
797
|
+
def squash_message(title, number, body):
|
|
798
|
+
summary = re.search(r"^## Summary\n+(.*?)(?=^## |\Z)", body, re.M | re.S)
|
|
799
|
+
field = lambda k: (re.search(rf"^{k}: (.*)$", body, re.M) or [0, "?"])[1].strip()
|
|
800
|
+
digest = (f"merge-risk v1: {field('door')}, {field('blast_radius')}, touches {field('touches')}, "
|
|
801
|
+
f"rollback {field('rollback')}")
|
|
802
|
+
return f"{title} (#{number})", (summary[1].strip() + "\n\n" if summary else "") + digest
|
|
803
|
+
|
|
804
|
+
|
|
805
|
+
def terminal_owner(pr, session, action):
|
|
806
|
+
"""Fence terminal writes against the current lease; never adopt its session."""
|
|
807
|
+
top = holder(leases(pr.comments(), pr.user()), pr.now())
|
|
808
|
+
if top and not session:
|
|
809
|
+
fail(f"{action} needs --session while a lease is active (reuse it on retries)")
|
|
810
|
+
if top and top[1] != session:
|
|
811
|
+
fail(f"{session} is stale: {top[1]} resumed the PR (taken over)")
|
|
812
|
+
|
|
813
|
+
|
|
814
|
+
def handoff(repo, number, reason, ci, rounds, gate, judge_line, fix_log, extra="", session=None, op=None):
|
|
815
|
+
pr = Pr(repo, number)
|
|
816
|
+
op = op or hashlib.sha256(json.dumps([reason, ci, rounds, gate, judge_line, fix_log]).encode()).hexdigest()[:12]
|
|
817
|
+
tag = f"<!-- babysit-pr handoff: {op} -->"
|
|
818
|
+
user, comments = pr.user(), pr.comments()
|
|
819
|
+
lease_boundary = max((l[0] for l in confirmed_leases(comments, user)), default=0)
|
|
820
|
+
mine = [c for c in comments if c["user"]["login"] == user]
|
|
821
|
+
terminal_owner(pr, session, "handoff")
|
|
822
|
+
last = max((c["id"] for c in mine if HANDOFF.match(c["body"])), default=None)
|
|
823
|
+
# A retry after a partial failure reuses its comment: a second one would move
|
|
824
|
+
# the owner-comment boundary past instructions given in between. A newer lease
|
|
825
|
+
# means the PR was resumed, so this is a new handoff.
|
|
826
|
+
reuse = last is not None and any(c["id"] == last and tag in c["body"] for c in mine) \
|
|
827
|
+
and not any(LEASE.match(c["body"]) and c["id"] > last for c in mine)
|
|
828
|
+
status = f"CI {ci}" + (f" · {rounds} fix rounds" if rounds is not None else "")
|
|
829
|
+
if not reuse:
|
|
830
|
+
pr.post(f"## 🧑 Needs human: {reason}\n\n{status}\n{gate}\n{judge_line}\n{extra}\n"
|
|
831
|
+
f"### Fix log\n\n{fix_log}\n\nResume: `/babysit-pr https://github.com/{repo}/pull/{number}`\n{tag}\n")
|
|
832
|
+
gh("api", "-X", "POST", f"{pr.repo}/labels", "-f", "name=needs-human", check=False) # 422 when it exists
|
|
833
|
+
terminal_owner(pr, session, "handoff")
|
|
834
|
+
pr.label(add=["needs-human"], remove=["babysitting"])
|
|
835
|
+
repair_if_taken_over(pr, session, lease_boundary)
|
|
836
|
+
if session:
|
|
837
|
+
release(pr, session)
|
|
838
|
+
print(json.dumps({"status": "handoff", "terminal": True, "reason": reason,
|
|
839
|
+
"next": "In Claude Code send PushNotification, then end the turn. Otherwise end the turn now."}))
|
|
840
|
+
|
|
841
|
+
|
|
842
|
+
def merge_cmd(repo, number, sha, body_file, policy, judge_label, approved, session=None, base=None):
|
|
843
|
+
pr = json.loads(gh("api", f"repos/{repo}/pulls/{number}"))
|
|
844
|
+
if base not in (None, pr["base"]["ref"]):
|
|
845
|
+
fail(f"--base {base} is not the PR's base {pr['base']['ref']}")
|
|
846
|
+
base = pr["base"]["ref"] # the policy that applies is the target branch's, never the caller's choice
|
|
847
|
+
body = Path(body_file).read_text()
|
|
848
|
+
live = (pr.get("body") or "").strip()
|
|
849
|
+
# The fetched PR body is what the gate judges; a stale snapshot must not stand in for it.
|
|
850
|
+
if live != body.strip():
|
|
851
|
+
fail("--body differs from the PR's current body: gate again")
|
|
852
|
+
body = live
|
|
853
|
+
base_tip = lambda: subprocess.run(["git", "rev-parse", f"origin/{base}"], text=True, capture_output=True).stdout.strip()
|
|
854
|
+
tip = base_tip() # the policy is read at this commit; a base that moves under the gate voids it
|
|
855
|
+
if pr["base"].get("sha") not in (None, tip): # GitHub's base is newer than the local ref the policy is read from
|
|
856
|
+
fail(f"origin/{base} is {tip[:7]} but the PR's base is {pr['base']['sha'][:7]}: fetch and gate again")
|
|
857
|
+
gate = "gate: passed"
|
|
858
|
+
judge_line = f"judge: {judge_label}"
|
|
859
|
+
op = hashlib.sha256(f"{sha} {judge_label} {approved}".encode()).hexdigest()[:12]
|
|
860
|
+
|
|
861
|
+
def stop(reason, extra=""):
|
|
862
|
+
handoff(repo, number, reason, "green", None, gate, judge_line, "(none)", extra, session, f"{op}-{reason}")
|
|
863
|
+
fail(reason)
|
|
864
|
+
|
|
865
|
+
if pr["head"]["sha"] != sha:
|
|
866
|
+
fail(f"head moved to {pr['head']['sha']} since the gate saw {sha}: gate again")
|
|
867
|
+
if approved is None:
|
|
868
|
+
if judge_label not in ("agree", "same-model agree"):
|
|
869
|
+
stop(f"judge {judge_label}")
|
|
870
|
+
mr = load_merge_risk(base)
|
|
871
|
+
if old := missing_functions(mr, *GATE_NEEDS):
|
|
872
|
+
stop(f"pr-risk is too old: {', '.join(old)}")
|
|
873
|
+
result = mr.gate(body, base, sha) # trusted policy, recomputed for this sha
|
|
874
|
+
if result["verdict"] != "auto":
|
|
875
|
+
gate = "gate: human"
|
|
876
|
+
stop(f"gate is human: {'; '.join(result['reasons'])}")
|
|
877
|
+
else:
|
|
878
|
+
judge_line = f"owner approved {approved}"
|
|
879
|
+
commits = pr_commits(repo, number)
|
|
880
|
+
oids = [c["sha"] for c in commits]
|
|
881
|
+
hits = {o for o in oids if o.startswith(approved)} if re.fullmatch(r"[0-9a-f]{7,40}", approved) else set()
|
|
882
|
+
full = hits.pop() if len(hits) == 1 else None # an ambiguous or short prefix approves nothing
|
|
883
|
+
found = owner_comments(repo, number)
|
|
884
|
+
unnamed = "merge approval must name a commit: @babysitter merge <sha>"
|
|
885
|
+
rebased = full is None and not any(o.startswith(approved) for o in oids) and re.fullmatch(r"[0-9a-f]{7,40}", approved) and found["handoff"] in (None, unnamed)
|
|
886
|
+
if not rebased and (full is None or not any(i["approved_sha"] == full for i in found["instructions"])):
|
|
887
|
+
stop(found["handoff"] or unnamed)
|
|
888
|
+
if full is None and not re.fullmatch(r"[0-9a-f]{7,40}", approved):
|
|
889
|
+
stop("approval must name a commit: @babysitter merge <sha>")
|
|
890
|
+
if full != sha:
|
|
891
|
+
extra = ""
|
|
892
|
+
if re.fullmatch(r"[0-9a-f]{7,40}", approved):
|
|
893
|
+
# A rebase rewrites the sha: the link still shows the change, but there is no list.
|
|
894
|
+
extra = f"\nNew commits since the approval: https://github.com/{repo}/compare/{full or approved}...{sha}\n"
|
|
895
|
+
if full:
|
|
896
|
+
who = lambda c: (c["author"] or {}).get("login") or c["commit"].get("author", {}).get("name", "unknown")
|
|
897
|
+
extra += "\n".join(f"- `{c['sha']}` {c['commit']['message'].splitlines()[0]} ({who(c)})"
|
|
898
|
+
for c in commits[oids.index(full) + 1:]) + "\n"
|
|
899
|
+
stop(f"approval was for {approved}", extra)
|
|
900
|
+
state = ci_state(repo, number, 0)
|
|
901
|
+
if state != "green":
|
|
902
|
+
stop(f"CI is {state} at merge time")
|
|
903
|
+
method = merge_method(repo, number, policy)
|
|
904
|
+
cmd = ["pr", "merge", str(number), "--repo", repo, f"--{method}", "--match-head-commit", sha]
|
|
905
|
+
if method == "squash":
|
|
906
|
+
subject, text = squash_message(pr["title"], number, body)
|
|
907
|
+
cmd += ["--subject", subject, "--body", text]
|
|
908
|
+
now = json.loads(gh("api", f"repos/{repo}/pulls/{number}"))
|
|
909
|
+
if now["base"]["ref"] != base or now["head"]["sha"] != sha or (now.get("body") or "").strip() != live or now["base"].get("sha") not in (None, tip) or base_tip() != tip:
|
|
910
|
+
fail("the PR's base, head or body changed during the gate: gate again")
|
|
911
|
+
terminal_owner(Pr(repo, number), session, "merge")
|
|
912
|
+
if session:
|
|
913
|
+
own_lease(repo, number, session)
|
|
914
|
+
p = subprocess.run(["gh", *cmd], text=True, capture_output=True)
|
|
915
|
+
if p.returncode:
|
|
916
|
+
err = p.stderr.strip()
|
|
917
|
+
if "head branch was modified" in err.lower():
|
|
918
|
+
fail(f"head moved since the gate saw {sha}: gate again")
|
|
919
|
+
stop(f"merge blocked: {'approval required' if 'approv' in err.lower() else err}")
|
|
920
|
+
pr = Pr(repo, number)
|
|
921
|
+
pr.post("🤖 Merged by babysit-pr: gate passed, " + (
|
|
922
|
+
f"judge {judge_label}" if approved is None else f"owner approved {approved}"))
|
|
923
|
+
if session:
|
|
924
|
+
release(pr, session)
|
|
925
|
+
|
|
926
|
+
|
|
927
|
+
def main():
|
|
928
|
+
ap = argparse.ArgumentParser()
|
|
929
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
930
|
+
lp = sub.add_parser("lease")
|
|
931
|
+
lp.add_argument("verb", choices=["acquire", "renew", "check", "release"])
|
|
932
|
+
for a in ("repo", "pr", "session", "host"):
|
|
933
|
+
lp.add_argument(f"--{a}", required=True)
|
|
934
|
+
op = sub.add_parser("owner-comments")
|
|
935
|
+
for a in ("repo", "pr"):
|
|
936
|
+
op.add_argument(f"--{a}", required=True)
|
|
937
|
+
cp = sub.add_parser("checks")
|
|
938
|
+
cp.add_argument("--repo", required=True)
|
|
939
|
+
cp.add_argument("--pr", required=True)
|
|
940
|
+
cp.add_argument("--wait-minutes", type=int, required=True)
|
|
941
|
+
rp = sub.add_parser("round")
|
|
942
|
+
rp.add_argument("verb", choices=["start", "record-failure"])
|
|
943
|
+
for a in ("repo", "pr", "session", "host"):
|
|
944
|
+
rp.add_argument(f"--{a}", required=True)
|
|
945
|
+
rp.add_argument("--check")
|
|
946
|
+
rp.add_argument("--error")
|
|
947
|
+
rp.add_argument("--op", help="stable round start ID; record-failure reuses its originating start ID on retries")
|
|
948
|
+
jp = sub.add_parser("judge")
|
|
949
|
+
for a in ("body", "base", "head"):
|
|
950
|
+
jp.add_argument(f"--{a}", required=True)
|
|
951
|
+
jp.add_argument("--agent", choices=["claude-code", "codex"], required=True)
|
|
952
|
+
up = sub.add_parser("update-plan")
|
|
953
|
+
up.add_argument("--base", required=True)
|
|
954
|
+
mp = sub.add_parser("merge-method")
|
|
955
|
+
mg = sub.add_parser("merge")
|
|
956
|
+
hp = sub.add_parser("handoff")
|
|
957
|
+
for p in (mp, mg, hp):
|
|
958
|
+
for x in ("repo", "pr"):
|
|
959
|
+
p.add_argument(f"--{x}", required=True)
|
|
960
|
+
for p in (mp, mg):
|
|
961
|
+
p.add_argument("--policy")
|
|
962
|
+
mg.add_argument("--sha", required=True)
|
|
963
|
+
mg.add_argument("--body", required=True)
|
|
964
|
+
mg.add_argument("--judge")
|
|
965
|
+
mg.add_argument("--approved-sha")
|
|
966
|
+
mg.add_argument("--base")
|
|
967
|
+
for p in (mg, hp):
|
|
968
|
+
p.add_argument("--session", help="release this session's lease")
|
|
969
|
+
for x in ("reason", "ci", "gate", "judge", "fix-log"):
|
|
970
|
+
hp.add_argument(f"--{x}", required=True)
|
|
971
|
+
hp.add_argument("--rounds", type=int, required=True)
|
|
972
|
+
a = ap.parse_args()
|
|
973
|
+
if a.cmd == "owner-comments":
|
|
974
|
+
print(json.dumps(owner_comments(a.repo, a.pr)))
|
|
975
|
+
elif a.cmd == "checks":
|
|
976
|
+
checks_cmd(a.repo, a.pr, a.wait_minutes)
|
|
977
|
+
elif a.cmd == "round":
|
|
978
|
+
if a.verb == "record-failure" and not (a.check and a.error):
|
|
979
|
+
ap.error("record-failure needs --check and --error")
|
|
980
|
+
round_cmd(a.verb, a.repo, a.pr, a.session, a.check, a.error, a.op)
|
|
981
|
+
elif a.cmd == "judge":
|
|
982
|
+
print(json.dumps(judge(a.base, a.head, a.body, a.agent)))
|
|
983
|
+
elif a.cmd == "merge-method":
|
|
984
|
+
print(json.dumps({"method": merge_method(a.repo, a.pr, a.policy)}))
|
|
985
|
+
elif a.cmd == "merge":
|
|
986
|
+
if not (a.judge or a.approved_sha):
|
|
987
|
+
ap.error("merge needs --judge or --approved-sha")
|
|
988
|
+
merge_cmd(a.repo, a.pr, a.sha, a.body, a.policy, a.judge, a.approved_sha, a.session, a.base)
|
|
989
|
+
elif a.cmd == "handoff":
|
|
990
|
+
handoff(a.repo, a.pr, a.reason, a.ci, a.rounds, a.gate, a.judge, Path(a.fix_log).read_text(), session=a.session)
|
|
991
|
+
elif a.cmd == "update-plan":
|
|
992
|
+
print(json.dumps(update_plan(a.base)))
|
|
993
|
+
else:
|
|
994
|
+
lease(a.verb, a.repo, a.pr, a.session, a.host)
|
|
995
|
+
|
|
996
|
+
|
|
997
|
+
if __name__ == "__main__":
|
|
998
|
+
main()
|