@jesdi/skills 0.0.62 → 0.0.64
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -0
- package/package.json +2 -2
- package/skills/babysit-pr/SKILL.md +54 -0
- package/skills/babysit-pr/babysit.py +998 -0
- package/skills/babysit-pr/fixtures/gh +310 -0
- package/skills/babysit-pr/hooks/post-pr-create.sh +56 -0
- package/skills/babysit-pr/hooks.json +10 -0
- package/skills/babysit-pr/judge-prompt.md +10 -0
- package/skills/babysit-pr/test_babysit.py +242 -0
- package/skills/babysit-pr/test_babysit_judge.py +286 -0
- package/skills/babysit-pr/test_babysit_judge_diff.py +25 -0
- package/skills/babysit-pr/test_babysit_judge_isolation.py +61 -0
- package/skills/babysit-pr/test_checks_regressions.py +210 -0
- package/skills/babysit-pr/test_comment_fidelity.py +88 -0
- package/skills/babysit-pr/test_comment_identity.py +70 -0
- package/skills/babysit-pr/test_e2e_setup.py +74 -0
- package/skills/babysit-pr/test_handoff_takeover.py +141 -0
- package/skills/babysit-pr/test_handoff_terminal.py +29 -0
- package/skills/babysit-pr/test_hook_quoting.py +25 -0
- package/skills/babysit-pr/test_hooks.py +62 -0
- package/skills/babysit-pr/test_lease_regressions.py +198 -0
- package/skills/babysit-pr/test_merge_and_handoff.py +260 -0
- package/skills/babysit-pr/test_merge_base_pin.py +10 -0
- package/skills/babysit-pr/test_merge_gate.py +124 -0
- package/skills/babysit-pr/test_merge_session_safety.py +117 -0
- package/skills/babysit-pr/test_merged_pr_labels.py +144 -0
- package/skills/babysit-pr/test_owner_comment_edits.py +26 -0
- package/skills/babysit-pr/test_owner_comments.py +316 -0
- package/skills/babysit-pr/test_retry_and_stall_hardening.py +143 -0
- package/skills/babysit-pr/test_rounds_and_checks.py +305 -0
- package/skills/babysit-pr/test_terminal_label_regressions.py +117 -0
- package/skills/babysit-pr/test_trusted_merge_risk.py +184 -0
- package/skills/babysit-pr/test_update_plan.py +157 -0
- package/skills/implement-spec/ARCHITECTURE.md +5 -0
- package/skills/implement-spec/README.md +7 -6
- package/skills/implement-spec/SKILL.md +1 -1
- package/skills/implement-spec/driver.py +11 -1
- package/skills/implement-spec/driver_decisions.py +23 -0
- package/skills/implement-spec/driver_final.py +49 -10
- package/skills/implement-spec/driver_fixloop.py +17 -5
- package/skills/implement-spec/driver_report.py +16 -5
- package/skills/implement-spec/driver_state.py +2 -2
- package/skills/implement-spec/prompts/pr-writer.md +3 -2
- package/skills/implement-spec/prompts/rejected.md +1 -0
- package/skills/implement-spec/tests/test_decisions.py +57 -0
- package/skills/implement-spec/tests/test_final.py +112 -1
- package/skills/implement-spec/tests/test_fixloop.py +14 -2
- package/skills/implement-spec/tests/test_report.py +18 -0
- package/skills/implement-spec/tests/test_review.py +1 -1
- package/skills/implement-spec/tests/test_state.py +1 -1
- package/skills/implement-spec/tests/test_tidy.py +2 -2
- package/skills/implement-spec/tests/test_walk.py +2 -2
- package/skills/pr-risk/SKILL.md +33 -0
- package/skills/pr-risk/hooks/pre-pr-create.sh +274 -0
- package/skills/pr-risk/hooks.json +10 -0
- package/skills/pr-risk/merge_policy.py +81 -0
- package/skills/pr-risk/merge_risk.py +314 -0
- package/skills/pr-risk/test_hook_commands.py +47 -0
- package/skills/pr-risk/test_hook_heredoc.py +16 -0
- package/skills/pr-risk/test_hook_substitution.py +40 -0
- package/skills/pr-risk/test_hooks.py +175 -0
- package/skills/pr-risk/test_merge_risk.py +97 -0
- package/skills/pr-risk/test_merge_risk_gate.py +217 -0
- package/skills/pr-risk/test_merge_risk_regressions.py +37 -0
- package/skills/pr-risk/test_merge_risk_structure.py +101 -0
- package/skills-manifest.json +15 -3
|
@@ -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))
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Regression coverage for PR command recognition and forbidden creation modes."""
|
|
2
|
+
import pytest
|
|
3
|
+
|
|
4
|
+
from test_hooks import VALID_BODY, assert_allow, assert_deny, make_repo, run_hook
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@pytest.mark.parametrize("agent", ["claude", "codex"])
|
|
8
|
+
@pytest.mark.parametrize("command", [
|
|
9
|
+
"if true; then gh pr create --fill; fi",
|
|
10
|
+
"if gh pr create --fill; then true; fi",
|
|
11
|
+
"if false; then true; else gh pr create --fill; fi",
|
|
12
|
+
"while false; do gh pr create --fill; done",
|
|
13
|
+
"gh --repo owner/repo pr create --fill",
|
|
14
|
+
"gh --repo=owner/repo pr create --fill",
|
|
15
|
+
"gh -R owner/repo pr create --fill",
|
|
16
|
+
"gh -Rowner/repo pr create --fill",
|
|
17
|
+
"gh pr --repo owner/repo create --fill",
|
|
18
|
+
"gh pr create --web --body-file body.md",
|
|
19
|
+
"gh pr create --fill --body-file body.md",
|
|
20
|
+
"gh pr create --fill-first --body-file body.md",
|
|
21
|
+
])
|
|
22
|
+
def test_creation_bypasses_are_denied_only_with_policy(tmp_path, agent, command):
|
|
23
|
+
repo = make_repo(tmp_path)
|
|
24
|
+
(repo / "body.md").write_text(VALID_BODY)
|
|
25
|
+
payload = {"tool_name": "Bash", "tool_input": {"command": command}, "cwd": str(repo)}
|
|
26
|
+
if agent == "claude":
|
|
27
|
+
payload["hook_event_name"] = "PreToolUse"
|
|
28
|
+
assert_deny(run_hook(payload), "the body must come from --body or --body-file",
|
|
29
|
+
"/pr, then /pr-risk")
|
|
30
|
+
(repo / ".merge-risk.json").unlink()
|
|
31
|
+
proc = run_hook(payload)
|
|
32
|
+
assert_allow(proc)
|
|
33
|
+
assert proc.stdout == ""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@pytest.mark.parametrize("command", [
|
|
37
|
+
"if true; then gh pr create --body-file body.md; fi",
|
|
38
|
+
"gh --repo owner/repo pr create --body-file body.md",
|
|
39
|
+
"gh pr create --title --web --body-file body.md",
|
|
40
|
+
"echo gh --repo owner/repo pr create --fill",
|
|
41
|
+
"gh --repo owner/repo pr view 12",
|
|
42
|
+
])
|
|
43
|
+
def test_valid_creations_and_other_commands_are_allowed(tmp_path, command):
|
|
44
|
+
repo = make_repo(tmp_path)
|
|
45
|
+
(repo / "body.md").write_text(VALID_BODY)
|
|
46
|
+
assert_allow(run_hook({"tool_name": "Bash", "tool_input": {"command": command},
|
|
47
|
+
"cwd": str(repo)}))
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Heredoc substitutions run as the shell runs them: continuations folded, before the line's `cd`."""
|
|
2
|
+
from test_hooks import assert_deny, claude, make_repo, run_hook
|
|
3
|
+
|
|
4
|
+
REASON = "the body must come from --body or --body-file"
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def test_continuation_inside_heredoc_does_not_hide_substitution(tmp_path):
|
|
8
|
+
repo = make_repo(tmp_path)
|
|
9
|
+
assert_deny(run_hook(claude("cat <<EOF\n$\\\n(gh pr create --fill)\nEOF", repo)), REASON)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def test_heredoc_substitution_runs_before_the_commands_cd(tmp_path):
|
|
13
|
+
repo = make_repo(tmp_path)
|
|
14
|
+
outside = tmp_path / "outside"
|
|
15
|
+
outside.mkdir()
|
|
16
|
+
assert_deny(run_hook(claude(f"cd {outside} <<EOF\n$(gh pr create --fill)\nEOF", repo)), REASON)
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Acceptance tests: `gh pr create` inside a command substitution, and shell quoting of the body."""
|
|
2
|
+
from test_hooks import NO_BLOCK_BODY, VALID_BODY, assert_allow, assert_deny, claude, make_repo, run_hook
|
|
3
|
+
|
|
4
|
+
BODY_FLAG_REASON = "the body must come from --body or --body-file"
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def test_substituted_fill_is_denied(tmp_path):
|
|
8
|
+
repo = make_repo(tmp_path)
|
|
9
|
+
assert_deny(run_hook(claude("url=$(gh pr create --fill)", repo)), BODY_FLAG_REASON)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def test_substituted_body_file_without_block_is_denied(tmp_path):
|
|
13
|
+
repo = make_repo(tmp_path)
|
|
14
|
+
(repo / "body.md").write_text(NO_BLOCK_BODY)
|
|
15
|
+
cmd = "url=$(gh pr create --title x --body-file /tmp/body.md)".replace("/tmp/body.md", str(repo / "body.md"))
|
|
16
|
+
assert_deny(run_hook(claude(cmd, repo)), "/pr, then /pr-risk")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_backtick_substitution_is_denied(tmp_path):
|
|
20
|
+
repo = make_repo(tmp_path)
|
|
21
|
+
assert_deny(run_hook(claude("url=`gh pr create --fill`", repo)), BODY_FLAG_REASON)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def test_single_quoted_substitution_body_is_literal_and_denied(tmp_path):
|
|
25
|
+
repo = make_repo(tmp_path)
|
|
26
|
+
(repo / "body.md").write_text(VALID_BODY)
|
|
27
|
+
cmd = "gh pr create --title x --body '$(cat body.md)'"
|
|
28
|
+
assert_deny(run_hook(claude(cmd, repo)), "/pr, then /pr-risk")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def test_double_quoted_substitution_body_is_expanded_and_allowed(tmp_path):
|
|
32
|
+
repo = make_repo(tmp_path)
|
|
33
|
+
(repo / "body.md").write_text(VALID_BODY)
|
|
34
|
+
assert_allow(run_hook(claude('gh pr create --title x --body "$(cat body.md)"', repo)))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def test_substitution_without_pr_create_allows_with_no_output(tmp_path):
|
|
38
|
+
repo = make_repo(tmp_path)
|
|
39
|
+
proc = run_hook(claude("x=$(git rev-parse HEAD) && echo $x", repo))
|
|
40
|
+
assert proc.returncode == 0 and proc.stdout.strip() == ""
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Acceptance tests for `hooks/pre-pr-create.sh`: agent payload JSON on stdin, agent output JSON on stdout.
|
|
2
|
+
|
|
3
|
+
Deny is `{"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny",
|
|
4
|
+
"permissionDecisionReason": ...}}`. Allow is empty stdout (or any output that is not a deny).
|
|
5
|
+
"""
|
|
6
|
+
import json
|
|
7
|
+
import subprocess
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
HOOK = Path(__file__).with_name("hooks") / "pre-pr-create.sh"
|
|
11
|
+
|
|
12
|
+
VALID_BODY = '''## Summary
|
|
13
|
+
|
|
14
|
+
Text.
|
|
15
|
+
|
|
16
|
+
## Merge Danger
|
|
17
|
+
|
|
18
|
+
```merge-risk v1
|
|
19
|
+
door: two-way
|
|
20
|
+
blast_radius: isolated
|
|
21
|
+
touches: [docs, tests]
|
|
22
|
+
rollback: revert
|
|
23
|
+
verdict: auto
|
|
24
|
+
reasons:
|
|
25
|
+
- "Only skill prose and its tests change"
|
|
26
|
+
```
|
|
27
|
+
'''
|
|
28
|
+
NO_BLOCK_BODY = "## Summary\n\nText, no block.\n"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def git(cwd, *args):
|
|
32
|
+
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args],
|
|
33
|
+
cwd=cwd, check=True, capture_output=True, text=True)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def make_repo(tmp_path, policy=True):
|
|
37
|
+
"""A clone of an origin whose base has no policy; the policy, when asked, is only in the working tree."""
|
|
38
|
+
origin = tmp_path / "origin.git"
|
|
39
|
+
seed = tmp_path / "seed"
|
|
40
|
+
repo = tmp_path / "repo"
|
|
41
|
+
git(tmp_path, "init", "--bare", "-b", "main", str(origin))
|
|
42
|
+
seed.mkdir()
|
|
43
|
+
git(seed, "init", "-b", "main")
|
|
44
|
+
(seed / "README.md").write_text("hi\n")
|
|
45
|
+
git(seed, "add", ".")
|
|
46
|
+
git(seed, "commit", "-m", "init")
|
|
47
|
+
git(seed, "push", str(origin), "main")
|
|
48
|
+
git(tmp_path, "clone", str(origin), str(repo))
|
|
49
|
+
if policy:
|
|
50
|
+
(repo / ".merge-risk.json").write_text('{"agentMerge": true}\n')
|
|
51
|
+
return repo
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def run_hook(payload):
|
|
55
|
+
return subprocess.run(["bash", str(HOOK)], input=json.dumps(payload),
|
|
56
|
+
text=True, capture_output=True, timeout=30)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def claude(command, cwd):
|
|
60
|
+
return {"hook_event_name": "PreToolUse", "tool_name": "Bash",
|
|
61
|
+
"tool_input": {"command": command}, "cwd": str(cwd)}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def decision(proc):
|
|
65
|
+
assert proc.returncode == 0, proc.stderr
|
|
66
|
+
if not proc.stdout.strip():
|
|
67
|
+
return None, ""
|
|
68
|
+
out = json.loads(proc.stdout)["hookSpecificOutput"]
|
|
69
|
+
assert out["hookEventName"] == "PreToolUse"
|
|
70
|
+
return out["permissionDecision"], out.get("permissionDecisionReason", "")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def assert_deny(proc, *needles):
|
|
74
|
+
verdict, reason = decision(proc)
|
|
75
|
+
assert verdict == "deny", proc.stdout
|
|
76
|
+
for n in needles:
|
|
77
|
+
assert n in reason, reason
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def assert_allow(proc):
|
|
81
|
+
assert decision(proc)[0] != "deny", proc.stdout
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def test_body_file_without_block_is_denied_with_the_fix(tmp_path):
|
|
85
|
+
repo = make_repo(tmp_path)
|
|
86
|
+
body = tmp_path / "body.md"
|
|
87
|
+
body.write_text(NO_BLOCK_BODY)
|
|
88
|
+
proc = run_hook(claude(f"gh pr create --title x --body-file {body}", repo))
|
|
89
|
+
assert_deny(proc, "/pr, then /pr-risk")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def test_valid_block_in_body_substitution_is_allowed(tmp_path):
|
|
93
|
+
repo = make_repo(tmp_path)
|
|
94
|
+
body = tmp_path / "body.md"
|
|
95
|
+
body.write_text(VALID_BODY)
|
|
96
|
+
proc = run_hook(claude(f'gh pr create --title x --body "$(cat {body})"', repo))
|
|
97
|
+
assert_allow(proc)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def test_fill_variants_and_no_body_flag_are_denied(tmp_path):
|
|
101
|
+
repo = make_repo(tmp_path)
|
|
102
|
+
for cmd in ("gh pr create --fill", "gh pr create --fill-first", "gh pr create --web",
|
|
103
|
+
"gh pr create --title x"):
|
|
104
|
+
assert_deny(run_hook(claude(cmd, repo)), "the body must come from --body or --body-file")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def test_repo_without_policy_allows_with_no_output(tmp_path):
|
|
108
|
+
repo = make_repo(tmp_path, policy=False)
|
|
109
|
+
proc = run_hook(claude("gh pr create --fill", repo))
|
|
110
|
+
assert proc.returncode == 0 and proc.stdout.strip() == ""
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def test_other_command_allows_with_no_output(tmp_path):
|
|
114
|
+
repo = make_repo(tmp_path)
|
|
115
|
+
proc = run_hook(claude("gh pr view 12", repo))
|
|
116
|
+
assert proc.returncode == 0 and proc.stdout.strip() == ""
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def test_policy_only_in_working_tree_still_enforces(tmp_path):
|
|
120
|
+
repo = make_repo(tmp_path)
|
|
121
|
+
assert (repo / ".merge-risk.json").exists()
|
|
122
|
+
assert_deny(run_hook(claude("gh pr create --fill", repo)))
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def test_codex_payload_is_denied(tmp_path):
|
|
126
|
+
repo = make_repo(tmp_path)
|
|
127
|
+
proc = run_hook({"tool_name": "Bash", "tool_input": {"command": "gh pr create --fill"},
|
|
128
|
+
"cwd": str(repo)})
|
|
129
|
+
assert proc.returncode == 0, proc.stderr
|
|
130
|
+
out = json.loads(proc.stdout)["hookSpecificOutput"]
|
|
131
|
+
assert out["hookEventName"] == "PreToolUse"
|
|
132
|
+
assert out["permissionDecision"] == "deny"
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def test_gh_pr_create_inside_a_longer_command_is_denied(tmp_path):
|
|
136
|
+
repo = make_repo(tmp_path)
|
|
137
|
+
outside = tmp_path / "outside"
|
|
138
|
+
outside.mkdir()
|
|
139
|
+
assert_deny(run_hook(claude(f"cd {repo} && gh pr create --fill", outside)))
|
|
140
|
+
(repo / "body.md").write_text(VALID_BODY)
|
|
141
|
+
assert_allow(run_hook(claude(f"cd {repo} && gh pr create --title x --body-file body.md", outside)))
|
|
142
|
+
(repo / "bad.md").write_text(NO_BLOCK_BODY)
|
|
143
|
+
assert_deny(run_hook(claude(f"cd {repo} && gh pr create --title x --body-file bad.md", outside)),
|
|
144
|
+
"/pr, then /pr-risk")
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def test_relative_body_file_resolves_against_cwd(tmp_path):
|
|
148
|
+
repo = make_repo(tmp_path)
|
|
149
|
+
(repo / "body.md").write_text(VALID_BODY)
|
|
150
|
+
assert_allow(run_hook(claude("gh pr create --title x --body-file body.md", repo)))
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def heredoc_command(body):
|
|
154
|
+
return f"gh pr create --title x --body \"$(cat <<'EOF'\n{body}EOF\n)\""
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def test_valid_block_in_quoted_heredoc_is_allowed(tmp_path):
|
|
158
|
+
repo = make_repo(tmp_path)
|
|
159
|
+
assert_allow(run_hook(claude(heredoc_command(VALID_BODY), repo)))
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def test_heredoc_body_without_block_is_denied(tmp_path):
|
|
163
|
+
repo = make_repo(tmp_path)
|
|
164
|
+
assert_deny(run_hook(claude(heredoc_command(NO_BLOCK_BODY), repo)), "/pr, then /pr-risk")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def test_malformed_existing_blocks_are_denied(tmp_path):
|
|
168
|
+
repo = make_repo(tmp_path)
|
|
169
|
+
bad_value = VALID_BODY.replace("door: two-way", "door: sideways")
|
|
170
|
+
missing_field = VALID_BODY.replace("rollback: revert\n", "")
|
|
171
|
+
duplicate = VALID_BODY + "\n" + VALID_BODY
|
|
172
|
+
for name, body in (("value", bad_value), ("missing", missing_field), ("dup", duplicate)):
|
|
173
|
+
(repo / f"{name}.md").write_text(body)
|
|
174
|
+
proc = run_hook(claude(f"gh pr create --title x --body-file {name}.md", repo))
|
|
175
|
+
assert_deny(proc, "/pr, then /pr-risk")
|