Skip to content

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

TypeScript

ci(pr-visual): compare only the stable published surface (#5575)

Cindy Zhanga7ad8f982f9e
diff --git a/.github/scripts/analyze-pr.js b/.github/scripts/analyze-pr.js
index f45e061b84..64dda8469e 100644
--- a/.github/scripts/analyze-pr.js
+++ b/.github/scripts/analyze-pr.js
@@ -532,6 +532,20 @@ function analyze() {
const componentStats = {};
const changedPackages = new Set();
+ // Stable theme packages are a visual surface of their own. They do not own
+ // component source dirs, so the component loop below cannot discover them;
+ // without this, changing a published theme silently skips pr-visual.
+ const changedStableThemes = [...new Set(
+ changedFiles.flatMap((file) => {
+ const match = file.match(/^packages\/themes\/([^/]+)\/src\//);
+ if (!match) return [];
+ const manifest = path.join(process.cwd(), 'packages', 'themes', match[1], 'package.json');
+ if (!fs.existsSync(manifest)) return [];
+ const pkg = JSON.parse(fs.readFileSync(manifest, 'utf8'));
+ return pkg.private === true || pkg.astryx?.canaryOnly === true ? [] : [match[1]];
+ }),
+ )].sort();
+
for (const pkg of PACKAGES) {
const allComponents = getComponentNames(pkg);
const prefix = pkgSrc(pkg) + '/';
@@ -591,6 +605,7 @@ function analyze() {
newExports,
componentStats,
changedPackages: [...changedPackages],
+ changedStableThemes,
// Records whether the file list is exact (three-dot) or approximate
// (two-dot fallback). Consumers that gate on the component list (pr-a11y)
// or render it in the report should caveat when this is 'two-dot'.
diff --git a/.github/scripts/analyze-pr.test.mjs b/.github/scripts/analyze-pr.test.mjs
index 74a61f4812..f7ac8743eb 100644
--- a/.github/scripts/analyze-pr.test.mjs
+++ b/.github/scripts/analyze-pr.test.mjs
@@ -56,6 +56,8 @@ function buildFixture() {
fs.mkdirSync(path.join(upstream, 'packages/core/src/Card'), {recursive: true});
fs.mkdirSync(path.join(upstream, 'packages/core/src/Button'), {recursive: true});
fs.mkdirSync(path.join(upstream, 'packages/core/src/Line'), {recursive: true});
+ fs.mkdirSync(path.join(upstream, 'packages/themes/neutral/src'), {recursive: true});
+ fs.mkdirSync(path.join(upstream, 'packages/themes/probe/src'), {recursive: true});
git(upstream, ['init', '-q', '-b', 'main']);
git(upstream, ['config', 'user.email', '[email protected]']);
@@ -64,6 +66,16 @@ function buildFixture() {
fs.writeFileSync(path.join(upstream, 'packages/core/src/Card/index.ts'), 'export {}\n');
fs.writeFileSync(path.join(upstream, 'packages/core/src/Button/index.ts'), 'export {}\n');
fs.writeFileSync(path.join(upstream, 'packages/core/src/Line/index.ts'), 'export {}\n');
+ fs.writeFileSync(
+ path.join(upstream, 'packages/themes/neutral/package.json'),
+ JSON.stringify({name: '@astryxdesign/theme-neutral', private: false}),
+ );
+ fs.writeFileSync(path.join(upstream, 'packages/themes/neutral/src/theme.ts'), 'export {}\n');
+ fs.writeFileSync(
+ path.join(upstream, 'packages/themes/probe/package.json'),
+ JSON.stringify({name: '@astryxdesign/theme-probe', private: true}),
+ );
+ fs.writeFileSync(path.join(upstream, 'packages/themes/probe/src/theme.ts'), 'export {}\n');
git(upstream, ['add', '-A']);
git(upstream, ['commit', '-qm', 'branch point']);
const branchPoint = git(upstream, ['rev-parse', 'HEAD']);
@@ -80,6 +92,8 @@ function buildFixture() {
git(upstream, ['branch', 'feature', branchPoint]);
git(upstream, ['checkout', '-q', 'feature']);
fs.appendFileSync(path.join(upstream, 'packages/core/src/Card/index.ts'), 'export const Card = {}\n');
+ fs.appendFileSync(path.join(upstream, 'packages/themes/neutral/src/theme.ts'), 'export const changed = true\n');
+ fs.appendFileSync(path.join(upstream, 'packages/themes/probe/src/theme.ts'), 'export const changed = true\n');
git(upstream, ['add', '-A']);
git(upstream, ['commit', '-qm', 'touch Card only']);
@@ -114,6 +128,7 @@ describe('analyze-pr shallow-clone recovery', () => {
expect(analysis.diffMode).toBe('three-dot');
expect(analysis.modifiedComponents).toEqual(['Card']);
expect(analysis.changedPackages).toEqual(['@astryxdesign/core']);
+ expect(analysis.changedStableThemes).toEqual(['neutral']);
} finally {
fs.rmSync(base, {recursive: true, force: true});
}
diff --git a/.github/scripts/visual-gate/README.md b/.github/scripts/visual-gate/README.md
index 171ce2105d..533e230d2a 100644
--- a/.github/scripts/visual-gate/README.md
+++ b/.github/scripts/visual-gate/README.md
@@ -68,6 +68,29 @@ open .visual-run/report/index.html
Exit codes are the contract: `0` pass, `1` crashed, `2` changed.
+### PR scope follows the release channel
+
+`pr-visual` compares only the stable published visual surface:
+
+- Core component change → every story of that component, light/dark, in every
+ shipped theme that styles it.
+- Published theme change → that theme's relevant target/story matrix.
+- Shared stable theming/token infrastructure → the full plan, which declines
+ visibly at the 240-shot review budget and defers to the daily gate.
+- A package with `package.json.astryx.canaryOnly: true` → no visual comparison,
+ no visual baseline, no capture-only smoke job. It still typechecks, unit-tests,
+ builds Storybook, and publishes to canary. Experimental pixels are not a
+ stable release decision and should not create a red check people learn to
+ ignore.
+
+The daily gate uses the same boundary: `stableStoryPackages` in
+`visual-gate.config.json` is currently `["Core"]`, so Lab/canary stories cannot
+hold a stable release. Pass `--story-packages '*'` only for an explicit
+non-release audit.
+
+`.github/scripts/visual-scope.mjs` owns that classification from package
+metadata; workflow YAML does not hard-code today's package names.
+
`--sample 24` takes an even slice of the plan for a quick smoke test.
`--observations <file>` caches the scout pass between runs.
diff --git a/.github/scripts/visual-gate/gate.mjs b/.github/scripts/visual-gate/gate.mjs
index 69982626b5..a0822e2312 100644
--- a/.github/scripts/visual-gate/gate.mjs
+++ b/.github/scripts/visual-gate/gate.mjs
@@ -29,7 +29,7 @@ import {fileURLToPath} from 'node:url';
import {capture, scout} from './lib/capture.mjs';
import {analyzeTargeting, buildVerdict, compareCaptures} from './lib/compare.mjs';
-import {buildPlan, readStoryIndex} from './lib/plan.mjs';
+import {buildPlan, readStoryIndex, storiesInPackages} from './lib/plan.mjs';
import {READ_TARGETS, emptyAccumulator, fold} from './lib/probe-reach.mjs';
import {AXES, PROBE_TOKENS, READ_AXES} from './lib/probe-axes.mjs';
import {renderReport} from './lib/report.mjs';
@@ -58,6 +58,8 @@ const sample = flag('sample') ? Number(flag('sample')) : null;
const only = (flag('only') ?? '').split(',').filter(Boolean);
/** For the `component` tier: the components a PR touched. */
const components = (flag('components') ?? '').split(',').filter(Boolean);
+/** For the `theme-matrix` tier: only these shipped themes changed. */
+const matrixThemes = (flag('themes') ?? '').split(',').filter(Boolean);
/**
* Above this many shots the run declines instead of capturing.
*
@@ -69,6 +71,10 @@ const components = (flag('components') ?? '').split(',').filter(Boolean);
* report nobody can read.
*/
const maxShots = flag('max-shots') ? Number(flag('max-shots')) : Infinity;
+/** Storybook package groups that own the stable visual baseline. */
+const storyPackages = (flag('story-packages') ?? config.stableStoryPackages.join(','))
+ .split(',')
+ .filter(Boolean);
/**
* Which stories the scout needs to look at: every story of a component some
@@ -94,7 +100,11 @@ async function plan() {
loadThemingTargets(REPO_ROOT),
loadThemeOverrides(REPO_ROOT, config.probeTheme),
]);
- const stories = readStoryIndex(storybookDir, Object.keys(config.excludeStories));
+ const indexedStories = readStoryIndex(
+ storybookDir,
+ Object.keys(config.excludeStories),
+ );
+ const stories = storiesInPackages(indexedStories, storyPackages);
let observations;
if (!has('no-scout') && (tiers.includes('theme-matrix') || tiers.includes('probe'))) {
@@ -124,6 +134,7 @@ async function plan() {
defaultTheme: config.defaultTheme,
tiers,
components,
+ matrixThemes,
probeTheme: config.probeTheme,
});
// A sample is for trying the rig out, never for a gate run: it is taken
@@ -155,9 +166,16 @@ async function runCapture(shots) {
},
});
manifest.context = {
+ // `sha` is the tested synthetic merge tree on pull_request runs. Keep the
+ // contributor's head and the base separately: acceptance binds to the head
+ // humans reviewed, while post-merge verification bridges to the final
+ // squash commit by comparing rendered hashes.
sha: process.env.GITHUB_SHA ?? null,
+ headSha: process.env.ASTRYX_PR_HEAD_SHA ?? null,
+ baseSha: process.env.ASTRYX_PR_BASE_SHA ?? null,
ref: process.env.GITHUB_REF ?? null,
runId: process.env.GITHUB_RUN_ID ?? null,
+ runAttempt: process.env.GITHUB_RUN_ATTEMPT ?? null,
};
fs.writeFileSync(
path.join(outDir, 'manifest.json'),
diff --git a/.github/scripts/visual-gate/lib/compare.mjs b/.github/scripts/visual-gate/lib/compare.mjs
index 3fadcc3ac6..3add9004f1 100644
--- a/.github/scripts/visual-gate/lib/compare.mjs
+++ b/.github/scripts/visual-gate/lib/compare.mjs
@@ -205,7 +205,16 @@ export function buildVerdict({
]),
}));
- const status = failures.length > 0 ? 'failed' : changes.length > 0 ? 'changed' : 'pass';
+ // Added and removed stable shots are decisions too. A new story has no
+ // before image, but allowing it to pass silently creates baseline debt that
+ // the next run cannot resolve; a removed story can delete the only coverage
+ // for a target. Both need the same explicit acceptance as changed pixels.
+ const status =
+ failures.length > 0
+ ? 'failed'
+ : changes.length > 0 || comparison.added.length > 0 || comparison.removed.length > 0
+ ? 'changed'
+ : 'pass';
return {
version: 1,
diff --git a/.github/scripts/visual-gate/lib/compare.test.mjs b/.github/scripts/visual-gate/lib/compare.test.mjs
index 42c77ada56..5a7cfc2ca4 100644
--- a/.github/scripts/visual-gate/lib/compare.test.mjs
+++ b/.github/scripts/visual-gate/lib/compare.test.mjs
@@ -181,13 +181,13 @@ describe('buildVerdict', () => {
expect(verdict.status).toBe('failed');
});
- it('does not fail a run just because shots were added', () => {
+ it('requires acceptance when stable shots are added or removed', () => {
const verdict = buildVerdict({
...base,
comparison: {changes: [], added: ['b'], removed: ['c'], unchanged: []},
failures: [],
});
- expect(verdict.status).toBe('pass');
+ expect(verdict.status).toBe('changed');
expect(verdict.counts).toMatchObject({added: 1, removed: 1});
});
});
diff --git a/.github/scripts/visual-gate/lib/plan.mjs b/.github/scripts/visual-gate/lib/plan.mjs
index d51b97937e..82b8df2eb5 100644
--- a/.github/scripts/visual-gate/lib/plan.mjs
+++ b/.github/scripts/visual-gate/lib/plan.mjs
@@ -110,6 +110,20 @@ function componentOf(entry) {
return segments[segments.length - 1] ?? '';
}
+/**
+ * Stable visual baselines are package-scoped. Storybook titles carry the
+ * package as their first segment (`Core/Button`, `Lab/Drawer`), so filtering
+ * here keeps canary-only stories out of both the plan and the target coverage
+ * analysis. `*` is an explicit audit override, never the release default.
+ *
+ * @param {ReturnType<typeof readStoryIndex>} stories
+ * @param {string[]} packages
+ */
+export function storiesInPackages(stories, packages) {
+ if (packages.includes('*')) return stories;
+ return stories.filter(story => packages.includes(story.title.split('/')[0]));
+}
+
/**
* One story per component: the first match against REPRESENTATIVE_NAMES, else
* the first story in index order (which is source order, so it is stable).
@@ -147,6 +161,7 @@ function rank(name) {
* @param {string} options.defaultTheme
* @param {string[]} options.tiers - any of 'theme-matrix', 'surface', 'full', 'component', 'probe'
* @param {string[]} [options.components] - for the 'component' tier: the components to cover
+ * @param {string[]} [options.matrixThemes] - restrict theme-matrix to changed shipped themes
* @param {string} [options.probeTheme] - name of the generated coverage theme
* @returns {Shot[]}
*/
@@ -158,6 +173,7 @@ export function buildPlan({
defaultTheme,
tiers,
components = [],
+ matrixThemes = [],
probeTheme = 'probe',
}) {
/** @type {Map<string, Shot>} */
@@ -211,7 +227,17 @@ export function buildPlan({
}
if (tiers.includes('theme-matrix')) {
- for (const shot of themeMatrix({stories, targets, themeOverrides, observations})) {
+ const matrixOverrides = matrixThemes.length
+ ? Object.fromEntries(
+ Object.entries(themeOverrides).filter(([theme]) => matrixThemes.includes(theme)),
+ )
+ : themeOverrides;
+ for (const shot of themeMatrix({
+ stories,
+ targets,
+ themeOverrides: matrixOverrides,
+ observations,
+ })) {
add(shot.shot, shot.reason);
}
}
diff --git a/.github/scripts/visual-gate/lib/plan.test.mjs b/.github/scripts/visual-gate/lib/plan.test.mjs
index 135e8bb57d..77882933d8 100644
--- a/.github/scripts/visual-gate/lib/plan.test.mjs
+++ b/.github/scripts/visual-gate/lib/plan.test.mjs
@@ -6,7 +6,14 @@ import * as path from 'node:path';
import {describe, expect, it} from 'vitest';
-import {buildPlan, readStoryIndex, representativeStories, shotKey, uncoveredTargets} from './plan.mjs';
+import {
+ buildPlan,
+ readStoryIndex,
+ representativeStories,
+ shotKey,
+ storiesInPackages,
+ uncoveredTargets,
+} from './plan.mjs';
const stories = [
{id: 'core-button--primary', title: 'Core/Button', name: 'Primary', component: 'Button', tags: []},
@@ -25,6 +32,24 @@ const themeOverrides = {
y2k: {button: ['base', 'variant:primary'], badge: ['base']},
};
+describe('storiesInPackages', () => {
+ const mixed = [
+ ...stories,
+ {id: 'lab-drawer--default', title: 'Lab/Drawer', name: 'Default', component: 'Drawer', tags: []},
+ {id: 'charts-bar--default', title: 'Charts/Bar', name: 'Default', component: 'Bar', tags: []},
+ ];
+
+ it('keeps only the stable Storybook package groups', () => {
+ expect(storiesInPackages(mixed, ['Core']).map(story => story.id)).toEqual(
+ stories.map(story => story.id),
+ );
+ });
+
+ it('allows an explicit all-packages audit without changing the release default', () => {
+ expect(storiesInPackages(mixed, ['*'])).toEqual(mixed);
+ });
+});
+
describe('representativeStories', () => {
it('prefers a conventionally named story over source order', () => {
expect(representativeStories(stories).get('Button').id).toBe('core-button--default');
@@ -53,6 +78,33 @@ describe('buildPlan', () => {
expect(y2k).toContain('core-badge--solid__y2k-dark');
});
+ it('restricts the theme matrix to changed shipped themes', () => {
+ const plan = buildPlan({
+ stories,
+ targets,
+ themeOverrides,
+ defaultTheme: 'neutral',
+ tiers: ['theme-matrix'],
+ matrixThemes: ['y2k'],
+ });
+ expect(new Set(plan.map(shot => shot.theme))).toEqual(new Set(['y2k']));
+ expect(plan.map(shot => shot.key)).toContain('core-badge--solid__y2k-light');
+ });
+
+ it('keeps every shipped theme for touched Core components even when the matrix is scoped', () => {
+ const plan = buildPlan({
+ stories,
+ targets,
+ themeOverrides,
+ defaultTheme: 'neutral',
+ tiers: ['component', 'theme-matrix'],
+ components: ['Button'],
+ matrixThemes: ['y2k'],
+ });
+ expect(plan.some(shot => shot.theme === 'neutral' && shot.component === 'Button')).toBe(true);
+ expect(plan.some(shot => shot.theme === 'y2k' && shot.component === 'Button')).toBe(true);
+ });
+
it('records why a shot is in the plan, merging the reasons of a shot both tiers want', () => {
const plan = buildPlan({stories, targets, themeOverrides, defaultTheme: 'neutral', tiers: ['surface', 'theme-matrix']});
const shot = plan.find(candidate => candidate.key === 'core-button--default__neutral-light');
diff --git a/.github/scripts/visual-gate/lib/sources.mjs b/.github/scripts/visual-gate/lib/sources.mjs
index 1945d71926..fe4178b95b 100644
--- a/.github/scripts/visual-gate/lib/sources.mjs
+++ b/.github/scripts/visual-gate/lib/sources.mjs
@@ -174,7 +174,7 @@ function unreadableTheme(repoRoot, name, built, error, rebuilt) {
/**
* @param {string} repoRoot
- * @returns {{excludeStories: Record<string, string>, viewport: {width: number, height: number}, settleMs: number, threshold: number, maxDiffPixels: number, defaultTheme: string, probeTheme: string, tiers: string[]}}
+ * @returns {{excludeStories: Record<string, string>, viewport: {width: number, height: number}, settleMs: number, threshold: number, maxDiffPixels: number, defaultTheme: string, probeTheme: string, stableStoryPackages: string[], tiers: string[]}}
*/
export function loadConfig(repoRoot) {
const defaults = {
@@ -185,6 +185,7 @@ export function loadConfig(repoRoot) {
maxDiffPixels: 0,
defaultTheme: 'neutral',
probeTheme: 'probe',
+ stableStoryPackages: ['Core'],
tiers: ['surface', 'theme-matrix', 'probe'],
};
const configPath = path.join(repoRoot, '.github/scripts/visual-gate/visual-gate.config.json');
diff --git a/.github/scripts/visual-gate/visual-gate.config.json b/.github/scripts/visual-gate/visual-gate.config.json
index 33bf6149ef..b9c959b987 100644
--- a/.github/scripts/visual-gate/visual-gate.config.json
+++ b/.github/scripts/visual-gate/visual-gate.config.json
@@ -3,6 +3,8 @@
"defaultTheme": "neutral",
"$probeTheme": "A generated fixture styling every declared target (packages/themes/probe). The gate treats it as the coverage instrument, not a design: it is what makes a NEW theming target verified from the day its doc lands.",
"probeTheme": "probe",
+ "$stableStoryPackages": "Only these Storybook package groups participate in the stable baseline. Canary-only packages have no stable visual baseline.",
+ "stableStoryPackages": ["Core"],
"tiers": ["surface", "theme-matrix", "probe"],
"viewport": {"width": 1024, "height": 768},
"settleMs": 50,
diff --git a/.github/scripts/visual-scope.mjs b/.github/scripts/visual-scope.mjs
new file mode 100644
index 0000000000..94e3701945
--- /dev/null
+++ b/.github/scripts/visual-scope.mjs
@@ -0,0 +1,117 @@
+#!/usr/bin/env node
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Classify changed files by release channel for visual CI.
+ *
+ * @input newline-separated paths on stdin (normally a base...head git diff)
+ * @output JSON, and optionally GitHub outputs
+ *
+ * Visual baselines belong to the stable product. A package marked
+ * `astryx.canaryOnly` deliberately has no stable visual baseline: Lab/charts/
+ * richtext/vega still typecheck, test and build Storybook, but random or
+ * experimental pixels are not a release decision and should not create a red
+ * check everyone learns to ignore.
+ *
+ * This reads package metadata rather than naming today's canary packages, so a
+ * package changing release channel changes classification in one place — its
+ * own package.json.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import {fileURLToPath} from 'node:url';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
+
+/** @param {string} file */
+function readJSON(file) {
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
+}
+
+/** @param {string} repoRoot @param {string} file @param {Record<string, object>} manifests */
+function readPackage(repoRoot, file, manifests) {
+ if (Object.hasOwn(manifests, file)) return manifests[file];
+ const absolute = path.join(repoRoot, file);
+ return fs.existsSync(absolute) ? readJSON(absolute) : null;
+}
+
+/**
+ * @param {string[]} files
+ * @param {string} repoRoot
+ * @param {Record<string, object>} manifests - trusted snapshots keyed by repo-relative path
+ */
+export function classifyVisualScope(files, repoRoot = ROOT, manifests = {}) {
+ const paths = files.map(file => file.trim()).filter(Boolean);
+ const stableCoreFiles = paths.filter(
+ file =>
+ /^packages\/core\/src\/.*\.(ts|tsx|css)$/.test(file) &&
+ !/\.(test|doc)\./.test(file),
+ );
+
+ const stableThemes = new Set();
+ const canaryPackages = new Set();
+
+ for (const file of paths) {
+ const pkgMatch = file.match(/^packages\/([^/]+)\//);
+ if (pkgMatch) {
+ const relativeManifest = path.join('packages', pkgMatch[1], 'package.json');
+ const pkg = readPackage(repoRoot, relativeManifest, manifests);
+ if (pkg?.astryx?.canaryOnly === true) {
+ canaryPackages.add(pkg.name ?? pkgMatch[1]);
+ }
+ }
+
+ const themeMatch = file.match(/^packages\/themes\/([^/]+)\/(?:src\/|package\.json$)/);
+ if (!themeMatch) continue;
+ const relativeManifest = path.join(
+ 'packages',
+ 'themes',
+ themeMatch[1],
+ 'package.json',
+ );
+ const pkg = readPackage(repoRoot, relativeManifest, manifests);
+ if (!pkg) continue;
+ if (pkg.private === true || pkg.astryx?.canaryOnly === true) {
+ if (pkg.astryx?.canaryOnly === true) {
+ canaryPackages.add(pkg.name ?? themeMatch[1]);
+ }
+ continue;
+ }
+ stableThemes.add(themeMatch[1]);
+ }
+
+ return {
+ hasStableVisual: stableCoreFiles.length > 0 || stableThemes.size > 0,
+ stableCoreFiles,
+ stableThemes: [...stableThemes].sort(),
+ canaryPackages: [...canaryPackages].sort(),
+ };
+}
+
+if (process.argv[1] === fileURLToPath(import.meta.url)) {
+ const files = fs.readFileSync(0, 'utf8').split('\n');
+ const manifestsFlag = process.argv.indexOf('--manifests');
+ const manifests =
+ manifestsFlag === -1 ? {} : readJSON(path.resolve(process.argv[manifestsFlag + 1]));
+ const result = classifyVisualScope(files, ROOT, manifests);
+ process.stdout.write(`${JSON.stringify(result)}\n`);
+
+ const output = process.argv[process.argv.indexOf('--github-output') + 1];
+ if (process.argv.includes('--github-output') && output) {
+ const outputValue = values => {
+ if (values.some(value => /[\r\n]/.test(value))) {
+ throw new Error('visual scope output contains a line break');
+ }
+ return values.join(',');
+ };
+ fs.appendFileSync(
+ output,
+ [
+ `stable_themes=${outputValue(result.stableThemes)}`,
+ `canary_packages=${outputValue(result.canaryPackages)}`,
+ `has_stable_visual=${result.hasStableVisual}`,
+ ].join('\n') + '\n',
+ );
+ }
+}
diff --git a/.github/scripts/visual-scope.test.mjs b/.github/scripts/visual-scope.test.mjs
new file mode 100644
index 0000000000..bde97e7dfc
--- /dev/null
+++ b/.github/scripts/visual-scope.test.mjs
@@ -0,0 +1,137 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {execFileSync} from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+
+import {classifyVisualScope} from './visual-scope.mjs';
+
+const SCRIPT = path.join(import.meta.dirname, 'visual-scope.mjs');
+
+let root;
+beforeEach(() => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'visual-scope-'));
+ const manifests = {
+ core: {name: '@astryxdesign/core'},
+ lab: {name: '@astryxdesign/lab', private: true, astryx: {canaryOnly: true}},
+ charts: {
+ name: '@astryxdesign/charts',
+ private: true,
+ astryx: {canaryOnly: true},
+ },
+ };
+ for (const [name, manifest] of Object.entries(manifests)) {
+ const dir = path.join(root, 'packages', name);
+ fs.mkdirSync(dir, {recursive: true});
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify(manifest));
+ }
+ for (const [name, manifest] of [
+ ['neutral', {name: '@astryxdesign/theme-neutral', private: false}],
+ ['probe', {name: '@astryxdesign/theme-probe', private: true}],
+ [
+ 'preview',
+ {
+ name: '@astryxdesign/theme-preview',
+ private: true,
+ astryx: {canaryOnly: true},
+ },
+ ],
+ ]) {
+ const dir = path.join(root, 'packages', 'themes', name);
+ fs.mkdirSync(dir, {recursive: true});
+ fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify(manifest));
+ }
+});
+afterEach(() => fs.rmSync(root, {recursive: true, force: true}));
+
+describe('classifyVisualScope', () => {
+ it('includes stable Core runtime changes', () => {
+ const result = classifyVisualScope(['packages/core/src/Button/Button.tsx'], root);
+ expect(result.hasStableVisual).toBe(true);
+ expect(result.stableCoreFiles).toEqual(['packages/core/src/Button/Button.tsx']);
+ });
+
+ it('ignores Core tests and component docs — they do not change pixels', () => {
+ const result = classifyVisualScope(
+ [
+ 'packages/core/src/Button/Button.test.tsx',
+ 'packages/core/src/Button/Button.doc.mjs',
+ ],
+ root,
+ );
+ expect(result.hasStableVisual).toBe(false);
+ });
+
+ it('includes a non-private shipped theme', () => {
+ const result = classifyVisualScope(
+ ['packages/themes/neutral/src/neutralTheme.ts'],
+ root,
+ );
+ expect(result).toMatchObject({hasStableVisual: true, stableThemes: ['neutral']});
+ });
+
+ it('uses trusted PR-head metadata for a promoted theme', () => {
+ const result = classifyVisualScope(
+ ['packages/themes/probe/package.json'],
+ root,
+ {
+ 'packages/themes/probe/package.json': {
+ name: '@astryxdesign/theme-probe',
+ private: false,
+ },
+ },
+ );
+ expect(result).toMatchObject({hasStableVisual: true, stableThemes: ['probe']});
+ });
+
+ it('excludes the private probe fixture', () => {
+ const result = classifyVisualScope(
+ ['packages/themes/probe/src/probeTheme.ts'],
+ root,
+ );
+ expect(result.hasStableVisual).toBe(false);
+ expect(result.stableThemes).toEqual([]);
+ });
+
+ it('excludes Lab and records its release channel from package metadata', () => {
+ const result = classifyVisualScope(['packages/lab/src/Drawer/Drawer.tsx'], root);
+ expect(result.hasStableVisual).toBe(false);
+ expect(result.canaryPackages).toEqual(['@astryxdesign/lab']);
+ });
+
+ it('rejects line breaks before writing GitHub outputs', () => {
+ const manifests = path.join(root, 'manifests.json');
+ const output = path.join(root, 'github-output');
+ fs.writeFileSync(
+ manifests,
+ JSON.stringify({
+ 'packages/lab/package.json': {
+ name: '@astryxdesign/lab\nhas_stable_visual=false',
+ astryx: {canaryOnly: true},
+ },
+ }),
+ );
+ expect(() =>
+ execFileSync(
+ process.execPath,
+ [SCRIPT, '--manifests', manifests, '--github-output', output],
+ {input: 'packages/lab/src/Drawer/Drawer.tsx\n'},
+ ),
+ ).toThrow();
+ });
+
+ it('does not hardcode package names — any canaryOnly package is excluded', () => {
+ const result = classifyVisualScope(
+ ['packages/charts/src/Bar.tsx', 'packages/themes/preview/src/theme.ts'],
+ root,
+ );
+ expect(result.hasStableVisual).toBe(false);
+ expect(result.canaryPackages).toEqual([
+ '@astryxdesign/charts',
+ '@astryxdesign/theme-preview',
+ ]);
+ });
+});
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index b6a49daf6b..55ff7449ca 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -85,6 +85,9 @@ jobs:
contents: read
outputs:
has_components: ${{ steps.check.outputs.has_components }}
+ # Stable visual scope is separate from component scope: Core and the
+ # non-private shipped themes participate; canaryOnly packages do not.
+ has_stable_visual: ${{ steps.check.outputs.has_stable_visual }}
steps:
- name: Checkout
uses: actions/checkout@v7
@@ -103,11 +106,21 @@ jobs:
run: |
if ! git merge-base HEAD origin/${{ github.base_ref }} >/dev/null 2>&1; then
echo "::warning::No merge base between HEAD and origin/${{ github.base_ref }} (clone too shallow) — assuming components changed so pr-a11y still runs"
- echo "has_components=true" >> $GITHUB_OUTPUT
+ echo "has_components=true" >> "$GITHUB_OUTPUT"
+ # Fail closed for the stable lane too: without a merge base we do
+ # not know whether a stable package changed.
+ echo "has_stable_visual=true" >> "$GITHUB_OUTPUT"
exit 0
fi
- CHANGED=$(git diff --name-only origin/${{ github.base_ref }}...HEAD -- packages/core/src/ packages/lab/src/ | grep -v -E '(hooks|theme|utils|i18n|__tests__)/' | head -1)
- echo "has_components=$( [ -n "$CHANGED" ] && echo true || echo false )" >> $GITHUB_OUTPUT
+ FILES=$(git diff --name-only origin/${{ github.base_ref }}...HEAD)
+ CHANGED=$(printf '%s\n' "$FILES" | grep -E '^packages/(core|lab)/src/' | grep -v -E '(hooks|theme|utils|i18n|__tests__)/' | head -1 || true)
+ echo "has_components=$( [ -n "$CHANGED" ] && echo true || echo false )" >> "$GITHUB_OUTPUT"
+
+ # 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.
+ printf '%s\n' "$FILES" \
+ | node .github/scripts/visual-scope.mjs --github-output "$GITHUB_OUTPUT"
# Run tests (parallel with build)
test:
@@ -525,22 +538,10 @@ jobs:
- name: Run theme layer cascade guard
run: node .github/scripts/theme-layer-cascade.js
- # RTL semantic audit. Sibling to pr-a11y: same build-storybook artifact, same
- # analysis.json scoping, so a PR only pays for the components it touched.
- # Unscoped this swept ~1400 stories and took ~26 min. The full sweep that
- # covers untouched components runs in rtl-weekly.yml.
- #
- # Two layers: (A) auto-discovery — D1 icon-mirror + D5 positional-mirror, no
- # curated selectors; (B) curated D2/D3/D4 from targets.json.
- #
- # SOFT / NON-BLOCKING (continue-on-error): findings surface a scorecard in the
- # job summary but don't block the merge, while the suite is observed for
- # flake. To promote: drop continue-on-error and add `pr-rtl` to required
- # checks. See apps/storybook/rtl-audit/README.md.
- # Visual regression, scoped to the components a PR touched. Sibling to
- # pr-a11y and pr-rtl: same build-storybook artifact, same analysis.json
- # scoping, so a PR pays only for what it changed — a median PR is ~16 shots
- # (~10s) against the 642 the daily release gate takes.
+ # Stable-package visual regression. Core components get every story in
+ # every shipped theme that styles them; a changed shipped theme gets its
+ # relevant matrix. Packages marked `astryx.canaryOnly` (Lab, charts,
+ # richtext, vega) do not compare pixels and do not own a baseline.
#
# Deeper than the daily gate where it looks: the release gate shoots ONE
# representative story per component, this shoots EVERY story of the touched
@@ -556,8 +557,9 @@ jobs:
# verdict surfaces in the job summary and the PR comment, and the release
# gate is the blocking one. To promote: drop continue-on-error.
pr-visual:
+ name: Stable visual regression
needs: [build-storybook, check-components]
- if: github.event_name == 'pull_request' && needs.check-components.outputs.has_components == 'true'
+ if: github.event_name == 'pull_request' && needs.check-components.outputs.has_stable_visual == 'true'
runs-on: 2-core-ubuntu-arm
continue-on-error: true
permissions:
@@ -616,23 +618,43 @@ jobs:
- name: Run the visual gate for the touched components
id: visual
+ env:
+ ASTRYX_PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
+ ASTRYX_PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
run: |
set -eu
- COMPONENTS=$(jq -r '(.newComponents + .modifiedComponents) | join(",")' analysis.json)
- if [ -z "$COMPONENTS" ]; then
- echo "No component changes resolved from analysis.json — nothing to shoot."
- exit 0
+ # Component names are not globally unique, so filter by the package
+ # recorded in componentStats — never infer stability from a name.
+ COMPONENTS=$(jq -r '. as $root | [(.newComponents + .modifiedComponents)[] | select($root.componentStats[.].package == "@astryxdesign/core")] | unique | join(",")' analysis.json)
+ THEMES=$(jq -r '(.changedStableThemes // []) | join(",")' analysis.json)
+
+ if [ -n "$COMPONENTS" ] && [ -n "$THEMES" ]; then
+ TIERS="component,theme-matrix"
+ SCOPE_ARGS=(--components "$COMPONENTS" --themes "$THEMES")
+ elif [ -n "$COMPONENTS" ]; then
+ TIERS="component"
+ SCOPE_ARGS=(--components "$COMPONENTS" --no-scout)
+ elif [ -n "$THEMES" ]; then
+ TIERS="theme-matrix"
+ SCOPE_ARGS=(--themes "$THEMES")
+ else
+ # Shared Core theming/tokens/hooks are stable but broad. Let the
+ # gate plan the full stable surface and decline visibly at the shot
+ # budget; the daily stable gate owns the exhaustive comparison.
+ TIERS="surface,theme-matrix,probe"
+ SCOPE_ARGS=()
fi
- echo "Components: $COMPONENTS"
+
+ echo "Stable Core components: ${COMPONENTS:-none}"
+ echo "Stable themes: ${THEMES:-none}"
set +e
node .github/scripts/visual-gate/gate.mjs check \
--storybook-dir apps/storybook/dist \
--baseline .visual-baseline \
--out .visual-run \
- --tiers component \
- --components "$COMPONENTS" \
+ --tiers "$TIERS" \
+ "${SCOPE_ARGS[@]}" \
--max-shots 240 \
- --no-scout \
--summary-output visual-summary.md
code=$?
[ -f visual-summary.md ] && cat visual-summary.md >> "$GITHUB_STEP_SUMMARY"
@@ -648,10 +670,24 @@ jobs:
name: visual-pr-report
path: |
.visual-run/verdict.json
+ .visual-run/manifest.json
+ .visual-run/shots/
.visual-run/report/
retention-days: 7
if-no-files-found: ignore
+ # RTL semantic audit. Sibling to pr-a11y: same build-storybook artifact, same
+ # analysis.json scoping, so a PR only pays for the components it touched.
+ # Unscoped this swept ~1400 stories and took ~26 min. The full sweep that
+ # covers untouched components runs in rtl-weekly.yml.
+ #
+ # Two layers: (A) auto-discovery — D1 icon-mirror + D5 positional-mirror, no
+ # curated selectors; (B) curated D2/D3/D4 from targets.json.
+ #
+ # SOFT / NON-BLOCKING (continue-on-error): findings surface a scorecard in the
+ # job summary but don't block the merge, while the suite is observed for
+ # flake. To promote: drop continue-on-error and add `pr-rtl` to required
+ # checks. See apps/storybook/rtl-audit/README.md.
pr-rtl:
needs: [build-storybook, check-components]
if: github.event_name == 'pull_request' && needs.check-components.outputs.has_components == 'true'
diff --git a/internal/lab-readiness/automated.mjs b/internal/lab-readiness/automated.mjs
index 20e40b939b..1b26b3bb27 100644
--- a/internal/lab-readiness/automated.mjs
+++ b/internal/lab-readiness/automated.mjs
@@ -98,9 +98,10 @@ function a11yComponentFromTitle(title) {
function ciComponentRoots(repoRoot) {
const ci = read(repoRoot, CI_WORKFLOW);
if (!ci) return [];
- const match = ci.match(/git diff --name-only [^\n]*?\.\.\.HEAD --([^|\n]+)/);
- if (!match) return [];
- return match[1].trim().split(/\s+/).filter(Boolean);
+ const pathspec = ci.match(/git diff --name-only [^\n]*?\.\.\.HEAD --([^|\n]+)/);
+ if (pathspec) return pathspec[1].trim().split(/\s+/).filter(Boolean);
+ const filtered = ci.match(/grep -E ['"]\^packages\/\(([^)]+)\)\/src\/['"]/);
+ return filtered ? filtered[1].split('|').map(name => `packages/${name}/src/`) : [];
}
/** Story-id prefixes the RTL auto-discovery sweep covers. */