diff --git a/.github/release.yml b/.github/release.yml new file mode 100644 index 00000000..63fbd63a --- /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 index 33f37a7a..deac3439 100644 --- a/.github/workflows/changelog.yml +++ b/.github/workflows/changelog.yml @@ -14,7 +14,6 @@ on: - unlabeled branches: - master - - main permissions: contents: read @@ -28,7 +27,7 @@ jobs: # 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 an engine change + - name: Require a changelog entry beside a user-visible change env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} REPOSITORY: ${{ github.repository }} @@ -36,6 +35,7 @@ jobs: # 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 @@ -43,18 +43,22 @@ jobs: 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 -q '^src/smda/'; then - echo "No files under src/smda/ changed; entry not required." + if ! printf '%s\n' "${changed}" | grep -qE '^(src/smda/|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 engine change." + echo "CHANGELOG.md touched beside the change." exit 0 fi - echo "::error file=CHANGELOG.md::This PR changes src/smda/ but does not touch CHANGELOG.md. Add an entry under ## Unreleased describing what moved and what it cost, or apply the no-changelog label if the change genuinely needs no entry." + 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 00000000..bc650607 --- /dev/null +++ b/.github/workflows/publish-release.yml @@ -0,0 +1,266 @@ +name: Publish release + +# A manual run rehearses against TestPyPI and stops before the GitHub release. +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 master + env: + TAG: ${{ github.ref_name }} + run: | + git fetch --quiet origin master + if ! git merge-base --is-ancestor "${TAG}" origin/master; then + echo "::error::${TAG} is not an ancestor of master; releases are cut from master." + 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 master to go green, then re-run." + exit 1 + fi + if [ "${conclusion}" != "success" ]; then + echo "::error::CI concluded '${conclusion}' for ${SHA}. Fix master before releasing." + exit 1 + fi + echo "CI passed on ${SHA}" + + - 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 }} + + - name: Build the sdist and the wheel + run: | + python -m pip install --upgrade pip build twine + python -m build + python -m twine check --strict dist/* + + # -P keeps the checkout off sys.path, so the import cannot fall back to the source tree + - 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/smda-"${VERSION}"-py3-none-any.whl + /tmp/smoke/bin/python -P - <<'PY' + import os + import pathlib + + import smda + from smda.Disassembler import Disassembler + from smda.SmdaConfig import SmdaConfig + + installed = pathlib.Path(smda.__file__).parent + assert "site-packages" in str(installed), f"imported a source tree: {installed}" + assert smda.__version__ == os.environ["VERSION"], smda.__version__ + assert (installed / "py.typed").exists(), "py.typed did not ship" + + raw = pathlib.Path("tests/cutwail_xored").read_bytes() + report = Disassembler(SmdaConfig()).disassembleUnmappedBuffer( + bytes(byte ^ (index % 256) for index, byte in enumerate(raw)) + ) + assert report.status == "ok", report.status + assert report.num_functions > 0, "the wheel recovered nothing" + print(f"smda {smda.__version__}: {report.num_functions} functions, status {report.status}") + PY + + - 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/smda' || 'https://pypi.org/p/smda' }} + 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[@]}" + + - 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/scripts/release_guard.py b/.github/workflows/scripts/release_guard.py new file mode 100644 index 00000000..2b46620b --- /dev/null +++ b/.github/workflows/scripts/release_guard.py @@ -0,0 +1,104 @@ +"""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 = [ + ("smda.__version__", "src/smda/__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}] - ` or `## [v{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 4f5b8265..7776dddd 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -111,13 +111,7 @@ ida_analyze.py   # IDA-side analysis/export helper
 
 ## Versioning & Releases
 
-When a change warrants a version bump, update **all three** in one commit:
-
-1. `src/smda/__init__.py` → `__version__`
-2. `src/smda/SmdaConfig.py` → `SmdaConfig.VERSION`
-3. `CHANGELOG.md` → rename `## [Unreleased]` to `## [vX.Y.Z] - YYYY-MM-DD`, drop the subsections the release did not use, open a fresh empty `## [Unreleased]` above it, and update the compare links at the foot of the file.
-
-Keep the two version strings in sync. Do not bump versions unless the change is a release-worthy change (and see Git Workflow re: explicit ask).
+The version is declared once, in `src/smda/__init__.py` (`__version__`); `pyproject.toml` reads it dynamically and `SmdaConfig.VERSION` imports it. A release bumps that line and `CHANGELOG.md` in one commit: rename `## [Unreleased]` to `## [vX.Y.Z] - YYYY-MM-DD`, drop the subsections the release did not use, open a fresh empty `## [Unreleased]` above it, and update the compare links at the foot of the file. Do not bump the version unless the change is a release-worthy change (and see Git Workflow re: explicit ask).
 
 **Scope lives in a milestone named for the tag.** A PR joins `vX.Y.Z` when it is accepted for that
 release rather than when it is opened, so the milestone stays a list of what is left rather than a
@@ -128,7 +122,9 @@ the changelog records what landed and what it cost, the milestone what has not l
 
 **Tag after `master` is green, not at merge.** A tag created on the merge commit before CI has confirmed the merged tree can need moving, and moving one a PyPI publish has already consumed is a different problem from moving one nobody has fetched.
 
-Every other PR writes its own bullet under `## [Unreleased]` as it merges, rather than the release being reconstructed from merge commits afterwards — see *How an entry is written* in `CHANGELOG.md` for the subsections, the scope prefix and the four content rules. `.github/workflows/changelog.yml` requires a PR touching `src/smda/` to touch `CHANGELOG.md` or carry the `no-changelog` label.
+**Pushing the tag is the release.** `.github/workflows/publish-release.yml` builds, publishes to PyPI through trusted publishing, creates the GitHub release from this version's `CHANGELOG.md` section, and closes the milestone. It refuses to publish unless the tag matches `__version__`, this version has a changelog section, the commit is on `master`, CI passed on that commit, and the milestone for the tag has no open items. The full procedure — cutting, rehearsing against TestPyPI, pre-releases, recovery, what a maintainer configures once — is in [`RELEASING.md`](RELEASING.md), which is the same process every MCRIT ecosystem repository follows.
+
+Every other PR writes its own bullet under `## [Unreleased]` as it merges, rather than the release being reconstructed from merge commits afterwards — see *How an entry is written* in `CHANGELOG.md` for the subsections, the scope prefix and the four content rules. `.github/workflows/changelog.yml` requires a PR touching `src/smda/` or `pyproject.toml` to touch `CHANGELOG.md` or carry the `no-changelog` label.
 
 ## Git Workflow
 
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 04c6c9cd..1837c41f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -72,10 +72,35 @@ past roughly six lines it belongs in the PR the entry links.
 
 ### Added
 
+- **(ci)** Pushing a `vX.Y.Z` tag now releases: the workflow builds, publishes to PyPI through
+  trusted publishing, creates the GitHub release from that version's changelog section, and closes
+  the milestone named for the tag. It refuses to publish unless the tag matches the packaged
+  version, the version has a changelog section, the commit is on `master`, CI passed on that
+  commit, and the milestone has no open items — the checks that previously lived in a person's
+  memory between `make package` and `make publish`. No API token is stored anywhere, and each file
+  carries signed provenance. Pre-release tags (`v4.7.0rc1`) are marked as such. A manual run
+  rehearses the whole path against TestPyPI. The process is documented in `RELEASING.md` and is
+  the one every MCRIT ecosystem repository follows. (#343)
+
 ### Changed
 
+- **(core)** `SmdaConfig.VERSION` is read from `smda.__version__` instead of being a second literal
+  kept in sync by hand, so a release bumps one line. `report.smda_version` is unchanged. (#343)
+
+- **(build)** `pyproject.toml` declares the license as the SPDX expression `BSD-2-Clause` with
+  `license-files` (PEP 639) instead of the free-text form and the deprecated license classifier,
+  and gains `Repository`, `Issues` and `Changelog` URLs. Building now needs `setuptools>=77`; the
+  wheel's metadata is otherwise unchanged. (#343)
+
 ### Deprecated
 
+- **(build)** Python 3.11 support will end at whichever comes first: MCRIT and purepdb moving their
+  floor to 3.12, a runtime dependency dropping 3.11, or 3.11's end of life in October 2027. SMDA's
+  floor follows MCRIT's and the two move together, because an SMDA that dropped an interpreter MCRIT
+  still declares would be silently held back under MCRIT rather than failing. This affects
+  `smda.ida` users too: IDA 9.3 and 9.4 accept any Python from 3.8 through `idapyswitch`, so an IDA
+  pointed at 3.11 or older will need switching to 3.12 or newer once the floor moves. (#343)
+
 ### Removed
 
 ### Fixed
diff --git a/RELEASING.md b/RELEASING.md
new file mode 100644
index 00000000..7687ad64
--- /dev/null
+++ b/RELEASING.md
@@ -0,0 +1,138 @@
+# Releasing SMDA
+
+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
+
+**The SMDA version is a release counter, not semantic versioning.** The top of `CHANGELOG.md` says what
+that means and which three constants carry the compatibility promise for report consumers instead.
+Scope for a release is tracked in a GitHub milestone named for the tag (`v4.7.0`); see
+`AGENTS.md`, *Versioning & Releases*.
+
+The version is declared in `src/smda/__init__.py` (`__version__`; `pyproject.toml` reads it dynamically and
+`SmdaConfig.VERSION` imports it). 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
+
+SMDA supports Python 3.11 through 3.14, and CI runs every one of them.
+
+The floor follows MCRIT's rather than being set on its own, and the two move in the same release
+wave. An installer resolves a dependency by the interpreter's version, so an SMDA that stopped
+supporting an interpreter MCRIT still declares would be silently held back to its last compatible
+release under MCRIT on that interpreter, with nothing reporting the downgrade.
+
+3.11 support ends at whichever of these comes first:
+
+- MCRIT and purepdb both move their floor to 3.12,
+- a runtime dependency drops 3.11, 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.
+
+## 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 `master` 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 `src/smda/__init__.py` (`__version__`; `pyproject.toml` reads it dynamically and
+`SmdaConfig.VERSION` imports it);
+   - in `CHANGELOG.md`, rename `## [Unreleased]` to `## [vX.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 "SMDA 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 `__version__`, `CHANGELOG.md` has a
+   `## [vX.Y.Z] - ` section (which becomes the release notes), the tagged commit is on
+   `master`, the `ci.yml` workflow 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 carrying only
+   the declared runtime dependencies to disassemble a bundled sample with it.
+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.
+
+Each gate fails with a message naming what to fix. Nothing has to be remembered at the console.
+
+The CI gate reads `ci.yml` only. Fuzzing, the security audit and the performance and correctness
+benchmark also run on `master` and are not checked here — the benchmark reports `skipping` on some
+events, and a gate that can never complete is worse than a narrow one — so confirm those by eye
+before tagging, the benchmark above all, since it is the one that catches a recovery regression.
+
+## Pre-releases
+
+A release candidate is tagged `vX.Y.Zrc1` (also `a1`, `b1`), with the same version string in
+`src/smda/__init__.py` (`__version__`; `pyproject.toml` reads it dynamically and
+`SmdaConfig.VERSION` imports it) and a `## [vX.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/smda) 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.
+
+A manual run uses the workflow file as it exists at the chosen tag, so a tag cut before this
+workflow existed has none to run. The first rehearsal needs a tag cut afterwards — a throwaway
+pre-release such as `vX.Y.Zrc0` is enough.
+
+## When a release fails
+
+- **A gate failed before anything was published** (tag/version mismatch, missing changelog section,
+  tag not on `master`, CI not green): fix the cause on `master`, 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 `smda` project: owner `danielplohmann`, repository `smda`,
+  workflow `publish-release.yml`, environment `pypi`. Add the same publisher on TestPyPI with
+  environment `testpypi` to enable rehearsals.
+- **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` (already present), 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/pyproject.toml b/pyproject.toml
index 8cfa3fed..b834d8e7 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,5 +1,5 @@
 [build-system]
-requires = ["setuptools>=64.0.0,<84.1.0", "wheel>=0.47.0"]
+requires = ["setuptools>=77,<84.1.0"]
 build-backend = "setuptools.build_meta"
 
 [project]
@@ -7,13 +7,13 @@ name = "smda"
 description = "A recursive disassmbler optimized for CFG recovery from memory dumps. Based on capstone."
 readme = "README.md"
 requires-python = ">=3.11"
-license = {text = "BSD 2-Clause"}
+license = "BSD-2-Clause"
+license-files = ["LICENSE"]
 authors = [
     {name = "Daniel Plohmann", email = "daniel.plohmann@mailbox.org"}
 ]
 classifiers = [
     "Development Status :: 4 - Beta",
-    "License :: OSI Approved :: BSD License",
     "Operating System :: OS Independent",
     "Programming Language :: Python :: 3",
     "Programming Language :: Python :: 3.11",
@@ -39,6 +39,9 @@ dependencies = [
 
 [project.urls]
 Homepage = "https://github.com/danielplohmann/smda"
+Repository = "https://github.com/danielplohmann/smda"
+Issues = "https://github.com/danielplohmann/smda/issues"
+Changelog = "https://github.com/danielplohmann/smda/blob/master/CHANGELOG.md"
 
 [project.optional-dependencies]
 dev = [
diff --git a/src/smda/SmdaConfig.py b/src/smda/SmdaConfig.py
index b8df1e1e..725e6043 100644
--- a/src/smda/SmdaConfig.py
+++ b/src/smda/SmdaConfig.py
@@ -1,10 +1,11 @@
 import logging
 import os
 
+from smda import __version__
+
 
 class SmdaConfig:
-    # keep this in sync with smda.__version__
-    VERSION = "4.7.0"
+    VERSION = __version__
     # Bump this whenever any architecture's InstructionEscaper changes its
     # output (mnemonic groups or escaped operands). Downstream indexes such as
     # MCRIT treat reports whose smda_version is below this value as stale.
diff --git a/tests/testReleaseGuard.py b/tests/testReleaseGuard.py
new file mode 100644
index 00000000..4a9ee31b
--- /dev/null
+++ b/tests/testReleaseGuard.py
@@ -0,0 +1,151 @@
+#!/usr/bin/python
+"""Tests for the release gate (`.github/workflows/scripts/release_guard.py`).
+
+Its checks run once per release, minutes before the artifact becomes permanent, so here is the
+only place they can be exercised before they matter.
+"""
+
+import importlib.util
+import tempfile
+import unittest
+from pathlib import Path
+
+_TESTS = Path(__file__).resolve().parent
+_ROOT = _TESTS.parent
+_SCRIPT = _ROOT / ".github" / "workflows" / "scripts" / "release_guard.py"
+
+
+def _load_module():
+    spec = importlib.util.spec_from_file_location("release_guard", _SCRIPT)
+    module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(module)
+    return module
+
+
+guard = _load_module()
+
+CHANGELOG = """# Changelog
+
+## [Unreleased]
+
+### Fixed
+
+- **(intel)** something not yet released. (#1)
+
+## [v4.7.0] - 2026-09-20
+
+### Changed
+
+- **(common)** the thing this release did. (#2)
+
+### Compatibility
+
+- recovery output moves. (#2)
+
+## [4.7.0rc1] - 2026-09-15
+
+### Added
+
+- the candidate. (#2)
+
+## [v4.6.0] - 2026-09-10
+
+### Fixed
+
+- an older release. (#3)
+
+## Older releases
+
+ * 2026-09-10: v4.6.0 - the one-line shape.
+"""
+
+
+class ChangelogSectionTest(unittest.TestCase):
+    def testTheSectionForAVersionIsReturned(self):
+        notes = guard.changelogSection(CHANGELOG, "4.7.0")
+        self.assertIn("the thing this release did", notes)
+        self.assertIn("### Compatibility", notes)
+
+    def testTheSectionStopsAtTheNextRelease(self):
+        # without the stop it would swallow every older entry and the whole Older releases block
+        notes = guard.changelogSection(CHANGELOG, "4.7.0")
+        self.assertNotIn("the candidate", notes)
+        self.assertNotIn("an older release", notes)
+        self.assertNotIn("Older releases", notes)
+
+    def testAHeadingWithOrWithoutTheVPrefixIsASection(self):
+        self.assertIn("the candidate", guard.changelogSection(CHANGELOG, "4.7.0rc1"))
+        self.assertIn("an older release", guard.changelogSection(CHANGELOG, "4.6.0"))
+
+    def testAnUnreleasedSectionIsNotAVersion(self):
+        # `## [Unreleased]` carries no date, so it cannot be mistaken for the release being cut
+        self.assertNotIn("not yet released", guard.changelogSection(CHANGELOG, "4.7.0"))
+        with self.assertRaises(SystemExit):
+            guard.changelogSection(CHANGELOG, "Unreleased")
+
+    def testAMissingSectionFailsAndSaysWhatToDo(self):
+        with self.assertRaises(SystemExit) as raised:
+            guard.changelogSection(CHANGELOG, "4.8.0")
+        self.assertIn("Unreleased", str(raised.exception))
+
+    def testAHeadingWithNothingUnderItFails(self):
+        # renaming Unreleased without writing anything into it is the shape this catches
+        empty = "# Changelog\n\n## [v9.0.0] - 2026-01-01\n\n## Older releases\n"
+        with self.assertRaises(SystemExit):
+            guard.changelogSection(empty, "9.0.0")
+
+    def testAnUndatedHeadingIsNotASection(self):
+        undated = "# Changelog\n\n## [v9.0.0]\n\n- something. (#1)\n"
+        with self.assertRaises(SystemExit):
+            guard.changelogSection(undated, "9.0.0")
+
+
+class DeclaredVersionTest(unittest.TestCase):
+    def testTheVersionIsReadFromTheRealTree(self):
+        versions = guard.declaredVersions(_ROOT)
+        self.assertEqual(set(versions), {"smda.__version__"})
+        self.assertRegex(versions["smda.__version__"], r"^\d+\.\d+\.\d+")
+
+
+class MainTest(unittest.TestCase):
+    """The gate as the workflow calls it."""
+
+    def _tree(self, version, changelog):
+        root = Path(tempfile.mkdtemp())
+        package = root / "src" / "smda"
+        package.mkdir(parents=True)
+        (package / "__init__.py").write_text(f'__version__ = "{version}"\n', encoding="utf-8")
+        (root / "CHANGELOG.md").write_text(changelog, encoding="utf-8")
+        return root
+
+    def testAMatchingTagPassesAndWritesTheNotesAndOutputs(self):
+        root = self._tree("4.7.0", CHANGELOG)
+        notes = root / "notes.md"
+        output = root / "output.txt"
+        argv = ["--tag", "v4.7.0", "--root", str(root), "--notes", str(notes), "--github-output", str(output)]
+        self.assertEqual(guard.main(argv), 0)
+        self.assertIn("the thing this release did", notes.read_text(encoding="utf-8"))
+        self.assertEqual(output.read_text(encoding="utf-8"), "version=4.7.0\nprerelease=false\n")
+
+    def testAPreReleaseTagIsFlagged(self):
+        root = self._tree("4.7.0rc1", CHANGELOG)
+        output = root / "output.txt"
+        self.assertEqual(guard.main(["--tag", "v4.7.0rc1", "--root", str(root), "--github-output", str(output)]), 0)
+        self.assertIn("prerelease=true", output.read_text(encoding="utf-8"))
+
+    def testATagThatDisagreesWithThePackagedVersionFails(self):
+        # nothing else in the release notices that the tag names a different version
+        root = self._tree("4.6.0", CHANGELOG)
+        with self.assertRaises(SystemExit) as raised:
+            guard.main(["--tag", "v4.7.0", "--root", str(root)])
+        self.assertIn("4.6.0", str(raised.exception))
+
+    def testAMalformedTagFails(self):
+        root = self._tree("4.7.0", CHANGELOG)
+        for tag in ("4.7.0", "v4.7", "v4.7.0-rc1", "v4.7.0.dev1", "vlatest"):
+            with self.subTest(tag=tag), self.assertRaises(SystemExit):
+                guard.main(["--tag", tag, "--root", str(root)])
+
+
+if __name__ == "__main__":
+    unittest.main()