@jesdi/skills 0.0.88 → 0.0.89

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.
@@ -17,23 +17,35 @@ DEFAULT_PATHS = {
17
17
  "infra": ["**/Dockerfile*"],
18
18
  "logic": ["**/SKILL.md", "**/AGENTS.md", "**/CLAUDE.md", "**/prompts/**"],
19
19
  }
20
- DEFAULT_POLICY = {"agentMerge": False, "paths": {}, "mergeMethod": None,
21
- "judgeMaxLines": 1500, "waitMinutes": 60,
22
- "alwaysHuman": ["schema/migration", "auth/security", "money", "data-delete",
23
- "infra"]}
20
+ # Risk of each category, 1 (harmless) to 10 (never merged by an agent). A repo overrides
21
+ # single entries with `categoryRisk`.
22
+ CATEGORY_RISK = {"docs": 1, "tests": 2, "ui": 3, "logic": 4, "deps": 5, "config": 6, "ci": 7,
23
+ "public-api": 7, "infra": 8, "schema/migration": 9, "auth/security": 10,
24
+ "money": 10, "data-delete": 10}
25
+ # A public repo never merges above this risk without a human; a repo that sets no
26
+ # `maxAutoRisk` gets it too.
27
+ PUBLIC_MAX_RISK = 3
28
+ DEFAULT_POLICY = {"maxAutoRisk": PUBLIC_MAX_RISK, "categoryRisk": {}, "paths": {},
29
+ "mergeMethod": None, "judgeMaxLines": 1500, "waitMinutes": 60}
30
+ REPLACED_KEYS = {"agentMerge": "maxAutoRisk", "alwaysHuman": "categoryRisk"}
24
31
 
25
32
 
26
33
  def is_int(v):
27
34
  return isinstance(v, int) and not isinstance(v, bool)
28
35
 
29
36
 
37
+ def is_risk(v, low=1):
38
+ return is_int(v) and low <= v <= 10
39
+
40
+
30
41
  def is_str_list(v):
31
42
  return isinstance(v, list) and all(isinstance(x, str) for x in v)
32
43
 
33
44
 
34
45
  POLICY_TYPES = {
35
- "agentMerge": lambda v: isinstance(v, bool),
36
- "alwaysHuman": lambda v: is_str_list(v) and all(c in CATEGORIES for c in v),
46
+ "maxAutoRisk": lambda v: is_risk(v, low=0),
47
+ "categoryRisk": lambda v: isinstance(v, dict) and all(
48
+ c in CATEGORIES and is_risk(r) for c, r in v.items()),
37
49
  "paths": lambda v: isinstance(v, dict) and all(
38
50
  c in CATEGORIES and is_str_list(g) for c, g in v.items()),
39
51
  "mergeMethod": lambda v: v in ("rebase", "merge", "squash"),
@@ -49,22 +61,30 @@ def git(*args, check=True):
49
61
  return p
50
62
 
51
63
 
64
+ def has_bracket_glob(paths):
65
+ return any("[" in g or "]" in g for globs in paths.values() for g in globs)
66
+
67
+
52
68
  def policy_error(key, value):
53
69
  """Why one policy entry is rejected, else None."""
70
+ if key in REPLACED_KEYS:
71
+ return f"policy: {key} was replaced by {REPLACED_KEYS[key]}"
54
72
  if key not in POLICY_TYPES:
55
73
  return f"policy: unknown key {key}"
56
74
  if not POLICY_TYPES[key](value):
57
75
  return f"policy: wrong type for {key}"
58
- if key == "paths" and any("[" in g or "]" in g for globs in value.values() for g in globs):
76
+ if key == "paths" and has_bracket_glob(value):
59
77
  return "policy: unsupported glob syntax in paths"
60
78
  return None
61
79
 
62
80
 
63
81
  def load_policy(base):
64
- """Policy from the base commit, never the PR head. Returns (policy, errors)."""
82
+ """Policy from the base commit, never the PR head. Returns (policy, errors).
83
+
84
+ No policy file on the base is an error: a PR must not merge itself under a policy it adds."""
65
85
  p = git("show", f"{base}:{POLICY_FILE}", check=False)
66
86
  if p.returncode:
67
- return dict(DEFAULT_POLICY), []
87
+ return dict(DEFAULT_POLICY), [f"policy: no {POLICY_FILE} on the base"]
68
88
  try:
69
89
  raw = json.loads(p.stdout)
70
90
  except ValueError:
@@ -9,15 +9,17 @@ import re
9
9
  import subprocess
10
10
  import sys
11
11
 
12
- from merge_policy import CATEGORIES, DEFAULT_PATHS, POLICY_FILE, git, load_policy # noqa: F401
12
+ from merge_policy import (CATEGORIES, CATEGORY_RISK, DEFAULT_PATHS, POLICY_FILE, # noqa: F401
13
+ PUBLIC_MAX_RISK, git, load_policy)
13
14
 
14
15
  ENUMS = {
15
16
  "door": ["one-way", "two-way"],
16
17
  "blast_radius": ["isolated", "module", "service", "consumers"],
17
18
  "rollback": ["revert", "revert+redeploy", "data-fix", "impossible"],
18
- "verdict": ["auto", "human"],
19
19
  }
20
- KEYS = [*ENUMS, "touches", "reasons"]
20
+ KEYS = [*ENUMS, "risk", "touches", "reasons"]
21
+ BLAST_RISK = {"isolated": 0, "module": 1, "service": 2, "consumers": 3}
22
+ ONE_WAY_ROLLBACKS = ("data-fix", "impossible")
21
23
  FENCE = re.compile(r"^```merge-risk v1[ \t]*\n(.*?)^```[ \t]*$", re.S | re.M)
22
24
 
23
25
 
@@ -149,6 +151,17 @@ class Block:
149
151
  if c and c not in CATEGORIES]
150
152
  if "reasons" in fields and not fields["reasons"]:
151
153
  self.errors.append("reasons must have at least one item")
154
+ self.read_risk()
155
+
156
+ def read_risk(self):
157
+ """Turn `risk` into an int from 1 to 10, or record why it is not one."""
158
+ risk = self.fields.get("risk")
159
+ if risk is None:
160
+ return
161
+ if re.fullmatch(r"[1-9]|10", risk):
162
+ self.fields["risk"] = int(risk)
163
+ else:
164
+ self.errors.append(f"risk: {risk!r} is not a whole number from 1 to 10")
152
165
 
153
166
 
154
167
  def parse_block(text):
@@ -254,21 +267,20 @@ def block_reasons(block, cats):
254
267
  return ["no merge-risk block"]
255
268
  if block["errors"]:
256
269
  return [f"invalid block: {e}" for e in block["errors"]]
270
+ # A one-way change is never merged by an agent, whatever the risk and the policy say.
257
271
  reasons = []
258
272
  if block["door"] == "one-way":
259
273
  reasons.append("door one-way")
260
- if block["rollback"] != "revert":
261
- reasons.append(f"rollback {block['rollback']}")
274
+ if block["rollback"] in ONE_WAY_ROLLBACKS:
275
+ reasons.append(f"rollback {block['rollback']} is one-way")
262
276
  return reasons + [f"diff touches {c}, not in touches"
263
277
  for c in sorted(cats - set(block["touches"]))]
264
278
 
265
279
 
266
- def diff_reasons(policy, touches, stats):
280
+ def diff_reasons(policy, stats):
267
281
  """Reasons from the policy and the diff stats."""
268
282
  cats, counted, unknown, policy_changed = stats
269
- reasons = [] if policy["agentMerge"] else ["agentMerge is off"]
270
- reasons += [f"{c} is always human" for c in sorted(touches | cats)
271
- if c in policy["alwaysHuman"]]
283
+ reasons = []
272
284
  if policy_changed:
273
285
  reasons.append(f"config: {POLICY_FILE} changed")
274
286
  reasons += [f"unknown line count: {p}" for p in unknown]
@@ -277,16 +289,47 @@ def diff_reasons(policy, touches, stats):
277
289
  return reasons
278
290
 
279
291
 
280
- def gate(body, base, head):
292
+ def risk_floor(policy, cats, block):
293
+ """The lowest risk the diff can have: its riskiest category, raised by blast radius and rollback.
294
+
295
+ The block's own `risk` can raise the score above this floor, never lower it."""
296
+ risks = {**CATEGORY_RISK, **policy["categoryRisk"]}
297
+ floor = max((risks[c] for c in cats), default=1) + BLAST_RISK[block["blast_radius"]]
298
+ floor += block["rollback"] == "revert+redeploy"
299
+ return min(floor, 10)
300
+
301
+
302
+ def risk_limit(policy, public):
303
+ """The highest risk an agent may merge: the repo's maxAutoRisk, never above 3 when public."""
304
+ return min(policy["maxAutoRisk"], PUBLIC_MAX_RISK) if public else policy["maxAutoRisk"]
305
+
306
+
307
+ def is_public_repo():
308
+ """Whether the checkout's GitHub repo is public. Unknown counts as public."""
309
+ try:
310
+ p = subprocess.run(["gh", "repo", "view", "--json", "isPrivate", "--jq", ".isPrivate"],
311
+ text=True, capture_output=True)
312
+ except OSError: # no gh
313
+ return True
314
+ return not (p.returncode == 0 and p.stdout.strip() == "true")
315
+
316
+
317
+ def gate(body, base, head, public=True):
318
+ """The merge verdict. `public` defaults to True so a caller that predates it gets the strict cap."""
281
319
  block = parse(body)
282
320
  base, policy, reasons = base_policy(base)
283
321
  stats = diff_stats(classify_diff(base, head, policy)[1])
284
322
  cats, counted = stats[0], stats[1]
285
323
  reasons += block_reasons(block, cats)
286
324
  touches = set(block["touches"]) if not block["errors"] else set()
287
- reasons += diff_reasons(policy, touches, stats)
288
- return {"verdict": "human" if reasons else "auto", "reasons": reasons,
289
- "categories": sorted(cats), "countedLines": counted}
325
+ reasons += diff_reasons(policy, stats)
326
+ risk = 10 if block["errors"] else max(risk_floor(policy, cats | touches, block), block["risk"])
327
+ limit = risk_limit(policy, public)
328
+ if risk > limit:
329
+ capped = limit < policy["maxAutoRisk"]
330
+ reasons.append(f"risk {risk} > max auto risk {limit}" + (" (public repo)" if capped else ""))
331
+ return {"verdict": "human" if reasons else "auto", "reasons": reasons, "risk": risk,
332
+ "maxAutoRisk": limit, "categories": sorted(cats), "countedLines": counted}
290
333
 
291
334
 
292
335
  def is_gate_call(argv):
@@ -296,7 +339,7 @@ def is_gate_call(argv):
296
339
  def main(argv):
297
340
  if is_gate_call(argv):
298
341
  with open(argv[3]) as f:
299
- print(json.dumps(gate(f.read(), argv[5], argv[7])))
342
+ print(json.dumps(gate(f.read(), argv[5], argv[7], is_public_repo())))
300
343
  return 0
301
344
  if len(argv) != 3 or argv[1] not in ("parse", "validate"):
302
345
  print(__doc__, file=sys.stderr)
@@ -20,7 +20,7 @@ door: two-way
20
20
  blast_radius: isolated
21
21
  touches: [docs, tests]
22
22
  rollback: revert
23
- verdict: auto
23
+ risk: 1
24
24
  reasons:
25
25
  - "Only skill prose and its tests change"
26
26
  ```
@@ -47,7 +47,7 @@ def make_repo(tmp_path, policy=True):
47
47
  git(seed, "push", str(origin), "main")
48
48
  git(tmp_path, "clone", str(origin), str(repo))
49
49
  if policy:
50
- (repo / ".merge-risk.json").write_text('{"agentMerge": true}\n')
50
+ (repo / ".merge-risk.json").write_text('{"maxAutoRisk": 3}\n')
51
51
  return repo
52
52
 
53
53
 
@@ -1,6 +1,6 @@
1
1
  """Acceptance tests for `merge_risk.py parse|validate`, through the command line only.
2
2
 
3
- `parse` prints one JSON object: door, blast_radius, touches, rollback, verdict,
3
+ `parse` prints one JSON object: door, blast_radius, touches, rollback, risk,
4
4
  reasons and errors (a list of messages, empty when the block is valid).
5
5
  """
6
6
  import json
@@ -14,7 +14,7 @@ VALID = '''door: two-way # one-way | two-way
14
14
  blast_radius: isolated
15
15
  touches: [docs, tests]
16
16
  rollback: revert
17
- verdict: auto
17
+ risk: 1
18
18
  reasons:
19
19
  - "Only skill prose and its tests change"
20
20
  '''
@@ -2,8 +2,10 @@
2
2
 
3
3
  Each test builds a temp git repo: `origin/<base>` is a remote-tracking ref that holds the
4
4
  policy, the head commit is the PR. The gate prints one JSON object on stdout:
5
- `verdict` ("auto" | "human"), `reasons` (every reason that made it human),
6
- `categories` (categories of the diff) and `countedLines`.
5
+ `verdict` ("auto" | "human"), `reasons` (every reason that made it human), `risk` (1-10),
6
+ `maxAutoRisk` (the limit that applied), `categories` (categories of the diff) and `countedLines`.
7
+ `gh` is a fake on PATH that answers `gh repo view` with $FAKE_PRIVATE ("true" | "false"); unset,
8
+ it fails, and the repo counts as public.
7
9
  """
8
10
  import json
9
11
  import os
@@ -53,27 +55,40 @@ def policy(**kw):
53
55
  return {POLICY: json.dumps(kw)}
54
56
 
55
57
 
56
- def block(door="two-way", touches="docs", rollback="revert", verdict="auto"):
58
+ def block(door="two-way", touches="docs", rollback="revert", risk=1, blast="isolated"):
57
59
  return (
58
60
  "## Summary\n\nText.\n\n## Merge Danger\n\n```merge-risk v1\n"
59
- f"door: {door}\nblast_radius: isolated\ntouches: [{touches}]\n"
60
- f"rollback: {rollback}\nverdict: {verdict}\n"
61
+ f"door: {door}\nblast_radius: {blast}\ntouches: [{touches}]\n"
62
+ f"rollback: {rollback}\nrisk: {risk}\n"
61
63
  'reasons:\n - "Small and reversible"\n```\n'
62
64
  )
63
65
 
64
66
 
65
- def gate(tmp_path, repo, sha, body, base="main"):
67
+ FAKE_GH = """#!/bin/sh
68
+ [ "$1 $2" = "repo view" ] && [ -n "$FAKE_PRIVATE" ] && echo "$FAKE_PRIVATE" && exit 0
69
+ exit 1
70
+ """
71
+
72
+
73
+ def gate(tmp_path, repo, sha, body, base="main", private=None):
66
74
  f = tmp_path / "body.md"
67
75
  f.write_text(body)
76
+ bin_dir = tmp_path / "bin"
77
+ bin_dir.mkdir(exist_ok=True)
78
+ (bin_dir / "gh").write_text(FAKE_GH)
79
+ (bin_dir / "gh").chmod(0o755)
80
+ env = {**ENV, "PATH": f"{bin_dir}{os.pathsep}{ENV['PATH']}"}
81
+ if private is not None:
82
+ env["FAKE_PRIVATE"] = "true" if private else "false"
68
83
  proc = subprocess.run(
69
84
  [sys.executable, str(SCRIPT), "gate", "--body", str(f), "--base", base, "--head", sha],
70
- cwd=repo, env=ENV, text=True, capture_output=True, timeout=60)
85
+ cwd=repo, env=env, text=True, capture_output=True, timeout=60)
71
86
  assert proc.returncode == 0, f"gate exited {proc.returncode}: {proc.stderr or proc.stdout}"
72
87
  return json.loads(proc.stdout)
73
88
 
74
89
 
75
90
  def test_no_block_is_human(tmp_path):
76
- repo, sha = make_repo(tmp_path, policy(agentMerge=True), {"docs/a.md": "x\n"})
91
+ repo, sha = make_repo(tmp_path, policy(maxAutoRisk=3), {"docs/a.md": "x\n"})
77
92
  out = gate(tmp_path, repo, sha, "## Summary\n\nNo block here.\n")
78
93
  assert out["verdict"] == "human"
79
94
  assert "no merge-risk block" in out["reasons"]
@@ -81,7 +96,7 @@ def test_no_block_is_human(tmp_path):
81
96
 
82
97
  def test_repo_paths_add_to_defaults(tmp_path):
83
98
  repo, sha = make_repo(
84
- tmp_path, policy(agentMerge=True, paths={"money": ["src/billing/**"]}),
99
+ tmp_path, policy(maxAutoRisk=3, paths={"money": ["src/billing/**"]}),
85
100
  {"src/billing/invoice.py": "x\n", "db/migrations/0042_add.sql": "x\n"})
86
101
  out = gate(tmp_path, repo, sha, block(touches="money, schema/migration"))
87
102
  assert sorted(out["categories"]) == ["money", "schema/migration"]
@@ -89,40 +104,50 @@ def test_repo_paths_add_to_defaults(tmp_path):
89
104
 
90
105
  def test_repo_paths_extend_default_globs_of_existing_category(tmp_path):
91
106
  repo, sha = make_repo(
92
- tmp_path, policy(agentMerge=True, paths={"docs": ["notes/**"]}),
107
+ tmp_path, policy(maxAutoRisk=3, paths={"docs": ["notes/**"]}),
93
108
  {"docs/a.md": "x\n", "notes/b.txt": "x\n"})
94
109
  out = gate(tmp_path, repo, sha, block(touches="docs"))
95
110
  assert out["categories"] == ["docs"]
96
111
  assert out["verdict"] == "auto"
97
112
 
98
113
 
99
- def test_repo_always_human_replaces_defaults(tmp_path):
100
- repo, sha = make_repo(tmp_path, policy(agentMerge=True, alwaysHuman=["money"]),
114
+ def test_repo_category_risk_overrides_one_default(tmp_path):
115
+ repo, sha = make_repo(tmp_path, policy(maxAutoRisk=8, categoryRisk={"infra": 5}),
101
116
  {"Dockerfile": "FROM x\n"})
102
- out = gate(tmp_path, repo, sha, block(touches="infra"))
117
+ out = gate(tmp_path, repo, sha, block(touches="infra"), private=True)
118
+ assert out["risk"] == 5
103
119
  assert out["verdict"] == "auto"
104
120
  assert out["reasons"] == []
105
121
 
106
122
 
123
+ def test_old_policy_keys_name_their_replacement(tmp_path):
124
+ repo, sha = make_repo(tmp_path, policy(agentMerge=True, alwaysHuman=["money"]),
125
+ {"docs/a.md": "x\n"})
126
+ out = gate(tmp_path, repo, sha, block())
127
+ assert out["verdict"] == "human"
128
+ assert "policy: agentMerge was replaced by maxAutoRisk" in out["reasons"]
129
+ assert "policy: alwaysHuman was replaced by categoryRisk" in out["reasons"]
130
+
131
+
107
132
  def test_pr_cannot_loosen_its_own_policy(tmp_path):
108
133
  repo, sha = make_repo(
109
- tmp_path, policy(agentMerge=True),
110
- {"db/migrations/0042_add.sql": "x\n", **policy(agentMerge=True, alwaysHuman=[])})
111
- out = gate(tmp_path, repo, sha, block(touches="schema/migration, config"))
134
+ tmp_path, policy(maxAutoRisk=3),
135
+ {"db/migrations/0042_add.sql": "x\n", **policy(maxAutoRisk=10)})
136
+ out = gate(tmp_path, repo, sha, block(touches="schema/migration, config"), private=True)
112
137
  assert out["verdict"] == "human"
113
- assert "schema/migration is always human" in out["reasons"]
138
+ assert "risk 9 > max auto risk 3" in out["reasons"]
114
139
  assert "config: .merge-risk.json changed" in out["reasons"]
115
140
 
116
141
 
117
142
  def test_first_policy_file_is_not_used_by_its_own_pr(tmp_path):
118
- repo, sha = make_repo(tmp_path, {"README.md": "hi\n"}, policy(agentMerge=True))
143
+ repo, sha = make_repo(tmp_path, {"README.md": "hi\n"}, policy(maxAutoRisk=3))
119
144
  out = gate(tmp_path, repo, sha, block(touches="config"))
120
145
  assert out["verdict"] == "human"
121
- assert "agentMerge is off" in out["reasons"]
146
+ assert "policy: no .merge-risk.json on the base" in out["reasons"]
122
147
 
123
148
 
124
149
  def test_unknown_policy_key_is_human(tmp_path):
125
- repo, sha = make_repo(tmp_path, policy(agentMerge=True, autoMerge=True),
150
+ repo, sha = make_repo(tmp_path, policy(maxAutoRisk=3, autoMerge=True),
126
151
  {"docs/a.md": "x\n"})
127
152
  out = gate(tmp_path, repo, sha, block())
128
153
  assert out["verdict"] == "human"
@@ -130,7 +155,7 @@ def test_unknown_policy_key_is_human(tmp_path):
130
155
 
131
156
 
132
157
  def test_skill_md_is_logic_not_docs(tmp_path):
133
- repo, sha = make_repo(tmp_path, policy(agentMerge=True),
158
+ repo, sha = make_repo(tmp_path, policy(maxAutoRisk=3),
134
159
  {"skills/pr-risk/SKILL.md": "x\n"})
135
160
  out = gate(tmp_path, repo, sha, block(touches="docs"))
136
161
  assert out["verdict"] == "human"
@@ -138,7 +163,7 @@ def test_skill_md_is_logic_not_docs(tmp_path):
138
163
 
139
164
 
140
165
  def test_instruction_file_under_docs_counts_as_logic_with_its_lines(tmp_path):
141
- repo, sha = make_repo(tmp_path, policy(agentMerge=True, judgeMaxLines=3),
166
+ repo, sha = make_repo(tmp_path, policy(maxAutoRisk=3, judgeMaxLines=3),
142
167
  {"docs/SKILL.md": "a\nb\nc\nd\ne\n"})
143
168
  out = gate(tmp_path, repo, sha, block(touches="docs, logic"))
144
169
  assert out["categories"] == ["logic"]
@@ -146,41 +171,90 @@ def test_instruction_file_under_docs_counts_as_logic_with_its_lines(tmp_path):
146
171
  assert out["verdict"] == "human"
147
172
 
148
173
 
149
- def test_one_way_door_is_human_whatever_verdict_says(tmp_path):
150
- repo, sha = make_repo(tmp_path, policy(agentMerge=True), {"docs/a.md": "x\n"})
151
- out = gate(tmp_path, repo, sha, block(door="one-way", verdict="auto"))
174
+ def test_one_way_door_is_human_at_any_risk_and_limit(tmp_path):
175
+ repo, sha = make_repo(tmp_path, policy(maxAutoRisk=10), {"docs/a.md": "x\n"})
176
+ out = gate(tmp_path, repo, sha, block(door="one-way", risk=1), private=True)
152
177
  assert out["verdict"] == "human"
153
- assert "door one-way" in out["reasons"]
178
+ assert out["reasons"] == ["door one-way"]
179
+
180
+
181
+ def test_rollback_that_cannot_revert_is_one_way(tmp_path):
182
+ for rollback in ("data-fix", "impossible"):
183
+ sub = tmp_path / rollback
184
+ sub.mkdir()
185
+ repo, sha = make_repo(sub, policy(maxAutoRisk=10), {"docs/a.md": "x\n"})
186
+ out = gate(sub, repo, sha, block(rollback=rollback), private=True)
187
+ assert out["reasons"] == [f"rollback {rollback} is one-way"]
154
188
 
155
189
 
156
- def test_rollback_other_than_revert_is_human(tmp_path):
157
- repo, sha = make_repo(tmp_path, policy(agentMerge=True), {"docs/a.md": "x\n"})
158
- out = gate(tmp_path, repo, sha, block(rollback="revert+redeploy"))
190
+ def test_risk_floor_adds_blast_radius_and_redeploy(tmp_path):
191
+ repo, sha = make_repo(tmp_path, policy(maxAutoRisk=10), {"src/app.py": "x\n"})
192
+ out = gate(tmp_path, repo, sha, block(touches="logic", blast="service",
193
+ rollback="revert+redeploy"), private=True)
194
+ assert out["risk"] == 4 + 2 + 1
195
+ assert out["verdict"] == "auto"
196
+
197
+
198
+ def test_block_risk_raises_the_floor_but_never_lowers_it(tmp_path):
199
+ repo, sha = make_repo(tmp_path, policy(maxAutoRisk=5), {"src/app.py": "x\n"})
200
+ assert gate(tmp_path, repo, sha, block(touches="logic", risk=6), private=True)["risk"] == 6
201
+ out = gate(tmp_path, repo, sha, block(touches="logic", risk=1), private=True)
202
+ assert out["risk"] == 4
203
+ assert out["verdict"] == "auto"
204
+
205
+
206
+ def test_risk_above_the_repo_limit_is_human(tmp_path):
207
+ repo, sha = make_repo(tmp_path, policy(maxAutoRisk=3), {"src/app.py": "x\n"})
208
+ out = gate(tmp_path, repo, sha, block(touches="logic"), private=True)
159
209
  assert out["verdict"] == "human"
210
+ assert out["reasons"] == ["risk 4 > max auto risk 3"]
211
+
212
+
213
+ def test_public_repo_caps_the_limit_at_3(tmp_path):
214
+ repo, sha = make_repo(tmp_path, policy(maxAutoRisk=8), {"src/app.py": "x\n"})
215
+ out = gate(tmp_path, repo, sha, block(touches="logic"), private=False)
216
+ assert out["maxAutoRisk"] == 3
217
+ assert out["reasons"] == ["risk 4 > max auto risk 3 (public repo)"]
218
+
219
+
220
+ def test_unknown_visibility_counts_as_public(tmp_path):
221
+ repo, sha = make_repo(tmp_path, policy(maxAutoRisk=8), {"src/app.py": "x\n"})
222
+ assert gate(tmp_path, repo, sha, block(touches="logic"))["maxAutoRisk"] == 3
223
+
224
+
225
+ def test_limit_defaults_to_3_when_the_policy_sets_none(tmp_path):
226
+ repo, sha = make_repo(tmp_path, policy(), {"src/app.py": "x\n"})
227
+ assert gate(tmp_path, repo, sha, block(touches="logic"), private=True)["maxAutoRisk"] == 3
228
+
229
+
230
+ def test_invalid_risk_is_an_invalid_block(tmp_path):
231
+ repo, sha = make_repo(tmp_path, policy(maxAutoRisk=3), {"docs/a.md": "x\n"})
232
+ out = gate(tmp_path, repo, sha, block(risk=11))
233
+ assert "invalid block: risk: '11' is not a whole number from 1 to 10" in out["reasons"]
234
+ assert out["risk"] == 10
160
235
 
161
236
 
162
237
  def test_undeclared_migration_is_human(tmp_path):
163
- repo, sha = make_repo(tmp_path, policy(agentMerge=True),
238
+ repo, sha = make_repo(tmp_path, policy(maxAutoRisk=3),
164
239
  {"src/app.py": "x\n", "tests/test_app.py": "x\n",
165
240
  "db/migrations/0042_add.sql": "x\n"})
166
241
  out = gate(tmp_path, repo, sha, block(touches="logic, tests"))
167
242
  assert out["verdict"] == "human"
168
243
  assert "diff touches schema/migration, not in touches" in out["reasons"]
169
- assert "schema/migration is always human" in out["reasons"]
170
244
 
171
245
 
172
- def test_always_human_category_declared_only_in_body_is_human(tmp_path):
173
- repo, sha = make_repo(tmp_path, policy(agentMerge=True), {"src/app.py": "x\n"})
174
- out = gate(tmp_path, repo, sha, block(touches="logic, auth/security"))
175
- assert out["verdict"] == "human"
176
- assert "auth/security is always human" in out["reasons"]
246
+ def test_category_declared_only_in_body_counts_toward_risk(tmp_path):
247
+ repo, sha = make_repo(tmp_path, policy(maxAutoRisk=9), {"src/app.py": "x\n"})
248
+ out = gate(tmp_path, repo, sha, block(touches="logic, auth/security"), private=True)
249
+ assert out["risk"] == 10
250
+ assert out["reasons"] == ["risk 10 > max auto risk 9"]
177
251
 
178
252
 
179
- def test_agent_merge_false_is_human(tmp_path):
180
- repo, sha = make_repo(tmp_path, policy(agentMerge=False), {"docs/a.md": "x\n"})
253
+ def test_max_auto_risk_0_is_human(tmp_path):
254
+ repo, sha = make_repo(tmp_path, policy(maxAutoRisk=0), {"docs/a.md": "x\n"})
181
255
  out = gate(tmp_path, repo, sha, block())
182
256
  assert out["verdict"] == "human"
183
- assert "agentMerge is off" in out["reasons"]
257
+ assert "risk 1 > max auto risk 0" in out["reasons"]
184
258
 
185
259
 
186
260
  def counted_diff(n):
@@ -189,14 +263,14 @@ def counted_diff(n):
189
263
 
190
264
 
191
265
  def test_counted_lines_at_the_limit_is_auto(tmp_path):
192
- repo, sha = make_repo(tmp_path, policy(agentMerge=True), counted_diff(1500))
193
- out = gate(tmp_path, repo, sha, block(touches="deps, docs, logic"))
266
+ repo, sha = make_repo(tmp_path, policy(maxAutoRisk=5), counted_diff(1500))
267
+ out = gate(tmp_path, repo, sha, block(touches="deps, docs, logic"), private=True)
194
268
  assert out["countedLines"] == 1500
195
269
  assert out["verdict"] == "auto"
196
270
 
197
271
 
198
272
  def test_counted_lines_over_the_limit_is_human(tmp_path):
199
- repo, sha = make_repo(tmp_path, policy(agentMerge=True), counted_diff(1501))
273
+ repo, sha = make_repo(tmp_path, policy(maxAutoRisk=3), counted_diff(1501))
200
274
  out = gate(tmp_path, repo, sha, block(touches="deps, docs, logic"))
201
275
  assert out["verdict"] == "human"
202
276
  assert "1501 counted lines > 1500" in out["reasons"]
@@ -208,10 +282,21 @@ def test_stacked_base_uses_origin_parent_never_main(tmp_path):
208
282
  git(repo, "init", "-q", "-b", "work")
209
283
  main_sha = commit(repo, {"README.md": "hi\n"}, "main") # main: no policy
210
284
  git(repo, "update-ref", "refs/remotes/origin/main", main_sha)
211
- parent_sha = commit(repo, {**policy(agentMerge=True), "db/migrations/0001.sql": "x\n"},
285
+ parent_sha = commit(repo, {**policy(maxAutoRisk=3), "db/migrations/0001.sql": "x\n"},
212
286
  "parent")
213
287
  git(repo, "update-ref", "refs/remotes/origin/feat/parent", parent_sha)
214
288
  sha = commit(repo, {"docs/a.md": "x\n"}, "head")
215
289
  out = gate(tmp_path, repo, sha, block(), base="feat/parent")
216
290
  assert out["categories"] == ["docs"]
217
291
  assert out["verdict"] == "auto"
292
+
293
+
294
+ def test_a_caller_that_predates_public_gets_the_public_cap(tmp_path):
295
+ """An older babysit-pr calls gate(body, base, head): it must get the strict cap, not crash."""
296
+ repo, sha = make_repo(tmp_path, policy(maxAutoRisk=8), {"src/app.py": "x\n"})
297
+ code = (f"import sys, json; sys.path.insert(0, {str(SCRIPT.parent)!r}); import merge_risk;"
298
+ f"print(json.dumps(merge_risk.gate({block(touches='logic')!r}, 'main', {sha!r})))")
299
+ out = json.loads(subprocess.run([sys.executable, "-c", code], cwd=repo, env=ENV, text=True,
300
+ capture_output=True, check=True).stdout)
301
+ assert out["maxAutoRisk"] == 3
302
+ assert out["verdict"] == "human"
@@ -7,7 +7,7 @@ from test_merge_risk_gate import block, commit, gate, git, make_repo, policy, wr
7
7
  @pytest.mark.parametrize("pattern", ["src/billing[12]/**", "src/billing[!3]/**"])
8
8
  def test_unsupported_policy_glob_requires_human(tmp_path, pattern):
9
9
  repo, sha = make_repo(
10
- tmp_path, policy(agentMerge=True, paths={"money": [pattern]}),
10
+ tmp_path, policy(maxAutoRisk=3, paths={"money": [pattern]}),
11
11
  {"src/billing1/invoice.py": "amount = 1\n"})
12
12
  out = gate(tmp_path, repo, sha, block(touches="logic"))
13
13
  assert out["verdict"] == "human"
@@ -18,20 +18,20 @@ def test_unsupported_policy_glob_requires_human(tmp_path, pattern):
18
18
  def test_deleted_file_uses_merge_base_marker_and_base_tip_policy(tmp_path, was_generated):
19
19
  repo, _ = make_repo(
20
20
  tmp_path,
21
- {**policy(agentMerge=False),
21
+ {**policy(maxAutoRisk=0),
22
22
  "src/app.py": ("# @generated\n" if was_generated else "") + "x\n" * 1501},
23
23
  {"README.md": "hi\n"})
24
24
  ancestor = git(repo, "rev-parse", "HEAD")
25
25
  (repo / "src/app.py").unlink()
26
26
  sha = commit(repo, {}, "PR deletes app")
27
27
  # Build an independent base commit without moving the PR's checked-out branch.
28
- write(repo, {**policy(agentMerge=True),
28
+ write(repo, {**policy(maxAutoRisk=4),
29
29
  "src/app.py": ("" if was_generated else "# @generated\n") + "x\n" * 1501})
30
30
  git(repo, "add", "-A")
31
31
  tree = git(repo, "write-tree")
32
32
  base_tip = git(repo, "commit-tree", tree, "-p", ancestor, "-m", "base changes marker")
33
33
  git(repo, "update-ref", "refs/remotes/origin/main", base_tip)
34
- out = gate(tmp_path, repo, sha, block(touches="logic"))
35
- assert "agentMerge is off" not in out["reasons"]
34
+ out = gate(tmp_path, repo, sha, block(touches="logic"), private=True)
35
+ assert out["maxAutoRisk"] == 4 # the policy of the base tip, not of the merge base
36
36
  assert out["countedLines"] == (0 if was_generated else 1501)
37
37
  assert out["verdict"] == ("auto" if was_generated else "human")
@@ -1,6 +1,7 @@
1
1
  """Structure and behavior-preservation tests for the merge_risk refactor (ticket 17).
2
2
 
3
- Golden outputs were recorded from merge_risk.py before the refactor (commit 74ccb2c).
3
+ Golden outputs were recorded from merge_risk.py before the refactor (commit 74ccb2c), then
4
+ re-recorded when the block's `verdict` became `risk` and the gate began to score risk.
4
5
  """
5
6
  import ast
6
7
  import os
@@ -13,10 +14,10 @@ SCRIPT = HERE / "merge_risk.py"
13
14
  BRANCHES = (ast.If, ast.For, ast.While, ast.ExceptHandler, ast.IfExp,
14
15
  ast.comprehension)
15
16
 
16
- CASES = {'valid': 'door: two-way\nblast_radius: isolated\ntouches: [docs, tests]\nrollback: revert\nverdict: auto\nreasons:\n - "Only prose"\n', 'inline': 'door: two-way\nblast_radius: isolated\ntouches: [docs, tests]\nrollback: revert\nverdict: auto\nreasons: [a, "b, c"]\n', 'bad': 'door: sideways\ntouches: [docs, styles, ]\nrollback: revert\nrollback: x\nfoo: 1\nreasons: nope\n junk\n', 'emptyreasons': 'door: two-way\nblast_radius: isolated\ntouches: [docs, tests]\nrollback: revert\nverdict: auto\nreasons:\n', 'badreasons': 'door: two-way\nblast_radius: isolated\ntouches: [docs, tests]\nrollback: revert\nverdict: auto\nreasons:\n - a: b\n - ""\n - [x]\n - \'q\'x\'\n'}
17
- GOLDEN = {'valid:parse': [0, '{"door": "two-way", "blast_radius": "isolated", "rollback": "revert", "verdict": "auto", "touches": ["docs", "tests"], "reasons": ["Only prose"], "errors": []}\n'], 'valid:validate': [0, ''], 'inline:parse': [0, '{"door": "two-way", "blast_radius": "isolated", "rollback": "revert", "verdict": "auto", "touches": ["docs", "tests"], "reasons": ["a", "b, c"], "errors": []}\n'], 'inline:validate': [0, ''], 'bad:parse': [0, '{"door": "sideways", "blast_radius": null, "rollback": "revert", "verdict": null, "touches": ["docs", "styles", ""], "reasons": [], "errors": ["touches has an empty element", "duplicate key: rollback", "unknown key: foo", "reasons must be a `- item` list or an inline list", "unsupported line: junk", "missing key: blast_radius", "missing key: verdict", "door: \'sideways\' is not one of one-way | two-way", "unknown category: styles", "reasons must have at least one item"]}\n'], 'bad:validate': [1, "touches has an empty element\nduplicate key: rollback\nunknown key: foo\nreasons must be a `- item` list or an inline list\nunsupported line: junk\nmissing key: blast_radius\nmissing key: verdict\ndoor: 'sideways' is not one of one-way | two-way\nunknown category: styles\nreasons must have at least one item\n"], 'emptyreasons:parse': [0, '{"door": "two-way", "blast_radius": "isolated", "rollback": "revert", "verdict": "auto", "touches": ["docs", "tests"], "reasons": [], "errors": ["reasons must have at least one item"]}\n'], 'emptyreasons:validate': [1, 'reasons must have at least one item\n'], 'badreasons:parse': [0, '{"door": "two-way", "blast_radius": "isolated", "rollback": "revert", "verdict": "auto", "touches": ["docs", "tests"], "reasons": [], "errors": ["unsupported reason form: a: b", "empty reason", "unsupported reason form: [x]", "malformed quoted reason: \'q\'x\'", "reasons must have at least one item"]}\n'], 'badreasons:validate': [1, "unsupported reason form: a: b\nempty reason\nunsupported reason form: [x]\nmalformed quoted reason: 'q'x'\nreasons must have at least one item\n"]}
17
+ CASES = {'valid': 'door: two-way\nblast_radius: isolated\ntouches: [docs, tests]\nrollback: revert\nrisk: 1\nreasons:\n - "Only prose"\n', 'inline': 'door: two-way\nblast_radius: isolated\ntouches: [docs, tests]\nrollback: revert\nrisk: 1\nreasons: [a, "b, c"]\n', 'bad': 'door: sideways\ntouches: [docs, styles, ]\nrollback: revert\nrollback: x\nfoo: 1\nreasons: nope\n junk\n', 'emptyreasons': 'door: two-way\nblast_radius: isolated\ntouches: [docs, tests]\nrollback: revert\nrisk: 1\nreasons:\n', 'badreasons': 'door: two-way\nblast_radius: isolated\ntouches: [docs, tests]\nrollback: revert\nrisk: 1\nreasons:\n - a: b\n - ""\n - [x]\n - \'q\'x\'\n'}
18
+ GOLDEN = {'valid:parse': [0, '{"door": "two-way", "blast_radius": "isolated", "rollback": "revert", "risk": 1, "touches": ["docs", "tests"], "reasons": ["Only prose"], "errors": []}\n'], 'valid:validate': [0, ''], 'inline:parse': [0, '{"door": "two-way", "blast_radius": "isolated", "rollback": "revert", "risk": 1, "touches": ["docs", "tests"], "reasons": ["a", "b, c"], "errors": []}\n'], 'inline:validate': [0, ''], 'bad:parse': [0, '{"door": "sideways", "blast_radius": null, "rollback": "revert", "risk": null, "touches": ["docs", "styles", ""], "reasons": [], "errors": ["touches has an empty element", "duplicate key: rollback", "unknown key: foo", "reasons must be a `- item` list or an inline list", "unsupported line: junk", "missing key: blast_radius", "missing key: risk", "door: \'sideways\' is not one of one-way | two-way", "unknown category: styles", "reasons must have at least one item"]}\n'], 'bad:validate': [1, "touches has an empty element\nduplicate key: rollback\nunknown key: foo\nreasons must be a `- item` list or an inline list\nunsupported line: junk\nmissing key: blast_radius\nmissing key: risk\ndoor: 'sideways' is not one of one-way | two-way\nunknown category: styles\nreasons must have at least one item\n"], 'emptyreasons:parse': [0, '{"door": "two-way", "blast_radius": "isolated", "rollback": "revert", "risk": 1, "touches": ["docs", "tests"], "reasons": [], "errors": ["reasons must have at least one item"]}\n'], 'emptyreasons:validate': [1, 'reasons must have at least one item\n'], 'badreasons:parse': [0, '{"door": "two-way", "blast_radius": "isolated", "rollback": "revert", "risk": 1, "touches": ["docs", "tests"], "reasons": [], "errors": ["unsupported reason form: a: b", "empty reason", "unsupported reason form: [x]", "malformed quoted reason: \'q\'x\'", "reasons must have at least one item"]}\n'], 'badreasons:validate': [1, "unsupported reason form: a: b\nempty reason\nunsupported reason form: [x]\nmalformed quoted reason: 'q'x'\nreasons must have at least one item\n"]}
18
19
 
19
- GATE_GOLDEN = '{"verdict": "human", "reasons": ["diff touches logic, not in touches", "agentMerge is off"], "categories": ["docs", "logic"], "countedLines": 1}\n'
20
+ GATE_GOLDEN = '{"verdict": "human", "reasons": ["policy: no .merge-risk.json on the base", "diff touches logic, not in touches", "risk 4 > max auto risk 3"], "risk": 4, "maxAutoRisk": 3, "categories": ["docs", "logic"], "countedLines": 1}\n'
20
21
 
21
22
 
22
23
  def complexity(fn):