@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-status ADDED
@@ -0,0 +1,797 @@
1
+ #!/usr/bin/env python3
2
+ """adr-status: ADR repository health dashboard.
3
+
4
+ Provides repo-wide visibility: total count, status breakdown, average age,
5
+ enforcement health, retirement candidates.
6
+
7
+ Usage:
8
+ adr-status [--format json|markdown|table] [--adr-dir DIR] [--limit N]
9
+ adr-status --format markdown > /tmp/health.md
10
+
11
+ Determinism of `--format json` (TASK-66)
12
+ ----------------------------------------
13
+ `summary.by_status` is emitted in a fixed (alphabetical) key order, so two runs
14
+ of this binary on unchanged ADRs produce the same ordering. It previously
15
+ iterated the CANONICAL_STATUSES *set*, whose order depends on PYTHONHASHSEED,
16
+ so every process emitted a different order.
17
+
18
+ The payload as a whole is still NOT byte-comparable, deliberately, and a
19
+ consumer wanting a stable artifact must compare it structurally:
20
+
21
+ * `summary.avg_age_days` and `adrs[].age_days` are measured against today's
22
+ real date, so they change overnight without the ADRs changing. They are
23
+ honest values; freezing them behind a `--today` flag would add a lying mode
24
+ to a read-only dashboard for the benefit of golden tests alone.
25
+ * `retrieval.probe_file` is an absolute resolved path and
26
+ `retrieval.index_error` quotes a native OS path, so both differ per machine
27
+ and per platform. They are produced by the shared `adr_query` /
28
+ `adr_retrieval_health` modules that `adr-context` and `adr-doctor` also read;
29
+ normalising them here would either lie about the path or fork the message.
30
+
31
+ `tests/test_adr_mcp.py::normalised_status_payload` documents the same three
32
+ exclusions on the consumer side.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import argparse
38
+ import importlib.machinery
39
+ import importlib.util
40
+ import json
41
+ import re
42
+ import sys
43
+ from datetime import date, datetime
44
+ from pathlib import Path
45
+ from typing import Any, Dict, List, Optional
46
+
47
+ _BIN_DIR = Path(__file__).resolve().parent
48
+
49
+
50
+ def _load_sibling(name: str):
51
+ """Import bin/<name>.py by explicit path, WITHOUT touching sys.path.
52
+
53
+ SEC-HIGH (TASK-62): `sys.path.insert(0, _BIN_DIR)` put this directory ahead
54
+ of the standard library for every import, so a module committed next to
55
+ this script executed as code -- and it re-added the very directory
56
+ CPython's -P / PYTHONSAFEPATH removes. Siblings are registered in
57
+ sys.modules under their bare name, so the plain `from adr_* import ...`
58
+ statements below (and the lazy ones inside functions) resolve from the
59
+ cache instead of the path. bin/adr-judge carries the full rationale.
60
+ """
61
+ cached = sys.modules.get(name)
62
+ if cached is not None:
63
+ return cached
64
+ loader = importlib.machinery.SourceFileLoader(name, str(_BIN_DIR / f"{name}.py"))
65
+ spec = importlib.util.spec_from_loader(name, loader)
66
+ module = importlib.util.module_from_spec(spec)
67
+ sys.modules[name] = module
68
+ loader.exec_module(module)
69
+ return module
70
+
71
+
72
+ # Dependency order: adr_catalog needs adr_format + adr_schema; adr_query
73
+ # lazily needs adr_catalog; adr_retrieval_health needs adr_query.
74
+ _load_sibling("adr_format")
75
+ _load_sibling("adr_schema")
76
+ _load_sibling("adr_catalog")
77
+ _load_sibling("adr_query")
78
+ _load_sibling("adr_retrieval_health")
79
+
80
+ # Report against the same readers the enforcement gate uses, so a status or
81
+ # coverage figure can never claim more (or less) than adr-judge actually acts on.
82
+ from adr_catalog import ENFORCEMENT_BLOCK_RE as _ENFORCEMENT_BLOCK_RE
83
+ from adr_catalog import adr_status as _adr_status
84
+ from adr_retrieval_health import run_retrieval_health
85
+
86
+
87
+ # ---------------------------------------------------------------------------
88
+ # Module-level compiled regexes (hoisted from per-call usage)
89
+ # ---------------------------------------------------------------------------
90
+
91
+ # Date patterns
92
+ _DATE_ISO_RE = re.compile(r"\b(\d{4}-\d{2}-\d{2})\b")
93
+ _MONTHS = (
94
+ "January|February|March|April|May|June|July|August|September|"
95
+ "October|November|December|Jan|Feb|Mar|Apr|Jun|Jul|Aug|Sep|Oct|Nov|Dec"
96
+ )
97
+ _DATE_LONG_RE = re.compile(
98
+ rf"\b(\d{{1,2}})\s+({_MONTHS})\s+(\d{{4}})\b",
99
+ re.IGNORECASE,
100
+ )
101
+
102
+
103
+ # Title: first heading line, stripping the ADR-XXX prefix
104
+ _TITLE_RE = re.compile(r"^#\s+(?:ADR-\d+\s+)?(.+)$", re.MULTILINE)
105
+
106
+ # ADR-id from filename
107
+ _ADR_ID_RE = re.compile(r"ADR-(\d{1,4})", re.IGNORECASE)
108
+
109
+
110
+ # ---------------------------------------------------------------------------
111
+ # Canonical statuses
112
+ # ---------------------------------------------------------------------------
113
+
114
+ CANONICAL_STATUSES = {"proposed", "accepted", "deprecated", "superseded", "amended"}
115
+
116
+
117
+ # ---------------------------------------------------------------------------
118
+ # Per-ADR record (computed once per file)
119
+ # ---------------------------------------------------------------------------
120
+
121
+ class AdrRecord:
122
+ """Per-ADR record. Plain class (not @dataclass) to avoid Python 3.14's
123
+ SourceFileLoader+dataclass interaction issue when this file is imported
124
+ without a .py extension via importlib."""
125
+
126
+ __slots__ = (
127
+ "path", "adr_id", "title", "status", "date", "age_days",
128
+ "has_enforcement", "enforcement_valid", "enforcement_types",
129
+ )
130
+
131
+ def __init__(
132
+ self,
133
+ path: Path,
134
+ adr_id: str,
135
+ title: str,
136
+ status: str,
137
+ date: Optional[str],
138
+ age_days: Optional[int],
139
+ has_enforcement: bool,
140
+ enforcement_valid: bool,
141
+ enforcement_types: Optional[List[str]] = None,
142
+ ) -> None:
143
+ self.path = path
144
+ self.adr_id = adr_id
145
+ self.title = title
146
+ self.status = status
147
+ self.date = date
148
+ self.age_days = age_days
149
+ self.has_enforcement = has_enforcement
150
+ self.enforcement_valid = enforcement_valid
151
+ self.enforcement_types = enforcement_types if enforcement_types is not None else []
152
+
153
+
154
+ # ---------------------------------------------------------------------------
155
+ # Extraction helpers (kept as standalone callables for tests / external use)
156
+ # ---------------------------------------------------------------------------
157
+
158
+ def extract_status(content: str) -> str:
159
+ """Extract the first status word from ADR content, or 'Unknown'.
160
+
161
+ Delegates to the shared adr_catalog reader so the report agrees with the
162
+ gate: the '## Status' heading body, bold-inline forms including
163
+ '**Status: Accepted**', and a plain 'Status: Accepted' line all resolve the
164
+ same way here as in adr-judge and adr-lint.
165
+ """
166
+ return (_adr_status(content) or "Unknown").capitalize()
167
+
168
+
169
+ def extract_date(content: str) -> Optional[str]:
170
+ """Extract date from ADR content.
171
+
172
+ Looks for YYYY-MM-DD first (ISO), then 'DD Month YYYY' (long form).
173
+ Returns the first valid date found, or None.
174
+ """
175
+ m = _DATE_ISO_RE.search(content)
176
+ if m:
177
+ return m.group(1)
178
+
179
+ m = _DATE_LONG_RE.search(content)
180
+ if m:
181
+ try:
182
+ d = datetime.strptime(f"{m.group(1)} {m.group(2)} {m.group(3)}", "%d %B %Y")
183
+ return d.strftime("%Y-%m-%d")
184
+ except ValueError:
185
+ try:
186
+ d = datetime.strptime(f"{m.group(1)} {m.group(2)} {m.group(3)}", "%d %b %Y")
187
+ return d.strftime("%Y-%m-%d")
188
+ except ValueError:
189
+ pass
190
+
191
+ return None
192
+
193
+
194
+ def compute_age_days(date_str: Optional[str]) -> Optional[int]:
195
+ """Compute age in days from today. Returns None if no date given."""
196
+ if not date_str:
197
+ return None
198
+ try:
199
+ d = date.fromisoformat(date_str)
200
+ return (date.today() - d).days
201
+ except ValueError:
202
+ return None
203
+
204
+
205
+ def _parse_enforcement(content: str):
206
+ """Return (has_block, parsed_dict_or_None). Used internally by parse_adr().
207
+
208
+ Single regex scan, single JSON parse.
209
+ """
210
+ m = _ENFORCEMENT_BLOCK_RE.search(content)
211
+ if not m:
212
+ return False, None
213
+ try:
214
+ parsed = json.loads(m.group(1))
215
+ except (json.JSONDecodeError, ValueError):
216
+ return True, None
217
+ if not isinstance(parsed, dict):
218
+ return True, None
219
+ return True, parsed
220
+
221
+
222
+ def has_enforcement(content: str) -> bool:
223
+ """True if the ADR has an ## Enforcement section containing a JSON block."""
224
+ return _ENFORCEMENT_BLOCK_RE.search(content) is not None
225
+
226
+
227
+ def has_valid_enforcement_json(content: str) -> bool:
228
+ """True if the Enforcement JSON block is parseable as a dict."""
229
+ has_block, parsed = _parse_enforcement(content)
230
+ return has_block and parsed is not None
231
+
232
+
233
+ _KNOWN_ENFORCEMENT_TYPES = [
234
+ "forbid_pattern",
235
+ "forbid_import",
236
+ "require_pattern",
237
+ "llm_judge",
238
+ ]
239
+
240
+
241
+ def _types_from_parsed(parsed: Dict[str, Any]) -> List[str]:
242
+ types: List[str] = []
243
+ for t in _KNOWN_ENFORCEMENT_TYPES:
244
+ val = parsed.get(t)
245
+ if val is True or (isinstance(val, list) and len(val) > 0):
246
+ types.append(t)
247
+ return types
248
+
249
+
250
+ def extract_enforcement_types(content: str) -> List[str]:
251
+ """Return list of rule-types from the Enforcement JSON block."""
252
+ _, parsed = _parse_enforcement(content)
253
+ if parsed is None:
254
+ return []
255
+ return _types_from_parsed(parsed)
256
+
257
+
258
+ def extract_title(content: str) -> str:
259
+ """Extract ADR title from the first heading line, stripping the ADR-XXX prefix."""
260
+ m = _TITLE_RE.search(content)
261
+ if m:
262
+ return m.group(1).strip()
263
+ return ""
264
+
265
+
266
+ # ---------------------------------------------------------------------------
267
+ # Loading — single pass per file produces a full AdrRecord
268
+ # ---------------------------------------------------------------------------
269
+
270
+ def parse_adr(path: Path) -> Optional[AdrRecord]:
271
+ """Read a single ADR file once and extract all fields into an AdrRecord.
272
+
273
+ Returns None if the file cannot be read or the filename doesn't match ADR-NNN.
274
+ """
275
+ m = _ADR_ID_RE.search(path.name)
276
+ if not m:
277
+ return None
278
+ adr_id = f"ADR-{int(m.group(1)):03d}"
279
+
280
+ try:
281
+ content = path.read_text(encoding="utf-8")
282
+ except OSError:
283
+ return None
284
+
285
+ status = extract_status(content)
286
+ title = extract_title(content)
287
+ dt = extract_date(content)
288
+ age = compute_age_days(dt)
289
+
290
+ has_block, parsed = _parse_enforcement(content)
291
+ has_enf = has_block
292
+ enf_valid = has_block and parsed is not None
293
+ enf_types = _types_from_parsed(parsed) if parsed is not None else []
294
+
295
+ return AdrRecord(
296
+ path=path,
297
+ adr_id=adr_id,
298
+ title=title,
299
+ status=status,
300
+ date=dt,
301
+ age_days=age,
302
+ has_enforcement=has_enf,
303
+ enforcement_valid=enf_valid,
304
+ enforcement_types=enf_types,
305
+ )
306
+
307
+
308
+ def load_adr_set(adr_dir: Path) -> List[AdrRecord]:
309
+ """Load all ADRs from adr_dir. Returns list of AdrRecord, sorted by filename."""
310
+ records: List[AdrRecord] = []
311
+ for f in sorted(adr_dir.glob("ADR-*.md")):
312
+ rec = parse_adr(f)
313
+ if rec is not None:
314
+ records.append(rec)
315
+ return records
316
+
317
+
318
+ # ---------------------------------------------------------------------------
319
+ # Analytics
320
+ # ---------------------------------------------------------------------------
321
+
322
+ def compute_summary(adrs: List[AdrRecord]) -> Dict[str, Any]:
323
+ """Compute summary statistics for the ADR set.
324
+
325
+ Returns:
326
+ total, by_status, health_pct, avg_age_days, with_enforcement,
327
+ enforcement_valid_pct, coverage_pct, llm_judge_pct
328
+
329
+ Coverage definitions (over Accepted ADRs only):
330
+ coverage_pct: percent of Accepted ADRs with a parseable Enforcement
331
+ block carrying at least one rule.
332
+ llm_judge_pct: percent of Accepted ADRs whose Enforcement includes
333
+ llm_judge: true.
334
+ """
335
+ total = len(adrs)
336
+ # TASK-66: sort at construction. CANONICAL_STATUSES is a set, so iterating
337
+ # it directly gave a by_status key order that depended on PYTHONHASHSEED --
338
+ # two runs of the same binary on the same ADRs emitted different JSON.
339
+ # Insertion order here is the JSON key order, so this is the whole fix.
340
+ by_status: Dict[str, int] = {
341
+ s: 0 for s in sorted(CANONICAL_STATUSES | {"unknown"})
342
+ }
343
+
344
+ ages: List[int] = []
345
+ with_enforcement = 0
346
+ enforcement_valid = 0
347
+ accepted_enforced = 0
348
+ accepted_llm_judge = 0
349
+ accepted_declarative = 0
350
+ accepted_manual_review = 0
351
+ accepted_no_enforcement = 0
352
+
353
+ _declarative_types = ("forbid_pattern", "forbid_import", "require_pattern")
354
+ for rec in adrs:
355
+ key = rec.status.lower()
356
+ if key not in by_status:
357
+ key = "unknown"
358
+ by_status[key] += 1
359
+
360
+ if rec.age_days is not None:
361
+ ages.append(rec.age_days)
362
+
363
+ if rec.has_enforcement:
364
+ with_enforcement += 1
365
+ if rec.enforcement_valid:
366
+ enforcement_valid += 1
367
+
368
+ if key == "accepted":
369
+ if rec.enforcement_valid and rec.enforcement_types:
370
+ accepted_enforced += 1
371
+ if "llm_judge" in rec.enforcement_types:
372
+ accepted_llm_judge += 1
373
+ # Fail-closed floor coverage buckets (ADR-004). A valid block with
374
+ # only "llm_judge": false (the documented manual-review pattern)
375
+ # has no rule types and is counted as manual review, not a gap.
376
+ if any(t in rec.enforcement_types for t in _declarative_types):
377
+ accepted_declarative += 1
378
+ elif rec.has_enforcement and rec.enforcement_valid and "llm_judge" not in rec.enforcement_types:
379
+ accepted_manual_review += 1
380
+ elif not rec.has_enforcement:
381
+ accepted_no_enforcement += 1
382
+
383
+ accepted = by_status["accepted"]
384
+ health_pct = round(accepted / total * 100, 1) if total > 0 else 0.0
385
+ avg_age_days: Optional[float] = round(sum(ages) / len(ages), 1) if ages else None
386
+ enforcement_valid_pct = (
387
+ round(enforcement_valid / with_enforcement * 100, 1)
388
+ if with_enforcement > 0
389
+ else 0.0
390
+ )
391
+ coverage_pct = round(accepted_enforced / accepted * 100, 1) if accepted > 0 else 0.0
392
+ llm_judge_pct = round(accepted_llm_judge / accepted * 100, 1) if accepted > 0 else 0.0
393
+
394
+ return {
395
+ "total": total,
396
+ "by_status": by_status,
397
+ "health_pct": health_pct,
398
+ "avg_age_days": avg_age_days,
399
+ "with_enforcement": with_enforcement,
400
+ "enforcement_valid_pct": enforcement_valid_pct,
401
+ "coverage_pct": coverage_pct,
402
+ "llm_judge_pct": llm_judge_pct,
403
+ "accepted_declarative": accepted_declarative,
404
+ "accepted_manual_review": accepted_manual_review,
405
+ "accepted_no_enforcement": accepted_no_enforcement,
406
+ }
407
+
408
+
409
+ _CONFIDENCE_ORDER = {"high": 3, "medium": 2, "low": 1}
410
+
411
+
412
+ def find_retirement_candidates(adrs: List[AdrRecord]) -> List[Dict[str, Any]]:
413
+ """Identify top-10 retirement candidates.
414
+
415
+ Candidates:
416
+ - Superseded or Deprecated ADRs (confidence: high)
417
+ - Proposed ADRs older than 365 days (confidence: medium)
418
+ - Accepted ADRs older than 730 days without Enforcement (confidence: low)
419
+
420
+ Sorted by confidence desc, then age desc.
421
+ """
422
+ candidates: List[Dict[str, Any]] = []
423
+ for rec in adrs:
424
+ status = rec.status
425
+ status_lower = status.lower()
426
+ age = rec.age_days
427
+
428
+ if status_lower in ("superseded", "deprecated"):
429
+ candidates.append({
430
+ "adr_id": rec.adr_id,
431
+ "status": status,
432
+ "age_days": age,
433
+ "reason": f"{status} — consider archiving",
434
+ "confidence": "high",
435
+ })
436
+ elif status_lower == "proposed" and age is not None and age > 365:
437
+ candidates.append({
438
+ "adr_id": rec.adr_id,
439
+ "status": status,
440
+ "age_days": age,
441
+ "reason": "Proposed for >365 days without acceptance",
442
+ "confidence": "medium",
443
+ })
444
+ elif (
445
+ status_lower == "accepted"
446
+ and age is not None
447
+ and age > 730
448
+ and not rec.has_enforcement
449
+ ):
450
+ candidates.append({
451
+ "adr_id": rec.adr_id,
452
+ "status": status,
453
+ "age_days": age,
454
+ "reason": "Accepted >730 days without Enforcement block",
455
+ "confidence": "low",
456
+ })
457
+
458
+ candidates.sort(
459
+ key=lambda c: (
460
+ _CONFIDENCE_ORDER.get(c["confidence"], 0),
461
+ c["age_days"] if c["age_days"] is not None else 0,
462
+ ),
463
+ reverse=True,
464
+ )
465
+ return candidates[:10]
466
+
467
+
468
+ # ---------------------------------------------------------------------------
469
+ # Formatting
470
+ # ---------------------------------------------------------------------------
471
+
472
+ def _health_indicator(status: str) -> str:
473
+ s = status.lower()
474
+ if s == "accepted":
475
+ return "OK"
476
+ if s == "proposed":
477
+ return "-"
478
+ if s in ("superseded", "deprecated"):
479
+ return "WARN"
480
+ return "?"
481
+
482
+
483
+ def _enforce_label(rec: AdrRecord) -> str:
484
+ if not rec.has_enforcement:
485
+ return "none"
486
+ if rec.enforcement_valid:
487
+ return "json"
488
+ return "invalid"
489
+
490
+
491
+ def format_table(
492
+ summary: Dict[str, Any],
493
+ adrs: List[AdrRecord],
494
+ candidates: List[Dict[str, Any]],
495
+ adr_dir: Path,
496
+ limit: Optional[int] = None,
497
+ retrieval: Optional[Dict[str, Any]] = None,
498
+ ) -> str:
499
+ today = date.today().isoformat()
500
+ lines = [
501
+ f"ADR Health Dashboard - {adr_dir}",
502
+ f"Generated: {today}",
503
+ "",
504
+ "Summary",
505
+ "-------",
506
+ f"Total ADRs: {summary['total']}",
507
+ ]
508
+
509
+ bs = summary["by_status"]
510
+ total = summary["total"]
511
+ accepted = bs["accepted"]
512
+ health_pct = summary["health_pct"]
513
+ lines.append(
514
+ f"Accepted: {accepted} ({health_pct}%)"
515
+ )
516
+ lines.append(f"Proposed: {bs['proposed']}")
517
+ lines.append(f"Superseded: {bs['superseded']}")
518
+ lines.append(f"Deprecated: {bs['deprecated']}")
519
+
520
+ avg = summary["avg_age_days"]
521
+ if avg is not None:
522
+ lines.append(f"Avg age: {int(avg)} days")
523
+ else:
524
+ lines.append("Avg age: n/a")
525
+
526
+ we = summary["with_enforcement"]
527
+ ev_pct = summary["enforcement_valid_pct"]
528
+ enf_pct_of_total = round(we / total * 100, 1) if total > 0 else 0.0
529
+ lines.append(
530
+ f"With Enforcement: {we} ({enf_pct_of_total}% of ADRs, {ev_pct}% valid)"
531
+ )
532
+ lines.append(
533
+ f"Coverage: {summary['coverage_pct']}% of Accepted ADRs enforced"
534
+ f" (llm_judge: {summary['llm_judge_pct']}%)"
535
+ )
536
+ lines.append(
537
+ f"Floor (ADR-004): {summary['accepted_declarative']} declarative, "
538
+ f"{summary['accepted_manual_review']} manual-review, "
539
+ f"{summary['accepted_no_enforcement']} no block"
540
+ )
541
+ if retrieval is not None:
542
+ probes = retrieval["probes"]["summary"]
543
+ lines.append(
544
+ "Retrieval health: "
545
+ f"{retrieval['status']} "
546
+ f"({probes['pass']} pass/{probes['fail']} fail probes; "
547
+ f"{len(retrieval.get('metadata_findings', []))} metadata finding(s))"
548
+ )
549
+
550
+ lines.append("")
551
+
552
+ # ADR table
553
+ col_id = 10
554
+ col_title = 30
555
+ col_status = 11
556
+ col_age = 6
557
+ col_enf = 7
558
+ col_health = 6
559
+
560
+ header = (
561
+ f"{'ADR-ID':<{col_id}} {'Title':<{col_title}} {'Status':<{col_status}}"
562
+ f" {'Age(d)':>{col_age}} {'Enforce':<{col_enf}} {'Health':<{col_health}}"
563
+ )
564
+ sep = (
565
+ f"{'-'*col_id} {'-'*col_title} {'-'*col_status}"
566
+ f" {'-'*col_age} {'-'*col_enf} {'-'*col_health}"
567
+ )
568
+ lines.append(header)
569
+ lines.append(sep)
570
+
571
+ display_adrs = adrs[:limit] if limit is not None else adrs
572
+ for rec in display_adrs:
573
+ age_str = str(rec.age_days) if rec.age_days is not None else "?"
574
+ enf = _enforce_label(rec)
575
+ health = _health_indicator(rec.status)
576
+ title = rec.title
577
+ title_trunc = title[:col_title] if len(title) > col_title else title
578
+ lines.append(
579
+ f"{rec.adr_id:<{col_id}} {title_trunc:<{col_title}} {rec.status:<{col_status}}"
580
+ f" {age_str:>{col_age}} {enf:<{col_enf}} {health:<{col_health}}"
581
+ )
582
+
583
+ if candidates:
584
+ lines.append("")
585
+ lines.append("Retirement Candidates")
586
+ lines.append("---------------------")
587
+ for c in candidates:
588
+ conf = c["confidence"]
589
+ lines.append(f"{c['adr_id']}: {c['reason']} [confidence: {conf}]")
590
+
591
+ return "\n".join(lines)
592
+
593
+
594
+ def format_markdown(
595
+ summary: Dict[str, Any],
596
+ adrs: List[AdrRecord],
597
+ candidates: List[Dict[str, Any]],
598
+ adr_dir: Path,
599
+ limit: Optional[int] = None,
600
+ retrieval: Optional[Dict[str, Any]] = None,
601
+ ) -> str:
602
+ today = date.today().isoformat()
603
+ bs = summary["by_status"]
604
+ total = summary["total"]
605
+ accepted = bs["accepted"]
606
+ health_pct = summary["health_pct"]
607
+ avg = summary["avg_age_days"]
608
+ avg_str = f"{int(avg)}d" if avg is not None else "n/a"
609
+ we = summary["with_enforcement"]
610
+ ev_pct = summary["enforcement_valid_pct"]
611
+
612
+ lines = [
613
+ "# ADR Health Dashboard",
614
+ "",
615
+ f"> Generated: {today} | {adr_dir}",
616
+ "",
617
+ "## Summary",
618
+ "",
619
+ "| Metric | Value |",
620
+ "|--------|-------|",
621
+ f"| Total ADRs | {total} |",
622
+ f"| Accepted | {accepted} ({health_pct}%) |",
623
+ f"| Proposed | {bs['proposed']} |",
624
+ f"| Superseded | {bs['superseded']} |",
625
+ f"| Deprecated | {bs['deprecated']} |",
626
+ f"| Avg age | {avg_str} |",
627
+ f"| With Enforcement | {we} ({ev_pct}% valid) |",
628
+ f"| Enforcement coverage | {summary['coverage_pct']}% of Accepted"
629
+ f" (llm_judge: {summary['llm_judge_pct']}%) |",
630
+ f"| Floor coverage (ADR-004) | {summary['accepted_declarative']} declarative,"
631
+ f" {summary['accepted_manual_review']} manual-review,"
632
+ f" {summary['accepted_no_enforcement']} no block |",
633
+ "",
634
+ "## ADR List",
635
+ "",
636
+ "| ADR | Title | Status | Age | Enforcement | Health |",
637
+ "|-----|-------|--------|-----|-------------|--------|",
638
+ ]
639
+ if retrieval is not None:
640
+ probes = retrieval["probes"]["summary"]
641
+ lines.insert(
642
+ lines.index("## ADR List") - 1,
643
+ f"| Selective-context retrieval | {retrieval['status']}; "
644
+ f"{probes['pass']} pass/{probes['fail']} fail probes; "
645
+ f"{len(retrieval.get('metadata_findings', []))} metadata finding(s) |",
646
+ )
647
+
648
+ display_adrs = adrs[:limit] if limit is not None else adrs
649
+ for rec in display_adrs:
650
+ age_str = f"{rec.age_days}d" if rec.age_days is not None else "?"
651
+ enf = _enforce_label(rec)
652
+ health = _health_indicator(rec.status)
653
+ lines.append(
654
+ f"| {rec.adr_id} | {rec.title} | {rec.status} | {age_str} | {enf} | {health} |"
655
+ )
656
+
657
+ if candidates:
658
+ lines.append("")
659
+ lines.append("## Retirement Candidates")
660
+ lines.append("")
661
+ lines.append("| ADR | Status | Age | Reason | Confidence |")
662
+ lines.append("|-----|--------|-----|--------|------------|")
663
+ for c in candidates:
664
+ age_str = f"{c['age_days']}d" if c["age_days"] is not None else "?"
665
+ lines.append(
666
+ f"| {c['adr_id']} | {c['status']} | {age_str} "
667
+ f"| {c['reason']} | {c['confidence']} |"
668
+ )
669
+
670
+ return "\n".join(lines)
671
+
672
+
673
+ def format_json_output(
674
+ summary: Dict[str, Any],
675
+ adrs: List[AdrRecord],
676
+ candidates: List[Dict[str, Any]],
677
+ retrieval: Optional[Dict[str, Any]] = None,
678
+ ) -> str:
679
+ adr_list = []
680
+ for rec in adrs:
681
+ adr_list.append({
682
+ "adr_id": rec.adr_id,
683
+ "status": rec.status,
684
+ "date": rec.date,
685
+ "age_days": rec.age_days,
686
+ "has_enforcement": rec.has_enforcement,
687
+ "enforcement_valid": rec.enforcement_valid,
688
+ "enforcement_types": rec.enforcement_types,
689
+ "title": rec.title,
690
+ })
691
+
692
+ data = {
693
+ "summary": summary,
694
+ "adrs": adr_list,
695
+ "retirement_candidates": candidates,
696
+ "retrieval": retrieval,
697
+ }
698
+ return json.dumps(data, indent=2)
699
+
700
+
701
+ # ---------------------------------------------------------------------------
702
+ # CLI entry point
703
+ # ---------------------------------------------------------------------------
704
+
705
+ def _ensure_utf8_stdout() -> None:
706
+ """Force stdout/stderr to UTF-8 on Windows where the console may default to cp1252."""
707
+ import io
708
+ if hasattr(sys.stdout, "reconfigure"):
709
+ try:
710
+ sys.stdout.reconfigure(encoding="utf-8")
711
+ sys.stderr.reconfigure(encoding="utf-8")
712
+ except (AttributeError, io.UnsupportedOperation):
713
+ pass
714
+
715
+
716
+ def main() -> None:
717
+ _ensure_utf8_stdout()
718
+
719
+ parser = argparse.ArgumentParser(
720
+ description="ADR repository health dashboard",
721
+ formatter_class=argparse.RawDescriptionHelpFormatter,
722
+ epilog=__doc__,
723
+ )
724
+ parser.add_argument(
725
+ "--format",
726
+ choices=["json", "markdown", "table"],
727
+ default="table",
728
+ help="Output format (default: table)",
729
+ )
730
+ parser.add_argument(
731
+ "--adr-dir",
732
+ dest="adr_dir",
733
+ default=None,
734
+ help="Directory containing ADR-*.md files (default: docs/adr)",
735
+ )
736
+ parser.add_argument(
737
+ "adr_dir_positional",
738
+ nargs="?",
739
+ default=None,
740
+ metavar="ADR_DIR",
741
+ help="Directory containing ADR-*.md files (positional alternative to --adr-dir)",
742
+ )
743
+ parser.add_argument(
744
+ "--limit",
745
+ type=int,
746
+ default=None,
747
+ metavar="N",
748
+ help="Limit ADR rows in table/markdown output (summary and candidates always shown in full)",
749
+ )
750
+
751
+ args = parser.parse_args()
752
+
753
+ # --adr-dir takes precedence over positional; positional falls back to docs/adr
754
+ if args.adr_dir is not None:
755
+ adr_dir = Path(args.adr_dir)
756
+ elif args.adr_dir_positional is not None:
757
+ adr_dir = Path(args.adr_dir_positional)
758
+ else:
759
+ adr_dir = Path("docs/adr")
760
+
761
+ if not adr_dir.is_dir():
762
+ print(f"adr-status: directory not found: {adr_dir}", file=sys.stderr)
763
+ sys.exit(1)
764
+
765
+ adrs = load_adr_set(adr_dir)
766
+ summary = compute_summary(adrs)
767
+ candidates = find_retirement_candidates(adrs)
768
+ retrieval = run_retrieval_health(adr_dir)
769
+
770
+ if args.format == "json":
771
+ print(format_json_output(summary, adrs, candidates, retrieval))
772
+ elif args.format == "markdown":
773
+ print(
774
+ format_markdown(
775
+ summary,
776
+ adrs,
777
+ candidates,
778
+ adr_dir,
779
+ limit=args.limit,
780
+ retrieval=retrieval,
781
+ )
782
+ )
783
+ else:
784
+ print(
785
+ format_table(
786
+ summary,
787
+ adrs,
788
+ candidates,
789
+ adr_dir,
790
+ limit=args.limit,
791
+ retrieval=retrieval,
792
+ )
793
+ )
794
+
795
+
796
+ if __name__ == "__main__":
797
+ main()