@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,70 @@
1
+ """CLI regressions for lease identity and hidden handoff boundaries."""
2
+ import json
3
+
4
+ from test_babysit import MIN, T, World
5
+ from test_owner_comments import HANDOFF_BODY, comment, read
6
+
7
+
8
+ def test_resume_instruction_before_new_confirmed_lease_is_returned(tmp_path):
9
+ w = World(tmp_path, comments=[comment(1001, "jesdi", HANDOFF_BODY),
10
+ comment(1002, "jesdi", "@babysitter add a test", at=T + MIN)])
11
+ w.set_now(T + 2 * MIN)
12
+ assert w.run("acquire", "s1").returncode == 0
13
+ st = w.github()
14
+ c = st["comments"][-1]
15
+ c.update(editor={"login": "jesdi"}, last_edited_at=c["updated_at"])
16
+ w.state.write_text(json.dumps(st))
17
+ w.log.write_text("")
18
+ assert [i["id"] for i in read(w)["instructions"]] == [1002]
19
+
20
+
21
+ def test_hidden_handoff_disguised_as_lease_cannot_replay_an_instruction(tmp_path):
22
+ w = World(tmp_path, comments=[comment(1001, "jesdi", "@babysitter add a test"),
23
+ comment(1002, "jesdi", HANDOFF_BODY, at=T + MIN)])
24
+ st = w.github()
25
+ c = st["comments"][-1]
26
+ c.update(body="<!-- babysit-pr lease: s1 mac 2020-01-01T11:00:00Z -->\nrounds: 0",
27
+ editor={"login": "jesdi"}, last_edited_at=c["updated_at"])
28
+ w.state.write_text(json.dumps(st))
29
+ out = read(w)
30
+ assert out["handoff"]
31
+ assert out["instructions"] == []
32
+
33
+
34
+ def test_created_lease_cannot_become_an_instruction_after_an_edit(tmp_path):
35
+ w = World(tmp_path)
36
+ assert w.run("acquire", "s1").returncode == 0
37
+ st = w.github()
38
+ c = st["comments"][-1]
39
+ c.update(body="@babysitter add a test", editor={"login": "jesdi"},
40
+ last_edited_at=c["updated_at"])
41
+ w.state.write_text(json.dumps(st))
42
+ w.log.write_text("")
43
+ assert read(w)["instructions"] == []
44
+
45
+
46
+ def test_known_lease_disguised_as_handoff_does_not_hide_a_new_instruction(tmp_path):
47
+ w = World(tmp_path, comments=[comment(1001, "jesdi", "@babysitter add a test")])
48
+ assert w.run("acquire", "s1").returncode == 0
49
+ st = w.github()
50
+ c = st["comments"][-1]
51
+ c.update(body=HANDOFF_BODY, editor={"login": "jesdi"}, last_edited_at=c["updated_at"])
52
+ w.state.write_text(json.dumps(st))
53
+ w.log.write_text("")
54
+ out = read(w)
55
+ assert out["handoff"] is None
56
+ assert [i["id"] for i in out["instructions"]] == [1001]
57
+
58
+
59
+ def test_observed_handoff_disguised_as_lease_keeps_its_identity(tmp_path):
60
+ w = World(tmp_path, comments=[comment(1001, "jesdi", HANDOFF_BODY)])
61
+ assert read(w)["handoff"] is None
62
+ st = w.github()
63
+ c = st["comments"][-1]
64
+ c.update(body="<!-- babysit-pr lease: s1 mac 2020-01-01T11:00:00Z -->\nrounds: 0",
65
+ editor={"login": "jesdi"}, last_edited_at=c["updated_at"])
66
+ st["comments"].append(comment(1002, "jesdi", "@babysitter add a test", at=T + MIN))
67
+ w.state.write_text(json.dumps(st))
68
+ out = read(w)
69
+ assert out["handoff"]
70
+ assert out["instructions"] == []
@@ -0,0 +1,74 @@
1
+ """Exercise the manual runner's skill provisioning without a GitHub session."""
2
+ import os
3
+ from pathlib import Path
4
+ import subprocess
5
+ import sys
6
+
7
+
8
+ def test_runner_loads_reviewed_dependency_outside_checkout(tmp_path):
9
+ runner = Path(__file__).resolve().parents[2] / "scripts/e2e-babysit.sh"
10
+ setup = runner.read_text().split('start=HEAD')[0]
11
+ gh = tmp_path / "gh"
12
+ gh.write_text('#!/bin/sh\nexec git init -q "$4"\n')
13
+ gh.chmod(0o755)
14
+ env = dict(os.environ, PATH=f"{tmp_path}:{os.environ['PATH']}", TMPDIR=str(tmp_path))
15
+ result = subprocess.run(
16
+ ["sh", "-c", setup + '\nprintf "%s\\n" "$tmp"', str(runner), "fix"],
17
+ env=env, capture_output=True, text=True, check=True,
18
+ )
19
+ staging = Path(result.stdout.strip())
20
+ probe = """
21
+ import importlib.util
22
+ from pathlib import Path
23
+ spec = importlib.util.spec_from_file_location('babysit', '.claude/skills/babysit-pr/babysit.py')
24
+ babysit = importlib.util.module_from_spec(spec)
25
+ spec.loader.exec_module(babysit)
26
+ reviewed = Path('.claude/skills/pr-risk').resolve()
27
+ assert not reviewed.is_relative_to(Path.cwd()), reviewed
28
+ assert babysit.trusted_pr_risk_dirs()[0] == reviewed
29
+ assert Path(babysit.load_merge_risk().__file__).resolve() == reviewed / 'merge_risk.py'
30
+ assert Path('.agents/skills/babysit-pr').resolve() == Path('.claude/skills/babysit-pr').resolve()
31
+ """
32
+ subprocess.run([sys.executable, "-c", probe], cwd=staging / "work", check=True)
33
+
34
+
35
+ def test_fix_scenario_keeps_a_feature_after_empty_input_repair(tmp_path):
36
+ runner = Path(__file__).resolve().parents[2] / "scripts/e2e-babysit.sh"
37
+ setup = runner.read_text().split('commit "$title"\ngit push')[0]
38
+ gh = tmp_path / "gh"
39
+ seed = tmp_path / "seed"
40
+ subprocess.run(["git", "init", "-q", str(seed)], check=True)
41
+ subprocess.run(["git", "-C", str(seed), "-c", "user.name=e2e", "-c",
42
+ "user.email=e2e@example.invalid", "-c", "commit.gpgsign=false",
43
+ "commit", "-q", "--allow-empty", "-m", "seed"], check=True)
44
+ # Model a previous successful run merged to the default branch.
45
+ (seed / "feature.txt").write_text("Already merged feature\n")
46
+ subprocess.run(["git", "-C", str(seed), "add", "."], check=True)
47
+ subprocess.run(["git", "-C", str(seed), "-c", "user.name=e2e", "-c",
48
+ "user.email=e2e@example.invalid", "-c", "commit.gpgsign=false",
49
+ "commit", "-qm", "previous run"], check=True)
50
+ gh.write_text('#!/bin/sh\ngit clone -q "$SEED_REPO" "$4"\nmkdir -p "$4/src/demo" "$4/tests"\n')
51
+ gh.chmod(0o755)
52
+ env = dict(os.environ, PATH=f"{tmp_path}:{os.environ['PATH']}", TMPDIR=str(tmp_path),
53
+ SEED_REPO=str(seed))
54
+ result = subprocess.run(
55
+ ["sh", "-c", setup + '\nprintf "%s\\n" "$tmp"', str(runner), "fix"],
56
+ env=env, capture_output=True, text=True, check=True,
57
+ )
58
+ work = Path(result.stdout.strip()) / "work"
59
+ assert not (work / "feature.txt").exists() # each run starts from the seed
60
+ source = work / "src/demo/parse.py"
61
+ namespace = {}
62
+ exec(source.read_text(), namespace)
63
+ assert namespace["parse"]("") == [[]] # the injected failure still exists
64
+ source.write_text(source.read_text().replace(" or [[]]", ""))
65
+ exec(source.read_text(), namespace)
66
+ assert namespace["parse"]("") == []
67
+ env["PYTHONPATH"] = str(work / "src")
68
+ subprocess.run(
69
+ [sys.executable, "-m", "pytest", "-q", "tests/test_parse_bom.py"],
70
+ cwd=work, env=env, check=True,
71
+ )
72
+ # The retained test covers behavior absent from the base, not a cosmetic diff.
73
+ exec(source.read_text().replace('text = text.removeprefix("\\ufeff")', 'text = text'), namespace)
74
+ assert namespace["parse"]("\ufeffa, b\nc, d\n") != [["a", "b"], ["c", "d"]]
@@ -0,0 +1,141 @@
1
+ """Acceptance tests: a terminal label write never leaves its labels on a taken-over PR.
2
+
3
+ Seam: `babysit.py handoff|merge --session S` and `babysit.py lease acquire`, with the fake `gh`.
4
+
5
+ The takeover is injected through a wrapper around the fake `gh`: right before the first PR label
6
+ write (issues/N/labels, not the repo-level label creation) that follows the terminal comment (handoff comment, or a recorded merge), the clock moves
7
+ past the lease expiry and session s2 runs the real `lease acquire`. That is after any ownership
8
+ check that precedes the write, and before the write lands over s2's labels.
9
+ Expected: s2 keeps `babysitting`, `needs-human` is off, the handoff comment stays, and the
10
+ command reports "taken over".
11
+ """
12
+ from test_babysit import SCRIPT
13
+ from test_merge_and_handoff import cli, handoffs, merge, world
14
+ from test_merge_session_safety import handoff
15
+
16
+ WRAPPER = '''#!/usr/bin/env python3
17
+ import json, os, re, subprocess, sys
18
+ from datetime import datetime, timedelta
19
+ from pathlib import Path
20
+ argv = sys.argv[1:]
21
+ state = Path(os.environ["GH_FAKE_STATE"])
22
+ st = json.loads(state.read_text())
23
+ paths = [a for a in argv if re.search(r"/issues/\\d+/labels(/|$)", a)]
24
+ write = (argv[:2] == ["pr", "edit"] and any("label" in a for a in argv)) or (
25
+ argv[:1] == ["api"] and paths and any(a in argv for a in ("-X", "--method", "-f", "-F", "--input")))
26
+ terminal = any(c["body"].startswith("## 🧑 Needs human") or "Merged by babysit-pr" in c["body"]
27
+ for c in st["comments"]) or st.get("merges")
28
+ if write and terminal and not st.get("taking"):
29
+ st["taking"] = True
30
+ st["now"] = (datetime.fromisoformat(st["now"].replace("Z", "+00:00"))
31
+ + timedelta(minutes=91)).strftime("%Y-%m-%dT%H:%M:%SZ")
32
+ state.write_text(json.dumps(st))
33
+ subprocess.run([sys.executable, {script!r}, "lease", "acquire", "--repo", "jesdi/demo",
34
+ "--pr", "58", "--session", "s2", "--host", "other"],
35
+ check=True, stdout=subprocess.DEVNULL)
36
+ st = json.loads(state.read_text())
37
+ st["taken"] = True
38
+ state.write_text(json.dumps(st))
39
+ st = json.loads(state.read_text())
40
+ if {finish!r} and st.get("taken") and argv[:3] == ["api", "-X", "DELETE"] and argv[3].endswith("/labels/needs-human") \
41
+ and not st.get("s2done"):
42
+ # s2 finishes its own handoff after s1's repair put babysitting back, right before s1's
43
+ # repair removes needs-human: that removal lands over s2's completed handoff.
44
+ st["s2done"] = True
45
+ state.write_text(json.dumps(st))
46
+ if {finish!r} == "paused":
47
+ # s2 has posted its handoff and written its labels but has not released its lease yet.
48
+ base = ["api", "-X"]
49
+ issue = "repos/jesdi/demo/issues/58"
50
+ for call in (["POST", issue + "/comments", "-f", "body=## 🧑 Needs human: done\\n"],
51
+ ["POST", issue + "/labels", "-f", "labels[]=needs-human"]):
52
+ subprocess.run([{real!r}, *base, *call], check=True, stdout=subprocess.DEVNULL)
53
+ subprocess.run([{real!r}, *base, "DELETE", issue + "/labels/babysitting"], check=True,
54
+ stdout=subprocess.DEVNULL)
55
+ else:
56
+ subprocess.run([sys.executable, {script!r}, "handoff", "--repo", "jesdi/demo", "--pr", "58",
57
+ "--reason", "done", "--ci", "green", "--rounds", "0", "--gate", "gate: human",
58
+ "--judge", "judge: not run", "--fix-log", {body!r}, "--session", "s2"],
59
+ check=True, stdout=subprocess.DEVNULL)
60
+ rc = subprocess.run([{real!r}, *argv]).returncode
61
+ sys.exit(rc)
62
+ '''
63
+
64
+
65
+ def takeover_before_label_write(w, finish_as_s2=False):
66
+ """finish_as_s2: True runs s2's whole handoff; "paused" stops it just before the lease release."""
67
+ fake = w.project.parent / "bin" / "gh"
68
+ real = fake.with_name("gh-real")
69
+ fake.rename(real)
70
+ fake.write_text(WRAPPER.format(script=str(SCRIPT), real=str(real), finish=finish_as_s2,
71
+ body=str(w.project.parent / "body.md")))
72
+ fake.chmod(0o755)
73
+
74
+
75
+ def holder(w):
76
+ return [lease[1] for lease in w.active_leases()]
77
+
78
+
79
+ def test_handoff_after_takeover_leaves_the_new_holders_labels_and_reports_it(tmp_path):
80
+ w = world(tmp_path, repo_labels=["babysitting", "needs-human"])
81
+ assert w.run("acquire", "s1").returncode == 0
82
+ takeover_before_label_write(w)
83
+ p = handoff(w, "--session", "s1")
84
+ assert w.github().get("taken"), "the takeover never fired"
85
+ assert holder(w) == ["s2"]
86
+ labels = w.github()["labels"]
87
+ assert "babysitting" in labels and "needs-human" not in labels
88
+ assert len(handoffs(w)) == 1
89
+ assert p.returncode != 0, p.output
90
+ assert "taken over" in p.output.lower()
91
+
92
+
93
+ def test_merge_after_takeover_leaves_the_new_holders_labels_and_reports_it(tmp_path):
94
+ w = world(tmp_path, repo_labels=["babysitting", "needs-human"])
95
+ assert w.run("acquire", "s1").returncode == 0
96
+ takeover_before_label_write(w)
97
+ p = merge(w, tmp_path, "a1b2c3d", "--judge", "agree", "--session", "s1")
98
+ assert w.github().get("taken"), "the takeover never fired"
99
+ assert len(w.github()["merges"]) == 1
100
+ assert holder(w) == ["s2"]
101
+ labels = w.github()["labels"]
102
+ assert "babysitting" in labels and "needs-human" not in labels
103
+ assert "taken over" in p.output.lower()
104
+
105
+
106
+ def test_handoff_without_takeover_ends_with_needs_human_and_no_babysitting(tmp_path):
107
+ w = world(tmp_path, repo_labels=["babysitting", "needs-human"])
108
+ assert w.run("acquire", "s1").returncode == 0
109
+ p = handoff(w, "--session", "s1")
110
+ assert p.returncode == 0, p.output
111
+ assert "taken over" not in p.output.lower()
112
+ labels = w.github()["labels"]
113
+ assert "needs-human" in labels and "babysitting" not in labels
114
+ assert len(handoffs(w)) == 1
115
+ assert holder(w) == []
116
+
117
+
118
+ def test_new_holders_own_handoff_survives_the_repair_of_a_stale_handoff(tmp_path):
119
+ w = world(tmp_path, repo_labels=["babysitting", "needs-human"])
120
+ assert w.run("acquire", "s1").returncode == 0
121
+ takeover_before_label_write(w, finish_as_s2=True)
122
+ p = handoff(w, "--session", "s1")
123
+ assert w.github().get("s2done"), "s2 never finished its handoff"
124
+ labels = w.github()["labels"]
125
+ assert "needs-human" in labels and "babysitting" not in labels, labels
126
+ assert holder(w) == []
127
+ assert len(handoffs(w)) == 2
128
+ assert p.returncode != 0, p.output
129
+ assert "taken over" in p.output.lower()
130
+
131
+
132
+ def test_new_holders_handoff_survives_the_repair_while_its_lease_is_still_active(tmp_path):
133
+ w = world(tmp_path, repo_labels=["babysitting", "needs-human"])
134
+ assert w.run("acquire", "s1").returncode == 0
135
+ takeover_before_label_write(w, finish_as_s2="paused")
136
+ p = handoff(w, "--session", "s1")
137
+ assert w.github().get("s2done"), "s2 never posted its handoff"
138
+ labels = w.github()["labels"]
139
+ assert "needs-human" in labels and "babysitting" not in labels, labels
140
+ assert holder(w) == ["s2"]
141
+ assert "taken over" in p.output.lower()
@@ -0,0 +1,29 @@
1
+ """Completed handoffs identify themselves even when merge exits with an error."""
2
+ import json
3
+
4
+ from test_merge_and_handoff import cli, merge, world
5
+
6
+
7
+ def test_direct_handoff_returns_terminal_notification_instruction(tmp_path):
8
+ w = world(tmp_path)
9
+ fix_log = tmp_path / "fix-log.md"
10
+ fix_log.write_text("No changes pushed.")
11
+ p = cli(w, "handoff", "--repo", "jesdi/demo", "--pr", "58",
12
+ "--reason", "cannot reproduce", "--ci", "red", "--rounds", "1",
13
+ "--gate", "not run", "--judge", "not run", "--fix-log", str(fix_log))
14
+ assert p.returncode == 0, p.output
15
+ result = json.loads(p.stdout)
16
+ assert result["terminal"] is True and result["status"] == "handoff"
17
+ assert result["reason"] == "cannot reproduce"
18
+ assert "PushNotification" in result["next"]
19
+
20
+
21
+ def test_merge_handoff_is_terminal_despite_error_exit(tmp_path):
22
+ w = world(tmp_path)
23
+ p = merge(w, tmp_path, "a1b2c3d", "--judge", "disagree")
24
+ assert p.returncode != 0
25
+ result = json.loads(p.stdout)
26
+ assert result["terminal"] is True and result["status"] == "handoff"
27
+ assert result["reason"] == "judge disagree"
28
+ assert "end the turn" in result["next"]
29
+ assert not w.github().get("merges")
@@ -0,0 +1,25 @@
1
+ import pytest
2
+
3
+ from test_hooks import OK, URL, context, repo, run
4
+
5
+
6
+ @pytest.mark.parametrize("codex", [False, True])
7
+ @pytest.mark.parametrize("body", [
8
+ '"text --draft text"',
9
+ '"hello ; world"',
10
+ "'hello ; world'",
11
+ '";"',
12
+ r'hello\;world',
13
+ 'hello" ; "world',
14
+ r'"hello \" ; world"',
15
+ ])
16
+ def test_attached_body_preserves_shell_quoting(repo, codex, body):
17
+ command = f"gh pr create --title x --body={body}"
18
+ assert f"/babysit-pr {URL}" in context(run(repo, command, OK, codex))
19
+ assert run(repo, command + " --draft", OK, codex) == ""
20
+
21
+
22
+ @pytest.mark.parametrize("separator", [";", "&&", "||", "\n", "|"])
23
+ def test_unquoted_operator_still_separates_commands(repo, separator):
24
+ command = f'echo x{separator}gh pr create --body="hello ; world"'
25
+ assert f"/babysit-pr {URL}" in context(run(repo, command, OK))
@@ -0,0 +1,62 @@
1
+ import json
2
+ import subprocess
3
+ from pathlib import Path
4
+
5
+ import pytest
6
+
7
+ HOOK = Path(__file__).parent / "hooks" / "post-pr-create.sh"
8
+ URL = "https://github.com/jesdi/demo/pull/58"
9
+
10
+
11
+ @pytest.fixture
12
+ def repo(tmp_path):
13
+ (tmp_path / ".merge-risk.json").write_text("{}")
14
+ return tmp_path
15
+
16
+
17
+ def run(cwd, command, response, codex=False):
18
+ """Feed one PostToolUse payload to the hook; return its stdout."""
19
+ if codex:
20
+ response = response["stdout"] if isinstance(response, dict) else response
21
+ payload = {
22
+ "hook_event_name": "PostToolUse",
23
+ "tool_name": "Bash",
24
+ "tool_input": {"command": command},
25
+ "tool_response": response,
26
+ "cwd": str(cwd),
27
+ }
28
+ p = subprocess.run(["bash", str(HOOK)], input=json.dumps(payload),
29
+ capture_output=True, text=True)
30
+ assert p.returncode == 0, p.stderr
31
+ return p.stdout.strip()
32
+
33
+
34
+ OK = {"stdout": f"Creating pull request\n{URL}\n", "stderr": "", "interrupted": False}
35
+
36
+
37
+ def context(out):
38
+ out = json.loads(out)["hookSpecificOutput"]
39
+ assert out["hookEventName"] == "PostToolUse"
40
+ return out["additionalContext"]
41
+
42
+
43
+ @pytest.mark.parametrize("codex", [False, True])
44
+ def test_created_pr_tells_agent_to_babysit(repo, codex):
45
+ out = run(repo, "gh pr create --title x --body y", OK, codex)
46
+ assert f"/babysit-pr {URL}" in context(out)
47
+
48
+
49
+ @pytest.mark.parametrize("codex", [False, True])
50
+ def test_draft_adds_nothing(repo, codex):
51
+ assert run(repo, "gh pr create --draft --title x --body y", OK, codex) == ""
52
+
53
+
54
+ @pytest.mark.parametrize("codex", [False, True])
55
+ def test_failed_create_adds_nothing(repo, codex):
56
+ failed = {"stdout": "", "stderr": "GraphQL: error\n", "interrupted": False}
57
+ assert run(repo, "gh pr create --title x --body y", failed, codex) == ""
58
+
59
+
60
+ @pytest.mark.parametrize("codex", [False, True])
61
+ def test_repo_without_policy_adds_nothing(tmp_path, codex):
62
+ assert run(tmp_path, "gh pr create --title x --body y", OK, codex) == ""
@@ -0,0 +1,198 @@
1
+ """Lease election, durable history, and deterministic CLI race regressions."""
2
+ import json
3
+ import subprocess
4
+ import sys
5
+ import time
6
+
7
+ import pytest
8
+
9
+ from test_babysit import MIN, SCRIPT, T, World, lease_comment
10
+
11
+
12
+ def test_renew_keeps_lowest_id_when_a_losing_claim_is_pending(tmp_path):
13
+ w = World(tmp_path, comments=[
14
+ lease_comment(1001, "s1", "mac", T, T + 85 * MIN),
15
+ lease_comment(1002, "s2", "mac2", T, T + 85 * MIN)])
16
+ p = w.run("renew", "s1")
17
+ assert p.returncode == 0, p.output
18
+ assert w.run("check", "s1").returncode == 0
19
+ assert w.run("check", "s2").returncode != 0
20
+
21
+
22
+ @pytest.mark.parametrize("already_ended", [False, True])
23
+ def test_release_handoff_keeps_rounds_and_failure_signatures(tmp_path, already_ended):
24
+ history = "rounds: 3\nsignature: test_empty AssertionError"
25
+ w = World(tmp_path, comments=[
26
+ lease_comment(1001, "s1", "mac", T, T + 85 * MIN,
27
+ rest="ended\n" + history if already_ended else history)])
28
+ if not already_ended:
29
+ assert w.run("release", "s1").returncode == 0
30
+ p = w.run("acquire", "s2")
31
+ assert p.returncode == 0, p.output
32
+ assert history in w.comment(1002)["body"]
33
+ assert "ended" not in w.comment(1002)["body"]
34
+
35
+
36
+ def install_pause_wrapper(w):
37
+ """Pause selected gh calls before dispatching to the unchanged fixture."""
38
+ gh = w.home.parent / "bin" / "gh"
39
+ real = gh.with_name("gh-real")
40
+ gh.rename(real)
41
+ gh.write_text("""#!/usr/bin/env python3
42
+ import json
43
+ import os
44
+ from pathlib import Path
45
+ import sys
46
+ import time
47
+ match = json.loads(os.environ.get("GH_PAUSE_MATCH", "[]"))
48
+ if match and all(part in " ".join(sys.argv[1:]) for part in match):
49
+ prefix = Path(os.environ["GH_PAUSE_PREFIX"])
50
+ prefix.with_suffix(".ready").touch()
51
+ deadline = time.monotonic() + 20
52
+ while not prefix.with_suffix(".resume").exists():
53
+ if time.monotonic() > deadline:
54
+ sys.exit("pause timed out")
55
+ time.sleep(0.01)
56
+ os.execv(str(Path(__file__).with_name("gh-real")), sys.argv)
57
+ """)
58
+ gh.chmod(0o755)
59
+
60
+
61
+ def start(w, verb, session, prefix, match):
62
+ # These election races model separate hosts. Same-host writers serialize on
63
+ # the home-directory lock, so each simulated host needs its own home.
64
+ home = w.home.parent / f"home-{session}"
65
+ (home / ".agents/skills/pr-risk").mkdir(parents=True, exist_ok=True)
66
+ return subprocess.Popen(
67
+ [sys.executable, str(SCRIPT), "lease", verb, "--repo", "jesdi/demo",
68
+ "--pr", "58", "--session", session, "--host", "mac2"],
69
+ cwd=w.project, env={**w.env, "HOME": str(home), "GH_PAUSE_PREFIX": str(prefix),
70
+ "GH_PAUSE_MATCH": json.dumps(match)},
71
+ text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
72
+
73
+
74
+ def wait_paused(process, prefix):
75
+ deadline = time.monotonic() + 10
76
+ while not prefix.with_suffix(".ready").exists():
77
+ assert process.poll() is None, process.communicate()
78
+ assert time.monotonic() < deadline, "CLI never reached the requested pause"
79
+ time.sleep(0.01)
80
+
81
+
82
+ def resume(process, prefix):
83
+ prefix.with_suffix(".resume").touch()
84
+ output = process.communicate(timeout=10)
85
+ return process.returncode, output
86
+
87
+
88
+ def test_takeover_cleanup_cannot_displace_a_successful_renewal(tmp_path):
89
+ w = World(tmp_path, comments=[
90
+ lease_comment(1001, "s1", "mac", T - 89 * MIN, T + MIN)])
91
+ install_pause_wrapper(w)
92
+ renew_pause, cleanup_pause = tmp_path / "renew", tmp_path / "cleanup"
93
+ renew = start(w, "renew", "s1", renew_pause, ["PATCH", "issues/comments/1001"])
94
+ acquire = None
95
+ try:
96
+ wait_paused(renew, renew_pause)
97
+ w.set_now(T + 2 * MIN)
98
+ acquire = start(w, "acquire", "s2", cleanup_pause,
99
+ ["PATCH", "issues/comments/1001", "ended"])
100
+ wait_paused(acquire, cleanup_pause)
101
+ renewal_status, output = resume(renew, renew_pause)
102
+ acquisition_status, acquisition_output = resume(acquire, cleanup_pause)
103
+ assert acquisition_status == 0, acquisition_output
104
+ assert renewal_status != 0, output
105
+ assert w.run("check", "s2").returncode == 0
106
+ assert w.run("check", "s1").returncode != 0
107
+ finally:
108
+ for process in (renew, acquire):
109
+ if process is not None and process.poll() is None:
110
+ process.kill()
111
+ process.communicate()
112
+
113
+
114
+ def test_renewal_completed_before_takeover_post_wins(tmp_path):
115
+ w = World(tmp_path, comments=[
116
+ lease_comment(1001, "s1", "mac", T - 89 * MIN, T + MIN)])
117
+ install_pause_wrapper(w)
118
+ renew_pause, post_pause = tmp_path / "renew", tmp_path / "post"
119
+ renew = start(w, "renew", "s1", renew_pause, ["PATCH", "issues/comments/1001"])
120
+ acquire = None
121
+ try:
122
+ wait_paused(renew, renew_pause)
123
+ w.set_now(T + 2 * MIN)
124
+ acquire = start(w, "acquire", "s2", post_pause, ["POST", "issues/58/comments"])
125
+ wait_paused(acquire, post_pause)
126
+ status, output = resume(renew, renew_pause)
127
+ assert status == 0, output
128
+ renewed = w.comment(1001)
129
+ status, output = resume(acquire, post_pause)
130
+ assert status != 0, output
131
+ assert w.comment(1001) == renewed
132
+ assert w.run("check", "s1").returncode == 0
133
+ finally:
134
+ for process in (renew, acquire):
135
+ if process is not None and process.poll() is None:
136
+ process.kill()
137
+ process.communicate()
138
+
139
+
140
+ def test_check_reads_github_time_after_comments_during_takeover(tmp_path):
141
+ w = World(tmp_path, comments=[
142
+ lease_comment(1001, "s1", "mac", T - 89 * MIN, T + MIN)])
143
+ install_pause_wrapper(w)
144
+ check_pause, cleanup_pause = tmp_path / "check", tmp_path / "cleanup"
145
+ check = start(w, "check", "s1", check_pause, ["issues/58/comments"])
146
+ acquire = None
147
+ try:
148
+ wait_paused(check, check_pause)
149
+ w.set_now(T + 2 * MIN)
150
+ acquire = start(w, "acquire", "s2", cleanup_pause,
151
+ ["PATCH", "issues/comments/1001", "ended"])
152
+ wait_paused(acquire, cleanup_pause)
153
+ status, output = resume(check, check_pause)
154
+ assert status != 0, output
155
+ status, output = resume(acquire, cleanup_pause)
156
+ assert status == 0, output
157
+ assert w.run("check", "s2").returncode == 0
158
+ finally:
159
+ for process in (check, acquire):
160
+ if process is not None and process.poll() is None:
161
+ process.kill()
162
+ process.communicate()
163
+
164
+
165
+ def test_losing_claim_cannot_replace_previous_holders_durable_history(tmp_path):
166
+ w = World(tmp_path)
167
+ assert w.run("acquire", "s1").returncode == 0
168
+ # Hide s1 from s2's first read, as if s1 posted just after that read.
169
+ state = w.github()
170
+ state.update(posted=False, hidden_until_post=[1001])
171
+ w.state.write_text(json.dumps(state))
172
+ assert w.run("acquire", "s2").returncode != 0
173
+ history = "rounds: 3\nsignature: test_empty AssertionError"
174
+ state = w.github()
175
+ state["comments"][0]["body"] = state["comments"][0]["body"].replace("rounds: 0", history)
176
+ w.state.write_text(json.dumps(state))
177
+ w.set_now(T + 91 * MIN)
178
+ p = w.run("acquire", "s3")
179
+ assert p.returncode == 0, p.output
180
+ assert history in w.comment(1003)["body"]
181
+
182
+
183
+ @pytest.mark.parametrize("resume_verb", [None, "acquire", "renew"])
184
+ def test_pending_claim_history_requires_successful_ownership(tmp_path, resume_verb):
185
+ history = "rounds: 3\nsignature: test_empty AssertionError"
186
+ pending = "<!-- babysit-pr claim: pending -->\n"
187
+ w = World(tmp_path, comments=[
188
+ lease_comment(1001, "s1", "mac", T - 91 * MIN, T - MIN, rest=history),
189
+ lease_comment(1002, "s2", "mac2", T, T + 90 * MIN,
190
+ rest=pending + "rounds: 4\nsignature: newer failure")])
191
+ if resume_verb:
192
+ p = w.run(resume_verb, "s2")
193
+ assert p.returncode == 0, p.output
194
+ history = "rounds: 4\nsignature: newer failure"
195
+ w.set_now(T + 91 * MIN)
196
+ p = w.run("acquire", "s3")
197
+ assert p.returncode == 0, p.output
198
+ assert history in w.comment(1003)["body"]