@jesdi/skills 0.0.62 → 0.0.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +15 -0
  2. package/package.json +2 -2
  3. package/skills/babysit-pr/SKILL.md +54 -0
  4. package/skills/babysit-pr/babysit.py +998 -0
  5. package/skills/babysit-pr/fixtures/gh +310 -0
  6. package/skills/babysit-pr/hooks/post-pr-create.sh +56 -0
  7. package/skills/babysit-pr/hooks.json +10 -0
  8. package/skills/babysit-pr/judge-prompt.md +10 -0
  9. package/skills/babysit-pr/test_babysit.py +242 -0
  10. package/skills/babysit-pr/test_babysit_judge.py +286 -0
  11. package/skills/babysit-pr/test_babysit_judge_diff.py +25 -0
  12. package/skills/babysit-pr/test_babysit_judge_isolation.py +61 -0
  13. package/skills/babysit-pr/test_checks_regressions.py +210 -0
  14. package/skills/babysit-pr/test_comment_fidelity.py +88 -0
  15. package/skills/babysit-pr/test_comment_identity.py +70 -0
  16. package/skills/babysit-pr/test_e2e_setup.py +74 -0
  17. package/skills/babysit-pr/test_handoff_takeover.py +141 -0
  18. package/skills/babysit-pr/test_handoff_terminal.py +29 -0
  19. package/skills/babysit-pr/test_hook_quoting.py +25 -0
  20. package/skills/babysit-pr/test_hooks.py +62 -0
  21. package/skills/babysit-pr/test_lease_regressions.py +198 -0
  22. package/skills/babysit-pr/test_merge_and_handoff.py +260 -0
  23. package/skills/babysit-pr/test_merge_base_pin.py +10 -0
  24. package/skills/babysit-pr/test_merge_gate.py +124 -0
  25. package/skills/babysit-pr/test_merge_session_safety.py +117 -0
  26. package/skills/babysit-pr/test_merged_pr_labels.py +144 -0
  27. package/skills/babysit-pr/test_owner_comment_edits.py +26 -0
  28. package/skills/babysit-pr/test_owner_comments.py +316 -0
  29. package/skills/babysit-pr/test_retry_and_stall_hardening.py +143 -0
  30. package/skills/babysit-pr/test_rounds_and_checks.py +305 -0
  31. package/skills/babysit-pr/test_terminal_label_regressions.py +117 -0
  32. package/skills/babysit-pr/test_trusted_merge_risk.py +184 -0
  33. package/skills/babysit-pr/test_update_plan.py +157 -0
  34. package/skills/implement-spec/ARCHITECTURE.md +5 -0
  35. package/skills/implement-spec/README.md +7 -6
  36. package/skills/implement-spec/SKILL.md +1 -1
  37. package/skills/implement-spec/driver.py +11 -1
  38. package/skills/implement-spec/driver_decisions.py +23 -0
  39. package/skills/implement-spec/driver_final.py +49 -10
  40. package/skills/implement-spec/driver_fixloop.py +17 -5
  41. package/skills/implement-spec/driver_report.py +16 -5
  42. package/skills/implement-spec/driver_state.py +2 -2
  43. package/skills/implement-spec/prompts/pr-writer.md +3 -2
  44. package/skills/implement-spec/prompts/rejected.md +1 -0
  45. package/skills/implement-spec/tests/test_decisions.py +57 -0
  46. package/skills/implement-spec/tests/test_final.py +112 -1
  47. package/skills/implement-spec/tests/test_fixloop.py +14 -2
  48. package/skills/implement-spec/tests/test_report.py +18 -0
  49. package/skills/implement-spec/tests/test_review.py +1 -1
  50. package/skills/implement-spec/tests/test_state.py +1 -1
  51. package/skills/implement-spec/tests/test_tidy.py +2 -2
  52. package/skills/implement-spec/tests/test_walk.py +2 -2
  53. package/skills/pr-risk/SKILL.md +33 -0
  54. package/skills/pr-risk/hooks/pre-pr-create.sh +274 -0
  55. package/skills/pr-risk/hooks.json +10 -0
  56. package/skills/pr-risk/merge_policy.py +81 -0
  57. package/skills/pr-risk/merge_risk.py +314 -0
  58. package/skills/pr-risk/test_hook_commands.py +47 -0
  59. package/skills/pr-risk/test_hook_heredoc.py +16 -0
  60. package/skills/pr-risk/test_hook_substitution.py +40 -0
  61. package/skills/pr-risk/test_hooks.py +175 -0
  62. package/skills/pr-risk/test_merge_risk.py +97 -0
  63. package/skills/pr-risk/test_merge_risk_gate.py +217 -0
  64. package/skills/pr-risk/test_merge_risk_regressions.py +37 -0
  65. package/skills/pr-risk/test_merge_risk_structure.py +101 -0
  66. package/skills-manifest.json +15 -3
@@ -569,3 +569,60 @@ def test_a_fixer_that_stops_asks_the_operator_and_retry_runs_its_round_again(tmp
569
569
  assert rig.code == 0 and rig.state()["tickets"]["01"]["phase"] == "merged", rig.ledger()
570
570
  assert rig.state()["tickets"]["01"]["round"] == 1 and len(rig.calls("01", "fixer")) == 2
571
571
  assert rig.led("Ruling: 01 fix round runs again (retry): the fixer reported NEEDS_CONTEXT")
572
+
573
+
574
+ # ---------------------------------------------------------------- a review report rejected twice; a question of a merged ticket
575
+
576
+ REJECTED = "01-review-rejected-1"
577
+ NO_PROOF = "mutations: no mutation proof for the locked test file tests/test_01b.py"
578
+
579
+
580
+ def test_a_review_report_rejected_twice_asks_the_operator_and_retry_resumes_it(tmp_path):
581
+ """Issue #136: a reviewer that gave no mutation proof for a second locked file, two times, was a dead end."""
582
+ # Both attempts give a proof for tests/test_01.py only; the third reviewer is the unscripted one, with every proof.
583
+ steps = plan(**{"01/test-writer": [two_locked()], "01/reviewer": [review("01"), review("01")]})
584
+ rig = Inside(tmp_path, ONE).run(steps)
585
+ assert rig.code == 2 and rig.state()["tickets"]["01"]["phase"] == "blocked", rig.ledger()
586
+ (question,) = rig.state()["run"]["questions"]
587
+ assert (question["id"], question["recommended"]) == (REJECTED, "retry")
588
+ assert [o["id"] for o in question["options"]] == ["retry", "redesign"]
589
+ assert question["evidence"][0] == ".agent/implement/01/reviewer-0.json"
590
+ assert question["subject"] == f"the reviewer: {NO_PROOF}"
591
+ rig.run(steps, "--answer", f"{REJECTED}=retry")
592
+ assert rig.code == 0 and rig.state()["tickets"]["01"]["phase"] == "merged", rig.ledger()
593
+ assert len(rig.calls("01", "reviewer")) == 3
594
+ assert rig.led(f"Ruling: 01 review runs again (retry): the reviewer: {NO_PROOF}")
595
+ assert NO_PROOF in rig.calls("01", "reviewer")[2]["prompt"]
596
+
597
+
598
+ def test_a_test_writer_report_that_locks_a_file_it_deleted_is_rejected(tmp_path):
599
+ """Issue #136: the correction of ticket 21 deleted a locked file and still listed it in `locked`; the driver
600
+ accepted it, and no reviewer could prove that file."""
601
+ deleted = two_locked()
602
+ deleted["git_after"] = [["add", "-A"], ["commit", "-q", "-m", "test: 01 both"], ["rm", "-q", "tests/test_01b.py"]]
603
+ rig = Inside(tmp_path, ONE).run(plan(**{"01/test-writer": [deleted, two_locked()]}))
604
+ assert rig.code == 0 and rig.state()["tickets"]["01"]["phase"] == "merged", rig.ledger()
605
+ assert rig.led("Ticket 01: test-writer ran on", "locked path tests/test_01b.py is not a file at the tip of")
606
+ assert len(rig.calls("01", "test-writer")) == 2 and len(rig.calls("01", "reviewer")) == 1
607
+
608
+
609
+ def test_a_question_of_a_ticket_that_merged_is_dropped_and_does_not_park_the_run(tmp_path, capsys):
610
+ """Issue #136: the operator set a stopped ticket to `merge` by hand; its question stayed open, with exit 2."""
611
+ rig = Inside(tmp_path, ONE).run(steps(stops()))
612
+ assert rig.code == 2, rig.ledger()
613
+ capsys.readouterr()
614
+ path = rig.repo / ".agent/implement/state.json"
615
+ state = json.loads(path.read_text())
616
+ state["tickets"]["01"]["phase"] = "merge"
617
+ path.write_text(json.dumps(state))
618
+ rig.run(steps(stops()))
619
+ assert rig.code == 0 and rig.state()["tickets"]["01"]["phase"] == "merged", rig.ledger()
620
+ assert decisions(rig)["questions"] == [] and IMPLEMENTER_STOPPED not in capsys.readouterr().out
621
+ assert rig.led(f"Ticket 01: the question {IMPLEMENTER_STOPPED} is dropped: the ticket merged.")
622
+
623
+
624
+ def test_dropping_the_questions_of_merged_tickets_keeps_the_answered_ones_and_those_of_other_tickets():
625
+ state = {"tickets": {"01": {"phase": "merged"}, "02": {"phase": "blocked"}},
626
+ "run": {"questions": [asked(), {**asked(stop=2), "id": "01-x", "answer": "accept"}, asked(ticket="02")]}}
627
+ assert [q["id"] for q in driver_decisions.drop_merged(state)] == ["01-locked-test-1"]
628
+ assert [q["id"] for q in state["run"]["questions"]] == ["01-x", "02-locked-test-1"]
@@ -24,13 +24,14 @@ Interface choices (ticket 06):
24
24
  """
25
25
  import json
26
26
  import re
27
+ import shutil
27
28
  import subprocess
28
29
  import sys
29
30
  from types import SimpleNamespace
30
31
 
31
32
  import pytest
32
33
 
33
- from test_cli import git, ticket
34
+ from test_cli import SKILL, git, ticket
34
35
  from test_review import FABLE, HOOKED, ONE, OPUS, Review, finding, gate_rule, review
35
36
  from test_stops import UNATTENDED, decisions, stage
36
37
  from test_walk import impl, plan, tw
@@ -445,3 +446,113 @@ def test_unattended_with_a_blocked_ticket_pushes_nothing_and_exits_1(tmp_path):
445
446
  assert rig.code == 1, rig.output()
446
447
  assert rig.pushes() == [] and not rig.prs() and not ref(rig.origin, "refs/heads/feat/csv")
447
448
  assert stage(rig) == {"stage": "implement", "status": "blocked", "blocked": ["01"]}
449
+
450
+
451
+ # ---------------------------------------------------------------- the merge-risk block of the PR body (ticket 15)
452
+
453
+ PR_RISK = SKILL.parent / "pr-risk"
454
+ BLOCK = ("door: two-way\nblast_radius: isolated\ntouches: [%s]\nrollback: revert\nverdict: auto\n"
455
+ "reasons:\n - \"Only prose changes\"\n")
456
+
457
+
458
+ def risk_body(touches="docs"):
459
+ return ("## Summary\n\nCSV export.\n\n## Merge Danger\n\n```merge-risk v1\n" + BLOCK % touches + "```\n")
460
+
461
+
462
+ def writer(body):
463
+ return {"report": dict(status="DONE", commits=[], files=[], concerns=[], body=body)}
464
+
465
+
466
+ def risk_valid(tmp_path, body):
467
+ f = tmp_path / "check-body.md"
468
+ f.write_text(body)
469
+ return subprocess.run([sys.executable, str(PR_RISK / "merge_risk.py"), "validate", str(f)],
470
+ capture_output=True, text=True).returncode == 0
471
+
472
+
473
+ def pushed_run(tmp_path, monkeypatch, steps, risk_in, gh_fails=False):
474
+ """`implement-spec` as installed (a copy next to review-diff) with `pr` installed in `risk_in`'s home, and
475
+ `pr-risk` there too unless `risk_in` is None; the run is `--push`."""
476
+ rig = Final(tmp_path, ONE)
477
+ if gh_fails:
478
+ (tmp_path / "bin/gh").write_text("#!/bin/sh\necho gh down >&2\nexit 1\n")
479
+ skills = tmp_path / "installed/skills"
480
+ shutil.copytree(SKILL, skills / "implement-spec", ignore=shutil.ignore_patterns("__pycache__", ".pytest_cache", "test_*"))
481
+ shutil.copytree(SKILL.parent / "review-diff", skills / "review-diff", ignore=shutil.ignore_patterns("__pycache__"))
482
+ home = tmp_path / "home"
483
+ claude = tmp_path / "claude-home"
484
+ claude.mkdir(), home.mkdir()
485
+ where = {"claude": claude / "skills", "agents": home / ".agents/skills", None: claude / "skills"}[risk_in]
486
+ names = ["pr", "pr-risk"] if risk_in else ["pr"]
487
+ for name in names:
488
+ (where / name).mkdir(parents=True)
489
+ (where / name / "SKILL.md").write_text(f"---\nname: {name}\n---\n")
490
+ if risk_in:
491
+ for module in ("merge_risk.py", "merge_policy.py"):
492
+ shutil.copy(PR_RISK / module, where / "pr-risk" / module)
493
+ env = {**rig.env, "HOME": str(home), "CLAUDE_CONFIG_DIR": str(claude)}
494
+ (rig.rig / "plan.json").write_text(json.dumps(steps))
495
+ args = ["--tickets", ".agent/tickets", "--gate", str(rig.rig / "gate"), "--spec", "specs/csv/spec.md",
496
+ "--models", str(rig.models), "--runner", str(rig.rig / "run-agent"), "--push"]
497
+ rig.rerun = lambda: _rerun(rig, ["sh", str(skills / "implement-spec/run.sh"), *args], env)
498
+ rig.rerun()
499
+ return rig, where / "pr-risk/SKILL.md"
500
+
501
+
502
+ def _rerun(rig, cmd, env):
503
+ proc = subprocess.run(cmd, cwd=rig.repo, env=env, text=True, capture_output=True, timeout=180)
504
+ rig.code, rig.out = proc.returncode, proc.stdout + proc.stderr
505
+
506
+
507
+ @pytest.mark.parametrize("home", ["claude", "agents"])
508
+ def test_the_pr_writer_gets_the_pr_risk_path_and_the_pr_opens_with_a_valid_block_above_the_facts(tmp_path, monkeypatch, home):
509
+ rig, skill = pushed_run(tmp_path, monkeypatch, plan(**{"final/pr-writer": [writer(risk_body())]}), home)
510
+ assert rig.code == 0, rig.out
511
+ (call,) = rig.final_calls("pr-writer")
512
+ assert str(skill) in call["prompt"]
513
+ (pr,) = rig.prs()
514
+ body = pr["body"]
515
+ assert risk_valid(tmp_path, body), body
516
+ assert 0 <= body.index("## Merge Danger") < body.index("## Tickets"), "the driver's facts come after the block"
517
+
518
+
519
+ def test_without_pr_risk_installed_the_run_is_blocked_with_the_install_command_and_pushes_nothing(tmp_path, monkeypatch):
520
+ rig, _ = pushed_run(tmp_path, monkeypatch, plan(), None)
521
+ assert rig.code != 0 and "pr-risk" in rig.out and "install" in rig.out.lower(), rig.out
522
+ assert re.search(r"npx [^\n]*pr-risk", rig.out), f"no executable install command: {rig.out}"
523
+ assert rig.pushes() == [] and not rig.prs() and not rig.final_calls("pr-writer")
524
+
525
+
526
+ def test_an_invalid_first_body_runs_the_pr_writer_once_more_and_a_valid_second_body_opens_the_pr(tmp_path, monkeypatch):
527
+ steps = plan(**{"final/pr-writer": [writer(risk_body("styles")), writer(risk_body())]})
528
+ rig, _ = pushed_run(tmp_path, monkeypatch, steps, "claude")
529
+ assert rig.code == 0, rig.out
530
+ assert len(rig.final_calls("pr-writer")) == 2
531
+ (pr,) = rig.prs()
532
+ assert risk_valid(tmp_path, pr["body"]) and "styles" not in pr["body"].split("## Tickets")[0]
533
+
534
+
535
+ def test_an_invalid_second_body_blocks_the_run_and_opens_no_pr(tmp_path, monkeypatch):
536
+ steps = plan(**{"final/pr-writer": [writer(risk_body("styles")), writer(risk_body("styles")), writer(risk_body())]})
537
+ rig, _ = pushed_run(tmp_path, monkeypatch, steps, "claude")
538
+ assert rig.code != 0, rig.out
539
+ assert len(rig.final_calls("pr-writer")) == 2 and not rig.prs()
540
+
541
+
542
+ def test_skill_md_step_2_tells_the_operator_to_start_the_babysitter_on_the_pr_url():
543
+ step = next(l for l in (SKILL / "SKILL.md").read_text().splitlines() if l.startswith("2. "))
544
+ assert "/babysit-pr https://github.com/jesdi/demo/pull/61" in step
545
+
546
+
547
+ def test_a_cached_body_that_no_longer_validates_is_rewritten_before_gh_pr_create_on_resume(tmp_path, monkeypatch):
548
+ steps = plan(**{"final/pr-writer": [writer(risk_body()), writer(risk_body())]})
549
+ rig, _ = pushed_run(tmp_path, monkeypatch, steps, "claude", gh_fails=True)
550
+ assert rig.code != 0 and "gh pr create failed" in rig.out and len(rig.final_calls("pr-writer")) == 1, rig.out
551
+ cached = rig.repo / ".agent/implement/final/pr-body.md"
552
+ cached.write_text(cached.read_text().replace("touches: [docs]", "touches: [styles]"))
553
+ (tmp_path / "bin/gh").write_text(GH)
554
+ rig.rerun()
555
+ assert rig.code == 0, rig.out
556
+ assert len(rig.final_calls("pr-writer")) == 2, "the invalid cached body was not rewritten"
557
+ (pr,) = rig.prs()
558
+ assert risk_valid(tmp_path, pr["body"].split("## Tickets")[0]) and "styles" not in pr["body"].split("## Tickets")[0]
@@ -16,6 +16,7 @@ import driver_report
16
16
  import driver_run
17
17
  import driver_review
18
18
  import test_review
19
+ from conftest import GIT
19
20
  from test_cli import three
20
21
  from test_review import FABLE, ONE, OPUS, RISKY, SOL, STUCK, correct, finding, fix, review
21
22
  from test_walk import impl, plan, tw
@@ -812,7 +813,10 @@ def test_a_fixer_that_does_not_finish_blocks_the_ticket_in_its_round(tmp_path):
812
813
 
813
814
  def test_a_first_review_proves_each_locked_file_and_a_second_bad_report_blocks(tmp_path):
814
815
  rig = Inside(tmp_path).run(plan(**{"01/reviewer": [review("01", lines=())] * 2}))
815
- assert "BLOCKED at the review: the reviewer: mutations: no mutation proof for the locked test file tests/test_01.py." in blocked(rig)
816
+ assert rig.code == 2 and rig.state()["tickets"]["01"]["phase"] == "blocked", rig.ledger()
817
+ assert rig.led("BLOCKED at the review: the reviewer: mutations: no mutation proof for the locked test file "
818
+ "tests/test_01.py.")
819
+ assert [q["id"] for q in rig.state()["run"]["questions"]] == ["01-review-rejected-1"]
816
820
  assert "feat: 01 rows" not in rig.pr_subjects()
817
821
 
818
822
 
@@ -863,7 +867,15 @@ def test_the_locked_file_rule_is_for_the_first_review_only(tmp_path):
863
867
  report = dict(status="DONE", commits=[], files=[], concerns=[], findings=[], mutations=[])
864
868
  path = tmp_path / "reviewer-0.json"
865
869
  path.write_text(json.dumps(report))
866
- context = {"repo": ".", "branch": "main", "start": "HEAD", "log": str(path), "locked": ["tests/a.py", "tests/b.py"]}
870
+ repo = tmp_path / "repo"
871
+ (repo / "tests").mkdir(parents=True)
872
+ for name in ("a", "b"):
873
+ (repo / f"tests/{name}.py").write_text("def test_x():\n pass\n")
874
+ subprocess.run(["git", "init", "-q", "-b", "main", str(repo)], check=True)
875
+ subprocess.run(["git", "-C", str(repo), "add", "-A"], check=True)
876
+ subprocess.run([*GIT, "-C", str(repo), "commit", "-q", "-m", "tests"], check=True)
877
+ context = {"repo": str(repo), "branch": "main", "start": "HEAD", "log": str(path),
878
+ "locked": ["tests/a.py", "tests/b.py"]}
867
879
  assert driver_report.validate("reviewer", str(path), context) == []
868
880
  assert driver_report.validate("reviewer", str(path), {**context, "full": True}) == [
869
881
  "mutations: no mutation proof for the locked test file tests/a.py",
@@ -174,6 +174,24 @@ def test_locked_path_absent_from_the_commit_is_a_violation(world):
174
174
  assert any("tests/test_other.py" in e for e in errors), errors
175
175
 
176
176
 
177
+ def test_a_locked_path_that_the_commits_delete_is_a_violation(world):
178
+ """Issue #136: a correction deleted a locked file and still listed it, so no review could prove it."""
179
+ shas, check, tmp_path = world
180
+ root = tmp_path / "slot"
181
+ git(root, "rm", "-q", "tests/test_export.py")
182
+ git(root, "commit", "-q", "-m", "drop the test")
183
+ assert check("test-writer", writer(shas), start=shas["base"]) == [
184
+ "locked path tests/test_export.py is not a file at the tip of ticket/01: list in `locked` only files you keep"]
185
+
186
+
187
+ def test_a_full_review_needs_no_proof_for_a_locked_file_that_is_not_at_the_tip(world):
188
+ shas, check, _ = world
189
+ locked = ["tests/test_export.py", "tests/test_gone.py"]
190
+ assert check("reviewer", reviewer(), start=shas["impl"], full=True, locked=locked) == []
191
+ assert check("reviewer", reviewer(mutations=[]), start=shas["impl"], full=True, locked=locked) == [
192
+ "mutations: no mutation proof for the locked test file tests/test_export.py"]
193
+
194
+
177
195
  def test_red_line_absent_from_the_log_is_a_violation(world):
178
196
  shas, check, _ = world
179
197
  assert check("test-writer", writer(shas), start=shas["base"]) == []
@@ -299,7 +299,7 @@ def test_a_red_line_missing_from_the_reviewer_log_reruns_once_then_blocks(tmp_pa
299
299
  rig.run(plan(**{"01/reviewer": [bad, review("01") if second_matches else bad]}))
300
300
  first, second = rig.calls("01", "reviewer")
301
301
  assert "red line not found in log" in second["prompt"] and "red line not found" not in first["prompt"]
302
- assert rig.code == (0 if second_matches else 1), rig.output()
302
+ assert rig.code == (0 if second_matches else 2), rig.output() # 2: the `review-rejected` question
303
303
  assert len(rig.calls("01", "reviewer")) == 2
304
304
  if not second_matches:
305
305
  assert rig.led("01", "BLOCKED") and "feat: 01 rows" not in rig.pr_subjects()
@@ -37,7 +37,7 @@ def test_start_keeps_a_recorded_run_and_adds_only_the_new_tickets(tmp_path):
37
37
  assert again["tickets"]["01"]["phase"] == "merged" and again["tickets"]["01"]["fixtures"] == []
38
38
  assert again["tickets"]["02"] == {
39
39
  "phase": "pending", "round": 0, "tip": None, "test_writer_sha": None, "locked": [], "green_gates": [], "slot": None,
40
- "note": "", "held": {}, "fixtures": []}
40
+ "note": "", "held": {}, "rejected": {}, "fixtures": []}
41
41
 
42
42
 
43
43
  def test_verified_trusts_a_tip_only_while_it_is_on_the_ticket_branch(repo, tmp_path):
@@ -95,8 +95,8 @@ def test_a_local_run_stops_before_the_push_and_a_push_rerun_pushes_and_opens_the
95
95
  (pr,) = rig.prs()
96
96
  assert pr["argv"][:10] == ["pr", "create", "--base", "main", "--head", "feat/csv", "--title", "csv spec",
97
97
  "--body-file", ".agent/implement/final/pr-body.md"]
98
- assert pr["body"].startswith("## Summary\n\nCSV export.\n\n## Tickets\n"), "the pr-writer's body, then the facts"
99
- assert [f"- {nn}: {row['sha'][:7]} {TITLES[nn]}" for nn, row in zip(order, rows)] == pr["body"].splitlines()[8:11]
98
+ assert pr["body"].startswith("## Summary\n\nCSV export.\n\n## Merge Danger\n"), "the pr-writer's body, then the facts"
99
+ assert [f"- {nn}: {row['sha'][:7]} {TITLES[nn]}" for nn, row in zip(order, rows)] == pr["body"].split("## Tickets\n\nOne commit per ticket, in merge order:\n\n")[1].splitlines()[:3]
100
100
  (writer,) = rig.final_calls("pr-writer")
101
101
  assert f"PR method: {pr_skill}\n" in writer["prompt"]
102
102
  assert "Facts of the run, which the driver puts after your body:\n## Tickets" in writer["prompt"]
@@ -66,8 +66,8 @@ if role in ("reviewer", "correctness", "final-reviewer") and "report" not in ste
66
66
  proofs = [dict(test=r.split()[1], file="demo/export.py", line=1, red=r) for r in reds]
67
67
  step = dict(step, stdout="".join(r + "\\n" for r in reds), report=dict(
68
68
  status="DONE", commits=[], files=[], concerns=[], findings=[], mutations=proofs))
69
- if role == "pr-writer" and "report" not in step: # an unscripted pr-writer writes one section
70
- step = dict(step, report=dict(status="DONE", commits=[], files=[], concerns=[], body="## Summary\\n\\nCSV export."))
69
+ if role == "pr-writer" and "report" not in step: # an unscripted pr-writer writes a summary and a valid merge-risk block
70
+ step = dict(step, report=dict(status="DONE", commits=[], files=[], concerns=[], body="## Summary\\n\\nCSV export.\\n\\n## Merge Danger\\n\\n```merge-risk v1\\ndoor: two-way\\nblast_radius: isolated\\ntouches: [docs]\\nrollback: revert\\nverdict: auto\\nreasons:\\n - \\"Only prose changes\\"\\n```\\n"))
71
71
  for name in step.get("touch", []):
72
72
  (rig / "sig" / name).touch()
73
73
  for name in step.get("wait", []):
@@ -0,0 +1,33 @@
1
+ ---
2
+ name: pr-risk
3
+ description: >-
4
+ Merge-risk block of a PR body. Use when a PR body needs its ```merge-risk v1
5
+ block parsed or validated, with every error named.
6
+ ---
7
+
8
+ # pr-risk
9
+
10
+ `python3 merge_risk.py parse <body-file>` prints the block as JSON, with an `errors` list.
11
+ `python3 merge_risk.py validate <body-file>` prints the errors and exits non-zero when the block is invalid.
12
+
13
+ The block is the one fenced ```` ```merge-risk v1 ```` block in the body. Keys: `door`, `blast_radius`,
14
+ `touches`, `rollback`, `verdict`, `reasons`.
15
+
16
+ `python3 merge_risk.py gate --body <file> --base <ref> --head <sha>` prints JSON with `verdict` (`auto | human`),
17
+ `reasons`, `categories` and `countedLines`. The policy is read from `origin/<base>`; the block's `verdict` is ignored.
18
+
19
+ ## Writing the block
20
+
21
+ In a repo with `.merge-risk.json`, a hook denies `gh pr create` unless the body, passed with `--body` or
22
+ `--body-file`, holds a valid block. Write the body with `/pr`, then run `/pr-risk` to add the block.
23
+
24
+ Read `.merge-risk.json` for the policy, then fill the block from the diff:
25
+
26
+ - `door`: `one-way` if the change cannot be undone once shipped, else `two-way`.
27
+ - `blast_radius`: how far a bad change reaches: `isolated`, `module`, `service` or `consumers`.
28
+ - `touches`: inline list of categories the diff touches, e.g. `[docs, tests]`.
29
+ - `rollback`: `revert`, `revert+redeploy`, `data-fix` or `impossible`.
30
+ - `verdict`: `auto` only when the policy allows an agent to merge this change, else `human`.
31
+ - `reasons`: one quoted line per reason for the verdict.
32
+
33
+ Check it with `python3 merge_risk.py validate <body-file>` before opening the PR.
@@ -0,0 +1,274 @@
1
+ #!/bin/sh
2
+ # PreToolUse hook (Claude and Codex): in a repo with .merge-risk.json, deny `gh pr create`
3
+ # unless its body (--body or --body-file) holds a valid merge-risk block. Otherwise print nothing.
4
+ here="$(cd "$(dirname "$0")" && pwd)"
5
+ PAYLOAD="$(cat)" exec python3 - "$here/../merge_risk.py" <<'PY'
6
+ import json, os, re, shlex, subprocess, sys
7
+ sys.path.insert(0, os.path.dirname(sys.argv[1]))
8
+ import merge_risk
9
+
10
+ try:
11
+ payload = json.loads(os.environ["PAYLOAD"])
12
+ except ValueError:
13
+ sys.exit(0)
14
+ command = (payload.get("tool_input") or {}).get("command") or ""
15
+ start_cwd = payload.get("cwd") or "."
16
+
17
+
18
+ LITERAL = "\0" # stands for a `$` the shell passes through unexpanded
19
+
20
+
21
+ def skip_quoted(s, i):
22
+ """i is just past an opening quote; return the index past the closing one."""
23
+ q = s[i - 1]
24
+ while i < len(s) and s[i] != q:
25
+ i += 2 if s[i] == "\\" and q == '"' else 1
26
+ return i + 1
27
+
28
+
29
+ def skip_subst(s, i):
30
+ """i is at `$(`; return the index past its matching `)`, skipping quotes and heredoc bodies."""
31
+ depth, i = 1, i + 2
32
+ while i < len(s) and depth:
33
+ c = s[i]
34
+ if c in "'\"":
35
+ i = skip_quoted(s, i + 1)
36
+ continue
37
+ if c == "\\":
38
+ i += 2
39
+ continue
40
+ h = re.compile(r"<<-?\s*['\"]?(\w+)['\"]?").match(s, i) if c == "<" else None
41
+ if h:
42
+ end = re.compile(r"^\s*" + h.group(1) + r"\s*$", re.M).search(s, s.find("\n", h.end()) + 1)
43
+ i = end.end() if end else len(s)
44
+ continue
45
+ depth += (c == "(") - (c == ")")
46
+ i += 1
47
+ return i
48
+
49
+
50
+ def skip_tick(s, i):
51
+ """i is just past an opening backtick; return the index past the closing one."""
52
+ while i < len(s) and s[i] != "`":
53
+ i += 2 if s[i] == "\\" else 1
54
+ return i + 1
55
+
56
+
57
+ def substitution(s, i, j):
58
+ """The command inside the substitution s[i:j]; a backtick body has its `\\$`, `\\`` and `\\\\` escapes removed."""
59
+ if s[i] == "$":
60
+ return s[i + 2:j - 1]
61
+ return re.sub(r"\\([$`\\])", r"\1", s[i + 1:j - 1])
62
+
63
+
64
+ def expansions(s, where):
65
+ """Commands run by the substitutions in unquoted heredoc text s."""
66
+ out, k = [], 0
67
+ s = re.sub(r"\\\n|(\\.)", lambda m: m.group(1) or "", s, flags=re.S) # line continuations vanish first
68
+ while k < len(s):
69
+ if s[k] == "\\":
70
+ k += 2
71
+ elif s.startswith("$(", k) or s[k] == "`":
72
+ e = skip_subst(s, k) if s[k] == "$" else skip_tick(s, k + 1)
73
+ out += parse(substitution(s, k, e), where)
74
+ k = e
75
+ else:
76
+ k += 1
77
+ return out
78
+
79
+
80
+ def parse(s, where):
81
+ """Split into (words, dir) commands: POSIX-ish words with `$(...)` kept raw inside its word, and
82
+ dir the directory left by `cd`s in the command's subshell scope."""
83
+ out, words, cur, i = [], [], None, 0
84
+ directories, heredocs = [], []
85
+
86
+ def end_word():
87
+ nonlocal cur
88
+ if cur is not None:
89
+ words.append(cur)
90
+ cur = None
91
+
92
+ def end_command():
93
+ nonlocal words, where
94
+ end_word()
95
+ # Shell control words introduce a command rather than forming its argv.
96
+ while words and words[0] in {"if", "then", "elif", "else", "while", "until", "do", "!", "{"}:
97
+ words = words[1:]
98
+ while words and "=" in words[0] and not words[0].startswith("-"):
99
+ words = words[1:]
100
+ if words[:1] == ["cd"] and len(words) > 1:
101
+ args = words[1:]
102
+ while args and args[0] in ("-L", "-P"):
103
+ args = args[1:]
104
+ if args[:1] == ["--"]:
105
+ args = args[1:]
106
+ if args:
107
+ where = os.path.join(where, os.path.expanduser(args[0].replace(LITERAL, "$")))
108
+ elif words:
109
+ out.append((words, where))
110
+ words = []
111
+
112
+ while i < len(s):
113
+ c, base = s[i], cur or ""
114
+ if s.startswith("\\\n", i):
115
+ i += 2
116
+ elif s.startswith("$(", i) or c == "`":
117
+ j = skip_subst(s, i) if c == "$" else skip_tick(s, i + 1)
118
+ out += parse(substitution(s, i, j), where)
119
+ cur, i = base + s[i:j], j
120
+ elif c == "'": # literal: mask `$` so a body of `$(cat f)` is not mistaken for a substitution
121
+ j = skip_quoted(s, i + 1)
122
+ cur, i = base + s[i + 1:j - 1].replace("$", LITERAL), j
123
+ elif c == '"': # a `$(...)` inside stays raw: its quotes must not end this string
124
+ k, inner = i + 1, ""
125
+ while k < len(s) and s[k] != '"':
126
+ if s.startswith("$(", k) or s[k] == "`":
127
+ e = skip_subst(s, k) if s[k] == "$" else skip_tick(s, k + 1)
128
+ out += parse(substitution(s, k, e), where)
129
+ inner, k = inner + s[k:e], e
130
+ elif s.startswith("\\\n", k):
131
+ k += 2
132
+ elif s[k] == "\\" and s[k + 1:k + 2] in ('"', "\\", "$", "`"):
133
+ inner, k = inner + (LITERAL if s[k + 1] == "$" else s[k + 1]), k + 2
134
+ else:
135
+ inner, k = inner + s[k], k + 1
136
+ cur, i = base + inner, k + 1
137
+ elif c == "\\":
138
+ cur, i = base + s[i + 1:i + 2].replace("$", LITERAL), i + 2
139
+ elif c in " \t":
140
+ end_word()
141
+ i += 1
142
+ elif s.startswith("<<", i) and not s.startswith("<<<", i):
143
+ # Delimiters undergo quote removal; the following lines are data,
144
+ # even when they contain shell commands or subshell punctuation.
145
+ h = re.match(r'''<<(-?)[ \t]*((?:[^\s;|&()<>"'\\]|'[^']*'|"(?:\\.|[^"\\])*"|\\.)+)''', s[i:])
146
+ if h:
147
+ end_word()
148
+ heredocs.append((shlex.split(h.group(2))[0], bool(h.group(1)), h.group(2) == shlex.split(h.group(2))[0], where))
149
+ i += h.end()
150
+ else:
151
+ cur, i = base + c, i + 1
152
+ elif c in "();&|\n":
153
+ end_command()
154
+ i += 1
155
+ if c == "(":
156
+ directories.append(where)
157
+ elif c == ")" and directories:
158
+ where = directories.pop()
159
+ elif c == "\n":
160
+ for delimiter, strip_tabs, expands, started in heredocs:
161
+ body = i
162
+ while i < len(s):
163
+ j = s.find("\n", i)
164
+ j = len(s) if j < 0 else j
165
+ line, i = s[i:j], min(j + 1, len(s))
166
+ if (line.lstrip("\t") if strip_tabs else line) == delimiter:
167
+ break
168
+ if expands: # an unquoted delimiter leaves the body's substitutions live
169
+ out += expansions(s[body:i], started) # runs before the line's cd
170
+ heredocs.clear()
171
+ else:
172
+ cur, i = base + c, i + 1
173
+ end_command()
174
+ return out
175
+
176
+
177
+ def creation_args(words):
178
+ """Recognize the subcommand while consuming gh's inherited repo option."""
179
+ if words[:1] != ["gh"]:
180
+ return None
181
+ i = 1
182
+ for expected in ("pr", "create"):
183
+ while i < len(words):
184
+ arg = words[i]
185
+ if arg in ("--repo", "-R"):
186
+ i += 2
187
+ elif arg.startswith("--repo=") or (arg.startswith("-R") and len(arg) > 2):
188
+ i += 1
189
+ else:
190
+ break
191
+ if i >= len(words) or words[i] != expected:
192
+ return None
193
+ i += 1
194
+ return words[i:]
195
+
196
+
197
+ creations = []
198
+ for words, cwd in parse(command, start_cwd):
199
+ args = creation_args(words)
200
+ if args is not None:
201
+ creations.append((args, cwd))
202
+
203
+
204
+ def deny(reason):
205
+ print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse",
206
+ "permissionDecision": "deny",
207
+ "permissionDecisionReason": reason}}))
208
+ sys.exit(0)
209
+
210
+
211
+ VALUED = {"--title", "-t", "--base", "-B", "--head", "-H", "--assignee", "-a", "--label", "-l",
212
+ "--milestone", "-m", "--project", "-p", "--reviewer", "-r", "--template", "-T",
213
+ "--repo", "-R"}
214
+ BODY_SOURCE_REQUIRED = (
215
+ "the body must come from --body or --body-file, so its merge-risk block can be checked. "
216
+ "Write the body with /pr, then /pr-risk."
217
+ )
218
+
219
+
220
+ def check(args, cwd):
221
+ top = subprocess.run(["git", "-C", cwd, "rev-parse", "--show-toplevel"],
222
+ capture_output=True, text=True).stdout.strip() or cwd
223
+ if not os.path.isfile(os.path.join(top, ".merge-risk.json")):
224
+ return
225
+ body = body_file = None
226
+ i = 0
227
+ while i < len(args):
228
+ a, i = args[i], i + 1
229
+ name, eq, val = a.partition("=")
230
+ if name in ("--body", "-b", "--body-file", "-F"):
231
+ if not eq and i < len(args):
232
+ val, i = args[i], i + 1
233
+ if name in ("--body", "-b"):
234
+ body = val
235
+ else:
236
+ body_file = val
237
+ elif name in {"--fill", "--fill-first", "--web"}:
238
+ deny(BODY_SOURCE_REQUIRED)
239
+ elif name in VALUED and not eq:
240
+ i += 1
241
+ if body is None and body_file is None:
242
+ deny(BODY_SOURCE_REQUIRED)
243
+
244
+ body_file = body_file and body_file.replace(LITERAL, "$")
245
+
246
+ def read(path):
247
+ with open(os.path.join(cwd, os.path.expanduser(path))) as f:
248
+ return f.read()
249
+
250
+ try:
251
+ if body_file is not None:
252
+ text = read(body_file)
253
+ else:
254
+ m = re.fullmatch(r"\s*\$\(\s*cat\s+(?:<<-?\s*'?(\w+)'?\n(.*?)\n\s*\1\s*|('[^']*'|\"[^\"]*\"|\S+)\s*)\)\s*",
255
+ body, re.S)
256
+ if m and m.group(1):
257
+ text = m.group(2) + "\n"
258
+ elif m:
259
+ text = read(m.group(3).strip("'\""))
260
+ else:
261
+ text = body.replace(LITERAL, "$")
262
+ except OSError as e:
263
+ deny(f"cannot read the PR body ({e.strerror}: {e.filename}); pass --body-file with a file that exists. "
264
+ "Write the body with /pr, then /pr-risk.")
265
+
266
+ errors = merge_risk.parse(text)["errors"]
267
+ if errors:
268
+ deny("The PR body has no valid merge-risk block: " + "; ".join(errors) +
269
+ ". Write the body with /pr, then /pr-risk.")
270
+
271
+
272
+ for args, cwd in creations:
273
+ check(args, cwd)
274
+ PY
@@ -0,0 +1,10 @@
1
+ {
2
+ "hooks": {
3
+ "PreToolUse": [
4
+ {
5
+ "matcher": "Bash",
6
+ "hooks": [{ "type": "command", "command": "hooks/pre-pr-create.sh" }]
7
+ }
8
+ ]
9
+ }
10
+ }