@rvdbreemen/adr-kit-opencode 0.56.0 → 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.56.0",
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
@@ -314,7 +314,7 @@ For another project, use the published package:
314
314
  ```json
315
315
  {
316
316
  "$schema": "https://opencode.ai/config.json",
317
- "plugin": ["@rvdbreemen/adr-kit-opencode@0.56.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.56.0
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.56.0
688
+ rev: v0.57.0
689
689
  hooks:
690
690
  - id: adr-judge
691
691
  ```
package/bin/adr CHANGED
@@ -387,19 +387,49 @@ def ensure_status_history(
387
387
  """
388
388
  if HISTORY_START_RE.search(body):
389
389
  return body
390
+
390
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
+
391
414
  if (status, when) == pending:
392
- # 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.
393
417
  return body
418
+
394
419
  return append_status_history(
395
420
  body,
396
421
  status,
397
422
  # The actor genuinely was never recorded. Naming the current user or
398
423
  # "adr-kit" would put a signature on a transition neither performed.
399
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).
400
430
  "Recovered from the record as it stood before this transition; this "
401
431
  "ADR predates the status_history convention. The actor was never "
402
- "recorded and is not guessed here.",
432
+ "recorded and is not guessed here. The Status line read: " + line,
403
433
  "unrecorded",
404
434
  when,
405
435
  )
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)
package/bin/adr_format.py CHANGED
@@ -828,6 +828,79 @@ def has_role_heading(text: str, profile: str, role: str) -> bool:
828
828
  return any(item.casefold() == expected for item in h2_headings(text))
829
829
 
830
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
+
831
904
  def _append_missing_role(text: str, profile: str, role: str) -> str:
832
905
  placeholders = {
833
906
  "drivers": "- TODO: capture the decision drivers.",
@@ -47,6 +47,7 @@ def rank_proposed(report: dict) -> list[dict]:
47
47
  linked = bool(isinstance(link, dict) and link.get("linked"))
48
48
  shipped = bool(item.get("documents_shipped"))
49
49
  ready = item.get("classification") == "ready-for-confirmation"
50
+ needs_human = item.get("classification") == "needs-human-input"
50
51
  open_questions = bool(item.get("open_questions"))
51
52
  age_days = _age_days(item, evaluated_on)
52
53
  quality = item.get("quality", {})
@@ -67,7 +68,14 @@ def rank_proposed(report: dict) -> list[dict]:
67
68
  # Proposed ADR that is sharp, unlinked, unshipped, not ready and asking
68
69
  # nothing has no work attached to it, and listing it teaches the reader
69
70
  # to skim the queue.
70
- signals = (linked, shipped, ready, open_questions, below_threshold)
71
+ # `needs_human` is here because the classification it names is the one
72
+ # that used to be `ready-for-confirmation`. A record whose References
73
+ # hold only a migration placeholder is unlinked, unshipped, above the
74
+ # quality threshold and asks no open question, so `ready` was its only
75
+ # signal; reporting the placeholder honestly would otherwise drop it out
76
+ # of the queue and make it LESS visible than saying nothing. Measured on
77
+ # ADR-042 with a placeholder: 0 candidates without this line.
78
+ signals = (linked, shipped, ready, open_questions, below_threshold, needs_human)
71
79
  if not any(signals):
72
80
  continue
73
81
 
@@ -80,6 +88,11 @@ def rank_proposed(report: dict) -> list[dict]:
80
88
  reasons.append("ready for confirmation")
81
89
  if open_questions:
82
90
  reasons.append("open human questions")
91
+ if needs_human and not open_questions:
92
+ # Before the unconditional age entry on purpose: the SessionStart
93
+ # block prints reasons[:2] and the auto-grill handoff reasons[:3],
94
+ # so a reason appended after it never reaches a human.
95
+ reasons.append("human input needed")
83
96
  if below_threshold:
84
97
  reasons.append(f"quality {quality_score:.3f} below {threshold:.2f}")
85
98
  reasons.append(f"age {age_days} days")
@@ -98,6 +111,7 @@ def rank_proposed(report: dict) -> list[dict]:
98
111
  -int(shipped),
99
112
  -int(ready),
100
113
  -int(open_questions),
114
+ -int(needs_human),
101
115
  -int(below_threshold),
102
116
  -age_days,
103
117
  quality_score,
@@ -190,6 +190,15 @@ def _section_text(content: str, heading: str) -> str:
190
190
  return m.group(1) if m else ""
191
191
 
192
192
 
193
+ # Same rule as bin/adr-lint: a heading with nothing under it is a hole, not a
194
+ # section. Emptiness only. A migration placeholder counts as content here by
195
+ # decision, not by oversight: an imported record must not fail a blocking gate
196
+ # on arrival (test_adr_policy.py, test_migration_discovery.py). adr-migrate
197
+ # reports the placeholders it wrote instead, which informs without refusing.
198
+ def _is_unfilled(body: str) -> bool:
199
+ return not any(ln.strip() for ln in body.splitlines())
200
+
201
+
193
202
  def gate_completeness(content: str) -> Dict:
194
203
  """Gate 1: Completeness (0.0-1.0).
195
204
 
@@ -216,9 +225,17 @@ def gate_completeness(content: str) -> Dict:
216
225
  pattern = _SECTION_PRESENCE_RE.get(section) or re.compile(
217
226
  r"^" + re.escape(section) + r"\b", re.MULTILINE
218
227
  )
228
+ # A heading with nothing under it is not a section (TASK-198). This loop
229
+ # used to test presence alone, while three checks further down already
230
+ # measured emptiness for Decision, Alternatives and Consequences. That
231
+ # split meant References or Related Decisions could be hollow and still
232
+ # score full marks here, and `adr accept --quality-threshold` reads this
233
+ # score. The placeholder case counts too: it is what adr-migrate writes
234
+ # into a heading it has to add.
219
235
  present = bool(pattern.search(content))
220
- checks[f"section_{section.replace('## ', '').replace(' ', '_').lower()}"] = present
221
- if not present:
236
+ filled = present and not _is_unfilled(_section_text(content, section))
237
+ checks[f"section_{section.replace('## ', '').replace(' ', '_').lower()}"] = filled
238
+ if not filled:
222
239
  missing_sections.append(section)
223
240
 
224
241
  score = 1.0
@@ -9,7 +9,7 @@ from pathlib import Path
9
9
  from typing import Dict, List, Optional, Sequence
10
10
 
11
11
  from adr_catalog import build_relationships, load_adr_records, normalize_adr_id
12
- from adr_format import all_open_questions
12
+ from adr_format import AdrFormatError, all_open_questions, placeholder_required_sections
13
13
  from adr_quality_core import QUALITY_THRESHOLD, score_path
14
14
 
15
15
 
@@ -85,6 +85,7 @@ FINDING_CODES = (
85
85
  "FORMAT_UNKNOWN",
86
86
  "FRONTMATTER_MALFORMED",
87
87
  "OPEN_QUESTION",
88
+ "SECTION_PLACEHOLDER_ONLY",
88
89
  "STATUS_UNKNOWN",
89
90
  "SUPERSESSION_STATE_INCONSISTENT",
90
91
  "VERIFIED_IN_CHANGED",
@@ -252,6 +253,62 @@ def _mechanical_findings(record: Dict) -> List[Dict[str, str]]:
252
253
  return sorted(findings, key=lambda item: item["code"])
253
254
 
254
255
 
256
+ def _record_path(record: Dict, adr_dir: Optional[Path] = None) -> Optional[Path]:
257
+ """Resolve a record's bare filename against the ADR directory, or None.
258
+
259
+ Records reach readiness with `path` set to a filename and no directory, and
260
+ the test suite passes records whose file does not exist at all. Both are
261
+ normal, so this answers "no path" rather than raising.
262
+ """
263
+ raw = record.get("path")
264
+ if not raw:
265
+ return None
266
+ path = Path(str(raw))
267
+ if not path.is_absolute() and adr_dir is not None and not path.exists():
268
+ path = Path(adr_dir) / path.name
269
+ return path if path.is_file() else None
270
+
271
+
272
+ def _placeholder_findings(
273
+ record: Dict, adr_dir: Optional[Path] = None
274
+ ) -> List[Dict[str, str]]:
275
+ """Required sections holding an adr-kit placeholder instead of an answer.
276
+
277
+ A migrated record reaches acceptance with `- TODO: add verifiable
278
+ references.` under `## References` and nothing refuses it: the completeness
279
+ gate treats a placeholder as content by decision, because an imported record
280
+ must not fail a blocking gate on arrival. The record then classifies
281
+ `ready-for-confirmation`, which is a lie about a record nobody has finished
282
+ writing. Saying so here reaches the operator before `adr accept` freezes it,
283
+ and readiness has no power to block, which is the point.
284
+
285
+ Empty sections are deliberately not reported: `bin/adr-lint` already fails
286
+ completeness on those, so acceptance refuses them without help.
287
+ """
288
+ path = _record_path(record, adr_dir)
289
+ if path is None:
290
+ return []
291
+ try:
292
+ text = path.read_text(encoding="utf-8", errors="replace")
293
+ except OSError:
294
+ return []
295
+ try:
296
+ sections = placeholder_required_sections(text, str(record.get("format", "")))
297
+ except AdrFormatError:
298
+ # 'hybrid' and 'unknown' are legal values of record["format"], and
299
+ # neither resolves to a required-section list. Nothing to say, and
300
+ # raising here would be invisible: bin/adr-guardian swallows the
301
+ # exception and returns 0, so the queue would just go stale.
302
+ return []
303
+ return [
304
+ {
305
+ "code": "SECTION_PLACEHOLDER_ONLY",
306
+ "message": f"## {title} holds a migration placeholder, not an answer.",
307
+ }
308
+ for title in sorted(sections)
309
+ ]
310
+
311
+
255
312
  def _classification(
256
313
  record: Dict,
257
314
  mechanical: Sequence[Dict[str, str]],
@@ -293,6 +350,7 @@ def readiness_for_record(
293
350
  }
294
351
  for question in record.get("open_questions", [])
295
352
  ]
353
+ human.extend(_placeholder_findings(record, adr_dir))
296
354
  # Three booleans used to stand in for quality here, which meant a vague ADR
297
355
  # and a sharp one scored identically as long as both had a decision line and
298
356
  # a verified_in. The real weighted scorer existed the whole time behind
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rvdbreemen/adr-kit-opencode",
3
- "version": "0.56.0",
3
+ "version": "0.57.0",
4
4
  "description": "Native OpenCode plugin for ADR Kit, backed by the shared deterministic Python engines.",
5
5
  "type": "module",
6
6
  "main": "./opencode/plugin.ts",
@@ -0,0 +1,198 @@
1
+ #!/usr/bin/env python3
2
+ """Refuse a CHANGELOG entry appended to a section that has already shipped.
3
+
4
+ `release-publish.yml` publishes a `## [X.Y.Z]` section verbatim as the GitHub
5
+ Release body, `bump-version.py` inserts the next release heading directly under
6
+ the `## [Unreleased]` marker, and `release_phases.py` reads a section from its
7
+ heading to the next `^## [`. Section membership is therefore positional, and a
8
+ bullet written under a released heading is lost twice over: it never reaches the
9
+ next release's notes, and the release that already shipped claims work it does
10
+ not contain. That happened twice, through two separate pull requests, and no
11
+ gate saw it: both diffs carry `### Fixed` as unchanged context, so the fragment
12
+ reads exactly like a correct addition unless you map the line numbers back to
13
+ the nearest `## [` heading.
14
+
15
+ WHY THIS COUNTS BULLETS RATHER THAN COMPARING TEXT. Editing a released section
16
+ is legitimate and this project does it: measured over 59 comparable sections,
17
+ six differ from their tag, and every one is a correction rather than an
18
+ addition -- a wrong count fixed from "Nine" to "Ten", a superseded npm claim
19
+ rewritten, two whitespace reflows, two rewordings. A byte-identity rule would
20
+ fail all six. Comparing bullet text fails four of them too, because a reworded
21
+ first line reads as a new bullet. The count is what separates correcting a
22
+ released note from appending to it.
23
+
24
+ Sections whose tag carries no CHANGELOG.md, and early releases made before the
25
+ tagging convention, cannot be compared at all. They are skipped and counted in
26
+ the output rather than passed silently, because a gate that reports "checked"
27
+ while checking nothing is the failure this whole file exists to prevent.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import argparse
33
+ import re
34
+ import subprocess
35
+ import sys
36
+ from pathlib import Path
37
+ from typing import Callable, Dict, List, Optional, Tuple
38
+
39
+ ROOT = Path(__file__).resolve().parents[1]
40
+ CHANGELOG = ROOT / "CHANGELOG.md"
41
+
42
+ RELEASE_HEADING = re.compile(r"^## \[(\d+\.\d+\.\d+)\]", re.MULTILINE)
43
+ TOP_LEVEL_BULLET = re.compile(r"^- \S")
44
+
45
+
46
+ def section(text: str, version: str) -> Optional[str]:
47
+ """The body under `## [version]`, up to the next release heading.
48
+
49
+ Deliberately the same shape as `release_phases._changelog_section`, because
50
+ a gate that reads a section differently from the tool that publishes it
51
+ would pass exactly the documents that break at release time.
52
+ """
53
+ match = re.search(
54
+ rf"^## \[{re.escape(version)}\][^\n]*\n(.*?)(?=^## \[|\Z)",
55
+ text,
56
+ re.MULTILINE | re.DOTALL,
57
+ )
58
+ return match.group(1) if match else None
59
+
60
+
61
+ def bullet_count(section_text: str) -> int:
62
+ """Top-level list items: the unit an author adds, unlike reflowed prose."""
63
+ return sum(1 for line in section_text.splitlines() if TOP_LEVEL_BULLET.match(line))
64
+
65
+
66
+ def appended_bullets(section_text: str, published_text: str) -> List[str]:
67
+ """The bullets present now that were not there at the tag.
68
+
69
+ Returned for the message only. The verdict is the count, so a reworded
70
+ bullet is not reported as an addition; this names the likely culprits by
71
+ taking the ones whose text is new, and falls back to the tail when every
72
+ bullet was reworded.
73
+ """
74
+ was = [line for line in published_text.splitlines() if TOP_LEVEL_BULLET.match(line)]
75
+ now = [line for line in section_text.splitlines() if TOP_LEVEL_BULLET.match(line)]
76
+ fresh = [line for line in now if line not in was]
77
+ gained = len(now) - len(was)
78
+ return fresh[:gained] if len(fresh) >= gained else now[-gained:]
79
+
80
+
81
+ def check(
82
+ current: str, published_for: Callable[[str], Optional[str]]
83
+ ) -> Tuple[List[Dict[str, object]], int, List[str]]:
84
+ """Compare every release section against the same section at its tag.
85
+
86
+ `published_for` returns the CHANGELOG.md at tag `vX.Y.Z`, or None when that
87
+ tag is unusable. Injected rather than called directly so the rule can be
88
+ tested without a git history, which the test matrix does not fetch.
89
+ """
90
+ findings: List[Dict[str, object]] = []
91
+ compared = 0
92
+ skipped: List[str] = []
93
+ for version in RELEASE_HEADING.findall(current):
94
+ published = published_for(version)
95
+ was = section(published, version) if published is not None else None
96
+ now = section(current, version)
97
+ if was is None or now is None:
98
+ skipped.append(version)
99
+ continue
100
+ compared += 1
101
+ if bullet_count(now) > bullet_count(was):
102
+ findings.append(
103
+ {
104
+ "version": version,
105
+ "was": bullet_count(was),
106
+ "now": bullet_count(now),
107
+ "bullets": appended_bullets(now, was),
108
+ }
109
+ )
110
+ return findings, compared, skipped
111
+
112
+
113
+ def _git(*args: str) -> Optional[str]:
114
+ result = subprocess.run(
115
+ ["git", *args], capture_output=True, text=True, encoding="utf-8", errors="replace"
116
+ )
117
+ return result.stdout if result.returncode == 0 else None
118
+
119
+
120
+ def _published_from_git(tags: set) -> Callable[[str], Optional[str]]:
121
+ # Two spellings ship in this repository: 65 tags read `v0.56.0` and 14
122
+ # older ones read `adr-kit--v0.1.0`. Resolving only the first silently
123
+ # skipped fourteen comparable sections, which is the same kind of
124
+ # overstated coverage this check exists to prevent.
125
+ def resolve(version: str) -> Optional[str]:
126
+ for tag in (f"v{version}", f"adr-kit--v{version}"):
127
+ if tag in tags:
128
+ published = _git("show", f"{tag}:CHANGELOG.md")
129
+ if published is not None:
130
+ return published
131
+ return None
132
+
133
+ return resolve
134
+
135
+
136
+ def report(findings, compared, skipped, stream=None) -> None:
137
+ # Resolved here rather than in the signature: a default bound at import
138
+ # time keeps writing to the stream that existed then, which silently
139
+ # bypasses any caller that replaced it.
140
+ stream = sys.stdout if stream is None else stream
141
+ print(
142
+ f"Compared {compared} released CHANGELOG section(s) against their tag; "
143
+ f"skipped {len(skipped)} with no usable tag.",
144
+ file=stream,
145
+ )
146
+ for finding in findings:
147
+ print(
148
+ f"\nFAIL ## [{finding['version']}] gained "
149
+ f"{finding['now'] - finding['was']} bullet(s) since its tag "
150
+ f"({finding['was']} -> {finding['now']}):",
151
+ file=stream,
152
+ )
153
+ for bullet in finding["bullets"]:
154
+ print(f" {bullet[:100]}", file=stream)
155
+ if findings:
156
+ print(
157
+ "\nThat section already shipped. release-publish.yml publishes it "
158
+ "verbatim as the GitHub Release body, so an entry added here is "
159
+ "absent from the next release's notes and falsely claimed by a "
160
+ "release that does not contain it.\nMove these bullets under "
161
+ "## [Unreleased], into the matching ### Added / ### Changed / "
162
+ "### Fixed heading.",
163
+ file=stream,
164
+ )
165
+
166
+
167
+ def main(argv: Optional[List[str]] = None) -> int:
168
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
169
+ parser.add_argument(
170
+ "--changelog", default=str(CHANGELOG), help="CHANGELOG.md to check"
171
+ )
172
+ args = parser.parse_args(argv)
173
+
174
+ listed = _git("tag")
175
+ if listed is None:
176
+ print(
177
+ "git tag failed: this check needs the tags, so the workflow step "
178
+ "running it must check out with fetch-depth: 0.",
179
+ file=sys.stderr,
180
+ )
181
+ return 2
182
+ tags = set(listed.split())
183
+ if not tags:
184
+ print(
185
+ "No tags in this checkout. The check cannot compare anything, and "
186
+ "reporting success would be a lie; check out with fetch-depth: 0.",
187
+ file=sys.stderr,
188
+ )
189
+ return 2
190
+
191
+ current = Path(args.changelog).read_text(encoding="utf-8")
192
+ findings, compared, skipped = check(current, _published_from_git(tags))
193
+ report(findings, compared, skipped)
194
+ return 1 if findings else 0
195
+
196
+
197
+ if __name__ == "__main__":
198
+ raise SystemExit(main())