Skip to content

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

TypeScript

fix test harness -- token and time spent, breakdown by jobs (#65)

Cindy Zhange734a0a4d257
diff --git a/.context/proposals/vibeability-test-harness.md b/.context/proposals/vibeability-test-harness.md
index 6bc90412a6..f3dee18298 100644
--- a/.context/proposals/vibeability-test-harness.md
+++ b/.context/proposals/vibeability-test-harness.md
@@ -5,24 +5,31 @@ Build a test harness that measures how well LLMs can use a component system, tra
## Directory Structure
```
-tools/vibeability-harness/
-├── harness.ts # Main entry point (Deno)
+internal/vibe-tests/
+├── src/
+│ ├── interactive.ts # Sets up test iteration for Claude Code subagents
+│ ├── run-interactive.ts # Generates subagent spawn instructions
+│ ├── aggregate.ts # Aggregates results, generates reports
+│ ├── types.ts # Core type definitions
+│ └── utils.ts # Shared utilities
+├── docs/
+│ └── job-taxonomy.md # Token/time analysis documentation
├── prompts/
-│ ├── evaluator.md # Judges generated code against criteria
-│ ├── analyst.md # Analyzes results, suggests refinements
-│ └── personas/
-│ ├── naive.md # "I want a card with an image"
-│ ├── experienced.md # Uses correct terminology
-│ └── adversarial.md # References competing patterns
-├── test-sets/
-│ └── default.json # Prompt battery organized by category
+│ └── test-set.json # Prompt battery organized by category
├── results/
│ └── {iteration-id}/
-│ ├── runs.jsonl # Append-only test results
-│ ├── report.html # Visual report with live previews
-│ ├── analysis.json # Analyst output
-│ └── refinements.json
-└── iterations.json # Tracks lineage across refinement cycles
+│ ├── manifest.json # Iteration metadata
+│ ├── tasks/ # Individual task files for subagents
+│ │ └── {promptId}.json
+│ ├── results/ # Individual result files (avoids race conditions)
+│ │ └── {promptId}.json
+│ ├── aggregate.json # Aggregated metrics
+│ └── report.html # Visual report with charts
+└── .xds-docs/ # XDS documentation (auto-injected via AGENTS.md)
+ ├── AGENTS.md
+ ├── principles.md
+ ├── tokens.md
+ └── {Component}.md
```
## Core Types
@@ -35,32 +42,73 @@ interface Turn {
evaluation?: Evaluation;
}
+type EscapeHatchType =
+ | 'hallucination'
+ | 'wrong_component'
+ | 'redundant_css'
+ | 'supplemental_css'
+ | 'wrapper_div'
+ | 'inline_style' // Anti-pattern: should use StyleX instead
+ | 'hardcoded_color' // Anti-pattern: breaks theming
+ | 'hardcoded_spacing' // Anti-pattern: breaks spacing system
+ | 'hardcoded_size' // Acceptable: explicit sizes are often needed
+ | 'custom_animation' // Gap: missing animation support
+ | 'layout_workaround'; // Gap: missing layout primitive
+
+type EscapeHatchSeverity = 'critical' | 'acceptable';
+
interface EscapeHatch {
- type:
- | 'hallucination'
- | 'wrong_component'
- | 'redundant_css'
- | 'supplemental_css'
- | 'wrapper_div'
- | 'inline_style';
- severity: 'critical' | 'acceptable';
+ type: EscapeHatchType;
+ severity: EscapeHatchSeverity;
detail: string;
codeSnippet: string;
+ gap?: string; // What capability gap does this represent?
}
+/**
+ * Result quality tiers:
+ * - gold: Pure XDS, no escape hatches needed
+ * - green: Correct components, only acceptable escape hatches
+ * - yellow: Minor issues (anti-patterns like hardcoded values)
+ * - red: Critical failures (hallucinations, wrong components)
+ */
+type ResultTier = 'gold' | 'green' | 'yellow' | 'red';
+
interface Evaluation {
success: boolean;
+ tier?: ResultTier;
componentsUsed: string[];
componentsExpected: string[];
- escapeHatches: EscapeHatch[];
+ escapeHatches: (string | EscapeHatch)[];
+ escapeHatchCount?: number;
failureMode: string | null;
- confusionSignals: string[]; // hedging language, clarifying questions
+ confusionSignals: string[];
+}
+
+/** Job breakdown for output token analysis */
+interface JobBreakdown {
+ componentRouting: number; // Import statements for XDS components
+ componentConfig: number; // Props and configuration on XDS components
+ supplementalStyling: number; // StyleX blocks
+ contentAuthoring: number; // HTML structure, JSX
+ businessLogic: number; // State, handlers, logic
+ boilerplate: number; // Type definitions, exports
+ total: number;
+}
+
+/** Input token breakdown by doc type */
+interface InputTokenBreakdown {
+ agentsMd: number; // AGENTS.md - always read
+ designDocs: number; // principles.md, tokens.md
+ componentDocs: number; // Component-specific docs (Button.md, etc.)
+ promptOverhead: number; // Task instructions
+ total: number;
}
interface TestResult {
id: string;
timestamp: string;
- systemVersion: string; // hash or version of skill doc
+ systemVersion: string;
model: string;
persona: string;
promptCategory: string;
@@ -70,289 +118,251 @@ interface TestResult {
evaluation: Evaluation;
fullConversation: Turn[];
contextWindowUsage: number;
+ // Timing and usage metrics
+ durationMs: number;
+ inputTokens: number;
+ outputTokens: number;
+ // Optional detailed breakdowns
+ jobBreakdown?: JobBreakdown;
+ docsRead?: string[]; // Docs accessed during generation
}
interface Refinement {
target: 'skill_doc' | 'component_api' | 'component_naming' | 'examples';
component: string | null;
suggestion: string;
- evidence: string[]; // TestResult IDs
+ evidence: string[];
confidence: number;
effortEstimate: 'trivial' | 'moderate' | 'significant';
}
-
-interface Iteration {
- id: string;
- parentIteration: string | null;
- skillDocHash: string;
- refinementsApplied: Refinement[];
- aggregateMetrics: {
- overallSuccessRate: number;
- byCategory: Record<string, number>;
- byPersona: Record<string, number>;
- degradationCliff: number; // avg turn where accuracy drops below 80%
- };
- analystSummary: string;
- nextRefinements: Refinement[];
- promptsRun: string[]; // IDs of prompts actually run (may be sampled subset)
- promptsTotal: number; // total prompts in pool
-}
-
-interface TestPrompt {
- id: string;
- category: string;
- prompt: string;
- expectedComponents: string[];
- complexity: 'simple' | 'moderate' | 'complex';
-}
-
-interface TestSet {
- name: string;
- prompts: TestPrompt[];
- holdout?: TestPrompt[]; // separate prompts for unbiased evaluation
- fillerPrompts?: string[];
- distractorPrompts?: string[];
- recoveryContext?: string;
-}
```
-## Escape Hatch Severity
-
-Escape hatches have two severity levels that determine whether they count against success:
-
-**Critical** (counts against success):
+## Quality Tiers
-- `hallucination` — Inventing props, components, events, or APIs that don't exist
-- `wrong_component` — Using a component for something it wasn't designed for
-- `redundant_css` — CSS that duplicates what a component prop already handles
+Results are categorized into quality tiers for nuanced analysis:
-**Acceptable** (noted but does NOT count against success):
+| Tier | Icon | Meaning | Counts as Success |
+| ------ | ---- | ---------------------------------------------------- | ----------------- |
+| Gold | 🥇 | Pure XDS, no escape hatches needed | Yes |
+| Green | 🟢 | Correct components, only acceptable escape hatches | Yes |
+| Yellow | 🟡 | Anti-patterns (hardcoded values break theming) | Yes |
+| Red | 🔴 | Critical failures (hallucinations, wrong components) | No |
-- `supplemental_css` — CSS for things the component system doesn't cover (layout gaps, responsive breakpoints, animations, decoration)
-- `wrapper_div` — Structural HTML needed to compose components
-- `inline_style` — Minor inline styles for things without a component prop
+## Token Usage Breakdown
-The component system doesn't aim for 100% coverage. CSS for layout, responsive behavior, or decoration outside component scope is expected and acceptable.
+The harness tracks token usage across two dimensions:
-## Prompt Categories for Test Set
-
-Generate realistic user prompts (goal-oriented, not component-oriented) in these categories:
-
-1. **feature-with-constraint**: "I need a banner that warns users their trial expires in X days and lets them upgrade"
-2. **workflow-description**: "Build a checkout flow: cart summary → shipping → payment → confirmation"
-3. **clone-with-modification**: "Something like Stripe's pricing table but with monthly/annual toggle"
-4. **state-driven**: "Show a dashboard with loading → error → data states"
-5. **data-display**: "A table of users with sortable columns and search"
-6. **responsive-context**: "Navigation that collapses to hamburger on mobile"
-7. **integration-oriented**: "A form that validates email and posts to /api/subscribe"
+### Input Tokens (estimated from doc reading)
-Each category should have 3-5 prompts at varying complexity. The test set also includes a `holdout` array with different prompts per category for unbiased evaluation.
-
-## Prompt Sampling
-
-To prevent refinement suggestions from overfitting to specific test prompts:
-
-- **`--sample N`**: Stratified sampling — selects N prompts with at least 1 per category, distributes remaining slots round-robin. Each run sees a different subset.
-- **`--holdout`**: Runs the holdout prompt set instead of the main set. Use to validate that doc improvements generalize beyond training prompts.
-- **No flag**: Runs all prompts (original behavior).
-
-Iteration metadata records `promptsRun` (IDs of prompts used) and `promptsTotal` (pool size) so the analyst knows whether results are from a sample.
-
-## Test Protocols
+| Source | Description | Est. Tokens |
+| ------------------- | ------------------------------------------- | -------------- |
+| **AGENTS.md** | Component catalog and XDS guidance | ~173 |
+| **Design docs** | principles.md, tokens.md - styling patterns | ~1,200 |
+| **Component docs** | Button.md, TextInput.md, etc. | 300-2,000 each |
+| **Prompt overhead** | Task instructions and persona | ~375 |
-### One-shot baseline
+### Output Tokens (by job type)
-1. Inject skill doc as system context
-2. Run each prompt from test set (or sampled subset)
-3. Evaluate response
-4. Record result
+Each generated code response is analyzed by job category:
-### Degradation curve
+| Job | Description | Typical % |
+| ------------------------ | ------------------------------------------- | --------- |
+| **Component Routing** | Import statements for XDS components | 3-10% |
+| **Component Config** | Props and attributes on XDS components | 7-30% |
+| **Supplemental Styling** | StyleX blocks for layout/spacing gaps | 10-27% |
+| **Content Authoring** | HTML structure, JSX elements, copy | 15-27% |
+| **Business Logic** | useState, handlers, API calls, conditionals | 5-51% |
+| **Boilerplate** | Type definitions, imports, exports | 5-10% |
-1. Inject skill doc
-2. Probe with test prompt, evaluate (turn 0)
-3. Run 5 filler turns (unrelated coding questions)
-4. Re-probe with natural framing, evaluate (turn 6)
-5. Inject distractor ("now do it in Tailwind")
-6. Re-probe with natural framing, evaluate (turn 8)
-7. Inject recovery (re-inject partial skill doc)
-8. Re-probe with natural framing, evaluate (turn 10)
-9. Plot accuracy over turns
+Business logic dominates integration-oriented prompts (51%), while page-setup prompts are more balanced across styling, content, and config.
-Re-probes use conversational framing (e.g., "Actually, let me revisit this. {prompt}" or "I want to redo that earlier request. {prompt}") instead of repeating the prompt verbatim. This prevents the LLM from noticing duplicate requests and hedging. Evaluation still uses the original prompt expectations.
+## Timing
-### Persona comparison
+Timing is tracked per test and aggregated per category:
-Run same prompt set with each persona, compare success rates and failure modes.
+- **Per test**: `durationMs` field in TestResult
+- **Inferred**: When not reported, timing is calculated from file timestamps (task creation → result write)
+- **Per category**: Average duration shown in aggregate reports
-## Agent Prompts
-
-### Evaluator (prompts/evaluator.md)
-
-You evaluate LLM-generated UI code against a component system.
-
-Given:
-
-- The user's prompt
-- The generated response
-- The expected components for this task
-
-Return JSON matching the Evaluation schema. Key rules:
-
-- **Success = correct components used where they exist + no critical escape hatches**
-- Custom CSS for things the component system doesn't cover is acceptable
-- Hallucinated props/events are always critical
-- `redundant_css` is critical only when a component prop exists for the same thing
-- A response can be successful AND have acceptable escape hatches
+## Escape Hatch Severity
-### Analyst (prompts/analyst.md)
+**Critical** (red tier - counts against success):
-You analyze batches of vibeability test results to identify patterns and suggest refinements.
+- `hallucination` — Inventing props, components, or APIs that don't exist
+- `wrong_component` — Using a component incorrectly
+- `redundant_css` — CSS that duplicates component props
-Look for:
+**Anti-pattern** (yellow tier - noted, still success):
-- Which prompt categories fail most often
-- Which components get hallucinated or misused
-- Where degradation typically starts in long conversations
-- Whether certain personas expose different weaknesses
-- **Critical** escape hatch patterns only (ignore acceptable ones)
+- `inline_style` — Should use StyleX
+- `hardcoded_color` — Breaks theming
+- `hardcoded_spacing` — Breaks spacing system
-Root cause categories:
+**Acceptable** (green tier - expected gaps):
-- **Documentation gap**: Component exists but isn't well explained
-- **Naming confusion**: Component name suggests wrong usage
-- **Missing example**: Use case isn't demonstrated
-- **API complexity**: Too many props or unclear defaults
-- **Competing patterns**: Other frameworks' patterns interfere
-- **Component gap**: No component exists for this need (flag for component team, not a doc fix)
+- `supplemental_css` — CSS for layout gaps
+- `wrapper_div` — Structural HTML for composition
+- `hardcoded_size` — Explicit sizes often needed
+- `custom_animation` — Missing animation support
+- `layout_workaround` — Missing layout primitive
-Sampling awareness:
+## Prompt Categories
-- Require evidence from ≥2 different categories before suggesting a refinement (unless confidence > 0.85 for a component-specific issue)
-- Distinguish systemic doc gaps from prompt-specific quirks
-- Don't over-index on frequency in sampled results
+1. **feature-with-constraint**: "A banner warning trial expires in X days with upgrade button"
+2. **workflow-description**: "Checkout flow: cart → shipping → payment → confirmation"
+3. **clone-with-modification**: "Stripe's pricing table with monthly/annual toggle"
+4. **state-driven**: "Dashboard with loading → error → data states"
+5. **data-display**: "User table with sortable columns and search"
+6. **responsive-context**: "Navigation that collapses to hamburger on mobile"
+7. **integration-oriented**: "Form that validates email and posts to /api/subscribe"
+8. **page-setup**: "Landing page with hero, features, and CTA"
-Prioritize refinements by: high impact + low effort first.
+## Test Protocols
-### Personas
+### One-shot (default)
-**naive.md**: You describe UIs in plain language without technical terms. You don't know component names. You say things like "a box with a shadow" not "a Card component".
+1. Read XDS docs (AGENTS.md auto-injected, component docs as needed)
+2. Generate code for prompt
+3. Self-evaluate response
+4. Write result to individual file
-**experienced.md**: You know the component system well. You use correct component names and props. You might reference the docs.
+### Degradation curve (`--degradation`)
-**adversarial.md**: You mix in patterns from other systems (Tailwind, shadcn, Bootstrap). You say things like "use flex justify-between" or "like a shadcn Dialog".
+1. Probe at turn 0, evaluate
+2. Run 5 filler turns (unrelated questions)
+3. Re-probe at turn 6, evaluate
+4. Inject distractor ("now do it in Tailwind")
+5. Re-probe at turn 8, evaluate
+6. Inject recovery (re-read docs)
+7. Re-probe at turn 10, evaluate
+8. Generate line graph showing tier progression
## CLI Interface
```bash
-# Run full test battery
-deno run --allow-all harness.ts run
-
-# Run sampled subset (stratified across categories)
-deno run --allow-all harness.ts run --sample 10
+# Set up interactive test iteration
+yarn workspace @xds/vibe-tests interactive --sample 5
-# Run holdout set for unbiased evaluation
-deno run --allow-all harness.ts run --holdout
+# Set up degradation test
+yarn workspace @xds/vibe-tests interactive --sample 3 --degradation
-# Run specific protocol
-deno run --allow-all harness.ts run --protocol degradation
+# Aggregate results after subagents complete
+yarn workspace @xds/vibe-tests aggregate --iteration abc123
-# Run with specific persona
-deno run --allow-all harness.ts run --persona naive
+# Output JSON instead of console
+yarn workspace @xds/vibe-tests aggregate --iteration abc123 --json
-# Generate HTML report for visual inspection
-deno run --allow-all harness.ts report --iteration abc123
+# CI mode (non-zero exit on low success rate)
+yarn workspace @xds/vibe-tests aggregate --iteration abc123 --ci
+```
-# Analyze results from an iteration
-deno run --allow-all harness.ts analyze --iteration abc123
+## Running Tests with Subagents
-# Start new iteration with refinements applied
-deno run --allow-all harness.ts iterate --from abc123
+Tests are run via Claude Code subagents spawned in parallel:
-# View iteration history
-deno run --allow-all harness.ts history
-```
+1. Run `yarn workspace @xds/vibe-tests interactive --sample N`
+2. Spawn subagents with `mode: "bypassPermissions"` for each task
+3. Each subagent:
+ - Reads task file from `results/{iteration}/tasks/{promptId}.json`
+ - Reads XDS docs (AGENTS.md auto-injected)
+ - Generates code for the prompt
+ - Self-evaluates the response
+ - Tracks timing (start → end)
+ - Records docs read
+ - Writes result to `results/{iteration}/results/{promptId}.json`
+4. Run `yarn workspace @xds/vibe-tests aggregate --iteration {id}`
-## Configuration
+## Output Example
-Read skill doc path from env or flag:
+### Console Output
-```bash
-SKILL_DOC=./skills/brownie.md deno run --allow-all harness.ts run
```
-
-Model selection:
-
-```bash
-deno run --allow-all harness.ts run --model claude-sonnet-4-20250514
-deno run --allow-all harness.ts run --model gpt-4o
+📊 Vibe Test Results - Iteration 657c993f
+==================================================
+
+Overall: 100% success (2/2)
+
+🏆 Quality Tiers:
+ 🥇 Gold (pure XDS): 2 (100%)
+ 🟢 Green (acceptable): 0 (0%)
+ 🟡 Yellow (anti-pattern): 0 (0%)
+ 🔴 Red (critical): 0 (0%)
+
+⏱️ Performance:
+ Total time: 33.3s (avg 16.7s per test)
+
+By Category:
+ data-display 100% (1/1) [🥇1 🟢0 🟡0 🔴0] ⏱️23.3s
+ integration-oriented 100% (1/1) [🥇1 🟢0 🟡0 🔴0] ⏱️10.0s
+
+📊 Token Usage Breakdown:
+ ┌─────────────────────────────────────────────────┐
+ │ INPUT TOKENS (estimated from doc reading) │
+ ├─────────────────────────────────────────────────┤
+ │ AGENTS.md: 346 tokens │
+ │ Design docs: 2360 tokens │
+ │ Component docs: 7033 tokens │
+ │ Prompt overhead: 750 tokens │
+ │ ───────────────────────────── │
+ │ Input subtotal: 10489 tokens │
+ ├─────────────────────────────────────────────────┤
+ │ OUTPUT TOKENS (from job breakdown) │
+ ├─────────────────────────────────────────────────┤
+ │ Component routing: 3% (~73 tokens) │
+ │ Component config: 13% (~281 tokens) │
+ │ Supplemental styling: 14% (~301 tokens) │
+ │ Content authoring: 45% (~943 tokens) │
+ │ Business logic: 19% (~411 tokens) │
+ │ Boilerplate: 5% (~103 tokens) │
+ │ ───────────────────────────── │
+ │ Output subtotal: 2112 tokens │
+ ├─────────────────────────────────────────────────┤
+ │ TOTAL: 12601 tokens │
+ └─────────────────────────────────────────────────┘
+
+✓ Acceptable Escape Hatches:
+ - supplemental_css: 2
+
+💡 Gap Suggestions (component/API improvements):
+ 🔧 [trivial] Add prop or variant to cover: supplemental_css (seen 2x)
```
-## Key Implementation Notes
+### HTML Report
-- Use JSONL for results (append-only, resumable)
-- Generate iteration IDs as short hashes (first 8 chars of UUID)
-- Hash skill doc content to track versions
-- Run tests sequentially (rate limit protection with 500ms delay)
-- Store full conversation history for debugging
-- Analyst should receive batch of results, not one at a time
-- Analyst receives sampling metadata (prompts run vs total pool) to avoid overfit suggestions
-- Keep token counts rough (string length / 4 is fine)
-- Summary output separates critical issues from acceptable escape hatches
+The HTML report includes:
-## Output Example
+- Quality tier breakdown with visual bars
+- Results by category with timing
+- Token usage breakdown (input and output) - aggregate and per test
+- Degradation line graph (if degradation mode)
+- Critical issues, anti-patterns, acceptable hatches
+- Gap suggestions for component improvements
+- Individual test results with:
+ - Tier icon and category
+ - Prompt text
+ - Escape hatches (if any)
+ - Duration (e.g., 23.3s)
+ - Token breakdown: Total (input/output) with hover tooltip showing full breakdown
+ - Docs read badges (which .md files were accessed)
+ - Expandable code view
-After `harness.ts run --sample 10`:
+### Per-Run Token Breakdown
-```
-Running vibeability tests...
- Protocol: one-shot
- Persona: naive
- Model: claude-sonnet-4-20250514
- Test set: default (10 sampled from 22 prompts)
- Iteration: a1b2c3d4
-
- [████████████████████] 10/10
-
-Results:
- Overall: 70% success (7/10)
-
- By category:
- feature-with-constraint: 100%
- workflow-description: 0%
- clone-with-modification: 100%
- state-driven: 100%
- data-display: 100%
- responsive-context: 0%
- integration-oriented: 50%
-
- Critical issues:
- - hallucination (2)
- - redundant_css (1)
-
- Acceptable escape hatches:
- - supplemental_css (5)
- - wrapper_div (2)
-
- Results saved: ./results/a1b2c3d4/runs.jsonl
-
-Run `harness.ts analyze --iteration a1b2c3d4` for refinement suggestions.
-```
-
-After `harness.ts analyze`:
-
-```
-Analyzing iteration a1b2c3d4...
+Each individual test shows:
-Patterns detected:
- - "clone-with-modification" prompts trigger Tailwind patterns
- - brow-select events hallucinated (brow-open, input) across 3 categories
- - countdown/timer props frequently hallucinated on Alert
+- **Total tokens**: Sum of input + output
+- **Input/Output split**: e.g., `6245 (5189/1056)` means 5189 input, 1056 output
+- **Hover tooltip**: Full breakdown including:
+ - Input: AGENTS tokens, Design doc tokens, Component doc tokens
+ - Output: Routing, Config, Styling, Content, Logic, Boilerplate tokens
+- **Docs read**: Badges showing which docs were accessed (e.g., `AGENTS`, `principles`, `tokens`, `TextInput`)
-Suggested refinements:
- 1. [component_api] Document brow-select events explicitly (confidence: 0.9, effort: trivial)
- 2. [examples] Add countdown example to Alert docs (confidence: 0.9, effort: trivial)
- 3. [skill_doc] Add explicit "do not use Tailwind" guidance (confidence: 0.7, effort: trivial)
+## Key Implementation Notes
-Saved: ./results/a1b2c3d4/refinements.json
-```
+- **Individual result files**: Each subagent writes to `results/{promptId}.json` to avoid parallel write conflicts
+- **Timing inference**: When `durationMs` is 0, timing is inferred from file timestamps
+- **Doc tracking**: Subagents record which docs they read in `docsRead` array
+- **Token estimation**: Input tokens estimated from doc sizes (~4 chars per token)
+- **Job analysis**: Output tokens categorized by parsing code structure
+- **Quality tiers**: Gold/green/yellow/red for nuanced success tracking
+- **AGENTS.md**: Always used (auto-injected by Claude Code)
diff --git a/CLAUDE.md b/CLAUDE.md
index bfc5a38310..8fec40676f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -6,29 +6,44 @@ A design system for building internal tools and products.
### `/vibe-test [count]` - Run vibeability tests
-Tests how well the AI skill doc helps generate correct XDS component code.
+Tests how well AGENTS.md helps LLMs generate correct XDS component code.
**Usage:**
```
-/vibe-test 5 # Run 5 stratified sample tests
-/vibe-test # Run all 21 tests
+/vibe-test 5 # Run 5 stratified sample tests (one-shot)
+/vibe-test # Run all 21 tests (one-shot)
+/vibe-test 5 --degradation # Run 5 tests with degradation curve (10-turn)
```
**How to execute:**
-1. Run `yarn workspace @xds/vibe-tests interactive --sample <count>` to set up iteration
-2. Spawn parallel subagents (one per test prompt) to:
- - Read the skill doc at `packages/core/xds.md`
- - Generate code for the prompt using XDS components
+1. Run `yarn workspace @xds/vibe-tests interactive --sample <count> [--degradation]` to set up iteration
+2. Spawn parallel subagents (one per test prompt) with `mode: "bypassPermissions"` to:
+ - Read the task file from `results/<iteration>/tasks/{promptId}.json`
+ - Generate code for the prompt using XDS components (AGENTS.md auto-injected)
- Self-evaluate for success/escape hatches
- - Append result to `results/<iteration>/runs.jsonl`
+ - Write result to individual file: `results/<iteration>/results/{promptId}.json`
3. Run `yarn workspace @xds/vibe-tests aggregate --iteration <id>` to see results
-**Result format in runs.jsonl:**
+**Degradation mode (--degradation):**
+Tests context retention across 10-turn conversations with filler, distractor, and recovery turns.
+Probes at turns 0, 6, 8, 10 to measure quality degradation. Results show a line graph of each test's progression.
+
+**Result format:**
```json
-{"id":"<iter>-<promptId>","timestamp":"...","model":"claude-code-interactive","persona":"naive","promptCategory":"...","prompt":"...","response":"<code>","evaluation":{"success":true,"componentsUsed":[...],"escapeHatches":[...]}}
+{
+ "id": "<iter>-<promptId>",
+ "timestamp": "...",
+ "model": "claude-code-interactive",
+ "persona": "naive",
+ "promptCategory": "...",
+ "trajectoryDepth": 0,
+ "prompt": "...",
+ "response": "<code>",
+ "evaluation": {"success": true, "componentsUsed": [...], "escapeHatches": [...]}
+}
```
## AI Context
diff --git a/internal/vibe-tests/docs/job-taxonomy.md b/internal/vibe-tests/docs/job-taxonomy.md
new file mode 100644
index 0000000000..2fa70965e0
--- /dev/null
+++ b/internal/vibe-tests/docs/job-taxonomy.md
@@ -0,0 +1,259 @@
+# Vibe Test Job Taxonomy
+
+When an LLM generates UI from a prompt, its output breaks down into distinct jobs. This taxonomy helps analyze token costs and identify optimization opportunities.
+
+## Summary
+
+### Input Token Sources
+
+| Source | Description |
+| ------------------- | ------------------------------------------- |
+| **AGENTS.md** | Component catalog and XDS guidance |
+| **Design docs** | principles.md, tokens.md - styling patterns |
+| **Component docs** | Button.md, TextInput.md, etc. |
+| **Prompt overhead** | Task instructions and persona |
+
+### Output Token Jobs
+
+| Job | Description | Typical % |
+| ------------------------ | ------------------------------------------- | --------- |
+| **Component Routing** | Import statements for XDS components | 3-10% |
+| **Component Config** | Props and attributes on XDS components | 7-30% |
+| **Supplemental Styling** | StyleX blocks for layout/spacing gaps | 10-27% |
+| **Content Authoring** | HTML structure, JSX elements, copy | 15-27% |
+| **Business Logic** | useState, handlers, API calls, conditionals | 5-51% |
+| **Boilerplate** | Type definitions, imports, exports | 5-10% |
+
+## Jobs (Detailed)
+
+### 1. Component Routing (~3-10% of output tokens)
+
+**Import statements for XDS components**
+
+```tsx
+import {XDSTextInput} from '@xds/core/TextInput';
+import {XDSButton} from '@xds/core/Button';
+```
+
+- Requires: Understanding component catalog, matching intent to components
+- Input cost: Reading component docs, AGENTS.md index
+- Failure modes: Wrong component choice, missing components, hallucinated components
+
+### 2. Component Configuration (~7-30% of output tokens)
+
+**Props and attributes on XDS components**
+
+```tsx
+<XDSTextInput
+ label="Name"
+ value={name}
+ onChange={setName}
+ isRequired
+ placeholder="Enter your name"
+/>
+<XDSButton variant="primary" disabled={!isFormValid}>
+```
+
+- Requires: Understanding component APIs, valid prop values
+- Input cost: Reading specific component docs (Button.md, TextInput.md, etc.)
+- Failure modes: Hallucinated props, wrong prop types, missing required props
+
+### 3. Supplemental Styling (~10-27% of output tokens)
+
+**StyleX blocks for layout/spacing gaps**
+
+```tsx
+const styles = stylex.create({
+ form: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 'var(--spacing-4)',
+ padding: 'var(--spacing-6)',
+ backgroundColor: 'var(--color-surface)',
+ },
+});
+```
+
+- Requires: Understanding design tokens, StyleX patterns
+- Input cost: Reading tokens.md, principles.md
+- Failure modes: Hardcoded values (anti-pattern), hallucinated CSS variables, redundant CSS
+
+### 4. Content Authoring (~15-27% of output tokens)
+
+**HTML structure, JSX elements, copy**
+
+```tsx
+return (
+ <form onSubmit={handleSubmit} {...stylex.props(styles.form)}>
+ {/* structure */}
+ <div>Main content goes here</div>
+ </form>
+);
+```
+
+- Requires: Understanding JSX, semantic HTML
+- Input cost: Minimal (general knowledge)
+- Failure modes: Accessibility issues, poor structure
+
+### 5. Business Logic (~5-51% of output tokens)
+
+**useState, handlers, API calls, conditionals**
+
+```tsx
+const [name, setName] = useState('');
+const isFormValid = name.trim() !== '' && email.trim() !== '';
+
+const handleSubmit = (e: React.FormEvent) => {
+ e.preventDefault();
+ if (isFormValid) {
+ console.log('Form submitted:', {name, email});
+ }
+};
+```
+
+- Requires: Understanding React patterns, state management
+- Input cost: Minimal (general knowledge)
+- Failure modes: Logic bugs, missing edge cases
+
+### 6. Boilerplate (~5-10% of output tokens)
+
+**Type definitions, imports, exports**
+
+```tsx
+import { useState } from 'react';
+import * as stylex from '@stylexjs/stylex';
+
+export function RequiredFieldsForm() {
+```
+
+- Requires: Understanding module system, TypeScript
+- Input cost: Minimal (general knowledge)
+- Failure modes: Missing imports, incorrect paths
+
+## Token Distribution by Prompt Category
+
+| Category | Routing | Config | Styling | Content | Logic | Boilerplate |
+| ------------------------ | ------- | ------ | ------- | ------- | ----- | ----------- |
+| **state-driven** | 8% | 29% | 20% | 15% | 19% | 9% |
+| **integration-oriented** | 2% | 7% | 10% | 24% | 51% | 5% |
+| **page-setup** | 6% | 26% | 27% | 27% | 5% | 10% |
+
+### Key Insights
+
+1. **Integration-oriented prompts are logic-heavy** (51% business logic)
+ - File uploads, API calls, complex state
+ - Component configuration is minimal (7%)
+
+2. **Page-setup prompts are balanced**
+ - Equal parts styling, content, and config
+ - Minimal business logic (5%)
+
+3. **State-driven prompts emphasize configuration**
+ - Form validation requires component props (29%)
+ - Moderate business logic for state (19%)
+
+## Input Token Costs by Job
+
+| Job | Docs Required | Est. Input Tokens |
+| -------------------- | ------------------------ | ----------------- |
+| Component Routing | AGENTS.md index | ~175 |
+| Component Config | Component docs (1-3) | 300-2000 each |
+| Supplemental Styling | tokens.md, principles.md | ~1200 |
+| Content Authoring | None (general knowledge) | 0 |
+| Business Logic | None (general knowledge) | 0 |
+| Boilerplate | None (general knowledge) | 0 |
+
+## Full Token Usage Breakdown
+
+The aggregate command shows a complete breakdown of token usage:
+
+```
+📊 Token Usage Breakdown:
+ ┌─────────────────────────────────────────────────┐
+ │ INPUT TOKENS (estimated from doc reading) │
+ ├─────────────────────────────────────────────────┤
+ │ AGENTS.md: 173 tokens │
+ │ Design docs: 1200 tokens │ (principles.md, tokens.md)
+ │ Component docs: 800 tokens │ (Button.md, TextInput.md, etc.)
+ │ Prompt overhead: 375 tokens │ (task instructions)
+ │ ───────────────────────────── │
+ │ Input subtotal: 2548 tokens │
+ ├─────────────────────────────────────────────────┤
+ │ OUTPUT TOKENS (from job breakdown) │
+ ├─────────────────────────────────────────────────┤
+ │ Component routing: 4% (~48 tokens) │
+ │ Component config: 16% (~195 tokens) │
+ │ Supplemental styling: 16% (~188 tokens) │
+ │ Content authoring: 22% (~263 tokens) │
+ │ Business logic: 34% (~408 tokens) │
+ │ Boilerplate: 7% (~86 tokens) │
+ │ ───────────────────────────── │
+ │ Output subtotal: 1188 tokens │
+ ├─────────────────────────────────────────────────┤
+ │ TOTAL: 3736 tokens │
+ └─────────────────────────────────────────────────┘
+```
+
+### Input Token Categories
+
+- **AGENTS.md**: Always read (~173 tokens) - component catalog and XDS guidance
+- **Design docs**: tokens.md (~897) and principles.md (~283) - styling patterns
+- **Component docs**: Varies by components used (300-2000 tokens each)
+- **Prompt overhead**: Task instructions and persona (~375 tokens)
+
+### Output Token Categories
+
+Analyzed from generated code by parsing:
+
+- Import statements → Component Routing
+- XDS component JSX with props → Component Config
+- `stylex.create()` blocks → Supplemental Styling
+- HTML elements and structure → Content Authoring
+- State hooks, handlers, logic → Business Logic
+- Type definitions, exports → Boilerplate
+
+## Timing
+
+Timing is tracked per test and per category:
+
+```
+⏱️ Performance:
+ Total time: 200.9s (avg 67.0s per test)
+
+By Category:
+ integration-oriented 100% (1/1) ⏱️70.1s
+ page-setup 100% (1/1) ⏱️65.8s
+ state-driven 100% (1/1) ⏱️65.0s
+```
+
+Timing is inferred from file timestamps (task creation → result write).
+
+## Optimization Opportunities
+
+### Reduce Component Config Tokens
+
+- Better defaults in components = fewer props needed
+- Compound components = less configuration
+
+### Reduce Supplemental Styling Tokens
+
+- More layout primitives = less custom CSS
+- Better gap/spacing props = less StyleX
+
+### Reduce Business Logic Tokens
+
+- Provide hooks (useForm, useUpload) = less custom logic
+- Built-in patterns = less boilerplate logic
+
+## Measuring Job Quality
+
+Each job can be evaluated independently:
+
+| Job | Success Criteria | Escape Hatch Types |
+| -------------------- | ------------------------------ | -------------------------------------- |
+| Component Routing | Correct components chosen | `wrong_component`, `hallucination` |
+| Component Config | Valid props, no hallucinations | `hallucination` |
+| Supplemental Styling | Uses tokens, not hardcoded | `hardcoded_color`, `hardcoded_spacing` |
+| Content Authoring | Semantic HTML, accessible | (not tracked) |
+| Business Logic | Works correctly | (not tracked) |
+| Boilerplate | Correct imports | (not tracked) |
diff --git a/internal/vibe-tests/prompts/evaluator.md b/internal/vibe-tests/prompts/evaluator.md
index 2bc02ea9bf..6faff7d485 100644
--- a/internal/vibe-tests/prompts/evaluator.md
+++ b/internal/vibe-tests/prompts/evaluator.md
@@ -68,6 +68,45 @@ A response can be successful AND have acceptable escape hatches.
3. `redundant_css` is critical only when a component prop exists for the same thing
4. Check the skill doc carefully before marking something as hallucinated
+### CSS Variable Validation
+
+XDS uses specific CSS variable naming. **Any variable not matching these patterns is a hallucination.**
+
+**Valid CSS variable prefixes:**
+
+| Category | Prefix | Examples |
+| ------------- | ---------------------------------------------- | ------------------------------------------------------------ |
+| Colors | `--color-*` | `--color-surface`, `--color-text-primary`, `--color-accent` |
+| Spacing | `--spacing-*` | `--spacing-0` through `--spacing-7` |
+| Radius | `--radius-*` | `--radius-container`, `--radius-element`, `--radius-content` |
+| Elevation | `--elevation-*` | `--elevation-base`, `--elevation-dialog`, `--elevation-menu` |
+| Transitions | `--transition-*` | `--transition-fast`, `--transition-normal` |
+| Font families | `--font-body`, `--font-code`, `--font-heading` | (only these three) |
+| Text sizes | `--text-*` | `--text-base`, `--text-sm`, `--text-lg`, `--text-xl` |
+| Line heights | `--leading-*` | `--leading-tight`, `--leading-normal`, `--leading-relaxed` |
+| Font weights | `--font-weight-*` | `--font-weight-normal`, `--font-weight-bold` |
+
+**Common hallucinations to flag:**
+
+- `--xds-*` prefix (INVALID - XDS doesn't use this prefix)
+- `--xds-color-*`, `--xds-space-*`, `--xds-font-*` (INVALID)
+- `--space-*` instead of `--spacing-*`
+- `--border-*` (doesn't exist - use `--color-divider` or component props)
+- `--font-family-*` (doesn't exist - use `--font-body`, `--font-code`, `--font-heading`)
+- `--font-size-*` (doesn't exist - use `--text-*`)
+- `--shadow-*` (doesn't exist - use `--elevation-*`)
+
+When you detect a hallucinated CSS variable, create an escape hatch entry:
+
+```json
+{
+ "type": "hallucination",
+ "severity": "critical",
+ "detail": "Used non-existent CSS variable --xds-font-family-base. Valid alternatives: --font-body, --font-code, --font-heading",
+ "codeSnippet": "fontFamily: 'var(--xds-font-family-base)'"
+}
+```
+
### Confusion Signals
Look for these in the response:
diff --git a/internal/vibe-tests/src/aggregate.ts b/internal/vibe-tests/src/aggregate.ts
index ba7e4977ae..8ad5330431 100644
--- a/internal/vibe-tests/src/aggregate.ts
+++ b/internal/vibe-tests/src/aggregate.ts
@@ -15,8 +15,222 @@ import type {
EscapeHatch,
GapSuggestion,
EscapeHatchType,
+ JobBreakdown,
+ InputTokenBreakdown,
+ TokenUsageBreakdown,
} from './types.js';
-import {readJsonl, readJson, writeJson, getResultsDir} from './utils.js';
+import {readJson, writeJson, getResultsDir} from './utils.js';
+
+/**
+ * Doc file sizes in characters (for input token estimation)
+ * ~4 chars per token is a reasonable estimate
+ */
+const DOC_SIZES: Record<string, number> = {
+ 'AGENTS.md': 691,
+ 'principles.md': 1131,
+ 'tokens.md': 3586,
+ 'Button.md': 1347,
+ 'Theme.md': 1355,
+ 'CheckboxInput.md': 1920,
+ 'Text.md': 2172,
+ 'Avatar.md': 2280,
+ 'Calendar.md': 2989,
+ 'Field.md': 3010,
+ 'TextInput.md': 3026,
+ 'Skeleton.md': 3096,
+ 'Icon.md': 3560,
+ 'TextArea.md': 3637,
+ 'Layer.md': 4867,
+ 'Container.md': 6263,
+ 'Layout.md': 6632,
+ 'Stack.md': 7007,
+ 'XDSLayout.md': 8284,
+};
+
+/** Base prompt overhead (task instructions, persona, etc.) in characters */
+const PROMPT_OVERHEAD_CHARS = 1500;
+
+/**
+ * Estimate input tokens based on docs read
+ */
+function estimateInputTokens(
+ docsRead: string[] | undefined,
+): InputTokenBreakdown {
+ const breakdown: InputTokenBreakdown = {
+ agentsMd: 0,
+ designDocs: 0,
+ componentDocs: 0,
+ promptOverhead: Math.round(PROMPT_OVERHEAD_CHARS / 4),
+ total: 0,
+ };
+
+ if (!docsRead || docsRead.length === 0) {
+ // Default: assume AGENTS.md was read
+ breakdown.agentsMd = Math.round((DOC_SIZES['AGENTS.md'] || 700) / 4);
+ } else {
+ for (const doc of docsRead) {
+ const size = DOC_SIZES[doc] || 2000; // Default 2000 chars for unknown docs
+ const tokens = Math.round(size / 4);
+
+ if (doc === 'AGENTS.md') {
+ breakdown.agentsMd += tokens;
+ } else if (doc === 'principles.md' || doc === 'tokens.md') {
+ breakdown.designDocs += tokens;
+ } else {
+ breakdown.componentDocs += tokens;
+ }
+ }
+ }
+
+ breakdown.total =
+ breakdown.agentsMd +
+ breakdown.designDocs +
+ breakdown.componentDocs +
+ breakdown.promptOverhead;
+ return breakdown;
+}
+
+/**
+ * Analyze code to break down tokens by job type
+ */
+function analyzeJobBreakdown(code: string): JobBreakdown {
+ const jobs = {
+ componentRouting: 0,
+ componentConfig: 0,
+ supplementalStyling: 0,
+ contentAuthoring: 0,
+ businessLogic: 0,
+ boilerplate: 0,
+ };
+
+ const lines = code.split('\n');
+ let inStyles = false;
+
+ for (const line of lines) {
+ const stripped = line.trim();
+ const chars = line.length + 1; // +1 for newline
+
+ // Imports
+ if (stripped.startsWith('import')) {
+ if (line.includes('XDS') || line.includes('@xds')) {
+ jobs.componentRouting += chars;
+ } else {
+ jobs.boilerplate += chars;
+ }
+ continue;
+ }
+
+ // StyleX styles block
+ if (line.includes('stylex.create')) {
+ inStyles = true;
+ }
+ if (inStyles) {
+ jobs.supplementalStyling += chars;
+ if (stripped === '});') {
+ inStyles = false;
+ }
+ continue;
+ }
+
+ // Type definitions
+ if (stripped.startsWith('type ') || stripped.startsWith('interface ')) {
+ jobs.boilerplate += chars;
+ continue;
+ }
+
+ // Function signature
+ if (
+ stripped.includes('function') &&
+ (stripped.includes('export') || stripped.startsWith('function'))
+ ) {
+ jobs.boilerplate += chars;
+ continue;
+ }
+
+ // JSX with XDS components and props
+ const propPatterns = [
+ 'label=',
+ 'value=',
+ 'onChange=',
+ 'variant=',
+ 'disabled=',
+ 'loading=',
+ 'onClick=',
+ 'placeholder=',
+ 'isRequired',
+ 'header=',
+ 'content=',
+ 'theme=',
+ ];
+ if (
+ line.includes('<XDS') ||
+ line.includes('</XDS') ||
+ (stripped && propPatterns.some(p => line.includes(p)))
+ ) {
+ jobs.componentConfig += chars;
+ continue;
+ }
+
+ // JSX structure (html elements)
+ if (/<\/?[a-z]/.test(line) && !line.includes('XDS')) {
+ jobs.contentAuthoring += chars;
+ continue;
+ }
+
+ // State, handlers, logic
+ const logicPatterns = [
+ 'useState',
+ 'useRef',
+ 'useEffect',
+ 'useCallback',
+ 'const ',
+ 'let ',
+ 'if ',
+ 'if(',
+ 'try ',
+ 'catch ',
+ 'await ',
+ 'async ',
+ '.then',
+ '.catch',
+ 'xhr.',
+ 'formData',
+ 'setIs',
+ 'setProgress',
+ 'handle',
+ ];
+ if (logicPatterns.some(p => line.includes(p))) {
+ if (line.includes('return (') || line.includes('return <')) {
+ jobs.contentAuthoring += chars;
+ } else {
+ jobs.businessLogic += chars;
+ }
+ continue;
+ }
+
+ // Closing braces and returns
+ if (
+ ['}', '});', ');', '};', 'return (', '} catch', '} finally'].includes(
+ stripped,
+ )
+ ) {
+ jobs.businessLogic += chars;
+ continue;
+ }
+
+ // Default: content authoring
+ if (stripped) {
+ jobs.contentAuthoring += chars;
+ }
+ }
+
+ const total = Object.values(jobs).reduce((a, b) => a + b, 0);
+
+ return {
+ ...jobs,
+ total,
+ };
+}
/** Escape hatch types that indicate anti-patterns (break theming/system) */
const ANTI_PATTERN_HATCHES: EscapeHatchType[] = [
@@ -39,6 +253,14 @@ interface TierCounts {
red: number;
}
+/** Individual test progression through degradation turns */
+interface TestProgression {
+ promptId: string;
+ category: string;
+ prompt: string;
+ turns: {depth: number; tier: ResultTier; success: boolean}[];
+}
+
interface AggregateResult {
iterationId: string;
totalTests: number;
@@ -49,9 +271,23 @@ interface AggregateResult {
tierRate: Record<ResultTier, number>;
byCategory: Record<
string,
- {success: number; total: number; rate: number; tiers: TierCounts}
+ {
+ success: number;
+ total: number;
+ rate: number;
+ tiers: TierCounts;
+ avgDurationMs: number;
+ }
>;
byPersona: Record<string, {success: number; total: number; rate: number}>;
+ // Degradation curve (only present if trajectory depths vary)
+ byTrajectoryDepth?: Record<
+ number,
+ {success: number; total: number; rate: number; tiers: TierCounts}
+ >;
+ degradationCliff?: number; // First depth where success rate drops below 80%
+ // Individual test progressions for line graph visualization
+ testProgressions?: TestProgression[];
criticalIssues: Record<string, number>;
acceptableEscapeHatches: Record<string, number>;
antiPatterns: Record<string, number>;
@@ -62,6 +298,31 @@ interface AggregateResult {
avgDurationMs: number;
totalInputTokens: number;
totalOutputTokens: number;
+ // Job breakdown stats (tokens by job type)
+ jobStats?: {
+ total: JobBreakdown;
+ byCategory: Record<string, JobBreakdown>;
+ percentages: {
+ componentRouting: number;
+ componentConfig: number;
+ supplementalStyling: number;
+ contentAuthoring: number;
+ businessLogic: number;
+ boilerplate: number;
+ };
+ };
+ // Full token usage breakdown (input + output)
+ tokenUsage?: {
+ input: {
+ total: InputTokenBreakdown;
+ byCategory: Record<string, InputTokenBreakdown>;
+ };
+ output: {
+ total: JobBreakdown;
+ byCategory: Record<string, JobBreakdown>;
+ };
+ grandTotal: number;
+ };
}
/** Normalize escape hatch to object format (handles string or object) */
@@ -71,6 +332,7 @@ function normalizeEscapeHatch(h: string | EscapeHatch): EscapeHatch {
return {
type: 'supplemental_css', // Default type for string descriptions
severity: 'acceptable',
+ detail: h,
codeSnippet: h,
};
}
@@ -188,15 +450,60 @@ function analyzeGaps(results: TestResult[]): GapSuggestion[] {
return suggestions.sort((a, b) => b.frequency - a.frequency);
}
-function aggregate(iterationId: string): AggregateResult {
- const resultsDir = path.join(getResultsDir(), iterationId);
- const runsPath = path.join(resultsDir, 'runs.jsonl');
+/**
+ * Load results from individual result files
+ * Optionally infers timing from file timestamps if durationMs is 0
+ */
+function loadResults(resultsDir: string): TestResult[] {
+ const individualResultsDir = path.join(resultsDir, 'results');
+ const tasksDir = path.join(resultsDir, 'tasks');
+ const results: TestResult[] = [];
- if (!fs.existsSync(runsPath)) {
- throw new Error(`No results found at ${runsPath}`);
+ if (!fs.existsSync(individualResultsDir)) {
+ throw new Error(`No results directory found at ${individualResultsDir}`);
}
- const results = readJsonl<TestResult>(runsPath);
+ const files = fs
+ .readdirSync(individualResultsDir)
+ .filter(f => f.endsWith('.json'));
+
+ if (files.length === 0) {
+ throw new Error(`No result files found in ${individualResultsDir}`);
+ }
+
+ 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);
+ // Duration = result file mtime - task file mtime
+ 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;
+}
+
+function aggregate(iterationId: string): AggregateResult {
+ const resultsDir = path.join(getResultsDir(), iterationId);
+
+ const results = loadResults(resultsDir);
if (results.length === 0) {
throw new Error('No results to aggregate');
@@ -204,9 +511,22 @@ function aggregate(iterationId: string): AggregateResult {
const byCategory: Record<
string,
- {success: number; total: number; tiers: TierCounts}
+ {success: number; total: number; tiers: TierCounts; durationMs: number}
> = {};
const byPersona: Record<string, {success: number; total: number}> = {};
+ const byTrajectoryDepth: Record<
+ number,
+ {success: number; total: number; tiers: TierCounts}
+ > = {};
+ // Track individual test progressions for degradation line graph
+ const progressionMap = new Map<
+ string,
+ {
+ category: string;
+ prompt: string;
+ turns: {depth: number; tier: ResultTier; success: boolean}[];
+ }
+ >();
const criticalIssues: Record<string, number> = {};
const acceptableEscapeHatches: Record<string, number> = {};
const antiPatterns: Record<string, number> = {};
@@ -238,10 +558,12 @@ function aggregate(iterationId: string): AggregateResult {
success: 0,
total: 0,
tiers: {gold: 0, green: 0, yellow: 0, red: 0},
+ durationMs: 0,
};
}
byCategory[result.promptCategory].total++;
byCategory[result.promptCategory].tiers[tier]++;
+ byCategory[result.promptCategory].durationMs += result.durationMs || 0;
if (tier !== 'red') {
byCategory[result.promptCategory].success++;
}
@@ -255,6 +577,43 @@ function aggregate(iterationId: string): AggregateResult {
byPersona[result.persona].success++;
}
+ // By trajectory depth (for degradation curve analysis)
+ const depth = result.trajectoryDepth ?? 0;
+ if (!byTrajectoryDepth[depth]) {
+ byTrajectoryDepth[depth] = {
+ success: 0,
+ total: 0,
+ tiers: {gold: 0, green: 0, yellow: 0, red: 0},
+ };
+ }
+ byTrajectoryDepth[depth].total++;
+ byTrajectoryDepth[depth].tiers[tier]++;
+ if (tier !== 'red') {
+ byTrajectoryDepth[depth].success++;
+ }
+
+ // Track individual test progressions (for degradation line graph)
+ // Extract base prompt ID - remove iteration prefix and depth suffix if present
+ // Format: iterationId-promptId or iterationId-promptId-depthN
+ const idParts = result.id.split('-');
+ // Remove first part (iteration) and reconstruct, checking for depth suffix
+ const basePromptId = idParts
+ .slice(1)
+ .filter(p => !p.match(/^depth\d+$/))
+ .join('-');
+ if (!progressionMap.has(basePromptId)) {
+ progressionMap.set(basePromptId, {
+ category: result.promptCategory,
+ prompt: result.prompt,
+ turns: [],
+ });
+ }
+ progressionMap.get(basePromptId)!.turns.push({
+ depth,
+ tier,
+ success: tier !== 'red',
+ });
+
// Escape hatches
for (const rawHatch of result.evaluation.escapeHatches) {
const hatch = normalizeEscapeHatch(rawHatch);
@@ -272,12 +631,19 @@ function aggregate(iterationId: string): AggregateResult {
// Calculate rates
const byCategoryWithRates: Record<
string,
- {success: number; total: number; rate: number; tiers: TierCounts}
+ {
+ success: number;
+ total: number;
+ rate: number;
+ tiers: TierCounts;
+ avgDurationMs: number;
+ }
> = {};
for (const [cat, stats] of Object.entries(byCategory)) {
byCategoryWithRates[cat] = {
...stats,
rate: Math.round((stats.success / stats.total) * 100),
+ avgDurationMs: Math.round(stats.durationMs / stats.total),
};
}
@@ -300,9 +666,186 @@ function aggregate(iterationId: string): AggregateResult {
red: Math.round((tiers.red / results.length) * 100),
};
+ // Calculate trajectory depth rates and degradation cliff
+ const depths = Object.keys(byTrajectoryDepth)
+ .map(Number)
+ .sort((a, b) => a - b);
+ const hasDegradationData =
+ depths.length > 1 || (depths.length === 1 && depths[0] !== 0);
+
+ let byTrajectoryDepthWithRates:
+ | Record<
+ number,
+ {success: number; total: number; rate: number; tiers: TierCounts}
+ >
+ | undefined;
+ let degradationCliff: number | undefined;
+
+ if (hasDegradationData) {
+ byTrajectoryDepthWithRates = {};
+ for (const [depthStr, stats] of Object.entries(byTrajectoryDepth)) {
+ const depth = Number(depthStr);
+ const rate = Math.round((stats.success / stats.total) * 100);
+ byTrajectoryDepthWithRates[depth] = {
+ ...stats,
+ rate,
+ };
+ // Find degradation cliff (first depth where rate drops below 80%)
+ if (degradationCliff === undefined && rate < 80 && depth > 0) {
+ degradationCliff = depth;
+ }
+ }
+ }
+
+ // Build test progressions array (only include tests with multiple turns)
+ const testProgressions: TestProgression[] = [];
+ for (const [promptId, data] of progressionMap) {
+ if (data.turns.length > 1) {
+ // Sort turns by depth
+ data.turns.sort((a, b) => a.depth - b.depth);
+ testProgressions.push({
+ promptId,
+ category: data.category,
+ prompt: data.prompt,
+ turns: data.turns,
+ });
+ }
+ }
+
// Analyze gaps and generate suggestions
const gaps = analyzeGaps(results);
+ // Analyze job breakdown for each result
+ const jobsByCategory: Record<string, JobBreakdown> = {};
+ const totalJobs: JobBreakdown = {
+ componentRouting: 0,
+ componentConfig: 0,
+ supplementalStyling: 0,
+ contentAuthoring: 0,
+ businessLogic: 0,
+ boilerplate: 0,
+ total: 0,
+ };
+
+ // Input token tracking
+ const inputByCategory: Record<string, InputTokenBreakdown> = {};
+ const totalInput: InputTokenBreakdown = {
+ agentsMd: 0,
+ designDocs: 0,
+ componentDocs: 0,
+ promptOverhead: 0,
+ total: 0,
+ };
+
+ for (const result of results) {
+ const breakdown = analyzeJobBreakdown(result.response);
+
+ // Accumulate output totals
+ totalJobs.componentRouting += breakdown.componentRouting;
+ totalJobs.componentConfig += breakdown.componentConfig;
+ totalJobs.supplementalStyling += breakdown.supplementalStyling;
+ totalJobs.contentAuthoring += breakdown.contentAuthoring;
+ totalJobs.businessLogic += breakdown.businessLogic;
+ totalJobs.boilerplate += breakdown.boilerplate;
+ totalJobs.total += breakdown.total;
+
+ // Accumulate output by category
+ if (!jobsByCategory[result.promptCategory]) {
+ jobsByCategory[result.promptCategory] = {
+ componentRouting: 0,
+ componentConfig: 0,
+ supplementalStyling: 0,
+ contentAuthoring: 0,
+ businessLogic: 0,
+ boilerplate: 0,
+ total: 0,
+ };
+ }
+ const catJobs = jobsByCategory[result.promptCategory];
+ catJobs.componentRouting += breakdown.componentRouting;
+ catJobs.componentConfig += breakdown.componentConfig;
+ catJobs.supplementalStyling += breakdown.supplementalStyling;
+ catJobs.contentAuthoring += breakdown.contentAuthoring;
+ catJobs.businessLogic += breakdown.businessLogic;
+ catJobs.boilerplate += breakdown.boilerplate;
+ catJobs.total += breakdown.total;
+
+ // Estimate input tokens based on docs read
+ const inputBreakdown = estimateInputTokens(result.docsRead);
+ totalInput.agentsMd += inputBreakdown.agentsMd;
+ totalInput.designDocs += inputBreakdown.designDocs;
+ totalInput.componentDocs += inputBreakdown.componentDocs;
+ totalInput.promptOverhead += inputBreakdown.promptOverhead;
+ totalInput.total += inputBreakdown.total;
+
+ // Accumulate input by category
+ if (!inputByCategory[result.promptCategory]) {
+ inputByCategory[result.promptCategory] = {
+ agentsMd: 0,
+ designDocs: 0,
+ componentDocs: 0,
+ promptOverhead: 0,
+ total: 0,
+ };
+ }
+ const catInput = inputByCategory[result.promptCategory];
+ catInput.agentsMd += inputBreakdown.agentsMd;
+ catInput.designDocs += inputBreakdown.designDocs;
+ catInput.componentDocs += inputBreakdown.componentDocs;
+ catInput.promptOverhead += inputBreakdown.promptOverhead;
+ catInput.total += inputBreakdown.total;
+ }
+
+ // Calculate percentages
+ const jobPercentages =
+ totalJobs.total > 0
+ ? {
+ componentRouting: Math.round(
+ (totalJobs.componentRouting / totalJobs.total) * 100,
+ ),
+ componentConfig: Math.round(
+ (totalJobs.componentConfig / totalJobs.total) * 100,
+ ),
+ supplementalStyling: Math.round(
+ (totalJobs.supplementalStyling / totalJobs.total) * 100,
+ ),
+ contentAuthoring: Math.round(
+ (totalJobs.contentAuthoring / totalJobs.total) * 100,
+ ),
+ businessLogic: Math.round(
+ (totalJobs.businessLogic / totalJobs.total) * 100,
+ ),
+ boilerplate: Math.round(
+ (totalJobs.boilerplate / totalJobs.total) * 100,
+ ),
+ }
+ : undefined;
+
+ const jobStats = jobPercentages
+ ? {
+ total: totalJobs,
+ byCategory: jobsByCategory,
+ percentages: jobPercentages,
+ }
+ : undefined;
+
+ // Calculate output tokens from job breakdown (chars / 4)
+ const outputTokens = Math.round(totalJobs.total / 4);
+ const grandTotal = totalInput.total + outputTokens;
+
+ // Full token usage breakdown
+ const tokenUsage = {
+ input: {
+ total: totalInput,
+ byCategory: inputByCategory,
+ },
+ output: {
+ total: totalJobs,
+ byCategory: jobsByCategory,
+ },
+ grandTotal,
+ };
+
return {
iterationId,
totalTests: results.length,
@@ -312,6 +855,10 @@ function aggregate(iterationId: string): AggregateResult {
tierRate,
byCategory: byCategoryWithRates,
byPersona: byPersonaWithRates,
+ byTrajectoryDepth: byTrajectoryDepthWithRates,
+ degradationCliff,
+ testProgressions:
+ testProgressions.length > 0 ? testProgressions : undefined,
criticalIssues,
acceptableEscapeHatches,
antiPatterns,
@@ -320,6 +867,8 @@ function aggregate(iterationId: string): AggregateResult {
avgDurationMs: Math.round(totalDurationMs / results.length),
totalInputTokens,
totalOutputTokens,
+ jobStats,
+ tokenUsage,
};
}
@@ -364,11 +913,124 @@ function printReport(agg: AggregateResult): void {
console.log(`\nBy Category:`);
for (const [cat, stats] of Object.entries(agg.byCategory)) {
const tierBar = `🥇${stats.tiers.gold} 🟢${stats.tiers.green} 🟡${stats.tiers.yellow} 🔴${stats.tiers.red}`;
+ const avgTime =
+ stats.avgDurationMs > 0
+ ? ` ⏱️${(stats.avgDurationMs / 1000).toFixed(1)}s`
+ : '';
console.log(
- ` ${cat.padEnd(25)} ${stats.rate}% (${stats.success}/${stats.total}) [${tierBar}]`,
+ ` ${cat.padEnd(25)} ${stats.rate}% (${stats.success}/${stats.total}) [${tierBar}]${avgTime}`,
);
}
+ // Full token usage breakdown (if present)
+ if (agg.tokenUsage) {
+ const tu = agg.tokenUsage;
+ console.log(`\n📊 Token Usage Breakdown:`);
+ console.log(` ┌─────────────────────────────────────────────────┐`);
+ console.log(` │ INPUT TOKENS (estimated from doc reading) │`);
+ console.log(` ├─────────────────────────────────────────────────┤`);
+ console.log(
+ ` │ AGENTS.md: ${String(tu.input.total.agentsMd).padStart(6)} tokens │`,
+ );
+ console.log(
+ ` │ Design docs: ${String(tu.input.total.designDocs).padStart(6)} tokens │`,
+ );
+ console.log(
+ ` │ Component docs: ${String(tu.input.total.componentDocs).padStart(6)} tokens │`,
+ );
+ console.log(
+ ` │ Prompt overhead: ${String(tu.input.total.promptOverhead).padStart(6)} tokens │`,
+ );
+ console.log(` │ ───────────────────────────── │`);
+ console.log(
+ ` │ Input subtotal: ${String(tu.input.total.total).padStart(6)} tokens │`,
+ );
+ console.log(` ├─────────────────────────────────────────────────┤`);
+ console.log(` │ OUTPUT TOKENS (from job breakdown) │`);
+ console.log(` ├─────────────────────────────────────────────────┤`);
+ if (agg.jobStats) {
+ const p = agg.jobStats.percentages;
+ const outputTokens = Math.round(tu.output.total.total / 4);
+ console.log(
+ ` │ Component routing: ${String(p.componentRouting).padStart(3)}% (~${Math.round(tu.output.total.componentRouting / 4)} tokens) │`,
+ );
+ console.log(
+ ` │ Component config: ${String(p.componentConfig).padStart(3)}% (~${Math.round(tu.output.total.componentConfig / 4)} tokens) │`,
+ );
+ console.log(
+ ` │ Supplemental styling: ${String(p.supplementalStyling).padStart(3)}% (~${Math.round(tu.output.total.supplementalStyling / 4)} tokens) │`,
+ );
+ console.log(
+ ` │ Content authoring: ${String(p.contentAuthoring).padStart(3)}% (~${Math.round(tu.output.total.contentAuthoring / 4)} tokens) │`,
+ );
+ console.log(
+ ` │ Business logic: ${String(p.businessLogic).padStart(3)}% (~${Math.round(tu.output.total.businessLogic / 4)} tokens) │`,
+ );
+ console.log(
+ ` │ Boilerplate: ${String(p.boilerplate).padStart(3)}% (~${Math.round(tu.output.total.boilerplate / 4)} tokens) │`,
+ );
+ console.log(` │ ───────────────────────────── │`);
+ console.log(
+ ` │ Output subtotal: ${String(outputTokens).padStart(6)} tokens │`,
+ );
+ }
+ console.log(` ├─────────────────────────────────────────────────┤`);
+ console.log(
+ ` │ TOTAL: ${String(tu.grandTotal).padStart(6)} tokens │`,
+ );
+ console.log(` └─────────────────────────────────────────────────┘`);
+ } else if (agg.jobStats) {
+ // Fallback: just show job breakdown if no full token usage
+ console.log(`\n🔧 Job Breakdown (output token distribution):`);
+ const p = agg.jobStats.percentages;
+ console.log(
+ ` Component routing: ${String(p.componentRouting).padStart(3)}%`,
+ );
+ console.log(
+ ` Component config: ${String(p.componentConfig).padStart(3)}%`,
+ );
+ console.log(
+ ` Supplemental styling: ${String(p.supplementalStyling).padStart(3)}%`,
+ );
+ console.log(
+ ` Content authoring: ${String(p.contentAuthoring).padStart(3)}%`,
+ );
+ console.log(
+ ` Business logic: ${String(p.businessLogic).padStart(3)}%`,
+ );
+ console.log(
+ ` Boilerplate: ${String(p.boilerplate).padStart(3)}%`,
+ );
+ console.log(
+ ` Total chars: ${agg.jobStats.total.total} (~${Math.round(agg.jobStats.total.total / 4)} tokens)`,
+ );
+ }
+
+ // Degradation curve (if present)
+ if (agg.byTrajectoryDepth && Object.keys(agg.byTrajectoryDepth).length > 0) {
+ console.log(`\n📉 Degradation Curve (success rate by conversation depth):`);
+ const depths = Object.keys(agg.byTrajectoryDepth)
+ .map(Number)
+ .sort((a, b) => a - b);
+ for (const depth of depths) {
+ const stats = agg.byTrajectoryDepth[depth];
+ const bar = '█'.repeat(Math.round(stats.rate / 5));
+ const tierBar = `🥇${stats.tiers.gold} 🟢${stats.tiers.green} 🟡${stats.tiers.yellow} 🔴${stats.tiers.red}`;
+ console.log(
+ ` Turn ${String(depth).padStart(2)}: ${bar.padEnd(20)} ${stats.rate}% (${stats.success}/${stats.total}) [${tierBar}]`,
+ );
+ }
+ if (agg.degradationCliff !== undefined) {
+ console.log(
+ ` ⚠️ Degradation cliff at turn ${agg.degradationCliff} (success dropped below 80%)`,
+ );
+ } else {
+ console.log(
+ ` ✓ No degradation cliff detected (maintained ≥80% throughout)`,
+ );
+ }
+ }
+
if (Object.keys(agg.criticalIssues).length > 0) {
console.log(`\n❌ Critical Issues (break functionality):`);
for (const [type, count] of Object.entries(agg.criticalIssues)) {
@@ -452,6 +1114,7 @@ function generateHtmlReport(
<span class="tier-label yellow">${stats.tiers.yellow}</span>
<span class="tier-label red">${stats.tiers.red}</span>
</td>
+ <td>${stats.avgDurationMs > 0 ? (stats.avgDurationMs / 1000).toFixed(1) + 's' : '-'}</td>
</tr>
`,
)
@@ -496,6 +1159,166 @@ function generateHtmlReport(
})
.join('');
+ // Generate degradation line graph data if available
+ let degradationGraphHtml = '';
+ if (agg.testProgressions && agg.testProgressions.length > 0) {
+ // Map tier to numeric value for graphing (higher = better)
+ const tierToValue = (tier: ResultTier): number => {
+ switch (tier) {
+ case 'gold':
+ return 100;
+ case 'green':
+ return 75;
+ case 'yellow':
+ return 50;
+ case 'red':
+ return 0;
+ }
+ };
+
+ const tierToColor = (tier: ResultTier): string => {
+ switch (tier) {
+ case 'gold':
+ return '#f59e0b';
+ case 'green':
+ return '#22c55e';
+ case 'yellow':
+ return '#eab308';
+ case 'red':
+ return '#ef4444';
+ }
+ };
+
+ // Get all unique depths and sort them
+ const allDepths = new Set<number>();
+ for (const prog of agg.testProgressions) {
+ for (const turn of prog.turns) {
+ allDepths.add(turn.depth);
+ }
+ }
+ const depths = Array.from(allDepths).sort((a, b) => a - b);
+
+ // SVG dimensions
+ const svgWidth = 800;
+ const svgHeight = 400;
+ const padding = {top: 40, right: 120, bottom: 60, left: 60};
+ const graphWidth = svgWidth - padding.left - padding.right;
+ const graphHeight = svgHeight - padding.top - padding.bottom;
+
+ // X scale
+ const xStep = graphWidth / (depths.length - 1 || 1);
+ const xPos = (depthIndex: number) => padding.left + depthIndex * xStep;
+
+ // Y scale (0-100)
+ const yPos = (value: number) =>
+ padding.top + graphHeight - (value / 100) * graphHeight;
+
+ // Generate unique colors for each test
+ const colors = [
+ '#6366f1',
+ '#ec4899',
+ '#14b8a6',
+ '#f97316',
+ '#8b5cf6',
+ '#06b6d4',
+ '#84cc16',
+ '#f43f5e',
+ '#0ea5e9',
+ '#a855f7',
+ ];
+
+ // Build SVG paths and legends
+ let paths = '';
+ let legends = '';
+ let legendY = padding.top;
+
+ agg.testProgressions.forEach((prog, idx) => {
+ const color = colors[idx % colors.length];
+ const points: string[] = [];
+
+ for (const turn of prog.turns) {
+ const depthIndex = depths.indexOf(turn.depth);
+ if (depthIndex !== -1) {
+ const x = xPos(depthIndex);
+ const y = yPos(tierToValue(turn.tier));
+ points.push(`${x},${y}`);
+ }
+ }
+
+ if (points.length > 1) {
+ paths += `<polyline points="${points.join(' ')}" fill="none" stroke="${color}" stroke-width="2" stroke-opacity="0.7" />`;
+ // Add dots at each point
+ for (const turn of prog.turns) {
+ const depthIndex = depths.indexOf(turn.depth);
+ if (depthIndex !== -1) {
+ const x = xPos(depthIndex);
+ const y = yPos(tierToValue(turn.tier));
+ paths += `<circle cx="${x}" cy="${y}" r="4" fill="${tierToColor(turn.tier)}" stroke="${color}" stroke-width="1" />`;
+ }
+ }
+ }
+
+ // Legend entry
+ legends += `
+ <g transform="translate(${svgWidth - padding.right + 10}, ${legendY})">
+ <line x1="0" y1="0" x2="20" y2="0" stroke="${color}" stroke-width="2" />
+ <text x="25" y="4" font-size="11" fill="#333">${escapeHtml(prog.promptId.slice(0, 15))}</text>
+ </g>
+ `;
+ legendY += 20;
+ });
+
+ // Build X axis labels
+ let xAxisLabels = '';
+ depths.forEach((depth, idx) => {
+ const x = xPos(idx);
+ xAxisLabels += `
+ <text x="${x}" y="${svgHeight - padding.bottom + 20}" text-anchor="middle" font-size="12" fill="#666">Turn ${depth}</text>
+ `;
+ });
+
+ // Build Y axis labels and gridlines
+ let yAxisContent = '';
+ const yTicks = [0, 25, 50, 75, 100];
+ const yLabels: Record<number, string> = {
+ 0: 'Red',
+ 25: '',
+ 50: 'Yellow',
+ 75: 'Green',
+ 100: 'Gold',
+ };
+ yTicks.forEach(tick => {
+ const y = yPos(tick);
+ yAxisContent += `
+ <line x1="${padding.left}" y1="${y}" x2="${svgWidth - padding.right}" y2="${y}" stroke="#e5e7eb" stroke-dasharray="4" />
+ <text x="${padding.left - 10}" y="${y + 4}" text-anchor="end" font-size="11" fill="#666">${yLabels[tick] || ''}</text>
+ `;
+ });
+
+ degradationGraphHtml = `
+ <div class="card">
+ <h2>📉 Degradation Progression</h2>
+ <p style="color: #666; font-size: 0.9em;">Each line shows a test's quality tier across conversation turns (probe points at turns 0, 6, 8, 10).</p>
+ <svg width="${svgWidth}" height="${svgHeight}" style="max-width: 100%; height: auto;">
+ <!-- Grid and axes -->
+ ${yAxisContent}
+ <line x1="${padding.left}" y1="${svgHeight - padding.bottom}" x2="${svgWidth - padding.right}" y2="${svgHeight - padding.bottom}" stroke="#333" />
+ <line x1="${padding.left}" y1="${padding.top}" x2="${padding.left}" y2="${svgHeight - padding.bottom}" stroke="#333" />
+ ${xAxisLabels}
+ <!-- Data lines -->
+ ${paths}
+ <!-- Legend -->
+ ${legends}
+ </svg>
+ ${
+ agg.degradationCliff !== undefined
+ ? `<p style="color: #dc2626; margin-top: 12px;">⚠️ Degradation cliff detected at turn ${agg.degradationCliff} (aggregate success dropped below 80%)</p>`
+ : `<p style="color: #16a34a; margin-top: 12px;">✓ No degradation cliff detected (maintained ≥80% success throughout)</p>`
+ }
+ </div>
+ `;
+ }
+
const testRows = results
.map(r => {
const tier = calculateTier(r.evaluation);
@@ -524,10 +1347,25 @@ function generateHtmlReport(
const durationStr = r.durationMs
? `${(r.durationMs / 1000).toFixed(1)}s`
: '-';
- const tokensStr =
- r.inputTokens || r.outputTokens
- ? `${(r.inputTokens || 0).toLocaleString()} / ${(r.outputTokens || 0).toLocaleString()}`
- : '-';
+
+ // Calculate per-test token breakdown
+ const jobBreakdown = analyzeJobBreakdown(r.response);
+ const inputBreakdown = estimateInputTokens(r.docsRead);
+ const outputTokens = Math.round(jobBreakdown.total / 4);
+ const totalTokens = inputBreakdown.total + outputTokens;
+
+ // Build token breakdown tooltip content
+ const tokenDetails = `Input: ${inputBreakdown.total} (AGENTS: ${inputBreakdown.agentsMd}, Design: ${inputBreakdown.designDocs}, Components: ${inputBreakdown.componentDocs})&#10;Output: ${outputTokens} (Routing: ${Math.round(jobBreakdown.componentRouting / 4)}, Config: ${Math.round(jobBreakdown.componentConfig / 4)}, Styling: ${Math.round(jobBreakdown.supplementalStyling / 4)}, Content: ${Math.round(jobBreakdown.contentAuthoring / 4)}, Logic: ${Math.round(jobBreakdown.businessLogic / 4)}, Boilerplate: ${Math.round(jobBreakdown.boilerplate / 4)})`;
+
+ // Docs read badges
+ const docsReadBadges = r.docsRead
+ ? r.docsRead
+ .map(
+ d =>
+ `<span class="badge doc-badge">${escapeHtml(d.replace('.md', ''))}</span>`,
+ )
+ .join(' ')
+ : '-';
return `
<tr class="${tierClass}">
@@ -536,7 +1374,8 @@ function generateHtmlReport(
<td class="prompt-cell">${escapeHtml(r.prompt)}</td>
<td>${escapeHatchBadges || '-'}</td>
<td>${durationStr}</td>
- <td>${tokensStr}</td>
+ <td title="${tokenDetails}" style="cursor: help;">${totalTokens} <span style="color: #666; font-size: 0.8em;">(${inputBreakdown.total}/${outputTokens})</span></td>
+ <td class="docs-cell">${docsReadBadges}</td>
<td>
<button class="toggle-code" onclick="toggleCode('${r.id}')">View Code</button>
<pre class="code-block" id="code-${r.id}" style="display:none"><code>${escapeHtml(r.response)}</code></pre>
@@ -552,7 +1391,102 @@ function generateHtmlReport(
const avgSecs = agg.avgDurationMs
? (agg.avgDurationMs / 1000).toFixed(1)
: '-';
- const totalTokens = agg.totalInputTokens + agg.totalOutputTokens;
+ // Use tokenUsage.grandTotal (calculated from docs read + job breakdown) instead of raw totals
+ const totalTokens =
+ agg.tokenUsage?.grandTotal ?? agg.totalInputTokens + agg.totalOutputTokens;
+
+ // Generate token usage breakdown HTML
+ let tokenUsageHtml = '';
+ if (agg.tokenUsage) {
+ const tu = agg.tokenUsage;
+ const outputTokens = Math.round(tu.output.total.total / 4);
+ const jobRows = agg.jobStats
+ ? `
+ <tr>
+ <td><strong>Component Routing</strong><br><span class="job-desc">Import statements for XDS components</span></td>
+ <td>${agg.jobStats.percentages.componentRouting}%</td>
+ <td>~${Math.round(tu.output.total.componentRouting / 4)}</td>
+ </tr>
+ <tr>
+ <td><strong>Component Config</strong><br><span class="job-desc">Props and attributes on XDS components</span></td>
+ <td>${agg.jobStats.percentages.componentConfig}%</td>
+ <td>~${Math.round(tu.output.total.componentConfig / 4)}</td>
+ </tr>
+ <tr>
+ <td><strong>Supplemental Styling</strong><br><span class="job-desc">StyleX blocks for layout/spacing gaps</span></td>
+ <td>${agg.jobStats.percentages.supplementalStyling}%</td>
+ <td>~${Math.round(tu.output.total.supplementalStyling / 4)}</td>
+ </tr>
+ <tr>
+ <td><strong>Content Authoring</strong><br><span class="job-desc">HTML structure, JSX elements, copy</span></td>
+ <td>${agg.jobStats.percentages.contentAuthoring}%</td>
+ <td>~${Math.round(tu.output.total.contentAuthoring / 4)}</td>
+ </tr>
+ <tr>
+ <td><strong>Business Logic</strong><br><span class="job-desc">useState, handlers, API calls, conditionals</span></td>
+ <td>${agg.jobStats.percentages.businessLogic}%</td>
+ <td>~${Math.round(tu.output.total.businessLogic / 4)}</td>
+ </tr>
+ <tr>
+ <td><strong>Boilerplate</strong><br><span class="job-desc">Type definitions, imports, exports</span></td>
+ <td>${agg.jobStats.percentages.boilerplate}%</td>
+ <td>~${Math.round(tu.output.total.boilerplate / 4)}</td>
+ </tr>
+ `
+ : '';
+
+ // Input token descriptions
+ const inputRows = `
+ <tr>
+ <td><strong>AGENTS.md</strong><br><span class="job-desc">Component catalog and XDS guidance</span></td>
+ <td>${tu.input.total.agentsMd}</td>
+ </tr>
+ <tr>
+ <td><strong>Design docs</strong><br><span class="job-desc">principles.md, tokens.md - styling patterns</span></td>
+ <td>${tu.input.total.designDocs}</td>
+ </tr>
+ <tr>
+ <td><strong>Component docs</strong><br><span class="job-desc">Button.md, TextInput.md, etc.</span></td>
+ <td>${tu.input.total.componentDocs}</td>
+ </tr>
+ <tr>
+ <td><strong>Prompt overhead</strong><br><span class="job-desc">Task instructions and persona</span></td>
+ <td>${tu.input.total.promptOverhead}</td>
+ </tr>
+ <tr style="font-weight: bold; border-top: 2px solid #333;"><td>Input Subtotal</td><td>${tu.input.total.total}</td></tr>
+ `;
+
+ tokenUsageHtml = `
+ <div class="card">
+ <h2>📊 Token Usage Breakdown</h2>
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
+ <div>
+ <h3 style="margin-top: 0;">Input Tokens (estimated)</h3>
+ <table>
+ <thead><tr><th>Source</th><th>Tokens</th></tr></thead>
+ <tbody>
+ ${inputRows}
+ </tbody>
+ </table>
+ </div>
+ <div>
+ <h3 style="margin-top: 0;">Output Tokens (by job)</h3>
+ <table>
+ <thead><tr><th>Job</th><th>%</th><th>Tokens</th></tr></thead>
+ <tbody>
+ ${jobRows}
+ <tr style="font-weight: bold; border-top: 2px solid #333;"><td>Output Subtotal</td><td>100%</td><td>${outputTokens}</td></tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+ <div style="text-align: center; margin-top: 16px; padding: 12px; background: #f0f9ff; border-radius: 8px;">
+ <span style="font-size: 1.2em; font-weight: bold;">Total: ${tu.grandTotal.toLocaleString()} tokens</span>
+ <span style="color: #666; margin-left: 12px;">(${tu.input.total.total} input + ${outputTokens} output)</span>
+ </div>
+ </div>
+ `;
+ }
return `<!DOCTYPE html>
<html lang="en">
@@ -630,10 +1564,13 @@ function generateHtmlReport(
.badge.critical { background: #fee2e2; color: #dc2626; }
.badge.anti-pattern { background: #fef9c3; color: #ca8a04; }
.badge.acceptable { background: #e0f2fe; color: #0369a1; }
+ .badge.doc-badge { background: #f3f4f6; color: #374151; font-size: 0.75em; }
.badge.gap-type { background: #e0e7ff; color: #4338ca; }
.badge.effort-trivial { background: #dcfce7; color: #16a34a; }
.badge.effort-moderate { background: #fef3c7; color: #d97706; }
.badge.effort-significant { background: #fee2e2; color: #dc2626; }
+ .docs-cell { max-width: 200px; }
+ .job-desc { font-size: 0.8em; color: #666; font-weight: normal; }
tr.tier-gold { background: #fffbeb; }
tr.tier-green { background: #f0fdf4; }
tr.tier-yellow { background: #fefce8; }
@@ -718,12 +1655,16 @@ function generateHtmlReport(
<h2>Results by Category</h2>
<table>
<thead>
- <tr><th>Category</th><th>Tiers</th><th>Rate</th><th>Count</th><th>Breakdown</th></tr>
+ <tr><th>Category</th><th>Tiers</th><th>Rate</th><th>Count</th><th>Breakdown</th><th>Avg Time</th></tr>
</thead>
<tbody>${categoryRows}</tbody>
</table>
</div>
+ ${tokenUsageHtml}
+
+ ${degradationGraphHtml}
+
${
criticalRows
? `
@@ -784,8 +1725,9 @@ function generateHtmlReport(
<th>Category</th>
<th>Prompt</th>
<th>Escape Hatches</th>
- <th>Duration</th>
- <th>Tokens</th>
+ <th>Time</th>
+ <th>Tokens (in/out)</th>
+ <th>Docs Read</th>
<th>Response</th>
</tr>
</thead>
@@ -820,9 +1762,8 @@ async function main() {
const resultsDir = path.join(getResultsDir(), iterationId);
try {
- // Read results for HTML report
- const runsPath = path.join(resultsDir, 'runs.jsonl');
- const results = readJsonl<TestResult>(runsPath);
+ // Read results for HTML report (uses individual files or runs.jsonl)
+ const results = loadResults(resultsDir);
const agg = aggregate(iterationId);
diff --git a/internal/vibe-tests/src/interactive.ts b/internal/vibe-tests/src/interactive.ts
index 82b6eb0f66..97567120a1 100644
--- a/internal/vibe-tests/src/interactive.ts
+++ b/internal/vibe-tests/src/interactive.ts
@@ -74,7 +74,7 @@ interface InteractiveConfig {
sample?: number;
holdout?: boolean;
persona: 'naive' | 'experienced' | 'adversarial';
- useAgentsMd: boolean; // Use AGENTS.md (default true)
+ degradation?: boolean; // Enable degradation curve testing
}
interface AgentTask {
@@ -83,14 +83,13 @@ interface AgentTask {
prompt: string;
expectedComponents: string[];
persona: string;
- skillDocPath: string;
- useAgentsMd?: boolean;
+ degradation?: boolean; // Run multi-turn degradation test
}
/**
* Generate the agent prompt for a single test
*/
-function generateAgentPrompt(task: AgentTask, skillDoc: string): string {
+function generateAgentPrompt(task: AgentTask): string {
const personaInstructions = {
naive: `You are testing as a NAIVE user who describes UIs in plain language without technical terms.
You don't know component names. Describe what you want visually.`,
@@ -100,16 +99,13 @@ Use correct component names and reference the docs.`,
Reference Tailwind, shadcn, Bootstrap patterns in your request.`,
};
- // When using AGENTS.md, don't inject skill doc - Claude Code reads it automatically
- const skillDocSection = task.useAgentsMd
- ? `## Component Documentation
-The XDS component library documentation is available via AGENTS.md.
-Read docs from .xds-docs/ for detailed component API and patterns.
-Key files: .xds-docs/principles.md, .xds-docs/tokens.md, .xds-docs/{ComponentName}.md`
- : `## Skill Doc (Component System)
-<skill-doc>
-${skillDoc}
-</skill-doc>`;
+ // Always use AGENTS.md - Claude Code auto-injects it from cwd
+ const skillDocSection = `## Component Documentation
+
+XDS documentation is auto-loaded via AGENTS.md.
+
+Before generating code, read \`.xds-docs/tokens.md\` for valid CSS variable names.
+Valid patterns: \`--color-*\`, \`--spacing-*\`, \`--radius-*\`, \`--elevation-*\`, \`--text-*\`, \`--font-body\`, \`--font-code\`, \`--font-heading\``;
return `# Vibe Test Task
@@ -135,6 +131,7 @@ Expected Components: ${task.expectedComponents.join(', ')}
- Did you hallucinate any props that don't exist?
- Did you use redundant CSS for things components already handle?
- Did you use acceptable supplemental CSS for gaps?
+ - **CSS Variables**: Did you use valid XDS tokens? Check .xds-docs/tokens.md for the complete list of valid variable names.
3. **Output JSON** in this exact format:
\`\`\`json
@@ -192,7 +189,6 @@ function createTaskManifest(
prompts: TestPrompt[],
config: InteractiveConfig,
iterationId: string,
- skillDocPath: string,
): void {
const resultsDir = path.join(getResultsDir(), iterationId);
ensureDir(resultsDir);
@@ -201,7 +197,6 @@ function createTaskManifest(
iterationId,
createdAt: timestamp(),
config,
- skillDocPath,
prompts: prompts.map(p => ({
id: p.id,
category: p.category,
@@ -226,8 +221,7 @@ function createTaskManifest(
prompt: prompt.prompt,
expectedComponents: prompt.expectedComponents,
persona: config.persona,
- skillDocPath,
- useAgentsMd: config.useAgentsMd,
+ degradation: config.degradation,
};
writeJson(path.join(tasksDir, `${prompt.id}.json`), task);
}
@@ -244,9 +238,27 @@ function createTaskManifest(
function generateSubagentInstructions(
iterationId: string,
prompts: TestPrompt[],
+ config: InteractiveConfig,
): string {
const resultsDir = path.join(getResultsDir(), iterationId);
+ const degradationInstructions = config.degradation
+ ? `
+
+### Degradation Protocol (10-turn curve)
+Each test runs through multiple conversation turns:
+- Turn 0: Initial probe (generate code)
+- Turns 1-5: Filler prompts (unrelated questions)
+- Turn 6: Re-probe with "Actually, let me revisit this..."
+- Turn 7: Distractor (different framework question)
+- Turn 8: Re-probe with "I want to redo that earlier request..."
+- Turn 9: Recovery (re-inject partial context)
+- Turn 10: Final re-probe with "Let me try that again..."
+
+Record results at turns 0, 6, 8, and 10 with trajectoryDepth field set accordingly.
+`
+ : '';
+
return `
# Interactive Vibe Test - Iteration ${iterationId}
@@ -254,6 +266,8 @@ function generateSubagentInstructions(
To run these ${prompts.length} tests in parallel, use the Task tool to spawn subagents.
+**Recommended**: Run with \`mode: "bypassPermissions"\` to avoid approval prompts for writing results.
+${degradationInstructions}
### Option 1: Run all in parallel (recommended for small batches)
Spawn ${prompts.length} subagents, one for each test prompt.
@@ -263,18 +277,19 @@ Spawn subagents in groups of 3-5 for larger test sets.
### Subagent Prompt Template
For each test, the subagent should:
1. Read the task file: ${resultsDir}/tasks/{prompt-id}.json
-2. Read the skill doc
-3. Generate a response to the prompt
+2. Read XDS docs from .xds-docs/ (AGENTS.md auto-injected)
+3. Generate a response to the prompt${config.degradation ? ' (with multi-turn conversation)' : ''}
4. Self-evaluate the response
-5. Write results to: ${resultsDir}/runs.jsonl
+5. Write result to individual file: ${resultsDir}/results/{promptId}.json
+ (Use individual files to avoid parallel write conflicts)
### After All Tests Complete
Run: yarn workspace @xds/vibe-tests aggregate --iteration ${iterationId}
This will:
-- Read all results from runs.jsonl
+- Read all results from results/ directory
- Calculate success rates by category
-- Generate the summary report
+- Generate the summary report${config.degradation ? '\n- Show degradation curve with line graph' : ''}
`;
}
@@ -291,15 +306,12 @@ async function main() {
personaIndex !== -1
? (args[personaIndex + 1] as 'naive' | 'experienced' | 'adversarial')
: 'naive';
- // AGENTS.md mode is now default, use --legacy-skill-doc to inject skill doc explicitly
- const useAgentsMd = !args.includes('--legacy-skill-doc');
+ const degradation = args.includes('--degradation');
- const config: InteractiveConfig = {sample, holdout, persona, useAgentsMd};
+ const config: InteractiveConfig = {sample, holdout, persona, degradation};
- // Install AGENTS.md if using agents mode
- if (useAgentsMd) {
- installAgentsDocs();
- }
+ // Always install AGENTS.md for retrieval-led approach
+ installAgentsDocs();
// Load test set
const testSetPath = path.join(__dirname, '..', 'test-sets', 'default.json');
@@ -320,33 +332,23 @@ async function main() {
// Generate iteration ID
const iterationId = generateIterationId();
- // Get skill doc path (still needed for legacy mode and version tracking)
- const skillDocPath = path.join(
- __dirname,
- '..',
- '..',
- '..',
- 'packages',
- 'core',
- 'xds.md',
- );
-
console.log(`\n🧪 Interactive Vibe Test Setup`);
console.log(`================================`);
console.log(`Iteration: ${iterationId}`);
console.log(`Persona: ${persona}`);
+ console.log(`Mode: AGENTS.md (retrieval-led)`);
console.log(
- `Mode: ${useAgentsMd ? 'AGENTS.md (retrieval-led)' : 'Legacy skill doc injection'}`,
+ `Protocol: ${degradation ? 'Degradation (10-turn curve)' : 'One-shot'}`,
);
console.log(
`Prompts: ${prompts.length}${sample ? ` (sampled from ${testSet.prompts.length})` : ''}`,
);
// Create task manifest
- createTaskManifest(prompts, config, iterationId, skillDocPath);
+ createTaskManifest(prompts, config, iterationId);
// Output instructions
- console.log(generateSubagentInstructions(iterationId, prompts));
+ console.log(generateSubagentInstructions(iterationId, prompts, config));
// Output the prompts for easy reference
console.log(`\n## Test Prompts\n`);
diff --git a/internal/vibe-tests/src/run-interactive.ts b/internal/vibe-tests/src/run-interactive.ts
index b57a10b0e7..043b8224dd 100644
--- a/internal/vibe-tests/src/run-interactive.ts
+++ b/internal/vibe-tests/src/run-interactive.ts
@@ -56,18 +56,19 @@ async function main() {
const taskPath = path.join(tasksDir, taskFile);
const task = JSON.parse(fs.readFileSync(taskPath, 'utf-8'));
- // Generate different instructions based on mode
- const docInstructions = task.useAgentsMd
- ? `Use the XDS documentation from AGENTS.md. Read docs from .xds-docs/ as needed (principles.md, tokens.md, {ComponentName}.md).`
- : `Read skill doc at: ${task.skillDocPath}`;
-
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}
-${docInstructions}
+
+XDS AGENTS.md is auto-injected and provides guidance on XDS components and which docs to read.
+
+IMPORTANT: Track which docs you read. Keep a list of doc filenames (e.g., ['AGENTS.md', 'Button.md', 'tokens.md']).
Generate code for: \\"${task.prompt}\\"
Expected components: ${task.expectedComponents.join(', ')}
@@ -77,7 +78,9 @@ Self-evaluate your response and output JSON with:
- response: your code
- evaluation: { success, componentsUsed, componentsExpected, escapeHatches, failureMode, confusionSignals }
-Then append the result as a TestResult JSON object to: ${resultsDir}/runs.jsonl
+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:
{
@@ -92,7 +95,11 @@ The TestResult format is:
response: <your generated code>,
evaluation: <your evaluation>,
fullConversation: [],
- contextWindowUsage: 0
+ contextWindowUsage: 0,
+ durationMs: <calculated duration in milliseconds>,
+ inputTokens: 0,
+ outputTokens: 0,
+ docsRead: <list of doc filenames you read>
}"
});
`);
diff --git a/internal/vibe-tests/src/types.ts b/internal/vibe-tests/src/types.ts
index 2af7210e10..578719cb67 100644
--- a/internal/vibe-tests/src/types.ts
+++ b/internal/vibe-tests/src/types.ts
@@ -67,6 +67,38 @@ export interface Evaluation {
confusionSignals: string[];
}
+/** Job breakdown for output token analysis */
+export interface JobBreakdown {
+ componentRouting: number;
+ componentConfig: number;
+ supplementalStyling: number;
+ contentAuthoring: number;
+ businessLogic: number;
+ boilerplate: number;
+ total: number;
+}
+
+/** Input token breakdown by doc type */
+export interface InputTokenBreakdown {
+ /** AGENTS.md - always read */
+ agentsMd: number;
+ /** principles.md, tokens.md - styling/design guidance */
+ designDocs: number;
+ /** Component-specific docs (Button.md, TextInput.md, etc.) */
+ componentDocs: number;
+ /** Prompt and instructions */
+ promptOverhead: number;
+ /** Total estimated input tokens */
+ total: number;
+}
+
+/** Full token usage breakdown */
+export interface TokenUsageBreakdown {
+ input: InputTokenBreakdown;
+ output: JobBreakdown;
+ total: number;
+}
+
export interface TestResult {
id: string;
timestamp: string;
@@ -84,6 +116,10 @@ export interface TestResult {
durationMs: number;
inputTokens: number;
outputTokens: number;
+ // Optional job breakdown
+ jobBreakdown?: JobBreakdown;
+ // Docs that were read (for input token tracking)
+ docsRead?: string[];
}
export type RefinementTarget =
diff --git a/packages/core/xds.md b/packages/core/xds.md
index 1e6d7df094..ad67fc6a3a 100644
--- a/packages/core/xds.md
+++ b/packages/core/xds.md
@@ -67,10 +67,25 @@ import {XDSTheme, useXDSTheme, defaultTheme} from '@xds/core';
// Good - use theme tokens via StyleX
const styles = stylex.create({
- error: { color: 'var(--xds-color-negative)' }
+ error: { color: 'var(--color-negative)' }
});
```
+## CSS Variables Reference
+
+XDS provides design tokens as CSS variables. Only use these patterns:
+
+| Category | Pattern | Examples |
+| ------------- | ---------------------------------------------- | ------------------------------------------------------------------------------- |
+| Colors | `--color-*` | `--color-surface`, `--color-text-primary`, `--color-accent`, `--color-negative` |
+| Spacing | `--spacing-*` | `--spacing-0`, `--spacing-1`, `--spacing-2`, ..., `--spacing-7` |
+| Radius | `--radius-*` | `--radius-container`, `--radius-element`, `--radius-content` |
+| Elevation | `--elevation-*` | `--elevation-base`, `--elevation-dialog`, `--elevation-menu` |
+| Font families | `--font-body`, `--font-code`, `--font-heading` | (only these three exist) |
+| Text sizes | `--text-*` | `--text-sm`, `--text-base`, `--text-lg`, `--text-xl` |
+| Line heights | `--leading-*` | `--leading-tight`, `--leading-normal`, `--leading-relaxed` |
+| Font weights | `--font-weight-*` | `--font-weight-normal`, `--font-weight-semibold`, `--font-weight-bold` |
+
❌ **Hardcoded spacing** - Use semantic tokens
```tsx