@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,786 @@
1
+ """Shared semantic ADR body profiles.
2
+
3
+ Profiles vary human-facing headings while adr-kit metadata, status history,
4
+ relationships, references, and Enforcement remain invariant. The module is
5
+ stdlib-only so every bundled CLI and generated client payload can import it.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from functools import lru_cache
12
+ from pathlib import Path
13
+ from typing import Dict, List, Optional, Tuple
14
+
15
+
16
+ DEFAULT_PROFILE = "madr"
17
+ SUPPORTED_PROFILES = ("madr", "nygard", "canonical")
18
+ DETECTED_PROFILES = SUPPORTED_PROFILES + ("hybrid", "unknown")
19
+ LEGACY_PROFILES = ("y-statement", "tyree-akerman", "arc42")
20
+
21
+ PROFILE_CATALOG: Dict[str, Dict[str, object]] = {
22
+ "madr": {
23
+ "label": "MADR 4",
24
+ "preferred": True,
25
+ "template": "adr-template.madr.md",
26
+ "best_for": (
27
+ "Agent-assisted decisions that benefit from explicit drivers, "
28
+ "options, outcome, trade-offs, and confirmation."
29
+ ),
30
+ "trade_off": "The most complete profile, but the longest to author.",
31
+ },
32
+ "nygard": {
33
+ "label": "Nygard",
34
+ "preferred": False,
35
+ "template": "adr-template.nygard.md",
36
+ "best_for": (
37
+ "Concise human-written decisions centered on context, decision, "
38
+ "and consequences."
39
+ ),
40
+ "trade_off": (
41
+ "Faster to scan, with adr-kit extension sections retained for "
42
+ "deterministic gates."
43
+ ),
44
+ },
45
+ "canonical": {
46
+ "label": "adr-kit canonical",
47
+ "preferred": False,
48
+ "template": "adr-template.canonical.md",
49
+ "best_for": (
50
+ "Existing adr-kit repositories and compatibility with the "
51
+ "pre-v0.34 section layout."
52
+ ),
53
+ "trade_off": (
54
+ "Maximum backward compatibility, with less explicit authoring "
55
+ "guidance than MADR."
56
+ ),
57
+ },
58
+ }
59
+
60
+ PROFILE_HEADINGS: Dict[str, Dict[str, str]] = {
61
+ "madr": {
62
+ "status": "Status",
63
+ "history": "Status History",
64
+ "context": "Context and Problem Statement",
65
+ "drivers": "Decision Drivers",
66
+ "alternatives": "Considered Options",
67
+ "decision": "Decision Outcome",
68
+ "decision_contract": "Decision Contract",
69
+ "consequences": "Consequences",
70
+ "related": "Related Decisions",
71
+ "references": "References",
72
+ "enforcement": "Enforcement",
73
+ "confirmation": "Confirmation",
74
+ "open_questions": "Open Questions",
75
+ },
76
+ "nygard": {
77
+ "status": "Status",
78
+ "history": "Status History",
79
+ "context": "Context",
80
+ "drivers": "Decision Drivers",
81
+ "alternatives": "Alternatives Considered",
82
+ "decision": "Decision",
83
+ "decision_contract": "Decision Contract",
84
+ "consequences": "Consequences",
85
+ "related": "Related Decisions",
86
+ "references": "References",
87
+ "enforcement": "Enforcement",
88
+ "confirmation": "Confirmation",
89
+ "open_questions": "Open Questions",
90
+ },
91
+ "canonical": {
92
+ "status": "Status",
93
+ "history": "Status History",
94
+ "context": "Context",
95
+ "drivers": "Decision Drivers",
96
+ "alternatives": "Alternatives Considered",
97
+ "decision": "Decision",
98
+ "decision_contract": "Decision Contract",
99
+ "consequences": "Consequences",
100
+ "related": "Related Decisions",
101
+ "references": "References",
102
+ "enforcement": "Enforcement",
103
+ "confirmation": "Confirmation",
104
+ "open_questions": "Open Questions",
105
+ },
106
+ }
107
+
108
+ REQUIRED_ROLES = (
109
+ "status",
110
+ "context",
111
+ "decision",
112
+ "alternatives",
113
+ "consequences",
114
+ "related",
115
+ "references",
116
+ )
117
+
118
+ PROFILE_REQUIRED_ROLES = {
119
+ "madr": REQUIRED_ROLES + ("drivers",),
120
+ "nygard": REQUIRED_ROLES,
121
+ "canonical": REQUIRED_ROLES,
122
+ }
123
+
124
+ _FORMAT_LINE_RE = re.compile(
125
+ r"^\s*format\s*:\s*[\"']?([a-z-]+)[\"']?\s*$", re.IGNORECASE | re.MULTILINE
126
+ )
127
+ _STATUS_LINE_RE = re.compile(r"^\s*status\s*:", re.IGNORECASE | re.MULTILINE)
128
+ _CANONICAL_FILENAME_RE = re.compile(
129
+ r"^ADR-\d{3,4}-[a-z0-9]+(?:-[a-z0-9]+)*\.md$",
130
+ re.IGNORECASE,
131
+ )
132
+ _LEGACY_NUMBER_RE = re.compile(
133
+ r"^(?:ADR[-_ ]?)?0*(\d{1,4})[-_. ]+(.+?)\.md$",
134
+ re.IGNORECASE,
135
+ )
136
+ _HEADING_NUMBER_RE = re.compile(
137
+ r"^#\s+(?:ADR[-_ ]?)?0*(\d{1,4})[.:\s-]+(.+?)\s*$",
138
+ re.IGNORECASE | re.MULTILINE,
139
+ )
140
+ _TITLE_RE = re.compile(r"^#\s+(.+?)\s*$", re.MULTILINE)
141
+ _ARC42_RE = re.compile(
142
+ r"^#{1,3}\s+(?:9(?:\.\d+)*[.:\s-]+)?architecture\s+decisions?\s*$",
143
+ re.IGNORECASE | re.MULTILINE,
144
+ )
145
+ _TYREE_LABEL_RE = re.compile(
146
+ r"^(?:#{1,6}\s+|\*\*)?"
147
+ r"(issue|decision|status|group|assumptions|constraints|positions|"
148
+ r"argument|implications|related decisions|related requirements|"
149
+ r"related artifacts|related principles|notes)"
150
+ r"(?:\*\*)?\s*:?\s*$",
151
+ re.IGNORECASE | re.MULTILINE,
152
+ )
153
+
154
+
155
+ class AdrFormatError(ValueError):
156
+ """Raised when a profile or document shape cannot be handled safely."""
157
+
158
+
159
+ def _validate_profile_catalog_contract() -> None:
160
+ catalog_ids = tuple(PROFILE_CATALOG)
161
+ if catalog_ids != SUPPORTED_PROFILES:
162
+ raise AdrFormatError(
163
+ "ADR profile catalog drift: expected "
164
+ + ", ".join(SUPPORTED_PROFILES)
165
+ + "; found "
166
+ + ", ".join(catalog_ids)
167
+ )
168
+ preferred = tuple(
169
+ profile
170
+ for profile, metadata in PROFILE_CATALOG.items()
171
+ if metadata.get("preferred") is True
172
+ )
173
+ if preferred != (DEFAULT_PROFILE,):
174
+ raise AdrFormatError(
175
+ f"ADR profile catalog must mark only {DEFAULT_PROFILE!r} as preferred"
176
+ )
177
+
178
+
179
+ def profile_template_path(profile: object, template_dir: Path) -> Path:
180
+ """Resolve one approved profile to its shipped template or fail closed."""
181
+ _validate_profile_catalog_contract()
182
+ normalized = normalize_profile(profile)
183
+ template_name = str(PROFILE_CATALOG[normalized]["template"])
184
+ path = template_dir / template_name
185
+ if not path.is_file():
186
+ raise AdrFormatError(
187
+ f"shipped ADR profile {normalized!r} is unavailable: "
188
+ f"missing template {path}"
189
+ )
190
+ return path
191
+
192
+
193
+ def profile_catalog(template_dir: Path) -> List[Dict[str, object]]:
194
+ """Return the ordered, agent-readable catalog and installed availability."""
195
+ _validate_profile_catalog_contract()
196
+ catalog: List[Dict[str, object]] = []
197
+ for profile in SUPPORTED_PROFILES:
198
+ metadata = PROFILE_CATALOG[profile]
199
+ path = template_dir / str(metadata["template"])
200
+ catalog.append(
201
+ {
202
+ "id": profile,
203
+ "label": metadata["label"],
204
+ "preferred": metadata["preferred"],
205
+ "template": str(path),
206
+ "available": path.is_file(),
207
+ "best_for": metadata["best_for"],
208
+ "trade_off": metadata["trade_off"],
209
+ }
210
+ )
211
+ return catalog
212
+
213
+
214
+ def normalize_profile(value: object, *, default: Optional[str] = None) -> str:
215
+ if value is None or value == "":
216
+ if default is None:
217
+ raise AdrFormatError("ADR format profile is required")
218
+ return default
219
+ if not isinstance(value, str):
220
+ raise AdrFormatError("ADR format profile must be a string")
221
+ profile = value.strip().lower()
222
+ if profile == "adr-kit":
223
+ profile = "canonical"
224
+ if profile not in SUPPORTED_PROFILES:
225
+ raise AdrFormatError(
226
+ f"unsupported ADR format {value!r}; choose one of: "
227
+ + ", ".join(SUPPORTED_PROFILES)
228
+ )
229
+ return profile
230
+
231
+
232
+ def configured_profile(config: Dict, *, default: str = DEFAULT_PROFILE) -> str:
233
+ template = config.get("template", {})
234
+ if not isinstance(template, dict):
235
+ raise AdrFormatError("config.template must be an object")
236
+ return normalize_profile(template.get("profile"), default=default)
237
+
238
+
239
+ def _leading_frontmatter(text: str) -> str:
240
+ lines = text.splitlines()
241
+ if not lines or lines[0].strip() != "---":
242
+ return ""
243
+ for index, line in enumerate(lines[1:], start=1):
244
+ if line.strip() == "---":
245
+ return "\n".join(lines[1:index])
246
+ return ""
247
+
248
+
249
+ def declared_profile(text: str) -> Optional[str]:
250
+ raw = _leading_frontmatter(text)
251
+ match = _FORMAT_LINE_RE.search(raw)
252
+ if not match:
253
+ return None
254
+ value = match.group(1).lower()
255
+ return "canonical" if value == "adr-kit" else value
256
+
257
+
258
+ def _lines_outside_fences(text: str) -> List[str]:
259
+ output: List[str] = []
260
+ fence: Optional[str] = None
261
+ for line in text.splitlines():
262
+ stripped = line.lstrip()
263
+ marker = stripped[:3]
264
+ if marker in {"```", "~~~"}:
265
+ if fence is None:
266
+ fence = marker
267
+ elif marker == fence:
268
+ fence = None
269
+ continue
270
+ if fence is None:
271
+ output.append(line)
272
+ return output
273
+
274
+
275
+ def h2_headings(text: str) -> List[str]:
276
+ headings: List[str] = []
277
+ for line in _lines_outside_fences(text):
278
+ match = re.match(r"^##\s+(.+?)\s*#*\s*$", line)
279
+ if match:
280
+ headings.append(match.group(1).strip())
281
+ return headings
282
+
283
+
284
+ def unresolved_open_questions(text: str) -> List[str]:
285
+ """Return stable unresolved items from the optional Open Questions role."""
286
+ section = section_text(text, "open_questions")
287
+ if not section:
288
+ return []
289
+ questions: List[str] = []
290
+ for raw_line in section.splitlines():
291
+ line = raw_line.strip()
292
+ if not line or line.startswith(("```", "<!--", "-->")):
293
+ continue
294
+ normalized = re.sub(r"^\s*[-*+]\s+", "", line).strip()
295
+ if normalized.casefold().rstrip(".") in {
296
+ "none",
297
+ "no open questions",
298
+ "no unresolved questions",
299
+ }:
300
+ continue
301
+ if re.match(r"^\[[xX]\]\s+", normalized):
302
+ continue
303
+ if re.match(r"^(?:answered|resolved)\s*:", normalized, re.IGNORECASE):
304
+ continue
305
+ unchecked = re.match(r"^\[\s\]\s+(.+)$", normalized)
306
+ if unchecked:
307
+ candidate = unchecked.group(1)
308
+ elif re.match(r"^[-*+]\s+", line) or normalized.endswith("?"):
309
+ candidate = normalized
310
+ else:
311
+ continue
312
+ candidate = re.sub(r"[`*_]", "", candidate)
313
+ candidate = re.sub(r"\s+", " ", candidate).strip()
314
+ if candidate:
315
+ questions.append(candidate)
316
+ return sorted(dict.fromkeys(questions), key=str.casefold)
317
+
318
+
319
+ def _normalise_question(raw: str) -> str:
320
+ """One question's identity, independent of how it is marked up.
321
+
322
+ The same text has to match across two revisions of a file, and between an
323
+ unanswered `- [ ] Why X?` and its answered `- [x] Why X? — **Answered ...**`
324
+ form. Markup and whitespace are noise for that comparison; the words are not.
325
+ """
326
+ text = re.sub(r"^\s*[-*+]\s+", "", raw.strip())
327
+ text = re.sub(r"^\[[ xX]\]\s*", "", text)
328
+ # Everything from the answer marker on belongs to the answer, not the question.
329
+ text = re.split(r"\s+[—-]{1,2}\s+\*\*Answered\b", text)[0]
330
+ text = re.sub(r"[`*_]", "", text)
331
+ return re.sub(r"\s+", " ", text).strip()
332
+
333
+
334
+ def all_open_questions(text: str) -> "Dict[str, bool]":
335
+ """Every question in the Open Questions role, mapped to whether it is answered.
336
+
337
+ `unresolved_open_questions` deliberately drops answered items, which is right
338
+ for "what still blocks acceptance" and useless for "what was here before".
339
+ Telling an answered question from a deleted one is the whole point of the
340
+ append-only rule (ADR-022): both leave the unresolved list empty, and only
341
+ one of them preserved the reasoning.
342
+ """
343
+ section = section_text(text, "open_questions")
344
+ if not section:
345
+ return {}
346
+ found: Dict[str, bool] = {}
347
+ for raw_line in section.splitlines():
348
+ line = raw_line.strip()
349
+ if not line or line.startswith(("```", "<!--", "-->")):
350
+ continue
351
+ stripped = re.sub(r"^\s*[-*+]\s+", "", line).strip()
352
+ if stripped.casefold().rstrip(".") in {
353
+ "none",
354
+ "no open questions",
355
+ "no unresolved questions",
356
+ }:
357
+ continue
358
+ answered = bool(re.match(r"^\[[xX]\]\s+", stripped))
359
+ if not answered and not (
360
+ re.match(r"^\[\s\]\s+", stripped)
361
+ or re.match(r"^[-*+]\s+", line)
362
+ or stripped.endswith("?")
363
+ ):
364
+ continue
365
+ question = _normalise_question(line)
366
+ if not question:
367
+ continue
368
+ # An answered form wins: a question listed twice, once each way, is
369
+ # answered.
370
+ found[question] = found.get(question, False) or answered
371
+ return found
372
+
373
+
374
+ @lru_cache(maxsize=256)
375
+ def detect_profile(text: str) -> str:
376
+ declared = declared_profile(text)
377
+ if declared is not None:
378
+ return declared if declared in SUPPORTED_PROFILES else "unknown"
379
+
380
+ ordered_headings = h2_headings(text)
381
+ headings = set(ordered_headings)
382
+ madr_unique = {
383
+ PROFILE_HEADINGS["madr"]["context"],
384
+ PROFILE_HEADINGS["madr"]["alternatives"],
385
+ PROFILE_HEADINGS["madr"]["decision"],
386
+ }
387
+ canonical_required = set(required_heading_names("canonical"))
388
+ nygard_core = {"Status", "Context", "Decision", "Consequences"}
389
+
390
+ madr_hits = len(madr_unique & headings)
391
+ canonical_match = canonical_required.issubset(headings)
392
+ nygard_match = nygard_core.issubset(headings)
393
+
394
+ has_frontmatter_status = bool(_STATUS_LINE_RE.search(_leading_frontmatter(text)))
395
+ if madr_hits >= 2 and (canonical_match or {"Context", "Decision"} <= headings):
396
+ return "hybrid"
397
+ if madr_hits >= 2 or (madr_hits >= 1 and has_frontmatter_status):
398
+ return "madr"
399
+ if canonical_match:
400
+ # The extended Nygard profile deliberately shares canonical heading
401
+ # names. Its defining order puts Consequences before Alternatives,
402
+ # while the historical canonical profile does the reverse.
403
+ consequences = ordered_headings.index("Consequences")
404
+ alternatives = ordered_headings.index("Alternatives Considered")
405
+ return "nygard" if consequences < alternatives else "canonical"
406
+ if nygard_match:
407
+ return "nygard"
408
+ return "unknown"
409
+
410
+
411
+ def detect_legacy_profile(text: str) -> Optional[str]:
412
+ """Identify common unsupported ADR families using conservative markers.
413
+
414
+ Supported profiles win before this function is considered. The detectors
415
+ intentionally require distinctive structures so ordinary Markdown is not
416
+ mislabeled as a migration candidate.
417
+ """
418
+ if detect_profile(text) != "unknown":
419
+ return None
420
+ visible = "\n".join(_lines_outside_fences(text))
421
+ lowered = visible.casefold()
422
+ cursor = 0
423
+ y_statement_markers = (
424
+ ("in the context of",),
425
+ ("facing",),
426
+ (
427
+ "we decided for",
428
+ "we decided to",
429
+ "we have decided for",
430
+ "we have decided to",
431
+ ),
432
+ ("neglected",),
433
+ ("to achieve",),
434
+ ("accepting",),
435
+ )
436
+ y_statement = True
437
+ for alternatives in y_statement_markers:
438
+ positions = [
439
+ lowered.find(marker, cursor)
440
+ for marker in alternatives
441
+ if lowered.find(marker, cursor) >= 0
442
+ ]
443
+ if not positions:
444
+ y_statement = False
445
+ break
446
+ cursor = min(positions) + 1
447
+ if y_statement:
448
+ return "y-statement"
449
+
450
+ labels = {match.casefold() for match in _TYREE_LABEL_RE.findall(visible)}
451
+ tyree_distinctive = {
452
+ "issue",
453
+ "decision",
454
+ "assumptions",
455
+ "constraints",
456
+ "positions",
457
+ "argument",
458
+ "implications",
459
+ }
460
+ if {"issue", "decision"} <= labels and len(labels & tyree_distinctive) >= 5:
461
+ return "tyree-akerman"
462
+
463
+ if _ARC42_RE.search(visible):
464
+ return "arc42"
465
+ return None
466
+
467
+
468
+ def classify_format(text: str) -> str:
469
+ """Return a supported, legacy, hybrid, or unknown format classification."""
470
+ profile = detect_profile(text)
471
+ if profile != "unknown":
472
+ return profile
473
+ return detect_legacy_profile(text) or "unknown"
474
+
475
+
476
+ def is_canonical_filename(path: Path) -> bool:
477
+ return bool(_CANONICAL_FILENAME_RE.fullmatch(path.name))
478
+
479
+
480
+ def _slugify(value: str) -> str:
481
+ slug = re.sub(r"[^a-z0-9]+", "-", value.casefold()).strip("-")
482
+ return slug or "decision"
483
+
484
+
485
+ def suggested_filename(path: Path, text: str) -> Optional[str]:
486
+ """Suggest an adr-kit filename when a legacy number can be inferred."""
487
+ number: Optional[int] = None
488
+ title: Optional[str] = None
489
+
490
+ filename_match = _LEGACY_NUMBER_RE.match(path.name)
491
+ if filename_match:
492
+ number = int(filename_match.group(1))
493
+ title = filename_match.group(2)
494
+
495
+ heading_match = _HEADING_NUMBER_RE.search(text)
496
+ if heading_match:
497
+ number = int(heading_match.group(1))
498
+ title = heading_match.group(2)
499
+
500
+ if number is None:
501
+ return None
502
+ if not title:
503
+ title_match = _TITLE_RE.search(text)
504
+ title = title_match.group(1) if title_match else "decision"
505
+ return f"ADR-{number:03d}-{_slugify(title)}.md"
506
+
507
+
508
+ def migration_notice(
509
+ text: str,
510
+ path: Path,
511
+ *,
512
+ metadata_changed: bool = False,
513
+ metadata_issues: Optional[List[str]] = None,
514
+ migrate_command: str = "bin/adr-migrate",
515
+ ) -> Optional[Dict]:
516
+ """Build a read-only migration recommendation for one document.
517
+
518
+ The result is deliberately data-only so lint, install, upgrade, and the
519
+ migration CLI can render the same advice. No function in this module writes
520
+ files.
521
+ """
522
+ classification = classify_format(text)
523
+ issues = list(metadata_issues or [])
524
+ canonical_name = is_canonical_filename(path)
525
+ rename_to = None if canonical_name else suggested_filename(path, text)
526
+ missing_sections: List[str] = []
527
+ if classification in SUPPORTED_PROFILES:
528
+ present = {item.casefold() for item in h2_headings(text)}
529
+ missing_sections = [
530
+ name
531
+ for name in required_heading_names(classification)
532
+ if name.casefold() not in present
533
+ ]
534
+
535
+ if (
536
+ classification in SUPPORTED_PROFILES
537
+ and not metadata_changed
538
+ and not issues
539
+ and canonical_name
540
+ and not missing_sections
541
+ ):
542
+ return None
543
+
544
+ quoted_path = '"' + str(path).replace('"', '\\"') + '"'
545
+ quoted_command = '"' + migrate_command.replace('"', '\\"') + '"'
546
+ command_prefix = f"python {quoted_command}"
547
+ base = {
548
+ "file": str(path),
549
+ "detected_format": classification,
550
+ "supported": classification in SUPPORTED_PROFILES,
551
+ "metadata_change": metadata_changed,
552
+ "metadata_issues": issues,
553
+ "missing_sections": missing_sections,
554
+ "rename_to": rename_to,
555
+ "writes_automatically": False,
556
+ }
557
+
558
+ if classification in SUPPORTED_PROFILES and not issues:
559
+ reasons: List[str] = []
560
+ if metadata_changed:
561
+ reasons.append("canonical metadata can be added deterministically")
562
+ if missing_sections:
563
+ reasons.append(
564
+ "required extension sections can be added deterministically"
565
+ )
566
+ if not canonical_name:
567
+ reasons.append("the filename needs adr-kit normalization")
568
+ profile_option = f" --to-profile {classification}"
569
+ return {
570
+ **base,
571
+ "action": "deterministic-preview",
572
+ "deterministic": True,
573
+ "message": (
574
+ f"Detected supported {classification} ADR; "
575
+ + "; ".join(reasons)
576
+ + "."
577
+ ),
578
+ "preview_command": (
579
+ f"{command_prefix} --dry-run{profile_option} {quoted_path}"
580
+ ),
581
+ "apply_command": (
582
+ f"{command_prefix}{profile_option} {quoted_path}"
583
+ ),
584
+ "guided_command": None,
585
+ }
586
+
587
+ if classification in LEGACY_PROFILES:
588
+ family = {
589
+ "y-statement": "Y-Statement",
590
+ "tyree-akerman": "Tyree/Akerman",
591
+ "arc42": "arc42 decision section",
592
+ }[classification]
593
+ return {
594
+ **base,
595
+ "action": "guided-migration",
596
+ "deterministic": False,
597
+ "message": (
598
+ f"Detected {family}; mapping its semantics requires review, "
599
+ "so adr-kit will not guess or rewrite it automatically."
600
+ ),
601
+ "preview_command": None,
602
+ "apply_command": None,
603
+ "guided_command": f'/adr-kit:migrate {quoted_path}',
604
+ }
605
+
606
+ if classification == "hybrid":
607
+ message = (
608
+ "Detected a hybrid of supported ADR headings; select the actual "
609
+ "source profile before conversion."
610
+ )
611
+ elif issues:
612
+ message = (
613
+ "Detected an ADR whose metadata cannot be normalized safely: "
614
+ + "; ".join(issues)
615
+ )
616
+ else:
617
+ message = (
618
+ "ADR format is unknown; use guided migration to map its semantic "
619
+ "sections without fabricating content."
620
+ )
621
+ return {
622
+ **base,
623
+ "action": "guided-migration",
624
+ "deterministic": False,
625
+ "message": message,
626
+ "preview_command": None,
627
+ "apply_command": None,
628
+ "guided_command": f'/adr-kit:migrate {quoted_path}',
629
+ }
630
+
631
+
632
+ def is_migration_candidate(path: Path, text: str) -> bool:
633
+ """Return whether a Markdown file belongs in format discovery."""
634
+ if path.name.casefold() in {"readme.md", "adr-index.md"}:
635
+ return False
636
+ if re.match(r"^ADR-\d{1,4}-.*\.md$", path.name, re.IGNORECASE):
637
+ return True
638
+ return classify_format(text) != "unknown"
639
+
640
+
641
+ def heading(profile: str, role: str) -> str:
642
+ normalized = normalize_profile(profile)
643
+ try:
644
+ return PROFILE_HEADINGS[normalized][role]
645
+ except KeyError as exc:
646
+ raise AdrFormatError(f"unknown ADR semantic role: {role}") from exc
647
+
648
+
649
+ def required_heading_names(profile: str) -> List[str]:
650
+ normalized = normalize_profile(profile)
651
+ return [heading(normalized, role) for role in PROFILE_REQUIRED_ROLES[normalized]]
652
+
653
+
654
+ def required_headings(profile: str) -> List[str]:
655
+ return [f"## {name}" for name in required_heading_names(profile)]
656
+
657
+
658
+ def profile_for_text(text: str, *, fallback: Optional[str] = None) -> str:
659
+ profile = detect_profile(text)
660
+ if profile in SUPPORTED_PROFILES:
661
+ return profile
662
+ if profile == "unknown" and fallback is not None:
663
+ return normalize_profile(fallback)
664
+ raise AdrFormatError(
665
+ f"ADR body format is {profile}; add frontmatter format: "
666
+ + " | ".join(SUPPORTED_PROFILES)
667
+ + " or migrate the document"
668
+ )
669
+
670
+
671
+ def section_text(
672
+ text: str,
673
+ role: str,
674
+ *,
675
+ profile: Optional[str] = None,
676
+ tolerant: bool = True,
677
+ ) -> str:
678
+ profiles: List[str] = []
679
+ if profile is not None:
680
+ profiles.append(normalize_profile(profile))
681
+ else:
682
+ detected = detect_profile(text)
683
+ if detected in SUPPORTED_PROFILES:
684
+ profiles.append(detected)
685
+ if tolerant:
686
+ profiles.extend(p for p in SUPPORTED_PROFILES if p not in profiles)
687
+
688
+ names: List[str] = []
689
+ for item in profiles:
690
+ name = heading(item, role)
691
+ if name not in names:
692
+ names.append(name)
693
+ for name in names:
694
+ match = re.search(
695
+ rf"^##\s+{re.escape(name)}\s*$\n(.*?)(?=^##\s+|\Z)",
696
+ text,
697
+ re.IGNORECASE | re.MULTILINE | re.DOTALL,
698
+ )
699
+ if match:
700
+ return match.group(1).strip()
701
+ return ""
702
+
703
+
704
+ def replace_role_heading(text: str, role: str, source: str, target: str) -> str:
705
+ old = heading(source, role)
706
+ new = heading(target, role)
707
+ if old == new:
708
+ return text
709
+ return re.sub(
710
+ rf"^(##\s+){re.escape(old)}(\s*)$",
711
+ rf"\g<1>{new}\g<2>",
712
+ text,
713
+ count=1,
714
+ flags=re.IGNORECASE | re.MULTILINE,
715
+ )
716
+
717
+
718
+ def has_role_heading(text: str, profile: str, role: str) -> bool:
719
+ expected = heading(profile, role).casefold()
720
+ return any(item.casefold() == expected for item in h2_headings(text))
721
+
722
+
723
+ def _append_missing_role(text: str, profile: str, role: str) -> str:
724
+ placeholders = {
725
+ "drivers": "- TODO: capture the decision drivers.",
726
+ "alternatives": "- TODO: record the considered options.",
727
+ "related": "- None.",
728
+ "references": "- TODO: add verifiable references.",
729
+ }
730
+ content = placeholders.get(role, f"TODO: migrate the {role} content.")
731
+ block = f"## {heading(profile, role)}\n\n{content}\n\n"
732
+ enforcement = re.search(r"^##\s+Enforcement\s*$", text, re.MULTILINE)
733
+ if enforcement:
734
+ return text[: enforcement.start()] + block + text[enforcement.start() :]
735
+ return text.rstrip() + "\n\n" + block
736
+
737
+
738
+ def set_frontmatter_profile(text: str, profile: str) -> str:
739
+ normalized = normalize_profile(profile)
740
+ raw = _leading_frontmatter(text)
741
+ if not raw:
742
+ raise AdrFormatError("canonical frontmatter is required before format conversion")
743
+ if _FORMAT_LINE_RE.search(raw):
744
+ return _FORMAT_LINE_RE.sub(f'format: "{normalized}"', text, count=1)
745
+ closing = text.find("\n---", 3)
746
+ if closing == -1:
747
+ raise AdrFormatError("unterminated frontmatter")
748
+ return text[:closing] + f'\nformat: "{normalized}"' + text[closing:]
749
+
750
+
751
+ def convert_profile(
752
+ text: str,
753
+ target: str,
754
+ *,
755
+ source: Optional[str] = None,
756
+ ) -> Tuple[str, str]:
757
+ target_profile = normalize_profile(target)
758
+ source_profile = normalize_profile(source) if source else profile_for_text(text)
759
+ declared = declared_profile(text)
760
+ if (
761
+ source is not None
762
+ and declared in SUPPORTED_PROFILES
763
+ and declared != source_profile
764
+ ):
765
+ raise AdrFormatError(
766
+ f"--from-profile {source_profile!r} conflicts with declared "
767
+ f"format {declared!r}"
768
+ )
769
+ missing_core = [
770
+ role
771
+ for role in ("context", "decision", "consequences")
772
+ if not has_role_heading(text, source_profile, role)
773
+ ]
774
+ if missing_core:
775
+ raise AdrFormatError(
776
+ f"{source_profile} source is missing required semantic section(s): "
777
+ + ", ".join(missing_core)
778
+ )
779
+ converted = text
780
+ for role in ("context", "drivers", "alternatives", "decision", "consequences"):
781
+ converted = replace_role_heading(converted, role, source_profile, target_profile)
782
+ for role in PROFILE_REQUIRED_ROLES[target_profile]:
783
+ if not has_role_heading(converted, target_profile, role):
784
+ converted = _append_missing_role(converted, target_profile, role)
785
+ converted = set_frontmatter_profile(converted, target_profile)
786
+ return converted, source_profile