@rvdbreemen/adr-kit-opencode 0.55.1 → 0.57.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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "adr-kit",
3
3
  "description": "Architecture Decision Record toolkit for AI coding agents: bootstrap, multi-format authoring, bounded deterministic enforcement, lifecycle workflows, context injection, generated graph indexes, and local health checks.",
4
- "version": "0.55.1",
4
+ "version": "0.57.0",
5
5
  "author": {
6
6
  "name": "Robert van den Breemen",
7
7
  "url": "https://github.com/rvdbreemen"
package/README.md CHANGED
@@ -135,8 +135,8 @@ And because decisions age, a periodic guardian flags drift between code and deci
135
135
  ### One engine, three certified CLIs plus OpenCode
136
136
 
137
137
  ADR Kit ships separate integration payloads for Claude Code CLI, OpenAI Codex
138
- CLI, and the standalone GitHub Copilot CLI. All three carry the same 15
139
- workflows, the same deterministic engines, the same key-free five-tool MCP
138
+ CLI, and the standalone GitHub Copilot CLI. All three carry the same 17
139
+ workflows, the same deterministic engines, the same key-free seven-tool MCP
140
140
  server, and English skill metadata; only the native event surface differs. A
141
141
  separate native OpenCode plugin uses the same engines and adds OpenCode-native
142
142
  config, skills, commands, hooks, compaction context, and MCP registration. The
@@ -241,7 +241,7 @@ required.
241
241
 
242
242
  The Claude integration keeps only its manifest under `.claude-plugin/`.
243
243
  Plugin-root `skills/`, `hooks/hooks.json`, `.mcp.json`, agents, and bundled
244
- executables provide 15 workflows, six bounded hooks, and the five-tool MCP
244
+ executables provide 17 workflows, eight bounded hooks, and the seven-tool MCP
245
245
  server.
246
246
 
247
247
  ### OpenAI Codex
@@ -255,8 +255,8 @@ codex mcp list
255
255
  Codex does not use Claude's `/adr-kit:...` slash-command syntax. ADR Kit
256
256
  workflows appear as namespaced skills: open `/skills`, or invoke
257
257
  `$adr-kit:context`, `$adr-kit:judge`, `$adr-kit:lint`, and the other skills.
258
- The separate `codex/` distribution contains all 15 workflows and the key-free
259
- five-tool MCP server. See the official [Codex skills](https://learn.chatgpt.com/docs/build-skills)
258
+ The separate `codex/` distribution contains all 17 workflows and the key-free
259
+ seven-tool MCP server. See the official [Codex skills](https://learn.chatgpt.com/docs/build-skills)
260
260
  and [plugin](https://learn.chatgpt.com/docs/build-plugins) contracts.
261
261
 
262
262
  ### Standalone GitHub Copilot CLI
@@ -295,7 +295,7 @@ Agents should use these native update commands instead of editing the installed
295
295
  ### OpenCode
296
296
 
297
297
  OpenCode is supported through a separate native plugin package. It uses the
298
- same deterministic Python engines and five-tool MCP server as the certified
298
+ same deterministic Python engines and seven-tool MCP server as the certified
299
299
  clients, while adding OpenCode-native configuration, skills, commands, context,
300
300
  compaction, edit, shell, and session hooks.
301
301
 
@@ -309,12 +309,12 @@ configured:
309
309
  }
310
310
  ```
311
311
 
312
- For another project, use the published package for v0.52.0:
312
+ For another project, use the published package:
313
313
 
314
314
  ```json
315
315
  {
316
316
  "$schema": "https://opencode.ai/config.json",
317
- "plugin": ["@rvdbreemen/adr-kit-opencode@0.52.0"]
317
+ "plugin": ["@rvdbreemen/adr-kit-opencode@0.57.0"]
318
318
  }
319
319
  ```
320
320
 
@@ -671,7 +671,7 @@ jobs:
671
671
  - uses: actions/checkout@v4
672
672
  with:
673
673
  fetch-depth: 0 # both sides of the diff must be available
674
- - uses: rvdbreemen/adr-kit/.github/actions/adr-judge@v0.55.1
674
+ - uses: rvdbreemen/adr-kit/.github/actions/adr-judge@v0.57.0
675
675
  with:
676
676
  adr-dir: docs/adr/
677
677
  ```
@@ -685,7 +685,7 @@ The action also takes `max-diff-bytes` (default 32 MiB, available from the relea
685
685
  ```yaml
686
686
  repos:
687
687
  - repo: https://github.com/rvdbreemen/adr-kit
688
- rev: v0.55.1
688
+ rev: v0.57.0
689
689
  hooks:
690
690
  - id: adr-judge
691
691
  ```
@@ -796,7 +796,7 @@ A plain ADR template gives you a markdown file with sections to fill in. What `a
796
796
  | Enforcement | absent | declarative rules vs every commit and PR, key-free; opt-in LLM judge |
797
797
  | Aging | absent | guardian (drift, missing, stale), retirement audit, trend history, coverage KPI |
798
798
  | Team workflows | absent | CI sweeps with tracking issue, collision-safe numbering, audited overrides, guided supersession |
799
- | Tool integration | none | Claude Code, OpenAI Codex, GitHub Copilot CLI, and OpenCode integrations plus a 5-tool MCP server |
799
+ | Tool integration | none | Claude Code, OpenAI Codex, GitHub Copilot CLI, and OpenCode integrations plus a 7-tool MCP server |
800
800
 
801
801
  If your team is happy with a plain template and the discipline lives in your culture, you do not need this. If you want the discipline to survive contact with an AI agent at 2 a.m., this is what `adr-kit` is for.
802
802
 
package/bin/adr CHANGED
@@ -54,6 +54,7 @@ from adr_format import (
54
54
  normalize_profile,
55
55
  profile_catalog,
56
56
  profile_template_path,
57
+ section_span,
57
58
  unresolved_open_questions,
58
59
  )
59
60
  from adr_schema import (
@@ -102,6 +103,24 @@ def find_adr_file(adr_dir: Path, adr_id: str) -> Path:
102
103
  return matches[0]
103
104
 
104
105
 
106
+ _ADR_RECORD_RE = re.compile(r"(?i)^ADR-\d{1,4}-")
107
+
108
+
109
+ def iter_adr_records(adr_dir: Path):
110
+ """Yield ADR record paths, skipping the generated ADR-INDEX.* artefacts.
111
+
112
+ ``glob("ADR-*.md")`` also matches ``ADR-INDEX.md``, which every lifecycle
113
+ command writes in the same transaction as the record it mutates. Feeding
114
+ that generated file to ``load_adr`` was only ever harmless because the
115
+ frontmatter inference invented ``status: Proposed`` for it. Once inference
116
+ started failing closed instead of guessing (issue #118), the generated
117
+ index became a hard error in the middle of an otherwise valid supersede.
118
+ """
119
+ for path in sorted(adr_dir.glob("ADR-*.md")):
120
+ if _ADR_RECORD_RE.match(path.name):
121
+ yield path
122
+
123
+
105
124
  def load_adr(path: Path) -> Tuple[Dict, str]:
106
125
  text = path.read_text(encoding="utf-8")
107
126
  migrated, _changed, issues = migrate_text(text, path)
@@ -236,6 +255,30 @@ def history_entry(status: str, changed_by: str, reason: str, changed_via: str, w
236
255
  )
237
256
 
238
257
 
258
+ def _splice_after_yaml_block(body: str, pos: int, limit: int, entry: str) -> str:
259
+ """Insert `entry` after the last line of an unfenced ``status_history`` block.
260
+
261
+ A line belongs to the block while it is blank or indented; the first
262
+ unindented non-blank line inside the section ends it. Bounded by `limit`
263
+ so a malformed document cannot walk out of the section.
264
+ """
265
+ newline = body.find("\n", pos)
266
+ insert_at = newline + 1 if newline != -1 and newline < limit else limit
267
+ cursor = insert_at
268
+ while cursor < limit:
269
+ newline = body.find("\n", cursor)
270
+ if newline == -1 or newline >= limit:
271
+ line, end = body[cursor:limit], limit
272
+ else:
273
+ line, end = body[cursor:newline], newline + 1
274
+ if line.strip():
275
+ if not line[:1].isspace():
276
+ break
277
+ insert_at = end
278
+ cursor = end
279
+ return body[:insert_at] + entry + body[insert_at:]
280
+
281
+
239
282
  def append_status_history(
240
283
  body: str,
241
284
  status: str,
@@ -245,11 +288,25 @@ def append_status_history(
245
288
  when: str,
246
289
  ) -> str:
247
290
  entry = history_entry(status, changed_by, reason, changed_via, when)
248
- start = HISTORY_START_RE.search(body)
249
- if start:
250
- closing = body.find("```", start.end())
251
- if closing != -1:
252
- return body[:closing] + entry + body[closing:]
291
+
292
+ # Bound every search to the section the reader parses. This used to search
293
+ # the whole remaining document for the next triple backtick, so an unfenced
294
+ # status_history block sent the entry into the next fenced block instead -
295
+ # the ## Enforcement JSON, on every ADR in this project. The command still
296
+ # exited 0, and the index went on reporting the pre-transition status
297
+ # because the reader only looks inside ## Status History (issue #119).
298
+ span = section_span(body, "history")
299
+ if span is not None:
300
+ section_start, section_end = span
301
+ start = HISTORY_START_RE.search(body, section_start, section_end)
302
+ if start:
303
+ closing = body.find("```", start.end(), section_end)
304
+ if closing != -1:
305
+ return body[:closing] + entry + body[closing:]
306
+ # No fence: append after the last line that belongs to the YAML
307
+ # block. Falling through to the section builder below would append
308
+ # a second ## Status History and invert chronology.
309
+ return _splice_after_yaml_block(body, start.end(), section_end, entry)
253
310
 
254
311
  section = (
255
312
  "\n## Status History\n\n"
@@ -330,19 +387,49 @@ def ensure_status_history(
330
387
  """
331
388
  if HISTORY_START_RE.search(body):
332
389
  return body
390
+
333
391
  status, when = prior_transition(path, data, body)
392
+ match = STATUS_RE.search(body)
393
+ line = match.group(2).strip() if match else ""
394
+
395
+ # read_status_line takes the LEADING word and the FIRST date, so a line
396
+ # carrying two transitions yields only one. When the second date is on the
397
+ # line and nothing accounts for it, the tool does not know what it is about
398
+ # to discard - and set_status_line replaces the whole line. Refuse instead
399
+ # of writing a history that silently omits the earlier transition, which is
400
+ # what templates/adr-kit-guide.md already promises (issue #120).
401
+ extra_dates = [found for found in dict.fromkeys(DATE_RE.findall(line)) if found != when]
402
+ if extra_dates:
403
+ raise AdrLifecycleError(
404
+ f"{path}: the Status line records more than one transition and this "
405
+ f"ADR has no status_history block, so rewriting the line would drop "
406
+ f"the earlier one.\n"
407
+ f" line: {line}\n"
408
+ f" kept: {status} {when}\n"
409
+ f" lost: {', '.join(extra_dates)}\n"
410
+ f"Write the status_history block first, recording each transition the "
411
+ f"line names, then re-run this command. Nothing has been changed."
412
+ )
413
+
334
414
  if (status, when) == pending:
335
- # Same status on the same day: there is no earlier transition to keep.
415
+ # Same status on the same day, and the check above proved the line
416
+ # carries nothing else: there is genuinely no earlier transition here.
336
417
  return body
418
+
337
419
  return append_status_history(
338
420
  body,
339
421
  status,
340
422
  # The actor genuinely was never recorded. Naming the current user or
341
423
  # "adr-kit" would put a signature on a transition neither performed.
342
424
  "unknown",
425
+ # The literal line goes in verbatim. Parsing every prose shape a Status
426
+ # line can take is how transitions get lost one shape at a time; keeping
427
+ # the words costs nothing and loses nothing, even where the structure
428
+ # cannot be recovered. history_entry quotes this through _yaml_scalar,
429
+ # so a line containing ": " cannot break the block (TASK-70).
343
430
  "Recovered from the record as it stood before this transition; this "
344
431
  "ADR predates the status_history convention. The actor was never "
345
- "recorded and is not guessed here.",
432
+ "recorded and is not guessed here. The Status line read: " + line,
346
433
  "unrecorded",
347
434
  when,
348
435
  )
@@ -1037,7 +1124,7 @@ def command_supersede(args) -> List[str]:
1037
1124
  # decision can legitimately retire more than one record. What stays
1038
1125
  # exclusive is the other direction, enforced below: each predecessor gets
1039
1126
  # exactly one successor.
1040
- for candidate in sorted(adr_dir.glob("ADR-*.md")):
1127
+ for candidate in iter_adr_records(adr_dir):
1041
1128
  if candidate in {old_path, new_path}:
1042
1129
  continue
1043
1130
  candidate_data, _candidate_body = load_adr(candidate)
@@ -1318,7 +1405,7 @@ def command_signer(args) -> List[str]:
1318
1405
 
1319
1406
  if args.audit:
1320
1407
  offenders = []
1321
- for path in sorted(adr_dir.glob("ADR-*.md")):
1408
+ for path in iter_adr_records(adr_dir):
1322
1409
  try:
1323
1410
  body = path.read_text(encoding="utf-8")
1324
1411
  except OSError:
package/bin/adr-lint CHANGED
@@ -494,12 +494,50 @@ def scan_extra_migration_notices(
494
494
  return notices
495
495
 
496
496
 
497
+ def _section_body(text: str, heading: str) -> Optional[str]:
498
+ """Return the text between `heading` and the next H2, or None if absent."""
499
+ match = _section_pattern(heading).search(text)
500
+ if match is None:
501
+ return None
502
+ rest = text[match.end():]
503
+ nxt = re.search(r"^##\s", rest, re.MULTILINE)
504
+ return rest[: nxt.start()] if nxt else rest
505
+
506
+
507
+ def _is_unfilled(body: str) -> bool:
508
+ """True when a required section has nothing under its heading at all.
509
+
510
+ Emptiness only, deliberately. A migration placeholder is content for this
511
+ gate's purposes: ADR-policy already decided that an imported record must not
512
+ fail a blocking gate on arrival, because a team that hits a wall on import
513
+ turns the gate off instead of filling the section in. That decision is
514
+ pinned by test_adr_policy.py and test_migration_discovery.py, and this gate
515
+ is not the place to reopen it. adr-migrate names the placeholders it wrote,
516
+ which is the migrating team's to-do list rather than a refusal.
517
+ """
518
+ return not any(ln.strip() for ln in body.splitlines())
519
+
520
+
497
521
  def gate_completeness(text: str, required: List[str]) -> Optional[List[str]]:
498
- """Return list of missing required headings, or None if all present."""
522
+ """Return required sections that are absent or unfilled, or None if all present.
523
+
524
+ A heading on its own is not a section. The skill contract has always said a
525
+ passing ADR carries every load-bearing section "with non-empty content";
526
+ checking only for the heading meant an empty one passed, and `bin/adr accept`
527
+ runs this gate with --strict, so that was enough to accept a record with no
528
+ verifiable reference at all.
529
+
530
+ The returned entry keeps the `## ` prefix the caller strips, and appends a
531
+ reason for anything that is present but hollow, so a reader can tell "you
532
+ never wrote this" from "you left the placeholder in".
533
+ """
499
534
  missing = []
500
535
  for s in required:
501
- if not _section_pattern(s).search(text):
536
+ body = _section_body(text, s)
537
+ if body is None:
502
538
  missing.append(s)
539
+ elif _is_unfilled(body):
540
+ missing.append(f"{s} (present but empty)")
503
541
  return missing or None
504
542
 
505
543
 
package/bin/adr-migrate CHANGED
@@ -62,6 +62,7 @@ from adr_format import (
62
62
  is_migration_candidate,
63
63
  migration_notice,
64
64
  normalize_profile,
65
+ unfilled_required_sections,
65
66
  )
66
67
  from adr_schema import migrate_text
67
68
  from adr_catalog import load_adr_record
@@ -166,12 +167,23 @@ def migrate_file(
166
167
 
167
168
  after, changed, issues = migrate_text(before, path)
168
169
  detected_source = None
170
+ unfilled: List[str] = []
169
171
  if not issues and to_profile is not None:
170
172
  try:
171
173
  after, detected_source = convert_profile(
172
174
  after, to_profile, source=from_profile
173
175
  )
174
176
  changed = after != before
177
+ # A conversion that adds a missing heading writes a TODO placeholder
178
+ # into it. That is a hole, not content, and saying nothing about it
179
+ # is how a migrated record reaches `adr accept` still unwritten.
180
+ # Report only what THIS run left unfilled, so a hole the author
181
+ # already had is not blamed on the migration.
182
+ unfilled = [
183
+ s
184
+ for s in unfilled_required_sections(after, to_profile)
185
+ if s not in unfilled_required_sections(before, to_profile)
186
+ ]
175
187
  except AdrFormatError as exc:
176
188
  issues = [str(exc)]
177
189
  if not issues and changed and write:
@@ -192,6 +204,7 @@ def migrate_file(
192
204
  "issues": issues,
193
205
  "source_profile": detected_source,
194
206
  "target_profile": to_profile,
207
+ "unfilled_sections": unfilled,
195
208
  }
196
209
 
197
210
 
@@ -203,14 +216,29 @@ def render_text(target: Path, results: List[Dict], check: bool, dry_run: bool) -
203
216
  f"adr-migrate {mode}: {target}",
204
217
  f"Files: {len(results)}; changed: {len(changed)}; failed: {len(failed)}",
205
218
  ]
219
+ unfilled_any = False
206
220
  for result in results:
207
221
  if result["changed"]:
208
222
  prefix = "needs migration" if check or dry_run else "migrated"
209
223
  lines.append(f" {prefix}: {result['file']}")
224
+ # Say what the conversion could not write for you. A required section
225
+ # that still carries a TODO placeholder reads as complete to anything
226
+ # counting headings, so leaving this unsaid is what lets an unfinished
227
+ # record reach acceptance.
228
+ for section in result.get("unfilled_sections") or []:
229
+ unfilled_any = True
230
+ lines.append(f" needs content: ## {section}")
210
231
  if result["issues"]:
211
232
  lines.append(f" failed: {result['file']}")
212
233
  for issue in result["issues"]:
213
234
  lines.append(f" {issue}")
235
+ if unfilled_any:
236
+ lines.append(
237
+ "Sections marked 'needs content' hold a placeholder, not an answer. "
238
+ "Nothing blocks on that: an imported record must not fail a gate on "
239
+ "arrival. adr-readiness reports it and adr accept will not refuse, "
240
+ "so write them before you accept."
241
+ )
214
242
  if not results:
215
243
  lines.append("No ADR files found.")
216
244
  return "\n".join(lines)
@@ -13,7 +13,11 @@ from pathlib import Path
13
13
  from typing import Dict, Iterable, List, Optional
14
14
 
15
15
  from adr_format import (
16
+ STATUS_BODY_LINE_RE,
17
+ STATUS_BOLD_INLINE_RE,
18
+ STATUS_HEADING_RE,
16
19
  SUPPORTED_PROFILES,
20
+ adr_status,
17
21
  detect_profile,
18
22
  section_text,
19
23
  unresolved_open_questions,
@@ -42,44 +46,18 @@ ENFORCEMENT_BLOCK_RE = re.compile(
42
46
  re.IGNORECASE | re.MULTILINE | re.DOTALL,
43
47
  )
44
48
 
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
- )
49
+ # The status reader and its shapes moved to adr_format so adr_schema can use
50
+ # the same one when it INFERS frontmatter; adr_catalog imports adr_schema, so
51
+ # the dependency could not run the other way (issue #118). Re-exported here
52
+ # under their original names because bin/adr-lint imports them from this
53
+ # module. STATUS_LINE_RE is the body-line form; adr_format keeps a private
54
+ # _STATUS_LINE_RE for frontmatter detection, which is a different question.
55
+ #
53
56
  # Superset of the two historical single-line variants so every tool agrees on
54
57
  # whether an ADR is Accepted: colon optional, leading indentation tolerated,
55
58
  # same line only. Recognizes "Status: Accepted", " Status: Accepted", and
56
59
  # "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
60
+ STATUS_LINE_RE = STATUS_BODY_LINE_RE
83
61
 
84
62
 
85
63
  def normalize_adr_id(raw: object) -> Optional[str]:
package/bin/adr_format.py CHANGED
@@ -125,6 +125,86 @@ _FORMAT_LINE_RE = re.compile(
125
125
  r"^\s*format\s*:\s*[\"']?([a-z-]+)[\"']?\s*$", re.IGNORECASE | re.MULTILINE
126
126
  )
127
127
  _STATUS_LINE_RE = re.compile(r"^\s*status\s*:", re.IGNORECASE | re.MULTILINE)
128
+
129
+ # The body-status reader, and the shapes it accepts. These live here rather
130
+ # than in adr_catalog because adr_schema needs them too and adr_catalog imports
131
+ # adr_schema, not the other way round. adr_catalog re-exports them, so the
132
+ # tools that already import them from there are unaffected.
133
+ STATUS_HEADING_RE = re.compile(
134
+ r"^##\s+Status\s*$\n+([^\n]+)", re.IGNORECASE | re.MULTILINE
135
+ )
136
+ STATUS_BOLD_INLINE_RE = re.compile(
137
+ r"^\s*\*\*\s*Status\s*:?\s*\*\*\s*:?\s*([A-Za-z]+)"
138
+ r"|^\s*\*\*\s*Status\s*:?\s*([A-Za-z]+)\s*\*\*",
139
+ re.IGNORECASE | re.MULTILINE,
140
+ )
141
+ STATUS_BODY_LINE_RE = re.compile(
142
+ r"^[ \t]*Status[ \t]*:?[ \t]*([A-Za-z]+)", re.IGNORECASE | re.MULTILINE
143
+ )
144
+ _STATUS_LEADING_WORD_RE = re.compile(r"\s*([A-Za-z]+)")
145
+
146
+
147
+ def adr_status(text: str) -> Optional[str]:
148
+ """Return the leading ADR status word, or None.
149
+
150
+ The single cross-tool status reader used by adr-index, adr-judge, adr-lint,
151
+ adr-retire, adr-watch and, since issue #118, the frontmatter inference that
152
+ ``adr-migrate`` writes with. A ``## Status`` heading body wins, then a
153
+ bold-inline ``**Status:** X`` form, then a plain ``Status: X`` line. The
154
+ line form is a deliberate superset of the older per-tool regexes so those
155
+ tools can never disagree on an ADR's status.
156
+
157
+ It returns None rather than guessing. That is the whole point: the writer
158
+ used to default to ``"Proposed"`` on a shape it could not read, which
159
+ silently downgraded Accepted records and stopped them being injected.
160
+ Authoritative lifecycle status still comes from the status_history chain in
161
+ ``load_adr_record``; this is the lightweight reader used by gates and
162
+ listings.
163
+ """
164
+ match = STATUS_HEADING_RE.search(text)
165
+ if match:
166
+ word = _STATUS_LEADING_WORD_RE.match(match.group(1))
167
+ return word.group(1) if word else None
168
+ match = STATUS_BOLD_INLINE_RE.search(text)
169
+ if match:
170
+ return match.group(1) or match.group(2)
171
+ match = STATUS_BODY_LINE_RE.search(text)
172
+ return match.group(1) if match else None
173
+
174
+
175
+ def status_statement(text: str) -> str:
176
+ """Return the whole line the status was read from, or an empty string.
177
+
178
+ The status word and the facts printed beside it - the date, the successor -
179
+ sit on the same line, so they must be recovered from the same region.
180
+ Reading the word from one shape and the successor from another is why
181
+ ``superseded_by`` came back None on records whose status reads
182
+ ``**Status:** Superseded by ADR-046``: the word was found, and the
183
+ successor was looked for in a ``## Status`` section those records do not
184
+ have (issue #118).
185
+ """
186
+ match = STATUS_HEADING_RE.search(text)
187
+ if match:
188
+ return match.group(1).strip()
189
+ for pattern in (STATUS_BOLD_INLINE_RE, STATUS_BODY_LINE_RE):
190
+ match = pattern.search(text)
191
+ if match:
192
+ # Anchor on the captured status word, not on match.start(): these
193
+ # patterns begin with `^\s*`, and `\s` eats the preceding newline,
194
+ # so match.start() can sit on the line ABOVE the status and slice
195
+ # out an empty string.
196
+ pos = next(
197
+ (
198
+ match.start(group)
199
+ for group in range(1, (match.lastindex or 0) + 1)
200
+ if match.group(group) is not None
201
+ ),
202
+ match.end(),
203
+ )
204
+ line_start = text.rfind("\n", 0, pos) + 1
205
+ line_end = text.find("\n", pos)
206
+ return text[line_start : line_end if line_end != -1 else len(text)].strip()
207
+ return ""
128
208
  _CANONICAL_FILENAME_RE = re.compile(
129
209
  r"^ADR-\d{3,4}-[a-z0-9]+(?:-[a-z0-9]+)*\.md$",
130
210
  re.IGNORECASE,
@@ -668,13 +748,28 @@ def profile_for_text(text: str, *, fallback: Optional[str] = None) -> str:
668
748
  )
669
749
 
670
750
 
671
- def section_text(
751
+ def section_span(
672
752
  text: str,
673
753
  role: str,
674
754
  *,
675
755
  profile: Optional[str] = None,
676
756
  tolerant: bool = True,
677
- ) -> str:
757
+ ) -> Optional[Tuple[int, int]]:
758
+ """Return the (start, end) offsets of a section's body, or None.
759
+
760
+ ``section_text`` answers *what* a section says; this answers *where* it
761
+ says it, which is what a writer needs in order to place something inside
762
+ the bounds the reader will later parse. Both go through this one matcher,
763
+ so a writer cannot put content where the reader does not look.
764
+
765
+ That failure was real: ``append_status_history`` used to find its insertion
766
+ point with ``body.find("```")`` over the whole remaining document, so on an
767
+ ADR whose ``status_history`` block carries no fence the entry landed in the
768
+ next fenced block - in this project, the ``## Enforcement`` JSON. The
769
+ lifecycle command reported success, the frontmatter said ``Accepted``, and
770
+ ``ADR-INDEX.json`` went on reporting ``Proposed`` because the reader only
771
+ ever looks inside ``## Status History`` (issue #119).
772
+ """
678
773
  profiles: List[str] = []
679
774
  if profile is not None:
680
775
  profiles.append(normalize_profile(profile))
@@ -697,8 +792,21 @@ def section_text(
697
792
  re.IGNORECASE | re.MULTILINE | re.DOTALL,
698
793
  )
699
794
  if match:
700
- return match.group(1).strip()
701
- return ""
795
+ return match.start(1), match.end(1)
796
+ return None
797
+
798
+
799
+ def section_text(
800
+ text: str,
801
+ role: str,
802
+ *,
803
+ profile: Optional[str] = None,
804
+ tolerant: bool = True,
805
+ ) -> str:
806
+ span = section_span(text, role, profile=profile, tolerant=tolerant)
807
+ if span is None:
808
+ return ""
809
+ return text[span[0] : span[1]].strip()
702
810
 
703
811
 
704
812
  def replace_role_heading(text: str, role: str, source: str, target: str) -> str:
@@ -720,6 +828,79 @@ def has_role_heading(text: str, profile: str, role: str) -> bool:
720
828
  return any(item.casefold() == expected for item in h2_headings(text))
721
829
 
722
830
 
831
+ # Matched on the marker rather than the exact sentence, so a reworded placeholder
832
+ # still counts, and anchored to a list item or line start so prose that merely
833
+ # mentions a TODO further down the section does not mask a real gap.
834
+ _PLACEHOLDER_LINE_RE = re.compile(r"^\s*(?:[-*+]\s*)?TODO\b", re.IGNORECASE)
835
+ # Two writers, two spellings: `bin/adr-migrate` emits a `- TODO:` list item and
836
+ # the `/adr-kit:migrate` skill emits an HTML comment. `bin/adr-lint` already
837
+ # strips comments before it counts alternatives, and `tests/test_adr_policy.py`
838
+ # pins the two as equivalent, so honouring only one of them made this the odd
839
+ # reader out. A comment is never content a reader sees, whatever it says.
840
+ _HTML_COMMENT_RE = re.compile(r"<!--.*?-->", re.DOTALL)
841
+
842
+ SECTION_EMPTY = "empty"
843
+ SECTION_PLACEHOLDER = "placeholder"
844
+
845
+
846
+ def _unwritten_required_sections(text: str, profile: str) -> List[tuple]:
847
+ """(heading, kind) for each required heading nobody has written yet.
848
+
849
+ The kinds differ in who is owed what. An empty heading fails completeness in
850
+ `bin/adr-lint`, so acceptance already refuses it. A placeholder does not, by
851
+ decision: an imported record must not fail a blocking gate on arrival. Only
852
+ a caller that can tell the two apart can say something true about either.
853
+ """
854
+ normalized = normalize_profile(profile)
855
+ unwritten: List[tuple] = []
856
+ for role in PROFILE_REQUIRED_ROLES[normalized]:
857
+ title = heading(normalized, role)
858
+ match = re.search(
859
+ r"^##\s+" + re.escape(title) + r"\s*$", text, re.MULTILINE
860
+ )
861
+ if match is None:
862
+ continue
863
+ rest = text[match.end():]
864
+ nxt = re.search(r"^##\s", rest, re.MULTILINE)
865
+ body = rest[: nxt.start()] if nxt else rest
866
+ visible = [
867
+ ln for ln in _HTML_COMMENT_RE.sub("", body).splitlines() if ln.strip()
868
+ ]
869
+ if visible and not all(_PLACEHOLDER_LINE_RE.match(ln) for ln in visible):
870
+ continue
871
+ if not visible and not body.strip():
872
+ unwritten.append((title, SECTION_EMPTY))
873
+ else:
874
+ unwritten.append((title, SECTION_PLACEHOLDER))
875
+ return unwritten
876
+
877
+
878
+ def unfilled_required_sections(text: str, profile: str) -> List[str]:
879
+ """Required headings present in `text` that nobody has actually written yet.
880
+
881
+ Covers the empty section and the placeholder section alike, because
882
+ `_append_missing_role` writes the latter: a heading whose body still says
883
+ TODO is a hole the migration opened, not content. Callers use this to tell
884
+ an operator that a migrated record is unfinished, which the write itself
885
+ otherwise does silently.
886
+ """
887
+ return [title for title, _ in _unwritten_required_sections(text, profile)]
888
+
889
+
890
+ def placeholder_required_sections(text: str, profile: str) -> List[str]:
891
+ """Required headings holding an adr-kit placeholder instead of an answer.
892
+
893
+ The narrower half of `unfilled_required_sections`, for the caller that must
894
+ not confuse the two: an empty heading is already refused at acceptance, a
895
+ placeholder is deliberately not, so only this set is news to anyone.
896
+ """
897
+ return [
898
+ title
899
+ for title, kind in _unwritten_required_sections(text, profile)
900
+ if kind == SECTION_PLACEHOLDER
901
+ ]
902
+
903
+
723
904
  def _append_missing_role(text: str, profile: str, role: str) -> str:
724
905
  placeholders = {
725
906
  "drivers": "- TODO: capture the decision drivers.",