diff --git a/.github/workflows/ci-macos-packaging.yml b/.github/workflows/ci-macos-packaging.yml index 2e6be773..5e1fa93f 100644 --- a/.github/workflows/ci-macos-packaging.yml +++ b/.github/workflows/ci-macos-packaging.yml @@ -5,12 +5,14 @@ on: paths: - '.github/workflows/ci-macos-packaging.yml' - '.github/workflows/release-macos.yml' + - '.github/workflows/release-finalize.yml' - 'scripts/macos/**' push: branches: [main] paths: - '.github/workflows/ci-macos-packaging.yml' - '.github/workflows/release-macos.yml' + - '.github/workflows/release-finalize.yml' - 'scripts/macos/**' permissions: diff --git a/.github/workflows/ci-portable.yml b/.github/workflows/ci-portable.yml index 585d2fda..a2e366f8 100644 --- a/.github/workflows/ci-portable.yml +++ b/.github/workflows/ci-portable.yml @@ -142,6 +142,8 @@ jobs: run: python3 scripts/docs/validate-manifest.py - name: Flatpak icon validation run: python3 scripts/release/test-flatpak-icon.py + - name: Release publication regression tests + run: python3 scripts/release/test-publication.py - name: Program status acceptance fixture tests run: python3 -m unittest discover -s scripts/terminal -p 'test_*.py' - name: Release script syntax checks diff --git a/.github/workflows/release-finalize.yml b/.github/workflows/release-finalize.yml index 88254791..54b3d5af 100644 --- a/.github/workflows/release-finalize.yml +++ b/.github/workflows/release-finalize.yml @@ -1,242 +1,237 @@ name: Finalize release -# Promotes a draft release to public once every platform-specific -# release workflow (release-linux.yml, release-macos.yml, -# release-windows.yml) has reported a `success` conclusion for the -# same tag. -# -# Why this exists -# --------------- -# The three platform release workflows are independent (each fans out -# from `push: tags`). They share a single GitHub release: whichever -# job calls `gh release create` first wins the create, and the others -# just upload to it. Until this workflow existed, the create call -# also published the release immediately, so the moment the FASTEST -# platform finished its `publish` job the release became visible at -# `/releases/latest` — even though the other two platforms still -# hadn't uploaded their assets. Fresh installs hit the symptom -# -# irm https://nowled.ge/con-ps1 | iex -# ✗ no ZIP found for windows-x86_64 -# -# (the tag was "latest" but only the Linux tarball was attached). -# -# Fix shape -# --------- -# release-{linux,macos,windows}.yml now create the release with -# `--draft`. Drafts are invisible to `/releases/latest`, the public -# REST API, and the public UI listing — install.sh / install.ps1 -# behave as if the tag does not exist yet, which is the correct -# answer while assets are still uploading. -# -# This workflow watches the three release workflows, verifies the -# release assets/appcasts/installers still agree on the same tag, -# and only then flips the draft to public via -# `gh release edit --draft=false`. If one platform or the final -# release gate fails, the draft stays a draft (intentional — better -# to block than to ship an incomplete release; the maintainer can -# either re-run the failing job or flip the draft manually via the -# UI once the situation is understood). -# -# Notes on workflow_run semantics -# ------------------------------- -# - `workflow_run` only fires when the file is on the default branch. -# That matches every other tag-driven workflow in this repo. -# - For tag pushes, `github.event.workflow_run.head_branch` is the -# tag name (e.g. `v0.1.0-beta.35`). We use it to derive the tag, -# and we use `head_sha` to correlate runs across the three sibling -# workflows. -# - Every completion event gets its own finalizer run. Do not collapse -# these events into one concurrency group: GitHub keeps only one -# pending run per group, so a later platform completion can otherwise -# cancel the event that would have promoted the release. - +# Signed metadata is prepared at tag-scoped staging paths. Only this workflow +# can update the canonical feeds, after publication and anonymous HTTP checks. on: workflow_run: workflows: - "Release Linux" - "Release macOS" - "Release Windows" - types: - - completed + types: [completed] + workflow_dispatch: + inputs: + tag: + description: "Existing release tag to reconcile (no rebuild or retag)" + required: true + type: string permissions: contents: write actions: read -# Keep each workflow_run completion independent. GitHub concurrency has -# one running slot and one pending slot per group; sharing a tag or -# repository-wide group silently drops completion events. The source -# run ID is unique, so all three completion events get a chance to run. +# Do not collapse sibling completion events into one pending concurrency slot. concurrency: - group: release-finalize-${{ github.event.workflow_run.id }} + group: release-finalize-${{ github.event.workflow_run.id || github.run_id }} cancel-in-progress: false jobs: finalize: - name: Promote draft when all platforms ship + name: Reconcile release and publish verified updater feeds runs-on: ubuntu-latest - - # Skip everything that didn't come from a `push` to a tag — - # workflow_run fires for every conclusion (cancelled, skipped, - # failure, success) and for every event type the source workflow - # accepts. We only care about tag-push completions. + timeout-minutes: 20 + outputs: + tag: ${{ steps.ctx.outputs.tag }} + ready: ${{ steps.gate.outputs.ready }} if: >- - github.event.workflow_run.event == 'push' && - startsWith(github.event.workflow_run.head_branch, 'v') + github.event_name == 'workflow_dispatch' || + (github.event.workflow_run.event == 'push' && + startsWith(github.event.workflow_run.head_branch, 'v')) steps: - - name: Resolve tag and head sha + # Use maintained finalization logic so recovery need not rebuild an old + # tag. Accept only tags whose commits are on main, never dispatch code. + - uses: actions/checkout@v5 + with: + ref: main + fetch-depth: 0 + + - name: Resolve and validate immutable tag id: ctx env: - HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }} - HEAD_SHA: ${{ github.event.workflow_run.head_sha }} - TRIGGER_WORKFLOW: ${{ github.event.workflow_run.name }} - TRIGGER_CONCLUSION: ${{ github.event.workflow_run.conclusion }} + TAG: ${{ inputs.tag || github.event.workflow_run.head_branch }} + EXPECTED_SHA: ${{ github.event.workflow_run.head_sha }} run: | set -euo pipefail - echo "Triggered by: $TRIGGER_WORKFLOW (conclusion=$TRIGGER_CONCLUSION)" - echo "Tag: $HEAD_BRANCH" - echo "Head SHA: $HEAD_SHA" - echo "tag=$HEAD_BRANCH" >>"$GITHUB_OUTPUT" - echo "sha=$HEAD_SHA" >>"$GITHUB_OUTPUT" - - - name: Wait for all three platform workflows to succeed + [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-(beta|dev)\.[0-9]+)?$ ]] || exit 1 + sha="$(git rev-parse "refs/tags/${TAG}^{commit}")" + git merge-base --is-ancestor "$sha" origin/main + [[ -z "$EXPECTED_SHA" || "$sha" == "$EXPECTED_SHA" ]] || exit 1 + echo "tag=$TAG" >>"$GITHUB_OUTPUT" + echo "sha=$sha" >>"$GITHUB_OUTPUT" + + - name: Reconcile required platform workflows id: gate env: GH_TOKEN: ${{ github.token }} GH_REPO: ${{ github.repository }} - HEAD_SHA: ${{ steps.ctx.outputs.sha }} - # Strategy: for each of the three release workflow files, - # query its workflow_runs filtered by head_sha and event=push. - # The newest matching run must be completed successfully. A - # previous success is not enough: a later retry may have failed. - # If all three latest runs are successful, we promote. - # Otherwise we exit cleanly — the next sibling's completion - # will trigger another finalize attempt. - # - # We don't use `--branch` because for tag pushes that filter - # is inconsistent across GitHub's REST surface in some - # corner cases; head_sha is unambiguous (all three sibling - # workflows run on exactly the same commit the tag points - # at). - run: | - set -euo pipefail - - workflows=( - "release-linux.yml" - "release-macos.yml" - "release-windows.yml" - ) - - all_done=1 - for wf in "${workflows[@]}"; do - # `gh api` paginates with --paginate; cap the page size - # to avoid scanning the whole history for an old tag. - # The triggering run is recent, so the matching siblings - # are also in the last few pages of runs for that file. - runs_json=$(gh api \ - "repos/${GH_REPO}/actions/workflows/${wf}/runs?head_sha=${HEAD_SHA}&event=push&per_page=20") - - total_count=$(jq -r '.total_count' <<<"$runs_json") - latest=$(jq -r --arg sha "$HEAD_SHA" ' - [.workflow_runs[] | select(.head_sha == $sha)] - | sort_by(.updated_at) | last // {} - | [.status // "missing", .conclusion // "", .id // ""] - | @tsv' <<<"$runs_json") - read -r latest_status latest_conclusion latest_id <<<"$latest" - - echo "${wf}: head_sha=${HEAD_SHA} total=${total_count} latest_run=${latest_id} status=${latest_status} conclusion=${latest_conclusion}" - - if [[ "$latest_status" != "completed" || "$latest_conclusion" != "success" ]]; then - all_done=0 - fi - done - - if [[ "$all_done" -eq 1 ]]; then - echo "ready=true" >>"$GITHUB_OUTPUT" - echo "All three platform workflows succeeded for $HEAD_SHA — ready to promote." - else - echo "ready=false" >>"$GITHUB_OUTPUT" - echo "Not all platforms have succeeded yet; waiting for the next sibling's completion." - fi - - - uses: actions/checkout@v5 - if: steps.gate.outputs.ready == 'true' - with: - ref: ${{ steps.ctx.outputs.sha }} + TAG: ${{ steps.ctx.outputs.tag }} + SHA: ${{ steps.ctx.outputs.sha }} + run: python3 scripts/release/publication.py wait "$TAG" "$SHA" - - name: Checkout gh-pages for release gate + - name: Checkout gh-pages staging if: steps.gate.outputs.ready == 'true' env: GH_TOKEN: ${{ github.token }} run: | set -euo pipefail git clone --single-branch --branch gh-pages \ - "https://x-access-token:${GH_TOKEN}@github.com/${{ github.repository }}.git" \ - gh-pages - - - name: Sync public installer scripts - if: steps.gate.outputs.ready == 'true' - run: | - set -euo pipefail - - cp scripts/install.sh gh-pages/install.sh - cp scripts/install.ps1 gh-pages/install.ps1 - - cd gh-pages - git config user.name "github-actions[bot]" - git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - git add install.sh install.ps1 - if git diff --cached --quiet; then - echo "Installer scripts are already current." - exit 0 - fi - - git commit -m "Sync installer scripts for ${{ steps.ctx.outputs.tag }}" - git pull --rebase origin gh-pages - git push origin gh-pages + "https://x-access-token:${GH_TOKEN}@github.com/${{ github.repository }}.git" gh-pages + git -C gh-pages config user.name "github-actions[bot]" + git -C gh-pages config user.email "41898282+github-actions[bot]@users.noreply.github.com" - - name: Verify release payload before promotion + - name: Verify payload, publish release, then notify updater clients if: steps.gate.outputs.ready == 'true' env: GH_TOKEN: ${{ github.token }} GH_REPO: ${{ github.repository }} + TAG: ${{ steps.ctx.outputs.tag }} + SHA: ${{ steps.ctx.outputs.sha }} + run: python3 scripts/release/publication.py finish "$TAG" "$SHA" + + update-homebrew: + name: Update Homebrew cask + runs-on: macos-15 + timeout-minutes: 10 + needs: finalize + if: needs.finalize.outputs.ready == 'true' && !contains(needs.finalize.outputs.tag, '-dev.') + env: + RELEASE_TAG: ${{ needs.finalize.outputs.tag }} + + steps: + - name: Derive release metadata + id: meta + shell: bash run: | set -euo pipefail - ./scripts/release/verify-release-gate.sh "${{ steps.ctx.outputs.tag }}" gh-pages + version="${RELEASE_TAG#v}" + channel="stable" + if [[ "$version" == *"-beta."* ]]; then + channel="beta" + elif [[ "$version" == *"-dev."* ]]; then + channel="dev" + fi + echo "version=$version" >>"$GITHUB_OUTPUT" + echo "channel=$channel" >>"$GITHUB_OUTPUT" - - name: Promote draft to public release - if: steps.gate.outputs.ready == 'true' + - name: Download release artifacts + if: steps.meta.outputs.channel != 'dev' env: GH_TOKEN: ${{ github.token }} GH_REPO: ${{ github.repository }} - TAG: ${{ steps.ctx.outputs.tag }} - # `gh release edit --draft=false` is idempotent: if a - # previous finalize run already promoted the release (e.g. - # because all three siblings finished within the same - # second), this call is a no-op. We still want to call it so - # any state drift (someone manually re-drafting via the UI - # mid-pipeline) gets corrected. - # - # We deliberately do NOT touch --prerelease here: the create - # step in each platform workflow set it correctly at draft - # time (true for *-dev.*, unset otherwise), and re-passing - # it would re-introduce the regression where beta tags - # appeared as Pre-release in the GitHub UI. + run: gh release download "$RELEASE_TAG" --pattern '*-macos-*.dmg' --dir release-artifacts + + - name: Update cask formula + if: steps.meta.outputs.channel != 'dev' + shell: bash + env: + GH_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }} run: | set -euo pipefail - if ! gh release view "$TAG" >/dev/null 2>&1; then - echo "::warning::release $TAG no longer exists — nothing to promote" + version="${{ steps.meta.outputs.version }}" + channel="${{ steps.meta.outputs.channel }}" + + if [[ -z "${GH_TOKEN:-}" ]]; then + echo "::warning::HOMEBREW_TAP_TOKEN not set — skipping cask update" exit 0 fi - is_draft=$(gh release view "$TAG" --json isDraft --jq '.isDraft') - if [[ "$is_draft" != "true" ]]; then - echo "$TAG is already published — nothing to do." + # Determine cask name + if [[ "$channel" == "beta" ]]; then + cask="con-beta" + app_name="con Beta" + else + cask="con" + app_name="con" + fi + + # Compute SHA256 for each arch DMG + arm64_dmg=$(find release-artifacts -name "*-macos-arm64.dmg" -type f | head -1) + x86_64_dmg=$(find release-artifacts -name "*-macos-x86_64.dmg" -type f | head -1) + + arm64_sha="" + x86_64_sha="" + [[ -n "$arm64_dmg" ]] && arm64_sha=$(shasum -a 256 "$arm64_dmg" | cut -d' ' -f1) + [[ -n "$x86_64_dmg" ]] && x86_64_sha=$(shasum -a 256 "$x86_64_dmg" | cut -d' ' -f1) + + if [[ -z "$arm64_sha" && -z "$x86_64_sha" ]]; then + echo "::warning::No DMGs found — skipping cask update" exit 0 fi - echo "Promoting $TAG from draft to public release." - gh release edit "$TAG" --draft=false + # Pre-compute values to avoid mixing Ruby/bash syntax in heredoc + dmg_prefix="${app_name// /-}" + if [[ "$channel" == "beta" ]]; then + bundle_suffix=".beta" + else + bundle_suffix="" + fi + + # Clone tap and update cask + git clone "https://x-access-token:${GH_TOKEN}@github.com/nowledge-co/homebrew-tap.git" tap + cd tap + + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + for attempt in 1 2 3 4 5; do + git fetch origin main + git checkout --detach origin/main + current=$(ruby -e 'puts File.read(ARGV[0])[/version "([^"]+)"/, 1]' "Casks/${cask}.rb" 2>/dev/null || true) + if [[ -n "$current" ]] && ruby -e 'exit(Gem::Version.new(ARGV[0]) >= Gem::Version.new(ARGV[1]) ? 0 : 1)' "$current" "$version"; then + echo "Homebrew already has $current; refusing to downgrade." + exit 0 + fi + + cat > "Casks/${cask}.rb" <>"$GITHUB_OUTPUT" - echo "::warning::SPARKLE_SIGNING_KEY not set — skipping appcast update" + echo "::error::SPARKLE_SIGNING_KEY not set — cannot prepare signed updater metadata" + exit 1 else echo "available=true" >>"$GITHUB_OUTPUT" fi @@ -279,7 +280,7 @@ jobs: git clone --single-branch --branch gh-pages \ "https://x-access-token:${{ github.token }}@github.com/${{ github.repository }}.git" \ gh-pages 2>/dev/null || { - mkdir -p gh-pages/appcast + mkdir -p "gh-pages/release-staging/$GITHUB_REF_NAME/appcast" cd gh-pages git init git checkout -b gh-pages @@ -313,12 +314,12 @@ jobs: channel="${{ steps.meta.outputs.channel }}" build_number="${{ github.run_number }}" - mkdir -p gh-pages/appcast + mkdir -p "gh-pages/release-staging/$GITHUB_REF_NAME/appcast" tarball=$(find release-artifacts -name "*-linux-x86_64.tar.gz" -type f | head -1) if [[ -z "$tarball" ]]; then - echo "::warning::No Linux tarball found — skipping" - exit 0 + echo "::error::No Linux tarball found" + exit 1 fi sig_output=$(./scripts/sparkle/sign-artifact.sh "$tarball") @@ -332,7 +333,7 @@ jobs: tarball_name=$(basename "$tarball") download_url="https://github.com/${repo}/releases/download/${tag}/${tarball_name}" - appcast_file="gh-pages/appcast/${channel}-linux-x86_64.xml" + appcast_file="gh-pages/release-staging/${tag}/appcast/${channel}-linux-x86_64.xml" # Re-use the same appcast generator macOS + Windows use. # Linux has no OS-minimum equivalent in the Sparkle schema @@ -357,7 +358,7 @@ jobs: echo "Updated appcast: ${channel}-linux-x86_64.xml (build $build_number)" - - name: Push appcast to gh-pages + - name: Stage signed appcasts without notifying clients if: steps.meta.outputs.channel != 'dev' && steps.sparkle.outputs.available == 'true' shell: bash run: | @@ -365,11 +366,7 @@ jobs: cd gh-pages git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - # Keep install.sh in sync from main repo. The macOS release - # job also copies it, but if a Linux-only tag fires (or the - # macOS job hasn't run yet) we still want the latest script. - cp "${{ github.workspace }}/scripts/install.sh" install.sh - git add appcast/ install.sh + git add "release-staging/$GITHUB_REF_NAME/appcast/" if git diff --cached --quiet; then echo "No appcast changes to commit" exit 0 diff --git a/.github/workflows/release-macos.yml b/.github/workflows/release-macos.yml index 4289d763..a7366dfa 100644 --- a/.github/workflows/release-macos.yml +++ b/.github/workflows/release-macos.yml @@ -261,7 +261,7 @@ jobs: -print0) update-appcast: - name: Update Sparkle appcast + name: Prepare signed updater metadata concurrency: # Keep macOS retries independent from the other platform jobs. The # push below rebases against the shared branch when another platform @@ -302,7 +302,8 @@ jobs: run: | if [[ -z "${SPARKLE_SIGNING_KEY:-}" ]]; then echo "available=false" >>"$GITHUB_OUTPUT" - echo "::warning::SPARKLE_SIGNING_KEY not set — skipping appcast update" + echo "::error::SPARKLE_SIGNING_KEY not set — cannot prepare signed updater metadata" + exit 1 else echo "available=true" >>"$GITHUB_OUTPUT" fi @@ -329,7 +330,7 @@ jobs: git clone --single-branch --branch gh-pages \ "https://x-access-token:${{ github.token }}@github.com/${{ github.repository }}.git" \ gh-pages 2>/dev/null || { - mkdir -p gh-pages/appcast + mkdir -p "gh-pages/release-staging/$GITHUB_REF_NAME/appcast" cd gh-pages git init git checkout -b gh-pages @@ -356,14 +357,14 @@ jobs: marketing="${{ steps.meta.outputs.marketing }}" build_number="${{ github.run_number }}" - mkdir -p gh-pages/appcast + mkdir -p "gh-pages/release-staging/$GITHUB_REF_NAME/appcast" for arch in arm64 x86_64; do # Find the DMG for this arch dmg=$(find release-artifacts -name "*-macos-${arch}.dmg" -type f | head -1) if [[ -z "$dmg" ]]; then - echo "::warning::No DMG found for $arch — skipping" - continue + echo "::error::No DMG found for $arch" + exit 1 fi # Sign the artifact and extract signature @@ -381,7 +382,7 @@ jobs: download_url="https://github.com/${repo}/releases/download/${tag}/${dmg_name}" # Update the appcast for this channel+arch - appcast_file="gh-pages/appcast/${channel}-macos-${arch}.xml" + appcast_file="gh-pages/release-staging/${tag}/appcast/${channel}-macos-${arch}.xml" APPCAST_FILE="$appcast_file" \ APPCAST_TITLE="con" \ @@ -398,7 +399,7 @@ jobs: echo "Updated appcast: ${channel}-macos-${arch}.xml (build $build_number)" done - - name: Push appcast to gh-pages + - name: Stage signed appcasts without notifying clients if: steps.meta.outputs.channel != 'dev' && steps.sparkle.outputs.available == 'true' shell: bash run: | @@ -406,9 +407,7 @@ jobs: cd gh-pages git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - # Keep install.sh in sync from main repo - cp "${{ github.workspace }}/scripts/install.sh" install.sh - git add appcast/ install.sh + git add "release-staging/$GITHUB_REF_NAME/appcast/" if git diff --cached --quiet; then echo "No appcast changes to commit" exit 0 @@ -426,131 +425,3 @@ jobs: fi sleep $((attempt * 2)) done - - update-homebrew: - name: Update Homebrew cask - runs-on: macos-15 - needs: publish - - steps: - - name: Derive release metadata - id: meta - shell: bash - run: | - set -euo pipefail - version="${GITHUB_REF_NAME#v}" - channel="stable" - if [[ "$version" == *"-beta."* ]]; then - channel="beta" - elif [[ "$version" == *"-dev."* ]]; then - channel="dev" - fi - echo "version=$version" >>"$GITHUB_OUTPUT" - echo "channel=$channel" >>"$GITHUB_OUTPUT" - - - name: Download release artifacts - if: steps.meta.outputs.channel != 'dev' - uses: actions/download-artifact@v5 - with: - pattern: macos-* - path: release-artifacts - - - name: Update cask formula - if: steps.meta.outputs.channel != 'dev' - shell: bash - env: - GH_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }} - run: | - set -euo pipefail - - version="${{ steps.meta.outputs.version }}" - channel="${{ steps.meta.outputs.channel }}" - - if [[ -z "${GH_TOKEN:-}" ]]; then - echo "::warning::HOMEBREW_TAP_TOKEN not set — skipping cask update" - exit 0 - fi - - # Determine cask name - if [[ "$channel" == "beta" ]]; then - cask="con-beta" - app_name="con Beta" - else - cask="con" - app_name="con" - fi - - # Compute SHA256 for each arch DMG - arm64_dmg=$(find release-artifacts -name "*-macos-arm64.dmg" -type f | head -1) - x86_64_dmg=$(find release-artifacts -name "*-macos-x86_64.dmg" -type f | head -1) - - arm64_sha="" - x86_64_sha="" - [[ -n "$arm64_dmg" ]] && arm64_sha=$(shasum -a 256 "$arm64_dmg" | cut -d' ' -f1) - [[ -n "$x86_64_dmg" ]] && x86_64_sha=$(shasum -a 256 "$x86_64_dmg" | cut -d' ' -f1) - - if [[ -z "$arm64_sha" && -z "$x86_64_sha" ]]; then - echo "::warning::No DMGs found — skipping cask update" - exit 0 - fi - - # Pre-compute values to avoid mixing Ruby/bash syntax in heredoc - dmg_prefix="${app_name// /-}" - if [[ "$channel" == "beta" ]]; then - bundle_suffix=".beta" - else - bundle_suffix="" - fi - - # Clone tap and update cask - git clone "https://x-access-token:${GH_TOKEN}@github.com/nowledge-co/homebrew-tap.git" tap - cd tap - - cat > "Casks/${cask}.rb" <>"$GITHUB_OUTPUT" - echo "channel=$channel" >>"$GITHUB_OUTPUT" - echo "marketing=$marketing" >>"$GITHUB_OUTPUT" + { + echo "version=$version" + echo "channel=$channel" + echo "marketing=$marketing" + } >>"$GITHUB_OUTPUT" - name: Check Sparkle signing key id: sparkle @@ -438,7 +440,8 @@ jobs: run: | if [[ -z "${SPARKLE_SIGNING_KEY:-}" ]]; then echo "available=false" >>"$GITHUB_OUTPUT" - echo "::warning::SPARKLE_SIGNING_KEY not set — skipping appcast update" + echo "::error::SPARKLE_SIGNING_KEY not set — cannot prepare signed updater metadata" + exit 1 else echo "available=true" >>"$GITHUB_OUTPUT" fi @@ -463,7 +466,7 @@ jobs: git clone --single-branch --branch gh-pages \ "https://x-access-token:${{ github.token }}@github.com/${{ github.repository }}.git" \ gh-pages 2>/dev/null || { - mkdir -p gh-pages/appcast + mkdir -p "gh-pages/release-staging/$GITHUB_REF_NAME/appcast" cd gh-pages git init git checkout -b gh-pages @@ -488,15 +491,14 @@ jobs: tag="$GITHUB_REF_NAME" version="${{ steps.meta.outputs.version }}" channel="${{ steps.meta.outputs.channel }}" - marketing="${{ steps.meta.outputs.marketing }}" build_number="${{ github.run_number }}" - mkdir -p gh-pages/appcast + mkdir -p "gh-pages/release-staging/$GITHUB_REF_NAME/appcast" zip=$(find release-artifacts -name "*-windows-x86_64.zip" -type f | head -1) if [[ -z "$zip" ]]; then - echo "::warning::No Windows ZIP found — skipping" - exit 0 + echo "::error::No Windows ZIP found" + exit 1 fi sig_output=$(./scripts/sparkle/sign-artifact.sh "$zip") @@ -510,7 +512,7 @@ jobs: zip_name=$(basename "$zip") download_url="https://github.com/${repo}/releases/download/${tag}/${zip_name}" - appcast_file="gh-pages/appcast/${channel}-windows-x86_64.xml" + appcast_file="gh-pages/release-staging/${tag}/appcast/${channel}-windows-x86_64.xml" # Re-use the same appcast generator the macOS pipeline uses. # Windows has no OS minimum so we feed a harmless sentinel; @@ -537,7 +539,7 @@ jobs: echo "Updated appcast: ${channel}-windows-x86_64.xml (build $build_number)" - - name: Push appcast to gh-pages + - name: Stage signed appcasts without notifying clients if: steps.meta.outputs.channel != 'dev' && steps.sparkle.outputs.available == 'true' shell: bash run: | @@ -545,9 +547,7 @@ jobs: cd gh-pages git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - # Keep install.ps1 in sync from main repo - cp "${{ github.workspace }}/scripts/install.ps1" install.ps1 - git add appcast/ install.ps1 + git add "release-staging/$GITHUB_REF_NAME/appcast/" if git diff --cached --quiet; then echo "No appcast changes to commit" exit 0 diff --git a/CHANGELOG.md b/CHANGELOG.md index 75736962..fdff9ef8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,18 @@ All notable changes to con are documented here. con is still pre-release, so entries may group related beta work while the product shape is stabilizing. +## `v0.1.0-beta.149` - 2026-10-23 + +### Fixed + +**Updates** + +- Update notifications and Homebrew updates now wait until the complete release + is public and its downloads are available, preventing download errors caused + by links to an unpublished release. Publication retries preserve newer updates + and recover without rebuilding the app. + _(PR [#508](https://github.com/nowledge-co/con-terminal/pull/508) by [@wey-gu](https://github.com/wey-gu))_ + ## `v0.1.0-beta.148` - 2026-10-22 ### Changed diff --git a/docs/impl/build-system.md b/docs/impl/build-system.md index aac97446..2296479b 100644 --- a/docs/impl/build-system.md +++ b/docs/impl/build-system.md @@ -16,6 +16,46 @@ Update the `source-sha256` comment in `packaging/flatpak/aetherpak.yaml`, then r AppStream composition and the bundle smoke test; the local size check does not replace those checks. +## Updater Publication + +Platform workflows upload release assets to a draft and prepare signed feeds at +`release-staging//appcast/` on this repository's `gh-pages` branch. These +staging paths are public metadata, not updater endpoints; clients continue to +read the existing `appcast/` feeds. A missing signing key or artifact fails the +platform workflow instead of silently preparing an incomplete release. + +The finalizer reconciles the latest push run for each exact tag and commit. +SHA-filtered Actions results can lag; it also lists recent runs and filters +locally. Missing results and API errors receive bounded retries, then fail +visibly. An observed running platform defers to that platform's completion +event. A failed platform never passes the gate. + +After validating all assets, checksum manifests and staged feeds, the finalizer +publishes the release. It checks the exact enclosure URLs anonymously, including +their lengths, before merging the staged entries into the canonical feeds. +Draft assets therefore never appear in the updater's current feed. Retry merges +preserve newer entries and unrelated Flatpak/Pages content. A failure after +promotion is recoverable: a public release still runs the feed validation and +publication steps. Homebrew updates run only after these steps succeed. + +For releases made with this staged workflow, recover without rebuilding or +creating another tag: + +```sh +gh workflow run release-finalize.yml --ref main -f tag=v0.1.0-beta.N +``` + +Older tags lack staged feeds; rerun their original finalizer only after checking +their payload and canonical feeds. Never manufacture staging data from an +unverified draft. Local tests use isolated fixtures and a local bare Git remote: + +```sh +python3 scripts/release/test-publication.py +actionlint .github/workflows/release-*.yml +``` + +See [the beta.148 incident](../../postmortem/2026-10-23-updater-draft-download.md). + ## macOS Release Handoff Dependency setup reuses the runner's installed CMake and logs its version. @@ -43,7 +83,8 @@ its separate PowerShell installer and existing request timeout. ### Homebrew Casks -The macOS release workflow generates both casks from its inline template. +The release finalizer generates both casks from its inline template, after the +release and its updater downloads are publicly available. Use `depends_on :macos` for the platform requirement: old macOS release symbols can disappear from Homebrew even when Ruby syntax still parses correctly. This does not change the app binary's deployment target. diff --git a/postmortem/2026-10-23-updater-draft-download.md b/postmortem/2026-10-23-updater-draft-download.md new file mode 100644 index 00000000..a7a6aa28 --- /dev/null +++ b/postmortem/2026-10-23-updater-draft-download.md @@ -0,0 +1,62 @@ +# Updater advertised a draft release + +## What Happened + +On October 23, a macOS beta.148 update failed with Sparkle's download error. +Local logs at 08:39 Asia/Shanghai recorded HTTP 404 for the ARM DMG. The public +appcast advertised beta.148, but GitHub still marked the release as a draft. +Authenticated maintainers could see the assets; updater clients could not. + +All platform workflows had succeeded. Finalizer run 39817569024 nevertheless +logged zero results for the Linux and macOS SHA-filtered workflow queries and +returned success without promoting the draft. The same queries later returned +the completed runs. This establishes a transient missing-result condition; it +does not establish a specific GitHub internal indexing fault. + +## Root Cause + +Platform jobs published canonical feeds before the release became public. +The finalizer treated missing API results like a still-running sibling and +exited successfully, assuming another completion event would arrive. The last +completion event could therefore leave both a private draft and a public update +notification indefinitely. Homebrew had the same early-publication ordering. + +## Recovery + +Rerunning only the finalizer passed the existing gate and published beta.148 at +2026-10-23T00:41:33Z. An anonymous cache-busted range request returned HTTP 206; +the original URL still briefly returned its cached 404. No tag was changed and +no binaries were rebuilt. The cache behavior reinforces why clients must not +be directed to a draft URL, even temporarily. + +## Fix + +- Platform jobs prepare tag-scoped signed metadata without changing live feeds. +- The finalizer retries missing/error responses and uses an independently + listed, locally filtered set of runs. Both tag and commit must match; a + persistent missing result is a visible failure. +- Payload validation precedes promotion. Anonymous checks of the exact URLs + precede canonical feed publication. Homebrew follows successful finalization. +- Public-but-unannounced releases can resume finalization. Feed merges retain + newer builds and retry against fresh Pages state without overwriting Flatpak. +- A manual reconciliation trigger repairs an existing staged release without + rebuilding or retagging. + +## Verification And Limits + +Offline regressions cover missing results, API errors, wrong tag/commit, failed +and running siblings, exact URL/size checks, cached download errors, absent +staged platforms, immutable feed entries, public-release retries and dev-channel +isolation. Local bare-remote tests cover publication order, idempotence and a +real rejected push followed by a concurrent Flatpak-preserving retry. + +Workflow lint and the actual Homebrew cask-template loader cover the changed +wiring. These tests do not emulate GitHub's production indexing or CDN. The next +release must confirm public asset availability before its updater feeds move. + +## Lessons + +An update feed is a promise that its artifact can already be downloaded without +maintainer credentials. Preparing metadata and notifying users are different +operations. A green workflow that intentionally deferred is not a publication +receipt; missing external state needs bounded reconciliation and a recovery path. diff --git a/scripts/macos/test-homebrew-cask.rb b/scripts/macos/test-homebrew-cask.rb index a122f215..0fbc1194 100644 --- a/scripts/macos/test-homebrew-cask.rb +++ b/scripts/macos/test-homebrew-cask.rb @@ -6,7 +6,7 @@ require "cask/cask_loader" require "simulate_system" -workflow_path = File.expand_path("../../.github/workflows/release-macos.yml", __dir__) +workflow_path = File.expand_path("../../.github/workflows/release-finalize.yml", __dir__) workflow = YAML.load_file(workflow_path) steps = workflow.fetch("jobs").values.flat_map { |job| job.fetch("steps", []) } step = steps.find { |entry| entry["name"] == "Update cask formula" } diff --git a/scripts/release/publication.py b/scripts/release/publication.py new file mode 100644 index 00000000..533e50e3 --- /dev/null +++ b/scripts/release/publication.py @@ -0,0 +1,251 @@ +#!/usr/bin/env python3 +"""Reconcile release runs and publish updater feeds only after anonymous delivery.""" + +import argparse +import copy +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile +import time +import urllib.request +import xml.etree.ElementTree as ET + + +SPARKLE = "http://www.andymatuschak.org/xml-namespaces/sparkle" +ET.register_namespace("sparkle", SPARKLE) +WORKFLOWS = ("release-linux.yml", "release-macos.yml", "release-windows.yml") +PENDING = {"queued", "in_progress", "waiting", "pending", "requested"} +TAG = re.compile(r"v\d+\.\d+\.\d+(?:-(?:beta|dev)\.\d+)?\Z") +ROOT = Path(__file__).resolve().parents[2] + + +def run(*args, cwd=None): + return subprocess.check_output(args, cwd=cwd, text=True).strip() + + +def gh_json(*args): + return json.loads(run("gh", *args)) + + +def channel_for(tag): + if not TAG.fullmatch(tag): + raise ValueError(f"Invalid release tag: {tag}") + return "dev" if "-dev." in tag else "beta" if "-beta." in tag else "stable" + + +def latest_run(runs, tag, sha): + matching = [r for r in runs if r.get("head_sha") == sha + and r.get("head_branch") == tag and r.get("event") == "push"] + # updated_at is not creation order: rerunning an old run must not hide a + # newer run. A rerun retains its ID and reports its current run_attempt. + return max(matching, key=lambda r: r["id"], default=None) + + +def workflow_run(repo, workflow, tag, sha): + endpoint = f"repos/{repo}/actions/workflows/{workflow}/runs" + result = gh_json("api", f"{endpoint}?head_sha={sha}&event=push&per_page=100") + found = latest_run(result["workflow_runs"], tag, sha) + if found is None: + # The SHA-filtered Actions index can transiently omit completed runs. + # Independently list recent runs, then apply BOTH identities locally. + recent = gh_json("api", f"{endpoint}?event=push&per_page=100") + found = latest_run(recent["workflow_runs"], tag, sha) + return found + + +def wait_for_platforms(repo, tag, sha, attempts=6, delay=15): + for attempt in range(attempts): + states = [] + for workflow in WORKFLOWS: + try: + item = workflow_run(repo, workflow, tag, sha) + if item is None: + state = "missing" + elif item["status"] != "completed": + state = item["status"] + else: + state = item["conclusion"] or "invalid-completion" + print(f"{workflow}: {state} (tag={tag}, sha={sha})", flush=True) + states.append(state) + except (subprocess.CalledProcessError, ValueError, KeyError) as error: + print(f"{workflow}: query failed: {error}", file=sys.stderr) + states.append("query-error") + if all(state == "success" for state in states): + return True + if any(state not in PENDING | {"success", "missing", "query-error"} for state in states): + raise RuntimeError("A required platform did not succeed; release is blocked") + if attempt + 1 < attempts: + time.sleep(delay) + if any(state in {"missing", "query-error"} for state in states): + raise RuntimeError("Actions results remained unavailable after retries; rerun finalizer") + # An observed running sibling will emit its own completion event. Unlike a + # missing result, this is a legitimate reason to defer without publishing. + return False + + +def feed_names(channel): + return [f"{channel}-{platform}.xml" for platform in + ("macos-arm64", "macos-x86_64", "linux-x86_64", "windows-x86_64")] + + +def staged_feeds(pages, repo, tag, release): + channel = channel_for(tag) + if channel == "dev": + return {} + assets = {asset["name"]: asset for asset in release["assets"]} + feeds = {} + for name in feed_names(channel): + tree = ET.parse(pages / "release-staging" / tag / "appcast" / name) + items = tree.findall("./channel/item") + if len(items) != 1: + raise ValueError(f"Staged feed must contain exactly one item: {name}") + item = items[0] + enc = item.find("enclosure") + platform = name.removeprefix(f"{channel}-").removesuffix(".xml") + version = tag.removeprefix("v") + prefix = "con-Beta" if channel == "beta" and platform.startswith("macos") else "con" + suffix = "dmg" if platform.startswith("macos") else ( + "zip" if platform.startswith("windows") else "tar.gz") + asset_name = f"{prefix}-{version}-{platform}.{suffix}" + asset = assets[asset_name] + url = f"https://github.com/{repo}/releases/download/{tag}/{asset_name}" + if enc is None or enc.get("url") != url: + raise ValueError(f"Unexpected staged enclosure URL: {name}") + if int(enc.get("length", "0")) != asset["size"] or asset["size"] <= 0: + raise ValueError(f"Staged size differs from release asset: {name}") + if not enc.get(f"{{{SPARKLE}}}edSignature"): + raise ValueError(f"Missing signature: {name}") + build_number(item) + feeds[name] = tree + return feeds + + +def build_number(item): + value = int(item.findtext(f"{{{SPARKLE}}}version", "0")) + if value <= 0: + raise ValueError("Appcast build number must be positive") + return value + + +def merge_feed(existing, incoming): + result = copy.deepcopy(existing if existing is not None else incoming) + channel = result.find("channel") + if channel is None: + raise ValueError("Appcast is missing its channel") + new_item = incoming.find("./channel/item") + number = build_number(new_item) + items = channel.findall("item") + newest = max((build_number(item) for item in items), default=0) + for item in items: + if build_number(item) == number: + # Immutable tags must not silently replace an already shipped item. + if item.find("enclosure").attrib != new_item.find("enclosure").attrib: + raise ValueError("Conflicting enclosure for an existing build number") + channel.remove(item) + by_number = {build_number(item): item for item in items} + by_number[number] = copy.deepcopy(new_item) + for key in sorted(by_number, reverse=True)[:20]: + channel.append(by_number[key]) + return result, number >= newest + + +def probe_downloads(feeds, attempts=6, delay=10): + for tree in feeds.values(): + enc = tree.find("./channel/item/enclosure") + url = enc.get("url") + for attempt in range(attempts): + try: + # No token or cache-busting query: verify the EXACT URL clients + # will use, including any cached draft-era 404 response. + request = urllib.request.Request(url, method="HEAD") + with urllib.request.urlopen(request, timeout=30) as response: + if response.status != 200: + raise ValueError(f"Unexpected HTTP status: {response.status}") + if int(response.headers.get("Content-Length", "0")) != int(enc.get("length")): + raise ValueError("Anonymous download size differs from signed feed") + break + except (OSError, ValueError) as error: + if attempt + 1 == attempts: + raise RuntimeError(f"Anonymous download unavailable: {url}") from error + time.sleep(delay) + + +def finish(repo, tag, sha, pages): + release = gh_json("release", "view", tag, "--repo", repo, "--json", "isDraft,assets") + feeds = staged_feeds(pages, repo, tag, release) + installers = installers_at(sha) + # Validate the candidate installer bytes, not an older Pages deployment. + # Canonical files stay untouched until public download probes succeed. + with tempfile.TemporaryDirectory(prefix="con-release-gate-") as candidate: + candidate = Path(candidate) + for name, content in installers.items(): + (candidate / name).write_text(content) + subprocess.run(["bash", str(ROOT / "scripts/release/verify-release-gate.sh"), + tag, str(candidate), str(pages / "release-staging" / tag / "appcast")], + check=True, env={**os.environ, "GH_REPO": repo}) + if release["isDraft"]: + run("gh", "release", "edit", tag, "--repo", repo, "--draft=false") + # A public release alone does not prove anonymous CDN availability. + probe_downloads(feeds) + if not feeds: # Dev releases never touch stable/beta updater endpoints. + return + for attempt in range(5): + run("git", "fetch", "origin", "gh-pages", cwd=pages) + # This dedicated CI clone is clean after each attempted commit. Start + # again from the latest remote tree so Flatpak and newer feeds survive. + run("git", "checkout", "--detach", "origin/gh-pages", cwd=pages) + current_release = gh_json("release", "view", tag, "--repo", repo, "--json", "isDraft") + if current_release["isDraft"]: + raise RuntimeError("Release became private; refusing updater publication") + current = True + for name, incoming in feeds.items(): + path = pages / "appcast" / name + merged, is_current = merge_feed(ET.parse(path) if path.exists() else None, incoming) + current &= is_current + path.parent.mkdir(parents=True, exist_ok=True) + ET.indent(merged, space=" ") + merged.write(path, encoding="utf-8", xml_declaration=True) + if current: + for name, content in installers.items(): + (pages / name).write_text(content) + run("git", "add", "appcast", "install.sh", "install.ps1", cwd=pages) + if subprocess.run(["git", "diff", "--cached", "--quiet"], cwd=pages).returncode == 0: + return + run("git", "commit", "-m", f"Publish verified updater feeds for {tag}", cwd=pages) + try: + run("git", "push", "origin", "HEAD:gh-pages", cwd=pages) + return + except subprocess.CalledProcessError: + if attempt == 4: + raise + time.sleep(2 * (attempt + 1)) + + +def installers_at(sha): + return {name: run("git", "show", f"{sha}:scripts/{name}", cwd=ROOT) + "\n" + for name in ("install.sh", "install.ps1")} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("command", choices=("wait", "finish")) + parser.add_argument("tag") + parser.add_argument("sha") + parser.add_argument("--pages", type=Path, default=Path("gh-pages")) + args = parser.parse_args() + channel_for(args.tag) + repo = os.environ["GH_REPO"] + if args.command == "wait": + ready = wait_for_platforms(repo, args.tag, args.sha) + with open(os.environ["GITHUB_OUTPUT"], "a") as output: + output.write(f"ready={str(ready).lower()}\n") + else: + finish(repo, args.tag, args.sha, args.pages.resolve()) + + +if __name__ == "__main__": + main() diff --git a/scripts/release/test-publication.py b/scripts/release/test-publication.py new file mode 100644 index 00000000..2f98af53 --- /dev/null +++ b/scripts/release/test-publication.py @@ -0,0 +1,358 @@ +#!/usr/bin/env python3 +"""Offline regression tests for publication ordering and Actions reconciliation.""" + +import copy +import importlib.util +import json +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest +from unittest.mock import Mock, patch +import xml.etree.ElementTree as ET + + +ROOT = Path(__file__).resolve().parents[2] +spec = importlib.util.spec_from_file_location("publication", ROOT / "scripts/release/publication.py") +p = importlib.util.module_from_spec(spec) +spec.loader.exec_module(p) +TAG = "v0.1.0-beta.149" +SHA = "a" * 40 +REPO = "nowledge-co/con-terminal" + + +def workflow(number=1, **kwargs): + return {"id": number, "head_sha": SHA, "head_branch": TAG, "event": "push", + "status": "completed", "conclusion": "success", **kwargs} + + +def feed(number=160, url="https://example.test/release.dmg"): + root = ET.Element("rss", version="2.0") + channel = ET.SubElement(root, "channel") + ET.SubElement(channel, "title").text = "con" + item = ET.SubElement(channel, "item") + ET.SubElement(item, f"{{{p.SPARKLE}}}version").text = str(number) + ET.SubElement(item, "enclosure", {"url": url, "length": "42", + f"{{{p.SPARKLE}}}edSignature": "signed"}) + return ET.ElementTree(root) + + +class WorkflowTests(unittest.TestCase): + def test_matches_tag_sha_event_not_updated_order(self): + runs = [workflow(1, updated_at="future"), workflow(2, status="in_progress"), + workflow(3, head_branch="v0.1.0-dev.149"), workflow(4, head_sha="b" * 40), + workflow(5, event="workflow_dispatch")] + self.assertEqual(p.latest_run(runs, TAG, SHA)["id"], 2) + + def test_empty_sha_index_falls_back_and_filters_locally(self): + with patch.object(p, "gh_json", side_effect=[{"workflow_runs": []}, + {"workflow_runs": [workflow(7), workflow(8, head_sha="wrong")]}]) as gh: + self.assertEqual(p.workflow_run(REPO, p.WORKFLOWS[0], TAG, SHA)["id"], 7) + self.assertNotIn("head_sha=", gh.call_args_list[1].args[1]) + + def test_transient_missing_result_retries(self): + with patch.object(p, "workflow_run", side_effect=[None, workflow(), workflow(), + workflow(), workflow(), workflow()]), patch.object(p.time, "sleep"): + self.assertTrue(p.wait_for_platforms(REPO, TAG, SHA, attempts=2)) + + def test_api_error_retries(self): + with patch.object(p, "workflow_run", side_effect=[ValueError("bad response"), + workflow(), workflow(), workflow(), workflow(), workflow()]), \ + patch.object(p.time, "sleep"): + self.assertTrue(p.wait_for_platforms(REPO, TAG, SHA, attempts=2)) + + def test_missing_results_never_silently_succeed(self): + with patch.object(p, "workflow_run", return_value=None), patch.object(p.time, "sleep"): + with self.assertRaisesRegex(RuntimeError, "unavailable"): + p.wait_for_platforms(REPO, TAG, SHA, attempts=2) + + def test_observed_pending_sibling_defers(self): + with patch.object(p, "workflow_run", return_value=workflow(status="in_progress")): + self.assertFalse(p.wait_for_platforms(REPO, TAG, SHA, attempts=1)) + + def test_failed_platform_blocks(self): + with patch.object(p, "workflow_run", return_value=workflow(conclusion="failure")): + with self.assertRaisesRegex(RuntimeError, "blocked"): + p.wait_for_platforms(REPO, TAG, SHA) + + def test_non_success_terminal_states_never_silently_defer(self): + for conclusion in ("neutral", "skipped", None, "unknown-status"): + with self.subTest(conclusion=conclusion), \ + patch.object(p, "workflow_run", return_value=workflow(conclusion=conclusion)): + with self.assertRaisesRegex(RuntimeError, "blocked"): + p.wait_for_platforms(REPO, TAG, SHA) + + +class FeedTests(unittest.TestCase): + def test_older_retry_cannot_move_latest_backwards(self): + tree, current = p.merge_feed(feed(161), feed(160)) + self.assertFalse(current) + self.assertEqual([p.build_number(i) for i in tree.findall("./channel/item")], [161, 160]) + + def test_duplicate_is_idempotent_with_different_xml_indentation(self): + old = feed() + ET.indent(old) + merged, current = p.merge_feed(old, feed()) + self.assertTrue(current) + self.assertEqual(len(merged.findall("./channel/item")), 1) + + def test_conflicting_immutable_build_is_rejected(self): + with self.assertRaisesRegex(ValueError, "Conflicting"): + p.merge_feed(feed(), feed(url="https://other.test/package")) + + def test_union_keeps_newest_twenty(self): + tree = feed(1) + for number in range(2, 23): + tree, _ = p.merge_feed(tree, feed(number)) + self.assertEqual([p.build_number(i) for i in tree.findall("./channel/item")], + list(range(22, 2, -1))) + + def test_anonymous_probe_uses_exact_url_without_token(self): + response = Mock(status=200, headers={"Content-Length": "42"}) + response.__enter__ = Mock(return_value=response) + response.__exit__ = Mock(return_value=False) + with patch.object(p.urllib.request, "urlopen", return_value=response) as open_url: + p.probe_downloads({"feed": feed()}) + request = open_url.call_args.args[0] + self.assertEqual(request.full_url, "https://example.test/release.dmg") + self.assertEqual(request.get_method(), "HEAD") + self.assertFalse(request.has_header("Authorization")) + + def test_cached_404_blocks_feeds(self): + with patch.object(p.urllib.request, "urlopen", side_effect=OSError("404")), \ + patch.object(p.time, "sleep"): + with self.assertRaisesRegex(RuntimeError, "unavailable"): + p.probe_downloads({"feed": feed()}, attempts=2) + + def test_invalid_tag_rejected(self): + for tag in ("../main", "main", "v1.2.3-beta.1/../../other"): + with self.assertRaises(ValueError): + p.channel_for(tag) + + +class PublicationTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.pages = Path(self.temp.name) + self.stage = self.pages / "release-staging" / TAG / "appcast" + self.stage.mkdir(parents=True) + self.release = {"isDraft": True, "assets": []} + installer_patch = patch.object(p, "installers_at", return_value={ + name: (ROOT / "scripts" / name).read_text() for name in ("install.sh", "install.ps1")}) + installer_patch.start() + self.addCleanup(installer_patch.stop) + for name in p.feed_names("beta"): + platform = name.removeprefix("beta-").removesuffix(".xml") + prefix = "con-Beta" if platform.startswith("macos") else "con" + suffix = "dmg" if platform.startswith("macos") else ( + "zip" if platform.startswith("windows") else "tar.gz") + asset = f"{prefix}-{TAG[1:]}-{platform}.{suffix}" + tree = feed(url=f"https://github.com/{REPO}/releases/download/{TAG}/{asset}") + tree.write(self.stage / name) + self.release["assets"].append({"name": asset, "size": 42}) + + def test_all_four_feeds_are_prepared(self): + self.assertEqual(len(p.staged_feeds(self.pages, REPO, TAG, self.release)), 4) + + def test_size_or_wrong_repository_is_rejected(self): + bad = copy.deepcopy(self.release) + bad["assets"][0]["size"] = 43 + with self.assertRaisesRegex(ValueError, "size"): + p.staged_feeds(self.pages, REPO, TAG, bad) + with self.assertRaisesRegex(ValueError, "URL"): + p.staged_feeds(self.pages, "other/repo", TAG, self.release) + + def test_missing_platform_blocks_before_promotion(self): + (self.stage / "beta-macos-arm64.xml").unlink() + with patch.object(p, "gh_json", return_value=self.release), patch.object(p, "run") as run: + with self.assertRaises(FileNotFoundError): + p.finish(REPO, TAG, SHA, self.pages) + run.assert_not_called() + + def test_multiple_items_cannot_smuggle_an_unpublished_release(self): + path = self.stage / "beta-macos-arm64.xml" + tree = ET.parse(path) + tree.find("channel").append(copy.deepcopy(tree.find("./channel/item"))) + tree.write(path) + with self.assertRaisesRegex(ValueError, "exactly one"): + p.staged_feeds(self.pages, REPO, TAG, self.release) + + def test_gate_failure_never_promotes(self): + with patch.object(p, "gh_json", return_value=self.release), \ + patch.object(p.subprocess, "run", side_effect=subprocess.CalledProcessError(1, "gate")), \ + patch.object(p, "run") as run: + with self.assertRaises(subprocess.CalledProcessError): + p.finish(REPO, TAG, SHA, self.pages) + run.assert_not_called() + + def test_download_failure_happens_after_promotion_but_before_any_git_write(self): + calls = [] + with patch.object(p, "gh_json", return_value=self.release), \ + patch.object(p.subprocess, "run"), \ + patch.object(p, "run", side_effect=lambda *a, **k: calls.append(a)), \ + patch.object(p, "probe_downloads", side_effect=RuntimeError("404")): + with self.assertRaisesRegex(RuntimeError, "404"): + p.finish(REPO, TAG, SHA, self.pages) + self.assertEqual(calls, [("gh", "release", "edit", TAG, "--repo", REPO, "--draft=false")]) + + def test_dev_never_changes_updater_feeds(self): + with patch.object(p, "gh_json", return_value=self.release), \ + patch.object(p.subprocess, "run"), patch.object(p, "run") as run: + p.finish(REPO, "v0.1.0-dev.149", SHA, self.pages) + self.assertEqual(run.call_count, 1) + self.assertEqual(run.call_args.args[:3], ("gh", "release", "edit")) + + def git_fixture(self): + remote = self.pages.parent / f"{self.pages.name}-remote.git" + self.addCleanup(lambda: shutil.rmtree(remote, ignore_errors=True)) + p.run("git", "init", "--bare", str(remote)) + p.run("git", "init", "-b", "gh-pages", cwd=self.pages) + p.run("git", "config", "user.name", "Fixture", cwd=self.pages) + p.run("git", "config", "user.email", "fixture@example.test", cwd=self.pages) + p.run("git", "remote", "add", "origin", str(remote), cwd=self.pages) + (self.pages / "appcast").mkdir() + for name in p.feed_names("beta"): + feed(159).write(self.pages / "appcast" / name) + for name in ("install.sh", "install.ps1"): + (self.pages / name).write_text((ROOT / "scripts" / name).read_text()) + (self.pages / "flatpak").mkdir() + (self.pages / "flatpak" / "keep").write_text("unrelated deployment") + p.run("git", "add", ".", cwd=self.pages) + p.run("git", "commit", "-m", "Fixture", cwd=self.pages) + p.run("git", "push", "origin", "HEAD:gh-pages", cwd=self.pages) + return remote + + def finish_with_real_git(self, *, conflict=False): + remote = self.git_fixture() + original_run = p.run + original_subprocess = subprocess.run + effects = [] + inserted = False + + def execute(*args, **kwargs): + nonlocal inserted + if args[0] == "gh": + effects.append("promote") + self.release["isDraft"] = False + return "" + if args[:2] == ("git", "push"): + effects.append("push") + if conflict and not inserted: + inserted = True + with tempfile.TemporaryDirectory() as other: + original_run("git", "clone", "--branch", "gh-pages", str(remote), other) + original_run("git", "config", "user.name", "Other", cwd=other) + original_run("git", "config", "user.email", "other@example.test", cwd=other) + (Path(other) / "flatpak" / "keep").write_text("concurrent deployment") + original_run("git", "add", ".", cwd=other) + original_run("git", "commit", "-m", "Concurrent Flatpak update", cwd=other) + original_run("git", "push", "origin", "HEAD:gh-pages", cwd=other) + return original_run(*args, **kwargs) + + def gate(args, **kwargs): + if args[0] == "bash": + effects.append("gate") + return subprocess.CompletedProcess(args, 0) + return original_subprocess(args, **kwargs) + + with patch.object(p, "run", side_effect=execute), \ + patch.object(p, "gh_json", side_effect=lambda *a: copy.deepcopy(self.release)), \ + patch.object(p.subprocess, "run", side_effect=gate), \ + patch.object(p, "probe_downloads", side_effect=lambda *a: effects.append("probe")), \ + patch.object(p.time, "sleep"): + p.finish(REPO, TAG, p.run("git", "rev-parse", "HEAD", cwd=ROOT), self.pages) + p.finish(REPO, TAG, p.run("git", "rev-parse", "HEAD", cwd=ROOT), self.pages) + self.assertEqual(effects[:3], ["gate", "promote", "probe"]) + self.assertEqual(effects.count("promote"), 1) + self.assertGreater(effects.index("push"), effects.index("probe")) + for name in p.feed_names("beta"): + items = ET.parse(self.pages / "appcast" / name).findall("./channel/item") + self.assertEqual([p.build_number(item) for item in items], [160, 159]) + expected = "concurrent deployment" if conflict else "unrelated deployment" + self.assertEqual((self.pages / "flatpak" / "keep").read_text(), expected) + + def test_real_git_publication_and_public_retry_are_idempotent(self): + self.finish_with_real_git() + + def test_real_git_push_race_preserves_concurrent_flatpak_changes(self): + self.finish_with_real_git(conflict=True) + + def gate_result(self, *, draft, broken_checksum=False): + release = copy.deepcopy(self.release) + release["isDraft"] = draft + manifests = { + "SHA256SUMS-macos-arm64.txt": [f"con-Beta-{TAG[1:]}-macos-arm64.dmg"], + "SHA256SUMS-macos-x86_64.txt": [f"con-Beta-{TAG[1:]}-macos-x86_64.dmg"], + "SHA256SUMS-linux.txt": [f"con-{TAG[1:]}-linux-x86_64.tar.gz"], + "SHA256SUMS-windows.txt": [f"con-{TAG[1:]}-windows-x86_64.zip"], + } + for arch in ("arm64", "x86_64"): + release["assets"].append({"name": f"con-Beta-{TAG[1:]}-macos-{arch}.zip", "size": 42}) + for name in manifests: + release["assets"].append({"name": name, "size": 42}) + for name in p.feed_names("beta"): + path = self.stage / name + tree = ET.parse(path) + item = tree.find("./channel/item") + ET.SubElement(item, f"{{{p.SPARKLE}}}shortVersionString").text = ( + "0.1.0" if "macos" in name else TAG[1:]) + tree.write(path) + for name in ("install.sh", "install.ps1"): + (self.pages / name).write_text((ROOT / "scripts" / name).read_text()) + if broken_checksum: + manifests["SHA256SUMS-linux.txt"] = ["wrong-artifact"] + binary = self.pages / "bin" + binary.mkdir() + gh = binary / "gh" + gh.write_text( + "#!/usr/bin/env python3\nimport json,sys\nfrom pathlib import Path\n" + f"release = {release!r}\nmanifests = {manifests!r}\n" + "if sys.argv[1:3] == ['release','view']:\n print(json.dumps(release))\n" + "elif sys.argv[1:3] == ['release','download']:\n" + " dest = Path(sys.argv[sys.argv.index('--dir')+1])\n" + " for name, assets in manifests.items():\n" + " (dest / name).write_text('\\n'.join('a'*64+' '+asset for asset in assets))\n" + "else:\n raise SystemExit('Unexpected gh invocation')\n") + gh.chmod(0o755) + return subprocess.run( + ["bash", str(ROOT / "scripts/release/verify-release-gate.sh"), + TAG, str(self.pages), str(self.stage)], text=True, capture_output=True, + env={**os.environ, "PATH": f"{binary}{os.pathsep}{os.environ['PATH']}", "GH_REPO": REPO}) + + def test_actual_gate_checks_staged_payload_for_public_resume(self): + result = self.gate_result(draft=False) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_actual_gate_checks_staged_payload_before_promotion(self): + result = self.gate_result(draft=True) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_actual_gate_rejects_wrong_checksum_manifest(self): + result = self.gate_result(draft=True, broken_checksum=True) + self.assertNotEqual(result.returncode, 0) + self.assertIn("does not reference the Linux tarball", result.stdout + result.stderr) + + +class WorkflowWiringTests(unittest.TestCase): + def test_platforms_stage_metadata_instead_of_publishing_live_feeds(self): + for platform in ("macos", "windows", "linux"): + source = (ROOT / ".github/workflows" / f"release-{platform}.yml").read_text() + self.assertIn('git add "release-staging/$GITHUB_REF_NAME/appcast/"', source) + self.assertNotIn('git add appcast/', source) + self.assertNotIn('appcast_file="gh-pages/appcast/', source) + self.assertNotIn("homebrew-tap.git", source) + + def test_recovery_and_homebrew_are_wired_after_finalization(self): + source = (ROOT / ".github/workflows/release-finalize.yml").read_text() + self.assertIn("workflow_dispatch:", source) + self.assertIn("needs: finalize", source) + self.assertIn('publication.py finish "$TAG" "$SHA"', source) + ci = (ROOT / ".github/workflows/ci-portable.yml").read_text() + self.assertIn("python3 scripts/release/test-publication.py", ci) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/release/verify-release-gate.sh b/scripts/release/verify-release-gate.sh index 0148ebc3..3e9dc203 100755 --- a/scripts/release/verify-release-gate.sh +++ b/scripts/release/verify-release-gate.sh @@ -36,6 +36,7 @@ require_line() { tag="${1:?usage: verify-release-gate.sh }" pages_dir="${2:?usage: verify-release-gate.sh }" +appcast_dir="${3:-$pages_dir/appcast}" repo="${GH_REPO:-${GITHUB_REPOSITORY:-}}" [[ -n "$repo" ]] || fail "GH_REPO or GITHUB_REPOSITORY is required" @@ -68,8 +69,8 @@ required_assets=( log "checking release assets for $tag" release_json="$(gh release view "$tag" --json isDraft,assets)" -is_draft="$(jq -r '.isDraft' <<<"$release_json")" -[[ "$is_draft" == "true" ]] || fail "$tag is not a draft; refusing to run final gate" +# Recovery after promotion must still validate the payload before publishing +# feeds. A public release is not a reason to skip or reject those checks. for asset in "${required_assets[@]}"; do size="$(jq -r --arg name "$asset" '.assets[] | select(.name == $name) | .size' <<<"$release_json" | head -1)" @@ -165,19 +166,19 @@ marketing_version="${version%%[-+]*}" log "checking appcasts for $channel" require_appcast \ - "$pages_dir/appcast/${channel}-macos-arm64.xml" \ + "$appcast_dir/${channel}-macos-arm64.xml" \ "${mac_prefix}-${version}-macos-arm64.dmg" \ "$marketing_version" require_appcast \ - "$pages_dir/appcast/${channel}-macos-x86_64.xml" \ + "$appcast_dir/${channel}-macos-x86_64.xml" \ "${mac_prefix}-${version}-macos-x86_64.dmg" \ "$marketing_version" require_appcast \ - "$pages_dir/appcast/${channel}-linux-x86_64.xml" \ + "$appcast_dir/${channel}-linux-x86_64.xml" \ "con-${version}-linux-x86_64.tar.gz" \ "$version" require_appcast \ - "$pages_dir/appcast/${channel}-windows-x86_64.xml" \ + "$appcast_dir/${channel}-windows-x86_64.xml" \ "con-${version}-windows-x86_64.zip" \ "$version" diff --git a/skills/release/SKILL.md b/skills/release/SKILL.md index 12c64ce4..e83e1b50 100644 --- a/skills/release/SKILL.md +++ b/skills/release/SKILL.md @@ -26,6 +26,10 @@ the source of truth; do not treat a green build on one platform as a release. be downloaded by publication jobs; `native-app-*` archives are internal. - A release is public only after all required platform assets and release-gate checks pass. Installers and updaters must never consume a draft. +- Signed feeds are prepared at `release-staging//appcast/`, not the live + updater endpoints. The finalizer publishes the release, verifies anonymous + access to the exact download URLs, then merges canonical feeds and updates + Homebrew. Public release metadata alone does not prove updater availability. - Never delete and recreate a tag to repair a release. Fix the workflow or rerun the affected workflow against the same commit. @@ -101,6 +105,14 @@ curl -fsSL https://con-releases.nowledge.co/install.ps1 >/dev/null - If all platform workflows succeeded but the release remains draft, inspect the latest `Finalize release` run. Rerun only the finalizer after confirming the release gate inputs are complete. +- Missing Actions results are retried with a recent-run fallback and exact + tag/SHA matching. Persistent query errors must fail visibly, not look like a + successful publication. Recover staged releases with + `gh workflow run release-finalize.yml --ref main -f tag=`. +- If promotion succeeded but feed publication failed, rerun the finalizer. It + validates public releases too, preserves newer feed entries, and never needs + a new tag. Legacy tags without staged metadata require their original + finalizer and explicit payload/feed checks instead. - If an asset is missing, rerun the platform that owns it and verify its checksum before promotion. - On the split macOS workflow, rerun failed packaging jobs without rebuilding