Skip to content

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

TypeScript

feat(vibe-tests): universal evaluation system with fair comparison metrics (#243)

Cindy Zhangc262058d3099
diff --git a/internal/vibe-tests/app/index.html b/internal/vibe-tests/app/index.html
new file mode 100644
index 0000000000..ea2fa262ec
--- /dev/null
+++ b/internal/vibe-tests/app/index.html
@@ -0,0 +1,29 @@
+<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>XDS Vibe Tests</title>
+ <style>
+ /* CSS Reset for consistent screenshots */
+ *, *::before, *::after {
+ box-sizing: border-box;
+ margin: 0;
+ padding: 0;
+ }
+ html, body {
+ height: 100%;
+ font-family: system-ui, -apple-system, sans-serif;
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+ }
+ #root {
+ min-height: 100%;
+ }
+ </style>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/src/main.tsx"></script>
+ </body>
+</html>
diff --git a/internal/vibe-tests/app/package.json b/internal/vibe-tests/app/package.json
new file mode 100644
index 0000000000..4ec97509ed
--- /dev/null
+++ b/internal/vibe-tests/app/package.json
@@ -0,0 +1,21 @@
+{
+ "name": "@xds/vibe-tests-app",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "dev": "vite",
+ "build": "vite build"
+ },
+ "dependencies": {
+ "@xds/core": "*",
+ "@xds/theme": "*",
+ "react": "^19.0.0",
+ "react-dom": "^19.0.0",
+ "@stylexjs/stylex": "*"
+ },
+ "devDependencies": {
+ "@vitejs/plugin-react": "^4.0.0",
+ "@stylexjs/unplugin": "*",
+ "vite": "^5.0.0"
+ }
+}
diff --git a/internal/vibe-tests/app/src/main.tsx b/internal/vibe-tests/app/src/main.tsx
new file mode 100644
index 0000000000..8e3c8389c1
--- /dev/null
+++ b/internal/vibe-tests/app/src/main.tsx
@@ -0,0 +1,27 @@
+import React, {Suspense, lazy} from 'react';
+import {createRoot} from 'react-dom/client';
+
+const params = new URLSearchParams(window.location.search);
+const mode = params.get('mode') ?? 'preview';
+const theme = params.get('theme') ?? 'light';
+
+function App() {
+ if (mode === 'report') {
+ const Report = lazy(() => import('./report/Report'));
+ return (
+ <Suspense fallback={<div>Loading report...</div>}>
+ <Report />
+ </Suspense>
+ );
+ }
+
+ const Preview = lazy(() => import('./preview'));
+ return (
+ <Suspense fallback={<div>Loading...</div>}>
+ <Preview theme={theme} />
+ </Suspense>
+ );
+}
+
+const root = createRoot(document.getElementById('root')!);
+root.render(<App />);
diff --git a/internal/vibe-tests/app/src/report/CompareView.tsx b/internal/vibe-tests/app/src/report/CompareView.tsx
new file mode 100644
index 0000000000..16e830260a
--- /dev/null
+++ b/internal/vibe-tests/app/src/report/CompareView.tsx
@@ -0,0 +1,263 @@
+import * as stylex from '@stylexjs/stylex';
+import {XDSCard} from '@xds/core/Card';
+import {XDSVStack} from '@xds/core/Stack';
+import {XDSHStack} from '@xds/core/Stack';
+import {XDSText} from '@xds/core/Text';
+import {XDSHeading} from '@xds/core/Text';
+import {XDSBadge} from '@xds/core/Badge';
+import {XDSTable} from '@xds/core/Table';
+import type {XDSTableColumn} from '@xds/core/Table/types';
+import {spacingVars, colorVars} from '@xds/core/theme/tokens.stylex';
+import type {UniversalComparison, UniversalDimension} from './types';
+import {ALL_DIMENSIONS, DIMENSION_LABELS, formatScore} from './utils';
+
+const styles = stylex.create({
+ section: {
+ padding: spacingVars['--spacing-4'],
+ },
+ summaryGrid: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(3, 1fr)',
+ gap: spacingVars['--spacing-4'],
+ },
+ winCard: {
+ padding: spacingVars['--spacing-4'],
+ textAlign: 'center',
+ },
+ positive: {
+ color: colorVars['--color-positive'],
+ },
+ negative: {
+ color: colorVars['--color-negative'],
+ },
+ neutral: {
+ color: colorVars['--color-text-secondary'],
+ },
+});
+
+interface CompareViewProps {
+ comparison: UniversalComparison;
+}
+
+interface DimRow extends Record<string, unknown> {
+ id: string;
+ dimension: string;
+ xdsScore: number;
+ baselineScore: number;
+ delta: number;
+ winner: string;
+}
+
+interface CatRow extends Record<string, unknown> {
+ id: string;
+ category: string;
+ xdsOverall: number;
+ baselineOverall: number;
+ delta: number;
+}
+
+export function CompareView({comparison}: CompareViewProps) {
+ const {xds, baseline, winners} = comparison;
+
+ // Count wins
+ let xdsWins = 0;
+ let baselineWins = 0;
+ let ties = 0;
+ for (const dim of ALL_DIMENSIONS) {
+ const w = winners[dim];
+ if (w === 'xds') xdsWins++;
+ else if (w === 'baseline') baselineWins++;
+ else ties++;
+ }
+
+ // Dimension comparison rows
+ const dimData: DimRow[] = ALL_DIMENSIONS.map(dim => ({
+ id: dim,
+ dimension: DIMENSION_LABELS[dim],
+ xdsScore: xds.averages[dim],
+ baselineScore: baseline.averages[dim],
+ delta: xds.averages[dim] - baseline.averages[dim],
+ winner: winners[dim],
+ }));
+
+ const dimColumns: XDSTableColumn<DimRow>[] = [
+ {key: 'dimension', header: 'Dimension'},
+ {
+ key: 'xdsScore',
+ header: 'XDS',
+ renderCell: row => (
+ <XDSText type="body">{formatScore(row.xdsScore)}</XDSText>
+ ),
+ },
+ {
+ key: 'baselineScore',
+ header: 'Baseline',
+ renderCell: row => (
+ <XDSText type="body">{formatScore(row.baselineScore)}</XDSText>
+ ),
+ },
+ {
+ key: 'delta',
+ header: 'Delta',
+ renderCell: row => (
+ <XDSText
+ type="body"
+ xstyle={
+ row.delta > 0
+ ? styles.positive
+ : row.delta < 0
+ ? styles.negative
+ : styles.neutral
+ }>
+ {row.delta > 0 ? '+' : ''}
+ {formatScore(row.delta)}
+ </XDSText>
+ ),
+ },
+ {
+ key: 'winner',
+ header: 'Winner',
+ renderCell: row => (
+ <XDSBadge
+ variant={
+ row.winner === 'xds'
+ ? 'success'
+ : row.winner === 'baseline'
+ ? 'error'
+ : 'neutral'
+ }>
+ {row.winner === 'xds'
+ ? 'XDS'
+ : row.winner === 'baseline'
+ ? 'Baseline'
+ : 'Tie'}
+ </XDSBadge>
+ ),
+ },
+ ];
+
+ // Category breakdown
+ const allCategories = new Set([
+ ...Object.keys(xds.byCategory),
+ ...Object.keys(baseline.byCategory),
+ ]);
+
+ const catData: CatRow[] = [...allCategories].map(cat => {
+ const xdsCat = xds.byCategory[cat] ?? {};
+ const baseCat = baseline.byCategory[cat] ?? {};
+ const xdsAvg =
+ ALL_DIMENSIONS.reduce(
+ (s, d) => s + ((xdsCat[d as UniversalDimension] as number) ?? 0),
+ 0,
+ ) / ALL_DIMENSIONS.length;
+ const baseAvg =
+ ALL_DIMENSIONS.reduce(
+ (s, d) => s + ((baseCat[d as UniversalDimension] as number) ?? 0),
+ 0,
+ ) / ALL_DIMENSIONS.length;
+ return {
+ id: cat,
+ category: cat,
+ xdsOverall: xdsAvg,
+ baselineOverall: baseAvg,
+ delta: xdsAvg - baseAvg,
+ };
+ });
+
+ const catColumns: XDSTableColumn<CatRow>[] = [
+ {key: 'category', header: 'Category'},
+ {
+ key: 'xdsOverall',
+ header: 'XDS',
+ renderCell: row => (
+ <XDSText type="body">{formatScore(row.xdsOverall)}</XDSText>
+ ),
+ },
+ {
+ key: 'baselineOverall',
+ header: 'Baseline',
+ renderCell: row => (
+ <XDSText type="body">{formatScore(row.baselineOverall)}</XDSText>
+ ),
+ },
+ {
+ key: 'delta',
+ header: 'Delta',
+ renderCell: row => (
+ <XDSText
+ type="body"
+ xstyle={
+ row.delta > 0
+ ? styles.positive
+ : row.delta < 0
+ ? styles.negative
+ : styles.neutral
+ }>
+ {row.delta > 0 ? '+' : ''}
+ {formatScore(row.delta)}
+ </XDSText>
+ ),
+ },
+ ];
+
+ return (
+ <XDSVStack gap="space6">
+ <div {...stylex.props(styles.summaryGrid)}>
+ <XDSCard>
+ <div {...stylex.props(styles.winCard)}>
+ <XDSVStack gap="space2">
+ <XDSText type="label">XDS Wins</XDSText>
+ <XDSHeading level={2}>
+ <span {...stylex.props(styles.positive)}>{xdsWins}</span>
+ </XDSHeading>
+ </XDSVStack>
+ </div>
+ </XDSCard>
+ <XDSCard>
+ <div {...stylex.props(styles.winCard)}>
+ <XDSVStack gap="space2">
+ <XDSText type="label">Baseline Wins</XDSText>
+ <XDSHeading level={2}>
+ <span {...stylex.props(styles.negative)}>{baselineWins}</span>
+ </XDSHeading>
+ </XDSVStack>
+ </div>
+ </XDSCard>
+ <XDSCard>
+ <div {...stylex.props(styles.winCard)}>
+ <XDSVStack gap="space2">
+ <XDSText type="label">Ties</XDSText>
+ <XDSHeading level={2}>
+ <span {...stylex.props(styles.neutral)}>{ties}</span>
+ </XDSHeading>
+ </XDSVStack>
+ </div>
+ </XDSCard>
+ </div>
+
+ <XDSVStack gap="space3">
+ <XDSHeading level={3}>Dimension Comparison</XDSHeading>
+ <XDSTable<DimRow>
+ data={dimData}
+ columns={dimColumns}
+ idKey="id"
+ density="balanced"
+ dividers="rows"
+ />
+ </XDSVStack>
+
+ {catData.length > 0 && (
+ <XDSVStack gap="space3">
+ <XDSHeading level={3}>Category Breakdown</XDSHeading>
+ <XDSTable<CatRow>
+ data={catData}
+ columns={catColumns}
+ idKey="id"
+ density="balanced"
+ dividers="rows"
+ />
+ </XDSVStack>
+ )}
+ </XDSVStack>
+ );
+}
diff --git a/internal/vibe-tests/app/src/report/DimensionTable.tsx b/internal/vibe-tests/app/src/report/DimensionTable.tsx
new file mode 100644
index 0000000000..2776e8c18e
--- /dev/null
+++ b/internal/vibe-tests/app/src/report/DimensionTable.tsx
@@ -0,0 +1,87 @@
+import {XDSTable} from '@xds/core/Table';
+import {XDSStatusDot} from '@xds/core/StatusDot';
+import {XDSHStack} from '@xds/core/Stack';
+import {XDSText} from '@xds/core/Text';
+import type {XDSTableColumn} from '@xds/core/Table/types';
+import type {UniversalScore} from './types';
+import {
+ ALL_DIMENSIONS,
+ DIMENSION_LABELS,
+ computeOverall,
+ formatScore,
+ scoreToStatusVariant,
+} from './utils';
+
+interface DimensionTableProps {
+ byPrompt: Record<string, UniversalScore>;
+ categories?: Record<string, string>;
+}
+
+interface RowData extends Record<string, unknown> {
+ id: string;
+ promptId: string;
+ category: string;
+ accessibility: number;
+ codeQuality: number;
+ repetition: number;
+ conciseness: number;
+ themeAdherence: number;
+ correctness: number;
+ overall: number;
+}
+
+function ScoreCell({score}: {score: number}) {
+ return (
+ <XDSHStack gap="space1" hAlign="center">
+ <XDSStatusDot
+ variant={scoreToStatusVariant(score)}
+ label={`Score: ${formatScore(score)}`}
+ size="sm"
+ />
+ <XDSText type="body">{formatScore(score)}</XDSText>
+ </XDSHStack>
+ );
+}
+
+export function DimensionTable({byPrompt, categories}: DimensionTableProps) {
+ const data: RowData[] = Object.entries(byPrompt).map(([promptId, score]) => ({
+ id: promptId,
+ promptId,
+ category: categories?.[promptId] ?? 'β€”',
+ accessibility: score.accessibility.score,
+ codeQuality: score.codeQuality.score,
+ repetition: score.repetition.score,
+ conciseness: score.conciseness.score,
+ themeAdherence: score.themeAdherence.score,
+ correctness: score.correctness.score,
+ overall: computeOverall(score),
+ }));
+
+ const columns: XDSTableColumn<RowData>[] = [
+ {key: 'promptId', header: 'Prompt'},
+ {key: 'category', header: 'Category'},
+ ...ALL_DIMENSIONS.map(
+ (dim): XDSTableColumn<RowData> => ({
+ key: dim,
+ header: DIMENSION_LABELS[dim],
+ renderCell: row => <ScoreCell score={row[dim] as number} />,
+ }),
+ ),
+ {
+ key: 'overall',
+ header: 'Overall',
+ renderCell: row => <ScoreCell score={row.overall} />,
+ },
+ ];
+
+ return (
+ <XDSTable<RowData>
+ data={data}
+ columns={columns}
+ idKey="id"
+ density="compact"
+ dividers="rows"
+ isStriped
+ />
+ );
+}
diff --git a/internal/vibe-tests/app/src/report/Report.tsx b/internal/vibe-tests/app/src/report/Report.tsx
new file mode 100644
index 0000000000..27ca61e141
--- /dev/null
+++ b/internal/vibe-tests/app/src/report/Report.tsx
@@ -0,0 +1,283 @@
+import {useState, useMemo} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {XDSTheme} from '@xds/core/theme';
+import {XDSVStack} from '@xds/core/Stack';
+import {XDSHStack} from '@xds/core/Stack';
+import {XDSText} from '@xds/core/Text';
+import {XDSHeading} from '@xds/core/Text';
+import {XDSTabList} from '@xds/core/TabList';
+import {XDSTab} from '@xds/core/TabList';
+import {XDSCard} from '@xds/core/Card';
+import {XDSButton} from '@xds/core/Button';
+import {defaultTheme} from '@xds/theme/default';
+import {spacingVars, colorVars} from '@xds/core/theme/tokens.stylex';
+import type {ReportData} from './types';
+import {ALL_DIMENSIONS, DIMENSION_LABELS, formatScore} from './utils';
+import {ScoreCard} from './ScoreCard';
+import {DimensionTable} from './DimensionTable';
+import {CompareView} from './CompareView';
+import {ScreenshotGallery} from './ScreenshotGallery';
+
+const styles = stylex.create({
+ root: {
+ minHeight: '100vh',
+ backgroundColor: colorVars['--color-wash'],
+ },
+ container: {
+ maxWidth: '1200px',
+ marginInline: 'auto',
+ padding: spacingVars['--spacing-6'],
+ },
+ header: {
+ paddingBlock: spacingVars['--spacing-4'],
+ },
+ scoreGrid: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))',
+ gap: spacingVars['--spacing-4'],
+ },
+ metricsCard: {
+ padding: spacingVars['--spacing-4'],
+ },
+ metricsGrid: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))',
+ gap: spacingVars['--spacing-3'],
+ },
+ metricItem: {
+ textAlign: 'center',
+ },
+ tabContent: {
+ paddingBlock: spacingVars['--spacing-6'],
+ },
+ emptyState: {
+ padding: spacingVars['--spacing-8'],
+ textAlign: 'center',
+ },
+});
+
+function ConcisenessMetricsCard({
+ byPrompt,
+}: {
+ byPrompt: ReportData['universal']['byPrompt'];
+}) {
+ // Aggregate conciseness metrics across prompts
+ const entries = Object.values(byPrompt);
+ if (entries.length === 0) return null;
+
+ const totals = entries.reduce(
+ (acc, score) => {
+ const m = score.conciseness.metrics;
+ return {
+ totalLines: acc.totalLines + m.totalLines,
+ codeLines: acc.codeLines + m.codeLines,
+ stylingRatio: acc.stylingRatio + m.stylingRatio,
+ boilerplateRatio: acc.boilerplateRatio + m.boilerplateRatio,
+ count: acc.count + 1,
+ };
+ },
+ {
+ totalLines: 0,
+ codeLines: 0,
+ stylingRatio: 0,
+ boilerplateRatio: 0,
+ count: 0,
+ },
+ );
+
+ const avgStyling = (totals.stylingRatio / totals.count) * 100;
+ const avgBoilerplate = (totals.boilerplateRatio / totals.count) * 100;
+
+ return (
+ <XDSCard>
+ <div {...stylex.props(styles.metricsCard)}>
+ <XDSVStack gap="space3">
+ <XDSHeading level={4}>Conciseness Metrics</XDSHeading>
+ <div {...stylex.props(styles.metricsGrid)}>
+ <div {...stylex.props(styles.metricItem)}>
+ <XDSVStack gap="space1">
+ <XDSText type="label">Total Lines</XDSText>
+ <XDSHeading level={3}>{totals.totalLines}</XDSHeading>
+ </XDSVStack>
+ </div>
+ <div {...stylex.props(styles.metricItem)}>
+ <XDSVStack gap="space1">
+ <XDSText type="label">Code Lines</XDSText>
+ <XDSHeading level={3}>{totals.codeLines}</XDSHeading>
+ </XDSVStack>
+ </div>
+ <div {...stylex.props(styles.metricItem)}>
+ <XDSVStack gap="space1">
+ <XDSText type="label">Styling Ratio</XDSText>
+ <XDSHeading level={3}>{avgStyling.toFixed(1)}%</XDSHeading>
+ </XDSVStack>
+ </div>
+ <div {...stylex.props(styles.metricItem)}>
+ <XDSVStack gap="space1">
+ <XDSText type="label">Boilerplate Ratio</XDSText>
+ <XDSHeading level={3}>{avgBoilerplate.toFixed(1)}%</XDSHeading>
+ </XDSVStack>
+ </div>
+ </div>
+ </XDSVStack>
+ </div>
+ </XDSCard>
+ );
+}
+
+export function Report() {
+ const [themeMode, setThemeMode] = useState<'light' | 'dark'>('light');
+ const [activeTab, setActiveTab] = useState('overview');
+
+ const data: ReportData | undefined = window.__REPORT_DATA__;
+
+ const hasScreenshots =
+ data?.screenshots && Object.keys(data.screenshots).length > 0;
+
+ const toggleTheme = () => {
+ setThemeMode(m => (m === 'light' ? 'dark' : 'light'));
+ };
+
+ if (!data) {
+ return (
+ <XDSTheme theme={defaultTheme} mode={themeMode}>
+ <div {...stylex.props(styles.root)}>
+ <div {...stylex.props(styles.container)}>
+ <div {...stylex.props(styles.emptyState)}>
+ <XDSVStack gap="space4">
+ <XDSHeading level={2}>No Report Data</XDSHeading>
+ <XDSText type="body">
+ No report data found. Run the vibe test harness to generate a
+ report.
+ </XDSText>
+ </XDSVStack>
+ </div>
+ </div>
+ </div>
+ </XDSTheme>
+ );
+ }
+
+ const {universal, comparison, screenshots} = data;
+
+ return (
+ <XDSTheme theme={defaultTheme} mode={themeMode}>
+ <div {...stylex.props(styles.root)}>
+ <div {...stylex.props(styles.container)}>
+ <XDSVStack gap="space6">
+ {/* Header */}
+ <div {...stylex.props(styles.header)}>
+ <XDSHStack gap="space4" hAlign="between" vAlign="center">
+ <XDSVStack gap="space1">
+ <XDSHeading level={1}>Vibe Test Report</XDSHeading>
+ {data.target && (
+ <XDSText type="supporting">Target: {data.target}</XDSText>
+ )}
+ {data.iterationId && (
+ <XDSText type="supporting">
+ Iteration: {data.iterationId}
+ </XDSText>
+ )}
+ </XDSVStack>
+ <XDSButton variant="secondary" onClick={toggleTheme}>
+ {themeMode === 'light' ? 'πŸŒ™ Dark' : 'β˜€οΈ Light'}
+ </XDSButton>
+ </XDSHStack>
+ </div>
+
+ {/* Tabs */}
+ <XDSTabList value={activeTab} onChange={setActiveTab} hasDivider>
+ <XDSTab value="overview" label="Overview" />
+ <XDSTab value="byPrompt" label="By Prompt" />
+ {hasScreenshots && (
+ <XDSTab value="screenshots" label="Screenshots" />
+ )}
+ </XDSTabList>
+
+ {/* Tab Content */}
+ <div {...stylex.props(styles.tabContent)}>
+ {activeTab === 'overview' && (
+ <XDSVStack gap="space6">
+ {/* Overall score */}
+ <ScoreCard
+ label="Overall Score"
+ score={universal.overall}
+ compareScore={comparison?.baseline.overall}
+ compareLabel="Baseline"
+ />
+
+ {/* Dimension scores grid */}
+ <XDSVStack gap="space3">
+ <XDSHeading level={3}>Dimensions</XDSHeading>
+ <div {...stylex.props(styles.scoreGrid)}>
+ {ALL_DIMENSIONS.map(dim => (
+ <ScoreCard
+ key={dim}
+ label={DIMENSION_LABELS[dim]}
+ score={universal.averages[dim]}
+ compareScore={comparison?.baseline.averages[dim]}
+ compareLabel="Baseline"
+ />
+ ))}
+ </div>
+ </XDSVStack>
+
+ {/* Dark mode rate */}
+ <XDSCard>
+ <div {...stylex.props(styles.metricsCard)}>
+ <XDSHStack gap="space4" hAlign="center">
+ <XDSText type="label">Dark Mode Support Rate</XDSText>
+ <XDSHeading level={3}>
+ {(universal.darkModeRate * 100).toFixed(0)}%
+ </XDSHeading>
+ </XDSHStack>
+ </div>
+ </XDSCard>
+
+ {/* Conciseness metrics */}
+ <ConcisenessMetricsCard byPrompt={universal.byPrompt} />
+
+ {/* Comparison view */}
+ {comparison && (
+ <XDSVStack gap="space3">
+ <XDSHeading level={3}>
+ XDS vs Baseline Comparison
+ </XDSHeading>
+ <CompareView comparison={comparison} />
+ </XDSVStack>
+ )}
+ </XDSVStack>
+ )}
+
+ {activeTab === 'byPrompt' && (
+ <DimensionTable
+ byPrompt={universal.byPrompt}
+ categories={
+ Object.keys(universal.byCategory).length > 0
+ ? Object.entries(universal.byPrompt).reduce(
+ (acc, [promptId]) => {
+ // Find category for this prompt by checking byCategory
+ for (const [cat, dims] of Object.entries(
+ universal.byCategory,
+ )) {
+ acc[promptId] = acc[promptId] ?? cat;
+ }
+ return acc;
+ },
+ {} as Record<string, string>,
+ )
+ : undefined
+ }
+ />
+ )}
+
+ {activeTab === 'screenshots' && screenshots && (
+ <ScreenshotGallery screenshots={screenshots} />
+ )}
+ </div>
+ </XDSVStack>
+ </div>
+ </div>
+ </XDSTheme>
+ );
+}
diff --git a/internal/vibe-tests/app/src/report/ScoreCard.tsx b/internal/vibe-tests/app/src/report/ScoreCard.tsx
new file mode 100644
index 0000000000..94dd13dc14
--- /dev/null
+++ b/internal/vibe-tests/app/src/report/ScoreCard.tsx
@@ -0,0 +1,76 @@
+import * as stylex from '@stylexjs/stylex';
+import {XDSCard} from '@xds/core/Card';
+import {XDSVStack} from '@xds/core/Stack';
+import {XDSHStack} from '@xds/core/Stack';
+import {XDSText} from '@xds/core/Text';
+import {XDSHeading} from '@xds/core/Text';
+import {XDSProgressBar} from '@xds/core/ProgressBar';
+import {spacingVars, colorVars} from '@xds/core/theme/tokens.stylex';
+import {formatScore, scoreToProgressVariant} from './utils';
+
+const styles = stylex.create({
+ card: {
+ padding: spacingVars['--spacing-4'],
+ },
+ deltaPositive: {
+ color: colorVars['--color-positive'],
+ },
+ deltaNegative: {
+ color: colorVars['--color-negative'],
+ },
+ deltaNeutral: {
+ color: colorVars['--color-text-secondary'],
+ },
+});
+
+interface ScoreCardProps {
+ label: string;
+ score: number;
+ compareScore?: number;
+ compareLabel?: string;
+}
+
+export function ScoreCard({
+ label,
+ score,
+ compareScore,
+ compareLabel,
+}: ScoreCardProps) {
+ const delta = compareScore != null ? score - compareScore : undefined;
+
+ return (
+ <XDSCard>
+ <div {...stylex.props(styles.card)}>
+ <XDSVStack gap="space2">
+ <XDSText type="label">{label}</XDSText>
+ <XDSHStack gap="space2" hAlign="center">
+ <XDSHeading level={2}>{formatScore(score)}</XDSHeading>
+ {delta != null && (
+ <XDSText
+ type="supporting"
+ xstyle={
+ delta > 0
+ ? styles.deltaPositive
+ : delta < 0
+ ? styles.deltaNegative
+ : styles.deltaNeutral
+ }>
+ {delta > 0 ? '+' : ''}
+ {formatScore(delta)}
+ {compareLabel ? ` vs ${compareLabel}` : ''}
+ </XDSText>
+ )}
+ </XDSHStack>
+ <XDSProgressBar
+ label={label}
+ isLabelHidden
+ value={score}
+ max={100}
+ variant={scoreToProgressVariant(score)}
+ size="sm"
+ />
+ </XDSVStack>
+ </div>
+ </XDSCard>
+ );
+}
diff --git a/internal/vibe-tests/app/src/report/ScreenshotGallery.tsx b/internal/vibe-tests/app/src/report/ScreenshotGallery.tsx
new file mode 100644
index 0000000000..fb11f7d098
--- /dev/null
+++ b/internal/vibe-tests/app/src/report/ScreenshotGallery.tsx
@@ -0,0 +1,128 @@
+import {useState} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {XDSCard} from '@xds/core/Card';
+import {XDSVStack} from '@xds/core/Stack';
+import {XDSText} from '@xds/core/Text';
+import {spacingVars, colorVars} from '@xds/core/theme/tokens.stylex';
+
+const styles = stylex.create({
+ grid: {
+ display: 'grid',
+ gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))',
+ gap: spacingVars['--spacing-4'],
+ },
+ cardContent: {
+ padding: spacingVars['--spacing-3'],
+ },
+ image: {
+ width: '100%',
+ height: 'auto',
+ display: 'block',
+ cursor: 'pointer',
+ borderRadius: spacingVars['--spacing-1'],
+ },
+ overlay: {
+ position: 'fixed',
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ backgroundColor: colorVars['--color-overlay'],
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ zIndex: 9999,
+ cursor: 'pointer',
+ },
+ overlayImage: {
+ maxWidth: '90vw',
+ maxHeight: '90vh',
+ objectFit: 'contain',
+ },
+ meta: {
+ display: 'flex',
+ gap: spacingVars['--spacing-2'],
+ flexWrap: 'wrap',
+ },
+});
+
+interface ScreenshotGalleryProps {
+ screenshots: Record<string, string>;
+}
+
+interface ScreenshotMeta {
+ filename: string;
+ src: string;
+ promptId: string;
+ viewport: string;
+ theme: string;
+}
+
+function parseFilename(filename: string): {
+ promptId: string;
+ viewport: string;
+ theme: string;
+} {
+ // Expected format: promptId-viewport-theme.png or similar
+ const withoutExt = filename.replace(/\.\w+$/, '');
+ const parts = withoutExt.split(/[-_]/);
+
+ if (parts.length >= 3) {
+ const theme = parts[parts.length - 1] ?? 'unknown';
+ const viewport = parts[parts.length - 2] ?? 'unknown';
+ const promptId = parts.slice(0, -2).join('-');
+ return {promptId, viewport, theme};
+ }
+
+ return {promptId: withoutExt, viewport: 'unknown', theme: 'unknown'};
+}
+
+export function ScreenshotGallery({screenshots}: ScreenshotGalleryProps) {
+ const [enlarged, setEnlarged] = useState<string | null>(null);
+
+ const items: ScreenshotMeta[] = Object.entries(screenshots).map(
+ ([filename, src]) => {
+ const {promptId, viewport, theme} = parseFilename(filename);
+ return {filename, src, promptId, viewport, theme};
+ },
+ );
+
+ return (
+ <>
+ <div {...stylex.props(styles.grid)}>
+ {items.map(item => (
+ <XDSCard key={item.filename}>
+ <XDSVStack gap="space0">
+ <img
+ {...stylex.props(styles.image)}
+ src={item.src}
+ alt={`Screenshot: ${item.promptId}`}
+ onClick={() => setEnlarged(item.src)}
+ />
+ <div {...stylex.props(styles.cardContent)}>
+ <XDSVStack gap="space1">
+ <XDSText type="label">{item.promptId}</XDSText>
+ <div {...stylex.props(styles.meta)}>
+ <XDSText type="supporting">{item.viewport}</XDSText>
+ <XDSText type="supporting">{item.theme}</XDSText>
+ </div>
+ </XDSVStack>
+ </div>
+ </XDSVStack>
+ </XDSCard>
+ ))}
+ </div>
+ {enlarged && (
+ <div
+ {...stylex.props(styles.overlay)}
+ onClick={() => setEnlarged(null)}>
+ <img
+ {...stylex.props(styles.overlayImage)}
+ src={enlarged}
+ alt="Enlarged screenshot"
+ />
+ </div>
+ )}
+ </>
+ );
+}
diff --git a/internal/vibe-tests/app/src/report/types.ts b/internal/vibe-tests/app/src/report/types.ts
new file mode 100644
index 0000000000..00990121fa
--- /dev/null
+++ b/internal/vibe-tests/app/src/report/types.ts
@@ -0,0 +1,33 @@
+import type {
+ UniversalScore,
+ UniversalAggregate,
+ UniversalComparison,
+ UniversalDimension,
+ ConcisenessMetrics,
+ DimensionScore,
+ UniversalFinding,
+} from '../../../src/types';
+
+export type {
+ UniversalScore,
+ UniversalAggregate,
+ UniversalComparison,
+ UniversalDimension,
+ ConcisenessMetrics,
+ DimensionScore,
+ UniversalFinding,
+};
+
+export interface ReportData {
+ universal: UniversalAggregate;
+ comparison?: UniversalComparison;
+ screenshots?: Record<string, string>;
+ iterationId?: string;
+ target?: string;
+}
+
+declare global {
+ interface Window {
+ __REPORT_DATA__?: ReportData;
+ }
+}
diff --git a/internal/vibe-tests/app/src/report/utils.ts b/internal/vibe-tests/app/src/report/utils.ts
new file mode 100644
index 0000000000..8d0c8b3357
--- /dev/null
+++ b/internal/vibe-tests/app/src/report/utils.ts
@@ -0,0 +1,46 @@
+import type {UniversalDimension, UniversalScore} from './types';
+
+export const ALL_DIMENSIONS: UniversalDimension[] = [
+ 'accessibility',
+ 'codeQuality',
+ 'repetition',
+ 'conciseness',
+ 'themeAdherence',
+ 'correctness',
+];
+
+export const DIMENSION_LABELS: Record<UniversalDimension, string> = {
+ accessibility: 'Accessibility',
+ codeQuality: 'Code Quality',
+ repetition: 'DRYness',
+ conciseness: 'Conciseness',
+ themeAdherence: 'Theme Adherence',
+ correctness: 'Correctness',
+};
+
+export function scoreToStatusVariant(
+ score: number,
+): 'positive' | 'neutral' | 'warning' | 'negative' {
+ if (score >= 90) return 'positive';
+ if (score >= 70) return 'neutral';
+ if (score >= 50) return 'warning';
+ return 'negative';
+}
+
+export function scoreToProgressVariant(
+ score: number,
+): 'positive' | 'accent' | 'warning' | 'negative' {
+ if (score >= 90) return 'positive';
+ if (score >= 70) return 'accent';
+ if (score >= 50) return 'warning';
+ return 'negative';
+}
+
+export function computeOverall(score: UniversalScore): number {
+ const values = ALL_DIMENSIONS.map(d => score[d].score);
+ return values.reduce((sum, v) => sum + v, 0) / values.length;
+}
+
+export function formatScore(n: number): string {
+ return n.toFixed(1);
+}
diff --git a/internal/vibe-tests/app/tsconfig.app.json b/internal/vibe-tests/app/tsconfig.app.json
new file mode 100644
index 0000000000..06ddb0f203
--- /dev/null
+++ b/internal/vibe-tests/app/tsconfig.app.json
@@ -0,0 +1,26 @@
+{
+ "compilerOptions": {
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
+ "target": "ES2020",
+ "useDefineForClassFields": true,
+ "lib": ["ES2020", "DOM", "DOM.Iterable"],
+ "module": "ESNext",
+ "skipLibCheck": true,
+ "moduleResolution": "bundler",
+ "allowImportingTsExtensions": true,
+ "verbatimModuleSyntax": false,
+ "moduleDetection": "force",
+ "noEmit": true,
+ "jsx": "react-jsx",
+ "strict": true,
+ "noUnusedLocals": false,
+ "noUnusedParameters": false,
+ "noFallthroughCasesInSwitch": true,
+ "paths": {
+ "@xds/core/*": ["../../../packages/core/src/*"],
+ "@xds/core": ["../../../packages/core/src"],
+ "@xds/theme/*": ["../../../packages/theme/src/*"]
+ }
+ },
+ "include": ["src"]
+}
diff --git a/internal/vibe-tests/app/tsconfig.json b/internal/vibe-tests/app/tsconfig.json
new file mode 100644
index 0000000000..b3de6fde91
--- /dev/null
+++ b/internal/vibe-tests/app/tsconfig.json
@@ -0,0 +1,7 @@
+{
+ "files": [],
+ "references": [
+ {"path": "./tsconfig.app.json"},
+ {"path": "./tsconfig.node.json"}
+ ]
+}
diff --git a/internal/vibe-tests/app/tsconfig.node.json b/internal/vibe-tests/app/tsconfig.node.json
new file mode 100644
index 0000000000..f5a4d62057
--- /dev/null
+++ b/internal/vibe-tests/app/tsconfig.node.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
+ "target": "ES2022",
+ "lib": ["ES2023"],
+ "module": "ESNext",
+ "skipLibCheck": true,
+ "moduleResolution": "bundler",
+ "allowImportingTsExtensions": true,
+ "verbatimModuleSyntax": false,
+ "moduleDetection": "force",
+ "noEmit": true,
+ "strict": true
+ },
+ "include": ["vite.config.ts"]
+}
diff --git a/internal/vibe-tests/app/vite.config.ts b/internal/vibe-tests/app/vite.config.ts
new file mode 100644
index 0000000000..e72f04a0e1
--- /dev/null
+++ b/internal/vibe-tests/app/vite.config.ts
@@ -0,0 +1,36 @@
+import path from 'path';
+import {fileURLToPath} from 'url';
+import {defineConfig} from 'vite';
+import react from '@vitejs/plugin-react';
+import stylex from '@stylexjs/unplugin';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const repoRoot = path.resolve(__dirname, '../../..');
+
+export default defineConfig({
+ plugins: [
+ stylex.vite({
+ dev: process.env.NODE_ENV === 'development',
+ runtimeInjection: false,
+ treeshakeCompensation: true,
+ unstable_moduleResolution: {
+ type: 'commonJS',
+ rootDir: repoRoot,
+ },
+ aliases: {
+ '@xds/core/theme/tokens.stylex': path.resolve(repoRoot, 'packages/core/src/theme/tokens.stylex.ts'),
+ },
+ }),
+ react(),
+ ],
+ resolve: {
+ alias: {
+ '@xds/core/theme/tokens.stylex': path.resolve(repoRoot, 'packages/core/src/theme/tokens.stylex.ts'),
+ '@xds/core': path.resolve(repoRoot, 'packages/core/src'),
+ '@xds/theme/default': path.resolve(repoRoot, 'packages/theme/src/default'),
+ '@xds/theme/neutral': path.resolve(repoRoot, 'packages/theme/src/neutral'),
+ '@xds/theme': path.resolve(repoRoot, 'packages/theme/src'),
+ },
+ },
+ server: {port: 5173, strictPort: true},
+});
diff --git a/internal/vibe-tests/src/build-report.ts b/internal/vibe-tests/src/build-report.ts
new file mode 100644
index 0000000000..70dcb381ba
--- /dev/null
+++ b/internal/vibe-tests/src/build-report.ts
@@ -0,0 +1,228 @@
+#!/usr/bin/env node
+/**
+ * @file Build pipeline: eval β†’ data injection β†’ Vite build β†’ static HTML
+ *
+ * Orchestrates the full report generation pipeline.
+ *
+ * Usage:
+ * tsx src/build-report.ts --iteration <id>
+ * tsx src/build-report.ts --iteration <id> --baseline <id>
+ * tsx src/build-report.ts --iteration <id> --baseline <id> --with-screenshots
+ * tsx src/build-report.ts --iteration <id> --dev
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {execSync} from 'node:child_process';
+import {getResultsDir, readJson, writeJson, ensureDir} from './utils.js';
+import type {UniversalAggregate, UniversalComparison} from './types.js';
+
+const APP_DIR = path.join(import.meta.dirname, '..', 'app');
+
+function parseArgs(): {
+ iteration: string;
+ baseline?: string;
+ withScreenshots: boolean;
+ dev: boolean;
+} {
+ const args = process.argv.slice(2);
+ let iteration = '';
+ let baseline: string | undefined;
+ let withScreenshots = false;
+ let dev = false;
+
+ for (let i = 0; i < args.length; i++) {
+ if (args[i] === '--iteration' && args[i + 1]) {
+ iteration = args[i + 1];
+ i++;
+ } else if (args[i] === '--baseline' && args[i + 1]) {
+ baseline = args[i + 1];
+ i++;
+ } else if (args[i] === '--with-screenshots') {
+ withScreenshots = true;
+ } else if (args[i] === '--dev') {
+ dev = true;
+ }
+ }
+
+ if (!iteration) {
+ console.error(
+ 'Usage: tsx src/build-report.ts --iteration <id> [--baseline <id>] [--with-screenshots] [--dev]',
+ );
+ process.exit(1);
+ }
+
+ return {iteration, baseline, withScreenshots, dev};
+}
+
+function ensureUniversalJson(iteration: string): UniversalAggregate {
+ const resultsDir = getResultsDir();
+ const universalPath = path.join(resultsDir, iteration, 'universal.json');
+
+ if (!fs.existsSync(universalPath)) {
+ console.log(`Generating universal.json for ${iteration}...`);
+ execSync(
+ `tsx ${path.join(import.meta.dirname, 'universal-aggregate.ts')} --iteration ${iteration}`,
+ {cwd: path.join(import.meta.dirname, '..'), stdio: 'inherit'},
+ );
+ }
+
+ return readJson<UniversalAggregate>(universalPath);
+}
+
+function ensureComparison(
+ xdsId: string,
+ baselineId: string,
+): UniversalComparison {
+ const resultsDir = getResultsDir();
+ const comparisonPath = path.join(
+ resultsDir,
+ `comparison-${xdsId}-${baselineId}.json`,
+ );
+
+ if (!fs.existsSync(comparisonPath)) {
+ console.log(`Generating comparison for ${xdsId} vs ${baselineId}...`);
+ execSync(
+ `tsx ${path.join(import.meta.dirname, 'universal-compare.ts')} --xds ${xdsId} --baseline ${baselineId}`,
+ {cwd: path.join(import.meta.dirname, '..'), stdio: 'inherit'},
+ );
+ }
+
+ return readJson<UniversalComparison>(comparisonPath);
+}
+
+function generateReportData(opts: {
+ iteration: string;
+ iterationData: UniversalAggregate;
+ baseline?: string;
+ comparison?: UniversalComparison;
+ manifest: unknown;
+ screenshotPaths?: string[];
+}): string {
+ const lines: string[] = [
+ '// AUTO-GENERATED β€” do not edit',
+ '// Generated by build-report.ts',
+ '',
+ `export const iterationId = ${JSON.stringify(opts.iteration)};`,
+ '',
+ `export const iterationData = ${JSON.stringify(opts.iterationData, null, 2)} as const;`,
+ '',
+ `export const manifest = ${JSON.stringify(opts.manifest, null, 2)} as const;`,
+ '',
+ ];
+
+ if (opts.baseline && opts.comparison) {
+ lines.push(`export const baselineId = ${JSON.stringify(opts.baseline)};`);
+ lines.push('');
+ lines.push(
+ `export const comparison = ${JSON.stringify(opts.comparison, null, 2)} as const;`,
+ );
+ lines.push('');
+ } else {
+ lines.push('export const baselineId: string | undefined = undefined;');
+ lines.push('export const comparison: unknown = undefined;');
+ lines.push('');
+ }
+
+ if (opts.screenshotPaths && opts.screenshotPaths.length > 0) {
+ lines.push(
+ `export const screenshotPaths = ${JSON.stringify(opts.screenshotPaths)} as const;`,
+ );
+ } else {
+ lines.push('export const screenshotPaths: string[] = [];');
+ }
+
+ lines.push('');
+ return lines.join('\n');
+}
+
+async function main() {
+ const {iteration, baseline, withScreenshots, dev} = parseArgs();
+ const resultsDir = getResultsDir();
+ const iterDir = path.join(resultsDir, iteration);
+ const manifestPath = path.join(iterDir, 'manifest.json');
+
+ if (!fs.existsSync(manifestPath)) {
+ console.error(`No manifest.json found at ${manifestPath}`);
+ process.exit(1);
+ }
+
+ const manifest = readJson(manifestPath);
+
+ // Step 1: Ensure universal.json exists
+ console.log('πŸ“Š Step 1: Ensuring evaluation data...');
+ const iterationData = ensureUniversalJson(iteration);
+
+ // Step 2: If baseline provided, ensure comparison
+ let comparison: UniversalComparison | undefined;
+ if (baseline) {
+ console.log('πŸ“Š Step 2: Ensuring comparison data...');
+ ensureUniversalJson(baseline);
+ comparison = ensureComparison(iteration, baseline);
+ }
+
+ // Step 3: Collect screenshot paths
+ let screenshotPaths: string[] = [];
+ if (withScreenshots) {
+ const screenshotsDir = path.join(iterDir, 'screenshots');
+ if (fs.existsSync(screenshotsDir)) {
+ screenshotPaths = fs
+ .readdirSync(screenshotsDir)
+ .filter(f => f.endsWith('.png'))
+ .sort();
+ }
+ }
+
+ // Step 4: Generate report data module
+ console.log('πŸ“ Step 3: Generating report data module...');
+ const dataDir = path.join(APP_DIR, 'src', 'data');
+ ensureDir(dataDir);
+
+ const reportDataContent = generateReportData({
+ iteration,
+ iterationData,
+ baseline,
+ comparison,
+ manifest,
+ screenshotPaths,
+ });
+
+ fs.writeFileSync(path.join(dataDir, 'report-data.ts'), reportDataContent);
+ console.log(' βœ“ app/src/data/report-data.ts');
+
+ // Step 5: Dev mode or build
+ if (dev) {
+ console.log('\nπŸš€ Starting Vite dev server...');
+ const {createServer} = await import('vite');
+ const server = await createServer({
+ root: APP_DIR,
+ server: {port: 5173, strictPort: true},
+ });
+ await server.listen();
+ server.printUrls();
+ console.log('\nOpen http://localhost:5173?mode=report to view the report.');
+ console.log('Press Ctrl+C to stop.\n');
+ } else {
+ console.log('\nπŸ—οΈ Step 4: Building static report...');
+ execSync('npx vite build', {
+ cwd: APP_DIR,
+ stdio: 'inherit',
+ });
+
+ // Copy built report to results dir
+ const distDir = path.join(APP_DIR, 'dist');
+ const reportHtml = path.join(distDir, 'index.html');
+ if (fs.existsSync(reportHtml)) {
+ const destPath = path.join(iterDir, 'report.html');
+ fs.copyFileSync(reportHtml, destPath);
+ console.log(`\nβœ… Report saved to: ${destPath}`);
+ } else {
+ console.error('Build succeeded but no index.html found in dist/');
+ }
+ }
+}
+
+main().catch(err => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/internal/vibe-tests/src/screenshot.ts b/internal/vibe-tests/src/screenshot.ts
new file mode 100644
index 0000000000..cbc90a6d92
--- /dev/null
+++ b/internal/vibe-tests/src/screenshot.ts
@@ -0,0 +1,209 @@
+#!/usr/bin/env node
+/**
+ * @file Playwright screenshot pipeline for vibe test results
+ *
+ * Captures screenshots of generated components at multiple viewport/theme combos.
+ *
+ * Usage:
+ * tsx src/screenshot.ts --iteration <id>
+ * tsx src/screenshot.ts --iteration <id> --prompt <promptId>
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {getResultsDir, readJson, ensureDir} from './utils.js';
+
+const VIEWPORTS = {
+ desktop: {width: 1280, height: 800},
+ mobile: {width: 375, height: 812},
+};
+const THEMES = ['light', 'dark'] as const;
+const APP_DIR = path.join(import.meta.dirname, '..', 'app');
+const PREVIEW_PATH = path.join(APP_DIR, 'src', 'preview.tsx');
+
+function parseArgs(): {iteration: string; prompt?: string} {
+ const args = process.argv.slice(2);
+ let iteration = '';
+ let prompt: string | undefined;
+
+ for (let i = 0; i < args.length; i++) {
+ if (args[i] === '--iteration' && args[i + 1]) {
+ iteration = args[i + 1];
+ i++;
+ } else if (args[i] === '--prompt' && args[i + 1]) {
+ prompt = args[i + 1];
+ i++;
+ }
+ }
+
+ if (!iteration) {
+ console.error('Usage: tsx src/screenshot.ts --iteration <id> [--prompt <promptId>]');
+ process.exit(1);
+ }
+
+ return {iteration, prompt};
+}
+
+function generatePreviewCode(
+ componentPath: string,
+ target: 'xds' | 'baseline',
+): string {
+ const relPath = path.relative(path.join(APP_DIR, 'src'), componentPath);
+ const importPath = relPath.replace(/\.tsx$/, '').replace(/\\/g, '/');
+
+ if (target === 'xds') {
+ return `
+import React from 'react';
+import Component from '${importPath}';
+import XDSWrapper from './xds-wrapper';
+
+export default function Preview({ theme }: { theme: string }) {
+ return (
+ <XDSWrapper theme={theme}>
+ <Component />
+ </XDSWrapper>
+ );
+}
+`;
+ }
+
+ return `
+import React from 'react';
+import Component from '${importPath}';
+import BaselineWrapper from './baseline-wrapper';
+
+export default function Preview({ theme }: { theme: string }) {
+ return (
+ <BaselineWrapper theme={theme}>
+ <Component />
+ </BaselineWrapper>
+ );
+}
+`;
+}
+
+async function main() {
+ const {iteration, prompt: singlePrompt} = parseArgs();
+ const resultsDir = getResultsDir();
+ const iterDir = path.join(resultsDir, iteration);
+ const codeDir = path.join(iterDir, 'results');
+ const manifestPath = path.join(iterDir, 'manifest.json');
+ const screenshotsDir = path.join(iterDir, 'screenshots');
+
+ if (!fs.existsSync(manifestPath)) {
+ console.error(`No manifest.json found at ${manifestPath}`);
+ process.exit(1);
+ }
+
+ const manifest = readJson<{
+ config: {target: string};
+ prompts: Array<{id: string; category: string}>;
+ }>(manifestPath);
+
+ const target = manifest.config.target as 'xds' | 'baseline';
+
+ // Determine which prompts to screenshot
+ let promptIds = manifest.prompts.map(p => p.id);
+ if (singlePrompt) {
+ promptIds = promptIds.filter(id => id === singlePrompt);
+ if (promptIds.length === 0) {
+ console.error(`Prompt "${singlePrompt}" not found in manifest`);
+ process.exit(1);
+ }
+ }
+
+ // Filter to prompts with result files
+ promptIds = promptIds.filter(id =>
+ fs.existsSync(path.join(codeDir, `${id}.tsx`)),
+ );
+
+ if (promptIds.length === 0) {
+ console.error('No result .tsx files found for specified prompts');
+ process.exit(1);
+ }
+
+ // Try to import playwright
+ let chromium: typeof import('playwright').chromium;
+ try {
+ const pw = await import('playwright');
+ chromium = pw.chromium;
+ } catch {
+ console.error(
+ 'Playwright is not installed. Install it with:\n' +
+ ' npm install -D playwright\n' +
+ ' npx playwright install chromium\n',
+ );
+ process.exit(1);
+ }
+
+ // Save original preview.tsx
+ const originalPreview = fs.existsSync(PREVIEW_PATH)
+ ? fs.readFileSync(PREVIEW_PATH, 'utf-8')
+ : null;
+
+ ensureDir(screenshotsDir);
+
+ // Start Vite dev server
+ const {createServer} = await import('vite');
+ const server = await createServer({
+ root: APP_DIR,
+ server: {port: 5174, strictPort: true},
+ logLevel: 'silent',
+ });
+ await server.listen();
+ const serverUrl = 'http://localhost:5174';
+
+ console.log(`πŸ“Έ Capturing screenshots for ${promptIds.length} components...\n`);
+
+ const browser = await chromium.launch();
+
+ try {
+ for (const promptId of promptIds) {
+ const componentPath = path.join(codeDir, `${promptId}.tsx`);
+ const previewCode = generatePreviewCode(componentPath, target);
+ fs.writeFileSync(PREVIEW_PATH, previewCode);
+
+ // Wait for HMR to pick up the change
+ await new Promise(resolve => setTimeout(resolve, 1000));
+
+ for (const [viewportName, viewport] of Object.entries(VIEWPORTS)) {
+ for (const theme of THEMES) {
+ const page = await browser.newPage({viewport});
+ const url = `${serverUrl}?theme=${theme}`;
+ await page.goto(url, {waitUntil: 'networkidle'});
+
+ // Wait a bit for rendering
+ await page.waitForTimeout(500);
+
+ const filename = `${promptId}-${viewportName}-${theme}.png`;
+ const screenshotPath = path.join(screenshotsDir, filename);
+ await page.screenshot({path: screenshotPath, fullPage: true});
+ await page.close();
+
+ console.log(` βœ“ ${filename}`);
+ }
+ }
+ }
+ } finally {
+ await browser.close();
+ await server.close();
+
+ // Restore original preview.tsx
+ if (originalPreview !== null) {
+ fs.writeFileSync(PREVIEW_PATH, originalPreview);
+ } else {
+ // Write the default placeholder back
+ fs.writeFileSync(
+ PREVIEW_PATH,
+ `export default function Preview({ theme }: { theme: string }) {\n return <div>No component loaded.</div>;\n}\n`,
+ );
+ }
+ }
+
+ console.log(`\nβœ… Screenshots saved to: ${screenshotsDir}`);
+}
+
+main().catch(err => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/internal/vibe-tests/src/universal-aggregate.ts b/internal/vibe-tests/src/universal-aggregate.ts
new file mode 100644
index 0000000000..a7a2a2e73b
--- /dev/null
+++ b/internal/vibe-tests/src/universal-aggregate.ts
@@ -0,0 +1,329 @@
+#!/usr/bin/env node
+/**
+ * @file Universal aggregate scoring across 5 dimensions
+ *
+ * Scores an iteration's results using target-neutral evaluation.
+ *
+ * Usage:
+ * tsx src/universal-aggregate.ts --iteration <id>
+ * tsx src/universal-aggregate.ts --iteration <id> --json
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import type {
+ UniversalDimension,
+ UniversalScore,
+ UniversalAggregate,
+} from './types.js';
+import {getResultsDir, writeJson} from './utils.js';
+import {evaluate, getDimensionNames} from './universal-eval.js';
+
+const DIMENSION_LABELS: Record<UniversalDimension, string> = {
+ correctness: 'Correctness',
+ accessibility: 'Accessibility',
+ codeQuality: 'Code Quality',
+ efficiency: 'Efficiency',
+ maintainability: 'Maintainability',
+};
+
+function parseArgs(): {iteration: string; json: boolean} {
+ const args = process.argv.slice(2);
+ let iteration = '';
+ let json = false;
+
+ for (let i = 0; i < args.length; i++) {
+ if (args[i] === '--iteration' && args[i + 1]) {
+ iteration = args[i + 1];
+ i++;
+ } else if (args[i] === '--json') {
+ json = true;
+ }
+ }
+
+ if (!iteration) {
+ console.error(
+ 'Usage: tsx src/universal-aggregate.ts --iteration <id> [--json]',
+ );
+ process.exit(1);
+ }
+
+ return {iteration, json};
+}
+
+async function main() {
+ const {iteration, json} = parseArgs();
+ const resultsDir = getResultsDir();
+ const iterDir = path.join(resultsDir, iteration);
+ const codeDir = path.join(iterDir, 'results');
+ const manifestPath = path.join(iterDir, 'manifest.json');
+
+ if (!fs.existsSync(manifestPath)) {
+ console.error(`No manifest.json found at ${manifestPath}`);
+ process.exit(1);
+ }
+
+ if (!fs.existsSync(codeDir)) {
+ console.error(`No results directory found at ${codeDir}`);
+ process.exit(1);
+ }
+
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
+ const target = (manifest.config?.target || 'xds') as string;
+ const promptMap = new Map<string, string>(
+ (manifest.prompts || []).map((p: {id: string; category: string}) => [
+ p.id,
+ p.category,
+ ]),
+ );
+
+ // Load .tsx files
+ const files = fs.readdirSync(codeDir).filter(f => f.endsWith('.tsx'));
+
+ if (files.length === 0) {
+ console.error('No .tsx result files found');
+ process.exit(1);
+ }
+
+ const dimensions = getDimensionNames();
+ const byPrompt: Record<string, UniversalScore> = {};
+ const categoryScores: Record<
+ string,
+ Record<UniversalDimension, number[]>
+ > = {};
+ let darkModeCount = 0;
+
+ // Cost tracking
+ const costByPrompt: Record<
+ string,
+ {
+ durationMs: number;
+ outputChars: number;
+ outputLines: number;
+ docsRead: string[];
+ estimatedInputTokens: number;
+ estimatedOutputTokens: number;
+ }
+ > = {};
+
+ /** Rough doc size estimates in chars (for input token calculation) */
+ const DOC_CHAR_SIZES: Record<string, number> = {
+ 'AGENTS.md': 1200,
+ 'AGENTS.baseline.md': 740,
+ 'principles.md': 1130,
+ 'tokens.md': 3600,
+ };
+ const DEFAULT_DOC_SIZE = 2500; // avg component doc size
+
+ for (const file of files) {
+ const promptId = path.basename(file, '.tsx');
+ const codePath = path.join(codeDir, file);
+ const code = fs.readFileSync(codePath, 'utf-8');
+ const score = evaluate(code, target);
+ byPrompt[promptId] = score;
+
+ if (score.maintainability.metrics?.darkModeSupport) {
+ darkModeCount++;
+ }
+
+ const category = promptMap.get(promptId) ?? 'unknown';
+ if (!categoryScores[category]) {
+ categoryScores[category] = {} as Record<UniversalDimension, number[]>;
+ for (const dim of dimensions) {
+ categoryScores[category][dim] = [];
+ }
+ }
+ for (const dim of dimensions) {
+ categoryScores[category][dim].push(score[dim].score);
+ }
+
+ // --- Cost data ---
+ // Duration: infer from file timestamps (task creation β†’ result write)
+ let durationMs = 0;
+ const taskPath = path.join(iterDir, 'tasks', `${promptId}.json`);
+ if (fs.existsSync(taskPath)) {
+ const taskStat = fs.statSync(taskPath);
+ const resultStat = fs.statSync(codePath);
+ const inferred = resultStat.mtimeMs - taskStat.mtimeMs;
+ if (inferred > 0) durationMs = Math.round(inferred);
+ }
+
+ // Docs read: from companion .json file
+ let docsRead: string[] = [];
+ const jsonPath = path.join(codeDir, `${promptId}.json`);
+ if (fs.existsSync(jsonPath)) {
+ try {
+ const meta = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
+ docsRead = meta.docsRead || [];
+ } catch {
+ // ignore parse errors
+ }
+ }
+
+ // Estimate input tokens from docs read
+ let estimatedInputChars = 0;
+ for (const doc of docsRead) {
+ const key = doc.endsWith('.md') ? doc : `${doc}.md`;
+ estimatedInputChars += DOC_CHAR_SIZES[key] || DEFAULT_DOC_SIZE;
+ }
+ // Add prompt overhead (~1500 chars)
+ estimatedInputChars += 1500;
+
+ costByPrompt[promptId] = {
+ durationMs,
+ outputChars: code.length,
+ outputLines: code.split('\n').length,
+ docsRead,
+ estimatedInputTokens: Math.round(estimatedInputChars / 4),
+ estimatedOutputTokens: Math.round(code.length / 4),
+ };
+ }
+
+ // Compute averages
+ const promptCount = Object.keys(byPrompt).length;
+ const averages = {} as Record<UniversalDimension, number>;
+ for (const dim of dimensions) {
+ const scores = Object.values(byPrompt).map(s => s[dim].score);
+ averages[dim] = Math.round(
+ scores.reduce((a, b) => a + b, 0) / scores.length,
+ );
+ }
+
+ const overall = Math.round(
+ dimensions.reduce((s, d) => s + averages[d], 0) / dimensions.length,
+ );
+
+ // Category averages
+ const byCategory: Record<string, Record<UniversalDimension, number>> = {};
+ for (const [cat, dimScores] of Object.entries(categoryScores)) {
+ byCategory[cat] = {} as Record<UniversalDimension, number>;
+ for (const dim of dimensions) {
+ const scores = dimScores[dim];
+ byCategory[cat][dim] = Math.round(
+ scores.reduce((a, b) => a + b, 0) / scores.length,
+ );
+ }
+ }
+
+ const darkModeRate = Math.round((darkModeCount / promptCount) * 100);
+
+ // Compute cost aggregates
+ const costEntries = Object.values(costByPrompt);
+ const totalDurationMs = costEntries.reduce((s, c) => s + c.durationMs, 0);
+ const totalOutputChars = costEntries.reduce((s, c) => s + c.outputChars, 0);
+ const totalOutputLines = costEntries.reduce((s, c) => s + c.outputLines, 0);
+ const totalDocsRead = costEntries.reduce((s, c) => s + c.docsRead.length, 0);
+ const totalInputTokens = costEntries.reduce(
+ (s, c) => s + c.estimatedInputTokens,
+ 0,
+ );
+ const totalOutputTokens = costEntries.reduce(
+ (s, c) => s + c.estimatedOutputTokens,
+ 0,
+ );
+
+ const aggregate: UniversalAggregate = {
+ averages,
+ overall,
+ byPrompt,
+ byCategory,
+ darkModeRate,
+ cost: {
+ totalDurationMs,
+ avgDurationMs: Math.round(totalDurationMs / promptCount),
+ avgOutputChars: Math.round(totalOutputChars / promptCount),
+ avgOutputLines: Math.round(totalOutputLines / promptCount),
+ avgDocsRead: Math.round((totalDocsRead / promptCount) * 10) / 10,
+ estimatedInputTokens: totalInputTokens,
+ estimatedOutputTokens: totalOutputTokens,
+ byPrompt: costByPrompt,
+ },
+ };
+
+ // Save
+ const outputPath = path.join(iterDir, 'universal.json');
+ writeJson(outputPath, aggregate);
+
+ if (json) {
+ console.log(JSON.stringify(aggregate, null, 2));
+ return;
+ }
+
+ // Print formatted table
+ console.log(`\nπŸ“Š Universal Evaluation β€” Iteration ${iteration}`);
+ console.log(` ${promptCount} prompts, target: ${target}\n`);
+
+ console.log('β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”');
+ console.log('β”‚ Dimension β”‚ Score β”‚');
+ console.log('β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€');
+ for (const dim of dimensions) {
+ const label = DIMENSION_LABELS[dim].padEnd(19);
+ const score = String(averages[dim]).padStart(3);
+ console.log(`β”‚ ${label} β”‚ ${score} β”‚`);
+ }
+ console.log('β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€');
+ console.log(`β”‚ ${'Overall'.padEnd(19)} β”‚ ${String(overall).padStart(3)} β”‚`);
+ console.log('β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”˜');
+
+ console.log(`\nπŸŒ™ Dark Mode: ${darkModeRate}%`);
+
+ // Efficiency metrics summary
+ const allEfficiency = Object.values(byPrompt).map(s => s.efficiency.metrics!);
+ if (allEfficiency.length > 0) {
+ const avgDecisions =
+ allEfficiency.reduce((s, m) => s + m.decisionsPerElement, 0) /
+ allEfficiency.length;
+ const avgLines =
+ allEfficiency.reduce((s, m) => s + m.codeLines, 0) / allEfficiency.length;
+ console.log(`\n⚑ Efficiency:`);
+ console.log(` Avg decisions/element: ${avgDecisions.toFixed(1)}`);
+ console.log(` Avg code lines: ${Math.round(avgLines)}`);
+ }
+
+ // Maintainability metrics summary
+ const allMaint = Object.values(byPrompt).map(s => s.maintainability.metrics!);
+ if (allMaint.length > 0) {
+ const avgSemantic =
+ allMaint.reduce((s, m) => s + m.semanticRatio, 0) / allMaint.length;
+ const totalMagic = allMaint.reduce((s, m) => s + m.magicValueCount, 0);
+ console.log(`\nπŸ”§ Maintainability:`);
+ console.log(` Semantic ratio: ${(avgSemantic * 100).toFixed(0)}%`);
+ console.log(` Magic values: ${totalMagic}`);
+ }
+
+ // Cost metrics
+ if (aggregate.cost && aggregate.cost.totalDurationMs > 0) {
+ const c = aggregate.cost;
+ console.log(`\nπŸ’° Cost:`);
+ console.log(
+ ` Duration: ${(c.totalDurationMs / 1000).toFixed(1)}s total, ${(c.avgDurationMs / 1000).toFixed(1)}s avg`,
+ );
+ console.log(
+ ` Output: ${c.avgOutputLines} lines avg (${c.avgOutputChars} chars)`,
+ );
+ console.log(` Docs read: ${c.avgDocsRead} avg per prompt`);
+ console.log(
+ ` Tokens: ~${c.estimatedInputTokens} input, ~${c.estimatedOutputTokens} output`,
+ );
+ }
+
+ // Category breakdown
+ const categories = Object.keys(byCategory).sort();
+ if (categories.length > 1) {
+ console.log('\nπŸ“‚ By Category:');
+ for (const cat of categories) {
+ const catOverall = Math.round(
+ dimensions.reduce((s, d) => s + byCategory[cat][d], 0) /
+ dimensions.length,
+ );
+ console.log(` ${cat.padEnd(25)} ${catOverall}`);
+ }
+ }
+
+ console.log(`\nSaved: ${outputPath}\n`);
+}
+
+main().catch(err => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/internal/vibe-tests/src/universal-compare.ts b/internal/vibe-tests/src/universal-compare.ts
new file mode 100644
index 0000000000..f7b285f097
--- /dev/null
+++ b/internal/vibe-tests/src/universal-compare.ts
@@ -0,0 +1,261 @@
+#!/usr/bin/env node
+/**
+ * @file Universal Compare β€” side-by-side comparison of two iterations
+ *
+ * Usage:
+ * tsx src/universal-compare.ts --xds abc123 --baseline def456
+ * tsx src/universal-compare.ts --xds abc123 --baseline def456 --json
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {execSync} from 'node:child_process';
+import type {
+ UniversalAggregate,
+ UniversalComparison,
+ UniversalDimension,
+} from './types.js';
+import {writeJson, getResultsDir} from './utils.js';
+import {getDimensionNames, getAverageScore} from './universal-eval.js';
+
+const DIMENSION_LABELS: Record<UniversalDimension, string> = {
+ correctness: 'Correctness',
+ accessibility: 'Accessibility',
+ codeQuality: 'Code Quality',
+ efficiency: 'Efficiency',
+ maintainability: 'Maintainability',
+};
+
+function loadOrGenerate(iterationId: string): UniversalAggregate {
+ const universalPath = path.join(
+ getResultsDir(),
+ iterationId,
+ 'universal.json',
+ );
+
+ if (fs.existsSync(universalPath)) {
+ return JSON.parse(fs.readFileSync(universalPath, 'utf-8'));
+ }
+
+ console.log(`⏳ Generating universal.json for ${iterationId}...`);
+ const scriptPath = path.join(import.meta.dirname, 'universal-aggregate.ts');
+ execSync(`npx tsx ${scriptPath} --iteration ${iterationId}`, {
+ stdio: 'inherit',
+ cwd: path.join(import.meta.dirname, '..'),
+ });
+
+ return JSON.parse(fs.readFileSync(universalPath, 'utf-8'));
+}
+
+function winner(a: number, b: number): 'xds' | 'baseline' | 'tie' {
+ if (a > b) return 'xds';
+ if (b > a) return 'baseline';
+ return 'tie';
+}
+
+function winnerIcon(w: 'xds' | 'baseline' | 'tie'): string {
+ switch (w) {
+ case 'xds':
+ return '🟒 XDS';
+ case 'baseline':
+ return 'πŸ”΅ Base';
+ case 'tie':
+ return 'βšͺ Tie';
+ }
+}
+
+function parseArgs(): {xds: string; baseline: string; json: boolean} {
+ const args = process.argv.slice(2);
+ let xds = '';
+ let baseline = '';
+ let json = false;
+
+ for (let i = 0; i < args.length; i++) {
+ if ((args[i] === '--xds' || args[i] === '-x') && args[i + 1]) {
+ xds = args[++i];
+ } else if ((args[i] === '--baseline' || args[i] === '-b') && args[i + 1]) {
+ baseline = args[++i];
+ } else if (args[i] === '--json') {
+ json = true;
+ }
+ }
+
+ if (!xds || !baseline) {
+ console.error(
+ 'Usage: tsx src/universal-compare.ts --xds <id> --baseline <id> [--json]',
+ );
+ process.exit(1);
+ }
+
+ return {xds, baseline, json};
+}
+
+async function main() {
+ const {xds: xdsId, baseline: baselineId, json} = parseArgs();
+
+ const xds = loadOrGenerate(xdsId);
+ const baseline = loadOrGenerate(baselineId);
+
+ const dimensions = getDimensionNames();
+
+ // Build comparison
+ const winners = {} as Record<UniversalDimension, 'xds' | 'baseline' | 'tie'>;
+ for (const d of dimensions) {
+ winners[d] = winner(xds.averages[d], baseline.averages[d]);
+ }
+
+ // Per-prompt comparison
+ const allPromptIds = new Set([
+ ...Object.keys(xds.byPrompt),
+ ...Object.keys(baseline.byPrompt),
+ ]);
+
+ const byPrompt: UniversalComparison['byPrompt'] = {};
+ for (const promptId of allPromptIds) {
+ const xdsScore = xds.byPrompt[promptId];
+ const baselineScore = baseline.byPrompt[promptId];
+ if (xdsScore && baselineScore) {
+ byPrompt[promptId] = {
+ xds: xdsScore,
+ baseline: baselineScore,
+ winner: winner(
+ getAverageScore(xdsScore),
+ getAverageScore(baselineScore),
+ ),
+ };
+ }
+ }
+
+ const comparison: UniversalComparison = {xds, baseline, winners, byPrompt};
+
+ // Save
+ const outputPath = path.join(
+ getResultsDir(),
+ `comparison-${xdsId}-${baselineId}.json`,
+ );
+ writeJson(outputPath, comparison);
+
+ if (json) {
+ console.log(JSON.stringify(comparison, null, 2));
+ return;
+ }
+
+ // --- Print report ---
+
+ console.log(`\nπŸ“Š Universal Comparison: XDS vs Baseline`);
+ console.log('═'.repeat(52));
+
+ // Dimension table
+ console.log('β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”');
+ console.log('β”‚ Dimension β”‚ XDS β”‚ Baseline β”‚ Winner β”‚');
+ console.log('β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€');
+ for (const d of dimensions) {
+ const label = DIMENSION_LABELS[d].padEnd(19);
+ const xScore = String(xds.averages[d]).padStart(3);
+ const bScore = String(baseline.averages[d]).padStart(3);
+ const w = winnerIcon(winners[d]).padEnd(8);
+ console.log(`β”‚ ${label} β”‚ ${xScore} β”‚ ${bScore} β”‚ ${w} β”‚`);
+ }
+ console.log('β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€');
+ const xOverall = String(xds.overall).padStart(3);
+ const bOverall = String(baseline.overall).padStart(3);
+ const overallW = winnerIcon(winner(xds.overall, baseline.overall)).padEnd(8);
+ console.log(
+ `β”‚ ${'Overall'.padEnd(19)} β”‚ ${xOverall} β”‚ ${bOverall} β”‚ ${overallW} β”‚`,
+ );
+ console.log('β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜');
+
+ // Dark mode
+ console.log(
+ `\nπŸŒ™ Dark Mode: XDS ${xds.darkModeRate}% | Baseline ${baseline.darkModeRate}%`,
+ );
+
+ // Efficiency metrics comparison
+ const xdsEff = Object.values(xds.byPrompt).map(s => s.efficiency.metrics!);
+ const baseEff = Object.values(baseline.byPrompt).map(
+ s => s.efficiency.metrics!,
+ );
+ if (xdsEff.length > 0 && baseEff.length > 0) {
+ const xDpe =
+ xdsEff.reduce((s, m) => s + m.decisionsPerElement, 0) / xdsEff.length;
+ const bDpe =
+ baseEff.reduce((s, m) => s + m.decisionsPerElement, 0) / baseEff.length;
+ const xLines = xdsEff.reduce((s, m) => s + m.codeLines, 0) / xdsEff.length;
+ const bLines =
+ baseEff.reduce((s, m) => s + m.codeLines, 0) / baseEff.length;
+ console.log(`\n⚑ Efficiency Metrics:`);
+ console.log(
+ ` Decisions/element: XDS ${xDpe.toFixed(1)} | Baseline ${bDpe.toFixed(1)} | ${winnerIcon(winner(bDpe, xDpe))}`,
+ );
+ console.log(
+ ` Avg code lines: XDS ${Math.round(xLines)} | Baseline ${Math.round(bLines)} | ${winnerIcon(winner(bLines, xLines))}`,
+ );
+ }
+
+ // Maintainability metrics comparison
+ const xdsMaint = Object.values(xds.byPrompt).map(
+ s => s.maintainability.metrics!,
+ );
+ const baseMaint = Object.values(baseline.byPrompt).map(
+ s => s.maintainability.metrics!,
+ );
+ if (xdsMaint.length > 0 && baseMaint.length > 0) {
+ const xSem =
+ xdsMaint.reduce((s, m) => s + m.semanticRatio, 0) / xdsMaint.length;
+ const bSem =
+ baseMaint.reduce((s, m) => s + m.semanticRatio, 0) / baseMaint.length;
+ const xMagic = xdsMaint.reduce((s, m) => s + m.magicValueCount, 0);
+ const bMagic = baseMaint.reduce((s, m) => s + m.magicValueCount, 0);
+ console.log(`\nπŸ”§ Maintainability Metrics:`);
+ console.log(
+ ` Semantic ratio: XDS ${(xSem * 100).toFixed(0)}% | Baseline ${(bSem * 100).toFixed(0)}% | ${winnerIcon(winner(xSem, bSem))}`,
+ );
+ console.log(
+ ` Magic values: XDS ${xMagic} | Baseline ${bMagic} | ${winnerIcon(winner(bMagic, xMagic))}`,
+ );
+ }
+
+ // Cost comparison
+ if (xds.cost && baseline.cost) {
+ console.log(`\nπŸ’° Cost:`);
+ const xAvgMs = xds.cost.avgDurationMs;
+ const bAvgMs = baseline.cost.avgDurationMs;
+ if (xAvgMs > 0 && bAvgMs > 0) {
+ console.log(
+ ` Avg duration: XDS ${(xAvgMs / 1000).toFixed(1)}s | Baseline ${(bAvgMs / 1000).toFixed(1)}s | ${winnerIcon(winner(bAvgMs, xAvgMs))}`,
+ );
+ }
+ console.log(
+ ` Avg output lines: XDS ${xds.cost.avgOutputLines} | Baseline ${baseline.cost.avgOutputLines} | ${winnerIcon(winner(baseline.cost.avgOutputLines, xds.cost.avgOutputLines))}`,
+ );
+ console.log(
+ ` Avg docs read: XDS ${xds.cost.avgDocsRead} | Baseline ${baseline.cost.avgDocsRead}`,
+ );
+ console.log(
+ ` Est. tokens: XDS ~${xds.cost.estimatedInputTokens + xds.cost.estimatedOutputTokens} | Baseline ~${baseline.cost.estimatedInputTokens + baseline.cost.estimatedOutputTokens} | ${winnerIcon(winner(baseline.cost.estimatedInputTokens + baseline.cost.estimatedOutputTokens, xds.cost.estimatedInputTokens + xds.cost.estimatedOutputTokens))}`,
+ );
+ }
+
+ // Per-prompt wins
+ const promptEntries = Object.entries(byPrompt);
+ if (promptEntries.length > 0) {
+ let xWins = 0;
+ let bWins = 0;
+ let ties = 0;
+ for (const [, data] of promptEntries) {
+ if (data.winner === 'xds') xWins++;
+ else if (data.winner === 'baseline') bWins++;
+ else ties++;
+ }
+ console.log(
+ `\nπŸ“ Per-Prompt: XDS wins ${xWins} | Baseline wins ${bWins} | Ties ${ties} (${promptEntries.length} prompts)`,
+ );
+ }
+
+ console.log(`\nSaved: ${outputPath}\n`);
+}
+
+main().catch(err => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/internal/vibe-tests/src/universal-eval.ts b/internal/vibe-tests/src/universal-eval.ts
new file mode 100644
index 0000000000..3a57be94da
--- /dev/null
+++ b/internal/vibe-tests/src/universal-eval.ts
@@ -0,0 +1,1096 @@
+/**
+ * @file Universal Evaluation β€” target-neutral static analysis
+ *
+ * Scores generated code across 5 dimensions on a 0-100 scale.
+ * All analyzers are pure functions: (code, target) β†’ score.
+ * No LLM calls β€” deterministic and fast.
+ *
+ * Dimensions:
+ * 1. Correctness β€” Does it work? (hallucinations, valid APIs)
+ * 2. Accessibility β€” Is it usable by everyone? (labels, semantics)
+ * 3. Code Quality β€” Is the code well-structured? (complexity, patterns)
+ * 4. Efficiency β€” How much ceremony vs intent? (DRY + conciseness + decisions/element)
+ * 5. Maintainability β€” How much breaks on change? (coupling, magic values, locality)
+ */
+
+import type {
+ UniversalScore,
+ UniversalDimension,
+ UniversalFinding,
+ DimensionScore,
+ EfficiencyMetrics,
+ MaintainabilityMetrics,
+} from './types.js';
+
+function clamp(n: number): number {
+ return Math.max(0, Math.min(100, Math.round(n)));
+}
+
+// ============================================================
+// Known component catalogs
+// ============================================================
+
+/**
+ * Auto-discover XDS components from the core package source.
+ * Falls back to a hardcoded list if the source isn't available.
+ */
+function discoverXDSComponents(): Set<string> {
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const fs = require('node:fs');
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const path = require('node:path');
+ const candidates = [
+ path.resolve(import.meta.dirname, '../../../packages/core/src'),
+ path.resolve(import.meta.dirname, '../../../../packages/core/src'),
+ ];
+ for (const srcDir of candidates) {
+ if (fs.existsSync(srcDir)) {
+ const components = new Set<string>();
+ function scan(dir: string) {
+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
+ if (
+ entry.isDirectory() &&
+ !entry.name.startsWith('_') &&
+ entry.name !== 'node_modules'
+ ) {
+ scan(path.join(dir, entry.name));
+ } else if (
+ /^XDS[A-Z]\w+\.tsx$/.test(entry.name) &&
+ !entry.name.includes('.test.')
+ ) {
+ components.add(entry.name.replace('.tsx', ''));
+ }
+ }
+ }
+ scan(srcDir);
+ components.add('Theme');
+ components.add('defaultTheme');
+ components.add('darkTheme');
+ return components;
+ }
+ }
+ } catch {
+ // Fall through to hardcoded list
+ }
+ return new Set([
+ 'XDSAspectRatio',
+ 'XDSAvatar',
+ 'XDSBadge',
+ 'XDSBanner',
+ 'XDSBaseTable',
+ 'XDSBreadcrumbs',
+ 'XDSBreadcrumbItem',
+ 'XDSButton',
+ 'XDSCalendar',
+ 'XDSCard',
+ 'XDSCenter',
+ 'XDSCheckboxInput',
+ 'XDSCloseButton',
+ 'XDSDateInput',
+ 'XDSDialog',
+ 'XDSDialogHeader',
+ 'XDSDivider',
+ 'XDSDropdownMenu',
+ 'XDSDropdownMenuItem',
+ 'XDSEmptyState',
+ 'XDSField',
+ 'XDSFieldLabel',
+ 'XDSFieldStatus',
+ 'XDSFontWrapper',
+ 'XDSGrid',
+ 'XDSGridSpan',
+ 'XDSHStack',
+ 'XDSHeading',
+ 'XDSHoverCard',
+ 'XDSIcon',
+ 'XDSLayer',
+ 'XDSLayout',
+ 'XDSLayoutContent',
+ 'XDSLayoutFooter',
+ 'XDSLayoutHeader',
+ 'XDSLayoutPanel',
+ 'XDSLink',
+ 'XDSNumberInput',
+ 'XDSProgressBar',
+ 'XDSRadioList',
+ 'XDSRadioListItem',
+ 'XDSSection',
+ 'XDSSelector',
+ 'XDSSelectorItem',
+ 'XDSSkeleton',
+ 'XDSSlider',
+ 'XDSSpinner',
+ 'XDSStack',
+ 'XDSStackItem',
+ 'XDSStatusDot',
+ 'XDSSwitch',
+ 'XDSTab',
+ 'XDSTabList',
+ 'XDSTabMenu',
+ 'XDSTable',
+ 'XDSTableCell',
+ 'XDSTableHeaderCell',
+ 'XDSTableRow',
+ 'XDSText',
+ 'XDSTextArea',
+ 'XDSTextInput',
+ 'XDSTheme',
+ 'XDSTimeInput',
+ 'XDSTooltip',
+ 'XDSTopNav',
+ 'XDSTopNavItem',
+ 'XDSTopNavMenu',
+ 'XDSTopNavTitle',
+ 'XDSTopNavTitleIcon',
+ 'XDSVStack',
+ 'Theme',
+ 'defaultTheme',
+ 'darkTheme',
+ ]);
+}
+
+const KNOWN_XDS_COMPONENTS = discoverXDSComponents();
+
+const KNOWN_BASELINE_COMPONENTS = new Set([
+ 'Button',
+ 'Input',
+ 'Label',
+ 'Card',
+ 'CardHeader',
+ 'CardTitle',
+ 'CardDescription',
+ 'CardContent',
+ 'CardFooter',
+ 'Table',
+ 'TableHeader',
+ 'TableBody',
+ 'TableRow',
+ 'TableHead',
+ 'TableCell',
+ 'TableCaption',
+ 'Dialog',
+ 'DialogTrigger',
+ 'DialogContent',
+ 'DialogHeader',
+ 'DialogTitle',
+ 'DialogDescription',
+ 'DialogFooter',
+ 'Popover',
+ 'PopoverTrigger',
+ 'PopoverContent',
+ 'Select',
+ 'SelectTrigger',
+ 'SelectValue',
+ 'SelectContent',
+ 'SelectItem',
+ 'Checkbox',
+ 'Badge',
+ 'Avatar',
+ 'AvatarImage',
+ 'AvatarFallback',
+ 'Tabs',
+ 'TabsList',
+ 'TabsTrigger',
+ 'TabsContent',
+ 'Command',
+ 'CommandInput',
+ 'CommandList',
+ 'CommandEmpty',
+ 'CommandGroup',
+ 'CommandItem',
+ 'DropdownMenu',
+ 'DropdownMenuTrigger',
+ 'DropdownMenuContent',
+ 'DropdownMenuItem',
+ 'DropdownMenuLabel',
+ 'DropdownMenuSeparator',
+ 'Tooltip',
+ 'TooltipProvider',
+ 'TooltipTrigger',
+ 'TooltipContent',
+ 'Switch',
+ 'Slider',
+ 'Progress',
+ 'Skeleton',
+ 'Textarea',
+ 'HoverCard',
+ 'HoverCardTrigger',
+ 'HoverCardContent',
+ 'Sheet',
+ 'SheetTrigger',
+ 'SheetContent',
+ 'ScrollArea',
+ 'Separator',
+ 'Collapsible',
+ 'CollapsibleTrigger',
+ 'CollapsibleContent',
+]);
+
+// ============================================================
+// 1. Correctness
+// ============================================================
+
+function analyzeCorrectness(code: string, target: string): DimensionScore {
+ const findings: UniversalFinding[] = [];
+
+ if (target === 'xds') {
+ // Flag unknown XDS components
+ const seen = new Set<string>();
+ const xdsRe = /\bXDS\w+/g;
+ let m: RegExpExecArray | null;
+ while ((m = xdsRe.exec(code)) !== null) {
+ const name = m[0];
+ if (!seen.has(name) && !KNOWN_XDS_COMPONENTS.has(name)) {
+ seen.add(name);
+ findings.push({
+ rule: 'unknown-component',
+ severity: 'critical',
+ detail: `Unknown XDS component: ${name}`,
+ line: code.slice(0, m.index).split('\n').length,
+ });
+ }
+ }
+
+ // Flag hallucinated CSS variables
+ const hallVarRe =
+ /var\((--xds-[\w-]+|--font-size-[\w-]+|--font-family-[\w-]+|--border-[\w-]+|--shadow-[\w-]+)\)/g;
+ const seenVars = new Set<string>();
+ while ((m = hallVarRe.exec(code)) !== null) {
+ if (!seenVars.has(m[1])) {
+ seenVars.add(m[1]);
+ findings.push({
+ rule: 'hallucinated-token',
+ severity: 'critical',
+ detail: `Hallucinated CSS variable: ${m[1]}`,
+ line: code.slice(0, m.index).split('\n').length,
+ });
+ }
+ }
+ } else if (target === 'baseline') {
+ // Flag unknown baseline components
+ const uiImportRe =
+ /import\s*\{([^}]+)\}\s*from\s*['"]@\/components\/ui\/[^'"]+['"]/g;
+ let m: RegExpExecArray | null;
+ while ((m = uiImportRe.exec(code)) !== null) {
+ const names = m[1]
+ .split(',')
+ .map(s => s.replace(/\s+as\s+\w+/, '').trim())
+ .filter(Boolean);
+ for (const name of names) {
+ if (!KNOWN_BASELINE_COMPONENTS.has(name)) {
+ findings.push({
+ rule: 'unknown-component',
+ severity: 'critical',
+ detail: `Unknown baseline component: ${name}`,
+ line: code.slice(0, m.index).split('\n').length,
+ });
+ }
+ }
+ }
+ }
+
+ // Missing export
+ if (!/export\s+(default|function|const|class)/.test(code)) {
+ findings.push({
+ rule: 'missing-export',
+ severity: 'minor',
+ detail: 'No export statement found',
+ });
+ }
+
+ // Score
+ let score = 100;
+ for (const f of findings) {
+ switch (f.severity) {
+ case 'critical':
+ score -= 20;
+ break;
+ case 'moderate':
+ score -= 8;
+ break;
+ case 'minor':
+ score -= 3;
+ break;
+ }
+ }
+
+ return {score: clamp(score), findings};
+}
+
+// ============================================================
+// 2. Accessibility
+// ============================================================
+
+function analyzeAccessibility(code: string): DimensionScore {
+ const findings: UniversalFinding[] = [];
+ const lines = code.split('\n');
+
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ const lineNum = i + 1;
+ const nearby = lines
+ .slice(Math.max(0, i - 2), Math.min(i + 4, lines.length))
+ .join(' ');
+
+ // onClick on non-interactive elements without role/tabIndex
+ const clickMatch = line.match(
+ /<(span|div|p|td|tr|li|img|svg)\b[^>]*\bonClick\b/i,
+ );
+ if (clickMatch) {
+ if (
+ !nearby.includes('role="button"') &&
+ !nearby.includes("role='button'") &&
+ !nearby.includes('tabIndex')
+ ) {
+ findings.push({
+ rule: 'click-non-interactive',
+ severity: 'critical',
+ detail: `onClick on <${clickMatch[1]}> without role="button" or tabIndex`,
+ line: lineNum,
+ });
+ }
+ }
+
+ // Icon-only buttons missing aria-label
+ if (line.match(/<(button|Button|XDSButton)\b/)) {
+ const btnContext = lines
+ .slice(i, Math.min(i + 5, lines.length))
+ .join(' ');
+ const hasIcon = /(<svg|Icon|icon)/.test(btnContext);
+ const hasLabel = /(aria-label|ariaLabel|label=)/.test(btnContext);
+ const hasText = />[^<]*\w{2,}[^<]*</.test(btnContext);
+ if (hasIcon && !hasLabel && !hasText) {
+ findings.push({
+ rule: 'icon-button-no-label',
+ severity: 'critical',
+ detail: 'Icon-only button missing aria-label',
+ line: lineNum,
+ });
+ }
+ }
+
+ // Form inputs without labels (skip XDS inputs with built-in labels)
+ if (line.match(/<(input|Input)\b/) && !line.includes('type="hidden"')) {
+ const isXdsInput = /XDS(TextInput|NumberInput|DateInput|TimeInput)/.test(
+ nearby,
+ );
+ if (!isXdsInput) {
+ const hasLabel = /(label|Label|aria-label|ariaLabel)/.test(nearby);
+ if (!hasLabel) {
+ findings.push({
+ rule: 'input-no-label',
+ severity: 'critical',
+ detail: 'Form input without associated label',
+ line: lineNum,
+ });
+ }
+ }
+ }
+
+ // Images without alt
+ if (line.includes('<img') && !line.includes('alt=')) {
+ findings.push({
+ rule: 'img-no-alt',
+ severity: 'moderate',
+ detail: 'Image without alt text',
+ line: lineNum,
+ });
+ }
+ }
+
+ // Heading hierarchy
+ const headingLevels: number[] = [];
+ for (const line of lines) {
+ const h = line.match(/<h([1-6])\b/i);
+ if (h) headingLevels.push(parseInt(h[1]));
+ const xh = line.match(/level\s*=\s*\{?\s*(\d)\s*\}?/);
+ if (xh && line.includes('Heading')) headingLevels.push(parseInt(xh[1]));
+ }
+ for (let i = 1; i < headingLevels.length; i++) {
+ if (headingLevels[i] > headingLevels[i - 1] + 1) {
+ findings.push({
+ rule: 'heading-skip',
+ severity: 'minor',
+ detail: `Heading level skipped: h${headingLevels[i - 1]} β†’ h${headingLevels[i]}`,
+ });
+ }
+ }
+
+ let score = 100;
+ for (const f of findings) {
+ switch (f.severity) {
+ case 'critical':
+ score -= 15;
+ break;
+ case 'moderate':
+ score -= 8;
+ break;
+ case 'minor':
+ score -= 3;
+ break;
+ }
+ }
+
+ return {score: clamp(score), findings};
+}
+
+// ============================================================
+// 3. Code Quality
+// ============================================================
+
+function analyzeCodeQuality(code: string): DimensionScore {
+ const findings: UniversalFinding[] = [];
+ const lines = code.split('\n');
+
+ let maxNesting = 0;
+ let currentNesting = 0;
+ let branchCount = 0;
+ let inFunction = false;
+ let functionStart = 0;
+ let functionNesting = 0;
+
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ const stripped = line.trim();
+ const lineNum = i + 1;
+
+ // Nesting
+ currentNesting +=
+ (line.match(/\{/g) || []).length - (line.match(/\}/g) || []).length;
+ maxNesting = Math.max(maxNesting, currentNesting);
+
+ // Function tracking
+ if (
+ stripped.match(
+ /^(export\s+)?(default\s+)?function\s|^(export\s+)?const\s+\w+\s*=.*=>/,
+ )
+ ) {
+ inFunction = true;
+ functionStart = i;
+ functionNesting = currentNesting;
+ }
+ if (inFunction && currentNesting < functionNesting) {
+ const len = i - functionStart;
+ if (len > 100) {
+ findings.push({
+ rule: 'long-function',
+ severity: 'moderate',
+ detail: `Function is ${len} lines`,
+ line: functionStart + 1,
+ });
+ }
+ inFunction = false;
+ }
+
+ // Branches
+ if (stripped.match(/^(if|else if|else|case|catch)\b/)) branchCount++;
+ branchCount += (line.match(/\?[^?:]/g) || []).length; // ternaries
+
+ // TypeScript any
+ if (stripped.match(/:\s*any\b/) || stripped.match(/as\s+any\b/)) {
+ findings.push({
+ rule: 'typescript-any',
+ severity: 'minor',
+ detail: 'Use of `any` type',
+ line: lineNum,
+ });
+ }
+
+ // console.log
+ if (stripped.includes('console.log(')) {
+ findings.push({
+ rule: 'console-log',
+ severity: 'minor',
+ detail: 'console.log left in code',
+ line: lineNum,
+ });
+ }
+
+ // Missing key in .map()
+ if (line.includes('.map(')) {
+ const mapCtx = lines.slice(i, Math.min(i + 5, lines.length)).join(' ');
+ if (
+ !mapCtx.includes('key=') &&
+ !mapCtx.includes('key:') &&
+ mapCtx.includes('<')
+ ) {
+ findings.push({
+ rule: 'missing-key',
+ severity: 'moderate',
+ detail: 'Array .map() without key prop',
+ line: lineNum,
+ });
+ }
+ }
+
+ // Index as key
+ if (line.match(/key\s*=\s*\{?\s*(index|i|idx)\s*\}?/)) {
+ findings.push({
+ rule: 'index-key',
+ severity: 'minor',
+ detail: 'Array index as key',
+ line: lineNum,
+ });
+ }
+ }
+
+ if (maxNesting > 6) {
+ findings.push({
+ rule: 'deep-nesting',
+ severity: 'moderate',
+ detail: `Max nesting depth: ${maxNesting}`,
+ });
+ }
+ if (branchCount > 15) {
+ findings.push({
+ rule: 'high-complexity',
+ severity: 'moderate',
+ detail: `Cyclomatic complexity: ${branchCount}`,
+ });
+ }
+
+ let score = 100;
+ for (const f of findings) {
+ switch (f.severity) {
+ case 'critical':
+ score -= 15;
+ break;
+ case 'moderate':
+ score -= 8;
+ break;
+ case 'minor':
+ score -= 3;
+ break;
+ }
+ }
+
+ return {score: clamp(score), findings};
+}
+
+// ============================================================
+// 4. Efficiency (merges DRYness + Conciseness + decisions/element)
+// ============================================================
+
+/**
+ * Check if a normalized line is component/prop usage (not real duplication).
+ */
+function isComponentUsageLine(normalizedLine: string): boolean {
+ if (/^<\/?[A-Z]\w*/.test(normalizedLine)) return true;
+ if (/^<\/[A-Z]\w*>$/.test(normalizedLine)) return true;
+ if (/^<[A-Z]\w*\s.*\/>$/.test(normalizedLine)) return true;
+ if (/^\w+=/.test(normalizedLine) && normalizedLine.length < 40) return true;
+ if (/^\w+:\s*\w+Vars\[/.test(normalizedLine)) return true;
+ return false;
+}
+
+function normalizeLine(line: string): string {
+ return line
+ .replace(/(["'`])(?:(?!\1).)*\1/g, '"_"')
+ .replace(/\b\d+(\.\d+)?\b/g, 'N')
+ .replace(/\s+/g, ' ')
+ .trim();
+}
+
+/**
+ * Count unique UI elements in the code (JSX tags that render visible output).
+ */
+function countElements(code: string): number {
+ const elements = new Set<string>();
+ // Match opening JSX tags (both component and HTML)
+ const tagRe = /<([A-Za-z]\w*)[\s>]/g;
+ let m: RegExpExecArray | null;
+ while ((m = tagRe.exec(code)) !== null) {
+ const tag = m[1];
+ // Skip non-visual tags
+ if (
+ ['React', 'Fragment', 'StrictMode', 'Suspense', 'ErrorBoundary'].includes(
+ tag,
+ )
+ )
+ continue;
+ // Skip wrapper/provider tags
+ if (/(Provider|Context|Theme|Wrapper)$/.test(tag)) continue;
+ elements.add(`${tag}-${m.index}`); // unique by position
+ }
+ return elements.size;
+}
+
+/**
+ * Count styling decisions β€” individual props, className tokens, or style properties
+ * that determine visual appearance.
+ */
+function countStylingDecisions(code: string, target: string): number {
+ let count = 0;
+
+ if (target === 'xds') {
+ // Component props that are styling decisions: variant, size, gap, color, type
+ count += (
+ code.match(
+ /\b(variant|size|gap|color|type|level|weight|crossAlign|mainAlign)\s*=\s*/g,
+ ) || []
+ ).length;
+ // StyleX properties (each key: value in stylex.create)
+ const stylexBlocks = code.match(/stylex\.create\(\{[\s\S]*?\}\)/g) || [];
+ for (const block of stylexBlocks) {
+ count += (block.match(/\w+\s*:/g) || []).length;
+ }
+ } else if (target === 'baseline') {
+ // Tailwind classes β€” each utility class is a decision
+ const classNames = code.match(/className\s*=\s*["']([^"']+)["']/g) || [];
+ for (const cn of classNames) {
+ const classes = cn
+ .replace(/className\s*=\s*["']/, '')
+ .replace(/["']$/, '');
+ count += classes.split(/\s+/).filter(Boolean).length;
+ }
+ // cn() calls
+ const cnCalls = code.match(/cn\([^)]+\)/g) || [];
+ for (const call of cnCalls) {
+ count += (call.match(/["'][^"']+["']/g) || []).length;
+ }
+ // Component variant/size props
+ count += (code.match(/\b(variant|size)\s*=\s*/g) || []).length;
+ } else {
+ // Raw HTML β€” inline style properties
+ const styleBlocks = code.match(/style\s*=\s*\{\{([^}]+)\}\}/g) || [];
+ for (const block of styleBlocks) {
+ count += (block.match(/\w+\s*:/g) || []).length;
+ }
+ // CSS class assignments
+ count += (code.match(/className\s*=\s*/g) || []).length;
+ }
+
+ return count;
+}
+
+function analyzeEfficiency(
+ code: string,
+ target: string,
+): DimensionScore<EfficiencyMetrics> {
+ const findings: UniversalFinding[] = [];
+ const lines = code.split('\n');
+ const normalizedLines = lines.map(normalizeLine);
+
+ // --- Line categorization ---
+ let blankLines = 0;
+ let commentLines = 0;
+ let importLines = 0;
+ let typeLines = 0;
+ let stylingLines = 0;
+ let logicLines = 0;
+ let inTypeBlock = false;
+ let inStyleBlock = false;
+ let inComment = false;
+
+ for (const line of lines) {
+ const stripped = line.trim();
+ if (stripped === '') {
+ blankLines++;
+ continue;
+ }
+ if (
+ stripped.startsWith('//') ||
+ stripped.startsWith('/*') ||
+ stripped.startsWith('*')
+ ) {
+ commentLines++;
+ if (stripped.startsWith('/*')) inComment = true;
+ if (stripped.includes('*/')) inComment = false;
+ continue;
+ }
+ if (inComment) {
+ commentLines++;
+ if (stripped.includes('*/')) inComment = false;
+ continue;
+ }
+ if (stripped.startsWith('import ')) {
+ importLines++;
+ continue;
+ }
+ if (/^(export\s+)?(type|interface)\s/.test(stripped)) inTypeBlock = true;
+ if (inTypeBlock) {
+ typeLines++;
+ if (stripped === '}' || stripped === '};') inTypeBlock = false;
+ continue;
+ }
+ if (target === 'xds' && stripped.includes('stylex.create'))
+ inStyleBlock = true;
+ if (inStyleBlock) {
+ stylingLines++;
+ if (stripped === '});') inStyleBlock = false;
+ continue;
+ }
+ if (target === 'baseline' && stripped.includes('className=')) {
+ stylingLines++;
+ continue;
+ }
+ if (target === 'html' && /style\s*=/.test(stripped)) {
+ stylingLines++;
+ continue;
+ }
+ logicLines++;
+ }
+
+ const totalLines = lines.length;
+ const codeLines = totalLines - blankLines - commentLines;
+ const boilerplateLines = importLines + typeLines;
+ const stylingRatio = codeLines > 0 ? stylingLines / codeLines : 0;
+ const boilerplateRatio = codeLines > 0 ? boilerplateLines / codeLines : 0;
+
+ // --- Duplicate detection (excluding component usage) ---
+ const lineCounts = new Map<string, number>();
+ for (const nl of normalizedLines) {
+ if (nl.length > 20 && !isComponentUsageLine(nl)) {
+ lineCounts.set(nl, (lineCounts.get(nl) || 0) + 1);
+ }
+ }
+ let duplicateLineCount = 0;
+ for (const [line, count] of lineCounts) {
+ if (count >= 3) {
+ duplicateLineCount += count;
+ findings.push({
+ rule: 'duplicate-lines',
+ severity: 'moderate',
+ detail: `Line repeated ${count} times`,
+ count,
+ example: line.slice(0, 80),
+ });
+ }
+ }
+ const duplicateRatio = codeLines > 0 ? duplicateLineCount / codeLines : 0;
+
+ // --- Repeated className patterns ---
+ const classRe = /className\s*=\s*["']([^"']{20,})["']/g;
+ const classCounts = new Map<string, number>();
+ let sm: RegExpExecArray | null;
+ while ((sm = classRe.exec(code)) !== null) {
+ classCounts.set(sm[1], (classCounts.get(sm[1]) || 0) + 1);
+ }
+ for (const [cls, count] of classCounts) {
+ if (count >= 3) {
+ findings.push({
+ rule: 'repeated-classname',
+ severity: 'moderate',
+ detail: `className pattern repeated ${count} times`,
+ count,
+ example: cls.slice(0, 60),
+ });
+ }
+ }
+
+ // --- Decisions per element ---
+ const elementCount = Math.max(1, countElements(code));
+ const stylingDecisionCount = countStylingDecisions(code, target);
+ const decisionsPerElement = stylingDecisionCount / elementCount;
+
+ const metrics: EfficiencyMetrics = {
+ totalLines,
+ codeLines,
+ stylingLines,
+ boilerplateLines,
+ logicLines,
+ stylingRatio,
+ boilerplateRatio,
+ decisionsPerElement: Math.round(decisionsPerElement * 10) / 10,
+ elementCount,
+ stylingDecisionCount,
+ duplicateRatio: Math.round(duplicateRatio * 100) / 100,
+ };
+
+ // Score: penalize high ceremony ratio, high duplication, high decisions/element
+ const ceremonyPenalty = (stylingRatio + boilerplateRatio) * 40;
+ const duplicationPenalty = duplicateRatio * 30;
+ // decisionsPerElement: 3 is ideal, 10+ is bad, 20+ is terrible
+ const decisionPenalty = Math.max(0, (decisionsPerElement - 3) * 3);
+ const findingPenalty = findings.reduce(
+ (s, f) => s + (f.severity === 'moderate' ? 5 : 2),
+ 0,
+ );
+
+ const score =
+ 100 -
+ ceremonyPenalty -
+ duplicationPenalty -
+ decisionPenalty -
+ findingPenalty;
+
+ return {score: clamp(score), findings, metrics};
+}
+
+// ============================================================
+// 5. Maintainability (coupling, magic values, locality)
+// ============================================================
+
+/**
+ * Detect magic values β€” raw literals in styling contexts that have no
+ * semantic meaning. Works for any target.
+ */
+function countMagicAndSemanticValues(
+ code: string,
+ target: string,
+): {magic: number; semantic: number} {
+ let magic = 0;
+ let semantic = 0;
+
+ // --- Semantic references (all targets) ---
+ // CSS variables
+ semantic += (code.match(/var\(--[\w-]+\)/g) || []).length;
+
+ if (target === 'xds') {
+ // StyleX token references: spacingVars["--spacing-4"], colorVars["--color-*"]
+ semantic += (code.match(/\w+Vars\[["']--[\w-]+["']\]/g) || []).length;
+ // Component props that delegate styling: variant=, size=, gap=, color=, type=
+ semantic += (
+ code.match(/\b(variant|size|gap|color|type|level)\s*=\s*["']/g) || []
+ ).length;
+ } else if (target === 'baseline') {
+ // Tailwind semantic tokens: bg-primary, text-muted-foreground, etc.
+ semantic += (
+ code.match(
+ /(?:bg|text|border|ring)-(?:primary|secondary|destructive|muted|accent|popover|card|foreground|background)[\w-]*/g,
+ ) || []
+ ).length;
+ // Tailwind scale values: p-4, gap-2, text-sm, rounded-lg (non-arbitrary)
+ semantic += (
+ code.match(
+ /(?:^|\s)(?:p|m|gap|space|text|rounded|font|w|h)-(?:\d+|xs|sm|md|lg|xl|2xl|3xl|full|auto)(?:\s|["']|$)/g,
+ ) || []
+ ).length;
+ // Component variant/size props
+ semantic += (code.match(/\b(variant|size)\s*=\s*["']/g) || []).length;
+ }
+
+ // --- Magic values (all targets) ---
+ const lines = code.split('\n');
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+
+ // Skip data arrays, comments, imports
+ if (
+ line.trim().startsWith('//') ||
+ line.trim().startsWith('import') ||
+ line.trim().startsWith('*')
+ )
+ continue;
+
+ // Hardcoded colors in style contexts
+ const colorMatches = line.match(
+ /(?:backgroundColor|borderColor|color|fill|stroke)\s*:\s*['"]?(#[0-9a-fA-F]{3,8}|rgb\(|hsl\(|rgba\(|hsla\()/gi,
+ );
+ if (colorMatches) {
+ // Skip if in data objects
+ const ctx = lines.slice(Math.max(0, i - 2), i + 1).join(' ');
+ if (
+ !ctx.includes('name:') &&
+ !ctx.includes('id:') &&
+ !ctx.includes('label:')
+ ) {
+ magic += colorMatches.length;
+ }
+ }
+
+ // Hardcoded spacing in style contexts
+ const spacingMatches = line.match(
+ /(?:padding|margin|gap)\w*\s*:\s*['"]?\d+px/gi,
+ );
+ if (spacingMatches && !line.includes('var(')) {
+ magic += spacingMatches.length;
+ }
+
+ // Hardcoded typography
+ const typoMatches = line.match(
+ /fontSize\s*:\s*['"]?\d+(?:\.\d+)?(?:px|rem|em)/gi,
+ );
+ if (typoMatches && !line.includes('var(')) {
+ magic += typoMatches.length;
+ }
+
+ // Tailwind arbitrary values (magic)
+ const arbitraryMatches = line.match(
+ /(?:bg|text|border|p|m|gap|w|h)-\[#?[\w.]+(?:px|rem|em|%)?\]/g,
+ );
+ if (arbitraryMatches) {
+ magic += arbitraryMatches.length;
+ }
+
+ // Inline hardcoded colors in style={{}}
+ const inlineColorMatches = line.match(
+ /(?:backgroundColor|color|borderColor)\s*:\s*['"]#[0-9a-fA-F]{3,8}['"]/gi,
+ );
+ if (inlineColorMatches) {
+ magic += inlineColorMatches.length;
+ }
+ }
+
+ return {magic, semantic};
+}
+
+/**
+ * Measure state variable spread β€” how far apart are declarations and usages?
+ */
+function measureStateSpread(code: string): number {
+ const lines = code.split('\n');
+ const spreads: number[] = [];
+
+ for (let i = 0; i < lines.length; i++) {
+ // Find useState declarations
+ const stateMatch = lines[i].match(
+ /\[\s*(\w+)\s*,\s*set\w+\s*\]\s*=\s*use[A-Z]/,
+ );
+ if (stateMatch) {
+ const varName = stateMatch[1];
+ // Find furthest usage of this variable
+ let furthest = i;
+ for (let j = i + 1; j < lines.length; j++) {
+ if (lines[j].includes(varName)) {
+ furthest = j;
+ }
+ }
+ spreads.push(furthest - i);
+ }
+ }
+
+ if (spreads.length === 0) return 0;
+ return Math.round(spreads.reduce((a, b) => a + b, 0) / spreads.length);
+}
+
+function analyzeMaintainability(
+ code: string,
+ target: string,
+): DimensionScore<MaintainabilityMetrics> {
+ const findings: UniversalFinding[] = [];
+
+ // --- Magic values vs semantic references ---
+ const {magic, semantic} = countMagicAndSemanticValues(code, target);
+ const totalValues = magic + semantic;
+ const semanticRatio = totalValues > 0 ? semantic / totalValues : 1;
+
+ if (magic > 0) {
+ findings.push({
+ rule: 'magic-values',
+ severity: magic > 5 ? 'moderate' : 'minor',
+ detail: `${magic} magic value${magic > 1 ? 's' : ''} (hardcoded colors, spacing, or typography)`,
+ count: magic,
+ });
+ }
+
+ // --- Dark mode support ---
+ let darkModeSupport = false;
+ if (target === 'xds') {
+ darkModeSupport = /dark(Theme|Mode|_mode)|mode\s*=\s*["']dark/i.test(code);
+ } else if (target === 'baseline') {
+ darkModeSupport = /\bdark:|\buseTheme\b|ThemeProvider|data-theme/i.test(
+ code,
+ );
+ } else {
+ darkModeSupport = /prefers-color-scheme|dark-mode|data-theme/i.test(code);
+ }
+
+ // --- State spread (locality) ---
+ const avgStateSpread = measureStateSpread(code);
+
+ if (avgStateSpread > 80) {
+ findings.push({
+ rule: 'high-state-spread',
+ severity: 'moderate',
+ detail: `Average state variable spread: ${avgStateSpread} lines`,
+ });
+ } else if (avgStateSpread > 50) {
+ findings.push({
+ rule: 'moderate-state-spread',
+ severity: 'minor',
+ detail: `Average state variable spread: ${avgStateSpread} lines`,
+ });
+ }
+
+ const metrics: MaintainabilityMetrics = {
+ semanticRatio: Math.round(semanticRatio * 100) / 100,
+ magicValueCount: magic,
+ semanticValueCount: semantic,
+ avgStateSpread,
+ darkModeSupport,
+ };
+
+ // Score: semantic ratio is the primary signal (0-60 points),
+ // locality adds up to 20, dark mode adds 10, findings subtract
+ const semanticScore = semanticRatio * 60;
+ const localityScore =
+ avgStateSpread < 30
+ ? 20
+ : avgStateSpread < 60
+ ? 12
+ : avgStateSpread < 100
+ ? 6
+ : 0;
+ const darkModeScore = darkModeSupport ? 10 : 0;
+ const baseScore = semanticScore + localityScore + darkModeScore + 10; // 10 free points
+
+ const findingPenalty = findings.reduce((s, f) => {
+ switch (f.severity) {
+ case 'critical':
+ return s + 15;
+ case 'moderate':
+ return s + 8;
+ case 'minor':
+ return s + 3;
+ default:
+ return s;
+ }
+ }, 0);
+
+ return {
+ score: clamp(baseScore - findingPenalty),
+ findings,
+ metrics,
+ };
+}
+
+// ============================================================
+// Main exports
+// ============================================================
+
+/**
+ * Run all 5 dimension analyzers on a code sample.
+ */
+export function evaluate(code: string, target: string): UniversalScore {
+ return {
+ correctness: analyzeCorrectness(code, target),
+ accessibility: analyzeAccessibility(code),
+ codeQuality: analyzeCodeQuality(code),
+ efficiency: analyzeEfficiency(code, target),
+ maintainability: analyzeMaintainability(code, target),
+ };
+}
+
+/**
+ * Get the list of dimension names.
+ */
+export function getDimensionNames(): UniversalDimension[] {
+ return [
+ 'correctness',
+ 'accessibility',
+ 'codeQuality',
+ 'efficiency',
+ 'maintainability',
+ ];
+}
+
+/**
+ * Get the score for a specific dimension.
+ */
+export function getDimensionScore(
+ score: UniversalScore,
+ dimension: UniversalDimension,
+): number {
+ return score[dimension].score;
+}
+
+/**
+ * Calculate an average score across all dimensions (unweighted).
+ */
+export function getAverageScore(score: UniversalScore): number {
+ const dims = getDimensionNames();
+ const total = dims.reduce((sum, d) => sum + score[d].score, 0);
+ return Math.round(total / dims.length);
+}