@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
@@ -0,0 +1,145 @@
1
+ """Acceptance tests for the missing-required-check warning of `babysit.py lease acquire`
2
+ (spec specs/pr-exam, requirement 15, scenario "babysit-pr warns when the check isn't required").
3
+
4
+ Interface under test: `lease acquire` prints one warning naming `pr-exam setup <owner/repo>` when the
5
+ repo is public, exams are enabled (`.pr-exam.json` on origin/<base>) and the default branch's required
6
+ status checks do not include `exam` (as `pr_exam.py setup --check` reads them: the branch `setup`
7
+ protects). `lease renew` and `lease check` print none. No warning when `exam` is required, when the
8
+ repo is private, when exams are disabled, or when the answer is unknown. The warning is advisory: it
9
+ is worked out after the lease lock is released, and never fails or delays the lease.
10
+ `gh` is the fake in fixtures/gh (required_checks, protection, private, protection_error).
11
+ """
12
+ import pytest
13
+
14
+ from test_babysit_judge import git
15
+ from test_exam_request import Exam
16
+
17
+ REPO = "jesdi/general-skills"
18
+ WARNING = f"pr-exam setup {REPO}"
19
+
20
+
21
+ def acquire(tmp_path, name, base_config=None, **github):
22
+ w = Exam(tmp_path / name, base_config=base_config)
23
+ w.env.pop("PR_EXAM_HOST", None)
24
+ w.seed(**github)
25
+ p = w.run("acquire", "s1", repo=REPO)
26
+ assert p.returncode == 0, p.output
27
+ return w, p
28
+
29
+
30
+ @pytest.fixture(autouse=True)
31
+ def dirs(tmp_path):
32
+ for n in ("warn", "quiet", "other"):
33
+ (tmp_path / n).mkdir()
34
+
35
+
36
+ @pytest.mark.parametrize("github", [{"required_checks": ["test"]}, {}],
37
+ ids=["other-checks-required", "unprotected"])
38
+ def test_acquire_warns_once_and_renew_and_check_stay_silent(tmp_path, github):
39
+ w, p = acquire(tmp_path, "warn", private=False, **github)
40
+ assert p.output.count(WARNING) == 1, p.output
41
+ for verb in ("renew", "check"):
42
+ q = w.run(verb, "s1", repo=REPO)
43
+ assert q.returncode == 0, q.output
44
+ assert "pr-exam setup" not in q.output, q.output
45
+
46
+
47
+ def test_no_warning_when_exam_is_required(tmp_path):
48
+ _, control = acquire(tmp_path, "warn", private=False, required_checks=["test"])
49
+ assert WARNING in control.output
50
+ _, p = acquire(tmp_path, "quiet", private=False, required_checks=["test", "exam"])
51
+ assert "pr-exam setup" not in p.output, p.output
52
+
53
+
54
+ def test_no_warning_when_exam_is_required_through_branch_protection(tmp_path):
55
+ _, control = acquire(tmp_path, "warn", private=False)
56
+ assert WARNING in control.output
57
+ protection = {"required_status_checks": {"strict": False, "contexts": ["exam"],
58
+ "checks": [{"context": "exam", "app_id": 424242}]},
59
+ "enforce_admins": {"enabled": True}}
60
+ _, p = acquire(tmp_path, "quiet", private=False, protection=protection)
61
+ assert "pr-exam setup" not in p.output, p.output
62
+
63
+
64
+ def test_no_warning_for_a_private_repo(tmp_path):
65
+ _, control = acquire(tmp_path, "warn", private=False, required_checks=[])
66
+ assert WARNING in control.output
67
+ _, p = acquire(tmp_path, "quiet", private=True, required_checks=[])
68
+ assert "pr-exam setup" not in p.output, p.output
69
+ _, p = acquire(tmp_path, "other", private=True,
70
+ protection_error={"status": 403, "message": "Upgrade to GitHub Pro or make this "
71
+ "repository public."})
72
+ assert "pr-exam setup" not in p.output, p.output
73
+
74
+
75
+ def test_no_warning_when_exams_are_disabled(tmp_path):
76
+ _, control = acquire(tmp_path, "warn", private=False, required_checks=[])
77
+ assert WARNING in control.output
78
+ _, p = acquire(tmp_path, "quiet", base_config='{"enabled": false}', private=False,
79
+ required_checks=[])
80
+ assert "pr-exam setup" not in p.output, p.output
81
+
82
+
83
+ @pytest.mark.parametrize("broken", ["not-fetched", "invalid-config"])
84
+ def test_an_unreadable_base_config_leaves_acquire_silent(tmp_path, broken):
85
+ # the advisory never speaks for `exam`/`merge`, which stop on the same cause with the full message
86
+ w = Exam(tmp_path / "quiet", base_config='{"enabled": "yes"}' if broken == "invalid-config" else None)
87
+ w.env.pop("PR_EXAM_HOST", None)
88
+ w.seed(private=False, required_checks=[])
89
+ if broken == "not-fetched":
90
+ git(w.project, "update-ref", "-d", "refs/remotes/origin/main")
91
+ p = w.run("acquire", "s1", repo=REPO)
92
+ assert p.returncode == 0, p.output
93
+ assert p.stderr == ""
94
+
95
+
96
+ def test_the_default_branch_is_the_one_checked_not_the_prs_base(tmp_path):
97
+ # `setup` protects the default branch: a PR into another branch is told about that one
98
+ _, control = acquire(tmp_path, "warn", private=False, default_branch="trunk", base_ref="main")
99
+ assert WARNING in control.output
100
+ protection = {"required_status_checks": {"strict": False, "contexts": ["exam"],
101
+ "checks": [{"context": "exam", "app_id": 424242}]}}
102
+ _, p = acquire(tmp_path, "quiet", private=False, default_branch="trunk", base_ref="main", protection=protection)
103
+ assert "pr-exam setup" not in p.output, p.output
104
+
105
+
106
+ def test_github_refusing_to_say_leaves_acquire_silent(tmp_path):
107
+ _, p = acquire(tmp_path, "quiet", private=False,
108
+ protection_error={"status": 500, "message": "Server Error"})
109
+ assert p.stderr == "", p.stderr
110
+
111
+
112
+ def test_the_warning_is_worked_out_after_the_lease_lock_is_released(tmp_path):
113
+ """While `setup --check` runs, another session's lease command is not held up."""
114
+ import os, subprocess, sys, time
115
+ w = Exam(tmp_path / "warn")
116
+ w.env.pop("PR_EXAM_HOST", None)
117
+ w.seed(private=False)
118
+ real = w.env["PATH"].split(os.pathsep)[0] + "/gh"
119
+ slow = tmp_path / "slow"
120
+ slow.mkdir()
121
+ gate = tmp_path / "gate"
122
+ (slow / "gh").write_text( # the protection read blocks until the gate file exists
123
+ f"#!{sys.executable}\nimport os, sys, time\n"
124
+ f"if any('protection' in a for a in sys.argv):\n"
125
+ f" open({str(tmp_path / 'reached')!r}, 'w').close()\n"
126
+ f" while not os.path.exists({str(gate)!r}):\n time.sleep(0.05)\n"
127
+ f"os.execv({real!r}, [{real!r}, *sys.argv[1:]])\n")
128
+ (slow / "gh").chmod(0o755)
129
+ env = {**w.env, "PATH": f"{slow}{os.pathsep}{w.env['PATH']}"}
130
+ cmd = [sys.executable, str(w.script), "lease", "{verb}", "--repo", REPO, "--pr", "58", "--session", "s1", "--host", "mac2"]
131
+ first = subprocess.Popen([c.format(verb="acquire") for c in cmd], cwd=w.project, env=env, text=True,
132
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE)
133
+ try:
134
+ deadline = time.time() + 60
135
+ while not (tmp_path / "reached").exists():
136
+ assert time.time() < deadline and first.poll() is None, "acquire never asked for the protection"
137
+ time.sleep(0.05)
138
+ other = subprocess.run([c.format(verb="check") for c in cmd], cwd=w.project, env=w.env, text=True,
139
+ capture_output=True, timeout=60) # would time out if acquire still held the lock
140
+ assert other.returncode == 0, other.stdout + other.stderr
141
+ finally:
142
+ gate.write_text("")
143
+ out, err = first.communicate(timeout=60)
144
+ assert first.returncode == 0, out + err
145
+ assert err.count(WARNING) == 1, err
@@ -0,0 +1,353 @@
1
+ """Acceptance tests for `babysit.py exam --repo R --pr N --wait --session S --host H`.
2
+
3
+ Spec specs/pr-exam, requirement 11 and 13; scenarios "babysit-pr waits for the exam once the PR is
4
+ otherwise ready", "a push while the exam is open replaces it", "a push after a pass adds nothing
5
+ new", "a push after a pass adds a new concept".
6
+
7
+ Interface under test:
8
+ --wait after the request of `exam`, poll GitHub for the head's `exam` commit status, with no
9
+ time limit, and keep the lease of --session/--host alive (`lease renew`) while waiting.
10
+ Real seconds between two polls: $BABYSIT_EXAM_POLL_SECONDS (default 60; tests set 0).
11
+ All time it reads is GitHub's clock (the fake gh `now`), never the host clock.
12
+ exit 0, printing "success" the newest `exam` status the box's GitHub App ($PR_EXAM_APP[bot])
13
+ posted on the head is success, read over every page of the head's
14
+ statuses. A status from anyone else and a host answer never end it.
15
+ exit non-zero, saying why the PR is closed or merged; another session holds the lease
16
+ head moved POST the host again ({"repo", "pr"}) and wait on the new head
17
+ head's `exam` still pending ask the host again whatever it answered last (a job may fail after
18
+ an `open` answer; the contract: "the next request retries"), after
19
+ 2, 4, 8, then every 16 polls; an `error` answer's `detail` is printed
20
+ host unreachable mid-wait one line saying so per request; the wait goes on, same schedule
21
+ (the first request, before --wait, still exits non-zero)
22
+ never prints "CI stalled" for a pending `exam`.
23
+
24
+ Controllable clock: the `gh` first on PATH is a wrapper around fixtures/gh. Every gh call advances
25
+ GitHub's clock by STEP minutes, and a timeline in the state file changes GitHub (head, statuses,
26
+ PR state, lease comment) when the clock reaches a given minute after T. The fake host answers per
27
+ current head, read from the same state file.
28
+ """
29
+ import json
30
+ import re
31
+ import subprocess
32
+ import sys
33
+ from pathlib import Path
34
+
35
+ import pytest
36
+
37
+ sys.path.insert(0, str(Path(__file__).parent / "fixtures"))
38
+ from exam_host import FakeHost # noqa: E402
39
+ from test_babysit import BOT, FAKE_GH, LEASE, MIN, T, iso, lease_comment, parse
40
+ from test_exam_request import Exam
41
+
42
+ STEP = 2 # minutes of GitHub time per gh call
43
+ PENDING = [{"context": "exam", "state": "pending", "creator": BOT}]
44
+ SUCCESS = [{"context": "exam", "state": "success", "description": "passed", "creator": BOT}]
45
+ GREEN_RUN = [{"name": "test", "status": "completed", "conclusion": "success", "started_at": iso(T)}]
46
+
47
+ WRAPPER = '''#!/usr/bin/env python3
48
+ import json, os, sys
49
+ from datetime import datetime, timedelta
50
+ STATE, LOG = os.environ["GH_FAKE_STATE"], os.environ["WAIT_LEASE_LOG"]
51
+ st = json.load(open(STATE))
52
+ fmt = "%Y-%m-%dT%H:%M:%SZ"
53
+ now = datetime.strptime(st["now"], fmt) + timedelta(minutes=int(os.environ["WAIT_STEP"]))
54
+ st["now"] = now.strftime(fmt)
55
+ minutes = (now - datetime.strptime(st["t0"], fmt)).total_seconds() / 60
56
+ for step in st.get("timeline", []):
57
+ if not step.get("done") and minutes >= step["at"]:
58
+ step["done"] = True
59
+ st.update(step["set"])
60
+ for c in step.get("comments", []):
61
+ st["comments"] = [x for x in st["comments"] if x["id"] != c["id"]] + [c]
62
+ json.dump(st, open(STATE, "w"))
63
+ with open(LOG, "a") as f:
64
+ f.write(json.dumps({"minutes": minutes, "now": st["now"], "argv": sys.argv[1:],
65
+ "comments": [c for c in st["comments"]]}) + "\\n")
66
+ os.execv(sys.executable, [sys.executable, os.environ["WAIT_REAL_GH"], *sys.argv[1:]])
67
+ '''
68
+
69
+
70
+ class HeadHost(FakeHost):
71
+ """Answers per current head (read from the fake GitHub state): {head: fields of the answer}."""
72
+
73
+ def __init__(self, state_file, answers):
74
+ self._state_file, self._answers, self.asked = state_file, answers, []
75
+ super().__init__()
76
+
77
+ @property
78
+ def answer(self): # read once per request: `asked` gets GitHub's minute of each one; None while host_down
79
+ st = json.loads(Path(self._state_file).read_text())
80
+ self.asked.append((parse(st["now"]) - T) / MIN)
81
+ if st.get("host_down"):
82
+ return None
83
+ return {**self._base, "head_sha": st["head_sha"], **self._answers.get(st["head_sha"], {})}
84
+
85
+ @answer.setter
86
+ def answer(self, value):
87
+ self._base = value
88
+
89
+
90
+ def world(tmp_path, timeline=(), head="abc123", statuses=None, lease=("s1", "mac"), **kw):
91
+ w = Exam(tmp_path, **kw)
92
+ bindir = tmp_path / "bin"
93
+ (bindir / "gh").write_text(WRAPPER)
94
+ (bindir / "gh").chmod(0o755)
95
+ comments = []
96
+ if lease:
97
+ comments = [lease_comment(1001, lease[0], lease[1], T, T + 90 * MIN)]
98
+ w.seed(head_sha=head, t0=iso(T), comments=comments, next_id=1002, labels=["babysitting"],
99
+ check_runs={h: GREEN_RUN for h in ("abc123", "def456")},
100
+ statuses=statuses if statuses is not None else {head: PENDING},
101
+ timeline=[{"at": at, "set": s, **({"comments": c} if c else {})}
102
+ for at, s, c in ((t + (None,))[:3] if len(t) == 2 else t for t in timeline)])
103
+ w.lease_log = tmp_path / "lease.jsonl"
104
+ w.env.update(WAIT_LEASE_LOG=str(w.lease_log), WAIT_STEP=str(STEP), WAIT_REAL_GH=str(FAKE_GH),
105
+ BABYSIT_EXAM_POLL_SECONDS="0")
106
+ return w
107
+
108
+
109
+ def wait(w, host, session="s1", host_name="mac"):
110
+ env = {**w.env, "PR_EXAM_HOST": host.url}
111
+ try:
112
+ p = subprocess.run([sys.executable, str(w.script), "exam", "--repo", "jesdi/demo", "--pr",
113
+ "58", "--wait", "--session", session, "--host", host_name],
114
+ cwd=w.project, env=env, text=True, capture_output=True, timeout=120)
115
+ except subprocess.TimeoutExpired as e:
116
+ pytest.fail("--wait never ended: " + str(e.stdout)[-500:])
117
+ p.output = p.stdout + p.stderr
118
+ return p
119
+
120
+
121
+ def minutes(w):
122
+ return (parse(w.github()["now"]) - T) / MIN
123
+
124
+
125
+ def holders(snapshot):
126
+ """(session, expires-at) of the lease comments not ended in a gh-call snapshot."""
127
+ out = []
128
+ for c in snapshot["comments"]:
129
+ m = LEASE.search(c["body"])
130
+ if m and "ended" not in c["body"].lower():
131
+ out.append((m.group(1), parse(m.group(3))))
132
+ return out
133
+
134
+
135
+ def snapshots(w):
136
+ return [json.loads(l) for l in w.lease_log.read_text().splitlines()]
137
+
138
+
139
+ def test_a_pending_exam_is_awaited_past_wait_minutes_and_the_lease_stays_this_sessions(tmp_path):
140
+ w = world(tmp_path, timeline=[(150, {"statuses": {"abc123": SUCCESS}})])
141
+ with HeadHost(w.state, {}) as host:
142
+ p = wait(w, host)
143
+ assert p.returncode == 0, p.output
144
+ assert "success" in p.stdout.lower()
145
+ assert "stalled" not in p.output.lower()
146
+ assert minutes(w) >= 150
147
+ for s in snapshots(w):
148
+ if 95 <= s["minutes"] < 150: # past the 90 minutes of the lease taken at minute 0
149
+ now = parse(s["now"])
150
+ assert ("s1", ) in [(h[0],) for h in holders(s) if h[1] > now], \
151
+ f"lease no longer s1's at minute {s['minutes']}: {holders(s)}"
152
+ assert any(s["minutes"] >= 120 for s in snapshots(w))
153
+
154
+
155
+ def test_an_exam_already_successful_on_the_head_ends_the_wait_with_success(tmp_path):
156
+ w = world(tmp_path, statuses={"abc123": SUCCESS})
157
+ with HeadHost(w.state, {"abc123": {"state": "passed", "pending": False}}) as host:
158
+ p = wait(w, host)
159
+ assert p.returncode == 0, p.output
160
+ assert "success" in p.stdout.lower()
161
+
162
+
163
+ def test_the_success_status_ends_the_wait_as_soon_as_it_appears(tmp_path):
164
+ w = world(tmp_path, timeline=[(30, {"statuses": {"abc123": SUCCESS}})])
165
+ with HeadHost(w.state, {}) as host:
166
+ p = wait(w, host)
167
+ assert p.returncode == 0, p.output
168
+ assert "success" in p.stdout.lower()
169
+ assert 30 <= minutes(w) < 60, minutes(w)
170
+
171
+
172
+ def test_a_new_head_while_waiting_sends_a_new_request_and_waits_on_the_new_head(tmp_path):
173
+ w = world(tmp_path, timeline=[
174
+ (20, {"head_sha": "def456", "statuses": {"abc123": PENDING, "def456": []}}),
175
+ (60, {"statuses": {"abc123": PENDING, "def456": SUCCESS}})])
176
+ with HeadHost(w.state, {"abc123": {"state": "open"}, "def456": {"state": "open"}}) as host:
177
+ p = wait(w, host)
178
+ assert p.returncode == 0, p.output
179
+ assert len(host.requests) == 2, host.requests
180
+ assert all(r["path"] == "/api/exam" and r["body"] == {"repo": "jesdi/demo", "pr": 58}
181
+ for r in host.requests)
182
+ assert minutes(w) >= 60 # it waited for the exam on def456, not the old pending one
183
+
184
+
185
+ def test_after_a_pass_a_new_head_the_host_answers_passed_for_ends_the_wait(tmp_path):
186
+ # the host posts success on the head it answers `passed` for (route contract, state table)
187
+ w = world(tmp_path, timeline=[(20, {"head_sha": "def456", "statuses": {"def456": SUCCESS}})])
188
+ with HeadHost(w.state, {"abc123": {"state": "open"},
189
+ "def456": {"state": "passed", "pending": False}}) as host:
190
+ p = wait(w, host)
191
+ assert p.returncode == 0, p.output
192
+ assert "success" in p.stdout.lower()
193
+ assert len(host.requests) == 2, host.requests
194
+ assert minutes(w) < 60, minutes(w)
195
+
196
+
197
+ def test_after_a_pass_a_new_head_the_host_answers_open_for_keeps_waiting(tmp_path):
198
+ w = world(tmp_path, timeline=[
199
+ (20, {"head_sha": "def456", "statuses": {"def456": []}}),
200
+ (60, {"statuses": {"def456": SUCCESS}})])
201
+ with HeadHost(w.state, {"abc123": {"state": "open"},
202
+ "def456": {"state": "open", "detail": "follow-up: retry budget"}}) as host:
203
+ p = wait(w, host)
204
+ assert p.returncode == 0, p.output
205
+ assert len(host.requests) == 2, host.requests
206
+ assert minutes(w) >= 60, minutes(w)
207
+
208
+
209
+ @pytest.mark.parametrize("pr_state", ["closed", "merged"])
210
+ def test_a_closed_or_merged_pr_ends_the_wait_non_zero_saying_so(tmp_path, pr_state):
211
+ w = world(tmp_path, timeline=[(20, {"pr_state": pr_state})])
212
+ with HeadHost(w.state, {}) as host:
213
+ p = wait(w, host)
214
+ assert p.returncode != 0, p.output
215
+ assert pr_state in p.output.lower(), p.output
216
+ assert minutes(w) < 60
217
+
218
+
219
+ def test_another_session_holding_the_lease_at_the_start_ends_the_wait_non_zero(tmp_path):
220
+ w = world(tmp_path, lease=("s2", "mac2"))
221
+ with HeadHost(w.state, {}) as host:
222
+ p = wait(w, host)
223
+ assert p.returncode != 0, p.output
224
+ assert "mac2" in p.output, p.output # names the session's host that holds the lease
225
+ assert "success" not in p.stdout.lower()
226
+
227
+
228
+ def test_another_session_taking_the_lease_over_during_the_wait_ends_it_non_zero(tmp_path):
229
+ stolen = lease_comment(1001, "s2", "mac2", T + 20 * MIN, T + 110 * MIN)
230
+ w = world(tmp_path, timeline=[(20, {}, [stolen])])
231
+ with HeadHost(w.state, {}) as host:
232
+ p = wait(w, host)
233
+ assert p.returncode != 0, p.output
234
+ assert "mac2" in p.output, p.output # names the session's host that holds the lease
235
+ assert minutes(w) < 60, minutes(w)
236
+
237
+
238
+ def test_a_host_error_is_printed_with_its_detail_and_the_wait_goes_on(tmp_path):
239
+ w = world(tmp_path, timeline=[(30, {"statuses": {"abc123": SUCCESS}})])
240
+ err = {"state": "error", "detail": "generation session crashed twice"}
241
+ with HeadHost(w.state, {"abc123": err}) as host:
242
+ p = wait(w, host)
243
+ assert "generation session crashed twice" in p.output, p.output
244
+ assert p.returncode == 0, p.output
245
+ assert minutes(w) >= 30
246
+
247
+
248
+ def test_a_passed_answer_for_an_earlier_head_does_not_end_the_wait(tmp_path):
249
+ w = world(tmp_path, timeline=[(150, {"statuses": {"abc123": SUCCESS}})])
250
+ stale = {"state": "passed", "head_sha": "old999", "pending": False}
251
+ with HeadHost(w.state, {"abc123": stale}) as host:
252
+ p = wait(w, host)
253
+ assert p.returncode == 0, p.output
254
+ assert minutes(w) >= 150, minutes(w) # ended by the status of abc123, not by the answer
255
+
256
+
257
+ def test_a_passed_answer_for_the_head_still_waits_for_its_status(tmp_path):
258
+ w = world(tmp_path, timeline=[(150, {"statuses": {"abc123": SUCCESS}})])
259
+ with HeadHost(w.state, {"abc123": {"state": "passed", "pending": False}}) as host:
260
+ p = wait(w, host)
261
+ assert p.returncode == 0, p.output
262
+ assert minutes(w) >= 150, minutes(w)
263
+
264
+
265
+ def test_success_is_found_behind_more_than_a_page_of_newer_statuses(tmp_path):
266
+ newer = [{"context": f"ci-{i}", "state": "success"} for i in range(35)]
267
+ w = world(tmp_path, statuses={"abc123": newer + SUCCESS})
268
+ with HeadHost(w.state, {}) as host:
269
+ p = wait(w, host)
270
+ assert p.returncode == 0, p.output
271
+ assert "success" in p.stdout.lower()
272
+
273
+
274
+ @pytest.mark.parametrize("creator", ["jesdi", "other-app[bot]", None], ids=["operator", "other-app", "none"])
275
+ def test_an_exam_success_posted_by_anyone_but_the_app_does_not_end_the_wait(tmp_path, creator):
276
+ foreign = {"context": "exam", "state": "success", "description": "passed", "creator": creator}
277
+ w = world(tmp_path, statuses={"abc123": [foreign, *PENDING]}, # newer than the App's pending
278
+ timeline=[(150, {"statuses": {"abc123": [*SUCCESS, foreign, *PENDING]}})])
279
+ with HeadHost(w.state, {}) as host:
280
+ p = wait(w, host)
281
+ assert p.returncode == 0, p.output
282
+ assert minutes(w) >= 150, minutes(w) # ended by the App's success, not the foreign one
283
+
284
+
285
+ class FailsOnce(HeadHost):
286
+ """`error` to the first request, `open` to every later one."""
287
+
288
+ @property
289
+ def answer(self):
290
+ state = {"state": "open"} if len(self.requests) > 1 else {"state": "error", "detail": "session crashed"}
291
+ return {**HeadHost.answer.fget(self), **state}
292
+
293
+ @answer.setter
294
+ def answer(self, value):
295
+ self._base = value
296
+
297
+
298
+ def test_a_pending_exam_is_asked_again_after_2_4_8_then_every_16_polls_whatever_the_answer(tmp_path):
299
+ w = world(tmp_path, timeline=[(1600, {"statuses": {"abc123": SUCCESS}})]) # about 46 polls
300
+ with FailsOnce(w.state, {}) as host:
301
+ p = wait(w, host)
302
+ assert p.returncode == 0, p.output
303
+ assert "session crashed" in p.output
304
+ assert polls_between_requests(w, host) == [2, 4, 8, 16, 16], host.asked # `open` is asked again too
305
+ assert all(r["body"] == {"repo": "jesdi/demo", "pr": 58} for r in host.requests)
306
+
307
+
308
+ def polls_between_requests(w, host):
309
+ """How many polls of the head's status each request came after the one before it."""
310
+ polls = [s["minutes"] for s in snapshots(w)
311
+ if any(a.endswith("/statuses") for a in s["argv"]) and s["minutes"] > host.asked[0]]
312
+ at = [1 + sum(m < r for m in polls) for r in host.asked[1:]]
313
+ return [b - a for a, b in zip([0] + at, at)]
314
+
315
+
316
+ class OpenThenFails(HeadHost):
317
+ """`open` to the first request; the host's job fails afterwards, so `error` to every later one."""
318
+
319
+ @property
320
+ def answer(self):
321
+ state = {"state": "open"} if len(self.requests) == 1 else {"state": "error", "detail": "grading crashed"}
322
+ return {**HeadHost.answer.fget(self), **state}
323
+
324
+ @answer.setter
325
+ def answer(self, value):
326
+ self._base = value
327
+
328
+
329
+ def test_a_job_failing_after_an_open_answer_is_asked_again_and_the_wait_ends_on_success(tmp_path):
330
+ w = world(tmp_path, timeline=[(150, {"statuses": {"abc123": SUCCESS}})])
331
+ with OpenThenFails(w.state, {}) as host:
332
+ p = wait(w, host)
333
+ assert p.returncode == 0, p.output
334
+ assert p.stdout.strip().endswith("success"), p.output
335
+ assert minutes(w) >= 150, minutes(w)
336
+ assert len(host.requests) >= 2, host.requests # the head never moved: the wait itself asked again
337
+ assert "grading crashed" in p.output
338
+ assert all(r["body"] == {"repo": "jesdi/demo", "pr": 58} for r in host.requests)
339
+
340
+
341
+
342
+ def test_a_host_down_for_a_while_mid_wait_neither_ends_the_wait_nor_changes_its_schedule(tmp_path):
343
+ w = world(tmp_path, timeline=[(50, {"host_down": True}), (300, {"host_down": False}),
344
+ (520, {"statuses": {"abc123": SUCCESS}})])
345
+ with HeadHost(w.state, {}) as host:
346
+ p = wait(w, host)
347
+ assert p.returncode == 0, p.output
348
+ assert p.stdout.strip().endswith("success"), p.output
349
+ assert minutes(w) >= 520, minutes(w)
350
+ down = [m for m in host.asked if 50 <= m < 300]
351
+ assert len(down) == 2, host.asked # two re-asks fell while the host was down
352
+ assert sum("unreachable" in line for line in p.output.splitlines()) == len(down), p.output
353
+ assert polls_between_requests(w, host) == [2, 4, 8], host.asked # the same backoff throughout
@@ -31,7 +31,7 @@ import sys
31
31
 
32
32
  import pytest
33
33
 
34
- from test_babysit import SCRIPT, T, World, iso
34
+ from test_babysit import BOT, SCRIPT, T, World, iso
35
35
  from test_babysit_judge import commit as git_commit, git
36
36
 
37
37
  BLOCK = """## Summary
@@ -57,11 +57,15 @@ def commit(sha, message="feat: x", author="jesdi", parents=("p0",)):
57
57
  return {"sha": sha, "date": iso(T), "message": message, "author": author, "parents": list(parents)}
58
58
 
59
59
 
60
- def checkout(w, shas, policy):
60
+ EXAM_OK = {"context": "exam", "state": "success", "description": "passed", "creator": BOT}
61
+
62
+
63
+ def checkout(w, shas, policy, exam_config=None):
61
64
  """A PR checkout: origin/main holds the policy, each sha is a branch named after it (so a fake
62
65
  short sha resolves) that adds one logic file."""
63
66
  git(w.project, "init", "-q", "-b", "work")
64
- base = git_commit(w.project, {"README.md": "hi\n", ".merge-risk.json": json.dumps(policy)}, "base")
67
+ base = git_commit(w.project, {"README.md": "hi\n", ".merge-risk.json": json.dumps(policy),
68
+ **({".pr-exam.json": exam_config} if exam_config else {})}, "base")
65
69
  git(w.project, "update-ref", "refs/remotes/origin/main", base)
66
70
  for sha in shas:
67
71
  git(w.project, "checkout", "-q", "-b", sha, base)
@@ -77,16 +81,18 @@ def owner_says(w, text, login="jesdi"):
77
81
  w.state.write_text(json.dumps(st))
78
82
 
79
83
 
80
- def world(tmp_path, head="a1b2c3d", commits=None, body=BLOCK, policy=None, approvals=(), pr_risk=True, **state):
84
+ def world(tmp_path, head="a1b2c3d", commits=None, body=BLOCK, policy=None, approvals=(), pr_risk=True,
85
+ exam_config=None, **state):
81
86
  w = World(tmp_path, labels=["babysitting"], pr_risk=pr_risk)
82
87
  st = w.github()
83
88
  green = [{"name": "ci", "status": "completed", "conclusion": "success",
84
89
  "created_at": iso(T), "started_at": iso(T)}]
85
90
  st.update(head_sha=head, title="feat: parse empty rows", body=body, # the live PR body is the gated one
86
- commits=commits or [commit(head)], **{"check_runs": {head: green}, "private": True, **state})
91
+ commits=commits or [commit(head)], **{"check_runs": {head: green}, "private": True,
92
+ "statuses": {c["sha"]: [EXAM_OK] for c in commits or [commit(head)]}, **state})
87
93
  w.state.write_text(json.dumps(st))
88
94
  (tmp_path / "body.md").write_text(body)
89
- checkout(w, [c["sha"] for c in st["commits"]], policy or {"maxAutoRisk": 5})
95
+ checkout(w, [c["sha"] for c in st["commits"]], policy or {"maxAutoRisk": 5}, exam_config)
90
96
  if policy: # the same policy also feeds `--policy`, the merge method
91
97
  w.policy_file = tmp_path / "policy.json"
92
98
  w.policy_file.write_text(json.dumps(policy))
@@ -12,7 +12,7 @@ import subprocess
12
12
  import sys
13
13
  from pathlib import Path
14
14
 
15
- from test_babysit import INSTALL, World
15
+ from test_babysit import STAGED, INSTALL, World
16
16
  from test_babysit_judge import Judge, git, commit
17
17
 
18
18
  SKILLS = Path(__file__).resolve().parent.parent
@@ -23,7 +23,7 @@ HERE = Path(__file__).resolve().parent
23
23
  def stage_script(tmp_path):
24
24
  dest = tmp_path / "stage" / "skills" / "babysit-pr"
25
25
  dest.mkdir(parents=True)
26
- for name in ("babysit.py", "judge-prompt.md"):
26
+ for name in STAGED:
27
27
  shutil.copy(HERE / name, dest / name)
28
28
  return dest / "babysit.py"
29
29