diff --git a/.github/workflows/changeset.yaml b/.github/workflows/changeset.yaml index 42c234937..77f540cbb 100644 --- a/.github/workflows/changeset.yaml +++ b/.github/workflows/changeset.yaml @@ -28,7 +28,7 @@ jobs: with: node-version-file: .tool-versions - name: Fetch pull request base ref - run: git fetch origin "${{ github.base_ref }}:refs/remotes/origin/${{ github.base_ref }}" + run: git fetch origin "refs/heads/$GITHUB_BASE_REF:refs/remotes/origin/$GITHUB_BASE_REF" - name: Validate changeset summaries run: | node --test scripts/release/validate-changesets.test.mjs diff --git a/.github/workflows/prepare-release.yaml b/.github/workflows/prepare-release.yaml index ea644102e..042c7e493 100644 --- a/.github/workflows/prepare-release.yaml +++ b/.github/workflows/prepare-release.yaml @@ -2,35 +2,38 @@ name: Prepare Release on: workflow_dispatch: + inputs: + source_branch: + description: Branch to prepare (defaults to the selected workflow branch) + type: string permissions: - contents: write - pull-requests: write + contents: read + pull-requests: read concurrency: - group: prepare-release-${{ github.ref_name }} + group: prepare-release-${{ inputs.source_branch || github.ref_name }} cancel-in-progress: false env: + SOURCE_BRANCH: ${{ inputs.source_branch || github.ref_name }} HUSKY: "0" jobs: prepare-release: runs-on: ubuntu-latest timeout-minutes: 20 + outputs: + source_sha: ${{ steps.checkout.outputs.commit }} + has_changes: ${{ steps.patch.outputs.has_changes }} steps: - - name: Require main branch - run: | - if [ "${{ github.ref_name }}" != "main" ]; then - { - echo "## Prepare release" - echo - echo "This workflow must be run from \`main\`. Selected ref: \`${{ github.ref_name }}\`." - } >> "$GITHUB_STEP_SUMMARY" - exit 1 - fi + - name: Validate source branch + run: git check-ref-format "refs/heads/$SOURCE_BRANCH" - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + id: checkout with: + persist-credentials: false + ref: refs/heads/${{ env.SOURCE_BRANCH }} fetch-depth: 0 - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0 - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 @@ -41,76 +44,83 @@ jobs: run: pnpm install --frozen-lockfile - name: Validate publishable package metadata run: node scripts/release/validate-publishable-packages.mjs - - name: Record source commit and prepare branch - id: source - run: | - main_sha="$(git rev-parse HEAD)" - short_main_sha="$(git rev-parse --short=12 HEAD)" - prepare_branch="prepare-release/${short_main_sha}" - - { - echo "main_sha=$main_sha" - echo "short_main_sha=$short_main_sha" - echo "prepare_branch=$prepare_branch" - } >> "$GITHUB_OUTPUT" - name: Run changeset version env: GITHUB_TOKEN: ${{ github.token }} run: pnpm exec changeset version - - name: Read release version - id: release_version + - name: Save release changes + id: patch run: | - release_version="$(node -p "require('./js/package.json').version")" - echo "version=$release_version" >> "$GITHUB_OUTPUT" - - name: Create release commit - id: release_commit - run: | - git config user.name "github-actions[bot]" - git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - git switch -c "${{ steps.source.outputs.prepare_branch }}" git add -A - if git diff --cached --quiet; then - echo "No release changes were generated by changeset version." + echo "No release changes were generated by changeset version." >> "$GITHUB_STEP_SUMMARY" echo "has_changes=false" >> "$GITHUB_OUTPUT" exit 0 fi - git commit -m "chore: Prepare release" - release_sha="$(git rev-parse HEAD)" - git push origin HEAD:refs/heads/${{ steps.source.outputs.prepare_branch }} + git diff --cached --binary > "$RUNNER_TEMP/version.patch" echo "has_changes=true" >> "$GITHUB_OUTPUT" - echo "release_sha=$release_sha" >> "$GITHUB_OUTPUT" - - name: Summarize empty release - if: steps.release_commit.outputs.has_changes == 'false' - run: | - { - echo "## Prepare release" - echo - echo "No release changes were generated by \`changeset version\`." - } >> "$GITHUB_STEP_SUMMARY" - - name: Create release PR - if: steps.release_commit.outputs.has_changes == 'true' + - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + if: steps.patch.outputs.has_changes == 'true' + with: + name: release-changes + path: ${{ runner.temp }}/version.patch + retention-days: 1 + if-no-files-found: error + + open-release-pr: + needs: prepare-release + if: needs.prepare-release.outputs.has_changes == 'true' + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: release-changes + path: ${{ runner.temp }}/release + - name: Create release commit and pull request env: GH_TOKEN: ${{ github.token }} - SOURCE_MAIN_SHA: ${{ steps.source.outputs.main_sha }} + SOURCE_SHA: ${{ needs.prepare-release.outputs.source_sha }} run: | - node <<'NODE' > release-packages.md + git check-ref-format "refs/heads/$SOURCE_BRANCH" + [[ "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]] + git merge-base --is-ancestor "$SOURCE_SHA" "refs/remotes/origin/$SOURCE_BRANCH" + short_sha="$(git rev-parse --short=12 "$SOURCE_SHA")" + prepare_branch="prepare-release/$SOURCE_BRANCH-$short_sha" + + # Build the release tree in the index without checking out source-branch files. + git read-tree "$SOURCE_SHA" + git apply --cached "$RUNNER_TEMP/release/version.patch" + release_version="$(git show :js/package.json | jq -er .version)" + if [[ "$SOURCE_BRANCH" =~ ^v([0-9]+)$ && "${release_version%%.*}" != "${BASH_REMATCH[1]}" ]]; then + echo "SDK version $release_version does not match maintenance branch $SOURCE_BRANCH." >&2 + exit 1 + fi + + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + release_sha="$(git commit-tree "$(git write-tree)" -p "$SOURCE_SHA" -m "chore: Prepare release")" + node <<'NODE' > "$RUNNER_TEMP/release-packages.md" const { execFileSync } = require("node:child_process"); - const fs = require("node:fs"); const paths = execFileSync( "git", - ["diff", "--name-only", process.env.SOURCE_MAIN_SHA, "HEAD", "--", "**/package.json", "package.json"], + ["diff", "--name-only", "--cached", process.env.SOURCE_SHA, "--", "**/package.json", "package.json"], { encoding: "utf8" }, ) .trim() .split("\n") .filter(Boolean); const packages = paths - .map((path) => ({ path, manifest: JSON.parse(fs.readFileSync(path, "utf8")) })) + .map((path) => ({ path, manifest: JSON.parse(execFileSync("git", ["show", `:${path}`], { encoding: "utf8" })) })) .filter(({ path, manifest }) => { const previous = JSON.parse( - execFileSync("git", ["show", `${process.env.SOURCE_MAIN_SHA}:${path}`], { encoding: "utf8" }), + execFileSync("git", ["show", `${process.env.SOURCE_SHA}:${path}`], { encoding: "utf8" }), ); return manifest.version !== previous.version; }) @@ -129,16 +139,18 @@ jobs: echo echo "## Packages" echo - cat release-packages.md + cat "$RUNNER_TEMP/release-packages.md" echo - echo "Source-main-sha: ${{ steps.source.outputs.main_sha }}" - } > release-pr-body.md + echo "Source-sha: $SOURCE_SHA" + } > "$RUNNER_TEMP/release/body.md" + + git push origin "$release_sha:refs/heads/$prepare_branch" pr_url="$(gh pr create \ - --base main \ - --head "${{ steps.source.outputs.prepare_branch }}" \ - --title "chore: Prepare release v${{ steps.release_version.outputs.version }} (${{ steps.source.outputs.short_main_sha }})" \ - --body-file release-pr-body.md)" + --base "$SOURCE_BRANCH" \ + --head "$prepare_branch" \ + --title "chore: Prepare release v$release_version ($short_sha)" \ + --body-file "$RUNNER_TEMP/release/body.md")" { echo "## Prepare release" @@ -148,6 +160,7 @@ jobs: echo "To publish this release, run the \`Publish Release\` workflow with:" echo echo "\`\`\`text" - echo "release_sha: ${{ steps.release_commit.outputs.release_sha }}" + echo "source_branch: $SOURCE_BRANCH" + echo "release_sha: $release_sha" echo "\`\`\`" } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/publish-stable-release.yaml b/.github/workflows/publish-stable-release.yaml index 270dc9581..35af71858 100644 --- a/.github/workflows/publish-stable-release.yaml +++ b/.github/workflows/publish-stable-release.yaml @@ -5,6 +5,9 @@ run-name: Publish ${{ inputs.prerelease && 'prerelease' || 'stable release' }} ( on: workflow_dispatch: inputs: + source_branch: + description: Stable release source branch (defaults to the selected workflow branch) + type: string release_sha: description: Full commit SHA to publish required: true @@ -15,10 +18,11 @@ on: type: boolean concurrency: - group: publish-release-${{ inputs.prerelease && 'rc' || 'latest' }}-${{ inputs.release_sha }} + group: publish-release-${{ inputs.prerelease && 'rc' || 'stable' }}-${{ inputs.release_sha }} cancel-in-progress: false env: + SOURCE_BRANCH: ${{ inputs.source_branch || github.ref_name }} HUSKY: "0" NPM_CONFIG_PROVENANCE: "true" @@ -51,36 +55,9 @@ jobs: release_sha="$(printf '%s\n' "$RELEASE_SHA" | tr '[:upper:]' '[:lower:]')" echo "release_sha=$release_sha" >> "$GITHUB_OUTPUT" - print-changelog-links: - needs: - - validate-release-sha - runs-on: ubuntu-latest - timeout-minutes: 5 - permissions: - contents: read - steps: - - name: Print changelog links - env: - GH_TOKEN: ${{ github.token }} - GH_REPO: ${{ github.repository }} - RELEASE_SHA: ${{ needs.validate-release-sha.outputs.release_sha }} - GITHUB_SERVER_URL: ${{ github.server_url }} - run: | - set -euo pipefail - - latest_release_tag="$(gh api "repos/$GH_REPO/releases/latest" --jq '.tag_name')" - encoded_latest_release_tag="$(jq -rn --arg tag "$latest_release_tag" '$tag|@uri')" - diff_url="$GITHUB_SERVER_URL/$GH_REPO/compare/$encoded_latest_release_tag...$RELEASE_SHA" - - { - echo "Release SHA: $RELEASE_SHA" - echo "Diff to latest release: $diff_url" - } | tee -a "$GITHUB_STEP_SUMMARY" - build-package-artifacts: needs: - validate-release-sha - - print-changelog-links runs-on: ubuntu-latest timeout-minutes: 30 permissions: @@ -89,9 +66,10 @@ jobs: attestations: write outputs: has_work: ${{ steps.detect.outputs.has_work }} - manifest_json: ${{ steps.detect.outputs.manifest_json }} + manifest_json: ${{ steps.manifest.outputs.json }} release_sha: ${{ needs.validate-release-sha.outputs.release_sha }} branch: ${{ steps.release-context.outputs.branch }} + github_latest: ${{ steps.release-context.outputs.github_latest }} on_release_branch: ${{ steps.release-context.outputs.on_release_branch }} # Displayed in the approval summary so reviewers can identify the selected SHA. commit_message: ${{ steps.release-context.outputs.commit_message }} @@ -113,21 +91,56 @@ jobs: fi - name: Read release context id: release-context + env: + PRERELEASE: ${{ inputs.prerelease }} run: | set -euo pipefail - containing_branches="$( - git branch -r --contains HEAD --format='%(refname:short)' | - sed '/^origin\/HEAD$/d; s|^origin/||' - )" - branch="${containing_branches%%$'\n'*}" - branch="${branch:-unknown}" + branch="$SOURCE_BRANCH" on_release_branch=false - case "$branch" in - main | prepare-release/*) on_release_branch=true ;; - esac + if [[ "$PRERELEASE" == true ]]; then + branch="$(git branch -r --contains HEAD --format='%(refname:short)' | sed '/^origin\/HEAD$/d; s|^origin/||' | sed -n '1p')" + branch="${branch:-unknown}" + else + git check-ref-format "refs/heads/$branch" + source_ref="refs/remotes/origin/$branch" + if ! git merge-base --is-ancestor HEAD "$source_ref"; then + # Before the PR merges, its version commit is one commit ahead of the source. + parent="$(git rev-parse --short=12 HEAD^)" + prepared_ref="refs/remotes/origin/prepare-release/$branch-$parent" + if [[ "$branch" == main ]] && ! git show-ref --verify --quiet "$prepared_ref"; then + prepared_ref="refs/remotes/origin/prepare-release/$parent" + fi + if ! git merge-base --is-ancestor HEAD^ "$source_ref" || + [[ "$(git rev-parse --verify "$prepared_ref" || true)" != "$(git rev-parse HEAD)" ]]; then + echo "Release SHA does not belong to $branch or its prepare release PR." >&2 + exit 1 + fi + fi + if [[ "$branch" =~ ^v([0-9]+)$ ]]; then + major="${BASH_REMATCH[1]}" + version="$(jq -er .version js/package.json)" + if [[ "${version%%.*}" != "$major" ]]; then + echo "SDK version $version does not match maintenance branch $branch." >&2 + exit 1 + fi + fi + fi + if [[ "$branch" == main || "$branch" =~ ^v[0-9]+$ || "$branch" == prepare-release/* ]]; then + on_release_branch=true + fi + previous_version="$(git show HEAD^:js/package.json 2>/dev/null | jq -er .version || true)" + previous="braintrust@$previous_version" + if git show-ref --verify --quiet "refs/tags/$previous"; then + echo "SDK changes: $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/compare/$previous..$(git rev-parse HEAD)" >> "$GITHUB_STEP_SUMMARY" + fi + github_latest=false + if [[ "$PRERELEASE" == false && "$branch" == main ]]; then + github_latest=true + fi { + echo "github_latest=$github_latest" echo "branch=$branch" echo "on_release_branch=$on_release_branch" echo "commit_message=$(git log -1 --format='%s' HEAD)" @@ -154,6 +167,14 @@ jobs: - name: Detect publish work id: detect run: node scripts/release/release-manifest.mjs --mode ${{ inputs.prerelease && 'prerelease --status-file .changeset-status.json' || 'stable' }} --output .release-manifest.json + - name: Set npm channel for approval and publication + id: manifest + run: | + # Use the workflow revision for channel selection, including when releasing an older SDK. + git show "$GITHUB_SHA:scripts/release/set-npm-channels.mjs" > "$RUNNER_TEMP/set-npm-channels.mjs" + node "$RUNNER_TEMP/set-npm-channels.mjs" .release-manifest.json ${{ inputs.prerelease && 'prerelease' || 'stable' }} + jq -r '.packages[] | "- \(.name)@\(.version) → \(.channel)"' .release-manifest.json >> "$GITHUB_STEP_SUMMARY" + echo "json=$(jq -c . .release-manifest.json)" >> "$GITHUB_OUTPUT" - name: Build packages if: steps.detect.outputs.needs_artifacts == 'true' run: pnpm run build @@ -240,17 +261,49 @@ jobs: id-token: write pull-requests: read attestations: read + concurrency: + group: npm-publish-${{ inputs.prerelease && 'rc' || 'stable' }} + queue: max environment: npm-publish steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - ref: ${{ needs.build-package-artifacts.outputs.release_sha }} + ref: ${{ github.sha }} - name: Download release package artifacts uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: name: release-packages path: release-artifacts + - name: Verify approved release manifest + env: + RELEASE_SHA: ${{ needs.build-package-artifacts.outputs.release_sha }} + APPROVED_MANIFEST: ${{ needs.build-package-artifacts.outputs.manifest_json }} + run: | + manifest="$(jq -c . release-artifacts/release-manifest.json)" + if [[ "$manifest" != "$APPROVED_MANIFEST" ]]; then + echo "The downloaded manifest differs from the approved release manifest." >&2 + exit 1 + fi + if [[ "$(jq -r .commit <<< "$manifest")" != "$RELEASE_SHA" ]]; then + echo "The manifest commit differs from the requested release SHA." >&2 + exit 1 + fi + git fetch --no-tags origin "$RELEASE_SHA" + - name: Check release tags before publication + env: + RELEASE_SHA: ${{ needs.build-package-artifacts.outputs.release_sha }} + run: | + while IFS= read -r tag; do + git check-ref-format "refs/tags/$tag" + if git show-ref --verify --quiet "refs/tags/$tag" && + [[ "$(git rev-list -n 1 "refs/tags/$tag")" != "$RELEASE_SHA" ]]; then + echo "Release tag $tag already exists on another commit." >&2 + exit 1 + fi + done < <(jq -r '.packages[].tag' release-artifacts/release-manifest.json) + - name: Verify approved npm tags and tarballs + run: node scripts/release/set-npm-channels.mjs release-artifacts/release-manifest.json ${{ inputs.prerelease && 'prerelease' || 'stable' }} --check - name: Publish package tarballs uses: braintrustdata/sdk-actions/actions/release/lang/js/publish-npm-tarballs@337c5475631d724441403f5a4d8ad0b32ce12e29 with: @@ -260,76 +313,31 @@ jobs: slack_token: ${{ secrets.SLACK_BOT_TOKEN }} slack_channel: C0ABHT0SWA2 - name: Push Changesets release tags + env: + RELEASE_SHA: ${{ needs.build-package-artifacts.outputs.release_sha }} run: | - set -euo pipefail - - git config user.name "github-actions[bot]" - git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - - manifest="release-artifacts/release-manifest.json" - target_commit="$(jq -r '.commit // empty' "$manifest")" - mapfile -t tags < <( - jq -r '.packages[]? | .tag // "\(.name)@\(.version)"' "$manifest" - ) - - if [ "${#tags[@]}" -eq 0 ]; then - echo "No release tags to push." - exit 0 - fi - - if [ -z "$target_commit" ]; then - echo "Release manifest is missing commit." >&2 - exit 1 - fi - - to_push=() - for tag in "${tags[@]}"; do - remote_ref="$(git ls-remote --tags origin "refs/tags/$tag" | head -n 1 || true)" - if [ -n "$remote_ref" ]; then - remote_target="$(printf '%s\n' "$remote_ref" | awk '{print $1}')" - if [ "$remote_target" != "$target_commit" ]; then - echo "Remote tag $tag already exists on $remote_target, expected $target_commit." >&2 - exit 1 - fi - continue - fi - - if git rev-parse -q --verify "refs/tags/$tag" >/dev/null 2>&1; then - local_target="$(git rev-list -n 1 "$tag")" - if [ "$local_target" != "$target_commit" ]; then - echo "Local tag $tag already exists on $local_target, expected $target_commit." >&2 - exit 1 - fi - else - git tag "$tag" "$target_commit" - fi - - to_push+=("refs/tags/$tag") - done - - if [ "${#to_push[@]}" -eq 0 ]; then - echo "All release tags already exist on origin." - exit 0 - fi - # Repository rules limit each push to five branches or tags. - for ref in "${to_push[@]}"; do - git push origin "$ref" - done + while IFS= read -r tag; do + if ! git show-ref --verify --quiet "refs/tags/$tag"; then + git push origin "$RELEASE_SHA:refs/tags/$tag" + fi + done < <(jq -r '.packages[].tag' release-artifacts/release-manifest.json) - name: Create GitHub Releases - if: ${{ !inputs.prerelease }} + if: needs.build-package-artifacts.outputs.github_latest == 'true' uses: braintrustdata/sdk-actions/actions/release/create-package-github-releases@337c5475631d724441403f5a4d8ad0b32ce12e29 with: manifest: release-artifacts/release-manifest.json repo: ${{ github.repository }} - - name: Create GitHub prereleases - # The pinned sdk-actions release action does not support prereleases. - if: inputs.prerelease + - name: Create GitHub releases outside latest + if: needs.build-package-artifacts.outputs.github_latest == 'false' env: + PRERELEASE: ${{ inputs.prerelease }} GH_TOKEN: ${{ github.token }} run: | set -euo pipefail + flags=(--latest=false) + if [[ "$PRERELEASE" == true ]]; then flags+=(--prerelease); fi notes_file="$(mktemp)" trap 'rm -f "$notes_file"' EXIT while IFS= read -r encoded; do @@ -347,8 +355,7 @@ jobs: --title "$title" \ --notes-file "$notes_file" \ --verify-tag \ - --prerelease \ - --latest=false + "${flags[@]}" done < <(jq -r '.packages[] | @base64' release-artifacts/release-manifest.json) - name: Ensure GitHub release SBOM assets env: @@ -388,7 +395,6 @@ jobs: notify-failure: needs: - validate-release-sha - - print-changelog-links - build-package-artifacts - attest-package-sboms - request-approval @@ -397,7 +403,6 @@ jobs: always() && ( needs.validate-release-sha.result == 'failure' || - needs.print-changelog-links.result == 'failure' || needs.build-package-artifacts.result == 'failure' || needs.attest-package-sboms.result == 'failure' || needs.request-approval.result == 'failure' || diff --git a/PUBLISHING.md b/PUBLISHING.md index 8cfa9c28b..8050a216c 100644 --- a/PUBLISHING.md +++ b/PUBLISHING.md @@ -5,11 +5,11 @@ All package publishing happens in GitHub Actions. Do not publish from your local ## Short Version - If your PR changes a publishable package, add a `.changeset/*.md` file to it. -- Merge the PR into `main`. +- Merge the PR into the branch you want to release. - For a stable release: - - Run **Prepare Release** on `main`. + - Run **Prepare Release** from `main`. For a maintenance release, set `source_branch` (for example, `v3`). - Review the generated prepare release PR. - - Run **Publish Release** with the `release_sha` shown in the prepare workflow summary and leave `prerelease` unchecked. + - Run **Publish Release** with the `source_branch` and `release_sha` shown in the prepare workflow summary and leave `prerelease` unchecked. - Approve the `npm-publish` environment. - The publish workflow builds, packs, and attests the packages _before_ the gate, then (after approval) publishes from the exact commit SHA, creates tags and GitHub Releases for that commit, and comments on issues closed by released PRs. - Merge the prepare release PR after publishing succeeds. @@ -29,39 +29,50 @@ If no release is intended, bypass the check with either: - the `skip-changeset` PR label - `#skip-changeset` in the PR title or body -## Stable Release (`latest`) +## Stable Release This is the normal production release flow. -1. Merge feature PRs into `main`. -2. Run **Prepare Release** from `main`. +1. Merge the changes into the source branch. +2. Run **Prepare Release** from `main`. Set `source_branch` to the branch you want to release. If you leave it empty, the workflow uses the branch selected in the Actions branch picker (normally `main`). 3. That workflow: - validates publishable package metadata - runs `changeset version` - - creates a branch named `prepare-release/{short-main-sha}` - - opens a prepare release PR from that branch into `main` + - creates a branch named `prepare-release/{source-branch}-{short-source-sha}` + - opens a prepare release PR from that branch into the source branch - writes the `release_sha` to the workflow summary 4. Review the prepare release PR to confirm the package versions, changelogs, and consumed changeset deletions look right. -5. Run **Publish Release** with: +5. Run **Publish Release** from the same workflow branch with: - `release_sha=` + - the same `source_branch` as in the prepare workflow summary - `prerelease=false` (the default) 6. Approve the `npm-publish` environment when GitHub asks. 7. Merge the prepare release PR after publishing succeeds. -The stable publish workflow checks out `release_sha` exactly. It accepts any full commit SHA with a parent, does not resolve the prepare release PR, and does not publish from the current tip of `main`. +The stable publish workflow checks out `release_sha` exactly. It checks that the commit belongs to the source branch or is the version commit on its prepare release branch. The workflow runs in stages, and the `npm-publish` approval gate sits _after_ the build so nothing is published until a reviewer approves: -1. **Build & pack (before the gate).** Detects packages whose versions changed between the release commit and its first parent, builds them, packs the tarballs, generates an SBOM per package, and attests build provenance for the tarballs. If no package versions changed, there is no work to approve. +1. **Build & pack (before the gate).** Checks the package versions at the release commit against npm and the Git release tags, builds them, packs the tarballs, generates an SBOM per package, and attests build provenance for the tarballs. If the manifest is empty, approval is skipped. 2. **Attest SBOMs.** Produces a signed attestation for each package's SBOM. 3. **Request approval.** Posts the release (SHA + package list) for review and waits on the `npm-publish` environment gate. -4. **Publish (after approval).** Publishes the prebuilt tarballs to the npm `latest` dist-tag (skipping versions already on npm), pushes Changesets-style release tags for the release commit, creates GitHub Releases with the SBOM assets attached, and comments on issues closed by PRs included in the release. +4. **Publish (after approval).** Publishes the prebuilt tarballs to the npm dist-tag shown in the approval request (skipping versions already on npm), pushes Changesets-style release tags for the release commit, creates GitHub Releases with the SBOM assets attached, and comments on issues closed by PRs included in the release. The build/attest, approval, publish, and GitHub-release steps run through the shared release actions in [`braintrustdata/sdk-actions`](https://github.com/braintrustdata/sdk-actions) (pinned by commit SHA). If publishing succeeds but the prepare release PR cannot be merged cleanly afterward, the release is still published. Repair or recreate the prepare release PR manually afterward. -Stable releases publish to the npm `latest` dist-tag. +Each stable package gets its own npm dist-tag, regardless of the source branch. +If npm’s `latest` tag points to a higher major, the package publishes to `latest-`. +A first release, a release on the current major, or a new major publishes to `latest`. + +For example, if `braintrust@latest` is 4.x and `@braintrust/otel@latest` is 1.x, the same release can publish `braintrust@3.45.0` to `latest-3` and `@braintrust/otel@1.2.0` to `latest`. +The approval manifest records each tag. +The workflow stops if the selected npm tag already points to a newer version. +If a new major changes a tag choice while approval is pending, start a new run to approve the updated tags. + +Only stable releases from `main` are eligible for GitHub’s Latest release. +Each package version must still be unique across branches because npm dist-tags share the same package versions. ## Prerelease (`rc`) @@ -88,7 +99,7 @@ Prereleases: ## Notes -- **Prepare Release** must be run from `main`. +- For an older branch such as `v3`, run both workflows from `main` and enter `v3` for `source_branch`. This uses the workflows on `main` and the package code on `v3`. - Both release types use `publish-stable-release.yaml`, the workflow configured for npm trusted publishing. - Publishing must use a full 40-character commit SHA, not a PR number. In the normal prepare release flow, use the `release_sha` from the **Prepare Release** summary. - The old `release` branch and backsync workflow are no longer part of the release process. diff --git a/scripts/release/set-npm-channels.mjs b/scripts/release/set-npm-channels.mjs new file mode 100644 index 000000000..f7db863c9 --- /dev/null +++ b/scripts/release/set-npm-channels.mjs @@ -0,0 +1,100 @@ +import { createHash } from "node:crypto"; +import { readFileSync, writeFileSync } from "node:fs"; +import { basename, dirname, join } from "node:path"; + +const [path, requestedMode, option] = process.argv.slice(2); +const manifest = JSON.parse(readFileSync(path, "utf8")); + +if (requestedMode !== "stable" && requestedMode !== "prerelease") { + throw new Error(`Unknown requested release mode: ${requestedMode}`); +} +if (manifest.mode !== requestedMode) { + throw new Error( + `Requested a ${requestedMode} release, but the manifest specifies ${manifest.mode}.`, + ); +} + +for (const pkg of manifest.packages) { + let channel = "rc"; + if (requestedMode === "stable") { + const response = await fetch( + `https://registry.npmjs.org/-/package/${encodeURIComponent(pkg.name)}/dist-tags`, + ); + if (!response.ok && response.status !== 404) { + throw new Error( + `Cannot read npm tags for ${pkg.name}: ${response.status}`, + ); + } + + const tags = response.ok ? await response.json() : {}; + const version = stableVersion(pkg.version); + const major = Number(version.split(".")[0]); + const latest = tags.latest && stableVersion(tags.latest); + channel = + latest && Number(latest.split(".")[0]) > major + ? `latest-${major}` + : "latest"; + + const current = tags[channel]; + if ( + current && + stableVersion(current).localeCompare(version, "en", { numeric: true }) > 0 + ) { + throw new Error( + `Cannot publish ${pkg.name}@${pkg.version} to ${channel}: the tag already points to ${current}.`, + ); + } + } else if ( + !/^\d+\.\d+\.\d+-rc\.[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*$/.test(pkg.version) + ) { + throw new Error( + `Expected an RC snapshot for ${pkg.name}, received ${pkg.version}`, + ); + } + + if (option === "--check") { + if (pkg.channel !== channel || pkg.registries.npm.channel !== channel) { + throw new Error( + `The approved npm tag for ${pkg.name}@${pkg.version} was ${pkg.channel}. It now needs ${channel}. Start a new release run for approval.`, + ); + } + + const response = await fetch( + `https://registry.npmjs.org/${encodeURIComponent(pkg.name)}/${encodeURIComponent(pkg.version)}`, + ); + if (response.status === 404) continue; + if (!response.ok) { + throw new Error( + `Cannot read npm version ${pkg.name}@${pkg.version}: ${response.status}`, + ); + } + + if (basename(pkg.tarball_asset) !== pkg.tarball_asset) { + throw new Error(`Invalid tarball filename: ${pkg.tarball_asset}`); + } + const tarball = readFileSync(join(dirname(path), pkg.tarball_asset)); + const integrity = createHash("sha512").update(tarball).digest("base64"); + const { dist } = await response.json(); + if (dist.integrity !== `sha512-${integrity}`) { + throw new Error( + `${pkg.name}@${pkg.version} is already published with a different tarball.`, + ); + } + } else { + pkg.label = `${pkg.name} (npm tag ${channel})`; + pkg.channel = channel; + pkg.registries.npm.channel = channel; + } +} + +if (option !== "--check") { + writeFileSync(path, `${JSON.stringify(manifest, null, 2)}\n`); +} + +function stableVersion(version) { + const match = /^(\d+\.\d+\.\d+)(?:\+[\w.-]+)?$/.exec(version); + if (!match) { + throw new Error(`Expected a stable npm version, received ${version}`); + } + return match[1]; +}