@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
@@ -0,0 +1,546 @@
1
+ #!/usr/bin/env python3
2
+ """adr-discover: deterministic candidate scanner for /adr-kit:init (v0.12.0+).
3
+
4
+ Walks a project root looking for decision-shaped artefacts: top-level config
5
+ files (deps, build tools, CI), and documented decisions in README/docs/AGENTS
6
+ (.md). Emits a JSON list of candidates that the /adr-kit:init skill feeds
7
+ into Claude for LLM curation. It also classifies existing ADRs in docs/adr/ by
8
+ body profile. MADR, Nygard, and canonical are supported; only unknown or
9
+ ambiguous hybrid shapes produce a `template_profile` migration finding.
10
+
11
+ This CLI is intentionally dumb on purpose. It surfaces evidence; it does NOT
12
+ decide which decisions deserve ADRs. That call belongs to the human reviewer
13
+ (via the skill) — adr-discover just makes sure no obvious decision is hidden
14
+ behind a config file the agent never opened.
15
+
16
+ Usage:
17
+ adr-discover # scan cwd, print JSON to stdout
18
+ adr-discover --root /path/to/project
19
+ adr-discover --output docs/adr/.adr-kit-init-candidates.json
20
+ adr-discover --skip 'vendor/**' --skip 'node_modules/**'
21
+
22
+ Exit codes:
23
+ 0 scan completed (zero or more candidates emitted)
24
+ 2 I/O error or invalid argument
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ import importlib.machinery
31
+ import importlib.util
32
+ import json
33
+ import re
34
+ import sys
35
+ from datetime import datetime, timezone
36
+ from pathlib import Path
37
+ from typing import Dict, List, Optional
38
+
39
+ _BIN_DIR = Path(__file__).resolve().parent
40
+
41
+
42
+ def _load_sibling(name: str):
43
+ """Import bin/<name>.py by explicit path, WITHOUT touching sys.path.
44
+
45
+ SEC-HIGH (TASK-62): `sys.path.insert(0, _BIN_DIR)` put this directory ahead
46
+ of the standard library for every import, so a module committed next to
47
+ this script executed as code -- and it re-added the very directory
48
+ CPython's -P / PYTHONSAFEPATH removes. Siblings are registered in
49
+ sys.modules under their bare name, so the plain `from adr_* import ...`
50
+ statements below (and the lazy ones inside functions) resolve from the
51
+ cache instead of the path. bin/adr-judge carries the full rationale.
52
+ """
53
+ cached = sys.modules.get(name)
54
+ if cached is not None:
55
+ return cached
56
+ loader = importlib.machinery.SourceFileLoader(name, str(_BIN_DIR / f"{name}.py"))
57
+ spec = importlib.util.spec_from_loader(name, loader)
58
+ module = importlib.util.module_from_spec(spec)
59
+ sys.modules[name] = module
60
+ loader.exec_module(module)
61
+ return module
62
+
63
+
64
+ _load_sibling("adr_format")
65
+
66
+ from adr_format import SUPPORTED_PROFILES, detect_profile
67
+
68
+ _load_sibling("adr_history_scan")
69
+
70
+ from adr_history_scan import DEFAULT_MAX_COMMITS, scan_history
71
+
72
+ # Top-level files that, by their mere presence, suggest a tooling decision.
73
+ TOOLING_MARKERS = [
74
+ ("Makefile", "build", "Project uses Make as build entry point."),
75
+ ("CMakeLists.txt", "build", "Project uses CMake as build system."),
76
+ ("meson.build", "build", "Project uses Meson as build system."),
77
+ ("build.py", "build", "Project uses a custom Python build script."),
78
+ ("Dockerfile", "runtime", "Project ships a container image."),
79
+ ("docker-compose.yml", "runtime", "Project uses Docker Compose for local orchestration."),
80
+ ("docker-compose.yaml", "runtime", "Project uses Docker Compose for local orchestration."),
81
+ (".pre-commit-config.yaml", "ci", "Project uses pre-commit framework."),
82
+ ("Procfile", "runtime", "Project deploys with a Procfile-based PaaS."),
83
+ ("Brewfile", "tooling", "Project depends on Homebrew bundle for dev setup."),
84
+ ("Vagrantfile", "tooling", "Project provides a Vagrant dev environment."),
85
+ ("flake.nix", "tooling", "Project uses Nix flakes for reproducible builds."),
86
+ ("shell.nix", "tooling", "Project uses Nix shell for dev environment."),
87
+ ("renovate.json", "ci", "Project uses Renovate for dependency updates."),
88
+ ("dependabot.yml", "ci", "Project uses Dependabot for dependency updates."),
89
+ ]
90
+
91
+ # Files whose contents we extract dependency lists from.
92
+ DEP_FILES = [
93
+ "package.json",
94
+ "pyproject.toml",
95
+ "requirements.txt",
96
+ "Cargo.toml",
97
+ "go.mod",
98
+ "Gemfile",
99
+ "composer.json",
100
+ "platformio.ini",
101
+ "library.properties",
102
+ ]
103
+
104
+ # Documentation files to grep for decision-narrative phrases.
105
+ DOC_FILES_PATTERN = ["README.md", "AGENTS.md", "CLAUDE.md"]
106
+ DOC_DIRS = ["docs"]
107
+
108
+ # Decision-narrative phrases (case-insensitive). Each match becomes a candidate.
109
+ DOC_PHRASES = [
110
+ r"\bwe\s+chose\b",
111
+ r"\bwe\s+picked\b",
112
+ r"\bwe\s+decided\b",
113
+ r"\bdecided\s+to\b",
114
+ r"\bdecided\s+against\b",
115
+ r"\binstead\s+of\b",
116
+ r"\brather\s+than\b",
117
+ r"\bwhy\s+not\b",
118
+ r"\brejected\b",
119
+ r"\bsuperseded\s+by\b",
120
+ ]
121
+
122
+ # ---------- template-profile detection (task-5, v0.21.0) ----------
123
+ #
124
+ # Classification delegates to the shared semantic registry. Detection is
125
+ # advisory here; strict validation belongs to adr-lint. ADR-005 supersedes
126
+ # ADR-003's canonical-only storage contract.
127
+
128
+ def detect_template_profile(text: str) -> str:
129
+ """Classify ADR text with the shared semantic profile registry."""
130
+ return detect_profile(text)
131
+
132
+
133
+ # Default skip globs (non-source / non-doc noise + existing ADR & backlog content).
134
+ # docs/adr is skipped because existing ADRs are already recorded decisions —
135
+ # scanning them just produces grep noise from the Decision sections.
136
+ # backlog/** is skipped because Backlog.md task narratives (decided to, instead
137
+ # of) describe TASK-level choices, not ADR-level architecture.
138
+ DEFAULT_SKIP_GLOBS = [
139
+ "node_modules/**",
140
+ "vendor/**",
141
+ ".git/**",
142
+ "dist/**",
143
+ "build/**",
144
+ "target/**",
145
+ ".venv/**",
146
+ "venv/**",
147
+ "__pycache__/**",
148
+ ".pytest_cache/**",
149
+ ".mypy_cache/**",
150
+ "docs/adr/**",
151
+ "backlog/**",
152
+ ]
153
+
154
+
155
+ def glob_to_regex(glob: str) -> re.Pattern:
156
+ """Same translator as bin/adr-judge. Brace expansion {a,b,c} added in v0.12.2."""
157
+ out: List[str] = []
158
+ i = 0
159
+ while i < len(glob):
160
+ c = glob[i]
161
+ if c == "*":
162
+ if i + 1 < len(glob) and glob[i + 1] == "*":
163
+ if i + 2 < len(glob) and glob[i + 2] == "/":
164
+ out.append("(?:.*/)?")
165
+ i += 3
166
+ else:
167
+ out.append(".*")
168
+ i += 2
169
+ else:
170
+ out.append("[^/]*")
171
+ i += 1
172
+ elif c == "?":
173
+ out.append("[^/]")
174
+ i += 1
175
+ elif c == "{":
176
+ close = glob.find("}", i + 1)
177
+ if close == -1 or "{" in glob[i + 1:close]:
178
+ out.append(re.escape(c))
179
+ i += 1
180
+ else:
181
+ inner = glob[i + 1:close]
182
+ alts = inner.split(",")
183
+ alt_patterns = [
184
+ glob_to_regex(a).pattern.lstrip("^").rstrip("$") if a else ""
185
+ for a in alts
186
+ ]
187
+ out.append("(?:" + "|".join(alt_patterns) + ")")
188
+ i = close + 1
189
+ else:
190
+ out.append(re.escape(c))
191
+ i += 1
192
+ return re.compile("^" + "".join(out) + "$")
193
+
194
+
195
+ def any_skip(rel_path: str, skip_regexes: List[re.Pattern]) -> bool:
196
+ return any(r.match(rel_path) for r in skip_regexes)
197
+
198
+
199
+ # ---------- candidate extractors ----------
200
+
201
+
202
+ def scan_tooling(root: Path) -> List[Dict]:
203
+ out: List[Dict] = []
204
+ for filename, kind, narrative in TOOLING_MARKERS:
205
+ p = root / filename
206
+ if p.is_file():
207
+ out.append(
208
+ {
209
+ "id": f"tooling-{filename.lower().replace('.', '-')}",
210
+ "title": narrative,
211
+ "decision_type": kind,
212
+ "evidence_files": [filename],
213
+ "details": {},
214
+ }
215
+ )
216
+ if (root / ".github" / "workflows").is_dir():
217
+ wfs = sorted(
218
+ p.name for p in (root / ".github" / "workflows").iterdir() if p.suffix in (".yml", ".yaml")
219
+ )
220
+ if wfs:
221
+ out.append(
222
+ {
223
+ "id": "tooling-github-actions",
224
+ "title": "Project uses GitHub Actions for CI.",
225
+ "decision_type": "ci",
226
+ "evidence_files": [f".github/workflows/{n}" for n in wfs],
227
+ "details": {"workflow_count": len(wfs)},
228
+ }
229
+ )
230
+ return out
231
+
232
+
233
+ def _safe_read(p: Path, max_bytes: int = 1024 * 256) -> Optional[str]:
234
+ try:
235
+ if p.stat().st_size > max_bytes:
236
+ return None
237
+ return p.read_text(encoding="utf-8", errors="replace")
238
+ except OSError:
239
+ return None
240
+
241
+
242
+ def scan_dependencies(root: Path) -> List[Dict]:
243
+ out: List[Dict] = []
244
+ for filename in DEP_FILES:
245
+ p = root / filename
246
+ if not p.is_file():
247
+ continue
248
+ text = _safe_read(p)
249
+ if text is None:
250
+ continue
251
+ deps = _extract_deps(filename, text)
252
+ if not deps:
253
+ # Even an empty extract is informative — surfaces presence.
254
+ deps = ["(parser produced no dependency list — file present)"]
255
+ out.append(
256
+ {
257
+ "id": f"deps-{filename.lower().replace('.', '-')}",
258
+ "title": f"Dependency choices in {filename}",
259
+ "decision_type": "dependency",
260
+ "evidence_files": [filename],
261
+ "details": {"sample": deps[:30]},
262
+ }
263
+ )
264
+ return out
265
+
266
+
267
+ def _extract_deps(filename: str, text: str) -> List[str]:
268
+ """Best-effort dependency list per file type. Heuristic, not a parser."""
269
+ deps: List[str] = []
270
+ if filename == "package.json":
271
+ try:
272
+ data = json.loads(text)
273
+ for k in ("dependencies", "devDependencies", "peerDependencies"):
274
+ if isinstance(data.get(k), dict):
275
+ deps.extend(sorted(data[k].keys()))
276
+ except json.JSONDecodeError:
277
+ pass
278
+ elif filename == "pyproject.toml":
279
+ # Cheap regex rather than tomllib (3.11+) — works for both poetry and PEP 621 layouts.
280
+ for m in re.finditer(r"^([A-Za-z0-9_.-]+)\s*=\s*['\"][^'\"]*['\"]", text, re.MULTILINE):
281
+ name = m.group(1)
282
+ if name.lower() in {"name", "version", "description", "readme", "requires-python", "license", "authors"}:
283
+ continue
284
+ deps.append(name)
285
+ for m in re.finditer(r'"([A-Za-z0-9_.-]+)"\s*[,\]]', text):
286
+ deps.append(m.group(1))
287
+ elif filename == "requirements.txt":
288
+ for line in text.splitlines():
289
+ line = line.strip()
290
+ if not line or line.startswith("#"):
291
+ continue
292
+ m = re.match(r"^([A-Za-z0-9_.\-\[\]]+)", line)
293
+ if m:
294
+ deps.append(m.group(1))
295
+ elif filename == "Cargo.toml":
296
+ in_deps = False
297
+ for line in text.splitlines():
298
+ s = line.strip()
299
+ if s.startswith("[dependencies"):
300
+ in_deps = True
301
+ continue
302
+ if s.startswith("["):
303
+ in_deps = False
304
+ if in_deps:
305
+ m = re.match(r"^([A-Za-z0-9_-]+)\s*=", s)
306
+ if m:
307
+ deps.append(m.group(1))
308
+ elif filename == "go.mod":
309
+ for m in re.finditer(r"^\s*([\w./-]+)\s+v\d", text, re.MULTILINE):
310
+ deps.append(m.group(1))
311
+ elif filename == "Gemfile":
312
+ for m in re.finditer(r"^\s*gem\s+['\"]([^'\"]+)['\"]", text, re.MULTILINE):
313
+ deps.append(m.group(1))
314
+ elif filename == "composer.json":
315
+ try:
316
+ data = json.loads(text)
317
+ for k in ("require", "require-dev"):
318
+ if isinstance(data.get(k), dict):
319
+ deps.extend(sorted(data[k].keys()))
320
+ except json.JSONDecodeError:
321
+ pass
322
+ elif filename == "platformio.ini":
323
+ for m in re.finditer(r"^\s*lib_deps\s*=\s*(.*)$", text, re.MULTILINE):
324
+ deps.extend([p.strip() for p in m.group(1).split() if p.strip()])
325
+ for kw in ("framework", "platform", "board"):
326
+ m = re.search(rf"^\s*{kw}\s*=\s*(.+)$", text, re.MULTILINE)
327
+ if m:
328
+ deps.append(f"{kw}={m.group(1).strip()}")
329
+ elif filename == "library.properties":
330
+ for kw in ("name", "version", "depends"):
331
+ m = re.search(rf"^{kw}\s*=\s*(.+)$", text, re.MULTILINE)
332
+ if m:
333
+ deps.append(f"{kw}={m.group(1).strip()}")
334
+ return deps
335
+
336
+
337
+ def scan_doc_decisions(root: Path, skip_regexes: List[re.Pattern]) -> List[Dict]:
338
+ """Grep README / AGENTS / CLAUDE / docs for decision-narrative phrases.
339
+
340
+ Emits ONE candidate per file (not per matching line) with up to 5 example
341
+ snippets in details.snippets. This prevents long docs from producing dozens
342
+ of near-duplicate candidates.
343
+ """
344
+ out: List[Dict] = []
345
+ phrase_re = re.compile("|".join(DOC_PHRASES), re.IGNORECASE)
346
+ candidates_paths: List[Path] = []
347
+ for n in DOC_FILES_PATTERN:
348
+ p = root / n
349
+ if p.is_file():
350
+ candidates_paths.append(p)
351
+ for d in DOC_DIRS:
352
+ dp = root / d
353
+ if dp.is_dir():
354
+ for fp in dp.rglob("*.md"):
355
+ rel = fp.relative_to(root).as_posix()
356
+ if any_skip(rel, skip_regexes):
357
+ continue
358
+ candidates_paths.append(fp)
359
+
360
+ next_id = 1
361
+ MAX_SNIPPETS_PER_FILE = 5
362
+ for fp in candidates_paths:
363
+ text = _safe_read(fp)
364
+ if not text:
365
+ continue
366
+ rel = fp.relative_to(root).as_posix()
367
+ if any_skip(rel, skip_regexes):
368
+ continue
369
+ snippets: List[Dict] = []
370
+ match_count = 0
371
+ for lineno, line in enumerate(text.splitlines(), start=1):
372
+ if phrase_re.search(line):
373
+ match_count += 1
374
+ if len(snippets) < MAX_SNIPPETS_PER_FILE:
375
+ snippets.append({"line": lineno, "text": line.strip()[:240]})
376
+ if not snippets:
377
+ continue
378
+ out.append(
379
+ {
380
+ "id": f"doc-quote-{next_id:03d}",
381
+ "title": f"Documented decision narrative in {rel}",
382
+ "decision_type": "documented",
383
+ "evidence_files": [rel],
384
+ "details": {
385
+ "match_count": match_count,
386
+ "snippets": snippets,
387
+ },
388
+ }
389
+ )
390
+ next_id += 1
391
+ return out
392
+
393
+
394
+ def scan_template_profiles(root: Path) -> List[Dict]:
395
+ """Flag unsupported or hybrid ADRs in docs/adr/ for /adr-kit:migrate.
396
+
397
+ The default skip glob `docs/adr/**` only applies to the decision-phrase
398
+ doc scan; this scanner deliberately targets the ADR directory itself.
399
+ All three supported profiles produce no finding. Unknown and hybrid files
400
+ need an explicit source profile or human review before safe conversion.
401
+ """
402
+ adr_dir = root / "docs" / "adr"
403
+ if not adr_dir.is_dir():
404
+ return []
405
+
406
+ declared: Optional[str] = None
407
+ cfg_path = adr_dir / ".adr-kit.json"
408
+ cfg_text = _safe_read(cfg_path) if cfg_path.is_file() else None
409
+ if cfg_text:
410
+ try:
411
+ cfg = json.loads(cfg_text)
412
+ value = cfg.get("template", {}).get("profile")
413
+ if isinstance(value, str) and value in SUPPORTED_PROFILES:
414
+ declared = value
415
+ except (json.JSONDecodeError, AttributeError):
416
+ pass
417
+
418
+ out: List[Dict] = []
419
+ next_id = 1
420
+ for fp in sorted(adr_dir.glob("*.md")):
421
+ text = _safe_read(fp)
422
+ if text is None:
423
+ continue
424
+ profile = detect_template_profile(text)
425
+ if profile not in ("unknown", "hybrid"):
426
+ continue
427
+ rel = fp.relative_to(root).as_posix()
428
+ details: Dict = {
429
+ "template_profile": profile,
430
+ "suggestion": (
431
+ "Add explicit format frontmatter or run /adr-kit:migrate "
432
+ "with a supported source and target profile."
433
+ ),
434
+ }
435
+ if declared:
436
+ details["declared_profile"] = declared
437
+ out.append(
438
+ {
439
+ "id": f"template-profile-{next_id:03d}",
440
+ "title": f"{rel} has an unsupported or ambiguous ADR body format ({profile})",
441
+ "decision_type": "template_profile",
442
+ "evidence_files": [rel],
443
+ "details": details,
444
+ }
445
+ )
446
+ next_id += 1
447
+ return out
448
+
449
+
450
+ # ---------- top-level ----------
451
+
452
+
453
+ def main() -> int:
454
+ p = argparse.ArgumentParser(
455
+ prog="adr-discover",
456
+ description="Scan a project for decision-shaped artefacts (used by /adr-kit:init).",
457
+ )
458
+ p.add_argument("--root", default=".", help="Project root to scan. Default: current directory.")
459
+ p.add_argument(
460
+ "--output",
461
+ default=None,
462
+ help="Write JSON to this path instead of stdout. Use 'docs/adr/.adr-kit-init-candidates.json' to drop next to the ADRs.",
463
+ )
464
+ p.add_argument(
465
+ "--skip",
466
+ action="append",
467
+ default=[],
468
+ help="Glob patterns to skip (in addition to the defaults: node_modules/**, vendor/**, .git/**, etc.). Can be repeated.",
469
+ )
470
+ p.add_argument(
471
+ "--no-history",
472
+ action="store_true",
473
+ help="Skip the git-history scan and report only what the working tree shows.",
474
+ )
475
+ p.add_argument(
476
+ "--max-commits",
477
+ type=int,
478
+ default=DEFAULT_MAX_COMMITS,
479
+ help=f"How far back the history scan reads. Default {DEFAULT_MAX_COMMITS}.",
480
+ )
481
+ args = p.parse_args()
482
+
483
+ try:
484
+ root = Path(args.root).resolve()
485
+ if not root.is_dir():
486
+ print(f"[adr-discover] ERROR: --root not a directory: {root}", file=sys.stderr)
487
+ return 2
488
+ skip_globs = list(DEFAULT_SKIP_GLOBS) + list(args.skip)
489
+ skip_regexes = [glob_to_regex(g) for g in skip_globs]
490
+
491
+ candidates: List[Dict] = []
492
+ candidates.extend(scan_tooling(root))
493
+ candidates.extend(scan_dependencies(root))
494
+ candidates.extend(scan_doc_decisions(root, skip_regexes))
495
+ candidates.extend(scan_template_profiles(root))
496
+ # Everything above walks the working tree, which shows what the project
497
+ # is. Stamp it before the history joins, so a reviewer can always tell
498
+ # a fact about a file from a claim in a commit message.
499
+ for candidate in candidates:
500
+ candidate.setdefault("source", "tree")
501
+
502
+ history = {"candidates": [], "available": False, "reason": "history scan disabled"}
503
+ if not args.no_history:
504
+ tracked = [
505
+ candidate["evidence_files"][0]
506
+ for candidate in candidates
507
+ if candidate.get("evidence_files")
508
+ ]
509
+ history = scan_history(root, tracked_paths=tracked,
510
+ max_commits=args.max_commits)
511
+ candidates.extend(history["candidates"])
512
+
513
+ payload = {
514
+ "scanned_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
515
+ "repo_root": str(root),
516
+ "candidate_count": len(candidates),
517
+ "history": {
518
+ "available": history["available"],
519
+ "reason": history["reason"],
520
+ "candidate_count": len(history["candidates"]),
521
+ },
522
+ "candidates": candidates,
523
+ }
524
+ text = json.dumps(payload, indent=2)
525
+ if args.output:
526
+ outp = Path(args.output)
527
+ if not outp.is_absolute():
528
+ outp = root / outp
529
+ outp.parent.mkdir(parents=True, exist_ok=True)
530
+ outp.write_text(text + "\n", encoding="utf-8")
531
+ print(
532
+ f"[adr-discover] wrote {len(candidates)} candidates to {outp.relative_to(root)}",
533
+ file=sys.stderr,
534
+ )
535
+ else:
536
+ print(text)
537
+ return 0
538
+ except KeyboardInterrupt:
539
+ return 2
540
+ except OSError as e:
541
+ print(f"[adr-discover] ERROR: {e}", file=sys.stderr)
542
+ return 2
543
+
544
+
545
+ if __name__ == "__main__":
546
+ sys.exit(main())