@jesdi/skills 0.0.63 → 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 (54) 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/README.md +1 -1
  35. package/skills/implement-spec/SKILL.md +1 -1
  36. package/skills/implement-spec/driver_final.py +49 -10
  37. package/skills/implement-spec/prompts/pr-writer.md +3 -2
  38. package/skills/implement-spec/tests/test_final.py +112 -1
  39. package/skills/implement-spec/tests/test_tidy.py +2 -2
  40. package/skills/implement-spec/tests/test_walk.py +2 -2
  41. package/skills/pr-risk/SKILL.md +33 -0
  42. package/skills/pr-risk/hooks/pre-pr-create.sh +274 -0
  43. package/skills/pr-risk/hooks.json +10 -0
  44. package/skills/pr-risk/merge_policy.py +81 -0
  45. package/skills/pr-risk/merge_risk.py +314 -0
  46. package/skills/pr-risk/test_hook_commands.py +47 -0
  47. package/skills/pr-risk/test_hook_heredoc.py +16 -0
  48. package/skills/pr-risk/test_hook_substitution.py +40 -0
  49. package/skills/pr-risk/test_hooks.py +175 -0
  50. package/skills/pr-risk/test_merge_risk.py +97 -0
  51. package/skills/pr-risk/test_merge_risk_gate.py +217 -0
  52. package/skills/pr-risk/test_merge_risk_regressions.py +37 -0
  53. package/skills/pr-risk/test_merge_risk_structure.py +101 -0
  54. package/skills-manifest.json +15 -3
@@ -0,0 +1,260 @@
1
+ """Acceptance tests for `babysit.py merge-method|merge|handoff`.
2
+
3
+ Interface under test (defined here):
4
+ babysit.py merge-method --repo R --pr N [--policy FILE]
5
+ stdout: {"method": "rebase" | "merge" | "squash"}. FILE is the policy `.merge-risk.json`.
6
+ babysit.py merge --repo R --pr N --sha SHA --body FILE [--policy FILE]
7
+ [--judge "agree" | "same-model agree"] [--approved-sha PREFIX]
8
+ SHA is the head the gate (and judge) saw. BODY is the PR body (summary + merge-risk block).
9
+ Run in a checkout with `origin/<base>` (--base, default `main`) and SHA as a commit: the gate
10
+ is recomputed for SHA with the trusted merge_risk and the policy committed on origin/<base>.
11
+ --judge agree merges only when that gate is auto; else it hands off with the gate's reasons.
12
+ Merges with `gh pr merge N --<method> --match-head-commit SHA`, never `--auto`, then posts
13
+ `🤖 Merged by babysit-pr: gate passed, judge <label>` and exits 0.
14
+ --approved-sha is the owner's `@babysitter merge <sha>` approval (instead of --judge): it
15
+ needs an owner comment `@babysitter merge <sha>` for it (else nothing merges and it hands
16
+ off with "merge approval must name a commit: @babysitter merge <sha>"), and is honoured only
17
+ while SHA starts with it, else nothing merges and it hands off with
18
+ "approval was for <approved-sha>".
19
+ Exit non-zero when it does not merge. A moved head prints "gate again" and merges nothing.
20
+ Any other `gh pr merge` failure hands off with "merge blocked: <reason>".
21
+ babysit.py handoff --repo R --pr N --reason TEXT --ci TEXT --rounds N --gate TEXT --judge TEXT
22
+ --fix-log FILE
23
+ One comment `## 🧑 Needs human: <reason>`, label `needs-human` added, `babysitting` removed.
24
+
25
+ `gh` is the fake in fixtures/gh, which records `gh pr merge` calls in the state `merges`.
26
+ """
27
+ import json
28
+ import subprocess
29
+ import sys
30
+
31
+ import pytest
32
+
33
+ from test_babysit import SCRIPT, T, World, iso
34
+ from test_babysit_judge import commit as git_commit, git
35
+
36
+ BLOCK = """## Summary
37
+
38
+ Parse rows that are empty.
39
+
40
+ ## Merge Danger
41
+
42
+ ```merge-risk v1
43
+ door: two-way
44
+ blast_radius: isolated
45
+ touches: [logic, tests]
46
+ rollback: revert
47
+ verdict: auto
48
+ reasons:
49
+ - "small and reversible"
50
+ ```
51
+ """
52
+ URL = "https://github.com/jesdi/demo/pull/59"
53
+
54
+
55
+ def commit(sha, message="feat: x", author="jesdi", parents=("p0",)):
56
+ return {"sha": sha, "date": iso(T), "message": message, "author": author, "parents": list(parents)}
57
+
58
+
59
+ def checkout(w, shas, policy):
60
+ """A PR checkout: origin/main holds the policy, each sha is a branch named after it (so a fake
61
+ short sha resolves) that adds one logic file."""
62
+ git(w.project, "init", "-q", "-b", "work")
63
+ base = git_commit(w.project, {"README.md": "hi\n", ".merge-risk.json": json.dumps(policy)}, "base")
64
+ git(w.project, "update-ref", "refs/remotes/origin/main", base)
65
+ for sha in shas:
66
+ git(w.project, "checkout", "-q", "-b", sha, base)
67
+ git_commit(w.project, {"src/app.py": f"x = '{sha}'\n"}, f"pr {sha}")
68
+ git(w.project, "checkout", "-q", "work")
69
+
70
+
71
+ def owner_says(w, text, login="jesdi"):
72
+ st = w.github()
73
+ st["comments"].append({"id": st["next_id"], "user": {"login": login}, "body": text,
74
+ "created_at": iso(T), "updated_at": iso(T)})
75
+ st["next_id"] += 1
76
+ w.state.write_text(json.dumps(st))
77
+
78
+
79
+ def world(tmp_path, head="a1b2c3d", commits=None, body=BLOCK, policy=None, approvals=(), pr_risk=True, **state):
80
+ w = World(tmp_path, labels=["babysitting"], pr_risk=pr_risk)
81
+ st = w.github()
82
+ green = [{"name": "ci", "status": "completed", "conclusion": "success",
83
+ "created_at": iso(T), "started_at": iso(T)}]
84
+ st.update(head_sha=head, title="feat: parse empty rows", body=body, # the live PR body is the gated one
85
+ commits=commits or [commit(head)], **{"check_runs": {head: green}, **state})
86
+ w.state.write_text(json.dumps(st))
87
+ (tmp_path / "body.md").write_text(body)
88
+ checkout(w, [c["sha"] for c in st["commits"]], policy or {"agentMerge": True})
89
+ if policy: # the same policy also feeds `--policy`, the merge method
90
+ w.policy_file = tmp_path / "policy.json"
91
+ w.policy_file.write_text(json.dumps(policy))
92
+ for sha in approvals:
93
+ owner_says(w, f"@babysitter merge {sha}")
94
+ return w
95
+
96
+
97
+ def cli(w, *args):
98
+ p = subprocess.run([sys.executable, str(w.script), *args], cwd=w.project, env=w.env,
99
+ text=True, capture_output=True)
100
+ p.output = p.stdout + p.stderr
101
+ return p
102
+
103
+
104
+ def merge(w, tmp_path, sha="a1b2c3d", *extra, pr="58"):
105
+ policy = ["--policy", str(w.policy_file)] if hasattr(w, "policy_file") else []
106
+ return cli(w, "merge", "--repo", "jesdi/demo", "--pr", pr, "--sha", sha,
107
+ "--body", str(tmp_path / "body.md"), *extra, *policy)
108
+
109
+
110
+ def comments(w):
111
+ return [c["body"] for c in w.github()["comments"]]
112
+
113
+
114
+ def handoffs(w):
115
+ return [b for b in comments(w) if b.startswith("## 🧑 Needs human")]
116
+
117
+
118
+ def test_stale_gate_sha_fails_and_nothing_merges(tmp_path):
119
+ w = world(tmp_path, head="f0e1d2c", commits=[commit("a1b2c3d"), commit("f0e1d2c", author="alice")])
120
+ p = merge(w, tmp_path, "a1b2c3d", "--judge", "agree")
121
+ assert p.returncode != 0
122
+ assert "gate again" in p.output
123
+ assert w.github().get("merges", []) == []
124
+ assert not any("Merged by babysit-pr" in b for b in comments(w))
125
+
126
+
127
+ @pytest.mark.parametrize("extra", [("--judge", "agree"), ("--approved-sha", "a1b2c3d")])
128
+ def test_head_with_no_checks_hands_off_and_nothing_merges(tmp_path, extra):
129
+ w = world(tmp_path, check_runs={}, approvals=("a1b2c3d",))
130
+ p = merge(w, tmp_path, "a1b2c3d", *extra)
131
+ assert p.returncode != 0
132
+ assert w.github().get("merges", []) == []
133
+ [h] = handoffs(w)
134
+ assert h.startswith("## 🧑 Needs human: CI is no checks at merge time")
135
+
136
+
137
+ def test_default_method_is_rebase_pinned_to_the_gated_sha_and_commented(tmp_path):
138
+ w = world(tmp_path)
139
+ p = merge(w, tmp_path, "a1b2c3d", "--judge", "agree")
140
+ assert p.returncode == 0, p.output
141
+ [m] = w.github()["merges"]
142
+ assert (m["number"], m["method"], m["match"], m["auto"]) == ("58", "rebase", "a1b2c3d", False)
143
+ assert "🤖 Merged by babysit-pr: gate passed, judge agree" in comments(w)
144
+
145
+
146
+ def test_same_model_judge_shows_in_the_merge_comment(tmp_path):
147
+ w = world(tmp_path)
148
+ p = merge(w, tmp_path, "a1b2c3d", "--judge", "same-model agree")
149
+ assert p.returncode == 0, p.output
150
+ assert "🤖 Merged by babysit-pr: gate passed, judge same-model agree" in comments(w)
151
+
152
+
153
+ def test_merge_method_is_merge_when_the_branch_has_a_merge_commit(tmp_path):
154
+ w = world(tmp_path, commits=[commit("c1"), commit("a1b2c3d", parents=("c1", "m1"))])
155
+ p = cli(w, "merge-method", "--repo", "jesdi/demo", "--pr", "58")
156
+ assert p.returncode == 0, p.output
157
+ assert json.loads(p.stdout) == {"method": "merge"}
158
+ assert merge(w, tmp_path, "a1b2c3d", "--judge", "agree").returncode == 0
159
+ assert w.github()["merges"][0]["method"] == "merge"
160
+
161
+
162
+ def test_merge_method_is_rebase_for_a_linear_branch(tmp_path):
163
+ w = world(tmp_path)
164
+ p = cli(w, "merge-method", "--repo", "jesdi/demo", "--pr", "58")
165
+ assert json.loads(p.stdout) == {"method": "rebase"}
166
+
167
+
168
+ def test_squash_policy_keeps_the_title_summary_and_block_digest(tmp_path):
169
+ w = world(tmp_path, policy={"agentMerge": True, "mergeMethod": "squash"})
170
+ p = merge(w, tmp_path, "a1b2c3d", "--judge", "agree")
171
+ assert p.returncode == 0, p.output
172
+ [m] = w.github()["merges"]
173
+ assert m["method"] == "squash"
174
+ assert m["match"] == "a1b2c3d"
175
+ assert m["subject"] == "feat: parse empty rows (#58)"
176
+ assert "Parse rows that are empty." in m["body"]
177
+ assert "merge-risk v1: two-way, isolated, touches [logic, tests], rollback revert" in m["body"]
178
+
179
+
180
+ def test_required_approval_failure_hands_off(tmp_path):
181
+ w = world(tmp_path, merge_error="At least 1 approving review is required by reviewers "
182
+ "with write access.")
183
+ p = merge(w, tmp_path, "a1b2c3d", "--judge", "agree")
184
+ assert p.returncode != 0
185
+ [h] = handoffs(w)
186
+ assert h.startswith("## 🧑 Needs human: merge blocked: approval required")
187
+ assert "needs-human" in w.github()["labels"]
188
+ assert w.github().get("merges", []) == []
189
+
190
+
191
+ def test_handoff_comment_label_and_resume_command(tmp_path):
192
+ w = world(tmp_path, repo_labels=["babysitting"]) # needs-human does not exist yet
193
+ (tmp_path / "fixlog.md").write_text("- round 1: fixed test_empty\n- round 2: fixed lint\n")
194
+ p = cli(w, "handoff", "--repo", "jesdi/demo", "--pr", "59", "--reason", "door one-way",
195
+ "--ci", "green", "--rounds", "2", "--gate", "gate: human (door one-way)",
196
+ "--judge", "judge: not run", "--fix-log", str(tmp_path / "fixlog.md"))
197
+ assert p.returncode == 0, p.output
198
+ [h] = handoffs(w)
199
+ assert h.startswith("## 🧑 Needs human: door one-way")
200
+ for part in ("CI green · 2 fix rounds", "gate: human (door one-way)", "judge: not run",
201
+ "- round 1: fixed test_empty", "- round 2: fixed lint", f"/babysit-pr {URL}"):
202
+ assert part in h
203
+ labels = w.github()["labels"]
204
+ assert "needs-human" in labels and "babysitting" not in labels
205
+ assert "needs-human" in w.github()["repo_labels"]
206
+ assert w.unsupported() == []
207
+
208
+
209
+ def test_owner_approval_of_the_head_merges_without_the_judge(tmp_path):
210
+ w = world(tmp_path, approvals=("a1b2c3d",))
211
+ p = merge(w, tmp_path, "a1b2c3d", "--approved-sha", "a1b2c3d", pr="59")
212
+ assert p.returncode == 0, p.output
213
+ [m] = w.github()["merges"]
214
+ assert (m["number"], m["match"], m["auto"]) == ("59", "a1b2c3d", False)
215
+ assert handoffs(w) == []
216
+
217
+
218
+ def test_owner_approval_of_a_sha_prefix_merges(tmp_path):
219
+ w = world(tmp_path, head="a1b2c3d4e5f6", approvals=("a1b2c3d",))
220
+ p = merge(w, tmp_path, "a1b2c3d4e5f6", "--approved-sha", "a1b2c3d", pr="59")
221
+ assert p.returncode == 0, p.output
222
+ assert w.github()["merges"][0]["match"] == "a1b2c3d4e5f6"
223
+
224
+
225
+ def test_approval_voided_by_a_new_commit_hands_off_with_the_new_commits(tmp_path):
226
+ w = world(tmp_path, head="e4f5a6b", approvals=("a1b2c3d",), commits=[
227
+ commit("a1b2c3d", "feat: parse empty rows"),
228
+ commit("e4f5a6b", "fix(ci): repair test_empty (babysit-pr)", author="babysitter-bot")])
229
+ p = merge(w, tmp_path, "e4f5a6b", "--approved-sha", "a1b2c3d", pr="59")
230
+ assert p.returncode != 0
231
+ assert w.github().get("merges", []) == []
232
+ [h] = handoffs(w)
233
+ assert h.startswith("## 🧑 Needs human: approval was for a1b2c3d")
234
+ assert "e4f5a6b" in h and "fix(ci): repair test_empty (babysit-pr)" in h
235
+ assert "babysitter-bot" in h
236
+ assert "https://github.com/jesdi/demo/compare/a1b2c3d...e4f5a6b" in h
237
+ assert "needs-human" in w.github()["labels"]
238
+
239
+
240
+ def test_approval_voided_by_a_rebase_hands_off(tmp_path):
241
+ w = world(tmp_path, head="b7c8d9e", commits=[commit("b7c8d9e")], approvals=("a1b2c3d",))
242
+ p = merge(w, tmp_path, "b7c8d9e", "--approved-sha", "a1b2c3d", pr="59")
243
+ assert p.returncode != 0
244
+ assert w.github().get("merges", []) == []
245
+ [h] = handoffs(w)
246
+ # a rebased-away commit is no longer a commit of the PR: either reason of requirement 23 hands off
247
+ assert h.startswith(("## 🧑 Needs human: approval was for a1b2c3d",
248
+ "## 🧑 Needs human: merge approval must name a commit"))
249
+
250
+
251
+ @pytest.mark.parametrize("method", [None, "squash", "merge", "rebase"])
252
+ @pytest.mark.parametrize("extra", [("--judge", "agree"), ("--approved-sha", "a1b2c3d")])
253
+ def test_auto_merge_is_never_requested(tmp_path, extra, method):
254
+ policy = {"agentMerge": True, "mergeMethod": method} if method else None
255
+ w = world(tmp_path, policy=policy, approvals=("a1b2c3d",))
256
+ assert merge(w, tmp_path, "a1b2c3d", *extra).returncode == 0
257
+ [m] = w.github()["merges"]
258
+ assert m["auto"] is False
259
+ assert method is None or m["method"] == method
260
+ assert not any("--auto" in argv for argv in w.calls())
@@ -0,0 +1,10 @@
1
+ """Merge refuses when GitHub's base is not the commit the local gate read the policy from."""
2
+ from test_merge_and_handoff import merge, world
3
+
4
+
5
+ def test_remote_base_ahead_of_the_local_ref_merges_nothing(tmp_path):
6
+ w = world(tmp_path, base_sha="f" * 40) # origin/main locally is another commit
7
+ p = merge(w, tmp_path, "a1b2c3d", "--judge", "agree")
8
+ assert p.returncode != 0
9
+ assert "gate again" in p.output
10
+ assert w.github().get("merges", []) == []
@@ -0,0 +1,124 @@
1
+ """Acceptance tests: `babysit.py merge` decides from the trusted gate and the owner's comment.
2
+
3
+ Seam: `babysit.py merge` and `babysit.py judge`, with the fake `gh` and a temporary git checkout
4
+ whose `origin/main` holds `.merge-risk.json` (see test_merge_and_handoff.py for the interface).
5
+ Spec requirements 7 (the gate) and 23 (the owner's `@babysitter merge <sha>` approval).
6
+ """
7
+ import json
8
+
9
+ from test_merge_and_handoff import BLOCK, handoffs, merge, owner_says, world
10
+ from test_trusted_merge_risk import judge_world, run_judge, write_pr_risk
11
+
12
+ HEAD = "a1b2c3d4e5f6"
13
+ APPROVAL_MESSAGE = "merge approval must name a commit: @babysitter merge <sha>"
14
+
15
+
16
+ def merged(w):
17
+ return w.github().get("merges", [])
18
+
19
+
20
+ def test_agent_merge_off_hands_off_with_the_policy_as_the_reason(tmp_path):
21
+ w = world(tmp_path, policy={"agentMerge": False})
22
+ p = merge(w, tmp_path, "a1b2c3d", "--judge", "agree")
23
+ assert p.returncode != 0
24
+ assert merged(w) == []
25
+ [h] = handoffs(w)
26
+ assert "agentMerge" in h.splitlines()[0]
27
+ assert not any("Merged by babysit-pr" in c["body"] for c in w.github()["comments"])
28
+
29
+
30
+ def test_one_way_door_hands_off_although_the_block_says_auto(tmp_path):
31
+ assert "verdict: auto" in BLOCK
32
+ w = world(tmp_path, body=BLOCK.replace("door: two-way", "door: one-way"))
33
+ p = merge(w, tmp_path, "a1b2c3d", "--judge", "agree")
34
+ assert p.returncode != 0
35
+ assert merged(w) == []
36
+ [h] = handoffs(w)
37
+ assert "door one-way" in h.splitlines()[0]
38
+
39
+
40
+ def test_approved_sha_without_an_owner_comment_approves_nothing(tmp_path):
41
+ w = world(tmp_path)
42
+ p = merge(w, tmp_path, "a1b2c3d", "--approved-sha", "a1b2c3d")
43
+ assert p.returncode != 0
44
+ assert merged(w) == []
45
+ [h] = handoffs(w)
46
+ assert h.startswith(f"## 🧑 Needs human: {APPROVAL_MESSAGE}")
47
+
48
+
49
+ def test_owner_comment_with_a_sha_prefix_merges_a_human_verdict_pinned_to_the_head(tmp_path):
50
+ # the policy gives human, so only the owner's comment can merge; the caller passes the full SHA
51
+ w = world(tmp_path, head=HEAD, policy={"agentMerge": False}, approvals=(HEAD[:7],))
52
+ p = merge(w, tmp_path, HEAD, "--approved-sha", HEAD)
53
+ assert p.returncode == 0, p.output
54
+ [m] = merged(w)
55
+ assert m["match"] == HEAD
56
+ assert handoffs(w) == []
57
+
58
+
59
+ def test_non_owner_approval_approves_nothing(tmp_path):
60
+ w = world(tmp_path, head=HEAD)
61
+ owner_says(w, f"@babysitter merge {HEAD}", login="alice")
62
+ p = merge(w, tmp_path, HEAD, "--approved-sha", HEAD)
63
+ assert p.returncode != 0
64
+ assert merged(w) == []
65
+ assert len(handoffs(w)) == 1
66
+
67
+
68
+ def old_install(folder, missing):
69
+ write_pr_risk(folder, folder.parent / "marker")
70
+ with open(folder / "merge_risk.py", "a") as f:
71
+ f.write("".join(f"\ndel {name}\n" for name in missing))
72
+
73
+
74
+ def test_judge_with_a_trusted_pr_risk_lacking_classify_diff_hands_off(tmp_path):
75
+ j, home, script = judge_world(tmp_path)
76
+ old_install(home / ".claude" / "skills" / "pr-risk", ["classify_diff"])
77
+ p = run_judge(j, script, home)
78
+ assert "pr-risk is too old: classify_diff" in p.stdout + p.stderr
79
+ assert "AttributeError" not in p.stdout + p.stderr
80
+ assert '"verdict": "agree"' not in p.stdout
81
+
82
+
83
+ def test_merge_with_a_trusted_pr_risk_lacking_classify_diff_hands_off(tmp_path):
84
+ w = world(tmp_path, pr_risk=False)
85
+ old_install(w.home / ".claude" / "skills" / "pr-risk", ["classify_diff"])
86
+ p = merge(w, tmp_path, "a1b2c3d", "--judge", "agree")
87
+ assert p.returncode != 0
88
+ assert "AttributeError" not in p.output
89
+ assert merged(w) == []
90
+ [h] = handoffs(w)
91
+ assert "pr-risk is too old: classify_diff" in h.splitlines()[0]
92
+
93
+
94
+ def test_gate_reads_the_diff_of_the_sha_it_merges_not_the_checked_out_head(tmp_path):
95
+ # the checkout sits on `work` (= origin/main, an empty diff); only HEAD's own commit adds a counted line
96
+ w = world(tmp_path, policy={"agentMerge": True, "judgeMaxLines": 0})
97
+ p = merge(w, tmp_path, "a1b2c3d", "--judge", "agree")
98
+ assert p.returncode != 0
99
+ assert merged(w) == []
100
+ [h] = handoffs(w)
101
+ assert "counted lines" in h.splitlines()[0]
102
+
103
+
104
+ def live_body_differs(tmp_path, live, *extra):
105
+ # the saved --body file holds the valid auto block; the PR itself says something else
106
+ w = world(tmp_path)
107
+ st = w.github()
108
+ st["body"] = live
109
+ w.state.write_text(json.dumps(st))
110
+ return w, merge(w, tmp_path, "a1b2c3d", *extra)
111
+
112
+
113
+ def test_saved_body_does_not_stand_in_for_a_one_way_live_body(tmp_path):
114
+ w, p = live_body_differs(tmp_path, BLOCK.replace("door: two-way", "door: one-way"), "--judge", "agree")
115
+ assert p.returncode != 0
116
+ assert merged(w) == []
117
+ assert not any("Merged by babysit-pr" in c["body"] for c in w.github()["comments"])
118
+
119
+
120
+ def test_saved_body_does_not_stand_in_for_an_empty_live_body(tmp_path):
121
+ w, p = live_body_differs(tmp_path, "", "--judge", "agree")
122
+ assert p.returncode != 0
123
+ assert merged(w) == []
124
+ assert not any("Merged by babysit-pr" in c["body"] for c in w.github()["comments"])
@@ -0,0 +1,117 @@
1
+ """CLI regressions for lease ownership at merge and handoff."""
2
+ import json
3
+
4
+ from test_merge_and_handoff import cli, handoffs, merge, world
5
+
6
+
7
+ def handoff(w, *extra):
8
+ return cli(w, "handoff", "--repo", "jesdi/demo", "--pr", "58",
9
+ "--reason", "door one-way", "--ci", "green", "--rounds", "0",
10
+ "--gate", "gate: human", "--judge", "judge: not run",
11
+ "--fix-log", str(w.project.parent / "body.md"), *extra)
12
+
13
+
14
+ def test_sessionless_handoff_cannot_adopt_a_lease(tmp_path):
15
+ w = world(tmp_path, repo_labels=["babysitting", "needs-human"])
16
+ assert w.run("acquire", "s1").returncode == 0
17
+ p = handoff(w)
18
+ assert p.returncode != 0, p.output
19
+ assert "--session" in p.output
20
+ assert handoffs(w) == []
21
+ assert w.active_leases()[0][1] == "s1"
22
+
23
+
24
+ def test_handoff_retry_cannot_end_resumed_session(tmp_path):
25
+ w = world(tmp_path, repo_labels=["babysitting", "needs-human"])
26
+ assert w.run("acquire", "s1").returncode == 0
27
+ assert handoff(w, "--session", "s1").returncode == 0
28
+ st = w.github()
29
+ st["comments"].append({"id": st["next_id"], "user": {"login": "jesdi"},
30
+ "body": "@babysitter add a test"})
31
+ st["next_id"] += 1
32
+ w.state.write_text(json.dumps(st))
33
+ assert w.run("acquire", "s2").returncode == 0
34
+ for args in [(), ("--session", "s1")]:
35
+ p = handoff(w, *args)
36
+ assert p.returncode != 0, p.output
37
+ assert len(handoffs(w)) == 1
38
+ assert w.active_leases()[0][1] == "s2"
39
+
40
+
41
+ def test_stale_session_cannot_merge_or_release_new_holder(tmp_path):
42
+ w = world(tmp_path)
43
+ assert w.run("acquire", "s2").returncode == 0
44
+ p = merge(w, tmp_path, "a1b2c3d", "--judge", "agree", "--session", "s1")
45
+ assert p.returncode != 0, p.output
46
+ assert w.github().get("merges", []) == []
47
+ assert handoffs(w) == []
48
+ assert w.active_leases()[0][1] == "s2"
49
+
50
+
51
+ def test_sessionless_merge_cannot_adopt_a_lease(tmp_path):
52
+ w = world(tmp_path)
53
+ assert w.run("acquire", "s2").returncode == 0
54
+ before = w.github()
55
+ p = merge(w, tmp_path, "a1b2c3d", "--judge", "agree")
56
+ assert p.returncode != 0, p.output
57
+ assert "--session" in p.output
58
+ assert w.github() == before
59
+
60
+
61
+ def resume_during_handoff(w, after_end):
62
+ """Resume via the real CLI at a terminal-write boundary of the fake gh."""
63
+ from test_babysit import SCRIPT
64
+
65
+ fake = w.project.parent / "bin" / "gh"
66
+ real = fake.with_name("gh-real")
67
+ fake.rename(real)
68
+ condition = ('any("\\nended\\n" in c["body"] for c in st["comments"])' if after_end else
69
+ 'any(c["body"].startswith("## 🧑 Needs human") for c in st["comments"])')
70
+ fake.write_text(f'''#!/usr/bin/env python3
71
+ import json, os, subprocess, sys
72
+ from datetime import datetime, timedelta
73
+ from pathlib import Path
74
+ p = subprocess.run([{str(real)!r}, *sys.argv[1:]])
75
+ state = Path(os.environ["GH_FAKE_STATE"])
76
+ st = json.loads(state.read_text())
77
+ if not st.get("resumed") and {condition}:
78
+ st["resumed"] = True
79
+ if not {after_end!r}:
80
+ st["now"] = (datetime.fromisoformat(st["now"].replace("Z", "+00:00")) + timedelta(minutes=91)).strftime("%Y-%m-%dT%H:%M:%SZ")
81
+ state.write_text(json.dumps(st))
82
+ subprocess.run([sys.executable, {str(SCRIPT)!r}, "lease", "acquire", "--repo", "jesdi/demo", "--pr", "58", "--session", "s2", "--host", "other"], check=True, stdout=subprocess.DEVNULL)
83
+ sys.exit(p.returncode)
84
+ ''')
85
+ fake.chmod(0o755)
86
+
87
+
88
+ def test_handoff_finishes_labels_before_releasing_to_resumed_session(tmp_path):
89
+ w = world(tmp_path, repo_labels=["babysitting", "needs-human"])
90
+ assert w.run("acquire", "s1").returncode == 0
91
+ resume_during_handoff(w, after_end=True)
92
+ p = handoff(w, "--session", "s1")
93
+ assert p.returncode == 0, p.output
94
+ assert w.active_leases()[0][1] == "s2"
95
+ assert "babysitting" in w.github()["labels"]
96
+ assert "needs-human" not in w.github()["labels"]
97
+
98
+
99
+ def test_handoff_rechecks_ownership_after_posting_comment(tmp_path):
100
+ w = world(tmp_path, repo_labels=["babysitting", "needs-human"])
101
+ assert w.run("acquire", "s1").returncode == 0
102
+ resume_during_handoff(w, after_end=False)
103
+ p = handoff(w, "--session", "s1")
104
+ assert p.returncode != 0, p.output
105
+ assert w.active_leases()[0][1] == "s2"
106
+ assert "babysitting" in w.github()["labels"]
107
+ assert "needs-human" not in w.github()["labels"]
108
+
109
+
110
+ def test_merge_with_own_session_ends_only_its_lease(tmp_path):
111
+ w = world(tmp_path)
112
+ assert w.run("acquire", "s1").returncode == 0
113
+ p = merge(w, tmp_path, "a1b2c3d", "--judge", "agree", "--session", "s1")
114
+ assert p.returncode == 0, p.output
115
+ assert len(w.github()["merges"]) == 1
116
+ assert w.active_leases() == []
117
+ assert "babysitting" not in w.github()["labels"]
@@ -0,0 +1,144 @@
1
+ """Acceptance tests: a merged PR never keeps a stale handoff label.
2
+
3
+ Seam: `babysit.py handoff --session S` and `babysit.py merge --session S`, with the fake `gh`.
4
+
5
+ The fake always serves the PR as open, so a wrapper around it serves the PR as merged once the
6
+ fake has recorded a `gh pr merge` (REST `merged: true, state: closed`, `gh pr view` `state: MERGED`).
7
+ The wrapper also injects the race: right before the stale session s1's terminal write, the clock
8
+ moves past the lease expiry and s2 takes over, merges and releases.
9
+ TRIGGER=comment: the injection fires just before s1 posts its handoff comment, so s1's comment
10
+ lands after s2's merge comment.
11
+ TRIGGER=labels: it fires just before s1's first label write, so s1's comment is older.
12
+ Expected: the merged PR ends without `needs-human` and without `babysitting`.
13
+ KIND picks what happens at the injection point: "successor" (s2 takes over, merges, releases), "hold"
14
+ (s2 takes over and keeps the open PR), "hold+owner" (s2 takes over, then the owner merges the PR with
15
+ no merge comment), "owner" (no takeover; the owner merges the PR with no merge comment).
16
+ """
17
+ import pytest
18
+
19
+ from test_babysit import SCRIPT
20
+ from test_merge_and_handoff import cli, handoffs, merge, world
21
+ from test_merge_session_safety import handoff
22
+
23
+ WRAPPER = '''#!/usr/bin/env python3
24
+ import json, os, re, subprocess, sys
25
+ from datetime import datetime, timedelta
26
+ from pathlib import Path
27
+ argv = sys.argv[1:]
28
+ state = Path(os.environ["GH_FAKE_STATE"])
29
+ st = json.loads(state.read_text())
30
+ text = " ".join(argv)
31
+ is_comment = (argv[:2] == ["pr", "comment"] or (argv[:1] == ["api"] and re.search(r"issues/\\d+/comments\\b", text)
32
+ and any(a in argv for a in ("-X", "--method", "-f", "-F", "--input")))) and "Needs human" in text
33
+ is_label = (argv[:2] == ["pr", "edit"] and "label" in text) or (
34
+ argv[:1] == ["api"] and re.search(r"/issues/\\d+/labels(/|\\s|$)", text)
35
+ and any(a in argv for a in ("-X", "--method", "-f", "-F", "--input")))
36
+ terminal = any(c["body"].startswith("## 🧑 Needs human") for c in st["comments"])
37
+ fire = {inject!r} and not st.get("taking") and (is_comment if {trigger!r} == "comment" else is_label and terminal)
38
+ if fire:
39
+ st["taking"] = True
40
+ kind = {kind!r}
41
+ if kind != "owner":
42
+ st["now"] = (datetime.fromisoformat(st["now"].replace("Z", "+00:00"))
43
+ + timedelta(minutes=91)).strftime("%Y-%m-%dT%H:%M:%SZ")
44
+ if kind.endswith("owner"):
45
+ st.setdefault("merges", []).append({{"number": 58, "method": "merge"}})
46
+ state.write_text(json.dumps(st))
47
+ base = [sys.executable, {script!r}]
48
+ where = ["--repo", "jesdi/demo", "--pr", "58"]
49
+ if kind != "owner":
50
+ subprocess.run([*base, "lease", "acquire", *where, "--session", "s2", "--host", "other"],
51
+ check=True, stdout=subprocess.DEVNULL)
52
+ if kind == "successor":
53
+ subprocess.run([*base, "merge", *where, "--sha", "a1b2c3d", "--body", {body!r},
54
+ "--judge", "agree", "--session", "s2"], check=True, stdout=subprocess.DEVNULL)
55
+ subprocess.run([*base, "lease", "release", *where, "--session", "s2"], stdout=subprocess.DEVNULL)
56
+ st = json.loads(state.read_text())
57
+ st["taken"] = True
58
+ state.write_text(json.dumps(st))
59
+
60
+ # serve the PR as merged once the fake recorded a merge
61
+ st = json.loads(state.read_text())
62
+ pr_read = (argv[:2] == ["pr", "view"]) or (argv[:1] == ["api"] and re.search(r"(issues|pulls)/\\d+$", text.split("--jq")[0].strip())
63
+ and not any(a in argv for a in ("-X", "--method", "-f", "-F", "--input")))
64
+ if st.get("merges") and pr_read:
65
+ jq, rest, i = None, [], 0
66
+ while i < len(argv):
67
+ if argv[i] in ("--jq", "-q"):
68
+ jq = argv[i + 1]; i += 2
69
+ else:
70
+ rest.append(argv[i]); i += 1
71
+ p = subprocess.run([{real!r}, *rest], capture_output=True, text=True)
72
+ if p.returncode:
73
+ sys.stderr.write(p.stderr); sys.exit(p.returncode)
74
+ obj = json.loads(p.stdout)
75
+ if argv[0] == "pr":
76
+ obj.update(state="MERGED", mergedAt=st["now"], closed=True)
77
+ else:
78
+ obj.update(state="closed", merged=True, merged_at=st["now"])
79
+ if jq:
80
+ q = subprocess.run(["jq", "-r", jq], input=json.dumps(obj), text=True, capture_output=True)
81
+ sys.stdout.write(q.stdout); sys.stderr.write(q.stderr); sys.exit(q.returncode)
82
+ print(json.dumps(obj)); sys.exit(0)
83
+ sys.exit(subprocess.run([{real!r}, *argv]).returncode)
84
+ '''
85
+
86
+
87
+ def install(w, tmp_path, trigger="labels", inject=True, kind="successor"):
88
+ fake = w.project.parent / "bin" / "gh"
89
+ real = fake.with_name("gh-real")
90
+ fake.rename(real)
91
+ fake.write_text(WRAPPER.format(script=str(SCRIPT), real=str(real), trigger=trigger, inject=inject, kind=kind,
92
+ body=str(tmp_path / "body.md")))
93
+ fake.chmod(0o755)
94
+
95
+
96
+ @pytest.mark.parametrize("trigger", ["comment", "labels"])
97
+ def test_stale_handoff_after_a_successor_merge_leaves_the_merged_pr_without_labels(tmp_path, trigger):
98
+ w = world(tmp_path, repo_labels=["babysitting", "needs-human"])
99
+ assert w.run("acquire", "s1").returncode == 0
100
+ install(w, tmp_path, trigger)
101
+ handoff(w, "--session", "s1")
102
+ st = w.github()
103
+ assert st.get("taken"), "the takeover never fired"
104
+ assert len(st["merges"]) == 1, "the successor never merged"
105
+ assert any("Merged by babysit-pr" in c["body"] for c in st["comments"])
106
+ assert "needs-human" not in st["labels"], st["labels"]
107
+ assert "babysitting" not in st["labels"], st["labels"]
108
+
109
+
110
+ def test_handoff_on_an_open_pr_with_no_takeover_still_ends_with_needs_human(tmp_path):
111
+ w = world(tmp_path, repo_labels=["babysitting", "needs-human"])
112
+ assert w.run("acquire", "s1").returncode == 0
113
+ install(w, tmp_path, inject=False)
114
+ p = handoff(w, "--session", "s1")
115
+ assert p.returncode == 0, p.output
116
+ labels = w.github()["labels"]
117
+ assert "needs-human" in labels and "babysitting" not in labels
118
+ assert len(handoffs(w)) == 1
119
+
120
+
121
+ def test_takeover_of_an_open_pr_keeps_the_new_holders_labels(tmp_path):
122
+ w = world(tmp_path, repo_labels=["babysitting", "needs-human"])
123
+ assert w.run("acquire", "s1").returncode == 0
124
+ install(w, tmp_path, "labels", kind="hold")
125
+ handoff(w, "--session", "s1")
126
+ st = w.github()
127
+ assert st.get("taken"), "the takeover never fired"
128
+ assert not st.get("merges")
129
+ assert "babysitting" in st["labels"], st["labels"]
130
+ assert "needs-human" not in st["labels"], st["labels"]
131
+
132
+
133
+ @pytest.mark.parametrize("kind", ["hold+owner", "owner"])
134
+ def test_pr_merged_during_the_stale_write_ends_without_labels(tmp_path, kind):
135
+ """The merge lands between the handoff comment and the label write, with no merge comment to order by."""
136
+ w = world(tmp_path, repo_labels=["babysitting", "needs-human"])
137
+ assert w.run("acquire", "s1").returncode == 0
138
+ install(w, tmp_path, "labels", kind=kind)
139
+ handoff(w, "--session", "s1")
140
+ st = w.github()
141
+ assert st.get("taken"), "the injection never fired"
142
+ assert len(st["merges"]) == 1
143
+ assert "needs-human" not in st["labels"], st["labels"]
144
+ assert "babysitting" not in st["labels"], st["labels"]