@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,536 @@
1
+ """Shared, deterministic ADR catalog and relationship graph helpers.
2
+
3
+ Markdown ADR files remain authoritative. This module projects their invariant
4
+ frontmatter and format-aware semantic sections into records consumed by
5
+ ``adr-index``, ``adr-context``, and ``adr-related``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import re
12
+ from pathlib import Path
13
+ from typing import Dict, Iterable, List, Optional
14
+
15
+ from adr_format import (
16
+ SUPPORTED_PROFILES,
17
+ detect_profile,
18
+ section_text,
19
+ unresolved_open_questions,
20
+ )
21
+ from adr_schema import (
22
+ FrontmatterError,
23
+ infer_frontmatter,
24
+ parse_frontmatter,
25
+ split_frontmatter,
26
+ )
27
+
28
+
29
+ GRAPH_SCHEMA_VERSION = 2
30
+ GRAPH_SCHEMA_REF = "../../schemas/adr-index.schema.json"
31
+ DECISION_SUMMARY_MAX = 120
32
+ RETRIEVAL_VALUE_MAX = 120
33
+ RETRIEVAL_VALUE_LIMIT = 32
34
+ CONTRACT_ITEM_MAX = 240
35
+ CONTRACT_ITEM_LIMIT = 20
36
+
37
+ ADR_FILENAME_RE = re.compile(r"(?i)^ADR-(\d{1,4})-.*\.md$")
38
+ ADR_TOKEN_RE = re.compile(r"\bADR-(\d{1,4})\b", re.IGNORECASE)
39
+ AMENDED_BY_RE = re.compile(r"\bAmended\s+by\s+ADR-(\d{1,4})\b", re.IGNORECASE)
40
+ ENFORCEMENT_BLOCK_RE = re.compile(
41
+ r"^##\s+Enforcement\s*$\n+.*?```json\s*\n(.*?)\n```",
42
+ re.IGNORECASE | re.MULTILINE | re.DOTALL,
43
+ )
44
+
45
+ STATUS_HEADING_RE = re.compile(
46
+ r"^##\s+Status\s*$\n+([^\n]+)", re.IGNORECASE | re.MULTILINE
47
+ )
48
+ STATUS_BOLD_INLINE_RE = re.compile(
49
+ r"^\s*\*\*\s*Status\s*:?\s*\*\*\s*:?\s*([A-Za-z]+)"
50
+ r"|^\s*\*\*\s*Status\s*:?\s*([A-Za-z]+)\s*\*\*",
51
+ re.IGNORECASE | re.MULTILINE,
52
+ )
53
+ # Superset of the two historical single-line variants so every tool agrees on
54
+ # whether an ADR is Accepted: colon optional, leading indentation tolerated,
55
+ # same line only. Recognizes "Status: Accepted", " Status: Accepted", and
56
+ # "Status Accepted"; it never captures the "## Status History" heading.
57
+ STATUS_LINE_RE = re.compile(
58
+ r"^[ \t]*Status[ \t]*:?[ \t]*([A-Za-z]+)", re.IGNORECASE | re.MULTILINE
59
+ )
60
+ _STATUS_LEADING_WORD_RE = re.compile(r"\s*([A-Za-z]+)")
61
+
62
+
63
+ def adr_status(text: str) -> Optional[str]:
64
+ """Return the leading ADR status word, or None.
65
+
66
+ The single cross-tool status reader used by adr-index, adr-judge, adr-lint,
67
+ adr-retire, and adr-watch. A ``## Status`` heading body wins, then a
68
+ bold-inline ``**Status:** X`` form, then a plain ``Status: X`` line. The
69
+ line form is a deliberate superset of the older per-tool regexes so those
70
+ tools can never disagree on an ADR's status. Authoritative lifecycle status
71
+ still comes from the status_history chain in ``load_adr_record``; this is
72
+ the lightweight reader used by gates and listings.
73
+ """
74
+ match = STATUS_HEADING_RE.search(text)
75
+ if match:
76
+ word = _STATUS_LEADING_WORD_RE.match(match.group(1))
77
+ return word.group(1) if word else None
78
+ match = STATUS_BOLD_INLINE_RE.search(text)
79
+ if match:
80
+ return match.group(1) or match.group(2)
81
+ match = STATUS_LINE_RE.search(text)
82
+ return match.group(1) if match else None
83
+
84
+
85
+ def normalize_adr_id(raw: object) -> Optional[str]:
86
+ match = ADR_TOKEN_RE.search(str(raw))
87
+ if not match:
88
+ return None
89
+ return f"ADR-{int(match.group(1)):03d}"
90
+
91
+
92
+ def adr_id_from_filename(name: str) -> Optional[str]:
93
+ """Return the normalized ADR-NNN id for an adr-kit filename, or None.
94
+
95
+ Anchored at the filename start, unlike ``normalize_adr_id``, which accepts
96
+ an ADR token anywhere in arbitrary text.
97
+ """
98
+ match = ADR_FILENAME_RE.match(name)
99
+ if not match:
100
+ return None
101
+ return f"ADR-{int(match.group(1)):03d}"
102
+
103
+
104
+ def discover_adr_files(adr_dir: Path) -> List[Path]:
105
+ if not adr_dir.is_dir():
106
+ return []
107
+ return sorted(
108
+ (
109
+ path
110
+ for path in adr_dir.glob("ADR-*.md")
111
+ if ADR_FILENAME_RE.match(path.name)
112
+ ),
113
+ key=lambda path: path.name.casefold(),
114
+ )
115
+
116
+
117
+ def enforcement_globs(text: str) -> List[str]:
118
+ """Return the stable, de-duplicated path_glob scope from Enforcement."""
119
+ match = ENFORCEMENT_BLOCK_RE.search(text)
120
+ if not match:
121
+ return []
122
+ try:
123
+ data = json.loads(match.group(1))
124
+ except json.JSONDecodeError:
125
+ return []
126
+ if not isinstance(data, dict):
127
+ return []
128
+
129
+ globs: List[str] = []
130
+ for kind in ("forbid_pattern", "forbid_import", "require_pattern"):
131
+ rules = data.get(kind)
132
+ if not isinstance(rules, list):
133
+ continue
134
+ for rule in rules:
135
+ if not isinstance(rule, dict):
136
+ continue
137
+ path_glob = rule.get("path_glob")
138
+ globs.append(path_glob if isinstance(path_glob, str) and path_glob else "**")
139
+ return list(dict.fromkeys(globs))
140
+
141
+
142
+ def _plain_markdown(value: str) -> str:
143
+ value = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", value)
144
+ value = re.sub(r"<[^>]+>", " ", value)
145
+ value = value.replace("`", "").replace("*", "").replace("_", "")
146
+ value = re.sub(r"^\s*(?:[-+]|\d+[.)])\s+", "", value)
147
+ return re.sub(r"\s+", " ", value).strip()
148
+
149
+
150
+ def decision_summary(text: str, *, decision: Optional[str] = None) -> str:
151
+ """Return the first meaningful decision paragraph as bounded plain text."""
152
+ if decision is None:
153
+ decision = section_text(text, "decision")
154
+ if not decision:
155
+ return ""
156
+
157
+ paragraph: List[str] = []
158
+ for raw_line in decision.splitlines():
159
+ line = raw_line.strip()
160
+ if not line:
161
+ if paragraph:
162
+ break
163
+ continue
164
+ if line.startswith(("#", "```", "<!--", "-->")):
165
+ if paragraph:
166
+ break
167
+ continue
168
+ paragraph.append(line)
169
+
170
+ summary = _plain_markdown(" ".join(paragraph))
171
+ sentence_match = re.match(r"^(.+?[.!?])(?:\s|$)", summary)
172
+ if sentence_match:
173
+ summary = sentence_match.group(1)
174
+ if len(summary) > DECISION_SUMMARY_MAX:
175
+ summary = summary[: DECISION_SUMMARY_MAX - 3].rstrip() + "..."
176
+ return summary
177
+
178
+
179
+ def _status_history(text: str) -> List[Dict[str, str]]:
180
+ """Parse adr-kit's deliberately small status_history YAML subset."""
181
+ history = section_text(text, "history")
182
+ entries: List[Dict[str, str]] = []
183
+ current: Optional[Dict[str, str]] = None
184
+ for raw_line in history.splitlines():
185
+ stripped = raw_line.strip()
186
+ if stripped.startswith("- date:"):
187
+ if current:
188
+ entries.append(current)
189
+ current = {"date": stripped.split(":", 1)[1].strip().strip("\"'")}
190
+ continue
191
+ if current is None or ":" not in stripped:
192
+ continue
193
+ key, value = stripped.split(":", 1)
194
+ if key in {"status", "changed_by", "reason", "changed_via"}:
195
+ current[key] = value.strip().strip("\"'")
196
+ if current:
197
+ entries.append(current)
198
+ return entries
199
+
200
+
201
+ def _ids(values: object) -> List[str]:
202
+ if values is None:
203
+ return []
204
+ items = values if isinstance(values, list) else [values]
205
+ normalized = [normalize_adr_id(value) for value in items]
206
+ return sorted({item for item in normalized if item})
207
+
208
+
209
+ def _strings(values: object) -> List[str]:
210
+ if values is None:
211
+ return []
212
+ items = values if isinstance(values, list) else [values]
213
+ return [str(item) for item in items if str(item)]
214
+
215
+
216
+ def _retrieval_strings(
217
+ metadata: Dict,
218
+ field: str,
219
+ findings: List[Dict[str, str]],
220
+ ) -> List[str]:
221
+ values = metadata.get(field)
222
+ if values is None:
223
+ return []
224
+ if not isinstance(values, list):
225
+ findings.append(
226
+ {
227
+ "code": "RETRIEVAL_METADATA_INVALID",
228
+ "message": f"{field} must be a list of strings",
229
+ }
230
+ )
231
+ return []
232
+ normalized: Dict[str, str] = {}
233
+ invalid = len(values) > RETRIEVAL_VALUE_LIMIT
234
+ for value in values[:RETRIEVAL_VALUE_LIMIT]:
235
+ if not isinstance(value, str):
236
+ invalid = True
237
+ continue
238
+ item = re.sub(r"\s+", " ", value).strip()
239
+ if not item or len(item) > RETRIEVAL_VALUE_MAX:
240
+ invalid = True
241
+ continue
242
+ normalized.setdefault(item.casefold(), item)
243
+ if len(normalized) != len(values):
244
+ invalid = True
245
+ if invalid:
246
+ findings.append(
247
+ {
248
+ "code": "RETRIEVAL_METADATA_INVALID",
249
+ "message": (
250
+ f"{field} must contain at most {RETRIEVAL_VALUE_LIMIT} "
251
+ f"unique strings of at most {RETRIEVAL_VALUE_MAX} characters"
252
+ ),
253
+ }
254
+ )
255
+ return sorted(normalized.values(), key=lambda item: (item.casefold(), item))
256
+
257
+
258
+ def decision_contract(text: str) -> Dict[str, List[str]]:
259
+ """Project the optional Decision Contract into bounded semantic lists."""
260
+ contract = {
261
+ "must": [],
262
+ "must_not": [],
263
+ "exceptions": [],
264
+ "verification": [],
265
+ }
266
+ section = section_text(text, "decision_contract")
267
+ if not section:
268
+ return contract
269
+
270
+ headings = {
271
+ "must": "must",
272
+ "must not": "must_not",
273
+ "exceptions": "exceptions",
274
+ "verification": "verification",
275
+ "confirmation": "verification",
276
+ }
277
+ current: Optional[str] = None
278
+ pending: List[str] = []
279
+
280
+ def flush() -> None:
281
+ nonlocal pending
282
+ if current is None or not pending or len(contract[current]) >= CONTRACT_ITEM_LIMIT:
283
+ pending = []
284
+ return
285
+ item = _plain_markdown(" ".join(pending))
286
+ pending = []
287
+ if not item:
288
+ return
289
+ if len(item) > CONTRACT_ITEM_MAX:
290
+ item = item[: CONTRACT_ITEM_MAX - 3].rstrip() + "..."
291
+ if item.casefold() not in {value.casefold() for value in contract[current]}:
292
+ contract[current].append(item)
293
+
294
+ for raw_line in section.splitlines():
295
+ heading_match = re.match(r"^#{3,6}\s+(.+?)\s*#*\s*$", raw_line.strip())
296
+ if heading_match:
297
+ flush()
298
+ current = headings.get(heading_match.group(1).strip().casefold())
299
+ continue
300
+ if current is None:
301
+ continue
302
+ item_match = re.match(
303
+ r"^\s*(?:[-+*]|\d+[.)])\s+(?:\[[ xX]\]\s+)?(.+?)\s*$",
304
+ raw_line,
305
+ )
306
+ if item_match:
307
+ flush()
308
+ pending = [item_match.group(1)]
309
+ continue
310
+ continuation = raw_line.strip()
311
+ if pending and continuation:
312
+ pending.append(continuation)
313
+ flush()
314
+ return contract
315
+
316
+
317
+ def related_ids(text: str, declared: Optional[Dict] = None) -> List[str]:
318
+ """Related-decision ids, from the prose section and the `related` field.
319
+
320
+ Both are read because both are real. Prose is what an author writes by
321
+ hand and what every ADR predating `bin/adr relate` carries; the frontmatter
322
+ field is what the command writes on both sides so the link is reciprocal
323
+ and machine-resolvable. A link declared either way is a link.
324
+ """
325
+ ids = {
326
+ f"ADR-{int(match.group(1)):03d}"
327
+ for match in ADR_TOKEN_RE.finditer(section_text(text, "related"))
328
+ }
329
+ for item in (declared or {}).get("related") or []:
330
+ normalized = normalize_adr_id(item)
331
+ if normalized:
332
+ ids.add(normalized)
333
+ return sorted(ids)
334
+
335
+
336
+ def load_adr_record(path: Path) -> Dict:
337
+ """Load one ADR into the shared semantic record shape."""
338
+ text = path.read_text(encoding="utf-8")
339
+ raw_frontmatter, body = split_frontmatter(text)
340
+ metadata_findings: List[Dict[str, str]] = []
341
+ try:
342
+ declared = parse_frontmatter(raw_frontmatter)
343
+ except FrontmatterError as exc:
344
+ # Index and retrieval are tolerant readers. Strict lint reports the
345
+ # malformed metadata; discovery still falls back to invariant prose.
346
+ declared = {}
347
+ metadata_findings.append(
348
+ {
349
+ "code": "FRONTMATTER_MALFORMED",
350
+ "message": f"Metadata could not be parsed: {exc}",
351
+ }
352
+ )
353
+ inferred = infer_frontmatter(body, path)
354
+ metadata = dict(inferred)
355
+ metadata.update(declared)
356
+
357
+ history = _status_history(text)
358
+ latest = history[-1] if history else {}
359
+ status = str(latest.get("status") or metadata.get("status") or "Unknown").capitalize()
360
+ status_date = latest.get("date") or metadata.get("date")
361
+ if status not in {"Proposed", "Accepted", "Rejected", "Deprecated", "Superseded", "Amended"}:
362
+ metadata_findings.append(
363
+ {
364
+ "code": "STATUS_UNKNOWN",
365
+ "message": f"Lifecycle status is not recognized: {status}",
366
+ }
367
+ )
368
+
369
+ detected_format = detect_profile(text)
370
+ declared_format = metadata.get("format")
371
+ profile = (
372
+ str(declared_format).casefold()
373
+ if declared_format in SUPPORTED_PROFILES
374
+ else detected_format
375
+ )
376
+ if declared_format is not None and str(declared_format).casefold() not in SUPPORTED_PROFILES:
377
+ metadata_findings.append(
378
+ {
379
+ "code": "FORMAT_UNKNOWN",
380
+ "message": f"ADR format is not recognized: {declared_format}",
381
+ }
382
+ )
383
+
384
+ adr_id = normalize_adr_id(metadata.get("id")) or normalize_adr_id(path.name)
385
+ if adr_id is None:
386
+ adr_id = path.stem
387
+
388
+ related = [item for item in related_ids(text, metadata) if item != adr_id]
389
+ supersedes = [item for item in _ids(metadata.get("supersedes")) if item != adr_id]
390
+ superseded_by = normalize_adr_id(metadata.get("superseded_by"))
391
+ if superseded_by == adr_id:
392
+ superseded_by = None
393
+ amended_by = sorted(
394
+ {
395
+ f"ADR-{int(match.group(1)):03d}"
396
+ for match in AMENDED_BY_RE.finditer(text)
397
+ if f"ADR-{int(match.group(1)):03d}" != adr_id
398
+ }
399
+ )
400
+
401
+ decision_text = section_text(text, "decision")
402
+ open_questions = unresolved_open_questions(text)
403
+ retrieval = {
404
+ field: _retrieval_strings(metadata, field, metadata_findings)
405
+ for field in ("topics", "aliases", "components", "symbols")
406
+ }
407
+ context_scope = metadata.get("context_scope", "selective")
408
+ if context_scope not in {"global", "selective"}:
409
+ metadata_findings.append(
410
+ {
411
+ "code": "RETRIEVAL_METADATA_INVALID",
412
+ "message": "context_scope must be global or selective",
413
+ }
414
+ )
415
+ context_scope = "selective"
416
+ return {
417
+ "num": int(re.search(r"\d+", adr_id).group(0)) if normalize_adr_id(adr_id) else 0,
418
+ "adr_id": adr_id,
419
+ "title": str(metadata.get("title") or inferred.get("title") or path.stem),
420
+ "path": path.name,
421
+ "format": profile,
422
+ "status": status,
423
+ "date": str(status_date) if status_date else None,
424
+ "decision": decision_summary(text, decision=decision_text),
425
+ "decision_text": decision_text,
426
+ "decision_contract": decision_contract(text),
427
+ "scope": enforcement_globs(text),
428
+ **retrieval,
429
+ "context_scope": context_scope,
430
+ "binding": bool(metadata.get("binding", False)),
431
+ "gate": metadata.get("gate"),
432
+ "documents_shipped": bool(metadata.get("documents_shipped", False)),
433
+ "verified_in": _strings(metadata.get("verified_in")),
434
+ "supersedes": supersedes,
435
+ "superseded_by": superseded_by,
436
+ "related_ids": related,
437
+ "amended_by": amended_by,
438
+ "open_questions": open_questions,
439
+ "metadata_findings": sorted(
440
+ metadata_findings, key=lambda item: (item["code"], item["message"])
441
+ ),
442
+ "_source_path": path,
443
+ }
444
+
445
+
446
+ def load_adr_records(adr_dir: Path) -> List[Dict]:
447
+ records = [load_adr_record(path) for path in discover_adr_files(adr_dir)]
448
+ records.sort(key=lambda row: (row["num"], row["adr_id"]))
449
+ return records
450
+
451
+
452
+ def build_relationships(records: Iterable[Dict]) -> List[Dict]:
453
+ """Return sorted, de-duplicated declared relationship edges."""
454
+ record_list = list(records)
455
+ known_ids = {record["adr_id"] for record in record_list}
456
+ edge_keys = set()
457
+ relationships: List[Dict] = []
458
+
459
+ def add(source: str, target: Optional[str], kind: str) -> None:
460
+ if not target or source == target:
461
+ return
462
+ key = (source, target, kind)
463
+ if key in edge_keys:
464
+ return
465
+ edge_keys.add(key)
466
+ relationships.append(
467
+ {
468
+ "source": source,
469
+ "target": target,
470
+ "type": kind,
471
+ "resolved": target in known_ids,
472
+ }
473
+ )
474
+
475
+ for record in record_list:
476
+ source = record["adr_id"]
477
+ for target in record.get("related_ids", []):
478
+ add(source, target, "related")
479
+ for target in record.get("supersedes", []):
480
+ add(source, target, "supersedes")
481
+ add(source, record.get("superseded_by"), "superseded-by")
482
+ for target in record.get("amended_by", []):
483
+ add(source, target, "amended-by")
484
+
485
+ relationships.sort(key=lambda edge: (edge["source"], edge["target"], edge["type"]))
486
+ return relationships
487
+
488
+
489
+ def public_adr_node(record: Dict) -> Dict:
490
+ return {
491
+ "id": record["adr_id"],
492
+ "title": record["title"],
493
+ "path": record["path"],
494
+ "format": record["format"],
495
+ "status": record["status"],
496
+ "date": record["date"],
497
+ "decision_summary": record["decision"],
498
+ "topics": record["topics"],
499
+ "aliases": record["aliases"],
500
+ "components": record["components"],
501
+ "symbols": record["symbols"],
502
+ "context_scope": record["context_scope"],
503
+ # A Superseded record stops governing, and authority is joined from
504
+ # status at search time (ADR-020), so its contract is dead weight in a
505
+ # graph every agent carries under ADR-014's 2 KiB-per-ADR budget. The
506
+ # empty shape keeps schema v2 valid; the full contract stays in the
507
+ # Markdown record, which supersession never deletes.
508
+ "decision_contract": (
509
+ {"must": [], "must_not": [], "exceptions": [], "verification": []}
510
+ if record["status"] == "Superseded"
511
+ else record["decision_contract"]
512
+ ),
513
+ "scope": {"path_globs": record["scope"]},
514
+ "metadata": {
515
+ "binding": record["binding"],
516
+ "gate": record["gate"],
517
+ "documents_shipped": record["documents_shipped"],
518
+ "verified_in": record["verified_in"],
519
+ "supersedes": record["supersedes"],
520
+ "superseded_by": record["superseded_by"],
521
+ },
522
+ }
523
+
524
+
525
+ def build_graph_document(
526
+ records: Iterable[Dict],
527
+ *,
528
+ schema_ref: str = GRAPH_SCHEMA_REF,
529
+ ) -> Dict:
530
+ record_list = list(records)
531
+ return {
532
+ "$schema": schema_ref,
533
+ "schema_version": GRAPH_SCHEMA_VERSION,
534
+ "adrs": [public_adr_node(record) for record in record_list],
535
+ "relationships": build_relationships(record_list),
536
+ }