diff --git a/.cursor/skills/release/SKILL.md b/.cursor/skills/release/SKILL.md index 7fcb7e7..3e2b485 100644 --- a/.cursor/skills/release/SKILL.md +++ b/.cursor/skills/release/SKILL.md @@ -1,90 +1,37 @@ --- name: release description: >- - Prepares a version bump in pyproject.toml, opens a PR from branch release/VERSION - toward main with auto-merge, and coordinates with CI that publishes a GitHub Release - when that branch merges. Use when the user invokes /release, /release VERSION, asks - for a release PR, version bump, or release automation. + Cuts a release with the Prepare release workflow. That workflow opens a + release/VERSION pull request for a person to merge. Merging publishes to + PyPI and tags vVERSION. Use when the user invokes /release, /release VERSION, + asks for a release PR, version bump, or release automation. --- -# Release (`/release` and optional VERSION) +# Release -## When this applies +Follow `RELEASING.md` at the repository root. Leave the pull request for a person to merge. -- User message starts with **`/release`** or **`/release VERSION`** (VERSION optional). -- User asks to cut a release, bump the package version, or open a release PR with auto-merge. +## Version -## Preconditions - -- Working tree clean (`git status`); stash or commit unrelated work first. -- `gh` CLI authenticated (`gh auth status`). -- Remote `origin` is GitHub. -- Repository allows **auto-merge** (Settings → General → Pull Requests → Allow auto-merge). If auto-merge is unavailable, open the PR anyway and tell the user to merge manually after checks pass. - -## Version selection - -1. Read the current version from `pyproject.toml` under `[project]` → `version` (PEP 440 / semver `MAJOR.MINOR.PATCH`). -2. If **VERSION was provided**: set the new version to that string (must match `^\d+\.\d+\.\d+` unless the project already uses a different scheme—then follow existing `pyproject.toml` format). -3. If **VERSION was omitted**: bump the **patch** segment only (e.g. `0.2.1` → `0.2.2`). If the current value is not `x.y.z`, stop and ask the user for an explicit VERSION. +Read `[project].version` in `pyproject.toml`. `/release` with no version means `patch`. `/release X.Y.Z` uses that version. The value is `X.Y.Z`, `patch`, `minor`, or `major`. -## Git identity (this repo) - -Configure once if needed: +## Preconditions -```bash -git config user.email "cursor@proxymesh.com" -git config user.name "Cursor" -``` +- `## Unreleased` in `CHANGELOG.md` on `main` already contains the release notes. +- `gh` CLI authenticated. +- Prepare release is on `main` (`.github/workflows/prepare-release.yml`). ## Steps -1. **Sync main** - - ```bash - git fetch origin main - ``` - -2. **Compute** `NEW_VERSION` (per rules above). **Branch name** is `release/${NEW_VERSION}` (no `v` prefix in the branch name). - -3. **Create branch from latest main** - - ```bash - git checkout -B "release/${NEW_VERSION}" origin/main - ``` - -4. **Edit** `pyproject.toml`: set `version = "NEW_VERSION"` in `[project]`. - -5. **Commit and push** (never push to `main`; push only the release branch) - - ```bash - git add pyproject.toml - git commit -m "chore: bump version to ${NEW_VERSION}" - git push -u origin "release/${NEW_VERSION}" - ``` - -6. **Open PR** into `main` with a short body (no Cursor boilerplate). Example: +1. Run Prepare release from `main`: ```bash - gh pr create --base main --head "release/${NEW_VERSION}" \ - --title "Release ${NEW_VERSION}" \ - --body "Bumps the package version to ${NEW_VERSION} for release." + gh workflow run "Prepare release" --ref main -f version=VERSION ``` -7. **Enable auto-merge** after the PR exists. In non-interactive mode, `gh` requires an explicit merge strategy with `--auto` (use the repository default: usually **`--merge`** for a merge commit, or **`--squash`** / **`--rebase`** if that is what the repo uses). - - ```bash - gh pr merge --auto --merge - ``` - - If `--auto` fails (permissions, auto-merge disabled, or pending checks), leave the PR open and report the error; the user can merge manually after CI passes. You can poll with `gh pr checks --watch` then retry `gh pr merge ... --auto --merge`, or merge manually. - -## After merge - -Merging the PR into `main` runs **Release on merge** (`.github/workflows/github_release_on_release_branch_merge.yml`), which creates a **GitHub Release** for tag `v{version}` from the merge commit. Because releases created with the default `GITHUB_TOKEN` do not trigger other workflows, **Publish to PyPI** (`publish.yml`) is also started via **`workflow_run`** when that release workflow finishes. Manual or API-created releases still match the `release: published` trigger on `publish.yml`. +2. The workflow runs the version, changelog, and package checks, then opens `Release X.Y.Z` from `release/X.Y.Z`. A pull request it opens does not start `pull_request` workflows. +3. Merging publishes to PyPI, tags `vX.Y.Z`, and creates the GitHub Release. -## Quick reference +If Prepare release is not on `main` yet, make the same edits by hand: set `pyproject.toml` `version` and `docs/conf.py` `release`, move `## Unreleased` to `## X.Y.Z - YYYY-MM-DD`, push `release/X.Y.Z`, and open the pull request with that changelog section as the body. -| Input | Result | -|--------------------|---------------------------------------------| -| `/release` | Patch bump, branch `release/x.y.(z+1)` | -| `/release 1.4.0` | Version `1.4.0`, branch `release/1.4.0` | +Git identity for those hand edits: `cursor@proxymesh.com` / `Cursor`. diff --git a/.github/scripts/release_lib.py b/.github/scripts/release_lib.py new file mode 100644 index 0000000..d85000b --- /dev/null +++ b/.github/scripts/release_lib.py @@ -0,0 +1,161 @@ +"""Bump version manifests and print the changelog notes for a release.""" + +import os +import re +import sys +from datetime import datetime, timezone +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +VERSION = re.compile(r"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$") +DATED = re.compile( + r"^## ((?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)) - (\d{4}-\d{2}-\d{2})\s*$" +) + + +def assignment(text, key): + pattern = re.compile( + rf"^(?P
{key}\s*=\s*['\"])(?P[^'\"]*)['\"]\s*$",
+        re.MULTILINE,
+    )
+    found = list(pattern.finditer(text))
+    if len(found) != 1:
+        raise SystemExit(f"expected one {key} assignment, found {len(found)}")
+    return found[0]
+
+
+def parse_version(value):
+    if VERSION.fullmatch(value) is None:
+        raise SystemExit(f"version {value!r} must look like X.Y.Z")
+    return tuple(int(part) for part in value.split("."))
+
+
+def next_version(current, spec):
+    spec = spec.strip()
+    major, minor, patch = parse_version(current)
+    name = spec.lower()
+    if name == "patch":
+        return f"{major}.{minor}.{patch + 1}"
+    if name == "minor":
+        return f"{major}.{minor + 1}.0"
+    if name == "major":
+        return f"{major + 1}.0.0"
+    new = parse_version(spec)
+    if new <= (major, minor, patch):
+        raise SystemExit(f"version {spec} is not newer than {current}")
+    return ".".join(str(part) for part in new)
+
+
+def span(lines, pred):
+    starts = [index for index, line in enumerate(lines) if pred(line)]
+    if len(starts) != 1:
+        raise SystemExit(f"expected one changelog heading, found {len(starts)}")
+    start = starts[0]
+    end = next(
+        (i for i in range(start + 1, len(lines)) if lines[i].startswith("## ")),
+        len(lines),
+    )
+    return start, end
+
+
+def check():
+    pyproject = (ROOT / "pyproject.toml").read_text(encoding="utf-8")
+    docs = (ROOT / "docs" / "conf.py").read_text(encoding="utf-8")
+    version = assignment(pyproject, "version").group("value")
+    docs_version = assignment(docs, "release").group("value")
+    parse_version(version)
+    if docs_version != version:
+        raise SystemExit(
+            f"docs/conf.py release is {docs_version}; pyproject version is {version}."
+        )
+    changelog = (ROOT / "CHANGELOG.md").read_text(encoding="utf-8")
+    dates = [
+        match.group(2)
+        for line in changelog.splitlines()
+        if (match := DATED.match(line.strip())) and match.group(1) == version
+    ]
+    if len(dates) != 1:
+        raise SystemExit(f"CHANGELOG.md needs one '## {version} - YYYY-MM-DD' section.")
+    datetime.strptime(dates[0], "%Y-%m-%d")
+    head = os.environ.get("GITHUB_HEAD_REF") or os.environ.get("HEAD_REF") or ""
+    if head.startswith("release/") and head != f"release/{version}":
+        raise SystemExit(f"branch {head} does not match version {version}.")
+    print(f"Version {version} matches the manifests and CHANGELOG.md.")
+
+
+def write_assignment(path, key, new):
+    text = path.read_text(encoding="utf-8")
+    match = assignment(text, key)
+    path.write_text(
+        text[: match.start("value")] + new + text[match.end("value") :],
+        encoding="utf-8",
+        newline="\n",
+    )
+
+
+def bump():
+    spec = os.environ.get("VERSION_INPUT", "").strip()
+    if not spec:
+        raise SystemExit("Set version to X.Y.Z, patch, minor, or major.")
+    py_path = ROOT / "pyproject.toml"
+    docs_path = ROOT / "docs" / "conf.py"
+    log_path = ROOT / "CHANGELOG.md"
+    pyproject = py_path.read_text(encoding="utf-8")
+    new = next_version(assignment(pyproject, "version").group("value"), spec)
+    day = datetime.now(timezone.utc).date().isoformat()
+    lines = log_path.read_text(encoding="utf-8").splitlines(keepends=True)
+    start, end = span(lines, lambda line: line.strip() == "## Unreleased")
+    body = "".join(lines[start + 1 : end])
+    if not body.strip():
+        raise SystemExit("The Unreleased section in CHANGELOG.md is empty.")
+    heading = f"## {new} - {day}\n"
+    lines[start] = "## Unreleased\n\n" + heading
+    updated = "".join(lines)
+    write_assignment(py_path, "version", new)
+    write_assignment(docs_path, "release", new)
+    log_path.write_text(updated, encoding="utf-8", newline="\n")
+    notes_file = os.environ.get("NOTES_FILE")
+    if notes_file:
+        Path(notes_file).write_text(
+            (heading + body).strip() + "\n",
+            encoding="utf-8",
+            newline="\n",
+        )
+    output = os.environ.get("GITHUB_OUTPUT")
+    if output:
+        with Path(output).open("a", encoding="utf-8") as handle:
+            handle.write(f"version={new}\n")
+    print(new)
+
+
+def notes():
+    version = assignment(
+        (ROOT / "pyproject.toml").read_text(encoding="utf-8"),
+        "version",
+    ).group("value")
+    lines = (
+        (ROOT / "CHANGELOG.md").read_text(encoding="utf-8").splitlines(keepends=True)
+    )
+
+    def is_version(line):
+        match = DATED.match(line.strip())
+        return match is not None and match.group(1) == version
+
+    start, end = span(lines, is_version)
+    sys.stdout.write("".join(lines[start:end]).strip() + "\n")
+
+
+def main(argv):
+    command = argv[1] if len(argv) > 1 else ""
+    if command == "bump":
+        bump()
+    elif command == "check":
+        check()
+    elif command == "notes":
+        notes()
+    else:
+        raise SystemExit("usage: release_lib.py bump|check|notes")
+
+
+if __name__ == "__main__":
+    main(sys.argv)
diff --git a/.github/workflows/github_release_on_release_branch_merge.yml b/.github/workflows/github_release_on_release_branch_merge.yml
deleted file mode 100644
index 941a225..0000000
--- a/.github/workflows/github_release_on_release_branch_merge.yml
+++ /dev/null
@@ -1,68 +0,0 @@
-# When a release/* PR merges into main, create a GitHub release (tag vX.Y.Z).
-# Events from GITHUB_TOKEN do not start other workflows; publish.yml is triggered via
-# workflow_run when this workflow completes (see publish.yml).
-
-name: Release on merge
-
-on:
-  pull_request:
-    types: [closed]
-    branches:
-      - main
-
-concurrency:
-  group: release-on-merge-${{ github.event.pull_request.number }}
-  cancel-in-progress: false
-
-permissions:
-  contents: write
-
-jobs:
-  github-release:
-    if: >-
-      github.event.pull_request.merged == true &&
-      startsWith(github.head_ref, 'release/') &&
-      github.event.pull_request.head.repo.full_name == github.repository
-    runs-on: ubuntu-24.04
-    steps:
-      - name: Checkout merge commit
-        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
-        with:
-          ref: ${{ github.event.pull_request.merge_commit_sha }}
-
-      - name: Set up Python
-        uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
-        with:
-          python-version: "3.12"
-
-      - name: Read version from pyproject.toml
-        id: meta
-        run: |
-          python3 <<'PY'
-          import os
-          import tomllib
-
-          with open("pyproject.toml", "rb") as f:
-              data = tomllib.load(f)
-          version = data["project"]["version"]
-          with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as out:
-              out.write(f"version={version}\n")
-          PY
-
-      - name: Create GitHub Release
-        env:
-          GH_TOKEN: ${{ github.token }}
-        run: |
-          set -euo pipefail
-          VERSION="${{ steps.meta.outputs.version }}"
-          TAG="v${VERSION}"
-          MERGE_SHA="${{ github.event.pull_request.merge_commit_sha }}"
-          if gh release view "${TAG}" --repo "${{ github.repository }}" >/dev/null 2>&1; then
-            echo "Release ${TAG} already exists; skipping."
-            exit 0
-          fi
-          gh release create "${TAG}" \
-            --repo "${{ github.repository }}" \
-            --target "${MERGE_SHA}" \
-            --title "${TAG}" \
-            --generate-notes
diff --git a/.github/workflows/prepare-release.yml b/.github/workflows/prepare-release.yml
new file mode 100644
index 0000000..0af1b67
--- /dev/null
+++ b/.github/workflows/prepare-release.yml
@@ -0,0 +1,80 @@
+# Open a release/X.Y.Z pull request from main.
+# A pull request opened with GITHUB_TOKEN does not run pull_request workflows,
+# so this job runs the release checks before it pushes.
+
+name: Prepare release
+
+on:
+  workflow_dispatch:
+    inputs:
+      version:
+        description: "X.Y.Z, or patch, minor, or major"
+        required: true
+        type: string
+
+permissions: {}
+
+concurrency:
+  group: prepare-release
+  cancel-in-progress: false
+
+jobs:
+  prepare:
+    runs-on: ubuntu-24.04
+    timeout-minutes: 15
+    permissions:
+      contents: write
+      pull-requests: write
+    steps:
+      - name: Require main
+        env:
+          REF: ${{ github.ref }}
+        run: test "$REF" = "refs/heads/main"
+
+      - name: Checkout main
+        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+        with:
+          ref: main
+          persist-credentials: true
+
+      - name: Set up Python
+        uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
+        with:
+          python-version: "3.12"
+
+      - name: Bump version and changelog
+        id: bump
+        env:
+          VERSION_INPUT: ${{ inputs.version }}
+          NOTES_FILE: ${{ runner.temp }}/release-notes.md
+        run: python .github/scripts/release_lib.py bump
+
+      - name: Check version and changelog
+        run: python .github/scripts/release_lib.py check
+
+      - name: Build sdist and wheel
+        run: |
+          python -m pip install --upgrade pip
+          python -m pip install build
+          python -m build
+
+      - name: Open the release pull request
+        env:
+          GH_TOKEN: ${{ github.token }}
+          NOTES_FILE: ${{ runner.temp }}/release-notes.md
+          VERSION: ${{ steps.bump.outputs.version }}
+        run: |
+          set -euo pipefail
+          branch="release/${VERSION}"
+          git checkout -b "$branch"
+          git add -- pyproject.toml docs/conf.py CHANGELOG.md
+          git -c user.name="github-actions[bot]" \
+            -c user.email="41898282+github-actions[bot]@users.noreply.github.com" \
+            commit -m "chore: bump version to ${VERSION}"
+          git push origin "HEAD:refs/heads/${branch}"
+          gh pr create \
+            --repo "$GITHUB_REPOSITORY" \
+            --base main \
+            --head "$branch" \
+            --title "Release ${VERSION}" \
+            --body-file "$NOTES_FILE"
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index fd48bd1..c6e31f4 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -1,133 +1,143 @@
+# pull_request: Release check (versions, changelog, sdist/wheel).
+# push to main: publish when the commit is a merged release/X.Y.Z pull request.
+
 name: Publish to PyPI
 
 on:
-  release:
-    types: [published]
-
-  # Allow manual trigger for testing
-  workflow_dispatch:
-    inputs:
-      test_pypi:
-        description: "Publish to TestPyPI instead of PyPI"
-        required: false
-        default: false
-        type: boolean
-
-  # GitHub does not start new workflow runs for events caused by the default
-  # GITHUB_TOKEN (e.g. gh release create in another workflow). After
-  # "Release on merge" creates a release, trigger publish here instead.
-  workflow_run:
-    workflows: [Release on merge]
-    types: [completed]
+  pull_request:
+    branches: [main]
+  push:
+    branches: [main]
 
 permissions:
   contents: read
-  id-token: write
+
+concurrency:
+  group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.ref }}
+  cancel-in-progress: false
 
 jobs:
-  gate:
+  release-check:
+    name: Release check
+    if: github.event_name == 'pull_request'
     runs-on: ubuntu-24.04
-    outputs:
-      publish: ${{ steps.decide.outputs.publish }}
+    timeout-minutes: 15
+    permissions:
+      contents: read
     steps:
       - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
-        if: github.event_name == 'workflow_run'
         with:
-          ref: main
+          persist-credentials: false
+
+      - name: Set up Python
+        uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
+        with:
+          python-version: "3.12"
+
+      - name: Check version and changelog
+        run: python .github/scripts/release_lib.py check
+
+      - name: Build sdist and wheel
+        run: |
+          python -m pip install --upgrade pip
+          python -m pip install build
+          python -m build
 
-      - id: decide
+  lookup:
+    if: github.event_name == 'push'
+    runs-on: ubuntu-24.04
+    timeout-minutes: 15
+    permissions:
+      pull-requests: read
+    outputs:
+      version: ${{ steps.release.outputs.version }}
+    steps:
+      - name: Find the release pull request
+        id: release
         env:
           GH_TOKEN: ${{ github.token }}
         run: |
           set -euo pipefail
-          if [[ "${{ github.event_name }}" != "workflow_run" ]]; then
-            echo "publish=true" >> "${GITHUB_OUTPUT}"
+          pulls=$(gh api "repos/${GITHUB_REPOSITORY}/commits/${GITHUB_SHA}/pulls")
+          mapfile -t refs < <(
+            jq -r --arg repo "$GITHUB_REPOSITORY" '
+              .[]
+              | select(
+                  .base.ref == "main"
+                  and .merged_at != null
+                  and (.head.ref | startswith("release/"))
+                  and .head.repo.full_name == $repo
+                )
+              | .head.ref
+            ' <<<"$pulls"
+          )
+          if [ "${#refs[@]}" -eq 0 ]; then
+            echo "Not a release merge."
             exit 0
           fi
-          if [[ "${{ github.event.workflow_run.conclusion }}" != "success" ]]; then
-            echo "publish=false" >> "${GITHUB_OUTPUT}"
-            exit 0
-          fi
-          VERSION="$(grep -m1 '^version = ' pyproject.toml | cut -d'"' -f2)"
-          TAG="v${VERSION}"
-          if gh release view "${TAG}" --repo "${{ github.repository }}" >/dev/null 2>&1; then
-            echo "publish=true" >> "${GITHUB_OUTPUT}"
-          else
-            echo "No GitHub release ${TAG} yet (or release job was skipped); skipping publish."
-            echo "publish=false" >> "${GITHUB_OUTPUT}"
+          if [ "${#refs[@]}" -ne 1 ]; then
+            echo "This commit matches more than one release pull request."
+            exit 1
           fi
+          version="${refs[0]#release/}"
+          echo "version=${version}" >> "$GITHUB_OUTPUT"
 
-  build:
-    name: Build distribution
-    needs: gate
-    if: needs.gate.outputs.publish == 'true'
+  publish:
+    needs: lookup
+    if: needs.lookup.outputs.version != ''
     runs-on: ubuntu-24.04
-
+    timeout-minutes: 15
+    environment:
+      name: pypi
+      url: https://pypi.org/p/python-proxy-headers
+    permissions:
+      contents: read
+      id-token: write
     steps:
       - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
         with:
-          ref: ${{ github.event_name == 'workflow_run' && 'main' || github.event_name == 'release' && github.ref || 'main' }}
+          persist-credentials: false
 
       - name: Set up Python
         uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
         with:
-          python-version: "3.x"
+          python-version: "3.12"
+
+      - name: Check version and changelog
+        env:
+          HEAD_REF: release/${{ needs.lookup.outputs.version }}
+        run: python .github/scripts/release_lib.py check
 
-      - name: Install build dependencies
+      - name: Build sdist and wheel
         run: |
           python -m pip install --upgrade pip
-          pip install build
-
-      - name: Build package
-        run: python -m build
-
-      - name: Store distribution packages
-        uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
-        with:
-          name: python-package-distributions
-          path: dist/
-
-  publish-to-pypi:
-    name: Publish to PyPI
-    if: >-
-      github.event_name == 'workflow_run' ||
-      github.event_name == 'release' ||
-      (github.event_name == 'workflow_dispatch' && inputs.test_pypi == false)
-    needs: build
-    runs-on: ubuntu-24.04
-
-    environment:
-      name: pypi
-      url: https://pypi.org/p/python-proxy-headers
-
-    steps:
-      - name: Download distribution packages
-        uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
-        with:
-          name: python-package-distributions
-          path: dist/
+          python -m pip install build
+          python -m build
 
       - name: Publish to PyPI
         uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3
 
-  publish-to-testpypi:
-    name: Publish to TestPyPI
-    if: github.event_name == 'workflow_dispatch' && inputs.test_pypi == true
-    needs: build
+  github-release:
+    needs: [lookup, publish]
+    if: needs.lookup.outputs.version != ''
     runs-on: ubuntu-24.04
-
-    environment:
-      name: testpypi
-      url: https://test.pypi.org/p/python-proxy-headers
-
+    timeout-minutes: 15
+    permissions:
+      contents: write
     steps:
-      - name: Download distribution packages
-        uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
+      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
         with:
-          name: python-package-distributions
-          path: dist/
+          persist-credentials: false
 
-      - name: Publish to TestPyPI
-        uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3
-        with:
-          repository-url: https://test.pypi.org/legacy/
+      - name: Create GitHub Release
+        env:
+          GH_TOKEN: ${{ github.token }}
+          VERSION: ${{ needs.lookup.outputs.version }}
+        run: |
+          set -euo pipefail
+          python3 .github/scripts/release_lib.py notes > "$RUNNER_TEMP/notes.md"
+          gh release view "v${VERSION}" \
+            || gh release create "v${VERSION}" \
+              --target "$GITHUB_SHA" \
+              --title "v${VERSION}" \
+              --notes-file "$RUNNER_TEMP/notes.md"
diff --git a/README.md b/README.md
index 10dacc4..6225b35 100644
--- a/README.md
+++ b/README.md
@@ -158,6 +158,7 @@ For detailed documentation, API reference, and more examples:
 
 - **Full Documentation:** [python-proxy-headers.readthedocs.io](https://python-proxy-headers.readthedocs.io/en/latest/)
 - **Example Code:** [proxy-examples for Python](https://github.com/proxymesh/proxy-examples/tree/main/python)
+- **Releasing:** [RELEASING.md](RELEASING.md)
 
 ## Other languages
 
diff --git a/RELEASING.md b/RELEASING.md
new file mode 100644
index 0000000..60b221d
--- /dev/null
+++ b/RELEASING.md
@@ -0,0 +1,46 @@
+# Releasing
+
+## Cut a release
+
+1. On `main`, write the notes under `## Unreleased` in `CHANGELOG.md` and merge them.
+2. Actions → **Prepare release** → **Run workflow** on `main`.
+3. Set **version** to `X.Y.Z`, or to `patch`, `minor`, or `major`.
+4. The workflow bumps `pyproject.toml` and `docs/conf.py`, moves Unreleased to `## X.Y.Z - YYYY-MM-DD`, runs the release checks, and builds the sdist and wheel. It then opens a pull request titled `Release X.Y.Z` from `release/X.Y.Z`. The body is that changelog section.
+5. Merge the pull request into `main`.
+
+A pull request opened with `GITHUB_TOKEN` does not start `pull_request` workflows, so Prepare release runs the checks before it pushes. A release pull request opened by hand uses the same publish path: branch `release/X.Y.Z`, both version manifests, and a dated changelog section. **Release check** runs on that pull request.
+
+## What runs
+
+### Prepare release
+
+`.github/workflows/prepare-release.yml` on `workflow_dispatch`, from `main`, runner `ubuntu-24.04`.
+
+Version manifests:
+
+- `pyproject.toml` field `version`
+- `docs/conf.py` field `release`
+
+### Release check
+
+The **Release check** job in `.github/workflows/publish.yml` runs on pull requests to `main`. It checks that the version manifests match, that `CHANGELOG.md` has `## X.Y.Z - YYYY-MM-DD` for that version, and that a `release/*` branch name matches it. It builds the sdist and wheel.
+
+Don't make Release check a required check: release PRs are opened with GITHUB_TOKEN, so it doesn't run on them unless you close and reopen the PR.
+
+### Publish
+
+A push to `main` looks up the pull request for that commit. When the pull request
+came from `release/X.Y.Z`, the **publish** job builds the package and uploads it
+to PyPI with the existing trusted publisher and the GitHub environment `pypi`
+(unchanged). A version that is already on PyPI fails the upload. The
+**github-release** job then runs `gh release view vX.Y.Z` or creates that
+release. The notes are the changelog section.
+
+## One-time owner setup
+
+1. Settings → Actions → General → Workflow permissions: allow GitHub Actions to
+   create pull requests. Dependabot auto-merge already needs that.
+
+## Tags
+
+Tags are `vX.Y.Z`. Existing tags `v0.1.0` through `v0.2.4` already use that form and stay as they are.