An open source design system that's fully customizable and agent ready
TypeScript
ci(changesets): refuse breaking work until a minor is scheduled (#6889)
Cindy Zhang5e0f026f5155
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex b80d7a3abe..2902c60832 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -678,6 +678,11 @@ pnpm changeset:new --category fix --summary "…" --pr 2717 --contributor yourha- **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.++ 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.### How a release is cutdiff --git a/scripts/check-changesets.mjs b/scripts/check-changesets.mjsindex 44b21c8883..22be7dc0d5 100755--- a/scripts/check-changesets.mjs+++ b/scripts/check-changesets.mjs@@ -12,6 +12,9 @@* 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.** Exits 1 with a readable report on any violation. config.json and README.md* are skipped.@@ -22,6 +25,11 @@ 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');@@ -61,6 +69,27 @@ 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.@@ -150,11 +179,36 @@ function main() {const files = fs.readdirSync(CS_DIR).filter(isChangesetFile);const problems = [];+ const entries = [];for (const f of files) {const contents = fs.readFileSync(path.join(CS_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,+ });+ }}+ 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);+if (problems.length) {console.error(`\n✗ check:changesets found ${problems.length} problem(s):\n`,@@ -163,8 +217,15 @@ function main() {console.error('\nSee the Release-Process wiki and `pnpm changeset:new`.\n');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)' : ''}`,+ `✓ check:changesets — ${files.length} changeset(s) valid${ctx.pre1 ? ' (0.x: [breaking] -> minor, [experimental] and other categories -> patch)' : ''}${mode}`,);}diff --git a/scripts/release-admission.mjs b/scripts/release-admission.mjsnew file mode 100644index 0000000000..adef20791c--- /dev/null+++ b/scripts/release-admission.mjs@@ -0,0 +1,256 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Patch-versus-minor admission for Changesets.+ *+ * 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:+ *+ * main targets a PATCH by default -> incompatible work is refused+ * an owner SCHEDULES a minor first -> incompatible work may land+ *+ * 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.+ *+ * 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.+ *+ * @input fixed groups, package versions, parsed Changesets, optional target+ * @output {mode, problems} — problems empty means admissible+ * @position scripts/ — consumed by check-changesets.mjs+ */++/** 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'];++/**+ * Is this Changeset incompatible?+ *+ * The `[breaking]` category is the authoring vocabulary (FR7); a declared+ * `minor` is the incompatible tier itself while packages are 0.x.+ * `check-changesets.mjs` already requires the two to agree, so reading either+ * alone as incompatible is the fail-closed direction.+ *+ * @param {{category: string|null, releases: Record<string,string>}} entry+ * @returns {boolean}+ */+export function isIncompatible(entry) {+ if (entry.category === 'breaking') return true;+ return Object.values(entry.releases || {}).some(bump => bump === 'minor');+}++/** The version a minor from `base` would carry. */+export function minorSuccessor(base) {+ const m = STABLE_VERSION.exec(base || '');+ return m ? `${Number(m[1])}.${Number(m[2]) + 1}.0` : null;+}++/** The version a patch from `base` would carry. */+export function patchSuccessor(base) {+ const m = STABLE_VERSION.exec(base || '');+ return m ? `${Number(m[1])}.${Number(m[2])}.${Number(m[3]) + 1}` : null;+}++/**+ * 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.+ *+ * @param {string} day already matched against YYYY-MM-DD+ * @returns {boolean}+ */+function isRealDay(day) {+ const parsed = new Date(`${day}T00:00:00Z`);+ return (+ !Number.isNaN(parsed.getTime()) &&+ parsed.toISOString().slice(0, 10) === day+ );+}++/**+ * 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.+ *+ * @param {string[][]} fixedGroups+ * @param {Map<string,string>} versionByName+ * @returns {{base: string|null, problems: string[]}}+ */+export function deriveBase(fixedGroups, versionByName) {+ const problems = [];+ const seen = new Map();++ for (const group of fixedGroups || []) {+ for (const name of group || []) {+ const version = versionByName.get(name);+ 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.`,+ );+ continue;+ }+ if (!seen.has(version)) seen.set(version, []);+ seen.get(version).push(name);+ }+ }++ if (seen.size > 1) {+ const spread = [...seen.entries()]+ .sort((a, b) => (a[0] < b[0] ? -1 : 1))+ .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.`,+ );+ }++ if (problems.length) return {base: null, problems};+ return {base: seen.size === 1 ? [...seen.keys()][0] : null, 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.+ *+ * @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[]}}+ */+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.`);+ }+ 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 (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.`,+ );+ }++ return {mode: 'minor', scheduled: {...target}, problems};+}++/**+ * FR50 — the refusal. Names what main is targeting 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+ * @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.`;++ 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` ++ ` 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.`+ );+}++/**+ * FR46-FR50 — decide what this tree 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[]}}+ */+export function checkAdmission({+ fixedGroups,+ versionByName,+ entries,+ target = null,+ today,+}) {+ 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 schedule = readSchedule({target, base, today});+ problems.push(...schedule.problems);++ if (schedule.mode === 'patch') {+ for (const entry of incompatible) problems.push(refuse(entry.file, base));+ }++ 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);+}diff --git a/scripts/release-admission.test.mjs b/scripts/release-admission.test.mjsnew file mode 100644index 0000000000..1fd6e99fb0--- /dev/null+++ b/scripts/release-admission.test.mjs@@ -0,0 +1,223 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file release-admission.test.mjs+ * Patch-versus-minor 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.+ */++import {describe, it, expect} from 'vitest';+import {+ checkAdmission,+ isIncompatible,+ minorSuccessor,+ readSchedule,+ utcToday,+ TARGET_FILE,+} 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]));++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 = {}) =>+ checkAdmission({+ fixedGroups: FIXED,+ versionByName: versions('1.2.3'),+ entries: [],+ target: null,+ today: TODAY,+ ...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/);+ });++ it('allows compatible work with no schedule', () => {+ const result = run({entries: [compatible('a.md'), compatible('b.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: []});+ });+});++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(),+ });+ expect(result.problems).toEqual([]);+ expect(result.mode).toBe('minor');+ expect(result.scheduled).toEqual(schedule());+ });++ it('admits every breaking Changeset while scheduled, with no per-change record', () => {+ const result = run({+ entries: [breaking('one.md'), breaking('two.md')],+ target: schedule(),+ });+ expect(result.problems).toEqual([]);+ });++ 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 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);+ });+});++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('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/,+ );+ });++ 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('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('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/,+ );+ });++ 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('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'}),+ });+ expect(result.problems).toEqual([]);+ });+});++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);+ });+});++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');+ });+});