@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,304 @@
1
+ #!/usr/bin/env python3
2
+ """Write a release version to every declared version site in one command.
3
+
4
+ This is the canonical bump writer (ADR-013, docs/RELEASING.md). `bin/bump-version`
5
+ delegates here rather than carrying a second implementation of the same release
6
+ step: two writers with different capabilities is what left the CHANGELOG compare
7
+ links unwritten on every release (TASK-139).
8
+
9
+ Releasing used to mean hand-editing the version in nine files, discovered one
10
+ error at a time across several tool runs. This writer takes the version once and
11
+ propagates it everywhere `packaging/version-sites.json` declares, including the
12
+ CHANGELOG release heading, the three client plugin manifests, the two versioned
13
+ marketplace manifests, the template version stamps and the README version pins.
14
+
15
+ Usage:
16
+ python scripts/bump-version.py 0.39.0
17
+ python scripts/bump-version.py 0.39.0 --date 2026-07-23
18
+ python scripts/bump-version.py 0.39.0 --check # report, change nothing
19
+
20
+ After bumping, run `python scripts/build-client-adapters.py` to regenerate the
21
+ codex/ and copilot/ trees, then the release gates.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import argparse
26
+ import json
27
+ import re
28
+ import sys
29
+ from datetime import date as date_cls
30
+ from pathlib import Path
31
+
32
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
33
+
34
+ from version_sites import ( # noqa: E402
35
+ SEMVER,
36
+ VersionSiteError,
37
+ apply_transaction,
38
+ check,
39
+ describe_changes,
40
+ format_findings,
41
+ load_registry,
42
+ plan_writes,
43
+ read_canonical,
44
+ )
45
+
46
+ ROOT = Path(__file__).resolve().parent.parent
47
+ UNRELEASED = re.compile(r"^## \[Unreleased\]\s*$", re.MULTILINE)
48
+ UNRELEASED_LINK = re.compile(r"^\[Unreleased\]:\s+.*$", re.MULTILINE)
49
+ COMPARE = "https://github.com/rvdbreemen/adr-kit/compare"
50
+
51
+ #: Which declared sites carry plugin identity, derived from the registry rather
52
+ #: than from a second list of paths. Moved here from `bin/bump-version` when that
53
+ #: script became a delegation: these were live preflight validations that only
54
+ #: the unnamed writer performed, so the tool the runbook actually names could
55
+ #: bump a tree whose manifests disagreed about the plugin's name (TASK-139).
56
+ PLUGIN_MANIFEST_POINTER = "/version"
57
+ MARKETPLACE_POINTER_RE = re.compile(r"^/plugins/(\d+)/version$")
58
+
59
+
60
+ def _read_json(path: Path):
61
+ try:
62
+ return json.loads(path.read_text(encoding="utf-8"))
63
+ except (OSError, json.JSONDecodeError) as exc:
64
+ raise VersionSiteError(f"{path}: {exc}") from exc
65
+
66
+
67
+ def plugin_identity(registry: dict) -> "tuple[str, str]":
68
+ """The (name, version) every declared client manifest agrees on.
69
+
70
+ Nothing declares a canonical manifest, so agreement is the check: if the
71
+ three disagree on the name, there is no defensible value to write into the
72
+ marketplace entries.
73
+ """
74
+ manifests = [
75
+ site
76
+ for site in registry["sites"]
77
+ if site.get("kind") == "json" and site.get("pointer") == PLUGIN_MANIFEST_POINTER
78
+ ]
79
+ if not manifests:
80
+ raise VersionSiteError(
81
+ "registry declares no client plugin manifest (a JSON site at /version)"
82
+ )
83
+ names: dict = {}
84
+ version = "?"
85
+ for site in manifests:
86
+ data = _read_json(ROOT / site["path"])
87
+ if not isinstance(data, dict) or not isinstance(data.get("version"), str):
88
+ raise VersionSiteError(
89
+ f"{site['path']}: expected an object with a string version field"
90
+ )
91
+ name = data.get("name")
92
+ if not isinstance(name, str) or not name:
93
+ raise VersionSiteError(f"{site['path']}: expected a non-empty string name")
94
+ names.setdefault(name, []).append(site["path"])
95
+ version = data["version"]
96
+ if len(names) > 1:
97
+ detail = "; ".join(f"{n!r} in {', '.join(p)}" for n, p in sorted(names.items()))
98
+ raise VersionSiteError(
99
+ f"all client manifests must use the same plugin name: {detail}"
100
+ )
101
+ return next(iter(names)), version
102
+
103
+
104
+ def check_marketplace_entries(registry: dict, plugin_name: str) -> None:
105
+ """Every marketplace pointer must resolve to the one entry naming this plugin."""
106
+ for site in registry["sites"]:
107
+ match = MARKETPLACE_POINTER_RE.match(str(site.get("pointer", "")))
108
+ if site.get("kind") != "json" or not match:
109
+ continue
110
+ path = ROOT / site["path"]
111
+ index = int(match.group(1))
112
+ document = _read_json(path)
113
+ plugins = document.get("plugins") if isinstance(document, dict) else None
114
+ if not isinstance(plugins, list) or index >= len(plugins):
115
+ raise VersionSiteError(
116
+ f"{site['path']}: {site['pointer']} does not resolve to a plugin entry"
117
+ )
118
+ target = plugins[index]
119
+ if not isinstance(target, dict):
120
+ raise VersionSiteError(
121
+ f"{site['path']}: the entry at {site['pointer']} is not an object"
122
+ )
123
+ if target.get("name") != plugin_name:
124
+ raise VersionSiteError(
125
+ f"no plugin named {plugin_name!r} at {site['pointer']} in "
126
+ f"{site['path']} (found {target.get('name')!r} there)"
127
+ )
128
+ if not isinstance(target.get("version"), str):
129
+ raise VersionSiteError(
130
+ f"{site['path']}: matching plugin entries require string version fields"
131
+ )
132
+ others = [
133
+ position
134
+ for position, entry in enumerate(plugins)
135
+ if position != index
136
+ and isinstance(entry, dict)
137
+ and entry.get("name") == plugin_name
138
+ ]
139
+ if others:
140
+ raise VersionSiteError(
141
+ f"{site['path']}: {plugin_name!r} also appears at index {others}, "
142
+ f"which the pointer {site['pointer']} would leave stale"
143
+ )
144
+
145
+
146
+ def plan_changelog_links(text: str, current: str, version: str) -> str:
147
+ """Retarget `[Unreleased]` and add the `[version]` compare link.
148
+
149
+ The block at the bottom of CHANGELOG.md went stale on every release. The
150
+ runbook runs this script, which had no link logic at all; the only tool that
151
+ could write it was `bin/bump-version`, which the runbook never named. After
152
+ v0.46.0 the block still pointed at v0.45.0 and seven earlier headings had no
153
+ target at all, all backfilled by hand in a31cb04. Hand-backfilling is not a
154
+ fix -- the next release reproduces the gap.
155
+
156
+ Pure, and folded into the same CHANGELOG image as the heading insert, so the
157
+ registry's own `[Unreleased]` site sees this edit rather than the stale
158
+ bytes.
159
+ """
160
+ unreleased = f"[Unreleased]: {COMPARE}/v{version}...HEAD"
161
+ release = f"[{version}]: {COMPARE}/v{current}...v{version}"
162
+ if re.search(rf"^\[{re.escape(version)}\]:", text, re.MULTILINE):
163
+ # Re-running a bump for the same version must not add a second target.
164
+ return UNRELEASED_LINK.sub(unreleased, text, count=1)
165
+ if UNRELEASED_LINK.search(text):
166
+ return UNRELEASED_LINK.sub(f"{unreleased}\n{release}", text, count=1)
167
+ return text.rstrip() + f"\n\n{unreleased}\n{release}\n"
168
+
169
+
170
+ def plan_changelog_heading(version: str, release_date: str) -> "tuple[bytes | None, str]":
171
+ """Compute a CHANGELOG.md carrying `## [version] - date` as the top release.
172
+
173
+ Writes nothing. The bytes join the same transaction as the declared sites,
174
+ because the CHANGELOG heading is the version every other tool reads as
175
+ canonical: writing it first and then failing to write the sites left the
176
+ repository announcing a release that no manifest carried, with no rollback.
177
+
178
+ Returns the new bytes (None when the file already says the right thing) and
179
+ a short description of what happened.
180
+ """
181
+ path = ROOT / "CHANGELOG.md"
182
+ original = path.read_text(encoding="utf-8")
183
+ heading_re = re.compile(rf"^## \[{re.escape(version)}\][^\n]*$", re.MULTILINE)
184
+
185
+ existing = heading_re.search(original)
186
+ if existing:
187
+ wanted = f"## [{version}] - {release_date}"
188
+ if existing.group(0) == wanted:
189
+ return None, f"CHANGELOG heading '{wanted}' already correct"
190
+ text = original[: existing.start()] + wanted + original[existing.end() :]
191
+ note = f"updated existing CHANGELOG heading to '{wanted}'"
192
+ else:
193
+ marker = UNRELEASED.search(original)
194
+ if not marker:
195
+ raise VersionSiteError(
196
+ "CHANGELOG.md has no '## [Unreleased]' marker to insert the new release under"
197
+ )
198
+ insert_at = marker.end()
199
+ block = (
200
+ f"\n\n## [{version}] - {release_date}\n\n### Added\n\n"
201
+ "- TODO: describe this release.\n"
202
+ )
203
+ text = original[:insert_at] + block + original[insert_at:]
204
+ note = (
205
+ f"inserted new CHANGELOG section '## [{version}] - {release_date}' "
206
+ "with a TODO placeholder: replace it with the real release notes"
207
+ )
208
+ return text.encode("utf-8"), note
209
+
210
+
211
+ def main(argv: list[str] | None = None) -> int:
212
+ parser = argparse.ArgumentParser(description=__doc__)
213
+ parser.add_argument("version", help="Release version, MAJOR.MINOR.PATCH (a leading 'v' is stripped)")
214
+ parser.add_argument("--date", help="Release date for the CHANGELOG heading (default: today)")
215
+ parser.add_argument("--check", action="store_true", help="Report drift and change nothing")
216
+ args = parser.parse_args(argv)
217
+
218
+ version = args.version.lstrip("vV").strip()
219
+ if not SEMVER.match(version):
220
+ parser.error(f"not a MAJOR.MINOR.PATCH version: {args.version!r}")
221
+ release_date = args.date or date_cls.today().isoformat()
222
+
223
+ try:
224
+ registry = load_registry(ROOT)
225
+
226
+ if args.check:
227
+ findings = check(ROOT, version, registry)
228
+ if findings:
229
+ print(f"Version drift against {version}:", file=sys.stderr)
230
+ print(format_findings(findings), file=sys.stderr)
231
+ return 1
232
+ print(f"All declared version sites already carry {version}.")
233
+ return 0
234
+
235
+ # Preflight the identity assumptions before the first byte lands. These
236
+ # only ever ran in bin/bump-version, which the runbook does not name.
237
+ plugin_name, manifest_version = plugin_identity(registry)
238
+ check_marketplace_entries(registry, plugin_name)
239
+
240
+ # Plan everything -- CHANGELOG included -- before the first byte lands,
241
+ # then write it as one transaction that rolls back as a unit.
242
+ #
243
+ # The CHANGELOG is folded in order into ONE image: heading, then links,
244
+ # then whatever the registry declares inside it. The previous shape
245
+ # planned the registry and the CHANGELOG separately and then assigned
246
+ # `changes[CHANGELOG] = changelog_bytes`, which silently discarded any
247
+ # registry-computed bytes for that file -- harmless while no site
248
+ # declared the CHANGELOG, and a silent no-op the moment one did.
249
+ changelog_bytes, note = plan_changelog_heading(version, release_date)
250
+ changelog_path = ROOT / "CHANGELOG.md"
251
+ current = read_canonical(ROOT, registry) or manifest_version
252
+ image = (
253
+ changelog_bytes.decode("utf-8")
254
+ if changelog_bytes is not None
255
+ else changelog_path.read_text(encoding="utf-8")
256
+ )
257
+ image = plan_changelog_links(image, current, version)
258
+
259
+ changes = plan_writes(
260
+ ROOT, version, registry, overrides={changelog_path: image}
261
+ )
262
+ changed = describe_changes(ROOT, changes, registry)
263
+ apply_transaction(changes)
264
+
265
+ print(note)
266
+ if changed:
267
+ print(f"Wrote {version} to {len(changed)} site(s):")
268
+ for entry in changed:
269
+ print(f" - {entry}")
270
+ else:
271
+ print(f"All declared version sites already carried {version}.")
272
+
273
+ canonical = read_canonical(ROOT, registry)
274
+ if canonical != version:
275
+ print(
276
+ f"WARNING: canonical CHANGELOG heading is {canonical!r}, expected {version!r}",
277
+ file=sys.stderr,
278
+ )
279
+ return 1
280
+
281
+ remaining = check(ROOT, version, registry)
282
+ if remaining:
283
+ print("Sites still not matching after the write:", file=sys.stderr)
284
+ print(format_findings(remaining), file=sys.stderr)
285
+ return 1
286
+
287
+ # The staging hint used to exist only in bin/bump-version, so the tool
288
+ # the runbook names sent people away without it. Carried across with the
289
+ # rest of that script's behaviour rather than lost in the merge.
290
+ staged = sorted(path.relative_to(ROOT).as_posix() for path in changes)
291
+ print()
292
+ print("Next: python scripts/build-client-adapters.py (regenerate codex/ and copilot/)")
293
+ print("Then verify the changes and:")
294
+ print(" git add " + " ".join(staged))
295
+ print(f' git commit -m "chore(release): v{version}"')
296
+ print(f" git tag v{version}")
297
+ return 0
298
+ except VersionSiteError as exc:
299
+ print(f"bump-version: {exc}", file=sys.stderr)
300
+ return 1
301
+
302
+
303
+ if __name__ == "__main__":
304
+ raise SystemExit(main())
@@ -0,0 +1,243 @@
1
+ #!/usr/bin/env python3
2
+ """Assert the release branch has been merged back into the development branch.
3
+
4
+ adr-kit releases land on `main` (protected, tagged, published), while day-to-day
5
+ work continues on `dev`. Nothing in the release flow moves those release commits
6
+ back, so `dev` silently drifts behind every time a version ships.
7
+
8
+ That drift is not cosmetic. It has already bitten twice: by v0.40.0 the `dev`
9
+ branch was 32 commits behind `main`, still declared version 0.37.0, and was
10
+ missing the whole release toolchain it is supposed to run (`bump-version.py`,
11
+ `check-release-version.py`, `packaging/version-sites.json`, `docs/RELEASING.md`,
12
+ `release-publish.yml`) plus three Accepted ADRs. Cutting the next release from
13
+ `dev` in that state would have reverted three published versions.
14
+
15
+ This check makes the drift loud instead of silent. It compares the two branches
16
+ and reports every release tag that reached the release branch but never reached
17
+ the development branch, so the finding names the versions at risk rather than a
18
+ bare commit count.
19
+
20
+ Exit codes follow the adr-readiness convention:
21
+ 0 the development branch contains every release-branch commit
22
+ 1 the development branch is behind (drift found)
23
+ 2 infrastructure or configuration error (bad ref, not a git repo)
24
+
25
+ Usage:
26
+ python scripts/check-branch-sync.py
27
+ python scripts/check-branch-sync.py --format json
28
+ python scripts/check-branch-sync.py --release-branch main --dev-branch dev
29
+ """
30
+ from __future__ import annotations
31
+
32
+ import argparse
33
+ import json
34
+ import re
35
+ import subprocess
36
+ import sys
37
+ from pathlib import Path
38
+ from typing import Dict, List, Optional, Tuple
39
+
40
+ ROOT = Path(__file__).resolve().parent.parent
41
+
42
+ # Cap the per-commit detail so a long drift reports a useful sample instead of
43
+ # thousands of lines. The counts and the tag list stay complete either way.
44
+ MAX_LISTED_COMMITS = 15
45
+
46
+ SEMVER_TAG = re.compile(r"^v?(\d+)\.(\d+)\.(\d+)$")
47
+
48
+
49
+ class GitError(RuntimeError):
50
+ """A git invocation failed or a ref could not be resolved."""
51
+
52
+
53
+ def run_git(args: List[str], repo: Path) -> str:
54
+ """Run a git command and return stdout, raising GitError on failure."""
55
+ try:
56
+ result = subprocess.run(
57
+ ["git", *args],
58
+ cwd=str(repo),
59
+ capture_output=True,
60
+ text=True,
61
+ encoding="utf-8",
62
+ )
63
+ except OSError as exc: # git missing entirely
64
+ raise GitError(f"could not run git: {exc}") from exc
65
+ if result.returncode != 0:
66
+ raise GitError(
67
+ f"git {' '.join(args)} failed: {result.stderr.strip() or 'unknown error'}"
68
+ )
69
+ return result.stdout
70
+
71
+
72
+ def resolve_ref(name: str, repo: Path) -> str:
73
+ """Resolve a branch name, preferring the remote-tracking copy.
74
+
75
+ CI checks out a single branch, so `main` may exist only as `origin/main`.
76
+ Local clones usually have both. Preferring the remote keeps the check
77
+ honest about what is actually published rather than what happens to be
78
+ checked out.
79
+ """
80
+ for candidate in (f"origin/{name}", name):
81
+ try:
82
+ run_git(["rev-parse", "--verify", f"{candidate}^{{commit}}"], repo)
83
+ except GitError:
84
+ continue
85
+ return candidate
86
+ raise GitError(
87
+ f"branch {name!r} not found as 'origin/{name}' or '{name}'. "
88
+ "Fetch it first (a shallow checkout will not have it)."
89
+ )
90
+
91
+
92
+ def count_commits(base: str, head: str, repo: Path) -> int:
93
+ """Count commits reachable from head but not from base."""
94
+ out = run_git(["rev-list", "--count", f"{base}..{head}"], repo)
95
+ return int(out.strip() or "0")
96
+
97
+
98
+ def list_commits(base: str, head: str, repo: Path, limit: int) -> List[Dict[str, str]]:
99
+ """List up to `limit` commits reachable from head but not from base."""
100
+ out = run_git(
101
+ ["log", f"--max-count={limit}", "--format=%h%x1f%s", f"{base}..{head}"],
102
+ repo,
103
+ )
104
+ commits = []
105
+ for line in out.splitlines():
106
+ if not line.strip():
107
+ continue
108
+ sha, _, subject = line.partition("\x1f")
109
+ commits.append({"sha": sha, "subject": subject})
110
+ return commits
111
+
112
+
113
+ def tags_merged_into(ref: str, repo: Path) -> List[str]:
114
+ """Return the release tags reachable from ref."""
115
+ out = run_git(["tag", "--merged", ref], repo)
116
+ return [line.strip() for line in out.splitlines() if line.strip()]
117
+
118
+
119
+ def version_key(tag: str) -> Tuple[int, int, int]:
120
+ """Sort key for a semver tag; unparsable tags sort first."""
121
+ match = SEMVER_TAG.match(tag)
122
+ if not match:
123
+ return (-1, -1, -1)
124
+ return (int(match.group(1)), int(match.group(2)), int(match.group(3)))
125
+
126
+
127
+ def missing_release_tags(release_ref: str, dev_ref: str, repo: Path) -> List[str]:
128
+ """Release tags on the release branch that never reached the dev branch."""
129
+ on_release = set(tags_merged_into(release_ref, repo))
130
+ on_dev = set(tags_merged_into(dev_ref, repo))
131
+ missing = [tag for tag in on_release - on_dev if SEMVER_TAG.match(tag)]
132
+ return sorted(missing, key=version_key)
133
+
134
+
135
+ def evaluate(release_branch: str, dev_branch: str, repo: Path) -> Dict:
136
+ """Compare the two branches and build the full report."""
137
+ release_ref = resolve_ref(release_branch, repo)
138
+ dev_ref = resolve_ref(dev_branch, repo)
139
+
140
+ behind = count_commits(dev_ref, release_ref, repo)
141
+ ahead = count_commits(release_ref, dev_ref, repo)
142
+
143
+ report: Dict = {
144
+ "release_branch": release_ref,
145
+ "dev_branch": dev_ref,
146
+ "in_sync": behind == 0,
147
+ "behind_count": behind,
148
+ "ahead_count": ahead,
149
+ "missing_tags": [],
150
+ "missing_commits": [],
151
+ "truncated": False,
152
+ }
153
+ if behind:
154
+ report["missing_tags"] = missing_release_tags(release_ref, dev_ref, repo)
155
+ report["missing_commits"] = list_commits(
156
+ dev_ref, release_ref, repo, MAX_LISTED_COMMITS
157
+ )
158
+ report["truncated"] = behind > MAX_LISTED_COMMITS
159
+ return report
160
+
161
+
162
+ def render(report: Dict) -> str:
163
+ """Render the report as human-readable text."""
164
+ release = report["release_branch"]
165
+ dev = report["dev_branch"]
166
+ lines = [f"Branch sync check: {release} -> {dev}", ""]
167
+
168
+ if report["in_sync"]:
169
+ lines.append(f" [ok] {dev} contains every commit from {release}")
170
+ if report["ahead_count"]:
171
+ lines.append(
172
+ f" [info] {dev} is {report['ahead_count']} commit(s) ahead, "
173
+ "which is expected for unreleased work"
174
+ )
175
+ lines.append("")
176
+ lines.append("Branches are in sync.")
177
+ return "\n".join(lines)
178
+
179
+ lines.append(
180
+ f" [BEHIND] {dev} is missing {report['behind_count']} commit(s) from {release}"
181
+ )
182
+ if report["missing_tags"]:
183
+ lines.append(
184
+ f" [BEHIND] released versions not on {dev}: "
185
+ + ", ".join(report["missing_tags"])
186
+ )
187
+ lines.append("")
188
+ lines.append("Missing commits (newest first):")
189
+ for commit in report["missing_commits"]:
190
+ lines.append(f" {commit['sha']} {commit['subject']}")
191
+ if report["truncated"]:
192
+ remaining = report["behind_count"] - len(report["missing_commits"])
193
+ lines.append(f" ... and {remaining} more")
194
+ lines.append("")
195
+ lines.append(f"{dev} has fallen behind {release}. Merge the release back:")
196
+ lines.append("")
197
+ lines.append(" git fetch origin")
198
+ lines.append(f" git checkout -b sync/release-to-dev origin/{dev.split('/')[-1]}")
199
+ lines.append(f" git merge {release}")
200
+ lines.append(" # resolve conflicts, run the release gates, open a PR into "
201
+ f"{dev.split('/')[-1]}")
202
+ lines.append("")
203
+ lines.append("See docs/RELEASING.md step 4 (merge the release back into dev).")
204
+ return "\n".join(lines)
205
+
206
+
207
+ def main(argv: Optional[List[str]] = None) -> int:
208
+ parser = argparse.ArgumentParser(description=__doc__)
209
+ parser.add_argument(
210
+ "--release-branch",
211
+ default="main",
212
+ help="Branch that receives releases. Default: main",
213
+ )
214
+ parser.add_argument(
215
+ "--dev-branch",
216
+ default="dev",
217
+ help="Branch that ongoing work continues on. Default: dev",
218
+ )
219
+ parser.add_argument(
220
+ "--repo-root",
221
+ default=None,
222
+ help="Repository to inspect. Default: the adr-kit checkout this script is in.",
223
+ )
224
+ parser.add_argument("--format", choices=["text", "json"], default="text")
225
+ args = parser.parse_args(argv)
226
+
227
+ repo = Path(args.repo_root).resolve() if args.repo_root else ROOT
228
+
229
+ try:
230
+ report = evaluate(args.release_branch, args.dev_branch, repo)
231
+ except GitError as exc:
232
+ print(f"check-branch-sync: {exc}", file=sys.stderr)
233
+ return 2
234
+
235
+ if args.format == "json":
236
+ print(json.dumps(report, indent=2))
237
+ else:
238
+ print(render(report))
239
+ return 0 if report["in_sync"] else 1
240
+
241
+
242
+ if __name__ == "__main__":
243
+ raise SystemExit(main())
@@ -0,0 +1,81 @@
1
+ #!/usr/bin/env python3
2
+ """Assert the release version is identical across every publish surface.
3
+
4
+ The three coding-agent marketplaces (Claude Code, Codex, GitHub Copilot) all
5
+ resolve adr-kit from the public repository, so a release is only coherent when
6
+ every version-bearing file, the CHANGELOG and the git tag agree. This check is
7
+ the gate the release workflow runs before cutting a GitHub Release.
8
+
9
+ The sites are not hard-coded here: they come from `packaging/version-sites.json`
10
+ via scripts/version_sites.py, which is the same registry the bump writer and the
11
+ test suite use. Declaring a new version-bearing file there teaches every tool at
12
+ once. Every mismatch is reported in one pass.
13
+
14
+ Usage:
15
+ python scripts/check-release-version.py --expect 0.39.0
16
+ python scripts/check-release-version.py --expect v0.39.0 # leading v is stripped
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import sys
22
+ from pathlib import Path
23
+
24
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
25
+
26
+ from version_sites import ( # noqa: E402
27
+ SEMVER,
28
+ VersionSiteError,
29
+ check,
30
+ format_findings,
31
+ load_registry,
32
+ read_all,
33
+ read_canonical,
34
+ )
35
+
36
+ ROOT = Path(__file__).resolve().parent.parent
37
+
38
+
39
+ def main(argv: list[str] | None = None) -> int:
40
+ parser = argparse.ArgumentParser(description=__doc__)
41
+ parser.add_argument(
42
+ "--expect",
43
+ required=True,
44
+ help="Expected release version (git tag). A leading 'v' is stripped.",
45
+ )
46
+ args = parser.parse_args(argv)
47
+ expected = args.expect.lstrip("vV").strip()
48
+ if not SEMVER.match(expected):
49
+ parser.error(f"not a MAJOR.MINOR.PATCH version: {args.expect!r}")
50
+
51
+ try:
52
+ registry = load_registry(ROOT)
53
+ except VersionSiteError as exc:
54
+ print(f"check-release-version: {exc}", file=sys.stderr)
55
+ return 1
56
+
57
+ print(f"Expected release version: {expected}")
58
+ canonical = read_canonical(ROOT, registry)
59
+ mark = "ok" if canonical == expected else "MISMATCH"
60
+ print(f" [{mark}] {registry['canonical']['label']}: {canonical}")
61
+ for site, values in read_all(ROOT, registry):
62
+ for value in values:
63
+ mark = "ok" if value == expected else "MISMATCH"
64
+ print(f" [{mark}] {site['label']}: {value}")
65
+
66
+ findings = check(ROOT, expected, registry)
67
+ if findings:
68
+ print("\nRelease version check FAILED:", file=sys.stderr)
69
+ print(format_findings(findings), file=sys.stderr)
70
+ print(
71
+ f"\nFix them all at once: python scripts/bump-version.py {expected}",
72
+ file=sys.stderr,
73
+ )
74
+ return 1
75
+
76
+ print("\nAll publish surfaces agree on the release version.")
77
+ return 0
78
+
79
+
80
+ if __name__ == "__main__":
81
+ raise SystemExit(main())