An open source design system that's fully customizable and agent ready
TypeScript
feat(internal): lab readiness audit tooling + CI a11y/RTL gate for lab, charts, richtext (#5197)
Ernest1dc3e5d63433
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex f18225d0ad..01a892c80b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -70,8 +70,14 @@ jobs:- name: Generate and test docsite datarun: pnpm -F @astryxdesign/docsite generate && pnpm -F @astryxdesign/docsite test- # Lightweight check — does the PR touch any core components?- # Gates pr-a11y to avoid unnecessary work+ # Lightweight check — does the PR touch any published components?+ # Gates pr-a11y and pr-rtl to avoid unnecessary work.+ #+ # Keep the roots and the exclude list in sync with analyze-pr.js: this job+ # only decides *whether* the downstream audits run, while analyze-pr.js+ # decides *which* components they audit. When the two disagree the audits+ # silently no-op — lab components were invisible to both audits until this+ # job learned about packages/lab/src.check-components:needs: [check-scope]if: github.event_name == 'pull_request' && needs.check-scope.outputs.docsite_only != 'true'@@ -101,7 +107,7 @@ jobs:echo "has_components=true" >> $GITHUB_OUTPUTexit 0fi- CHANGED=$(git diff --name-only origin/${{ github.base_ref }}...HEAD -- packages/core/src/ | grep -v -E '(hooks|theme|utils|__tests__)/' | head -1)+ 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# Run tests (parallel with build)@@ -137,6 +143,12 @@ jobs:if: needs.check-scope.outputs.docsite_only != 'true'run: node scripts/generate-token-docs.mjs --check+ # Fails when the lab readiness manifest claims a check the source tree+ # contradicts — the report is derived, never hand-maintained.+ - name: Check lab readiness manifest is current+ if: needs.check-scope.outputs.docsite_only != 'true'+ run: pnpm lab:readiness:check+- run: pnpm testif: needs.check-scope.outputs.docsite_only != 'true'diff --git a/.github/workflows/rtl-weekly.yml b/.github/workflows/rtl-weekly.ymlindex 1bf255ec0e..bf8afb3844 100644--- a/.github/workflows/rtl-weekly.yml+++ b/.github/workflows/rtl-weekly.yml@@ -56,8 +56,8 @@ jobs:- name: Install Playwright browserrun: npx playwright install chromium- # No --filter: with the flag absent the audit covers every core-* story- # (full-suite sweep). continue-on-error because the audit exits non-zero+ # No --filter: with the flag absent the audit covers every core-* and+ # lab-* story (full sweep). continue-on-error because the audit exits non-zero# on any finding — the summarize step below turns the report into the# real status.- name: Run full-suite RTL auditdiff --git a/.gitignore b/.gitignoreindex af7661aacc..7954fae9eb 100644--- a/.gitignore+++ b/.gitignore@@ -74,3 +74,11 @@ mise.toml# Generated i18n artifacts (rebuilt from en.json)packages/core/locales/pseudo.json++# Generated lab readiness report (rebuild with `pnpm lab:readiness`).+# Deliberately not committed: a checked-in snapshot goes stale the moment the+# source tree moves, and a stale score read as current is what this tooling+# exists to prevent. CI runs `pnpm lab:readiness:check` instead, which fails+# when the manifest's claims no longer match the repo.+apps/storybook/.lab-readiness/+apps/storybook/.storybook/lab-readiness/diff --git a/apps/storybook/rtl-audit/README.md b/apps/storybook/rtl-audit/README.mdindex 51734ac723..265ee1e130 100644--- a/apps/storybook/rtl-audit/README.md+++ b/apps/storybook/rtl-audit/README.md@@ -11,7 +11,7 @@ is the `pr-rtl` job — the RTL sibling of `pr-a11y`.## Two layers-### A. Auto-discovery — over every `core-*` story in scope+### A. Auto-discovery — over every `core-*` and `lab-*` story in scopeThe point of the audit is to auto-catch **new or changed** components, so theauto-discovery layer runs with **zero curated selectors**. There are two@@ -24,7 +24,7 @@ independent auto passes: **D1 (icon-mirror)** and **D5 (positional-mirror)**.### A.1 D1 icon-mirror-Directional-icon mirroring. For each core story it:+Directional-icon mirroring. For each audited story it:1. Loads the story LTR and RTL.2. Finds **directional** icons generically — classifying each icon SVG asdiff --git a/apps/storybook/rtl-audit/rtl-audit.mjs b/apps/storybook/rtl-audit/rtl-audit.mjsindex dbd6d60179..c06203c1c5 100644--- a/apps/storybook/rtl-audit/rtl-audit.mjs+++ b/apps/storybook/rtl-audit/rtl-audit.mjs@@ -6,9 +6,9 @@* @description RTL semantic audit. Grades component stories against the astryx* RTL contract by comparing their LTR vs RTL render in the SAME run* (relationship-based, no golden screenshots). Two layers:- * (A) AUTO-DISCOVERY — runs over EVERY `core-*` story with zero curated- * selectors, so a NEW component that ships without RTL handling is- * caught automatically. Two auto passes:+ * (A) AUTO-DISCOVERY — runs over EVERY `core-*` and `lab-*` story with zero+ * curated selectors, so a NEW component that ships without RTL handling+ * is caught automatically. Two auto passes:* - D1 (icon-mirror): directional glyphs must flip/swap under RTL.* - D5 (positional-mirror): an absolutely/fixed-positioned element* with a LOGICAL anchor (insetInlineStart/End) + an UNFLIPPED@@ -21,8 +21,8 @@* genuinely need hand-written selectors.* @input --storybook-dir <path> --output <file> [--targets <path>] [--filter <csv>]* [--auto-only] [--curated-only]- * @output JSON scorecard: auto-discovery D1 verdicts across all core stories +- * curated D2/D3/D4 results. Mirrors the pr-a11y accessibility-audit harness.+ * @output JSON scorecard: auto-discovery D1 verdicts across all audited stories+ * + curated D2/D3/D4 results. Mirrors the pr-a11y accessibility-audit harness.* @position internal test harness; run by the soft-gated `pr-rtl` CI job and* locally via `pnpm -F @astryxdesign/storybook rtl-audit`.*@@ -54,6 +54,13 @@ const TARGETS_PATH = getArg('targets') || path.join(HERE, 'targets.json');const FILTER = (getArg('filter') || '').split(',').map(s => s.trim().toLowerCase()).filter(Boolean);const AUTO_ONLY = hasFlag('auto-only');const CURATED_ONLY = hasFlag('curated-only');+// Story-id prefixes the auto-discovery layer sweeps. These mirror the+// publishable component packages in analyze-pr.js — a component the PR job can+// name in --filter must also be discoverable here, or the audit silently+// reports zero targets. Lab stories (`lab-*`) were excluded until this list+// existed, so no lab component had ever been RTL-audited.+const AUDITED_STORY_PREFIXES = ['core-', 'lab-'];+const AUDITED_STORY_PREFIX = new RegExp(`^(?:${AUDITED_STORY_PREFIXES.join('|')})`);// Worker pool size. Each worker owns its own Playwright page; stories are// independent, and the run is dominated by page-load latency rather than CPU.// Defaults to 1 (serial) so the per-PR job's behaviour is unchanged while the@@ -670,7 +677,8 @@ async function scoreCurated(page, port, t) {// ---------------------------------------------------------------------------function componentFromId(id) {// core-tabletree--default -> TableTree (best-effort display name)- const seg = id.replace(/^core-/, '').split('--')[0];+ // lab-listinput--tag-options -> listinput+ const seg = id.replace(AUDITED_STORY_PREFIX, '').split('--')[0];return seg;}@@ -709,12 +717,15 @@ async function mapPool(items, pages, fn) {process.exit(2);}- // ---- (A) auto-discovery over all core-* stories ----+ // ---- (A) auto-discovery over every audited-package story ----const autoResults = []; // D1 icon-mirrorconst pmResults = []; // D5 positional-mirrorif (!CURATED_ONLY) {const storyIds = Object.keys(entries).filter(- id => entries[id].type === 'story' && id.startsWith('core-') && !/--docs$/.test(id),+ id =>+ entries[id].type === 'story' &&+ AUDITED_STORY_PREFIX.test(id) &&+ !/--docs$/.test(id),);// D1 runs one representative story per component (extra stories add little// D1 signal). D5 (positional-mirror) runs over EVERY core story — a@@ -742,7 +753,7 @@ async function mapPool(items, pages, fn) {}})),);- // D5 positional-mirror over every core story.+ // D5 positional-mirror over every audited story.const pmTargets = storyIds.map(id => ({id, comp: componentFromId(id)})).filter(({comp}) => !FILTER.length || FILTER.includes(comp.toLowerCase()));diff --git a/internal/lab-readiness/audit.mjs b/internal/lab-readiness/audit.mjsnew file mode 100644index 0000000000..ce3d035bc5--- /dev/null+++ b/internal/lab-readiness/audit.mjs@@ -0,0 +1,385 @@+#!/usr/bin/env node+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file audit.mjs+ * @description Scores every lab graduation candidate against the 30-check+ * rubric and writes the readiness report the Storybook panel reads. Merges+ * what the repo can prove (`automated.mjs`) over what the manifest claims+ * (`manifest.mjs`), so a stale claim is corrected by the source tree rather+ * than trusted.+ * @input --output <file> --registry <file> --candidate <id> --check --json+ * @output Readiness report JSON (schema v1) and the derived Storybook+ * registry. Exits 1 in `--check` mode when a manifest claim is contradicted.+ * @position Run locally via `pnpm lab:readiness`, and in CI to keep the+ * committed report honest. Replaces the ad-hoc report that was generated+ * from an unlanded working tree and could never be reproduced.+ */++import fs from 'node:fs';+import path from 'node:path';+import {fileURLToPath} from 'node:url';+import {execFileSync} from 'node:child_process';++import {+ CHECK_CATALOG,+ CHECK_KEYS,+ HUMAN_REVIEW_KEYS,+ PASSING_STATE,+ REPORT_KIND,+ SCHEMA_VERSION,+ STAGE_DEFINITIONS,+ getCheck,+} from './catalog.mjs';+import {deriveChecks} from './automated.mjs';+import {CANDIDATES} from './manifest.mjs';++const HERE = path.dirname(fileURLToPath(import.meta.url));+const REPO_ROOT = path.resolve(HERE, '..', '..');++const DEFAULT_OUTPUT = 'apps/storybook/.lab-readiness/latest.json';+const DEFAULT_REGISTRY =+ 'apps/storybook/.storybook/lab-readiness/generated-registry.json';++const args = process.argv.slice(2);+const getArg = name => {+ const i = args.indexOf(`--${name}`);+ return i !== -1 ? args[i + 1] : null;+};+const hasFlag = name => args.includes(`--${name}`);++/** Current commit and whether the tree is dirty, for report provenance. */+function gitProvenance(repoRoot) {+ const run = cmd => {+ try {+ return execFileSync('git', cmd, {+ cwd: repoRoot,+ encoding: 'utf8',+ // A scratch dir is not a repo; that is expected, not worth the noise.+ stdio: ['ignore', 'pipe', 'ignore'],+ }).trim();+ } catch {+ return null;+ }+ };+ return {+ sourceSha: run(['rev-parse', 'HEAD']),+ dirty: run(['status', '--porcelain']) !== '',+ };+}++/**+ * Resolve one check's final state.+ *+ * Precedence is deliberate: a derived result always beats a declared one, and+ * an evidence-free `passed` claim is demoted. Human-review checks are never+ * derivable, so they pass through as declared — but the manifest cannot mark+ * them `passed` without evidence either.+ */+function resolveCheck(key, declared, derived) {+ const catalog = getCheck(key);++ if (derived && !catalog.humanReview) {+ const contradicts =+ declared?.state === PASSING_STATE && derived.state !== PASSING_STATE;+ return {+ state: derived.state,+ note: derived.note,+ evidence: declared?.evidence ?? [],+ derivedEvidence: derived.evidence,+ provenance: 'derived',+ contradictsManifest: contradicts,+ };+ }++ const state = declared?.state ?? 'not_started';+ const evidence = declared?.evidence ?? [];+ // A passing claim with nothing to open is not a claim, it is an assertion.+ const demoted = state === PASSING_STATE && evidence.length === 0;+ return {+ state: demoted ? 'in_progress' : state,+ note: demoted+ ? `${declared?.note ? `${declared.note} ` : ''}Demoted: a passing claim requires linked evidence.`+ : (declared?.note ?? 'No verified evidence has been linked.'),+ evidence,+ derivedEvidence: [],+ provenance: 'declared',+ contradictsManifest: false,+ };+}++/** Roll per-check states up into stage and section tallies. */+function scoreStages(checks) {+ const byKey = new Map(checks.map(c => [c.key, c]));+ const stageResults = {};++ for (const stage of STAGE_DEFINITIONS) {+ const stageChecks = CHECK_CATALOG.filter(c => c.stageKey === stage.key);+ const sections = {};++ for (const check of stageChecks) {+ const section = (sections[check.sectionKey] ??= {+ state: 'not_started',+ passedChecks: 0,+ applicableChecks: 0,+ totalChecks: 0,+ });+ section.totalChecks += 1;+ section.applicableChecks += 1;+ if (byKey.get(check.key)?.state === PASSING_STATE) {+ section.passedChecks += 1;+ }+ }++ for (const section of Object.values(sections)) {+ section.state =+ section.passedChecks === section.applicableChecks+ ? 'passed'+ : section.passedChecks === 0+ ? 'not_started'+ : 'in_progress';+ }++ const passedChecks = Object.values(sections).reduce(+ (n, s) => n + s.passedChecks,+ 0,+ );+ const applicableChecks = Object.values(sections).reduce(+ (n, s) => n + s.applicableChecks,+ 0,+ );+ // A stage with some but not all checks passing is in progress; a stage+ // where a section has started is in progress even if none passed yet.+ const anyStarted = stageChecks.some(+ c => byKey.get(c.key)?.state === 'in_progress',+ );+ stageResults[stage.key] = {+ state:+ passedChecks === applicableChecks+ ? 'passed'+ : passedChecks > 0 || anyStarted+ ? 'in_progress'+ : 'not_started',+ passedChecks,+ applicableChecks,+ totalChecks: applicableChecks,+ sections,+ };+ }++ return stageResults;+}++/** Score one candidate into its full check list, stage rollup, and summary. */+export function auditCandidate(repoRoot, candidate) {+ const derived = deriveChecks(repoRoot, candidate);++ const checks = CHECK_KEYS.map(key => {+ const catalog = getCheck(key);+ const resolved = resolveCheck(key, candidate.declared?.[key], derived[key]);+ return {...catalog, ...resolved, key};+ });++ const stageResults = scoreStages(checks);+ const passed = checks.filter(c => c.state === PASSING_STATE).length;+ const contradictions = checks.filter(c => c.contradictsManifest);+ const blockingStage = STAGE_DEFINITIONS.find(+ s => stageResults[s.key].state !== 'passed',+ );++ return {+ id: candidate.id,+ candidateId: candidate.id,+ displayName: candidate.displayName,+ sourceDir: candidate.sourceDir,+ targetPackage: candidate.targetPackage,+ trackingIssue: candidate.trackingIssue,+ voteIssue: candidate.voteIssue,+ storybookStoryId: candidate.storybookStoryId,+ publicExports: candidate.publicExports,+ summary: candidate.summary,+ passedChecks: passed,+ totalChecks: CHECK_KEYS.length,+ isGraduationReady: passed === CHECK_KEYS.length,+ summaryText: buildSummary(candidate, passed, blockingStage, contradictions),+ contradictions: contradictions.map(c => ({key: c.key, note: c.note})),+ stageResults,+ checks,+ };+}++function buildSummary(candidate, passed, blockingStage, contradictions) {+ const total = CHECK_KEYS.length;+ if (passed === total) {+ return `${candidate.displayName} passes all ${total} checks and is ready to graduate into ${candidate.targetPackage}.`;+ }+ const parts = [+ `${candidate.displayName} passes ${passed} of ${total} checks; the ${blockingStage.label} stage is the first that is not complete.`,+ ];+ if (contradictions.length > 0) {+ parts.push(+ `${contradictions.length} manifest claim${contradictions.length === 1 ? '' : 's'} contradicted by the source tree: ${contradictions.map(c => c.key).join(', ')}.`,+ );+ }+ return parts.join(' ');+}++/** Build the full report envelope. */+export function buildReport(repoRoot, candidates) {+ const startedAt = new Date().toISOString();+ const {sourceSha, dirty} = gitProvenance(repoRoot);+ const audited = candidates.map(c => auditCandidate(repoRoot, c));+ const finishedAt = new Date().toISOString();++ return {+ schemaVersion: SCHEMA_VERSION,+ kind: REPORT_KIND,+ auditedAt: finishedAt,+ run: {+ id: `lab-${finishedAt.replace(/[-:.]/g, '')}`,+ status: 'completed',+ startedAt,+ finishedAt,+ sourceSha,+ dirty,+ candidateIds: audited.map(c => c.id),+ completedCount: audited.length,+ failedCount: 0,+ },+ stageDefinitions: STAGE_DEFINITIONS,+ checkCatalog: CHECK_CATALOG,+ humanReviewKeys: HUMAN_REVIEW_KEYS,+ candidates: audited,+ };+}++/** The slimmer shape the Storybook readiness panel consumes. */+export function buildRegistry(report) {+ return {+ schemaVersion: report.schemaVersion,+ auditedAt: report.auditedAt.slice(0, 10),+ stageDefinitions: report.stageDefinitions,+ components: report.candidates.map(c => ({+ id: c.id,+ displayName: c.displayName,+ sourceDir: c.sourceDir,+ targetPackage: c.targetPackage,+ trackingIssue: c.trackingIssue,+ voteIssue: c.voteIssue,+ storybookStoryId: c.storybookStoryId,+ summary: c.summary,+ auditedAt: report.auditedAt.slice(0, 10),+ passedChecks: c.passedChecks,+ totalChecks: c.totalChecks,+ isGraduationReady: c.isGraduationReady,+ stageResults: c.stageResults,+ checks: c.checks.map(check => ({+ key: check.key,+ label: check.label,+ state: check.state,+ note: check.note,+ evidence: check.evidence,+ provenance: check.provenance,+ })),+ })),+ };+}++function writeJSON(repoRoot, relPath, value) {+ const abs = path.join(repoRoot, relPath);+ fs.mkdirSync(path.dirname(abs), {recursive: true});+ fs.writeFileSync(abs, `${JSON.stringify(value, null, 2)}\n`);+ return abs;+}++function main() {+ const only = getArg('candidate');+ const candidates = only+ ? CANDIDATES.filter(c => c.id === only)+ : CANDIDATES;++ if (candidates.length === 0) {+ console.error(+ `No candidate matches "${only}". Known: ${CANDIDATES.map(c => c.id).join(', ')}`,+ );+ process.exit(1);+ }++ const report = buildReport(REPO_ROOT, candidates);++ if (hasFlag('json')) {+ console.log(JSON.stringify(report, null, 2));+ return;+ }++ for (const candidate of report.candidates) {+ const bar = `${candidate.passedChecks}/${candidate.totalChecks}`;+ console.log(`\n${candidate.displayName} ${bar}`);+ for (const stage of report.stageDefinitions) {+ const s = candidate.stageResults[stage.key];+ console.log(+ ` ${stage.label.padEnd(16)} ${String(s.passedChecks).padStart(2)}/${s.applicableChecks} ${s.state}`,+ );+ }+ const failing = candidate.checks.filter(c => c.state !== PASSING_STATE);+ if (failing.length > 0) {+ console.log(' open:');+ for (const check of failing) {+ console.log(` - ${check.key}: ${check.note}`);+ }+ }+ }++ if (hasFlag('check')) {+ const contradicted = report.candidates.flatMap(c =>+ c.contradictions.map(x => `${c.id}/${x.key}`),+ );+ // Also detect positive staleness: a derived check now passes but the+ // manifest still claims not_started/in_progress — the manifest is behind.+ const stale = report.candidates.flatMap(c => {+ const candidate = CANDIDATES.find(cand => cand.id === c.id);+ if (!candidate) return [];+ return c.checks+ .filter(+ ch =>+ ch.provenance === 'derived' &&+ ch.state === PASSING_STATE,+ )+ .filter(ch => {+ const declared = candidate.declared?.[ch.key];+ return (+ declared != null &&+ declared.state != null &&+ declared.state !== PASSING_STATE+ );+ })+ .map(ch => `${c.id}/${ch.key}`);+ });+ const issues = [...contradicted, ...stale];+ if (issues.length > 0) {+ console.error(+ `\nManifest is stale — these checks disagree with the source tree:\n ${issues.join('\n ')}`,+ );+ process.exit(1);+ }+ console.log('\nManifest agrees with the source tree.');+ return;+ }++ const reportPath = writeJSON(+ REPO_ROOT,+ getArg('output') || DEFAULT_OUTPUT,+ report,+ );+ const registryPath = writeJSON(+ REPO_ROOT,+ getArg('registry') || DEFAULT_REGISTRY,+ buildRegistry(report),+ );+ console.log(`\nWrote ${path.relative(REPO_ROOT, reportPath)}`);+ console.log(`Wrote ${path.relative(REPO_ROOT, registryPath)}`);+}++if (process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) {+ main();+}diff --git a/internal/lab-readiness/audit.test.mjs b/internal/lab-readiness/audit.test.mjsnew file mode 100644index 0000000000..96d9c1326f--- /dev/null+++ b/internal/lab-readiness/audit.test.mjs@@ -0,0 +1,313 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file audit.test.mjs+ * Pins the two properties that make the readiness report trustworthy:+ * the source tree overrides the manifest (a stale claim cannot inflate a+ * score), and a component invisible to the CI accessibility or RTL gates+ * cannot pass the checks that depend on those gates. The second property is+ * the regression guard for the gap that let every lab component sit outside+ * both audits while still being scored against them.+ */++import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import {describe, it, expect, beforeAll, afterAll} from 'vitest';++import {CHECK_KEYS, HUMAN_REVIEW_KEYS} from './catalog.mjs';+import {deriveChecks, _internal} from './automated.mjs';+import {auditCandidate, buildRegistry, buildReport} from './audit.mjs';++/** A candidate whose files we can write into a scratch repo. */+const candidate = {+ id: 'widget',+ displayName: 'Widget',+ sourceDir: 'Widget',+ targetPackage: '@astryxdesign/core',+ trackingIssue: 1,+ voteIssue: 1,+ storyTitle: 'Lab/Widget',+ storybookStoryId: 'lab-widget--default',+ publicExports: ['Widget'],+ stateProps: ['isDisabled'],+ summary: 'A widget.',+ declared: {},+};++let root;++/** Write a fully passing scratch repo for `candidate`. */+function scaffold(overrides = {}) {+ const files = {+ '.github/workflows/ci.yml':+ 'CHANGED=$(git diff --name-only origin/main...HEAD -- packages/core/src/ packages/lab/src/ | grep -v x)\n',+ 'apps/storybook/rtl-audit/rtl-audit.mjs':+ "const AUDITED_STORY_PREFIXES = ['core-', 'lab-'];\n",+ 'packages/lab/package.json': JSON.stringify({+ name: '@astryxdesign/lab',+ dependencies: {'d3-scale': '^4.0.2'},+ peerDependencies: {react: '>=19.0.0'},+ }),+ 'packages/lab/src/index.ts': "export {Widget} from './Widget';\n",+ 'packages/lab/src/Widget/index.ts':+ "export {Widget} from './Widget';\nexport type {WidgetProps} from './Widget';\n",+ 'packages/lab/src/Widget/Widget.tsx':+ "import {Text} from '@astryxdesign/core/Text';\nexport function Widget() { return <Text />; }\n",+ 'packages/lab/src/Widget/Widget.doc.mjs':+ 'export const docs = {props: [], usage: {}, examples: [], theming: {targets: []}};\n',+ 'packages/lab/src/Widget/Widget.test.tsx':+ "it('renders', () => {});\nit('supports isDisabled', () => {});\nit('handles Enter', () => {});\n",+ 'apps/storybook/stories/Widget.stories.tsx':+ "const meta = {title: 'Lab/Widget'};\n" ++ 'export const Default: Story = {};\n' ++ 'export const Disabled: Story = {isDisabled: true};\n' ++ 'export const Loading: Story = {};\n' ++ 'export const Empty: Story = {};\n' ++ 'export const ThemeMatrix: Story = {};\n',+ ...overrides,+ };+ for (const [rel, contents] of Object.entries(files)) {+ if (contents === null) continue;+ const abs = path.join(root, rel);+ fs.mkdirSync(path.dirname(abs), {recursive: true});+ fs.writeFileSync(abs, contents);+ }+}++beforeAll(() => {+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'lab-readiness-'));+});+afterAll(() => {+ fs.rmSync(root, {recursive: true, force: true});+});++describe('automated derivation', () => {+ it('passes the derivable checks for a fully wired component', () => {+ scaffold();+ const derived = deriveChecks(root, candidate);+ const failing = Object.entries(derived)+ .filter(([, v]) => v.state !== 'passed')+ .map(([k, v]) => `${k}: ${v.note}`);+ expect(failing).toEqual([]);+ });++ it('fails the accessibility check when ci.yml stops watching lab', () => {+ scaffold({+ '.github/workflows/ci.yml':+ 'CHANGED=$(git diff --name-only origin/main...HEAD -- packages/core/src/ | grep -v x)\n',+ });+ const derived = deriveChecks(root, candidate);+ expect(derived.accessibilityContracts.state).not.toBe('passed');+ expect(derived.accessibilityContracts.note).toMatch(/excludes packages\/lab/);+ });++ it('fails the keyboard check when the RTL sweep stops covering lab', () => {+ scaffold({+ 'apps/storybook/rtl-audit/rtl-audit.mjs':+ "const AUDITED_STORY_PREFIXES = ['core-'];\n",+ });+ const derived = deriveChecks(root, candidate);+ expect(derived.keyboardAccessibility.state).not.toBe('passed');+ expect(derived.keyboardAccessibility.note).toMatch(/RTL/);+ });++ it('fails the accessibility check when no story title resolves to the component name', () => {+ scaffold({+ 'apps/storybook/stories/Widget.stories.tsx':+ "const meta = {title: 'Lab/WidgetSelector'};\nexport const Default: Story = {};\n",+ });+ const derived = deriveChecks(root, candidate);+ expect(derived.accessibilityContracts.state).not.toBe('passed');+ expect(derived.accessibilityContracts.note).toMatch(/resolves to the analyzer/);+ });++ it('requires an advertised state to appear in both a story and a test', () => {+ scaffold({+ 'packages/lab/src/Widget/Widget.test.tsx':+ "it('renders', () => {});\nit('handles Enter', () => {});\n",+ });+ const derived = deriveChecks(root, candidate);+ expect(derived.stateCoverage.state).not.toBe('passed');+ expect(derived.stateCoverage.note).toMatch(/isDisabled.*no test/);+ });++ it('accepts a locally defined SVG glyph', () => {+ // Core defines glyphs this way in Avatar, Thumbnail, and Indicator, so a+ // raw <svg> is idiomatic rather than a finding.+ scaffold({+ 'packages/lab/src/Widget/Widget.tsx':+ "import {Text} from '@astryxdesign/core/Text';\n" ++ 'function Glyph() { return <svg><circle /></svg>; }\n' ++ 'export function Widget() { return <Text><Glyph /></Text>; }\n',+ });+ const derived = deriveChecks(root, candidate);+ expect(derived.systemIntegration.state).toBe('passed');+ expect(derived.reuseNaming.state).toBe('passed');+ });++ it('flags an icon import from an undeclared package', () => {+ scaffold({+ 'packages/lab/src/Widget/Widget.tsx':+ "import {Text} from '@astryxdesign/core/Text';\n" ++ "import {GripVertical} from 'lucide-react';\n" ++ 'export function Widget() { return <Text><GripVertical /></Text>; }\n',+ });+ const derived = deriveChecks(root, candidate);+ expect(derived.systemIntegration.state).not.toBe('passed');+ expect(derived.systemIntegration.note).toMatch(/lucide-react/);+ expect(derived.reuseNaming.note).toMatch(/lucide-react/);+ });++ it('does not flag a package the lab manifest declares', () => {+ scaffold({+ 'packages/lab/src/Widget/Widget.tsx':+ "import {Text} from '@astryxdesign/core/Text';\n" ++ "import {scaleLinear} from 'd3-scale';\n" ++ 'export function Widget() { return <Text>{String(scaleLinear)}</Text>; }\n',+ });+ expect(deriveChecks(root, candidate).systemIntegration.state).toBe('passed');+ });++ it('accepts inline type modifiers in the barrel', () => {+ scaffold({+ 'packages/lab/src/Widget/index.ts':+ "export {Widget, type WidgetProps} from './Widget';\n",+ });+ expect(deriveChecks(root, candidate).structureTypes.state).toBe('passed');+ });+});++describe('manifest reconciliation', () => {+ it('lets the source tree override a passing manifest claim', () => {+ scaffold({+ 'packages/lab/src/Widget/Widget.doc.mjs':+ 'export const docs = {props: [], usage: {}, examples: []};\n',+ });+ const result = auditCandidate(root, {+ ...candidate,+ declared: {+ tokensTheming: {+ state: 'passed',+ note: 'claimed',+ evidence: [{label: 'PR #1', url: 'https://example.com'}],+ },+ },+ });+ const check = result.checks.find(c => c.key === 'tokensTheming');+ expect(check.state).toBe('in_progress');+ expect(check.contradictsManifest).toBe(true);+ expect(result.contradictions.map(c => c.key)).toContain('tokensTheming');+ });++ it('demotes a passing claim that links no evidence', () => {+ scaffold();+ const result = auditCandidate(root, {+ ...candidate,+ declared: {visualQuality: {state: 'passed', note: 'looks fine'}},+ });+ const check = result.checks.find(c => c.key === 'visualQuality');+ expect(check.state).toBe('in_progress');+ expect(check.note).toMatch(/requires linked evidence/);+ });++ it('keeps a human-review claim that does link evidence', () => {+ scaffold();+ const result = auditCandidate(root, {+ ...candidate,+ declared: {+ visualQuality: {+ state: 'passed',+ note: 'reviewed',+ evidence: [{label: 'PR #2', url: 'https://example.com'}],+ },+ },+ });+ expect(result.checks.find(c => c.key === 'visualQuality').state).toBe(+ 'passed',+ );+ });++ it('never derives a human-review check from the source tree', () => {+ scaffold();+ const derived = deriveChecks(root, candidate);+ for (const key of HUMAN_REVIEW_KEYS) {+ expect(derived[key]).toBeUndefined();+ }+ });+});++describe('report shape', () => {+ it('scores every catalog check exactly once', () => {+ scaffold();+ const result = auditCandidate(root, candidate);+ expect(result.checks.map(c => c.key)).toEqual(CHECK_KEYS);+ expect(result.totalChecks).toBe(CHECK_KEYS.length);+ });++ it('reports graduation readiness only when every check passes', () => {+ scaffold();+ const result = auditCandidate(root, candidate);+ expect(result.isGraduationReady).toBe(false);+ expect(result.passedChecks).toBeLessThan(CHECK_KEYS.length);++ // A perfect source tree is not enough: the checks that only a manifest can+ // assert (research, spec, review, merge, and human sign-off) must each+ // carry evidence too.+ const derivable = new Set(Object.keys(deriveChecks(root, candidate)));+ const declaredOnly = CHECK_KEYS.filter(key => !derivable.has(key));+ expect(declaredOnly).toEqual(expect.arrayContaining(HUMAN_REVIEW_KEYS));++ const complete = auditCandidate(root, {+ ...candidate,+ declared: Object.fromEntries(+ declaredOnly.map(key => [+ key,+ {+ state: 'passed',+ note: 'evidenced',+ evidence: [{label: 'PR #3', url: 'https://example.com'}],+ },+ ]),+ ),+ });+ expect(complete.isGraduationReady).toBe(true);+ expect(complete.passedChecks).toBe(CHECK_KEYS.length);+ });++ it('emits a registry the Storybook panel can read', () => {+ scaffold();+ const report = buildReport(root, [candidate]);+ const registry = buildRegistry(report);+ expect(registry.components).toHaveLength(1);+ const [component] = registry.components;+ expect(component.id).toBe('widget');+ expect(Object.keys(component.stageResults)).toEqual([+ 'research',+ 'spec',+ 'build',+ 'hardenChecks',+ 'hardenReview',+ ]);+ expect(component.checks).toHaveLength(CHECK_KEYS.length);+ });+});++describe('CI wiring parsers', () => {+ it('reads the component roots out of the real ci.yml', () => {+ const repoRoot = path.resolve(import.meta.dirname, '..', '..');+ const roots = _internal.ciComponentRoots(repoRoot);+ expect(roots).toContain('packages/core/src/');+ expect(roots).toContain('packages/lab/src/');+ });++ it('reads the audited story prefixes out of the real rtl-audit', () => {+ const repoRoot = path.resolve(import.meta.dirname, '..', '..');+ expect(_internal.rtlAuditedPrefixes(repoRoot)).toEqual(['core-', 'lab-']);+ });++ it('derives the component name pr-a11y matches against', () => {+ expect(_internal.a11yComponentFromTitle('Lab/ListInput')).toBe('listinput');+ expect(_internal.a11yComponentFromTitle('Core/XDSButton')).toBe('button');+ });+});diff --git a/internal/lab-readiness/automated.mjs b/internal/lab-readiness/automated.mjsnew file mode 100644index 0000000000..33cf90ac34--- /dev/null+++ b/internal/lab-readiness/automated.mjs@@ -0,0 +1,545 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file automated.mjs+ * @description Derives the readiness checks that can be proven from the repo+ * itself — source layout, exports, stories, tests, docs, token usage, and+ * whether the component is actually reachable by the CI accessibility and+ * RTL gates. Everything that needs a human, an RFC, or a CI run is declared+ * in `manifest.mjs` instead.+ * @input repoRoot + a candidate descriptor from `manifest.mjs`+ * @output `Record<checkKey, {state, note, evidence[]}>` for the derivable subset+ * @position Called by `audit.mjs`, which merges these results over the+ * manifest's declared states. A derived result always wins over a declared+ * one: the point of the tooling is that the repo can contradict the claim.+ *+ * Every derivation is deliberately shallow — regex and file existence, no AST.+ * A check here answers "is the evidence present and wired up", never "is it+ * good". Quality judgements belong to the human review stage.+ */++import fs from 'node:fs';+import path from 'node:path';++const LAB_SRC = 'packages/lab/src';+const STORIES_DIR = 'apps/storybook/stories';+const CI_WORKFLOW = '.github/workflows/ci.yml';+const RTL_AUDIT = 'apps/storybook/rtl-audit/rtl-audit.mjs';++/** Read a repo-relative file, or null when it does not exist. */+function read(repoRoot, relPath) {+ try {+ return fs.readFileSync(path.join(repoRoot, relPath), 'utf8');+ } catch {+ return null;+ }+}++function exists(repoRoot, relPath) {+ return fs.existsSync(path.join(repoRoot, relPath));+}++/** A single piece of machine-derived evidence. */+function ev(description, filePath, line) {+ return {description, path: filePath ?? null, line: line ?? null, url: null};+}++/** Find the 1-based line number of the first regex match, or null. */+function lineOf(content, pattern) {+ if (!content) return null;+ const lines = content.split('\n');+ for (let i = 0; i < lines.length; i++) {+ if (pattern.test(lines[i])) return i + 1;+ }+ return null;+}++/**+ * Resolve every path a candidate owns. `sourceDir` is the directory name under+ * `packages/lab/src`, which is also how analyze-pr.js names the component.+ */+function paths(candidate) {+ const dir = `${LAB_SRC}/${candidate.sourceDir}`;+ return {+ dir,+ source: `${dir}/${candidate.sourceDir}.tsx`,+ barrel: `${dir}/index.ts`,+ doc: `${dir}/${candidate.sourceDir}.doc.mjs`,+ test: `${dir}/${candidate.sourceDir}.test.tsx`,+ stories: `${STORIES_DIR}/${candidate.sourceDir}.stories.tsx`,+ };+}++/** Named story exports in a stories file. */+function storyExports(content) {+ if (!content) return [];+ return [...content.matchAll(/^export const (\w+):\s*Story\b/gm)].map(+ m => m[1],+ );+}++/** Every `title: 'X/Y'` in a stories file. */+function storyTitles(content) {+ if (!content) return [];+ return [...content.matchAll(/title:\s*['"]([^'"]+)['"]/g)].map(m => m[1]);+}++/**+ * The component name `pr-a11y` derives from a story title, mirroring+ * accessibility-audit.js: second title segment, `XDS` stripped, lowercased.+ */+function a11yComponentFromTitle(title) {+ const parts = title.split('/');+ const componentPart = parts.length > 1 ? parts[1] : parts[0];+ return componentPart.replace(/^XDS/i, '').toLowerCase();+}++/** Roots the ci.yml `check-components` gate diffs against. */+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);+}++/** Story-id prefixes the RTL auto-discovery sweep covers. */+function rtlAuditedPrefixes(repoRoot) {+ const rtl = read(repoRoot, RTL_AUDIT);+ if (!rtl) return [];+ const match = rtl.match(/AUDITED_STORY_PREFIXES\s*=\s*\[([^\]]+)\]/);+ if (!match) return [];+ return [...match[1].matchAll(/['"]([^'"]+)['"]/g)].map(m => m[1]);+}++/** Pass/fail helper: `passed` when every requirement holds, else `in_progress`. */+function verdict(failures) {+ return failures.length === 0 ? 'passed' : 'in_progress';+}++/** Bare package specifiers imported by a source file. */+function importedPackages(source) {+ const specifiers = [...source.matchAll(/from\s+['"]([^'"]+)['"]/g)].map(+ m => m[1],+ );+ return [+ ...new Set(+ specifiers+ .filter(s => !s.startsWith('.') && !s.startsWith('node:'))+ // Scoped packages keep two segments, everything else keeps one.+ .map(s => (s.startsWith('@') ? s.split('/').slice(0, 2).join('/') : s.split('/')[0])),+ ),+ ];+}++/**+ * Packages a lab component imports that the lab package does not declare.+ *+ * A component that reaches for an undeclared package still builds in the+ * monorepo — the dependency is hoisted — but breaks for anyone installing+ * `@astryxdesign/lab` on its own. `react` and the workspace's own packages are+ * always available, so they are never reported.+ */+function undeclaredDependencies(repoRoot, source) {+ let manifest;+ try {+ manifest = JSON.parse(read(repoRoot, 'packages/lab/package.json') ?? '');+ } catch {+ return [];+ }+ const declared = new Set([+ ...Object.keys(manifest.dependencies ?? {}),+ ...Object.keys(manifest.peerDependencies ?? {}),+ ...Object.keys(manifest.devDependencies ?? {}),+ 'react',+ 'react-dom',+ ]);+ return importedPackages(source).filter(+ name => !declared.has(name) && !name.startsWith('@astryxdesign/'),+ );+}++/**+ * Derive every provable check for one candidate.+ *+ * @param {string} repoRoot+ * @param {object} candidate+ * @returns {Record<string, {state: string, note: string, evidence: object[]}>}+ */+export function deriveChecks(repoRoot, candidate) {+ const p = paths(candidate);+ const source = read(repoRoot, p.source);+ const barrel = read(repoRoot, p.barrel);+ const doc = read(repoRoot, p.doc);+ const test = read(repoRoot, p.test);+ const stories = read(repoRoot, p.stories);+ const labBarrel = read(repoRoot, `${LAB_SRC}/index.ts`);++ const results = {};+ const add = (key, state, note, evidence = []) => {+ results[key] = {state, note, evidence};+ };++ /* ---------------------------------------------------------- build ---- */++ {+ const failures = [];+ const evidence = [];+ if (!source) {+ failures.push('source file missing');+ evidence.push(ev('Expected component source is absent.', p.source));+ } else {+ evidence.push(+ ev('Component source.', p.source, lineOf(source, /^export /m)),+ );+ }+ const missingExports = candidate.publicExports.filter(+ name => !barrel || !new RegExp(`\\b${name}\\b`).test(barrel),+ );+ if (missingExports.length > 0) {+ failures.push(`barrel omits ${missingExports.join(', ')}`);+ evidence.push(ev('Component barrel.', p.barrel));+ }+ add(+ 'implementation',+ verdict(failures),+ failures.length === 0+ ? 'Source is present and every declared public export is re-exported.'+ : `Contract incomplete: ${failures.join('; ')}.`,+ evidence,+ );+ }++ {+ const failures = [];+ const evidence = [];+ if (source) {+ if (!/@astryxdesign\/core\//.test(source)) {+ failures.push('composes no core primitive');+ }+ const portalLine = lineOf(source, /createPortal/);+ if (portalLine) {+ failures.push('portals directly instead of composing Layer');+ evidence.push(+ ev(+ 'Direct createPortal use; the shared Layer behavior is the supported path.',+ p.source,+ portalLine,+ ),+ );+ }+ const ariaLiveLine = lineOf(source, /aria-live/);+ if (ariaLiveLine && !/useAnnounce/.test(source)) {+ failures.push('hand-rolls a live region instead of useAnnounce');+ evidence.push(+ ev('Ad hoc aria-live node.', p.source, ariaLiveLine),+ );+ }+ const undeclared = undeclaredDependencies(repoRoot, source);+ if (undeclared.length > 0) {+ failures.push(`imports undeclared package(s): ${undeclared.join(', ')}`);+ evidence.push(+ ev(+ `Not listed in the lab package's dependencies or peerDependencies, so a consumer installing @astryxdesign/lab would not get ${undeclared.join(', ')}.`,+ p.source,+ lineOf(source, new RegExp(`from '${undeclared[0]}`)),+ ),+ );+ }+ }+ add(+ 'systemIntegration',+ verdict(failures),+ failures.length === 0+ ? 'Composes core primitives and shared behaviors rather than re-implementing them.'+ : `Bypasses shared primitives: ${failures.join('; ')}.`,+ evidence,+ );+ }++ {+ const names = storyExports(stories);+ const titles = storyTitles(stories);+ const failures = [];+ if (names.length === 0) failures.push('no exported stories');+ if (!titles.includes(candidate.storyTitle)) {+ failures.push(`no story titled ${candidate.storyTitle}`);+ }+ add(+ 'stories',+ verdict(failures),+ failures.length === 0+ ? `${names.length} stories under ${candidate.storyTitle}.`+ : `Story set incomplete: ${failures.join('; ')}.`,+ [ev(`Exported stories: ${names.join(', ') || 'none'}.`, p.stories)],+ );+ }++ {+ const count = test ? (test.match(/\bit\(/g) || []).length : 0;+ add(+ 'tests',+ count > 0 ? 'passed' : 'not_started',+ count > 0+ ? `${count} focused tests colocated with the source.`+ : 'No colocated test file.',+ [ev(`${count} test cases.`, p.test)],+ );+ }++ {+ const failures = [];+ if (!doc) failures.push('no .doc.mjs');+ else {+ if (!/\bprops:\s*\[/.test(doc)) failures.push('no props inventory');+ if (!/\busage:\s*\{/.test(doc)) failures.push('no usage guidance');+ if (!/\bexamples:\s*\[/.test(doc)) failures.push('no examples');+ }+ add(+ 'documentation',+ verdict(failures),+ failures.length === 0+ ? 'Component doc declares props, usage, and examples.'+ : `Documentation incomplete: ${failures.join('; ')}.`,+ [ev('Component documentation.', p.doc)],+ );+ }++ /* --------------------------------------------------- harden: audit ---- */++ {+ const failures = [];+ const evidence = [];+ if (!doc || !/\btheming:\s*\{/.test(doc)) {+ failures.push('no theming.targets inventory');+ evidence.push(+ ev(+ 'The theme builder derives a component\u2019s known visual props from its doc; without a theming block it is invisible to `astryx theme build`.',+ p.doc,+ ),+ );+ }+ if (source) {+ const hexLine = lineOf(source, /:\s*'#[0-9a-fA-F]{3,8}'/);+ if (hexLine) {+ failures.push('hardcoded hex color');+ evidence.push(ev('Raw hex instead of a color token.', p.source, hexLine));+ }+ }+ add(+ 'tokensTheming',+ verdict(failures),+ failures.length === 0+ ? 'Theme targets are declared and colors come from tokens.'+ : `Theming incomplete: ${failures.join('; ')}.`,+ evidence,+ );+ }++ {+ const failures = [];+ const badNames = candidate.publicExports.filter(+ name => !/^[A-Z]/.test(name) && !name.endsWith('Vars'),+ );+ if (badNames.length > 0) {+ failures.push(`non-conventional export names: ${badNames.join(', ')}`);+ }+ // A locally-defined SVG glyph is idiomatic here — core does the same in+ // Avatar, Thumbnail, and Indicator — so a raw <svg> is not itself a+ // finding. What matters is that the glyph does not arrive from an+ // undeclared package, which systemIntegration already asserts.+ if (source && /from ['"]lucide-react['"]/.test(source)) {+ failures.push('imports icons from lucide-react rather than defining them locally');+ }+ add(+ 'reuseNaming',+ verdict(failures),+ failures.length === 0+ ? 'Public names follow convention and shared primitives are reused.'+ : `Reuse or naming issue: ${failures.join('; ')}.`,+ [],+ );+ }++ {+ const failures = [];+ if (!barrel) failures.push('no index.ts barrel');+ // Both spellings are conventional: a dedicated `export type {...}` block,+ // or inline `type` modifiers inside a value export block.+ else if (!/export type\s*\{|\{[^}]*\btype\s+\w/s.test(barrel)) {+ failures.push('barrel exports no public types');+ }+ add(+ 'structureTypes',+ verdict(failures),+ failures.length === 0+ ? 'Conventional barrel exporting both the component and its public types.'+ : `Structure incomplete: ${failures.join('; ')}.`,+ [ev('Component barrel.', p.barrel)],+ );+ }++ {+ // The gate this component must clear before axe ever sees it. Both halves+ // have silently excluded lab components before, so both are asserted.+ const failures = [];+ const evidence = [];+ const roots = ciComponentRoots(repoRoot);+ if (!roots.some(root => root.startsWith(`${LAB_SRC}`))) {+ failures.push('ci.yml change detection excludes packages/lab/src');+ evidence.push(+ ev(+ `check-components diffs only ${roots.join(' ') || '(unparsed)'}, so a lab-only PR skips pr-a11y entirely.`,+ CI_WORKFLOW,+ lineOf(read(repoRoot, CI_WORKFLOW), /git diff --name-only/),+ ),+ );+ }+ const titles = storyTitles(stories);+ const resolves = titles.some(+ t => a11yComponentFromTitle(t) === candidate.sourceDir.toLowerCase(),+ );+ if (!resolves) {+ failures.push(+ `no story title resolves to the analyzer's component name "${candidate.sourceDir}"`,+ );+ evidence.push(+ ev(+ `pr-a11y matches a story's title segment against the changed component name; found ${titles.join(', ') || 'no titles'}.`,+ p.stories,+ ),+ );+ }+ add(+ 'accessibilityContracts',+ verdict(failures),+ failures.length === 0+ ? 'Reachable by the automated accessibility gate.'+ : `Not reachable by the accessibility gate: ${failures.join('; ')}.`,+ evidence,+ );+ }++ {+ const failures = [];+ const exported =+ labBarrel &&+ candidate.publicExports.every(name =>+ new RegExp(`\\b${name}\\b`).test(labBarrel),+ );+ if (!exported) failures.push('not exported from the lab package barrel');+ add(+ 'exportsAuditCI',+ verdict(failures),+ failures.length === 0+ ? 'Public exports reach the package barrel.'+ : `Export gap: ${failures.join('; ')}.`,+ [ev('Lab package barrel.', `${LAB_SRC}/index.ts`)],+ );+ }++ /* ------------------------------------------------ harden: objective ---- */++ {+ // Every state the component advertises must be exercised somewhere a+ // reviewer can see it (a story) and somewhere regression-proof (a test).+ const missing = [];+ for (const state of candidate.stateProps) {+ const inStories = stories ? new RegExp(`\\b${state}\\b`).test(stories) : false;+ const inTests = test ? new RegExp(`\\b${state}\\b`).test(test) : false;+ if (!inStories || !inTests) {+ missing.push(+ `${state} (${!inStories ? 'no story' : ''}${!inStories && !inTests ? ', ' : ''}${!inTests ? 'no test' : ''})`,+ );+ }+ }+ add(+ 'stateCoverage',+ verdict(missing),+ missing.length === 0+ ? `All ${candidate.stateProps.length} advertised states are covered by a story and a test.`+ : `Uncovered states: ${missing.join('; ')}.`,+ [ev('Stories.', p.stories), ev('Tests.', p.test)],+ );+ }++ {+ const names = storyExports(stories);+ const hasThemeStory = names.some(n => /theme/i.test(n));+ add(+ 'visualThemes',+ hasThemeStory ? 'passed' : 'in_progress',+ hasThemeStory+ ? 'A pinned theme story fixes light, dark, and nested rendering.'+ : 'No pinned theme story; theme rendering is only reachable through the global toolbar toggle.',+ [ev(`Story names: ${names.join(', ') || 'none'}.`, p.stories)],+ );+ }++ {+ const failures = [];+ const evidence = [];+ if (!test || !/\bkeyboard\b|\bArrow|\bTab\b|\bEnter\b|\bEscape\b/i.test(test)) {+ failures.push('no keyboard interaction tests');+ }+ const prefixes = rtlAuditedPrefixes(repoRoot);+ if (!prefixes.includes('lab-')) {+ failures.push('RTL auto-discovery skips lab stories');+ evidence.push(+ ev(+ `The RTL sweep only walks ${prefixes.join(', ') || '(unparsed)'} story ids.`,+ RTL_AUDIT,+ ),+ );+ }+ add(+ 'keyboardAccessibility',+ verdict(failures),+ failures.length === 0+ ? 'Keyboard behavior is tested and the component is inside the RTL sweep.'+ : `Keyboard or direction coverage incomplete: ${failures.join('; ')}.`,+ evidence,+ );+ }++ {+ const names = storyExports(stories).join(' ');+ const missing = ['empty', 'loading', 'disabled'].filter(+ kind => !new RegExp(kind, 'i').test(names),+ );+ add(+ 'edgeCases',+ verdict(missing),+ missing.length === 0+ ? 'Empty, loading, and disabled cases each have a dedicated story.'+ : `No dedicated story for: ${missing.join(', ')}.`,+ [ev(`Story names: ${names || 'none'}.`, p.stories)],+ );+ }++ {+ // Story completeness is the roll-up of the three story-shaped checks — it+ // passes only when the matrix a reviewer needs is actually reviewable.+ const dependencies = ['stories', 'visualThemes', 'edgeCases', 'stateCoverage'];+ const unmet = dependencies.filter(key => results[key]?.state !== 'passed');+ add(+ 'storyCompleteness',+ verdict(unmet),+ unmet.length === 0+ ? 'The full state, edge-case, and theme matrix is reviewable in Storybook.'+ : `Matrix incomplete because these are unmet: ${unmet.join(', ')}.`,+ [],+ );+ }++ return results;+}++/** Exported for tests. */+export const _internal = {+ a11yComponentFromTitle,+ ciComponentRoots,+ rtlAuditedPrefixes,+ storyExports,+ storyTitles,+};diff --git a/internal/lab-readiness/catalog.mjs b/internal/lab-readiness/catalog.mjsnew file mode 100644index 0000000000..7309d8e0a2--- /dev/null+++ b/internal/lab-readiness/catalog.mjs@@ -0,0 +1,192 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file catalog.mjs+ * @description The lab graduation rubric: the five lifecycle stages and the 30+ * checks a lab component must pass before it can be promoted into+ * `@astryxdesign/core`. This is the schema the Storybook readiness panel and+ * `apps/storybook/.lab-readiness/latest.json` are built against.+ * @input none — static data+ * @output STAGE_DEFINITIONS, CHECK_CATALOG, SCHEMA_VERSION, REPORT_KIND, and+ * lookup helpers+ * @position Shared vocabulary for the readiness tooling. `automated.mjs`+ * derives the checks it can prove from the repo; `manifest.mjs` declares the+ * rest; `audit.mjs` merges and scores them against this catalog.+ *+ * A check belongs to exactly one stage and one section. Sections exist so the+ * hardening stage can separate what a machine proved (`automatedAudit`) from+ * what a person had to fix by hand (`objectiveFixes`) and from what only a+ * person can sign off (`humanReview`).+ *+ * SYNC: When adding or renaming a check, bump SCHEMA_VERSION and update the+ * Storybook readiness panel that reads the emitted report.+ */++export const SCHEMA_VERSION = 1;+export const REPORT_KIND = 'astryx-lab-readiness-report';++const SPEC_PROTOCOL =+ 'https://github.com/facebook/astryx/wiki/Component-Specification-Protocol';+const BUILD_PROTOCOL =+ 'https://github.com/facebook/astryx/wiki/Component-Build-Protocol';+const HARDEN_PROTOCOL =+ 'https://github.com/facebook/astryx/wiki/Component-Hardening-Protocol';++/** @typedef {'not_started' | 'in_progress' | 'passed' | 'blocked'} CheckState */++export const STAGE_DEFINITIONS = [+ {key: 'research', label: 'Research'},+ {key: 'spec', label: 'Spec'},+ {key: 'build', label: 'Build'},+ {key: 'hardenChecks', label: 'Harden checks'},+ {key: 'hardenReview', label: 'Harden review'},+];++/**+ * Terse per-stage metadata so a check entry only has to name its stage and+ * section rather than repeat the labels and protocol URL.+ */+const STAGE_META = {+ research: {+ label: 'Research',+ protocolUrl: SPEC_PROTOCOL,+ sections: {research: 'Research'},+ },+ spec: {+ label: 'Spec',+ protocolUrl: SPEC_PROTOCOL,+ sections: {spec: 'Specification'},+ },+ build: {+ label: 'Build',+ protocolUrl: BUILD_PROTOCOL,+ sections: {build: 'Build'},+ },+ hardenChecks: {+ label: 'Harden checks',+ protocolUrl: HARDEN_PROTOCOL,+ sections: {+ automatedAudit: 'Automated audit',+ objectiveFixes: 'Objective fixes',+ },+ },+ hardenReview: {+ label: 'Harden review',+ protocolUrl: HARDEN_PROTOCOL,+ sections: {humanReview: 'Human review'},+ },+};++/**+ * `[stageKey, sectionKey, key, label, description]`. Order is the order the+ * readiness panel renders them in, and it is also lifecycle order.+ */+const CHECKS = [+ ['research', 'research', 'triage', 'Triage',+ 'A named owner has confirmed the problem and scope.'],+ ['research', 'research', 'internalResearch', 'Internal research',+ 'Existing Astryx and internal patterns have been audited.'],+ ['research', 'research', 'externalResearch', 'External research',+ 'Relevant design-system and web precedents have been compared.'],+ ['research', 'research', 'useCases', 'Use cases',+ 'Primary use cases, non-goals, and constraints are documented.'],++ ['spec', 'spec', 'draftSpec', 'Draft spec',+ 'An RFC describes the component contract and intended behavior.'],+ ['spec', 'spec', 'surfaceAudit', 'Surface audit',+ 'Composition, naming, variants, states, and tokens are enumerated.'],+ ['spec', 'spec', 'specReview', 'Spec review',+ 'Design and engineering reviewers have resolved blocking feedback.'],+ ['spec', 'spec', 'apiArbitration', 'API arbitration',+ 'Competing APIs were evaluated when the choice was non-obvious.'],+ ['spec', 'spec', 'finalizedSpec', 'Finalized spec',+ 'The accepted contract is recorded as the build baseline.'],++ ['build', 'build', 'implementation', 'Implementation',+ 'The component implements the agreed public contract.'],+ ['build', 'build', 'systemIntegration', 'System integration',+ 'Tokens, themes, composition, and shared primitives are integrated.'],+ ['build', 'build', 'stories', 'Stories',+ 'Storybook demonstrates representative states and composition.'],+ ['build', 'build', 'tests', 'Tests',+ 'Focused behavioral and contract tests cover the implementation.'],+ ['build', 'build', 'documentation', 'Documentation',+ 'The public API, usage, and important constraints are documented.'],+ ['build', 'build', 'reviewAndCI', 'Review and CI',+ 'Code review and required automated checks are complete.'],+ ['build', 'build', 'mergedPR', 'Merged PR',+ 'The build is merged into the lab package.'],++ ['hardenChecks', 'automatedAudit', 'tokensTheming', 'Tokens and theming',+ 'Token usage and theme integration pass the automated audit.'],+ ['hardenChecks', 'automatedAudit', 'reuseNaming', 'Reuse and naming',+ 'Existing primitives are reused and public names follow conventions.'],+ ['hardenChecks', 'automatedAudit', 'structureTypes', 'Structure and types',+ 'File structure, exports, and TypeScript contracts pass inspection.'],+ ['hardenChecks', 'automatedAudit', 'accessibilityContracts',+ 'Accessibility contracts',+ 'Static and automated accessibility requirements pass.'],+ ['hardenChecks', 'automatedAudit', 'exportsAuditCI', 'Exports and CI',+ 'Public exports, builds, tests, and required CI checks are green.'],++ ['hardenChecks', 'objectiveFixes', 'stateCoverage', 'State coverage',+ 'All supported interaction and semantic states are covered.'],+ ['hardenChecks', 'objectiveFixes', 'visualThemes', 'Visual themes',+ 'Light, dark, and nested-theme rendering is verified.'],+ ['hardenChecks', 'objectiveFixes', 'keyboardAccessibility',+ 'Keyboard and accessibility',+ 'Keyboard, focus, semantics, naming, and contrast are verified.'],+ ['hardenChecks', 'objectiveFixes', 'edgeCases', 'Edge cases',+ 'Empty, overflow, loading, disabled, and stress cases are resolved.'],+ ['hardenChecks', 'objectiveFixes', 'storyCompleteness', 'Story completeness',+ 'Stories make the completed state and edge-case matrix reviewable.'],++ ['hardenReview', 'humanReview', 'visualQuality', 'Visual quality',+ 'A human reviewer has approved polish and visual consistency.'],+ ['hardenReview', 'humanReview', 'compositionQuality', 'Composition quality',+ 'Real compositions confirm the API works beyond isolated demos.'],+ ['hardenReview', 'humanReview', 'scopeBoundary', 'Scope boundary',+ 'The component\u2019s responsibilities and non-goals remain coherent.'],+ ['hardenReview', 'humanReview', 'archivedReview', 'Archived review',+ 'The final checklist, decision, and follow-ups are linked.'],+];++export const CHECK_CATALOG = CHECKS.map(+ ([stageKey, sectionKey, key, label, description]) => {+ const stage = STAGE_META[stageKey];+ return {+ key,+ label,+ description,+ stageKey,+ stageLabel: stage.label,+ sectionKey,+ sectionLabel: stage.sections[sectionKey],+ protocolUrl: stage.protocolUrl,+ humanReview: stageKey === 'hardenReview',+ };+ },+);++const BY_KEY = new Map(CHECK_CATALOG.map(check => [check.key, check]));++/** Every check key, in lifecycle order. */+export const CHECK_KEYS = CHECK_CATALOG.map(check => check.key);++/** Check keys a human must sign off — no automation may propose these. */+export const HUMAN_REVIEW_KEYS = CHECK_CATALOG.filter(c => c.humanReview).map(+ c => c.key,+);++/** @param {string} key */+export function getCheck(key) {+ const check = BY_KEY.get(key);+ if (!check) throw new Error(`Unknown readiness check: ${key}`);+ return check;+}++/** A check counts toward a passing grade only in the `passed` state. */+export const PASSING_STATE = 'passed';++/** @type {readonly CheckState[]} */+export const CHECK_STATES = ['not_started', 'in_progress', 'passed', 'blocked'];diff --git a/internal/lab-readiness/manifest.mjs b/internal/lab-readiness/manifest.mjsnew file mode 100644index 0000000000..14c0c3bf1e--- /dev/null+++ b/internal/lab-readiness/manifest.mjs@@ -0,0 +1,192 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file manifest.mjs+ * @description Declares each lab graduation candidate and the readiness checks+ * that cannot be proven from the repo — the ones that live in an RFC, a code+ * review, or a person's judgement. Everything derivable from the source tree+ * is computed in `automated.mjs` and overrides whatever is claimed here.+ * @input none — static data, hand-maintained alongside the RFC and PRs+ * @output CANDIDATES+ * @position Read by `audit.mjs`. This file is the honest boundary of the+ * tooling: a claim here is a citation, not a proof.+ *+ * Declaring a check `passed` requires an `evidence` link a reviewer can open.+ * `audit.mjs` demotes any evidence-free `passed` claim to `in_progress`, so an+ * optimistic manifest cannot inflate the score.+ *+ * SYNC: When a tracking issue closes or a PR merges, update the state and the+ * evidence link here in the same change.+ */++/** @typedef {{label: string, url: string}} Evidence */++const issue = n => ({+ label: `Issue #${n}`,+ url: `https://github.com/facebook/astryx/issues/${n}`,+});+const pr = n => ({+ label: `PR #${n}`,+ url: `https://github.com/facebook/astryx/pull/${n}`,+});++/**+ * The lab components currently queued for promotion into core.+ *+ * `stateProps` lists the states the public API advertises. The automated audit+ * requires each one to appear in both a story (so a reviewer can see it) and a+ * test (so it cannot silently regress).+ */+export const CANDIDATES = [+ {+ id: 'list-input',+ displayName: 'List Input',+ sourceDir: 'ListInput',+ targetPackage: '@astryxdesign/core',+ trackingIssue: 4531,+ voteIssue: 4531,+ storyTitle: 'Lab/ListInput',+ storybookStoryId: 'lab-listinput--tag-options',+ publicExports: ['ListInput'],+ stateProps: ['isDisabled', 'isLoading', 'status'],+ summary:+ 'Compact editor for short collections of simple records.',+ declared: {+ triage: {+ state: 'passed',+ note: 'RFC #4531 was accepted and closed with a named owner.',+ evidence: [issue(4531)],+ },+ internalResearch: {+ state: 'passed',+ note: 'The accepted RFC audits existing Astryx and internal patterns.',+ evidence: [issue(4531)],+ },+ externalResearch: {+ state: 'passed',+ note: 'The accepted RFC compares external design-system precedents.',+ evidence: [issue(4531)],+ },+ useCases: {+ state: 'passed',+ note: 'Primary use cases, non-goals, and constraints are in the RFC and the component doc.',+ evidence: [issue(4531)],+ },+ draftSpec: {+ state: 'passed',+ note: 'RFC #4531 describes the component contract and intended behavior.',+ evidence: [issue(4531)],+ },+ surfaceAudit: {+ state: 'passed',+ note: 'Composition, variants, states, and theme targets are enumerated in the RFC and the component doc.',+ evidence: [issue(4531)],+ },+ specReview: {+ state: 'passed',+ note: 'Design and engineering feedback was resolved before the RFC closed.',+ evidence: [issue(4531)],+ },+ apiArbitration: {+ state: 'passed',+ note: 'Three API models were evaluated across six scenarios in the RFC.',+ evidence: [issue(4531)],+ },+ finalizedSpec: {+ state: 'passed',+ note: 'The closed RFC is the accepted build baseline.',+ evidence: [issue(4531)],+ },+ reviewAndCI: {+ state: 'passed',+ note: 'PR #4740 merged with required checks green.',+ evidence: [pr(4740)],+ },+ mergedPR: {+ state: 'passed',+ note: 'Merged into main on 2026-08-07.',+ evidence: [pr(4740)],+ },+ visualQuality: {state: 'not_started'},+ compositionQuality: {state: 'not_started'},+ scopeBoundary: {state: 'not_started'},+ archivedReview: {state: 'not_started'},+ },+ },++ {+ id: 'transfer-list',+ displayName: 'Transfer List',+ sourceDir: 'TransferList',+ targetPackage: '@astryxdesign/core',+ trackingIssue: 3281,+ voteIssue: 3281,+ storyTitle: 'Lab/TransferList',+ storybookStoryId: 'lab-transferlist--basic',+ publicExports: ['TransferList', 'TransferListSelector', 'transferListVars'],+ stateProps: ['isReorderable', 'hasSearch', 'hasSelectAll', 'hasClear'],+ summary:+ 'Controlled dual-panel input for moving options between lists.',+ declared: {+ triage: {+ state: 'passed',+ note: 'RFC #3281 confirms the problem and scope.',+ evidence: [issue(3281)],+ },+ internalResearch: {+ state: 'passed',+ note: 'The RFC audits existing Astryx collection patterns.',+ evidence: [issue(3281)],+ },+ externalResearch: {+ state: 'passed',+ note: 'The RFC compares external transfer-list precedents.',+ evidence: [issue(3281)],+ },+ useCases: {+ state: 'passed',+ note: 'Use cases and non-goals are documented in the RFC.',+ evidence: [issue(3281)],+ },+ draftSpec: {+ state: 'passed',+ note: 'RFC #3281 describes the intended contract.',+ evidence: [issue(3281)],+ },+ surfaceAudit: {+ state: 'in_progress',+ note: 'The RFC labels its surface audit preliminary and leaves naming and composition questions open. TransferListSelector shipped after it was written and is not covered.',+ evidence: [issue(3281), pr(4773)],+ },+ specReview: {+ state: 'not_started',+ note: 'No design or engineering review resolving blocking RFC feedback has been recorded.',+ evidence: [issue(3281)],+ },+ apiArbitration: {+ state: 'passed',+ note: 'The RFC weighs competing selection APIs before choosing.',+ evidence: [issue(3281)],+ },+ finalizedSpec: {+ state: 'not_started',+ note: 'RFC #3281 is still open, and its proposed listbox semantics contradict the shipped tests, which require semantic lists without listbox roles.',+ evidence: [issue(3281)],+ },+ reviewAndCI: {+ state: 'in_progress',+ note: 'Neither PR #4773 nor the carrier PR #4769 carries an approving review.',+ evidence: [pr(4773), pr(4769)],+ },+ mergedPR: {+ state: 'passed',+ note: 'Carrier PR #4769 merged into main on 2026-08-16.',+ evidence: [pr(4769)],+ },+ visualQuality: {state: 'not_started'},+ compositionQuality: {state: 'not_started'},+ scopeBoundary: {state: 'not_started'},+ archivedReview: {state: 'not_started'},+ },+ },+];diff --git a/package.json b/package.jsonindex 5c3931b3c9..c672f40c79 100644--- a/package.json+++ b/package.json@@ -27,6 +27,8 @@"a11y:audit": "node .github/scripts/accessibility-audit.js --baseline .github/a11y-baseline.json --fail-on-new","a11y:baseline": "node .github/scripts/accessibility-audit.js --baseline .github/a11y-baseline.json --update-baseline","rtl:audit": "node apps/storybook/rtl-audit/rtl-audit.mjs",+ "lab:readiness": "node internal/lab-readiness/audit.mjs",+ "lab:readiness:check": "node internal/lab-readiness/audit.mjs --check","guard:modal-close": "node .github/scripts/modal-close-visibility.js","storybook": "pnpm -F @astryxdesign/storybook dev","storybook:build": "pnpm -F @astryxdesign/storybook build",