@greenrenge/skills 0.0.0-stage → 0.2.0

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 (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +99 -2
  3. package/bin/cli.mjs +525 -0
  4. package/bin/lib/onboard.mjs +1168 -0
  5. package/bin/lib/probe.mjs +631 -0
  6. package/catalog.json +590 -0
  7. package/package.json +50 -4
  8. package/skills/deck-story/SKILL.md +258 -0
  9. package/skills/deck-story/check-svg-text.mjs +94 -0
  10. package/skills/deck-story/check.mjs +348 -0
  11. package/skills/diagram-router/LICENSE +21 -0
  12. package/skills/diagram-router/SKILL.md +193 -0
  13. package/skills/diagram-router/THIRD_PARTY_NOTICES.md +15 -0
  14. package/skills/diagram-router/references/channels.md +213 -0
  15. package/skills/diagram-router/references/evals.md +85 -0
  16. package/skills/diagram-router/references/gathering.md +101 -0
  17. package/skills/diagram-router/references/prior-art.md +65 -0
  18. package/skills/diagram-router/references/routing.md +166 -0
  19. package/skills/diagram-router/skill-release.json +17 -0
  20. package/skills/frontend-design/SKILL.md +443 -0
  21. package/skills/frontend-design/references/rtl.md +72 -0
  22. package/skills/frontend-design/scripts/.upstream-sha +1 -0
  23. package/skills/frontend-design/scripts/LICENSE +21 -0
  24. package/skills/frontend-design/scripts/README.md +24 -0
  25. package/skills/frontend-design/scripts/gates.md +243 -0
  26. package/skills/frontend-design/scripts/sloplint-render.mjs +1283 -0
  27. package/skills/frontend-design/scripts/sloplint.mjs +4426 -0
  28. package/skills/open-code-review-rules/SKILL.md +59 -0
  29. package/skills/open-code-review-rules/references/ocr-allowlists.json +161 -0
  30. package/skills/open-code-review-rules/references/ocr-rule-semantics.md +39 -0
  31. package/skills/open-code-review-rules/scripts/verify_ocr_rules.py +836 -0
  32. package/skills/plain-english-mode/SKILL.md +41 -0
  33. package/skills/pr-diagram-portfolio/SKILL.md +75 -0
  34. package/skills/pr-diagram-portfolio/references/angle-framework.md +124 -0
  35. package/skills/pr-diagram-portfolio/references/portfolio-delivery.md +79 -0
  36. package/skills/pr-diagram-portfolio/scripts/restore_still_css.py +180 -0
  37. package/skills/pr-lens/LICENSE-upstream +21 -0
  38. package/skills/pr-lens/SKILL.md +99 -0
  39. package/skills/pr-lens/VENDOR.md +47 -0
  40. package/skills/pr-lens/package-lock.json +91 -0
  41. package/skills/pr-lens/package.json +9 -0
  42. package/skills/pr-lens/references/config.md +90 -0
  43. package/skills/pr-lens/references/example.graph.json +580 -0
  44. package/skills/pr-lens/references/graph-document.md +233 -0
  45. package/skills/pr-lens/skill-release.json +16 -0
  46. package/skills/security-remediation-epic/SKILL.md +316 -0
  47. package/skills/security-remediation-epic/prompt-template.md +33 -0
  48. package/skills/skill-maintainer/SKILL.md +99 -0
  49. package/skills/skill-maintainer/references/placement-and-coupling.md +43 -0
  50. package/skills/skill-maintainer/scripts/audit_skills.py +297 -0
  51. package/skills/t3-successor-handoff/SKILL.md +141 -0
  52. package/skills/t3-thread-bridge/SKILL.md +175 -0
  53. package/skills/t3-thread-bridge/references/launch-recipes.md +123 -0
  54. package/skills/t3-thread-bridge/references/ping-back.md +108 -0
  55. package/skills/t3-thread-bridge/scripts/thread_ledger.py +203 -0
  56. package/skills/t3-ticket-orchestrator/SKILL.md +304 -0
  57. package/skills/t3-ticket-orchestrator/references/proving-the-gates.md +63 -0
  58. package/skills/ticket-scheme/SKILL.md +144 -0
  59. package/skills/ulw-plan/SKILL.md +98 -0
  60. package/skills/ulw-plan/references/full-workflow.md +255 -0
  61. package/skills/ulw-plan/references/intent-clear.md +44 -0
  62. package/skills/ulw-plan/references/intent-unclear.md +44 -0
  63. package/skills/ulw-plan/scripts/plan-templates.mjs +180 -0
  64. package/skills/ulw-plan/scripts/scaffold-plan.mjs +187 -0
@@ -0,0 +1,836 @@
1
+ #!/usr/bin/env python3
2
+ """Verify .opencodereview/rule.json against alibaba/open-code-review (ocr) semantics.
3
+
4
+ Performs:
5
+ 1. Schema, type, and external rule-file validation (<= 512 KiB, confined to repo).
6
+ 2. Brace-expansion and glob lint matching OCR's expandBraces + doublestar rules.
7
+ 3. First-match-wins reachability, shadowing, and include/exclude conflict analysis.
8
+ 4. Extension allowlist and default-exclude alignment against ocr-allowlists.json.
9
+ 5. Live `ocr` CLI cross-check (`ocr delegate rule --format json` and optional `--preview`).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import functools
16
+ import json
17
+ import os
18
+ import posixpath
19
+ import re
20
+ import shutil
21
+ import subprocess
22
+ import sys
23
+ from dataclasses import asdict, dataclass, field
24
+ from pathlib import Path
25
+ from typing import Any
26
+
27
+ ALLOWED_TOP_KEYS = {"include", "exclude", "rules"}
28
+ ALLOWED_RULE_KEYS = {"path", "rule", "merge_system_rule"}
29
+ ALLOWED_RULE_FILE_EXTS = {".md", ".txt", ".markdown"}
30
+ MAX_RULE_FILE_BYTES = 512 * 1024
31
+ SECRET_ENV_EXCEPTIONS = {".env.example", ".env.sample", ".env.template"}
32
+
33
+
34
+ @dataclass
35
+ class Finding:
36
+ level: str # "error" | "warning" | "info"
37
+ code: str
38
+ message: str
39
+ rule_index: int | None = None
40
+ pattern: str | None = None
41
+
42
+
43
+ @dataclass
44
+ class RuleCoverage:
45
+ index: int
46
+ pattern: str
47
+ merge_system_rule: bool
48
+ total_repo_matches: int = 0
49
+ eligible_repo_matches: int = 0
50
+ excluded_repo_matches: int = 0
51
+ sample_eligible: list[str] = field(default_factory=list)
52
+ sample_excluded: list[tuple[str, str]] = field(default_factory=list)
53
+ ocr_cli_matches: int | None = None
54
+
55
+
56
+ def load_allowlists() -> dict[str, Any]:
57
+ ref_path = Path(__file__).resolve().parent.parent / "references" / "ocr-allowlists.json"
58
+ with ref_path.open("r", encoding="utf-8") as f:
59
+ return json.load(f)
60
+
61
+
62
+ def expand_braces(pattern: str) -> tuple[list[str], list[str]]:
63
+ """Mirror OCR's expandBraces(s) in internal/config/rules/system_rules.go.
64
+
65
+ Returns (expanded_patterns, lint_warnings).
66
+ """
67
+ warnings: list[str] = []
68
+ open_idx = pattern.find("{")
69
+ if open_idx < 0:
70
+ return [pattern], warnings
71
+
72
+ close_idx = pattern.find("}", open_idx)
73
+ if close_idx < 0:
74
+ warnings.append(f"Unclosed '{{' in pattern {pattern!r}")
75
+ return [pattern], warnings
76
+
77
+ inner = pattern[open_idx + 1 : close_idx]
78
+ rest = pattern[close_idx + 1 :]
79
+ if "{" in inner:
80
+ warnings.append(
81
+ f"Nested braces in {pattern!r}: OCR's expandBraces splits at the first '{{' and '}}', "
82
+ "which drops inner options."
83
+ )
84
+ if "{" in rest:
85
+ warnings.append(
86
+ f"Multiple brace groups in {pattern!r}: OCR's expandBraces only expands the first "
87
+ "'{...}' group; the second group is treated literally and will not match."
88
+ )
89
+
90
+ prefix = pattern[:open_idx]
91
+ options = inner.split(",")
92
+ if any(opt == "" for opt in options):
93
+ warnings.append(f"Empty brace option in {pattern!r}")
94
+ return [prefix + opt + rest for opt in options], warnings
95
+
96
+
97
+ @functools.lru_cache(maxsize=4096)
98
+ def _segment_to_regex(seg: str) -> re.Pattern[str]:
99
+ i = 0
100
+ n = len(seg)
101
+ out = ["^"]
102
+ while i < n:
103
+ c = seg[i]
104
+ if c == "*":
105
+ out.append(".*")
106
+ elif c == "?":
107
+ out.append(".")
108
+ elif c == "[":
109
+ j = i + 1
110
+ if j < n and seg[j] in ("!", "^"):
111
+ j += 1
112
+ if j < n and seg[j] == "]":
113
+ j += 1
114
+ while j < n and seg[j] != "]":
115
+ j += 1
116
+ if j >= n:
117
+ out.append(r"\[")
118
+ else:
119
+ body = seg[i + 1 : j]
120
+ if body.startswith("!"):
121
+ body = "^" + body[1:]
122
+ out.append("[" + body + "]")
123
+ i = j
124
+ elif c == "\\" and i + 1 < n:
125
+ i += 1
126
+ out.append(re.escape(seg[i]))
127
+ else:
128
+ out.append(re.escape(c))
129
+ i += 1
130
+ out.append("$")
131
+ return re.compile("".join(out))
132
+
133
+
134
+ @functools.lru_cache(maxsize=4096)
135
+ def _match_segments(pat_segs: tuple[str, ...], path_segs: tuple[str, ...]) -> bool:
136
+ pi, pj = 0, len(pat_segs)
137
+ si, sj = 0, len(path_segs)
138
+
139
+ @functools.lru_cache(maxsize=None)
140
+ def dp(i: int, j: int) -> bool:
141
+ if i == pj and j == sj:
142
+ return True
143
+ if i < pj and pat_segs[i] == "**":
144
+ # '**' matches zero segments or consumes one segment.
145
+ if dp(i + 1, j):
146
+ return True
147
+ if j < sj and dp(i, j + 1):
148
+ return True
149
+ return False
150
+ if i == pj or j == sj:
151
+ return False
152
+ if _segment_to_regex(pat_segs[i]).match(path_segs[j]):
153
+ return dp(i + 1, j + 1)
154
+ return False
155
+
156
+ return dp(pi, si)
157
+
158
+
159
+ def doublestar_match(pattern: str, path: str) -> bool:
160
+ """Case-insensitive doublestar match matching OCR's behavior."""
161
+ expanded, _ = expand_braces(pattern.lower())
162
+ clean_path = path.lower().lstrip("./")
163
+ path_segs = tuple(clean_path.split("/")) if clean_path else ("",)
164
+ for p in expanded:
165
+ clean_p = p.lstrip("./")
166
+ pat_segs = tuple(clean_p.split("/")) if clean_p else ("",)
167
+ if _match_segments(pat_segs, path_segs):
168
+ return True
169
+ return False
170
+
171
+
172
+ def doublestar_match_single(single_pattern: str, path: str) -> bool:
173
+ clean_path = path.lower().lstrip("./")
174
+ clean_p = single_pattern.lower().lstrip("./")
175
+ path_segs = tuple(clean_path.split("/")) if clean_path else ("",)
176
+ pat_segs = tuple(clean_p.split("/")) if clean_p else ("",)
177
+ return _match_segments(pat_segs, path_segs)
178
+
179
+
180
+ def sample_paths_for_single_pattern(single_pattern: str) -> list[str]:
181
+ """Generate concrete probe paths covering a single (brace-expanded) glob pattern."""
182
+ segs = single_pattern.lstrip("./").split("/")
183
+ concrete_variants: list[list[str]] = [[]]
184
+ for seg in segs:
185
+ if seg == "**":
186
+ next_variants: list[list[str]] = []
187
+ for v in concrete_variants:
188
+ next_variants.append(v) # 0 directories
189
+ next_variants.append(v + ["sub", "dir"]) # nested directories
190
+ concrete_variants = next_variants[:4]
191
+ continue
192
+
193
+ # Replace single-segment wildcards with concrete tokens.
194
+ s = seg
195
+ s = re.sub(r"\[([^\]]+)\]", lambda m: m.group(1).lstrip("!^")[:1] or "a", s)
196
+ s = s.replace("?", "x")
197
+ if s == "*":
198
+ tokens = ["file", "file.py"]
199
+ else:
200
+ tokens = [s.replace("*", "sample")]
201
+ next_variants = []
202
+ for v in concrete_variants:
203
+ for tok in tokens:
204
+ next_variants.append(v + [tok])
205
+ concrete_variants = next_variants[:6]
206
+
207
+ return ["/".join(v) for v in concrete_variants if v]
208
+
209
+
210
+ def looks_like_rule_file_path(rule_val: str) -> bool:
211
+ if "\n" in rule_val or " " in rule_val:
212
+ return False
213
+ _, ext = posixpath.splitext(rule_val.lower())
214
+ return ext in ALLOWED_RULE_FILE_EXTS
215
+
216
+
217
+ def is_secret_path(path: str, secret_patterns: list[str]) -> bool:
218
+ lower = path.lower()
219
+ base = posixpath.basename(lower)
220
+ if base == ".env" or (base.startswith(".env.") and base not in SECRET_ENV_EXCEPTIONS):
221
+ return True
222
+ return any(doublestar_match(pat, lower) for pat in secret_patterns)
223
+
224
+
225
+ def classify_file_selection(
226
+ path: str,
227
+ user_include: list[str],
228
+ user_exclude: list[str],
229
+ supported_exts: set[str],
230
+ default_excludes: list[str],
231
+ secret_patterns: list[str],
232
+ ) -> str:
233
+ """Return 'selected' or the OCR ExcludeReason."""
234
+ if is_secret_path(path, secret_patterns):
235
+ return "secret_exclude"
236
+ if any(doublestar_match(p, path) for p in user_exclude):
237
+ return "user_exclude"
238
+ if user_include and any(doublestar_match(p, path) for p in user_include):
239
+ return "selected"
240
+ _, ext = posixpath.splitext(path.lower())
241
+ if ext != "" and ext not in supported_exts:
242
+ return "unsupported_ext"
243
+ if any(doublestar_match(p, path) for p in default_excludes):
244
+ return "default_path"
245
+ return "selected"
246
+
247
+
248
+ def resolve_repo_root(repo_arg: str) -> Path:
249
+ p = Path(repo_arg).resolve()
250
+ res = subprocess.run(
251
+ ["git", "-C", str(p), "rev-parse", "--show-toplevel"],
252
+ capture_output=True,
253
+ text=True,
254
+ check=False,
255
+ )
256
+ if res.returncode == 0 and res.stdout.strip():
257
+ return Path(res.stdout.strip()).resolve()
258
+ return p
259
+
260
+
261
+ def list_repo_files(repo_root: Path) -> list[str]:
262
+ res = subprocess.run(
263
+ ["git", "-C", str(repo_root), "ls-files", "-z"],
264
+ capture_output=True,
265
+ check=False,
266
+ )
267
+ if res.returncode == 0:
268
+ raw = res.stdout.decode("utf-8", errors="replace")
269
+ return sorted(p for p in raw.split("\0") if p)
270
+
271
+ files: list[str] = []
272
+ for root, dirs, names in os.walk(repo_root):
273
+ dirs[:] = [d for d in dirs if d != ".git"]
274
+ rel_root = Path(root).relative_to(repo_root)
275
+ for name in names:
276
+ files.append((rel_root / name).as_posix())
277
+ return sorted(files)
278
+
279
+
280
+ def run_ocr_delegate_rule(
281
+ repo_root: Path, rule_path: Path, custom_rule_arg: str | None, paths: list[str]
282
+ ) -> tuple[dict[str, dict[str, str]], str | None]:
283
+ """Query `ocr delegate rule --format json` in chunks to cross-check rule matching."""
284
+ ocr_bin = shutil.which("ocr")
285
+ if not ocr_bin or not paths:
286
+ return {}, None
287
+
288
+ resolved: dict[str, dict[str, str]] = {}
289
+ chunk_size = 150
290
+ for i in range(0, len(paths), chunk_size):
291
+ chunk = paths[i : i + chunk_size]
292
+ cmd = [ocr_bin, "delegate", "rule", "--repo", str(repo_root), "--format", "json"]
293
+ if custom_rule_arg:
294
+ cmd.extend(["--rule", str(rule_path)])
295
+ cmd.extend(chunk)
296
+ res = subprocess.run(cmd, capture_output=True, text=True, check=False)
297
+ if res.returncode != 0:
298
+ return resolved, res.stderr.strip() or res.stdout.strip() or f"exit {res.returncode}"
299
+ try:
300
+ payload = json.loads(res.stdout)
301
+ except json.JSONDecodeError as e:
302
+ return resolved, f"invalid JSON from ocr delegate rule: {e}"
303
+ for g in payload.get("groups", []):
304
+ src = g.get("source", "")
305
+ pat = g.get("pattern", "")
306
+ for fp in g.get("files", []):
307
+ resolved[fp] = {"source": src, "pattern": pat}
308
+ return resolved, None
309
+
310
+
311
+ def extract_explicit_exts(pattern: str) -> set[str]:
312
+ expanded, _ = expand_braces(pattern.lower())
313
+ exts: set[str] = set()
314
+ for p in expanded:
315
+ base = posixpath.basename(p)
316
+ if "." in base and "*" not in base.rsplit(".", 1)[-1] and "?" not in base.rsplit(".", 1)[-1]:
317
+ exts.add("." + base.rsplit(".", 1)[-1])
318
+ return exts
319
+
320
+
321
+ def verify(
322
+ repo_root: Path,
323
+ rule_path: Path,
324
+ custom_rule_arg: str | None,
325
+ use_ocr: bool,
326
+ preview_refs: tuple[str | None, str | None, str | None],
327
+ ) -> dict[str, Any]:
328
+ findings: list[Finding] = []
329
+ allowlists = load_allowlists()
330
+ supported_exts = set(allowlists["supported_file_types"])
331
+ default_excludes = list(allowlists["default_exclude_patterns"])
332
+ secret_patterns = list(allowlists["default_secret_patterns"])
333
+
334
+ if not rule_path.exists():
335
+ findings.append(
336
+ Finding("error", "missing_rule_json", f"Rule file does not exist: {rule_path}")
337
+ )
338
+ return {"repo_root": str(repo_root), "rule_path": str(rule_path), "findings": [asdict(f) for f in findings]}
339
+
340
+ try:
341
+ data = json.loads(rule_path.read_text(encoding="utf-8"))
342
+ except (OSError, json.JSONDecodeError) as e:
343
+ findings.append(Finding("error", "invalid_json", f"Failed to parse {rule_path}: {e}"))
344
+ return {"repo_root": str(repo_root), "rule_path": str(rule_path), "findings": [asdict(f) for f in findings]}
345
+
346
+ if not isinstance(data, dict):
347
+ findings.append(Finding("error", "invalid_schema", "Top-level JSON value must be an object."))
348
+ return {"repo_root": str(repo_root), "rule_path": str(rule_path), "findings": [asdict(f) for f in findings]}
349
+
350
+ unknown_top = set(data.keys()) - ALLOWED_TOP_KEYS
351
+ if unknown_top:
352
+ findings.append(
353
+ Finding("warning", "unknown_top_keys", f"Ignored unknown top-level keys: {sorted(unknown_top)}")
354
+ )
355
+
356
+ user_include = data.get("include") or []
357
+ user_exclude = data.get("exclude") or []
358
+ rules = data.get("rules")
359
+
360
+ for key, arr in (("include", data.get("include")), ("exclude", data.get("exclude"))):
361
+ if arr is not None:
362
+ if not isinstance(arr, list) or not all(isinstance(x, str) and x.strip() for x in arr):
363
+ findings.append(
364
+ Finding("error", f"invalid_{key}", f"'{key}' must be an array of non-empty strings.")
365
+ )
366
+
367
+ if not isinstance(rules, list):
368
+ findings.append(Finding("error", "invalid_rules", "'rules' must be an array."))
369
+ return {"repo_root": str(repo_root), "rule_path": str(rule_path), "findings": [asdict(f) for f in findings]}
370
+
371
+ # Lint include/exclude brace syntax and conflicts.
372
+ if isinstance(user_exclude, list) and isinstance(user_include, list):
373
+ for pat in user_exclude + user_include:
374
+ if isinstance(pat, str):
375
+ _, brace_warns = expand_braces(pat)
376
+ for w in brace_warns:
377
+ findings.append(Finding("warning", "glob_brace_syntax", w, pattern=pat))
378
+ for inc in user_include:
379
+ if not isinstance(inc, str):
380
+ continue
381
+ inc_expanded, _ = expand_braces(inc)
382
+ for branch in inc_expanded:
383
+ samples = sample_paths_for_single_pattern(branch)
384
+ if samples and all(any(doublestar_match(exc, s) for exc in user_exclude) for s in samples):
385
+ findings.append(
386
+ Finding(
387
+ "warning",
388
+ "include_killed_by_exclude",
389
+ f"include pattern {inc!r} is overridden by 'exclude' (user_exclude runs before user_include).",
390
+ pattern=inc,
391
+ )
392
+ )
393
+ break
394
+
395
+ # Validate each rules[] entry.
396
+ valid_entries: list[tuple[int, dict[str, Any]]] = []
397
+ for idx, entry in enumerate(rules):
398
+ if not isinstance(entry, dict):
399
+ findings.append(Finding("error", "invalid_rule_entry", f"rules[{idx}] must be an object.", rule_index=idx))
400
+ continue
401
+ unknown_keys = set(entry.keys()) - ALLOWED_RULE_KEYS
402
+ if unknown_keys:
403
+ findings.append(
404
+ Finding(
405
+ "warning",
406
+ "unknown_rule_keys",
407
+ f"rules[{idx}] has ignored keys: {sorted(unknown_keys)}",
408
+ rule_index=idx,
409
+ pattern=entry.get("path") if isinstance(entry.get("path"), str) else None,
410
+ )
411
+ )
412
+ path_pat = entry.get("path")
413
+ rule_text = entry.get("rule")
414
+ merge_sys = entry.get("merge_system_rule", False)
415
+
416
+ if not isinstance(path_pat, str) or not path_pat.strip():
417
+ findings.append(Finding("error", "missing_path", f"rules[{idx}].path must be a non-empty string.", rule_index=idx))
418
+ continue
419
+ if not isinstance(rule_text, str):
420
+ findings.append(
421
+ Finding(
422
+ "error",
423
+ "invalid_rule_type",
424
+ f"rules[{idx}].rule must be a string (got {type(rule_text).__name__}).",
425
+ rule_index=idx,
426
+ pattern=path_pat,
427
+ )
428
+ )
429
+ continue
430
+ if "merge_system_rule" in entry and not isinstance(entry["merge_system_rule"], bool):
431
+ findings.append(
432
+ Finding(
433
+ "error",
434
+ "invalid_merge_system_rule",
435
+ f"rules[{idx}].merge_system_rule must be a JSON boolean, not {type(entry['merge_system_rule']).__name__} "
436
+ "(non-boolean types can break OCR loading).",
437
+ rule_index=idx,
438
+ pattern=path_pat,
439
+ )
440
+ )
441
+ continue
442
+
443
+ if rule_text == "" and not merge_sys:
444
+ findings.append(
445
+ Finding(
446
+ "warning",
447
+ "empty_rule_skipped",
448
+ f"rules[{idx}] ({path_pat!r}) has empty 'rule' and merge_system_rule=false; OCR skips this entry.",
449
+ rule_index=idx,
450
+ pattern=path_pat,
451
+ )
452
+ )
453
+ continue
454
+
455
+ _, brace_warns = expand_braces(path_pat)
456
+ for w in brace_warns:
457
+ findings.append(Finding("warning", "glob_brace_syntax", f"rules[{idx}]: {w}", rule_index=idx, pattern=path_pat))
458
+
459
+ # External rule file validation.
460
+ if rule_text.strip() and looks_like_rule_file_path(rule_text):
461
+ base_dir = rule_path.parent if custom_rule_arg else repo_root
462
+ target = (base_dir / rule_text).resolve() if not os.path.isabs(rule_text) else Path(rule_text).resolve()
463
+ if not custom_rule_arg:
464
+ try:
465
+ target.relative_to(repo_root)
466
+ except ValueError:
467
+ findings.append(
468
+ Finding(
469
+ "error",
470
+ "rule_file_escapes_repo",
471
+ f"rules[{idx}] references {rule_text!r}, which resolves outside repo root {repo_root}.",
472
+ rule_index=idx,
473
+ pattern=path_pat,
474
+ )
475
+ )
476
+ if not target.exists():
477
+ findings.append(
478
+ Finding(
479
+ "error",
480
+ "missing_rule_file",
481
+ f"rules[{idx}] references missing rule file {rule_text!r} ({target}).",
482
+ rule_index=idx,
483
+ pattern=path_pat,
484
+ )
485
+ )
486
+ elif target.stat().st_size > MAX_RULE_FILE_BYTES:
487
+ findings.append(
488
+ Finding(
489
+ "error",
490
+ "rule_file_too_large",
491
+ f"rules[{idx}] file {rule_text!r} exceeds OCR's 512 KiB cap.",
492
+ rule_index=idx,
493
+ pattern=path_pat,
494
+ )
495
+ )
496
+
497
+ valid_entries.append((idx, entry))
498
+
499
+ # First-match-wins reachability & subsumption check.
500
+ for pos, (idx, entry) in enumerate(valid_entries):
501
+ pat = entry["path"]
502
+ expanded_b, _ = expand_braces(pat.lower())
503
+ shadowed_branches = 0
504
+ shadowed_by: list[tuple[int, str]] = []
505
+ for branch in expanded_b:
506
+ samples = sample_paths_for_single_pattern(branch)
507
+ matched_earlier = None
508
+ for prev_idx, prev_entry in valid_entries[:pos]:
509
+ prev_pat = prev_entry["path"]
510
+ if samples and all(doublestar_match(prev_pat, s) for s in samples):
511
+ matched_earlier = (prev_idx, prev_pat)
512
+ break
513
+ if matched_earlier is not None:
514
+ shadowed_branches += 1
515
+ shadowed_by.append(matched_earlier)
516
+
517
+ if expanded_b and shadowed_branches == len(expanded_b):
518
+ first_blocker = shadowed_by[0]
519
+ findings.append(
520
+ Finding(
521
+ "error",
522
+ "unreachable_rule",
523
+ f"rules[{idx}] ({pat!r}) is completely unreachable: earlier rule rules[{first_blocker[0]}] "
524
+ f"({first_blocker[1]!r}) matches first (OCR uses first-match-wins).",
525
+ rule_index=idx,
526
+ pattern=pat,
527
+ )
528
+ )
529
+ elif shadowed_branches > 0:
530
+ first_blocker = shadowed_by[0]
531
+ findings.append(
532
+ Finding(
533
+ "warning",
534
+ "partially_shadowed_rule",
535
+ f"rules[{idx}] ({pat!r}) has {shadowed_branches}/{len(expanded_b)} brace branch(es) shadowed by "
536
+ f"rules[{first_blocker[0]}] ({first_blocker[1]!r}).",
537
+ rule_index=idx,
538
+ pattern=pat,
539
+ )
540
+ )
541
+
542
+ # Flag catch-all sitting after specific rules (info if trailing fallback, warning if non-trailing).
543
+ if pat.strip() in {"**/*", "**"} and pos > 0:
544
+ level = "info" if pos == len(valid_entries) - 1 else "warning"
545
+ findings.append(
546
+ Finding(
547
+ level,
548
+ "catchall_does_not_stack",
549
+ f"rules[{idx}] ({pat!r}) is a catch-all after {pos} earlier rule(s). Files matched by rules[0..{pos-1}] "
550
+ "never receive this entry (merge_system_rule only merges with OCR's built-in system rule).",
551
+ rule_index=idx,
552
+ pattern=pat,
553
+ )
554
+ )
555
+
556
+ # Extension allowlist alignment.
557
+ explicit_exts = extract_explicit_exts(pat)
558
+ if explicit_exts:
559
+ unsupported = sorted(e for e in explicit_exts if e not in supported_exts)
560
+ if unsupported:
561
+ # Check if user_include covers this pattern.
562
+ samples = [s for br in expanded_b for s in sample_paths_for_single_pattern(br)]
563
+ covered_by_include = bool(
564
+ user_include and samples and any(any(doublestar_match(inc, s) for inc in user_include) for s in samples)
565
+ )
566
+ if not covered_by_include:
567
+ findings.append(
568
+ Finding(
569
+ "warning",
570
+ "unsupported_ext_without_include",
571
+ f"rules[{idx}] ({pat!r}) targets extension(s) {unsupported} not in OCR's supported_file_types, "
572
+ "and no 'include' pattern admits them — ocr review will skip those files.",
573
+ rule_index=idx,
574
+ pattern=pat,
575
+ )
576
+ )
577
+
578
+ # Prose check for tests/docs/fixtures claims when no include is defined.
579
+ if not user_include and isinstance(entry.get("rule"), str):
580
+ low_rule = entry["rule"].lower()
581
+ claims = []
582
+ if re.search(r"\bincluding in tests\b|\bin tests\b|\btest files\b", low_rule) and "except in" not in low_rule:
583
+ claims.append("tests")
584
+ if re.search(r"\bfixtures\b", low_rule):
585
+ claims.append("fixtures")
586
+ if re.search(r"\band docs\b|\bkeep agents\.md\b|\breadme\b", low_rule):
587
+ claims.append("docs/Markdown")
588
+ if claims:
589
+ findings.append(
590
+ Finding(
591
+ "warning",
592
+ "prose_targets_excluded_scope",
593
+ f"rules[{idx}] ({pat!r}) mentions {', '.join(claims)}, but rule.json has no 'include' entries "
594
+ "to bypass OCR's unsupported_ext (.md) and default_path (tests/fixtures) exclusions.",
595
+ rule_index=idx,
596
+ pattern=pat,
597
+ )
598
+ )
599
+
600
+ # Scan repository files and measure real coverage.
601
+ repo_files = list_repo_files(repo_root)
602
+ coverages: list[RuleCoverage] = [
603
+ RuleCoverage(
604
+ index=idx,
605
+ pattern=entry["path"],
606
+ merge_system_rule=bool(entry.get("merge_system_rule", False)),
607
+ )
608
+ for idx, entry in valid_entries
609
+ ]
610
+ cov_by_idx = {c.index: c for c in coverages}
611
+
612
+ unmatched_eligible: list[str] = []
613
+ for fp in repo_files:
614
+ sel = classify_file_selection(
615
+ fp,
616
+ user_include if isinstance(user_include, list) else [],
617
+ user_exclude if isinstance(user_exclude, list) else [],
618
+ supported_exts,
619
+ default_excludes,
620
+ secret_patterns,
621
+ )
622
+ matched_idx = None
623
+ for idx, entry in valid_entries:
624
+ if doublestar_match(entry["path"], fp):
625
+ matched_idx = idx
626
+ break
627
+ if matched_idx is not None:
628
+ c = cov_by_idx[matched_idx]
629
+ c.total_repo_matches += 1
630
+ if sel == "selected":
631
+ c.eligible_repo_matches += 1
632
+ if len(c.sample_eligible) < 3:
633
+ c.sample_eligible.append(fp)
634
+ else:
635
+ c.excluded_repo_matches += 1
636
+ if len(c.sample_excluded) < 3:
637
+ c.sample_excluded.append((fp, sel))
638
+ elif sel == "selected":
639
+ unmatched_eligible.append(fp)
640
+
641
+ for c in coverages:
642
+ if c.total_repo_matches == 0:
643
+ findings.append(
644
+ Finding(
645
+ "warning",
646
+ "zero_repo_matches",
647
+ f"rules[{c.index}] ({c.pattern!r}) matches 0 files in the repository.",
648
+ rule_index=c.index,
649
+ pattern=c.pattern,
650
+ )
651
+ )
652
+ elif c.eligible_repo_matches == 0:
653
+ reasons = sorted({r for _, r in c.sample_excluded})
654
+ findings.append(
655
+ Finding(
656
+ "warning",
657
+ "zero_eligible_matches",
658
+ f"rules[{c.index}] ({c.pattern!r}) matched {c.total_repo_matches} file(s), but 0 are review-eligible "
659
+ f"(excluded by {reasons}).",
660
+ rule_index=c.index,
661
+ pattern=c.pattern,
662
+ )
663
+ )
664
+
665
+ # Check if user exclude includes **/build/** and source files live under build/.
666
+ if isinstance(user_exclude, list) and any(p.lower() in {"**/build/**", "build/**"} for p in user_exclude):
667
+ build_hits = [fp for fp in repo_files if "/build/" in f"/{fp.lower()}"]
668
+ if build_hits:
669
+ findings.append(
670
+ Finding(
671
+ "info",
672
+ "build_dir_excluded",
673
+ f"rule.json excludes '**/build/**', suppressing {len(build_hits)} tracked file(s) under build/ "
674
+ f"(sample: {build_hits[:3]}).",
675
+ )
676
+ )
677
+
678
+ # Check global ~/.opencodereview/rule.json presence.
679
+ global_rule = Path.home() / ".opencodereview" / "rule.json"
680
+ if global_rule.exists():
681
+ findings.append(
682
+ Finding(
683
+ "info",
684
+ "global_rule_present",
685
+ f"Global {global_rule} exists; project rules take priority, and FileFilter uses the highest-priority "
686
+ "layer with non-empty include/exclude.",
687
+ )
688
+ )
689
+
690
+ # Live `ocr` CLI verification.
691
+ ocr_cli_status: dict[str, Any] = {"ran": False}
692
+ if use_ocr:
693
+ ocr_bin = shutil.which("ocr")
694
+ if not ocr_bin:
695
+ findings.append(Finding("warning", "ocr_not_installed", "`ocr` CLI not found on PATH; skipped live CLI cross-check."))
696
+ else:
697
+ # Verify against real repo files (bounded sample if very large, plus one synthetic probe per rule).
698
+ probe_files: list[str] = []
699
+ seen_probes: set[str] = set()
700
+ for fp in repo_files:
701
+ if fp not in seen_probes:
702
+ seen_probes.add(fp)
703
+ probe_files.append(fp)
704
+
705
+ resolved_map, cli_err = run_ocr_delegate_rule(repo_root, rule_path, custom_rule_arg, probe_files)
706
+ ocr_cli_status = {"ran": True, "checked_files": len(probe_files), "error": cli_err}
707
+ if cli_err:
708
+ findings.append(Finding("error", "ocr_cli_error", f"`ocr delegate rule` failed: {cli_err}"))
709
+ else:
710
+ cli_counts: dict[str, int] = {}
711
+ mismatches = 0
712
+ for fp, info in resolved_map.items():
713
+ pat = info.get("pattern", "")
714
+ cli_counts[pat] = cli_counts.get(pat, 0) + 1
715
+ # Compare against static first-match.
716
+ expected_pat = None
717
+ for _, entry in valid_entries:
718
+ if doublestar_match(entry["path"], fp):
719
+ expected_pat = entry["path"]
720
+ break
721
+ if expected_pat is not None and pat != expected_pat:
722
+ mismatches += 1
723
+ if mismatches <= 5:
724
+ findings.append(
725
+ Finding(
726
+ "warning",
727
+ "static_vs_ocr_mismatch",
728
+ f"For {fp!r}, static matcher predicted {expected_pat!r} but `ocr` resolved "
729
+ f"{pat!r} (source={info.get('source')}).",
730
+ pattern=pat,
731
+ )
732
+ )
733
+ seen_cli_patterns: set[str] = set()
734
+ for c in coverages:
735
+ if c.pattern in seen_cli_patterns:
736
+ c.ocr_cli_matches = 0
737
+ else:
738
+ seen_cli_patterns.add(c.pattern)
739
+ c.ocr_cli_matches = cli_counts.get(c.pattern, 0)
740
+
741
+ # Optional `ocr review --preview` if refs or workspace changes exist.
742
+ p_commit, p_from, p_to = preview_refs
743
+ if p_commit or p_from:
744
+ cmd = [ocr_bin, "review", "--repo", str(repo_root), "--preview"]
745
+ if custom_rule_arg:
746
+ cmd.extend(["--rule", str(rule_path)])
747
+ if p_commit:
748
+ cmd.extend(["--commit", p_commit])
749
+ else:
750
+ cmd.extend(["--from", p_from, "--to", p_to or "HEAD"])
751
+ prev = subprocess.run(cmd, capture_output=True, text=True, check=False)
752
+ ocr_cli_status["preview_exit"] = prev.returncode
753
+ ocr_cli_status["preview_summary"] = "\n".join(prev.stdout.splitlines()[:20])
754
+
755
+ return {
756
+ "repo_root": str(repo_root),
757
+ "rule_path": str(rule_path),
758
+ "repo_files_total": len(repo_files),
759
+ "unmatched_eligible_count": len(unmatched_eligible),
760
+ "ocr_cli": ocr_cli_status,
761
+ "rules": [asdict(c) for c in coverages],
762
+ "findings": [asdict(f) for f in findings],
763
+ }
764
+
765
+
766
+ def print_text_report(report: dict[str, Any]) -> None:
767
+ print(f"Repo root : {report['repo_root']}")
768
+ print(f"Rule file : {report['rule_path']}")
769
+ print(f"Repo files: {report.get('repo_files_total', 0)} (unmatched review-eligible: {report.get('unmatched_eligible_count', 0)})")
770
+ cli = report.get("ocr_cli", {})
771
+ if cli.get("ran"):
772
+ print(f"Live ocr : checked {cli.get('checked_files', 0)} file(s)" + (f" [ERROR: {cli['error']}]" if cli.get("error") else " [OK]"))
773
+ else:
774
+ print("Live ocr : skipped")
775
+
776
+ rules = report.get("rules", [])
777
+ if rules:
778
+ print("\nRule coverage (in declaration order, first-match-wins):")
779
+ for r in rules:
780
+ cli_col = f" ocr={r['ocr_cli_matches']}" if r["ocr_cli_matches"] is not None else ""
781
+ print(
782
+ f" [{r['index']:>2}] merge={str(r['merge_system_rule']):5s} "
783
+ f"eligible={r['eligible_repo_matches']:>4} total={r['total_repo_matches']:>4}{cli_col} "
784
+ f"pattern={r['pattern']}"
785
+ )
786
+
787
+ findings = report.get("findings", [])
788
+ print(f"\nFindings ({len(findings)}):")
789
+ if not findings:
790
+ print(" None — all checks passed.")
791
+ for f in findings:
792
+ print(f" [{f['level'].upper():7s}] {f['code']}: {f['message']}")
793
+
794
+ if cli.get("preview_summary"):
795
+ print("\nocr review --preview:")
796
+ print(cli["preview_summary"])
797
+
798
+
799
+ def main() -> int:
800
+ parser = argparse.ArgumentParser(description="Verify .opencodereview/rule.json against ocr semantics.")
801
+ parser.add_argument("--repo", default=".", help="Repository or worktree path (default: cwd)")
802
+ parser.add_argument("--rule", default=None, help="Custom rule.json path (overrides <repo>/.opencodereview/rule.json)")
803
+ parser.add_argument("--no-ocr", action="store_true", help="Skip live `ocr` CLI cross-check")
804
+ parser.add_argument("--commit", default=None, help="Optional commit for `ocr review --preview`")
805
+ parser.add_argument("--from", dest="from_ref", default=None, help="Optional base ref for `ocr review --preview`")
806
+ parser.add_argument("--to", dest="to_ref", default=None, help="Optional head ref for `ocr review --preview`")
807
+ parser.add_argument("--json", action="store_true", help="Emit JSON report")
808
+ parser.add_argument("--strict", action="store_true", help="Exit 1 on warnings as well as errors")
809
+ args = parser.parse_args()
810
+
811
+ repo_root = resolve_repo_root(args.repo)
812
+ rule_path = Path(args.rule).resolve() if args.rule else (repo_root / ".opencodereview" / "rule.json")
813
+
814
+ report = verify(
815
+ repo_root=repo_root,
816
+ rule_path=rule_path,
817
+ custom_rule_arg=args.rule,
818
+ use_ocr=not args.no_ocr,
819
+ preview_refs=(args.commit, args.from_ref, args.to_ref),
820
+ )
821
+
822
+ if args.json:
823
+ print(json.dumps(report, indent=2))
824
+ else:
825
+ print_text_report(report)
826
+
827
+ levels = {f["level"] for f in report["findings"]}
828
+ if "error" in levels:
829
+ return 1
830
+ if args.strict and "warning" in levels:
831
+ return 1
832
+ return 0
833
+
834
+
835
+ if __name__ == "__main__":
836
+ sys.exit(main())