Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

ci: bind releases to marked branches (#6860)

Cindy Zhang9711e3d4483c
diff --git a/.github/scripts/ci-docsite-browser.test.mjs b/.github/scripts/ci-docsite-browser.test.mjs
index 8e5b283d88..2584d7b79b 100644
--- a/.github/scripts/ci-docsite-browser.test.mjs
+++ b/.github/scripts/ci-docsite-browser.test.mjs
@@ -28,7 +28,7 @@ describe('docsite browser required-check projection', () => {
it('joins the existing required context and uses the same surface route', () => {
expect(owner.needs).toEqual(['check-scope', 'docsite-browser']);
expect(owner.if).toBe(
- "${{ github.event_name != 'workflow_dispatch' && always() && !cancelled() }}",
+ "${{ github.event_name != 'workflow_dispatch' && needs.check-scope.outputs.release_bump != 'true' && always() && !cancelled() }}",
);
expect(browser.needs).toEqual(['check-scope']);
expect(browser.if).toBe(
diff --git a/.github/scripts/release-check-workflow.test.mjs b/.github/scripts/release-check-workflow.test.mjs
index 81dbc7ae04..7b1031d1d9 100644
--- a/.github/scripts/release-check-workflow.test.mjs
+++ b/.github/scripts/release-check-workflow.test.mjs
@@ -1,7 +1,7 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file Exact-main release dispatch contracts.
+ * @file Exact-release-branch dispatch contracts.
* @input CI workflow and independent event, dependency, scope, and API fixtures
* @output Fail-closed release routing and unchanged maintenance/PR assertions
* @position Node contracts for AST-030 FR12 and DEC-5
@@ -96,9 +96,17 @@ function shell(script, env = {}, prefix = '') {
}
const sha = 'a'.repeat(40);
+const releaseBranch = 'release/v0.6.5';
+const planDigest = 'b'.repeat(64);
async function githubScript(
script,
- {ref = 'refs/heads/main', mainSha = sha, needs, apiFails = false} = {},
+ {
+ ref = `refs/heads/${releaseBranch}`,
+ remoteSha = sha,
+ expectedHead = sha,
+ needs,
+ apiFails = false,
+ } = {},
) {
const summary = {
addHeading() {
@@ -122,15 +130,22 @@ async function githubScript(
rest: {
git: {
async getRef(request) {
- expect(request.ref).toBe('heads/main');
+ expect(request.ref).toBe(`heads/${releaseBranch}`);
if (apiFails) throw new Error('API unavailable');
- return {data: {object: {sha: mainSha}}};
+ return {data: {object: {sha: remoteSha}}};
},
},
},
},
{summary},
- {env: {RELEASE_NEEDS: JSON.stringify(needs)}},
+ {
+ env: {
+ RELEASE_NEEDS: JSON.stringify(needs),
+ RELEASE_BRANCH: releaseBranch,
+ EXPECTED_HEAD: expectedHead,
+ PLAN_DIGEST: planDigest,
+ },
+ },
);
}
@@ -217,23 +232,17 @@ describe('explicit release routing', () => {
});
});
-describe('exact current main request and completion', () => {
- const request = step('check-scope', 'Require exact current main for release')
- .with.script;
+describe('exact release branch completion', () => {
const join = step(
'release-check',
- 'Require complete exact-main release checks',
+ 'Require complete exact-head release branch checks',
).with.script;
const complete = Object.fromEntries(
jobs['release-check'].needs.map(name => [name, {result: 'success'}]),
);
- it('checks main before checkout and accepts only complete exact-main evidence', async () => {
- expect(jobs['check-scope'].steps[0].with.script).toBe(request);
- await expect(githubScript(request)).resolves.toBeUndefined();
- await expect(
- githubScript(join, {needs: complete}),
- ).resolves.toBeUndefined();
+ it('accepts only complete exact-branch evidence', async () => {
+ await expect(githubScript(join, {needs: complete})).resolves.toBeUndefined();
expect(jobs['release-check'].needs).toEqual([
'check-scope',
'check-components',
@@ -244,34 +253,34 @@ describe('exact current main request and completion', () => {
]);
});
- it.each(['refs/heads/feature', 'refs/tags/main', ''])(
- 'rejects ref %s at request and completion',
+ it.each(['refs/heads/main', 'refs/tags/v0.6.5', ''])(
+ 'rejects ref %s',
async ref => {
- for (const script of [request, join]) {
- await expect(
- githubScript(script, {ref, needs: complete}),
- ).rejects.toThrow('dispatched from main');
- }
+ await expect(
+ githubScript(join, {ref, needs: complete}),
+ ).rejects.toThrow('marked release branch');
},
);
+ it('rejects checkout drift from the expected head', async () => {
+ await expect(
+ githubScript(join, {expectedHead: 'b'.repeat(40), needs: complete}),
+ ).rejects.toThrow('does not match expected head');
+ });
+
it.each(['b'.repeat(40), undefined])(
- 'rejects main drift or missing SHA %s',
- async mainSha => {
- for (const script of [request, join]) {
- await expect(
- githubScript(script, {mainSha: mainSha ?? '', needs: complete}),
- ).rejects.toThrow('Main changed');
- }
+ 'rejects release-branch drift or a missing remote SHA %s',
+ async remoteSha => {
+ await expect(
+ githubScript(join, {remoteSha: remoteSha ?? '', needs: complete}),
+ ).rejects.toThrow('Release branch moved');
},
);
- it('fails closed when current main cannot be read', async () => {
- for (const script of [request, join]) {
- await expect(
- githubScript(script, {apiFails: true, needs: complete}),
- ).rejects.toThrow('API unavailable');
- }
+ it('fails closed when the release branch cannot be read', async () => {
+ await expect(
+ githubScript(join, {apiFails: true, needs: complete}),
+ ).rejects.toThrow('API unavailable');
});
it.each(['failure', 'cancelled', 'skipped', 'neutral', ''])(
@@ -299,7 +308,12 @@ describe('full release scope without PR metadata or maintenance writes', () => {
[
'check-scope',
'Determine change scope',
- {docsite_only: 'false', spec_only: 'false', tooling_only: 'false'},
+ {
+ docsite_only: 'false',
+ spec_only: 'false',
+ tooling_only: 'false',
+ release_bump: 'false',
+ },
],
[
'check-components',
@@ -318,7 +332,12 @@ describe('full release scope without PR metadata or maintenance writes', () => {
);
const result = shell(
script,
- {GITHUB_OUTPUT: output},
+ {
+ GITHUB_OUTPUT: output,
+ ...(job === 'check-scope'
+ ? {EVENT_NAME: 'workflow_dispatch', BASE_REF: ''}
+ : {}),
+ },
'git() { echo "must not inspect changed files" >&2; return 99; }',
);
expect(result.status, result.stderr).toBe(0);
diff --git a/.github/scripts/release-publish-workflow.test.mjs b/.github/scripts/release-publish-workflow.test.mjs
new file mode 100644
index 0000000000..2f828ade87
--- /dev/null
+++ b/.github/scripts/release-publish-workflow.test.mjs
@@ -0,0 +1,126 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {describe, expect, it} from 'vitest';
+import yaml from 'yaml';
+
+const ROOT = path.resolve(import.meta.dirname, '../..');
+const workflow = yaml.parse(
+ fs.readFileSync(path.join(ROOT, '.github/workflows/release.yml'), 'utf8'),
+);
+const ci = yaml.parse(
+ fs.readFileSync(path.join(ROOT, '.github/workflows/ci.yml'), 'utf8'),
+);
+const stable = workflow.jobs.publish;
+const canary = workflow.jobs.canary;
+const step = (job, name) =>
+ job.steps.find(candidate => candidate.name === name);
+
+describe('stable and canary publication authority', () => {
+ it('keeps stable explicit and canary limited to main pushes', () => {
+ expect(stable.if).toBe("github.event_name == 'workflow_dispatch'");
+ expect(canary.if).toBe("github.event_name == 'push'");
+ expect(workflow.on.push.branches).toEqual(['main']);
+ for (const name of [
+ 'release-branch',
+ 'release-version',
+ 'release-tag',
+ 'expected-head',
+ 'plan-digest',
+ ]) {
+ expect(workflow.on.workflow_dispatch.inputs[name].required).toBe(true);
+ }
+ });
+
+ it('binds stable publication to marker, tag, branch, head, version, and plan', () => {
+ const gateInputs = ci.on.workflow_dispatch.inputs;
+ expect(gateInputs['release-version']).toBeDefined();
+ expect(gateInputs['plan-digest']).toBeDefined();
+ const gate = step(
+ ci.jobs['check-scope'],
+ 'Validate active release authority',
+ ).run;
+ expect(gate).toContain('--release-version "$RELEASE_VERSION"');
+ expect(gate).toContain('--plan-digest "$PLAN_DIGEST"');
+
+ const validation = step(
+ stable,
+ 'Validate marked release branch, tag commit, and plan',
+ ).run;
+ for (const flag of [
+ '--mode publish',
+ '--release-branch "$RELEASE_BRANCH"',
+ '--release-version "$RELEASE_VERSION"',
+ '--release-tag "$RELEASE_TAG"',
+ '--expected-head "$EXPECTED_HEAD"',
+ '--plan-digest "$PLAN_DIGEST"',
+ '--checkout-sha "$GITHUB_SHA"',
+ '--remote-head "$REMOTE_HEAD"',
+ '--ref-name "$GITHUB_REF_NAME"',
+ '--active-branches "$ACTIVE_BRANCHES"',
+ ]) {
+ expect(validation).toContain(flag);
+ }
+ expect(validation).toContain('list-active');
+ expect(validation).toContain('refs/heads/$RELEASE_BRANCH');
+ });
+
+ it('builds stable packages from the checked-out tag and never consumes canary artifacts', () => {
+ expect(step(stable, 'Checkout immutable release tag').uses).toMatch(
+ /^actions\/checkout@/u,
+ );
+ expect(step(stable, 'Build all packages').run).toBe('pnpm build');
+ expect(step(stable, 'Verify published package contents').run).toBe(
+ 'pnpm check:public-package-identifiers',
+ );
+ expect(
+ stable.steps.some(candidate =>
+ /download-artifact/u.test(candidate.uses ?? ''),
+ ),
+ ).toBe(false);
+ const publish = step(stable, 'Publish changed packages').run;
+ expect(publish).toContain('--tag latest');
+ expect(publish).not.toContain('--tag canary');
+ });
+
+ it('keeps canary ephemeral and unable to mutate stable authority', () => {
+ const publish = step(canary, 'Publish canary versions').run;
+ expect(publish).toContain('BASE_VERSION=');
+ expect(publish).toContain('--tag canary');
+ expect(publish).not.toContain('--tag latest');
+ const canaryText = JSON.stringify(canary);
+ expect(canaryText).not.toContain('.release/');
+ expect(canaryText).not.toContain('release-publish-receipt');
+ expect(canaryText).not.toContain('active-release.mjs');
+ });
+
+ it('validates every main sync against trusted base policy and the immutable tag', () => {
+ const sync = ci.jobs['release-sync'];
+ expect(sync.if).toContain("github.base_ref == 'main'");
+ const scope = step(
+ sync,
+ 'Detect and require the release-sync branch contract',
+ ).run;
+ expect(scope).toContain('chore/sync-v*-to-main');
+ expect(scope).toContain('stable package-version change on main');
+ const validation = step(
+ sync,
+ 'Validate published bytes and consumed-only Changeset sync',
+ ).run;
+ expect(validation).toContain('validate-sync');
+ expect(validation).toContain('--base origin/main');
+ expect(validation).toContain('--release-ref "v$VERSION"');
+ expect(validation).toContain('--active-branches "$ACTIVE_BRANCHES"');
+ expect(
+ step(sync, 'Fetch release authority and trusted validator').run,
+ ).toContain('git show origin/main:scripts/release/active-release.mjs');
+ const parity = step(
+ sync,
+ 'Verify immutable tag package bytes match npm',
+ ).run;
+ expect(parity).toContain('git worktree add --detach');
+ expect(parity).toContain('pnpm build');
+ expect(parity).toContain('verify-published.mjs --version "$VERSION"');
+ });
+});
diff --git a/.github/scripts/spec-owner-workflow.test.mjs b/.github/scripts/spec-owner-workflow.test.mjs
index 872666223d..bf5e9f11d2 100644
--- a/.github/scripts/spec-owner-workflow.test.mjs
+++ b/.github/scripts/spec-owner-workflow.test.mjs
@@ -218,7 +218,7 @@ describe('spec-only workflow contract', () => {
it('fails closed when file APIs are truncated or scope classification fails', () => {
const ci = read('.github/workflows/ci.yml');
expect(ci).toContain(
- "if: ${{ github.event_name != 'workflow_dispatch' && always() && !cancelled() }}",
+ "if: ${{ github.event_name != 'workflow_dispatch' && needs.check-scope.outputs.release_bump != 'true' && always() && !cancelled() }}",
);
expect(ci).toContain("if: needs.check-scope.result != 'success'");
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 4daa48ee0b..3d38127991 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -9,18 +9,34 @@ name: CI
on:
pull_request:
- branches: ['main']
+ branches: ['main', 'release/**']
merge_group:
# Explicit release checks and baseline capture share the canonical owners.
# Reviewed captures are committed through a normal pull request.
workflow_dispatch:
inputs:
operation:
- description: 'Check exact main for release or capture a baseline candidate'
+ description: 'Check the marked release branch or capture a main baseline candidate'
type: choice
options: [capture, release-check]
default: capture
required: true
+ release-branch:
+ description: 'Marked release/vX.Y.Z branch; required for release-check'
+ type: string
+ required: false
+ release-version:
+ description: 'Exact X.Y.Z version recorded by the active marker; required for release-check'
+ type: string
+ required: false
+ expected-head:
+ description: 'Exact full release branch SHA; required for release-check'
+ type: string
+ required: false
+ plan-digest:
+ description: 'Exact SHA-256 digest recorded by the active marker; required for release-check'
+ type: string
+ required: false
permissions: {}
@@ -51,24 +67,61 @@ jobs:
docsite_only: ${{ steps.scope.outputs.docsite_only }}
spec_only: ${{ steps.scope.outputs.spec_only }}
tooling_only: ${{ steps.scope.outputs.tooling_only }}
+ release_bump: ${{ steps.scope.outputs.release_bump }}
+ release_branch: ${{ steps.release-authority.outputs.branch }}
+ release_head: ${{ steps.release-authority.outputs.head }}
+ release_plan_digest: ${{ steps.release-authority.outputs.planDigest }}
steps:
- - name: Require exact current main for release
- if: github.event_name == 'workflow_dispatch'
- uses: actions/github-script@v9
- with:
- script: |
- if (context.ref !== 'refs/heads/main') {
- throw new Error('Release checks must be dispatched from main.');
- }
- const {data} = await github.rest.git.getRef({...context.repo, ref: 'heads/main'});
- if (data.object.sha !== context.sha) {
- throw new Error('Main changed since dispatch; dispatch release-check again.');
- }
-
- uses: actions/checkout@v7
with:
ref: ${{ github.sha }}
- fetch-depth: 50
+ fetch-depth: 0
+
+ - name: Fetch active release refs
+ if: >-
+ (github.event_name == 'workflow_dispatch' && inputs.operation == 'release-check') ||
+ (github.event_name == 'pull_request' && startsWith(github.base_ref, 'release/v'))
+ run: git fetch origin '+refs/heads/release/v*:refs/remotes/origin/release/v*'
+
+ - name: Validate active release authority
+ id: release-authority
+ if: >-
+ (github.event_name == 'workflow_dispatch' && inputs.operation == 'release-check') ||
+ (github.event_name == 'pull_request' && startsWith(github.base_ref, 'release/v'))
+ env:
+ RELEASE_BRANCH: ${{ github.event_name == 'workflow_dispatch' && inputs['release-branch'] || github.base_ref }}
+ RELEASE_VERSION: ${{ github.event_name == 'workflow_dispatch' && inputs['release-version'] || '' }}
+ EXPECTED_HEAD: ${{ github.event_name == 'workflow_dispatch' && inputs['expected-head'] || github.event.pull_request.head.sha }}
+ PLAN_DIGEST: ${{ github.event_name == 'workflow_dispatch' && inputs['plan-digest'] || '' }}
+ RECEIPT_HEAD: ${{ github.event_name == 'workflow_dispatch' && github.sha || github.event.pull_request.head.sha }}
+ REF_NAME: ${{ github.event_name == 'workflow_dispatch' && github.ref_name || github.base_ref }}
+ MODE: ${{ github.event_name == 'workflow_dispatch' && 'check' || 'pr' }}
+ run: |
+ set -eu
+ TRUSTED_POLICY="$RUNNER_TEMP/release-policy"
+ mkdir -p "$TRUSTED_POLICY/scripts/release" "$TRUSTED_POLICY/scripts/lib"
+ git show "origin/$RELEASE_BRANCH:scripts/release/active-release.mjs" \
+ > "$TRUSTED_POLICY/scripts/release/active-release.mjs"
+ git show "origin/$RELEASE_BRANCH:scripts/lib/workspace-globs.mjs" \
+ > "$TRUSTED_POLICY/scripts/lib/workspace-globs.mjs"
+ VALIDATOR="$TRUSTED_POLICY/scripts/release/active-release.mjs"
+ ACTIVE_BRANCHES=$(node "$VALIDATOR" list-active --root "$GITHUB_WORKSPACE")
+ ARGS=(
+ validate
+ --root "$GITHUB_WORKSPACE"
+ --mode "$MODE"
+ --release-branch "$RELEASE_BRANCH"
+ --expected-head "$EXPECTED_HEAD"
+ --checkout-sha "$RECEIPT_HEAD"
+ --ref-name "$REF_NAME"
+ --active-branches "$ACTIVE_BRANCHES"
+ )
+ if [ "$MODE" = check ]; then
+ ARGS+=(--release-version "$RELEASE_VERSION" --plan-digest "$PLAN_DIGEST")
+ REMOTE_HEAD=$(git ls-remote origin "refs/heads/$RELEASE_BRANCH" | awk '{print $1}')
+ ARGS+=(--remote-head "$REMOTE_HEAD")
+ fi
+ node "$VALIDATOR" "${ARGS[@]}"
- name: Fetch base branch
if: github.event_name == 'pull_request'
@@ -76,16 +129,26 @@ jobs:
- name: Determine change scope
id: scope
+ env:
+ EVENT_NAME: ${{ github.event_name }}
+ BASE_REF: ${{ github.base_ref }}
run: |
- if [ "${{ github.event_name }}" != "pull_request" ]; then
- printf 'docsite_only=false\nspec_only=false\ntooling_only=false\n' >> "$GITHUB_OUTPUT"
+ if [ "$EVENT_NAME" != pull_request ]; then
+ printf 'docsite_only=false\nspec_only=false\ntooling_only=false\nrelease_bump=false\n' >> "$GITHUB_OUTPUT"
+ exit 0
+ fi
+ if [[ "$BASE_REF" == release/v* ]]; then
+ # Release bump PRs contain generated bookkeeping only. The final
+ # branch head receives one full visual/a11y/RTL release-check.
+ printf 'docsite_only=false\nspec_only=true\ntooling_only=true\nrelease_bump=true\n' >> "$GITHUB_OUTPUT"
exit 0
fi
MERGE_BASE=$(git merge-base HEAD origin/${{ github.base_ref }} 2>/dev/null || echo "")
if [ -z "$MERGE_BASE" ]; then
- printf 'docsite_only=false\nspec_only=false\ntooling_only=false\n' >> "$GITHUB_OUTPUT"
+ printf 'docsite_only=false\nspec_only=false\ntooling_only=false\nrelease_bump=false\n' >> "$GITHUB_OUTPUT"
exit 0
fi
+ echo 'release_bump=false' >> "$GITHUB_OUTPUT"
CLASSIFIER_ROOT="$RUNNER_TEMP/change-scope"
CLASSIFIER_DIR="$CLASSIFIER_ROOT/.github/scripts"
REGISTRY_DIR="$CLASSIFIER_ROOT/scripts"
@@ -104,10 +167,164 @@ jobs:
printf 'docsite_only=false\nspec_only=false\ntooling_only=false\n' \
>> "$GITHUB_OUTPUT"
fi
+ # Generated-only version PR lane. It validates release bookkeeping in a few
+ # minutes; the merged branch head receives one full visual/a11y/RTL projection.
+ release-bump:
+ needs: [check-scope]
+ if: ${{ github.event_name == 'pull_request' && needs.check-scope.outputs.release_bump == 'true' }}
+ runs-on: 2-core-ubuntu-arm
+ permissions:
+ contents: read
+ steps:
+ - uses: actions/checkout@v7
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+ fetch-depth: 0
+
+ - name: Fetch release refs, base, and trusted release policy
+ run: |
+ git fetch origin '+refs/heads/release/v*:refs/remotes/origin/release/v*'
+ git fetch origin "${{ github.base_ref }}" --depth=50
+ TRUSTED_POLICY="$RUNNER_TEMP/release-policy"
+ mkdir -p "$TRUSTED_POLICY/scripts/release" "$TRUSTED_POLICY/scripts/lib"
+ git show "origin/${{ github.base_ref }}:scripts/release/active-release.mjs" \
+ > "$TRUSTED_POLICY/scripts/release/active-release.mjs"
+ git show "origin/${{ github.base_ref }}:scripts/lib/workspace-globs.mjs" \
+ > "$TRUSTED_POLICY/scripts/lib/workspace-globs.mjs"
+
+ - name: Setup Node and pnpm
+ uses: ./.github/actions/setup
+
+ - name: Require generated-only release bookkeeping
+ run: |
+ node "$RUNNER_TEMP/release-policy/scripts/release/active-release.mjs" validate-diff \
+ --root "$GITHUB_WORKSPACE" \
+ --base "origin/${{ github.base_ref }}" \
+ --head "${{ github.event.pull_request.head.sha }}"
+
+ - name: Validate branch, head, plan, versions, and Changeset consumption
+ run: |
+ set -eu
+ VALIDATOR="$RUNNER_TEMP/release-policy/scripts/release/active-release.mjs"
+ ACTIVE_BRANCHES=$(node "$VALIDATOR" list-active --root "$GITHUB_WORKSPACE")
+ node "$VALIDATOR" validate \
+ --root "$GITHUB_WORKSPACE" \
+ --mode pr \
+ --release-branch "${{ github.base_ref }}" \
+ --expected-head "${{ github.event.pull_request.head.sha }}" \
+ --checkout-sha "${{ github.event.pull_request.head.sha }}" \
+ --ref-name "${{ github.base_ref }}" \
+ --active-branches "$ACTIVE_BRANCHES" \
+ | tee release-bump-receipt.json
+
+ - name: Validate generated changelogs and codemods
+ run: |
+ pnpm check:changesets
+ node scripts/format-changelogs.mjs --check
+ VERSION=$(node -p "require('./.release/active.json').version")
+ pnpm exec vitest run \
+ "packages/cli/assets/codemods/transforms/v${VERSION}/__tests__" \
+ packages/cli/assets/codemods/__tests__/registry.test.mjs
+
+ - name: Upload exact-head release bump receipt
+ uses: actions/upload-artifact@v7
+ with:
+ name: release-bump-receipt-${{ github.event.pull_request.head.sha }}
+ path: release-bump-receipt.json
+ retention-days: 30
+
+ release-sync:
+ name: release-sync
+ if: ${{ github.event_name == 'pull_request' && github.base_ref == 'main' }}
+ runs-on: 2-core-ubuntu-arm
+ permissions:
+ contents: read
+ steps:
+ - name: Checkout sync candidate
+ uses: actions/checkout@v7
+ with:
+ fetch-depth: 0
+
+ - name: Detect and require the release-sync branch contract
+ id: release-sync-scope
+ env:
+ SYNC_BRANCH: ${{ github.head_ref }}
+ run: |
+ set -eu
+ git fetch origin main
+ BASE_VERSION=$(git show origin/main:packages/core/package.json | node -e "let s='';process.stdin.on('data',d=>s+=d).on('end',()=>console.log(JSON.parse(s).version))")
+ HEAD_VERSION=$(node -p "require('./packages/core/package.json').version")
+ case "$SYNC_BRANCH" in
+ chore/sync-v*-to-main)
+ VERSION=${SYNC_BRANCH#chore/sync-v}
+ VERSION=${VERSION%-to-main}
+ printf '%s' "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$'
+ test "$HEAD_VERSION" = "$VERSION"
+ echo 'required=true' >> "$GITHUB_OUTPUT"
+ ;;
+ *)
+ if [ "$HEAD_VERSION" != "$BASE_VERSION" ]; then
+ echo 'A stable package-version change on main must use chore/sync-vX.Y.Z-to-main and pass release-sync.'
+ exit 1
+ fi
+ echo 'required=false' >> "$GITHUB_OUTPUT"
+ ;;
+ esac
+
+ - name: Fetch release authority and trusted validator
+ if: steps.release-sync-scope.outputs.required == 'true'
+ run: |
+ set -eu
+ git fetch origin main 'refs/tags/v*:refs/tags/v*' '+refs/heads/release/v*:refs/remotes/origin/release/v*'
+ TRUSTED_POLICY="$RUNNER_TEMP/release-policy"
+ mkdir -p "$TRUSTED_POLICY/scripts/release" "$TRUSTED_POLICY/scripts/lib"
+ git show origin/main:scripts/release/active-release.mjs \
+ > "$TRUSTED_POLICY/scripts/release/active-release.mjs"
+ git show origin/main:scripts/lib/workspace-globs.mjs \
+ > "$TRUSTED_POLICY/scripts/lib/workspace-globs.mjs"
+
+ - name: Validate published bytes and consumed-only Changeset sync
+ if: steps.release-sync-scope.outputs.required == 'true'
+ env:
+ SYNC_BRANCH: ${{ github.head_ref }}
+ run: |
+ set -eu
+ VERSION=${SYNC_BRANCH#chore/sync-v}
+ VERSION=${VERSION%-to-main}
+ printf '%s' "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$'
+ VALIDATOR="$RUNNER_TEMP/release-policy/scripts/release/active-release.mjs"
+ ACTIVE_BRANCHES=$(node "$VALIDATOR" list-active --root "$GITHUB_WORKSPACE")
+ node "$VALIDATOR" validate-sync \
+ --root "$GITHUB_WORKSPACE" \
+ --base origin/main \
+ --release-ref "v$VERSION" \
+ --active-branches "$ACTIVE_BRANCHES"
+
+ - name: Setup Node and pnpm for published-byte verification
+ if: steps.release-sync-scope.outputs.required == 'true'
+ uses: ./.github/actions/setup
+ with:
+ install: 'false'
+
+ - name: Verify immutable tag package bytes match npm
+ if: steps.release-sync-scope.outputs.required == 'true'
+ env:
+ SYNC_BRANCH: ${{ github.head_ref }}
+ run: |
+ set -eu
+ VERSION=${SYNC_BRANCH#chore/sync-v}
+ VERSION=${VERSION%-to-main}
+ TAG_ROOT="$RUNNER_TEMP/release-tag"
+ git worktree add --detach "$TAG_ROOT" "v$VERSION"
+ cd "$TAG_ROOT"
+ pnpm install --frozen-lockfile
+ pnpm build
+ node scripts/release/verify-published.mjs --version "$VERSION"
+
# Required docsite owner: data tests plus the production browser contract.
docsite-test:
needs: [check-scope, docsite-browser]
- if: ${{ github.event_name != 'workflow_dispatch' && always() && !cancelled() }}
+ if: ${{ github.event_name != 'workflow_dispatch' && needs.check-scope.outputs.release_bump != 'true' && always() && !cancelled() }}
runs-on: 2-core-ubuntu-arm
permissions:
contents: read
@@ -1767,10 +1984,13 @@ jobs:
permissions:
contents: read
steps:
- - name: Require complete exact-main release checks
+ - name: Require complete exact-head release branch checks
uses: actions/github-script@v9
env:
RELEASE_NEEDS: ${{ toJSON(needs) }}
+ RELEASE_BRANCH: ${{ inputs['release-branch'] }}
+ EXPECTED_HEAD: ${{ inputs['expected-head'] }}
+ PLAN_DIGEST: ${{ needs.check-scope.outputs.release_plan_digest }}
with:
script: |
const needs = JSON.parse(process.env.RELEASE_NEEDS);
@@ -1779,15 +1999,22 @@ jobs:
throw new Error(`Required release job ${name} did not succeed: ${needs[name]?.result}`);
}
}
- if (context.ref !== 'refs/heads/main') {
- throw new Error('Release checks must be dispatched from main.');
+ const branch = process.env.RELEASE_BRANCH;
+ const expectedHead = process.env.EXPECTED_HEAD;
+ if (context.ref !== `refs/heads/${branch}`) {
+ throw new Error('Release checks must run from the marked release branch.');
+ }
+ if (context.sha !== expectedHead) {
+ throw new Error('Checked-out release commit does not match expected head.');
}
- const {data} = await github.rest.git.getRef({...context.repo, ref: 'heads/main'});
- if (data.object.sha !== context.sha) {
- throw new Error('Main changed during checks; dispatch release-check again.');
+ const {data} = await github.rest.git.getRef({...context.repo, ref: `heads/${branch}`});
+ if (data.object.sha !== expectedHead) {
+ throw new Error('Release branch moved during checks; dispatch release-check again for its new head.');
}
await core.summary
.addHeading('Release checks complete')
- .addRaw(`Exact main SHA: ${context.sha}\n\n`)
- .addRaw('Canonical visual, accessibility, and RTL checks completed with full scope. Recheck main before release mutation; this run does not approve or publish a baseline.')
+ .addRaw(`Branch: ${branch}\n\n`)
+ .addRaw(`Exact head: ${expectedHead}\n\n`)
+ .addRaw(`Plan digest: ${process.env.PLAN_DIGEST}\n\n`)
+ .addRaw('Canonical visual, accessibility, and RTL checks completed with full scope. Main movement is not release input. This receipt is reusable only for this exact branch, head, and plan digest; any cherry-pick requires a new run.')
.write();
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 40f6dcce68..fffdad5c7f 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -15,10 +15,11 @@
# Two jobs, selected by trigger:
# - publish (stable): workflow_dispatch only. Publishes the `latest` dist-tag.
# The release flow is:
-# 1. Land the changesets "Version Packages" PR on main (`pnpm
-# version-packages` → PR → merge). This bumps versions; it never touches
-# the registry.
-# 2. Run this workflow to publish the bumped versions.
+# 1. Cut and mark one release/vX.Y.Z branch from exact window-time main.
+# 2. Target the generated Version Packages PR to that branch.
+# 3. Run the final exact-head release checks, tag the merged bump commit,
+# and dispatch this workflow from that immutable tag with the recorded
+# release branch and head. Stable publication from main is rejected.
# Version-gated and idempotent: any version already on the registry is
# skipped, so re-running (or a `dry-run` first) is safe.
# - canary: push to main only. Publishes 0.x.y-canary.<short-sha> to the
@@ -49,6 +50,26 @@ on:
description: 'Build and resolve what would publish, but do not publish'
type: boolean
default: false
+ release-branch:
+ description: 'Single marked release/vX.Y.Z branch'
+ type: string
+ required: true
+ release-version:
+ description: 'Exact X.Y.Z version recorded by the active marker'
+ type: string
+ required: true
+ release-tag:
+ description: 'Exact immutable vX.Y.Z tag checked out by this run'
+ type: string
+ required: true
+ expected-head:
+ description: 'Exact full release branch SHA carried by this tag'
+ type: string
+ required: true
+ plan-digest:
+ description: 'Exact SHA-256 digest recorded by the active marker'
+ type: string
+ required: true
push:
branches: [main]
@@ -68,8 +89,55 @@ jobs:
contents: read
id-token: write # npm OIDC trusted publishing + provenance
steps:
- - name: Checkout
+ - name: Checkout immutable release tag
uses: actions/checkout@v7
+ with:
+ fetch-depth: 0
+
+ - name: Validate marked release branch, tag commit, and plan
+ env:
+ RELEASE_BRANCH: ${{ inputs['release-branch'] }}
+ RELEASE_VERSION: ${{ inputs['release-version'] }}
+ RELEASE_TAG: ${{ inputs['release-tag'] }}
+ EXPECTED_HEAD: ${{ inputs['expected-head'] }}
+ PLAN_DIGEST: ${{ inputs['plan-digest'] }}
+ run: |
+ set -eu
+ git fetch origin '+refs/heads/release/v*:refs/remotes/origin/release/v*'
+ ACTIVE_BRANCHES=$(node scripts/release/active-release.mjs list-active)
+ REMOTE_HEAD=$(git ls-remote origin "refs/heads/$RELEASE_BRANCH" | awk '{print $1}')
+ node scripts/release/active-release.mjs validate \
+ --mode publish \
+ --release-branch "$RELEASE_BRANCH" \
+ --release-version "$RELEASE_VERSION" \
+ --release-tag "$RELEASE_TAG" \
+ --expected-head "$EXPECTED_HEAD" \
+ --plan-digest "$PLAN_DIGEST" \
+ --checkout-sha "$GITHUB_SHA" \
+ --remote-head "$REMOTE_HEAD" \
+ --ref-name "$GITHUB_REF_NAME" \
+ --active-branches "$ACTIVE_BRANCHES" \
+ | tee release-publish-receipt.json
+
+ - name: Upload exact release authority receipt
+ uses: actions/upload-artifact@v7
+ with:
+ name: release-publish-receipt-${{ inputs['expected-head'] }}
+ path: release-publish-receipt.json
+ retention-days: 90
+
+ - name: Record release authority summary
+ run: |
+ PLAN_DIGEST=$(node -p "require('./.release/active.json').planDigest")
+ {
+ echo '## Stable release authority'
+ echo
+ echo "- Branch: ${{ inputs['release-branch'] }}"
+ echo "- Version: ${{ inputs['release-version'] }}"
+ echo "- Head: ${{ inputs['expected-head'] }}"
+ echo "- Tag: ${{ inputs['release-tag'] }}"
+ echo "- Plan digest: $PLAN_DIGEST"
+ } >> "$GITHUB_STEP_SUMMARY"
# registry-url makes setup-node write the auth config `npm publish` reads.
# The Node line in .nvmrc must stay >= 24 so npm >= 11.5.1 ships with it,
@@ -82,6 +150,9 @@ jobs:
- name: Build all packages
run: pnpm build
+ - name: Verify published package contents
+ run: pnpm check:public-package-identifiers
+
- name: Publish changed packages
env:
DRY_RUN: ${{ inputs.dry-run }}
diff --git a/scripts/prune-branches.sh b/scripts/prune-branches.sh
index 3bd2a5f37f..9ea4a92d14 100755
--- a/scripts/prune-branches.sh
+++ b/scripts/prune-branches.sh
@@ -13,7 +13,6 @@
set -euo pipefail
REPO="facebook/astryx"
-PROTECTED="main|gh-pages"
MODE="${1:-dry-run}"
PARALLEL=15
STALE_DAYS=60 # branches with no PR older than this are also flagged
@@ -33,13 +32,36 @@ echo ""
echo -e "${DIM}Fetching and pruning remote refs...${NC}"
git fetch origin --prune --quiet 2>/dev/null
+# Active release branches are protected by their checked-in marker. A release/*
+# branch without a readable matching marker is uncertainty, not permission to
+# delete: stop the entire cleanup before producing a kill list.
+release_branches=()
+while IFS= read -r b; do
+ [ -n "$b" ] || continue
+ if ! marker=$(node scripts/release/active-release.mjs inspect-ref --ref "origin/$b"); then
+ echo "Refusing branch cleanup: $b lacks a valid release marker." >&2
+ exit 1
+ fi
+ state=$(node -e 'console.log(JSON.parse(process.argv[1]).state)' "$marker")
+ [ "$state" = active ] && release_branches+=("$b")
+done < <(git branch -r | sed 's|^[[:space:]]*origin/||' | grep '^release/v' || true)
+
+is_protected_branch() {
+ case "$1" in main|gh-pages) return 0 ;; esac
+ local protected
+ for protected in "${release_branches[@]}"; do
+ [ "$1" = "$protected" ] && return 0
+ done
+ return 1
+}
+
# Get all remote branches, excluding protected
branches=()
while IFS= read -r b; do
- branches+=("$b")
-done < <(git branch -r | grep -v HEAD | sed 's| origin/||' | grep -Ev "^($PROTECTED)$")
+ is_protected_branch "$b" || branches+=("$b")
+done < <(git branch -r | grep -v HEAD | sed 's| origin/||')
total=${#branches[@]}
-echo -e "Found ${BOLD}$total${NC} remote branches (excluding $PROTECTED)"
+echo -e "Found ${BOLD}$total${NC} remote branches (active release branches protected)"
echo ""
# Temp dirs — one file per branch avoids concurrent write corruption
diff --git a/scripts/release/active-release.mjs b/scripts/release/active-release.mjs
new file mode 100644
index 0000000000..0c8c566b8e
--- /dev/null
+++ b/scripts/release/active-release.mjs
@@ -0,0 +1,700 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Active release branch authority and receipt validation.
+ *
+ * @input .release marker/plan files, release refs, expected branch/head inputs
+ * @output fail-closed validation receipts bound to branch + commit + plan digest
+ * @position single authority used by release CI, stable publishing, and branch cleanup
+ */
+
+import crypto from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+import {execFileSync} from 'node:child_process';
+import {fileURLToPath} from 'node:url';
+import {expandWorkspaceDirs} from '../lib/workspace-globs.mjs';
+
+const ROOT = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ '../..',
+);
+const RELEASE_DIR = '.release';
+const MARKER_FILE = 'active.json';
+const PLAN_FILE = 'plan.json';
+const SHA_RE = /^[0-9a-f]{40}$/;
+const VERSION_RE = /^\d+\.\d+\.\d+$/;
+const BRANCH_RE = /^release\/v(\d+\.\d+\.\d+)$/;
+
+function sha256(value) {
+ return crypto.createHash('sha256').update(value).digest('hex');
+}
+
+function canonicalJson(value) {
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
+ if (value && typeof value === 'object') {
+ return `{${Object.keys(value)
+ .sort()
+ .map(key => `${JSON.stringify(key)}:${canonicalJson(value[key])}`)
+ .join(',')}}`;
+ }
+ return JSON.stringify(value);
+}
+
+function computePlanDigest(plan) {
+ return sha256(canonicalJson(plan));
+}
+
+function readJson(file) {
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
+}
+
+function changesetEntries(root) {
+ const dir = path.join(root, '.changeset');
+ return fs
+ .readdirSync(dir)
+ .filter(name => name.endsWith('.md') && !['README.md'].includes(name))
+ .sort()
+ .map(name => {
+ const relative = `.changeset/${name}`;
+ return {
+ path: relative,
+ sha256: sha256(fs.readFileSync(path.join(root, relative))),
+ };
+ });
+}
+
+function buildPlan({root, version, branch, cutSha}) {
+ return {
+ schemaVersion: 1,
+ version,
+ branch,
+ cutSha,
+ changesets: changesetEntries(root),
+ };
+}
+
+function buildMarker(plan) {
+ return {
+ schemaVersion: 1,
+ state: 'active',
+ version: plan.version,
+ branch: plan.branch,
+ cutSha: plan.cutSha,
+ planDigest: computePlanDigest(plan),
+ };
+}
+
+function validateIdentity(marker, plan) {
+ const errors = [];
+ if (marker?.schemaVersion !== 1)
+ errors.push('marker schemaVersion must be 1');
+ if (marker?.state !== 'active') errors.push('marker state must be active');
+ if (!VERSION_RE.test(marker?.version ?? ''))
+ errors.push('marker version must be X.Y.Z');
+ const branchMatch = BRANCH_RE.exec(marker?.branch ?? '');
+ if (!branchMatch) errors.push('marker branch must be release/vX.Y.Z');
+ if (branchMatch && branchMatch[1] !== marker.version)
+ errors.push('marker branch version must match marker version');
+ if (!SHA_RE.test(marker?.cutSha ?? ''))
+ errors.push('marker cutSha must be a full SHA');
+ if (!/^[0-9a-f]{64}$/.test(marker?.planDigest ?? ''))
+ errors.push('marker planDigest must be a SHA-256 digest');
+ if (plan?.schemaVersion !== 1) errors.push('plan schemaVersion must be 1');
+ for (const key of ['version', 'branch', 'cutSha']) {
+ if (plan?.[key] !== marker?.[key])
+ errors.push(`plan ${key} must match marker`);
+ }
+ if (computePlanDigest(plan) !== marker?.planDigest)
+ errors.push('plan digest does not match marker');
+ const seen = new Set();
+ for (const entry of plan?.changesets ?? []) {
+ if (
+ !entry ||
+ !/^\.changeset\/[A-Za-z0-9._-]+\.md$/.test(entry.path ?? '')
+ ) {
+ errors.push('plan contains an invalid Changeset path');
+ continue;
+ }
+ if (seen.has(entry.path)) errors.push(`plan repeats ${entry.path}`);
+ seen.add(entry.path);
+ if (!/^[0-9a-f]{64}$/.test(entry.sha256 ?? ''))
+ errors.push(`plan has an invalid digest for ${entry.path}`);
+ }
+ return errors;
+}
+
+function publishablePackages(root) {
+ return expandWorkspaceDirs(root)
+ .map(dir => path.join(dir, 'package.json'))
+ .filter(file => fs.existsSync(file))
+ .map(file => ({file, manifest: readJson(file)}))
+ .filter(
+ ({manifest}) =>
+ manifest.name?.startsWith('@astryxdesign/') &&
+ manifest.private !== true &&
+ manifest.astryx?.canaryOnly !== true,
+ );
+}
+
+function validateReleaseState({
+ root,
+ marker,
+ plan,
+ mode,
+ releaseBranch,
+ releaseVersion,
+ releaseTag,
+ expectedPlanDigest,
+ refName,
+ expectedHead,
+ checkoutSha,
+ remoteHead,
+ activeBranches,
+}) {
+ const errors = validateIdentity(marker, plan);
+ if (releaseBranch !== marker.branch)
+ errors.push('release-branch input does not match marker');
+ if (releaseVersion !== undefined && releaseVersion !== marker.version)
+ errors.push('release-version input does not match marker');
+ if (releaseTag !== undefined && releaseTag !== `v${marker.version}`)
+ errors.push('release-tag input does not match marker version');
+ if (
+ expectedPlanDigest !== undefined &&
+ expectedPlanDigest !== marker.planDigest
+ )
+ errors.push('plan-digest input does not match marker');
+ if (activeBranches.length !== 1 || activeBranches[0] !== marker.branch)
+ errors.push(
+ `exactly one active release branch is required; found ${activeBranches.join(',') || 'none'}`,
+ );
+ if (!SHA_RE.test(expectedHead ?? ''))
+ errors.push('expected-head must be a full SHA');
+ if (!SHA_RE.test(checkoutSha ?? ''))
+ errors.push('checkout SHA must be a full SHA');
+ if (expectedHead !== checkoutSha)
+ errors.push('checked-out commit does not match expected head');
+ if (remoteHead && remoteHead !== expectedHead)
+ errors.push('release branch moved after the expected head was recorded');
+
+ if (mode === 'check') {
+ if (releaseVersion === undefined)
+ errors.push('release check requires release-version');
+ if (expectedPlanDigest === undefined)
+ errors.push('release check requires plan-digest');
+ }
+
+ if (mode === 'publish') {
+ if (releaseVersion === undefined)
+ errors.push('stable publish requires release-version');
+ if (releaseTag === undefined)
+ errors.push('stable publish requires release-tag');
+ if (expectedPlanDigest === undefined)
+ errors.push('stable publish requires plan-digest');
+ if (refName !== `v${marker.version}`)
+ errors.push('stable publish must run from the version tag');
+ if (releaseTag !== undefined && refName !== releaseTag)
+ errors.push('checked-out tag does not match release-tag input');
+ } else if (refName !== marker.branch) {
+ errors.push('release validation must run from the marked release branch');
+ }
+
+ const current = new Map(
+ changesetEntries(root).map(entry => [entry.path, entry.sha256]),
+ );
+ if (mode === 'cut') {
+ for (const entry of plan.changesets) {
+ if (current.get(entry.path) !== entry.sha256)
+ errors.push(`cut Changeset differs or is missing: ${entry.path}`);
+ }
+ if (current.size !== plan.changesets.length)
+ errors.push('cut Changeset set differs from the recorded plan');
+ } else {
+ if (current.size !== 0)
+ errors.push('versioned release must consume every branch Changeset');
+ for (const {manifest, file} of publishablePackages(root)) {
+ if (manifest.version !== marker.version)
+ errors.push(
+ `${path.relative(root, file)} is ${manifest.version}, expected ${marker.version}`,
+ );
+ }
+ }
+ return errors;
+}
+
+function git(root, args) {
+ return execFileSync('git', args, {cwd: root, encoding: 'utf8'}).trim();
+}
+
+function fileDigestAtRef(root, ref, file) {
+ try {
+ return sha256(execFileSync('git', ['show', `${ref}:${file}`], {cwd: root}));
+ } catch {
+ return null;
+ }
+}
+
+function changesetMapAtRef(root, ref) {
+ const files = git(root, [
+ 'ls-tree',
+ '-r',
+ '--name-only',
+ ref,
+ '--',
+ '.changeset',
+ ]);
+ return new Map(
+ files
+ .split('\n')
+ .filter(
+ file =>
+ file.startsWith('.changeset/') &&
+ file.endsWith('.md') &&
+ file !== '.changeset/README.md',
+ )
+ .map(file => [file, fileDigestAtRef(root, ref, file)]),
+ );
+}
+
+function releaseOutputMapAtRef(root, plan, releaseRef) {
+ const files = git(root, [
+ 'diff',
+ '--name-only',
+ plan.cutSha,
+ releaseRef,
+ '--',
+ ]);
+ return new Map(
+ files
+ .split('\n')
+ .filter(Boolean)
+ .filter(isReleaseOutputPath)
+ .map(file => [file, fileDigestAtRef(root, releaseRef, file)]),
+ );
+}
+
+function currentOutputMap(root, files) {
+ return new Map(
+ [...files].map(file => {
+ const absolute = path.join(root, file);
+ return [
+ file,
+ fs.existsSync(absolute) ? sha256(fs.readFileSync(absolute)) : null,
+ ];
+ }),
+ );
+}
+
+function markerAtRef(root, ref) {
+ return JSON.parse(
+ git(root, ['show', `${ref}:${RELEASE_DIR}/${MARKER_FILE}`]),
+ );
+}
+
+function validateRefMarker(marker, branch) {
+ const match = BRANCH_RE.exec(branch);
+ if (
+ marker?.schemaVersion !== 1 ||
+ !['active', 'closed'].includes(marker?.state) ||
+ !match ||
+ marker.branch !== branch ||
+ marker.version !== match[1] ||
+ !SHA_RE.test(marker.cutSha ?? '') ||
+ !/^[0-9a-f]{64}$/.test(marker.planDigest ?? '')
+ ) {
+ throw new Error(
+ `release branch ${branch} has an invalid or mismatched marker`,
+ );
+ }
+}
+
+function listActiveBranches(root) {
+ const refs = git(root, [
+ 'for-each-ref',
+ '--format=%(refname:short)',
+ 'refs/remotes/origin/release/v*',
+ ]);
+ if (!refs) return [];
+ const active = [];
+ for (const ref of refs.split('\n').filter(Boolean)) {
+ let marker;
+ try {
+ marker = markerAtRef(root, ref);
+ } catch {
+ throw new Error(`release branch ${ref} has no readable marker`);
+ }
+ const branch = ref.replace(/^origin\//, '');
+ validateRefMarker(marker, branch);
+ if (marker.state === 'active') active.push(branch);
+ }
+ return active.sort();
+}
+
+const RELEASE_OUTPUT_PATTERNS = [
+ /^packages\/(?:[^/]+|themes\/[^/]+)\/package\.json$/,
+ /^packages\/(?:[^/]+|themes\/[^/]+)\/CHANGELOG\.md$/,
+ /^packages\/cli\/assets\/codemods\/registry\.mjs$/,
+ /^packages\/cli\/assets\/codemods\/__tests__\/registry\.test\.mjs$/,
+ /^packages\/cli\/assets\/codemods\/transforms\/(?:next|v\d+\.\d+\.\d+)\//,
+ /^pnpm-lock\.yaml$/,
+];
+
+function isReleaseOutputPath(file) {
+ return RELEASE_OUTPUT_PATTERNS.some(pattern => pattern.test(file));
+}
+
+function validateReleaseDiff(entries, {plan, baseChangesets} = {}) {
+ const errors = [];
+ const planned = plan
+ ? new Map(plan.changesets.map(entry => [entry.path, entry.sha256]))
+ : null;
+ const deletedChangesets = new Set();
+ for (const entry of entries) {
+ const [status, ...files] = entry.split('\t');
+ const isMove = status?.startsWith('R') || status?.startsWith('C');
+ const expectedPaths = isMove ? 2 : 1;
+ if (
+ !status ||
+ files.length !== expectedPaths ||
+ files.some(file => !file)
+ ) {
+ errors.push(`invalid diff entry: ${entry}`);
+ continue;
+ }
+ for (const file of files) {
+ if (!file.startsWith('.changeset/') && !isReleaseOutputPath(file))
+ errors.push(`release bump contains a non-generated path: ${file}`);
+ if (file.startsWith('.changeset/')) {
+ if (status !== 'D')
+ errors.push(
+ `release bump may only delete planned Changesets: ${file}`,
+ );
+ else {
+ deletedChangesets.add(file);
+ if (planned && !planned.has(file))
+ errors.push(`release bump deletes an unplanned Changeset: ${file}`);
+ }
+ }
+ }
+ }
+ if (planned && baseChangesets) {
+ for (const [file, digest] of planned) {
+ if (baseChangesets.get(file) !== digest)
+ errors.push(
+ `frozen Changeset differs or is missing at branch base: ${file}`,
+ );
+ if (!deletedChangesets.has(file))
+ errors.push(`release bump did not delete frozen Changeset: ${file}`);
+ }
+ for (const file of baseChangesets.keys()) {
+ if (!planned.has(file))
+ errors.push(`release branch contains an unplanned Changeset: ${file}`);
+ }
+ }
+ return errors;
+}
+
+function validateReleaseSync({
+ entries,
+ plan,
+ baseChangesets,
+ headChangesets,
+ releaseOutputs,
+ headOutputs,
+}) {
+ const errors = [];
+ const planned = new Set(plan.changesets.map(entry => entry.path));
+ for (const entry of entries) {
+ const [status, ...files] = entry.split('\t');
+ if (!status || files.length !== 1 || !files[0]) {
+ errors.push(`invalid sync diff entry: ${entry}`);
+ continue;
+ }
+ const file = files[0];
+ if (file.startsWith('.changeset/')) {
+ if (status !== 'D' || !planned.has(file))
+ errors.push(`release sync may only delete frozen Changesets: ${file}`);
+ } else if (
+ !isReleaseOutputPath(file) &&
+ !/^\.github\/pages\/assets\/(?:manifest\.json|reset\.css|astryx\.css|theme\.css)$/.test(
+ file,
+ )
+ ) {
+ errors.push(`release sync contains a non-bookkeeping path: ${file}`);
+ }
+ }
+ for (const file of planned) {
+ if (baseChangesets.has(file) && headChangesets.has(file))
+ errors.push(`release sync did not delete frozen Changeset: ${file}`);
+ }
+ for (const [file, digest] of baseChangesets) {
+ if (planned.has(file)) continue;
+ if (headChangesets.get(file) !== digest)
+ errors.push(`release sync changed post-cut Changeset: ${file}`);
+ }
+ for (const file of headChangesets.keys()) {
+ if (!baseChangesets.has(file))
+ errors.push(
+ `release sync added a Changeset instead of preserving main: ${file}`,
+ );
+ }
+ for (const [file, digest] of releaseOutputs) {
+ if (headOutputs.get(file) !== digest)
+ errors.push(`release sync output differs from published branch: ${file}`);
+ }
+ return errors;
+}
+
+function parseArgs(argv) {
+ const [command, ...rest] = argv;
+ const values = {};
+ for (let index = 0; index < rest.length; index += 1) {
+ const key = rest[index];
+ if (!key.startsWith('--')) throw new Error(`unexpected argument ${key}`);
+ const value = rest[index + 1];
+ if (value == null || value.startsWith('--'))
+ throw new Error(`${key} needs a value`);
+ values[key.slice(2)] = value;
+ index += 1;
+ }
+ return {command, values};
+}
+
+function required(values, key) {
+ if (!values[key]) throw new Error(`--${key} is required`);
+ return values[key];
+}
+
+function versionTagExists(root, version) {
+ try {
+ execFileSync(
+ 'git',
+ ['rev-parse', '--verify', '--quiet', `refs/tags/v${version}`],
+ {cwd: root, stdio: 'ignore'},
+ );
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+function writeAuthority(root, values, refresh) {
+ const version = required(values, 'version');
+ const branch = required(values, 'branch');
+ const cutSha = required(values, 'cut-sha');
+ if (
+ !VERSION_RE.test(version) ||
+ branch !== `release/v${version}` ||
+ !SHA_RE.test(cutSha)
+ )
+ throw new Error(
+ 'version, branch, and cut SHA do not form a valid release identity',
+ );
+ const dir = path.join(root, RELEASE_DIR);
+ const markerPath = path.join(dir, MARKER_FILE);
+ const planPath = path.join(dir, PLAN_FILE);
+ const markerExists = fs.existsSync(markerPath);
+ const planExists = fs.existsSync(planPath);
+
+ if (refresh) {
+ if (!markerExists || !planExists)
+ throw new Error('release refresh requires an existing active marker and plan');
+ const existingMarker = readJson(markerPath);
+ const existingPlan = readJson(planPath);
+ const identityErrors = validateIdentity(existingMarker, existingPlan);
+ if (identityErrors.length) throw new Error(identityErrors.join('\n'));
+ for (const [key, value] of [
+ ['version', version],
+ ['branch', branch],
+ ['cutSha', cutSha],
+ ]) {
+ if (existingMarker[key] !== value)
+ throw new Error(`release refresh cannot change ${key}`);
+ }
+ } else {
+ if (markerExists || planExists)
+ throw new Error(
+ 'release authority already exists; a release branch cannot be reused',
+ );
+ if (versionTagExists(root, version))
+ throw new Error(
+ `version v${version} already has an immutable tag; use a new release branch and version`,
+ );
+ }
+
+ fs.mkdirSync(dir, {recursive: true});
+ const plan = buildPlan({root, version, branch, cutSha});
+ const marker = buildMarker(plan);
+ fs.writeFileSync(planPath, `${JSON.stringify(plan, null, 2)}\n`);
+ fs.writeFileSync(markerPath, `${JSON.stringify(marker, null, 2)}\n`);
+ console.log(
+ JSON.stringify({branch, version, cutSha, planDigest: marker.planDigest}),
+ );
+}
+
+function main() {
+ const {command, values} = parseArgs(process.argv.slice(2));
+ const root = path.resolve(values.root ?? ROOT);
+ if (command === 'create' || command === 'refresh') {
+ writeAuthority(root, values, command === 'refresh');
+ return;
+ }
+ if (command === 'list-active') {
+ console.log(listActiveBranches(root).join(','));
+ return;
+ }
+ if (command === 'inspect-ref') {
+ const ref = required(values, 'ref');
+ const marker = markerAtRef(root, ref);
+ const branch = ref.replace(/^origin\//, '');
+ validateRefMarker(marker, branch);
+ console.log(JSON.stringify(marker));
+ return;
+ }
+ if (command === 'validate-diff') {
+ const base = required(values, 'base');
+ const head = required(values, 'head');
+ const marker = markerAtRef(root, base);
+ const plan = JSON.parse(
+ git(root, ['show', `${base}:${RELEASE_DIR}/${PLAN_FILE}`]),
+ );
+ const raw = git(root, ['diff', '--name-status', `${base}...${head}`]);
+ const errors = [
+ ...validateIdentity(marker, plan),
+ ...validateReleaseDiff(raw ? raw.split('\n') : [], {
+ plan,
+ baseChangesets: changesetMapAtRef(root, base),
+ }),
+ ];
+ if (errors.length) throw new Error(errors.join('\n'));
+ console.log(
+ JSON.stringify({
+ base,
+ head,
+ planDigest: marker.planDigest,
+ files: raw ? raw.split('\n').length : 0,
+ }),
+ );
+ return;
+ }
+ if (command === 'validate-sync') {
+ const base = required(values, 'base');
+ const releaseRef = required(values, 'release-ref');
+ const marker = markerAtRef(root, releaseRef);
+ const plan = JSON.parse(
+ git(root, ['show', `${releaseRef}:${RELEASE_DIR}/${PLAN_FILE}`]),
+ );
+ const errors = validateIdentity(marker, plan);
+ if (releaseRef !== `v${marker.version}`)
+ errors.push('release sync must use the immutable version tag');
+ const releaseHead = git(root, ['rev-parse', releaseRef]);
+ const branchHead = git(root, ['rev-parse', `origin/${marker.branch}`]);
+ if (releaseHead !== branchHead)
+ errors.push('version tag does not match the active release branch head');
+ const activeBranches = required(values, 'active-branches')
+ .split(',')
+ .filter(Boolean)
+ .sort();
+ if (activeBranches.length !== 1 || activeBranches[0] !== marker.branch)
+ errors.push('release sync requires exactly the marked active branch');
+ const raw = git(root, [
+ 'diff',
+ '--name-status',
+ '--find-renames',
+ base,
+ 'HEAD',
+ ]);
+ const releaseOutputs = releaseOutputMapAtRef(root, plan, releaseRef);
+ errors.push(
+ ...validateReleaseSync({
+ entries: raw ? raw.split('\n') : [],
+ plan,
+ baseChangesets: changesetMapAtRef(root, base),
+ headChangesets: new Map(
+ changesetEntries(root).map(entry => [entry.path, entry.sha256]),
+ ),
+ releaseOutputs,
+ headOutputs: currentOutputMap(root, releaseOutputs.keys()),
+ }),
+ );
+ if (errors.length) throw new Error(errors.join('\n'));
+ console.log(
+ JSON.stringify({
+ branch: marker.branch,
+ head: releaseHead,
+ version: marker.version,
+ planDigest: marker.planDigest,
+ base,
+ releaseRef,
+ }),
+ );
+ return;
+ }
+ if (command !== 'validate')
+ throw new Error(
+ 'command must be create, refresh, list-active, inspect-ref, validate-diff, validate-sync, or validate',
+ );
+
+ const marker = readJson(path.join(root, RELEASE_DIR, MARKER_FILE));
+ const plan = readJson(path.join(root, RELEASE_DIR, PLAN_FILE));
+ const activeBranches = required(values, 'active-branches')
+ .split(',')
+ .filter(Boolean)
+ .sort();
+ const errors = validateReleaseState({
+ root,
+ marker,
+ plan,
+ mode: required(values, 'mode'),
+ releaseBranch: required(values, 'release-branch'),
+ releaseVersion: values['release-version'],
+ releaseTag: values['release-tag'],
+ expectedPlanDigest: values['plan-digest'],
+ refName: required(values, 'ref-name'),
+ expectedHead: required(values, 'expected-head'),
+ checkoutSha: required(values, 'checkout-sha'),
+ remoteHead: values['remote-head'],
+ activeBranches,
+ });
+ if (errors.length) throw new Error(errors.join('\n'));
+ const receipt = {
+ branch: marker.branch,
+ head: values['expected-head'],
+ version: marker.version,
+ planDigest: marker.planDigest,
+ mode: values.mode,
+ };
+ if (process.env.GITHUB_OUTPUT) {
+ fs.appendFileSync(
+ process.env.GITHUB_OUTPUT,
+ Object.entries(receipt)
+ .map(([key, value]) => `${key}=${value}\n`)
+ .join(''),
+ );
+ }
+ console.log(JSON.stringify(receipt));
+}
+
+if (process.argv[1] === fileURLToPath(import.meta.url)) {
+ try {
+ main();
+ } catch (error) {
+ console.error(`release authority validation failed: ${error.message}`);
+ process.exit(1);
+ }
+}
+
+export {
+ buildMarker,
+ buildPlan,
+ canonicalJson,
+ computePlanDigest,
+ listActiveBranches,
+ validateIdentity,
+ validateRefMarker,
+ validateReleaseDiff,
+ validateReleaseState,
+ validateReleaseSync,
+ versionTagExists,
+ writeAuthority,
+};
diff --git a/scripts/release/active-release.test.mjs b/scripts/release/active-release.test.mjs
new file mode 100644
index 0000000000..3b194c6b99
--- /dev/null
+++ b/scripts/release/active-release.test.mjs
@@ -0,0 +1,432 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Release branch authority regression tests.
+ *
+ * @input synthetic active markers, plans, package versions, and branch heads
+ * @output proofs that only one exact marked release branch can gate or publish
+ * @position focused safety suite for the release-branch CI contract
+ */
+
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import {execFileSync} from 'node:child_process';
+import {afterEach, describe, expect, it} from 'vitest';
+import {
+ buildMarker,
+ buildPlan,
+ validateReleaseDiff,
+ validateReleaseState,
+ validateReleaseSync,
+ writeAuthority,
+} from './active-release.mjs';
+
+const CUT = '1'.repeat(40);
+const HEAD = '2'.repeat(40);
+const NEXT_HEAD = '3'.repeat(40);
+const BRANCH = 'release/v0.6.5';
+const roots = [];
+
+function fixture({withChangeset = false} = {}) {
+ const root = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'astryx-release-authority-'),
+ );
+ roots.push(root);
+ fs.mkdirSync(path.join(root, '.changeset'), {recursive: true});
+ fs.mkdirSync(path.join(root, 'packages/core'), {recursive: true});
+ fs.writeFileSync(
+ path.join(root, 'pnpm-workspace.yaml'),
+ "packages:\n - 'packages/*'\n",
+ );
+ fs.writeFileSync(
+ path.join(root, 'packages/core/package.json'),
+ JSON.stringify({name: '@astryxdesign/core', version: '0.6.5'}, null, 2),
+ );
+ fs.writeFileSync(path.join(root, '.changeset/README.md'), '# Changesets\n');
+ if (withChangeset) {
+ fs.writeFileSync(
+ path.join(root, '.changeset/in-cut.md'),
+ "---\n'@astryxdesign/core': patch\n---\n\n[fix] Included\n@person\n",
+ );
+ }
+ const plan = buildPlan({root, version: '0.6.5', branch: BRANCH, cutSha: CUT});
+ const marker = buildMarker(plan);
+ if (withChangeset) fs.rmSync(path.join(root, '.changeset/in-cut.md'));
+ return {root, plan, marker};
+}
+
+function validate(state, overrides = {}) {
+ return validateReleaseState({
+ ...state,
+ mode: 'check',
+ releaseBranch: BRANCH,
+ releaseVersion: state.marker.version,
+ releaseTag: `v${state.marker.version}`,
+ expectedPlanDigest: state.marker.planDigest,
+ refName: BRANCH,
+ expectedHead: HEAD,
+ checkoutSha: HEAD,
+ remoteHead: HEAD,
+ activeBranches: [BRANCH],
+ ...overrides,
+ });
+}
+
+afterEach(() => {
+ for (const root of roots.splice(0))
+ fs.rmSync(root, {recursive: true, force: true});
+});
+
+describe('one branch per release lifecycle', () => {
+ const values = {
+ version: '0.6.5',
+ branch: BRANCH,
+ 'cut-sha': CUT,
+ };
+
+ it('allows an explicit plan revision only within the same active identity', () => {
+ const {root} = fixture({withChangeset: true});
+ writeAuthority(root, values, false);
+ const original = JSON.parse(
+ fs.readFileSync(path.join(root, '.release/active.json'), 'utf8'),
+ );
+
+ fs.writeFileSync(
+ path.join(root, '.changeset/authorized-revision.md'),
+ 'authorized revision',
+ );
+ writeAuthority(root, values, true);
+ const revised = JSON.parse(
+ fs.readFileSync(path.join(root, '.release/active.json'), 'utf8'),
+ );
+ expect(revised.planDigest).not.toBe(original.planDigest);
+ expect(() =>
+ writeAuthority(
+ root,
+ {...values, version: '0.6.6', branch: 'release/v0.6.6'},
+ true,
+ ),
+ ).toThrow('release refresh cannot change version');
+ expect(() =>
+ writeAuthority(root, {...values, 'cut-sha': HEAD}, true),
+ ).toThrow('release refresh cannot change cutSha');
+ });
+
+ it('never revives or recreates a closed branch lifecycle', () => {
+ const {root} = fixture();
+ writeAuthority(root, values, false);
+ const markerPath = path.join(root, '.release/active.json');
+ const marker = JSON.parse(fs.readFileSync(markerPath, 'utf8'));
+ fs.writeFileSync(markerPath, `${JSON.stringify({...marker, state: 'closed'})}\n`);
+
+ expect(() => writeAuthority(root, values, true)).toThrow(
+ 'marker state must be active',
+ );
+ expect(() => writeAuthority(root, values, false)).toThrow(
+ 'release branch cannot be reused',
+ );
+ });
+
+ it('requires a new version when the immutable tag already exists', () => {
+ const {root} = fixture();
+ execFileSync('git', ['init', '-q'], {cwd: root});
+ execFileSync('git', ['config', 'user.name', 'Release Test'], {cwd: root});
+ execFileSync('git', ['config', 'user.email', '[email protected]'], {
+ cwd: root,
+ });
+ execFileSync('git', ['add', '.'], {cwd: root});
+ execFileSync('git', ['commit', '-qm', 'fixture'], {cwd: root});
+ execFileSync('git', ['tag', 'v0.6.5'], {cwd: root});
+
+ expect(() => writeAuthority(root, values, false)).toThrow(
+ 'use a new release branch and version',
+ );
+ });
+});
+
+describe('active release branch authority', () => {
+ it('accepts one marked active branch at its exact head', () => {
+ expect(validate(fixture())).toEqual([]);
+ });
+
+ it('requires explicit version and plan authority for the final branch gate', () => {
+ const state = fixture();
+ expect(validate(state, {releaseVersion: undefined})).toContain(
+ 'release check requires release-version',
+ );
+ expect(validate(state, {expectedPlanDigest: undefined})).toContain(
+ 'release check requires plan-digest',
+ );
+ });
+
+ it('ignores post-cut main package and Changeset activity', () => {
+ const state = fixture();
+ fs.mkdirSync(path.join(state.root, 'moving-main-snapshot/.changeset'), {
+ recursive: true,
+ });
+ fs.writeFileSync(
+ path.join(state.root, 'moving-main-snapshot/package.json'),
+ JSON.stringify({version: '9.9.9'}),
+ );
+ fs.writeFileSync(
+ path.join(state.root, 'moving-main-snapshot/.changeset/later.md'),
+ 'later main input',
+ );
+ expect(validate(state)).toEqual([]);
+ });
+
+ it('rejects main and an unmarked or wrong release branch', () => {
+ const state = fixture();
+ expect(validate(state, {refName: 'main'})).toContain(
+ 'release validation must run from the marked release branch',
+ );
+ expect(validate(state, {releaseBranch: 'release/v0.6.4'})).toContain(
+ 'release-branch input does not match marker',
+ );
+ });
+
+ it('rejects missing or ambiguous active branches', () => {
+ const state = fixture();
+ expect(validate(state, {activeBranches: []})[0]).toMatch(
+ /exactly one active release branch/,
+ );
+ expect(
+ validate(state, {activeBranches: [BRANCH, 'release/v0.6.4']})[0],
+ ).toMatch(/exactly one active release branch/);
+ });
+
+ it('rejects stale expected heads', () => {
+ const state = fixture();
+ expect(validate(state, {checkoutSha: NEXT_HEAD})).toContain(
+ 'checked-out commit does not match expected head',
+ );
+ expect(validate(state, {remoteHead: NEXT_HEAD})).toContain(
+ 'release branch moved after the expected head was recorded',
+ );
+ });
+
+ it('accepts an explicitly updated branch head only with a new receipt', () => {
+ const state = fixture();
+ expect(validate(state, {remoteHead: NEXT_HEAD})).not.toEqual([]);
+ expect(
+ validate(state, {
+ expectedHead: NEXT_HEAD,
+ checkoutSha: NEXT_HEAD,
+ remoteHead: NEXT_HEAD,
+ }),
+ ).toEqual([]);
+ });
+
+ it('accepts publication only from the matching immutable tag', () => {
+ const state = fixture();
+ expect(validate(state, {mode: 'publish', refName: 'v0.6.5'})).toEqual([]);
+ expect(validate(state, {mode: 'publish', refName: BRANCH})).toContain(
+ 'stable publish must run from the version tag',
+ );
+ expect(validate(state, {mode: 'publish', refName: 'main'})).toContain(
+ 'stable publish must run from the version tag',
+ );
+ });
+
+ it('does not let dispatch inputs override marker authority', () => {
+ const state = fixture();
+ expect(
+ validate(state, {
+ mode: 'publish',
+ refName: 'v0.6.5',
+ releaseVersion: '0.6.4',
+ }),
+ ).toContain('release-version input does not match marker');
+ expect(
+ validate(state, {
+ mode: 'publish',
+ refName: 'v0.6.5',
+ releaseTag: 'v0.6.4',
+ }),
+ ).toEqual(
+ expect.arrayContaining([
+ 'release-tag input does not match marker version',
+ 'checked-out tag does not match release-tag input',
+ ]),
+ );
+ expect(
+ validate(state, {
+ mode: 'publish',
+ refName: 'v0.6.5',
+ expectedPlanDigest: 'f'.repeat(64),
+ }),
+ ).toContain('plan-digest input does not match marker');
+ });
+
+ it('rejects package versions that do not match the marked release', () => {
+ const state = fixture();
+ fs.writeFileSync(
+ path.join(state.root, 'packages/core/package.json'),
+ JSON.stringify({name: '@astryxdesign/core', version: '0.6.4'}, null, 2),
+ );
+ expect(validate(state, {mode: 'publish', refName: 'v0.6.5'})).toContain(
+ 'packages/core/package.json is 0.6.4, expected 0.6.5',
+ );
+ });
+
+ it('keeps the fast bump lane generated-only', () => {
+ expect(
+ validateReleaseDiff([
+ 'D\t.changeset/in-cut.md',
+ 'M\tpackages/core/package.json',
+ 'M\tpackages/core/CHANGELOG.md',
+ 'A\tpackages/cli/assets/codemods/transforms/v0.6.5/index.mjs',
+ 'M\tpnpm-lock.yaml',
+ ]),
+ ).toEqual([]);
+ expect(
+ validateReleaseDiff(['M\tpackages/core/src/Button/Button.tsx']),
+ ).toContain(
+ 'release bump contains a non-generated path: packages/core/src/Button/Button.tsx',
+ );
+ expect(validateReleaseDiff(['A\t.changeset/post-cut.md'])).toContain(
+ 'release bump may only delete planned Changesets: .changeset/post-cut.md',
+ );
+ expect(
+ validateReleaseDiff([
+ 'R100\tpackages/core/CHANGELOG.md\tpackages/core/src/release.ts',
+ ]),
+ ).toContain(
+ 'release bump contains a non-generated path: packages/core/src/release.ts',
+ );
+ expect(
+ validateReleaseDiff([
+ 'R100\tpackages/core/src/release.ts\tpackages/core/CHANGELOG.md',
+ ]),
+ ).toContain(
+ 'release bump contains a non-generated path: packages/core/src/release.ts',
+ );
+ expect(
+ validateReleaseDiff([
+ 'R100\tpackages/core/CHANGELOG.md\tpackages/cli/CHANGELOG.md',
+ ]),
+ ).toEqual([]);
+ });
+
+ it('binds generated-only deletion to the frozen plan paths and hashes', () => {
+ const digest = value => value.repeat(64).slice(0, 64);
+ const plan = {
+ changesets: [{path: '.changeset/frozen.md', sha256: digest('a')}],
+ };
+ expect(
+ validateReleaseDiff(['D\t.changeset/frozen.md'], {
+ plan,
+ baseChangesets: new Map([['.changeset/frozen.md', digest('a')]]),
+ }),
+ ).toEqual([]);
+ expect(
+ validateReleaseDiff(['D\t.changeset/not-frozen.md'], {
+ plan,
+ baseChangesets: new Map([
+ ['.changeset/frozen.md', digest('b')],
+ ['.changeset/not-frozen.md', digest('c')],
+ ]),
+ }),
+ ).toEqual(
+ expect.arrayContaining([
+ 'release bump deletes an unplanned Changeset: .changeset/not-frozen.md',
+ 'frozen Changeset differs or is missing at branch base: .changeset/frozen.md',
+ 'release bump did not delete frozen Changeset: .changeset/frozen.md',
+ 'release branch contains an unplanned Changeset: .changeset/not-frozen.md',
+ ]),
+ );
+ });
+
+ it('binds the plan to the exact Changesets recorded at cut', () => {
+ const state = fixture({withChangeset: true});
+ expect(validate(state)).toEqual([]);
+ fs.writeFileSync(path.join(state.root, '.changeset/later.md'), 'post-cut');
+ expect(validate(state)).toContain(
+ 'versioned release must consume every branch Changeset',
+ );
+ });
+});
+
+describe('post-release bookkeeping sync', () => {
+ const digest = value => value.repeat(64).slice(0, 64);
+ const plan = {
+ changesets: [
+ {path: '.changeset/frozen.md', sha256: digest('a')},
+ {path: '.changeset/already-consumed.md', sha256: digest('b')},
+ ],
+ };
+
+ function sync(overrides = {}) {
+ return validateReleaseSync({
+ entries: [
+ 'D\t.changeset/frozen.md',
+ 'M\tpackages/core/package.json',
+ 'M\tpackages/core/CHANGELOG.md',
+ ],
+ plan,
+ baseChangesets: new Map([
+ ['.changeset/frozen.md', digest('a')],
+ ['.changeset/post-cut.md', digest('c')],
+ ]),
+ headChangesets: new Map([['.changeset/post-cut.md', digest('c')]]),
+ releaseOutputs: new Map([
+ ['packages/core/package.json', digest('d')],
+ ['packages/core/CHANGELOG.md', digest('e')],
+ ]),
+ headOutputs: new Map([
+ ['packages/core/package.json', digest('d')],
+ ['packages/core/CHANGELOG.md', digest('e')],
+ ]),
+ ...overrides,
+ });
+ }
+
+ it('accepts consumed-only deletion, exact outputs, and idempotent reruns', () => {
+ expect(sync()).toEqual([]);
+ expect(
+ sync({
+ entries: [],
+ baseChangesets: new Map([['.changeset/post-cut.md', digest('c')]]),
+ }),
+ ).toEqual([]);
+ });
+
+ it('rejects changes to post-cut Changesets and non-bookkeeping paths', () => {
+ expect(
+ sync({
+ entries: [
+ 'M\t.changeset/post-cut.md',
+ 'M\tpackages/core/src/Button/Button.tsx',
+ ],
+ headChangesets: new Map([['.changeset/post-cut.md', digest('f')]]),
+ }),
+ ).toEqual(
+ expect.arrayContaining([
+ 'release sync may only delete frozen Changesets: .changeset/post-cut.md',
+ 'release sync contains a non-bookkeeping path: packages/core/src/Button/Button.tsx',
+ 'release sync changed post-cut Changeset: .changeset/post-cut.md',
+ ]),
+ );
+ });
+
+ it('rejects missing frozen deletions and release-output drift', () => {
+ expect(
+ sync({
+ headChangesets: new Map([
+ ['.changeset/frozen.md', digest('a')],
+ ['.changeset/post-cut.md', digest('c')],
+ ]),
+ headOutputs: new Map([
+ ['packages/core/package.json', digest('f')],
+ ['packages/core/CHANGELOG.md', digest('e')],
+ ]),
+ }),
+ ).toEqual(
+ expect.arrayContaining([
+ 'release sync did not delete frozen Changeset: .changeset/frozen.md',
+ 'release sync output differs from published branch: packages/core/package.json',
+ ]),
+ );
+ });
+});
diff --git a/scripts/release/verify-published.mjs b/scripts/release/verify-published.mjs
new file mode 100644
index 0000000000..e7fcdf9265
--- /dev/null
+++ b/scripts/release/verify-published.mjs
@@ -0,0 +1,175 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import crypto from 'node:crypto';
+import {execFileSync} from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {expandWorkspaceDirs} from '../lib/workspace-globs.mjs';
+
+function sha256(file) {
+ return crypto
+ .createHash('sha256')
+ .update(fs.readFileSync(file))
+ .digest('hex');
+}
+
+function files(root, directory = root, result = new Map()) {
+ for (const entry of fs.readdirSync(directory, {withFileTypes: true})) {
+ const absolute = path.join(directory, entry.name);
+ if (entry.isDirectory()) files(root, absolute, result);
+ else if (entry.isFile()) {
+ result.set(
+ path.relative(root, absolute).split(path.sep).join('/'),
+ sha256(absolute),
+ );
+ }
+ }
+ return result;
+}
+
+export function comparePackageTrees(localRoot, publishedRoot) {
+ const local = files(localRoot);
+ const published = files(publishedRoot);
+ const errors = [];
+ for (const [file, digest] of local) {
+ if (!published.has(file))
+ errors.push(`published package is missing ${file}`);
+ else if (published.get(file) !== digest)
+ errors.push(`published package differs at ${file}`);
+ }
+ for (const file of published.keys()) {
+ if (!local.has(file))
+ errors.push(`published package has unexpected ${file}`);
+ }
+ return errors;
+}
+
+function publishablePackages(root) {
+ return expandWorkspaceDirs(root)
+ .filter(directory => fs.existsSync(path.join(directory, 'package.json')))
+ .map(directory => ({
+ directory,
+ manifest: JSON.parse(
+ fs.readFileSync(path.join(directory, 'package.json'), 'utf8'),
+ ),
+ }))
+ .filter(
+ ({manifest}) =>
+ manifest.name?.startsWith('@astryxdesign/') &&
+ manifest.private !== true &&
+ manifest.astryx?.canaryOnly !== true,
+ );
+}
+
+function packLocal(directory, destination) {
+ fs.mkdirSync(destination, {recursive: true});
+ const output = execFileSync(
+ 'pnpm',
+ ['pack', '--pack-destination', destination],
+ {cwd: directory, encoding: 'utf8'},
+ ).trim();
+ const filename = output.split(/\r?\n/u).filter(Boolean).at(-1);
+ if (!filename)
+ throw new Error(`pnpm pack returned no tarball for ${directory}`);
+ return path.isAbsolute(filename)
+ ? filename
+ : path.join(destination, path.basename(filename));
+}
+
+function packPublished(specifier, destination, cwd) {
+ fs.mkdirSync(destination, {recursive: true});
+ const output = execFileSync(
+ 'npm',
+ [
+ 'pack',
+ specifier,
+ '--pack-destination',
+ destination,
+ '--ignore-scripts',
+ '--silent',
+ ],
+ {cwd, encoding: 'utf8'},
+ ).trim();
+ const filename = output.split(/\r?\n/u).filter(Boolean).at(-1);
+ if (!filename)
+ throw new Error(`npm pack returned no tarball for ${specifier}`);
+ return path.join(destination, filename);
+}
+
+function extract(tarball, destination) {
+ fs.mkdirSync(destination, {recursive: true});
+ execFileSync('tar', ['-xzf', tarball, '-C', destination]);
+ return path.join(destination, 'package');
+}
+
+function parseArgs(argv) {
+ const values = {};
+ for (let index = 0; index < argv.length; index += 2) {
+ const key = argv[index];
+ const value = argv[index + 1];
+ if (!key?.startsWith('--') || value == null)
+ throw new Error('expected --version X.Y.Z and optional --root PATH');
+ values[key.slice(2)] = value;
+ }
+ return values;
+}
+
+export function verifyPublishedPackages({root, version}) {
+ const scratch = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'astryx-published-parity-'),
+ );
+ const errors = [];
+ try {
+ for (const {directory, manifest} of publishablePackages(root)) {
+ if (manifest.version !== version) {
+ errors.push(
+ `${manifest.name} is ${manifest.version}, expected ${version}`,
+ );
+ continue;
+ }
+ const slug = manifest.name.replace('@', '').replace('/', '-');
+ const localTar = packLocal(directory, path.join(scratch, 'local'));
+ const publishedTar = packPublished(
+ `${manifest.name}@${version}`,
+ path.join(scratch, 'published'),
+ root,
+ );
+ const localRoot = extract(localTar, path.join(scratch, `${slug}-local`));
+ const publishedRoot = extract(
+ publishedTar,
+ path.join(scratch, `${slug}-published`),
+ );
+ for (const error of comparePackageTrees(localRoot, publishedRoot)) {
+ errors.push(`${manifest.name}: ${error}`);
+ }
+ }
+ } finally {
+ fs.rmSync(scratch, {recursive: true, force: true});
+ }
+ return errors;
+}
+
+function main() {
+ const values = parseArgs(process.argv.slice(2));
+ const version = values.version;
+ if (!/^\d+\.\d+\.\d+$/u.test(version ?? ''))
+ throw new Error('--version must be X.Y.Z');
+ const root = path.resolve(values.root ?? process.cwd());
+ const errors = verifyPublishedPackages({root, version});
+ if (errors.length > 0) throw new Error(errors.join('\n'));
+ console.log(`Published package contents match ${version}.`);
+}
+
+if (
+ process.argv[1] &&
+ fileURLToPath(import.meta.url) === path.resolve(process.argv[1])
+) {
+ try {
+ main();
+ } catch (error) {
+ console.error(`published package parity failed: ${error.message}`);
+ process.exit(1);
+ }
+}
diff --git a/scripts/release/verify-published.test.mjs b/scripts/release/verify-published.test.mjs
new file mode 100644
index 0000000000..5bc182f027
--- /dev/null
+++ b/scripts/release/verify-published.test.mjs
@@ -0,0 +1,44 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import {expect, it} from 'vitest';
+import {comparePackageTrees} from './verify-published.mjs';
+
+function tree(entries) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-package-parity-'));
+ for (const [file, contents] of Object.entries(entries)) {
+ const absolute = path.join(root, file);
+ fs.mkdirSync(path.dirname(absolute), {recursive: true});
+ fs.writeFileSync(absolute, contents);
+ }
+ return root;
+}
+
+it('accepts byte-identical package trees', () => {
+ const local = tree({'package.json': '{}\n', 'dist/index.js': 'export {};\n'});
+ const published = tree({
+ 'package.json': '{}\n',
+ 'dist/index.js': 'export {};\n',
+ });
+ expect(comparePackageTrees(local, published)).toEqual( []);
+});
+
+it('reports missing, unexpected, and changed package bytes', () => {
+ const local = tree({
+ 'package.json': '{}\n',
+ 'dist/index.js': 'local\n',
+ 'dist/only-local.js': 'local\n',
+ });
+ const published = tree({
+ 'package.json': '{}\n',
+ 'dist/index.js': 'published\n',
+ 'dist/only-published.js': 'published\n',
+ });
+ expect(comparePackageTrees(local, published)).toEqual( [
+ 'published package differs at dist/index.js',
+ 'published package is missing dist/only-local.js',
+ 'published package has unexpected dist/only-published.js',
+ ]);
+});