slopthreshold 2.1.0.dev22__py3-none-any.whl

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 (44) hide show
  1. slopthreshold/__init__.py +1 -0
  2. slopthreshold/guide/STYLE_GUIDE.md +495 -0
  3. slopthreshold/packs/editorconfig-pack/.editorconfig +899 -0
  4. slopthreshold/packs/editorconfig-pack/Directory.Build.props +47 -0
  5. slopthreshold/packs/editorconfig-pack/Directory.Build.targets +16 -0
  6. slopthreshold/packs/editorconfig-pack/Directory.Packages.props +29 -0
  7. slopthreshold/packs/editorconfig-pack/README.md +141 -0
  8. slopthreshold/packs/editorconfig-pack/global.json +7 -0
  9. slopthreshold/packs/editorconfig-pack/nuget.config +19 -0
  10. slopthreshold/packs/editorconfig-pack/ruff.toml +29 -0
  11. slopthreshold/packs/editorconfig-pack/sonar-drift-allowlist.json +10 -0
  12. slopthreshold/packs/frontend-lint-pack/.prettierrc.json +7 -0
  13. slopthreshold/packs/frontend-lint-pack/.stylelintrc.json +64 -0
  14. slopthreshold/packs/frontend-lint-pack/README.md +64 -0
  15. slopthreshold/packs/frontend-lint-pack/eslint.config.mjs +108 -0
  16. slopthreshold/packs/frontend-lint-pack/package.json +23 -0
  17. slopthreshold/packs/frontend-lint-pack/tsconfig.app.json +17 -0
  18. slopthreshold/packs/frontend-lint-pack/tsconfig.base.json +20 -0
  19. slopthreshold/packs/frontend-lint-pack/tsconfig.json +4 -0
  20. slopthreshold/packs/frontend-lint-pack/tsconfig.spec.json +8 -0
  21. slopthreshold/packs/project-guide-starters/app-STYLE_GUIDE.md +35 -0
  22. slopthreshold/packs/project-guide-starters/frontend-STYLE_GUIDE.md +33 -0
  23. slopthreshold/packs/project-guide-starters/library-STYLE_GUIDE.md +36 -0
  24. slopthreshold/packs/three-layer-wiring/.githooks/commit-msg +13 -0
  25. slopthreshold/packs/three-layer-wiring/.githooks/post-merge +8 -0
  26. slopthreshold/packs/three-layer-wiring/.githooks/pre-commit +10 -0
  27. slopthreshold/packs/three-layer-wiring/.githooks/pre-push +14 -0
  28. slopthreshold/packs/three-layer-wiring/.github/actionlint.yaml +3 -0
  29. slopthreshold/packs/three-layer-wiring/.github/workflows/quality.yml +164 -0
  30. slopthreshold/packs/three-layer-wiring/.gitleaks.toml +16 -0
  31. slopthreshold/packs/three-layer-wiring/.hadolint.yaml +6 -0
  32. slopthreshold/packs/three-layer-wiring/README.md +62 -0
  33. slopthreshold/packs/three-layer-wiring/budget.json +14 -0
  34. slopthreshold/tools/check_characters.py +104 -0
  35. slopthreshold/tools/check_ci_config.py +405 -0
  36. slopthreshold/tools/check_package_health.py +554 -0
  37. slopthreshold/tools/check_sonar_drift.py +1123 -0
  38. slopthreshold/tools/mine_sonar_metrics.py +1259 -0
  39. slopthreshold/tools/validate_guide_tags.py +795 -0
  40. slopthreshold/zh.py +973 -0
  41. slopthreshold-2.1.0.dev22.dist-info/METADATA +49 -0
  42. slopthreshold-2.1.0.dev22.dist-info/RECORD +44 -0
  43. slopthreshold-2.1.0.dev22.dist-info/WHEEL +4 -0
  44. slopthreshold-2.1.0.dev22.dist-info/entry_points.txt +2 -0
@@ -0,0 +1,795 @@
1
+ #!/usr/bin/env python3
2
+ """Validate OVERRIDE / BYPASS / BYPASS-LIB tags in a project style guide
3
+ against the Generalized Style Guide.
4
+
5
+ Rules enforced (guide section "Rule tiers and bypass tags"):
6
+ - OVERRIDE targets a DEFAULT rule and carries replacement + reason.
7
+ - BYPASS targets a REQUIRED rule and carries reason, approver and an
8
+ unexpired review date at most 12 months out.
9
+ - BYPASS-LIB names a package from the guide's package map and carries a
10
+ reason plus the alternative that replaces it.
11
+ - Tags inside fenced code blocks or HTML comments are examples, ignored.
12
+ - Tags belong under "## Generalized guide overrides"; elsewhere warns.
13
+ - A valid bypass of a security rule (ST-SEC/ST-FE-SEC) is reported as
14
+ INFO so it stays visible in reviews.
15
+
16
+ Validator v2 adds:
17
+ - (a) Adoption line: the project guide must state it adopts the
18
+ Generalized Style Guide with a version (for example "adopts the
19
+ Generalized Style Guide v1.1"). Missing adoption line (or adoption
20
+ without a version) is an ERROR. A version differing from the
21
+ generalized guide's version is a WARN (stale adoption). If the
22
+ generalized version cannot be parsed, the comparison is skipped
23
+ with an INFO.
24
+ - (b) BYPASS-LIB targeting a Planned or Held package is a WARN:
25
+ build behind an interface instead (ST-LIB-02/ST-LIB-03). Statuses
26
+ come from the generalized guide's package-map tables.
27
+ - (c) Scope globs: with --repo-root, each tag's [scope: glob] must
28
+ match at least one real file under the repo root, else WARN.
29
+ Globs are repo-relative; * stays within one path segment, **
30
+ crosses segments, and a wildcard-free scope names a file or a
31
+ directory prefix.
32
+ - (d) ST-DEP-03 decision lines: any line matching "decision:"
33
+ (case-insensitive, outside fenced code and HTML comments) must
34
+ carry "review: YYYY-MM-DD" within 6 months from today, else ERROR.
35
+
36
+ Exit code 1 when any ERROR is found (warnings fail too under --strict).
37
+ Exit code 2 on usage problems (guide not found, bad --repo-root).
38
+ """
39
+ import argparse
40
+ import datetime
41
+ from dataclasses import dataclass
42
+ import json
43
+ import pathlib
44
+ import re
45
+ import sys
46
+
47
+ RULE_RE = re.compile(r"\*\*((?:ST|SG)-[A-Z0-9-]+-\d+) \[(REQUIRED|DEFAULT)\]\*\*")
48
+ LEGACY_PREFIX = "SG-"
49
+ CANONICAL_PREFIX = "ST-"
50
+
51
+
52
+ def canonical_rule_id(rule_id):
53
+ """Guide v2.0 renamed the SG- prefix to ST- (SlopThreshold); numbers are
54
+ unchanged. Legacy SG- IDs normalize to their ST- form so project guides
55
+ written against v1.x keep validating during the migration."""
56
+ if rule_id.startswith(LEGACY_PREFIX):
57
+ return CANONICAL_PREFIX + rule_id[len(LEGACY_PREFIX):]
58
+ return rule_id
59
+ # Package names are extracted by splitting on backticks and validating each
60
+ # span with plain string checks: linear by construction, no regex for Sonar
61
+ # S8786 (super-linear backtracking) to flag.
62
+ _PKG_DOTNET_PREFIX = "ZhEaIsNsAaBn."
63
+ _PKG_NPM_PREFIX = "@zheaisnsaabn/"
64
+
65
+
66
+ def _is_package_span(span):
67
+ if span.startswith(_PKG_DOTNET_PREFIX):
68
+ rest = span[len(_PKG_DOTNET_PREFIX):]
69
+ return bool(rest) and all(part.isalnum() for part in rest.split("."))
70
+ if span.startswith(_PKG_NPM_PREFIX):
71
+ rest = span[len(_PKG_NPM_PREFIX):]
72
+ return bool(rest) and all(ch.islower() or ch.isdigit() or ch == "-" for ch in rest)
73
+ return False
74
+
75
+
76
+ def find_packages(text):
77
+ """Backtick-quoted house package names in text, in order of appearance."""
78
+ spans = text.split("`")[1::2]
79
+ return [span for span in spans if _is_package_span(span)]
80
+ TAG_RE = re.compile(r"^\s*[-*]\s+(OVERRIDE|BYPASS-LIB|BYPASS)\s+(\S+):\s*(.*)$")
81
+ # Linear forms: the capture's first character excludes whitespace, so it
82
+ # cannot compete with the leading \s* for the same characters (the old
83
+ # \s*([^\]]*) / \s*([^,]+) shapes backtrack quadratically on failing
84
+ # input). Captures are unchanged: group 1 still holds the scope text
85
+ # (empty for "[scope:]" / "[scope: ]") and the approver text.
86
+ SCOPE_RE = re.compile(r"\[scope:\s*([^\s\]][^\]]*|)\]\s*$")
87
+ APPROVED_RE = re.compile(r"approved:\s*([^\s,][^,]*|\s)", re.IGNORECASE)
88
+ REVIEW_RE = re.compile(r"review:\s*(\d{4}-\d{2}-\d{2})", re.IGNORECASE)
89
+ SECURITY_PREFIXES = ("ST-SEC-", "ST-FE-SEC-")
90
+
91
+ # v2 patterns
92
+ GEN_VERSION_RE = re.compile(r"\*\*Version:\*\*\s*v?(\d+(?:\.\d+)+)", re.IGNORECASE)
93
+ GEN_TITLE_VERSION_RE = re.compile(r"Generalized Style Guide\s+v(\d+(?:\.\d+)+)", re.IGNORECASE)
94
+ ADOPTION_RE = re.compile(
95
+ r"adopts\s+the\s+Generalized\s+Style\s+Guide\s+v(\d+(?:\.\d+)+)", re.IGNORECASE)
96
+ ADOPTION_NO_VERSION_RE = re.compile(
97
+ r"adopts\s+the\s+Generalized\s+Style\s+Guide\b", re.IGNORECASE)
98
+ STATUS_RE = re.compile(r"^(Available|Planned|Held)\b")
99
+ DECISION_RE = re.compile(r"\bdecision\s*:", re.IGNORECASE)
100
+ STATUS_SEVERITY = {"Available": 0, "Planned": 1, "Held": 2}
101
+
102
+ DEFAULT_GENERALIZED_CANDIDATES = [
103
+ "docs/GENERALIZED_STYLE_GUIDE.md",
104
+ "GENERALIZED_STYLE_GUIDE.md",
105
+ "tools/STYLE_GUIDE.generalized.md",
106
+ "docs/style-guide.md",
107
+ "~/workspace/stack-code-review-install/generalized-style-guide/STYLE_GUIDE.md",
108
+ ]
109
+
110
+ # Sentinel for validate(): callers that predate v2 and pass no
111
+ # generalized_version keep the old behaviour (no adoption check).
112
+ # The CLI always passes a version string, or None when the
113
+ # generalized version could not be parsed.
114
+ _UNSET = object()
115
+
116
+
117
+ def parse_generalized(text):
118
+ rules = {canonical_rule_id(m.group(1)): m.group(2) for m in RULE_RE.finditer(text)}
119
+ packages = set(find_packages(text))
120
+ return rules, packages
121
+
122
+
123
+ def parse_generalized_version(text):
124
+ """Return the generalized guide version (for example '1.1') or None."""
125
+ m = GEN_VERSION_RE.search(text)
126
+ if m:
127
+ return m.group(1)
128
+ m = GEN_TITLE_VERSION_RE.search(text)
129
+ if m:
130
+ return m.group(1)
131
+ return None
132
+
133
+
134
+ def _row_status(line):
135
+ """Status named by a table row's last non-empty cell, or None."""
136
+ cells = [c.strip() for c in line.split("|")]
137
+ for cell in reversed(cells):
138
+ if not cell:
139
+ continue
140
+ m = STATUS_RE.match(cell)
141
+ if m:
142
+ return m.group(1)
143
+ return None
144
+ return None
145
+
146
+
147
+ def _merge_status(statuses, pkg, status):
148
+ """Keep the most restrictive status seen for one package."""
149
+ current = statuses.get(pkg)
150
+ if current is None or STATUS_SEVERITY[status] > STATUS_SEVERITY[current]:
151
+ statuses[pkg] = status
152
+
153
+
154
+ def _apply_status_row(statuses, line):
155
+ """Fold one table row's status into the package-status map."""
156
+ if "|" not in line:
157
+ return
158
+ pkgs = find_packages(line)
159
+ if not pkgs:
160
+ return
161
+ status = _row_status(line)
162
+ if status is None:
163
+ return
164
+ for pkg in pkgs:
165
+ _merge_status(statuses, pkg, status)
166
+
167
+
168
+ def parse_package_statuses(text):
169
+ """Map package ID -> Available/Planned/Held from package-map tables.
170
+
171
+ A table row contributes its status (the last cell, starting with
172
+ Available, Planned or Held) to every backticked package ID in the
173
+ row. When a package appears with several statuses, the most
174
+ restrictive one wins (Held over Planned over Available).
175
+ """
176
+ statuses = {}
177
+ for line in text.splitlines():
178
+ _apply_status_row(statuses, line)
179
+ return statuses
180
+
181
+
182
+ def _consume_in_comment(rest):
183
+ """Consume text up to a comment end; return (rest, in_comment, kept)."""
184
+ end = rest.find("-->")
185
+ if end == -1:
186
+ return "", True, ""
187
+ return rest[end + 3:], False, ""
188
+
189
+
190
+ def _consume_outside_comment(rest):
191
+ """Consume text up to a comment start; return (rest, in_comment, kept)."""
192
+ start = rest.find("<!--")
193
+ if start == -1:
194
+ return "", False, rest
195
+ prefix = rest[:start]
196
+ end = rest.find("-->", start + 4)
197
+ if end == -1:
198
+ return "", True, prefix
199
+ return rest[end + 3:], False, prefix
200
+
201
+
202
+ def _consume_comment_chunk(rest, in_comment):
203
+ """Consume one comment-state chunk; return (rest, in_comment, kept)."""
204
+ if in_comment:
205
+ return _consume_in_comment(rest)
206
+ return _consume_outside_comment(rest)
207
+
208
+
209
+ def _strip_comments_in_line(line, in_comment):
210
+ """Remove HTML comments from one line; return (result, in_comment)."""
211
+ result = ""
212
+ rest = line
213
+ while rest:
214
+ rest, in_comment, kept = _consume_comment_chunk(rest, in_comment)
215
+ result += kept
216
+ return result, in_comment
217
+
218
+
219
+ def _strip_ignored_line(line, in_fence, in_comment):
220
+ """Strip one line; return (result, in_fence, in_comment)."""
221
+ if line.strip().startswith("```"):
222
+ return "", not in_fence, in_comment
223
+ if in_fence:
224
+ return "", in_fence, in_comment
225
+ result, in_comment = _strip_comments_in_line(line, in_comment)
226
+ return result, in_fence, in_comment
227
+
228
+
229
+ def strip_ignored(text):
230
+ """Blank out fenced code blocks and HTML comments, keeping line numbers."""
231
+ out = []
232
+ in_fence = False
233
+ in_comment = False
234
+ for line in text.splitlines():
235
+ stripped, in_fence, in_comment = _strip_ignored_line(
236
+ line, in_fence, in_comment)
237
+ out.append(stripped)
238
+ return out
239
+
240
+
241
+ def split_reason(body):
242
+ """Return (before, after) split on an em dash or double hyphen."""
243
+ for sep in ("\u2014", "--"):
244
+ if sep in body:
245
+ before, _, after = body.partition(sep)
246
+ return before.strip(), after.strip()
247
+ return body.strip(), ""
248
+
249
+
250
+ def add_months(day, months):
251
+ """Return day shifted by whole calendar months, clamping month-end."""
252
+ month_index = (day.year * 12 + (day.month - 1)) + months
253
+ year, month = divmod(month_index, 12)
254
+ month += 1
255
+ # Last day of the target month.
256
+ next_month = datetime.date(year + 1, 1, 1) if month == 12 else datetime.date(year, month + 1, 1)
257
+ last_day = (next_month - datetime.timedelta(days=1)).day
258
+ return datetime.date(year, month, min(day.day, last_day))
259
+
260
+
261
+ def _parse_review_date(raw):
262
+ """Parse YYYY-MM-DD, returning a date or None when not a real date."""
263
+ try:
264
+ return datetime.date.fromisoformat(raw)
265
+ except ValueError:
266
+ return None
267
+
268
+
269
+ def _normalize_glob_pattern(pattern):
270
+ """Normalize separators and strip a leading ./ or / from a glob."""
271
+ pattern = pattern.replace("\\", "/").strip()
272
+ if pattern.startswith("./"):
273
+ pattern = pattern[2:]
274
+ if pattern.startswith("/"):
275
+ pattern = pattern[1:]
276
+ return pattern
277
+
278
+
279
+ def _glob_class_end(pattern, i):
280
+ """Index of the ] closing the class at i, or len(pattern)."""
281
+ n = len(pattern)
282
+ j = i + 1
283
+ if j < n and pattern[j] in "!^":
284
+ j += 1
285
+ if j < n and pattern[j] == "]":
286
+ j += 1
287
+ while j < n and pattern[j] != "]":
288
+ j += 1
289
+ return j
290
+
291
+
292
+ def _glob_class_fragment(pattern, i, j):
293
+ """Regex fragment for the class at i ending at j; return (frag, next)."""
294
+ if j >= len(pattern):
295
+ return re.escape("["), i + 1
296
+ body = pattern[i + 1:j]
297
+ if body.startswith("!"):
298
+ body = "^" + body[1:]
299
+ return "[" + body.replace("\\", "\\\\") + "]", j + 1
300
+
301
+
302
+ def _glob_class(pattern, i):
303
+ """Regex fragment for the [...] class at i; return (frag, next)."""
304
+ return _glob_class_fragment(pattern, i, _glob_class_end(pattern, i))
305
+
306
+
307
+ def _glob_double_star_token(pattern, i):
308
+ """Fragment for a ** token at i, or None; return (frag, next)."""
309
+ if pattern.startswith("**/", i):
310
+ return r"(?:.*/)?", i + 3
311
+ if pattern.startswith("/**", i) and i + 3 == len(pattern):
312
+ return r"(?:/.*)?", i + 3
313
+ if pattern.startswith("**", i):
314
+ return r".*", i + 2
315
+ return None
316
+
317
+
318
+ def _glob_single_token(pattern, i):
319
+ """Fragment for a single-character token at i; return (frag, next)."""
320
+ ch = pattern[i]
321
+ if ch == "*":
322
+ return r"[^/]*", i + 1
323
+ if ch == "?":
324
+ return r"[^/]", i + 1
325
+ if ch == "[":
326
+ return _glob_class(pattern, i)
327
+ return re.escape(ch), i + 1
328
+
329
+
330
+ def _glob_token(pattern, i):
331
+ """Regex fragment for the glob token at i; return (frag, next)."""
332
+ token = _glob_double_star_token(pattern, i)
333
+ if token is not None:
334
+ return token
335
+ return _glob_single_token(pattern, i)
336
+
337
+
338
+ def _glob_regex(pattern):
339
+ """Compile a repo-relative glob to an anchored regex.
340
+
341
+ * matches within one path segment, ** crosses segments, ? matches
342
+ one non-separator character, and [...] is a character class.
343
+ """
344
+ pattern = _normalize_glob_pattern(pattern)
345
+ out = "^"
346
+ i = 0
347
+ n = len(pattern)
348
+ while i < n:
349
+ fragment, i = _glob_token(pattern, i)
350
+ out += fragment
351
+ out += "$"
352
+ return re.compile(out)
353
+
354
+
355
+ def scope_matches(scope, rel_paths):
356
+ """True when scope matches at least one repo-relative file path."""
357
+ scope = scope.replace("\\", "/").strip()
358
+ if scope.startswith("./"):
359
+ scope = scope[2:]
360
+ if scope.startswith("/"):
361
+ scope = scope[1:]
362
+ if not any(ch in scope for ch in "*?["):
363
+ prefix = scope.rstrip("/") + "/"
364
+ return any(rel == scope or rel.startswith(prefix) for rel in rel_paths)
365
+ regex = _glob_regex(scope)
366
+ return any(regex.match(rel) for rel in rel_paths)
367
+
368
+
369
+ def collect_repo_files(repo_root):
370
+ """Sorted repo-relative POSIX paths of real files under repo_root.
371
+
372
+ Paths inside a .git directory are skipped so version-control
373
+ internals cannot satisfy a scope by accident.
374
+ """
375
+ root = pathlib.Path(repo_root).expanduser()
376
+ files = []
377
+ for path in root.rglob("*"):
378
+ if ".git" in path.parts:
379
+ continue
380
+ if path.is_file():
381
+ files.append(path.relative_to(root).as_posix())
382
+ return sorted(files)
383
+
384
+
385
+ def _check_adoption(lines, generalized_version, findings):
386
+ """(a) Adoption-line check over stripped project-guide lines."""
387
+ joined = " ".join(lines)
388
+ match = ADOPTION_RE.search(joined)
389
+ adoption_line = 1
390
+ for idx, line in enumerate(lines, start=1):
391
+ if "adopts" in line.lower():
392
+ adoption_line = idx
393
+ break
394
+ if match is None:
395
+ if ADOPTION_NO_VERSION_RE.search(joined):
396
+ findings.append((
397
+ "ERROR", adoption_line,
398
+ "adoption line names the Generalized Style Guide without a "
399
+ "version; state the adopted version (for example "
400
+ "'adopts the Generalized Style Guide v1.1')"))
401
+ else:
402
+ findings.append((
403
+ "ERROR", 1,
404
+ "missing adoption line; the project guide must state it "
405
+ "adopts the Generalized Style Guide with a version (for "
406
+ "example 'adopts the Generalized Style Guide v1.1')"))
407
+ return
408
+ adopted = match.group(1)
409
+ if generalized_version is None:
410
+ findings.append((
411
+ "INFO", adoption_line,
412
+ "generalized guide version could not be parsed; adoption "
413
+ "version comparison skipped"))
414
+ elif adopted != generalized_version:
415
+ findings.append((
416
+ "WARN", adoption_line,
417
+ f"stale adoption: project adopts Generalized Style Guide "
418
+ f"v{adopted}, generalized guide is v{generalized_version}"))
419
+
420
+
421
+ def _check_decision_line(line, idx, today, findings):
422
+ """(d) ST-DEP-03: decision lines need a review date within 6 months."""
423
+ if not DECISION_RE.search(line):
424
+ return
425
+ rm = REVIEW_RE.search(line)
426
+ if not rm:
427
+ findings.append((
428
+ "ERROR", idx,
429
+ "decision line needs review date within 6 months (ST-DEP-03)"))
430
+ return
431
+ review = _parse_review_date(rm.group(1))
432
+ if review is None:
433
+ findings.append((
434
+ "ERROR", idx,
435
+ f"decision line review date {rm.group(1)} is not a real date; "
436
+ "needs review date within 6 months (ST-DEP-03)"))
437
+ elif review < today:
438
+ findings.append((
439
+ "ERROR", idx,
440
+ f"decision line review date {review} has expired; needs "
441
+ "review date within 6 months (ST-DEP-03)"))
442
+ elif review > add_months(today, 6):
443
+ findings.append((
444
+ "ERROR", idx,
445
+ f"decision line review date {review} is more than 6 months "
446
+ "out; needs review date within 6 months (ST-DEP-03)"))
447
+
448
+
449
+ def _resolve_repo_files(repo_root, findings):
450
+ """Repo file list for scope checks, or None when not requested."""
451
+ if repo_root is None:
452
+ return None
453
+ root = pathlib.Path(repo_root).expanduser()
454
+ if root.is_dir():
455
+ return collect_repo_files(root)
456
+ findings.append((
457
+ "ERROR", 1, f"repo root {repo_root} is not a directory"))
458
+ return []
459
+
460
+
461
+ def _canonicalize_tag_target(kind, target, idx, findings):
462
+ """Warn on a legacy SG- tag target; return its canonical form."""
463
+ if kind not in ("OVERRIDE", "BYPASS"):
464
+ return target
465
+ if not target.startswith(LEGACY_PREFIX):
466
+ return target
467
+ findings.append((
468
+ "WARN", idx,
469
+ f"{kind} {target}: legacy SG- prefix; rename to "
470
+ f"{canonical_rule_id(target)} (guide v2.0)"))
471
+ return canonical_rule_id(target)
472
+
473
+
474
+ def _check_scope_value(scope, kind, target, idx, repo_files, findings):
475
+ """Check one extracted scope value for emptiness and file matches."""
476
+ if not scope:
477
+ findings.append(("ERROR", idx, f"{kind} {target}: empty scope"))
478
+ return
479
+ if repo_files is None:
480
+ return
481
+ if not scope_matches(scope, repo_files):
482
+ findings.append((
483
+ "WARN", idx,
484
+ f"{kind} {target}: scope '{scope}' matches no files "
485
+ "under repo root"))
486
+
487
+
488
+ def _extract_scope(body, kind, target, idx, repo_files, findings):
489
+ """Split a trailing [scope: ...] off body; return (scope, body)."""
490
+ sm = SCOPE_RE.search(body)
491
+ if not sm:
492
+ return "", body
493
+ scope = sm.group(1).strip()
494
+ body = body[:sm.start()].strip()
495
+ _check_scope_value(scope, kind, target, idx, repo_files, findings)
496
+ return scope, body
497
+
498
+
499
+ def _check_duplicate(seen, kind, target, scope, idx, findings):
500
+ """Warn when the same (kind, target, scope) tag repeats."""
501
+ key = (kind, target, scope)
502
+ if key in seen:
503
+ findings.append(("WARN", idx, f"{kind} {target}: duplicate tag (first on line {seen[key]})"))
504
+ return
505
+ seen[key] = idx
506
+
507
+
508
+ def _validate_override(target, body, idx, rules, findings):
509
+ """OVERRIDE checks: known DEFAULT rule with replacement and reason."""
510
+ if target not in rules:
511
+ findings.append(("ERROR", idx, f"OVERRIDE {target}: unknown rule ID"))
512
+ return
513
+ if rules[target] == "REQUIRED":
514
+ findings.append(("ERROR", idx, f"OVERRIDE {target}: rule is REQUIRED; use BYPASS with approver and review date"))
515
+ replacement, reason = split_reason(body)
516
+ if not replacement or not reason:
517
+ findings.append(("ERROR", idx, f"OVERRIDE {target}: needs '<replacement> - <reason>'"))
518
+
519
+
520
+ def _check_bypass_reason(body, target, idx, findings):
521
+ """BYPASS check: a reason must be present."""
522
+ reason, _ = split_reason(body)
523
+ if not reason:
524
+ findings.append(("ERROR", idx, f"BYPASS {target}: missing reason"))
525
+
526
+
527
+ def _check_bypass_approver(body, target, idx, findings):
528
+ """BYPASS check: an 'approved: <name>' approver must be present."""
529
+ am = APPROVED_RE.search(body)
530
+ if not am or not am.group(1).strip():
531
+ findings.append(("ERROR", idx, f"BYPASS {target}: missing 'approved: <name>'"))
532
+
533
+
534
+ def _check_bypass_review(body, target, idx, today, findings):
535
+ """BYPASS check: review date present, real, unexpired, within 12 months."""
536
+ rm = REVIEW_RE.search(body)
537
+ if not rm:
538
+ findings.append(("ERROR", idx, f"BYPASS {target}: missing 'review: YYYY-MM-DD'"))
539
+ return
540
+ review = _parse_review_date(rm.group(1))
541
+ if review is None:
542
+ findings.append(("ERROR", idx, f"BYPASS {target}: review date {rm.group(1)} is not a real date"))
543
+ return
544
+ if review < today:
545
+ findings.append(("ERROR", idx, f"BYPASS {target}: review date {review} has expired"))
546
+ return
547
+ if (review - today).days > 366:
548
+ findings.append(("WARN", idx, f"BYPASS {target}: review date {review} is more than 12 months out"))
549
+
550
+
551
+ def _check_bypass_security(target, idx, findings):
552
+ """Report a security-rule bypass as INFO so it stays visible."""
553
+ if target.startswith(SECURITY_PREFIXES):
554
+ findings.append(("INFO", idx, f"BYPASS {target}: security rule bypassed; reviews report this as a HIGH visibility finding"))
555
+
556
+
557
+ def _validate_bypass(target, body, idx, rules, today, findings):
558
+ """BYPASS checks: known REQUIRED rule with reason, approver, review."""
559
+ if target not in rules:
560
+ findings.append(("ERROR", idx, f"BYPASS {target}: unknown rule ID"))
561
+ return
562
+ if rules[target] == "DEFAULT":
563
+ findings.append(("ERROR", idx, f"BYPASS {target}: rule is DEFAULT; use OVERRIDE"))
564
+ _check_bypass_reason(body, target, idx, findings)
565
+ _check_bypass_approver(body, target, idx, findings)
566
+ _check_bypass_review(body, target, idx, today, findings)
567
+ _check_bypass_security(target, idx, findings)
568
+
569
+
570
+ def _check_bypass_lib_status(target, idx, statuses, findings):
571
+ """Warn when a bypassed package is Planned or Held."""
572
+ status = statuses.get(target)
573
+ if status in ("Planned", "Held"):
574
+ findings.append((
575
+ "WARN", idx,
576
+ f"BYPASS-LIB {target}: package is {status}; build "
577
+ "behind an interface instead (ST-LIB-02/ST-LIB-03)"))
578
+
579
+
580
+ def _check_bypass_lib_alternative(body, target, idx, findings):
581
+ """BYPASS-LIB check: reason plus a non-empty alternative."""
582
+ if "alternative:" not in body.lower():
583
+ findings.append(("ERROR", idx, f"BYPASS-LIB {target}: missing 'alternative: <what replaces it>'"))
584
+ return
585
+ reason_part, _, alt_part = body.lower().partition("alternative:")
586
+ reason = reason_part.strip().rstrip("\u2014-").strip()
587
+ if not reason:
588
+ findings.append(("ERROR", idx, f"BYPASS-LIB {target}: missing reason"))
589
+ if not alt_part.strip():
590
+ findings.append(("ERROR", idx, f"BYPASS-LIB {target}: empty alternative"))
591
+
592
+
593
+ def _validate_bypass_lib(target, body, idx, packages, statuses, findings):
594
+ """BYPASS-LIB checks: known package with reason and alternative."""
595
+ if target not in packages:
596
+ findings.append(("ERROR", idx, f"BYPASS-LIB {target}: package not in the generalized guide's package map"))
597
+ return
598
+ _check_bypass_lib_status(target, idx, statuses, findings)
599
+ _check_bypass_lib_alternative(body, target, idx, findings)
600
+
601
+
602
+ @dataclass
603
+ class _ValidationContext:
604
+ """Shared validation state threaded through the per-line checks."""
605
+
606
+ rules: dict
607
+ packages: dict
608
+ statuses: dict
609
+ today: datetime.date
610
+ repo_files: list
611
+ findings: list
612
+ seen: dict
613
+
614
+
615
+ def _validate_tag_kind(kind, target, body, idx, ctx):
616
+ """Dispatch to the checks for one tag kind."""
617
+ if kind == "OVERRIDE":
618
+ _validate_override(target, body, idx, ctx.rules, ctx.findings)
619
+ return
620
+ if kind == "BYPASS":
621
+ _validate_bypass(target, body, idx, ctx.rules, ctx.today, ctx.findings)
622
+ return
623
+ _validate_bypass_lib(target, body, idx, ctx.packages, ctx.statuses, ctx.findings)
624
+
625
+
626
+ def _process_tag_line(line, idx, in_overrides, ctx):
627
+ """Run all tag checks for one line when it carries a tag."""
628
+ m = TAG_RE.match(line)
629
+ if not m:
630
+ return
631
+ kind, target, body = m.group(1), m.group(2), m.group(3).strip()
632
+ target = _canonicalize_tag_target(kind, target, idx, ctx.findings)
633
+ if not in_overrides:
634
+ ctx.findings.append(("WARN", idx, f"{kind} {target}: tag outside the 'Generalized guide overrides' section"))
635
+ scope, body = _extract_scope(
636
+ body, kind, target, idx, ctx.repo_files, ctx.findings)
637
+ _check_duplicate(ctx.seen, kind, target, scope, idx, ctx.findings)
638
+ _validate_tag_kind(kind, target, body, idx, ctx)
639
+
640
+
641
+ def _process_line(line, idx, in_overrides, ctx):
642
+ """Process one project-guide line; return the overrides-section flag."""
643
+ _check_decision_line(line, idx, ctx.today, ctx.findings)
644
+ if line.startswith("## "):
645
+ return line.strip().lower() == "## generalized guide overrides"
646
+ _process_tag_line(line, idx, in_overrides, ctx)
647
+ return in_overrides
648
+
649
+
650
+ def validate(project_text, rules, packages, today, *,
651
+ generalized_version=_UNSET, package_statuses=None, repo_root=None):
652
+ """Return findings as (level, line_no, message) tuples.
653
+
654
+ generalized_version: pass the generalized guide's version string
655
+ to enable the adoption check, or None when it could not be
656
+ parsed (presence still enforced, comparison skipped with INFO).
657
+ Omitting it keeps the pre-v2 behaviour for direct callers; the
658
+ CLI always passes it. package_statuses maps package IDs to
659
+ Available/Planned/Held. repo_root enables scope-glob matching
660
+ against real files.
661
+ """
662
+ findings = [] # (level, line_no, message)
663
+ lines = strip_ignored(project_text)
664
+ statuses = package_statuses or {}
665
+ repo_files = _resolve_repo_files(repo_root, findings)
666
+ if generalized_version is not _UNSET:
667
+ _check_adoption(lines, generalized_version, findings)
668
+ in_overrides = False
669
+ ctx = _ValidationContext(
670
+ rules=rules, packages=packages, statuses=statuses, today=today,
671
+ repo_files=repo_files, findings=findings, seen={})
672
+ for idx, line in enumerate(lines, start=1):
673
+ in_overrides = _process_line(line, idx, in_overrides, ctx)
674
+ findings.sort(key=lambda f: f[1])
675
+ return findings
676
+
677
+
678
+ def find_generalized(arg):
679
+ candidates = [arg] if arg else DEFAULT_GENERALIZED_CANDIDATES
680
+ for c in candidates:
681
+ if not c:
682
+ continue
683
+ p = pathlib.Path(c).expanduser()
684
+ if p.is_file():
685
+ return p
686
+ return None
687
+
688
+
689
+ def _build_arg_parser():
690
+ """Build the command-line argument parser."""
691
+ ap = argparse.ArgumentParser(description="Validate style-guide override/bypass tags.")
692
+ ap.add_argument("project_guide", help="path to the project STYLE_GUIDE.md")
693
+ ap.add_argument("--generalized", help="path to the Generalized Style Guide")
694
+ ap.add_argument("--repo-root",
695
+ help="repo root directory; each tag scope glob must "
696
+ "match at least one real file under it")
697
+ ap.add_argument("--today", help="override today's date (YYYY-MM-DD), for tests")
698
+ ap.add_argument("--strict", action="store_true", help="warnings also fail")
699
+ ap.add_argument("--json", action="store_true", help="emit JSON findings")
700
+ return ap
701
+
702
+
703
+ def _load_generalized_guide(generalized_arg):
704
+ """Load the generalized guide; return (text, rules, packages) or None."""
705
+ gen_path = find_generalized(generalized_arg)
706
+ if gen_path is None:
707
+ print("ERROR: generalized guide not found; pass --generalized", file=sys.stderr)
708
+ return None
709
+ gen_text = gen_path.read_text(encoding="utf-8")
710
+ rules, packages = parse_generalized(gen_text)
711
+ if not rules:
712
+ print(f"ERROR: no rules parsed from {gen_path}", file=sys.stderr)
713
+ return None
714
+ return gen_text, rules, packages
715
+
716
+
717
+ def _resolve_cli_repo_root(repo_root_arg):
718
+ """Resolve --repo-root; return (repo_root, ok)."""
719
+ if not repo_root_arg:
720
+ return None, True
721
+ repo_root = pathlib.Path(repo_root_arg).expanduser()
722
+ if repo_root.is_dir():
723
+ return repo_root, True
724
+ print(f"ERROR: --repo-root {repo_root_arg} is not a directory",
725
+ file=sys.stderr)
726
+ return None, False
727
+
728
+
729
+ def _resolve_today(today_arg):
730
+ """Return the --today override date, or today's date."""
731
+ if today_arg:
732
+ return datetime.date.fromisoformat(today_arg)
733
+ return datetime.date.today()
734
+
735
+
736
+ def _findings_at_level(findings, level):
737
+ """Findings at one severity level."""
738
+ return [f for f in findings if f[0] == level]
739
+
740
+
741
+ def _emit_text_findings(findings, rules, packages):
742
+ """Print findings as text lines plus a summary line."""
743
+ for level, line_no, message in findings:
744
+ print(f"{level} line {line_no}: {message}")
745
+ print(f"{len(_findings_at_level(findings, 'ERROR'))} error(s), "
746
+ f"{len(_findings_at_level(findings, 'WARN'))} warning(s), "
747
+ f"{len(_findings_at_level(findings, 'INFO'))} info - "
748
+ f"checked against {len(rules)} rules, {len(packages)} packages")
749
+
750
+
751
+ def _emit_findings(findings, rules, packages, as_json):
752
+ """Print findings as JSON or as text, per the --json flag."""
753
+ if as_json:
754
+ print(json.dumps([{"level": l, "line": n, "message": m} for l, n, m in findings], indent=1))
755
+ return
756
+ _emit_text_findings(findings, rules, packages)
757
+
758
+
759
+ def _exit_code(findings, strict):
760
+ """Exit code for a finding set: 1 on errors (or warnings if strict)."""
761
+ if _findings_at_level(findings, "ERROR"):
762
+ return 1
763
+ if strict and _findings_at_level(findings, "WARN"):
764
+ return 1
765
+ return 0
766
+
767
+
768
+ def main(argv=None):
769
+ args = _build_arg_parser().parse_args(argv)
770
+
771
+ loaded = _load_generalized_guide(args.generalized)
772
+ if loaded is None:
773
+ return 2
774
+ gen_text, rules, packages = loaded
775
+ generalized_version = parse_generalized_version(gen_text)
776
+ package_statuses = parse_package_statuses(gen_text)
777
+
778
+ repo_root, repo_ok = _resolve_cli_repo_root(args.repo_root)
779
+ if not repo_ok:
780
+ return 2
781
+
782
+ today = _resolve_today(args.today)
783
+ project_text = pathlib.Path(args.project_guide).expanduser().read_text(encoding="utf-8")
784
+ findings = validate(
785
+ project_text, rules, packages, today,
786
+ generalized_version=generalized_version,
787
+ package_statuses=package_statuses,
788
+ repo_root=repo_root)
789
+
790
+ _emit_findings(findings, rules, packages, args.json)
791
+ return _exit_code(findings, args.strict)
792
+
793
+
794
+ if __name__ == "__main__":
795
+ raise SystemExit(main())