name: release

# Fully automated release: on every push to main, this decides the next version
# itself, then creates the vX.Y.Z tag, publishes a GitHub Release, and publishes
# to npm -- all in one job. Nothing about a release needs to be done by hand
# anymore, PR merges are the only input:
#
#   - If package.json's version still matches the latest release tag (the
#     normal case -- nobody touched it in the merged PR), this job resolves the
#     next version from the labels on every PR merged since that tag
#     (.github/scripts/resolve_version.py: minor/feature/enhancement -> minor,
#     patch/fix/bug -> patch, unlabeled -> patch, chore/ci/docs/dependencies
#     only -> nothing to release, major -> refused), bumps
#     package.json, .claude-plugin/plugin.json and docs/contract.md to that version, writes a CHANGELOG.md
#     section listing those merged PRs, and pushes that bump commit to main
#     itself before continuing -- see "Auto-bump" below.
#   - If a PR *did* bump package.json's version by hand (and, by this repo's
#     convention, wrote its own CHANGELOG.md section and docs/contract.md
#     edits), that manual choice is left alone and used as-is -- auto-bump
#     only fills in when nobody made the call already.
#
# Either way, once package.json's version has no matching tag, this creates
# that tag, publishes a GitHub Release with notes extracted from
# CHANGELOG.md's matching section, and publishes to npm. A push to main that
# ends up not changing the version at all (nothing mergeable since the last
# release, e.g. this very bump commit -- see below) creates no tag, Release,
# npm publish, Pages rebuild or plugin-branch commit: those steps are skipped.
# The MCP Registry step still runs on it (unless the bump was superseded): it
# asks npm and the registry about server.json's version and publishes the entry
# only when npm has the version and the registry does not, so a re-run or a
# later push finishes an entry an earlier run failed to publish -- while that
# version is still the one on main; an older version's entry is not gone back to
# (docs/design-decisions.md, "After 3.4.3").
#
# This runs as one job triggered directly by the push to main, not chained
# through a separate tag-push trigger, because a tag (or, now, a bump commit)
# pushed by the built-in GITHUB_TOKEN does not itself trigger another workflow
# run (a deliberate GitHub Actions anti-recursion rule) -- splitting any of
# this into "push a commit/tag" / "react to that push" workflows would
# silently never fire the second one. That anti-recursion rule is also why
# the auto-bump commit below is safe to push straight from this job without
# looping: it never starts a second run of this workflow, this same run just
# continues on past it with the new version.
#
# main is protected by a ruleset (PR required, 8 status checks) that the
# built-in GITHUB_TOKEN cannot bypass (GitHub Actions is not an accepted
# bypass actor; #137). The bump commit is therefore pushed with the
# RELEASE_PUSH_TOKEN secret when it exists: a fine-grained PAT of a repository
# admin (Contents: read/write on this repo only), whose "Repository admin"
# bypass lets the push through. A PAT push DOES trigger workflows, unlike
# GITHUB_TOKEN, so the bump commit message carries [skip ci]: the tag, the
# GitHub Release and the npm publish all happen in this same run, and a second
# run on the bump commit would only find the tag already present. Without the
# secret the push falls back to GITHUB_TOKEN (works on an unprotected main).

#
# A second way in: `workflow_dispatch` with a `version` runs only the `recover` job at the end of
# this file, never the `release` job. It finishes a version that has its tag but never reached npm
# (the npm publish failed and the run that tagged it cannot be re-run into a publish: its re-run
# sees the tag and skips). See that job's comments for what it checks and why it lives here.

on:
  push:
    branches: [main]
  workflow_dispatch:
    inputs:
      version:
        description: "X.Y.Z of a tagged version npm does not have. Dispatch on the tag: gh workflow run release.yml --ref vX.Y.Z -f version=X.Y.Z"
        required: true
        type: string

# Two merges in quick succession must release one after the other, never side by side: each
# run resolves "the next version" from the same last tag, so two concurrent runs would both
# pick the same number and the second one's bump push / tag creation would collide.
concurrency:
  group: release
  cancel-in-progress: false

permissions:
  contents: read

jobs:
  release:
    # A dispatch runs `recover` alone: the auto-bump and tag steps below only ever answer a push.
    if: github.event_name == 'push'
    runs-on: ubuntu-latest
    permissions:
      contents: write        # bump commit, tag, GitHub release, plugin branch
      pull-requests: read    # resolve_version.py reads merged PRs' labels through gh api
      id-token: write        # required for `npm publish --provenance`
      actions: write         # dispatch pages.yml once the release commit is on main
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          # The tip of main, not the SHA that triggered this run: with two merges in quick
          # succession the concurrency group queues the second run, and the first must bump on
          # top of everything already on main or its push is rejected as non-fast-forward
          # (1.4.2's first run, 2026-09-11: #171 landed while #167's run was still bumping).
          ref: main
          fetch-depth: 0
          token: ${{ secrets.RELEASE_PUSH_TOKEN || secrets.GITHUB_TOKEN }}

      - name: Decide whether an automatic version bump is needed
        id: setup
        run: |
          PKG_VERSION=$(node -p "require('./package.json').version")
          LAST_TAG=$(git tag --list 'v*' --sort=-v:refname | head -n1)
          LAST_VERSION="${LAST_TAG#v}"
          LAST_VERSION="${LAST_VERSION:-0.0.0}"
          echo "pkg_version=$PKG_VERSION" >> "$GITHUB_OUTPUT"
          echo "last_version=$LAST_VERSION" >> "$GITHUB_OUTPUT"
          if [ "$PKG_VERSION" = "$LAST_VERSION" ]; then
            echo "needs_auto_bump=true" >> "$GITHUB_OUTPUT"
          else
            echo "needs_auto_bump=false" >> "$GITHUB_OUTPUT"
          fi

      # Decides the next version from the labels of every PR merged since the last vX.Y.Z tag
      # (.github/scripts/resolve_version.py: the same label vocabulary as release-drafter.yml's
      # autolabeler; chore/ci/docs/dependencies-only PRs are not releasable; an empty result
      # means "nothing to release" and every remaining step is skipped). This used to be a
      # release-drafter call with `dry-run: true` -- an input that action does not have, so it
      # silently ran live, and it could never answer "nothing" (its `exclude-labels` hides PRs
      # from the notes but `default: patch` still bumps), which published 1.0.4 for a
      # workflow-only merge. Reads labels through `gh api`, never PR text.
      - name: Resolve the next version from merged PR labels
        id: drafter
        if: steps.setup.outputs.needs_auto_bump == 'true'
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          LAST_VERSION: ${{ steps.setup.outputs.last_version }}
        run: python3 .github/scripts/resolve_version.py

      # Nobody bumped package.json by hand, and resolve_version.py found something new to
      # release: bump package.json/docs/contract.md ourselves and write a CHANGELOG.md
      # section listing the merged PRs (and any issues they closed) since the last tag,
      # then push that commit to main before the rest of this job continues. Reads PR
      # titles via `git log` at runtime rather than interpolating them into this script,
      # since PR titles are attacker-controlled text and GitHub Actions expression
      # interpolation into a run: block is a known script-injection vector -- only our own
      # already-resolved, numeric version strings pass through ${{ }} here.
      - name: Auto-bump package.json / docs/contract.md / docs/roadmap.md / CHANGELOG.md
        id: bump
        if: |
          steps.setup.outputs.needs_auto_bump == 'true' &&
          steps.drafter.outputs.resolved_version != '' &&
          steps.drafter.outputs.resolved_version != steps.setup.outputs.last_version
        env:
          OLD_VERSION: ${{ steps.setup.outputs.last_version }}
          NEW_VERSION: ${{ steps.drafter.outputs.resolved_version }}
        run: |
          python3 - <<'PY'
          import os, re, subprocess, pathlib, sys

          old = os.environ["OLD_VERSION"]
          new = os.environ["NEW_VERSION"]
          root = pathlib.Path(".")

          # An automatic bump never crosses a major boundary. 1.0.0-1.0.2 were published by
          # accident (2026-09-11) when a `major` label reached three dependency bumps through an
          # autolabeler rule; that rule is gone, but a hand-applied `major` label on the wrong PR
          # would do the same. A real major is a deliberate, manual package.json bump in a PR
          # (the existing manual path), never something this job infers from labels.
          if old.split(".")[0] != new.split(".")[0]:
              sys.exit(f"refusing to auto-bump across a major boundary ({old} -> {new}); "
                       f"bump package.json by hand in a PR if a major release is intended")

          pkg_path = root / "package.json"
          pkg = pkg_path.read_text(encoding="utf-8")
          pkg_new = re.sub(r'("version":\s*")[^"]+(")', rf'\g<1>{new}\g<2>', pkg, count=1)
          assert pkg != pkg_new, "package.json version field not found/replaced"
          pkg_path.write_text(pkg_new, encoding="utf-8")

          # every plugin host's manifest carries the package version (Claude Code, Cursor, Gemini CLI)
          for manifest in (".claude-plugin/plugin.json", ".cursor-plugin/plugin.json", "gemini-extension.json"):
              plugin_path = root / manifest
              plugin = plugin_path.read_text(encoding="utf-8")
              plugin_new = re.sub(r'("version":\s*")[^"]+(")', rf'\g<1>{new}\g<2>', plugin, count=1)
              assert plugin != plugin_new, f"{manifest} version field not found/replaced"
              plugin_path.write_text(plugin_new, encoding="utf-8")

          # Only the two current-version mentions move; a blind replace of the version string
          # also rewrote every historical "since"/"added in" version (see the helper's docstring).
          sys.path.insert(0, str(root / ".github" / "scripts"))
          from bump_server_json import bump_server_json
          server_path = root / "server.json"
          server_path.write_text(bump_server_json(server_path.read_text(encoding="utf-8"), old, new), encoding="utf-8")

          from bump_contract_md import bump_contract_md
          contract_path = root / "docs" / "contract.md"
          contract = contract_path.read_text(encoding="utf-8")
          contract_path.write_text(bump_contract_md(contract, old, new), encoding="utf-8")

          # The roadmap's "released version today" sentence is pinned to package.json by a test;
          # the auto-bump used to leave it behind, so every label-driven release left main red
          # until a docs PR moved it (2.2.1 -> #288).
          from bump_roadmap_md import bump_roadmap_md
          roadmap_path = root / "docs" / "roadmap.md"
          roadmap = roadmap_path.read_text(encoding="utf-8")
          roadmap_path.write_text(bump_roadmap_md(roadmap, old, new), encoding="utf-8")

          # design-decisions sections written as "## Unreleased — topic" take the shipped version,
          # as CHANGELOG's do, and its contents list follows. Eleven such headings were left saying
          # "Unreleased" long after they shipped (2.3.0 .. 2.12.0) before this step existed.
          from design_decisions_index import release_headings
          dd_path = root / "docs" / "design-decisions.md"
          dd_path.write_text(release_headings(dd_path.read_text(encoding="utf-8"), new), encoding="utf-8")

          last_tag = f"v{old}" if old != "0.0.0" else None
          rev_range = f"{last_tag}..HEAD" if last_tag else "HEAD"
          log = subprocess.run(
              ["git", "log", rev_range, "--format=%s----BODY----%b----COMMIT----"],
              capture_output=True, text=True, check=True,
          ).stdout
          commits = [c for c in log.split("----COMMIT----") if c.strip()]
          subjects, issues = [], set()
          for c in commits:
              subject, _, body = c.partition("----BODY----")
              subject = subject.strip()
              if subject:
                  subjects.append(subject)
              issues.update(int(n) for n in re.findall(r"(?im)^closes\s+#(\d+)\.?\s*$", body))

          bullets = "\n".join(f"- {s}" for s in subjects) or "- (no commit subjects found)"
          closes_line = f"\n\nCloses: {', '.join(f'#{n}' for n in sorted(issues))}" if issues else ""
          section = (
              f"## {new}\n\n"
              f"_Automated release: version and notes generated from pull requests merged "
              f"since {old}._\n\n"
              f"{bullets}{closes_line}\n\n"
          )

          changelog_path = root / "CHANGELOG.md"
          changelog = changelog_path.read_text(encoding="utf-8")
          # Whatever sits under "## Unreleased" (hand-written bullets from the merged PRs, or the
          # placeholder "(nothing yet)") moves into the new version's section, ahead of the
          # generated commit-subject bullets, and the placeholder is put back. The anchor used to
          # be the literal "(nothing yet)" line, so a PR that wrote real notes there broke the
          # bump step (1.4.1's first run).
          m = re.search(r"## Unreleased\n(.*?)(?=^## )", changelog, re.S | re.M)
          assert m, "CHANGELOG.md has no '## Unreleased' section followed by a version heading"
          unreleased = m.group(1).strip()
          if unreleased and unreleased != "(nothing yet)":
              section = section.replace(f"since {old}._\n\n", f"since {old}._\n\n{unreleased}\n", 1)
          changelog = changelog[:m.start()] + "## Unreleased\n\n(nothing yet)\n\n" + section + changelog[m.end():]
          changelog_path.write_text(changelog, encoding="utf-8")
          PY

          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add package.json server.json .claude-plugin/plugin.json .cursor-plugin/plugin.json gemini-extension.json docs/contract.md CHANGELOG.md docs/roadmap.md docs/design-decisions.md
          git commit -m "chore(release): bump version to ${NEW_VERSION} [skip ci]"
          # A merge that landed after this job's checkout makes the push non-fast-forward. The
          # bump is not replayed on top of it: this used to `git pull --rebase` here, which put
          # the newer merge under the release commit, so it shipped in the tag without its label
          # being read or its line written into CHANGELOG.md, and its own release run then found
          # nothing to release (#467, A25). Instead the bump is dropped and this run releases
          # nothing: the newer merge's own run is queued behind this one in the `release`
          # concurrency group, starts from main's tip, and resolves the version from every PR
          # merged since the last tag, this run's included.
          BASE=$(git rev-parse HEAD~1)
          if ! git push origin HEAD:main; then
            git fetch origin main
            if [ "$(git rev-parse origin/main)" = "$BASE" ]; then
              echo "::error::the bump commit was refused although main has not moved (a ruleset, or RELEASE_PUSH_TOKEN): nothing was released"
              exit 1
            fi
            echo "::notice::main moved while ${NEW_VERSION} was being prepared; this run releases nothing and the run for the newer merge releases both"
            git reset --hard origin/main
            # The checkout is now the newer merge, and nothing below may release it from this
            # run: a merge that set its own version by hand (a major) has no tag yet, and the
            # steps below would tag and publish it here, under this run's label arithmetic.
            echo "superseded=true" >> "$GITHUB_OUTPUT"
          fi

      - name: Check whether this version is already released
        id: check
        env:
          SUPERSEDED: ${{ steps.bump.outputs.superseded }}
        run: |
          VERSION=$(node -p "require('./package.json').version")
          TAG="v$VERSION"
          echo "version=$VERSION" >> "$GITHUB_OUTPUT"
          echo "tag=$TAG" >> "$GITHUB_OUTPUT"
          # The commit to tag is whatever HEAD is *now*: after an auto-bump that is the bump
          # commit this job just pushed, not the merge commit that triggered the run. Tagging
          # github.sha (as this did through v1.1.0) put every auto-released tag one commit
          # before its own version bump, so `git checkout v1.1.0` showed package.json at 1.0.4.
          echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
          if [ "$SUPERSEDED" = "true" ]; then
            # not released, and not this run's to release: every step below that tags or
            # publishes is conditioned on already_released == 'false'
            echo "::notice::this run's bump was superseded; $TAG is left to the run for the newer merge"
            echo "already_released=true" >> "$GITHUB_OUTPUT"
          elif git rev-parse "$TAG" >/dev/null 2>&1; then
            echo "already_released=true" >> "$GITHUB_OUTPUT"
          else
            echo "already_released=false" >> "$GITHUB_OUTPUT"
          fi

      - name: Extract this version's CHANGELOG section
        if: steps.check.outputs.already_released == 'false'
        run: |
          awk -v ver="${{ steps.check.outputs.version }}" '
            BEGIN { found=0 }
            /^## / {
              if (found) exit
              if (index($0, ver) > 0) { found=1; next }
            }
            found { print }
          ' CHANGELOG.md > release_notes.md
          if [ ! -s release_notes.md ]; then
            echo "No matching CHANGELOG.md section found for ${{ steps.check.outputs.version }}; using a generic note." > release_notes.md
          fi

      - name: Create tag and GitHub Release
        if: steps.check.outputs.already_released == 'false'
        uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4
        with:
          tag_name: ${{ steps.check.outputs.tag }}
          target_commitish: ${{ steps.check.outputs.sha }}
          body_path: release_notes.md
          generate_release_notes: true

      # The site prints the released version and the changelog, and pages.yml's own push trigger
      # never sees the bump commit: it carries [skip ci] (#467, A28: the live site named the
      # previous version and showed the shipped notes under "Unreleased" until the next docs
      # push). A workflow_dispatch is one of the two events GITHUB_TOKEN may raise, so this run
      # asks for the build itself, on main, which by now holds the release commit. Like the plugin
      # branch it must not hold the npm publish back: it may fail, and the job's end reports it.
      - name: Rebuild GitHub Pages for the released version
        id: pages_dispatch
        if: steps.check.outputs.already_released == 'false'
        continue-on-error: true
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: gh workflow run pages.yml --ref main

      - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
        if: steps.check.outputs.already_released == 'false'
        with:
          node-version: "20"
          registry-url: "https://registry.npmjs.org"

      # The installable plugin tree (the npm tarball's contents, 2.6 MB instead of the 28 MB
      # repository) goes to the `plugin` branch, one commit per release, for plugin hosts to
      # fetch with git alone. It runs before the npm publish so a missing npm token does not
      # hold it back, and it must not hold the npm publish back either: the tag already exists,
      # so a re-run would skip every step below and that version would never reach npm. So the
      # step may fail without stopping the job, and the last step turns the job red for it. A
      # failure leaves the branch at the previous release.
      - name: Publish the plugin branch
        id: plugin_branch
        if: steps.check.outputs.already_released == 'false'
        continue-on-error: true
        run: bash .github/scripts/publish_plugin_branch.sh

      # Requires an npm access token in this repo's Settings -> Secrets and variables ->
      # Actions, named NPM_TOKEN (npmjs.com -> your avatar -> Access Tokens -> Generate New
      # Token -> Granular Access Token or Automation, with publish permission on this
      # package). Without it, this step fails but the tag/GitHub Release above still stand --
      # only the npm publish is skipped, so a missing token never blocks the rest of a release.
      - name: Publish to npm
        if: steps.check.outputs.already_released == 'false'
        run: npm publish --provenance --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

      # A green job is not a correct release (2026-09-11: three "successful" runs published
      # 1.0.0-1.0.2 by mistake). So check the *result*, not the exit code: the registry's `latest`
      # must be exactly the version this run meant to publish, and unless a PR bumped package.json
      # by hand, the major must not have moved since the previous tag. npm's own publish notice
      # says the package "may take a few minutes to become available": 1.1.0 was not visible after
      # 60 s and this step went red on a release that was in fact fine, so the window is now five
      # minutes. A failure here never re-publishes anything (the next run sees the tag and skips).
      # Two questions, asked apart. Whether npm has the version is what the MCP Registry steps
      # below need, and a version npm does not have fails here. Whether `latest` has moved to it
      # is slower to answer: npm's dist-tag read lagged more than five minutes behind the publish
      # on 3.6.2, the step failed, and every later step (the MCP Registry among them) was skipped
      # for a version npm already had. A `latest` still behind after the wait is recorded and
      # fails the job in its last step, after the registry steps have run.
      - name: Verify the publish landed as intended
        id: npm_verify
        if: steps.check.outputs.already_released == 'false'
        env:
          EXPECTED: ${{ steps.check.outputs.version }}
          PREVIOUS: ${{ steps.setup.outputs.last_version }}
          AUTO_BUMPED: ${{ steps.setup.outputs.needs_auto_bump }}
        run: |
          PKG=$(node -p "require('./package.json').name")
          if [ "$AUTO_BUMPED" = "true" ] && [ "${EXPECTED%%.*}" != "${PREVIOUS%%.*}" ]; then
            echo "::error::automatic release crossed a major boundary: $PREVIOUS -> $EXPECTED"; exit 1
          fi
          # 15 minutes, and --prefer-online so a cached "not found" is not what gets re-read: 3.8.8
          # took more than the 5 minutes this loop used to wait, which failed the job after a
          # good publish and skipped the MCP Registry step
          # Bounded by elapsed time, not by a count: one `npm view` can itself take minutes when
          # the registry stalls (the last request may overshoot the deadline by its own timeout)
          deadline=$((SECONDS + 900))
          while [ "$SECONDS" -lt "$deadline" ]; do
            HAVE=$(npm view "$PKG@$EXPECTED" version --prefer-online --cache /tmp/npm-verify-cache 2>"$RUNNER_TEMP/npm-verify.err" || true)
            [ "$HAVE" = "$EXPECTED" ] && break
            echo "npm has no $PKG@$EXPECTED yet (${SECONDS}s elapsed)"; sleep 10
          done
          if [ "$HAVE" != "$EXPECTED" ]; then
            echo "::error::npm does not have $PKG@$EXPECTED after publishing it; the last npm view said: $(tail -n 3 "$RUNNER_TEMP/npm-verify.err" 2>/dev/null | tr '\n' ' ')"; exit 1
          fi
          for i in $(seq 1 60); do
            LATEST=$(npm view "$PKG" version --cache /tmp/npm-verify-cache 2>/dev/null || true)
            [ "$LATEST" = "$EXPECTED" ] && break
            echo "npm latest=$LATEST, expected $EXPECTED (attempt $i/60)"; sleep 10
          done
          if [ "$LATEST" != "$EXPECTED" ]; then
            echo "::warning::npm has $PKG@$EXPECTED but still reports latest=$LATEST; the job fails at its end"
            echo "latest_lag=${LATEST:-unknown}" >> "$GITHUB_OUTPUT"
          fi
          echo "published $PKG@$EXPECTED (previous tag $PREVIOUS)"

      # The MCP Registry entry (server.json, io.github.kajisho5/ffmpeg-skill). It points at the npm
      # package, so it can only be published once npm has this version, and the registry refuses a
      # version it already lists. These steps therefore do not hang on `already_released`: every
      # run asks the two registries and publishes when npm has the version and the MCP Registry
      # does not. That makes a re-run finish a publish that failed, for the version on main at
      # the time of the re-run (the checkout is main's tip, not the commit that failed), and it is
      # how a version that was released before these steps existed gets listed. Authentication is GitHub's OIDC token
      # for this repository (`id-token: write` above), which is what lets a name under
      # io.github.kajisho5/ be published with no stored secret. mcp-publisher is pinned to a
      # release and its Sigstore bundle is verified before it runs, as the registry's own guide
      # says to. Like the plugin branch, a failure here must not undo or block a release: the
      # steps may fail, and the job's last step reports it.
      - name: Ask whether the MCP Registry already lists this version
        id: registry_state
        if: steps.bump.outputs.superseded != 'true'
        continue-on-error: true
        run: |
          set -euo pipefail
          NAME=$(node -p "require('./server.json').name")
          VERSION=$(node -p "require('./server.json').version")
          PKG=$(node -p "require('./package.json').name")
          # npm answers a version it does not have with E404 and exit 1; any other failure (network,
          # registry down) also exits 1, and stops this step as "could not ask". Neither is a quiet
          # skip. By this point the version is either one this run just published (the verify step
          # above saw it on npm) or one an earlier run tagged, so a version npm does not have is a
          # release that never reached npm: a re-run skips `npm publish` because the tag exists,
          # and without this the job would be green with the release on neither registry.
          NPM_STATE=0
          ON_NPM=$(npm view "$PKG@$VERSION" version --cache /tmp/npm-verify-cache 2> npm-view.err) || NPM_STATE=$?
          if [ "$NPM_STATE" -ne 0 ]; then
            if grep -q "E404" npm-view.err; then
              rm -f npm-view.err
              echo "::error::$PKG@$VERSION is tagged but npm does not have it, so the MCP Registry cannot list it. This job skips npm publish once the tag exists; the recover job publishes it, with provenance and a dist-tag that never moves latest back: gh workflow run release.yml --ref v$VERSION -f version=$VERSION (see README, Releasing)."; exit 1
            fi
            cat npm-view.err >&2
            echo "::error::could not ask npm whether $PKG@$VERSION exists (npm view exited $NPM_STATE)"; exit 1
          fi
          rm -f npm-view.err
          if [ "$ON_NPM" != "$VERSION" ]; then
            echo "::error::npm answered '$ON_NPM' for $PKG@$VERSION"; exit 1
          fi
          # One name and one version, asked exactly: the list endpoint is paginated, and a version on
          # a later page would read as absent, be published a second time and be refused. 200 is
          # listed and 404 is not; anything else (a registry that could not be asked, a 5xx) is
          # neither, and stops the step.
          ENCODED=$(NAME="$NAME" node -p 'encodeURIComponent(process.env.NAME)')
          STATUS=$(curl --silent --show-error --max-time 60 --output /dev/null --write-out '%{http_code}' \
            "https://registry.modelcontextprotocol.io/v0/servers/$ENCODED/versions/$VERSION") || {
            echo "::error::could not ask the MCP Registry whether $NAME $VERSION is listed"; exit 1; }
          case "$STATUS" in
            200) LISTED=yes ;;
            404) LISTED=no ;;
            *) echo "::error::the MCP Registry answered HTTP $STATUS for $NAME $VERSION"; exit 1 ;;
          esac
          if [ "$LISTED" = "yes" ]; then
            echo "the MCP Registry already lists $NAME $VERSION"
            echo "publish=false" >> "$GITHUB_OUTPUT"
          else
            echo "the MCP Registry does not list $NAME $VERSION yet"
            echo "publish=true" >> "$GITHUB_OUTPUT"
          fi

      - name: Install cosign
        id: cosign
        if: steps.registry_state.outputs.publish == 'true'
        continue-on-error: true
        uses: sigstore/cosign-installer@756fe2d284c7292c4e9b62c8a28f1e5629c59532 # v4.1.3

      - name: Publish to the MCP Registry
        id: mcp_registry
        if: steps.registry_state.outputs.publish == 'true' && steps.cosign.outcome == 'success'
        continue-on-error: true
        env:
          MCP_PUBLISHER_VERSION: v1.8.1
        run: |
          set -euo pipefail
          WORK="$(mktemp -d)"
          archive="mcp-publisher_linux_amd64.tar.gz"
          base_url="https://github.com/modelcontextprotocol/registry/releases/download/${MCP_PUBLISHER_VERSION}"
          curl --fail --location --silent --show-error --output "$WORK/$archive" "$base_url/$archive"
          curl --fail --location --silent --show-error --output "$WORK/$archive.sigstore.json" "$base_url/$archive.sigstore.json"
          cosign verify-blob \
            --bundle "$WORK/$archive.sigstore.json" \
            --certificate-identity "https://github.com/modelcontextprotocol/registry/.github/workflows/release.yml@refs/tags/${MCP_PUBLISHER_VERSION}" \
            --certificate-oidc-issuer "https://token.actions.githubusercontent.com" \
            "$WORK/$archive"
          tar xzf "$WORK/$archive" -C "$WORK" mcp-publisher
          "$WORK/mcp-publisher" login github-oidc
          "$WORK/mcp-publisher" publish

      - name: Fail the job when the MCP Registry was not updated
        if: steps.registry_state.outcome == 'failure' || steps.cosign.outcome == 'failure' || steps.mcp_registry.outcome == 'failure'
        run: |
          echo "::error::the MCP Registry entry was not published (see the three MCP Registry steps, which say why). The tag, the GitHub Release and npm do not depend on it. A re-run publishes the version that is on main when it runs: if main has moved on to a newer version by then, that one is listed and this one is not."
          exit 1

      - name: Fail the job when npm's latest did not move to this version
        if: always() && steps.npm_verify.outputs.latest_lag != ''
        env:
          EXPECTED: ${{ steps.check.outputs.version }}
          LATEST: ${{ steps.npm_verify.outputs.latest_lag }}
        run: |
          echo "::error::npm has $EXPECTED but its latest dist-tag still read $LATEST after ten minutes. The MCP Registry steps above ran. Check 'npm view <package> dist-tags' and move latest by hand if it is still behind."
          exit 1

      # always(): the step above may already have failed the job, and a second failure still has
      # to be reported, not skipped.
      - name: Fail the job when the plugin branch was not published
        if: always() && steps.plugin_branch.outcome == 'failure'
        run: |
          echo "::error::the plugin branch was not updated for this release (see the 'Publish the plugin branch' step); npm and the GitHub Release are unaffected. Run .github/scripts/publish_plugin_branch.sh from the release commit to publish it."
          exit 1

      - name: Fail the job when GitHub Pages was not asked to rebuild
        if: always() && steps.pages_dispatch.outcome == 'failure'
        run: |
          echo "::error::pages.yml was not dispatched for this release, so the site still shows the previous version; npm and the GitHub Release are unaffected. Run: gh workflow run pages.yml --ref main"
          exit 1

  # Finishing a release that was tagged (GitHub Release included) but never reached npm (#448).
  # The `release` job cannot do it: once the tag exists, a re-run skips every publish step, and its
  # MCP Registry step only reports the gap. Dispatch this on the tag, for that tag's version:
  #
  #   gh workflow run release.yml --ref vX.Y.Z -f version=X.Y.Z
  #
  # Why here and not in a workflow file of its own: the npm publish authenticates the way the
  # `release` job's does (the NPM_TOKEN secret, with `--provenance` signed through this job's
  # OIDC token). Kept in release.yml it stays on the one workflow file an npm trusted publisher
  # would name if the package moves to trusted publishing (a trusted publisher names a repository
  # and a workflow filename, optionally an environment, not a branch), and in the `release`
  # concurrency group, so it never runs beside a release.
  #
  # Why it runs on the tag and refuses anything else: the provenance attestation npm publishes
  # names the run's commit (GITHUB_SHA) and ref as the package's source. Dispatched on main with
  # the tag checked out, the tarball would be built from the tag while its attestation named main's
  # tip, a different commit. So the job checks out refs/tags/vX.Y.Z and refuses to publish unless
  # that is GITHUB_SHA: dispatched with --ref vX.Y.Z (which runs the release.yml committed at the
  # tag), or on main while main's tip is still the tagged commit. The cost: a tag cut before this
  # job existed has no dispatch trigger at its own commit, and cannot be recovered here.
  #
  # What it checks before publishing, each a refusal with its own message: the input is X.Y.Z; the
  # tag vX.Y.Z exists; package.json at the tag carries that version; npm answers E404 for it (a
  # version npm has is refused, and an npm that cannot be asked is not read as "absent"). It
  # publishes under `latest` only when the version is above every stable version npm has, and
  # under `backport` otherwise (.github/scripts/recover_release.py), so `latest` never moves back.
  # Then the two steps the failed run may have skipped, each only when it is still missing: the
  # plugin branch (no commit for this version on it, and its tip is an older version; the branch
  # only moves forward) and the MCP Registry entry (not listed; a `backport` is not listed, as the
  # registry's newest entry is the one clients read). The GitHub Release is not touched.
  recover:
    if: github.event_name == 'workflow_dispatch'
    runs-on: ubuntu-latest
    permissions:
      contents: write        # the plugin branch push; reading the tag
      id-token: write        # `npm publish --provenance` and the MCP Registry's github-oidc login
    steps:
      # Nothing is checked out yet, and the input is untrusted text: it reaches the shell only
      # through the environment, and nothing below reads it before this step has matched it.
      - name: Refuse a version that is malformed or not tagged
        id: gate
        env:
          VERSION: ${{ inputs.version }}
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          set -euo pipefail
          if ! [[ "$VERSION" =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]]; then
            echo "::error::version must be X.Y.Z (no leading v); got '$VERSION'"; exit 1
          fi
          TAG="v$VERSION"
          TAG_STATE=0
          gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/$TAG" --jq .ref > "$RUNNER_TEMP/tag-ref.out" 2> "$RUNNER_TEMP/tag-ref.err" || TAG_STATE=$?
          if [ "$TAG_STATE" -ne 0 ]; then
            if grep -q "HTTP 404" "$RUNNER_TEMP/tag-ref.err"; then
              echo "::error::there is no tag $TAG; recovery only finishes a version that was tagged"; exit 1
            fi
            cat "$RUNNER_TEMP/tag-ref.err" >&2
            echo "::error::could not ask GitHub whether $TAG exists (gh api exited $TAG_STATE)"; exit 1
          fi
          if [ "$(cat "$RUNNER_TEMP/tag-ref.out")" != "refs/tags/$TAG" ]; then
            echo "::error::GitHub answered '$(cat "$RUNNER_TEMP/tag-ref.out")' for refs/tags/$TAG"; exit 1
          fi
          rm -f "$RUNNER_TEMP/tag-ref.out" "$RUNNER_TEMP/tag-ref.err"
          echo "version=$VERSION" >> "$GITHUB_OUTPUT"
          echo "tag=$TAG" >> "$GITHUB_OUTPUT"

      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
        with:
          # The tagged commit, never main. Credentials stay: the plugin branch step pushes.
          ref: refs/tags/${{ steps.gate.outputs.tag }}
          fetch-depth: 0
          token: ${{ secrets.RELEASE_PUSH_TOKEN || secrets.GITHUB_TOKEN }}

      - name: Refuse unless the tag is this run's commit and npm does not have the version
        id: state
        env:
          VERSION: ${{ steps.gate.outputs.version }}
          TAG: ${{ steps.gate.outputs.tag }}
        run: |
          set -euo pipefail
          HEAD_SHA=$(git rev-parse HEAD)
          TAG_SHA=$(git rev-parse "refs/tags/$TAG^{commit}")
          if [ "$HEAD_SHA" != "$TAG_SHA" ]; then
            echo "::error::checked out $HEAD_SHA, but $TAG is $TAG_SHA"; exit 1
          fi
          if [ "$TAG_SHA" != "$GITHUB_SHA" ]; then
            echo "::error::$TAG is $TAG_SHA but this run is $GITHUB_REF at $GITHUB_SHA. The provenance attestation would name $GITHUB_SHA as the source of a package built from $TAG. Dispatch on the tag: gh workflow run release.yml --ref $TAG -f version=$VERSION"; exit 1
          fi
          PKG=$(node -p "require('./package.json').name")
          PKG_VERSION=$(node -p "require('./package.json').version")
          if [ "$PKG_VERSION" != "$VERSION" ]; then
            echo "::error::package.json at $TAG says $PKG_VERSION, not $VERSION"; exit 1
          fi
          # E404 is the one answer that means "npm does not have it". A version npm has is refused
          # (npm never takes a version twice), and any other failure is "could not ask".
          NPM_STATE=0
          npm view "$PKG@$VERSION" version --cache /tmp/npm-recover-cache > "$RUNNER_TEMP/npm-view.out" 2> "$RUNNER_TEMP/npm-view.err" || NPM_STATE=$?
          if [ "$NPM_STATE" -eq 0 ]; then
            echo "::error::npm already has $PKG@$(cat "$RUNNER_TEMP/npm-view.out"); there is nothing to recover"; exit 1
          fi
          if ! grep -q "E404" "$RUNNER_TEMP/npm-view.err"; then
            cat "$RUNNER_TEMP/npm-view.err" >&2
            echo "::error::could not ask npm whether $PKG@$VERSION exists (npm view exited $NPM_STATE)"; exit 1
          fi
          # The package exists (every recovered version follows one that reached npm), so a failure
          # to list its versions stops the step under set -e; it is never read as "no versions".
          npm view "$PKG" versions --json --cache /tmp/npm-recover-cache > "$RUNNER_TEMP/npm-versions.json"
          DIST_TAG=$(python3 .github/scripts/recover_release.py dist-tag "$VERSION" "$RUNNER_TEMP/npm-versions.json")
          case "$DIST_TAG" in
            latest|backport) ;;
            *) echo "::error::no dist-tag decided for $VERSION (got '$DIST_TAG')"; exit 1 ;;
          esac
          rm -f "$RUNNER_TEMP/npm-view.out" "$RUNNER_TEMP/npm-view.err"
          echo "npm does not have $PKG@$VERSION; it is published under the dist-tag $DIST_TAG"
          echo "package=$PKG" >> "$GITHUB_OUTPUT"
          echo "dist_tag=$DIST_TAG" >> "$GITHUB_OUTPUT"

      - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
        with:
          node-version: "20"
          registry-url: "https://registry.npmjs.org"

      # The same publish as the `release` job's, with the dist-tag named: npm's default would be
      # `latest` whatever the version.
      - name: Publish the tagged version to npm
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
          DIST_TAG: ${{ steps.state.outputs.dist_tag }}
        run: npm publish --provenance --access public --tag "$DIST_TAG"

      # As in the `release` job: whether npm has the version gates what follows; whether the
      # dist-tag has caught up is slower to answer and fails the job at its end instead.
      - name: Verify the recovered version landed under its dist-tag
        id: npm_verify
        env:
          PKG: ${{ steps.state.outputs.package }}
          EXPECTED: ${{ steps.gate.outputs.version }}
          DIST_TAG: ${{ steps.state.outputs.dist_tag }}
        run: |
          # 15 minutes, and --prefer-online so a cached "not found" is not what gets re-read: 3.8.8
          # took more than the 5 minutes this loop used to wait, which failed the job after a
          # good publish and skipped the MCP Registry step
          # Bounded by elapsed time, not by a count: one `npm view` can itself take minutes when
          # the registry stalls (the last request may overshoot the deadline by its own timeout)
          deadline=$((SECONDS + 900))
          while [ "$SECONDS" -lt "$deadline" ]; do
            HAVE=$(npm view "$PKG@$EXPECTED" version --prefer-online --cache /tmp/npm-verify-cache 2>"$RUNNER_TEMP/npm-verify.err" || true)
            [ "$HAVE" = "$EXPECTED" ] && break
            echo "npm has no $PKG@$EXPECTED yet (${SECONDS}s elapsed)"; sleep 10
          done
          if [ "$HAVE" != "$EXPECTED" ]; then
            echo "::error::npm does not have $PKG@$EXPECTED after publishing it; the last npm view said: $(tail -n 3 "$RUNNER_TEMP/npm-verify.err" 2>/dev/null | tr '\n' ' ')"; exit 1
          fi
          for i in $(seq 1 60); do
            TAGGED=$(npm view "$PKG" "dist-tags.$DIST_TAG" --cache /tmp/npm-verify-cache 2>/dev/null || true)
            [ "$TAGGED" = "$EXPECTED" ] && break
            echo "npm $DIST_TAG=$TAGGED, expected $EXPECTED (attempt $i/60)"; sleep 10
          done
          if [ "$TAGGED" != "$EXPECTED" ]; then
            echo "::warning::npm has $PKG@$EXPECTED but its $DIST_TAG dist-tag still reads '$TAGGED'; the job fails at its end"
            echo "tag_lag=${TAGGED:-unknown}" >> "$GITHUB_OUTPUT"
          fi
          echo "recovered $PKG@$EXPECTED under $DIST_TAG"

      # Missing means: no commit on the branch says it was built for this version, and the branch's
      # tip is an older version (or there is no branch). A newer tip stays: hosts read the tip, and
      # the branch only moves forward. A branch that cannot be asked stops the step.
      - name: Ask whether the plugin branch still lacks this version
        id: plugin_state
        continue-on-error: true
        env:
          VERSION: ${{ steps.gate.outputs.version }}
        run: |
          set -euo pipefail
          REMOTE_STATE=0
          git ls-remote --exit-code --heads origin plugin >/dev/null || REMOTE_STATE=$?
          if [ "$REMOTE_STATE" -eq 2 ]; then
            echo "there is no plugin branch yet"; echo "publish=true" >> "$GITHUB_OUTPUT"; exit 0
          fi
          if [ "$REMOTE_STATE" -ne 0 ]; then
            echo "::error::could not ask origin whether the plugin branch exists (git ls-remote exited $REMOTE_STATE)"; exit 1
          fi
          git fetch --quiet origin refs/heads/plugin
          if git log --format=%s FETCH_HEAD | grep -qF "plugin: ffmpeg-skill $VERSION (built from "; then
            echo "the plugin branch already has a commit for $VERSION"; echo "publish=false" >> "$GITHUB_OUTPUT"; exit 0
          fi
          TIP=$(git show FETCH_HEAD:ffmpeg-skill/package.json | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>console.log(JSON.parse(s).version))')
          NEWER=0
          python3 .github/scripts/recover_release.py newer "$VERSION" "$TIP" || NEWER=$?
          case "$NEWER" in
            0) echo "the plugin branch is at $TIP, older than $VERSION"; echo "publish=true" >> "$GITHUB_OUTPUT" ;;
            1) echo "the plugin branch is at $TIP, not older than $VERSION; it stays there"; echo "publish=false" >> "$GITHUB_OUTPUT" ;;
            *) echo "::error::could not compare $VERSION with the plugin branch's version '$TIP'"; exit 1 ;;
          esac

      - name: Publish the plugin branch for the recovered version
        id: plugin_branch
        if: steps.plugin_state.outputs.publish == 'true'
        continue-on-error: true
        run: bash .github/scripts/publish_plugin_branch.sh

      # The same three steps as the `release` job's, asked for the tag's server.json, and skipped
      # for a `backport`.
      - name: Ask whether the MCP Registry still lacks the recovered version
        id: registry_state
        if: steps.state.outputs.dist_tag == 'latest'
        continue-on-error: true
        env:
          EXPECTED: ${{ steps.gate.outputs.version }}
        run: |
          set -euo pipefail
          NAME=$(node -p "require('./server.json').name")
          VERSION=$(node -p "require('./server.json').version")
          if [ "$VERSION" != "$EXPECTED" ]; then
            echo "::error::server.json at the tag says $VERSION, not $EXPECTED"; exit 1
          fi
          ENCODED=$(NAME="$NAME" node -p 'encodeURIComponent(process.env.NAME)')
          STATUS=$(curl --silent --show-error --max-time 60 --output /dev/null --write-out '%{http_code}' \
            "https://registry.modelcontextprotocol.io/v0/servers/$ENCODED/versions/$VERSION") || {
            echo "::error::could not ask the MCP Registry whether $NAME $VERSION is listed"; exit 1; }
          case "$STATUS" in
            200) echo "the MCP Registry already lists $NAME $VERSION"; echo "publish=false" >> "$GITHUB_OUTPUT" ;;
            404) echo "the MCP Registry does not list $NAME $VERSION yet"; echo "publish=true" >> "$GITHUB_OUTPUT" ;;
            *) echo "::error::the MCP Registry answered HTTP $STATUS for $NAME $VERSION"; exit 1 ;;
          esac

      - name: Install cosign for the recovered version
        id: cosign
        if: steps.registry_state.outputs.publish == 'true'
        continue-on-error: true
        uses: sigstore/cosign-installer@756fe2d284c7292c4e9b62c8a28f1e5629c59532 # v4.1.3

      - name: Publish the recovered version to the MCP Registry
        id: mcp_registry
        if: steps.registry_state.outputs.publish == 'true' && steps.cosign.outcome == 'success'
        continue-on-error: true
        env:
          MCP_PUBLISHER_VERSION: v1.8.1
        run: |
          set -euo pipefail
          WORK="$(mktemp -d)"
          archive="mcp-publisher_linux_amd64.tar.gz"
          base_url="https://github.com/modelcontextprotocol/registry/releases/download/${MCP_PUBLISHER_VERSION}"
          curl --fail --location --silent --show-error --output "$WORK/$archive" "$base_url/$archive"
          curl --fail --location --silent --show-error --output "$WORK/$archive.sigstore.json" "$base_url/$archive.sigstore.json"
          cosign verify-blob \
            --bundle "$WORK/$archive.sigstore.json" \
            --certificate-identity "https://github.com/modelcontextprotocol/registry/.github/workflows/release.yml@refs/tags/${MCP_PUBLISHER_VERSION}" \
            --certificate-oidc-issuer "https://token.actions.githubusercontent.com" \
            "$WORK/$archive"
          tar xzf "$WORK/$archive" -C "$WORK" mcp-publisher
          "$WORK/mcp-publisher" login github-oidc
          "$WORK/mcp-publisher" publish

      # always(): each failure is reported, whichever failed first. A second dispatch cannot finish
      # either step: npm has the version by then, so it stops at its first check, by design.
      - name: Fail the recovery when its dist-tag did not move
        if: always() && steps.npm_verify.outputs.tag_lag != ''
        env:
          EXPECTED: ${{ steps.gate.outputs.version }}
          DIST_TAG: ${{ steps.state.outputs.dist_tag }}
          TAGGED: ${{ steps.npm_verify.outputs.tag_lag }}
        run: |
          echo "::error::npm has $EXPECTED but its $DIST_TAG dist-tag still read $TAGGED after ten minutes. Check 'npm view <package> dist-tags' and move it by hand if it is still behind."
          exit 1

      - name: Fail the recovery when the plugin branch was not published
        if: always() && (steps.plugin_state.outcome == 'failure' || steps.plugin_branch.outcome == 'failure')
        run: |
          echo "::error::the plugin branch was not updated for the recovered version (see the two plugin branch steps); npm is unaffected. Run .github/scripts/publish_plugin_branch.sh from the tag to publish it."
          exit 1

      - name: Fail the recovery when the MCP Registry was not updated
        if: always() && (steps.registry_state.outcome == 'failure' || steps.cosign.outcome == 'failure' || steps.mcp_registry.outcome == 'failure')
        run: |
          echo "::error::the MCP Registry entry was not published for the recovered version (see the three MCP Registry steps); npm is unaffected. Publish server.json from the tag with mcp-publisher by hand."
          exit 1