Skip to content

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

TypeScript

refactor(vibe-tests): CLI-retrieval runner + remove dead correctness code (#1525)

Cindy Zhang8433c7b4873a
diff --git a/internal/vibe-tests/package.json b/internal/vibe-tests/package.json
index b9c9b70755..3d6145e53b 100644
--- a/internal/vibe-tests/package.json
+++ b/internal/vibe-tests/package.json
@@ -11,11 +11,8 @@
"harness": "tsx src/cli.ts",
"interactive": "tsx src/interactive.ts",
"interactive:sample": "tsx src/interactive.ts --sample 5",
- "run-interactive": "tsx src/run-interactive.ts",
- "run-interactive:sample": "tsx src/run-interactive.ts --sample 5",
"aggregate": "tsx src/universal-aggregate.ts",
"universal": "tsx src/universal-aggregate.ts",
- "quality": "tsx src/quality.ts",
"compare": "tsx src/universal-compare.ts",
"compare:md": "tsx src/universal-compare.ts --markdown",
"universal:compare": "tsx src/universal-compare.ts",
diff --git a/internal/vibe-tests/scripts/run-radius-ab-test.sh b/internal/vibe-tests/scripts/run-radius-ab-test.sh
deleted file mode 100755
index bccc0c9323..0000000000
--- a/internal/vibe-tests/scripts/run-radius-ab-test.sh
+++ /dev/null
@@ -1,48 +0,0 @@
-#!/usr/bin/env bash
-# @file Run radius token naming A/B vibe test
-# @position internal/vibe-tests/scripts/run-radius-ab-test.sh
-#
-# Runs two iterations of the radius-tokens test set:
-# 1. "semantic" — current naming (--radius-container, --radius-element, etc.)
-# 2. "numeric" — proposed naming (--radius-1, --radius-2, --radius-3, etc.)
-#
-# After both complete, compare results with:
-# yarn workspace @xds/vibe-tests compare --iterations <id-A>,<id-B>
-
-set -euo pipefail
-
-SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-VIBE_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
-
-echo "=== Radius Token Naming A/B Test ==="
-echo ""
-echo "This sets up two iterations for comparison:"
-echo " A) Semantic names (--radius-container, --radius-element, etc.)"
-echo " B) Numeric scale (--radius-1, --radius-2, --radius-3, etc.)"
-echo ""
-
-# Generate fresh skill doc from current source
-echo "Step 1: Generating skill docs..."
-bash "$SCRIPT_DIR/generate-skill-doc.sh"
-
-echo ""
-echo "Step 2: Setting up iteration A (semantic radius tokens)..."
-cd "$VIBE_DIR"
-npx tsx src/interactive.ts \
- --test-set radius-tokens \
- --label "radius-semantic" \
- --skill-doc .generated/xds-skill-radius-semantic.md
-
-echo ""
-echo "Step 3: Setting up iteration B (numeric radius tokens)..."
-npx tsx src/interactive.ts \
- --test-set radius-tokens \
- --label "radius-numeric" \
- --skill-doc .generated/xds-skill-radius-numeric.md
-
-echo ""
-echo "=== Setup complete ==="
-echo ""
-echo "Next steps:"
-echo " 1. Run each iteration's tests with subagents (see task manifests above)"
-echo " 2. After both complete, aggregate and compare results"
diff --git a/internal/vibe-tests/src/quality-agent.ts b/internal/vibe-tests/src/quality-agent.ts
deleted file mode 100644
index 99a580683c..0000000000
--- a/internal/vibe-tests/src/quality-agent.ts
+++ /dev/null
@@ -1,402 +0,0 @@
-/**
- * @file Quality Assessment Agent
- * @description Evaluates generated code for accessibility, design system adherence, and code quality
- */
-
-import fs from 'fs';
-import path from 'path';
-import type {QualityAssessment} from './types.js';
-
-interface ComponentA11yInfo {
- component: string;
- builtIn: string[];
- keyboard: string[];
- developerMust: string[];
- notes: string[];
-}
-
-interface A11yManifest {
- source: string;
- generatedAt: string;
- version: string;
- components: Record<string, ComponentA11yInfo>;
-}
-
-const MANIFESTS_DIR = path.join(import.meta.dirname, '..', 'a11y-manifests');
-
-/**
- * Load accessibility manifest for a target
- */
-function loadA11yManifest(target: 'xds' | 'baseline'): A11yManifest | null {
- const manifestPath = path.join(MANIFESTS_DIR, `${target}.json`);
- if (!fs.existsSync(manifestPath)) {
- console.warn(`A11y manifest not found: ${manifestPath}`);
- console.warn('Run: yarn generate-a11y-manifest');
- return null;
- }
- return JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
-}
-
-/**
- * Extract component names from code to find relevant a11y info
- */
-function extractComponentNames(
- code: string,
- target: 'xds' | 'baseline',
-): string[] {
- const components: string[] = [];
-
- if (target === 'xds') {
- // Match XDS component imports and usages
- const xdsPattern = /XDS\w+/g;
- const matches = code.match(xdsPattern) || [];
- components.push(...new Set(matches.map(m => m.replace(/^XDS/, ''))));
- } else {
- // Match shadcn component imports
- const importPattern = /from\s+["']@\/components\/ui\/(\w+)["']/g;
- let match;
- while ((match = importPattern.exec(code)) !== null) {
- components.push(match[1].charAt(0).toUpperCase() + match[1].slice(1));
- }
- // Also match common component names in JSX
- const jsxPattern =
- /<(Button|Input|Card|Dialog|Select|Checkbox|Switch|Tabs|Badge|Avatar|Progress|Table|Tooltip|Popover|DropdownMenu)\b/g;
- while ((match = jsxPattern.exec(code)) !== null) {
- if (!components.includes(match[1])) {
- components.push(match[1]);
- }
- }
- }
-
- return components;
-}
-
-/**
- * Generate accessibility context from manifest
- */
-function generateA11yContext(
- manifest: A11yManifest,
- componentNames: string[],
- target: 'xds' | 'baseline',
-): string {
- const lines: string[] = [];
- const targetName = target === 'xds' ? 'XDS' : 'shadcn/Radix';
-
- lines.push(`## Built-in Accessibility (${targetName})`);
- lines.push('');
- lines.push(`**Source:** ${manifest.source}`);
- lines.push(`**Generated:** ${manifest.generatedAt}`);
- lines.push('');
- lines.push(
- 'IMPORTANT: Do NOT flag accessibility issues that are already handled by the component library.',
- );
- lines.push("Only flag issues that are the developer's responsibility.");
- lines.push('');
-
- // Add info for detected components
- const relevantComponents = componentNames
- .map(name => {
- // Try exact match first, then case-insensitive
- return (
- manifest.components[name] ||
- Object.values(manifest.components).find(
- c => c.component.toLowerCase() === name.toLowerCase(),
- )
- );
- })
- .filter(Boolean) as ComponentA11yInfo[];
-
- if (relevantComponents.length > 0) {
- lines.push('### Components used in this code:');
- lines.push('');
-
- for (const comp of relevantComponents) {
- lines.push(`**${comp.component}:**`);
- if (comp.builtIn.length > 0) {
- lines.push(
- "- Built-in (don't flag): " + comp.builtIn.slice(0, 3).join('; '),
- );
- }
- if (comp.developerMust.length > 0) {
- lines.push(
- '- Developer must provide: ' + comp.developerMust.join('; '),
- );
- }
- lines.push('');
- }
- }
-
- // Add general guidance
- lines.push('### General developer responsibilities (always check):');
- lines.push('- aria-label for icon-only buttons');
- lines.push('- aria-live regions for dynamic content updates');
- lines.push('- Proper heading hierarchy');
- lines.push(
- '- Keyboard-accessible custom interactive elements (not using library components)',
- );
- lines.push('- Focus management for modals and dynamic content');
- lines.push('');
-
- return lines.join('\n');
-}
-
-/**
- * Persona prompt for the quality assessment agent
- */
-export const QUALITY_AGENT_PERSONA = `You are a senior frontend engineer specializing in accessibility and design system compliance.
-
-Your role is to review React components and provide objective, actionable feedback. You focus on:
-
-1. **Accessibility** - WCAG compliance, keyboard navigation, screen reader support
-2. **Design System Adherence** - Proper component usage, token usage, pattern consistency
-3. **Code Quality** - State management, event handling, TypeScript correctness
-
-## Review Guidelines
-
-- Be thorough but fair - only flag genuine problems, not stylistic preferences
-- Prioritize issues by severity (critical > moderate > minor)
-- Provide specific, actionable recommendations
-- Reference line numbers when possible
-- Don't flag issues that are acceptable trade-offs (e.g., native HTML when no component exists)
-- CRITICAL: Do NOT flag accessibility features that are built into the design system components
-
-## Scoring
-
-- **good**: No critical issues, few moderate issues, code follows best practices
-- **needs-work**: Some moderate issues or patterns that could be improved
-- **poor**: Critical issues present that would affect users or maintainability`;
-
-/**
- * Generate the prompt for quality assessment
- */
-export function generateQualityAssessmentPrompt(
- code: string,
- target: 'xds' | 'baseline',
- promptDescription: string,
-): string {
- // Load accessibility manifest
- const manifest = loadA11yManifest(target);
- const componentNames = extractComponentNames(code, target);
- const a11yContext = manifest
- ? generateA11yContext(manifest, componentNames, target)
- : '';
-
- const designSystemContext =
- target === 'xds'
- ? `
-## Design System Context (XDS)
-
-The code should use:
-- XDS components (XDSButton, XDSTextInput, XDSCard, etc.)
-- StyleX for styling with CSS variable tokens (var(--spacing-*), var(--color-*))
-- XDSTextInput should use \`status\` prop for validation errors (not manual border styling)
-- Interactive elements should use Button components, not clickable divs/spans
-- Layout should use XDSVStack, XDSHStack, XDSStackItem when appropriate
-
-### Typography Requirements
-- **XDSHeading** for all heading text (h1-h6), with \`level\` prop for semantic level and \`variant="editorial"\` for display-scale headings
-- **XDSText** for all non-heading text, with \`type\` prop: \`body\`, \`large\`, \`label\`, \`supporting\`, or \`code\`
-- **XDSFontWrapper** is a global provider that styles native HTML elements with proper typography — raw HTML is acceptable for prose/markdown content rendered within it
-- For structured UI (cards, forms, dashboards), prefer XDSHeading/XDSText over raw HTML for access to props like \`weight\`, \`maxLines\`, \`variant\`, \`hasTabularNumbers\`
-- Never hardcode fontSize, fontWeight, lineHeight, or fontFamily — use the component type system or design tokens
-- Valid typography tokens: \`--text-*\` (sizes), \`--font-weight-*\` (weights), \`--leading-*\` (line heights), \`--font-family-body\`, \`--font-family-code\`, \`--font-family-heading\` (font families)
-- Common hallucinated tokens to flag: \`--font-size-*\`, \`--font-family-*\`, \`--xds-font-*\` (these don't exist)`
- : `
-## Design System Context (shadcn/Tailwind)
-
-The code should use:
-- shadcn components (Button, Input, Card, Dialog, etc.)
-- Tailwind utility classes with semantic tokens (text-muted-foreground, bg-destructive, etc.)
-- cn() utility for conditional class composition
-- Proper component patterns (e.g., Dialog with DialogTrigger, DialogContent)`;
-
- return `${QUALITY_AGENT_PERSONA}
-
-${designSystemContext}
-
-${a11yContext}
-
-## Component to Review
-
-The following component was generated in response to: "${promptDescription}"
-
-\`\`\`tsx
-${code}
-\`\`\`
-
-## Your Task
-
-Review this code and provide a quality assessment. Return your findings as a JSON object with this structure:
-
-\`\`\`json
-{
- "accessibility": {
- "issues": [
- {
- "severity": "critical|moderate|minor",
- "element": "<element name or description>",
- "issue": "<description of the issue>",
- "recommendation": "<how to fix it>",
- "lineNumber": <optional line number>
- }
- ],
- "score": "good|needs-work|poor"
- },
- "designSystemAdherence": {
- "issues": [
- {
- "severity": "critical|moderate|minor",
- "category": "component-usage|token-usage|pattern-violation|typography-violation",
- "issue": "<description of the issue>",
- "recommendation": "<how to fix it>",
- "codeSnippet": "<optional relevant code>"
- }
- ],
- "score": "good|needs-work|poor"
- },
- "codeQuality": {
- "issues": [
- {
- "severity": "critical|moderate|minor",
- "category": "state-management|event-handling|typescript|performance",
- "issue": "<description of the issue>",
- "recommendation": "<how to fix it>",
- "codeSnippet": "<optional relevant code>"
- }
- ],
- "score": "good|needs-work|poor"
- },
- "overallScore": "good|needs-work|poor",
- "summary": "<2-3 sentence summary of the review>"
-}
-\`\`\`
-
-Only return the JSON object, no additional text.`;
-}
-
-/**
- * Parse the quality assessment response from the agent
- */
-export function parseQualityAssessment(
- response: string,
-): QualityAssessment | null {
- try {
- // Extract JSON from response (may be wrapped in markdown code blocks)
- const jsonMatch = response.match(/```(?:json)?\s*([\s\S]*?)```/);
- const jsonStr = jsonMatch ? jsonMatch[1].trim() : response.trim();
-
- const assessment = JSON.parse(jsonStr) as QualityAssessment;
-
- // Validate structure
- if (
- !assessment.accessibility ||
- !assessment.designSystemAdherence ||
- !assessment.codeQuality ||
- !assessment.overallScore
- ) {
- console.error('Invalid quality assessment structure');
- return null;
- }
-
- return assessment;
- } catch (error) {
- console.error('Failed to parse quality assessment:', error);
- return null;
- }
-}
-
-/**
- * Format severity with icon
- */
-function severityIcon(severity: string): string {
- switch (severity) {
- case 'critical':
- return '🔴';
- case 'moderate':
- return '🟡';
- case 'minor':
- return '⚪';
- default:
- return '•';
- }
-}
-
-/**
- * Generate a summary of quality issues for display
- */
-export function summarizeQualityIssues(
- assessment: QualityAssessment,
- options: {verbose?: boolean} = {},
-): string {
- const lines: string[] = [];
- const {verbose = false} = options;
-
- lines.push(`Quality Assessment: ${assessment.overallScore.toUpperCase()}`);
- lines.push('');
-
- // Accessibility section
- const a11yIssues = assessment.accessibility.issues;
- if (a11yIssues.length > 0) {
- const critical = a11yIssues.filter(i => i.severity === 'critical').length;
- lines.push(
- ` Accessibility: ${assessment.accessibility.score} (${a11yIssues.length} issues, ${critical} critical)`,
- );
- if (verbose || assessment.accessibility.score !== 'good') {
- for (const issue of a11yIssues) {
- lines.push(` ${severityIcon(issue.severity)} ${issue.issue}`);
- if (verbose && issue.recommendation) {
- lines.push(` → ${issue.recommendation}`);
- }
- }
- }
- } else {
- lines.push(` Accessibility: ${assessment.accessibility.score}`);
- }
-
- lines.push('');
-
- // Design System section
- const dsIssues = assessment.designSystemAdherence.issues;
- if (dsIssues.length > 0) {
- const critical = dsIssues.filter(i => i.severity === 'critical').length;
- lines.push(
- ` Design System: ${assessment.designSystemAdherence.score} (${dsIssues.length} issues, ${critical} critical)`,
- );
- if (verbose || assessment.designSystemAdherence.score !== 'good') {
- for (const issue of dsIssues) {
- lines.push(` ${severityIcon(issue.severity)} ${issue.issue}`);
- if (verbose && issue.recommendation) {
- lines.push(` → ${issue.recommendation}`);
- }
- }
- }
- } else {
- lines.push(` Design System: ${assessment.designSystemAdherence.score}`);
- }
-
- lines.push('');
-
- // Code Quality section
- const cqIssues = assessment.codeQuality.issues;
- if (cqIssues.length > 0) {
- const critical = cqIssues.filter(i => i.severity === 'critical').length;
- lines.push(
- ` Code Quality: ${assessment.codeQuality.score} (${cqIssues.length} issues, ${critical} critical)`,
- );
- if (verbose || assessment.codeQuality.score !== 'good') {
- for (const issue of cqIssues) {
- lines.push(` ${severityIcon(issue.severity)} ${issue.issue}`);
- if (verbose && issue.recommendation) {
- lines.push(` → ${issue.recommendation}`);
- }
- }
- }
- } else {
- lines.push(` Code Quality: ${assessment.codeQuality.score}`);
- }
-
- lines.push('');
- lines.push(` ${assessment.summary}`);
-
- return lines.join('\n');
-}
diff --git a/internal/vibe-tests/src/quality.ts b/internal/vibe-tests/src/quality.ts
deleted file mode 100644
index 3c38544c04..0000000000
--- a/internal/vibe-tests/src/quality.ts
+++ /dev/null
@@ -1,156 +0,0 @@
-#!/usr/bin/env tsx
-/**
- * @file Quality Assessment CLI
- * @description Runs quality assessment agent on generated code results
- *
- * Usage:
- * yarn workspace @xds/vibe-tests quality --iteration <id>
- * yarn workspace @xds/vibe-tests quality --iteration <id> --prompt wd-1
- */
-
-import fs from 'fs';
-import path from 'path';
-import {generateQualityAssessmentPrompt} from './quality-agent.js';
-
-const RESULTS_DIR = path.join(import.meta.dirname, '..', 'results');
-
-interface TaskManifest {
- iterationId: string;
- config: {
- target: 'xds' | 'baseline';
- };
- prompts: Array<{
- id: string;
- prompt: string;
- status: string;
- }>;
-}
-
-function loadManifest(iterationId: string): TaskManifest {
- const manifestPath = path.join(RESULTS_DIR, iterationId, 'manifest.json');
- if (!fs.existsSync(manifestPath)) {
- throw new Error(`Manifest not found: ${manifestPath}`);
- }
- return JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
-}
-
-function loadCode(iterationId: string, promptId: string): string | null {
- const codePath = path.join(
- RESULTS_DIR,
- iterationId,
- 'results',
- `${promptId}.tsx`,
- );
- if (!fs.existsSync(codePath)) {
- return null;
- }
- return fs.readFileSync(codePath, 'utf-8');
-}
-
-function printUsage(): void {
- console.log(`
-Quality Assessment CLI
-
-Usage:
- yarn workspace @xds/vibe-tests quality --iteration <id> [--prompt <promptId>]
-
-Options:
- --iteration, -i Iteration ID to assess (required)
- --prompt, -p Specific prompt ID to assess (optional, defaults to all)
- --help, -h Show this help message
-
-Examples:
- yarn workspace @xds/vibe-tests quality --iteration 2126954a
- yarn workspace @xds/vibe-tests quality -i 2126954a -p wd-1
-
-Note: This generates prompts for quality assessment. Run the prompts with a subagent
-to get the actual assessments.
-`);
-}
-
-async function main(): Promise<void> {
- const args = process.argv.slice(2);
-
- if (args.includes('--help') || args.includes('-h')) {
- printUsage();
- process.exit(0);
- }
-
- // Parse arguments
- let iterationId: string | null = null;
- let promptId: string | null = null;
-
- for (let i = 0; i < args.length; i++) {
- if (args[i] === '--iteration' || args[i] === '-i') {
- iterationId = args[++i];
- } else if (args[i] === '--prompt' || args[i] === '-p') {
- promptId = args[++i];
- }
- }
-
- if (!iterationId) {
- console.error('Error: --iteration is required');
- printUsage();
- process.exit(1);
- }
-
- // Load manifest
- const manifest = loadManifest(iterationId);
- const target = manifest.config.target;
-
- console.log(`\n🔍 Quality Assessment Setup - Iteration ${iterationId}`);
- console.log(`Target: ${target.toUpperCase()}`);
- console.log('');
-
- // Filter prompts if specific one requested
- const promptsToAssess = promptId
- ? manifest.prompts.filter(p => p.id === promptId)
- : manifest.prompts;
-
- if (promptsToAssess.length === 0) {
- console.error(`No prompts found${promptId ? ` matching ${promptId}` : ''}`);
- process.exit(1);
- }
-
- console.log(
- `Generating quality assessment prompts for ${promptsToAssess.length} result(s):\n`,
- );
-
- for (const prompt of promptsToAssess) {
- const code = loadCode(iterationId, prompt.id);
- if (!code) {
- console.log(` [${prompt.id}] ⚠️ No code file found, skipping`);
- continue;
- }
-
- const assessmentPrompt = generateQualityAssessmentPrompt(
- code,
- target,
- prompt.prompt,
- );
-
- // Save the prompt for later execution
- const promptPath = path.join(
- RESULTS_DIR,
- iterationId,
- 'results',
- `${prompt.id}.quality-prompt.md`,
- );
- fs.writeFileSync(promptPath, assessmentPrompt);
-
- console.log(` [${prompt.id}] ✓ Generated prompt: ${promptPath}`);
- }
-
- console.log(`
-Next steps:
-1. Run quality assessment subagents on the generated prompts
-2. Save results to {promptId}.quality.json files
-3. Re-run aggregator to include quality scores
-
-Example subagent prompt:
-"Run quality assessment for iteration ${iterationId} by reading each .quality-prompt.md
-file, evaluating the code, and saving results to .quality.json files"
-`);
-}
-
-main().catch(console.error);
diff --git a/internal/vibe-tests/src/run-interactive.ts b/internal/vibe-tests/src/run-interactive.ts
deleted file mode 100644
index 29333dd5d9..0000000000
--- a/internal/vibe-tests/src/run-interactive.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-#!/usr/bin/env node
-/**
- * @file Run complete interactive vibe test with subagents
- *
- * Usage:
- * yarn workspace @xds/vibe-tests run-interactive
- * yarn workspace @xds/vibe-tests run-interactive --sample 5
- */
-
-import {execSync} from 'node:child_process';
-import * as fs from 'node:fs';
-import * as path from 'node:path';
-import {fileURLToPath} from 'node:url';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-
-async function main() {
- const args = process.argv.slice(2);
-
- // Step 1: Setup the test iteration
- console.log('🧪 Setting up interactive vibe test...\n');
- const setupOutput = execSync(
- `tsx ${path.join(__dirname, 'interactive.ts')} ${args.join(' ')}`,
- {
- cwd: path.join(__dirname, '..'),
- encoding: 'utf-8',
- },
- );
-
- console.log(setupOutput);
-
- // Extract iteration ID from output
- const iterationMatch = setupOutput.match(/Iteration: ([a-f0-9]+)/);
- if (!iterationMatch) {
- console.error('Failed to extract iteration ID');
- process.exit(1);
- }
-
- const iterationId = iterationMatch[1];
- const resultsDir = path.join(__dirname, '..', 'results', iterationId);
- const tasksDir = path.join(resultsDir, 'tasks');
-
- // Step 2: Read all task files
- const taskFiles = fs.readdirSync(tasksDir).filter(f => f.endsWith('.json'));
-
- console.log(`\n🚀 Spawning ${taskFiles.length} parallel subagents...\n`);
-
- // Step 3: Generate the agent spawn instructions
- console.log('INSTRUCTIONS FOR CLAUDE CODE:');
- console.log('='.repeat(50));
- console.log(
- '\nPlease run the following to spawn all test agents in parallel:\n',
- );
-
- for (const taskFile of taskFiles) {
- const taskPath = path.join(tasksDir, taskFile);
- const task = JSON.parse(fs.readFileSync(taskPath, 'utf-8'));
-
- console.log(`Task("Vibe test: ${task.promptId}", {
- "subagent_type": "general-purpose",
- "description": "Vibe test ${task.promptId}",
- "mode": "bypassPermissions",
- "prompt": "Run vibe test for iteration ${iterationId}, task ${task.promptId}.
-
-TIMING: Record the current timestamp as startTime NOW before doing anything else.
-
-Read task file at: ${taskPath}
-
-XDS AGENTS.md is auto-injected and provides guidance on XDS components and CLI commands for reading docs.
-
-IMPORTANT: Track which docs you read. Keep a list of doc names (e.g., ['AGENTS.md', 'Button', 'tokens']).
-
-Generate code for: \\"${task.prompt}\\"
-Expected components: ${task.expectedComponents.join(', ')}
-Persona: ${task.persona}
-
-Self-evaluate your response and output JSON with:
-- response: your code
-- evaluation: { success, componentsUsed, componentsExpected, escapeHatches, failureMode, confusionSignals }
-
-TIMING: Record the current timestamp as endTime and calculate durationMs = endTime - startTime.
-
-Write the result as a TestResult JSON object to: ${resultsDir}/results/${task.promptId}.json
-
-The TestResult format is:
-{
- id: '${iterationId}-${task.promptId}',
- timestamp: new Date().toISOString(),
- systemVersion: 'xds-agents-v1',
- model: 'claude-code-interactive',
- persona: '${task.persona}',
- promptCategory: '${task.category}',
- trajectoryDepth: 0,
- prompt: '${task.prompt}',
- response: <your generated code>,
- evaluation: <your evaluation>,
- fullConversation: [],
- contextWindowUsage: 0,
- durationMs: <calculated duration in milliseconds>,
- inputTokens: 0,
- outputTokens: 0,
- docsRead: <list of doc filenames you read>
-}"
-});
-`);
- }
-
- console.log('\n' + '='.repeat(50));
- console.log(`\nAfter all agents complete, run:\n`);
- console.log(
- ` yarn workspace @xds/vibe-tests aggregate --iteration ${iterationId}\n`,
- );
-}
-
-main().catch(console.error);
diff --git a/internal/vibe-tests/src/setup-iteration.mjs b/internal/vibe-tests/src/setup-iteration.mjs
new file mode 100644
index 0000000000..20b67ab531
--- /dev/null
+++ b/internal/vibe-tests/src/setup-iteration.mjs
@@ -0,0 +1,262 @@
+#!/usr/bin/env node
+/**
+ * @file setup-iteration.mjs
+ *
+ * Sets up a vibe test iteration where XDS sub-agents use the CLI for doc retrieval.
+ * Generates task manifests with instructions to run `npx xds component <Name>`
+ * on the MacBook CLI node before generating code.
+ *
+ * Usage:
+ * node internal/vibe-tests/src/setup-iteration.mjs --sample 10 --target xds
+ * node internal/vibe-tests/src/setup-iteration.mjs --sample 10 --target baseline
+ * node internal/vibe-tests/src/setup-iteration.mjs --sample 10 --target html
+ * node internal/vibe-tests/src/setup-iteration.mjs --sample 10 --target xds --prompts cwm-1,dd-2,fwc-6
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as crypto from 'node:crypto';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const VIBE_DIR = path.resolve(__dirname, '..');
+const RESULTS_DIR = path.join(VIBE_DIR, 'results');
+
+// ── Helpers ──────────────────────────────────────────────────────────
+
+function generateId() {
+ return crypto.randomBytes(4).toString('hex');
+}
+
+function timestamp() {
+ return new Date().toISOString();
+}
+
+function ensureDir(dir) {
+ fs.mkdirSync(dir, { recursive: true });
+}
+
+function loadTestSet() {
+ const testSetDir = path.join(VIBE_DIR, 'test-sets');
+ const files = fs.readdirSync(testSetDir).filter(f => f.endsWith('.json'));
+ const prompts = [];
+ for (const file of files) {
+ const data = JSON.parse(fs.readFileSync(path.join(testSetDir, file), 'utf-8'));
+ if (Array.isArray(data)) {
+ prompts.push(...data);
+ } else if (data.prompts) {
+ prompts.push(...data.prompts);
+ }
+ }
+ return prompts;
+}
+
+function samplePrompts(prompts, n) {
+ if (!n || n >= prompts.length) return prompts;
+ const byCategory = {};
+ for (const p of prompts) {
+ if (!byCategory[p.category]) byCategory[p.category] = [];
+ byCategory[p.category].push(p);
+ }
+ const categories = Object.keys(byCategory);
+ const perCategory = Math.max(1, Math.floor(n / categories.length));
+ const sampled = [];
+ for (const cat of categories) {
+ const shuffled = byCategory[cat].sort(() => Math.random() - 0.5);
+ sampled.push(...shuffled.slice(0, perCategory));
+ }
+ while (sampled.length < n) {
+ const remaining = prompts.filter(p => !sampled.includes(p));
+ if (remaining.length === 0) break;
+ sampled.push(remaining[Math.floor(Math.random() * remaining.length)]);
+ }
+ return sampled.slice(0, n);
+}
+
+// ── Task prompt templates ────────────────────────────────────────────
+
+function generateXdsTaskPrompt(prompt, iterDir) {
+ const componentNames = (prompt.expectedComponents || [])
+ .map(c => c.replace(/^XDS/, ''));
+
+ const cliCommands = componentNames
+ .map(c => `npx xds component ${c}`)
+ .join('\n');
+
+ return `You are generating React/TSX code using the XDS design system.
+
+## IMPORTANT: Read component docs FIRST
+
+You MUST run the following commands on the MacBook CLI node (node: "cli:MacBook-Pro-2")
+to read the component API docs BEFORE writing any code:
+
+cd ~/xds/worktrees/main
+${cliCommands}
+
+Read the output carefully. Use ONLY the props documented in the CLI output.
+Do NOT guess prop names or values. If you need additional components beyond
+the ones listed above, look them up too: npx xds component <Name>
+
+## Rules
+
+1. Import from '@xds/core' (e.g. import { XDSButton } from '@xds/core')
+2. Use StyleX for custom styling (import * as stylex from '@stylexjs/stylex')
+3. Use CSS variables for tokens: var(--color-*), var(--spacing-*), var(--radius-*)
+4. Form inputs are controlled: value + onChange
+5. No <div> for layout — use XDSVStack, XDSHStack, XDSGrid
+6. Export default a single React component
+
+## Task
+
+${prompt.prompt}
+
+## Output
+
+Write the TSX code to: ${path.join(iterDir, 'results', `${prompt.id}.tsx`)}
+Write metadata to: ${path.join(iterDir, 'results', `${prompt.id}.json`)}
+
+The metadata JSON should contain:
+{
+ "completedAt": "<current ISO timestamp>",
+ "docsRead": [<list of component names you looked up via CLI>]
+}
+
+Write ONLY valid TSX in the .tsx file. No markdown fences, no explanation.`;
+}
+
+function generateBaselineTaskPrompt(prompt, iterDir) {
+ return `You are generating React/TSX code using shadcn/ui components with Tailwind CSS.
+
+Read the baseline docs at /vercel/sandbox/repos/xds/internal/vibe-tests/.baseline-docs/
+and AGENTS.baseline.md for component guidance.
+
+## Task
+
+${prompt.prompt}
+
+## Output
+
+Write the TSX code to: ${path.join(iterDir, 'results', `${prompt.id}.tsx`)}
+Write metadata to: ${path.join(iterDir, 'results', `${prompt.id}.json`)}
+
+Metadata: {"completedAt": "<ISO timestamp>", "docsRead": [<docs you read>]}
+Write ONLY valid TSX. No markdown fences, no explanation.`;
+}
+
+function generateHtmlTaskPrompt(prompt, iterDir) {
+ return `You are generating React/TSX code using ONLY plain HTML elements and inline CSS.
+Do NOT use any component library. Use standard HTML elements (div, button, input, etc.)
+with inline styles or a styles object.
+
+## Task
+
+${prompt.prompt}
+
+## Output
+
+Write the TSX code to: ${path.join(iterDir, 'results', `${prompt.id}.tsx`)}
+Write metadata to: ${path.join(iterDir, 'results', `${prompt.id}.json`)}
+
+Metadata: {"completedAt": "<ISO timestamp>", "docsRead": []}
+Write ONLY valid TSX. No markdown fences, no explanation.`;
+}
+
+// ── Main ─────────────────────────────────────────────────────────────
+
+const args = process.argv.slice(2);
+const sampleIdx = args.indexOf('--sample');
+const sample = sampleIdx !== -1 ? parseInt(args[sampleIdx + 1]) : 10;
+const targetIdx = args.indexOf('--target');
+const target = targetIdx !== -1 ? args[targetIdx + 1] : 'xds';
+const promptsIdx = args.indexOf('--prompts');
+const promptFilter = promptsIdx !== -1 ? args[promptsIdx + 1].split(',') : null;
+
+console.log(`\n🧪 Setup Vibe Test Iteration`);
+console.log(` Target: ${target}, Sample: ${sample}`);
+if (target === 'xds') console.log(` Mode: CLI-retrieval (MacBook)\n`);
+else console.log(` Mode: ${target === 'baseline' ? 'baseline-docs' : 'no docs'}\n`);
+
+// 1. Load and filter/sample prompts
+const allPrompts = loadTestSet();
+let prompts;
+if (promptFilter) {
+ prompts = allPrompts.filter(p => promptFilter.includes(p.id));
+ console.log(`📋 Using ${prompts.length} specified prompts`);
+} else {
+ prompts = samplePrompts(allPrompts, sample);
+ console.log(`📋 Sampled ${prompts.length} prompts from ${allPrompts.length} total`);
+}
+
+// 2. Create iteration
+const iterationId = generateId();
+const iterDir = path.join(RESULTS_DIR, iterationId);
+ensureDir(iterDir);
+ensureDir(path.join(iterDir, 'results'));
+ensureDir(path.join(iterDir, 'tasks'));
+
+// 3. Generate manifest + task files
+const manifest = {
+ iterationId,
+ createdAt: timestamp(),
+ config: {
+ target,
+ persona: 'naive',
+ holdout: false,
+ degradation: false,
+ cliRetrieval: target === 'xds',
+ },
+ prompts: prompts.map(p => ({
+ id: p.id,
+ category: p.category,
+ prompt: p.prompt,
+ expectedComponents: p.expectedComponents,
+ status: 'pending',
+ })),
+};
+
+fs.writeFileSync(path.join(iterDir, 'manifest.json'), JSON.stringify(manifest, null, 2));
+
+const generateTaskPrompt = target === 'xds' ? generateXdsTaskPrompt
+ : target === 'baseline' ? generateBaselineTaskPrompt
+ : generateHtmlTaskPrompt;
+
+for (const prompt of prompts) {
+ const taskPrompt = generateTaskPrompt(prompt, iterDir);
+
+ const task = {
+ promptId: prompt.id,
+ category: prompt.category,
+ prompt: prompt.prompt,
+ expectedComponents: prompt.expectedComponents,
+ target,
+ persona: 'naive',
+ taskPrompt,
+ createdAt: timestamp(),
+ };
+
+ fs.writeFileSync(
+ path.join(iterDir, 'tasks', `${prompt.id}.json`),
+ JSON.stringify(task, null, 2)
+ );
+}
+
+// 4. Output
+console.log(`\n✅ Iteration ${iterationId} ready`);
+console.log(` Dir: ${iterDir}`);
+console.log(` ${prompts.length} tasks created`);
+console.log(` Prompt IDs: ${prompts.map(p => p.id).join(',')}\n`);
+
+if (target === 'xds') {
+ console.log(`## Sub-agent spawn pattern (XDS with CLI retrieval):\n`);
+ console.log(`Each agent needs: node "cli:MacBook-Pro-2" for CLI, workspace for file I/O\n`);
+} else if (target === 'baseline') {
+ console.log(`## Sub-agent spawn pattern (baseline):\n`);
+ console.log(`Agents read .baseline-docs/ and AGENTS.baseline.md\n`);
+} else {
+ console.log(`## Sub-agent spawn pattern (HTML):\n`);
+ console.log(`Agents use plain HTML/CSS — no design system docs\n`);
+}
+
+for (const prompt of prompts) {
+ console.log(` Task: ${iterDir}/tasks/${prompt.id}.json`);
+}
diff --git a/internal/vibe-tests/src/setup-nightly.mjs b/internal/vibe-tests/src/setup-nightly.mjs
new file mode 100644
index 0000000000..ff827c0815
--- /dev/null
+++ b/internal/vibe-tests/src/setup-nightly.mjs
@@ -0,0 +1,290 @@
+#!/usr/bin/env node
+/**
+ * @file setup-nightly.mjs
+ *
+ * Sets up a complete nightly vibe test run: 3 iterations (xds, baseline, html)
+ * using the same prompts. XDS tasks include CLI-retrieval instructions.
+ *
+ * Usage:
+ * node internal/vibe-tests/src/setup-nightly.mjs
+ * node internal/vibe-tests/src/setup-nightly.mjs --sample 5
+ *
+ * Output: prints JSON with all three iteration IDs and prompt IDs
+ * for the nightly runner to use when spawning sub-agents.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as crypto from 'node:crypto';
+import {fileURLToPath} from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const VIBE_DIR = path.resolve(__dirname, '..');
+const RESULTS_DIR = path.join(VIBE_DIR, 'results');
+
+// ── Helpers ──────────────────────────────────────────────────────────
+
+function generateId() {
+ return crypto.randomBytes(4).toString('hex');
+}
+
+function timestamp() {
+ return new Date().toISOString();
+}
+
+function ensureDir(dir) {
+ fs.mkdirSync(dir, {recursive: true});
+}
+
+function loadTestSet() {
+ const testSetDir = path.join(VIBE_DIR, 'test-sets');
+ const files = fs.readdirSync(testSetDir).filter(f => f.endsWith('.json'));
+ const prompts = [];
+ for (const file of files) {
+ const data = JSON.parse(
+ fs.readFileSync(path.join(testSetDir, file), 'utf-8'),
+ );
+ if (Array.isArray(data)) {
+ prompts.push(...data);
+ } else if (data.prompts) {
+ prompts.push(...data.prompts);
+ }
+ }
+ return prompts;
+}
+
+function samplePrompts(prompts, n) {
+ if (!n || n >= prompts.length) return prompts;
+ const byCategory = {};
+ for (const p of prompts) {
+ if (!byCategory[p.category]) byCategory[p.category] = [];
+ byCategory[p.category].push(p);
+ }
+ const categories = Object.keys(byCategory);
+ const perCategory = Math.max(1, Math.floor(n / categories.length));
+ const sampled = [];
+ for (const cat of categories) {
+ const shuffled = byCategory[cat].sort(() => Math.random() - 0.5);
+ sampled.push(...shuffled.slice(0, perCategory));
+ }
+ while (sampled.length < n) {
+ const remaining = prompts.filter(p => !sampled.includes(p));
+ if (remaining.length === 0) break;
+ sampled.push(remaining[Math.floor(Math.random() * remaining.length)]);
+ }
+ return sampled.slice(0, n);
+}
+
+// ── Task prompt templates ────────────────────────────────────────────
+
+function generateXdsTaskPrompt(prompt, iterDir) {
+ const componentNames = (prompt.expectedComponents || []).map(c =>
+ c.replace(/^XDS/, ''),
+ );
+
+ const cliCommands = componentNames
+ .map(c => `npx xds component ${c}`)
+ .join('\n');
+
+ return `You are generating React/TSX code using the XDS design system.
+
+## IMPORTANT: Read component docs FIRST
+
+You MUST run the following commands on the MacBook CLI node (node: "cli:MacBook-Pro-2")
+to read the component API docs BEFORE writing any code:
+
+cd ~/xds/worktrees/main
+${cliCommands}
+
+Read the output carefully. Use ONLY the props documented in the CLI output.
+Do NOT guess prop names or values. If you need additional components beyond
+the ones listed above, look them up too: npx xds component <Name>
+
+## Rules
+
+1. Import from '@xds/core' (e.g. import { XDSButton } from '@xds/core')
+2. Use StyleX for custom styling (import * as stylex from '@stylexjs/stylex')
+3. Use CSS variables for tokens: var(--color-*), var(--spacing-*), var(--radius-*)
+4. Form inputs are controlled: value + onChange
+5. No <div> for layout — use XDSVStack, XDSHStack, XDSGrid
+6. Export default a single React component
+
+## Task
+
+${prompt.prompt}
+
+## Output
+
+Write the TSX code to: ${path.join(iterDir, 'results', `${prompt.id}.tsx`)}
+Write metadata to: ${path.join(iterDir, 'results', `${prompt.id}.json`)}
+
+The metadata JSON should contain:
+{
+ "completedAt": "<current ISO timestamp>",
+ "docsRead": [<list of component names you looked up via CLI>]
+}
+
+Write ONLY valid TSX in the .tsx file. No markdown fences, no explanation.`;
+}
+
+function generateBaselineTaskPrompt(prompt, iterDir) {
+ return `You are generating React/TSX code using shadcn/ui components with Tailwind CSS.
+
+Read the baseline docs at ${VIBE_DIR}/.baseline-docs/
+and ${VIBE_DIR}/AGENTS.baseline.md for component guidance.
+
+## Task
+
+${prompt.prompt}
+
+## Output
+
+Write the TSX code to: ${path.join(iterDir, 'results', `${prompt.id}.tsx`)}
+Write metadata to: ${path.join(iterDir, 'results', `${prompt.id}.json`)}
+
+Metadata: {"completedAt": "<ISO timestamp>", "docsRead": [<docs you read>]}
+Write ONLY valid TSX. No markdown fences, no explanation.`;
+}
+
+function generateHtmlTaskPrompt(prompt, iterDir) {
+ return `You are generating React/TSX code using ONLY plain HTML elements and inline CSS.
+Do NOT use any component library. Use standard HTML elements (div, button, input, etc.)
+with inline styles or a styles object.
+
+## Task
+
+${prompt.prompt}
+
+## Output
+
+Write the TSX code to: ${path.join(iterDir, 'results', `${prompt.id}.tsx`)}
+Write metadata to: ${path.join(iterDir, 'results', `${prompt.id}.json`)}
+
+Metadata: {"completedAt": "<ISO timestamp>", "docsRead": []}
+Write ONLY valid TSX. No markdown fences, no explanation.`;
+}
+
+function createIteration(target, prompts, generateFn) {
+ const iterationId = generateId();
+ const iterDir = path.join(RESULTS_DIR, iterationId);
+ ensureDir(iterDir);
+ ensureDir(path.join(iterDir, 'results'));
+ ensureDir(path.join(iterDir, 'tasks'));
+
+ const manifest = {
+ iterationId,
+ createdAt: timestamp(),
+ config: {
+ target,
+ persona: 'naive',
+ holdout: false,
+ degradation: false,
+ cliRetrieval: target === 'xds',
+ },
+ prompts: prompts.map(p => ({
+ id: p.id,
+ category: p.category,
+ prompt: p.prompt,
+ expectedComponents: p.expectedComponents,
+ status: 'pending',
+ })),
+ };
+
+ fs.writeFileSync(
+ path.join(iterDir, 'manifest.json'),
+ JSON.stringify(manifest, null, 2),
+ );
+
+ for (const prompt of prompts) {
+ const taskPrompt = generateFn(prompt, iterDir);
+ const task = {
+ promptId: prompt.id,
+ category: prompt.category,
+ prompt: prompt.prompt,
+ expectedComponents: prompt.expectedComponents,
+ target,
+ persona: 'naive',
+ taskPrompt,
+ createdAt: timestamp(),
+ };
+ fs.writeFileSync(
+ path.join(iterDir, 'tasks', `${prompt.id}.json`),
+ JSON.stringify(task, null, 2),
+ );
+ }
+
+ return {iterationId, iterDir};
+}
+
+// ── Main ─────────────────────────────────────────────────────────────
+
+const args = process.argv.slice(2);
+const sampleIdx = args.indexOf('--sample');
+const sample = sampleIdx !== -1 ? parseInt(args[sampleIdx + 1]) : 10;
+
+console.log(`\n🧪 Nightly Vibe Test Setup`);
+console.log(` Sample: ${sample} prompts × 3 targets = ${sample * 3} total tasks\n`);
+
+// 1. Sample prompts once — reuse across all targets
+const allPrompts = loadTestSet();
+const prompts = samplePrompts(allPrompts, sample);
+const promptIds = prompts.map(p => p.id);
+console.log(`📋 Selected ${prompts.length} prompts from ${allPrompts.length} total`);
+console.log(` IDs: ${promptIds.join(', ')}\n`);
+
+// 2. Create iterations for all three targets
+const xds = createIteration('xds', prompts, generateXdsTaskPrompt);
+const baseline = createIteration('baseline', prompts, generateBaselineTaskPrompt);
+const html = createIteration('html', prompts, generateHtmlTaskPrompt);
+
+console.log(`✅ All iterations ready:\n`);
+console.log(` XDS: ${xds.iterationId} (${xds.iterDir})`);
+console.log(` Baseline: ${baseline.iterationId} (${baseline.iterDir})`);
+console.log(` HTML: ${html.iterationId} (${html.iterDir})\n`);
+
+// 3. Output structured data for the nightly runner
+const nightlyConfig = {
+ createdAt: timestamp(),
+ sample,
+ promptIds,
+ iterations: {
+ xds: xds.iterationId,
+ baseline: baseline.iterationId,
+ html: html.iterationId,
+ },
+ dirs: {
+ xds: xds.iterDir,
+ baseline: baseline.iterDir,
+ html: html.iterDir,
+ },
+};
+
+// Write config for the runner to pick up
+const configPath = path.join(RESULTS_DIR, 'nightly-config.json');
+fs.writeFileSync(configPath, JSON.stringify(nightlyConfig, null, 2));
+console.log(`📄 Config written: ${configPath}\n`);
+
+// Print spawn instructions
+console.log(`## XDS agents (CLI retrieval on MacBook):\n`);
+for (const p of prompts) {
+ console.log(` ${xds.iterDir}/tasks/${p.id}.json`);
+}
+console.log(`\n## Baseline agents (read .baseline-docs/):\n`);
+for (const p of prompts) {
+ console.log(` ${baseline.iterDir}/tasks/${p.id}.json`);
+}
+console.log(`\n## HTML agents (no docs):\n`);
+for (const p of prompts) {
+ console.log(` ${html.iterDir}/tasks/${p.id}.json`);
+}
+
+console.log(`\n## After all agents complete:\n`);
+console.log(` # tsc type-checking`);
+console.log(` npx tsx src/build-previews.ts --iterations "${xds.iterationId},${baseline.iterationId},${html.iterationId}" --tsc-only`);
+console.log(`\n # Evaluation`);
+console.log(` npx tsx src/universal-aggregate.ts --iteration ${xds.iterationId}`);
+console.log(` npx tsx src/universal-aggregate.ts --iteration ${baseline.iterationId}`);
+console.log(` npx tsx src/universal-aggregate.ts --iteration ${html.iterationId}`);
+console.log(` npx tsx src/universal-compare.ts --xds ${xds.iterationId} --baseline ${baseline.iterationId} --html ${html.iterationId}`);
+console.log(`\n # Deploy report`);
+console.log(` npx tsx src/deploy-report.ts --iteration ${xds.iterationId} --baseline ${baseline.iterationId} --html ${html.iterationId}`);
diff --git a/internal/vibe-tests/src/universal-eval.ts b/internal/vibe-tests/src/universal-eval.ts
index 48519fd2fa..8534c5bd4c 100644
--- a/internal/vibe-tests/src/universal-eval.ts
+++ b/internal/vibe-tests/src/universal-eval.ts
@@ -67,7 +67,9 @@ export function loadBuildErrors(iterDir: string): BuildErrors | null {
}
try {
- const data = JSON.parse(_fs.readFileSync(errorsPath, 'utf-8')) as BuildErrors;
+ const data = JSON.parse(
+ _fs.readFileSync(errorsPath, 'utf-8'),
+ ) as BuildErrors;
buildErrorsCache.set(iterDir, data);
return data;
} catch {
@@ -82,7 +84,10 @@ export function loadBuildErrors(iterDir: string): BuildErrors | null {
* Each type error: -15
* Floor at 0
*/
-function scoreTscErrors(tscResult: TscResult): {score: number; findings: UniversalFinding[]} {
+function scoreTscErrors(tscResult: TscResult): {
+ score: number;
+ findings: UniversalFinding[];
+} {
const findings: UniversalFinding[] = [];
for (const err of tscResult.errors) {
@@ -99,304 +104,22 @@ function scoreTscErrors(tscResult: TscResult): {score: number; findings: Univers
}
// ============================================================
-// 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 {
- 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',
- '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',
- 'XDSSelectorOption',
- 'XDSSkeleton',
- 'XDSSlider',
- 'XDSSpinner',
- 'XDSStack',
- 'XDSStackItem',
- 'XDSStatusDot',
- 'XDSSwitch',
- 'XDSTab',
- 'XDSTabList',
- 'XDSTabMenu',
- 'XDSTable',
- 'XDSTableCell',
- 'XDSTableHeaderCell',
- 'XDSTableRow',
- 'XDSText',
- 'XDSTextArea',
- 'XDSTextInput',
- 'XDSTheme',
- 'XDSTimeInput',
- 'XDSTooltip',
- 'XDSTopNav',
- 'XDSTopNavItem',
- 'XDSTopNavMenu',
- 'XDSTopNavHeading',
- 'XDSNavIcon',
- '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
+// 1. Correctness (tsc-based)
// ============================================================
function analyzeCorrectness(
code: string,
- target: string,
+ _target: string,
tscResult?: TscResult | null,
): DimensionScore {
- // If tsc results are available, use them as primary correctness signal
+ // tsc results are the sole correctness signal
if (tscResult) {
- const {score: tscScore, findings: tscFindings} = scoreTscErrors(tscResult);
-
- // Add regex-based supplementary findings (hallucinated tokens, unknown components)
- const regexFindings = analyzeCorrectnessRegex(code, target);
-
- // Combine: tsc errors are primary, regex findings are additive
- const allFindings = [...tscFindings, ...regexFindings.findings];
- const regexPenalty = regexFindings.findings.reduce((sum, f) => {
- switch (f.severity) {
- case 'critical': return sum + 20;
- case 'moderate': return sum + 8;
- case 'minor': return sum + 3;
- default: return sum;
- }
- }, 0);
-
- const finalScore = Math.max(0, tscScore - regexPenalty);
- return {score: clamp(finalScore), findings: allFindings};
+ const {score, findings} = scoreTscErrors(tscResult);
+ return {score: clamp(score), findings};
}
- // Fallback: regex-only scoring (backwards compat with older iterations)
- const {score, findings} = analyzeCorrectnessRegex(code, target);
- return {score: clamp(score), findings};
-}
-
-/**
- * Regex-based correctness checks (supplementary to tsc).
- * Detects hallucinated components and tokens that tsc might not catch.
- */
-function analyzeCorrectnessRegex(
- code: string,
- target: string,
-): {score: number; findings: UniversalFinding[]} {
+ // No tsc data available — check for missing export only
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',
@@ -405,23 +128,12 @@ function analyzeCorrectnessRegex(
});
}
- // Score
+ // Without tsc data, assume code is correct (backwards compat for old iterations)
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;
- }
+ score -= f.severity === 'minor' ? 3 : 0;
}
-
- return {score, findings};
+ return {score: clamp(score), findings};
}
// ============================================================