Skip to content

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

TypeScript

ci: a pull request runs the tests and audits its changes reach (AST-030 FR13) (#8597)

Cindy Zhangd9b43cf24b0f
diff --git a/.github/scripts/analyze-pr.js b/.github/scripts/analyze-pr.js
index c5354a0a8a..1f74842db6 100644
--- a/.github/scripts/analyze-pr.js
+++ b/.github/scripts/analyze-pr.js
@@ -4,11 +4,15 @@
/**
* @description Analyzes PR changes to detect new/modified components and gather stats
- * @input --base <branch> --head <ref> --output <file> [--base-root <dir> [--base-only]]
+ * @input --base <branch> --head <ref> --output <file> [--base-root <dir> [--base-only]] [--force-full]
* @output JSON file with component analysis; exits non-zero if the base...head diff fails (e.g. shallow clone without a merge base).
* With --base-root (a built checkout of the merge base), the analysis also
* records baseComponentStats and baseBundlePackages measured in that tree;
* --base-only writes just those, with the head and base commits they belong to.
+ * A changed module outside every component folder (a shared hook, the
+ * animator) owns the components whose bundle reaches it, so browser audits
+ * run for those reverse dependents; one no component reaches, or --force-full
+ * (a change to shared infrastructure), asks for full audits.
*/
const fs = require('node:fs');
@@ -40,6 +44,7 @@ const headRef = getArg('head') || 'HEAD';
const outputFile = getArg('output') || 'analysis.json';
const baseRoot = getArg('base-root');
const baseOnly = args.includes('--base-only');
+const forceFull = args.includes('--force-full');
if (baseOnly && !baseRoot) {
console.error('::error::--base-only needs --base-root');
process.exit(1);
@@ -62,6 +67,58 @@ const pkgDist = (pkg) => `${pkg.dir}/dist`;
// Get canonical direct public component names for a package. Nested family,
// context, and shared directories deliberately stay unresolved so audits widen.
+// The canonical components a nested package's folder implements (its docs
+// name them, and the barrel exports them from inside it).
+const familyIndex = new Map();
+function familyMembers(pkg, folder) {
+ const sourceDir = path.join(process.cwd(), pkgSrc(pkg));
+ if (!familyIndex.has(pkg.name)) {
+ familyIndex.set(pkg.name, {
+ canonical: new Set(nestedPackageComponentNames(process.cwd(), pkg)),
+ exports: componentExportsFromBarrel(path.join(sourceDir, 'index.ts'), sourceDir),
+ });
+ }
+ const { canonical, exports } = familyIndex.get(pkg.name);
+ const directory = path.join(sourceDir, folder);
+ try {
+ return documentedComponentNames(directory).filter(
+ (name) => canonical.has(name) && exports.get(name)?.startsWith(`${directory}${path.sep}`),
+ );
+ } catch {
+ return [];
+ }
+}
+
+// Every canonical component a folder implements: the package barrel exports
+// it from inside that folder, documented or not (FieldLabel in Field,
+// DrawerHeader in Drawer). RTL matches owners by these names.
+const folderIndex = new Map();
+function folderComponents(pkg, folder, repoRoot = process.cwd()) {
+ const sourceDir = path.join(repoRoot, pkgSrc(pkg));
+ const key = `${repoRoot}\0${pkg.name}`;
+ if (!folderIndex.has(key)) {
+ folderIndex.set(key, {
+ canonical:
+ pkg.layout === 'flat'
+ ? new Set(flatPackageComponentNames(repoRoot, pkg))
+ : new Set(nestedPackageComponentNames(repoRoot, pkg)),
+ exports:
+ pkg.layout === 'flat'
+ ? new Map()
+ : componentExportsFromBarrel(path.join(sourceDir, 'index.ts'), sourceDir),
+ });
+ }
+ const { canonical, exports } = folderIndex.get(key);
+ if (pkg.layout === 'flat') return canonical.has(folder) ? [folder] : [];
+ const directory = path.join(sourceDir, folder);
+ return [...canonical]
+ .filter((name) => {
+ const file = exports.get(name);
+ return file === directory || file?.startsWith(`${directory}${path.sep}`);
+ })
+ .sort();
+}
+
function getComponentNames(pkg) {
if (pkg.layout === 'flat') {
return flatPackageComponentNames(process.cwd(), pkg);
@@ -556,10 +613,16 @@ function packageTargets(pkg) {
// Every canonical public component a change can affect: its own folder or
// file changed, or its bundle, import() targets included, reaches a changed
// module of its package, such as a shared hook or style module. Family folders
-// that hold several components yield each of them.
-function sizeTargets(changedFiles) {
+// that hold several components yield each of them. `reach`, when given,
+// collects each changed source path some component reaches (its folder, or a
+// module in its bundle) in `paths`, and in `measured` each package whose
+// bundles could be read: there, a module no bundle holds reaches nothing.
+function sizeTargets(changedFiles, reached = null) {
const withoutExtension = (file) => file.replace(/\.(tsx?|jsx?|mjs)$/, '');
- const targets = [];
+ // Each package's changed modules, and its built dist to find them in: a
+ // bundle in any package can reach them (Lab, Charts, Rich Text and Vega
+ // import Core).
+ const changed = [];
for (const pkg of PACKAGES) {
const prefix = pkgSrc(pkg) + '/';
const changedModules = new Set(
@@ -568,20 +631,44 @@ function sizeTargets(changedFiles) {
.map((file) => withoutExtension(file.slice(prefix.length))),
);
if (changedModules.size === 0) continue;
- const changedTops = new Set([...changedModules].map((file) => file.split('/')[0]));
const dist = path.join(process.cwd(), pkgDist(pkg));
- // esbuild reports inputs by real path.
- const distReal = fs.existsSync(dist) ? fs.realpathSync(dist) : dist;
+ changed.push({
+ pkg,
+ prefix,
+ changedModules,
+ changedTops: new Set([...changedModules].map((file) => file.split('/')[0])),
+ // esbuild reports inputs by real path.
+ distReal: fs.existsSync(dist) ? fs.realpathSync(dist) : dist,
+ });
+ }
+ if (changed.length === 0) return [];
+ const targets = [];
+ for (const pkg of PACKAGES) {
+ const own = changed.find((entry) => entry.pkg === pkg) ?? null;
+ const dist = path.join(process.cwd(), pkgDist(pkg));
const all = packageTargets(pkg);
const reach = bundleInputsByEntry(all.map((target) => path.join(dist, target.distModule)));
for (const target of all) {
const top = withoutExtension(target.distModule.split('/')[0]);
const inputs = reach?.get(path.join(dist, target.distModule)) ?? [];
- const reachesChange = inputs.some((input) => {
- const relative = path.relative(distReal, input);
- return !relative.startsWith('..') && changedModules.has(withoutExtension(relative));
- });
- if (changedTops.has(top) || reachesChange) targets.push(target);
+ const reachedPaths = inputs.flatMap((input) =>
+ changed.flatMap((entry) => {
+ const relative = path.relative(entry.distReal, input);
+ const module = withoutExtension(relative);
+ return !relative.startsWith('..') && entry.changedModules.has(module)
+ ? [entry.prefix + module]
+ : [];
+ }),
+ );
+ const isOwnFolder = own != null && own.changedTops.has(top);
+ if (isOwnFolder || reachedPaths.length > 0) targets.push(target);
+ if (reached != null) {
+ for (const reachedPath of reachedPaths) reached.paths.add(reachedPath);
+ if (isOwnFolder) reached.paths.add(own.prefix + top);
+ }
+ }
+ if (reached != null && own != null && reach != null && reach.size > 0) {
+ reached.measured.add(own.prefix);
}
}
return targets;
@@ -691,6 +778,8 @@ function analyze() {
const newComponentOwners = [];
const modifiedComponentOwners = [];
const unresolvedComponentSources = [];
+ // Each changed file under an unresolved source, to decide its reach.
+ const unresolvedFiles = [];
const componentStats = {};
const changedPackages = new Set();
@@ -727,6 +816,7 @@ function analyze() {
if (!allComponents.includes(componentName)) {
const source = `${pkg.packageName}/${componentName}`;
+ unresolvedFiles.push({ source, file });
if (!unresolvedComponentSources.includes(source)) {
unresolvedComponentSources.push(source);
}
@@ -788,7 +878,8 @@ function analyze() {
// Components a change can affect, by reach in the head build and, when the
// merge base is built, in the base build too: CI's size-base job builds only
// the base, and a module change can add or remove reach.
- const headTargets = sizeTargets(changedFiles);
+ const reachedSources = { paths: new Set(), measured: new Set() };
+ const headTargets = sizeTargets(changedFiles, reachedSources);
let targets = headTargets;
let baseComponentSizes = null;
if (baseRoot) {
@@ -814,6 +905,59 @@ function analyze() {
}
const componentSizes = baseOnly ? null : measureSizes(targets);
+ // Every changed module, inside a component folder or not (a shared hook,
+ // the animator, a family folder), adds the components whose head bundle
+ // reaches it as reverse dependents: visual and RTL audits run them, PR
+ // accessibility stays with changed components (spec:AST-030 FR12, FR13).
+ // In a package whose bundles were read, a module no bundle holds adds none.
+ // One outside every component folder in a package whose bundles could not
+ // be read stays unresolved and asks for full audits, as does --force-full.
+ const isDecided = (file) =>
+ [...reachedSources.measured].some((prefix) => file.startsWith(prefix)) ||
+ [...reachedSources.paths].some((reachedPath) => {
+ const module = file.replace(/\.(tsx?|jsx?|mjs)$/, '');
+ return module === reachedPath || module.startsWith(reachedPath + '/');
+ });
+ const unreachedSources = unresolvedComponentSources.filter((source) =>
+ unresolvedFiles.some((entry) => entry.source === source && !isDecided(entry.file)),
+ );
+ // One affected set of component folders, which visual and RTL both audit
+ // (spec:AST-030 FR13): each reverse dependent's folder, and each changed
+ // multi-component folder that documents components. Visual reads the
+ // folders (its stories are keyed by folder); RTL reads every component each
+ // folder implements (its routes are keyed by component: FieldLabel, not
+ // Field).
+ const folderOf = (target) => target.distModule.split('/')[0].replace(/\.(tsx?|jsx?|mjs)$/, '');
+ const dependentComponentFolders = [];
+ const dependentComponentOwners = [];
+ if (!baseOnly) {
+ const touched = new Set([...newComponentOwners, ...modifiedComponentOwners]);
+ const addFolder = (pkg, folder) => {
+ const qualified = `${pkg.packageName}/${folder}`;
+ if (dependentComponentFolders.includes(qualified)) return;
+ const members = folderComponents(pkg, folder);
+ const owners = (members.length > 0 ? members : [folder]).map(
+ (name) => `${pkg.packageName}/${name}`,
+ );
+ if (owners.every((owner) => touched.has(owner))) return;
+ dependentComponentFolders.push(qualified);
+ for (const owner of owners) {
+ if (!touched.has(owner) && !dependentComponentOwners.includes(owner)) {
+ dependentComponentOwners.push(owner);
+ }
+ }
+ };
+ for (const target of headTargets) addFolder(target.pkg, folderOf(target));
+ for (const source of unresolvedComponentSources) {
+ const [packageName, folder] = source.split('/');
+ const pkg = PACKAGES.find((candidate) => candidate.packageName === packageName);
+ if (pkg != null && pkg.layout !== 'flat' && familyMembers(pkg, folder).length > 0) {
+ addFolder(pkg, folder);
+ }
+ }
+ console.log(`Reverse dependents: ${dependentComponentOwners.join(', ') || 'none'}`);
+ }
+
if (baseOnly) {
const baseResult = {
headSha: execSync('git rev-parse HEAD', { encoding: 'utf8' }).trim(),
@@ -833,8 +977,13 @@ function analyze() {
modifiedComponents,
newComponentOwners,
modifiedComponentOwners,
+ dependentComponentOwners,
+ dependentComponentFolders,
+ // Every changed multi-component folder stays listed: PR accessibility
+ // expands it to its members (spec:AST-030 FR12, DEC-5). Only the sources
+ // no bundle decided ask for full audits.
unresolvedComponentSources,
- forceFullComponentAudits: unresolvedComponentSources.length > 0,
+ forceFullComponentAudits: forceFull || unreachedSources.length > 0,
newExports,
componentStats,
changedPackages: [...changedPackages],
@@ -857,4 +1006,6 @@ function analyze() {
return result;
}
-analyze();
+if (require.main === module) analyze();
+
+module.exports = { folderComponents };
diff --git a/.github/scripts/analyze-pr.test.mjs b/.github/scripts/analyze-pr.test.mjs
index a8ff24b558..3baca3245f 100644
--- a/.github/scripts/analyze-pr.test.mjs
+++ b/.github/scripts/analyze-pr.test.mjs
@@ -22,6 +22,7 @@ import {execFileSync} from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
+import {createRequire} from 'node:module';
import {fileURLToPath} from 'node:url';
import {describe, it, expect} from 'vitest';
@@ -168,6 +169,9 @@ function buildFixture() {
}
describe('analyze-pr shallow-clone recovery', () => {
+ // Analysis bundles every package's build to find reverse dependents
+ // across packages, which takes this five-package fixture past the default
+ // 30 s on a loaded runner.
it('recovers the three-dot diff and reports Core, Rich Text, and Vega owners', () => {
const {base, clone} = buildFixture();
try {
@@ -219,7 +223,7 @@ describe('analyze-pr shallow-clone recovery', () => {
} finally {
fs.rmSync(base, {recursive: true, force: true});
}
- });
+ }, 60_000);
});
describe('analyze-pr component ownership', () => {
@@ -280,9 +284,19 @@ describe('analyze-pr component ownership', () => {
);
const analysis = JSON.parse(fs.readFileSync(path.join(repo, 'analysis.json'), 'utf8'));
+ // A family folder's components are reverse dependents of its change:
+ // visual and RTL audit them, PR accessibility (changed components with
+ // stories of their own) does not.
expect(analysis.modifiedComponentOwners).toEqual(['core/Tokenizer']);
+ // One set of folders: visual reads the folder, RTL every component the
+ // folder implements.
+ expect(analysis.dependentComponentFolders).toEqual(['core/Chat']);
+ expect(analysis.dependentComponentOwners).toEqual(['core/Chat', 'core/ChatComposer']);
+ // The changed family folder stays listed, so PR accessibility expands
+ // it to its members (spec:AST-030 FR12, DEC-5), and visual gets it.
expect(analysis.unresolvedComponentSources).toEqual(['core/Chat']);
- expect(analysis.forceFullComponentAudits).toBe(true);
+ // Its change was decided by the folder, so it asks for no full audit.
+ expect(analysis.forceFullComponentAudits).toBe(false);
} finally {
fs.rmSync(repo, {recursive: true, force: true});
}
@@ -328,6 +342,106 @@ describe('analyze-pr base and head sizes', () => {
);
const analysis = JSON.parse(fs.readFileSync(path.join(repo, 'analysis.json'), 'utf8'));
expect(Object.keys(analysis.componentSizes)).toEqual(['core/Card']);
+ // The shared hook's reverse dependent is audited, not the whole roster.
+ // A reverse dependent, kept apart from the changed owners: visual and
+ // RTL audits run it, PR accessibility stays with changed owners.
+ expect(analysis.modifiedComponentOwners).toEqual([]);
+ expect(analysis.dependentComponentOwners).toEqual(['core/Card']);
+ // The shared folder stays listed (PR accessibility finds no component
+ // documented in it); its reach decided it, so no full audit.
+ expect(analysis.unresolvedComponentSources).toEqual(['core/hooks']);
+ expect(analysis.forceFullComponentAudits).toBe(false);
+
+ // A change to shared infrastructure asks for full audits whatever it
+ // reaches.
+ execFileSync(
+ process.execPath,
+ [SCRIPT, '--base', 'main', '--head', 'HEAD', '--output', 'analysis.json', '--force-full'],
+ {cwd: repo, encoding: 'utf8'},
+ );
+ const forced = JSON.parse(fs.readFileSync(path.join(repo, 'analysis.json'), 'utf8'));
+ expect(forced.forceFullComponentAudits).toBe(true);
+
+ // A module no component bundle holds changes no component: it adds no
+ // owner and asks for no full audit.
+ write('packages/core/src/hooks/useOrphan.ts', 'export function useOrphan() { return 1; }\n');
+ git(repo, ['add', '-A']);
+ git(repo, ['commit', '-qm', 'add a module nothing imports']);
+ write('packages/core/dist/hooks/useOrphan.js', 'export function useOrphan() { return 1; }\n');
+ execFileSync(
+ process.execPath,
+ [SCRIPT, '--base', 'main', '--head', 'HEAD', '--output', 'analysis.json'],
+ {cwd: repo, encoding: 'utf8'},
+ );
+ const orphan = JSON.parse(fs.readFileSync(path.join(repo, 'analysis.json'), 'utf8'));
+ expect(orphan.dependentComponentOwners).toEqual(['core/Card']);
+ expect(orphan.forceFullComponentAudits).toBe(false);
+
+ // Without a build to read reach from, a shared module stays unresolved:
+ // full audits.
+ fs.rmSync(path.join(repo, 'packages/core/dist'), {recursive: true});
+ execFileSync(
+ process.execPath,
+ [SCRIPT, '--base', 'main', '--head', 'HEAD', '--output', 'analysis.json'],
+ {cwd: repo, encoding: 'utf8'},
+ );
+ const unbuilt = JSON.parse(fs.readFileSync(path.join(repo, 'analysis.json'), 'utf8'));
+ expect(unbuilt.unresolvedComponentSources).toEqual(['core/hooks']);
+ expect(unbuilt.forceFullComponentAudits).toBe(true);
+ } finally {
+ fs.rmSync(repo, {recursive: true, force: true});
+ }
+ });
+
+ it('adds the components of another package whose bundle reaches a changed Core module', () => {
+ const repo = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-analyze-crossreach-'));
+ const write = (file, content) => {
+ fs.mkdirSync(path.dirname(path.join(repo, file)), {recursive: true});
+ fs.writeFileSync(path.join(repo, file), content);
+ };
+ try {
+ write('package.json', '{}');
+ write('.gitignore', 'dist/\n*.json.out\nanalysis.json\n');
+ write('packages/core/package.json', '{"type": "module"}\n');
+ write('packages/core/src/index.ts', "export {Card} from './Card';\n");
+ write('packages/core/src/Card/index.ts', "export {Card} from './Card';\n");
+ write('packages/core/src/Card/Card.tsx', "import {useHold} from '../hooks/useHold';\nexport function Card() { return useHold(); }\n");
+ write('packages/core/src/Card/Card.doc.mjs', "export const docs = {\n name: 'Card',\n};\n");
+ write('packages/core/src/hooks/useHold.ts', 'export function useHold() { return 1; }\n');
+ write('packages/lab/package.json', '{"type": "module"}\n');
+ write('packages/lab/src/index.ts', "export {Sketch} from './Sketch';\nexport {Plain} from './Plain';\n");
+ write('packages/lab/src/Sketch/index.ts', "export {Sketch} from './Sketch';\n");
+ write('packages/lab/src/Sketch/Sketch.tsx', "import {useHold} from '@astryxdesign/core';\nexport function Sketch() { return useHold(); }\n");
+ write('packages/lab/src/Sketch/Sketch.doc.mjs', "export const docs = {\n name: 'Sketch',\n};\n");
+ write('packages/lab/src/Plain/index.ts', "export {Plain} from './Plain';\n");
+ write('packages/lab/src/Plain/Plain.tsx', 'export function Plain() {}\n');
+ write('packages/lab/src/Plain/Plain.doc.mjs', "export const docs = {\n name: 'Plain',\n};\n");
+ git(repo, ['init', '-q', '-b', 'main']);
+ git(repo, ['config', 'user.email', '[email protected]']);
+ git(repo, ['config', 'user.name', 'Test']);
+ git(repo, ['add', '-A']);
+ git(repo, ['commit', '-qm', 'base']);
+ git(repo, ['checkout', '-q', '-b', 'feature']);
+ write('packages/core/src/hooks/useHold.ts', 'export function useHold() { return 2; }\n');
+ git(repo, ['commit', '-qam', 'touch the Core hook']);
+ write('packages/core/dist/Card/Card.js', "import {useHold} from '../hooks/useHold.js';\nexport function Card() { return useHold(); }\n");
+ write('packages/core/dist/hooks/useHold.js', 'export function useHold() { return 2; }\n');
+ write('packages/core/dist/index.js', "export {Card} from './Card/Card.js';\n");
+ // Lab's build imports Core's build, as the package does.
+ write('packages/lab/dist/Sketch/Sketch.js', "import {useHold} from '../../../core/dist/hooks/useHold.js';\nexport function Sketch() { return useHold(); }\n");
+ write('packages/lab/dist/Plain/Plain.js', 'export function Plain() { return 0; }\n');
+ write('packages/lab/dist/index.js', "export {Sketch} from './Sketch/Sketch.js';\nexport {Plain} from './Plain/Plain.js';\n");
+
+ execFileSync(
+ process.execPath,
+ [SCRIPT, '--base', 'main', '--head', 'HEAD', '--output', 'analysis.json'],
+ {cwd: repo, encoding: 'utf8'},
+ );
+ const analysis = JSON.parse(fs.readFileSync(path.join(repo, 'analysis.json'), 'utf8'));
+ // RTL and visual follow the Core change into Lab, as the full audit the
+ // base ran did; Lab's untouched Plain stays out.
+ expect(analysis.dependentComponentOwners).toEqual(['core/Card', 'lab/Sketch']);
+ expect(analysis.forceFullComponentAudits).toBe(false);
} finally {
fs.rmSync(repo, {recursive: true, force: true});
}
@@ -579,3 +693,108 @@ describe('analyze-pr base and head sizes', () => {
}
});
});
+
+// An oracle over this repository: every Core component a story can own is one
+// of the components its folder's affected set hands RTL, found here by
+// reading the barrels independently of analyze-pr (spec:AST-030 FR13).
+describe('analyze-pr folder membership oracle', () => {
+ const require = createRequire(import.meta.url);
+ const {folderComponents} = require('./analyze-pr.js');
+ const {
+ COMPONENT_PACKAGES,
+ nestedPackageComponentNames,
+ } = require('../../scripts/component-packages.cjs');
+ const repoRoot = path.resolve(SCRIPTS_DIR, '../..');
+ const core = COMPONENT_PACKAGES.find(pkg => pkg.name === 'core');
+ const src = path.join(repoRoot, core.src);
+ const canonical = new Set(nestedPackageComponentNames(repoRoot, core));
+
+ // The names a module exports, following its re-exports within its folder.
+ const exportedNames = (file, folder, seen = new Set()) => {
+ if (seen.has(file) || !fs.existsSync(file)) return [];
+ seen.add(file);
+ const text = fs.readFileSync(file, 'utf8');
+ const names = [];
+ for (const [, list, from] of text.matchAll(
+ /export\s*\{([^}]*)\}\s*(?:from\s*['"]([^'"]+)['"])?/g,
+ )) {
+ // A re-export from another folder belongs to that folder.
+ if (
+ from != null &&
+ !path.resolve(path.dirname(file), from).startsWith(folder + path.sep)
+ )
+ continue;
+ for (const part of list.split(',')) {
+ const name = part
+ .replace(/^\s*type\s+/, '')
+ .split(/\s+as\s+/)
+ .pop()
+ ?.trim();
+ if (name) names.push(name);
+ }
+ }
+ for (const [, name] of text.matchAll(
+ /export\s+(?:declare\s+)?(?:function|const|class)\s+([A-Z]\w*)/g,
+ )) {
+ names.push(name);
+ }
+ for (const [, target] of text.matchAll(
+ /export\s*\*\s*from\s*['"](\.[^'"]+)['"]/g,
+ )) {
+ const base = path
+ .resolve(path.dirname(file), target)
+ .replace(/\.js$/, '');
+ if (!base.startsWith(folder + path.sep)) continue;
+ const next = ['.ts', '.tsx', '/index.ts', '/index.tsx']
+ .map(ext => base + ext)
+ .find(fs.existsSync);
+ if (next) names.push(...exportedNames(next, folder, seen));
+ }
+ return names;
+ };
+ // Every Core folder with a barrel of its own, whether the package barrel
+ // names it directly or reaches it through another folder (Code via
+ // CodeBlock).
+ const folders = fs
+ .readdirSync(src, {withFileTypes: true})
+ .filter(
+ entry =>
+ entry.isDirectory() &&
+ fs.existsSync(path.join(src, entry.name, 'index.ts')),
+ )
+ .map(entry => entry.name);
+
+ it('finds Core folders to check', () => {
+ expect(folders.length).toBeGreaterThan(50);
+ });
+
+ it('hands RTL every canonical component each Core folder exports, family members included', () => {
+ const missing = [];
+ for (const folder of folders) {
+ const expected = exportedNames(
+ path.join(src, folder, 'index.ts'),
+ path.join(src, folder),
+ ).filter(name => canonical.has(name));
+ const actual = new Set(folderComponents(core, folder, repoRoot));
+ for (const name of expected)
+ if (!actual.has(name)) missing.push(`${folder}/${name}`);
+ }
+ expect(missing).toEqual([]);
+ });
+
+ it('places every canonical Core component in some folder', () => {
+ const placed = new Set(
+ folders.flatMap(folder => folderComponents(core, folder, repoRoot)),
+ );
+ expect([...canonical].filter(name => !placed.has(name))).toEqual([]);
+ });
+
+ it('lists the members CodeBunny found skipped (FieldLabel in Field, DrawerHeader in Drawer)', () => {
+ const owners = folders.flatMap(folder =>
+ folderComponents(core, folder, repoRoot),
+ );
+ for (const name of ['FieldLabel', 'DrawerHeader', 'AvatarStatusDot']) {
+ if (canonical.has(name)) expect(owners).toContain(name);
+ }
+ });
+});
diff --git a/.github/scripts/change-scope.cjs b/.github/scripts/change-scope.cjs
index 1ac435847b..88cc3ecb6e 100644
--- a/.github/scripts/change-scope.cjs
+++ b/.github/scripts/change-scope.cjs
@@ -61,6 +61,41 @@ const NODE_TOOLING_PATHS = new Set([
'.github/workflows/crowdin-upload.yml',
]);
+// Inside a runtime package, files every component's tests or build read:
+// manifests, build and test configuration, shared test setup. A change to one
+// runs the full suite, like any shared-or-unknown or theme-build path.
+const PACKAGE_INFRA_PATTERNS = [
+ /^packages\/[^/]+\/package\.json$/,
+ /^packages\/[^/]+\/[^/]*\.config\.[^/]+$/,
+ /^packages\/[^/]+\/tsconfig[^/]*\.json$/,
+ /^packages\/[^/]+\/src\/(?:test-utils|testing|__mocks__)\//,
+ /^packages\/[^/]+\/src\/[^/]*setup[^/]*\.[^/]+$/i,
+ /^apps\/storybook\/\.storybook\//,
+ /^internal\//,
+ // A package's root scripts are build configuration (its Babel plugins).
+ /^packages\/[^/]+\/[^/]+\.(?:c|m)?js$/,
+];
+
+// Surfaces a pull request's tests can be scoped to by the import graph (the
+// components and modules it changed, and what imports them). Anything else,
+// or any infrastructure path above, runs the full suite; Node tooling keeps
+// its whole Node project (spec:AST-030 FR8).
+const SCOPABLE_SURFACES = new Set([
+ SURFACES.KNOWLEDGE,
+ SURFACES.DOCSITE,
+ 'storybook-visual',
+ ...RUNTIME_PACKAGE_SURFACES.map(([, surface]) => surface),
+]);
+
+function isSharedInfraPath(filePath) {
+ // A Changeset records release notes; no test or build reads it.
+ if (CHANGESET_PATTERN.test(filePath)) return false;
+ return (
+ PACKAGE_INFRA_PATTERNS.some(pattern => pattern.test(filePath)) ||
+ surfacesForPath(filePath).some(surface => !SCOPABLE_SURFACES.has(surface))
+ );
+}
+
const THEME_DOC_CANDIDATE = /^docs\/themes\/(?!README\.md$)[^/]+\.md$/;
const THEME_PACKAGE_CANDIDATE =
/^packages\/themes\/[^/]+\/(?:.*\/)?[^/]+\.spec\.md$/;
@@ -152,6 +187,8 @@ function classifyChanges(changes, {expectedCount} = {}) {
touchesDesignAssets: false,
specChangesetConflict: false,
docsiteOnly: false,
+ // No paths to scope from runs everything (spec:AST-030 FR4).
+ fullSuite: true,
surfaces: complete ? [] : [SURFACES.SHARED_OR_UNKNOWN],
complete,
reason: complete ? 'no changed files' : 'changed-file list is incomplete',
@@ -199,6 +236,8 @@ function classifyChanges(changes, {expectedCount} = {}) {
const specOnly = exactSurface(SURFACES.KNOWLEDGE);
const docsiteOnly = exactSurface(SURFACES.DOCSITE);
const toolingOnly = exactSurface(SURFACES.NODE_TOOLING);
+ // An incomplete list, or any shared infrastructure, runs everything.
+ const fullSuite = !complete || allPaths.some(isSharedInfraPath);
return {
specOnly,
toolingOnly,
@@ -206,6 +245,7 @@ function classifyChanges(changes, {expectedCount} = {}) {
touchesDesignAssets,
specChangesetConflict,
docsiteOnly,
+ fullSuite,
surfaces,
complete,
reason: !complete
@@ -253,7 +293,7 @@ if (require.main === module) {
throw new Error('GITHUB_OUTPUT is required with --github-output.');
fs.appendFileSync(
outputPath,
- `spec_only=${result.specOnly}\ndocsite_only=${result.docsiteOnly}\ntooling_only=${result.toolingOnly}\n`,
+ `spec_only=${result.specOnly}\ndocsite_only=${result.docsiteOnly}\ntooling_only=${result.toolingOnly}\nfull_suite=${result.fullSuite}\n`,
);
} else {
process.stdout.write(`${JSON.stringify(result)}\n`);
@@ -267,6 +307,7 @@ module.exports = {
isKnowledgeRecordPath,
isNodeToolingPath,
isPackageReleasePath,
+ isSharedInfraPath,
isSpecRecordPath,
parseNameStatus,
};
diff --git a/.github/scripts/change-scope.test.mjs b/.github/scripts/change-scope.test.mjs
index 0161155f80..479a6180b9 100644
--- a/.github/scripts/change-scope.test.mjs
+++ b/.github/scripts/change-scope.test.mjs
@@ -357,3 +357,71 @@ describe('positive CI surfaces', () => {
}
});
});
+
+describe('full-suite scope', () => {
+ const full = files =>
+ classifyChanges(files.map(filename => ({filename}))).fullSuite;
+
+ it('scopes component, shared-module, docs and spec changes to the import graph', () => {
+ expect(full(['packages/core/src/Button/Button.tsx'])).toBe(false);
+ expect(full(['packages/core/src/motion/animator.ts'])).toBe(false);
+ expect(full(['packages/lab/src/Sketch/Sketch.tsx'])).toBe(false);
+ expect(full(['apps/docsite/src/app/page.tsx'])).toBe(false);
+ expect(full(['docs/specs/AST-001-overlay-policy/spec.md'])).toBe(false);
+ expect(full(['apps/storybook/stories/Button.stories.tsx'])).toBe(false);
+ // A Changeset beside the change is release notes, not infrastructure.
+ expect(
+ full([
+ 'packages/core/src/Layer/useLayer.tsx',
+ '.changeset/layer-slot-second-render.md',
+ ]),
+ ).toBe(false);
+ });
+
+ it('runs everything for shared infrastructure', () => {
+ for (const file of [
+ 'package.json',
+ 'pnpm-lock.yaml',
+ 'vitest.config.ts',
+ '.github/workflows/ci.yml',
+ '.github/scripts/change-scope.cjs',
+ 'internal/interaction-harness/src/busy.ts',
+ 'scripts/build-css.mjs',
+ 'packages/themes/neutral/src/index.ts',
+ 'packages/build/src/index.ts',
+ 'packages/core/src/theme/tokens.stylex.ts',
+ 'packages/core/package.json',
+ 'packages/core/tsconfig.json',
+ 'packages/core/vite.config.ts',
+ 'packages/core/src/test-utils/render.tsx',
+ 'packages/core/src/testing/fixtures.ts',
+ 'packages/core/src/__mocks__/matchMedia.ts',
+ 'packages/core/src/setupTests.ts',
+ 'packages/lab/src/vitest.setup.ts',
+ 'packages/core/babel-plugin-add-extensions.cjs',
+ 'packages/lab/babel-plugin-add-extensions.cjs',
+ 'apps/storybook/.storybook/preview.tsx',
+ // Node tooling keeps its whole Node project (FR8), internal/ included.
+ 'internal/scripts/lib/a-future-strategy.mjs',
+ 'scripts/score-ledger.mjs',
+ ]) {
+ expect(full(['packages/core/src/Button/Button.tsx', file]), file).toBe(
+ true,
+ );
+ }
+ });
+
+ it('runs everything when the changed-file list is incomplete', () => {
+ expect(
+ classifyChanges([{filename: 'packages/core/src/Button/Button.tsx'}], {
+ expectedCount: 2,
+ }).fullSuite,
+ ).toBe(true);
+ expect(classifyChanges([], {expectedCount: 1}).fullSuite).toBe(true);
+ });
+
+ it('runs everything when there are no paths to scope from', () => {
+ expect(classifyChanges([]).fullSuite).toBe(true);
+ expect(classifyChanges([], {expectedCount: 0}).fullSuite).toBe(true);
+ });
+});
diff --git a/.github/scripts/ci-test-routing.test.mjs b/.github/scripts/ci-test-routing.test.mjs
index 85b7d7814a..014c557f98 100644
--- a/.github/scripts/ci-test-routing.test.mjs
+++ b/.github/scripts/ci-test-routing.test.mjs
@@ -63,6 +63,8 @@ const WORKFLOWS = {
lanes: ['test-ui', 'test-node'],
// A PR that only touches docs skips the suite but must still report.
scopeConditional: true,
+ // A pull request the import graph can scope runs only related tests.
+ graphScoped: true,
// Each Vitest lane splits its project across matrix legs.
sharded: true,
},
@@ -71,6 +73,8 @@ const WORKFLOWS = {
// other and so ride one lane of their own.
lanes: ['test-ui', 'test-node', 'typecheck'],
scopeConditional: false,
+ // The push to main runs every test.
+ graphScoped: false,
sharded: true,
},
};
@@ -103,7 +107,7 @@ function runLines(job) {
describe.each(Object.entries(WORKFLOWS))(
'%s test routing',
- (file, {lanes, scopeConditional, sharded}) => {
+ (file, {lanes, scopeConditional, graphScoped, sharded}) => {
const workflow = load(file);
it('gives the Node suite more than one Vitest worker', () => {
@@ -161,7 +165,56 @@ describe.each(Object.entries(WORKFLOWS))(
// runs FR23 in a later step on the same runner, after its share exited.
expect(suites).toHaveLength(2);
const [share, isolated] = suites;
- expect(share.run.trim()).toBe(`pnpm test:ui ${SHARD_ARG}`);
+ // Its share is the full UI project, or for a scoped pull request the
+ // tests related to its diff (check-scope's full_suite).
+ if (graphScoped) {
+ expect(share.run.trim()).toBe(
+ [
+ 'if [ "$SCOPED" = true ]; then',
+ ` pnpm test:ui --changed=HEAD^1 --passWithNoTests ${SHARD_ARG}`,
+ ' # Tests no module graph relates to the change run too: guards',
+ ' # that read sources, and tests that load a changed package from',
+ ' # its build (by name or its dist/).',
+ ' # The list goes through a file so a failing lister fails the step.',
+ ' node .github/scripts/fs-guard-tests.mjs --changed HEAD^1 > "$RUNNER_TEMP/fs-guards.txt"',
+ ' mapfile -t GUARDS < "$RUNNER_TEMP/fs-guards.txt"',
+ ' if [ "${#GUARDS[@]}" -gt 0 ]; then',
+ ` pnpm test:ui --passWithNoTests ${SHARD_ARG} "\${GUARDS[@]}"`,
+ ' fi',
+ 'else',
+ ` pnpm test:ui ${SHARD_ARG}`,
+ 'fi',
+ ].join('\n'),
+ );
+ expect(share.env.SCOPED).toBe(
+ "${{ github.event_name == 'pull_request' && needs.check-scope.outputs.full_suite == 'false' }}",
+ );
+ // The Node lane runs the same scoped share, guards included.
+ const node = workflow.jobs['test-node'].steps.find(
+ step => step.name === 'Run this shard of the Node tests',
+ );
+ expect(node.run.trim()).toBe(
+ [
+ 'if [ "$SCOPED" = true ]; then',
+ ` pnpm test:node --changed=HEAD^1 --passWithNoTests ${SHARD_ARG}`,
+ ' # Tests no module graph relates to the change run too: guards',
+ ' # that read sources, and tests that load a changed package from',
+ ' # its build (by name or its dist/).',
+ ' # The list goes through a file so a failing lister fails the step.',
+ ' node .github/scripts/fs-guard-tests.mjs --changed HEAD^1 > "$RUNNER_TEMP/fs-guards.txt"',
+ ' mapfile -t GUARDS < "$RUNNER_TEMP/fs-guards.txt"',
+ ' if [ "${#GUARDS[@]}" -gt 0 ]; then',
+ ` pnpm test:node --passWithNoTests ${SHARD_ARG} "\${GUARDS[@]}"`,
+ ' fi',
+ 'else',
+ ` pnpm test:node ${SHARD_ARG}`,
+ 'fi',
+ ].join('\n'),
+ );
+ expect(node.env.SCOPED).toBe(share.env.SCOPED);
+ } else {
+ expect(share.run.trim()).toBe(`pnpm test:ui ${SHARD_ARG}`);
+ }
expect(isolated.run.trim()).toBe('pnpm test:ui:isolated');
expect(job.steps.indexOf(isolated)).toBeGreaterThan(
job.steps.indexOf(share),
@@ -719,3 +772,59 @@ describe('ci.yml interaction proofs', () => {
expect(scope).toContain('if [ "$scope" = 1 ]; then');
});
});
+
+describe('scoped browser audits (spec:AST-030 FR9, FR13)', () => {
+ const workflow = load('ci.yml');
+ const stepNamed = name => {
+ for (const job of Object.values(workflow.jobs)) {
+ const step = (job.steps ?? []).find(candidate => candidate.name === name);
+ if (step != null) return step;
+ }
+ throw new Error(`no step named ${name}`);
+ };
+
+ it('asks component analysis for full audits unless check-scope reports a scoped suite', () => {
+ const analyze = stepNamed('Analyze components');
+ expect(analyze.env.FULL_SUITE).toBe(
+ '${{ needs.check-scope.outputs.full_suite }}',
+ );
+ expect(analyze.run).toContain(
+ 'if [ "$FULL_SUITE" != false ]; then FORCE_FULL=(--force-full); fi',
+ );
+ expect(analyze.run).toContain('"${FORCE_FULL[@]}"');
+ });
+
+ it('hands the visual gate the folder-level reverse dependents RTL audits, and the whole plan when analysis or the gate asks for it', () => {
+ const visual = stepNamed('Run the visual gate for the touched components');
+ expect(visual.run).toContain(
+ `DEPENDENTS=$(jq -r '[(.dependentComponentFolders // [])[] | select(startswith("core/")) | ltrimstr("core/")] | unique | join(",")' analysis.json)`,
+ );
+ expect(visual.run).toContain(
+ 'if [ -n "$DEPENDENTS" ]; then DEPENDENT_ARGS=(--dependents "$DEPENDENTS"); fi',
+ );
+ expect(visual.run).toContain(
+ 'SCOPE_ARGS=(--tiers component --components "$COMPONENTS" "${DEPENDENT_ARGS[@]}" --no-scout)',
+ );
+ expect(visual.run).toContain(
+ "FORCE_FULL_AUDITS=$(jq -r '.forceFullComponentAudits == true' analysis.json)",
+ );
+ expect(visual.run).toContain('[ "$FORCE_FULL_AUDITS" = \'true\' ]');
+ // The gate's broaden exit runs the whole plan instead of skipping.
+ expect(visual.run).toMatch(
+ /if \[ "\$code" = 3 \]; then[\s\S]*?COMMAND=release\s+SCOPE_ARGS=\(\)\s+run_gate/,
+ );
+ });
+
+ it('scopes the visual classification only on a pull request check-scope scoped', () => {
+ const check = stepNamed('Check for component changes');
+ expect(check.env.SCOPED).toBe(
+ "${{ github.event_name == 'pull_request' && needs.check-scope.outputs.full_suite == 'false' }}",
+ );
+ expect(check.run).toContain(
+ 'if [ "$SCOPED" = true ]; then VISUAL_ARGS=(--scoped); fi',
+ );
+ expect(check.run).toContain(
+ 'visual-scope.mjs --github-output "$GITHUB_OUTPUT" "${VISUAL_ARGS[@]}"',
+ );
+ });
+});
diff --git a/.github/scripts/ci-tooling-routing.test.mjs b/.github/scripts/ci-tooling-routing.test.mjs
index 09d9dd65ee..ec002723bc 100644
--- a/.github/scripts/ci-tooling-routing.test.mjs
+++ b/.github/scripts/ci-tooling-routing.test.mjs
@@ -72,7 +72,7 @@ describe('Node-tooling CI routing', () => {
it('runs the Node project and required lint owners for tooling', () => {
const nodeSuite = ci.jobs['test-node'].steps.find(candidate =>
- /^pnpm test:node\b/.test(candidate.run ?? ''),
+ /\bpnpm test:node\b/.test(candidate.run ?? ''),
);
expect(nodeSuite.if).not.toContain('tooling_only');
expect(
diff --git a/.github/scripts/fs-guard-tests.mjs b/.github/scripts/fs-guard-tests.mjs
new file mode 100644
index 0000000000..f9a19c09db
--- /dev/null
+++ b/.github/scripts/fs-guard-tests.mjs
@@ -0,0 +1,205 @@
+#!/usr/bin/env node
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+// Lists the tests a scoped pull request runs beyond Vitest's `--changed`
+// (spec:AST-030 FR13), in two groups no module graph relates to a change:
+//
+// - Guards that read repository sources, directly or through a module they
+// import. Any spelling of a module that reads files counts: `fs`,
+// `fs/promises`, `child_process` (`node:` or bare), and the libraries that
+// read sources for the test (the TypeScript compiler and ts-morph, Babel,
+// bundlers, ESLint and Prettier, globs, process runners), through `from`,
+// `require`, `import()` or `vi.importActual`. So do `createRequire`, a
+// computed `import()` and `import.meta.glob`: each loads what it computes
+// or lists.
+// - With `--changed <ref>`: the tests that reach a changed workspace package
+// through its built output, by its name (`@astryxdesign/core` and any
+// subpath) or a relative path into its `dist/`. A project that loads a
+// package from its build sees its source change only through those.
+//
+// Usage: node .github/scripts/fs-guard-tests.mjs [--changed <ref>]
+// (newline-separated paths)
+
+import {execFileSync} from 'node:child_process';
+import fs from 'node:fs';
+import path from 'node:path';
+import {fileURLToPath} from 'node:url';
+
+const TEST_FILE = /\.test\.(?:tsx?|mjs|cjs|js)$/;
+const FILE_MODULE = String.raw`(?:fs|fs\/promises|fs-extra|child_process|typescript|ts-morph|@babel\/core|esbuild|vite|rollup|eslint|prettier|glob|fast-glob|tinyglobby|globby|execa|cross-spawn)`;
+const READS_FILES = new RegExp(
+ [
+ String.raw`\bnode:${FILE_MODULE}\b`,
+ String.raw`\bfrom\s*['"]${FILE_MODULE}['"]`,
+ // Any call naming the module: require, a createRequire require,
+ // import(), vi.importActual.
+ String.raw`\(\s*['"]${FILE_MODULE}['"]\s*[,)]`,
+ String.raw`\bimport\.meta\.glob\b`,
+ String.raw`\bcreateRequire\b`,
+ String.raw`\bimport\(\s*[^'"\s)]`,
+ ].join('|'),
+);
+/** Every module specifier: `from`, a bare `import '…'`, `import()`, `require()`, `vi.importActual()`, `vi.mock()`. */
+const SPECIFIER =
+ /(?:\bfrom|\bimport|\brequire|\bimportActual|\bmock)\s*\(?\s*['"]([^'"]+)['"]/g;
+const EXTENSIONS = ['', '.ts', '.tsx', '.mjs', '.js', '.cjs', '.mts', '.cts'];
+
+/** Resolves a relative specifier to a tracked file, or null. */
+function resolve(from, specifier, tracked) {
+ const base = path.posix.normalize(
+ path.posix.join(path.posix.dirname(from), specifier),
+ );
+ // TypeScript ESM imports name the emitted `.js`; the source is `.ts`.
+ const stems = [base, base.replace(/\.(?:m|c)?js$/, '')];
+ for (const stem of stems) {
+ for (const extension of EXTENSIONS) {
+ if (tracked.has(stem + extension)) return stem + extension;
+ }
+ for (const extension of EXTENSIONS.slice(1)) {
+ if (tracked.has(`${stem}/index${extension}`))
+ return `${stem}/index${extension}`;
+ }
+ }
+ return null;
+}
+
+/**
+ * The tests whose import closure (relative imports followed) satisfies
+ * `matches` for some file's source and specifiers.
+ *
+ * @param {string[]} files tracked repository paths
+ * @param {(file: string) => string} read the file's source
+ * @param {(source: string, specifiers: {raw: string, joined: string}[]) => boolean} matches
+ */
+function testsWhoseClosure(files, read, matches) {
+ const tracked = new Set(files);
+ const memo = new Map();
+ const visit = (file, visiting) => {
+ if (memo.has(file)) return memo.get(file);
+ if (visiting.has(file)) return false;
+ visiting.add(file);
+ let source = '';
+ try {
+ source = read(file);
+ } catch {
+ source = '';
+ }
+ const specifiers = [...source.matchAll(SPECIFIER)].map(([, raw]) => ({
+ raw,
+ joined: raw.startsWith('.')
+ ? path.posix.normalize(path.posix.join(path.posix.dirname(file), raw))
+ : raw,
+ }));
+ let result = matches(source, specifiers);
+ if (!result) {
+ for (const {raw} of specifiers) {
+ if (!raw.startsWith('.')) continue;
+ const target = resolve(file, raw, tracked);
+ if (target != null && visit(target, visiting)) {
+ result = true;
+ break;
+ }
+ }
+ }
+ visiting.delete(file);
+ memo.set(file, result);
+ return result;
+ };
+ return files.filter(file => TEST_FILE.test(file) && visit(file, new Set()));
+}
+
+/**
+ * @param {string[]} files tracked repository paths
+ * @param {(file: string) => string} read the file's source
+ * @returns {string[]} the tests whose import closure reads files
+ */
+export function fsGuardTests(files, read) {
+ return testsWhoseClosure(files, read, source => READS_FILES.test(source));
+}
+
+/**
+ * The workspace packages a change touches outside their tests: each tracked
+ * `package.json` below the root names its directory's package.
+ *
+ * @param {string[]} files tracked repository paths
+ * @param {(file: string) => string} read
+ * @param {string[]} changedFiles
+ * @returns {{dir: string, name: string}[]}
+ */
+export function changedWorkspacePackages(files, read, changedFiles) {
+ const packages = files
+ .filter(
+ file => file.endsWith('/package.json') && !file.includes('node_modules/'),
+ )
+ .flatMap(file => {
+ try {
+ const name = JSON.parse(read(file)).name;
+ return typeof name === 'string'
+ ? [{dir: path.posix.dirname(file), name}]
+ : [];
+ } catch {
+ return [];
+ }
+ })
+ // The deepest directory owns a file.
+ .sort((a, b) => b.dir.length - a.dir.length);
+ const changed = new Map();
+ for (const file of changedFiles) {
+ if (TEST_FILE.test(file)) continue;
+ const owner = packages.find(pkg => file.startsWith(`${pkg.dir}/`));
+ if (owner != null) changed.set(owner.name, owner);
+ }
+ return [...changed.values()];
+}
+
+/**
+ * The tests a scoped pull request runs beyond `--changed`: every file-system
+ * guard, and every test that reaches a changed workspace package through its
+ * name or its `dist/`.
+ *
+ * @param {string[]} files tracked repository paths
+ * @param {(file: string) => string} read
+ * @param {string[]} changedFiles the pull request's paths
+ */
+export function scopedExtraTests(files, read, changedFiles = []) {
+ const guards = new Set(fsGuardTests(files, read));
+ const changed = changedWorkspacePackages(files, read, changedFiles);
+ if (changed.length > 0) {
+ const reachesBuild = (_source, specifiers) =>
+ specifiers.some(({raw, joined}) =>
+ changed.some(
+ pkg =>
+ raw === pkg.name ||
+ raw.startsWith(`${pkg.name}/`) ||
+ joined.startsWith(`${pkg.dir}/dist/`),
+ ),
+ );
+ for (const test of testsWhoseClosure(files, read, reachesBuild)) {
+ guards.add(test);
+ }
+ }
+ return files.filter(file => guards.has(file));
+}
+
+if (process.argv[1] === fileURLToPath(import.meta.url)) {
+ const files = execFileSync('git', ['ls-files', '-z'], {
+ encoding: 'utf8',
+ maxBuffer: 64 * 1024 * 1024,
+ })
+ .split('\0')
+ .filter(Boolean);
+ const changedFlag = process.argv.indexOf('--changed');
+ const changedFiles =
+ changedFlag === -1
+ ? []
+ : execFileSync(
+ 'git',
+ ['diff', '--name-only', '-z', process.argv[changedFlag + 1], 'HEAD'],
+ {encoding: 'utf8', maxBuffer: 64 * 1024 * 1024},
+ )
+ .split('\0')
+ .filter(Boolean);
+ const read = file => fs.readFileSync(file, 'utf8');
+ const tests = scopedExtraTests(files, read, changedFiles);
+ process.stdout.write(tests.length > 0 ? `${tests.join('\n')}\n` : '');
+}
diff --git a/.github/scripts/fs-guard-tests.test.mjs b/.github/scripts/fs-guard-tests.test.mjs
new file mode 100644
index 0000000000..9d16d86adb
--- /dev/null
+++ b/.github/scripts/fs-guard-tests.test.mjs
@@ -0,0 +1,172 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+
+import {execFileSync} from 'node:child_process';
+import fs from 'node:fs';
+import path from 'node:path';
+
+import {fsGuardTests, scopedExtraTests} from './fs-guard-tests.mjs';
+
+const sources = {
+ 'packages/core/src/Button/Button.test.tsx':
+ "import {Button} from './Button';",
+ 'packages/core/src/Button/Button.tsx': 'export function Button() {}',
+ 'packages/core/src/serverSafe.test.ts': "import fs from 'node:fs';",
+ 'packages/cli/test/doc-quality.test.mjs':
+ "import {guides} from '../foundation/discovery.mjs';",
+ 'packages/cli/foundation/discovery.mjs':
+ "import {read} from './io.js';\nexport const guides = read();",
+ 'packages/cli/foundation/io.ts': "import {readFileSync} from 'fs';",
+ 'scripts/topics.test.mjs':
+ 'const load = name => import(`./topics/${name}.mjs`);',
+ 'scripts/plain.test.mjs': "import {sum} from './sum.mjs';",
+ 'scripts/sum.mjs': 'export const sum = (a, b) => a + b;',
+ 'scripts/literal.test.mjs': "const mod = await import('./sum.mjs');",
+ 'packages/core/src/motion/springRows.test.ts':
+ "import {execFileSync} from 'node:child_process';",
+ 'packages/cli/test/readme-gen.test.mjs':
+ "const {spawnSync} = require('child_process');",
+ 'packages/core/src/AspectRatio/AspectRatio.test.tsx':
+ "const {readFileSync} = await import('fs');",
+ 'packages/core/src/theme/onMediaTokens.test.ts':
+ 'const fs = await import("fs/promises");',
+ 'scripts/node-prefix.test.cjs': "const fs = require('node:fs/promises');",
+ 'scripts/create-require.test.mjs':
+ "const load = createRequire(import.meta.url);\nconst cp = load('child_process');",
+ 'scripts/actual.test.ts': "const real = await vi.importActual('fs');",
+ 'scripts/glob.test.ts':
+ "const stories = import.meta.glob('./stories/*.tsx');",
+ 'scripts/named-like.test.mjs': "import {fsLike} from 'fs-extra-like';",
+ 'packages/cli/api/search/search-return-type.test.mjs':
+ "import ts from 'typescript';\nconst program = ts.createProgram([path.join(here, 'search.mjs')], {});",
+ 'scripts/loader.test.mjs':
+ "import {createRequire} from 'node:module';\nconst load = createRequire(import.meta.url);\nconst mod = load(computed);",
+ 'scripts/bundled.test.mjs': "const {buildSync} = require('esbuild');",
+ 'scripts/morph.test.ts': "import {Project} from 'ts-morph';",
+ 'scripts/babel.test.mjs': "import {transformFileSync} from '@babel/core';",
+ 'scripts/lint.test.mjs': "const {ESLint} = await import('eslint');",
+ 'scripts/plugin.test.mjs': "import plugin from 'eslint-plugin-local';",
+};
+
+const guards = () =>
+ fsGuardTests(Object.keys(sources), file => {
+ if (!(file in sources)) throw new Error(`untracked ${file}`);
+ return sources[file];
+ });
+
+describe('fsGuardTests', () => {
+ it('lists a test that reads the file system itself', () => {
+ expect(guards()).toContain('packages/core/src/serverSafe.test.ts');
+ });
+
+ it('lists a test that reads sources through a helper it imports, .js naming .ts', () => {
+ expect(guards()).toContain('packages/cli/test/doc-quality.test.mjs');
+ });
+
+ it('lists a test that imports a computed path', () => {
+ expect(guards()).toContain('scripts/topics.test.mjs');
+ });
+
+ it('lists a test that runs a script in a child process, which reads what it likes', () => {
+ expect(guards()).toContain('packages/core/src/motion/springRows.test.ts');
+ expect(guards()).toContain('packages/cli/test/readme-gen.test.mjs');
+ });
+
+ it.each([
+ 'packages/core/src/AspectRatio/AspectRatio.test.tsx',
+ 'packages/core/src/theme/onMediaTokens.test.ts',
+ 'scripts/node-prefix.test.cjs',
+ 'scripts/create-require.test.mjs',
+ 'scripts/actual.test.ts',
+ 'scripts/glob.test.ts',
+ 'packages/cli/api/search/search-return-type.test.mjs',
+ 'scripts/loader.test.mjs',
+ 'scripts/bundled.test.mjs',
+ 'scripts/morph.test.ts',
+ 'scripts/babel.test.mjs',
+ 'scripts/lint.test.mjs',
+ ])('lists %s, which names a file module in another spelling', file => {
+ expect(guards()).toContain(file);
+ });
+
+ it('leaves out tests whose imports read no files', () => {
+ expect(guards()).not.toContain('scripts/named-like.test.mjs');
+ expect(guards()).not.toContain('scripts/plugin.test.mjs');
+ expect(guards()).not.toContain('packages/core/src/Button/Button.test.tsx');
+ expect(guards()).not.toContain('scripts/plain.test.mjs');
+ expect(guards()).not.toContain('scripts/literal.test.mjs');
+ });
+
+ it('lists only tests', () => {
+ expect(guards().every(file => /\.test\./.test(file))).toBe(true);
+ });
+});
+
+describe('scopedExtraTests: tests that reach a changed package through its build', () => {
+ const tree = {
+ 'packages/core/package.json': '{"name": "@astryxdesign/core"}',
+ 'packages/core/src/utils/color.ts': 'export const mix = () => 1;',
+ 'packages/core/src/utils/color.test.ts': "import {mix} from './color';",
+ 'packages/themes/neutral/package.json':
+ '{"name": "@astryxdesign/theme-neutral"}',
+ 'packages/themes/neutral/src/neutralTheme.ts':
+ "import {mix} from '@astryxdesign/core/theme';\nexport const theme = mix();",
+ 'packages/themes/neutral/src/neutralTheme.test.ts':
+ "import {theme} from './neutralTheme';",
+ 'scripts/check-contrast.test.mjs':
+ "import {mix} from '@astryxdesign/core';",
+ 'scripts/from-dist.test.mjs':
+ "import {mix} from '../packages/core/dist/utils/color.js';",
+ 'scripts/unrelated.test.mjs':
+ "import {theme} from '@astryxdesign/theme-neutral';",
+ };
+ const run = changed =>
+ scopedExtraTests(Object.keys(tree), file => tree[file], changed);
+
+ it('lists the tests whose imports reach a changed package by name or through its dist/', () => {
+ expect(run(['packages/core/src/utils/color.ts'])).toEqual([
+ 'packages/themes/neutral/src/neutralTheme.test.ts',
+ 'scripts/check-contrast.test.mjs',
+ 'scripts/from-dist.test.mjs',
+ ]);
+ });
+
+ it('lists none for a change to a package nothing reaches through its build, or to a test only', () => {
+ expect(run(['packages/core/src/utils/color.test.ts'])).toEqual([]);
+ expect(run(['docs/notes.md'])).toEqual([]);
+ });
+
+ it('follows the package that changed: a theme change lists its own importers', () => {
+ expect(run(['packages/themes/neutral/src/neutralTheme.ts'])).toEqual([
+ 'scripts/unrelated.test.mjs',
+ ]);
+ });
+});
+
+describe('scopedExtraTests on this repository (contract)', () => {
+ const root = path.resolve(import.meta.dirname, '../..');
+ const files = execFileSync('git', ['ls-files', '-z'], {
+ cwd: root,
+ encoding: 'utf8',
+ maxBuffer: 64 * 1024 * 1024,
+ })
+ .split('\0')
+ .filter(Boolean);
+ const read = file => fs.readFileSync(path.join(root, file), 'utf8');
+
+ it("a Core color utility change runs the theme packages' suites and the contrast checks that load Core's build", () => {
+ const tests = scopedExtraTests(files, read, [
+ 'packages/core/src/utils/color.ts',
+ ]);
+ for (const expected of [
+ 'packages/themes/neutral/src/neutralTheme.test.ts',
+ 'packages/themes/stone/src/stoneTheme.test.ts',
+ '.github/scripts/visual-gate/lib/probe-theme.test.mjs',
+ 'scripts/check-badge-contrast.test.mjs',
+ 'scripts/check-status-text-contrast.test.mjs',
+ ]) {
+ expect(tests).toContain(expected);
+ }
+ });
+});
diff --git a/.github/scripts/release-check-workflow.test.mjs b/.github/scripts/release-check-workflow.test.mjs
index d5275c4859..baf1a36fbe 100644
--- a/.github/scripts/release-check-workflow.test.mjs
+++ b/.github/scripts/release-check-workflow.test.mjs
@@ -501,6 +501,7 @@ describe('full release scope without PR metadata or maintenance writes', () => {
docsite_only: 'false',
spec_only: 'false',
tooling_only: 'false',
+ full_suite: 'true',
release_bump: 'false',
},
],
diff --git a/.github/scripts/rtl-shard-scope.mjs b/.github/scripts/rtl-shard-scope.mjs
index 9413e83716..ee32ea4732 100644
--- a/.github/scripts/rtl-shard-scope.mjs
+++ b/.github/scripts/rtl-shard-scope.mjs
@@ -78,7 +78,16 @@ export function readAnalysis(analysisPath) {
'modifiedComponentOwners',
'modifiedComponents',
);
- const owners = [...added.owners, ...modified.owners];
+ // Reverse dependents of a changed shared module are audited too
+ // (spec:AST-030 FR13); the field is optional for older artifacts.
+ const dependents = analysis.dependentComponentOwners ?? [];
+ if (
+ !Array.isArray(dependents) ||
+ dependents.some(value => typeof value !== 'string')
+ ) {
+ throw new Error('dependentComponentOwners must be an array of strings');
+ }
+ const owners = [...added.owners, ...modified.owners, ...dependents];
if (
analysis.forceFullComponentAudits !== undefined &&
typeof analysis.forceFullComponentAudits !== 'boolean'
diff --git a/.github/scripts/rtl-shard-scope.test.mjs b/.github/scripts/rtl-shard-scope.test.mjs
index d74a517708..bbfc30e9ce 100644
--- a/.github/scripts/rtl-shard-scope.test.mjs
+++ b/.github/scripts/rtl-shard-scope.test.mjs
@@ -219,6 +219,51 @@ describe('RTL shard scope artifact handling', () => {
}
});
+ it('adds the reverse dependents of a changed shared module', () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'rtl-analysis-'));
+ const file = path.join(dir, 'analysis.json');
+ try {
+ fs.writeFileSync(
+ file,
+ JSON.stringify({
+ newComponentOwners: [],
+ modifiedComponentOwners: ['core/Button'],
+ dependentComponentOwners: ['core/Card'],
+ }),
+ );
+ expect(readAnalysis(file).owners).toEqual(['core/Button', 'core/Card']);
+ } finally {
+ fs.rmSync(dir, {recursive: true, force: true});
+ }
+ });
+
+ it("passes a dependent folder's members to the RTL filter by component name", () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'rtl-analysis-'));
+ const file = path.join(dir, 'analysis.json');
+ try {
+ fs.writeFileSync(
+ file,
+ JSON.stringify({
+ newComponentOwners: [],
+ modifiedComponentOwners: [],
+ dependentComponentOwners: ['core/Avatar', 'core/AvatarStatusDot'],
+ }),
+ );
+ const scope = resolveRtlShardScope({
+ packageName: 'core',
+ forceFull: false,
+ hasComponents: true,
+ hasHarness: false,
+ analysis: readAnalysis(file),
+ });
+ expect(scope.filter.split(',')).toEqual(
+ expect.arrayContaining(['core/Avatar', 'core/AvatarStatusDot']),
+ );
+ } finally {
+ fs.rmSync(dir, {recursive: true, force: true});
+ }
+ });
+
it.each([
['missing', null, 'Could not read analysis artifact'],
['malformed', '{not json', 'Could not read analysis artifact'],
diff --git a/.github/scripts/spec-owner-workflow.test.mjs b/.github/scripts/spec-owner-workflow.test.mjs
index f4f443f43b..aa576739f2 100644
--- a/.github/scripts/spec-owner-workflow.test.mjs
+++ b/.github/scripts/spec-owner-workflow.test.mjs
@@ -83,7 +83,7 @@ describe('spec-only workflow contract', () => {
);
expect(result.status, result.stderr).toBe(0);
expect(fs.readFileSync(output, 'utf8')).toBe(
- 'spec_only=true\ndocsite_only=false\ntooling_only=false\n',
+ 'spec_only=true\ndocsite_only=false\ntooling_only=false\nfull_suite=false\n',
);
fs.rmSync(path.join(classifierDir, 'knowledge-paths.cjs'));
diff --git a/.github/scripts/visual-gate/gate-context.test.mjs b/.github/scripts/visual-gate/gate-context.test.mjs
index b324c98b1e..a26e6025a1 100644
--- a/.github/scripts/visual-gate/gate-context.test.mjs
+++ b/.github/scripts/visual-gate/gate-context.test.mjs
@@ -155,3 +155,121 @@ describe('visual gate capture identity', () => {
).toMatchObject({sha: 'invalid', runId: '', runAttempt: 'invalid'});
});
});
+
+// Each case spawns the gate on a 192-story index; a loaded CI runner can take
+// longer than the default 30 s for the first, cold spawn.
+describe(
+ 'component scope with reverse dependents (spec:AST-030 FR13)',
+ {timeout: 120_000},
+ () => {
+ const repoRoot = path.resolve(path.dirname(SCRIPT), '../../..');
+ const baselineDir = path.join(repoRoot, '.github/visual-baseline');
+ let storybook;
+ let folders;
+
+ // A Storybook index of every baselined story, each tagged for every theme,
+ // so the touched-plus-dependent scope can pass the focused budget.
+ beforeEach(() => {
+ storybook = path.join(root, 'storybook');
+ fs.mkdirSync(storybook);
+ const manifest = JSON.parse(
+ fs.readFileSync(path.join(baselineDir, 'manifest.json'), 'utf8'),
+ );
+ const ids = [
+ ...new Set(Object.keys(manifest.shots).map(key => key.split('__')[0])),
+ ];
+ const entries = {};
+ for (const id of ids) {
+ const folder = id.split('--')[0].replace(/^core-/, '');
+ entries[id] = {
+ type: 'story',
+ id,
+ title: `Core/${folder}`,
+ name: id.split('--')[1],
+ componentPath: `../../packages/core/src/${folder}/index.ts`,
+ importPath: './stories/fixture.stories.tsx',
+ tags: ['visual-baseline'],
+ };
+ }
+ fs.writeFileSync(
+ path.join(storybook, 'index.json'),
+ JSON.stringify({v: 5, entries}),
+ );
+ folders = [
+ ...new Set(Object.values(entries).map(entry => entry.title.slice(5))),
+ ];
+ });
+
+ const gate = (command, ...args) =>
+ spawnSync(
+ process.execPath,
+ [
+ SCRIPT,
+ command,
+ '--storybook-dir',
+ storybook,
+ '--baseline',
+ baselineDir,
+ '--out',
+ output,
+ '--tiers',
+ 'component',
+ '--no-scout',
+ ...args,
+ ],
+ {encoding: 'utf8'},
+ );
+ const verdict = () =>
+ JSON.parse(fs.readFileSync(path.join(output, 'verdict.json'), 'utf8'));
+
+ it('writes the skipped verdict for an over-budget plan with reverse dependents, which the workflow answers with the whole plan', () => {
+ const result = gate(
+ 'check',
+ '--components',
+ folders[0],
+ '--dependents',
+ folders.join(','),
+ );
+ expect(result.stderr).not.toMatch(/ReferenceError/);
+ expect(result.status).toBe(0);
+ expect(verdict().status).toBe('skipped');
+ });
+
+ it('writes the same skipped verdict for an over-budget plan of touched components alone', () => {
+ const result = gate('check', '--components', folders.join(','));
+ expect(result.status).toBe(0);
+ expect(verdict().status).toBe('skipped');
+ });
+
+ it('plans the touched component and each dependent folder with a stable story, and reports the rest', () => {
+ const touched = gate('plan', '--json', '--components', folders[0]);
+ const scoped = gate(
+ 'plan',
+ '--json',
+ '--components',
+ folders[0],
+ '--dependents',
+ `${folders[1]},nosuchfolder`,
+ );
+ expect(scoped.status).toBe(0);
+ expect(scoped.stdout).toContain(
+ 'Reverse dependents with no stable story: nosuchfolder',
+ );
+ const planned = text => JSON.parse(text.slice(text.indexOf('[')));
+ expect(planned(scoped.stdout).length).toBeGreaterThan(
+ planned(touched.stdout).length,
+ );
+ });
+
+ it('asks for the whole plan (exit 3) when nothing the scope reaches has a stable story', () => {
+ const result = gate(
+ 'plan',
+ '--components',
+ '',
+ '--dependents',
+ 'nosuchfolder',
+ );
+ expect(result.status).toBe(3);
+ });
+ },
+);
diff --git a/.github/scripts/visual-gate/gate.mjs b/.github/scripts/visual-gate/gate.mjs
index 0043b28656..ce7f47905f 100644
--- a/.github/scripts/visual-gate/gate.mjs
+++ b/.github/scripts/visual-gate/gate.mjs
@@ -58,6 +58,7 @@ import {
resolvePrVisualTotalShotLimit,
storiesInPackages,
summarizeBaselineAccounting,
+ visualComponentScope,
withThemeMetadata,
} from './lib/plan.mjs';
import {renderReport} from './lib/report.mjs';
@@ -99,14 +100,25 @@ const sample = flag('sample') ? Number(flag('sample')) : null;
/** Restrict the plan to story ids containing any of these — for debugging a shot, never for a gate run. */
const only = (flag('only') ?? '').split(',').filter(Boolean);
/** For the `component` tier: the components a PR touched. */
-const components = (flag('components') ?? '').split(',').filter(Boolean);
+let components = (flag('components') ?? '').split(',').filter(Boolean);
+/**
+ * For the `component` tier: the folders the touched modules reach (reverse
+ * dependents, spec:AST-030 FR13), audited where they have a stable story.
+ */
+const dependents = (flag('dependents') ?? '').split(',').filter(Boolean);
+/**
+ * Exit code that asks the caller for the whole plan instead: nothing the scope
+ * reaches has a stable story. An over-budget focused plan writes the
+ * `skipped` verdict, which the workflow also answers with the whole plan.
+ */
+const BROADEN_EXIT_CODE = 3;
/** For the `theme-matrix` tier: only these shipped themes changed. */
const matrixThemes = (flag('themes') ?? '').split(',').filter(Boolean);
const explicitMaxShots = has('max-shots') ? flag('max-shots') : null;
if (has('max-shots') && explicitMaxShots === undefined) {
throw new Error('--max-shots requires a value.');
}
-const maxShots = resolvePrVisualTotalShotLimit({
+let maxShots = resolvePrVisualTotalShotLimit({
explicitMaxShots,
components,
matrixThemes,
@@ -130,6 +142,7 @@ if (
has('no-scout') ||
planFile ||
components.length ||
+ dependents.length ||
matrixThemes.length ||
only.length ||
sample)
@@ -227,6 +240,27 @@ async function plan({scoutOnly = false} = {}) {
config.defaultTheme,
);
const themeStories = baselineVisualStories(stories, baselineManifest);
+ if (dependents.length > 0) {
+ const scope = visualComponentScope(stories, components, dependents);
+ if (scope.dropped.length > 0) {
+ console.log(`Reverse dependents with no stable story: ${scope.dropped.join(', ')}`);
+ }
+ components = scope.components;
+ if (components.length === 0) {
+ // Nothing the scope reaches has a stable story: the caller runs the
+ // whole plan rather than an empty one.
+ console.log('No touched component or reverse dependent has a stable story; asking for the whole plan.');
+ process.exit(BROADEN_EXIT_CODE);
+ }
+ maxShots = resolvePrVisualTotalShotLimit({
+ explicitMaxShots,
+ components,
+ matrixThemes,
+ tiers,
+ configuredLimit: config.prVisualShotLimit,
+ safetyLimit: config.visualPlanSafetyLimit,
+ });
+ }
let observations;
const scouts =
diff --git a/.github/scripts/visual-gate/lib/plan.mjs b/.github/scripts/visual-gate/lib/plan.mjs
index b579b76c4d..f7f7f62b77 100644
--- a/.github/scripts/visual-gate/lib/plan.mjs
+++ b/.github/scripts/visual-gate/lib/plan.mjs
@@ -453,6 +453,28 @@ export function representativeStories(stories) {
return byComponent;
}
+/**
+ * The components a scoped pull request's visual gate audits (spec:AST-030
+ * FR13): every touched component, which must have a stable representative,
+ * plus each reverse-dependent folder that has one. A dependent folder with no
+ * stable story is reported, not audited.
+ *
+ * @param {ReturnType<typeof readStoryIndex>} stories
+ * @param {string[]} touched
+ * @param {string[]} dependents
+ * @returns {{components: string[], dropped: string[]}}
+ */
+export function visualComponentScope(stories, touched, dependents) {
+ const representatives = representativeStories(stories);
+ const kept = [];
+ const dropped = [];
+ for (const dependent of new Set(dependents)) {
+ if (touched.includes(dependent)) continue;
+ (representatives.has(dependent) ? kept : dropped).push(dependent);
+ }
+ return {components: [...new Set([...touched, ...kept])], dropped};
+}
+
/**
* Select the focused PR stories for touched components and fail closed when a
* requested component has no stable representative in the built Storybook.
diff --git a/.github/scripts/visual-gate/lib/plan.test.mjs b/.github/scripts/visual-gate/lib/plan.test.mjs
index d42e29adfb..e85636d78f 100644
--- a/.github/scripts/visual-gate/lib/plan.test.mjs
+++ b/.github/scripts/visual-gate/lib/plan.test.mjs
@@ -24,6 +24,7 @@ import {
storiesInPackages,
summarizeBaselineAccounting,
uncoveredTargets,
+ visualComponentScope,
} from './plan.mjs';
const story = (value, packageName = '@astryxdesign/core', stableVisual = true) => ({
@@ -762,3 +763,18 @@ describe('uncoveredTargets', () => {
expect(uncoveredTargets(targets, plan)).toEqual([{key: 'tooltip', component: 'Tooltip'}]);
});
});
+
+describe('visualComponentScope (spec:AST-030 FR13)', () => {
+ it('audits every touched component and each reverse-dependent folder with a stable story', () => {
+ expect(
+ visualComponentScope(stories, ['Button'], ['Badge', 'Button', 'Tooltip', 'Badge']),
+ ).toEqual({components: ['Button', 'Badge'], dropped: ['Tooltip']});
+ });
+
+ it('audits reverse dependents alone when nothing was touched directly', () => {
+ expect(visualComponentScope(stories, [], ['Badge'])).toEqual({
+ components: ['Badge'],
+ dropped: [],
+ });
+ });
+});
diff --git a/.github/scripts/visual-scope.mjs b/.github/scripts/visual-scope.mjs
index 9995dfcfe7..b06a9f02b7 100644
--- a/.github/scripts/visual-scope.mjs
+++ b/.github/scripts/visual-scope.mjs
@@ -41,13 +41,26 @@ function readPackage(repoRoot, file, manifests) {
return fs.existsSync(absolute) ? readJSON(absolute) : null;
}
+/** A Changeset is release notes: it renders nothing. */
+const CHANGESET = /^\.changeset\/(?!README\.md$)[^/]+\.md$/;
+
/**
* @param {string[]} files
* @param {string} repoRoot
* @param {Record<string, object>} manifests - trusted snapshots keyed by repo-relative path
+ * @param {{scoped?: boolean}} options - `scoped`: a pull request whose CI runs
+ * what it reaches (spec:AST-030 FR13); a Core module outside every
+ * component folder is audited through its reverse dependents, not the
+ * whole plan
*/
-export function classifyVisualScope(files, repoRoot = ROOT, manifests = {}) {
+export function classifyVisualScope(
+ files,
+ repoRoot = ROOT,
+ manifests = {},
+ {scoped = false} = {},
+) {
const paths = files.map(file => file.trim()).filter(Boolean);
+ const rendered = paths.filter(file => !CHANGESET.test(file));
const stableCoreFiles = paths.filter(
file =>
/^packages\/core\/src\/.*\.(ts|tsx|css)$/.test(file) &&
@@ -59,7 +72,7 @@ export function classifyVisualScope(files, repoRoot = ROOT, manifests = {}) {
const canaryPackages = new Set();
// Reuse the accepted surface taxonomy: unknown/shared inputs and the build
// pipeline cannot rely on a daily backup once this is the only visual owner.
- const {surfaces} = changeScope.classifyChanges(paths);
+ const {surfaces} = changeScope.classifyChanges(rendered);
const stableVisualInfrastructure =
paths.length === 0 ||
surfaces.some(surface =>
@@ -73,7 +86,7 @@ export function classifyVisualScope(files, repoRoot = ROOT, manifests = {}) {
for (const file of stableCoreFiles) {
const match = file.match(/^packages\/core\/src\/([^/]+)\//);
if (match && /^[A-Z]/.test(match[1])) stableComponents.add(match[1]);
- else broadStableVisual = true;
+ else if (!scoped) broadStableVisual = true;
}
for (const file of paths) {
@@ -149,7 +162,9 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
manifestsFlag === -1
? {}
: readJSON(path.resolve(process.argv[manifestsFlag + 1]));
- const result = classifyVisualScope(files, ROOT, manifests);
+ const result = classifyVisualScope(files, ROOT, manifests, {
+ scoped: process.argv.includes('--scoped'),
+ });
process.stdout.write(`${JSON.stringify(result)}\n`);
const output = process.argv[process.argv.indexOf('--github-output') + 1];
diff --git a/.github/scripts/visual-scope.test.mjs b/.github/scripts/visual-scope.test.mjs
index 0a5b41347f..b1529b458b 100644
--- a/.github/scripts/visual-scope.test.mjs
+++ b/.github/scripts/visual-scope.test.mjs
@@ -121,6 +121,35 @@ describe('classifyVisualScope', () => {
});
});
+ it('leaves a Changeset out: release notes render nothing', () => {
+ expect(
+ classifyVisualScope(
+ ['packages/core/src/Button/Button.tsx', '.changeset/button-fix.md'],
+ root,
+ ),
+ ).toMatchObject({
+ hasStableVisual: true,
+ broadStableVisual: false,
+ stableComponents: ['Button'],
+ });
+ expect(classifyVisualScope(['.changeset/notes.md'], root)).toMatchObject({
+ hasStableVisual: false,
+ broadStableVisual: false,
+ });
+ });
+
+ it('audits a shared Core module through its reverse dependents when the pull request runs what it reaches (spec:AST-030 FR13)', () => {
+ const files = ['packages/core/src/hooks/useHold.ts'];
+ expect(classifyVisualScope(files, root, {}, {scoped: true})).toMatchObject({
+ hasStableVisual: true,
+ broadStableVisual: false,
+ });
+ // Unscoped (main, a full-suite change), it keeps the whole plan.
+ expect(classifyVisualScope(files, root)).toMatchObject({
+ broadStableVisual: true,
+ });
+ });
+
it('ignores Core tests and component docs — they do not change pixels', () => {
const result = classifyVisualScope(
[
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index b8afa7ea57..4c4cefaab5 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -76,6 +76,13 @@ jobs:
docsite_only: ${{ steps.scope.outputs.docsite_only }}
spec_only: ${{ steps.scope.outputs.spec_only }}
tooling_only: ${{ steps.scope.outputs.tooling_only }}
+ # 'false' only for a pull request whose changes the import graph can
+ # scope (components, shared modules, docs, records). Anything else, an
+ # empty value included, runs the full suite: main, release branches,
+ # the merge queue, release-check dispatches, and shared infrastructure
+ # (build and test config, the test harness, tokens, themes, root
+ # dependencies, CI itself).
+ full_suite: ${{ steps.scope.outputs.full_suite }}
release_bump: ${{ steps.scope.outputs.release_bump }}
release_branch: ${{ steps.release-authority.outputs.branch || steps.main-authority.outputs.branch }}
release_head: ${{ steps.release-authority.outputs.head || steps.main-authority.outputs.head }}
@@ -181,18 +188,18 @@ jobs:
BASE_REF: ${{ github.base_ref }}
run: |
if [ "$EVENT_NAME" != pull_request ]; then
- printf 'docsite_only=false\nspec_only=false\ntooling_only=false\nrelease_bump=false\n' >> "$GITHUB_OUTPUT"
+ printf 'docsite_only=false\nspec_only=false\ntooling_only=false\nfull_suite=true\nrelease_bump=false\n' >> "$GITHUB_OUTPUT"
exit 0
fi
if [[ "$BASE_REF" == release/v* ]]; then
# Release bump PRs contain generated bookkeeping only. The final
# branch head receives one full visual/a11y/RTL release-check.
- printf 'docsite_only=false\nspec_only=true\ntooling_only=true\nrelease_bump=true\n' >> "$GITHUB_OUTPUT"
+ printf 'docsite_only=false\nspec_only=true\ntooling_only=true\nfull_suite=true\nrelease_bump=true\n' >> "$GITHUB_OUTPUT"
exit 0
fi
MERGE_BASE=$(git merge-base HEAD origin/${{ github.base_ref }} 2>/dev/null || echo "")
if [ -z "$MERGE_BASE" ]; then
- printf 'docsite_only=false\nspec_only=false\ntooling_only=false\nrelease_bump=false\n' >> "$GITHUB_OUTPUT"
+ printf 'docsite_only=false\nspec_only=false\ntooling_only=false\nfull_suite=true\nrelease_bump=false\n' >> "$GITHUB_OUTPUT"
exit 0
fi
echo 'release_bump=false' >> "$GITHUB_OUTPUT"
@@ -211,7 +218,7 @@ jobs:
else
# Missing trusted policy or dependencies cannot grant a specialized
# lane. Run broad CI until the base branch supplies the full classifier.
- printf 'docsite_only=false\nspec_only=false\ntooling_only=false\n' \
+ printf 'docsite_only=false\nspec_only=false\ntooling_only=false\nfull_suite=true\n' \
>> "$GITHUB_OUTPUT"
fi
# Generated-only version PR lane. It validates release bookkeeping in a few
@@ -548,6 +555,8 @@ jobs:
- name: Check for component changes
id: check
+ env:
+ SCOPED: ${{ github.event_name == 'pull_request' && needs.check-scope.outputs.full_suite == 'false' }}
run: |
if [ "${{ github.event_name }}" = 'workflow_dispatch' ]; then
printf 'has_components=true\nhas_rtl_components=true\nhas_rtl_harness=true\nforce_full_component_audits=true\nhas_stable_visual=true\nbroad_stable_visual=true\n' >> "$GITHUB_OUTPUT"
@@ -587,8 +596,12 @@ jobs:
# One classifier owns the release-channel rule. It reads each
# package's `astryx.canaryOnly` metadata rather than hard-coding
# today's Lab/charts/richtext/vega list.
+ # A pull request that runs what it reaches audits a shared Core
+ # module through its reverse dependents (spec:AST-030 FR13).
+ VISUAL_ARGS=()
+ if [ "$SCOPED" = true ]; then VISUAL_ARGS=(--scoped); fi
printf '%s\n' "$FILES" \
- | node .github/scripts/visual-scope.mjs --github-output "$GITHUB_OUTPUT"
+ | node .github/scripts/visual-scope.mjs --github-output "$GITHUB_OUTPUT" "${VISUAL_ARGS[@]}"
# Tests run as two parallel lanes joined by `test` below.
#
@@ -639,8 +652,12 @@ jobs:
if: needs.check-scope.outputs.docsite_only == 'true' || needs.check-scope.outputs.spec_only == 'true' || needs.check-scope.outputs.tooling_only == 'true'
run: echo "Specialized PR lane — skipping unrelated test suite"
+ # Two commits: a pull request's merge commit and its base parent, the
+ # diff a scoped run follows.
- uses: actions/checkout@v7
if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true' && needs.check-scope.outputs.tooling_only != 'true'
+ with:
+ fetch-depth: 2
- uses: ./.github/actions/setup
if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true' && needs.check-scope.outputs.tooling_only != 'true'
@@ -678,8 +695,28 @@ jobs:
if: matrix.shard == 1 && needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true' && needs.check-scope.outputs.tooling_only != 'true'
run: pnpm lab:readiness:check
+ # A scoped pull request runs the tests Vitest's module graph relates to
+ # its diff against the base (`--changed`): the changed tests, and every
+ # test that imports a changed module, however indirectly. Anything else
+ # runs every test.
- name: Run this shard of the UI tests
- run: pnpm test:ui --shard=${{ matrix.shard }}/${{ strategy.job-total }}
+ env:
+ SCOPED: ${{ github.event_name == 'pull_request' && needs.check-scope.outputs.full_suite == 'false' }}
+ run: |
+ if [ "$SCOPED" = true ]; then
+ pnpm test:ui --changed=HEAD^1 --passWithNoTests --shard=${{ matrix.shard }}/${{ strategy.job-total }}
+ # Tests no module graph relates to the change run too: guards
+ # that read sources, and tests that load a changed package from
+ # its build (by name or its dist/).
+ # The list goes through a file so a failing lister fails the step.
+ node .github/scripts/fs-guard-tests.mjs --changed HEAD^1 > "$RUNNER_TEMP/fs-guards.txt"
+ mapfile -t GUARDS < "$RUNNER_TEMP/fs-guards.txt"
+ if [ "${#GUARDS[@]}" -gt 0 ]; then
+ pnpm test:ui --passWithNoTests --shard=${{ matrix.shard }}/${{ strategy.job-total }} "${GUARDS[@]}"
+ fi
+ else
+ pnpm test:ui --shard=${{ matrix.shard }}/${{ strategy.job-total }}
+ fi
if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true' && needs.check-scope.outputs.tooling_only != 'true'
# A child process isolates engine state, not CPU or memory contention.
@@ -718,11 +755,31 @@ jobs:
- uses: actions/checkout@v7
if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'
+ with:
+ fetch-depth: 2
- uses: ./.github/actions/setup
if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'
- - run: pnpm test:node --shard=${{ matrix.shard }}/${{ strategy.job-total }}
+ # Scoped like test-ui's run.
+ - name: Run this shard of the Node tests
+ env:
+ SCOPED: ${{ github.event_name == 'pull_request' && needs.check-scope.outputs.full_suite == 'false' }}
+ run: |
+ if [ "$SCOPED" = true ]; then
+ pnpm test:node --changed=HEAD^1 --passWithNoTests --shard=${{ matrix.shard }}/${{ strategy.job-total }}
+ # Tests no module graph relates to the change run too: guards
+ # that read sources, and tests that load a changed package from
+ # its build (by name or its dist/).
+ # The list goes through a file so a failing lister fails the step.
+ node .github/scripts/fs-guard-tests.mjs --changed HEAD^1 > "$RUNNER_TEMP/fs-guards.txt"
+ mapfile -t GUARDS < "$RUNNER_TEMP/fs-guards.txt"
+ if [ "${#GUARDS[@]}" -gt 0 ]; then
+ pnpm test:node --passWithNoTests --shard=${{ matrix.shard }}/${{ strategy.job-total }} "${GUARDS[@]}"
+ fi
+ else
+ pnpm test:node --shard=${{ matrix.shard }}/${{ strategy.job-total }}
+ fi
if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'
# Theme-family compilation is owned by `theme-build`, not Build. Until
@@ -1051,11 +1108,18 @@ jobs:
- name: Analyze components
if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true' && needs.check-scope.outputs.tooling_only != 'true' && github.event_name == 'pull_request'
+ env:
+ FULL_SUITE: ${{ needs.check-scope.outputs.full_suite }}
run: |
+ # Browser audits follow the changed components and their reverse
+ # dependents, unless the change touches shared infrastructure.
+ FORCE_FULL=()
+ if [ "$FULL_SUITE" != false ]; then FORCE_FULL=(--force-full); fi
node .github/scripts/analyze-pr.js \
--base origin/${{ github.base_ref }} \
--head HEAD \
- --output analysis.json
+ --output analysis.json \
+ "${FORCE_FULL[@]}"
- name: Write PR comment metadata
if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true' && needs.check-scope.outputs.tooling_only != 'true' && github.event_name == 'pull_request'
@@ -2068,16 +2132,25 @@ jobs:
run: |
set -eu
# Component names are not globally unique; use their package identity.
- COMPONENTS=$(jq -r '. as $root | [(.newComponents + .modifiedComponents)[] | select($root.componentStats[.].package == "@astryxdesign/core")] | unique | join(",")' analysis.json)
+ TOUCHED=$(jq -r '. as $root | [(.newComponents + .modifiedComponents)[] | select($root.componentStats[.].package == "@astryxdesign/core")] | unique | join(",")' analysis.json)
+ # Reverse dependents by folder: the folders of the components RTL
+ # audits (spec:AST-030 FR13).
+ DEPENDENTS=$(jq -r '[(.dependentComponentFolders // [])[] | select(startswith("core/")) | ltrimstr("core/")] | unique | join(",")' analysis.json)
+ COMPONENTS="$TOUCHED"
+ DEPENDENT_ARGS=()
+ if [ -n "$DEPENDENTS" ]; then DEPENDENT_ARGS=(--dependents "$DEPENDENTS"); fi
THEMES=$(jq -r '(.changedStableThemes // []) | join(",")' analysis.json)
COMMAND=check
- if [ "$BROAD_STABLE_VISUAL" = 'true' ]; then
+ # Sources no build decided, or a full-suite change, audit the whole
+ # plan (spec:AST-030 FR13).
+ FORCE_FULL_AUDITS=$(jq -r '.forceFullComponentAudits == true' analysis.json)
+ if [ "$BROAD_STABLE_VISUAL" = 'true' ] || [ "$FORCE_FULL_AUDITS" = 'true' ]; then
COMMAND=release
SCOPE_ARGS=()
- elif [ -n "$COMPONENTS" ] && [ -n "$THEMES" ]; then
- SCOPE_ARGS=(--tiers 'component,theme-matrix' --components "$COMPONENTS" --themes "$THEMES")
- elif [ -n "$COMPONENTS" ]; then
- SCOPE_ARGS=(--tiers component --components "$COMPONENTS" --no-scout)
+ elif [ -n "$COMPONENTS$DEPENDENTS" ] && [ -n "$THEMES" ]; then
+ SCOPE_ARGS=(--tiers 'component,theme-matrix' --components "$COMPONENTS" "${DEPENDENT_ARGS[@]}" --themes "$THEMES")
+ elif [ -n "$COMPONENTS$DEPENDENTS" ]; then
+ SCOPE_ARGS=(--tiers component --components "$COMPONENTS" "${DEPENDENT_ARGS[@]}" --no-scout)
elif [ -n "$THEMES" ]; then
SCOPE_ARGS=(--tiers theme-matrix --themes "$THEMES")
else
@@ -2088,18 +2161,31 @@ jobs:
fi
echo "Stable Core components: ${COMPONENTS:-none}"
+ echo "Stable Core reverse dependents: ${DEPENDENTS:-none}"
echo "Stable themes: ${THEMES:-none}"
OBS_ARGS=()
if [ -d .visual-scout ]; then OBS_ARGS=(--observation-shards .visual-scout); fi
+ run_gate() {
+ node .github/scripts/visual-gate/gate.mjs "$COMMAND" \
+ --storybook-dir apps/storybook/dist \
+ --baseline .github/visual-baseline \
+ --out .visual-run \
+ "${SCOPE_ARGS[@]}" \
+ "${OBS_ARGS[@]}" \
+ --summary-output visual-summary.md
+ }
set +e
- node .github/scripts/visual-gate/gate.mjs "$COMMAND" \
- --storybook-dir apps/storybook/dist \
- --baseline .github/visual-baseline \
- --out .visual-run \
- "${SCOPE_ARGS[@]}" \
- "${OBS_ARGS[@]}" \
- --summary-output visual-summary.md
+ run_gate
code=$?
+ if [ "$code" = 3 ]; then
+ # Nothing the scope reaches has a stable story: the whole plan
+ # runs instead (spec:AST-030 FR13). An over-budget focused plan
+ # writes the skipped verdict, answered below the same way.
+ COMMAND=release
+ SCOPE_ARGS=()
+ run_gate
+ code=$?
+ fi
set -e
# Exit 2 is a visual change for review; every other nonzero exit is
# an infrastructure failure, not a successful evidence receipt.
diff --git a/docs/specs/AST-030/spec.md b/docs/specs/AST-030/spec.md
index 320827251f..b42e50e577 100644
--- a/docs/specs/AST-030/spec.md
+++ b/docs/specs/AST-030/spec.md
@@ -206,6 +206,32 @@ they are separately named.
surface, component, package, theme family, or visual suite MUST join the
canonical workflow. A repository guard MUST reject independent visual owners
while preserving legitimate non-visual artifact use.
+- **FR13 — Broad CI on a pull request runs what the change reaches.** On a
+ `pull_request` event whose trusted classification finds no shared
+ infrastructure, broad CI keeps every owner and required context and narrows
+ what those owners run. The Vitest test owner runs the tests whose module graph
+ reaches a changed file, against the merge commit's base parent, plus every test
+ that reads repository sources through the file system, directly or through a
+ module it imports; a computed `import()`, a child process, or a library that
+ reads sources for it (the TypeScript compiler, a bundler) counts as reading
+ sources; and every test that loads a changed workspace package from its build,
+ by the package's name or a path into its `dist/`. The visual and RTL
+ owners audit one affected set of component folders: the changed components
+ and their reverse dependents, the folders of the components, in any package,
+ whose built bundle, `import()` targets included, reaches a changed module.
+ Visual audits each dependent folder that has a stable story, and runs the
+ whole plan when the dependents exceed its focused budget or none has one; RTL
+ audits every component each of those folders implements. A Changeset renders nothing and widens no audit. A changed module that no component bundle holds adds none, and without
+ a readable build the audits run in full. PR accessibility stays scoped to
+ changed components (FR12). Shared infrastructure runs the full suite: root
+ dependency manifests and lockfile, root configuration, a package's manifest,
+ build or test configuration and test setup, `internal/` (the test harness
+ included), `theme-build` paths (tokens and themes), Storybook configuration,
+ `node-tooling` paths (FR8 keeps their whole Node project), and every other
+ `shared-or-unknown` path except Changesets. Every fail-closed
+ condition of FR3–FR4 also runs the full suite. `main`, release branches,
+ merge-group entries and `release-check` dispatches always run the full suite,
+ and release checks keep FR12's full scope.
### Platform support
@@ -226,7 +252,9 @@ itself.
Implementation begins by preserving those existing singleton surface sets and
making their ownership model reusable. Existing package, theme/build, and
Storybook/visual surfaces remain on broad CI until their dedicated owners are
-admitted. The current broad workflow may dispatch surface-owned jobs; their names
+admitted. Within broad CI, a pull request runs what its change reaches (FR13),
+while `main`, merge-group entries and release checks run everything. The current
+broad workflow may dispatch surface-owned jobs; their names
describe implementation, but they do not receive a specialized route until the
classifier and join contract are complete. New surfaces may add lanes only through
FR10. New coverage joins its current surface owner; visual regression remains in
@@ -244,6 +272,7 @@ the shared Storybook PR owner.
| 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 |
## Decision log
@@ -341,6 +370,20 @@ Rejected: a separate workflow, per-push full audits, and treating a maintenance
capture, skipped check, a checked SHA no longer in current `main` history, or
retroactive status as release evidence.
+### DEC-6 — Pull requests run what the change reaches; full runs stay where landing is decided
+
+**Reference:** `spec:AST-030/DEC-6`
+**Decider:** `cixzhang`, `2026-10-26`
+
+A pull request's Vitest legs and browser audits follow what its change reaches:
+the module graph for tests and built-bundle reach for components. Tests that
+read sources through the file system run whole, because no import reaches what
+they read. Shared infrastructure, uncertainty, `main`, merge-group entries and
+release checks run everything, so no landing or release gate narrows.
+
+Rejected: a full run triggered by approval, a label or a draft-to-ready change,
+which tests the pull request's head rather than the merged result.
+
## Open questions
None.