An open source design system that's fully customizable and agent ready
TypeScript
Improve vibe test harness with natural prompts and external evaluation (#73)
Cindy Zhang21d38be5cae0
diff --git a/internal/vibe-tests/src/aggregate.ts b/internal/vibe-tests/src/aggregate.tsindex 8ad5330431..359f7b4e14 100644--- a/internal/vibe-tests/src/aggregate.ts+++ b/internal/vibe-tests/src/aggregate.ts@@ -451,49 +451,274 @@ function analyzeGaps(results: TestResult[]): GapSuggestion[] {}/**- * Load results from individual result files- * Optionally infers timing from file timestamps if durationMs is 0+ * Extract XDS components used from code imports+ */+function extractComponentsFromCode(code: string): string[] {+ const components: string[] = [];+ // Match imports from @xds/core or @xds/core/*+ const importRegex = /import\s+\{([^}]+)\}\s+from\s+['"]@xds\/core[^'"]*['"]/g;+ let match;+ while ((match = importRegex.exec(code)) !== null) {+ const imports = match[1].split(',').map(s => s.trim());+ for (const imp of imports) {+ // Handle "Foo as Bar" syntax+ const name = imp.split(/\s+as\s+/)[0].trim();+ if (name.startsWith('XDS')) {+ components.push(name);+ }+ }+ }+ return [...new Set(components)];+}++/**+ * Detect escape hatches in code+ */+function detectEscapeHatches(code: string): EscapeHatch[] {+ const hatches: EscapeHatch[] = [];++ // Check for hardcoded colors (hex, rgb, hsl, or named colors in style context)+ const hardcodedColorRegex =+ /(?:color|background|border|fill|stroke)\s*:\s*['"]?(#[0-9a-fA-F]{3,8}|rgb\([^)]+\)|hsl\([^)]+\)|rgba\([^)]+\)|hsla\([^)]+\))['"]?/gi;+ let match;+ while ((match = hardcodedColorRegex.exec(code)) !== null) {+ hatches.push({+ type: 'hardcoded_color',+ severity: 'acceptable',+ detail: 'Hardcoded color value instead of CSS variable',+ codeSnippet: match[0],+ });+ }++ // Check for hardcoded spacing (px values in padding, margin, gap)+ const hardcodedSpacingRegex =+ /(?:padding|margin|gap|top|bottom|left|right|width|height)\s*:\s*['"]?\d+px['"]?/gi;+ while ((match = hardcodedSpacingRegex.exec(code)) !== null) {+ // Skip if it's inside a var() or uses spacing tokens+ if (!match[0].includes('var(')) {+ hatches.push({+ type: 'hardcoded_spacing',+ severity: 'acceptable',+ detail: 'Hardcoded spacing value instead of spacing token',+ codeSnippet: match[0],+ });+ }+ }++ // Check for inline style props (not StyleX)+ const inlineStyleRegex = /style\s*=\s*\{\{/g;+ while ((match = inlineStyleRegex.exec(code)) !== null) {+ hatches.push({+ type: 'inline_style',+ severity: 'acceptable',+ detail: 'Inline style object instead of StyleX',+ codeSnippet: match[0],+ });+ }++ // Check for wrapper divs (plain divs that could use XDS layout)+ const wrapperDivRegex = /<div\s+(?:className|style)/g;+ while ((match = wrapperDivRegex.exec(code)) !== null) {+ hatches.push({+ type: 'wrapper_div',+ severity: 'acceptable',+ detail: 'Wrapper div that could potentially use XDS layout components',+ codeSnippet: match[0],+ });+ }++ // Check for hallucinated props (common mistakes)+ // Only flag clearly invalid patterns, not valid but uncommon props+ const hallucinatedProps = [+ {pattern: /variant\s*=\s*["']outline["']/g, prop: 'variant="outline"'},+ {pattern: /size\s*=\s*["'](?:xs|xxl|xxxl)["']/g, prop: 'invalid size prop'},+ ];+ for (const {pattern, prop} of hallucinatedProps) {+ if (pattern.test(code)) {+ hatches.push({+ type: 'hallucination',+ severity: 'critical',+ detail: `Potentially hallucinated prop: ${prop}`,+ codeSnippet: prop,+ });+ }+ }++ // Check for StyleX with valid CSS variables (this is acceptable - supplemental_css)+ const stylexBlockRegex = /stylex\.create\(\{[\s\S]*?\}\)/g;+ while ((match = stylexBlockRegex.exec(code)) !== null) {+ // Only flag if it has significant styling (not just layout)+ const block = match[0];+ if (+ block.includes('backgroundColor') ||+ block.includes('borderColor') ||+ block.includes('color:')+ ) {+ // Check if using CSS variables+ if (block.includes('var(--')) {+ hatches.push({+ type: 'supplemental_css',+ severity: 'acceptable',+ detail: 'StyleX styling using CSS variables',+ codeSnippet: block.slice(0, 100) + '...',+ });+ }+ }+ }++ return hatches;+}++/**+ * Load results from individual result files (.tsx code files)+ * Evaluates code externally instead of relying on self-evaluation*/function loadResults(resultsDir: string): TestResult[] {const individualResultsDir = path.join(resultsDir, 'results');const tasksDir = path.join(resultsDir, 'tasks');+ const manifestPath = path.join(resultsDir, 'manifest.json');const results: TestResult[] = [];if (!fs.existsSync(individualResultsDir)) {throw new Error(`No results directory found at ${individualResultsDir}`);}- const files = fs+ // Try to load .tsx files first (new natural prompt format)+ let files = fs.readdirSync(individualResultsDir)- .filter(f => f.endsWith('.json'));+ .filter(f => f.endsWith('.tsx'));+ // Fall back to .json files if no .tsx files foundif (files.length === 0) {- throw new Error(`No result files found in ${individualResultsDir}`);+ files = fs+ .readdirSync(individualResultsDir)+ .filter(f => f.endsWith('.json'));++ if (files.length === 0) {+ throw new Error(`No result files found in ${individualResultsDir}`);+ }++ // Process JSON files (legacy format)+ for (const file of files) {+ try {+ const resultPath = path.join(individualResultsDir, file);+ const content = fs.readFileSync(resultPath, 'utf-8');+ const result = JSON.parse(content) as TestResult;++ // Infer timing from file timestamps if durationMs is 0 or missing+ if (!result.durationMs || result.durationMs === 0) {+ const taskPath = path.join(tasksDir, file);+ if (fs.existsSync(taskPath)) {+ const taskStat = fs.statSync(taskPath);+ const resultStat = fs.statSync(resultPath);+ const inferredDurationMs = resultStat.mtimeMs - taskStat.mtimeMs;+ if (inferredDurationMs > 0) {+ result.durationMs = Math.round(inferredDurationMs);+ }+ }+ }++ results.push(result);+ } catch (e) {+ console.warn(`Warning: Failed to parse ${file}: ${e}`);+ }+ }++ return results;}+ // Load manifest for iteration info+ let manifest: {iterationId: string; config: {persona: string}} | null = null;+ if (fs.existsSync(manifestPath)) {+ try {+ manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));+ } catch {+ console.warn('Warning: Could not parse manifest.json');+ }+ }++ // Process .tsx files (new format - external evaluation)for (const file of files) {try {+ const promptId = file.replace('.tsx', '');const resultPath = path.join(individualResultsDir, file);- const content = fs.readFileSync(resultPath, 'utf-8');- const result = JSON.parse(content) as TestResult;-- // Infer timing from file timestamps if durationMs is 0 or missing- if (!result.durationMs || result.durationMs === 0) {- const taskPath = path.join(tasksDir, file);- if (fs.existsSync(taskPath)) {- const taskStat = fs.statSync(taskPath);- const resultStat = fs.statSync(resultPath);- // Duration = result file mtime - task file mtime- const inferredDurationMs = resultStat.mtimeMs - taskStat.mtimeMs;- if (inferredDurationMs > 0) {- result.durationMs = Math.round(inferredDurationMs);- }+ const taskPath = path.join(tasksDir, `${promptId}.json`);+ const metaPath = path.join(individualResultsDir, `${promptId}.meta.json`);++ // Read the generated code+ const code = fs.readFileSync(resultPath, 'utf-8');++ // Load task metadata+ let task: {+ promptId: string;+ category: string;+ prompt: string;+ expectedComponents: string[];+ persona: string;+ } | null = null;+ if (fs.existsSync(taskPath)) {+ task = JSON.parse(fs.readFileSync(taskPath, 'utf-8'));+ }++ // Load docs read metadata if available+ let docsRead: string[] | undefined;+ if (fs.existsSync(metaPath)) {+ try {+ const meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8'));+ docsRead = meta.docsRead;+ } catch {+ console.warn(`Warning: Could not parse ${metaPath}`);}}+ // External evaluation: extract components and detect escape hatches+ const componentsUsed = extractComponentsFromCode(code);+ const escapeHatches = detectEscapeHatches(code);++ // Determine success based on critical escape hatches+ const hasCritical = escapeHatches.some(h => h.severity === 'critical');+ const success = !hasCritical;++ // Infer timing from file timestamps+ let durationMs = 0;+ if (fs.existsSync(taskPath)) {+ const taskStat = fs.statSync(taskPath);+ const resultStat = fs.statSync(resultPath);+ const inferredDurationMs = resultStat.mtimeMs - taskStat.mtimeMs;+ if (inferredDurationMs > 0) {+ durationMs = Math.round(inferredDurationMs);+ }+ }++ const result: TestResult = {+ id: `${manifest?.iterationId || 'unknown'}-${promptId}`,+ timestamp: new Date().toISOString(),+ systemVersion: 'claude-code-interactive',+ model: 'claude-code-interactive',+ persona: task?.persona || manifest?.config?.persona || 'naive',+ promptCategory: task?.category || 'unknown',+ trajectoryDepth: 0,+ prompt: task?.prompt || promptId,+ response: code,+ evaluation: {+ success,+ componentsUsed,+ componentsExpected: task?.expectedComponents || [],+ escapeHatches,+ failureMode: hasCritical ? 'Critical escape hatches detected' : null,+ confusionSignals: [],+ },+ fullConversation: [],+ contextWindowUsage: 0,+ durationMs,+ inputTokens: 0,+ outputTokens: 0,+ docsRead,+ };+results.push(result);} catch (e) {- console.warn(`Warning: Failed to parse ${file}: ${e}`);+ console.warn(`Warning: Failed to process ${file}: ${e}`);}}diff --git a/internal/vibe-tests/src/interactive.ts b/internal/vibe-tests/src/interactive.tsindex 97567120a1..75577a3de2 100644--- a/internal/vibe-tests/src/interactive.ts+++ b/internal/vibe-tests/src/interactive.ts@@ -215,13 +215,22 @@ function createTaskManifest(ensureDir(tasksDir);for (const prompt of prompts) {- const task: AgentTask = {+ // Generate the complete subagent prompt+ const subagentPrompt = generateSubagentPrompt(+ iterationId,+ prompt,+ config,+ resultsDir,+ );++ const task: AgentTask & {subagentPrompt: string} = {promptId: prompt.id,category: prompt.category,prompt: prompt.prompt,expectedComponents: prompt.expectedComponents,persona: config.persona,degradation: config.degradation,+ subagentPrompt,};writeJson(path.join(tasksDir, `${prompt.id}.json`), task);}@@ -232,6 +241,38 @@ function createTaskManifest(console.log(`Individual tasks: ${tasksDir}/`);}+/**+ * Generate the complete prompt for a subagent to run a single test+ */+function generateSubagentPrompt(+ iterationId: string,+ prompt: TestPrompt,+ config: InteractiveConfig,+ resultsDir: string,+): string {+ const codePath = `${resultsDir}/results/${prompt.id}.tsx`;+ const metaPath = `${resultsDir}/results/${prompt.id}.meta.json`;++ // Persona-specific framing to simulate different user types+ const personaFraming: Record<string, string> = {+ naive: '', // No special framing - just the natural request+ experienced: `Use XDS components from @xds/core. `,+ adversarial: `I'm used to Tailwind/shadcn patterns but need to use your design system. `,+ };++ const framing = personaFraming[config.persona] || '';++ // Natural prompt with AGENTS.md instruction and metadata tracking+ return `First read AGENTS.md in this directory for component library guidance.++${framing}${prompt.prompt}++Write the code to: ${codePath}++After writing the code, create ${metaPath} listing any doc files you read:+{"docsRead": ["filename1.md", "filename2.md"]}`;+}+/*** Generate instructions for running tests with subagents*/diff --git a/packages/agent-tools/bin/agents-md.mjs b/packages/agent-tools/bin/agents-md.mjsindex ea2dd23c10..ea546ab25b 100755--- a/packages/agent-tools/bin/agents-md.mjs+++ b/packages/agent-tools/bin/agents-md.mjs@@ -133,18 +133,88 @@ function findComponentReadmes(coreDir) {return readmes;}+/**+ * Discover all XDS components by scanning for XDS*.tsx files+ * Returns { components: string[], layout: string[] }+ */+function discoverComponents(coreDir) {+ const srcDir = path.join(coreDir, 'src');+ const components = new Set();+ const layoutComponents = new Set();++ // Layout-related directory names+ const LAYOUT_DIRS = ['Layout', 'Grid', 'Center', 'Divider', 'AspectRatio', 'Section'];++ if (!fs.existsSync(srcDir)) {+ return { components: [], layout: [] };+ }++ /**+ * Recursively scan a directory for XDS*.tsx files+ */+ function scanDir(dirPath, isLayoutContext) {+ const entries = fs.readdirSync(dirPath, { withFileTypes: true });++ for (const entry of entries) {+ const fullPath = path.join(dirPath, entry.name);++ if (entry.isDirectory()) {+ // Recurse into subdirectories+ scanDir(fullPath, isLayoutContext);+ } else if (+ entry.name.startsWith('XDS') &&+ entry.name.endsWith('.tsx') &&+ !entry.name.includes('.test.')+ ) {+ const componentName = entry.name.replace('.tsx', '');+ if (isLayoutContext) {+ layoutComponents.add(componentName);+ } else {+ components.add(componentName);+ }+ }+ }+ }++ const entries = fs.readdirSync(srcDir, { withFileTypes: true });++ for (const entry of entries) {+ if (!entry.isDirectory()) continue;++ const dirPath = path.join(srcDir, entry.name);+ const isLayoutDir = LAYOUT_DIRS.includes(entry.name);++ scanDir(dirPath, isLayoutDir);+ }++ // Sort alphabetically for consistent output+ return {+ components: [...components].sort(),+ layout: [...layoutComponents].sort(),+ };+}+/*** Compressed index for AGENTS.md* Uses pipe-delimited format for 80% token reduction per Vercel research*/-function generateCompressedIndex(version) {+function generateCompressedIndex(version, discoveredComponents) {+ // Use discovered components if available, otherwise use defaults+ const componentList = discoveredComponents?.components?.length > 0+ ? discoveredComponents.components.join('|')+ : 'Button|TextInput|TextArea|CheckboxInput|Field|Layout|Layer|Avatar|Skeleton|Text|Icon';++ const layoutList = discoveredComponents?.layout?.length > 0+ ? discoveredComponents.layout.join('|')+ : 'XDSLayout|XDSLayoutHeader|XDSLayoutContent|XDSLayoutPanel|XDSHStack|XDSVStack|XDSCard';+return `${XDS_MARKER_START}[XDS Component Library v${version}]|root: ./${XDS_DOCS_DIR}|IMPORTANT: Prefer retrieval-led reasoning. Read docs from .xds-docs/ before generating XDS code.|principles.md: Key rules, anti-patterns, StyleX patterns|tokens.md: Full design token reference (spacing, colors, radius, typography)-|components: Button|TextInput|TextArea|CheckboxInput|Field|Layout|Layer|Avatar|Skeleton|Text|Icon-|layout: XDSLayout|XDSLayoutHeader|XDSLayoutContent|XDSLayoutPanel|XDSHStack|XDSVStack|XDSCard+|layout: ${layoutList}+|components: ${componentList}|theme: Theme provider, defaultTheme, CSS variables via StyleX|For component API: read .xds-docs/{ComponentName}.md${XDS_MARKER_END}`;@@ -250,9 +320,9 @@ function installDocs(targetDir) {/*** Inject or update XDS section in AGENTS.md*/-function injectAgentsMd(targetDir, version) {+function injectAgentsMd(targetDir, version, discoveredComponents) {const agentsPath = path.join(targetDir, AGENTS_MD);- const compressedIndex = generateCompressedIndex(version);+ const compressedIndex = generateCompressedIndex(version, discoveredComponents);let content = '';@@ -384,7 +454,13 @@ if (args.includes('--remove')) {process.exit(1);}- injectAgentsMd(targetDir, version);+ // Discover components dynamically+ const discoveredComponents = coreDir ? discoverComponents(coreDir) : null;+ if (discoveredComponents) {+ console.log(`✓ Discovered ${discoveredComponents.layout.length} layout + ${discoveredComponents.components.length} other components`);+ }++ injectAgentsMd(targetDir, version, discoveredComponents);console.log(`✓ Injected compressed index into ${AGENTS_MD}`);updateGitignore(targetDir);