@jesdi/skills 0.0.101 → 0.0.103

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 (89) hide show
  1. package/package.json +1 -1
  2. package/skills/babysit-pr/SKILL.md +9 -2
  3. package/skills/babysit-pr/babysit.py +98 -36
  4. package/skills/babysit-pr/exam.py +156 -0
  5. package/skills/babysit-pr/fixtures/exam_host.py +47 -0
  6. package/skills/babysit-pr/fixtures/gh +107 -11
  7. package/skills/babysit-pr/test_babysit.py +8 -2
  8. package/skills/babysit-pr/test_e2e_setup.py +1 -1
  9. package/skills/babysit-pr/test_exam_merge_gate.py +189 -0
  10. package/skills/babysit-pr/test_exam_request.py +337 -0
  11. package/skills/babysit-pr/test_exam_required_check.py +145 -0
  12. package/skills/babysit-pr/test_exam_wait.py +353 -0
  13. package/skills/babysit-pr/test_merge_and_handoff.py +12 -6
  14. package/skills/babysit-pr/test_trusted_merge_risk.py +2 -2
  15. package/skills/pr-exam/SKILL.md +151 -0
  16. package/skills/pr-exam/fixtures/README.md +23 -0
  17. package/skills/pr-exam/fixtures/chat-answer/prompt.md +92 -0
  18. package/skills/pr-exam/fixtures/chat-answer/reply.md +7 -0
  19. package/skills/pr-exam/fixtures/chat-answer/turn.json +1 -0
  20. package/skills/pr-exam/fixtures/delta-new-concept/body.md +9 -0
  21. package/skills/pr-exam/fixtures/delta-new-concept/diff.patch +82 -0
  22. package/skills/pr-exam/fixtures/delta-new-concept/exam.json +46 -0
  23. package/skills/pr-exam/fixtures/delta-new-concept/passed.diff +66 -0
  24. package/skills/pr-exam/fixtures/delta-new-concept/records/0001-single-sync-leader.md +10 -0
  25. package/skills/pr-exam/fixtures/delta-new-concept/records/0002-stale-leader-writes.md +10 -0
  26. package/skills/pr-exam/fixtures/delta-new-concept/records/0003-fencing-token.md +10 -0
  27. package/skills/pr-exam/fixtures/delta-new-concept/records/0004-lease-expiry.md +10 -0
  28. package/skills/pr-exam/fixtures/delta-new-concept/records/0005-injected-monotonic-clock.md +10 -0
  29. package/skills/pr-exam/fixtures/delta-new-concept/records/0006-leader-lifecycle.md +10 -0
  30. package/skills/pr-exam/fixtures/delta-new-concept/records/0007-lease-rollback.md +10 -0
  31. package/skills/pr-exam/fixtures/delta-new-concept/records/0008-sync-blast-radius.md +10 -0
  32. package/skills/pr-exam/fixtures/delta-new-concept/request.json +43 -0
  33. package/skills/pr-exam/fixtures/delta-nothing-new/body.md +9 -0
  34. package/skills/pr-exam/fixtures/delta-nothing-new/diff.patch +66 -0
  35. package/skills/pr-exam/fixtures/delta-nothing-new/exam.json +10 -0
  36. package/skills/pr-exam/fixtures/delta-nothing-new/passed.diff +66 -0
  37. package/skills/pr-exam/fixtures/delta-nothing-new/records/0001-single-sync-leader.md +10 -0
  38. package/skills/pr-exam/fixtures/delta-nothing-new/records/0002-stale-leader-writes.md +10 -0
  39. package/skills/pr-exam/fixtures/delta-nothing-new/records/0003-fencing-token.md +10 -0
  40. package/skills/pr-exam/fixtures/delta-nothing-new/records/0004-lease-expiry.md +10 -0
  41. package/skills/pr-exam/fixtures/delta-nothing-new/records/0005-injected-monotonic-clock.md +10 -0
  42. package/skills/pr-exam/fixtures/delta-nothing-new/records/0006-leader-lifecycle.md +10 -0
  43. package/skills/pr-exam/fixtures/delta-nothing-new/records/0007-lease-rollback.md +10 -0
  44. package/skills/pr-exam/fixtures/delta-nothing-new/records/0008-sync-blast-radius.md +10 -0
  45. package/skills/pr-exam/fixtures/delta-nothing-new/request.json +43 -0
  46. package/skills/pr-exam/fixtures/followup/body.md +9 -0
  47. package/skills/pr-exam/fixtures/followup/diff.patch +66 -0
  48. package/skills/pr-exam/fixtures/followup/exam.json +61 -0
  49. package/skills/pr-exam/fixtures/followup/records/0001-single-sync-leader.md +10 -0
  50. package/skills/pr-exam/fixtures/followup/records/0002-stale-leader-writes.md +10 -0
  51. package/skills/pr-exam/fixtures/followup/records/0003-fencing-token.md +10 -0
  52. package/skills/pr-exam/fixtures/followup/records/0004-lease-expiry.md +10 -0
  53. package/skills/pr-exam/fixtures/followup/records/0005-injected-monotonic-clock.md +10 -0
  54. package/skills/pr-exam/fixtures/followup/records/0006-lease-rollback.md +10 -0
  55. package/skills/pr-exam/fixtures/followup/records/0007-sync-blast-radius.md +10 -0
  56. package/skills/pr-exam/fixtures/followup/request.json +41 -0
  57. package/skills/pr-exam/fixtures/grading/answers.json +5 -0
  58. package/skills/pr-exam/fixtures/grading/attempt.json +10 -0
  59. package/skills/pr-exam/fixtures/grading/grades.json +14 -0
  60. package/skills/pr-exam/fixtures/grading/questions.json +26 -0
  61. package/skills/pr-exam/fixtures/grading/request.json +10 -0
  62. package/skills/pr-exam/fixtures/tip-choice/prompt.md +97 -0
  63. package/skills/pr-exam/fixtures/tip-choice/reply.md +1 -0
  64. package/skills/pr-exam/fixtures/tip-choice/turn.json +1 -0
  65. package/skills/pr-exam/fixtures/tip-text/prompt.md +97 -0
  66. package/skills/pr-exam/fixtures/tip-text/reply.md +1 -0
  67. package/skills/pr-exam/fixtures/tip-text/turn.json +1 -0
  68. package/skills/pr-exam/fixtures/twelve-concepts/body.md +9 -0
  69. package/skills/pr-exam/fixtures/twelve-concepts/diff.patch +66 -0
  70. package/skills/pr-exam/fixtures/twelve-concepts/exam.json +195 -0
  71. package/skills/pr-exam/fixtures/twelve-concepts/request.json +15 -0
  72. package/skills/pr-exam/fixtures/typo-readme/body.md +1 -0
  73. package/skills/pr-exam/fixtures/typo-readme/diff.patch +7 -0
  74. package/skills/pr-exam/fixtures/typo-readme/exam.json +30 -0
  75. package/skills/pr-exam/fixtures/typo-readme/request.json +15 -0
  76. package/skills/pr-exam/pr_exam.py +887 -0
  77. package/skills/pr-exam/test_config.py +83 -0
  78. package/skills/pr-exam/test_context.py +174 -0
  79. package/skills/pr-exam/test_exam_format.py +252 -0
  80. package/skills/pr-exam/test_flag_shapes.py +18 -0
  81. package/skills/pr-exam/test_followup_delta.py +90 -0
  82. package/skills/pr-exam/test_learning_records.py +355 -0
  83. package/skills/pr-exam/test_record_publication.py +45 -0
  84. package/skills/pr-exam/test_scoring.py +287 -0
  85. package/skills/pr-exam/test_served_shapes.py +38 -0
  86. package/skills/pr-exam/test_setup.py +349 -0
  87. package/skills/pr-exam/test_skill_fixtures.py +136 -0
  88. package/skills/pr-exam/test_turn_shapes.py +34 -0
  89. package/skills-manifest.json +9 -3
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jesdi/skills",
3
- "version": "0.0.101",
3
+ "version": "0.0.103",
4
4
  "description": "jesdi's agent skills (content package consumed by @jesdi/skills-cli)",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -21,7 +21,8 @@ Invoking the skill alone, or a hook starting it, does not grant this explicit au
21
21
 
22
22
  ## Before anything
23
23
 
24
- - `pr-risk` must be in `.my-skills/pr-risk`, `.agents/skills/pr-risk`, `.claude/skills/pr-risk` or `~/.my-skills/pr-risk`, in this order. If it is in none, stop and print the install command.
24
+ - `pr-risk` must be installed, in this order: next to this skill; under `~` in `.my-skills`, `.agents/skills`, `.claude/skills` or `.codex/skills`; or committed on `origin/<base>` in one of the first three. A copy inside the PR checkout never counts. If it is in none, stop and print the install command.
25
+ - `PR_EXAM_HOST` and `PR_EXAM_APP` (the slug of the box's GitHub App: only its `exam` status counts) must be set, and `pr-exam` must be installed the same way as `pr-risk`. If one is missing, stop and name it; for `pr-exam`, print the install command.
25
26
  - Codex needs `--profile babysit` (network on). If `gh` cannot reach GitHub, hand off at once with reason `no network for gh`; never wait on an approval prompt.
26
27
  - `lease acquire`. If another session holds it, stop with no comment and no push.
27
28
 
@@ -31,7 +32,13 @@ Invoking the skill alone, or a hook starting it, does not grant this explicit au
31
32
  2. `update-plan --base <base>` when the base moved; follow its plan (see Base moved). Every step uses `origin/<base>` of the PR (a stacked PR's parent), never `main`.
32
33
  3. `checks --wait-minutes <waitMinutes>` until the head is green, red, stalled (`CI stalled`) or empty (`no checks`). Green means every check passed.
33
34
  4. Red: `round start --op <id>` (keep the id), then the fix round below. Renew the lease each round and `lease check` before each push.
34
- 5. Green: with explicit session authorization, use its merge path above. Otherwise, absent an owner commit approval, run the gate (`pr-risk` `merge_risk.py gate`), then `judge`, then `merge-method` and `merge`. Pass the judge's label and risk to `merge --judge agree --judge-risk <risk>` (or `--judge 'same-model agree'` for fallback), never an output file path. The merge pins the head SHA the gate and judge saw, and hands off when the gate's or the judge's risk is above the repo's limit.
35
+ 5. Green: with reviews clear, run `exam` (`python3 babysit.py exam --repo <owner/name> --pr <n>`) before any gate, judge or merge, on every approval path: session authorization, the owner's `@babysitter merge <sha>` comment, and the automatic path. A session never skips it. A pass is not merge approval: it only lets the usual path continue.
36
+ 6. Show the operator the exam link, then wait with `exam --wait`. In Claude Code run it in the background. It has no time limit: never report it as `CI stalled`, and never hand off for waiting.
37
+ 7. Passed: with explicit session authorization, use its merge path above. Otherwise, absent an owner commit approval, run the gate (`pr-risk` `merge_risk.py gate`), then `judge`, then `merge-method` and `merge`. Pass the judge's label and risk to `merge --judge agree --judge-risk <risk>` (or `--judge 'same-model agree'` for fallback), never an output file path. The merge pins the head SHA the gate and judge saw, and hands off when the gate's or the judge's risk is above the repo's limit.
38
+
39
+ If `merge` refuses with `exam not passed`, go back to waiting with `exam --wait`: no handoff. After a push or rebase following a pass, run `exam` again before merging; an earlier pass does not carry over.
40
+
41
+ An agent never applies, removes or re-applies a bypass label, and never posts an `exam` status. Only the repo owner's label counts.
35
42
 
36
43
  ## A fix round
37
44
 
@@ -6,6 +6,7 @@ gh user. Expiry is judged against GitHub's clock (the `Date` header of `gh api -
6
6
  clock. Among valid lease comments the lowest comment id holds the lease; the label is not the lock.
7
7
  """
8
8
  import argparse
9
+ import atexit
9
10
  import fcntl
10
11
  import hashlib
11
12
  import json
@@ -22,10 +23,15 @@ from datetime import datetime, timedelta, timezone
22
23
  from email.utils import parsedate_to_datetime
23
24
  from pathlib import Path
24
25
 
26
+ sys.path.insert(0, str(Path(__file__).resolve().parent)) # the sibling module, ahead of the current directory:
27
+ import exam # noqa: E402 a loader that is not `python babysit.py` may have the PR's checkout first
28
+
25
29
  LEASE = re.compile(r"\A<!-- babysit-pr lease: (\S+) (\S+) (\S+) -->")
26
30
  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")
31
+ SKILL_DIRS = (".my-skills", ".agents/skills", ".claude/skills") # where a skill is installed, under $HOME or a repo
32
+ HOME_SKILL_DIRS = (*SKILL_DIRS, ".codex/skills") # a Codex session on the box sees only its ~/.codex
33
+ PR_RISK = ("pr-risk", ("merge_risk.py", "merge_policy.py")) # a skill and the files babysit-pr runs from it
34
+ PR_EXAM = ("pr-exam", ("pr_exam.py",))
29
35
  CLAIM_PENDING = "<!-- babysit-pr claim: pending -->\n"
30
36
  CLAIM_HELD = "<!-- babysit-pr claim: held -->\n"
31
37
  MAX_ROUNDS = 5
@@ -319,7 +325,8 @@ def ci_state(repo, number, wait):
319
325
  for line in out.splitlines():
320
326
  if line:
321
327
  status = json.loads(line)
322
- latest.setdefault(status["context"], status)
328
+ if status["context"] != exam.CONTEXT: # the exam is asked for after CI: it never gates CI
329
+ latest.setdefault(status["context"], status)
323
330
  reset_terminal_statuses(pr, f"{repo}#{sha}#status:", latest)
324
331
  red = red or any(s["state"] in ("failure", "error") for s in latest.values())
325
332
  pending_runs = [r for r in runs if r["status"] != "completed"]
@@ -380,13 +387,13 @@ def extend(pr, c, session, host, expires, user):
380
387
 
381
388
 
382
389
  def require_pr_risk(repo, number):
383
- if trusted_pr_risk_dirs():
390
+ if trusted_install(*PR_RISK):
384
391
  return
385
392
  if subprocess.run(["git", "rev-parse", "--git-dir"], capture_output=True).returncode == 0:
386
393
  base = gh("api", f"repos/{repo}/pulls/{number}", "--jq", ".base.ref", check=False).strip()
387
- if base and base_install(base):
394
+ if base and trusted_install(*PR_RISK, base):
388
395
  return
389
- fail(f"pr-risk is not installed. Run: {INSTALL}")
396
+ fail(not_installed("pr-risk"))
390
397
 
391
398
 
392
399
  def renew(repo, number, session):
@@ -397,7 +404,9 @@ def renew(repo, number, session):
397
404
  def lease(verb, repo, number, session, host):
398
405
  # Every lease-body writer reads its snapshot inside the same lock as rounds.
399
406
  with locked():
400
- return lease_locked(verb, repo, number, session, host)
407
+ lease_locked(verb, repo, number, session, host)
408
+ if verb == "acquire": # advisory, once per run: outside the lock, it never holds another session up
409
+ warn_exam_not_required(repo, number)
401
410
 
402
411
 
403
412
  def confirmed_leases(comments, user):
@@ -518,6 +527,23 @@ def lease_locked(verb, repo, number, session, host):
518
527
  pr.label(add=["babysitting"], remove=["needs-human"])
519
528
 
520
529
 
530
+ def warn_exam_not_required(repo, number):
531
+ """A public repo with exams on whose default branch does not require `exam`: say how to fix it.
532
+
533
+ Silent whenever the answer is unknown (no fetch yet, an invalid config, no install, GitHub down):
534
+ `exam` and `merge` stop on the same cause with the full message."""
535
+ try:
536
+ base = json.loads(gh("api", f"repos/{repo}/pulls/{number}", check=False))["base"]
537
+ script = pr_exam_script(base["ref"])
538
+ if base["repo"]["private"] is not False or not exam.enabled(base["ref"], script):
539
+ return
540
+ except (ValueError, KeyError, TypeError, exam.ExamError):
541
+ return
542
+ if exam.required(repo, script) is False:
543
+ print(f"warning: `{exam.CONTEXT}` is not a required check on {repo}: run `pr-exam setup {repo}`",
544
+ file=sys.stderr)
545
+
546
+
521
547
  def connection(repo, number, name):
522
548
  """All nodes of one PR connection over GraphQL (REST has no comment `editor`)."""
523
549
  owner, _, repo_name = repo.partition("/")
@@ -608,30 +634,32 @@ def checkout_root():
608
634
  return Path(p.stdout.strip() if p.returncode == 0 else ".").resolve()
609
635
 
610
636
 
611
- def trusted_pr_risk_dirs():
612
- """Installs a PR cannot change: next to this skill, and under $HOME. Never inside the checkout.
637
+ def not_installed(skill):
638
+ return f"{skill} is not installed. Run: npx @jesdi/skills-cli install {skill}"
613
639
 
614
- A path counts only if it, and the module files in it, resolve outside the checkout:
615
- HOME may be the checkout, and a symlink may point into it. A project install is
616
- read from origin/<base> instead.
640
+
641
+ def trusted_install(skill, files, base=None):
642
+ """The folder of an install of `skill` that a PR cannot change, holding `files`; None when there is none.
643
+
644
+ Next to this skill or under $HOME, and only if the folder and its files resolve outside the
645
+ checkout: HOME may be the checkout, and a symlink may point into it. A project install counts
646
+ only as committed on origin/<base>: it is copied out of git into a folder removed at exit.
617
647
  """
618
648
  root = checkout_root()
619
- home = Path.home()
620
649
  outside = lambda p: not p.resolve().is_relative_to(root)
621
- return [d.resolve() for d in [Path(__file__).resolve().parent.parent / "pr-risk",
622
- *(home / n for n in PR_RISK_DIRS)]
623
- if d.is_dir() and outside(d)
624
- and all((d / n).is_file() and outside(d / n) for n in ("merge_risk.py", "merge_policy.py"))]
625
-
626
-
627
- def base_install(base):
628
- """[(file name, bytes)] of a pr-risk install committed on origin/<base>, else None."""
629
- names = ("merge_risk.py", "merge_policy.py")
630
- for d in PR_RISK_DIRS: # a project install counts only as committed on origin/<base>
631
- shown = [subprocess.run(["git", "show", f"origin/{base}:{d}/{n}"], capture_output=True)
632
- for n in names]
650
+ for d in [Path(__file__).resolve().parent.parent / skill, *(Path.home() / s / skill for s in HOME_SKILL_DIRS)]:
651
+ if d.is_dir() and outside(d) and all((d / n).is_file() and outside(d / n) for n in files):
652
+ return d.resolve()
653
+ for s in SKILL_DIRS if base else ():
654
+ shown = [subprocess.run(["git", "show", f"origin/{base}:{s}/{skill}/{n}"], capture_output=True)
655
+ for n in files]
633
656
  if all(p.returncode == 0 for p in shown):
634
- return [(n, p.stdout) for n, p in zip(names, shown)]
657
+ tmp = Path(tempfile.mkdtemp(prefix=f"babysit-{skill}-", dir="/tmp")) # never TMPDIR: it may be the checkout
658
+ atexit.register(shutil.rmtree, tmp, ignore_errors=True)
659
+ for n, p in zip(files, shown):
660
+ (tmp / n).write_bytes(p.stdout)
661
+ return tmp
662
+ return None
635
663
 
636
664
 
637
665
  def import_merge_risk(folder):
@@ -648,16 +676,32 @@ def import_merge_risk(folder):
648
676
 
649
677
 
650
678
  def load_merge_risk(base=None):
651
- for d in trusted_pr_risk_dirs():
652
- if (d / "merge_risk.py").is_file():
653
- return import_merge_risk(d)
654
- files = base_install(base) if base else None
655
- if files:
656
- with tempfile.TemporaryDirectory(prefix="babysit-pr-risk-", dir="/tmp") as tmp:
657
- for n, data in files:
658
- (Path(tmp) / n).write_bytes(data)
659
- return import_merge_risk(tmp)
660
- fail(f"pr-risk is not installed. Run: {INSTALL}")
679
+ folder = trusted_install(*PR_RISK, base)
680
+ if folder is None:
681
+ fail(not_installed("pr-risk"))
682
+ return import_merge_risk(folder)
683
+
684
+
685
+ def pr_exam_script(base):
686
+ """The trusted pr_exam.py, or None when pr-exam is not installed."""
687
+ folder = trusted_install(*PR_EXAM, base)
688
+ return folder / "pr_exam.py" if folder else None
689
+
690
+
691
+ def exam_cmd(repo, number, wait=False, session=None, lease_host=None):
692
+ info = json.loads(gh("api", f"repos/{repo}/pulls/{number}"))
693
+ try:
694
+ if not exam.enabled(info["base"]["ref"], pr_exam_script(info["base"]["ref"])):
695
+ return print("exams are disabled for this repo")
696
+ exam.host(), exam.app() # not configured: stop before asking GitHub anything more
697
+ if ci_state(repo, number, 60) != "green" or owner_comments(repo, number)["handoff"]:
698
+ return print("the PR is not ready: CI is not green or a review is open")
699
+ exam.request(repo, number)
700
+ if wait: # `check` names the holder when it is not us
701
+ keep_lease = lambda: [lease(verb, repo, number, session, lease_host) for verb in ("check", "renew")]
702
+ exam.wait(repo, number, info["head"]["sha"], keep_lease)
703
+ except exam.ExamError as e:
704
+ fail(e)
661
705
 
662
706
 
663
707
  JUDGE_NEEDS = ("base_policy", "classify_diff", "diff_stats", "FENCE")
@@ -869,6 +913,12 @@ def merge_cmd(repo, number, sha, body_file, policy, judge_label, approved, sessi
869
913
 
870
914
  if pr["head"]["sha"] != sha:
871
915
  fail(f"head moved to {pr['head']['sha']} since the gate saw {sha}: gate again")
916
+ try: # every approval path needs the pass of this exact sha; a refusal is no handoff
917
+ exams = exam.enabled(base, pr_exam_script(base))
918
+ if exams and not exam.passed(repo, sha):
919
+ fail("exam not passed")
920
+ except exam.ExamError as e:
921
+ fail(e)
872
922
  if session_approved:
873
923
  own_lease(repo, number, session)
874
924
  gate = "gate: explicit session authorization"
@@ -946,6 +996,8 @@ def merge_cmd(repo, number, sha, body_file, policy, judge_label, approved, sessi
946
996
  pr.post("🤖 Merged by babysit-pr: " + (
947
997
  f"session {session} authorized merge at {sha}" if session_approved else
948
998
  f"{risk_line}gate passed, judge {judge_label}" if approved is None else f"owner approved {approved}"))
999
+ if exams:
1000
+ exam.notify_merged(repo, number)
949
1001
  if session:
950
1002
  release(pr, session)
951
1003
 
@@ -964,6 +1016,12 @@ def main():
964
1016
  cp.add_argument("--repo", required=True)
965
1017
  cp.add_argument("--pr", required=True)
966
1018
  cp.add_argument("--wait-minutes", type=int, required=True)
1019
+ xp = sub.add_parser("exam")
1020
+ xp.add_argument("--repo", required=True)
1021
+ xp.add_argument("--pr", required=True)
1022
+ xp.add_argument("--wait", action="store_true")
1023
+ xp.add_argument("--session")
1024
+ xp.add_argument("--host", help="lease host")
967
1025
  rp = sub.add_parser("round")
968
1026
  rp.add_argument("verb", choices=["start", "record-failure"])
969
1027
  for a in ("repo", "pr", "session", "host"):
@@ -1003,6 +1061,10 @@ def main():
1003
1061
  print(json.dumps(owner_comments(a.repo, a.pr)))
1004
1062
  elif a.cmd == "checks":
1005
1063
  checks_cmd(a.repo, a.pr, a.wait_minutes)
1064
+ elif a.cmd == "exam":
1065
+ if a.wait and not (a.session and a.host):
1066
+ ap.error("--wait needs --session and --host")
1067
+ exam_cmd(a.repo, a.pr, a.wait, a.session, a.host)
1006
1068
  elif a.cmd == "round":
1007
1069
  if a.verb == "record-failure" and not (a.check and a.error):
1008
1070
  ap.error("record-failure needs --check and --error")
@@ -0,0 +1,156 @@
1
+ """babysit-pr's side of the PR exam: whether exams are on, the host's route, the `exam` commit status.
2
+
3
+ babysit-pr is a client: it sends a repo and a PR number, and reads the `exam` status of a commit. It
4
+ never generates, grades or decides a bypass. This module knows nothing of leases or rounds; every
5
+ failure is an ExamError, and the caller decides whether it stops the run.
6
+ """
7
+ import http.client
8
+ import json
9
+ import os
10
+ import subprocess
11
+ import sys
12
+ import tempfile
13
+ import time
14
+ import urllib.request
15
+
16
+ CONTEXT = "exam" # the commit status the host posts
17
+
18
+
19
+ class ExamError(Exception):
20
+ """Why the exam cannot go on. The message is for the user."""
21
+
22
+
23
+ def gh_api(*args):
24
+ p = subprocess.run(["gh", "api", *args], text=True, capture_output=True)
25
+ if p.returncode:
26
+ raise ExamError(f"gh api {' '.join(args)} failed: {p.stderr.strip()}")
27
+ return p.stdout
28
+
29
+
30
+ def validated(config, script, base):
31
+ """`config` as the trusted pr_exam.py reads it; an invalid file is never read as "exams off"."""
32
+ with tempfile.NamedTemporaryFile("w", suffix=".json", dir="/tmp") as f: # never TMPDIR: it may be the checkout
33
+ f.write(config)
34
+ f.flush()
35
+ p = subprocess.run([sys.executable, "-I", str(script), "config", f.name], capture_output=True, text=True)
36
+ if p.returncode:
37
+ raise ExamError(f".pr-exam.json on origin/{base} is invalid:\n{p.stderr.strip()}")
38
+ return json.loads(p.stdout)
39
+
40
+
41
+ def enabled(base, script):
42
+ """Whether exams run for the repo, from `.pr-exam.json` on origin/<base>. A config only on the PR
43
+ branch never counts.
44
+
45
+ `script` is a trusted pr_exam.py, or None when there is none. It alone reads the config, so
46
+ without it the run stops, whatever the file says (`"enabled": false` included).
47
+ """
48
+ known = subprocess.run(["git", "rev-parse", "--verify", "-q", f"origin/{base}^{{commit}}"], capture_output=True)
49
+ if known.returncode:
50
+ raise ExamError(f"origin/{base} is not readable: run git fetch origin")
51
+ if script is None:
52
+ raise ExamError("pr-exam is not installed. Run: npx @jesdi/skills-cli install pr-exam")
53
+ shown = subprocess.run(["git", "show", f"origin/{base}:.pr-exam.json"], capture_output=True, text=True)
54
+ return shown.returncode != 0 or validated(shown.stdout, script, base)["enabled"]
55
+
56
+
57
+ def required(repo, script):
58
+ """Whether `exam` is a required check of the repo's default branch, as the trusted pr_exam.py reads
59
+ GitHub (`setup --check`); None when it could not tell."""
60
+ p = subprocess.run([sys.executable, "-I", str(script), "setup", "--check", repo], capture_output=True, text=True)
61
+ try:
62
+ return json.loads(p.stdout)["required"] if p.returncode == 0 else None
63
+ except (ValueError, KeyError, TypeError):
64
+ return None
65
+
66
+
67
+ def host():
68
+ url = os.environ.get("PR_EXAM_HOST")
69
+ if not url:
70
+ raise ExamError("PR_EXAM_HOST is not set: point it at the pr-exam host")
71
+ return url.rstrip("/")
72
+
73
+
74
+ def app():
75
+ """The login of the box's GitHub App, `<PR_EXAM_APP>[bot]`: the only creator whose `exam` counts.
76
+ Read from the environment, never from the host, so the merge gate works while the box is down."""
77
+ slug = os.environ.get("PR_EXAM_APP")
78
+ if not slug:
79
+ raise ExamError("PR_EXAM_APP is not set: set it to the slug of the pr-exam host's GitHub App")
80
+ return f"{slug}[bot]"
81
+
82
+
83
+ def by_app(status, login):
84
+ """Whether the App posted `status`. A missing or unexpected creator never counts."""
85
+ creator = status.get("creator")
86
+ return isinstance(creator, dict) and creator.get("type") == "Bot" and creator.get("login") == login
87
+
88
+
89
+ def post(repo, number):
90
+ """The one call babysit-pr makes, `POST /api/exam` with {repo, pr}: "bring this PR's exam in line with GitHub"."""
91
+ req = urllib.request.Request(host() + "/api/exam", method="POST", headers={"Content-Type": "application/json"},
92
+ data=json.dumps({"repo": repo, "pr": int(number)}).encode())
93
+ try:
94
+ with urllib.request.urlopen(req, timeout=30) as r:
95
+ return json.load(r)
96
+ except (OSError, ValueError, http.client.HTTPException) as e:
97
+ raise ExamError(f"pr-exam host unreachable at {host()}: {e}") from None
98
+
99
+
100
+ def request(repo, number):
101
+ """Ask the host for the PR's exam and print what it answers."""
102
+ answer = post(repo, number)
103
+ print(json.dumps({k: answer.get(k) for k in ("url", "state", "debt", "detail")}), flush=True)
104
+ if answer.get("state") == "skipped":
105
+ print("exam bypassed")
106
+ elif answer.get("debt"):
107
+ print("exam deferred")
108
+ return answer
109
+
110
+
111
+ def notify_merged(repo, number):
112
+ """Best effort after a merge: the host cleans up at once. Its sweep catches a call that failed."""
113
+ try:
114
+ post(repo, number)
115
+ except ExamError:
116
+ pass
117
+
118
+
119
+ def passed(repo, sha):
120
+ """Whether the newest `exam` commit status the App posted on `sha` is success, read over every
121
+ page. Agents on the Mac share the operator's login, so a status from anyone else is ignored."""
122
+ login = app()
123
+ out = gh_api("--paginate", f"repos/{repo}/commits/{sha}/statuses", "--jq", ".[] | tojson")
124
+ latest = next((st for st in map(json.loads, out.splitlines())
125
+ if st["context"] == CONTEXT and by_app(st, login)), None)
126
+ return latest is not None and latest["state"] == "success"
127
+
128
+
129
+ def wait(repo, number, head, keep_lease):
130
+ """Block until the head's `exam` status is success. No time limit; `keep_lease()` runs on every poll.
131
+
132
+ A host answer never ends the wait: it may be about an earlier head. A head that moved is requested
133
+ again at once. While the status stays pending the host is asked again 2, 4, 8, then every 16
134
+ polls after the last request, whatever it answered: a job that fails after an `open` answer is
135
+ retried by the host only when asked again. A host that cannot be reached then is said once per
136
+ request and the wait goes on, on the same schedule.
137
+ """
138
+ pull = lambda: json.loads(gh_api(f"repos/{repo}/pulls/{number}"))
139
+ asks, polls = 1, 0 # requests for this head; polls since the last one
140
+ while True:
141
+ pr = pull()
142
+ if pr.get("merged") or pr["state"] != "open":
143
+ raise ExamError(f"PR {number} is {'merged' if pr.get('merged') else pr['state']}")
144
+ keep_lease()
145
+ sha = pull()["head"]["sha"] # it may have moved while the lease was renewed
146
+ polls += 1
147
+ if sha != head or polls >= min(2 ** asks, 16):
148
+ asks = 1 if sha != head else asks + 1
149
+ try:
150
+ request(repo, number)
151
+ except ExamError as e:
152
+ print(e, flush=True)
153
+ head, polls = sha, 0
154
+ if passed(repo, sha):
155
+ return print("success")
156
+ time.sleep(float(os.environ.get("BABYSIT_EXAM_POLL_SECONDS", "60")))
@@ -0,0 +1,47 @@
1
+ """Fake pr-exam host for babysit-pr tests: `POST /api/exam`, as in agent-ops
2
+ specs/pr-exam-host/design.md "Route contract". Answers every POST with `answer` (200) and records
3
+ each request as {"path", "body"} in `requests`. An `answer` of None drops the connection unanswered,
4
+ as a host that is down.
5
+
6
+ with FakeHost({"state": "open", ...}) as host: # host.url is the PR_EXAM_HOST value
7
+ """
8
+ import json
9
+ import threading
10
+ from http.server import BaseHTTPRequestHandler, HTTPServer
11
+
12
+
13
+ class FakeHost:
14
+ def __init__(self, answer=None):
15
+ self.answer = {"repo": "jesdi/demo", "pr": 58, "url": "https://box.example.ts.net/exam/jesdi/demo/58",
16
+ "state": "open", "head_sha": "head1", "debt": False,
17
+ "detail": "attempt 1, 5 questions", "pending": True, **(answer or {})}
18
+ self.requests = []
19
+ host = self
20
+
21
+ class Handler(BaseHTTPRequestHandler):
22
+ def do_POST(self):
23
+ body = self.rfile.read(int(self.headers.get("Content-Length") or 0))
24
+ host.requests.append({"path": self.path, "body": json.loads(body or b"null")})
25
+ answer = host.answer
26
+ if answer is None:
27
+ return
28
+ data = json.dumps(answer).encode()
29
+ self.send_response(200)
30
+ self.send_header("Content-Type", "application/json")
31
+ self.send_header("Content-Length", str(len(data)))
32
+ self.end_headers()
33
+ self.wfile.write(data)
34
+
35
+ def log_message(self, *args):
36
+ pass
37
+
38
+ self.server = HTTPServer(("127.0.0.1", 0), Handler)
39
+ self.url = f"http://127.0.0.1:{self.server.server_port}"
40
+
41
+ def __enter__(self):
42
+ threading.Thread(target=self.server.serve_forever, daemon=True).start()
43
+ return self
44
+
45
+ def __exit__(self, *exc):
46
+ self.server.shutdown()
47
+ self.server.server_close()
@@ -10,9 +10,31 @@ State is the JSON file $GH_FAKE_STATE:
10
10
  repo_labels [name] labels that exist in the repository (optional; when set, assigning a label
11
11
  that is not in it fails 422 like GitHub, and `POST repos/O/R/labels -f name=X` creates it)
12
12
  head_sha head commit of every PR (default "head1")
13
+ pr_state "open" (default), "closed" or "merged": the PR's REST `state` ("closed" when merged)
14
+ and `merged`, and `gh pr view`'s upper-case `state`
13
15
  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
+ statuses {sha: [{context, state, creator}]} newest first; commits/SHA/statuses is [] when unseeded
17
+ (only the first 30 without --paginate, like GitHub's default page). `creator` is a login
18
+ and is served as GitHub's user object: an App posts as "<slug>[bot]", type "Bot",
19
+ anyone else as type "User"; without it, creator is null
20
+ required_checks [name] returned as branch protection contexts of the default branch
21
+ private, default_branch visibility (default public) and default branch (default "main") of the repo
22
+ protection branch protection of the default branch in GitHub's response shape (absent: 404
23
+ "Branch not protected"; derived from required_checks when that is set; its
24
+ required_status_checks null: 404 "Required status checks not enabled" for that
25
+ sub-resource). Writes, like GitHub:
26
+ `PATCH branches/B/protection/required_status_checks --input -` changes only that
27
+ sub-resource: `strict` and `checks` [{context, app_id}] when given; an app_id of -1 is
28
+ stored as null ("any app"), null is refused 422. On a protected branch with status checks
29
+ off it turns them on, unless patch_needs_checks is set: then 404.
30
+ `POST branches/B/protection/required_status_checks/contexts --input -` adds contexts
31
+ bound to no app, turning status checks on.
32
+ `PUT branches/B/protection --input -` replaces everything: the body must hold
33
+ required_status_checks, enforce_admins, required_pull_request_reviews and restrictions;
34
+ a boolean setting the body omits is reset to disabled.
35
+ protection_error {status, message}: every branch protection call fails like gh ("gh: <message>
36
+ (HTTP <status>)"); put_error the same for the writes only
37
+ puts bodies of the successful branch protection PUTs
16
38
  reviews [{id, user: {login}, state, body, submitted_at}] (optional)
17
39
  commits [{sha, date}] oldest first, date = commit time (optional)
18
40
  threads [{user: {login}, resolved}] review threads (optional)
@@ -33,7 +55,7 @@ State is the JSON file $GH_FAKE_STATE:
33
55
  Every call is appended to $GH_FAKE_LOG as one JSON line {argv, write, unsupported}.
34
56
  Supported: `gh api` (user, pulls/N/reviews, pulls/N/comments (review comments, always empty),
35
57
  pulls/N/commits, pulls (open list), `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,
36
- 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`.
58
+ issues/N/labels[/NAME], commits/SHA/check-runs, commits/SHA/statuses, branches/B/protection[/required_status_checks[/contexts]]; -X, -f/-F, --input, --jq, --paginate, -i), `gh pr|issue view|comment|edit`.
37
59
  """
38
60
  import json
39
61
  import os
@@ -95,6 +117,16 @@ def emit(obj, jq, include=False):
95
117
  print(json.dumps(obj))
96
118
 
97
119
 
120
+ def user(login):
121
+ """GitHub's user object for `login`, as a status's `creator`; None stays null."""
122
+ if login is None:
123
+ return None
124
+ bot = login.endswith("[bot]")
125
+ return {"login": login, "id": 40209326 if bot else 1000, "type": "Bot" if bot else "User",
126
+ "site_admin": False, "url": f"https://api.github.com/users/{login.replace('[', '%5B').replace(']', '%5D')}",
127
+ "html_url": f"https://github.com/apps/{login[:-5]}" if bot else f"https://github.com/{login}"}
128
+
129
+
98
130
  def labels_obj():
99
131
  return [{"name": n} for n in st["labels"]]
100
132
 
@@ -151,7 +183,9 @@ def api(args):
151
183
  log(False); return emit({"login": st["user"]}, jq, include)
152
184
  if m := re.fullmatch(rf"(?:issues|pulls)/{n}", path) and method == "GET":
153
185
  log(False)
154
- return emit({"number": int(path.split("/")[1]), "state": "open", "labels": labels_obj(),
186
+ pr_state = st.get("pr_state", "open")
187
+ return emit({"number": int(path.split("/")[1]), "state": "open" if pr_state == "open" else "closed",
188
+ "merged": pr_state == "merged", "labels": labels_obj(),
155
189
  "user": {"login": st["user"]},
156
190
  "title": st.get("title", ""), "body": st.get("body", ""),
157
191
  "head": {"sha": st.get("head_sha", "head1"), "ref": st.get("head_ref", "feature")},
@@ -163,8 +197,10 @@ def api(args):
163
197
  if fields.get("base") in (None, p["base"])], jq, include)
164
198
  if re.fullmatch(r"repos/[^/]+/[^/]+", path) and method == "GET":
165
199
  log(False)
166
- return emit(st.get("repo_settings", {"allow_rebase_merge": True, "allow_merge_commit": True,
167
- "allow_squash_merge": False}), jq, include)
200
+ return emit({**st.get("repo_settings", {"allow_rebase_merge": True, "allow_merge_commit": True,
201
+ "allow_squash_merge": False}),
202
+ "private": st.get("private", False),
203
+ "default_branch": st.get("default_branch", "main")}, jq, include)
168
204
  if re.fullmatch(rf"pulls/{n}/reviews", path) and method == "GET":
169
205
  log(False)
170
206
  return emit([{"id": r["id"], "user": r["user"], "state": r["state"], "body": r.get("body", ""),
@@ -214,10 +250,70 @@ def api(args):
214
250
  return emit({"total_count": len(runs), "check_runs": runs}, jq, include)
215
251
  if m := re.fullmatch(r"commits/([^/]+)/statuses", path):
216
252
  log(False)
217
- return emit(st.get("statuses", {}).get(m.group(1), []), jq, include)
218
- if re.fullmatch(r"branches/[^/]+/protection/required_status_checks", path):
219
- log(False)
220
- return emit({"strict": False, "contexts": st.get("required_checks", [])}, jq, include)
253
+ found = [{**s, "creator": user(s.get("creator"))} for s in st.get("statuses", {}).get(m.group(1), [])]
254
+ return emit(found if "--paginate" in args else found[:30], jq, include) # GitHub's page: 30
255
+ if m := re.fullmatch(r"branches/([^/]+)/protection(/required_status_checks(/contexts)?)?", path):
256
+ write = method != "GET"
257
+ def refuse(message, status=404):
258
+ log(write); print(f"gh: {message} (HTTP {status})", file=sys.stderr); sys.exit(1)
259
+ err = st.get("protection_error") or (write and st.get("put_error"))
260
+ if err:
261
+ refuse(err["message"], err["status"])
262
+ if m.group(1) != st.get("default_branch", "main"):
263
+ refuse("Branch not found")
264
+ prot = st.get("protection")
265
+ if prot is None and "required_checks" in st:
266
+ prot = {"required_status_checks": {"strict": False, "contexts": st["required_checks"],
267
+ "checks": [{"context": c, "app_id": None}
268
+ for c in st["required_checks"]]}}
269
+ def checks_of(given):
270
+ if any(c.get("app_id", -1) is None for c in given):
271
+ refuse("Invalid request. For 'properties/app_id', nil is not an integer.", 422)
272
+ return [{"context": c["context"], "app_id": None if c.get("app_id", -1) == -1 else c["app_id"]}
273
+ for c in given]
274
+ def store(rsc):
275
+ rsc["contexts"] = [c["context"] for c in rsc["checks"]]
276
+ prot["required_status_checks"] = rsc
277
+ log(True); st["protection"] = prot; save()
278
+ return emit(rsc, jq, include)
279
+ if m.group(2) and prot is None:
280
+ refuse("Branch not protected")
281
+ if method == "GET":
282
+ if prot is None:
283
+ refuse("Branch not protected")
284
+ if m.group(2) and prot["required_status_checks"] is None:
285
+ refuse("Required status checks not enabled")
286
+ log(False)
287
+ return emit(prot["required_status_checks"] if m.group(2) else prot, jq, include)
288
+ rsc = prot["required_status_checks"] if prot else None
289
+ if method == "PATCH" and m.group(2) and not m.group(3):
290
+ if rsc is None and st.get("patch_needs_checks"):
291
+ refuse("Required status checks not enabled")
292
+ rsc = rsc or {"strict": False, "checks": []}
293
+ return store({"strict": bool(fields.get("strict", rsc["strict"])),
294
+ "checks": checks_of(fields["checks"]) if "checks" in fields else rsc["checks"]})
295
+ if method == "POST" and m.group(3):
296
+ rsc = rsc or {"strict": False, "checks": []}
297
+ new = [{"context": c, "app_id": None} for c in fields.get("contexts", [])
298
+ if c not in [x["context"] for x in rsc["checks"]]]
299
+ return store({"strict": rsc["strict"], "checks": rsc["checks"] + new})
300
+ if method == "PUT" and not m.group(2):
301
+ missing = [k for k in ("required_status_checks", "enforce_admins",
302
+ "required_pull_request_reviews", "restrictions") if k not in fields]
303
+ if missing:
304
+ die(f"HTTP 422: Invalid request, missing {missing}", True)
305
+ rsc = fields["required_status_checks"] or {"strict": False, "checks": []}
306
+ checks = checks_of(rsc.get("checks", []))
307
+ prot = {"required_status_checks": {"strict": bool(rsc.get("strict")), "checks": checks,
308
+ "contexts": [c["context"] for c in checks]},
309
+ "enforce_admins": {"enabled": bool(fields["enforce_admins"])},
310
+ "required_pull_request_reviews": fields["required_pull_request_reviews"],
311
+ "restrictions": fields["restrictions"]}
312
+ for k in ("required_linear_history", "allow_force_pushes", "allow_deletions", "block_creations",
313
+ "required_conversation_resolution", "lock_branch", "allow_fork_syncing"):
314
+ prot[k] = {"enabled": bool(fields.get(k))}
315
+ log(True); st["protection"] = prot; st.setdefault("puts", []).append(fields); save()
316
+ return emit(prot, jq, include)
221
317
  if re.fullmatch(rf"issues/{n}/comments", path):
222
318
  if method == "GET":
223
319
  log(False); return emit(visible(), jq, include)
@@ -276,7 +372,7 @@ def pr_like(args):
276
372
  comments = [{"id": str(c["id"]), "body": c["body"], "author": c["user"],
277
373
  "createdAt": c["created_at"], "updatedAt": c["updated_at"]} for c in visible()]
278
374
  log(False)
279
- return emit({"labels": labels_obj(), "comments": comments, "state": "OPEN",
375
+ return emit({"labels": labels_obj(), "comments": comments, "state": st.get("pr_state", "open").upper(),
280
376
  "title": st.get("title", ""), "body": st.get("body", ""),
281
377
  "headRefOid": st.get("head_sha", "head1")}, jq)
282
378
  if verb == "merge":