diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ecb779b80ff..3fc042c1cbe 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -335,6 +335,28 @@ jobs: ) ) }} + # Set when the push-time guard decisively refuses because the version + # already shipped; notify_failure keeps this benign refusal out of the + # release-failed issue and autofix dispatch. + outputs: + version_refusal: '${{ steps.push_release_branch.outputs.version_refusal }}' + # Serialize publish per release tag: the pre-push re-validation in the + # push step is only sound while at most one run pushes and publishes a + # given version at a time, and --force removed the non-fast-forward + # rejection that used to serialize the push itself. In-progress runs are + # never cancelled; of queued same-tag runs only the latest survives, but + # whichever run reaches the push re-validates first, so the invariant + # holds. is_dry_run is part of the key because a dry run ships nothing + # (no push, tag, or release) and must not queue ahead of — or delay — + # the real release for the same tag. timeout-minutes bounds the hold + # a wedged publish (a stalled npm publish or release-asset upload) + # keeps on the group: without it the GitHub default of 360 minutes + # leaves same-tag retries queued behind it, unable to run, fail, or + # notify; a healthy publish completes well inside 90 minutes. + concurrency: + group: 'release-publish-${{ needs.prepare.outputs.release_tag }}-${{ needs.prepare.outputs.is_dry_run }}' + cancel-in-progress: false + timeout-minutes: 90 environment: name: 'production-release' url: '${{ github.server_url }}/${{ github.repository }}/releases/tag/${{ needs.prepare.outputs.release_tag }}' @@ -393,10 +415,13 @@ jobs: npm run release:version "${RELEASE_VERSION}" - name: 'Commit and Conditionally Push package versions' + id: 'push_release_branch' env: BRANCH_NAME: '${{ steps.release_branch.outputs.BRANCH_NAME }}' + GITHUB_TOKEN: '${{ github.token }}' IS_DRY_RUN: '${{ needs.prepare.outputs.is_dry_run }}' RELEASE_TAG: '${{ needs.prepare.outputs.release_tag }}' + RELEASE_VERSION: '${{ needs.prepare.outputs.release_version }}' run: |- git add package.json package-lock.json packages/*/package.json packages/channels/*/package.json integrations/external-context/package.json if git diff --staged --quiet; then @@ -405,8 +430,59 @@ jobs: git commit -m "chore(release): ${RELEASE_TAG}" fi if [[ "${IS_DRY_RUN}" == "false" ]]; then + # The guard runs scripts/get-release-version.js from the + # checked-out ref — the operator-controlled dispatch input `ref` + # — not the branch this workflow file came from. A ref predating + # this PR has an entry point that ignores --assert-unreleased, + # prints version JSON, and exits 0 (probed against the merge + # base), which would read as "unreleased verified" while the + # guard never ran. Refuse the force push unless the checked-out + # script carries the guard. + if ! grep -q "assert-unreleased" scripts/get-release-version.js; then + echo "::error::Checked-out ref predates the push-time guard; refusing force push." + exit 1 + fi + # Force: a failed earlier attempt may have left this branch on an + # older head, and its divergent bump commit would fail a plain + # retry push as non-fast-forward. Replacing it is safe only while + # nothing for this version has shipped. prepare checked that once, + # but the validation jobs and the production-release approval gate + # separate that check from this push by minutes to hours, so + # re-validate prepare's invariant (doesVersionExist in + # scripts/get-release-version.js) at push time against the live + # registry, origin's tags, and GitHub releases: a concurrent + # same-version run that shipped in between would otherwise have + # its branch tip — and the tag and merge-to-main anchored to it — + # silently replaced. The script owns the published-package list, + # so this guard cannot drift from it. Exit 3 marks the decisive + # "already shipped" refusal, which the version_refusal output + # keeps out of the release-failed notification: such a refusal + # means the release shipped elsewhere (or partially), not that + # it failed. Any other non-zero exit stays a real failure. Exit 2 + # (a probe failure) is retried a bounded number of times so a + # transient registry or network blip cannot fail the release and + # dispatch autofix at infrastructure noise; exit 0 and exit 3 + # stay decisive on the first attempt. + for attempt in 1 2 3; do + GUARD_STATUS=0 + node scripts/get-release-version.js --assert-unreleased="${RELEASE_VERSION}" || GUARD_STATUS=$? + if [[ "${GUARD_STATUS}" -ne 2 ]]; then + break + fi + if [[ "${attempt}" -lt 3 ]]; then + echo "Push-time guard probe failed (exit 2); retrying in $(( attempt * 15 ))s (attempt ${attempt} of 3)..." + sleep $(( attempt * 15 )) + fi + done + if [[ "${GUARD_STATUS}" -eq 3 ]]; then + echo "version_refusal=true" >> "${GITHUB_OUTPUT}" + exit 1 + fi + if [[ "${GUARD_STATUS}" -ne 0 ]]; then + exit "${GUARD_STATUS}" + fi echo "Pushing release branch to remote..." - git push --set-upstream origin "${BRANCH_NAME}" --follow-tags + git push --force --set-upstream origin "${BRANCH_NAME}" --follow-tags else echo "Dry run enabled. Skipping push." fi @@ -649,6 +725,12 @@ jobs: - 'integration_none' - 'integration_docker' - 'publish' + # The push-time guard's decisive "already shipped" refusal + # (version_refusal) is a correct outcome, not a release failure: the + # version shipped via another attempt, or partially, so filing a + # "Release Failed" issue and dispatching autofix would chase a release + # that did not fail. Genuine publish failures — including the guard's + # fail-closed probe errors — still notify. if: |- ${{ always() && @@ -661,7 +743,10 @@ jobs: needs.quality.result == 'failure' || needs.integration_none.result == 'failure' || needs.integration_docker.result == 'failure' || - needs.publish.result == 'failure' + ( + needs.publish.result == 'failure' && + needs.publish.outputs.version_refusal != 'true' + ) ) }} permissions: diff --git a/scripts/get-release-version.js b/scripts/get-release-version.js index 3ed56d26968..f632b5f51a4 100644 --- a/scripts/get-release-version.js +++ b/scripts/get-release-version.js @@ -180,7 +180,7 @@ function detectRollbackAndGetBaseline(npmDistTag) { * All packages that share the same release version. A version is considered * "taken" if it exists on *any* of them — not just the main package. */ -const PUBLISHED_PACKAGES = [ +export const PUBLISHED_PACKAGES = [ '@qwen-code/qwen-code', '@qwen-code/audio-capture', '@qwen-code/channel-base', @@ -193,23 +193,63 @@ const PUBLISHED_PACKAGES = [ '@qwen-code/channel-weixin', ]; -function doesVersionExist(version) { +function doesVersionExist(version, { strict = false, shippedTo } = {}) { // Check NPM across all published packages + const shippedPackages = []; for (const pkg of PUBLISHED_PACKAGES) { try { - const command = `npm view ${pkg}@${version} version 2>/dev/null`; + // The best-effort path silences npm's expected E404 noise; strict + // mode needs that stderr to tell "absent" from a failed probe. + const command = strict + ? `npm view ${pkg}@${version} version` + : `npm view ${pkg}@${version} version 2>/dev/null`; const output = execSync(command).toString().trim(); if (output === version) { - console.error(`Version ${version} already exists on NPM (${pkg}).`); - return true; + if (!strict) { + console.error(`Version ${version} already exists on NPM (${pkg}).`); + return true; + } + shippedPackages.push(pkg); + } + } catch (error) { + // E404 means the version is absent from this package. Strict mode + // guards the force push, so any other probe failure is "cannot + // verify" and must throw instead of passing — but once a package + // has shipped the refusal is decided, and a throw would mask its + // recovery guidance with a probe-failure exit. + if ( + strict && + shippedPackages.length === 0 && + !error.message?.includes('E404') + ) { + throw new Error( + `Failed to verify ${pkg}@${version} on npm: ${error.message}`, + ); } - } catch (_error) { - // This is expected if the version doesn't exist on this package. } } + // Strict mode scans every package instead of stopping at the first hit + // so a partial publish's refusal can name everything that shipped. A hit + // ends the check: the remaining probes can no longer change the outcome, + // and a failed one would mask the refusal's recovery guidance. + if (shippedPackages.length > 0) { + console.error( + `Version ${version} already exists on NPM (${shippedPackages.join(', ')}).`, + ); + shippedTo?.push(...shippedPackages); + return true; + } - // Check Git tags + // Check Git tags. Push-time callers pass strict: the checkout at job + // start can only know tags that existed when the job began, and the + // version may ship between that fetch and this push — check origin. try { + if (strict) { + execSync(`git ls-remote --exit-code origin "refs/tags/v${version}"`); + console.error(`Git tag v${version} already exists on origin.`); + shippedTo?.push(`origin tag v${version}`); + return true; + } const command = `git tag -l 'v${version}'`; const tagOutput = execSync(command).toString().trim(); if (tagOutput === `v${version}`) { @@ -217,7 +257,18 @@ function doesVersionExist(version) { return true; } } catch (error) { - console.error(`Failed to check git tags for conflicts: ${error.message}`); + if (strict) { + // ls-remote exits 2 when no ref matches; that is "tag absent". Any + // other failure means the check could not run — fail the push + // instead of reading a failed check as "unreleased". + if (error.status !== 2) { + throw new Error( + `Failed to verify tag v${version} on origin: ${error.message}`, + ); + } + } else { + console.error(`Failed to check git tags for conflicts: ${error.message}`); + } } // Check GitHub releases @@ -226,10 +277,16 @@ function doesVersionExist(version) { const output = execSync(command).toString().trim(); if (output === `v${version}`) { console.error(`GitHub release v${version} already exists.`); + shippedTo?.push(`GitHub release v${version}`); return true; } } catch (error) { if (!isExpectedMissingGitHubRelease(error)) { + if (strict) { + throw new Error( + `Failed to verify release v${version} on GitHub: ${error.message}`, + ); + } console.error( `Failed to check GitHub releases for conflicts: ${error.message}`, ); @@ -239,6 +296,28 @@ function doesVersionExist(version) { return false; } +/** + * Push-time re-validation of prepare's doesVersionExist invariant, for the + * release branch force push. Throws when the version has shipped anywhere + * (an error coded VERSION_SHIPPED, naming where it was found), or when a + * probe cannot run — a failed probe must not read as "unreleased". + */ +export function assertVersionUnreleased(version) { + if (typeof version !== 'string' || version.length === 0) { + throw new Error( + 'assert-unreleased requires a version, e.g. --assert-unreleased=1.2.3', + ); + } + const shippedTo = []; + if (doesVersionExist(version, { strict: true, shippedTo })) { + const error = new Error( + `Version ${version} has already shipped; refusing to force-push the release branch over it. Found on: ${shippedTo.join(', ')}. If a previous attempt published only part of the release, complete the remaining artifacts manually — re-running this job will keep failing here while the version stays published.`, + ); + error.code = 'VERSION_SHIPPED'; + throw error; + } +} + function getAndVerifyTags(npmDistTag, _gitTagPattern) { // Detect rollback scenarios and get the correct baseline const rollbackInfo = detectRollbackAndGetBaseline(npmDistTag); @@ -508,6 +587,34 @@ export function getVersion(options = {}) { return result; } +/** + * CLI dispatch, exported for tests: `--assert-unreleased=` runs + * the push-time guard; anything else prints the version JSON. Returns the + * exit code. Guard codes: 0 = unreleased, 3 = already shipped (a decisive, + * benign refusal the workflow marks to skip the release-failed + * notification), 2 = probe or usage failure. 1 is never returned on + * purpose: node exits 1 on uncaught errors, and those must stay on the + * real-failure path. + */ +export function runCli(args) { + if (args['assert-unreleased'] !== undefined) { + try { + assertVersionUnreleased(args['assert-unreleased']); + } catch (error) { + // stdout, not stderr: the runner parses workflow commands from + // stdout only, so ::error:: on stderr would never annotate. + console.log(`::error::${error.message}`); + return error.code === 'VERSION_SHIPPED' ? 3 : 2; + } + return 0; + } + console.log(JSON.stringify(getVersion(args), null, 2)); + return 0; +} + if (process.argv[1] === fileURLToPath(import.meta.url)) { - console.log(JSON.stringify(getVersion(getArgs()), null, 2)); + const exitCode = runCli(getArgs()); + if (exitCode !== 0) { + process.exit(exitCode); + } } diff --git a/scripts/tests/get-release-version.test.js b/scripts/tests/get-release-version.test.js index caa7b5ab581..dedec44837e 100644 --- a/scripts/tests/get-release-version.test.js +++ b/scripts/tests/get-release-version.test.js @@ -4,8 +4,13 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { vi, describe, it, expect, beforeEach } from 'vitest'; -import { getVersion } from '../get-release-version.js'; +import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { + assertVersionUnreleased, + getVersion, + PUBLISHED_PACKAGES, + runCli, +} from '../get-release-version.js'; import { execSync } from 'node:child_process'; import { readFileSync } from 'node:fs'; @@ -608,4 +613,276 @@ describe('getVersion', () => { ); }); }); + + it('runCli default dispatch prints the version JSON and exits 0', () => { + // The prepare job consumes this path (VERSION_JSON=$(node + // scripts/get-release-version.js ...)); pin it through runCli, the + // wrapper prepare actually invokes, so a dropped args pass-through or + // a flipped exit code fails here instead of at the next release. The + // override makes the printed version depend on args reaching + // getVersion. + vi.mocked(execSync).mockImplementation(mockExecSync); + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); + expect(runCli({ type: 'stable', stable_version_override: '9.9.9' })).toBe( + 0, + ); + expect(logSpy).toHaveBeenCalledTimes(1); + expect(JSON.parse(logSpy.mock.calls[0][0])).toEqual({ + releaseTag: 'v9.9.9', + releaseVersion: '9.9.9', + npmTag: 'latest', + previousReleaseTag: 'v0.6.1', + }); + }); +}); + +describe('assertVersionUnreleased', () => { + beforeEach(() => { + vi.resetAllMocks(); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + const notFoundAnywhere = (command) => { + if (command.includes('npm view')) throw new Error('npm error code E404'); + if (command.includes('git ls-remote')) { + // --exit-code exits 2 when no ref matches. + throw Object.assign(new Error('no match'), { status: 2 }); + } + if (command.includes('gh release view')) { + throw new Error('release not found'); + } + return ''; + }; + + // The push-time refusal must tell the operator where the version was + // found and that re-running cannot fix a partial publish. + const refusalMessage = (foundOn) => + `Version 1.2.3 has already shipped; refusing to force-push the release branch over it. Found on: ${foundOn}. If a previous attempt published only part of the release, complete the remaining artifacts manually — re-running this job will keep failing here while the version stays published.`; + + it('pins the full published-package set', () => { + // The push-time guard derives from this list; the workflow's publish + // steps hardcode the same set separately, so adding or removing a + // package must update both this pin and the publish steps in + // release.yml so every consumer is reviewed together. + expect(PUBLISHED_PACKAGES).toEqual([ + '@qwen-code/qwen-code', + '@qwen-code/audio-capture', + '@qwen-code/channel-base', + '@qwen-code/channel-dingtalk', + '@qwen-code/channel-feishu', + '@qwen-code/channel-github', + '@qwen-code/channel-qqbot', + '@qwen-code/channel-telegram', + '@qwen-code/channel-wecom', + '@qwen-code/channel-weixin', + ]); + }); + + it('passes when no package, tag, or release has shipped the version', () => { + vi.mocked(execSync).mockImplementation(notFoundAnywhere); + expect(() => assertVersionUnreleased('1.2.3')).not.toThrow(); + }); + + it('checks origin for tags, not the stale local checkout', () => { + const commands = []; + vi.mocked(execSync).mockImplementation((command) => { + commands.push(command); + return notFoundAnywhere(command); + }); + assertVersionUnreleased('1.2.3'); + expect(commands).toContain( + 'git ls-remote --exit-code origin "refs/tags/v1.2.3"', + ); + expect(commands.some((c) => c.includes('git tag -l'))).toBe(false); + }); + + it('refuses when ANY published package has shipped the version', () => { + // Ship the version on one package at a time, middle-list packages + // included: dropping any of them from PUBLISHED_PACKAGES must fail. + for (const pkg of PUBLISHED_PACKAGES) { + vi.mocked(execSync).mockImplementation((command) => { + if (command === `npm view ${pkg}@1.2.3 version`) { + return '1.2.3'; + } + return notFoundAnywhere(command); + }); + expect(() => assertVersionUnreleased('1.2.3')).toThrow(/already shipped/); + } + }); + + it('refuses when the tag already exists on origin', () => { + vi.mocked(execSync).mockImplementation((command) => { + if (command.includes('git ls-remote')) { + return '0123456789abcdef\trefs/tags/v1.2.3'; + } + return notFoundAnywhere(command); + }); + expect(() => assertVersionUnreleased('1.2.3')).toThrow( + refusalMessage('origin tag v1.2.3'), + ); + }); + + it('refuses when the GitHub release already exists', () => { + vi.mocked(execSync).mockImplementation((command) => { + if (command.includes('gh release view')) return 'v1.2.3'; + return notFoundAnywhere(command); + }); + expect(() => assertVersionUnreleased('1.2.3')).toThrow( + refusalMessage('GitHub release v1.2.3'), + ); + }); + + it('names every shipped package after a partial publish', () => { + // A retry of a partially published release is refused forever; the + // refusal must name exactly which packages to complete, which needs + // the strict scan of every package, not a stop at the first hit. + const shipped = [PUBLISHED_PACKAGES[1], PUBLISHED_PACKAGES[7]]; + const commands = []; + vi.mocked(execSync).mockImplementation((command) => { + commands.push(command); + if (shipped.some((pkg) => command === `npm view ${pkg}@1.2.3 version`)) { + return '1.2.3'; + } + return notFoundAnywhere(command); + }); + expect(() => assertVersionUnreleased('1.2.3')).toThrow( + refusalMessage(shipped.join(', ')), + ); + expect(commands.filter((c) => c.startsWith('npm view '))).toHaveLength( + PUBLISHED_PACKAGES.length, + ); + }); + + it('stops probing once the refusal is decided', () => { + // A shipped version already decides the refusal; running the remaining + // probes would let a flaky one replace the refusal's recovery + // guidance with a probe-failure error. + const commands = []; + vi.mocked(execSync).mockImplementation((command) => { + commands.push(command); + if (command === `npm view ${PUBLISHED_PACKAGES[0]}@1.2.3 version`) { + return '1.2.3'; + } + return notFoundAnywhere(command); + }); + expect(() => assertVersionUnreleased('1.2.3')).toThrow(/already shipped/); + expect(commands.some((c) => c.includes('ls-remote'))).toBe(false); + expect(commands.some((c) => c.includes('gh release view'))).toBe(false); + }); + + it('rejects a missing or non-string version instead of failing open', () => { + for (const bad of [undefined, '', true]) { + expect(() => assertVersionUnreleased(bad)).toThrow(/requires a version/); + } + }); + + it('fails closed when an npm probe errors with anything other than E404', () => { + vi.mocked(execSync).mockImplementation((command) => { + if (command.includes('npm view')) { + throw new Error('npm error code ETIMEDOUT'); + } + return notFoundAnywhere(command); + }); + expect(() => assertVersionUnreleased('1.2.3')).toThrow( + /Failed to verify .* on npm/, + ); + }); + + it('keeps the refusal decisive when a probe fails after a shipped hit', () => { + // A partial publish retried during a registry disruption: the scan + // hits on a shipped package, then a later probe errors transiently. + // The refusal is already decided; throwing there would demote the + // exit-3 refusal to a probe-failure exit and lose the version_refusal + // marker the workflow keys on to skip the release-failed notification. + vi.mocked(execSync).mockImplementation((command) => { + if (command === `npm view ${PUBLISHED_PACKAGES[0]}@1.2.3 version`) { + return '1.2.3'; + } + if (command.includes('npm view')) { + throw new Error('npm error code ETIMEDOUT'); + } + return notFoundAnywhere(command); + }); + vi.spyOn(console, 'error').mockImplementation(() => {}); + // The runner parses workflow commands from stdout only; ::error:: on + // stderr would never surface as an annotation in the Actions UI. + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); + expect(runCli({ 'assert-unreleased': '1.2.3' })).toBe(3); + expect(logSpy).toHaveBeenCalledWith( + `::error::${refusalMessage(PUBLISHED_PACKAGES[0])}`, + ); + }); + + it('fails closed when ls-remote errors with anything other than no-match', () => { + vi.mocked(execSync).mockImplementation((command) => { + if (command.includes('git ls-remote')) { + throw Object.assign(new Error('fatal: authentication failed'), { + status: 128, + }); + } + return notFoundAnywhere(command); + }); + expect(() => assertVersionUnreleased('1.2.3')).toThrow( + /Failed to verify tag v1\.2\.3 on origin/, + ); + }); + + it('fails closed when gh release view errors with anything other than not-found', () => { + vi.mocked(execSync).mockImplementation((command) => { + if (command.includes('gh release view')) { + throw new Error('gh: To use GitHub CLI in automation, set GH_TOKEN.'); + } + return notFoundAnywhere(command); + }); + expect(() => assertVersionUnreleased('1.2.3')).toThrow( + /Failed to verify release v1\.2\.3 on GitHub/, + ); + }); + + it('CLI dispatch: exits 3 (benign refusal) when the version has shipped', () => { + // Exit 3 is the marker the release workflow uses to keep this + // decisive, benign refusal out of the release-failed notification. + vi.mocked(execSync).mockImplementation((command) => { + if (command.includes('npm view')) return '1.2.3'; + return notFoundAnywhere(command); + }); + vi.spyOn(console, 'error').mockImplementation(() => {}); + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); + expect(runCli({ 'assert-unreleased': '1.2.3' })).toBe(3); + expect(logSpy).toHaveBeenCalledWith( + `::error::${refusalMessage(PUBLISHED_PACKAGES.join(', '))}`, + ); + }); + + it('CLI dispatch: exits 2 (not the refusal marker) when a probe fails', () => { + vi.mocked(execSync).mockImplementation((command) => { + if (command.includes('npm view')) { + throw new Error('npm error code ETIMEDOUT'); + } + return notFoundAnywhere(command); + }); + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); + expect(runCli({ 'assert-unreleased': '1.2.3' })).toBe(2); + expect(logSpy).toHaveBeenCalledWith( + expect.stringContaining('::error::Failed to verify'), + ); + }); + + it('CLI dispatch: exits 2 (not the refusal marker) on a missing version', () => { + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); + expect(runCli({ 'assert-unreleased': '' })).toBe(2); + expect(logSpy).toHaveBeenCalledWith( + '::error::assert-unreleased requires a version, e.g. --assert-unreleased=1.2.3', + ); + }); + + it('CLI dispatch: exits 0 when the version has not shipped', () => { + vi.mocked(execSync).mockImplementation(notFoundAnywhere); + const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {}); + expect(runCli({ 'assert-unreleased': '1.2.3' })).toBe(0); + expect(logSpy).not.toHaveBeenCalled(); + }); }); diff --git a/scripts/tests/release-workflow.test.js b/scripts/tests/release-workflow.test.js index 0babddb4056..c48a45e38d9 100644 --- a/scripts/tests/release-workflow.test.js +++ b/scripts/tests/release-workflow.test.js @@ -4,7 +4,10 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { readFileSync } from 'node:fs'; +import { spawnSync } from 'node:child_process'; +import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import { describe, expect, it } from 'vitest'; const workflow = readFileSync('.github/workflows/release.yml', 'utf8'); @@ -60,6 +63,147 @@ describe('release workflow', () => { ); }); + it('force-pushes the release branch so a retry replaces a failed attempt', () => { + // A failed attempt leaves release/ on an older head, and the + // retry's divergent bump commit makes a plain push fail as + // non-fast-forward, blocking every retry of the release. Force is safe + // only while nothing for this version has shipped, so the push is + // pinned INSIDE the dry-run guard: the dry-run contract (release.yml's + // dispatch input) promises no branch is created, and no other test + // pins this guard — a force push outside it would turn a dry run into + // a destructive overwrite of the remote branch. + expect(workflow).toMatch( + /if \[\[ "\$\{IS_DRY_RUN\}" == "false" \]\]; then[\s\S]*?git push --force --set-upstream origin "\$\{BRANCH_NAME\}" --follow-tags\n {10}else\n {12}echo "Dry run enabled\. Skipping push\."/, + ); + }); + + it('serializes publish jobs per release tag', () => { + // The pre-push re-validation below is only sound while at most one + // publish job pushes and publishes a given version at a time; --force + // removed the non-fast-forward rejection that used to serialize the + // push itself. The group must sit on the publish job — in-progress + // runs are never cancelled, and of queued same-tag runs only the + // latest survives, but whichever run reaches the push re-validates + // first — and it must be keyed by the computed tag, which only exists + // as a prepare output, plus is_dry_run, so a dry run (which ships + // nothing) never queues ahead of the real release for the same tag. + // timeout-minutes bounds the hold a wedged publish (a stalled npm + // publish or asset upload) keeps on the group: without it the GitHub + // default of 360 minutes leaves same-tag retries queued behind it, + // unable to run, fail, or notify. + expect(workflow).toMatch( + / {2}publish:\n {4}name: 'Publish Release'[\s\S]*?concurrency:\n {6}group: 'release-publish-\$\{\{ needs\.prepare\.outputs\.release_tag \}\}-\$\{\{ needs\.prepare\.outputs\.is_dry_run \}\}'\n {6}cancel-in-progress: false\n {4}timeout-minutes: 90\n {4}environment:\n {6}name: 'production-release'/, + ); + }); + + it('refuses the force push when the checked-out ref predates the guard', () => { + // The guard runs scripts/get-release-version.js from the checked-out + // ref — the operator-controlled dispatch input `ref` — and a pre-PR + // ref's entry point ignores --assert-unreleased, prints version JSON, + // and exits 0 (probed against the merge base), so GUARD_STATUS=0 + // would read as "unreleased verified" while the guard never ran. Pin + // the capability check that fails closed instead: inside the dry-run + // guard, ahead of the guard invocation, refusing with a plain + // failure so the run notifies instead of force-pushing unverified. + expect(workflow).toMatch( + /if \[\[ "\$\{IS_DRY_RUN\}" == "false" \]\]; then[\s\S]*?if ! grep -q "assert-unreleased" scripts\/get-release-version\.js; then\n {14}echo "::error::Checked-out ref predates the push-time guard; refusing force push\."\n {14}exit 1\n {12}fi[\s\S]*?for attempt in 1 2 3; do\n {14}GUARD_STATUS=0\n {14}node scripts\/get-release-version\.js --assert-unreleased="\$\{RELEASE_VERSION\}" \|\| GUARD_STATUS=\$\?/, + ); + }); + + it('re-validates that the version is still unshipped right before force-pushing', () => { + // prepare computed and validated the version minutes to hours before + // this push (the validation jobs and the production-release approval + // gate sit in between). A concurrent same-version run can ship in that + // window; the force push would then replace the branch tip that the + // shipped npm packages, tag, and merge to main anchor to. Pin the + // re-validation of prepare's invariant directly before the push, and + // pinned to the script that owns the published-package list so the + // guard cannot silently drift from it: the call must sit inside the + // dry-run guard, before the push, as an anchored full line (moving it + // out of the guard, inverting it, or narrowing it fails), and the + // step must receive RELEASE_VERSION — without it the check aborts + // every release — and GITHUB_TOKEN, which its gh release view probe + // needs: without a token the probe errors, and the guard fails closed + // on probe errors, so every push would abort. The script-side checks + // (every published package, the remote tag, the release, aborting on + // a hit, failing closed on a probe error) are unit-tested in + // get-release-version.test.js. The `|| GUARD_STATUS=$?` suffix is + // pinned too: notify_failure's refusal gate reads the guard's exit + // code through it, and the retry loop is pinned around the call: + // GUARD_STATUS is reset each attempt and only exit 2 (a probe + // failure) retries — exit 0 and exit 3 stay decisive on the first + // attempt. + expect(workflow).toMatch( + /name: 'Commit and Conditionally Push package versions'\n {8}id: 'push_release_branch'\n {8}env:\n[\s\S]*?GITHUB_TOKEN: '\$\{\{ github\.token \}\}'[\s\S]*?RELEASE_VERSION: '\$\{\{ needs\.prepare\.outputs\.release_version \}\}'[\s\S]*?if \[\[ "\$\{IS_DRY_RUN\}" == "false" \]\]; then\n[\s\S]*?for attempt in 1 2 3; do\n {14}GUARD_STATUS=0\n {14}node scripts\/get-release-version\.js --assert-unreleased="\$\{RELEASE_VERSION\}" \|\| GUARD_STATUS=\$\?\n[\s\S]*?git push --force --set-upstream origin "\$\{BRANCH_NAME\}" --follow-tags/, + ); + }); + + it('keeps a decisive version refusal out of the release-failed notification', () => { + // The guard's exit 3 means the version already shipped (fully or + // partially) — a correct refusal, not a release failure. The step + // must turn exactly that exit into the version_refusal marker, the + // publish job must export the marker, and notify_failure must skip + // its "Release Failed" issue + autofix dispatch for it — while any + // other guard exit (a fail-closed probe error) and every later + // publish failure still notify — including through the propagation + // branch pinned verbatim below: without it a probe failure falls + // through to the force push unverified. + expect(workflow).toMatch( + /node scripts\/get-release-version\.js --assert-unreleased="\$\{RELEASE_VERSION\}" \|\| GUARD_STATUS=\$\?[\s\S]*?if \[\[ "\$\{GUARD_STATUS\}" -eq 3 \]\]; then\n {14}echo "version_refusal=true" >> "\$\{GITHUB_OUTPUT\}"\n {14}exit 1\n {12}fi\n {12}if \[\[ "\$\{GUARD_STATUS\}" -ne 0 \]\]; then\n {14}exit "\$\{GUARD_STATUS\}"\n {12}fi/, + ); + expect(workflow).toContain( + "version_refusal: '${{ steps.push_release_branch.outputs.version_refusal }}'", + ); + expect(workflow).toMatch( + /needs\.publish\.result == 'failure' &&\n {12}needs\.publish\.outputs\.version_refusal != 'true'/, + ); + }); + + it('wires the guard exit code to the process exit status end to end', () => { + // The workflow reads the guard's decision from the process exit + // status. Run the real entry point without mocks — a usage error + // needs no network — so an inverted or dropped process.exit fails + // here instead of letting a refusal exit 0 at push time. + const result = spawnSync( + process.execPath, + ['scripts/get-release-version.js', '--assert-unreleased='], + { encoding: 'utf8' }, + ); + expect(result.status).toBe(2); + expect(result.stdout).toContain( + '::error::assert-unreleased requires a version', + ); + }); + + it.skipIf(process.platform === 'win32')( + 'exits 3 from the real entry point when the version already shipped', + () => { + // The workflow reads the refusal through the entry-point exit-status + // glue, not through runCli(); the usage-error test above never + // exercises exit 3. A stub npm on PATH that echoes the probed + // version makes the strict npm scan report "shipped" without + // network, so an entry point that swallowed exit 3 fails here + // instead of reading as GUARD_STATUS=0 at push time. The stub is a + // '#!/bin/sh' script prepended to PATH with ':' — unresolvable on + // Windows, so win32 skips it and Linux CI remains the authoritative + // coverage. + const stubDir = mkdtempSync(join(tmpdir(), 'npm-stub-')); + writeFileSync(join(stubDir, 'npm'), '#!/bin/sh\necho "${2##*@}"\n', { + mode: 0o755, + }); + const result = spawnSync( + process.execPath, + ['scripts/get-release-version.js', '--assert-unreleased=1.2.3'], + { + encoding: 'utf8', + env: { ...process.env, PATH: `${stubDir}:${process.env.PATH}` }, + }, + ); + expect(result.status).toBe(3); + expect(result.stdout).toContain('has already shipped'); + }, + ); + it('keeps a dispatch failure from failing an already-published release', () => { // The packages are published before this step runs, so it must not fail // the release; but the failure must still surface (as an error, not a