An open source design system that's fully customizable and agent ready
TypeScript
ci(release): main declares the version; release branches admit and version against it (#7249)
Cindy Zhang97372707d365
diff --git a/.github/scripts/release-publish-workflow.test.mjs b/.github/scripts/release-publish-workflow.test.mjsindex 89c4f951c8..e90072565e 100644--- a/.github/scripts/release-publish-workflow.test.mjs+++ b/.github/scripts/release-publish-workflow.test.mjs@@ -86,7 +86,11 @@ describe('stable and canary publication authority', () => {it('keeps canary ephemeral and unable to mutate stable authority', () => {const publish = step(canary, 'Publish canary versions').run;- expect(publish).toContain('BASE_VERSION=');+ // FR46: canaries carry the next version main declares.+ expect(publish).toContain(+ 'DECLARED_VERSION=$(node -p "require(\'./packages/core/package.json\').version")',+ );+ expect(publish).toContain('CANARY_VERSION="${DECLARED_VERSION}-canary.');expect(publish).toContain('--tag canary');expect(publish).not.toContain('--tag latest');const canaryText = JSON.stringify(canary);@@ -98,12 +102,9 @@ describe('stable and canary publication authority', () => {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;+ const scope = step(sync, 'Detect the release-sync branch contract').run;expect(scope).toContain('chore/sync-v*-to-main');- expect(scope).toContain('stable package-version change on main');+ expect(scope).not.toContain('stable package-version change on main');const lintScope = step(lint.jobs.lint,@@ -111,6 +112,27 @@ describe('stable and canary publication authority', () => {).run;expect(lintScope).toContain('chore/sync-v*-to-main');expect(lintScope).toContain("grep -Eq '^[0-9]+\\.[0-9]+\\.[0-9]+$'");++ // FR46: the tag-relative version guard lives in required lint, not the+ // optional release-sync context.+ const declared = step(+ lint.jobs.lint,+ "Keep main's declared version above latest stable",+ );+ expect(declared.if).toBe("github.event_name == 'pull_request'");+ expect(declared.run).toContain(+ 'git show origin/main:scripts/release/active-release.mjs',+ );+ expect(declared.run).toContain("'refs/tags/v*:refs/tags/v*'");+ expect(declared.run).toContain('ALLOW_BOOTSTRAP_EQUAL=false');+ expect(declared.run).toContain('ALLOW_BOOTSTRAP_EQUAL=true');+ expect(declared.run).toContain(+ '--allow-bootstrap-equal "$ALLOW_BOOTSTRAP_EQUAL"',+ );+ expect(declared.run).toContain('validate-main-version');+ expect(declared.run).toContain('--base origin/main');+ expect(JSON.stringify(sync)).not.toContain('validate-main-version');+expect(step(lint.jobs.lint, 'Check Changeset coverage').if).toBe("github.event_name == 'pull_request' && steps.release-sync-scope.outputs.required != 'true'",);@@ -131,7 +153,6 @@ describe('stable and canary publication authority', () => {]) {expect(requiredLintValidation.run).toContain(command);}-const validation = step(sync,'Validate published bytes and consumed-only Changeset sync',diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 0a4f0fc406..e3c1d161bf 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -275,28 +275,20 @@ jobs:with:fetch-depth: 0- - name: Detect and require the release-sync branch contract+ - name: Detect the release-sync branch contractid: release-sync-scopeenv: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" inchore/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- fiecho 'required=false' >> "$GITHUB_OUTPUT";;esacdiff --git a/.github/workflows/lint.yml b/.github/workflows/lint.ymlindex 911d6d0bca..a750252403 100644--- a/.github/workflows/lint.yml+++ b/.github/workflows/lint.yml@@ -48,6 +48,35 @@ jobs:>> "$GITHUB_OUTPUT"fi+ # Main declares the next planned version (spec:AST-017 FR46). An owner may+ # raise or lower it before cut, but it must remain strictly above the newest+ # stable tag and keep the fixed group together. This runs in required lint,+ # not the optional release-sync context, so every main pull request is gated.+ - name: Keep main's declared version above latest stable+ if: github.event_name == 'pull_request'+ run: |+ set -eu+ git fetch origin main 'refs/tags/v*:refs/tags/v*'+ TRUSTED_POLICY="$RUNNER_TEMP/main-version-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"+ VALIDATOR="$TRUSTED_POLICY/scripts/release/active-release.mjs"+ ALLOW_BOOTSTRAP_EQUAL=false+ if ! grep -q 'validate-main-version' "$VALIDATOR"; then+ # Main's trusted policy predates this command; the candidate's copy+ # applies only while this command is landing. Current main still+ # equals the newest tag until the separate owner bump lands next.+ VALIDATOR="$GITHUB_WORKSPACE/scripts/release/active-release.mjs"+ ALLOW_BOOTSTRAP_EQUAL=true+ fi+ node "$VALIDATOR" validate-main-version \+ --root "$GITHUB_WORKSPACE" \+ --base origin/main \+ --allow-bootstrap-equal "$ALLOW_BOOTSTRAP_EQUAL"+# Release-sync PRs copy already-published generated outputs and consume the# frozen Changesets. They cannot add a new Changeset, so the required lint# context runs the trusted release-sync validator instead.diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex e72cb874d0..9d0e96a0af 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -15,15 +15,18 @@# Two jobs, selected by trigger:# - publish (stable): workflow_dispatch only. Publishes the `latest` dist-tag.# The release flow is:-# 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.+# 1. Cut and mark one release/vX.Y.Z branch from exact window-time main;+# X.Y.Z is the version main's package.json declares at that commit.+# 2. Target the generated Version Packages PR to that branch. It writes+# changelogs under that version and never moves it.# 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-# `canary` dist-tag on every push to main:+# - canary: push to main only. Main declares the next planned version, so+# this publishes <declared>-canary.<short-sha> to the `canary` dist-tag on+# every push to main:# npm install @astryxdesign/core@canary## Why both jobs live here instead of in deploy.yml:@@ -215,8 +218,9 @@ jobs:run: |set -euSHORT_SHA="${GITHUB_SHA:0:7}"- BASE_VERSION=$(node -p "require('./packages/core/package.json').version")- CANARY_VERSION="${BASE_VERSION}-canary.${SHORT_SHA}"+ # Main's package.json carries the next planned version.+ DECLARED_VERSION=$(node -p "require('./packages/core/package.json').version")+ CANARY_VERSION="${DECLARED_VERSION}-canary.${SHORT_SHA}"echo "Publishing canary ${CANARY_VERSION}"diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex e7e10e2aa7..b6e9b05f0e 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -709,21 +709,25 @@ slugs and docs routes, are data and may change.### Version Bumps-- **0.x (current): bump follows the category.** We track standard semver for the `0.x.y` range, where a minor bump is the stable breaking tier (under a caret range like `^0.1.8`, npm resolves `<0.2.0`). A `[breaking]` change bumps the **minor** (`0.x.y → 0.(x+1).0`). A change confined to a surface that was explicitly marked experimental before its first stable publication uses `[experimental]` and bumps the **patch**, even when that experimental API changes incompatibly. Every other category (`feat`, `fix`, `component`, `perf`, `docs`, `chore`) also bumps the patch. If stable defaults, behavior, props, imports, CLI commands, or machine schemas break, the change remains `[breaking]`. `major` is never used while 0.x — it would jump to `1.0.0`. `pnpm changeset:new` writes the right bump from the category you pick; `pnpm check:changesets` enforces the coupling both ways.-- All publishable packages are a `fixed` group, so a single change co-bumps them to the same version. Only genuinely-affected packages get a changelog entry — the rest get a clean version-only bump.-- **Main targets a patch by default, and `[breaking]` waits for a scheduled minor.** Because the packages are a fixed group, one `[breaking]` entry moves every package to a new minor — so `pnpm check:changesets` refuses one while main is on its patch default. There are two ways forward, and the refusal prints both:- - **Keep the release patch-compatible** (the usual answer): leave the released surface working and deprecate it instead. Ship the replacement, keep the old usage equivalent, and take the patch bump; the removal lands once a minor is scheduled.- - **Wait for the scheduled minor**: minors are scheduled for a specific day. A release owner adds `.release/target.json` with the target version and that day, and from then until the release your `[breaking]` changeset can land. Removing that file afterwards is part of normal post-release setup, and an expired date stops admitting breaking changes on its own.+- **Main declares the next version.** The fixed group's version in main's `package.json` files is the next planned release, for example `0.7.0` while `0.6.7` is the latest stable release. Main publishes only canaries of it (`0.7.0-canary.<sha>`). Before the cut, a release owner may raise or lower the plan—`0.7.0` to `0.6.8`, for example—but it must remain strictly above the newest stable `vX.Y.Z` tag. After a release, sync uses the higher of the current plan and the released version's patch successor. CI refuses a declaration at or below newest stable or a split fixed group.+- **0.x: the category states the tier a change needs.** We track standard semver for the `0.x.y` range, where a minor is the stable breaking tier (under a caret range like `^0.1.8`, npm resolves `<0.2.0`). A `[breaking]` Changeset declares `minor`: it can ship only in a minor release. A change confined to a surface that was explicitly marked experimental before its first stable publication uses `[experimental]` and declares `patch`, even when that experimental API changes incompatibly. Every other category (`feat`, `fix`, `component`, `perf`, `docs`, `chore`) also declares `patch`. If stable defaults, behavior, props, imports, CLI commands, or machine schemas break, the change remains `[breaking]`. `major` is never used while 0.x — it would jump to `1.0.0`. `pnpm changeset:new` writes the right bump from the category you pick; `pnpm check:changesets` enforces the coupling both ways. A Changeset's bump never chooses the release version.+- All publishable packages are a `fixed` group, so they release together at one version. Only genuinely-affected packages get a changelog entry.+- **Pull requests to main check Changeset format, not the release.** `pnpm check:changesets` and the coverage check run on every pull request; neither compares your Changeset with a release version, so a `[breaking]` Changeset can merge while main declares a patch.+- **The release branch admits Changesets against the declared version.** If main declares the patch after the latest stable release (`0.6.7` after `0.6.6`), the release refuses an incompatible Changeset. There are two ways forward, and the refusal prints both:+ - **Keep the release patch-compatible** (the usual answer): leave the released surface working and deprecate it instead. Ship the replacement, keep the old usage equivalent, and let the removal ship in a minor release.+ - **Plan the minor**: a release owner bumps main's version to the minor (`0.7.0`) before the cut. A release that declares `0.7.0` consumes a `[breaking]` Changeset into `0.7.0` changelogs; it does not move to `0.8.0`.- As a contributor you never author that file or decide the schedule — say what you intend in the PR and a maintainer handles it. The rule is `spec:AST-017` FR46–FR50.+ As a contributor you never change the declared version — say what you intend in the PR and a maintainer handles it. The rule is `spec:AST-017` FR46–FR50.### How a release is cut+A release branch `release/vX.Y.Z` is cut from main, where `X.Y.Z` is the version main declares at that commit. On that branch only:+```bash-pnpm version-packages # changeset version + scripts/format-changelogs.mjs+pnpm version-packages # changelogs at the declared version + codemod promotion + formatting```-`format-changelogs.mjs` rewrites each just-bumped package CHANGELOG into the doc-site format (h1 version, `#### <Category>` sections in canonical order, and a `#### Contributors` section aggregated from the changeset `@handle`s). It's idempotent and has a `--check` mode for CI drift detection.+`scripts/release/version-packages.mjs` admits the pending Changesets against the declared version, writes their changelog entries under it, and deletes them; it never changes a package version. `format-changelogs.mjs` then rewrites each package CHANGELOG into the doc-site format (h1 version, `#### <Category>` sections in canonical order, and a `#### Contributors` section aggregated from the changeset `@handle`s). It's idempotent and has a `--check` mode for CI drift detection. After publication, syncing the release back to main carries the changelogs, removes the consumed Changesets, and moves main to the release's next patch unless an owner already set it higher; main's versions never move backward.## Finding Something to Work Ondiff --git a/docs/release.md b/docs/release.mdindex 65761fc7b9..225765814f 100644--- a/docs/release.md+++ b/docs/release.md@@ -4,7 +4,7 @@ astryx publishes its 12 public `@astryxdesign/*` packages to the public npm regi### How it fits together-- **Versioning is local and unchanged.** `pnpm run version-packages` (= `changeset version && promote-codemod-next && sync-internal-deps && format-changelogs`) only edits files, changelogs, and release-staged codemods on disk. It needs no npm auth and is untouched by trusted publishing.+- **Main declares the version; the release branch versions.** Main's `package.json` carries the next planned version and publishes only canaries of it. On the marked release branch, `pnpm run version-packages` (= `scripts/release/version-packages.mjs && promote-codemod-next && sync-internal-deps && format-changelogs`) admits the pending Changesets against that declared version, writes changelogs under it, and promotes release-staged codemods. It never changes a package version, edits only files on disk, needs no npm auth, and is untouched by trusted publishing.- **Publishing is pnpm-native and tokenless.** CI runs `pnpm publish ... --provenance --access public --no-git-checks` (not `changeset publish`, whose `npm whoami` precheck breaks under tokenless OIDC). pnpm natively fetches the OIDC token and attaches provenance.- **Trust is per-package.** npm allows exactly **one** trust configuration per package, registered against the **calling** workflow. Each of the 12 packages must be configured individually.@@ -13,8 +13,8 @@ astryx publishes its 12 public `@astryxdesign/*` packages to the public npm regiCore codemods for unreleased breaking changes are staged in`packages/cli/assets/codemods/transforms/next/`, not in a guessed future versionfolder. During the Version Packages PR, `pnpm version-packages` runs-`scripts/promote-codemod-next.mjs` immediately after `changeset version`, when-`packages/core/package.json` contains the actual version being released.+`scripts/promote-codemod-next.mjs` immediately after the changelogs are written;+`packages/core/package.json` already carries the declared release version.The promotion step copies every entry from `next` except `README.md` into`packages/cli/assets/codemods/transforms/v<released-version>/`, removes thediff --git a/package.json b/package.jsonindex b1f7b38461..b013eb06dc 100644--- a/package.json+++ b/package.json@@ -63,11 +63,10 @@"package:source": "node scripts/package-source.js","changeset": "changeset","changeset:new": "node scripts/changeset-new.mjs",- "version-packages": "changeset version && node scripts/promote-codemod-next.mjs && node scripts/sync-internal-deps.mjs && node scripts/format-changelogs.mjs",+ "version-packages": "node scripts/release/version-packages.mjs && node scripts/promote-codemod-next.mjs && node scripts/sync-internal-deps.mjs && node scripts/format-changelogs.mjs","format-changelogs": "node scripts/format-changelogs.mjs","setup-trusted-publishing": "node scripts/npm/setup-trusted-publishing.mjs","verify-exports": "node scripts/verify-exports.mjs",- "release": "pnpm build && changeset publish","prepare": "node scripts/generate-i18n-runtime.mjs --best-effort && husky install","dev:sandbox": "pnpm -F @astryxdesign/core build && pnpm -F @astryxdesign/sandbox dev","dev:sandbox:source": "pnpm generate:i18n-runtime && ASTRYX_SOURCE=1 pnpm -F @astryxdesign/sandbox dev",diff --git a/scripts/check-changesets.mjs b/scripts/check-changesets.mjsindex 22be7dc0d5..ef1921c1fe 100755--- a/scripts/check-changesets.mjs+++ b/scripts/check-changesets.mjs@@ -12,9 +12,11 @@* 2. Every changeset body must carry a recognized [category] tag.* 3. Every changeset body must credit at least one @contributor.* 4. Frontmatter packages must be real, publishable, non-ignored packages.- * 5. Patch-versus-minor admission (spec:AST-017 FR46-FR50): main targets a- * patch by default, so incompatible work is refused until an owner- * schedules a minor in `.release/target.json`. See release-admission.mjs.+ *+ * It checks each Changeset's format and nothing about which release will carry+ * it. Main's package.json declares the next planned version, and only a release+ * branch admits Changesets against it (spec:AST-017 FR46-FR50; see+ * release-admission.mjs and release/version-packages.mjs).** Exits 1 with a readable report on any violation. config.json and README.md* are skipped.@@ -25,25 +27,21 @@ import path from 'node:path';import {fileURLToPath} from 'node:url';import {createRequire} from 'node:module';import {expandWorkspaceDirs} from './lib/workspace-globs.mjs';-import {- checkAdmission,- utcToday,- TARGET_FILE,-} from './release-admission.mjs';const require = createRequire(import.meta.url);const {parseEntry} = require('./changeset-entry-format.cjs');const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');-const CS_DIR = path.join(ROOT, '.changeset');-function readConfig() {- return JSON.parse(fs.readFileSync(path.join(CS_DIR, 'config.json'), 'utf8'));+function readConfig(root) {+ return JSON.parse(+ fs.readFileSync(path.join(root, '.changeset', 'config.json'), 'utf8'),+ );}-function discoverPackages() {+function discoverPackages(root) {const pkgs = [];- for (const dir of expandWorkspaceDirs(ROOT)) {+ for (const dir of expandWorkspaceDirs(root)) {const pj = path.join(dir, 'package.json');if (!fs.existsSync(pj)) continue;const p = JSON.parse(fs.readFileSync(pj, 'utf8'));@@ -69,27 +67,6 @@ function isChangesetFile(name) {return name.endsWith('.md') && !SKIP.has(name);}-/**- * Read the owner's minor schedule, when one is set. Absent is the ordinary- * case and means main is on its patch default. Present but unreadable is an- * untrustworthy input, so it is reported and main stays on the default.- *- * @param {string} root- * @returns {{target: unknown|null, problems: string[]}}- */-function readSchedule(root) {- const file = path.join(root, TARGET_FILE);- if (!fs.existsSync(file)) return {target: null, problems: []};- try {- return {target: JSON.parse(fs.readFileSync(file, 'utf8')), problems: []};- } catch (err) {- return {- target: null,- problems: [`${TARGET_FILE}: is not valid JSON (${err.message}).`],- };- }-}-/*** Validate one changeset's contents against the conventions. Pure and* side-effect-free so it can be unit-tested without the filesystem.@@ -165,9 +142,16 @@ function validateChangeset(file, contents, ctx) {return problems;}-function main() {- const config = readConfig();- const pkgs = discoverPackages();+/**+ * Validate every pending Changeset at `root`. Reads no release version and no+ * tag: format, category, bump coupling, and package names only.+ *+ * @param {string} root+ * @returns {{files: string[], problems: string[], pre1: boolean}}+ */+function checkRepository(root) {+ const config = readConfig(root);+ const pkgs = discoverPackages(root);const pub = pkgs.filter(p => !p.private && !(config.ignore || []).includes(p.name),);@@ -177,38 +161,18 @@ function main() {pre1: pub.every(p => /^0\./.test(String(p.version || '0'))),};- const files = fs.readdirSync(CS_DIR).filter(isChangesetFile);+ const dir = path.join(root, '.changeset');+ const files = fs.readdirSync(dir).filter(isChangesetFile);const problems = [];- const entries = [];for (const f of files) {- const contents = fs.readFileSync(path.join(CS_DIR, f), 'utf8');+ const contents = fs.readFileSync(path.join(dir, f), 'utf8');problems.push(...validateChangeset(f, contents, ctx));-- // What the admission gate reads. A changeset whose frontmatter does not- // parse is already reported above; it contributes nothing here rather- // than a guessed category or bump.- const fm = parseFrontmatter(contents);- if (fm) {- entries.push({- file: f,- category: parseEntry(fm.summary).category,- releases: fm.releases,- });- }}+ return {files, problems, pre1: ctx.pre1};+}- const {target, problems: scheduleReadProblems} = readSchedule(ROOT);- problems.push(...scheduleReadProblems);-- const admission = checkAdmission({- fixedGroups: config.fixed || [],- versionByName: new Map(pub.map(p => [p.name, p.version])),- entries,- target,- today: utcToday(),- });- problems.push(...admission.problems);-+function main() {+ const {files, problems, pre1} = checkRepository(ROOT);if (problems.length) {console.error(`\n✗ check:changesets found ${problems.length} problem(s):\n`,@@ -218,14 +182,8 @@ function main() {process.exit(1);}- const mode =- admission.mode === 'minor'- ? ` — main targets ${admission.scheduled.version}, a minor scheduled for ${admission.scheduled.scheduledFor}`- : admission.base- ? ` — main targets a patch (published at ${admission.base})`- : '';console.log(- `✓ check:changesets — ${files.length} changeset(s) valid${ctx.pre1 ? ' (0.x: [breaking] -> minor, [experimental] and other categories -> patch)' : ''}${mode}`,+ `✓ check:changesets — ${files.length} changeset(s) valid${pre1 ? ' (0.x: [breaking] -> minor, [experimental] and other categories -> patch)' : ''}`,);}@@ -234,4 +192,4 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {main();}-export {validateChangeset, parseFrontmatter};+export {checkRepository, validateChangeset, parseFrontmatter};diff --git a/scripts/check-changesets.test.mjs b/scripts/check-changesets.test.mjsindex af82e5297f..6f7d01336f 100644--- a/scripts/check-changesets.test.mjs+++ b/scripts/check-changesets.test.mjs@@ -8,8 +8,11 @@* pre-1.0.*/-import {describe, it, expect} from 'vitest';-import {validateChangeset} from './check-changesets.mjs';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import {afterEach, describe, it, expect} from 'vitest';+import {checkRepository, validateChangeset} from './check-changesets.mjs';const ctx = {pre1: true,@@ -142,3 +145,80 @@ describe('validateChangeset — 0.x semver coupling', () => {expect(problems.some(p => /private\/ignored/.test(p))).toBe(true);});});++describe('checkRepository — main pull requests check format, not the release', () => {+ const roots = [];+ afterEach(() => {+ for (const root of roots.splice(0))+ fs.rmSync(root, {recursive: true, force: true});+ });++ function mainCheckout(version, changesets) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-main-cs-'));+ roots.push(root);+ const put = (file, text) => {+ fs.mkdirSync(path.dirname(path.join(root, file)), {recursive: true});+ fs.writeFileSync(path.join(root, file), text);+ };+ put('pnpm-workspace.yaml', "packages:\n - 'packages/*'\n");+ put(+ 'packages/core/package.json',+ JSON.stringify({name: '@astryxdesign/core', version}),+ );+ put(+ '.changeset/config.json',+ JSON.stringify({fixed: [['@astryxdesign/core']], ignore: []}),+ );+ for (const [name, text] of Object.entries(changesets))+ put(`.changeset/${name}.md`, text);+ return root;+ }++ it('accepts a [breaking] Changeset while main declares a patch (FR46)', () => {+ // Main at 0.6.7 is the next patch after 0.6.6. Release admission happens+ // on the release branch; main's check reads no release version or tag.+ const root = mainCheckout('0.6.7', {+ 'remove-thing': cs(+ `'@astryxdesign/core': minor`,+ '[breaking] Remove the old thing\n@person',+ ),+ });+ const result = checkRepository(root);+ expect(result.problems).toEqual([]);+ expect(result.files).toEqual(['remove-thing.md']);+ });++ it('accepts the same Changeset on a pre-bumped minor main', () => {+ const root = mainCheckout('0.7.0', {+ 'remove-thing': cs(+ `'@astryxdesign/core': minor`,+ '[breaking] Remove the old thing\n@person',+ ),+ });+ expect(checkRepository(root).problems).toEqual([]);+ });++ it('still refuses malformed Changesets on main', () => {+ const root = mainCheckout('0.6.7', {+ 'no-category': cs(`'@astryxdesign/core': patch`, 'Something\n@person'),+ 'wrong-bump': cs(+ `'@astryxdesign/core': patch`,+ '[breaking] Remove the old thing\n@person',+ ),+ });+ const {problems} = checkRepository(root);+ expect(problems.join('\n')).toMatch(+ /no-category\.md: body must start with a \[category\] tag/,+ );+ expect(problems.join('\n')).toMatch(+ /wrong-bump\.md: .* is a \[breaking\] change but declares "patch"/,+ );+ });++ it('ignores any leftover schedule file', () => {+ const root = mainCheckout('0.6.7', {});+ fs.mkdirSync(path.join(root, '.release'));+ fs.writeFileSync(path.join(root, '.release/target.json'), 'not json');+ expect(checkRepository(root).problems).toEqual([]);+ });+});diff --git a/scripts/release-admission.mjs b/scripts/release-admission.mjsindex adef20791c..c4b155c2d1 100644--- a/scripts/release-admission.mjs+++ b/scripts/release-admission.mjs@@ -1,34 +1,32 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file Patch-versus-minor admission for Changesets.+ * @file Release-version admission for a release branch.*- * Implements `spec:AST-017` FR46-FR50. The publishable packages are a `fixed`- * group, so one `[breaking]` Changeset moves every package to a new minor.- * This gate makes that deliberate:+ * Implements `spec:AST-017` FR46-FR50. Main's package.json carries the next+ * planned version for the fixed package group, and a release branch releases+ * exactly that version:*- * main targets a PATCH by default -> incompatible work is refused- * an owner SCHEDULES a minor first -> incompatible work may land+ * main declares the next version; publishes canaries only+ * release branch admits pending Changesets against that declared version*- * The schedule is one small file, `.release/target.json`, carrying a version- * and a day and nothing else. Pending Changesets never set the mode: the entry- * being judged cannot be its own authorization.+ * The declared version must be the patch or minor successor of the latest+ * stable release, and that choice is the release tier. Incompatible Changesets+ * are admissible only in a minor release. A Changeset never moves the version:+ * the owner sets it on main before the cut.*- * This answers patch-versus-minor and nothing else. Deprecation lifecycle,- * cleanup ids, release planning, and ordinary review live where they already- * live and are not enforced here.+ * This answers one question — does this release admit these Changesets — and+ * nothing else. Deprecation lifecycle, cleanup ids, release planning, and+ * ordinary review live where they already live and are not enforced here.+ * Pull-request CI on main does not run it.*- * @input fixed groups, package versions, parsed Changesets, optional target- * @output {mode, problems} — problems empty means admissible- * @position scripts/ — consumed by check-changesets.mjs+ * @input fixed groups, package versions, parsed Changesets, latest stable tag+ * @output {declared, latestStable, tier, problems} — problems empty means admissible+ * @position scripts/ — consumed by release-branch tooling under scripts/release*/-/** Where an owner schedules the next minor, when one is scheduled. */-export const TARGET_FILE = '.release/target.json';-const STABLE_VERSION = /^(\d+)\.(\d+)\.(\d+)$/;-const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/;-const TARGET_KEYS = ['version', 'scheduledFor'];+const STABLE_TAG = /^v(\d+\.\d+\.\d+)$/;/*** Is this Changeset incompatible?@@ -59,31 +57,48 @@ export function patchSuccessor(base) {}/**- * Is this a day that exists? `Date.parse` silently rolls an impossible date- * forward — `2026-02-30` becomes March 2 — so compare the round trip instead- * of trusting the parse to fail.+ * Order two MAJOR.MINOR.PATCH versions.*- * @param {string} day already matched against YYYY-MM-DD- * @returns {boolean}+ * @param {string} a+ * @param {string} b+ * @returns {number} negative, zero, or positive*/-function isRealDay(day) {- const parsed = new Date(`${day}T00:00:00Z`);- return (- !Number.isNaN(parsed.getTime()) &&- parsed.toISOString().slice(0, 10) === day- );+export function compareVersions(a, b) {+ const pa = STABLE_VERSION.exec(a);+ const pb = STABLE_VERSION.exec(b);+ if (!pa || !pb) throw new Error(`cannot compare "${a}" with "${b}"`);+ for (let i = 1; i <= 3; i += 1) {+ const delta = Number(pa[i]) - Number(pb[i]);+ if (delta !== 0) return delta;+ }+ return 0;+}++/**+ * The newest stable release among `vX.Y.Z` tags. Prerelease and canary tags+ * are publication metadata and never a release base.+ *+ * @param {string[]} tags+ * @returns {string|null}+ */+export function latestStableVersion(tags) {+ const versions = (tags || [])+ .map(tag => STABLE_TAG.exec(tag.trim())?.[1])+ .filter(Boolean);+ if (versions.length === 0) return null;+ return versions.sort(compareVersions).at(-1);}/**- * The version the published packages share. The fixed group publishes as one- * version, so a group whose members disagree has no base, and a prerelease or- * canary identifier is publication metadata rather than a base.+ * The version main declares for the fixed group. The group publishes as one+ * version, so members that disagree declare nothing, and a prerelease or+ * canary identifier is never a declared release version.** @param {string[][]} fixedGroups* @param {Map<string,string>} versionByName- * @returns {{base: string|null, problems: string[]}}+ * @returns {{declared: string|null, problems: string[]}}*/-export function deriveBase(fixedGroups, versionByName) {+export function declaredVersion(fixedGroups, versionByName) {const problems = [];const seen = new Map();@@ -93,7 +108,7 @@ export function deriveBase(fixedGroups, versionByName) {if (version === undefined) continue;if (!STABLE_VERSION.test(version)) {problems.push(- `${name}: version "${version}" is not MAJOR.MINOR.PATCH. A prerelease or canary identifier is never the published version this gate reads.`,+ `${name}: version "${version}" is not MAJOR.MINOR.PATCH. A prerelease or canary identifier is never a declared release version.`,);continue;}@@ -104,153 +119,100 @@ export function deriveBase(fixedGroups, versionByName) {if (seen.size > 1) {const spread = [...seen.entries()]- .sort((a, b) => (a[0] < b[0] ? -1 : 1))+ .sort((a, b) => compareVersions(a[0], b[0])).map(([version, names]) => `${version} (${names.join(', ')})`).join('; ');problems.push(- `the published packages do not share one version: ${spread}. They publish together, so there is nothing to check a scheduled minor against.`,+ `the fixed package group does not declare one version: ${spread}. The group releases together, so it must carry one version.`,);}+ if (seen.size === 0 && problems.length === 0) {+ problems.push('the fixed package group declares no version.');+ }- if (problems.length) return {base: null, problems};- return {base: seen.size === 1 ? [...seen.keys()][0] : null, problems};+ if (problems.length) return {declared: null, problems};+ return {declared: [...seen.keys()][0], problems};}/**- * FR47/FR49 — read the owner's schedule.- *- * Returns `minor` only for a statement that can be read with certainty and- * still applies. Anything else leaves main on its patch default and says why,- * rather than inheriting a mode from an input nobody can trust.+ * FR47/FR49 — which tier the declared version is.** @param {object} input- * @param {unknown} input.target parsed .release/target.json, or null when absent- * @param {string|null} input.base- * @param {string} input.today YYYY-MM-DD- * @returns {{mode: 'patch'|'minor', scheduled: object|null, problems: string[]}}+ * @param {string|null} input.declared+ * @param {string|null} input.latestStable+ * @returns {{tier: 'patch'|'minor'|null, problems: string[]}}*/-export function readSchedule({target, base, today}) {- if (target === null || target === undefined) {- return {mode: 'patch', scheduled: null, problems: []};- }-- const problems = [];- const deny = reason => {- problems.push(`${TARGET_FILE}: ${reason}`);- return {mode: 'patch', scheduled: null, problems};- };-- if (typeof target !== 'object' || Array.isArray(target)) {- return deny('must be a JSON object with exactly "version" and "scheduledFor".');- }-- const keys = Object.keys(target).sort();- if (keys.join(',') !== TARGET_KEYS.slice().sort().join(',')) {- return deny(- `must carry exactly "version" and "scheduledFor" — found ${keys.length ? keys.map(k => `"${k}"`).join(', ') : 'nothing'}. This file schedules a minor; it records nothing else.`,- );- }-- if (typeof target.version !== 'string' || !STABLE_VERSION.test(target.version)) {- return deny(`"version" must be a MAJOR.MINOR.PATCH version.`);+export function releaseTier({declared, latestStable}) {+ if (!declared) return {tier: null, problems: []};+ if (!latestStable) {+ return {+ tier: null,+ problems: [+ `no stable vX.Y.Z release tag is available, so the declared ${declared} cannot be placed in a tier.`,+ ],+ };}- if (- typeof target.scheduledFor !== 'string' ||- !ISO_DAY.test(target.scheduledFor) ||- !isRealDay(target.scheduledFor)- ) {- return deny(`"scheduledFor" must be a real YYYY-MM-DD day.`);- }-- if (!base) {- return deny(- `cannot be checked, because the published packages do not share one version.`,- );- }-- const expected = minorSuccessor(base);- if (target.version !== expected) {- return deny(- `schedules ${target.version}, but the published packages are at ${base}, whose next minor is ${expected}. The schedule and the repository disagree.`,- );+ if (declared === patchSuccessor(latestStable)) {+ return {tier: 'patch', problems: []};}-- if (target.scheduledFor < today) {- return deny(- `was scheduled for ${target.scheduledFor}, which has passed. Cut the minor or remove this file; an expired schedule does not keep admitting breaking changes.`,- );+ if (declared === minorSuccessor(latestStable)) {+ return {tier: 'minor', problems: []};}-- return {mode: 'minor', scheduled: {...target}, problems};+ const problem =+ compareVersions(declared, latestStable) <= 0+ ? `main declares ${declared}, which is not newer than the latest stable release ${latestStable}. A release owner bumps main to the next planned version (${patchSuccessor(latestStable)} or ${minorSuccessor(latestStable)}) before the cut.`+ : `main declares ${declared}, but the latest stable release is ${latestStable}; the next release is ${patchSuccessor(latestStable)} or ${minorSuccessor(latestStable)}.`;+ return {tier: null, problems: [problem]};}/**- * FR50 — the refusal. Names what main is targeting and both ways forward,+ * FR48/FR50 — the refusal. Names the declared release and both ways forward,* and names no particular version, surface, or contributor as a special case:* every value is read from the tree being checked.** @param {string} file- * @param {string|null} base+ * @param {string} declared+ * @param {string} latestStable* @returns {string}*/-function refuse(file, base) {- const patch = patchSuccessor(base);- const minor = minorSuccessor(base);- const heading = patch- ? `${file}: this entry is incompatible, and main is targeting ${patch} — a patch.`- : `${file}: this entry is incompatible, and main is targeting a patch.`;-+function refuse(file, declared, latestStable) {+ const minor = minorSuccessor(latestStable);return (- `${heading}\n` +- ` The published packages release together, so admitting it would move all of\n` +- ` them${minor ? ` to ${minor}` : ' to a new minor'}.\n` ++ `${file}: this entry is incompatible, and this release is ${declared} — a patch of ${latestStable}.\n` ++ ` Incompatible work ships only in a minor release.\n` +` Either keep the release patch-compatible: leave the released surface working\n` +` and deprecate it instead (AST-017 FR28) — ship the replacement, keep old usage\n` +- ` equivalent, and take the patch bump; the removal lands once a minor is\n` +- ` scheduled.\n` +- ` Or schedule that minor first (AST-017 FR47): a release owner adds\n` +- ` ${TARGET_FILE} with the target version and the day it is scheduled for.`+ ` equivalent, and let the removal ship in a minor release.\n` ++ ` Or plan the minor (AST-017 FR47): a release owner bumps main's fixed-group\n` ++ ` version to ${minor} before the next cut.`);}/**- * FR46-FR50 — decide what this tree admits.+ * FR46-FR50 — decide what this release admits.** @param {object} input* @param {string[][]} input.fixedGroups* @param {Map<string,string>} input.versionByName* @param {Array<{file: string, category: string|null, releases: Record<string,string>}>} input.entries- * @param {unknown} [input.target] parsed schedule, or null when absent- * @param {string} input.today YYYY-MM-DD- * @returns {{base: string|null, mode: 'patch'|'minor', scheduled: object|null, problems: string[]}}+ * @param {string|null} input.latestStable newest stable release version+ * @returns {{declared: string|null, latestStable: string|null, tier: 'patch'|'minor'|null, problems: string[]}}*/export function checkAdmission({fixedGroups,versionByName,entries,- target = null,- today,+ latestStable,}) {- const incompatible = (entries || []).filter(isIncompatible);- const {base, problems: baseProblems} = deriveBase(fixedGroups, versionByName);-- // The base matters only when there is a schedule to check it against or- // incompatible work to judge. Staying quiet otherwise keeps this gate to the- // one question it answers.- const problems =- target !== null || incompatible.length > 0 ? [...baseProblems] : [];+ const {declared, problems} = declaredVersion(fixedGroups, versionByName);+ const tier = releaseTier({declared, latestStable});+ problems.push(...tier.problems);- const schedule = readSchedule({target, base, today});- problems.push(...schedule.problems);-- if (schedule.mode === 'patch') {- for (const entry of incompatible) problems.push(refuse(entry.file, base));+ if (tier.tier === 'patch') {+ for (const entry of (entries || []).filter(isIncompatible)) {+ problems.push(refuse(entry.file, declared, latestStable));+ }}- return {base, mode: schedule.mode, scheduled: schedule.scheduled, problems};-}--/** Today in UTC, as the YYYY-MM-DD the schedule is compared against. */-export function utcToday(now = new Date()) {- return now.toISOString().slice(0, 10);+ return {declared, latestStable, tier: tier.tier, problems};}diff --git a/scripts/release-admission.test.mjs b/scripts/release-admission.test.mjsindex 1fd6e99fb0..2994418b15 100644--- a/scripts/release-admission.test.mjs+++ b/scripts/release-admission.test.mjs@@ -2,26 +2,27 @@/*** @file release-admission.test.mjs- * Patch-versus-minor admission (`spec:AST-017` FR46-FR50).+ * Release-version admission (`spec:AST-017` FR46-FR50).*- * Narrow on purpose: this gate answers one question, so the cases are the- * states of that question. No version, package, or surface in these fixtures- * is a real one — the rule must read the same for any release.+ * Main declares the next version; a release branch admits Changesets against+ * it. No version, package, or surface in these fixtures is a real one — the+ * rule must read the same for any release.*/import {describe, it, expect} from 'vitest';import {checkAdmission,+ compareVersions,+ declaredVersion,isIncompatible,+ latestStableVersion,minorSuccessor,- readSchedule,- utcToday,- TARGET_FILE,+ patchSuccessor,+ releaseTier,} from './release-admission.mjs';const GROUP = ['@scope/a', '@scope/b', '@scope/c'];const FIXED = [GROUP];-const TODAY = '2026-03-10';const versions = (v, overrides = {}) =>new Map(GROUP.map(name => [name, overrides[name] ?? v]));@@ -30,194 +31,170 @@ const entry = (file, category, releases) => ({file, category, releases});const compatible = file => entry(file, 'fix', {'@scope/a': 'patch'});const breaking = file => entry(file, 'breaking', {'@scope/a': 'minor'});-/** A valid schedule for the minor after 1.2.3. */-const schedule = (overrides = {}) => ({- version: '1.3.0',- scheduledFor: '2026-03-20',- ...overrides,-});--const run = (input = {}) =>+const run = (declared, input = {}) =>checkAdmission({fixedGroups: FIXED,- versionByName: versions('1.2.3'),+ versionByName: versions(declared),entries: [],- target: null,- today: TODAY,+ latestStable: '1.2.3',...input,});-describe('FR46/FR48 — main targets a patch by default', () => {- it('denies a breaking Changeset with no schedule', () => {- const result = run({entries: [compatible('a.md'), breaking('b.md')]});- expect(result.mode).toBe('patch');- expect(result.problems).toHaveLength(1);- expect(result.problems[0]).toMatch(/^b\.md: this entry is incompatible/);+describe('FR47/FR48 — a declared minor admits breaking work at that version', () => {+ it('admits a breaking Changeset when main already declares the minor', () => {+ const result = run('1.3.0', {+ entries: [breaking('remove-thing.md'), compatible('a.md')],+ });+ expect(result).toMatchObject({+ declared: '1.3.0',+ latestStable: '1.2.3',+ tier: 'minor',+ problems: [],+ });});- it('allows compatible work with no schedule', () => {- const result = run({entries: [compatible('a.md'), compatible('b.md')]});+ it('admits every breaking Changeset in a minor, with no per-change record', () => {+ const result = run('1.3.0', {+ entries: [breaking('one.md'), breaking('two.md'), breaking('three.md')],+ });expect(result.problems).toEqual([]);- expect(result.mode).toBe('patch');});- it('needs no file to be on the default', () => {- expect(run({entries: []})).toMatchObject({mode: 'patch', problems: []});+ it('never derives a later version from the pending Changesets', () => {+ // A pre-bumped minor plus a [breaking] entry is still that minor; the+ // Changeset's own `minor` bump is the tier it needs, not a further bump.+ const result = run('1.3.0', {entries: [breaking('b.md')]});+ expect(result.declared).toBe('1.3.0');+ expect(minorSuccessor(result.declared)).toBe('1.4.0');+ expect(result.problems.join('\n')).not.toContain('1.4.0');});});-describe('FR47 — an explicitly scheduled minor admits breaking work', () => {- it('allows a breaking Changeset once the minor is scheduled', () => {- const result = run({- entries: [breaking('remove-thing.md'), compatible('a.md')],- target: schedule(),+describe('FR48 — a declared patch refuses incompatible work', () => {+ it('admits compatible work in a patch release', () => {+ const result = run('1.2.4', {+ entries: [compatible('a.md'), compatible('b.md')],});- expect(result.problems).toEqual([]);- expect(result.mode).toBe('minor');- expect(result.scheduled).toEqual(schedule());+ expect(result).toMatchObject({tier: 'patch', problems: []});});- it('admits every breaking Changeset while scheduled, with no per-change record', () => {- const result = run({- entries: [breaking('one.md'), breaking('two.md')],- target: schedule(),+ it('refuses a breaking Changeset in a patch release', () => {+ const result = run('1.2.4', {+ entries: [compatible('a.md'), breaking('b.md')],});- expect(result.problems).toEqual([]);+ expect(result.tier).toBe('patch');+ expect(result.problems).toHaveLength(1);+ expect(result.problems[0]).toMatch(/^b\.md: this entry is incompatible/);});- it('never lets a pending Changeset set the mode by itself', () => {- // The circularity this gate exists to avoid: the entry being judged is- // not evidence for the mode that would admit it.- expect(run({entries: [breaking('b.md')]}).mode).toBe('patch');+ it('reads a minor bump alone as incompatible, failing closed', () => {+ const result = run('1.2.4', {+ entries: [entry('m.md', 'feat', {'@scope/a': 'minor'})],+ });+ expect(result.problems).toHaveLength(1);});- it('reads a declared minor as incompatible even without the category', () => {- expect(isIncompatible(entry('x.md', 'fix', {'@scope/a': 'minor'}))).toBe(true);- expect(isIncompatible(entry('x.md', 'fix', {'@scope/a': 'patch'}))).toBe(false);- expect(run({entries: [entry('sneaky.md', 'fix', {'@scope/a': 'minor'})]})- .problems).toHaveLength(1);+ it('admits a deprecation in a patch release', () => {+ const result = run('1.2.4', {+ entries: [entry('dep.md', 'feat', {'@scope/a': 'patch'})],+ });+ expect(result.problems).toEqual([]);});-});--describe('FR49 — the schedule fails closed', () => {- const denied = target => {- const result = run({entries: [breaking('b.md')], target});- expect(result.mode).toBe('patch');- return result.problems.join('\n');- };- it('denies a schedule carrying anything beyond the two fields', () => {- expect(denied(schedule({approvedBy: 'someone'}))).toMatch(- /must carry exactly "version" and "scheduledFor"/,- );+ it('names the declared release and both ways forward', () => {+ const [message] = run('1.2.4', {entries: [breaking('b.md')]}).problems;+ expect(message).toContain('this release is 1.2.4 — a patch of 1.2.3');+ expect(message).toContain('deprecate it instead (AST-017 FR28)');+ expect(message).toContain("bumps main's fixed-group");+ expect(message).toContain('version to 1.3.0 before the next cut');+ expect(message).not.toContain('target.json');});+});- it('denies a malformed version or day', () => {- expect(denied(schedule({version: '1.3'}))).toMatch(/"version" must be a/);- expect(denied(schedule({scheduledFor: 'soon'}))).toMatch(- /"scheduledFor" must be a real/,- );- expect(denied(schedule({scheduledFor: '2026-02-30'}))).toMatch(- /"scheduledFor" must be a real/,+describe('FR49 — the declared version fails closed', () => {+ it('refuses a version that is already released', () => {+ const result = run('1.2.3', {entries: [compatible('a.md')]});+ expect(result.tier).toBeNull();+ expect(result.problems[0]).toMatch(+ /declares 1\.2\.3, which is not newer than the latest stable release 1\.2\.3/,);});- it('denies a schedule that is not the minor after the published version', () => {- expect(denied(schedule({version: '1.2.4'}))).toMatch(- /schedules 1\.2\.4, but the published packages are at 1\.2\.3, whose next minor is 1\.3\.0/,- );- expect(denied(schedule({version: '2.0.0'}))).toMatch(/whose next minor is 1\.3\.0/);+ it('refuses a version that moves backward', () => {+ expect(run('1.2.0').problems[0]).toMatch(/not newer than/);});- it('denies a schedule whose day has passed', () => {- expect(denied(schedule({scheduledFor: '2026-03-09'}))).toMatch(- /was scheduled for 2026-03-09, which has passed/,+ it('refuses a version that skips a release', () => {+ expect(run('1.2.5').problems[0]).toMatch(+ /the next release is 1\.2\.4 or 1\.3\.0/,);- });-- it('still admits on the scheduled day itself', () => {- const result = run({- entries: [breaking('b.md')],- target: schedule({scheduledFor: TODAY}),- });- expect(result.problems).toEqual([]);- expect(result.mode).toBe('minor');- });-- it('denies when the published packages disagree', () => {- const result = run({- entries: [breaking('b.md')],- versionByName: versions('1.2.3', {'@scope/c': '1.2.4'}),- target: schedule(),- });- expect(result.mode).toBe('patch');- expect(result.problems.join('\n')).toMatch(- /do not share one version: 1\.2\.3 .*; 1\.2\.4/,+ expect(run('1.4.0').problems[0]).toMatch(+ /the next release is 1\.2\.4 or 1\.3\.0/,);+ expect(run('2.0.0').tier).toBeNull();});- it('denies a prerelease or canary identifier as the published version', () => {- const result = run({- entries: [breaking('b.md')],- versionByName: versions('1.2.3', {'@scope/b': '1.2.3-canary.abc1234'}),- target: schedule(),- });- expect(result.problems.join('\n')).toMatch(/is never the published version/);+ it('refuses when no stable release exists to compare against', () => {+ const result = run('1.3.0', {latestStable: null});+ expect(result.tier).toBeNull();+ expect(result.problems[0]).toMatch(/no stable vX\.Y\.Z release tag/);});- it('stays quiet about the published version when nothing asks', () => {- // No schedule and no incompatible work: the base is not this gate's- // business, so a disagreement is not reported here.- const result = run({- entries: [compatible('a.md')],- versionByName: versions('1.2.3', {'@scope/c': '1.2.4'}),+ it('refuses a group whose members disagree', () => {+ const result = checkAdmission({+ fixedGroups: FIXED,+ versionByName: versions('1.3.0', {'@scope/c': '1.2.4'}),+ entries: [],+ latestStable: '1.2.3',});- expect(result.problems).toEqual([]);+ expect(result.declared).toBeNull();+ expect(result.problems[0]).toMatch(/does not declare one version/);});-});--describe('FR50 — switching back, and the refusal', () => {- it('returns to the patch default when the schedule is removed', () => {- const scheduled = run({entries: [breaking('b.md')], target: schedule()});- expect(scheduled.problems).toEqual([]);- const afterRemoval = run({entries: [breaking('b.md')], target: null});- expect(afterRemoval.mode).toBe('patch');- expect(afterRemoval.problems).toHaveLength(1);- });-- it('names what main targets and both ways forward', () => {- const refusal = run({entries: [breaking('remove-thing.md')]}).problems[0];- expect(refusal).toMatch(/remove-thing\.md/);- expect(refusal).toMatch(/main is targeting 1\.2\.4 — a patch/);- expect(refusal).toMatch(/would move all of\s+them to 1\.3\.0/);- expect(refusal).toMatch(/deprecate it instead \(AST-017 FR28\)/);- expect(refusal).toMatch(/schedule that minor first \(AST-017 FR47\)/);- expect(refusal).toContain(TARGET_FILE);- });-- it('hard-codes no version, surface, package, or contributor', () => {- const refusal = run({entries: [breaking('b.md')]}).problems[0];- expect(refusal).not.toMatch(/layout|astryx|0\.6\.|0\.7\./i);+ it('never treats a canary as a declared version', () => {+ const {declared, problems} = declaredVersion(+ FIXED,+ versions('1.3.0-canary.abc1234'),+ );+ expect(declared).toBeNull();+ expect(problems.join('\n')).toMatch(/never a declared release version/);+ });++ it('takes the base from the newest stable tag only', () => {+ expect(+ latestStableVersion([+ 'v1.2.3',+ 'v1.10.0',+ 'v1.9.9',+ 'v2.0.0-canary.1',+ 'v1.11.0-rc.1',+ 'nope',+ ]),+ ).toBe('1.10.0');+ expect(latestStableVersion([])).toBeNull();});});describe('helpers', () => {- it('computes the next minor', () => {- expect(minorSuccessor('0.6.4')).toBe('0.7.0');- expect(minorSuccessor('1.2.3')).toBe('1.3.0');- expect(minorSuccessor('nope')).toBeNull();- });-- it('treats an absent schedule as the default, not an error', () => {- expect(readSchedule({target: null, base: '1.2.3', today: TODAY})).toEqual({- mode: 'patch',- scheduled: null,- problems: [],- });- });-- it('formats today as a UTC calendar day', () => {- expect(utcToday(new Date('2026-03-10T23:30:00Z'))).toBe('2026-03-10');+ it('orders versions numerically', () => {+ expect(compareVersions('1.10.0', '1.9.9')).toBeGreaterThan(0);+ expect(compareVersions('0.6.7', '0.7.0')).toBeLessThan(0);+ expect(compareVersions('0.7.0', '0.7.0')).toBe(0);+ });++ it('places a declared version in its tier', () => {+ expect(+ releaseTier({declared: patchSuccessor('0.6.6'), latestStable: '0.6.6'})+ .tier,+ ).toBe('patch');+ expect(+ releaseTier({declared: minorSuccessor('0.6.6'), latestStable: '0.6.6'})+ .tier,+ ).toBe('minor');+ });++ it('classifies incompatibility from category or bump', () => {+ expect(isIncompatible(breaking('x'))).toBe(true);+ expect(isIncompatible(compatible('x'))).toBe(false);});});diff --git a/scripts/release/active-release.mjs b/scripts/release/active-release.mjsindex 979f862805..547b3d91bd 100644--- a/scripts/release/active-release.mjs+++ b/scripts/release/active-release.mjs@@ -3,9 +3,16 @@/*** @file Active release branch authority and receipt validation.*+ * A release branch releases the fixed-group version main declared at its cut+ * (spec:AST-017 FR47); main publishes canaries only and its versions never move+ * backward (FR46, FR50).+ ** @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+ *+ * CI copies this file and lib/workspace-globs.mjs alone as trusted policy, so+ * it imports nothing else at module load.*/import crypto from 'node:crypto';@@ -41,6 +48,15 @@ function canonicalJson(value) {return JSON.stringify(value);}+/** Order two X.Y.Z versions; null when either is not X.Y.Z. */+function compareVersions(a, b) {+ if (!VERSION_RE.test(a ?? '') || !VERSION_RE.test(b ?? '')) return null;+ const pa = a.split('.').map(Number);+ const pb = b.split('.').map(Number);+ for (let i = 0; i < 3; i += 1) if (pa[i] !== pb[i]) return pa[i] - pb[i];+ return 0;+}+function computePlanDigest(plan) {return sha256(canonicalJson(plan));}@@ -220,15 +236,16 @@ function validateReleaseState({}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}`,- );- }+ } else if (current.size !== 0) {+ errors.push('versioned release must consume every branch Changeset');+ }+ // FR47: the branch releases the version main declared at the cut, before and+ // after its Changesets are consumed.+ 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;}@@ -237,6 +254,17 @@ function git(root, args) {return execFileSync('git', args, {cwd: root, encoding: 'utf8'}).trim();}+/** The highest local stable vX.Y.Z tag, or null when none exists. */+function latestStableVersion(root) {+ const versions = git(root, ['tag', '--list', 'v*'])+ .split('\n')+ .filter(Boolean)+ .map(tag => tag.slice(1))+ .filter(version => VERSION_RE.test(version))+ .sort((a, b) => compareVersions(a, b));+ return versions.at(-1) ?? null;+}+function fileDigestAtRef(root, ref, file) {try {return sha256(execFileSync('git', ['show', `${ref}:${file}`], {cwd: root}));@@ -288,7 +316,13 @@ function releaseOutputMapAtRef(root, plan, releaseRef) {function jsonAtRef(root, ref, file) {try {- return JSON.parse(git(root, ['show', `${ref}:${file}`]));+ return JSON.parse(+ execFileSync('git', ['show', `${ref}:${file}`], {+ cwd: root,+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'ignore'],+ }),+ );} catch {return null;}@@ -434,49 +468,75 @@ const VERSION_DEPENDENCY_FIELDS = ['optionalDependencies','peerDependencies',];+const EXACT_SPEC_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;-function expectedSyncedManifest({file, cut, base, release}) {- if (!cut || !base || !release)- return {error: `release sync cannot read manifest history: ${file}`};+function patchSuccessor(version) {+ if (!VERSION_RE.test(version ?? '')) return null;+ const [major, minor, patch] = version.split('.').map(Number);+ return `${major}.${minor}.${patch + 1}`;+}- const releaseFromCut = structuredClone(cut);- releaseFromCut.version = release.version;+/**+ * FR50 — the version main declares after syncing a release: the higher of+ * main's version and the released version's patch successor. Main declares+ * the next patch by default and keeps an owner's higher bump.+ *+ * @param {string} mainVersion main's fixed-group version at the sync base+ * @param {string} releaseVersion the published version+ * @returns {string|null}+ */+function syncedMainVersion(mainVersion, releaseVersion) {+ const next = patchSuccessor(releaseVersion);+ const order = compareVersions(mainVersion, next);+ if (next === null || order === null) return null;+ return order >= 0 ? mainVersion : next;+}++/**+ * A main manifest after sync: fixed-group members carry `version`, and every+ * exact internal pin on a fixed-group package points at it, the way+ * sync-internal-deps keeps them. Nothing else changes.+ */+function syncedManifest(base, {version, fixedNames}) {const expected = structuredClone(base);- expected.version = release.version;+ if (fixedNames.has(base.name)) expected.version = version;+ for (const field of VERSION_DEPENDENCY_FIELDS) {+ for (const [name, spec] of Object.entries(expected[field] ?? {})) {+ if (fixedNames.has(name) && EXACT_SPEC_RE.test(spec))+ expected[field][name] = version;+ }+ }+ return expected;+}+/**+ * The release bump may change a published manifest's version and internal+ * pins only.+ */+function releaseManifestChangeError({file, cut, release}) {+ if (!cut || !release)+ return `release sync cannot read manifest history: ${file}`;+ const releaseFromCut = structuredClone(cut);+ releaseFromCut.version = release.version;for (const field of VERSION_DEPENDENCY_FIELDS) {const cutValues = cut[field] ?? {};const releaseValues = release[field] ?? {};- const names = new Set([+ for (const name of new Set([...Object.keys(cutValues),...Object.keys(releaseValues),- ]);- for (const name of names) {+ ])) {if (canonicalJson(cutValues[name]) === canonicalJson(releaseValues[name]))continue;if (!name.startsWith('@astryxdesign/'))- return {- error: `published manifest contains a non-version release change: ${file} ${field}.${name}`,- };+ return `published manifest contains a non-version release change: ${file} ${field}.${name}`;releaseFromCut[field] ??= {};if (releaseValues[name] === undefined) delete releaseFromCut[field][name];else releaseFromCut[field][name] = releaseValues[name];-- if (- canonicalJson(base[field]?.[name]) === canonicalJson(cutValues[name])- ) {- expected[field] ??= {};- if (releaseValues[name] === undefined) delete expected[field][name];- else expected[field][name] = releaseValues[name];- }}}-- if (canonicalJson(releaseFromCut) !== canonicalJson(release))- return {- error: `published manifest contains a non-version release change: ${file}`,- };- return {expected};+ return canonicalJson(releaseFromCut) === canonicalJson(release)+ ? null+ : `published manifest contains a non-version release change: ${file}`;}function validateReleaseSync({@@ -487,9 +547,11 @@ function validateReleaseSync({releaseOutputs,headOutputs,releaseRenames = new Set(),+ releaseVersion,+ fixedNames = new Set(),cutManifests = new Map(),- baseManifests = new Map(),releaseManifests = new Map(),+ baseManifests = new Map(),headManifests = new Map(),}) {const errors = [];@@ -519,9 +581,9 @@ function validateReleaseSync({`release sync may only delete frozen Changesets: ${file}`,);} else if (isPackageManifestPath(file)) {- if (!releaseManifests.has(file))+ if (!baseManifests.has(file))errors.push(- `release sync changed an unplanned package manifest: ${file}`,+ `release sync changed an unknown package manifest: ${file}`,);} else if (!isReleaseOutputPath(file) &&@@ -553,25 +615,118 @@ function validateReleaseSync({errors.push(`release sync output differs from published branch: ${file}`);}for (const [file, release] of releaseManifests) {- const result = expectedSyncedManifest({+ const error = releaseManifestChangeError({file,cut: cutManifests.get(file),- base: baseManifests.get(file),release,});- if (result.error) {- errors.push(result.error);+ if (error) errors.push(error);+ }++ // FR50: every main manifest moves to one synced version, never backward.+ const mainVersions = new Set(+ [...baseManifests.values()]+ .filter(manifest => manifest && fixedNames.has(manifest.name))+ .map(manifest => manifest.version),+ );+ if (mainVersions.size !== 1) {+ errors.push(+ `release sync needs one fixed-group version on main; found ${[...mainVersions].join(', ') || 'none'}`,+ );+ return errors;+ }+ const [mainVersion] = mainVersions;+ const version = syncedMainVersion(mainVersion, releaseVersion);+ if (version === null) {+ errors.push(+ `release sync cannot order main ${mainVersion} after release ${releaseVersion}`,+ );+ return errors;+ }+ for (const [file, base] of baseManifests) {+ if (!base) continue;+ const head = headManifests.get(file);+ if (!head) {+ errors.push(`release sync removed a package manifest: ${file}`);continue;}- const head = headManifests.get(file);- if (!head || head.version !== release.version)- errors.push(`release sync manifest has the wrong version: ${file}`);- if (canonicalJson(head) !== canonicalJson(result.expected))+ const expected = syncedManifest(base, {version, fixedNames});+ if (canonicalJson(head) === canonicalJson(expected)) continue;+ if (+ fixedNames.has(base.name) &&+ compareVersions(head.version, base.version) < 0+ )+ errors.push(+ `release sync moves main backward: ${file} ${base.version} -> ${head.version}`,+ );+ else if (head.version !== expected.version)+ errors.push(+ `release sync manifest has the wrong version: ${file} is ${head.version}, expected ${expected.version}`,+ );+ elseerrors.push(`release sync changed non-version manifest fields: ${file}`);}return errors;}+/**+ * FR46 — main's fixed-group version on a pull request into main.+ *+ * Main carries a malleable plan until cut. It may move up or down, but always+ * remains one plain version strictly above the newest stable release.+ *+ * @param {object} input+ * @param {string[]} input.fixed trusted fixed-group package names+ * @param {string} input.releasedVersion newest stable vX.Y.Z tag, without v+ * @param {Map<string, object|null>} input.headManifests name -> manifest at head+ * @param {boolean} [input.allowBootstrapEqual] one-time landing bridge when trusted main predates this validator+ * @returns {string[]}+ */+function validateMainVersions({+ fixed,+ releasedVersion,+ headManifests,+ allowBootstrapEqual = false,+}) {+ const errors = [];+ if (!VERSION_RE.test(releasedVersion ?? ''))+ errors.push('main version check needs the newest stable vX.Y.Z tag');+ const headVersions = new Set();+ for (const name of fixed) {+ const head = headManifests.get(name);+ if (!head || !isStableReleasePackage(head)) continue;+ if (!VERSION_RE.test(head.version ?? '')) {+ errors.push(`${name} is ${head.version}; main declares an X.Y.Z version`);+ continue;+ }+ headVersions.add(head.version);+ }+ if (headVersions.size !== 1) {+ errors.push(+ `the fixed group must declare one version on main; found ${[...headVersions].sort().join(', ') || 'none'}`,+ );+ return errors;+ }+ const [declaredVersion] = headVersions;+ const order = VERSION_RE.test(releasedVersion ?? '')+ ? compareVersions(declaredVersion, releasedVersion)+ : null;+ if (order < 0 || (order === 0 && !allowBootstrapEqual))+ errors.push(+ `main declares ${declaredVersion}; it must stay strictly above newest stable v${releasedVersion}`,+ );+ return errors;+}++function packageManifestsByName(read, root) {+ const manifests = new Map();+ for (const dir of expandWorkspaceDirs(root)) {+ const manifest = read(path.relative(root, path.join(dir, 'package.json')));+ if (manifest?.name) manifests.set(manifest.name, manifest);+ }+ return manifests;+}+function parseArgs(argv) {const [command, ...rest] = argv;const values = {};@@ -605,6 +760,52 @@ function versionTagExists(root, version) {}}+/**+ * FR47/FR49 — the fixed-group version main declared at `ref`.+ *+ * @param {string} root+ * @param {string} ref+ * @returns {{version: string|null, errors: string[]}}+ */+function declaredVersionAtRef(root, ref) {+ const config = jsonAtRef(root, ref, '.changeset/config.json');+ if (!config)+ return {+ version: null,+ errors: [`${ref} has no readable .changeset/config.json`],+ };+ const fixed = new Set((config.fixed ?? []).flat());+ const versions = new Map();+ for (const dir of expandWorkspaceDirs(root)) {+ const file = path.relative(root, path.join(dir, 'package.json'));+ const manifest = jsonAtRef(root, ref, file);+ if (!manifest || !fixed.has(manifest.name)) continue;+ if (!isStableReleasePackage(manifest)) continue;+ if (!versions.has(manifest.version)) versions.set(manifest.version, []);+ versions.get(manifest.version).push(manifest.name);+ }+ if (versions.size !== 1)+ return {+ version: null,+ errors: [+ `the fixed group at ${ref} must declare one version; found ${+ [...versions.entries()]+ .map(([v, names]) => `${v} (${names.join(', ')})`)+ .join('; ') || 'none'+ }`,+ ],+ };+ const [version] = versions.keys();+ if (!VERSION_RE.test(version))+ return {+ version: null,+ errors: [+ `the fixed group at ${ref} declares ${version}, which is not X.Y.Z`,+ ],+ };+ return {version, errors: []};+}+function writeAuthority(root, values, refresh) {const version = required(values, 'version');const branch = required(values, 'branch');@@ -617,6 +818,12 @@ function writeAuthority(root, values, refresh) {throw new Error('version, branch, and cut SHA do not form a valid release identity',);+ const declared = declaredVersionAtRef(root, cutSha);+ if (declared.errors.length) throw new Error(declared.errors.join('\n'));+ if (declared.version !== version)+ throw new Error(+ `main declares ${declared.version} at the cut, so the release is ${declared.version}, not ${version}`,+ );const dir = path.join(root, RELEASE_DIR);const markerPath = path.join(dir, MARKER_FILE);const planPath = path.join(dir, PLAN_FILE);@@ -661,10 +868,20 @@ function writeAuthority(root, values, refresh) {);}-function main() {+async function main() {const {command, values} = parseArgs(process.argv.slice(2));const root = path.resolve(values.root ?? ROOT);if (command === 'create' || command === 'refresh') {+ // FR48/FR49: admission runs where the plan is made. Loaded here so the+ // trusted CI copy of this file needs no other module.+ const {admitRelease} = await import('./release-inputs.mjs');+ const admission = admitRelease(root, {+ version: required(values, 'version'),+ });+ if (admission.problems.length)+ throw new Error(+ `release admission refused ${values.version}:\n${admission.problems.join('\n')}`,+ );writeAuthority(root, values, command === 'refresh');return;}@@ -706,6 +923,25 @@ function main() {);return;}+ if (command === 'validate-main-version') {+ const base = required(values, 'base');+ const config = jsonAtRef(root, base, '.changeset/config.json');+ if (!config)+ throw new Error(`cannot read trusted fixed group from ${base}`);+ const releasedVersion = latestStableVersion(root);+ const errors = validateMainVersions({+ fixed: (config.fixed ?? []).flat(),+ releasedVersion,+ allowBootstrapEqual: values['allow-bootstrap-equal'] === 'true',+ headManifests: packageManifestsByName(file => {+ const absolute = path.join(root, file);+ return fs.existsSync(absolute) ? readJson(absolute) : null;+ }, root),+ });+ if (errors.length) throw new Error(errors.join('\n'));+ console.log(JSON.stringify({base, releasedVersion, valid: true}));+ return;+ }if (command === 'validate-sync') {const base = required(values, 'base');const releaseRef = required(values, 'release-ref');@@ -761,12 +997,25 @@ function main() {plan.cutSha,releaseManifestFiles,);- const baseManifests = manifestMapAtRef(root, base, releaseManifestFiles);const releaseManifests = manifestMapAtRef(root,releaseRef,releaseManifestFiles,);+ // FR50 covers every package manifest on main, not only those the release+ // bump touched: sync advances main's declared version everywhere.+ const mainManifestFiles = git(root, [+ 'ls-tree',+ '-r',+ '--name-only',+ base,+ '--',+ 'packages',+ ])+ .split('\n')+ .filter(isPackageManifestPath);+ const baseManifests = manifestMapAtRef(root, base, mainManifestFiles);+ const baseConfig = jsonAtRef(root, base, '.changeset/config.json');errors.push(...validateReleaseSync({entries: raw ? raw.split('\n') : [],@@ -778,10 +1027,12 @@ function main() {releaseOutputs,headOutputs: currentOutputMap(root, releaseOutputs.keys()),releaseRenames,+ releaseVersion: marker.version,+ fixedNames: new Set((baseConfig?.fixed ?? []).flat()),cutManifests,- baseManifests,releaseManifests,- headManifests: currentManifestMap(root, releaseManifestFiles),+ baseManifests,+ headManifests: currentManifestMap(root, mainManifestFiles),}),);if (errors.length) throw new Error(errors.join('\n'));@@ -799,7 +1050,7 @@ function main() {}if (command !== 'validate')throw new Error(- 'command must be create, refresh, list-active, inspect-ref, validate-diff, validate-sync, or validate',+ 'command must be create, refresh, list-active, inspect-ref, validate-diff, validate-main-version, validate-sync, or validate',);const marker = readJson(path.join(root, RELEASE_DIR, MARKER_FILE));@@ -843,22 +1094,25 @@ function main() {}if (process.argv[1] === fileURLToPath(import.meta.url)) {- try {- main();- } catch (error) {+ main().catch(error => {console.error(`release authority validation failed: ${error.message}`);process.exit(1);- }+ });}export {buildMarker,buildPlan,canonicalJson,+ compareVersions,computePlanDigest,+ declaredVersionAtRef,+ syncedMainVersion,isStableReleasePackage,+ latestStableVersion,listActiveBranches,validateIdentity,+ validateMainVersions,validateRefMarker,validateReleaseDiff,validateReleaseState,diff --git a/scripts/release/active-release.test.mjs b/scripts/release/active-release.test.mjsindex e593fa2d75..b99040ec40 100644--- a/scripts/release/active-release.test.mjs+++ b/scripts/release/active-release.test.mjs@@ -16,6 +16,10 @@ import {afterEach, describe, expect, it} from 'vitest';import {buildMarker,buildPlan,+ declaredVersionAtRef,+ latestStableVersion,+ syncedMainVersion,+ validateMainVersions,validateReleaseDiff,validateReleaseState,validateReleaseSync,@@ -56,6 +60,37 @@ function fixture({withChangeset = false} = {}) {return {root, plan, marker};}+function git(root, ...args) {+ return execFileSync('git', args, {cwd: root, encoding: 'utf8'}).trim();+}++/**+ * A committed fixture whose fixed group declares `version` at the cut commit,+ * the way main's package.json does at a release cut.+ */+function cutFixture(version = '0.6.5') {+ const state = fixture({withChangeset: true});+ const {root} = state;+ fs.writeFileSync(+ path.join(root, '.changeset/config.json'),+ JSON.stringify({fixed: [['@astryxdesign/core']]}),+ );+ fs.writeFileSync(+ path.join(root, 'packages/core/package.json'),+ JSON.stringify({name: '@astryxdesign/core', version}, null, 2),+ );+ fs.writeFileSync(+ path.join(root, '.changeset/in-cut.md'),+ "---\n'@astryxdesign/core': patch\n---\n\n[fix] Included\n@person\n",+ );+ git(root, 'init', '-q');+ git(root, 'config', 'user.name', 'Release Test');+ git(root, 'config', 'user.email', '[email protected]');+ git(root, 'add', '.');+ git(root, 'commit', '-qm', 'cut');+ return {...state, cutSha: git(root, 'rev-parse', 'HEAD')};+}+function validate(state, overrides = {}) {return validateReleaseState({...state,@@ -79,14 +114,15 @@ afterEach(() => {});describe('one branch per release lifecycle', () => {- const values = {+ const identity = cutSha => ({version: '0.6.5',branch: BRANCH,- 'cut-sha': CUT,- };+ 'cut-sha': cutSha,+ });it('allows an explicit plan revision only within the same active identity', () => {- const {root} = fixture({withChangeset: true});+ const {root, cutSha} = cutFixture();+ const values = identity(cutSha);writeAuthority(root, values, false);const original = JSON.parse(fs.readFileSync(path.join(root, '.release/active.json'), 'utf8'),@@ -107,14 +143,22 @@ describe('one branch per release lifecycle', () => {{...values, version: '0.6.6', branch: 'release/v0.6.6'},true,),- ).toThrow('release refresh cannot change version');+ ).toThrow(+ /main declares 0\.6\.5 at the cut|release refresh cannot change version/,+ );+ git(root, 'commit', '-qm', 'later', '--allow-empty');expect(() =>- writeAuthority(root, {...values, 'cut-sha': HEAD}, true),+ writeAuthority(+ root,+ {...values, 'cut-sha': git(root, 'rev-parse', 'HEAD')},+ true,+ ),).toThrow('release refresh cannot change cutSha');});it('never revives or recreates a closed branch lifecycle', () => {- const {root} = fixture();+ const {root, cutSha} = cutFixture();+ const values = identity(cutSha);writeAuthority(root, values, false);const markerPath = path.join(root, '.release/active.json');const marker = JSON.parse(fs.readFileSync(markerPath, 'utf8'));@@ -132,20 +176,50 @@ describe('one branch per release lifecycle', () => {});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});+ const {root, cutSha} = cutFixture();+ git(root, 'tag', 'v0.6.5');- expect(() => writeAuthority(root, values, false)).toThrow(+ expect(() => writeAuthority(root, identity(cutSha), false)).toThrow('use a new release branch and version',);});++ it("binds the release version to main's declared version at the cut", () => {+ // A pre-bumped main that declares 0.7.0 cuts 0.7.0. Nothing may compute a+ // different version from the pending Changesets.+ const {root, cutSha} = cutFixture('0.7.0');+ expect(declaredVersionAtRef(root, cutSha)).toEqual({+ version: '0.7.0',+ errors: [],+ });+ expect(() =>+ writeAuthority(+ root,+ {version: '0.8.0', branch: 'release/v0.8.0', 'cut-sha': cutSha},+ false,+ ),+ ).toThrow(+ 'main declares 0.7.0 at the cut, so the release is 0.7.0, not 0.8.0',+ );+ expect(() =>+ writeAuthority(+ root,+ {version: '0.6.5', branch: BRANCH, 'cut-sha': cutSha},+ false,+ ),+ ).toThrow('main declares 0.7.0 at the cut');+ expect(fs.existsSync(path.join(root, '.release/active.json'))).toBe(false);++ writeAuthority(+ root,+ {version: '0.7.0', branch: 'release/v0.7.0', 'cut-sha': cutSha},+ false,+ );+ const marker = JSON.parse(+ fs.readFileSync(path.join(root, '.release/active.json'), 'utf8'),+ );+ expect(marker.version).toBe('0.7.0');+ });});describe('active release branch authority', () => {@@ -351,33 +425,38 @@ describe('active release branch authority', () => {});});-describe('post-release bookkeeping sync', () => {+describe('post-release bookkeeping sync (FR50)', () => {const digest = value => value.repeat(64).slice(0, 64);- const manifestPath = 'packages/core/package.json';- const cutManifest = {+ const corePath = 'packages/core/package.json';+ const themePath = 'packages/themes/neutral/package.json';+ const labPath = 'packages/lab/package.json';+ const fixedNames = new Set([+ '@astryxdesign/core',+ '@astryxdesign/theme-neutral',+ ]);+ const core = version => ({name: '@astryxdesign/core',- version: '0.6.5',- exports: {'.': './dist/index.js'},- files: ['dist'],- sideEffects: false,- dependencies: {'@astryxdesign/build': '^0.6.5'},- };- const releaseManifest = {- ...cutManifest,- version: '0.6.6',- dependencies: {'@astryxdesign/build': '^0.6.6'},- };- const baseManifest = {- ...cutManifest,- exports: {...cutManifest.exports, './fonts.css': './dist/fonts.css'},+ version,+ exports: {'.': './dist/index.js', './fonts.css': './dist/fonts.css'},files: ['dist', 'fonts.css'],- sideEffects: ['*.css'],- };- const headManifest = {- ...baseManifest,- version: '0.6.6',- dependencies: {'@astryxdesign/build': '^0.6.6'},- };+ });+ const theme = version => ({+ name: '@astryxdesign/theme-neutral',+ version,+ peerDependencies: {'@astryxdesign/core': version, react: '^19.0.0'},+ });+ const lab = pin => ({+ name: '@astryxdesign/lab',+ version: '0.1.9',+ private: true,+ peerDependencies: {'@astryxdesign/core': pin},+ });+ const mainAt = (version, labPin = version) =>+ new Map([+ [corePath, core(version)],+ [themePath, theme(version)],+ [labPath, lab(labPin)],+ ]);const plan = {changesets: [{path: '.changeset/frozen.md', sha256: digest('a')},@@ -385,11 +464,13 @@ describe('post-release bookkeeping sync', () => {],};- function sync(overrides = {}) {+ function sync({release = '0.7.0', base, head, ...overrides}) {return validateReleaseSync({entries: ['D\t.changeset/frozen.md',- `M\t${manifestPath}`,+ `M\t${corePath}`,+ `M\t${themePath}`,+ `M\t${labPath}`,'M\tpackages/core/CHANGELOG.md',],plan,@@ -400,21 +481,69 @@ describe('post-release bookkeeping sync', () => {headChangesets: new Map([['.changeset/post-cut.md', digest('c')]]),releaseOutputs: new Map([['packages/core/CHANGELOG.md', digest('e')]]),headOutputs: new Map([['packages/core/CHANGELOG.md', digest('e')]]),- cutManifests: new Map([[manifestPath, cutManifest]]),- baseManifests: new Map([[manifestPath, baseManifest]]),- releaseManifests: new Map([[manifestPath, releaseManifest]]),- headManifests: new Map([[manifestPath, headManifest]]),+ releaseVersion: release,+ fixedNames,+ baseManifests: base,+ headManifests: head,...overrides,});}- it('accepts version-only manifests, exact outputs, and idempotent reruns', () => {- expect(sync()).toEqual([]);+ it('advances main from the released version to its patch successor', () => {+ expect(sync({base: mainAt('0.7.0'), head: mainAt('0.7.1')})).toEqual([]);+ });++ it('rejects a sync that leaves main declaring the published version', () => {+ expect(sync({base: mainAt('0.7.0'), head: mainAt('0.7.0')})).toContain(+ `release sync manifest has the wrong version: ${corePath} is 0.7.0, expected 0.7.1`,+ );+ });++ it("preserves an owner's higher bump and refuses to roll it back", () => {+ // Main was bumped to plan 0.8.0 while 0.7.0 was releasing.+ expect(sync({base: mainAt('0.8.0'), head: mainAt('0.8.0')})).toEqual([]);+ expect(sync({base: mainAt('0.8.0'), head: mainAt('0.7.1')})).toEqual(+ expect.arrayContaining([+ `release sync moves main backward: ${corePath} 0.8.0 -> 0.7.1`,+ `release sync moves main backward: ${themePath} 0.8.0 -> 0.7.1`,+ ]),+ );+ expect(sync({base: mainAt('0.8.0'), head: mainAt('0.7.0')})).toContain(+ `release sync moves main backward: ${corePath} 0.8.0 -> 0.7.0`,+ );+ });++ it('keeps an owner bump that is exactly the patch successor', () => {+ expect(sync({base: mainAt('0.7.1'), head: mainAt('0.7.1')})).toEqual([]);+ });++ it('raises a main that is behind the release past it, never to it', () => {+ expect(+ sync({release: '0.6.7', base: mainAt('0.6.6'), head: mainAt('0.6.8')}),+ ).toEqual([]);+ expect(+ sync({release: '0.6.7', base: mainAt('0.6.6'), head: mainAt('0.6.7')}),+ ).toContain(+ `release sync manifest has the wrong version: ${corePath} is 0.6.7, expected 0.6.8`,+ );+ });++ it('repins exact internal pins everywhere and leaves private versions alone', () => {+ const head = mainAt('0.7.1');+ expect(head.get(labPath).version).toBe('0.1.9');+ expect(sync({base: mainAt('0.7.0'), head})).toEqual([]);+ expect(+ sync({base: mainAt('0.7.0'), head: mainAt('0.7.1', '0.7.0')}),+ ).toContain(`release sync changed non-version manifest fields: ${labPath}`);+ });++ it('is idempotent once main is synced', () => {expect(sync({entries: [],baseChangesets: new Map([['.changeset/post-cut.md', digest('c')]]),- baseManifests: new Map([[manifestPath, headManifest]]),+ base: mainAt('0.7.1'),+ head: mainAt('0.7.1'),}),).toEqual([]);});@@ -424,7 +553,7 @@ describe('post-release bookkeeping sync', () => {const to = 'packages/cli/assets/codemods/transforms/v0.6.6/transform.mjs';const entries = ['D\t.changeset/frozen.md',- `M\t${manifestPath}`,+ `M\t${corePath}`,'M\tpackages/core/CHANGELOG.md',`R100\t${from}\t${to}`,];@@ -440,36 +569,56 @@ describe('post-release bookkeeping sync', () => {releaseOutputs,headOutputs,releaseRenames: new Set([`${from}\t${to}`]),+ base: mainAt('0.7.0'),+ head: mainAt('0.7.1'),}),).toEqual([]);- expect(sync({entries, releaseOutputs, headOutputs})).toContain(+ expect(+ sync({+ entries,+ releaseOutputs,+ headOutputs,+ base: mainAt('0.7.0'),+ head: mainAt('0.7.1'),+ }),+ ).toContain(`release sync rename does not match published branch: ${from} -> ${to}`,);});- it('rejects wholesale release-manifest copies that erase newer main fields', () => {- expect(- sync({headManifests: new Map([[manifestPath, releaseManifest]])}),- ).toContain(- `release sync changed non-version manifest fields: ${manifestPath}`,+ it('rejects any other manifest change, including wholesale tag copies', () => {+ const head = mainAt('0.7.1');+ head.set(corePath, {...core('0.7.1'), scripts: {build: 'changed'}});+ expect(sync({base: mainAt('0.7.0'), head})).toContain(+ `release sync changed non-version manifest fields: ${corePath}`,+ );+ const copied = mainAt('0.7.1');+ copied.set(corePath, {...core('0.7.1'), files: ['dist']});+ expect(sync({base: mainAt('0.7.0'), head: copied})).toContain(+ `release sync changed non-version manifest fields: ${corePath}`,);});- it('rejects any other non-version manifest change', () => {+ it('rejects a release bump that changed more than versions and pins', () => {expect(sync({- headManifests: new Map([- [manifestPath, {...headManifest, scripts: {build: 'changed'}}],+ base: mainAt('0.7.0'),+ head: mainAt('0.7.1'),+ cutManifests: new Map([[corePath, core('0.7.0')]]),+ releaseManifests: new Map([+ [corePath, {...core('0.7.0'), sideEffects: false}],]),}),).toContain(- `release sync changed non-version manifest fields: ${manifestPath}`,+ `published manifest contains a non-version release change: ${corePath}`,);});it('rejects changes to post-cut Changesets and non-bookkeeping paths', () => {expect(sync({+ base: mainAt('0.7.0'),+ head: mainAt('0.7.1'),entries: ['M\t.changeset/post-cut.md','M\tpackages/core/src/Button/Button.tsx',@@ -488,6 +637,8 @@ describe('post-release bookkeeping sync', () => {it('rejects missing frozen deletions and exact-output drift', () => {expect(sync({+ base: mainAt('0.7.0'),+ head: mainAt('0.7.1'),headChangesets: new Map([['.changeset/frozen.md', digest('a')],['.changeset/post-cut.md', digest('c')],@@ -501,4 +652,85 @@ describe('post-release bookkeeping sync', () => {]),);});++ it('computes the synced version as max(main, released patch successor)', () => {+ expect(syncedMainVersion('0.7.0', '0.7.0')).toBe('0.7.1');+ expect(syncedMainVersion('0.8.0', '0.7.0')).toBe('0.8.0');+ expect(syncedMainVersion('0.6.6', '0.6.7')).toBe('0.6.8');+ expect(syncedMainVersion('0.7.0-canary.1', '0.7.0')).toBeNull();+ });+});++describe('newest stable release selection', () => {+ it('selects the highest vX.Y.Z tag and ignores non-release tags', () => {+ const {root} = cutFixture('0.7.0');+ for (const tag of ['v0.6.5', 'v0.6.7', 'v0.6.6', 'canary-0.8.0'])+ git(root, 'tag', tag);+ expect(latestStableVersion(root)).toBe('0.6.7');+ });+});++describe('main pull requests keep the declared version above newest stable (FR46)', () => {+ const fixed = ['@astryxdesign/core', '@astryxdesign/cli'];+ const at = (core, cli = core) =>+ new Map([+ ['@astryxdesign/core', {name: '@astryxdesign/core', version: core}],+ ['@astryxdesign/cli', {name: '@astryxdesign/cli', version: cli}],+ ]);+ // `base` is passed deliberately as a red arm: a check that compares against+ // previous main would reject the first case instead of comparing with v0.6.7.+ const check = (+ base,+ head,+ releasedVersion = '0.6.7',+ allowBootstrapEqual = false,+ ) =>+ validateMainVersions({+ fixed,+ releasedVersion,+ allowBootstrapEqual,+ baseManifests: base,+ headManifests: head,+ });++ it('accepts a planned-version decrease that stays above newest stable', () => {+ expect(check(at('0.7.0'), at('0.6.8'))).toEqual([]);+ expect(check(at('0.6.8'), at('0.7.0'))).toEqual([]);+ });++ it('allows only the one-time equal-version bootstrap while the validator lands', () => {+ expect(check(at('0.6.7'), at('0.6.7'), '0.6.7', true)).toEqual([]);+ expect(check(at('0.6.7'), at('0.6.6'), '0.6.7', true)).toContain(+ 'main declares 0.6.6; it must stay strictly above newest stable v0.6.7',+ );+ });++ it('refuses equality, a lower version, a split group, and a prerelease', () => {+ expect(check(at('0.7.0'), at('0.6.7'))).toContain(+ 'main declares 0.6.7; it must stay strictly above newest stable v0.6.7',+ );+ expect(check(at('0.7.0'), at('0.6.6'))).toContain(+ 'main declares 0.6.6; it must stay strictly above newest stable v0.6.7',+ );+ expect(check(at('0.6.8'), at('0.7.0', '0.6.8'))).toContain(+ 'the fixed group must declare one version on main; found 0.6.8, 0.7.0',+ );+ expect(check(at('0.6.8'), at('0.7.0-canary.abc'))[0]).toMatch(+ /main declares an X\.Y\.Z version/,+ );+ expect(check(at('0.6.8'), at('0.7.0'), null)).toContain(+ 'main version check needs the newest stable vX.Y.Z tag',+ );+ });++ it('accepts a package new to main', () => {+ expect(+ check(+ new Map([+ ['@astryxdesign/core', at('0.7.0').get('@astryxdesign/core')],+ ]),+ at('0.7.0'),+ ),+ ).toEqual([]);+ });});diff --git a/scripts/release/changeset-coverage.mjs b/scripts/release/changeset-coverage.mjsindex 084e182277..3910c62368 100644--- a/scripts/release/changeset-coverage.mjs+++ b/scripts/release/changeset-coverage.mjs@@ -788,8 +788,8 @@ export function checkReleasedIds({` Scripts read released JSON ids, so removing or renaming one is incompatible\n` +` (spec:AST-017 FR3, FR13). Restore \`${token}\`, or classify the removal in a\n` +` Changeset naming '${CLI_PACKAGE}':\n` +- ` - a [breaking] Changeset whose text names \`${token}\` (admitted only once a minor\n` +- ` is scheduled; see check:changesets), or\n` ++ ` - a [breaking] Changeset whose text names \`${token}\` (it ships only in a minor\n` ++ ` release, so main must declare the next minor before the cut), or\n` +` - a paragraph beginning "Compatibility:" that names \`${token}\` and says why a\n` +` consumer of ${releasedLabel} keeps working.`,);diff --git a/scripts/release/release-inputs.mjs b/scripts/release/release-inputs.mjsnew file mode 100644index 0000000000..afec3abb96--- /dev/null+++ b/scripts/release/release-inputs.mjs@@ -0,0 +1,108 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Release-branch admission over a working tree.+ *+ * Reads what `release-admission.mjs` judges — the fixed group, the version+ * main declared for it, the pending Changesets, and the latest stable tag —+ * from a checkout, and requires the declared version to be the release+ * version. Run where a release is planned and versioned, never on main.+ *+ * @input a checkout root and the release version its marker or cut names+ * @output {declared, latestStable, tier, entries, problems}+ * @position scripts/release — used by active-release create/refresh and+ * version-packages+ */++import fs from 'node:fs';+import path from 'node:path';+import {execFileSync} from 'node:child_process';+import {createRequire} from 'node:module';+import {parseFrontmatter} from '../check-changesets.mjs';+import {expandWorkspaceDirs} from '../lib/workspace-globs.mjs';+import {checkAdmission, latestStableVersion} from '../release-admission.mjs';++const require = createRequire(import.meta.url);+const {parseEntry} = require('../changeset-entry-format.cjs');++function readJson(file) {+ return JSON.parse(fs.readFileSync(file, 'utf8'));+}++/** Every `v*` tag in the repository at `root`, or none outside a repository. */+export function repositoryTags(root) {+ try {+ return execFileSync('git', ['tag', '--list', 'v*'], {+ cwd: root,+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'ignore'],+ })+ .split('\n')+ .filter(Boolean);+ } catch {+ return [];+ }+}++/** The Changesets pending at `root`, as admission reads them. */+export function pendingEntries(root) {+ const dir = path.join(root, '.changeset');+ return fs+ .readdirSync(dir)+ .filter(name => name.endsWith('.md') && name !== 'README.md')+ .sort()+ .flatMap(name => {+ const fm = parseFrontmatter(+ fs.readFileSync(path.join(dir, name), 'utf8'),+ );+ // An unparseable Changeset is check:changesets' finding; admission adds+ // nothing guessed.+ if (!fm) return [];+ return [+ {+ file: name,+ category: parseEntry(fm.summary).category,+ releases: fm.releases,+ },+ ];+ });+}++/** Name -> version for every workspace package at `root`. */+export function workspaceVersions(root) {+ const versions = new Map();+ for (const dir of expandWorkspaceDirs(root)) {+ const file = path.join(dir, 'package.json');+ if (!fs.existsSync(file)) continue;+ const manifest = readJson(file);+ if (manifest.name && manifest.version)+ versions.set(manifest.name, manifest.version);+ }+ return versions;+}++/**+ * Admit the release at `root`.+ *+ * @param {string} root+ * @param {object} input+ * @param {string} input.version release version named by the cut or marker+ * @param {string[]} [input.tags] defaults to the repository's tags+ * @returns {{declared: string|null, latestStable: string|null, tier: 'patch'|'minor'|null, entries: object[], problems: string[]}}+ */+export function admitRelease(root, {version, tags = repositoryTags(root)}) {+ const config = readJson(path.join(root, '.changeset/config.json'));+ const entries = pendingEntries(root);+ const result = checkAdmission({+ fixedGroups: config.fixed || [],+ versionByName: workspaceVersions(root),+ entries,+ latestStable: latestStableVersion(tags),+ });+ if (result.declared && result.declared !== version) {+ result.problems.unshift(+ `the release version is ${version}, but main declares ${result.declared}. A release branch releases the version main's package.json declares.`,+ );+ }+ return {...result, entries};+}diff --git a/scripts/release/release-inputs.test.mjs b/scripts/release/release-inputs.test.mjsnew file mode 100644index 0000000000..609b7d0f92--- /dev/null+++ b/scripts/release/release-inputs.test.mjs@@ -0,0 +1,106 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Release-branch admission over a checkout.+ *+ * @input temporary checkouts with a fixed group, Changesets, and tags+ * @output proofs that admission reads main's declared version and the newest+ * stable tag, and runs where a release is planned (spec:AST-017 FR47-FR49)+ * @position focused suite for scripts/release/release-inputs.mjs+ */++import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import {afterEach, describe, expect, it} from 'vitest';+import {admitRelease} from './release-inputs.mjs';++const roots = [];+afterEach(() => {+ for (const root of roots.splice(0))+ fs.rmSync(root, {recursive: true, force: true});+});++function checkout(version, changesets = {}) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-admit-'));+ roots.push(root);+ const put = (file, text) => {+ fs.mkdirSync(path.dirname(path.join(root, file)), {recursive: true});+ fs.writeFileSync(path.join(root, file), text);+ };+ put('pnpm-workspace.yaml', "packages:\n - 'packages/*'\n");+ for (const name of ['core', 'cli'])+ put(+ `packages/${name}/package.json`,+ JSON.stringify({name: `@astryxdesign/${name}`, version}),+ );+ put(+ '.changeset/config.json',+ JSON.stringify({fixed: [['@astryxdesign/core', '@astryxdesign/cli']]}),+ );+ for (const [name, text] of Object.entries(changesets))+ put(`.changeset/${name}.md`, text);+ return root;+}++const BREAKING =+ "---\n'@astryxdesign/core': minor\n---\n\n[breaking] Remove it\n@person\n";+const FIX = "---\n'@astryxdesign/core': patch\n---\n\n[fix] Fix it\n@person\n";+const TAGS = ['v0.6.5', 'v0.6.6', 'v0.7.0-canary.abc1234'];++describe('admitRelease', () => {+ it('admits a [breaking] Changeset when main declares the minor', () => {+ const result = admitRelease(checkout('0.7.0', {b: BREAKING}), {+ version: '0.7.0',+ tags: TAGS,+ });+ expect(result).toMatchObject({+ declared: '0.7.0',+ latestStable: '0.6.6',+ tier: 'minor',+ problems: [],+ });+ });++ it('keeps the patch path and refuses incompatible work in it', () => {+ expect(+ admitRelease(checkout('0.6.7', {f: FIX}), {version: '0.6.7', tags: TAGS})+ .problems,+ ).toEqual([]);+ const refused = admitRelease(checkout('0.6.7', {f: FIX, b: BREAKING}), {+ version: '0.6.7',+ tags: TAGS,+ });+ expect(refused.problems).toHaveLength(1);+ expect(refused.problems[0]).toMatch(/^b\.md: this entry is incompatible/);+ });++ it("refuses a release version other than main's declaration", () => {+ const result = admitRelease(checkout('0.7.0', {b: BREAKING}), {+ version: '0.8.0',+ tags: TAGS,+ });+ expect(result.problems[0]).toBe(+ "the release version is 0.8.0, but main declares 0.7.0. A release branch releases the version main's package.json declares.",+ );+ });++ it('refuses a declared version that is already released', () => {+ const result = admitRelease(checkout('0.6.6', {f: FIX}), {+ version: '0.6.6',+ tags: TAGS,+ });+ expect(result.problems[0]).toMatch(+ /not newer than the latest stable release 0\.6\.6/,+ );+ });++ it('reads the base from tags, never from a canary', () => {+ const result = admitRelease(checkout('0.7.1', {f: FIX}), {+ version: '0.7.1',+ tags: TAGS,+ });+ expect(result.latestStable).toBe('0.6.6');+ expect(result.tier).toBeNull();+ });+});diff --git a/scripts/release/version-packages.mjs b/scripts/release/version-packages.mjsnew file mode 100644index 0000000000..5981f63e6f--- /dev/null+++ b/scripts/release/version-packages.mjs@@ -0,0 +1,193 @@+#!/usr/bin/env node+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Release-branch versioning at the version main declared.+ *+ * `spec:AST-017` FR47: a release branch releases the fixed-group version+ * declared at its cut, and consuming Changesets never moves it. Stock+ * `changeset version` adds each Changeset's bump to the current version, so a+ * branch that already declares 0.7.0 would become 0.8.0 on its first+ * `[breaking]` entry. This step assembles the same release plan with the same+ * Changesets libraries the pinned CLI uses, pins every release to the declared+ * version, and applies it: changelogs are written under the declared version,+ * consumed Changesets are deleted, and package versions stay where main put+ * them.+ *+ * It runs only on the marked release branch whose marker names the declared+ * version, and only after release admission passes (FR48, FR49).+ *+ * @input a release-branch checkout with `.release/active.json`+ * @output CHANGELOG entries at the declared version; consumed Changesets removed+ * @position scripts/release — first step of `pnpm version-packages`+ */++import fs from 'node:fs';+import path from 'node:path';+import {execFileSync} from 'node:child_process';+import {createRequire} from 'node:module';+import {fileURLToPath} from 'node:url';+import {isStableReleasePackage, validateIdentity} from './active-release.mjs';+import {admitRelease} from './release-inputs.mjs';++const ROOT = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '../..',+);+const MARKER = '.release/active.json';+const PLAN = '.release/plan.json';++/**+ * The Changesets libraries `@changesets/cli` itself resolves, so versioning+ * reads Changesets, fixed groups, and changelog output exactly as the pinned+ * CLI does.+ */+function changesetsLibraries() {+ const cliManifest = createRequire(import.meta.url).resolve(+ '@changesets/cli/package.json',+ );+ const fromCli = createRequire(cliManifest);+ const load = name => {+ const mod = fromCli(name);+ return mod.default ?? mod;+ };+ return {+ cliDist: path.join(path.dirname(cliManifest), 'dist'),+ readChangesets: load('@changesets/read'),+ assembleReleasePlan: load('@changesets/assemble-release-plan'),+ applyReleasePlan: load('@changesets/apply-release-plan'),+ readConfig: fromCli('@changesets/config').read,+ getPackages: fromCli('@manypkg/get-packages').getPackages,+ };+}++/**+ * FR47 — pin a Changesets release plan to the declared version.+ *+ * Every fixed-group release must already carry the declared version and keeps+ * it. Private and canary-only packages outside the group never publish to the+ * stable channel, so they keep the version Changesets computes for them, as+ * they always have. Any other release would publish a version main did not+ * declare.+ *+ * @param {{releases: Array<{name: string, oldVersion: string, newVersion: string}>}} plan+ * @param {object} input+ * @param {string} input.version declared release version+ * @param {Set<string>} input.fixedNames+ * @param {Set<string>} [input.unstableNames] private or canary-only packages+ * @returns {{plan: object, problems: string[]}}+ */+export function pinReleasePlan(+ plan,+ {version, fixedNames, unstableNames = new Set()},+) {+ const problems = [];+ const releases = plan.releases.map(release => {+ if (!fixedNames.has(release.name)) {+ if (!unstableNames.has(release.name))+ problems.push(+ `${release.name} publishes outside the fixed package group, so it has no declared release version.`,+ );+ return release;+ }+ if (release.oldVersion !== version) {+ problems.push(+ `${release.name} is ${release.oldVersion}, but the release version is ${version}.`,+ );+ }+ return {...release, newVersion: version};+ });+ return {plan: {...plan, releases}, problems};+}++/**+ * Consume every pending Changeset at `root` into changelogs for `version`.+ *+ * @param {string} root+ * @param {string} version declared release version+ * @returns {Promise<{releases: Array<{name: string, computed: string, version: string}>}>}+ */+export async function versionAtDeclared(root, version) {+ const lib = changesetsLibraries();+ const packages = await lib.getPackages(root);+ const config = await lib.readConfig(root, packages);+ const changesets = await lib.readChangesets(root);+ if (changesets.length === 0) {+ throw new Error('there are no Changesets to release.');+ }++ const assembled = lib.assembleReleasePlan(+ changesets,+ packages,+ config,+ undefined,+ );+ const fixedNames = new Set((config.fixed || []).flat());+ const unstableNames = new Set(+ packages.packages+ .filter(({packageJson}) => !isStableReleasePackage(packageJson))+ .map(({packageJson}) => packageJson.name),+ );+ const {plan, problems} = pinReleasePlan(assembled, {+ version,+ fixedNames,+ unstableNames,+ });+ if (problems.length) throw new Error(problems.join('\n'));++ await lib.applyReleasePlan(plan, packages, config, undefined, lib.cliDist);+ return {+ releases: assembled.releases.map(release => ({+ name: release.name,+ computed: release.newVersion,+ version: fixedNames.has(release.name) ? version : release.newVersion,+ })),+ };+}++function currentBranch(root) {+ return execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], {+ cwd: root,+ encoding: 'utf8',+ }).trim();+}++async function main(argv) {+ const branchFlag = argv.indexOf('--branch');+ const root = ROOT;+ const markerPath = path.join(root, MARKER);+ if (!fs.existsSync(markerPath)) {+ throw new Error(+ `${MARKER} is missing. Versioning runs only on a marked release branch; main publishes canaries only.`,+ );+ }+ const marker = JSON.parse(fs.readFileSync(markerPath, 'utf8'));+ const plan = JSON.parse(fs.readFileSync(path.join(root, PLAN), 'utf8'));+ const identity = validateIdentity(marker, plan);+ if (identity.length) throw new Error(identity.join('\n'));+ const branch = branchFlag >= 0 ? argv[branchFlag + 1] : currentBranch(root);+ if (marker.state !== 'active' || branch !== marker.branch) {+ throw new Error(+ `versioning runs only on the active marked release branch ${marker.branch}; this checkout is ${branch}.`,+ );+ }++ const admission = admitRelease(root, {version: marker.version});+ if (admission.problems.length) {+ throw new Error(+ `release admission refused ${marker.version}:\n - ${admission.problems.join('\n - ')}`,+ );+ }++ await versionAtDeclared(root, marker.version);+ console.log(+ `✓ consumed ${admission.entries.length} Changeset(s) into ${marker.version} changelogs (${admission.tier} release of ${admission.latestStable})`,+ );+}++if (process.argv[1] === fileURLToPath(import.meta.url)) {+ main(process.argv.slice(2)).catch(error => {+ console.error(`version-packages: ${error.message}`);+ process.exit(1);+ });+}diff --git a/scripts/release/version-packages.test.mjs b/scripts/release/version-packages.test.mjsnew file mode 100644index 0000000000..d1d60bb57c--- /dev/null+++ b/scripts/release/version-packages.test.mjs@@ -0,0 +1,218 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Release-branch versioning keeps the version main declared.+ *+ * @input temporary workspaces using this repository's Changesets config shape+ * and changelog generator+ * @output proofs that consuming Changesets writes changelogs under the declared+ * version and never moves it (spec:AST-017 FR47)+ * @position focused suite for scripts/release/version-packages.mjs+ */++import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import {spawnSync} from 'node:child_process';+import {fileURLToPath} from 'node:url';+import {afterEach, describe, expect, it} from 'vitest';+import {pinReleasePlan, versionAtDeclared} from './version-packages.mjs';++const REPO = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '../..',+);+const FIXED = [+ '@astryxdesign/core',+ '@astryxdesign/cli',+ '@astryxdesign/theme-neutral',+];+const roots = [];++function write(root, file, contents) {+ fs.mkdirSync(path.dirname(path.join(root, file)), {recursive: true});+ fs.writeFileSync(+ path.join(root, file),+ typeof contents === 'string'+ ? contents+ : `${JSON.stringify(contents, null, 2)}\n`,+ );+}++function workspace(version, changesets) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-version-'));+ roots.push(root);+ write(root, 'package.json', {name: 'fixture-root', private: true});+ write(root, 'pnpm-workspace.yaml', "packages:\n - 'packages/*'\n");+ write(root, 'packages/core/package.json', {+ name: '@astryxdesign/core',+ version,+ });+ write(root, 'packages/cli/package.json', {+ name: '@astryxdesign/cli',+ version,+ });+ write(root, 'packages/theme-neutral/package.json', {+ name: '@astryxdesign/theme-neutral',+ version,+ peerDependencies: {'@astryxdesign/core': version},+ });+ const config = JSON.parse(+ fs.readFileSync(path.join(REPO, '.changeset/config.json'), 'utf8'),+ );+ write(root, '.changeset/config.json', {+ ...config,+ fixed: [FIXED],+ ignore: [],+ });+ write(+ root,+ '.changeset/changelog.cjs',+ fs.readFileSync(path.join(REPO, '.changeset/changelog.cjs'), 'utf8'),+ );+ write(+ root,+ 'scripts/changeset-entry-format.cjs',+ fs.readFileSync(+ path.join(REPO, 'scripts/changeset-entry-format.cjs'),+ 'utf8',+ ),+ );+ for (const [name, body] of Object.entries(changesets))+ write(root, `.changeset/${name}.md`, body);+ return root;+}++const read = (root, file) => fs.readFileSync(path.join(root, file), 'utf8');+const manifest = (root, dir) =>+ JSON.parse(read(root, `packages/${dir}/package.json`));++const BREAKING =+ "---\n'@astryxdesign/core': minor\n---\n\n[breaking] Remove the old thing\n@person\n";+const FIX =+ "---\n'@astryxdesign/core': patch\n---\n\n[fix] Fix the thing\n@person\n";++afterEach(() => {+ for (const root of roots.splice(0))+ fs.rmSync(root, {recursive: true, force: true});+});++describe('FR47 — consuming Changesets never moves the declared version', () => {+ it('cuts a pre-bumped 0.7.0 with a [breaking] Changeset as 0.7.0, not 0.8.0', async () => {+ const root = workspace('0.7.0', {'remove-thing': BREAKING, 'fix-it': FIX});++ const {releases} = await versionAtDeclared(root, '0.7.0');++ // Red arm: stock Changesets would add the minor bump on top of 0.7.0.+ expect(releases.find(r => r.name === '@astryxdesign/core').computed).toBe(+ '0.8.0',+ );+ for (const dir of ['core', 'cli', 'theme-neutral'])+ expect(manifest(root, dir).version).toBe('0.7.0');+ expect(manifest(root, 'theme-neutral').peerDependencies).toEqual({+ '@astryxdesign/core': '0.7.0',+ });+ const changelog = read(root, 'packages/core/CHANGELOG.md');+ expect(changelog).toMatch(/^## 0\.7\.0$/m);+ expect(changelog).not.toContain('0.8.0');+ expect(changelog).toContain('Remove the old thing');+ expect(changelog).toContain('Fix the thing');+ expect(fs.existsSync(path.join(root, '.changeset/remove-thing.md'))).toBe(+ false,+ );+ expect(fs.existsSync(path.join(root, '.changeset/fix-it.md'))).toBe(false);+ });++ it('keeps the patch path: a declared 0.6.7 with a [fix] Changeset releases 0.6.7', async () => {+ const root = workspace('0.6.7', {'fix-it': FIX});++ const {releases} = await versionAtDeclared(root, '0.6.7');++ expect(releases.find(r => r.name === '@astryxdesign/core').computed).toBe(+ '0.6.8',+ );+ for (const dir of ['core', 'cli', 'theme-neutral'])+ expect(manifest(root, dir).version).toBe('0.6.7');+ const changelog = read(root, 'packages/core/CHANGELOG.md');+ expect(changelog).toMatch(/^## 0\.6\.7$/m);+ expect(changelog).not.toContain('0.6.8');+ expect(fs.existsSync(path.join(root, '.changeset/fix-it.md'))).toBe(false);+ });++ it('refuses a release version the packages do not carry, before writing', async () => {+ const root = workspace('0.7.0', {'fix-it': FIX});+ await expect(versionAtDeclared(root, '0.7.1')).rejects.toThrow(+ 'is 0.7.0, but the release version is 0.7.1',+ );+ expect(fs.existsSync(path.join(root, '.changeset/fix-it.md'))).toBe(true);+ expect(fs.existsSync(path.join(root, 'packages/core/CHANGELOG.md'))).toBe(+ false,+ );+ });++ it('refuses an empty release', async () => {+ const root = workspace('0.7.0', {});+ await expect(versionAtDeclared(root, '0.7.0')).rejects.toThrow(+ 'no Changesets to release',+ );+ });+});++describe('pinReleasePlan', () => {+ const fixedNames = new Set(['@scope/a', '@scope/b']);++ it('pins every fixed release to the declared version', () => {+ const {plan, problems} = pinReleasePlan(+ {+ releases: [+ {name: '@scope/a', oldVersion: '1.3.0', newVersion: '1.4.0'},+ {name: '@scope/b', oldVersion: '1.3.0', newVersion: '1.4.0'},+ ],+ },+ {version: '1.3.0', fixedNames},+ );+ expect(problems).toEqual([]);+ expect(plan.releases.map(r => r.newVersion)).toEqual(['1.3.0', '1.3.0']);+ });++ it('refuses a stable release outside the fixed group', () => {+ const {problems} = pinReleasePlan(+ {+ releases: [+ {name: '@scope/x', oldVersion: '1.3.0', newVersion: '1.3.1'},+ ],+ },+ {version: '1.3.0', fixedNames},+ );+ expect(problems[0]).toMatch(/publishes outside the fixed package group/);+ });++ it('leaves private dependents on the version Changesets computes', () => {+ const {plan, problems} = pinReleasePlan(+ {+ releases: [+ {name: '@scope/a', oldVersion: '1.3.0', newVersion: '1.4.0'},+ {name: '@scope/lab', oldVersion: '0.1.9', newVersion: '0.1.10'},+ ],+ },+ {version: '1.3.0', fixedNames, unstableNames: new Set(['@scope/lab'])},+ );+ expect(problems).toEqual([]);+ expect(plan.releases.map(r => r.newVersion)).toEqual(['1.3.0', '0.1.10']);+ });+});++describe('versioning runs only on a release branch', () => {+ it('refuses on a checkout with no active release marker, such as main', () => {+ if (fs.existsSync(path.join(REPO, '.release/active.json'))) return;+ const result = spawnSync(+ process.execPath,+ [path.join(REPO, 'scripts/release/version-packages.mjs')],+ {cwd: REPO, encoding: 'utf8'},+ );+ expect(result.status).toBe(1);+ expect(result.stderr).toContain(+ 'Versioning runs only on a marked release branch; main publishes canaries only.',+ );+ });+});