diff --git a/.github/release.yml b/.github/release.yml new file mode 100644 index 0000000..63fbd63 --- /dev/null +++ b/.github/release.yml @@ -0,0 +1,24 @@ +# Not a workflow: GitHub reads the generated-release-notes configuration from this path and +# nowhere else. The release itself is cut by the workflow under `.github/workflows/`. +# +# The generated list is appended under the hand-written CHANGELOG.md section, so it exists to +# credit contributors and link every pull request, not to describe the release. Dependency and +# tooling bumps are grouped so they do not sit between the real changes. +changelog: + exclude: + authors: + - github-actions[bot] + categories: + - title: Changes + labels: + - "*" + exclude: + labels: + - dependencies + - github_actions + - pre_commit + - title: Dependency and tooling updates + labels: + - dependencies + - github_actions + - pre_commit diff --git a/.github/workflows/changelog.yml b/.github/workflows/changelog.yml new file mode 100644 index 0000000..051f3ae --- /dev/null +++ b/.github/workflows/changelog.yml @@ -0,0 +1,64 @@ +name: Changelog + +# pull_request rather than pull_request_target: this needs the PR's changed-file list and no +# secrets, so the read-only token a fork PR receives is enough, and no PR content is checked +# out or executed. `labeled`/`unlabeled` are here so applying the skip label re-runs the check +# rather than leaving a stale failure behind. +on: + pull_request: + types: + - opened + - reopened + - synchronize + - labeled + - unlabeled + branches: + - main + +permissions: + contents: read + pull-requests: read + +jobs: + changelog-entry: + name: Changelog entry + runs-on: ubuntu-latest + steps: + # The job runs unconditionally and decides inside the step, rather than skipping on an + # `if`: a skipped job reports as neither passing nor failing, and the reason a PR is + # exempt belongs in the log where the next reader will look for it. + - name: Require a changelog entry beside a user-visible change + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REPOSITORY: ${{ github.repository }} + PR_NUMBER: ${{ github.event.pull_request.number }} + # contains() matches an array element exactly, so a label carrying a comma or a + # name this one is a prefix of cannot be mistaken for it + SKIP_LABELLED: ${{ contains(github.event.pull_request.labels.*.name, 'no-changelog') }} + IS_DEPENDABOT: ${{ github.event.pull_request.user.login == 'dependabot[bot]' }} + run: | + set -euo pipefail + + if [ "${SKIP_LABELLED}" = "true" ]; then + echo "Labelled no-changelog; entry not required." + exit 0 + fi + if [ "${IS_DEPENDABOT}" = "true" ]; then + echo "Dependency bump; the generated release notes list these under their own heading." + exit 0 + fi + + changed="$(gh api --paginate "repos/${REPOSITORY}/pulls/${PR_NUMBER}/files" --jq '.[].filename')" + + if ! printf '%s\n' "${changed}" | grep -qE '^(purepdb/|pyproject.toml$)'; then + echo "No shipped files changed; entry not required." + exit 0 + fi + + if printf '%s\n' "${changed}" | grep -qx 'CHANGELOG.md'; then + echo "CHANGELOG.md touched beside the change." + exit 0 + fi + + echo "::error file=CHANGELOG.md::This PR changes shipped files but does not touch CHANGELOG.md. Add an entry under ## [Unreleased], or apply the no-changelog label if the change genuinely needs no entry." + exit 1 diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml new file mode 100644 index 0000000..0e1fae5 --- /dev/null +++ b/.github/workflows/publish-release.yml @@ -0,0 +1,271 @@ +name: Publish release + +# Pushing a vX.Y.Z tag is the release. A manual run rehearses the same path against TestPyPI +# and stops before the GitHub release, so the whole workflow can be exercised without +# consuming a version number on PyPI. +on: + push: + tags: + - "v*" + workflow_dispatch: + +permissions: + contents: read + +# A cancelled publish can leave PyPI holding some files of a version and not others, and the +# version number cannot be reused afterwards. +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false + +defaults: + run: + shell: bash + +env: + PYTHON_VERSION: "3.11" + +jobs: + verify: + name: Verify the tag + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + actions: read + issues: read + outputs: + version: ${{ steps.guard.outputs.version }} + prerelease: ${{ steps.guard.outputs.prerelease }} + steps: + - name: Refuse anything that is not a tag + env: + REF_TYPE: ${{ github.ref_type }} + REF_NAME: ${{ github.ref_name }} + run: | + if [ "${REF_TYPE}" != "tag" ]; then + echo "::error::Run this from a tag, not ${REF_TYPE} ${REF_NAME}." + exit 1 + fi + + - name: Checkout the tag + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: ${{ env.PYTHON_VERSION }} + + - name: Check the tag against the packaged version and the changelog + id: guard + env: + TAG: ${{ github.ref_name }} + run: | + python .github/workflows/scripts/release_guard.py \ + --tag "${TAG}" --notes release-notes.md --github-output "${GITHUB_OUTPUT}" + + - name: Check the tag is on main + env: + TAG: ${{ github.ref_name }} + run: | + git fetch --quiet origin main + if ! git merge-base --is-ancestor "${TAG}" origin/main; then + echo "::error::${TAG} is not an ancestor of main; releases are cut from main." + exit 1 + fi + + - name: Check CI passed on this commit + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REPO: ${{ github.repository }} + SHA: ${{ github.sha }} + run: | + conclusion=$(gh api \ + "repos/${REPO}/actions/workflows/ci.yml/runs?head_sha=${SHA}&status=completed" \ + --jq '.workflow_runs[0].conclusion // ""') + if [ -z "${conclusion}" ]; then + echo "::error::No completed CI run for ${SHA}. Wait for main to go green, then re-run." + exit 1 + fi + if [ "${conclusion}" != "success" ]; then + echo "::error::CI concluded '${conclusion}' for ${SHA}. Fix main before releasing." + exit 1 + fi + echo "CI passed on ${SHA}" + + # Milestones here are named for the tag they ship in, so an open item is work that was + # assigned to this release and did not make it. A repository that does not track a release + # this way has no milestone for the tag, which is not an error. + - name: Check the milestone for this tag is finished + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REPO: ${{ github.repository }} + TAG: ${{ github.ref_name }} + run: | + open_items=$(gh api "repos/${REPO}/milestones?state=all&per_page=100" \ + --jq "[.[] | select(.title == \"${TAG}\")] | .[0].open_issues // \"none\"") + if [ "${open_items}" = "none" ]; then + echo "::notice::No milestone named ${TAG}; releasing without one." + elif [ "${open_items}" != "0" ]; then + echo "::error::Milestone ${TAG} still has ${open_items} open item(s)." + exit 1 + else + echo "Milestone ${TAG} reads 100%" + fi + + - name: Keep the release notes for the later jobs + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: release-notes + path: release-notes.md + if-no-files-found: error + + build: + name: Build and check the distribution + needs: verify + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - name: Checkout the tag + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: ${{ env.PYTHON_VERSION }} + + # Isolated: the wheel is a product of the declared build requirements, not of the runner. + # The tool versions come from the dev group, the one place they are pinned. + - name: Build the sdist and the wheel + run: | + python -m pip install --upgrade pip + python -m pip install --group dev + python -m build + python -m twine check --strict dist/* + + # The artifact is tested, not the tree it came from: a clean environment carrying only the + # declared runtime dependencies has to import the package and run its entry point. `-P` + # keeps the checkout in the working directory off sys.path, so the import cannot fall back + # to the source tree and pass for a wheel that is missing something. + - name: Smoke-test the built wheel + env: + VERSION: ${{ needs.verify.outputs.version }} + run: | + python -m venv /tmp/smoke + /tmp/smoke/bin/python -m pip install --upgrade pip + /tmp/smoke/bin/python -m pip install dist/purepdb-"${VERSION}"-py3-none-any.whl + /tmp/smoke/bin/python -P - <<'PY' + import os + import pathlib + + import purepdb + + installed = pathlib.Path(purepdb.__file__).parent + assert "site-packages" in str(installed), f"imported a source tree: {installed}" + assert purepdb.__version__ == os.environ["VERSION"], purepdb.__version__ + assert (installed / "py.typed").exists(), "py.typed did not ship" + print(f"purepdb {purepdb.__version__} imported from {installed}") + PY + /tmp/smoke/bin/purepdb --help >/dev/null + + - name: Keep the distribution for the later jobs + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: distribution + path: dist/ + if-no-files-found: error + + publish: + name: Publish to ${{ github.event_name == 'workflow_dispatch' && 'TestPyPI' || 'PyPI' }} + needs: [verify, build] + runs-on: ubuntu-latest + timeout-minutes: 15 + environment: + name: ${{ github.event_name == 'workflow_dispatch' && 'testpypi' || 'pypi' }} + url: ${{ github.event_name == 'workflow_dispatch' && 'https://test.pypi.org/p/purepdb' || 'https://pypi.org/p/purepdb' }} + permissions: + # mandatory for trusted publishing, and it must be the only credential in the job + id-token: write + steps: + - name: Fetch the distribution + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: distribution + path: dist + + - name: Publish + uses: pypa/gh-action-pypi-publish@dc37677b2e1c63e2034f94d8a5b11f265b73ba33 # v1.14.2 + with: + # empty resolves to PyPI: the canonical input carries no default and the action falls + # through to the deprecated alias, which defaults to the real index + repository-url: ${{ github.event_name == 'workflow_dispatch' && 'https://test.pypi.org/legacy/' || '' }} + # a PyPI collision means the version is already public, so only a rehearsal skips it + skip-existing: ${{ github.event_name == 'workflow_dispatch' }} + attestations: true + print-hash: true + + release: + name: Create the GitHub release + needs: [verify, build, publish] + if: github.event_name != 'workflow_dispatch' + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: write + issues: write + steps: + - name: Fetch the distribution + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: distribution + path: dist + + - name: Fetch the release notes + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: release-notes + + # --generate-notes appends its list under --notes-file rather than replacing it, so the + # changelog section leads and `.github/release.yml` groups what follows. A pre-release + # is marked as such and never becomes "latest". + - name: Create the release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REPO: ${{ github.repository }} + TAG: ${{ github.ref_name }} + PRERELEASE: ${{ needs.verify.outputs.prerelease }} + run: | + shopt -s failglob + flags=(--latest) + if [ "${PRERELEASE}" = "true" ]; then + flags=(--prerelease --latest=false) + fi + gh release create "${TAG}" dist/* \ + --repo "${REPO}" \ + --title "${TAG}" \ + --notes-file release-notes.md \ + --generate-notes \ + --verify-tag \ + "${flags[@]}" + + # Last, so a failure here leaves a released version with an open milestone rather than a + # closed milestone and no release. + - name: Close the milestone for this tag + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REPO: ${{ github.repository }} + TAG: ${{ github.ref_name }} + run: | + number=$(gh api "repos/${REPO}/milestones?state=open&per_page=100" \ + --jq "[.[] | select(.title == \"${TAG}\")] | .[0].number // \"\"") + if [ -z "${number}" ]; then + echo "No open milestone named ${TAG}; nothing to close." + else + gh api -X PATCH "repos/${REPO}/milestones/${number}" -f state=closed >/dev/null + echo "Closed milestone ${TAG}" + fi diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index efef222..0000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,80 +0,0 @@ -name: Release - -# A GitHub release is built on a git tag, so the tag is the trigger. Pushing -# v1.2.3 builds the artefacts, checks their metadata, and attaches them to the -# release for that tag -- alongside the source archives GitHub generates itself. -# -# Publishing to PyPI is deliberately NOT here. That needs either a stored token -# or a Trusted Publisher configured against this repository, both of which are -# the maintainer's decision to make rather than something a workflow should -# assume. `make publish` remains the manual path. -on: - push: - tags: - # Deliberately loose: the build job fails unless the tag equals - # v, which is the real constraint and gives a far - # better error than a tag that silently matches nothing. - - "v*" - -permissions: - contents: read - -jobs: - build: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 - with: - python-version: "3.11" - - name: Build - run: | - python -m pip install --upgrade pip - pip install --group dev -e . - python -m build - - name: Check metadata - run: python -m twine check dist/* - # The tag says what version this is; the package says what version it is. - # A release where they disagree is worse than a release that fails here. - - name: Verify the tag matches the packaged version - env: - TAG: ${{ github.ref_name }} - run: | - version=$(python -c "import tomllib; print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])") - if [ "$TAG" != "v$version" ]; then - echo "tag $TAG does not match pyproject version $version" >&2 - exit 1 - fi - - name: Run the suite against what was built - run: python -m pytest -q - - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: dist - path: dist/ - - attach: - needs: build - runs-on: ubuntu-latest - # Raised for this job alone: it is the only one that writes anything. - permissions: - contents: write - steps: - - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: dist - path: dist/ - # `gh` is preinstalled on the runner, so no third-party action is needed - # to reach the releases API. --notes-from-tag falls back to generated - # notes when the tag carries no message. - - name: Attach artefacts to the release - env: - GH_TOKEN: ${{ github.token }} - GH_REPO: ${{ github.repository }} - TAG: ${{ github.ref_name }} - run: | - if ! gh release view "$TAG" >/dev/null 2>&1; then - gh release create "$TAG" --generate-notes --verify-tag - fi - gh release upload "$TAG" dist/* --clobber diff --git a/.github/workflows/scripts/release_guard.py b/.github/workflows/scripts/release_guard.py new file mode 100644 index 0000000..07a3b51 --- /dev/null +++ b/.github/workflows/scripts/release_guard.py @@ -0,0 +1,105 @@ +"""Checks that decide whether a tag may be released, and the notes that go with it. + +A script rather than inline workflow steps so the parsing has tests: the changelog format it +reads is a convention, and a release is the one action here that cannot be undone. + +The same script, with a different VERSION_SOURCES table, guards every repository in the MCRIT +ecosystem. Keep the logic identical across them and vary only the table. +""" + +import argparse +import re +import sys +import tomllib +from pathlib import Path + +#: Where this repository states its version. Every entry has to agree with the tag. +#: ("label", "relative/path", regex-with-one-group) reads a literal from a text file; +#: ("label", "pyproject.toml", None) reads `[project].version`. +VERSION_SOURCES = [ + ("pyproject.toml", "pyproject.toml", None), + ("purepdb.__version__", "purepdb/__init__.py", r'^__version__ = "([0-9][0-9a-z.]*)"'), +] + +#: A release version as this ecosystem tags it: `1.2.3`, or a PEP 440 pre-release such as +#: `1.2.3rc1`, `1.2.3b2`, `1.2.3a1`. Anything else is refused rather than guessed at. +VERSION = re.compile(r"^(?P\d+\.\d+\.\d+)(?P
(a|b|rc)\d+)?$")
+#: `## [1.2.3] - 2026-09-20` (or `[v1.2.3]`), the heading a release section opens with.
+SECTION = re.compile(r"^## \[v?(?P[0-9][0-9a-z.]*)\] - (?P\d{4}-\d{2}-\d{2})\s*$")
+#: any second-level heading, which is where a section ends
+NEXT_HEADING = re.compile(r"^## ")
+
+
+def declaredVersions(root: Path) -> dict:
+    """The version as each place that carries it states it."""
+    found = {}
+    for label, relative, pattern in VERSION_SOURCES:
+        path = root / relative
+        if pattern is None:
+            found[label] = tomllib.loads(path.read_text(encoding="utf-8"))["project"]["version"]
+            continue
+        match = re.search(pattern, path.read_text(encoding="utf-8"), re.MULTILINE)
+        if match is None:
+            raise SystemExit(f"could not read a version from {path}")
+        found[label] = match.group(1)
+    return found
+
+
+def changelogSection(changelog: str, version: str) -> str:
+    """The release notes for `version`, or a failure naming what is missing."""
+    lines = changelog.splitlines()
+    for index, line in enumerate(lines):
+        match = SECTION.match(line)
+        if match is None or match.group("version") != version:
+            continue
+        body = []
+        for following in lines[index + 1 :]:
+            if NEXT_HEADING.match(following):
+                break
+            body.append(following)
+        text = "\n".join(body).strip()
+        if not text:
+            raise SystemExit(f"CHANGELOG.md has a heading for {version} but nothing under it")
+        return text
+    raise SystemExit(
+        f"CHANGELOG.md has no `## [{version}] - ` section. "
+        "Rename `## [Unreleased]` to the release being cut before tagging."
+    )
+
+
+def main(argv: list) -> int:
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument("--tag", required=True, help="the tag being released, e.g. v1.2.0")
+    parser.add_argument("--root", default=".", help="repository root")
+    parser.add_argument("--notes", help="write the release notes to this file")
+    parser.add_argument("--github-output", help="append version= and prerelease= to this file")
+    args = parser.parse_args(argv)
+
+    if not args.tag.startswith("v"):
+        raise SystemExit(f"tag {args.tag!r} does not start with 'v'")
+    version = args.tag[1:]
+    shape = VERSION.match(version)
+    if shape is None:
+        shape_wanted = "vMAJOR.MINOR.PATCH with an optional a/b/rc pre-release suffix"
+        raise SystemExit(f"tag {args.tag!r} is not {shape_wanted}")
+
+    versions = declaredVersions(Path(args.root))
+    disagreeing = {label: value for label, value in versions.items() if value != version}
+    if disagreeing:
+        stated = ", ".join(f"{label} = {value}" for label, value in versions.items())
+        raise SystemExit(f"tag {args.tag} does not match the packaged version ({stated})")
+
+    changelog = (Path(args.root) / "CHANGELOG.md").read_text(encoding="utf-8")
+    notes = changelogSection(changelog, version)
+    if args.notes:
+        Path(args.notes).write_text(notes + "\n", encoding="utf-8")
+    if args.github_output:
+        prerelease = "true" if shape.group("pre") else "false"
+        with open(args.github_output, "a", encoding="utf-8") as output:
+            output.write(f"version={version}\nprerelease={prerelease}\n")
+    print(f"{args.tag} matches the declared version and has a changelog section")
+    return 0
+
+
+if __name__ == "__main__":
+    sys.exit(main(sys.argv[1:]))
diff --git a/AGENTS.md b/AGENTS.md
index aa54757..ef42896 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -56,7 +56,7 @@ tests/              # pytest suite
 tools/fuzz.py       # the parse-boundary fuzzer; runs outside pytest
 tools/relink_omap.py  # CLI over tests/_relink.py
 dev/                # scratch, EXCEPT two validate_* scripts (see below)
-.github/workflows/  # ci.yml, fuzz.yml, release.yml, validate.yml
+.github/workflows/  # ci.yml, changelog.yml, fuzz.yml, publish-release.yml, validate.yml
 ```
 
 `dev/` is a scratch directory with two tracked exceptions: `.gitignore` holds
@@ -246,23 +246,16 @@ not the count of symbols a release happens to recover from a given PDB.
 Recovering *more* symbols is an `Added`, even though `len(pdb.functions())`
 moves; making a previously-resolved address resolve *differently* is breaking.
 
-The version lives in **two** places that nothing else ties together:
-`pyproject.toml` `[project].version` and `purepdb/__init__.__version__`.
-`tests/test_version.py` asserts they agree. Bump both in one commit, or not at
-all.
+The version lives in **two** places: `pyproject.toml` `[project].version` and
+`purepdb/__init__.__version__`. `tests/test_version.py` asserts they agree and
+the release workflow refuses a tag that matches only one. Bump both in one
+commit, or not at all.
 
-To cut a release (maintainer action — do not do this unprompted):
-
-1. Move the `Unreleased` entries under a new `## [x.y.z] - YYYY-MM-DD` heading
-   and update the link definitions at the bottom of the file.
-2. Set the same version in `pyproject.toml` *and* `purepdb/__init__.py`.
-3. `git tag -a vx.y.z -m 'purepdb x.y.z'` and push the tag.
-
-Pushing the tag runs `release.yml`, which builds the artefacts, checks metadata
-with twine, **fails if the tag and the packaged version disagree**, runs the
-suite against what it built, and attaches the artefacts to the GitHub release.
-Publishing to PyPI stays manual (`make publish`) — automating it needs a stored
-token or a Trusted Publisher, which is a maintainer decision.
+Every PR that changes `purepdb/` adds its own entry under `## [Unreleased]`
+in `CHANGELOG.md`, or carries the `no-changelog` label; `changelog.yml`
+enforces it. The release process itself — cutting, rehearsing against TestPyPI,
+pre-releases, recovery — is in [`RELEASING.md`](RELEASING.md). Do not cut a
+release unprompted.
 
 ## Git Workflow
 
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3a97190..b82d0fd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,7 +14,22 @@ resolve *differently* would be breaking, and would say so here.
 
 ## [Unreleased]
 
-Nothing yet.
+### Added
+
+- Pushing a `vX.Y.Z` tag now publishes the release. The workflow refuses to
+  continue unless the tag matches both version strings, `CHANGELOG.md` has a
+  section for it, the commit is on `main`, CI passed there, and a milestone
+  named for the tag, if one exists, has no open items; it then builds the sdist
+  and wheel in an isolated environment, installs the wheel into a clean
+  environment and runs it, uploads to PyPI through trusted publishing with
+  signed provenance, creates the GitHub release from that version's changelog
+  section, and closes that milestone. Pre-release tags (`v1.2.3rc1`) are marked
+  as such, and a manual run rehearses the same path against TestPyPI. Before,
+  publishing was `make publish` with an API token and the tag workflow only
+  attached artefacts. See `RELEASING.md`; the trusted publisher and the `pypi`
+  and `testpypi` environments are configured once by a maintainer.
+- A pull request that changes `purepdb/` or `pyproject.toml` has to add a
+  `CHANGELOG.md` entry or carry the `no-changelog` label; CI checks it.
 
 ## [0.5.0] - 2026-08-28
 
diff --git a/README.md b/README.md
index 0b7ad5a..5adbe17 100644
--- a/README.md
+++ b/README.md
@@ -292,25 +292,9 @@ and [`CHANGELOG.md`](CHANGELOG.md) follows
 number covers is stated at the top of that file: the API in `__all__`, not the
 count of symbols a release happens to recover from a given PDB.
 
-To cut a release:
-
-1. Move the `Unreleased` entries under a new `## [x.y.z] - YYYY-MM-DD`
-   heading, and update the link definitions at the bottom of the file.
-2. Set the same version in **both** `pyproject.toml` and
-   `purepdb/__init__.py`. Nothing ties them together, so `tests/test_version.py`
-   asserts they agree — the release workflow compares the tag against
-   `pyproject.toml` alone and would not notice on its own.
-3. Tag it: `git tag -a vx.y.z -m 'purepdb x.y.z'` and push the tag.
-
-Pushing the tag runs `.github/workflows/release.yml`, which builds the sdist
-and wheel, checks their metadata with twine, **fails if the tag and the
-packaged version disagree**, runs the suite against what it built, and
-attaches the artefacts to the GitHub release for that tag — creating the
-release with generated notes if it does not already exist.
-
-Publishing to PyPI stays manual (`make publish`). Automating it needs either a
-stored token or a Trusted Publisher configured against the repository, which
-is a maintainer decision rather than something a workflow should assume.
+How a release is cut, rehearsed and recovered is in [`RELEASING.md`](RELEASING.md):
+pushing a `vX.Y.Z` tag builds the package, publishes it to PyPI through trusted
+publishing and creates the GitHub release from that version's changelog section.
 
 `tests/data/` is in the repository but excluded from the sdist and wheel, so
 installing purepdb does not pull down 12 MB of binaries. Those tests skip when
diff --git a/RELEASING.md b/RELEASING.md
new file mode 100644
index 0000000..9025a3a
--- /dev/null
+++ b/RELEASING.md
@@ -0,0 +1,140 @@
+# Releasing purepdb
+
+This repository follows the release process shared across the MCRIT ecosystem
+([smda](https://github.com/danielplohmann/smda), [purepdb](https://github.com/danielplohmann/purepdb),
+[mcrit](https://github.com/danielplohmann/mcrit), [mcritweb](https://github.com/fkie-cad/mcritweb),
+[mcrit-plugin](https://github.com/danielplohmann/mcrit-plugin),
+[docker-mcrit](https://github.com/danielplohmann/docker-mcrit)). The shape is the same everywhere;
+this file states the values that are specific to this repository.
+
+## Versioning
+
+purepdb follows [Semantic Versioning 2.0.0](https://semver.org/spec/v2.0.0.html) over the API
+listed in `purepdb.__all__`; see the note at the top of `CHANGELOG.md` for what that does and does
+not cover.
+
+The version is declared in `pyproject.toml` (`[project].version`) and `purepdb/__init__.py` (`__version__`). The release workflow refuses a tag that does not
+match every one of them, so a bump that misses one fails before anything is published.
+
+## Supported Python versions
+
+purepdb supports Python 3.11 through 3.14, and CI runs every one of them: the floor and the
+ceiling on Linux, plus the floor on macOS and Windows.
+
+purepdb sits at the bottom of the ecosystem's dependency stack — SMDA depends on it as
+`purepdb>=0.3.0`, and MCRIT reaches it through SMDA — so this floor is the one that constrains
+everything above it rather than the one that follows. An installer resolves a dependency by the
+interpreter's version, so a purepdb that stopped supporting an interpreter SMDA still declares
+would be silently held back to its last compatible release under SMDA on that interpreter, with
+nothing reporting the downgrade. Nothing in the parser needs a version above 3.11: it reads a
+little-endian format with `struct` and `pathlib`.
+
+3.11 support ends at whichever of these comes first:
+
+- SMDA and MCRIT both move their floor to 3.12,
+- a runtime dependency drops 3.11 — purepdb has none today, so this is the least likely of the
+  three, or
+- 3.11 reaches end of life, in October 2027.
+
+The release that raises the floor says so in its `Removed` section, and the one before it carries
+a `Deprecated` notice. Raising it is not only metadata: Ruff's pyupgrade rules key on
+`target-version`, so the same change starts rewriting syntax to the new floor and stops being
+reversible by a one-line edit. The places that state it are `requires-python`, the classifiers,
+`[tool.ruff] target-version` and the `ci.yml` matrix.
+
+## Changelog
+
+`CHANGELOG.md` follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). It is the one
+authoritative record of what a release contains: the GitHub release notes are generated from it, and
+nothing is written twice.
+
+- Every pull request that changes something a user can observe adds its own bullet under
+  `## [Unreleased]`, in the subsection it belongs to (`Added`, `Changed`, `Deprecated`, `Removed`,
+  `Fixed`, `Security`), while the change is fresh. The `Changelog` check fails a PR that touches
+  shipped files without touching `CHANGELOG.md`; apply the `no-changelog` label when a change
+  genuinely needs no entry (a typo, a CI-only change), and say why in the PR.
+- An entry says what changed and what it costs the reader: what to do when upgrading, what may
+  behave differently, which issue or PR it closes.
+- Dependency bumps need no entry. GitHub lists them under their own heading in the release notes,
+  from the `dependencies` / `github_actions` labels (`.github/release.yml`).
+
+## Cutting a release
+
+1. Check that `main` is green and that everything meant for the release has merged.
+2. In one commit on a branch, then merged through a PR:
+   - set the new version in `pyproject.toml` (`[project].version`) and `purepdb/__init__.py` (`__version__`);
+   - in `CHANGELOG.md`, rename `## [Unreleased]` to `## [X.Y.Z] - YYYY-MM-DD`, drop the empty
+     subsections, open a fresh empty `## [Unreleased]` above it, and update the compare links at
+     the foot of the file.
+3. Wait for CI to pass on the merge commit. Then tag that commit and push the tag:
+
+   ```bash
+   git tag -a vX.Y.Z -m "purepdb X.Y.Z"
+   git push origin vX.Y.Z
+   ```
+
+Pushing the tag is the release. `.github/workflows/publish-release.yml` then:
+
+1. **Verify** — refuses to continue unless the tag matches both version strings, `CHANGELOG.md`
+   has a `## [X.Y.Z] - ` section (which becomes the release notes), the tagged commit is on
+   `main`, CI passed on that commit, and the milestone named for the tag, if there is one, has no
+   open items.
+2. **Build** — builds the sdist and wheel in an isolated environment, checks their metadata with
+   `twine check --strict`, and installs the wheel into a clean virtual environment to import it,
+   check `__version__` and run the `purepdb` entry point.
+3. **Publish** — uploads to PyPI through [trusted publishing](https://docs.pypi.org/trusted-publishers/)
+   with signed provenance attestations. No API token is stored anywhere.
+4. **Release** — creates the GitHub release for the tag with the changelog section as its body,
+   GitHub's generated contributor and PR list appended under it, and the sdist and wheel attached;
+   then closes the milestone.
+
+A milestone is optional here: name one `vX.Y.Z`, exactly as the tag is written, to have the gate
+see it. A tag with no milestone releases with a notice rather than a failure, so tracking a release
+this way is a choice per release and not a step that has to be remembered.
+
+Each gate fails with a message naming what to fix. Nothing has to be remembered at the console.
+
+## Pre-releases
+
+A release candidate is tagged `vX.Y.Zrc1` (also `a1`, `b1`), with the same version string in
+`pyproject.toml` (`[project].version`) and `purepdb/__init__.py` (`__version__`) and a `## [X.Y.Zrc1] - YYYY-MM-DD` changelog section. The workflow marks the
+GitHub release as a pre-release and does not make it "latest". PyPI
+does not install a pre-release unless it is asked for explicitly (`pip install --pre`).
+
+## Rehearsing
+
+Run *Publish release* manually from the Actions tab, choosing a tag as the ref. A manual run goes
+through the same gates and build, publishes to [TestPyPI](https://test.pypi.org/p/purepdb) instead of
+PyPI (an already-present version is skipped rather than failed), and stops before creating the
+GitHub release. Rehearse the first release after any change to the workflow.
+
+## When a release fails
+
+- **A gate failed before anything was published** (tag/version mismatch, missing changelog section,
+  tag not on `main`, CI not green): fix the cause on `main`, delete the
+  tag locally and on the remote (`git push --delete origin vX.Y.Z`), and tag again once the fix has
+  merged. Nothing needs cleaning up.
+- **Publishing to PyPI failed part-way**: a version number on PyPI is permanent even when yanked,
+  so do not try to reuse it. Fix the cause, bump the patch version, and release again. Yank the
+  incomplete version on PyPI if any of its files were accepted.
+- **The GitHub release step failed after publishing**: re-run only the failed job from the Actions
+  UI; the built artifacts are kept as workflow artifacts and the step is idempotent.
+
+## Maintainer configuration
+
+Done once, by a repository owner; the workflow cannot create these for itself.
+
+- **PyPI trusted publisher** for the `purepdb` project: owner `danielplohmann`, repository `purepdb`,
+  workflow `publish-release.yml`, environment `pypi`. The project already exists on PyPI, so this is
+  added under its own Publishing settings.
+- **TestPyPI trusted publisher**, the same four values with environment `testpypi`, to enable
+  rehearsals. `purepdb` does not exist on TestPyPI, so this one is added as a *pending* publisher
+  (Your projects → Publishing → add a pending publisher), which names a project that is not there
+  yet; the first rehearsal that uploads creates the project and turns it into an ordinary publisher.
+  A rehearsal is the only thing that publishes to TestPyPI — pushing a tag always goes to PyPI.
+- **GitHub environments** `pypi` and `testpypi` (Settings → Environments). Restricting `pypi` to
+  the `v*` tag pattern and requiring a reviewer is recommended: it makes the publish step a
+  deliberate click even if a tag is pushed by mistake.
+- **Label** `no-changelog`, used by the changelog check.
+- Optionally, **immutable releases** (Settings → General → Releases), so a published release's
+  assets and tag can no longer be changed.
diff --git a/tests/test_release_guard.py b/tests/test_release_guard.py
new file mode 100644
index 0000000..a5c042c
--- /dev/null
+++ b/tests/test_release_guard.py
@@ -0,0 +1,122 @@
+"""The release gate (`.github/workflows/scripts/release_guard.py`) runs once per release, minutes
+before the artefact becomes permanent, so here is the only place its checks can be exercised
+before they matter."""
+
+import importlib.util
+from pathlib import Path
+
+import pytest
+
+ROOT = Path(__file__).resolve().parent.parent
+SCRIPT = ROOT / ".github" / "workflows" / "scripts" / "release_guard.py"
+
+CHANGELOG = """# Changelog
+
+## [Unreleased]
+
+### Fixed
+
+- something not yet released.
+
+## [0.6.0] - 2026-09-20
+
+### Changed
+
+- the thing this release did.
+
+## [0.6.0rc1] - 2026-09-15
+
+### Added
+
+- the candidate.
+
+## [0.5.0] - 2026-09-10
+
+### Fixed
+
+- an older release.
+"""
+
+
+@pytest.fixture(scope="module")
+def guard():
+    if not SCRIPT.exists():
+        pytest.skip("running outside a source tree")
+    spec = importlib.util.spec_from_file_location("release_guard", SCRIPT)
+    assert spec is not None and spec.loader is not None
+    module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(module)
+    return module
+
+
+def _tree(tmp_path: Path, version: str, changelog: str = CHANGELOG) -> Path:
+    pyproject = f'[project]\nname = "purepdb"\nversion = "{version}"\n'
+    (tmp_path / "pyproject.toml").write_text(pyproject)
+    (tmp_path / "purepdb").mkdir()
+    (tmp_path / "purepdb" / "__init__.py").write_text(f'__version__ = "{version}"\n')
+    (tmp_path / "CHANGELOG.md").write_text(changelog)
+    return tmp_path
+
+
+def test_the_section_for_a_version_is_returned_and_stops_at_the_next(guard):
+    notes = guard.changelogSection(CHANGELOG, "0.6.0")
+    assert "the thing this release did" in notes
+    assert "the candidate" not in notes
+    assert "not yet released" not in notes
+
+
+def test_a_missing_or_empty_section_fails(guard):
+    with pytest.raises(SystemExit, match="Unreleased"):
+        guard.changelogSection(CHANGELOG, "0.7.0")
+    with pytest.raises(SystemExit, match="nothing under it"):
+        empty = "# Changelog\n\n## [9.0.0] - 2026-01-01\n\n## [8.0.0] - 2025-01-01\n\n- x\n"
+        guard.changelogSection(empty, "9.0.0")
+
+
+def test_an_undated_heading_is_not_a_section(guard):
+    with pytest.raises(SystemExit):
+        guard.changelogSection("# Changelog\n\n## [9.0.0]\n\n- something.\n", "9.0.0")
+
+
+def test_a_v_prefixed_heading_is_accepted(guard):
+    assert "x" in guard.changelogSection("## [v9.0.0] - 2026-01-01\n\n- x\n", "9.0.0")
+
+
+def test_the_declared_versions_in_this_tree_agree(guard):
+    versions = guard.declaredVersions(ROOT)
+    assert set(versions) == {"pyproject.toml", "purepdb.__version__"}
+    assert len(set(versions.values())) == 1
+
+
+def test_a_matching_tag_passes_and_writes_notes_and_outputs(guard, tmp_path):
+    root = _tree(tmp_path, "0.6.0")
+    notes, output = root / "notes.md", root / "output.txt"
+    argv = ["--tag", "v0.6.0", "--root", str(root)]
+    argv += ["--notes", str(notes), "--github-output", str(output)]
+    assert guard.main(argv) == 0
+    assert "the thing this release did" in notes.read_text()
+    assert output.read_text() == "version=0.6.0\nprerelease=false\n"
+
+
+def test_a_pre_release_tag_is_flagged(guard, tmp_path):
+    root = _tree(tmp_path, "0.6.0rc1")
+    output = root / "output.txt"
+    argv = ["--tag", "v0.6.0rc1", "--root", str(root), "--github-output", str(output)]
+    assert guard.main(argv) == 0
+    assert "prerelease=true" in output.read_text()
+
+
+@pytest.mark.parametrize("tag", ["0.6.0", "v0.6", "v0.6.0-rc1", "v0.6.0.dev1", "vlatest"])
+def test_a_malformed_tag_fails(guard, tmp_path, tag):
+    root = _tree(tmp_path, "0.6.0")
+    with pytest.raises(SystemExit):
+        guard.main(["--tag", tag, "--root", str(root)])
+
+
+def test_a_tag_disagreeing_with_any_declared_version_fails(guard, tmp_path):
+    root = _tree(tmp_path, "0.5.0")
+    with pytest.raises(SystemExit, match=r"0\.5\.0"):
+        guard.main(["--tag", "v0.6.0", "--root", str(root)])
+    (root / "pyproject.toml").write_text('[project]\nname = "purepdb"\nversion = "0.6.0"\n')
+    with pytest.raises(SystemExit, match=r"purepdb\.__version__ = 0\.5\.0"):
+        guard.main(["--tag", "v0.6.0", "--root", str(root)])
diff --git a/tests/test_validator.py b/tests/test_validator.py
index 0293c0b..5b00e9b 100644
--- a/tests/test_validator.py
+++ b/tests/test_validator.py
@@ -10,6 +10,7 @@
 """
 
 import importlib.util
+import os
 import struct
 import subprocess
 import sys
@@ -247,7 +248,10 @@ def test_a_negative_diff_limit_is_refused(validator):
 def stub_tool(tmp_path):
     """A stand-in for llvm-pdbutil, so these test the guard under review and
     not whether an LLVM toolchain happens to be installed."""
-    tool = tmp_path / "stub-pdbutil"
+    # Since Python 3.12, shutil.which() on Windows resolves a file only under
+    # one of the PATHEXT extensions, even when handed an absolute path; a
+    # bare "stub-pdbutil" reads as absent there and the guard skips instead.
+    tool = tmp_path / ("stub-pdbutil.bat" if os.name == "nt" else "stub-pdbutil")
     tool.write_text("#!/bin/sh\nexit 0\n")
     tool.chmod(0o755)
     return str(tool)