@rvdbreemen/adr-kit-opencode 0.52.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 (129) hide show
  1. package/.claude-plugin/plugin.json +29 -0
  2. package/LICENSE +21 -0
  3. package/README.md +850 -0
  4. package/bin/adr +1552 -0
  5. package/bin/adr-audit +454 -0
  6. package/bin/adr-context +584 -0
  7. package/bin/adr-discover +546 -0
  8. package/bin/adr-doctor +166 -0
  9. package/bin/adr-generate-scripts +421 -0
  10. package/bin/adr-grill-signal +131 -0
  11. package/bin/adr-guardian +1263 -0
  12. package/bin/adr-index +199 -0
  13. package/bin/adr-judge +2832 -0
  14. package/bin/adr-judge-precommit +87 -0
  15. package/bin/adr-lint +2087 -0
  16. package/bin/adr-mcp +1093 -0
  17. package/bin/adr-migrate +644 -0
  18. package/bin/adr-quality +275 -0
  19. package/bin/adr-readiness +211 -0
  20. package/bin/adr-readiness-ci +111 -0
  21. package/bin/adr-related +401 -0
  22. package/bin/adr-renumber +254 -0
  23. package/bin/adr-retire +467 -0
  24. package/bin/adr-settings +399 -0
  25. package/bin/adr-status +797 -0
  26. package/bin/adr-suggest +803 -0
  27. package/bin/adr-watch +674 -0
  28. package/bin/adr_catalog.py +536 -0
  29. package/bin/adr_config.py +280 -0
  30. package/bin/adr_doctor_checks.py +407 -0
  31. package/bin/adr_doctor_core.py +342 -0
  32. package/bin/adr_doctor_models.py +186 -0
  33. package/bin/adr_doctor_probes.py +216 -0
  34. package/bin/adr_format.py +786 -0
  35. package/bin/adr_grill_signal.py +123 -0
  36. package/bin/adr_guardian_queue.py +218 -0
  37. package/bin/adr_history_scan.py +278 -0
  38. package/bin/adr_index_core.py +443 -0
  39. package/bin/adr_llm.py +333 -0
  40. package/bin/adr_llm_judge_migration.py +314 -0
  41. package/bin/adr_quality_core.py +674 -0
  42. package/bin/adr_query.py +678 -0
  43. package/bin/adr_readiness.py +442 -0
  44. package/bin/adr_readiness_ci.py +123 -0
  45. package/bin/adr_regex.py +165 -0
  46. package/bin/adr_regex_worker.py +30 -0
  47. package/bin/adr_retrieval_health.py +385 -0
  48. package/bin/adr_schema.py +448 -0
  49. package/bin/adr_state.py +172 -0
  50. package/bin/bump-version +71 -0
  51. package/clients/workflows.json +229 -0
  52. package/hooks/__init__.py +1 -0
  53. package/hooks/adapters/__init__.py +13 -0
  54. package/hooks/adapters/claude.py +27 -0
  55. package/hooks/adapters/codex.py +26 -0
  56. package/hooks/adapters/copilot.py +11 -0
  57. package/hooks/adr-hook.py +128 -0
  58. package/hooks/adr_hook_core.py +843 -0
  59. package/hooks/adr_pr_guard.py +367 -0
  60. package/instructions/ADR-guide.md +48 -0
  61. package/instructions/adr.coding.md +82 -0
  62. package/instructions/adr.review.md +182 -0
  63. package/opencode/plugin.ts +451 -0
  64. package/package.json +41 -0
  65. package/schemas/adr-context-probes.schema.json +56 -0
  66. package/schemas/adr-enforcement.schema.json +57 -0
  67. package/schemas/adr-frontmatter.schema.json +144 -0
  68. package/schemas/adr-index.schema.json +276 -0
  69. package/schemas/adr-kit-config.schema.json +371 -0
  70. package/schemas/adr-readiness.schema.json +41 -0
  71. package/schemas/client-capabilities.schema.json +503 -0
  72. package/schemas/client-certification.schema.json +101 -0
  73. package/schemas/doctor-output.schema.json +92 -0
  74. package/schemas/marketplace.json.schema.json +70 -0
  75. package/schemas/plugin.json.schema.json +67 -0
  76. package/scripts/adr_settings.py +239 -0
  77. package/scripts/benchmark-adr-grilling.py +323 -0
  78. package/scripts/benchmark-client-generation.py +178 -0
  79. package/scripts/build-client-adapters.py +139 -0
  80. package/scripts/bump-version.py +304 -0
  81. package/scripts/check-branch-sync.py +243 -0
  82. package/scripts/check-release-version.py +81 -0
  83. package/scripts/client_certification.py +153 -0
  84. package/scripts/client_evidence.py +280 -0
  85. package/scripts/client_generation.py +288 -0
  86. package/scripts/client_generation_artifacts.py +351 -0
  87. package/scripts/client_generation_model.py +173 -0
  88. package/scripts/client_generation_state.py +260 -0
  89. package/scripts/client_support_matrix.py +360 -0
  90. package/scripts/install-agent-envs.py +300 -0
  91. package/scripts/probe-client-events.py +183 -0
  92. package/scripts/project_setup.py +379 -0
  93. package/scripts/refresh-otgw-corpus.py +219 -0
  94. package/scripts/settings.py +81 -0
  95. package/scripts/setup-project.py +205 -0
  96. package/scripts/sync-agent-plugins.py +17 -0
  97. package/scripts/version_sites.py +377 -0
  98. package/skills/adr/SKILL.md +780 -0
  99. package/skills/audit/SKILL.md +103 -0
  100. package/skills/context/SKILL.md +77 -0
  101. package/skills/grill/SKILL.md +84 -0
  102. package/skills/grill/agents/openai.yaml +4 -0
  103. package/skills/guardian/SKILL.md +316 -0
  104. package/skills/init/SKILL.md +499 -0
  105. package/skills/install-hooks/SKILL.md +154 -0
  106. package/skills/judge/SKILL.md +168 -0
  107. package/skills/lint/SKILL.md +321 -0
  108. package/skills/migrate/SKILL.md +313 -0
  109. package/skills/related/SKILL.md +62 -0
  110. package/skills/retire/SKILL.md +41 -0
  111. package/skills/review/SKILL.md +167 -0
  112. package/skills/settings/SKILL.md +73 -0
  113. package/skills/setup/SKILL.md +128 -0
  114. package/skills/supersede/SKILL.md +136 -0
  115. package/skills/upgrade/SKILL.md +273 -0
  116. package/templates/adr-kit-guide.md +354 -0
  117. package/templates/adr-template.canonical.md +115 -0
  118. package/templates/adr-template.madr.md +131 -0
  119. package/templates/adr-template.md +131 -0
  120. package/templates/adr-template.nygard.md +111 -0
  121. package/templates/cc-settings/guardian-hook-entry.json +9 -0
  122. package/templates/githooks/pre-commit +337 -0
  123. package/templates/github-workflows/adr-audit.yml +58 -0
  124. package/templates/github-workflows/adr-guardian-audit.yml +133 -0
  125. package/templates/github-workflows/adr-index-check.yml +30 -0
  126. package/templates/github-workflows/adr-judge.yml +31 -0
  127. package/templates/github-workflows/adr-readiness.yml +18 -0
  128. package/templates/validate_adr_template.py +38 -0
  129. package/templates/validate_adr_template.sh +74 -0
package/bin/adr-lint ADDED
@@ -0,0 +1,2087 @@
1
+ #!/usr/bin/env python3
2
+ """adr-lint: deterministic CLI for the four adr-kit verification gates.
3
+
4
+ Pairs with the /adr-kit:lint Claude Code skill. Use this CLI in CI / pre-commit
5
+ hooks where Claude is not in the loop. Default gates are completeness and
6
+ consistency (the deterministic ones). The heuristic gates evidence and clarity
7
+ are available behind --gates but are off by default because they need
8
+ judgement that a regex cannot reliably provide.
9
+
10
+ Severity model matches the v0.9.0 skill exactly:
11
+ ignore > per-ADR markers > config.severity
12
+ always_strict > always_advisory > advisory_before_strict_from
13
+
14
+ Exit codes:
15
+ 0 no FAIL (PASS / ADVISORY / SKIPPED counts may be non-zero)
16
+ 1 at least one FAIL
17
+ 2 config or input error (malformed JSON, unknown field, bad path)
18
+
19
+ Usage:
20
+ adr-lint # lint docs/adr/, config from docs/adr/.adr-kit.json
21
+ adr-lint docs/decisions/ # lint a different directory
22
+ adr-lint docs/adr/ADR-042-foo.md # lint a single file
23
+ adr-lint --strict-from ADR-100 # override config strict_from
24
+ adr-lint --gates completeness # only completeness gate
25
+ adr-lint --gates schema # validate canonical frontmatter
26
+ adr-lint --format json # machine-readable output
27
+ adr-lint --config /tmp/policy.json # custom config path
28
+ adr-lint --context-dir docs/adr docs/adr/ADR-042-foo.md
29
+ # lint one file, resolve its
30
+ # cross-references against the whole set
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import argparse
36
+ import importlib.machinery
37
+ import importlib.util
38
+ import json
39
+ import os
40
+ import re
41
+ import shutil
42
+ import subprocess
43
+ import sys
44
+ from datetime import date
45
+ from pathlib import Path
46
+ from typing import Dict, Iterable, List, Optional, Set, Tuple
47
+
48
+ _BIN_DIR = Path(__file__).resolve().parent
49
+
50
+
51
+ def _load_sibling(name: str):
52
+ """Import bin/<name>.py by explicit path, WITHOUT touching sys.path.
53
+
54
+ SEC-HIGH (TASK-62): `sys.path.insert(0, _BIN_DIR)` put this directory ahead
55
+ of the standard library for every import, so a module committed next to
56
+ this script executed as code -- and it re-added the very directory
57
+ CPython's -P / PYTHONSAFEPATH removes. Siblings are registered in
58
+ sys.modules under their bare name, so the plain `from adr_* import ...`
59
+ statements below resolve from the cache instead of the path.
60
+
61
+ This one matters more than most: adr-lint is the only executable that still
62
+ imports the optional third-party `jsonschema` (three sites below), which is
63
+ exactly the name the original finding used as its payload.
64
+ bin/adr-judge carries the full rationale.
65
+ """
66
+ cached = sys.modules.get(name)
67
+ if cached is not None:
68
+ return cached
69
+ loader = importlib.machinery.SourceFileLoader(name, str(_BIN_DIR / f"{name}.py"))
70
+ spec = importlib.util.spec_from_loader(name, loader)
71
+ module = importlib.util.module_from_spec(spec)
72
+ sys.modules[name] = module
73
+ loader.exec_module(module)
74
+ return module
75
+
76
+
77
+ # Dependency order: adr_catalog imports adr_format and adr_schema.
78
+ _load_sibling("adr_format")
79
+ _load_sibling("adr_schema")
80
+ _load_sibling("adr_catalog")
81
+ _load_sibling("adr_config")
82
+
83
+
84
+ def _import_jsonschema():
85
+ """Import the optional third-party jsonschema -- never a bin/ sibling.
86
+
87
+ SEC-HIGH (TASK-62), the residual half. Dropping the explicit
88
+ sys.path.insert is not enough on its own: CPython still puts this script's
89
+ own directory at sys.path[0] for a plain `python bin/adr-lint` run, and
90
+ jsonschema is the one name adr-lint resolves through the path rather than
91
+ through _load_sibling. It is also the exact name the original finding used
92
+ as its payload, so a committed bin/jsonschema.py still executed here after
93
+ the sibling conversion -- reproduced, then fixed by this function.
94
+
95
+ The masking is scoped and reverted because the test suite imports this file
96
+ in-process; a permanent scrub would delete bin/ from pytest's own sys.path
97
+ and break unrelated test modules that put it there deliberately.
98
+
99
+ Returns the module, or None when jsonschema is not installed.
100
+ """
101
+ saved = list(sys.path)
102
+ sys.path[:] = [entry for entry in saved if not _is_bin_dir(entry)]
103
+ try:
104
+ import jsonschema # type: ignore
105
+
106
+ return jsonschema
107
+ except ImportError:
108
+ return None
109
+ finally:
110
+ sys.path[:] = saved
111
+
112
+
113
+ def _is_bin_dir(entry: str) -> bool:
114
+ """True when a sys.path entry resolves to this script's own directory.
115
+
116
+ Compared resolved, not textually: CPython only guarantees an absolute
117
+ sys.path[0] from 3.11 onward, and "" (cwd) must also be caught when bin/
118
+ happens to be the working directory.
119
+ """
120
+ try:
121
+ return Path(entry or ".").resolve() == _BIN_DIR
122
+ except (OSError, ValueError):
123
+ return False
124
+
125
+ from adr_schema import (
126
+ FrontmatterError,
127
+ migrate_text,
128
+ parse_frontmatter,
129
+ split_frontmatter,
130
+ validate_frontmatter,
131
+ )
132
+ from adr_catalog import (
133
+ ENFORCEMENT_BLOCK_RE,
134
+ STATUS_BOLD_INLINE_RE,
135
+ STATUS_HEADING_RE,
136
+ STATUS_LINE_RE,
137
+ adr_status,
138
+ )
139
+ from adr_format import (
140
+ SUPPORTED_PROFILES,
141
+ all_open_questions,
142
+ detect_profile,
143
+ is_migration_candidate,
144
+ migration_notice,
145
+ required_headings,
146
+ section_text,
147
+ unresolved_open_questions,
148
+ )
149
+
150
+ CANONICAL_REQUIRED_SECTIONS = [
151
+ "## Status",
152
+ "## Context",
153
+ "## Decision",
154
+ "## Alternatives Considered",
155
+ "## Consequences",
156
+ "## Related Decisions",
157
+ "## References",
158
+ ]
159
+
160
+ # PERF-MEDIUM: precompile section-heading patterns. gate_completeness used to
161
+ # compile these per call per heading per file; for large ADR sets this
162
+ # dominated the run.
163
+ _SECTION_PATTERNS: Dict[str, "re.Pattern[str]"] = {
164
+ s: re.compile(r"^" + re.escape(s) + r"\b", re.MULTILINE)
165
+ for s in CANONICAL_REQUIRED_SECTIONS
166
+ }
167
+
168
+
169
+ def _section_pattern(heading: str) -> "re.Pattern[str]":
170
+ """Return a cached MULTILINE pattern for a `## Heading` line."""
171
+ pat = _SECTION_PATTERNS.get(heading)
172
+ if pat is None:
173
+ pat = re.compile(r"^" + re.escape(heading) + r"\b", re.MULTILINE)
174
+ _SECTION_PATTERNS[heading] = pat
175
+ return pat
176
+
177
+
178
+ # PERF-MEDIUM: cached jsonschema validator for the enforcement block.
179
+ _ENFORCEMENT_VALIDATOR = None
180
+ _ENFORCEMENT_VALIDATOR_LOADED = False
181
+
182
+
183
+ def _get_enforcement_validator():
184
+ """Return a cached Draft7Validator for the enforcement schema, or None."""
185
+ global _ENFORCEMENT_VALIDATOR, _ENFORCEMENT_VALIDATOR_LOADED
186
+ if _ENFORCEMENT_VALIDATOR_LOADED:
187
+ return _ENFORCEMENT_VALIDATOR
188
+ _ENFORCEMENT_VALIDATOR_LOADED = True
189
+ jsonschema = _import_jsonschema()
190
+ if jsonschema is None:
191
+ return None
192
+ schema_path = (
193
+ Path(__file__).resolve().parent.parent
194
+ / "schemas"
195
+ / "adr-enforcement.schema.json"
196
+ )
197
+ if not schema_path.exists():
198
+ return None
199
+ schema = json.loads(schema_path.read_text(encoding="utf-8"))
200
+ _ENFORCEMENT_VALIDATOR = jsonschema.Draft7Validator(schema)
201
+ return _ENFORCEMENT_VALIDATOR
202
+
203
+ LEGAL_SEVERITIES = {"always_strict", "always_advisory", "advisory_before_strict_from"}
204
+ ALL_GATES = [
205
+ "schema",
206
+ "completeness",
207
+ "audit",
208
+ "evidence",
209
+ "clarity",
210
+ "consistency",
211
+ "policy",
212
+ "quality",
213
+ "open-questions",
214
+ ]
215
+ DEFAULT_GATES = ["completeness", "audit", "consistency"]
216
+
217
+ ENFORCEMENT_KNOWN_KEYS = frozenset(
218
+ {"forbid_pattern", "forbid_import", "require_pattern", "llm_judge", "llm_judge_reason"}
219
+ )
220
+ ENFORCEMENT_ARRAY_KEYS = frozenset({"forbid_pattern", "forbid_import", "require_pattern"})
221
+
222
+ MARKER_RE = re.compile(r"<!--\s*adr-kit-lint:\s*([^>]+?)\s*-->", re.IGNORECASE)
223
+ ADR_FILENAME_RE = re.compile(r"(?i)^ADR-(\d{1,4})-")
224
+ CANONICAL_FILENAME_RE = re.compile(r"^ADR-\d{3}-[a-z0-9-]+\.md$")
225
+ HEADING_NUMBER_RE = re.compile(r"^#\s+(?i:ADR)-(\d{1,4})\b")
226
+ STATUS_HISTORY_START_RE = re.compile(r"^\s*status_history\s*:\s*$", re.IGNORECASE)
227
+ STATUS_HISTORY_ITEM_RE = re.compile(r"^\s*-\s*([a-z_]+)\s*:\s*(.*?)\s*$", re.IGNORECASE)
228
+ STATUS_HISTORY_FIELD_RE = re.compile(r"^\s+([a-z_]+)\s*:\s*(.*?)\s*$", re.IGNORECASE)
229
+ STATUS_HISTORY_REQUIRED_FIELDS = ("date", "status", "changed_by", "reason", "changed_via")
230
+ # Supersession declarations (task-10). Both linear: a literal word, one
231
+ # whitespace run, a literal prefix, one bounded digit run.
232
+ SUPERSEDES_CLAIM_RE = re.compile(r"(?i)\bsupersedes\s+ADR-(\d{1,4})\b")
233
+ SUPERSEDED_BY_RE = re.compile(r"(?i)\bsuperseded\s+by\s+ADR-(\d{1,4})\b")
234
+ TEXT_SCAN_SUFFIXES = {
235
+ ".cfg",
236
+ ".h",
237
+ ".hpp",
238
+ ".ini",
239
+ ".ino",
240
+ ".js",
241
+ ".json",
242
+ ".md",
243
+ ".py",
244
+ ".sh",
245
+ ".ts",
246
+ ".tsx",
247
+ ".txt",
248
+ ".yaml",
249
+ ".yml",
250
+ }
251
+ TEXT_SCAN_DIRS = {".github", ".githooks", "scripts", "tests"}
252
+ TEXT_SCAN_SKIP_DIRS = {
253
+ ".git",
254
+ ".pytest_cache",
255
+ ".venv",
256
+ "__pycache__",
257
+ "backlog",
258
+ "docs",
259
+ "node_modules",
260
+ "vendor",
261
+ }
262
+
263
+
264
+ class PolicyError(Exception):
265
+ """Raised when the configuration file is malformed."""
266
+
267
+
268
+ def load_config(path: Optional[Path]) -> Dict:
269
+ """Read .adr-kit.json (if present) and return as a dict.
270
+
271
+ Returns an empty dict if path is None or does not exist (default behaviour
272
+ is "no config, everything strict"). Raises PolicyError on malformed JSON or
273
+ unrecognised severity values.
274
+ """
275
+ if path is None or not path.exists():
276
+ return {}
277
+ try:
278
+ cfg = json.loads(path.read_text(encoding="utf-8"))
279
+ except json.JSONDecodeError as e:
280
+ raise PolicyError(f"{path}: invalid JSON ({e.msg} at line {e.lineno})")
281
+
282
+ sev = cfg.get("severity")
283
+ if sev is not None:
284
+ if not isinstance(sev, dict):
285
+ raise PolicyError(f"{path}: 'severity' must be an object")
286
+ for gate, value in sev.items():
287
+ if gate not in ALL_GATES:
288
+ raise PolicyError(
289
+ f"{path}: unknown severity gate {gate!r}; legal: {ALL_GATES}"
290
+ )
291
+ if value not in LEGAL_SEVERITIES:
292
+ raise PolicyError(
293
+ f"{path}: severity.{gate}={value!r} not legal; "
294
+ f"must be one of {sorted(LEGAL_SEVERITIES)}"
295
+ )
296
+
297
+ sf = cfg.get("strict_from")
298
+ if sf is not None and not re.match(r"^ADR-\d{3}$", sf):
299
+ raise PolicyError(
300
+ f"{path}: strict_from={sf!r} does not match pattern ADR-NNN"
301
+ )
302
+
303
+ template = cfg.get("template")
304
+ if template is not None:
305
+ if not isinstance(template, dict):
306
+ raise PolicyError(f"{path}: 'template' must be an object")
307
+ profile = template.get("profile")
308
+ if profile is not None and profile not in SUPPORTED_PROFILES:
309
+ raise PolicyError(
310
+ f"{path}: template.profile={profile!r} is unsupported; "
311
+ f"choose one of {SUPPORTED_PROFILES}"
312
+ )
313
+
314
+ # Optional jsonschema validation: deeper structural check.
315
+ jsonschema = _import_jsonschema() # None when not installed; basic checks suffice.
316
+ if jsonschema is not None:
317
+ try:
318
+ schema_path = (
319
+ Path(__file__).resolve().parent.parent
320
+ / "schemas"
321
+ / "adr-kit-config.schema.json"
322
+ )
323
+ if schema_path.exists():
324
+ schema = json.loads(schema_path.read_text(encoding="utf-8"))
325
+ # Retired keys are no longer declared, and this validator is a
326
+ # real schema engine that would reject them as unknown. Lint has
327
+ # to agree with adr_config, which accepts and ignores them --
328
+ # otherwise removing a key nothing read would newly FAIL every
329
+ # project that still sets one. See adr_config.RETIRED_KEYS.
330
+ jsonschema.validate(_without_retired_keys(cfg), schema)
331
+ except Exception as e:
332
+ raise PolicyError(f"{path}: schema validation failed: {e}")
333
+
334
+ return cfg
335
+
336
+
337
+ def _without_retired_keys(cfg: Dict) -> Dict:
338
+ """Return a copy of cfg with the retired keys pruned, for schema validation.
339
+
340
+ A shallow prune of a deep copy: the retirement list is keyed by dotted path,
341
+ so a key is only dropped where it was actually retired, not wherever the
342
+ name happens to appear.
343
+ """
344
+ from adr_config import RETIRED_KEYS
345
+
346
+ def prune(value, path: str):
347
+ if not isinstance(value, dict):
348
+ return value
349
+ return {
350
+ key: prune(item, f"{path}.{key}")
351
+ for key, item in value.items()
352
+ if f"{path}.{key}" not in RETIRED_KEYS
353
+ }
354
+
355
+ return prune(cfg, "$")
356
+
357
+
358
+ def severity_of(
359
+ gate: str, adr_num: int, cfg: Dict, strict_from_override: Optional[str]
360
+ ) -> str:
361
+ """Return 'FAIL' or 'ADVISORY' for a gate failure, given the policy."""
362
+ sf_id = strict_from_override or cfg.get("strict_from")
363
+ sf_num = (
364
+ int(re.match(r"ADR-(\d+)", sf_id).group(1)) if sf_id else None
365
+ )
366
+ sev = cfg.get("severity", {})
367
+ default = "advisory_before_strict_from" if sf_id and gate != "consistency" else "always_strict"
368
+ s = sev.get(gate, default)
369
+ if s == "always_strict":
370
+ return "FAIL"
371
+ if s == "always_advisory":
372
+ return "ADVISORY"
373
+ if s == "advisory_before_strict_from":
374
+ return "ADVISORY" if (sf_num is None or adr_num < sf_num) else "FAIL"
375
+ return "FAIL"
376
+
377
+
378
+ def level_for(
379
+ gate: str,
380
+ adr_num: int,
381
+ cfg: Dict,
382
+ strict_from_override: Optional[str],
383
+ file_advisory: bool,
384
+ strict_mode: bool,
385
+ ) -> str:
386
+ """Resolve finding level for one gate."""
387
+ if strict_mode:
388
+ return "FAIL"
389
+ if file_advisory:
390
+ return "ADVISORY"
391
+ return severity_of(gate, adr_num, cfg, strict_from_override)
392
+
393
+
394
+ def parse_marker(text: str) -> Tuple[bool, bool, Set[str], Optional[str]]:
395
+ """Scan an ADR file body for the first adr-kit-lint marker.
396
+
397
+ Returns: (file_skipped, file_advisory, gate_skip_set, raw_directive_or_None).
398
+ """
399
+ for line in text.splitlines():
400
+ m = MARKER_RE.search(line)
401
+ if not m:
402
+ continue
403
+ directive = m.group(1).strip().lower()
404
+ if directive == "skip":
405
+ return True, False, set(), directive
406
+ if directive == "advisory":
407
+ return False, True, set(), directive
408
+ if directive.startswith("skip "):
409
+ gates = {g.strip() for g in directive[5:].split(",")}
410
+ unknown = gates - set(ALL_GATES)
411
+ if unknown:
412
+ # Treat unknown gate names as no-op rather than fail; warn caller.
413
+ gates = gates - unknown
414
+ return False, False, gates, directive
415
+ # Unknown directive: report so the user notices.
416
+ return False, False, set(), f"unknown directive: {directive!r}"
417
+ return False, False, set(), None
418
+
419
+
420
+ def discover_files(target: Path) -> List[Path]:
421
+ """Return ADR files under target. target may be a file or directory."""
422
+ if target.is_file():
423
+ return [target]
424
+ if not target.is_dir():
425
+ return []
426
+ seen = {}
427
+ for p in target.glob("*.md"):
428
+ if ADR_FILENAME_RE.match(p.name):
429
+ seen[p.name.lower()] = p
430
+ return sorted(seen.values(), key=lambda p: p.name.lower())
431
+
432
+
433
+ def _path_key(path: Path) -> str:
434
+ """Return a comparable identity for a file path.
435
+
436
+ Two Path objects can name the same file and still compare unequal: the
437
+ target handed in as `docs/adr/ADR-017-x.md` and the same file found by
438
+ walking a context directory differ by absoluteness, and on Windows by case.
439
+ Resolving and case-folding both is what keeps a file from counting twice.
440
+ """
441
+ try:
442
+ resolved = path.resolve()
443
+ except OSError: # pragma: no cover - unresolvable path (broken symlink)
444
+ resolved = Path(os.path.abspath(str(path)))
445
+ return os.path.normcase(str(resolved))
446
+
447
+
448
+ def merge_lookup_context(targets: List[Path], context: List[Path]) -> List[Path]:
449
+ """Return the targets plus every context ADR that is not already a target.
450
+
451
+ Deduplication is by resolved path, not by Path object. A context directory
452
+ normally contains the target file, and counting it twice would manufacture
453
+ a duplicate-ADR-number finding against the very ADR being linted.
454
+ """
455
+ seen = {_path_key(fp) for fp in targets}
456
+ merged = list(targets)
457
+ for fp in context:
458
+ key = _path_key(fp)
459
+ if key in seen:
460
+ continue
461
+ seen.add(key)
462
+ merged.append(fp)
463
+ return merged
464
+
465
+
466
+ def scan_extra_migration_notices(
467
+ target: Path,
468
+ linted_files: List[Path],
469
+ ) -> List[Dict]:
470
+ """Detect recognizable legacy Markdown that canonical lint discovery skips."""
471
+ if target.is_file() or not target.is_dir():
472
+ return []
473
+ linted = {path.resolve() for path in linted_files}
474
+ notices: List[Dict] = []
475
+ for path in sorted(target.glob("*.md"), key=lambda p: p.name.lower()):
476
+ if path.resolve() in linted:
477
+ continue
478
+ try:
479
+ text = path.read_text(encoding="utf-8", errors="replace")
480
+ except OSError:
481
+ continue
482
+ if not is_migration_candidate(path, text):
483
+ continue
484
+ _after, changed, issues = migrate_text(text, path)
485
+ notice = migration_notice(
486
+ text,
487
+ path,
488
+ metadata_changed=changed,
489
+ metadata_issues=issues,
490
+ migrate_command=str(Path(__file__).resolve().with_name("adr-migrate")),
491
+ )
492
+ if notice is not None:
493
+ notices.append(notice)
494
+ return notices
495
+
496
+
497
+ def gate_completeness(text: str, required: List[str]) -> Optional[List[str]]:
498
+ """Return list of missing required headings, or None if all present."""
499
+ missing = []
500
+ for s in required:
501
+ if not _section_pattern(s).search(text):
502
+ missing.append(s)
503
+ return missing or None
504
+
505
+
506
+ def _yaml_scalar(value: str) -> str:
507
+ value = value.strip()
508
+ if len(value) >= 2 and value[0] == value[-1] == '"':
509
+ try:
510
+ return str(json.loads(value))
511
+ except json.JSONDecodeError:
512
+ return value[1:-1]
513
+ if len(value) >= 2 and value[0] == value[-1] == "'":
514
+ return value[1:-1].replace("''", "'")
515
+ return value
516
+
517
+
518
+ def _status_history(text: str) -> Tuple[bool, List[Dict[str, str]]]:
519
+ entries: List[Dict[str, str]] = []
520
+ current: Optional[Dict[str, str]] = None
521
+ found = False
522
+ for line in text.splitlines():
523
+ stripped = line.strip()
524
+ if not found:
525
+ if STATUS_HISTORY_START_RE.match(line):
526
+ found = True
527
+ continue
528
+ if stripped.startswith("```") or stripped.startswith("## "):
529
+ break
530
+ if not stripped or stripped.startswith("#"):
531
+ continue
532
+ item = STATUS_HISTORY_ITEM_RE.match(line)
533
+ if item:
534
+ if current is not None:
535
+ entries.append(current)
536
+ current = {item.group(1).lower(): _yaml_scalar(item.group(2))}
537
+ continue
538
+ field = STATUS_HISTORY_FIELD_RE.match(line)
539
+ if field and current is not None:
540
+ current[field.group(1).lower()] = _yaml_scalar(field.group(2))
541
+ continue
542
+ if current is not None:
543
+ break
544
+ if current is not None:
545
+ entries.append(current)
546
+ return found, entries
547
+
548
+
549
+ def _current_status(text: str) -> Optional[str]:
550
+ return adr_status(text)
551
+
552
+
553
+ def gate_audit(text: str) -> Optional[List[str]]:
554
+ """Validate a present status_history chain; legacy ADRs remain valid."""
555
+ found, entries = _status_history(text)
556
+ if not found:
557
+ return None
558
+ if not entries:
559
+ return ["status_history is present but contains no transition entries"]
560
+ issues: List[str] = []
561
+ previous: Optional[date] = None
562
+ today = date.today()
563
+ for number, entry in enumerate(entries, start=1):
564
+ missing = [key for key in STATUS_HISTORY_REQUIRED_FIELDS if not entry.get(key)]
565
+ if missing:
566
+ issues.append(f"entry {number} missing fields: {', '.join(missing)}")
567
+ continue
568
+ try:
569
+ entry_date = date.fromisoformat(entry["date"])
570
+ except ValueError:
571
+ issues.append(f"entry {number} has invalid date: {entry['date']!r}")
572
+ continue
573
+ if entry_date > today:
574
+ issues.append(f"entry {number} has future date: {entry['date']}")
575
+ if previous is not None and entry_date < previous:
576
+ issues.append(f"entry {number} is earlier than its preceding entry")
577
+ previous = entry_date
578
+ current = _current_status(text)
579
+ if current:
580
+ last = re.match(r"\s*([A-Za-z]+)", entries[-1].get("status", ""))
581
+ if not last or current.lower() != last.group(1).lower():
582
+ issues.append(
583
+ "latest history status does not match the ADR Status section "
584
+ f"({entries[-1].get('status', '')!r} != {current!r})"
585
+ )
586
+ return issues or None
587
+
588
+
589
+ def gate_evidence(text: str) -> Optional[List[Tuple[int, str]]]:
590
+ """Heuristic: bare adjectives without nearby measurement / citation.
591
+
592
+ Returns hits (line, text) when 3+ are found. Threshold suppresses noise.
593
+ """
594
+ bare = re.compile(
595
+ r"\b(faster|slower|better|worse|improves|reduces|"
596
+ r"more reliable|more performant|much faster|much slower)\b",
597
+ re.IGNORECASE,
598
+ )
599
+ hits = []
600
+ lines = text.splitlines()
601
+ for i, ln in enumerate(lines):
602
+ if bare.search(ln):
603
+ window = "\n".join(lines[max(0, i - 2):i + 5])
604
+ if not re.search(
605
+ r"\d|http|RFC|spec|datasheet|measured|see\s+\w+:",
606
+ window, re.IGNORECASE,
607
+ ):
608
+ hits.append((i + 1, ln.strip()[:80]))
609
+ return hits if len(hits) >= 3 else None
610
+
611
+
612
+ # Acronyms that carry no explanatory value in an ADR: either universal
613
+ # technical vocabulary or terms this toolkit defines everywhere else. Demanding
614
+ # an inline expansion for these produces noise, not clarity.
615
+ CLARITY_ACRONYM_ALLOWLIST = frozenset({
616
+ # Ordinary technical vocabulary.
617
+ "ADR", "API", "CLI", "CPU", "CSV", "DNS", "GPU", "HTML", "HTTP", "HTTPS",
618
+ "IDE", "JSON", "LLM", "MADR", "MCP", "NFR", "PR", "REST", "RFC", "SDK",
619
+ "SQL", "SSH", "TASK", "TLS", "TOML", "URI", "URL", "UTC", "UUID", "XML",
620
+ "YAML",
621
+ # This kit's own verdict and status vocabulary. These are literal tokens a
622
+ # record quotes from output it is describing -- "the gate reports FAIL", "an
623
+ # [adr-guardian] ... DUE block" -- not abbreviations a reader needs
624
+ # expanded. Asking an author to write "FAIL (failure)" would make the record
625
+ # worse in order to satisfy a check.
626
+ "PASS", "FAIL", "SKIP", "WARN", "INFO", "NOTE", "DUE", "TODO",
627
+ })
628
+
629
+ # An acronym inside an identifier is not prose. `SKILL.md`, `ADR-INDEX.json` and
630
+ # `TODO(ADR-042)` all matched the bare word-boundary pattern, so the gate asked
631
+ # authors to expand a fragment of a filename.
632
+ _CLARITY_IDENTIFIER_CHARS = set("._-/\\")
633
+
634
+ # Inline code spans are blanked rather than removed, so reported line positions
635
+ # stay true to the source.
636
+ _CLARITY_CODE_SPAN_RE = re.compile(r"`[^`]*`")
637
+
638
+
639
+ def gate_clarity(text: str) -> Optional[List[Tuple[int, str]]]:
640
+ """Heuristic: ALL-CAPS acronyms (3 to 5 letters) without inline expansion.
641
+
642
+ Conservative: only flag when 3+ distinct acronyms appear without an
643
+ obvious expansion. Off by default; opt in with --gates.
644
+
645
+ An acronym counts as expanded when it is written either as
646
+ 'ACRONYM (expansion)' or as 'expansion (ACRONYM)'; both are normal
647
+ technical prose. Allowlisted acronyms and YAML frontmatter are ignored,
648
+ because frontmatter is metadata where an inline expansion cannot be
649
+ written at all.
650
+ """
651
+ acro_re = re.compile(r"\b[A-Z]{3,5}\b")
652
+ seen_with_expansion: Set[str] = set()
653
+ flagged: List[Tuple[int, str]] = []
654
+ in_fence = False
655
+ for i, ln in enumerate(_strip_frontmatter_lines(text)):
656
+ if ln is None: # frontmatter line: keeps numbering, skips analysis
657
+ continue
658
+ if ln.lstrip().startswith("```"):
659
+ in_fence = not in_fence
660
+ continue
661
+ if in_fence:
662
+ # A fenced block is code, output or configuration. An acronym there
663
+ # is a literal the record quotes, and it cannot carry an inline
664
+ # expansion without changing what it quotes.
665
+ continue
666
+ scannable = _CLARITY_CODE_SPAN_RE.sub(
667
+ lambda m: " " * len(m.group(0)), ln
668
+ )
669
+ for m in acro_re.finditer(scannable):
670
+ acro = m.group(0)
671
+ if acro in CLARITY_ACRONYM_ALLOWLIST:
672
+ continue
673
+ before = scannable[m.start() - 1] if m.start() else ""
674
+ after = scannable[m.end()] if m.end() < len(scannable) else ""
675
+ if (before in _CLARITY_IDENTIFIER_CHARS
676
+ or after in _CLARITY_IDENTIFIER_CHARS):
677
+ continue
678
+ # 'ACRONYM (expansion)' — a '(' immediately after the acronym.
679
+ tail = ln[m.end():m.end() + 100]
680
+ # 'expansion (ACRONYM)' — the acronym parenthesised after words.
681
+ head = ln[max(0, m.start() - 100):m.start()]
682
+ if re.match(r"\s*\(", tail) or re.search(r"\w\s+\($", head):
683
+ seen_with_expansion.add(acro)
684
+ continue
685
+ if acro in seen_with_expansion:
686
+ continue
687
+ flagged.append((i + 1, acro))
688
+ if len({a for _, a in flagged}) >= 3:
689
+ return flagged
690
+ return None
691
+
692
+
693
+ def _strip_frontmatter_lines(text: str) -> List[Optional[str]]:
694
+ """Return the lines of ``text`` with YAML frontmatter blanked to None.
695
+
696
+ Line positions are preserved so reported line numbers stay accurate.
697
+ """
698
+ lines: List[Optional[str]] = list(text.splitlines())
699
+ if not lines or lines[0].strip() != "---":
700
+ return lines
701
+ for i in range(1, len(lines)):
702
+ line = lines[i]
703
+ lines[i] = None
704
+ if line is not None and line.strip() == "---":
705
+ break
706
+ lines[0] = None
707
+ return lines
708
+
709
+
710
+ def _status_line(text: str) -> Optional[str]:
711
+ """Return the full status line (e.g. 'Superseded by ADR-099, 2026-05-01.')."""
712
+ m = STATUS_HEADING_RE.search(text)
713
+ if m:
714
+ return m.group(1).strip()
715
+ for rx in (STATUS_BOLD_INLINE_RE, STATUS_LINE_RE):
716
+ m = rx.search(text)
717
+ if m:
718
+ start = text.rfind("\n", 0, m.start()) + 1
719
+ end = text.find("\n", m.start())
720
+ return (text[start:] if end == -1 else text[start:end]).strip()
721
+ return None
722
+
723
+
724
+ def detect_reference_issues(
725
+ files: List[Path],
726
+ report_files: Optional[List[Path]] = None,
727
+ ) -> Dict[int, List[Dict[str, str]]]:
728
+ """Integrity of the *declared* `related` links, on both sides.
729
+
730
+ Supersession has an integrity check; a plain cross-reference had none, so an
731
+ ADR could name ADR-042 forever while ADR-042 never learned it was named, and
732
+ nothing noticed if ADR-042 turned out not to exist. `bin/adr relate` closed
733
+ the writing half by putting the link in frontmatter and writing both sides
734
+ in one transaction. This is the reading half.
735
+
736
+ **Only the `related` frontmatter field is gated, never the prose section**,
737
+ and that boundary is the whole design rather than a shortcut:
738
+
739
+ * Prose `## Related Decisions` is free-form. It legitimately names decisions
740
+ from another repository, ADRs not written yet, and ADRs outside whatever
741
+ subset is being linted. adr-lint routinely runs on a fragment -- `bin/adr
742
+ accept` lints exactly one file -- where every prose reference resolves to
743
+ nothing. A gate that fires there is reporting a fact about the invocation,
744
+ not about the code, which is the same reason the judge treats
745
+ `require_pattern` under `--snapshot diff` as advisory. ADR-009 forbids
746
+ exactly this kind of unactionable finding. `bin/adr-related` still lists
747
+ prose dangling links for a human who asks for them.
748
+ * `related` is machine-written. `bin/adr relate` resolves the target before
749
+ writing and writes both entries together, so a dangling or one-sided one
750
+ can only come from a hand edit or a half-applied write. That is the same
751
+ class of defect as a half supersession link, it is unambiguous, and it is
752
+ fixable on an Accepted record too, because frontmatter reference
753
+ bookkeeping is a permitted mutation where editing the body is not.
754
+
755
+ `files` is the lookup corpus; `report_files` narrows which of them may
756
+ produce a finding, matching detect_frontmatter_consistency so a single-file
757
+ lint still resolves references against the whole directory.
758
+
759
+ The known-set is built from filenames rather than parsed records on purpose:
760
+ a malformed ADR should be reported as malformed, not make every reference
761
+ pointing at it read as dangling.
762
+ """
763
+ known: Dict[int, Path] = {}
764
+ for path in files:
765
+ match = ADR_FILENAME_RE.match(path.name)
766
+ if match:
767
+ known.setdefault(int(match.group(1)), path)
768
+
769
+ declared_links: Dict[int, Set[int]] = {}
770
+ for num, path in known.items():
771
+ try:
772
+ text = path.read_text(encoding="utf-8", errors="replace")
773
+ except OSError:
774
+ continue
775
+ raw_frontmatter, _body = split_frontmatter(text)
776
+ try:
777
+ declared = parse_frontmatter(raw_frontmatter)
778
+ except FrontmatterError:
779
+ declared = {}
780
+ declared_links[num] = {
781
+ int(item.split("-")[1]) for item in _declared_related(declared)
782
+ } - {num}
783
+
784
+ wanted = (
785
+ {_path_key(fp) for fp in report_files} if report_files is not None else None
786
+ )
787
+ issues: Dict[int, List[Dict[str, str]]] = {}
788
+
789
+ def add(num: int, level: str, code: str, message: str) -> None:
790
+ if wanted is not None and _path_key(known[num]) not in wanted:
791
+ return
792
+ issues.setdefault(num, []).append(
793
+ {"level": level, "code": code, "message": message}
794
+ )
795
+
796
+ for num in sorted(declared_links):
797
+ for ref in sorted(declared_links[num]):
798
+ if ref not in known:
799
+ add(
800
+ num,
801
+ "FAIL",
802
+ "REFERENCE_DANGLING",
803
+ f"related lists ADR-{ref:03d}, which is not in this directory; "
804
+ f"run `adr relate ADR-{num:03d} --to ADR-{ref:03d} --remove` "
805
+ f"to drop it, or restore the missing ADR",
806
+ )
807
+ elif num not in declared_links.get(ref, set()):
808
+ add(
809
+ num,
810
+ "FAIL",
811
+ "REFERENCE_ONE_SIDED",
812
+ f"related lists ADR-{ref:03d}, but ADR-{ref:03d} does not list "
813
+ f"ADR-{num:03d} back; run `adr relate ADR-{num:03d} --to "
814
+ f"ADR-{ref:03d}` to write both sides, or --remove to drop it",
815
+ )
816
+ return issues
817
+
818
+
819
+ def _declared_related(declared: Dict) -> List[str]:
820
+ """The `related` frontmatter list, normalized, ignoring junk entries."""
821
+ values = declared.get("related")
822
+ if not isinstance(values, list):
823
+ return []
824
+ out: List[str] = []
825
+ for item in values:
826
+ match = re.fullmatch(r"ADR-(\d{1,4})", str(item).strip())
827
+ if match:
828
+ out.append(f"ADR-{int(match.group(1)):03d}")
829
+ return out
830
+
831
+
832
+ def detect_supersession_conflicts(files: List[Path]) -> Dict[int, List[str]]:
833
+ """Detect supersession-integrity problems for the consistency gate.
834
+
835
+ A claim is any 'Supersedes ADR-NNN' phrase in an Accepted ADR (self-claims
836
+ ignored). The target's Status line is the single source of truth and can
837
+ name at most ONE successor ('Superseded by ADR-X'). Two problems are FAILed:
838
+
839
+ - Concurrent supersession: 2+ Accepted ADRs claim the same target, so at
840
+ least one claim is dangling; every claimant FAILs with all files named.
841
+ - One-directional supersession: a single Accepted ADR claims a target that
842
+ exists but whose Status line does not name it back. The audit trail is
843
+ then one-way (the superseded ADR still reads as live), so the claimant
844
+ FAILs. A claim against a target absent from the directory is left to the
845
+ broken-reference detectors (bin/adr-retire) to avoid flagging prose
846
+ mentions of unknown ADR numbers.
847
+
848
+ A single clean, bidirectional supersession passes.
849
+
850
+ Returns: claimant adr_num -> list of issue strings for the consistency gate.
851
+ """
852
+ info: Dict[int, Tuple[str, str, str, Set[int]]] = {}
853
+ for fp in files:
854
+ m = ADR_FILENAME_RE.match(fp.name)
855
+ if not m:
856
+ continue
857
+ num = int(m.group(1))
858
+ try:
859
+ text = fp.read_text(encoding="utf-8", errors="replace")
860
+ except OSError:
861
+ continue
862
+ status = (_current_status(text) or "").lower()
863
+ sline = _status_line(text) or ""
864
+ claims = {int(c) for c in SUPERSEDES_CLAIM_RE.findall(text) if int(c) != num}
865
+ # First file wins on duplicate numbers; duplicates are flagged separately.
866
+ info.setdefault(num, (fp.name, status, sline, claims))
867
+
868
+ by_target: Dict[int, List[Tuple[int, str]]] = {}
869
+ for num, (name, status, _sline, claims) in info.items():
870
+ if status != "accepted":
871
+ continue
872
+ for target in claims:
873
+ by_target.setdefault(target, []).append((num, name))
874
+
875
+ issues: Dict[int, List[str]] = {}
876
+ for target, claimants in by_target.items():
877
+ target_info = info.get(target)
878
+ successor: Optional[int] = None
879
+ if target_info:
880
+ sm = SUPERSEDED_BY_RE.search(target_info[2])
881
+ if sm:
882
+ successor = int(sm.group(1))
883
+
884
+ if len(claimants) >= 2:
885
+ names = sorted(name for _, name in claimants)
886
+ if successor is not None:
887
+ agreement = f"target Status names ADR-{successor:03d} as successor"
888
+ elif target_info is None:
889
+ agreement = f"ADR-{target:03d} not found in this directory"
890
+ else:
891
+ agreement = "target Status does not name a successor"
892
+ msg = (
893
+ f"concurrent supersession of ADR-{target:03d}: claimed by multiple "
894
+ f"Accepted ADRs ({', '.join(names)}); {agreement}. A target can have "
895
+ f"exactly one successor."
896
+ )
897
+ for num, _name in claimants:
898
+ issues.setdefault(num, []).append(msg)
899
+ continue
900
+
901
+ # Single Accepted claimant: the supersession must be bidirectional.
902
+ # A target absent from the directory is left to the broken-reference
903
+ # detectors (bin/adr-retire); flagging it here would trip on prose
904
+ # mentions of unknown ADR numbers.
905
+ if target_info is None:
906
+ continue
907
+ num, _name = claimants[0]
908
+ if successor != num:
909
+ detail = (
910
+ f"ADR-{target:03d} Status names ADR-{successor:03d}"
911
+ if successor is not None
912
+ else f"ADR-{target:03d} Status names no successor"
913
+ )
914
+ issues.setdefault(num, []).append(
915
+ f"one-directional supersession of ADR-{target:03d}: ADR-{num:03d} "
916
+ f"claims to supersede it, but {detail}. The superseded ADR's Status "
917
+ f"line must read 'Superseded by ADR-{num:03d}' so the audit trail is "
918
+ f"bidirectional."
919
+ )
920
+ return issues
921
+
922
+
923
+ def _frontmatter_records(files: List[Path]) -> Dict[str, Dict]:
924
+ """Return valid frontmatter records keyed by ADR id."""
925
+ records: Dict[str, Dict] = {}
926
+ for fp in files:
927
+ m = ADR_FILENAME_RE.match(fp.name)
928
+ if not m:
929
+ continue
930
+ try:
931
+ text = fp.read_text(encoding="utf-8", errors="replace")
932
+ except OSError:
933
+ continue
934
+ raw_frontmatter, body = split_frontmatter(text)
935
+ if raw_frontmatter is None:
936
+ continue
937
+ try:
938
+ data = parse_frontmatter(raw_frontmatter)
939
+ except FrontmatterError:
940
+ continue
941
+ if validate_frontmatter(data):
942
+ continue
943
+ adr_id = data["id"]
944
+ records[adr_id] = {
945
+ "adr_num": int(m.group(1)),
946
+ "file": fp,
947
+ "body": body,
948
+ "data": data,
949
+ }
950
+ return records
951
+
952
+
953
+ def _verified_pointer_resolves(pointer: str, repo_root: Path) -> bool:
954
+ """Resolve local evidence pointers: path, path:symbol, or commit:<sha>."""
955
+ if pointer.startswith("commit:"):
956
+ commit = pointer.split(":", 1)[1].strip()
957
+ if not commit:
958
+ return False
959
+ try:
960
+ result = subprocess.run(
961
+ ["git", "-C", str(repo_root), "cat-file", "-e", f"{commit}^{{commit}}"],
962
+ capture_output=True,
963
+ text=True,
964
+ timeout=5,
965
+ )
966
+ except (OSError, subprocess.TimeoutExpired):
967
+ return False
968
+ return result.returncode == 0
969
+
970
+ path_part = pointer
971
+ symbol = None
972
+ if ":" in pointer and not re.match(r"^[A-Za-z]:[\\/]", pointer):
973
+ path_part, symbol = pointer.split(":", 1)
974
+ symbol = symbol.strip() or None
975
+ path = (repo_root / path_part).resolve()
976
+ if not path.exists() or not path.is_file():
977
+ return False
978
+ if symbol is None:
979
+ return True
980
+ try:
981
+ return symbol in path.read_text(encoding="utf-8", errors="ignore")
982
+ except OSError:
983
+ return False
984
+
985
+
986
+ def _iter_gate_scan_files(repo_root: Path):
987
+ count = 0
988
+ for dirpath, dirnames, filenames in os.walk(repo_root, followlinks=False):
989
+ dirnames[:] = [
990
+ d for d in dirnames
991
+ if d not in TEXT_SCAN_SKIP_DIRS and d.lower() not in TEXT_SCAN_SKIP_DIRS
992
+ ]
993
+ # Never descend into a nested checkout (git worktree, vendored clone):
994
+ # its files belong to another tree, not to this project's source.
995
+ dirnames[:] = [
996
+ d for d in dirnames if not (Path(dirpath) / d / ".git").exists()
997
+ ]
998
+ current = Path(dirpath)
999
+ try:
1000
+ rel_first = current.relative_to(repo_root).parts[:1]
1001
+ except ValueError:
1002
+ rel_first = ()
1003
+ preferred_dir = bool(rel_first and rel_first[0] in TEXT_SCAN_DIRS)
1004
+ for fname in filenames:
1005
+ path = current / fname
1006
+ if fname == "evaluate.py" or preferred_dir or path.suffix.lower() in TEXT_SCAN_SUFFIXES:
1007
+ yield path
1008
+ count += 1
1009
+ if count >= 5000:
1010
+ return
1011
+
1012
+
1013
+ def _resolve_gates_locally(gates: Iterable[str], repo_root: Path) -> Set[str]:
1014
+ """Return the subset of `gates` that appear somewhere under repo_root.
1015
+
1016
+ One pass over the scan set regardless of how many gates are checked. The
1017
+ previous per-gate helper re-walked and re-read the whole tree for every
1018
+ gate, making lint runtime O(gates x files).
1019
+ """
1020
+ pending = {g.strip() for g in gates if g and g.strip()}
1021
+ found: Set[str] = set()
1022
+ if not pending:
1023
+ return found
1024
+ for path in _iter_gate_scan_files(repo_root):
1025
+ try:
1026
+ text = path.read_text(encoding="utf-8", errors="ignore")
1027
+ except OSError:
1028
+ continue
1029
+ hits = {needle for needle in pending if needle in text}
1030
+ if hits:
1031
+ found |= hits
1032
+ pending -= hits
1033
+ if not pending:
1034
+ break
1035
+ return found
1036
+
1037
+
1038
+ def _gate_exists_locally(gate: str, repo_root: Path) -> bool:
1039
+ """Single-gate convenience wrapper (kept for direct callers and tests)."""
1040
+ needle = gate.strip()
1041
+ if not needle:
1042
+ return False
1043
+ return needle in _resolve_gates_locally([needle], repo_root)
1044
+
1045
+
1046
+ def detect_frontmatter_consistency(
1047
+ files: List[Path],
1048
+ repo_root: Path,
1049
+ report_files: Optional[List[Path]] = None,
1050
+ ) -> Dict[int, List[str]]:
1051
+ """Detect cross-file and consuming-repo frontmatter consistency issues.
1052
+
1053
+ `files` is the lookup corpus: any record in it can be resolved as the
1054
+ target of a `supersedes` or `superseded_by` reference. `report_files`, when
1055
+ given, narrows which of those records may *produce* a finding, so a caller
1056
+ can hand in a whole directory as context and still get a verdict about one
1057
+ ADR alone. `bin/adr accept` needs exactly that split: without the corpus
1058
+ every cross-reference resolved to nothing and reported "target not found"
1059
+ (TASK-67), and without the narrowing an unrelated ADR elsewhere in the
1060
+ directory would block an unrelated acceptance.
1061
+ """
1062
+ records = _frontmatter_records(files)
1063
+ reported = records
1064
+ if report_files is not None:
1065
+ wanted = {_path_key(fp) for fp in report_files}
1066
+ reported = {
1067
+ adr_id: record
1068
+ for adr_id, record in records.items()
1069
+ if _path_key(record["file"]) in wanted
1070
+ }
1071
+ issues: Dict[int, List[str]] = {}
1072
+
1073
+ def add(record: Dict, message: str) -> None:
1074
+ issues.setdefault(record["adr_num"], []).append(message)
1075
+
1076
+ # Gate presence is a property of one record, not a cross-reference, so it
1077
+ # is asked only of the records that may report. Resolve every named gate in
1078
+ # a single pass over the tree instead of re-scanning once per gate.
1079
+ _wanted_gates = {
1080
+ str(record["data"].get("gate")).strip()
1081
+ for record in reported.values()
1082
+ if record["data"].get("status") == "Accepted"
1083
+ and record["data"].get("binding") is True
1084
+ and record["data"].get("gate")
1085
+ }
1086
+ present_gates = _resolve_gates_locally(_wanted_gates, repo_root)
1087
+
1088
+ for adr_id, record in reported.items():
1089
+ data = record["data"]
1090
+ body_status = _current_status(record["body"])
1091
+ if body_status and body_status.capitalize() != data["status"]:
1092
+ add(
1093
+ record,
1094
+ f"frontmatter status {data['status']!r} does not match "
1095
+ f"Status section {body_status!r}",
1096
+ )
1097
+
1098
+ superseded_by = data.get("superseded_by")
1099
+ if data["status"] == "Superseded" and not superseded_by:
1100
+ add(record, "status Superseded requires superseded_by")
1101
+ if data["status"] != "Superseded" and superseded_by:
1102
+ add(record, "superseded_by is only valid when status is Superseded")
1103
+
1104
+ for target_id in data.get("supersedes", []):
1105
+ target = records.get(target_id)
1106
+ if target is None:
1107
+ add(record, f"supersedes target {target_id} not found")
1108
+ continue
1109
+ if target["data"].get("superseded_by") != adr_id:
1110
+ add(
1111
+ record,
1112
+ f"supersedes {target_id} but {target_id}.superseded_by "
1113
+ f"is not {adr_id}",
1114
+ )
1115
+
1116
+ if superseded_by:
1117
+ successor = records.get(superseded_by)
1118
+ if successor is None:
1119
+ add(record, f"superseded_by target {superseded_by} not found")
1120
+ elif adr_id not in successor["data"].get("supersedes", []):
1121
+ add(
1122
+ record,
1123
+ f"superseded_by {superseded_by} but {superseded_by}.supersedes "
1124
+ f"does not include {adr_id}",
1125
+ )
1126
+
1127
+ for pointer in data.get("verified_in", []):
1128
+ if not _verified_pointer_resolves(pointer, repo_root):
1129
+ add(record, f"verified_in pointer does not resolve: {pointer}")
1130
+
1131
+ if data.get("documents_shipped") and not data.get("verified_in"):
1132
+ add(record, "documents_shipped requires at least one verified_in pointer")
1133
+
1134
+ if (
1135
+ data["status"] == "Accepted"
1136
+ and data.get("binding") is True
1137
+ ):
1138
+ gate = data.get("gate")
1139
+ if not gate:
1140
+ add(record, "Accepted binding ADR requires a named gate")
1141
+ elif str(gate).strip() not in present_gates:
1142
+ add(record, f"gate {gate!r} was not found under {repo_root}")
1143
+
1144
+ return issues
1145
+
1146
+
1147
+ def gate_consistency(
1148
+ fp: Path, adr_num: int, text: str, duplicates: Dict[int, List[str]],
1149
+ supersession_issues: Optional[List[str]] = None,
1150
+ ) -> Optional[List[str]]:
1151
+ """Filename pattern, heading match, duplicate numbers, etc."""
1152
+ issues = []
1153
+ if supersession_issues:
1154
+ issues.extend(supersession_issues)
1155
+ first_heading = next(
1156
+ (l.strip() for l in text.splitlines() if l.strip().startswith("# ")),
1157
+ "",
1158
+ )
1159
+ m = HEADING_NUMBER_RE.match(first_heading)
1160
+ if not m:
1161
+ issues.append(f"first heading {first_heading!r} does not match # ADR-NNN")
1162
+ elif int(m.group(1)) != adr_num:
1163
+ issues.append(
1164
+ f"heading number {m.group(1)} != filename {adr_num:03d}"
1165
+ )
1166
+ if not CANONICAL_FILENAME_RE.match(fp.name):
1167
+ issues.append(f"filename {fp.name} does not match ADR-NNN-kebab.md")
1168
+ if adr_num in duplicates:
1169
+ issues.append(
1170
+ f"duplicate ADR-{adr_num:03d}: number is shared by "
1171
+ f"{', '.join(duplicates[adr_num])}; "
1172
+ f"run bin/adr-renumber to move one to a free number"
1173
+ )
1174
+ return issues or None
1175
+
1176
+
1177
+ def _section_text(text: str, heading: str) -> str:
1178
+ """Extract text of a markdown section (up to the next ## heading or EOF)."""
1179
+ role_by_heading = {
1180
+ "## Status": "status",
1181
+ "## Context": "context",
1182
+ "## Decision": "decision",
1183
+ "## Alternatives Considered": "alternatives",
1184
+ "## Consequences": "consequences",
1185
+ "## Related Decisions": "related",
1186
+ "## References": "references",
1187
+ "## Enforcement": "enforcement",
1188
+ }
1189
+ role = role_by_heading.get(heading)
1190
+ if role:
1191
+ return section_text(text, role)
1192
+ m = re.search(
1193
+ rf"^{re.escape(heading)}\s*$\n(.*?)(?=\n##\s+|\Z)",
1194
+ text, re.MULTILINE | re.DOTALL,
1195
+ )
1196
+ return m.group(1) if m else ""
1197
+
1198
+
1199
+ def _extract_enforcement_block(content: str) -> Tuple[Optional[Dict], Optional[str]]:
1200
+ """Parse the ## Enforcement JSON block.
1201
+
1202
+ Returns:
1203
+ (dict, None) — parsed successfully
1204
+ (None, None) — section absent (skip silently)
1205
+ (None, msg) — section present but JSON is malformed or invalid
1206
+ """
1207
+ m = ENFORCEMENT_BLOCK_RE.search(content)
1208
+ if not m:
1209
+ return None, None
1210
+ raw = m.group(1)
1211
+ try:
1212
+ data = json.loads(raw)
1213
+ except json.JSONDecodeError as e:
1214
+ return None, f"malformed JSON in ## Enforcement block ({e.msg} at line {e.lineno})"
1215
+ if not isinstance(data, dict):
1216
+ return None, f"## Enforcement JSON must be an object, got {type(data).__name__}"
1217
+ # Manual additionalProperties check (works without jsonschema installed).
1218
+ unknown_keys = set(data.keys()) - ENFORCEMENT_KNOWN_KEYS
1219
+ if unknown_keys:
1220
+ return None, f"## Enforcement block has unknown key(s): {sorted(unknown_keys)}"
1221
+ for key in ENFORCEMENT_ARRAY_KEYS:
1222
+ if key in data and not isinstance(data[key], list):
1223
+ return None, f"Enforcement.{key} must be an array"
1224
+ if "llm_judge" in data and not isinstance(data["llm_judge"], bool):
1225
+ return None, "Enforcement.llm_judge must be a boolean"
1226
+ return data, None
1227
+
1228
+
1229
+ def check_open_questions_append_only(
1230
+ path: Path, text: str, status: str
1231
+ ) -> List[Dict]:
1232
+ """A question may go from open to answered, and nowhere else (ADR-022).
1233
+
1234
+ Every consumer of this data checks only *unresolved* items, so deleting a
1235
+ question raises the quality score and clears the acceptance gate exactly as
1236
+ answering it does -- while `bin/adr answer` is the strictly more expensive
1237
+ path. The cheapest route through the gates destroyed the record of the
1238
+ grilling. Nobody has to act in bad faith for that to happen; it is what the
1239
+ incentive rewarded.
1240
+
1241
+ The check needs the previous revision, so it needs git. Outside a repository,
1242
+ or on a file with no history, it degrades to ADVISORY and says so rather than
1243
+ passing silently -- a hole named is worth more than a check that pretends.
1244
+ """
1245
+ if status != "Proposed":
1246
+ return []
1247
+
1248
+ previous = _previous_revision(path)
1249
+ if previous is None:
1250
+ return [{
1251
+ "code": "open-questions-unverifiable",
1252
+ "severity": "ADVISORY",
1253
+ "message": (
1254
+ f"{path.name}: cannot check the append-only rule for Open "
1255
+ "Questions without git history for this file. The rule still "
1256
+ "applies; nothing verified it here."
1257
+ ),
1258
+ }]
1259
+
1260
+ before = all_open_questions(previous)
1261
+ if not before:
1262
+ return []
1263
+ after = all_open_questions(text)
1264
+
1265
+ vanished = [question for question in before if question not in after]
1266
+ if not vanished:
1267
+ return []
1268
+ return [{
1269
+ "code": "open-questions-deleted",
1270
+ "severity": "FAIL",
1271
+ "message": (
1272
+ f"{path.name}: {len(vanished)} Open Question(s) disappeared without "
1273
+ "an answer: "
1274
+ + "; ".join(f'"{question}"' for question in sorted(vanished))
1275
+ + ". Answer it with `bin/adr answer` -- the reasoning is what a "
1276
+ "future reader needs in order to re-evaluate the decision."
1277
+ ),
1278
+ }]
1279
+
1280
+
1281
+ def _previous_revision(path: Path) -> Optional[str]:
1282
+ """The committed content of this file, or None when git cannot say.
1283
+
1284
+ None covers every case the check cannot see through: no git on PATH, not a
1285
+ repository, a file that has never been committed. They are one outcome here
1286
+ because the remedy is the same -- say the rule was not verified.
1287
+ """
1288
+ if shutil.which("git") is None:
1289
+ return None
1290
+ try:
1291
+ result = subprocess.run(
1292
+ ["git", "show", f"HEAD:./{path.name}"],
1293
+ cwd=str(path.parent),
1294
+ capture_output=True,
1295
+ text=True,
1296
+ encoding="utf-8",
1297
+ errors="replace",
1298
+ timeout=10,
1299
+ )
1300
+ except (OSError, subprocess.SubprocessError):
1301
+ return None
1302
+ if result.returncode != 0:
1303
+ return None
1304
+ return result.stdout
1305
+
1306
+
1307
+ def check_policy_gate(content: str, adr_id: str) -> List[Dict]:
1308
+ """Validate the ## Enforcement JSON block in an ADR.
1309
+
1310
+ Returns list of finding dicts:
1311
+ {
1312
+ "gate": "policy",
1313
+ "severity": "FAIL" | "ADVISORY",
1314
+ "code": "POLICY_xxx",
1315
+ "message": str,
1316
+ }
1317
+ """
1318
+ data, err = _extract_enforcement_block(content)
1319
+ if err is not None:
1320
+ # Schema / JSON error — FAIL. The probing `import jsonschema` that used
1321
+ # to sit here assigned the same code on both branches, so it decided
1322
+ # nothing; its only remaining effect was executing whatever module the
1323
+ # name resolved to (TASK-62). Dropped, behaviour unchanged.
1324
+ code = "POLICY_SCHEMA_INVALID"
1325
+ return [{"gate": "policy", "severity": "FAIL", "code": code, "message": err}]
1326
+ if data is None:
1327
+ # No enforcement block — skip silently.
1328
+ return []
1329
+
1330
+ findings: List[Dict] = []
1331
+
1332
+ # Optional: deeper schema validation when jsonschema is available.
1333
+ validator = _get_enforcement_validator()
1334
+ if validator is not None:
1335
+ try:
1336
+ validator.validate(data)
1337
+ except Exception as ve:
1338
+ findings.append({
1339
+ "gate": "policy",
1340
+ "severity": "FAIL",
1341
+ "code": "POLICY_SCHEMA_INVALID",
1342
+ "message": f"schema validation failed: {getattr(ve, 'message', str(ve))}",
1343
+ })
1344
+ return findings
1345
+
1346
+ # Regex compilation checks across all pattern-bearing keys.
1347
+ for key in ("forbid_pattern", "forbid_import", "require_pattern"):
1348
+ for i, rule in enumerate(data.get(key, [])):
1349
+ pat = rule.get("pattern", "")
1350
+ try:
1351
+ re.compile(pat)
1352
+ except re.error as exc:
1353
+ findings.append({
1354
+ "gate": "policy",
1355
+ "severity": "FAIL",
1356
+ "code": "POLICY_BAD_REGEX",
1357
+ "message": (
1358
+ f"{key}[{i}].pattern {pat!r} is not a valid regex: {exc}"
1359
+ ),
1360
+ })
1361
+
1362
+ # Anti-pattern advisories.
1363
+ for key in ("forbid_pattern", "forbid_import", "require_pattern"):
1364
+ for i, rule in enumerate(data.get(key, [])):
1365
+ pat = rule.get("pattern", "")
1366
+ # Excessive wildcard: three or more consecutive .* occurrences.
1367
+ if ".*.*.*" in pat:
1368
+ findings.append({
1369
+ "gate": "policy",
1370
+ "severity": "ADVISORY",
1371
+ "code": "POLICY_EXCESSIVE_WILDCARD",
1372
+ "message": (
1373
+ f"{key}[{i}].pattern {pat!r} contains excessive wildcards "
1374
+ f"(three or more consecutive .*); this matches almost everything"
1375
+ ),
1376
+ })
1377
+ # Broad glob: path_glob absent or is pure ** / **/* without further scoping.
1378
+ path_glob = rule.get("path_glob", "")
1379
+ if not path_glob or path_glob in ("**", "**/*"):
1380
+ findings.append({
1381
+ "gate": "policy",
1382
+ "severity": "ADVISORY",
1383
+ "code": "POLICY_BROAD_GLOB",
1384
+ "message": (
1385
+ f"{key}[{i}] has no path_glob or a very broad glob {path_glob!r}; "
1386
+ f"consider scoping to a specific directory or extension"
1387
+ ),
1388
+ })
1389
+
1390
+ return findings
1391
+
1392
+
1393
+ def count_alternatives(content: str) -> Optional[int]:
1394
+ """How many options the record weighed, or None when the section is absent.
1395
+
1396
+ Format-aware through `_section_text`, which maps the heading to the semantic
1397
+ role: MADR writes `## Considered Options` and Nygard writes
1398
+ `## Alternatives Considered`, and both have to be counted or the check would
1399
+ silently skip whichever profile it was not written against.
1400
+
1401
+ A missing section is None rather than 0, because that is the completeness
1402
+ gate's own finding to report -- two findings for one cause would tell the
1403
+ author to fix the same thing twice.
1404
+ """
1405
+ text = _section_text(content, "## Alternatives Considered")
1406
+ if not text:
1407
+ return None
1408
+ # Migration writes a placeholder when the source record listed nothing, and
1409
+ # it deliberately never fabricates alternatives. There are two spellings:
1410
+ # `/adr-kit:migrate`'s skill emits an HTML comment, `bin/adr-migrate` emits
1411
+ # a `- TODO:` list item. Both mean "unknown, fill this in".
1412
+ #
1413
+ # Counting either as a real option would turn every honest import into a
1414
+ # blocking failure and push a migrating team to disable the gate -- the
1415
+ # outcome spec R15 exists to prevent. The placeholder already tells the
1416
+ # author what to do; a section holding only placeholders is treated as
1417
+ # absent, which is the completeness gate's own finding to report.
1418
+ stripped = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL)
1419
+ real_items = [
1420
+ item for item in re.findall(r"^\s*[-*]\s+(\S.*)$", stripped, re.MULTILINE)
1421
+ if not item.lstrip().upper().startswith("TODO")
1422
+ ]
1423
+ heading_items = re.findall(r"^###\s+\S", stripped, re.MULTILINE)
1424
+ if not real_items and not heading_items:
1425
+ return None
1426
+ return len(real_items) + len(heading_items)
1427
+
1428
+
1429
+ def check_quality_gate(content: str, adr_id: str) -> List[Dict]:
1430
+ """Advisory quality checks. For comprehensive scoring, use bin/adr-quality (which runs 4 weighted gates with letter grades)."""
1431
+ findings: List[Dict] = []
1432
+
1433
+ # Unified vague-words set; identical to bin/adr-quality's VAGUE_WORDS_RE.
1434
+ vague_words = re.compile(
1435
+ r"\b(appropriate|somehow|maybe|possibly|might|could|"
1436
+ r"should\s+consider|might\s+consider)\b",
1437
+ re.IGNORECASE,
1438
+ )
1439
+ decision_text = _section_text(content, "## Decision")
1440
+ if vague_words.search(decision_text):
1441
+ findings.append({
1442
+ "gate": "quality",
1443
+ "severity": "ADVISORY",
1444
+ "code": "QUALITY_VAGUE_LANGUAGE",
1445
+ "message": (
1446
+ "## Decision section contains vague language "
1447
+ "(appropriate / somehow / maybe / possibly / might / could / "
1448
+ "should consider / might consider); "
1449
+ "prefer concrete, measurable statements"
1450
+ ),
1451
+ })
1452
+
1453
+ consequences_text = _section_text(content, "## Consequences")
1454
+ if consequences_text and not re.search(r"\d|%", consequences_text):
1455
+ findings.append({
1456
+ "gate": "quality",
1457
+ "severity": "ADVISORY",
1458
+ "code": "QUALITY_NO_METRICS",
1459
+ "message": (
1460
+ "## Consequences section contains no numbers or percentages; "
1461
+ "consider quantifying the impact"
1462
+ ),
1463
+ })
1464
+
1465
+ # The alternatives count moved to the completeness gate as a FAIL. R0 is not
1466
+ # a suggestion: a record that states only the outcome cannot be re-evaluated,
1467
+ # and a decision that cannot be re-evaluated cannot be superseded honestly.
1468
+ # Leaving it here as an advisory meant a one-option record passed every
1469
+ # blocking gate. See count_alternatives and COMPLETENESS_FEW_ALTERNATIVES.
1470
+
1471
+ return findings
1472
+
1473
+
1474
+ def check_retrieval_metadata(content: str, cfg: Dict) -> Optional[Dict]:
1475
+ """Find Accepted ADRs an agent's query will not surface.
1476
+
1477
+ `binding: true` used to be a precondition, and it made the check almost
1478
+ inert. Measured on this repository: all 12 records with no retrieval
1479
+ metadata escaped through that one condition, every one of them
1480
+ `binding: false`. Being non-binding means a decision does not gate code; it
1481
+ does not mean the decision should be invisible. An Accepted ADR nobody can
1482
+ retrieve is a decision that will be re-made, which is the failure R0 names.
1483
+
1484
+ The other exits stay, because each says the record is findable by some other
1485
+ route: `context_scope: global` is injected regardless of the query, and a
1486
+ populated Decision Contract gives the ranker text to match on.
1487
+ """
1488
+ mode = cfg.get("context", {}).get("retrieval_completeness", "advisory")
1489
+ if mode == "off":
1490
+ return None
1491
+ raw, _body = split_frontmatter(content)
1492
+ if raw is None:
1493
+ return None
1494
+ try:
1495
+ data = parse_frontmatter(raw)
1496
+ except FrontmatterError:
1497
+ return None
1498
+ if data.get("status") != "Accepted":
1499
+ return None
1500
+ if data.get("context_scope") == "global":
1501
+ return None
1502
+ if any(data.get(field) for field in ("topics", "aliases", "components", "symbols")):
1503
+ return None
1504
+ contract = re.search(
1505
+ r"^##\s+Decision Contract\s*$([\s\S]*?)(?=^##\s+|\Z)",
1506
+ content,
1507
+ re.IGNORECASE | re.MULTILINE,
1508
+ )
1509
+ if contract and re.search(
1510
+ r"^\s*[-*]\s+(?!None\.?\s*$)\S",
1511
+ contract.group(1),
1512
+ re.MULTILINE,
1513
+ ):
1514
+ return None
1515
+ return {
1516
+ "gate": "completeness",
1517
+ "level": "FAIL" if mode == "strict" else "ADVISORY",
1518
+ "code": "SELECTIVE_CONTEXT_METADATA",
1519
+ "details": [
1520
+ "Add topics, aliases, components, symbols, a Decision Contract, "
1521
+ "or explicitly mark context_scope: global"
1522
+ ],
1523
+ "summary": (
1524
+ "Accepted ADR has no retrieval metadata, so a query will not "
1525
+ "surface it; add topics, aliases, components, symbols, a Decision "
1526
+ "Contract, or explicitly mark context_scope: global"
1527
+ ),
1528
+ }
1529
+
1530
+
1531
+ def lint_file(
1532
+ fp: Path,
1533
+ cfg: Dict,
1534
+ strict_from_override: Optional[str],
1535
+ enabled_gates: Set[str],
1536
+ duplicates: Dict[int, List[str]],
1537
+ required_sections: Optional[List[str]],
1538
+ ignore: Set[str],
1539
+ supersession: Optional[Dict[int, List[str]]] = None,
1540
+ frontmatter_consistency: Optional[Dict[int, List[str]]] = None,
1541
+ strict_mode: bool = False,
1542
+ reference_issues: Optional[Dict[int, List[Dict[str, str]]]] = None,
1543
+ ) -> Dict:
1544
+ """Lint one file. Returns a dict ready for JSON serialisation."""
1545
+ m = ADR_FILENAME_RE.match(fp.name)
1546
+ adr_num = int(m.group(1)) if m else -1
1547
+ adr_id = f"ADR-{adr_num:03d}"
1548
+
1549
+ if adr_id in ignore or fp.name in ignore:
1550
+ return {"file": fp.name, "adr_num": adr_num, "bucket": "SKIPPED",
1551
+ "skip_reason": "config.ignore", "findings": []}
1552
+
1553
+ text = fp.read_text(encoding="utf-8", errors="replace")
1554
+ file_skipped, file_advisory, skip_gates, _ = parse_marker(text)
1555
+ if file_skipped:
1556
+ return {"file": fp.name, "adr_num": adr_num, "bucket": "SKIPPED",
1557
+ "skip_reason": "marker", "findings": []}
1558
+
1559
+ findings = []
1560
+ profile = detect_profile(text)
1561
+ _migrated, metadata_changed, metadata_issues = migrate_text(text, fp)
1562
+ migration = migration_notice(
1563
+ text,
1564
+ fp,
1565
+ metadata_changed=metadata_changed,
1566
+ metadata_issues=metadata_issues,
1567
+ migrate_command=str(Path(__file__).resolve().with_name("adr-migrate")),
1568
+ )
1569
+
1570
+ if "schema" in enabled_gates and "schema" not in skip_gates:
1571
+ raw_frontmatter, _body = split_frontmatter(text)
1572
+ schema_issues: List[str] = []
1573
+ if raw_frontmatter is None:
1574
+ schema_issues.append(
1575
+ "missing canonical frontmatter; run bin/adr-migrate"
1576
+ )
1577
+ else:
1578
+ try:
1579
+ schema_issues.extend(validate_frontmatter(parse_frontmatter(raw_frontmatter)))
1580
+ except FrontmatterError as exc:
1581
+ schema_issues.append(str(exc))
1582
+ if schema_issues:
1583
+ level = level_for(
1584
+ "schema", adr_num, cfg, strict_from_override,
1585
+ file_advisory, strict_mode,
1586
+ )
1587
+ findings.append({
1588
+ "gate": "schema",
1589
+ "level": level,
1590
+ "details": schema_issues,
1591
+ "summary": "; ".join(schema_issues),
1592
+ })
1593
+
1594
+ if "completeness" in enabled_gates and "completeness" not in skip_gates:
1595
+ if required_sections is None and profile not in SUPPORTED_PROFILES:
1596
+ level = level_for(
1597
+ "completeness", adr_num, cfg, strict_from_override,
1598
+ file_advisory, strict_mode,
1599
+ )
1600
+ findings.append({
1601
+ "gate": "completeness",
1602
+ "level": level,
1603
+ "details": [f"format={profile}"],
1604
+ "summary": (
1605
+ (
1606
+ f"ADR body format is {profile}. "
1607
+ + migration["message"]
1608
+ + (
1609
+ f" Next: {migration['guided_command']}"
1610
+ if migration and migration.get("guided_command")
1611
+ else ""
1612
+ )
1613
+ )
1614
+ if migration
1615
+ else (
1616
+ f"ADR body format is {profile}; add frontmatter "
1617
+ f"format: {' | '.join(SUPPORTED_PROFILES)} or migrate it"
1618
+ )
1619
+ ),
1620
+ })
1621
+ effective_required: List[str] = []
1622
+ else:
1623
+ effective_required = (
1624
+ required_sections
1625
+ if required_sections is not None
1626
+ else required_headings(profile)
1627
+ )
1628
+ miss = gate_completeness(text, effective_required)
1629
+ if miss:
1630
+ level = level_for(
1631
+ "completeness", adr_num, cfg, strict_from_override,
1632
+ file_advisory, strict_mode,
1633
+ )
1634
+ findings.append({
1635
+ "gate": "completeness", "level": level,
1636
+ "details": [s.replace("## ", "") for s in miss],
1637
+ "summary": f"missing sections: {[s.replace('## ', '') for s in miss]}",
1638
+ })
1639
+ alternatives = count_alternatives(text)
1640
+ if alternatives is not None and alternatives < 2:
1641
+ # R0's guarantee, enforced rather than suggested. A record that
1642
+ # states only the outcome cannot be re-evaluated later, and a
1643
+ # decision that cannot be re-evaluated cannot be superseded
1644
+ # honestly -- which is the whole mechanism this kit rests on.
1645
+ # Satisfiable by editing the record, per spec R15: name the option
1646
+ # that lost, and "do nothing" is always one.
1647
+ level = level_for(
1648
+ "completeness", adr_num, cfg, strict_from_override,
1649
+ file_advisory, strict_mode,
1650
+ )
1651
+ findings.append({
1652
+ "gate": "completeness",
1653
+ "level": level,
1654
+ "code": "COMPLETENESS_FEW_ALTERNATIVES",
1655
+ "details": [f"{alternatives} alternative(s) listed"],
1656
+ "summary": (
1657
+ f"{alternatives} alternative(s) considered; a decision needs "
1658
+ f"at least 2, because an outcome with nothing weighed "
1659
+ f"against it cannot be re-evaluated later ('do nothing' "
1660
+ f"counts)"
1661
+ ),
1662
+ })
1663
+ open_questions = unresolved_open_questions(text)
1664
+ if open_questions:
1665
+ current_status = (_current_status(text) or "").casefold()
1666
+ level = "FAIL" if current_status == "accepted" else "ADVISORY"
1667
+ findings.append({
1668
+ "gate": "completeness",
1669
+ "level": level,
1670
+ "code": "OPEN_QUESTIONS_UNRESOLVED",
1671
+ "details": open_questions,
1672
+ "summary": (
1673
+ f"{len(open_questions)} unresolved Open Questions; "
1674
+ + (
1675
+ "Accepted ADRs cannot contain unresolved questions"
1676
+ if current_status == "accepted"
1677
+ else "resolve, reject, or explicitly defer before acceptance"
1678
+ )
1679
+ ),
1680
+ })
1681
+
1682
+ if "audit" in enabled_gates and "audit" not in skip_gates:
1683
+ issues = gate_audit(text)
1684
+ if issues:
1685
+ level = level_for(
1686
+ "audit", adr_num, cfg, strict_from_override,
1687
+ file_advisory, strict_mode,
1688
+ )
1689
+ findings.append({
1690
+ "gate": "audit", "level": level,
1691
+ "details": issues, "summary": "; ".join(issues),
1692
+ })
1693
+
1694
+ if "evidence" in enabled_gates and "evidence" not in skip_gates:
1695
+ hits = gate_evidence(text)
1696
+ if hits:
1697
+ level = level_for(
1698
+ "evidence", adr_num, cfg, strict_from_override,
1699
+ file_advisory, strict_mode,
1700
+ )
1701
+ findings.append({
1702
+ "gate": "evidence", "level": level,
1703
+ "details": [{"line": l, "text": t} for l, t in hits],
1704
+ "summary": f"{len(hits)} bare-adjective hit(s) without nearby measurement",
1705
+ })
1706
+
1707
+ if "clarity" in enabled_gates and "clarity" not in skip_gates:
1708
+ hits = gate_clarity(text)
1709
+ if hits:
1710
+ level = level_for(
1711
+ "clarity", adr_num, cfg, strict_from_override,
1712
+ file_advisory, strict_mode,
1713
+ )
1714
+ findings.append({
1715
+ "gate": "clarity", "level": level,
1716
+ # Details are capped for readability; the summary counts every
1717
+ # distinct acronym so the reported number matches the gate.
1718
+ "details": [{"line": l, "acronym": a} for l, a in hits[:5]],
1719
+ "summary": f"{len({a for _, a in hits})} acronym(s) without inline expansion",
1720
+ })
1721
+
1722
+ if "consistency" in enabled_gates and "consistency" not in skip_gates:
1723
+ issues = gate_consistency(
1724
+ fp, adr_num, text, duplicates,
1725
+ (supersession or {}).get(adr_num),
1726
+ )
1727
+ if frontmatter_consistency:
1728
+ issues = (issues or []) + frontmatter_consistency.get(adr_num, [])
1729
+ if issues:
1730
+ level = level_for(
1731
+ "consistency", adr_num, cfg, strict_from_override,
1732
+ file_advisory, strict_mode,
1733
+ )
1734
+ findings.append({
1735
+ "gate": "consistency", "level": level,
1736
+ "details": issues, "summary": "; ".join(issues),
1737
+ })
1738
+ # Reference findings carry their own severity (ADR-009: never FAIL an
1739
+ # author for a record they are not allowed to edit), so they are added
1740
+ # as separate findings rather than folded into the one consistency
1741
+ # level above.
1742
+ for issue in (reference_issues or {}).get(adr_num, []):
1743
+ findings.append({
1744
+ "gate": "consistency",
1745
+ "level": "FAIL" if strict_mode else (
1746
+ "ADVISORY" if file_advisory else issue["level"]
1747
+ ),
1748
+ "code": issue["code"],
1749
+ "details": [issue["message"]],
1750
+ "summary": issue["message"],
1751
+ })
1752
+
1753
+ if "policy" in enabled_gates and "policy" not in skip_gates:
1754
+ policy_findings = check_policy_gate(text, adr_id)
1755
+ for pf in policy_findings:
1756
+ # Intrinsic severity: FAIL for schema/regex errors, ADVISORY for anti-patterns.
1757
+ # Demote to ADVISORY if the whole file is marked advisory.
1758
+ level = "FAIL" if strict_mode else (
1759
+ "ADVISORY" if file_advisory else pf["severity"]
1760
+ )
1761
+ findings.append({
1762
+ "gate": "policy",
1763
+ "level": level,
1764
+ "code": pf["code"],
1765
+ "details": [pf["message"]],
1766
+ "summary": pf["message"],
1767
+ })
1768
+ # Findability is a completeness question, not a policy one, and it runs in
1769
+ # the default set. Under `policy` it never ran: 12 of this repository's 28
1770
+ # records carried no retrieval metadata at all -- ADR-004 among them, so a
1771
+ # query about context injection did not return the decision that defines
1772
+ # context injection -- and nothing reported it for months.
1773
+ if "completeness" in enabled_gates and "completeness" not in skip_gates:
1774
+ retrieval_finding = check_retrieval_metadata(text, cfg)
1775
+ if retrieval_finding:
1776
+ findings.append(retrieval_finding)
1777
+
1778
+ if "open-questions" in enabled_gates and "open-questions" not in skip_gates:
1779
+ for oqf in check_open_questions_append_only(fp, text, _current_status(text) or ""):
1780
+ findings.append({
1781
+ "gate": "open-questions",
1782
+ "level": "ADVISORY" if file_advisory else oqf["severity"],
1783
+ "code": oqf["code"],
1784
+ "details": [oqf["message"]],
1785
+ "summary": oqf["message"],
1786
+ })
1787
+
1788
+ if "quality" in enabled_gates and "quality" not in skip_gates:
1789
+ quality_findings = check_quality_gate(text, adr_id)
1790
+ for qf in quality_findings:
1791
+ # Quality is always ADVISORY — demoting doesn't change anything, but
1792
+ # honour file_advisory marker for uniformity.
1793
+ findings.append({
1794
+ "gate": "quality",
1795
+ "level": "FAIL" if strict_mode else "ADVISORY",
1796
+ "code": qf["code"],
1797
+ "details": [qf["message"]],
1798
+ "summary": qf["message"],
1799
+ })
1800
+
1801
+ levels = {f["level"] for f in findings}
1802
+ bucket = "PASS" if not findings else ("FAIL" if "FAIL" in levels else "ADVISORY")
1803
+
1804
+ return {
1805
+ "file": fp.name,
1806
+ "adr_num": adr_num,
1807
+ "bucket": bucket,
1808
+ "findings": findings,
1809
+ "migration_notice": migration,
1810
+ }
1811
+
1812
+
1813
+ def detect_duplicates(files: List[Path]) -> Dict[int, List[str]]:
1814
+ grouped: Dict[int, List[str]] = {}
1815
+ for fp in files:
1816
+ m = ADR_FILENAME_RE.match(fp.name)
1817
+ if m:
1818
+ grouped.setdefault(int(m.group(1)), []).append(fp.name)
1819
+ return {n: lst for n, lst in grouped.items() if len(lst) > 1}
1820
+
1821
+
1822
+ def render_human(result: Dict, verbose: bool) -> str:
1823
+ out = []
1824
+ s = result["summary"]
1825
+ out.append(f"Linting {result['target']} ({s['total']} ADRs)")
1826
+ if result["config_path"]:
1827
+ cfg_str = "; ".join(
1828
+ f"{k}={v}" for k, v in result["config_summary"].items()
1829
+ )
1830
+ out.append(f"Config: {result['config_path']} ({cfg_str})")
1831
+ elif result["strict_from_override"]:
1832
+ out.append(f"Config: command-line --strict-from {result['strict_from_override']}")
1833
+ if result.get("strict_mode"):
1834
+ out.append(f"Mode: strict (repo_root={result.get('repo_root')})")
1835
+ out.append("")
1836
+ out.append(f"PASS strictly ({s['pass']}):")
1837
+ for f in result["files"]:
1838
+ if f["bucket"] == "PASS":
1839
+ out.append(f" {f['file']}")
1840
+ out.append("")
1841
+ out.append(f"ADVISORY only ({s['advisory']}):")
1842
+ if verbose:
1843
+ for f in result["files"]:
1844
+ if f["bucket"] == "ADVISORY":
1845
+ out.append(f" {f['file']}")
1846
+ for fnd in f["findings"]:
1847
+ out.append(f" {fnd['gate']} ADVISORY: {fnd['summary']}")
1848
+ else:
1849
+ out.append(f" ({s['advisory']} files; pass --verbose for detail)")
1850
+ out.append("")
1851
+ out.append(f"FAIL ({s['fail']}):")
1852
+ for f in result["files"]:
1853
+ if f["bucket"] == "FAIL":
1854
+ out.append(f" {f['file']}")
1855
+ for fnd in f["findings"]:
1856
+ if fnd["level"] == "FAIL":
1857
+ out.append(f" {fnd['gate']} FAIL: {fnd['summary']}")
1858
+ out.append("")
1859
+ out.append(f"SKIPPED ({s['skipped']})")
1860
+ if verbose and s["skipped"]:
1861
+ for f in result["files"]:
1862
+ if f["bucket"] == "SKIPPED":
1863
+ out.append(f" {f['file']} (reason: {f.get('skip_reason', '?')})")
1864
+ out.append("")
1865
+ notices = result.get("migration_notices", [])
1866
+ out.append(f"Migration notices ({len(notices)}; read-only):")
1867
+ for notice in notices:
1868
+ mode = "deterministic" if notice["deterministic"] else "guided"
1869
+ out.append(
1870
+ f" {notice['file']} [{notice['detected_format']}; {mode}]"
1871
+ )
1872
+ out.append(f" {notice['message']}")
1873
+ if notice.get("preview_command"):
1874
+ out.append(f" preview: {notice['preview_command']}")
1875
+ if notice.get("rename_to"):
1876
+ out.append(f" rename after migration: {notice['rename_to']}")
1877
+ if notice.get("guided_command"):
1878
+ out.append(f" next: {notice['guided_command']}")
1879
+ if not notices:
1880
+ out.append(" none")
1881
+ out.append(" No ADRs were migrated.")
1882
+ out.append("")
1883
+ out.append("Aggregate:")
1884
+ if s["fail"] > 0:
1885
+ # Find ADR with most FAIL gates.
1886
+ worst = max(
1887
+ (f for f in result["files"] if f["bucket"] == "FAIL"),
1888
+ key=lambda f: sum(1 for fnd in f["findings"] if fnd["level"] == "FAIL"),
1889
+ )
1890
+ n_fail_gates = sum(
1891
+ 1 for fnd in worst["findings"] if fnd["level"] == "FAIL"
1892
+ )
1893
+ out.append(
1894
+ f" Next steps: focus on {worst['file']}, "
1895
+ f"which fails {n_fail_gates} enabled gate(s)."
1896
+ )
1897
+ else:
1898
+ out.append(
1899
+ f" All linted ADRs pass at the configured severity. "
1900
+ f"{s['advisory']} ADVISORY findings remain, treated as informational."
1901
+ )
1902
+ return "\n".join(out)
1903
+
1904
+
1905
+ def render_json(result: Dict) -> str:
1906
+ return json.dumps(result, indent=2, ensure_ascii=False)
1907
+
1908
+
1909
+ def parse_gates(arg: Optional[str]) -> Set[str]:
1910
+ if not arg:
1911
+ return set(DEFAULT_GATES)
1912
+ if arg.strip().lower() == "all":
1913
+ return set(ALL_GATES)
1914
+ parts = {p.strip() for p in arg.split(",") if p.strip()}
1915
+ unknown = parts - set(ALL_GATES)
1916
+ if unknown:
1917
+ raise ValueError(
1918
+ f"unknown gate(s) {sorted(unknown)}; legal: {ALL_GATES}"
1919
+ )
1920
+ return parts
1921
+
1922
+
1923
+ def main(argv: Optional[List[str]] = None) -> int:
1924
+ parser = argparse.ArgumentParser(
1925
+ prog="adr-lint",
1926
+ description="Deterministic CLI for the four adr-kit verification gates.",
1927
+ )
1928
+ parser.add_argument(
1929
+ "path", nargs="?", default="docs/adr/",
1930
+ help="File or directory to lint (default: docs/adr/)",
1931
+ )
1932
+ parser.add_argument(
1933
+ "--strict-from", metavar="ADR-NNN", default=None,
1934
+ help="First ADR id (inclusive) on which gates are strict; overrides config.",
1935
+ )
1936
+ parser.add_argument(
1937
+ "--strict", action="store_true",
1938
+ help="CI governance mode: enable schema by default and make findings FAIL.",
1939
+ )
1940
+ parser.add_argument(
1941
+ "--repo-root", metavar="PATH", default=None,
1942
+ help="Consuming repo root for gate and verified_in resolution (default: cwd).",
1943
+ )
1944
+ parser.add_argument(
1945
+ "--context-dir", metavar="PATH", default=None,
1946
+ help="ADR directory used only to resolve cross-references (supersedes, "
1947
+ "superseded_by). Findings are still reported for <path> alone.",
1948
+ )
1949
+ parser.add_argument(
1950
+ "--gates", default=None,
1951
+ help=f"Comma-separated gates to run. Default: {','.join(DEFAULT_GATES)}. "
1952
+ f"All: {','.join(ALL_GATES)}",
1953
+ )
1954
+ parser.add_argument(
1955
+ "--format", choices=["human", "text", "json"], default="human",
1956
+ help="Output format (default: human). 'text' is an alias for 'human'.",
1957
+ )
1958
+ parser.add_argument(
1959
+ "--config", metavar="PATH", default=None,
1960
+ help="Override .adr-kit.json location (default: <path>/.adr-kit.json)",
1961
+ )
1962
+ parser.add_argument(
1963
+ "-v", "--verbose", action="store_true",
1964
+ help="Show ADVISORY and SKIPPED details too",
1965
+ )
1966
+ parser.add_argument(
1967
+ "--version", action="version", version="adr-lint 0.15.0",
1968
+ )
1969
+ args = parser.parse_args(argv)
1970
+
1971
+ target = Path(args.path)
1972
+ if not target.exists():
1973
+ print(f"adr-lint: path not found: {target}", file=sys.stderr)
1974
+ return 2
1975
+
1976
+ try:
1977
+ gates = parse_gates(args.gates)
1978
+ except ValueError as e:
1979
+ print(f"adr-lint: {e}", file=sys.stderr)
1980
+ return 2
1981
+ if args.strict and args.gates is None:
1982
+ gates.add("schema")
1983
+
1984
+ repo_root = Path(args.repo_root).resolve() if args.repo_root else Path.cwd().resolve()
1985
+
1986
+ config_path = (
1987
+ Path(args.config) if args.config
1988
+ else (target / ".adr-kit.json" if target.is_dir()
1989
+ else target.parent / ".adr-kit.json")
1990
+ )
1991
+ try:
1992
+ cfg = load_config(config_path if config_path.exists() else None)
1993
+ except PolicyError as e:
1994
+ print(f"adr-lint: {e}", file=sys.stderr)
1995
+ return 2
1996
+
1997
+ ignore = set(cfg.get("ignore", []))
1998
+ required_sections = cfg.get("template", {}).get("required_sections")
1999
+
2000
+ files = discover_files(target)
2001
+
2002
+ # Cross-file gates need the whole set to resolve a reference, but a caller
2003
+ # that asked about one file must not be told about someone else's problem.
2004
+ # Corpus is what the detectors look things up in; `files` stays what they
2005
+ # may report on.
2006
+ corpus = files
2007
+ if args.context_dir:
2008
+ context_root = Path(args.context_dir)
2009
+ if not context_root.exists():
2010
+ print(f"adr-lint: context dir not found: {context_root}", file=sys.stderr)
2011
+ return 2
2012
+ corpus = merge_lookup_context(files, discover_files(context_root))
2013
+
2014
+ duplicates = detect_duplicates(corpus)
2015
+ supersession = (
2016
+ detect_supersession_conflicts(corpus) if "consistency" in gates else {}
2017
+ )
2018
+ frontmatter_consistency = (
2019
+ detect_frontmatter_consistency(corpus, repo_root, report_files=files)
2020
+ if "consistency" in gates
2021
+ else {}
2022
+ )
2023
+ reference_issues = (
2024
+ detect_reference_issues(corpus, report_files=files)
2025
+ if "consistency" in gates
2026
+ else {}
2027
+ )
2028
+
2029
+ file_results = [
2030
+ lint_file(
2031
+ fp, cfg, args.strict_from, gates, duplicates,
2032
+ required_sections, ignore, supersession,
2033
+ frontmatter_consistency, args.strict,
2034
+ reference_issues=reference_issues,
2035
+ ) for fp in files
2036
+ ]
2037
+ migration_notices = [
2038
+ result["migration_notice"]
2039
+ for result in file_results
2040
+ if result.get("migration_notice") is not None
2041
+ ]
2042
+ migration_notices.extend(scan_extra_migration_notices(target, files))
2043
+
2044
+ counts = {"pass": 0, "advisory": 0, "fail": 0, "skipped": 0, "total": len(file_results)}
2045
+ for r in file_results:
2046
+ b = r["bucket"]
2047
+ counts[b.lower()] += 1
2048
+
2049
+ config_summary = {}
2050
+ if cfg.get("strict_from") or args.strict_from:
2051
+ config_summary["strict_from"] = args.strict_from or cfg["strict_from"]
2052
+ if cfg.get("severity"):
2053
+ for g, v in cfg["severity"].items():
2054
+ config_summary[f"severity.{g}"] = v
2055
+ if cfg.get("template", {}).get("required_sections"):
2056
+ config_summary["template_override"] = "yes"
2057
+ config_summary["template.profile"] = cfg.get("template", {}).get(
2058
+ "profile", "madr"
2059
+ )
2060
+ config_summary["context.retrieval_completeness"] = cfg.get(
2061
+ "context", {}
2062
+ ).get("retrieval_completeness", "advisory")
2063
+
2064
+ result = {
2065
+ "target": str(target),
2066
+ "config_path": str(config_path) if config_path.exists() else None,
2067
+ "config_summary": config_summary,
2068
+ "strict_from_override": args.strict_from,
2069
+ "strict_mode": args.strict,
2070
+ "repo_root": str(repo_root),
2071
+ "gates_enabled": sorted(gates),
2072
+ "summary": counts,
2073
+ "files": file_results,
2074
+ "migration_notices": migration_notices,
2075
+ "exit_code": 1 if counts["fail"] > 0 else 0,
2076
+ }
2077
+
2078
+ if args.format == "json":
2079
+ print(render_json(result))
2080
+ else:
2081
+ print(render_human(result, args.verbose))
2082
+
2083
+ return result["exit_code"]
2084
+
2085
+
2086
+ if __name__ == "__main__":
2087
+ sys.exit(main())