@jesdi/skills 0.0.63 → 0.0.65

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 (57) 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 +9 -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 +3 -3
  35. package/skills/implement-spec/SKILL.md +1 -1
  36. package/skills/implement-spec/driver.py +27 -4
  37. package/skills/implement-spec/driver_final.py +49 -10
  38. package/skills/implement-spec/prompts/overruled.md +3 -1
  39. package/skills/implement-spec/prompts/pr-writer.md +3 -2
  40. package/skills/implement-spec/tests/test_decisions.py +36 -2
  41. package/skills/implement-spec/tests/test_final.py +112 -1
  42. package/skills/implement-spec/tests/test_tidy.py +2 -2
  43. package/skills/implement-spec/tests/test_walk.py +2 -2
  44. package/skills/pr-risk/SKILL.md +33 -0
  45. package/skills/pr-risk/hooks/pre-pr-create.sh +274 -0
  46. package/skills/pr-risk/hooks.json +10 -0
  47. package/skills/pr-risk/merge_policy.py +81 -0
  48. package/skills/pr-risk/merge_risk.py +314 -0
  49. package/skills/pr-risk/test_hook_commands.py +47 -0
  50. package/skills/pr-risk/test_hook_heredoc.py +16 -0
  51. package/skills/pr-risk/test_hook_substitution.py +40 -0
  52. package/skills/pr-risk/test_hooks.py +175 -0
  53. package/skills/pr-risk/test_merge_risk.py +97 -0
  54. package/skills/pr-risk/test_merge_risk_gate.py +217 -0
  55. package/skills/pr-risk/test_merge_risk_regressions.py +37 -0
  56. package/skills/pr-risk/test_merge_risk_structure.py +101 -0
  57. package/skills-manifest.json +15 -3
@@ -0,0 +1,157 @@
1
+ """Acceptance tests for `babysit.py update-plan --base <ref>`.
2
+
3
+ Interface under test (run with the PR branch checked out, cwd = the clone):
4
+ babysit.py update-plan --base <ref>
5
+ Prints one JSON object on stdout, exit 0:
6
+ plan "rebase" | "rebase-with-conflict" | "merge"
7
+ compare the ref compared against, e.g. "origin/main"
8
+ push the push command: rebase plans use
9
+ `git push --force-with-lease=<branch>:<old sha> origin <branch>`;
10
+ the merge plan pushes without any force flag
11
+ files conflicting files (rebase-with-conflict only)
12
+ It never changes the worktree, the index, HEAD or any ref.
13
+ """
14
+ import json
15
+ import subprocess
16
+ from pathlib import Path
17
+
18
+ SCRIPT = Path(__file__).with_name("babysit.py").resolve()
19
+ BRANCH = "feat/x"
20
+
21
+
22
+ def git(cwd, *args):
23
+ return subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True,
24
+ env={"GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@t",
25
+ "GIT_COMMITTER_NAME": "t", "GIT_COMMITTER_EMAIL": "t@t",
26
+ "PATH": "/usr/bin:/bin:/usr/local/bin:/opt/homebrew/bin",
27
+ "HOME": str(cwd)}).stdout.strip()
28
+
29
+
30
+ def commit(cwd, path, text, msg):
31
+ f = Path(cwd) / path
32
+ f.parent.mkdir(parents=True, exist_ok=True)
33
+ f.write_text(text)
34
+ git(cwd, "add", path)
35
+ git(cwd, "commit", "-m", msg)
36
+
37
+
38
+ class Repo:
39
+ """origin (bare) + clone `work`, with main history that already touched src/parse.py twice."""
40
+
41
+ def __init__(self, tmp):
42
+ self.origin = tmp / "origin.git"
43
+ self.work = tmp / "work"
44
+ git(tmp, "init", "--bare", "-b", "main", str(self.origin))
45
+ git(tmp, "clone", str(self.origin), str(self.work))
46
+ git(self.work, "checkout", "-b", "main")
47
+ commit(self.work, "src/parse.py", "a\nb\nc\n", "old 1")
48
+ commit(self.work, "src/parse.py", "a\nb\nc\nd\n", "old 2")
49
+ git(self.work, "push", "origin", "main")
50
+ git(self.work, "checkout", "-b", BRANCH)
51
+
52
+ def branch_commits(self, n, path="src/parse.py"):
53
+ for i in range(n):
54
+ commit(self.work, path, f"X{i}\nb\nc\nd\n", f"branch {i}")
55
+ git(self.work, "push", "origin", BRANCH)
56
+
57
+ def advance(self, branch, n, path="other.txt", text=None):
58
+ git(self.work, "checkout", branch)
59
+ for i in range(n):
60
+ commit(self.work, path, text or f"base {i}\n", f"{branch} {i}")
61
+ git(self.work, "push", "origin", branch)
62
+ git(self.work, "checkout", BRANCH)
63
+
64
+ def plan(self, base="main"):
65
+ git(self.work, "fetch", "origin")
66
+ r = subprocess.run(["python3", str(SCRIPT), "update-plan", "--base", base],
67
+ cwd=self.work, capture_output=True, text=True)
68
+ assert r.returncode == 0, r.stdout + r.stderr
69
+ return json.loads(r.stdout)
70
+
71
+
72
+ def test_new_base_commits_without_conflict_plan_rebase(tmp_path):
73
+ r = Repo(tmp_path)
74
+ r.branch_commits(1)
75
+ r.advance("main", 3)
76
+ old = git(r.work, "rev-parse", "HEAD")
77
+ p = r.plan()
78
+ assert p["plan"] == "rebase"
79
+ assert p["push"] == f"git push --force-with-lease={BRANCH}:{old} origin {BRANCH}"
80
+
81
+
82
+ def test_conflict_in_two_branch_commits_plans_rebase_with_conflict(tmp_path):
83
+ r = Repo(tmp_path)
84
+ r.branch_commits(2)
85
+ r.advance("main", 1, "src/parse.py", "M\nb\nc\nd\n")
86
+ p = r.plan()
87
+ assert p["plan"] == "rebase-with-conflict"
88
+ assert "src/parse.py" in p["files"]
89
+ assert "--force-with-lease=" in p["push"]
90
+
91
+
92
+ def test_conflict_in_three_branch_commits_plans_merge(tmp_path):
93
+ r = Repo(tmp_path)
94
+ r.branch_commits(3)
95
+ r.advance("main", 1, "src/parse.py", "M\nb\nc\nd\n")
96
+ p = r.plan()
97
+ assert p["plan"] == "merge"
98
+ assert p["compare"] == "origin/main"
99
+ assert "force" not in p["push"]
100
+ assert p["push"].endswith(f"origin {BRANCH}")
101
+
102
+
103
+ def test_update_plan_leaves_worktree_index_and_head_unchanged(tmp_path):
104
+ r = Repo(tmp_path)
105
+ r.branch_commits(2)
106
+ r.advance("main", 1, "src/parse.py", "M\nb\nc\nd\n")
107
+ (r.work / "src/parse.py").write_text("dirty\n")
108
+ (r.work / "untracked.txt").write_text("u\n")
109
+ (r.work / "staged.txt").write_text("s\n")
110
+ git(r.work, "add", "staged.txt")
111
+ git(r.work, "fetch", "origin")
112
+ before = (git(r.work, "status", "--porcelain"), git(r.work, "rev-parse", "HEAD"),
113
+ git(r.work, "for-each-ref"), git(r.work, "diff", "--cached"),
114
+ (r.work / "src/parse.py").read_text())
115
+ p = r.plan()
116
+ assert p["plan"] == "rebase-with-conflict"
117
+ after = (git(r.work, "status", "--porcelain"), git(r.work, "rev-parse", "HEAD"),
118
+ git(r.work, "for-each-ref"), git(r.work, "diff", "--cached"),
119
+ (r.work / "src/parse.py").read_text())
120
+ assert after == before
121
+ assert not (r.work / ".git" / "MERGE_HEAD").exists()
122
+ assert not (r.work / ".git" / "rebase-merge").exists()
123
+
124
+
125
+ def test_base_feat_parent_compares_with_origin_feat_parent(tmp_path):
126
+ r = Repo(tmp_path)
127
+ r.branch_commits(1)
128
+ # main would conflict with the branch; the parent does not
129
+ r.advance("main", 1, "src/parse.py", "M\nb\nc\nd\n")
130
+ git(r.work, "checkout", "-b", "feat/parent", "origin/main~1")
131
+ git(r.work, "push", "origin", "feat/parent")
132
+ git(r.work, "checkout", BRANCH)
133
+ r.advance("feat/parent", 1)
134
+ p = r.plan("feat/parent")
135
+ assert p["compare"] == "origin/feat/parent"
136
+ assert p["plan"] == "rebase"
137
+
138
+
139
+ def test_commits_across_two_conflicting_files_are_counted_as_a_union(tmp_path):
140
+ r = Repo(tmp_path)
141
+ git(r.work, "checkout", "main")
142
+ commit(r.work, "a.py", "a\nb\nc\n", "add a")
143
+ commit(r.work, "b.py", "a\nb\nc\n", "add b")
144
+ git(r.work, "push", "origin", "main")
145
+ git(r.work, "checkout", BRANCH)
146
+ git(r.work, "merge", "--ff-only", "main")
147
+ commit(r.work, "a.py", "A1\nb\nc\n", "branch a1")
148
+ commit(r.work, "a.py", "A2\nb\nc\n", "branch a2")
149
+ commit(r.work, "b.py", "B1\nb\nc\n", "branch b1")
150
+ git(r.work, "push", "origin", BRANCH)
151
+ git(r.work, "checkout", "main")
152
+ commit(r.work, "a.py", "M\nb\nc\n", "main a")
153
+ commit(r.work, "b.py", "M\nb\nc\n", "main b")
154
+ git(r.work, "push", "origin", "main")
155
+ git(r.work, "checkout", BRANCH)
156
+ p = r.plan()
157
+ assert p["plan"] == "merge"
@@ -140,7 +140,7 @@ The end of run starts only when every ticket is merged and every slot is idle. I
140
140
  3. **Gate**, then the **final-reviewer** (`prompts/final-reviewer.md`) on the whole range, with the method of the `review-diff` skill. It gets the minor findings of the tickets and the rulings of the operator.
141
141
  4. **Fix batch.** Critical and important findings go to one fixer (`prompts/final-fixer.md`). The driver names each of its commits `fix(NN): …` from the ticket in the report. Then the gate, then one scoped review of those commits.
142
142
  5. Findings that are open after the second review become questions of kind `final-finding`. There is no third review.
143
- 6. **Push.** With `--push` or `--unattended`, the driver pushes the reviewed tip once, with no force, and opens the PR with `gh`, ready for review. The **pr-writer** (`prompts/pr-writer.md`) writes the body with the method of the `pr` skill; the driver puts the facts of the run after it: the ticket-to-commit map, the fix commits, the rulings and the review coverage (`prompts/pr-body.md`). A push stops before any agent when no `pr` skill is next to this skill, in `${CLAUDE_CONFIG_DIR:-~/.claude}/skills` or in `~/.agents/skills`. Without them it prints the two tips and the command to run again with `--push`.
143
+ 6. **Push.** With `--push` or `--unattended`, the driver pushes the reviewed tip once, with no force, and opens the PR with `gh`, ready for review. The **pr-writer** (`prompts/pr-writer.md`) writes the body with the method of the `pr` skill; the driver puts the facts of the run after it: the ticket-to-commit map, the fix commits, the rulings and the review coverage (`prompts/pr-body.md`). The body carries the merge-risk block of the `pr-risk` skill under `## Merge Danger`, above the facts; the driver validates it, runs the pr-writer once more with the errors when it is invalid, and blocks the run, opening no PR, when the second body is invalid too. A push stops before any agent when no `pr` skill or no `pr-risk` skill is next to this skill, in `${CLAUDE_CONFIG_DIR:-~/.claude}/skills` or in `~/.agents/skills`. Without them it prints the two tips and the command to run again with `--push`.
144
144
 
145
145
  History rules:
146
146
 
@@ -177,7 +177,7 @@ Every report has `status` (`DONE`, `DONE_WITH_CONCERNS`, `NEEDS_CONTEXT`, `BLOCK
177
177
 
178
178
  | Role | Template | More fields | Checks after the schema |
179
179
  |---|---|---|---|
180
- | test-writer | `prompts/test-writer.md` | `locked` (test file paths), `red` (`test`, `line`), optional `fixtures` (each locked file that holds no test, as a fake `gh`) | The driver reads a test node id `<file>::<test>` in `locked` as its file. Each fixture is in `locked`; the ticket record keeps it a fixture until a later correction lists the file again. With DONE: one commit, one locked file and one red line or more. Each locked path is in a commit that the role made, and is a file at the tip: a correction that deletes a locked file leaves it out of `locked`. Each `line` is in the log. A locked file of a merged ticket that the role changed is in `locked`. A correction (after `overrule-test`, or for a review finding) changes only the files that it lists in `locked` and the files that the driver restored before it. When the gate is red on the restore commit, a DONE correction lists a restored file in `locked`. Each `not_addressed[].finding` is the title of a finding of the correction; a DONE correction with each of its findings there needs no commit. |
180
+ | test-writer | `prompts/test-writer.md` | `locked` (test file paths), `red` (`test`, `line`), optional `fixtures` (each locked file that holds no test, as a fake `gh`) | The driver reads a test node id `<file>::<test>` in `locked` as its file. Each fixture is in `locked`; the ticket record keeps it a fixture until a later correction lists the file again. With DONE: one commit, one locked file and one red line or more. A correction's test can be green on the implementer's code, so its red line comes from a production edit that the correction makes and reverts. Each locked path is in a commit that the role made and is a file at the tip: a correction that deletes a locked file leaves it out of `locked`. Each `line` is in the log. A locked file of a merged ticket that the role changed is in `locked`. A correction (after `overrule-test`, or for a review finding) changes only the files that it lists in `locked` and the files that the driver restored before it. When the gate is red on the restore commit, a DONE correction lists a restored file in `locked`. Each `not_addressed[].finding` is the title of a finding of the correction, or after `overrule-test` an overruled concern as its prompt lists it (the driver logs its reason, and the implementer runs again); a DONE correction with each of its findings there needs no commit. |
181
181
  | implementer | `prompts/implementer.md` | `green` | With DONE and no commit: no new commit on the branch, no uncommitted change, and a concern that says why the start needs no change. The driver then gates and reviews the start commit. |
182
182
  | reviewer | `prompts/reviewer.md` | `findings` (`severity`, `file`, `line`, `title`, `evidence`, `kind`), `mutations` (`test`, `file`, `line`, `red`) | In a full review (one with no fix range: round 1, and the review after a test-writer correction): `mutations` is required, with a proof for each locked test file (`test` is `<locked file>::<test name>`). A locked fixture needs no proof: it holds no test that a proof could name, and the locked-file check protects it. Neither does a locked file that is not at the reviewed tip. Each `red` is in the log. |
183
183
  | correctness | `prompts/correctness.md` | the same as the reviewer | `mutations` is optional. |
@@ -195,7 +195,7 @@ A question is a bounded choice for the operator. `driver_decisions.py` `KINDS` h
195
195
 
196
196
  | Kind | Question id | Asked when | Run exit | Options |
197
197
  |---|---|---|---|---|
198
- | `locked-test` | `<NN>-locked-test-<n>` | An implementer or a fixer reports BLOCKED with a concern that starts with `locked test contradicts spec:`. | 2 | `overrule-test`: the test-writer corrects the test from that report, then the implementer runs again, and the fix rounds count from 0: the corrected tests are a new contract. `overrule-implementer` (recommended): the implementer runs again. |
198
+ | `locked-test` | `<NN>-locked-test-<n>` | An implementer or a fixer reports BLOCKED with a concern that starts with `locked test contradicts spec:`. Asked again on the same test, from the same report, when the driver refuses the report of the correction after `overrule-test` and its rerun, or the correction reports BLOCKED. | 2 | `overrule-test`: the test-writer corrects the test from that report, then the implementer runs again, and the fix rounds count from 0: the corrected tests are a new contract. `overrule-implementer` (recommended): the implementer runs again. |
199
199
  | `finding` | `<NN>-finding-<n>` | A finding is open after fix round 4. One question for each finding. | 1 | `accept`: close the finding; the ticket merges when each of its findings is accepted. `split` (recommended) and `redesign`: the ticket stays BLOCKED, with the ruling in the ledger. |
200
200
  | `locked-test-again` | `<NN>-locked-test-again-<n>` | A finding for a test-writer correction is open in the review right after a correction, or the driver rejects the correction's report (for example, it changes a file that it does not list in `locked`). One question for each finding. | 2 | `correct-again` (recommended): the ticket resumes from the review, and that review's findings get one more correction. `accept`: no more correction runs for the ticket, its locked tests stay as they are, and the ticket goes on to its fix rounds with its other findings; a changed locked file is still restored. `redesign`: the ticket stays BLOCKED, with the ruling in the ledger. After two `correct-again` stops on a ticket, its next question offers only `accept` (recommended) and `redesign`, so a test-writer and a reviewer that never agree cannot loop. |
201
201
  | `review-stopped` | `<NN>-review-stopped-<n>` | The reviewer or the correctness pass reports `BLOCKED` or `NEEDS_CONTEXT`. One question for each agent that stopped. | 2 | `retry` (recommended): the ticket resumes from the review, and each agent of the review runs again. `accept`: the same, and for the rest of the ticket a `BLOCKED` or `NEEDS_CONTEXT` report of that agent does not stop it: the review goes on with that report's findings and those of the other reports. `redesign`: the ticket stays BLOCKED, with the ruling in the ledger. |
@@ -24,7 +24,7 @@ has passed. The review rounds adapt superpowers' subagent-driven-development
24
24
  Run the driver. It makes every choice of the run; you start it and relay its result.
25
25
 
26
26
  1. In the PR worktree, run `sh <skill-dir>/run.sh` with the flags the operator gave, unchanged. `<skill-dir>` is the directory of this file. The driver needs `--gate` and `--spec`: ask the operator for a flag that is missing. A run can take hours: run the command in the background and wait for it to exit.
27
- 2. When it exits, relay `.agent/implement/summary.md` and the exit code: 0 is done, 1 is a BLOCKED ticket, 2 is parked on questions, 3 is invalid input, 4 is stopped by a CLI failure (after the fix, the same command resumes). Relay the lines the driver printed after the summary too.
27
+ 2. When it exits, relay `.agent/implement/summary.md` and the exit code: 0 is done, 1 is a BLOCKED ticket, 2 is parked on questions, 3 is invalid input, 4 is stopped by a CLI failure (after the fix, the same command resumes). Relay the lines the driver printed after the summary too. With exit 0 and a PR URL such as `https://github.com/jesdi/demo/pull/61`, tell the operator to start the babysitter: run `/babysit-pr https://github.com/jesdi/demo/pull/61`.
28
28
  3. With exit 2, and with exit 1 when the driver printed questions, show the operator those questions. When the operator answers, run the same command again with one `--answer <question id>=<option id>` for each answer.
29
29
 
30
30
  Do not answer a question for the operator. Do not edit `.agent/implement/`, the code or the branches during a run.
@@ -75,11 +75,22 @@ def _check_out_ticket(ticket: Ticket, slot_number: int, entry: dict, run: Run) -
75
75
  return driver_slots.head(slot)
76
76
 
77
77
 
78
+ def _locked_test_stop(number: str, run: Run) -> dict:
79
+ """The last `locked-test` question of the ticket; {} when it has none."""
80
+ asked = [q for q in run.state.read()["run"]["questions"] if (q["ticket"], q["kind"]) == (number, "locked-test")]
81
+ return asked[-1] if asked else {}
82
+
83
+
78
84
  def _blocked_report(number: str, run: Run) -> str:
79
85
  """The report of the last `locked-test` stop of the ticket: an implementer's or a fixer's."""
80
- asked = [q["evidence"][0] for q in run.state.read()["run"]["questions"]
81
- if (q["ticket"], q["kind"]) == (number, "locked-test")]
82
- return asked[-1] if asked else str(OUT / number / "implementer-0.json")
86
+ return _locked_test_stop(number, run).get("evidence", [str(OUT / number / "implementer-0.json")])[0]
87
+
88
+
89
+ def _overruled(number: str, run: Run) -> list[str]:
90
+ """The concerns of that report that the operator overruled: what an overrule correction names in
91
+ `not_addressed` (issue #134)."""
92
+ concerns = json.loads(Path(_blocked_report(number, run)).read_text())["concerns"]
93
+ return [concern for concern in concerns if concern.startswith(driver_decisions.CONTRADICTS)]
83
94
 
84
95
 
85
96
  def _prompt_values(ticket: Ticket, slot: str, run: Run) -> dict[str, str]:
@@ -114,11 +125,23 @@ def _run_roles(ticket: Ticket, slot_number: int, run: Run) -> None:
114
125
  values.update(start_sha=start, gate_record=os.path.relpath(driver_gate.record_path(OUT / number, start), slot))
115
126
  # A test-writer on a ticket that has locked tests is the correction after a ruling.
116
127
  check = {"correction": role == "test-writer" and bool(entry["test_writer_sha"])}
128
+ if check["correction"]:
129
+ check["findings"] = _overruled(number, run)
130
+ values["overruled"] = "".join(f"- {concern}\n" for concern in check["findings"])
117
131
  if check["correction"] and (restored := run.restore_locked_files(number, slot)):
118
132
  values.update(start_sha=driver_slots.head(slot), restored=" ".join(restored))
119
133
  notes, check["restored"] = [*notes, "restored"], restored
120
134
  with during(f"the {role}"):
121
- report = run.agent(role, number, slot, values, notes=notes, check=check)
135
+ try:
136
+ report = run.agent(role, number, slot, values, notes=notes, check=check)
137
+ except Blocked:
138
+ if check["correction"]:
139
+ # The ruling did not take: the operator rules on the same locked test again (issue #134).
140
+ run.ask(number, "locked-test", [_locked_test_stop(number, run)["subject"]],
141
+ _blocked_report(number, run))
142
+ raise
143
+ for item in report.get("not_addressed", []):
144
+ ledger(f"Ticket {number}: the test-writer correction did not correct {item['finding']}: {item['reason']}.")
122
145
  facts = {"tip": driver_slots.head(slot)}
123
146
  if role == "test-writer":
124
147
  facts.update(driver_review.written(slot, entry, report["locked"], report.get("fixtures", []),
@@ -22,6 +22,7 @@ import re
22
22
  import shlex
23
23
  import shutil
24
24
  import subprocess
25
+ import sys
25
26
  from pathlib import Path
26
27
 
27
28
  import driver_agents
@@ -41,12 +42,34 @@ ROUNDS = 2 # the full review and the scoped one after the fix batch
41
42
  REVIEW_DIFF = driver_agents.SKILL.parent / "review-diff" / "SKILL.md"
42
43
 
43
44
 
44
- def pr_skill() -> Path | None:
45
- """The SKILL.md of the pr skill, which the PR body follows: next to this skill, else in the skill folder of the
46
- Claude home or of the shared home of Codex and OpenCode."""
45
+ def _installed(name: str) -> Path | None:
46
+ """The SKILL.md of a skill: next to this skill, else in the skill folder of the Claude home or of the shared
47
+ home of Codex and OpenCode."""
47
48
  claude = Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude")
48
49
  homes = (driver_agents.SKILL.parent, claude / "skills", Path.home() / ".agents" / "skills")
49
- return next((home / "pr" / "SKILL.md" for home in homes if (home / "pr" / "SKILL.md").is_file()), None)
50
+ return next((home / name / "SKILL.md" for home in homes if (home / name / "SKILL.md").is_file()), None)
51
+
52
+
53
+ def pr_skill() -> Path | None:
54
+ """The SKILL.md of the pr skill, which the PR body follows."""
55
+ return _installed("pr")
56
+
57
+
58
+ def pr_risk_skill() -> Path | None:
59
+ """The SKILL.md of the pr-risk skill, which parses and validates the merge-risk block of the PR body."""
60
+ return _installed("pr-risk")
61
+
62
+
63
+ PR_RISK_INSTALL = "`npx skills add jesdi/general-skills --skill pr-risk`"
64
+
65
+
66
+ def _risk_errors(method: Path, body: str) -> str:
67
+ """The errors of the merge-risk block of `body` as `pr-risk` names them, or "" when the block is valid."""
68
+ checked = OUT / FINAL / "pr-risk-check.md"
69
+ checked.write_text(body)
70
+ done = subprocess.run([sys.executable, str(method.parent / "merge_risk.py"), "validate", str(checked)],
71
+ capture_output=True, text=True)
72
+ return (done.stdout + done.stderr).strip() if done.returncode else ""
50
73
 
51
74
 
52
75
  def _has_origin() -> bool:
@@ -62,6 +85,9 @@ def precondition_errors(push: bool) -> list[str]:
62
85
  if push and not pr_skill():
63
86
  errors.append("the pr skill is missing: the PR body follows it; install it with "
64
87
  "`npx skills add mattpocock/skills --skill pr`, or run without --push and --unattended")
88
+ if push and not pr_risk_skill():
89
+ errors.append(f"the pr-risk skill is missing: the PR body carries its merge-risk block; install it with "
90
+ f"{PR_RISK_INSTALL}, or run without --push and --unattended")
65
91
  if push and not _has_origin():
66
92
  errors.append("the repository has no origin remote: --unattended and --push push the PR branch to origin; "
67
93
  "add the remote, or run without them to stop before the push")
@@ -433,18 +459,31 @@ def _facts(run: Run, final: dict, tickets: list[Ticket]) -> str:
433
459
 
434
460
  def _write_body(run: Run, final: dict, tickets: list[Ticket]) -> Path:
435
461
  """Write the PR body: what the pr-writer wrote with the method of the pr skill, then the facts of the run. A body
436
- written for the reviewed tip is kept, so a PR that failed to open costs no second agent."""
462
+ written for the reviewed tip is kept when its merge-risk block still validates, so a PR that failed to open costs
463
+ no second agent."""
437
464
  body, tip = OUT / FINAL / "pr-body.md", final["reviewed"]
438
- if final["body"] == tip and body.is_file():
465
+ method, risk, facts = pr_skill(), pr_risk_skill(), _facts(run, final, tickets)
466
+ if final["body"] == tip and body.is_file() and risk and not _risk_errors(risk, body.read_text()):
439
467
  return body
440
- method, facts = pr_skill(), _facts(run, final, tickets)
441
468
  if not method:
442
469
  raise Blocked("the pr skill is missing: the PR body follows it; install it with "
443
470
  "`npx skills add mattpocock/skills --skill pr`")
471
+ if not risk:
472
+ raise Blocked(f"the pr-risk skill is missing: the PR body carries its merge-risk block; install it with "
473
+ f"{PR_RISK_INSTALL}")
444
474
  values = {**_prompt_values(run), "start_sha": tip, "range": f"{final['onto']}..{tip}",
445
- "gate": str(driver_gate.record_path(OUT / FINAL, tip)), "pr_skill": str(method), "facts": facts}
446
- with during("the PR body"):
447
- report = run.read_only(FINAL, ".", run.pr, tip, lambda: run.agent("pr-writer", FINAL, ".", values))
475
+ "gate": str(driver_gate.record_path(OUT / FINAL, tip)), "pr_skill": str(method),
476
+ "pr_risk_skill": str(risk), "risk_errors": "", "facts": facts}
477
+ for round_ in range(2): # the pr-writer gets one more run with the errors of the block
478
+ with during("the PR body"):
479
+ report = run.read_only(FINAL, ".", run.pr, tip,
480
+ lambda: run.agent("pr-writer", FINAL, ".", values, fix_round=round_))
481
+ if not (errors := _risk_errors(risk, report["body"])):
482
+ break
483
+ values["risk_errors"] = (f"Your previous body has an invalid merge-risk block. Fix it with the pr-risk "
484
+ f"skill; its errors:\n{errors}\n")
485
+ else:
486
+ raise Blocked(f"the merge-risk block of the PR body is invalid after a second run of the pr-writer: {errors}")
448
487
  body.write_text(f"{report['body'].strip()}\n\n{facts}")
449
488
  run.state.update(lambda state: state["run"]["final"].update(body=tip))
450
489
  return body
@@ -2,4 +2,6 @@
2
2
  This call is a correction after a ruling, not a new test set. The implementer or the fixer reported that a locked test contradicts the spec or the ticket, and the operator ruled that the test is wrong: read `concerns` in {blocked_report}.
3
3
  Correct only the tests that those concerns name, so that they state what the spec and the ticket require. Keep each other test as it is.
4
4
  The branch can hold commits of the implementer, and the tree can hold its uncommitted work: change neither, and commit only the test files you correct.
5
- A corrected test fails because the behavior is missing: run it and print that failing output. In `locked`, list each test file you corrected.
5
+ A corrected test fails because the behavior is missing: run it, print that failing output, and give its failure line in `red`. A corrected test can be green, because the implementer's code is there: then break the production line that the test protects, run the test, print its failing output, give that line in `red`, and revert the edit. In `locked`, list each test file you corrected.
6
+ When a concern needs no test change, leave the test as it is and add the concern to `not_addressed`: `finding` is its text, copied exactly from this list, and `reason` is why the test stands:
7
+ {overruled}
@@ -6,11 +6,12 @@ PR branch: {pr_branch}, at commit {start_sha}
6
6
  Range: {range}
7
7
  Gate record of the driver for {start_sha}: {gate}
8
8
  PR method: {pr_skill}
9
+ Merge-risk block: {pr_risk_skill}
9
10
  Facts of the run, which the driver puts after your body:
10
11
  {facts}
11
12
 
12
- Write the body of the PR of the range with the method of the pr skill in the file above: its sections, in its order. Read the spec, the tickets and the range first. The gate record and the tests of the range are the execution-based evidence; you cannot take screenshots. Do not repeat the facts of the run: the driver puts them after your body.
13
- Do not commit. Leave the branch and the tree as you found them.
13
+ Write the body of the PR of the range with the method of the pr skill in the file above: its sections, in its order. Put the merge-risk block, as the pr-risk skill describes it, under `## Merge Danger`, and check it with `python3 merge_risk.py validate <body-file>` from that skill's folder. Read the spec, the tickets and the range first. The gate record and the tests of the range are the execution-based evidence; you cannot take screenshots. Do not repeat the facts of the run: the driver puts them after your body.
14
+ {risk_errors}Do not commit. Leave the branch and the tree as you found them.
14
15
 
15
16
  Write one JSON report at {report} that matches this schema:
16
17
 
@@ -15,7 +15,7 @@ from test_fixloop import Inside, inside # noqa: F401 (the autouse fixture puts
15
15
  from test_tidy import Inside as Pushing, tools # noqa: F401 (an unattended run pushes: the rig with an origin and a fake gh)
16
16
  from test_review import ONE, STUCK, finding, fix, review
17
17
  from test_stops import CONTRA, NEW_TEST, Q1, UNATTENDED, blocked, correction, decisions, stage, steps, write_answers
18
- from test_walk import impl, plan, tw
18
+ from test_walk import COST, impl, plan, tw
19
19
 
20
20
  PAGE = ".agent/implement-review.html"
21
21
 
@@ -218,15 +218,49 @@ def test_a_correction_that_commits_more_than_the_files_it_lists_is_rejected(tmp_
218
218
  scenario = plan(**{"01/test-writer": [two_locked(), correction(), correction()], "01/implementer": [dirty, impl("01")]})
219
219
  rig = Inside(tmp_path, ONE).run(scenario)
220
220
  rig.run(scenario, "--answer", f"{Q1}=overrule-test")
221
- assert rig.code == 1, rig.ledger()
221
+ assert rig.code == 2, rig.ledger()
222
222
  assert rig.led("Ticket 01: BLOCKED at the test-writer: a correction may change only the files it lists in "
223
223
  "`locked`: its commits also change demo/export.py.")
224
+ # Issue #134: the refused correction asks the locked-test question again, from the same blocked report.
225
+ (again,) = decisions(rig)["questions"]
226
+ asked_again = rig.state()["run"]["questions"][-1]
227
+ assert again["id"] == "01-locked-test-2" and asked_again["subject"] == "tests/test_01.py::test_x"
228
+ assert asked_again["evidence"][0] == ".agent/implement/01/implementer-0.json"
224
229
  assert rig.led(restored(OTHER)) and git(rig.repo, "show", f"ticket/feat%2Fcsv/01:{OTHER}") == OTHER_TEST
225
230
  assert len(rig.calls("01", "test-writer")) == 3 and len(rig.calls("01", "implementer")) == 1, "one rerun, no implementer"
226
231
  assert "its commits also change demo/export.py" in rig.prompt("test-writer-0")
227
232
  assert "feat: 01 rows" not in rig.pr_subjects() and rig.state()["tickets"]["01"]["held"] == {}
228
233
 
229
234
 
235
+ MUTATION = "FAILED tests/test_01.py::test_x - AssertionError: fn_01 deleted"
236
+
237
+
238
+ def test_an_overrule_correction_whose_test_is_green_against_the_tip_reaches_the_review(tmp_path, capsys):
239
+ # Issue #134: the corrected test is green on the implementer's code, so its red line comes from a reverted mutation.
240
+ green = {**correction(), "stdout": MUTATION + "\n" + COST}
241
+ green["report"] = {**green["report"], "red": [{"test": "tests/test_01.py::test_x", "line": MUTATION}]}
242
+ scenario = plan(**{"01/test-writer": [tw("01"), green, green], "01/implementer": [partial(), impl("01")]})
243
+ rig = Inside(tmp_path, ONE).run(scenario)
244
+ rig.run(scenario, "--answer", f"{Q1}=overrule-test")
245
+ assert rig.code == 0, rig.ledger()
246
+ assert len(rig.calls("01", "test-writer")) == 2, "the green correction is accepted with no rerun"
247
+ assert "break the production line that the test protects" in rig.prompt("test-writer-0")
248
+ assert rig.state()["tickets"]["01"]["phase"] == "merged"
249
+
250
+
251
+ def test_an_overrule_correction_may_leave_the_overruled_concern_not_addressed(tmp_path, capsys):
252
+ keeps = {**correction(), "files": {}, "commit": None, "stdout": COST}
253
+ del keeps["files"], keeps["commit"]
254
+ keeps["report"] = {**keeps["report"], "commits": [], "files": [], "locked": [], "red": [],
255
+ "not_addressed": [{"finding": CONTRA, "reason": "the test is right"}]}
256
+ scenario = plan(**{"01/test-writer": [tw("01"), keeps, keeps], "01/implementer": [blocked(), impl("01")]})
257
+ rig = Inside(tmp_path, ONE).run(scenario)
258
+ rig.run(scenario, "--answer", f"{Q1}=overrule-test")
259
+ assert rig.code == 0, rig.ledger()
260
+ assert len(rig.calls("01", "test-writer")) == 2, "the concern is a target the correction can name"
261
+ assert f"- {CONTRA}" in rig.prompt("test-writer-0")
262
+ assert rig.led(f"Ticket 01: the test-writer correction did not correct {CONTRA}: the test is right.")
263
+
230
264
  def test_a_correction_of_its_own_file_leaves_the_work_in_the_tree_to_the_implementer(tmp_path, capsys):
231
265
  dirty = {**blocked(), "files": {"demo/export.py": "half = 1\n"}}
232
266
  # This correction commits only its test file: the implementer's file is out of the reach of `git add -A`.
@@ -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]
@@ -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.