An open source design system that's fully customizable and agent ready
TypeScript
ci(visual): bound component screenshot scope (#5840)
nynexman446474490c638ae9
diff --git a/.github/scripts/visual-gate/README.md b/.github/scripts/visual-gate/README.mdindex ab947a733e..4cb8401ab8 100644--- a/.github/scripts/visual-gate/README.md+++ b/.github/scripts/visual-gate/README.md@@ -72,12 +72,15 @@ Exit codes are the contract: `0` pass, `1` crashed, `2` changed.`pr-visual` compares only the stable published visual surface:-- Core component change → the representative story in the default theme and- every shipped theme that styles the component, plus any story explicitly- tagged `visual-baseline` in the default theme; all are captured light/dark.- Behavioral and audit-only fixtures stay in their dedicated checks without- multiplying the pixel baseline.-- Published theme change → that theme's relevant target/story matrix.+- Core component change → the representative story in every accepted baseline+ theme. Additional stories may opt into the default theme with+ `visual-baseline`, or the same all-theme matrix with `visual-theme-matrix`;+ all are captured light/dark. Behavioral and audit-only fixtures stay in their+ dedicated checks without multiplying the pixel baseline.+- Published theme change → every currently accepted visual story rendered in that+ theme. This catches a theme beginning to override a component it did not+ previously target. Theme-only plans are not charged against the focused+ component review ceiling.- Shared stable theming/token infrastructure → the full plan, which declinesvisibly at the 240-shot review budget and defers to the daily gate.- A package with `package.json.astryx.canaryOnly: true` → no visual comparison,@@ -86,6 +89,23 @@ Exit codes are the contract: `0` pass, `1` crashed, `2` changed.stable release decision and should not create a red check people learn toignore.+Visual scope is declared directly on the Storybook story object, next to the+example it controls—not in a separate registry:++```tsx+export const CustomSeparator: Story = {+ tags: ['visual-baseline'],+ render: () => /* ... */,+};+```++The representative story (`Default`, `Primary`, and similar conventional names)+is selected automatically and needs no tag. Use `visual-baseline` for an+additional default-theme contract, `visual-theme-matrix` only when that story+must be judged in every accepted theme, and no visual tag for behavioral or+audit-only fixtures. The existing `no-visual` tag excludes an unstable story+from visual capture entirely.+The daily gate uses the same boundary: `stableStoryPackages` in`visual-gate.config.json` is currently `["Core"]`, so Lab/canary stories cannothold a stable release. Pass `--story-packages '*'` only for an explicitdiff --git a/.github/scripts/visual-gate/gate-context.test.mjs b/.github/scripts/visual-gate/gate-context.test.mjsindex f19b45b767..190d3eedc9 100644--- a/.github/scripts/visual-gate/gate-context.test.mjs+++ b/.github/scripts/visual-gate/gate-context.test.mjs@@ -91,6 +91,14 @@ describe('visual gate capture identity', () => {});});+ it('rejects a max-shots flag without a value', () => {+ expect(() =>+ execFileSync(process.execPath, [SCRIPT, 'plan', '--max-shots'], {+ encoding: 'utf8',+ }),+ ).toThrow(/--max-shots requires a value/);+ });+it('records missing identity as null', () => {expect(captureContext()).toMatchObject({sha: null,diff --git a/.github/scripts/visual-gate/gate.mjs b/.github/scripts/visual-gate/gate.mjsindex 6bc6c913e6..3075f88be7 100644--- a/.github/scripts/visual-gate/gate.mjs+++ b/.github/scripts/visual-gate/gate.mjs@@ -36,11 +36,15 @@ import {validateReleasePlan,} from './lib/compare.mjs';import {+ acceptedVisualThemes,accountBaseline,+ baselineVisualStories,buildPlan,createReleasePlan,+ exceedsPrVisualShotLimit,readStoryIndex,readThemeCatalog,+ resolvePrVisualTotalShotLimit,storiesInPackages,summarizeBaselineAccounting,withBaselineCoverage,@@ -87,7 +91,18 @@ const only = (flag('only') ?? '').split(',').filter(Boolean);const components = (flag('components') ?? '').split(',').filter(Boolean);/** For the `theme-matrix` tier: only these shipped themes changed. */const matrixThemes = (flag('themes') ?? '').split(',').filter(Boolean);-const maxShots = flag('max-shots') ? Number(flag('max-shots')) : Infinity;+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({+ explicitMaxShots,+ components,+ matrixThemes,+ tiers,+ configuredLimit: config.prVisualShotLimit,+ safetyLimit: config.visualPlanSafetyLimit,+});const storyPackages = (flag('story-packages') ?? config.stableStoryPackages.join(',')).split(',').filter(Boolean);@@ -111,8 +126,10 @@ if (function readExactPlan(file) {const shots = JSON.parse(fs.readFileSync(path.resolve(file), 'utf8'));- if (!Array.isArray(shots) || shots.length > 5000) {- throw new Error('Exact visual plan must contain at most 5000 trusted shots.');+ if (!Array.isArray(shots) || shots.length > config.visualPlanSafetyLimit) {+ throw new Error(+ `Exact visual plan must contain at most ${config.visualPlanSafetyLimit} trusted shots.`,+ );}const keys = new Set();for (const shot of shots) {@@ -176,9 +193,20 @@ async function plan() {REPO_ROOT,);const stories = storiesInPackages(indexedStories, storyPackages);+ const {manifest: baselineManifest} = readBaseline(baselineDir);+ const componentThemes = acceptedVisualThemes(+ baselineManifest,+ themeCatalog,+ config.defaultTheme,+ );+ const themeStories = baselineVisualStories(stories, baselineManifest);let observations;- if (!has('no-scout') && (tiers.includes('theme-matrix') || tiers.includes('probe'))) {+ if (+ !has('no-scout') &&+ (tiers.includes('probe') ||+ (tiers.includes('theme-matrix') && matrixThemes.length === 0))+ ) {const cachePath = flag('observations');if (cachePath && fs.existsSync(cachePath)) {observations = JSON.parse(fs.readFileSync(cachePath, 'utf8'));@@ -198,6 +226,19 @@ async function plan() {}}+ const componentShotCount = tiers.includes('component')+ ? buildPlan({+ stories,+ targets,+ themeOverrides,+ observations,+ defaultTheme: config.defaultTheme,+ tiers: ['component'],+ components,+ componentThemes,+ probeTheme: config.probeTheme,+ }).length+ : 0;let shots = buildPlan({stories,targets,@@ -206,13 +247,19 @@ async function plan() {defaultTheme: config.defaultTheme,tiers,components,+ componentThemes,matrixThemes,+ themeStories,probeTheme: config.probeTheme,});let baselineAccount = null;if (releaseMode) {- const {manifest} = readBaseline(baselineDir);- baselineAccount = accountBaseline(manifest, indexedStories, themeCatalog, REPO_ROOT);+ baselineAccount = accountBaseline(+ baselineManifest,+ indexedStories,+ themeCatalog,+ REPO_ROOT,+ );shots = withBaselineCoverage(shots, {stories,baselineManifest: baselineAccount.manifest,@@ -226,7 +273,12 @@ async function plan() {? shots.filter(shot => only.some(fragment => shot.storyId.includes(fragment))): shots;if (!sample || sample >= filtered.length) {- return {shots: filtered, stories: indexedStories, baselineAccount};+ return {+ shots: filtered,+ stories: indexedStories,+ baselineAccount,+ componentShotCount,+ };}const step = filtered.length / sample;return {@@ -236,10 +288,16 @@ async function plan() {),stories: indexedStories,baselineAccount,+ componentShotCount,};}async function runCapture(shots, releasePlan = null) {+ if (shots.length > config.visualPlanSafetyLimit) {+ throw new Error(+ `Visual plan has ${shots.length} shots; safety limit is ${config.visualPlanSafetyLimit}.`,+ );+ }fs.rmSync(outDir, {recursive: true, force: true});fs.mkdirSync(outDir, {recursive: true});let last = 0;@@ -304,7 +362,8 @@ function stageReportImages({reportDir, keys, currentDir, baselinePath}) {}async function check() {- const {shots, stories, baselineAccount} = await plan();+ const {shots, stories, baselineAccount, componentShotCount = 0} =+ await plan();const releasePlan = releaseMode ? createReleasePlan(shots) : null;const baselineAccounting = releaseMode? summarizeBaselineAccounting(baselineAccount, shots)@@ -318,15 +377,30 @@ async function check() {);}- // Over budget: say so in the verdict rather than capturing. The report and- // the PR comment both render this, so a skipped check is visible as a- // decision, never as a silent pass.- if (shots.length > maxShots) {+ // Over budget: say so in the verdict rather than capturing. The focused+ // ceiling applies only to component-selected shots; theme-only matrices are+ // release evidence, not component review expansion. Broad unscoped plans use+ // the same configured ceiling through maxShots.+ const componentOverBudget = exceedsPrVisualShotLimit(+ componentShotCount,+ config.prVisualShotLimit,+ );+ const totalOverBudget = shots.length > maxShots;+ if (componentOverBudget || totalOverBudget) {+ const measuredShots = componentOverBudget+ ? componentShotCount+ : shots.length;+ const budget = componentOverBudget+ ? config.prVisualShotLimit+ : maxShots;+ const scope = componentOverBudget+ ? `component-selected shots (${components.length} components touched)`+ : 'shots';const verdict = {version: 1,status: 'skipped',generatedAt: new Date().toISOString(),- reason: `${shots.length} shots exceeds the ${maxShots}-shot budget${components.length ? ` (${components.length} components touched)` : ''} — too broad to review shot by shot here. The daily release gate covers this change against the full baseline.`,+ reason: `${measuredShots} ${scope} exceeds the ${budget}-shot budget — too broad to review shot by shot here. The daily release gate covers this change against the full baseline.`,context: {...captureIdentity(),headSha: process.env.ASTRYX_PR_HEAD_SHA ?? null,diff --git a/.github/scripts/visual-gate/lib/plan.mjs b/.github/scripts/visual-gate/lib/plan.mjsindex 3936dc9267..2c5e933355 100644--- a/.github/scripts/visual-gate/lib/plan.mjs+++ b/.github/scripts/visual-gate/lib/plan.mjs@@ -43,9 +43,12 @@ export const MODES = ['light', 'dark'];/** Story names preferred as a component's representative, most preferred first. */const REPRESENTATIVE_NAMES = ['Default', 'Basic', 'Primary', 'Overview', 'Example'];-/** A story carrying this tag is always captured for a touched component. */+/** A story carrying this tag is captured in the default theme for a touched component. */export const VISUAL_BASELINE_TAG = 'visual-baseline';+/** A story carrying this tag is captured in every accepted theme for a touched component. */+export const VISUAL_THEME_MATRIX_TAG = 'visual-theme-matrix';+/** A story carrying this tag is never captured (see visual-gate.config.json for the reasoned list). */export const SKIP_TAG = 'no-visual';@@ -393,6 +396,96 @@ export function representativeStories(stories) {return byComponent;}+/**+ * Select the focused PR stories for touched components and fail closed when a+ * requested component has no stable representative in the built Storybook.+ *+ * @param {ReturnType<typeof readStoryIndex>} stories+ * @param {string[]} components+ */+export function componentVisualStories(stories, components) {+ const wanted = [...new Set(components)];+ const representatives = representativeStories(stories);+ const missing = wanted.filter(component => !representatives.has(component));+ if (missing.length > 0) {+ throw new Error(+ `Touched component(s) have no stable visual representative: ${missing.join(', ')}`,+ );+ }+ return stories+ .filter(story => {+ if (!wanted.includes(story.component)) return false;+ return (+ representatives.get(story.component)?.id === story.id ||+ (story.tags ?? []).includes(VISUAL_BASELINE_TAG) ||+ (story.tags ?? []).includes(VISUAL_THEME_MATRIX_TAG)+ );+ })+ .map(story => ({+ story,+ useThemeMatrix:+ representatives.get(story.component)?.id === story.id ||+ (story.tags ?? []).includes(VISUAL_THEME_MATRIX_TAG),+ }));+}++/**+ * Themes already represented by the accepted stable baseline. The default+ * theme is always present for a focused component capture.+ */+export function acceptedVisualThemes(manifest, themes, defaultTheme) {+ const accepted = new Set(+ Object.values(manifest?.shots ?? {})+ .map(shot => shot.theme)+ .filter(theme => themes[theme]?.stableVisual === true),+ );+ if (themes[defaultTheme]?.stableVisual === true) accepted.add(defaultTheme);+ return [...accepted].sort();+}++/** Current stable stories that own at least one accepted baseline contract. */+export function baselineVisualStories(stories, manifest) {+ const indexed = new Map(stories.map(story => [story.id, story]));+ const selected = new Map();+ for (const shot of Object.values(manifest?.shots ?? {})) {+ const story = indexed.get(shot.storyId);+ if (story) selected.set(story.id, story);+ }+ return [...selected.values()].sort((a, b) => a.id.localeCompare(b.id));+}++/** Resolve the total-plan ceiling: review budget for broad plans, safety budget for focused scopes. */+export function resolvePrVisualTotalShotLimit({+ explicitMaxShots,+ components,+ matrixThemes,+ tiers,+ configuredLimit,+ safetyLimit,+}) {+ if (!Number.isSafeInteger(safetyLimit) || safetyLimit <= 0) {+ throw new Error('Visual plan safety limit must be a positive integer.');+ }+ if (explicitMaxShots != null) {+ const explicit = Number(explicitMaxShots);+ if (!Number.isSafeInteger(explicit) || explicit < 0) {+ throw new Error('--max-shots must be a non-negative integer.');+ }+ return Math.min(explicit, safetyLimit);+ }+ const focusedComponent =+ tiers.includes('component') && components.length > 0;+ const focusedTheme =+ tiers.includes('theme-matrix') && matrixThemes.length > 0;+ if (focusedComponent || focusedTheme) return safetyLimit;+ return Math.min(configuredLimit, safetyLimit);+}++/** Component review budgets are shared by the ordinary and trusted planners. */+export function exceedsPrVisualShotLimit(count, limit) {+ return count > limit;+}+/*** @param {string} name* @returns {number}@@ -413,7 +506,9 @@ 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.componentThemes] - accepted themes for representative and matrix-tagged stories* @param {string[]} [options.matrixThemes] - restrict theme-matrix to changed shipped themes+ * @param {ReturnType<typeof readStoryIndex>} [options.themeStories] - accepted stories to render for changed themes* @param {string} [options.probeTheme] - name of the generated coverage theme* @returns {Shot[]}*/@@ -425,7 +520,9 @@ export function buildPlan({defaultTheme,tiers,components = [],+ componentThemes = [],matrixThemes = [],+ themeStories = [],probeTheme = 'probe',}) {/** @type {Map<string, Shot>} */@@ -453,33 +550,19 @@ export function buildPlan({}if (tiers.includes('component')) {- // The PR tier: one representative story in every theme that styles the- // touched component, plus explicit visual-baseline opt-ins in the default- // theme. Behavioral and audit-only fixtures remain available to their- // dedicated checks without multiplying the pixel baseline.- const themesByComponent = new Map();- for (const target of targets) {- for (const [theme, keys] of Object.entries(themeOverrides)) {- if (!Object.hasOwn(keys, target.key)) continue;- if (!themesByComponent.has(target.component)) {- themesByComponent.set(target.component, new Set());- }- themesByComponent.get(target.component).add(theme);- }- }- const subject = stories.filter(- story =>- components.includes(story.component) &&- (representatives.get(story.component)?.id === story.id ||- (story.tags ?? []).includes(VISUAL_BASELINE_TAG)),- );- for (const story of subject) {- const isRepresentative =- representatives.get(story.component)?.id === story.id;+ // The PR tier: one representative story in every accepted theme.+ // visual-baseline adds a default-theme story; visual-theme-matrix opts a+ // visually dense story into the same all-theme matrix. Behavioral and+ // audit-only fixtures remain available to their dedicated checks without+ // multiplying the baseline.+ for (const {story, useThemeMatrix} of componentVisualStories(+ stories,+ components,+ )) {for (const mode of MODES) {add({...toShotBase(story), theme: defaultTheme, mode}, 'component');- if (!isRepresentative) continue;- for (const theme of themesByComponent.get(story.component) ?? []) {+ if (!useThemeMatrix) continue;+ for (const theme of componentThemes) {if (theme === defaultTheme) continue;add({...toShotBase(story), theme, mode}, `theme:${theme}`);}@@ -488,18 +571,31 @@ export function buildPlan({}if (tiers.includes('theme-matrix')) {- 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);+ if (matrixThemes.length > 0) {+ if (themeStories.length === 0) {+ throw new Error(+ `Changed theme(s) have no accepted visual stories: ${matrixThemes.join(', ')}`,+ );+ }+ for (const theme of matrixThemes) {+ for (const story of themeStories) {+ for (const mode of MODES) {+ add(+ {...toShotBase(story), theme, mode},+ `changed-theme:${theme}`,+ );+ }+ }+ }+ } else {+ for (const shot of themeMatrix({+ stories,+ targets,+ themeOverrides,+ 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.mjsindex 88f8227870..63d6edac57 100644--- a/.github/scripts/visual-gate/lib/plan.test.mjs+++ b/.github/scripts/visual-gate/lib/plan.test.mjs@@ -7,12 +7,16 @@ import * as path from 'node:path';import {describe, expect, it} from 'vitest';import {+ acceptedVisualThemes,accountBaseline,+ baselineVisualStories,buildPlan,createReleasePlan,+ exceedsPrVisualShotLimit,readStoryIndex,readThemeCatalog,representativeStories,+ resolvePrVisualTotalShotLimit,shotKey,storiesInPackages,summarizeBaselineAccounting,@@ -71,6 +75,114 @@ describe('representativeStories', () => {});});+describe('acceptedVisualThemes', () => {+ it('uses stable baseline themes and always includes the stable default', () => {+ expect(+ acceptedVisualThemes(+ {shots: {a: {theme: 'y2k'}, b: {theme: 'probe'}}},+ {+ neutral: {stableVisual: true},+ probe: {stableVisual: false},+ y2k: {stableVisual: true},+ },+ 'neutral',+ ),+ ).toEqual(['neutral', 'y2k']);+ });+});++describe('baselineVisualStories', () => {+ it('reuses every current story with an accepted contract for changed themes', () => {+ const selected = baselineVisualStories(stories, {+ shots: {+ button: {storyId: 'core-button--default', theme: 'neutral'},+ badge: {storyId: 'core-badge--solid', theme: 'y2k'},+ deleted: {storyId: 'core-gone--default', theme: 'neutral'},+ },+ });+ expect(selected.map(story => story.id)).toEqual([+ 'core-badge--solid',+ 'core-button--default',+ ]);+ });+});++describe('resolvePrVisualTotalShotLimit', () => {+ it('caps broad plans at the review limit and scoped plans at the safety limit', () => {+ const base = {+ configuredLimit: 240,+ explicitMaxShots: null,+ safetyLimit: 5000,+ tiers: [],+ };+ expect(+ resolvePrVisualTotalShotLimit({+ ...base,+ components: [],+ matrixThemes: [],+ }),+ ).toBe(240);+ expect(+ resolvePrVisualTotalShotLimit({+ ...base,+ tiers: ['surface'],+ components: ['Button'],+ matrixThemes: [],+ }),+ ).toBe(240);+ expect(+ resolvePrVisualTotalShotLimit({+ ...base,+ tiers: ['component'],+ components: ['Button'],+ matrixThemes: [],+ }),+ ).toBe(5000);+ expect(+ resolvePrVisualTotalShotLimit({+ ...base,+ tiers: ['theme-matrix'],+ components: [],+ matrixThemes: ['neutral'],+ }),+ ).toBe(5000);+ expect(+ resolvePrVisualTotalShotLimit({+ ...base,+ explicitMaxShots: '17',+ tiers: ['theme-matrix'],+ components: [],+ matrixThemes: ['neutral'],+ }),+ ).toBe(17);+ expect(+ resolvePrVisualTotalShotLimit({+ ...base,+ explicitMaxShots: '6000',+ tiers: ['theme-matrix'],+ components: [],+ matrixThemes: ['neutral'],+ }),+ ).toBe(5000);+ expect(() =>+ resolvePrVisualTotalShotLimit({+ ...base,+ explicitMaxShots: 'not-a-number',+ tiers: [],+ components: [],+ matrixThemes: [],+ }),+ ).toThrow(/non-negative integer/);+ });+});++describe('exceedsPrVisualShotLimit', () => {+ it('allows the exact configured ceiling and rejects one more', () => {+ expect(exceedsPrVisualShotLimit(240, 240)).toBe(false);+ expect(exceedsPrVisualShotLimit(241, 240)).toBe(true);+ });+});+describe('buildPlan', () => {it('photographs one story per component in the default theme for the surface tier', () => {const plan = buildPlan({stories, targets, themeOverrides, defaultTheme: 'neutral', tiers: ['surface']});@@ -97,8 +209,12 @@ describe('buildPlan', () => {defaultTheme: 'neutral',tiers: ['theme-matrix'],matrixThemes: ['y2k'],+ themeStories: stories,});expect(new Set(plan.map(shot => shot.theme))).toEqual(new Set(['y2k']));+ expect(new Set(plan.map(shot => shot.storyId))).toEqual(+ new Set(stories.map(story => story.id)),+ );expect(plan.map(shot => shot.key)).toContain('core-badge--solid__y2k-light');});@@ -110,7 +226,9 @@ describe('buildPlan', () => {defaultTheme: 'neutral',tiers: ['component', 'theme-matrix'],components: ['Button'],+ componentThemes: ['neutral', 'y2k'],matrixThemes: ['y2k'],+ themeStories: stories,});expect(plan.some(shot => shot.theme === 'neutral' && shot.component === 'Button')).toBe(true);expect(plan.some(shot => shot.theme === 'y2k' && shot.component === 'Button')).toBe(true);@@ -120,6 +238,7 @@ describe('buildPlan', () => {const componentStories = [...stories,story({id: 'core-button--separator', title: 'Core/Button', name: 'Separator', component: 'Button', tags: ['visual-baseline']}),+ story({id: 'core-button--variants', title: 'Core/Button', name: 'Variants', component: 'Button', tags: ['visual-theme-matrix']}),story({id: 'core-button--fixture', title: 'Core/Button', name: 'Fixture', component: 'Button'}),];const plan = buildPlan({@@ -129,11 +248,42 @@ describe('buildPlan', () => {defaultTheme: 'neutral',tiers: ['component'],components: ['Button'],+ componentThemes: ['neutral', 'y2k', 'gothic'],});expect(new Set(plan.map(shot => shot.storyId))).toEqual(- new Set(['core-button--default', 'core-button--separator']),+ new Set([+ 'core-button--default',+ 'core-button--separator',+ 'core-button--variants',+ ]),);- expect(plan).toHaveLength(6);+ expect(plan).toHaveLength(14);+ expect(+ plan+ .filter(shot => shot.storyId === 'core-button--separator')+ .map(shot => shot.theme),+ ).toEqual(['neutral', 'neutral']);+ expect(+ new Set(+ plan+ .filter(shot => shot.storyId === 'core-button--variants')+ .map(shot => shot.theme),+ ),+ ).toEqual(new Set(['gothic', 'neutral', 'y2k']));+ });++ it('fails closed when a touched component has no stable representative', () => {+ expect(() =>+ buildPlan({+ stories,+ targets,+ themeOverrides,+ defaultTheme: 'neutral',+ tiers: ['component'],+ components: ['Button', 'Missing'],+ componentThemes: ['neutral'],+ }),+ ).toThrow(/Missing/);});it('records why a shot is in the plan, merging the reasons of a shot both tiers want', () => {diff --git a/.github/scripts/visual-gate/lib/sources.mjs b/.github/scripts/visual-gate/lib/sources.mjsindex 2a23a96573..54b2b369fe 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, scoutConcurrency: number, captureConcurrency: number, compareConcurrency: number, threshold: number, maxDiffPixels: number, defaultTheme: string, probeTheme: string, stableStoryPackages: string[], tiers: string[]}}+ * @returns {{excludeStories: Record<string, string>, viewport: {width: number, height: number}, settleMs: number, scoutConcurrency: number, captureConcurrency: number, compareConcurrency: number, threshold: number, maxDiffPixels: number, defaultTheme: string, probeTheme: string, stableStoryPackages: string[], prVisualShotLimit: number, visualPlanSafetyLimit: number, tiers: string[]}}*/export function loadConfig(repoRoot) {const defaults = {@@ -189,6 +189,8 @@ export function loadConfig(repoRoot) {defaultTheme: 'neutral',probeTheme: 'probe',stableStoryPackages: ['Core'],+ prVisualShotLimit: 240,+ visualPlanSafetyLimit: 5000,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/publish-pr-report.mjs b/.github/scripts/visual-gate/publish-pr-report.mjsindex 121bdc414b..ca3e4165d2 100644--- a/.github/scripts/visual-gate/publish-pr-report.mjs+++ b/.github/scripts/visual-gate/publish-pr-report.mjs@@ -51,7 +51,7 @@ const MAX_PNG_BYTES = 12 * 1024 * 1024;const MAX_PNG_WIDTH = 5000;const MAX_PNG_HEIGHT = 10000;const MAX_PNG_PIXELS = 25_000_000;-const MAX_SHOTS = 5000;+const MAX_SHOTS = config.visualPlanSafetyLimit;function fail(message) {throw new Error(`visual evidence rejected: ${message}`);diff --git a/.github/scripts/visual-gate/publish-pr-report.test.mjs b/.github/scripts/visual-gate/publish-pr-report.test.mjsindex 0b1cdb4544..04f8c4a7be 100644--- a/.github/scripts/visual-gate/publish-pr-report.test.mjs+++ b/.github/scripts/visual-gate/publish-pr-report.test.mjs@@ -323,6 +323,42 @@ describe('trusted PR visual publisher', () => {expect(fs.existsSync(path.join(output, 'after', `${key}.png`))).toBe(true);});+ it('publishes trusted evidence for a theme-only bundle above the component limit', () => {+ writeBaseline({});+ writeJSON(scope, {+ hasStableVisual: true,+ broadStableVisual: false,+ stableComponents: [],+ stableThemes: ['neutral'],+ });+ const shots = {};+ const bytes = png(0, 255, 0);+ for (let index = 0; index < 242; index += 1) {+ const key = `core-theme-${index}--default__neutral-light`;+ shots[key] = {+ shot: {+ ...SHOT,+ storyId: `core-theme-${index}--default`,+ component: `Theme${index}`,+ },+ bytes,+ };+ }+ writeCapture(shots);++ run();++ const evidence = JSON.parse(+ fs.readFileSync(path.join(output, 'evidence.json'), 'utf8'),+ );+ expect(evidence.verdict).toMatchObject({+ status: 'changed',+ counts: {total: 242, added: 242, failed: 0},+ });+ expect(evidence.deltas).toHaveLength(242);+ expect(fs.readdirSync(path.join(output, 'after'))).toHaveLength(242);+ });+it('does not derive removals from a scoped PR capture', () => {const other = 'core-card--default__neutral-light';writeBaseline({diff --git a/.github/scripts/visual-gate/visual-acceptance.mjs b/.github/scripts/visual-gate/visual-acceptance.mjsindex 8a51a49281..690f1ceee3 100644--- a/.github/scripts/visual-gate/visual-acceptance.mjs+++ b/.github/scripts/visual-gate/visual-acceptance.mjs@@ -20,6 +20,10 @@ import {} from './authorization.mjs';import {canonicalizePng} from './lib/canonical-png.mjs';import {+ acceptedVisualThemes,+ baselineVisualStories,+ componentVisualStories,+ exceedsPrVisualShotLimit,readStoryIndex,readThemeCatalog,representativeStories,@@ -199,7 +203,10 @@ function validateEvidence(evidence, expected) {) {fail('evidence verdict is invalid');}- if (!Array.isArray(evidence.deltas) || evidence.deltas.length > 5000) {+ if (+ !Array.isArray(evidence.deltas) ||+ evidence.deltas.length > config.visualPlanSafetyLimit+ ) {fail('evidence delta list is invalid');}if (evidence.verdict.status === 'skipped') {@@ -624,8 +631,13 @@ function readTrustedBaseline(stories = null) {fail('trusted visual baseline is invalid');}const entries = Object.entries(baseline.shots);- if (entries.length === 0 || entries.length > 5000) {- fail(`trusted visual baseline has invalid size ${entries.length}`);+ if (+ entries.length === 0 ||+ entries.length > config.visualPlanSafetyLimit+ ) {+ fail(+ `trusted visual baseline has invalid size ${entries.length}; safety limit is ${config.visualPlanSafetyLimit}`,+ );}return {baseline, entries};}@@ -723,16 +735,17 @@ function trustedPlan() {allIndexed,config.stableStoryPackages,);- const {entries: baselineEntries} = readTrustedBaseline(allIndexed);+ const {baseline} = readTrustedBaseline(allIndexed);- const baselineThemes = [- ...new Set(baselineEntries.map(([, shot]) => shot.theme)),- ].filter(Boolean);+ const baselineThemes = acceptedVisualThemes(+ baseline,+ themeCatalog,+ config.defaultTheme,+ );const shots = [];if (scope.stableComponents.length > 0 || scope.stableThemes.length > 0) {- const indexedStories = new Map(indexed.map(story => [story.id, story]));- const add = (story, theme) => {+ const add = (story, theme, componentKeys = null) => {for (const mode of ['light', 'dark']) {const shot = {storyId: story.storyId ?? story.id,@@ -746,44 +759,40 @@ function trustedPlan() {mode,reasons: ['trusted:pr-scope'],};- shots.push({...shot, key: shotKey(shot)});+ const keyed = {...shot, key: shotKey(shot)};+ shots.push(keyed);+ componentKeys?.add(keyed.key);}};- const componentStories = new Map();- const representatives = representativeStories(indexed);- for (const story of indexedStories.values()) {- const isRepresentative =- representatives.get(story.component)?.id === story.id;- if (- scope.stableComponents.includes(story.component) &&- (isRepresentative ||- (story.tags ?? []).includes(VISUAL_BASELINE_TAG))- ) {- componentStories.set(story.storyId ?? story.id, {- isRepresentative,- story,- });- }- }- for (const {isRepresentative, story} of componentStories.values()) {- add(story, config.defaultTheme);- if (!isRepresentative) continue;+ const componentKeys = new Set();+ for (const {story, useThemeMatrix} of componentVisualStories(+ indexed,+ scope.stableComponents,+ )) {+ add(story, config.defaultTheme, componentKeys);+ if (!useThemeMatrix) continue;for (const theme of baselineThemes) {- if (theme !== config.defaultTheme) add(story, theme);+ if (theme !== config.defaultTheme) add(story, theme, componentKeys);}}+ if (+ exceedsPrVisualShotLimit(+ componentKeys.size,+ config.prVisualShotLimit,+ )+ ) {+ fail(+ `trusted component plan has invalid size ${componentKeys.size}; focused PR limit is ${config.prVisualShotLimit}`,+ );+ }+ const themeStories = baselineVisualStories(indexed, baseline);for (const theme of scope.stableThemes) {- const isNew = !baselineThemes.includes(theme);- const themeStories = new Map();- for (const [, shot] of baselineEntries) {- const story = indexedStories.get(shot.storyId) ?? shot;- if (isNew || shot.theme === theme) {- themeStories.set(shot.storyId, story);- }+ if (themeStories.length === 0) {+ fail(`changed theme ${theme} has no accepted visual stories`);}- for (const story of themeStories.values()) add(story, theme);+ for (const story of themeStories) add(story, theme);}}const unique = withThemeMetadata(@@ -793,8 +802,13 @@ function trustedPlan() {if (unique.some(shot => shot.stableThemeVisual !== true)) {fail('trusted stable plan includes a private or canary theme');}- if (unique.length === 0 || unique.length > 5000) {- fail(`trusted visual plan has invalid size ${unique.length}`);+ if (+ unique.length === 0 ||+ unique.length > config.visualPlanSafetyLimit+ ) {+ fail(+ `trusted visual plan has invalid size ${unique.length}; safety limit is ${config.visualPlanSafetyLimit}`,+ );}writeJSON(output, unique);process.stdout.write(diff --git a/.github/scripts/visual-gate/visual-acceptance.test.mjs b/.github/scripts/visual-gate/visual-acceptance.test.mjsindex e868fb0da7..4ed1086560 100644--- a/.github/scripts/visual-gate/visual-acceptance.test.mjs+++ b/.github/scripts/visual-gate/visual-acceptance.test.mjs@@ -514,6 +514,14 @@ describe('visual acceptance', () => {componentPath: '../../packages/core/src/Button/index.ts',tags: ['visual-baseline'],},+ variants: {+ type: 'story',+ id: 'core-button--variants',+ title: 'Core/Button',+ name: 'Variants',+ componentPath: '../../packages/core/src/Button/index.ts',+ tags: ['visual-theme-matrix'],+ },fixture: {type: 'story',id: 'core-button--interaction-fixture',@@ -561,13 +569,226 @@ describe('visual acceptance', () => {'core-button--default__y2k-dark','core-button--separator__neutral-light','core-button--separator__neutral-dark',+ 'core-button--variants__neutral-light',+ 'core-button--variants__neutral-dark',+ 'core-button--variants__y2k-light',+ 'core-button--variants__y2k-dark',+ ]);+ });++ it('fails closed when any touched component has no representative story', () => {+ const storybook = path.join(root, 'storybook-missing-component');+ fs.mkdirSync(storybook);+ writeJSON(path.join(storybook, 'index.json'), {+ entries: {+ button: {+ type: 'story',+ id: 'core-button--default',+ title: 'Core/Button',+ name: 'Default',+ componentPath: '../../packages/core/src/Button/index.ts',+ tags: [],+ },+ },+ });+ const scope = path.join(root, 'scope-missing-component.json');+ writeJSON(scope, {+ hasStableVisual: true,+ broadStableVisual: false,+ stableComponents: ['Button', 'Card'],+ stableThemes: [],+ });+ expect(+ fail('trusted-plan', {+ scope,+ baseline: path.join(pages, 'visual-gate', 'baseline'),+ 'storybook-dir': storybook,+ output: path.join(root, 'missing-component-plan.json'),+ }),+ ).toMatch(/Card/);+ });++ it('applies the focused PR shot limit to trusted tagged stories', () => {+ const storybook = path.join(root, 'storybook-shot-limit');+ fs.mkdirSync(storybook);+ const entries = {};+ for (let index = 0; index < 61; index += 1) {+ entries[`story-${index}`] = {+ type: 'story',+ id: `core-button--story-${index}`,+ title: 'Core/Button',+ name: index === 0 ? 'Default' : `Story ${index}`,+ componentPath: '../../packages/core/src/Button/index.ts',+ tags: index === 0 ? [] : ['visual-theme-matrix'],+ };+ }+ writeJSON(path.join(storybook, 'index.json'), {entries});+ const baselineFile = path.join(+ pages,+ 'visual-gate',+ 'baseline',+ 'manifest.json',+ );+ const baseline = JSON.parse(fs.readFileSync(baselineFile, 'utf8'));+ baseline.shots['core-button--default__y2k-light'] = {+ ...baseline.shots[KEY],+ key: 'core-button--default__y2k-light',+ theme: 'y2k',+ mode: 'light',+ };+ writeJSON(baselineFile, baseline);+ const scope = path.join(root, 'scope-shot-limit.json');+ writeJSON(scope, {+ hasStableVisual: true,+ broadStableVisual: false,+ stableComponents: ['Button'],+ stableThemes: [],+ });+ expect(+ fail('trusted-plan', {+ scope,+ baseline: path.join(pages, 'visual-gate', 'baseline'),+ 'storybook-dir': storybook,+ output: path.join(root, 'over-limit-plan.json'),+ }),+ ).toMatch(/244.*240/);+ });++ it('allows a theme-only trusted plan above the component review limit', () => {+ const storybook = path.join(root, 'storybook-large-theme');+ fs.mkdirSync(storybook);+ const entries = {};+ const shots = {};+ for (let index = 0; index < 121; index += 1) {+ const id = `core-button--theme-${index}`;+ const key = `${id}__neutral-light`;+ entries[`story-${index}`] = {+ type: 'story',+ id,+ title: 'Core/Button',+ name: index === 0 ? 'Default' : `Theme ${index}`,+ componentPath: '../../packages/core/src/Button/index.ts',+ tags: [],+ };+ shots[key] = {+ ...SHOT,+ key,+ storyId: id,+ name: entries[`story-${index}`].name,+ theme: 'neutral',+ mode: 'light',+ };+ }+ writeJSON(path.join(storybook, 'index.json'), {entries});+ writeJSON(+ path.join(pages, 'visual-gate', 'baseline', 'manifest.json'),+ {+ version: 1,+ platform: 'linux-arm64',+ browser: 'chromium-140.0',+ viewport: {width: 1280, height: 900},+ shots,+ decisions: [],+ },+ );+ const scope = path.join(root, 'scope-large-theme.json');+ writeJSON(scope, {+ hasStableVisual: true,+ broadStableVisual: false,+ stableComponents: [],+ stableThemes: ['neutral'],+ });+ const output = path.join(root, 'large-theme-plan.json');+ run('trusted-plan', {+ scope,+ baseline: path.join(pages, 'visual-gate', 'baseline'),+ 'storybook-dir': storybook,+ output,+ });+ const plan = JSON.parse(fs.readFileSync(output, 'utf8'));+ expect(plan).toHaveLength(242);+ expect(new Set(plan.map(shot => shot.theme))).toEqual(new Set(['neutral']));+ });++ it('includes newly targeted components for an existing changed theme', () => {+ const storybook = path.join(root, 'storybook-existing-theme');+ fs.mkdirSync(storybook);+ writeJSON(path.join(storybook, 'index.json'), {+ entries: {+ button: {+ type: 'story',+ id: 'core-button--default',+ title: 'Core/Button',+ name: 'Default',+ componentPath: '../../packages/core/src/Button/index.ts',+ tags: [],+ },+ card: {+ type: 'story',+ id: 'core-card--default',+ title: 'Core/Card',+ name: 'Default',+ componentPath: '../../packages/core/src/Card/index.ts',+ tags: [],+ },+ },+ });+ const baselineFile = path.join(+ pages,+ 'visual-gate',+ 'baseline',+ 'manifest.json',+ );+ const baseline = JSON.parse(fs.readFileSync(baselineFile, 'utf8'));+ baseline.shots['core-card--default__y2k-light'] = {+ ...baseline.shots[KEY],+ key: 'core-card--default__y2k-light',+ storyId: 'core-card--default',+ title: 'Core/Card',+ component: 'Card',+ theme: 'y2k',+ mode: 'light',+ };+ writeJSON(baselineFile, baseline);+ const scope = path.join(root, 'scope-existing-theme.json');+ writeJSON(scope, {+ hasStableVisual: true,+ broadStableVisual: false,+ stableComponents: [],+ stableThemes: ['y2k'],+ });+ const output = path.join(root, 'existing-theme-plan.json');+ run('trusted-plan', {+ scope,+ baseline: path.join(pages, 'visual-gate', 'baseline'),+ 'storybook-dir': storybook,+ output,+ });+ expect(+ JSON.parse(fs.readFileSync(output, 'utf8')).map(shot => shot.key),+ ).toEqual([+ 'core-button--default__y2k-light',+ 'core-button--default__y2k-dark',+ 'core-card--default__y2k-light',+ 'core-card--default__y2k-dark',]);});it('plans every baseline story for a newly promoted stable theme', () => {const storybook = path.join(root, 'storybook-new-theme');fs.mkdirSync(storybook);- writeJSON(path.join(storybook, 'index.json'), {entries: {}});+ writeJSON(path.join(storybook, 'index.json'), {+ entries: {+ button: {+ type: 'story',+ id: 'core-button--default',+ title: 'Core/Button',+ name: 'Default',+ componentPath: '../../packages/core/src/Button/index.ts',+ tags: [],+ },+ },+ });const scope = path.join(root, 'scope-new-theme.json');writeJSON(scope, {hasStableVisual: true,diff --git a/.github/scripts/visual-gate/visual-gate.config.json b/.github/scripts/visual-gate/visual-gate.config.jsonindex 440077f6f5..32a0eaf820 100644--- a/.github/scripts/visual-gate/visual-gate.config.json+++ b/.github/scripts/visual-gate/visual-gate.config.json@@ -5,6 +5,10 @@"probeTheme": "probe","$stableStoryPackages": "Only these Storybook package groups participate in the stable baseline. Canary-only packages have no stable visual baseline.","stableStoryPackages": ["Core"],+ "$prVisualShotLimit": "Review ceiling for focused component shots and broad shared-infrastructure plans. Theme-only matrices are not component-budgeted.",+ "prVisualShotLimit": 240,+ "$visualPlanSafetyLimit": "Absolute resource ceiling for every ordinary and trusted visual plan, regardless of scope.",+ "visualPlanSafetyLimit": 5000,"tiers": ["surface", "theme-matrix", "probe"],"viewport": {"width": 1024, "height": 768},"settleMs": 50,diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex a2ad46c07a..052a3b06a2 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -627,17 +627,19 @@ jobs:run: pnpm -F @astryxdesign/vibe-tests fixtures:contrast# Stable-package visual regression. Core components get one representative- # story in every shipped theme that styles them, plus explicit- # `visual-baseline` stories in the default theme; a changed shipped theme gets- # its relevant matrix. Packages marked `astryx.canaryOnly` (Lab, charts,+ # story in every accepted baseline theme. `visual-baseline` adds default-theme+ # stories; `visual-theme-matrix` adds all-theme stories. A changed shipped+ # theme gets its relevant matrix. Packages marked `astryx.canaryOnly` (Lab,# richtext, vega) do not compare pixels and do not own a baseline.## Deeper than the daily gate only where the component declares it: audit and# interaction fixtures stay available to their dedicated checks without# multiplying the pixel baseline.#- # SKIPS ITSELF WHEN A PR IS TOO BROAD (--max-shots). A token or shared-hook- # change puts hundreds of diffs in front of a reviewer who cannot judge them+ # SKIPS ITSELF WHEN COMPONENT OR SHARED-INFRASTRUCTURE SCOPE IS TOO BROAD.+ # Theme-only matrices are release evidence and are not charged against the+ # focused component review ceiling. A token or shared-hook change puts+ # hundreds of diffs in front of a reviewer who cannot judge them# one by one, and a per-PR check is the wrong instrument for that change —# the daily gate reviews it against the whole baseline instead. The skip# states its reason in the PR comment rather than vanishing.@@ -743,7 +745,6 @@ jobs:--out .visual-run \--tiers "$TIERS" \"${SCOPE_ARGS[@]}" \- --max-shots 240 \--summary-output visual-summary.mdcode=$?[ -f visual-summary.md ] && cat visual-summary.md >> "$GITHUB_STEP_SUMMARY"