@jesdi/skills 0.0.62 → 0.0.64

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.
Files changed (66) hide show
  1. package/README.md +15 -0
  2. package/package.json +2 -2
  3. package/skills/babysit-pr/SKILL.md +54 -0
  4. package/skills/babysit-pr/babysit.py +998 -0
  5. package/skills/babysit-pr/fixtures/gh +310 -0
  6. package/skills/babysit-pr/hooks/post-pr-create.sh +56 -0
  7. package/skills/babysit-pr/hooks.json +10 -0
  8. package/skills/babysit-pr/judge-prompt.md +10 -0
  9. package/skills/babysit-pr/test_babysit.py +242 -0
  10. package/skills/babysit-pr/test_babysit_judge.py +286 -0
  11. package/skills/babysit-pr/test_babysit_judge_diff.py +25 -0
  12. package/skills/babysit-pr/test_babysit_judge_isolation.py +61 -0
  13. package/skills/babysit-pr/test_checks_regressions.py +210 -0
  14. package/skills/babysit-pr/test_comment_fidelity.py +88 -0
  15. package/skills/babysit-pr/test_comment_identity.py +70 -0
  16. package/skills/babysit-pr/test_e2e_setup.py +74 -0
  17. package/skills/babysit-pr/test_handoff_takeover.py +141 -0
  18. package/skills/babysit-pr/test_handoff_terminal.py +29 -0
  19. package/skills/babysit-pr/test_hook_quoting.py +25 -0
  20. package/skills/babysit-pr/test_hooks.py +62 -0
  21. package/skills/babysit-pr/test_lease_regressions.py +198 -0
  22. package/skills/babysit-pr/test_merge_and_handoff.py +260 -0
  23. package/skills/babysit-pr/test_merge_base_pin.py +10 -0
  24. package/skills/babysit-pr/test_merge_gate.py +124 -0
  25. package/skills/babysit-pr/test_merge_session_safety.py +117 -0
  26. package/skills/babysit-pr/test_merged_pr_labels.py +144 -0
  27. package/skills/babysit-pr/test_owner_comment_edits.py +26 -0
  28. package/skills/babysit-pr/test_owner_comments.py +316 -0
  29. package/skills/babysit-pr/test_retry_and_stall_hardening.py +143 -0
  30. package/skills/babysit-pr/test_rounds_and_checks.py +305 -0
  31. package/skills/babysit-pr/test_terminal_label_regressions.py +117 -0
  32. package/skills/babysit-pr/test_trusted_merge_risk.py +184 -0
  33. package/skills/babysit-pr/test_update_plan.py +157 -0
  34. package/skills/implement-spec/ARCHITECTURE.md +5 -0
  35. package/skills/implement-spec/README.md +7 -6
  36. package/skills/implement-spec/SKILL.md +1 -1
  37. package/skills/implement-spec/driver.py +11 -1
  38. package/skills/implement-spec/driver_decisions.py +23 -0
  39. package/skills/implement-spec/driver_final.py +49 -10
  40. package/skills/implement-spec/driver_fixloop.py +17 -5
  41. package/skills/implement-spec/driver_report.py +16 -5
  42. package/skills/implement-spec/driver_state.py +2 -2
  43. package/skills/implement-spec/prompts/pr-writer.md +3 -2
  44. package/skills/implement-spec/prompts/rejected.md +1 -0
  45. package/skills/implement-spec/tests/test_decisions.py +57 -0
  46. package/skills/implement-spec/tests/test_final.py +112 -1
  47. package/skills/implement-spec/tests/test_fixloop.py +14 -2
  48. package/skills/implement-spec/tests/test_report.py +18 -0
  49. package/skills/implement-spec/tests/test_review.py +1 -1
  50. package/skills/implement-spec/tests/test_state.py +1 -1
  51. package/skills/implement-spec/tests/test_tidy.py +2 -2
  52. package/skills/implement-spec/tests/test_walk.py +2 -2
  53. package/skills/pr-risk/SKILL.md +33 -0
  54. package/skills/pr-risk/hooks/pre-pr-create.sh +274 -0
  55. package/skills/pr-risk/hooks.json +10 -0
  56. package/skills/pr-risk/merge_policy.py +81 -0
  57. package/skills/pr-risk/merge_risk.py +314 -0
  58. package/skills/pr-risk/test_hook_commands.py +47 -0
  59. package/skills/pr-risk/test_hook_heredoc.py +16 -0
  60. package/skills/pr-risk/test_hook_substitution.py +40 -0
  61. package/skills/pr-risk/test_hooks.py +175 -0
  62. package/skills/pr-risk/test_merge_risk.py +97 -0
  63. package/skills/pr-risk/test_merge_risk_gate.py +217 -0
  64. package/skills/pr-risk/test_merge_risk_regressions.py +37 -0
  65. package/skills/pr-risk/test_merge_risk_structure.py +101 -0
  66. package/skills-manifest.json +15 -3
@@ -0,0 +1,310 @@
1
+ #!/usr/bin/env python3
2
+ """Fake `gh` for babysit-pr tests. It serves and records GitHub state.
3
+
4
+ State is the JSON file $GH_FAKE_STATE:
5
+ now GitHub's clock (ISO, Z). Every comment written gets created_at/updated_at = now.
6
+ user login of `gh api user`
7
+ next_id id of the next comment posted
8
+ comments [{id, user: {login}, body, created_at, updated_at}]
9
+ labels [name] on the PR
10
+ repo_labels [name] labels that exist in the repository (optional; when set, assigning a label
11
+ that is not in it fails 422 like GitHub, and `POST repos/O/R/labels -f name=X` creates it)
12
+ head_sha head commit of every PR (default "head1")
13
+ check_runs {sha: [{name, status, conclusion, created_at, started_at}]} (REST check-runs shape)
14
+ statuses {sha: [{context, state}]} newest first; commits/SHA/statuses is [] when unseeded
15
+ required_checks [name] returned as branch protection contexts of any branch
16
+ reviews [{id, user: {login}, state, body, submitted_at}] (optional)
17
+ commits [{sha, date}] oldest first, date = commit time (optional)
18
+ threads [{user: {login}, resolved}] review threads (optional)
19
+ Comments may carry `editor` ({login}) and `last_edited_at` (GraphQL `editor` / `lastEditedAt`).
20
+ page_size GraphQL connections return this many nodes per page (cursor = offset); default all
21
+ threads may carry `more_comments` (true: the thread has comments beyond the page read)
22
+ title, body PR title and body (default "" )
23
+ repo_settings {allow_rebase_merge, allow_merge_commit, allow_squash_merge} served by `gh api repos/O/R`
24
+ merge_error when set, `gh pr merge` fails printing it (e.g. a required approval)
25
+ merges recorded successful `gh pr merge` calls: {number, method, match, subject, body, auto}
26
+ Commits may carry `message`, `author` (login) and `parents` (list of shas; 2 = a merge commit).
27
+ `gh pr merge N --rebase|--merge|--squash --match-head-commit SHA [--subject S] [--body B]` fails
28
+ when SHA is not head_sha, like GitHub does.
29
+ hidden_until_post comment ids missing from comment lists until the first comment is posted
30
+ (a race: the other session posts after our first read)
31
+ Every call is appended to $GH_FAKE_LOG as one JSON line {argv, write, unsupported}.
32
+ Supported: `gh api` (user, pulls/N/reviews, pulls/N/comments (review comments, always empty),
33
+ pulls/N/commits, `graphql` (answers the one connection the query asks for, with only the fields it selects), issues/N, pulls/N, issues/N/comments, issues/comments/ID,
34
+ issues/N/labels[/NAME], commits/SHA/check-runs, commits/SHA/statuses, branches/B/protection/required_status_checks; -X, -f/-F, --input, --jq, --paginate, -i), `gh pr|issue view|comment|edit`.
35
+ """
36
+ import json
37
+ import os
38
+ import re
39
+ import subprocess
40
+ import sys
41
+
42
+ STATE = os.environ["GH_FAKE_STATE"]
43
+ LOG = os.environ["GH_FAKE_LOG"]
44
+ argv = sys.argv[1:]
45
+ st = json.load(open(STATE))
46
+
47
+
48
+ def log(write, unsupported=False):
49
+ with open(LOG, "a") as f:
50
+ f.write(json.dumps({"argv": argv, "write": write, "unsupported": unsupported}) + "\n")
51
+
52
+
53
+ def save():
54
+ json.dump(st, open(STATE, "w"))
55
+
56
+
57
+ def die(msg, write=False):
58
+ log(write, unsupported=True)
59
+ print(f"fake gh: {msg}: gh {' '.join(argv)}", file=sys.stderr)
60
+ sys.exit(1)
61
+
62
+
63
+ def visible():
64
+ if st.get("posted"):
65
+ return st["comments"]
66
+ return [c for c in st["comments"] if c["id"] not in st.get("hidden_until_post", [])]
67
+
68
+
69
+ def new_comment(body):
70
+ c = {"id": st["next_id"], "user": {"login": st["user"]}, "body": body,
71
+ "created_at": st["now"], "updated_at": st["now"]}
72
+ st["next_id"] += 1
73
+ st["comments"].append(c)
74
+ st["posted"] = True
75
+ return c
76
+
77
+
78
+ def find(cid):
79
+ for c in st["comments"]:
80
+ if c["id"] == int(cid):
81
+ return c
82
+ die("no such comment")
83
+
84
+
85
+ def emit(obj, jq, include=False):
86
+ if include:
87
+ print(f"HTTP/2.0 200 OK\nDate: {st['now']}\nContent-Type: application/json\n")
88
+ if jq:
89
+ p = subprocess.run(["jq", "-r", jq], input=json.dumps(obj), text=True, capture_output=True)
90
+ sys.stdout.write(p.stdout)
91
+ sys.stderr.write(p.stderr)
92
+ sys.exit(p.returncode)
93
+ print(json.dumps(obj))
94
+
95
+
96
+ def labels_obj():
97
+ return [{"name": n} for n in st["labels"]]
98
+
99
+
100
+ def add_labels(names):
101
+ if "repo_labels" in st:
102
+ missing = [n for n in names if n not in st["repo_labels"]]
103
+ if missing:
104
+ die(f"HTTP 422: label does not exist in the repository: {missing}", True)
105
+ for n in names:
106
+ if n not in st["labels"]:
107
+ st["labels"].append(n)
108
+
109
+
110
+ def remove_label(name):
111
+ if name in st["labels"]:
112
+ st["labels"].remove(name)
113
+
114
+
115
+ def api(args):
116
+ method, fields, jq, path, inp, include = None, {}, None, None, None, False
117
+ i = 0
118
+ while i < len(args):
119
+ a = args[i]
120
+ if a in ("-X", "--method"):
121
+ method = args[i + 1].upper(); i += 2
122
+ elif a in ("-f", "-F", "--raw-field", "--field"):
123
+ k, _, v = args[i + 1].partition("=")
124
+ if k.endswith("[]"):
125
+ fields.setdefault(k[:-2], []).append(v)
126
+ else:
127
+ fields[k] = v
128
+ i += 2
129
+ elif a == "--input":
130
+ inp = args[i + 1]
131
+ data = sys.stdin.read() if inp == "-" else open(inp).read()
132
+ fields.update(json.loads(data)); i += 2
133
+ elif a in ("--jq", "-q"):
134
+ jq = args[i + 1]; i += 2
135
+ elif a in ("-H", "--header", "--cache"):
136
+ i += 2
137
+ elif a in ("-i", "--include"):
138
+ include = True; i += 1
139
+ elif a.startswith("-"):
140
+ i += 1
141
+ else:
142
+ path = a; i += 1
143
+ if method is None:
144
+ method = "POST" if fields else "GET"
145
+ path = re.sub(r"^/?(repos/[^/]+/[^/]+/)?", "", path or "")
146
+ write = method != "GET"
147
+ n = r"(\d+)"
148
+ if path == "user":
149
+ log(False); return emit({"login": st["user"]}, jq, include)
150
+ if m := re.fullmatch(rf"(?:issues|pulls)/{n}", path) and method == "GET":
151
+ log(False)
152
+ return emit({"number": int(path.split("/")[1]), "state": "open", "labels": labels_obj(),
153
+ "user": {"login": st["user"]},
154
+ "title": st.get("title", ""), "body": st.get("body", ""),
155
+ "head": {"sha": st.get("head_sha", "head1")},
156
+ "base": {"ref": st.get("base_ref", "main"), **({"sha": st["base_sha"]} if "base_sha" in st else {})}}, jq, include)
157
+ if re.fullmatch(r"repos/[^/]+/[^/]+", path) and method == "GET":
158
+ log(False)
159
+ return emit(st.get("repo_settings", {"allow_rebase_merge": True, "allow_merge_commit": True,
160
+ "allow_squash_merge": False}), jq, include)
161
+ if re.fullmatch(rf"pulls/{n}/reviews", path) and method == "GET":
162
+ log(False)
163
+ return emit([{"id": r["id"], "user": r["user"], "state": r["state"], "body": r.get("body", ""),
164
+ "submitted_at": r["submitted_at"]} for r in st.get("reviews", [])], jq, include)
165
+ if re.fullmatch(rf"pulls/{n}/comments", path) and method == "GET":
166
+ log(False); return emit([], jq, include)
167
+ if re.fullmatch(rf"pulls/{n}/commits", path) and method == "GET":
168
+ log(False)
169
+ return emit([{"sha": c["sha"], "parents": [{"sha": x} for x in c.get("parents", ["p0"])],
170
+ "author": {"login": c.get("author", "jesdi")},
171
+ "commit": {"message": c.get("message", ""), "committer": {"date": c["date"]}}}
172
+ for c in st.get("commits", [])], jq, include)
173
+ if path == "graphql":
174
+ log(False)
175
+ q = fields.get("query", "")
176
+ def pick(node, sel): # only the fields the query selects, as the real API does
177
+ if isinstance(node, dict):
178
+ return {k: pick(v, sel) for k, v in node.items() if re.search(rf"\b{k}\b", sel)}
179
+ if isinstance(node, list):
180
+ return [pick(v, sel) for v in node]
181
+ return node
182
+ every = {
183
+ "comments": [{"databaseId": c["id"], "author": c["user"], "editor": c.get("editor"),
184
+ "lastEditedAt": c.get("last_edited_at"), "createdAt": c["created_at"],
185
+ "body": c["body"]} for c in visible()],
186
+ "reviews": [{"databaseId": r["id"], "author": r["user"], "state": r["state"],
187
+ "body": r.get("body", ""), "submittedAt": r["submitted_at"],
188
+ "editor": r.get("editor"), "lastEditedAt": r.get("last_edited_at")}
189
+ for r in st.get("reviews", [])],
190
+ "reviewThreads": [{"isResolved": t["resolved"], "comments": {"nodes": [{"author": t["user"], "createdAt": t.get("created_at")}],
191
+ "pageInfo": {"hasNextPage": t.get("more_comments", False), "endCursor": None}}}
192
+ for t in st.get("threads", [])],
193
+ "commits": [{"commit": {"oid": c["sha"], "committedDate": c["date"]}}
194
+ for c in st.get("commits", [])]}
195
+ m = re.search(r"pullRequest\([^)]*\)\s*\{\s*(\w+)", q)
196
+ name = m.group(1) if m else None
197
+ if name not in every:
198
+ die("graphql query selects no known connection", False)
199
+ size, start = st.get("page_size") or len(every[name]) or 1, int(fields.get("after") or 0)
200
+ end = start + size
201
+ page = {"nodes": pick(every[name][start:end], q),
202
+ "pageInfo": {"hasNextPage": end < len(every[name]), "endCursor": str(end)}}
203
+ return emit({"data": {"repository": {"pullRequest": {name: page}}}}, jq, include)
204
+ if m := re.fullmatch(r"commits/([^/]+)/check-runs", path):
205
+ log(False)
206
+ runs = st.get("check_runs", {}).get(m.group(1), [])
207
+ return emit({"total_count": len(runs), "check_runs": runs}, jq, include)
208
+ if m := re.fullmatch(r"commits/([^/]+)/statuses", path):
209
+ log(False)
210
+ return emit(st.get("statuses", {}).get(m.group(1), []), jq, include)
211
+ if re.fullmatch(r"branches/[^/]+/protection/required_status_checks", path):
212
+ log(False)
213
+ return emit({"strict": False, "contexts": st.get("required_checks", [])}, jq, include)
214
+ if re.fullmatch(rf"issues/{n}/comments", path):
215
+ if method == "GET":
216
+ log(False); return emit(visible(), jq, include)
217
+ if method == "POST":
218
+ log(True); c = new_comment(fields.get("body", "")); save(); return emit(c, jq, include)
219
+ if m := re.fullmatch(r"issues/comments/(\d+)", path):
220
+ c = find(m.group(1))
221
+ if method == "GET":
222
+ log(False); return emit(c, jq, include)
223
+ if method in ("PATCH", "PUT"):
224
+ log(True)
225
+ c["body"] = fields.get("body", c["body"]); c["updated_at"] = st["now"]
226
+ c["editor"] = {"login": st["user"]}
227
+ c["last_edited_at"] = st["now"]
228
+ save(); return emit(c, jq, include)
229
+ if method == "DELETE":
230
+ log(True); st["comments"].remove(c); save(); return
231
+ if path == "labels" and method == "POST":
232
+ name = fields.get("name", "")
233
+ if name in st.get("repo_labels", []):
234
+ die("HTTP 422: already_exists", True)
235
+ log(True); st.setdefault("repo_labels", []).append(name); save()
236
+ return emit({"name": name}, jq, include)
237
+ if re.fullmatch(rf"issues/{n}/labels", path):
238
+ if method == "GET":
239
+ log(False); return emit(labels_obj(), jq, include)
240
+ if method == "POST":
241
+ log(True); add_labels(fields.get("labels", [])); save(); return emit(labels_obj(), jq, include)
242
+ if method == "PUT":
243
+ log(True); st["labels"] = list(fields.get("labels", [])); save(); return emit(labels_obj(), jq, include)
244
+ if method == "DELETE":
245
+ log(True); st["labels"] = []; save(); return
246
+ if m := re.fullmatch(rf"issues/{n}/labels/(.+)", path):
247
+ if method == "DELETE":
248
+ from urllib.parse import unquote
249
+ log(True); remove_label(unquote(m.group(2))); save(); return emit(labels_obj(), jq, include)
250
+ die(f"unsupported api {method} {path}", write)
251
+
252
+
253
+ def flag_values(args, *names):
254
+ out = []
255
+ for i, a in enumerate(args):
256
+ if a in names:
257
+ out.append(args[i + 1])
258
+ for nm in names:
259
+ if a.startswith(nm + "="):
260
+ out.append(a.split("=", 1)[1])
261
+ return out
262
+
263
+
264
+ def pr_like(args):
265
+ verb = args[0]
266
+ rest = args[1:]
267
+ if verb == "view":
268
+ jq = (flag_values(rest, "--jq", "-q") or [None])[0]
269
+ comments = [{"id": str(c["id"]), "body": c["body"], "author": c["user"],
270
+ "createdAt": c["created_at"], "updatedAt": c["updated_at"]} for c in visible()]
271
+ log(False)
272
+ return emit({"labels": labels_obj(), "comments": comments, "state": "OPEN",
273
+ "title": st.get("title", ""), "body": st.get("body", ""),
274
+ "headRefOid": st.get("head_sha", "head1")}, jq)
275
+ if verb == "merge":
276
+ match = (flag_values(rest, "--match-head-commit") or [None])[0]
277
+ method = next((m for m in ("rebase", "merge", "squash") if f"--{m}" in rest), None)
278
+ if st.get("merge_error"):
279
+ log(True); print(st["merge_error"], file=sys.stderr); sys.exit(1)
280
+ if match != st.get("head_sha", "head1"):
281
+ log(True); print("Head branch was modified. Review and try the merge again.", file=sys.stderr)
282
+ sys.exit(1)
283
+ log(True)
284
+ st.setdefault("merges", []).append({
285
+ "number": rest[0], "method": method, "match": match, "auto": "--auto" in rest,
286
+ "subject": (flag_values(rest, "--subject", "-t") or [None])[0],
287
+ "body": (flag_values(rest, "--body", "-b") or [None])[0]})
288
+ save(); return
289
+ if verb == "comment":
290
+ body = (flag_values(rest, "--body", "-b") or [""])[0]
291
+ log(True); new_comment(body); save(); return
292
+ if verb == "edit":
293
+ log(True)
294
+ for lab in flag_values(rest, "--add-label"):
295
+ add_labels(lab.split(","))
296
+ for lab in flag_values(rest, "--remove-label"):
297
+ for x in lab.split(","):
298
+ remove_label(x)
299
+ save(); return
300
+ die("unsupported pr/issue verb", True)
301
+
302
+
303
+ if not argv:
304
+ die("no args")
305
+ if argv[0] == "api":
306
+ api(argv[1:])
307
+ elif argv[0] in ("pr", "issue") and len(argv) > 1:
308
+ pr_like(argv[1:])
309
+ else:
310
+ die("unsupported command")
@@ -0,0 +1,56 @@
1
+ #!/bin/sh
2
+ # PostToolUse hook (Claude and Codex): after a ready `gh pr create` in a repo with
3
+ # .merge-risk.json, tell the agent to run /babysit-pr <url>. Otherwise print nothing.
4
+ payload="$(cat)"
5
+ command -v jq >/dev/null 2>&1 || exit 0
6
+ cmd="$(printf '%s' "$payload" | jq -r '.tool_input.command // ""')"
7
+ # Split only at unquoted operators, then parse each command as POSIX shell words.
8
+ printf '%s' "$cmd" | python3 -c '
9
+ import shlex, sys
10
+ command = sys.stdin.read()
11
+ segments, start, quote, escaped = [], 0, None, False
12
+ for i, char in enumerate(command):
13
+ if escaped:
14
+ escaped = False
15
+ elif char == "\\" and quote != chr(39):
16
+ escaped = True
17
+ elif quote:
18
+ if char == quote:
19
+ quote = None
20
+ elif char in (chr(39), chr(34)):
21
+ quote = char
22
+ elif char in "();&|\n":
23
+ segments.append(command[start:i])
24
+ start = i + 1
25
+ segments.append(command[start:])
26
+ try:
27
+ segs = [shlex.split(segment) for segment in segments]
28
+ except ValueError:
29
+ sys.exit(1)
30
+ VALUED = {"--title", "-t", "--body", "-b", "--body-file", "-F", "--base", "-B", "--head", "-H",
31
+ "--assignee", "-a", "--label", "-l", "--milestone", "-m", "--project", "-p",
32
+ "--reviewer", "-r", "--template", "-T", "--repo", "-R"}
33
+ for s in segs:
34
+ while s and "=" in s[0] and not s[0].startswith("-"):
35
+ s = s[1:]
36
+ if s[:3] == ["gh", "pr", "create"]:
37
+ skip = False
38
+ for a in s[3:]:
39
+ if skip:
40
+ skip = False
41
+ elif a in ("--draft", "-d") or a.startswith("--draft="):
42
+ sys.exit(1)
43
+ elif a in VALUED:
44
+ skip = True
45
+ sys.exit(0)
46
+ sys.exit(1)
47
+ ' || exit 0
48
+ cwd="$(printf '%s' "$payload" | jq -r '.cwd // "."')"
49
+ root="$(git -C "$cwd" rev-parse --show-toplevel 2>/dev/null || printf '%s' "$cwd")"
50
+ [ -f "$root/.merge-risk.json" ] || exit 0
51
+ # Claude sends {stdout,...}, Codex a plain string.
52
+ url="$(printf '%s' "$payload" | jq -r '.tool_response | if type == "object" then .stdout // "" else . // "" end' |
53
+ grep -Eo 'https://[^ /]+/[^ /]+/[^ /]+/pull/[0-9]+' | tail -n 1)"
54
+ [ -n "$url" ] || exit 0
55
+ jq -n --arg url "$url" '{hookSpecificOutput: {hookEventName: "PostToolUse",
56
+ additionalContext: "A pull request was opened. Run `/babysit-pr \($url)`."}}'
@@ -0,0 +1,10 @@
1
+ {
2
+ "hooks": {
3
+ "PostToolUse": [
4
+ {
5
+ "matcher": "Bash",
6
+ "hooks": [{ "type": "command", "command": "hooks/post-pr-create.sh" }]
7
+ }
8
+ ]
9
+ }
10
+ }
@@ -0,0 +1,10 @@
1
+ You are an independent judge of merge risk. You see only the input below: the diff of the counted
2
+ files, the names and line counts of the other files, the PR's merge-risk block and the categories
3
+ of the diff. You have no other context, and you must not assume any.
4
+
5
+ Decide whether an agent may merge this change without a human. Any doubt is `disagree`: public
6
+ interfaces, auth, money, data loss, anything hard to revert, or a block that understates the diff.
7
+
8
+ Answer with one JSON object and nothing else:
9
+ {"verdict": "agree" | "disagree", "reason": "<one short sentence>"}
10
+
@@ -0,0 +1,242 @@
1
+ """Acceptance tests for `babysit.py lease acquire|renew|check|release`.
2
+
3
+ Interface under test:
4
+ babysit.py lease <verb> --repo <owner/name> --pr <number> --session <id> --host <name>
5
+ Exit 0 means success (acquire: the session holds the lease; check: it still holds it).
6
+ Any failure exits non-zero and prints its reason on stdout or stderr.
7
+
8
+ The lease is a PR comment `<!-- babysit-pr lease: <session> <host> <expires-at> -->` (ISO UTC).
9
+ An ended lease comment keeps its id and its body says "ended".
10
+
11
+ `gh` is the fake in fixtures/gh, first on PATH. It holds GitHub state and its own clock (`now`),
12
+ and records every call. The fake GitHub clock is set in 2020 or 2099, never near the host
13
+ clock, so a babysitter that reads the host clock decides wrongly.
14
+ """
15
+ import json
16
+ import os
17
+ import re
18
+ import shutil
19
+ import subprocess
20
+ import sys
21
+ from datetime import datetime, timedelta, timezone
22
+ from pathlib import Path
23
+
24
+ import pytest
25
+
26
+ SCRIPT = Path(__file__).with_name("babysit.py").resolve()
27
+ FAKE_GH = Path(__file__).parent / "fixtures" / "gh"
28
+ LEASE = re.compile(r"<!-- babysit-pr lease: (\S+) (\S+) (\S+) -->")
29
+ INSTALL = "npx @jesdi/skills-cli install pr-risk"
30
+ T = datetime(2020, 1, 1, 10, 5, tzinfo=timezone.utc)
31
+ MIN = timedelta(minutes=1)
32
+
33
+
34
+ def iso(dt):
35
+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
36
+
37
+
38
+ def parse(s):
39
+ return datetime.fromisoformat(s.replace("Z", "+00:00"))
40
+
41
+
42
+ def lease_comment(cid, session, host, updated_at, expires_at, login="jesdi", rest="rounds: 0"):
43
+ return {"id": cid, "user": {"login": login}, "created_at": iso(updated_at),
44
+ "updated_at": iso(updated_at),
45
+ "body": f"<!-- babysit-pr lease: {session} {host} {iso(expires_at)} -->\n{rest}"}
46
+
47
+
48
+ class World:
49
+ def __init__(self, tmp_path, now=T, comments=(), labels=(), hidden=(), pr_risk=True):
50
+ self.project = tmp_path / "project"
51
+ self.home = tmp_path / "home"
52
+ bindir = tmp_path / "bin"
53
+ for d in (self.project, self.home, bindir):
54
+ d.mkdir()
55
+ shutil.copy(FAKE_GH, bindir / "gh")
56
+ (bindir / "gh").chmod(0o755)
57
+ self.script = SCRIPT
58
+ if not pr_risk: # no sibling pr-risk beside the script, no install under HOME
59
+ stage = tmp_path / "stage" / "skills" / "babysit-pr"
60
+ stage.mkdir(parents=True)
61
+ for name in ("babysit.py", "judge-prompt.md"):
62
+ shutil.copy(SCRIPT.parent / name, stage / name)
63
+ self.script = stage / "babysit.py"
64
+ if pr_risk:
65
+ skill = self.home / ".agents" / "skills" / "pr-risk"
66
+ skill.mkdir(parents=True)
67
+ (skill / "SKILL.md").write_text("---\nname: pr-risk\n---\n")
68
+ self.state = tmp_path / "state.json"
69
+ self.log = tmp_path / "log.jsonl"
70
+ self.log.write_text("")
71
+ self.state.write_text(json.dumps({
72
+ "now": iso(now), "user": "jesdi", "comments": list(comments),
73
+ "labels": list(labels), "hidden_until_post": list(hidden), "posted": False,
74
+ "next_id": max([c["id"] for c in comments] + [1000]) + 1}))
75
+ self.env = {**os.environ, "PATH": f"{bindir}{os.pathsep}{os.environ['PATH']}",
76
+ "HOME": str(self.home), "GH_FAKE_STATE": str(self.state),
77
+ "GH_FAKE_LOG": str(self.log)}
78
+
79
+ def run(self, verb, session, repo="jesdi/demo", pr="58"):
80
+ p = subprocess.run(
81
+ [sys.executable, str(self.script), "lease", verb, "--repo", repo, "--pr", pr,
82
+ "--session", session, "--host", "mac2"],
83
+ cwd=self.project, env=self.env, text=True, capture_output=True)
84
+ p.output = p.stdout + p.stderr
85
+ return p
86
+
87
+ def set_now(self, dt):
88
+ st = self.github()
89
+ st["now"] = iso(dt)
90
+ self.state.write_text(json.dumps(st))
91
+
92
+ def github(self):
93
+ return json.loads(self.state.read_text())
94
+
95
+ def comment(self, cid):
96
+ return next(c for c in self.github()["comments"] if c["id"] == cid)
97
+
98
+ def writes(self):
99
+ return [e for e in map(json.loads, self.log.read_text().splitlines()) if e["write"]]
100
+
101
+ def calls(self):
102
+ return [e["argv"] for e in map(json.loads, self.log.read_text().splitlines())]
103
+
104
+ def unsupported(self):
105
+ return [e["argv"] for e in map(json.loads, self.log.read_text().splitlines())
106
+ if e["unsupported"]]
107
+
108
+ def active_leases(self):
109
+ """(id, session, host, expires-at, updated_at) of lease comments not ended."""
110
+ return [(c["id"], *LEASE.search(c["body"]).groups(), c["updated_at"])
111
+ for c in self.github()["comments"]
112
+ if LEASE.search(c["body"]) and "ended" not in c["body"].lower()]
113
+
114
+
115
+ @pytest.mark.parametrize("verb", ["acquire", "renew", "check", "release"])
116
+ def test_without_pr_risk_nothing_runs_and_nothing_is_written(tmp_path, verb):
117
+ w = World(tmp_path, pr_risk=False)
118
+ p = w.run(verb, "s2")
119
+ assert p.returncode != 0
120
+ assert INSTALL in p.output
121
+ assert w.writes() == []
122
+
123
+
124
+ def test_valid_lease_of_another_session_blocks_acquire_without_writes(tmp_path):
125
+ w = World(tmp_path, comments=[lease_comment(1001, "s1", "mac", T - 50 * MIN, T + 40 * MIN)],
126
+ labels=["babysitting"])
127
+ p = w.run("acquire", "s2")
128
+ assert p.returncode != 0
129
+ assert "already babysat by mac" in p.output
130
+ assert w.unsupported() == []
131
+ assert w.writes() == []
132
+
133
+
134
+ def test_expired_lease_is_taken_over_with_expiry_90_minutes_after_github_updated_at(tmp_path):
135
+ now = datetime(2099, 1, 1, 10, 5, tzinfo=timezone.utc)
136
+ w = World(tmp_path, now=now,
137
+ comments=[lease_comment(1001, "s1", "mac", now - 91 * MIN, now - 1 * MIN)])
138
+ p = w.run("acquire", "s2")
139
+ assert p.returncode == 0, p.output
140
+ mine = [l for l in w.active_leases() if l[1] == "s2"]
141
+ assert len(mine) == 1
142
+ _, _, host, expires_at, updated_at = mine[0]
143
+ assert host == "mac2"
144
+ assert parse(updated_at) == now
145
+ assert parse(expires_at) == parse(updated_at) + 90 * MIN
146
+ assert [l for l in w.active_leases() if l[1] == "s1"] == []
147
+ assert w.run("check", "s2").returncode == 0
148
+
149
+
150
+ def test_two_claims_within_one_second_lowest_comment_id_wins(tmp_path):
151
+ t = datetime(2020, 1, 1, 10, 0, 1, tzinfo=timezone.utc)
152
+ # s1's comment 1001 is not visible to s2's first read: s1 posts right after it.
153
+ s1 = lease_comment(1001, "s1", "mac", t, t + 90 * MIN)
154
+ w = World(tmp_path, now=t, comments=[s1], hidden=[1001], labels=["babysitting"])
155
+ p = w.run("acquire", "s2")
156
+ assert p.returncode != 0
157
+ assert w.unsupported() == []
158
+ mine = w.comment(1002)
159
+ assert LEASE.search(mine["body"]) and LEASE.search(mine["body"]).group(1) == "s2"
160
+ assert "ended" in mine["body"].lower()
161
+ assert w.comment(1001) == s1
162
+ assert "babysitting" in w.github()["labels"]
163
+
164
+
165
+ def test_expiry_uses_github_time_not_the_host_clock(tmp_path):
166
+ t10 = datetime(2020, 1, 1, 10, 0, tzinfo=timezone.utc)
167
+ w = World(tmp_path, now=T,
168
+ comments=[lease_comment(1001, "s1", "mac", t10, t10 + 90 * MIN)])
169
+ p = w.run("acquire", "s2")
170
+ assert p.returncode != 0
171
+ assert "already babysat by mac" in p.output
172
+ assert w.writes() == []
173
+
174
+
175
+ def test_check_fails_for_a_session_that_does_not_hold_the_lease(tmp_path):
176
+ w = World(tmp_path, comments=[
177
+ lease_comment(1001, "s2", "mac", T - 5 * MIN, T + 85 * MIN),
178
+ lease_comment(1002, "s1", "mac2", T - 4 * MIN, T + 86 * MIN)])
179
+ p = w.run("check", "s1")
180
+ assert p.returncode != 0
181
+ assert w.writes() == []
182
+ assert w.run("check", "s2").returncode == 0
183
+
184
+
185
+ def test_release_removes_the_label_and_marks_the_lease_ended(tmp_path):
186
+ w = World(tmp_path, comments=[lease_comment(1001, "s1", "mac2", T - 5 * MIN, T + 85 * MIN)],
187
+ labels=["babysitting"])
188
+ p = w.run("release", "s1")
189
+ assert p.returncode == 0, p.output
190
+ assert "babysitting" not in w.github()["labels"]
191
+ assert "ended" in w.comment(1001)["body"].lower()
192
+ assert w.active_leases() == []
193
+ assert w.unsupported() == []
194
+
195
+
196
+ def test_acquire_adds_the_babysitting_label_and_removes_needs_human(tmp_path):
197
+ w = World(tmp_path, labels=["needs-human", "bug"])
198
+ p = w.run("acquire", "s2")
199
+ assert p.returncode == 0, p.output
200
+ assert sorted(w.github()["labels"]) == ["babysitting", "bug"]
201
+ assert [l[1] for l in w.active_leases()] == ["s2"]
202
+ assert w.unsupported() == []
203
+
204
+
205
+ def test_renew_extends_expiry_from_github_time_and_keeps_persisted_state(tmp_path):
206
+ rest = "rounds: 3\nsignature: test_empty AssertionError"
207
+ w = World(tmp_path, comments=[lease_comment(1001, "s1", "mac2", T - 5 * MIN, T + 85 * MIN, rest=rest)],
208
+ labels=["babysitting"])
209
+ w.set_now(T + 60 * MIN)
210
+ p = w.run("renew", "s1")
211
+ assert p.returncode == 0, p.output
212
+ [(cid, session, _, expires_at, updated_at)] = w.active_leases()
213
+ assert (cid, session) == (1001, "s1")
214
+ assert parse(updated_at) == T + 60 * MIN
215
+ assert parse(expires_at) == T + 150 * MIN
216
+ assert rest in w.comment(1001)["body"]
217
+ assert w.unsupported() == []
218
+ w.set_now(T + 120 * MIN) # past the original expiry, within the renewed one
219
+ assert w.run("check", "s1").returncode == 0
220
+
221
+
222
+ def test_renew_by_a_session_that_does_not_hold_the_lease_fails_without_writes(tmp_path):
223
+ w = World(tmp_path, comments=[lease_comment(1001, "s1", "mac", T - 5 * MIN, T + 85 * MIN)])
224
+ p = w.run("renew", "s2")
225
+ assert p.returncode != 0
226
+ assert w.writes() == []
227
+ assert w.comment(1001)["body"] == lease_comment(1001, "s1", "mac", T, T + 85 * MIN)["body"]
228
+
229
+
230
+ @pytest.mark.parametrize("repo,pr", [("jesdi/demo", "58"), ("acme/widgets", "7"), ("other-org/x.y", "1234")])
231
+ def test_every_call_targets_the_requested_repository_and_pr(tmp_path, repo, pr):
232
+ w = World(tmp_path, labels=["needs-human"])
233
+ for verb in ("acquire", "renew", "check", "release"):
234
+ p = w.run(verb, "s2", repo=repo, pr=pr)
235
+ assert p.returncode == 0, p.output
236
+ assert w.unsupported() == []
237
+ targets = [a for argv in w.calls() for a in argv
238
+ if re.search(r"\b(repos|issues|pulls)/", a) or a in ("--repo", "-R")]
239
+ assert targets
240
+ pattern = rf"^/?repos/{re.escape(repo)}/(issues|pulls)/({pr}(/|$)|comments/\d+$)"
241
+ for t in targets:
242
+ assert re.match(pattern, t), t