@rvdbreemen/adr-kit-opencode 0.56.0 → 0.58.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.
@@ -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())
@@ -0,0 +1,171 @@
1
+ #!/usr/bin/env python3
2
+ """Drive a release end to end, leaving only what a person must do.
3
+
4
+ ADR-042: the release runs from the maintainer's machine, with the maintainer's
5
+ own credentials, because GitHub does not start workflow runs for events caused
6
+ by GITHUB_TOKEN - a pull request a workflow opens never receives the checks
7
+ `main` requires, so it can never merge. The tag is not typed here either:
8
+ `release-publish.yml` creates it from the merged commit and publishes in the
9
+ same run, and this driver only verifies that it landed where it belongs.
10
+
11
+ What stays human: deciding to release and choosing the version, writing the
12
+ release notes, approving the merge, and npm's 2FA. Everything between those is
13
+ mechanical, and mechanical steps performed by hand are what cost v0.55.0 and
14
+ left three npm versions unapproved for a week.
15
+
16
+ Safe to re-run. Each phase asks the repository whether its work is already
17
+ done, so an interrupted release is resumed rather than restarted:
18
+
19
+ python scripts/release.py 0.57.0
20
+ python scripts/release.py 0.57.0 --skip-tests # CI still runs them
21
+ python scripts/release.py 0.57.0 --status # what is left, changing nothing
22
+ python scripts/release.py 0.57.0 --only prepare # one phase
23
+
24
+ docs/RELEASING.md is the specification; the phases mirror its steps in order.
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import argparse
29
+ import re
30
+ import sys
31
+ from pathlib import Path
32
+
33
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
34
+
35
+ from release_npm import ( # noqa: E402
36
+ DONE,
37
+ STAGED,
38
+ UNREACHABLE,
39
+ WRONG_LATEST,
40
+ npm_instructions,
41
+ npm_state,
42
+ npm_wrong_latest,
43
+ )
44
+ from release_phases import PHASES, Context, ReleaseError # noqa: E402
45
+
46
+ NPM_LABEL = {
47
+ DONE: "done",
48
+ WRONG_LATEST: "PUBLISHED, but `latest` names another version",
49
+ STAGED: "awaiting your 2FA",
50
+ UNREACHABLE: "npm did not answer; run this again",
51
+ }
52
+
53
+ SEMVER = re.compile(r"^\d+\.\d+\.\d+$")
54
+
55
+
56
+ def _say(text: str = "") -> None:
57
+ print(text, flush=True)
58
+
59
+
60
+ def _status(ctx: Context) -> int:
61
+ _say(f"Release {ctx.tag}: what each phase reports about the repository now.")
62
+ _say()
63
+ for phase in PHASES:
64
+ try:
65
+ state = "done" if phase.done(ctx) else "to do"
66
+ except ReleaseError as exc: # a phase that cannot even answer
67
+ state = f"unknown ({exc})"
68
+ _say(f" step {phase.step} {phase.name:<10} {state}")
69
+ _say(f" step 3a npm {NPM_LABEL[npm_state(ctx)]}")
70
+ _say()
71
+ _say("Nothing was changed.")
72
+ return 0
73
+
74
+
75
+ def main(argv: list[str] | None = None) -> int:
76
+ parser = argparse.ArgumentParser(description=__doc__)
77
+ parser.add_argument("version", help="release version, for example 0.57.0")
78
+ parser.add_argument(
79
+ "--only",
80
+ choices=[phase.name for phase in PHASES],
81
+ help="run a single phase, skipping the done-check for it",
82
+ )
83
+ parser.add_argument(
84
+ "--status",
85
+ action="store_true",
86
+ help="report what each phase would do and change nothing",
87
+ )
88
+ parser.add_argument(
89
+ "--skip-tests",
90
+ action="store_true",
91
+ help="skip the local pytest run; the pull request still runs it in CI",
92
+ )
93
+ parser.add_argument(
94
+ "--timeout-min",
95
+ type=int,
96
+ default=45,
97
+ help="how long to wait for a merge or for the publish workflow (default 45)",
98
+ )
99
+ args = parser.parse_args(argv)
100
+
101
+ version = args.version.lstrip("vV").strip()
102
+ if not SEMVER.match(version):
103
+ parser.error(f"not a MAJOR.MINOR.PATCH version: {args.version!r}")
104
+
105
+ ctx = Context(
106
+ version=version,
107
+ skip_tests=args.skip_tests,
108
+ timeout_min=args.timeout_min,
109
+ )
110
+
111
+ if args.status:
112
+ return _status(ctx)
113
+
114
+ phases = [p for p in PHASES if p.name == args.only] if args.only else list(PHASES)
115
+ _say(f"Releasing {ctx.tag}. Re-running this command is safe; finished phases are skipped.")
116
+ _say()
117
+
118
+ for phase in phases:
119
+ label = f"step {phase.step} {phase.name}"
120
+ if not args.only and phase.done(ctx):
121
+ _say(f" {label:<22} already done")
122
+ continue
123
+ _say(f" {label:<22} running")
124
+ try:
125
+ for note in phase.run(ctx):
126
+ _say(f" {note}")
127
+ except ReleaseError as exc:
128
+ _say()
129
+ _say(f"Stopped in {phase.name}:")
130
+ _say()
131
+ _say(str(exc))
132
+ _say()
133
+ _say("Nothing after this phase ran. Fix the above and run the same "
134
+ "command again; the phases that finished will be skipped.")
135
+ return 1
136
+
137
+ _say()
138
+ state = npm_state(ctx)
139
+
140
+ if state == DONE:
141
+ _say(f"npm already serves {ctx.version} as latest.")
142
+ _say()
143
+ _say(f"{ctx.tag} is released and every surface agrees.")
144
+ return 0
145
+
146
+ if state == WRONG_LATEST:
147
+ _say("=" * 72)
148
+ _say("RELEASED, BUT npm SERVES A DIFFERENT VERSION")
149
+ _say("=" * 72)
150
+ _say()
151
+ _say(npm_wrong_latest(ctx))
152
+ return 1
153
+
154
+ if state == UNREACHABLE:
155
+ _say(f"Everything up to npm is done, but npm did not answer, so this "
156
+ f"cannot say whether {ctx.version} is published or still staged. "
157
+ f"Run the same command again once you have a connection.")
158
+ return 1
159
+
160
+ _say("=" * 72)
161
+ _say("ONE THING LEFT, AND ONLY YOU CAN DO IT")
162
+ _say("=" * 72)
163
+ _say()
164
+ _say(npm_instructions(ctx))
165
+ _say()
166
+ _say("Then re-run this command: it will verify the dist-tag and finish.")
167
+ return 0
168
+
169
+
170
+ if __name__ == "__main__":
171
+ raise SystemExit(main())
@@ -0,0 +1,117 @@
1
+ #!/usr/bin/env python3
2
+ """The one step of a release npm will not let any tool finish.
3
+
4
+ npm requires proof of presence to publish, so a staged package waits for the
5
+ maintainer's 2FA no matter what drives the release. That makes this the seam
6
+ between what ADR-042 automates and what it deliberately leaves to a person,
7
+ which is why it is its own module rather than an eighth entry in PHASES.
8
+
9
+ The distinction the rest of the driver depends on is between a version that is
10
+ still staged and a version that is published while `latest` names an older
11
+ release. From outside they look the same - `npm install` gives you the wrong
12
+ package either way - but only the second is a fault, and only the second has a
13
+ remedy the maintainer can apply without npm's approval flow.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
22
+
23
+ from release_shell import PACKAGE, Context, run # noqa: E402
24
+
25
+
26
+ DONE = "done"
27
+ WRONG_LATEST = "wrong-latest"
28
+ STAGED = "staged"
29
+ UNREACHABLE = "unreachable"
30
+
31
+
32
+ def _dist_tags(ctx: Context) -> dict | None:
33
+ """None means npm did not answer, which is not the same as an empty answer."""
34
+ code, out, _ = run(["npm", "view", PACKAGE, "dist-tags", "--json", "--prefer-online"])
35
+ if code != 0:
36
+ return None
37
+ try:
38
+ parsed = json.loads(out)
39
+ except json.JSONDecodeError:
40
+ return None
41
+ return parsed if isinstance(parsed, dict) else None
42
+
43
+
44
+ def npm_state(ctx: Context) -> str:
45
+ """Which of the four things npm is currently doing about this version.
46
+
47
+ Deciding this in one place is what keeps the driver's report and its exit
48
+ code from disagreeing, which is the defect this function replaced: the
49
+ predicate existed and nothing wired it to a failure.
50
+
51
+ A registry that does not answer gets its own state rather than being folded
52
+ into one of the others. Reporting "awaiting your 2FA" because npm was down
53
+ would be a guess presented as a reading, and it is the reading a maintainer
54
+ would act on.
55
+ """
56
+ tags = _dist_tags(ctx)
57
+ if tags is None:
58
+ return UNREACHABLE
59
+ if tags.get("latest") == ctx.version:
60
+ return DONE
61
+ return WRONG_LATEST if npm_published(ctx) else STAGED
62
+
63
+
64
+ def npm_published(ctx: Context) -> bool:
65
+ """Is the version on the registry at all, whatever `latest` points at?
66
+
67
+ This separates the two npm states that look identical from outside. A
68
+ version still staged is a release waiting on the maintainer's 2FA, which is
69
+ the normal end of a release rather than a fault. A version that IS
70
+ published while `latest` names an older release is the v0.55.1 defect:
71
+ `npm install` quietly serves the wrong package. Only the second is a
72
+ failure, and telling the maintainer to go and approve something that is
73
+ already approved sends them to the one place that cannot fix it.
74
+ """
75
+ code, out, _ = run(["npm", "view", PACKAGE, "versions", "--json", "--prefer-online"])
76
+ if code != 0:
77
+ return False
78
+ try:
79
+ versions = json.loads(out)
80
+ except json.JSONDecodeError:
81
+ return False
82
+ if isinstance(versions, str): # npm returns a bare string for a lone version
83
+ versions = [versions]
84
+ return isinstance(versions, list) and ctx.version in versions
85
+
86
+
87
+ def npm_wrong_latest(ctx: Context) -> str:
88
+ latest = (_dist_tags(ctx) or {}).get("latest") or "nothing this driver could read"
89
+ return (
90
+ f"{ctx.version} is published on npm, but `latest` names {latest}.\n\n"
91
+ f"`npm install {PACKAGE}` therefore serves {latest} rather than the "
92
+ f"release. npm sets `latest` to the version published LAST, not the "
93
+ f"highest, so approving staged versions out of order does exactly "
94
+ f"this. It left 0.55.1 released while `latest` read 0.54.0 for a "
95
+ f"week, and nothing surfaced it.\n\n"
96
+ f" npm dist-tag add {PACKAGE}@{ctx.version} latest\n"
97
+ f" npm dist-tag ls {PACKAGE} # latest must read {ctx.version}\n\n"
98
+ f"Read the first command's own exit code. Piping it into `tail` "
99
+ f"reports tail's status instead, and npm's failure disappears."
100
+ )
101
+
102
+
103
+ def npm_instructions(ctx: Context) -> str:
104
+ return (
105
+ f"The OpenCode package for {ctx.tag} is STAGED, not published. npm "
106
+ f"requires proof of presence, so no tool can finish this.\n\n"
107
+ f" npm login\n"
108
+ f" npm stage list {PACKAGE}\n"
109
+ f" npm stage view <stage-id> # inspect the tarball first\n"
110
+ f" npm stage approve <stage-id> # prompts for your OTP\n\n"
111
+ f" or from the browser: https://www.npmjs.com/staged-packages\n\n"
112
+ f"If more than one version is staged, approve them in ASCENDING order. "
113
+ f"npm sets `latest` to the version published LAST, not the highest. On "
114
+ f"2026-08-26 approving 0.55.1, then 0.53.0, then 0.54.0 left `latest` on "
115
+ f"0.54.0 while 0.55.1 was the release.\n\n"
116
+ f" npm dist-tag ls {PACKAGE} # latest must read {ctx.version}"
117
+ )