An open source design system that's fully customizable and agent ready
TypeScript
Set up vibe test harness (#57)
Cindy Zhang9019cc40ffbd
diff --git a/.claude/commands/vibe-test.md b/.claude/commands/vibe-test.mdnew file mode 100644index 0000000000..380b2551cb--- /dev/null+++ b/.claude/commands/vibe-test.md@@ -0,0 +1,135 @@+# Run Vibe Tests++Run vibeability tests to measure how well the XDS skill doc helps LLMs generate correct component code.++## Sample Count++$ARGUMENTS++If no argument provided, default to 5 samples.++## Instructions++Run interactive vibe tests using parallel subagents:++### Step 1: Setup the test iteration++Run the interactive setup command:++```bash+yarn workspace @xds/vibe-tests interactive --sample <count>+```++This creates:++- A unique iteration ID+- Task files in `internal/vibe-tests/results/<iteration>/tasks/`+- A manifest file++### Step 2: Read the test prompts++Read the manifest to get the list of test prompts:++```+internal/vibe-tests/results/<iteration>/manifest.json+```++### Step 3: Run tests in parallel++For each test prompt, spawn a subagent using the Task tool with:++- `subagent_type`: "general-purpose"+- Read the skill doc at `packages/core/xds.md`+- Generate code for the prompt using XDS components+- Self-evaluate the response for:+ - Correct components used+ - No hallucinated props+ - Acceptable vs critical escape hatches+- Track timing: record start time before generating, calculate durationMs after+- Return JSON with: response, evaluation, durationMs, inputTokens, outputTokens++### Step 4: Write results++After all subagents complete, write results to:++```+internal/vibe-tests/results/<iteration>/runs.jsonl+```++Each line should be a JSON object with:++```json+{+ "id": "<iteration>-<promptId>",+ "timestamp": "<ISO timestamp>",+ "systemVersion": "xds-llms-v1",+ "model": "claude-code-interactive",+ "persona": "naive",+ "promptCategory": "<category>",+ "trajectoryDepth": 0,+ "prompt": "<the prompt>",+ "response": "<generated code>",+ "evaluation": {+ "success": true/false,+ "componentsUsed": ["XDSCard", ...],+ "componentsExpected": ["XDSCard", ...],+ "escapeHatches": [{"type": "...", "severity": "acceptable/critical", "detail": "...", "codeSnippet": "..."}],+ "failureMode": null or "description",+ "confusionSignals": []+ },+ "fullConversation": [],+ "contextWindowUsage": 0,+ "durationMs": <milliseconds taken>,+ "inputTokens": <input tokens used>,+ "outputTokens": <output tokens generated>+}+```++### Step 5: Aggregate results++Run:++```bash+yarn workspace @xds/vibe-tests aggregate --iteration <id>+```++This will print a summary showing:++- Overall success rate+- Performance stats (total time, avg time, tokens used)+- Success by category+- Critical issues (if any)+- Acceptable escape hatches++It also generates an HTML report at `results/<iteration>/report.html` that you can open in a browser to inspect individual test results.++### Evaluation Criteria++**Quality Tiers:**++- π₯ **Gold** - Pure XDS, no escape hatches needed+- π’ **Green** - Correct components, only acceptable escape hatches+- π‘ **Yellow** - Anti-patterns that break theming (hardcoded values)+- π΄ **Red** - Critical failures++**Critical escape hatches (Red tier):**++- `hallucination` - Invented props/components that don't exist+- `wrong_component` - Using a component incorrectly+- `redundant_css` - CSS that duplicates a component prop++**Anti-pattern escape hatches (Yellow tier - break theming):**++- `hardcoded_color` - Direct color values instead of CSS variables+- `hardcoded_spacing` - Direct pixel values for spacing instead of CSS variables+- `hardcoded_size` - Direct pixel values for sizes instead of CSS variables+- `inline_style` - Inline styles instead of StyleX++**Acceptable escape hatches (Green tier):**++- `supplemental_css` - StyleX for things XDS doesn't cover+- `wrapper_div` - Structural HTML for composition+- `custom_animation` - Animation not covered by XDS+- `layout_workaround` - Layout patterns XDS doesn't support++When evaluating, also include a `gap` field on escape hatches describing what capability is missing, to help generate improvement suggestions.diff --git a/.context/proposals/vibeability-test-harness.md b/.context/proposals/vibeability-test-harness.mdnew file mode 100644index 0000000000..6bc90412a6--- /dev/null+++ b/.context/proposals/vibeability-test-harness.md@@ -0,0 +1,358 @@+# Vibeability Test Harness Spec++Build a test harness that measures how well LLMs can use a component system, tracks degradation over conversation length, and suggests refinements through a closed-loop analysis cycle.++## Directory Structure++```+tools/vibeability-harness/+βββ harness.ts # Main entry point (Deno)+βββ 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+βββ 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+```++## Core Types++```typescript+interface Turn {+ type: 'probe' | 'filler' | 'distractor' | 'recovery';+ prompt: string;+ response: string;+ evaluation?: Evaluation;+}++interface EscapeHatch {+ type:+ | 'hallucination'+ | 'wrong_component'+ | 'redundant_css'+ | 'supplemental_css'+ | 'wrapper_div'+ | 'inline_style';+ severity: 'critical' | 'acceptable';+ detail: string;+ codeSnippet: string;+}++interface Evaluation {+ success: boolean;+ componentsUsed: string[];+ componentsExpected: string[];+ escapeHatches: EscapeHatch[];+ failureMode: string | null;+ confusionSignals: string[]; // hedging language, clarifying questions+}++interface TestResult {+ id: string;+ timestamp: string;+ systemVersion: string; // hash or version of skill doc+ model: string;+ persona: string;+ promptCategory: string;+ trajectoryDepth: number;+ prompt: string;+ response: string;+ evaluation: Evaluation;+ fullConversation: Turn[];+ contextWindowUsage: number;+}++interface Refinement {+ target: 'skill_doc' | 'component_api' | 'component_naming' | 'examples';+ component: string | null;+ suggestion: string;+ evidence: string[]; // TestResult IDs+ 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):++- `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++**Acceptable** (noted but does NOT count against success):++- `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++The component system doesn't aim for 100% coverage. CSS for layout, responsive behavior, or decoration outside component scope is expected and acceptable.++## 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"++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++### One-shot baseline++1. Inject skill doc as system context+2. Run each prompt from test set (or sampled subset)+3. Evaluate response+4. Record result++### Degradation curve++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++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.++### Persona comparison++Run same prompt set with each persona, compare success rates and failure modes.++## 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++### Analyst (prompts/analyst.md)++You analyze batches of vibeability test results to identify patterns and suggest refinements.++Look for:++- 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)++Root cause categories:++- **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)++Sampling awareness:++- 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++Prioritize refinements by: high impact + low effort first.++### Personas++**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".++**experienced.md**: You know the component system well. You use correct component names and props. You might reference the docs.++**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".++## 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++# Run holdout set for unbiased evaluation+deno run --allow-all harness.ts run --holdout++# Run specific protocol+deno run --allow-all harness.ts run --protocol degradation++# Run with specific persona+deno run --allow-all harness.ts run --persona naive++# Generate HTML report for visual inspection+deno run --allow-all harness.ts report --iteration abc123++# Analyze results from an iteration+deno run --allow-all harness.ts analyze --iteration abc123++# Start new iteration with refinements applied+deno run --allow-all harness.ts iterate --from abc123++# View iteration history+deno run --allow-all harness.ts history+```++## Configuration++Read skill doc path from env or flag:++```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+```++## Key Implementation Notes++- 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++## Output Example++After `harness.ts run --sample 10`:++```+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...++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++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)++Saved: ./results/a1b2c3d4/refinements.json+```diff --git a/.github/workflows/vibe-tests.yml.disabled b/.github/workflows/vibe-tests.yml.disablednew file mode 100644index 0000000000..f98ccc0943--- /dev/null+++ b/.github/workflows/vibe-tests.yml.disabled@@ -0,0 +1,224 @@+# =============================================================================+# DISABLED: This workflow is temporarily disabled.+#+# To re-enable:+# 1. Add ANTHROPIC_API_KEY secret to the repository+# 2. Rename this file back to vibe-tests.yml+# =============================================================================++name: Vibe Tests++on:+ pull_request:+ branches: [main, master]+ push:+ branches: [main, master]+ workflow_dispatch:+ inputs:+ sample_size:+ description: 'Number of test prompts to run'+ required: false+ default: '10'++concurrency:+ group: vibe-tests-${{ github.head_ref || github.ref }}+ cancel-in-progress: true++jobs:+ vibe-test:+ name: Run Vibe Tests+ runs-on: ubuntu-latest+ permissions:+ contents: read+ pull-requests: write+ actions: read++ steps:+ - name: Checkout+ uses: actions/checkout@v4++ - name: Setup Node.js+ uses: actions/setup-node@v4+ with:+ node-version: '22'+ cache: 'yarn'++ - name: Install dependencies+ run: yarn install --frozen-lockfile++ - name: Run vibe tests+ id: vibe-test+ env:+ ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}+ SKILL_DOC: packages/core/xds.md+ run: |+ # Determine sample size+ SAMPLE_SIZE="${{ github.event.inputs.sample_size || '10' }}"++ # Run the tests+ echo "Running vibe tests with sample size: $SAMPLE_SIZE"+ yarn workspace @xds/vibe-tests test:xds:sample 2>&1 | tee vibe-test-output.txt++ # Extract iteration ID from output+ ITERATION_ID=$(grep -oP 'Iteration: \K[a-f0-9]+' vibe-test-output.txt | head -1)+ echo "iteration_id=$ITERATION_ID" >> $GITHUB_OUTPUT+ echo "Iteration ID: $ITERATION_ID"++ - name: Aggregate results+ id: aggregate+ if: steps.vibe-test.outputs.iteration_id != ''+ run: |+ ITERATION_ID="${{ steps.vibe-test.outputs.iteration_id }}"+ yarn workspace @xds/vibe-tests aggregate --iteration "$ITERATION_ID" --ci++ - name: Upload results artifact+ if: steps.vibe-test.outputs.iteration_id != ''+ uses: actions/upload-artifact@v4+ with:+ name: vibe-test-results-${{ steps.vibe-test.outputs.iteration_id }}+ path: |+ internal/vibe-tests/results/${{ steps.vibe-test.outputs.iteration_id }}/+ retention-days: 90++ - name: Upload HTML report+ if: steps.vibe-test.outputs.iteration_id != ''+ uses: actions/upload-artifact@v4+ with:+ name: vibe-test-report-${{ steps.vibe-test.outputs.iteration_id }}+ path: internal/vibe-tests/results/${{ steps.vibe-test.outputs.iteration_id }}/report.html+ retention-days: 90++ - name: Comment on PR+ if: github.event_name == 'pull_request' && steps.vibe-test.outputs.iteration_id != ''+ uses: actions/github-script@v7+ with:+ script: |+ const successRate = '${{ steps.aggregate.outputs.success_rate }}';+ const gold = '${{ steps.aggregate.outputs.gold }}' || '0';+ const green = '${{ steps.aggregate.outputs.green }}' || '0';+ const yellow = '${{ steps.aggregate.outputs.yellow }}' || '0';+ const red = '${{ steps.aggregate.outputs.red }}' || '0';+ const iterationId = '${{ steps.vibe-test.outputs.iteration_id }}';+ const runUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;++ // Determine status emoji+ let statusEmoji = 'π΄';+ if (parseInt(successRate) >= 90) statusEmoji = 'π’';+ else if (parseInt(successRate) >= 70) statusEmoji = 'π‘';++ const body = `## ${statusEmoji} Vibe Test Results++ **Iteration:** \`${iterationId}\`+ **Success Rate:** ${successRate}%++ ### Quality Tiers+ | Tier | Count |+ |------|-------|+ | π₯ Gold (pure XDS) | ${gold} |+ | π’ Green (acceptable) | ${green} |+ | π‘ Yellow (anti-pattern) | ${yellow} |+ | π΄ Red (critical) | ${red} |++ <details>+ <summary>Tier Definitions</summary>++ - **Gold**: Pure XDS, no escape hatches needed+ - **Green**: Correct components with acceptable escape hatches+ - **Yellow**: Anti-patterns that break theming (hardcoded values, inline styles)+ - **Red**: Critical failures (hallucinations, wrong components)+ </details>++ π [View full report](${runUrl}) (download artifacts)+ `;++ // Find existing comment+ const { data: comments } = await github.rest.issues.listComments({+ owner: context.repo.owner,+ repo: context.repo.repo,+ issue_number: context.issue.number,+ });++ const botComment = comments.find(comment =>+ comment.user.type === 'Bot' &&+ comment.body.includes('Vibe Test Results')+ );++ if (botComment) {+ await github.rest.issues.updateComment({+ owner: context.repo.owner,+ repo: context.repo.repo,+ comment_id: botComment.id,+ body: body+ });+ } else {+ await github.rest.issues.createComment({+ owner: context.repo.owner,+ repo: context.repo.repo,+ issue_number: context.issue.number,+ body: body+ });+ }++ - name: Check threshold+ if: steps.aggregate.outputs.success_rate != ''+ run: |+ SUCCESS_RATE="${{ steps.aggregate.outputs.success_rate }}"+ RED="${{ steps.aggregate.outputs.red }}"++ echo "β Success rate: $SUCCESS_RATE%"+ echo "β Critical failures: $RED"++ # Fail if success rate is below 70%+ if [ "$SUCCESS_RATE" -lt 70 ]; then+ echo "::error::Vibe test success rate ($SUCCESS_RATE%) is below threshold (70%)"+ exit 1+ fi++ echo "β Vibe tests passed with $SUCCESS_RATE% success rate"++ store-results:+ name: Store Historical Results+ needs: vibe-test+ if: github.event_name == 'push' && github.ref == 'refs/heads/main'+ runs-on: ubuntu-latest+ permissions:+ contents: write++ steps:+ - name: Checkout+ uses: actions/checkout@v4+ with:+ ref: vibe-test-history+ fetch-depth: 0++ - name: Download artifacts+ uses: actions/download-artifact@v4+ with:+ pattern: vibe-test-results-*+ path: results/+ merge-multiple: true++ - name: Commit results+ run: |+ git config user.name "github-actions[bot]"+ git config user.email "github-actions[bot]@users.noreply.github.com"++ # Create branch if it doesn't exist+ if ! git rev-parse --verify vibe-test-history >/dev/null 2>&1; then+ git checkout --orphan vibe-test-history+ git rm -rf . || true+ echo "# Vibe Test Results History" > README.md+ echo "" >> README.md+ echo "This branch stores historical vibe test results from CI runs." >> README.md+ fi++ # Add new results+ TIMESTAMP=$(date +%Y-%m-%d-%H%M%S)+ COMMIT_SHA="${{ github.sha }}"+ mkdir -p "history/${TIMESTAMP}-${COMMIT_SHA:0:7}"+ cp -r results/* "history/${TIMESTAMP}-${COMMIT_SHA:0:7}/" || true++ # Commit and push+ git add .+ git commit -m "Add vibe test results from ${COMMIT_SHA:0:7}" || echo "No changes to commit"+ git push origin vibe-test-history || echo "Failed to push, branch may not exist"diff --git a/.gitignore b/.gitignoreindex 136be0f7e7..cfc76a44e1 100644--- a/.gitignore+++ b/.gitignore@@ -42,3 +42,9 @@ e2e/playwright/.cache/# Lint.eslintcache++# Vibe tests (large generated files)+internal/vibe-tests/results/++# XDS agent docs (generated)+.xds-docs/diff --git a/CLAUDE.md b/CLAUDE.mdindex 10c971a357..bfc5a38310 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -2,9 +2,39 @@A design system for building internal tools and products.+## Custom Commands++### `/vibe-test [count]` - Run vibeability tests++Tests how well the AI skill doc helps generate correct XDS component code.++**Usage:**++```+/vibe-test 5 # Run 5 stratified sample tests+/vibe-test # Run all 21 tests+```++**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+ - Self-evaluate for success/escape hatches+ - Append result to `results/<iteration>/runs.jsonl`+3. Run `yarn workspace @xds/vibe-tests aggregate --iteration <id>` to see results++**Result format in runs.jsonl:**++```json+{"id":"<iter>-<promptId>","timestamp":"...","model":"claude-code-interactive","persona":"naive","promptCategory":"...","prompt":"...","response":"<code>","evaluation":{"success":true,"componentsUsed":[...],"escapeHatches":[...]}}+```+## AI ContextFor architectural context and decisions, see `.context/`:+- `.context/decisions/` β Architecture Decision Records- `.context/explorations/` β Research and brainstorms- `.context/proposals/` β Feature proposals@@ -18,6 +48,7 @@ This project uses **Fractal Documentation** β a self-referential pattern where3. **File Headers** β Each source file has a structured JSDoc header with `@input`, `@output`, `@position`**Update Protocol**: When modifying code, update:+1. The file's header comment2. The directory's README.md3. Parent documentation if architecture changes@@ -27,7 +58,6 @@ Look for `<!-- SYNC: ... -->` comments and `SYNC:` in file headers as reminders.## Quick Reference- **Package manager**: Yarn 1 (Classic)-- **Monorepo tool**: Turborepo- **Testing**: Vitest (colocated tests)- **Components**: `packages/core/`- **Storybook**: `apps/storybook/`diff --git a/internal/README.md b/internal/README.mdindex 8cf69f33bd..c4c74953e8 100644--- a/internal/README.md+++ b/internal/README.md@@ -4,7 +4,7 @@ Internal tooling packages not published to npm.<!-- SYNC: When files in this directory change, update this document. -->-| Directory | Role | Purpose |-|-----------|------|---------|-| `test-utils/` | Testing | Shared testing utilities and setup for Vitest |-+| Directory | Role | Purpose |+| ------------- | ------- | ------------------------------------------------- |+| `test-utils/` | Testing | Shared testing utilities and setup for Vitest |+| `vibe-tests/` | Testing | LLM vibeability test harness for component system |diff --git a/internal/vibe-tests/.gitignore b/internal/vibe-tests/.gitignorenew file mode 100644index 0000000000..e409d44519--- /dev/null+++ b/internal/vibe-tests/.gitignore@@ -0,0 +1,3 @@+# XDS agent docs (generated)+.xds-docs/+AGENTS.mddiff --git a/internal/vibe-tests/README.md b/internal/vibe-tests/README.mdnew file mode 100644index 0000000000..723ce41597--- /dev/null+++ b/internal/vibe-tests/README.md@@ -0,0 +1,261 @@+# Vibe Tests++Vibeability test harness for measuring how well LLMs can use the XDS component system.++## Quick Start - Interactive Mode (Claude Code)++Run vibe tests directly in Claude Code without an API key:++```+/vibe-test 5+```++Or ask Claude Code:++```+"Run a vibe test with 5 samples"+```++This will:++1. Set up a test iteration+2. Spawn parallel subagents to run each test+3. Write results to runs.jsonl+4. Aggregate and show results++## Quick Start - API Mode++```bash+# Requires ANTHROPIC_API_KEY+yarn workspace @xds/vibe-tests test:xds:sample+```++## What It Does++The harness:++1. **Tests** LLM responses against the component system using realistic prompts+2. **Evaluates** whether the LLM used the right components and avoided escape hatches+3. **Analyzes** failures to suggest documentation improvements+4. **Tracks** degradation over conversation length++## Directory Structure++```+internal/vibe-tests/+βββ src/+β βββ cli.ts # Command-line interface+β βββ types.ts # TypeScript types+β βββ runner.ts # Test orchestration+β βββ evaluator.ts # Response evaluation+β βββ analyst.ts # Results analysis+β βββ sampling.ts # Stratified sampling+β βββ utils.ts # Utilities+βββ prompts/+β βββ evaluator.md # Evaluator agent prompt+β βββ analyst.md # Analyst agent prompt+β βββ personas/ # User personas+βββ test-sets/+β βββ default.json # Test prompt battery+βββ results/ # Generated (gitignored)+β βββ {iteration-id}/+β βββ runs.jsonl+β βββ analysis.json+β βββ report.html+βββ iterations.json # Iteration lineage+```++## Test Protocols++### One-shot++Single turn: inject skill doc β prompt β evaluate++### Degradation++Multi-turn conversation with re-probes:++- Turn 0: Initial probe+- Turns 1-5: Filler questions+- Turn 6: Re-probe+- Turn 7: Distractor ("use Tailwind instead")+- Turn 8: Re-probe+- Turn 9: Recovery (re-inject doc)+- Turn 10: Final re-probe++### Persona Comparison++Run same prompts with different personas:++- **naive**: Plain language, no component names+- **experienced**: Uses correct terminology+- **adversarial**: Mixes in patterns from other frameworks++## Escape Hatches++Tracked behaviors when LLMs deviate from the component system:++**Critical (Red tier - failures):**++- `hallucination` - Invented props/events/components+- `wrong_component` - Using a component incorrectly+- `redundant_css` - CSS that duplicates a component prop++**Anti-Patterns (Yellow tier - break theming):**++- `hardcoded_color` - Direct color values instead of CSS variables+- `hardcoded_spacing` - Direct pixel values instead of spacing tokens+- `hardcoded_size` - Direct pixel values instead of size tokens+- `inline_style` - Inline styles instead of StyleX++**Acceptable (Green tier - gaps in system):**++- `supplemental_css` - StyleX for gaps in component coverage+- `wrapper_div` - Structural HTML for composition+- `custom_animation` - Animation not covered by XDS+- `layout_workaround` - Layout patterns XDS doesn't support++## Quality Tiers++Results are scored into four quality tiers:++- π₯ **Gold** - Pure XDS, no escape hatches needed+- π’ **Green** - Correct components, only acceptable escape hatches+- π‘ **Yellow** - Anti-patterns that break theming+- π΄ **Red** - Critical failures++The aggregate report shows tier breakdown by category and generates suggestions for component/API improvements based on escape hatch patterns.++## Configuration++Set skill doc path:++```bash+SKILL_DOC=./path/to/skill.md yarn harness run+# or+yarn harness run --skill-doc ./path/to/skill.md+```++Choose model:++```bash+yarn harness run --model claude-sonnet-4-20250514+yarn harness run --model gpt-4o+```++## Output++After running tests:++```+Running vibeability tests...+ Protocol: one-shot+ Persona: naive+ Model: claude-sonnet-4-20250514+ Test set: default (21 prompts)+ Iteration: a1b2c3d4++ [ββββββββββββββββββββ] 21/21++Results:+ Overall: 86% success (18/21)++ Quality Tiers:+ π₯ Gold (pure XDS): 5 (24%)+ π’ Green (acceptable): 10 (48%)+ π‘ Yellow (anti-pattern): 3 (14%)+ π΄ Red (critical): 3 (14%)++ Performance:+ Total time: 45.2s (avg 2.2s per test)+ Tokens: 125,000 total (100,000 in / 25,000 out)++ By category:+ feature-with-constraint: 100% [π₯2 π’1 π‘0 π΄0]+ workflow-description: 67% [π₯0 π’1 π‘1 π΄1]+ ...++ Critical issues (Red):+ - hallucination (3)++ Anti-patterns (Yellow):+ - hardcoded_color (2)+ - hardcoded_spacing (1)+ - inline_style (3)++ Acceptable escape hatches (Green):+ - supplemental_css (8)+ - wrapper_div (4)++ Gap Suggestions:+ π¨ [trivial] Add semantic color token for: accent backgrounds (seen 2x)+ π§ [trivial] Add spacing/size prop to cover: card padding (seen 1x)++ HTML Report: results/a1b2c3d4/report.html+```++### HTML Report++The aggregate command generates an interactive HTML report at `results/<iteration>/report.html` that shows:++- Summary stats (success rate, timing, tokens)+- Results by category with progress bars+- Critical issues and escape hatches+- Individual test results with expandable code responses++After analysis:++```+Analyzing iteration a1b2c3d4...++Patterns detected:+ - Multi-step workflows trigger hallucinated state props+ - Adversarial persona causes Tailwind utility usage++Suggested refinements:+ 1. [examples] Add multi-step form example (confidence: 0.9, effort: trivial)+ 2. [skill_doc] Explicit "do not use Tailwind" note (confidence: 0.7, effort: trivial)+```++## CI Integration++Vibe tests run automatically on every PR via GitHub Actions.++### GitHub Action++The workflow (`.github/workflows/vibe-tests.yml`) runs on:++- Every pull request to main/master+- Every push to main/master+- Manual trigger with configurable sample size++### What it does:++1. Runs 10 stratified sample tests+2. Aggregates results and generates HTML report+3. Posts a summary comment on the PR+4. Uploads results as artifacts (90-day retention)+5. Fails the check if:+ - Success rate is below 70%+ - Any critical (Red tier) failures++### Required Secrets:++- `ANTHROPIC_API_KEY`: API key for running tests++### Aggregate CLI Flags:++```bash+# Standard output+yarn workspace @xds/vibe-tests aggregate --iteration abc123++# JSON output (for scripting)+yarn workspace @xds/vibe-tests aggregate --iteration abc123 --json++# CI mode (GitHub Actions output format)+yarn workspace @xds/vibe-tests aggregate --iteration abc123 --ci+```++## For More Details++See the full spec in `.context/proposals/vibeability-test-harness.md`diff --git a/internal/vibe-tests/iterations.json b/internal/vibe-tests/iterations.jsonnew file mode 100644index 0000000000..f37d5730c9--- /dev/null+++ b/internal/vibe-tests/iterations.json@@ -0,0 +1,3 @@+{+ "iterations": []+}diff --git a/internal/vibe-tests/package.json b/internal/vibe-tests/package.jsonnew file mode 100644index 0000000000..578288638f--- /dev/null+++ b/internal/vibe-tests/package.json@@ -0,0 +1,32 @@+{+ "name": "@xds/vibe-tests",+ "version": "0.0.1",+ "private": true,+ "description": "Vibeability test harness for measuring LLM component system usage",+ "type": "module",+ "bin": {+ "vibe-tests": "./src/cli.ts"+ },+ "scripts": {+ "harness": "tsx src/cli.ts",+ "test:xds": "SKILL_DOC=../../packages/core/xds.md tsx src/cli.ts run",+ "test:xds:sample": "SKILL_DOC=../../packages/core/xds.md tsx src/cli.ts run --sample 10",+ "test:xds:holdout": "SKILL_DOC=../../packages/core/xds.md tsx src/cli.ts run --holdout",+ "test:ci": "SKILL_DOC=../../packages/core/xds.md tsx src/cli.ts run --sample 10",+ "interactive": "tsx src/interactive.ts",+ "interactive:sample": "tsx src/interactive.ts --sample 5",+ "run-interactive": "tsx src/run-interactive.ts",+ "run-interactive:sample": "tsx src/run-interactive.ts --sample 5",+ "aggregate": "tsx src/aggregate.ts",+ "aggregate:ci": "tsx src/aggregate.ts --ci",+ "aggregate:json": "tsx src/aggregate.ts --json",+ "analyze": "tsx src/cli.ts analyze"+ },+ "dependencies": {+ "@anthropic-ai/sdk": "^0.52.0",+ "commander": "^12.1.0"+ },+ "devDependencies": {+ "tsx": "^4.19.0"+ }+}diff --git a/internal/vibe-tests/prompts/analyst.md b/internal/vibe-tests/prompts/analyst.mdnew file mode 100644index 0000000000..533ade96f5--- /dev/null+++ b/internal/vibe-tests/prompts/analyst.md@@ -0,0 +1,71 @@+# Analyst++You analyze batches of vibeability test results to identify patterns and suggest refinements to the component system documentation.++## Input++You will receive:++- A batch of TestResult objects+- The current skill doc+- Sampling metadata (prompts run vs total pool)++## Output++Return JSON matching the AnalysisResult schema:++```typescript+interface AnalysisResult {+ patterns: string[];+ refinements: Refinement[];+ summary: string;+}++interface Refinement {+ target: 'skill_doc' | 'component_api' | 'component_naming' | 'examples';+ component: string | null;+ suggestion: string;+ evidence: string[]; // TestResult IDs+ confidence: number; // 0-1+ effortEstimate: 'trivial' | 'moderate' | 'significant';+}+```++## Analysis Focus++Look for:++- 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)++## Root Cause Categories++- **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)++## Sampling Awareness++When results are from a sampled subset:++- Require evidence from β₯2 different categories before suggesting a refinement+- Exception: 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++## Prioritization++Order refinements by: high impact + low effort first.++A good refinement:++- Has clear evidence from multiple failures+- Has a specific, actionable suggestion+- Can be implemented quickly (trivial effort preferred)+- Will likely prevent similar failuresdiff --git a/internal/vibe-tests/prompts/evaluator.md b/internal/vibe-tests/prompts/evaluator.mdnew file mode 100644index 0000000000..2bc02ea9bf--- /dev/null+++ b/internal/vibe-tests/prompts/evaluator.md@@ -0,0 +1,78 @@+# Evaluator++You evaluate LLM-generated UI code against a component system.++## Input++You will receive:++- The user's prompt+- The generated response+- The expected components for this task+- The component system documentation (skill doc)++## Output++Return JSON matching the Evaluation schema:++```typescript+interface Evaluation {+ success: boolean;+ componentsUsed: string[];+ componentsExpected: string[];+ escapeHatches: EscapeHatch[];+ failureMode: string | null;+ confusionSignals: string[];+}++interface EscapeHatch {+ type:+ | 'hallucination'+ | 'wrong_component'+ | 'redundant_css'+ | 'supplemental_css'+ | 'wrapper_div'+ | 'inline_style';+ severity: 'critical' | 'acceptable';+ detail: string;+ codeSnippet: string;+}+```++## Evaluation Rules++### Success Criteria++**Success = correct components used where they exist + no critical escape hatches**++A response can be successful AND have acceptable escape hatches.++### Escape Hatch Severity++**Critical** (counts against success):++- `hallucination` β Inventing props, components, events, or APIs that don't exist in the skill doc+- `wrong_component` β Using a component for something it wasn't designed for+- `redundant_css` β CSS that duplicates what a component prop already handles++**Acceptable** (noted but does NOT count against success):++- `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++### Key Rules++1. Custom CSS for things the component system doesn't cover is acceptable+2. Hallucinated props/events are always critical+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++### Confusion Signals++Look for these in the response:++- Hedging language ("I think...", "Maybe...", "You might want to...")+- Clarifying questions+- Multiple alternatives offered with uncertainty+- Explicit mentions of not being sure about the APIdiff --git a/internal/vibe-tests/prompts/personas/adversarial.md b/internal/vibe-tests/prompts/personas/adversarial.mdnew file mode 100644index 0000000000..6ff26c8d8b--- /dev/null+++ b/internal/vibe-tests/prompts/personas/adversarial.md@@ -0,0 +1,27 @@+# Adversarial User Persona++You are a developer who mixes in patterns from other UI systems.++## Characteristics++- You reference Tailwind, shadcn, Bootstrap, Material UI, and other frameworks+- You use terminology from competing systems+- You might ask to replicate patterns that don't exist in this system+- You blur the lines between different component libraries++## Examples of how you speak++- "Can I use `flex justify-between` here?"+- "Make it look like a shadcn Dialog"+- "I want the Bootstrap card style with the image on top"+- "Add some `gap-4` spacing between these"+- "Use the MUI-style outlined variant"+- "I need a Radix-like dropdown menu"++## When making requests++- Mix framework-specific terminology freely+- Reference visual patterns from other libraries+- Use Tailwind utility class names as descriptions+- Ask to replicate specific designs from other systems+- Assume props or patterns exist that come from other librariesdiff --git a/internal/vibe-tests/prompts/personas/experienced.md b/internal/vibe-tests/prompts/personas/experienced.mdnew file mode 100644index 0000000000..10da9ed48c--- /dev/null+++ b/internal/vibe-tests/prompts/personas/experienced.md@@ -0,0 +1,25 @@+# Experienced User Persona++You are a developer who knows the component system well.++## Characteristics++- You use correct component names and props+- You might reference the docs+- You understand component composition patterns+- You ask specific, targeted questions++## Examples of how you speak++- "I need to use XDSCard with a header section"+- "What props does XDSButton accept for the loading state?"+- "How do I compose XDSField with XDSTextInput?"+- "The docs mention a 'variant' prop but I'm not sure which values are valid"++## When making requests++- Reference specific components by name+- Ask about prop configurations+- Inquire about edge cases and advanced usage+- May ask about composition patterns between components+- Sometimes quote or reference documentationdiff --git a/internal/vibe-tests/prompts/personas/naive.md b/internal/vibe-tests/prompts/personas/naive.mdnew file mode 100644index 0000000000..34451e48e9--- /dev/null+++ b/internal/vibe-tests/prompts/personas/naive.md@@ -0,0 +1,36 @@+# Naive User Persona++You are a developer who describes UIs in plain language without technical terms.++## Characteristics++- You don't know component names+- You describe visual appearance, not implementation+- You use everyday language instead of technical jargon++## Examples of how you speak++Instead of "a Card component", you say:++- "a box with a shadow"+- "a container with rounded corners"+- "a panel that holds content"++Instead of "a Button with variant='primary'", you say:++- "a clickable thing that stands out"+- "the main action button, you know, the blue one"+- "something users click to submit"++Instead of "a Modal dialog", you say:++- "a popup that blocks the background"+- "one of those overlay things"+- "a window that appears on top"++## When making requests++- Describe what you want to achieve, not how to implement it+- Reference visual examples from other sites you've seen+- Focus on user actions and outcomes+- Ask "how do I make it look like X" rather than "how do I use component Y"diff --git a/internal/vibe-tests/src/aggregate.ts b/internal/vibe-tests/src/aggregate.tsnew file mode 100644index 0000000000..ba7e4977ae--- /dev/null+++ b/internal/vibe-tests/src/aggregate.ts@@ -0,0 +1,903 @@+#!/usr/bin/env node+/**+ * @file Aggregate results from interactive vibe test runs+ *+ * Usage:+ * yarn workspace @xds/vibe-tests aggregate --iteration abc123+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import type {+ TestResult,+ Evaluation,+ ResultTier,+ EscapeHatch,+ GapSuggestion,+ EscapeHatchType,+} from './types.js';+import {readJsonl, readJson, writeJson, getResultsDir} from './utils.js';++/** Escape hatch types that indicate anti-patterns (break theming/system) */+const ANTI_PATTERN_HATCHES: EscapeHatchType[] = [+ 'hardcoded_color',+ 'hardcoded_spacing',+ 'inline_style', // Should use StyleX instead+];++/** Escape hatch types that indicate gaps in the component system */+const GAP_HATCHES: EscapeHatchType[] = [+ 'supplemental_css',+ 'custom_animation',+ 'layout_workaround',+];++interface TierCounts {+ gold: number;+ green: number;+ yellow: number;+ red: number;+}++interface AggregateResult {+ iterationId: string;+ totalTests: number;+ successCount: number;+ successRate: number;+ // Tiered results+ tiers: TierCounts;+ tierRate: Record<ResultTier, number>;+ byCategory: Record<+ string,+ {success: number; total: number; rate: number; tiers: TierCounts}+ >;+ byPersona: Record<string, {success: number; total: number; rate: number}>;+ criticalIssues: Record<string, number>;+ acceptableEscapeHatches: Record<string, number>;+ antiPatterns: Record<string, number>;+ // Gap analysis+ gaps: GapSuggestion[];+ // Timing and token metrics+ totalDurationMs: number;+ avgDurationMs: number;+ totalInputTokens: number;+ totalOutputTokens: number;+}++/** Normalize escape hatch to object format (handles string or object) */+function normalizeEscapeHatch(h: string | EscapeHatch): EscapeHatch {+ if (typeof h === 'string') {+ // String escape hatches are treated as acceptable with undefined type+ return {+ type: 'supplemental_css', // Default type for string descriptions+ severity: 'acceptable',+ codeSnippet: h,+ };+ }+ return h;+}++/** Calculate the tier for a single result */+function calculateTier(evaluation: Evaluation): ResultTier {+ const normalizedHatches = evaluation.escapeHatches.map(normalizeEscapeHatch);++ const criticalHatches = normalizedHatches.filter(+ h => h.severity === 'critical',+ );+ const antiPatternHatches = normalizedHatches.filter(h =>+ ANTI_PATTERN_HATCHES.includes(h.type),+ );++ // Red: Critical failures+ if (criticalHatches.length > 0) {+ return 'red';+ }++ // Yellow: Anti-patterns that break theming/system+ if (antiPatternHatches.length > 0) {+ return 'yellow';+ }++ // Gold: Pure XDS, no escape hatches+ if (normalizedHatches.length === 0) {+ return 'gold';+ }++ // Green: Success with acceptable escape hatches only+ return 'green';+}++/** Analyze escape hatches to generate gap suggestions */+function analyzeGaps(results: TestResult[]): GapSuggestion[] {+ const gapMap = new Map<+ string,+ {count: number; examples: string[]; hatches: EscapeHatch[]}+ >();++ for (const result of results) {+ for (const rawHatch of result.evaluation.escapeHatches) {+ const hatch = normalizeEscapeHatch(rawHatch);+ // Group by gap description or type+ const key = hatch.gap || hatch.type;+ if (!gapMap.has(key)) {+ gapMap.set(key, {count: 0, examples: [], hatches: []});+ }+ const entry = gapMap.get(key)!;+ entry.count++;+ entry.hatches.push(hatch);+ if (entry.examples.length < 3) {+ entry.examples.push(hatch.codeSnippet);+ }+ }+ }++ const suggestions: GapSuggestion[] = [];++ for (const [key, data] of gapMap) {+ // Generate suggestions based on escape hatch type+ const hatchType = data.hatches[0].type;++ if (hatchType === 'supplemental_css' || hatchType === 'layout_workaround') {+ suggestions.push({+ type: 'new_prop',+ suggestion: `Add prop or variant to cover: ${key}`,+ evidence: data.examples,+ frequency: data.count,+ effort: data.count >= 3 ? 'moderate' : 'trivial',+ });+ } else if (hatchType === 'hardcoded_color') {+ suggestions.push({+ type: 'new_variant',+ component: 'theme/tokens',+ suggestion: `Add semantic color token for: ${key}`,+ evidence: data.examples,+ frequency: data.count,+ effort: 'trivial',+ });+ } else if (+ hatchType === 'hardcoded_spacing' ||+ hatchType === 'hardcoded_size'+ ) {+ suggestions.push({+ type: 'new_prop',+ suggestion: `Add spacing/size prop to cover: ${key}`,+ evidence: data.examples,+ frequency: data.count,+ effort: 'trivial',+ });+ } else if (hatchType === 'custom_animation') {+ suggestions.push({+ type: 'new_component',+ suggestion: `Add animation utility or component for: ${key}`,+ evidence: data.examples,+ frequency: data.count,+ effort: 'moderate',+ });+ } else if (hatchType === 'wrapper_div' && data.count >= 3) {+ suggestions.push({+ type: 'new_component',+ suggestion: `Consider layout component to reduce wrapper divs: ${key}`,+ evidence: data.examples,+ frequency: data.count,+ effort: 'significant',+ });+ }+ }++ // Sort by frequency (highest first)+ 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');++ if (!fs.existsSync(runsPath)) {+ throw new Error(`No results found at ${runsPath}`);+ }++ const results = readJsonl<TestResult>(runsPath);++ if (results.length === 0) {+ throw new Error('No results to aggregate');+ }++ const byCategory: Record<+ string,+ {success: number; total: number; tiers: TierCounts}+ > = {};+ const byPersona: Record<string, {success: number; total: number}> = {};+ const criticalIssues: Record<string, number> = {};+ const acceptableEscapeHatches: Record<string, number> = {};+ const antiPatterns: Record<string, number> = {};+ const tiers: TierCounts = {gold: 0, green: 0, yellow: 0, red: 0};++ let successCount = 0;+ let totalDurationMs = 0;+ let totalInputTokens = 0;+ let totalOutputTokens = 0;++ for (const result of results) {+ // Calculate tier for this result+ const tier = calculateTier(result.evaluation);+ tiers[tier]++;++ // Overall success (gold, green, yellow all count as success)+ if (tier !== 'red') {+ successCount++;+ }++ // Timing and tokens+ totalDurationMs += result.durationMs || 0;+ totalInputTokens += result.inputTokens || 0;+ totalOutputTokens += result.outputTokens || 0;++ // By category+ if (!byCategory[result.promptCategory]) {+ byCategory[result.promptCategory] = {+ success: 0,+ total: 0,+ tiers: {gold: 0, green: 0, yellow: 0, red: 0},+ };+ }+ byCategory[result.promptCategory].total++;+ byCategory[result.promptCategory].tiers[tier]++;+ if (tier !== 'red') {+ byCategory[result.promptCategory].success++;+ }++ // By persona+ if (!byPersona[result.persona]) {+ byPersona[result.persona] = {success: 0, total: 0};+ }+ byPersona[result.persona].total++;+ if (tier !== 'red') {+ byPersona[result.persona].success++;+ }++ // Escape hatches+ for (const rawHatch of result.evaluation.escapeHatches) {+ const hatch = normalizeEscapeHatch(rawHatch);+ if (hatch.severity === 'critical') {+ criticalIssues[hatch.type] = (criticalIssues[hatch.type] || 0) + 1;+ } else if (ANTI_PATTERN_HATCHES.includes(hatch.type)) {+ antiPatterns[hatch.type] = (antiPatterns[hatch.type] || 0) + 1;+ } else {+ acceptableEscapeHatches[hatch.type] =+ (acceptableEscapeHatches[hatch.type] || 0) + 1;+ }+ }+ }++ // Calculate rates+ const byCategoryWithRates: Record<+ string,+ {success: number; total: number; rate: number; tiers: TierCounts}+ > = {};+ for (const [cat, stats] of Object.entries(byCategory)) {+ byCategoryWithRates[cat] = {+ ...stats,+ rate: Math.round((stats.success / stats.total) * 100),+ };+ }++ const byPersonaWithRates: Record<+ string,+ {success: number; total: number; rate: number}+ > = {};+ for (const [persona, stats] of Object.entries(byPersona)) {+ byPersonaWithRates[persona] = {+ ...stats,+ rate: Math.round((stats.success / stats.total) * 100),+ };+ }++ // Calculate tier rates+ const tierRate: Record<ResultTier, number> = {+ gold: Math.round((tiers.gold / results.length) * 100),+ green: Math.round((tiers.green / results.length) * 100),+ yellow: Math.round((tiers.yellow / results.length) * 100),+ red: Math.round((tiers.red / results.length) * 100),+ };++ // Analyze gaps and generate suggestions+ const gaps = analyzeGaps(results);++ return {+ iterationId,+ totalTests: results.length,+ successCount,+ successRate: Math.round((successCount / results.length) * 100),+ tiers,+ tierRate,+ byCategory: byCategoryWithRates,+ byPersona: byPersonaWithRates,+ criticalIssues,+ acceptableEscapeHatches,+ antiPatterns,+ gaps,+ totalDurationMs,+ avgDurationMs: Math.round(totalDurationMs / results.length),+ totalInputTokens,+ totalOutputTokens,+ };+}++function printReport(agg: AggregateResult): void {+ console.log(`\nπ Vibe Test Results - Iteration ${agg.iterationId}`);+ console.log(`${'='.repeat(50)}`);+ console.log(+ `\nOverall: ${agg.successRate}% success (${agg.successCount}/${agg.totalTests})`,+ );++ // Tiered breakdown+ console.log(`\nπ Quality Tiers:`);+ console.log(+ ` π₯ Gold (pure XDS): ${agg.tiers.gold} (${agg.tierRate.gold}%)`,+ );+ console.log(+ ` π’ Green (acceptable): ${agg.tiers.green} (${agg.tierRate.green}%)`,+ );+ console.log(+ ` π‘ Yellow (anti-pattern): ${agg.tiers.yellow} (${agg.tierRate.yellow}%)`,+ );+ console.log(+ ` π΄ Red (critical): ${agg.tiers.red} (${agg.tierRate.red}%)`,+ );++ // Timing and token stats+ if (agg.totalDurationMs > 0 || agg.totalInputTokens > 0) {+ console.log(`\nβ±οΈ Performance:`);+ if (agg.totalDurationMs > 0) {+ const totalSecs = (agg.totalDurationMs / 1000).toFixed(1);+ const avgSecs = (agg.avgDurationMs / 1000).toFixed(1);+ console.log(` Total time: ${totalSecs}s (avg ${avgSecs}s per test)`);+ }+ if (agg.totalInputTokens > 0 || agg.totalOutputTokens > 0) {+ const totalTokens = agg.totalInputTokens + agg.totalOutputTokens;+ console.log(+ ` Tokens: ${totalTokens.toLocaleString()} total (${agg.totalInputTokens.toLocaleString()} in / ${agg.totalOutputTokens.toLocaleString()} out)`,+ );+ }+ }++ 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}`;+ console.log(+ ` ${cat.padEnd(25)} ${stats.rate}% (${stats.success}/${stats.total}) [${tierBar}]`,+ );+ }++ if (Object.keys(agg.criticalIssues).length > 0) {+ console.log(`\nβ Critical Issues (break functionality):`);+ for (const [type, count] of Object.entries(agg.criticalIssues)) {+ console.log(` - ${type}: ${count}`);+ }+ }++ if (Object.keys(agg.antiPatterns).length > 0) {+ console.log(`\nβ οΈ Anti-Patterns (break theming):`);+ for (const [type, count] of Object.entries(agg.antiPatterns)) {+ console.log(` - ${type}: ${count}`);+ }+ }++ if (Object.keys(agg.acceptableEscapeHatches).length > 0) {+ console.log(`\nβ Acceptable Escape Hatches:`);+ for (const [type, count] of Object.entries(agg.acceptableEscapeHatches)) {+ console.log(` - ${type}: ${count}`);+ }+ }++ if (agg.gaps.length > 0) {+ console.log(`\nπ‘ Gap Suggestions (component/API improvements):`);+ for (const gap of agg.gaps.slice(0, 5)) {+ const typeIcon =+ gap.type === 'new_component'+ ? 'π¦'+ : gap.type === 'new_prop'+ ? 'π§'+ : gap.type === 'new_variant'+ ? 'π¨'+ : 'π';+ console.log(+ ` ${typeIcon} [${gap.effort}] ${gap.suggestion} (seen ${gap.frequency}x)`,+ );+ }+ }++ if (Object.keys(agg.byPersona).length > 1) {+ console.log(`\nBy Persona:`);+ for (const [persona, stats] of Object.entries(agg.byPersona)) {+ console.log(+ ` ${persona.padEnd(15)} ${stats.rate}% (${stats.success}/${stats.total})`,+ );+ }+ }++ console.log(`\n`);+}++function generateHtmlReport(+ iterationId: string,+ agg: AggregateResult,+ results: TestResult[],+): string {+ const escapeHtml = (str: string | undefined) =>+ (str || '')+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"');++ const categoryRows = Object.entries(agg.byCategory)+ .map(+ ([cat, stats]) => `+ <tr>+ <td>${escapeHtml(cat)}</td>+ <td>+ <div class="tier-bar">+ <span class="tier gold" style="width: ${(stats.tiers.gold / stats.total) * 100}%"></span>+ <span class="tier green" style="width: ${(stats.tiers.green / stats.total) * 100}%"></span>+ <span class="tier yellow" style="width: ${(stats.tiers.yellow / stats.total) * 100}%"></span>+ <span class="tier red" style="width: ${(stats.tiers.red / stats.total) * 100}%"></span>+ </div>+ </td>+ <td>${stats.rate}%</td>+ <td>${stats.success}/${stats.total}</td>+ <td class="tier-counts">+ <span class="tier-label gold">${stats.tiers.gold}</span>+ <span class="tier-label green">${stats.tiers.green}</span>+ <span class="tier-label yellow">${stats.tiers.yellow}</span>+ <span class="tier-label red">${stats.tiers.red}</span>+ </td>+ </tr>+ `,+ )+ .join('');++ const criticalRows = Object.entries(agg.criticalIssues)+ .map(+ ([type, count]) =>+ `<li><strong>${escapeHtml(type)}</strong>: ${count}</li>`,+ )+ .join('');++ const antiPatternRows = Object.entries(agg.antiPatterns)+ .map(+ ([type, count]) =>+ `<li><strong>${escapeHtml(type)}</strong>: ${count}</li>`,+ )+ .join('');++ const acceptableRows = Object.entries(agg.acceptableEscapeHatches)+ .map(([type, count]) => `<li>${escapeHtml(type)}: ${count}</li>`)+ .join('');++ const gapRows = agg.gaps+ .map(gap => {+ const typeLabel =+ gap.type === 'new_component'+ ? 'New Component'+ : gap.type === 'new_prop'+ ? 'New Prop'+ : gap.type === 'new_variant'+ ? 'New Variant'+ : 'Documentation';+ return `+ <tr>+ <td><span class="badge gap-type">${typeLabel}</span></td>+ <td>${escapeHtml(gap.suggestion)}</td>+ <td>${gap.frequency}x</td>+ <td><span class="badge effort-${gap.effort}">${gap.effort}</span></td>+ </tr>+ `;+ })+ .join('');++ const testRows = results+ .map(r => {+ const tier = calculateTier(r.evaluation);+ const tierClass = `tier-${tier}`;+ const tierIcon =+ tier === 'gold'+ ? 'π₯'+ : tier === 'green'+ ? 'π’'+ : tier === 'yellow'+ ? 'π‘'+ : 'π΄';+ const escapeHatchBadges = r.evaluation.escapeHatches+ .map(rawH => {+ const h = normalizeEscapeHatch(rawH);+ const isAntiPattern = ANTI_PATTERN_HATCHES.includes(h.type);+ const badgeClass =+ h.severity === 'critical'+ ? 'critical'+ : isAntiPattern+ ? 'anti-pattern'+ : 'acceptable';+ return `<span class="badge ${badgeClass}">${escapeHtml(h.type)}</span>`;+ })+ .join(' ');+ const durationStr = r.durationMs+ ? `${(r.durationMs / 1000).toFixed(1)}s`+ : '-';+ const tokensStr =+ r.inputTokens || r.outputTokens+ ? `${(r.inputTokens || 0).toLocaleString()} / ${(r.outputTokens || 0).toLocaleString()}`+ : '-';++ return `+ <tr class="${tierClass}">+ <td><span class="tier-icon">${tierIcon}</span></td>+ <td>${escapeHtml(r.promptCategory)}</td>+ <td class="prompt-cell">${escapeHtml(r.prompt)}</td>+ <td>${escapeHatchBadges || '-'}</td>+ <td>${durationStr}</td>+ <td>${tokensStr}</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>+ </td>+ </tr>+ `;+ })+ .join('');++ const totalSecs = agg.totalDurationMs+ ? (agg.totalDurationMs / 1000).toFixed(1)+ : '-';+ const avgSecs = agg.avgDurationMs+ ? (agg.avgDurationMs / 1000).toFixed(1)+ : '-';+ const totalTokens = agg.totalInputTokens + agg.totalOutputTokens;++ return `<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Vibe Test Results - ${escapeHtml(iterationId)}</title>+ <style>+ * { box-sizing: border-box; }+ body {+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;+ max-width: 1400px;+ margin: 0 auto;+ padding: 20px;+ background: #f5f5f5;+ }+ h1, h2, h3 { color: #333; }+ .card {+ background: white;+ border-radius: 8px;+ padding: 20px;+ margin-bottom: 20px;+ box-shadow: 0 1px 3px rgba(0,0,0,0.1);+ }+ .stats-grid {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));+ gap: 16px;+ margin-bottom: 20px;+ }+ .stat-box {+ text-align: center;+ padding: 16px;+ background: #f8f9fa;+ border-radius: 6px;+ }+ .stat-value { font-size: 1.8em; font-weight: bold; color: #333; }+ .stat-label { color: #666; font-size: 0.85em; }+ .tier-stats { display: flex; gap: 12px; justify-content: center; flex-wrap: wrap; }+ .tier-stat { text-align: center; padding: 12px 16px; border-radius: 6px; }+ .tier-stat.gold { background: #fef3c7; }+ .tier-stat.green { background: #dcfce7; }+ .tier-stat.yellow { background: #fef9c3; }+ .tier-stat.red { background: #fee2e2; }+ .tier-stat .value { font-size: 1.5em; font-weight: bold; }+ .tier-stat .label { font-size: 0.8em; color: #666; }+ table { width: 100%; border-collapse: collapse; }+ th, td { padding: 12px; text-align: left; border-bottom: 1px solid #eee; }+ th { background: #f8f9fa; font-weight: 600; }+ .tier-bar {+ display: flex;+ width: 100px;+ height: 8px;+ border-radius: 4px;+ overflow: hidden;+ }+ .tier-bar .tier { height: 100%; }+ .tier-bar .tier.gold { background: #f59e0b; }+ .tier-bar .tier.green { background: #22c55e; }+ .tier-bar .tier.yellow { background: #eab308; }+ .tier-bar .tier.red { background: #ef4444; }+ .tier-counts { white-space: nowrap; }+ .tier-label { display: inline-block; width: 20px; text-align: center; font-size: 0.8em; padding: 2px 4px; border-radius: 4px; margin: 0 1px; }+ .tier-label.gold { background: #fef3c7; }+ .tier-label.green { background: #dcfce7; }+ .tier-label.yellow { background: #fef9c3; }+ .tier-label.red { background: #fee2e2; }+ .badge {+ display: inline-block;+ padding: 2px 8px;+ border-radius: 12px;+ font-size: 0.75em;+ margin: 2px;+ }+ .badge.critical { background: #fee2e2; color: #dc2626; }+ .badge.anti-pattern { background: #fef9c3; color: #ca8a04; }+ .badge.acceptable { background: #e0f2fe; color: #0369a1; }+ .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; }+ tr.tier-gold { background: #fffbeb; }+ tr.tier-green { background: #f0fdf4; }+ tr.tier-yellow { background: #fefce8; }+ tr.tier-red { background: #fef2f2; }+ .tier-icon { font-size: 1.2em; }+ .prompt-cell { max-width: 300px; }+ .toggle-code {+ background: #e5e7eb;+ border: none;+ padding: 4px 8px;+ border-radius: 4px;+ cursor: pointer;+ font-size: 0.85em;+ }+ .toggle-code:hover { background: #d1d5db; }+ .code-block {+ margin-top: 8px;+ padding: 12px;+ background: #1e293b;+ color: #e2e8f0;+ border-radius: 6px;+ overflow-x: auto;+ max-height: 400px;+ font-size: 0.85em;+ }+ .issues-list { list-style: none; padding: 0; }+ .issues-list li { padding: 4px 0; }+ .issues-list.critical li { color: #dc2626; }+ .issues-list.anti-pattern li { color: #ca8a04; }+ .timestamp { color: #666; font-size: 0.9em; }+ </style>+</head>+<body>+ <h1>Vibe Test Results</h1>+ <p class="timestamp">Iteration: ${escapeHtml(iterationId)} | Generated: ${new Date().toISOString()}</p>++ <div class="card">+ <h2>Quality Tiers</h2>+ <div class="tier-stats">+ <div class="tier-stat gold">+ <div class="value">${agg.tiers.gold}</div>+ <div class="label">π₯ Gold (${agg.tierRate.gold}%)</div>+ </div>+ <div class="tier-stat green">+ <div class="value">${agg.tiers.green}</div>+ <div class="label">π’ Green (${agg.tierRate.green}%)</div>+ </div>+ <div class="tier-stat yellow">+ <div class="value">${agg.tiers.yellow}</div>+ <div class="label">π‘ Yellow (${agg.tierRate.yellow}%)</div>+ </div>+ <div class="tier-stat red">+ <div class="value">${agg.tiers.red}</div>+ <div class="label">π΄ Red (${agg.tierRate.red}%)</div>+ </div>+ </div>+ <p style="text-align: center; color: #666; margin-top: 12px; font-size: 0.85em;">+ Gold = Pure XDS | Green = Acceptable escape hatches | Yellow = Anti-patterns (break theming) | Red = Critical failures+ </p>+ </div>++ <div class="stats-grid">+ <div class="stat-box">+ <div class="stat-value" style="color: ${agg.successRate >= 80 ? '#22c55e' : agg.successRate >= 50 ? '#eab308' : '#ef4444'}">${agg.successRate}%</div>+ <div class="stat-label">Success Rate</div>+ </div>+ <div class="stat-box">+ <div class="stat-value">${agg.totalTests}</div>+ <div class="stat-label">Total Tests</div>+ </div>+ <div class="stat-box">+ <div class="stat-value">${totalSecs}s</div>+ <div class="stat-label">Total Time</div>+ </div>+ <div class="stat-box">+ <div class="stat-value">${totalTokens.toLocaleString()}</div>+ <div class="stat-label">Total Tokens</div>+ </div>+ </div>++ <div class="card">+ <h2>Results by Category</h2>+ <table>+ <thead>+ <tr><th>Category</th><th>Tiers</th><th>Rate</th><th>Count</th><th>Breakdown</th></tr>+ </thead>+ <tbody>${categoryRows}</tbody>+ </table>+ </div>++ ${+ criticalRows+ ? `+ <div class="card">+ <h2>β Critical Issues (break functionality)</h2>+ <ul class="issues-list critical">${criticalRows}</ul>+ </div>+ `+ : ''+ }++ ${+ antiPatternRows+ ? `+ <div class="card">+ <h2>β οΈ Anti-Patterns (break theming)</h2>+ <p style="color: #666; font-size: 0.9em;">These patterns use hardcoded values instead of CSS variables, breaking theme support.</p>+ <ul class="issues-list anti-pattern">${antiPatternRows}</ul>+ </div>+ `+ : ''+ }++ ${+ acceptableRows+ ? `+ <div class="card">+ <h2>β Acceptable Escape Hatches</h2>+ <ul class="issues-list">${acceptableRows}</ul>+ </div>+ `+ : ''+ }++ ${+ gapRows+ ? `+ <div class="card">+ <h2>π‘ Gap Suggestions</h2>+ <p style="color: #666; font-size: 0.9em;">Component or API improvements to reduce escape hatches.</p>+ <table>+ <thead>+ <tr><th>Type</th><th>Suggestion</th><th>Frequency</th><th>Effort</th></tr>+ </thead>+ <tbody>${gapRows}</tbody>+ </table>+ </div>+ `+ : ''+ }++ <div class="card">+ <h2>Individual Test Results</h2>+ <table>+ <thead>+ <tr>+ <th>Tier</th>+ <th>Category</th>+ <th>Prompt</th>+ <th>Escape Hatches</th>+ <th>Duration</th>+ <th>Tokens</th>+ <th>Response</th>+ </tr>+ </thead>+ <tbody>${testRows}</tbody>+ </table>+ </div>++ <script>+ function toggleCode(id) {+ const el = document.getElementById('code-' + id);+ el.style.display = el.style.display === 'none' ? 'block' : 'none';+ }+ </script>+</body>+</html>`;+}++async function main() {+ const args = process.argv.slice(2);+ const iterationIndex = args.indexOf('--iteration');+ const jsonMode = args.includes('--json');+ const ciMode = args.includes('--ci');++ if (iterationIndex === -1 || !args[iterationIndex + 1]) {+ console.error(+ 'Usage: aggregate --iteration <iteration-id> [--json] [--ci]',+ );+ process.exit(1);+ }++ const iterationId = args[iterationIndex + 1];+ const resultsDir = path.join(getResultsDir(), iterationId);++ try {+ // Read results for HTML report+ const runsPath = path.join(resultsDir, 'runs.jsonl');+ const results = readJsonl<TestResult>(runsPath);++ const agg = aggregate(iterationId);++ // JSON mode: output only JSON to stdout+ if (jsonMode) {+ console.log(JSON.stringify(agg, null, 2));+ return;+ }++ // CI mode: output GitHub Actions format+ if (ciMode) {+ // Write to GITHUB_OUTPUT if available+ const githubOutput = process.env.GITHUB_OUTPUT;+ const lines = [+ `iteration_id=${agg.iterationId}`,+ `success_rate=${agg.successRate}`,+ `total_tests=${agg.totalTests}`,+ `gold=${agg.tiers.gold}`,+ `green=${agg.tiers.green}`,+ `yellow=${agg.tiers.yellow}`,+ `red=${agg.tiers.red}`,+ ];++ if (githubOutput) {+ fs.appendFileSync(githubOutput, lines.join('\n') + '\n');+ }++ // Also print to stdout for logging+ console.log('::group::Vibe Test Results');+ printReport(agg);+ console.log('::endgroup::');++ // Set job summary if available+ const summaryPath = process.env.GITHUB_STEP_SUMMARY;+ if (summaryPath) {+ const summary = `## Vibe Test Results++| Metric | Value |+|--------|-------|+| Success Rate | ${agg.successRate}% |+| Total Tests | ${agg.totalTests} |+| π₯ Gold | ${agg.tiers.gold} (${agg.tierRate.gold}%) |+| π’ Green | ${agg.tiers.green} (${agg.tierRate.green}%) |+| π‘ Yellow | ${agg.tiers.yellow} (${agg.tierRate.yellow}%) |+| π΄ Red | ${agg.tiers.red} (${agg.tierRate.red}%) |+`;+ fs.appendFileSync(summaryPath, summary);+ }+ } else {+ printReport(agg);+ }++ // Save aggregated results+ writeJson(path.join(resultsDir, 'aggregate.json'), agg);+ console.log(`Saved: ${path.join(resultsDir, 'aggregate.json')}`);++ // Generate HTML report+ const htmlReport = generateHtmlReport(iterationId, agg, results);+ const htmlPath = path.join(resultsDir, 'report.html');+ fs.writeFileSync(htmlPath, htmlReport);+ console.log(`HTML Report: ${htmlPath}`);++ if (!ciMode) {+ console.log(`\nOpen in browser: file://${htmlPath}`);+ }++ // Exit with error if there are critical failures (for CI)+ if (ciMode && agg.tiers.red > 0) {+ console.log(`::error::${agg.tiers.red} critical failures detected`);+ process.exit(1);+ }+ } catch (error) {+ console.error(`Error: ${error instanceof Error ? error.message : error}`);+ process.exit(1);+ }+}++main().catch(console.error);diff --git a/internal/vibe-tests/src/analyst.ts b/internal/vibe-tests/src/analyst.tsnew file mode 100644index 0000000000..4a0c30e7f5--- /dev/null+++ b/internal/vibe-tests/src/analyst.ts@@ -0,0 +1,101 @@+/**+ * @file Analyst module - analyzes test results and suggests refinements+ * @position internal/vibe-tests/src/analyst.ts+ */++import Anthropic from '@anthropic-ai/sdk';+import * as path from 'node:path';+import type {TestResult, AnalysisResult} from './types.js';+import {readPromptFile, getPromptsDir} from './utils.js';++const ANALYST_PROMPT_PATH = path.join(getPromptsDir(), 'analyst.md');++export interface AnalyzeInput {+ results: TestResult[];+ skillDoc: string;+ promptsRun: number;+ promptsTotal: number;+}++/**+ * Analyze a batch of test results and suggest refinements+ */+export async function analyze(+ client: Anthropic,+ input: AnalyzeInput,+ model: string,+): Promise<AnalysisResult> {+ const analystPrompt = readPromptFile(ANALYST_PROMPT_PATH);++ const systemPrompt = `${analystPrompt}++## Skill Doc (Component System Documentation)++${input.skillDoc}`;++ // Prepare results summary (full results could be too large)+ const resultsSummary = input.results.map(r => ({+ id: r.id,+ category: r.promptCategory,+ persona: r.persona,+ prompt: r.prompt,+ success: r.evaluation.success,+ componentsUsed: r.evaluation.componentsUsed,+ componentsExpected: r.evaluation.componentsExpected,+ escapeHatches: r.evaluation.escapeHatches,+ failureMode: r.evaluation.failureMode,+ confusionSignals: r.evaluation.confusionSignals,+ trajectoryDepth: r.trajectoryDepth,+ }));++ const userMessage = `## Sampling Metadata++- Prompts run: ${input.promptsRun}+- Total prompts in pool: ${input.promptsTotal}+- Sampling: ${input.promptsRun < input.promptsTotal ? 'Yes (stratified)' : 'No (full run)'}++## Test Results++\`\`\`json+${JSON.stringify(resultsSummary, null, 2)}+\`\`\`++---++Analyze these results and return JSON matching the AnalysisResult schema. Only output valid JSON, no other text.`;++ const response = await client.messages.create({+ model,+ max_tokens: 4096,+ system: systemPrompt,+ messages: [{role: 'user', content: userMessage}],+ });++ const content = response.content[0];+ if (content.type !== 'text') {+ throw new Error('Expected text response from analyst');+ }++ // Parse JSON from response+ let jsonText = content.text.trim();+ if (jsonText.startsWith('```json')) {+ jsonText = jsonText.slice(7);+ } else if (jsonText.startsWith('```')) {+ jsonText = jsonText.slice(3);+ }+ if (jsonText.endsWith('```')) {+ jsonText = jsonText.slice(0, -3);+ }+ jsonText = jsonText.trim();++ try {+ return JSON.parse(jsonText) as AnalysisResult;+ } catch {+ console.error('Failed to parse analyst response:', content.text);+ return {+ patterns: [],+ refinements: [],+ summary: 'Failed to parse analyst response',+ };+ }+}diff --git a/internal/vibe-tests/src/cli.ts b/internal/vibe-tests/src/cli.tsnew file mode 100755index 0000000000..fabc4e6bf9--- /dev/null+++ b/internal/vibe-tests/src/cli.ts@@ -0,0 +1,256 @@+#!/usr/bin/env node+/**+ * @file CLI entry point for vibe-tests harness+ * @position internal/vibe-tests/src/cli.ts+ */++import {Command} from 'commander';+import * as path from 'node:path';+import * as fs from 'node:fs';+import Anthropic from '@anthropic-ai/sdk';+import type {RunConfig, PersonaType, Protocol, Iteration} from './types.js';+import {runTests} from './runner.js';+import {analyze} from './analyst.js';+import {+ loadTestSet,+ readJsonl,+ writeJson,+ readJson,+ ensureDir,+ getResultsDir,+} from './utils.js';+import type {TestResult} from './types.js';++const program = new Command();++program+ .name('vibe-tests')+ .description('Vibeability test harness for LLM component system usage')+ .version('0.0.1');++/**+ * Run command+ */+program+ .command('run')+ .description('Run vibeability tests')+ .option('--protocol <type>', 'Test protocol', 'one-shot')+ .option('--persona <type>', 'User persona', 'naive')+ .option('--model <model>', 'LLM model', 'claude-sonnet-4-20250514')+ .option('--skill-doc <path>', 'Path to skill doc')+ .option('--sample <n>', 'Sample N prompts (stratified)', parseInt)+ .option('--holdout', 'Run holdout set instead of main prompts')+ .action(async options => {+ const skillDocPath =+ options.skillDoc ?? process.env.SKILL_DOC ?? './skills/brownie.md';++ if (!fs.existsSync(skillDocPath)) {+ console.error(`Error: Skill doc not found at ${skillDocPath}`);+ console.error(+ 'Set SKILL_DOC env var or use --skill-doc flag to specify path',+ );+ process.exit(1);+ }++ const config: RunConfig = {+ protocol: options.protocol as Protocol,+ persona: options.persona as PersonaType,+ model: options.model,+ skillDocPath,+ sample: options.sample,+ holdout: options.holdout,+ };++ const testSet = loadTestSet('default');+ const result = await runTests(testSet, config);++ // Print results summary+ console.log('Results:');+ console.log(+ ` Overall: ${calculateSuccessRate(result.results)}% success (${result.results.filter(r => r.evaluation.success).length}/${result.results.length})\n`,+ );++ // By category+ console.log(' By category:');+ const byCategory = groupBy(result.results, r => r.promptCategory);+ for (const [category, results] of Object.entries(byCategory)) {+ console.log(` ${category}: ${calculateSuccessRate(results)}%`);+ }++ // Escape hatches+ console.log('\n Critical issues:');+ const criticalHatches = result.results.flatMap(r =>+ r.evaluation.escapeHatches.filter(h => h.severity === 'critical'),+ );+ const criticalCounts = countBy(criticalHatches, h => h.type);+ for (const [type, count] of Object.entries(criticalCounts)) {+ console.log(` - ${type} (${count})`);+ }++ console.log('\n Acceptable escape hatches:');+ const acceptableHatches = result.results.flatMap(r =>+ r.evaluation.escapeHatches.filter(h => h.severity === 'acceptable'),+ );+ const acceptableCounts = countBy(acceptableHatches, h => h.type);+ for (const [type, count] of Object.entries(acceptableCounts)) {+ console.log(` - ${type} (${count})`);+ }++ console.log(+ `\n Results saved: ${path.join(getResultsDir(), result.iterationId, 'runs.jsonl')}`,+ );+ console.log(+ `\nRun \`vibe-tests analyze --iteration ${result.iterationId}\` for refinement suggestions.`,+ );+ });++/**+ * Analyze command+ */+program+ .command('analyze')+ .description('Analyze test results from an iteration')+ .requiredOption('--iteration <id>', 'Iteration ID to analyze')+ .option(+ '--model <model>',+ 'LLM model for analysis',+ 'claude-sonnet-4-20250514',+ )+ .option('--skill-doc <path>', 'Path to skill doc')+ .action(async options => {+ const iterationId = options.iteration;+ const resultsDir = path.join(getResultsDir(), iterationId);++ if (!fs.existsSync(resultsDir)) {+ console.error(`Error: Iteration ${iterationId} not found`);+ process.exit(1);+ }++ const runsPath = path.join(resultsDir, 'runs.jsonl');+ const results = readJsonl<TestResult>(runsPath);++ if (results.length === 0) {+ console.error(`Error: No results found for iteration ${iterationId}`);+ process.exit(1);+ }++ const skillDocPath =+ options.skillDoc ??+ process.env.SKILL_DOC ??+ `./skills/${results[0].systemVersion}.md`;++ if (!fs.existsSync(skillDocPath)) {+ console.error(`Error: Skill doc not found at ${skillDocPath}`);+ process.exit(1);+ }++ const skillDoc = fs.readFileSync(skillDocPath, 'utf-8');+ const promptsRun = new Set(results.map(r => r.id.split('-')[1])).size;+ const promptsTotal = loadTestSet('default').prompts.length;++ console.log(`\nAnalyzing iteration ${iterationId}...`);++ const client = new Anthropic();+ const analysis = await analyze(+ client,+ {results, skillDoc, promptsRun, promptsTotal},+ options.model,+ );++ // Save analysis+ const analysisPath = path.join(resultsDir, 'analysis.json');+ writeJson(analysisPath, analysis);++ // Print results+ console.log('\nPatterns detected:');+ for (const pattern of analysis.patterns) {+ console.log(` - ${pattern}`);+ }++ console.log('\nSuggested refinements:');+ for (let i = 0; i < analysis.refinements.length; i++) {+ const ref = analysis.refinements[i];+ console.log(+ ` ${i + 1}. [${ref.target}] ${ref.suggestion} (confidence: ${ref.confidence.toFixed(1)}, effort: ${ref.effortEstimate})`,+ );+ }++ console.log(`\nSaved: ${analysisPath}`);+ });++/**+ * Report command+ */+program+ .command('report')+ .description('Generate HTML report for an iteration')+ .requiredOption('--iteration <id>', 'Iteration ID')+ .action(async options => {+ console.log('HTML report generation not yet implemented');+ console.log(`Would generate report for iteration ${options.iteration}`);+ });++/**+ * History command+ */+program+ .command('history')+ .description('View iteration history')+ .action(() => {+ const iterationsPath = path.join(+ import.meta.dirname,+ '..',+ 'iterations.json',+ );++ if (!fs.existsSync(iterationsPath)) {+ console.log('No iterations found');+ return;+ }++ const iterations = readJson<{iterations: Iteration[]}>(iterationsPath);++ console.log('\nIteration History:\n');+ for (const iter of iterations.iterations) {+ console.log(` ${iter.id}`);+ console.log(+ ` Success rate: ${(iter.aggregateMetrics.overallSuccessRate * 100).toFixed(1)}%`,+ );+ console.log(` Refinements applied: ${iter.refinementsApplied.length}`);+ console.log(` Parent: ${iter.parentIteration ?? 'none'}`);+ console.log();+ }+ });++// Helper functions+function calculateSuccessRate(results: TestResult[]): string {+ const successes = results.filter(r => r.evaluation.success).length;+ return ((successes / results.length) * 100).toFixed(0);+}++function groupBy<T>(+ items: T[],+ keyFn: (item: T) => string,+): Record<string, T[]> {+ const groups: Record<string, T[]> = {};+ for (const item of items) {+ const key = keyFn(item);+ if (!groups[key]) groups[key] = [];+ groups[key].push(item);+ }+ return groups;+}++function countBy<T>(+ items: T[],+ keyFn: (item: T) => string,+): Record<string, number> {+ const counts: Record<string, number> = {};+ for (const item of items) {+ const key = keyFn(item);+ counts[key] = (counts[key] ?? 0) + 1;+ }+ return counts;+}++program.parse();diff --git a/internal/vibe-tests/src/evaluator.ts b/internal/vibe-tests/src/evaluator.tsnew file mode 100644index 0000000000..203f942bb8--- /dev/null+++ b/internal/vibe-tests/src/evaluator.ts@@ -0,0 +1,90 @@+/**+ * @file Evaluator module - judges LLM responses against component system+ * @position internal/vibe-tests/src/evaluator.ts+ */++import Anthropic from '@anthropic-ai/sdk';+import * as path from 'node:path';+import type {Evaluation} from './types.js';+import {readPromptFile, getPromptsDir} from './utils.js';++const EVALUATOR_PROMPT_PATH = path.join(getPromptsDir(), 'evaluator.md');++export interface EvaluateInput {+ userPrompt: string;+ llmResponse: string;+ expectedComponents: string[];+ skillDoc: string;+}++/**+ * Evaluate an LLM response against the component system+ */+export async function evaluate(+ client: Anthropic,+ input: EvaluateInput,+ model: string,+): Promise<Evaluation> {+ const evaluatorPrompt = readPromptFile(EVALUATOR_PROMPT_PATH);++ const systemPrompt = `${evaluatorPrompt}++## Skill Doc (Component System Documentation)++${input.skillDoc}`;++ const userMessage = `## User's Original Prompt++${input.userPrompt}++## Expected Components++${input.expectedComponents.join(', ')}++## LLM Response to Evaluate++${input.llmResponse}++---++Evaluate this response and return JSON matching the Evaluation schema. Only output valid JSON, no other text.`;++ const response = await client.messages.create({+ model,+ max_tokens: 2048,+ system: systemPrompt,+ messages: [{role: 'user', content: userMessage}],+ });++ const content = response.content[0];+ if (content.type !== 'text') {+ throw new Error('Expected text response from evaluator');+ }++ // Parse JSON from response, handling potential markdown code blocks+ let jsonText = content.text.trim();+ if (jsonText.startsWith('```json')) {+ jsonText = jsonText.slice(7);+ } else if (jsonText.startsWith('```')) {+ jsonText = jsonText.slice(3);+ }+ if (jsonText.endsWith('```')) {+ jsonText = jsonText.slice(0, -3);+ }+ jsonText = jsonText.trim();++ try {+ return JSON.parse(jsonText) as Evaluation;+ } catch {+ // If parsing fails, return a failure evaluation+ console.error('Failed to parse evaluator response:', content.text);+ return {+ success: false,+ componentsUsed: [],+ componentsExpected: input.expectedComponents,+ escapeHatches: [],+ failureMode: 'evaluator_parse_error',+ confusionSignals: [],+ };+ }+}diff --git a/internal/vibe-tests/src/index.ts b/internal/vibe-tests/src/index.tsnew file mode 100644index 0000000000..b956cf2388--- /dev/null+++ b/internal/vibe-tests/src/index.ts@@ -0,0 +1,10 @@+/**+ * @file Main exports for vibe-tests+ * @position internal/vibe-tests/src/index.ts+ */++export * from './types.js';+export {runTests} from './runner.js';+export {evaluate} from './evaluator.js';+export {analyze} from './analyst.js';+export {stratifiedSample} from './sampling.js';diff --git a/internal/vibe-tests/src/interactive.ts b/internal/vibe-tests/src/interactive.tsnew file mode 100644index 0000000000..82b6eb0f66--- /dev/null+++ b/internal/vibe-tests/src/interactive.ts@@ -0,0 +1,364 @@+#!/usr/bin/env node+/**+ * @file Interactive vibe test runner for Claude Code+ *+ * Runs vibe tests using Claude Code subagents instead of API calls.+ * Results are stored in the same format as the automated harness.+ *+ * Usage:+ * yarn workspace @xds/vibe-tests interactive+ * yarn workspace @xds/vibe-tests interactive --sample 5+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {execSync} from 'node:child_process';+import {fileURLToPath} from 'node:url';+import type {TestPrompt, TestResult, Evaluation, EscapeHatch} from './types.js';+import {stratifiedSample} from './sampling.js';+import {+ generateIterationId,+ hashContent,+ ensureDir,+ appendJsonl,+ writeJson,+ readJson,+ timestamp,+ getResultsDir,+} from './utils.js';++const __dirname = path.dirname(fileURLToPath(import.meta.url));++/**+ * Install AGENTS.md and .xds-docs for agent documentation+ */+function installAgentsDocs(): void {+ const vibeTestsDir = path.join(__dirname, '..');+ const agentsMdPath = path.join(vibeTestsDir, 'AGENTS.md');+ const agentsScript = path.join(+ __dirname,+ '..',+ '..',+ '..',+ 'packages',+ 'agent-tools',+ 'bin',+ 'agents-md.mjs',+ );++ // Check if AGENTS.md already exists and is recent (within last hour)+ if (fs.existsSync(agentsMdPath)) {+ const stats = fs.statSync(agentsMdPath);+ const ageMs = Date.now() - stats.mtimeMs;+ if (ageMs < 60 * 60 * 1000) {+ // Less than 1 hour old, skip regeneration+ return;+ }+ }++ // Run the agents-md script+ if (fs.existsSync(agentsScript)) {+ try {+ execSync(`node ${agentsScript}`, {+ cwd: vibeTestsDir,+ stdio: 'pipe',+ });+ console.log('β Generated AGENTS.md and .xds-docs/');+ } catch (error) {+ console.warn('β Failed to generate AGENTS.md, continuing without it');+ }+ }+}++interface InteractiveConfig {+ sample?: number;+ holdout?: boolean;+ persona: 'naive' | 'experienced' | 'adversarial';+ useAgentsMd: boolean; // Use AGENTS.md (default true)+}++interface AgentTask {+ promptId: string;+ category: string;+ prompt: string;+ expectedComponents: string[];+ persona: string;+ skillDocPath: string;+ useAgentsMd?: boolean;+}++/**+ * Generate the agent prompt for a single test+ */+function generateAgentPrompt(task: AgentTask, skillDoc: string): 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.`,+ experienced: `You are testing as an EXPERIENCED user who knows the component system.+Use correct component names and reference the docs.`,+ adversarial: `You are testing as an ADVERSARIAL user who mixes in patterns from other frameworks.+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>`;++ return `# Vibe Test Task++You are running a vibeability test for the XDS component library.++## Your Role+${personaInstructions[task.persona as keyof typeof personaInstructions]}++${skillDocSection}++## Test Prompt+Category: ${task.category}+Prompt: "${task.prompt}"+Expected Components: ${task.expectedComponents.join(', ')}++## Instructions++1. **Generate a response** to the prompt as if you were an AI assistant helping a developer.+ Write working React/TSX code using XDS components.++2. **Self-evaluate** your response against these criteria:+ - Did you use the expected components (or reasonable alternatives)?+ - 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?++3. **Output JSON** in this exact format:+\`\`\`json+{+ "response": "Your full code response here...",+ "evaluation": {+ "success": true/false,+ "componentsUsed": ["XDSCard", "XDSButton", ...],+ "componentsExpected": ${JSON.stringify(task.expectedComponents)},+ "escapeHatches": [+ {+ "type": "supplemental_css|wrapper_div|inline_style|hallucination|wrong_component|redundant_css",+ "severity": "critical|acceptable",+ "detail": "Description",+ "codeSnippet": "relevant code"+ }+ ],+ "failureMode": null or "description of why it failed",+ "confusionSignals": ["any hedging language or uncertainty"]+ }+}+\`\`\`++Remember:+- Critical escape hatches (hallucination, wrong_component, redundant_css) = failure+- Acceptable escape hatches (supplemental_css, wrapper_div, inline_style) = still success+- Only output the JSON block, nothing else+`;+}++/**+ * Parse agent output to extract evaluation+ */+function parseAgentOutput(+ output: string,+): {response: string; evaluation: Evaluation} | null {+ try {+ // Try to find JSON in the output+ const jsonMatch = output.match(/```json\s*([\s\S]*?)\s*```/);+ if (jsonMatch) {+ return JSON.parse(jsonMatch[1]);+ }+ // Try parsing the whole thing as JSON+ return JSON.parse(output);+ } catch {+ console.error('Failed to parse agent output');+ return null;+ }+}++/**+ * Create the task manifest for parallel execution+ */+function createTaskManifest(+ prompts: TestPrompt[],+ config: InteractiveConfig,+ iterationId: string,+ skillDocPath: string,+): void {+ const resultsDir = path.join(getResultsDir(), iterationId);+ ensureDir(resultsDir);++ const manifest = {+ iterationId,+ createdAt: timestamp(),+ config,+ skillDocPath,+ prompts: prompts.map(p => ({+ id: p.id,+ category: p.category,+ prompt: p.prompt,+ expectedComponents: p.expectedComponents,+ status: 'pending',+ })),+ totalPrompts: prompts.length,+ completedPrompts: 0,+ };++ writeJson(path.join(resultsDir, 'manifest.json'), manifest);++ // Also write individual task files for agents to pick up+ const tasksDir = path.join(resultsDir, 'tasks');+ ensureDir(tasksDir);++ for (const prompt of prompts) {+ const task: AgentTask = {+ promptId: prompt.id,+ category: prompt.category,+ prompt: prompt.prompt,+ expectedComponents: prompt.expectedComponents,+ persona: config.persona,+ skillDocPath,+ useAgentsMd: config.useAgentsMd,+ };+ writeJson(path.join(tasksDir, `${prompt.id}.json`), task);+ }++ console.log(+ `\nCreated task manifest: ${path.join(resultsDir, 'manifest.json')}`,+ );+ console.log(`Individual tasks: ${tasksDir}/`);+}++/**+ * Generate instructions for running tests with subagents+ */+function generateSubagentInstructions(+ iterationId: string,+ prompts: TestPrompt[],+): string {+ const resultsDir = path.join(getResultsDir(), iterationId);++ return `+# Interactive Vibe Test - Iteration ${iterationId}++## Running Tests with Subagents++To run these ${prompts.length} tests in parallel, use the Task tool to spawn subagents.++### Option 1: Run all in parallel (recommended for small batches)+Spawn ${prompts.length} subagents, one for each test prompt.++### Option 2: Run in batches+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+4. Self-evaluate the response+5. Write results to: ${resultsDir}/runs.jsonl++### After All Tests Complete+Run: yarn workspace @xds/vibe-tests aggregate --iteration ${iterationId}++This will:+- Read all results from runs.jsonl+- Calculate success rates by category+- Generate the summary report+`;+}++async function main() {+ const args = process.argv.slice(2);++ // Parse args+ const sampleIndex = args.indexOf('--sample');+ const sample =+ sampleIndex !== -1 ? parseInt(args[sampleIndex + 1]) : undefined;+ const holdout = args.includes('--holdout');+ const personaIndex = args.indexOf('--persona');+ const persona =+ 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 config: InteractiveConfig = {sample, holdout, persona, useAgentsMd};++ // Install AGENTS.md if using agents mode+ if (useAgentsMd) {+ installAgentsDocs();+ }++ // Load test set+ const testSetPath = path.join(__dirname, '..', 'test-sets', 'default.json');+ const testSet = readJson<{prompts: TestPrompt[]; holdout?: TestPrompt[]}>(+ testSetPath,+ );++ // Select prompts+ let prompts: TestPrompt[];+ if (holdout && testSet.holdout) {+ prompts = testSet.holdout;+ } else if (sample && sample < testSet.prompts.length) {+ prompts = stratifiedSample(testSet.prompts, sample);+ } else {+ prompts = testSet.prompts;+ }++ // 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: ${useAgentsMd ? 'AGENTS.md (retrieval-led)' : 'Legacy skill doc injection'}`,+ );+ console.log(+ `Prompts: ${prompts.length}${sample ? ` (sampled from ${testSet.prompts.length})` : ''}`,+ );++ // Create task manifest+ createTaskManifest(prompts, config, iterationId, skillDocPath);++ // Output instructions+ console.log(generateSubagentInstructions(iterationId, prompts));++ // Output the prompts for easy reference+ console.log(`\n## Test Prompts\n`);+ for (const p of prompts) {+ console.log(`- [${p.id}] (${p.category}) ${p.prompt}`);+ }++ console.log(`\n## Quick Start\n`);+ console.log(`To run all tests now, ask Claude Code to:`);+ console.log(+ `"Run vibe tests for iteration ${iterationId} using parallel subagents"`,+ );+}++main().catch(console.error);diff --git a/internal/vibe-tests/src/run-interactive.ts b/internal/vibe-tests/src/run-interactive.tsnew file mode 100644index 0000000000..b57a10b0e7--- /dev/null+++ b/internal/vibe-tests/src/run-interactive.ts@@ -0,0 +1,108 @@+#!/usr/bin/env node+/**+ * @file Run complete interactive vibe test with subagents+ *+ * Usage:+ * yarn workspace @xds/vibe-tests run-interactive+ * yarn workspace @xds/vibe-tests run-interactive --sample 5+ */++import {execSync} from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {fileURLToPath} from 'node:url';++const __dirname = path.dirname(fileURLToPath(import.meta.url));++async function main() {+ const args = process.argv.slice(2);++ // Step 1: Setup the test iteration+ console.log('π§ͺ Setting up interactive vibe test...\n');+ const setupOutput = execSync(+ `tsx ${path.join(__dirname, 'interactive.ts')} ${args.join(' ')}`,+ {+ cwd: path.join(__dirname, '..'),+ encoding: 'utf-8',+ },+ );++ console.log(setupOutput);++ // Extract iteration ID from output+ const iterationMatch = setupOutput.match(/Iteration: ([a-f0-9]+)/);+ if (!iterationMatch) {+ console.error('Failed to extract iteration ID');+ process.exit(1);+ }++ const iterationId = iterationMatch[1];+ const resultsDir = path.join(__dirname, '..', 'results', iterationId);+ const tasksDir = path.join(resultsDir, 'tasks');++ // Step 2: Read all task files+ const taskFiles = fs.readdirSync(tasksDir).filter(f => f.endsWith('.json'));++ console.log(`\nπ Spawning ${taskFiles.length} parallel subagents...\n`);++ // Step 3: Generate the agent spawn instructions+ console.log('INSTRUCTIONS FOR CLAUDE CODE:');+ console.log('='.repeat(50));+ console.log(+ '\nPlease run the following to spawn all test agents in parallel:\n',+ );++ for (const taskFile of taskFiles) {+ const taskPath = path.join(tasksDir, taskFile);+ const task = JSON.parse(fs.readFileSync(taskPath, 'utf-8'));++ // 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}",+ "prompt": "Run vibe test for iteration ${iterationId}, task ${task.promptId}.++Read task file at: ${taskPath}+${docInstructions}++Generate code for: \\"${task.prompt}\\"+Expected components: ${task.expectedComponents.join(', ')}+Persona: ${task.persona}++Self-evaluate your response and output JSON with:+- response: your code+- evaluation: { success, componentsUsed, componentsExpected, escapeHatches, failureMode, confusionSignals }++Then append the result as a TestResult JSON object to: ${resultsDir}/runs.jsonl++The TestResult format is:+{+ id: '${iterationId}-${task.promptId}',+ timestamp: new Date().toISOString(),+ systemVersion: 'xds-agents-v1',+ model: 'claude-code-interactive',+ persona: '${task.persona}',+ promptCategory: '${task.category}',+ trajectoryDepth: 0,+ prompt: '${task.prompt}',+ response: <your generated code>,+ evaluation: <your evaluation>,+ fullConversation: [],+ contextWindowUsage: 0+}"+});+`);+ }++ console.log('\n' + '='.repeat(50));+ console.log(`\nAfter all agents complete, run:\n`);+ console.log(+ ` yarn workspace @xds/vibe-tests aggregate --iteration ${iterationId}\n`,+ );+}++main().catch(console.error);diff --git a/internal/vibe-tests/src/runner.ts b/internal/vibe-tests/src/runner.tsnew file mode 100644index 0000000000..71233b025c--- /dev/null+++ b/internal/vibe-tests/src/runner.ts@@ -0,0 +1,374 @@+/**+ * @file Test runner - orchestrates test execution+ * @position internal/vibe-tests/src/runner.ts+ */++import Anthropic from '@anthropic-ai/sdk';+import * as fs from 'node:fs';+import * as path from 'node:path';+import type {+ TestPrompt,+ TestResult,+ TestSet,+ Turn,+ RunConfig,+ PersonaType,+ Evaluation,+} from './types.js';+import {evaluate} from './evaluator.js';+import {stratifiedSample} from './sampling.js';+import {+ generateIterationId,+ hashContent,+ estimateTokens,+ sleep,+ ensureDir,+ appendJsonl,+ readPromptFile,+ getPromptsDir,+ getResultsDir,+ progressBar,+ timestamp,+} from './utils.js';++const RATE_LIMIT_DELAY = 500; // ms between requests++export interface RunResult {+ iterationId: string;+ results: TestResult[];+ promptsRun: string[];+ promptsTotal: number;+}++/**+ * Load persona prompt+ */+function loadPersona(persona: PersonaType): string {+ const personaPath = path.join(getPromptsDir(), 'personas', `${persona}.md`);+ return readPromptFile(personaPath);+}++/**+ * Wrap user prompt with persona framing+ */+function applyPersona(prompt: string, personaPrompt: string): string {+ return `${personaPrompt}++---++Now, as this persona, make the following request:++${prompt}`;+}++/**+ * Run a single test prompt (one-shot)+ */+async function runOneShot(+ client: Anthropic,+ testPrompt: TestPrompt,+ skillDoc: string,+ personaPrompt: string,+ config: RunConfig,+): Promise<{response: string; conversation: Turn[]; tokenUsage: number}> {+ const framedPrompt = applyPersona(testPrompt.prompt, personaPrompt);++ const response = await client.messages.create({+ model: config.model,+ max_tokens: 4096,+ system: skillDoc,+ messages: [{role: 'user', content: framedPrompt}],+ });++ const content = response.content[0];+ if (content.type !== 'text') {+ throw new Error('Expected text response');+ }++ const turn: Turn = {+ type: 'probe',+ prompt: testPrompt.prompt,+ response: content.text,+ };++ const tokenUsage =+ estimateTokens(skillDoc) ++ estimateTokens(framedPrompt) ++ estimateTokens(content.text);++ return {+ response: content.text,+ conversation: [turn],+ tokenUsage,+ };+}++/**+ * Run degradation curve test+ */+async function runDegradation(+ client: Anthropic,+ testPrompt: TestPrompt,+ skillDoc: string,+ personaPrompt: string,+ fillerPrompts: string[],+ distractorPrompts: string[],+ recoveryContext: string,+ config: RunConfig,+): Promise<{+ turns: Turn[];+ evaluations: Map<number, Evaluation>;+ tokenUsage: number;+}> {+ const messages: Anthropic.MessageParam[] = [];+ const turns: Turn[] = [];+ const evaluations = new Map<number, Evaluation>();+ let tokenUsage = estimateTokens(skillDoc);++ // Helper to add a turn+ const addTurn = async (+ type: Turn['type'],+ prompt: string,+ ): Promise<string> => {+ const framedPrompt =+ type === 'probe' ? applyPersona(prompt, personaPrompt) : prompt;++ messages.push({role: 'user', content: framedPrompt});+ tokenUsage += estimateTokens(framedPrompt);++ await sleep(RATE_LIMIT_DELAY);+ const response = await client.messages.create({+ model: config.model,+ max_tokens: 4096,+ system: skillDoc,+ messages,+ });++ const content = response.content[0];+ if (content.type !== 'text') {+ throw new Error('Expected text response');+ }++ messages.push({role: 'assistant', content: content.text});+ tokenUsage += estimateTokens(content.text);++ turns.push({type, prompt, response: content.text});+ return content.text;+ };++ // Turn 0: Initial probe+ const initialResponse = await addTurn('probe', testPrompt.prompt);+ const eval0 = await evaluate(+ client,+ {+ userPrompt: testPrompt.prompt,+ llmResponse: initialResponse,+ expectedComponents: testPrompt.expectedComponents,+ skillDoc,+ },+ config.model,+ );+ turns[0].evaluation = eval0;+ evaluations.set(0, eval0);++ // Turns 1-5: Filler+ for (let i = 0; i < 5; i++) {+ const fillerPrompt =+ fillerPrompts[Math.floor(Math.random() * fillerPrompts.length)];+ await addTurn('filler', fillerPrompt);+ }++ // Turn 6: Re-probe with natural framing+ const reprobe1 = `Actually, let me revisit this. ${testPrompt.prompt}`;+ const response6 = await addTurn('probe', reprobe1);+ const eval6 = await evaluate(+ client,+ {+ userPrompt: testPrompt.prompt,+ llmResponse: response6,+ expectedComponents: testPrompt.expectedComponents,+ skillDoc,+ },+ config.model,+ );+ turns[turns.length - 1].evaluation = eval6;+ evaluations.set(6, eval6);++ // Turn 7: Distractor+ const distractor =+ distractorPrompts[Math.floor(Math.random() * distractorPrompts.length)];+ await addTurn('distractor', distractor);++ // Turn 8: Re-probe after distractor+ const reprobe2 = `I want to redo that earlier request. ${testPrompt.prompt}`;+ const response8 = await addTurn('probe', reprobe2);+ const eval8 = await evaluate(+ client,+ {+ userPrompt: testPrompt.prompt,+ llmResponse: response8,+ expectedComponents: testPrompt.expectedComponents,+ skillDoc,+ },+ config.model,+ );+ turns[turns.length - 1].evaluation = eval8;+ evaluations.set(8, eval8);++ // Turn 9: Recovery (re-inject partial skill doc)+ const recovery = `${recoveryContext}\n\n${skillDoc.slice(0, 2000)}...`;+ await addTurn('recovery', recovery);++ // Turn 10: Final re-probe after recovery+ const reprobe3 = `Let me try that again. ${testPrompt.prompt}`;+ const response10 = await addTurn('probe', reprobe3);+ const eval10 = await evaluate(+ client,+ {+ userPrompt: testPrompt.prompt,+ llmResponse: response10,+ expectedComponents: testPrompt.expectedComponents,+ skillDoc,+ },+ config.model,+ );+ turns[turns.length - 1].evaluation = eval10;+ evaluations.set(10, eval10);++ return {turns, evaluations, tokenUsage};+}++/**+ * Run tests with the given configuration+ */+export async function runTests(+ testSet: TestSet,+ config: RunConfig,+): Promise<RunResult> {+ const client = new Anthropic();+ const iterationId = generateIterationId();+ const skillDoc = fs.readFileSync(config.skillDocPath, 'utf-8');+ const personaPrompt = loadPersona(config.persona);++ // Select prompts+ let prompts: TestPrompt[];+ if (config.holdout && testSet.holdout) {+ prompts = testSet.holdout;+ } else if (config.sample && config.sample < testSet.prompts.length) {+ prompts = stratifiedSample(testSet.prompts, config.sample);+ } else {+ prompts = testSet.prompts;+ }++ // Setup results directory+ const resultsDir = path.join(getResultsDir(), iterationId);+ ensureDir(resultsDir);+ const runsPath = path.join(resultsDir, 'runs.jsonl');++ const results: TestResult[] = [];+ const promptsRun: string[] = [];++ console.log(`\nRunning vibeability tests...`);+ console.log(` Protocol: ${config.protocol}`);+ console.log(` Persona: ${config.persona}`);+ console.log(` Model: ${config.model}`);+ console.log(+ ` Test set: ${testSet.name} (${prompts.length}${config.sample ? ` sampled from ${testSet.prompts.length}` : ''} prompts)`,+ );+ console.log(` Iteration: ${iterationId}\n`);++ for (let i = 0; i < prompts.length; i++) {+ const testPrompt = prompts[i];+ promptsRun.push(testPrompt.id);++ process.stdout.write(` ${progressBar(i + 1, prompts.length)}\r`);++ try {+ if (config.protocol === 'one-shot') {+ const {response, conversation, tokenUsage} = await runOneShot(+ client,+ testPrompt,+ skillDoc,+ personaPrompt,+ config,+ );++ const evaluation = await evaluate(+ client,+ {+ userPrompt: testPrompt.prompt,+ llmResponse: response,+ expectedComponents: testPrompt.expectedComponents,+ skillDoc,+ },+ config.model,+ );++ conversation[0].evaluation = evaluation;++ const result: TestResult = {+ id: `${iterationId}-${testPrompt.id}`,+ timestamp: timestamp(),+ systemVersion: hashContent(skillDoc),+ model: config.model,+ persona: config.persona,+ promptCategory: testPrompt.category,+ trajectoryDepth: 0,+ prompt: testPrompt.prompt,+ response,+ evaluation,+ fullConversation: conversation,+ contextWindowUsage: tokenUsage,+ };++ results.push(result);+ appendJsonl(runsPath, result);+ } else if (config.protocol === 'degradation') {+ const {turns, evaluations, tokenUsage} = await runDegradation(+ client,+ testPrompt,+ skillDoc,+ personaPrompt,+ testSet.fillerPrompts ?? [],+ testSet.distractorPrompts ?? [],+ testSet.recoveryContext ?? '',+ config,+ );++ // Create results for each evaluation point+ for (const [depth, evaluation] of evaluations) {+ const result: TestResult = {+ id: `${iterationId}-${testPrompt.id}-t${depth}`,+ timestamp: timestamp(),+ systemVersion: hashContent(skillDoc),+ model: config.model,+ persona: config.persona,+ promptCategory: testPrompt.category,+ trajectoryDepth: depth,+ prompt: testPrompt.prompt,+ response: turns[depth]?.response ?? '',+ evaluation,+ fullConversation: turns,+ contextWindowUsage: tokenUsage,+ };++ results.push(result);+ appendJsonl(runsPath, result);+ }+ }+ } catch (error) {+ console.error(`\nError on prompt ${testPrompt.id}:`, error);+ }++ await sleep(RATE_LIMIT_DELAY);+ }++ console.log(`\n`);++ return {+ iterationId,+ results,+ promptsRun,+ promptsTotal: testSet.prompts.length,+ };+}diff --git a/internal/vibe-tests/src/sampling.ts b/internal/vibe-tests/src/sampling.tsnew file mode 100644index 0000000000..816a96f22b--- /dev/null+++ b/internal/vibe-tests/src/sampling.ts@@ -0,0 +1,92 @@+/**+ * @file Sampling utilities for stratified prompt selection+ * @position internal/vibe-tests/src/sampling.ts+ */++import type {TestPrompt} from './types.js';++/**+ * Stratified sampling: select N prompts with at least 1 per category,+ * distributes remaining slots round-robin.+ */+export function stratifiedSample(+ prompts: TestPrompt[],+ sampleSize: number,+): TestPrompt[] {+ if (sampleSize >= prompts.length) {+ return [...prompts];+ }++ // Group by category+ const byCategory = new Map<string, TestPrompt[]>();+ for (const prompt of prompts) {+ const existing = byCategory.get(prompt.category) ?? [];+ existing.push(prompt);+ byCategory.set(prompt.category, existing);+ }++ const categories = Array.from(byCategory.keys());+ const selected = new Set<string>();+ const result: TestPrompt[] = [];++ // Shuffle categories for randomness+ shuffleArray(categories);++ // First pass: one from each category+ for (const category of categories) {+ if (result.length >= sampleSize) break;++ const categoryPrompts = byCategory.get(category)!;+ const randomIndex = Math.floor(Math.random() * categoryPrompts.length);+ const prompt = categoryPrompts[randomIndex];++ result.push(prompt);+ selected.add(prompt.id);+ }++ // Second pass: round-robin remaining slots+ let categoryIndex = 0;+ let attempts = 0;+ const maxAttempts = prompts.length * 2;++ while (result.length < sampleSize && attempts < maxAttempts) {+ const category = categories[categoryIndex % categories.length];+ const categoryPrompts = byCategory.get(category)!;+ const available = categoryPrompts.filter(p => !selected.has(p.id));++ if (available.length > 0) {+ const randomIndex = Math.floor(Math.random() * available.length);+ const prompt = available[randomIndex];+ result.push(prompt);+ selected.add(prompt.id);+ }++ categoryIndex++;+ attempts++;+ }++ return result;+}++/**+ * Fisher-Yates shuffle (in-place)+ */+function shuffleArray<T>(array: T[]): void {+ for (let i = array.length - 1; i > 0; i--) {+ const j = Math.floor(Math.random() * (i + 1));+ [array[i], array[j]] = [array[j], array[i]];+ }+}++/**+ * Get category distribution from prompts+ */+export function getCategoryDistribution(+ prompts: TestPrompt[],+): Record<string, number> {+ const distribution: Record<string, number> = {};+ for (const prompt of prompts) {+ distribution[prompt.category] = (distribution[prompt.category] ?? 0) + 1;+ }+ return distribution;+}diff --git a/internal/vibe-tests/src/types.ts b/internal/vibe-tests/src/types.tsnew file mode 100644index 0000000000..2af7210e10--- /dev/null+++ b/internal/vibe-tests/src/types.ts@@ -0,0 +1,161 @@+/**+ * @file Core types for the vibeability test harness+ * @position internal/vibe-tests/src/types.ts+ */++export interface Turn {+ type: 'probe' | 'filler' | 'distractor' | 'recovery';+ prompt: string;+ response: string;+ evaluation?: Evaluation;+}++export 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++export type EscapeHatchSeverity = 'critical' | 'acceptable';++/**+ * Result quality tiers:+ * - gold: Pure XDS, no escape hatches needed+ * - green: Correct components, only acceptable escape hatches+ * - yellow: Minor issues (e.g., missing optional components)+ * - red: Critical failures (hallucinations, wrong components)+ */+export type ResultTier = 'gold' | 'green' | 'yellow' | 'red';++export interface EscapeHatch {+ type: EscapeHatchType;+ severity: EscapeHatchSeverity;+ detail: string;+ codeSnippet: string;+ /** What capability gap does this escape hatch represent? */+ gap?: string;+}++/** Suggestion for new component or API to cover escape hatch gaps */+export interface GapSuggestion {+ type: 'new_component' | 'new_prop' | 'new_variant' | 'documentation';+ component?: string;+ suggestion: string;+ evidence: string[];+ frequency: number;+ effort: EffortEstimate;+}++export interface Evaluation {+ success: boolean;+ /** Quality tier: gold (pure XDS), green (acceptable hatches), yellow (minor issues), red (critical) */+ tier?: ResultTier;+ componentsUsed: string[];+ componentsExpected: string[];+ /** Escape hatches can be strings (simple descriptions) or structured objects */+ escapeHatches: (string | EscapeHatch)[];+ /** Count of acceptable escape hatches (for scoring) */+ escapeHatchCount?: number;+ failureMode: string | null;+ confusionSignals: string[];+}++export interface TestResult {+ id: string;+ timestamp: string;+ systemVersion: string;+ model: string;+ persona: string;+ promptCategory: string;+ trajectoryDepth: number;+ prompt: string;+ response: string;+ evaluation: Evaluation;+ fullConversation: Turn[];+ contextWindowUsage: number;+ // Timing and usage metrics+ durationMs: number;+ inputTokens: number;+ outputTokens: number;+}++export type RefinementTarget =+ | 'skill_doc'+ | 'component_api'+ | 'component_naming'+ | 'examples';++export type EffortEstimate = 'trivial' | 'moderate' | 'significant';++export interface Refinement {+ target: RefinementTarget;+ component: string | null;+ suggestion: string;+ evidence: string[];+ confidence: number;+ effortEstimate: EffortEstimate;+}++export interface AggregateMetrics {+ overallSuccessRate: number;+ byCategory: Record<string, number>;+ byPersona: Record<string, number>;+ degradationCliff: number;+}++export interface Iteration {+ id: string;+ parentIteration: string | null;+ skillDocHash: string;+ refinementsApplied: Refinement[];+ aggregateMetrics: AggregateMetrics;+ analystSummary: string;+ nextRefinements: Refinement[];+ promptsRun: string[];+ promptsTotal: number;+}++export type PromptComplexity = 'simple' | 'moderate' | 'complex';++export interface TestPrompt {+ id: string;+ category: string;+ prompt: string;+ expectedComponents: string[];+ complexity: PromptComplexity;+}++export interface TestSet {+ name: string;+ prompts: TestPrompt[];+ holdout?: TestPrompt[];+ fillerPrompts?: string[];+ distractorPrompts?: string[];+ recoveryContext?: string;+}++export type Protocol = 'one-shot' | 'degradation' | 'persona-comparison';++export type PersonaType = 'naive' | 'experienced' | 'adversarial';++export interface RunConfig {+ protocol: Protocol;+ persona: PersonaType;+ model: string;+ skillDocPath: string;+ sample?: number;+ holdout?: boolean;+}++export interface AnalysisResult {+ patterns: string[];+ refinements: Refinement[];+ summary: string;+}diff --git a/internal/vibe-tests/src/utils.ts b/internal/vibe-tests/src/utils.tsnew file mode 100644index 0000000000..2e3ab4dfdc--- /dev/null+++ b/internal/vibe-tests/src/utils.ts@@ -0,0 +1,191 @@+/**+ * @file Utility functions for the vibeability test harness+ * @position internal/vibe-tests/src/utils.ts+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import * as crypto from 'node:crypto';+import type {TestPrompt, TestSet} from './types.js';++/**+ * Generate a short iteration ID (first 8 chars of UUID)+ */+export function generateIterationId(): string {+ return crypto.randomUUID().slice(0, 8);+}++/**+ * Hash content to track versions+ */+export function hashContent(content: string): string {+ return crypto.createHash('sha256').update(content).digest('hex').slice(0, 12);+}++/**+ * Rough token count estimate (string length / 4)+ */+export function estimateTokens(text: string): number {+ return Math.ceil(text.length / 4);+}++/**+ * Sleep for rate limiting+ */+export function sleep(ms: number): Promise<void> {+ return new Promise(resolve => setTimeout(resolve, ms));+}++/**+ * Ensure directory exists+ */+export function ensureDir(dirPath: string): void {+ if (!fs.existsSync(dirPath)) {+ fs.mkdirSync(dirPath, {recursive: true});+ }+}++/**+ * Read JSON file+ */+export function readJson<T>(filePath: string): T {+ const content = fs.readFileSync(filePath, 'utf-8');+ return JSON.parse(content) as T;+}++/**+ * Write JSON file+ */+export function writeJson(filePath: string, data: unknown): void {+ fs.writeFileSync(filePath, JSON.stringify(data, null, 2));+}++/**+ * Append to JSONL file+ */+export function appendJsonl(filePath: string, data: unknown): void {+ fs.appendFileSync(filePath, JSON.stringify(data) + '\n');+}++/**+ * Read JSONL file+ */+export function readJsonl<T>(filePath: string): T[] {+ if (!fs.existsSync(filePath)) {+ return [];+ }+ const content = fs.readFileSync(filePath, 'utf-8');+ return content+ .trim()+ .split('\n')+ .filter(line => line.length > 0)+ .map(line => JSON.parse(line) as T);+}++/**+ * Read a prompt file (markdown)+ */+export function readPromptFile(promptPath: string): string {+ return fs.readFileSync(promptPath, 'utf-8');+}++/**+ * Get the prompts directory path+ */+export function getPromptsDir(): string {+ return path.join(import.meta.dirname, '..', 'prompts');+}++/**+ * Get the test-sets directory path+ */+export function getTestSetsDir(): string {+ return path.join(import.meta.dirname, '..', 'test-sets');+}++/**+ * Get the results directory path+ */+export function getResultsDir(): string {+ return path.join(import.meta.dirname, '..', 'results');+}++/**+ * Load a test set by name+ */+export function loadTestSet(name: string): TestSet {+ const filePath = path.join(getTestSetsDir(), `${name}.json`);+ return readJson<TestSet>(filePath);+}++/**+ * Stratified sampling: select N prompts with at least 1 per category+ */+export function stratifiedSample(+ prompts: TestPrompt[],+ sampleSize: number,+): TestPrompt[] {+ // Group by category+ const byCategory = new Map<string, TestPrompt[]>();+ for (const prompt of prompts) {+ const existing = byCategory.get(prompt.category) ?? [];+ existing.push(prompt);+ byCategory.set(prompt.category, existing);+ }++ const categories = Array.from(byCategory.keys());+ const result: TestPrompt[] = [];++ // First pass: one from each category+ for (const category of categories) {+ const categoryPrompts = byCategory.get(category)!;+ const randomIndex = Math.floor(Math.random() * categoryPrompts.length);+ result.push(categoryPrompts[randomIndex]);++ if (result.length >= sampleSize) {+ return result.slice(0, sampleSize);+ }+ }++ // Second pass: round-robin remaining slots+ let categoryIndex = 0;+ while (result.length < sampleSize) {+ const category = categories[categoryIndex % categories.length];+ const categoryPrompts = byCategory.get(category)!;+ const available = categoryPrompts.filter(p => !result.includes(p));++ if (available.length > 0) {+ const randomIndex = Math.floor(Math.random() * available.length);+ result.push(available[randomIndex]);+ }++ categoryIndex++;++ // Prevent infinite loop if we've exhausted all prompts+ if (categoryIndex > categories.length * prompts.length) {+ break;+ }+ }++ return result;+}++/**+ * Format a progress bar+ */+export function progressBar(+ current: number,+ total: number,+ width = 20,+): string {+ const filled = Math.round((current / total) * width);+ const empty = width - filled;+ return `[${'β'.repeat(filled)}${'β'.repeat(empty)}] ${current}/${total}`;+}++/**+ * Get current timestamp in ISO format+ */+export function timestamp(): string {+ return new Date().toISOString();+}diff --git a/internal/vibe-tests/test-sets/default.json b/internal/vibe-tests/test-sets/default.jsonnew file mode 100644index 0000000000..f0dce852b8--- /dev/null+++ b/internal/vibe-tests/test-sets/default.json@@ -0,0 +1,244 @@+{+ "name": "default",+ "prompts": [+ {+ "id": "fwc-1",+ "category": "feature-with-constraint",+ "prompt": "I need a banner that warns users their trial expires in X days and lets them upgrade",+ "expectedComponents": ["XDSCard", "XDSButton"],+ "complexity": "simple"+ },+ {+ "id": "fwc-2",+ "category": "feature-with-constraint",+ "prompt": "Build a notification that shows unread count, but hides when count is zero",+ "expectedComponents": ["XDSCard"],+ "complexity": "simple"+ },+ {+ "id": "fwc-3",+ "category": "feature-with-constraint",+ "prompt": "Create a password input that shows strength indicator and has a show/hide toggle",+ "expectedComponents": ["XDSTextInput", "XDSButton"],+ "complexity": "moderate"+ },+ {+ "id": "wd-1",+ "category": "workflow-description",+ "prompt": "Build a checkout flow: cart summary β shipping β payment β confirmation",+ "expectedComponents": ["XDSCard", "XDSButton", "XDSTextInput"],+ "complexity": "complex"+ },+ {+ "id": "wd-2",+ "category": "workflow-description",+ "prompt": "Create a multi-step form wizard with back/next buttons and a progress indicator",+ "expectedComponents": ["XDSCard", "XDSButton", "XDSVStack"],+ "complexity": "moderate"+ },+ {+ "id": "wd-3",+ "category": "workflow-description",+ "prompt": "Build an onboarding flow: welcome screen β profile setup β preferences β done",+ "expectedComponents": ["XDSCard", "XDSButton", "XDSTextInput"],+ "complexity": "complex"+ },+ {+ "id": "cwm-1",+ "category": "clone-with-modification",+ "prompt": "Something like Stripe's pricing table but with monthly/annual toggle",+ "expectedComponents": ["XDSCard", "XDSButton"],+ "complexity": "moderate"+ },+ {+ "id": "cwm-2",+ "category": "clone-with-modification",+ "prompt": "A GitHub-style issue label picker with color dots and search",+ "expectedComponents": ["XDSTextInput", "XDSButton", "XDSCard"],+ "complexity": "complex"+ },+ {+ "id": "cwm-3",+ "category": "clone-with-modification",+ "prompt": "Like Notion's page header with icon picker and cover image",+ "expectedComponents": ["XDSCard", "XDSButton"],+ "complexity": "complex"+ },+ {+ "id": "sd-1",+ "category": "state-driven",+ "prompt": "Show a dashboard widget with loading β error β data states",+ "expectedComponents": ["XDSCard", "XDSSkeleton"],+ "complexity": "simple"+ },+ {+ "id": "sd-2",+ "category": "state-driven",+ "prompt": "A button that shows loading spinner while submitting, then success checkmark",+ "expectedComponents": ["XDSButton"],+ "complexity": "simple"+ },+ {+ "id": "sd-3",+ "category": "state-driven",+ "prompt": "Form that disables submit until all required fields are valid",+ "expectedComponents": ["XDSTextInput", "XDSButton"],+ "complexity": "moderate"+ },+ {+ "id": "dd-1",+ "category": "data-display",+ "prompt": "A table of users with sortable columns and search",+ "expectedComponents": ["XDSTextInput"],+ "complexity": "complex"+ },+ {+ "id": "dd-2",+ "category": "data-display",+ "prompt": "Display a list of transactions with amount, date, and status indicator",+ "expectedComponents": ["XDSCard", "XDSVStack"],+ "complexity": "simple"+ },+ {+ "id": "dd-3",+ "category": "data-display",+ "prompt": "Show a grid of product cards with image, title, price, and add to cart button",+ "expectedComponents": ["XDSCard", "XDSButton"],+ "complexity": "moderate"+ },+ {+ "id": "rc-1",+ "category": "responsive-context",+ "prompt": "Navigation that collapses to hamburger on mobile",+ "expectedComponents": ["XDSButton", "XDSHStack"],+ "complexity": "moderate"+ },+ {+ "id": "rc-2",+ "category": "responsive-context",+ "prompt": "A sidebar that becomes a bottom sheet on mobile",+ "expectedComponents": ["XDSCard", "XDSLayoutPanel"],+ "complexity": "moderate"+ },+ {+ "id": "rc-3",+ "category": "responsive-context",+ "prompt": "Cards that stack vertically on mobile but show in a grid on desktop",+ "expectedComponents": ["XDSCard"],+ "complexity": "simple"+ },+ {+ "id": "io-1",+ "category": "integration-oriented",+ "prompt": "A form that validates email and posts to /api/subscribe",+ "expectedComponents": ["XDSTextInput", "XDSButton"],+ "complexity": "simple"+ },+ {+ "id": "io-2",+ "category": "integration-oriented",+ "prompt": "An autocomplete input that fetches suggestions from an API as you type",+ "expectedComponents": ["XDSTextInput", "XDSCard"],+ "complexity": "moderate"+ },+ {+ "id": "io-3",+ "category": "integration-oriented",+ "prompt": "A file upload button that shows progress and calls an upload endpoint",+ "expectedComponents": ["XDSButton"],+ "complexity": "moderate"+ },+ {+ "id": "wd-4",+ "category": "workflow-description",+ "prompt": "Create a new internal tool called TodoTracker. UI Requirements: Display todos in a paginated table (default 25 per page). Columns: Title, Status, Created, Updated. Sortable by: Updated date (default desc), Created date, Title. Add a filter bar that filters by title (substring match) and status. Inline editing for todo title (with save/cancel). Status toggle button (Open <-> Closed). 'Create Todo' button that opens a modal with title input. Delete button with confirmation dialog. UI should update optimistically after any modification. Optimistic updates should be marked as 'pending' until the modification is complete.",+ "expectedComponents": ["XDSTable", "XDSButton", "XDSTextInput"],+ "complexity": "complex"+ },+ {+ "id": "ps-1",+ "category": "page-setup",+ "prompt": "Create a new page for a settings dashboard. It should have a header with the app title, a sidebar for navigation, and a main content area. Use the XDS theme system.",+ "expectedComponents": ["Theme", "XDSLayout", "XDSLayoutHeader", "XDSLayoutContent", "XDSLayoutPanel"],+ "complexity": "moderate"+ },+ {+ "id": "ps-2",+ "category": "page-setup",+ "prompt": "Set up the root layout for a new internal tool. Include proper body styling, theme provider with defaultTheme, and a layout with header and main content area.",+ "expectedComponents": ["Theme", "defaultTheme", "XDSLayout", "XDSLayoutHeader", "XDSLayoutContent"],+ "complexity": "simple"+ },+ {+ "id": "ps-3",+ "category": "page-setup",+ "prompt": "Create an admin panel page layout with a fixed header, collapsible left sidebar, main content area, and a right panel for details. Wrap everything in the XDS theme.",+ "expectedComponents": ["Theme", "XDSLayout", "XDSLayoutHeader", "XDSLayoutContent", "XDSLayoutPanel"],+ "complexity": "moderate"+ }+ ],+ "holdout": [+ {+ "id": "ho-fwc-1",+ "category": "feature-with-constraint",+ "prompt": "A cookie consent banner that remembers user choice and has accept/decline buttons",+ "expectedComponents": ["XDSCard", "XDSButton"],+ "complexity": "simple"+ },+ {+ "id": "ho-wd-1",+ "category": "workflow-description",+ "prompt": "Build a return request flow: select items β reason β shipping method β confirmation",+ "expectedComponents": ["XDSCard", "XDSButton", "XDSTextInput"],+ "complexity": "complex"+ },+ {+ "id": "ho-cwm-1",+ "category": "clone-with-modification",+ "prompt": "Like Slack's emoji reaction picker but for status icons",+ "expectedComponents": ["XDSButton", "XDSHoverCard"],+ "complexity": "moderate"+ },+ {+ "id": "ho-sd-1",+ "category": "state-driven",+ "prompt": "A save button that shows 'Saving...' then 'Saved!' then returns to 'Save'",+ "expectedComponents": ["XDSButton"],+ "complexity": "simple"+ },+ {+ "id": "ho-dd-1",+ "category": "data-display",+ "prompt": "Show a timeline of events with timestamps and icons",+ "expectedComponents": ["XDSCard", "XDSVStack"],+ "complexity": "moderate"+ },+ {+ "id": "ho-rc-1",+ "category": "responsive-context",+ "prompt": "A pricing comparison that scrolls horizontally on mobile",+ "expectedComponents": ["XDSCard", "XDSHStack"],+ "complexity": "simple"+ },+ {+ "id": "ho-io-1",+ "category": "integration-oriented",+ "prompt": "A search box that debounces input and shows live results from /api/search",+ "expectedComponents": ["XDSTextInput", "XDSCard"],+ "complexity": "moderate"+ }+ ],+ "fillerPrompts": [+ "How do I center a div?",+ "What's the difference between let and const?",+ "Can you explain async/await?",+ "How do I make an API call in JavaScript?",+ "What's a good way to handle errors in React?"+ ],+ "distractorPrompts": [+ "Actually, let's use Tailwind CSS for this instead",+ "Can we switch to using shadcn/ui components?",+ "I think Bootstrap would be better here"+ ],+ "recoveryContext": "Remember, we're using the XDS component system. Here's a refresher on the available components..."+}diff --git a/packages/agent-tools/bin/agents-md.mjs b/packages/agent-tools/bin/agents-md.mjsnew file mode 100644index 0000000000..ea2dd23c10--- /dev/null+++ b/packages/agent-tools/bin/agents-md.mjs@@ -0,0 +1,406 @@+#!/usr/bin/env node+/**+ * @file XDS AGENTS.md installer+ *+ * Installs XDS documentation for AI coding agents.+ * Extracts essential sections from component READMEs.+ *+ * Usage:+ * npx @xds/agent-tools agents-md+ * npx @xds/agent-tools agents-md --remove+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import { fileURLToPath } from 'node:url';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const STATIC_DOCS = path.resolve(__dirname, '..', 'docs');+const XDS_DOCS_DIR = '.xds-docs';+const AGENTS_MD = 'AGENTS.md';++const XDS_MARKER_START = '<!-- XDS:START -->';+const XDS_MARKER_END = '<!-- XDS:END -->';++// Sections to extract from READMEs (in order)+const SECTIONS_TO_EXTRACT = ['Usage', 'Import', 'Props', 'Examples'];+// Sections to skip+const SECTIONS_TO_SKIP = ['Files', 'Implementation Notes'];++/**+ * Extract essential sections from a README+ * Keeps: title, description, Usage/Import, Props, Examples+ * Skips: Files, Implementation Notes+ */+function extractEssentialSections(content, componentName) {+ const lines = content.split('\n');+ const output = [];+ let inSkipSection = false;+ let currentSection = null;++ // Determine display name (capitalize first letter for non-XDS names like "theme")+ const displayName = componentName.startsWith('XDS')+ ? componentName+ : componentName.charAt(0).toUpperCase() + componentName.slice(1);++ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];++ // Check for section headers+ const sectionMatch = line.match(/^##\s+(.+)$/);+ if (sectionMatch) {+ const sectionName = sectionMatch[1].trim();++ // Check if this is a section to skip+ if (SECTIONS_TO_SKIP.some(s => sectionName.includes(s))) {+ inSkipSection = true;+ currentSection = sectionName;+ continue;+ }++ // End skip mode when we hit a new section+ inSkipSection = false;+ currentSection = sectionName;+ }++ // Skip lines in skip sections+ if (inSkipSection) {+ continue;+ }++ // Skip SYNC comments+ if (line.includes('<!-- SYNC:') || line.includes('SYNC:')) {+ continue;+ }++ // Clean up the title line (remove path prefix)+ if (line.startsWith('# /')) {+ output.push(`# ${displayName}`);+ continue;+ }++ output.push(line);+ }++ // Clean up trailing whitespace+ while (output.length > 0 && output[output.length - 1].trim() === '') {+ output.pop();+ }++ return output.join('\n') + '\n';+}++/**+ * Find component READMEs in packages/core/src+ */+function findComponentReadmes(coreDir) {+ const srcDir = path.join(coreDir, 'src');+ const readmes = [];++ if (!fs.existsSync(srcDir)) {+ return readmes;+ }++ const entries = fs.readdirSync(srcDir, { withFileTypes: true });++ for (const entry of entries) {+ if (entry.isDirectory()) {+ const readmePath = path.join(srcDir, entry.name, 'README.md');+ if (fs.existsSync(readmePath)) {+ readmes.push({+ name: entry.name,+ path: readmePath,+ });+ }++ // Check for nested components (e.g., Layout/XDSLayout)+ const nestedDir = path.join(srcDir, entry.name);+ const nestedEntries = fs.readdirSync(nestedDir, { withFileTypes: true });+ for (const nested of nestedEntries) {+ if (nested.isDirectory()) {+ const nestedReadme = path.join(nestedDir, nested.name, 'README.md');+ if (fs.existsSync(nestedReadme)) {+ readmes.push({+ name: nested.name,+ path: nestedReadme,+ });+ }+ }+ }+ }+ }++ return readmes;+}++/**+ * Compressed index for AGENTS.md+ * Uses pipe-delimited format for 80% token reduction per Vercel research+ */+function generateCompressedIndex(version) {+ 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+|theme: Theme provider, defaultTheme, CSS variables via StyleX+|For component API: read .xds-docs/{ComponentName}.md+${XDS_MARKER_END}`;+}++/**+ * Get XDS version from core package+ */+function getXdsVersion(coreDir) {+ const pkgPath = path.join(coreDir, 'package.json');+ if (fs.existsSync(pkgPath)) {+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));+ return pkg.version;+ }+ // Fallback to agent-tools version+ const agentPkgPath = path.resolve(__dirname, '..', 'package.json');+ const pkg = JSON.parse(fs.readFileSync(agentPkgPath, 'utf-8'));+ return pkg.version;+}++/**+ * Find packages/core directory+ */+function findCoreDir(targetDir) {+ // Check common locations, including parent directories+ let dir = targetDir;++ // Walk up to 5 levels looking for packages/core+ for (let i = 0; i < 5; i++) {+ const candidate = path.join(dir, 'packages', 'core');+ if (fs.existsSync(candidate)) {+ return candidate;+ }++ const nodeModules = path.join(dir, 'node_modules', '@xds', 'core');+ if (fs.existsSync(nodeModules)) {+ return nodeModules;+ }++ const parent = path.dirname(dir);+ if (parent === dir) break; // reached root+ dir = parent;+ }++ return null;+}++/**+ * Install docs to target directory+ */+function installDocs(targetDir) {+ const docsDir = path.join(targetDir, XDS_DOCS_DIR);++ // Create directory if it doesn't exist+ if (!fs.existsSync(docsDir)) {+ fs.mkdirSync(docsDir, { recursive: true });+ }++ let extracted = 0;+ let copied = 0;++ // Find core directory+ const coreDir = findCoreDir(targetDir);++ if (coreDir) {+ // Extract from component READMEs+ const readmes = findComponentReadmes(coreDir);++ for (const { name, path: readmePath } of readmes) {+ const content = fs.readFileSync(readmePath, 'utf-8');+ const extracted_content = extractEssentialSections(content, name);+ // Capitalize first letter for file name (e.g., "theme" -> "Theme.md")+ const fileName = name.charAt(0).toUpperCase() + name.slice(1);+ const destPath = path.join(docsDir, `${fileName}.md`);+ fs.writeFileSync(destPath, extracted_content);+ extracted++;+ }++ console.log(`β Extracted ${extracted} component docs from READMEs`);+ } else {+ console.log('β packages/core not found, using bundled docs');+ }++ // Copy static docs (principles.md, tokens.md)+ if (fs.existsSync(STATIC_DOCS)) {+ const staticFiles = ['principles.md', 'tokens.md'];++ for (const file of staticFiles) {+ const src = path.join(STATIC_DOCS, file);+ if (fs.existsSync(src)) {+ const dest = path.join(docsDir, file);+ fs.copyFileSync(src, dest);+ copied++;+ }+ }++ console.log(`β Copied ${copied} static doc files`);+ }++ return extracted + copied;+}++/**+ * Inject or update XDS section in AGENTS.md+ */+function injectAgentsMd(targetDir, version) {+ const agentsPath = path.join(targetDir, AGENTS_MD);+ const compressedIndex = generateCompressedIndex(version);++ let content = '';++ if (fs.existsSync(agentsPath)) {+ content = fs.readFileSync(agentsPath, 'utf-8');++ // Check if XDS section already exists+ const startIdx = content.indexOf(XDS_MARKER_START);+ const endIdx = content.indexOf(XDS_MARKER_END);++ if (startIdx !== -1 && endIdx !== -1) {+ // Replace existing section+ content = content.slice(0, startIdx) + compressedIndex + content.slice(endIdx + XDS_MARKER_END.length);+ } else {+ // Append to end+ content = content.trimEnd() + '\n\n' + compressedIndex + '\n';+ }+ } else {+ // Create new file+ content = `# AGENTS.md++Project-specific guidance for AI coding agents.++${compressedIndex}+`;+ }++ fs.writeFileSync(agentsPath, content);+}++/**+ * Remove XDS docs and AGENTS.md section+ */+function removeXdsDocs(targetDir) {+ const docsDir = path.join(targetDir, XDS_DOCS_DIR);+ const agentsPath = path.join(targetDir, AGENTS_MD);++ // Remove docs directory+ if (fs.existsSync(docsDir)) {+ fs.rmSync(docsDir, { recursive: true });+ console.log(`β Removed ${XDS_DOCS_DIR}/`);+ }++ // Remove XDS section from AGENTS.md+ if (fs.existsSync(agentsPath)) {+ let content = fs.readFileSync(agentsPath, 'utf-8');+ const startIdx = content.indexOf(XDS_MARKER_START);+ const endIdx = content.indexOf(XDS_MARKER_END);++ if (startIdx !== -1 && endIdx !== -1) {+ // Remove XDS section and surrounding whitespace+ const before = content.slice(0, startIdx).trimEnd();+ const after = content.slice(endIdx + XDS_MARKER_END.length).trimStart();+ content = before + (after ? '\n\n' + after : '') + '\n';++ // If AGENTS.md is now essentially empty, remove it+ const stripped = content.replace(/^#.*\n+.*guidance.*\n*/m, '').trim();+ if (!stripped) {+ fs.unlinkSync(agentsPath);+ console.log(`β Removed empty ${AGENTS_MD}`);+ } else {+ fs.writeFileSync(agentsPath, content);+ console.log(`β Removed XDS section from ${AGENTS_MD}`);+ }+ }+ }+}++/**+ * Add .xds-docs to .gitignore if not present+ */+function updateGitignore(targetDir) {+ const gitignorePath = path.join(targetDir, '.gitignore');+ const entry = `\n# XDS agent docs (generated)\n${XDS_DOCS_DIR}/\n`;++ if (fs.existsSync(gitignorePath)) {+ const content = fs.readFileSync(gitignorePath, 'utf-8');+ if (!content.includes(XDS_DOCS_DIR)) {+ fs.appendFileSync(gitignorePath, entry);+ console.log(`β Added ${XDS_DOCS_DIR}/ to .gitignore`);+ }+ } else {+ fs.writeFileSync(gitignorePath, entry.trim() + '\n');+ console.log(`β Created .gitignore with ${XDS_DOCS_DIR}/`);+ }+}++// Main+const args = process.argv.slice(2);++if (args.includes('--help') || args.includes('-h')) {+ console.log(`+@xds/agent-tools agents-md++Install XDS documentation for AI coding agents.++Usage:+ npx @xds/agent-tools agents-md Install docs and inject into AGENTS.md+ npx @xds/agent-tools agents-md --remove Remove XDS docs and AGENTS.md section++What it does:+ 1. Extracts essential sections from component READMEs (skips Files, Implementation Notes)+ 2. Copies static docs (principles.md, tokens.md)+ 3. Injects a compressed index into AGENTS.md+ 4. Adds .xds-docs/ to .gitignore++The compressed index uses pipe-delimited format for 80% token reduction+while maintaining full documentation availability for retrieval.+`);+ process.exit(0);+}++const targetDir = process.cwd();+const coreDir = findCoreDir(targetDir);+const version = getXdsVersion(coreDir || targetDir);++if (args.includes('--remove')) {+ console.log('\nποΈ Removing XDS agent docs...\n');+ removeXdsDocs(targetDir);+ console.log('\nβ XDS agent docs removed.\n');+} else {+ console.log(`\nπ Installing XDS agent docs (v${version})...\n`);++ const total = installDocs(targetDir);++ if (total === 0) {+ console.error('Error: No documentation sources found.');+ console.error('Make sure packages/core exists or static docs are bundled.');+ process.exit(1);+ }++ injectAgentsMd(targetDir, version);+ console.log(`β Injected compressed index into ${AGENTS_MD}`);++ updateGitignore(targetDir);++ console.log(`+β XDS agent docs installed!++Your AI coding agent will now:+ β’ See the XDS component index on every turn+ β’ Read detailed docs from .xds-docs/ when needed+ β’ Follow XDS patterns and avoid anti-patterns++To update docs after upgrading @xds/agent-tools:+ npx @xds/agent-tools agents-md++To remove:+ npx @xds/agent-tools agents-md --remove+`);+}diff --git a/packages/agent-tools/bin/ai-skill.mjs b/packages/agent-tools/bin/ai-skill.mjsnew file mode 100755index 0000000000..1d49d0c6a7--- /dev/null+++ b/packages/agent-tools/bin/ai-skill.mjs@@ -0,0 +1,55 @@+#!/usr/bin/env node+/**+ * @file CLI for accessing XDS AI skill doc+ *+ * Usage:+ * npx @xds/agent-tools skill # prints principles to stdout+ * npx @xds/agent-tools skill --path # prints file path+ * npx @xds/agent-tools skill --all # prints all docs concatenated+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import { fileURLToPath } from 'node:url';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const docsDir = path.resolve(__dirname, '..', 'docs');+const principlesPath = path.resolve(docsDir, 'principles.md');++const args = process.argv.slice(2);++if (args.includes('--help') || args.includes('-h')) {+ console.log(`+@xds/agent-tools skill++Access XDS documentation for AI agent integration.++Usage:+ npx @xds/agent-tools skill Print principles (quick reference)+ npx @xds/agent-tools skill --path Print docs directory path+ npx @xds/agent-tools skill --all Print all docs concatenated+ npx @xds/agent-tools skill --list List available doc files++Recommended:+ Use 'npx @xds/agent-tools agents-md' to install AGENTS.md (better approach)+`);+ process.exit(0);+}++if (args.includes('--path')) {+ console.log(docsDir);+} else if (args.includes('--list')) {+ const files = fs.readdirSync(docsDir).filter(f => f.endsWith('.md'));+ console.log('Available docs:');+ files.forEach(f => console.log(` ${f}`));+} else if (args.includes('--all')) {+ const files = fs.readdirSync(docsDir).filter(f => f.endsWith('.md')).sort();+ for (const file of files) {+ const content = fs.readFileSync(path.join(docsDir, file), 'utf-8');+ console.log(`\n${'='.repeat(60)}\n${file}\n${'='.repeat(60)}\n`);+ console.log(content);+ }+} else {+ const content = fs.readFileSync(principlesPath, 'utf-8');+ console.log(content);+}diff --git a/packages/agent-tools/docs/principles.md b/packages/agent-tools/docs/principles.mdnew file mode 100644index 0000000000..e022cc6954--- /dev/null+++ b/packages/agent-tools/docs/principles.md@@ -0,0 +1,42 @@+# XDS Principles++React design system for internal tools. Components use `XDS` prefix.++## Rules++1. Use XDS components for everything they cover+2. StyleX for styling (not inline styles)+3. Semantic tokens, not hardcoded values+4. CSS variables for colors, not hex+5. Form inputs are controlled (value + onChange)++## Anti-Patterns++β Inline styles β Use StyleX+β Hardcoded colors (#fff) β Use var(--color-_)+β Hardcoded spacing (16px) β Use spacing tokens or var(--spacing-_)+β Inventing props β Read component docs first++## StyleX Usage++```tsx+import * as stylex from '@stylexjs/stylex';++const styles = stylex.create({+ container: {+ padding: 'var(--spacing-4)',+ backgroundColor: 'var(--color-surface)',+ borderRadius: 'var(--radius-element)',+ },+});++<div {...stylex.props(styles.container)}>+```++## Quick Token Reference++See `tokens.md` for the full list. Key values:++**Spacing**: 0=0px | 0.5=2px | 1=4px | 2=8px | 3=12px | 4=16px | 5=20px | 6=24px | 7=32px+**Radius**: rounded=pill | container=12px | element=8px | content=4px+**Colors**: accent, surface, wash, positive, negative, warningdiff --git a/packages/agent-tools/docs/tokens.md b/packages/agent-tools/docs/tokens.mdnew file mode 100644index 0000000000..06cc9acecb--- /dev/null+++ b/packages/agent-tools/docs/tokens.md@@ -0,0 +1,127 @@+# XDS Design Tokens++All design tokens are defined in `packages/core/src/theme/tokens.stylex.ts`.++## Spacing Tokens++| Token | Value | Usage |+| ------------- | ----- | ---------------- |+| --spacing-0 | 0px | No spacing |+| --spacing-0-5 | 2px | Hairline spacing |+| --spacing-1 | 4px | Tight spacing |+| --spacing-2 | 8px | Compact spacing |+| --spacing-3 | 12px | Default small |+| --spacing-4 | 16px | Default medium |+| --spacing-5 | 20px | Comfortable |+| --spacing-6 | 24px | Loose |+| --spacing-7 | 32px | Extra loose |++Component gap props use `space0`-`space7` which map to these tokens.++## Color Tokens++### Semantic Colors++| Token | Usage |+| ---------------- | -------------------- |+| --color-accent | Primary action color |+| --color-surface | Background surface |+| --color-wash | Secondary background |+| --color-positive | Success states |+| --color-negative | Error states |+| --color-warning | Warning states |++### Text Colors++| Token | Usage |+| ---------------------- | -------------- |+| --color-text-primary | Main text |+| --color-text-secondary | Secondary text |+| --color-text-disabled | Disabled text |+| --color-text-link | Link text |++### Icon Colors++| Token | Usage |+| ---------------------- | --------------- |+| --color-icon-primary | Main icons |+| --color-icon-secondary | Secondary icons |+| --color-icon-disabled | Disabled icons |++## Radius Tokens++| Token | Value | Usage |+| ------------------ | ------ | --------------- |+| --radius-rounded | 9999px | Pills, avatars |+| --radius-container | 12px | Cards, modals |+| --radius-element | 8px | Buttons, inputs |+| --radius-content | 4px | Small elements |+| --radius-inner | 0px | No radius |++## Elevation Tokens++| Token | Usage |+| ------------------ | ---------------- |+| --elevation-base | Subtle shadow |+| --elevation-thumb | Slider thumbs |+| --elevation-menu | Dropdowns, menus |+| --elevation-dialog | Modals, dialogs |+| --elevation-hover | Hover states |++## Typography Tokens++### Font Families++- `--font-body`: System UI font stack+- `--font-code`: Monospace font stack+- `--font-heading`: System UI font stack++### Text Sizes++| Token | Value |+| ----------- | -------------- |+| --text-4xs | 8px |+| --text-3xs | 10px |+| --text-2xs | 11px |+| --text-xsm | 12px |+| --text-sm | 13px |+| --text-base | 14px (default) |+| --text-lg | 16px |+| --text-xl | 18px |+| --text-2xl | 20px |+| --text-3xl | 24px |+| --text-4xl | 32px |++### Font Weights++- `--font-weight-normal`: 400+- `--font-weight-medium`: 500+- `--font-weight-semibold`: 600+- `--font-weight-bold`: 700++## Usage in StyleX++```tsx+import * as stylex from '@stylexjs/stylex';+import {colorVars, spacingVars, radiusVars} from '@xds/core';++const styles = stylex.create({+ card: {+ padding: spacingVars['--spacing-4'],+ backgroundColor: colorVars['--color-surface'],+ borderRadius: radiusVars['--radius-container'],+ },+});+```++Or use CSS custom properties directly:++```tsx+const styles = stylex.create({+ card: {+ padding: 'var(--spacing-4)',+ backgroundColor: 'var(--color-surface)',+ borderRadius: 'var(--radius-container)',+ },+});+```diff --git a/packages/agent-tools/package.json b/packages/agent-tools/package.jsonnew file mode 100644index 0000000000..34b7269b72--- /dev/null+++ b/packages/agent-tools/package.json@@ -0,0 +1,27 @@+{+ "name": "@xds/agent-tools",+ "version": "0.0.1",+ "description": "XDS documentation tools for AI coding agents",+ "type": "module",+ "bin": {+ "xds-agents-md": "./bin/agents-md.mjs",+ "xds-skill": "./bin/ai-skill.mjs"+ },+ "files": [+ "bin",+ "docs"+ ],+ "scripts": {+ "agents-md": "node bin/agents-md.mjs",+ "skill": "node bin/ai-skill.mjs"+ },+ "keywords": [+ "xds",+ "ai",+ "agents",+ "documentation",+ "claude",+ "cursor"+ ],+ "license": "MIT"+}diff --git a/packages/core/README.md b/packages/core/README.mdindex 07a20e0cb4..6a537ec1b0 100644--- a/packages/core/README.md+++ b/packages/core/README.md@@ -7,6 +7,7 @@ Core UI components library for the XDS design system (`@xds/core`).| Directory/File | Role | Purpose || ---------------- | ------ | -------------------------------------- || `src/` | Source | Component source code |+| `docs/` | Docs | Documentation including AI skill doc || `package.json` | Config | Package configuration and dependencies || `tsconfig.json` | Config | TypeScript compiler configuration || `tsup.config.ts` | Build | Bundle configuration using tsup |diff --git a/packages/core/package.json b/packages/core/package.jsonindex 724ebde4e0..e9af26d11e 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -73,7 +73,8 @@"types": "./dist/hooks/index.d.ts","import": "./dist/hooks/index.mjs","require": "./dist/hooks/index.js"- }+ },+ "./xds.md": "./xds.md"},"scripts": {"build": "tsup",diff --git a/packages/core/src/theme/README.md b/packages/core/src/theme/README.mdnew file mode 100644index 0000000000..0e0e922236--- /dev/null+++ b/packages/core/src/theme/README.md@@ -0,0 +1,64 @@+# /packages/core/src/theme++XDS theme provider and design tokens.++<!-- SYNC: When files in this directory change, update this document. -->++## Features++- **Theme Provider**: Wraps app to provide CSS variables+- **Design Tokens**: Colors, spacing, radius, typography via StyleX+- **Multiple Themes**: defaultTheme, neutralTheme+- **useTheme Hook**: Access current theme in components++## Usage++```tsx+import {Theme, defaultTheme} from '@xds/core';++function App() {+ return (+ <Theme theme={defaultTheme}>+ <YourApp />+ </Theme>+ );+}+```++## Props++| Prop | Type | Default | Description |+| ---------- | ----------- | ------- | ------------------------------------------- |+| `theme` | `XDSTheme` | β | Theme object (defaultTheme or neutralTheme) |+| `children` | `ReactNode` | β | App content |++## Available Themes++- `defaultTheme` - XDS branded colors+- `neutralTheme` - Grayscale palette++## useTheme Hook++Access current theme in components:++```tsx+import {useTheme} from '@xds/core';++const {theme} = useTheme();+```++## CSS Variables++Theme provides CSS variables for use in StyleX:++```tsx+const styles = stylex.create({+ card: {+ backgroundColor: 'var(--color-surface)',+ padding: 'var(--spacing-4)',+ borderRadius: 'var(--radius-container)',+ },+});+```++See `.xds-docs/tokens.md` for the full token reference.diff --git a/packages/core/src/theme/tokens.stylex.ts b/packages/core/src/theme/tokens.stylex.tsindex e8015dfd5c..460315035a 100644--- a/packages/core/src/theme/tokens.stylex.ts+++ b/packages/core/src/theme/tokens.stylex.ts@@ -4,6 +4,8 @@* Defines all design tokens using StyleX defineVars.* - *Raw: Plain objects with default values (can be reused by themes)* - *Vars: CSS custom properties that themes can override via createTheme+ *+ * SYNC: When modified, update /packages/agent-tools/docs/tokens.md*/import * as stylex from '@stylexjs/stylex';diff --git a/packages/core/xds.md b/packages/core/xds.mdnew file mode 100644index 0000000000..9ef76049a7--- /dev/null+++ b/packages/core/xds.md@@ -0,0 +1,87 @@+# XDS Component Library++> A React design system for building internal tools. Provides form inputs, buttons, layout primitives, and floating UI. All components use the `XDS` prefix (e.g., XDSButton, XDSCard). Use StyleX for custom styling, not inline styles.++XDS is a component library for building internal applications with consistent UI patterns. The library emphasizes composition over configuration, controlled form components, and semantic spacing via CSS variables.++## Key Principles++1. Use XDS components for everything they cover+2. Use StyleX (not inline styles) for layout and styling gaps+3. All components use the `XDS` prefix+4. Form inputs are controlled (value + onChange)+5. Use semantic spacing tokens (space0-space7), not pixel values+6. Use CSS variables for colors (not hardcoded hex values) to support theming++## Component Documentation++Each component has a README.md in its source directory with usage examples, props, and implementation notes.++**Pattern**: For any import like `import { XDSButton } from '@xds/core/Button'`, find docs at `src/Button/README.md`.++| Import Path | README Location | Components |+| ------------------------- | ---------------------------------------------------------------- | ----------------------------------------------------------------------------- |+| `@xds/core/Button` | [src/Button/README.md](src/Button/README.md) | XDSButton |+| `@xds/core/TextInput` | [src/TextInput/README.md](src/TextInput/README.md) | XDSTextInput |+| `@xds/core/TextArea` | [src/TextArea/README.md](src/TextArea/README.md) | XDSTextArea |+| `@xds/core/CheckboxInput` | [src/CheckboxInput/README.md](src/CheckboxInput/README.md) | XDSCheckboxInput |+| `@xds/core/Field` | [src/Field/README.md](src/Field/README.md) | XDSField |+| `@xds/core/Avatar` | [src/Avatar/README.md](src/Avatar/README.md) | XDSAvatar |+| `@xds/core/Skeleton` | [src/Skeleton/README.md](src/Skeleton/README.md) | XDSSkeleton |+| `@xds/core/Text` | [src/Text/README.md](src/Text/README.md) | XDSText |+| `@xds/core/Icon` | [src/Icon/README.md](src/Icon/README.md) | XDSIcon |+| `@xds/core/Layout` | [src/Layout/README.md](src/Layout/README.md) | XDSHStack, XDSVStack, XDSStackItem, XDSCard, XDSSection |+| `@xds/core/Layout` | [src/Layout/XDSLayout/README.md](src/Layout/XDSLayout/README.md) | XDSLayout, XDSLayoutHeader, XDSLayoutContent, XDSLayoutFooter, XDSLayoutPanel |+| `@xds/core/Layer` | [src/Layer/README.md](src/Layer/README.md) | XDSTooltip, XDSHoverCard, XDSMenu |++## Theme++Theme tokens and utilities are documented in [src/theme/README.md](src/theme/README.md) (if available).++```tsx+import {Theme, useTheme, defaultTheme} from '@xds/core';++// Wrap app in theme provider+<Theme theme={defaultTheme}>+ <App />+</Theme>;+```++## Anti-Patterns to Avoid++β **Inline styles** - Use StyleX instead++```tsx+// Bad+<div style={{ padding: '16px' }}>++// Good+<div {...stylex.props(styles.container)}>+```++β **Hardcoded colors** - Use CSS variables for theming++```tsx+// Bad+<div style={{ color: '#ff0000' }}>++// Good - use theme tokens via StyleX+const styles = stylex.create({+ error: { color: 'var(--xds-color-negative)' }+});+```++β **Hardcoded spacing** - Use semantic tokens++```tsx+// Bad+<XDSVStack style={{ gap: '8px' }}>++// Good+<XDSVStack gap="space2">+```++## Optional Resources++- [Storybook Examples](../../apps/storybook/): Interactive component demos+- [Source Code](./src/): Component implementationsdiff --git a/yarn.lock b/yarn.lockindex c78d62274d..aa707303bd 100644--- a/yarn.lock+++ b/yarn.lock@@ -20,6 +20,11 @@"@jridgewell/gen-mapping" "^0.3.5""@jridgewell/trace-mapping" "^0.3.24"+"@anthropic-ai/sdk@^0.52.0":+ version "0.52.0"+ resolved "https://registry.yarnpkg.com/@anthropic-ai/sdk/-/sdk-0.52.0.tgz#fa521708f926963da78d7bea50dd29bf786f465b"+ integrity sha512-d4c+fg+xy9e46c8+YnrrgIQR45CZlAi7PwdzIfDXDM6ACxEZli1/fxhURsq30ZpMZy6LvSkr41jGq5aF5TD7rQ==+"@asamuzakjp/css-color@^4.1.1":version "4.1.1"resolved "https://registry.yarnpkg.com/@asamuzakjp/css-color/-/css-color-4.1.1.tgz#e5c662f488367dc74194609179fe6621f2586114"@@ -2488,6 +2493,11 @@ color-name@~1.1.4:resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2"integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==+commander@^12.1.0:+ version "12.1.0"+ resolved "https://registry.yarnpkg.com/commander/-/commander-12.1.0.tgz#01423b36f501259fdaac4d0e4d60c96c991585d3"+ integrity sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==+commander@^4.0.0:version "4.1.1"resolved "https://registry.yarnpkg.com/commander/-/commander-4.1.1.tgz#9fd602bd936294e9e9ef46a3f4d6964044b18068"@@ -2806,7 +2816,7 @@ esbuild@^0.24.0:"@esbuild/win32-ia32" "0.24.2""@esbuild/win32-x64" "0.24.2"-esbuild@^0.27.0:+esbuild@^0.27.0, esbuild@~0.27.0:version "0.27.2"resolved "https://registry.yarnpkg.com/esbuild/-/esbuild-0.27.2.tgz#d83ed2154d5813a5367376bb2292a9296fc83717"integrity sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==@@ -3138,6 +3148,13 @@ get-proto@^1.0.1:dunder-proto "^1.0.1"es-object-atoms "^1.0.0"+get-tsconfig@^4.7.5:+ version "4.13.0"+ resolved "https://registry.yarnpkg.com/get-tsconfig/-/get-tsconfig-4.13.0.tgz#fcdd991e6d22ab9a600f00e91c318707a5d9a0d7"+ integrity sha512-1VKTZJCwBrvbd+Wn3AOgQP/2Av+TfTCOlE4AcRJE72W1ksZXbAx8PPBR9RzgTeSPzlPMHrbANMH3LbltH73wxQ==+ dependencies:+ resolve-pkg-maps "^1.0.0"+glob-parent@^5.1.2:version "5.1.2"resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.2.tgz#869832c58034fe68a4093c17dc15e8340d8401c4"@@ -4233,6 +4250,11 @@ resolve-from@^5.0.0:resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-5.0.0.tgz#c35225843df8f776df21c57557bc087e9dfdfc69"integrity sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==+resolve-pkg-maps@^1.0.0:+ version "1.0.0"+ resolved "https://registry.yarnpkg.com/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz#616b3dc2c57056b5588c31cdf4b3d64db133720f"+ integrity sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==+resolve@^1.22.1, resolve@^1.22.8:version "1.22.11"resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.22.11.tgz#aad857ce1ffb8bfa9b0b1ac29f1156383f68c262"@@ -4676,6 +4698,16 @@ tsup@^8.3.0:tinyglobby "^0.2.11"tree-kill "^1.2.2"+tsx@^4.19.0:+ version "4.21.0"+ resolved "https://registry.yarnpkg.com/tsx/-/tsx-4.21.0.tgz#32aa6cf17481e336f756195e6fe04dae3e6308b1"+ integrity sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==+ dependencies:+ esbuild "~0.27.0"+ get-tsconfig "^4.7.5"+ optionalDependencies:+ fsevents "~2.3.3"+type-check@^0.4.0, type-check@~0.4.0:version "0.4.0"resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.4.0.tgz#07b8203bfa7056c0657050e3ccd2c37730bab8f1"