@jesdi/skills 0.0.63 → 0.0.64

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +15 -0
  2. package/package.json +2 -2
  3. package/skills/babysit-pr/SKILL.md +54 -0
  4. package/skills/babysit-pr/babysit.py +998 -0
  5. package/skills/babysit-pr/fixtures/gh +310 -0
  6. package/skills/babysit-pr/hooks/post-pr-create.sh +56 -0
  7. package/skills/babysit-pr/hooks.json +10 -0
  8. package/skills/babysit-pr/judge-prompt.md +10 -0
  9. package/skills/babysit-pr/test_babysit.py +242 -0
  10. package/skills/babysit-pr/test_babysit_judge.py +286 -0
  11. package/skills/babysit-pr/test_babysit_judge_diff.py +25 -0
  12. package/skills/babysit-pr/test_babysit_judge_isolation.py +61 -0
  13. package/skills/babysit-pr/test_checks_regressions.py +210 -0
  14. package/skills/babysit-pr/test_comment_fidelity.py +88 -0
  15. package/skills/babysit-pr/test_comment_identity.py +70 -0
  16. package/skills/babysit-pr/test_e2e_setup.py +74 -0
  17. package/skills/babysit-pr/test_handoff_takeover.py +141 -0
  18. package/skills/babysit-pr/test_handoff_terminal.py +29 -0
  19. package/skills/babysit-pr/test_hook_quoting.py +25 -0
  20. package/skills/babysit-pr/test_hooks.py +62 -0
  21. package/skills/babysit-pr/test_lease_regressions.py +198 -0
  22. package/skills/babysit-pr/test_merge_and_handoff.py +260 -0
  23. package/skills/babysit-pr/test_merge_base_pin.py +10 -0
  24. package/skills/babysit-pr/test_merge_gate.py +124 -0
  25. package/skills/babysit-pr/test_merge_session_safety.py +117 -0
  26. package/skills/babysit-pr/test_merged_pr_labels.py +144 -0
  27. package/skills/babysit-pr/test_owner_comment_edits.py +26 -0
  28. package/skills/babysit-pr/test_owner_comments.py +316 -0
  29. package/skills/babysit-pr/test_retry_and_stall_hardening.py +143 -0
  30. package/skills/babysit-pr/test_rounds_and_checks.py +305 -0
  31. package/skills/babysit-pr/test_terminal_label_regressions.py +117 -0
  32. package/skills/babysit-pr/test_trusted_merge_risk.py +184 -0
  33. package/skills/babysit-pr/test_update_plan.py +157 -0
  34. package/skills/implement-spec/README.md +1 -1
  35. package/skills/implement-spec/SKILL.md +1 -1
  36. package/skills/implement-spec/driver_final.py +49 -10
  37. package/skills/implement-spec/prompts/pr-writer.md +3 -2
  38. package/skills/implement-spec/tests/test_final.py +112 -1
  39. package/skills/implement-spec/tests/test_tidy.py +2 -2
  40. package/skills/implement-spec/tests/test_walk.py +2 -2
  41. package/skills/pr-risk/SKILL.md +33 -0
  42. package/skills/pr-risk/hooks/pre-pr-create.sh +274 -0
  43. package/skills/pr-risk/hooks.json +10 -0
  44. package/skills/pr-risk/merge_policy.py +81 -0
  45. package/skills/pr-risk/merge_risk.py +314 -0
  46. package/skills/pr-risk/test_hook_commands.py +47 -0
  47. package/skills/pr-risk/test_hook_heredoc.py +16 -0
  48. package/skills/pr-risk/test_hook_substitution.py +40 -0
  49. package/skills/pr-risk/test_hooks.py +175 -0
  50. package/skills/pr-risk/test_merge_risk.py +97 -0
  51. package/skills/pr-risk/test_merge_risk_gate.py +217 -0
  52. package/skills/pr-risk/test_merge_risk_regressions.py +37 -0
  53. package/skills/pr-risk/test_merge_risk_structure.py +101 -0
  54. package/skills-manifest.json +15 -3
@@ -0,0 +1,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
+ }
@@ -0,0 +1,81 @@
1
+ """Merge-risk policy: categories, default paths, the repo policy file and its validation."""
2
+ import json
3
+ import subprocess
4
+
5
+ CATEGORIES = ["docs", "tests", "ci", "deps", "config", "schema/migration", "auth/security",
6
+ "public-api", "infra", "money", "data-delete", "ui", "logic"]
7
+ POLICY_FILE = ".merge-risk.json"
8
+ LOCKFILES = ["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "poetry.lock",
9
+ "uv.lock", "Pipfile.lock", "Cargo.lock", "Gemfile.lock", "go.sum", "composer.lock"]
10
+ DEFAULT_PATHS = {
11
+ "docs": ["docs/**", "README*", "*.md"],
12
+ "tests": ["tests/**", "**/test_*.py", "**/*_test.py", "**/*.test.*", "**/*.spec.*"],
13
+ "ci": [".github/workflows/**"],
14
+ "deps": [f"**/{n}" for n in LOCKFILES],
15
+ "config": [POLICY_FILE],
16
+ "schema/migration": ["**/migrations/**"],
17
+ "infra": ["**/Dockerfile*"],
18
+ "logic": ["**/SKILL.md", "**/AGENTS.md", "**/CLAUDE.md", "**/prompts/**"],
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"]}
24
+
25
+
26
+ def is_int(v):
27
+ return isinstance(v, int) and not isinstance(v, bool)
28
+
29
+
30
+ def is_str_list(v):
31
+ return isinstance(v, list) and all(isinstance(x, str) for x in v)
32
+
33
+
34
+ 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),
37
+ "paths": lambda v: isinstance(v, dict) and all(
38
+ c in CATEGORIES and is_str_list(g) for c, g in v.items()),
39
+ "mergeMethod": lambda v: v in ("rebase", "merge", "squash"),
40
+ "judgeMaxLines": is_int,
41
+ "waitMinutes": is_int,
42
+ }
43
+
44
+
45
+ def git(*args, check=True):
46
+ p = subprocess.run(["git", *args], text=True, capture_output=True)
47
+ if check and p.returncode:
48
+ raise SystemExit(f"git {' '.join(args)}: {p.stderr.strip()}")
49
+ return p
50
+
51
+
52
+ def policy_error(key, value):
53
+ """Why one policy entry is rejected, else None."""
54
+ if key not in POLICY_TYPES:
55
+ return f"policy: unknown key {key}"
56
+ if not POLICY_TYPES[key](value):
57
+ 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):
59
+ return "policy: unsupported glob syntax in paths"
60
+ return None
61
+
62
+
63
+ def load_policy(base):
64
+ """Policy from the base commit, never the PR head. Returns (policy, errors)."""
65
+ p = git("show", f"{base}:{POLICY_FILE}", check=False)
66
+ if p.returncode:
67
+ return dict(DEFAULT_POLICY), []
68
+ try:
69
+ raw = json.loads(p.stdout)
70
+ except ValueError:
71
+ return dict(DEFAULT_POLICY), ["policy: invalid JSON"]
72
+ if not isinstance(raw, dict):
73
+ return dict(DEFAULT_POLICY), ["policy: not an object"]
74
+ policy, errors = dict(DEFAULT_POLICY), []
75
+ for key, value in raw.items():
76
+ err = policy_error(key, value)
77
+ if err:
78
+ errors.append(err)
79
+ else:
80
+ policy[key] = value
81
+ return policy, errors
@@ -0,0 +1,314 @@
1
+ #!/usr/bin/env python3
2
+ """Parse and validate the ```merge-risk v1 block of a PR body.
3
+
4
+ Usage: merge_risk.py parse|validate <body-file>
5
+ merge_risk.py gate --body <file> --base <ref> --head <sha>
6
+ """
7
+ import json
8
+ import re
9
+ import subprocess
10
+ import sys
11
+
12
+ from merge_policy import CATEGORIES, DEFAULT_PATHS, POLICY_FILE, git, load_policy # noqa: F401
13
+
14
+ ENUMS = {
15
+ "door": ["one-way", "two-way"],
16
+ "blast_radius": ["isolated", "module", "service", "consumers"],
17
+ "rollback": ["revert", "revert+redeploy", "data-fix", "impossible"],
18
+ "verdict": ["auto", "human"],
19
+ }
20
+ KEYS = [*ENUMS, "touches", "reasons"]
21
+ FENCE = re.compile(r"^```merge-risk v1[ \t]*\n(.*?)^```[ \t]*$", re.S | re.M)
22
+
23
+
24
+ def strip_comment(line):
25
+ quote = None
26
+ for i, ch in enumerate(line):
27
+ if quote:
28
+ quote = None if ch == quote else quote
29
+ elif ch in "\"'":
30
+ quote = ch
31
+ elif ch == "#":
32
+ return line[:i].rstrip()
33
+ return line.rstrip()
34
+
35
+
36
+ def unquote(v):
37
+ return v[1:-1] if len(v) >= 2 and v[0] == v[-1] and v[0] in "\"'" else v
38
+
39
+
40
+ def split_inline(value):
41
+ """Split the inside of `[a, b]` on commas outside quotes; keep empty elements."""
42
+ parts, cur, quote = [], "", None
43
+ for ch in value:
44
+ if quote:
45
+ quote = None if ch == quote else quote
46
+ elif ch in "\"'":
47
+ quote = ch
48
+ elif ch == ",":
49
+ parts.append(cur.strip())
50
+ cur = ""
51
+ continue
52
+ cur += ch
53
+ parts.append(cur.strip())
54
+ return parts
55
+
56
+
57
+ def quoted_reason_error(v):
58
+ """Why a quoted reason is malformed or empty, else None."""
59
+ if len(v) < 2 or v[-1] != v[0] or v[0] in v[1:-1]:
60
+ return f"malformed quoted reason: {v}"
61
+ return None if v[1:-1].strip() else "empty reason"
62
+
63
+
64
+ def reason_error(v):
65
+ """Why a reason is not a plain or fully quoted scalar, else None."""
66
+ if not v:
67
+ return "empty reason"
68
+ if v[0] in "\"'":
69
+ return quoted_reason_error(v)
70
+ if v[0] in "[{-" or re.search(r":(\s|$)", v):
71
+ return f"unsupported reason form: {v}"
72
+ return None
73
+
74
+
75
+ def enum_errors(fields):
76
+ """One error per enum field whose value is not allowed."""
77
+ return [f"{k}: {fields[k]!r} is not one of {' | '.join(allowed)}"
78
+ for k, allowed in ENUMS.items() if k in fields and fields[k] not in allowed]
79
+
80
+
81
+ class Block:
82
+ """Fields and errors collected while reading one merge-risk block."""
83
+
84
+ def __init__(self):
85
+ self.fields, self.errors, self.in_reasons = {}, [], False
86
+
87
+ def add_reason(self, v):
88
+ """Add one reason, or record why it is not a plain or quoted scalar."""
89
+ err = reason_error(v)
90
+ if err:
91
+ self.errors.append(err)
92
+ else:
93
+ self.fields["reasons"].append(unquote(v))
94
+
95
+ def add_reasons_key(self, value):
96
+ """Handle `reasons:`: an inline list, or empty before `- item` lines."""
97
+ self.fields["reasons"] = []
98
+ if value.startswith("[") and value.endswith("]"):
99
+ for v in split_inline(value[1:-1]):
100
+ self.add_reason(v)
101
+ elif value:
102
+ self.errors.append("reasons must be a `- item` list or an inline list")
103
+
104
+ def add_touches_key(self, value):
105
+ """Handle `touches:`: it must be an inline list without empty elements."""
106
+ if not (value.startswith("[") and value.endswith("]")):
107
+ self.fields["touches"] = []
108
+ self.errors.append("touches must be an inline list like [docs, tests]")
109
+ return
110
+ items = split_inline(value[1:-1]) if value[1:-1].strip() else []
111
+ self.fields["touches"] = items
112
+ if "" in items:
113
+ self.errors.append("touches has an empty element")
114
+
115
+ def add_key(self, key, value):
116
+ """Store one `key: value` pair, or record an unknown or duplicate key."""
117
+ self.in_reasons = key == "reasons"
118
+ if key not in KEYS:
119
+ self.errors.append(f"unknown key: {key}")
120
+ elif key in self.fields:
121
+ self.errors.append(f"duplicate key: {key}")
122
+ elif key == "reasons":
123
+ self.add_reasons_key(value)
124
+ elif key == "touches":
125
+ self.add_touches_key(value)
126
+ else:
127
+ self.fields[key] = unquote(value)
128
+
129
+ def add_line(self, raw):
130
+ """Route one source line to a `- item` reason, a `key: value` pair, or an error."""
131
+ line = strip_comment(raw)
132
+ if not line.strip():
133
+ return
134
+ item = re.match(r"^\s+-\s+(.*)$", line)
135
+ if item and self.in_reasons:
136
+ return self.add_reason(item.group(1).strip())
137
+ m = re.match(r"^([a-z_]+):[ \t]*(.*)$", line)
138
+ if m:
139
+ self.add_key(m.group(1), m.group(2).strip())
140
+ else:
141
+ self.errors.append(f"unsupported line: {line.strip()}")
142
+
143
+ def validate(self):
144
+ """Append errors for missing keys, bad enum values, unknown categories, empty reasons."""
145
+ fields = self.fields
146
+ self.errors += [f"missing key: {k}" for k in KEYS if k not in fields]
147
+ self.errors += enum_errors(fields)
148
+ self.errors += [f"unknown category: {c}" for c in fields.get("touches", [])
149
+ if c and c not in CATEGORIES]
150
+ if "reasons" in fields and not fields["reasons"]:
151
+ self.errors.append("reasons must have at least one item")
152
+
153
+
154
+ def parse_block(text):
155
+ """Return (fields, errors) for the inside of one block."""
156
+ block = Block()
157
+ for raw in text.splitlines():
158
+ block.add_line(raw)
159
+ block.validate()
160
+ return block.fields, block.errors
161
+
162
+
163
+ def parse(body):
164
+ blocks = FENCE.findall(body)
165
+ if not blocks:
166
+ fields, errors = {}, ["no merge-risk block"]
167
+ elif len(blocks) > 1:
168
+ fields, errors = {}, ["more than one block"]
169
+ else:
170
+ fields, errors = parse_block(blocks[0])
171
+ out = {k: fields.get(k) for k in KEYS}
172
+ out["errors"] = errors
173
+ return out
174
+
175
+
176
+ def glob_re(glob):
177
+ out, i = "", 0
178
+ while i < len(glob):
179
+ if glob.startswith("**/", i):
180
+ out, i = out + "(?:.*/)?", i + 3
181
+ elif glob.startswith("**", i):
182
+ out, i = out + ".*", i + 2
183
+ else:
184
+ c = glob[i]
185
+ out += "[^/]*" if c == "*" else "[^/]" if c == "?" else re.escape(c)
186
+ i += 1
187
+ return re.compile(out + r"\Z")
188
+
189
+
190
+ def file_categories(path, paths):
191
+ cats = {c for c, globs in paths.items() if any(glob_re(g).match(path) for g in globs)}
192
+ if "logic" in cats:
193
+ cats.discard("docs")
194
+ return cats or {"logic"}
195
+
196
+
197
+ def is_generated(path, base, head):
198
+ if path.endswith(".snap") or any(glob_re(g).match(path) for g in DEFAULT_PATHS["deps"]):
199
+ return True
200
+ # the head version decides; only a deleted file falls back to its base version
201
+ blob = subprocess.run(["git", "show", f"{head}:{path}"], capture_output=True)
202
+ if blob.returncode:
203
+ blob = subprocess.run(["git", "show", f"{base}:{path}"], capture_output=True)
204
+ return b"@generated" in blob.stdout
205
+
206
+
207
+ def base_policy(base):
208
+ """(sha of origin/<base>, the policy committed there, policy errors as reasons)."""
209
+ sha = git("rev-parse", "--verify", f"origin/{base}^{{commit}}").stdout.strip()
210
+ return (sha, *load_policy(sha))
211
+
212
+
213
+ def classify_diff(base, head, policy):
214
+ """The one classification of a PR's files that the gate and the judge both read.
215
+
216
+ Returns (diff_base, files) for head against its merge-base with base (a commit sha).
217
+ Each file is (path, categories, lines, counted): lines is added plus removed, None when
218
+ unknown (binary, or hidden by a -diff attribute); docs and generated files are not counted.
219
+ Diff drivers of the repo never apply: they could hide counted lines.
220
+ """
221
+ diff_base = git("merge-base", base, head).stdout.strip()
222
+ paths = {c: list(g) for c, g in DEFAULT_PATHS.items()}
223
+ for c, globs in policy["paths"].items():
224
+ paths[c] = paths.get(c, []) + globs
225
+ out = git("diff", "-z", "--numstat", "--no-renames", "--no-textconv", "--no-ext-diff",
226
+ diff_base, head).stdout
227
+ files = []
228
+ for line in filter(None, out.split("\0")):
229
+ added, removed, path = line.split("\t", 2)
230
+ cats = file_categories(path, paths)
231
+ lines = None if added == "-" else int(added) + int(removed)
232
+ files.append((path, cats, lines,
233
+ "docs" not in cats and not is_generated(path, diff_base, head)))
234
+ return diff_base, files
235
+
236
+
237
+ def diff_stats(files):
238
+ """Return (categories, counted_lines, unknown_paths, policy_changed) of classified files."""
239
+ cats, counted, unknown = set(), 0, []
240
+ for path, file_cats, lines, is_counted in files:
241
+ cats |= file_cats
242
+ if not is_counted:
243
+ continue
244
+ if lines is None:
245
+ unknown.append(path)
246
+ else:
247
+ counted += lines
248
+ return cats, counted, unknown, any(path == POLICY_FILE for path, *_ in files)
249
+
250
+
251
+ def block_reasons(block, cats):
252
+ """Reasons from the parsed merge-risk block, given the categories the diff touches."""
253
+ if "no merge-risk block" in block["errors"]:
254
+ return ["no merge-risk block"]
255
+ if block["errors"]:
256
+ return [f"invalid block: {e}" for e in block["errors"]]
257
+ reasons = []
258
+ if block["door"] == "one-way":
259
+ reasons.append("door one-way")
260
+ if block["rollback"] != "revert":
261
+ reasons.append(f"rollback {block['rollback']}")
262
+ return reasons + [f"diff touches {c}, not in touches"
263
+ for c in sorted(cats - set(block["touches"]))]
264
+
265
+
266
+ def diff_reasons(policy, touches, stats):
267
+ """Reasons from the policy and the diff stats."""
268
+ 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"]]
272
+ if policy_changed:
273
+ reasons.append(f"config: {POLICY_FILE} changed")
274
+ reasons += [f"unknown line count: {p}" for p in unknown]
275
+ if counted > policy["judgeMaxLines"]:
276
+ reasons.append(f"{counted} counted lines > {policy['judgeMaxLines']}")
277
+ return reasons
278
+
279
+
280
+ def gate(body, base, head):
281
+ block = parse(body)
282
+ base, policy, reasons = base_policy(base)
283
+ stats = diff_stats(classify_diff(base, head, policy)[1])
284
+ cats, counted = stats[0], stats[1]
285
+ reasons += block_reasons(block, cats)
286
+ 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}
290
+
291
+
292
+ def is_gate_call(argv):
293
+ return len(argv) == 8 and argv[1] == "gate" and argv[2::2] == ["--body", "--base", "--head"]
294
+
295
+
296
+ def main(argv):
297
+ if is_gate_call(argv):
298
+ with open(argv[3]) as f:
299
+ print(json.dumps(gate(f.read(), argv[5], argv[7])))
300
+ return 0
301
+ if len(argv) != 3 or argv[1] not in ("parse", "validate"):
302
+ print(__doc__, file=sys.stderr)
303
+ return 2
304
+ with open(argv[2]) as f:
305
+ result = parse(f.read())
306
+ if argv[1] == "parse":
307
+ print(json.dumps(result))
308
+ return 0
309
+ print(*result["errors"], sep="\n", end="\n" if result["errors"] else "")
310
+ return 1 if result["errors"] else 0
311
+
312
+
313
+ if __name__ == "__main__":
314
+ sys.exit(main(sys.argv))