An open source design system that's fully customizable and agent ready
TypeScript
ci: drafts and outside contributors run CI on a maintainer's call; one author's PRs share heavy suites (AST-030 FR16–FR17) (#8893)
Cindy Zhang383dd2998444
diff --git a/.github/actions/heavy-caps/action.yml b/.github/actions/heavy-caps/action.ymlnew file mode 100644index 0000000000..8a82e37978--- /dev/null+++ b/.github/actions/heavy-caps/action.yml@@ -0,0 +1,103 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.++# Holds a heavy suite back when its pull request's author is over a limit+# (spec:AST-030 FR16). A heavy job runs this right after its checkout and a+# "Heavy suite runs" step right after it; a held job fails here with the+# reason, so it never passes a required join untested.+#+# - One author's suites run for their three oldest open non-draft pull+# requests, and for at most twelve heavy runs a UTC day.+# - The shared agent login counts each branch prefix as an author, with that+# login also held to its five oldest pull requests and forty runs a day.+# - A re-run (the pre-merge restart) and a bot are exempt; a lookup that fails+# runs the suite.+#+# Each limit is one entry in `limits`, checked in order.++name: Heavy-suite caps+description: Fails a heavy job whose pull request's author is over a limit.++runs:+ using: composite+ steps:+ - uses: actions/github-script@v9+ with:+ retries: 3+ script: |+ const pr = context.payload.pull_request;+ if (context.eventName !== 'pull_request' || pr == null) return;+ if (Number(process.env.GITHUB_RUN_ATTEMPT ?? '1') !== 1) return;+ const login = pr.user.login;+ if (login.endsWith('[bot]')) return;++ // Agent lanes share one login: each branch prefix counts as an author.+ const shared = ['cixzhang'].includes(login);+ const lane = ref => (shared ? ref.split('/')[0] : '');+ const mine = ref => lane(ref) === lane(pr.head.ref);+ let open;+ const openPullRequests = async () =>+ (open ??= (+ await github.graphql(+ 'query($q: String!) { search(query: $q, type: ISSUE, first: 100) { nodes { ... on PullRequest { number headRefName headRepository { nameWithOwner } } } } }',+ {q: `repo:${context.repo.owner}/${context.repo.repo} is:pr is:open draft:false author:${login} sort:created-asc`},+ )+ ).search.nodes);++ const limits = [+ // Pull request numbers rise with creation, and the search returns+ // the oldest, so it holds every older one that could queue this.+ async function oldestPullRequests() {+ const nodes = await openPullRequests();+ const older = list => list.filter(p => p.number < pr.number).length;+ if (older(nodes.filter(p => mine(p.headRefName))) >= 3 || (shared && older(nodes) >= 5)) {+ return 'Queued behind your 3 oldest PRs: runs on a push once it is among them, or at the pre-merge re-run.';+ }+ },+ // A heavy run is a run on one of those pull requests whose heavy job+ // ran its suite, as its "Heavy suite runs" step records. A run is a+ // pull request's by its branch and that branch's repository.+ async function dailyHeavyRuns() {+ const nodes = await openPullRequests();+ const key = (repo, branch) => `${repo}:${branch}`;+ const oldest = new Map([+ [key(pr.head.repo.full_name, pr.head.ref), pr.head.ref],+ ...[...nodes.filter(p => mine(p.headRefName)).slice(0, 3), ...(shared ? nodes.slice(0, 5) : [])].map(p => [+ key(p.headRepository?.nameWithOwner, p.headRefName),+ p.headRefName,+ ]),+ ]);+ let laneHeavy = 0;+ let loginHeavy = 0;+ for (const [owner, branch] of oldest) {+ const {data} = await github.rest.actions.listWorkflowRuns({+ ...context.repo, workflow_id: 'ci.yml', event: 'pull_request', branch,+ created: `>=${new Date().toISOString().slice(0, 10)}`, per_page: 100,+ });+ for (const run of data.workflow_runs) {+ if (key(run.head_repository?.full_name, run.head_branch) !== owner) continue;+ if (run.id === context.runId || run.conclusion === 'cancelled') continue;+ const {data: {jobs}} = await github.rest.actions.listJobsForWorkflowRun({+ ...context.repo, run_id: run.id, filter: 'latest', per_page: 100,+ });+ if (!jobs.some(job => job.steps?.some(step => step.name === 'Heavy suite runs' && step.conclusion === 'success'))) continue;+ loginHeavy += 1;+ if (mine(run.head_branch)) laneHeavy += 1;+ }+ }+ if (laneHeavy >= 12 || (shared && loginHeavy >= 40)) {+ return 'Daily heavy-run cap reached, runs tomorrow or at pre-merge.';+ }+ },+ ];++ try {+ for (const limit of limits) {+ const held = await limit();+ if (held) {+ core.setFailed(held);+ return;+ }+ }+ } catch (error) {+ core.warning(`Per-author caps could not be checked (${error.message}); running the heavy suite.`);+ }diff --git a/.github/scripts/ci-docsite-browser.test.mjs b/.github/scripts/ci-docsite-browser.test.mjsindex 337bb05fb7..193b647535 100644--- a/.github/scripts/ci-docsite-browser.test.mjs+++ b/.github/scripts/ci-docsite-browser.test.mjs@@ -11,6 +11,7 @@ import path from 'node:path';import {spawnSync} from 'node:child_process';import {describe, expect, it} from 'vitest';import yaml from 'yaml';+import {PR_REPORT_GATE, gated} from './ci-pr-gate.mjs';const root = path.resolve(import.meta.dirname, '../..');const {jobs} = yaml.parse(@@ -36,7 +37,10 @@ describe('docsite browser required-check projection', () => {'docsite-data',]);expect(owner.if).toBe(- "${{ github.event_name != 'workflow_dispatch' && needs.check-scope.outputs.release_bump != 'true' && always() && !cancelled() }}",+ gated(+ "${{ github.event_name != 'workflow_dispatch' && needs.check-scope.outputs.release_bump != 'true' && always() && !cancelled() }}",+ PR_REPORT_GATE,+ ),);expect(browser.needs).toEqual(['check-scope']);expect(browser.if).toBe(diff --git a/.github/scripts/ci-duration-guard.test.mjs b/.github/scripts/ci-duration-guard.test.mjsindex 8e53f46dff..a7834d5b17 100644--- a/.github/scripts/ci-duration-guard.test.mjs+++ b/.github/scripts/ci-duration-guard.test.mjs@@ -16,6 +16,7 @@ import path from 'node:path';import {describe, expect, it} from 'vitest';import yaml from 'yaml';+import {gated} from './ci-pr-gate.mjs';const root = path.resolve(import.meta.dirname, '../..');const ci = yaml.parse(@@ -82,7 +83,7 @@ describe('PR CI duration budget', () => {it('reports every pull-request job after it finishes, without gating', () => {const report = ci.jobs['ci-duration'];expect(report.if).toBe(- "${{ always() && github.event_name == 'pull_request' }}",+ gated("${{ always() && github.event_name == 'pull_request' }}"),);expect(report['continue-on-error']).toBe(true);expect(report.permissions).toEqual({actions: 'read'});diff --git a/.github/scripts/ci-heavy-lanes.test.mjs b/.github/scripts/ci-heavy-lanes.test.mjsindex ea706a43a5..da1d133992 100644--- a/.github/scripts/ci-heavy-lanes.test.mjs+++ b/.github/scripts/ci-heavy-lanes.test.mjs@@ -11,6 +11,7 @@import fs from 'node:fs';import {describe, expect, it} from 'vitest';import yaml from 'yaml';+import {ungated} from './ci-pr-gate.mjs';const read = name =>yaml.parse(@@ -40,7 +41,7 @@ describe('visual, accessibility and RTL owners', () => {it.each(HEAVY)('%s runs on a pull request only with the ci:heavy-lanes label',name => {- const condition = ci.jobs[name].if;+ const condition = ungated(ci.jobs[name].if);expect(condition).toContain(PR_CLAUSE);expect(condition.replaceAll(PR_CLAUSE, '')).not.toContain("'pull_request'",@@ -57,7 +58,7 @@ describe('visual, accessibility and RTL owners', () => {});it('adds no trigger: a label takes effect on the next push or reopen', () => {- expect(ci.on.pull_request.types).toBeUndefined();+ expect(ci.on.pull_request.types).not.toContain('labeled');});});diff --git a/.github/scripts/ci-merge-back-scope.test.mjs b/.github/scripts/ci-merge-back-scope.test.mjsindex 80965c0e1b..cf2cd9c737 100644--- a/.github/scripts/ci-merge-back-scope.test.mjs+++ b/.github/scripts/ci-merge-back-scope.test.mjs@@ -15,13 +15,16 @@ import fs from 'node:fs';import {describe, expect, it} from 'vitest';import yaml from 'yaml';+import {ungated} from './ci-pr-gate.mjs';+const ci = yaml.parse(fs.readFileSync(new URL('../workflows/ci.yml', import.meta.url), 'utf8'),);const job = ci.jobs['release-merge-back'];function runs({event = 'pull_request', base = 'main', head}) {- const expression = job.if.replace(/^\$\{\{\s*|\s*\}\}$/g, '');+ // The pull-request gate in front is ci-pr-gate.test.mjs's to prove.+ const expression = ungated(job.if).replace(/^\$\{\{\s*|\s*\}\}$/g, '');return Function('github','startsWith',diff --git a/.github/scripts/ci-pr-gate.mjs b/.github/scripts/ci-pr-gate.mjsnew file mode 100644index 0000000000..3b8901f842--- /dev/null+++ b/.github/scripts/ci-pr-gate.mjs@@ -0,0 +1,45 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file When a pull request runs CI (spec:AST-030 FR17). A draft runs+ * nothing. A pull request runs CI when its branch lives in this repository+ * (pushing one needs write access) or a maintainer has labelled it `ci:run`.+ * Every other event (a push to main, a merge-group entry, a dispatch) passes.+ *+ * Jobs that report a required context keep only the draft skip: for a pull+ * request CI does not run, their first step fails with the reason, because a+ * skipped required check counts as passing.+ */++const TRUSTED =+ '(github.event.pull_request.head.repo.full_name == github.repository || ' ++ "contains(github.event.pull_request.labels.*.name, 'ci:run'))";++/** Every job that can start on a pull request begins with this. */+export const PR_CI_GATE = `(github.event_name != 'pull_request' || !github.event.pull_request.draft && ${TRUSTED})`;++/** A job that reports a required context begins with this instead. */+export const PR_REPORT_GATE =+ "(github.event_name != 'pull_request' || !github.event.pull_request.draft)";++/** The condition of a required job's first step, which fails with the reason. */+export const PR_HELD = `github.event_name == 'pull_request' && !${TRUSTED}`;++/** A job condition with a gate in front: `${{ GATE && (condition) }}`. */+export function gated(condition, gate = PR_CI_GATE) {+ if (condition == null || condition === '') return gate;+ const expression = condition.replace(/^\$\{\{\s*|\s*\}\}$/g, '');+ const wrapped = `${gate} && (${expression})`;+ return condition.startsWith('${{') ? `\${{ ${wrapped} }}` : wrapped;+}++/** The job's own condition, without the gate in front. */+export function ungated(condition) {+ const expression = condition.replace(/^\$\{\{\s*|\s*\}\}$/g, '');+ for (const gate of [PR_CI_GATE, PR_REPORT_GATE]) {+ const prefix = `${gate} && (`;+ if (expression.startsWith(prefix))+ return expression.slice(prefix.length, -1);+ }+ return expression;+}diff --git a/.github/scripts/ci-pr-gate.test.mjs b/.github/scripts/ci-pr-gate.test.mjsnew file mode 100644index 0000000000..f170e27f62--- /dev/null+++ b/.github/scripts/ci-pr-gate.test.mjs@@ -0,0 +1,253 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file A pull request runs CI when it is ready and its branch lives in this+ * repository or a maintainer labelled it `ci:run` (spec:AST-030 FR17).+ */++import fs from 'node:fs';+import path from 'node:path';++import {describe, expect, it} from 'vitest';+import yaml from 'yaml';++import {PR_CI_GATE, PR_HELD, PR_REPORT_GATE, ungated} from './ci-pr-gate.mjs';++/**+ * Whether a workflow starts when a pull request is opened or updated: any+ * `pull_request` trigger (bare, in a list, or a map) except one that lists+ * only `closed`. A trigger with no `types` takes GitHub's default ones.+ */+function startsOnPullRequest(workflow) {+ const on = workflow.on ?? workflow[true];+ if (on === 'pull_request') return true;+ if (Array.isArray(on)) return on.includes('pull_request');+ if (on == null || typeof on !== 'object' || !('pull_request' in on))+ return false;+ const types = on.pull_request?.types;+ return !(types?.length && types.every(type => type === 'closed'));+}++const dir = path.resolve(import.meta.dirname, '../workflows');+const workflows = fs+ .readdirSync(dir)+ .filter(name => name.endsWith('.yml'))+ .map(name => [+ name,+ yaml.parse(fs.readFileSync(path.join(dir, name), 'utf8')),+ ])+ .filter(([, value]) => startsOnPullRequest(value));+// The jobs that report a required context (build, test, docsite-test, lint).+const REQUIRED = {+ 'ci.yml': ['build', 'docsite-test', 'test'],+ 'lint.yml': ['lint'],+};++const escape = text => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+const startsWithGate = gate => new RegExp(`^(\\$\\{\\{ )?${escape(gate)}`);++function pullRequest({draft = false, fork = false, labels = []}) {+ return {+ draft,+ head: {repo: {full_name: fork ? 'someone/astryx' : 'meta/astryx'}},+ labels: labels.map(name => ({name})),+ };+}++/** Evaluates a gate expression as Actions would, for one event. */+function evaluate(expression, {event = 'pull_request', ...pr}) {+ const github = {+ event_name: event,+ repository: 'meta/astryx',+ event: {pull_request: event === 'pull_request' ? pullRequest(pr) : null},+ };+ const js = expression.replace(+ /\.labels\.\*\.name/g,+ '.labels.map(l => l.name)',+ );+ return Function(+ 'github',+ 'contains',+ `return Boolean(${js});`,+ )(github, (list, item) => list.includes(item));+}++/**+ * Whether a job's condition starts it for an unlabelled fork with every job it+ * needs skipped, under Actions' rule: a condition with no status-check function+ * (`always()`, `cancelled()`, `failure()`, `success()`) also needs `success()`,+ * which is false once a needed job skipped.+ */+function startsWithNeedsSkipped(condition, needs, pr = {fork: true}) {+ const expression = ungated(condition)+ .replace(`${PR_REPORT_GATE} && (`, '(')+ .replace(/^\$\{\{\s*|\s*\}\}$/g, '')+ .replace(/\.labels\.\*\.name/g, '.labels.map(l => l.name)');+ const hasStatusCheck = /\b(always|cancelled|failure|success)\(\)/.test(+ expression,+ );+ const succeeded = Object.values(needs).every(+ need => need.result === 'success',+ );+ return Function(+ 'github',+ 'needs',+ 'always',+ 'cancelled',+ 'failure',+ 'success',+ 'startsWith',+ 'contains',+ `return Boolean(${hasStatusCheck ? '' : 'success() && '}(${expression.replace(/needs\.([a-z][a-z0-9-]*)/g, 'needs["$1"]')}));`,+ )(+ {+ event_name: 'pull_request',+ base_ref: 'main',+ repository: 'meta/astryx',+ event: {pull_request: pullRequest(pr)},+ },+ needs,+ () => true,+ () => false,+ () => !succeeded,+ () => succeeded,+ (value, prefix) => String(value ?? '').startsWith(prefix),+ (list, item) => list.includes(item),+ );+}++const runs = event => evaluate(PR_CI_GATE, event);+const held = event => evaluate(PR_HELD, event);++describe('pull-request CI gate (spec:AST-030 FR17)', () => {+ it('selects every workflow a pull request update starts, with or without listed types', () => {+ expect(+ startsOnPullRequest({on: {pull_request: {branches: ['main']}}}),+ ).toBe(true);+ expect(startsOnPullRequest({on: {pull_request: null}})).toBe(true);+ expect(startsOnPullRequest({on: 'pull_request'})).toBe(true);+ expect(startsOnPullRequest({on: ['push', 'pull_request']})).toBe(true);+ expect(startsOnPullRequest({on: {pull_request: {types: ['opened']}}})).toBe(+ true,+ );+ expect(startsOnPullRequest({on: {pull_request: {types: ['closed']}}})).toBe(+ false,+ );+ expect(startsOnPullRequest({on: {push: {branches: ['main']}}})).toBe(false);+ expect(startsOnPullRequest({on: 'push'})).toBe(false);+ });++ it('finds the pull-request workflows', () => {+ expect(workflows.map(([name]) => name).sort()).toEqual([+ 'ci.yml',+ 'cli-smoke-test.yml',+ 'codemod-verify.yml',+ 'crowdin-download.yml',+ 'internal-registry.yml',+ 'lint.yml',+ ]);+ });++ it.each(workflows)(+ '%s starts when a draft is marked ready, never on a label, and gates every job that can start',+ (name, value) => {+ expect((value.on ?? value[true]).pull_request.types).toEqual([+ 'opened',+ 'synchronize',+ 'reopened',+ 'ready_for_review',+ ]);+ for (const [id, job] of Object.entries(value.jobs)) {+ const condition = String(job.if ?? '');+ if (REQUIRED[name]?.includes(id)) {+ // Skips only a draft. For an unlabelled fork it starts even when every+ // job it needs skipped, and its first step fails with the reason.+ expect(condition, `${name}/${id}`).toMatch(+ startsWithGate(PR_REPORT_GATE),+ );+ const needs = Object.fromEntries(+ [job.needs ?? []]+ .flat()+ .map(need => [need, {result: 'skipped', outputs: {}}]),+ );+ expect(+ startsWithNeedsSkipped(condition, needs),+ `${name}/${id}`,+ ).toBe(true);+ // A pull request that may run CI keeps the job's own rule: a build+ // join whose Storybook build skipped (spec-only, release bump) skips.+ if (id === 'build') {+ expect(startsWithNeedsSkipped(condition, needs, {}), id).toBe(+ false,+ );+ }+ expect(job.steps[0], `${name}/${id}`).toMatchObject({+ if: `\${{ ${PR_HELD} }}`,+ });+ expect(job.steps[0].run).toContain('exit 1');+ continue;+ }+ // A job that needs others is skipped with them, unless it asks to run+ // anyway; a dispatch-only job never starts on a pull request.+ if (+ job.needs &&+ !/always\(\)|cancelled\(\)|failure\(\)/.test(condition)+ )+ continue;+ if (+ /^(\$\{\{\s*)?(always\(\) && )?github\.event_name == 'workflow_dispatch' &&/.test(+ condition,+ )+ )+ continue;+ expect(condition, `${name}/${id}`).toMatch(startsWithGate(PR_CI_GATE));+ }+ },+ );++ it('models the implicit success() a condition without a status check gets', () => {+ const skipped = {a: {result: 'skipped'}};+ // Without a status-check function, a skipped need skips the job, so a+ // required join that dropped its !cancelled() would pass as skipped.+ expect(+ startsWithNeedsSkipped(+ "${{ github.event_name == 'pull_request' }}",+ skipped,+ ),+ ).toBe(false);+ expect(+ startsWithNeedsSkipped(+ "${{ !cancelled() && github.event_name == 'pull_request' }}",+ skipped,+ ),+ ).toBe(true);+ expect(startsWithNeedsSkipped('${{ always() }}', skipped)).toBe(true);+ });++ it('runs a pull request from a branch here, or from a fork once labelled; never a draft', () => {+ expect(runs({})).toBe(true);+ expect(runs({fork: true})).toBe(false);+ expect(runs({fork: true, labels: ['ci:run']})).toBe(true);+ expect(runs({fork: true, labels: ['ci:heavy-lanes']})).toBe(false);+ expect(runs({draft: true})).toBe(false);+ expect(runs({draft: true, fork: true, labels: ['ci:run']})).toBe(false);+ });++ it('skips the required checks of a draft and fails those of an unlabelled fork', () => {+ const reports = event => evaluate(PR_REPORT_GATE, event) && !held(event);+ expect(reports({})).toBe(true);+ expect(reports({fork: true, labels: ['ci:run']})).toBe(true);+ expect(evaluate(PR_REPORT_GATE, {fork: true})).toBe(true);+ expect(held({fork: true})).toBe(true);+ expect(evaluate(PR_REPORT_GATE, {draft: true})).toBe(false);+ });++ it('passes every event that is not a pull request', () => {+ for (const event of ['push', 'merge_group', 'workflow_dispatch']) {+ expect(runs({event}), event).toBe(true);+ expect(evaluate(PR_REPORT_GATE, {event}) && !held({event}), event).toBe(+ true,+ );+ }+ });+});diff --git a/.github/scripts/heavy-caps-action.test.mjs b/.github/scripts/heavy-caps-action.test.mjsnew file mode 100644index 0000000000..702b9beb44--- /dev/null+++ b/.github/scripts/heavy-caps-action.test.mjs@@ -0,0 +1,312 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Per-author caps on heavy suites (.github/actions/heavy-caps,+ * spec:AST-030 FR16). These cases run the action's real script, as+ * actions/github-script runs it, against a stubbed GitHub API.+ */++import fs from 'node:fs';+import path from 'node:path';++import {describe, expect, it} from 'vitest';+import yaml from 'yaml';++const root = path.resolve(import.meta.dirname, '../..');+const action = yaml.parse(+ fs.readFileSync(+ path.join(root, '.github/actions/heavy-caps/action.yml'),+ 'utf8',+ ),+);+const script = action.runs.steps.find(step =>+ step.uses?.startsWith('actions/github-script@'),+).with.script;+const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor;++const QUEUED =+ 'Queued behind your 3 oldest PRs: runs on a push once it is among them, or at the pre-merge re-run.';+const CAPPED = 'Daily heavy-run cap reached, runs tomorrow or at pre-merge.';++function pullRequestContext(pr = {}) {+ return {+ eventName: 'pull_request',+ repo: {owner: 'o', repo: 'r'},+ runId: 1,+ payload: {+ pull_request: {+ number: 7,+ head: {ref: 'fix/a', repo: {full_name: 'author/r'}},+ user: {login: 'author'},+ ...pr,+ },+ },+ };+}++/** Runs the action script; returns the failure and warning messages. */+async function check({+ context = pullRequestContext(),+ open = [],+ runs = [],+ attempt = '1',+} = {}) {+ const messages = {failed: [], warning: []};+ const core = {+ setFailed: message => messages.failed.push(message),+ warning: message => messages.warning.push(message),+ };+ const github = {+ // The author's open non-draft PRs, oldest first.+ graphql: async () => {+ if (open instanceof Error) throw open;+ return {search: {nodes: open}};+ },+ rest: {+ actions: {+ // Today's ci.yml runs on a branch name, from any repository.+ listWorkflowRuns: async ({branch}) => ({+ data: {workflow_runs: runs.filter(run => run.head_branch === branch)},+ }),+ // A CI run has more jobs than the API's default page of 30; a run whose+ // heavy job ran its suite has a successful marker step.+ listJobsForWorkflowRun: async ({run_id, per_page = 30}) => {+ if (per_page < 100) throw new Error('read one default page of jobs');+ const heavy = runs.find(run => run.id === run_id).heavy !== false;+ return {+ data: {+ jobs: [+ {+ steps: heavy+ ? [{name: 'Heavy suite runs', conclusion: 'success'}]+ : [],+ },+ ],+ },+ };+ },+ },+ },+ };+ const saved = process.env.GITHUB_RUN_ATTEMPT;+ process.env.GITHUB_RUN_ATTEMPT = attempt;+ try {+ await new AsyncFunction('github', 'context', 'core', script)(+ github,+ context,+ core,+ );+ } finally {+ if (saved === undefined) delete process.env.GITHUB_RUN_ATTEMPT;+ else process.env.GITHUB_RUN_ATTEMPT = saved;+ }+ return messages;+}++const fork = {nameWithOwner: 'author/r'};+const here = {nameWithOwner: 'o/r'};+const pulls = (...refs) =>+ refs.map((headRefName, i) => ({+ number: i + 1,+ headRefName,+ headRepository: headRefName.startsWith('fix/') ? fork : here,+ }));+const me = {number: 7, headRefName: 'fix/a', headRepository: fork};+let nextRun = 100;+const runsOn = (count, head_branch = 'fix/a', run = {}) =>+ Array.from({length: count}, () => ({+ id: nextRun++,+ head_branch,+ head_repository: {+ full_name: head_branch.startsWith('fix/') ? 'author/r' : 'o/r',+ },+ ...run,+ }));++describe('per-author caps on heavy suites (spec:AST-030 FR16)', () => {+ it("fails a heavy job behind the author's 3 oldest PRs", async () => {+ const open = [...pulls('fix/b', 'fix/c', 'fix/d'), me];+ expect((await check({open})).failed).toEqual([QUEUED]);+ expect((await check({open: open.slice(1)})).failed).toEqual([]);+ // The search holds at most the author's 100 oldest; a newer pull request+ // missing from it is still behind them.+ const many = pulls(...Array.from({length: 100}, (_, i) => `fix/${i}`));+ expect(+ (await check({context: pullRequestContext({number: 300}), open: many}))+ .failed,+ ).toEqual([QUEUED]);+ });++ it("fails a heavy job past the author's 12 heavy runs today", async () => {+ expect((await check({open: [me], runs: runsOn(12)})).failed).toEqual([+ CAPPED,+ ]);+ // The cap counts the author's heavy runs across all of their oldest pull+ // requests, not only the one deciding.+ const spread = await check({+ open: [...pulls('fix/b', 'fix/c'), me],+ runs: [...runsOn(6, 'fix/b'), ...runsOn(3, 'fix/c'), ...runsOn(3)],+ });+ expect(spread.failed).toEqual([CAPPED]);+ // When the deciding pull request is the author's oldest, the count still+ // reaches their third-oldest.+ const first = await check({+ context: pullRequestContext({number: 1}),+ open: [{...me, number: 1}, ...pulls('fix/x', 'fix/b', 'fix/c').slice(1)],+ runs: [...runsOn(4), ...runsOn(4, 'fix/b'), ...runsOn(4, 'fix/c')],+ });+ expect(first.failed).toEqual([CAPPED]);+ // Cancelled runs, runs whose heavy suites never ran (a queued PR) and runs+ // on other branches are not heavy runs.+ const light = await check({+ open: [me],+ runs: [+ ...runsOn(11),+ ...runsOn(5, 'fix/a', {conclusion: 'cancelled'}),+ ...runsOn(5, 'fix/a', {heavy: false}),+ ...runsOn(5, 'fix/old-merged'),+ ],+ });+ expect(light.failed).toEqual([]);+ // A run is the pull request's by its branch and that branch's repository:+ // another fork's same-named branch is not, whoever pushed.+ const elsewhere = await check({+ open: [me],+ runs: [+ ...runsOn(11),+ ...runsOn(5, 'fix/a', {head_repository: {full_name: 'other/r'}}),+ ],+ });+ expect(elsewhere.failed).toEqual([]);+ });++ it('counts each agent lane of the shared login as an author, with backstops', async () => {+ const context = pullRequestContext({+ user: {login: 'cixzhang'},+ head: {ref: 'lane4/x', repo: {full_name: 'o/r'}},+ });+ const mine = {number: 7, headRefName: 'lane4/x', headRepository: here};+ const others = await check({+ context,+ open: [...pulls('lane1/a', 'lane2/b', 'lane3/c', 'lane0/d'), mine],+ runs: [...runsOn(30, 'lane1/a'), ...runsOn(2, 'lane4/x')],+ });+ expect(others.failed).toEqual([]);+ const backstop = await check({+ context,+ open: [+ ...pulls('lane1/a', 'lane2/b', 'lane3/c', 'lane0/d', 'ci/e'),+ mine,+ ],+ });+ expect(backstop.failed).toEqual([QUEUED]);+ // The login's forty-run count reaches its fifth-oldest pull request.+ const fifth = await check({+ context: pullRequestContext({+ number: 1,+ user: {login: 'cixzhang'},+ head: {ref: 'lane4/x', repo: {full_name: 'o/r'}},+ }),+ open: [+ {...mine, number: 1},+ ...pulls('x', 'lane1/a', 'lane2/b', 'lane3/c', 'lane0/d').slice(1),+ ],+ runs: ['lane4/x', 'lane1/a', 'lane2/b', 'lane3/c', 'lane0/d'].flatMap(+ branch => runsOn(8, branch),+ ),+ });+ expect(fifth.failed).toEqual([CAPPED]);+ // The login as a whole stops at forty heavy runs a day.+ const lanes = [...pulls('lane1/a', 'lane2/b'), mine];+ expect(+ (+ await check({+ context,+ open: lanes,+ runs: [...runsOn(38, 'lane1/a'), ...runsOn(2, 'lane4/x')],+ })+ ).failed,+ ).toEqual([CAPPED]);+ expect(+ (+ await check({+ context,+ open: lanes,+ runs: [...runsOn(37, 'lane1/a'), ...runsOn(2, 'lane4/x')],+ })+ ).failed,+ ).toEqual([]);+ });++ it('exempts bots and does not count the run deciding', async () => {+ const bot = await check({+ context: pullRequestContext({user: {login: 'dependabot[bot]'}}),+ open: [...pulls('fix/b', 'fix/c', 'fix/d'), me],+ });+ expect(bot.failed).toEqual([]);+ const self = await check({+ context: {...pullRequestContext(), runId: 900},+ open: [me],+ runs: [+ ...runsOn(11),+ {+ id: 900,+ head_branch: 'fix/a',+ head_repository: {full_name: 'author/r'},+ },+ ],+ });+ expect(self.failed).toEqual([]);+ });++ it('exempts the pre-merge re-run and events other than a pull request, and runs when the lookup fails', async () => {+ expect(+ (await check({open: [me], runs: runsOn(20), attempt: '2'})).failed,+ ).toEqual([]);+ expect(+ (+ await check({+ context: {+ eventName: 'merge_group',+ repo: {owner: 'o', repo: 'r'},+ payload: {},+ },+ open: new Error('unused'),+ })+ ).failed,+ ).toEqual([]);+ const failed = await check({open: new Error('rate limited')});+ expect(failed.failed).toEqual([]);+ expect(failed.warning[0]).toContain('running the heavy suite');+ });++ it('runs in each heavy job right after its checkout, followed by the step the daily cap counts', () => {+ const ci = yaml.parse(+ fs.readFileSync(path.join(root, '.github/workflows/ci.yml'), 'utf8'),+ );+ const heavyJobs = Object.entries(ci.jobs).filter(([, job]) =>+ job.steps?.some(step => step.uses === './.github/actions/heavy-caps'),+ );+ expect(heavyJobs.map(([id]) => id).sort()).toEqual([+ 'fixture-contrast',+ 'pr-interaction',+ 'test-build',+ ]);+ for (const [id, job] of heavyJobs) {+ const caps = job.steps.findIndex(+ step => step.uses === './.github/actions/heavy-caps',+ );+ expect(job.steps[caps - 1].uses, id).toMatch(/^actions\/checkout@/);+ expect(job.permissions, id).toMatchObject({+ actions: 'read',+ 'pull-requests': 'read',+ });+ expect(job.steps[caps + 1], id).toMatchObject({+ name: 'Heavy suite runs',+ run: 'true',+ });+ expect(job.steps[caps + 1].if, id).toBe(job.steps[caps].if);+ expect(job.steps[caps].if, id).toBe(job.steps[caps - 1].if);+ }+ });+});diff --git a/.github/scripts/spec-owner-workflow.test.mjs b/.github/scripts/spec-owner-workflow.test.mjsindex 9160b309b8..464f93d9f5 100644--- a/.github/scripts/spec-owner-workflow.test.mjs+++ b/.github/scripts/spec-owner-workflow.test.mjs@@ -6,6 +6,7 @@ import path from 'node:path';import {spawnSync} from 'node:child_process';import {createRequire} from 'node:module';import {describe, expect, it} from 'vitest';+import {PR_REPORT_GATE, gated} from './ci-pr-gate.mjs';const require = createRequire(import.meta.url);@@ -229,7 +230,7 @@ describe('spec-only workflow contract', () => {it('fails closed when file APIs are truncated or scope classification fails', () => {const ci = read('.github/workflows/ci.yml');expect(ci).toContain(- "if: ${{ github.event_name != 'workflow_dispatch' && needs.check-scope.outputs.release_bump != 'true' && always() && !cancelled() }}",+ `if: ${gated("${{ github.event_name != 'workflow_dispatch' && needs.check-scope.outputs.release_bump != 'true' && always() && !cancelled() }}", PR_REPORT_GATE)}`,);expect(ci).toContain("if: needs.check-scope.result != 'success'");diff --git a/.github/scripts/visual-maintenance-workflow.test.mjs b/.github/scripts/visual-maintenance-workflow.test.mjsindex 92045ddd18..c329b9ccc0 100644--- a/.github/scripts/visual-maintenance-workflow.test.mjs+++ b/.github/scripts/visual-maintenance-workflow.test.mjs@@ -13,6 +13,7 @@ import path from 'node:path';import {describe, expect, it} from 'vitest';import yaml from 'yaml';+import {ungated} from './ci-pr-gate.mjs';const root = path.resolve(import.meta.dirname, '../..');const workflow = yaml.parse(@@ -34,7 +35,8 @@ function runs(labels = [],} = {},) {- const expression = (job.if ?? 'true')+ // The pull-request gate in front is ci-pr-gate.test.mjs's to prove.+ const expression = ungated(job.if ?? 'true').replace(/^\$\{\{\s*|\s*\}\}$/g, '').replace(/needs\.([a-z][a-z0-9-]*)/g, 'needs["$1"]')// GitHub's object filter: `labels.*.name` lists the labels' names.diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 1a6dd8d963..c956dd433f 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -9,6 +9,10 @@ name: CIon:pull_request:+ # A draft runs nothing until it is ready; an outside contributor's pull+ # request runs once a maintainer labels it ci:run and pushes or reopens+ # (spec:AST-030 FR17).+ types: [opened, synchronize, reopened, ready_for_review]branches: ['main', 'release/**']merge_group:# Explicit release checks and baseline capture share the canonical owners.@@ -87,7 +91,7 @@ jobs:# Detect lightweight changes. Missing merge-base data fails closed.check-scope:- if: github.event_name != 'workflow_dispatch' || inputs.operation == 'release-check'+ if: (github.event_name != 'pull_request' || !github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run'))) && (github.event_name != 'workflow_dispatch' || inputs.operation == 'release-check')runs-on: ubuntu-slimpermissions:contents: read@@ -314,7 +318,7 @@ jobs:# below (minutes on a larger runner). The step after the checkout still# checks the exact branch contract, and required lint validates merge-back# branches with the same trusted policy.- if: ${{ github.event_name == 'pull_request' && github.base_ref == 'main' && startsWith(github.head_ref, 'chore/merge-v') && endsWith(github.head_ref, '-to-main') }}+ if: ${{ (github.event_name != 'pull_request' || !github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run'))) && (github.event_name == 'pull_request' && github.base_ref == 'main' && startsWith(github.head_ref, 'chore/merge-v') && endsWith(github.head_ref, '-to-main')) }}# Match the stable publisher so byte parity covers the same packed manifest.runs-on: ${{ startsWith(github.head_ref, 'chore/merge-v') && '4-core-ubuntu' || 'ubuntu-latest' }}timeout-minutes: 15@@ -401,12 +405,17 @@ jobs:# spec-only lane validates spec records here, where it always has.docsite-test:needs: [check-scope, docsite-browser, docsite-data]- if: ${{ github.event_name != 'workflow_dispatch' && needs.check-scope.outputs.release_bump != 'true' && always() && !cancelled() }}+ if: ${{ (github.event_name != 'pull_request' || !github.event.pull_request.draft) && (github.event_name != 'workflow_dispatch' && needs.check-scope.outputs.release_bump != 'true' && always() && !cancelled()) }}runs-on: ubuntu-24.04-armtimeout-minutes: 15permissions:contents: readsteps:+ - name: Require a branch in this repository or the ci:run label+ if: ${{ github.event_name == 'pull_request' && !(github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run')) }}+ run: |+ echo "::error::Waiting for a maintainer's ci:run label: an outside contributor's pull request runs CI once a maintainer adds it (spec:AST-030 FR17)."+ exit 1- name: Require successful scope classificationif: needs.check-scope.result != 'success'run: |@@ -651,7 +660,7 @@ jobs:test-ui:name: test-ui (${{ matrix.shard }}/${{ strategy.job-total }})needs: [check-scope]- if: ${{ github.event_name != 'workflow_dispatch' && always() && !cancelled() && needs.check-scope.outputs.spec_only != 'true' }}+ if: ${{ (github.event_name != 'pull_request' || !github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run'))) && (github.event_name != 'workflow_dispatch' && always() && !cancelled() && needs.check-scope.outputs.spec_only != 'true') }}# One runner ran the whole UI project in ~16 minutes and set the PR's wall# time. Vitest's --shard gives each leg an equal share of the files; the# two slowest files (~3.5 minutes each) bound a leg, so more legs stop@@ -757,7 +766,7 @@ jobs:test-node:name: test-node (${{ matrix.shard }}/${{ strategy.job-total }})needs: [check-scope]- if: ${{ github.event_name != 'workflow_dispatch' && always() && !cancelled() && needs.check-scope.outputs.spec_only != 'true' }}+ if: ${{ (github.event_name != 'pull_request' || !github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run'))) && (github.event_name != 'workflow_dispatch' && always() && !cancelled() && needs.check-scope.outputs.spec_only != 'true') }}# One runner ran the Node project in ~12 minutes. Vitest's --shard splits# the files across the legs; `test` joins them.strategy:@@ -845,7 +854,7 @@ jobs:# without work.native-swift-scope:needs: [check-scope]- if: ${{ github.event_name != 'workflow_dispatch' && always() && !cancelled() && needs.check-scope.outputs.spec_only != 'true' }}+ if: ${{ (github.event_name != 'pull_request' || !github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run'))) && (github.event_name != 'workflow_dispatch' && always() && !cancelled() && needs.check-scope.outputs.spec_only != 'true') }}runs-on: ubuntu-slimpermissions:contents: read@@ -902,7 +911,7 @@ jobs:test-native-swift:needs: [check-scope, native-swift-scope]- if: ${{ github.event_name != 'workflow_dispatch' && always() && !cancelled() && needs.check-scope.outputs.spec_only != 'true' }}+ if: ${{ (github.event_name != 'pull_request' || !github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run'))) && (github.event_name != 'workflow_dispatch' && always() && !cancelled() && needs.check-scope.outputs.spec_only != 'true') }}runs-on: ${{ needs.native-swift-scope.outputs.applies == 'true' && 'macos-15' || 'ubuntu-slim' }}timeout-minutes: 30permissions:@@ -933,7 +942,7 @@ jobs:registry-contract:name: registry-contract (${{ matrix.leg }})needs: [check-scope]- if: ${{ github.event_name != 'workflow_dispatch' && always() && !cancelled() && needs.check-scope.outputs.spec_only != 'true' }}+ if: ${{ (github.event_name != 'pull_request' || !github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run'))) && (github.event_name != 'workflow_dispatch' && always() && !cancelled() && needs.check-scope.outputs.spec_only != 'true') }}# The preview and hidden production registries are generated and verified# independently, so each gets its own leg (~9 minutes in one job). `test`# joins them: the job result is success only when both passed.@@ -1014,11 +1023,16 @@ jobs:test-native-swift,pr-interaction,]- if: ${{ github.event_name != 'workflow_dispatch' && always() && !cancelled() && needs.check-scope.outputs.spec_only != 'true' }}+ if: ${{ (github.event_name != 'pull_request' || !github.event.pull_request.draft) && (github.event_name != 'workflow_dispatch' && always() && !cancelled() && needs.check-scope.outputs.spec_only != 'true') }}runs-on: ubuntu-slimpermissions:contents: readsteps:+ - name: Require a branch in this repository or the ci:run label+ if: ${{ github.event_name == 'pull_request' && !(github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run')) }}+ run: |+ echo "::error::Waiting for a maintainer's ci:run label: an outside contributor's pull request runs CI once a maintainer adds it (spec:AST-030 FR17)."+ exit 1- uses: actions/checkout@v7- name: Require expected test-owner outcomes@@ -1041,7 +1055,7 @@ jobs:# builds no Sandbox of its own.build-storybook:needs: [check-scope]- if: ${{ (github.event_name != 'workflow_dispatch' || inputs.operation == 'release-check') && always() && !cancelled() && needs.check-scope.outputs.spec_only != 'true' }}+ if: ${{ (github.event_name != 'pull_request' || !github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run'))) && ((github.event_name != 'workflow_dispatch' || inputs.operation == 'release-check') && always() && !cancelled() && needs.check-scope.outputs.spec_only != 'true') }}# Every browser lane waits for this job, and the package builds and the# Storybook build run side by side (build-packages-and-storybook.mjs).runs-on: ${{ (github.event_name == 'workflow_dispatch' && inputs.operation == 'release-check' && github.triggering_actor != 'github-actions[bot]') && '4-core-ubuntu' || 'ubuntu-latest' }}@@ -1283,7 +1297,7 @@ jobs:# so a type error still fails both.typecheck:needs: [check-scope]- if: ${{ (github.event_name != 'workflow_dispatch' || inputs.operation == 'release-check') && always() && !cancelled() && needs.check-scope.outputs.spec_only != 'true' }}+ if: ${{ (github.event_name != 'pull_request' || !github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run'))) && ((github.event_name != 'workflow_dispatch' || inputs.operation == 'release-check') && always() && !cancelled() && needs.check-scope.outputs.spec_only != 'true') }}runs-on: ${{ (github.event_name == 'workflow_dispatch' && inputs.operation == 'release-check' && github.triggering_actor != 'github-actions[bot]') && '2-core-ubuntu-arm' || 'ubuntu-24.04-arm' }}timeout-minutes: ${{ github.event_name == 'workflow_dispatch' && 360 || 15 }}permissions:@@ -1341,10 +1355,15 @@ jobs:# gate too.build:needs: [build-storybook, typecheck]- if: ${{ github.event_name != 'workflow_dispatch' && !cancelled() && needs.build-storybook.result != 'skipped' }}+ if: ${{ (github.event_name != 'pull_request' || !github.event.pull_request.draft) && (github.event_name != 'workflow_dispatch' && !cancelled() && (needs.build-storybook.result != 'skipped' || github.event_name == 'pull_request' && !(github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run')))) }}runs-on: ubuntu-slimpermissions: {}steps:+ - name: Require a branch in this repository or the ci:run label+ if: ${{ github.event_name == 'pull_request' && !(github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run')) }}+ run: |+ echo "::error::Waiting for a maintainer's ci:run label: an outside contributor's pull request runs CI once a maintainer adds it (spec:AST-030 FR17)."+ exit 1- name: Assert parallel builds succeededrun: |echo "build-storybook: ${{ needs.build-storybook.result }}"@@ -1648,7 +1667,7 @@ jobs:# Stable required context joining the scoped audit/guards and browser specs.pr-a11y:needs: [check-components, pr-a11y-guards, pr-a11y-specs]- if: ${{ always() && ((github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'ci:heavy-lanes')) || (github.event_name == 'workflow_dispatch' && inputs.operation == 'release-check')) && needs.check-components.outputs.has_components == 'true' }}+ if: ${{ (github.event_name != 'pull_request' || !github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run'))) && (always() && ((github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'ci:heavy-lanes')) || (github.event_name == 'workflow_dispatch' && inputs.operation == 'release-check')) && needs.check-components.outputs.has_components == 'true') }}runs-on: ubuntu-slimtimeout-minutes: 5permissions:@@ -1796,7 +1815,7 @@ jobs:# passes without them.interaction-scope:needs: [check-scope]- if: ${{ github.event_name != 'workflow_dispatch' && always() && !cancelled() && needs.check-scope.outputs.spec_only != 'true' }}+ if: ${{ (github.event_name != 'pull_request' || !github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run'))) && (github.event_name != 'workflow_dispatch' && always() && !cancelled() && needs.check-scope.outputs.spec_only != 'true') }}runs-on: ubuntu-slimtimeout-minutes: 5permissions:@@ -1877,12 +1896,15 @@ jobs:pr-interaction:needs: [check-scope, interaction-scope, build-storybook]- if: ${{ github.event_name != 'workflow_dispatch' && always() && !cancelled() && needs.check-scope.outputs.spec_only != 'true' }}+ if: ${{ (github.event_name != 'pull_request' || !github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run'))) && (github.event_name != 'workflow_dispatch' && always() && !cancelled() && needs.check-scope.outputs.spec_only != 'true') }}# Frame evidence measures timing: four cores, one Playwright worker.runs-on: ${{ needs.interaction-scope.outputs.applies == 'true' && 'ubuntu-latest' || 'ubuntu-slim' }}timeout-minutes: 15permissions:+ # The heavy-suite caps read the author's pull requests and runs.+ actions: readcontents: read+ pull-requests: readsteps:- name: Require a decided interaction scopeif: needs.interaction-scope.result != 'success'@@ -1906,6 +1928,15 @@ jobs:with:ref: ${{ github.event.pull_request.head.sha }}+ - name: Per-author heavy-suite caps+ if: needs.interaction-scope.outputs.applies == 'true'+ uses: ./.github/actions/heavy-caps++ # The daily heavy-run cap counts this step (spec:AST-030 FR16).+ - name: Heavy suite runs+ if: needs.interaction-scope.outputs.applies == 'true'+ run: 'true'+- name: Verify evidence checkoutif: needs.interaction-scope.outputs.applies == 'true'env:@@ -1958,10 +1989,20 @@ jobs:runs-on: ubuntu-24.04-armtimeout-minutes: 15permissions:+ # The heavy-suite caps read the author's pull requests and runs.+ actions: readcontents: read+ pull-requests: readsteps:- uses: actions/checkout@v7+ - name: Per-author heavy-suite caps+ uses: ./.github/actions/heavy-caps++ # The daily heavy-run cap counts this step (spec:AST-030 FR16).+ - name: Heavy suite runs+ run: 'true'+- uses: ./.github/actions/setup- name: Install Playwright@@ -1982,10 +2023,20 @@ jobs:runs-on: ubuntu-24.04-armtimeout-minutes: 15permissions:+ # The heavy-suite caps read the author's pull requests and runs.+ actions: readcontents: read+ pull-requests: readsteps:- uses: actions/checkout@v7+ - name: Per-author heavy-suite caps+ uses: ./.github/actions/heavy-caps++ # The daily heavy-run cap counts this step (spec:AST-030 FR16).+ - name: Heavy suite runs+ run: 'true'+- uses: ./.github/actions/setup- name: Install Playwright@@ -2007,13 +2058,13 @@ jobs:name: Stable visual scout (${{ matrix.shard }}/${{ strategy.job-total }})needs: [build-storybook, check-components]if: >-- !cancelled() &&+ (github.event_name != 'pull_request' || !github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run'))) && (!cancelled() &&needs.build-storybook.result == 'success' &&needs.check-components.result == 'success' &&(((github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'ci:heavy-lanes')) &&needs.check-components.outputs.has_stable_visual == 'true' &&needs.check-components.outputs.broad_stable_visual == 'true') ||- (github.event_name == 'workflow_dispatch' && inputs.operation == 'release-check'))+ (github.event_name == 'workflow_dispatch' && inputs.operation == 'release-check')))# Five legs: at three, each leg's scout took ~4.5 minutes and the visual# regression waited for the slowest one.strategy:@@ -2080,7 +2131,7 @@ jobs:needs:[build-storybook, check-components, maintenance-request, visual-scout]if: >-- !cancelled() &&+ (github.event_name != 'pull_request' || !github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run'))) && (!cancelled() &&(((github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'ci:heavy-lanes')) &&needs.build-storybook.result == 'success' &&needs.check-components.result == 'success' &&@@ -2089,7 +2140,7 @@ jobs:((inputs.operation == 'release-check' &&needs.build-storybook.result == 'success' &&needs.check-components.result == 'success') ||- (needs.maintenance-request.result == 'success' && inputs.operation == 'capture'))))+ (needs.maintenance-request.result == 'success' && inputs.operation == 'capture')))))runs-on: ${{ (github.event_name == 'workflow_dispatch' && inputs.operation == 'release-check' && github.triggering_actor != 'github-actions[bot]') && '2-core-ubuntu-arm' || 'ubuntu-24.04-arm' }}timeout-minutes: ${{ github.event_name == 'workflow_dispatch' && 360 || 15 }}permissions:@@ -2542,12 +2593,12 @@ jobs:name: pr-rtl (core)needs: [build-storybook, check-components, pr-rtl-shard]if: >-- always() && !cancelled() &&+ (github.event_name != 'pull_request' || !github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run'))) && (always() && !cancelled() &&((github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'ci:heavy-lanes')) ||(github.event_name == 'workflow_dispatch' && inputs.operation == 'release-check')) &&(needs.check-components.outputs.has_rtl_components == 'true' ||needs.check-components.outputs.has_rtl_harness == 'true' ||- needs.check-components.outputs.force_full_component_audits == 'true')+ needs.check-components.outputs.force_full_component_audits == 'true'))runs-on: ${{ (github.event_name == 'workflow_dispatch' && inputs.operation == 'release-check' && github.triggering_actor != 'github-actions[bot]') && '2-core-ubuntu-arm' || 'ubuntu-24.04-arm' }}timeout-minutes: 15permissions:@@ -2631,7 +2682,7 @@ jobs:# Stable required context joining the five package shards above.pr-rtl:needs: [check-scope, check-components, pr-rtl-shard, pr-rtl-merge]- if: ${{ always() && !cancelled() && (((github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'ci:heavy-lanes')) && needs.check-scope.outputs.spec_only != 'true') || (github.event_name == 'workflow_dispatch' && inputs.operation == 'release-check')) }}+ if: ${{ (github.event_name != 'pull_request' || !github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run'))) && (always() && !cancelled() && (((github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'ci:heavy-lanes')) && needs.check-scope.outputs.spec_only != 'true') || (github.event_name == 'workflow_dispatch' && inputs.operation == 'release-check'))) }}runs-on: ubuntu-slimtimeout-minutes: 5steps:@@ -2692,7 +2743,7 @@ jobs:pr-rtl-merge,pr-rtl,]- if: ${{ always() && github.event_name == 'pull_request' }}+ if: ${{ (github.event_name != 'pull_request' || !github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run'))) && (always() && github.event_name == 'pull_request') }}runs-on: ubuntu-slimtimeout-minutes: 5continue-on-error: truediff --git a/.github/workflows/cli-smoke-test.yml b/.github/workflows/cli-smoke-test.ymlindex c11004c0bb..c10938f4d2 100644--- a/.github/workflows/cli-smoke-test.yml+++ b/.github/workflows/cli-smoke-test.yml@@ -6,6 +6,7 @@ name: CLI Smoke Teston:pull_request:+ types: [opened, synchronize, reopened, ready_for_review]branches: ['main']# Runs only when something the CLI reads or the smoke scripts run can# change (spec:AST-030 FR14): every package (the CLI discovers Core, Lab,@@ -37,6 +38,7 @@ concurrency:jobs:smoke-test:+ if: (github.event_name != 'pull_request' || !github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run')))runs-on: ubuntu-24.04-arm# PR CI's budget is 15 minutes (see ci.yml).timeout-minutes: 15diff --git a/.github/workflows/codemod-verify.yml b/.github/workflows/codemod-verify.ymlindex 98ebfbbcbe..78853d075c 100644--- a/.github/workflows/codemod-verify.yml+++ b/.github/workflows/codemod-verify.yml@@ -15,6 +15,7 @@ name: Codemod Verifyon:pull_request:+ types: [opened, synchronize, reopened, ready_for_review]branches: ["main"]paths:- "packages/cli/assets/codemods/**"@@ -27,6 +28,7 @@ concurrency:jobs:verify-codemods:+ if: (github.event_name != 'pull_request' || !github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run')))runs-on: ubuntu-24.04-armpermissions:contents: readdiff --git a/.github/workflows/crowdin-download.yml b/.github/workflows/crowdin-download.ymlindex ee600792eb..9b73258c98 100644--- a/.github/workflows/crowdin-download.yml+++ b/.github/workflows/crowdin-download.yml@@ -23,6 +23,7 @@ name: Crowdin Translations Validationon:pull_request:+ types: [opened, synchronize, reopened, ready_for_review]branches: [main]paths:- 'packages/core/locales/*.json'@@ -35,6 +36,7 @@ concurrency:jobs:validate:+ if: (github.event_name != 'pull_request' || !github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run')))runs-on: ubuntu-latestpermissions:contents: readdiff --git a/.github/workflows/internal-registry.yml b/.github/workflows/internal-registry.ymlindex 4f4bfd5d9c..99e34174cd 100644--- a/.github/workflows/internal-registry.yml+++ b/.github/workflows/internal-registry.yml@@ -14,6 +14,7 @@ name: Internal Registryon:pull_request:+ types: [opened, synchronize, reopened, ready_for_review]branches: ['main']# Runs only when a dependency declaration or the lockfile can change what# the registry must serve (spec:AST-030 FR14). A merge-group entry, which@@ -36,6 +37,7 @@ concurrency:jobs:dependency-check:+ if: (github.event_name != 'pull_request' || !github.event.pull_request.draft && (github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run')))runs-on: ubuntu-latestpermissions:contents: readdiff --git a/.github/workflows/lint.yml b/.github/workflows/lint.ymlindex fe6e543fc0..a56be95d76 100644--- a/.github/workflows/lint.yml+++ b/.github/workflows/lint.yml@@ -6,6 +6,7 @@ on:push:branches: [main]pull_request:+ types: [opened, synchronize, reopened, ready_for_review]branches: [main]permissions: {}@@ -18,11 +19,17 @@ concurrency:jobs:lint:+ if: (github.event_name != 'pull_request' || !github.event.pull_request.draft)runs-on: ubuntu-24.04-armpermissions:contents: readsteps:+ - name: Require a branch in this repository or the ci:run label+ if: ${{ github.event_name == 'pull_request' && !(github.event.pull_request.head.repo.full_name == github.repository || contains(github.event.pull_request.labels.*.name, 'ci:run')) }}+ run: |+ echo "::error::Waiting for a maintainer's ci:run label: an outside contributor's pull request runs CI once a maintainer adds it (spec:AST-030 FR17)."+ exit 1# Enough history for the merge commit to reach its merge base with the# base branch, as ci.yml's check-scope checks out. At depth 1 the merge# base is never found, and every pull request ran full lint.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 571cb1d768..c699ee6e56 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -914,6 +914,28 @@ Storybook story for anything you added or altered.> `.github/workflows/**` can't be pushed on your behalf — GitHub requires the> author to update those; we'll ping you if so.)+### When CI runs on your pull request++- **Drafts run no CI.** Marking the pull request ready for review starts+ CI, which runs the checks your change reaches.+- **A pull request from a fork runs CI once a maintainer labels it+ `ci:run`.** Only maintainers can apply labels, so you don't need to ask: a+ maintainer adds it after a first look. The label takes effect on your next+ push, or when the maintainer closes and reopens the pull request; CI then+ runs on each push while the label stays. Until then the required checks fail+ with "Waiting for a maintainer's ci:run label".+- **`ci:heavy-lanes` opts a pull request into the visual, accessibility and+ RTL suites**, which otherwise run on `main` after it merges. A maintainer+ applies it when a change needs that evidence before merging; like `ci:run`,+ it takes effect on the next push or a close and reopen.+- **Pull requests from a branch in this repository run CI without the label**,+ since pushing a branch here needs write access. Maintainers who work from a+ fork either push their branches here or apply `ci:run` themselves.+- **Heavy browser suites are shared per author.** They run for an author's+ three oldest open pull requests, up to twelve such runs a day. A pull request+ past either limit shows a failing check that says why, and runs in full at+ its pre-merge re-run.+## Code StyleThe design-system rules — StyleX usage, semantic tokens, theming, APIdiff --git a/docs/specs/AST-030/spec.md b/docs/specs/AST-030/spec.mdindex 184f1662fd..6384c9bf8d 100644--- a/docs/specs/AST-030/spec.md+++ b/docs/specs/AST-030/spec.md@@ -38,7 +38,9 @@ affects_consumer_docs: []".github/scripts/change-scope.*",".github/scripts/*routing*.test.mjs",".github/scripts/pr-scope-touches.*",- ".github/scripts/workflow-paths.test.mjs"+ ".github/scripts/workflow-paths.test.mjs",+ ".github/actions/heavy-caps/**",+ ".github/scripts/ci-pr-gate.*"]}```@@ -264,6 +266,36 @@ they are separately named.`paths-ignore` or another exclusion list, which would run on any path no onethought to exclude.+- **FR16 — One author's pull requests share the heavy suites.** On a pull+ request, the heavy browser suites (the interaction proofs and the Build+ package's browser and fixture-contrast contracts) run only when the pull+ request is among its author's three oldest open non-draft pull requests and+ the author has had at most twelve heavy runs that UTC day. A heavy run is a+ CI run on one of those pull requests in which a heavy suite ran; a cancelled+ run does not count, and neither does a run whose heavy suites were held.+ Pull requests from the shared agent login count per branch prefix, and that+ login as a whole is also held to its five oldest pull requests and forty+ heavy runs a day; bot accounts are exempt. A held suite's check fails with+ "Queued behind your 3 oldest PRs: runs on a push once it is among them, or at+ the pre-merge re-run." or "Daily heavy-run cap reached, runs tomorrow or at+ pre-merge.", so no pull request passes the required checks without its heavy+ suites. A re-run, which is the pre-merge restart, is exempt from both limits,+ and when the limits cannot be looked up the suite runs. Merge-queue entries,+ `main`, release checks and the visual, accessibility and RTL owners a+ maintainer opts a pull request into with `ci:heavy-lanes` are unaffected.+- **FR17 — A pull request runs CI when it is ready and a maintainer can vouch+ for it.** A draft pull request runs no CI, and marking it ready for review+ starts its pull-request run, which runs what the change reaches (FR13,+ DEC-6). A pull request runs CI when its head branch lives in this repository,+ which pushing needs write access for, or when it carries the+ maintainer-applied `ci:run` label. The label takes effect on the next push or+ a close and reopen; applying or removing any label starts no run. For a pull+ request that may not run CI, the required contexts (FR7) report failure with+ "Waiting for a maintainer's ci:run label", never success, because a skipped+ required check would count as passing. Events other than a pull request (a+ push to `main`, a merge-group entry, a dispatch) are unaffected, and a fork's+ code never runs with the repository's secrets.+### Platform support- Supported feature/engine floor: GitHub pull-request and merge-group workflows@@ -299,18 +331,20 @@ read change (FR14).## Verification-| Contract | Verification | Representative states | Mutation or failure expectation |-| -------- | --------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| FR1–FR2 | classifier unit tests expose the surface set | knowledge; docsite; admitted tool; Core/Lab/Charts/Rich Text/Vega source; shared config; unknown | an unclassified path receives a specialized lane or a category has no check owner |-| FR3–FR4 | workflow contract tests execute an isolated trusted-base classifier | valid base; missing merge base; missing matcher/registry; classifier self-change; merge group | PR-controlled policy grants a lane, or missing trust data skips checks |-| FR5 | mixed-surface and incomplete-owner routing tests | spec+component; tooling+component; named surface without admitted lane; docsite+shared | one surface hides another owner or a named-but-incomplete surface skips broad CI |-| FR6–FR8 | Node-tooling dependency, CI workflow, and trusted post-CI workflow tests | both admitted score-ledger paths; Sandbox projection imports; test/build joins; preview/visual publisher | UI/browser/build work or preview publication runs for the singleton tool set, an operational consumer is untested, a visual status stays pending, or a required context disappears |-| FR9 | mutation-sensitive classifier and workflow fixtures | unknown path; rename from unknown; truncated list; package-specific public paths | weakening a fail-closed rule leaves the suite green |-| FR10 | surface-admission and routing contract tests | existing surface; proposed surface with and without the full admission contract | a new surface adds lanes without its approved paths, commands, ownership, projections, and routing tests |-| FR11 | surface owner, internal-job, and required-join contract tests | Build package browser behavior; CLI; theme-family broad fallback; mixed Core+CLI | a second owner is routed for one surface, an internal job masquerades as a lane, an owned failure misses its join, or an unrelated owner runs |-| FR12 | Storybook visual-plan, canonical workflow, and repository-owner guard tests | PR scope; full-plan maintenance; report-only publication; deployment/a11y/RTL/vibe artifacts | another workflow captures or compares pixels, a renamed or aliased owner escapes the guard, or legitimate non-visual artifacts are rejected |-| FR13 | classifier, workflow contract, component-analysis and RTL-scope tests | component change; shared module; Changeset beside code; infrastructure path; incomplete list; no build | an infrastructure path is scoped, a file-system guard test is skipped, a reverse dependent leaves visual/RTL or enters PR accessibility, or a full-suite event is narrowed |-| FR14 | `workflow-paths.test.mjs` over every workflow | path allowlist; required-context workflow | a `paths-ignore`, a match-all or exclusion glob, or a path filter on a workflow that reports a required context fails |+| Contract | Verification | Representative states | Mutation or failure expectation |+| -------- | ---------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| FR1–FR2 | classifier unit tests expose the surface set | knowledge; docsite; admitted tool; Core/Lab/Charts/Rich Text/Vega source; shared config; unknown | an unclassified path receives a specialized lane or a category has no check owner |+| FR3–FR4 | workflow contract tests execute an isolated trusted-base classifier | valid base; missing merge base; missing matcher/registry; classifier self-change; merge group | PR-controlled policy grants a lane, or missing trust data skips checks |+| FR5 | mixed-surface and incomplete-owner routing tests | spec+component; tooling+component; named surface without admitted lane; docsite+shared | one surface hides another owner or a named-but-incomplete surface skips broad CI |+| FR6–FR8 | Node-tooling dependency, CI workflow, and trusted post-CI workflow tests | both admitted score-ledger paths; Sandbox projection imports; test/build joins; preview/visual publisher | UI/browser/build work or preview publication runs for the singleton tool set, an operational consumer is untested, a visual status stays pending, or a required context disappears |+| FR9 | mutation-sensitive classifier and workflow fixtures | unknown path; rename from unknown; truncated list; package-specific public paths | weakening a fail-closed rule leaves the suite green |+| FR10 | surface-admission and routing contract tests | existing surface; proposed surface with and without the full admission contract | a new surface adds lanes without its approved paths, commands, ownership, projections, and routing tests |+| FR11 | surface owner, internal-job, and required-join contract tests | Build package browser behavior; CLI; theme-family broad fallback; mixed Core+CLI | a second owner is routed for one surface, an internal job masquerades as a lane, an owned failure misses its join, or an unrelated owner runs |+| FR12 | Storybook visual-plan, canonical workflow, and repository-owner guard tests | PR scope; full-plan maintenance; report-only publication; deployment/a11y/RTL/vibe artifacts | another workflow captures or compares pixels, a renamed or aliased owner escapes the guard, or legitimate non-visual artifacts are rejected |+| FR13 | classifier, workflow contract, component-analysis and RTL-scope tests | component change; shared module; Changeset beside code; infrastructure path; incomplete list; no build | an infrastructure path is scoped, a file-system guard test is skipped, a reverse dependent leaves visual/RTL or enters PR accessibility, or a full-suite event is narrowed |+| FR14 | `workflow-paths.test.mjs` over every workflow | path allowlist; required-context workflow | a `paths-ignore`, a match-all or exclusion glob, or a path filter on a workflow that reports a required context fails |+| FR16 | `heavy-caps-action.test.mjs` cap cases and heavy-job contract | fourth-oldest PR; thirteenth heavy run of the day, beside cancelled, light and other-branch runs; agent lane and its five-PR and forty-run backstops; bot; the deciding run; re-run; failed lookup | a heavy suite that runs ahead of the author's three oldest PRs, or past the daily cap, a capped job that passes, or a re-run that is held fails |+| FR17 | `ci-pr-gate.test.mjs` over every `pull_request` workflow and the shared conditions | branch here, fork with and without `ci:run`, another label, draft with the label, ready, push, merge group, dispatch | a job that can start on a pull request without the condition, a label trigger, a required job that skips for a pull request that may not run CI, or a draft or unlabelled fork that runs fails |## Decision log