@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,584 @@
1
+ #!/usr/bin/env python3
2
+ """adr-context: find relevant ADRs for a given task query.
3
+
4
+ Uses heuristic scoring with 5 weighted signals. Returns top N ranked ADRs.
5
+
6
+ Usage:
7
+ adr-context "cache invalidation strategy"
8
+ adr-context --limit 10 "database indexes"
9
+ adr-context --format json "authentication"
10
+ adr-context --format text "authentication"
11
+ adr-context --adr-dir docs/adr "authentication"
12
+ adr-context --min-score 0.2 "authentication"
13
+ adr-context --config /path/to/.adr-kit.json "authentication"
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import importlib.machinery
20
+ import importlib.util
21
+ import json
22
+ import re
23
+ import sys
24
+ from datetime import date
25
+ from pathlib import Path
26
+ from typing import Dict, List, Optional
27
+
28
+ _BIN_DIR = Path(__file__).resolve().parent
29
+
30
+
31
+ def _load_sibling(name: str):
32
+ """Import bin/<name>.py by explicit path, WITHOUT touching sys.path.
33
+
34
+ SEC-HIGH (TASK-62): `sys.path.insert(0, _BIN_DIR)` put this directory ahead
35
+ of the standard library for every import, so a module committed next to
36
+ this script executed as code -- and it re-added the very directory
37
+ CPython's -P / PYTHONSAFEPATH removes. Siblings are registered in
38
+ sys.modules under their bare name, so the plain `from adr_* import ...`
39
+ statements below (and the lazy ones inside functions) resolve from the
40
+ cache instead of the path. bin/adr-judge carries the full rationale.
41
+ """
42
+ cached = sys.modules.get(name)
43
+ if cached is not None:
44
+ return cached
45
+ loader = importlib.machinery.SourceFileLoader(name, str(_BIN_DIR / f"{name}.py"))
46
+ spec = importlib.util.spec_from_loader(name, loader)
47
+ module = importlib.util.module_from_spec(spec)
48
+ sys.modules[name] = module
49
+ loader.exec_module(module)
50
+ return module
51
+
52
+
53
+ # Dependency order: adr_schema needs adr_format; adr_catalog needs both;
54
+ # adr_query lazily imports adr_catalog; adr_retrieval_health imports
55
+ # adr_query. adr_catalog and adr_retrieval_health are also imported lazily
56
+ # further down this file and resolve from the same cache.
57
+ _load_sibling("adr_format")
58
+ _load_sibling("adr_schema")
59
+ _load_sibling("adr_catalog")
60
+ _load_sibling("adr_query")
61
+ _load_sibling("adr_retrieval_health")
62
+
63
+ from adr_query import (
64
+ IndexQueryError,
65
+ SUPPORTED_AUTHORITIES,
66
+ SUPPORTED_STATUSES,
67
+ query_adr_context,
68
+ score_record,
69
+ )
70
+
71
+
72
+ def _index_first_cli() -> int:
73
+ """Run the healthy CLI path before loading legacy scoring compatibility."""
74
+ parser = argparse.ArgumentParser(
75
+ description="Find relevant ADRs through the generated ADR graph.",
76
+ formatter_class=argparse.RawDescriptionHelpFormatter,
77
+ epilog=__doc__,
78
+ )
79
+ parser.add_argument("query", nargs="?", help="Task description or question")
80
+ parser.add_argument("--limit", type=int, default=None)
81
+ parser.add_argument("--format", choices=["json", "text"], default="text")
82
+ parser.add_argument("--adr-dir", default=None)
83
+ parser.add_argument("--min-score", type=float, default=None)
84
+ parser.add_argument("--config", default=None)
85
+ parser.add_argument("--strict-index", action="store_true")
86
+ parser.add_argument("--include-history", action="store_true")
87
+ parser.add_argument(
88
+ "--status",
89
+ action="append",
90
+ choices=sorted(SUPPORTED_STATUSES),
91
+ default=[],
92
+ )
93
+ parser.add_argument(
94
+ "--authority",
95
+ action="append",
96
+ choices=sorted(SUPPORTED_AUTHORITIES),
97
+ default=[],
98
+ )
99
+ parser.add_argument("--path", action="append", default=[])
100
+ parser.add_argument("--symbol", action="append", default=[])
101
+ parser.add_argument("--component", action="append", default=[])
102
+ parser.add_argument("--topic", action="append", default=[])
103
+ parser.add_argument(
104
+ "--check-probes",
105
+ action="store_true",
106
+ help="Evaluate the project's deterministic selective-context probes",
107
+ )
108
+ parser.add_argument(
109
+ "--probes-file",
110
+ default=None,
111
+ help="Override the retrieval probe JSON path",
112
+ )
113
+ args = parser.parse_args()
114
+
115
+ adr_dir = Path(args.adr_dir or "docs/adr")
116
+ if not adr_dir.exists():
117
+ if args.format == "json":
118
+ print("[]")
119
+ return 0
120
+
121
+ config: Dict = {}
122
+ candidates = [Path(args.config)] if args.config else []
123
+ if not candidates:
124
+ current = adr_dir.resolve()
125
+ for _ in range(5):
126
+ candidates.append(current / ".adr-kit.json")
127
+ if current.parent == current:
128
+ break
129
+ current = current.parent
130
+ for path in candidates:
131
+ try:
132
+ if path.is_file():
133
+ config = json.loads(path.read_text(encoding="utf-8"))
134
+ break
135
+ except (OSError, UnicodeError, json.JSONDecodeError):
136
+ continue
137
+ ctx_cfg = config.get("context", {}) if isinstance(config, dict) else {}
138
+ if args.check_probes:
139
+ from adr_retrieval_health import (
140
+ render_retrieval_health,
141
+ run_retrieval_health,
142
+ )
143
+
144
+ probe_path = Path(args.probes_file) if args.probes_file else None
145
+ if probe_path is not None and not probe_path.is_absolute():
146
+ probe_path = adr_dir / probe_path
147
+ health = run_retrieval_health(
148
+ adr_dir,
149
+ probe_path=probe_path,
150
+ config=config,
151
+ )
152
+ if args.format == "json":
153
+ print(json.dumps(health, indent=2))
154
+ else:
155
+ print(render_retrieval_health(health))
156
+ return 1 if health["status"] in {"fail", "degraded"} else 0
157
+ if not args.query:
158
+ parser.error("query is required unless --check-probes is used")
159
+ limit = args.limit if args.limit is not None else ctx_cfg.get("default_limit", 5)
160
+ min_score = (
161
+ args.min_score
162
+ if args.min_score is not None
163
+ else ctx_cfg.get("min_score", 0.1)
164
+ )
165
+ try:
166
+ outcome = query_adr_context(
167
+ args.query,
168
+ adr_dir,
169
+ limit=limit,
170
+ min_score=min_score,
171
+ strict_index=args.strict_index or bool(ctx_cfg.get("strict_index", False)),
172
+ include_history=args.include_history,
173
+ statuses=tuple(args.status),
174
+ authorities=tuple(args.authority),
175
+ paths=tuple(args.path),
176
+ symbols=tuple(args.symbol),
177
+ components=tuple(args.component),
178
+ topics=tuple(args.topic),
179
+ )
180
+ except (IndexQueryError, ValueError) as exc:
181
+ print(f"[adr-context] ERROR: {exc}", file=sys.stderr)
182
+ return 2
183
+ for warning in outcome["warnings"]:
184
+ print(warning, file=sys.stderr)
185
+ results = outcome["results"]
186
+ if args.format == "json":
187
+ print(json.dumps(results, indent=2))
188
+ else:
189
+ for result in results:
190
+ print(
191
+ f"{result['adr_id']}: {result['title']} "
192
+ f"(status: {result['status']}; "
193
+ f"{result['authority']} {result['role']}; "
194
+ f"relevance: {result['score']}; path: {result['path']})"
195
+ )
196
+ return 0
197
+
198
+
199
+ if __name__ == "__main__":
200
+ raise SystemExit(_index_first_cli())
201
+
202
+
203
+ # ---------------------------------------------------------------------------
204
+ # Domain keyword sets used by infer_task_domain()
205
+ # ---------------------------------------------------------------------------
206
+
207
+ _DOMAIN_KEYWORDS: Dict[str, List[str]] = {
208
+ "frontend": [
209
+ "react", "css", "html", "ui", "component", "vue", "angular",
210
+ "frontend", "browser", "dom", "webpack", "vite", "svelte", "typescript",
211
+ "stylesheet", "layout", "responsive", "accessibility", "a11y",
212
+ ],
213
+ "infra": [
214
+ "docker", "kubernetes", "k8s", "ci", "cd", "deploy", "deployment",
215
+ "pipeline", "terraform", "helm", "ansible", "nginx", "load", "balancer",
216
+ "container", "cloud", "aws", "azure", "gcp", "infrastructure",
217
+ "monitoring", "logging", "observability", "prometheus", "grafana",
218
+ ],
219
+ "security": [
220
+ "auth", "authentication", "authorization", "token", "jwt", "oauth",
221
+ "ssl", "tls", "cert", "certificate", "rbac", "acl", "permission",
222
+ "encrypt", "encryption", "secret", "password", "hash", "hmac",
223
+ "saml", "sso", "mfa", "2fa", "firewall", "cors", "csrf", "xss",
224
+ ],
225
+ "data": [
226
+ "database", "sql", "postgres", "postgresql", "mysql", "sqlite",
227
+ "cache", "caching", "redis", "memcache", "index", "indexing", "query",
228
+ "migration", "schema", "orm", "etl", "data", "warehouse", "nosql",
229
+ "mongodb", "elasticsearch", "kafka", "queue", "stream", "pipeline",
230
+ "backup", "replication", "sharding", "partitioning",
231
+ ],
232
+ "backend": [
233
+ "api", "rest", "graphql", "grpc", "rpc", "service", "microservice",
234
+ "server", "backend", "endpoint", "route", "handler", "middleware",
235
+ "framework", "django", "flask", "fastapi", "spring", "express",
236
+ "async", "concurrency", "thread", "worker", "task", "job", "queue",
237
+ "business", "logic", "domain", "model", "entity", "repository",
238
+ ],
239
+ }
240
+
241
+
242
+ _DOMAIN_RE: Optional[Dict[str, re.Pattern]] = None
243
+
244
+
245
+ def _domain_patterns() -> Dict[str, re.Pattern]:
246
+ """Compile legacy domain helpers only when compatibility callers use them."""
247
+ global _DOMAIN_RE
248
+ if _DOMAIN_RE is None:
249
+ _DOMAIN_RE = {
250
+ domain: re.compile(
251
+ r"\b(?:" + "|".join(map(re.escape, keywords)) + r")\b",
252
+ re.IGNORECASE,
253
+ )
254
+ for domain, keywords in _DOMAIN_KEYWORDS.items()
255
+ }
256
+ return _DOMAIN_RE
257
+
258
+
259
+ # ---------------------------------------------------------------------------
260
+ # Keyword extraction
261
+ # ---------------------------------------------------------------------------
262
+
263
+ def extract_keywords(query: str) -> List[str]:
264
+ """Parse query into a sorted keyword list.
265
+
266
+ Lowercases the query, splits on non-alphanumeric characters, and filters
267
+ out words shorter than 3 characters.
268
+ """
269
+ words = re.split(r"[^a-z0-9]+", query.lower())
270
+ keywords = sorted({w for w in words if len(w) >= 3})
271
+ return keywords
272
+
273
+
274
+ # ---------------------------------------------------------------------------
275
+ # Domain inference
276
+ # ---------------------------------------------------------------------------
277
+
278
+ def infer_task_domain(text: str) -> Optional[str]:
279
+ """Detect domain from text.
280
+
281
+ Checks text against per-domain keyword sets using precompiled word-bounded
282
+ regexes. Returns the domain with the most keyword hits. Returns ``None``
283
+ when no domain keyword matches (true ambiguity). Callers should treat a
284
+ ``None`` result as "domain unknown" and award no domain_tag signal credit.
285
+ """
286
+ scores: Dict[str, int] = {}
287
+ for domain, pattern in _domain_patterns().items():
288
+ count = len(pattern.findall(text))
289
+ if count > 0:
290
+ scores[domain] = count
291
+
292
+ if not scores:
293
+ return None
294
+
295
+ # Return the domain with the highest hit count; ties broken alphabetically
296
+ return max(scores, key=lambda d: (scores[d], d))
297
+
298
+
299
+ def _domain_has_signal(text: str) -> bool:
300
+ """Return True if at least one domain keyword appears in text.
301
+
302
+ Used to avoid awarding domain_tag credit when neither query nor ADR has
303
+ any concrete domain evidence.
304
+ """
305
+ for pattern in _domain_patterns().values():
306
+ if pattern.search(text):
307
+ return True
308
+ return False
309
+
310
+
311
+ # ---------------------------------------------------------------------------
312
+ # ADR metadata extraction
313
+ # ---------------------------------------------------------------------------
314
+
315
+ def extract_adr_metadata(adr_file: Path) -> Dict:
316
+ """Read ADR file and extract relevant metadata.
317
+
318
+ Returns a dict with:
319
+ - adr_id: "ADR-001"
320
+ - title: text after "# ADR-NNN "
321
+ - status: Accepted / Proposed / etc.
322
+ - domain_tags: inferred domain from title + decision text
323
+ - related_ids: list of "ADR-NNN" strings from Related Decisions section
324
+ - date: datetime.date or None (from ## Status section)
325
+ - decision_text: raw text of ## Decision section (for keyword + domain scoring)
326
+ """
327
+ from adr_catalog import load_adr_record
328
+
329
+ record = load_adr_record(adr_file)
330
+ adr_date: Optional[date] = None
331
+ if record["date"]:
332
+ try:
333
+ adr_date = date.fromisoformat(record["date"])
334
+ except ValueError:
335
+ adr_date = None
336
+
337
+ # Domain: infer from title + decision text
338
+ domain_source = f"{record['title']} {record['decision_text']}"
339
+ domain_tags = infer_task_domain(domain_source)
340
+ domain_has_keywords = _domain_has_signal(domain_source)
341
+
342
+ return {
343
+ "adr_id": record["adr_id"],
344
+ "title": record["title"],
345
+ "path": adr_file.as_posix(),
346
+ "status": record["status"],
347
+ "format": record["format"],
348
+ "domain_tags": domain_tags,
349
+ "domain_has_keywords": domain_has_keywords,
350
+ "related_ids": record["related_ids"],
351
+ "date": adr_date,
352
+ "decision_text": record["decision_text"],
353
+ "decision_summary": record["decision"],
354
+ "topics": record["topics"],
355
+ "aliases": record["aliases"],
356
+ "components": record["components"],
357
+ "symbols": record["symbols"],
358
+ "context_scope": record["context_scope"],
359
+ "decision_contract": record["decision_contract"],
360
+ "scope": record["scope"],
361
+ "metadata": {
362
+ "binding": record["binding"],
363
+ "gate": record["gate"],
364
+ "documents_shipped": record["documents_shipped"],
365
+ "verified_in": record["verified_in"],
366
+ "supersedes": record["supersedes"],
367
+ "superseded_by": record["superseded_by"],
368
+ },
369
+ }
370
+
371
+
372
+ # ---------------------------------------------------------------------------
373
+ # Scoring
374
+ # ---------------------------------------------------------------------------
375
+
376
+ def score_adr(query: str, keywords: List[str], domain: Optional[str], metadata: Dict,
377
+ weights: Optional[Dict[str, float]] = None) -> Dict:
378
+ """Compatibility wrapper over the index-first positive-evidence scorer.
379
+
380
+ ``keywords``, ``domain``, and legacy ``weights`` remain accepted for one
381
+ compatibility window, but status, age, domain, and relationship count no
382
+ longer contribute relevance.
383
+ """
384
+ record = {
385
+ "title": metadata.get("title", ""),
386
+ "decision_summary": metadata.get("decision_summary")
387
+ or metadata.get("decision_text", ""),
388
+ "scope": {"path_globs": metadata.get("scope", [])},
389
+ "topics": metadata.get("topics", []),
390
+ "aliases": metadata.get("aliases", []),
391
+ "components": metadata.get("components", []),
392
+ "symbols": metadata.get("symbols", []),
393
+ "decision_contract": metadata.get("decision_contract", {}),
394
+ }
395
+ return score_record(record, query)
396
+
397
+
398
+ # ---------------------------------------------------------------------------
399
+ # Main loader
400
+ # ---------------------------------------------------------------------------
401
+
402
+ def load_adr_context(
403
+ query: str,
404
+ adr_dir: Path,
405
+ limit: int = 5,
406
+ min_score: float = 0.1,
407
+ config: Optional[Dict] = None,
408
+ strict_index: bool = False,
409
+ include_history: bool = False,
410
+ statuses: tuple[str, ...] = (),
411
+ authorities: tuple[str, ...] = (),
412
+ paths: tuple[str, ...] = (),
413
+ symbols: tuple[str, ...] = (),
414
+ components: tuple[str, ...] = (),
415
+ topics: tuple[str, ...] = (),
416
+ ) -> List[Dict]:
417
+ """Return ranked ADRs from the graph, with visible Markdown fallback."""
418
+ ctx_cfg = config.get("context", {}) if isinstance(config, dict) else {}
419
+ outcome = query_adr_context(
420
+ query,
421
+ adr_dir,
422
+ limit=limit,
423
+ min_score=min_score,
424
+ strict_index=strict_index or bool(ctx_cfg.get("strict_index", False)),
425
+ include_history=include_history,
426
+ statuses=statuses,
427
+ authorities=authorities,
428
+ paths=paths,
429
+ symbols=symbols,
430
+ components=components,
431
+ topics=topics,
432
+ )
433
+ for warning in outcome["warnings"]:
434
+ print(warning, file=sys.stderr)
435
+ return outcome["results"]
436
+
437
+
438
+ # ---------------------------------------------------------------------------
439
+ # Config loading
440
+ # ---------------------------------------------------------------------------
441
+
442
+ def load_config(config_path: Optional[Path], adr_dir: Path) -> Dict:
443
+ """Load .adr-kit.json from explicit path or auto-discover near adr_dir."""
444
+ candidates: List[Path] = []
445
+ if config_path:
446
+ candidates.append(config_path)
447
+ else:
448
+ # Walk up from adr_dir to find .adr-kit.json
449
+ current = adr_dir.resolve()
450
+ for _ in range(5):
451
+ candidates.append(current / ".adr-kit.json")
452
+ parent = current.parent
453
+ if parent == current:
454
+ break
455
+ current = parent
456
+
457
+ for path in candidates:
458
+ if path.exists():
459
+ try:
460
+ return json.loads(path.read_text(encoding="utf-8"))
461
+ except Exception:
462
+ pass
463
+ return {}
464
+
465
+
466
+ # ---------------------------------------------------------------------------
467
+ # CLI
468
+ # ---------------------------------------------------------------------------
469
+
470
+ def main() -> None:
471
+ parser = argparse.ArgumentParser(
472
+ description="Find relevant ADRs for a task query using weighted signals.",
473
+ formatter_class=argparse.RawDescriptionHelpFormatter,
474
+ epilog=__doc__,
475
+ )
476
+ parser.add_argument("query", nargs="?", help="Task description or question")
477
+ parser.add_argument("--limit", type=int, default=None,
478
+ help="Maximum number of results (default: 5 or from config)")
479
+ parser.add_argument("--format", choices=["json", "text"], default="text",
480
+ help="Output format (default: text)")
481
+ parser.add_argument("--adr-dir", default=None,
482
+ help="Directory containing ADR-*.md files (default: docs/adr)")
483
+ parser.add_argument("--min-score", type=float, default=None,
484
+ help="Minimum relevance score threshold (default: 0.1 or from config)")
485
+ parser.add_argument("--config", default=None,
486
+ help="Path to .adr-kit.json config file")
487
+ parser.add_argument("--strict-index", action="store_true",
488
+ help="Fail instead of using the Markdown compatibility fallback")
489
+ parser.add_argument("--include-history", action="store_true",
490
+ help="Include non-governing historical ADR statuses")
491
+ parser.add_argument("--status", action="append",
492
+ choices=sorted(SUPPORTED_STATUSES), default=[],
493
+ help="Lifecycle status filter; may be repeated")
494
+ parser.add_argument("--authority", action="append",
495
+ choices=sorted(SUPPORTED_AUTHORITIES), default=[],
496
+ help="Authority filter; may be repeated")
497
+ parser.add_argument("--path", action="append", default=[],
498
+ help="Changed or target path; may be repeated")
499
+ parser.add_argument("--symbol", action="append", default=[],
500
+ help="Code symbol; may be repeated")
501
+ parser.add_argument("--component", action="append", default=[],
502
+ help="Architectural component; may be repeated")
503
+ parser.add_argument("--topic", action="append", default=[],
504
+ help="Explicit retrieval topic; may be repeated")
505
+ parser.add_argument("--check-probes", action="store_true",
506
+ help="Evaluate deterministic selective-context probes")
507
+ parser.add_argument("--probes-file", default=None,
508
+ help="Override the retrieval probe JSON path")
509
+
510
+ args = parser.parse_args()
511
+
512
+ # Resolve config
513
+ config_path = Path(args.config) if args.config else None
514
+ adr_dir_raw = args.adr_dir or "docs/adr"
515
+ adr_dir = Path(adr_dir_raw)
516
+
517
+ config = load_config(config_path, adr_dir)
518
+ ctx_cfg = config.get("context", {})
519
+ if args.check_probes:
520
+ from adr_retrieval_health import (
521
+ render_retrieval_health,
522
+ run_retrieval_health,
523
+ )
524
+ probe_path = Path(args.probes_file) if args.probes_file else None
525
+ if probe_path is not None and not probe_path.is_absolute():
526
+ probe_path = adr_dir / probe_path
527
+ health = run_retrieval_health(
528
+ adr_dir,
529
+ probe_path=probe_path,
530
+ config=config,
531
+ )
532
+ if args.format == "json":
533
+ print(json.dumps(health, indent=2))
534
+ else:
535
+ print(render_retrieval_health(health))
536
+ sys.exit(1 if health["status"] in {"fail", "degraded"} else 0)
537
+ if not args.query:
538
+ parser.error("query is required unless --check-probes is used")
539
+
540
+ # Apply config defaults, CLI flags take priority
541
+ limit = args.limit if args.limit is not None else ctx_cfg.get("default_limit", 5)
542
+ # Canonical key is "min_score"; legacy "min_relevance_threshold" was removed.
543
+ cfg_min_score = ctx_cfg.get("min_score", 0.1)
544
+ min_score = args.min_score if args.min_score is not None else cfg_min_score
545
+
546
+ if not adr_dir.exists():
547
+ if args.format == "json":
548
+ print("[]")
549
+ # In text mode, print nothing for a missing directory
550
+ sys.exit(0)
551
+
552
+ try:
553
+ results = load_adr_context(
554
+ query=args.query,
555
+ adr_dir=adr_dir,
556
+ limit=limit,
557
+ min_score=min_score,
558
+ config=config,
559
+ strict_index=args.strict_index,
560
+ include_history=args.include_history,
561
+ statuses=tuple(args.status),
562
+ authorities=tuple(args.authority),
563
+ paths=tuple(args.path),
564
+ symbols=tuple(args.symbol),
565
+ components=tuple(args.component),
566
+ topics=tuple(args.topic),
567
+ )
568
+ except (IndexQueryError, ValueError) as exc:
569
+ print(f"[adr-context] ERROR: {exc}", file=sys.stderr)
570
+ sys.exit(2)
571
+
572
+ if args.format == "json":
573
+ print(json.dumps(results, indent=2))
574
+ else:
575
+ for r in results:
576
+ print(
577
+ f"{r['adr_id']}: {r['title']} "
578
+ f"(status: {r['status']}; {r['authority']} {r['role']}; "
579
+ f"relevance: {r['score']}; path: {r['path']})"
580
+ )
581
+
582
+
583
+ if __name__ == "__main__":
584
+ main()